forked from Tencent/ncnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ncnnoptimize.cpp
3702 lines (3035 loc) · 115 KB
/
ncnnoptimize.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
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <algorithm>
#include <set>
#include <vector>
// ncnn public header
#include "datareader.h"
#include "layer.h"
#include "net.h"
// ncnn private header
#include "layer/batchnorm.h"
#include "layer/bias.h"
#include "layer/binaryop.h"
#include "layer/clip.h"
#include "layer/concat.h"
#include "layer/convolution.h"
#include "layer/convolutiondepthwise.h"
#include "layer/crop.h"
#include "layer/deconvolution.h"
#include "layer/deconvolutiondepthwise.h"
#include "layer/detectionoutput.h"
#include "layer/dropout.h"
#include "layer/eltwise.h"
#include "layer/elu.h"
#include "layer/exp.h"
#include "layer/expanddims.h"
#include "layer/flatten.h"
#include "layer/hardsigmoid.h"
#include "layer/hardswish.h"
#include "layer/innerproduct.h"
#include "layer/input.h"
#include "layer/instancenorm.h"
#include "layer/interp.h"
#include "layer/log.h"
#include "layer/lrn.h"
#include "layer/lstm.h"
#include "layer/memorydata.h"
#include "layer/mvn.h"
#include "layer/normalize.h"
#include "layer/padding.h"
#include "layer/permute.h"
#include "layer/pixelshuffle.h"
#include "layer/pooling.h"
#include "layer/power.h"
#include "layer/prelu.h"
#include "layer/priorbox.h"
#include "layer/proposal.h"
#include "layer/psroipooling.h"
#include "layer/quantize.h"
#include "layer/reduction.h"
#include "layer/relu.h"
#include "layer/reorg.h"
#include "layer/requantize.h"
#include "layer/reshape.h"
#include "layer/roialign.h"
#include "layer/roipooling.h"
#include "layer/scale.h"
#include "layer/shufflechannel.h"
#include "layer/slice.h"
#include "layer/softmax.h"
#include "layer/squeeze.h"
#include "layer/threshold.h"
#include "layer/unaryop.h"
#include "layer/yolodetectionoutput.h"
#include "layer/yolov3detectionoutput.h"
#if defined(__aarch64__) && defined(LINUX)
#include <cassert>
#include <chrono>
#include <limits>
#include <locale>
#include <random>
#define TEXT_GREEN "\033[32m"
#define TEXT_YELLOW "\033[33m"
#define TEXT_RED "\033[31m"
#define CLR "\033[0m"
#endif // defined(__aarch64__) && defined(LINUX)
class DataReaderFromEmpty : public ncnn::DataReader
{
public:
virtual int scan(const char* format, void* p) const
{
return 0;
}
virtual size_t read(void* /*buf*/, size_t size) const
{
return size;
}
};
class NetOptimize : public ncnn::Net
{
public:
// 0=fp32 1=fp16
int storage_type;
public:
int fuse_batchnorm_scale();
int fuse_convolution_batchnorm();
int fuse_convolution_mul();
int fuse_convolution_add();
int fuse_convolutiondepthwise_batchnorm();
int fuse_convolutiondepthwise_mul();
int fuse_convolutiondepthwise_add();
int fuse_deconvolution_batchnorm();
int fuse_deconvolution_mul();
int fuse_deconvolution_add();
int fuse_deconvolutiondepthwise_batchnorm();
int fuse_innerproduct_batchnorm();
int fuse_innerproduct_add();
int fuse_innerproduct_dropout();
int fuse_convolution_activation();
int fuse_convolutiondepthwise_activation();
int fuse_deconvolution_activation();
int fuse_deconvolutiondepthwise_activation();
int fuse_innerproduct_activation();
int fuse_memorydata_binaryop();
int fuse_binaryop_eltwise();
int eliminate_dropout();
int eliminate_pooling1x1();
int eliminate_noop();
int eliminate_orphaned_memorydata();
int eliminate_flatten_after_global_pooling();
int eliminate_reshape_after_global_pooling();
int eliminate_flatten_after_innerproduct();
int eliminate_reshape_before_binaryop();
int replace_convolution_with_innerproduct_after_global_pooling();
int replace_convolution_with_innerproduct_after_innerproduct();
int shape_inference();
public:
int fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp);
int fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp);
int fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp);
int fwrite_weight_data(const ncnn::Mat& data, FILE* bp);
int save(const char* parampath, const char* binpath);
#if defined(__aarch64__) && defined(LINUX)
void gauss_random(ncnn::Mat& m);
void find_fastest_fp32_conv(const char* name, int w, int h, int c);
int support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& mat, const int type);
#endif
};
#if defined(__aarch64__) && defined(LINUX)
void NetOptimize::gauss_random(ncnn::Mat& m)
{
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<float> d(1.0f, 1.0f);
int size = m.total();
for (int i = 0; i < size; ++i)
{
m[i] = d(gen);
}
}
void NetOptimize::find_fastest_fp32_conv(const char* dataname, int w, int h, int c)
{
ncnn::PoolAllocator allocator;
allocator.clear();
ncnn::Option opt;
// embeded system generally use single thread
opt.num_threads = 1;
const size_t layer_count = layers.size();
ncnn::Extractor ex = create_extractor();
ncnn::Mat input(w, h, c);
if (ex.input(dataname, input) < 0)
{
fprintf(stderr, "set input failed, check dataname.\n");
return;
}
const char* IMPL_NAME[6] = {"baseline", "winograd", "pointwise", "im2col", "direct", "conv3x3s2"};
for (int i = 0; i < layer_count; ++i)
{
ncnn::Layer* layer = layers[i];
if (layer->type == "Convolution")
{
ncnn::Convolution* op = (ncnn::Convolution*)layer;
ncnn::Mat bottom_blob;
ncnn::Mat top_blob;
ex.extract(layer->bottoms[0], bottom_blob);
ex.extract(layer->tops[0], top_blob);
if (bottom_blob.empty() || top_blob.empty())
{
continue;
}
ncnn::Mat weight_blob(op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
fprintf(stdout, TEXT_GREEN "Input [w h nc]: %d %d %d\n" CLR, bottom_blob.w, bottom_blob.h, bottom_blob.c);
fprintf(stdout, TEXT_GREEN "Kernel [w h nc]: %d %d %d\n" CLR, op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
fprintf(stdout, TEXT_GREEN "Output [w h nc]: %d %d %d\n" CLR, top_blob.w, top_blob.h, top_blob.c);
// randomize input and kernel
gauss_random(bottom_blob);
// try every implementation
double min_cost = std::numeric_limits<double>::max();
int best_type = 0;
// how much conv implementation type ncnn has ?
for (int type = 1; type <= 5; ++type)
{
int support = support_fp32_conv_type(op, bottom_blob, type);
if (support < 1)
{
// implementation type mismatch convolution configuration, skip
continue;
}
op->impl_type = type;
auto start = std::chrono::high_resolution_clock::now();
const int NREPEATS = 20;
op->create_pipeline(opt);
for (int repeat = 0; repeat < NREPEATS; ++repeat)
{
op->forward(top_blob, bottom_blob, opt);
}
op->destroy_pipeline(opt);
auto stop = std::chrono::high_resolution_clock::now();
double cur_cost = std::chrono::duration<double, std::micro>(stop - start).count() / NREPEATS;
fprintf(stdout, TEXT_GREEN "%s cost %0.3lfms \n" CLR, IMPL_NAME[type], cur_cost / 1000);
if (cur_cost < min_cost)
{
min_cost = cur_cost;
best_type = type;
}
}
op->impl_type = best_type;
fprintf(stdout, TEXT_YELLOW "%d: %s use %s \n\n" CLR, i, layer->name.c_str(), IMPL_NAME[op->impl_type]);
}
}
}
int NetOptimize::support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& bottom, const int type)
{
// not baseline, then k_h == k_w and s_h == s_w
// no dilation conv shall be allowed
if (op->kernel_w != op->kernel_h || op->stride_w != op->stride_h || op->dilation_w != op->dilation_h || op->dilation_h != 1)
{
return -1;
}
// (kernel, stride) in {(1, 1), (1, 2), (2, 1), (3, 1), (3, 2), (4, 4), (5, 1), (5, 2), (7, 1), (7, 2)}
const int support_table[7][4] = {
{1, 1, 0, 0},
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 0, 0, 1},
{1, 1, 0, 0},
{0, 0, 0, 0},
{1, 1, 0, 0}
};
// kernel_size x stride
const int kernel = op->kernel_h,
stride = op->stride_h;
// if match prequisation
switch (type)
{
case 1:
// winograd
if (kernel != 3 || stride != 1)
{
return -1;
}
break;
case 2:
// pointwise
// input_h == 1, input_w == 1, dilation == 1, stride == 1
if (bottom.h != 1 || bottom.w != 1 || stride != 1)
{
return -1;
}
break;
case 3:
// im2col
break;
case 4:
// direct conv
if (support_table[kernel - 1][stride - 1] == 0)
{
return -1;
}
break;
case 5:
// conv3x3s2
// kernel == 3 and stride == 2
if (kernel != 3 || stride != 2)
{
return -1;
}
break;
default:
fprintf(stderr, TEXT_RED "unrecognize convolution impl type: %d" CLR, type);
break;
}
return 1;
}
#endif // defined(__aarch64__) && defined(LINUX)
int NetOptimize::fuse_batchnorm_scale()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "BatchNorm")
continue;
// BatchNorm - Scale
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "Scale")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse BatchNorm - Scale to BatchNorm
ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
ncnn::Scale* scale = (ncnn::Scale*)layers[j];
fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
{
// v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
// = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
int channels = batchnorm->channels;
float* slope = batchnorm->slope_data;
float* bias = batchnorm->bias_data;
for (int q = 0; q < channels; q++)
{
slope[q] = slope[q] * scale->scale_data[q];
if (scale->bias_term)
bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
else
bias[q] = bias[q] * scale->scale_data[q];
}
}
int top_blob_index_final = scale->tops[0];
batchnorm->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
scale->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolution_batchnorm()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Convolution")
continue;
// Convolution - BatchNorm
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BatchNorm")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse Convolution - BatchNorm to Convolution
ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
{
int channels = batchnorm->channels;
float eps = batchnorm->eps;
// a = bias - slope * mean / sqrt(var + eps)
// b = slope / sqrt(var + eps)
// value = value * b + a
std::vector<float> a(channels);
std::vector<float> b(channels);
for (int i = 0; i < channels; i++)
{
float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
b[i] = batchnorm->slope_data[i] / sqrt_var;
}
if (convolution->bias_term == 0)
{
// init bias as zero
convolution->bias_term = 1;
convolution->bias_data = ncnn::Mat(channels);
convolution->bias_data.fill(0.f);
}
const int weight_per_outch = convolution->weight_data_size / channels;
float* weight = convolution->weight_data;
float* bias = convolution->bias_data;
for (int i = 0; i < channels; i++)
{
float* conv_weight_outch = weight + weight_per_outch * i;
for (int j = 0; j < weight_per_outch; j++)
{
conv_weight_outch[j] *= b[i];
}
bias[i] = bias[i] * b[i] + a[i];
}
}
int top_blob_index_final = batchnorm->tops[0];
convolution->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
batchnorm->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolution_mul()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Convolution")
continue;
// Convolution - BinaryOp
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BinaryOp")
continue;
if (layers[j]->bottoms.size() != 2)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse Convolution - BinaryOp to Convolution
ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
if (binaryop->op_type != 2 || binaryop->with_scalar)
continue;
// MemoryData - ..... - BinaryOp
int k = 0;
for (; k < j; k++)
{
if (layers[k]->type != "MemoryData")
continue;
if (layers[k]->tops[0] == binaryop->bottoms[1])
break;
}
if (k == j)
continue;
ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
int channels = convolution->num_output;
if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
{
// not bias-like broadcasting type
continue;
}
fprintf(stderr, "fuse_convolution_mul %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
{
const int weight_per_outch = convolution->weight_data_size / channels;
float* weight = convolution->weight_data;
float* bias = convolution->bias_data;
for (int i = 0; i < channels; i++)
{
float* conv_weight_outch = weight + weight_per_outch * i;
for (int j = 0; j < weight_per_outch; j++)
{
conv_weight_outch[j] *= memorydata->data[i];
}
if (bias)
{
bias[i] = bias[i] * memorydata->data[i];
}
}
}
int top_blob_index_final = binaryop->tops[0];
convolution->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
binaryop->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolution_add()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Convolution")
continue;
// Convolution - BinaryOp
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BinaryOp")
continue;
if (layers[j]->bottoms.size() != 2)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse Convolution - BinaryOp to Convolution
ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
if (binaryop->op_type != 0 || binaryop->with_scalar)
continue;
// MemoryData - ..... - BinaryOp
int k = 0;
for (; k < j; k++)
{
if (layers[k]->type != "MemoryData")
continue;
if (layers[k]->tops[0] == binaryop->bottoms[1])
break;
}
if (k == j)
continue;
ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
int channels = convolution->num_output;
if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
{
// not bias-like broadcasting type
continue;
}
fprintf(stderr, "fuse_convolution_add %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
{
if (convolution->bias_term == 0)
{
// init bias
convolution->bias_term = 1;
convolution->bias_data = memorydata->data;
}
else
{
float* bias = convolution->bias_data;
for (int i = 0; i < channels; i++)
{
bias[i] = bias[i] + memorydata->data[i];
}
}
}
int top_blob_index_final = binaryop->tops[0];
convolution->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
binaryop->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolutiondepthwise_batchnorm()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "ConvolutionDepthWise")
continue;
// ConvolutionDepthWise - BatchNorm
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BatchNorm")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
{
int channels = batchnorm->channels;
float eps = batchnorm->eps;
// a = bias - slope * mean / sqrt(var + eps)
// b = slope / sqrt(var + eps)
// value = value * b + a
std::vector<float> a(channels);
std::vector<float> b(channels);
for (int i = 0; i < channels; i++)
{
float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
b[i] = batchnorm->slope_data[i] / sqrt_var;
}
if (convolutiondepthwise->bias_term == 0)
{
// init bias as zero
convolutiondepthwise->bias_term = 1;
convolutiondepthwise->bias_data = ncnn::Mat(channels);
convolutiondepthwise->bias_data.fill(0.f);
}
const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
float* weight = convolutiondepthwise->weight_data;
float* bias = convolutiondepthwise->bias_data;
for (int i = 0; i < channels; i++)
{
float* conv_weight_outch = weight + weight_per_outch * i;
for (int j = 0; j < weight_per_outch; j++)
{
conv_weight_outch[j] *= b[i];
}
bias[i] = bias[i] * b[i] + a[i];
}
}
int top_blob_index_final = batchnorm->tops[0];
convolutiondepthwise->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
batchnorm->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolutiondepthwise_mul()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "ConvolutionDepthWise")
continue;
// ConvolutionDepthWise - BinaryOp
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BinaryOp")
continue;
if (layers[j]->bottoms.size() != 2)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
if (binaryop->op_type != 2 || binaryop->with_scalar)
continue;
// MemoryData - ..... - BinaryOp
int k = 0;
for (; k < j; k++)
{
if (layers[k]->type != "MemoryData")
continue;
if (layers[k]->tops[0] == binaryop->bottoms[1])
break;
}
if (k == j)
continue;
ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
int channels = convolutiondepthwise->num_output;
if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
{
// not bias-like broadcasting type
continue;
}
fprintf(stderr, "fuse_convolutiondepthwise_mul %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
{
const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
float* weight = convolutiondepthwise->weight_data;
float* bias = convolutiondepthwise->bias_data;
for (int i = 0; i < channels; i++)
{
float* conv_weight_outch = weight + weight_per_outch * i;
for (int j = 0; j < weight_per_outch; j++)
{
conv_weight_outch[j] *= memorydata->data[i];
}
if (bias)
{
bias[i] = bias[i] * memorydata->data[i];
}
}
}
int top_blob_index_final = binaryop->tops[0];
convolutiondepthwise->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
binaryop->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_convolutiondepthwise_add()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "ConvolutionDepthWise")
continue;
// ConvolutionDepthWise - BinaryOp
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BinaryOp")
continue;
if (layers[j]->bottoms.size() != 2)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
if (binaryop->op_type != 0 || binaryop->with_scalar)
continue;
// MemoryData - ..... - BinaryOp
int k = 0;
for (; k < j; k++)
{
if (layers[k]->type != "MemoryData")
continue;
if (layers[k]->tops[0] == binaryop->bottoms[1])
break;
}
if (k == j)
continue;
ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
int channels = convolutiondepthwise->num_output;
if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
{
// not bias-like broadcasting type
continue;
}
fprintf(stderr, "fuse_convolutiondepthwise_add %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
{
if (convolutiondepthwise->bias_term == 0)
{
// init bias
convolutiondepthwise->bias_term = 1;
convolutiondepthwise->bias_data = memorydata->data;
}
else
{
float* bias = convolutiondepthwise->bias_data;
for (int i = 0; i < channels; i++)
{
bias[i] = bias[i] + memorydata->data[i];
}
}
}
int top_blob_index_final = binaryop->tops[0];
convolutiondepthwise->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
binaryop->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_deconvolution_batchnorm()
{
const size_t layer_count = layers.size();
for (int i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Deconvolution")
continue;
// Deconvolution - BatchNorm
int top_blob_index = layers[i]->tops[0];
int j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "BatchNorm")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse Deconvolution - BatchNorm to Deconvolution
ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
{
int channels = batchnorm->channels;
float eps = batchnorm->eps;
// a = bias - slope * mean / sqrt(var + eps)
// b = slope / sqrt(var + eps)
// value = value * b + a
std::vector<float> a(channels);
std::vector<float> b(channels);
for (int i = 0; i < channels; i++)
{
float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
b[i] = batchnorm->slope_data[i] / sqrt_var;
}
if (deconvolution->bias_term == 0)
{
// init bias as zero
deconvolution->bias_term = 1;
deconvolution->bias_data = ncnn::Mat(channels);
deconvolution->bias_data.fill(0.f);
}
const int weight_per_outch = deconvolution->weight_data_size / channels;
float* weight = deconvolution->weight_data;
float* bias = deconvolution->bias_data;
for (int i = 0; i < channels; i++)
{
float* conv_weight_outch = weight + weight_per_outch * i;
for (int j = 0; j < weight_per_outch; j++)
{
conv_weight_outch[j] *= b[i];
}
bias[i] = bias[i] * b[i] + a[i];
}
}
int top_blob_index_final = batchnorm->tops[0];
deconvolution->tops[0] = top_blob_index_final;
blobs[top_blob_index_final].producer = i;
batchnorm->type = "ncnnfused";
}
return 0;
}
int NetOptimize::fuse_deconvolution_mul()
{