forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UpSampleKernel.cpp
1589 lines (1397 loc) · 59.9 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>
#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>>;
// 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.
//
// Linear 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 index_t, int interp_size>
struct Interpolate {
static inline scalar_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
scalar_t wts = *(scalar_t*)&data[1][i * strides[1]];
scalar_t t = Interpolate<n - 1, scalar_t, index_t, interp_size>::eval(src + ids, &data[2 * interp_size], &strides[2 * interp_size], i);
scalar_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, 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 index_t, int interp_size>
struct Interpolate<1, scalar_t, index_t, interp_size> {
static inline scalar_t eval(char* src, char** data, const int64_t* strides, int64_t i) {
index_t ids = *(index_t*)&data[0][i * strides[0]];
scalar_t wts = *(scalar_t*)&data[1][i * strides[1]];
scalar_t t = *(scalar_t *)&src[ids];
scalar_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 index_t>
struct Interpolate<n, scalar_t, index_t, 1> {
static inline scalar_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, index_t, 1>::eval(src + ids, &data[2], &strides[2], i);
}
};
template <typename scalar_t, typename index_t>
struct Interpolate<1, scalar_t, index_t, 1> {
static inline scalar_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 index_t>
struct Interpolate<n, scalar_t, index_t, 2> {
static inline scalar_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]];
scalar_t w0 = *(scalar_t *)&data[1][i * strides[1]];
scalar_t w1 = *(scalar_t *)&data[3][i * strides[3]];
scalar_t t0 = Interpolate<n - 1, scalar_t, index_t, 2>::eval(src + i0, &data[4], &strides[4], i);
scalar_t t1 = Interpolate<n - 1, scalar_t, index_t, 2>::eval(src + i1, &data[4], &strides[4], i);
return t0 * w0 + t1 * w1;
}
};
template <typename scalar_t, typename index_t>
struct Interpolate<1, scalar_t, index_t, 2> {
static inline scalar_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]];
scalar_t w0 = *(scalar_t *)&data[1][i * strides[1]];
scalar_t w1 = *(scalar_t *)&data[3][i * strides[3]];
scalar_t t0 = *(scalar_t *)&src[i0];
scalar_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) {
return Interpolate<n, scalar_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, typename index_t>
static inline void basic_loop_aa_single_dim_zero_strides(
char** data,
const int64_t* strides,
int64_t n) {
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const index_t ids_stride = *(index_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, index_t>(
src + i * strides[1], &data[2], ids_stride);
}
}
template <typename scalar_t, typename index_t>
static inline void basic_loop_aa_single_dim_nonzero_strides(
char** data,
const int64_t* strides,
int64_t n) {
char* dst = data[0];
char* src = data[1];
// index stride is constant for the given dimension
const index_t ids_stride = *(index_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, index_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, index_t>(
src + i * strides[1], &data[2], &strides[2], i, ids_stride);
}
}
}
// 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)));
}
}
template <typename scalar_t, typename aa_filter_fn_t>
static inline void _compute_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 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;
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;
}
for (j = 0; j < xsize; j++) {
if (total_w != 0.0) {
wt_ptr[j] /= total_w;
}
}
for (; j < interp_size; j++) {
wt_ptr[j] = static_cast<scalar_t>(0.0);
}
}
template <typename scalar_t, typename aa_filter_fn_t>
static inline std::vector<Tensor> _compute_indices_weights_aa(
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
) {
std::vector<Tensor> output;
scalar_t support =
(scale >= 1.0) ? (interp_size * 0.5) * scale : interp_size * 0.5;
interp_size = (int)ceilf(support) * 2 + 1;
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 * 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>();
int64_t xmin, xmax;
for (const auto i : c10::irange(output_size)) {
HelperInterpBase::_compute_weights_aa(
i,
input_size,
scale,
support,
wt_ptr + i * interp_size,
interp_size,
aa_filter_fn,
xmin,
xmax);
idx_ptr_xmin[i] = xmin * stride;
idx_ptr_size[i] = xmax;
idx_ptr_stride[i] = stride;
wt_idx_ptr[i] = i * interp_size * sizeof(scalar_t);
}
return output;
}
};
struct HelperInterpNearest : public HelperInterpBase {
// This structure implements outdated and buggy method to compute indices
// for nearest neighbours interpolation
// We keep this structure for BC and consider as deprecated.
// See HelperInterpNearestExact as replacement
static const int interp_size = 1;
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>())));
// Defines weights for consistency, but not used
output.emplace_back(at::ones(new_shape, CPU(output_type)));
}
}
// Compute nearest mode indices and weights for each interpolated dimension
// indices_weights = {
// {indices_0, 1.0, }, // dim -n
// {indices_0, 1.0, }, // dim -(n-1)
// ...
// {indices_0, 1.0, }, // dim -1
// }
// Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to
// fit input/output tensors.
// Indices are already containing the strides to optimize the computations
static inline std::vector<Tensor> compute_indices_weights(
at::ScalarType scalar_type,
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
) {
TORCH_INTERNAL_ASSERT(!align_corners);
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
std::vector<Tensor> output;
HelperInterpNearest::init_indices_weights(
scalar_type, output, output_size, ndims, reshape_dim, HelperInterpNearest::interp_size);
AT_DISPATCH_FLOATING_TYPES_AND(
ScalarType::BFloat16, scalar_type, "compute_indices_weights_nearest", [&] {
scalar_t scale = area_pixel_compute_scale<scalar_t>(input_size, output_size, align_corners, opt_scale);
auto input_index_ptr = output[0].data_ptr<int64_t>();
int64_t input_index;
// Indices are computed as following:
// scale = 1.0 * isize / osize
// index_f32 = (output_index) * scale
// input_index = floor(index_f32)
// Same as OpenCV INTER_NEAREST
using opmath_t = at::opmath_type<scalar_t>;
for (const auto i : c10::irange(output_size)) {
const auto real_input_index =
area_pixel_compute_source_index<opmath_t>(
scale, i, /*align_corners=*/true, /*cubic=*/false);
input_index = static_cast<int64_t>(floorf(real_input_index));
input_index_ptr[i] = static_cast<int64_t>(std::min(input_index, input_size - 1)) * stride;
}
}
);
return output;
}
};
struct HelperInterpNearestExact : public HelperInterpNearest {
// Compute nearest mode indices and weights for each interpolated dimension
// indices_weights = {
// {indices_0, 1.0, }, // dim -n
// {indices_0, 1.0, }, // dim -(n-1)
// ...
// {indices_0, 1.0, }, // dim -1
// }
// Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to
// fit input/output tensors.
// Indices are already containing the strides to optimize the computations
static inline std::vector<Tensor> compute_indices_weights(
at::ScalarType scalar_type,
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
) {
TORCH_INTERNAL_ASSERT(!align_corners);
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
std::vector<Tensor> output;
HelperInterpNearest::init_indices_weights(
scalar_type, output, output_size, ndims, reshape_dim, HelperInterpNearest::interp_size);
AT_DISPATCH_FLOATING_TYPES(
scalar_type, "compute_indices_weights_nearest", [&] {
scalar_t scale = area_pixel_compute_scale<scalar_t>(input_size, output_size, align_corners, opt_scale);
auto input_index_ptr = output[0].data_ptr<int64_t>();
int64_t input_index;
// Indices should be computed as following:
// scale = 1.0 * isize / osize
// index_f32 = (output_index + 0.5) * scale - 0.5
// input_index = round(index_f32)
// Same as Pillow and Scikit-Image/Scipy ndi.zoom
using opmath_t = at::opmath_type<scalar_t>;
for (const auto i : c10::irange(output_size)) {
const auto real_input_index =
area_pixel_compute_source_index<opmath_t>(
scale, i, /*align_corners=*/align_corners, /*cubic=*/false);
input_index = static_cast<int64_t>(floorf(real_input_index + 0.5));
input_index_ptr[i] = static_cast<int64_t>(std::min(input_index, input_size - 1)) * stride;
}
}
);
return output;
}
};
struct HelperInterpLinear : public HelperInterpBase {
static const int interp_size = 2;
// Compute indices and weights for each interpolated dimension
// indices_weights = {
// {indices_0, weights_0, indices_1, weights_1}, // dim -n
// {indices_0, weights_0, indices_1, weights_1}, // dim -(n-1)
// ...
// {indices_0, weights_0, indices_1, weights_1}, // dim -1
// }
// Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to
// fit input/output tensors.
// Indices are already containing the strides to optimize the computations
static inline std::vector<Tensor> compute_indices_weights(
at::ScalarType scalar_type,
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
) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
std::vector<Tensor> output;
HelperInterpLinear::init_indices_weights(
scalar_type, output, output_size, ndims, reshape_dim, HelperInterpLinear::interp_size);
AT_DISPATCH_FLOATING_TYPES_AND(
ScalarType::BFloat16, scalar_type, "compute_indices_weights_linear", [&] {
scalar_t scale = area_pixel_compute_scale<scalar_t>(input_size, output_size, align_corners, opt_scale);
auto input_index0_ptr = output[0].data_ptr<int64_t>();
auto lambda0_ptr = output[1].data_ptr<scalar_t>();
auto input_index1_ptr = output[2].data_ptr<int64_t>();
auto lambda1_ptr = output[3].data_ptr<scalar_t>();
for (const auto i : c10::irange(output_size)) {
compute_source_index_and_lambda<scalar_t>(
input_index0_ptr[i], input_index1_ptr[i],
lambda0_ptr[i], lambda1_ptr[i],
scale, i, input_size, output_size, align_corners
);
// put stride into indices
// index values correspond to input indices (0, 1, 2, 3, ...)
// when multiplied by input stride, maximum possible value
// input_size[dim-1] * input_size[dim-2] * ... for the given dimension.
input_index0_ptr[i] *= stride;
input_index1_ptr[i] *= stride;
}
}
);
return output;
}
// taken from
// https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/
// src/libImaging/Resample.c#L20-L29
template<typename scalar_t>
static inline scalar_t aa_filter(scalar_t x) {
if (x < 0.0) {
x = -x;
}
if (x < 1.0) {
return 1.0 - x;
}
return 0.0;
}
static inline std::vector<Tensor> compute_indices_weights_aa(
at::ScalarType scalar_type,
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
) {
std::vector<Tensor> indices_weights;
AT_DISPATCH_FLOATING_TYPES(
scalar_type, "compute_indices_weights_aa", [&] {
scalar_t scale = area_pixel_compute_scale<scalar_t>(
input_size, output_size, align_corners, opt_scale);
auto interp_size = HelperInterpLinear::interp_size;
indices_weights = HelperInterpLinear::_compute_indices_weights_aa<scalar_t>(
input_size,
output_size,
stride,
ndims,
reshape_dim,
scale,
interp_size,
&HelperInterpLinear::aa_filter<scalar_t>);
}
);
return indices_weights;
}
};
struct HelperInterpCubic : public HelperInterpBase {
static const int interp_size = 4;
// Compute indices and weights for each interpolated dimension
// indices_weights = {
// {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -n
// {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -(n-1)
// ...
// {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -1
// }
// Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to
// fit input/output tensors.
// Indices are already containing the strides to optimize the computations
static inline std::vector<Tensor> compute_indices_weights(
at::ScalarType scalar_type,
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
) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
std::vector<Tensor> output;
HelperInterpCubic::init_indices_weights(
scalar_type, output, output_size, ndims, reshape_dim, HelperInterpCubic::interp_size);
AT_DISPATCH_FLOATING_TYPES_AND(
ScalarType::BFloat16, scalar_type, "compute_indices_weights_cubic", [&] {
scalar_t scale = area_pixel_compute_scale<scalar_t>(input_size, output_size, align_corners, opt_scale);
int64_t input_index;
int64_t zero = static_cast<int64_t>(0);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
scalar_t coeffs[4];
int64_t * idx_ptr;
scalar_t * wt_ptr;
using opmath_t = at::opmath_type<scalar_t>;
for (const auto i : c10::irange(output_size)) {
const auto real_input_index =
area_pixel_compute_source_index<opmath_t>(
scale, i, align_corners, /*cubic=*/true);
input_index = static_cast<int64_t>(floorf(real_input_index));
get_cubic_upsample_coefficients<scalar_t>(coeffs, real_input_index - input_index);
for (const auto j : c10::irange(interp_size)) {
idx_ptr = output[2 * j + 0].data_ptr<int64_t>();
idx_ptr[i] = static_cast<int64_t>(std::max(std::min(input_index + j - 1, input_size - 1), zero)) * stride;
wt_ptr = output[2 * j + 1].data_ptr<scalar_t>();
wt_ptr[i] = coeffs[j];
}
}
}
);
return output;
}
// taken from
// https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/
// src/libImaging/Resample.c#L46-L62
template<typename scalar_t>