forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_norm_kernel.cpp
1417 lines (1284 loc) · 60 KB
/
batch_norm_kernel.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
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <ATen/native/batch_norm.h>
#include <ATen/core/Tensor.h>
#include <ATen/AccumulateType.h>
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/cpu/Loops.h>
#include <ATen/native/cpu/utils.h>
#include <ATen/native/cpu/mixed_data_type.h>
#include <ATen/cpu/vec/functional.h>
#include <ATen/cpu/vec/vec.h>
#include <c10/util/irange.h>
#include <ATen/OpMathType.h>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#else
#include <ATen/ops/empty.h>
#include <ATen/ops/ones.h>
#include <ATen/ops/zeros.h>
#endif
namespace at::native {
namespace {
using namespace vec;
template<typename param_t, typename opmath_t>
void batch_norm_cpu_collect_linear_and_constant_terms(
opmath_t* alpha, opmath_t* beta, int64_t n_channel,
const Tensor& weight /* optional */, const Tensor& bias /* optional */,
const Tensor& save_mean, const Tensor& save_invstd,
const Tensor& running_mean, const Tensor& running_var, bool train, double eps) {
const param_t* weight_data = weight.defined() ? weight.data_ptr<param_t>() : nullptr;
const param_t* bias_data = bias.defined() ? bias.data_ptr<param_t>() : nullptr;
auto save_mean_a = conditional_accessor_1d<param_t>(save_mean);
auto save_invstd_a = conditional_accessor_1d<param_t>(save_invstd);
auto running_mean_a = conditional_accessor_1d<param_t>(running_mean);
auto running_var_a = conditional_accessor_1d<param_t>(running_var);
/// Collect the linear and constant terms regarding the input.
/// output(n, c, h, w)
/// = (input(n, c, h, w) - mean(c)) / sqrt(var(c) + eps) * weight(c)
/// + bias(c)
/// = input(n, c, h, w) * inv_var(c) * weight(c)
/// - mean(c) * inv_var(c) * weight(c) + bias(c),
/// where inv_var(c) = 1 / sqrt(var(c) + eps).
/// So the linear term, alpha(c) = inv_var(c) * weight(c),
/// the constant term beta(c) = bias(c) - mean(c) * inv_var(c) * weight(c)
/// Note that this is only a good idea if (input_size >> c), in degenerate
/// cases where image_size == 1 && batch_size == 1, it is slow.
for (const auto c : c10::irange(n_channel)) {
opmath_t mean, invstd;
if (train) {
mean = save_mean_a[c];
invstd = save_invstd_a[c];
} else {
mean = running_mean_a[c];
invstd = 1 / std::sqrt(running_var_a[c] + static_cast<opmath_t>(eps));
}
param_t weight_v = weight_data ? weight_data[c] : param_t(1);
param_t bias_v = bias_data ? bias_data[c] : param_t(0);
alpha[c] = invstd * weight_v;
beta[c] = bias_v - mean * alpha[c];
}
}
/// A fast path for CPU inference and training forward when all tensors are contiguous.
template<typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_contiguous_impl(Tensor& output, const Tensor& input,
const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd,
const Tensor& running_mean, const Tensor& running_var, bool train, double eps) {
using Vec = Vectorized<scalar_t>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
Tensor alpha = at::empty({n_channel}, input.options());
Tensor beta = at::empty({n_channel}, input.options());
scalar_t* alpha_data = alpha.mutable_data_ptr<scalar_t>();
scalar_t* beta_data = beta.data_ptr<scalar_t>();
batch_norm_cpu_collect_linear_and_constant_terms<scalar_t, scalar_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
scalar_t* output_data = output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
// Apply the linear terms to the input,
// output(n, c, h, w) = input(n, c, h, w) * alpha(c) + beta(c)
const int64_t loop_size = image_size - (image_size % Vec::size());
at::parallel_for(0, n_batch * n_channel, 1, [&](int64_t begin, int64_t end) {
int64_t n = 0;
int64_t c = 0;
data_index_init(begin, n, n_batch, c, n_channel);
for (const auto i : c10::irange(begin, end)) {
const Vec alpha_vec(alpha_data[c]);
const Vec beta_vec(beta_data[c]);
int64_t offset = i * image_size;
int64_t d = 0;
for (; d < loop_size; d += Vec::size()) {
Vec data_vec = Vec::loadu(input_data + offset + d);
Vec output_vec = data_vec * alpha_vec + beta_vec;
output_vec.store(output_data + offset + d);
}
if (image_size - d > 0) {
Vec data_vec = Vec::loadu(input_data + offset + d, image_size - d);
Vec output_vec = data_vec * alpha_vec + beta_vec;
output_vec.store(output_data + offset + d, image_size - d);
}
// move on to next index
data_index_step(n, n_batch, c, n_channel);
}
});
}
template <typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_channels_last_impl(Tensor& output, const Tensor& input,
const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd,
const Tensor& running_mean, const Tensor& running_var, bool train, double eps) {
using Vec = Vectorized<scalar_t>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
Tensor alpha = at::empty({n_channel}, input.options());
Tensor beta = at::empty({n_channel}, input.options());
scalar_t* alpha_data = alpha.mutable_data_ptr<scalar_t>();
scalar_t* beta_data = beta.data_ptr<scalar_t>();
batch_norm_cpu_collect_linear_and_constant_terms<scalar_t, scalar_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
scalar_t* output_data = output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
// Apply the linear terms to the input,
// output(n, c, h, w) = input(n, c, h, w) * alpha(c) + beta(c)
const int64_t loop_size = n_channel - (n_channel % Vec::size());
at::parallel_for(0, n_batch * image_size, 1, [&](int64_t begin, int64_t end) {
for (const auto i : c10::irange(begin, end)) {
int64_t offset = i * n_channel;
int64_t d = 0;
// vectorize on channel dimension, for normal batch_norm input size,
// alpha/beta should fit in L1 cache, otherwise consider blocking.
for (; d < loop_size; d += Vec::size()) {
Vec alpha_vec = Vec::loadu(alpha_data + d);
Vec beta_vec = Vec::loadu(beta_data + d);
Vec data_vec = Vec::loadu(input_data + offset + d);
Vec output_vec = data_vec * alpha_vec + beta_vec;
output_vec.store(output_data + offset + d);
}
if (n_channel - d > 0) {
Vec alpha_vec = Vec::loadu(alpha_data + d, n_channel - d);
Vec beta_vec = Vec::loadu(beta_data + d, n_channel - d);
Vec data_vec = Vec::loadu(input_data + offset + d, n_channel - d);
Vec output_vec = data_vec * alpha_vec + beta_vec;
output_vec.store(output_data + offset + d, n_channel - d);
}
}
});
}
template <typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_collect_stats_contiguous_impl(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
// keep acc_type as opmath_type will use float type when scalar_t==float
// while acc_type uses double for float.
using accscalar_t = at::acc_type<scalar_t, false>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
int64_t N = input.numel() / n_channel;
const scalar_t* input_data = input.data_ptr<scalar_t>();
scalar_t* mean_data = mean.data_ptr<scalar_t>();
scalar_t* var_sum_data = var_sum.data_ptr<scalar_t>();
// parallel dim reduce on 'channel'
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
// compute mean per input
accscalar_t sum = 0;
for (const auto n : c10::irange(n_batch)) {
for (const auto i : c10::irange(image_size)) {
auto offset = n * n_channel * image_size + c * image_size + i;
sum += input_data[offset];
}
}
scalar_t mean = sum / N;
mean_data[c] = mean;
// compute variance per input
accscalar_t _var_sum = 0;
for (const auto n : c10::irange(n_batch)) {
for (const auto i : c10::irange(image_size)) {
auto offset = n * n_channel * image_size + c * image_size + i;
auto x = input_data[offset];
_var_sum += (x - mean) * (x - mean);
}
}
var_sum_data[c] = _var_sum;
}
});
}
template <typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_collect_stats_channels_last_impl(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
using Vec = Vectorized<scalar_t>;
// keep acc_type as opmath_type will use float type when scalar_t==float
// while acc_type uses double for float.
using accscalar_t = at::acc_type<scalar_t, false>;
int64_t n_channel = input.size(1);
int64_t N = input.numel() / n_channel;
const scalar_t* input_data = input.data_ptr<scalar_t>();
scalar_t* mean_data = mean.data_ptr<scalar_t>();
scalar_t* var_sum_data = var_sum.data_ptr<scalar_t>();
// Typical vertical reduce from shape of {NHW, C} to {C}.
// Apply two path parallel reduction when NHW > max_threads:
// First path: allocate an immediate buffer of size {max_threads, C}, parallel along dim0,
// {NHW, C} => {max_threads, C}
//
// Second path: parallel along dim1 of the immediate buffer,
// {max_threads, C} => {C}
//
// Normal size of C should fit in L1, otherwise consider blocking on C.
//
int num_threads = at::get_num_threads();
if (N > num_threads) {
Tensor buffer = at::zeros({num_threads, n_channel}, input.options());
scalar_t* buffer_data = buffer.data_ptr<scalar_t>();
// compute mean per input
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
int tid = at::get_thread_num();
TORCH_CHECK(tid < num_threads,
"expect thread id smaller than ", num_threads, ", got thread id ", tid);
scalar_t* buffer_ptr = buffer_data + tid * n_channel;
for (const auto i : c10::irange(begin, end)) {
const scalar_t* x_ptr = input_data + i * n_channel;
vec::map2<scalar_t>(
[](Vec x, Vec y) { return x + y; },
buffer_ptr,
x_ptr,
buffer_ptr,
n_channel);
}
});
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
accscalar_t sum = 0;
for (const auto t : c10::irange(num_threads)) {
sum += buffer_data[t * n_channel + c];
}
scalar_t mean = sum / N;
mean_data[c] = mean;
}
});
// compute variance per input, reuse the immediate buffer
buffer.zero_();
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
int tid = at::get_thread_num();
TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid);
scalar_t* buffer_ptr = buffer_data + tid * n_channel;
for (const auto i : c10::irange(begin, end)) {
const scalar_t* x_ptr = input_data + i * n_channel;
vec::map3<scalar_t>(
[](Vec x, Vec y, Vec mean) { return y + (x - mean) * (x - mean); },
buffer_ptr,
x_ptr,
buffer_ptr,
mean_data,
n_channel);
}
});
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
accscalar_t _var_sum = 0;
for (const auto t : c10::irange(num_threads)) {
_var_sum += buffer_data[t * n_channel + c];
}
var_sum_data[c] = _var_sum;
}
});
} else {
// Vertical reduce from shape of {NHW, C} to {C} when NHW <= max_threads.
// We'll use two methods, Method 1 and Method 2.
//
// Method 1: when TILE_SIZE < C <= THRESHOLD, parallel on C
// {NHW, C} => {C}
//
// Method 2: when C <= TILE_SIZE or C > THRESHOLD, tile and vectorize on C, C is tiled as:
// C: {TILE_SIZE, TILE_SIZE, ..., Remainder}
// parallel on tiles, vectorized vertical reduce on each tile
// {NHW, TILE_SIZE} => {TILE_SIZE}
//
// The optimal THRESHOLD to tile was found empirically.
// When C > THRESHOLD, C is large enough that the benefit from tiling and vectorization outweigh the synchronization overhead.
// Wehn C <= TILE_SIZE, the problem size is small enough (C <= TILE_SIZE && NHW <= max_threads) that it's better to launch single thread with vectorization than C threads without vectorization.
//
// When num_threads == 1, always use Method 2 as there is no synchronization overhead.
//
int64_t TILE_SIZE = 16;
int64_t THRESHOLD = 2048;
// Method 2: parallel on tiles of C, vectorized vertical reduce on each tile
if (num_threads == 1 || (n_channel <= TILE_SIZE || n_channel > THRESHOLD)) {
// compute mean per input
mean.zero_();
at::parallel_for(0, (n_channel + TILE_SIZE - 1) / TILE_SIZE, 1, [&](int64_t tile_idx_begin, int64_t tile_idx_end) {
for (int64_t tile_idx = tile_idx_begin; tile_idx < tile_idx_end; tile_idx++) {
int64_t jj_begin = tile_idx * TILE_SIZE;
int64_t jj_end = std::min(jj_begin + TILE_SIZE, n_channel);
scalar_t* mean_ptr = mean_data + jj_begin;
for (const auto i : c10::irange(N)) {
const scalar_t* x_ptr = input_data + (i * n_channel + jj_begin);
vec::map2<scalar_t>(
[](Vec x, Vec y) { return x + y; },
mean_ptr,
x_ptr,
mean_ptr,
jj_end - jj_begin);
}
vec::map<scalar_t>(
[N](Vec x) { return x / Vec(N); },
mean_ptr,
mean_ptr,
jj_end - jj_begin);
}
});
// compute variance per input
var_sum.zero_();
at::parallel_for(0, (n_channel + TILE_SIZE - 1) / TILE_SIZE, 1, [&](int64_t tile_idx_begin, int64_t tile_idx_end) {
for (int64_t tile_idx = tile_idx_begin; tile_idx < tile_idx_end; tile_idx++) {
int64_t jj_begin = tile_idx * TILE_SIZE;
int64_t jj_end = std::min(jj_begin + TILE_SIZE, n_channel);
scalar_t* var_sum_ptr = var_sum_data + jj_begin;
scalar_t* mean_ptr = mean_data + jj_begin;
for (const auto i : c10::irange(N)) {
const scalar_t* x_ptr = input_data + (i * n_channel + jj_begin);
vec::map3<scalar_t>(
[](Vec x, Vec y, Vec mean) { return y + (x - mean) * (x - mean); },
var_sum_ptr,
x_ptr,
var_sum_ptr,
mean_ptr,
jj_end - jj_begin);
}
}
});
}
// Method 1: parallel on C, vertical reduce
else {
// compute mean per input
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
accscalar_t sum = 0;
for (const auto t : c10::irange(N)) {
sum += input_data[t * n_channel + c];
}
scalar_t mean = sum / N;
mean_data[c] = mean;
}
});
// compute variance per input
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
accscalar_t _var_sum = 0;
for (const auto t : c10::irange(N)) {
_var_sum += (input_data[t * n_channel + c] - mean_data[c]) * (input_data[t * n_channel + c] - mean_data[c]);
}
var_sum_data[c] = _var_sum;
}
});
}
}
}
template <typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_backward_contiguous_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias,
const Tensor& grad_output, const Tensor& input, const Tensor& weight,
const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd,
bool train, double eps) {
using Vec = Vectorized<scalar_t>;
// keep acc_type as opmath_type will use float type when scalar_t==float
// while acc_type uses double for float.
using accscalar_t = at::acc_type<scalar_t, false>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
int64_t N = input.numel() / n_channel;
const scalar_t* grad_output_data = grad_output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr<scalar_t>() : nullptr;
scalar_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr<scalar_t>() : nullptr;
scalar_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr<scalar_t>() : nullptr;
const bool grad_input_null = grad_input_data == nullptr;
const bool grad_weight_null = grad_weight_data == nullptr;
const bool grad_bias_null = grad_bias_data == nullptr;
auto weight_a = conditional_accessor_1d<scalar_t>(weight);
auto save_mean_a = conditional_accessor_1d<scalar_t>(save_mean);
auto save_invstd_a = conditional_accessor_1d<scalar_t>(save_invstd);
auto running_mean_a = conditional_accessor_1d<scalar_t>(running_mean);
auto running_var_a = conditional_accessor_1d<scalar_t>(running_var);
// parallel dim reduce on 'channel'
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
scalar_t w = weight.defined() ? weight_a[c] : 1;
scalar_t mean, invstd;
if (train) {
mean = save_mean_a[c];
invstd = save_invstd_a[c];
} else {
mean = running_mean_a[c];
invstd = 1 / std::sqrt(running_var_a[c] + eps);
}
// reduce over grad_output in feature plane
// compute 1) sum; 2) dot product of Q(X) and dY.
// fuse into a single loop to reuse dY
//
accscalar_t sum = 0;
accscalar_t dotp = 0;
for (const auto n : c10::irange(n_batch)) {
const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size;
const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size;
sum += vec::reduce_all<scalar_t>(
[](Vec& x, Vec& y) { return x + y; },
dy_ptr,
image_size);
dotp += vec::map2_reduce_all<scalar_t>(
[mean](Vec x, Vec dy) { return (x - Vec(mean)) * dy; },
[](Vec x, Vec y) { return x + y; },
x_ptr,
dy_ptr,
image_size);
}
if (!grad_input_null) {
if (train) {
scalar_t k = (scalar_t) dotp * invstd * invstd / N;
scalar_t grad_mean = sum / N;
for (const auto n : c10::irange(n_batch)) {
const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size;
scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size;
const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size;
// Scalar math:
// for (const auto j : c10::irange(image_size)) {
// scalar_t dx = (x_ptr[j] - mean) * k;
// dx_ptr[j] = (dy_ptr[j] - grad_mean - dx) * invstd * w;
// }
vec::map2<scalar_t>(
[=](Vec x, Vec dy) {
Vec dx = (x - Vec(mean)) * Vec(k);
return (dy - Vec(grad_mean) - dx) * Vec(invstd) * Vec(w);
},
dx_ptr,
x_ptr,
dy_ptr,
image_size);
}
} else { // evaluation mode
for (const auto n : c10::irange(n_batch)) {
scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size;
const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size;
// Scalar math:
// for (const auto j : c10::irange(image_size)) {
// dx_ptr[j] = dy_ptr[j] * invstd * w;
// }
vec::map<scalar_t>(
[=](Vec dy) { return dy * Vec(invstd) * Vec(w); },
dx_ptr,
dy_ptr,
image_size);
}
}
}
if (!grad_weight_null) {
grad_weight_data[c] = dotp * invstd;
}
if (!grad_bias_null) {
grad_bias_data[c] = sum;
}
}
});
}
template <typename scalar_t>
typename std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_backward_channels_last_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias,
const Tensor& grad_output, const Tensor& input, const Tensor& weight,
const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd,
bool train, double eps) {
using Vec = Vectorized<scalar_t>;
// keep acc_type as opmath_type will use float type when scalar_t==float
// while acc_type uses double for float.
using accscalar_t = at::acc_type<scalar_t, false>;
int64_t n_channel = input.size(1);
int64_t N = input.numel() / n_channel;
const scalar_t* grad_output_data = grad_output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr<scalar_t>() : nullptr;
scalar_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr<scalar_t>() : nullptr;
scalar_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr<scalar_t>() : nullptr;
scalar_t* save_mean_data = conditional_data_ptr<scalar_t>(save_mean);
scalar_t* save_invstd_data = conditional_data_ptr<scalar_t>(save_invstd);
scalar_t* running_mean_data = conditional_data_ptr<scalar_t>(running_mean);
scalar_t* running_var_data = conditional_data_ptr<scalar_t>(running_var);
Tensor weight_ = weight.defined() ? weight : at::ones({n_channel}, input.options());
const scalar_t* weight_data = weight_.data_ptr<scalar_t>();
scalar_t* mean_ptr = nullptr;
scalar_t* invstd_ptr = nullptr;
Tensor invstd = at::empty({0}, input.options());
if (train) {
mean_ptr = save_mean_data;
invstd_ptr = save_invstd_data;
} else {
mean_ptr = running_mean_data;
invstd.resize_({n_channel});
invstd_ptr = invstd.data_ptr<scalar_t>();
for (const auto c : c10::irange(n_channel)) {
invstd_ptr[c] = 1 / std::sqrt(running_var_data[c] + eps);
}
}
// Typical vertical reduce from shape of {NHW, C} to {C}.
// Apply two path parallel reduction:
// First path: allocate an immediate buffer of size {2, max_threads, C}, parallel along dim0,
// sum = buffer[0], dotp = buffer[2]
//
// Second path: parallel along dim1 of the immediate buffer.
//
int num_threads = at::get_num_threads();
Tensor buffer = at::zeros({2, num_threads, n_channel}, input.options());
scalar_t* sum_data = buffer.data_ptr<scalar_t>();
scalar_t* dotp_data = sum_data + num_threads * n_channel;
// compute sum and dotp per feature plain,
// fuse into a single loop to reuse grad_output in L1.
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
int tid = at::get_thread_num();
TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid);
scalar_t* sum_ptr = sum_data + tid * n_channel;
scalar_t* dotp_ptr = dotp_data + tid * n_channel;
for (const auto i : c10::irange(begin, end)) {
const scalar_t* x_ptr = input_data + i * n_channel;
const scalar_t* dy_ptr = grad_output_data + i * n_channel;
vec::map2<scalar_t>(
[](Vec sum, Vec dy) { return sum + dy; },
sum_ptr,
sum_ptr,
dy_ptr,
n_channel);
vec::map4<scalar_t>(
[](Vec dotp, Vec x, Vec mean, Vec dy) { return dotp + (x - mean) * dy; },
dotp_ptr,
dotp_ptr,
x_ptr,
mean_ptr,
dy_ptr,
n_channel);
}
});
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
// store the final result of sum and dotp in the 1st lane of immediate buffer,
// so that we won't need to allocate anther buffer to store the temp values.
accscalar_t _sum = 0;
for (const auto t : c10::irange(num_threads)) {
_sum += sum_data[t * n_channel + c];
}
sum_data[/* 0 * n_channel + */c] = _sum;
accscalar_t _dotp = 0;
for (const auto t : c10::irange(num_threads)) {
_dotp += dotp_data[t * n_channel + c];
}
dotp_data[/* 0 * n_channel + */c] = _dotp;
}
});
// compute grad_input
const int64_t loop_size = n_channel - (n_channel % Vec::size());
if (grad_input.defined()) {
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
for (const auto i : c10::irange(begin, end)) {
scalar_t* dx_ptr = grad_input_data + i * n_channel;
const scalar_t* x_ptr = input_data + i * n_channel;
const scalar_t* dy_ptr = grad_output_data + i * n_channel;
if (train) {
int64_t d = 0;
for (; d < loop_size; d += Vec::size()) {
Vec x = Vec::loadu(x_ptr + d);
Vec mean = Vec::loadu(mean_ptr + d);
Vec dotp = Vec::loadu(dotp_data + d);
Vec invstd = Vec::loadu(invstd_ptr + d);
Vec k = dotp * invstd * invstd / Vec(N);
Vec dx = (x - mean) * k;
Vec dy = Vec::loadu(dy_ptr + d);
Vec grad_mean = Vec::loadu(sum_data + d) / Vec(N);
Vec w = Vec::loadu(weight_data + d);
dx = (dy - grad_mean - dx) * invstd * w;
dx.store(dx_ptr + d);
}
if (n_channel - d > 0) {
Vec x = Vec::loadu(x_ptr + d, n_channel - d);
Vec mean = Vec::loadu(mean_ptr + d, n_channel - d);
Vec dotp = Vec::loadu(dotp_data + d, n_channel - d);
Vec invstd = Vec::loadu(invstd_ptr + d, n_channel - d);
Vec k = dotp * invstd * invstd / Vec(N);
Vec dx = (x - mean) * k;
Vec dy = Vec::loadu(dy_ptr + d, n_channel - d);
Vec grad_mean = Vec::loadu(sum_data + d, n_channel - d) / Vec(N);
Vec w = Vec::loadu(weight_data + d, n_channel - d);
dx = (dy - grad_mean - dx) * invstd * w;
dx.store(dx_ptr + d, n_channel - d);
}
} else { // evaluation mode
int64_t d = 0;
for (; d < loop_size; d += Vec::size()) {
Vec dy = Vec::loadu(dy_ptr + d);
Vec invstd = Vec::loadu(invstd_ptr + d);
Vec w = Vec::loadu(weight_data + d);
Vec dx = dy * invstd * w;
dx.store(dx_ptr + d);
}
if (n_channel - d > 0) {
Vec dy = Vec::loadu(dy_ptr + d, n_channel - d);
Vec invstd = Vec::loadu(invstd_ptr + d, n_channel - d);
Vec w = Vec::loadu(weight_data + d, n_channel - d);
Vec dx = dy * invstd * w;
dx.store(dx_ptr + d, n_channel - d);
}
}
}
});
}
if (grad_weight.defined()) {
// grad_weight = dotp * invstd
vec::map2<scalar_t>(
[](Vec dotp, Vec invstd) { return dotp * invstd; },
grad_weight_data,
dotp_data,
invstd_ptr,
n_channel);
}
// grad_bias = sum
if (grad_bias.defined()) {
vec::map<scalar_t>(
[](Vec sum) { return sum; },
grad_bias_data,
sum_data,
n_channel);
}
}
/// bfloat16/Half kernels
template<typename scalar_t>
typename std::enable_if_t<!std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_contiguous_impl(Tensor& output, const Tensor& input,
const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd,
const Tensor& running_mean, const Tensor& running_var, bool train, double eps) {
using opmath_t = at::opmath_type<scalar_t>;
using bVec = Vectorized<scalar_t>;
using fVec = Vectorized<opmath_t>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
// use float as acc type
Tensor alpha = at::empty({n_channel}, input.options().dtype(kFloat));
Tensor beta = at::empty({n_channel}, input.options().dtype(kFloat));
opmath_t* alpha_data = alpha.mutable_data_ptr<opmath_t>();
opmath_t* beta_data = beta.data_ptr<opmath_t>();
const bool mixed_type = is_mixed_type(input, weight, bias, save_mean, save_invstd, running_mean, running_var);
if (mixed_type) {
batch_norm_cpu_collect_linear_and_constant_terms<opmath_t, opmath_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
} else {
batch_norm_cpu_collect_linear_and_constant_terms<scalar_t, opmath_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
}
scalar_t* output_data = output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
const int64_t loop_size = image_size - (image_size % bVec::size());
at::parallel_for(0, n_batch * n_channel, 1, [&](int64_t begin, int64_t end) {
int64_t n = 0;
int64_t c = 0;
data_index_init(begin, n, n_batch, c, n_channel);
for (const auto i : c10::irange(begin, end)) {
const scalar_t* input_ptr = input_data + i * image_size;
scalar_t* output_ptr = output_data + i * image_size;
const opmath_t alpha_val = alpha_data[c];
const opmath_t beta_val = beta_data[c];
const fVec alpha_fvec(alpha_val);
const fVec beta_fvec(beta_val);
int64_t d = 0;
for (; d < loop_size; d += bVec::size()) {
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
fVec out_fvec0 = data_fvec0 * alpha_fvec + beta_fvec;
fVec out_fvec1 = data_fvec1 * alpha_fvec + beta_fvec;
bVec out_bvec = convert_from_float<scalar_t>(out_fvec0, out_fvec1);
out_bvec.store(output_ptr + d);
}
for (; d < image_size; d++) {
output_ptr[d] = scalar_t(opmath_t(input_ptr[d]) * alpha_val + beta_val);
}
// move on to next index
data_index_step(n, n_batch, c, n_channel);
}
});
}
template <typename scalar_t>
typename std::enable_if_t<!std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_channels_last_impl(Tensor& output, const Tensor& input,
const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd,
const Tensor& running_mean, const Tensor& running_var, bool train, double eps) {
using opmath_t = at::opmath_type<scalar_t>;
using bVec = Vectorized<scalar_t>;
using fVec = Vectorized<opmath_t>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
Tensor alpha = at::empty({n_channel}, input.options().dtype(kFloat));
Tensor beta = at::empty({n_channel}, input.options().dtype(kFloat));
opmath_t* alpha_data = alpha.mutable_data_ptr<opmath_t>();
opmath_t* beta_data = beta.data_ptr<opmath_t>();
const bool mixed_type = is_mixed_type(input, weight, bias, save_mean, save_invstd, running_mean, running_var);
if (mixed_type) {
batch_norm_cpu_collect_linear_and_constant_terms<opmath_t, opmath_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
} else {
batch_norm_cpu_collect_linear_and_constant_terms<scalar_t, opmath_t>(
alpha_data, beta_data, n_channel, weight, bias,
save_mean, save_invstd, running_mean, running_var, train, eps);
}
scalar_t* output_data = output.data_ptr<scalar_t>();
const scalar_t* input_data = input.data_ptr<scalar_t>();
const int64_t loop_size = n_channel - (n_channel % bVec::size());
at::parallel_for(0, n_batch * image_size, 1, [&](int64_t begin, int64_t end) {
for (const auto i : c10::irange(begin, end)) {
const scalar_t* input_ptr = input_data + i * n_channel;
scalar_t* output_ptr = output_data + i * n_channel;
int64_t d = 0;
for (; d < loop_size; d += bVec::size()) {
fVec alpha_fvec0 = fVec::loadu(alpha_data + d);
fVec alpha_fvec1 = fVec::loadu(alpha_data + d + fVec::size());
fVec beta_fvec0 = fVec::loadu(beta_data + d);
fVec beta_fvec1 = fVec::loadu(beta_data + d + fVec::size());
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
fVec out_fvec0 = data_fvec0 * alpha_fvec0 + beta_fvec0;
fVec out_fvec1 = data_fvec1 * alpha_fvec1 + beta_fvec1;
bVec out_bvec = convert_from_float<scalar_t>(out_fvec0, out_fvec1);
out_bvec.store(output_ptr + d);
}
for (; d < n_channel; d++) {
output_ptr[d] = scalar_t(opmath_t(input_ptr[d]) * alpha_data[d] + beta_data[d]);
}
}
});
}
template <typename scalar_t, typename param_t>
inline void batch_norm_cpu_collect_stats_contiguous_internal(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
using opmath_t = at::opmath_type<scalar_t>;
using bVec = Vectorized<scalar_t>;
using fVec = Vectorized<opmath_t>;
int64_t n_batch = input.size(0);
int64_t n_channel = input.size(1);
int64_t image_size = input.numel() / n_batch / n_channel;
int64_t N = input.numel() / n_channel;
const scalar_t* input_data = input.data_ptr<scalar_t>();
param_t* mean_data = mean.data_ptr<param_t>();
param_t* var_sum_data = var_sum.data_ptr<param_t>();
at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) {
for (const auto c : c10::irange(begin, end)) {
opmath_t sum_val = opmath_t(0);
fVec sum_fvec = fVec(opmath_t(0));
for (int64_t n = 0; n < n_batch; n++) {
const scalar_t* input_ptr = input_data + n * n_channel * image_size + c * image_size;
int64_t d = 0;
for (; d < image_size - (image_size % bVec::size()); d += bVec::size()) {
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
sum_fvec += data_fvec0;
sum_fvec += data_fvec1;
}
for (; d < image_size; d++) {
sum_val += opmath_t(input_ptr[d]);
}
}
// TODO: use fast version
sum_val += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, sum_fvec, fVec::size());
opmath_t mean_val = sum_val / N;
mean_data[c] = param_t(mean_val);
opmath_t var_val = opmath_t(0);
fVec var_fvec = fVec(opmath_t(0));
fVec mean_fvec = fVec(mean_val);
for (int64_t n = 0; n < n_batch; n++) {
const scalar_t* input_ptr = input_data + n * n_channel * image_size + c * image_size;
int64_t d = 0;
for (; d < image_size - (image_size % bVec::size()); d += bVec::size()) {
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
var_fvec += (data_fvec0 - mean_fvec) * (data_fvec0 - mean_fvec);
var_fvec += (data_fvec1 - mean_fvec) * (data_fvec1 - mean_fvec);
}
for (; d < image_size; d++) {
opmath_t data_val = input_ptr[d];
var_val += (data_val - mean_val) * (data_val - mean_val);
}
}
// TODO: use fast version
var_val += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, var_fvec, fVec::size());
var_sum_data[c] = param_t(var_val);
}
});
}
template <typename scalar_t>
typename std::enable_if_t<!std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_collect_stats_contiguous_impl(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
const bool mixed_type = is_mixed_type(input, mean, var_sum);
if (mixed_type) {
batch_norm_cpu_collect_stats_contiguous_internal<scalar_t, at::opmath_type<scalar_t>>(mean, var_sum, input);
} else {
batch_norm_cpu_collect_stats_contiguous_internal<scalar_t, scalar_t>(mean, var_sum, input);
}
}
template <typename scalar_t, typename param_t>
inline void batch_norm_cpu_collect_stats_channels_last_internal(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
using opmath_t = at::opmath_type<scalar_t>;
using bVec = Vectorized<scalar_t>;
using fVec = Vectorized<opmath_t>;
int64_t n_channel = input.size(1);
int64_t N = input.numel() / n_channel;
const scalar_t* input_data = input.data_ptr<scalar_t>();
param_t* mean_data = mean.data_ptr<param_t>();
param_t* var_sum_data = var_sum.data_ptr<param_t>();
int num_threads = at::get_num_threads();
Tensor buffer = at::zeros({num_threads, n_channel}, input.options().dtype(kFloat));
opmath_t* buffer_data = buffer.data_ptr<opmath_t>();
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
int tid = at::get_thread_num();
TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid);
opmath_t* buffer_ptr = buffer_data + tid * n_channel;
for (const auto i : c10::irange(begin, end)) {
const scalar_t* input_ptr = input_data + i * n_channel;
int64_t d = 0;
for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) {
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
fVec sum_fvec0 = fVec::loadu(buffer_ptr + d) + data_fvec0;
fVec sum_fvec1 = fVec::loadu(buffer_ptr + d + fVec::size()) + data_fvec1;
sum_fvec0.store(buffer_ptr + d);
sum_fvec1.store(buffer_ptr + d + fVec::size());
}
for (; d < n_channel; d++) {
buffer_ptr[d] += input_ptr[d];
}
}
});
for (const auto c : c10::irange(n_channel)) {
opmath_t sum = 0;
for (const auto t : c10::irange(num_threads)) {
sum += buffer_data[t * n_channel + c];
}
mean_data[c] = param_t(sum / N);
}
buffer.zero_();
at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) {
int tid = at::get_thread_num();
TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid);
opmath_t* buffer_ptr = buffer_data + tid * n_channel;
for (const auto i : c10::irange(begin, end)) {
const scalar_t* input_ptr = input_data + i * n_channel;
int64_t d = 0;
for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) {
bVec data_bvec = bVec::loadu(input_ptr + d);
fVec data_fvec0, data_fvec1;
std::tie(data_fvec0, data_fvec1) = convert_to_float<scalar_t>(data_bvec);
fVec mean_fvec0, mean_fvec1;
std::tie(mean_fvec0, mean_fvec1) = load2f(mean_data + d);
fVec var_fvec0 = fVec::loadu(buffer_ptr + d);
fVec var_fvec1 = fVec::loadu(buffer_ptr + d + fVec::size());
var_fvec0 += (data_fvec0 - mean_fvec0) * (data_fvec0 - mean_fvec0);
var_fvec1 += (data_fvec1 - mean_fvec1) * (data_fvec1 - mean_fvec1);
var_fvec0.store(buffer_ptr + d);
var_fvec1.store(buffer_ptr + d + fVec::size());
}
for (; d < n_channel; d++) {
opmath_t data_val = opmath_t(input_ptr[d]);
opmath_t mean_val = opmath_t(mean_data[d]);
buffer_ptr[d] += (data_val - mean_val) * (data_val - mean_val);
}
}
});
for (const auto c : c10::irange(n_channel)) {
opmath_t _var_sum = 0;
for (const auto t : c10::irange(num_threads)) {
_var_sum += buffer_data[t * n_channel + c];
}
var_sum_data[c] = param_t(_var_sum);
}
}
template <typename scalar_t>
typename std::enable_if_t<!std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
batch_norm_cpu_collect_stats_channels_last_impl(
Tensor& mean, Tensor& var_sum, const Tensor& input) {
const bool mixed_type = is_mixed_type(input, mean, var_sum);
if (mixed_type) {
batch_norm_cpu_collect_stats_channels_last_internal<scalar_t, at::opmath_type<scalar_t>>(mean, var_sum, input);
} else {
batch_norm_cpu_collect_stats_channels_last_internal<scalar_t, scalar_t>(mean, var_sum, input);
}