-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy patheigenbackend.cpp
1872 lines (1645 loc) · 62.4 KB
/
eigenbackend.cpp
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
#ifdef USE_EIGEN_BACKEND
/** Eigen3 backend.
*
* Only supports float32 computation with NHWC memory layout (at runtime and as input).
*/
//TODO someday - not sure how to make thread pool work with TensorMap. It works with Tensor, but TensorMap doesn't seem to have a device(...) method.
//#define EIGEN_USE_THREADS
#include "../neuralnet/nninterface.h"
#include <Eigen/Dense>
#include <unsupported/Eigen/CXX11/Tensor>
#include <zstr/src/zstr.hpp>
#include "../neuralnet/desc.h"
#include "../neuralnet/modelversion.h"
#include "../neuralnet/nninputs.h"
#include "../neuralnet/nneval.h"
using namespace std;
using Eigen::Tensor;
using Eigen::TensorMap;
//Eigen doesn't seem to have a way to make a const tensor map out of a const float* ??
//So we have to cast away qualifiers to build it.
#pragma GCC diagnostic ignored "-Wcast-qual"
// Eigen tensors are stored in column-major order, so an NHWC memory layout is given by Tensor<4>(C,W,H,N).
#define SCALAR float
#define TENSOR2 Tensor<SCALAR, 2>
#define TENSOR3 Tensor<SCALAR, 3>
#define TENSOR4 Tensor<SCALAR, 4>
#define TENSORMAP2 TensorMap<Tensor<SCALAR, 2>>
#define TENSORMAP3 TensorMap<Tensor<SCALAR, 3>>
#define TENSORMAP4 TensorMap<Tensor<SCALAR, 4>>
#define CONSTTENSOR2 const Tensor<SCALAR, 2>
#define CONSTTENSOR3 const Tensor<SCALAR, 3>
#define CONSTTENSOR4 const Tensor<SCALAR, 4>
#define CONSTTENSORMAP2 const TensorMap<Tensor<SCALAR, 2>>
#define CONSTTENSORMAP3 const TensorMap<Tensor<SCALAR, 3>>
#define CONSTTENSORMAP4 const TensorMap<Tensor<SCALAR, 4>>
// Debugging -----------------------------------------------------------------------------------------------------------
// #define DEBUG true
template <typename T>
void printTensorShape(const string& name, const T* t) {
auto d = t->dimensions();
cout << name << " rank=" << d.size() << " - (";
for (int i = 0; i < d.size(); i++) {
cout << d[i] << ",";
}
cout << ")" << endl;
}
#if DEBUG
#define DSHAPE(n, x) printTensorShape(n,x)
#define DTENSOR(n, x) cout << n << *x << endl
#else
#define DSHAPE(n, x)
#define DTENSOR(n, x)
#endif
// LoadedModel / ModelDesc ---------------------------------------------------------------------------------------------
struct LoadedModel {
ModelDesc modelDesc;
LoadedModel(const string& fileName) {
ModelDesc::loadFromFileMaybeGZipped(fileName,modelDesc);
}
LoadedModel() = delete;
LoadedModel(const LoadedModel&) = delete;
LoadedModel& operator=(const LoadedModel&) = delete;
};
LoadedModel* NeuralNet::loadModelFile(const string& file) {
LoadedModel* loadedModel = new LoadedModel(file);
return loadedModel;
}
void NeuralNet::freeLoadedModel(LoadedModel* loadedModel) {
delete loadedModel;
}
string NeuralNet::getModelName(const LoadedModel* loadedModel) {
return loadedModel->modelDesc.name;
}
int NeuralNet::getModelVersion(const LoadedModel* loadedModel) {
return loadedModel->modelDesc.version;
}
Rules NeuralNet::getSupportedRules(const LoadedModel* loadedModel, const Rules& desiredRules, bool& supported) {
return loadedModel->modelDesc.getSupportedRules(desiredRules, supported);
}
// Helpers --------------------------------------------------------------------------------------------------------------
static void computeMaskSum(CONSTTENSORMAP3* mask, float* maskSum) {
for (int n = 0; n < mask->dimension(2); n++) {
float s = 0.f;
for (int h = 0; h < mask->dimension(1); h++) {
for (int w = 0; w < mask->dimension(0); w++) {
s += (*mask)(w, h, n);
}
}
maskSum[n] = s;
}
}
// in NxHxWxC, bias NxC
static void addNCBiasInplace(TENSORMAP4* in, CONSTTENSORMAP2* bias) {
assert(in->dimension(0) == bias->dimension(0) && in->dimension(3) == bias->dimension(1));
for (int n = 0; n < in->dimension(3); n++) {
for (int h = 0; h < in->dimension(2); h++) {
for (int w = 0; w < in->dimension(1); w++) {
for (int c = 0; c < in->dimension(0); c++) {
(*in)(c,w,h,n) += (*bias)(c,n);
}
}
}
}
}
static void poolRowsGPool(CONSTTENSORMAP4* in, TENSORMAP2* out, const float* maskSum) {
for (int n = 0; n < in->dimension(3); n++) {
for (int c = 0; c < in->dimension(0); c++) {
float s = 0.f;
float m = 0.f;
for (int h = 0; h < in->dimension(2); h++) {
for (int w = 0; w < in->dimension(1); w++) {
float x = (*in)(c, w, h, n);
s += x;
m = max(m, x);
}
}
float div = maskSum[n];
float sqrtdiv = sqrt(div);
float mean = s / div;
(*out)(c, n) = mean;
(*out)(c + in->dimension(0), n) = mean * (sqrtdiv - 14.f) * 0.1f;
(*out)(c + 2*in->dimension(0), n) = m;
}
}
}
static void poolRowsValueHead(CONSTTENSORMAP4* in, TENSORMAP2* out, const float* maskSum) {
for (int n = 0; n < in->dimension(3); n++) {
for (int c = 0; c < in->dimension(0); c++) {
float s = 0.f;
for (int h = 0; h < in->dimension(2); h++) {
for (int w = 0; w < in->dimension(1); w++) {
float x = (*in)(c, w, h, n);
s += x;
}
}
float div = maskSum[n];
float sqrtdiv = sqrt(div);
float mean = s / div;
(*out)(c, n) = mean;
(*out)(c + in->dimension(0), n) = mean * (sqrtdiv - 14.f) * 0.1f;
(*out)(c + 2*in->dimension(0), n) = mean * ((sqrtdiv - 14.0f) * (sqrtdiv - 14.0f) * 0.01f - 0.1f);
}
}
}
static size_t roundUpToMultiple(size_t size, size_t ofThis) {
return (size + ofThis - 1) / ofThis * ofThis;
}
// --------------------------------------------------------------------------------------------------------------
struct ComputeHandleInternal {
//static constexpr int numEigenThreads = 2;
//Eigen::ThreadPool threadPool;
//Eigen::ThreadPoolDevice device;
ComputeHandleInternal()
{
}
};
// Layers --------------------------------------------------------------------------------------------------------------
// Convolution layer with zero-padding.
struct ConvLayer {
string name;
TENSOR2 imagePatchKernel;
TENSOR3 winogradKernel;
int inChannels;
int outChannels;
int convYSize;
int convXSize;
int nnXLen;
int nnYLen;
int imagePatchSize;
int numTilesX;
int numTilesY;
int inTileXYSize;
int outTileXYSize;
ConvLayer() = delete;
ConvLayer(const ConvLayer&) = delete;
ConvLayer& operator=(const ConvLayer&) = delete;
ConvLayer(const ConvLayerDesc& desc, int nnX, int nnY) {
name = desc.name;
convYSize = desc.convYSize;
convXSize = desc.convXSize;
inChannels = desc.inChannels;
outChannels = desc.outChannels;
//Currently eigen impl doesn't support dilated convs
int dilationY = desc.dilationY;
int dilationX = desc.dilationX;
if(dilationX != 1 || dilationY != 1)
throw StringError("Eigen backend: Encountered convolution dilation factors other than 1, not supported");
assert(convXSize % 2 == 1);
assert(convYSize % 2 == 1);
nnXLen = nnX;
nnYLen = nnY;
if((convXSize == 3 && convYSize == 3) || (convXSize == 5 && convYSize == 5)) {
imagePatchSize = 0; //not used in this branch
const int inTileXSize = 6;
const int inTileYSize = 6;
const int outTileXSize = convXSize == 5 ? 2 : 4;
const int outTileYSize = convYSize == 5 ? 2 : 4;
numTilesX = (nnXLen + outTileXSize - 1) / outTileXSize;
numTilesY = (nnYLen + outTileYSize - 1) / outTileYSize;
inTileXYSize = inTileXSize * inTileYSize;
outTileXYSize = outTileXSize * outTileYSize;
static constexpr int maxTileXSize = 6;
static constexpr int maxTileYSize = 6;
//INTILE_YSIZE, INTILE_XSIZE, ic, oc
vector<float> transWeights(inTileXYSize * inChannels * outChannels);
auto transform3x3_6 = [](float& a0, float& a1, float& a2, float& a3, float& a4, float& a5) {
float z0 = a0; float z1 = a1; float z2 = a2;
a0 = 0.25f * z0;
a1 = (float)( (1.0 / 6.0) * (-z0 - z1 - z2) );
a2 = (float)( (1.0 / 6.0) * (-z0 + z1 - z2) );
a3 = (float)( (1.0 / 24.0) * (z0 + 2.0*z1 + 4.0*z2) );
a4 = (float)( (1.0 / 24.0) * (z0 - 2.0*z1 + 4.0*z2) );
a5 = 1.0f * z2;
};
auto transform5x5_6 = [](float& a0, float& a1, float& a2, float& a3, float& a4, float& a5) {
float z0 = a0; float z1 = a1; float z2 = a2; float z3 = a3; float z4 = a4;
a0 = 0.25f * z0;
a1 = (float)( (1.0 / 6.0) * (-z0 - z1 - z2 - z3 - z4) );
a2 = (float)( (1.0 / 6.0) * (-z0 + z1 - z2 + z3 - z4) );
a3 = (float)( (1.0 / 24.0) * (z0 + 2.0*z1 + 4.0*z2 + 8.0*z3 + 16.0*z4) );
a4 = (float)( (1.0 / 24.0) * (z0 - 2.0*z1 + 4.0*z2 - 8.0*z3 + 16.0*z4) );
a5 = 1.0f * z4;
};
for(int oc = 0; oc < outChannels; oc++) {
for(int ic = 0; ic < inChannels; ic++) {
float tmp[maxTileYSize][maxTileXSize];
for(int subY = 0; subY < convYSize; subY++) {
for(int subX = 0; subX < convXSize; subX++) {
if(oc < outChannels && ic < inChannels)
tmp[subY][subX] = desc.weights[((oc * inChannels + ic) * convYSize + subY) * convXSize + subX];
else
tmp[subY][subX] = 0.0f;
}
}
if(convXSize == 3) {
for(int subY = 0; subY < convYSize; subY++)
transform3x3_6(tmp[subY][0], tmp[subY][1], tmp[subY][2], tmp[subY][3], tmp[subY][4], tmp[subY][5]);
}
else if(convXSize == 5) {
for(int subY = 0; subY < convYSize; subY++)
transform5x5_6(tmp[subY][0], tmp[subY][1], tmp[subY][2], tmp[subY][3], tmp[subY][4], tmp[subY][5]);
}
if(convYSize == 3) {
for(int subX = 0; subX < inTileXSize; subX++)
transform3x3_6(tmp[0][subX], tmp[1][subX], tmp[2][subX], tmp[3][subX], tmp[4][subX], tmp[5][subX]);
}
else if(convYSize == 5) {
for(int subX = 0; subX < inTileXSize; subX++)
transform5x5_6(tmp[0][subX], tmp[1][subX], tmp[2][subX], tmp[3][subX], tmp[4][subX], tmp[5][subX]);
}
for(int subY = 0; subY < inTileYSize; subY++) {
for(int subX = 0; subX < inTileXSize; subX++) {
transWeights[((subY*inTileXSize + subX)*inChannels + ic)*outChannels + oc] = tmp[subY][subX];
}
}
}
}
winogradKernel = TensorMap<const Tensor<const SCALAR, 3>>(
transWeights.data(), outChannels, inChannels, inTileXSize * inTileYSize);
}
else {
numTilesX = 0; //not used in this branch
numTilesY = 0; //not used in this branch
inTileXYSize = 0; //not used in this branch
outTileXYSize = 0; //not used in this branch
TENSOR4 kernel = TensorMap<const Tensor<const SCALAR, 4>>(desc.weights.data(), convXSize, convYSize, inChannels, outChannels);
imagePatchSize = convXSize * convYSize * inChannels;
Eigen::array<Eigen::Index, 4> dimensionPermutatation = {3, 2, 0, 1};
Eigen::array<Eigen::Index, 2> newShape = {outChannels, imagePatchSize};
imagePatchKernel = kernel.shuffle(dimensionPermutatation).reshape(newShape);
}
}
size_t requiredConvWorkspaceElts(size_t maxBatchSize) const {
if((convXSize == 3 && convYSize == 3) || (convXSize == 5 && convYSize == 5)) {
constexpr int inTileXSize = 6;
constexpr int inTileYSize = 6;
size_t totalChannelsRounded = roundUpToMultiple(inChannels,32) + roundUpToMultiple(outChannels,32);
size_t sizeForTransforms = totalChannelsRounded * maxBatchSize * numTilesY * numTilesX * inTileXSize * inTileYSize;
size_t sizeForTileBufs = 2 * inTileXSize * inTileYSize * roundUpToMultiple(std::max(inChannels,outChannels),32);
return sizeForTransforms + sizeForTileBufs;
}
return 0;
}
void apply(ComputeHandleInternal* handle, CONSTTENSORMAP4* input, TENSORMAP4* output, float* convWorkspace, bool accumulate) const {
(void)handle;
assert(output->dimension(0) == outChannels);
assert(input->dimension(0) == inChannels);
assert(input->dimension(1) == nnXLen);
assert(input->dimension(2) == nnYLen);
const int batchSize = input->dimension(3);
const int xSize = nnXLen;
const int ySize = nnYLen;
if((convXSize == 3 && convYSize == 3) || (convXSize == 5 && convYSize == 5)) {
constexpr int inTileXSize = 6;
constexpr int inTileYSize = 6;
const int inTileXOffset = convXSize == 5 ? -2 : -1;
const int inTileYOffset = convYSize == 5 ? -2 : -1;
const int outTileXSize = convXSize == 5 ? 2 : 4;
const int outTileYSize = convYSize == 5 ? 2 : 4;
float* tile = convWorkspace;
float* tile2 = tile + inTileXSize * inTileYSize * roundUpToMultiple(std::max(inChannels,outChannels),32);
float* convWorkspaceIn = tile2 + inTileXSize * inTileYSize * roundUpToMultiple(std::max(inChannels,outChannels),32);
float* convWorkspaceOut = convWorkspaceIn + roundUpToMultiple(inChannels,32) * batchSize * numTilesY * numTilesX * inTileXSize * inTileYSize;
TENSORMAP3 transformedInput(convWorkspaceIn, inChannels, batchSize * numTilesY * numTilesX, inTileXSize * inTileYSize);
TENSORMAP3 transformedOutput(convWorkspaceOut, outChannels, batchSize * numTilesY * numTilesX, inTileXSize * inTileYSize);
for(int n = 0; n < batchSize; n++) {
for(int yTile = 0; yTile < numTilesY; yTile++) {
for(int xTile = 0; xTile < numTilesX; xTile++) {
for(int dy = 0; dy < inTileYSize; dy++) {
for(int dx = 0; dx < inTileXSize; dx++) {
int x = xTile*outTileXSize+dx+inTileXOffset;
int y = yTile*outTileYSize+dy+inTileYOffset;
int subTileIdx = dy * inTileXSize + dx;
if(x < 0 || y < 0 || x >= xSize || y >= ySize) {
std::fill(tile + subTileIdx * inChannels, tile + (subTileIdx+1) * inChannels, 0.0f);
}
else {
for(int ic = 0; ic < inChannels; ic++) {
float z = (*input)(ic,x,y,n);
tile[subTileIdx * inChannels + ic] = z;
}
}
}
}
for(int subY = 0; subY < inTileYSize; subY++) {
float* __restrict t0 = &tile[(subY*inTileXSize+0)*inChannels];
float* __restrict t1 = &tile[(subY*inTileXSize+1)*inChannels];
float* __restrict t2 = &tile[(subY*inTileXSize+2)*inChannels];
float* __restrict t3 = &tile[(subY*inTileXSize+3)*inChannels];
float* __restrict t4 = &tile[(subY*inTileXSize+4)*inChannels];
float* __restrict t5 = &tile[(subY*inTileXSize+5)*inChannels];
for(int ic = 0; ic < inChannels; ic++) {
float z0 = t0[ic];
float z1 = t1[ic];
float z2 = t2[ic];
float z3 = t3[ic];
float z4 = t4[ic];
float z5 = t5[ic];
t0[ic] = 4.0f*z0 - 5.0f*z2 + z4;
t1[ic] = - 4.0f*z1 - 4.0f*z2 + z3 + z4;
t2[ic] = 4.0f*z1 - 4.0f*z2 - z3 + z4;
t3[ic] = - 2.0f*z1 - z2 + 2.0f*z3 + z4;
t4[ic] = 2.0f*z1 - z2 - 2.0f*z3 + z4;
t5[ic] = 4.0f*z1 - 5.0f*z3 + z5;
}
}
for(int subX = 0; subX < inTileXSize; subX++) {
float* __restrict t0 = &tile[(0*inTileXSize+subX)*inChannels];
float* __restrict t1 = &tile[(1*inTileXSize+subX)*inChannels];
float* __restrict t2 = &tile[(2*inTileXSize+subX)*inChannels];
float* __restrict t3 = &tile[(3*inTileXSize+subX)*inChannels];
float* __restrict t4 = &tile[(4*inTileXSize+subX)*inChannels];
float* __restrict t5 = &tile[(5*inTileXSize+subX)*inChannels];
for(int ic = 0; ic < inChannels; ic++) {
float z0 = t0[ic];
float z1 = t1[ic];
float z2 = t2[ic];
float z3 = t3[ic];
float z4 = t4[ic];
float z5 = t5[ic];
t0[ic] = 4.0f*z0 - 5.0f*z2 + z4;
t1[ic] = - 4.0f*z1 - 4.0f*z2 + z3 + z4;
t2[ic] = 4.0f*z1 - 4.0f*z2 - z3 + z4;
t3[ic] = - 2.0f*z1 - z2 + 2.0f*z3 + z4;
t4[ic] = 2.0f*z1 - z2 - 2.0f*z3 + z4;
t5[ic] = 4.0f*z1 - 5.0f*z3 + z5;
}
}
int batchTileXTileY = n * numTilesY * numTilesX + yTile * numTilesX + xTile;
for(int dy = 0; dy < inTileYSize; dy++) {
for(int dx = 0; dx < inTileXSize; dx++) {
for(int ic = 0; ic < inChannels; ic++) {
int subTileIdx = dy * inTileXSize + dx;
transformedInput(ic, batchTileXTileY, subTileIdx) = tile[subTileIdx*inChannels+ic];
}
}
}
}
}
}
//TODO someday: Does eigen have a fast batched matrix multiply?
//Here we just manually iterate over the 36 matrices that need to get multiplied.
//Also, if eigen were to support *interleaved* matrices (viewing it as a matrix whose element is
//a vector of length 36 instead of a float), that might allow for improved transform/untransform implementations.
for(int dy = 0; dy < inTileYSize; dy++) {
for(int dx = 0; dx < inTileXSize; dx++) {
int subTileIdx = dy * inTileXSize + dx;
auto transformedInputMap = Eigen::Map<Eigen::Matrix<SCALAR,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>>(
(float*)transformedInput.data() + subTileIdx * batchSize * numTilesY * numTilesX * inChannels,
inChannels,
batchSize * numTilesY * numTilesX
);
auto winogradKernelMap = Eigen::Map<Eigen::Matrix<SCALAR,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>>(
(float*)winogradKernel.data() + subTileIdx * outChannels * inChannels,
outChannels,
inChannels
);
auto transformedOutputMap = Eigen::Map<Eigen::Matrix<SCALAR,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>>(
(float*)transformedOutput.data() + subTileIdx * batchSize * numTilesY * numTilesX * outChannels,
outChannels,
batchSize * numTilesY * numTilesX
);
transformedOutputMap = winogradKernelMap * transformedInputMap;
}
}
for(int n = 0; n < batchSize; n++) {
for(int yTile = 0; yTile < numTilesY; yTile++) {
for(int xTile = 0; xTile < numTilesX; xTile++) {
int batchTileXTileY = n * numTilesY * numTilesX + yTile * numTilesX + xTile;
for(int dy = 0; dy < inTileYSize; dy++) {
for(int dx = 0; dx < inTileXSize; dx++) {
int subTileIdx = dy * inTileXSize + dx;
for(int oc = 0; oc < outChannels; oc++) {
tile[subTileIdx*outChannels+oc] = transformedOutput(oc, batchTileXTileY, subTileIdx);
}
}
}
if(convXSize == 5 && convYSize == 5) {
for(int subY = 0; subY < inTileYSize; subY++) {
float* __restrict t0 = &tile[(subY*inTileXSize+0)*outChannels];
float* __restrict t1 = &tile[(subY*inTileXSize+1)*outChannels];
float* __restrict t2 = &tile[(subY*inTileXSize+2)*outChannels];
float* __restrict t3 = &tile[(subY*inTileXSize+3)*outChannels];
float* __restrict t4 = &tile[(subY*inTileXSize+4)*outChannels];
float* __restrict t5 = &tile[(subY*inTileXSize+5)*outChannels];
for(int oc = 0; oc < outChannels; oc++) {
float z0 = t0[oc];
float z1 = t1[oc];
float z2 = t2[oc];
float z3 = t3[oc];
float z4 = t4[oc];
float z5 = t5[oc];
t0[oc] = z0 + z1 + z2 + z3 + z4;
t1[oc] = (z1-z2) + 2.0f*(z3-z4) + z5;
}
}
for(int subX = 0; subX < outTileXSize; subX++) {
float* __restrict t0 = &tile[(0*inTileXSize+subX)*outChannels];
float* __restrict t1 = &tile[(1*inTileXSize+subX)*outChannels];
float* __restrict t2 = &tile[(2*inTileXSize+subX)*outChannels];
float* __restrict t3 = &tile[(3*inTileXSize+subX)*outChannels];
float* __restrict t4 = &tile[(4*inTileXSize+subX)*outChannels];
float* __restrict t5 = &tile[(5*inTileXSize+subX)*outChannels];
for(int oc = 0; oc < outChannels; oc++) {
float z0 = t0[oc];
float z1 = t1[oc];
float z2 = t2[oc];
float z3 = t3[oc];
float z4 = t4[oc];
float z5 = t5[oc];
t0[oc] = z0 + z1 + z2 + z3 + z4;
t1[oc] = (z1-z2) + 2.0f*(z3-z4) + z5;
}
}
}
else {
for(int subY = 0; subY < inTileYSize; subY++) {
float* __restrict t0 = &tile[(subY*inTileXSize+0)*outChannels];
float* __restrict t1 = &tile[(subY*inTileXSize+1)*outChannels];
float* __restrict t2 = &tile[(subY*inTileXSize+2)*outChannels];
float* __restrict t3 = &tile[(subY*inTileXSize+3)*outChannels];
float* __restrict t4 = &tile[(subY*inTileXSize+4)*outChannels];
float* __restrict t5 = &tile[(subY*inTileXSize+5)*outChannels];
for(int oc = 0; oc < outChannels; oc++) {
float z0 = t0[oc];
float z1 = t1[oc];
float z2 = t2[oc];
float z3 = t3[oc];
float z4 = t4[oc];
float z5 = t5[oc];
t0[oc] = z0 + z1 + z2 + z3 + z4;
t1[oc] = (z1-z2) + 2.0f*(z3-z4);
t2[oc] = (z1+z2) + 4.0f*(z3+z4);
t3[oc] = (z1-z2) + 8.0f*(z3-z4) + z5;
}
}
for(int subX = 0; subX < outTileXSize; subX++) {
float* __restrict t0 = &tile[(0*inTileXSize+subX)*outChannels];
float* __restrict t1 = &tile[(1*inTileXSize+subX)*outChannels];
float* __restrict t2 = &tile[(2*inTileXSize+subX)*outChannels];
float* __restrict t3 = &tile[(3*inTileXSize+subX)*outChannels];
float* __restrict t4 = &tile[(4*inTileXSize+subX)*outChannels];
float* __restrict t5 = &tile[(5*inTileXSize+subX)*outChannels];
for(int oc = 0; oc < outChannels; oc++) {
float z0 = t0[oc];
float z1 = t1[oc];
float z2 = t2[oc];
float z3 = t3[oc];
float z4 = t4[oc];
float z5 = t5[oc];
t0[oc] = z0 + z1 + z2 + z3 + z4;
t1[oc] = (z1-z2) + 2.0f*(z3-z4);
t2[oc] = (z1+z2) + 4.0f*(z3+z4);
t3[oc] = (z1-z2) + 8.0f*(z3-z4) + z5;
}
}
}
if(accumulate) {
for(int dy = 0; dy < outTileYSize; dy++) {
for(int dx = 0; dx < outTileXSize; dx++) {
int x = xTile*outTileXSize+dx;
int y = yTile*outTileYSize+dy;
if(!(x < 0 || y < 0 || x >= xSize || y >= ySize)) {
int subTileIdx = dy * inTileXSize + dx;
for(int oc = 0; oc < outChannels; oc++) {
(*output)(oc,x,y,n) += tile[subTileIdx*outChannels+oc];
}
}
}
}
}
else {
for(int dy = 0; dy < outTileYSize; dy++) {
for(int dx = 0; dx < outTileXSize; dx++) {
int x = xTile*outTileXSize+dx;
int y = yTile*outTileYSize+dy;
if(!(x < 0 || y < 0 || x >= xSize || y >= ySize)) {
int subTileIdx = dy * inTileXSize + dx;
for(int oc = 0; oc < outChannels; oc++) {
(*output)(oc,x,y,n) = tile[subTileIdx*outChannels+oc];
}
}
}
}
}
}
}
}
}
else {
Eigen::array<Eigen::Index, 2> imagePatchColVectorShape = {imagePatchSize, xSize*ySize*batchSize};
Eigen::array<Eigen::IndexPair<int>, 1> contractionDims = {Eigen::IndexPair<int>(1, 0)};
Eigen::array<Eigen::Index, 4> outputShape = {outChannels,xSize,ySize,batchSize};
auto imagePatches = input->extract_image_patches(convXSize,convYSize).reshape(imagePatchColVectorShape);
auto convolution = imagePatchKernel.contract(imagePatches, contractionDims).reshape(outputShape);
if(accumulate)
*output += convolution;
else
*output = convolution;
}
}
};
//--------------------------------------------------------------
struct BatchNormLayer {
string name;
vector<float> mergedScale;
vector<float> mergedBias;
BatchNormLayer() = delete;
BatchNormLayer(const BatchNormLayer&) = delete;
BatchNormLayer& operator=(const BatchNormLayer&) = delete;
BatchNormLayer(const BatchNormLayerDesc& desc) {
name = desc.name;
int numChannels = desc.numChannels;
float epsilon = desc.epsilon;
mergedScale.resize(numChannels);
mergedBias.resize(numChannels);
for(int c = 0; c < numChannels; c++) {
mergedScale[c] = desc.scale[c] / sqrt(desc.variance[c] + epsilon);
mergedBias[c] = desc.bias[c] - mergedScale[c] * desc.mean[c];
}
}
// Mask should be in 'NHW' format (no "C" channel).
void apply(
bool applyRelu,
CONSTTENSORMAP4* input,
TENSORMAP4* output,
CONSTTENSORMAP3* mask
) const {
for(int c = 0; c < input->dimension(0); c++) {
auto inC = input->chip(c, 0);
auto x = inC * mergedScale[c] + mergedBias[c];
auto z = TENSOR3(mask->dimension(0), mask->dimension(1), mask->dimension(2)).setZero();
if(applyRelu)
output->chip(c, 0) = (*mask == 1.f).select(x.cwiseMax(0.f), z);
else
output->chip(c, 0) = (*mask == 1.f).select(x, z);
}
}
};
//--------------------------------------------------------------
struct ActivationLayer {
string name;
ActivationLayer() = delete;
ActivationLayer(const ActivationLayer&) = delete;
ActivationLayer& operator=(const ActivationLayer&) = delete;
ActivationLayer(const ActivationLayerDesc& desc) { name = desc.name; }
template <int N>
void apply(const Tensor<SCALAR, N>* input, Tensor<SCALAR, N>* output) const { *output = input->cwiseMax(0.f); }
template <int N>
void apply(const TensorMap<Tensor<SCALAR, N>>* input, TensorMap<Tensor<SCALAR, N>>* output) const { *output = input->cwiseMax(0.f); }
};
//--------------------------------------------------------------
struct MatMulLayer {
string name;
TENSOR2 weights;
MatMulLayer() = delete;
MatMulLayer(const MatMulLayer&) = delete;
MatMulLayer& operator=(const MatMulLayer&) = delete;
MatMulLayer(const MatMulLayerDesc& desc)
: name(desc.name)
{
weights = TENSOR2(desc.outChannels, desc.inChannels);
memcpy(weights.data(), desc.weights.data(), sizeof(SCALAR) * weights.size());
}
void apply(CONSTTENSORMAP2* in, TENSORMAP2* out) const {
Eigen::array<Eigen::IndexPair<int>, 1> product_dims = { Eigen::IndexPair<int>(1, 0) };
*out = weights.contract(*in, product_dims);
}
};
struct MatBiasLayer {
string name;
std::vector<float> weights;
MatBiasLayer() = delete;
MatBiasLayer(const MatBiasLayer&) = delete;
MatBiasLayer& operator=(const MatBiasLayer&) = delete;
MatBiasLayer(const MatBiasLayerDesc& desc)
: name(desc.name),
weights(desc.weights) {}
void apply(TENSORMAP2* mat) const {
for(int n = 0; n < mat->dimension(1); n++) {
for(int c = 0; c < mat->dimension(0); c++) {
(*mat)(c, n) += weights[c];
}
}
}
};
// Blocks
// --------------------------------------------------------------------------------------------------------------
struct ResidualBlockIntf {
virtual ~ResidualBlockIntf(){}
virtual void apply(
ComputeHandleInternal* handle,
TENSORMAP4* trunk,
TENSORMAP4* trunkScratch,
TENSORMAP4* regularOut,
TENSORMAP4* regularScratch,
TENSORMAP4* midIn,
TENSORMAP4* midScratch,
TENSORMAP4* gpoolOut,
TENSORMAP4* gpoolOut2,
TENSORMAP2* gpoolConcat,
TENSORMAP2* gpoolBias,
CONSTTENSORMAP3* mask,
const float* maskSum,
float* convWorkspace
) const = 0;
virtual size_t requiredConvWorkspaceElts(size_t maxBatchSize) const = 0;
};
struct ResidualBlock final : public ResidualBlockIntf {
string name;
BatchNormLayer preBN;
ConvLayer regularConv;
BatchNormLayer midBN;
ConvLayer finalConv;
ResidualBlock() = delete;
ResidualBlock(const ResidualBlock&) = delete;
ResidualBlock& operator=(const ResidualBlock&) = delete;
~ResidualBlock(){}
ResidualBlock(const ResidualBlockDesc& desc, int nnX, int nnY)
: name(desc.name),
preBN(desc.preBN),
regularConv(desc.regularConv,nnX,nnY),
midBN(desc.midBN),
finalConv(desc.finalConv,nnX,nnY) {}
size_t requiredConvWorkspaceElts(size_t maxBatchSize) const {
return std::max(
regularConv.requiredConvWorkspaceElts(maxBatchSize),
finalConv.requiredConvWorkspaceElts(maxBatchSize)
);
}
void apply(
ComputeHandleInternal* handle,
TENSORMAP4* trunk,
TENSORMAP4* trunkScratch,
TENSORMAP4* regularOut,
TENSORMAP4* regularScratch,
TENSORMAP4* midIn,
TENSORMAP4* midScratch,
TENSORMAP4* gpoolOut,
TENSORMAP4* gpoolOut2,
TENSORMAP2* gpoolConcat,
TENSORMAP2* gpoolBias,
CONSTTENSORMAP3* mask,
const float* maskSum,
float* convWorkspace
) const override {
(void)regularOut;
(void)regularScratch;
(void)gpoolOut;
(void)gpoolOut2;
(void)gpoolConcat;
(void)gpoolBias;
(void)maskSum;
const bool applyBNRelu = true;
preBN.apply(applyBNRelu, trunk, trunkScratch, mask);
regularConv.apply(handle, trunkScratch, midIn, convWorkspace, false);
midBN.apply(applyBNRelu, midIn, midScratch, mask);
finalConv.apply(handle, midScratch, trunk, convWorkspace, true);
}
};
struct GlobalPoolingResidualBlock final : public ResidualBlockIntf {
string name;
BatchNormLayer preBN;
ActivationLayer preActivation;
ConvLayer regularConv;
ConvLayer gpoolConv;
BatchNormLayer gpoolBN;
ActivationLayer gpoolActivation;
MatMulLayer gpoolToBiasMul;
BatchNormLayer midBN;
ActivationLayer midActivation;
ConvLayer finalConv;
GlobalPoolingResidualBlock() = delete;
GlobalPoolingResidualBlock(const GlobalPoolingResidualBlock&) = delete;
GlobalPoolingResidualBlock& operator=(const GlobalPoolingResidualBlock&) = delete;
~GlobalPoolingResidualBlock(){}
GlobalPoolingResidualBlock(const GlobalPoolingResidualBlockDesc& desc, int nnX, int nnY)
: name(desc.name),
preBN(desc.preBN),
preActivation(desc.preActivation),
regularConv(desc.regularConv,nnX,nnY),
gpoolConv(desc.gpoolConv,nnX,nnY),
gpoolBN(desc.gpoolBN),
gpoolActivation(desc.gpoolActivation),
gpoolToBiasMul(desc.gpoolToBiasMul),
midBN(desc.midBN),
midActivation(desc.midActivation),
finalConv(desc.finalConv,nnX,nnY) {}
size_t requiredConvWorkspaceElts(size_t maxBatchSize) const {
size_t maxElts = 0;
maxElts = std::max(maxElts,regularConv.requiredConvWorkspaceElts(maxBatchSize));
maxElts = std::max(maxElts,gpoolConv.requiredConvWorkspaceElts(maxBatchSize));
maxElts = std::max(maxElts,finalConv.requiredConvWorkspaceElts(maxBatchSize));
return maxElts;
}
void apply(
ComputeHandleInternal* handle,
TENSORMAP4* trunk,
TENSORMAP4* trunkScratch,
TENSORMAP4* regularOut,
TENSORMAP4* regularScratch,
TENSORMAP4* midIn,
TENSORMAP4* midScratch,
TENSORMAP4* gpoolOut,
TENSORMAP4* gpoolOut2,
TENSORMAP2* gpoolConcat,
TENSORMAP2* gpoolBias,
CONSTTENSORMAP3* mask,
const float* maskSum,
float* convWorkspace
) const override {
(void)midIn;
(void)midScratch;
const bool applyBNRelu = true;
DTENSOR("trunk", trunk);
DTENSOR("mask", mask);
preBN.apply(applyBNRelu, trunk, trunkScratch, mask);
DTENSOR("trunkScratch", trunkScratch);
regularConv.apply(handle, trunkScratch, regularOut, convWorkspace, false);
DTENSOR("regularOut", regularOut);
gpoolConv.apply(handle, trunkScratch, gpoolOut, convWorkspace, false);
DTENSOR("gpoolOut", gpoolOut);
gpoolBN.apply(applyBNRelu, gpoolOut, gpoolOut2, mask);
DTENSOR("gpoolOut2", gpoolOut2);
poolRowsGPool(gpoolOut2, gpoolConcat, maskSum);
gpoolToBiasMul.apply(gpoolConcat, gpoolBias);
addNCBiasInplace(regularOut, gpoolBias);
midBN.apply(applyBNRelu, regularOut, regularScratch, mask);
finalConv.apply(handle, regularScratch, trunk, convWorkspace, true);
DSHAPE("trunk", trunk);
DSHAPE("trunkScratch", trunkScratch);
DSHAPE("regularOut", regularOut);
DSHAPE("gpoolOut", gpoolOut);
DSHAPE("gpoolOut2", gpoolOut2);
DSHAPE("gpoolConcat", gpoolConcat);
DSHAPE("gpoolBias", gpoolBias);
DSHAPE("mask", mask);
}
};
struct Trunk {
string name;
int version;
int numBlocks;
ConvLayer initialConv;
MatMulLayer initialMatMul;
vector<pair<int, ResidualBlockIntf*>> blocks;
BatchNormLayer trunkTipBN;
ActivationLayer trunkTipActivation;
Trunk() = delete;
Trunk(const Trunk&) = delete;
Trunk& operator=(const Trunk&) = delete;
Trunk(const TrunkDesc& desc, int nnX, int nnY)
: name(desc.name),
version(desc.version),
numBlocks(desc.numBlocks),
initialConv(desc.initialConv,nnX,nnY),
initialMatMul(desc.initialMatMul),
trunkTipBN(desc.trunkTipBN),
trunkTipActivation(desc.trunkTipActivation)
{
for (int i = 0; i < numBlocks; ++i) {
if (desc.blocks[i].first == ORDINARY_BLOCK_KIND) {
ResidualBlockDesc* blockDesc = (ResidualBlockDesc*)desc.blocks[i].second;
ResidualBlockIntf* block = new ResidualBlock(*blockDesc,nnX,nnY);
blocks.push_back(make_pair(ORDINARY_BLOCK_KIND, block));
}
else if (desc.blocks[i].first == DILATED_BLOCK_KIND) {
throw StringError("Eigen backend: Dilated residual blocks are not supported right now");
}
else if (desc.blocks[i].first == GLOBAL_POOLING_BLOCK_KIND) {
GlobalPoolingResidualBlockDesc* blockDesc = (GlobalPoolingResidualBlockDesc*)desc.blocks[i].second;
GlobalPoolingResidualBlock* block = new GlobalPoolingResidualBlock(*blockDesc,nnX,nnY);
blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND, block));
}
else {
ASSERT_UNREACHABLE;
}
}
}
virtual ~Trunk() {
for (auto p : blocks) {
delete p.second;
}
}
size_t requiredConvWorkspaceElts(size_t maxBatchSize) const {
size_t maxElts = initialConv.requiredConvWorkspaceElts(maxBatchSize);
for(int i = 0; i<blocks.size(); i++) {
maxElts = std::max(maxElts,blocks[i].second->requiredConvWorkspaceElts(maxBatchSize));
}
return maxElts;
}
void apply(
ComputeHandleInternal* handle,
CONSTTENSORMAP4* input,
CONSTTENSORMAP2* inputGlobal,
TENSORMAP2* inputMatMulOut,
TENSORMAP4* trunk,
TENSORMAP4* trunkScratch,
TENSORMAP4* regularOut,
TENSORMAP4* regularScratch,
TENSORMAP4* midIn,
TENSORMAP4* midScratch,
TENSORMAP4* gpoolOut,
TENSORMAP4* gpoolOut2,
TENSORMAP2* gpoolConcat,
TENSORMAP2* gpoolBias,
CONSTTENSORMAP3* mask,
const float* maskSum,
float* convWorkspace
) const {
initialConv.apply(handle, input, trunkScratch, convWorkspace, false);
initialMatMul.apply(inputGlobal, inputMatMulOut);
addNCBiasInplace(trunkScratch, inputMatMulOut);
// apply blocks
// Flip trunkBuf and trunkScratchBuf so that the result gets accumulated in trunkScratchBuf
for (auto block : blocks) {
block.second->apply(
handle,
trunkScratch,
trunk,
regularOut,
regularScratch,
midIn,
midScratch,
gpoolOut,
gpoolOut2,
gpoolConcat,
gpoolBias,
mask,
maskSum,
convWorkspace
);
}
// And now with the final BN port it from trunkScratchBuf to trunkBuf.
const bool applyBNRelu = true;
trunkTipBN.apply(applyBNRelu, trunkScratch, trunk, mask);
}
};
struct PolicyHead {
string name;
int version;
ConvLayer p1Conv;
ConvLayer g1Conv;
BatchNormLayer g1BN;
ActivationLayer g1Activation;