-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcatseye.h
executable file
·2512 lines (2317 loc) · 73.9 KB
/
catseye.h
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
//---------------------------------------------------------
// Cat's eye
//
// ©2016-2023 Yuichiro Nakada
//---------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
static inline float time_diff(struct timespec *start, struct timespec *end)
{
return (end->tv_sec - start->tv_sec) + 1e-9*(end->tv_nsec - start->tv_nsec);
}
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define _debug(...) { printf("%s(%d):", __func__, __LINE__); printf(__VA_ARGS__); }
#if 1
#if defined(_MSC_VER) || defined(__MINGW32__)
#define malloc(size) _aligned_malloc(size, 16)
#define free(p) _aligned_free(p)
#else
#define malloc(size) ({ void* p; posix_memalign((void**) &p, 16, size)==0 ? p : NULL; })
#define free(p) free(p)
#endif /* _MSC_VER */
//#define calloc(n, size) ({ void* p = malloc((n*size)); memset(p, 0, (n*size))!=0 ? p : NULL; })
#define calloc(n, size) ({ uint64_t s = n * size; void* p = malloc(s); memset(p, 0, s)!=0 ? p : NULL; })
#endif
#if defined(CATS_OPENGL) || defined(CATS_OPENCL)
#ifndef CATS_USE_FLOAT
#define CATS_USE_FLOAT
#endif
#endif
#ifdef CATS_USE_FIXED
#define real short
#elif defined CATS_USE_FLOAT
#define real float
#define sqrt sqrtf
#define pow powf
#define exp expf
#define log logf
#define fabs fabsf
#define sin sinf
#define cos cosf
#define tan tanf
#define tanh tanhf
#else
#define real double
#warning "using double!!"
#endif
#if defined(CATS_OPENGL)
#define GL_DEBUG
#include "sgemm_gl1.h"
#define sgemm_init(s) sgemm_gl_init(s, s, s)
#define sgemm_finish() sgemm_gl_finish()
#define gemm_rnn(m, n, k, alpha, a, b, beta, c) sgemm_gl(GEMM1_RNN, m, n, k, alpha, a, b, beta, c)
#define gemm_rnt(m, n, k, alpha, a, b, beta, c) sgemm_gl(GEMM1_RNT, m, n, k, alpha, a, b, beta, c)
#define gemm_rtn(m, n, k, alpha, a, b, beta, c) sgemm_gl(GEMM1_RTN, m, n, k, alpha, a, b, beta, c)
#elif defined(CATS_OPENCL)
#include "sgemm_ocl2.h"
#define sgemm_init(s) sgemm_ocl_init(0, 0, /*(s*3)*/0)
#define sgemm_finish() sgemm_ocl_finish()
#define gemm_rnn(m, n, k, alpha, a, b, beta, c) sgemm_ocl('N', 'N', m, n, k, alpha, a, b, beta, c)
#define gemm_rnt(m, n, k, alpha, a, b, beta, c) sgemm_ocl('N', 'T', m, n, k, alpha, a, b, beta, c)
#define gemm_rtn(m, n, k, alpha, a, b, beta, c) sgemm_ocl('T', 'N', m, n, k, alpha, a, b, beta, c)
#else
//#include "gemm_cpu.h"
static void gemm_rnn(int M, int N, int K, real alpha, real* restrict A, real* restrict B, real beta, real* restrict C)
{
if (beta==0.0) {
memset(C, 0, M*N*sizeof(real));
} else if (beta!=1.0) {
for (int i=0; i<M*N; i++) C[i] *= beta;
}
#pragma omp parallel for
for (int m=0; m<M; ++m) { // fast
for (int k=0; k<K; ++k) {
register real A_PART = alpha * A[m*K+k];
for (int n=0; n<N; ++n) {
C[m*N+n] += A_PART * B[k*N+n];
}
}
}
}
static void gemm_rnt(int M, int N, int K, real alpha, real* restrict A, real* restrict B, real beta, real* restrict C)
{
if (beta==0.0) {
memset(C, 0, M*N*sizeof(real));
} else if (beta!=1.0) {
for (int i=0; i<M*N; i++) C[i] *= beta;
}
#pragma omp parallel for
for (int m=0; m<M; ++m) {
for (int n=0; n<N; ++n) {
register real sum = 0;
for (int k=0; k<K; ++k) {
sum += A[m*K+k] * B[k+K*n];
}
C[m*N+n] += alpha * sum;
}
}
}
static void gemm_rtn(int M, int N, int K, real alpha, real* restrict A, real* restrict B, real beta, real* restrict C)
{
if (beta==0.0) {
memset(C, 0, M*N*sizeof(real));
} else if (beta!=1.0) {
for (int i=0; i<M*N; i++) C[i] *= beta;
}
#pragma omp parallel for
for (int m=0; m<M; ++m) {
for (int k=0; k<K; ++k) {
register real A_PART = alpha * A[m+M*k];
for (int n=0; n<N; ++n) {
C[m*N+n] += A_PART * B[k*N+n];
}
}
}
}
#define sgemm_init(s)
#define sgemm_finish()
#endif
// http://xorshift.di.unimi.it/xorshift128plus.c
// https://github.com/AndreasMadsen/xorshift/blob/master/reference.c
// https://ogawa-sankinkoutai.seesaa.net/article/108848981.html
#define XOR128_MAX 18446744073709551615.0
#if __WORDSIZE == 64
typedef unsigned long int uint64_t;
#else
__extension__
typedef unsigned long long int uint64_t;
#endif
// The state must be seeded so that it is not everywhere zero.
uint64_t seed[2];
void xor128_init(uint64_t s)
{
for (int i=1; i<=2; i++) {
seed[i-1] = s = 1812433253U * ( s ^ ( s >> 30 ) ) + i;
}
}
static inline uint64_t xor128()
{
uint64_t s1 = seed[0];
const uint64_t s0 = seed[1];
seed[0] = s0;
s1 ^= s1 << 23;
return ( seed[1] = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) ) ) + s0;
}
// xoroshiro generator taken from http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c
uint64_t xoroshiro_s[2] = {
0X922AC4EB35B502D9L,
0XDA3AA4832B8F1D27L
};
void xoroshiro128plus_init(uint64_t s)
{
for (int i=1; i<=2; i++) {
xoroshiro_s[i-1] = s = 1812433253U * ( s ^ ( s >> 30 ) ) + i;
}
}
static inline uint64_t rotl(const uint64_t x, int k)
{
return (x << k) | (x >> (64 - k));
}
uint64_t xoroshiro128plus()
{
const uint64_t s0 = xoroshiro_s[0];
uint64_t s1 = xoroshiro_s[1];
const uint64_t result = s0 + s1;
s1 ^= s0;
xoroshiro_s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b
xoroshiro_s[1] = rotl(s1, 36); // c
return result;
}
// taken from https://github.com/svaarala/duktape/blob/master/misc/splitmix64.c
uint64_t splitmix64_x; /* The state can be seeded with any value. */
uint64_t splitmix64_next()
{
uint64_t z = (splitmix64_x += UINT64_C(0x9E3779B97F4A7C15));
z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
return z ^ (z >> 31);
}
//#define CATS_USE_XOR128
#ifdef CATS_USE_XOR128
#define xrand() xor128()
#define frand() ( xor128() / (XOR128_MAX+1.0) )
#else
#define xrand() xoroshiro128plus()
#define frand() ( xoroshiro128plus() / (XOR128_MAX+1.0) )
#endif
#define _rand(max) (int)( frand() * max)
#define random(min, max) ( frand() * (max -min) +min )
#define irand(min, max) ( (xrand() % (max -min +1)) +min )
// http://www.natural-science.or.jp/article/20110404234734.php (mt19937ar.h)
// https://omitakahiro.github.io/random/random_variables_generation.html
static inline real rand_normal(real mu, real sigma)
{
real z = sqrt(-2.0*log(frand())) * sin(2.0*M_PI*frand());
return mu + sigma*z;
}
static inline int binomial(/*int n, */real p)
{
// if (p<0 || p>1) return 0;
int c = 0;
// for (int i=0; i<n; i++) {
real r = frand();
if (r < p) c++;
// }
return c;
}
struct __CatsEye;
typedef struct __CatsEye_layer {
int inputs; // input size
int type; // layer type
real eta; // learning rate
int fix; // training / no training
int wtype; // weight init type
real wrange; // weight init
int ksize, kw, kh; // CNN
int stride; // CNN
int padding, pw, ph; // CNN
int px, py, pz; // CNN (AUTO: padding)
int ich, ch; // CNN
int sx, sy, ox, oy; // CNN (AUTO: i/o size)
int r; // Pixel Shuffler
char *layer; // concat
struct __CatsEye_layer* l; // concat
int offset; // concat
// int size; // concat
int order; // concat
// int hiddens; // RNN
// int truncatedTime; // RNN
union {
real momentum; // SGD with momentum
real rho; // RMSProp RHO
} u;
real beta1, beta2; // Adam
real *mu, *var; // Batch Normalization [average, variance]
// real *gamma, *beta; // Batch Normalization
real gamma, beta; // Batch Normalization
real alpha, min, max; // Leaky ReLU, RReLU
// auto config
int outputs; // output size
int wsize; // weight size
real *x; // input
real *z; // output
real *bias; // bias
real *w, *dw, *g, *s; // weight
real *dOut, *dIn; // gradient
real *workspace; // for im2col, col2im
/* real *Wi, *dOuti; // RNN [hidden * time](input -> hidden) = W, dOut
real *Wr, *dOutr; // RNN [hidden * hidden]
real *Wo, *dOuto; // RNN [output * hidden](hidden -> output)
// real *U, *dU; // RNN [hidden * time](input -> hidden)
// real *V, *dV; // RNN [output * hidden](hidden -> output)
real *eh; // RNN [time * hidden]
real *s; // RNN [time * hidden]
real *u; // RNN [time * hidden]
// real *y; // RNN [time * output]
real *v; // RNN [time * output]*/
// real (*act2)(real x); // RNN
// real (*dact2)(real x); // RNN
// research
real forward_time;
real backward_time;
// real update_time;
void (*forward)(struct __CatsEye_layer*);
void (*backward)(struct __CatsEye_layer*);
void (*update)(struct __CatsEye_layer*);
struct __CatsEye *p; // point to struct CatsEye for loss function
char *name; // layer name
} CatsEye_layer;
typedef struct __CatsEye {
// number of each layer
int layers, *u;
CatsEye_layer *layer;
int start, stop, end;
int da; // use data augmentation
// void (*set_data)(struct __CatsEye *this, CatsEye_layer *l, void *data, void *label, void *x, void *t);
void (*set_data)(struct __CatsEye *this, CatsEye_layer *l, int n, int b);
// train parameter
int epoch;
int batch;
int slide;
// label
int16_t *clasify;
real *label;
real lr; // learning rate
real lambda; // weight decay (L2 norm)
int label_size; // internal use
void *label_data; // internal use
real *learning_data; // internal use
int data_num; // internal use
int *shuffle_buffer; // internal use
int shuffle_base; // internal use
real loss;
// output layers [o = f(z)]
real **z, **o, *odata;
int osize;
// gradient value
real **d, *ddata;
int dsize;
// weights
real **w, *wdata;
int *ws, wsize;
// working memory
real *mem;
} CatsEye;
#ifndef RMSPROP_RHO
#define RMSPROP_RHO 0.9
#endif
#ifndef ADAM_BETA1
#define ADAM_BETA1 0.9
#define ADAM_BETA2 0.999
#endif
// https://qiita.com/omiita/items/1735c1d048fe5f611f80
#ifdef CATS_USE_MOMENTUM_SGD
// MomentumSGD [ dw = u * dw - n * g ]
#define SOLVER(l) CatsEye_optimizer_momentumSGD(l)
static void CatsEye_optimizer_momentumSGD(CatsEye_layer *l)
{
for (int i=l->wsize-1; i>=0; i--) {
// l->g[i] = l->u.momentum * l->g[i] -l->p->lr * l->dw[i];
l->g[i] = l->u.momentum * l->g[i] -l->eta * l->dw[i];
l->w[i] += l->g[i];
}
}
#elif defined CATS_USE_ADAGRAD
// adagrad [ g2[i] += g * g; w[i] -= eta * g / sqrt(g2[i]); ]
#define SOLVER(l) CatsEye_optimizer_adagrad(l)
static void CatsEye_optimizer_adagrad(CatsEye_layer *l)
{
for (int i=l->wsize-1; i>=0; i--) {
l->s[i] += l->dw[i] * l->dw[i];
// l->w[i] -= l->p->lr * l->dw[i] / (sqrt(l->s[i]) +1e-12);
l->w[i] -= l->eta * l->dw[i] / (sqrt(l->s[i]) +1e-12);
}
}
#elif defined CATS_USE_RMSPROP
#define SOLVER(l) CatsEye_optimizer_RMSprop(l)
static void CatsEye_optimizer_RMSprop(CatsEye_layer *l)
{
for (int i=l->wsize-1; i>=0; i--) {
l->g[i] = l->u.rho * l->g[i] + (1 - l->u.rho) * l->dw[i] * l->dw[i];
// l->w[i] -= l->p->lr * l->dw[i] / (sqrt(l->g[i] +1e-12));
l->w[i] -= l->eta * l->dw[i] / (sqrt(l->g[i] +1e-12));
}
}
#elif defined CATS_USE_ADAM
#define SOLVER(l) CatsEye_optimizer_Adam(l)
static void CatsEye_optimizer_Adam(CatsEye_layer *l)
{
for (int i=l->wsize-1; i>=0; i--) {
l->g[i] = l->beta1 * l->g[i] + (1 - l->beta1) * l->dw[i];
l->s[i] = l->beta2 * l->s[i] + (1 - l->beta2) * l->dw[i] * l->dw[i];
// l->w[i] -= l->p->lr * l->g[i] / (sqrt(l->s[i] +1e-12));
l->w[i] -= l->eta * l->g[i] / (sqrt(l->s[i] +1e-12));
// l->w[i] -= l->eta * l->g[i]/(1 - l->beta1) / (sqrt(l->s[i]/(1 - l->beta2) +1e-12));
}
}
#else // SGD
// https://tech-lab.sios.jp/archives/21823
// https://github.com/tiny-dnn/tiny-dnn/wiki/%E5%AE%9F%E8%A3%85%E3%83%8E%E3%83%BC%E3%83%88
#define SOLVER(l) CatsEye_optimizer_SGD(l)
static void CatsEye_optimizer_SGD(CatsEye_layer *l)
{
for (int i=l->wsize-1; i>=0; i--) {
// l->w[i] -= l->p->lr * (l->dw[i] +l->p->lambda *l->w[i]); // L2 norm
l->w[i] -= l->eta * (l->dw[i] +/*l->p->lambda*/0.0 *l->w[i]); // L2 norm
}
}
#endif
// Fully connected [ z^l = ( w^l * a^l-1 + b^l ) ]
static void CatsEye_linear_forward(CatsEye_layer *l)
{
#ifdef CATS_TEST
real *o = l->z;
real *w = l->w;
for (int i=l->outputs; i>0; i--) {
real *x = l->x;
register real a = 0;
for (int n=0; n<l->inputs; n++) {
a += (*x++) * (*w++);
}
// *o++ = a;
*o++ = a + *w++; // bias!!
}
#else
// https://petewarden.com/2015/04/20/why-gemm-is-at-the-heart-of-deep-learning/
// output(m,n) := input(m=1,k) * weightsT(k,n)
gemm_rnt(l->p->batch, l->outputs, l->inputs, 1, l->x, l->w, 0, l->z);
for (int n=0; n<l->p->batch; n++) {
for (int i=0; i<l->outputs; i++) l->z[n*l->outputs +i] += l->w[l->inputs*l->outputs +i]; // bias!!
}
// for (int i=l->inputs-10; i<l->inputs; i++) printf("%f ", l->x[i]);
// printf("\n");
// https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html
// output := weightsT * input
// gemm_rtn(l->outputs, l->p->batch, l->inputs, 1, l->w, l->x, 0, l->z);
#endif
}
static void CatsEye_linear_backward(CatsEye_layer *l)
{
#ifdef CATS_TEST
real *d = l->dIn;
real *w = l->w;
// for (int i=0; i<l->inputs; i++) {
for (int i=0; i<=l->inputs; i++) { // bias!!
real *dw = l->dOut;
real *ww = w++;
register real a = 0;
for (int n=0; n<l->outputs; n++) {
a += (*dw++) * (*ww);
// ww += l->inputs;
ww += l->inputs+1; // bias!!
}
*d++ = a;
}
#else
// dIn := dOut * W
gemm_rnn(l->p->batch, l->inputs, l->outputs, 1, l->dOut, l->w, 0, l->dIn);
/* printf("gemm_rnn: ");
for (int i=l->inputs-10; i<l->inputs; i++) printf("%f ", l->dIn[i]);
printf("\n");
printf("GEMM1_RNN: ");
sgemm_gl(GEMM1_RNN, l->p->batch, l->inputs, l->outputs, 1, l->dOut, l->w, 0, l->dIn);
for (int i=l->inputs-10; i<l->inputs; i++) printf("%f ", l->dIn[i]);
printf("\n");*/
// gradients(input) := weights * gradients(output)
// gemm_rnn(l->inputs, l->p->batch, l->outputs, 1, l->w, l->dOut, 0, l->dIn);
#endif
}
static void CatsEye_linear_update(CatsEye_layer *l)
{
#ifdef CATS_TEST
real *w = l->w;
real *d = l->dOut;
for (int i=l->outputs; i>0; i--) {
real *x = l->x;
register real a = -l->eta * (*d++);
for (int n=0; n<l->inputs; n++) {
*w++ += (*x++) * a;
}
*w++ += a; // bias!!
}
#else
// W := W - eta * dOutT * x
gemm_rtn(l->outputs, l->inputs, l->p->batch, 1, l->dOut, l->x, 1, l->dw);
// SOLVER(l);
for (int n=0; n<l->p->batch; n++) {
for (int i=0; i<l->outputs; i++) l->w[l->inputs*l->outputs +i] -= l->eta * l->dOut[n*l->outputs +i]; // bias!!
}
// for (int i=0; i<10; i++) printf("%f ", l->dOut[i]);
/* for (int i=0; i<10; i++) printf("%f ", l->w[i]);
printf("\n");*/
// weights := weights - eta * input * gradientsT(output)
// gemm_rnt(l->inputs, l->outputs, l->p->batch, -l->eta, l->x, l->dOut, 1, l->w);
#endif
}
// convolution [https://github.com/hiroyam/dnn-im2col, https://github.com/pjreddie/darknet]
static inline void im2col(const real *im, const int channels,
const int height, const int width, const int kernel_h, const int kernel_w,
const int pad_h, const int pad_w, const int stride_h, const int stride_w, real *col)
{
int height_col = (height + 2 * pad_h - kernel_h) / stride_h + 1;
int width_col = (width + 2 * pad_w - kernel_w) / stride_w + 1;
int channels_col = channels * kernel_h * kernel_w;
for (int c=0; c<channels_col; c++) {
int w_offset = c % kernel_w;
int h_offset = (c / kernel_w) % kernel_h;
int c_im = c / kernel_h / kernel_w;
for (int h=0; h<height_col; h++) {
for (int w=0; w<width_col; w++) {
int h_pad = h * stride_h - pad_h + h_offset;
int w_pad = w * stride_w - pad_w + w_offset;
if (h_pad >= 0 && h_pad < height && w_pad >= 0 && w_pad < width)
col[(c * height_col + h) * width_col + w] =
im[(c_im * height + h_pad) * width + w_pad];
else
col[(c * height_col + h) * width_col + w] = 0;
}
}
}
}
static inline void col2im(const real *col, const int channels,
const int height, const int width, const int patch_h, const int patch_w,
const int pad_h, const int pad_w, const int stride_h, const int stride_w, real *im)
{
memset(im, 0, sizeof(real)*height * width * channels);
int height_col = (height + 2 * pad_h - patch_h) / stride_h + 1;
int width_col = (width + 2 * pad_w - patch_w) / stride_w + 1;
int channels_col = channels * patch_h * patch_w;
for (int c=0; c<channels_col; ++c) {
int w_offset = c % patch_w;
int h_offset = (c / patch_w) % patch_h;
int c_im = c / patch_h / patch_w;
for (int h=0; h<height_col; ++h) {
for (int w=0; w<width_col; ++w) {
int h_pad = h * stride_h - pad_h + h_offset;
int w_pad = w * stride_w - pad_w + w_offset;
if (h_pad >= 0 && h_pad < height && w_pad >= 0 && w_pad < width)
im[(c_im * height + h_pad) * width + w_pad] +=
col[(c * height_col + h) * width_col + w];
}
}
}
}
static void CatsEye_convolutional_forward(CatsEye_layer *l)
{
#if 1
for (int i=0; i<l->p->batch; i++) {
real *workspace;
if (l->ksize==1) {
workspace = l->x +l->inputs*i;
} else {
workspace = l->workspace +l->ox*l->oy*l->kw*l->kh*l->ich *i;
im2col(l->x +l->inputs*i, l->ich, l->sy, l->sx, l->kh, l->kw, l->ph, l->pw, l->stride, l->stride, workspace);
}
// z = W * x [A(m,k) B(k,n) C(m,n)], cnhw
gemm_rnn(l->ch, l->ox*l->oy*1, l->kw*l->kh*l->ich, 1, l->w, workspace, 0, l->z +l->outputs*i);
// https://docs.nvidia.com/deeplearning/performance/dl-performance-convolutional/index.html
// output := workspace * weights
// gemm_rnn(l->ox*l->oy*1, l->ch, l->ksize*l->ksize*l->ich, 1, workspace, l->w, 0, l->z +l->outputs*i);
}
#else
// https://qiita.com/t-tkd3a/items/6b17f296d61d14e12953
real *workspace;
if (l->ksize==1) {
workspace = l->x;
} else {
workspace = l->workspace;
for (int i=0; i<l->p->batch; i++) {
im2col(l->x +l->inputs*i, l->ich, l->sy, l->sx, l->ksize, l->ksize, l->padding, l->padding, l->stride, l->stride, workspace +l->ksize*l->ksize*l->ich *l->ox*l->oy*i);
}
}
gemm_rnn(l->ch, l->ox*l->oy*l->p->batch, l->ksize*l->ksize*l->ich, 1, l->w, workspace, 0, l->z); // !!z: [ch][ox*sy*batch]
#endif
}
static void CatsEye_convolutional_backward(CatsEye_layer *l)
{
#if 1
for (int i=0; i<l->p->batch; i++) {
real *workspace = l->ksize!=1 ? l->p->mem : l->dIn +l->inputs*i;
// dIn = W**T * dOut [A(m,k) B(k,n) C(m,n)]
gemm_rtn(l->kw*l->kh*l->ich, l->ox*l->oy*1, l->ch, 1, l->w, l->dOut +l->outputs*i, 0, workspace);
/*printf("gemm_rtn: ");
if (i==l->p->batch-1) for (int i=0; i<10; i++) printf("%f ", workspace[i]);
printf("\n");*/
if (l->ksize!=1) {
col2im(workspace, l->ich, l->sy, l->sx, l->kh, l->kw, l->ph, l->pw, l->stride, l->stride, l->dIn +l->inputs*i);
// for (int n=0; n<10; n++) printf("%f ", l->dIn[l->inputs*i + l->inputs-1-n]);
// printf("[%d]\n", l->wsize);
}
}
#else
real *workspace = l->ksize!=1 ? l->p->mem : l->dIn;
gemm_rtn(l->ksize*l->ksize*l->ich, l->ox*l->oy*l->p->batch, l->ch, 1, l->w, l->dOut, 0, workspace);
if (l->ksize!=1) {
for (int i=0; i<l->p->batch; i++) {
col2im(workspace +l->ksize*l->ksize*l->ich *l->ox*l->oy*i, l->ich, l->sy, l->sx, l->ksize, l->ksize, l->padding, l->padding, l->stride, l->stride, l->dIn +l->inputs*i);
}
}
#endif
}
static void CatsEye_convolutional_update(CatsEye_layer *l)
{
#if 1
for (int i=0; i<l->p->batch; i++) {
real *workspace = l->ksize!=1 ? l->workspace +l->ox*l->oy*l->kw*l->kh*l->ich *i : l->x +l->inputs*i;
// W = W - eta * dOut * x**T [A(m,k) B(k,n) C(m,n)]
// gemm_rnt(l->ch, l->ksize*l->ksize*l->ich, l->ox*l->oy*1, 1, l->dOut +l->outputs*i, workspace, 1, l->dw);
gemm_rnt(l->ch, l->kw*l->kh*l->ich, l->ox*l->oy*1, 1.0/l->p->batch, l->dOut +l->outputs*i, workspace, 1, l->dw);
// for (int i=0; i<100; i++) printf("%f ", l->dw[l->wsize-1-i]);
// printf("\n");
}
// for (int i=0; i<l->wsize; i++) l->dw[i] /= l->p->batch; // avg
// for (int i=0; i<10; i++) printf("%f ", l->dOut[i +l->outputs*(l->p->batch-1)]);
// for (int i=0; i<10; i++) printf("%f ", l->dw[i]);
// printf("w:%d %d\n", l->wsize, l->ch*l->ksize*l->ksize*l->ich);
// SOLVER(l);
#else
real *workspace = l->ksize!=1 ? l->workspace : l->x;
gemm_rnt(l->ch, l->ksize*l->ksize*l->ich, l->ox*l->oy*l->p->batch, -l->eta, l->dOut, workspace, 0, l->dw);
#endif
}
// https://github.com/pjreddie/darknet/blob/master/src/deconvolutional_layer.c
static void CatsEye_deconvolutional_forward(CatsEye_layer *l)
{
for (int i=0; i<l->p->batch; i++) {
gemm_rtn(l->ksize*l->ksize*l->ch, l->sx*l->sy*1, l->ich, 1, l->w, l->x +l->inputs*i, 0, l->p->mem);
col2im(l->p->mem, l->ch, l->oy, l->ox, l->ksize, l->ksize, l->padding, l->padding, l->stride, l->stride, l->z +l->outputs*i);
}
}
static void CatsEye_deconvolutional_backward(CatsEye_layer *l)
{
for (int i=0; i<l->p->batch; i++) {
real *workspace = l->workspace +l->sx*l->sy*l->kw*l->kh*l->ch *i;
im2col(l->dOut +l->outputs*i, l->ch, l->oy, l->ox, l->ksize, l->ksize, l->padding, l->padding, l->stride, l->stride, workspace);
gemm_rnn(l->ich, l->sx*l->sy*1, l->ksize*l->ksize*l->ch, 1, l->w, workspace, 0, l->dIn +i*l->inputs);
}
}
static void CatsEye_deconvolutional_update(CatsEye_layer *l)
{
for (int i=0; i<l->p->batch; i++) {
real *workspace = l->workspace +l->sx*l->sy*l->kw*l->kh*l->ch *i;
gemm_rnt(l->ich, l->ksize*l->ksize*l->ch, l->sx*l->sy*1, 1, l->x +l->inputs*i, workspace, 1, l->dw);
}
// SOLVER(l);
}
// calculate forward propagation
static void CatsEye_maxpooling_forward(CatsEye_layer *l)
{
int step = l->sx -l->ksize;
for (int i=0; i<l->p->batch; i++) {
int *max = (int*)l->workspace +l->outputs*i; // temp
real *o = l->z +l->outputs*i;
for (int c=0; c<l->ch; c++) { // in/out
for (int y=0; y<l->oy; y++) {
int ix = c*l->sx*l->sy + y*l->stride*l->sx +l->inputs*i;
for (int x=0; x<l->ox; x++) {
int n = ix+x*l->stride;
real a = l->x[n];
*max = n;
for (int wy=l->ksize; wy>0; wy--) {
for (int wx=l->ksize; wx>0; wx--) {
if (a<l->x[n]) {
a = l->x[n];
*max = n;
}
n++;
}
n += step;
}
max++;
*o++ = a;
}
}
}
}
}
// calculate back propagation
static void CatsEye_maxpooling_backward(CatsEye_layer *l)
{
int *max = (int*)l->workspace; // temp
real *delta = l->dOut;
real *d = l->dIn;
memset(d, 0, sizeof(real)*l->inputs *l->p->batch);
for (int i=0; i<l->outputs *l->p->batch; i++) {
d[*max++] += *delta++;
}
}
static void CatsEye_avgpooling_forward(CatsEye_layer *l)
{
int step = l->sx -l->ksize;
real n = l->ksize * l->ksize;
for (int i=0; i<l->p->batch; i++) {
real *o = l->z +l->outputs*i;
for (int c=0; c<l->ch; c++) { // in/out
for (int y=0; y<l->oy; y++) {
int ix = c*l->sx*l->sy + y*l->stride*l->sx +l->inputs*i;
for (int x=0; x<l->ox; x++) {
real *u = l->x + ix+x*l->stride;
real a = 0;
for (int wy=l->ksize; wy>0; wy--) {
for (int wx=l->ksize; wx>0; wx--) {
a += *u++;
}
u += step;
}
*o++ = a / n;
}
}
}
}
}
static void CatsEye_avgpooling_backward(CatsEye_layer *l)
{
int step = l->sx -l->ksize;
real n = l->ksize * l->ksize;
memset(l->dIn, 0, sizeof(real)*l->inputs *l->p->batch);
for (int i=0; i<l->p->batch; i++) {
real *delta = l->dOut +l->outputs*i;
for (int c=0; c<l->ch; c++) { // in/out
for (int y=0; y<l->oy; y++) {
int ix = c*l->sx*l->sy + y*l->stride*l->sx +l->inputs*i;
for (int x=0; x<l->ox; x++) {
real *d = l->dIn + ix+x*l->stride;
real a = *delta++ / n;
for (int wy=l->ksize; wy>0; wy--) {
for (int wx=l->ksize; wx>0; wx--) {
*d++ += a;
}
d += step;
}
}
}
}
}
}
static void CatsEye_global_avgpooling_forward(CatsEye_layer *l)
{
real *o = l->z;
real *u = l->x;
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ich; c++) { // in/out
real a = 0;
for (int n=l->sx*l->sy; n>0; n--) {
a += *u++;
}
*o++ = a / (l->sx*l->sy);
}
}
}
static void CatsEye_global_avgpooling_backward(CatsEye_layer *l)
{
// memset(l->dIn, 0, sizeof(real)*l->inputs *l->p->batch);
real *delta = l->dOut;
real *d = l->dIn;
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ich; c++) { // in/out
real a = (*delta++) / (l->sx*l->sy);
for (int n=l->sx*l->sy; n>0; n--) {
*d++ = a;
}
}
}
}
// Sub-Pixel Convolution
static void CatsEye_PixelShuffler_forward(CatsEye_layer *l)
{
int ch = l->ich / l->ch;
real *x = l->x;
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ch; c++) { // out
real *o = l->z + c*l->ox*l->oy +l->outputs*i;
for (int cc=0; cc<ch; cc++) { // in
int px = cc%l->r;
int py = cc/l->r;
for (int n=0; n<l->sy; n++) {
for (int m=0; m<l->sx; m++) {
o[m*l->r+px +(n*l->r+py)*l->ox] = *x++;
}
}
}
}
}
}
static void CatsEye_PixelShuffler_backward(CatsEye_layer *l)
{
int ch = l->ich / l->ch;
real *x = l->dIn;
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ch; c++) { // out
real *delta = l->dOut + c*l->ox*l->oy +l->outputs*i;
for (int cc=0; cc<ch; cc++) { // in
int px = cc%l->r;
int py = cc/l->r;
for (int n=0; n<l->sy; n++) {
for (int m=0; m<l->sx; m++) {
*x++ = delta[m*l->r+px +(n*l->r+py)*l->ox];
}
}
}
}
}
}
// FIXME: obsolete
static void CatsEye_padding_forward(CatsEye_layer *l)
{
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ch; c++) { // in/out
real *x = l->x +c*l->sx*l->sy +l->inputs*i;
real *o = l->z +c*l->ox*l->oy +l->ox*l->padding +l->padding +l->outputs*i;
for (int n=0; n<l->sy; n++) {
memcpy(o, x, sizeof(real)*l->sx);
x += l->sx;
o += l->ox;
}
}
}
}
static void CatsEye_padding_backward(CatsEye_layer *l)
{
for (int i=0; i<l->p->batch; i++) {
for (int c=0; c<l->ch; c++) { // in/out
real *d = l->dIn +c*l->sx*l->sy +l->inputs*i;
real *delta = l->dOut +c*l->ox*l->oy +l->ox*l->padding +l->padding +l->outputs*i;
for (int n=0; n<l->sy; n++) {
memcpy(d, delta, sizeof(real)*l->sx);
d += l->sx;
delta += l->ox;
}
}
}
}
// https://qiita.com/t-tkd3a/items/14950dbf55f7a3095600
// https://qiita.com/omiita/items/01855ff13cc6d3720ea4
static void CatsEye_BatchNormalization_forward(CatsEye_layer *l)
{
// if (l->p->batch<4) return;
int len = l->p->batch *l->inputs /l->r/*ch*/;
real *x = l->x;
real *z = l->z;
for (int n=0; n<l->r; n++) {
// average/mean
real avg = 0;
for (int i=0; i<len; i++) avg += x[i];
avg /= len;
// variance
real var = 0;
for (int i=0; i<len; i++) {
z[i] = x[i] -avg;
var += z[i] * z[i];
}
var /= len;
real sigma = sqrt(var + 1e-8);
// normalize, scale and shift
for (int i=0; i<len; i++) {
z[i] = (z[i] / sigma) * l->gamma + l->beta;
}
l->mu[n] = avg;
l->var[n] = var;
x += len;
z += len;
}
}
// https://deepnotes.io/batchnorm
static void CatsEye_BatchNormalization_backward(CatsEye_layer *l)
{
// if (l->p->batch<4) return;
int len = l->p->batch *l->inputs /l->r;
real *x = l->x;
real *delta = l->dOut;
real *d = l->dIn;
real dgamma = 0;
real dbeta = 0;
for (int n=0; n<l->r; n++) {
real sigma = sqrt(l->var[n] + 1e-8);
real dvar = 0;
real dmu = 0;
real dmu2 = 0;
for (int i=0; i<len; i++) {
real X_mu = x[i] - l->mu[n];
real dX_norm = delta[i] * l->gamma;
dvar += dX_norm * X_mu;
d[i] = dX_norm / sigma;
dmu += - d[i]; //dX_norm / -sigma;
dmu2 += -2.0 * X_mu;
dbeta += delta[i];
dgamma = delta[i] * (x[i] -l->mu[n]) /sqrt(l->var[n] + 1e-8);
}
dvar *= -0.5 * pow(l->var[n] + 1e-8, -3.0/2.0);
dmu += dvar * dmu2/len;
real a = dmu / len;
real b = dvar * 2.0 / len;
for (int i=0; i<len; i++) {
d[i] += a + b * (x[i] - l->mu[n]);
}
// l->beta[n] -= l->eta * dbeta;
// l->gamma[n] -= l->eta * dgamma;
l->beta -= l->eta * dbeta;
l->gamma -= l->eta * dgamma;
x += len;
delta += len;
d += len;
}
}
static void CatsEye_concat_forward(CatsEye_layer *l)
{
real *x = l->x;
real *mix = l->l->x +l->offset;
real *z = l->z;
for (int i=0; i<l->p->batch; i++) {
if (l->order) {
memcpy(z+(l->outputs - l->inputs), x, l->inputs*sizeof(real));
memcpy(z, mix, (l->outputs - l->inputs)*sizeof(real));
} else {
memcpy(z, x, l->inputs*sizeof(real));
memcpy(z+l->inputs, mix, (l->outputs - l->inputs)*sizeof(real));
}
x += l->inputs;
mix += l->l->inputs;
z += l->outputs;
}
}
static void CatsEye_concat_backward(CatsEye_layer *l)
{
real *d = l->dIn;
real *delta = l->dOut;
for (int i=0; i<l->p->batch; i++) {
if (l->order) {
memcpy(d, delta+(l->outputs - l->inputs), l->inputs*sizeof(real));
} else {
memcpy(d, delta, l->inputs*sizeof(real));
}
// memcpy(l->l->dIn+l->offset, l->dOut+l->inputs, (l->outputs - l->inputs)*sizeof(real));
d += l->inputs;
delta += l->outputs;
}
}
static void CatsEye_shortcut_forward(CatsEye_layer *l)
{
real *x = l->x;
real *a = l->l->x +l->offset;
real *z = l->z;
for (int i=0; i<l->p->batch; i++) {
memcpy(z, x, l->inputs*sizeof(real));
if (l->r) { // *r
int len = l->l->inputs / l->l->ich;
for (int ic=0; ic<l->l->ich; ic++) {
for (int c=0; c<l->r; c++) {
for (int n=0; n<len; n++) z[(ic*l->r +c)*len +n] += a[ic*len +n];
}
}
} else {
for (int n=0; n<l->inputs; n++) z[n] += a[n];
}
x += l->inputs;
a += l->l->inputs;
z += l->outputs;
}
}