forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTensorFactories.cpp
1568 lines (1344 loc) · 54.4 KB
/
TensorFactories.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/ATen.h>
#include <ATen/CPUGeneratorImpl.h>
#include <ATen/Dispatch.h>
#include <ATen/EmptyTensor.h>
#include <ATen/Parallel.h>
#include <ATen/MapAllocator.h>
#include <ATen/NativeFunctions.h>
#include <ATen/TracerMode.h>
#include <c10/core/ScalarType.h>
#include <c10/util/Deprecated.h>
#include <ATen/native/Math.h>
#include <ATen/native/Resize.h>
#include <ATen/native/TensorFactories.h>
#include <c10/core/TensorOptions.h>
#include <ATen/detail/CUDAHooksInterface.h>
#include <c10/util/Exception.h>
#include <c10/util/irange.h>
#include <ATen/NamedTensorUtils.h>
#include <ATen/native/UnaryOps.h>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <string>
namespace at {
namespace native {
namespace {
void window_function_checks(
const char* function_name,
const TensorOptions& options,
int64_t window_length) {
TORCH_CHECK(
options.layout() != kSparse,
function_name,
" is not implemented for sparse types, got: ",
options);
TORCH_CHECK(
at::isFloatingType(typeMetaToScalarType(options.dtype())) || at::isComplexType(typeMetaToScalarType(options.dtype())),
function_name,
" expects floating point dtypes, got: ",
options);
TORCH_CHECK(
window_length >= 0,
function_name,
" requires non-negative window_length, got window_length=",
window_length);
}
} // namespace
DEFINE_DISPATCH(complex_stub);
DEFINE_DISPATCH(polar_stub);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ arange ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor arange(const Scalar& end,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::arange(/*start=*/0, end, dtype, layout, device, pin_memory);
}
Tensor arange(const Scalar& start, const Scalar& end,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::arange(
start, end, /*step=*/1, dtype, layout, device, pin_memory);
}
Tensor arange(
const Scalar& start,
const Scalar& end,
const Scalar& step,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
bool set_to_integral_dtype = !options.has_dtype() &&
// bool inputs are considered integral
start.isIntegral(true) &&
end.isIntegral(true) &&
step.isIntegral(true);
Tensor result = set_to_integral_dtype
? at::empty({0}, options.dtype(at::ScalarType::Long))
: at::empty({0}, options);
return at::arange_out(result, start, end, step);
}
Tensor& arange_out(const Scalar& end, Tensor& result) {
return at::arange_out(result, /*start=*/0, end);
}
Tensor& arange_out(Tensor& result, const Scalar& start, const Scalar& end) {
return at::arange_out(result, start, end, /*step=*/1);
}
Tensor _dim_arange(const Tensor& like, int64_t dim) {
return at::arange(like.size(dim), like.options().dtype(at::kLong));
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ complex / polar ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void complex_check_floating(const Tensor& a, const Tensor& b) {
TORCH_CHECK((a.scalar_type() == kFloat || a.scalar_type() == kDouble) &&
(b.scalar_type() == kFloat || b.scalar_type() == kDouble),
"Expected both inputs to be Float or Double tensors but got ",
a.scalar_type(), " and ", b.scalar_type());
}
void complex_check_dtype(
const Tensor& result,
const Tensor& a,
const Tensor& b) {
complex_check_floating(a, b);
TORCH_CHECK(a.scalar_type() == b.scalar_type(),
"Expected object of scalar type ", a.scalar_type(),
" but got scalar type ", b.scalar_type(), " for second argument");
TORCH_CHECK(result.scalar_type() == toComplexType(a.scalar_type()),
"Expected object of scalar type ", toComplexType(a.scalar_type()),
" but got scalar type ", result.scalar_type(),
" for argument 'out'");
}
Tensor& complex_out(const Tensor& real, const Tensor& imag, Tensor& result) {
complex_check_dtype(result, real, imag);
auto iter = TensorIteratorConfig()
.add_output(result)
.add_input(real)
.add_input(imag)
.check_all_same_dtype(false)
.build();
complex_stub(iter.device_type(), iter);
return result;
}
Tensor complex(const Tensor& real, const Tensor& imag) {
complex_check_floating(real, imag);
c10::TensorOptions options = real.options();
options = options.dtype(toComplexType(real.scalar_type()));
Tensor result = at::empty(0, options);
return at::complex_out(result, real, imag);
}
Tensor& polar_out(const Tensor& abs, const Tensor& angle, Tensor& result) {
complex_check_dtype(result, abs, angle);
auto iter = TensorIteratorConfig()
.add_output(result)
.add_input(abs)
.add_input(angle)
.check_all_same_dtype(false)
.build();
polar_stub(iter.device_type(), iter);
return result;
}
Tensor polar(const Tensor& abs, const Tensor& angle) {
complex_check_floating(abs, angle);
c10::TensorOptions options = abs.options();
options = options.dtype(toComplexType(abs.scalar_type()));
Tensor result = at::empty(0, options);
return at::polar_out(result, abs, angle);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ empty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor empty_cpu(IntArrayRef size, c10::optional<ScalarType> dtype_opt, c10::optional<Layout> layout_opt,
c10::optional<Device> device_opt, c10::optional<bool> pin_memory_opt, c10::optional<c10::MemoryFormat> memory_format_opt) {
return at::detail::empty_cpu(size, dtype_opt, layout_opt, device_opt, pin_memory_opt, memory_format_opt);
}
Tensor empty(
IntArrayRef size,
c10::optional<DimnameList> names,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
optional<MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
if (!names.has_value()) {
return at::empty(size, options, optional_memory_format);
}
TORCH_CHECK(options.layout() == Layout::Strided,
"NYI: named tensors only support strided layout");
TORCH_CHECK(options.device().is_cpu() || options.device().is_cuda(),
"NYI: named tensors only support CPU and CUDA tensors");
auto result = at::empty(size, options, optional_memory_format);
internal_set_names_inplace(result, names);
return result;
}
Tensor empty_strided_cpu(IntArrayRef size, IntArrayRef stride, c10::optional<ScalarType> dtype_opt,
c10::optional<Layout> layout_opt, c10::optional<Device> device_opt, c10::optional<bool> pin_memory_opt) {
return at::detail::empty_strided_cpu(size, stride, dtype_opt, layout_opt, device_opt, pin_memory_opt);
}
Tensor& empty_out(IntArrayRef size,
c10::optional<c10::MemoryFormat> optional_memory_format,
Tensor& result) {
// Preferably, this argument would not be accepted by _out, but the code
// generator requires the out and non-out overloads to match exactly
TORCH_CHECK(
!optional_memory_format.has_value(),
"'memory_format' argument is incompatible with 'out' tensor argument");
check_size_nonnegative(size);
if (result.is_sparse()) {
result.sparse_resize_and_clear_(size, size.size(), 0);
} else {
result.resize_(size);
}
return result;
}
// Temporary type cast operators. These are needed to trace type-casts now since
// Type's are not supported in the IR. Instead, we call down to these
// specialized operators for each datatype.
// TODO: remove when we have Type support in the IR
#define DEFINE_CAST_OP(_1, n) \
Tensor _cast_##n(const Tensor& self, bool non_blocking) { \
if (self.scalar_type() == ScalarType::n) \
return self; \
return self.to(ScalarType::n, non_blocking); \
}
AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, DEFINE_CAST_OP)
#undef DEFINE_CAST_OP
Tensor empty_like(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options_ = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
TORCH_CHECK(
!(options_.has_memory_format() && optional_memory_format.has_value()),
"Cannot set memory_format both in TensorOptions and explicit argument; please delete "
"the redundant setter.");
TensorOptions options =
self.options()
.merge_in(options_)
.merge_memory_format(optional_memory_format);
TORCH_CHECK(
!(options.layout() != kStrided &&
optional_memory_format.has_value()),
"memory format option is only supported by strided tensors");
auto memory_format = options.memory_format_opt().value_or(MemoryFormat::Preserve);
Tensor result;
if (memory_format == MemoryFormat::Preserve) {
if (self.is_non_overlapping_and_dense()) {
result = at::empty_strided(self.sizes(), self.strides(), options.memory_format(c10::nullopt));
} else if (self.unsafeGetTensorImpl()->support_as_strided() && self.layout() == kStrided) {
// If input tensor is not dense and non-overlapping but strided, we will infer an output strides
// which keeps the layout permutation of the input tensor.
std::vector<int64_t> strides = infer_dense_strides(self.sizes(), self.strides());
// See Note [Explicit nullopt MemoryFormat argument]
result = at::empty_strided(self.sizes(), strides, options.memory_format(c10::nullopt));
} else {
// See Note [Explicit nullopt MemoryFormat argument]
result = at::empty(self.sizes(), options.memory_format(self.suggest_memory_format()), c10::nullopt);
}
} else {
// See Note [Explicit nullopt MemoryFormat argument]
result = at::empty(self.sizes(), options.memory_format(memory_format), c10::nullopt);
}
if (self.opt_names()) {
namedinference::propagate_names(result, self.names());
}
// never propagate Conjugate, Negative, and ZeroTensor dispatch key
result._set_conj(false);
result._set_neg(false);
result._set_zero(false);
return result;
}
Tensor empty_like_quantized(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options_ = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
TORCH_CHECK(
!(options_.has_memory_format() && optional_memory_format.has_value()),
"Cannot set memory_format both in TensorOptions and explicit argument; please delete "
"the redundant setter.");
TensorOptions options =
self.options()
.merge_in(options_)
.merge_memory_format(optional_memory_format);
TORCH_CHECK(
!(options.layout() != kStrided &&
optional_memory_format.has_value()),
"memory format option is only supported by strided tensors");
auto memory_format = options.memory_format_opt().value_or(MemoryFormat::Preserve);
// TODO: To support all features of MemoryFormat::Preserve we need to add
// _empty_affine_quantized_strided function and use it similarly to
// Tensor clone(const Tensor& src, c10::optional<c10::MemoryFormat> optional_memory_format)
// if (self.is_non_overlapping_and_dense()) -> _empty_affine_quantized_strided
if (memory_format == MemoryFormat::Preserve) {
memory_format = self.suggest_memory_format();
}
// Note [Explicit nullopt MemoryFormat argument]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Some functions which we call default the OPTIONAL MemoryFormat
// argument to something that's not nullopt. If we pass the
// MemoryFormat via TensorOptions, we must explicitly disable this
// defaulting process, by explicitly passing nullopt for the MemoryFormat
// argument. When codegen is adjusted so we can delete this argument from
// the method signature, the argument will just disappear entirely.
//
// BTW, there are a few places where the optional MemoryFormat is None,
// but I still pass in nullopt for robustness.
// We could check if dtype is still quantized? But then should we shift/scale
// the q_zero_point / q_scale or not?
TORCH_CHECK(!options.has_dtype() || options.dtype() == self.dtype(),
"It is currently not supported to specify a dtype that doesn't match "
"the input tensor's dtype via empty_like. Specified: ", options.dtype(),
" Input tensor's dtype: ", self.dtype());
auto qscheme = self.qscheme();
if (qscheme == kPerTensorAffine) {
return at::_empty_affine_quantized(self.sizes(), options.memory_format(memory_format),
self.q_scale(),
self.q_zero_point(),
// See Note [Explicit nullopt MemoryFormat argument]
c10::nullopt);
} else if (qscheme == kPerChannelAffine) {
// Copy the tensors with channels to avoid accidental overrides
return at::_empty_per_channel_affine_quantized(
self.sizes(),
self.q_per_channel_scales().clone(at::MemoryFormat::Preserve),
self.q_per_channel_zero_points().clone(at::MemoryFormat::Preserve),
self.q_per_channel_axis(),
options.memory_format(memory_format),
// See Note [Explicit nullopt MemoryFormat argument]
c10::nullopt);
} else {
TORCH_CHECK(false, "Unsupported qscheme: ", toString(qscheme));
}
}
Tensor new_empty(
const Tensor& self,
IntArrayRef size,
c10::optional<ScalarType> dtype_opt,
c10::optional<Layout> layout_opt,
c10::optional<Device> device_opt,
c10::optional<bool> pin_memory_opt
) {
auto dtype = dtype_opt.has_value() ? dtype_opt : optTypeMetaToScalarType(self.options().dtype_opt());
auto layout = layout_opt.has_value() ? layout_opt : self.options().layout_opt();
auto device = device_opt.has_value() ? device_opt : self.options().device_opt();
auto pin_memory = pin_memory_opt.has_value() ? pin_memory_opt : self.options().pinned_memory_opt();
return at::empty(size, dtype, layout, device, pin_memory, c10::nullopt);
}
Tensor new_empty_strided(
const Tensor& self,
IntArrayRef size,
IntArrayRef stride,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory
) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
return at::empty_strided(size, stride, self.options().merge_in(options));
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ eye ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor eye(int64_t n,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// the default value of `m` equals to `n`
return native::eye(n, n, dtype, layout, device, pin_memory);
}
Tensor eye(int64_t n, int64_t m,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto tensor = at::empty({0}, options); // to be resized
return at::eye_out(tensor, n, m);
}
Tensor& eye_out_cpu(int64_t n, Tensor& result) {
// the default value of `m` equals to `n`
return native::eye_out_cpu(n, n, result);
}
Tensor& eye_out_cpu(int64_t n, int64_t m, Tensor& result) {
TORCH_CHECK(n >= 0, "n must be greater or equal to 0, got ", n);
TORCH_CHECK(m >= 0, "m must be greater or equal to 0, got ", m);
result.resize_({n, m});
result.zero_();
int64_t sz = std::min<int64_t>(n, m);
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(at::ScalarType::Half, at::ScalarType::Bool, result.scalar_type(), "eye", [&]() -> void {
scalar_t* result_data = result.data_ptr<scalar_t>();
at::parallel_for(0, sz, internal::GRAIN_SIZE, [&](int64_t p_begin, int64_t p_end) {
for (const auto i : c10::irange(p_begin, p_end))result_data[i*(result.strides()[0] + result.strides()[1])] = 1;
});
});
return result;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ full ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
namespace {
// Performs dtype inference for full
TensorOptions infer_full_options(
const Scalar& fill_value,
const TensorOptions& options) {
if (!options.has_dtype()) {
if (fill_value.isBoolean()) {
return options.dtype(at::kBool);
} else if (fill_value.isIntegral(false)) {
return options.dtype(at::kLong);
} else if (fill_value.isComplex()) {
auto scalar_type = (get_default_dtype() == ScalarType::Double) ?
ScalarType::ComplexDouble :
ScalarType::ComplexFloat;
return options.dtype(scalar_type);
} else {
return options.dtype(get_default_dtype());
}
}
return options;
}
} // anonymous namespace
Tensor full(IntArrayRef size, const Scalar& fill_value,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
TORCH_CHECK(options.layout() != kSparse,
"full(...) is not implemented for sparse layout");
auto result = at::empty(size, infer_full_options(fill_value, options));
return result.fill_(fill_value);
}
Tensor& full_out(IntArrayRef size, const Scalar& fill_value, Tensor& result) {
TORCH_CHECK(!result.is_sparse(),
"full(...) is not implemented for sparse layout");
result.resize_(size);
return result.fill_(fill_value);
}
Tensor full_like(
const Tensor& self,
const Scalar& fill_value,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty_like(self, options, optional_memory_format);
return result.fill_(fill_value);
}
Tensor new_full(
const Tensor& self,
IntArrayRef size,
const Scalar& fill_value,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory
) {
Tensor r = self.new_empty(size, TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory));
r.fill_(fill_value);
return r;
}
namespace {
TensorOptions linspace_logspace_infer_options(
const Scalar& start,
const Scalar& end,
const TensorOptions& options,
const char* fn_name) {
if (start.isComplex() || end.isComplex()) {
const auto default_complex_dtype = c10::get_default_complex_dtype();
if (options.has_dtype()) {
auto dtype = c10::typeMetaToScalarType(options.dtype());
TORCH_CHECK(at::isComplexType(dtype),
fn_name, ": inferred dtype ", default_complex_dtype, " can't be safely cast to passed dtype ", dtype);
} else {
return options.dtype(default_complex_dtype);
}
}
return options.has_dtype() ? options : options.dtype(c10::get_default_dtype());
}
} // anonymous namespace
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linspace ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor linspace(
const Scalar& start,
const Scalar& end,
int64_t steps,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
TORCH_CHECK(steps >= 0, "number of steps must be non-negative");
auto result_options = linspace_logspace_infer_options(start, end, options, "torch.linspace()");
Tensor result = at::empty({steps}, result_options);
return at::linspace_out(result, start, end, steps);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ logspace ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor logspace(
const Scalar& start,
const Scalar& end,
int64_t steps,
double base,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
TORCH_CHECK(steps >= 0, "number of steps must be non-negative");
auto result_options = linspace_logspace_infer_options(start, end, options, "torch.logspace()");
Tensor result = at::empty({steps}, result_options);
return at::logspace_out(result, start, end, steps, base);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ones ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor ones(IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::full(size, /*fill_value=*/1., dtype, layout, device, pin_memory);
}
Tensor& ones_out(IntArrayRef size, Tensor& result) {
return native::full_out(size, /*fill_value=*/1., result);
}
Tensor ones_like(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
auto result = at::empty_like(self, dtype, layout, device, pin_memory, optional_memory_format);
return result.fill_(1.);
}
Tensor new_ones(
const Tensor& self,
IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
Tensor r = self.new_empty(size, TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory));
r.fill_(1.);
return r;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ scalar_tensor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor scalar_tensor(const Scalar& s,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
if (options.device() == at::kCPU) {
// This is a fast track to skip device dispatch for making scalar tensor on CPU.
// See https://github.com/pytorch/pytorch/pull/29915 for more detailed perf
// difference.
// In the future when we remove the overhead of device dispatch, we'll happily
// revert this to following:
// auto result = at::empty({}, options);
at::tracer::impl::NoTracerDispatchMode tracer_guard;
at::AutoDispatchBelowAutograd mode;
auto result = empty_cpu({}, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
at::native::fill_(result, s);
return result;
}
return at::empty({}, options).fill_(s);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rand ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor rand(IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::rand(size, static_cast<c10::optional<Generator>>(c10::nullopt), dtype, layout, device, pin_memory);
}
Tensor rand(IntArrayRef size, c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty(size, options);
return result.uniform_(0, 1, generator);
}
Tensor& rand_out(IntArrayRef size, Tensor& result) {
return native::rand_out(size, c10::nullopt, result);
}
Tensor& rand_out(IntArrayRef size, c10::optional<Generator> generator, Tensor& result) {
result.resize_(size);
return result.uniform_(0, 1, generator);
}
Tensor rand_like(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty_like(self, options, optional_memory_format);
return result.uniform_(0, 1, c10::nullopt);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ randint ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor randint(int64_t high, IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::randint(high, size, c10::nullopt /* generator*/, dtype, layout, device, pin_memory);
}
Tensor randint(
int64_t high,
IntArrayRef size,
c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::randint(0, high, size, generator, dtype, layout, device, pin_memory);
}
Tensor randint(
int64_t low,
int64_t high,
IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::randint(low, high, size, c10::nullopt, dtype, layout, device, pin_memory);
}
Tensor randint(
int64_t low,
int64_t high,
IntArrayRef size,
c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty(size, options);
return result.random_(low, high, generator);
}
Tensor& randint_out(int64_t high, IntArrayRef size, Tensor& result) {
return native::randint_out(high, size, c10::nullopt, result);
}
Tensor& randint_out(int64_t high,
IntArrayRef size,
c10::optional<Generator> generator,
Tensor& result) {
result.resize_(size);
return result.random_(0, high, generator);
}
Tensor& randint_out(int64_t low, int64_t high, IntArrayRef size, Tensor& result) {
return native::randint_out(low, high, size, c10::nullopt, result);
}
Tensor& randint_out(int64_t low,
int64_t high,
IntArrayRef size,
c10::optional<Generator> generator,
Tensor& result) {
result.resize_(size);
return result.random_(low, high, generator);
}
Tensor randint_like(
const Tensor& self,
int64_t high,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty_like(self, options, optional_memory_format);
return result.random_(0, high, c10::nullopt);
}
Tensor randint_like(
const Tensor& self,
int64_t low,
int64_t high,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty_like(self, options, optional_memory_format);
return result.random_(low, high, c10::nullopt);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ randn ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor randn(IntArrayRef size,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::randn(size, static_cast<c10::optional<Generator>>(c10::nullopt), dtype, layout, device, pin_memory);
}
Tensor randn(IntArrayRef size, c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty(size, options);
return result.normal_(0, 1, generator);
}
Tensor& randn_out(IntArrayRef size, Tensor& result) {
return native::randn_out(size, c10::nullopt, result);
}
Tensor& randn_out(IntArrayRef size, c10::optional<Generator> generator, Tensor& result) {
result.resize_(size);
return result.normal_(0, 1, generator);
}
Tensor normal(double mean, double std, IntArrayRef size,
c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty(size, options);
return result.normal_(mean, std, generator);
}
Tensor& normal_out(double mean, double std,
IntArrayRef size, c10::optional<Generator> generator, Tensor& result) {
result.resize_(size);
return result.normal_(mean, std, generator);
}
Tensor randn_like(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto result = at::empty_like(self, options, optional_memory_format);
return result.normal_(0, 1, c10::nullopt);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ randperm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
namespace {
template <typename scalar_t>
void randperm_cpu(Tensor& result, int64_t n, CPUGeneratorImpl* generator) {
scalar_t *r__data = result.data_ptr<scalar_t>();
result.resize_({n});
int64_t r__stride_0 = result.stride(0);
at::parallel_for(0, n, internal::GRAIN_SIZE,
[&r__data, &r__stride_0](int64_t p_begin, int64_t p_end) {
for (const auto i : c10::irange(p_begin, p_end)) {
r__data[i*r__stride_0] = static_cast<scalar_t>(i);
}
});
for(int64_t i = 0; i < n - 1; i++)
{
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.rand)
int64_t z = generator->random() % (n-i);
scalar_t sav = r__data[i*r__stride_0];
r__data[i*r__stride_0] = r__data[(z+i)*r__stride_0];
r__data[(z+i)*r__stride_0] = sav;
}
}
} // namespace
Tensor randperm(int64_t n,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return native::randperm(n, c10::nullopt, dtype, layout, device, pin_memory);
}
Tensor randperm(int64_t n, c10::optional<Generator> generator,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
if (!dtype.has_value()) {
dtype = ScalarType::Long;
}
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto tensor = at::empty(n, options);
return at::randperm_out(tensor, n, generator);
}
Tensor& randperm_out(int64_t n, Tensor& result) {
return at::randperm_out(result, n, c10::nullopt);
}
Tensor& randperm_out_cpu(int64_t n, c10::optional<Generator> generator, Tensor& result) {
TORCH_CHECK(n >= 0, "n must be non-negative, got", n);
TORCH_CHECK(!generator.has_value() || (generator.has_value() && result.device() == generator->device()), "Expected a '", result.device(), "' generator device but found '", generator->device(), "'");
check_supported_max_int_with_precision(n, result);
result.resize_({n});
auto gen = get_generator_or_default<CPUGeneratorImpl>(generator, detail::getDefaultCPUGenerator());
// See Note [Acquire lock when using random generators]
std::lock_guard<std::mutex> lock(gen->mutex_);
AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::Half, result.scalar_type(), "randperm", [&]() -> void {
randperm_cpu<scalar_t>(result, n, gen);
});
return result;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ range ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor range(
const Scalar& start,
const Scalar& end,
const Scalar& step,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
Tensor result = at::empty({0}, options);
return at::range_out(result, start, end, step);
}
Tensor range(
const Scalar& start,
const Scalar& end,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory) {
return at::native::range(start, end, 1, dtype, layout, device, pin_memory);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ triangle ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor tril_indices_cpu(
int64_t row, int64_t col, int64_t offset, c10::optional<ScalarType> dtype_opt,
c10::optional<Layout> layout_opt, c10::optional<Device> device_opt, c10::optional<bool> pin_memory_opt) {
if (!dtype_opt.has_value()) {
dtype_opt = ScalarType::Long;
}
check_args(row, col, layout_opt);
auto tril_size = get_tril_size(row, col, offset);
// create an empty Tensor with correct size
auto result = at::native::empty_cpu({2, tril_size}, dtype_opt, layout_opt, device_opt, pin_memory_opt);
// The following three approaches result in very little performance
// differences. Hence, the 2nd option is taken for simpler code, and to return
// contiguous tensors. Refer to #14904 for more details.
//
// 1. sequential RAM access: fill row coordinates first, then columns. This
// results in two for-loop and more arithmetic operations.
//
// 2. interleaved RAM access: fill in index coordinates one by one, which
// jumps between the two output Tensor rows in every iteration.
//
// 3. sequential RAM + transpose: create an n X 2 Tensor, fill the Tensor
// sequentially, and then transpose it.
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, result.scalar_type(), "tril_indices", [&]() -> void {
// fill the Tensor with correct values
scalar_t* result_data = result.data_ptr<scalar_t>();
int64_t i = 0;