forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTensorAdvancedIndexing.cpp
1918 lines (1673 loc) · 74.7 KB
/
TensorAdvancedIndexing.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
// Indexing tensors by by tensors
//
// This corresponds to "advanced indexing" in NumPy. The two operations are:
//
// index(Tensor self, indices) -> Tensor
// index_put_(Tensor self, indices, value, accumulate=false)
//
// The index is a TensorList containg kLong, kBool or kByte tensors or nulls. Byte
// tensors (boolean masks) are expanded to long tensors via nonzero(). Null
// tensors signify that the dimension is not indexed.
//
// All indexes are broadcast together and iterated as *one*. From NumPy:
//
// result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, ..., i_M],
// ..., ind_N[i_1, ..., i_M]]
//
// Note 1: ByteTensors expand to index as many dimensions as there are in the
// mask.
//
// Note 2: The behavior is more complicated when the index tensors are not all
// adjacent (e.g. x[[0, 1], :, [2, 3]]). In this case, self and the index
// tensors are transposed to the front: x.transpose(1, 2)[[0, 1], [2, 3]]
//
// The code contains two implementations of indexing. The more efficient
// implementation treats indexing like an elementwise operation over the
// tensors `result`, `x`, `ind_1`, `ind_2`, etc. This implementation does
// not work for index_put_ with accumulate=True. The other implementation
// combines the indexed tensors into a single linear index that is used
// with Tensor.put_. This is used for index_put_ with accumulate=True.
//
// The more efficient implementation takes the following steps for the
// above operation:
//
// 1) Broadcast ind_1, ind_2, ind_3 together to a common shape
// 2) Record x.stride(i) for each indexed dimension `i`
// 3) Replace the indexed subspace of `x` with the shape of the corresponding
// subspace of `result` but with stride 0
// 4) Add dimensions of size 1 to the index tensors (ind_1, ind_2, etc.) so
// that their shape is compatible with the result shape
//
// The CPU or CUDA kernel then computes element-wise over the broadcasted
// and restrided result, x, ind_1, ind_2, etc.:
//
// result[...] = *(&x[...] +
// ind_1[...] * x.stride(1) +
// ind_2[...] * x.stride(2) +
// ...)
//
// where & and * represent the C-style address-of and indirection operations.
#include <ATen/native/TensorAdvancedIndexing.h>
#include <ATen/native/IndexKernel.h>
#include <ATen/native/IndexingUtils.h>
#include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/ExpandUtils.h>
#include <ATen/MemoryOverlap.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/BinaryOps.h>
#include <ATen/native/Copy.h>
#include <ATen/native/Resize.h>
#include <ATen/native/ScatterGatherChecks.h>
#include <ATen/Parallel.h>
#include <c10/util/irange.h>
#include <c10/util/Unroll.h>
#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
namespace at {
namespace meta {
native::SCATTER_GATHER_OP get_operator_enum(const c10::string_view reduce) {
if (reduce == "add") {
return native::SCATTER_GATHER_OP::REDUCE_ADD;
} else if (reduce == "multiply") {
return native::SCATTER_GATHER_OP::REDUCE_MULTIPLY;
} else {
TORCH_CHECK(false, "reduce argument must be either add or multiply.");
}
}
TORCH_META_FUNC(gather)
(const Tensor & self, int64_t dim, const Tensor & index, bool sparse_grad) {
const Tensor& result = maybe_get_output(0);
int64_t wrapped_dim = at::maybe_wrap_dim(dim, self.dim());
// Memory overlap checks need to be done after resizing (if required) is done.
// But it only makes sense to do these checks when result was defined, hence
// the boolean variable `check_result` here.
// For more details, see: https://github.com/pytorch/pytorch/pull/63312#discussion_r694794832
// and https://github.com/pytorch/pytorch/issues/63837
bool check_result = result.defined();
set_output(index.sizes(), self.options());
if (check_result) {
at::assert_no_internal_overlap(result);
at::assert_no_overlap(result, self);
at::assert_no_partial_overlap(result, index);
}
auto is_index_empty = index.numel() == 0;
if (!is_index_empty) {
TORCH_CHECK(
index.scalar_type() == at::ScalarType::Long,
"gather", "(): Expected dtype int64 for index"
);
}
if (is_index_empty) return;
at::native::gather_shape_check(self, wrapped_dim, index);
}
template <typename Meta>
void scatter_meta_impl(
Meta& meta,
const Tensor& self,
int64_t dim,
const Tensor& index,
const c10::optional<Tensor>& src = nullopt,
const c10::optional<c10::string_view> reduce = nullopt) {
int64_t wrapped_dim = at::maybe_wrap_dim(dim, self.dim());
at::native::scatter_gather_dtype_check("scatter", self, index, src);
at::native::scatter_shape_check(self, wrapped_dim, index, src);
auto output = meta.maybe_get_output(0);
if (output.defined()) {
at::assert_no_internal_overlap(output);
at::assert_no_overlap(output, index);
if (src.has_value()) {
at::assert_no_overlap(output, src.value());
}
}
meta.set_output(self.sizes(), self.options());
if (reduce.has_value()) {
// Check if we have a valid reduce operator.
get_operator_enum(reduce.value());
}
}
TORCH_META_FUNC2(scatter, src)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) {
scatter_meta_impl(*this, self, dim, index, src);
}
TORCH_META_FUNC2(scatter, value)
(const Tensor& self, int64_t dim, const Tensor& index, const Scalar& value) {
scatter_meta_impl(*this, self, dim, index);
}
TORCH_META_FUNC2(scatter, reduce)
(const Tensor& self,
int64_t dim,
const Tensor& index,
const Tensor& src,
const c10::string_view reduce) {
scatter_meta_impl(*this, self, dim, index, src, reduce);
}
TORCH_META_FUNC2(scatter, value_reduce)
(const Tensor& self,
int64_t dim,
const Tensor& index,
const Scalar& src,
const c10::string_view reduce) {
scatter_meta_impl(*this, self, dim, index, nullopt, reduce);
}
TORCH_META_FUNC(scatter_add)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) {
scatter_meta_impl(*this, self, dim, index, src, "add");
}
TORCH_PRECOMPUTE_META_FUNC(index_copy)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source) {
dim = maybe_wrap_dim(dim, self.dim());
const Tensor& result = maybe_get_output(0);
// Memory overlap checks need to be done after resizing (if required) is done.
// But it only makes sense to do these checks when result was defined, hence
// the boolean variable `check_result` here.
// For more details, see: https://github.com/pytorch/pytorch/pull/63312#discussion_r694794832
// and https://github.com/pytorch/pytorch/issues/63837
bool check_result = result.defined();
set_output(self.sizes(), self.options());
if (check_result) {
at::assert_no_internal_overlap(result);
at::assert_no_overlap(result, index);
at::assert_no_overlap(result, source);
}
TORCH_CHECK_INDEX(index.dim() < 2, "index_copy_(): Index should have dimension 1 or 0 (got ", index.dim(), ")");
int64_t numIndices = index.numel();
if (source.dim() == 0 && numIndices != 1) {
TORCH_CHECK_INDEX(false, "index_copy_(): When source is scalar, index should have one element (got ", numIndices, ")");
} else if ((source.dim() != self.dim()) && (source.dim() != 0 && self.dim() != 0)) {
TORCH_CHECK_INDEX(false, "index_copy_(): When source and destination are not scalars, their dimensionality must match. Source dimensionality (",
source.dim(), "), destination dimensionality (", self.dim(), ")");
}
TORCH_CHECK(index.scalar_type() == ScalarType::Long, "index_copy_(): Expected a long tensor for index, but got ", index.scalar_type());
TORCH_CHECK(self.scalar_type() == source.scalar_type(), "index_copy_(): self and source expected to have the same dtype, but got (self) ", self.scalar_type(), " and (source) ", source.scalar_type());
TORCH_CHECK(self.device() == source.device() && self.device() == index.device(),
"index_copy_(): self, index and source expected to be in the same device, but got (self) ",
self.device(), ", (index) ", index.device(), ", and (source) ", source.device());
// Check that source and destination slices have the same size
auto selfSlicedSizes = self.sizes().vec();
if (selfSlicedSizes.size() > 0) {
selfSlicedSizes.erase(selfSlicedSizes.begin() + dim);
}
auto sourceSlicedSizes = source.sizes().vec();
if (sourceSlicedSizes.size() > 0) {
sourceSlicedSizes.erase(sourceSlicedSizes.begin() + dim);
}
if (selfSlicedSizes.size() != sourceSlicedSizes.size() ||
!std::equal(selfSlicedSizes.begin(), selfSlicedSizes.end(),
sourceSlicedSizes.begin())) {
std::stringstream ss;
ss << "index_copy_(): Source/destination tensor must have same slice shapes. ";
ss << "Destination slice shape: " << selfSlicedSizes << " at dimension " << dim;
ss << " and source slice shape: " << sourceSlicedSizes << " at dimension 0.";
TORCH_CHECK(false, ss.str());
}
TORCH_CHECK_INDEX(source.dim() == 0 || numIndices == source.size(dim),
"index_copy_(): Number of indices (", numIndices, ") should be equal to source.size(dim) (", source.size(dim), ")");
return TORCH_PRECOMPUTE_STRUCT(index_copy)().set_dim(dim);
}
TORCH_PRECOMPUTE_META_FUNC(index_add)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Scalar& alpha) {
dim = maybe_wrap_dim(dim, self.dim());
auto numel = index.numel();
TORCH_CHECK_INDEX(index.dim() <= 1, "index_add_(): Index is supposed to be a vector, but got dim: ",
index.dim(), " with type: ", index.scalar_type(), " and size: ", index.sizes());
TORCH_CHECK(index.scalar_type() == ScalarType::Long || index.scalar_type() == ScalarType::Int,
"index_add_(): Expected dtype int32/int64 for index but got: ", index.scalar_type());
TORCH_CHECK(self.scalar_type() == source.scalar_type(),
"index_add_(): self (", self.scalar_type(), ") and source (", source.scalar_type(),
") must have the same scalar type");
TORCH_CHECK(dim == 0 || dim < source.dim(),
"index_add_(): Indexing dim ", dim, " is out of bounds of the source tensor with dim ",
source.dim());
TORCH_CHECK(numel == (source.dim() == 0 ? 1 : source.size(dim)),
"index_add_(): Number of indices (", numel, ") should be equal to source.size(dim): (",
source.size(dim), "), for dim: ", dim);
auto& result = maybe_get_output(0);
bool is_defined = result.defined();
set_output(self.sizes(), self.options());
if (is_defined) {
at::assert_no_internal_overlap(result);
at::assert_no_overlap(result, index);
at::assert_no_overlap(result, source);
}
// A hack to run TensorIterator checks in the meta function.
// See comment: https://github.com/pytorch/pytorch/pull/65993#discussion_r760307417
// TODO: (@krshrimali) Try inheriting from TensorIteratorBase instead.
if (result.device() == kMeta) {
auto selfSlice = result.select(dim, 0);
auto sourceSlice = source.select(dim, 0);
auto iter = TensorIterator::borrowing_binary_op(selfSlice, selfSlice, sourceSlice);
}
return TORCH_PRECOMPUTE_STRUCT(index_add)().set_dim(dim);
}
} // namespace meta
namespace native {
DEFINE_DISPATCH(index_stub);
DEFINE_DISPATCH(index_fill_stub);
DEFINE_DISPATCH(index_copy_stub);
DEFINE_DISPATCH(index_put_stub);
DEFINE_DISPATCH(index_put_with_sort_stub);
DEFINE_DISPATCH(put_stub);
DEFINE_DISPATCH(take_stub);
DEFINE_DISPATCH(masked_fill_stub);
REGISTER_NO_CPU_DISPATCH(index_put_with_sort_stub);
DEFINE_DISPATCH(masked_select_serial_stub);
DEFINE_DISPATCH(masked_select_stub);
DEFINE_DISPATCH(masked_scatter_stub);
DEFINE_DISPATCH(gather_stub);
DEFINE_DISPATCH(scatter_stub);
DEFINE_DISPATCH(scatter_fill_stub);
DEFINE_DISPATCH(scatter_add_stub);
DEFINE_DISPATCH(scatter_reduce_stub);
DEFINE_DISPATCH(scatter_scalar_reduce_stub);
static bool all_strides_match(TensorList tensors) {
TORCH_CHECK(tensors.size() >= 1);
auto strides = tensors[0].strides();
for (auto& tensor : tensors.slice(1)) {
if (!strides.equals(tensor.strides())) {
return false;
}
}
return true;
}
static std::string shapes_as_str(TensorList tensors) {
std::ostringstream os;
bool first = true;
for (auto& tensor : tensors) {
if (tensor.defined()) {
if (!first) {
os << ", ";
}
os << tensor.sizes();
first = false;
}
}
return os.str();
}
// Replace indexed dimensions in src with stride 0 and the size of the result tensor.
// The offset in these dimensions is computed by the kernel using the index tensor's
// values and the stride of src. The new shape is not meaningful. It's used to make
// the shape compatible with the result tensor.
static Tensor restride_src(const Tensor& src, int64_t dims_before, int64_t dims_indexed,
IntArrayRef replacement_shape) {
auto shape = DimVector(src.sizes());
auto strides = DimVector(src.strides());
int64_t end = dims_before + dims_indexed;
shape.erase(shape.begin() + dims_before, shape.begin() + end);
strides.erase(strides.begin() + dims_before, strides.begin() + end);
shape.insert(shape.begin() + dims_before, replacement_shape.begin(), replacement_shape.end());
strides.insert(strides.begin() + dims_before, replacement_shape.size(), 0);
return src.as_strided(shape, strides);
}
// Add dimensions of size 1 to an index tensor so that it can be broadcast to the result
// shape and iterated over element-wise like the result tensor and the restrided src.
static Tensor reshape_indexer(const Tensor& index, int64_t dims_before, int64_t dims_after) {
auto orig_shape = index.sizes();
auto shape = DimVector();
shape.append(dims_before, 1);
shape.append(orig_shape.begin(), orig_shape.end());
shape.append(dims_after, 1);
return index.reshape(shape);
}
AdvancedIndex::AdvancedIndex(const Tensor& src, TensorList indices_list)
{
int64_t element_size_bytes = src.element_size();
int64_t dims_before = 0, dims_after = 0, dims_indexed = 0;
IntArrayRef replacement_shape;
for (const auto dim : c10::irange(indices_list.size())) {
if (!indices_list[dim].defined()) {
if (dims_indexed == 0) {
dims_before++;
} else {
dims_after++;
}
} else {
dims_indexed++;
replacement_shape = indices_list[dim].sizes();
indexed_sizes.push_back(src.size(dim));
indexed_strides.push_back(src.stride(dim) * element_size_bytes);
}
}
// Check if the indexed subspace contains a dim of size 0, but the replacement
// shape does not. This implies that an index is out of bounds, because there
// is no number that's a valid index for an empty tensor. Normally, out of
// bounds is handled in the indexing kernel, but this case fails earlier in
// restride_src with an unhelpful error message.
if (std::find(indexed_sizes.begin(), indexed_sizes.end(), 0) != indexed_sizes.end() &&
std::find(replacement_shape.begin(), replacement_shape.end(), 0) == replacement_shape.end()) {
TORCH_CHECK_INDEX(false, "index is out of bounds for dimension with size 0");
}
this->dims_before = dims_before;
this->dims_after = dims_after;
this->src = restride_src(src, dims_before, dims_indexed, replacement_shape);
for (auto& index : indices_list) {
if (index.defined()) {
indices.push_back(reshape_indexer(index, dims_before, dims_after));
}
}
// For CUDA tensors, force all index tensors to have the same striding to
// simplify the CUDA kernel.
if (indices.size() >= 2 && this->src.device().type() == kCUDA) {
if (!all_strides_match(indices)) {
for (auto & indice : indices) {
indice = indice.contiguous();
}
}
}
}
static std::tuple<bool, Tensor> canDispatchToMaskedFill(const Tensor& self, const torch::List<c10::optional<at::Tensor>>& indices,
const Tensor& value){
if (!(value.numel() ==1 && value.device().is_cpu())){
return std::make_tuple(false,Tensor());
}
int64_t num_ind = 0;
Tensor mask;
auto self_device = self.device();
for (const c10::optional<Tensor> i: indices) {
if (!i.has_value() || !(*i).defined()){
num_ind++;
} else {
Tensor index = std::move(*i);
if ((index.scalar_type() != kByte && index.scalar_type() != kBool) ||
index.device() != self_device || mask.defined()){
return std::make_tuple(false, Tensor());
} else {
mask = index;
for (const auto j : c10::irange(index.dim())) {
int64_t srcIdx = num_ind + j;
TORCH_CHECK_INDEX(index.size(j) == self.size(srcIdx), "The shape of the mask ", index.sizes(), " at index ", j,
" does not match the shape of the indexed tensor ", self.sizes(), " at index ", srcIdx);
}
num_ind += mask.ndimension();
}
}
}
for (const auto i : c10::irange(num_ind, self.ndimension())) {
(void)i; //Suppress unused variable warning
mask = mask.unsqueeze(-1);
}
return std::make_tuple(true, mask);
}
static AdvancedIndex make_info(Tensor self, const torch::List<c10::optional<at::Tensor>>& orig) {
checkIndexTensorTypes(orig);
// first expand BoolTensor (masks) or ByteTensor (masks) into 1 or more LongTensors
auto indices = expandTensors(self, orig);
// next broadcast all index tensors together
try {
indices = expand_outplace(indices);
} catch (std::exception& e) {
TORCH_CHECK_INDEX(false, "shape mismatch: indexing tensors could not be broadcast together"
" with shapes ", shapes_as_str(indices));
}
// add missing null Tensors so that it matches self.dim()
while (indices.size() < (size_t)self.dim()) {
indices.emplace_back();
}
// if the non-null indices are not all adjacent, transpose self and indices
// together so that they're adjacent at the front
if (!hasContiguousSubspace(indices)) {
std::tie(self, indices) = transposeToFront(self, indices);
}
// Ensure indices are on the same device as self
for (auto & indice : indices) {
if (indice.defined() && indice.device() != self.device()) {
indice = indice.to(self.device());
}
}
return AdvancedIndex(self, indices);
}
static TensorIterator make_index_put_iterator(const AdvancedIndex& info, const Tensor& value) {
TORCH_CHECK(is_expandable_to(value.sizes(), info.src.sizes()), "shape mismatch: value tensor of shape ", value.sizes(),
" cannot be broadcast to indexing result of shape ", info.src.sizes());
TORCH_CHECK(value.scalar_type() == info.src.scalar_type(),
"Index put requires the source and destination dtypes match, "
"got ", info.src.scalar_type(), " for the destination "
"and ", value.scalar_type(), " for the source.");
TensorIteratorConfig config;
// info.src is restrided by restride_src with 0 strided dimensions
config.set_check_mem_overlap(false);
config.resize_outputs(false);
config.check_all_same_dtype(false);
config.add_output(info.src);
config.add_input(value);
for (auto& index : info.indices) {
config.add_input(index);
}
return config.build();
}
static TensorIterator make_index_iterator(const AdvancedIndex& info) {
TensorIteratorConfig config;
config.set_check_mem_overlap(false)
.check_all_same_dtype(false)
.declare_static_dtype_and_device(info.src.scalar_type(), info.src.device())
.add_owned_output(Tensor())
.add_input(info.src);
for (auto& index : info.indices) {
config.add_input(index);
}
return config.build();
}
static TensorIterator make_index_out_iterator(const AdvancedIndex& info, Tensor& result) {
TensorIteratorConfig config;
// info.src is a restrided view of result
config.set_check_mem_overlap(false)
.check_all_same_dtype(false)
.add_output(result)
.add_input(info.src);
for (auto& index : info.indices) {
config.add_input(index);
}
return config.build();
}
Tensor index(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) {
TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")");
auto info = make_info(self, indices);
auto iter = make_index_iterator(info);
index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides);
return iter.output();
}
Tensor quantized_index(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) {
TORCH_INTERNAL_ASSERT(
self.qscheme() == c10::kPerTensorAffine ||
self.qscheme() == c10::kPerTensorSymmetric,
"Indexing is only supported for per-Tensor quantized Tensors.");
// For now, this is a naive implementation which does dq -> index -> q.
// TODO(future PR): improve performance by removing the copies.
const auto& self_dq = self.dequantize();
TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")");
auto info = make_info(self_dq, indices);
auto iter = make_index_iterator(info);
index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides);
at::Tensor res = iter.output();
return at::quantize_per_tensor(
res, self.q_scale(), self.q_zero_point(), self.scalar_type());
}
Tensor& index_out(Tensor& result, const Tensor & self, const torch::List<c10::optional<Tensor>>& indices) {
TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")");
at::assert_no_internal_overlap(result);
at::assert_no_overlap(result, self);
// NOLINTNEXTLINE(performance-implicit-conversion-in-loop)
for (const c10::optional<Tensor>& index: indices) {
if (index.has_value()) {
at::assert_no_overlap(result, *index);
}
}
auto info = make_info(self, indices);
auto iter = make_index_out_iterator(info, result);
index_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides);
return result;
}
Tensor & put_(Tensor & self, const Tensor& index, const Tensor & source, const bool accumulate) {
// See note [Writing Nondeterministic Operations]
// Nondeterministic when index contains duplicate entries and we do not accumulate
// If we accumulate on GPU, we use atomicGPUAdd, which is non-deterministic
if (!accumulate || (accumulate && self.device().type() == DeviceType::CUDA)) {
at::globalContext().alertNotDeterministic("put_");
}
// Type and device checks
TORCH_CHECK(index.scalar_type() == ScalarType::Long, "put_(): Expected a long tensor for index, but got ", index.scalar_type())
TORCH_CHECK(self.scalar_type() == source.scalar_type(), "put_(): self and source expected to have the same dtype, but got self.dtype = ", self.scalar_type(), " and source.dtype = ", source.scalar_type());
TORCH_CHECK(self.device() == source.device() && self.device() == index.device(),
"put_(): self, index and source expected to be in the same device, but got self.device = ",
self.device(), ", index.device = ", index.device(), ", and source.device = ", source.device());
// index checks
TORCH_CHECK_INDEX(source.numel() == index.numel(), "put_(): Expected source and index to have the same number of elements, but got source.numel() = ", source.numel(), ", index.numel() = ", index.numel());
TORCH_CHECK_INDEX(!(self.numel() == 0 && index.numel() != 0), "put_(): Tried to put elements into an empty tensor");
at::assert_no_internal_overlap(self);
at::assert_no_overlap(self, index);
at::assert_no_overlap(self, source);
// Early return
if (index.numel() == 0) {
return self;
}
auto index_reshaped = index.reshape(source.sizes());
// Do not iterate over self, we will compute the offsets manually
auto iter = TensorIteratorConfig()
.set_check_mem_overlap(false)
.check_all_same_dtype(false)
.add_input(source)
.add_input(index_reshaped)
.build();
put_stub(iter.device_type(), iter, self, accumulate);
return self;
}
Tensor put(const Tensor & self, const Tensor& index, const Tensor & source, const bool accumulate) {
return self.clone(at::MemoryFormat::Preserve).put_(index, source, accumulate);
}
Tensor index_put(const Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, bool accumulate) {
return self.clone(at::MemoryFormat::Preserve).index_put_(indices, value, accumulate);
}
Tensor & _index_put_impl_(Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, const bool accumulate, const bool unsafe) {
TORCH_CHECK_INDEX(indices.size() <= (size_t)self.dim(), "too many indices for tensor of dimension ", self.dim(), " (got ", indices.size(), ")");
if (at::has_internal_overlap(self) == MemOverlap::YES) {
TORCH_WARN(
"Use of index_put_ on expanded tensors is deprecated. "
"Please clone() the tensor before performing this operation. "
"This also applies to advanced indexing e.g. tensor[indices] = tensor");
}
if (!accumulate) {
auto masked_fill_dispatch = canDispatchToMaskedFill(self, indices, value);
if (std::get<0>(masked_fill_dispatch)) {
return self.masked_fill_(std::get<1>(masked_fill_dispatch), value.item());
}
}
auto value_ = value;
if (value.device() != self.device() && value.numel() == 1 && value.dim() == 0) {
value_ = value.to(self.device());
}
at::assert_no_overlap(self, value);
// NOLINTNEXTLINE(performance-implicit-conversion-in-loop)
for (const c10::optional<Tensor>& index: indices) {
if (index.has_value()) {
at::assert_no_overlap(self, *index);
}
}
if (self.device().type() == DeviceType::CUDA && (accumulate || globalContext().deterministicAlgorithms())) {
TORCH_CHECK(value_.device() == self.device(), "expected device ", self.device(), " but got device ",
value_.device(), " for value tensor");
index_put_with_sort_stub(self.device().type(), self, indices, value_, accumulate, unsafe);
return self;
}
auto info = make_info(self, indices);
auto iter = make_index_put_iterator(info, value_);
index_put_stub(iter.device_type(), iter, info.indexed_sizes, info.indexed_strides, accumulate);
return self;
}
Tensor& take_out(const Tensor& self, const Tensor& index, Tensor& out) {
// Type and device checks
TORCH_CHECK(index.scalar_type() == ScalarType::Long, "take(): Expected a long tensor for index, but got ", index.scalar_type())
TORCH_CHECK(self.scalar_type() == out.scalar_type(), "take(): self and out expected to have the same dtype, but got self.dtype = ", self.scalar_type(), " and out.dtype = ", out.scalar_type());
TORCH_CHECK(self.device() == out.device() && self.device() == index.device(),
"take(): self, index and out expected to be in the same device, but got self.device = ",
self.device(), ", index.device = ", index.device(), ", and out.device = ", out.device());
// index checks
TORCH_CHECK_INDEX(!(self.numel() == 0 && index.numel() != 0), "take(): tried to take from an empty tensor");
at::assert_no_internal_overlap(out);
at::assert_no_overlap(out, index);
at::assert_no_overlap(out, self);
// Do not iterate over self, we will compute the offsets manually
// out is resized inside tensor_iterator
auto iter = TensorIteratorConfig()
.set_check_mem_overlap(false)
.check_all_same_dtype(false)
.add_output(out)
.add_input(index)
.build();
// Early return after out has been resized
if (index.numel() == 0) {
return out;
}
take_stub(iter.device_type(), iter, self);
return out;
}
Tensor take(const Tensor& self, const Tensor& index) {
auto out = at::empty(index.sizes(), self.options());
at::native::take_out(self, index, out);
return out;
}
Tensor & index_put_(Tensor & self, const torch::List<c10::optional<Tensor>>& indices, const Tensor & value, const bool accumulate) {
return at::_index_put_impl_(self, indices, value, accumulate, /*unsafe=*/false);
}
TORCH_IMPL_FUNC(index_copy_out)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Tensor& result) {
if (!result.is_same(self)) result.copy_(self);
// See Note [Enabling Deterministic Operations]
if (result.is_cuda() && globalContext().deterministicAlgorithms()){
torch::List<c10::optional<Tensor>> indices;
indices.reserve(dim + 1);
for (const auto i: c10::irange(dim)) {
(void)i;
indices.emplace_back();
}
indices.emplace_back(index);
result.index_put_(indices, source, false);
return;
}
// Handle the case when self / source is 0-dim
Tensor result_nonzero = result.dim() == 0 ? result.unsqueeze(0) : result;
Tensor source_nonzero = source.dim() == 0 ? source.unsqueeze(0) : source;
// The only difference between the following tensor iterator and that of index_fill_ is that
// this one has also source as an input. We should refactor it when if constexpr is available (C++17)
// Prepare `index` for TensorIterator.
// It is restrided to be broadcastable over `self` in TensorIterator.
auto index_sizes = std::vector<int64_t>(result_nonzero.dim(), 1);
auto index_strides = std::vector<int64_t>(result_nonzero.dim(), 0);
index_sizes[dim] = index.numel();
index_strides[dim] = (index.dim() > 0) ? index.stride(0) : 1; // `index` is 1d or scalar
auto index_restrided = index.as_strided(
index_sizes, index_strides);
// Prepare `result` for TensorIterator.
// Restride `result` to not advance in dimension `dim`.
// We do not use squash_dim here because `index` will
// need to advance in this dimension.
// Note that self_sizes[dim] is set to index.numel().
// This is done so that self_sizes[dim] and index_sizes[dim]
// match as required by TensorIterator (input shape should
// strictly broadcast over output shape, i.e.
// output.shape[i] >= input.shape[i] for i in range(dims)).
auto result_sizes = result_nonzero.sizes().vec();
auto result_strides = result_nonzero.strides().vec();
result_sizes[dim] = index.numel();
result_strides[dim] = 0;
auto result_restrided = result_nonzero.as_strided(result_sizes, result_strides);
auto iter = TensorIteratorConfig()
// We do not check for overlap because `result` is restrided
// with zero stride. Zero strides trigger memory overlap assert
// within TensorIterator.
.set_check_mem_overlap(false)
.check_all_same_dtype(false)
.resize_outputs(false)
.add_output(result_restrided)
.add_input(index_restrided)
.add_input(source_nonzero)
.build();
auto result_dim_size = result_nonzero.size(dim);
auto result_dim_stride = result_nonzero.stride(dim);
index_copy_stub(
iter.device_type(),
iter,
dim,
result_dim_size,
result_dim_stride);
}
TORCH_IMPL_FUNC(index_add_cpu_out)
(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& source, const Scalar& alpha, const Tensor& result) {
if (!result.is_same(self)) result.copy_(self);
auto numel = index.numel();
auto index_contig = index.contiguous();
if (result.dim() > 1) {
// Equivalent to:
// for (const auto i : c10::irange(numel)) {
// auto selfSlice = self.select(dim, index_data[i]);
// auto sourceSlice = source.select(dim, i);
// selfSlice.add_(sourceSlice);
// }
// But much faster as this reuses the iterator from add_
if (numel == 0) {
return;
}
auto selfSlice = result.select(dim, 0);
auto sourceSlice = source.select(dim, 0);
auto self_stride_bytes = result.stride(dim) * elementSize(result.scalar_type());
auto source_stride_bytes = source.stride(dim) * elementSize(source.scalar_type());
auto self_dim_size = result.size(dim);
auto iter = TensorIterator::borrowing_binary_op(selfSlice, selfSlice, sourceSlice);
AT_DISPATCH_INDEX_TYPES(index.scalar_type(), "index_add_cpu_", [&] () {
auto index_data = index_contig.data_ptr<index_t>();
for (const auto i : c10::irange(numel)) {
auto self_i = index_data[i];
TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_dim_size), "index out of range in self");
auto self_data = static_cast<char*>(selfSlice.data_ptr()) + self_i * self_stride_bytes;
auto source_data = static_cast<char*>(sourceSlice.data_ptr()) + i * source_stride_bytes;
iter.unsafe_replace_operand(0, self_data);
iter.unsafe_replace_operand(1, self_data);
iter.unsafe_replace_operand(2, source_data);
add_stub(iter.device_type(), iter, alpha);
}
});
}
else {
TORCH_CHECK(source.dim() <= 1, "source.dim() (", source.dim(), ") must one or zero for given self.dim() (", self.dim(), ")");
// explicitly capture all required variables to work around windows build
// TODO: fix this when windows can correctly capture variables in nested lambda
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16,
result.scalar_type(), "index_add_", [&result, &source, &dim, &index_contig, &numel, &alpha] {
auto alpha_value = alpha.to<scalar_t>();
auto result_stride = result.dim() == 0 ? 1 : result.stride(dim);
auto source_stride = source.dim() == 0 ? 1 : source.stride(dim);
// TODO: Maybe TensorAccessor can be used here?
auto* result_ptr = result.data_ptr<scalar_t>();
auto* source_ptr = source.data_ptr<scalar_t>();
AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_add_cpu_",
[&index_contig, &numel, &result, &result_ptr, &result_stride, &source_ptr, &source_stride, &alpha_value] {
auto index_data = index_contig.data_ptr<index_t>();
for (const auto i : c10::irange(numel)) {
auto self_i = index_data[i];
TORCH_CHECK_INDEX((self_i >= 0) && (self_i < result.numel()), "index out of range in self");
scalar_t *self_ip = result_ptr + self_i * result_stride;
*self_ip += *(source_ptr + i * source_stride) * alpha_value;
}
});
});
}
}
// Check that indices fall within dimension array size
// Avoid redispatch call to min/max
template <typename IndexType>
static void check_indexarray_range(
const IndexType* indices,
int64_t n,
IndexType indexing_axis_dim) {
for (const auto i : c10::irange(n)) {
auto idx = indices[i];
TORCH_CHECK(
0 <= idx && idx < indexing_axis_dim,
"INDICES element is out of DATA bounds, id=",
idx,
" axis_dim=",
indexing_axis_dim);
}
}
Tensor & index_select_out_cpu_dim1_(
Tensor & result_contig, const Tensor & self, const Tensor & index_contig) {
auto self_contig = self.contiguous();
const caffe2::TypeMeta dataType = self_contig.dtype();
size_t item_bytesize = dataType.itemsize();
auto out = static_cast<char*>(result_contig.data_ptr());
auto src_base = static_cast<const char*>(self_contig.data_ptr());
auto self_sizes = self_contig.sizes();
auto outer_dims_product = c10::size_to_dim_(1, self_sizes);
auto block_size = c10::size_from_dim_(2, self_sizes);
auto block_bytesize = block_size * item_bytesize;
auto src_indexing_axis_dim = self_sizes[1];
auto src_batch_bytesize = self_sizes[1] * block_bytesize;
auto N = index_contig.numel();
auto gathered_batch_bytesize = N * block_bytesize;
AT_DISPATCH_INDEX_TYPES(
index_contig.scalar_type(), "batch_index_select_compute", [&]() {
const auto* idxs = index_contig.data_ptr<index_t>();
check_indexarray_range<index_t>(idxs, N, src_indexing_axis_dim);
// Special-case single-float copy for efficiency
if (self.scalar_type() == ScalarType::Float && block_size == 1) {
for (const auto batch : c10::irange(outer_dims_product)) {
const float* src_floats =
(const float*)(src_base + batch * src_batch_bytesize);
float* dst_floats = (float*)(out + batch * gathered_batch_bytesize);
for (const auto i : c10::irange(N)) {
auto idx = idxs[i];
if (idx < 0) {
idx = idx + src_indexing_axis_dim;
}
dst_floats[i] = src_floats[idx];
}
}
} else {
// outer_dims_product specifies how many times we repeat inner dimensions,
// so we just iterate over it to cover all outer dimensions.
for (const auto batch : c10::irange(outer_dims_product)) {
for (const auto i : c10::irange(N)) {
auto idx = idxs[i];
if (idx < 0) {
idx = idx + src_indexing_axis_dim;
}
auto src = src_base + batch * src_batch_bytesize + idx * block_bytesize;
auto dst = out + batch * gathered_batch_bytesize + i * block_bytesize;
memcpy(dst, src, block_bytesize);
}
}
}
});
return result_contig;
}
Tensor & index_select_out_cpu_(const Tensor & self, int64_t dim, const Tensor & index, Tensor & result) {
if (self.is_quantized()) {
TORCH_CHECK(
self.qscheme() == kPerTensorAffine,
"Only per_tensor quantized quantized tensors are supported by index_select.")
}
dim = maybe_wrap_dim(dim, self.dim());
auto numel = index.numel();
TORCH_CHECK_INDEX(index.dim() <= 1, "index_select(): Index is supposed to be a vector");
TORCH_CHECK(index.scalar_type() == ScalarType::Long || index.scalar_type() == ScalarType::Int, "index_select(): Expected dtype int32 or int64 for index");
TORCH_CHECK(self.scalar_type() == result.scalar_type(),
"index_select(): self and result must have the same scalar type");
TORCH_CHECK(dim == 0 || dim < self.dim(),
"index_select(): Indexing dim ", dim, " is out of bounds of tensor");
at::assert_no_internal_overlap(result);
at::assert_no_overlap(result, self);
at::assert_no_overlap(result, index);
auto result_size = self.sizes().vec();
if (self.dim() > 0) {
result_size[dim] = numel;
}
at::native::resize_output(result, result_size);
auto index_contig = index.contiguous();
if (self.dim() > 1) {
if (numel == 0 || self.numel() == 0) {
return result;
}
if (dim == 1 && result.is_contiguous()) {
// fast pass
return index_select_out_cpu_dim1_(result, self, index_contig);
}
auto selfSlice = self.select(dim, 0);
auto resultSlice = result.select(dim, 0);
auto selfSlice_data = selfSlice.data_ptr();
auto resultSlice_data = resultSlice.data_ptr();
auto self_stride_bytes = self.stride(dim) * elementSize(self.scalar_type());
auto result_stride_bytes = result.stride(dim) * elementSize(result.scalar_type());
auto self_dim_size = self.size(dim);
auto slice_size = selfSlice.numel();
auto iter = TensorIteratorConfig()
.check_all_same_dtype(false)
.resize_outputs(false)
.add_output(resultSlice)
.add_input(selfSlice)
.build();
auto grain_size = at::internal::GRAIN_SIZE;
auto outer_loop =
// explicitly capture all required variables to work around windows build
// TODO: fix this when windows can correctly capture variables in nested lambda
[&index_contig, &iter, &self_dim_size, &selfSlice_data, &self_stride_bytes, &resultSlice_data,
&result_stride_bytes](int64_t start, int64_t end) {
auto sub_iter = TensorIterator(iter);
AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_",
[&index_contig, &start, &end, &sub_iter, &self_dim_size, &selfSlice_data, &self_stride_bytes,
&resultSlice_data, &result_stride_bytes] () {
auto index_data = index_contig.data_ptr<index_t>();
for (const auto i : c10::irange(start, end)) {
auto self_i = index_data[i];
TORCH_CHECK_INDEX((self_i >= 0) && (self_i < self_dim_size), "index out of range in self");
auto self_data = static_cast<char*>(selfSlice_data) + self_i * self_stride_bytes;
auto result_data = static_cast<char*>(resultSlice_data) + i * result_stride_bytes;
sub_iter.unsafe_replace_operand(0, result_data);
sub_iter.unsafe_replace_operand(1, self_data);
copy_stub(sub_iter.device_type(), sub_iter, false);
};
});
};
// parallel on inner loop in case the slice is large enough;
// otherwise parallel on outer loop
if (slice_size >= grain_size) {
outer_loop(0, numel);
} else {
// use a fast loop when self and result are contiguous and of the same data type
if (iter.is_contiguous() && self.scalar_type() == result.scalar_type()) {
auto slice_size_bytes = slice_size * elementSize(self.scalar_type());
// explicitly capture all required variables to work around windows build
// TODO: fix this when windows can correctly capture variables in nested lambda
at::parallel_for(0, numel, grain_size / slice_size,
[&index_contig, &slice_size_bytes, &self_dim_size, &selfSlice_data,
&self_stride_bytes, &resultSlice_data, &result_stride_bytes](int64_t start, int64_t end) {
AT_DISPATCH_INDEX_TYPES(index_contig.scalar_type(), "index_select_out_cpu_",
[&index_contig, &slice_size_bytes, &self_dim_size, &selfSlice_data,
&self_stride_bytes, &resultSlice_data, &result_stride_bytes, &start, &end] () {
auto index_data = index_contig.data_ptr<index_t>();
for (const auto i : c10::irange(start, end)) {