forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTensorShape.cpp
2728 lines (2400 loc) · 103 KB
/
TensorShape.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
#include <ATen/AccumulateType.h>
#include <ATen/ATen.h>
#include <ATen/ExpandUtils.h>
#include <ATen/InferSize.h>
#include <ATen/MemoryOverlap.h>
#include <ATen/NamedTensorUtils.h>
#include <ATen/core/DimVector.h>
#include <ATen/native/Copy.h>
#include <ATen/native/Resize.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/TypeProperties.h>
#include <ATen/native/TensorShape.h>
#include <ATen/native/cpu/CatKernel.h>
#include <ATen/native/cpu/StackKernel.h>
#include <ATen/native/cpu/SerialStackImpl.h>
#include <ATen/NativeFunctions.h>
#include <ATen/quantized/QTensorImpl.h>
#include <ATen/SparseTensorUtils.h>
#include <ATen/WrapDimUtils.h>
#include <c10/util/accumulate.h>
#include <c10/util/Exception.h>
#include <c10/util/irange.h>
#include <c10/util/Optional.h>
#include <c10/util/SmallVector.h>
#include <algorithm>
#include <cstdint>
#include <vector>
namespace at {
namespace native {
DEFINE_DISPATCH(cat_serial_stub);
DEFINE_DISPATCH(stack_serial_stub);
Tensor _reshape_from_tensor(const Tensor& self, const Tensor& shape_tensor) {
TORCH_CHECK(shape_tensor.dim() == 1);
std::vector<int64_t> shape;
auto accessor = shape_tensor.accessor<int64_t, 1>();
for (const auto i : c10::irange(shape_tensor.numel())) {
shape.push_back(accessor[i]);
}
return self.reshape(IntArrayRef(shape));
}
Tensor _shape_as_tensor(const Tensor& self) {
auto options = TensorOptions(at::kLong);
return at::tensor(self.sizes(), options);
}
Tensor& set_(Tensor& result, Storage source) {
int64_t new_size =
static_cast<int64_t>(source.nbytes() / result.dtype().itemsize());
return result.set_(source, 0, new_size, {});
}
// unify with cuda implementation? This is not done to avoid a dispatch in resize_impl_cpu_
Tensor& set_storage_cpu_(Tensor& result, Storage storage, int64_t storage_offset, IntArrayRef size, IntArrayRef stride) {
checkSetStorage(result, storage, storage_offset, size, stride);
result.unsafeGetTensorImpl()->set_storage_offset(storage_offset);
c10::optional<IntArrayRef> stride_opt = stride.data() != nullptr ?
c10::optional<IntArrayRef>(stride) : c10::nullopt;
at::native::resize_impl_cpu_(result.unsafeGetTensorImpl(), size, stride_opt);
return result;
}
Tensor& set_tensor_(Tensor& result, const Tensor& source) {
if (result.unsafeGetTensorImpl() != source.unsafeGetTensorImpl()) {
return result.set_(source.storage(), source.storage_offset(), source.sizes(), source.strides());
}
return result;
}
// this needs to be split along CPU/CUDA lines because we don't have a consistent
// way of getting the allocator to use for a device (c10::GetAllocator is not
// the same as at::cuda::getCUDADeviceAllocator().
Tensor& set_cpu_(Tensor& result) {
caffe2::TypeMeta dtype = result.dtype();
Storage storage(
Storage::use_byte_size_t(),
0,
c10::GetAllocator(kCPU),
true);
result.set_(storage, 0, {0}, {});
TORCH_INTERNAL_ASSERT(dtype == result.dtype());
return result;
}
Tensor sparse_broadcast_to(const Tensor& self, IntArrayRef size) {
TORCH_CHECK(self.is_sparse(), "input must be sparse tensor");
int64_t sparse_extra_ndim = size.size() - self.dim();
int64_t sparse_ndim = size.size() - self.dense_dim();
TORCH_CHECK(sparse_extra_ndim >= 0, "input not broadcastable to size with smaller dimensionality");
Tensor indices = self._indices();
Tensor values = self._values();
auto nnz = values.size(0);
std::vector<int64_t> broadcast_sizes;
std::vector<int64_t> broadcast_dense_sizes;
std::vector<int64_t> broadcast_dims;
std::vector<int64_t> unchanged_dims;
broadcast_sizes.reserve(sparse_ndim);
broadcast_dense_sizes.reserve(self.dense_dim() + 1);
broadcast_dims.reserve(self.sparse_dim());
unchanged_dims.reserve(self.sparse_dim());
int64_t nnz_factor = 1;
int64_t min_broadcast_dim = (sparse_extra_ndim > 0 ? 0: -1);
int64_t max_unchanged_dim = -1;
for (int64_t i=0; i<sparse_extra_ndim; i++) {
auto d = size[i];
nnz_factor *= d;
broadcast_sizes.emplace_back(d);
}
for (int64_t i=0; i<self.sparse_dim(); i++) {
auto d = size[sparse_extra_ndim + i];
if (self.size(i) != d) {
TORCH_CHECK(self.size(i) == 1,
"The expanded size of the tensor (",size[sparse_extra_ndim + i],") ",
"must match the existing size (",self.size(i),")");
nnz_factor *= d;
broadcast_sizes.emplace_back(d);
if (min_broadcast_dim == -1) {
min_broadcast_dim = sparse_extra_ndim + i;
}
broadcast_dims.emplace_back(i);
} else {
unchanged_dims.emplace_back(i);
max_unchanged_dim = sparse_extra_ndim + i;
}
}
// to_broadcast conserves is_coalesced property iff only the last
// sparse dimensions are expaned. Possible expansion of dense
// dimensions can be discarded as it does not affect the is_coalesce
// property.
bool is_coalesced = self.dim()==0 || (self.is_coalesced() && (max_unchanged_dim < min_broadcast_dim || min_broadcast_dim == -1));
broadcast_dense_sizes.emplace_back(nnz);
for (int64_t i=0; i<self.dense_dim(); i++) {
broadcast_dense_sizes.emplace_back(size[sparse_extra_ndim + self.sparse_dim() + i]);
}
std::vector<int64_t> new_indices_size{sparse_ndim, nnz * nnz_factor};
std::vector<int64_t> new_values_size(values.sizes().vec());
new_values_size[0] = new_indices_size[1];
Tensor new_values = values.expand(broadcast_dense_sizes).repeat_interleave(nnz_factor, 0);
Tensor new_indices = at::native::new_empty(indices, new_indices_size);
if (broadcast_sizes.size()>0) {
// ones(broadcast_sizes).nonzero() is equivalent to
// product(map(arange, broadcast_sizes)) but avoids creating
// auxilary arange tensors
Tensor broadcast_indices = at::native::new_ones(indices, broadcast_sizes).nonzero().transpose(0, 1).tile(nnz);
new_indices.narrow(0, 0, sparse_extra_ndim).copy_(broadcast_indices.narrow(0, 0, sparse_extra_ndim));
for (size_t i=0; i<broadcast_dims.size(); i++) {
int64_t j=broadcast_dims[i];
new_indices.select(0, sparse_extra_ndim + j).copy_(broadcast_indices.select(0, sparse_extra_ndim + i));
}
}
for (int64_t j:unchanged_dims) {
new_indices.select(0, sparse_extra_ndim + j).copy_(indices.select(0, j).repeat_interleave(nnz_factor));
}
return at::sparse_coo_tensor(new_indices, new_values, size)._coalesced_(is_coalesced);
}
Tensor broadcast_to(const Tensor& self, IntArrayRef size) {
return self.expand(size);
}
std::vector<Tensor> broadcast_tensors(TensorList tensors) {
return expand_outplace(tensors);
}
static bool should_skip(const Tensor& t) {
return t.numel() == 0 && t.dim() == 1;
}
Tensor & _cat_out_cpu(TensorList tensors, int64_t dim, Tensor& result) {
check_cat_no_zero_dim(tensors);
dim = legacy_cat_wrap_dim(dim, tensors);
// previously, size [0] tensors were the only possible empty tensors; thus, it wasn't possible
// to cat empty tensors unless all the other tensors were 1-dimensional, so we allowed these tensors
// to be "skipped". We maintain this behavior for backwards compatibility, but only for this specific
// size (i.e. other empty sizes are not skipped).
bool allContiguous = true;
// Inputs cannot alias the output tensor
for (const auto i : c10::irange(tensors.size())) {
auto lap = at::get_overlap_status(result, tensors[i]);
TORCH_CHECK(lap != at::MemOverlapStatus::PARTIAL &&
lap != at::MemOverlapStatus::FULL, 0,
"unsupported operation: the input tensors cannot refer to any of the "
"output memory locations. Found overlap in input tensor ", i);
}
at::assert_no_internal_overlap(result);
const Tensor* pnotSkippedTensor = [](const TensorList &tensors) -> const Tensor* {
for (auto const &tensor : tensors) {
if (should_skip(tensor)) {
continue;
}
// we've found a non-empty tensor
return &tensor;
}
return nullptr;
}(tensors);
if (!pnotSkippedTensor) {
// FIXME: warn if this is the case -- see comment about skipped
// tensors at top of function.
return result;
}
const Tensor& notSkippedTensor = *pnotSkippedTensor;
TORCH_CHECK(tensors.size() > 0, "torch.cat(): expected a non-empty list of Tensors");
TORCH_CHECK(dim <= notSkippedTensor.dim(), "torch.cat(): dimension ", dim, "out of range");
// when the input tensors are of the same size and strides,
// reuse the same iterator for all input tensors
bool reuse_iterator = true;
bool no_type_promotion = true;
// Check the type of the result
no_type_promotion = result.dtype() == notSkippedTensor.dtype();
// compute size of the result in the cat dimension
int64_t cat_dim_size = 0;
auto first_tensor_mem_format = tensors[0].suggest_memory_format();
for (const auto i : c10::irange(tensors.size())) {
auto const &tensor = tensors[i];
if (should_skip(tensor)) {
// don't use fast path for empty tensor
allContiguous = false;
continue;
}
check_cat_shape_except_dim(notSkippedTensor, tensor, dim, i);
cat_dim_size += tensor.sizes()[dim];
if (!tensor.is_contiguous(first_tensor_mem_format)) {
allContiguous = false;
}
if (tensor.sizes() != notSkippedTensor.sizes() ||
tensor.strides() != notSkippedTensor.strides()) {
reuse_iterator = false;
}
if (tensor.dtype() != notSkippedTensor.dtype()) {
no_type_promotion = false;
}
}
// compute the size of the result
auto result_size = notSkippedTensor.sizes().vec();
result_size[dim] = cat_dim_size;
// skip resizing if size of result is same as expected
// raise a warning while resizing if output has one or more elements
// See https://github.com/pytorch/pytorch/pull/62560#discussion_r687363362
// for understanding why at::native::resize_output is not called directly.
// if (at::native::resize_output_check(result, result_size)) {
// TODO: restore the above, see https://github.com/pytorch/pytorch/issues/64709
if (result.sizes() != result_size) {
result.resize_(result_size, first_tensor_mem_format);
}
if (result.numel() == 0) {
return result;
}
// fast path for single thread when both inputs and result are contiguous and not empty
allContiguous = allContiguous && result.is_contiguous(first_tensor_mem_format);
bool use_serial_kernel = result.numel() < at::internal::GRAIN_SIZE || at::get_num_threads() == 1;
ScalarType dtype = notSkippedTensor.scalar_type();
bool serial_dtype = (dtype == ScalarType::Double || dtype == ScalarType::Float || dtype == ScalarType::BFloat16);
if (use_serial_kernel && allContiguous && no_type_promotion && serial_dtype) {
cat_serial_stub(kCPU, result, tensors, dim);
return result;
}
int64_t offset = 0;
if (reuse_iterator &&
result.is_contiguous(first_tensor_mem_format) &&
no_type_promotion) {
const auto& source_slice = notSkippedTensor;
auto slice_dim_size = source_slice.sizes()[dim];
auto result_slice = result.narrow(dim, 0, slice_dim_size);
auto result_slice_data = result_slice.data_ptr();
auto result_stride_bytes = result.stride(dim) * elementSize(result.scalar_type());
auto iter = TensorIteratorConfig()
.set_check_mem_overlap(false) // Already checked above
.resize_outputs(false)
.add_output(result_slice)
.add_input(source_slice)
.enforce_safe_casting_to_output(true)
.build();
for (auto const &tensor : tensors) {
if (should_skip(tensor)) {
continue;
}
auto source_data = static_cast<char*>(tensor.data_ptr());
auto result_data = static_cast<char*>(result_slice_data) + offset * result_stride_bytes;
iter.unsafe_replace_operand(0, result_data);
iter.unsafe_replace_operand(1, source_data);
copy_stub(iter.device_type(), iter, false);
offset += slice_dim_size;
}
} else {
for (auto const &tensor: tensors) {
if (should_skip(tensor)) {
continue;
}
auto slice_dim_size = tensor.sizes()[dim];
auto result_slice = result.narrow(dim, offset, slice_dim_size);
auto iter = TensorIteratorConfig()
.set_check_mem_overlap(false) // Already checked above
.resize_outputs(false)
.add_output(result_slice)
.add_input(tensor)
.promote_inputs_to_common_dtype(true)
.cast_common_dtype_to_outputs(true)
.enforce_safe_casting_to_output(true)
.build();
copy_stub(iter.device_type(), iter, false);
offset += slice_dim_size;
}
}
return result;
}
Tensor _cat_cpu(TensorList tensors, int64_t dim) {
ScalarType high_type = result_type(tensors);
Tensor result = at::empty({0}, tensors[0].options().dtype(high_type));
return native::_cat_out_cpu(tensors, dim, result);
}
Tensor & cat_out(TensorList tensors, int64_t dim, Tensor & result) {
auto maybe_outnames = namedinference::compute_cat_outnames(tensors);
{
NoNamesGuard guard;
at::_cat_out(result, tensors, dim);
}
namedinference::propagate_names_if_nonempty(result, maybe_outnames);
return result;
}
Tensor& cat_out(TensorList tensors, Dimname dim, Tensor& result) {
TORCH_CHECK(!tensors.empty(), "expected a non-empty list of Tensors");
return at::cat_out(result, tensors, dimname_to_position(tensors[0], dim));
}
Tensor cat(TensorList tensors, Dimname dim) {
TORCH_CHECK(!tensors.empty(), "expected a non-empty list of Tensors");
return at::cat(tensors, dimname_to_position(tensors[0], dim));
}
// torch.concat, alias for torch.cat
Tensor& concat_out(TensorList tensors, Dimname dim, Tensor& result) {
return at::cat_out(result, tensors, dimname_to_position(tensors[0], dim));
}
Tensor concat(TensorList tensors, Dimname dim) {
return at::cat(tensors, dimname_to_position(tensors[0], dim));
}
Tensor & concat_out(TensorList tensors, int64_t dim, Tensor & result) {
return at::cat_out(result, tensors, dim);
}
Tensor concat(TensorList tensors, int64_t dim) {
return at::cat(tensors, dim);
}
static bool sizes_match_except(IntArrayRef s1, IntArrayRef s2, int64_t dim_except /* should already be wrapped */) {
if (s1.size() != s2.size()) {
return false;
}
for (const auto i : c10::irange(static_cast<int64_t>(s1.size()))) {
if (i != dim_except && s1[i] != s2[i]) {
return false;
}
}
return true;
}
// Check to see if the shape of tensors is compatible
// for being concatenated along a given dimension.
static void check_cat_sparse_dims(Tensor const &t,
int64_t pos /* used only for debug messages */,
IntArrayRef sizes,
int64_t wrapped,
int64_t sparse_dim,
int64_t dense_dim) {
TORCH_CHECK(t.is_sparse(),
"Concatenating sparse tensors, but a dense tensor was found at position ", pos, ".");
TORCH_CHECK(sizes_match_except(sizes, t.sizes(), wrapped),
"All tensors must have the same shape: ", sizes, " (except in the concatenating dimension),"
" but found shape: ", t.sizes(), " at position ", pos, ".");
TORCH_CHECK(t.sparse_dim() == sparse_dim && t.dense_dim() == dense_dim,
"All tensors must have the same sparse_dim and dense_dim: ", sparse_dim, ", ", dense_dim,
", but tensor at position ", pos, " has ", t.sparse_dim(), ", ", t.dense_dim(), ".");
}
static Tensor cat_sparse(TensorList tensors, int64_t dim) {
std::vector<Tensor> indices;
std::vector<Tensor> values;
int64_t wrapped = maybe_wrap_dim(dim, tensors[0].dim());
int64_t sparse_dim = tensors[0].sparse_dim();
int64_t dense_dim = tensors[0].dense_dim();
IntArrayRef sizes = tensors[0].sizes();
if (wrapped < sparse_dim) {
for (const auto i : c10::irange(tensors.size())) {
auto const &t = tensors[i];
check_cat_sparse_dims(t, i, sizes, wrapped, sparse_dim, dense_dim);
indices.push_back(t._indices());
values.push_back(t._values());
}
Tensor idxs = at::cat(indices, 1);
Tensor vals = at::cat(values, 0);
// We now need to move the indices of each
// input tensor up along `dim` by an appropriate amount.
// E.g., if t1 has indices [[2,3,4],[5,6,7]],
// and sizes [10, 7]
// then torch.cat((t1,t1,t1),1) should have indices
// [[2,3,4,2,3,4,2,3,4],[5,6,7,12,13,14,19,20,21]],
// so we need to increase idxs[1][3:6] by 7
// and idxs[1][6:9] by 14.
int64_t col = 0;
int64_t cumulative_offset = 0;
for (const auto i : c10::irange(tensors.size())) {
auto const &t = tensors[i];
int64_t this_piece_size = t._nnz();
// cumulative_offset is zero for the first piece, so
// don't waste time doing this operation unless i > 0.
if (i > 0) {
idxs[wrapped].narrow(0, col, this_piece_size) += cumulative_offset;
}
cumulative_offset += t.size(wrapped);
col += this_piece_size;
}
auto sizes_copy = sizes.vec();
sizes_copy[wrapped] = cumulative_offset;
return native::sparse_coo_tensor(
idxs,
vals,
sizes_copy,
optTypeMetaToScalarType(tensors[0].options().dtype_opt()),
tensors[0].options().layout_opt(),
tensors[0].options().device_opt(),
tensors[0].options().pinned_memory_opt());
}
else {
// Catting along a dense dimension requires us to create new values.
// For illustration, consider the sparse 3d tensors t1 and t2,
// given by t1 = [[[1,2],[3,4]], ... (zeros) ..., [[5,6],[7,8]]]
// and t2 = [... (zeros) ..., [[9, 10], [11,12]], ... (zeros) ...],
// Their concatenation along dimension 2 is:
// [[[1,2,0,0],[3,4,0,0]], ... (zeros) ..., [[0,0,9,10],[0,0,11,12]], ... (zeros) ..., [[5,6,0,0],[7,8,0,0]]]
//
// Their values tensors are, respectively,
// [[[1,2],[3,4]],[[5,6],[7,8]]] and [[[9,10],[11,12]]].
//
// and so the values tensor of their concatenation along dim 2 will be:
// [[[1,2,0,0],[3,4,0,0]],[[5,6,0,0],[7,8,0,0]],[[0,0,9,10],[0,0,11,12]]]
//
// which we can get by taking the values tensor of each tensor, catting it with zeros of the appropriate size on the left and right,
// and then catting all those results together.
// The dimension in each tensor's values object that corresponds to the overall dimension along which we're catting.
int64_t values_dim = wrapped - sparse_dim + 1;
// The final size along the catted dimension.
const int64_t total_size = std::accumulate(tensors.begin(), tensors.end(), static_cast<int64_t>(0), [values_dim](int64_t l, Tensor const &r) {
return l + r._values().size(values_dim);
});
auto zeros_sizes = tensors[0]._values().sizes().vec();
int64_t cumulative_size = 0;
std::vector<Tensor> vals_pieces;
std::vector<Tensor> idxs_pieces;
for (const auto i : c10::irange(tensors.size())) {
auto const &t = tensors[i];
check_cat_sparse_dims(t, i, sizes, wrapped, sparse_dim, dense_dim);
// dimension 0 of values corresponds to the number of values,
// rather than to any logical dimension of the sparse tensor.
zeros_sizes[0] = t._values().size(0);
zeros_sizes[values_dim] = cumulative_size;
cumulative_size += t._values().size(values_dim);
auto z1 = native::zeros(
zeros_sizes,
optTypeMetaToScalarType(t._values().options().dtype_opt()),
t._values().options().layout_opt(),
t._values().options().device_opt(),
t._values().options().pinned_memory_opt());
zeros_sizes[values_dim] = total_size - cumulative_size;
auto z2 = native::zeros(
zeros_sizes,
optTypeMetaToScalarType(t._values().options().dtype_opt()),
t._values().options().layout_opt(),
t._values().options().device_opt(),
t._values().options().pinned_memory_opt());
vals_pieces.push_back(native::cat({z1, t._values(), z2}, values_dim));
idxs_pieces.push_back(t._indices());
}
auto sizes_copy = sizes.vec();
sizes_copy[wrapped] = total_size;
// This can create an uncoalesced tensor
return native::sparse_coo_tensor(
native::cat(idxs_pieces, 1),
native::cat(vals_pieces),
sizes_copy,
optTypeMetaToScalarType(tensors[0].options().dtype_opt()),
tensors[0].options().layout_opt(),
tensors[0].options().device_opt(),
tensors[0].options().pinned_memory_opt());
}
}
Tensor cat(TensorList tensors, int64_t dim) {
if (tensors.size() > 0 &&
tensors[0].is_sparse()) {
return cat_sparse(tensors, dim);
}
auto maybe_outnames = namedinference::compute_cat_outnames(tensors);
Tensor result;
{
NoNamesGuard guard;
result = at::_cat(tensors, dim);
}
namedinference::propagate_names_if_nonempty(result, maybe_outnames);
return result;
}
Tensor block_diag(TensorList tensors) {
Tensor result;
if (tensors.size() == 0) {
result = at::empty({1, 0});
return result;
}
const Device& device = tensors[0].device();
for (const auto tensor_idx : c10::irange(tensors.size())) {
const Tensor& tensor = tensors[tensor_idx];
TORCH_CHECK(
tensor.device() == device,
"torch.block_diag: input tensors must all be on the same device.",
" Input 0 is on device ", device,
" and input ", tensor_idx, " is on device ", tensor.device()
);
}
ScalarType output_scalar_type = native::result_type(tensors);
int64_t result_dim0 = 0;
int64_t result_dim1 = 0;
std::vector<Tensor> tensors_2D(tensors.size());
// Sum the dimensions of the tensors, check tensor sizes,
// and expand all 0-D and 1-D tensors so that everything
// is 2-D
for (const auto tensor_idx : c10::irange(tensors.size())) {
const Tensor& tensor = tensors[tensor_idx];
int64_t ndims = tensor.dim();
TORCH_CHECK(
ndims <= 2,
"torch.block_diag: Input tensors must have 2 or fewer dimensions. Input ",
tensor_idx, " has ", ndims, " dimensions"
);
int64_t dim0 = 1;
int64_t dim1 = 1;
if (ndims == 2) {
dim0 = tensor.size(0);
dim1 = tensor.size(1);
tensors_2D[tensor_idx] = tensor;
} else if (ndims == 1) {
// Switching dim 0 to dim 1 is intentional
dim1 = tensor.size(0);
tensors_2D[tensor_idx] = tensor.expand({dim0, dim1});
} else {
tensors_2D[tensor_idx] = tensor.expand({dim0, dim1});
}
result_dim0 += dim0;
result_dim1 += dim1;
}
result = at::zeros(
{result_dim0, result_dim1},
tensors[0].options().dtype(output_scalar_type)
);
int64_t cur_dim0 = 0;
int64_t cur_dim1 = 0;
// Copy each tensor into the appropriate location in the result matrix
for (const auto& tensor : tensors_2D) {
int64_t dim0 = tensor.size(0);
int64_t dim1 = tensor.size(1);
result.slice(0, cur_dim0, cur_dim0+dim0).slice(1, cur_dim1, cur_dim1+dim1).copy_(tensor);
cur_dim0 += dim0;
cur_dim1 += dim1;
}
return result;
}
std::vector<Tensor> chunk(const Tensor& self, int64_t chunks, int64_t dim) {
TORCH_CHECK(self.dim() > 0,
"chunk expects at least a 1-dimensional tensor");
TORCH_CHECK(chunks > 0,
"chunk expects `chunks` to be greater than 0, got: ", chunks);
const auto dim_size = self.size(dim);
int64_t split_size = (dim_size + chunks - 1) / chunks;
// We need to call split_with_sizes in the case where split_size and dimension size are 0, because
// a call to split would discard the number of chunks (because we can have an arbitrary number of
// 0-sized chunks adding up to 0). So, call split_with_sizes with the correct number of chunks,
// eventually we will do this for all cases.
if (split_size == 0 && dim_size == 0) {
std::vector<int64_t> split_sizes(chunks, split_size);
split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size);
return self.split_with_sizes(split_sizes, dim);
} else {
return self.split(split_size, dim);
}
}
std::vector<Tensor> tensor_split(const Tensor& self, int64_t sections, int64_t dim) {
TORCH_CHECK(self.dim() > 0, "tensor_split expected at least a 1-dimensional tensor, but got a tensor with ", self.dim()," dims");
int64_t dim_ = maybe_wrap_dim(dim, self.dim());
TORCH_CHECK(sections > 0, "number of sections must be larger than 0, got ", sections);
const auto dim_size = self.size(dim_);
std::vector<Tensor> splits(sections);
int64_t min_split_size = dim_size / sections;
int64_t num_splits_one_extra = dim_size % sections;
int64_t start_idx = 0;
for (const auto split_idx : c10::irange(sections)) {
int64_t split_size = (split_idx < num_splits_one_extra) ? (min_split_size + 1) : min_split_size;
splits[split_idx] = at::slice(self, dim_, start_idx, start_idx + split_size);
start_idx += split_size;
}
return splits;
}
std::vector<Tensor> tensor_split(const Tensor& self, IntArrayRef indices, int64_t dim) {
TORCH_CHECK(self.dim() > 0, "tensor_split expected at least a 1-dimensional tensor, but got a tensor with ", self.dim()," dims");
int64_t dim_ = maybe_wrap_dim(dim, self.dim());
int64_t num_indices = indices.size();
std::vector<Tensor> splits(num_indices + 1);
int64_t start_idx = 0;
for (const auto split_idx : c10::irange(num_indices)) {
int64_t end_idx = indices[split_idx];
splits[split_idx] = at::slice(self, dim_, start_idx, end_idx);
start_idx = end_idx;
}
splits[num_indices] = at::slice(self, dim_, start_idx, self.size(dim_));
return splits;
}
std::vector<Tensor> tensor_split(const Tensor& self, const Tensor& tensor_indices_or_sections, int64_t dim) {
TORCH_CHECK(self.dim() > 0, "tensor_split expected at least a 1-dimensional tensor, but got a tensor with ", self.dim()," dims");
auto split_device = tensor_indices_or_sections.device();
TORCH_CHECK(split_device == kCPU,
"tensor_split expected tensor_indices_or_sections to be on cpu, but it's on ", split_device);
auto split_dtype = tensor_indices_or_sections.scalar_type();
TORCH_CHECK(split_dtype == at::kLong,
"tensor_split expected tensor_indices_or_sections to have dtype of long, but got ", split_dtype);
auto split_dim = tensor_indices_or_sections.dim();
TORCH_CHECK(split_dim == 1 || split_dim == 0,
"tensor_split expected tensor_indices_or_sections to be a zero-dimensional or one-dimensional tensor, but got a tensor with ", split_dim, " dims");
if (split_dim == 0) {
int64_t sections = tensor_indices_or_sections.item<int64_t>();
return self.tensor_split(sections, dim);
} else {
auto indices_data = tensor_indices_or_sections.data_ptr<int64_t>();
auto stride = tensor_indices_or_sections.stride(0);
auto numel = tensor_indices_or_sections.numel();
std::vector<int64_t> indices(numel);
for (const auto offset : c10::irange(numel)) {
// indices tensor could be non-contiguous
indices[offset] = *(indices_data + offset * stride);
}
return self.tensor_split(indices, dim);
}
}
std::vector<Tensor> unsafe_chunk(const Tensor& self, int64_t chunks, int64_t dim) {
TORCH_CHECK(self.dim() > 0,
"chunk expects at least a 1-dimensional tensor");
TORCH_CHECK(chunks > 0,
"chunk expects `chunks` to be greater than 0, got: ", chunks);
const auto dim_size = self.size(dim);
int64_t split_size = (dim_size + chunks - 1) / chunks;
// See the comment above in chunk(...)
if (split_size == 0 && dim_size == 0) {
std::vector<int64_t> split_sizes(chunks, split_size);
split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size);
return self.unsafe_split_with_sizes(split_sizes, dim);
} else {
return self.unsafe_split(split_size, dim);
}
}
Tensor diagflat(const Tensor& self, int64_t offset) {
return self.contiguous().view(-1).diag(offset);
}
Tensor diagonal(const Tensor& self, int64_t offset, int64_t dim1_, int64_t dim2_) {
int64_t nDims = self.dim();
int64_t dim1 = maybe_wrap_dim(dim1_, nDims);
int64_t dim2 = maybe_wrap_dim(dim2_, nDims);
TORCH_CHECK(dim1 != dim2, "diagonal dimensions cannot be identical ", dim1_, ", ", dim2_);
auto outnames = namedinference::compute_diagonal_outnames(self, dim1, dim2);
NoNamesGuard no_names_guard;
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
int64_t diag_size;
int64_t storage_offset = self.storage_offset();
// compute storage offset and size for the diagonal
// for positive values of offset (above the main diagonal)
// "leftmost columns" (along dim2) are dropped
// for negative values of offset (below the main diagonal)
// "topmost rows" (along dim1) are dropped.
// Note that we invert +/- in the second to absorb the negative
// sign in the offset.
if (offset >= 0) {
diag_size = std::max<int64_t>(std::min(self.size(dim1), self.size(dim2)-offset), 0);
} else {
diag_size = std::max<int64_t>(std::min(self.size(dim1)+offset, self.size(dim2)), 0);
}
// NumPy allows you to specify offsets "off the end"; let's just be careful not to
// set a ridiculous storage_offset in that case (technically it shouldn't matter
// because there are no elements in the tensor, but let's be kosher).
if (diag_size == 0) {
// skip
} else if (offset >= 0) {
storage_offset += offset * self.stride(dim2);
} else {
storage_offset -= offset * self.stride(dim1);
}
// construct new size and stride: we drop dim1 and dim2 (maximum first for not changing the index of the minimum)
// the new ("joint") dimension is appended to the end of the shape / stride to match numpy semantics
DimVector sizes(self.sizes().begin(), self.sizes().end());
DimVector strides(self.strides().begin(), self.strides().end());
sizes.erase(sizes.begin() + std::max(dim1, dim2));
strides.erase(strides.begin() + std::max(dim1, dim2));
sizes.erase(sizes.begin() + std::min(dim1, dim2));
strides.erase(strides.begin() + std::min(dim1, dim2));
sizes.push_back(diag_size);
strides.push_back(self.stride(dim1)+self.stride(dim2));
// return view with new parameters
auto result = self.as_strided(sizes, strides, storage_offset);
no_names_guard.reset();
namedinference::propagate_names_if_nonempty(result, outnames);
return result;
}
Tensor diagonal(const Tensor& self, Dimname outdim, Dimname dim1, Dimname dim2, int64_t offset) {
auto result = at::diagonal(
self,
offset,
dimname_to_position(self, dim1),
dimname_to_position(self, dim2));
// This is slower than it needs to be because there is no way to modify
// the names of a tensor in-place right now. In the future we should consider
// offering that functionality.
std::vector<Dimname> new_names = result.names().vec();
new_names[new_names.size() - 1] = outdim;
return result.refine_names(new_names);
}
Tensor diag_embed(const Tensor& self, int64_t offset, int64_t dim1_, int64_t dim2_) {
int64_t nDims = self.dim() + 1;
int64_t dim1 = maybe_wrap_dim(dim1_, nDims);
int64_t dim2 = maybe_wrap_dim(dim2_, nDims);
TORCH_CHECK(dim1 != dim2, "diagonal dimensions cannot be identical ", dim1_, ", ", dim2_);
int64_t new_dim_len = std::abs(offset) + self.size(-1);
auto sizes = self.sizes().vec();
sizes.pop_back();
sizes.insert(sizes.begin() + std::min(dim1, dim2), new_dim_len);
sizes.insert(sizes.begin() + std::max(dim1, dim2), new_dim_len);
auto result = at::zeros(sizes, self.options());
auto diag = result.diagonal(offset, dim1, dim2);
diag.copy_(self);
return result;
}
Tensor expand(const Tensor& self, IntArrayRef size, bool /*unused*/) {
TORCH_CHECK(size.size() >= (size_t)self.dim(),
"expand(", self.toString(), "{", self.sizes(), "}, size=", size,
"): the number of sizes provided (", size.size(), ") ",
"must be greater or equal to the number of dimensions in the tensor (",
self.dim(), ")");
auto expandedSizesAndStrides = inferExpandGeometry_dimvector(self.sizes(), self.strides(), size);
auto result = self.as_strided(
expandedSizesAndStrides.sizes, expandedSizesAndStrides.strides);
namedinference::propagate_names_for_expand(result, self);
return result;
}
Tensor expand_as(const Tensor& self, const Tensor& other) {
return self.expand(other.sizes());
}
Tensor sum_to_size(const Tensor& self, IntArrayRef size) {
TORCH_CHECK(is_expandable_to(size, self.sizes()),
"size {", size, "} is not expandable to size {", self.sizes(), "}.");
return sum_to(self, size);
}
// We currently do not support per-channel quant for unfold, diagonal, expand, permute.
// TODO: Make this an aten function and replace as_strided_qtensorimpl once that is done.
Tensor make_qtensor(const Tensor& self, IntArrayRef size, IntArrayRef stride, QuantizerPtr quantizer) {
auto result = at::detail::make_tensor<QTensorImpl>(
c10::TensorImpl::VIEW, Storage(self.storage()), self.key_set(), self.dtype(), quantizer);
setStrided(result, size, stride, self.storage_offset());
return result;
}
Tensor as_strided_tensorimpl(const Tensor& self, IntArrayRef size, IntArrayRef stride, optional<int64_t> storage_offset_) {
auto storage_offset = storage_offset_.value_or(self.storage_offset());
auto result = at::detail::make_tensor<TensorImpl>(
c10::TensorImpl::VIEW, Storage(self.storage()), self.key_set(), self.dtype());
setStrided(result, size, stride, storage_offset);
return result;
}
Tensor as_strided_qtensorimpl(const Tensor& self, IntArrayRef size, IntArrayRef stride, optional<int64_t> storage_offset_) {
auto storage_offset = storage_offset_.value_or(self.storage_offset());
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(
quantizer->qscheme() == QScheme::PER_TENSOR_AFFINE,
"Setting strides is possible only on uniformly quantized tensor");
auto result = at::detail::make_tensor<QTensorImpl>(
c10::TensorImpl::VIEW, Storage(self.storage()), self.key_set(), self.dtype(), quantizer);
setStrided(result, size, stride, storage_offset);
return result;
}
// This is an overloaded function similar to
// Tensor as_strided_qtensorimpl(const Tensor& self, IntArrayRef size, IntArrayRef stride, optional<int64_t> storage_offset_)
// and is currently not available through the dispatcher. The additional
// input, quantizer, is called by the select & slice methods.
// TODO: Make this function compatible with the dispatcher
Tensor as_strided_qtensorimpl(const Tensor& self, IntArrayRef size, IntArrayRef stride, optional<int64_t> storage_offset_,
QuantizerPtr quantizer) {
auto storage_offset = storage_offset_.value_or(self.storage_offset());
TORCH_CHECK(
(quantizer->qscheme() == QScheme::PER_TENSOR_AFFINE) ||
(quantizer->qscheme() == QScheme::PER_CHANNEL_AFFINE),
"Setting strides is possible only on uniformly or per channel quantized tensors");
auto result = at::detail::make_tensor<QTensorImpl>(
c10::TensorImpl::VIEW, Storage(self.storage()), self.key_set(), self.dtype(), quantizer);
setStrided(result, size, stride, storage_offset);
return result;
}
const Tensor &as_strided_(const Tensor& self, IntArrayRef size, IntArrayRef stride, optional<int64_t> storage_offset_) {
auto storage_offset = storage_offset_.value_or(self.storage_offset());
setStrided(self, size, stride, storage_offset);
return self;
}
Tensor narrow_copy_sparse(const Tensor& self, int64_t dim, int64_t start, int64_t length) {
int64_t allDim = self.dim();
int64_t end = start+length;
TORCH_CHECK(allDim > 0, "narrow() cannot be applied to a 0-dim tensor.");
TORCH_CHECK(dim >= 0 && dim < allDim,
"Dimension ", dim, " out of range. Expecting 0 <= dim < ", allDim, ".");
TORCH_CHECK(start >= 0 && length >= 0 && end <= self.size(dim),
"Invalid range to narrow. range(start, start+length) must be a subset of range(0, ", self.size(dim), ").")
Tensor indices = self._indices();
int64_t sparse_dim = self.sparse_dim();
std::vector<int64_t> new_sizes = self.sizes().vec();
new_sizes[dim] = length;
Tensor new_values;
Tensor new_indices;
if (dim < sparse_dim) {
Tensor mask = (indices[dim] >= start).__and__((indices[dim] < end));
new_indices = indices.masked_select(mask).view({sparse_dim, -1});
new_indices[dim].sub_(start);
Tensor nzIndices = mask.nonzero().view(-1);
new_values = self._values().index_select(0, nzIndices);
} else {
/* This means we are narrowing on a dense dim, which is in effect just a
regular narrow on _values() */
new_indices = indices;
int64_t dense_dim = dim - sparse_dim + 1;
new_values = self._values().narrow_copy(dense_dim, start, length);
}
auto newTensor = at::sparse_coo_tensor(new_indices, new_values, new_sizes);
return newTensor._coalesced_(self.is_coalesced());
}
Tensor& narrow_copy_dense_cpu_out(
const Tensor& self, int64_t dim, int64_t start, int64_t length, Tensor& output
) {
TORCH_CHECK(self.dim() > 0, "narrow() cannot be applied to a 0-dim tensor.");
TORCH_CHECK(self.dtype() == output.dtype());
auto self_contig = self.expect_contiguous();
const auto self_sizes = self_contig->sizes();
// wrap dim if negative and do bound check
if (dim < 0) {
dim = at::maybe_wrap_dim(dim, self_sizes.size());
} else {
TORCH_CHECK(dim < static_cast<int64_t>(self_sizes.size()));
}
// wrap start and do bound check
const auto cur_size = self_sizes[dim];
if (start != cur_size && start < 0) { // start being the end is valid, but
// not a valid dim specification.
start = at::maybe_wrap_dim(start, cur_size);
}
TORCH_CHECK(
length >= 0 && start <= cur_size - length,
"start (",
start,
") + length (",
length,
") exceeds dimension size (",
cur_size,
").");
// resize output
auto output_sizes = self_sizes.vec();
output_sizes[dim] = length;
at::native::resize_(output, output_sizes);
// NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions)
const int64_t unit = c10::size_from_dim_(dim + 1, self_sizes);
const int64_t num_blocks = c10::size_to_dim_(dim, self_sizes);
const auto itemsize = self_contig->dtype().itemsize();
// NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
size_t src_nbytes = itemsize * self_contig->numel();
// NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
size_t dst_nbytes = itemsize * output.numel();
size_t src_block_size = unit * self_sizes[dim];
size_t dst_block_size = unit * length;
if (num_blocks == 0 || dst_block_size == 0) {
return output;
}
char* src_bytes = static_cast<char*>(self_contig->data_ptr());
char* dst_bytes = static_cast<char*>(output.data_ptr());
size_t src_block_size_bytes = itemsize * src_block_size;
size_t dst_block_size_bytes = itemsize * dst_block_size;
size_t src_offset = unit * start;
char* src_offset_bytes = src_bytes + itemsize * src_offset;
char* dst_offset_bytes = dst_bytes;
for (const auto i : c10::irange(num_blocks)) {
char* local_src_offset_bytes = src_offset_bytes + i * src_block_size_bytes;
char* local_dst_offset_bytes = dst_offset_bytes + i * dst_block_size_bytes;
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
static_cast<void*>(local_src_offset_bytes + dst_block_size_bytes) <=
static_cast<void*>(src_bytes + src_nbytes));
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
static_cast<void*>(local_dst_offset_bytes + dst_block_size_bytes) <=
static_cast<void*>(dst_bytes + dst_nbytes));
memcpy(
local_dst_offset_bytes, local_src_offset_bytes, dst_block_size_bytes);
}
return output;
}
Tensor narrow_copy_dense(const Tensor& self, int64_t dim, int64_t start, int64_t length){
return self.narrow(dim, start, length).clone(at::MemoryFormat::Contiguous);
}
Tensor narrow_copy_dense_cpu(const Tensor& self, int64_t dim, int64_t start, int64_t length){
auto output = at::empty_like(self);
return narrow_copy_dense_cpu_out(self, dim, start, length, output);