luclima commited on
Commit
6d3dafd
·
verified ·
1 Parent(s): d306868

Upload folder using huggingface_hub (part 22)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. western_ai/usa/pytorch/aten/src/ATen/CPUApplyUtils.h +351 -0
  2. western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.cpp +311 -0
  3. western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.h +49 -0
  4. western_ai/usa/pytorch/aten/src/ATen/DLConvertor.cpp +560 -0
  5. western_ai/usa/pytorch/aten/src/ATen/DLConvertor.h +84 -0
  6. western_ai/usa/pytorch/aten/src/ATen/DTensorState.cpp +17 -0
  7. western_ai/usa/pytorch/aten/src/ATen/DTensorState.h +34 -0
  8. western_ai/usa/pytorch/aten/src/ATen/Device.h +2 -0
  9. western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.cpp +154 -0
  10. western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.h +126 -0
  11. western_ai/usa/pytorch/aten/src/ATen/DeviceGuard.h +41 -0
  12. western_ai/usa/pytorch/aten/src/ATen/DimVector.h +2 -0
  13. western_ai/usa/pytorch/aten/src/ATen/Dispatch.cpp +15 -0
  14. western_ai/usa/pytorch/aten/src/ATen/Dispatch.h +798 -0
  15. western_ai/usa/pytorch/aten/src/ATen/Dispatch_v2.h +177 -0
  16. western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.cpp +107 -0
  17. western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.h +36 -0
  18. western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.cpp +483 -0
  19. western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.h +166 -0
  20. western_ai/usa/pytorch/aten/src/ATen/ExpandBase.h +30 -0
  21. western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.cpp +230 -0
  22. western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.h +547 -0
  23. western_ai/usa/pytorch/aten/src/ATen/Formatting.h +1 -0
  24. western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.cpp +31 -0
  25. western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.h +46 -0
  26. western_ai/usa/pytorch/aten/src/ATen/FunctionalInverses.cpp +467 -0
  27. western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.cpp +140 -0
  28. western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.h +285 -0
  29. western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.cpp +940 -0
  30. western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.h +481 -0
  31. western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.cpp +425 -0
  32. western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.h +58 -0
  33. western_ai/usa/pytorch/aten/src/ATen/Generator.h +2 -0
  34. western_ai/usa/pytorch/aten/src/ATen/InferSize.h +128 -0
  35. western_ai/usa/pytorch/aten/src/ATen/InitialTensorOptions.h +15 -0
  36. western_ai/usa/pytorch/aten/src/ATen/Layout.h +2 -0
  37. western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.cpp +378 -0
  38. western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.h +25 -0
  39. western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.cpp +158 -0
  40. western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.h +161 -0
  41. western_ai/usa/pytorch/aten/src/ATen/LegacyBatchingRegistrations.cpp +1291 -0
  42. western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.cpp +26 -0
  43. western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.h +26 -0
  44. western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.cpp +294 -0
  45. western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.h +183 -0
  46. western_ai/usa/pytorch/aten/src/ATen/LinalgBackend.h +31 -0
  47. western_ai/usa/pytorch/aten/src/ATen/MapAllocator.cpp +644 -0
  48. western_ai/usa/pytorch/aten/src/ATen/MapAllocator.h +147 -0
  49. western_ai/usa/pytorch/aten/src/ATen/MatrixRef.h +109 -0
  50. western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.cpp +114 -0
western_ai/usa/pytorch/aten/src/ATen/CPUApplyUtils.h ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/CollapseDims.h>
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/TensorUtils.h>
6
+ #include <c10/util/irange.h>
7
+ #include <cstring>
8
+ #include <limits>
9
+
10
+ namespace at {
11
+
12
+ /*
13
+ * The basic strategy for apply is as follows:
14
+ *
15
+ * 1. Starting with the outermost index, loop until we reach a dimension where
16
+ * the data is no longer contiguous, i.e. the stride at that dimension is not
17
+ * equal to the size of the tensor defined by the outer dimensions. Let's call
18
+ * this outer (contiguous) tensor A. Note that if the Tensor is contiguous, then
19
+ * A is equal to the entire Tensor. Let's call the inner tensor B.
20
+ *
21
+ * 2. We loop through the indices in B, starting at its outermost dimension. For
22
+ * example, if B is a 2x2 matrix, then we do:
23
+ *
24
+ * B[0][0]
25
+ * B[0][1]
26
+ * B[1][0]
27
+ * B[1][1]
28
+ *
29
+ * We set the offset into the underlying storage as (storageOffset + stride_B *
30
+ * index_B), i.e. basically we compute the offset into the storage as we would
31
+ * normally for a Tensor. But because we are guaranteed the subsequent data is
32
+ * contiguous in memory, we can simply loop for sizeof(A) iterations and perform
33
+ * the operation, without having to follow the order described by the strides of
34
+ * A.
35
+ *
36
+ * 3. As an optimization, we merge dimensions of A that are contiguous in
37
+ * memory. For example, if A is a 3x3x3x3 tensor narrowed from a 3x3x4x3 tensor,
38
+ * then the first two dimensions can be merged for the purposes of APPLY,
39
+ * reducing the number of nested loops.
40
+ */
41
+
42
+ inline Tensor sort_strides(Tensor& tensor_) {
43
+ IntArrayRef strides = tensor_.strides();
44
+ std::vector<int64_t> indices;
45
+ indices.reserve(tensor_.ndimension());
46
+ for (const auto i : c10::irange(tensor_.ndimension())) {
47
+ indices.push_back(i);
48
+ }
49
+ std::sort(indices.begin(), indices.end(), [&strides](int64_t i1, int64_t i2) {
50
+ return strides[i1] > strides[i2];
51
+ });
52
+ Tensor tensor = tensor_.permute(indices);
53
+ return tensor;
54
+ }
55
+
56
+ template <typename T, int N>
57
+ struct strided_tensor_iter_fixed {
58
+ public:
59
+ T* data_ = NULL;
60
+ int64_t dim_ = 0;
61
+
62
+ // NOLINTNEXTLINE(*array*)
63
+ int64_t counter_[N] = {0};
64
+ // NOLINTNEXTLINE(*array*)
65
+ int64_t sizes_[N] = {0};
66
+ // NOLINTNEXTLINE(*array*)
67
+ int64_t strides_[N] = {0};
68
+
69
+ strided_tensor_iter_fixed(strided_tensor_iter_fixed const&) = delete;
70
+ strided_tensor_iter_fixed& operator=(strided_tensor_iter_fixed const& x) =
71
+ delete;
72
+ strided_tensor_iter_fixed(strided_tensor_iter_fixed&&) noexcept = default;
73
+ strided_tensor_iter_fixed& operator=(strided_tensor_iter_fixed&& x) noexcept =
74
+ default;
75
+ ~strided_tensor_iter_fixed() noexcept = default;
76
+ strided_tensor_iter_fixed(
77
+ Tensor& tensor,
78
+ [[maybe_unused]] bool sort_strides = false)
79
+ : data_(tensor.data_ptr<T>()) {
80
+ std::memset(counter_, 0, sizeof(int64_t) * N);
81
+ if (tensor.dim() > 0) {
82
+ std::memcpy(
83
+ sizes_, tensor.sizes().data(), tensor.dim() * sizeof(int64_t));
84
+ std::memcpy(
85
+ strides_, tensor.strides().data(), tensor.dim() * sizeof(int64_t));
86
+ }
87
+ dim_ = std::get<1>(collapse_dims(sizes_, strides_, tensor.ndimension()));
88
+ }
89
+ };
90
+
91
+ template <typename T>
92
+ struct strided_tensor_iter {
93
+ private:
94
+ public:
95
+ T* data_ = NULL;
96
+ int64_t dim_;
97
+
98
+ std::vector<int64_t> counter_;
99
+ std::vector<int64_t> sizes_;
100
+ std::vector<int64_t> strides_;
101
+
102
+ strided_tensor_iter(strided_tensor_iter const&) = delete;
103
+ strided_tensor_iter& operator=(strided_tensor_iter const& x) = delete;
104
+ strided_tensor_iter(strided_tensor_iter&&) noexcept = default;
105
+ strided_tensor_iter& operator=(strided_tensor_iter&&) noexcept = default;
106
+ ~strided_tensor_iter() noexcept = default;
107
+ strided_tensor_iter(Tensor& tensor)
108
+ : data_(tensor.data_ptr<T>()),
109
+ dim_(tensor.ndimension()),
110
+ counter_(dim_, 0),
111
+ sizes_(tensor.sizes().vec()),
112
+ strides_(tensor.strides().vec()) {
113
+ dim_ = std::get<1>(collapse_dims(sizes_.data(), strides_.data(), dim_));
114
+ }
115
+ };
116
+
117
+ inline bool _all_equal_numel(at::ArrayRef<Tensor> tensors) {
118
+ if (tensors.empty())
119
+ return true;
120
+ int64_t all_numel = tensors[0].numel();
121
+ for (const auto i : c10::irange(1, tensors.size())) {
122
+ if (tensors[i].numel() != all_numel)
123
+ return false;
124
+ }
125
+ return true;
126
+ }
127
+
128
+ inline std::string _all_equal_numel_error(at::ArrayRef<Tensor> tensors) {
129
+ std::ostringstream oss;
130
+ oss << "inconsistent tensor size, expected ";
131
+ for (size_t i = 0; i < tensors.size() - 1; i++) {
132
+ oss << tensors[i].sizes() << ", ";
133
+ }
134
+ oss << "and " << tensors[tensors.size() - 1].sizes()
135
+ << " to have the same number of elements, but got ";
136
+ for (size_t i = 0; i < tensors.size() - 1; i++) {
137
+ oss << tensors[i].numel() << ", ";
138
+ }
139
+ oss << "and " << tensors[tensors.size() - 1].numel()
140
+ << " elements respectively";
141
+ return oss.str();
142
+ }
143
+
144
+ inline bool _apply_preamble(ArrayRef<Tensor> tensors) {
145
+ checkDeviceType("CPU_tensor_apply", tensors, kCPU);
146
+ checkLayout("CPU_tensor_apply", tensors, kStrided);
147
+ TORCH_CHECK(_all_equal_numel(tensors), _all_equal_numel_error(tensors));
148
+ // An empty tensor has no elements
149
+ for (auto& t : tensors)
150
+ if (t.numel() == 0)
151
+ return false;
152
+ return true;
153
+ }
154
+
155
+ inline int64_t _max_dim_tensors(ArrayRef<Tensor> tensors) {
156
+ int64_t dim = 0;
157
+ for (auto& t : tensors)
158
+ dim = std::max(dim, t.ndimension());
159
+ return dim;
160
+ }
161
+
162
+ inline void iterate(int64_t /*size*/) {}
163
+
164
+ template <typename Arg, typename... Args>
165
+ inline void iterate(int64_t size, Arg& iter, Args&... iter_tail) {
166
+ iter.counter_[iter.dim_ - 1] += size;
167
+ iter.data_ = iter.data_ + size * iter.strides_[iter.dim_ - 1];
168
+ iterate(size, iter_tail...);
169
+ }
170
+
171
+ inline bool iterate_continue() {
172
+ return true;
173
+ }
174
+
175
+ template <typename Arg, typename... Args>
176
+ inline bool iterate_continue(Arg& iter, Args&... iter_tail) {
177
+ return iter.counter_[iter.dim_ - 1] < iter.sizes_[iter.dim_ - 1] &&
178
+ iterate_continue(iter_tail...);
179
+ }
180
+
181
+ inline int64_t max_iterate_size() {
182
+ return std::numeric_limits<int64_t>::max();
183
+ }
184
+
185
+ template <typename Arg, typename... Args>
186
+ inline int64_t max_iterate_size(Arg& iter, Args&... iter_tail) {
187
+ return std::min(
188
+ (iter.sizes_[iter.dim_ - 1] - iter.counter_[iter.dim_ - 1]),
189
+ max_iterate_size(iter_tail...));
190
+ }
191
+
192
+ inline void iterate_overflow() {}
193
+
194
+ template <typename Arg, typename... Args>
195
+ inline void iterate_overflow(Arg& iter, Args&... iter_tail) {
196
+ if (iter.counter_[iter.dim_ - 1] == iter.sizes_[iter.dim_ - 1]) {
197
+ for (int64_t i = iter.dim_ - 1; i > 0; i--) {
198
+ if (iter.counter_[i] == iter.sizes_[i]) {
199
+ iter.counter_[i] = 0;
200
+ iter.counter_[i - 1]++;
201
+ iter.data_ = iter.data_ - (iter.sizes_[i] * iter.strides_[i]) +
202
+ iter.strides_[i - 1];
203
+ }
204
+ }
205
+ }
206
+ iterate_overflow(iter_tail...);
207
+ }
208
+
209
+ inline void forward(int64_t /*offset*/) {}
210
+
211
+ template <typename Arg, typename... Args>
212
+ inline void forward(int64_t offset, Arg& iter, Args&... iter_tail) {
213
+ int64_t multi = offset;
214
+ for (int64_t i = iter.dim_ - 1; i >= 0; i--) {
215
+ int64_t inc = multi % iter.sizes_[i];
216
+ multi = multi / iter.sizes_[i];
217
+ iter.data_ = iter.data_ + inc * iter.strides_[i];
218
+ iter.counter_[i] += inc;
219
+ }
220
+ forward(offset, iter_tail...);
221
+ }
222
+
223
+ inline int64_t max_dim() {
224
+ return 0;
225
+ }
226
+
227
+ template <typename Arg, typename... Args>
228
+ inline int64_t max_dim(Arg& iter, Args&... iter_tail) {
229
+ return std::max(iter.dim_, max_dim(iter_tail...));
230
+ }
231
+
232
+ inline void apply_op() {}
233
+
234
+ template <typename Op, typename... Args>
235
+ inline void apply_op(
236
+ int64_t numel,
237
+ int64_t offset,
238
+ const Op& op,
239
+ Args... iters) {
240
+ // For 0-dim tensors
241
+ if (numel == 1 && max_dim(iters...) == 0) {
242
+ op(*iters.data_...);
243
+ return;
244
+ }
245
+ if (offset > 0)
246
+ forward(offset, iters...);
247
+ // Splitting this into chunks helps the compiler create faster assembly
248
+ for (int64_t i = 0; i < numel;) {
249
+ for (; iterate_continue(iters...) && i < numel;) {
250
+ op(*iters.data_...);
251
+ iterate(1, iters...);
252
+ i++;
253
+ }
254
+ iterate_overflow(iters...);
255
+ }
256
+ }
257
+
258
+ /*
259
+ Apply a pointwise operator to sequence of tensors
260
+
261
+ The calling convention for op is a function/functor that takes the same
262
+ number of pointers of type scalar as the number of given tensors. For example,
263
+ to compute a = b * c, op would be of the form:
264
+ [](scalar* a_val, const scalar* b_val, const scalar* c_val) { a_val[0] =
265
+ b_val[0] * c_val[0]; };
266
+ */
267
+
268
+ template <typename scalar1, typename scalar2, typename Op>
269
+ inline void CPU_tensor_apply2(Tensor tensor1, Tensor tensor2, const Op op) {
270
+ if (!_apply_preamble({tensor1, tensor2}))
271
+ return;
272
+ if (_max_dim_tensors({tensor1, tensor2}) <= 8) {
273
+ apply_op(
274
+ tensor1.numel(),
275
+ 0,
276
+ op,
277
+ strided_tensor_iter_fixed<scalar1, 8>(tensor1),
278
+ strided_tensor_iter_fixed<scalar2, 8>(tensor2));
279
+ } else {
280
+ apply_op(
281
+ tensor1.numel(),
282
+ 0,
283
+ op,
284
+ strided_tensor_iter<scalar1>(tensor1),
285
+ strided_tensor_iter<scalar2>(tensor2));
286
+ }
287
+ }
288
+
289
+ template <typename scalar1, typename scalar2, typename scalar3, typename Op>
290
+ inline void CPU_tensor_apply3(
291
+ Tensor tensor1,
292
+ Tensor tensor2,
293
+ Tensor tensor3,
294
+ const Op op) {
295
+ if (!_apply_preamble({tensor1, tensor2, tensor3}))
296
+ return;
297
+ if (_max_dim_tensors({tensor1, tensor2, tensor3}) <= 8) {
298
+ apply_op(
299
+ tensor1.numel(),
300
+ 0,
301
+ op,
302
+ strided_tensor_iter_fixed<scalar1, 8>(tensor1),
303
+ strided_tensor_iter_fixed<scalar2, 8>(tensor2),
304
+ strided_tensor_iter_fixed<scalar3, 8>(tensor3));
305
+ } else {
306
+ apply_op(
307
+ tensor1.numel(),
308
+ 0,
309
+ op,
310
+ strided_tensor_iter<scalar1>(tensor1),
311
+ strided_tensor_iter<scalar2>(tensor2),
312
+ strided_tensor_iter<scalar3>(tensor3));
313
+ }
314
+ }
315
+
316
+ template <
317
+ typename scalar1,
318
+ typename scalar2,
319
+ typename scalar3,
320
+ typename scalar4,
321
+ typename Op>
322
+ inline void CPU_tensor_apply4(
323
+ Tensor tensor1,
324
+ Tensor tensor2,
325
+ Tensor tensor3,
326
+ Tensor tensor4,
327
+ const Op op) {
328
+ if (!_apply_preamble({tensor1, tensor2, tensor3, tensor4}))
329
+ return;
330
+ if (_max_dim_tensors({tensor1, tensor2, tensor3, tensor4}) <= 8) {
331
+ apply_op(
332
+ tensor1.numel(),
333
+ 0,
334
+ op,
335
+ strided_tensor_iter_fixed<scalar1, 8>(tensor1),
336
+ strided_tensor_iter_fixed<scalar2, 8>(tensor2),
337
+ strided_tensor_iter_fixed<scalar3, 8>(tensor3),
338
+ strided_tensor_iter_fixed<scalar4, 8>(tensor4));
339
+ } else {
340
+ apply_op(
341
+ tensor1.numel(),
342
+ 0,
343
+ op,
344
+ strided_tensor_iter<scalar1>(tensor1),
345
+ strided_tensor_iter<scalar2>(tensor2),
346
+ strided_tensor_iter<scalar3>(tensor3),
347
+ strided_tensor_iter<scalar4>(tensor4));
348
+ }
349
+ }
350
+
351
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.cpp ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/CPUGeneratorImpl.h>
2
+ #include <ATen/Utils.h>
3
+ #include <ATen/core/MT19937RNGEngine.h>
4
+ #include <algorithm>
5
+
6
+ namespace at {
7
+
8
+ namespace detail {
9
+
10
+ /**
11
+ * CPUGeneratorImplStateLegacy is a POD class needed for memcpys
12
+ * in torch.get_rng_state() and torch.set_rng_state().
13
+ * It is a legacy class and even though it is replaced with
14
+ * at::CPUGeneratorImpl, we need this class and some of its fields
15
+ * to support backward compatibility on loading checkpoints.
16
+ */
17
+ struct CPUGeneratorImplStateLegacy {
18
+ /* The initial seed. */
19
+ uint64_t the_initial_seed;
20
+ int left; /* = 1; */
21
+ int seeded; /* = 0; */
22
+ uint64_t next;
23
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
24
+ uint64_t state[at::MERSENNE_STATE_N]; /* the array for the state vector */
25
+
26
+ /********************************/
27
+
28
+ /* For normal distribution */
29
+ double normal_x;
30
+ double normal_y;
31
+ double normal_rho;
32
+ int normal_is_valid; /* = 0; */
33
+ };
34
+
35
+ /**
36
+ * CPUGeneratorImplState is a POD class containing
37
+ * new data introduced in at::CPUGeneratorImpl and the legacy state. It is used
38
+ * as a helper for torch.get_rng_state() and torch.set_rng_state()
39
+ * functions.
40
+ */
41
+ struct CPUGeneratorImplState {
42
+ CPUGeneratorImplStateLegacy legacy_pod;
43
+ float next_float_normal_sample;
44
+ bool is_next_float_normal_sample_valid;
45
+ };
46
+
47
+ /**
48
+ * PyTorch maintains a collection of default generators that get
49
+ * initialized once. The purpose of these default generators is to
50
+ * maintain a global running state of the pseudo random number generation,
51
+ * when a user does not explicitly mention any generator.
52
+ * getDefaultCPUGenerator gets the default generator for a particular
53
+ * device.
54
+ */
55
+ const Generator& getDefaultCPUGenerator() {
56
+ static auto default_gen_cpu = createCPUGenerator(c10::detail::getNonDeterministicRandom());
57
+ return default_gen_cpu;
58
+ }
59
+
60
+ /**
61
+ * Utility to create a CPUGeneratorImpl. Returns a shared_ptr
62
+ */
63
+ Generator createCPUGenerator(uint64_t seed_val) {
64
+ return make_generator<CPUGeneratorImpl>(seed_val);
65
+ }
66
+
67
+ /**
68
+ * Helper function to concatenate two 32 bit unsigned int
69
+ * and return them as a 64 bit unsigned int
70
+ */
71
+ inline static uint64_t make64BitsFrom32Bits(uint32_t hi, uint32_t lo) {
72
+ return (static_cast<uint64_t>(hi) << 32) | lo;
73
+ }
74
+
75
+ } // namespace detail
76
+
77
+ /**
78
+ * CPUGeneratorImpl class implementation
79
+ */
80
+ CPUGeneratorImpl::CPUGeneratorImpl(uint64_t seed_in)
81
+ : c10::GeneratorImpl{Device(DeviceType::CPU), DispatchKeySet(c10::DispatchKey::CPU)},
82
+ engine_{seed_in},
83
+ next_float_normal_sample_{std::optional<float>()},
84
+ next_double_normal_sample_{std::optional<double>()} { }
85
+
86
+ /**
87
+ * Manually seeds the engine with the seed input
88
+ * See Note [Acquire lock when using random generators]
89
+ */
90
+ void CPUGeneratorImpl::set_current_seed(uint64_t seed) {
91
+ next_float_normal_sample_.reset();
92
+ next_double_normal_sample_.reset();
93
+ engine_ = mt19937(seed);
94
+ }
95
+
96
+ /**
97
+ * Sets the offset of RNG state.
98
+ * See Note [Acquire lock when using random generators]
99
+ */
100
+ void CPUGeneratorImpl::set_offset(uint64_t offset [[maybe_unused]]) {
101
+ TORCH_CHECK(false, "CPU Generator does not use offset");
102
+ }
103
+
104
+ /**
105
+ * Gets the current offset of CPUGeneratorImpl.
106
+ */
107
+ uint64_t CPUGeneratorImpl::get_offset() const {
108
+ TORCH_CHECK(false, "CPU Generator does not use offset");
109
+ }
110
+
111
+ /**
112
+ * Gets the current seed of CPUGeneratorImpl.
113
+ */
114
+ uint64_t CPUGeneratorImpl::current_seed() const {
115
+ return engine_.seed();
116
+ }
117
+
118
+ /**
119
+ * Gets a nondeterministic random number from /dev/urandom or time,
120
+ * seeds the CPUGeneratorImpl with it and then returns that number.
121
+ *
122
+ * FIXME: You can move this function to Generator.cpp if the algorithm
123
+ * in getNonDeterministicRandom is unified for both CPU and CUDA
124
+ */
125
+ uint64_t CPUGeneratorImpl::seed() {
126
+ auto random = c10::detail::getNonDeterministicRandom();
127
+ this->set_current_seed(random);
128
+ return random;
129
+ }
130
+
131
+ /**
132
+ * Sets the internal state of CPUGeneratorImpl. The new internal state
133
+ * must be a strided CPU byte tensor and of the same size as CPUGeneratorImplState.
134
+ */
135
+ void CPUGeneratorImpl::set_state(const c10::TensorImpl& new_state) {
136
+ using detail::CPUGeneratorImplState;
137
+ using detail::CPUGeneratorImplStateLegacy;
138
+
139
+ static_assert(std::is_standard_layout_v<CPUGeneratorImplState>, "CPUGeneratorImplState is not a PODType");
140
+ constexpr size_t size = sizeof(CPUGeneratorImplState);
141
+
142
+ detail::check_rng_state(new_state);
143
+
144
+ at::mt19937 engine;
145
+ auto new_state_size = new_state.numel();
146
+
147
+ TORCH_CHECK(new_state_size == size, "Expected a CPUGeneratorImplState of size ", size,
148
+ " but found the input RNG state size to be ", new_state_size);
149
+
150
+ auto rng_state = new_state.data_ptr_impl<CPUGeneratorImplState>();
151
+ auto legacy_pod = &(rng_state->legacy_pod);
152
+ // construct engine_
153
+ // Note that CPUGeneratorImplStateLegacy stored a state array of 64 bit uints, whereas in our
154
+ // redefined mt19937, we have changed to a state array of 32 bit uints. Hence, we are
155
+ // doing a std::copy.
156
+ at::mt19937_data_pod rng_data{};
157
+ std::copy(std::begin(legacy_pod->state), std::end(legacy_pod->state), rng_data.state_.begin());
158
+ rng_data.seed_ = legacy_pod->the_initial_seed;
159
+ rng_data.left_ = legacy_pod->left;
160
+ rng_data.seeded_ = legacy_pod->seeded;
161
+ rng_data.next_ = static_cast<uint32_t>(legacy_pod->next);
162
+ engine.set_data(rng_data);
163
+ TORCH_CHECK(engine.is_valid(), "Invalid mt19937 state");
164
+ this->engine_ = engine;
165
+ this->next_float_normal_sample_ = rng_state->is_next_float_normal_sample_valid
166
+ ? std::optional<float>(rng_state->next_float_normal_sample)
167
+ : std::optional<float>();
168
+ this->next_double_normal_sample_ = legacy_pod->normal_is_valid
169
+ ? std::optional<double>(legacy_pod->normal_y)
170
+ : std::optional<double>();
171
+ }
172
+
173
+ /**
174
+ * Gets the current internal state of CPUGeneratorImpl. The internal
175
+ * state is returned as a CPU byte tensor.
176
+ */
177
+ c10::intrusive_ptr<c10::TensorImpl> CPUGeneratorImpl::get_state() const {
178
+ using detail::CPUGeneratorImplState;
179
+
180
+ static const size_t size = sizeof(CPUGeneratorImplState);
181
+ static_assert(std::is_standard_layout_v<CPUGeneratorImplState>, "CPUGeneratorImplState is not a PODType");
182
+
183
+ auto state_tensor = at::detail::empty_cpu({static_cast<int64_t>(size)}, ScalarType::Byte, std::nullopt, std::nullopt, std::nullopt, std::nullopt);
184
+ auto rng_state = state_tensor.data_ptr();
185
+
186
+ // accumulate generator data to be copied into byte tensor
187
+ auto accum_state = std::make_unique<CPUGeneratorImplState>();
188
+ auto rng_data = this->engine_.data();
189
+ accum_state->legacy_pod.the_initial_seed = rng_data.seed_;
190
+ accum_state->legacy_pod.left = rng_data.left_;
191
+ accum_state->legacy_pod.seeded = rng_data.seeded_;
192
+ accum_state->legacy_pod.next = rng_data.next_;
193
+ std::copy(rng_data.state_.begin(), rng_data.state_.end(), std::begin(accum_state->legacy_pod.state));
194
+ accum_state->legacy_pod.normal_x = 0.0; // we don't use it anymore and this is just a dummy
195
+ accum_state->legacy_pod.normal_rho = 0.0; // we don't use it anymore and this is just a dummy
196
+ accum_state->legacy_pod.normal_is_valid = false;
197
+ accum_state->legacy_pod.normal_y = 0.0;
198
+ accum_state->next_float_normal_sample = 0.0f;
199
+ accum_state->is_next_float_normal_sample_valid = false;
200
+ if (this->next_double_normal_sample_) {
201
+ accum_state->legacy_pod.normal_is_valid = true;
202
+ accum_state->legacy_pod.normal_y = *(this->next_double_normal_sample_);
203
+ }
204
+ if (this->next_float_normal_sample_) {
205
+ accum_state->is_next_float_normal_sample_valid = true;
206
+ accum_state->next_float_normal_sample = *(this->next_float_normal_sample_);
207
+ }
208
+
209
+ memcpy(rng_state, accum_state.get(), size);
210
+ return state_tensor.getIntrusivePtr();
211
+ }
212
+
213
+ /**
214
+ * Gets the DeviceType of CPUGeneratorImpl.
215
+ * Used for type checking during run time.
216
+ */
217
+ DeviceType CPUGeneratorImpl::device_type() {
218
+ return DeviceType::CPU;
219
+ }
220
+
221
+ /**
222
+ * Gets a random 32 bit unsigned integer from the engine
223
+ *
224
+ * See Note [Acquire lock when using random generators]
225
+ */
226
+ uint32_t CPUGeneratorImpl::random() {
227
+ return engine_();
228
+ }
229
+
230
+ /**
231
+ * Gets a random 64 bit unsigned integer from the engine
232
+ *
233
+ * See Note [Acquire lock when using random generators]
234
+ */
235
+ uint64_t CPUGeneratorImpl::random64() {
236
+ uint32_t random1 = engine_();
237
+ uint32_t random2 = engine_();
238
+ return detail::make64BitsFrom32Bits(random1, random2);
239
+ }
240
+
241
+ /**
242
+ * Get the cached normal random in float
243
+ */
244
+ std::optional<float> CPUGeneratorImpl::next_float_normal_sample() {
245
+ return next_float_normal_sample_;
246
+ }
247
+
248
+ /**
249
+ * Get the cached normal random in double
250
+ */
251
+ std::optional<double> CPUGeneratorImpl::next_double_normal_sample() {
252
+ return next_double_normal_sample_;
253
+ }
254
+
255
+ /**
256
+ * Cache normal random in float
257
+ *
258
+ * See Note [Acquire lock when using random generators]
259
+ */
260
+ void CPUGeneratorImpl::set_next_float_normal_sample(std::optional<float> randn) {
261
+ next_float_normal_sample_ = randn;
262
+ }
263
+
264
+ /**
265
+ * Cache normal random in double
266
+ *
267
+ * See Note [Acquire lock when using random generators]
268
+ */
269
+ void CPUGeneratorImpl::set_next_double_normal_sample(std::optional<double> randn) {
270
+ next_double_normal_sample_ = randn;
271
+ }
272
+
273
+ /**
274
+ * Get the engine of the CPUGeneratorImpl
275
+ */
276
+ at::mt19937 CPUGeneratorImpl::engine() {
277
+ return engine_;
278
+ }
279
+
280
+ /**
281
+ * Set the engine of the CPUGeneratorImpl
282
+ *
283
+ * See Note [Acquire lock when using random generators]
284
+ */
285
+ void CPUGeneratorImpl::set_engine(at::mt19937 engine) {
286
+ engine_ = engine;
287
+ }
288
+
289
+ /**
290
+ * Public clone method implementation
291
+ *
292
+ * See Note [Acquire lock when using random generators]
293
+ */
294
+ std::shared_ptr<CPUGeneratorImpl> CPUGeneratorImpl::clone() const {
295
+ return std::shared_ptr<CPUGeneratorImpl>(this->clone_impl());
296
+ }
297
+
298
+ /**
299
+ * Private clone method implementation
300
+ *
301
+ * See Note [Acquire lock when using random generators]
302
+ */
303
+ CPUGeneratorImpl* CPUGeneratorImpl::clone_impl() const {
304
+ auto gen = new CPUGeneratorImpl();
305
+ gen->set_engine(engine_);
306
+ gen->set_next_float_normal_sample(next_float_normal_sample_);
307
+ gen->set_next_double_normal_sample(next_double_normal_sample_);
308
+ return gen;
309
+ }
310
+
311
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Generator.h>
4
+ #include <ATen/core/MT19937RNGEngine.h>
5
+ #include <c10/core/GeneratorImpl.h>
6
+ #include <optional>
7
+
8
+ namespace at {
9
+
10
+ struct TORCH_API CPUGeneratorImpl : public c10::GeneratorImpl {
11
+ // Constructors
12
+ CPUGeneratorImpl(uint64_t seed_in = default_rng_seed_val);
13
+ ~CPUGeneratorImpl() override = default;
14
+
15
+ // CPUGeneratorImpl methods
16
+ std::shared_ptr<CPUGeneratorImpl> clone() const;
17
+ void set_current_seed(uint64_t seed) override;
18
+ void set_offset(uint64_t offset) override;
19
+ uint64_t get_offset() const override;
20
+ uint64_t current_seed() const override;
21
+ uint64_t seed() override;
22
+ void set_state(const c10::TensorImpl& new_state) override;
23
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
24
+ static c10::DeviceType device_type();
25
+ uint32_t random();
26
+ uint64_t random64();
27
+ std::optional<float> next_float_normal_sample();
28
+ std::optional<double> next_double_normal_sample();
29
+ void set_next_float_normal_sample(std::optional<float> randn);
30
+ void set_next_double_normal_sample(std::optional<double> randn);
31
+ at::mt19937 engine();
32
+ void set_engine(at::mt19937 engine);
33
+
34
+ private:
35
+ CPUGeneratorImpl* clone_impl() const override;
36
+ at::mt19937 engine_;
37
+ std::optional<float> next_float_normal_sample_;
38
+ std::optional<double> next_double_normal_sample_;
39
+ };
40
+
41
+ namespace detail {
42
+
43
+ TORCH_API const Generator& getDefaultCPUGenerator();
44
+ TORCH_API Generator
45
+ createCPUGenerator(uint64_t seed_val = default_rng_seed_val);
46
+
47
+ } // namespace detail
48
+
49
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DLConvertor.cpp ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/DLConvertor.h>
2
+ #include <memory>
3
+
4
+ using namespace std;
5
+ namespace at {
6
+
7
+ DLDataType getDLDataType(const Tensor& t) {
8
+ DLDataType dtype;
9
+ dtype.lanes = 1;
10
+ dtype.bits = t.element_size() * 8;
11
+ switch (t.scalar_type()) {
12
+ case ScalarType::UInt1:
13
+ case ScalarType::UInt2:
14
+ case ScalarType::UInt3:
15
+ case ScalarType::UInt4:
16
+ case ScalarType::UInt5:
17
+ case ScalarType::UInt6:
18
+ case ScalarType::UInt7:
19
+ case ScalarType::Byte:
20
+ case ScalarType::UInt16:
21
+ case ScalarType::UInt32:
22
+ case ScalarType::UInt64:
23
+ dtype.code = DLDataTypeCode::kDLUInt;
24
+ break;
25
+ case ScalarType::Int1:
26
+ case ScalarType::Int2:
27
+ case ScalarType::Int3:
28
+ case ScalarType::Int4:
29
+ case ScalarType::Int5:
30
+ case ScalarType::Int6:
31
+ case ScalarType::Int7:
32
+ case ScalarType::Char:
33
+ dtype.code = DLDataTypeCode::kDLInt;
34
+ break;
35
+ // NOLINTNEXTLINE(bugprone-branch-clone)
36
+ case ScalarType::Double:
37
+ dtype.code = DLDataTypeCode::kDLFloat;
38
+ break;
39
+ case ScalarType::Float:
40
+ dtype.code = DLDataTypeCode::kDLFloat;
41
+ break;
42
+ // NOLINTNEXTLINE(bugprone-branch-clone)
43
+ case ScalarType::Int:
44
+ dtype.code = DLDataTypeCode::kDLInt;
45
+ break;
46
+ case ScalarType::Long:
47
+ dtype.code = DLDataTypeCode::kDLInt;
48
+ break;
49
+ case ScalarType::Short:
50
+ dtype.code = DLDataTypeCode::kDLInt;
51
+ break;
52
+ case ScalarType::Half:
53
+ dtype.code = DLDataTypeCode::kDLFloat;
54
+ break;
55
+ case ScalarType::Bool:
56
+ dtype.code = DLDataTypeCode::kDLBool;
57
+ break;
58
+ case ScalarType::ComplexHalf:
59
+ case ScalarType::ComplexFloat:
60
+ case ScalarType::ComplexDouble:
61
+ dtype.code = DLDataTypeCode::kDLComplex;
62
+ break;
63
+ case ScalarType::BComplex32:
64
+ TORCH_CHECK_BUFFER(false, "BComplex32 type is not supported by dlpack");
65
+ break;
66
+ case ScalarType::BFloat16:
67
+ dtype.code = DLDataTypeCode::kDLBfloat;
68
+ break;
69
+ // TODO(#146647): use macro here instead of spelling out each shell dtype
70
+ case ScalarType::Float8_e5m2:
71
+ dtype.code = DLDataTypeCode::kDLFloat8_e5m2;
72
+ break;
73
+ case ScalarType::Float8_e5m2fnuz:
74
+ dtype.code = DLDataTypeCode::kDLFloat8_e5m2fnuz;
75
+ break;
76
+ case ScalarType::Float8_e4m3fn:
77
+ dtype.code = DLDataTypeCode::kDLFloat8_e4m3fn;
78
+ break;
79
+ case ScalarType::Float8_e4m3fnuz:
80
+ dtype.code = DLDataTypeCode::kDLFloat8_e4m3fnuz;
81
+ break;
82
+ case ScalarType::Float8_e8m0fnu:
83
+ dtype.code = DLDataTypeCode::kDLFloat8_e8m0fnu;
84
+ break;
85
+ case ScalarType::Float4_e2m1fn_x2:
86
+ dtype.code = DLDataTypeCode::kDLFloat4_e2m1fn;
87
+ dtype.lanes = 2;
88
+ dtype.bits = 4;
89
+ break;
90
+ case ScalarType::QInt8:
91
+ case ScalarType::QUInt8:
92
+ case ScalarType::QInt32:
93
+ case ScalarType::QUInt4x2:
94
+ case ScalarType::QUInt2x4:
95
+ TORCH_CHECK_BUFFER(false, "QUInt/QInt types are not supported by dlpack");
96
+ break;
97
+ case ScalarType::Bits1x8:
98
+ case ScalarType::Bits2x4:
99
+ case ScalarType::Bits4x2:
100
+ case ScalarType::Bits8:
101
+ case ScalarType::Bits16:
102
+ TORCH_CHECK_BUFFER(false, "Bit types are not supported by dlpack");
103
+ break;
104
+ case ScalarType::Undefined:
105
+ TORCH_CHECK_BUFFER(false, "Undefined is not a valid ScalarType");
106
+ case ScalarType::NumOptions:
107
+ TORCH_CHECK_BUFFER(false, "NumOptions is not a valid ScalarType");
108
+ }
109
+ return dtype;
110
+ }
111
+
112
+ DLDevice torchDeviceToDLDevice(at::Device device) {
113
+ DLDevice ctx;
114
+
115
+ ctx.device_id =
116
+ (device.is_cuda() || device.is_privateuseone() || device.is_mtia())
117
+ ? static_cast<int32_t>(static_cast<unsigned char>(device.index()))
118
+ : 0;
119
+
120
+ switch (device.type()) {
121
+ case DeviceType::CPU:
122
+ ctx.device_type = DLDeviceType::kDLCPU;
123
+ break;
124
+ case DeviceType::CUDA:
125
+ #ifdef USE_ROCM
126
+ // ROCM, if enabled will look like cuda to PyTorch
127
+ // while everyone else should see HIP
128
+ ctx.device_type = DLDeviceType::kDLROCM;
129
+ #else
130
+ ctx.device_type = DLDeviceType::kDLCUDA;
131
+ #endif
132
+ break;
133
+ case DeviceType::OPENCL:
134
+ ctx.device_type = DLDeviceType::kDLOpenCL;
135
+ break;
136
+ case DeviceType::HIP:
137
+ ctx.device_type = DLDeviceType::kDLROCM;
138
+ break;
139
+ case DeviceType::XPU:
140
+ ctx.device_type = DLDeviceType::kDLOneAPI;
141
+ ctx.device_id = at::detail::getXPUHooks().getGlobalIdxFromDevice(device);
142
+ break;
143
+ case DeviceType::MAIA:
144
+ ctx.device_type = DLDeviceType::kDLMAIA;
145
+ break;
146
+ case DeviceType::PrivateUse1:
147
+ ctx.device_type = DLDeviceType::kDLExtDev;
148
+ break;
149
+ case DeviceType::MTIA:
150
+ ctx.device_type = DLDeviceType::kDLExtDev;
151
+ break;
152
+ case DeviceType::MPS:
153
+ ctx.device_type = DLDeviceType::kDLMetal;
154
+ break;
155
+ default:
156
+ TORCH_CHECK_BUFFER(false, "Cannot pack tensors on " + device.str());
157
+ }
158
+
159
+ return ctx;
160
+ }
161
+
162
+ Device dlDeviceToTorchDevice(
163
+ DLDeviceType type,
164
+ c10::DeviceIndex index,
165
+ void* data) {
166
+ switch (type) {
167
+ case DLDeviceType::kDLCPU:
168
+ return at::Device(DeviceType::CPU);
169
+ #ifndef USE_ROCM
170
+ // if we are compiled under HIP, we cannot do cuda
171
+ case DLDeviceType::kDLCUDA:
172
+ return at::Device(DeviceType::CUDA, index);
173
+ #endif
174
+ case DLDeviceType::kDLOpenCL:
175
+ return at::Device(DeviceType::OPENCL, index);
176
+ case DLDeviceType::kDLROCM:
177
+ #ifdef USE_ROCM
178
+ // this looks funny, we need to return CUDA here to masquerade
179
+ return at::Device(DeviceType::CUDA, index);
180
+ #else
181
+ return at::Device(DeviceType::HIP, index);
182
+ #endif
183
+ case DLDeviceType::kDLOneAPI:
184
+ TORCH_CHECK(data != nullptr, "Can't get ATen device for XPU without XPU data.");
185
+ return at::detail::getXPUHooks().getDeviceFromPtr(data);
186
+ case DLDeviceType::kDLMAIA:
187
+ return at::Device(DeviceType::MAIA, index);
188
+ case DLDeviceType::kDLExtDev:
189
+ return at::Device(DeviceType::PrivateUse1, index);
190
+ case DLDeviceType::kDLMetal:
191
+ return at::Device(DeviceType::MPS, index);
192
+ default:
193
+ TORCH_CHECK_BUFFER(
194
+ false, "Unsupported device_type: ", std::to_string(type));
195
+ }
196
+ }
197
+
198
+ ScalarType toScalarType(const DLDataType& dtype) {
199
+ ScalarType stype = ScalarType::Undefined;
200
+ if (dtype.code != DLDataTypeCode::kDLFloat4_e2m1fn) {
201
+ TORCH_CHECK_BUFFER(
202
+ dtype.lanes == 1,
203
+ "ATen does not support lanes != 1 for dtype code", std::to_string(dtype.code));
204
+ }
205
+ switch (dtype.code) {
206
+ case DLDataTypeCode::kDLUInt:
207
+ switch (dtype.bits) {
208
+ case 8:
209
+ stype = ScalarType::Byte;
210
+ break;
211
+ case 16:
212
+ stype = ScalarType::UInt16;
213
+ break;
214
+ case 32:
215
+ stype = ScalarType::UInt32;
216
+ break;
217
+ case 64:
218
+ stype = ScalarType::UInt64;
219
+ break;
220
+ default:
221
+ TORCH_CHECK_BUFFER(
222
+ false, "Unsupported kUInt bits ", std::to_string(dtype.bits));
223
+ }
224
+ break;
225
+ case DLDataTypeCode::kDLInt:
226
+ switch (dtype.bits) {
227
+ case 8:
228
+ stype = ScalarType::Char;
229
+ break;
230
+ case 16:
231
+ stype = ScalarType::Short;
232
+ break;
233
+ case 32:
234
+ stype = ScalarType::Int;
235
+ break;
236
+ case 64:
237
+ stype = ScalarType::Long;
238
+ break;
239
+ default:
240
+ TORCH_CHECK_BUFFER(
241
+ false, "Unsupported kInt bits ", std::to_string(dtype.bits));
242
+ }
243
+ break;
244
+ case DLDataTypeCode::kDLFloat:
245
+ switch (dtype.bits) {
246
+ case 16:
247
+ stype = ScalarType::Half;
248
+ break;
249
+ case 32:
250
+ stype = ScalarType::Float;
251
+ break;
252
+ case 64:
253
+ stype = ScalarType::Double;
254
+ break;
255
+ default:
256
+ TORCH_CHECK_BUFFER(
257
+ false, "Unsupported kFloat bits ", std::to_string(dtype.bits));
258
+ }
259
+ break;
260
+ case DLDataTypeCode::kDLBfloat:
261
+ switch (dtype.bits) {
262
+ case 16:
263
+ stype = ScalarType::BFloat16;
264
+ break;
265
+ default:
266
+ TORCH_CHECK_BUFFER(
267
+ false, "Unsupported kFloat bits ", std::to_string(dtype.bits));
268
+ }
269
+ break;
270
+ case DLDataTypeCode::kDLComplex:
271
+ switch (dtype.bits) {
272
+ case 32:
273
+ stype = ScalarType::ComplexHalf;
274
+ break;
275
+ case 64:
276
+ stype = ScalarType::ComplexFloat;
277
+ break;
278
+ case 128:
279
+ stype = ScalarType::ComplexDouble;
280
+ break;
281
+ default:
282
+ TORCH_CHECK_BUFFER(
283
+ false, "Unsupported kFloat bits ", std::to_string(dtype.bits));
284
+ }
285
+ break;
286
+ case DLDataTypeCode::kDLBool:
287
+ switch (dtype.bits) {
288
+ case 8:
289
+ stype = ScalarType::Bool;
290
+ break;
291
+ default:
292
+ TORCH_CHECK_BUFFER(
293
+ false, "Unsupported kDLBool bits ", std::to_string(dtype.bits));
294
+ }
295
+ break;
296
+ case DLDataTypeCode::kDLFloat8_e5m2:
297
+ switch (dtype.bits) {
298
+ case 8:
299
+ stype = ScalarType::Float8_e5m2;
300
+ break;
301
+ default:
302
+ TORCH_CHECK_BUFFER(
303
+ false, "Unsupported kDLFloat8_e5m2 bits ", std::to_string(dtype.bits));
304
+ }
305
+ break;
306
+ case DLDataTypeCode::kDLFloat8_e5m2fnuz:
307
+ switch (dtype.bits) {
308
+ case 8:
309
+ stype = ScalarType::Float8_e5m2fnuz;
310
+ break;
311
+ default:
312
+ TORCH_CHECK_BUFFER(
313
+ false, "Unsupported kDLFloat8_e5m2fnuz bits ", std::to_string(dtype.bits));
314
+ }
315
+ break;
316
+ case DLDataTypeCode::kDLFloat8_e4m3fn:
317
+ switch (dtype.bits) {
318
+ case 8:
319
+ stype = ScalarType::Float8_e4m3fn;
320
+ break;
321
+ default:
322
+ TORCH_CHECK_BUFFER(
323
+ false, "Unsupported kDLFloat8_e4m3fn bits ", std::to_string(dtype.bits));
324
+ }
325
+ break;
326
+ case DLDataTypeCode::kDLFloat8_e4m3fnuz:
327
+ switch (dtype.bits) {
328
+ case 8:
329
+ stype = ScalarType::Float8_e4m3fnuz;
330
+ break;
331
+ default:
332
+ TORCH_CHECK_BUFFER(
333
+ false, "Unsupported kDLFloat8_e4m3fnuz bits ", std::to_string(dtype.bits));
334
+ }
335
+ break;
336
+ case DLDataTypeCode::kDLFloat8_e8m0fnu:
337
+ switch (dtype.bits) {
338
+ case 8:
339
+ stype = ScalarType::Float8_e8m0fnu;
340
+ break;
341
+ default:
342
+ TORCH_CHECK_BUFFER(
343
+ false, "Unsupported kDLFloat8_e8m0fnu bits ", std::to_string(dtype.bits));
344
+ }
345
+ break;
346
+ case DLDataTypeCode::kDLFloat4_e2m1fn:
347
+ switch (dtype.bits) {
348
+ case 4:
349
+ switch (dtype.lanes) {
350
+ case 2:
351
+ stype = ScalarType::Float4_e2m1fn_x2;
352
+ break;
353
+ default:
354
+ TORCH_CHECK_BUFFER(
355
+ false, "Unsupported kDLFloat4_e2m1fn lanes ", std::to_string(dtype.lanes));
356
+ }
357
+ break;
358
+ default:
359
+ TORCH_CHECK_BUFFER(
360
+ false, "Unsupported kDLFloat4_e2m1fn bits ", std::to_string(dtype.bits));
361
+ }
362
+ break;
363
+ default:
364
+ TORCH_CHECK_BUFFER(false, "Unsupported code ", std::to_string(dtype.code));
365
+ }
366
+ return stype;
367
+ }
368
+
369
+
370
+ namespace {
371
+
372
+ int64_t toStorageOffset(int64_t byte_offset, ScalarType stype) {
373
+ if (byte_offset == 0) {
374
+ return 0;
375
+ }
376
+ const auto element_size = c10::elementSize(stype);
377
+ TORCH_CHECK_VALUE(byte_offset % element_size == 0, "byte offset must be multiple of element size");
378
+ return byte_offset / element_size;
379
+ }
380
+
381
+ // The templated classes below are needed for supporting both:
382
+ // - DLManagedTensor
383
+ // - DLManagedTensorVersioned
384
+ template <class T>
385
+ struct ATenDLMTensor {
386
+ Tensor handle;
387
+ T tensor{};
388
+ };
389
+
390
+ template <class T>
391
+ void deleter(T* arg) {
392
+ delete static_cast<ATenDLMTensor<T>*>(arg->manager_ctx);
393
+ }
394
+
395
+ // Adds version information for DLManagedTensorVersioned.
396
+ // This is a no-op for the other types. read_only only applies to the versioned
397
+ // struct; the legacy DLManagedTensor has no flags field.
398
+ template <class T>
399
+ void fillVersion(T* tensor, bool read_only) {}
400
+
401
+ template <>
402
+ void fillVersion<DLManagedTensorVersioned>(
403
+ DLManagedTensorVersioned* tensor,
404
+ bool read_only) {
405
+ tensor->flags = read_only ? DLPACK_FLAG_BITMASK_READ_ONLY : 0;
406
+ tensor->version.major = DLPACK_MAJOR_VERSION;
407
+ tensor->version.minor = DLPACK_MINOR_VERSION;
408
+ }
409
+
410
+ // This function returns a shared_ptr to memory managed DLpack tensor
411
+ // constructed out of ATen tensor. When read_only is set, the data is exported
412
+ // through const_data_ptr() (avoiding a copy-on-write materialization) and the
413
+ // DLPACK_FLAG_BITMASK_READ_ONLY flag is set on the versioned struct.
414
+ template <class T>
415
+ T* toDLPackImpl(const Tensor& src, bool read_only) {
416
+ auto atDLMTensor = std::make_unique<ATenDLMTensor<T>>();
417
+ atDLMTensor->handle = src;
418
+ atDLMTensor->tensor.manager_ctx = atDLMTensor.get();
419
+ atDLMTensor->tensor.deleter = &deleter<T>;
420
+ // DLTensor::data is a plain void*, so the read-only path const_casts away the
421
+ // const from const_data_ptr(). This is safe: const_data_ptr() does not
422
+ // materialize a copy-on-write tensor, and DLPACK_FLAG_BITMASK_READ_ONLY is
423
+ // set on the versioned struct (see fillVersion) so the consumer is told not
424
+ // to write through the pointer. The mutable path uses mutable_data_ptr().
425
+ if (src.device().type() == kMPS) {
426
+ atDLMTensor->tensor.dl_tensor.data = read_only
427
+ ? const_cast<void*>(src.storage().data())
428
+ : src.storage().mutable_data();
429
+ atDLMTensor->tensor.dl_tensor.byte_offset = src.storage_offset() * c10::elementSize(src.scalar_type());
430
+ } else {
431
+ atDLMTensor->tensor.dl_tensor.data = read_only
432
+ ? const_cast<void*>(src.const_data_ptr())
433
+ : src.mutable_data_ptr();
434
+ atDLMTensor->tensor.dl_tensor.byte_offset = 0;
435
+ }
436
+ atDLMTensor->tensor.dl_tensor.device = torchDeviceToDLDevice(src.device());
437
+ atDLMTensor->tensor.dl_tensor.ndim = static_cast<int32_t>(src.dim());
438
+ atDLMTensor->tensor.dl_tensor.dtype = getDLDataType(src);
439
+ atDLMTensor->tensor.dl_tensor.shape = const_cast<int64_t*>(src.sizes().data());
440
+ atDLMTensor->tensor.dl_tensor.strides = const_cast<int64_t*>(src.strides().data());
441
+ fillVersion(&atDLMTensor->tensor, read_only);
442
+
443
+ return &(atDLMTensor.release()->tensor);
444
+ }
445
+
446
+ // Explicitly instantiate the template above for both classes.
447
+ template DLManagedTensor* toDLPackImpl<DLManagedTensor>(const Tensor&, bool);
448
+ template DLManagedTensorVersioned* toDLPackImpl<DLManagedTensorVersioned>(const Tensor&, bool);
449
+
450
+ // This function constructs a Tensor from a memory managed DLPack which
451
+ // may be represented as either: DLManagedTensor and DLManagedTensorVersioned.
452
+ template <class T>
453
+ at::Tensor fromDLPackImpl(T* src, std::function<void(void*)> deleter) {
454
+ if (!deleter) {
455
+ deleter = [src](void* self [[maybe_unused]]) {
456
+ if (src->deleter) {
457
+ src->deleter(src);
458
+ }
459
+ };
460
+ }
461
+
462
+ DLTensor& dl_tensor = src->dl_tensor;
463
+ Device device = dlDeviceToTorchDevice(
464
+ dl_tensor.device.device_type, dl_tensor.device.device_id, dl_tensor.data);
465
+ ScalarType stype = toScalarType(dl_tensor.dtype);
466
+
467
+ if (!dl_tensor.strides) {
468
+ TORCH_CHECK_VALUE(dl_tensor.byte_offset == 0, "Expected zero byte_offset");
469
+ return at::from_blob(
470
+ dl_tensor.data,
471
+ IntArrayRef(dl_tensor.shape, dl_tensor.ndim),
472
+ std::move(deleter),
473
+ at::device(device).dtype(stype),
474
+ {device});
475
+ }
476
+ return at::from_blob(
477
+ dl_tensor.data,
478
+ IntArrayRef(dl_tensor.shape, dl_tensor.ndim),
479
+ IntArrayRef(dl_tensor.strides, dl_tensor.ndim),
480
+ toStorageOffset(dl_tensor.byte_offset, stype),
481
+ deleter,
482
+ at::device(device).dtype(stype),
483
+ {device});
484
+ }
485
+
486
+ // Explicitly instantiate the template above for both classes.
487
+ template at::Tensor fromDLPackImpl<DLManagedTensor>(DLManagedTensor* src, std::function<void(void*)> deleter);
488
+ template at::Tensor fromDLPackImpl<DLManagedTensorVersioned>(DLManagedTensorVersioned* src, std::function<void(void*)> deleter);
489
+
490
+ } // namespace
491
+
492
+ void toDLPackNonOwning(const Tensor& src, DLTensor* out, bool read_only) {
493
+ // Fill in the pre-allocated DLTensor struct with direct pointers
494
+ // This is a non-owning conversion - the caller owns the tensor
495
+ // and must keep it alive for the duration of DLTensor usage
496
+ // See toDLPackImpl for why the read-only const_cast is safe.
497
+ out->data = read_only ? const_cast<void*>(src.const_data_ptr())
498
+ : src.mutable_data_ptr();
499
+ out->device = torchDeviceToDLDevice(src.device());
500
+ out->ndim = static_cast<int32_t>(src.dim());
501
+ out->dtype = getDLDataType(src);
502
+ // sizes() and strides() return pointers to TensorImpl's stable storage
503
+ // which remains valid as long as the tensor is alive
504
+ out->shape = const_cast<int64_t*>(src.sizes().data());
505
+ out->strides = const_cast<int64_t*>(src.strides().data());
506
+ out->byte_offset = 0;
507
+ }
508
+
509
+ DLManagedTensor* toDLPack(const Tensor& src) {
510
+ return toDLPackImpl<DLManagedTensor>(src, /*read_only=*/false);
511
+ }
512
+
513
+ DLManagedTensorVersioned* toDLPackVersioned(const Tensor& src) {
514
+ return toDLPackImpl<DLManagedTensorVersioned>(src, /*read_only=*/false);
515
+ }
516
+
517
+ DLManagedTensorVersioned* toDLPackVersionedReadOnly(const Tensor& src) {
518
+ return toDLPackImpl<DLManagedTensorVersioned>(src, /*read_only=*/true);
519
+ }
520
+
521
+ Tensor fromDLPack(DLManagedTensor* src, std::function<void(void*)> deleter) {
522
+ return fromDLPackImpl<DLManagedTensor>(src, std::move(deleter));
523
+ }
524
+
525
+ Tensor fromDLPackVersioned(DLManagedTensorVersioned* src, std::function<void(void*)> deleter) {
526
+ return fromDLPackImpl<DLManagedTensorVersioned>(src, std::move(deleter));
527
+ }
528
+
529
+ Tensor maybeCopyTensor(
530
+ const Tensor& data,
531
+ std::optional<DLDevice> optional_dl_device,
532
+ std::optional<bool> copy) {
533
+ bool force_copy = copy.has_value() && *copy;
534
+ bool force_move = copy.has_value() && !*copy;
535
+
536
+ if (optional_dl_device.has_value()) {
537
+ auto device = at::dlDeviceToTorchDevice(
538
+ optional_dl_device->device_type,
539
+ static_cast<c10::DeviceIndex>(optional_dl_device->device_id));
540
+
541
+ if (device != data.device()) {
542
+ TORCH_CHECK_VALUE(
543
+ !force_move,
544
+ "cannot move (i.e. copy=False) tensor from ",
545
+ data.device(),
546
+ " to ",
547
+ device,
548
+ " without copying.");
549
+ return data.to(device);
550
+ }
551
+ }
552
+
553
+ if (force_copy) {
554
+ return data.clone();
555
+ }
556
+
557
+ return data;
558
+ }
559
+
560
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DLConvertor.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <ATen/Tensor.h>
5
+ #include <ATen/dlpack.h>
6
+
7
+ // this converter will:
8
+ // 1) take a Tensor object and wrap it in the DLPack tensor
9
+ // 2) take a dlpack tensor and convert it to the ATen Tensor
10
+
11
+ namespace at {
12
+
13
+ TORCH_API ScalarType toScalarType(const DLDataType& dtype);
14
+ TORCH_API DLManagedTensor* toDLPack(const Tensor& src);
15
+ TORCH_API struct DLManagedTensorVersioned* toDLPackVersioned(const Tensor& src);
16
+ // Read-only variant: sets DLPACK_FLAG_BITMASK_READ_ONLY and exports through
17
+ // const_data_ptr() so the conversion does not materialize a copy-on-write
18
+ // tensor. The consumer must not mutate the data.
19
+ TORCH_API struct DLManagedTensorVersioned* toDLPackVersionedReadOnly(
20
+ const Tensor& src);
21
+ TORCH_API void toDLPackNonOwning(
22
+ const Tensor& src,
23
+ DLTensor* out,
24
+ bool read_only = false);
25
+ TORCH_API Tensor
26
+ fromDLPack(DLManagedTensor* src, std::function<void(void*)> deleter = {});
27
+ TORCH_API Tensor fromDLPackVersioned(
28
+ DLManagedTensorVersioned* src,
29
+ std::function<void(void*)> deleter = {});
30
+ TORCH_API DLDataType getDLDataType(const Tensor& t);
31
+ TORCH_API DLDevice getDLContext(const Tensor& tensor, const int64_t& device_id);
32
+
33
+ // Copies the Tensor if there's a device mismatch or copy is forced.
34
+ // This should be used before actually creating the DLPack capsule.
35
+ TORCH_API Tensor maybeCopyTensor(
36
+ const Tensor& data,
37
+ std::optional<DLDevice> optional_dl_device,
38
+ std::optional<bool> copy);
39
+
40
+ // Converts the given at::Device into a DLDevice.
41
+ TORCH_API DLDevice torchDeviceToDLDevice(at::Device device);
42
+
43
+ // Converts the DLDevice to an ATen device.
44
+ TORCH_API Device dlDeviceToTorchDevice(
45
+ DLDeviceType type,
46
+ c10::DeviceIndex index,
47
+ void* data = nullptr);
48
+
49
+ // This trait class is used for retrieving different attributes, such as the
50
+ // PyCapsule names and conversion functions for both DLPack tensor classes:
51
+ // `DLManagedTensor` and `DLManagedTensorVersioned`.
52
+ //
53
+ // Each specialization should contain the following 2 traits:
54
+ // - `capsule`: actual name of the capsule
55
+ // - `used`: name of the capsule after using it
56
+ // - `toDLPack`: function for converting a tensor into a DLPack capsule
57
+ // - `fromDLPack`: function for creating a tensor from a DLPack capsule
58
+ //
59
+ // While `toDLPack` is the directly exposed to Python, `fromDLPack` is not.
60
+ // Although it contains the core implementation, it lacks the required book
61
+ // keeping logic contained in its caller `tensor_fromDLPack`.
62
+ //
63
+ // That said, `fromDLPack` is used directly in a few DLPack tests that live
64
+ // inside ATen (no Python available).
65
+ template <class T>
66
+ struct DLPackTraits {};
67
+
68
+ template <>
69
+ struct DLPackTraits<DLManagedTensor> {
70
+ inline static constexpr const char* capsule = "dltensor";
71
+ inline static constexpr const char* used = "used_dltensor";
72
+ inline static auto toDLPack = at::toDLPack;
73
+ inline static auto fromDLPack = at::fromDLPack;
74
+ };
75
+
76
+ template <>
77
+ struct DLPackTraits<DLManagedTensorVersioned> {
78
+ inline static constexpr const char* capsule = "dltensor_versioned";
79
+ inline static constexpr const char* used = "used_dltensor_versioned";
80
+ inline static auto toDLPack = at::toDLPackVersioned;
81
+ inline static auto fromDLPack = at::fromDLPackVersioned;
82
+ };
83
+
84
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DTensorState.cpp ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/DTensorState.h>
2
+
3
+ namespace at {
4
+
5
+ namespace {
6
+ thread_local bool kDTensorAllowImplicitReplication = false;
7
+ }
8
+
9
+ bool get_dtensor_allow_implicit_replication() {
10
+ return kDTensorAllowImplicitReplication;
11
+ }
12
+
13
+ void set_dtensor_allow_implicit_replication(bool enabled) {
14
+ kDTensorAllowImplicitReplication = enabled;
15
+ }
16
+
17
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DTensorState.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ namespace at {
6
+
7
+ TORCH_API bool get_dtensor_allow_implicit_replication();
8
+ TORCH_API void set_dtensor_allow_implicit_replication(bool enabled);
9
+
10
+ struct DTensorAllowImplicitReplication {
11
+ DTensorAllowImplicitReplication()
12
+ : prev_dtensor_allow_implicit_replication_(
13
+ get_dtensor_allow_implicit_replication()) {
14
+ set_dtensor_allow_implicit_replication(true);
15
+ }
16
+
17
+ DTensorAllowImplicitReplication(const DTensorAllowImplicitReplication&) =
18
+ delete;
19
+ DTensorAllowImplicitReplication& operator=(
20
+ const DTensorAllowImplicitReplication&) = delete;
21
+ DTensorAllowImplicitReplication(DTensorAllowImplicitReplication&&) = delete;
22
+ DTensorAllowImplicitReplication& operator=(
23
+ DTensorAllowImplicitReplication&&) = delete;
24
+
25
+ ~DTensorAllowImplicitReplication() {
26
+ set_dtensor_allow_implicit_replication(
27
+ prev_dtensor_allow_implicit_replication_);
28
+ }
29
+
30
+ private:
31
+ bool prev_dtensor_allow_implicit_replication_;
32
+ };
33
+
34
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/Device.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <c10/core/Device.h>
western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.cpp ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/Context.h>
2
+ #include <ATen/core/CachingHostAllocator.h>
3
+ #include <ATen/DeviceAccelerator.h>
4
+ #include <c10/core/impl/VirtualGuardImpl.h>
5
+
6
+ namespace at::accelerator {
7
+
8
+ std::optional<c10::DeviceType> getAccelerator(bool checked) {
9
+ // 1. Check PrivateUse1 backends
10
+ // We explicitly allow PrivateUse1 and another device at the same time as we
11
+ // use this for testing. Whenever a PrivateUse1 device is registered, use it
12
+ // first.
13
+ // Note that this check is only for hook registration and thus is NOT initializing
14
+ // the device or poisoning fork.
15
+ if (is_privateuse1_backend_registered()) {
16
+ return kPrivateUse1;
17
+ }
18
+
19
+ // 2. Check runtime backends
20
+ // This state is temporary, these runtime checks should be moved to compile-time
21
+ // once they provide the new isBuilt API and we are sure they're never in the
22
+ // same binary as another accelerator.
23
+ #define DETECT_RUNTIME_ACCELERATOR(device_name) \
24
+ if (at::has##device_name()) { \
25
+ return k##device_name; \
26
+ }
27
+
28
+ DETECT_RUNTIME_ACCELERATOR(MTIA)
29
+
30
+ #undef DETECT_RUNTIME_ACCELERATOR
31
+
32
+ // 2. Check compile-time backends
33
+ std::optional<c10::DeviceType> device_type = std::nullopt;
34
+
35
+ #define DETECT_AND_ASSIGN_ACCELERATOR_COMP(device_name) \
36
+ if (at::detail::get##device_name##Hooks().isBuilt()) { \
37
+ TORCH_CHECK( \
38
+ !device_type.has_value(), \
39
+ "Cannot have both " #device_name " and ", \
40
+ device_type.value(), "."); \
41
+ device_type = k##device_name; \
42
+ }
43
+
44
+ DETECT_AND_ASSIGN_ACCELERATOR_COMP(CUDA)
45
+ DETECT_AND_ASSIGN_ACCELERATOR_COMP(XPU)
46
+ DETECT_AND_ASSIGN_ACCELERATOR_COMP(HIP)
47
+ DETECT_AND_ASSIGN_ACCELERATOR_COMP(MPS)
48
+ DETECT_AND_ASSIGN_ACCELERATOR_COMP(HPU)
49
+ if (checked) {
50
+ TORCH_CHECK(
51
+ device_type, "Cannot access accelerator device when none is available.")
52
+ }
53
+ return device_type;
54
+
55
+ #undef DETECT_AND_ASSIGN_ACCELERATOR_COMP
56
+ }
57
+
58
+ bool isAccelerator(c10::DeviceType device_type) {
59
+ switch (device_type) {
60
+ case at::kCUDA:
61
+ case at::kMTIA:
62
+ case at::kXPU:
63
+ case at::kHIP:
64
+ case at::kMPS:
65
+ case at::kHPU:
66
+ case at::kPrivateUse1:
67
+ return true;
68
+ default:
69
+ return false;
70
+ }
71
+ }
72
+
73
+ // NOLINTBEGIN(bugprone-unchecked-optional-access)
74
+ c10::DeviceIndex deviceCount() {
75
+ const auto device_type = getAccelerator(false);
76
+ if (!device_type.has_value()) {
77
+ return static_cast<c10::DeviceIndex>(0);
78
+ }
79
+ c10::impl::VirtualGuardImpl impl(device_type.value());
80
+ return impl.deviceCount();
81
+ }
82
+
83
+ void setDeviceIndex(c10::DeviceIndex device_index) {
84
+ const auto device_type = getAccelerator(true).value();
85
+ c10::impl::VirtualGuardImpl impl(device_type);
86
+ impl.setDevice({device_type, device_index});
87
+ }
88
+
89
+ c10::DeviceIndex getDeviceIndex() {
90
+ const auto device_type = getAccelerator(true).value();
91
+ c10::impl::VirtualGuardImpl impl(device_type);
92
+ return impl.getDevice().index();
93
+ }
94
+
95
+ void setCurrentStream(c10::Stream stream) {
96
+ const auto device_type = getAccelerator(true).value();
97
+ TORCH_CHECK(
98
+ device_type == stream.device_type(),
99
+ "stream's device type ",
100
+ c10::DeviceTypeName(stream.device_type()),
101
+ " doesn't match the current accelerator ",
102
+ c10::DeviceTypeName(device_type));
103
+ c10::impl::VirtualGuardImpl impl(device_type);
104
+ impl.exchangeStream(stream);
105
+ }
106
+
107
+ c10::Stream getCurrentStream(c10::DeviceIndex device_index) {
108
+ const auto device_type = getAccelerator(true).value();
109
+ c10::impl::VirtualGuardImpl impl(device_type);
110
+ return impl.getStream({device_type, device_index});
111
+ }
112
+
113
+ void synchronizeDevice(c10::DeviceIndex device_index) {
114
+ const auto device_type = getAccelerator(true).value();
115
+ c10::impl::VirtualGuardImpl impl(device_type);
116
+ // impl.synchronizeDevice should can be safely called from any device
117
+ impl.synchronizeDevice(device_index);
118
+ }
119
+
120
+ c10::DeviceIndex exchangeDevice(c10::DeviceIndex device_index) {
121
+ const auto device_type = getAccelerator(true).value();
122
+ c10::impl::VirtualGuardImpl impl(device_type);
123
+ return impl.exchangeDevice({device_type, device_index}).index();
124
+ }
125
+
126
+ c10::DeviceIndex maybeExchangeDevice(c10::DeviceIndex device_index) {
127
+ const auto device_type = getAccelerator(true).value();
128
+ c10::impl::VirtualGuardImpl impl(device_type);
129
+ // Avoid creating a new context if the context for the given device_index
130
+ // is not initialized.
131
+ impl.uncheckedSetDevice({device_type, device_index});
132
+ return impl.getDevice().index();
133
+ }
134
+
135
+ c10::DeviceCapability getDeviceCapability(c10::DeviceIndex device_index) {
136
+ const auto device_type = getAccelerator(true).value();
137
+ c10::impl::VirtualGuardImpl impl(device_type);
138
+ return impl.getDeviceCapability({device_type, device_index});
139
+ }
140
+
141
+ void emptyHostCache() {
142
+ const auto device_type = getAccelerator(true).value();
143
+ at::getHostAllocator(device_type)->empty_cache();
144
+ }
145
+
146
+ const at::Generator& getDefaultGenerator(c10::DeviceIndex device_index) {
147
+ const auto device_type = getAccelerator(true).value();
148
+ return at::globalContext()
149
+ .getAcceleratorHooksInterface(device_type)
150
+ .getDefaultGenerator(device_index);
151
+ }
152
+ // NOLINTEND(bugprone-unchecked-optional-access)
153
+
154
+ } // namespace at::accelerator
western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/CachingDeviceAllocator.h>
4
+ #include <c10/core/DeviceCapability.h>
5
+ #include <c10/core/DeviceType.h>
6
+ #include <c10/macros/Macros.h>
7
+
8
+ #include <ATen/accelerator/Graph.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <optional>
11
+
12
+ namespace at::accelerator {
13
+
14
+ // Note [Accelerator Concept]
15
+ // This file defines the top level Accelerator concept for PyTorch.
16
+ // A device is an accelerator per the definition here if:
17
+ // - It is mutually exclusive with all other accelerators
18
+ // - It performs asynchronous compute via a Stream/Event system
19
+ // - It provides a set of common APIs as defined by AcceleratorHooksInterface
20
+ //
21
+ // As of today, accelerator devices are (in no particular order):
22
+ // CUDA, MTIA, XPU, HIP, MPS, PrivateUse1
23
+
24
+ // Ensures that only one accelerator is available (at
25
+ // compile time if possible) and return it.
26
+ // When checked is true, the returned optional always has a value.
27
+ TORCH_API std::optional<c10::DeviceType> getAccelerator(bool checked = false);
28
+
29
+ // Check if the given device type is an accelerator.
30
+ TORCH_API bool isAccelerator(c10::DeviceType device_type);
31
+
32
+ // Check if the given device type is an accelerator, not the excluded ones.
33
+ template <
34
+ typename... T,
35
+ typename = std::enable_if_t<(std::is_same_v<T, c10::DeviceType> && ...)>>
36
+ inline bool isAcceleratorExcluded(
37
+ c10::DeviceType device_type,
38
+ c10::DeviceType first_excluded,
39
+ T... rest_excluded) {
40
+ if constexpr (sizeof...(rest_excluded) > 0) {
41
+ return device_type != first_excluded &&
42
+ isAcceleratorExcluded(device_type, rest_excluded...);
43
+ } else {
44
+ return device_type != first_excluded && isAccelerator(device_type);
45
+ }
46
+ }
47
+
48
+ // Return the number of the device available. Note that this is *REQUIRED* to
49
+ // not raise any exception.
50
+ TORCH_API c10::DeviceIndex deviceCount();
51
+
52
+ // Set the current device index to the given device index.
53
+ TORCH_API void setDeviceIndex(c10::DeviceIndex device_index);
54
+
55
+ // Get the current device index.
56
+ TORCH_API c10::DeviceIndex getDeviceIndex();
57
+
58
+ // Set the current stream to a given stream. Note that this API doesn't change
59
+ // the current device index.
60
+ TORCH_API void setCurrentStream(c10::Stream stream);
61
+
62
+ // Get the current stream of the given device index.
63
+ TORCH_API c10::Stream getCurrentStream(c10::DeviceIndex device_index);
64
+
65
+ // Wait (by blocking the calling thread) until all the work previously enqueued
66
+ // on the given device index has been completed.
67
+ TORCH_API void synchronizeDevice(c10::DeviceIndex device_index);
68
+
69
+ // Set the current device index to the given device_index and return the
70
+ // original device index that was active before the change.
71
+ TORCH_API c10::DeviceIndex exchangeDevice(c10::DeviceIndex device_index);
72
+
73
+ // Set the current device index to the given device_index. Avoid creating a new
74
+ // context if the context for device_index is not initialized. Return the
75
+ // original device index that was active before the change.
76
+ TORCH_API c10::DeviceIndex maybeExchangeDevice(c10::DeviceIndex device_index);
77
+
78
+ // Get the device capability of the given device index.
79
+ TORCH_API c10::DeviceCapability getDeviceCapability(
80
+ c10::DeviceIndex device_index);
81
+
82
+ // Releases all unused device memory currently held by the accelerator's
83
+ // device-side caching allocator. The freed memory becomes available for reuse
84
+ // by other applications or processes.
85
+ TORCH_API inline void emptyCache() {
86
+ const auto device_type = getAccelerator(true).value();
87
+ at::getDeviceAllocator(device_type)->emptyCache();
88
+ }
89
+
90
+ // Releases all unused host (pinned) memory currently held by the accelerator's
91
+ // host-side caching allocator. The freed memory becomes available for reuse by
92
+ // other applications or processes.
93
+ TORCH_API void emptyHostCache();
94
+
95
+ TORCH_API inline at::CachingDeviceAllocator::DeviceStats getDeviceStats(
96
+ c10::DeviceIndex device_index) {
97
+ const auto device_type = getAccelerator(true).value();
98
+ return at::getDeviceAllocator(device_type)->getDeviceStats(device_index);
99
+ }
100
+
101
+ TORCH_API inline void resetAccumulatedStats(c10::DeviceIndex device_index) {
102
+ const auto device_type = getAccelerator(true).value();
103
+ at::getDeviceAllocator(device_type)->resetAccumulatedStats(device_index);
104
+ }
105
+
106
+ TORCH_API inline void resetPeakStats(c10::DeviceIndex device_index) {
107
+ const auto device_type = getAccelerator(true).value();
108
+ at::getDeviceAllocator(device_type)->resetPeakStats(device_index);
109
+ }
110
+
111
+ TORCH_API inline std::pair<size_t, size_t> getMemoryInfo(
112
+ c10::DeviceIndex device_index) {
113
+ const auto device_type = getAccelerator(true).value();
114
+ return at::getDeviceAllocator(device_type)->getMemoryInfo(device_index);
115
+ }
116
+
117
+ TORCH_API const at::Generator& getDefaultGenerator(
118
+ c10::DeviceIndex device_index);
119
+
120
+ } // namespace at::accelerator
121
+
122
+ namespace at {
123
+ // Keep BC only
124
+ using at::accelerator::getAccelerator;
125
+ using at::accelerator::isAccelerator;
126
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DeviceGuard.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/IListRef.h>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <c10/core/DeviceGuard.h>
6
+ #include <c10/core/ScalarType.h> // TensorList whyyyyy
7
+
8
+ namespace at {
9
+
10
+ // Are you here because you're wondering why DeviceGuard(tensor) no
11
+ // longer works? For code organization reasons, we have temporarily(?)
12
+ // removed this constructor from DeviceGuard. The new way to
13
+ // spell it is:
14
+ //
15
+ // OptionalDeviceGuard guard(device_of(tensor));
16
+
17
+ /// Return the Device of a Tensor, if the Tensor is defined.
18
+ inline std::optional<Device> device_of(const Tensor& t) {
19
+ if (t.defined()) {
20
+ return t.device();
21
+ } else {
22
+ return std::nullopt;
23
+ }
24
+ }
25
+
26
+ inline std::optional<Device> device_of(const std::optional<Tensor>& t) {
27
+ return t.has_value() ? device_of(t.value()) : std::nullopt;
28
+ }
29
+
30
+ /// Return the Device of a TensorList, if the list is non-empty and
31
+ /// the first Tensor is defined. (This function implicitly assumes
32
+ /// that all tensors in the list have the same device.)
33
+ inline std::optional<Device> device_of(ITensorListRef t) {
34
+ if (!t.empty()) {
35
+ return device_of(t.front());
36
+ } else {
37
+ return std::nullopt;
38
+ }
39
+ }
40
+
41
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DimVector.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/DimVector.h>
western_ai/usa/pytorch/aten/src/ATen/Dispatch.cpp ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/Dispatch.h>
2
+ #if defined ENABLE_RECORD_KERNEL_FUNCTION_DTYPE
3
+ #include <ATen/record_function.h>
4
+
5
+ namespace at::detail {
6
+
7
+ void record_kernel_function_dtype(std::string name) {
8
+ RECORD_FUNCTION_WITH_SCOPE(
9
+ at::RecordScope::KERNEL_FUNCTION_DTYPE,
10
+ std::move(name),
11
+ c10::ArrayRef<const c10::IValue>{});
12
+ }
13
+
14
+ } // namespace at::detail
15
+ #endif
western_ai/usa/pytorch/aten/src/ATen/Dispatch.h ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/ScalarType.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/Half.h>
7
+ #include <c10/util/Metaprogramming.h>
8
+ #include <c10/util/complex.h>
9
+ #include <torch/headeronly/core/Dispatch.h>
10
+
11
+ #ifdef __CUDACC__
12
+ #include <cuda.h> // For CUDA_VERSION
13
+ #endif
14
+
15
+ #ifdef TEMPLATE_SELECTIVE_BUILD
16
+ #include <ATen/selected_mobile_ops.h>
17
+ #else
18
+ namespace at {
19
+ /**
20
+ * The method should_include_kernel_dtype() returns true/false
21
+ * based on whether the switching code for a specific dtype should be
22
+ * included based on build time constants generated from tracing model
23
+ * execution. This method will be implemented via code-generation and
24
+ * included in this file when code-gen is ready.
25
+ */
26
+ inline constexpr bool should_include_kernel_dtype(
27
+ const char* /*kernel_tag_str*/,
28
+ at::ScalarType /*scalar_type*/
29
+ ) {
30
+ return true;
31
+ }
32
+ } // namespace at
33
+ #endif
34
+
35
+ /**
36
+ * In the Facebook internal build (using BUCK), this macro is enabled by
37
+ * passing in -c pt.enable_record_kernel_dtype=1 when building the tracer
38
+ * binary.
39
+ */
40
+ #if defined ENABLE_RECORD_KERNEL_FUNCTION_DTYPE
41
+ namespace at::detail {
42
+ TORCH_API void record_kernel_function_dtype(std::string name);
43
+ } // namespace at::detail
44
+
45
+ #define RECORD_KERNEL_FUNCTION_DTYPE(NAME, enum_type) \
46
+ at::detail::record_kernel_function_dtype( \
47
+ std::string(NAME) + "$" + toString(enum_type));
48
+ #else
49
+ #define RECORD_KERNEL_FUNCTION_DTYPE(NAME, enum_type)
50
+ #endif
51
+
52
+ #define AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type) \
53
+ do { \
54
+ if constexpr (!at::should_include_kernel_dtype( \
55
+ at_dispatch_name, enum_type)) { \
56
+ TORCH_CHECK( \
57
+ false, \
58
+ "dtype '", \
59
+ toString(enum_type), \
60
+ "' not selected for kernel tag ", \
61
+ at_dispatch_name); \
62
+ } \
63
+ } while (0)
64
+
65
+ #define AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, HINT, ...) \
66
+ THO_PRIVATE_CASE_TYPE_USING_HINT_TMPL( \
67
+ AT_PRIVATE_CHECK_SELECTIVE_BUILD, enum_type, HINT, __VA_ARGS__)
68
+
69
+ #define AT_DISPATCH_CASE(enum_type, ...) \
70
+ AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__)
71
+
72
+ #define AT_DISPATCH_CASE_QINT(enum_type, scalar_type, ...) \
73
+ case enum_type: { \
74
+ AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type); \
75
+ using scalar_t = scalar_type; \
76
+ using underlying_t [[maybe_unused]] = typename scalar_t::underlying; \
77
+ [[maybe_unused]] const auto& SCALAR_TYPE = enum_type; \
78
+ [[maybe_unused]] const auto& UNDERLYING_TYPE = toUnderlying(enum_type); \
79
+ return __VA_ARGS__(); \
80
+ }
81
+
82
+ #define AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
83
+ enum_type, scalar_type, bitwidth, qmin, qmax, ...) \
84
+ case enum_type: { \
85
+ AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type); \
86
+ using scalar_t = scalar_type; \
87
+ using underlying_t [[maybe_unused]] = typename scalar_t::underlying; \
88
+ [[maybe_unused]] const auto& SCALAR_TYPE = enum_type; \
89
+ [[maybe_unused]] const auto& UNDERLYING_TYPE = toUnderlying(enum_type); \
90
+ [[maybe_unused]] int bit_width = bitwidth; \
91
+ [[maybe_unused]] int64_t quant_min = qmin; \
92
+ [[maybe_unused]] int64_t quant_max = qmax; \
93
+ return __VA_ARGS__(); \
94
+ }
95
+
96
+ // The AT_DISPATCH_* family of macros provides the ability to
97
+ // conveniently generate specializations of a kernel over all of the
98
+ // dtypes we care about in PyTorch. We call it "dispatch" because
99
+ // we are "dispatching" to the correct, dtype-specific kernel.
100
+ //
101
+ // A standard usage looks like:
102
+ //
103
+ // AT_DISPATCH_ALL_TYPES(self.scalar_type(), "op_name", [&] {
104
+ // // Your code here, with 'scalar_t' now defined to
105
+ // // be the dtype in question
106
+ // });
107
+ //
108
+ // There are many variations of this macro, so it's important to
109
+ // understand exactly /which/ dtypes you want to get instantiated, as
110
+ // well as what the "default" set is.
111
+ //
112
+ // The default set of dtypes that are instantiated (e.g., by
113
+ // AT_DISPATCH_ALL_TYPES) are floating point types (float, double),
114
+ // and integral types (int32_t, int64_t, int16_t, int8_t, uint8_t),
115
+ // but NOT booleans (bool), half-precision floats (Half) or
116
+ // complex number (c10::complex<float>, c10::complex<double>).
117
+ // This "cut" is somewhat historical (the default types are the
118
+ // ones that TH historically supported), but it also reflects the
119
+ // fact that the non-default types are "poorly" behaved (booleans
120
+ // are NOT integers mod 2, half precision operations ~essentially
121
+ // don't exist on CPU, complex numbers are an experimental application).
122
+ //
123
+ // Here are the questions you should generally ask to decide which
124
+ // dispatch you want:
125
+ //
126
+ // 1. Is this an integral or floating point specific operation?
127
+ // (If so, you'll want one of the FLOATING or INTEGRAL macros.)
128
+ //
129
+ // 2. Should half be supported? (If you're on CPU, the answer is almost
130
+ // definitely no. If you do want support, use one of the AND_HALF
131
+ // macros)
132
+ //
133
+ // Much rarer situations:
134
+ //
135
+ // 3. Should bool be supported? (You often have to write your kernel
136
+ // differently if arithmetic operations are involved.) If so,
137
+ // Use AT_DISPATCH_ALL_TYPES_AND along with ScalarType::Bool
138
+ //
139
+ // 4. Should complex be supported? The answer is almost always no,
140
+ // unless you are working on "generic" code that should work on
141
+ // all dtypes.
142
+ //
143
+ // Parameters:
144
+ // -----------
145
+ //
146
+ // 1. The NAME argument is a "tag" that is used to trace and then
147
+ // conditionally compile fragments of the case statements such
148
+ // that the kernel functions are specialized only for the dtypes
149
+ // that are needed. The NAME parameter *must* be a build time
150
+ // const char* (can't be std::string, etc...)
151
+ //
152
+ // Please ensure that the NAME is unique for every implementation
153
+ // or you run the risk of over-including code for the kernel
154
+ // functions. There is no risk of missing out on any code, so
155
+ // it's mostly a risk of a Type-2 error, and not a Type-1 error.
156
+ //
157
+ // Switch-like syntax:
158
+ // -------------------
159
+ // There is also a switch-case like syntax which is useful if a kernel
160
+ // needs to be specialized for particular scalar types
161
+ //
162
+ // AT_DISPATCH_SWITCH(self.scalar_type(), "op_name",
163
+ // AT_DISPATCH_CASE_INTEGRAL_TYPES([&] {
164
+ // op_integral<scalar_t>(iter);
165
+ // })
166
+ // AT_DISPATCH_CASE_FLOATING_TYPES([&] {
167
+ // op_floating<scalar_t>(iter);
168
+ // })
169
+ // AT_DISPATCH_CASE(kBool, [&] {
170
+ // op_bool(iter);
171
+ // })
172
+ // );
173
+ //
174
+ // For each AT_DISPATCH_FOO macro, there is a corresponding
175
+ // AT_DISPATCH_CASE_FOO macro which can be used inside of an
176
+ // AT_DISPATCH_SWITCH block.
177
+
178
+ // NB: the the_type variable is not used, but we have kept it for
179
+ // backwards compatibility. It's probably not used by anyone though;
180
+ // but we're just being safe (and it doesn't hurt.) Note we must
181
+ // use it to shut up warnings about unused store.
182
+
183
+ #define AT_DISPATCH_SWITCH(TYPE, NAME, ...) \
184
+ THO_DISPATCH_SWITCH_TMPL( \
185
+ RECORD_KERNEL_FUNCTION_DTYPE, \
186
+ TORCH_CHECK_NOT_IMPLEMENTED, \
187
+ TYPE, \
188
+ NAME, \
189
+ __VA_ARGS__)
190
+
191
+ #define AT_DISPATCH_CASE_FLOATING_TYPES(...) \
192
+ AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
193
+ AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__)
194
+
195
+ #define AT_DISPATCH_FLOATING_TYPES(TYPE, NAME, ...) \
196
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
197
+
198
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF(...) \
199
+ AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
200
+ AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__) \
201
+ AT_DISPATCH_CASE(at::ScalarType::Half, __VA_ARGS__)
202
+
203
+ #define AT_DISPATCH_FLOATING_TYPES_AND_HALF(TYPE, NAME, ...) \
204
+ AT_DISPATCH_SWITCH( \
205
+ TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF(__VA_ARGS__))
206
+
207
+ #define AT_DISPATCH_CASE_REDUCED_FLOATING_TYPES(...) \
208
+ AT_DISPATCH_CASE(at::ScalarType::Half, __VA_ARGS__) \
209
+ AT_DISPATCH_CASE(at::ScalarType::BFloat16, __VA_ARGS__)
210
+
211
+ #define AT_DISPATCH_REDUCED_FLOATING_TYPES(TYPE, NAME, ...) \
212
+ AT_DISPATCH_SWITCH( \
213
+ TYPE, NAME, AT_DISPATCH_CASE_REDUCED_FLOATING_TYPES(__VA_ARGS__))
214
+
215
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND(SCALARTYPE, ...) \
216
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
217
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
218
+
219
+ #define AT_DISPATCH_FLOATING_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \
220
+ AT_DISPATCH_SWITCH( \
221
+ TYPE, \
222
+ NAME, \
223
+ AT_DISPATCH_CASE_FLOATING_TYPES_AND(SCALARTYPE, __VA_ARGS__))
224
+
225
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \
226
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
227
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
228
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__)
229
+
230
+ #define AT_DISPATCH_FLOATING_TYPES_AND2( \
231
+ SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \
232
+ AT_DISPATCH_SWITCH( \
233
+ TYPE, \
234
+ NAME, \
235
+ AT_DISPATCH_CASE_FLOATING_TYPES_AND2( \
236
+ SCALARTYPE1, SCALARTYPE2, __VA_ARGS__))
237
+
238
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND3( \
239
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \
240
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
241
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
242
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
243
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__)
244
+
245
+ #define AT_DISPATCH_FLOATING_TYPES_AND3( \
246
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \
247
+ AT_DISPATCH_SWITCH( \
248
+ TYPE, \
249
+ NAME, \
250
+ AT_DISPATCH_CASE_FLOATING_TYPES_AND3( \
251
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__))
252
+
253
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND4( \
254
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \
255
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
256
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
257
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
258
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
259
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__)
260
+
261
+ #define AT_DISPATCH_CASE_FLOATING_TYPES_AND5( \
262
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \
263
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
264
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
265
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
266
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
267
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
268
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__)
269
+
270
+ #define AT_DISPATCH_FLOATING_TYPES_AND4( \
271
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \
272
+ AT_DISPATCH_SWITCH( \
273
+ TYPE, \
274
+ NAME, \
275
+ AT_DISPATCH_CASE_FLOATING_TYPES_AND4( \
276
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__))
277
+
278
+ #define AT_DISPATCH_FLOATING_TYPES_AND5( \
279
+ SCALARTYPE1, \
280
+ SCALARTYPE2, \
281
+ SCALARTYPE3, \
282
+ SCALARTYPE4, \
283
+ SCALARTYPE5, \
284
+ TYPE, \
285
+ NAME, \
286
+ ...) \
287
+ AT_DISPATCH_SWITCH( \
288
+ TYPE, \
289
+ NAME, \
290
+ AT_DISPATCH_CASE_FLOATING_TYPES_AND5( \
291
+ SCALARTYPE1, \
292
+ SCALARTYPE2, \
293
+ SCALARTYPE3, \
294
+ SCALARTYPE4, \
295
+ SCALARTYPE5, \
296
+ __VA_ARGS__))
297
+
298
+ #define AT_DISPATCH_CASE_COMPLEX_TYPES(...) \
299
+ AT_DISPATCH_CASE(at::ScalarType::ComplexDouble, __VA_ARGS__) \
300
+ AT_DISPATCH_CASE(at::ScalarType::ComplexFloat, __VA_ARGS__)
301
+
302
+ #define AT_DISPATCH_COMPLEX_TYPES(TYPE, NAME, ...) \
303
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__))
304
+
305
+ #define AT_DISPATCH_CASE_COMPLEX_TYPES_AND(SCALARTYPE, ...) \
306
+ AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) \
307
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
308
+
309
+ #define AT_DISPATCH_CASE_COMPLEX_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \
310
+ AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) \
311
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
312
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__)
313
+
314
+ #define AT_DISPATCH_COMPLEX_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \
315
+ AT_DISPATCH_SWITCH( \
316
+ TYPE, NAME, AT_DISPATCH_CASE_COMPLEX_TYPES_AND(SCALARTYPE, __VA_ARGS__))
317
+
318
+ #define AT_DISPATCH_COMPLEX_TYPES_AND2( \
319
+ SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \
320
+ AT_DISPATCH_SWITCH( \
321
+ TYPE, \
322
+ NAME, \
323
+ AT_DISPATCH_CASE_COMPLEX_TYPES_AND2( \
324
+ SCALARTYPE1, SCALARTYPE2, __VA_ARGS__))
325
+
326
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(...) \
327
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \
328
+ AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__)
329
+
330
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(TYPE, NAME, ...) \
331
+ AT_DISPATCH_SWITCH( \
332
+ TYPE, NAME, AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__))
333
+
334
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND1(SCALARTYPE, ...) \
335
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
336
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
337
+
338
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND1( \
339
+ SCALARTYPE, TYPE, NAME, ...) \
340
+ AT_DISPATCH_SWITCH( \
341
+ TYPE, \
342
+ NAME, \
343
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND1( \
344
+ SCALARTYPE, __VA_ARGS__))
345
+
346
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND2( \
347
+ SCALARTYPE1, SCALARTYPE2, ...) \
348
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
349
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
350
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__)
351
+
352
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( \
353
+ SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \
354
+ AT_DISPATCH_SWITCH( \
355
+ TYPE, \
356
+ NAME, \
357
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND2( \
358
+ SCALARTYPE1, SCALARTYPE2, __VA_ARGS__))
359
+
360
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND3( \
361
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \
362
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
363
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
364
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
365
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__)
366
+
367
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3( \
368
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \
369
+ AT_DISPATCH_SWITCH( \
370
+ TYPE, \
371
+ NAME, \
372
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND3( \
373
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__))
374
+
375
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND4( \
376
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \
377
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
378
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
379
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
380
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
381
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__)
382
+
383
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND4( \
384
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \
385
+ AT_DISPATCH_SWITCH( \
386
+ TYPE, \
387
+ NAME, \
388
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND4( \
389
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__))
390
+
391
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND5( \
392
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \
393
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
394
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
395
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
396
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
397
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
398
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__)
399
+
400
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND5( \
401
+ SCALARTYPE1, \
402
+ SCALARTYPE2, \
403
+ SCALARTYPE3, \
404
+ SCALARTYPE4, \
405
+ SCALARTYPE5, \
406
+ TYPE, \
407
+ NAME, \
408
+ ...) \
409
+ AT_DISPATCH_SWITCH( \
410
+ TYPE, \
411
+ NAME, \
412
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND5( \
413
+ SCALARTYPE1, \
414
+ SCALARTYPE2, \
415
+ SCALARTYPE3, \
416
+ SCALARTYPE4, \
417
+ SCALARTYPE5, \
418
+ __VA_ARGS__))
419
+
420
+ #define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND6( \
421
+ SCALARTYPE1, \
422
+ SCALARTYPE2, \
423
+ SCALARTYPE3, \
424
+ SCALARTYPE4, \
425
+ SCALARTYPE5, \
426
+ SCALARTYPE6, \
427
+ ...) \
428
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \
429
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
430
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
431
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
432
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
433
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \
434
+ AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__)
435
+
436
+ #define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND6( \
437
+ SCALARTYPE1, \
438
+ SCALARTYPE2, \
439
+ SCALARTYPE3, \
440
+ SCALARTYPE4, \
441
+ SCALARTYPE5, \
442
+ SCALARTYPE6, \
443
+ TYPE, \
444
+ NAME, \
445
+ ...) \
446
+ AT_DISPATCH_SWITCH( \
447
+ TYPE, \
448
+ NAME, \
449
+ AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND6( \
450
+ SCALARTYPE1, \
451
+ SCALARTYPE2, \
452
+ SCALARTYPE3, \
453
+ SCALARTYPE4, \
454
+ SCALARTYPE5, \
455
+ SCALARTYPE6, \
456
+ __VA_ARGS__))
457
+
458
+ #define AT_DISPATCH_CASE_INTEGRAL_TYPES(...) \
459
+ AT_DISPATCH_CASE(at::ScalarType::Byte, __VA_ARGS__) \
460
+ AT_DISPATCH_CASE(at::ScalarType::Char, __VA_ARGS__) \
461
+ AT_DISPATCH_CASE(at::ScalarType::Int, __VA_ARGS__) \
462
+ AT_DISPATCH_CASE(at::ScalarType::Long, __VA_ARGS__) \
463
+ AT_DISPATCH_CASE(at::ScalarType::Short, __VA_ARGS__)
464
+
465
+ #define AT_DISPATCH_INTEGRAL_TYPES(TYPE, NAME, ...) \
466
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__))
467
+
468
+ #define AT_DISPATCH_CASE_INTEGRAL_TYPES_AND(SCALARTYPE, ...) \
469
+ AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__) \
470
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
471
+
472
+ #define AT_DISPATCH_INTEGRAL_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \
473
+ AT_DISPATCH_SWITCH( \
474
+ TYPE, \
475
+ NAME, \
476
+ AT_DISPATCH_CASE_INTEGRAL_TYPES_AND(SCALARTYPE, __VA_ARGS__))
477
+
478
+ #define AT_DISPATCH_CASE_ALL_TYPES(...) \
479
+ AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__) \
480
+ AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__)
481
+
482
+ #define AT_DISPATCH_ALL_TYPES(TYPE, NAME, ...) \
483
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__))
484
+
485
+ #define AT_DISPATCH_CASE_QINT_TYPES(...) \
486
+ AT_DISPATCH_CASE_QINT(at::kQInt8, at::qint8, __VA_ARGS__) \
487
+ AT_DISPATCH_CASE_QINT(at::kQUInt8, at::quint8, __VA_ARGS__) \
488
+ AT_DISPATCH_CASE_QINT(at::kQInt32, at::qint32, __VA_ARGS__)
489
+
490
+ #define AT_DISPATCH_QINT_TYPES(TYPE, NAME, ...) \
491
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_QINT_TYPES(__VA_ARGS__))
492
+
493
+ #define AT_DISPATCH_CASE_QINT_TYPES_AND(SCALARTYPE, ...) \
494
+ AT_DISPATCH_CASE_QINT_TYPES(__VA_ARGS__) \
495
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
496
+
497
+ #define AT_DISPATCH_QINT_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \
498
+ AT_DISPATCH_SWITCH( \
499
+ TYPE, NAME, AT_DISPATCH_CASE_QINT_TYPES_AND(SCALARTYPE, __VA_ARGS__))
500
+
501
+ #define AT_DISPATCH_CASE_QINT_BYTE_TYPES(...) \
502
+ AT_DISPATCH_CASE_QINT(at::kQInt8, at::qint8, __VA_ARGS__) \
503
+ AT_DISPATCH_CASE_QINT(at::kQUInt8, at::quint8, __VA_ARGS__)
504
+
505
+ #define AT_DISPATCH_QINT_BYTE_TYPES(TYPE, NAME, ...) \
506
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_QINT_BYTE_TYPES(__VA_ARGS__))
507
+
508
+ #define AT_DISPATCH_CASE_QINT_AND_SUB_BYTE_TYPES(...) \
509
+ AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
510
+ at::kQInt8, at::qint8, CHAR_BIT, SCHAR_MIN, SCHAR_MAX, __VA_ARGS__) \
511
+ AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
512
+ at::kQUInt8, at::quint8, CHAR_BIT, 0, UCHAR_MAX, __VA_ARGS__) \
513
+ AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
514
+ at::kQInt32, \
515
+ at::qint32, \
516
+ CHAR_BIT * sizeof(int), \
517
+ INT_MIN, \
518
+ INT_MAX, \
519
+ __VA_ARGS__) \
520
+ AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
521
+ at::kQUInt4x2, at::quint4x2, 4, 0, 15, __VA_ARGS__) \
522
+ AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \
523
+ at::kQUInt2x4, at::quint2x4, 2, 0, 3, __VA_ARGS__)
524
+
525
+ #define AT_DISPATCH_QINT_AND_SUB_BYTE_TYPES(TYPE, NAME, ...) \
526
+ AT_DISPATCH_SWITCH( \
527
+ TYPE, NAME, AT_DISPATCH_CASE_QINT_AND_SUB_BYTE_TYPES(__VA_ARGS__))
528
+
529
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(...) \
530
+ AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \
531
+ AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__)
532
+
533
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX(TYPE, NAME, ...) \
534
+ AT_DISPATCH_SWITCH( \
535
+ TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__))
536
+
537
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND(SCALARTYPE, ...) \
538
+ AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \
539
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
540
+
541
+ #define AT_DISPATCH_ALL_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \
542
+ AT_DISPATCH_SWITCH( \
543
+ TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES_AND(SCALARTYPE, __VA_ARGS__))
544
+
545
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, ...) \
546
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
547
+ AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__)
548
+
549
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, TYPE, NAME, ...) \
550
+ AT_DISPATCH_SWITCH( \
551
+ TYPE, \
552
+ NAME, \
553
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, __VA_ARGS__))
554
+
555
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \
556
+ AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \
557
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
558
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__)
559
+
560
+ #define AT_DISPATCH_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \
561
+ AT_DISPATCH_SWITCH( \
562
+ TYPE, \
563
+ NAME, \
564
+ AT_DISPATCH_CASE_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, __VA_ARGS__))
565
+
566
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND2( \
567
+ SCALARTYPE1, SCALARTYPE2, ...) \
568
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
569
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
570
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__)
571
+
572
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( \
573
+ SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \
574
+ AT_DISPATCH_SWITCH( \
575
+ TYPE, \
576
+ NAME, \
577
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND2( \
578
+ SCALARTYPE1, SCALARTYPE2, __VA_ARGS__))
579
+
580
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND3( \
581
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \
582
+ AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \
583
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
584
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
585
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__)
586
+
587
+ #define AT_DISPATCH_ALL_TYPES_AND3( \
588
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \
589
+ AT_DISPATCH_SWITCH( \
590
+ TYPE, \
591
+ NAME, \
592
+ AT_DISPATCH_CASE_ALL_TYPES_AND3( \
593
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__))
594
+
595
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND3( \
596
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \
597
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
598
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
599
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
600
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__)
601
+
602
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( \
603
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \
604
+ AT_DISPATCH_SWITCH( \
605
+ TYPE, \
606
+ NAME, \
607
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND3( \
608
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__))
609
+
610
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND4( \
611
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \
612
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
613
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
614
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
615
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
616
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__)
617
+
618
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4( \
619
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \
620
+ AT_DISPATCH_SWITCH( \
621
+ TYPE, \
622
+ NAME, \
623
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND4( \
624
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__))
625
+
626
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND5( \
627
+ SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \
628
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
629
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
630
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
631
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
632
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
633
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__)
634
+
635
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5( \
636
+ SCALARTYPE1, \
637
+ SCALARTYPE2, \
638
+ SCALARTYPE3, \
639
+ SCALARTYPE4, \
640
+ SCALARTYPE5, \
641
+ TYPE, \
642
+ NAME, \
643
+ ...) \
644
+ AT_DISPATCH_SWITCH( \
645
+ TYPE, \
646
+ NAME, \
647
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND5( \
648
+ SCALARTYPE1, \
649
+ SCALARTYPE2, \
650
+ SCALARTYPE3, \
651
+ SCALARTYPE4, \
652
+ SCALARTYPE5, \
653
+ __VA_ARGS__))
654
+
655
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND6( \
656
+ SCALARTYPE1, \
657
+ SCALARTYPE2, \
658
+ SCALARTYPE3, \
659
+ SCALARTYPE4, \
660
+ SCALARTYPE5, \
661
+ SCALARTYPE6, \
662
+ ...) \
663
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
664
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
665
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
666
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
667
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
668
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \
669
+ AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__)
670
+
671
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND6( \
672
+ SCALARTYPE1, \
673
+ SCALARTYPE2, \
674
+ SCALARTYPE3, \
675
+ SCALARTYPE4, \
676
+ SCALARTYPE5, \
677
+ SCALARTYPE6, \
678
+ TYPE, \
679
+ NAME, \
680
+ ...) \
681
+ AT_DISPATCH_SWITCH( \
682
+ TYPE, \
683
+ NAME, \
684
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND6( \
685
+ SCALARTYPE1, \
686
+ SCALARTYPE2, \
687
+ SCALARTYPE3, \
688
+ SCALARTYPE4, \
689
+ SCALARTYPE5, \
690
+ SCALARTYPE6, \
691
+ __VA_ARGS__))
692
+
693
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND7( \
694
+ SCALARTYPE1, \
695
+ SCALARTYPE2, \
696
+ SCALARTYPE3, \
697
+ SCALARTYPE4, \
698
+ SCALARTYPE5, \
699
+ SCALARTYPE6, \
700
+ SCALARTYPE7, \
701
+ ...) \
702
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
703
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
704
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
705
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
706
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
707
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \
708
+ AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) \
709
+ AT_DISPATCH_CASE(SCALARTYPE7, __VA_ARGS__)
710
+
711
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND7( \
712
+ SCALARTYPE1, \
713
+ SCALARTYPE2, \
714
+ SCALARTYPE3, \
715
+ SCALARTYPE4, \
716
+ SCALARTYPE5, \
717
+ SCALARTYPE6, \
718
+ SCALARTYPE7, \
719
+ TYPE, \
720
+ NAME, \
721
+ ...) \
722
+ AT_DISPATCH_SWITCH( \
723
+ TYPE, \
724
+ NAME, \
725
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND7( \
726
+ SCALARTYPE1, \
727
+ SCALARTYPE2, \
728
+ SCALARTYPE3, \
729
+ SCALARTYPE4, \
730
+ SCALARTYPE5, \
731
+ SCALARTYPE6, \
732
+ SCALARTYPE7, \
733
+ __VA_ARGS__))
734
+
735
+ #define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND8( \
736
+ SCALARTYPE1, \
737
+ SCALARTYPE2, \
738
+ SCALARTYPE3, \
739
+ SCALARTYPE4, \
740
+ SCALARTYPE5, \
741
+ SCALARTYPE6, \
742
+ SCALARTYPE7, \
743
+ SCALARTYPE8, \
744
+ ...) \
745
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \
746
+ AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \
747
+ AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \
748
+ AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \
749
+ AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \
750
+ AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \
751
+ AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) \
752
+ AT_DISPATCH_CASE(SCALARTYPE7, __VA_ARGS__) \
753
+ AT_DISPATCH_CASE(SCALARTYPE8, __VA_ARGS__)
754
+
755
+ #define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND8( \
756
+ SCALARTYPE1, \
757
+ SCALARTYPE2, \
758
+ SCALARTYPE3, \
759
+ SCALARTYPE4, \
760
+ SCALARTYPE5, \
761
+ SCALARTYPE6, \
762
+ SCALARTYPE7, \
763
+ SCALARTYPE8, \
764
+ TYPE, \
765
+ NAME, \
766
+ ...) \
767
+ AT_DISPATCH_SWITCH( \
768
+ TYPE, \
769
+ NAME, \
770
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND8( \
771
+ SCALARTYPE1, \
772
+ SCALARTYPE2, \
773
+ SCALARTYPE3, \
774
+ SCALARTYPE4, \
775
+ SCALARTYPE5, \
776
+ SCALARTYPE6, \
777
+ SCALARTYPE7, \
778
+ SCALARTYPE8, \
779
+ __VA_ARGS__))
780
+
781
+ #define AT_DISPATCH_CASE_BIT_TYPES(...) \
782
+ AT_DISPATCH_CASE(at::ScalarType::Bits1x8, __VA_ARGS__) \
783
+ AT_DISPATCH_CASE(at::ScalarType::Bits2x4, __VA_ARGS__) \
784
+ AT_DISPATCH_CASE(at::ScalarType::Bits4x2, __VA_ARGS__) \
785
+ AT_DISPATCH_CASE(at::ScalarType::Bits8, __VA_ARGS__) \
786
+ AT_DISPATCH_CASE(at::ScalarType::Bits16, __VA_ARGS__)
787
+
788
+ #define AT_DISPATCH_BIT_TYPES(TYPE, NAME, ...) \
789
+ AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_BIT_TYPES(__VA_ARGS__))
790
+
791
+ #define AT_DISPATCH_INDEX_TYPES(TYPE, NAME, ...) \
792
+ AT_DISPATCH_SWITCH( \
793
+ TYPE, \
794
+ NAME, \
795
+ AT_PRIVATE_CASE_TYPE_USING_HINT( \
796
+ at::ScalarType::Int, index_t, __VA_ARGS__) \
797
+ AT_PRIVATE_CASE_TYPE_USING_HINT( \
798
+ at::ScalarType::Long, index_t, __VA_ARGS__))
western_ai/usa/pytorch/aten/src/ATen/Dispatch_v2.h ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/headeronly/core/Dispatch_v2.h>
4
+
5
+ // Get AT_DISPATCH_SWITCH and AT_DISPATCH_CASE:
6
+ #include <ATen/Dispatch.h>
7
+
8
+ // This is a new implementation of the AT_DISPATCH macro family from
9
+ // ATen/Dispatch.h
10
+ //
11
+ // The intended usage is:
12
+ //
13
+ // ScalarType scalar_type;
14
+ //
15
+ // AT_DISPATCH_V2(
16
+ // scalar_type,
17
+ // "debug string",
18
+ // AT_WRAP([&] {
19
+ // ... code to specialize with scalar_t ...
20
+ // }),
21
+ // kHalf,
22
+ // AT_EXPAND(AT_ALL_TYPES),
23
+ // ... as many types arguments as needed ...
24
+ // )
25
+ //
26
+ // For example, given an old style:
27
+ //
28
+ // AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(
29
+ // kComplexHalf,
30
+ // kHalf,
31
+ // self.scalar_type(),
32
+ // "_local_scalar_dense_cpu",
33
+ // [&] {
34
+ // scalar_t value = *self.data_ptr<scalar_t>();
35
+ // r = Scalar(value);
36
+ // }
37
+ // )
38
+ //
39
+ // You now write:
40
+ //
41
+ // AT_DISPATCH_V2(
42
+ // self.scalar_type(),
43
+ // "_local_scalar_dense_cpu",
44
+ // AT_WRAP([&] {
45
+ // scalar_t value = *self.data_ptr<scalar_t>();
46
+ // r = Scalar(value);
47
+ // }),
48
+ // AT_EXPAND(AT_ALL_TYPES),
49
+ // AT_EXPAND(AT_COMPLEX_TYPES),
50
+ // kComplexHalf,
51
+ // kHalf,
52
+ // )
53
+ //
54
+ // Notably, it sports the following improvements:
55
+ //
56
+ // - It is not necessary to specify the arity (e.g.,
57
+ // AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND{2,3,4,...})
58
+ // when using the macro
59
+ //
60
+ // - It is not necessary to specify each dtype individually; if
61
+ // there is a set of related dtypes and you want to dispatch
62
+ // over all of them, you can simply say, e.g., AT_EXPAND(AT_INTEGRAL_TYPES)
63
+ // in your argument list.
64
+ //
65
+ // However, you must remember to wrap the payload body in AT_WRAP, or commas
66
+ // inside your lambda will be improperly handled. Furthermore, if you more
67
+ // entries to ScalarType than can be supported by this macro, it will fail
68
+ // with an obscure error (due to attempting to concatenate AT_AP with
69
+ // something that is not a number).
70
+ //
71
+ // The implementation strategy is to use the count arguments trick
72
+ // (e.g., as described in https://stackoverflow.com/a/2124385/23845)
73
+ // to discover how many dtypes have been passed, and then dispatch to a
74
+ // hand-written macro for each arity that applies as many DISPATCH_CASE as
75
+ // necessary. The hand-written macros can be regenerated for other arities
76
+ // with the script below.
77
+ //
78
+ // There is some delicacy in the implementation in controlling when
79
+ // macro expansion occurs, mediated with AT_EXPAND and AT_GUARD. I mostly
80
+ // relied on GPT4 to help me get it right.
81
+
82
+ // See documentation above
83
+ #define AT_DISPATCH_V2(TYPE, NAME, BODY, ...) \
84
+ THO_DISPATCH_V2_TMPL( \
85
+ AT_DISPATCH_SWITCH, \
86
+ AT_DISPATCH_CASE, \
87
+ TYPE, \
88
+ NAME, \
89
+ AT_WRAP(BODY), \
90
+ __VA_ARGS__)
91
+
92
+ // Unused helper macros, kept for BC:
93
+ #define AT_AP_VAR(N, T, ...) \
94
+ AT_EXPAND(AT_CONCAT(AT_AP, AT_NUM_ARGS(__VA_ARGS__))(AT_WRAP(N), __VA_ARGS__))
95
+
96
+ // Ensure we never have too many scalar types for the expansion here to
97
+ // support. To bump this, you must regenerate the macros below.
98
+ static_assert(static_cast<int>(c10::ScalarType::NumOptions) < 60);
99
+
100
+ // Python code to regenerate generate code below:
101
+ #if 0
102
+
103
+ num_args = 60
104
+
105
+ for i in range(1, num_args+1):
106
+ args = ', '.join(f'_{i}' for i in range(1, i+1))
107
+ cases = ' '.join([f'AT_DISPATCH_CASE(_{j}, N)' for j in range(1, i+1)])
108
+ print(f'#define AT_AP{i}(N, {args}) {cases}')
109
+
110
+ #endif
111
+
112
+ // Begin generated code
113
+ // clang-format off
114
+
115
+ #define AT_AP1(N, _1) AT_DISPATCH_CASE(_1, N)
116
+ #define AT_AP2(N, _1, _2) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N)
117
+ #define AT_AP3(N, _1, _2, _3) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N)
118
+ #define AT_AP4(N, _1, _2, _3, _4) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N)
119
+ #define AT_AP5(N, _1, _2, _3, _4, _5) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N)
120
+ #define AT_AP6(N, _1, _2, _3, _4, _5, _6) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N)
121
+ #define AT_AP7(N, _1, _2, _3, _4, _5, _6, _7) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N)
122
+ #define AT_AP8(N, _1, _2, _3, _4, _5, _6, _7, _8) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N)
123
+ #define AT_AP9(N, _1, _2, _3, _4, _5, _6, _7, _8, _9) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N)
124
+ #define AT_AP10(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N)
125
+ #define AT_AP11(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N)
126
+ #define AT_AP12(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N)
127
+ #define AT_AP13(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N)
128
+ #define AT_AP14(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N)
129
+ #define AT_AP15(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N)
130
+ #define AT_AP16(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N)
131
+ #define AT_AP17(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N)
132
+ #define AT_AP18(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N)
133
+ #define AT_AP19(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N)
134
+ #define AT_AP20(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N)
135
+ #define AT_AP21(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N)
136
+ #define AT_AP22(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N)
137
+ #define AT_AP23(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N)
138
+ #define AT_AP24(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N)
139
+ #define AT_AP25(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N)
140
+ #define AT_AP26(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N)
141
+ #define AT_AP27(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N)
142
+ #define AT_AP28(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N)
143
+ #define AT_AP29(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N)
144
+ #define AT_AP30(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N)
145
+ #define AT_AP31(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N)
146
+ #define AT_AP32(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N)
147
+ #define AT_AP33(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N)
148
+ #define AT_AP34(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N)
149
+ #define AT_AP35(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N)
150
+ #define AT_AP36(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N)
151
+ #define AT_AP37(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N)
152
+ #define AT_AP38(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N)
153
+ #define AT_AP39(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N)
154
+ #define AT_AP40(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N)
155
+ #define AT_AP41(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N)
156
+ #define AT_AP42(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N)
157
+ #define AT_AP43(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N)
158
+ #define AT_AP44(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N)
159
+ #define AT_AP45(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N)
160
+ #define AT_AP46(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N)
161
+ #define AT_AP47(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N)
162
+ #define AT_AP48(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N)
163
+ #define AT_AP49(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N)
164
+ #define AT_AP50(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N)
165
+ #define AT_AP51(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N)
166
+ #define AT_AP52(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N)
167
+ #define AT_AP53(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N)
168
+ #define AT_AP54(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N)
169
+ #define AT_AP55(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N)
170
+ #define AT_AP56(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N)
171
+ #define AT_AP57(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N)
172
+ #define AT_AP58(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N)
173
+ #define AT_AP59(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N) AT_DISPATCH_CASE(_59, N)
174
+ #define AT_AP60(N, _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) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N) AT_DISPATCH_CASE(_59, N) AT_DISPATCH_CASE(_60, N)
175
+
176
+ // End generated code
177
+ // clang-format on
western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.cpp ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <c10/util/Exception.h>
2
+ #include <ATen/DynamicLibrary.h>
3
+
4
+ #ifndef _WIN32
5
+ #include <dlfcn.h>
6
+ #include <libgen.h>
7
+ #else
8
+ #include <c10/util/win32-headers.h>
9
+ #include <c10/util/Unicode.h>
10
+ #endif
11
+
12
+ namespace at {
13
+
14
+
15
+ #ifndef C10_MOBILE
16
+ #ifndef _WIN32
17
+
18
+ // Unix
19
+
20
+ static void* checkDL(void* x) {
21
+ if (!x) {
22
+ TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen or dlsym: ", dlerror());
23
+ }
24
+
25
+ return x;
26
+ }
27
+ DynamicLibrary::DynamicLibrary(const char* name, const char* alt_name, bool leak_handle_): leak_handle(leak_handle_), handle(dlopen(name, RTLD_LOCAL | RTLD_NOW)) {
28
+ if (!handle) {
29
+ if (alt_name) {
30
+ handle = dlopen(alt_name, RTLD_LOCAL | RTLD_NOW);
31
+ if (!handle) {
32
+ TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen for library ", name, "and ", alt_name);
33
+ }
34
+ } else {
35
+ TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen: ", dlerror());
36
+ }
37
+ }
38
+ }
39
+
40
+ void* DynamicLibrary::sym(const char* name) {
41
+ AT_ASSERT(handle);
42
+ return checkDL(dlsym(handle, name));
43
+ }
44
+
45
+ DynamicLibrary::~DynamicLibrary() {
46
+ if (!handle || leak_handle) {
47
+ return;
48
+ }
49
+ dlclose(handle);
50
+ }
51
+
52
+ #else
53
+
54
+ // Windows
55
+
56
+ DynamicLibrary::DynamicLibrary(const char* name, const char* alt_name, bool leak_handle_): leak_handle(leak_handle_) {
57
+ // NOLINTNEXTLINE(hicpp-signed-bitwise)
58
+ HMODULE theModule;
59
+ bool reload = true;
60
+ auto wname = c10::u8u16(name);
61
+ // Check if LOAD_LIBRARY_SEARCH_DEFAULT_DIRS is supported
62
+ if (GetProcAddress(GetModuleHandleW(L"KERNEL32.DLL"), "AddDllDirectory") != NULL) {
63
+ theModule = LoadLibraryExW(
64
+ wname.c_str(),
65
+ NULL,
66
+ LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
67
+ if (theModule != NULL || (GetLastError() != ERROR_MOD_NOT_FOUND)) {
68
+ reload = false;
69
+ }
70
+ }
71
+
72
+ if (reload) {
73
+ theModule = LoadLibraryW(wname.c_str());
74
+ }
75
+
76
+ if (theModule) {
77
+ handle = theModule;
78
+ } else {
79
+ char buf[256];
80
+ DWORD dw = GetLastError();
81
+ FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
82
+ NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
83
+ buf, (sizeof(buf) / sizeof(char)), NULL);
84
+ TORCH_CHECK_WITH(DynamicLibraryError, false, "error in LoadLibrary for ", name, ". WinError ", dw, ": ", buf);
85
+ }
86
+ }
87
+
88
+ void* DynamicLibrary::sym(const char* name) {
89
+ AT_ASSERT(handle);
90
+ FARPROC procAddress = GetProcAddress((HMODULE)handle, name);
91
+ if (!procAddress) {
92
+ TORCH_CHECK_WITH(DynamicLibraryError, false, "error in GetProcAddress");
93
+ }
94
+ return (void*)procAddress;
95
+ }
96
+
97
+ DynamicLibrary::~DynamicLibrary() {
98
+ if (!handle || leak_handle) {
99
+ return;
100
+ }
101
+ FreeLibrary((HMODULE)handle);
102
+ }
103
+
104
+ #endif
105
+ #endif
106
+
107
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Utils.h>
4
+ #include <c10/macros/Export.h>
5
+ #include <c10/util/Exception.h>
6
+
7
+ namespace c10 {
8
+
9
+ class DynamicLibraryError : public Error {
10
+ using Error::Error;
11
+ };
12
+
13
+ } // namespace c10
14
+
15
+ namespace at {
16
+
17
+ struct DynamicLibrary {
18
+ AT_DISALLOW_COPY_AND_ASSIGN(DynamicLibrary);
19
+ DynamicLibrary(DynamicLibrary&& other) = delete;
20
+ DynamicLibrary& operator=(DynamicLibrary&&) = delete;
21
+
22
+ TORCH_API DynamicLibrary(
23
+ const char* name,
24
+ const char* alt_name = nullptr,
25
+ bool leak_handle = false);
26
+
27
+ TORCH_API void* sym(const char* name);
28
+
29
+ TORCH_API ~DynamicLibrary();
30
+
31
+ private:
32
+ bool leak_handle;
33
+ void* handle = nullptr;
34
+ };
35
+
36
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.cpp ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_NO_OPERATORS
2
+ #include <ATen/EmptyTensor.h>
3
+ #include <ATen/Context.h>
4
+ #include <c10/core/CPUAllocator.h>
5
+ #include <c10/util/safe_numerics.h>
6
+
7
+ #include <limits>
8
+
9
+ namespace at::detail {
10
+ namespace {
11
+ c10::Allocator* GetCPUAllocatorMaybePinned(bool pin_memory) {
12
+ if (pin_memory) {
13
+ // NB: This is not quite right, if you somehow had both CUDA and PrivateUse1 initialized
14
+ // in the same PyTorch build, you would ONLY ever get the CUDA pinned memory allocator.
15
+ // To properly support this, see https://github.com/pytorch/pytorch/issues/14560
16
+
17
+ std::optional<c10::DeviceType> opt_device_type = std::nullopt;
18
+ // As mentioned in Note [Accelerator Context], the accelerators in PyTorch should be mutually exclusive,
19
+ // and PrivateUse1 has the highest priority, followed by CUDA;
20
+ // However, since exclusivity between accelerators cannot be guaranteed at present,
21
+ // in order to ensure backward compatibility (previously the default was CUDA), CUDA are prioritized.
22
+ if (at::globalContext().hasCUDA()) {
23
+ opt_device_type = c10::DeviceType::CUDA;
24
+ } else {
25
+ opt_device_type = at::getAccelerator(false);
26
+ }
27
+ if (opt_device_type.has_value()) {
28
+ return at::globalContext().getPinnedMemoryAllocator(opt_device_type);
29
+ } else {
30
+ TORCH_CHECK(
31
+ false,
32
+ "pin_memory=True requires a CUDA or other accelerator backend; "
33
+ "no pinned memory allocator is available on this system.")
34
+ }
35
+ }
36
+
37
+ return c10::GetCPUAllocator();
38
+ }
39
+
40
+ #ifndef C10_MOBILE
41
+ constexpr uint64_t storage_max() {
42
+ // int64_t and size_t are used somewhat inconsistently throughout ATen.
43
+ // To be safe, storage size calculations must fit in both types.
44
+ constexpr auto int64_max = static_cast<uint64_t>(
45
+ std::numeric_limits<int64_t>::max());
46
+ constexpr auto size_max = static_cast<uint64_t>(
47
+ std::numeric_limits<size_t>::max());
48
+ return std::min(int64_max, size_max);
49
+ }
50
+ #endif
51
+
52
+ inline void raise_warning_for_complex_half(ScalarType dtype) {
53
+ if (dtype == kComplexHalf) {
54
+ TORCH_WARN_ONCE(
55
+ "ComplexHalf support is experimental and many operators don't support it yet.");
56
+ } else if (dtype == kBComplex32) {
57
+ TORCH_WARN_ONCE(
58
+ "BComplex32 support is experimental and many operators don't support it yet.");
59
+ }
60
+ }
61
+
62
+ } // namespace (anonymous)
63
+
64
+ size_t computeStorageNbytesContiguous(
65
+ IntArrayRef sizes,
66
+ size_t itemsize_bytes,
67
+ size_t storage_offset
68
+ ) {
69
+ // Ignore overflow checks on mobile
70
+ #ifndef C10_MOBILE
71
+ uint64_t size = 1;
72
+ bool overflowed = c10::safe_multiplies_u64(sizes, &size);
73
+ overflowed |= c10::add_overflows(size, storage_offset, &size);
74
+ overflowed |= c10::mul_overflows(size, itemsize_bytes, &size);
75
+ overflowed |= size > storage_max();
76
+ TORCH_CHECK(!overflowed,
77
+ "Storage size calculation overflowed with sizes=", sizes);
78
+ return static_cast<size_t>(size);
79
+ #else
80
+ const auto numel = c10::multiply_integers(sizes);
81
+ return itemsize_bytes * (storage_offset + numel);
82
+ #endif
83
+ }
84
+
85
+ size_t computeStorageNbytes(
86
+ IntArrayRef sizes,
87
+ IntArrayRef strides,
88
+ size_t itemsize_bytes,
89
+ size_t storage_offset
90
+ ) {
91
+ TORCH_CHECK(
92
+ sizes.size() == strides.size(),
93
+ "dimensionality of sizes (",
94
+ sizes.size(),
95
+ ") must match dimensionality of strides (",
96
+ strides.size(),
97
+ ")");
98
+
99
+ // Ignore overflow checks on mobile
100
+ #ifndef C10_MOBILE
101
+ // size of the underlying storage is 1 bigger than the offset
102
+ // of the last element according to stride
103
+ uint64_t size = storage_offset + 1;
104
+ bool overflowed = false;
105
+ for (const auto i : c10::irange(sizes.size())) {
106
+ if (sizes[i] == 0) {
107
+ return 0;
108
+ }
109
+
110
+ uint64_t strided_size = 0;
111
+ overflowed |= c10::mul_overflows(strides[i], sizes[i] - 1, &strided_size);
112
+ overflowed |= c10::add_overflows(size, strided_size, &size);
113
+ }
114
+ overflowed |= c10::mul_overflows(size, itemsize_bytes, &size);
115
+ overflowed |= size > storage_max();
116
+ TORCH_CHECK(!overflowed,
117
+ "Storage size calculation overflowed with sizes=",
118
+ sizes, " and strides=", strides);
119
+ return static_cast<size_t>(size);
120
+ #else
121
+ // size of the underlying storage is 1 bigger than the offset
122
+ // of the last element according to stride
123
+ uint64_t size = 1;
124
+ for (const auto i : c10::irange(sizes.size())) {
125
+ if (sizes[i] == 0) {
126
+ return 0;
127
+ }
128
+
129
+ size += strides[i] * (sizes[i] - 1);
130
+ }
131
+ return itemsize_bytes * (storage_offset + size);
132
+ #endif
133
+ }
134
+
135
+ SymInt computeStorageNbytesContiguous(
136
+ SymIntArrayRef sizes,
137
+ const SymInt& itemsize_bytes,
138
+ const SymInt& storage_offset
139
+ ) {
140
+ const auto numel = c10::multiply_integers(sizes);
141
+ return itemsize_bytes * (storage_offset + numel);
142
+ }
143
+
144
+ // not including mobile-only macros in this function,
145
+ // since mobile shouldn't be using symints.
146
+ SymInt computeStorageNbytes(
147
+ SymIntArrayRef sizes,
148
+ SymIntArrayRef strides,
149
+ const SymInt& itemsize_bytes,
150
+ const SymInt& storage_offset
151
+ ) {
152
+ TORCH_CHECK(
153
+ sizes.size() == strides.size(),
154
+ "dimensionality of sizes (",
155
+ sizes.size(),
156
+ ") must match dimensionality of strides (",
157
+ strides.size(),
158
+ ")");
159
+
160
+ // size of the underlying storage is 1 bigger than the offset
161
+ // of the last element according to stride
162
+ SymInt size = 1;
163
+ for (const auto i : c10::irange(sizes.size())) {
164
+ if (TORCH_GUARD_OR_FALSE(sizes[i].sym_eq(0))) {
165
+ return 0;
166
+ }
167
+
168
+ // NOTE: while this can technically return negative sizes for
169
+ // 0-element tensors, there's a check in TensorShape:set_storage_meta__symint
170
+ // that skips setting nbytes with unbacked expressions.
171
+ // Would probably be safer to wrap this with a max(*, 0),
172
+ // once our min/max symbolic reasoning improves.
173
+ size += strides[i] * (sizes[i] - 1);
174
+ }
175
+ return itemsize_bytes * (storage_offset + size);
176
+ }
177
+
178
+ template <typename T>
179
+ static TensorBase _empty_generic(
180
+ ArrayRef<T> size,
181
+ c10::Allocator* allocator,
182
+ c10::DispatchKeySet ks,
183
+ ScalarType scalar_type,
184
+ std::optional<c10::MemoryFormat> memory_format_opt) {
185
+ at::detail::check_size_nonnegative(size);
186
+ at::detail::raise_warning_for_complex_half(scalar_type);
187
+ caffe2::TypeMeta dtype = scalarTypeToTypeMeta(scalar_type);
188
+ auto size_bytes = computeStorageNbytesContiguous(size, dtype.itemsize());
189
+ auto storage_impl = c10::make_intrusive<StorageImpl>(
190
+ c10::StorageImpl::use_byte_size_t(),
191
+ size_bytes,
192
+ allocator,
193
+ /*resizeable=*/true);
194
+
195
+ auto tensor = detail::make_tensor_base<TensorImpl>(
196
+ std::move(storage_impl), ks, dtype);
197
+ // Default TensorImpl has size [0]
198
+ // NB: test for meta dispatch key to avoid guarding on zero-ness
199
+ if (ks.has(c10::DispatchKey::Meta) || size.size() != 1 || size[0] != 0) {
200
+ tensor.unsafeGetTensorImpl()->generic_set_sizes_contiguous(size);
201
+ }
202
+
203
+ if (memory_format_opt.has_value()) {
204
+ // Restriding a just-created empty contiguous tensor does nothing.
205
+ if (*memory_format_opt != MemoryFormat::Contiguous) {
206
+ tensor.unsafeGetTensorImpl()->empty_tensor_restride(*memory_format_opt);
207
+ }
208
+ }
209
+
210
+ return tensor;
211
+ }
212
+
213
+ TensorBase empty_generic(
214
+ IntArrayRef size,
215
+ c10::Allocator* allocator,
216
+ c10::DispatchKeySet ks,
217
+ ScalarType scalar_type,
218
+ std::optional<c10::MemoryFormat> memory_format_opt) {
219
+ return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt);
220
+ }
221
+
222
+ TensorBase empty_generic_symint(
223
+ SymIntArrayRef size,
224
+ c10::Allocator* allocator,
225
+ c10::DispatchKeySet ks,
226
+ ScalarType scalar_type,
227
+ std::optional<c10::MemoryFormat> memory_format_opt) {
228
+ return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt);
229
+ }
230
+
231
+ template <typename T>
232
+ static TensorBase _empty_strided_generic(
233
+ T size,
234
+ T stride,
235
+ c10::Allocator* allocator,
236
+ c10::DispatchKeySet ks,
237
+ ScalarType scalar_type) {
238
+ at::detail::check_size_nonnegative(size);
239
+ at::detail::raise_warning_for_complex_half(scalar_type);
240
+ caffe2::TypeMeta dtype = scalarTypeToTypeMeta(scalar_type);
241
+ auto size_bytes = computeStorageNbytes(size, stride, dtype.itemsize());
242
+ auto storage_impl = c10::make_intrusive<StorageImpl>(
243
+ c10::StorageImpl::use_byte_size_t(),
244
+ size_bytes,
245
+ allocator,
246
+ /*resizeable=*/true);
247
+
248
+ auto tensor = detail::make_tensor_base<TensorImpl>(
249
+ std::move(storage_impl), ks, dtype);
250
+ tensor.unsafeGetTensorImpl()->set_sizes_and_strides(size, stride);
251
+ return tensor;
252
+ }
253
+
254
+ TensorBase empty_strided_generic(
255
+ IntArrayRef size,
256
+ IntArrayRef stride,
257
+ c10::Allocator* allocator,
258
+ c10::DispatchKeySet ks,
259
+ ScalarType scalar_type) {
260
+ return _empty_strided_generic<IntArrayRef>(size, stride, allocator, ks, scalar_type);
261
+ }
262
+
263
+ TensorBase empty_strided_symint_generic(
264
+ SymIntArrayRef size,
265
+ SymIntArrayRef stride,
266
+ c10::Allocator* allocator,
267
+ c10::DispatchKeySet ks,
268
+ ScalarType scalar_type) {
269
+ return _empty_strided_generic<SymIntArrayRef>(size, stride, allocator, ks, scalar_type);
270
+ }
271
+
272
+ TensorBase empty_cpu(IntArrayRef size, ScalarType dtype, bool pin_memory,
273
+ std::optional<c10::MemoryFormat> memory_format_opt) {
274
+ auto allocator = GetCPUAllocatorMaybePinned(pin_memory);
275
+ constexpr c10::DispatchKeySet cpu_ks(c10::DispatchKey::CPU);
276
+ return empty_generic(size, allocator, cpu_ks, dtype, memory_format_opt);
277
+ }
278
+
279
+ TensorBase empty_cpu(
280
+ IntArrayRef size,
281
+ std::optional<ScalarType> dtype_opt,
282
+ std::optional<Layout> layout_opt,
283
+ std::optional<Device> device_opt,
284
+ std::optional<bool> pin_memory_opt,
285
+ std::optional<c10::MemoryFormat> memory_format_opt) {
286
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::CPU);
287
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided);
288
+
289
+ auto pin_memory = pinned_memory_or_default(pin_memory_opt);
290
+ auto dtype = dtype_or_default(dtype_opt);
291
+ return empty_cpu(size, dtype, pin_memory, memory_format_opt);
292
+ }
293
+
294
+ TensorBase empty_cpu(
295
+ IntArrayRef size, const TensorOptions &options) {
296
+ return at::detail::empty_cpu(
297
+ size,
298
+ optTypeMetaToScalarType(options.dtype_opt()),
299
+ options.layout_opt(),
300
+ options.device_opt(),
301
+ options.pinned_memory_opt(),
302
+ options.memory_format_opt());
303
+ }
304
+
305
+ TensorBase empty_strided_cpu(IntArrayRef size, IntArrayRef stride,
306
+ ScalarType dtype, bool pin_memory) {
307
+ auto allocator = at::detail::GetCPUAllocatorMaybePinned(pin_memory);
308
+ constexpr c10::DispatchKeySet cpu_ks(c10::DispatchKey::CPU);
309
+ return at::detail::empty_strided_generic(
310
+ size, stride, allocator, cpu_ks, dtype);
311
+ }
312
+
313
+ TensorBase empty_strided_cpu(
314
+ IntArrayRef size,
315
+ IntArrayRef stride,
316
+ std::optional<ScalarType> dtype_opt,
317
+ std::optional<Layout> layout_opt,
318
+ std::optional<Device> device_opt,
319
+ std::optional<bool> pin_memory_opt) {
320
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::CPU);
321
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided);
322
+
323
+ auto pin_memory = pinned_memory_or_default(pin_memory_opt);
324
+ auto dtype = dtype_or_default(dtype_opt);
325
+ return at::detail::empty_strided_cpu(size, stride, dtype, pin_memory);
326
+ }
327
+
328
+ TensorBase empty_strided_cpu(
329
+ IntArrayRef size,
330
+ IntArrayRef stride,
331
+ const TensorOptions &options) {
332
+ return at::detail::empty_strided_cpu(
333
+ size,
334
+ stride,
335
+ optTypeMetaToScalarType(options.dtype_opt()),
336
+ options.layout_opt(),
337
+ options.device_opt(),
338
+ options.pinned_memory_opt());
339
+ }
340
+
341
+ // The meta allocator ignores whatever allocation is requested and always
342
+ // gives you nullptr
343
+ struct MetaAllocator final : public at::Allocator {
344
+ MetaAllocator() = default;
345
+ ~MetaAllocator() override = default;
346
+ static void deleter(void* const pointer) {
347
+ TORCH_INTERNAL_ASSERT(!pointer);
348
+ }
349
+ DataPtr allocate(const size_t nbytes [[maybe_unused]]) override {
350
+ return {nullptr, nullptr, &deleter, at::Device(DeviceType::Meta)};
351
+ }
352
+ DeleterFnPtr raw_deleter() const override {
353
+ return deleter;
354
+ }
355
+ void copy_data(void* dest, const void* src, std::size_t count) const final {}
356
+ };
357
+
358
+ static MetaAllocator g_meta_alloc;
359
+
360
+ REGISTER_ALLOCATOR(kMeta, &g_meta_alloc)
361
+
362
+ TensorBase empty_meta(IntArrayRef size, ScalarType dtype,
363
+ std::optional<c10::MemoryFormat> memory_format_opt) {
364
+ auto *allocator = GetAllocator(kMeta);
365
+ constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta);
366
+ return at::detail::empty_generic(
367
+ size, allocator, meta_dks, dtype, memory_format_opt);
368
+ }
369
+
370
+ TensorBase empty_meta(
371
+ IntArrayRef size,
372
+ std::optional<ScalarType> dtype_opt,
373
+ std::optional<Layout> layout_opt,
374
+ std::optional<Device> device_opt,
375
+ std::optional<bool> pin_memory_opt,
376
+ std::optional<c10::MemoryFormat> memory_format_opt
377
+ ) {
378
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta);
379
+ // NB: because there is no SparseMeta (yet), non-strided layout is
380
+ // exerciseable
381
+ TORCH_CHECK_NOT_IMPLEMENTED(
382
+ layout_or_default(layout_opt) == Layout::Strided,
383
+ "non-strided meta tensors not supported yet"
384
+ );
385
+
386
+ auto dtype = dtype_or_default(dtype_opt);
387
+ return empty_meta(size, dtype, memory_format_opt);
388
+ }
389
+
390
+ TensorBase empty_symint_meta(
391
+ SymIntArrayRef size,
392
+ std::optional<ScalarType> dtype_opt,
393
+ std::optional<Layout> layout_opt,
394
+ std::optional<Device> device_opt,
395
+ std::optional<bool> pin_memory_opt,
396
+ std::optional<c10::MemoryFormat> memory_format_opt
397
+ ) {
398
+ auto *allocator = GetAllocator(kMeta);
399
+ constexpr c10::DispatchKeySet ks(c10::DispatchKey::Meta);
400
+ auto scalar_type = dtype_or_default(dtype_opt);
401
+ return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt);
402
+ }
403
+
404
+ TensorBase empty_meta(
405
+ IntArrayRef size, const TensorOptions &options) {
406
+ return at::detail::empty_meta(
407
+ size,
408
+ optTypeMetaToScalarType(options.dtype_opt()),
409
+ options.layout_opt(),
410
+ options.device_opt(),
411
+ options.pinned_memory_opt(),
412
+ options.memory_format_opt());
413
+ }
414
+
415
+ TensorBase empty_strided_meta(IntArrayRef size, IntArrayRef stride,
416
+ ScalarType dtype) {
417
+ auto *allocator = GetAllocator(kMeta);
418
+ constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta);
419
+ return at::detail::empty_strided_generic(
420
+ size, stride, allocator, meta_dks, dtype);
421
+ }
422
+
423
+ TensorBase empty_strided_meta(
424
+ IntArrayRef size,
425
+ IntArrayRef stride,
426
+ std::optional<ScalarType> dtype_opt,
427
+ std::optional<Layout> layout_opt,
428
+ std::optional<Device> device_opt,
429
+ std::optional<bool> pin_memory_opt) {
430
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta);
431
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided);
432
+
433
+ auto dtype = dtype_or_default(dtype_opt);
434
+ return at::detail::empty_strided_meta(size, stride, dtype);
435
+ }
436
+
437
+ TensorBase empty_strided_meta(
438
+ IntArrayRef size,
439
+ IntArrayRef stride,
440
+ const TensorOptions &options) {
441
+ return at::detail::empty_strided_meta(
442
+ size,
443
+ stride,
444
+ optTypeMetaToScalarType(options.dtype_opt()),
445
+ options.layout_opt(),
446
+ options.device_opt(),
447
+ options.pinned_memory_opt());
448
+ }
449
+
450
+ TensorBase empty_strided_symint_meta(SymIntArrayRef size, SymIntArrayRef stride,
451
+ ScalarType dtype) {
452
+ auto *allocator = GetAllocator(kMeta);
453
+ constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta);
454
+ return at::detail::empty_strided_symint_generic(
455
+ size, stride, allocator, meta_dks, dtype);
456
+ }
457
+
458
+ TensorBase empty_strided_symint_meta(
459
+ SymIntArrayRef size,
460
+ SymIntArrayRef stride,
461
+ std::optional<ScalarType> dtype_opt,
462
+ std::optional<Layout> layout_opt,
463
+ std::optional<Device> device_opt) {
464
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta);
465
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided);
466
+
467
+ auto dtype = dtype_or_default(dtype_opt);
468
+ return at::detail::empty_strided_symint_meta(size, stride, dtype);
469
+ }
470
+
471
+ TensorBase empty_strided_symint_meta(
472
+ SymIntArrayRef size,
473
+ SymIntArrayRef stride,
474
+ const TensorOptions &options) {
475
+ return at::detail::empty_strided_symint_meta(
476
+ size,
477
+ stride,
478
+ optTypeMetaToScalarType(options.dtype_opt()),
479
+ options.layout_opt(),
480
+ options.device_opt());
481
+ }
482
+
483
+ } // namespace at::detail
western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.h ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/TensorBase.h>
3
+
4
+ namespace at::detail {
5
+
6
+ inline void check_size_nonnegative(ArrayRef<int64_t> size) {
7
+ for (const auto& x : size) {
8
+ TORCH_CHECK(
9
+ x >= 0,
10
+ "Trying to create tensor with negative dimension ",
11
+ x,
12
+ ": ",
13
+ size);
14
+ }
15
+ }
16
+
17
+ inline void check_size_nonnegative(ArrayRef<c10::SymInt> size) {
18
+ for (const auto& x : size) {
19
+ TORCH_SYM_CHECK(
20
+ x.sym_ge(0),
21
+ "Trying to create tensor with negative dimension ",
22
+ x,
23
+ ": ",
24
+ size);
25
+ }
26
+ }
27
+
28
+ TORCH_API size_t computeStorageNbytesContiguous(
29
+ IntArrayRef sizes,
30
+ size_t itemsize,
31
+ size_t storage_offset = 0);
32
+ TORCH_API SymInt computeStorageNbytesContiguous(
33
+ SymIntArrayRef sizes,
34
+ const SymInt& itemsize,
35
+ const SymInt& storage_offset = 0);
36
+ TORCH_API size_t computeStorageNbytes(
37
+ IntArrayRef sizes,
38
+ IntArrayRef strides,
39
+ size_t itemsize,
40
+ size_t storage_offset = 0);
41
+ TORCH_API SymInt computeStorageNbytes(
42
+ SymIntArrayRef sizes,
43
+ SymIntArrayRef strides,
44
+ const SymInt& itemsize,
45
+ const SymInt& storage_offset = 0);
46
+
47
+ TORCH_API TensorBase empty_generic(
48
+ IntArrayRef size,
49
+ c10::Allocator* allocator,
50
+ c10::DispatchKeySet ks,
51
+ ScalarType scalar_type,
52
+ std::optional<c10::MemoryFormat> memory_format_opt);
53
+
54
+ TORCH_API TensorBase empty_generic_symint(
55
+ SymIntArrayRef size,
56
+ c10::Allocator* allocator,
57
+ c10::DispatchKeySet ks,
58
+ ScalarType scalar_type,
59
+ std::optional<c10::MemoryFormat> memory_format_opt);
60
+
61
+ TORCH_API TensorBase empty_strided_generic(
62
+ IntArrayRef size,
63
+ IntArrayRef stride,
64
+ c10::Allocator* allocator,
65
+ c10::DispatchKeySet ks,
66
+ ScalarType scalar_type);
67
+
68
+ TORCH_API TensorBase empty_strided_symint_generic(
69
+ SymIntArrayRef size,
70
+ SymIntArrayRef stride,
71
+ c10::Allocator* allocator,
72
+ c10::DispatchKeySet ks,
73
+ ScalarType scalar_type);
74
+
75
+ TORCH_API TensorBase empty_cpu(
76
+ IntArrayRef size,
77
+ ScalarType dtype,
78
+ bool pin_memory = false,
79
+ std::optional<c10::MemoryFormat> memory_format_opt = std::nullopt);
80
+
81
+ TORCH_API TensorBase empty_cpu(
82
+ IntArrayRef size,
83
+ std::optional<ScalarType> dtype_opt,
84
+ std::optional<Layout> layout_opt,
85
+ std::optional<Device> device_opt,
86
+ std::optional<bool> pin_memory_opt,
87
+ std::optional<c10::MemoryFormat> memory_format_opt);
88
+
89
+ TORCH_API TensorBase empty_cpu(IntArrayRef size, const TensorOptions& options);
90
+
91
+ TORCH_API TensorBase empty_strided_cpu(
92
+ IntArrayRef size,
93
+ IntArrayRef stride,
94
+ ScalarType dtype,
95
+ bool pin_memory = false);
96
+
97
+ TORCH_API TensorBase empty_strided_cpu(
98
+ IntArrayRef size,
99
+ IntArrayRef stride,
100
+ std::optional<ScalarType> dtype_opt,
101
+ std::optional<Layout> layout_opt,
102
+ std::optional<Device> device_opt,
103
+ std::optional<bool> pin_memory_opt);
104
+
105
+ TORCH_API TensorBase empty_strided_cpu(
106
+ IntArrayRef size,
107
+ IntArrayRef stride,
108
+ const TensorOptions& options);
109
+
110
+ TORCH_API TensorBase empty_meta(
111
+ IntArrayRef size,
112
+ ScalarType dtype,
113
+ std::optional<c10::MemoryFormat> memory_format_opt = std::nullopt);
114
+
115
+ TORCH_API TensorBase empty_meta(
116
+ IntArrayRef size,
117
+ std::optional<ScalarType> dtype_opt,
118
+ std::optional<Layout> layout_opt,
119
+ std::optional<Device> device_opt,
120
+ std::optional<bool> pin_memory_opt,
121
+ std::optional<c10::MemoryFormat> memory_format_opt);
122
+
123
+ TORCH_API TensorBase empty_symint_meta(
124
+ SymIntArrayRef size,
125
+ std::optional<ScalarType> dtype_opt,
126
+ std::optional<Layout> layout_opt,
127
+ std::optional<Device> device_opt,
128
+ std::optional<bool> pin_memory_opt,
129
+ std::optional<c10::MemoryFormat> memory_format_opt);
130
+
131
+ TORCH_API TensorBase empty_meta(IntArrayRef size, const TensorOptions& options);
132
+
133
+ TORCH_API TensorBase
134
+ empty_strided_meta(IntArrayRef size, IntArrayRef stride, ScalarType dtype);
135
+
136
+ TORCH_API TensorBase empty_strided_meta(
137
+ IntArrayRef size,
138
+ IntArrayRef stride,
139
+ std::optional<ScalarType> dtype_opt,
140
+ std::optional<Layout> layout_opt,
141
+ std::optional<Device> device_opt,
142
+ std::optional<bool> pin_memory_opt);
143
+
144
+ TORCH_API TensorBase empty_strided_meta(
145
+ IntArrayRef size,
146
+ IntArrayRef stride,
147
+ const TensorOptions& options);
148
+
149
+ TORCH_API TensorBase empty_strided_symint_meta(
150
+ SymIntArrayRef size,
151
+ SymIntArrayRef stride,
152
+ ScalarType dtype);
153
+
154
+ TORCH_API TensorBase empty_strided_symint_meta(
155
+ SymIntArrayRef size,
156
+ SymIntArrayRef stride,
157
+ std::optional<ScalarType> dtype_opt,
158
+ std::optional<Layout> layout_opt,
159
+ std::optional<Device> device_opt);
160
+
161
+ TORCH_API TensorBase empty_strided_symint_meta(
162
+ SymIntArrayRef size,
163
+ SymIntArrayRef stride,
164
+ const TensorOptions& options);
165
+
166
+ } // namespace at::detail
western_ai/usa/pytorch/aten/src/ATen/ExpandBase.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/TensorBase.h>
2
+
3
+ // Broadcasting utilities for working with TensorBase
4
+ namespace at {
5
+ namespace internal {
6
+ TORCH_API TensorBase expand_slow_path(const TensorBase& self, IntArrayRef size);
7
+ } // namespace internal
8
+
9
+ inline c10::MaybeOwned<TensorBase> expand_size(
10
+ const TensorBase& self,
11
+ IntArrayRef size) {
12
+ if (size.equals(self.sizes())) {
13
+ return c10::MaybeOwned<TensorBase>::borrowed(self);
14
+ }
15
+ return c10::MaybeOwned<TensorBase>::owned(
16
+ at::internal::expand_slow_path(self, size));
17
+ }
18
+ c10::MaybeOwned<TensorBase> expand_size(TensorBase&& self, IntArrayRef size) =
19
+ delete;
20
+
21
+ inline c10::MaybeOwned<TensorBase> expand_inplace(
22
+ const TensorBase& tensor,
23
+ const TensorBase& to_expand) {
24
+ return expand_size(to_expand, tensor.sizes());
25
+ }
26
+ c10::MaybeOwned<TensorBase> expand_inplace(
27
+ const TensorBase& tensor,
28
+ TensorBase&& to_expand) = delete;
29
+
30
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.cpp ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
2
+ #include <ATen/ExpandUtils.h>
3
+ #include <ATen/ExpandBase.h>
4
+
5
+ #include <c10/util/irange.h>
6
+
7
+ namespace at {
8
+ namespace internal {
9
+ TensorBase expand_slow_path(const TensorBase &self, IntArrayRef size) {
10
+ return OptionalTensorRef(self)->expand(size);
11
+ }
12
+ } // namespace internal
13
+
14
+ namespace {
15
+ // NOTE: are_expandable did a similar check, please keep them sync if change is needed
16
+ template <typename Container, typename ArrayType>
17
+ Container infer_size_impl(ArrayType a, ArrayType b) {
18
+ // Use ptrdiff_t to ensure signed comparison.
19
+ auto dimsA = static_cast<ptrdiff_t>(a.size());
20
+ auto dimsB = static_cast<ptrdiff_t>(b.size());
21
+ auto ndim = dimsA > dimsB ? dimsA : dimsB;
22
+ Container expandedSizes(ndim);
23
+
24
+ for (ptrdiff_t i = ndim - 1; i >= 0; --i) {
25
+ ptrdiff_t offset = ndim - 1 - i;
26
+ ptrdiff_t dimA = dimsA - 1 - offset;
27
+ ptrdiff_t dimB = dimsB - 1 - offset;
28
+ auto sizeA = (dimA >= 0) ? a[dimA] : 1;
29
+ auto sizeB = (dimB >= 0) ? b[dimB] : 1;
30
+
31
+ // If we know for sure one of them is 1, we are done.
32
+ // otherwise for unbacked we assume non-broadcasting path.
33
+ // Unbacked semantics should match python infer_size fake_impl.
34
+ if (!TORCH_GUARD_OR_FALSE(sym_eq(sizeA, 1)) && !TORCH_GUARD_OR_FALSE(sym_eq(sizeB, 1))) {
35
+ TORCH_MAYBE_SYM_CHECK(sym_eq(sizeA, sizeB),
36
+ "The size of tensor a (", sizeA,
37
+ ") must match the size of tensor b (", sizeB,
38
+ ") at non-singleton dimension ", i);
39
+ }
40
+ // 1s map to the other size (even 0).
41
+ expandedSizes[i] = TORCH_GUARD_OR_FALSE(sym_eq(sizeA, 1)) ? sizeB : sizeA;
42
+ }
43
+
44
+ return expandedSizes;
45
+ }
46
+ }
47
+
48
+ std::vector<int64_t> infer_size(IntArrayRef a, IntArrayRef b) {
49
+ return infer_size_impl<std::vector<int64_t>>(a, b);
50
+ }
51
+
52
+ std::vector<SymInt> infer_size_symint(SymIntArrayRef a, SymIntArrayRef b) {
53
+ return infer_size_impl<std::vector<SymInt>>(a, b);
54
+ }
55
+
56
+ DimVector infer_size_dimvector(IntArrayRef a, IntArrayRef b) {
57
+ return infer_size_impl<DimVector, IntArrayRef>(a, b);
58
+ }
59
+
60
+ SymDimVector infer_size_symdimvector(SymIntArrayRef a, SymIntArrayRef b) {
61
+ return infer_size_impl<SymDimVector, SymIntArrayRef>(a, b);
62
+ }
63
+
64
+ template<typename Container>
65
+ C10_ALWAYS_INLINE static InferExpandGeometryResult<Container> inferExpandGeometryImpl(
66
+ IntArrayRef tensor_sizes,
67
+ IntArrayRef tensor_strides,
68
+ IntArrayRef sizes) {
69
+ int64_t ndim = static_cast<int64_t>(sizes.size());
70
+ int64_t tensor_dim = static_cast<int64_t>(tensor_sizes.size());
71
+
72
+ if (tensor_dim == 0) {
73
+ return InferExpandGeometryResult<Container>(sizes, ndim);
74
+ }
75
+
76
+ InferExpandGeometryResult<Container> result(ndim);
77
+ auto& expandedSizes = result.sizes;
78
+ auto& expandedStrides = result.strides;
79
+
80
+ // create a new geometry for the tensors
81
+ for (int64_t i = ndim - 1; i >= 0; --i) {
82
+ int64_t offset = ndim - 1 - i;
83
+ int64_t dim = tensor_dim - 1 - offset;
84
+ int64_t size = (dim >= 0) ? tensor_sizes[dim] : 1;
85
+ int64_t stride = (dim >= 0) ? tensor_strides[dim]
86
+ : expandedSizes[i + 1] * expandedStrides[i + 1];
87
+ int64_t targetSize = sizes[i];
88
+ if (targetSize == -1) {
89
+ TORCH_CHECK(
90
+ dim >= 0,
91
+ "The expanded size of the tensor (",
92
+ targetSize,
93
+ ") isn't allowed in a leading, non-existing dimension ",
94
+ i);
95
+ targetSize = size;
96
+ }
97
+ if (size != targetSize) {
98
+ TORCH_CHECK(
99
+ size == 1,
100
+ "The expanded size of the tensor (",
101
+ targetSize,
102
+ ") must match the existing size (",
103
+ size,
104
+ ") at non-singleton dimension ",
105
+ i,
106
+ ". Target sizes: ",
107
+ sizes,
108
+ ". Tensor sizes: ",
109
+ tensor_sizes);
110
+ size = targetSize;
111
+ stride = 0;
112
+ }
113
+ expandedSizes[i] = size;
114
+ expandedStrides[i] = stride;
115
+ }
116
+ return result;
117
+ }
118
+
119
+ std::tuple<std::vector<int64_t>, std::vector<int64_t>> inferExpandGeometry(
120
+ IntArrayRef tensor_sizes,
121
+ IntArrayRef tensor_strides,
122
+ IntArrayRef sizes) {
123
+ auto result = inferExpandGeometryImpl<std::vector<int64_t>>(
124
+ tensor_sizes, tensor_strides, sizes);
125
+ return std::make_tuple(std::move(result.sizes), std::move(result.strides));
126
+ }
127
+
128
+ InferExpandGeometryResult<DimVector> inferExpandGeometry_dimvector(
129
+ IntArrayRef tensor_sizes,
130
+ IntArrayRef tensor_strides,
131
+ IntArrayRef sizes) {
132
+ return inferExpandGeometryImpl<DimVector>(
133
+ tensor_sizes, tensor_strides, sizes);
134
+ }
135
+
136
+
137
+ // This function returns a dense and non-overlapping strides, which keeps the same layout permutation
138
+ // as the input `tensor_strides`, computed based on the input `tensor_sizes`.
139
+ // Note:
140
+ // 1. This function expects the inputs `tensor_strides` and `tensor_sizes` are non-dense or overlapping,
141
+ // If the inputs are densed and non-overlapping, the output strides will be the same as `tensor_strides`.
142
+ // However, this function won't check whether inputs are dense or overlapping, so the whole function will
143
+ // still be executed even the inputs are already dense and non-overlapping, this will cause slowness.
144
+ //
145
+ // Please verify whether the inputs are non-dense or overlapping before calling this function if possible,
146
+ // if the inputs come from a tensor, you can check this through `is_non_overlapping_and_dense()`
147
+ //
148
+ // 2. The strides propagation rule that is used in this function is exactily the same as what is being used in
149
+ // TensorIterator. Please refer to https://github.com/pytorch/pytorch/pull/42922 for more details
150
+
151
+ std::vector<int64_t> infer_dense_strides(IntArrayRef tensor_sizes, IntArrayRef tensor_strides) {
152
+
153
+ TORCH_CHECK(tensor_sizes.size() == tensor_strides.size(),
154
+ "Input sizes and strides should have same size but got ", tensor_sizes.size(), " and ", tensor_strides.size());
155
+
156
+ size_t ndim = tensor_sizes.size();
157
+ if (ndim == 0) {
158
+ return {};
159
+ }
160
+ if (ndim == 1) {
161
+ return {1};
162
+ }
163
+
164
+ std::vector<int64_t> perm(ndim);
165
+ // initialize perm with n-1, n-2, ..., 1, 0
166
+ std::iota(perm.rbegin(), perm.rend(), 0);
167
+
168
+ // The following sorting algorithm has exactly the same behavior as TensorIterator
169
+ // This is to make sure we have the same stride propagation everywhere.
170
+
171
+ // return -1 if dim0 should come before dim1
172
+ // return 1 if dim0 should come after dim1
173
+ // return 0 if comparison is ambiguous
174
+ auto should_swap = [&](size_t dim0, size_t dim1) {
175
+ int64_t stride0 = tensor_strides[dim0];
176
+ int64_t stride1 = tensor_strides[dim1];
177
+
178
+ // if any stride is 0, treat it as ambiguous comparison to
179
+ // keep the same behavior as TensorIterator
180
+ if (stride0 == 0 || stride1 == 0) {
181
+ return 0;
182
+ }
183
+ if (stride0 < stride1) {
184
+ return -1;
185
+ }
186
+ if (stride0 > stride1) {
187
+ return 1;
188
+ }
189
+ // for equal strides, the dimension with smaller size goes front
190
+ if (tensor_sizes[dim0] > tensor_sizes[dim1]) {
191
+ return 1;
192
+ }
193
+ return 0;
194
+ };
195
+
196
+ // Insertion sort (stable) indices in `perm` based on input tensor's stride and shape,
197
+ // all dimensions with 0 stride won't move. This is the same behavior as TensorIterator.
198
+ // eg. Given tensor with size/stride (6, 5, 4, 3, 2)/(6, 0, 120, 0, 1), the initial `perm`
199
+ // is (4, 3, 2, 1, 0) and the sorted `perm` will be (4, 3, 0, 1, 2)
200
+ for (const auto i : c10::irange(1, ndim)) {
201
+ auto dim1 = i;
202
+ for (const auto j : c10::irange(1, i + 1)) {
203
+ auto dim0 = i - j;
204
+ int comparison = should_swap(perm[dim0], perm[dim1]);
205
+ if (comparison > 0) {
206
+ std::swap(perm[dim0], perm[dim1]);
207
+ dim1 = dim0;
208
+ }
209
+ else if (comparison < 0) {
210
+ break;
211
+ }
212
+ }
213
+ }
214
+
215
+ // compute output strides which preserves the input tensor's memory layout
216
+ std::vector<int64_t> out_strides(ndim);
217
+ int64_t curr_stride = 1;
218
+ for (const auto i : c10::irange(ndim)) {
219
+ int64_t idx = perm[i];
220
+ out_strides[idx] = curr_stride;
221
+ // Note: for size 0, we simply treated it as 1, it really doesn't matter here
222
+ // since the total number of element is 0.
223
+ if (tensor_sizes[idx] > 1) {
224
+ curr_stride *= tensor_sizes[idx];
225
+ }
226
+ }
227
+ return out_strides;
228
+ }
229
+
230
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.h ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifndef AT_PER_OPERATOR_HEADERS
4
+ #include <ATen/Functions.h>
5
+ #else
6
+ #include <ATen/ops/view.h>
7
+ #include <ATen/ops/view_copy.h>
8
+ #endif
9
+
10
+ #include <ATen/Tensor.h>
11
+ #include <ATen/core/DimVector.h>
12
+ #include <c10/core/SymBool.h>
13
+ #include <c10/util/Exception.h>
14
+ #include <c10/util/MaybeOwned.h>
15
+ #include <c10/util/irange.h>
16
+
17
+ #include <functional>
18
+ #include <tuple>
19
+ #include <utility>
20
+
21
+ namespace at {
22
+
23
+ TORCH_API std::vector<int64_t> infer_size(IntArrayRef a, IntArrayRef b);
24
+ TORCH_API std::vector<SymInt> infer_size_symint(
25
+ SymIntArrayRef a,
26
+ SymIntArrayRef b);
27
+ TORCH_API DimVector infer_size_dimvector(IntArrayRef a, IntArrayRef b);
28
+ TORCH_API SymDimVector
29
+ infer_size_symdimvector(SymIntArrayRef a, SymIntArrayRef b);
30
+
31
+ // Named type instead of a pair/tuple so that we can be sure to
32
+ // construct the vectors in place and get NRVO.
33
+ template <typename Container>
34
+ struct InferExpandGeometryResult {
35
+ Container sizes;
36
+ Container strides;
37
+ explicit InferExpandGeometryResult(size_t ndim)
38
+ : sizes(ndim), strides(ndim) {}
39
+ explicit InferExpandGeometryResult(IntArrayRef sizes_, size_t ndim)
40
+ : sizes(sizes_.begin(), sizes_.end()), strides(ndim) {}
41
+ };
42
+
43
+ TORCH_API std::tuple<std::vector<int64_t>, std::vector<int64_t>>
44
+ inferExpandGeometry(
45
+ IntArrayRef tensor_sizes,
46
+ IntArrayRef tensor_strides,
47
+ IntArrayRef sizes);
48
+
49
+ TORCH_API InferExpandGeometryResult<DimVector> inferExpandGeometry_dimvector(
50
+ IntArrayRef tensor_sizes,
51
+ IntArrayRef tensor_strides,
52
+ IntArrayRef sizes);
53
+
54
+ TORCH_API std::vector<int64_t> infer_dense_strides(
55
+ IntArrayRef tensor_sizes,
56
+ IntArrayRef tensor_strides);
57
+
58
+ // True if input shapes are expandable
59
+ // NOTE: infer_size did a similar check, please keep them sync if change is
60
+ // needed
61
+ inline bool are_expandable(IntArrayRef shape1, IntArrayRef shape2) {
62
+ size_t ndim1 = shape1.size();
63
+ size_t ndim2 = shape2.size();
64
+ size_t ndim = ndim1 < ndim2 ? ndim1 : ndim2;
65
+
66
+ for (int64_t i = static_cast<int64_t>(ndim) - 1; i >= 0; --i) {
67
+ if (shape1[--ndim1] == shape2[--ndim2] || shape1[ndim1] == 1 ||
68
+ shape2[ndim2] == 1) {
69
+ continue;
70
+ }
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+
76
+ // avoid copy-construction of Tensor by using a reference_wrapper.
77
+ inline void check_defined(
78
+ std::initializer_list<std::reference_wrapper<const Tensor>> tensors,
79
+ const char* api_name) {
80
+ for (auto& t : tensors) {
81
+ if (!t.get().defined()) {
82
+ TORCH_CHECK(false, api_name, "(...) called with an undefined Tensor");
83
+ }
84
+ }
85
+ }
86
+
87
+ // NOTE [ ExpandUtils Borrowing ]
88
+ //
89
+ // Functions in ExpandUtils return `c10::MaybeOwned<Tensor>` because
90
+ // expansion may not actually be needed, in which case we can improve
91
+ // efficiency by returning
92
+ // `c10::MaybeOwned<Tensor>::borrowed(to_expand)`. However, this means
93
+ // that you need to be careful: the returned `c10::MaybeOwned<Tensor>`
94
+ // must not outlive the original `Tensor` object that `to_expand`
95
+ // referred to! The deleted rvalue reference overloads of these
96
+ // functions help with this by preventing trivial use of a temporary
97
+ // resulting from a function call, but it is still possible to make a
98
+ // mistake.
99
+
100
+ inline c10::MaybeOwned<Tensor> expand_inplace(
101
+ const Tensor& tensor,
102
+ const Tensor& to_expand) {
103
+ auto t_sizes = tensor.sym_sizes();
104
+ auto e_sizes = to_expand.sym_sizes();
105
+ bool same = t_sizes.size() == e_sizes.size();
106
+ if (same) {
107
+ for (size_t i = 0; i < t_sizes.size(); ++i) {
108
+ if (!TORCH_GUARD_OR_FALSE(sym_eq(t_sizes[i], e_sizes[i]))) {
109
+ same = false;
110
+ break;
111
+ }
112
+ }
113
+ }
114
+ if (same) {
115
+ return c10::MaybeOwned<Tensor>::borrowed(to_expand);
116
+ }
117
+ return c10::MaybeOwned<Tensor>::owned(
118
+ to_expand.expand_symint(tensor.sym_sizes()));
119
+ }
120
+
121
+ inline c10::MaybeOwned<Tensor> expand_inplace(
122
+ const Tensor& tensor,
123
+ Tensor&& to_expand) = delete;
124
+
125
+ inline c10::MaybeOwned<Tensor> expand_inplace(
126
+ const Tensor& tensor,
127
+ const Tensor& to_expand,
128
+ const char* api_name) {
129
+ check_defined({tensor, to_expand}, api_name);
130
+ return expand_inplace(tensor, to_expand);
131
+ }
132
+
133
+ inline c10::MaybeOwned<Tensor> expand_inplace(
134
+ const Tensor& tensor,
135
+ Tensor&& to_expand,
136
+ const char* api_name) = delete;
137
+
138
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
139
+ expand_inplace(
140
+ const Tensor& tensor,
141
+ const Tensor& to_expand1,
142
+ const Tensor& to_expand2) {
143
+ if (tensor.sizes().equals(to_expand1.sizes()) &&
144
+ tensor.sizes().equals((to_expand2.sizes()))) {
145
+ return std::make_tuple(
146
+ c10::MaybeOwned<Tensor>::borrowed(to_expand1),
147
+ c10::MaybeOwned<Tensor>::borrowed(to_expand2));
148
+ }
149
+
150
+ return std::make_tuple(
151
+ c10::MaybeOwned<Tensor>::owned(to_expand1.expand(tensor.sizes())),
152
+ c10::MaybeOwned<Tensor>::owned(to_expand2.expand(tensor.sizes())));
153
+ }
154
+
155
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
156
+ expand_inplace(
157
+ const Tensor& tensor,
158
+ Tensor&& to_expand1,
159
+ const Tensor& to_expand2) = delete;
160
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
161
+ expand_inplace(
162
+ const Tensor& tensor,
163
+ const Tensor& to_expand1,
164
+ Tensor&& to_expand2) = delete;
165
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
166
+ expand_inplace(const Tensor& tensor, Tensor&& to_expand1, Tensor&& to_expand2) =
167
+ delete;
168
+
169
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
170
+ expand_inplace(
171
+ const Tensor& tensor,
172
+ const Tensor& to_expand1,
173
+ const Tensor& to_expand2,
174
+ const char* api_name) {
175
+ check_defined({tensor, to_expand1, to_expand2}, api_name);
176
+ return expand_inplace(tensor, to_expand1, to_expand2);
177
+ }
178
+
179
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
180
+ expand_inplace(
181
+ const Tensor& tensor,
182
+ Tensor&& to_expand1,
183
+ const Tensor& to_expand2,
184
+ const char* api_name) = delete;
185
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
186
+ expand_inplace(
187
+ const Tensor& tensor,
188
+ const Tensor& to_expand1,
189
+ Tensor&& to_expand2,
190
+ const char* api_name) = delete;
191
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
192
+ expand_inplace(
193
+ const Tensor& tensor,
194
+ Tensor&& to_expand1,
195
+ Tensor&& to_expand2,
196
+ const char* api_name) = delete;
197
+
198
+ // See NOTE [ ExpandUtils Borrowing ] above for `MaybeOwned` explanation.
199
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
200
+ expand_outplace(const Tensor& to_expand1, const Tensor& to_expand2) {
201
+ auto s1 = to_expand1.sym_sizes();
202
+ auto s2 = to_expand2.sym_sizes();
203
+ if (s1.equals(s2)) {
204
+ return std::make_tuple(
205
+ c10::MaybeOwned<Tensor>::borrowed(to_expand1),
206
+ c10::MaybeOwned<Tensor>::borrowed(to_expand2));
207
+ }
208
+
209
+ auto expanded_size = infer_size_symdimvector(s1, s2);
210
+ return std::make_tuple(
211
+ c10::MaybeOwned<Tensor>::owned(to_expand1.expand_symint(expanded_size)),
212
+ c10::MaybeOwned<Tensor>::owned(to_expand2.expand_symint(expanded_size)));
213
+ }
214
+
215
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
216
+ expand_outplace(Tensor&& to_expand1, const Tensor& to_expand2) = delete;
217
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
218
+ expand_outplace(const Tensor& to_expand1, Tensor&& to_expand2) = delete;
219
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
220
+ expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2) = delete;
221
+
222
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
223
+ expand_outplace(
224
+ const Tensor& to_expand1,
225
+ const Tensor& to_expand2,
226
+ const char* api_name) {
227
+ check_defined({to_expand1, to_expand2}, api_name);
228
+ return expand_outplace(to_expand1, to_expand2);
229
+ }
230
+
231
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
232
+ expand_outplace(
233
+ Tensor&& to_expand1,
234
+ const Tensor& to_expand2,
235
+ const char* api_name) = delete;
236
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
237
+ expand_outplace(
238
+ const Tensor& to_expand1,
239
+ Tensor&& to_expand2,
240
+ const char* api_name) = delete;
241
+ inline std::tuple<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>>
242
+ expand_outplace(
243
+ Tensor&& to_expand1,
244
+ Tensor&& to_expand2,
245
+ const char* api_name) = delete;
246
+
247
+ inline std::tuple<
248
+ c10::MaybeOwned<Tensor>,
249
+ c10::MaybeOwned<Tensor>,
250
+ c10::MaybeOwned<Tensor>>
251
+ expand_outplace(
252
+ const Tensor& to_expand1,
253
+ const Tensor& to_expand2,
254
+ const Tensor& to_expand3) {
255
+ if (to_expand1.sizes().equals(to_expand2.sizes()) &&
256
+ to_expand1.sizes().equals(to_expand3.sizes())) {
257
+ return std::make_tuple(
258
+ c10::MaybeOwned<Tensor>::borrowed(to_expand1),
259
+ c10::MaybeOwned<Tensor>::borrowed(to_expand2),
260
+ c10::MaybeOwned<Tensor>::borrowed(to_expand3));
261
+ }
262
+
263
+ auto expanded_size12 =
264
+ infer_size_dimvector(to_expand1.sizes(), to_expand2.sizes());
265
+ auto expanded_size =
266
+ infer_size_dimvector(expanded_size12, to_expand3.sizes());
267
+ return std::make_tuple(
268
+ c10::MaybeOwned<Tensor>::owned(to_expand1.expand(expanded_size)),
269
+ c10::MaybeOwned<Tensor>::owned(to_expand2.expand(expanded_size)),
270
+ c10::MaybeOwned<Tensor>::owned(to_expand3.expand(expanded_size)));
271
+ }
272
+
273
+ inline std::tuple<
274
+ c10::MaybeOwned<Tensor>,
275
+ c10::MaybeOwned<Tensor>,
276
+ c10::MaybeOwned<Tensor>>
277
+ expand_outplace(
278
+ Tensor&& to_expand1,
279
+ const Tensor& to_expand2,
280
+ const Tensor& to_expand3) = delete;
281
+ inline std::tuple<
282
+ c10::MaybeOwned<Tensor>,
283
+ c10::MaybeOwned<Tensor>,
284
+ c10::MaybeOwned<Tensor>>
285
+ expand_outplace(
286
+ const Tensor& to_expand1,
287
+ Tensor&& to_expand2,
288
+ const Tensor& to_expand3) = delete;
289
+ inline std::tuple<
290
+ c10::MaybeOwned<Tensor>,
291
+ c10::MaybeOwned<Tensor>,
292
+ c10::MaybeOwned<Tensor>>
293
+ expand_outplace(
294
+ Tensor&& to_expand1,
295
+ Tensor&& to_expand2,
296
+ const Tensor& to_expand3) = delete;
297
+ inline std::tuple<
298
+ c10::MaybeOwned<Tensor>,
299
+ c10::MaybeOwned<Tensor>,
300
+ c10::MaybeOwned<Tensor>>
301
+ expand_outplace(
302
+ const Tensor& to_expand1,
303
+ const Tensor& to_expand2,
304
+ Tensor&& to_expand3) = delete;
305
+ inline std::tuple<
306
+ c10::MaybeOwned<Tensor>,
307
+ c10::MaybeOwned<Tensor>,
308
+ c10::MaybeOwned<Tensor>>
309
+ expand_outplace(
310
+ Tensor&& to_expand1,
311
+ const Tensor& to_expand2,
312
+ Tensor&& to_expand3) = delete;
313
+ inline std::tuple<
314
+ c10::MaybeOwned<Tensor>,
315
+ c10::MaybeOwned<Tensor>,
316
+ c10::MaybeOwned<Tensor>>
317
+ expand_outplace(
318
+ const Tensor& to_expand1,
319
+ Tensor&& to_expand2,
320
+ Tensor&& to_expand3) = delete;
321
+ inline std::tuple<
322
+ c10::MaybeOwned<Tensor>,
323
+ c10::MaybeOwned<Tensor>,
324
+ c10::MaybeOwned<Tensor>>
325
+ expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2, Tensor&& to_expand3) =
326
+ delete;
327
+
328
+ inline std::tuple<
329
+ c10::MaybeOwned<Tensor>,
330
+ c10::MaybeOwned<Tensor>,
331
+ c10::MaybeOwned<Tensor>>
332
+ expand_outplace(
333
+ const Tensor& to_expand1,
334
+ const Tensor& to_expand2,
335
+ const Tensor& to_expand3,
336
+ const char* api_name) {
337
+ check_defined({to_expand1, to_expand2, to_expand3}, api_name);
338
+ return expand_outplace(to_expand1, to_expand2, to_expand3);
339
+ }
340
+
341
+ inline std::tuple<
342
+ c10::MaybeOwned<Tensor>,
343
+ c10::MaybeOwned<Tensor>,
344
+ c10::MaybeOwned<Tensor>>
345
+ expand_outplace(
346
+ Tensor&& to_expand1,
347
+ const Tensor& to_expand2,
348
+ const Tensor& to_expand3,
349
+ const char* api_name) = delete;
350
+ inline std::tuple<
351
+ c10::MaybeOwned<Tensor>,
352
+ c10::MaybeOwned<Tensor>,
353
+ c10::MaybeOwned<Tensor>>
354
+ expand_outplace(
355
+ const Tensor& to_expand1,
356
+ Tensor&& to_expand2,
357
+ const Tensor& to_expand3,
358
+ const char* api_name) = delete;
359
+ inline std::tuple<
360
+ c10::MaybeOwned<Tensor>,
361
+ c10::MaybeOwned<Tensor>,
362
+ c10::MaybeOwned<Tensor>>
363
+ expand_outplace(
364
+ Tensor&& to_expand1,
365
+ Tensor&& to_expand2,
366
+ const Tensor& to_expand3,
367
+ const char* api_name) = delete;
368
+ inline std::tuple<
369
+ c10::MaybeOwned<Tensor>,
370
+ c10::MaybeOwned<Tensor>,
371
+ c10::MaybeOwned<Tensor>>
372
+ expand_outplace(
373
+ const Tensor& to_expand1,
374
+ const Tensor& to_expand2,
375
+ Tensor&& to_expand3,
376
+ const char* api_name) = delete;
377
+ inline std::tuple<
378
+ c10::MaybeOwned<Tensor>,
379
+ c10::MaybeOwned<Tensor>,
380
+ c10::MaybeOwned<Tensor>>
381
+ expand_outplace(
382
+ Tensor&& to_expand1,
383
+ const Tensor& to_expand2,
384
+ Tensor&& to_expand3,
385
+ const char* api_name) = delete;
386
+ inline std::tuple<
387
+ c10::MaybeOwned<Tensor>,
388
+ c10::MaybeOwned<Tensor>,
389
+ c10::MaybeOwned<Tensor>>
390
+ expand_outplace(
391
+ const Tensor& to_expand1,
392
+ Tensor&& to_expand2,
393
+ Tensor&& to_expand3,
394
+ const char* api_name) = delete;
395
+ inline std::tuple<
396
+ c10::MaybeOwned<Tensor>,
397
+ c10::MaybeOwned<Tensor>,
398
+ c10::MaybeOwned<Tensor>>
399
+ expand_outplace(
400
+ Tensor&& to_expand1,
401
+ Tensor&& to_expand2,
402
+ Tensor&& to_expand3,
403
+ const char* api_name) = delete;
404
+
405
+ inline c10::MaybeOwned<Tensor> expand_size(
406
+ const Tensor& to_expand,
407
+ IntArrayRef sizes) {
408
+ if (to_expand.sizes().equals(sizes)) {
409
+ return c10::MaybeOwned<Tensor>::borrowed(to_expand);
410
+ }
411
+
412
+ return c10::MaybeOwned<Tensor>::owned(to_expand.expand(sizes));
413
+ }
414
+
415
+ inline c10::MaybeOwned<Tensor> expand_size(
416
+ Tensor&& to_expand,
417
+ IntArrayRef sizes) = delete;
418
+
419
+ inline c10::MaybeOwned<Tensor> expand_size(
420
+ const Tensor& to_expand,
421
+ IntArrayRef sizes,
422
+ const char* api_name) {
423
+ check_defined({to_expand}, api_name);
424
+ return expand_size(to_expand, sizes);
425
+ }
426
+
427
+ inline c10::MaybeOwned<Tensor> expand_size(
428
+ Tensor&& to_expand,
429
+ IntArrayRef sizes,
430
+ const char* api_name) = delete;
431
+
432
+ inline std::vector<Tensor> expand_outplace(TensorList to_expand) {
433
+ // expands a list of Tensors; ignores undefined (null) tensors
434
+ bool first = true;
435
+ SymDimVector sizes;
436
+ for (const auto i : c10::irange(to_expand.size())) {
437
+ if (!to_expand[i].defined()) {
438
+ continue;
439
+ } else if (first) {
440
+ sizes = to_expand[i].sym_sizes();
441
+ first = false;
442
+ } else {
443
+ sizes = infer_size_symdimvector(sizes, to_expand[i].sym_sizes());
444
+ }
445
+ }
446
+
447
+ std::vector<Tensor> result(to_expand.size());
448
+ for (const auto i : c10::irange(to_expand.size())) {
449
+ if (!to_expand[i].defined()) {
450
+ continue;
451
+ } else if (to_expand[i].sym_sizes().equals(sizes)) {
452
+ result[i] = to_expand[i];
453
+ } else {
454
+ result[i] = to_expand[i].expand_symint(sizes);
455
+ }
456
+ }
457
+ return result;
458
+ }
459
+
460
+ template <typename T>
461
+ inline Tensor _sum_to(
462
+ Tensor tensor,
463
+ const c10::ArrayRef<T> shape,
464
+ bool always_return_non_view = false) {
465
+ if (shape.size() == 0) {
466
+ return tensor.sum();
467
+ }
468
+
469
+ auto sizes = at::symint::sizes<T>(tensor);
470
+ c10::SmallVector<int64_t, 8> reduce_dims;
471
+ const int64_t leading_dims = sizes.size() - shape.size();
472
+ for (const auto i : c10::irange(leading_dims)) {
473
+ reduce_dims.push_back(i);
474
+ }
475
+ for (int64_t i = leading_dims; i < static_cast<int64_t>(sizes.size()); ++i) {
476
+ if (TORCH_GUARD_OR_FALSE(sym_eq(shape[i - leading_dims], 1)) &&
477
+ TORCH_GUARD_OR_TRUE(sym_ne(sizes[i], 1))) {
478
+ reduce_dims.push_back(i);
479
+ } else {
480
+ // if we assume no reduction due to unbacked we ensure that at runtime.
481
+ TORCH_MAYBE_SYM_CHECK(
482
+ sym_eq(shape[i - leading_dims], sizes[i]),
483
+ "non-reduction path was assumed due to unbacked symbols expected those two sizes to be the same:",
484
+ shape[i - leading_dims],
485
+ ", ",
486
+ sizes[i])
487
+ }
488
+ }
489
+
490
+ if (!reduce_dims.empty()) {
491
+ tensor = tensor.sum(reduce_dims, /*keepdim=*/true);
492
+ }
493
+
494
+ if (always_return_non_view) {
495
+ // This is only actually used by the functionalization pass.
496
+ // We want to be able to guarantee that this function doesn't return a view
497
+ // of the input.
498
+ return leading_dims > 0 ? at::symint::view_copy<T>(tensor, shape)
499
+ : tensor.clone();
500
+ } else {
501
+ return leading_dims > 0 ? at::symint::view<T>(tensor, shape) : tensor;
502
+ }
503
+ }
504
+
505
+ inline Tensor sum_to(
506
+ Tensor tensor,
507
+ const c10::SymIntArrayRef shape,
508
+ bool always_return_non_view = false) {
509
+ return _sum_to(std::move(tensor), shape, always_return_non_view);
510
+ }
511
+
512
+ // Sums `tensor` repeatedly to produce a tensor of shape `shape`.
513
+ // Precondition: is_expandable_to(shape, tensor.sizes()) must be true
514
+ inline Tensor sum_to(
515
+ Tensor tensor,
516
+ const IntArrayRef shape,
517
+ bool always_return_non_view = false) {
518
+ return _sum_to(std::move(tensor), shape, always_return_non_view);
519
+ }
520
+
521
+ inline bool is_expandable_to(
522
+ SymIntArrayRef shape,
523
+ c10::SymIntArrayRef desired) {
524
+ size_t ndim = shape.size();
525
+ size_t target_dim = desired.size();
526
+ if (ndim > target_dim) {
527
+ return false;
528
+ }
529
+ for (const auto i : c10::irange(ndim)) {
530
+ const auto& size = shape[ndim - i - 1];
531
+ const auto& target = desired[target_dim - i - 1];
532
+ if (size != target && size != 1) {
533
+ return false;
534
+ }
535
+ }
536
+ return true;
537
+ }
538
+
539
+ inline bool is_expandable_to(IntArrayRef shape, IntArrayRef desired) {
540
+ auto sym_shape = c10::SymIntArrayRef(
541
+ reinterpret_cast<const c10::SymInt*>(shape.data()), shape.size());
542
+ auto sym_desired = c10::SymIntArrayRef(
543
+ reinterpret_cast<const c10::SymInt*>(desired.data()), desired.size());
544
+ return is_expandable_to(sym_shape, sym_desired);
545
+ }
546
+
547
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/Formatting.h ADDED
@@ -0,0 +1 @@
 
 
1
+ #include <ATen/core/Formatting.h>
western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.cpp ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/FuncTorchTLS.h>
2
+
3
+ namespace at::functorch {
4
+
5
+ namespace {
6
+
7
+ thread_local std::unique_ptr<FuncTorchTLSBase> kFuncTorchTLS = nullptr;
8
+
9
+ }
10
+
11
+ std::unique_ptr<FuncTorchTLSBase> getCopyOfFuncTorchTLS() {
12
+ if (kFuncTorchTLS == nullptr) {
13
+ return nullptr;
14
+ }
15
+ return kFuncTorchTLS->deepcopy();
16
+ }
17
+
18
+ void setFuncTorchTLS(const std::shared_ptr<const FuncTorchTLSBase>& state) {
19
+ if (state == nullptr) {
20
+ kFuncTorchTLS = nullptr;
21
+ return;
22
+ }
23
+ kFuncTorchTLS = state->deepcopy();
24
+ }
25
+
26
+ std::unique_ptr<FuncTorchTLSBase>& functorchTLSAccessor() {
27
+ return kFuncTorchTLS;
28
+ }
29
+
30
+
31
+ } // namespace at::functorch
western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <memory>
5
+
6
+ namespace at::functorch {
7
+
8
+ // NOTE [functorch TLS in pytorch/pytorch]
9
+ //
10
+ // functorch lives out-of-tree. However, it has some TLS that needs to be
11
+ // propagated. The solution for that is we store a pointer to the TLS
12
+ // inside pytorch/pytorch and extend FuncTorchTLSBase inside functorch to
13
+ // include whatever functorch needs.
14
+ //
15
+ // We need to store a pointer due to the indirection:
16
+ // inside functorch, we will create a subclass of FunctorchTLSBase called
17
+ // FuncTorchTLSImpl that actually contains metadata, like the DynamicLayerStack.
18
+ // FuncTorchTLSBase doesn't have any metadata because it hasn't been defined
19
+ // yet.
20
+ //
21
+ // Here in pytorch/pytorch, we will pass around FuncTorchTLSBase*, but inside
22
+ // functorch, we will assign a FuncTorchTLSImpl* to the FunctorchTLSBase*.
23
+ // We can't directly pass around FunctorchTLSBase (without a pointer) because
24
+ // FuncTorchTLSImpl does not fit inside a FuncTorchTLSBase by virtue of having
25
+ // more elements.
26
+ struct TORCH_API FuncTorchTLSBase {
27
+ virtual ~FuncTorchTLSBase() = default;
28
+ virtual std::unique_ptr<FuncTorchTLSBase> deepcopy() const = 0;
29
+
30
+ virtual int64_t checkSupportsSingleLevelAutogradFunction() const = 0;
31
+ virtual void checkSupportsCppAutogradFunction() const = 0;
32
+ virtual void checkSupportsInplaceRequiresGrad() const = 0;
33
+ virtual void checkSupportsRetainGrad() const = 0;
34
+ };
35
+
36
+ // returns deepcopy of the functorch tls
37
+ TORCH_API std::unique_ptr<FuncTorchTLSBase> getCopyOfFuncTorchTLS();
38
+
39
+ // sets the functorch tls. always does a deep copy.
40
+ TORCH_API void setFuncTorchTLS(
41
+ const std::shared_ptr<const FuncTorchTLSBase>& state);
42
+
43
+ // get a mutable reference to the functorch tls
44
+ TORCH_API std::unique_ptr<FuncTorchTLSBase>& functorchTLSAccessor();
45
+
46
+ } // namespace at::functorch
western_ai/usa/pytorch/aten/src/ATen/FunctionalInverses.cpp ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #include <ATen/FunctionalInverses.h>
3
+
4
+ #include <ATen/ATen.h>
5
+ #include <ATen/ExpandUtils.h>
6
+ #include <ATen/WrapDimUtilsMulti.h>
7
+
8
+ #include <utility>
9
+ namespace at::functionalization {
10
+
11
+ // This logic is similar to autograd code for view backwards calls.
12
+ // We can't easily share it though, because (eventually) these functions
13
+ // will all call `permute/unsqueeze_copy()` instead of `permute/unsqueeze`.
14
+
15
+ static Tensor permute_inverse(const Tensor& self, IntArrayRef dims, InverseReturnMode inverse_return_mode) {
16
+ // invert the permutation
17
+ auto ndims = static_cast<int64_t>(dims.size());
18
+ std::vector<int64_t> dims_(ndims);
19
+ for(const auto i : c10::irange(ndims)) {
20
+ dims_[at::maybe_wrap_dim(dims[i], ndims)] = i;
21
+ }
22
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
23
+ return at::permute(self, dims_);
24
+ } else {
25
+ return at::permute_copy(self, dims_);
26
+ }
27
+ }
28
+
29
+ static Tensor unsqueeze_copy_to(const Tensor & self, c10::SymIntArrayRef sizes, InverseReturnMode inverse_return_mode) {
30
+ auto result = self;
31
+ bool need_alias = (inverse_return_mode == InverseReturnMode::AlwaysView);
32
+ int64_t nDims = static_cast<int64_t>(sizes.size());
33
+ for(const auto dim : c10::irange(nDims)) {
34
+ if (sizes[dim] == 1) {
35
+ need_alias = false;
36
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
37
+ result = at::unsqueeze(result, dim);
38
+ } else {
39
+ result = at::unsqueeze_copy(result, dim);
40
+ }
41
+ }
42
+ }
43
+
44
+ // return an alias to ensure the output is a view when necessary
45
+ return need_alias ? at::alias(result) : result;
46
+ }
47
+
48
+ static Tensor unsqueeze_copy_to(const Tensor & self, IntArrayRef dim, c10::SymIntArrayRef sizes, InverseReturnMode inverse_return_mode) {
49
+ const auto ndim = static_cast<int64_t>(sizes.size());
50
+ const auto mask = at::dim_list_to_bitset(dim, ndim);
51
+ Tensor result = self;
52
+ bool need_alias = (inverse_return_mode == InverseReturnMode::AlwaysView);
53
+ // in NumPy it's not an error to unsqueeze a scalar, but we still need to avoided
54
+ // unsqueezing in the backward.
55
+ if (ndim == 0) {
56
+ // return an alias to ensure the output is a view when necessary
57
+ return need_alias ? at::alias(result) : result;
58
+ }
59
+
60
+ for (const auto d : c10::irange(ndim)) {
61
+ if (mask.test(d) && sizes[d] == 1) {
62
+ need_alias = false;
63
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
64
+ result = at::unsqueeze(result, d);
65
+ } else {
66
+ result = at::unsqueeze_copy(result, d);
67
+ }
68
+ }
69
+ }
70
+
71
+ // return an alias to ensure the output is a view when necessary
72
+ return need_alias ? at::alias(result) : result;
73
+ }
74
+
75
+ // Note [Functionalization Pass: View Inverses].
76
+ // This file contains the implementation of each "view inverse".
77
+ // These aren't really true inverses in the mathematically sense: each view inverse describes how to undo
78
+ // the original view (although it takes in different arguments).
79
+ //
80
+ // E.g. Below is an example of a program that has alias operations removed, and the role that view inverses play:
81
+ //
82
+ // normal program with views and mutations:
83
+ // view1 = input1.view_op(args...)
84
+ // view1.add_(1) (perform a mutation on the view, which should also modify input)
85
+
86
+ // version of the program with no aliasing, that instead uses view_inverse functions:
87
+ // view_copy1 = input1.view_copy_op(args...)
88
+ // view_copy1.add_(1) (perform a mutation on view_copy1. At this point, input1 is NOT modified)
89
+ // x = view_op_inverse(input1, view_copy1, args...)
90
+ //
91
+ // at this point, input1 and x should be equal
92
+ //
93
+ // Note that input1 is also passed as an argument to view_op_inverse in the above example.
94
+ // This isn't actually required for most view operators: it's only required for view ops
95
+ // where you can't figure out what the size of the base tensor is given just the view tensor and arguments.
96
+ // Examples are slice/select/scatter/squeeze/as_strided.
97
+ // We happen to be passing in the base tensor in all cases, mostly to make the codegen simpler.
98
+ // But you'll see below that the "base" argument is ignored by most view_inverse implementations.
99
+
100
+ // ----------------------------------------------------------
101
+ // Implementations of each view_inverse() function are below.
102
+ // One of these needs to be implemented for every existing non-composite view operator.
103
+ // The codegen automatically generates the corresponding function declaration.
104
+ // ----------------------------------------------------------
105
+
106
+ Tensor FunctionalInverses::_fw_primal_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t level) {
107
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _fw_primal() during the functionalization pass. For now, this is not supported.");
108
+ }
109
+
110
+ Tensor FunctionalInverses::_make_dual_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode, const at::Tensor& tangent, int64_t level) {
111
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _make_dual() during the functionalization pass. For now, this is not supported.");
112
+ }
113
+
114
+ Tensor FunctionalInverses::view_as_real_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
115
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
116
+ return at::view_as_complex(mutated_view);
117
+ } else {
118
+ return at::view_as_complex_copy(mutated_view);
119
+ }
120
+ }
121
+
122
+ Tensor FunctionalInverses::view_as_complex_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
123
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
124
+ return at::view_as_real(mutated_view.resolve_conj());
125
+ } else {
126
+ return at::view_as_real_copy(mutated_view.resolve_conj());
127
+ }
128
+ }
129
+
130
+ Tensor FunctionalInverses::_conj_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
131
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
132
+ return at::_conj(mutated_view);
133
+ } else {
134
+ return at::_conj_copy(mutated_view);
135
+ }
136
+ }
137
+
138
+ Tensor FunctionalInverses::_neg_view_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
139
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
140
+ return at::_neg_view(mutated_view);
141
+ } else {
142
+ return at::_neg_view_copy(mutated_view);
143
+ }
144
+ }
145
+
146
+ Tensor FunctionalInverses::as_strided_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, at::SymIntArrayRef stride, std::optional<c10::SymInt> storage_offset) {
147
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
148
+ // NB: assumes mutated_view is a narrowed view of base.
149
+ // We should NOT do this for functionalization
150
+ return mutated_view.as_strided_symint(
151
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
152
+ } else {
153
+ return base.as_strided_scatter_symint(mutated_view, size, stride, std::move(storage_offset));
154
+ }
155
+ }
156
+
157
+ Tensor FunctionalInverses::diagonal_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t offset, int64_t dim1, int64_t dim2) {
158
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
159
+ // NB: assumes mutated_view is a narrowed view of base.
160
+ // We should NOT do this for functionalization
161
+ return mutated_view.as_strided_symint(
162
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
163
+ } else {
164
+ return base.diagonal_scatter(mutated_view, offset, dim1, dim2);
165
+ }
166
+ }
167
+
168
+ Tensor FunctionalInverses::expand_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, bool implicit) {
169
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
170
+ // NB: assumes mutated_view is an expanded view of base.
171
+ // We should NOT do this for functionalization
172
+ return mutated_view.as_strided_symint(
173
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
174
+ } else {
175
+ return base + at::sum_to(
176
+ mutated_view - base,
177
+ base.sym_sizes(),
178
+ /*always_return_non_view=*/inverse_return_mode == InverseReturnMode::NeverView
179
+ );
180
+ }
181
+ }
182
+
183
+ Tensor FunctionalInverses::permute_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::IntArrayRef dims) {
184
+ return at::functionalization::permute_inverse(mutated_view, dims, inverse_return_mode);
185
+ }
186
+
187
+ Tensor FunctionalInverses::_reshape_alias_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, at::SymIntArrayRef stride) {
188
+ // Note that I'm directly calling reshape(), and ignoring the strides.
189
+ // _reshape_alias() isn't available from user code, and is an implementation detail of reshape().
190
+ // Specifically, passing in the strides directly can get us into trouble in cases like:
191
+ // b = a[0]; c = b.reshape(...); c.add_(1); print(a)
192
+ // When we eventually run the _reshape_alias_inverse() call here, if we were to pass in both sizes and strides,
193
+ // The call would fail because `mutated_view` doesn't have enough bytes of storage.
194
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
195
+ return at::_reshape_alias_symint(mutated_view, base.sym_sizes(), base.sym_strides());
196
+ } else {
197
+ return at::_reshape_alias_copy_symint(mutated_view, base.sym_sizes(), base.sym_strides());
198
+ }
199
+ }
200
+
201
+ Tensor FunctionalInverses::select_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim, c10::SymInt index) {
202
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
203
+ // NB: assumes mutated_view is a narrowed view of base.
204
+ // We should NOT do this for functionalization
205
+ return mutated_view.as_strided_symint(
206
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
207
+ } else {
208
+ return base.select_scatter_symint(mutated_view, dim, std::move(index));
209
+ }
210
+ }
211
+
212
+ Tensor FunctionalInverses::detach_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
213
+ // the functionalization pass doesn't care about autograd metadata - as a view, I think detach() is just an identity function
214
+ return mutated_view;
215
+ }
216
+
217
+ Tensor FunctionalInverses::lift_fresh_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
218
+ return mutated_view;
219
+ }
220
+
221
+ Tensor FunctionalInverses::slice_Tensor_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim, std::optional<c10::SymInt> start, std::optional<c10::SymInt> end, c10::SymInt step) {
222
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
223
+ // NB: assumes mutated_view is a narrowed view of base.
224
+ // We should NOT do this for functionalization
225
+ return mutated_view.slice_inverse_symint(
226
+ base, dim, std::move(start), std::move(end), std::move(step));
227
+ } else {
228
+ return base.slice_scatter_symint(mutated_view, dim, std::move(start), std::move(end), std::move(step));
229
+ }
230
+ }
231
+
232
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
233
+ Tensor FunctionalInverses::split_Tensor_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, c10::SymInt split_size, int64_t dim) {
234
+ // It would be nice if this logic could be reused from autograd's split_backward(), but I don't think it can.
235
+ // For functionalization, we have only have one of the tensors from the TensorList outputted by split(), and we want to layer i
236
+ // on top of the base tensor.
237
+ // For autograd, we have all of the tensors outputted by split() and we just want to stack them.
238
+ dim = at::maybe_wrap_dim(dim, base.dim());
239
+ auto dim_size = base.sym_size(dim);
240
+ auto start = split_size * mutated_view_idx;
241
+ auto end = split_size + start;
242
+ if (end > dim_size) end = dim_size;
243
+
244
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
245
+ // NB: assumes mutated_view is a narrowed view of base.
246
+ // We should NOT do this for functionalization
247
+ return mutated_view.slice_inverse_symint(base, dim, start, end, 1);
248
+ } else {
249
+ return base.slice_scatter_symint(mutated_view, dim, start, end, 1);
250
+ }
251
+ }
252
+
253
+ Tensor FunctionalInverses::split_with_sizes_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, c10::SymIntArrayRef split_sizes, int64_t dim) {
254
+ dim = at::maybe_wrap_dim(dim, base.dim());
255
+ auto dim_size = base.sym_size(dim);
256
+ c10::SymInt start = 0;
257
+ for (int64_t i = 0; i < mutated_view_idx; ++i) {
258
+ start += split_sizes[i];
259
+ }
260
+ auto end = start + split_sizes[mutated_view_idx];
261
+ if (end > dim_size) end = dim_size;
262
+
263
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
264
+ // NB: assumes mutated_view is a narrowed view of base.
265
+ // We should NOT do this for functionalization
266
+ return mutated_view.slice_inverse_symint(base, dim, start, end, 1);
267
+ } else {
268
+ return base.slice_scatter_symint(mutated_view, dim, start, end, 1);
269
+ }
270
+ }
271
+
272
+ Tensor FunctionalInverses::squeeze_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
273
+ return unsqueeze_copy_to(mutated_view, base.sym_sizes(), inverse_return_mode);
274
+ }
275
+
276
+ Tensor FunctionalInverses::squeeze_dim_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim) {
277
+ return unsqueeze_copy_to(mutated_view, dim, base.sym_sizes(), inverse_return_mode);
278
+ }
279
+
280
+ Tensor FunctionalInverses::squeeze_dims_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, IntArrayRef dim) {
281
+ return unsqueeze_copy_to(mutated_view, dim, base.sym_sizes(), inverse_return_mode);
282
+ }
283
+
284
+ Tensor FunctionalInverses::t_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
285
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
286
+ return at::t(mutated_view);
287
+ } else {
288
+ return at::t_copy(mutated_view);
289
+ }
290
+ }
291
+
292
+ Tensor FunctionalInverses::transpose_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim0, int64_t dim1) {
293
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
294
+ return transpose(mutated_view, dim0, dim1);
295
+ } else {
296
+ return transpose_copy(mutated_view, dim0, dim1);
297
+ }
298
+ }
299
+
300
+ Tensor FunctionalInverses::_nested_view_from_buffer_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, const Tensor& nested_sizes, const Tensor& nested_strides, const Tensor& storage_offsets) {
301
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _nested_view_from_buffer() during the functionalization pass. For now, nested tensors aren't supported during functionalization");
302
+ }
303
+
304
+ Tensor FunctionalInverses::_nested_view_from_jagged_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, const Tensor& offsets, const Tensor& dummy, const std::optional<Tensor>& lengths, int64_t ragged_idx, const std::optional<Tensor>& min_seqlen, const std::optional<Tensor>& max_seqlen) {
305
+ auto values = at::_nested_get_values(mutated_view);
306
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
307
+ return values;
308
+ } else {
309
+ return values.clone(/*memory_format=*/at::MemoryFormat::Contiguous);
310
+ }
311
+ }
312
+
313
+ Tensor FunctionalInverses::_nested_get_values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
314
+ auto offsets = at::_nested_get_offsets(base);
315
+ auto lengths = at::_nested_get_lengths(base);
316
+ auto ragged_idx = at::_nested_get_ragged_idx(base);
317
+ auto dummy = at::_nested_get_jagged_dummy(base);
318
+ auto min_seqlen = at::_nested_get_min_seqlen(base);
319
+ auto max_seqlen = at::_nested_get_max_seqlen(base);
320
+ auto nt = at::_nested_view_from_jagged(
321
+ mutated_view, offsets, dummy, lengths, ragged_idx,
322
+ (min_seqlen.defined() ? std::optional<Tensor>(min_seqlen) : std::nullopt),
323
+ (max_seqlen.defined() ? std::optional<Tensor>(max_seqlen) : std::nullopt));
324
+
325
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
326
+ return nt;
327
+ } else {
328
+ return nt.clone(/*memory_format=*/at::MemoryFormat::Contiguous);
329
+ }
330
+ }
331
+
332
+ Tensor FunctionalInverses::unsqueeze_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim) {
333
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
334
+ return at::squeeze(mutated_view, dim);
335
+ } else {
336
+ return at::squeeze_copy(mutated_view, dim);
337
+ }
338
+ }
339
+
340
+ Tensor FunctionalInverses::_indices_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
341
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
342
+ }
343
+
344
+ Tensor FunctionalInverses::_values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
345
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _values() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
346
+ }
347
+
348
+ Tensor FunctionalInverses::indices_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
349
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
350
+ }
351
+
352
+ Tensor FunctionalInverses::values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
353
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call values() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
354
+ }
355
+
356
+ Tensor FunctionalInverses::_sparse_broadcast_to_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::IntArrayRef size) {
357
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call _sparse_broadcast_to() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
358
+ }
359
+
360
+ Tensor FunctionalInverses::crow_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
361
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call crow_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
362
+ }
363
+
364
+ Tensor FunctionalInverses::col_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
365
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call col_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
366
+ }
367
+
368
+ Tensor FunctionalInverses::ccol_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
369
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call ccol_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
370
+ }
371
+
372
+ Tensor FunctionalInverses::row_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
373
+ TORCH_INTERNAL_ASSERT(false, "Attempted to call row_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization");
374
+ }
375
+
376
+ Tensor FunctionalInverses::unbind_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int64_t dim) {
377
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
378
+ // NB: assumes mutated_view is a narrowed view of base.
379
+ // We should NOT do this for functionalization
380
+ return mutated_view.as_strided_symint(
381
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
382
+ } else {
383
+ dim = at::maybe_wrap_dim(dim, static_cast<int64_t>(base.sizes().size()));
384
+ return base.select_scatter(mutated_view, dim, mutated_view_idx);
385
+ }
386
+ }
387
+
388
+ Tensor FunctionalInverses::view_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size) {
389
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
390
+ return mutated_view.view_symint(base.sym_sizes());
391
+ } else {
392
+ return at::view_copy_symint(mutated_view, base.sym_sizes());
393
+ }
394
+ }
395
+
396
+
397
+ Tensor FunctionalInverses::view_dtype_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::ScalarType dtype) {
398
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
399
+ return mutated_view.view(base.scalar_type());
400
+ } else {
401
+ return at::view_copy(mutated_view, base.scalar_type());
402
+ }
403
+ }
404
+
405
+ Tensor FunctionalInverses::unfold_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dimension, int64_t size, int64_t step) {
406
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
407
+ // NB: assumes mutated_view is a narrowed view of base.
408
+ // We should NOT do this for functionalization
409
+ return mutated_view.as_strided_symint(
410
+ base.sym_sizes(), base.sym_strides(), base.sym_storage_offset());
411
+ } else {
412
+ // I think autograd and the functionalization pass want the exact same thing here, but need to test to confirm.
413
+ // unfold_backward() is safe to use here because it is NOT a view op.
414
+ // (note: technically, we'll have an extra memory copy.
415
+ // We'd need to add an aliasing version of unfold_backward to fix that though).
416
+ TORCH_CHECK(
417
+ !(inverse_return_mode == InverseReturnMode::ViewOrScatterInverse && size > step),
418
+ "While executing unfold, functionalization encountered a tensor being mutated that has internal overlap. \
419
+ When using torch.compile (or running functionalization directly), this is banned \
420
+ as the behavior is not well defined. Consider cloning the tensor before mutating it, \
421
+ or removing the mutation from your model."
422
+ );
423
+ return unfold_backward(mutated_view, base.sizes(), dimension, size, step);
424
+ }
425
+ }
426
+
427
+ Tensor FunctionalInverses::alias_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) {
428
+ if (inverse_return_mode != InverseReturnMode::NeverView) {
429
+ return at::alias(mutated_view);
430
+ } else {
431
+ return at::alias_copy(mutated_view);
432
+ }
433
+ }
434
+
435
+ Tensor FunctionalInverses::chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim) {
436
+ // TODO: Can the logic from TensorShape.cpp be reused here somehow?
437
+ const auto dim_size = base.sym_size(dim);
438
+ auto split_size = (dim_size + chunks - 1) / chunks;
439
+ std::vector<c10::SymInt> split_sizes(chunks, split_size);
440
+ split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size);
441
+ return split_with_sizes_inverse(base, mutated_view, inverse_return_mode, mutated_view_idx, split_sizes, dim);
442
+ }
443
+
444
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
445
+ Tensor FunctionalInverses::narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length) {
446
+ if (inverse_return_mode == InverseReturnMode::AlwaysView) {
447
+ // NB: assumes mutated_view is a narrowed view of base.
448
+ // We should NOT do this for functionalization
449
+ return mutated_view.slice_inverse_symint(base, dim, start, start + length, 1);
450
+ } else {
451
+ return base.slice_scatter_symint(
452
+ mutated_view, dim, start, start + length, 1);
453
+ }
454
+ }
455
+
456
+ Tensor FunctionalInverses::slice_inverse_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, const at::Tensor & src, int64_t dim, std::optional<c10::SymInt> start, std::optional<c10::SymInt> end, c10::SymInt step) {
457
+ // slice_inverse() inverse is just slice()
458
+ if (inverse_return_mode == InverseReturnMode::NeverView) {
459
+ return at::slice_copy_symint(
460
+ mutated_view, dim, std::move(start), std::move(end), std::move(step));
461
+ } else {
462
+ return mutated_view.slice_symint(
463
+ dim, std::move(start), std::move(end), std::move(step));
464
+ }
465
+ }
466
+
467
+ } // namespace at::functionalization
western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.cpp ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/FunctionalStorageImpl.h>
2
+
3
+ #include <ATen/EmptyTensor.h>
4
+ #include <ATen/FunctionalTensorWrapper.h>
5
+ #include <ATen/SparseCsrTensorUtils.h>
6
+ #include <ATen/core/LegacyTypeDispatch.h>
7
+ #include <c10/util/Exception.h>
8
+ #include <vector>
9
+
10
+ namespace at::functionalization {
11
+
12
+ // Note [Functionalization: Alias Removal Part 2]
13
+ // See Note [Functionalization: Alias Removal] for more details.
14
+ // This function applies a single update from one of the views to the StorageImpl.
15
+ // We start out with <original_base> and <mutated_view>, and our goal is to end up with <mutated_base>.
16
+ // Consider this program:
17
+ //
18
+ // base = ...
19
+ // a = base.view1()
20
+ // b = a.view2()
21
+ // c = b.view3()
22
+ // c.add_(3)
23
+ //
24
+ // Then the functionalization pass will queue an update as follows:
25
+ //
26
+ // update.new_val = c # the updated value of c
27
+ // update.view_metas = [view1_meta, view2_meta, view3_meta]
28
+ //
29
+ // Syncing any of a, b or c will eventually call apply_update() on the storage, and the following will run:
30
+ //
31
+ // tmp_values = [base, a, b] # NB: c is not necessary
32
+ // t = update.new_val
33
+ // t = view3_inverse(b, t, 0) # 0 is output index, these are all single output views so it's 0
34
+ // t = view2_inverse(a, t, 0)
35
+ // t = view1_inverse(base, t, 0) # t now represents the updated storage.
36
+ // storage.base_ = t
37
+ static const Tensor apply_update(const FunctionalStorageImpl::Update& update, const Tensor& base) {
38
+ at::Tensor t = update.new_val;
39
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t));
40
+ if (update.view_metas.empty()) { return t; }
41
+
42
+ std::vector<at::Tensor> tmp_values({base});
43
+ tmp_values.reserve(update.view_metas.size());
44
+ for (size_t i = 0; i < update.view_metas.size() - 1; ++i) {
45
+ at::Tensor next_view = update.view_metas[i]->forward(tmp_values.back());
46
+ // NB: We only actually need tmp_values for ops like select/slice/diagonal/squeeze/as_strided
47
+ // All of these ops require additional information to recover the sizes of the original tensor.
48
+ // If need to, we could probably apply this optimization and only bother computing tmp_values
49
+ // for those necessary view ops.
50
+ tmp_values.push_back(std::move(next_view));
51
+ }
52
+ for(int64_t i = static_cast<int64_t>(update.view_metas.size()) - 1; i >= 0; --i) {
53
+ // Each view inverse is implemented in ViewInverses.cpp.
54
+ t = update.view_metas[i]->reverse(tmp_values[i], t);
55
+ }
56
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t));
57
+ return t;
58
+ }
59
+
60
+
61
+ static c10::SymInt get_nbytes(const Tensor& value) {
62
+ // The functionalization story when wrapping tensors that don't have storage
63
+ // is a bit wonky, but fortunately for some models (e.g., dlrm) we never
64
+ // actually perform mutations on these tensors, so you never really get
65
+ // called out on it. For now, functionalization still creates "storages"
66
+ // for these tensors (which is wrong), but we don't give them any space.
67
+ // A more proper fix would be to have a SparseFunctionalTensorWrapper that
68
+ // models sparse correctly.
69
+ if (value.is_sparse() || at::sparse_csr::is_sparse_compressed(value)) {
70
+ return 0;
71
+ }
72
+ if (value.unsafeGetTensorImpl()->has_symbolic_sizes_strides()) {
73
+ // Today, the two implementations of SymInt are in Python (proxy tensor),
74
+ // and lazy tensor (LTC/XLA).
75
+ // LTC hasn't implemented SymInt support yet though
76
+ // Once it does, we should remove this check.
77
+ if (value.key_set().has(c10::DispatchKey::Python)) {
78
+ return value.storage().sym_nbytes();
79
+ }
80
+ return at::detail::computeStorageNbytes(value.sym_sizes(), value.sym_strides(),static_cast<int64_t>(value.dtype().itemsize()), value.sym_storage_offset());
81
+ }
82
+ // XLA storage objects also do not properly track nbytes.
83
+ return static_cast<int64_t>(at::detail::computeStorageNbytes(value.sizes(), value.strides(), value.dtype().itemsize(), value.storage_offset()));
84
+ }
85
+
86
+ FunctionalStorageImpl::FunctionalStorageImpl(const Tensor& base)
87
+ : c10::StorageImpl(
88
+ c10::StorageImpl::use_byte_size_t(),
89
+ get_nbytes(base),
90
+ DataPtr{nullptr, base.device()},
91
+ GetAllocator(kMeta),
92
+ /*resizable=*/true
93
+ ),
94
+ base_(base)
95
+ {
96
+ // SparseTensorImpl has no storage, so we cannot query its nbytes.
97
+ // (original_storage_size is only used for storage resizing in fsdp anyway, which does not apply to sparse)
98
+ // Same for XLA
99
+ if (base.unsafeGetTensorImpl()->has_storage() && data_ptr().device().type() != c10::DeviceType::XLA) {
100
+ original_storage_size_ = base.unsafeGetTensorImpl()->unsafe_storage().unsafeGetStorageImpl()->sym_nbytes();
101
+ } else {
102
+ original_storage_size_ = -1;
103
+ }
104
+ curr_storage_size_ = original_storage_size_;
105
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(base_));
106
+ }
107
+
108
+ void FunctionalStorageImpl::add_update(const Tensor& updated_val, const std::vector<std::shared_ptr<ViewMeta>>& metas) {
109
+ TORCH_CHECK(!frozen_, "cannot mutate tensors with frozen storage");
110
+
111
+ if (metas.size() > 1) {
112
+ for (size_t i = 1; i < metas.size(); ++i) {
113
+ // Skipping this check for XLA. Would be good to add it back, but it is failing XLA CI
114
+ TORCH_CHECK(updated_val.device().type() == c10::DeviceType::XLA || !metas[i]->is_as_strided,
115
+ "During torch.compile, encountered a mutation on a view chain of length ", metas.size(), ", where view ", i,
116
+ " was an as_strided() call. as_strided() is non-compositional, and therefore is not possible to functionalize properly today,"
117
+ "so this behavior is banned in compile. As a workaround, you can either remove the mutation from the model code, or you "
118
+ "can insert a graph break right before the mutation with torch._dynamo.graph_break(). If you would like this behavior to "
119
+ "work properly, please comment on https://github.com/pytorch/pytorch/issues/104505.");
120
+ }
121
+ }
122
+ updates_.push_back({updated_val, metas});
123
+ generation_++;
124
+ }
125
+
126
+ bool FunctionalStorageImpl::apply_updates() {
127
+ // N.B:none of the tensors used in this function should be FunctionalTensorWrappers at this point.
128
+ // The only reason we currently need the TLS exclude guard here is because of functorch's DynamicLayer stack.
129
+ // It adds the Functionalize key into TLS before redispatching to the functionalization kernels,
130
+ // which means that we need to explicitly exclude it here before doing any other work underneath the pass.
131
+ at::AutoDispatchSkipFunctionalize guard;
132
+ bool any_updates = !updates_.empty();
133
+ for (auto& update_data: updates_) {
134
+ base_ = apply_update(update_data, base_);
135
+ }
136
+ updates_.clear();
137
+ return any_updates;
138
+ }
139
+
140
+ } // namespace at::functionalization
western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.h ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+
5
+ #include <tuple>
6
+ #include <type_traits>
7
+ #include <utility>
8
+
9
+ namespace at::functionalization {
10
+
11
+ // See Note [Functionalization Pass In Core]
12
+
13
+ enum class InverseReturnMode {
14
+ /// Specifies that functional inverses should always return a view.
15
+ AlwaysView,
16
+ /// Specifies that functional inverses should always return a non-view / copy.
17
+ NeverView,
18
+ /// Specifies that functional inverses should return a view unless a (copying)
19
+ /// scatter
20
+ /// inverse exists, in which case that will be used instead.
21
+ /// This avoids as_strided() calls that can be difficult for subclasses to
22
+ /// handle.
23
+ ViewOrScatterInverse,
24
+ };
25
+
26
+ #define FUNCTIONALIZATION_VIEWMETA_NAME(TYPE) \
27
+ static const char* name() { \
28
+ return #TYPE; \
29
+ }
30
+
31
+ template <class T>
32
+ struct tuple_elements_are_owning;
33
+
34
+ template <class... Ts>
35
+ struct tuple_elements_are_owning<std::tuple<Ts...>>
36
+ : std::bool_constant<(std::is_same_v<std::decay_t<Ts>, Ts> && ...)> {};
37
+
38
+ #define FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(...) \
39
+ using SerializableTuple = std::tuple<__VA_ARGS__>; \
40
+ static_assert( \
41
+ ::at::functionalization::tuple_elements_are_owning< \
42
+ SerializableTuple>::value, \
43
+ "FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE elements must be " \
44
+ "owning value types (no references or cv-qualifiers); a reference " \
45
+ "element would dangle in to_serializable_tuple() and in the data " \
46
+ "member it initializes.")
47
+
48
+ // ViewMeta is a class used by the functionalization pass to navigate between
49
+ // a base tensor and a view tensor.
50
+ // For example, if I call `b = a.view1(...)`
51
+ // the functionalization pass will generate and store a ViewMeta specialization
52
+ // for `view1` operation on b that looks like:
53
+ //
54
+ // struct TORCH_API view1_ViewMeta : public ViewMeta {
55
+ // FUNCTIONALIZATION_VIEWMETA_NAME(view1_ViewMeta);
56
+ // FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(
57
+ // bool /* reapply_views */,
58
+ // std::vector<int64_t>);
59
+ //
60
+ // view1_ViewMeta(const SerializableTuple& tpl)
61
+ // : view1_ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {}
62
+ //
63
+ // view1_ViewMeta(bool reapply_views, const std::vector<int64_t>& size)
64
+ // : ViewMeta(/*has_symbolic_inputs=*/false),
65
+ // reapply_views(reapply_views),
66
+ // size(size) {}
67
+ //
68
+ // Tensor forward(const Tensor& base) override {
69
+ // return base.view1(...);
70
+ // }
71
+ //
72
+ // Tensor reverse(const Tensor& base, const Tensor& mutated_view) override {
73
+ // return at::functionalization::impl::view1_inverse(base, mutated_view,
74
+ // ...);
75
+ // }
76
+ //
77
+ // SerializableTuple to_serializable_tuple() {
78
+ // return std::make_tuple(reapply_views, size);
79
+ // }
80
+ //
81
+ // bool reapply_views;
82
+ // std::vector<int64_t> size;
83
+ // };
84
+ //
85
+ // The forward function describes how to replay view1 on a tensor.
86
+ //
87
+ // The reverse function describes how, given a tensor that is already a view,
88
+ // how to get the corresponding base tensor. See Note [Functionalization Pass:
89
+ // View Inverses] for details.
90
+ //
91
+ // `SerializedTuple` is a typedef that defines an `std::tuple<...>` type
92
+ // representing the `ViewMeta` instance state. Methods that take in/return such
93
+ // a type are used for supporting pickle serialization.
94
+ struct ViewMeta {
95
+ ViewMeta(
96
+ bool has_symbolic_inputs,
97
+ bool is_multi_output = false,
98
+ bool is_as_strided = false,
99
+ int64_t out_idx = 0)
100
+ : out_index(out_idx),
101
+ is_multi_output(is_multi_output),
102
+ is_as_strided(is_as_strided),
103
+ has_symbolic_inputs(has_symbolic_inputs) {}
104
+
105
+ virtual ~ViewMeta() = default;
106
+
107
+ virtual Tensor forward(const Tensor& base) = 0;
108
+ virtual Tensor reverse(const Tensor& base, const Tensor& mutated_view) = 0;
109
+
110
+ // See Note [out_idx in ViewMeta]
111
+ int64_t out_index;
112
+
113
+ // Tells us if this is a multi-output view
114
+ bool is_multi_output;
115
+
116
+ bool is_as_strided;
117
+
118
+ // Tells us if this view operation has any symbolic inputs
119
+ bool has_symbolic_inputs;
120
+
121
+ // Returns a new ViewMeta with the same forward/reverse
122
+ // functions, but a new out index.
123
+ //
124
+ // This method should be implemented by those `ViewMeta` that have more than
125
+ // one output.
126
+ virtual std::shared_ptr<ViewMeta> to_out_index(int64_t out_index) {
127
+ TORCH_CHECK_NOT_IMPLEMENTED(
128
+ false,
129
+ "ViewMeta::to_out_index not implemented. ",
130
+ "Likely because there's only one output.");
131
+ }
132
+ };
133
+
134
+ // FunctionalStorageImpl is a subclass of StorageImpl used by the
135
+ // functionalization pass. It has no underlying data (similar to meta storage).
136
+ // It also knows how to reflect mutations to tensors in the absence of a valid
137
+ // data pointer.
138
+ //
139
+ // A storage represents the state shared by (potentially multiple) views of the
140
+ // same tensor. For example, in the following code:
141
+ //
142
+ // b = a.view1(...)
143
+ // c = b.view2(...)
144
+ // b.add_(1)
145
+ // --> storage.add_update(b, {view1_meta})
146
+ //
147
+ // The call to add_(1) will result in a call to alias.add_update(b,
148
+ // {view1_meta}), queueing up the mutation from b onto the alias. Later, suppose
149
+ // c is used in an expression (e.g. you try to print c, or pass it to an
150
+ // operator). Doing so will involve "syncing" c. First we apply any pending
151
+ // updates to the alias, and then we regenerate c by replaying its views off of
152
+ // the updated alias. E.g:
153
+ //
154
+ // print(str(c))
155
+ // --> c.sync_()
156
+ // --> alias.apply_updates() // after this, the alias will be updated to
157
+ // reflect the mutation to b
158
+ struct TORCH_API FunctionalStorageImpl : public c10::StorageImpl {
159
+ public:
160
+ struct Update {
161
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
162
+ const at::Tensor new_val;
163
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
164
+ const std::vector<std::shared_ptr<ViewMeta>> view_metas;
165
+ };
166
+
167
+ explicit FunctionalStorageImpl(const Tensor& value);
168
+
169
+ void add_update(
170
+ const Tensor& updated_val,
171
+ const std::vector<std::shared_ptr<ViewMeta>>& view_metas);
172
+ bool apply_updates();
173
+ const Tensor& base() {
174
+ return base_;
175
+ }
176
+ size_t generation() const {
177
+ return generation_;
178
+ }
179
+ void freeze() {
180
+ frozen_ = true;
181
+ }
182
+
183
+ c10::SymInt get_storage_size(bool before) {
184
+ if (before) {
185
+ return original_storage_size_;
186
+ } else {
187
+ return curr_storage_size_;
188
+ }
189
+ }
190
+
191
+ ~FunctionalStorageImpl() override = default;
192
+
193
+ uint64_t mutation_counter() {
194
+ return mutation_counter_;
195
+ }
196
+ void mark_mutation() {
197
+ mutation_counter_++;
198
+ }
199
+ void mark_mutation_during_no_grad_or_inference_mode() {
200
+ mutation_counter_during_no_grad_or_inference_mode_++;
201
+ }
202
+ void mark_mutation_hidden_from_autograd() {
203
+ mutation_counter_hidden_from_autograd_++;
204
+ }
205
+
206
+ bool are_all_mutations_under_no_grad_or_inference_mode() const {
207
+ auto non_autograd_mutations =
208
+ mutation_counter_during_no_grad_or_inference_mode_ +
209
+ mutation_counter_hidden_from_autograd_;
210
+ // The <= is because both counters will technically be incremented, if we
211
+ // perform e.g. a triton kernel mutation under no_grad
212
+ return mutation_counter_ <= non_autograd_mutations;
213
+ }
214
+
215
+ bool are_all_mutations_hidden_from_autograd() const {
216
+ // mutations under no_grad / inference_mode are technically not hidden from
217
+ // autograd - they change the version counter
218
+ return mutation_counter_ <= mutation_counter_hidden_from_autograd_;
219
+ }
220
+
221
+ void mark_inductor_storage_resize(c10::SymInt new_size) {
222
+ inductor_storage_resized_ = true;
223
+ curr_storage_size_ = std::move(new_size);
224
+ inductor_storage_resized_counter_++;
225
+ }
226
+
227
+ bool was_inductor_storage_resized() {
228
+ return inductor_storage_resized_;
229
+ }
230
+
231
+ uint64_t inductor_storage_resized_counter() {
232
+ return inductor_storage_resized_counter_;
233
+ }
234
+
235
+ private:
236
+ // NB: base_ should always point to a tensor BELOW the current
237
+ // functionalization layer. This is mainly to avoid reference cycles. e.g.
238
+ // given `b = a.view(...)` Both a.storage_ and b.storage_ are a
239
+ // FunctionStorageImpl containing an Walualias, with contains a Tensor
240
+ // `base_`. In this case (where a and b are FunctionalTensorWrapper's), base_
241
+ // should point not to a, but to a's unwrapped value, a.value_` See Note
242
+ // [Functionalization: Walualias Removal] for a diagram that shows this
243
+ // visually.
244
+ at::Tensor base_;
245
+ std::vector<Update> updates_;
246
+ // generation_ gets incremented every time a mutation is queued onto the
247
+ // alias. It is used to determine if a given tensor is "up to date", or if it
248
+ // needs to be regenerated from the alias.
249
+ size_t generation_ = 0;
250
+ // If frozen, no more mutations are allowed on this storage. Once frozen, a
251
+ // storage cannot be unfrozen.
252
+ bool frozen_ = false;
253
+
254
+ // These mutation counters are bumped on the storage
255
+ // whenever a FunctionalTensorWrapper experiences a mutation.
256
+ // When the mutation is under no_grad, or comes from a triton kernel, we also
257
+ // bump the corresponding during_no_grad or hidden_from_autograd counters. Why
258
+ // do we need to detect these two situations separately from "normal" input
259
+ // mutations? (1) "normal" input mutations can mutate autograd metadata like
260
+ // .grad_fn,
261
+ // in which case they need to be replayed outside of the compiled graph
262
+ // (2) "no_grad" input mutations are generally safe to keep in the graph (and
263
+ // compile),
264
+ // but they bump the tensor's VC, so we need to mark_dirty() on the inputs
265
+ // in torch.compile
266
+ // (3) mutations that are fully hidden from autograd (e.g. from a triton
267
+ // kernel)
268
+ // do not mutate any autograd state, and be fully kept in the graph
269
+ // When we detect that an input was mutated, we need to be able to tell if:
270
+ // (1) all of the mutations were from triton kernels
271
+ // (2) all of the mutations were under no_grad
272
+ uint64_t mutation_counter_during_no_grad_or_inference_mode_ = 0;
273
+ uint64_t mutation_counter_ = 0;
274
+ uint64_t mutation_counter_hidden_from_autograd_ = 0;
275
+
276
+ // Used to tell if:
277
+ // (1) There were any storage resizes on a graph input
278
+ // (2) The original/curr storage size tell us if these resizes result in a nop
279
+ bool inductor_storage_resized_ = false;
280
+ uint64_t inductor_storage_resized_counter_ = 0;
281
+ c10::SymInt original_storage_size_;
282
+ c10::SymInt curr_storage_size_;
283
+ };
284
+
285
+ } // namespace at::functionalization
western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.cpp ADDED
@@ -0,0 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #include <ATen/FunctionalTensorWrapper.h>
3
+
4
+ #include <ATen/core/IListRef.h>
5
+ #include <ATen/core/LegacyTypeDispatch.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ #include <c10/util/irange.h>
9
+
10
+ #ifndef AT_PER_OPERATOR_HEADERS
11
+ #include <ATen/Functions.h>
12
+ #else
13
+ #include <ATen/ops/_propagate_xla_data.h>
14
+ #include <ATen/ops/_to_copy.h>
15
+ #endif
16
+
17
+ namespace at {
18
+
19
+ void FunctionalTensorWrapper::set_constructor_metadata() {
20
+ TORCH_INTERNAL_ASSERT(value_.defined());
21
+ // Note: "level" is a concept that we don't know how to compute in core.
22
+ // For now I'm retroactively setting this in functorch,
23
+ // but once Open Multiple Dispatch lands we should be able to calculate this in core.
24
+ level_ = -1;
25
+ // mirror all of the generic tensor metadata onto the wrapper
26
+ copy_generic_tensor_metadata(value_.getIntrusivePtr().get(), this);
27
+ refresh_numel();
28
+ refresh_contiguous();
29
+ storage_access_should_throw_ = false;
30
+ // In general, the sizes/stride metadata on a tensor can change as it is mutated,
31
+ // and these changes need to be reflected in the metadata of the wrapper.
32
+ set_allow_tensor_metadata_change(true);
33
+ key_set_ = c10::DispatchKeySet(c10::DispatchKey::Functionalize) | value_.key_set();
34
+ // All of the keys corresponding to functorch transforms should not be copied over.
35
+ // Functorch transforms all have their own wrapper tensors (e.g. BatchedTensorImpl) which expect
36
+ // to participate in the functorch transforms.
37
+ key_set_ = key_set_ - c10::functorch_transforms_ks - c10::python_ks;
38
+ // We override a bunch of _custom(), so make sure they get called
39
+ // TODO: metadata copying may not actually be necessary then
40
+ set_custom_sizes_strides(SizesStridesPolicy::CustomSizes);
41
+ set_custom_device(true);
42
+ // E.g. when running torch.compile under inference mode, we need to make sure that
43
+ // for any inputs that were created outside of inference mode (so they are not inference tensors),
44
+ // then the functional wrappers that we wrap them with should also not be inference tensors.
45
+ version_counter_ = value_.unsafeGetTensorImpl()->version_counter();
46
+ }
47
+
48
+ FunctionalTensorWrapper::FunctionalTensorWrapper(const Tensor& value)
49
+ : c10::TensorImpl(
50
+ c10::Storage(c10::make_intrusive<functionalization::FunctionalStorageImpl>(value)),
51
+ c10::DispatchKeySet(DispatchKey::Functionalize) | value.key_set(),
52
+ value.dtype()
53
+ ),
54
+ value_(value)
55
+ {
56
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(value_));
57
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
58
+ set_constructor_metadata();
59
+ }
60
+
61
+ void FunctionalTensorWrapper::freeze_storage() const {
62
+ functional_storage_impl()->freeze();
63
+ }
64
+
65
+ // Note [Functionalization: Alias Removal]
66
+ // When someone calls a view() op during the functionalization pass, e.g. 'b = a.view(...)',
67
+ // we link `b` and `a` to a shared Alias object to preserve the aliasing relationship.
68
+ //
69
+ // How do we do that?
70
+ //
71
+ // Every FunctionalTensorWrapper contains a dummy FunctionalStorageImpl, which subclasses from c10::StorageImpl.
72
+ // It doesn't contain any data (similar to MetaTensor storage), but it contains an Alias object that knows about the base tensor.
73
+ // When a tensor is created through a view operation, both the new and old tensor point to the same FunctionalStorageImpl.
74
+ //
75
+ // As mutations are applied to any of the views, we also queue each mutation up on the Alias object, so we can replay them.
76
+ // When the user requests a tensor that's had a view taken, we check if it's up to date.
77
+ // If it's not up to date, we first replay all of the queued up mutations onto the alias, and then re-apply the current view
78
+ // on top of the newly updated alias.
79
+ //
80
+ // Why do we queue up and lazily run mutations on the alias, instead of updating the alias eagerly?
81
+ // This behavior was taken from pytorch/xla, which the alias-removal logic was inspired from.
82
+ // One benefit of the laziness is that we save work in the cases where a user has multiple views and mutates one of them,
83
+ // but never uses the other views later in the program (in which case we'll never update the alias).
84
+ // It also has downsides though: repeatedly applying mutations to the same view without syncing
85
+ // will silently use up more and more memory as more mutations are queued up.
86
+ //
87
+ // Corresponding diagram:
88
+ //
89
+ // b = a.view(...)
90
+ //
91
+ // a b
92
+ // | | If the user asks for b and it’s out of date,
93
+ // \/ \/ We regenerate b by replaying it’s views from the alias.
94
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - .
95
+ // | FunctionalTensorWrapper | | FunctionalTensorWrapper |
96
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - .
97
+ // | value | storage | | storage | Value |
98
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - .
99
+ // | \ / |
100
+ // | \ / |
101
+ // | . - - - - - - - - - - - - . |
102
+ // | | FunctionalStorageImpl | |
103
+ // | . - - - - - - - - - - - - . |
104
+ // | | Alias | |
105
+ // | . - - - - - - - - - - - - . |
106
+ // | / mutations to a or b |
107
+ // | / are queued onto Alias |
108
+ // | / |
109
+ // \/ / \/
110
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - .
111
+ // | TensorImpl | | TensorImpl |
112
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - .
113
+ // | value | storage | | storage | Value |
114
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - .
115
+ // | |
116
+ // | |
117
+ // | |
118
+ // | In this picture the two tensor views their own storages, |
119
+ // | have their own storages, but backends like functorch |
120
+ // \/ are allowed to re-alias underneath the pass \/
121
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - .
122
+ // | underlying_storage | | underlying_storage |
123
+ // . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - .
124
+ //
125
+ // This constructor is only used by view ops.
126
+ // - view_value: The output tensor that we need to wrap.
127
+ // - base: The "base" of the view that `view_value` was generated from.
128
+ // See Note [Functionalization: Alias Removal Part 2] for more details on the mutation replay logic.
129
+ FunctionalTensorWrapper::FunctionalTensorWrapper(
130
+ const Tensor& view_value,
131
+ const FunctionalTensorWrapper* base,
132
+ const std::shared_ptr<functionalization::ViewMeta>& meta)
133
+ : c10::TensorImpl(
134
+ c10::DispatchKeySet(DispatchKey::Functionalize),
135
+ view_value.dtype(),
136
+ base->storage().data_ptr().device()),
137
+ value_(view_value),
138
+ is_multi_output_view_(
139
+ base->is_multi_output_view_ || meta->is_multi_output),
140
+ was_storage_changed_(base->was_storage_changed_),
141
+ is_symbolic_(base->is_symbolic_) {
142
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(value_));
143
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
144
+ set_constructor_metadata();
145
+ // Copy the original tensor's ViewMeta vector and push the current one.
146
+ if (!base->view_metas_.empty()) {
147
+ view_metas_ = base->view_metas_; // copy
148
+ }
149
+ view_metas_.push_back(meta);
150
+ maybe_mark_symbolic(meta.get());
151
+ storage_ = base->storage_; // alias this tensor's storage with the base tensor's
152
+ }
153
+
154
+ functionalization::FunctionalStorageImpl* FunctionalTensorWrapper::functional_storage_impl() const {
155
+ return static_cast<functionalization::FunctionalStorageImpl*>(storage_.unsafeGetStorageImpl());
156
+ }
157
+
158
+ void FunctionalTensorWrapper::commit_update() {
159
+ auto storage_impl = functional_storage_impl();
160
+ storage_impl->add_update(value_, view_metas_);
161
+ // As an optimization, we used to mark the tensor here as "up-to-date",
162
+ // That way, code like:
163
+ // x = torch.ones(1'000'000)
164
+ // x[0].add_(1)
165
+ // doesn't result in an unnecessary materialization of the base.
166
+ // This optimization results in the slice temporarily haven't incorrect
167
+ // stride/storage_offset though, and DCE should handle that optimization anyway.
168
+ // generation_ = storage_impl->generation();
169
+ }
170
+
171
+ bool FunctionalTensorWrapper::is_up_to_date() const {
172
+ auto alias_generation = functional_storage_impl()->generation();
173
+ return generation_ == alias_generation;
174
+ }
175
+
176
+ // See Note [Functionalization Pass - Inplace View Ops]
177
+ void FunctionalTensorWrapper::mutate_view_meta(const std::shared_ptr<at::functionalization::ViewMeta>& meta) {
178
+ view_metas_.push_back(meta);
179
+ // Manually track the fact that this tensor received a metadata mutation!
180
+ has_metadata_mutation_ = true;
181
+ // Mark this tensor as being symbolic if there are any symbolic inputs used by the view operation.
182
+ maybe_mark_symbolic(meta.get());
183
+ // Note [Functionalization Pass - Inplace View Ops]
184
+ // So, these ops are special - they're mutation AND view ops. They get special codegen.
185
+ // An example is transpose_, e.g. `a.transpose_()`
186
+ // Calling transpose_() should ensure that a gets an alias, and append the new ViewMeta to a's current list of ViewMetas.
187
+ at::AutoDispatchSkipFunctionalize guard;
188
+ value_ = meta->forward(value_);
189
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
190
+ }
191
+
192
+ // Note [Functionalization: Mutation Removal]
193
+ // Mutation removal is used to take a program like this:
194
+ //
195
+ // a.add_(b)
196
+ //
197
+ // and replace it with a slightly different program that has the same semantics:
198
+ //
199
+ // tmp = a.add(b)
200
+ // a.replace_(tmp)
201
+ //
202
+ // Where the replace_() call is implemented directly in the functionalization pass, so it is transparent to the backend.
203
+ // This is useful for backends that aren't able to handle certain types of mutations, like functorch.
204
+ //
205
+ // Why do we need to wrap every tensor in a FunctionalTensorWrapper? Consider this program:
206
+ //
207
+ // Before:
208
+ // tensor.add_(batched_tensor)
209
+ //
210
+ // After:
211
+ // tmp = tensor.add(batched_tensor)
212
+ // tensor.replace_(tmp)
213
+ //
214
+ // In the above, tmp is a batched tensor (because adding a normal tensor to a batched tensor does broadcasting and creates a batched tensor).
215
+ // But we can't just replace the underlying memory backing `tensor` with `tmp` - a batched tensor takes up more space!
216
+ // Instead, every input, intermediate and output of the program is wrapped in a FunctionalTensorImpl, which wraps the underlying tensor.
217
+ void FunctionalTensorWrapper::replace_(const Tensor& other, bool from_lazy_regenerate) {
218
+ // TODO: going to need to change this if we want nested functionalize() transforms.
219
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(other));
220
+ value_ = other;
221
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
222
+ // out= ops are allowed to resize the output tensors, mutating both the data and metadata of the tensor.
223
+ // We need to propagate that metadata mutation to the wrapper (new size).
224
+ auto sizes_ = value_.sym_sizes();
225
+ auto strides_ = value_.sym_strides();
226
+ auto storage_offset_ = value_.sym_storage_offset();
227
+ set_sizes_and_strides(sizes_, strides_, storage_offset_);
228
+ if (dtype() != value_.unsafeGetTensorImpl()->dtype() || layout() != value_.unsafeGetTensorImpl()->layout()) {
229
+ // .to() should not re-entrantly go through functionalization.
230
+ at::AutoDispatchSkipFunctionalize guard;
231
+ // and we want _to_copy() to show up in the graph, not the composite .to() operator
232
+ // (this can happen if autograd has already run by the time we enter this code)
233
+ value_ = at::_to_copy(value_, c10::TensorOptions().dtype(dtype()).layout(layout()));
234
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
235
+ }
236
+ // might not be until after the no_grad region is exited.
237
+ // Therefore, replace_() is not unconditionally safe to check the current no_grad state.
238
+ // If this is a lazy regeneration, then it is guaranteed that we have already
239
+ // done the mutation for the storage alias (when we originally performed the mutation),
240
+ // so no counter update may be needed.
241
+ // Example: if a mutation happens to a view under a no_grad,
242
+ // we won't call replace_() on the other alias until the alias is later used, which
243
+ if (!from_lazy_regenerate) {
244
+ mark_mutation();
245
+ if (!at::GradMode::is_enabled() || InferenceMode::is_enabled()) {
246
+ // This mutation happened under no_grad or inference_mode
247
+ mark_mutation_during_no_grad_or_inference_mode();
248
+ }
249
+ }
250
+ }
251
+
252
+ bool FunctionalTensorWrapper::has_data_mutation() {
253
+ // Current tensor's data was mutated if its storage saw any mutations.
254
+ return functional_storage_impl()->generation() > 0;
255
+ }
256
+
257
+ void FunctionalTensorWrapper::set__impl(const FunctionalTensorWrapper* other) {
258
+ // self.set_(src) will cause self to have all of the tensor properties of self.
259
+ value_ = other->value_;
260
+ generation_ = other->generation_;
261
+ view_metas_ = other->view_metas_;
262
+ is_symbolic_ = other->is_symbolic_;
263
+ // FREEZE the old storage, preventing mutations to it.
264
+ // this is a huge pain to handle properly in all cases, so we ban it.
265
+ functional_storage_impl()->freeze();
266
+ // Unsafely swap out the storage with other's storage,
267
+ // disconnecting `self` with its view chain
268
+ storage_ = other->storage_;
269
+ /// explicitly mark the tensor as having its storage changed from set_()
270
+ // Otherwise, we don't actually have a 100% accurate way to check this.
271
+ // (We could check if the updated value has a new storage than the original value,
272
+ // but this won't also let us uniquely determine if the tensor **also**
273
+ // experienced a data mutation).
274
+ mark_storage_changed();
275
+
276
+ auto sizes_ = value_.sym_sizes();
277
+ auto strides_ = value_.sym_strides();
278
+ auto storage_offset_ = value_.sym_storage_offset();
279
+ set_sizes_and_strides(sizes_, strides_, storage_offset_);
280
+ }
281
+
282
+ void FunctionalTensorWrapper::storage_resize_(const c10::SymInt& new_size) {
283
+ auto curr_storage_size = value_.unsafeGetTensorImpl()->unsafe_storage().unsafeGetStorageImpl()->sym_nbytes();
284
+ // storage resizing is severely limited: we only support resizing either to zero, or from zero bytes.
285
+ TORCH_CHECK(new_size == 0 || curr_storage_size == 0, "new_size: ", new_size, ". curr_storage_size: ", curr_storage_size);
286
+ // The "functionalization rule" for storage resizing is a giant no-op, mainly because we don't want
287
+ // resize_() calls to actually emit any ops in the functional graph.
288
+ // How does it work?
289
+ // Resizing up (old size == 0):
290
+ // We do nothing in this case.
291
+ // The expectation is that for the user code to be valid, the next op that should run against the current tensor "x"
292
+ // will be a x.copy_(y) (or similar), that will fully overwrite the data of x.
293
+ // If there are any outstanding aliases of x, we expect them not to be used until after the copy_() call
294
+ // (otherwise the eager code would be invalid),
295
+ // and therefore functionalization will regenerate the aliases off of the result of `x.copy(y)`.
296
+ // Resizing down (new size == 0):
297
+ // We also do nothing in this case. The assumption is that after resizing a tensor down,
298
+ // it is fully unused in the program (unless it is later resized back up first, has data copied in)
299
+ // Although it might be saved for backward, which happens in FSDP.
300
+ // The expected pattern is that the param will then be resized back up from zero in the backward.
301
+
302
+ // Mark the tensor as having its storage resized.
303
+ // This is so we can detect it for inputs in AOTAutograd and error / emit
304
+ // an input mutation resize_() appropriately
305
+ functional_storage_impl()->mark_inductor_storage_resize(new_size);
306
+ }
307
+
308
+ void FunctionalTensorWrapper::maybe_replace_storage(const Tensor& other) {
309
+ // Note [resize_() in functionalization pass]
310
+ // resize_() is a special operator in functionalization because it can reallocate its underlying storage.
311
+ // This function is only ever called in the case that resize_() needs to reallocate its storage to a larger size.
312
+ //
313
+ // However, functionalization currently bans the following code:
314
+ // a = torch.ones(2)
315
+ // b = a.view(2)
316
+ // b.resize_(4) # b is a view tensor, that we are trying to increase the storage size of
317
+ //
318
+ // Why is this code difficult to handle?
319
+ // The functionalization pass currently keeps aliases in sync by making the following assumptions:
320
+ // - The “base” tensor always refers to “all of the data”
321
+ // - Whenever you have b = view_op(a), “b” should always refer to a subset of “a”s memory.
322
+ //
323
+ // The code above breaks that assumption b.resize_(4) actually needs to update "a"
324
+ // to tell it that it is now actually some slice of a pre-existing larger storage.
325
+ // We're also no longer re-generate "b" fully from "a" anymore, since "a" refers to a slice of "b"'s data.
326
+ //
327
+ // This is probably fixable in theory, but:
328
+ // - the fix would likely complicated the functionalization logic quite a bit.
329
+ // - the primary use case for resize_() today is resizing zero-sized tensors in out= variants of operators
330
+ // - resize_() also can give you weird results today if you try to resize_() a weirdly strided tensor.
331
+ //
332
+ // Given all of the above, for now we're just banning the above usage.
333
+ TORCH_CHECK(storage().use_count() == 1, "Attempted to resize a view tensor to a larger size. This is not allowed in the functionalization pass");
334
+ TORCH_CHECK(view_metas_.empty(), "Attempted to resize a view tensor to a larger size. This is not allowed in the functionalization pass");
335
+ // If this tensor is not a view (and has no outstanding views taken out on it),
336
+ // Then it's safe to throw out the old storage and replace it with the new, larger one.
337
+ storage_ = c10::Storage(c10::make_intrusive<functionalization::FunctionalStorageImpl>(other));
338
+ value_ = other;
339
+ TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize));
340
+ generation_ = 0;
341
+ // And update the metadata on the wrapper to reflect the new sizes and strides
342
+ set_sizes_and_strides(value_.sizes(), value_.strides());
343
+ refresh_numel();
344
+ // (Technically we should be guaranteed that the tensor was already contiguous,
345
+ // since it's guaranteed not to have been a view. Doesn't hurt to run though)
346
+ refresh_contiguous();
347
+ // Swapping out the storage of a tensor (aka from a resize_() call) will update the sizes and strides of the tensor,
348
+ // so we need to record the fact that metadata was mutated.
349
+ has_metadata_mutation_ = true;
350
+ }
351
+
352
+ void FunctionalTensorWrapper::_unsafe_reset_storage() {
353
+ // Reset the storage with the current value_ tensor as the base
354
+ storage_ = c10::Storage(c10::make_intrusive<functionalization::FunctionalStorageImpl>(value_));
355
+ // Reset the generation so that it matches the new storage
356
+ generation_ = 0;
357
+ // Clear any pre-existing view metas so that base and value_ are semantically the same
358
+ view_metas_.clear();
359
+ }
360
+
361
+ void FunctionalTensorWrapper::sync_() {
362
+ if (is_up_to_date()) {
363
+ return;
364
+ }
365
+ apply_updates();
366
+ regenerate_from_base();
367
+ }
368
+
369
+ const std::vector<std::shared_ptr<functionalization::ViewMeta>>& FunctionalTensorWrapper::view_metas() const {
370
+ return view_metas_;
371
+ }
372
+
373
+ void FunctionalTensorWrapper::regenerate_from_base() {
374
+ at::AutoDispatchSkipFunctionalize guard;
375
+ auto storage_impl = functional_storage_impl();
376
+ auto t = storage_impl->base();
377
+
378
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t));
379
+ t = at::functionalization::impl::apply_view_meta_sequence(t, view_metas_);
380
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t));
381
+
382
+ replace_(t, /*from_lazy_regenerate=*/true);
383
+ generation_ = storage_impl->generation();
384
+ }
385
+
386
+ bool FunctionalTensorWrapper::apply_updates() {
387
+ // Apply all updates on alias_
388
+ auto storage_impl = functional_storage_impl();
389
+ return storage_impl->apply_updates();
390
+ }
391
+
392
+ const char* FunctionalTensorWrapper::tensorimpl_type_name() const {
393
+ return "FunctionalTensorWrapper";
394
+ }
395
+
396
+ void FunctionalTensorWrapper::copy_tensor_metadata(
397
+ const FunctionalTensorWrapper* src_impl,
398
+ FunctionalTensorWrapper* dest_impl,
399
+ const c10::VariableVersion& version_counter,
400
+ bool allow_tensor_metadata_change) {
401
+ TensorImpl::copy_tensor_metadata(
402
+ src_impl,
403
+ dest_impl,
404
+ version_counter,
405
+ allow_tensor_metadata_change);
406
+
407
+ // FunctionalTensorWrapper-specific fields.
408
+ dest_impl->value_ = src_impl->value_;
409
+ dest_impl->level_ = src_impl->level_;
410
+ dest_impl->has_metadata_mutation_ = src_impl->has_metadata_mutation_;
411
+ dest_impl->is_multi_output_view_ = src_impl->is_multi_output_view_;
412
+ dest_impl->was_storage_changed_ = src_impl->was_storage_changed_;
413
+ dest_impl->is_symbolic_ = src_impl->is_symbolic_;
414
+ dest_impl->generation_ = src_impl->generation_;
415
+ dest_impl->view_metas_ = src_impl->view_metas_;
416
+ }
417
+
418
+
419
+ void FunctionalTensorWrapper::copy_tensor_metadata_and_refresh(
420
+ const FunctionalTensorWrapper* src_impl,
421
+ FunctionalTensorWrapper* dest_impl,
422
+ const c10::VariableVersion& version_counter,
423
+ bool allow_tensor_metadata_change) const {
424
+ copy_tensor_metadata(src_impl, dest_impl, version_counter, allow_tensor_metadata_change);
425
+ dest_impl->refresh_numel();
426
+ dest_impl->refresh_contiguous();
427
+ }
428
+
429
+ template <typename VariableVersion>
430
+ c10::intrusive_ptr<TensorImpl> FunctionalTensorWrapper::shallow_copy_and_detach_core(
431
+ VariableVersion&& version_counter,
432
+ bool allow_tensor_metadata_change) const {
433
+ if (key_set_.has(DispatchKey::Python) &&
434
+ !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) {
435
+ auto r = (*c10::impl::getGlobalPyInterpreter())->detach(this);
436
+ if (r) {
437
+ r->set_version_counter(std::forward<VariableVersion>(version_counter));
438
+ r->set_allow_tensor_metadata_change(allow_tensor_metadata_change);
439
+ return r;
440
+ }
441
+ }
442
+
443
+ auto impl = c10::make_intrusive<FunctionalTensorWrapper>(value_);
444
+ copy_tensor_metadata_and_refresh(
445
+ /*src_impl=*/this,
446
+ /*dest_impl=*/impl.get(),
447
+ /*version_counter=*/std::forward<VariableVersion>(version_counter),
448
+ /*allow_tensor_metadata_change=*/allow_tensor_metadata_change);
449
+ return impl;
450
+ }
451
+
452
+ c10::intrusive_ptr<TensorImpl> FunctionalTensorWrapper::shallow_copy_and_detach(
453
+ const c10::VariableVersion& version_counter,
454
+ bool allow_tensor_metadata_change) const {
455
+ return shallow_copy_and_detach_core(
456
+ version_counter, allow_tensor_metadata_change);
457
+ }
458
+
459
+ c10::intrusive_ptr<TensorImpl> FunctionalTensorWrapper::shallow_copy_and_detach(
460
+ c10::VariableVersion&& version_counter,
461
+ bool allow_tensor_metadata_change) const {
462
+ return shallow_copy_and_detach_core(
463
+ std::move(version_counter), allow_tensor_metadata_change);
464
+ }
465
+
466
+ void FunctionalTensorWrapper::shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) {
467
+ AT_ASSERT(has_compatible_shallow_copy_type(impl->key_set()));
468
+ auto functional_impl =
469
+ static_cast<FunctionalTensorWrapper*>(impl.get());
470
+ copy_tensor_metadata_and_refresh(
471
+ /*src_impl=*/functional_impl,
472
+ /*dest_impl=*/this,
473
+ /*version_counter=*/version_counter(),
474
+ /*allow_tensor_metadata_change=*/allow_tensor_metadata_change());
475
+ }
476
+
477
+
478
+ c10::Device FunctionalTensorWrapper::device_custom() const {
479
+ // The storage pointer already uses the underlying tensor custom device (if
480
+ // applicable) to extract the device. So, we dont have to recurse again by
481
+ // doing value_.unsafeGetTensorImpl()->device().
482
+ return storage().data_ptr().device();
483
+ }
484
+ at::IntArrayRef FunctionalTensorWrapper::sizes_custom() const {
485
+ return value_.unsafeGetTensorImpl()->sizes();
486
+ }
487
+ at::IntArrayRef FunctionalTensorWrapper::strides_custom() const {
488
+ return value_.unsafeGetTensorImpl()->strides();
489
+ }
490
+ int64_t FunctionalTensorWrapper::dim_custom() const {
491
+ return value_.unsafeGetTensorImpl()->dim();
492
+ }
493
+ int64_t FunctionalTensorWrapper::numel_custom() const {
494
+ return value_.unsafeGetTensorImpl()->numel();
495
+ }
496
+ c10::SymBool FunctionalTensorWrapper::sym_is_contiguous_custom(at::MemoryFormat memory_format) const {
497
+ return value_.unsafeGetTensorImpl()->sym_is_contiguous(memory_format);
498
+ }
499
+ c10::SymIntArrayRef FunctionalTensorWrapper::sym_sizes_custom() const {
500
+ return value_.unsafeGetTensorImpl()->sym_sizes();
501
+ }
502
+ c10::SymIntArrayRef FunctionalTensorWrapper::sym_strides_custom() const {
503
+ return value_.unsafeGetTensorImpl()->sym_strides();
504
+ }
505
+ c10::SymInt FunctionalTensorWrapper::sym_size_custom(int64_t d) const {
506
+ return value_.unsafeGetTensorImpl()->sym_size(d);
507
+ }
508
+ c10::SymInt FunctionalTensorWrapper::sym_storage_offset_custom() const {
509
+ return value_.unsafeGetTensorImpl()->sym_storage_offset();
510
+ }
511
+ c10::Layout FunctionalTensorWrapper::layout_impl() const {
512
+ return value_.unsafeGetTensorImpl()->layout();
513
+ }
514
+
515
+ namespace functionalization {
516
+ namespace impl {
517
+
518
+ Tensor to_functional_tensor(const Tensor& tensor) {
519
+ // Note [Wrapped Numbers <> Functionalization]
520
+ if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) {
521
+ return tensor;
522
+ }
523
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!isFunctionalTensor(tensor));
524
+ return at::detail::make_tensor<FunctionalTensorWrapper>(tensor);
525
+ }
526
+ std::optional<Tensor> to_functional_tensor(const std::optional<Tensor>& tensor) {
527
+ if (tensor.has_value()) {
528
+ return to_functional_tensor(*tensor);
529
+ }
530
+ return std::nullopt;
531
+ }
532
+ c10::List<::std::optional<Tensor>> to_functional_tensor(const c10::List<::std::optional<Tensor>>& t_list) {
533
+ c10::List<::std::optional<Tensor>> outputs;
534
+ outputs.reserve(t_list.size());
535
+ for (const auto i : c10::irange(t_list.size())) {
536
+ outputs.push_back(to_functional_tensor(t_list[i]));
537
+ }
538
+ return outputs;
539
+ }
540
+ std::vector<Tensor> to_functional_tensor(ITensorListRef t_list) {
541
+ std::vector<Tensor> outputs;
542
+ outputs.reserve(t_list.size());
543
+ for (const auto& tensor : t_list) {
544
+ outputs.push_back(to_functional_tensor(tensor));
545
+ }
546
+ return outputs;
547
+ }
548
+
549
+ Tensor from_functional_tensor(const Tensor& tensor, bool assert_functional) {
550
+ // Note [Wrapped Numbers <> Functionalization]
551
+ if (!tensor.defined() || tensor.unsafeGetTensorImpl()->is_wrapped_number()) {
552
+ return tensor;
553
+ }
554
+ if (isFunctionalTensor(tensor)) {
555
+ auto impl = unsafeGetFunctionalWrapper(tensor);
556
+ return impl->value();
557
+ } else {
558
+ // If the current tensor is not functional, then raise an error
559
+ // if assert_functional is true. Otherwise, return the input.
560
+ TORCH_INTERNAL_ASSERT(!assert_functional)
561
+ return tensor;
562
+ }
563
+ }
564
+ std::optional<Tensor> from_functional_tensor(const std::optional<Tensor>& t, bool assert_functional) {
565
+ if (t.has_value()) {
566
+ return from_functional_tensor(*t, assert_functional);
567
+ }
568
+ return std::nullopt;
569
+ }
570
+ std::vector<Tensor> from_functional_tensor(ITensorListRef t_list) {
571
+ std::vector<Tensor> outputs;
572
+ outputs.reserve(t_list.size());
573
+ for (const auto& tensor : t_list) {
574
+ // from_functional_tensor(Tensor) has asserts to make sure you don't accidentally call
575
+ // it on a non-functional input,
576
+ // but from_functional_tensor(TensorList) can receive a list containing both
577
+ // functional and non-functional tensors.
578
+ // Example of when that can happen: torch.cat(function_input_tensor, global_state_tensor).
579
+ // When that happens, we're okay with only unwrapping the functional tensors.
580
+ outputs.push_back(from_functional_tensor(tensor, /*assert_functional=*/false));
581
+ }
582
+ return outputs;
583
+ }
584
+ c10::List<::std::optional<Tensor>> from_functional_tensor(const c10::List<::std::optional<Tensor>>& t_list) {
585
+ c10::List<::std::optional<Tensor>> outputs;
586
+ outputs.reserve(t_list.size());
587
+ for (const auto i : c10::irange(t_list.size())) {
588
+ outputs.push_back(from_functional_tensor(t_list[i], /*assert_functional=*/false));
589
+ }
590
+ return outputs;
591
+ }
592
+
593
+ void sync(const Tensor& t) {
594
+ if (t.unsafeGetTensorImpl()->is_wrapped_number()) {
595
+ // Note [Wrapped Numbers <> Functionalization]
596
+ // Unfortunately, we can't easily guarantee that wrapped numbers (scalar-tensors)
597
+ // get wrapped up in a FunctionalTensorWrapper object, since they skip the dispatcher.
598
+ // That shouldn't matter, since I don't think we're allowed to assign to wrapped numbers anyway.
599
+ return;
600
+ }
601
+ // Not every tensor that hits a functionalization kernel is necessarily a functional tensor.
602
+ // For example, xla_tensor.copy_(cpu_tensor) needs to hit the functionalization kernel
603
+ // to sync xla_tensor, but not cpu_tensor.
604
+ if (!at::functionalization::impl::isFunctionalTensor(t)) {
605
+ return;
606
+ }
607
+ auto functional_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(t);
608
+ functional_impl->sync_();
609
+ }
610
+ void sync(const std::optional<Tensor>& t) {
611
+ if (t.has_value()) {
612
+ sync(*t);
613
+ }
614
+ }
615
+ void sync(ITensorListRef t_list) {
616
+ for (const auto& t : t_list) {
617
+ sync(t);
618
+ }
619
+ }
620
+ void sync(const c10::List<::std::optional<Tensor>>& t_list) {
621
+ for (const auto i : c10::irange(t_list.size())) {
622
+ sync(t_list[i]);
623
+ }
624
+ }
625
+
626
+ void replace_(const Tensor& functional_tensor, const Tensor& other) {
627
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor));
628
+ unsafeGetFunctionalWrapper(functional_tensor)->replace_(other);
629
+ }
630
+
631
+ void replace_(const ITensorListRef functional_tensor, ITensorListRef other) {
632
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_tensor.size() == other.size());
633
+ auto functional_tensor_it = functional_tensor.begin();
634
+ auto other_it = other.begin();
635
+ for ([[maybe_unused]] const auto i : c10::irange(functional_tensor.size())) {
636
+ replace_(*functional_tensor_it++, *other_it++);
637
+ }
638
+ }
639
+
640
+ void propagate_xla_data(const Tensor& functional_tensor, const Tensor& other) {
641
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor));
642
+ if (functional_tensor.key_set().has(c10::DispatchKey::XLA)) {
643
+ at::_propagate_xla_data(at::functionalization::impl::unsafeGetFunctionalWrapper(functional_tensor)
644
+ ->value(), other);
645
+ }
646
+ }
647
+
648
+ void propagate_xla_data(const ITensorListRef functional_tensor, ITensorListRef other) {
649
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_tensor.size() == other.size());
650
+ auto functional_tensor_it = functional_tensor.begin();
651
+ auto other_it = other.begin();
652
+ for ([[maybe_unused]] const auto i : c10::irange(functional_tensor.size())) {
653
+ propagate_xla_data(*functional_tensor_it++, *other_it++);
654
+ }
655
+ }
656
+
657
+ void propagate_xla_data_direct(const Tensor& tensor, const Tensor& other) {
658
+ if (tensor.key_set().has(c10::DispatchKey::XLA)) {
659
+ at::_propagate_xla_data(tensor, other);
660
+ }
661
+ }
662
+
663
+ void propagate_xla_data_direct(const ITensorListRef tensor,
664
+ ITensorListRef other) {
665
+ auto tensor_it = tensor.begin();
666
+ auto other_it = other.begin();
667
+ for ([[maybe_unused]] const auto i : c10::irange(tensor.size())) {
668
+ propagate_xla_data_direct(*tensor_it++, *other_it++);
669
+ }
670
+ }
671
+
672
+ void commit_update(const Tensor& functional_tensor) {
673
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor));
674
+ unsafeGetFunctionalWrapper(functional_tensor)->commit_update();
675
+ }
676
+
677
+ void commit_update(ITensorListRef functional_tensor) {
678
+ for (const auto& t : functional_tensor) {
679
+ commit_update(t);
680
+ }
681
+ }
682
+
683
+ void unsafe_reset_storage(const Tensor& functional_tensor) {
684
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor));
685
+ unsafeGetFunctionalWrapper(functional_tensor)->_unsafe_reset_storage();
686
+ }
687
+
688
+ void mark_mutation_hidden_from_autograd(const Tensor& functional_tensor) {
689
+ TORCH_CHECK(isFunctionalTensor(functional_tensor));
690
+ unsafeGetFunctionalWrapper(functional_tensor)->mark_mutation_hidden_from_autograd();
691
+ }
692
+
693
+ bool are_all_mutations_hidden_from_autograd(const Tensor& functional_tensor) {
694
+ TORCH_CHECK(isFunctionalTensor(functional_tensor));
695
+ return unsafeGetFunctionalWrapper(functional_tensor)->are_all_mutations_hidden_from_autograd();
696
+ }
697
+
698
+ bool are_all_mutations_under_no_grad_or_inference_mode(const Tensor& functional_tensor) {
699
+ TORCH_CHECK(isFunctionalTensor(functional_tensor));
700
+ return unsafeGetFunctionalWrapper(functional_tensor)->are_all_mutations_under_no_grad_or_inference_mode();
701
+ }
702
+
703
+ bool isFunctionalTensor(const at::Tensor& tensor) {
704
+ return tensor.unsafeGetTensorImpl()->key_set().has(c10::DispatchKey::Functionalize);
705
+ }
706
+
707
+ bool isBaseTensor(const at::Tensor& tensor) {
708
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(tensor));
709
+ return unsafeGetFunctionalWrapper(tensor)->isBaseTensor();
710
+ }
711
+
712
+ bool isFunctionalTensor(const std::optional<Tensor>& t) {
713
+ if (t.has_value()) {
714
+ return isFunctionalTensor(*t);
715
+ } else {
716
+ return false;
717
+ }
718
+ }
719
+
720
+ bool isFunctionalTensor(const c10::List<::std::optional<Tensor>>& t_list) {
721
+ if (t_list.empty()) { return false; }
722
+ auto functional_count = 0;
723
+ for (const auto i : c10::irange(t_list.size())) {
724
+ auto const & e= t_list[i];
725
+ if (!e.has_value() || !e->defined()) { continue; }
726
+ if (isFunctionalTensor(e)) {
727
+ ++functional_count;
728
+ }
729
+ }
730
+ return functional_count > 0;
731
+ }
732
+
733
+ template <typename T>
734
+ static bool isFunctionalTensorIListRef(c10::IListRef<T> list) {
735
+ if (list.size() == 0) { return false; }
736
+ auto functional_count = 0;
737
+ for (const auto& tensor : list) {
738
+ if (!tensor.defined()) { continue; }
739
+ if (isFunctionalTensor(tensor)) {
740
+ ++functional_count;
741
+ }
742
+ }
743
+ return functional_count > 0;
744
+ }
745
+
746
+ bool isFunctionalTensor(ITensorListRef list) {
747
+ return isFunctionalTensorIListRef(list);
748
+ }
749
+
750
+ void freeze_functional_tensor(const Tensor& tensor) {
751
+ TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(tensor));
752
+ auto functional_base_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(tensor);
753
+ functional_base_impl->freeze_storage();
754
+ }
755
+
756
+ Tensor create_functional_tensor_with_view_meta(
757
+ const at::Tensor& view_to_wrap,
758
+ const at::Tensor& base,
759
+ const std::shared_ptr<functionalization::ViewMeta>& meta,
760
+ int64_t out_idx) {
761
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(view_to_wrap));
762
+ TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(base));
763
+ auto functional_base_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(base);
764
+ auto meta_ = meta;
765
+ if (out_idx != 0) {
766
+ // Note [out_idx in ViewMeta]
767
+ // When a view op outputs multiple tensors, each output needs its own separate ViewMeta.
768
+ // Each ViewMeta also tracks the index of the particular output tensor, which is needed in the reverse function.
769
+ meta_ = meta->to_out_index(out_idx);
770
+ }
771
+ return at::detail::make_tensor<FunctionalTensorWrapper>(view_to_wrap, functional_base_impl, meta_);
772
+ }
773
+
774
+ std::vector<Tensor> create_functional_tensor_with_view_meta(
775
+ ITensorListRef view_to_wrap,
776
+ const at::Tensor& base,
777
+ const std::shared_ptr<functionalization::ViewMeta>& meta) {
778
+ std::vector<Tensor> outputs(view_to_wrap.size());
779
+ int64_t i = 0;
780
+ for (const auto& tensor : view_to_wrap) {
781
+ outputs[i] = create_functional_tensor_with_view_meta(tensor, base, meta, i);
782
+ i++;
783
+ }
784
+ return outputs;
785
+ }
786
+
787
+ void mutate_view_meta(const at::Tensor& self, const std::shared_ptr<functionalization::ViewMeta>& meta) {
788
+ TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(self));
789
+ auto self_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self);
790
+ self_impl->mutate_view_meta(meta);
791
+ }
792
+
793
+ Tensor apply_view_meta_sequence(
794
+ const Tensor& base,
795
+ const std::vector<std::shared_ptr<functionalization::ViewMeta>>& sequence) {
796
+ Tensor r = base;
797
+ for (auto& vm : sequence) {
798
+ r = vm->forward(r);
799
+ }
800
+ return r;
801
+ }
802
+
803
+ // Note [Propagating strides in the functionalization pass]
804
+ // In order to properly compute stride information, the functionalization pass
805
+ // calls each {view} reference implementations with meta tensors.
806
+ // The output meta tensor's stride info serves as a reference for what the correct strides should be.
807
+ void set_sizes_strides_offset(const Tensor& out, const Tensor& reference_out) {
808
+ out.unsafeGetTensorImpl()->set_sizes_and_strides(reference_out.sym_sizes(), reference_out.sym_strides(), reference_out.sym_storage_offset());
809
+ }
810
+
811
+ void set_sizes_strides_offset(const std::vector<Tensor>& outs, const std::vector<Tensor>& reference_outs) {
812
+ TORCH_INTERNAL_ASSERT(outs.size() == reference_outs.size());
813
+ for (const auto i : c10::irange(reference_outs.size())) {
814
+ set_sizes_strides_offset(outs[i], reference_outs[i]);
815
+ }
816
+ }
817
+
818
+ thread_local static bool _functionalizationReapplyViews;
819
+
820
+ bool getFunctionalizationReapplyViewsTLS() {
821
+ return _functionalizationReapplyViews;
822
+ }
823
+ void setFunctionalizationReapplyViewsTLS(bool reapply_views) {
824
+ _functionalizationReapplyViews = reapply_views;
825
+ }
826
+
827
+ } // namespace impl
828
+
829
+
830
+ // Given an **out-of-place** op that might internally call view/inplace ops,
831
+ // This function will "functionalize" it.
832
+ // That is, it will call the operator, but removing any intermediate views/mutations
833
+ // that are performed inside of it.
834
+ // This is useful for LTC/XLA, which would like to reuse some of our composite kernels
835
+ // from pytorch core but not have to worry about the view ops that they might call.
836
+ // e.g. at::block_diag
837
+ void functionalize_op_helper(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
838
+ const auto& schema = op.schema();
839
+ const auto num_arguments = schema.arguments().size();
840
+ const auto arguments_begin = stack->size() - num_arguments;
841
+ auto arguments = torch::jit::last(stack, num_arguments);
842
+
843
+ // Wrap all tensor-like inputs into FunctionalTensorWrappers.
844
+ // When we re-invoke the dispatcher, this will automatically enable the functionalization pass.
845
+ for (uint64_t idx = 0; idx < num_arguments; ++idx) {
846
+ const auto& ivalue = arguments[idx];
847
+ if (ivalue.isTensor()) {
848
+ const auto& t = ivalue.toTensor();
849
+ if (t.defined()) {
850
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t),
851
+ "The composite op functionalization fallback expects its inputs all not to be functional tensors");
852
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(t));
853
+ (*stack)[arguments_begin + idx] = t_new;
854
+ }
855
+ } else if (ivalue.isTensorList()) {
856
+ auto tensors = ivalue.toTensorList();
857
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(tensors),
858
+ "The composite op functionalization fallback expects its inputs all not to be functional tensors");
859
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(tensors));
860
+ (*stack)[arguments_begin + idx] = t_new;
861
+ } else if (ivalue.isOptionalTensorList()) {
862
+ auto opt_tensors = ivalue.toOptionalTensorList();
863
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(opt_tensors),
864
+ "The composite op functionalization fallback expects its inputs all not to be functional tensors");
865
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(opt_tensors));
866
+ (*stack)[arguments_begin + idx] = t_new;
867
+ } else if (ivalue.isList()) {
868
+ // Handle nested lists containing tensor lists (e.g., Tensor[][]).
869
+ auto list = ivalue.toList();
870
+ for (const auto i : c10::irange(list.size())) {
871
+ const auto& elem = list.get(i);
872
+ if (elem.isTensorList()) {
873
+ auto tensors = elem.toTensorList();
874
+ TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(tensors),
875
+ "The composite op functionalization fallback expects its inputs all not to be functional tensors");
876
+ list.set(i, c10::IValue(at::functionalization::impl::to_functional_tensor(tensors)));
877
+ }
878
+ }
879
+ }
880
+ }
881
+
882
+ {
883
+ // Today when you call at::empty(device=lazy), the lazy backend decides whether or not to wrap
884
+ // the output in a functional tensor based on TLS.
885
+ // In this code, we're re-entrantly entering functionalization in the same call-stack,
886
+ // so we need to manually fix up TLS as if it hadn't already been called.
887
+ auto curr_tls = c10::impl::tls_local_dispatch_key_set();
888
+ auto tls_reenable_functionalize = c10::impl::PODLocalDispatchKeySet();
889
+ tls_reenable_functionalize.set_included(curr_tls.included_);
890
+ tls_reenable_functionalize.set_excluded(curr_tls.excluded_.remove(c10::DispatchKey::Functionalize));
891
+ c10::impl::ForceDispatchKeyGuard guard_(tls_reenable_functionalize);
892
+ // So, we should probably provide a way to directly call a kernel registered to
893
+ // the `CompositeExplicitAutograd` key.
894
+ // We can't do that today, so this should be a reasonably good proxy
895
+ // (It won't work in cases where an op has both a CompositeExplicitAutograd kernel
896
+ // AND a dedicated meta kernel, but that probably shouldn't ever happen).
897
+ op.redispatchBoxed(c10::DispatchKeySet(c10::DispatchKey::Meta), stack);
898
+ }
899
+
900
+ const auto num_returns = schema.returns().size();
901
+ const auto returns_begin = stack->size() - num_returns;
902
+ auto returns = torch::jit::last(stack, num_returns);
903
+
904
+ for (const auto idx : c10::irange(num_returns)) {
905
+ const auto& ivalue = returns[idx];
906
+ if (ivalue.isTensor()) {
907
+ const auto& t = ivalue.toTensor();
908
+ if (!t.defined()) { continue; }
909
+ at::functionalization::impl::sync(t);
910
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(t));
911
+ (*stack)[returns_begin + idx] = t_new;
912
+ } else if (ivalue.isTensorList()) {
913
+ auto tensors = ivalue.toTensorList();
914
+ at::functionalization::impl::sync(tensors);
915
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(tensors));
916
+ (*stack)[returns_begin + idx] = t_new;
917
+ } else if (ivalue.isOptionalTensorList()) {
918
+ auto opt_tensors = ivalue.toOptionalTensorList();
919
+ at::functionalization::impl::sync(opt_tensors);
920
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(opt_tensors));
921
+ (*stack)[returns_begin + idx] = t_new;
922
+ } else if (ivalue.isList()) {
923
+ // Handle nested lists containing tensor lists (e.g., Tensor[][]).
924
+ auto list = ivalue.toList();
925
+ for (const auto i : c10::irange(list.size())) {
926
+ const auto& elem = list.get(i);
927
+ if (elem.isTensorList()) {
928
+ auto tensors = elem.toTensorList();
929
+ at::functionalization::impl::sync(tensors);
930
+ list.set(i, c10::IValue(at::functionalization::impl::from_functional_tensor(tensors)));
931
+ }
932
+ }
933
+ }
934
+ }
935
+ }
936
+
937
+
938
+
939
+ } // namespace functionalization
940
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.h ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #pragma once
3
+
4
+ #include <ATen/ArrayRef.h>
5
+ #include <ATen/FunctionalStorageImpl.h>
6
+ #include <ATen/core/IListRef.h>
7
+ #include <ATen/core/List.h>
8
+ #include <ATen/core/boxing/BoxedKernel.h>
9
+ #include <ATen/core/boxing/impl/boxing.h>
10
+ #include <ATen/core/dispatch/Dispatcher.h>
11
+
12
+ #include <c10/core/DispatchKey.h>
13
+
14
+ namespace at {
15
+
16
+ // Note [Functionalization Pass In Core]
17
+ // The Functionalization pass is used to remove aliasing from a pytorch program.
18
+ //
19
+ // This is useful for backends that don't support aliasing, like XLA and Vulkan.
20
+ // It's also necessary in order to remove mutation from a program, which is
21
+ // needed in Functorch.
22
+ //
23
+ // Consider this program:
24
+ // a = torch.ones(...)
25
+ // b = a.view(...)
26
+ // b.add_(1)
27
+ //
28
+ // In this program, b is meant to alias with a due to the use of view(). At the
29
+ // end of the program, both a and b are full of 2's. However, backends that
30
+ // don't support aliasing aren't able to correctly implement the view()
31
+ // operator. Instead, they can opt into the Functionalization pass, which will
32
+ // sit between the user and the backend, and provide the necessary aliasing
33
+ // logic.
34
+ //
35
+ // The functionalization pass will turn the above program into a slightly
36
+ // different program that has the same semantics, transparently to the user,
37
+ // that backends like XLA/Vulkan are able to implement a = torch.ones(...) b =
38
+ // a.view_copy(...) # view() replaced with view_copy(). Backends like
39
+ // XLA/Vulkan can implement this! b.add_(1) a.add_(1) # Our functionalization
40
+ // pass machinery knows that a and b are aliased - it applies b's mutation to a
41
+ // too.
42
+ //
43
+ // So, how does the functionalization pass keep track of which tensors are
44
+ // aliased? The pass works by wrapping EVERY tensor in the program inside of a
45
+ // FunctionalTensorWrapper, which knows about its alias'd tensors.
46
+ //
47
+ // See Note [Functionalization: Alias Removal] for details on the aliasing
48
+ // machinery. See Note [Functionalization: Mutation Removal] for details on
49
+ // mutation removal.
50
+ struct TORCH_API FunctionalTensorWrapper : public c10::TensorImpl {
51
+ explicit FunctionalTensorWrapper(const Tensor& value);
52
+ // Additional constructor to create a FunctionalTensorWrapper directly from an
53
+ // underlying tensor that was created from a view. For example, the code b =
54
+ // a.view1() will generate a constructor call to FunctionalTensorWrapper(b, a,
55
+ // view1_meta)
56
+ explicit FunctionalTensorWrapper(
57
+ const Tensor& view_value,
58
+ const FunctionalTensorWrapper* base,
59
+ const std::shared_ptr<functionalization::ViewMeta>& meta);
60
+
61
+ // Get the underlying, actual tensor, that doesn't know anything about
62
+ // functionalization.
63
+ const Tensor& value() const {
64
+ return value_;
65
+ }
66
+ // The concept of "level" is only ever important to functorch; it's exposed
67
+ // here as more of a hook for functorch to use.
68
+ int64_t level() const {
69
+ return level_;
70
+ }
71
+ void set_level(int64_t level) {
72
+ level_ = level;
73
+ }
74
+ bool has_metadata_mutation() const {
75
+ return has_metadata_mutation_;
76
+ }
77
+ uint64_t mutation_counter() const {
78
+ return functional_storage_impl()->mutation_counter();
79
+ }
80
+ void mark_mutation() {
81
+ functional_storage_impl()->mark_mutation();
82
+ }
83
+ // Denotes a mutation that's hidden from autograd,
84
+ // e.g. for the purposes of passing a tensor to a triton kernel
85
+ void mark_mutation_hidden_from_autograd() {
86
+ functional_storage_impl()->mark_mutation_hidden_from_autograd();
87
+ }
88
+ void mark_mutation_during_no_grad_or_inference_mode() {
89
+ functional_storage_impl()->mark_mutation_during_no_grad_or_inference_mode();
90
+ }
91
+ // Are all the mutations happening to the tensor hidden from autograd
92
+ bool are_all_mutations_hidden_from_autograd() const {
93
+ return functional_storage_impl()->are_all_mutations_hidden_from_autograd();
94
+ }
95
+ // Did all mutations happen under no_grad or inference_mode
96
+ // (We also need to ignore mutations fully hidden from autograd here)
97
+ bool are_all_mutations_under_no_grad_or_inference_mode() const {
98
+ return functional_storage_impl()
99
+ ->are_all_mutations_under_no_grad_or_inference_mode();
100
+ }
101
+
102
+ void maybe_mark_symbolic(functionalization::ViewMeta* meta) {
103
+ is_symbolic_ = is_symbolic_ | meta->has_symbolic_inputs;
104
+ }
105
+
106
+ bool is_symbolic() const {
107
+ return is_symbolic_;
108
+ }
109
+
110
+ // Retrieves the ViewMeta sequence of this tensor.
111
+ const std::vector<std::shared_ptr<functionalization::ViewMeta>>& view_metas()
112
+ const;
113
+
114
+ // Sync's the underlying tensor with its alias, if it's out of date. This
115
+ // involves two steps: 1) Apply any pending updates/mutations to the alias 2)
116
+ // Replay the views (if any) to regenerate the current tensor off of the
117
+ // updated alias.
118
+ void sync_();
119
+ // Performs step (1) of the sync. This is its own public API because it's
120
+ // needed by view_inplace ops like transpose_. See Note [Functionalization
121
+ // Pass - Inplace View Ops]
122
+ void regenerate_from_base();
123
+ // Performs step (2) of the sync. This is its own public API because it's
124
+ // needed by functorch. functorch wants to make sure that all input tensors to
125
+ // a functionalized program have been properly synced so it can properly
126
+ // propagate mutations to inputs. It can't just call sync_(), because the
127
+ // FunctionalTensorWrapper will look like it has no aliases and sync_ will be
128
+ // a noop. We use the reference count on storage_ to determine if the wrapper
129
+ // is aliased, and by the time functorch is ready to propagate updates to
130
+ // inputs, any intermediate views of the input created by the program will
131
+ // have been deallocated. This function also returns whether or not the base
132
+ // actually had any updates to apply.
133
+ bool apply_updates();
134
+ // Takes the current state of value_ and snapshots it, sending it as a pending
135
+ // update to the alias.
136
+ void commit_update();
137
+ // When any tensor is mutated, the tensor increments its alias's "generation".
138
+ // Separately, each tensor maintains its own "generation" counter, which is
139
+ // used to determine if it's up-to-date with its alias. The act of syncing a
140
+ // tensor will set a tensor's generation equal to its alias's generation.
141
+ bool is_up_to_date() const;
142
+ // Freezes the storage of this tensor, preventing subsequent mutations
143
+ void freeze_storage() const;
144
+ // Every FunctionalTensorWrapper contains a vector<ViewMeta> objects
145
+ // describing the series of view ops that ran to generate the current tensor
146
+ // from the base tensor. This method is used by inplace-view ops like
147
+ // transpose_. It appends a ViewMeta to the existing stack, and refreshes the
148
+ // tensor by replaying the views off of the alias.
149
+ void mutate_view_meta(
150
+ const std::shared_ptr<at::functionalization::ViewMeta>& meta);
151
+
152
+ // Custom implementation of self.set_(src)
153
+ void set__impl(const FunctionalTensorWrapper* other);
154
+
155
+ // Custom implementation of resize_storage_bytes_(self, new_size)
156
+ void storage_resize_(const c10::SymInt& new_size);
157
+
158
+ // Returns whether the current tensor's data was ever mutated
159
+ bool has_data_mutation();
160
+ //
161
+ // Returns whether the current FunctionalTensorWrapper
162
+ // experienced a set_() call.
163
+ bool was_storage_changed() {
164
+ return was_storage_changed_;
165
+ }
166
+
167
+ void mark_storage_changed() {
168
+ was_storage_changed_ = true;
169
+ storage_changed_counter_++;
170
+ }
171
+
172
+ bool was_shallow_copy_data() {
173
+ return was_shallow_copy_data_;
174
+ }
175
+
176
+ void mark_shallow_copy_data() {
177
+ was_shallow_copy_data_ = true;
178
+ }
179
+
180
+ uint64_t storage_changed_counter() {
181
+ return storage_changed_counter_;
182
+ }
183
+
184
+ // A FunctionalTensor is considered a base if its not a view of another
185
+ // tensor.
186
+ bool isBaseTensor() const {
187
+ return view_metas_.empty();
188
+ }
189
+
190
+ c10::SymInt get_storage_size(bool before) {
191
+ return functional_storage_impl()->get_storage_size(before);
192
+ }
193
+
194
+ // Returns whether the FunctionalTensor experienced an
195
+ // untyped_storage().resize_() call
196
+ bool was_inductor_storage_resized() {
197
+ return functional_storage_impl()->was_inductor_storage_resized();
198
+ }
199
+
200
+ bool inductor_storage_resized_counter() {
201
+ return functional_storage_impl()->inductor_storage_resized_counter();
202
+ }
203
+ // The functionalization pass can be used to remove mutations.
204
+ // It does so by replacing any mutation op with it's corresponding
205
+ // out-of-place op, followed by a call to replace_(). e.g:
206
+ //
207
+ // a.add_(1)
208
+ //
209
+ // will turn into:
210
+ //
211
+ // tmp = a.add(1)
212
+ // a.replace_(tmp)
213
+ //
214
+ // replace_() swaps out the wrapped tensor, value_, with tmp.
215
+ void replace_(const Tensor& other, bool from_lazy_regenerate = false);
216
+
217
+ bool is_multi_output_view() {
218
+ return is_multi_output_view_;
219
+ }
220
+
221
+ // See Note[resize_() in functionalization pass]
222
+ void maybe_replace_storage(const Tensor& other);
223
+
224
+ // Replaces the storage with a new functional storage,
225
+ // and clears the view_metas_ stack.
226
+ // WARNING: Calling this function will sever the aliasing relationship between
227
+ // the current FunctionalTensorWrapper and any of its outstanding aliases.
228
+ // Please only call if you know what you're doing.
229
+ void _unsafe_reset_storage();
230
+
231
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
232
+ const c10::VariableVersion& version_counter,
233
+ bool allow_tensor_metadata_change) const override;
234
+
235
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
236
+ c10::VariableVersion&& version_counter,
237
+ bool allow_tensor_metadata_change) const override;
238
+
239
+ ~FunctionalTensorWrapper() override = default;
240
+
241
+ // FunctionalTensorWrapper overrides all custom size/stride function,
242
+ // so that if the inner tensor has a custom implementation
243
+ // we make sure to call that implementation.
244
+ at::IntArrayRef sizes_custom() const override;
245
+ at::IntArrayRef strides_custom() const override;
246
+ int64_t dim_custom() const override;
247
+ int64_t numel_custom() const override;
248
+ c10::SymBool sym_is_contiguous_custom(
249
+ at::MemoryFormat memory_format) const override;
250
+ c10::SymIntArrayRef sym_sizes_custom() const override;
251
+ c10::SymInt sym_size_custom(int64_t d) const override;
252
+ c10::SymIntArrayRef sym_strides_custom() const override;
253
+ c10::SymInt sym_storage_offset_custom() const override;
254
+ c10::Device device_custom() const override;
255
+ c10::Layout layout_impl() const override;
256
+
257
+ private:
258
+ const char* tensorimpl_type_name() const override;
259
+ void set_constructor_metadata();
260
+ functionalization::FunctionalStorageImpl* functional_storage_impl() const;
261
+
262
+ // This is used to re-implement shallow_copy_and_detach for
263
+ // FunctionalTensorWrapper. The implementation is identical, but we just need
264
+ // to return a subclass instead of a plain TensorImpl.
265
+ // TODO: maybe it's possible to arrange for that to happen automatically
266
+ // without an override here?
267
+ template <typename VariableVersion>
268
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach_core(
269
+ VariableVersion&& version_counter,
270
+ bool allow_tensor_metadata_change) const;
271
+
272
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
273
+ void copy_tensor_metadata_and_refresh(
274
+ const FunctionalTensorWrapper* src_impl,
275
+ FunctionalTensorWrapper* dest_impl,
276
+ const c10::VariableVersion& version_counter,
277
+ bool allow_tensor_metadata_change) const;
278
+
279
+ // Note that value is not taken by reference: internally, the wrapper will
280
+ // change the value tensor that it points to over time.
281
+ Tensor value_;
282
+ int64_t level_{};
283
+ // These two counters are used for identifying
284
+ // whether all the mutations on a given tensor are hidden from autograd or
285
+ // not. If we have an input mutation that is hidden from autograd, then once
286
+ // we convert the input mutation to a copy_() we know it will be safe to hide
287
+ // the copy_() from autograd as well.
288
+ bool has_metadata_mutation_ = false;
289
+ bool is_multi_output_view_ = false;
290
+ // Did the tensor experience a set_() call.
291
+ bool was_storage_changed_ = false;
292
+ // Did the tensor experience a shallow_copy_data_() call.
293
+ bool was_shallow_copy_data_ = false;
294
+ uint64_t storage_changed_counter_ = 0;
295
+ // Did the tensor experience any view operation with symbolic int.
296
+ bool is_symbolic_ = false;
297
+
298
+ size_t generation_ = 0;
299
+ std::vector<std::shared_ptr<at::functionalization::ViewMeta>> view_metas_;
300
+
301
+ protected:
302
+ static void copy_tensor_metadata(
303
+ const FunctionalTensorWrapper* src_impl,
304
+ FunctionalTensorWrapper* dest_impl,
305
+ const c10::VariableVersion& version_counter,
306
+ bool allow_tensor_metadata_change);
307
+ };
308
+
309
+ // Utility functions for the functionalization pass.
310
+
311
+ namespace functionalization {
312
+ namespace impl {
313
+
314
+ inline FunctionalTensorWrapper* unsafeGetFunctionalWrapper(
315
+ const Tensor& tensor) {
316
+ auto functional_impl =
317
+ static_cast<FunctionalTensorWrapper*>(tensor.unsafeGetTensorImpl());
318
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_impl != nullptr);
319
+ return functional_impl;
320
+ }
321
+
322
+ TORCH_API bool isBaseTensor(const at::Tensor& tensor);
323
+
324
+ TORCH_API bool isFunctionalTensor(const at::Tensor& tensor);
325
+ TORCH_API bool isFunctionalTensor(const std::optional<Tensor>& t);
326
+ TORCH_API bool isFunctionalTensor(
327
+ const c10::List<std::optional<Tensor>>& t_list);
328
+ TORCH_API bool isFunctionalTensor(ITensorListRef list);
329
+
330
+ TORCH_API Tensor to_functional_tensor(const Tensor& tensor);
331
+ TORCH_API std::optional<Tensor> to_functional_tensor(
332
+ const std::optional<Tensor>& tensor);
333
+ TORCH_API c10::List<std::optional<Tensor>> to_functional_tensor(
334
+ const c10::List<std::optional<Tensor>>& t_list);
335
+ TORCH_API std::vector<Tensor> to_functional_tensor(ITensorListRef t_list);
336
+
337
+ TORCH_API void freeze_functional_tensor(const Tensor& tensor);
338
+
339
+ TORCH_API Tensor
340
+ from_functional_tensor(const Tensor& tensor, bool assert_functional = true);
341
+ TORCH_API std::optional<Tensor> from_functional_tensor(
342
+ const std::optional<Tensor>& t,
343
+ bool assert_functional = true);
344
+ TORCH_API c10::List<std::optional<Tensor>> from_functional_tensor(
345
+ const c10::List<std::optional<Tensor>>& t_list);
346
+ TORCH_API std::vector<Tensor> from_functional_tensor(ITensorListRef t_list);
347
+
348
+ TORCH_API void sync(const at::Tensor& t);
349
+ TORCH_API void sync(const std::optional<Tensor>& t);
350
+ TORCH_API void sync(const c10::List<std::optional<Tensor>>& t_list);
351
+ TORCH_API void sync(ITensorListRef t_list);
352
+
353
+ TORCH_API void replace_(const Tensor& functional_tensor, const Tensor& other);
354
+ TORCH_API void replace_(
355
+ const ITensorListRef functional_tensor,
356
+ ITensorListRef other);
357
+
358
+ TORCH_API void commit_update(const Tensor& functional_tensor);
359
+ TORCH_API void commit_update(ITensorListRef functional_tensor);
360
+
361
+ TORCH_API void unsafe_reset_storage(const Tensor& functional_tensor);
362
+
363
+ TORCH_API void mark_mutation_hidden_from_autograd(
364
+ const Tensor& functional_tensor);
365
+
366
+ TORCH_API bool are_all_mutations_hidden_from_autograd(
367
+ const Tensor& functional_tensor);
368
+
369
+ TORCH_API bool are_all_mutations_under_no_grad_or_inference_mode(
370
+ const Tensor& functional_tensor);
371
+
372
+ // These two methods are XLA-specific logic and are no-ops
373
+ // for the normal functionalization flow.
374
+ TORCH_API void propagate_xla_data(
375
+ const Tensor& functional_tensor,
376
+ const Tensor& other);
377
+ TORCH_API void propagate_xla_data(
378
+ const ITensorListRef functional_tensor,
379
+ ITensorListRef other);
380
+
381
+ TORCH_API void propagate_xla_data_direct(
382
+ const Tensor& tensor,
383
+ const Tensor& other);
384
+ TORCH_API void propagate_xla_data_direct(
385
+ const ITensorListRef tensor,
386
+ ITensorListRef other);
387
+
388
+ Tensor create_functional_tensor_with_view_meta(
389
+ const Tensor& view_to_wrap,
390
+ const Tensor& base,
391
+ const std::shared_ptr<functionalization::ViewMeta>& meta,
392
+ int64_t out_idx = 0);
393
+ std::vector<Tensor> create_functional_tensor_with_view_meta(
394
+ ITensorListRef view_to_wrap,
395
+ const Tensor& base,
396
+ const std::shared_ptr<functionalization::ViewMeta>& meta);
397
+
398
+ void mutate_view_meta(
399
+ const Tensor& self,
400
+ const std::shared_ptr<functionalization::ViewMeta>& meta);
401
+
402
+ TORCH_API Tensor apply_view_meta_sequence(
403
+ const Tensor& base,
404
+ const std::vector<std::shared_ptr<functionalization::ViewMeta>>& sequence);
405
+
406
+ void set_sizes_strides_offset(const Tensor& out, const Tensor& meta_out);
407
+ void set_sizes_strides_offset(
408
+ const std::vector<Tensor>& outs,
409
+ const std::vector<Tensor>& meta_outs);
410
+
411
+ // ~~~~~ TLS used in functionalization ~~~~~
412
+
413
+ TORCH_API bool getFunctionalizationReapplyViewsTLS();
414
+ TORCH_API void setFunctionalizationReapplyViewsTLS(bool reapply_views);
415
+
416
+ class TORCH_API FunctionalizationReapplyViewsGuard {
417
+ public:
418
+ FunctionalizationReapplyViewsGuard(bool reapply_views)
419
+ : prev_(getFunctionalizationReapplyViewsTLS()) {
420
+ setFunctionalizationReapplyViewsTLS(reapply_views);
421
+ }
422
+
423
+ ~FunctionalizationReapplyViewsGuard() {
424
+ setFunctionalizationReapplyViewsTLS(prev_);
425
+ }
426
+
427
+ FunctionalizationReapplyViewsGuard(
428
+ const FunctionalizationReapplyViewsGuard&) = delete;
429
+ FunctionalizationReapplyViewsGuard operator=(
430
+ const FunctionalizationReapplyViewsGuard&) = delete;
431
+ FunctionalizationReapplyViewsGuard(FunctionalizationReapplyViewsGuard&&) =
432
+ delete;
433
+ FunctionalizationReapplyViewsGuard operator=(
434
+ FunctionalizationReapplyViewsGuard&&) = delete;
435
+
436
+ private:
437
+ bool prev_;
438
+ };
439
+
440
+ } // namespace impl
441
+
442
+ // Helper function to call an out-of-place composite aten kernel that may use
443
+ // mutations / views internally, and functionalize them.
444
+ TORCH_API void functionalize_op_helper(
445
+ const c10::OperatorHandle& op,
446
+ torch::jit::Stack* stack);
447
+
448
+ template <class Op, bool symint, class ReturnType, class... ParameterTypes>
449
+ struct _functionalize_aten_op final {};
450
+
451
+ template <class Op, bool symint, class ReturnType, class... ParameterTypes>
452
+ struct _functionalize_aten_op<Op, symint, ReturnType(ParameterTypes...)> final {
453
+ static ReturnType call(
454
+ typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
455
+ using FuncType = ReturnType(
456
+ typename c10::maybe_keep_symint<symint, ParameterTypes>::type...);
457
+ auto op = c10::Dispatcher::singleton()
458
+ .findSchemaOrThrow(
459
+ (const char*)Op::name, (const char*)Op::overload_name)
460
+ .typed<FuncType>();
461
+
462
+ return c10::impl::BoxedKernelWrapper<FuncType>::call(
463
+ c10::BoxedKernel::makeFromFunction<functionalize_op_helper>(),
464
+ op,
465
+ // BoxedKernelWrapper knows to ignore this keyset argument,
466
+ // because functionalize_op_helper doesn't take in a DispatchKeySet
467
+ c10::DispatchKeySet(),
468
+ args...);
469
+ }
470
+ };
471
+
472
+ template <class Op>
473
+ using functionalize_aten_op =
474
+ _functionalize_aten_op<Op, false, typename Op::schema>;
475
+
476
+ template <class Op>
477
+ using functionalize_aten_op_symint =
478
+ _functionalize_aten_op<Op, true, typename Op::schema>;
479
+
480
+ } // namespace functionalization
481
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.cpp ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/FunctionalizeFallbackKernel.h>
2
+
3
+ #include <ATen/core/dispatch/Dispatcher.h>
4
+ #include <ATen/core/LegacyTypeDispatch.h>
5
+ #include <ATen/EmptyTensor.h>
6
+ #include <ATen/FunctionalTensorWrapper.h>
7
+ #include <ATen/InferSize.h>
8
+ #include <ATen/TensorUtils.h>
9
+ #include <torch/library.h>
10
+ #include <c10/util/irange.h>
11
+ #include <c10/util/strides.h>
12
+
13
+ #ifndef AT_PER_OPERATOR_HEADERS
14
+ #include <ATen/ATen.h>
15
+ #include <ATen/Functions.h>
16
+ #include <ATen/NativeFunctions.h>
17
+ #else
18
+ #include <ATen/ops/_to_copy.h>
19
+ #include <ATen/ops/lift.h>
20
+ #include <ATen/ops/lift_fresh.h>
21
+ #include <ATen/ops/lift_fresh_copy.h>
22
+ #include <ATen/ops/resize.h>
23
+ #include <ATen/ops/as_strided_copy.h>
24
+ #include <ATen/ops/_unsafe_view.h>
25
+
26
+ #include <utility>
27
+ #endif
28
+
29
+ namespace at::functionalization {
30
+
31
+ Tensor resize__ViewMeta::forward(const Tensor& base) {
32
+ if (!reapply_views) {
33
+ return at::as_strided_copy(base, size, c10::contiguous_strides(size));
34
+ }
35
+ return base.as_strided(size, c10::contiguous_strides(size));
36
+ }
37
+
38
+ Tensor resize__ViewMeta::reverse(const Tensor& base, const Tensor& mutated_view) {
39
+ return base.as_strided_scatter(
40
+ mutated_view, size, c10::contiguous_strides(size));
41
+ }
42
+
43
+ Tensor _unsafe_view_ViewMeta::forward(const Tensor& base) {
44
+ return at::_unsafe_view_symint(base, size);
45
+ }
46
+
47
+ Tensor _unsafe_view_ViewMeta::reverse(const Tensor& base, const Tensor& mutated_view) {
48
+ return at::_unsafe_view_symint(mutated_view, base.sym_sizes());
49
+ }
50
+
51
+ } // namespace at::functionalization
52
+
53
+ namespace {
54
+ void functionalizeFallback(const c10::OperatorHandle& op, c10::DispatchKeySet dispatchKeySet [[maybe_unused]], torch::jit::Stack* stack) {
55
+ const auto& schema = op.schema();
56
+ // NB: auto_functionalize handles the case where outputs do not have alias info.
57
+ // This error message therefore suggests users to modify their custom op to the
58
+ // point where auto_functionalize works instead of asking them to try the raw
59
+ // functionalization API (because that is a bit difficult to use).
60
+ // If you're here and want to try the raw functionalizaton kernel approach,
61
+ // see https://gist.github.com/bdhirsh/7dadbf6296f8f7d1abcf4c482f438aaa
62
+ TORCH_CHECK(
63
+ !schema.hasAnyAliasInfo(),
64
+ "Found a custom (non-ATen) operator whose output has alias annotations: ",
65
+ op.schema(),
66
+ ". We only support functionalizing operators whose outputs do not have alias ",
67
+ "annotations (e.g. 'Tensor(a)' is a Tensor with an alias annotation whereas ",
68
+ "'Tensor' is a Tensor without. The '(a)' is the alias annotation). "
69
+ "The alias annotation specifies that the output ",
70
+ "Tensor shares storage with an input that has the same annotation. ",
71
+ "Please check if ",
72
+ "(1) the output needs to be an output (if not, don't return it), ",
73
+ "(2) if the output doesn't share storage with any inputs, then ",
74
+ "delete the alias annotation. ",
75
+ "(3) if the output indeed shares storage with an input, then add a ",
76
+ ".clone() before returning it to prevent storage sharing and then "
77
+ "delete the alias annotation. ",
78
+ "Otherwise, please file an issue on GitHub.");
79
+ const auto num_arguments = schema.arguments().size();
80
+ const auto arguments_begin = stack->size() - num_arguments;
81
+ auto arguments = torch::jit::last(stack, num_arguments);
82
+
83
+ auto any_functional_inputs = false;
84
+ auto any_tensor_inputs = false;
85
+ for (uint64_t idx = 0; idx < num_arguments; ++idx) {
86
+ const auto& ivalue = arguments[idx];
87
+ if (ivalue.isTensor()) {
88
+ any_tensor_inputs = true;
89
+ const auto& t = ivalue.toTensor();
90
+ if (t.defined() && at::functionalization::impl::isFunctionalTensor(t)) {
91
+ any_functional_inputs = true;
92
+ at::functionalization::impl::sync(t);
93
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(t));
94
+ (*stack)[arguments_begin + idx] = t_new;
95
+ }
96
+ } else if (ivalue.isTensorList()) {
97
+ any_tensor_inputs = true;
98
+ auto tensors = ivalue.toTensorList();
99
+ if (at::functionalization::impl::isFunctionalTensor(tensors)) {
100
+ any_functional_inputs = true;
101
+ at::functionalization::impl::sync(tensors);
102
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(tensors));
103
+ (*stack)[arguments_begin + idx] = t_new;
104
+ }
105
+ } else if (ivalue.isOptionalTensorList()) {
106
+ any_tensor_inputs = true;
107
+ auto opt_tensors = ivalue.toOptionalTensorList();
108
+ if (at::functionalization::impl::isFunctionalTensor(opt_tensors)) {
109
+ any_functional_inputs = true;
110
+ at::functionalization::impl::sync(opt_tensors);
111
+ auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(opt_tensors));
112
+ (*stack)[arguments_begin + idx] = t_new;
113
+ }
114
+ } else if (ivalue.isList()) {
115
+ // Handle nested lists containing tensor lists (e.g., Tensor[][]).
116
+ auto list = ivalue.toList();
117
+ for (const auto i : c10::irange(list.size())) {
118
+ const auto& elem = list.get(i);
119
+ if (elem.isTensorList()) {
120
+ any_tensor_inputs = true;
121
+ auto tensors = elem.toTensorList();
122
+ if (at::functionalization::impl::isFunctionalTensor(tensors)) {
123
+ any_functional_inputs = true;
124
+ at::functionalization::impl::sync(tensors);
125
+ list.set(i, c10::IValue(at::functionalization::impl::from_functional_tensor(tensors)));
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ // we should wrap the output if any inputs were wrapped,
132
+ // OR if we're hitting a factory function (with no tensor inputs)
133
+ auto should_wrap_outputs = !any_tensor_inputs || any_functional_inputs;
134
+ {
135
+ at::AutoDispatchSkipFunctionalize guard;
136
+ op.callBoxed(stack);
137
+ }
138
+ const auto num_returns = schema.returns().size();
139
+ const auto returns_begin = stack->size() - num_returns;
140
+ auto returns = torch::jit::last(stack, num_returns);
141
+
142
+ for (const auto idx : c10::irange(num_returns)) {
143
+ const auto& ivalue = returns[idx];
144
+ if (ivalue.isTensor() && should_wrap_outputs) {
145
+ const auto& t = ivalue.toTensor();
146
+ if (!t.defined()) {
147
+ continue;
148
+ }
149
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(t));
150
+ (*stack)[returns_begin + idx] = t_new;
151
+ } else if (ivalue.isTensorList() && should_wrap_outputs) {
152
+ auto tensors = ivalue.toTensorList();
153
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(tensors));
154
+ (*stack)[returns_begin + idx] = t_new;
155
+ } else if (ivalue.isOptionalTensorList() && should_wrap_outputs) {
156
+ auto opt_tensors = ivalue.toOptionalTensorList();
157
+ auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(opt_tensors));
158
+ (*stack)[returns_begin + idx] = t_new;
159
+ } else if (ivalue.isList() && should_wrap_outputs) {
160
+ // Handle nested lists containing tensor lists (e.g., Tensor[][]).
161
+ auto list = ivalue.toList();
162
+ for (const auto i : c10::irange(list.size())) {
163
+ const auto& elem = list.get(i);
164
+ if (elem.isTensorList()) {
165
+ auto tensors = elem.toTensorList();
166
+ list.set(i, c10::IValue(at::functionalization::impl::to_functional_tensor(tensors)));
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ }
173
+
174
+ // resize_() is special because:
175
+ // - when we resize to a larger size, it acts as a mutation
176
+ // - when we resize to a smaller size, it acts as a view
177
+ // See Note [resize_ in Functionalization] for more dtails
178
+ static const at::Tensor & resize__functionalization(c10::DispatchKeySet dispatchKeySet [[maybe_unused]], const at::Tensor & self, at::IntArrayRef size, std::optional<at::MemoryFormat> memory_format) {
179
+ // First unwrap the tensor arguments
180
+ at::Tensor self_;
181
+ if (at::functionalization::impl::isFunctionalTensor(self)) {
182
+ at::functionalization::impl::sync(self);
183
+ self_ = at::functionalization::impl::from_functional_tensor(self);
184
+ } else {
185
+ self_ = self;
186
+ }
187
+ // Case 1: arguments are not functional tensors, so we no-op and redispatch.
188
+ if (!at::functionalization::impl::isFunctionalTensor(self)) {
189
+ at::AutoDispatchSkipFunctionalize guard;
190
+ self_.resize_(size, memory_format);
191
+ return self;
192
+ }
193
+
194
+ // Case 2: actually functionalize resize_()
195
+ at::Tensor tmp_output;
196
+ {
197
+ at::AutoDispatchSkipFunctionalize guard;
198
+ tmp_output = at::resize(self_, size, memory_format);
199
+ }
200
+
201
+ auto itemsize = self.dtype().itemsize();
202
+ auto storage_offset = self.storage_offset();
203
+ auto new_size_bytes = at::detail::computeStorageNbytesContiguous(size, itemsize, storage_offset);
204
+ auto needs_resize_storage = new_size_bytes > self.storage().nbytes();
205
+
206
+ if (needs_resize_storage) {
207
+ // If resize_() actually increases the size of the storage, then we need to tell FunctionalTensorWrapper about it.
208
+ // See Note[resize_() in functionalization pass]
209
+ auto func_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self);
210
+ func_impl->maybe_replace_storage(tmp_output);
211
+ // See the note - we're guaranteed at this point that "self" is *not* a view (and has no outstanding views)
212
+ // So we don't need to treat the output of resize as view tensor.
213
+ return self;
214
+ }
215
+
216
+ // Otherwise, we know that we're resizing to a smaller size.
217
+ // resize_() is effectively a view operator.
218
+ // The output of resizing is equivalent to taking a slice of a larger tensor.
219
+ // We have to emulate this "slicing" with an as_strided call.
220
+ auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS();
221
+ auto view_meta = std::make_shared<at::functionalization::resize__ViewMeta>(
222
+ reapply_views, size.vec());
223
+ at::functionalization::impl::mutate_view_meta(self, view_meta);
224
+ return self;
225
+ }
226
+
227
+
228
+ static at::Tensor lift_functionalize(const at::Tensor & self) {
229
+ if (at::functionalization::impl::isFunctionalTensor(self)) {
230
+ return self.view_as(self);
231
+ }
232
+
233
+ at::AutoDispatchSkipFunctionalize guard;
234
+ auto out = at::lift(self);
235
+ return at::functionalization::impl::to_functional_tensor(out);
236
+ }
237
+
238
+ static at::Tensor lift_fresh_functionalize(const at::Tensor & self) {
239
+ // See Note [Exporting and compiling a graph with lift_fresh_copy]
240
+ if (at::functionalization::impl::isFunctionalTensor(self)) {
241
+ return self.view_as(self);
242
+ }
243
+
244
+ at::AutoDispatchSkipFunctionalize guard;
245
+ auto out = at::lift_fresh(self);
246
+ return at::functionalization::impl::to_functional_tensor(out);
247
+ }
248
+
249
+ static at::Tensor lift_fresh_functionalize_copy(const at::Tensor & self) {
250
+ // Note [Exporting and compiling a graph with lift_fresh_copy]
251
+ // If out is already a functional tensor, don't wrap it twice.
252
+ // In theory this could be useful if we want to nest functionalization with itself,
253
+ // but that isn't really a use case today.
254
+ // Needed for https://github.com/pytorch/pytorch/issues/105327
255
+ if (at::functionalization::impl::isFunctionalTensor(self)) {
256
+ // Note [Composite Functionalization under PreDispatch mode]
257
+ // When we are tracing under PreDispatch, PreDispatch key will be
258
+ // in the local include TLS. As a result, when we redispatch here,
259
+ // we will end up hitting PreDispatch stack first. So, we should
260
+ // directly redispatch to the functionalize key manually.
261
+ static auto op = c10::Dispatcher::singleton().findSchemaOrThrow("aten::clone", "").typed<at::Tensor(const at::Tensor &, std::optional<at::MemoryFormat>)>();
262
+ return op.redispatch(c10::DispatchKeySet({c10::DispatchKey::Functionalize}), self, std::nullopt);
263
+ }
264
+
265
+ at::AutoDispatchSkipFunctionalize guard;
266
+ auto out = at::lift_fresh_copy(self);
267
+ return at::functionalization::impl::to_functional_tensor(out);
268
+ }
269
+
270
+ static bool device_opted_into_functionalization(c10::Device self_device, std::optional<c10::Device> tgt_device) {
271
+ // If the target device is empty, then the output tensor should be on the same device as the input
272
+ auto real_tgt_device = tgt_device.has_value() ? tgt_device.value() : self_device;
273
+ return real_tgt_device.type() == c10::DeviceType::XLA || real_tgt_device.type() == c10::DeviceType::Lazy;
274
+ }
275
+
276
+ // note I only need this because the to.dtype/to.dtype_layout overload calls this, so we skip the op above.
277
+ // We should probably get rid of this though.
278
+ static at::Tensor _to_copy_functionalize(
279
+ const at::Tensor & self,
280
+ std::optional<at::ScalarType> dtype,
281
+ std::optional<at::Layout> layout,
282
+ std::optional<at::Device> device,
283
+ std::optional<bool> pin_memory,
284
+ bool non_blocking,
285
+ std::optional<at::MemoryFormat> memory_format) {
286
+ at::Tensor self_;
287
+ if (at::functionalization::impl::isFunctionalTensor(self)) {
288
+ // sync any pending updates
289
+ at::functionalization::impl::sync(self);
290
+ // pass the unwrapped tensor to the backend
291
+ self_ = at::functionalization::impl::from_functional_tensor(self);
292
+ } else {
293
+ self_ = self;
294
+ }
295
+
296
+ at::AutoDispatchSkipFunctionalize guard;
297
+ auto out = at::_to_copy(self_, dtype, layout, device, pin_memory, non_blocking, memory_format);
298
+
299
+ // Special case: if the Functionalize key is not in TLS, we assume that we're running
300
+ // on a lazy backend (LTC).
301
+ // In that case, if we're copying to a non-functionalize-enabled device,
302
+ // then the functionalization pass should "end". We need to sync any updates on the input
303
+ // tensor, but we shouldn't wrap the output.
304
+ if (!c10::impl::tls_local_dispatch_key_set().included_.has(c10::DispatchKey::Functionalize)) {
305
+ if (!device_opted_into_functionalization(self.device(), device)) {
306
+ return out;
307
+ }
308
+ }
309
+ return at::functionalization::impl::to_functional_tensor(out);
310
+ }
311
+
312
+
313
+ // Why is _unsafe_view special-cased here?
314
+ // Basically just to satisfy autograd's debug asserts.
315
+ // The situation:
316
+ // - _unsafe_view's autograd kernel has debug asserts to confirm
317
+ // that the input and output alias storage.
318
+ // - _unsafe_view's schema in native_functions.yaml
319
+ // does not contain alias annotations, so it advertises as non-aliasing.
320
+ // - functionalization will then treat _unsafe_view like a non-aliasing op.
321
+ // Specifically, autograd will redispatch to functionalization's
322
+ // boxed fallback kernel, which creates a new FunctionalTensorWrapper output
323
+ // that does **not** alias storage with the input, tripping the assert.
324
+ // The kernel written here just manually re-ifies the aliasing relationship.
325
+ //
326
+ // Another way to handle this would be to fix unsafe_view's alias annotations
327
+ // in native_functions.yaml, but I think this would be a pessimization.
328
+ // The idea with _unsafe_view is that you're guaranteed that the input
329
+ // is a temporary, and don't actually have to worry about propagating
330
+ // mutations between the input and output.
331
+ static at::Tensor _unsafe_view_functionalize(const at::Tensor & self, at::SymIntArrayRef size) {
332
+ if (!at::functionalization::impl::isFunctionalTensor(self)) {
333
+ at::AutoDispatchSkipFunctionalize guard;
334
+ return at::_unsafe_view_symint(self, size);
335
+ }
336
+
337
+ auto self_ = at::functionalization::impl::from_functional_tensor(self);
338
+ at::Tensor tmp_output;
339
+ {
340
+ at::AutoDispatchSkipFunctionalize guard;
341
+ tmp_output = at::_unsafe_view_symint(self_, size);
342
+ }
343
+
344
+ bool has_symbolic_inputs = std::any_of(
345
+ size.begin(), size.end(), [=](auto& s) { return s.is_symbolic(); });
346
+ auto view_meta =
347
+ std::make_shared<at::functionalization::_unsafe_view_ViewMeta>(
348
+ has_symbolic_inputs, size.vec());
349
+
350
+ auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, self, std::move(view_meta));
351
+ // See Note [Propagating strides in the functionalization pass]
352
+ // (for _unsafe_view, I'm just manually doing the shape inference rule here instead of calling the meta function for unsafe_view)
353
+ auto inferred_size = at::infer_size_dv(size, self.sym_numel());
354
+
355
+ auto stride = at::detail::computeStride(self.sym_sizes(), self.sym_strides(), inferred_size);
356
+
357
+ if (!stride.has_value()) {
358
+
359
+ TORCH_SYM_CHECK(
360
+ self.sym_is_contiguous(),
361
+ "View is not valid from size:",
362
+ self.sym_sizes(),
363
+ " stride: ",
364
+ self.sym_strides(),
365
+ " to shape: ",
366
+ inferred_size,
367
+ " in case of unbacked symbols consider adding torch.check to guide computing strides.");
368
+
369
+ // With unbacked symints, computeStride could fail even on contiguous
370
+ // tensors. In this case, we can use the strides of an empty tensor of
371
+ // inferred_size.
372
+ stride = at::detail::empty_symint_meta(
373
+ inferred_size,
374
+ std::nullopt,
375
+ std::nullopt,
376
+ std::nullopt,
377
+ std::nullopt,
378
+ std::nullopt)
379
+ .sym_strides();
380
+ }
381
+
382
+ out.unsafeGetTensorImpl()->set_sizes_and_strides(inferred_size, stride.value());
383
+ return out;
384
+ }
385
+
386
+ static at::Tensor& set__functionalize(at::Tensor& self, const at::Tensor& src) {
387
+ // error case
388
+ TORCH_CHECK(at::functionalization::impl::isFunctionalTensor(self) || !at::functionalization::impl::isFunctionalTensor(src),
389
+ "set__functionalize: Tried to mutate a non-functional tensor with a functional tensor, which is not allowed");
390
+
391
+ // nop case
392
+ if (!at::functionalization::impl::isFunctionalTensor(self) && !at::functionalization::impl::isFunctionalTensor(src)) {
393
+ at::AutoDispatchSkipFunctionalize guard;
394
+ return self.set_(src);
395
+ }
396
+
397
+ TORCH_CHECK(at::functionalization::impl::isFunctionalTensor(src),
398
+ "set__functionalize: We do not currently support x.set_(y) where y is not a FunctionalTensor. Please file an issue");
399
+
400
+ TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(self));
401
+ TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(src));
402
+ auto self_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self);
403
+ auto src_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(src);
404
+ // See Note [Ordering of resize_() and set_()]
405
+ TORCH_CHECK(!self_impl->was_inductor_storage_resized(),
406
+ "storage_resize_() followed by set_() in torch.compile is not supported today");
407
+ self_impl->set__impl(src_impl);
408
+ return self;
409
+ }
410
+
411
+ TORCH_LIBRARY_IMPL(_, Functionalize, m) {
412
+ m.fallback(torch::CppFunction::makeFromBoxedFunction<&functionalizeFallback>());
413
+ }
414
+
415
+ TORCH_LIBRARY_IMPL(aten, Functionalize, m) {
416
+ m.impl("resize_", TORCH_FN(resize__functionalization));
417
+ m.impl("lift", TORCH_FN(lift_functionalize));
418
+ m.impl("lift_fresh", TORCH_FN(lift_fresh_functionalize));
419
+ m.impl("lift_fresh_copy", TORCH_FN(lift_fresh_functionalize_copy));
420
+ m.impl("_to_copy", TORCH_FN(_to_copy_functionalize));
421
+ m.impl("_unsafe_view", TORCH_FN(_unsafe_view_functionalize));
422
+ // The overloads of set_() that take in a storage should never
423
+ // appear with torch.compile, because dynamo graph breaks
424
+ m.impl("set_.source_Tensor", TORCH_FN(set__functionalize));
425
+ }
western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/FunctionalStorageImpl.h>
4
+
5
+ namespace at::functionalization {
6
+
7
+ // `ViewMeta` implementation for `resize_` operation.
8
+ struct TORCH_API resize__ViewMeta : public ViewMeta {
9
+ FUNCTIONALIZATION_VIEWMETA_NAME(resize__ViewMeta)
10
+ FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(
11
+ bool /* reapply_views */,
12
+ std::vector<int64_t>);
13
+
14
+ resize__ViewMeta(const SerializableTuple& tpl)
15
+ : resize__ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {}
16
+
17
+ resize__ViewMeta(bool reapply_views, const std::vector<int64_t>& size)
18
+ : ViewMeta(/*has_symbolic_inputs=*/false),
19
+ reapply_views(reapply_views),
20
+ size(size) {}
21
+
22
+ Tensor forward(const Tensor& base) override;
23
+ Tensor reverse(const Tensor& base, const Tensor& mutated_view) override;
24
+
25
+ SerializableTuple to_serializable_tuple() {
26
+ return std::make_tuple(reapply_views, size);
27
+ }
28
+
29
+ bool reapply_views;
30
+ std::vector<int64_t> size;
31
+ };
32
+
33
+ // `ViewMeta` implementation for `_unsafe_view` operation.
34
+ struct TORCH_API _unsafe_view_ViewMeta : public ViewMeta {
35
+ FUNCTIONALIZATION_VIEWMETA_NAME(_unsafe_view_ViewMeta)
36
+ FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(
37
+ bool /* has_symbolic_inputs */,
38
+ std::vector<c10::SymInt>);
39
+
40
+ _unsafe_view_ViewMeta(const SerializableTuple& tpl)
41
+ : _unsafe_view_ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {}
42
+
43
+ _unsafe_view_ViewMeta(
44
+ bool has_symbolic_inputs,
45
+ const std::vector<c10::SymInt>& size)
46
+ : ViewMeta(has_symbolic_inputs), size(size) {}
47
+
48
+ Tensor forward(const Tensor& base) override;
49
+ Tensor reverse(const Tensor& base, const Tensor& mutated_view) override;
50
+
51
+ SerializableTuple to_serializable_tuple() {
52
+ return std::make_tuple(has_symbolic_inputs, size);
53
+ }
54
+
55
+ std::vector<c10::SymInt> size;
56
+ };
57
+
58
+ } // namespace at::functionalization
western_ai/usa/pytorch/aten/src/ATen/Generator.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Generator.h>
western_ai/usa/pytorch/aten/src/ATen/InferSize.h ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/DimVector.h>
4
+ #include <c10/core/ScalarType.h>
5
+ #include <c10/core/SymIntArrayRef.h>
6
+ #include <c10/util/DimVector.h>
7
+ #include <c10/util/Exception.h>
8
+ #include <optional>
9
+ #include <sstream>
10
+ #include <vector>
11
+
12
+ namespace at {
13
+
14
+ // Infers the size of a dim with size -1, if it exists. Also checks that new
15
+ // shape is compatible with the number of elements.
16
+ //
17
+ // templated to handle std::vector<int64_t> and DimVector use cases, see
18
+ // below
19
+ //
20
+ template <typename InputArrayRef, typename NumelType, typename ResultVec>
21
+ inline void infer_size_impl(
22
+ InputArrayRef shape,
23
+ NumelType numel,
24
+ ResultVec& res) {
25
+ NumelType newsize = 1;
26
+ // N.B. this is an index, not a sym dim!
27
+ std::optional<int64_t> infer_dim;
28
+ for (int64_t dim = 0, ndim = shape.size(); dim != ndim; dim++) {
29
+ if (TORCH_GUARD_OR_FALSE(sym_eq(shape[dim], -1))) {
30
+ TORCH_CHECK(!infer_dim, "only one dimension can be inferred");
31
+ infer_dim = dim;
32
+ } else {
33
+ // in case of unbacked shape[dim] we assume it's not -1 and add a runtime
34
+ // assertion.
35
+ TORCH_MAYBE_SYM_CHECK(
36
+ sym_gt(shape[dim], -1),
37
+ "invalid shape dimension ",
38
+ shape[dim],
39
+ " at index ",
40
+ dim,
41
+ " of shape ",
42
+ shape);
43
+ newsize *= shape[dim];
44
+ }
45
+ }
46
+
47
+ if (infer_dim) {
48
+ // numel is the product of known sizes, it has to be divisible by newsize.
49
+ // and newsize should be positive unless newsize == numel (we throw
50
+ // different) error message in that case.
51
+ if constexpr (std::is_same_v<NumelType, c10::SymInt>) {
52
+ auto v = newsize.maybe_as_int();
53
+ if (v and *v == 0) {
54
+ // Avoid div by 0 when sym_eq(numel % newsize, 0) is constructed!
55
+ // which may happen when newsize is not a symbol! if its a symbol
56
+ // division won't happen anyway during compile.
57
+ TORCH_MAYBE_SYM_CHECK(
58
+ numel == newsize,
59
+ "shape '",
60
+ shape,
61
+ "' is invalid for input of size ",
62
+ numel);
63
+ } else {
64
+ auto cond = sym_gt(newsize, 0)
65
+ .sym_and(sym_eq(numel % newsize, 0))
66
+ .sym_or(sym_eq(numel, newsize));
67
+ TORCH_MAYBE_SYM_CHECK(
68
+ cond, "shape '", shape, "' is invalid for input of size ", numel);
69
+ }
70
+
71
+ } else {
72
+ TORCH_CHECK(
73
+ (newsize > 0 && (numel % newsize == 0)) || numel == newsize,
74
+ "shape '",
75
+ shape,
76
+ "' is invalid for input of size ",
77
+ numel);
78
+ }
79
+
80
+ // We have a degree of freedom here to select the dimension size; follow
81
+ // NumPy semantics and just bail. However, a nice error message is needed
82
+ // because users often use `view` as a way to flatten & unflatten
83
+ // dimensions and will otherwise be confused why
84
+ // empty_tensor.view( 0, 0)
85
+ // works yet
86
+ // empty_tensor.view(-1, 0)
87
+ // doesn't.
88
+ TORCH_MAYBE_SYM_CHECK(
89
+ newsize != 0,
90
+ "cannot reshape tensor of 0 elements into shape ",
91
+ shape,
92
+ " because the unspecified dimension size -1 can be any "
93
+ "value and is ambiguous");
94
+
95
+ res[*infer_dim] = numel / newsize;
96
+ return;
97
+ }
98
+
99
+ TORCH_MAYBE_SYM_CHECK(
100
+ sym_eq(numel, newsize),
101
+ "shape '",
102
+ shape,
103
+ "' is invalid for input of size ",
104
+ numel);
105
+ }
106
+
107
+ inline std::vector<int64_t> infer_size(IntArrayRef shape, int64_t numel) {
108
+ auto res = shape.vec();
109
+ infer_size_impl(shape, numel, res);
110
+ return res;
111
+ }
112
+
113
+ inline at::DimVector infer_size_dv(IntArrayRef shape, int64_t numel) {
114
+ auto res = at::DimVector(shape);
115
+ infer_size_impl(shape, numel, res);
116
+ return res;
117
+ }
118
+
119
+ inline at::SymDimVector infer_size_dv(
120
+ c10::SymIntArrayRef shape,
121
+ c10::SymInt numel) {
122
+ auto res = at::SymDimVector(shape);
123
+ infer_size_impl<c10::SymIntArrayRef, c10::SymInt, at::SymDimVector>(
124
+ shape, std::move(numel), res);
125
+ return res;
126
+ }
127
+
128
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/InitialTensorOptions.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/TensorOptions.h>
4
+
5
+ namespace at {
6
+
7
+ // Represents the initial TensorOptions, before the "defaults" are ever changed.
8
+ // This is designed to be used in library code, where the explicit devices,
9
+ // dtypes, etc. are known. NOTE: this is not a stable API.
10
+ inline TensorOptions initialTensorOptions() {
11
+ return TensorOptions(kCPU).dtype(kFloat).layout(kStrided).requires_grad(
12
+ false);
13
+ }
14
+
15
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/Layout.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <c10/core/Layout.h>
western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.cpp ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/Context.h>
2
+ #include <ATen/LegacyBatchedFallback.h>
3
+ #include <ATen/MatrixRef.h>
4
+ #include <ATen/LegacyVmapTransforms.h>
5
+ #include <ATen/core/dispatch/Dispatcher.h>
6
+ #include <c10/util/accumulate.h>
7
+ #include <c10/util/llvmMathExtras.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ namespace at {
11
+
12
+ // Given a linear index, return the actual index.
13
+ // Example: Given linear_idx = 3, sizes = [5, 2], we would return [1, 0]
14
+ static SmallVector<indexing::TensorIndex,kVmapStaticDimVecSize>
15
+ computeIndex(int64_t linear_idx, IntArrayRef sizes) {
16
+ SmallVector<indexing::TensorIndex,kVmapStaticDimVecSize> result;
17
+ result.reserve(sizes.size());
18
+ for (auto it = sizes.rbegin(); it != sizes.rend(); it++) {
19
+ auto remainder = linear_idx % *it;
20
+ result.push_back(remainder);
21
+ linear_idx -= remainder;
22
+ linear_idx /= *it;
23
+ }
24
+ std::reverse(std::begin(result), std::end(result));
25
+ return result;
26
+ }
27
+
28
+ static bool areAllReturnsTensors(const FunctionSchema& schema) {
29
+ return std::all_of(
30
+ schema.returns().begin(),
31
+ schema.returns().end(),
32
+ [] (const Argument& arg) { return arg.type() == TensorType::get(); });
33
+ }
34
+
35
+ static bool areAnyArgumentsTensorList(const FunctionSchema& schema) {
36
+ return std::any_of(
37
+ schema.arguments().begin(),
38
+ schema.arguments().end(),
39
+ [] (const Argument& arg) { return arg.type()->isSubtypeOf(*ListType::ofTensors()); });
40
+ }
41
+
42
+ // Returns if an operator is in-place. An operator is inplace if:
43
+ // 1. The first argument is a Tensor and it is being written to
44
+ // 2. The first argument is being returned
45
+ // 3. No other arguments are aliased
46
+ // Here is an example of an in-place operator:
47
+ // add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
48
+ static bool isInplaceOp(const c10::FunctionSchema& schema) {
49
+ if (!schema.is_mutable() || schema.returns().size() != 1) {
50
+ return false;
51
+ }
52
+ // Check that the first argument is being written to
53
+ const AliasInfo* first_arg_alias_info = schema.arguments().begin()->alias_info();
54
+ if (!first_arg_alias_info || !first_arg_alias_info->isWrite()) {
55
+ return false;
56
+ }
57
+ // Check that none of the other args are being aliased
58
+ for (auto it = schema.arguments().begin() + 1; it != schema.arguments().end(); ++it) {
59
+ const AliasInfo* alias_info = it->alias_info();
60
+ if (alias_info) {
61
+ return false;
62
+ }
63
+ }
64
+ // Check that the first tensor is being returned (i.e., output has a (a!))
65
+ const AliasInfo* return_alias_info = schema.returns()[0].alias_info();
66
+ return return_alias_info && return_alias_info->isWrite();
67
+ }
68
+
69
+ static void warnFallback(const c10::FunctionSchema& schema) {
70
+ if (!globalContext().areVmapFallbackWarningsEnabled()) {
71
+ return;
72
+ }
73
+ TORCH_WARN("There is a performance drop because we have not yet implemented ",
74
+ "the batching rule for ", schema.operator_name(), ". ",
75
+ "You are using the legacy vmap prototype (torch._vmap_internals.vmap). ",
76
+ "If you are using torch.autograd.functional.{jacobian, hessian} ",
77
+ "or torch._vmap_internals.vmap: please switch to using ",
78
+ "torch.func.{jacrev, jacfwd, hessian} and/or torch.vmap instead ",
79
+ "for better operator coverage and performance improvements .");
80
+ }
81
+
82
+ // The general flow of the algorithm is as follows.
83
+ // - First, we figure out which arguments are BatchedTensors and save them
84
+ // to a vector. We also store a vector of which index of the arguments list
85
+ // each BatchedTensor appears in. This will be useful for bookkeeping later.
86
+ // - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors.
87
+ // This returns a vector of VmapPhysicalView that hold tensors that contain
88
+ // all of the collective batch dimensions at the front of the tensors.
89
+ // - Then, we attempt to call `op` once per slice of the inputs. To do this,
90
+ // we repeatedly we slice the input arguments (if they are BatchedTensors),
91
+ // put the sliced (or a not-sliced) version of the input onto the stack, invoke
92
+ // the operator, and then pop the results off the stack.
93
+ static void batchedTensorInplaceForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
94
+ const auto& schema = op.schema();
95
+ warnFallback(schema);
96
+
97
+ const auto num_arguments = static_cast<int64_t>(schema.arguments().size());
98
+ const auto arguments = torch::jit::last(stack, num_arguments);
99
+ const auto arguments_begin = stack->size() - num_arguments;
100
+
101
+ // `self` is the Tensor being modified in-place
102
+ Tensor self = arguments[0].toTensor();
103
+ const auto* self_impl = maybeGetBatchedImpl(self);
104
+ std::bitset<kVmapMaxTensorDims> self_vmap_levels;
105
+ if (self_impl) {
106
+ self_vmap_levels = createVmapLevelsBitset(self_impl->bdims());
107
+ }
108
+
109
+ // Figure out which arguments are BatchedTensor. Save them to a vector.
110
+ // For each BatchedTensor, also record what position of `arguments` they came from.
111
+ SmallVector<Tensor,kVmapTransformStaticInputSize> batched_tensor_inputs;
112
+ VmapDimVector batched_tensor_inputs_position;
113
+ for (const auto idx : c10::irange(arguments.size())) {
114
+ const auto& ivalue = arguments[idx];
115
+ if (!ivalue.isTensor()) {
116
+ continue;
117
+ }
118
+ const auto& tensor = ivalue.toTensor();
119
+ if (!tensor.defined()) {
120
+ continue;
121
+ }
122
+ const auto* batched = maybeGetBatchedImpl(tensor);
123
+ if (!batched) {
124
+ continue;
125
+ }
126
+
127
+ // NOTE: [vmap-incompatible in-place operations]
128
+ // In-place operations on `self` are not possible if there exists some vmap
129
+ // level `l` such that `self` is not being vmapped on that level but another
130
+ // argument is. For example, let B0 be a batch dim inside vmap and consider
131
+ // vmap(Tensor.add_, in_dims=(None, 0))(torch.ones(3), torch.ones(B0, 3))
132
+ // - self is torch.ones(3) and does not participate in this vmap
133
+ // - other is BatchedTensor(torch.ones(B0, 3))
134
+ // There's no way to do self.add_(other) because `other` has more elements
135
+ // elements than `self` due to being vmapped over.
136
+ //
137
+ // In the vmap fallback, we should error out when we detect this.
138
+ auto other_vmap_levels = createVmapLevelsBitset(batched->bdims());
139
+ if (self_vmap_levels != (self_vmap_levels | other_vmap_levels)) {
140
+ // Find one vmap level to complain about
141
+ auto additional_bdims = (self_vmap_levels | other_vmap_levels) ^ self_vmap_levels;
142
+ [[maybe_unused]] auto offending_level = llvm::findLastSet(additional_bdims.to_ulong());
143
+ // The following prints out "vmap: aten::add_(tensor, ...) is not possible",
144
+ // but it would be better to print out "tensor.add_(...) is not possible".
145
+ // Afaict there's no official way to get the add_ and there is no way to
146
+ // tell if an operator has method or function variants.
147
+ TORCH_CHECK(false,
148
+ "vmap: ", schema.name(), "(self, *extra_args) is not possible because ",
149
+ "there exists a Tensor `other` in extra_args that has more elements ",
150
+ "than `self`. This happened due to `other` being vmapped over but ",
151
+ "`self` not being vmapped over at level ", offending_level, ". ",
152
+ "Please try to use out-of-place operators instead of ", schema.name(), ". ",
153
+ "If said operator is being called inside the PyTorch framework, ",
154
+ "please file a bug report instead.");
155
+ }
156
+ batched_tensor_inputs.push_back(tensor);
157
+ batched_tensor_inputs_position.push_back(static_cast<int64_t>(idx));
158
+ }
159
+ TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty());
160
+
161
+ // MultiBatchVmapTransform the BatchedTensor arguments. This returns
162
+ // VmapPhysicalViews that contain all of the batch dimensions.
163
+ const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical(
164
+ batched_tensor_inputs);
165
+
166
+ // Compute the total number of batches
167
+ auto num_batch_dims = input_physical_views.front().numBatchDims();
168
+ auto first_physical_view_sizes = input_physical_views.front().tensor().sizes();
169
+ auto batch_sizes = ArrayRef<int64_t>(
170
+ first_physical_view_sizes.begin(), first_physical_view_sizes.begin() + num_batch_dims);
171
+ const auto num_batches = c10::multiply_integers(batch_sizes);
172
+ // Without a shape-checking API, we're unable to compute the correct shape of
173
+ // the output so we just error out.
174
+ TORCH_CHECK(num_batches > 0,
175
+ "Batching rule not implemented for ", schema.operator_name(), ". ",
176
+ "The fallback path does not support vmap over dims of size 0.");
177
+
178
+ // Strategy: For each batch, we are going to push slices (where applicable)
179
+ // of the arguments onto `stack`, and call `op`.
180
+ for (const auto linear_idx : c10::irange(num_batches)) {
181
+ auto index = computeIndex(linear_idx, batch_sizes);
182
+ auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin();
183
+ auto input_physical_views_iter = input_physical_views.begin();
184
+ for (const auto arg_idx : c10::irange(num_arguments)) {
185
+ // We assume that torch::jit::Stack is backed by vector<IValue> for
186
+ // simplicity. When that is not the case, this code should be updated.
187
+ const auto& argument = (*stack)[arguments_begin + arg_idx];
188
+ if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end()
189
+ || arg_idx != *batched_tensor_inputs_pos_iter) {
190
+ // argument isn't a BatchedTensor
191
+ torch::jit::push(stack, argument);
192
+ continue;
193
+ }
194
+ // argument is a BatchedTensor
195
+ TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end());
196
+ const auto& physical_view_for_argument = *input_physical_views_iter;
197
+ torch::jit::push(stack, physical_view_for_argument.tensor().index(index));
198
+ batched_tensor_inputs_pos_iter++;
199
+ input_physical_views_iter++;
200
+ }
201
+
202
+ op.callBoxed(stack);
203
+ torch::jit::drop(stack, 1);
204
+ }
205
+
206
+ // Return the tensor that was written to in-place
207
+ torch::jit::drop(stack, num_arguments);
208
+ torch::jit::push(stack, self);
209
+ }
210
+
211
+ static Tensor safeStack(TensorList tensors) {
212
+ auto is_defined = [](const Tensor& t) { return t.defined(); };
213
+ if (std::all_of(tensors.begin(), tensors.end(), is_defined)) {
214
+ return at::stack(tensors);
215
+ }
216
+ // NOTE [vmap through backward and undefined grad]
217
+ // While vmapping through backward functions (to compute batched grad), it
218
+ // is possible for the backward function to return an undefined grad for some
219
+ // grad_input for each example. In that case, we return an undefined grad.
220
+ //
221
+ // It is theoretically possible for *some* of the examples to produce an
222
+ // undefined grad (a kernel could peek at the gradient values and return an
223
+ // undefined tensor if it determines the gradient is full of zeros). We
224
+ // could handle this by treating the undefined grad as a zero-filled tensor
225
+ // of the correct shape while stacking the tensors together. However I expect
226
+ // this to happen very rarely (I have not been able to find an example in our
227
+ // codebase) so we just error out in this case.
228
+ if (std::none_of(tensors.begin(), tensors.end(), is_defined)) {
229
+ return Tensor();
230
+ }
231
+ TORCH_CHECK(false,
232
+ "vmap: slow fallback received a mix of undefined and defined tensors ",
233
+ "as the result of an operation. This is not supported, please file us ",
234
+ "an issue on github.");
235
+ }
236
+
237
+ // The general flow of the algorithm is as follows.
238
+ // - First, we figure out which arguments are BatchedTensors and save them
239
+ // to a vector. We also store a vector of which index of the arguments list
240
+ // each BatchedTensor appears in. This will be useful for bookkeeping later.
241
+ // - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors.
242
+ // This returns a vector of VmapPhysicalView that hold tensors that contain
243
+ // all of the collective batch dimensions at the front of the tensors.
244
+ // - Then, we attempt to call `op` once per slice of the inputs. To do this,
245
+ // we repeatedly we slice the input arguments (if they are BatchedTensors),
246
+ // put the sliced (or a not-sliced) version of the input onto the stack, invoke
247
+ // the operator, and then pop the results off the stack.
248
+ // - Each result obtained from the previous step is a slice of the total result,
249
+ // so we stack those tensors together to form the final result.
250
+ void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
251
+ const auto& schema = op.schema();
252
+ const auto num_returns = schema.returns().size();
253
+
254
+ if (isInplaceOp(schema)) {
255
+ batchedTensorInplaceForLoopFallback(op, stack);
256
+ return;
257
+ }
258
+ TORCH_CHECK(!schema.is_mutable() && !schema.hasAnyAliasInfo(),
259
+ "Batching rule not implemented for ", schema.operator_name(), "; ",
260
+ "the fallback path doesn't work on out= or view ops.");
261
+ TORCH_CHECK(areAllReturnsTensors(schema) && !areAnyArgumentsTensorList(schema),
262
+ "Batching rule not implemented for ", schema.operator_name(), ". ",
263
+ "We could not generate a fallback.");
264
+ TORCH_CHECK(num_returns >= 1,
265
+ "Batching rule not implemented for ", schema.operator_name(), ". ",
266
+ "The fallback path does not support operations with no returns.");
267
+ warnFallback(schema);
268
+
269
+ const auto num_arguments = static_cast<int64_t>(schema.arguments().size());
270
+ const auto arguments = torch::jit::last(stack, num_arguments);
271
+ const auto arguments_begin = stack->size() - num_arguments;
272
+
273
+ // Figure out which arguments are BatchedTensor. Save them to a vector.
274
+ // For each BatchedTensor, also record what position of `arguments` they came from.
275
+ SmallVector<Tensor,kVmapTransformStaticInputSize> batched_tensor_inputs;
276
+ VmapDimVector batched_tensor_inputs_position;
277
+ for (const auto idx : c10::irange(arguments.size())) {
278
+ const auto& ivalue = arguments[idx];
279
+ if (!ivalue.isTensor()) {
280
+ continue;
281
+ }
282
+ const auto& tensor = ivalue.toTensor();
283
+ if (!tensor.defined()) {
284
+ continue;
285
+ }
286
+ const auto* batched = maybeGetBatchedImpl(tensor);
287
+ if (!batched) {
288
+ continue;
289
+ }
290
+ batched_tensor_inputs.push_back(tensor);
291
+ batched_tensor_inputs_position.push_back(static_cast<int64_t>(idx));
292
+ }
293
+ TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty());
294
+
295
+ // MultiBatchVmapTransform the BatchedTensor arguments. This returns
296
+ // VmapPhysicalViews that contain all of the batch dimensions.
297
+ const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical(
298
+ batched_tensor_inputs);
299
+
300
+ // Compute the total number of batches
301
+ auto num_batch_dims = input_physical_views.front().numBatchDims();
302
+ auto some_sizes = input_physical_views.front().tensor().sizes();
303
+ auto batch_sizes = ArrayRef<int64_t>(some_sizes.begin(), some_sizes.begin() + num_batch_dims);
304
+ const auto num_batches = c10::multiply_integers(batch_sizes);
305
+ // Without a shape-checking API, we're unable to compute the correct shape of
306
+ // the output so we just error out.
307
+ TORCH_CHECK(num_batches > 0,
308
+ "Batching rule not implemented for ", schema.operator_name(), ". ",
309
+ "The fallback path does not support vmap over dims of size 0.");
310
+
311
+ // Strategy: For each batch, we are going to push slices (where applicable)
312
+ // of the arguments onto `stack`, call `op`, and store the result in
313
+ // `output_shards`.
314
+ //
315
+ // NOTE: [Output shards layout]
316
+ // Assume that the operator has three outputs: a, b, c.
317
+ // The layout of output_shards is as follows:
318
+ // [ a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3]
319
+ // This is so that we can call at::stack([a0...a3]), at::stack([b0...b3])
320
+ // more easily in the next step.
321
+ std::vector<Tensor> output_shards(num_batches * num_returns);
322
+
323
+ for (const auto linear_idx : c10::irange(num_batches)) {
324
+ auto index = computeIndex(linear_idx, batch_sizes);
325
+ auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin();
326
+ auto input_physical_views_iter = input_physical_views.begin();
327
+ for (const auto arg_idx : c10::irange(num_arguments)) {
328
+ // We assume that torch::jit::Stack is backed by vector<IValue> for
329
+ // simplicity. When that is not the case, this code should be updated.
330
+ const auto& argument = (*stack)[arguments_begin + arg_idx];
331
+ if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end()
332
+ || arg_idx != *batched_tensor_inputs_pos_iter) {
333
+ // argument isn't a BatchedTensor
334
+ torch::jit::push(stack, argument);
335
+ continue;
336
+ }
337
+ // argument is a BatchedTensor
338
+ TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end());
339
+ const auto& physical_view_for_argument = *input_physical_views_iter;
340
+ torch::jit::push(stack, physical_view_for_argument.tensor().index(index));
341
+ batched_tensor_inputs_pos_iter++;
342
+ input_physical_views_iter++;
343
+ }
344
+
345
+ op.callBoxed(stack);
346
+
347
+ // Store the result into `output_shards`. See NOTE: [Output shards layout]
348
+ // to learn about the details of how we store the shards.
349
+ const auto returns = torch::jit::last(stack, num_returns);
350
+ for (const auto return_idx : c10::irange(returns.size())) {
351
+ output_shards[num_batches * return_idx + linear_idx] = returns[return_idx].toTensor();
352
+ }
353
+ torch::jit::drop(stack, num_returns);
354
+ }
355
+
356
+ // For each output Tensor, stack the shards of the tensor together to form a return
357
+ torch::jit::drop(stack, num_arguments);
358
+ auto output_shards_chunks = MatrixRef<Tensor>(output_shards, num_batches);
359
+ for (const auto return_idx : c10::irange(num_returns)) {
360
+ auto shards = output_shards_chunks[return_idx];
361
+ auto flat_output = safeStack(shards);
362
+ // See NOTE [vmap through backward and undefined grad]
363
+ if (!flat_output.defined()) {
364
+ torch::jit::push(stack, flat_output);
365
+ continue;
366
+ }
367
+ VmapDimVector output_sizes(batch_sizes);
368
+ output_sizes.insert(
369
+ output_sizes.end(),
370
+ flat_output.sizes().begin() + 1,
371
+ flat_output.sizes().end());
372
+ torch::jit::push(
373
+ stack,
374
+ input_physical_views.front().getPhysicalToLogicalMap().apply(flat_output.view(output_sizes)));
375
+ }
376
+ }
377
+
378
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/ATen.h>
3
+ #include <ATen/core/op_registration/op_registration.h>
4
+ #include <torch/library.h>
5
+
6
+ namespace at {
7
+
8
+ // If an operator doesn't have a batching rule implemented then we fallback
9
+ // to this implementation. The fallback only works on out-of-place operators
10
+ // that return only tensors with new memory. (e.g., no in-place operators, no
11
+ // view operations).
12
+ //
13
+ // The fallback effectively takes all of the BatchedTensors in `stack`, slices
14
+ // them, and runs `op` on all of the corresponding slices to produce slices
15
+ // of the outputs. The output slices then get `torch.stack`ed to create the
16
+ // final returns.
17
+ //
18
+ // The performance of the fallback is not very good because it introduces an
19
+ // extra copy from stacking the sliced outputs. Because of this, we prefer to
20
+ // write batching rules for operators whenever possible.
21
+ void batchedTensorForLoopFallback(
22
+ const c10::OperatorHandle& op,
23
+ torch::jit::Stack* stack);
24
+
25
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.cpp ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/LegacyBatchedTensorImpl.h>
2
+
3
+ #include <ATen/WrapDimUtils.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/irange.h>
6
+
7
+ namespace at {
8
+
9
+ BatchedTensorImpl::BatchedTensorImpl(Tensor value, BatchDims bdims)
10
+ : TensorImpl(
11
+ c10::DispatchKeySet(DispatchKey::Batched),
12
+ value.dtype(),
13
+ value.device()
14
+ )
15
+ , value_(std::move(value))
16
+ , bdims_(std::move(bdims))
17
+ {
18
+ TORCH_INTERNAL_ASSERT(value_.defined());
19
+ set_storage_access_should_throw();
20
+ set_custom_sizes_strides(SizesStridesPolicy::CustomStrides);
21
+ checkInvariants();
22
+
23
+ const auto public_dims = value_.dim() - bdims_.size();
24
+ const auto value_sizes = value_.sizes();
25
+ const auto value_strides = value_.strides();
26
+ sizes_and_strides_.resize(public_dims);
27
+ for (const auto dim : c10::irange(public_dims)) {
28
+ auto actual_dim = actualDim(static_cast<int64_t>(dim), /*wrap_dim=*/false);
29
+ sizes_and_strides_.size_at_unchecked(dim) = value_sizes.at(actual_dim);
30
+ sizes_and_strides_.stride_at_unchecked(dim) = value_strides.at(actual_dim);
31
+ }
32
+ storage_offset_ = value_.storage_offset();
33
+ refresh_numel();
34
+ refresh_contiguous();
35
+ }
36
+
37
+ int64_t BatchedTensorImpl::actualDim(int64_t dim, bool wrap_dim) const {
38
+ if (wrap_dim) {
39
+ const auto ndim = sizes_and_strides_.size();
40
+ dim = maybe_wrap_dim(dim, static_cast<int64_t>(ndim));
41
+ }
42
+ auto is_bdim = createBatchDimBitset(bdims_);
43
+
44
+ // Example: assume dim = 3, and is_bdim = 10010011000...
45
+ // The 1's are batch dims and 0's are normal dims of the underlying value_ Tensor.
46
+ // actualDim gives us the index of `dim` in the `value_` Tensor, which is equivalent
47
+ // to asking "where does the 3rd (0-indexed) zero occur in the bitset?".
48
+ // The answer to that is index 5.
49
+ //
50
+ // TODO(rzou): the PDEP instruction does exactly this
51
+ // (https://stackoverflow.com/questions/7669057/find-nth-set-bit-in-an-int)
52
+ // but it might require newer (>= ~2015) CPUs. We should clean this up
53
+ // if/when we have dropped support for older CPUs.
54
+ int64_t non_bdim_count = 0;
55
+ for (const auto actual_dim : c10::irange(kVmapMaxTensorDims)) {
56
+ if (is_bdim[actual_dim]) {
57
+ continue;
58
+ }
59
+ if (non_bdim_count == dim) {
60
+ return actual_dim;
61
+ }
62
+ non_bdim_count++;
63
+ }
64
+ // If we hit this assert, then that means
65
+ // `non_bdim_count` + #num_bdims > kVmapMaxTensorDims. We restrict the number
66
+ // of dims a BatchedTensorImpl can have to kVmapMaxTensorDims so this should
67
+ // never be hit.
68
+ TORCH_INTERNAL_ASSERT(false);
69
+ }
70
+
71
+ void BatchedTensorImpl::checkInvariants() const {
72
+ int64_t prev_level = -1;
73
+ for (const auto& bdim : bdims_) {
74
+ TORCH_INTERNAL_ASSERT(bdim.level() > prev_level);
75
+ prev_level = bdim.level();
76
+ }
77
+ }
78
+
79
+ // The following are publicly exposed as methods of Tensor
80
+
81
+ IntArrayRef BatchedTensorImpl::strides_custom() const {
82
+ return strides_default();
83
+ }
84
+
85
+ // TODO: implement proper contiguity on batched tensor, then put
86
+ // sizes_strides_policy back to Default
87
+ c10::SymBool BatchedTensorImpl::sym_is_contiguous_custom(at::MemoryFormat memory_format) const {
88
+ TORCH_CHECK(memory_format == MemoryFormat::Contiguous,
89
+ "NYI: querying is_contiguous inside of vmap for memory_format ",
90
+ "other than torch.contiguous_format");
91
+ return is_contiguous_;
92
+ }
93
+
94
+ // The following are some internal inherited methods that we do not support.
95
+ // They should never get called.
96
+ void BatchedTensorImpl::set_size(int64_t dim, int64_t new_size) {
97
+ TORCH_INTERNAL_ASSERT(false, "Can't set_size for BatchedTensorImpl");
98
+ }
99
+ void BatchedTensorImpl::set_stride(int64_t dim, int64_t new_stride) {
100
+ TORCH_INTERNAL_ASSERT(false, "Can't set_stride for BatchedTensorImpl");
101
+ }
102
+ void BatchedTensorImpl::set_storage_offset(int64_t storage_offset) {
103
+ TORCH_INTERNAL_ASSERT(false, "Can't set_storage_offset for BatchedTensorImpl");
104
+ }
105
+ #ifdef DEBUG
106
+ bool BatchedTensorImpl::has_storage() const {
107
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!storage_, "BatchedTensorImpl assumes that storage_ is never set");
108
+ return false;
109
+ }
110
+ #endif
111
+
112
+ const char* BatchedTensorImpl::tensorimpl_type_name() const {
113
+ return "BatchedTensorImpl";
114
+ }
115
+
116
+ Tensor makeBatched(Tensor tensor, BatchDims bdims) {
117
+ TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor));
118
+ auto tensor_dim = tensor.dim();
119
+ TORCH_CHECK(
120
+ tensor_dim <= kVmapMaxTensorDims,
121
+ "vmap only supports tensors of dimensionality up to ", kVmapMaxTensorDims,
122
+ "; got a tensor with dim ", tensor_dim);
123
+ TORCH_INTERNAL_ASSERT(
124
+ std::all_of(bdims.begin(), bdims.end(),
125
+ [](const BatchDim& bdim) { return bdim.level() < kVmapNumLevels; }),
126
+ "We only support up to ", kVmapNumLevels, " nested vmaps");
127
+ return at::detail::make_tensor<BatchedTensorImpl>(std::move(tensor), std::move(bdims));
128
+ }
129
+
130
+ Tensor addBatchDim(Tensor tensor, int64_t level, int64_t dim) {
131
+ const auto* batched = maybeGetBatchedImpl(tensor);
132
+ if (!batched) {
133
+ BatchDims bdims;
134
+ bdims.emplace_back(level, dim);
135
+ return at::detail::make_tensor<BatchedTensorImpl>(std::move(tensor), std::move(bdims));
136
+ }
137
+ BatchDims new_bdims(batched->bdims().begin(), batched->bdims().end());
138
+ auto actual_bdim = batched->actualDim(dim, /*wrap_dim=*/true);
139
+ new_bdims.emplace_back(level, actual_bdim);
140
+ return makeBatched(batched->value(), std::move(new_bdims));
141
+ }
142
+
143
+ bool inplaceIsVmapCompatible(const Tensor& self, const Tensor& other) {
144
+ const auto* other_batched = maybeGetBatchedImpl(other);
145
+ if (!other_batched) {
146
+ return true;
147
+ }
148
+ const auto* self_batched = maybeGetBatchedImpl(self);
149
+ if (!self_batched) {
150
+ // self is not batched but other is batched
151
+ return false;
152
+ }
153
+ auto self_levels = createVmapLevelsBitset(self_batched->bdims());
154
+ auto other_levels = createVmapLevelsBitset(other_batched->bdims());
155
+ return self_levels == (self_levels | other_levels);
156
+ }
157
+
158
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.h ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <bitset>
4
+
5
+ #include <ATen/ArrayRef.h>
6
+ #include <ATen/SmallVector.h>
7
+ #include <ATen/Tensor.h>
8
+
9
+ namespace at {
10
+
11
+ // We assume this in a few other places in the codebase,
12
+ // but there isn't a centralized definition.
13
+ constexpr int64_t kVmapMaxTensorDims = 64;
14
+
15
+ // The valid vmap levels range from [0, 64). This effectively means that we
16
+ // support a maximum of 64 nested vmaps.
17
+ constexpr int64_t kVmapNumLevels = 64;
18
+
19
+ // Store this number of elements of BatchDims on the stack. Most people will
20
+ // probably use <= 5 nested vmaps, but adjust this number as necessary.
21
+ constexpr int64_t kBatchDimsStackSize = 5;
22
+
23
+ // a BatchDim represents a "private" dimension on a Tensor created inside of
24
+ // vmap. It is a (level, dim) tuple, with the `dim` indicating which dimension
25
+ // is being vmap'ed over and the `level` being an identifier for which vmap
26
+ // said dimension was created inside. The `dim` corresponds to a "physical
27
+ // dim" - it is a dimension index on the underlying physical tensor that is
28
+ // being vmapped over.
29
+ struct BatchDim {
30
+ BatchDim(int64_t level, int64_t dim) : dim_(dim), level_(level) {}
31
+ int64_t dim() const {
32
+ return dim_;
33
+ }
34
+ int64_t level() const {
35
+ return level_;
36
+ }
37
+
38
+ private:
39
+ int64_t dim_;
40
+ int64_t level_;
41
+ };
42
+
43
+ using BatchDims = SmallVector<BatchDim, kBatchDimsStackSize>;
44
+ using BatchDimsRef = ArrayRef<BatchDim>;
45
+
46
+ // A BatchedTensorImpl holds an underlying Tensor and a list of BatchDim
47
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
48
+ // BatchedTensorImpl.
49
+ //
50
+ // The batch dimensions are treated as being "private"; they are not
51
+ // user-visible. For example, in the following Tensor,
52
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), [(lvl=1, dim=0), (lvl=2, dim=1)])
53
+ // dimensions 0 and 1 are batch dimensions.
54
+ //
55
+ // bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public)
56
+ // dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7)
57
+ // tensor.
58
+ struct TORCH_API BatchedTensorImpl : public c10::TensorImpl {
59
+ explicit BatchedTensorImpl(Tensor value, BatchDims bdims);
60
+
61
+ // Returns a reference to BatchDims that represent which dimensions of this
62
+ // tensor are private.
63
+ BatchDimsRef bdims() const {
64
+ return bdims_;
65
+ }
66
+
67
+ // BatchedTensorImpl wraps a Tensor
68
+ const Tensor& value() const {
69
+ return value_;
70
+ }
71
+
72
+ // Given a public dimension index, return the dimension index in the
73
+ // underlying value() tensor. For example, if we have
74
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), [(lvl=1, dim=0), (lvl=2,
75
+ // dim=2)])
76
+ // bt.actualDim(0) -> 1
77
+ // bt.actualDim(1) -> 3
78
+ // bt.actualDim(2) -> Error
79
+ int64_t actualDim(int64_t dim, bool wrap_dim = true) const;
80
+
81
+ // We have to override this because we opted into CustomStrides
82
+ IntArrayRef strides_custom() const override;
83
+ // Override a bunch of methods inherited from TensorImpl to return error
84
+ // messages.
85
+ c10::SymBool sym_is_contiguous_custom(
86
+ at::MemoryFormat memory_format) const override;
87
+ void set_size(int64_t dim, int64_t new_size) override;
88
+ void set_stride(int64_t dim, int64_t new_stride) override;
89
+ void set_storage_offset(int64_t storage_offset) override;
90
+ #ifdef DEBUG
91
+ bool has_storage() const override;
92
+ #endif
93
+
94
+ private:
95
+ // see NOTE: [BatchedTensorImpl levels invariant]
96
+ void checkInvariants() const;
97
+ const char* tensorimpl_type_name() const override;
98
+
99
+ Tensor value_;
100
+
101
+ // Note: [BatchedTensorImpl levels invariant]
102
+ // There is an invariant that the BatchDims must be stored in increasing
103
+ // `level` order. That is, for i < j, bdims_[i].level must be less than
104
+ // bdims_[j].level.
105
+ BatchDims bdims_;
106
+ };
107
+
108
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
109
+ // BatchedTensorImpl.
110
+ inline bool isBatchedTensor(const Tensor& tensor) {
111
+ return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::Batched);
112
+ }
113
+
114
+ // It is unsafe to call this on a Tensor that is not backed by a
115
+ // BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible.
116
+ inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) {
117
+ return static_cast<BatchedTensorImpl*>(tensor.unsafeGetTensorImpl());
118
+ }
119
+
120
+ inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) {
121
+ if (!isBatchedTensor(tensor)) {
122
+ return nullptr;
123
+ }
124
+ return unsafeGetBatchedImpl(tensor);
125
+ }
126
+
127
+ // Returns a bitset. If bit i is set, then that means dim i is a batchdim.
128
+ inline std::bitset<kVmapMaxTensorDims> createBatchDimBitset(
129
+ BatchDimsRef bdims) {
130
+ std::bitset<kVmapMaxTensorDims> is_bdim;
131
+ for (const auto& bdim : bdims) {
132
+ is_bdim.set(bdim.dim());
133
+ }
134
+ return is_bdim;
135
+ }
136
+
137
+ // Creates a bitset for all of the levels present in `bdims`
138
+ inline std::bitset<kVmapNumLevels> createVmapLevelsBitset(BatchDimsRef bdims) {
139
+ std::bitset<kVmapNumLevels> result;
140
+ for (const auto& bdim : bdims) {
141
+ result.set(bdim.level());
142
+ }
143
+ return result;
144
+ }
145
+
146
+ inline std::ostream& operator<<(std::ostream& out, const BatchDim& bdim) {
147
+ out << "(lvl=" << bdim.level() << ", dim=" << bdim.dim() << ')';
148
+ return out;
149
+ }
150
+
151
+ // Use this to construct a BatchedTensor from a regular Tensor
152
+ TORCH_API Tensor makeBatched(Tensor tensor, BatchDims bdims);
153
+
154
+ // Adds a batch dim to `tensor`, returning a BatchedTensor
155
+ TORCH_API Tensor addBatchDim(Tensor tensor, int64_t level, int64_t dim);
156
+
157
+ // Checks if an inplace operation on self and other is "vmap compatible".
158
+ // See NOTE: [vmap-incompatible in-place operations] for the definition of this.
159
+ TORCH_API bool inplaceIsVmapCompatible(const Tensor& self, const Tensor& other);
160
+
161
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyBatchingRegistrations.cpp ADDED
@@ -0,0 +1,1291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/library.h>
2
+ #include <ATen/LegacyVmapTransforms.h>
3
+ #include <ATen/LegacyBatchedFallback.h>
4
+ #include <ATen/RedispatchFunctions.h>
5
+ #include <ATen/native/ResizeCommon.h>
6
+ #include <c10/util/irange.h>
7
+
8
+ #include <utility>
9
+
10
+ namespace at {
11
+
12
+ // NOTE: [What is a batching rule?]
13
+ //
14
+ // A *batching rule* implements the logic of how to call an operator on inputs
15
+ // that have zero or more additional batch dimensions. When one does a vmap, the
16
+ // dimension(s) being vmap'ed over get recorded as batch dimensions.
17
+ //
18
+ // For example, vmap(torch.add)(x, y)
19
+ // 1. wraps `x` into batched_x = BatchedTensor(x, bdims=[(lvl=1, dim=0)];
20
+ // 2. wraps `y` into batched_y = BatchedTensor(y, bdims=[(lvl=1, dim=0)];
21
+ // 3. and then runs `torch.add(batched_x, batched_y)`.
22
+
23
+ // NOTE: [When should I add a batching rule?]
24
+ // When you are adding a new operator, you'll need to add a batching rule so
25
+ // that vmap can work efficiently with said operator. If you do not, we'll attempt
26
+ // to generate a slow fallback for the batching rule.
27
+
28
+ // NOTE: [How to write batching rules?]
29
+ // The signature of a batching rule should look like exactly like the C++ signature
30
+ // of its operator.
31
+ //
32
+ // First, see NOTE: [Logical vs physical args] in VmapTransforms.h for terminology.
33
+ //
34
+ // At a high level, what a batching rule does is the following:
35
+ // 1. Converts (logical) BatchedTensors to views on physical tensors.
36
+ // 2. Converts logical arguments (e.g. dimension indexes, shapes) to physical
37
+ // arguments that correspond to the physical tensors.
38
+ // 3. Calls at:: operations on the physical tensors and arguments to produce
39
+ // some physical results.
40
+ // 4. Converts physical results back to BatchedTensors.
41
+ //
42
+ // Steps 1, 2, and 4 differ for operators with different batching behaviors. When
43
+ // writing a new batching rule, please select a VmapTransform that matches the
44
+ // batching behavior of your operation. The VmapTransform provides helper functions
45
+ // to do steps (1), (2), and (4).
46
+ // (see NOTE: [What is an VmapTransform?] in VmapTransforms.h)
47
+
48
+ // Note: [Future plans]
49
+ // The API for writing a batching rule isn't stable. In the future, we'd like
50
+ // to think about the problem of translating these batching rules to TorchScript.
51
+ // Ideally batching rules in eager mode vs TorchScript would look pretty similar,
52
+ // if not use the same mechanism. In order to accomplish that we might have to
53
+ // do some refactoring.
54
+
55
+ namespace{
56
+
57
+ // PyTorch allows operations to specify dim 0 and dim -1 on a scalar tensor.
58
+ bool is_allowed_dim_on_scalar_tensor(int64_t dim) {
59
+ return dim == 0 || dim == -1;
60
+ }
61
+
62
+ Tensor sum_batching_rule(const Tensor& self, OptionalIntArrayRef opt_dims, bool keepdim, std::optional<ScalarType> dtype) {
63
+ if (opt_dims.has_value()) {
64
+ auto dims = opt_dims.value();
65
+ // PyTorch has a special case where sum(scalar_tensor, dim=0) does not fail
66
+ // and instead returns a new scalar tensor (this also happens for dim=-1)
67
+ // If the following happens:
68
+ // >>> x = torch.randn(B0) # the per-examples are all scalars
69
+ // >>> vmap(partial(torch.sum, dim=0), x)
70
+ // then we replicate the behavior of sum(scalar_tensor, dim=0).
71
+ if (/*logical*/self.dim() == 0 && (dims.empty() || (dims.size() == 1 && is_allowed_dim_on_scalar_tensor(dims[0])))) {
72
+ return self.clone();
73
+ }
74
+ }
75
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
76
+ auto dims_physical = self_physical.getPhysicalDims(opt_dims);
77
+ auto result = at::sum(self_physical.tensor(), dims_physical, keepdim, dtype);
78
+ return self_physical.getPhysicalToLogicalMap().apply(result);
79
+ }
80
+
81
+ bool isPhysicalScalarTensor(const Tensor& logical_tensor) {
82
+ if (logical_tensor.dim() > 0) {
83
+ return false;
84
+ }
85
+ auto* batched = maybeGetBatchedImpl(logical_tensor);
86
+ if (batched) {
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+
92
+ template <typename F, F Func, typename... ExtraArgs>
93
+ Tensor binary_pointwise_batching_rule(
94
+ const Tensor& self, const Tensor& other, ExtraArgs... args) {
95
+ if (self.dim() > 0 && other.dim() > 0) {
96
+ auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other});
97
+ auto result = Func(physical_args[0].tensor(), physical_args[1].tensor(), args...);
98
+ return physical_args[0].getPhysicalToLogicalMap().apply(result);
99
+ }
100
+ if (isPhysicalScalarTensor(self)) {
101
+ auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other);
102
+ auto result = Func(self, other_physical.tensor(), args...);
103
+ return other_physical.getPhysicalToLogicalMap().apply(result);
104
+ }
105
+ if (isPhysicalScalarTensor(other)) {
106
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
107
+ auto result = Func(self_physical.tensor(), other, args...);
108
+ return self_physical.getPhysicalToLogicalMap().apply(result);
109
+ }
110
+
111
+ // At this point, we know at least one of the operands is a logical Scalar tensor.
112
+ // Here we must emulate TensorIterator's special behavior on Scalars.
113
+ //
114
+ // As a motivating example, consider the following:
115
+ // x = torch.randn(3, 10)
116
+ // y = torch.randn(3, dtype=torch.double)
117
+ // vmap(torch.mul)(torch.randn(3, 10), torch.randn(3, dtype=torch.double))
118
+ //
119
+ // At a per-example level, we are adding FloatTensor[10] and DoubleTensor[];
120
+ // Type Promotion dictates that the result should be FloatTensor[10].
121
+ // This means we cannot directly pass the physical tensors (x and y) to
122
+ // TensorIterator (if we did, it would promote them to DoubleTensor).
123
+ //
124
+ // FIXME(rzou): I didn't want to go down the slippery slope of emulating
125
+ // everything TensorIterator does (it would be better to refactor out the
126
+ // TensorIterator logic). The one thing that this code doesn't handle
127
+ // is cross-device logical scalar tensors.
128
+ // cpu_tensor = torch.randn(3)
129
+ // cuda_tensor = torch.randn(3, 10, device='cuda')
130
+ // vmap(torch.mul)(cpu_tensor, cuda_tensor)
131
+ //
132
+ // At a per-example level, we are adding CPUTensor[] and CUDATensor[10].
133
+ // TensorIterator allows for this cross-device operation because one of the
134
+ // tensors is a Scalar CPU tensor. However, the following code will throw an
135
+ // error in that case. I don't expect to see many use cases for this, so
136
+ // this is probably fine as-is.
137
+ auto logical_self = self;
138
+ auto logical_other = other;
139
+ auto result_type = at::native::result_type(logical_self, logical_other);
140
+ if (logical_self.scalar_type() != result_type) {
141
+ logical_self = logical_self.to(result_type);
142
+ }
143
+ if (logical_other.scalar_type() != result_type) {
144
+ logical_other = logical_other.to(result_type);
145
+ }
146
+ auto physical_args = BroadcastingVmapTransform::logicalToPhysical(
147
+ {std::move(logical_self), std::move(logical_other)});
148
+ auto result = Func(physical_args[0].tensor(), physical_args[1].tensor(), args...);
149
+ return physical_args[0].getPhysicalToLogicalMap().apply(result);
150
+ }
151
+
152
+ Tensor expand_batching_rule(const Tensor& self, IntArrayRef size, bool implicit) {
153
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
154
+ auto size_physical = self_physical.getPhysicalShape(size);
155
+ auto self_physical_dim = self_physical.tensor().dim();
156
+
157
+ TORCH_CHECK(self_physical_dim <= static_cast<int64_t>(size_physical.size()),
158
+ "expand: the number of sizes provided (", /*logical*/size.size(), ") ",
159
+ "must be greater or equal to the number of dimensions in the tensor (",
160
+ /*logical dim*/self.dim(), ")");
161
+
162
+ if (self_physical_dim == static_cast<int64_t>(size_physical.size())) {
163
+ auto result = self_physical.tensor().expand(size_physical, implicit);
164
+ return self_physical.getPhysicalToLogicalMap().apply(result);
165
+ }
166
+
167
+ TORCH_INTERNAL_ASSERT(self_physical_dim < static_cast<int64_t>(size_physical.size()));
168
+ // Here, we know we are expanding a (logical) tensor to a larger number
169
+ // of dimensions. We have to be careful because we can't call expand directly
170
+ // due to the presence of batch dimensions.
171
+ //
172
+ // As an example, let B0 be a batch dimension and consider expand(Tensor[B0, 3], [2, 3]).
173
+ // The result should be a tensor of size [B0, 2, 3].
174
+ // A physical view of size [B0, 3] can't directly be expanded to size [B0, 2, 3]
175
+ // so the strategy here is to view it first as a tensor of size [B0, 1, 3] and
176
+ // then expand.
177
+ auto self_physical_size = self_physical.tensor().sizes();
178
+ auto extra_dims = size_physical.size() - self_physical_dim;
179
+ VmapDimVector view_shape(size_physical.size(), 1);
180
+ std::copy(self_physical_size.begin(),
181
+ self_physical_size.begin() + self_physical.numBatchDims(),
182
+ view_shape.begin());
183
+ std::copy(self_physical_size.begin() + self_physical.numBatchDims(),
184
+ self_physical_size.end(),
185
+ view_shape.begin() + self_physical.numBatchDims() + extra_dims);
186
+ auto result = self_physical.tensor().view(view_shape).expand(size_physical, implicit);
187
+ return self_physical.getPhysicalToLogicalMap().apply(result);
188
+ }
189
+
190
+ std::vector<Tensor> chunk_batching_rule(const Tensor& self, int64_t chunks, int64_t dim) {
191
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
192
+ auto dim_physical = self_physical.getPhysicalDim(dim);
193
+ auto result = at::chunk(self_physical.tensor(), chunks, dim_physical);
194
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
195
+ return result;
196
+ }
197
+
198
+ Tensor clamp_batching_rule(const Tensor& self, const std::optional<Scalar>& min, const std::optional<Scalar>& max) {
199
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
200
+ auto result = at::clamp(self_physical.tensor(), min, max);
201
+ return self_physical.getPhysicalToLogicalMap().apply(result);
202
+ }
203
+
204
+ Tensor clamp_min_batching_rule(const Tensor& self, const Scalar& min) {
205
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
206
+ auto result = at::clamp_min(self_physical.tensor(), min);
207
+ return self_physical.getPhysicalToLogicalMap().apply(result);
208
+ }
209
+
210
+ Tensor clamp_max_batching_rule(const Tensor& self, const Scalar& max) {
211
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
212
+ auto result = at::clamp_max(self_physical.tensor(), max);
213
+ return self_physical.getPhysicalToLogicalMap().apply(result);
214
+ }
215
+
216
+ std::vector<Tensor> tensor_split_sections_batching_rule(const Tensor& self, int64_t sections, int64_t dim) {
217
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
218
+ auto dim_physical = self_physical.getPhysicalDim(dim);
219
+ auto result = at::tensor_split(self_physical.tensor(), sections, dim_physical);
220
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
221
+ return result;
222
+ }
223
+
224
+ std::vector<Tensor> tensor_split_indices_batching_rule(const Tensor& self, IntArrayRef indices, int64_t dim) {
225
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
226
+ auto dim_physical = self_physical.getPhysicalDim(dim);
227
+ auto result = at::tensor_split(self_physical.tensor(), indices, dim_physical);
228
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
229
+ return result;
230
+ }
231
+
232
+ Tensor unsqueeze_batching_rule(const Tensor& self, int64_t dim) {
233
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
234
+ // NB: unsqueeze has some special handling of its `dim` argument so we can't call
235
+ // self_physical.getPhysicalDim directly. In particular, native::unsqueeze
236
+ // wraps the dim to (the logical dimension) + 1, so we need to do that here too.
237
+ // https://github.com/pytorch/pytorch/blob/b623bdeabb0aa8da44285d303246e7f8ac06c2a9/aten/src/ATen/native/TensorShape.cpp#L1413
238
+ auto dim_physical =
239
+ self_physical.numBatchDims() + maybe_wrap_dim(dim, /*logical_dim*/self.dim() + 1);
240
+ auto result = self_physical.tensor().unsqueeze(dim_physical);
241
+ return self_physical.getPhysicalToLogicalMap().apply(result);
242
+ }
243
+
244
+ Tensor& fill_inplace_scalar_batching_rule(Tensor& self, const Scalar& value) {
245
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
246
+ self_physical.tensor().fill_(value);
247
+ return self;
248
+ }
249
+
250
+ Tensor& fill_inplace_tensor_batching_rule(Tensor& self, const Tensor& value) {
251
+ auto value_batched = isBatchedTensor(value);
252
+
253
+ if (value_batched) {
254
+ auto physical_args =
255
+ BroadcastingVmapTransform::logicalToPhysical({self, value});
256
+ physical_args[0].tensor().copy_(physical_args[1].tensor());
257
+ } else {
258
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
259
+ self_physical.tensor().fill_(value);
260
+ }
261
+ return self;
262
+ }
263
+
264
+ Tensor& zero_inplace_batching_rule(Tensor &self) {
265
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
266
+ self_physical.tensor().zero_();
267
+ return self;
268
+ }
269
+
270
+ Tensor squeeze_batching_rule(const Tensor& self) {
271
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
272
+ auto physical_sizes = self_physical.tensor().sizes();
273
+
274
+ // Don't squeeze the batch dims!
275
+ VmapDimVector squeezed_sizes;
276
+ int64_t num_batch_dims = self_physical.numBatchDims();
277
+ squeezed_sizes.insert(
278
+ squeezed_sizes.end(),
279
+ physical_sizes.begin(),
280
+ physical_sizes.begin() + num_batch_dims);
281
+ for (auto it = physical_sizes.begin() + num_batch_dims; it != physical_sizes.end(); ++it) {
282
+ if (*it != 1) {
283
+ squeezed_sizes.push_back(*it);
284
+ }
285
+ }
286
+
287
+ auto result = self_physical.tensor().view(squeezed_sizes);
288
+ return self_physical.getPhysicalToLogicalMap().apply(result);
289
+ }
290
+
291
+ Tensor squeeze_dim_batching_rule(const Tensor& self, int64_t dim) {
292
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
293
+ auto dim_physical = self_physical.getPhysicalDim(dim);
294
+ auto result = self_physical.tensor().squeeze(dim_physical);
295
+ return self_physical.getPhysicalToLogicalMap().apply(result);
296
+ }
297
+
298
+ Tensor squeeze_dims_batching_rule(const Tensor& self, IntArrayRef dims) {
299
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
300
+ auto dims_physical = self_physical.getPhysicalDims(dims);
301
+ auto result = self_physical.tensor().squeeze(dims_physical);
302
+ return self_physical.getPhysicalToLogicalMap().apply(result);
303
+ }
304
+
305
+ Tensor trace_batching_rule(const Tensor& self) {
306
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
307
+ // Batched Diagonal View
308
+ auto self_diag = at::diagonal(self_physical.tensor(), /*offset*/0, /*dim1*/-2, /*dim2*/-1);
309
+ auto result = at::sum(self_diag, -1);
310
+ return self_physical.getPhysicalToLogicalMap().apply(result);
311
+ }
312
+
313
+ Tensor trace_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes) {
314
+ auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad);
315
+ auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options());
316
+ // Batched Diagonal View
317
+ auto grad_input_diag = at::diagonal(grad_input, /*offset*/0, /*dim1*/-2, /*dim2*/-1);
318
+ // Append a dimension of size one to the grad output
319
+ auto grad_physical_tensor = grad_physical.tensor().unsqueeze(-1);
320
+ grad_input_diag.copy_(grad_physical_tensor);
321
+ return grad_physical.getPhysicalToLogicalMap().apply(grad_input);
322
+ }
323
+
324
+ Tensor transpose_int_batching_rule(const Tensor& self, int64_t dim0, int64_t dim1) {
325
+ // PyTorch has a special case where scalar_tensor.transpose(dim0, dim1) works
326
+ // for dim0, dim1 in {0, -1} and returns the scalar tensor. If the following happens:
327
+ // >>> x = torch.randn(B0) # the per-examples are all scalars
328
+ // >>> vmap(lambda x: x.transpose(0, -1), x)
329
+ // then we replicate this behavior.
330
+ if (/*logical*/self.dim() == 0 && is_allowed_dim_on_scalar_tensor(dim0) &&
331
+ is_allowed_dim_on_scalar_tensor(dim1)) {
332
+ return self;
333
+ }
334
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
335
+ auto dim0_physical = self_physical.getPhysicalDim(dim0);
336
+ auto dim1_physical = self_physical.getPhysicalDim(dim1);
337
+ auto result = self_physical.tensor().transpose(dim0_physical, dim1_physical);
338
+ return self_physical.getPhysicalToLogicalMap().apply(result);
339
+ }
340
+
341
+ Tensor permute_batching_rule(const Tensor& self, IntArrayRef dims) {
342
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
343
+ auto dims_physical = self_physical.getPhysicalDims(dims);
344
+
345
+ VmapDimVector all_dims_physical;
346
+ all_dims_physical.reserve(self_physical.tensor().dim());
347
+ for (const auto bdim : c10::irange(self_physical.numBatchDims())) {
348
+ all_dims_physical.push_back(bdim);
349
+ }
350
+ all_dims_physical.insert(
351
+ all_dims_physical.end(),
352
+ dims_physical.begin(),
353
+ dims_physical.end());
354
+ auto result = self_physical.tensor().permute(all_dims_physical);
355
+ return self_physical.getPhysicalToLogicalMap().apply(result);
356
+ }
357
+
358
+ Tensor select_batching_rule(const Tensor& self, int64_t dim, int64_t index) {
359
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
360
+ auto dim_physical = self_physical.getPhysicalDim(dim);
361
+ auto result = self_physical.tensor().select(dim_physical, index);
362
+ return self_physical.getPhysicalToLogicalMap().apply(result);
363
+ }
364
+
365
+ int64_t getGradInputPhysicalDim(int64_t dim, IntArrayRef input_sizes, int64_t num_batch_dims) {
366
+ return maybe_wrap_dim(dim, static_cast<int64_t>(input_sizes.size())) + num_batch_dims;
367
+ }
368
+
369
+ Tensor select_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t dim, int64_t index) {
370
+ auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad);
371
+ auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options());
372
+ auto physical_dim = getGradInputPhysicalDim(dim, input_sizes, grad_physical.numBatchDims());
373
+ grad_input.select(physical_dim, index).copy_(grad_physical.tensor());
374
+ return grad_physical.getPhysicalToLogicalMap().apply(grad_input);
375
+ }
376
+
377
+ Tensor slice_batching_rule(
378
+ const Tensor& self,
379
+ int64_t dim,
380
+ std::optional<int64_t> start,
381
+ std::optional<int64_t> end,
382
+ int64_t step) {
383
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
384
+ auto dim_physical = self_physical.getPhysicalDim(dim);
385
+ auto result = self_physical.tensor().slice(dim_physical, start, end, step);
386
+ return self_physical.getPhysicalToLogicalMap().apply(result);
387
+ }
388
+
389
+ Tensor slice_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) {
390
+ auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad);
391
+ auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options());
392
+ auto physical_dim = getGradInputPhysicalDim(dim, input_sizes, grad_physical.numBatchDims());
393
+ grad_input.slice(physical_dim, start, end, step).copy_(grad_physical.tensor());
394
+ return grad_physical.getPhysicalToLogicalMap().apply(grad_input);
395
+ }
396
+
397
+ Tensor diagonal_batching_rule(const Tensor& self, int64_t offset, int64_t dim1, int64_t dim2) {
398
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
399
+ auto dim1_physical = self_physical.getPhysicalDim(dim1);
400
+ auto dim2_physical = self_physical.getPhysicalDim(dim2);
401
+ auto result = at::diagonal(self_physical.tensor(), offset, dim1_physical, dim2_physical);
402
+ return self_physical.getPhysicalToLogicalMap().apply(result);
403
+ }
404
+
405
+ Tensor diagonal_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2) {
406
+ auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad);
407
+ auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options());
408
+ auto dim1_physical = getGradInputPhysicalDim(dim1, input_sizes, grad_physical.numBatchDims());
409
+ auto dim2_physical = getGradInputPhysicalDim(dim2, input_sizes, grad_physical.numBatchDims());
410
+ grad_input.diagonal(offset, dim1_physical, dim2_physical).copy_(grad_physical.tensor());
411
+ return grad_physical.getPhysicalToLogicalMap().apply(grad_input);
412
+ }
413
+
414
+ Tensor movedim_batching_rule(const Tensor& self, IntArrayRef source, IntArrayRef destination) {
415
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
416
+ auto source_physical = self_physical.getPhysicalDims(source);
417
+ auto destination_physical = self_physical.getPhysicalDims(destination);
418
+ auto result = at::movedim(self_physical.tensor(), source_physical, destination_physical);
419
+ return self_physical.getPhysicalToLogicalMap().apply(result);
420
+ }
421
+
422
+ Tensor reshape_batching_rule(const Tensor& self, IntArrayRef shape) {
423
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
424
+ auto shape_physical = self_physical.getPhysicalShape(shape);
425
+ auto result = self_physical.tensor().reshape(shape_physical);
426
+ return self_physical.getPhysicalToLogicalMap().apply(result);
427
+ }
428
+
429
+ std::vector<Tensor> split_batching_rule(const Tensor& self, int64_t split_size, int64_t dim) {
430
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
431
+ auto dim_physical = self_physical.getPhysicalDim(dim);
432
+ auto result = at::split(self_physical.tensor(), split_size, dim_physical);
433
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
434
+ return result;
435
+ }
436
+
437
+ std::vector<Tensor> split_with_sizes_batching_rule(const Tensor& self, IntArrayRef split_sizes, int64_t dim) {
438
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
439
+ auto dim_physical = self_physical.getPhysicalDim(dim);
440
+ auto result = at::split_with_sizes(self_physical.tensor(), split_sizes, dim_physical);
441
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
442
+ return result;
443
+ }
444
+
445
+ std::vector<Tensor> unbind_batching_rule(const Tensor& self, int64_t dim) {
446
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
447
+ auto dim_physical = self_physical.getPhysicalDim(dim);
448
+ auto result = at::unbind(self_physical.tensor(), dim_physical);
449
+ self_physical.getPhysicalToLogicalMap().applyInplace(result);
450
+ return result;
451
+ }
452
+
453
+ Tensor unfold_batching_rule(const Tensor& self, int64_t dim, int64_t size, int64_t step) {
454
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
455
+ auto dim_physical = self_physical.getPhysicalDim(dim);
456
+ auto result = self_physical.tensor().unfold(dim_physical, size, step);
457
+ return self_physical.getPhysicalToLogicalMap().apply(result);
458
+ }
459
+
460
+ Tensor contiguous_batching_rule(const Tensor& self, MemoryFormat memory_format) {
461
+ TORCH_CHECK(memory_format == MemoryFormat::Contiguous,
462
+ "NYI: Tensor.contiguous(...) inside of vmap for memory_format other ",
463
+ "than torch.contiguous_format");
464
+ auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self);
465
+ auto result = physical_view.tensor().contiguous(memory_format);
466
+ return physical_view.getPhysicalToLogicalMap().apply(result);
467
+ }
468
+
469
+ Tensor view_batching_rule(const Tensor& self, IntArrayRef size) {
470
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
471
+ auto size_physical = self_physical.getPhysicalShape(size);
472
+ auto result = self_physical.tensor().view(size_physical);
473
+ return self_physical.getPhysicalToLogicalMap().apply(result);
474
+ }
475
+
476
+ Tensor view_as_complex_batching_rule(const Tensor& self) {
477
+ // guard against the user passing in a batch of scalar tensors with batch
478
+ // size equal to 2.
479
+ TORCH_CHECK(!self.sizes().empty(), "Input tensor must have one or more dimensions");
480
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
481
+ auto result = at::view_as_complex(self_physical.tensor());
482
+ return self_physical.getPhysicalToLogicalMap().apply(result);
483
+ }
484
+
485
+ // Checks that the smallest batch stride is greater than the largest example
486
+ // stride. This is something we can support but we choose not to because it's
487
+ // potentially error prone.
488
+ void checkBatchDimsAtFrontInLayout(IntArrayRef physical_strides, int64_t num_batch_dims) {
489
+ auto smallest_batch_stride = std::min_element(
490
+ physical_strides.begin(), physical_strides.begin() + num_batch_dims);
491
+ auto largest_example_stride = std::max_element(
492
+ physical_strides.begin() + num_batch_dims, physical_strides.end());
493
+ if (largest_example_stride == physical_strides.end()) {
494
+ // No example dimensions
495
+ return;
496
+ }
497
+ TORCH_CHECK(*smallest_batch_stride >= *largest_example_stride,
498
+ "vmap: Calling Tensor.as_strided is not supported unless the batch dims being ",
499
+ "vmapped over are at the front of the tensor (in memory layout). When they are ",
500
+ "not at the front of the tensor this operation can be error prone so we "
501
+ "actively discourage it; please file us a bug report and/or try to ",
502
+ "express the as_strided operation in terms of PyTorch view operations");
503
+ }
504
+
505
+ // given (sizes, strides, storage_offset) returns the maximum location that
506
+ // can be indexed (or nullopt if such a location doesn't exist, e.g., tensors
507
+ // with zero-size dims).
508
+ std::optional<int64_t> maximum_indexable_location(
509
+ IntArrayRef sizes, IntArrayRef strides, int64_t storage_offset) {
510
+ auto result = native::storage_size_for(sizes, strides);
511
+ if (result == 0) {
512
+ return std::nullopt;
513
+ }
514
+ return result + storage_offset;
515
+ }
516
+
517
+ // Let x be the "first slice" of physical_tensor.
518
+ // This checks that the range of possible memory locations accessible by
519
+ // x.as_strided(sizes, strides, maybe_storage_offset)
520
+ // are within the bounds of possible memory locations accessible by x.
521
+ void checkBasicAsStridedValidForSlice(
522
+ const Tensor& physical_tensor,
523
+ int64_t num_batch_dims,
524
+ IntArrayRef sizes,
525
+ IntArrayRef strides,
526
+ std::optional<int64_t> maybe_storage_offset) {
527
+ auto slice_sizes = physical_tensor.sizes().slice(num_batch_dims);
528
+ auto slice_strides = physical_tensor.strides().slice(num_batch_dims);
529
+ auto base_offset = physical_tensor.storage_offset();
530
+
531
+ auto storage_offset = maybe_storage_offset.value_or(base_offset);
532
+
533
+ auto max_as_strided_loc = maximum_indexable_location(sizes, strides, storage_offset);
534
+ auto max_slice_loc = maximum_indexable_location(slice_sizes, slice_strides, base_offset);
535
+
536
+ if (!max_as_strided_loc.has_value()) {
537
+ return;
538
+ }
539
+ if (!max_slice_loc.has_value()) {
540
+ TORCH_CHECK(false,
541
+ "result = tensor.as_strided(", sizes, ",", strides, ",", storage_offset, ")",
542
+ "can access memory outside of `tensor`. `tensor` has no storage but the ",
543
+ "passed-in (size, stride, storage_offset) imply a result with some storage. ",
544
+ "This is not supported inside of vmap, please try to rewrite the ",
545
+ "`as_strided` call as a sequence of PyTorch view operations");
546
+ }
547
+
548
+ TORCH_CHECK(
549
+ *max_as_strided_loc <= *max_slice_loc && base_offset <= storage_offset,
550
+ "result = tensor.as_strided(", sizes, ",", strides, ",", storage_offset, ")",
551
+ "can access memory outside of `tensor`. `result` can access some",
552
+ "memory in range [", storage_offset, ", ", *max_as_strided_loc, "], but ",
553
+ "`tensor` can only access some memory in range [", base_offset, ", ",
554
+ *max_slice_loc, "]. This is not supported inside of vmap, please try to",
555
+ "rewrite the `as_strided` call as a sequence of PyTorch view operations");
556
+ }
557
+
558
+ Tensor _reshape_alias_batching_rule(const Tensor& self, IntArrayRef sizes, IntArrayRef strides [[maybe_unused]]) {
559
+ return reshape_batching_rule(self, sizes);
560
+ }
561
+
562
+ Tensor _new_zeros_with_same_feature_meta_batching_rule(
563
+ const Tensor& self,
564
+ const Tensor& other,
565
+ int64_t unused_num_batch_dims) {
566
+ TORCH_CHECK(isBatchedTensor(self) && !isBatchedTensor(other),
567
+ "Only the 'batched grad' use case is supported in PyTorch core.");
568
+
569
+ TORCH_INTERNAL_ASSERT(unused_num_batch_dims == 0,
570
+ "num_batch_dims should not be explicitly passed in because it will be overridden");
571
+ auto self_physical_view = at::MultiBatchVmapTransform::logicalToPhysical(self);
572
+ const auto& self_physical_tensor = self_physical_view.tensor();
573
+ int64_t num_batch_dims = self_physical_view.numBatchDims();
574
+ checkBatchDimsAtFrontInLayout(self_physical_tensor.strides(), num_batch_dims);
575
+ auto result = at::_new_zeros_with_same_feature_meta(self_physical_tensor, other, num_batch_dims);
576
+ return self_physical_view.getPhysicalToLogicalMap().apply(result);
577
+ }
578
+
579
+ bool _has_same_storage_numel_batching_rule(const Tensor& self, const Tensor& other) {
580
+ TORCH_CHECK(isBatchedTensor(self) && !isBatchedTensor(other),
581
+ "Only the 'batched grad' use case is supported in PyTorch core.");
582
+ // The _has_same_storage_numel check is skipped if the tangent is a batched
583
+ // tensor because using as_strided to access storage locations not indexable
584
+ // by the input tensor is not supported in vmap
585
+ return true;
586
+ }
587
+
588
+ // What are the semantics of as_strided inside of vmap?
589
+ // y = vmap(lambda x: x.as_strided(sizes, strides, offset))(xs)
590
+ // This returns a view on `x`, `y`, such that each y[i] has:
591
+ // - sizes: `sizes`
592
+ // - strides: `strides`
593
+ // - storage_offset: offset + i * x.stride(batch_dim)
594
+ //
595
+ // In other words, it is as if we had treated each x[i] as having storage
596
+ // offset equal to xs.offset() and called as_strided(sizes, sizes, offset).
597
+ // (that is equivalent to x[i].as_strided(
598
+ // sizes, sizes, offset + x[i].storage_offset() - xs.offset()) for all i)
599
+ //
600
+ // Note that this *may* be different from actually running as_strided
601
+ // in a for-loop. This is due to how as_strided takes in `offset` to be
602
+ // an *absolute* offset. As an example, consider:
603
+ // >>> x = torch.tensor([0., 1., 2., 3., 4.]).as_strided([4], [1], 1)
604
+ // >>> z = [x[i].as_strided([1], [1], 1) for i in range(4)]
605
+ // Each z[i] is actually the same view on x (z[i] == torch.tensor([1.]))!
606
+ // However, we consider the above for-loop comprehension to be a user error:
607
+ // a user should have written the following if they wanted to use as_strided
608
+ // in a per-sample way:
609
+ // >>> z = [x[i].as_strided([1], [1], 1 + x[i].storage_offset() - 1) for i in range(4)]
610
+ Tensor as_strided_batching_rule(
611
+ const Tensor& tensor,
612
+ IntArrayRef sizes,
613
+ IntArrayRef strides,
614
+ std::optional<int64_t> storage_offset) {
615
+ auto physical_view = at::MultiBatchVmapTransform::logicalToPhysical(tensor);
616
+ auto num_batch_dims = physical_view.numBatchDims();
617
+ auto physical_sizes = physical_view.getPhysicalShape(sizes);
618
+ const auto& physical_tensor = physical_view.tensor();
619
+
620
+ // We can't rely on the physical as_strided call to do this for us because
621
+ // we do some sanity checks on the size/strides before calling into as_strided.
622
+ TORCH_CHECK(sizes.size() == strides.size(),
623
+ "Tensor.as_strided(size, stride, ...): size and stride must have the ",
624
+ "same length! Got size ", sizes, " and stride ", strides);
625
+
626
+ // Sanity checks:
627
+ // 1. All batch dims are at the front in memory layout (not necessary for
628
+ // correctness, but we are worried the user might be doing crazy things)
629
+ // 2. as_strided(sizes, strides, storage_offset + tensor[i].offset() - tensor.offset())
630
+ // is valid for a slice of the input tensor.
631
+ // See Note: [When will the as_strided batching rule fail?] for details.
632
+ checkBatchDimsAtFrontInLayout(physical_tensor.strides(), num_batch_dims);
633
+ checkBasicAsStridedValidForSlice(
634
+ physical_tensor, num_batch_dims, sizes, strides, storage_offset);
635
+
636
+ // physical_strides = physical tensor's batch strides + (logical) strides
637
+ auto batch_strides = physical_tensor.strides().slice(0, num_batch_dims);
638
+ at::VmapDimVector physical_strides;
639
+ physical_strides.reserve(num_batch_dims + strides.size());
640
+ physical_strides.insert(
641
+ physical_strides.end(), batch_strides.begin(), batch_strides.end());
642
+ physical_strides.insert(
643
+ physical_strides.end(), strides.begin(), strides.end());
644
+
645
+ // If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset())
646
+ // is valid for all i, then it turns out that
647
+ // xs.as_strided(physical_sizes, physical_strides, offset) always succeeds
648
+ // and creates a tensor y such that each y[i] references the same memory
649
+ // locations as zi. See NOTE: [When will the as_strided batching rule fail?]
650
+ auto result = physical_view.tensor().as_strided(
651
+ physical_sizes, physical_strides, storage_offset);
652
+ return physical_view.getPhysicalToLogicalMap().apply(result);
653
+ }
654
+
655
+ // NOTE: [When will the as_strided batching rule fail?]
656
+ // If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset())
657
+ // is valid for all i, then it turns out that
658
+ // xs.as_strided(physical_sizes, physical_strides, offset) always succeeds and
659
+ // creates a tensor y such that each y[i] refers to the same memory as zi.
660
+ //
661
+ // Let's say we have xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()).
662
+ // Furthermore, let's say that as a part of being "valid" this as_strided call
663
+ // does not return a result that can index memory not indexable by xs[i].
664
+ //
665
+ // WLOG, assume that there's only one batch dim and it is at the front of the
666
+ // `xs` tensor. Let B be the batch size and S be the stride of the batch dim.
667
+ // - If the batch dim isn't at the front of the tensor, then we can just move it
668
+ // to the front with movedim/permute. This is always valid because it just swaps
669
+ // some strides around.
670
+ // - This proof also works for tensors with multiple batch dims. We just have to
671
+ // do a little accounting:
672
+ // - instead of [B], we'd have [B0, B1, ..., Bk].
673
+ // - instead of [S], we'd have [S0, S1, ..., Sk].
674
+ // - instead of i, we'd have a list of indices [I0, I1, ..., Ik]
675
+ // - instead of S * I, we'd have \sum_{i=0}^k S_i * I_i
676
+ //
677
+ // [Equation 1]
678
+ // xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) has:
679
+ // - sizes: sizes
680
+ // - strides: strides
681
+ // - offset: offset + S * i
682
+ //
683
+ // x.as_strided itself checks that:
684
+ // - (sizes, strides, offset) are in bounds for `x`'s storage.
685
+ // - strides are positive
686
+ // - offset is positive
687
+ //
688
+ // Claim 1: if xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset())
689
+ // is valid, then
690
+ // ([B] + sizes, [S] + strides, offset + xs.offset()) are in bounds for `xs`'s storage.
691
+ //
692
+ // If we have the claim, then xs.as_strided([B] + sizes, [S] + strides, offset)
693
+ // won't error out. So all we need to check is that the memory locations are
694
+ // what we expected. See [Hand-wavy proof of Claim 1] for proof (it's not very important)
695
+ //
696
+ // xs.as_strided(physical_sizes, physical_strides, offset) is equivalent to
697
+ // xs.as_strided([B] + sizes, [S] + strides, offset)
698
+ //
699
+ // xs.as_strided([B] + sizes, [S] + strides, offset) has:
700
+ // - sizes: [B] + sizes
701
+ // - strides: [S] + strides
702
+ // - offset: offset
703
+ //
704
+ // xs.as_strided([B] + sizes, [S] + strides, offset)[i] has:
705
+ // - sizes: sizes
706
+ // - strides: strides
707
+ // - offset: offset + S * i
708
+ // These memory locations are exactly the same as what we got for [Equation 1],
709
+ // so the xs.as_strided([B] + sizes, [S] + strides, offset) is valid.
710
+ //
711
+ // [Hand-wavy proof of Claim 1]
712
+ // Part of our definition of being valid is that xs[i].as_strided(...)
713
+ // must return a tensor that only uses memory indexable by xs[i].
714
+ // This means that (sizes, strides, offset + xs[i].offset() - xs.offset()) satisfies:
715
+ // offset + xs[i].offset() - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j]
716
+ // <= xs[i].offset() + 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j)
717
+ // (the largest-index memory location of xs[i].as_strided(...) must be \leq
718
+ // the largest-index memory location of xs[i])
719
+ //
720
+ // Fiddling that inequality gives us:
721
+ // offset - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j]
722
+ // <= 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j)
723
+ //
724
+ // offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j]
725
+ // <= 1 + (B-1)*S + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j)
726
+ //
727
+ // offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j]
728
+ // <= 1 + \sum_j (xs.size(j) - 1) * xs.stride(j)
729
+ //
730
+ // offset + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j]
731
+ // <= xs.offset() + 1 + \sum_j (xs.size(j) - 1) * xs.stride(j)
732
+ // (the largest-index memory location of xs.as_strided(size, stride, offset)
733
+ // is \leq than the largest-index memory location of xs)
734
+ // Under the assumptions we've made, the lower bound (lowest indexed memory)
735
+ // is trivially within the storage.
736
+ //
737
+ // Therefore ([B] + sizes, [S] + strides, offset) are in bounds for
738
+ // `xs`'s storage.
739
+
740
+ template <typename F, F Func, typename... ExtraArgs>
741
+ Tensor unwrap_and_call(const Tensor& input, ExtraArgs... args) {
742
+ auto* input_batched = unsafeGetBatchedImpl(input);
743
+ auto output_physical = Func(input_batched->value(), args...);
744
+ auto old_bdims = input_batched->bdims();
745
+ return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end()));
746
+ }
747
+
748
+ template <typename F, F Func, typename... ExtraArgs>
749
+ Tensor unwrap_and_call_method(const Tensor& input, ExtraArgs... extra_args) {
750
+ auto* input_batched = unsafeGetBatchedImpl(input);
751
+ auto output_physical = (input_batched->value().*Func)(extra_args...);
752
+ auto old_bdims = input_batched->bdims();
753
+ return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end()));
754
+ }
755
+
756
+ Tensor pow_scalar_Tensor_batching_rule(const Scalar& other, const Tensor& self) {
757
+ auto* self_batched = unsafeGetBatchedImpl(self);
758
+ auto output_physical = at::pow(other, self_batched->value());
759
+ auto old_bdims = self_batched->bdims();
760
+ return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end()));
761
+ }
762
+
763
+ Tensor clone_batching_rule(const Tensor& self, std::optional<MemoryFormat> memory_format) {
764
+ // Memory format support is a little tricky because vmap is allowed to move
765
+ // around batch dimensions and some memory formats are rank-dependent.
766
+ // Another weird case is:
767
+ // - a tensor with MemoryFormat::ChannelsLast MUST have 4 dimensions. Do we
768
+ // allow the user to clone a Tensor with 3 logical dimensions and 1 batch
769
+ // dim into a ChannelsLast Tensor? What about a Tensor with 3 logical dims
770
+ // and N>1 batch dims?
771
+ TORCH_CHECK(!memory_format.has_value() || memory_format == MemoryFormat::Preserve
772
+ || memory_format == MemoryFormat::Contiguous,
773
+ "NYI: Tensor.clone(memory_format) inside vmap is only supported with ",
774
+ "memory_format torch.preserve_format or torch.contiguous_format (got ",
775
+ *memory_format, ")");
776
+
777
+ if (memory_format == MemoryFormat::Contiguous) {
778
+ // There is an ambiguity here when the batch dims are not at the front of
779
+ // the tensor.
780
+ // >>> x = torch.randn(3, B0, 5)
781
+ // >>> y = vmap(lambda x: x.clone(torch.contiguous_format), in_dims=1, out_dims=0)(x)
782
+ // >>> y[0].is_contiguous()
783
+ // ???
784
+ // Should we make the whole tensor contiguous, or should we
785
+ // make the non-batch dims contiguous? We've chosen the latter because
786
+ // philosophically vmap hides the batch dims and operates on a per-sample level.
787
+ auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self);
788
+ auto output_physical = at::clone(physical_view.tensor(), memory_format);
789
+ return physical_view.getPhysicalToLogicalMap().apply(output_physical);
790
+ }
791
+
792
+ TORCH_INTERNAL_ASSERT(!memory_format.has_value() || memory_format == MemoryFormat::Preserve);
793
+ auto* self_batched = unsafeGetBatchedImpl(self);
794
+ auto output_physical = at::clone(self_batched->value(), memory_format);
795
+ auto old_bdims = self_batched->bdims();
796
+ return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end()));
797
+ }
798
+
799
+ // Note [Batching rules for matmul-like operators]
800
+ // at::matmul doesn't "de-expand" arguments to get better performance (maybe
801
+ // it should). In the batching rules for matmul-like operators (dot, mv, mm),
802
+ // we should be careful not to expand any unnecessary dimensions. e.g., if
803
+ // only one of the two arguments is a BatchedTensor, then we should try
804
+ // not to expand batch dimensions onto the other arg.
805
+ Tensor mv_batching_rule(const Tensor& self, const Tensor& other) {
806
+ auto self_batched = isBatchedTensor(self);
807
+ auto other_batched = isBatchedTensor(other);
808
+
809
+ // A shape checking API would be nice...
810
+ TORCH_CHECK(self.dim() == 2 && other.dim() == 1,
811
+ "mv(self, other): Shape mismatch: expected matrix "
812
+ "(got `self` of size ", self.sizes(), ") ",
813
+ "and vector (got `other` of size ", other.sizes(), ")");
814
+
815
+ // See Note [Batching rules for matmul-like operators] for why we have cases
816
+ if (self_batched && !other_batched) {
817
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
818
+ auto result = at::matmul(self_physical.tensor(), other);
819
+ return self_physical.getPhysicalToLogicalMap().apply(result);
820
+ }
821
+ if (!self_batched && other_batched) {
822
+ // self_physical: [L, K], other_physical: [..., K]
823
+ // We view the tensors as [L, K], [..., K, 1], perform matmul to get
824
+ // a tensor of size [..., L, 1], and unsqueeze the last dim.
825
+ auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other);
826
+ auto result = at::matmul(self, other_physical.tensor().unsqueeze(-1));
827
+ return other_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1));
828
+ }
829
+ if (self_batched && other_batched) {
830
+ // self_physical: [..., L, K], other_physical: [..., K]
831
+ // We view the tensors as [..., L, K], [..., K, 1], perform matmul to get
832
+ // a tensor of size [..., L, 1], and unsqueeze the last dim.
833
+ auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other});
834
+ auto result = at::matmul(
835
+ physical_args[0].tensor(),
836
+ physical_args[1].tensor().unsqueeze(-1));
837
+ return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1));
838
+ }
839
+ TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor");
840
+ }
841
+
842
+ Tensor _make_dual_batching_rule(
843
+ c10::DispatchKeySet ks,
844
+ const Tensor& primal,
845
+ const Tensor& tangent,
846
+ int64_t level
847
+ ) {
848
+ DispatchKeySet after_batched_keyset =
849
+ DispatchKeySet(DispatchKeySet::FULL_AFTER, c10::DispatchKey::Batched);
850
+ return at::redispatch::_make_dual(ks & after_batched_keyset, primal, tangent, level);
851
+ }
852
+
853
+ Tensor dot_batching_rule(const Tensor& self, const Tensor& other) {
854
+ auto self_batched = isBatchedTensor(self);
855
+ auto other_batched = isBatchedTensor(other);
856
+
857
+ TORCH_CHECK(/*logical*/self.dim() == 1 && /*logical*/other.dim() == 1,
858
+ "dot(self, other): Shape mismatch: vector "
859
+ "(got `self` of size ", self.sizes(), ") ",
860
+ "and vector (got `other` of size ", other.sizes(), ")");
861
+
862
+ // See Note [Batching rules for matmul-like operators] for why we have cases
863
+ if (self_batched && !other_batched) {
864
+ // self_physical: [..., K], other_physical: [K]
865
+ // View the tensors as [..., 1, K] and [K], perform matmul, and unsqueeze.
866
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
867
+ auto result = at::matmul(self_physical.tensor().unsqueeze(-2), other);
868
+ return self_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1));
869
+ }
870
+ if (!self_batched && other_batched) {
871
+ // self_physical: [K], other_physical: [..., K]
872
+ // View the tensors as [K] and [..., K, 1], perform matmul, and unsqueeze.
873
+ auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other);
874
+ auto result = at::matmul(self, other_physical.tensor().unsqueeze(-1));
875
+ return other_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1));
876
+ }
877
+ if (self_batched && other_batched) {
878
+ // self_physical: [..., K], other_physical: [..., K]
879
+ // View the tensors as [..., 1, K] and [..., K, 1], perform matmul, and unsqueeze.
880
+ auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other});
881
+ auto result = at::matmul(
882
+ physical_args[0].tensor().unsqueeze(-2),
883
+ physical_args[1].tensor().unsqueeze(-1));
884
+ return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1).squeeze(-1));
885
+ }
886
+ TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor");
887
+ }
888
+
889
+ Tensor bmm_batching_rule(const Tensor& self, const Tensor& other) {
890
+ TORCH_CHECK(/*logical*/self.dim() == 3 && /*logical*/other.dim() == 3,
891
+ "bmm(self, other): Shape mismatch: expected 3D `self` "
892
+ "(got `self` of size ", self.sizes(), ") ",
893
+ "and 3D `other` (got `other` of size ", other.sizes(), ")");
894
+
895
+ auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other});
896
+ auto result = at::matmul(physical_args[0].tensor(), physical_args[1].tensor());
897
+ return physical_args[0].getPhysicalToLogicalMap().apply(result);
898
+ }
899
+
900
+ Tensor mm_batching_rule(const Tensor& self, const Tensor& other) {
901
+ auto self_batched = isBatchedTensor(self);
902
+ auto other_batched = isBatchedTensor(other);
903
+
904
+ TORCH_CHECK(/*logical*/self.dim() == 2 && /*logical*/other.dim() == 2,
905
+ "mm(self, other): Shape mismatch: expected matrix "
906
+ "(got `self` of size ", self.sizes(), ") ",
907
+ "and matrix (got `other` of size ", other.sizes(), ")");
908
+
909
+ // See Note [Batching rules for matmul-like operators] for why we have cases
910
+ if (self_batched && !other_batched) {
911
+ auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self);
912
+ auto result = at::matmul(self_physical.tensor(), other);
913
+ return self_physical.getPhysicalToLogicalMap().apply(result);
914
+ }
915
+ if (!self_batched && other_batched) {
916
+ auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other);
917
+ auto result = at::matmul(self, other_physical.tensor());
918
+ return other_physical.getPhysicalToLogicalMap().apply(result);
919
+ }
920
+ if (self_batched && other_batched) {
921
+ auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other});
922
+ auto result = at::matmul(physical_args[0].tensor(), physical_args[1].tensor());
923
+ return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1).squeeze(-1));
924
+ }
925
+ TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor");
926
+ }
927
+
928
+ Tensor cat_batching_rule(const ITensorListRef& tensors, int64_t dim) {
929
+ auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors);
930
+ auto physical_tensors = fmap(
931
+ physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); });
932
+ TORCH_INTERNAL_ASSERT(
933
+ !tensors.empty(), "The dispatcher should not have dispatched here otherwise.");
934
+ auto result = at::cat(physical_tensors, physical_views[0].getPhysicalDim(dim));
935
+ return physical_views[0].getPhysicalToLogicalMap().apply(result);
936
+ }
937
+
938
+ Tensor stack_batching_rule(TensorList tensors, int64_t dim) {
939
+ auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors);
940
+ auto physical_tensors = fmap(
941
+ physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); });
942
+ TORCH_INTERNAL_ASSERT(
943
+ !tensors.empty(), "The dispatcher should not have dispatched here otherwise.");
944
+ // NB: stack wraps the dimensionality to (logical dim + 1), so we have to
945
+ // manually handle that here.
946
+ auto dim_physical =
947
+ physical_views[0].numBatchDims() + maybe_wrap_dim(dim, /*logical*/tensors[0].dim() + 1);
948
+ auto result = at::stack(physical_tensors, dim_physical);
949
+ return physical_views[0].getPhysicalToLogicalMap().apply(result);
950
+ }
951
+
952
+ // I am quite sad that we need to register operators with exploded TensorOptions,
953
+ // even though the native:: implementations can use TensorOptions&.
954
+ // This also makes it hard to metaprogram: i.e., we can't use
955
+ // unwrap_and_call<..., at::to> because at::to takes TensorOptions& (!!)
956
+ Tensor to_dtype_layout_batching_rule(
957
+ const Tensor& self,
958
+ std::optional<ScalarType> dtype,
959
+ std::optional<Layout> layout,
960
+ std::optional<Device> device,
961
+ std::optional<bool> pin_memory,
962
+ bool non_blocking, bool copy,
963
+ std::optional<MemoryFormat> memory_format) {
964
+ auto options = TensorOptions()
965
+ .dtype(dtype)
966
+ .layout(layout)
967
+ .device(device)
968
+ .pinned_memory(pin_memory);
969
+ auto* input_batched = unsafeGetBatchedImpl(self);
970
+ auto output_physical = input_batched->value().to(options, non_blocking, copy, memory_format);
971
+ auto old_bdims = input_batched->bdims();
972
+ return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end()));
973
+ }
974
+
975
+ Tensor new_zeros_batching_rule(
976
+ const Tensor& self,
977
+ IntArrayRef size,
978
+ std::optional<ScalarType> dtype,
979
+ std::optional<Layout> layout,
980
+ std::optional<Device> device,
981
+ std::optional<bool> pin_memory) {
982
+ auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self);
983
+ auto physical_size = physical_view.getPhysicalShape(size);
984
+ auto options = TensorOptions()
985
+ .dtype(dtype)
986
+ .layout(layout)
987
+ .device(device)
988
+ .pinned_memory(pin_memory);
989
+ auto result = physical_view.tensor().new_zeros(physical_size, options);
990
+ return physical_view.getPhysicalToLogicalMap().apply(result);
991
+ }
992
+
993
+ Tensor new_empty_batching_rule(
994
+ const Tensor& self,
995
+ IntArrayRef size,
996
+ std::optional<ScalarType> dtype,
997
+ std::optional<Layout> layout,
998
+ std::optional<Device> device,
999
+ std::optional<bool> pin_memory) {
1000
+ auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self);
1001
+ auto physical_size = physical_view.getPhysicalShape(size);
1002
+ auto result = physical_view.tensor().new_empty(physical_size, TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory));
1003
+ return physical_view.getPhysicalToLogicalMap().apply(result);
1004
+ }
1005
+
1006
+ Tensor new_empty_strided_batching_rule(
1007
+ const Tensor& self,
1008
+ IntArrayRef size,
1009
+ IntArrayRef stride,
1010
+ std::optional<ScalarType> dtype,
1011
+ std::optional<Layout> layout,
1012
+ std::optional<Device> device,
1013
+ std::optional<bool> pin_memory) {
1014
+ auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self);
1015
+ auto physical_size = physical_view.getPhysicalShape(size);
1016
+
1017
+ // Let [B0, B1, B2] be the shape of the batch dims. We're going to create
1018
+ // the batch dimensions at the front of the tensor (in memory layout),
1019
+ // irrespective of whether or not they are actually at the front (in memory layout)
1020
+ // in the original `self` tensor. This is because when a user calls
1021
+ // `new_empty_strided` in general, the `strides` they provide are for a new
1022
+ // tensor and have no relation to the strides of the original tensor.
1023
+ //
1024
+ // So, the physical shape of the result should be ([B0, B1, B2] + size),
1025
+ // but what about the physical strides?
1026
+ //
1027
+ // We're actually free to pick whatever stride we want:
1028
+ // e.g., for size=[5, 3], stride=[0, 1], we could decide to
1029
+ // use
1030
+ // - physical size: [B0, B1, B2, 5, 3]
1031
+ // - physical stride: [9999*B1*B2, 9999*B2, 9999, 0, 1]
1032
+ //
1033
+ // Let's select some reasonable strides such that:
1034
+ // - The batch dims are "contiguous" with respect to each other
1035
+ // - if empty_strided(size, stride) would have created a contiguous Tensor,
1036
+ // then this new physical Tensor (with batch dims) is also contiguous
1037
+ //
1038
+ // Let S be the size of the storage if one were to construct a tensor
1039
+ // with `size` and `stride` via empty_strided(size, stride).
1040
+ // Then the physical sizes/strides should be:
1041
+ // - physical size: [B0, B1, B2, 5, 3]
1042
+ // - physical stride: [B1 * B2 * S, B2 * S, S, 0, 1]
1043
+ auto batch_shape = IntArrayRef(
1044
+ physical_view.tensor().sizes().begin(), physical_view.numBatchDims());
1045
+
1046
+ // physical_strides = [B1 * B2 * S, B2 * S, S]
1047
+ auto physical_strides = at::detail::defaultStrides(batch_shape);
1048
+ TORCH_CHECK(size.size() == stride.size(),
1049
+ "new_empty_strided(sizes, strides): dimensionality of sizes (",
1050
+ size.size(), ") must match dimensionality of strides (",
1051
+ stride.size(), ")");
1052
+ auto storage_size = native::storage_size_for(size, stride);
1053
+ for (auto& physical_stride : physical_strides) {
1054
+ physical_stride *= storage_size;
1055
+ }
1056
+
1057
+ // physical_strides = [B1 * B2 * S, B2 * S, S] + strides
1058
+ physical_strides.insert(physical_strides.end(), stride.begin(), stride.end());
1059
+
1060
+ auto result = physical_view.tensor().new_empty_strided(
1061
+ physical_size, physical_strides, dtype, layout, device, pin_memory);
1062
+ return physical_view.getPhysicalToLogicalMap().apply(result);
1063
+ }
1064
+
1065
+ template <typename F, F Func>
1066
+ Tensor comparison_pointwise_batching_rule(const Tensor& self, const Tensor& other) {
1067
+ auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other});
1068
+ auto result = Func(physical_args[0].tensor(), physical_args[1].tensor());
1069
+ return physical_args[0].getPhysicalToLogicalMap().apply(result);
1070
+ }
1071
+ }
1072
+ TORCH_LIBRARY_IMPL(_, Batched, m) {
1073
+ m.fallback(torch::CppFunction::makeFromBoxedFunction<&batchedTensorForLoopFallback>());
1074
+ }
1075
+
1076
+ TORCH_LIBRARY_IMPL(aten, Batched, m) {
1077
+ // NB: Ideally we would like some operators, like size.int, to "fallthrough"
1078
+ // to the underlying implementation. However, because a BatchedTensor is a
1079
+ // Tensor wrapper, it only has one dispatch key (Batched) on it. The resolution
1080
+ // here is to just directly call the underlying implementation.
1081
+ m.impl("size.int", static_cast<int64_t (*)(const Tensor&, int64_t)>(native::size));
1082
+ m.impl("_add_batch_dim", native::_add_batch_dim);
1083
+ m.impl("_remove_batch_dim", native::_remove_batch_dim);
1084
+ m.impl("_make_dual", _make_dual_batching_rule);
1085
+ m.impl("_has_same_storage_numel", _has_same_storage_numel_batching_rule);
1086
+ m.impl("is_same_size", native::is_same_size);
1087
+ m.impl("_new_zeros_with_same_feature_meta", _new_zeros_with_same_feature_meta_batching_rule);
1088
+
1089
+ m.impl("sum.dim_IntList", sum_batching_rule);
1090
+ m.impl("is_complex", native::is_complex);
1091
+
1092
+ // inplace operations
1093
+ m.impl("fill_.Scalar", fill_inplace_scalar_batching_rule);
1094
+ m.impl("fill_.Tensor", fill_inplace_tensor_batching_rule);
1095
+ m.impl("zero_", zero_inplace_batching_rule);
1096
+
1097
+ // view operations
1098
+ m.impl("as_strided", as_strided_batching_rule);
1099
+ m.impl("chunk", chunk_batching_rule);
1100
+ m.impl("tensor_split.sections", tensor_split_sections_batching_rule);
1101
+ m.impl("tensor_split.indices", tensor_split_indices_batching_rule);
1102
+ m.impl("diagonal", diagonal_batching_rule);
1103
+ m.impl("expand", expand_batching_rule);
1104
+ m.impl("expand_as", native::expand_as); // composite wrt autograd
1105
+ m.impl("movedim.intlist", movedim_batching_rule);
1106
+ m.impl("movedim.int", static_cast<Tensor(*)(const Tensor&,int64_t,int64_t)>(native::movedim)); // composite wrt autograd
1107
+ // There is another variant of narrow. However, we don't
1108
+ // want to support the other variant yet bc it isn't documented...
1109
+ m.impl("narrow", native::narrow_symint); // composite wrt autograd
1110
+ m.impl("numpy_T", native::numpy_T); // composite wrt autograd
1111
+ m.impl("matrix_H", native::matrix_H); // composite wrt autograd
1112
+ m.impl("mT", native::mT); // composite wrt autograd
1113
+ m.impl("mH", native::mH); // composite wrt autograd
1114
+ m.impl("permute", permute_batching_rule);
1115
+ m.impl("reshape", reshape_batching_rule);
1116
+ m.impl("_reshape_alias", _reshape_alias_batching_rule);
1117
+ m.impl("reshape_as", native::reshape_as); // composite wrt autograd
1118
+ m.impl("select.int", select_batching_rule);
1119
+ m.impl("slice.Tensor", slice_batching_rule);
1120
+ m.impl("split.Tensor", split_batching_rule);
1121
+ m.impl("split.sizes", split_with_sizes_batching_rule);
1122
+ m.impl("split_with_sizes", split_with_sizes_batching_rule);
1123
+ m.impl("squeeze", squeeze_batching_rule);
1124
+ m.impl("squeeze.dim", squeeze_dim_batching_rule);
1125
+ m.impl("squeeze.dims", squeeze_dims_batching_rule);
1126
+ m.impl("t", native::t); // composite wrt autograd
1127
+ m.impl("trace", trace_batching_rule);
1128
+ m.impl("transpose.int", transpose_int_batching_rule);
1129
+ m.impl("unbind.int", unbind_batching_rule);
1130
+ m.impl("unfold", unfold_batching_rule);
1131
+ m.impl("unsqueeze", unsqueeze_batching_rule);
1132
+ m.impl("view", view_batching_rule);
1133
+ m.impl("view_as", native::view_as); // composite wrt autograd
1134
+
1135
+ // clamp operations
1136
+ m.impl("clamp", clamp_batching_rule);
1137
+ m.impl("clamp_min", clamp_min_batching_rule);
1138
+ m.impl("clamp_max", clamp_max_batching_rule);
1139
+
1140
+ // unary pointwise, out-of-place, no additional arguments.
1141
+ #define UNARY_POINTWISE(op) m.impl(#op, \
1142
+ unwrap_and_call<Tensor (*)(const Tensor&), at::op>);
1143
+ UNARY_POINTWISE(abs);
1144
+ UNARY_POINTWISE(acos);
1145
+ UNARY_POINTWISE(asin);
1146
+ UNARY_POINTWISE(atan);
1147
+ UNARY_POINTWISE(ceil);
1148
+ UNARY_POINTWISE(cos);
1149
+ UNARY_POINTWISE(cosh);
1150
+ UNARY_POINTWISE(conj_physical);
1151
+ UNARY_POINTWISE(digamma);
1152
+ UNARY_POINTWISE(exp);
1153
+ UNARY_POINTWISE(expm1);
1154
+ UNARY_POINTWISE(floor);
1155
+ UNARY_POINTWISE(frac);
1156
+ UNARY_POINTWISE(lgamma);
1157
+ UNARY_POINTWISE(log);
1158
+ UNARY_POINTWISE(log10);
1159
+ UNARY_POINTWISE(log1p);
1160
+ UNARY_POINTWISE(log2);
1161
+ UNARY_POINTWISE(neg);
1162
+ UNARY_POINTWISE(reciprocal);
1163
+ UNARY_POINTWISE(relu);
1164
+ UNARY_POINTWISE(round);
1165
+ UNARY_POINTWISE(rsqrt);
1166
+ UNARY_POINTWISE(sigmoid);
1167
+ UNARY_POINTWISE(sign);
1168
+ UNARY_POINTWISE(sin);
1169
+ UNARY_POINTWISE(sinh);
1170
+ UNARY_POINTWISE(sqrt);
1171
+ UNARY_POINTWISE(tan);
1172
+ UNARY_POINTWISE(tanh);
1173
+ UNARY_POINTWISE(trunc);
1174
+ #undef UNARY_POINTWISE
1175
+ #define TO_BATCHING_RULE(name, ...) \
1176
+ { \
1177
+ using to_type = Tensor(Tensor::*)(__VA_ARGS__) const; \
1178
+ m.impl(name, unwrap_and_call_method< \
1179
+ to_type, &Tensor::to, __VA_ARGS__>);\
1180
+ }
1181
+ TO_BATCHING_RULE("to.device", Device, ScalarType, bool, bool, std::optional<MemoryFormat>)
1182
+ TO_BATCHING_RULE("to.dtype", ScalarType, bool, bool, std::optional<MemoryFormat>)
1183
+ TO_BATCHING_RULE("to.other", const Tensor&, bool, bool, std::optional<MemoryFormat>)
1184
+ m.impl("to.dtype_layout", to_dtype_layout_batching_rule);
1185
+ #undef TO_BATCHING_RULE
1186
+ m.impl("clone", clone_batching_rule);
1187
+
1188
+ using TensorTensorScalarType = Tensor (*)(const Tensor&, const Tensor&, const Scalar&);
1189
+ using TensorTensorType = Tensor (*)(const Tensor&, const Tensor&);
1190
+ using TensorScalarType = Tensor (*)(const Tensor&, const Scalar&);
1191
+
1192
+ #define BINARY_POINTWISE(op) \
1193
+ m.impl(#op".Tensor", binary_pointwise_batching_rule<TensorTensorType, at::op>); \
1194
+ m.impl(#op".Scalar", unwrap_and_call<TensorScalarType, at::op, const Scalar&>);
1195
+ #define BINARY_POINTWISE_VA(op, ...) \
1196
+ { \
1197
+ using Binop = Tensor (*)(const Tensor&, const Tensor&, __VA_ARGS__); \
1198
+ using Unop = Tensor (*)(const Tensor&, const Scalar&, __VA_ARGS__); \
1199
+ m.impl(#op".Tensor", binary_pointwise_batching_rule<Binop, at::op, __VA_ARGS__>); \
1200
+ m.impl(#op".Scalar", unwrap_and_call<Unop, at::op, const Scalar&, __VA_ARGS__>); \
1201
+ }
1202
+
1203
+ BINARY_POINTWISE_VA(add, const Scalar&);
1204
+ BINARY_POINTWISE_VA(sub, const Scalar&);
1205
+ BINARY_POINTWISE_VA(rsub, const Scalar&);
1206
+ BINARY_POINTWISE(mul);
1207
+ BINARY_POINTWISE(div);
1208
+ {
1209
+ using Binop = Tensor (*)(const Tensor&, const Tensor&, std::optional<std::string_view>);
1210
+ using Unop = Tensor (*)(const Tensor&, const Scalar&, std::optional<std::string_view>);
1211
+ m.impl("div.Tensor_mode", binary_pointwise_batching_rule<Binop, at::div, std::optional<std::string_view>>);
1212
+ m.impl("div.Scalar_mode", unwrap_and_call<Unop, at::div, const Scalar&, std::optional<std::string_view>>);
1213
+ }
1214
+
1215
+ // at::pow has three out-of-place overloads
1216
+ m.impl("pow.Tensor_Tensor", binary_pointwise_batching_rule<TensorTensorType, at::pow>);
1217
+ m.impl("pow.Tensor_Scalar", unwrap_and_call<TensorScalarType, at::pow, const Scalar&>);
1218
+ m.impl("pow.Scalar", pow_scalar_Tensor_batching_rule);
1219
+
1220
+ m.impl("sigmoid_backward", binary_pointwise_batching_rule<TensorTensorType, at::sigmoid_backward>);
1221
+ m.impl(
1222
+ "threshold_backward",
1223
+ binary_pointwise_batching_rule<
1224
+ TensorTensorScalarType,
1225
+ at::threshold_backward,
1226
+ const Scalar&>);
1227
+
1228
+ // for at::result_type, call the native::result_type implementation.
1229
+ // We don't have to do anything special because native::result_type operates
1230
+ // on the logical shape of the tensors.
1231
+ m.impl("result_type.Tensor", static_cast<ScalarType (*)(const Tensor&, const Tensor&)>(native::result_type));
1232
+ m.impl("result_type.Scalar", static_cast<ScalarType (*)(const Tensor&, const Scalar&)>(native::result_type));
1233
+ m.impl("result_type.Scalar_Tensor", static_cast<ScalarType (*)(const Scalar&, const Tensor&)>(native::result_type));
1234
+ m.impl("result_type.Scalar_Scalar", static_cast<ScalarType (*)(const Scalar&, const Scalar&)>(native::result_type));
1235
+
1236
+ #undef BINARY_POINTWISE_VA
1237
+ #undef BINARY_POINTWISE
1238
+
1239
+
1240
+ #define TRIVIAL_OP(op) m.impl(#op, \
1241
+ unwrap_and_call<Tensor (*)(const Tensor&), at::op>);
1242
+ // complex number view operators
1243
+ TRIVIAL_OP(imag)
1244
+ TRIVIAL_OP(real);
1245
+ TRIVIAL_OP(view_as_real);
1246
+ TRIVIAL_OP(conj);
1247
+ TRIVIAL_OP(_conj);
1248
+ TRIVIAL_OP(resolve_conj);
1249
+ TRIVIAL_OP(resolve_neg);
1250
+ m.impl("view_as_complex", view_as_complex_batching_rule);
1251
+ #undef TRIVIAL
1252
+
1253
+ // matmul-like operators
1254
+ m.impl("mv", mv_batching_rule);
1255
+ m.impl("dot", dot_batching_rule);
1256
+ m.impl("bmm", bmm_batching_rule);
1257
+ m.impl("mm", mm_batching_rule);
1258
+
1259
+ // cat/stack
1260
+ m.impl("cat", cat_batching_rule);
1261
+ m.impl("stack", stack_batching_rule);
1262
+
1263
+ // backward operators
1264
+ m.impl("select_backward", select_backward_batching_rule);
1265
+ m.impl("slice_backward", slice_backward_batching_rule);
1266
+ m.impl("trace_backward", trace_backward_batching_rule);
1267
+ m.impl("diagonal_backward", diagonal_backward_batching_rule);
1268
+
1269
+ // Tensor.new_* operators
1270
+ m.impl("new_empty", new_empty_batching_rule);
1271
+ m.impl("new_empty_strided", new_empty_strided_batching_rule);
1272
+ m.impl("new_zeros", new_zeros_batching_rule);
1273
+
1274
+ m.impl("contiguous", contiguous_batching_rule);
1275
+
1276
+ // Comparison ops
1277
+ #define COMPARISON_POINTWISE(op) \
1278
+ m.impl(#op".Tensor", comparison_pointwise_batching_rule<TensorTensorType, at::op>); \
1279
+ m.impl(#op".Scalar", unwrap_and_call<TensorScalarType, at::op, const Scalar&>);
1280
+
1281
+ COMPARISON_POINTWISE(eq);
1282
+ COMPARISON_POINTWISE(gt);
1283
+ COMPARISON_POINTWISE(ge);
1284
+ COMPARISON_POINTWISE(le);
1285
+ COMPARISON_POINTWISE(lt);
1286
+ COMPARISON_POINTWISE(ne);
1287
+
1288
+ #undef COMPARISON_POINTWISE
1289
+ }
1290
+
1291
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.cpp ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/LegacyVmapMode.h>
2
+
3
+ namespace at::impl {
4
+
5
+ thread_local static int64_t VmapMode_current_vmap_level = 0;
6
+
7
+ int64_t VmapMode::current_vmap_level() {
8
+ return VmapMode_current_vmap_level;
9
+ }
10
+
11
+ int64_t VmapMode::increment_nesting() {
12
+ VmapMode_current_vmap_level++;
13
+ if (VmapMode_current_vmap_level == 1) {
14
+ c10::impl::tls_set_dispatch_key_included(DispatchKey::VmapMode, true);
15
+ }
16
+ return VmapMode_current_vmap_level;
17
+ }
18
+
19
+ int64_t VmapMode::decrement_nesting() {
20
+ VmapMode_current_vmap_level--;
21
+ if (VmapMode_current_vmap_level == 0) {
22
+ c10::impl::tls_set_dispatch_key_included(DispatchKey::VmapMode, false);
23
+ }
24
+ return VmapMode_current_vmap_level;
25
+ }
26
+ } // namespace at::impl
western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/impl/LocalDispatchKeySet.h>
4
+
5
+ namespace at::impl {
6
+
7
+ // VmapMode contains a thread local count of how many nested vmaps
8
+ // we are currently inside. That number is known as the `vmap level`.
9
+ // VmapMode is used in the implementation of the Python `torch.vmap` API.
10
+ //
11
+ // NOTE: this is NOT the c++ api for torch.vmap. That doesn't exist yet.
12
+
13
+ struct TORCH_API VmapMode {
14
+ // Returns the vmap level, aka the count of how many nested vmaps we're in.
15
+ static int64_t current_vmap_level();
16
+
17
+ // Increment the count of nested vmaps. If this causes the vmap level to be
18
+ // greater than 0, then it enables DispatchKey::VmapMode on all tensors.
19
+ static int64_t increment_nesting();
20
+
21
+ // Decrements the count of nested vmaps. If this causes the vmap level to be
22
+ // equal to 0, then it disables DispatchKey::VmapMode on all tensors.
23
+ static int64_t decrement_nesting();
24
+ };
25
+
26
+ } // namespace at::impl
western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.cpp ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/LegacyVmapTransforms.h>
2
+ #include <c10/util/irange.h>
3
+
4
+ namespace at {
5
+
6
+ // Checks if the batch dims in `bdims` appear at the front of the tensor.
7
+ static bool areBdimsAtFrontInOrder(BatchDimsRef bdims) {
8
+ for (const auto idx : c10::irange(static_cast<int64_t>(bdims.size()))) {
9
+ if (bdims[idx].dim() != idx) {
10
+ return false;
11
+ }
12
+ }
13
+ return true;
14
+ }
15
+
16
+ // Takes a BatchedTensorImpl, permutes all of the batch dims to the front,
17
+ // and then returns a physical version of the Tensor.
18
+ static Tensor permuteBatchDimsToFront(BatchedTensorImpl* batched) {
19
+ auto bdims = batched->bdims();
20
+ const Tensor& physical_tensor = batched->value();
21
+ if (areBdimsAtFrontInOrder(bdims)) {
22
+ return physical_tensor;
23
+ }
24
+ const auto sizes = physical_tensor.sizes();
25
+ VmapDimVector permutation(sizes.size(), 0);
26
+ permutation.reserve(sizes.size());
27
+ const auto is_bdim = createBatchDimBitset(bdims);
28
+ int64_t idx = 0;
29
+ for (const auto& bdim : bdims) {
30
+ permutation[idx++] = bdim.dim();
31
+ }
32
+ for (const auto ptr : c10::irange(sizes.size())) {
33
+ if (is_bdim[ptr]) {
34
+ continue;
35
+ }
36
+ permutation[idx++] = static_cast<int64_t>(ptr);
37
+ }
38
+ return physical_tensor.permute(permutation);
39
+ }
40
+
41
+ VmapPhysicalView MultiBatchVmapTransform::logicalToPhysical(const Tensor& logical_tensor) {
42
+ auto* batched = maybeGetBatchedImpl(logical_tensor);
43
+ TORCH_INTERNAL_ASSERT(
44
+ batched,
45
+ "logicalToPhysical(tensor) should only be passed a BatchedTensor");
46
+ return { permuteBatchDimsToFront(batched), createVmapLevelsBitset(batched->bdims()) };
47
+ }
48
+
49
+ int64_t VmapPhysicalView::numBatchDims() const {
50
+ return static_cast<int64_t>(levels_.count());
51
+ }
52
+
53
+ int64_t VmapPhysicalView::numLogicalDims() const {
54
+ return /*physical*/tensor_.dim() - numBatchDims();
55
+ }
56
+
57
+ VmapDimVector VmapPhysicalView::getPhysicalDims(OptionalIntArrayRef opt_logical_dims) const {
58
+ auto logical_ndim = numLogicalDims();
59
+ // NB: fmap doesn't have a SmallVector variant, so we don't use it here.
60
+ VmapDimVector result;
61
+ result.reserve(logical_ndim);
62
+ if (opt_logical_dims.has_value() && !opt_logical_dims.value().empty()) {
63
+ auto logical_dims = opt_logical_dims.value();
64
+ for (auto dim : logical_dims) {
65
+ result.push_back(maybe_wrap_dim(dim, logical_ndim) + numBatchDims());
66
+ }
67
+ } else {
68
+ for (int64_t dim = 0; dim < logical_ndim; dim++) {
69
+ result.push_back(dim + numBatchDims());
70
+ }
71
+ }
72
+ return result;
73
+ }
74
+
75
+ int64_t VmapPhysicalView::getPhysicalDim(int64_t logical_dim) const {
76
+ auto logical_ndim = numLogicalDims();
77
+ return maybe_wrap_dim(logical_dim, logical_ndim) + numBatchDims();
78
+ }
79
+
80
+ VmapDimVector VmapPhysicalView::getPhysicalShape(IntArrayRef logical_shape) const {
81
+ VmapDimVector result;
82
+ result.reserve(logical_shape.size() + numBatchDims());
83
+ auto tensor_sizes = tensor_.sizes();
84
+ result.insert(result.end(), tensor_sizes.begin(), tensor_sizes.begin() + numBatchDims());
85
+ result.insert(result.end(), logical_shape.begin(), logical_shape.end());
86
+ return result;
87
+ }
88
+
89
+ static BatchDims computeFrontBatchDimsFromLevels(std::bitset<kVmapNumLevels> levels_bitset) {
90
+ BatchDims bdims;
91
+ int64_t dim = 0;
92
+ for (const auto level : c10::irange(kVmapNumLevels)) {
93
+ if (!levels_bitset[level]) {
94
+ continue;
95
+ }
96
+ bdims.emplace_back(level, dim++);
97
+ }
98
+ return bdims;
99
+ }
100
+
101
+ // Given a Tensor or a BatchedTensor, returns the underlying physical tensor
102
+ // with all vmapped dimensions permuted to the front, if they exist, and a
103
+ // bitset of vmap levels that were present in the tensor.
104
+ static std::pair<Tensor,std::bitset<kVmapNumLevels>>
105
+ getPhysicalTensorAndLevels(const Tensor& self) {
106
+ auto* batched = maybeGetBatchedImpl(self);
107
+ if (batched) {
108
+ return {permuteBatchDimsToFront(batched), createVmapLevelsBitset(batched->bdims())};
109
+ }
110
+ return {self, 0};
111
+ }
112
+
113
+ // Given a Tensor or a BatchedTensor, creates a physical view of the tensor
114
+ // such that it has a batch dimension for each level in `requested_levels`
115
+ // and `requested_example_dim` number of non-batch-dimensions.
116
+ //
117
+ // This function is useful in preparing physical views on tensors that can
118
+ // then be passed into broadcasting operations. For example, when adding
119
+ // two BatchedTensors of sizes [B0, 3] and [B0, B1, 2, 3], where the Bi are the
120
+ // batch dimensions, we must align the batch dimensions and non-batch-dimensions
121
+ // (henceforth referred to as the "example" dimensions) separately to produce
122
+ // tensors of size [B0, 1, 1, 3] and [B0, B1, 2, 3] so that they can be added.
123
+ //
124
+ // Here's a direct example of using alignBatchDimsAtFront on the above two tensors.
125
+ //
126
+ // 1) alignBatchDimsAtFront([B0, 3], requested_levels={0, 1}, requested_example_dim=2)
127
+ // returns a physical view of size [B0, 1, 1, 3] by adding an extra dimension for
128
+ // level 1 and another extra dimension to pad the example dimensions to 2.
129
+ //
130
+ // 2) alignBatchDimsAtFront([B0, B1, 2, 3], requested_levels={0, 1}, requested_example_dim=2)
131
+ // returns a physical view of size [B0, B1, 2, 3]
132
+ static Tensor alignBatchDimsAtFront(
133
+ const Tensor& self,
134
+ std::bitset<kVmapNumLevels> requested_levels,
135
+ int64_t requested_example_dim) {
136
+ auto [physical_tensor, tensor_levels] = getPhysicalTensorAndLevels(self);
137
+
138
+ TORCH_INTERNAL_ASSERT(
139
+ (tensor_levels | requested_levels) == requested_levels,
140
+ "`requested_levels` must be a superset of `self`'s levels");
141
+
142
+ auto physical_sizes = physical_tensor.sizes();
143
+
144
+ const auto tensor_example_dim = (
145
+ static_cast<int64_t>(physical_sizes.size())
146
+ - /*num_batch_dims*/static_cast<int64_t>(tensor_levels.count())
147
+ );
148
+ TORCH_INTERNAL_ASSERT(tensor_example_dim <= requested_example_dim);
149
+
150
+ if (tensor_levels == requested_levels && tensor_example_dim == requested_example_dim) {
151
+ // Optimization: no need to do another view if the physical tensor is
152
+ // already the correct shape
153
+ return physical_tensor;
154
+ }
155
+
156
+ VmapDimVector aligned_sizes(requested_levels.count() + requested_example_dim, 1);
157
+
158
+ // align the example dims (non-bdims dims) first
159
+ // aligned_sizes[-tensor_example_dim:] = tensor_sizes[-tensor_example_dim:]
160
+ std::copy(
161
+ physical_sizes.rbegin(),
162
+ physical_sizes.rbegin() + tensor_example_dim,
163
+ aligned_sizes.rbegin());
164
+
165
+ // align the bdims
166
+ int64_t level = 0;
167
+ int64_t tensor_dim = 0;
168
+ for (const auto bdim : c10::irange(requested_levels.count())) {
169
+ // Determine the level of the bdim
170
+ while (!requested_levels[level]) level++;
171
+ if (tensor_levels[level]) {
172
+ aligned_sizes[bdim] = physical_sizes[tensor_dim++];
173
+ }
174
+ level++;
175
+ }
176
+ return physical_tensor.view(aligned_sizes);
177
+ }
178
+
179
+ // The algorithm is as follows:
180
+ // 1. Figure out what all of the collective levels in `logical_tensors` is.
181
+ // 2. Move all batch dims to the front of the tensors and add extra dims
182
+ // of size 1. At this point, every tensor will have a dimension for
183
+ // each of the collective levels.
184
+ // 3. Compute the batch_sizes.
185
+ // 4. Expand each physical tensor so that they have output batch size equal
186
+ // to `batch_sizes`
187
+ VmapPhysicalViewVec
188
+ MultiBatchVmapTransform::logicalToPhysical(ITensorListRef logical_tensors) {
189
+ // Figure out all of the collective vmap levels in `logical_tensors`.
190
+ std::bitset<kVmapNumLevels> collective_levels;
191
+ for (const auto& logical_tensor : logical_tensors) {
192
+ auto* batched = maybeGetBatchedImpl(logical_tensor);
193
+ if (batched) {
194
+ collective_levels |= createVmapLevelsBitset(batched->bdims());
195
+ }
196
+ }
197
+
198
+ // Populate physical_tensors.
199
+ // This contains a list of regular (non-Batched) Tensors where all of the
200
+ // batch dims have been moved to the front of the tensor. Any previously
201
+ // non-existing batch dims get added to the tensors as new dimensions of size 1.
202
+ std::vector<Tensor> physical_tensors;
203
+ auto num_batch_dims = collective_levels.count();
204
+ for (const auto& logical_tensor : logical_tensors) {
205
+ auto requested_example_dim = /*logical_dim*/logical_tensor.dim();
206
+ auto physical_tensor = alignBatchDimsAtFront(
207
+ logical_tensor, collective_levels, requested_example_dim);
208
+ physical_tensors.push_back(std::move(physical_tensor));
209
+ }
210
+
211
+ // Compute batch_sizes
212
+ VmapDimVector batch_sizes(num_batch_dims, 1);
213
+ for (const auto& physical_tensor : physical_tensors) {
214
+ auto physical_sizes = physical_tensor.sizes();
215
+ for (const auto dim : c10::irange(num_batch_dims)) {
216
+ if (physical_sizes[dim] != 1) {
217
+ batch_sizes[dim] = physical_sizes[dim];
218
+ }
219
+ }
220
+ }
221
+
222
+ // Expand each physical_tensor so that it has batch sizes `batch_sizes`
223
+ VmapPhysicalViewVec result;
224
+ for (const auto& physical_tensor : physical_tensors) {
225
+ VmapDimVector expanded_size(batch_sizes.begin(), batch_sizes.end());
226
+ auto physical_sizes = physical_tensor.sizes();
227
+ expanded_size.insert(
228
+ expanded_size.end(),
229
+ physical_sizes.begin() + num_batch_dims,
230
+ physical_sizes.end());
231
+ result.emplace_back(physical_tensor.expand(expanded_size), collective_levels);
232
+ }
233
+ return result;
234
+ }
235
+
236
+ static std::pair<std::bitset<kVmapNumLevels>,int64_t>
237
+ getLevelsAndLargestLogicalDim(TensorList logical_tensors) {
238
+ TORCH_INTERNAL_ASSERT(!logical_tensors.empty());
239
+ std::bitset<kVmapNumLevels> levels;
240
+ int64_t largest_logical_dim = -1;
241
+ for (const auto& tensor : logical_tensors) {
242
+ auto* batched = maybeGetBatchedImpl(tensor);
243
+ if (batched) {
244
+ levels = levels | createVmapLevelsBitset(batched->bdims());
245
+ }
246
+ auto tensor_logical_dim = /*logical dim*/tensor.dim();
247
+ if (tensor_logical_dim > largest_logical_dim) {
248
+ largest_logical_dim = tensor_logical_dim;
249
+ }
250
+ }
251
+ return { levels, largest_logical_dim };
252
+ }
253
+
254
+ VmapPhysicalViewVec BroadcastingVmapTransform::logicalToPhysical(TensorList logical_tensors) {
255
+ TORCH_INTERNAL_ASSERT(
256
+ logical_tensors.size() == 2,
257
+ "This function has only been tested for two tensors. Please add more tests ",
258
+ "before removing this check ");
259
+
260
+ VmapPhysicalViewVec result;
261
+
262
+ auto [levels, largest_logical_dim] = getLevelsAndLargestLogicalDim(logical_tensors);
263
+
264
+ for (const auto& tensor : logical_tensors) {
265
+ // NB: It's possible that we didn't actually need to align `tensor`.
266
+ // For example, when adding two tensors of size (B, 2), and (3, 2), where
267
+ // the first Tensor is a BatchedTensor with batch dim B and the second is
268
+ // a regular Tensor, we will return views of size (B, 1, 2) and (1, 3, 2).
269
+ // However, the view on the second tensor is unnecessary: broadcasting
270
+ // semantics allow for the addition of two tensors of size (B, 1, 2) and (3, 2)!
271
+ //
272
+ // If this unnecessary view is a problem, consider optimizing it away in
273
+ // the future. This may involve creating a new type of VmapPhysicalView
274
+ auto aligned = alignBatchDimsAtFront(tensor, levels, largest_logical_dim) ;
275
+ result.emplace_back(std::move(aligned), levels);
276
+ }
277
+ return result;
278
+ }
279
+
280
+ VmapPhysicalToLogicalMap VmapPhysicalView::getPhysicalToLogicalMap() const {
281
+ return VmapPhysicalToLogicalMap(levels_);
282
+ }
283
+
284
+ Tensor VmapPhysicalToLogicalMap::apply(const Tensor& physical_tensor) const {
285
+ return makeBatched(physical_tensor, computeFrontBatchDimsFromLevels(levels_));
286
+ }
287
+
288
+ void VmapPhysicalToLogicalMap::applyInplace(std::vector<Tensor>& physical_tensors) const {
289
+ for (auto & physical_tensor : physical_tensors) {
290
+ physical_tensor = apply(physical_tensor);
291
+ }
292
+ }
293
+
294
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.h ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/LegacyBatchedTensorImpl.h>
4
+ #include <ATen/core/IListRef.h>
5
+
6
+ namespace at {
7
+
8
+ // This file contains abstractions used for transforming *logical* vmap
9
+ // arguments into *physical* arguments. (Keep reading for definitions of these
10
+ // terms).
11
+
12
+ // NOTE: [Logical vs physical args]
13
+ // Consider the following vmap.
14
+ // vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4))
15
+ // This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4],
16
+ // with batch dims 0 and 2:
17
+ // BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)])
18
+ //
19
+ // We say the *logical* view of the tensor has size [3] -- tensors inside
20
+ // `func` appear to have size [3].
21
+ // However, the *physical* underlying tensor (the one passed to vmap) has size
22
+ // [2, 3, 4].
23
+ //
24
+ // This notion of logical vs physical also extends to non-tensor arguments.
25
+ // Consider the previous tensor; let's assume the user called
26
+ // `torch.sum(tensor, dim=0)` inside of `func`. Then the logical
27
+ // dimension they are reducing over is dim 0 but the physical dim is dim 1
28
+ // (the first non-batch dimension)
29
+
30
+ // Forward declared; see NOTE: [What is a VmapPhysicalView?]
31
+ struct VmapPhysicalView;
32
+
33
+ // Most PyTorch operators take 4 or fewer inputs.
34
+ constexpr int64_t kVmapTransformStaticInputSize = 4;
35
+ using VmapPhysicalViewVec =
36
+ SmallVector<VmapPhysicalView, kVmapTransformStaticInputSize>;
37
+
38
+ // Pytorch generally advertises good performance for <= 5 dims.
39
+ // (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap
40
+ // dimensions to get 8. Adjust this number as necessary
41
+ constexpr int64_t kVmapStaticDimVecSize = 8;
42
+ using VmapDimVector = SmallVector<int64_t, kVmapStaticDimVecSize>;
43
+ using VmapSymDimVector = SmallVector<c10::SymInt, kVmapStaticDimVecSize>;
44
+
45
+ // NOTE: [What is an VmapTransform?]
46
+ // An *VmapTransform* converts logical views of tensors to physical views.
47
+ //
48
+ // Batching rules use VmapTransforms to convert logical arguments to
49
+ // physical arguments, then call one or more at:: operator that handles the
50
+ // physical arguments, and then converts the physical result back to a logical
51
+ // argument.
52
+
53
+ // VmapTransform for operators that take tensors with multiple batch dims.
54
+ // Given one or more logical views on Tensors, `logicalToPhysical`
55
+ // permutes all of the batch dims to the front of the tensor, aligns
56
+ // and expands the batch dims to match each other (according to their `level`),
57
+ // and returns a VmapPhysicalView on the tensor(s).
58
+ struct TORCH_API MultiBatchVmapTransform {
59
+ static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor);
60
+ static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors);
61
+ };
62
+
63
+ // VmapTransform for operators that broadcast all inputs.
64
+ // Given some logical views on Tensors, `logicalToPhysical`:
65
+ // - permutes all of the batch dims to the front of the tensors
66
+ // - aligns all the batch dims to the collective levels of all of the tensors.
67
+ // If a tensor does not have a batch dim for a vmap level, then it receives
68
+ // a size-one dimension for said level.
69
+ // - aligns the non-batch dims to have the same dimensionality, adding extra
70
+ // size-1 dimensions in between the batch dimensions and the non-batch
71
+ // dimensions so that the batch dimensions are lined up from the right.
72
+ //
73
+ // For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch
74
+ // dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap
75
+ // tensors of size (B, 1, 2) and (B, 3, 2).
76
+ //
77
+ // Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns
78
+ // VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't
79
+ // actually *need* to return a tensor of size (1, 2) for the second tensor
80
+ // because the broadcasting operation takes care of that for us, but we do
81
+ // it anyways to keep things simple.
82
+ struct TORCH_API BroadcastingVmapTransform {
83
+ static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors);
84
+ };
85
+
86
+ // Forward declared, if you're reading this file head to toe, don't worry about
87
+ // it yet.
88
+ struct VmapPhysicalToLogicalMap;
89
+
90
+ // NOTE: [What is a VmapPhysicalView?]
91
+ // VmapPhysicalView represents a physical view on a Tensor.
92
+ //
93
+ // One can use it to further convert logical dimension indices, logical shapes,
94
+ // and more to their physical variants, or convert a new (physical) tensor into
95
+ // a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented).
96
+ //
97
+ // VmapPhysicalView stores a physical tensor with all of its batch dimensions at
98
+ // the front and some levels that correspond to said batch dimensions.
99
+ //
100
+ // The levels bitset specifies which vmap levels correspond to the batch
101
+ // dimensions at the front of the tensor. In particular, the number of set bits
102
+ // corresponds to the number of batch dimensions on `tensor` and the rightmost
103
+ // bit of `levels` specifies the maximum number of nested vmaps we are in at
104
+ // this point in time.
105
+ // For example, given:
106
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3})
107
+ //
108
+ // Rightmost bit of `levels` is 3 indicating the number of nested vmaps less
109
+ // than or equal to 3.
110
+ // bitset: 010100
111
+ // ^
112
+ // |
113
+ // levels: 012345
114
+ struct TORCH_API VmapPhysicalView {
115
+ VmapPhysicalView(Tensor&& tensor, std::bitset<kVmapNumLevels> levels)
116
+ : levels_(levels), tensor_(std::move(tensor)) {
117
+ TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor_));
118
+ }
119
+
120
+ Tensor& tensor() {
121
+ return tensor_;
122
+ }
123
+ const Tensor& tensor() const {
124
+ return tensor_;
125
+ }
126
+
127
+ // Maps logical dim indices to physical dim indices. Also does dim wrapping.
128
+ //
129
+ // For example, given:
130
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3})
131
+ //
132
+ // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}.
133
+ // This is because the size of levels tell us that the first two dimensions
134
+ // of `tensor_` are batch dimensions, so a logical dim of `n` is actually
135
+ // a physical dim of `n + 2`.
136
+ VmapDimVector getPhysicalDims(OptionalIntArrayRef logical_dims) const;
137
+ int64_t getPhysicalDim(int64_t logical_dim) const;
138
+
139
+ // Returns a VmapPhysicalToLogicalMap object. This can be used for
140
+ // mapping a physical tensor to a new logical tensor (BatchedTensor)
141
+ VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const;
142
+
143
+ // Maps a logical shape to a physical shape by prepending the batch
144
+ // sizes to the logical shape.
145
+ VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const;
146
+
147
+ int64_t numBatchDims() const;
148
+
149
+ private:
150
+ int64_t numLogicalDims() const;
151
+
152
+ std::bitset<kVmapNumLevels> levels_;
153
+ Tensor tensor_;
154
+ };
155
+
156
+ // Convenience struct used for mapping a physical tensor (a non-BatchedTensor)
157
+ // to a logical one (BatchedTensor). It holds some levels that are used to do
158
+ // the mapping and assumes that the batch dimensions in the physical tensor all
159
+ // occur at the front of the tensor.
160
+ struct TORCH_API VmapPhysicalToLogicalMap {
161
+ VmapPhysicalToLogicalMap(std::bitset<kVmapNumLevels> levels)
162
+ : levels_(levels) {}
163
+
164
+ // Maps a physical tensor to a new logical tensor (BatchedTensor).
165
+ // Assumes that all of the "batch dimensions" are at the front
166
+ // of the physical tensor. For example, given:
167
+ // - x = rank-4 Tensor with size 2, 3, 5, 7
168
+ // - levels = (2, 4)
169
+ // Returns:
170
+ // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)])
171
+ Tensor apply(const Tensor& physical_tensor) const;
172
+
173
+ // Given a vector of physical tensors,
174
+ // 1. maps each tensor to a new logical tensor. Assumes that all of the
175
+ // "batch dimensions" are at the front of the physical tensors.
176
+ // 2. stores the new logical tensors back into the passed-in vector. This is
177
+ // to avoid additional dynamic allocations.
178
+ void applyInplace(std::vector<Tensor>& physical_tensors) const;
179
+
180
+ std::bitset<kVmapNumLevels> levels_;
181
+ };
182
+
183
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/LinalgBackend.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Exception.h>
4
+
5
+ #include <ostream>
6
+ #include <string>
7
+
8
+ namespace at {
9
+
10
+ enum class LinalgBackend : int8_t { Default, Cusolver, Magma };
11
+
12
+ inline std::string LinalgBackendToString(at::LinalgBackend backend) {
13
+ switch (backend) {
14
+ case LinalgBackend::Default:
15
+ return "at::LinalgBackend::Default";
16
+ case LinalgBackend::Cusolver:
17
+ return "at::LinalgBackend::Cusolver";
18
+ case LinalgBackend::Magma:
19
+ return "at::LinalgBackend::Magma";
20
+ default:
21
+ TORCH_CHECK(false, "Unknown linalg backend");
22
+ }
23
+ }
24
+
25
+ inline std::ostream& operator<<(
26
+ std::ostream& stream,
27
+ at::LinalgBackend backend) {
28
+ return stream << LinalgBackendToString(backend);
29
+ }
30
+
31
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/MapAllocator.cpp ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/MapAllocator.h>
2
+
3
+ #include <atomic>
4
+ #include <random>
5
+ #include <string>
6
+ #if ATOMIC_INT_LOCK_FREE == 2
7
+ #define AT_ATOMIC_IPC_REFCOUNT 1
8
+ #endif
9
+
10
+
11
+ #include <c10/util/error.h>
12
+ #ifdef _WIN32
13
+ #include <c10/util/Unicode.h>
14
+ #endif
15
+
16
+ #if defined(HAVE_MMAP)
17
+ #include <fcntl.h>
18
+ #include <sys/mman.h>
19
+ #include <sys/stat.h>
20
+ #endif
21
+
22
+ #if !defined(_MSC_VER) || defined(HAVE_MMAP)
23
+ #include <sys/types.h>
24
+ #include <unistd.h>
25
+ #elif defined(_MSC_VER)
26
+ #include <c10/util/win32-headers.h>
27
+ #endif
28
+ #include <fmt/format.h>
29
+
30
+ namespace at {
31
+
32
+ static constexpr int64_t map_alloc_alignment = 64;
33
+
34
+ std::string NewProcessWideShmHandle() {
35
+ static std::atomic<uint64_t> counter{0};
36
+ static std::random_device rd;
37
+ #ifdef _MSC_VER
38
+ return fmt::format(
39
+ "/torch_{}_{}_{}",
40
+ GetCurrentProcessId(),
41
+ rd(),
42
+ counter.fetch_add(1, std::memory_order_relaxed));
43
+ #else
44
+ return fmt::format(
45
+ "/torch_{}_{}_{}",
46
+ getpid(),
47
+ rd(),
48
+ counter.fetch_add(1, std::memory_order_relaxed));
49
+ #endif
50
+ }
51
+ #if defined(_WIN32) || defined(HAVE_MMAP)
52
+
53
+ namespace {
54
+ struct MapInfo {
55
+ std::atomic<int> refcount;
56
+ };
57
+
58
+ constexpr const char* unknown_filename = "filename not specified";
59
+ #ifdef _WIN32
60
+ constexpr const char* unknown_eventname = "eventname not specified";
61
+ #endif
62
+ } // namespace (anonymous)
63
+
64
+ MapAllocator::MapAllocator(WithFd /*unused*/, std::string_view filename, int fd, int flags, size_t size)
65
+ : filename_(filename.empty() ? unknown_filename : filename)
66
+ , size_(0) // to be filled later
67
+ #ifdef _WIN32
68
+ , handle_(INVALID_HANDLE_VALUE) // to be filled later
69
+ , event_(INVALID_HANDLE_VALUE) // to be filled later
70
+ , eventname_(filename.empty() ? unknown_eventname : (std::string(filename) + "_event"))
71
+ #else
72
+ , fd_(fd)
73
+ #endif
74
+ {
75
+
76
+ if (!(flags & ALLOCATOR_MAPPED_SHARED) && !(flags & ALLOCATOR_MAPPED_SHAREDMEM)) {
77
+ flags &= ~ALLOCATOR_MAPPED_NOCREATE;
78
+ }
79
+ if ((flags ^ ALLOCATOR_MAPPED_EXCLUSIVE) == 0) {
80
+ TORCH_CHECK(false, "ALLOCATOR_MAPPED_EXCLUSIVE flag requires opening the file in shared mode");
81
+ }
82
+ #ifdef _WIN32
83
+ if (fd != -1) {
84
+ TORCH_CHECK(false, "MapAllocator_newWithFd is unsupported on Windows");
85
+ }
86
+ #endif
87
+ flags_ = flags;
88
+
89
+ // OK, now do the allocation
90
+
91
+ if (size == 0) {
92
+ return;
93
+ }
94
+
95
+ #ifdef _WIN32
96
+ if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
97
+ // Shadowing
98
+ const wchar_t *filename;
99
+ const wchar_t *eventname;
100
+ const std::wstring wFilename = c10::u8u16(filename_);
101
+ const std::wstring wEventname = c10::u8u16(eventname_);
102
+ LARGE_INTEGER hfilesz;
103
+
104
+ if (filename_[0] == '/') {
105
+ filename = wFilename.c_str() + 1;
106
+ eventname = wEventname.c_str() + 1;
107
+ } else {
108
+ filename = wFilename.c_str();
109
+ eventname = wEventname.c_str();
110
+ }
111
+
112
+ hfilesz.QuadPart = size;
113
+
114
+ if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) {
115
+ event_ = CreateEventW(nullptr, FALSE, FALSE, eventname);
116
+ } else if (flags_ & ALLOCATOR_MAPPED_NOCREATE) {
117
+ event_ = OpenEventW(EVENT_ALL_ACCESS, FALSE, eventname);
118
+ } else {
119
+ TORCH_CHECK(false, "Expected either ALLOCATOR_MAPPED_EXCLUSIVE or ALLOCATOR_MAPPED_NOCREATE");
120
+ }
121
+
122
+ if (event_ == nullptr) {
123
+ TORCH_CHECK(false, "Couldn't open shared event: <", eventname, ">, error code: <", GetLastError(), ">");
124
+ }
125
+
126
+ if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) {
127
+ handle_ = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, filename);
128
+ } else if (flags_ & ALLOCATOR_MAPPED_NOCREATE) {
129
+ handle_ = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, filename);
130
+ } else {
131
+ TORCH_CHECK(false, "Expected either ALLOCATOR_MAPPED_EXCLUSIVE or ALLOCATOR_MAPPED_NOCREATE");
132
+ }
133
+
134
+ if (handle_ == nullptr) {
135
+ TORCH_CHECK(false, "Couldn't open shared file mapping: <", filename, ">, error code: <", GetLastError(), ">");
136
+ }
137
+
138
+ size_ = size;
139
+ base_ptr_ = MapViewOfFile(handle_, FILE_MAP_ALL_ACCESS, 0, 0, size);
140
+ if (!base_ptr_) {
141
+ TORCH_CHECK(false, "Couldn't map view of shared file <", filename, ">, error code: <", GetLastError(), ">");
142
+ }
143
+ } else {
144
+
145
+ HANDLE hfile;
146
+ HANDLE hmfile;
147
+ LARGE_INTEGER hfilesz;
148
+
149
+ if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) {
150
+ TORCH_CHECK(false, "exclusive file mapping is not supported on Windows");
151
+ }
152
+ if (flags_ & ALLOCATOR_MAPPED_NOCREATE) {
153
+ TORCH_CHECK(false, "file mapping without creation is not supported on Windows");
154
+ }
155
+ if (flags_ & ALLOCATOR_MAPPED_KEEPFD) {
156
+ TORCH_CHECK(false, "ALLOCATOR_MAPPED_KEEPFD not supported on Windows");
157
+ }
158
+ if (flags_ & ALLOCATOR_MAPPED_FROMFD) {
159
+ TORCH_CHECK(false, "ALLOCATOR_MAPPED_FROMFD not supported on Windows");
160
+ }
161
+
162
+ // Shadowing
163
+ const wchar_t *filename;
164
+ const std::wstring wFilename = c10::u8u16(filename_);
165
+
166
+ filename = wFilename.c_str();
167
+
168
+ /* open file */
169
+ /* FILE_FLAG_RANDOM_ACCESS ? */
170
+ if (flags_) {
171
+ hfile = CreateFileW(filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
172
+ if (hfile == INVALID_HANDLE_VALUE) {
173
+ TORCH_CHECK(false, "could not open file <", filename_, "> in read-write mode; error code: <", GetLastError(), ">");
174
+ }
175
+ } else {
176
+ hfile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
177
+ if (hfile == INVALID_HANDLE_VALUE) {
178
+ TORCH_CHECK(false, "could not open file <", filename_, "> in read-only mode; error code: <", GetLastError(), ">");
179
+ }
180
+ }
181
+
182
+ if (GetFileSizeEx(hfile, &hfilesz) == 0) {
183
+ TORCH_CHECK(false, "could not get file size: <", filename_, ">; error code: <", GetLastError(), ">");
184
+ }
185
+
186
+ if (size > 0) {
187
+ if (size > hfilesz.QuadPart) {
188
+ if (flags_) {
189
+ hfilesz.QuadPart = size;
190
+ if (SetFilePointerEx(hfile, hfilesz, NULL, FILE_BEGIN) == 0) {
191
+ CloseHandle(hfile);
192
+ TORCH_CHECK(false, "unable to stretch file <", filename_, "> to the right size; error code: <", GetLastError(), ">", filename_);
193
+ }
194
+ if (SetEndOfFile(hfile) == 0) {
195
+ CloseHandle(hfile);
196
+ TORCH_CHECK(false, "unable to write to file <", filename_, ">; error code: <", GetLastError(), ">");
197
+ }
198
+ } else {
199
+ CloseHandle(hfile);
200
+ TORCH_CHECK(false, "file <", filename_, "> size <", hfilesz.QuadPart, "> is smaller than the required mapping size <", size, ">; error code: <", GetLastError(), ">");
201
+ }
202
+ }
203
+ } else {
204
+ size = hfilesz.QuadPart;
205
+ }
206
+
207
+ size_ = size; /* if we are here, it must be the right size */
208
+
209
+ hfilesz.QuadPart = size_;
210
+
211
+ /* get map handle */
212
+ if (flags_) {
213
+ if ( (hmfile = CreateFileMappingW(hfile, NULL, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL ) {
214
+ TORCH_CHECK(false, "could not create a map on file <", filename_, ">; error code: <", GetLastError(), ">");
215
+ }
216
+ } else {
217
+ if ( (hmfile = CreateFileMappingW(hfile, NULL, PAGE_WRITECOPY, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL ) {
218
+ TORCH_CHECK(false, "could not create a map on file <", filename_, ">; error code: <", GetLastError(), ">");
219
+ }
220
+ }
221
+
222
+ /* map the stuff */
223
+ if(flags_) {
224
+ base_ptr_ = MapViewOfFile(hmfile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
225
+ } else {
226
+ base_ptr_ = MapViewOfFile(hmfile, FILE_MAP_COPY, 0, 0, 0);
227
+ }
228
+
229
+ CloseHandle(hfile);
230
+ CloseHandle(hmfile);
231
+ }
232
+ #else /* _WIN32 */
233
+ {
234
+ /* open file */
235
+ int fd{-1};
236
+ int flags{}; // shadow
237
+
238
+ if (flags_ & (ALLOCATOR_MAPPED_SHARED | ALLOCATOR_MAPPED_SHAREDMEM)) {
239
+ flags = O_RDWR | O_CREAT;
240
+ } else {
241
+ flags = O_RDONLY;
242
+ }
243
+
244
+ if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) {
245
+ flags |= O_EXCL;
246
+ }
247
+ if (flags_ & ALLOCATOR_MAPPED_NOCREATE) {
248
+ flags &= ~O_CREAT;
249
+ }
250
+
251
+ if (!(flags_ & ALLOCATOR_MAPPED_FROMFD)) {
252
+ if (flags_ & ALLOCATOR_MAPPED_SHARED) {
253
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
254
+ if ((fd = open(filename_.c_str(), flags, static_cast<mode_t>(0600))) == -1) {
255
+ TORCH_CHECK(false, "unable to open file <", filename_, "> in read-write mode: ", c10::utils::str_error(errno), " (", errno, ")");
256
+ }
257
+ } else if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
258
+ #ifdef HAVE_SHM_OPEN
259
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
260
+ if((fd = shm_open(filename_.c_str(), flags, static_cast<mode_t>(0600))) == -1) {
261
+ TORCH_CHECK(false, "unable to open shared memory object <", filename_, "> in read-write mode: ", c10::utils::str_error(errno), " (", errno, ")");
262
+ }
263
+ #else
264
+ TORCH_CHECK(false, "unable to open file <", filename_, "> in sharedmem mode, shm_open unavailable on this platform");
265
+ #endif
266
+ } else {
267
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
268
+ if ((fd = open(filename_.c_str(), O_RDONLY)) == -1) {
269
+ TORCH_CHECK(false, "unable to open file <", filename_, "> in read-only mode: ", c10::utils::str_error(errno), " (", errno, ")");
270
+ }
271
+ }
272
+ } else {
273
+ fd = fd_;
274
+ TORCH_INTERNAL_ASSERT(fd >= 0);
275
+ }
276
+
277
+ struct stat file_stat{};
278
+ if (fstat(fd, &file_stat) == -1) {
279
+ #ifndef STRIP_ERROR_MESSAGES
280
+ int last_err = errno;
281
+ #endif
282
+ if (!(flags_ & ALLOCATOR_MAPPED_FROMFD)) {
283
+ ::close(fd);
284
+ }
285
+ TORCH_CHECK(false, "unable to stat the file <", filename_, ">: ", c10::utils::str_error(last_err), " (", last_err, ")");
286
+ }
287
+
288
+ if (size > 0) {
289
+ if (static_cast<int64_t>(size) > file_stat.st_size) {
290
+ if (flags_) {
291
+ if (ftruncate(fd, static_cast<off_t>(size)) == -1) {
292
+ TORCH_CHECK(false, "unable to resize file <", filename_, "> to the right size: ", c10::utils::str_error(errno), " (", errno, ")");
293
+ }
294
+
295
+ #ifdef HAVE_POSIX_FALLOCATE
296
+ if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
297
+ for (;;) {
298
+ int err = posix_fallocate(fd, 0, static_cast<off_t>(size));
299
+ if (err == 0) {
300
+ break;
301
+ }
302
+
303
+ if (err == EINTR) {
304
+ continue;
305
+ }
306
+
307
+ if (err == EINVAL || err == EOPNOTSUPP) {
308
+ // the underlying filesystem does not support the operation
309
+ break;
310
+ }
311
+
312
+ TORCH_CHECK(false, "unable to allocate shared memory(shm) for file <", filename_, ">: ", c10::utils::str_error(err), " (", err, ")");
313
+ }
314
+ }
315
+ #endif
316
+
317
+ if (fstat(fd, &file_stat) == -1 || file_stat.st_size < static_cast<int64_t>(size)) {
318
+ #ifndef STRIP_ERROR_MESSAGES
319
+ int last_err = errno;
320
+ #endif
321
+ ::close(fd);
322
+ TORCH_CHECK(false, "unable to stretch file <", filename_, "> to the right size: ", c10::utils::str_error(last_err), " (", last_err, ")");
323
+ }
324
+ /* on macOS write returns with errno 45 (Operation not supported) when used
325
+ * with a file descriptor obtained via shm_open
326
+ */
327
+ #ifndef __APPLE__
328
+ if ((write(fd, "", 1)) != 1) /* note that the string "" contains the '\0' byte ... */ {
329
+ #ifndef STRIP_ERROR_MESSAGES
330
+ int last_err = errno;
331
+ #endif
332
+ ::close(fd);
333
+ TORCH_CHECK(false, "unable to write to file <", filename_, ">: ", c10::utils::str_error(last_err), " (", last_err, ")");
334
+ }
335
+ #endif
336
+ } else {
337
+ ::close(fd);
338
+ TORCH_CHECK(false, "file <", filename_, "> size <", file_stat.st_size, "> is smaller than the required mapping size <", size, ">");
339
+ }
340
+ }
341
+ } else {
342
+ size = file_stat.st_size;
343
+ }
344
+
345
+ size_ = static_cast<ptrdiff_t>(size); /* if we are here, it must be the right size */
346
+
347
+ /* map it */
348
+ if (flags_ & (ALLOCATOR_MAPPED_SHARED | ALLOCATOR_MAPPED_SHAREDMEM)) {
349
+ base_ptr_ = mmap(nullptr, size_, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
350
+ } else {
351
+ base_ptr_ = mmap(nullptr, size_, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
352
+ }
353
+
354
+ if (base_ptr_ == MAP_FAILED) {
355
+ base_ptr_ = nullptr; /* let's be sure it is NULL */
356
+ TORCH_CHECK(false, "unable to mmap ", size_, " bytes from file <", filename_, ">: ", c10::utils::str_error(errno), " (", errno, ")");
357
+ }
358
+
359
+ #if !defined(__APPLE__) && !defined(__ANDROID__)
360
+ /* attempt to use larger block size on Linux, which is important for getting better CUDA upload speed */
361
+ posix_fadvise(fd, 0, static_cast<off_t>(size), POSIX_FADV_SEQUENTIAL);
362
+ #endif
363
+
364
+ if (flags_ & ALLOCATOR_MAPPED_KEEPFD) {
365
+ fd_ = fd;
366
+ } else {
367
+ if (::close(fd) == -1) {
368
+ TORCH_CHECK(false, "Error closing file <", filename_, ">: ", c10::utils::str_error(errno), " (", errno, ")");
369
+ }
370
+ fd_ = -1;
371
+ }
372
+
373
+ if (flags_ & ALLOCATOR_MAPPED_UNLINK) {
374
+ if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
375
+ #ifdef HAVE_SHM_UNLINK
376
+ if (shm_unlink(filename_.c_str()) == -1) {
377
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")");
378
+ }
379
+ #else
380
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform");
381
+ #endif
382
+ } else {
383
+ if (unlink(filename_.c_str()) == -1)
384
+ TORCH_CHECK(false, "could not unlink file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")");
385
+ }
386
+ }
387
+
388
+ if (base_ptr_ == MAP_FAILED) {
389
+ TORCH_CHECK(false, "$ Torch: unable to mmap memory: you tried to mmap ", size_/1073741824, " GB.");
390
+ }
391
+ }
392
+ #endif
393
+ c10::reportMemoryUsageToProfiler(base_ptr_, size_, 0, size_, c10::Device(c10::DeviceType::CPU));
394
+ }
395
+
396
+ MapAllocator::MapAllocator(std::string_view filename, int flags, size_t size)
397
+ : MapAllocator(WITH_FD, filename, -1, flags, size)
398
+ {}
399
+
400
+ #ifdef _WIN32
401
+ struct ReleaseContext {
402
+ HANDLE event;
403
+ HANDLE handle;
404
+ HANDLE wait;
405
+ };
406
+ static void CALLBACK WaitForReleaseHandle(PVOID lpParam, BOOLEAN TimerOrWaitFired)
407
+ {
408
+ if (lpParam) {
409
+ ReleaseContext *ctx = (ReleaseContext *)lpParam;
410
+
411
+ SetEvent(ctx->event);
412
+ CloseHandle(ctx->event);
413
+ CloseHandle(ctx->handle);
414
+
415
+ UnregisterWait(ctx->wait);
416
+
417
+ delete ctx;
418
+ }
419
+ }
420
+ #endif
421
+
422
+ void MapAllocator::close() {
423
+ if (closed_) {
424
+ return;
425
+ }
426
+ closed_ = true;
427
+ if (base_ptr_ == nullptr) {
428
+ return;
429
+ }
430
+ #ifdef _WIN32
431
+ if ((flags_ & ALLOCATOR_MAPPED_KEEPFD) || (flags_ & ALLOCATOR_MAPPED_SHAREDMEM))
432
+ CloseHandle(handle_);
433
+ if(UnmapViewOfFile(base_ptr_) == 0)
434
+ TORCH_CHECK(false, "could not unmap the shared memory file");
435
+ #else /* _WIN32 */
436
+ if (flags_ & ALLOCATOR_MAPPED_KEEPFD) {
437
+ if (::close(fd_) == -1) {
438
+ TORCH_CHECK(false, "could not close file descriptor ", fd_, " :", c10::utils::str_error(errno), " (", errno, ")" );
439
+ }
440
+ }
441
+
442
+ if (munmap(base_ptr_, size_)) {
443
+ TORCH_CHECK(false, "could not unmap the shared memory file: ", c10::utils::str_error(errno), " (", errno, ")");
444
+ }
445
+
446
+ if (!(flags_ & (ALLOCATOR_MAPPED_FROMFD | ALLOCATOR_MAPPED_UNLINK))) {
447
+ if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
448
+ #ifdef HAVE_SHM_UNLINK
449
+ if (shm_unlink(filename_.c_str()) == -1) {
450
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")");
451
+ }
452
+ #else
453
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform");
454
+ #endif
455
+ }
456
+ }
457
+ #endif /* _WIN32 */
458
+ }
459
+
460
+ #else /* defined(_WIN32) || defined(HAVE_MMAP) */
461
+
462
+ MapAllocator::MapAllocator(std::string_view filename, int flags, size_t size) {
463
+ TORCH_CHECK(false, "file mapping not supported on your system");
464
+ }
465
+
466
+ MapAllocator::MapAllocator(WithFd, std::string_view filename, int fd, int flags, size_t size) {
467
+ TORCH_CHECK(false, "file mapping not supported on your system");
468
+ }
469
+
470
+ void MapAllocator::close() { }
471
+
472
+ #endif
473
+
474
+ #if (defined(_WIN32) || defined(HAVE_MMAP)) && defined(AT_ATOMIC_IPC_REFCOUNT)
475
+
476
+ RefcountedMapAllocatorArgCheck::RefcountedMapAllocatorArgCheck(int flags) {
477
+ if (flags & ALLOCATOR_MAPPED_FROMFD) {
478
+ TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_FROMFD flag");
479
+ }
480
+ if (flags & ALLOCATOR_MAPPED_KEEPFD) {
481
+ TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_KEEPFD flag");
482
+ }
483
+ if (flags & ALLOCATOR_MAPPED_UNLINK) {
484
+ TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_UNLINK flag");
485
+ }
486
+ if (!(flags & ALLOCATOR_MAPPED_SHAREDMEM)) {
487
+ TORCH_CHECK(false, "RefcountedMapAllocator requires ALLOCATOR_MAPPED_SHAREDMEM flag");
488
+ }
489
+ }
490
+
491
+ RefcountedMapAllocator::RefcountedMapAllocator(const char *filename, int flags, size_t size)
492
+ : RefcountedMapAllocatorArgCheck(flags)
493
+ , MapAllocator(filename, flags, size + map_alloc_alignment) {
494
+
495
+ initializeAlloc();
496
+ }
497
+ RefcountedMapAllocator::RefcountedMapAllocator(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size)
498
+ : RefcountedMapAllocatorArgCheck(flags)
499
+ , MapAllocator(WITH_FD, filename, flags, fd, size + map_alloc_alignment) {
500
+
501
+ initializeAlloc();
502
+ }
503
+
504
+ void RefcountedMapAllocator::initializeAlloc() {
505
+ TORCH_CHECK(base_ptr_, "base_ptr_ is null");
506
+ MapInfo *map_info = static_cast<MapInfo*>(base_ptr_);
507
+
508
+ #ifdef _WIN32
509
+ ReleaseContext* r_ctx = new ReleaseContext;
510
+ r_ctx->handle = handle_;
511
+ r_ctx->event = event_;
512
+ r_ctx->wait = NULL;
513
+ BOOL can_wait = RegisterWaitForSingleObject(&r_ctx->wait, event_, WaitForReleaseHandle, (PVOID)r_ctx, INFINITE, WT_EXECUTEONLYONCE);
514
+ TORCH_CHECK(can_wait, "Couldn't register wait on event, error code: <", GetLastError(), ">");
515
+ #endif
516
+
517
+ if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) {
518
+ new (&map_info->refcount) std::atomic<int>(1);
519
+ } else {
520
+ map_info->refcount++;
521
+ }
522
+ }
523
+
524
+ void RefcountedMapAllocator::close() {
525
+ if (closed_) {
526
+ return;
527
+ }
528
+ closed_ = true;
529
+
530
+ void* data = base_ptr_;
531
+
532
+ #ifdef _WIN32
533
+ MapInfo *info = (MapInfo*)data;
534
+ if (--info->refcount == 0) {
535
+ SetEvent(event_);
536
+ }
537
+ if(UnmapViewOfFile(data) == 0) {
538
+ TORCH_CHECK(false, "could not unmap the shared memory file");
539
+ }
540
+ #else /* _WIN32 */
541
+
542
+ MapInfo *info = static_cast<MapInfo*>(data);
543
+ if (--info->refcount == 0) {
544
+ #ifdef HAVE_SHM_UNLINK
545
+ if (shm_unlink(filename_.c_str()) == -1) {
546
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_);
547
+ }
548
+ #else
549
+ TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform");
550
+ #endif /* HAVE_SHM_UNLINK */
551
+ }
552
+ if (munmap(info, size_)) {
553
+ TORCH_CHECK(false, "could not unmap the shared memory file ", filename_);
554
+ }
555
+ #endif /* _WIN32 */
556
+ }
557
+
558
+ void RefcountedMapAllocator::incref()
559
+ {
560
+ MapInfo *map_info = static_cast<MapInfo*>(base_ptr_);
561
+ ++map_info->refcount;
562
+ }
563
+
564
+ int RefcountedMapAllocator::decref()
565
+ {
566
+ MapInfo *map_info = static_cast<MapInfo*>(base_ptr_);
567
+ return --map_info->refcount == 0;
568
+ }
569
+
570
+ #else
571
+
572
+
573
+ RefcountedMapAllocatorArgCheck::RefcountedMapAllocatorArgCheck(int flags) {}
574
+
575
+ RefcountedMapAllocator::RefcountedMapAllocator(const char *filename, int flags, size_t size)
576
+ : RefcountedMapAllocatorArgCheck(flags),
577
+ MapAllocator(filename, flags, size + map_alloc_alignment)
578
+ {
579
+ TORCH_CHECK(false, "refcounted file mapping not supported on your system");
580
+ }
581
+
582
+ RefcountedMapAllocator::RefcountedMapAllocator(WithFd, const char *filename, int fd, int flags, size_t size)
583
+ : RefcountedMapAllocatorArgCheck(flags),
584
+ MapAllocator(WITH_FD, filename, flags, fd, size + map_alloc_alignment)
585
+ {
586
+ TORCH_CHECK(false, "refcounted file mapping not supported on your system");
587
+ }
588
+
589
+ void RefcountedMapAllocator::initializeAlloc() {}
590
+
591
+ void RefcountedMapAllocator::close() {}
592
+
593
+ #endif
594
+
595
+ static void deleteMapAllocator(void* ptr) {
596
+ delete static_cast<MapAllocator*>(ptr);
597
+ }
598
+
599
+ static void deleteRefcountedMapAllocator(void* ptr) {
600
+ delete static_cast<RefcountedMapAllocator*>(ptr);
601
+ }
602
+
603
+ MapAllocator* MapAllocator::fromDataPtr(const at::DataPtr& dptr) {
604
+ return dptr.cast_context<MapAllocator>(&deleteMapAllocator);
605
+ }
606
+
607
+ RefcountedMapAllocator* RefcountedMapAllocator::fromDataPtr(const at::DataPtr& dptr) {
608
+ return dptr.cast_context<RefcountedMapAllocator>(&deleteRefcountedMapAllocator);
609
+ }
610
+
611
+ at::DataPtr MapAllocator::makeDataPtr(std::string_view filename, int flags, size_t size, size_t* actual_size_out) {
612
+ auto* context = new MapAllocator(filename, flags, size);
613
+ if (actual_size_out) *actual_size_out = context->size();
614
+ return {context->data(), context, &deleteMapAllocator, at::DeviceType::CPU};
615
+ }
616
+
617
+ at::DataPtr MapAllocator::makeDataPtr(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size, size_t* actual_size_out) {
618
+ auto* context = new MapAllocator(WITH_FD, filename, fd, flags, size);
619
+ if (actual_size_out) *actual_size_out = context->size();
620
+ return {context->data(), context, &deleteMapAllocator, at::DeviceType::CPU};
621
+ }
622
+
623
+ at::DataPtr RefcountedMapAllocator::makeDataPtr(const char *filename, int flags, size_t size, size_t* actual_size_out) {
624
+ auto* context = new RefcountedMapAllocator(filename, flags, size);
625
+ if (actual_size_out) *actual_size_out = context->size() - map_alloc_alignment;
626
+ return {context->data(), context, &deleteRefcountedMapAllocator, at::DeviceType::CPU};
627
+ }
628
+
629
+ at::DataPtr RefcountedMapAllocator::makeDataPtr(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size, size_t* actual_size_out) {
630
+ auto* context = new RefcountedMapAllocator(WITH_FD, filename, fd, flags, size);
631
+ if (actual_size_out) *actual_size_out = context->size() - map_alloc_alignment;
632
+ return {context->data(), context, &deleteRefcountedMapAllocator, at::DeviceType::CPU};
633
+ }
634
+
635
+ void* RefcountedMapAllocator::data() const {
636
+ return static_cast<void*>(static_cast<char*>(base_ptr_) + map_alloc_alignment);
637
+ }
638
+
639
+ MapAllocator::~MapAllocator() {
640
+ MapAllocator::close();
641
+ c10::reportMemoryUsageToProfiler(base_ptr_, -size_, 0, 0, c10::Device(c10::DeviceType::CPU));
642
+ }
643
+
644
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/MapAllocator.h ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <string_view>
5
+
6
+ namespace at {
7
+
8
+ enum MappedAllocatorModes {
9
+ ALLOCATOR_MAPPED_SHARED = 1,
10
+ ALLOCATOR_MAPPED_SHAREDMEM = 2,
11
+ ALLOCATOR_MAPPED_EXCLUSIVE = 4,
12
+ ALLOCATOR_MAPPED_NOCREATE = 8,
13
+ ALLOCATOR_MAPPED_KEEPFD = 16,
14
+ ALLOCATOR_MAPPED_FROMFD = 32,
15
+ ALLOCATOR_MAPPED_UNLINK = 64
16
+ };
17
+
18
+ // Sentinel value/type to help distinguish the file descriptor constructor from
19
+ // the non-file descriptor constructor
20
+ enum WithFd { WITH_FD };
21
+
22
+ TORCH_API std::string NewProcessWideShmHandle();
23
+
24
+ class TORCH_API MapAllocator {
25
+ public:
26
+ MapAllocator(std::string_view filename, int flags, size_t size);
27
+ MapAllocator(
28
+ WithFd /*unused*/,
29
+ std::string_view filename,
30
+ int fd,
31
+ int flags,
32
+ size_t size);
33
+ MapAllocator(const MapAllocator&) = delete;
34
+ MapAllocator& operator=(const MapAllocator&) = delete;
35
+ MapAllocator(MapAllocator&&) = delete;
36
+ MapAllocator& operator=(MapAllocator&&) = delete;
37
+
38
+ const char* filename() const {
39
+ return filename_.c_str();
40
+ }
41
+ int fd() const {
42
+ #ifdef _WIN32
43
+ TORCH_CHECK(false, "MapAllocator::fd() is unsupported on Windows");
44
+ #else
45
+ return fd_;
46
+ #endif
47
+ }
48
+ ptrdiff_t size() const {
49
+ return size_;
50
+ }
51
+ // Return a pointer to the actual data for this allocator
52
+ // (in the case of the refcounted allocator, this is offset
53
+ // from the base pointer.)
54
+ virtual void* data() const {
55
+ return base_ptr_;
56
+ }
57
+
58
+ int flags() const {
59
+ return flags_;
60
+ }
61
+
62
+ static MapAllocator* fromDataPtr(const at::DataPtr& /*dptr*/);
63
+ static at::DataPtr makeDataPtr(
64
+ std::string_view filename,
65
+ int flags,
66
+ size_t size,
67
+ size_t* actual_size_out);
68
+ static at::DataPtr makeDataPtr(
69
+ WithFd /*unused*/,
70
+ const char* filename,
71
+ int fd,
72
+ int flags,
73
+ size_t size,
74
+ size_t* actual_size_out);
75
+
76
+ // Closes the data. Helps us avoid destructor shenanigans
77
+ virtual void close();
78
+
79
+ // This is very dangerous. You have to redefine this destructor for each
80
+ // subclass
81
+ virtual ~MapAllocator();
82
+
83
+ protected:
84
+ bool closed_ = false;
85
+ std::string filename_;
86
+ int flags_ = 0;
87
+ ptrdiff_t size_; /* mapped size */
88
+ #ifdef _WIN32
89
+ void* handle_;
90
+ void* event_;
91
+ std::string eventname_;
92
+ #else
93
+ int fd_ = -1;
94
+ #endif
95
+ void* base_ptr_ = nullptr;
96
+ };
97
+
98
+ // Base-from-member idiom
99
+ struct TORCH_API RefcountedMapAllocatorArgCheck {
100
+ RefcountedMapAllocatorArgCheck(int flags);
101
+ };
102
+
103
+ class TORCH_API RefcountedMapAllocator : private RefcountedMapAllocatorArgCheck,
104
+ public MapAllocator {
105
+ public:
106
+ RefcountedMapAllocator(const char* filename, int flags, size_t size);
107
+ RefcountedMapAllocator(
108
+ WithFd /*unused*/,
109
+ const char* filename,
110
+ int fd,
111
+ int flags,
112
+ size_t size);
113
+
114
+ static RefcountedMapAllocator* fromDataPtr(const at::DataPtr& /*dptr*/);
115
+ RefcountedMapAllocator(const RefcountedMapAllocator&) = delete;
116
+ RefcountedMapAllocator(RefcountedMapAllocator&&) = delete;
117
+ RefcountedMapAllocator& operator=(const RefcountedMapAllocator&) = delete;
118
+ RefcountedMapAllocator& operator=(RefcountedMapAllocator&&) = delete;
119
+ static at::DataPtr makeDataPtr(
120
+ const char* filename,
121
+ int flags,
122
+ size_t size,
123
+ size_t* actual_size_out);
124
+ static at::DataPtr makeDataPtr(
125
+ WithFd /*unused*/,
126
+ const char* filename,
127
+ int fd,
128
+ int flags,
129
+ size_t size,
130
+ size_t* actual_size_out);
131
+
132
+ void* data() const override;
133
+
134
+ void incref();
135
+ int decref();
136
+ void close() override;
137
+
138
+ ~RefcountedMapAllocator() override {
139
+ RefcountedMapAllocator::close();
140
+ }
141
+
142
+ protected:
143
+ void checkFlags();
144
+ void initializeAlloc();
145
+ };
146
+
147
+ } // namespace at
western_ai/usa/pytorch/aten/src/ATen/MatrixRef.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/Utils.h>
3
+ #include <c10/util/ArrayRef.h>
4
+
5
+ namespace at {
6
+ /// MatrixRef - Like an ArrayRef, but with an extra recorded strides so that
7
+ /// we can easily view it as a multidimensional array.
8
+ ///
9
+ /// Like ArrayRef, this class does not own the underlying data, it is expected
10
+ /// to be used in situations where the data resides in some other buffer.
11
+ ///
12
+ /// This is intended to be trivially copyable, so it should be passed by
13
+ /// value.
14
+ ///
15
+ /// For now, 2D only (so the copies are actually cheap, without having
16
+ /// to write a SmallVector class) and contiguous only (so we can
17
+ /// return non-strided ArrayRef on index).
18
+ ///
19
+ /// P.S. dimension 0 indexes rows, dimension 1 indexes columns
20
+ template <typename T>
21
+ class MatrixRef {
22
+ public:
23
+ typedef size_t size_type;
24
+
25
+ private:
26
+ /// Underlying ArrayRef
27
+ ArrayRef<T> arr;
28
+
29
+ /// Stride of dim 0 (outer dimension)
30
+ size_type stride0;
31
+
32
+ // Stride of dim 1 is assumed to be 1
33
+
34
+ public:
35
+ /// Construct an empty Matrixref.
36
+ /*implicit*/ MatrixRef() : arr(nullptr), stride0(0) {}
37
+
38
+ /// Construct an MatrixRef from an ArrayRef and outer stride.
39
+ /*implicit*/ MatrixRef(ArrayRef<T> arr, size_type stride0)
40
+ : arr(arr), stride0(stride0) {
41
+ TORCH_CHECK(
42
+ arr.size() % stride0 == 0,
43
+ "MatrixRef: ArrayRef size ",
44
+ arr.size(),
45
+ " not divisible by stride ",
46
+ stride0)
47
+ }
48
+
49
+ /// @}
50
+ /// @name Simple Operations
51
+ /// @{
52
+
53
+ /// empty - Check if the matrix is empty.
54
+ bool empty() const {
55
+ return arr.empty();
56
+ }
57
+
58
+ const T* data() const {
59
+ return arr.data();
60
+ }
61
+
62
+ /// size - Get size a dimension
63
+ size_t size(size_t dim) const {
64
+ if (dim == 0) {
65
+ return arr.size() / stride0;
66
+ } else if (dim == 1) {
67
+ return stride0;
68
+ } else {
69
+ TORCH_CHECK(
70
+ 0, "MatrixRef: out of bounds dimension ", dim, "; expected 0 or 1");
71
+ }
72
+ }
73
+
74
+ size_t numel() const {
75
+ return arr.size();
76
+ }
77
+
78
+ /// equals - Check for element-wise equality.
79
+ bool equals(MatrixRef RHS) const {
80
+ return stride0 == RHS.stride0 && arr.equals(RHS.arr);
81
+ }
82
+
83
+ /// @}
84
+ /// @name Operator Overloads
85
+ /// @{
86
+ ArrayRef<T> operator[](size_t Index) const {
87
+ return arr.slice(Index * stride0, stride0);
88
+ }
89
+
90
+ /// Disallow accidental assignment from a temporary.
91
+ ///
92
+ /// The declaration here is extra complicated so that "arrayRef = {}"
93
+ /// continues to select the move assignment operator.
94
+ template <typename U>
95
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
96
+ std::enable_if_t<std::is_same_v<U, T>, MatrixRef<T>>& operator=(
97
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
98
+ U&& Temporary) = delete;
99
+
100
+ /// Disallow accidental assignment from a temporary.
101
+ ///
102
+ /// The declaration here is extra complicated so that "arrayRef = {}"
103
+ /// continues to select the move assignment operator.
104
+ template <typename U>
105
+ std::enable_if_t<std::is_same_v<U, T>, MatrixRef<T>>& operator=(
106
+ std::initializer_list<U>) = delete;
107
+ };
108
+
109
+ } // end namespace at
western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.cpp ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/MemoryOverlap.h>
2
+ #include <ATen/core/TensorBase.h>
3
+ #include <c10/util/irange.h>
4
+
5
+ namespace at {
6
+
7
+ MemOverlap has_internal_overlap(const TensorBase& tensor) {
8
+ return has_internal_overlap(tensor.unsafeGetTensorImpl());
9
+ }
10
+
11
+ MemOverlap has_internal_overlap(TensorImpl* t) {
12
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(t->layout() == kStrided);
13
+
14
+ auto sizes = t->sym_sizes();
15
+ auto strides = t->sym_strides();
16
+
17
+ // When we have unbacked symint strides, is_non_overlapping_and_dense
18
+ // often results in guard on data dependent errors. For now
19
+ // let us bail early if there are unbacked symint strides.
20
+ for (const auto i : c10::irange(strides.size())) {
21
+ if (!strides[i].has_hint()) {
22
+ return MemOverlap::TooHard;
23
+ }
24
+ }
25
+
26
+ if (t->is_non_overlapping_and_dense_or_false()) {
27
+ return MemOverlap::No;
28
+ }
29
+
30
+ for (const auto i : c10::irange(strides.size())) {
31
+ // NB: The size oblivious test is written very carefully here. When
32
+ // unbacked SymInts are involved, we should try to conservatively report
33
+ // if memory overlap /could/ happen under some setting of unbacked
34
+ // SymInts. Thus, if I have u0 size, we should assume that this has > 1
35
+ // elements (first expression), but if I have a u0 stride, I should NOT
36
+ // assume that it is not zero (second expression)
37
+ if (TORCH_GUARD_OR_FALSE(sizes[i].sym_gt(1)) && strides[i] == 0) {
38
+ return MemOverlap::Yes;
39
+ }
40
+ }
41
+
42
+ return MemOverlap::TooHard;
43
+ }
44
+
45
+ void assert_no_internal_overlap(const TensorBase& t) {
46
+ assert_no_internal_overlap(t.unsafeGetTensorImpl());
47
+ }
48
+
49
+ void assert_no_internal_overlap(TensorImpl* t) {
50
+ TORCH_CHECK(has_internal_overlap(t) != MemOverlap::Yes,
51
+ "unsupported operation: more than one element of the written-to tensor "
52
+ "refers to a single memory location. Please clone() the tensor before "
53
+ "performing the operation.");
54
+ }
55
+
56
+ MemOverlapStatus get_overlap_status(const TensorBase& a, const TensorBase& b) {
57
+ return get_overlap_status(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl());
58
+ }
59
+
60
+ MemOverlapStatus get_overlap_status(const TensorImpl* a, const TensorImpl* b) {
61
+ if (a == b) return MemOverlapStatus::Full;
62
+ if (a->numel() == 0 || b->numel() == 0) {
63
+ return MemOverlapStatus::No;
64
+ }
65
+ if (!a->is_non_overlapping_and_dense_or_false() || !b->is_non_overlapping_and_dense_or_false()) {
66
+ return MemOverlapStatus::TooHard;
67
+ }
68
+ // Test for storage equality, rather than pointer equality.
69
+ // This reduces precision, but if people are aliasing the
70
+ // same pointer across multiple storages there are many
71
+ // similar situations (e.g., storage().data() == storage().data()+1)
72
+ // which we will miss.
73
+ const auto& a_storage = a->unsafe_storage();
74
+ if (a_storage && a_storage.is_alias_of(b->unsafe_storage())) {
75
+ const auto a_begin = static_cast<const char*>(a->data());
76
+ const auto a_end = a_begin + a->numel() * a->itemsize();
77
+ const auto b_begin = static_cast<const char*>(b->data());
78
+ const auto b_end = b_begin + b->numel() * b->itemsize();
79
+
80
+ if (a_begin == b_begin && a_end == b_end) {
81
+ return (a->strides() == b->strides()) ?
82
+ MemOverlapStatus::Full : MemOverlapStatus::Partial;
83
+ }
84
+ if (a_begin < b_end && b_begin < a_end) {
85
+ return MemOverlapStatus::Partial;
86
+ }
87
+ }
88
+ return MemOverlapStatus::No;
89
+ }
90
+
91
+ void assert_no_partial_overlap(const TensorBase& a, const TensorBase& b) {
92
+ assert_no_partial_overlap(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl());
93
+ }
94
+
95
+ void assert_no_partial_overlap(TensorImpl* a, TensorImpl* b) {
96
+ TORCH_CHECK(get_overlap_status(a, b) != MemOverlapStatus::Partial,
97
+ "unsupported operation: some elements of the input tensor and "
98
+ "the written-to tensor refer to a single memory location. "
99
+ "Please clone() the tensor before performing the operation.");
100
+ }
101
+
102
+ void assert_no_overlap(const TensorBase& a, const TensorBase& b) {
103
+ assert_no_overlap(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl());
104
+ }
105
+
106
+ void assert_no_overlap(TensorImpl* a, TensorImpl* b) {
107
+ const auto lap = get_overlap_status(a, b);
108
+ TORCH_CHECK(lap != MemOverlapStatus::Partial && lap != MemOverlapStatus::Full,
109
+ "unsupported operation: some elements of the input tensor and "
110
+ "the written-to tensor refer to a single memory location. "
111
+ "Please clone() the tensor before performing the operation.");
112
+ }
113
+
114
+ }