-
Notifications
You must be signed in to change notification settings - Fork 0
/
kautodiff.c
2396 lines (2209 loc) · 70.8 KB
/
kautodiff.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include "kautodiff.h"
typedef struct {
uint64_t s[2];
double n_gset;
int n_iset;
volatile int lock;
} kad_rng_t;
/**********************
* Graph construction *
**********************/
static inline kad_node_t *kad_new_core(int n_d, int op, int n_child)
{
kad_node_t *s;
if (n_d >= KAD_MAX_DIM) return 0;
s = (kad_node_t*)calloc(1, sizeof(kad_node_t));
s->n_d = n_d, s->op = op, s->n_child = n_child;
if (s->n_child) s->child = (kad_node_t**)calloc(s->n_child, sizeof(kad_node_t*));
return s;
}
static inline kad_node_t *kad_vleaf(uint8_t flag, float *x, float *g, int n_d, va_list ap)
{
int i;
kad_node_t *p;
if (n_d > KAD_MAX_DIM) return 0;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
p->n_d = n_d;
for (i = 0; i < n_d; ++i)
p->d[i] = va_arg(ap, int32_t);
p->x = x, p->g = g, p->flag = flag;
return p;
}
kad_node_t *kad_const(float *x, int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(KAD_CONST, x, 0, n_d, ap); va_end(ap);
return p;
}
kad_node_t *kad_feed(int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(0, 0, 0, n_d, ap); va_end(ap);
return p;
}
kad_node_t *kad_var(float *x, float *g, int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(KAD_VAR, x, g, n_d, ap); va_end(ap);
return p;
}
static inline kad_node_t *kad_finalize_node(kad_node_t *s) /* a helper function */
{
int i;
if (kad_op_list[s->op](s, KAD_SYNC_DIM) < 0) { /* check dimension */
if (s->ptr) free(s->ptr);
free(s->child); free(s);
return 0;
}
for (i = 0; i < s->n_child; ++i)
if (kad_is_back(s->child[i]))
break;
if (i < s->n_child) s->flag |= KAD_VAR;
return s;
}
/********** Simple arithmetic **********/
static inline kad_node_t *kad_op2_core(int op, kad_node_t *x, kad_node_t *y)
{
kad_node_t *s;
s = kad_new_core(0, op, 2);
s->child[0] = x, s->child[1] = y;
return kad_finalize_node(s);
}
static inline kad_node_t *kad_op1_core(int op, kad_node_t *x)
{
kad_node_t *s;
s = kad_new_core(0, op, 1);
s->child[0] = x;
return kad_finalize_node(s);
}
#define KAD_FUNC_OP2(fname, op) kad_node_t *fname(kad_node_t *x, kad_node_t *y) { return kad_op2_core((op), x, y); }
KAD_FUNC_OP2(kad_add, 1)
KAD_FUNC_OP2(kad_sub, 23)
KAD_FUNC_OP2(kad_mul, 2)
KAD_FUNC_OP2(kad_cmul, 3)
KAD_FUNC_OP2(kad_matmul, 9)
KAD_FUNC_OP2(kad_ce_multi, 13)
KAD_FUNC_OP2(kad_ce_bin, 22)
KAD_FUNC_OP2(kad_ce_bin_neg, 4)
KAD_FUNC_OP2(kad_mse, 29)
#define KAD_FUNC_OP1(fname, op) kad_node_t *fname(kad_node_t *x) { return kad_op1_core((op), x); }
KAD_FUNC_OP1(kad_log, 27)
KAD_FUNC_OP1(kad_exp, 33)
KAD_FUNC_OP1(kad_sin, 34)
KAD_FUNC_OP1(kad_square, 5)
KAD_FUNC_OP1(kad_sigm, 6)
KAD_FUNC_OP1(kad_tanh, 7)
KAD_FUNC_OP1(kad_relu, 8)
KAD_FUNC_OP1(kad_1minus, 11)
KAD_FUNC_OP1(kad_softmax, 14)
KAD_FUNC_OP1(kad_stdnorm, 32)
kad_node_t *kad_ce_multi_weighted(kad_node_t *pred, kad_node_t *truth, kad_node_t *weight)
{
kad_node_t *s;
s = kad_new_core(0, 13, 3);
s->child[0] = pred, s->child[1] = truth, s->child[2] = weight;
return kad_finalize_node(s);
}
/********** Convolution **********/
/* compute output dimension and padding sizes on both sides */
static inline int conv_find_par(int in_size, int kernel_size, int stride, int pad0, int *new_pad0, int *new_pad1)
{
int out_size, pad_both;
/* key equation: out_size = (in_size - kernel_size + pad_both) / stride + 1 */
if (pad0 == KAD_PAD_SAME && stride == 1) out_size = in_size;
else out_size = (in_size - kernel_size + (pad0 > 0? pad0 : 0) + stride - 1) / stride + 1;
pad_both = (out_size - 1) * stride + kernel_size - in_size;
*new_pad0 = pad_both / 2;
*new_pad1 = pad_both - *new_pad0;
return out_size;
}
typedef struct {
int kernel_size, stride, pad[2];
} conv_conf_t;
static inline conv_conf_t *conv2d_gen_aux(int in_row, int in_col, int kernel_r, int kernel_c, int stride_r, int stride_c, int top_pad, int left_pad)
{
conv_conf_t *cnn;
cnn = (conv_conf_t*)calloc(2, sizeof(conv_conf_t));
cnn[0].kernel_size = kernel_r, cnn[0].stride = stride_r;
cnn[1].kernel_size = kernel_c, cnn[1].stride = stride_c;
conv_find_par(in_row, kernel_r, stride_r, top_pad, &cnn[0].pad[0], &cnn[0].pad[1]);
conv_find_par(in_col, kernel_c, stride_c, left_pad, &cnn[1].pad[0], &cnn[1].pad[1]);
return cnn;
}
kad_node_t *kad_conv2d(kad_node_t *x, kad_node_t *w, int stride_r, int stride_c, int top_pad, int left_pad)
{
kad_node_t *s;
if (x->n_d != 4 || w->n_d != 4) return 0;
s = kad_new_core(0, 16, 2);
s->child[0] = x, s->child[1] = w;
s->ptr = conv2d_gen_aux(x->d[2], x->d[3], w->d[2], w->d[3], stride_r, stride_c, top_pad, left_pad);
s->ptr_size = sizeof(conv_conf_t) * 2;
return kad_finalize_node(s);
}
kad_node_t *kad_max2d(kad_node_t *x, int kernel_r, int kernel_c, int stride_r, int stride_c, int top_pad, int left_pad)
{
kad_node_t *s;
if (x->n_d != 4) return 0;
s = kad_new_core(0, 17, 1);
s->child[0] = x;
s->ptr = conv2d_gen_aux(x->d[2], x->d[3], kernel_r, kernel_c, stride_r, stride_c, top_pad, left_pad);
s->ptr_size = sizeof(conv_conf_t) * 2;
return kad_finalize_node(s);
}
static inline conv_conf_t *conv1d_gen_aux(int in_col, int kernel_c, int stride_c, int left_pad)
{
conv_conf_t *cnn;
cnn = (conv_conf_t*)calloc(1, sizeof(conv_conf_t));
cnn->kernel_size = kernel_c, cnn->stride = stride_c;
conv_find_par(in_col, kernel_c, stride_c, left_pad, &cnn->pad[0], &cnn->pad[1]);
return cnn;
}
kad_node_t *kad_conv1d(kad_node_t *x, kad_node_t *w, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3 || w->n_d != 3) return 0;
s = kad_new_core(0, 18, 2);
s->child[0] = x, s->child[1] = w;
s->ptr = conv1d_gen_aux(x->d[2], w->d[2], stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
kad_node_t *kad_max1d(kad_node_t *x, int kernel_size, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3) return 0;
s = kad_new_core(0, 19, 1);
s->child[0] = x;
s->ptr = conv1d_gen_aux(x->d[2], kernel_size, stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
kad_node_t *kad_avg1d(kad_node_t *x, int kernel_size, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3) return 0;
s = kad_new_core(0, 28, 1);
s->child[0] = x;
s->ptr = conv1d_gen_aux(x->d[2], kernel_size, stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
/********** Multi-node pooling **********/
static kad_node_t *kad_pooling_general(int op, int n, kad_node_t **x)
{
int i;
kad_node_t *s;
s = kad_new_core(0, op, n);
s->flag |= KAD_POOL;
for (i = 0; i < n; ++i)
s->child[i] = x[i];
return kad_finalize_node(s);
}
kad_node_t *kad_avg(int n, kad_node_t **x) { return kad_pooling_general(10, n, x); }
kad_node_t *kad_max(int n, kad_node_t **x) { return kad_pooling_general(21, n, x); }
kad_node_t *kad_stack(int n, kad_node_t **x) { return kad_pooling_general(35, n, x); }
kad_node_t *kad_select(int n, kad_node_t **x, int which)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)calloc(1, 4);
*aux = which;
s = kad_new_core(0, 12, n);
for (i = 0; i < n; ++i) s->child[i] = x[i];
s->flag |= KAD_POOL, s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
/********** Dimension reduction **********/
static kad_node_t *kad_reduce_general(int op, kad_node_t *x, int axis)
{
kad_node_t *s;
int32_t *aux;
aux = (int32_t*)malloc(4);
aux[0] = axis;
s = kad_new_core(0, op, 1);
s->child[0] = x;
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_reduce_sum(kad_node_t *x, int axis) { return kad_reduce_general(25, x, axis); }
kad_node_t *kad_reduce_mean(kad_node_t *x, int axis) { return kad_reduce_general(26, x, axis); }
/********** Sampling related **********/
kad_node_t *kad_dropout(kad_node_t *x, kad_node_t *y)
{
kad_node_t *z;
z = kad_op2_core(15, x, y);
z->ptr = kad_rng(), z->ptr_size = sizeof(kad_rng_t);
return z;
}
kad_node_t *kad_sample_normal(kad_node_t *x)
{
kad_node_t *z;
z = kad_op1_core(24, x);
z->ptr = kad_rng(), z->ptr_size = sizeof(kad_rng_t);
return z;
}
/********** Miscellaneous **********/
kad_node_t *kad_slice(kad_node_t *x, int axis, int start, int end)
{
kad_node_t *s;
int32_t *aux;
if (end < start || start < 0) return 0;
aux = (int32_t*)malloc(3 * 4);
aux[0] = axis, aux[1] = start, aux[2] = end;
s = kad_new_core(0, 20, 1);
s->child[0] = x;
s->ptr = aux, s->ptr_size = 3 * 4;
return kad_finalize_node(s);
}
kad_node_t *kad_concat_array(int axis, int n, kad_node_t **p)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)malloc(4);
aux[0] = axis;
s = kad_new_core(0, 31, n);
for (i = 0; i < n; ++i)
s->child[i] = p[i];
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_concat(int axis, int n, ...)
{
int i;
kad_node_t **p, *s;
va_list ap;
p = (kad_node_t**)malloc(n * sizeof(kad_node_t*));
va_start(ap, n);
for (i = 0; i < n; ++i) p[i] = va_arg(ap, kad_node_p);
va_end(ap);
s = kad_concat_array(axis, n, p);
free(p);
return s;
}
kad_node_t *kad_reshape(kad_node_t *x, int n_d, int *d)
{
kad_node_t *s;
int32_t i, *aux = 0;
if (n_d > 0) {
aux = (int32_t*)malloc(n_d * 4);
for (i = 0; i < n_d; ++i) aux[i] = d? d[i] : -1;
}
s = kad_new_core(0, 30, 1);
s->child[0] = x, s->ptr = aux, s->ptr_size = n_d * 4;
return kad_finalize_node(s);
}
kad_node_t *kad_reverse(kad_node_t *x, int axis)
{
kad_node_t *s;
int32_t *aux;
aux = (int32_t*)malloc(4);
*aux = axis;
s = kad_new_core(0, 36, 1);
s->child[0] = x, s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_switch(int n, kad_node_t **p)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)calloc(1, 4);
s = kad_new_core(0, 12, n);
for (i = 0; i < n; ++i)
s->child[i] = p[i];
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
/***********************
* Graph linearization *
***********************/
static void kad_mark_back(int n, kad_node_t **v)
{
int i, j;
for (i = 0; i < n; ++i) {
if (v[i]->n_child == 0) continue;
for (j = 0; j < v[i]->n_child; ++j)
if (kad_is_back(v[i]->child[j]))
break;
if (j < v[i]->n_child) v[i]->flag |= KAD_VAR;
else v[i]->flag &= ~KAD_VAR;
}
}
static void kad_allocate_internal(int n, kad_node_t **v)
{
int i;
kad_mark_back(n, v);
for (i = 0; i < n; ++i) {
kad_node_t *p = v[i];
if (p->n_child == 0) continue;
p->x = (float*)realloc(p->x, kad_len(p) * sizeof(float));
if (kad_is_back(p)) {
p->g = (float*)realloc(p->g, kad_len(p) * sizeof(float));
kad_op_list[p->op](p, KAD_ALLOC);
}
}
}
int kad_sync_dim(int n, kad_node_t **v, int batch_size)
{
int i, req_alloc = 0, req_sync = 0, old_size = 0;
for (i = 0; i < n; ++i) {
if (kad_is_feed(v[i])) {
old_size = v[i]->d[0]; /* TODO: check if all feeds have the same batch size */
if (batch_size > 0 && v[i]->d[0] != batch_size)
v[i]->d[0] = batch_size, req_sync = 1;
} else if (v[i]->n_child > 0 && req_sync)
kad_op_list[v[i]->op](v[i], KAD_SYNC_DIM);
}
if (old_size < batch_size) req_alloc = 1;
for (i = 0; i < n; ++i)
if (v[i]->n_child > 0 && v[i]->x == 0) req_alloc = 1;
if (req_alloc) kad_allocate_internal(n, v);
return batch_size > 0? batch_size : old_size;
}
#define kvec_t(type) struct { size_t n, m; type *a; }
#define kv_pop(v) ((v).a[--(v).n])
#define kv_push(type, v, x) do { \
if ((v).n == (v).m) { \
(v).m = (v).m? (v).m<<1 : 2; \
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m); \
} \
(v).a[(v).n++] = (x); \
} while (0)
/* IMPORTANT: kad_node_t::tmp MUST BE set to zero before calling this function */
kad_node_t **kad_compile_array(int *n_node, int n_roots, kad_node_t **roots)
{
int i;
kvec_t(kad_node_p) stack = {0,0,0}, a = {0,0,0};
/* generate kad_node_t::tmp, the count of the parent nodes; shifted by 1; lowest bit to detect fake roots */
for (i = 0; i < n_roots; ++i) {
roots[i]->tmp = 1; /* mark the root */
kv_push(kad_node_p, stack, roots[i]);
}
while (stack.n) {
kad_node_t *p = kv_pop(stack);
for (i = 0; i < p->n_child; ++i) {
kad_node_t *q = p->child[i];
if (q->tmp == 0) kv_push(kad_node_p, stack, q);
q->tmp += 1<<1;
}
}
/* topological sorting (Kahn's algorithm) */
for (i = 0; i < n_roots; ++i)
if (roots[i]->tmp>>1 == 0) /* if roots[i]->tmp>>1 != 0, it is not a real root */
kv_push(kad_node_p, stack, roots[i]);
while (stack.n) {
kad_node_t *p = kv_pop(stack);
kv_push(kad_node_p, a, p);
for (i = 0; i < p->n_child; ++i) {
p->child[i]->tmp -= 1<<1;
if (p->child[i]->tmp>>1 == 0)
kv_push(kad_node_p, stack, p->child[i]);
}
}
free(stack.a);
for (i = 0; i < (int)a.n; ++i) { /* check cycles; no cycles if constructed with kad_add() etc */
assert(a.a[i]->tmp>>1 == 0);
a.a[i]->tmp = 0;
}
/* reverse */
for (i = 0; i < (int)a.n>>1; ++i) { /* reverse a.a[] */
kad_node_p t;
t = a.a[i], a.a[i] = a.a[a.n-1-i], a.a[a.n-1-i] = t;
}
kad_allocate_internal(a.n, a.a);
*n_node = a.n;
return a.a;
}
kad_node_t **kad_compile(int *n_node, int n_roots, ...)
{
int i;
kad_node_t **roots, **ret;
va_list ap;
roots = (kad_node_t**)malloc(n_roots * sizeof(kad_node_t*));
va_start(ap, n_roots);
for (i = 0; i < n_roots; ++i) roots[i] = va_arg(ap, kad_node_p);
va_end(ap);
ret = kad_compile_array(n_node, n_roots, roots);
free(roots);
return ret;
}
/************************************
* Miscellaneous on compiled graphs *
************************************/
void kad_delete(int n, kad_node_t **a)
{
int i;
for (i = 0; i < n; ++i) {
kad_node_t *p = a[i];
if (p->n_child) {
free(p->x); free(p->g);
}
free(p->child); free(p->ptr); free(p->gtmp); free(p);
}
free(a);
}
int kad_size_var(int n, kad_node_t *const* v)
{
int c, i;
for (i = c = 0; i < n; ++i)
if (kad_is_var(v[i]))
c += kad_len(v[i]);
return c;
}
int kad_size_const(int n, kad_node_t *const* v)
{
int c, i;
for (i = c = 0; i < n; ++i)
if (kad_is_const(v[i]))
c += kad_len(v[i]);
return c;
}
/**********************************
* Computate values and gradients *
**********************************/
static void kad_propagate_marks(int n, kad_node_t **a)
{
int i, j;
for (i = n - 1; i >= 0; --i) {
kad_node_t *p = a[i];
if (p->tmp > 0) {
if (kad_is_switch(p)) {
int32_t *aux = (int32_t*)p->ptr;
if (p->child[*aux]->tmp == 0)
p->child[*aux]->tmp = 1;
} else {
for (j = 0; j < p->n_child; ++j)
if (p->child[j]->tmp == 0)
p->child[j]->tmp = 1;
}
}
}
}
void kad_eval_marked(int n, kad_node_t **a)
{
int i;
kad_propagate_marks(n, a);
for (i = 0; i < n; ++i)
if (a[i]->n_child && a[i]->tmp > 0)
kad_op_list[a[i]->op](a[i], KAD_FORWARD);
for (i = 0; i < n; ++i) a[i]->tmp = 0;
}
const float *kad_eval_at(int n, kad_node_t **a, int from)
{
int i;
if (from < 0 || from >= n) from = n - 1;
for (i = 0; i < n; ++i) a[i]->tmp = (i == from);
kad_eval_marked(n, a);
return a[from]->x;
}
void kad_grad(int n, kad_node_t **a, int from)
{
int i;
if (from < 0 || from >= n) from = n - 1;
assert(a[from]->n_d == 0);
for (i = 0; i < n; ++i) a[i]->tmp = (i == from);
kad_propagate_marks(n, a);
for (i = 0; i <= from; ++i) /* set all grandients to zero */
if (a[i]->g && a[i]->tmp > 0)
memset(a[i]->g, 0, kad_len(a[i]) * sizeof(float));
for (i = from, a[i]->g[0] = 1.0f; i >= 0; --i) /* backprop */
if (a[i]->n_child && a[i]->tmp > 0)
kad_op_list[a[i]->op](a[i], KAD_BACKWARD);
for (i = 0; i <= from; ++i) a[i]->tmp = 0;
}
/***********************
* Load and save graph *
***********************/
static void kad_save1(FILE *fp, const kad_node_t *p)
{
fwrite(&p->ext_label, 4, 1, fp);
fwrite(&p->ext_flag, 4, 1, fp);
fwrite(&p->flag, 1, 1, fp);
fwrite(&p->n_child, 4, 1, fp);
if (p->n_child) {
int32_t j, pre = p->pre? p->pre->tmp : -1;
fwrite(&p->op, 2, 1, fp);
for (j = 0; j < p->n_child; ++j)
fwrite(&p->child[j]->tmp, 4, 1, fp);
fwrite(&pre, 4, 1, fp);
fwrite(&p->ptr_size, 4, 1, fp);
if (p->ptr_size > 0 && p->ptr)
fwrite(p->ptr, p->ptr_size, 1, fp);
} else {
fwrite(&p->n_d, 1, 1, fp);
if (p->n_d) fwrite(p->d, 4, p->n_d, fp);
}
}
static kad_node_t *kad_load1(FILE *fp, kad_node_t **node)
{
kad_node_t *p;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
fread(&p->ext_label, 4, 1, fp);
fread(&p->ext_flag, 4, 1, fp);
fread(&p->flag, 1, 1, fp);
fread(&p->n_child, 4, 1, fp);
if (p->n_child) {
int32_t j, k;
p->child = (kad_node_t**)calloc(p->n_child, sizeof(kad_node_t*));
fread(&p->op, 2, 1, fp);
for (j = 0; j < p->n_child; ++j) {
fread(&k, 4, 1, fp);
p->child[j] = node? node[k] : 0;
}
fread(&k, 4, 1, fp);
if (k >= 0) p->pre = node[k];
fread(&p->ptr_size, 4, 1, fp);
if (p->ptr_size > 0) {
p->ptr = malloc(p->ptr_size);
fread(p->ptr, p->ptr_size, 1, fp);
}
} else {
fread(&p->n_d, 1, 1, fp);
if (p->n_d) fread(p->d, 4, p->n_d, fp);
}
return p;
}
int kad_save(FILE *fp, int n_node, kad_node_t **node)
{
int32_t i, k = n_node;
fwrite(&k, 4, 1, fp);
for (i = 0; i < n_node; ++i) node[i]->tmp = i;
for (i = 0; i < n_node; ++i) kad_save1(fp, node[i]);
for (i = 0; i < n_node; ++i) node[i]->tmp = 0;
return 0;
}
kad_node_t **kad_load(FILE *fp, int *_n_node)
{
int32_t i, n_node;
kad_node_t **node;
fread(&n_node, 4, 1, fp);
node = (kad_node_t**)malloc(n_node * sizeof(kad_node_t*));
for (i = 0; i < n_node; ++i) {
kad_node_t *p;
p = node[i] = kad_load1(fp, node);
if (p->n_child) {
kad_op_list[p->op](p, KAD_ALLOC);
kad_op_list[p->op](p, KAD_SYNC_DIM);
}
}
*_n_node = n_node;
kad_mark_back(n_node, node);
return node;
}
/***************
* Graph clone *
***************/
static inline kad_node_t *kad_dup1(const kad_node_t *p)
{
kad_node_t *q;
q = (kad_node_t*)malloc(sizeof(kad_node_t));
memcpy(q, p, sizeof(kad_node_t));
q->pre = 0, q->tmp = 0, q->gtmp = 0;
if (p->ptr && p->ptr_size > 0) {
if (kad_use_rng(p) && !(p->flag & KAD_SHARE_RNG) && p->ptr_size == sizeof(kad_rng_t)) {
q->ptr = kad_rng(); /* each time step uses a different RNG */
} else {
q->ptr = malloc(p->ptr_size);
memcpy(q->ptr, p->ptr, p->ptr_size);
}
}
if (q->n_child) {
q->x = q->g = 0;
q->child = (kad_node_t**)calloc(q->n_child, sizeof(kad_node_t*));
}
return q;
}
kad_node_t **kad_clone(int n, kad_node_t **v, int batch_size)
{
int i, j;
kad_node_t **u;
u = (kad_node_t**)calloc(n, sizeof(kad_node_t*));
for (i = 0; i < n; ++i) v[i]->tmp = i;
for (i = 0; i < n; ++i) {
kad_node_t *p = v[i], *q;
q = u[i] = kad_dup1(p);
if (p->pre) q->pre = u[p->pre->tmp];
if (p->n_child) {
for (j = 0; j < p->n_child; ++j)
q->child[j] = u[p->child[j]->tmp];
} else if (!kad_is_feed(p)) {
q->x = (float*)malloc(kad_len(p) * sizeof(float));
memcpy(q->x, p->x, kad_len(p) * sizeof(float));
q->g = 0;
}
}
for (i = 0; i < n; ++i) v[i]->tmp = 0;
kad_sync_dim(n, u, batch_size); /* this will allocate x[] and g[] at internal nodes */
return u;
}
/**************
* Unroll RNN *
**************/
typedef struct {
int32_t n, m;
kad_node_t **v;
} nodes_t;
static inline void push_nodes(nodes_t *w, kad_node_t *p)
{
if (w->n == w->m) {
w->m = w->m? w->m<<1 : 16;
w->v = (kad_node_t**)realloc(w->v, w->m * sizeof(kad_node_t*));
}
w->v[w->n++] = p;
}
static void kad_unroll_helper(int n_v, kad_node_t **v, int i_pivot, kad_node_t **t, int len, nodes_t *w)
{
int i, j, l;
uint8_t *flag;
kad_node_t **aux;
assert(kad_is_pivot(v[i_pivot]) && t[i_pivot] == 0);
t[i_pivot] = kad_dup1(v[i_pivot]);
t[i_pivot]->n_child = len;
t[i_pivot]->child = (kad_node_t**)realloc(t[i_pivot]->child, len * sizeof(kad_node_t*));
flag = (uint8_t*)calloc(n_v, 1);
for (i = i_pivot, flag[i] = 16; i >= 0; --i) {
if (i < i_pivot && kad_is_pivot(v[i])) continue; /* don't trespass other pivots */
if (flag[i]&16) /* flag 16: nodes to unroll */
for (j = 0; j < v[i]->n_child; ++j)
flag[v[i]->child[j]->tmp] = 16;
}
for (i = 0; i < i_pivot; ++i) {
if (!(flag[i]&16)) continue;
if (kad_is_var(v[i]) || kad_is_const(v[i]) || kad_is_pivot(v[i])) flag[i] |= 1; /* external nodes that should not be duplicated */
if (v[i]->pre) flag[v[i]->pre->tmp] |= 2;
}
flag[v[i_pivot]->child[0]->tmp] |= 4;
aux = (kad_node_t**)calloc(n_v, sizeof(kad_node_t*));
for (l = 0; l < len; ++l) {
for (i = 0; i < i_pivot; ++i) {
if (!(flag[i]&16) || ((flag[i]&3) && t[i])) continue;
t[i] = kad_dup1(v[i]);
if (v[i]->n_child)
for (j = 0; j < v[i]->n_child; ++j)
t[i]->child[j] = t[v[i]->child[j]->tmp];
if (flag[i]&4) t[i_pivot]->child[l] = t[i];
if (l == 0 && (flag[i]&2)) aux[i] = t[i];
if (v[i]->pre) {
t[v[i]->pre->tmp] = t[i];
if (l == len - 1) t[i]->pre = aux[v[i]->pre->tmp]; /* this forms a cycle! */
}
push_nodes(w, t[i]);
}
}
push_nodes(w, t[i_pivot]);
free(aux); free(flag);
}
int kad_n_pivots(int n_v, kad_node_t **v)
{
int i, n_pivots = 0;
for (i = 0; i < n_v; ++i)
if (kad_is_pivot(v[i])) ++n_pivots;
return n_pivots;
}
kad_node_t **kad_unroll(int n_v, kad_node_t **v, int *new_n, int *len)
{
int i, j, n_pivots = 0;
kad_node_t **t;
nodes_t w = {0,0,0};
t = (kad_node_t**)calloc(n_v, sizeof(kad_node_t*));
n_pivots = kad_n_pivots(n_v, v);
for (i = 0; i < n_v; ++i) v[i]->tmp = i;
if (n_pivots) {
int k, *i_pivots;
i_pivots = (int*)calloc(n_pivots, sizeof(int));
for (i = k = 0; i < n_v; ++i) /* collect pivots */
if (kad_is_pivot(v[i])) i_pivots[k++] = i;
for (i = 0; i < n_pivots; ++i) /* unroll each pivot, from the lowest to the highest */
kad_unroll_helper(n_v, v, i_pivots[i], t, len[i], &w);
free(i_pivots);
}
for (i = 0; i < n_v; ++i) { /* copy over the rest of nodes */
if (t[i]) continue;
t[i] = kad_dup1(v[i]);
if (v[i]->n_child)
for (j = 0; j < v[i]->n_child; ++j)
t[i]->child[j] = t[v[i]->child[j]->tmp];
push_nodes(&w, t[i]);
}
free(t);
for (i = 0; i < n_v; ++i) v[i]->tmp = 0;
for (i = 0; i < w.n; ++i) /* stack may change the output dimension */
if (w.v[i]->n_child > 0)
kad_op_list[w.v[i]->op](w.v[i], KAD_SYNC_DIM);
kad_allocate_internal(w.n, w.v);
*new_n = w.n;
return w.v;
}
/********************************
* Vector and matrix operations *
********************************/
#ifdef __SSE__
#include <xmmintrin.h>
static inline float kad_sdot(int n, const float *x, const float *y) /* BLAS sdot using SSE */
{
int i, n8 = n>>3<<3;
__m128 vs1, vs2;
float s, t[4];
vs1 = _mm_setzero_ps();
vs2 = _mm_setzero_ps();
for (i = 0; i < n8; i += 8) {
__m128 vx1, vx2, vy1, vy2;
vx1 = _mm_loadu_ps(&x[i]);
vx2 = _mm_loadu_ps(&x[i+4]);
vy1 = _mm_loadu_ps(&y[i]);
vy2 = _mm_loadu_ps(&y[i+4]);
vs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1));
vs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2));
}
for (s = 0.; i < n; ++i) s += x[i] * y[i];
_mm_storeu_ps(t, vs1);
s += t[0] + t[1] + t[2] + t[3];
_mm_storeu_ps(t, vs2);
s += t[0] + t[1] + t[2] + t[3];
return s;
}
static inline void kad_saxpy_inlined(int n, float a, const float *x, float *y) /* BLAS saxpy using SSE */
{
int i, n8 = n>>3<<3;
__m128 va;
va = _mm_set1_ps(a);
for (i = 0; i < n8; i += 8) {
__m128 vx1, vx2, vy1, vy2, vt1, vt2;
vx1 = _mm_loadu_ps(&x[i]);
vx2 = _mm_loadu_ps(&x[i+4]);
vy1 = _mm_loadu_ps(&y[i]);
vy2 = _mm_loadu_ps(&y[i+4]);
vt1 = _mm_add_ps(_mm_mul_ps(va, vx1), vy1);
vt2 = _mm_add_ps(_mm_mul_ps(va, vx2), vy2);
_mm_storeu_ps(&y[i], vt1);
_mm_storeu_ps(&y[i+4], vt2);
}
for (; i < n; ++i) y[i] += a * x[i];
}
#else
static inline float kad_sdot(int n, const float *x, const float *y) /* BLAS sdot */
{
int i;
float s = 0.;
for (i = 0; i < n; ++i) s += x[i] * y[i];
return s;
}
static inline void kad_saxpy_inlined(int n, float a, const float *x, float *y) // BLAS saxpy
{
int i;
for (i = 0; i < n; ++i) y[i] += a * x[i];
}
#endif
void kad_vec_mul_sum(int n, float *a, const float *b, const float *c)
{
int i;
for (i = 0; i < n; ++i) a[i] += b[i] * c[i];
}
void kad_saxpy(int n, float a, const float *x, float *y) { kad_saxpy_inlined(n, a, x, y); }
#ifdef HAVE_CBLAS
#include <cblas.h>
void kad_sgemm_simple(int trans_A, int trans_B, int M, int N, int K, const float *A, const float *B, float *C)
{
cblas_sgemm(CblasRowMajor, trans_A? CblasTrans : CblasNoTrans, trans_B? CblasTrans : CblasNoTrans, M, N, K, 1.0f, A, trans_A? M : K, B, trans_B? K : N, 1.0f, C, N);
}
#else
void kad_sgemm_simple(int trans_A, int trans_B, int M, int N, int K, const float *A, const float *B, float *C) /* simplified BLAS sgemm */
{
static const int x = 16;
int i, j, k;
if (!trans_A && trans_B) {
for (i = 0; i < M; i += x)
for (j = 0; j < N; j += x) {
int ii, ie = M < i + x? M : i + x;
int jj, je = N < j + x? N : j + x;
for (ii = i; ii < ie; ++ii) { /* loop tiling */
const float *aii = A + ii * K, *bjj;
float *cii = C + ii * N;
for (jj = j, bjj = B + j * K; jj < je; ++jj, bjj += K)
cii[jj] += kad_sdot(K, aii, bjj);
}
}
} else if (!trans_A && !trans_B) {
for (i = 0; i < M; ++i)
for (k = 0; k < K; ++k)
kad_saxpy_inlined(N, A[i*K+k], &B[k*N], &C[i*N]);
} else if (trans_A && !trans_B) {
for (k = 0; k < K; ++k)
for (i = 0; i < M; ++i)
kad_saxpy_inlined(N, A[k*M+i], &B[k*N], &C[i*N]);
} else abort(); /* not implemented for (trans_A && trans_B) */
}
#endif
/***************************
* Random number generator *
***************************/
static kad_rng_t kad_rng_dat = { {0x50f5647d2380309dULL, 0x91ffa96fc4c62cceULL}, 0.0, 0, 0 };
static inline uint64_t kad_splitmix64(uint64_t x)
{
uint64_t z = (x += 0x9E3779B97F4A7C15ULL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}
static inline uint64_t kad_xoroshiro128plus_next(kad_rng_t *r)
{
const uint64_t s0 = r->s[0];
uint64_t s1 = r->s[1];
const uint64_t result = s0 + s1;
s1 ^= s0;
r->s[0] = (s0 << 55 | s0 >> 9) ^ s1 ^ (s1 << 14);
r->s[1] = s0 << 36 | s0 >> 28;
return result;
}
static inline void kad_xoroshiro128plus_jump(kad_rng_t *r)
{
static const uint64_t JUMP[] = { 0xbeac0467eba5facbULL, 0xd86b048b86aa9922ULL };
uint64_t s0 = 0, s1 = 0;
int i, b;
for (i = 0; i < 2; ++i)
for (b = 0; b < 64; b++) {
if (JUMP[i] & 1ULL << b)
s0 ^= r->s[0], s1 ^= r->s[1];
kad_xoroshiro128plus_next(r);
}
r->s[0] = s0, r->s[1] = s1;
}
void kad_srand(void *d, uint64_t seed)
{
kad_rng_t *r = d? (kad_rng_t*)d : &kad_rng_dat;
r->n_gset = 0.0, r->n_iset = 0;
r->s[0] = kad_splitmix64(seed);
r->s[1] = kad_splitmix64(r->s[0]);
}
void *kad_rng(void)
{
kad_rng_t *r;
r = (kad_rng_t*)calloc(1, sizeof(kad_rng_t));
kad_xoroshiro128plus_jump(&kad_rng_dat);
r->s[0] = kad_rng_dat.s[0], r->s[1] = kad_rng_dat.s[1];
return r;
}
uint64_t kad_rand(void *d) { return kad_xoroshiro128plus_next(d? (kad_rng_t*)d : &kad_rng_dat); }
double kad_drand(void *d)
{
union { uint64_t i; double d; } u;
u.i = 0x3FFULL << 52 | kad_xoroshiro128plus_next(d? (kad_rng_t*)d : &kad_rng_dat) >> 12;
return u.d - 1.0;
}
double kad_drand_normal(void *d)