forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GridSamplerKernel.cpp
1322 lines (1161 loc) · 56.2 KB
/
GridSamplerKernel.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_NO_OPERATORS
#include <ATen/native/GridSampler.h>
#include <ATen/native/cpu/GridSamplerKernel.h>
#include <ATen/core/TensorBase.h>
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/TensorGeometry.h>
#include <ATen/TensorIterator.h>
#include <ATen/cpu/vec/vec.h>
#include <c10/util/irange.h>
#include <algorithm>
#include <cstring>
namespace at::native { namespace {
/** NOTE [ Grid Sample CPU Kernels ]
*
* Implementation of vectorized grid sample CPU kernels is divided into three
* parts. More detailed description exist after this paragraph, but on a high
* level, they are
* 1. `ComputeLocation` struct
* + Computes the interpolation location basing on padding mode.
* 2. `ApplyGridSample` struct
* + Owns N (# spatial dims) `ComputeLocation` structs, and uses them to
* compute the interpolation locations.
* + Interpolates the values and writes to output.
* 3. `grid_sample_2d_grid_slice_iterator` function
* + Iterates over a slice of the grid tensor based on the geometry by the
* spatial ordering, i.e., the first iteration will process grid values
* grid[n, 0, 0, :], grid[n, 0, 1, :], grid[n, 0, 2, :], ...
* (Recall that, e.g., 2D grid has shape [N x H x W x 2], so grid[n, ...]
* is a slice, and grid[n, h, w, :] contains the values for a single
* output spatial location.)
* + Applies a given operator at each iteration, so we can use the same
* pattern for forward and backward.
*
* Putting everything together, we have, e.g., the forward kernel implemented
* as
*
* // `ApplyGridSample` struct that processes grid values, extracts and
* // interpolates input values, and write to output.
* ApplyGridSample<scalar_t, 2, interp, padding> grid_sample(input_accessor);
*
* // For each slice, we call `grid_sample_2d_grid_slice_iterator` with
* // 1. the grid slice, and
* // 2. a lambda that takes in
* // i. location vectors (x and y for 2D) extracted from grid
* // ii. `spatial_offset` as the spatial offset of these vectors
* // from the beginning of this slice.
* // iii. `len` as the number of valid locations in the vectors.
* // (There might not be enough near boundary.)
* for (const auto n : c10::irange(input_accessor.size(0))) {
* grid_sample_2d_grid_slice_iterator(
* grid_accessor[n],
* [&](const Vectorized<scalar_t>& grid_x,
* const Vectorized<scalar_t>& grid_y,
* int64_t spatial_offset, int64_t len) {
* grid_sample.forward(out_accessor[n], input_accessor[n],
* spatial_offset, grid_x, grid_y, len);
* });
* }
*
* Now we talk about details of each of these three parts:
*
* 1. `ComputeLocation` struct
* Transforms grid values into interpolation locations of the input tensor
* for a particular spatial dimension, based on the size of that dimension
* in input tensor, and the padding mode.
*
* template<typename scalar_t, GridSamplerPadding padding>
* struct ComputeLocation {
* using Vec = Vectorized<scalar_t>;
*
* // ctor
* ComputeLocation(int64_t size);
*
* // Given grid values `in`, return the interpolation locations after
* // un-normalization and padding mechanism (elementwise).
* Vec apply(const Vec &in) const;
*
* // Similar to `apply`, but also returns `d apply(in) / d in`
* // (elementwise).
* // this is often used in gradient computation.
* std::pair<Vec, Vec> apply_get_grad(const Vec &in) const;
* };
*
* 2. `ApplyGridSample` struct
* Owns N `ComputeLocation` structs, where N is the number of spatial
* dimensions. Given N input grid vectors (one for each spatial dimension)
* and spatial offset, it gets the interpolation locations from
* `ComputeLocation`s, applies interpolation procedure, and then writes to
* the output (or grad_input & grad_grid in backward).
*
* template<typename scalar_t, int spatial_dim,
* GridSamplerInterpolation interp,
* GridSamplerPadding padding>
* struct ApplyGridSample {
*
* // ctor
* ApplyGridSample(const TensorAccessor<scalar_t, 4>& input);
*
* // Applies grid sampling (forward) procedure:
* // 1. computes interpolation locations from grid values `grid_x`
* // and `grid_y`,
* // 2. interpolates output values using the locations and input
* // data in `inp_slice`, and
* // 3. writes the first `len` values in the interpolated vector to
* // `out_slice` with spatial offset being `offset`.
* //
* // This assumes that `grid_x` and `grid_y` all contain valid grid
* // values \in [-1, 1], even at indices greater than `len`.
* //
* // The `*_slice` argument names mean samples within a batch (i.e.,
* // with the batch dimension sliced out).
* void forward(TensorAccessor<scalar_t, 3>& out_slice,
* const TensorAccessor<scalar_t, 3>& inp_slice,
* int64_t offset, const Vec& grid_x, const Vec& grid_y,
* int64_t len) const;
*
* // Applies grid sampling (backward) procedure. Arguments semantics
* // and strategy are similar to those of `forward`, with the
* // exception that `backward` has branches based on whether `input`
* // requires gradient (passed in as a template parameter). The
* // TensorAccessor for the input gradient is also given as a
* // pointer instead of reference, so that it can be null if the
* // gradient is not calculated.
* template <bool input_requires_grad>
* void backward(TensorAccessor<scalar_t, 3>* gInp_slice_ptr,
* TensorAccessor<scalar_t, 3>& gGrid_slice,
* const TensorAccessor<scalar_t, 3>& gOut_slice,
* const TensorAccessor<scalar_t, 3>& inp_slice,
* int64_t offset, const Vec& grid_x, const Vec& grid_y,
* int64_t len) const;
* };
*
* 3. `grid_sample_2d_grid_slice_iterator` function
* Among the tensors we work with, we know that the output tensors are
* contiguous (i.e., `output` in forward, and `grad_input` & `grad_grid` in
* backward), we need to randomly read `input` anyways, and `grad_output`
* usually comes from autograd and is often contiguous. So we base our
* iterating strategy on the geometry of grid.
* `grid_sample_2d_grid_slice_iterator` function provides an abstraction to
* efficiently iterates through a `grid` slice (without batch dimension).
* See comments of that function on the specific cases and strategies used.
*
* template<typename scalar_t, typename ApplyFn>
* void grid_sample_2d_grid_slice_iterator(
* const TensorAccessor<scalar_t, 3>& grid_slice,
* const ApplyFn &apply_fn);
*
* `apply_fn` is a function/lambda that takes in
* i. location vectors (x and y for 2D) extracted from grid
* ii. `spatial_offset` as the spatial offset of these vectors
* from the beginning of this slice.
* iii. `len` as the number of valid locations in the vectors.
* (There might not be enough near boundary.)
* It should be callable as if it has declaration:
* void apply_fn(const Vectorized<scalar_t>& grid_x,
* const Vectorized<scalar_t>& grid_y,
* int64_t spatial_offset, int64_t len);
*
* `apply_fn` will be called multiple times, and together cover the entire
* output spatial space.
*
* Now you should be able to understand everything about the implementation of
* 2D forward kernel shown at the beginning of this note.
*
**/
using at::native::detail::GridSamplerInterpolation;
using at::native::detail::GridSamplerPadding;
using namespace at::vec;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComputeLocation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Struct to compute interpolation location from grid values, and to apply
// padding mechanism (e.g., reflection).
// See NOTE [ Grid Sample CPU Kernels ] for details.
template<typename scalar_t, bool align_corners>
struct ComputeLocationBase;
template<typename scalar_t>
struct ComputeLocationBase<scalar_t, /*align_corners=*/true> {
using Vec = Vectorized<scalar_t>;
// values are clipped to between 0 and max_val
const scalar_t max_val;
// unnormalization scaling factor
const scalar_t scaling_factor;
// reflection parameters: reflected coordinates land in [low, low+span] inclusive
const scalar_t low; // only used when align_corners=False
const scalar_t twice_span;
// if the reflecting span is empty, all reflected coords are set to 0
const bool empty;
ComputeLocationBase(int64_t size)
: max_val(static_cast<scalar_t>(size - 1))
, scaling_factor(static_cast<scalar_t>(size - 1) / 2)
, low(static_cast<scalar_t>(0))
, twice_span(static_cast<scalar_t>(size - 1) * 2)
, empty(size <= 1) {}
inline Vec unnormalize(const Vec &in) const {
return (in + Vec(1)) * Vec(scaling_factor);
}
inline Vec clip_coordinates(const Vec &in) const {
// Invert order of clamp_min operands in order to clamp Nans to zero
return clamp_max(Vec(max_val), clamp_min(Vec(0), in));
}
// same as clip_coordinates but also returns the gradient multiplier
inline std::pair<Vec, Vec> clip_coordinates_get_grad(const Vec &in) const {
using int_t = int_same_size_t<scalar_t>;
auto bounded_lo = maximum(in, Vec(0));
// Integral type equality comparison is very very fast because it just looks
// at the bits. Casting is free too. So we use the following pattern instead
// of comparison + blendv.
// Note that it is important for the gradient calculation that borders
// are considered out of bounds.
auto in_bound_lo = cast<scalar_t>(cast<int_t>(bounded_lo) != cast<int_t>(Vec(0)));
auto res = minimum(bounded_lo, Vec(max_val));
auto in_bound_hi = cast<scalar_t>(cast<int_t>(res) != cast<int_t>(Vec(max_val)));
return std::make_pair(res, in_bound_lo & in_bound_hi);
}
inline Vec reflect_coordinates(const Vec &in) const {
if (empty) {
return Vec(0);
}
Vec twice_span_vec(twice_span);
auto abs_in = in.abs();
auto fdouble_flips = abs_in / twice_span_vec;
auto double_flips = fdouble_flips.trunc();
auto extra = abs_in - double_flips * twice_span_vec;
// Now we need to test if extra > max_val to find out if another flip is
// needed. The following comparison does that and returns the correct
// flipped value.
return minimum(extra, twice_span_vec - extra);
}
// same as reflect_coordinates but also returns the gradient multiplier
inline std::pair<Vec, Vec> reflect_coordinates_get_grad(const Vec &in) const {
if (empty) {
return std::make_pair(Vec(0), Vec(0));
}
Vec twice_span_vec(twice_span);
auto neg_in = in < Vec(0);
auto abs_in = in.abs();
auto fdouble_flips = abs_in / twice_span_vec;
auto double_flips = fdouble_flips.trunc();
auto extra = abs_in - double_flips * twice_span_vec;
auto reflected_extra = twice_span_vec - extra;
auto one_more_flip = extra > reflected_extra;
return std::make_pair(
Vec::blendv(extra, reflected_extra, one_more_flip),
Vec::blendv(Vec(1), Vec(-1), one_more_flip ^ neg_in)
);
}
};
template<typename scalar_t>
struct ComputeLocationBase<scalar_t, /*align_corners=*/false> {
using Vec = Vectorized<scalar_t>;
// values are clipped to between 0 and max_val
const scalar_t max_val;
// unnormalization scaling factor
const scalar_t scaling_factor;
// reflection parameters: reflected coordinates land in [low, low+span] inclusive
const scalar_t low;
const scalar_t twice_span;
// if the reflecting span is empty, all reflected coords are set to 0
const bool empty; // only used when align_corners=True
ComputeLocationBase(int64_t size)
: max_val(static_cast<scalar_t>(size - 1))
, scaling_factor(static_cast<scalar_t>(size) / 2)
, low(static_cast<scalar_t>(-0.5))
, twice_span(static_cast<scalar_t>(size) * 2)
, empty(size <= 0) {}
inline Vec unnormalize(const Vec &in) const {
return (in + Vec(1)) * Vec(scaling_factor) - Vec(0.5);
}
inline Vec clip_coordinates(const Vec &in) const {
// Invert order of clamp_min operands in order to clamp Nans to zero
return clamp_max(Vec(max_val), clamp_min(Vec(0), in));
}
// same as clip_coordinates but also returns the gradient multiplier
inline std::pair<Vec, Vec> clip_coordinates_get_grad(const Vec &in) const {
using int_t = int_same_size_t<scalar_t>;
auto bounded_lo = maximum(in, Vec(0));
// Integral type equality comparison is very very fast because it just looks
// at the bits. Casting is free too. So we use the following pattern instead
// of comparison + blendv.
// Note that it is important for the gradient calculation that borders
// are considered out of bounds.
auto in_bound_lo = cast<scalar_t>(cast<int_t>(bounded_lo) != cast<int_t>(Vec(0)));
auto res = minimum(bounded_lo, Vec(max_val));
auto in_bound_hi = cast<scalar_t>(cast<int_t>(res) != cast<int_t>(Vec(max_val)));
return std::make_pair(res, in_bound_lo & in_bound_hi);
}
inline Vec reflect_coordinates(const Vec &in) const {
Vec twice_span_vec(twice_span), low_vec(low);
// Since reflection is around low and low+span, subtract low before
// the reflection, and then add it back at the end.
auto abs_in = (in - low_vec).abs();
auto fdouble_flips = abs_in / twice_span_vec;
auto double_flips = fdouble_flips.trunc();
auto extra = abs_in - double_flips * twice_span_vec;
// Now we need to test if extra > max_val to find out if another flip is
// needed. The following comparison does that and returns the correct
// flipped value.
return minimum(extra, twice_span_vec - extra) + low_vec;
}
// same as reflect_coordinates but also returns the gradient multiplier
inline std::pair<Vec, Vec> reflect_coordinates_get_grad(const Vec &in) const {
Vec twice_span_vec(twice_span), low_vec(low);
Vec in_minus_low = in - low_vec;
auto neg_in = in_minus_low < Vec(0);
auto abs_in = in_minus_low.abs();
auto fdouble_flips = abs_in / twice_span_vec;
auto double_flips = fdouble_flips.trunc();
auto extra = abs_in - double_flips * twice_span_vec;
auto reflected_extra = twice_span_vec - extra;
auto one_more_flip = extra > reflected_extra;
return std::make_pair(
Vec::blendv(extra, reflected_extra, one_more_flip) + low_vec,
Vec::blendv(Vec(1), Vec(-1), one_more_flip ^ neg_in)
);
}
};
template<typename scalar_t, GridSamplerPadding padding, bool align_corners>
struct ComputeLocation;
template<typename scalar_t, bool align_corners>
struct ComputeLocation<scalar_t, GridSamplerPadding::Zeros, align_corners>
: ComputeLocationBase<scalar_t, align_corners> {
using Vec = Vectorized<scalar_t>;
using ComputeLocationBase<scalar_t, align_corners>::unnormalize;
using ComputeLocationBase<scalar_t, align_corners>::scaling_factor;
using ComputeLocationBase<scalar_t, align_corners>::ComputeLocationBase;
inline Vec apply(const Vec &in) const {
return unnormalize(in);
}
inline Vec compute_coordinates(const Vec &in) const {
return in;
}
inline std::pair<Vec, Vec> apply_get_grad(const Vec &in) const {
return std::make_pair(unnormalize(in), Vec(scaling_factor));
}
};
template<typename scalar_t, bool align_corners>
struct ComputeLocation<scalar_t, GridSamplerPadding::Border, align_corners>
: ComputeLocationBase<scalar_t, align_corners> {
using Vec = Vectorized<scalar_t>;
using ComputeLocationBase<scalar_t, align_corners>::unnormalize;
using ComputeLocationBase<scalar_t, align_corners>::clip_coordinates;
using ComputeLocationBase<scalar_t, align_corners>::clip_coordinates_get_grad;
using ComputeLocationBase<scalar_t, align_corners>::scaling_factor;
using ComputeLocationBase<scalar_t, align_corners>::ComputeLocationBase;
inline Vec apply(const Vec &in) const {
return clip_coordinates(unnormalize(in));
}
inline Vec compute_coordinates(const Vec &in) const {
return clip_coordinates(in);
}
inline std::pair<Vec, Vec> apply_get_grad(const Vec &in) const {
auto [res, grad_clip] = clip_coordinates_get_grad(unnormalize(in));
return std::make_pair(res, grad_clip & Vec(scaling_factor));
}
};
template<typename scalar_t, bool align_corners>
struct ComputeLocation<scalar_t, GridSamplerPadding::Reflection, align_corners>
: ComputeLocationBase<scalar_t, align_corners> {
using Vec = Vectorized<scalar_t>;
using ComputeLocationBase<scalar_t, align_corners>::unnormalize;
using ComputeLocationBase<scalar_t, align_corners>::clip_coordinates;
using ComputeLocationBase<scalar_t, align_corners>::clip_coordinates_get_grad;
using ComputeLocationBase<scalar_t, align_corners>::reflect_coordinates;
using ComputeLocationBase<scalar_t, align_corners>::reflect_coordinates_get_grad;
using ComputeLocationBase<scalar_t, align_corners>::scaling_factor;
using ComputeLocationBase<scalar_t, align_corners>::ComputeLocationBase;
inline Vec apply(const Vec &in) const {
auto res = reflect_coordinates(unnormalize(in));
res = clip_coordinates(res);
return res;
}
inline Vec compute_coordinates(const Vec &in) const {
auto res = reflect_coordinates(in);
res = clip_coordinates(res);
return res;
}
inline std::pair<Vec, Vec> apply_get_grad(const Vec &in) const {
auto [res, grad_refl] = reflect_coordinates_get_grad(unnormalize(in));
Vec grad(scaling_factor);
grad = grad_refl * grad;
auto [res2, grad_clip] = clip_coordinates_get_grad(res);
grad = grad_clip & grad;
return std::make_pair(res2, grad);
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ApplyGridSample ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Struct to apply grid sample (reading from input, interpolate, and write to
// output).
// See NOTE [ Grid Sample CPU Kernels ] for details.
template<typename scalar_t>
static inline void
mask_scatter_add(const scalar_t *src, scalar_t* base_addr,
const int_same_size_t<scalar_t> *offsets,
const int_same_size_t<scalar_t> *mask, int64_t len) {
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto i : c10::irange(len)) {
if (mask[i] & 0x01) {
base_addr[offsets[i]] += src[i];
}
}
}
template<typename scalar_t, int spatial_dim,
GridSamplerInterpolation interp,
GridSamplerPadding padding,
bool align_corners>
struct ApplyGridSample;
template<typename scalar_t, GridSamplerPadding padding, bool align_corners>
struct ApplyGridSample<scalar_t, 2, GridSamplerInterpolation::Bilinear,
padding, align_corners> {
using Vec = Vectorized<scalar_t>;
using integer_t = int_same_size_t<scalar_t>;
using iVec = Vectorized<integer_t>;
const int64_t inp_H;
const int64_t inp_W;
const int64_t inp_sH;
const int64_t inp_sW;
const int64_t C;
const int64_t inp_sC;
const ComputeLocation<scalar_t, padding, align_corners> compute_H;
const ComputeLocation<scalar_t, padding, align_corners> compute_W;
const bool must_in_bound = padding != GridSamplerPadding::Zeros;
ApplyGridSample(const TensorAccessor<const scalar_t, 4>& input)
: inp_H(input.size(2))
, inp_W(input.size(3))
, inp_sH(input.stride(2))
, inp_sW(input.stride(3))
, C(input.size(1))
, inp_sC(input.stride(1))
, compute_H(input.size(2))
, compute_W(input.size(3)) {}
inline std::tuple<
Vec, Vec, Vec, Vec, // distances to 4 sides
Vec, Vec, Vec, Vec, // interpolation weights wrt 4 corners
Vec, Vec, Vec, Vec, // in_bound masks
iVec, iVec // y_n and x_w
>
compute_interp_params(const Vec& x, const Vec& y) const {
// get NE, NW, SE, SW pixel values from (x, y)
// assuming we get exact integer representation and just use scalar_t
// if we don't, the weights will be garbage anyways.
auto x_w = x.floor();
auto y_n = y.floor();
// get distances to each side
auto w = x - x_w;
auto e = Vec(1) - w;
auto n = y - y_n;
auto s = Vec(1) - n;
// get interpolation weights for each neighbor
// e.g., for the nw corner, the weight is `dist_to_south * dist_to_east`.
auto nw = s * e;
auto ne = s * w;
auto sw = n * e;
auto se = n * w;
auto i_x_w = convert_to_int_of_same_size(x_w);
auto i_y_n = convert_to_int_of_same_size(y_n);
auto i_x_e = i_x_w + iVec(1);
auto i_y_s = i_y_n + iVec(1);
// Use int comparison because it is much faster than float comp with AVX2
// (latency 1 cyc vs. 4 cyc on skylake)
// Avoid using the le and ge because those are not implemented in AVX2 and
// are actually simulated using multiple instructions.
auto w_mask = must_in_bound ? iVec(-1) // true = all ones
: (i_x_w > iVec(-1)) & (i_x_w < iVec(inp_W));
auto n_mask = must_in_bound ? iVec(-1) // true = all ones
: (i_y_n > iVec(-1)) & (i_y_n < iVec(inp_H));
auto e_mask = must_in_bound ? (i_x_e < iVec(inp_W))
: (i_x_e > iVec(-1)) & (i_x_e < iVec(inp_W));
auto s_mask = must_in_bound ? (i_y_s < iVec(inp_H))
: (i_y_s > iVec(-1)) & (i_y_s < iVec(inp_H));
auto nw_mask = cast<scalar_t>(must_in_bound ? iVec(-1) : (w_mask & n_mask));
auto ne_mask = cast<scalar_t>(e_mask & n_mask);
auto sw_mask = cast<scalar_t>(w_mask & s_mask);
auto se_mask = cast<scalar_t>(e_mask & s_mask);
return std::make_tuple(
n, s, w, e,
nw, ne, sw, se,
nw_mask, ne_mask, sw_mask, se_mask,
i_y_n, i_x_w);
}
inline void forward(TensorAccessor<scalar_t, 3>& out_slice,
const TensorAccessor<const scalar_t, 3>& inp_slice,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
auto x = compute_W.apply(grid_x);
auto y = compute_H.apply(grid_y);
auto interp_params = compute_interp_params(x, y);
auto nw = std::get<4>(interp_params);
auto ne = std::get<5>(interp_params);
auto sw = std::get<6>(interp_params);
auto se = std::get<7>(interp_params);
auto nw_mask = std::get<8>(interp_params);
auto ne_mask = std::get<9>(interp_params);
auto sw_mask = std::get<10>(interp_params);
auto se_mask = std::get<11>(interp_params);
auto i_y_n = std::get<12>(interp_params);
auto i_x_w = std::get<13>(interp_params);
auto i_nw_offset = i_y_n * iVec(inp_sH) + i_x_w * iVec(inp_sW);
auto i_ne_offset = i_nw_offset + iVec(inp_sW);
auto i_sw_offset = i_nw_offset + iVec(inp_sH);
auto i_se_offset = i_sw_offset + iVec(inp_sW);
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto c : c10::irange(C)) {
auto inp_slice_C_ptr = inp_slice[c].data();
// mask_gather zeros out the mask, so we need to make copies
Vec nw_mask_copy = nw_mask;
Vec ne_mask_copy = ne_mask;
Vec sw_mask_copy = sw_mask;
Vec se_mask_copy = se_mask;
auto nw_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_nw_offset, nw_mask_copy);
auto ne_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_ne_offset, ne_mask_copy);
auto sw_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_sw_offset, sw_mask_copy);
auto se_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_se_offset, se_mask_copy);
auto interpolated = (nw_val * nw) + (ne_val * ne) + (sw_val * sw) + (se_val * se);
interpolated.store(out_slice[c].data() + offset, len);
}
}
template<bool input_requires_grad>
inline void backward(TensorAccessor<scalar_t, 3>* gInp_slice_ptr,
TensorAccessor<scalar_t, 3>& gGrid_slice,
const TensorAccessor<const scalar_t, 3>& gOut_slice,
const TensorAccessor<const scalar_t, 3>& inp_slice,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
auto [x, gx_mult] = compute_W.apply_get_grad(grid_x);
auto [y, gy_mult] = compute_H.apply_get_grad(grid_y);
auto [
n, s, w, e, nw, ne, sw, se, nw_mask, ne_mask, sw_mask, se_mask,
i_y_n, i_x_w] = compute_interp_params(x, y);
auto i_nw_offset = i_y_n * iVec(inp_sH) + i_x_w * iVec(inp_sW);
auto i_ne_offset = i_nw_offset + iVec(inp_sW);
auto i_sw_offset = i_nw_offset + iVec(inp_sH);
auto i_se_offset = i_sw_offset + iVec(inp_sW);
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_nw_mask_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_ne_mask_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_sw_mask_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_se_mask_arr[iVec::size()];
nw_mask.store(i_nw_mask_arr);
ne_mask.store(i_ne_mask_arr);
sw_mask.store(i_sw_mask_arr);
se_mask.store(i_se_mask_arr);
// i_gInp_*_offset_arr and gInp_corner_arr variables below are unnecessary
// when input_requires_grad is false (they are only used within the
// if-blocks), but required to make the code well-formed.
// When reading input values, we used mask_gather. Unfortunately, there is
// no mask_scatter_add (the backward of mask_gather) in Intel intrinsics.
// So we store the necessary vectors to temporary arrays and use the helper
// mask_scatter_add defined above.
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_gInp_nw_offset_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_gInp_ne_offset_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_gInp_sw_offset_arr[iVec::size()];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_gInp_se_offset_arr[iVec::size()];
if (input_requires_grad) {
auto i_gInp_nw_offset = i_y_n * iVec(inp_W) + i_x_w;
auto i_gInp_ne_offset = i_gInp_nw_offset + iVec(1);
auto i_gInp_sw_offset = i_gInp_nw_offset + iVec(inp_W);
auto i_gInp_se_offset = i_gInp_sw_offset + iVec(1);
i_gInp_nw_offset.store(i_gInp_nw_offset_arr);
i_gInp_ne_offset.store(i_gInp_ne_offset_arr);
i_gInp_sw_offset.store(i_gInp_sw_offset_arr);
i_gInp_se_offset.store(i_gInp_se_offset_arr);
}
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
scalar_t gInp_corner_arr[Vec::size()];
auto gx = Vec(0), gy = Vec(0);
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto c : c10::irange(C)) {
auto inp_slice_C_ptr = inp_slice[c].data();
auto gOut = Vec::loadu(gOut_slice[c].data() + offset, len);
if (input_requires_grad) {
TORCH_INTERNAL_ASSERT(gInp_slice_ptr);
auto gInp_slice_C_ptr = (*gInp_slice_ptr)[c].data();
(nw * gOut).store(gInp_corner_arr);
mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_nw_offset_arr, i_nw_mask_arr, len);
(ne * gOut).store(gInp_corner_arr);
mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_ne_offset_arr, i_ne_mask_arr, len);
(sw * gOut).store(gInp_corner_arr);
mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_sw_offset_arr, i_sw_mask_arr, len);
(se * gOut).store(gInp_corner_arr);
mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_se_offset_arr, i_se_mask_arr, len);
}
// mask_gather zeros out the mask, so we need to make copies
Vec nw_mask_copy = nw_mask;
Vec ne_mask_copy = ne_mask;
Vec sw_mask_copy = sw_mask;
Vec se_mask_copy = se_mask;
auto nw_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_nw_offset, nw_mask_copy);
auto ne_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_ne_offset, ne_mask_copy);
auto sw_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_sw_offset, sw_mask_copy);
auto se_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_C_ptr, i_se_offset, se_mask_copy);
gx = gx + ((ne_val - nw_val) * s + (se_val - sw_val) * n) * gOut;
gy = gy + ((sw_val - nw_val) * e + (se_val - ne_val) * w) * gOut;
}
gx = gx * gx_mult;
gy = gy * gy_mult;
constexpr int64_t step = Vec::size();
auto interleaved_gGrid = interleave2(gx, gy);
auto gGrid_ptr = gGrid_slice.data() + offset * 2;
std::get<0>(interleaved_gGrid).store(gGrid_ptr,
std::min(len * 2, step));
std::get<1>(interleaved_gGrid).store(gGrid_ptr + step,
std::max(static_cast<int64_t>(0), len * 2 - step));
}
};
template<typename scalar_t, GridSamplerPadding padding, bool align_corners>
struct ApplyGridSample<scalar_t, 2, GridSamplerInterpolation::Nearest,
padding, align_corners> {
using Vec = Vectorized<scalar_t>;
using integer_t = int_same_size_t<scalar_t>;
using iVec = Vectorized<integer_t>;
const int64_t inp_H;
const int64_t inp_W;
const int64_t inp_sH;
const int64_t inp_sW;
const int64_t C;
const int64_t inp_sC;
const ComputeLocation<scalar_t, padding, align_corners> compute_H;
const ComputeLocation<scalar_t, padding, align_corners> compute_W;
const bool must_in_bound = padding != GridSamplerPadding::Zeros;
ApplyGridSample(const TensorAccessor<const scalar_t, 4>& input)
: inp_H(input.size(2))
, inp_W(input.size(3))
, inp_sH(input.stride(2))
, inp_sW(input.stride(3))
, C(input.size(1))
, inp_sC(input.stride(1))
, compute_H(input.size(2))
, compute_W(input.size(3)) {}
inline void forward(TensorAccessor<scalar_t, 3>& out_slice,
const TensorAccessor<const scalar_t, 3>& inp_slice,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
auto x = compute_W.apply(grid_x);
auto y = compute_H.apply(grid_y);
auto x_nearest = x.round();
auto y_nearest = y.round();
auto i_x_nearest = convert_to_int_of_same_size(x_nearest);
auto i_y_nearest = convert_to_int_of_same_size(y_nearest);
auto i_mask = must_in_bound ? iVec(-1)
: (i_x_nearest > iVec(-1)) & (i_x_nearest < iVec(inp_W)) &
(i_y_nearest > iVec(-1)) & (i_y_nearest < iVec(inp_H));
auto mask = cast<scalar_t>(i_mask);
auto i_offset = i_y_nearest * iVec(inp_sH) + i_x_nearest * iVec(inp_sW);
auto out_ptr = out_slice.data() + offset;
auto out_sC = out_slice.stride(0);
auto inp_slice_ptr = inp_slice.data();
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (int64_t c = 0; c < C; ++c, out_ptr += out_sC, inp_slice_ptr += inp_sC) {
// mask_gather zeros out the mask, so we need to make a copy
auto mask_copy = mask;
auto inp_val = mask_gather<sizeof(scalar_t)>(Vec(0), inp_slice_ptr, i_offset, mask_copy);
inp_val.store(static_cast<void*>(out_ptr), len);
}
}
template<bool input_requires_grad>
inline void backward(TensorAccessor<scalar_t, 3>* gInp_slice_ptr,
TensorAccessor<scalar_t, 3>& gGrid_slice,
const TensorAccessor<const scalar_t, 3>& gOut_slice,
const TensorAccessor<const scalar_t, 3>& /*inp_slice*/,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
if (input_requires_grad) {
auto x = compute_W.apply(grid_x);
auto y = compute_H.apply(grid_y);
auto x_nearest = x.round();
auto y_nearest = y.round();
auto i_x_nearest = convert_to_int_of_same_size(x_nearest);
auto i_y_nearest = convert_to_int_of_same_size(y_nearest);
auto i_mask = must_in_bound ? iVec(-1)
: (i_x_nearest > iVec(-1)) & (i_x_nearest < iVec(inp_W)) &
(i_y_nearest > iVec(-1)) & (i_y_nearest < iVec(inp_H));
auto i_gInp_offset = i_y_nearest * iVec(inp_W) + i_x_nearest; // gInp is contiguous
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t mask_arr[iVec::size()];
i_mask.store(mask_arr);
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t gInp_offset_arr[iVec::size()];
i_gInp_offset.store(gInp_offset_arr);
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto c : c10::irange(C)) {
mask_scatter_add(gOut_slice[c].data() + offset, (*gInp_slice_ptr)[c].data(),
gInp_offset_arr, mask_arr, len);
}
}
// grid has zero 0 gradient in Nearest mode
auto gGrid_ptr = gGrid_slice.data() + offset * 2;
std::memset(gGrid_ptr, 0, sizeof(scalar_t) * len * 2);
}
};
// Use bicubic convolution algorithm. Based on
// https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
template<typename scalar_t, GridSamplerPadding padding, bool align_corners>
struct ApplyGridSample<scalar_t, 2, GridSamplerInterpolation::Bicubic,
padding, align_corners> {
using Vec = Vectorized<scalar_t>;
using integer_t = int_same_size_t<scalar_t>;
using iVec = Vectorized<integer_t>;
const int64_t inp_H;
const int64_t inp_W;
const int64_t inp_sH;
const int64_t inp_sW;
const int64_t C;
const int64_t inp_sC;
const ComputeLocation<scalar_t, padding, align_corners> compute_H;
const ComputeLocation<scalar_t, padding, align_corners> compute_W;
const bool must_in_bound = padding != GridSamplerPadding::Zeros;
// constant used in cubic convolution
// could be -0.5 or -0.75, use the same value in UpSampleBicubic2d.h
const Vec A = Vec(-0.75);
ApplyGridSample(const TensorAccessor<const scalar_t, 4>& input)
: inp_H(input.size(2))
, inp_W(input.size(3))
, inp_sH(input.stride(2))
, inp_sW(input.stride(3))
, C(input.size(1))
, inp_sC(input.stride(1))
, compute_H(input.size(2))
, compute_W(input.size(3)) {}
// Calculate the cubic convolution coefficient
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
inline void get_cubic_coefficients(Vec (&coeffs)[4], const Vec& tx) const {
Vec x;
x = tx + Vec(1); // 1 < x = |-1 - tx| < 2
coeffs[0] = ((A * x - Vec(5) * A) * x + Vec(8) * A) * x - Vec(4) * A;
x = tx; // x = |0 - tx| <= 1
coeffs[1] = ((A + Vec(2)) * x - (A + Vec(3))) * x * x + Vec(1);
x = Vec(1) - tx; // x = |1 - tx| <= 1
coeffs[2] = ((A + Vec(2)) * x - (A + Vec(3))) * x * x + Vec(1);
x = Vec(2) - tx; // 1 < x = |2 - tx| < 2
coeffs[3] = ((A * x - Vec(5) * A) * x + Vec(8) * A) * x - Vec(4) * A;
}
// Calculate the differential of the cubic convolution, i.e. `d coeff / d x`
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
inline void get_cubic_coefficients_grad(Vec (&coeffs)[4], const Vec& tx) const {
Vec x;
x = Vec(-1) - tx; // 1 < x = |-1 - tx| < 2
coeffs[0] = (Vec(-3) * A * x - Vec(10) * A ) * x - Vec(8) * A;
x = Vec(0) - tx; // x = |0 - tx| <= 1
coeffs[1] = (Vec(-3) * (A + Vec(2)) * x - Vec(2) * (A + Vec(3))) * x;
x = Vec(1) - tx; // x = |1 - tx| <= 1
coeffs[2] = (Vec(3) * (A + Vec(2)) * x - Vec(2) * (A + Vec(3))) * x;
x = Vec(2) - tx; // 1 < x = |2 - tx| < 2
coeffs[3] = (Vec(3) * A * x - Vec(10) * A) * x + Vec(8) * A;
}
inline Vec get_value_bounded(const scalar_t* data, const Vec& x, const Vec& y) const {
auto ix = convert_to_int_of_same_size(compute_W.compute_coordinates(x));
auto iy = convert_to_int_of_same_size(compute_H.compute_coordinates(y));
auto mask_x = must_in_bound ? iVec(-1) : (ix > iVec(-1)) & (ix < iVec(inp_W));
auto mask_y = must_in_bound ? iVec(-1) : (iy > iVec(-1)) & (iy < iVec(inp_H));
auto mask = cast<scalar_t>(mask_x & mask_y);
auto offset = iy * iVec(inp_sH) + ix * iVec(inp_sW);
auto val = mask_gather<sizeof(scalar_t)>(Vec(0), data, offset, mask);
return val;
}
inline void add_value_bounded(scalar_t* data, int64_t len, const Vec& x, const Vec&y,
const Vec& delta) const {
auto ix = convert_to_int_of_same_size(compute_W.compute_coordinates(x));
auto iy = convert_to_int_of_same_size(compute_H.compute_coordinates(y));
auto mask_x = must_in_bound ? iVec(-1) : (ix > iVec(-1)) & (ix < iVec(inp_W));
auto mask_y = must_in_bound ? iVec(-1) : (iy > iVec(-1)) & (iy < iVec(inp_H));
auto mask = cast<scalar_t>(mask_x & mask_y);
auto i_gInp_offset = iy * iVec(inp_W) + ix;
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t i_gInp_offset_arr[iVec::size()];
i_gInp_offset.store(i_gInp_offset_arr);
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
integer_t mask_arr[iVec::size()];
mask.store(mask_arr);
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
scalar_t gInp_corner_arr[Vec::size()];
delta.store(gInp_corner_arr);
mask_scatter_add(gInp_corner_arr, data, i_gInp_offset_arr, mask_arr, len);
}
inline void forward(TensorAccessor<scalar_t, 3>& out_slice,
const TensorAccessor<const scalar_t, 3>& inp_slice,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
auto x = compute_W.unnormalize(grid_x);
auto y = compute_H.unnormalize(grid_y);
auto ix = x.floor();
auto iy = y.floor();
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_x[4];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_y[4];
get_cubic_coefficients(coeff_x, x - ix);
get_cubic_coefficients(coeff_y, y - iy);
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto c : c10::irange(C)) {
auto inp_slice_C_ptr = inp_slice[c].data();
// Interpolate the 4 values in the x direction
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec interp_x[4];
for (const auto i : c10::irange(4)) {
interp_x[i] =
coeff_x[0] * get_value_bounded(inp_slice_C_ptr, ix - Vec(1), iy + Vec(-1 + i)) +
coeff_x[1] * get_value_bounded(inp_slice_C_ptr, ix + Vec(0), iy + Vec(-1 + i)) +
coeff_x[2] * get_value_bounded(inp_slice_C_ptr, ix + Vec(1), iy + Vec(-1 + i)) +
coeff_x[3] * get_value_bounded(inp_slice_C_ptr, ix + Vec(2), iy + Vec(-1 + i));
}
// Interpolate the 4 values in the y direction
auto interpolated = coeff_y[0] * interp_x[0] + coeff_y[1] * interp_x[1] +
coeff_y[2] * interp_x[2] + coeff_y[3] * interp_x[3];
interpolated.store(out_slice[c].data() + offset, len);
}
}
template<bool input_requires_grad>
inline void backward(TensorAccessor<scalar_t, 3>* gInp_slice_ptr,
TensorAccessor<scalar_t, 3>& gGrid_slice,
const TensorAccessor<const scalar_t, 3>& gOut_slice,
const TensorAccessor<const scalar_t, 3>& inp_slice,
int64_t offset, const Vec& grid_x, const Vec& grid_y,
int64_t len) const {
Vec x = compute_W.unnormalize(grid_x);
Vec y = compute_H.unnormalize(grid_y);
Vec gx_mult = Vec(compute_W.scaling_factor);
Vec gy_mult = Vec(compute_H.scaling_factor);
auto ix = x.floor();
auto iy = y.floor();
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_x[4];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_y[4];
get_cubic_coefficients(coeff_x, x - ix);
get_cubic_coefficients(coeff_y, y - iy);
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_x_grad[4];
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
Vec coeff_y_grad[4];
get_cubic_coefficients_grad(coeff_x_grad, x - ix);
get_cubic_coefficients_grad(coeff_y_grad, y - iy);
auto gx = Vec(0), gy = Vec(0);
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
# pragma unroll
#endif
for (const auto c : c10::irange(C)) {
auto inp_slice_C_ptr = inp_slice[c].data();
auto gOut = Vec::loadu(gOut_slice[c].data() + offset, len);
for (const auto i : c10::irange(4)) {
for (const auto j : c10::irange(4)) {
auto xx = ix + Vec(-1 + i);
auto yy = iy + Vec(-1 + j);
if (input_requires_grad) {
auto gInp_slice_C_ptr = (*gInp_slice_ptr)[c].data();
add_value_bounded(gInp_slice_C_ptr, len, xx, yy, gOut * coeff_x[i] * coeff_y[j]);
}
auto val = get_value_bounded(inp_slice_C_ptr, xx, yy);
gx = gx - val * gOut * coeff_x_grad[i] * coeff_y[j];
gy = gy - val * gOut * coeff_y_grad[j] * coeff_x[i];
}