forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UpSampleKernel.cpp
2104 lines (1849 loc) · 81.4 KB
/
UpSampleKernel.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/core/Tensor.h>
#include <ATen/Context.h>
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/TensorIterator.h>
#include <ATen/cpu/vec/vec.h>
#include <ATen/native/UpSample.h>
#include <ATen/native/cpu/utils.h>
#include <c10/util/irange.h>
#include <ATen/native/cpu/UpSampleKernelAVXAntialias.h>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#else
#include <ATen/ops/empty.h>
#include <ATen/ops/empty_native.h>
#include <ATen/ops/ones.h>
#endif
namespace at::native {
namespace {
using scale_t = std::vector<c10::optional<double>>;
// TODO: this file could benefit from a global renaming of its functions /
// classes and terms, as well as from adding more comments. In particular:
// - It's not obvious that despite their names (and the file name), all these
// kernels don't just do upsampling: they do general interpolation, i.e. they
// also all support downscaling.
// - the term "horizontal" or "within dims" or "contiguous dim" refers to the
// last dimension.
// It's not specific to 2D images and applies to 3D (and 1D??) inputs as well.
// Similarly "vertical" or "across dims" refers to all dims that aren't the
// last one. In other kernels these are also referred to as "zero-stride" and
// "non-zero-stride" - we should unify all this.
// - the terms "zero-stride" and "non-zero strides" refer to the weights and
// indices, not to the contiguity of input or output
// - It's not always clear which kernel is vectorized and which one isn't.
// - The functions like _use_vectorized_kernel_cond() should be renamed and
// their description updated, because they're not the only "fork" in the
// code-path where a choice is made between a vectorized kernel vs a
// non-vectorized one. See e.g. upsample_bilinear2d_kernel_impl() where we
// already make a similar check, before the one in
// _use_vectorized_kernel_cond().
// - It's not always clear which code is part of a "separable interpolation"
// code-path.
// - Some names need to be more specific. For example
// "cpu_upsample_generic_aa()" looks like a super generic name, but the function
// is instead fairly specific - we need to make that clearer.
// - Some functions have a "aa" suffix but it doesn't mean that they only
// support antialias. Some of them also support antialias=False now.
// - Various comments are outdated. Case in point: the one just below about the
// `Interpolate` struct being used for cpu_upsample_linear:
// cpu_upsample_linear doesn't exist anymore, and these structs are used for
// various modes, *not* just linear.
// - It'd be useful to document how interpolation works in general, and in particular state explicitly:
// - that the weights and indices across a given dimension are the same for
// all pixels (hence the benefit of pre-computing them)
// - that it can be "separated", i.e. we can do the horizontal pass and the
// vertical pass independently (and that some kernels are written this way,
// while some aren't.)
// - we can probably remove the template over index_t, because it's always
// hard-coded as int64_t
// Helper structs and methods for cpu_upsample_linear
//
// Interpolation methods that used below are separable, and as such we can compute the interpolation
// independently per dimension in a recursive way. Please, refer to #10482 for more context.
//
// Interpolation structure to compute output value in n-dimensional case.
// - recursively compute interpolated output for each dimension
// - we rely a lot on compiler's code optimization such that implemented operations
// can be automatically factorized and vectorized using SSE and AVX2
template <int n, typename scalar_t, typename opmath_t, typename index_t, int interp_size>
struct Interpolate {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
opmath_t wts = *(scalar_t*)&data[1][i * strides[1]];
opmath_t t = Interpolate<n - 1, scalar_t, opmath_t, index_t, interp_size>::eval(src + ids, &data[2 * interp_size], &strides[2 * interp_size], i);
opmath_t output = t * wts;
for (const auto j : c10::irange(1, interp_size)) {
ids = *(index_t*)&data[2 * j + 0][i * strides[2 * j + 0]];
wts = *(scalar_t*)&data[2 * j + 1][i * strides[2 * j + 1]];
t = Interpolate<n - 1, scalar_t, opmath_t, index_t, interp_size>::eval(src + ids, &data[2 * interp_size], &strides[2 * interp_size], i);
output += t * wts;
}
return output;
}
};
template <typename scalar_t, typename opmath_t, typename index_t, int interp_size>
struct Interpolate<1, scalar_t, opmath_t, index_t, interp_size> {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
opmath_t wts = *(scalar_t*)&data[1][i * strides[1]];
opmath_t t = *(scalar_t *)&src[ids];
opmath_t output = t * wts;
for (const auto j : c10::irange(1, interp_size)) {
ids = *(index_t*)&data[2 * j + 0][i * strides[2 * j + 0]];
wts = *(scalar_t*)&data[2 * j + 1][i * strides[2 * j + 1]];
t = *(scalar_t *)&src[ids];
output += t * wts;
}
return output;
}
};
template <int n, typename scalar_t, typename opmath_t, typename index_t>
struct Interpolate<n, scalar_t, opmath_t, index_t, 1> {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
return Interpolate<n - 1, scalar_t, opmath_t, index_t, 1>::eval(src + ids, &data[2], &strides[2], i);
}
};
template <typename scalar_t, typename opmath_t, typename index_t>
struct Interpolate<1, scalar_t, opmath_t, index_t, 1> {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
return *(scalar_t *)&src[ids];
}
};
// There is an unexpected 2x slowdown for upsample_trilinear3d channels_first
// for both 1 and 6 threads. We have to specialize this case as below:
// Once the issue is fixed we can keep generic implementation and remove:
// struct Interpolate<n, scalar_t, index_t, 2> and
// struct Interpolate<1, scalar_t, index_t, 2>
template <int n, typename scalar_t, typename opmath_t, typename index_t>
struct Interpolate<n, scalar_t, opmath_t, index_t, 2> {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t i0 = *(index_t*)&data[0][i * strides[0]];
index_t i1 = *(index_t*)&data[2][i * strides[2]];
opmath_t w0 = *(scalar_t *)&data[1][i * strides[1]];
opmath_t w1 = *(scalar_t *)&data[3][i * strides[3]];
opmath_t t0 = Interpolate<n - 1, scalar_t, opmath_t, index_t, 2>::eval(src + i0, &data[4], &strides[4], i);
opmath_t t1 = Interpolate<n - 1, scalar_t, opmath_t, index_t, 2>::eval(src + i1, &data[4], &strides[4], i);
return t0 * w0 + t1 * w1;
}
};
template <typename scalar_t, typename opmath_t, typename index_t>
struct Interpolate<1, scalar_t, opmath_t, index_t, 2> {
static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t i0 = *(index_t*)&data[0][i * strides[0]];
index_t i1 = *(index_t*)&data[2][i * strides[2]];
opmath_t w0 = *(scalar_t *)&data[1][i * strides[1]];
opmath_t w1 = *(scalar_t *)&data[3][i * strides[3]];
opmath_t t0 = *(scalar_t *)&src[i0];
opmath_t t1 = *(scalar_t *)&src[i1];
return t0 * w0 + t1 * w1;
}
};
template <int n, typename scalar_t, typename index_t, int interp_size>
static inline scalar_t interpolate(char* src, char** data, const int64_t* strides, int64_t i) {
using opmath_t = at::opmath_type<scalar_t>;
return Interpolate<n, scalar_t, opmath_t, index_t, interp_size>::eval(src, data, strides, i);
}
template <typename scalar_t, typename index_t>
static inline scalar_t interpolate_aa_single_dim_zero_strides(
char* src,
char** data,
const index_t ids_stride) {
const index_t ids_min = *(index_t*)&data[0][0];
const index_t ids_size = *(index_t*)&data[1][0];
char* src_min = src + ids_min;
scalar_t t = *(scalar_t*)&src_min[0];
index_t wts_idx = *(index_t*)&data[4][0];
scalar_t* wts_ptr = (scalar_t*)&data[3][wts_idx];
scalar_t wts = wts_ptr[0];
scalar_t output = t * wts;
for (const auto j : c10::irange(1, ids_size)) {
wts = wts_ptr[j];
t = *(scalar_t*)&src_min[j * ids_stride];
output += t * wts;
}
return output;
}
template <typename scalar_t, typename index_t>
static inline scalar_t interpolate_aa_single_dim(
char* src,
char** data,
const int64_t* strides,
int64_t i,
const index_t ids_stride) {
index_t ids_min = *(index_t*)&data[0][i * strides[0]];
index_t ids_size = *(index_t*)&data[1][i * strides[1]];
char* src_min = src + ids_min;
scalar_t t = *(scalar_t*)&src_min[0];
index_t wts_idx = *(index_t*)&data[4][i * strides[4]];
scalar_t* wts_ptr = (scalar_t*)&data[3][wts_idx];
scalar_t wts = wts_ptr[0];
scalar_t output = t * wts;
for (const auto j : c10::irange(1, ids_size)) {
wts = wts_ptr[j];
t = *(scalar_t*)&src_min[j * ids_stride];
output += t * wts;
}
return output;
}
template<int m>
static inline bool is_zero_stride(const int64_t* strides) {
bool output = strides[0] == 0;
for (const auto i : c10::irange(1, m)) {
output &= (strides[i] == 0);
}
return output;
}
template <typename scalar_t, typename index_t, int interp_size>
static inline bool is_contiguous_stride(const int64_t* strides) {
bool output = (strides[0] == sizeof(index_t)) && (strides[1] == sizeof(scalar_t));
for (int i=2; i<2 * interp_size; i+=2) {
output &= (strides[i] == sizeof(index_t)) && (strides[i + 1] == sizeof(scalar_t));
}
return output;
}
// Helper class to recursively check if all input strides corresponding to interpolated dimensions
// are equal zero except on a single dimension.
//
// Inputs: array of strides of size N, non_zero_stride_dim which can be -1, 0, 1, 2, ...
// if non_zero_stride_dim, we check that all strides are equal zero, otherwise
// 4 strides corresponding to the strides for index_0, weight_0, index_1 and weight_1 for non_zero_stride_dim
// dimension should be non zero.
//
// Unit check of the recursion is to verify whether 4 strides for one interpolated dimension are either zero,
// see method is_zero_stride, or (sizeof(index_t), sizeof(scalar_t), sizeof(index_t), sizeof(scalar_t)), see
// method is_contiguous_stride.
//
// In practice, we have the following cases:
// - for ND, float32, channel first, strides are
// dimN-1, dim1, dim0
// i0, w0, i1, w1, ..., i0, w0, i1, w1, i0, w0, i1, w1
// strides=(0, 0, 0, 0, ..., 0, 0, 0, 0, 4, 4, 4, 4)
//
// if size dim0 is 1 then its strides are 0 and dim1 strides are equal 4
//
// - for ND, float32, channel last, strides are
// dimN-1, dimN-2, dim0
// i0, w0, i1, w1, i0, w0, i1, w1, ... i0, w0, i1, w1
// strides=(0, 0, 0, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0)
//
// Using these methods we can hint the compiler to factorize constant indices and weights
// in cpu_upsample_linear method
template <int N, int non_zero_stride_dim, typename scalar_t, typename index_t, int interp_size>
struct CheckAlmostAllZeroStrides {
static inline bool eval(const int64_t* strides) {
// N is dim index: N -> dim0, N-1 -> dim1, ...
// non_zero_stride_dim should be out_dims - dim
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
bool output;
if (N == non_zero_stride_dim) {
output = is_contiguous_stride<scalar_t, index_t, interp_size>(strides);
} else {
output = is_zero_stride<2 * interp_size>(strides);
}
return output &&
CheckAlmostAllZeroStrides<N - 1, non_zero_stride_dim, scalar_t, index_t, interp_size>::eval(
&strides[2 * interp_size]);
}
};
template <int non_zero_stride_dim, typename scalar_t, typename index_t, int interp_size>
struct CheckAlmostAllZeroStrides<0, non_zero_stride_dim, scalar_t, index_t, interp_size> {
static inline bool eval(const int64_t* /*strides*/) {
return true;
}
};
template <int n, int s, typename scalar_t, typename index_t, int interp_size>
static inline bool check_almost_all_zero_stride(const int64_t* strides) {
return CheckAlmostAllZeroStrides<n, s, scalar_t, index_t, interp_size>::eval(strides);
}
// Helper method to compute interpolation for nearest, linear, cubic modes
template <typename scalar_t, typename index_t, int out_ndims, int interp_size>
static inline void basic_loop(char** data, const int64_t* strides, int64_t n) {
char* dst = data[0];
char* src = data[1];
for (const auto i : c10::irange(n)) {
*(scalar_t*)&dst[i * strides[0]] = interpolate<out_ndims, scalar_t, index_t, interp_size>(
src + i * strides[1], &data[2], &strides[2], i);
}
}
template <typename scalar_t>
static inline void basic_loop_aa_vertical(
char** data,
const int64_t* strides,
int64_t n,
unsigned int weights_precision) {
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const int64_t ids_stride = *(int64_t*)&data[2 + 2][0];
for (const auto i : c10::irange(n)) {
*(scalar_t*)&dst[i * strides[0]] =
interpolate_aa_single_dim_zero_strides<scalar_t, int64_t>(
src + i * strides[1], &data[2], ids_stride);
}
}
template <>
inline void basic_loop_aa_vertical<uint8_t>(
char** data,
const int64_t* strides,
int64_t n,
unsigned int weights_precision) {
// See Note [ Weights computation for uint8_t and multiplication trick ]
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const int64_t ids_stride = *(int64_t*)&data[2 + 2][0];
const int64_t ids_size = *(int64_t*)&data[2 + 1][0];
const int64_t ids_min = *(int64_t*)&data[2 + 0][0];
int64_t i = 0;
for (; i<n; i++) {
char* src_min = src + i * strides[1] + ids_min;
uint8_t t = *(uint8_t*)&src_min[0];
int64_t wts_idx = *(int64_t*)&data[2 + 4][0];
int16_t* wts_ptr = (int16_t*)&data[2 + 3][wts_idx];
int16_t wts = wts_ptr[0];
// Intermediate computations are using integer type
int output = 1 << (weights_precision - 1); // accounts for the +0.5 part
output += t * wts;
for (const auto j : c10::irange(1, ids_size)) {
wts = wts_ptr[j];
t = *(uint8_t*)&src_min[j * ids_stride];
output += t * wts;
}
*(uint8_t*)&dst[i * strides[0]] = (uint8_t)std::clamp(output >> weights_precision, 0, 255);
}
}
template <typename scalar_t>
static inline void basic_loop_aa_horizontal(
char** data,
const int64_t* strides,
int64_t n,
unsigned int weights_precision) {
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const int64_t ids_stride = *(int64_t*)&data[2 + 2][0];
if (strides[1] == 0) {
for (const auto i : c10::irange(n)) {
*(scalar_t*)&dst[i * strides[0]] =
interpolate_aa_single_dim<scalar_t, int64_t>(
src, &data[2], &strides[2], i, ids_stride);
}
} else {
for (const auto i : c10::irange(n)) {
*(scalar_t*)&dst[i * strides[0]] =
interpolate_aa_single_dim<scalar_t, int64_t>(
src + i * strides[1], &data[2], &strides[2], i, ids_stride);
}
}
}
template <>
inline void basic_loop_aa_horizontal<uint8_t>(
char** data,
const int64_t* strides,
int64_t n,
unsigned int weights_precision) {
// See Note [ Weights computation for uint8_t and multiplication trick ]
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const int64_t ids_stride = *(int64_t*)&data[2 + 2][0];
int64_t i = 0;
// Here we are implementing data interpolation within the same line (vs between the lines)
// output[x, y] = input[xmin[x], y] * W[x] + input[xmin[x] + 1, y] * W[x + 1] + ... + input[xmin[x] + xsize, y] * W[x + xsize]
for (; i<n; i++) {
int64_t ids_min = *(int64_t*)&data[2 + 0][i * strides[2 + 0]];
int64_t ids_size = *(int64_t*)&data[2 + 1][i * strides[2 + 1]];
char* src_min = src + i * strides[1] + ids_min;
uint8_t t = *(uint8_t*)&src_min[0];
int64_t wts_idx = *(int64_t*)&data[2 + 4][i * strides[2 + 4]];
int16_t* wts_ptr = (int16_t*)&data[2 + 3][wts_idx];
int16_t wts = wts_ptr[0];
// Intermediate computations are using integer type
int output = 1 << (weights_precision - 1); // accounts for the +0.5 part
output += t * wts;
for (const auto j : c10::irange(1, ids_size)) {
wts = wts_ptr[j];
t = *(uint8_t*)&src_min[j * ids_stride];
output += t * wts;
}
*(uint8_t*)&dst[i * strides[0]] = (uint8_t)std::clamp(output >> weights_precision, 0, 255);
}
}
// Generic upsampling computation method using TensorIterator for Nd case.
// Supports: nearest, linear, cubic modes with interp_size template argument: 1, 2, 4
//
// Single loop function for 1d, 2d and 3d cases and modes
// For N dimensions, output value up to Di dimension can be computed as
//
// output_i[a] = interpolate(output_{i+1}[a], w_{i+1}[a], output_{i+1}[a+1], w_{i+1}[a+1], ...)
// with
// output_DN[a] = interpolate(input_DN[a], w_DN[a], input_DN[a+1], w_DN[a+1], ...)
// and i - dimension index and a - linear index for spatial coordinates
//
// The recursive call is implemented with InterpLinear struct using template for
// the loop unrolling on compile time.
template <typename scalar_t, int out_ndims, int interp_size>
void cpu_upsample_generic(at::TensorIterator& iter)
{
auto loop = [&](char** data, const int64_t* strides, int64_t n) {
// special-cases to let the compiler apply compile-time input-specific optimizations
if ((strides[0] == sizeof(scalar_t) && (strides[1] == 0) &&
// NOLINTNEXTLINE(bugprone-branch-clone)
check_almost_all_zero_stride<out_ndims, 1, scalar_t, int64_t, interp_size>(&strides[2]))) {
// contiguous channels-first case
basic_loop<scalar_t, int64_t, out_ndims, interp_size>(data, strides, n);
} else if ((strides[0] == sizeof(scalar_t) && (strides[1] == sizeof(scalar_t)) &&
check_almost_all_zero_stride<out_ndims, -1, scalar_t, int64_t, interp_size>(&strides[2]))) {
// contiguous channels-last case
basic_loop<scalar_t, int64_t, out_ndims, interp_size>(data, strides, n);
} else {
// fallback
basic_loop<scalar_t, int64_t, out_ndims, interp_size>(data, strides, n);
}
};
iter.for_each(loop);
}
template <typename scalar_t, typename scale_type, nearest_idx_fn_t nearest_idx_fn>
void cpu_upsample_nearest_channels_last(
const Tensor& output_,
const Tensor& input_,
const scale_type& scales) {
TORCH_CHECK(input_.dtype() == output_.dtype(), "expected dtype ", input_.dtype(),
" for `output` but got dtype ", output_.dtype());
auto input_sizes = input_.sizes().vec();
auto output_sizes = output_.sizes().vec();
auto ndim = input_sizes.size();
TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.")
auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d;
auto input = input_.contiguous(channels_last_memory_format);
auto output = output_.contiguous(channels_last_memory_format);
auto input_data = input.data_ptr<scalar_t>();
auto output_data = output.data_ptr<scalar_t>();
int64_t num_batches = input_sizes[0];
int64_t channels = input_sizes[1];
int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1;
int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1;
int64_t input_height = (ndim >= 4) ? input_sizes[ndim - 2] : 1;
int64_t output_height = (ndim >= 4) ? output_sizes[ndim - 2] : 1;
int64_t input_width = input_sizes[ndim - 1];
int64_t output_width = output_sizes[ndim - 1];
int64_t numel = output.numel();
TORCH_CHECK(channels > 0, "expected input and output channels greater than 0 but got ", channels);
using Vec = vec::Vectorized<scalar_t>;
auto copy = [](scalar_t* out, scalar_t* in, int64_t size) {
int64_t d = 0;
for (; d < size - (size % Vec::size()); d += Vec::size()) {
Vec out_vec = Vec::loadu(in + d);
out_vec.store(out + d);
}
for (; d < size; d++) {
out[d] = in[d];
}
};
auto loop2d = [&](int64_t begin, int64_t end) {
int64_t n = 0;
int64_t oh = 0;
int64_t ow = 0;
data_index_init(begin, n, num_batches, oh, output_height, ow, output_width);
for (const auto i : c10::irange(begin, end)) {
int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[0]);
int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[1]);
scalar_t* output_ptr = output_data + i * channels;
scalar_t* input_ptr = input_data + n * input_height * input_width * channels +
ih * input_width * channels + iw * channels;
copy(output_ptr, input_ptr, channels);
data_index_step(n, num_batches, oh, output_height, ow, output_width);
}
};
auto loop3d = [&](int64_t begin, int64_t end) {
int64_t n = 0;
int64_t od = 0;
int64_t oh = 0;
int64_t ow = 0;
data_index_init(begin, n, num_batches, od, output_depth, oh, output_height, ow, output_width);
for (const auto i : c10::irange(begin, end)) {
int64_t id = nearest_idx_fn(od, input_depth, output_depth, scales[0]);
int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[1]);
int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[2]);
scalar_t* output_ptr = output_data + i * channels;
scalar_t* input_ptr = input_data + n * input_depth * input_height * input_width * channels +
id * input_height * input_width * channels +
ih * input_width * channels + iw * channels;
copy(output_ptr, input_ptr, channels);
data_index_step(n, num_batches, od, output_depth, oh, output_height, ow, output_width);
}
};
if (ndim == 4) {
// upsample nearest 2d
at::parallel_for(0, numel / channels, at::internal::GRAIN_SIZE / channels, loop2d);
} else {
// upsample nearest 3d
TORCH_INTERNAL_ASSERT(ndim == 5);
at::parallel_for(0, numel / channels, at::internal::GRAIN_SIZE / channels, loop3d);
}
if (!output_.is_contiguous(channels_last_memory_format)) {
output_.copy_(output);
}
}
template <typename scalar_t, typename accscalar_t>
inline VecType<scalar_t> interpolate(const scalar_t* t, accscalar_t w) {
return VecType<scalar_t>::loadu(t) * VecType<scalar_t>(w);
}
template <typename scalar_t, typename accscalar_t, typename... Args>
inline VecType<scalar_t> interpolate(const scalar_t* t, accscalar_t w, Args... args) {
return VecType<scalar_t>::loadu(t) * VecType<scalar_t>(w) + interpolate(args...);
}
template <typename scalar_t, typename scale_type>
void cpu_upsample_linear_channels_last(
const Tensor& output_,
const Tensor& input_,
bool align_corners,
const scale_type& scales) {
TORCH_CHECK(input_.dtype() == output_.dtype(), "expected dtype ", input_.dtype(),
" for `output` but got dtype ", output_.dtype());
auto input_sizes = input_.sizes().vec();
auto output_sizes = output_.sizes().vec();
auto ndim = input_sizes.size();
TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.")
auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d;
auto input = input_.contiguous(channels_last_memory_format);
auto output = output_.contiguous(channels_last_memory_format);
auto input_data = input.data_ptr<scalar_t>();
auto output_data = output.data_ptr<scalar_t>();
int64_t num_batches = input_sizes[0];
int64_t channels = input_sizes[1];
int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1;
int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1;
int64_t input_height = (ndim >= 4) ? input_sizes[ndim - 2] : 1;
int64_t output_height = (ndim >= 4) ? output_sizes[ndim - 2] : 1;
int64_t input_width = input_sizes[ndim - 1];
int64_t output_width = output_sizes[ndim - 1];
TORCH_CHECK(channels > 0, "expected input and output channels greater than 0 but got ", channels);
int64_t output_slice_size = output_depth * output_height * output_width * channels;
using opmath_t = at::opmath_type<scalar_t>;
using Vec = vec::Vectorized<scalar_t>;
auto loop2d = [&](int64_t begin, int64_t end) {
const auto height_scale = area_pixel_compute_scale<opmath_t>(
input_height, output_height, align_corners, scales[0]);
const auto width_scale = area_pixel_compute_scale<opmath_t>(
input_width, output_width, align_corners, scales[1]);
auto input_indexr = [=](int64_t n, int64_t h, int64_t w) {
return input_data + n * input_height * input_width * channels +
h * input_width * channels + w * channels;
};
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
int64_t ih0, ih1, iw0, iw1;
opmath_t h0lambda, h1lambda, w0lambda, w1lambda;
for (const auto n : c10::irange(begin, end)) {
for (const auto oh : c10::irange(output_height)) {
compute_source_index_and_lambda(
ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners);
for (const auto ow : c10::irange(output_width)) {
compute_source_index_and_lambda(
iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners);
scalar_t* out = output_data + n * output_slice_size +
oh * output_width * channels + ow * channels;
scalar_t* i00 = input_indexr(n, ih0, iw0);
scalar_t* i01 = input_indexr(n, ih0, iw1);
scalar_t* i10 = input_indexr(n, ih1, iw0);
scalar_t* i11 = input_indexr(n, ih1, iw1);
opmath_t w00 = h0lambda * w0lambda;
opmath_t w01 = h0lambda * w1lambda;
opmath_t w10 = h1lambda * w0lambda;
opmath_t w11 = h1lambda * w1lambda;
int64_t size = channels;
int64_t d = 0;
for (; d < size - (size % Vec::size()); d += Vec::size()) {
auto out_vec = interpolate(i00 + d, w00, i01 + d, w01, i10 + d, w10, i11 + d, w11);
out_vec.store(out + d);
}
for (; d < size; d++) {
out[d] = i00[d] * w00 + i01[d] * w01 + i10[d] * w10 + i11[d] * w11;
}
}
}
}
};
auto loop3d = [&](int64_t begin, int64_t end) {
const auto depth_scale = area_pixel_compute_scale<opmath_t>(
input_depth, output_depth, align_corners, scales[0]);
const auto height_scale = area_pixel_compute_scale<opmath_t>(
input_height, output_height, align_corners, scales[1]);
const auto width_scale = area_pixel_compute_scale<opmath_t>(
input_width, output_width, align_corners, scales[2]);
auto input_indexr = [=](int64_t n, int64_t d, int64_t h, int64_t w) {
return input_data + n * input_depth * input_height * input_width * channels +
d * input_height * input_width * channels +
h * input_width * channels + w * channels;
};
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
int64_t id0, id1, ih0, ih1, iw0, iw1;
opmath_t d0lambda, d1lambda, h0lambda, h1lambda, w0lambda, w1lambda;
for (const auto n : c10::irange(begin, end)) {
for (const auto od : c10::irange(output_depth)) {
compute_source_index_and_lambda(
id0, id1, d0lambda, d1lambda, depth_scale, od, input_depth, output_depth, align_corners);
for (const auto oh : c10::irange(output_height)) {
compute_source_index_and_lambda(
ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners);
for (const auto ow : c10::irange(output_width)) {
compute_source_index_and_lambda(
iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners);
scalar_t* out = output_data + n * output_slice_size +
od * output_height * output_width * channels +
oh * output_width * channels + ow * channels;
scalar_t* i000 = input_indexr(n, id0, ih0, iw0);
scalar_t* i001 = input_indexr(n, id0, ih0, iw1);
scalar_t* i010 = input_indexr(n, id0, ih1, iw0);
scalar_t* i011 = input_indexr(n, id0, ih1, iw1);
scalar_t* i100 = input_indexr(n, id1, ih0, iw0);
scalar_t* i101 = input_indexr(n, id1, ih0, iw1);
scalar_t* i110 = input_indexr(n, id1, ih1, iw0);
scalar_t* i111 = input_indexr(n, id1, ih1, iw1);
opmath_t w000 = d0lambda * h0lambda * w0lambda;
opmath_t w001 = d0lambda * h0lambda * w1lambda;
opmath_t w010 = d0lambda * h1lambda * w0lambda;
opmath_t w011 = d0lambda * h1lambda * w1lambda;
opmath_t w100 = d1lambda * h0lambda * w0lambda;
opmath_t w101 = d1lambda * h0lambda * w1lambda;
opmath_t w110 = d1lambda * h1lambda * w0lambda;
opmath_t w111 = d1lambda * h1lambda * w1lambda;
int64_t size = channels;
int64_t d = 0;
for (; d < size - (size % Vec::size()); d += Vec::size()) {
auto out_vec = interpolate(
i000 + d, w000, i001 + d, w001, i010 + d, w010, i011 + d, w011,
i100 + d, w100, i101 + d, w101, i110 + d, w110, i111 + d, w111);
out_vec.store(out + d);
}
for (; d < size; d++) {
out[d] =
i000[d] * w000 + i001[d] * w001 + i010[d] * w010 + i011[d] * w011 +
i100[d] * w100 + i101[d] * w101 + i110[d] * w110 + i111[d] * w111;
}
}
}
}
}
};
if (ndim == 4) {
// upsample nearest 2d
at::parallel_for(0, num_batches, at::internal::GRAIN_SIZE / output_slice_size / 4, loop2d);
} else {
// upsample nearest 3d
TORCH_INTERNAL_ASSERT(ndim == 5);
at::parallel_for(0, num_batches, at::internal::GRAIN_SIZE / output_slice_size / 8, loop3d);
}
if (!output_.is_contiguous(channels_last_memory_format)) {
output_.copy_(output);
}
}
// Helper structs to use with upsample_generic_Nd_kernel_impl
struct HelperInterpBase {
static inline void init_indices_weights(
at::ScalarType output_type,
std::vector<Tensor> & output, int64_t output_size, int64_t ndims,
int64_t reshape_dim, int interp_size
) {
auto new_shape = std::vector<int64_t>(ndims, 1);
new_shape[reshape_dim] = output_size;
for (const auto j C10_UNUSED : c10::irange(interp_size)) {
output.emplace_back(empty(new_shape, CPU(c10::CppTypeToScalarType<int64_t>())));
output.emplace_back(empty(new_shape, CPU(output_type)));
}
}
// This is a helper function for _compute_index_ranges_weights method that computes
// source two int64 scalars index min and size and a list weights (of size max_interp_size)
// for interpolation with antialiasing=true mode. It returns the maximal weights value
template <typename scalar_t, typename aa_filter_fn_t>
static inline scalar_t _compute_indices_min_size_weights_aa(
const int64_t i, const int64_t input_size, const scalar_t scale, const scalar_t support,
scalar_t* wt_ptr, const int64_t max_interp_size, aa_filter_fn_t filter_fn,
int64_t& xmin, int64_t& xsize
) {
scalar_t center = scale * (i + 0.5);
scalar_t total_w = 0.0;
scalar_t invscale = (scale >= 1.0) ? 1.0 / scale : 1.0;
xmin = std::max(
static_cast<int64_t>(center - support + 0.5), static_cast<int64_t>(0));
xsize = std::min(
static_cast<int64_t>(center + support + 0.5), input_size) - xmin;
// There are rare cases when due to precision xsize can be larger than max_interp_size by one.
// We have to clip the value
xsize = std::clamp(xsize, static_cast<int64_t>(0), max_interp_size);
int64_t j = 0;
for (; j < xsize; j++) {
scalar_t w = filter_fn((j + xmin - center + 0.5) * invscale);
wt_ptr[j] = w;
total_w += w;
}
scalar_t wt_max = 0.0;
if (total_w != 0.0) {
for (j = 0; j < xsize; j++) {
wt_ptr[j] /= total_w;
wt_max = std::max(wt_max, wt_ptr[j]);
}
}
for (; j < max_interp_size; j++) {
wt_ptr[j] = static_cast<scalar_t>(0.0);
}
return wt_max;
}
// This is a helper function for _compute_index_ranges_weights method that computes
// source two int64 scalars index min and size and a list weights (of size max_interp_size)
// for interpolation with antialiasing=false mode. It returns the maximal weights value.
// This function is templated with scalar_t for type of scale and weights but is only used for
// bilinear/bicubic modes on uint8 input and antialiasing=false (in this case scalar_t is double).
// For float input types we are using upsample_generic_Nd_kernel_impl and compute_indices_weights methods
template <typename scalar_t, typename aa_filter_fn_t>
static inline scalar_t _compute_indices_min_size_weights(
const int64_t i, const int64_t input_size, const scalar_t scale,
scalar_t* wt_ptr, const int64_t max_interp_size, aa_filter_fn_t filter_fn,
bool align_corners, int64_t& index_min, int64_t& index_size
) {
// Notes. We do not use opmath_t in this method as f16 and other smaller float types are not routed here.
// Typical usage of this method is with scalar_t = double when computing indices and weights for uint8 input
// The code below partly adapts indices and lambda computation from compute_indices_weights method and
// index_min/index_size from _compute_indices_min_size_weights_aa
bool cubic = max_interp_size > 2;
const auto real_input_index = area_pixel_compute_source_index<scalar_t>(
scale, i, align_corners, /*cubic=*/cubic);
scalar_t lambda;
int64_t input_index;
guard_index_and_lambda(real_input_index, input_size, input_index, lambda);
const auto support = static_cast<int64_t>(max_interp_size * 0.5);
const auto unbound_index_min = input_index - support + 1;
const auto unbound_index_max = input_index + support + 1;
index_min = std::max(unbound_index_min, static_cast<int64_t>(0));
index_size = std::min(unbound_index_max, input_size) - index_min;
// There are rare cases when due to precision xsize can be larger than max_interp_size by one.
// We have to clip the value
index_size = std::clamp(index_size, static_cast<int64_t>(0), max_interp_size);
// Below the weights are computed using filter_fn and accumulating values for indices being out of bounds
// For example, for bicubic mode for output index i = 0, we have input_index = -1,
// then we have unbound_index_min = -2 and unbound_index_max = 1 => unbounded input indices are [-2, -1, 0, 1] and
// valid input indices will be [0, 1]
// For unbounded input indices we compute four non-zero weights values [w0, w1, w2, w3] and as only two weights can
// be used with valid input indcies, we accumulate values in the following way: [w0 + w1 + w2, w3, 0.0, 0.0]
// This is equivalent to the float path which would compute indices as [0, 0, 0, 1] and weights as [w0, w1, w2, s3].
// A similar accumulation should done for unbounded indices larger than input size.
auto w_index = 0;
scalar_t wt_max = 0.0;
for (const auto j : c10::irange(max_interp_size)) {
// initialize weights value as we will accumulate below
wt_ptr[j] = 0.0;
scalar_t w = filter_fn(static_cast<scalar_t>(j + 1 - support) - lambda);
if (unbound_index_min + j <= 0) {
w_index = 0;
} else if (unbound_index_min + j >= input_size - 1) {
w_index = index_size - 1;
}
wt_ptr[w_index] += w;
wt_max = std::max(wt_max, wt_ptr[w_index]);
w_index++;
}
return wt_max;
}
// Note [ Support for antialias=False as a subcase of antialias=True ]
// This function was originally written with the hard assumption that
// antialias=True and it was later extended to support antialias=False.
// The only difference between aa and no-aa is in how the
// weights and indices are computed (and their number). In aa their number is
// variable but with no-aa, they're fixed to interp_size. The same "filters"
// can be used otherwise. HOWEVER, support for antialias=False here may not be
// optimally optimized: the code assumes an arbitrary number of weights and
// indices, but this can be optimized further when aa=False since we know
// their actual dimensions.
template <typename scalar_t, typename aa_filter_fn_t, int weight_index_stride=sizeof(scalar_t)>
static inline std::tuple<std::vector<Tensor>, int, scalar_t> _compute_index_ranges_weights(
int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims,
int64_t reshape_dim, scalar_t scale,
int interp_size, aa_filter_fn_t aa_filter_fn, bool antialias, bool align_corners
) {
std::vector<Tensor> output;
scalar_t support;
int max_interp_size;
if (antialias) {
support = (scale >= 1.0) ? (interp_size * 0.5) * scale : interp_size * 0.5;
max_interp_size = (int) std::ceil(support) * 2 + 1;
} else {
support = interp_size * 0.5;
max_interp_size = interp_size;
}
auto new_shape = std::vector<int64_t>(ndims, 1);
new_shape[reshape_dim] = output_size;
// Bounds approach as in PIL: xmin/xmax
output.emplace_back(
empty(new_shape, CPU(c10::CppTypeToScalarType<int64_t>())));
output.emplace_back(
empty(new_shape, CPU(c10::CppTypeToScalarType<int64_t>())));
output.emplace_back(
empty(new_shape, CPU(c10::CppTypeToScalarType<int64_t>())));
{
// Weights
new_shape[reshape_dim] = output_size * max_interp_size;
auto wts = empty(new_shape, CPU(c10::CppTypeToScalarType<scalar_t>()));
auto strides = wts.strides().vec();
strides[reshape_dim] = 0;
new_shape[reshape_dim] = output_size;
wts = wts.as_strided(new_shape, strides);
output.emplace_back(wts);
// Weights indices
output.emplace_back(
empty(new_shape, CPU(c10::CppTypeToScalarType<int64_t>())));
}
int64_t* idx_ptr_xmin = output[0].data_ptr<int64_t>();
int64_t* idx_ptr_size = output[1].data_ptr<int64_t>();
int64_t* idx_ptr_stride = output[2].data_ptr<int64_t>();
scalar_t* wt_ptr = output[3].data_ptr<scalar_t>();
int64_t* wt_idx_ptr = output[4].data_ptr<int64_t>();
scalar_t wt_max = 0.0;
for (const auto i : c10::irange(output_size)) {
int64_t xmin, xsize;
scalar_t wt_max_i;
if (antialias) {
wt_max_i = HelperInterpBase::_compute_indices_min_size_weights_aa(
i,
input_size,
scale,
support,
wt_ptr + i * max_interp_size,
max_interp_size,
aa_filter_fn,
xmin,
xsize);
} else {
wt_max_i = HelperInterpBase::_compute_indices_min_size_weights(
i,
input_size,
scale,
wt_ptr + i * max_interp_size,
max_interp_size,
aa_filter_fn,
align_corners,
xmin,
xsize);
}
wt_max = std::max(wt_max, wt_max_i);
idx_ptr_xmin[i] = xmin * stride;
idx_ptr_size[i] = xsize;
idx_ptr_stride[i] = stride;
wt_idx_ptr[i] = i * max_interp_size * weight_index_stride;
}
return {output, max_interp_size, wt_max};
}
/*
NOTE [ Weights computation for uint8_t and multiplication trick ]
When the input/output dtype is uint8_t, we still compute the interpolation
weights as double, but then convert them to int16 via some conversion logic
detailed below. This allows us to compute all interpolation operation (sum of
multiplications) as ints instead of floats. The result is converted back into
uint8 in basic_loop_aa_horizontal<uint8_t> (and vertical)
In essence the idea is to avoid a multiplication between a float (the
weight) and an int (the pixel value) and instead run a multiplication between
2 ints:
```py
COEF_PREC = 16
def mul(a:float, b:int) -> Tuple[float, int]:
# return a * b, round(a * b)
actual = a * b
assert a > 0 # I'm lazy
int_a = floor(0.5 + a * (1 << COEF_PREC))
with_trick = ((int_a * b) + (1 << (COEF_PREC - 1))) >> COEF_PREC
return actual, with_trick # round(actual) == with_trick!!
```
Here's how it works:
N == COEFF_PREC
1 << N == 2**N
floor(0.5 + x) == round(x)
So the operation is something like
int_a = round(a * 2**N) -- let's just say it's `a * 2**N` for simplicity
res = ((int_a * b) + (1 << (N - 1))) >> N
= ((a * 2**N * b + 2**(N - 1)) / 2**N
= a * b + 0.5
= round(a * b)
= what we wanted
*/
template <typename aa_filter_fn_t>
static inline std::tuple<std::vector<Tensor>, int, unsigned int> _compute_index_ranges_int16_weights(
int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims,
int64_t reshape_dim, bool align_corners, const c10::optional<double> opt_scale,
int interp_size, aa_filter_fn_t aa_filter_fn, bool antialias, bool align_i32=false
) {
double scale = area_pixel_compute_scale<double>(
input_size, output_size, align_corners, opt_scale);
std::vector<Tensor> indices_weights;
double wt_max;
std::tie(indices_weights, interp_size, wt_max) = HelperInterpBase::_compute_index_ranges_weights<double, aa_filter_fn_t, sizeof(int16_t)>(
input_size, output_size, stride, ndims, reshape_dim, scale, interp_size, aa_filter_fn, antialias, align_corners);