assassinlike commited on
Commit
e638be6
·
verified ·
1 Parent(s): 9252c7e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Descriptors.h +409 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Handle.h +9 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Handles.h +2 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Types.h +14 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Utils.h +22 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/cudnn-wrapper.h +16 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/AcceleratorHooksInterface.h +96 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/CUDAHooksInterface.h +224 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/FunctionTraits.h +103 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/HIPHooksInterface.h +67 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/HPUHooksInterface.h +57 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/IPUHooksInterface.h +43 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MAIAHooksInterface.h +42 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MPSHooksInterface.h +125 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MTIAHooksInterface.h +164 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/PrivateUse1HooksInterface.h +89 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/XPUHooksInterface.h +84 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/ADInterpreters.h +38 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchRulesHelper.h +481 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedFallback.h +81 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h +170 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h +126 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/DynamicLayer.h +124 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h +22 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/Interpreter.h +351 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h +187 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/Macros.h +3 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/PlumbingHelper.h +63 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/TensorWrapper.h +103 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/VmapInterpreter.h +25 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h +169 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h +41 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h +9 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h +13 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h +18 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h +21 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h +28 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h +73 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h +49 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +321 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h +173 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h +304 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h +46 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h +97 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h +34 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h +14 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Copy.h +20 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h +14 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h +229 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h +495 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Descriptors.h ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/cuda/Exceptions.h>
7
+
8
+ #include <ATen/cudnn/cudnn-wrapper.h>
9
+ #include <ATen/cudnn/Utils.h>
10
+ #include <ATen/core/Tensor.h>
11
+ #include <ATen/TensorUtils.h>
12
+ #include <ATen/cuda/ATenCUDAGeneral.h>
13
+ #include <cuda.h>
14
+
15
+ #ifndef AT_PER_OPERATOR_HEADERS
16
+ #include <ATen/Functions.h>
17
+ #else
18
+ #include <ATen/ops/empty.h>
19
+ #endif
20
+
21
+ #if defined(CUDNN_VERSION) && CUDNN_VERSION >= 8907
22
+ #define USE_CUDNN_RNN_V8_API
23
+ #endif
24
+
25
+ namespace at::native {
26
+
27
+ std::string cudnnTypeToString(cudnnDataType_t dtype);
28
+
29
+ // TODO: Add constructors for all of the descriptors
30
+
31
+ inline int dataSize(cudnnDataType_t dataType)
32
+ {
33
+ switch (dataType) {
34
+ case CUDNN_DATA_BFLOAT16:
35
+ case CUDNN_DATA_HALF: return 2;
36
+ case CUDNN_DATA_FLOAT: return 4;
37
+ default: return 8;
38
+ }
39
+ }
40
+
41
+ // The stride for a size-1 dimensions is not uniquely determined; in
42
+ // fact, it can be anything you want, because the fact that the
43
+ // tensor is size 1 at this dimension means that you will never actually
44
+ // try advancing your pointer by this stride.
45
+ //
46
+ // However, CuDNN has a much more stringent requirement on strides:
47
+ // if you are passing a contiguous input, it better be the case
48
+ // that the stride for dim i is the product of the sizes of dims
49
+ // i+1 to the end. This stride is indeed uniquely determined. This
50
+ // function modifies 'stride' in place so this invariant holds.
51
+ template <typename T>
52
+ static inline void fixSizeOneDimStride(int dim, const T *size, T *stride, bool nhwc) {
53
+ int64_t z = 1;
54
+ int index = 0;
55
+ std::vector<int> permutation(dim);
56
+
57
+ if (nhwc) {
58
+ permutation[index++] = 1;
59
+ }
60
+ for (int d = dim-1; d > 1; d--) {
61
+ permutation[index++] = d;
62
+ }
63
+ if (!nhwc) {
64
+ permutation[index++] = 1;
65
+ }
66
+ permutation[index++] = 0;
67
+ for (int d : permutation) {
68
+ if (size[d] == 1) {
69
+ stride[d] = z;
70
+ } else {
71
+ z *= size[d];
72
+ }
73
+ }
74
+ }
75
+
76
+ template <typename T, cudnnStatus_t (*dtor)(T*)>
77
+ struct DescriptorDeleter {
78
+ void operator()(T* x) {
79
+ if (x != nullptr) {
80
+ AT_CUDNN_CHECK(dtor(x));
81
+ }
82
+ }
83
+ };
84
+
85
+ // A generic class for wrapping cuDNN descriptor types. All you need
86
+ // is to give the underlying type the Descriptor_t points to (usually,
87
+ // if it's cudnnTensorDescriptor_t it points to cudnnTensorStruct),
88
+ // the constructor and the destructor. Subclasses are responsible
89
+ // for defining a set() function to actually set the descriptor.
90
+ //
91
+ // Descriptors default construct to a nullptr, and have a descriptor
92
+ // initialized the first time you call set() or any other initializing
93
+ // function.
94
+ template <typename T, cudnnStatus_t (*ctor)(T**), cudnnStatus_t (*dtor)(T*)>
95
+ // NOLINTNEXTLINE(bugprone-exception-escape)
96
+ class TORCH_CUDA_CPP_API Descriptor {
97
+ public:
98
+ // TODO: Figure out why const-correctness doesn't work here
99
+
100
+ // Use desc() to access the underlying descriptor pointer in
101
+ // a read-only fashion. Most client code should use this.
102
+ // If the descriptor was never initialized, this will return
103
+ // nullptr.
104
+ T* desc() const { return desc_.get(); }
105
+ T* desc() { return desc_.get(); }
106
+
107
+ // Use mut_desc() to access the underlying descriptor pointer
108
+ // if you intend to modify what it points to (e.g., using
109
+ // cudnnSetFooDescriptor). This will ensure that the descriptor
110
+ // is initialized. Code in this file will use this function.
111
+ T* mut_desc() { init(); return desc_.get(); }
112
+ protected:
113
+ void init() {
114
+ if (desc_ == nullptr) {
115
+ T* raw_desc = nullptr;
116
+ AT_CUDNN_CHECK(ctor(&raw_desc));
117
+ desc_.reset(raw_desc);
118
+ }
119
+ }
120
+ private:
121
+ std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_;
122
+ };
123
+
124
+ class TORCH_CUDA_CPP_API RNNDataDescriptor : public Descriptor<
125
+ cudnnRNNDataStruct,
126
+ &cudnnCreateRNNDataDescriptor,
127
+ &cudnnDestroyRNNDataDescriptor> {
128
+ public:
129
+ void set(const at::Tensor &t, cudnnRNNDataLayout_t layout, int maxSeqLength, int batchSize, int vectorSize, const int* seqLengthArray);
130
+ private:
131
+ void set(cudnnDataType_t dataType, cudnnRNNDataLayout_t layout, int maxSeqLength, int batchSize, int vectorSize, const int* seqLengthArray) {
132
+ AT_CUDNN_CHECK(cudnnSetRNNDataDescriptor(mut_desc(), dataType, layout, maxSeqLength, batchSize, vectorSize, seqLengthArray, nullptr));
133
+ }
134
+ };
135
+
136
+ class TORCH_CUDA_CPP_API TensorDescriptor : public Descriptor<
137
+ cudnnTensorStruct,
138
+ &cudnnCreateTensorDescriptor,
139
+ &cudnnDestroyTensorDescriptor> {
140
+ public:
141
+ TensorDescriptor() = default;
142
+ explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) {
143
+ set(t, pad);
144
+ }
145
+
146
+ // Note [CuDNN broadcast padding]
147
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148
+ // pad specifies the minimum dimensionality of the tensor descriptor
149
+ // we produce (it doesn't have anything to do with, e.g., convolution
150
+ // padding). If 't' is lower-dimensional than 'pad', the remaining
151
+ // dimensions (on the right) are padded with ones. This doesn't
152
+ // affect the underlying data layout. This is particularly useful for
153
+ // dealing with a peculiarity of the CuDNN API, which is that broadcasting in CuDNN is
154
+ // done in two steps: first, the client code is expected to pad out
155
+ // (the dimensions) input tensors to be the same dimension as the
156
+ // target broadcast, and then second, CuDNN takes of actually
157
+ // broadcasting size 1 dimensions.
158
+
159
+ void set(const at::Tensor &t, size_t pad = 0);
160
+ void set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad = 0);
161
+ void set(cudnnDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0);
162
+
163
+ void print();
164
+
165
+ private:
166
+ void set(cudnnDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad, bool nhwc);
167
+
168
+ void set(cudnnDataType_t dataType, int dim, int* size, int* stride, bool nhwc) {
169
+ std::vector<int> strides_copy(stride, stride + dim);
170
+ fixSizeOneDimStride<int>(dim, size, strides_copy.data(), nhwc);
171
+ AT_CUDNN_CHECK(cudnnSetTensorNdDescriptor(mut_desc(), dataType, dim, size, strides_copy.data()));
172
+ }
173
+ };
174
+
175
+ std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d);
176
+
177
+ class TORCH_CUDA_CPP_API FilterDescriptor : public Descriptor<
178
+ cudnnFilterStruct,
179
+ &cudnnCreateFilterDescriptor,
180
+ &cudnnDestroyFilterDescriptor> {
181
+ public:
182
+ void set(const at::Tensor &t, int64_t pad = 0) {
183
+ set(t, at::MemoryFormat::Contiguous, pad);
184
+ }
185
+
186
+ void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0);
187
+
188
+ void print();
189
+ private:
190
+ void set(cudnnDataType_t dataType, int dim, int* size, cudnnTensorFormat_t filter_format) {
191
+ AT_CUDNN_CHECK(cudnnSetFilterNdDescriptor(mut_desc(), dataType, filter_format, dim, size));
192
+ }
193
+ };
194
+
195
+ std::ostream& operator<<(std::ostream & out, const FilterDescriptor& d);
196
+
197
+ struct TORCH_CUDA_CPP_API ConvolutionDescriptor
198
+ : public Descriptor<
199
+ cudnnConvolutionStruct,
200
+ &cudnnCreateConvolutionDescriptor,
201
+ &cudnnDestroyConvolutionDescriptor> {
202
+ void set(cudnnDataType_t dataType, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool allow_tf32) {
203
+ cudnnDataType_t mathType = dataType;
204
+ if (dataType == CUDNN_DATA_HALF) mathType = CUDNN_DATA_FLOAT;
205
+ AT_CUDNN_CHECK(cudnnSetConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale,
206
+ CUDNN_CROSS_CORRELATION, mathType));
207
+ AT_CUDNN_CHECK(cudnnSetConvolutionGroupCount(mut_desc(), groups));
208
+ // See Note [behavior of cudnnFind and cudnnGet]
209
+ AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_DEFAULT_MATH));
210
+ if(dataType == CUDNN_DATA_HALF) {
211
+ AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_TENSOR_OP_MATH));
212
+ } else if (dataType == CUDNN_DATA_FLOAT && !allow_tf32) {
213
+ AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_FMA_MATH));
214
+ }
215
+ }
216
+ };
217
+
218
+ struct TORCH_CUDA_CPP_API SpatialTransformerDescriptor
219
+ : public Descriptor<
220
+ cudnnSpatialTransformerStruct,
221
+ &cudnnCreateSpatialTransformerDescriptor,
222
+ &cudnnDestroySpatialTransformerDescriptor> {
223
+ void set(cudnnDataType_t dataType, int dim, int* size) {
224
+ AT_CUDNN_CHECK(cudnnSetSpatialTransformerNdDescriptor(mut_desc(), CUDNN_SAMPLER_BILINEAR, dataType, dim, size));
225
+ }
226
+ };
227
+
228
+ // NOLINTNEXTLINE(bugprone-exception-escape)
229
+ struct TORCH_CUDA_CPP_API DropoutDescriptor
230
+ : public Descriptor<
231
+ cudnnDropoutStruct,
232
+ &cudnnCreateDropoutDescriptor,
233
+ &cudnnDestroyDropoutDescriptor> {
234
+ at::Tensor state;
235
+
236
+ // Initialize a dropout descriptor's RNG state.
237
+ // WARNING: This function is very expensive, avoid calling this function!
238
+ void initialize_rng(cudnnHandle_t handle, float dropout, long long int seed, const TensorOptions& options) {
239
+ TORCH_INTERNAL_ASSERT(dropout > 0, "dropout must be nonzero; otherwise call set_no_dropout");
240
+ size_t state_size = 0;
241
+ AT_CUDNN_CHECK(cudnnDropoutGetStatesSize(handle, &state_size));
242
+ AT_ASSERT(options.device().type() == kCUDA);
243
+ AT_ASSERT(options.dtype() == kByte);
244
+ state = at::empty({static_cast<int64_t>(state_size)}, options);
245
+ AT_CUDNN_CHECK(cudnnSetDropoutDescriptor(mut_desc(), handle, dropout, state.data_ptr(), state_size, seed));
246
+ }
247
+
248
+ // Restore a dropout descriptor given a dropout probability and existing RNG state.
249
+ void set(cudnnHandle_t handle, float dropout, const at::Tensor& state) {
250
+ TORCH_INTERNAL_ASSERT(dropout > 0, "dropout must be nonzero; otherwise call set_no_dropout");
251
+ void *state_ptr = state.data_ptr();
252
+ size_t state_size = state.size(0);
253
+ // NB: The seed doesn't actually matter, so we give a dummy value
254
+ AT_CUDNN_CHECK(cudnnRestoreDropoutDescriptor(mut_desc(), handle, dropout, state_ptr, state_size, 0 /* seed */));
255
+ }
256
+
257
+ // Restore a dropout descriptor corresponding to no dropout
258
+ void set_no_dropout(cudnnHandle_t handle) {
259
+ // NB: seed doesn't matter when dropout = 0, because no random number
260
+ // initialization actually takes place when there is no dropout.
261
+ // NB: Empirically, cudnnSetDropoutDescriptor is cheap when
262
+ // dropout == 0
263
+ AT_CUDNN_CHECK(cudnnSetDropoutDescriptor(mut_desc(), handle, 0 /* dropout */, nullptr, 0 /* state_size */, 0 /* seed */));
264
+ }
265
+ };
266
+
267
+ struct TORCH_CUDA_CPP_API RNNDescriptor : public Descriptor<
268
+ cudnnRNNStruct,
269
+ &cudnnCreateRNNDescriptor,
270
+ &cudnnDestroyRNNDescriptor> {
271
+ DropoutDescriptor dropout_desc_;
272
+ void set(cudnnHandle_t handle,
273
+ #ifdef USE_CUDNN_RNN_V8_API
274
+ int input_size,
275
+ bool packed,
276
+ #endif
277
+ int hidden_size, int proj_size, int num_layers, DropoutDescriptor&& dropout_desc,
278
+ cudnnRNNInputMode_t input_mode, cudnnDirectionMode_t bidirectional,
279
+ cudnnRNNMode_t mode, cudnnDataType_t datatype, cudnnDataType_t input_type, cudnnRNNAlgo_t algo, bool allow_tf32) {
280
+ dropout_desc_ = std::move(dropout_desc);
281
+ #ifndef USE_CUDNN_RNN_V8_API
282
+ AT_CUDNN_CHECK(cudnnSetRNNDescriptor_v6(
283
+ handle,
284
+ mut_desc(),
285
+ hidden_size,
286
+ num_layers,
287
+ dropout_desc_.desc(),
288
+ input_mode,
289
+ bidirectional,
290
+ mode,
291
+ algo,
292
+ datatype));
293
+ if (proj_size != 0) {
294
+ AT_CUDNN_CHECK(cudnnSetRNNProjectionLayers(
295
+ handle,
296
+ /*rnnDesc=*/mut_desc(),
297
+ /*recProjSize=*/proj_size,
298
+ /*outProjSize=*/0));
299
+ }
300
+ cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties();
301
+ if (prop->major >= 7) {
302
+ if (input_type == CUDNN_DATA_HALF) {
303
+ cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_TENSOR_OP_MATH);
304
+ }
305
+ else if (input_type == CUDNN_DATA_FLOAT && !allow_tf32) {
306
+ cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_FMA_MATH);
307
+ }
308
+ else {
309
+ // Technically, as the default it's not necessary to explicitly
310
+ // set this.
311
+ cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_DEFAULT_MATH);
312
+ }
313
+ }
314
+ #else
315
+ cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties();
316
+ auto math_type = CUDNN_DEFAULT_MATH;
317
+ if (prop->major >= 7) {
318
+ if (input_type == CUDNN_DATA_HALF) {
319
+ math_type = CUDNN_TENSOR_OP_MATH;
320
+ } else if (!allow_tf32) {
321
+ math_type = CUDNN_FMA_MATH;
322
+ }
323
+ }
324
+ AT_CUDNN_CHECK(cudnnSetRNNDescriptor_v8(
325
+ mut_desc(),
326
+ algo,
327
+ mode,
328
+ CUDNN_RNN_DOUBLE_BIAS,
329
+ bidirectional,
330
+ input_mode,
331
+ input_type,
332
+ datatype,
333
+ math_type,
334
+ input_size,
335
+ hidden_size,
336
+ proj_size ? proj_size : hidden_size,
337
+ num_layers,
338
+ dropout_desc_.desc(),
339
+ packed ? CUDNN_RNN_PADDED_IO_DISABLED : CUDNN_RNN_PADDED_IO_ENABLED));
340
+ #endif
341
+ }
342
+ };
343
+
344
+ struct TORCH_CUDA_CPP_API CTCLossDescriptor
345
+ : public Descriptor<
346
+ cudnnCTCLossStruct,
347
+ &cudnnCreateCTCLossDescriptor,
348
+ &cudnnDestroyCTCLossDescriptor> {
349
+ void set(cudnnDataType_t datatype) {
350
+ AT_CUDNN_CHECK(cudnnSetCTCLossDescriptor(mut_desc(), datatype));
351
+ }
352
+ void setEx(
353
+ cudnnDataType_t datatype,
354
+ cudnnLossNormalizationMode_t normMode,
355
+ cudnnNanPropagation_t gradMode) {
356
+ AT_CUDNN_CHECK(
357
+ cudnnSetCTCLossDescriptorEx(mut_desc(), datatype, normMode, gradMode));
358
+ }
359
+ void set_v8_v9(
360
+ cudnnDataType_t datatype,
361
+ cudnnLossNormalizationMode_t normMode,
362
+ cudnnNanPropagation_t gradMode,
363
+ int maxLabelLength) {
364
+ #if defined(CUDNN_VERSION) && CUDNN_VERSION >= 90000
365
+ auto gradModev9 = CUDNN_CTC_ZERO_OOB_GRADIENTS;
366
+ if (gradMode == cudnnNanPropagation_t::CUDNN_PROPAGATE_NAN) {
367
+ gradModev9 = CUDNN_CTC_SKIP_OOB_GRADIENTS;
368
+ }
369
+ AT_CUDNN_CHECK(
370
+ cudnnSetCTCLossDescriptor_v9(mut_desc(), datatype, normMode, gradModev9, maxLabelLength));
371
+ #else
372
+ AT_CUDNN_CHECK(
373
+ cudnnSetCTCLossDescriptor_v8(mut_desc(), datatype, normMode, gradMode, maxLabelLength));
374
+ #endif
375
+ }
376
+
377
+ };
378
+
379
+ struct TORCH_CUDA_CPP_API ActivationDescriptor
380
+ : public Descriptor<
381
+ cudnnActivationStruct,
382
+ &cudnnCreateActivationDescriptor,
383
+ &cudnnDestroyActivationDescriptor> {
384
+ void set(cudnnActivationMode_t mode) {
385
+ AT_ASSERT(
386
+ mode == CUDNN_ACTIVATION_RELU,
387
+ "TODO: support more cuDNN activation modes");
388
+ AT_CUDNN_CHECK(cudnnSetActivationDescriptor(
389
+ mut_desc(),
390
+ mode,
391
+ cudnnNanPropagation_t::CUDNN_NOT_PROPAGATE_NAN,
392
+ std::numeric_limits<double>::max()));
393
+ }
394
+ };
395
+
396
+ union Constant
397
+ {
398
+ float f;
399
+ double d;
400
+ Constant(cudnnDataType_t dataType, double value) {
401
+ if (dataType == CUDNN_DATA_HALF || dataType == CUDNN_DATA_FLOAT) {
402
+ f = static_cast<float>(value);
403
+ } else {
404
+ d = value;
405
+ }
406
+ }
407
+ };
408
+
409
+ } // namespace
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Handle.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/ATenCUDAGeneral.h>
4
+ #include <ATen/cudnn/cudnn-wrapper.h>
5
+
6
+ namespace at::native {
7
+
8
+ TORCH_CUDA_CPP_API cudnnHandle_t getCudnnHandle();
9
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Handles.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <ATen/cudnn/Handle.h>
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Types.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <ATen/cudnn/cudnn-wrapper.h>
5
+
6
+ namespace at::native {
7
+
8
+ TORCH_CUDA_CPP_API cudnnDataType_t
9
+ getCudnnDataTypeFromScalarType(const at::ScalarType dtype);
10
+ cudnnDataType_t getCudnnDataType(const at::Tensor& tensor);
11
+
12
+ int64_t cudnn_version();
13
+
14
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/Utils.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/cuda/Exceptions.h>
5
+ #include <ATen/cudnn/Handle.h>
6
+ #include <ATen/cudnn/cudnn-wrapper.h>
7
+
8
+ namespace at::native {
9
+
10
+ // cuDNN has a buggy check for tensor being contiguous (that is, it does
11
+ // not ignore stride for dimension that is equal to 0). This function
12
+ // makes tensors which have zero stride contiguous, by setting the
13
+ // strides to 1 as cuDNN likes.
14
+ inline Tensor contiguousIfZeroInStrides(const Tensor& t) {
15
+ for (auto s : t.strides()) {
16
+ if (s == 0)
17
+ return t.contiguous();
18
+ }
19
+ return t;
20
+ }
21
+
22
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/cudnn/cudnn-wrapper.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cudnn.h>
4
+
5
+ #define STRINGIFY(x) #x
6
+ #define STRING(x) STRINGIFY(x)
7
+
8
+ #if CUDNN_MAJOR < 8 || (CUDNN_MAJOR == 8 && CUDNN_MINOR < 5)
9
+ #pragma message("CuDNN v" STRING( \
10
+ CUDNN_MAJOR) " found, but need at least CuDNN v8. You can get the latest version of CuDNN from https://developer.nvidia.com/cudnn or disable CuDNN with USE_CUDNN=0")
11
+ #pragma message "We strongly encourage you to move to 8.5 and above."
12
+ #pragma message "This message is intended to annoy you enough to update."
13
+ #endif
14
+
15
+ #undef STRINGIFY
16
+ #undef STRING
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/AcceleratorHooksInterface.h ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Generator.h>
4
+
5
+ #include <c10/core/Allocator.h>
6
+ #include <c10/core/Device.h>
7
+ #include <c10/core/Stream.h>
8
+
9
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
10
+
11
+ namespace at {
12
+
13
+ // AcceleratorHooksInterface is a shared interface provided by all
14
+ // accelerators to allow generic code.
15
+ // This inferface is hook-based as it corresponds to all the functions
16
+ // that are going to be called in a generic way from the CPU code.
17
+
18
+ struct TORCH_API AcceleratorHooksInterface {
19
+ // This should never actually be implemented, but it is used to
20
+ // squelch -Werror=non-virtual-dtor
21
+ virtual ~AcceleratorHooksInterface() = default;
22
+
23
+ // Whether this backend was enabled at compilation time.
24
+ // This function should NEVER throw.
25
+ virtual bool isBuilt() const {
26
+ return false;
27
+ }
28
+
29
+ // Whether this backend can be used at runtime, meaning it was built,
30
+ // its runtime dependencies are available (driver) and at least one
31
+ // supported device can be used.
32
+ // This function should NEVER throw. This function should NOT initialize the context
33
+ // on any device (result of hasPrimaryContext below should not change).
34
+ // While it is acceptable for this function to poison fork, it is
35
+ // recommended to avoid doing so whenever possible.
36
+ virtual bool isAvailable() const {
37
+ return false;
38
+ }
39
+
40
+ // Whether the device at device_index is fully initialized or not.
41
+ virtual bool hasPrimaryContext(DeviceIndex device_index) const = 0;
42
+
43
+ virtual void init() const {
44
+ TORCH_CHECK(false, "Backend doesn`t support init()");
45
+ }
46
+
47
+ virtual DeviceIndex deviceCount() const {
48
+ return 0;
49
+ }
50
+
51
+ virtual void setCurrentDevice(DeviceIndex device) const {
52
+ TORCH_CHECK(false, "Backend doesn't support setCurrentDevice()");
53
+ }
54
+
55
+ virtual DeviceIndex getCurrentDevice() const {
56
+ TORCH_CHECK(false, "Backend doesn't support getCurrentDevice()");
57
+ return -1;
58
+ }
59
+
60
+ virtual DeviceIndex exchangeDevice(DeviceIndex device) const {
61
+ TORCH_CHECK(false, "Backend doesn't support exchangeDevice()");
62
+ return -1;
63
+ }
64
+
65
+ virtual DeviceIndex maybeExchangeDevice(DeviceIndex device) const {
66
+ TORCH_CHECK(false, "Backend doesn't support maybeExchangeDevice()");
67
+ return -1;
68
+ }
69
+
70
+ virtual bool isPinnedPtr(const void* data) const {
71
+ return false;
72
+ }
73
+
74
+ virtual Allocator* getPinnedMemoryAllocator() const {
75
+ TORCH_CHECK(false, "Backend doesn't support getPinnedMemoryAllocator()");
76
+ return nullptr;
77
+ }
78
+
79
+ virtual Device getDeviceFromPtr(void* data) const {
80
+ TORCH_CHECK(false, "Backend doesn't support getDeviceFromPtr()");
81
+ }
82
+
83
+ virtual const Generator& getDefaultGenerator(
84
+ [[maybe_unused]] DeviceIndex device_index = -1) const {
85
+ TORCH_CHECK(false, "Backend doesn`t support getDefaultGenerator()");
86
+ }
87
+
88
+ virtual Generator getNewGenerator(
89
+ [[maybe_unused]] DeviceIndex device_index = -1) const {
90
+ TORCH_CHECK(false, "Backend doesn`t support getNewGenerator()");
91
+ }
92
+ };
93
+
94
+ } // namespace at
95
+
96
+ C10_DIAGNOSTIC_POP()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/CUDAHooksInterface.h ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/Registry.h>
6
+
7
+ #include <ATen/detail/AcceleratorHooksInterface.h>
8
+
9
+ // NB: Class must live in `at` due to limitations of Registry.h.
10
+ namespace at {
11
+
12
+ // Forward-declares at::cuda::NVRTC
13
+ namespace cuda {
14
+ struct NVRTC;
15
+ } // namespace cuda
16
+
17
+ #ifdef _MSC_VER
18
+ constexpr const char* CUDA_HELP =
19
+ "PyTorch splits its backend into two shared libraries: a CPU library "
20
+ "and a CUDA library; this error has occurred because you are trying "
21
+ "to use some CUDA functionality, but the CUDA library has not been "
22
+ "loaded by the dynamic linker for some reason. The CUDA library MUST "
23
+ "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! "
24
+ "One common culprit is a lack of -INCLUDE:?warp_size@cuda@at@@YAHXZ "
25
+ "in your link arguments; many dynamic linkers will delete dynamic library "
26
+ "dependencies if you don't depend on any of their symbols. You can check "
27
+ "if this has occurred by using link on your binary to see if there is a "
28
+ "dependency on *_cuda.dll library.";
29
+ #else
30
+ constexpr const char* CUDA_HELP =
31
+ "PyTorch splits its backend into two shared libraries: a CPU library "
32
+ "and a CUDA library; this error has occurred because you are trying "
33
+ "to use some CUDA functionality, but the CUDA library has not been "
34
+ "loaded by the dynamic linker for some reason. The CUDA library MUST "
35
+ "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! "
36
+ "One common culprit is a lack of -Wl,--no-as-needed in your link arguments; many "
37
+ "dynamic linkers will delete dynamic library dependencies if you don't "
38
+ "depend on any of their symbols. You can check if this has occurred by "
39
+ "using ldd on your binary to see if there is a dependency on *_cuda.so "
40
+ "library.";
41
+ #endif
42
+
43
+ // The CUDAHooksInterface is an omnibus interface for any CUDA functionality
44
+ // which we may want to call into from CPU code (and thus must be dynamically
45
+ // dispatched, to allow for separate compilation of CUDA code). How do I
46
+ // decide if a function should live in this class? There are two tests:
47
+ //
48
+ // 1. Does the *implementation* of this function require linking against
49
+ // CUDA libraries?
50
+ //
51
+ // 2. Is this function *called* from non-CUDA ATen code?
52
+ //
53
+ // (2) should filter out many ostensible use-cases, since many times a CUDA
54
+ // function provided by ATen is only really ever used by actual CUDA code.
55
+ //
56
+ // TODO: Consider putting the stub definitions in another class, so that one
57
+ // never forgets to implement each virtual function in the real implementation
58
+ // in CUDAHooks. This probably doesn't buy us much though.
59
+ struct TORCH_API CUDAHooksInterface : AcceleratorHooksInterface {
60
+ // This should never actually be implemented, but it is used to
61
+ // squelch -Werror=non-virtual-dtor
62
+ ~CUDAHooksInterface() override = default;
63
+
64
+ // Initialize THCState and, transitively, the CUDA state
65
+ void init() const override {
66
+ TORCH_CHECK(false, "Cannot initialize CUDA without ATen_cuda library. ", CUDA_HELP);
67
+ }
68
+
69
+ const Generator& getDefaultGenerator(
70
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
71
+ TORCH_CHECK(
72
+ false,
73
+ "Cannot get default CUDA generator without ATen_cuda library. ",
74
+ CUDA_HELP);
75
+ }
76
+
77
+ Generator getNewGenerator(
78
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
79
+ TORCH_CHECK(
80
+ false,
81
+ "Cannot get CUDA generator without ATen_cuda library. ",
82
+ CUDA_HELP);
83
+ }
84
+
85
+ Device getDeviceFromPtr(void* /*data*/) const override {
86
+ TORCH_CHECK(false, "Cannot get device of pointer on CUDA without ATen_cuda library. ", CUDA_HELP);
87
+ }
88
+
89
+ bool isPinnedPtr(const void* /*data*/) const override {
90
+ return false;
91
+ }
92
+
93
+ virtual bool hasCUDA() const {
94
+ return false;
95
+ }
96
+
97
+ virtual bool hasCUDART() const {
98
+ return false;
99
+ }
100
+
101
+ virtual bool hasMAGMA() const {
102
+ return false;
103
+ }
104
+
105
+ virtual bool hasCuDNN() const {
106
+ return false;
107
+ }
108
+
109
+ virtual bool hasCuSOLVER() const {
110
+ return false;
111
+ }
112
+
113
+ virtual bool hasCuBLASLt() const {
114
+ return false;
115
+ }
116
+
117
+ virtual bool hasROCM() const {
118
+ return false;
119
+ }
120
+
121
+ virtual const at::cuda::NVRTC& nvrtc() const {
122
+ TORCH_CHECK(false, "NVRTC requires CUDA. ", CUDA_HELP);
123
+ }
124
+
125
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
126
+ TORCH_CHECK(false, "Cannot call hasPrimaryContext(", device_index, ") without ATen_cuda library. ", CUDA_HELP);
127
+ }
128
+
129
+ virtual DeviceIndex current_device() const {
130
+ return -1;
131
+ }
132
+
133
+ Allocator* getPinnedMemoryAllocator() const override {
134
+ TORCH_CHECK(false, "Pinned memory requires CUDA. ", CUDA_HELP);
135
+ }
136
+
137
+ virtual Allocator* getCUDADeviceAllocator() const {
138
+ TORCH_CHECK(false, "CUDADeviceAllocator requires CUDA. ", CUDA_HELP);
139
+ }
140
+
141
+ virtual bool compiledWithCuDNN() const {
142
+ return false;
143
+ }
144
+
145
+ virtual bool compiledWithMIOpen() const {
146
+ return false;
147
+ }
148
+
149
+ virtual bool supportsDilatedConvolutionWithCuDNN() const {
150
+ return false;
151
+ }
152
+
153
+ virtual bool supportsDepthwiseConvolutionWithCuDNN() const {
154
+ return false;
155
+ }
156
+
157
+ virtual bool supportsBFloat16ConvolutionWithCuDNNv8() const {
158
+ return false;
159
+ }
160
+
161
+ virtual long versionCuDNN() const {
162
+ TORCH_CHECK(false, "Cannot query cuDNN version without ATen_cuda library. ", CUDA_HELP);
163
+ }
164
+
165
+ virtual long versionMIOpen() const {
166
+ TORCH_CHECK(false, "Cannot query MIOpen version without ATen_cuda library. ", CUDA_HELP);
167
+ }
168
+
169
+ virtual long versionCUDART() const {
170
+ TORCH_CHECK(false, "Cannot query CUDART version without ATen_cuda library. ", CUDA_HELP);
171
+ }
172
+
173
+ virtual std::string showConfig() const {
174
+ TORCH_CHECK(false, "Cannot query detailed CUDA version without ATen_cuda library. ", CUDA_HELP);
175
+ }
176
+
177
+ virtual double batchnormMinEpsilonCuDNN() const {
178
+ TORCH_CHECK(false,
179
+ "Cannot query batchnormMinEpsilonCuDNN() without ATen_cuda library. ", CUDA_HELP);
180
+ }
181
+
182
+ virtual int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex /*device_index*/) const {
183
+ TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
184
+ }
185
+
186
+ virtual void cuFFTSetPlanCacheMaxSize(DeviceIndex /*device_index*/, int64_t /*max_size*/) const {
187
+ TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
188
+ }
189
+
190
+ virtual int64_t cuFFTGetPlanCacheSize(DeviceIndex /*device_index*/) const {
191
+ TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
192
+ }
193
+
194
+ virtual void cuFFTClearPlanCache(DeviceIndex /*device_index*/) const {
195
+ TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
196
+ }
197
+
198
+ virtual int getNumGPUs() const {
199
+ return 0;
200
+ }
201
+
202
+ #ifdef USE_ROCM
203
+ virtual bool isGPUArch(const std::vector<std::string>& /*archs*/, DeviceIndex = -1 /*device_index*/) const {
204
+ TORCH_CHECK(false, "Cannot check GPU arch without ATen_cuda library. ", CUDA_HELP);
205
+ }
206
+ #endif
207
+
208
+ virtual void deviceSynchronize(DeviceIndex /*device_index*/) const {
209
+ TORCH_CHECK(false, "Cannot synchronize CUDA device without ATen_cuda library. ", CUDA_HELP);
210
+ }
211
+ };
212
+
213
+ // NB: dummy argument to suppress "ISO C++11 requires at least one argument
214
+ // for the "..." in a variadic macro"
215
+ struct TORCH_API CUDAHooksArgs {};
216
+
217
+ TORCH_DECLARE_REGISTRY(CUDAHooksRegistry, CUDAHooksInterface, CUDAHooksArgs);
218
+ #define REGISTER_CUDA_HOOKS(clsname) \
219
+ C10_REGISTER_CLASS(CUDAHooksRegistry, clsname, clsname)
220
+
221
+ namespace detail {
222
+ TORCH_API const CUDAHooksInterface& getCUDAHooks();
223
+ } // namespace detail
224
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/FunctionTraits.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <tuple>
5
+
6
+ // Modified from https://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda
7
+
8
+ // Fallback, anything with an operator()
9
+ template <typename T>
10
+ struct function_traits : public function_traits<decltype(&T::operator())> {
11
+ };
12
+
13
+ // Pointers to class members that are themselves functors.
14
+ // For example, in the following code:
15
+ // template <typename func_t>
16
+ // struct S {
17
+ // func_t f;
18
+ // };
19
+ // template <typename func_t>
20
+ // S<func_t> make_s(func_t f) {
21
+ // return S<func_t> { .f = f };
22
+ // }
23
+ //
24
+ // auto s = make_s([] (int, float) -> double { /* ... */ });
25
+ //
26
+ // function_traits<decltype(&s::f)> traits;
27
+ template <typename ClassType, typename T>
28
+ struct function_traits<T ClassType::*> : public function_traits<T> {
29
+ };
30
+
31
+ // Const class member functions
32
+ template <typename ClassType, typename ReturnType, typename... Args>
33
+ struct function_traits<ReturnType(ClassType::*)(Args...) const> : public function_traits<ReturnType(Args...)> {
34
+ };
35
+
36
+ // Reference types
37
+ template <typename T>
38
+ struct function_traits<T&> : public function_traits<T> {};
39
+ template <typename T>
40
+ struct function_traits<T*> : public function_traits<T> {};
41
+
42
+ // Free functions
43
+ template <typename ReturnType, typename... Args>
44
+ struct function_traits<ReturnType(Args...)> {
45
+ // arity is the number of arguments.
46
+ enum { arity = sizeof...(Args) };
47
+
48
+ using ArgsTuple = std::tuple<Args...>;
49
+ using result_type = ReturnType;
50
+
51
+ template <size_t i>
52
+ struct arg
53
+ {
54
+ using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
55
+ // the i-th argument is equivalent to the i-th tuple element of a tuple
56
+ // composed of those arguments.
57
+ };
58
+ };
59
+
60
+ template <typename T>
61
+ struct nullary_function_traits {
62
+ using traits = function_traits<T>;
63
+ using result_type = typename traits::result_type;
64
+ };
65
+
66
+ template <typename T>
67
+ struct unary_function_traits {
68
+ using traits = function_traits<T>;
69
+ using result_type = typename traits::result_type;
70
+ using arg1_t = typename traits::template arg<0>::type;
71
+ };
72
+
73
+ template <typename T>
74
+ struct binary_function_traits {
75
+ using traits = function_traits<T>;
76
+ using result_type = typename traits::result_type;
77
+ using arg1_t = typename traits::template arg<0>::type;
78
+ using arg2_t = typename traits::template arg<1>::type;
79
+ };
80
+
81
+
82
+ // Traits for calling with c10::guts::invoke, where member_functions have a first argument of ClassType
83
+ template <typename T>
84
+ struct invoke_traits : public function_traits<T>{
85
+ };
86
+
87
+ template <typename T>
88
+ struct invoke_traits<T&> : public invoke_traits<T>{
89
+ };
90
+
91
+ template <typename T>
92
+ struct invoke_traits<T&&> : public invoke_traits<T>{
93
+ };
94
+
95
+ template <typename ClassType, typename ReturnType, typename... Args>
96
+ struct invoke_traits<ReturnType(ClassType::*)(Args...)> :
97
+ public function_traits<ReturnType(ClassType&, Args...)> {
98
+ };
99
+
100
+ template <typename ClassType, typename ReturnType, typename... Args>
101
+ struct invoke_traits<ReturnType(ClassType::*)(Args...) const> :
102
+ public function_traits<ReturnType(const ClassType&, Args...)> {
103
+ };
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/HIPHooksInterface.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/Registry.h>
6
+
7
+ #include <ATen/detail/AcceleratorHooksInterface.h>
8
+
9
+ // NB: Class must live in `at` due to limitations of Registry.h.
10
+ namespace at {
11
+
12
+ // The HIPHooksInterface is an omnibus interface for any HIP functionality
13
+ // which we may want to call into from CPU code (and thus must be dynamically
14
+ // dispatched, to allow for separate compilation of HIP code). See
15
+ // CUDAHooksInterface for more detailed motivation.
16
+ struct TORCH_API HIPHooksInterface : AcceleratorHooksInterface {
17
+ // This should never actually be implemented, but it is used to
18
+ // squelch -Werror=non-virtual-dtor
19
+ ~HIPHooksInterface() override = default;
20
+
21
+ void init() const override {
22
+ TORCH_CHECK(false, "Cannot initialize HIP without ATen_hip library.");
23
+ }
24
+
25
+ const Generator& getDefaultGenerator(
26
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
27
+ TORCH_CHECK(false, "Cannot initialize HIP without ATen_hip library.");
28
+ }
29
+
30
+ virtual bool hasHIP() const {
31
+ return false;
32
+ }
33
+
34
+ virtual c10::DeviceIndex current_device() const {
35
+ return -1;
36
+ }
37
+
38
+ bool isPinnedPtr(const void* /*data*/ ) const override {
39
+ return false;
40
+ }
41
+
42
+ Allocator* getPinnedMemoryAllocator() const override {
43
+ TORCH_CHECK(false, "Pinned memory requires HIP.");
44
+ }
45
+
46
+ virtual int getNumGPUs() const {
47
+ return 0;
48
+ }
49
+
50
+ bool hasPrimaryContext(DeviceIndex /*device_index*/ ) const override {
51
+ TORCH_CHECK(false, "Cannot check primary context without ATen_hip library.");
52
+ }
53
+ };
54
+
55
+ // NB: dummy argument to suppress "ISO C++11 requires at least one argument
56
+ // for the "..." in a variadic macro"
57
+ struct TORCH_API HIPHooksArgs {};
58
+
59
+ TORCH_DECLARE_REGISTRY(HIPHooksRegistry, HIPHooksInterface, HIPHooksArgs);
60
+ #define REGISTER_HIP_HOOKS(clsname) \
61
+ C10_REGISTER_CLASS(HIPHooksRegistry, clsname, clsname)
62
+
63
+ namespace detail {
64
+ TORCH_API const HIPHooksInterface& getHIPHooks();
65
+
66
+ } // namespace detail
67
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/HPUHooksInterface.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Generator.h>
4
+ #include <ATen/detail/AcceleratorHooksInterface.h>
5
+
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/core/Device.h>
8
+ #include <c10/util/Registry.h>
9
+
10
+ namespace at {
11
+
12
+ struct TORCH_API HPUHooksInterface : AcceleratorHooksInterface {
13
+ ~HPUHooksInterface() override = default;
14
+
15
+ void init() const override {
16
+ TORCH_CHECK(false, "Cannot initialize HPU without HPU backend");
17
+ }
18
+
19
+ virtual bool hasHPU() const {
20
+ return false;
21
+ }
22
+
23
+ Device getDeviceFromPtr(void* /*data*/) const override {
24
+ TORCH_CHECK(
25
+ false, "Cannot get device of pointer on HPU without HPU backend");
26
+ }
27
+
28
+ bool isPinnedPtr(const void*) const override {
29
+ return false;
30
+ }
31
+
32
+ Allocator* getPinnedMemoryAllocator() const override {
33
+ TORCH_CHECK(
34
+ false,
35
+ "You should register `HPUHooksInterface` for HPU before call `getPinnedMemoryAllocator`.");
36
+ }
37
+
38
+ bool hasPrimaryContext(
39
+ [[maybe_unused]] DeviceIndex device_index) const override {
40
+ TORCH_CHECK(
41
+ false,
42
+ "You should register `HPUHooksInterface` for HPU before call `hasPrimaryContext`.");
43
+ }
44
+ };
45
+
46
+ struct TORCH_API HPUHooksArgs {};
47
+
48
+ TORCH_DECLARE_REGISTRY(HPUHooksRegistry, HPUHooksInterface, HPUHooksArgs);
49
+ #define REGISTER_HPU_HOOKS(clsname) \
50
+ C10_REGISTER_CLASS(HPUHooksRegistry, clsname, clsname)
51
+
52
+ namespace detail {
53
+
54
+ TORCH_API const at::HPUHooksInterface& getHPUHooks();
55
+
56
+ } // namespace detail
57
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/IPUHooksInterface.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/detail/AcceleratorHooksInterface.h>
4
+
5
+ #include <c10/core/Allocator.h>
6
+ #include <c10/util/Exception.h>
7
+ #include <c10/util/Registry.h>
8
+
9
+ namespace at {
10
+
11
+ struct TORCH_API IPUHooksInterface : AcceleratorHooksInterface {
12
+ ~IPUHooksInterface() override = default;
13
+
14
+ void init() const override {
15
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
16
+ }
17
+
18
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
19
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
20
+ return false;
21
+ }
22
+
23
+ const Generator& getDefaultGenerator(
24
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
25
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
26
+ }
27
+
28
+ Generator getNewGenerator(
29
+ DeviceIndex /*device_index*/ = -1) const override {
30
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
31
+ }
32
+ };
33
+
34
+ struct TORCH_API IPUHooksArgs {};
35
+
36
+ TORCH_DECLARE_REGISTRY(IPUHooksRegistry, IPUHooksInterface, IPUHooksArgs);
37
+ #define REGISTER_IPU_HOOKS(clsname) \
38
+ C10_REGISTER_CLASS(IPUHooksRegistry, clsname, clsname)
39
+
40
+ namespace detail {
41
+ TORCH_API const IPUHooksInterface& getIPUHooks();
42
+ } // namespace detail
43
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MAIAHooksInterface.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Exception.h>
4
+ #include <c10/util/Registry.h>
5
+
6
+ #include <ATen/detail/AcceleratorHooksInterface.h>
7
+
8
+ // NB: Class must live in `at` due to limitations of Registry.h.
9
+ namespace at {
10
+
11
+ struct TORCH_API MAIAHooksInterface : AcceleratorHooksInterface {
12
+ // This should never actually be implemented, but it is used to
13
+ // squelch -Werror=non-virtual-dtor
14
+ ~MAIAHooksInterface() override = default;
15
+
16
+ void init() const override {
17
+ TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library.");
18
+ }
19
+
20
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
21
+ TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library.");
22
+ return false;
23
+ }
24
+
25
+ virtual std::string showConfig() const {
26
+ TORCH_CHECK(false, "Cannot query detailed MAIA version information.");
27
+ }
28
+ };
29
+
30
+ // NB: dummy argument to suppress "ISO C++11 requires at least one argument
31
+ // for the "..." in a variadic macro"
32
+ struct TORCH_API MAIAHooksArgs {};
33
+
34
+ TORCH_DECLARE_REGISTRY(MAIAHooksRegistry, MAIAHooksInterface, MAIAHooksArgs);
35
+ #define REGISTER_MAIA_HOOKS(clsname) \
36
+ C10_REGISTER_CLASS(MAIAHooksRegistry, clsname, clsname)
37
+
38
+ namespace detail {
39
+ TORCH_API const MAIAHooksInterface& getMAIAHooks();
40
+ } // namespace detail
41
+
42
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MPSHooksInterface.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/detail/AcceleratorHooksInterface.h>
6
+
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/util/Exception.h>
9
+ #include <c10/util/Registry.h>
10
+
11
+ #include <cstddef>
12
+
13
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
14
+ namespace at {
15
+
16
+ struct TORCH_API MPSHooksInterface : AcceleratorHooksInterface {
17
+ // this fails the implementation if MPSHooks functions are called, but
18
+ // MPS backend is not present.
19
+ #define FAIL_MPSHOOKS_FUNC(func) \
20
+ TORCH_CHECK(false, "Cannot execute ", func, "() without MPS backend.");
21
+
22
+ ~MPSHooksInterface() override = default;
23
+
24
+ // Initialize the MPS library state
25
+ void init() const override {
26
+ FAIL_MPSHOOKS_FUNC(__func__);
27
+ }
28
+ virtual bool hasMPS() const {
29
+ return false;
30
+ }
31
+ virtual bool isOnMacOSorNewer(unsigned major = 13, unsigned minor = 0) const {
32
+ FAIL_MPSHOOKS_FUNC(__func__);
33
+ }
34
+ const Generator& getDefaultGenerator(
35
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
36
+ FAIL_MPSHOOKS_FUNC(__func__);
37
+ }
38
+ Generator getNewGenerator(
39
+ [[maybe_unused]] DeviceIndex device_index) const override {
40
+ FAIL_MPSHOOKS_FUNC(__func__);
41
+ }
42
+ virtual Allocator* getMPSDeviceAllocator() const {
43
+ FAIL_MPSHOOKS_FUNC(__func__);
44
+ }
45
+ virtual void deviceSynchronize() const {
46
+ FAIL_MPSHOOKS_FUNC(__func__);
47
+ }
48
+ virtual void commitStream() const {
49
+ FAIL_MPSHOOKS_FUNC(__func__);
50
+ }
51
+ virtual void* getCommandBuffer() const {
52
+ FAIL_MPSHOOKS_FUNC(__func__);
53
+ }
54
+ virtual void* getDispatchQueue() const {
55
+ FAIL_MPSHOOKS_FUNC(__func__);
56
+ }
57
+ virtual void emptyCache() const {
58
+ FAIL_MPSHOOKS_FUNC(__func__);
59
+ }
60
+ virtual size_t getCurrentAllocatedMemory() const {
61
+ FAIL_MPSHOOKS_FUNC(__func__);
62
+ }
63
+ virtual size_t getDriverAllocatedMemory() const {
64
+ FAIL_MPSHOOKS_FUNC(__func__);
65
+ }
66
+ virtual size_t getRecommendedMaxMemory() const {
67
+ FAIL_MPSHOOKS_FUNC(__func__);
68
+ }
69
+ virtual void setMemoryFraction(double /*ratio*/) const {
70
+ FAIL_MPSHOOKS_FUNC(__func__);
71
+ }
72
+ virtual void profilerStartTrace(const std::string& mode, bool waitUntilCompleted) const {
73
+ FAIL_MPSHOOKS_FUNC(__func__);
74
+ }
75
+ virtual void profilerStopTrace() const {
76
+ FAIL_MPSHOOKS_FUNC(__func__);
77
+ }
78
+ virtual uint32_t acquireEvent(bool enable_timing) const {
79
+ FAIL_MPSHOOKS_FUNC(__func__);
80
+ }
81
+ Device getDeviceFromPtr(void* data) const override {
82
+ TORCH_CHECK(false, "Cannot get device of pointer on MPS without ATen_mps library. ");
83
+ }
84
+ virtual void releaseEvent(uint32_t event_id) const {
85
+ FAIL_MPSHOOKS_FUNC(__func__);
86
+ }
87
+ virtual void recordEvent(uint32_t event_id) const {
88
+ FAIL_MPSHOOKS_FUNC(__func__);
89
+ }
90
+ virtual void waitForEvent(uint32_t event_id) const {
91
+ FAIL_MPSHOOKS_FUNC(__func__);
92
+ }
93
+ virtual void synchronizeEvent(uint32_t event_id) const {
94
+ FAIL_MPSHOOKS_FUNC(__func__);
95
+ }
96
+ virtual bool queryEvent(uint32_t event_id) const {
97
+ FAIL_MPSHOOKS_FUNC(__func__);
98
+ }
99
+ virtual double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id) const {
100
+ FAIL_MPSHOOKS_FUNC(__func__);
101
+ }
102
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
103
+ FAIL_MPSHOOKS_FUNC(__func__);
104
+ }
105
+ bool isPinnedPtr(const void* data) const override {
106
+ return false;
107
+ }
108
+ Allocator* getPinnedMemoryAllocator() const override {
109
+ FAIL_MPSHOOKS_FUNC(__func__);
110
+ }
111
+ #undef FAIL_MPSHOOKS_FUNC
112
+ };
113
+
114
+ struct TORCH_API MPSHooksArgs {};
115
+
116
+ TORCH_DECLARE_REGISTRY(MPSHooksRegistry, MPSHooksInterface, MPSHooksArgs);
117
+ #define REGISTER_MPS_HOOKS(clsname) \
118
+ C10_REGISTER_CLASS(MPSHooksRegistry, clsname, clsname)
119
+
120
+ namespace detail {
121
+ TORCH_API const MPSHooksInterface& getMPSHooks();
122
+
123
+ } // namespace detail
124
+ } // namespace at
125
+ C10_DIAGNOSTIC_POP()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/MTIAHooksInterface.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Device.h>
4
+ #include <c10/util/Exception.h>
5
+
6
+ #include <c10/core/Stream.h>
7
+ #include <c10/util/Registry.h>
8
+
9
+ #include <c10/core/Allocator.h>
10
+
11
+ #include <c10/util/python_stub.h>
12
+ #include <ATen/detail/AcceleratorHooksInterface.h>
13
+
14
+ #include <string>
15
+ namespace at {
16
+ class Context;
17
+ }
18
+
19
+ namespace at {
20
+ constexpr const char* MTIA_HELP =
21
+ "The MTIA backend requires MTIA extension for PyTorch;"
22
+ "this error has occurred because you are trying "
23
+ "to use some MTIA's functionality without MTIA extension included.";
24
+
25
+ struct TORCH_API MTIAHooksInterface : AcceleratorHooksInterface {
26
+ // this fails the implementation if MTIAHooks functions are called, but
27
+ // MTIA backend is not present.
28
+ #define FAIL_MTIAHOOKS_FUNC(func) \
29
+ TORCH_CHECK(false, "Cannot execute ", func, "() without MTIA backend.");
30
+
31
+ ~MTIAHooksInterface() override = default;
32
+
33
+ void init() const override {
34
+ // Avoid logging here, since MTIA needs init devices first then it will know
35
+ // how many devices are available. Make it as no-op if mtia extension is not
36
+ // dynamically loaded.
37
+ return;
38
+ }
39
+
40
+ virtual bool hasMTIA() const {
41
+ return false;
42
+ }
43
+
44
+ DeviceIndex deviceCount() const override {
45
+ return 0;
46
+ }
47
+
48
+ virtual void deviceSynchronize(c10::DeviceIndex /*device_index*/) const {
49
+ FAIL_MTIAHOOKS_FUNC(__func__);
50
+ }
51
+
52
+ virtual std::string showConfig() const {
53
+ FAIL_MTIAHOOKS_FUNC(__func__);
54
+ }
55
+
56
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
57
+ return false;
58
+ }
59
+
60
+ void setCurrentDevice(DeviceIndex /*device*/) const override {
61
+ FAIL_MTIAHOOKS_FUNC(__func__);
62
+ }
63
+
64
+ DeviceIndex getCurrentDevice() const override {
65
+ FAIL_MTIAHOOKS_FUNC(__func__);
66
+ return -1;
67
+ }
68
+
69
+ DeviceIndex exchangeDevice(DeviceIndex /*device*/) const override {
70
+ FAIL_MTIAHOOKS_FUNC(__func__);
71
+ return -1;
72
+ }
73
+
74
+ DeviceIndex maybeExchangeDevice(DeviceIndex /*device*/) const override {
75
+ FAIL_MTIAHOOKS_FUNC(__func__);
76
+ return -1;
77
+ }
78
+
79
+ virtual c10::Stream getCurrentStream(DeviceIndex /*device*/) const {
80
+ FAIL_MTIAHOOKS_FUNC(__func__);
81
+ return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA);
82
+ }
83
+
84
+ virtual int64_t getCurrentRawStream(DeviceIndex /*device*/) const {
85
+ FAIL_MTIAHOOKS_FUNC(__func__);
86
+ return -1;
87
+ }
88
+
89
+ virtual c10::Stream getDefaultStream(DeviceIndex /*device*/) const {
90
+ FAIL_MTIAHOOKS_FUNC(__func__);
91
+ return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA);
92
+ }
93
+
94
+ virtual void setCurrentStream(const c10::Stream& /*stream*/ ) const {
95
+ FAIL_MTIAHOOKS_FUNC(__func__);
96
+ }
97
+
98
+ bool isPinnedPtr(const void* /*data*/) const override {
99
+ return false;
100
+ }
101
+
102
+ Allocator* getPinnedMemoryAllocator() const override {
103
+ FAIL_MTIAHOOKS_FUNC(__func__);
104
+ return nullptr;
105
+ }
106
+
107
+ virtual PyObject* memoryStats(DeviceIndex /*device*/) const {
108
+ FAIL_MTIAHOOKS_FUNC(__func__);
109
+ return nullptr;
110
+ }
111
+
112
+ virtual PyObject* getDeviceCapability(DeviceIndex /*device*/) const {
113
+ FAIL_MTIAHOOKS_FUNC(__func__);
114
+ return nullptr;
115
+ }
116
+
117
+ virtual PyObject* getDeviceProperties(DeviceIndex device) const {
118
+ FAIL_MTIAHOOKS_FUNC(__func__);
119
+ return nullptr;
120
+ }
121
+
122
+ virtual void emptyCache() const {
123
+ FAIL_MTIAHOOKS_FUNC(__func__);
124
+ }
125
+
126
+
127
+ virtual void recordMemoryHistory(
128
+ const std::optional<std::string>& /*enabled*/,
129
+ const std::string& /*stacks*/,
130
+ size_t /*max_entries*/) const {
131
+ FAIL_MTIAHOOKS_FUNC(__func__);
132
+ }
133
+
134
+ virtual PyObject* memorySnapshot(const std::optional<std::string>& local_path) const {
135
+ FAIL_MTIAHOOKS_FUNC(__func__);
136
+ return nullptr;
137
+ }
138
+
139
+ virtual DeviceIndex getDeviceCount() const {
140
+ FAIL_MTIAHOOKS_FUNC(__func__);
141
+ return 0;
142
+ }
143
+
144
+ virtual void resetPeakMemoryStats(DeviceIndex /*device*/) const {
145
+ FAIL_MTIAHOOKS_FUNC(__func__);
146
+ }
147
+
148
+ virtual void attachOutOfMemoryObserver(PyObject* observer) const {
149
+ FAIL_MTIAHOOKS_FUNC(__func__);
150
+ return;
151
+ }
152
+ };
153
+
154
+ struct TORCH_API MTIAHooksArgs {};
155
+
156
+ TORCH_DECLARE_REGISTRY(MTIAHooksRegistry, MTIAHooksInterface, MTIAHooksArgs);
157
+ #define REGISTER_MTIA_HOOKS(clsname) \
158
+ C10_REGISTER_CLASS(MTIAHooksRegistry, clsname, clsname)
159
+
160
+ namespace detail {
161
+ TORCH_API const MTIAHooksInterface& getMTIAHooks();
162
+ TORCH_API bool isMTIAHooksBuilt();
163
+ } // namespace detail
164
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/PrivateUse1HooksInterface.h ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/GeneratorForPrivateuseone.h>
4
+ #include <ATen/detail/AcceleratorHooksInterface.h>
5
+
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/core/Device.h>
8
+ #include <c10/core/Storage.h>
9
+ #include <c10/util/Exception.h>
10
+
11
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
12
+
13
+ namespace at {
14
+
15
+ struct TORCH_API PrivateUse1HooksInterface : AcceleratorHooksInterface {
16
+ #define FAIL_PRIVATEUSE1HOOKS_FUNC(func) \
17
+ TORCH_CHECK_NOT_IMPLEMENTED( \
18
+ false, \
19
+ "You should register `PrivateUse1HooksInterface`", \
20
+ "by `RegisterPrivateUse1HooksInterface` and implement `", \
21
+ func, \
22
+ "` at the same time for PrivateUse1.");
23
+
24
+ ~PrivateUse1HooksInterface() override = default;
25
+
26
+ bool isBuilt() const override {
27
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
28
+ }
29
+
30
+ bool isAvailable() const override {
31
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
32
+ }
33
+
34
+ const at::Generator& getDefaultGenerator(
35
+ c10::DeviceIndex device_index) const override {
36
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
37
+ }
38
+
39
+ Generator getNewGenerator(
40
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
41
+ // TODO(FFFrog): Perserved for BC and will be removed in the future.
42
+ if (at::GetGeneratorPrivate().has_value())
43
+ return at::GetGeneratorForPrivateuse1(device_index);
44
+
45
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
46
+ }
47
+
48
+ at::Device getDeviceFromPtr(void* data) const override {
49
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
50
+ }
51
+
52
+ bool isPinnedPtr(const void* data) const override {
53
+ return false;
54
+ }
55
+
56
+ Allocator* getPinnedMemoryAllocator() const override {
57
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
58
+ }
59
+
60
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
61
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
62
+ }
63
+
64
+ void init() const override {}
65
+ virtual void resizePrivateUse1Bytes(
66
+ const c10::Storage& storage,
67
+ size_t newsize) const {
68
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
69
+ }
70
+
71
+ #undef FAIL_PRIVATEUSE1HOOKS_FUNC
72
+ };
73
+
74
+ struct TORCH_API PrivateUse1HooksArgs {};
75
+
76
+ TORCH_API void RegisterPrivateUse1HooksInterface(
77
+ at::PrivateUse1HooksInterface* hook_);
78
+
79
+ TORCH_API bool isPrivateUse1HooksRegistered();
80
+
81
+ namespace detail {
82
+
83
+ TORCH_API const at::PrivateUse1HooksInterface& getPrivateUse1Hooks();
84
+
85
+ } // namespace detail
86
+
87
+ } // namespace at
88
+
89
+ C10_DIAGNOSTIC_POP()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/detail/XPUHooksInterface.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Device.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/Registry.h>
6
+
7
+ #include <ATen/detail/AcceleratorHooksInterface.h>
8
+
9
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
10
+
11
+ namespace at {
12
+
13
+ struct TORCH_API XPUHooksInterface : AcceleratorHooksInterface{
14
+ ~XPUHooksInterface() override = default;
15
+
16
+ void init() const override {
17
+ TORCH_CHECK(false, "Cannot initialize XPU without ATen_xpu library.");
18
+ }
19
+
20
+ virtual bool hasXPU() const {
21
+ return false;
22
+ }
23
+
24
+ virtual std::string showConfig() const {
25
+ TORCH_CHECK(
26
+ false,
27
+ "Cannot query detailed XPU version without ATen_xpu library.");
28
+ }
29
+
30
+ virtual int32_t getGlobalIdxFromDevice(const Device& device) const {
31
+ TORCH_CHECK(false, "Cannot get XPU global device index without ATen_xpu library.");
32
+ }
33
+
34
+ const Generator& getDefaultGenerator(
35
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
36
+ TORCH_CHECK(
37
+ false, "Cannot get default XPU generator without ATen_xpu library.");
38
+ }
39
+
40
+ Generator getNewGenerator(
41
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
42
+ TORCH_CHECK(false, "Cannot get XPU generator without ATen_xpu library.");
43
+ }
44
+
45
+ virtual DeviceIndex getNumGPUs() const {
46
+ return 0;
47
+ }
48
+
49
+ virtual DeviceIndex current_device() const {
50
+ TORCH_CHECK(false, "Cannot get current device on XPU without ATen_xpu library.");
51
+ }
52
+
53
+ Device getDeviceFromPtr(void* /*data*/) const override {
54
+ TORCH_CHECK(false, "Cannot get device of pointer on XPU without ATen_xpu library.");
55
+ }
56
+
57
+ virtual void deviceSynchronize(DeviceIndex /*device_index*/) const {
58
+ TORCH_CHECK(false, "Cannot synchronize XPU device without ATen_xpu library.");
59
+ }
60
+
61
+ Allocator* getPinnedMemoryAllocator() const override {
62
+ TORCH_CHECK(false, "Cannot get XPU pinned memory allocator without ATen_xpu library.");
63
+ }
64
+
65
+ bool isPinnedPtr(const void* data) const override {
66
+ return false;
67
+ }
68
+
69
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
70
+ TORCH_CHECK(false, "Cannot query primary context without ATen_xpu library.");
71
+ }
72
+ };
73
+
74
+ struct TORCH_API XPUHooksArgs {};
75
+
76
+ TORCH_DECLARE_REGISTRY(XPUHooksRegistry, XPUHooksInterface, XPUHooksArgs);
77
+ #define REGISTER_XPU_HOOKS(clsname) \
78
+ C10_REGISTER_CLASS(XPUHooksRegistry, clsname, clsname)
79
+
80
+ namespace detail {
81
+ TORCH_API const XPUHooksInterface& getXPUHooks();
82
+ } // namespace detail
83
+ } // namespace at
84
+ C10_DIAGNOSTIC_POP()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/ADInterpreters.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/functorch/Interpreter.h>
3
+
4
+ namespace at::functorch {
5
+
6
+ // These are the interpreters for our AD transforms
7
+ // (grad, vjp and jvp).
8
+ // See NOTE: [functorch interpreter stack] for more details.
9
+
10
+ struct TORCH_API GradInterpreterPtr {
11
+ explicit GradInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Grad); }
12
+ TransformType key() const { return base_->key(); }
13
+ int64_t level() const { return base_->level(); }
14
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
15
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
16
+ bool prevGradMode() const {
17
+ return std::get<GradInterpreterMeta>(base_->meta()).prevGradMode_;
18
+ }
19
+ Tensor lift(const Tensor& tensor) const;
20
+ private:
21
+ const Interpreter* base_;
22
+ };
23
+
24
+ struct TORCH_API JvpInterpreterPtr {
25
+ explicit JvpInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Jvp); }
26
+ TransformType key() const { return base_->key(); }
27
+ int64_t level() const { return base_->level(); }
28
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
29
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
30
+ bool prevFwdGradMode() const {
31
+ return std::get<JvpInterpreterMeta>(base_->meta()).prevFwdGradMode_;
32
+ }
33
+ Tensor lift(const Tensor& tensor) const;
34
+ private:
35
+ const Interpreter* base_;
36
+ };
37
+
38
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchRulesHelper.h ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #pragma once
7
+
8
+ #include <c10/util/TypeList.h>
9
+
10
+ #include <ATen/ATen.h>
11
+ #include <ATen/Operators.h>
12
+
13
+ #include <ATen/functorch/DynamicLayer.h>
14
+ #include <ATen/functorch/TensorWrapper.h>
15
+ #include <ATen/functorch/BatchingMetaprogramming.h>
16
+ #include <ATen/functorch/LegacyVmapTransforms.h>
17
+ #include <ATen/functorch/BatchedFallback.h>
18
+ #include <ATen/functorch/PlumbingHelper.h>
19
+ #include <ATen/core/dispatch/Dispatcher.h>
20
+ #include <ATen/VmapGeneratedPlumbing.h>
21
+
22
+ #include <utility>
23
+
24
+ // This file contains helper functions for batching rules.
25
+
26
+ namespace at::functorch {
27
+
28
+ TORCH_API Tensor reshape_dim_into(int64_t src, int64_t dst, const Tensor& x);
29
+ TORCH_API Tensor reshape_dim_outof(int64_t src, int64_t size1, const Tensor& x);
30
+
31
+ TORCH_API Tensor reshape_dim_outof_symint(int64_t src, const c10::SymInt& size1, const Tensor& x);
32
+
33
+ Tensor moveBatchDimToFront(Tensor tensor, std::optional<int64_t> maybe_batch_dim);
34
+ int64_t rankWithoutBatchDim(const Tensor& tensor, std::optional<int64_t> maybe_batch_dim);
35
+ int64_t numelWithoutBatchDim(const Tensor& tensor, std::optional<int64_t> maybe_batch_dim);
36
+ std::optional<int64_t> valIfNonempty(std::optional<int64_t> maybe_empty, int64_t new_val);
37
+ int64_t getPhysicalDim(const Tensor& tensor, bool has_batch_dim, int64_t logical_dim);
38
+ VmapDimVector getPhysicalDims(const Tensor& tensor, bool has_batch_dim, IntArrayRef logical_dims);
39
+
40
+ void vmapIncompatibleInplaceError(const char* schema_name);
41
+
42
+ Tensor maybePadToLogicalRank(const Tensor& tensor, std::optional<int64_t> has_bdim, int64_t logical_rank);
43
+
44
+ void check_randomness(RandomnessType randomness);
45
+ void check_randomness(RandomnessType randomness, bool any_tensor_bdim);
46
+
47
+ inline Tensor ensure_has_bdim(const Tensor& tensor, bool has_bdim, c10::SymInt batch_size) {
48
+ if (has_bdim) {
49
+ return tensor;
50
+ }
51
+ const auto sizes = tensor.sym_sizes();
52
+ SymDimVector expanded_shape;
53
+ expanded_shape.reserve(sizes.size());
54
+ expanded_shape.emplace_back(std::move(batch_size));
55
+ expanded_shape.insert(expanded_shape.end(), sizes.begin(), sizes.end());
56
+ return tensor.expand_symint(expanded_shape);
57
+ }
58
+
59
+ #define VMAP_SUPPORT(op, batch_rule) \
60
+ m.impl(#op, op ## _generated_plumbing<decltype(&batch_rule), &batch_rule>);
61
+
62
+ #define VMAP_SUPPORT2(op, overload, batch_rule) \
63
+ m.impl(#op "." #overload, op ## _ ## overload ## _generated_plumbing<decltype(&batch_rule), &batch_rule>);
64
+
65
+ #define OP_DECOMPOSE(op) m.impl(#op, static_cast<decltype(&ATEN_FN(op))>(native::op));
66
+ #define OP_DECOMPOSE2(op, overload) m.impl(#op"."#overload, static_cast<decltype(&ATEN_FN2(op, overload))>(native::op));
67
+
68
+ // DO NOT USE ME DIRECTLY! Use BASIC_UNARY_BATCH_RULE to save yourself some pain
69
+ template <typename A, A a, typename C>
70
+ struct BasicUnaryBatchRuleHelper;
71
+
72
+ template <typename F, F Func, typename A, typename... T>
73
+ struct BasicUnaryBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
74
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
75
+ const Tensor& tensor,
76
+ std::optional<int64_t> batch_dim,
77
+ T... extra_args) {
78
+ return std::make_tuple(Func(tensor, std::forward<T>(extra_args)...), batch_dim);
79
+ }
80
+ };
81
+
82
+ // USAGE: BASIC_UNARY_BATCH_RULE(at::sin)
83
+ // INCORRECT USAGE: BASIC_UNARY_BATCH_RULE(&at::sin)
84
+ // It is important that this macro is not passed a function pointer!!
85
+ #define BASIC_UNARY_BATCH_RULE(fn) SINGLE_ARG(\
86
+ BasicUnaryBatchRuleHelper<\
87
+ decltype(&fn),\
88
+ &fn,\
89
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
90
+
91
+ #define UNARY_POINTWISE(op) \
92
+ VMAP_SUPPORT(op, BASIC_UNARY_BATCH_RULE(ATEN_FN(op)));
93
+
94
+ template <typename A, A a, typename C>
95
+ struct VariadicBdimsBatchRuleHelper;
96
+
97
+ template <typename F, F Func, typename A, typename... T>
98
+ struct VariadicBdimsBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
99
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
100
+ const Tensor& tensor,
101
+ std::optional<int64_t> batch_dim,
102
+ T... extra_args) {
103
+ auto tensor_ = moveBatchDimToFront(tensor, batch_dim);
104
+ return std::make_tuple(Func(tensor_, std::forward<T>(extra_args)...), 0);
105
+ }
106
+ };
107
+
108
+ // USAGE: VARIADIC_BDIMS_BATCH_RULE(at::cholesky_inverse)
109
+ // INCORRECT USAGE: VARIADIC_BDIMS_BATCH_RULE(&at::cholesky_inverse)
110
+ // It is important that this macro is not passed a function pointer!!
111
+ #define VARIADIC_BDIMS_BATCH_RULE(fn) SINGLE_ARG(\
112
+ VariadicBdimsBatchRuleHelper<\
113
+ decltype(&fn),\
114
+ &fn,\
115
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
116
+
117
+ #define VARIADIC_BDIMS(op) \
118
+ VMAP_SUPPORT(op, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN(op)));
119
+
120
+ #define VARIADIC_BDIMS2(op, overload) \
121
+ VMAP_SUPPORT2(op, overload, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN2(op, overload)));
122
+
123
+ template<class F, F Func>
124
+ void boxed_tensor_inputs_batch_rule(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
125
+ const auto& schema = op.schema();
126
+ const auto num_returns = schema.returns().size();
127
+ const auto num_arguments = schema.arguments().size();
128
+
129
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
130
+ auto maybe_layer = maybeCurrentDynamicLayer();
131
+ vmap_check_escaped(maybe_layer, "boxed_tensor_inputs_batch_rule");
132
+
133
+ int64_t cur_level = maybe_layer->layerId();
134
+
135
+ auto orig_arguments = torch::jit::last(*stack, num_arguments);
136
+ if (std::none_of(orig_arguments.begin(), orig_arguments.end(), ivalueParticipatesInCurrentLevel)) {
137
+ op.callBoxed(stack);
138
+ return;
139
+ }
140
+
141
+ auto arguments = torch::jit::pop(*stack, num_arguments);
142
+ std::vector<std::pair<Tensor, std::optional<int64_t>>> tensor_inputs;
143
+ std::vector<int64_t> tensor_pos;
144
+ for (const auto idx : c10::irange(0, num_arguments)) {
145
+ const auto& ivalue = arguments[idx];
146
+ if (ivalue.isTensor()) {
147
+ auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(ivalue.toTensor(), cur_level);
148
+ tensor_inputs.emplace_back(std::move(tensor_value), tensor_bdim);
149
+ tensor_pos.push_back(static_cast<int64_t>(idx));
150
+ }
151
+ }
152
+ Func(tensor_inputs);
153
+
154
+ size_t tensor_idx = 0;
155
+ TORCH_INTERNAL_ASSERT(!tensor_pos.empty());
156
+ for (const auto arg_idx : c10::irange(0, num_arguments)) {
157
+ if (tensor_idx >= tensor_pos.size() || (int64_t)arg_idx != tensor_pos[tensor_idx]) {
158
+ torch::jit::push(stack, arguments[arg_idx]);
159
+ } else {
160
+ TORCH_INTERNAL_ASSERT(tensor_idx < tensor_inputs.size());
161
+ torch::jit::push(stack, tensor_inputs[tensor_idx].first);
162
+ tensor_idx++;
163
+ }
164
+ }
165
+
166
+ op.callBoxed(stack);
167
+ const auto returns = torch::jit::pop(*stack, num_returns);
168
+ for (const auto& ret : returns) {
169
+ if (ret.isTensor()) {
170
+ torch::jit::push(stack, makeBatched(ret.toTensor(), 0, cur_level));
171
+ } else {
172
+ TORCH_INTERNAL_ASSERT(false, "This boxed batching rule does not currently support ops that return non-tensor values");
173
+ }
174
+ }
175
+ }
176
+
177
+ inline void handle_pointwise_ops(std::vector<std::pair<Tensor, std::optional<int64_t>>> &tensor_inputs) {
178
+ int64_t out_logical_rank = 0;
179
+ for (auto& tensor_input : tensor_inputs) {
180
+ int64_t cur_logical_rank = rankWithoutBatchDim(tensor_input.first, tensor_input.second);
181
+ out_logical_rank = std::max(out_logical_rank, cur_logical_rank);
182
+ }
183
+ for (auto& tensor_input: tensor_inputs) {
184
+ tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second);
185
+ tensor_input.first = maybePadToLogicalRank(tensor_input.first, tensor_input.second, out_logical_rank);
186
+ }
187
+ }
188
+
189
+ #define POINTWISE_BOXED(op) \
190
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_pointwise_ops), &handle_pointwise_ops>>());
191
+
192
+ #define POINTWISE_BOXED2(op, overload) \
193
+ m.impl(#op "." #overload, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_pointwise_ops), &handle_pointwise_ops>>());
194
+
195
+ inline void handle_variadic_bdims(std::vector<std::pair<Tensor, std::optional<int64_t>>> &tensor_inputs) {
196
+ for (auto & tensor_input : tensor_inputs) {
197
+ tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second);
198
+ }
199
+ }
200
+
201
+ #define VARIADIC_BDIMS_BOXED(op) \
202
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_variadic_bdims), &handle_variadic_bdims>>());
203
+
204
+ using UnpackedBatchedTensor = std::tuple<Tensor, std::optional<int64_t>>;
205
+
206
+ inline void find_and_unpack_tensors(
207
+ const torch::jit::Stack* stack,
208
+ int64_t num_args,
209
+ int64_t cur_level,
210
+ SmallVector<UnpackedBatchedTensor, 5>* tensors,
211
+ SmallVector<int64_t, 5>* tensors_pos,
212
+ int64_t* batch_size) {
213
+
214
+ int64_t computed_batch_size = -1;
215
+ int64_t args_begin = static_cast<int64_t>(stack->size()) - num_args;
216
+
217
+ for (const auto idx : c10::irange(0, num_args)) {
218
+ const auto& ivalue = (*stack)[args_begin + idx];
219
+ if (!ivalue.isTensor()) {
220
+ continue;
221
+ }
222
+ auto unpacked = unwrapTensorAtLevel(ivalue.toTensor(), cur_level);
223
+ const auto& [tensor_value, tensor_bdim] = unpacked;
224
+ if (tensor_bdim.has_value()) {
225
+ auto candidate_batch_size = tensor_value.size(*tensor_bdim);
226
+ if (computed_batch_size == -1) {
227
+ computed_batch_size = candidate_batch_size;
228
+ }
229
+ TORCH_INTERNAL_ASSERT(candidate_batch_size == computed_batch_size);
230
+ }
231
+
232
+ tensors->push_back(std::move(unpacked));
233
+ tensors_pos->push_back(idx);
234
+ }
235
+ TORCH_INTERNAL_ASSERT(computed_batch_size > -1);
236
+ *batch_size = computed_batch_size;
237
+ }
238
+
239
+ inline void boxed_existing_bdim_all_batch_rule(
240
+ const c10::OperatorHandle& op, torch::jit::Stack* stack) {
241
+ const auto& schema = op.schema();
242
+ const auto num_returns = schema.returns().size();
243
+ const auto num_arguments = static_cast<int64_t>(schema.arguments().size());
244
+
245
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
246
+ const auto maybe_layer = maybeCurrentDynamicLayer();
247
+ vmap_check_escaped(maybe_layer, "boxed_existing_bdim_all_batch_rule");
248
+
249
+ const auto arguments = torch::jit::last(stack, num_arguments);
250
+ if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) {
251
+ op.callBoxed(stack);
252
+ return;
253
+ }
254
+
255
+ int64_t args_begin = static_cast<int64_t>(stack->size()) - num_arguments;
256
+ SmallVector<UnpackedBatchedTensor, 5> tensor_inputs;
257
+ SmallVector<int64_t, 5> tensor_pos;
258
+ int64_t batch_size = 0;
259
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
260
+ int64_t cur_level = maybe_layer->layerId();
261
+
262
+ find_and_unpack_tensors(
263
+ stack, num_arguments, cur_level,
264
+ &tensor_inputs, &tensor_pos, &batch_size);
265
+
266
+ // for each tensor, ensure it has a bdim and reshape it.
267
+ for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) {
268
+ const auto& [value, bdim] = tensor_inputs[tensor_idx];
269
+ auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size);
270
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = reshape_dim_into(bdim.value_or(0), 0, value_);
271
+ }
272
+
273
+ op.callBoxed(stack);
274
+
275
+ for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) {
276
+ const auto& ret = (*stack)[idx];
277
+ TORCH_INTERNAL_ASSERT(ret.isTensor(),
278
+ "This boxed batching rule does not currently support ops that return non-tensor values");
279
+ (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level);
280
+ }
281
+ }
282
+
283
+ // Use when all tensors arguments accept one (normal) batch dim.
284
+ // This batching rule expands the batch dim on all Tensors, reshapes it into
285
+ // dim 0, calls the op, and then reshapes the batch dim out of dim 0.
286
+ // This is not the most efficient thing; if there are alternatives, plese try
287
+ // to use them. Use this only as a last resort.
288
+ #define EXISTING_BDIM_ALL_BOXED(op) \
289
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_existing_bdim_all_batch_rule>());
290
+
291
+ template <int64_t feature_rank, int64_t contig_tensor_index=-1>
292
+ inline void boxed_all_tensors_have_optional_bdim(
293
+ const c10::OperatorHandle& op, torch::jit::Stack* stack) {
294
+ const auto& schema = op.schema();
295
+ const auto num_returns = schema.returns().size();
296
+ const auto num_arguments = schema.arguments().size();
297
+
298
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
299
+ auto maybe_layer = maybeCurrentDynamicLayer();
300
+ vmap_check_escaped(maybe_layer, "boxed_all_tensors_have_optional_bdim");
301
+ int64_t cur_level = maybe_layer->layerId();
302
+
303
+ const auto arguments = torch::jit::last(stack, num_arguments);
304
+ if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) {
305
+ op.callBoxed(stack);
306
+ return;
307
+ }
308
+
309
+ int64_t args_begin = static_cast<int64_t>(stack->size() - num_arguments);
310
+ SmallVector<UnpackedBatchedTensor, 5> tensor_inputs;
311
+ SmallVector<int64_t, 5> tensor_pos;
312
+ int64_t batch_size = 0;
313
+
314
+ find_and_unpack_tensors(
315
+ stack, static_cast<int64_t>(num_arguments), cur_level,
316
+ &tensor_inputs, &tensor_pos, &batch_size);
317
+
318
+ std::optional<bool> is_no_batch_dim_case;
319
+
320
+ for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) {
321
+ const auto& value = std::get<0>(tensor_inputs[tensor_idx]);
322
+ auto bdim = std::get<1>(tensor_inputs[tensor_idx]);
323
+ const auto logical_rank = rankWithoutBatchDim(value, bdim);
324
+
325
+ if (!is_no_batch_dim_case.has_value()) {
326
+ is_no_batch_dim_case = (logical_rank == feature_rank);
327
+ }
328
+ auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size);
329
+ if (!bdim.has_value()) {
330
+ bdim = 0;
331
+ }
332
+ if (*is_no_batch_dim_case) {
333
+ TORCH_INTERNAL_ASSERT(logical_rank == feature_rank);
334
+ value_ = moveBatchDimToFront(value_, bdim);
335
+ if (tensor_idx == contig_tensor_index) {
336
+ value_ = value_.contiguous();
337
+ }
338
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_);
339
+ continue;
340
+ }
341
+ TORCH_INTERNAL_ASSERT(logical_rank == feature_rank + 1);
342
+ value_ = reshape_dim_into(*bdim, 0, value_);
343
+ if (tensor_idx == contig_tensor_index) {
344
+ value_ = value_.contiguous();
345
+ }
346
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_);
347
+ }
348
+
349
+ op.callBoxed(stack);
350
+
351
+ for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) {
352
+ const auto& ret = (*stack)[idx];
353
+ TORCH_INTERNAL_ASSERT(ret.isTensor(),
354
+ "This boxed batching rule does not currently support ops that return non-tensor values");
355
+ if (*is_no_batch_dim_case) {
356
+ (*stack)[idx] = makeBatched(ret.toTensor(), 0, cur_level);
357
+ } else {
358
+ (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level);
359
+ }
360
+ }
361
+ }
362
+
363
+ // Useful for many NN operators.
364
+ // The operator must satisfy the following:
365
+ // - All arguments must accept an optional batch dim.
366
+ // - All arguments must be the same rank
367
+ #define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED(feature_rank, op) \
368
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_all_tensors_have_optional_bdim<feature_rank>>());
369
+
370
+ #define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(feature_rank, op, contig_tensor_index) \
371
+ m.impl(#op, \
372
+ torch::CppFunction::makeFromBoxedFunction<\
373
+ boxed_all_tensors_have_optional_bdim<\
374
+ feature_rank, \
375
+ contig_tensor_index>\
376
+ >());
377
+
378
+ template <typename A, A a, typename C>
379
+ struct ExistingBdimBatchRuleHelper;
380
+
381
+ template <typename F, F Func, typename A, typename... T>
382
+ struct ExistingBdimBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
383
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
384
+ const Tensor& self,
385
+ std::optional<int64_t> self_bdim,
386
+ T... extra_args) {
387
+ auto self_ = reshape_dim_into(*self_bdim, 0, self);
388
+ auto out = Func(self_, std::forward<T>(extra_args)...);
389
+ return std::make_tuple(reshape_dim_outof_symint(0, self.sym_sizes()[*self_bdim], out), 0);
390
+ }
391
+ };
392
+
393
+ // USAGE: EXISTING_BDIM_BATCH_RULE(at::cholesky_inverse)
394
+ // INCORRECT USAGE: EXISTING_BDIM_BATCH_RULE(&at::cholesky_inverse)
395
+ // It is important that this macro is not passed a function pointer!!
396
+ #define EXISTING_BDIM_BATCH_RULE(fn) SINGLE_ARG(\
397
+ ExistingBdimBatchRuleHelper<\
398
+ decltype(&fn),\
399
+ &fn,\
400
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
401
+
402
+
403
+ #define EXISTING_BDIM(op) \
404
+ VMAP_SUPPORT(op, EXISTING_BDIM_BATCH_RULE(ATEN_FN(op)));
405
+
406
+ #define EXISTING_BDIM2(op, overload) \
407
+ VMAP_SUPPORT2(op, overload, EXISTING_BDIM_BATCH_RULE(ATEN_FN2(op, overload)));
408
+
409
+ #define INVOKE(object,ptrToMember) ((object).*(ptrToMember))
410
+
411
+
412
+ template <typename F, F Method, typename... ExtraArgs>
413
+ Tensor& unary_inplace_batch_rule(Tensor& self, std::optional<int64_t>, ExtraArgs... extra_args) {
414
+ INVOKE(self, Method)(std::forward<ExtraArgs>(extra_args)...);
415
+ return self;
416
+ }
417
+
418
+ inline int64_t get_bdim_size4(
419
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
420
+ const Tensor& b_value, std::optional<int64_t> b_bdim,
421
+ const Tensor& c_value, std::optional<int64_t> c_bdim,
422
+ const Tensor& d_value, std::optional<int64_t> d_bdim) {
423
+ if (a_bdim)
424
+ return a_value.size(*a_bdim);
425
+ if (b_bdim)
426
+ return b_value.size(*b_bdim);
427
+ if (c_bdim)
428
+ return c_value.size(*c_bdim);
429
+ if (d_bdim)
430
+ return d_value.size(*d_bdim);
431
+ TORCH_INTERNAL_ASSERT(false);
432
+ }
433
+
434
+ inline int64_t get_bdim_size3(
435
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
436
+ const Tensor& b_value, std::optional<int64_t> b_bdim,
437
+ const Tensor& c_value, std::optional<int64_t> c_bdim) {
438
+ if (a_bdim)
439
+ return a_value.size(*a_bdim);
440
+ if (b_bdim)
441
+ return b_value.size(*b_bdim);
442
+ if (c_bdim)
443
+ return c_value.size(*c_bdim);
444
+ TORCH_INTERNAL_ASSERT(false);
445
+ }
446
+
447
+ inline int64_t get_bdim_size2(
448
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
449
+ const Tensor& b_value, std::optional<int64_t> b_bdim) {
450
+ if (a_bdim)
451
+ return a_value.size(*a_bdim);
452
+ if (b_bdim)
453
+ return b_value.size(*b_bdim);
454
+ TORCH_INTERNAL_ASSERT(false);
455
+ }
456
+
457
+ inline c10::SymInt get_bdim_size2_symint(
458
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
459
+ const Tensor& b_value, std::optional<int64_t> b_bdim) {
460
+ if (a_bdim)
461
+ return a_value.sym_size(*a_bdim);
462
+ if (b_bdim)
463
+ return b_value.sym_size(*b_bdim);
464
+ TORCH_INTERNAL_ASSERT(false);
465
+ }
466
+
467
+ // [start, start + 1, ..., stop - 1]
468
+ inline VmapDimVector range(int64_t start, int64_t stop) {
469
+ TORCH_INTERNAL_ASSERT(stop >= start);
470
+ VmapDimVector dims;
471
+ dims.reserve(stop - start);
472
+ for (int64_t i = start; i < stop; i++) {
473
+ dims.emplace_back(i);
474
+ }
475
+ return dims;
476
+ }
477
+ std::tuple<Tensor, Tensor> _binary_pointwise_helper(
478
+ const Tensor& tensor, std::optional<int64_t> tensor_batch_dim, const Tensor& other, std::optional<int64_t> other_batch_dim,
479
+ bool do_type_promotion=true);
480
+
481
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedFallback.h ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/ATen.h>
9
+ #include <ATen/core/op_registration/op_registration.h>
10
+ #include <torch/library.h>
11
+
12
+ namespace at::functorch {
13
+
14
+ // This file contains code for the vmap fallback (also known as the
15
+ // BatchedTensor fallback or the Batched fallback). This code runs
16
+ // when an operation doesn't have a batching rule implemented.
17
+
18
+ // If an operator doesn't have a batching rule implemented then we fallback
19
+ // to this implementation. The fallback doesn't work on out= variants or
20
+ // view operations; that is, it works for out-of-place operations and
21
+ // in-place non-view operations.
22
+ //
23
+ // For out-of-place operations, the fallback effectively takes all of the
24
+ // BatchedTensors in `stack`, slices them, and runs `op` on all of the
25
+ // corresponding slices to produce slices of the outputs. The output slices
26
+ // then get `torch.stack`ed to create the
27
+ // final returns.
28
+ //
29
+ // The performance of the fallback is not very good because it introduces an
30
+ // extra copy from stacking the sliced outputs. Because of this, we prefer to
31
+ // write batching rules for operators whenever possible.
32
+ void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
33
+ void batchedNestedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
34
+
35
+ void vmapErrorFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
36
+
37
+ // The vmap fallback emits a warning by default, but it may be disabled if
38
+ // the user finds it to be too annoying.
39
+ TORCH_API bool isVmapFallbackWarningEnabled();
40
+ TORCH_API void setVmapFallbackWarningEnabled(bool enabled);
41
+
42
+ // Used for testing. The vmap fallback is enabled by default. When it is disabled,
43
+ // it raises an error.
44
+ TORCH_API bool isVmapFallbackEnabled();
45
+ TORCH_API void setVmapFallbackEnabled(bool enabled);
46
+
47
+ template <typename A> A vector_to_result(const std::vector<IValue>& buffer) {
48
+ return buffer[0].to<A>();
49
+ }
50
+ template <typename A, typename B> std::tuple<A, B> vector_to_result(const std::vector<IValue>& buffer) {
51
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>());
52
+ }
53
+ template <typename A, typename B, typename C> std::tuple<A, B, C> vector_to_result(const std::vector<IValue>& buffer) {
54
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>(), buffer[2].to<B>());
55
+ }
56
+
57
+ // slow_fallback is a way to call the vmap fallback inside some boxed kernel.
58
+ // There is probably some better way to metaprogram this.
59
+ template <typename Ret>
60
+ Ret slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
61
+ std::vector<IValue> stack(args.begin(), args.end());
62
+ batchedTensorForLoopFallback(op, &stack);
63
+ return vector_to_result<Ret>(stack);
64
+ }
65
+
66
+ template <typename A, typename B>
67
+ std::tuple<A, B> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
68
+ std::vector<IValue> stack(args.begin(), args.end());
69
+ batchedTensorForLoopFallback(op, &stack);
70
+ return vector_to_result<A, B>(stack);
71
+ }
72
+
73
+ template <typename A, typename B, typename C>
74
+ std::tuple<A, B, C> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
75
+ std::vector<IValue> stack(args.begin(), args.end());
76
+ batchedTensorForLoopFallback(op, &stack);
77
+ return vector_to_result<A, B, C>(stack);
78
+ }
79
+
80
+
81
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <bitset>
10
+
11
+ #include <ATen/ArrayRef.h>
12
+ #include <ATen/SmallVector.h>
13
+ #include <ATen/Tensor.h>
14
+
15
+ namespace at::functorch {
16
+
17
+ using Tensor = at::Tensor;
18
+
19
+ // We assume this in a few other places in the codebase,
20
+ // but there isn't a centralized definition.
21
+ constexpr int64_t kVmapMaxTensorDims = 64;
22
+
23
+ // The valid vmap levels range from [0, 64). This effectively means that we
24
+ // support a maximum of 64 nested vmaps.
25
+ constexpr int64_t kVmapNumLevels = 64;
26
+
27
+ // Store this number of elements of BatchDims on the stack. Most people will
28
+ // probably use <= 5 nested vmaps, but adjust this number as necessary.
29
+ constexpr int64_t kBatchDimsStackSize = 5;
30
+
31
+ // A BatchedTensorImpl holds an underlying Tensor and a single batch dim
32
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
33
+ // BatchedTensorImpl.
34
+ //
35
+ // The batch dimensions are treated as being "private"; they are not user-visible.
36
+ // For example, in the following Tensor,
37
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
38
+ // dimension 0 is batch dimension.
39
+ //
40
+ // bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public)
41
+ // dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7) tensor.
42
+ struct TORCH_API BatchedTensorImpl : public c10::TensorImpl {
43
+ explicit BatchedTensorImpl(at::DispatchKeySet key_set, Tensor value, int64_t dim, int64_t level);
44
+
45
+ // Returns batch dimension of this tensor
46
+ int64_t bdim() const { return bdim_; }
47
+
48
+ // Returns batch dimension of this tensor
49
+ int64_t level() const { return level_; }
50
+
51
+ // BatchedTensorImpl wraps a Tensor
52
+ const Tensor& value() const { return value_; }
53
+
54
+ // Given a public dimension index, return the dimension index in the underlying
55
+ // value() tensor.
56
+ // For example, if we have
57
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
58
+ // bt.actualDim(0) -> 1
59
+ // bt.actualDim(1) -> 2
60
+ // bt.actualDim(2) -> 3
61
+ // bt.actualDim(3) -> Error
62
+ int64_t actualDim(int64_t dim, bool wrap_dim = true) const;
63
+
64
+ IntArrayRef sizes_custom() const override;
65
+ SymIntArrayRef sym_sizes_custom() const override;
66
+ int64_t size_custom(int64_t d) const override;
67
+ c10::SymInt sym_size_custom(int64_t d) const override;
68
+ // We have to override this because we opted into CustomStrides
69
+ IntArrayRef strides_custom() const override;
70
+ SymIntArrayRef sym_strides_custom() const override;
71
+ // Override a bunch of methods inherited from TensorImpl to return error messages.
72
+ bool is_contiguous_custom(at::MemoryFormat memory_format=at::MemoryFormat::Contiguous) const override;
73
+ void set_size(int64_t dim, int64_t new_size) override;
74
+ void set_stride(int64_t dim, int64_t new_stride) override;
75
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
76
+ const c10::VariableVersion& version_counter,
77
+ bool allow_tensor_metadata_change) const override;
78
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
79
+ c10::VariableVersion&& version_counter,
80
+ bool allow_tensor_metadata_change) const override;
81
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
82
+ #ifdef DEBUG
83
+ bool has_storage() const override;
84
+ #endif
85
+
86
+ void refreshTensorMetadata();
87
+
88
+ // Used in torchdim. torchdim uses non-lexical BatchedTensor; the way it
89
+ // accomplishes this is a hack where it is able to modify the levels of
90
+ // BatchedTensor to match the level of the current vmap transform.
91
+ void _unsafe_set_level(int64_t level) {
92
+ level_ = level;
93
+ }
94
+
95
+ // Used in batching rule for in-place view operations that can change
96
+ // the index of the bdim (think squeeze_, unsqueeze_)
97
+ void unsafe_set_bdim(int64_t bdim) {
98
+ // NB: you MUST call refreshTensorMetadata after doing this.
99
+ bdim_ = bdim;
100
+ }
101
+ private:
102
+ // see NOTE: [BatchedTensorImpl levels invariant]
103
+ void checkInvariants() const;
104
+ const char* tensorimpl_type_name() const override;
105
+
106
+ Tensor value_;
107
+
108
+ int64_t level_;
109
+ int64_t bdim_;
110
+ };
111
+
112
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
113
+ // BatchedTensorImpl.
114
+ inline bool isBatchedTensor(const Tensor& tensor) {
115
+ return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::FuncTorchBatched) ||
116
+ tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::BatchedNestedTensor);
117
+ }
118
+
119
+ // It is unsafe to call this on a Tensor that is not backed by a
120
+ // BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible.
121
+ inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) {
122
+ return static_cast<BatchedTensorImpl*>(tensor.unsafeGetTensorImpl());
123
+ }
124
+
125
+ inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) {
126
+ if (!isBatchedTensor(tensor)) {
127
+ return nullptr;
128
+ }
129
+ return unsafeGetBatchedImpl(tensor);
130
+ }
131
+
132
+ // Returns a bitset. If bit i is set, then that means dim i is a batchdim.
133
+ inline std::bitset<kVmapMaxTensorDims> createBatchDimBitset(int64_t dim) {
134
+ std::bitset<kVmapMaxTensorDims> is_bdim;
135
+ is_bdim.set(dim);
136
+ return is_bdim;
137
+ }
138
+
139
+ // Creates a bitset for the given level
140
+ inline std::bitset<kVmapNumLevels> createVmapLevelsBitset(int64_t level) {
141
+ std::bitset<kVmapNumLevels> result;
142
+ result.set(level);
143
+ return result;
144
+ }
145
+
146
+ // Use this to construct a BatchedTensor from a regular Tensor
147
+ TORCH_API Tensor makeBatched(Tensor tensor, int64_t dim, int64_t level);
148
+
149
+ // Adds a batch dim to `tensor`, returning a BatchedTensor
150
+ TORCH_API Tensor addBatchDim(Tensor tensor, int64_t dim, int64_t level);
151
+
152
+ // Certain dispatch keys must be propagated to the BatchedTensor (or, in general,
153
+ // any wrapper Tensor subclasses). This is because there are methods on Tensor
154
+ // that skip dispatch and check for the presence of a dispatch key (e.g. is_cpu()).
155
+ // TODO: should probably contain more (or all?) backend keys
156
+ constexpr DispatchKeySet kKeysToPropagateToWrapper({
157
+ DispatchKey::Negative,
158
+ DispatchKey::Conjugate,
159
+ DispatchKey::XLA,
160
+ DispatchKey::CUDA,
161
+ DispatchKey::CPU,
162
+ DispatchKey::PrivateUse1,
163
+ });
164
+
165
+ inline DispatchKeySet getKeysToPropagateToWrapper(const Tensor& tensor, DispatchKeySet to_propagate=kKeysToPropagateToWrapper) {
166
+ auto key_set = tensor.unsafeGetTensorImpl()->key_set();
167
+ return key_set & kKeysToPropagateToWrapper;
168
+ }
169
+
170
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/Tensor.h>
9
+ #include <ATen/VmapGeneratedPlumbing.h>
10
+
11
+ // This file contains template metaprogramming things that are used for our
12
+ // batching rules.
13
+ //
14
+ // See NOTE: [vmap plumbing] for more details on why this is necessary.
15
+ // The plumbing has a bunch of metaprogramming hacks for determining the signature
16
+ // of a batching rule from the signature of the operator, many of which use the
17
+ // helper functions in this file.
18
+
19
+ namespace at::functorch {
20
+
21
+ // Metaprogramming things
22
+ template <class... Items> using typelist = c10::guts::typelist::typelist<Items...>;
23
+ template <class TypeList> using head_t = c10::guts::typelist::head_t<TypeList>;
24
+ template <class TL1, class TL2> using concat_t = c10::guts::typelist::concat_t<TL1, TL2>;
25
+ template <typename T> class debug_t;
26
+
27
+ // tail operation
28
+ template<class TypeList>
29
+ struct tail final {
30
+ static_assert(c10::guts::false_t<TypeList>::value,
31
+ "In typelist::tail<T>, the T argument must be typelist<...>.");
32
+ };
33
+ template<class Head, class... Tail>
34
+ struct tail<typelist<Head, Tail...>> final {
35
+ using type = typelist<Tail...>;
36
+ };
37
+ template<class TypeList> using tail_t = typename tail<TypeList>::type;
38
+
39
+ template <class First, class Second, class Next, class Tail>
40
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext {
41
+ using type = Next;
42
+ };
43
+ template <class Next, class Tail>
44
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor, std::optional<int64_t>, Next, Tail> {
45
+ using type = Tail;
46
+ };
47
+ template <class Next, class Tail>
48
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const Tensor&, std::optional<int64_t>, Next, Tail> {
49
+ using type = Tail;
50
+ };
51
+ template <class Next, class Tail>
52
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor&, std::optional<int64_t>, Next, Tail> {
53
+ using type = Tail;
54
+ };
55
+ template <class Next, class Tail>
56
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>, std::optional<int64_t>, Next, Tail> {
57
+ using type = Tail;
58
+ };
59
+ template <class Next, class Tail>
60
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
61
+ using type = Tail;
62
+ };
63
+ template <class Next, class Tail>
64
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
65
+ using type = Tail;
66
+ };
67
+ template <class Next, class Tail>
68
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::vector<Tensor>, std::optional<int64_t>, Next, Tail> {
69
+ using type = Tail;
70
+ };
71
+ template <class TypeList> struct RemoveBatchDimAfterTensor {
72
+ using first = head_t<TypeList>;
73
+ using next = tail_t<TypeList>;
74
+ using second = head_t<next>;
75
+ using tail = tail_t<next>;
76
+
77
+ using type = concat_t<
78
+ typelist<first>,
79
+ typename RemoveBatchDimAfterTensor<
80
+ typename IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<first, second, next, tail>::type
81
+ >::type
82
+ >;
83
+ };
84
+ template <class Type> struct RemoveBatchDimAfterTensor<typelist<Type>> {
85
+ using type = typelist<Type>;
86
+ };
87
+ template <> struct RemoveBatchDimAfterTensor<typelist<>> {
88
+ using type = typelist<>;
89
+ };
90
+ template<class TypeList> using remove_batch_dim_after_tensor_t = typename RemoveBatchDimAfterTensor<TypeList>::type;
91
+
92
+ template <typename T> struct UnpackSingleItemTuple {
93
+ using type = T;
94
+ };
95
+ template <typename T> struct UnpackSingleItemTuple<std::tuple<T>> {
96
+ using type = T;
97
+ };
98
+ template <typename T> using unpack_single_item_tuple_t = typename UnpackSingleItemTuple<T>::type;
99
+
100
+ template <typename Return, typename TupleArgs> struct BuildFunctionHelper;
101
+ template <typename Return, typename... Args> struct BuildFunctionHelper<Return, std::tuple<Args...>> {
102
+ using type = Return(Args...);
103
+ };
104
+ template <typename Return, typename TL>
105
+ struct BuildFunction {
106
+ using type = typename BuildFunctionHelper<Return, c10::guts::typelist::to_tuple_t<TL>>::type;
107
+ };
108
+ template <typename Return, typename TL> using build_function_t = typename BuildFunction<Return, TL>::type;
109
+
110
+
111
+ template <typename batch_rule_t> struct ToOperatorType {
112
+ using batch_rule_return_type = typename c10::guts::function_traits<batch_rule_t>::return_type;
113
+ using batch_rule_parameter_types = typename c10::guts::function_traits<batch_rule_t>::parameter_types;
114
+
115
+ using operator_parameter_types = remove_batch_dim_after_tensor_t<batch_rule_parameter_types>;
116
+ using operator_return_type =
117
+ unpack_single_item_tuple_t<
118
+ c10::guts::typelist::to_tuple_t<
119
+ remove_batch_dim_after_tensor_t<
120
+ c10::guts::typelist::from_tuple_t<batch_rule_return_type>>>>;
121
+
122
+ using type = build_function_t<operator_return_type, operator_parameter_types>;
123
+ };
124
+ template <typename batch_rule_t> using to_operator_t = typename ToOperatorType<batch_rule_t>::type;
125
+
126
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/DynamicLayer.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/functorch/Macros.h>
9
+ #include <c10/core/DispatchKey.h>
10
+ #include <ATen/core/function_schema.h>
11
+ #include <optional>
12
+ #include <c10/core/impl/LocalDispatchKeySet.h>
13
+ #include <ATen/functorch/Interpreter.h>
14
+ #include <ATen/functorch/VmapInterpreter.h>
15
+ #include <ATen/functorch/ADInterpreters.h>
16
+ #include <ATen/functorch/FunctionalizeInterpreter.h>
17
+
18
+ // Forward declared
19
+ namespace c10 { struct AutogradMetaInterface; }
20
+
21
+ namespace at::functorch {
22
+
23
+ // This file contains the implementation of functorch's interpreter stack.
24
+ // See NOTE: [functorch interpreter stack] first before reading on.
25
+ //
26
+ // NB: the functorch interpreter stack is also referred to as:
27
+ // - the "dynamic layer stack" -- an older name for "interpreter" was
28
+ // "dynamic layer".
29
+ // - the "functorch mode stack". You can think of each functorch transform as a
30
+ // "mode" (in the same sense as torch_dispatch mode or torch_function mode),
31
+ // and functorch being an implementation of a "mode stack" where the modes
32
+ // may be arbitrary composed.
33
+
34
+ // DynamicLayer is basically the same thing as an Interpreter.
35
+ // It represents a functorch transform and it holds an Interpreter,
36
+ // which contains metadata related to the transform and instructions on
37
+ // how to perform the transform.
38
+ //
39
+ // TODO: we can excise DynamicLayer in favor of Interpreter,
40
+ // But I am going to leave it for now as a compatiblity shim to avoid
41
+ // needing to refactor a lot of callsites...
42
+ struct TORCH_API DynamicLayer {
43
+ explicit DynamicLayer(
44
+ TransformType transform_type,
45
+ int64_t layerId,
46
+ std::optional<c10::SymInt> batchSize = std::nullopt,
47
+ std::optional<RandomnessType> randomness = std::nullopt,
48
+ std::optional<bool> prev_grad_mode = std::nullopt,
49
+ std::optional<bool> pre_fwd_grad_mode = std::nullopt,
50
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
51
+
52
+ TransformType key() const;
53
+ int64_t layerId() const;
54
+
55
+ const Interpreter& interpreter() const { return interpreter_; }
56
+ Interpreter& interpreter() { return interpreter_; }
57
+
58
+ // Only valid for vmap
59
+ c10::SymInt batchSize() const;
60
+ RandomnessType randomness() const;
61
+
62
+ private:
63
+ Interpreter interpreter_;
64
+ };
65
+
66
+ TORCH_API int64_t initAndPushDynamicLayer(
67
+ TransformType transform_type,
68
+ std::optional<c10::SymInt> batch_size = std::nullopt,
69
+ std::optional<RandomnessType> randomness = std::nullopt,
70
+ std::optional<bool> prev_grad_mode = std::nullopt,
71
+ std::optional<bool> prev_fwd_grad_mode = std::nullopt,
72
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
73
+ TORCH_API DynamicLayer popDynamicLayerAndDeleteMetadata();
74
+ TORCH_API std::optional<DynamicLayer> maybeCurrentDynamicLayer();
75
+ TORCH_API const std::vector<DynamicLayer>& getDynamicLayerStack();
76
+ TORCH_API void setDynamicLayerStack(const std::vector<DynamicLayer>& stack);
77
+ TORCH_API void setDynamicLayerFrontBackKeysIncluded(bool included);
78
+
79
+ // NOTE: [Life handles and lexically scoped transforms]
80
+ // functorch transforms are lexically scoped.
81
+ // Given a level, we store a "life handle" that is a boolean that tells us if the
82
+ // transform with that level is active or not.
83
+ //
84
+ // functorch's TensorWrapper (for grad transforms) stores a life handle.
85
+ // If a TensorWrapper escapes from the scope of the transform, then somehow
86
+ // it must know it escaped; it can tell by querying the life handle.
87
+ TORCH_API const std::shared_ptr<bool>& getLifeHandleForLevel(int64_t level);
88
+
89
+ // Returns if an operator is in-place. An operator is inplace if:
90
+ // 1. The first argument is a Tensor and it is being written to
91
+ // 2. The first argument is being returned
92
+ // 3. No other arguments are aliased
93
+ // Here is an example of an in-place operator:
94
+ // add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
95
+ TORCH_API bool isInplaceOp(const c10::FunctionSchema& schema);
96
+
97
+ // Given the indices of unwrapped inputs and the schema, this returns the indices of any outputs that should remain unwrapped
98
+ TORCH_API std::optional<size_t> findAliasedOutput(const FunctionSchema& schema, const int64_t immutable_input);
99
+
100
+ TORCH_API Tensor unwrapIfDead(const Tensor& tensor);
101
+ TORCH_API bool isDeadTensorWrapper(const Tensor& tensor);
102
+
103
+ // Pretty printers
104
+ TORCH_API std::ostream& operator<<(std::ostream& os, const DynamicLayer& layer);
105
+ TORCH_API std::ostream& operator<<(std::ostream& os, const std::vector<DynamicLayer>& dynamicLayerStack);
106
+
107
+ // While a functorch transform is active, torch.autograd.function._SingleLevelFunction
108
+ // is disabled by default. The following two APIs are APIs for enabling
109
+ // it. These are not user-facing APIs. We can delete this in the future, but
110
+ // it is useful for debugging when something goes wrong with the
111
+ // autograd.Function <> functorch interaction, which uses _SingleLevelFunction,
112
+ // because it leads to loud errors if something is incorrect.
113
+ TORCH_API void setSingleLevelAutogradFunctionAllowed(bool allowed);
114
+ TORCH_API bool getSingleLevelAutogradFunctionAllowed();
115
+
116
+ // While a functorch grad transform is active, Tensor.requires_grad_() gets
117
+ // disabled. These two functions are the mechanism to controlling that.
118
+ TORCH_API void setInplaceRequiresGradAllowed(bool allowed);
119
+ TORCH_API bool getInplaceRequiresGradAllowed();
120
+
121
+ TORCH_API DynamicLayer popDynamicLayer();
122
+ TORCH_API int64_t pushDynamicLayer(DynamicLayer&& layer);
123
+
124
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/functorch/Interpreter.h>
3
+
4
+ namespace at::functorch {
5
+
6
+ // This is the interpreter that handles the functionalize() transform.
7
+ // See NOTE: [functorch interpreter stack] for more details.
8
+
9
+ struct FunctionalizeInterpreterPtr {
10
+ explicit FunctionalizeInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Functionalize); }
11
+ TransformType key() const { return base_->key(); }
12
+ int64_t level() const { return base_->level(); }
13
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
14
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
15
+ bool functionalizeAddBackViews() const {
16
+ return std::get<FunctionalizeInterpreterMeta>(base_->meta()).functionalizeAddBackViews_;
17
+ }
18
+ private:
19
+ const Interpreter* base_;
20
+ };
21
+
22
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/Interpreter.h ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/functorch/Macros.h>
4
+ #include <ATen/core/dispatch/Dispatcher.h>
5
+ #include <c10/core/impl/LocalDispatchKeySet.h>
6
+ #include <optional>
7
+ #include <bitset>
8
+ #include <utility>
9
+ #include <variant>
10
+
11
+ #include <nlohmann/json.hpp>
12
+
13
+ namespace at::functorch {
14
+
15
+ // NOTE: [functorch interpreter stack]
16
+ //
17
+ // functorch's dispatching system uses a stack of interpreters.
18
+ // Historically we've referred to this as the "DynamicLayerStack".
19
+ //
20
+ // An interpreter is something that reads in the code it is passed
21
+ // and then executes it. We have a different interpreter per-transform:
22
+ // the "VmapInterpreter" is responsible for reading in operators (like aten::mv)
23
+ // and executing the batched version of it (the batching rule for aten::mv).
24
+ //
25
+ // Concretely, each interpreter is responsible for two things:
26
+ //
27
+ // 1) process(ophandle, stack)
28
+ // Given an operator handle and a stack of arguments, the interpreter is
29
+ // responsible for figuring out how to execute the operation under the semantics
30
+ // of the interpreter. For e.g. VmapInterpreter, this is figuring out how to call
31
+ // the batching rule.
32
+ //
33
+ // The batching rules are stored as kernels on the FuncTorchBatched key, so the way
34
+ // VmapInterpreter calls the batching rule is roughly: (A) exclude all
35
+ // dispatch keys aside from the Batched key, (B) redispatch so we get to the
36
+ // Batched key.
37
+ //
38
+ // 2) sendToNextInterpreter(ophandle, stack)
39
+ // The VmapInterpreter, when it sees aten::mv, will process it into a call to
40
+ // aten::mm. It then needs to send the call to aten::mm to the next interpreter
41
+ // in the interpreter stack.
42
+ //
43
+ // The VmapInterpreter just does this via a call to ophandle.callBoxed(stack)
44
+ // and most Interpreters will implement it this way.
45
+
46
+ enum class RandomnessType {
47
+ Error, // always errors when calling a random function
48
+ Same, // randomness appears the same across batches
49
+ Different, // randomness appears different across batches
50
+ END
51
+ };
52
+
53
+ enum class TransformType {
54
+ Torch, // Unused
55
+ Vmap,
56
+ Grad, // reverse-mode AD, aka vjp
57
+ Jvp, // forward-mode AD
58
+ Functionalize,
59
+ };
60
+
61
+ std::ostream& operator<<(std::ostream& os, const TransformType& t);
62
+
63
+ // NOTE: [Interpreter "subclassing" design]
64
+ //
65
+ // How are various Interpreters for different transforms (vmap, grad, ...)
66
+ // implemented?
67
+ //
68
+ // Accessing interpreters is in the hot-path of functorch so we have a constraint
69
+ // that this code must be as fast as possible.
70
+ //
71
+ // As a result, we stay away from virtual methods and this causes our code
72
+ // to look a little funny.
73
+ //
74
+ // `Interpreter` is the struct for Interpreters. It holds ALL of the
75
+ // relevant information (what type of interpreter it is and the metadata).
76
+ // Metadata for each interpreter is represented as a Union (std::variant)
77
+ // of all possible metadata (VmapInterpreterMeta, GradInterpreterMeta, ...).
78
+ //
79
+ // Given an Interpreter, how do I get a "VmapInterpreter"? You may wish to do this
80
+ // if you want to access the metadata fields (like batchSize and randomness).
81
+ //
82
+ // Each type of interpreter (e.g. Vmap) has a convenience struct
83
+ // (e.g. VmapInterpreterPtr) associated with it.
84
+ //
85
+ // Construct the convenience struct with VmapInterpreterPtr(Interpreter*),
86
+ // and then one can access methods on VmapInterpreterPtr like so:
87
+ // >>> VmapInterpreterPtr(&interpreter).batchSize()
88
+ //
89
+ // Finally, Interpreter::process switches on the type of the interpreter
90
+ // and calls one of {Transform}Intepreter::processImpl under the hood.
91
+ // Same for Interpreter::sendToNextInterpreter :)
92
+
93
+ struct VmapInterpreterMeta {
94
+ explicit VmapInterpreterMeta(c10::SymInt batchSize, RandomnessType randomness) :
95
+ batchSize_(std::move(batchSize)), randomness_(randomness) {}
96
+
97
+ c10::SymInt batchSize_;
98
+ RandomnessType randomness_;
99
+
100
+ VmapInterpreterMeta() = default;
101
+ VmapInterpreterMeta(const VmapInterpreterMeta&) = default;
102
+ VmapInterpreterMeta(VmapInterpreterMeta&&) = default;
103
+ VmapInterpreterMeta& operator=(const VmapInterpreterMeta&) = default;
104
+ VmapInterpreterMeta& operator=(VmapInterpreterMeta&&) = default;
105
+ ~VmapInterpreterMeta() = default;
106
+
107
+ template <typename T>
108
+ friend void to_json(T& json_j, const VmapInterpreterMeta& json_t) {
109
+ if (json_t.batchSize_.is_heap_allocated()) {
110
+ throw std::runtime_error("Serialization for heap-allocated SymInt is not implemented yet");
111
+ }
112
+ json_j["batchSize"] = json_t.batchSize_.as_int_unchecked();
113
+ json_j["randomness"] = static_cast<int64_t>(json_t.randomness_);
114
+ }
115
+
116
+ template <typename T>
117
+ friend void from_json(const T& json_j, VmapInterpreterMeta& json_t) {
118
+ json_t.batchSize_ = c10::SymInt(SymInt::Unchecked::UNCHECKED, json_j["batchSize"]);
119
+ json_t.randomness_ = static_cast<RandomnessType>(json_j["randomness"]);
120
+ }
121
+ };
122
+
123
+ struct GradInterpreterMeta {
124
+ explicit GradInterpreterMeta(bool prevGradMode): prevGradMode_(prevGradMode) {}
125
+ GradInterpreterMeta() = default;
126
+ GradInterpreterMeta(const GradInterpreterMeta&) = default;
127
+ GradInterpreterMeta(GradInterpreterMeta&&) = default;
128
+ GradInterpreterMeta& operator=(const GradInterpreterMeta&) = default;
129
+ GradInterpreterMeta& operator=(GradInterpreterMeta&&) = default;
130
+ ~GradInterpreterMeta() = default;
131
+
132
+ bool prevGradMode_;
133
+ template <typename T>
134
+ friend void to_json(T& json_j, const GradInterpreterMeta& json_t) {
135
+ json_j["prevGradMode"] = json_t.prevGradMode_;
136
+ }
137
+
138
+ template <typename T>
139
+ friend void from_json(const T& json_j, GradInterpreterMeta& json_t) {
140
+ json_t.prevGradMode_ = json_j["prevGradMode"];
141
+ }
142
+ };
143
+
144
+ struct JvpInterpreterMeta {
145
+ explicit JvpInterpreterMeta(bool prevFwdGradMode) : prevFwdGradMode_(prevFwdGradMode) {}
146
+ JvpInterpreterMeta() = default;
147
+ JvpInterpreterMeta(const JvpInterpreterMeta&) = default;
148
+ JvpInterpreterMeta(JvpInterpreterMeta&&) = default;
149
+ JvpInterpreterMeta& operator=(const JvpInterpreterMeta&) = default;
150
+ JvpInterpreterMeta& operator=(JvpInterpreterMeta&&) = default;
151
+ ~JvpInterpreterMeta() = default;
152
+
153
+ bool prevFwdGradMode_;
154
+ template <typename T>
155
+ friend void to_json(T& json_j, const JvpInterpreterMeta& json_t) {
156
+ json_j["prevFwdGradMode"] = json_t.prevFwdGradMode_;
157
+ }
158
+
159
+ template <typename T>
160
+ friend void from_json(const T& json_j, JvpInterpreterMeta& json_t) {
161
+ json_t.prevFwdGradMode_ = json_j["prevFwdGradMode"];
162
+ }
163
+ };
164
+
165
+ struct FunctionalizeInterpreterMeta {
166
+ explicit FunctionalizeInterpreterMeta(bool functionalizeAddBackViews) :
167
+ functionalizeAddBackViews_(functionalizeAddBackViews) {}
168
+ FunctionalizeInterpreterMeta() = default;
169
+ FunctionalizeInterpreterMeta(const FunctionalizeInterpreterMeta&) = default;
170
+ FunctionalizeInterpreterMeta(FunctionalizeInterpreterMeta&&) = default;
171
+ FunctionalizeInterpreterMeta& operator=(const FunctionalizeInterpreterMeta&) = default;
172
+ FunctionalizeInterpreterMeta& operator=(FunctionalizeInterpreterMeta&&) = default;
173
+ ~FunctionalizeInterpreterMeta() = default;
174
+
175
+ bool functionalizeAddBackViews_;
176
+ template <typename T>
177
+ friend void to_json(T& json_j, const FunctionalizeInterpreterMeta& json_t) {
178
+ json_j["functionalizeAddBackViews"] = json_t.functionalizeAddBackViews_;
179
+ }
180
+
181
+ template <typename T>
182
+ friend void from_json(const T& json_j, FunctionalizeInterpreterMeta& json_t) {
183
+ json_t.functionalizeAddBackViews_ = json_j["functionalizeAddBackViews"];
184
+ }
185
+ };
186
+
187
+ typedef std::variant<
188
+ int64_t,
189
+ GradInterpreterMeta,
190
+ JvpInterpreterMeta,
191
+ VmapInterpreterMeta,
192
+ FunctionalizeInterpreterMeta
193
+ > InterpreterMeta;
194
+
195
+
196
+ struct Interpreter {
197
+ // factory functions
198
+ static Interpreter Vmap(int64_t level, c10::SymInt batchSize, RandomnessType randomness) {
199
+ return Interpreter(TransformType::Vmap, level, VmapInterpreterMeta(std::move(batchSize), randomness));
200
+ }
201
+ static Interpreter Grad(int64_t level, bool prevGradMode) {
202
+ return Interpreter(TransformType::Grad, level, GradInterpreterMeta(prevGradMode));
203
+ }
204
+ static Interpreter Jvp(int64_t level, bool prevFwdGradMode) {
205
+ return Interpreter(TransformType::Jvp, level, JvpInterpreterMeta(prevFwdGradMode));
206
+ }
207
+ static Interpreter Functionalize(int64_t level, bool functionalizeAddBackViews) {
208
+ return Interpreter(TransformType::Functionalize, level, FunctionalizeInterpreterMeta(functionalizeAddBackViews));
209
+ }
210
+
211
+ // methods
212
+ TransformType key() const { return type_; }
213
+ int64_t level() const { return level_; }
214
+ const InterpreterMeta& meta() const { return meta_; }
215
+
216
+ void process(const c10::OperatorHandle& op, torch::jit::Stack* stack);
217
+ void sendToNextInterpreter(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
218
+
219
+ void saveLocalDispatchKeySet(c10::impl::LocalDispatchKeySet keyset) {
220
+ TORCH_INTERNAL_ASSERT(!savedLocalDispatchKeySet_.has_value());
221
+ savedLocalDispatchKeySet_ = keyset;
222
+ }
223
+ void clearSavedLocalDispatchKeySet() {
224
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
225
+ savedLocalDispatchKeySet_ = std::nullopt;
226
+ }
227
+ c10::impl::LocalDispatchKeySet getSavedLocalDispatchKeySet() const {
228
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
229
+ return *savedLocalDispatchKeySet_;
230
+ }
231
+
232
+ // An Interpreter is alive if we are currently inside the ongoing transform
233
+ // for the interpreter. For example, vmap(f)(x); inside of f, the vmap's
234
+ // corresponding Interpreter is alive, even when it is not on the DynamicLayerStack.
235
+ bool is_alive() const {
236
+ return *is_alive_;
237
+ }
238
+ const std::shared_ptr<bool>& is_alive_ptr() const {
239
+ return is_alive_;
240
+ }
241
+ void set_is_alive(bool alive) {
242
+ *is_alive_ = alive;
243
+ }
244
+
245
+ // Please don't use this
246
+ explicit Interpreter() = default;
247
+
248
+ template <typename T>
249
+ friend void to_json(T& json_j, const Interpreter& json_t) {
250
+ json_j["type"] = static_cast<int64_t>(json_t.type_);
251
+ json_j["level"] = json_t.level_;
252
+ if (json_t.savedLocalDispatchKeySet_) {
253
+ json_j["savedLocalDispatchKeySet"] = {
254
+ {"included", json_t.savedLocalDispatchKeySet_->included_.raw_repr()},
255
+ {"excluded", json_t.savedLocalDispatchKeySet_->excluded_.raw_repr()}
256
+ };
257
+ } else {
258
+ json_j["savedLocalDispatchKeySet"] = nlohmann::json();
259
+ }
260
+ json_j["is_alive"] = *json_t.is_alive_;
261
+ std::visit([&](auto&& arg) {
262
+ using V = std::decay_t<decltype(arg)>;
263
+ if constexpr (std::is_same_v<V, int64_t>) {
264
+ json_j["meta"] = {{"Torch", arg}};
265
+ } else if constexpr (std::is_same_v<V, GradInterpreterMeta>) {
266
+ json_j["meta"] = {{"Grad", arg}};
267
+ } else if constexpr (std::is_same_v<V, JvpInterpreterMeta>) {
268
+ json_j["meta"] = {{"Jvp", arg}};
269
+ } else if constexpr (std::is_same_v<V, VmapInterpreterMeta>) {
270
+ json_j["meta"] = {{"Vmap", arg}};
271
+ } else if constexpr (std::is_same_v<V, FunctionalizeInterpreterMeta>) {
272
+ json_j["meta"] = {{"Functionalize", arg}};
273
+ } else {
274
+ static_assert(false && sizeof(V), "unknown variant case");
275
+ }
276
+ }, json_t.meta_);
277
+ }
278
+
279
+ template <typename T>
280
+ friend void from_json(const T& json_j, Interpreter& json_t) {
281
+ json_t.type_ = static_cast<TransformType>(json_j["type"]);
282
+ json_t.level_ = json_j["level"];
283
+ auto savedLocalDispatchKeySet = json_j["savedLocalDispatchKeySet"];
284
+ if (savedLocalDispatchKeySet.is_null()) {
285
+ json_t.savedLocalDispatchKeySet_ = std::nullopt;
286
+ } else {
287
+ c10::impl::PODLocalDispatchKeySet pod;
288
+ pod.set_included(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["included"].template get<uint64_t>()));
289
+ pod.set_excluded(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["excluded"].template get<uint64_t>()));
290
+ json_t.savedLocalDispatchKeySet_ = c10::impl::LocalDispatchKeySet(pod);
291
+ }
292
+ json_t.is_alive_ = std::make_shared<bool>(json_j["is_alive"]);
293
+ auto meta = json_j["meta"];
294
+ if (meta.contains("Torch")) {
295
+ json_t.meta_.emplace<int64_t>(meta["Torch"].template get<int64_t>());
296
+ } else if (meta.contains("Grad")) {
297
+ json_t.meta_.emplace<GradInterpreterMeta>(meta["Grad"].template get<GradInterpreterMeta>());
298
+ } else if (meta.contains("Jvp")) {
299
+ json_t.meta_.emplace<JvpInterpreterMeta>(meta["Jvp"].template get<JvpInterpreterMeta>());
300
+ } else if (meta.contains("Vmap")) {
301
+ json_t.meta_.emplace<VmapInterpreterMeta>(meta["Vmap"].template get<VmapInterpreterMeta>());
302
+ } else if (meta.contains("Functionalize")) {
303
+ json_t.meta_.emplace<FunctionalizeInterpreterMeta>(meta["Functionalize"].template get<FunctionalizeInterpreterMeta>());
304
+ } else {
305
+ throw std::runtime_error("unknown interpreter metadata type");
306
+ }
307
+ }
308
+
309
+ std::string serialize() const {
310
+ return nlohmann::json(*this).dump();
311
+ }
312
+
313
+ static Interpreter deserialize(const std::string& serialized) {
314
+ return nlohmann::json::parse(serialized).get<Interpreter>();
315
+ }
316
+
317
+ private:
318
+ explicit Interpreter(TransformType type, int64_t level, InterpreterMeta meta):
319
+ type_(type), level_(level), is_alive_(std::make_shared<bool>(false)), meta_(std::move(meta)) {}
320
+
321
+ // fields
322
+ TransformType type_{};
323
+ int64_t level_{};
324
+ std::optional<c10::impl::LocalDispatchKeySet> savedLocalDispatchKeySet_;
325
+ std::shared_ptr<bool> is_alive_;
326
+ InterpreterMeta meta_;
327
+ };
328
+
329
+ // Applies the following for-loop:
330
+ // for i in range(begin, end):
331
+ // args[i] = func(args[i])
332
+ void foreachTensorInplace(std::vector<IValue>& args, int64_t begin, int64_t end,
333
+ std::function<Tensor(const Tensor&)> func);
334
+
335
+ // Applies the following for-loop:
336
+ // for i in range(begin, end):
337
+ // if use_flag_relative[i] == 1: <-- treats use_flag_relative as a bitset
338
+ // args[i] = func(args[i], i - begin, true)
339
+ // args[i] = func(args[i], i - begin)
340
+ void foreachTensorInplaceWithFlag(std::vector<IValue>& args, int64_t begin, int64_t end,
341
+ const std::bitset<64> use_flag_relative, const std::function<Tensor(const Tensor&, bool)>& func);
342
+
343
+ std::vector<int64_t> findUnwrappedInputs(std::vector<IValue>& args, int64_t begin, int64_t end);
344
+
345
+ DispatchKeySet keysToExcludeWhenEnteringDynamicLayer(TransformType key);
346
+
347
+ void setup_dispatch_key_tls(TransformType key, DispatchKeySet include);
348
+
349
+ void sanityCheckStack(const c10::OperatorHandle& op, torch::jit::Stack* stack);
350
+
351
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <ATen/functorch/Macros.h>
10
+ #include <ATen/functorch/BatchedTensorImpl.h>
11
+
12
+ namespace at::functorch {
13
+
14
+ // This files contains the legacy (now-deprecated) batching rule API.
15
+ // Please try to use the new-style batching rule API (see writing_batch_rules.md)
16
+
17
+ // This file contains abstractions used for transforming *logical* vmap arguments
18
+ // into *physical* arguments. (Keep reading for definitions of these terms).
19
+
20
+ // NOTE: [Logical vs physical args]
21
+ // Consider the following vmap.
22
+ // vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4))
23
+ // This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4],
24
+ // with batch dims 0 and 2:
25
+ // BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)])
26
+ //
27
+ // We say the *logical* view of the tensor has size [3] -- tensors inside
28
+ // `func` appear to have size [3].
29
+ // However, the *physical* underlying tensor (the one passed to vmap) has size
30
+ // [2, 3, 4].
31
+ //
32
+ // This notion of logical vs physical also extends to non-tensor arguments.
33
+ // Consider the previous tensor; let's assume the user called
34
+ // `torch.sum(tensor, dim=0)` inside of `func`. Then the logical
35
+ // dimension they are reducing over is dim 0 but the physical dim is dim 1
36
+ // (the first non-batch dimension)
37
+
38
+ // Forward declared; see NOTE: [What is a VmapPhysicalView?]
39
+ struct VmapPhysicalView;
40
+
41
+ // Most PyTorch operators take 4 or fewer inputs.
42
+ constexpr int64_t kVmapTransformStaticInputSize = 4;
43
+ using VmapPhysicalViewVec = SmallVector<VmapPhysicalView, kVmapTransformStaticInputSize>;
44
+
45
+ // Pytorch generally advertises good performance for <= 5 dims.
46
+ // (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap
47
+ // dimensions to get 8. Adjust this number as necessary
48
+ constexpr int64_t kVmapStaticDimVecSize = 8;
49
+ using VmapDimVector = SmallVector<int64_t, kVmapStaticDimVecSize>;
50
+ using VmapSymDimVector = SmallVector<c10::SymInt, kVmapStaticDimVecSize>;
51
+
52
+ // NOTE: [What is an VmapTransform?]
53
+ // An *VmapTransform* converts logical views of tensors to physical views.
54
+ //
55
+ // Batching rules use VmapTransforms to convert logical arguments to
56
+ // physical arguments, then call one or more at:: operator that handles the
57
+ // physical arguments, and then converts the physical result back to a logical
58
+ // argument.
59
+
60
+ // VmapTransform for operators that take tensors with multiple batch dims.
61
+ // Given one or more logical views on Tensors, `logicalToPhysical`
62
+ // permutes all of the batch dims to the front of the tensor, aligns
63
+ // and expands the batch dims to match each other (according to their `level`),
64
+ // and returns a VmapPhysicalView on the tensor(s).
65
+ struct TORCH_API MultiBatchVmapTransform {
66
+ static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor);
67
+ static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors);
68
+ };
69
+
70
+ // VmapTransform for operators that broadcast all inputs.
71
+ // Given some logical views on Tensors, `logicalToPhysical`:
72
+ // - permutes all of the batch dims to the front of the tensors
73
+ // - aligns all the batch dims to the collective levels of all of the tensors.
74
+ // If a tensor does not have a batch dim for a vmap level, then it receives
75
+ // a size-one dimension for said level.
76
+ // - aligns the non-batch dims to have the same dimensionality, adding extra
77
+ // size-1 dimensions in between the batch dimensions and the non-batch dimensions
78
+ // so that the batch dimensions are lined up from the right.
79
+ //
80
+ // For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch
81
+ // dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap tensors
82
+ // of size (B, 1, 2) and (B, 3, 2).
83
+ //
84
+ // Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns
85
+ // VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't
86
+ // actually *need* to return a tensor of size (1, 2) for the second tensor
87
+ // because the broadcasting operation takes care of that for us, but we do
88
+ // it anyways to keep things simple.
89
+ struct TORCH_API BroadcastingVmapTransform {
90
+ static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors);
91
+ };
92
+
93
+ // Forward declared, if you're reading this file head to toe, don't worry about
94
+ // it yet.
95
+ struct VmapPhysicalToLogicalMap;
96
+
97
+ // NOTE: [What is a VmapPhysicalView?]
98
+ // VmapPhysicalView represents a physical view on a Tensor.
99
+ //
100
+ // One can use it to further convert logical dimension indices, logical shapes,
101
+ // and more to their physical variants, or convert a new (physical) tensor into
102
+ // a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented).
103
+ //
104
+ // VmapPhysicalView stores a physical tensor with all of its batch dimensions at
105
+ // the front and some levels that correspond to said batch dimensions.
106
+ //
107
+ // The levels bitset specifies which vmap levels correspond to the batch
108
+ // dimensions at the front of the tensor. In particular, the number of set bits
109
+ // corresponds to the number of batch dimensions on `tensor` and the rightmost
110
+ // bit of `levels` specifies the maximum number of nested vmaps we are in at
111
+ // this point in time.
112
+ // For example, given:
113
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3})
114
+ //
115
+ // Rightmost bit of `levels` is 3 indicating the number of nested vmaps less
116
+ // than or equal to 3.
117
+ // bitset: 010100
118
+ // ^
119
+ // |
120
+ // levels: 012345
121
+ struct TORCH_API VmapPhysicalView {
122
+ VmapPhysicalView(Tensor&& tensor, std::bitset<kVmapNumLevels> levels)
123
+ : levels_(levels), tensor_(std::move(tensor)) {
124
+ // TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor));
125
+ }
126
+
127
+ Tensor& tensor() { return tensor_; }
128
+ const Tensor& tensor() const { return tensor_; }
129
+
130
+ // Maps logical dim indices to physical dim indices. Also does dim wrapping.
131
+ //
132
+ // For example, given:
133
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3})
134
+ //
135
+ // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}.
136
+ // This is because the size of levels tell us that the first two dimensions
137
+ // of `tensor_` are batch dimensions, so a logical dim of `n` is actually
138
+ // a physical dim of `n + 2`.
139
+ VmapDimVector getPhysicalDims(IntArrayRef logical_dims) const;
140
+ int64_t getPhysicalDim(int64_t logical_dim) const;
141
+
142
+ // Returns a VmapPhysicalToLogicalMap object. This can be used for
143
+ // mapping a physical tensor to a new logical tensor (BatchedTensor)
144
+ VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const;
145
+
146
+ // Maps a logical shape to a physical shape by pre-pending the batch
147
+ // sizes to the logical shape.
148
+ VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const;
149
+ SymDimVector getPhysicalShape(c10::SymIntArrayRef logical_shape) const;
150
+
151
+ int64_t numBatchDims() const;
152
+
153
+ private:
154
+ int64_t numLogicalDims() const;
155
+
156
+ std::bitset<kVmapNumLevels> levels_;
157
+ Tensor tensor_;
158
+ };
159
+
160
+ // Convenience struct used for mapping a physical tensor (a non-BatchedTensor)
161
+ // to a logical one (BatchedTensor). It holds some levels that are used to do the
162
+ // mapping and assumes that the batch dimensions in the physical tensor all
163
+ // occur at the front of the tensor.
164
+ struct TORCH_API VmapPhysicalToLogicalMap {
165
+ VmapPhysicalToLogicalMap(std::bitset<kVmapNumLevels> levels): levels_(levels) {}
166
+
167
+ // Maps a physical tensor to a new logical tensor (BatchedTensor).
168
+ // Assumes that all of the "batch dimensions" are at the front
169
+ // of the physical tensor. For example, given:
170
+ // - x = rank-4 Tensor with size 2, 3, 5, 7
171
+ // - levels = (2, 4)
172
+ // Returns:
173
+ // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)])
174
+ Tensor apply(const Tensor& physical_tensor) const;
175
+
176
+ // Given a vector of physical tensors,
177
+ // 1. maps each tensor to a new logical tensor. Assumes that all of the
178
+ // "batch dimensions" are at the front of the physical tensors.
179
+ // 2. stores the new logical tensors back into the passed-in vector. This is
180
+ // to avoid additional dynamic allocations.
181
+ void applyInplace(std::vector<Tensor>& physical_tensors) const;
182
+
183
+ std::bitset<kVmapNumLevels> levels_;
184
+ };
185
+
186
+
187
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/Macros.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+
3
+ #define SINGLE_ARG(...) __VA_ARGS__
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/PlumbingHelper.h ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #pragma once
7
+ #include <ATen/Tensor.h>
8
+ #include <ATen/functorch/BatchedTensorImpl.h>
9
+ #include <ATen/functorch/DynamicLayer.h>
10
+
11
+ // NOTE: [vmap plumbing]
12
+ //
13
+ // Here's how "batching rules" work.
14
+ // - we register kernels to the Batched key
15
+ // - these kernels have the same signatures as the original operators.
16
+ // For example, at::sin(Tensor self) accepts a Tensor, and the batched kernel
17
+ // must also accept a Tensor
18
+ // - However, it is more natural for users to write a batching rule like the
19
+ // following: sin_batch_rule(Tensor self, std::optional<int> self_bdim)
20
+ // - There is some codegenerated layer (the "plumbing") that wraps the user
21
+ // defined batching rule (e.g. sin_batch_rule) in a kernel that can be
22
+ // registered to the Batched key.
23
+ //
24
+ // The plumbing is responsible for wrapping a batching rule into a form that may
25
+ // be registered as the kernel for the batched key.
26
+
27
+ namespace at::functorch {
28
+
29
+ void vmap_check_escaped(const std::optional<DynamicLayer> &layer, const char* what);
30
+
31
+ // Create a BatchedTensor given a tensor, bdim, and level
32
+ TORCH_API Tensor makeBatched(Tensor tensor, std::optional<int64_t> bdim, int64_t level);
33
+
34
+ // Given a Tensor that may or may not be a BatchedTensor, unwrap it.
35
+ // If `tensor` is not a BatchedTensor, or is a BatchedTensor but the level
36
+ // doesn't match, then this returns (tensor, std::nullopt).
37
+ // Otherwise, it returns (unwrap(tensor), bdim).
38
+ TORCH_API std::tuple<Tensor, std::optional<int64_t>> unwrapTensorAtLevel(const Tensor& tensor, int64_t level);
39
+
40
+ // Creates a vector of BatchedTensor
41
+ TORCH_API std::vector<Tensor> makeBatchedVector(std::vector<Tensor> tensors, std::optional<int64_t> bdim, int64_t level);
42
+
43
+ // Returns True if ANY tensor in tensors is batched at level
44
+ TORCH_API bool isBatchedAtLevel(ITensorListRef tensors, int64_t level);
45
+ TORCH_API bool isBatchedAtLevel(const c10::List<std::optional<Tensor>>& maybe_tensors, int64_t level);
46
+ TORCH_API bool isBatchedAtLevel(const Tensor& tensor, int64_t level);
47
+ TORCH_API bool isBatchedAtLevel(const std::optional<Tensor>& maybe_tensor, int64_t level);
48
+
49
+ // Convenience helper. Returns true if any tensor is batched at level
50
+ TORCH_API bool areAnyBatchedAtLevel(ArrayRef<std::optional<Tensor>> maybe_tensors, int64_t level);
51
+
52
+ inline bool ivalueParticipatesInCurrentLevel(const IValue& ivalue) {
53
+ if (ivalue.isTensor()) {
54
+ auto maybe_level = maybeCurrentDynamicLayer();
55
+ TORCH_INTERNAL_ASSERT(maybe_level.has_value());
56
+ auto current_level = maybe_level->layerId();
57
+ return isBatchedAtLevel(ivalue.toTensor(), current_level);
58
+ }
59
+ // TODO: should really check this
60
+ return false;
61
+ }
62
+
63
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/TensorWrapper.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <ATen/functorch/Macros.h>
10
+ #include <ATen/Tensor.h>
11
+ #include <ATen/functorch/Interpreter.h>
12
+
13
+ namespace at::functorch {
14
+
15
+ // NOTE: [functorch's TensorWrapper]
16
+ //
17
+ // Taking better suggestions for a name. TensorWrapper is the wrapper Tensor
18
+ // Subclass for functorch's grad-based transforms (grad, vjp, jvp). It is
19
+ // analogous to how vmap uses BatchedTensor as the wrapper Tensor subclass.
20
+ //
21
+ // If you're familiar with the Tensor-Variable merge, TensorWrapper is effectively
22
+ // another Variable.
23
+ //
24
+ // Consider grad(grad(torch.sin))(x). This wraps `x` as TensorWrapper(TensorWrapper(x)).
25
+ // The reason why is so that each TensorWrapper can hold its own AutogradMeta and
26
+ // participate in a **separate** autograd graph.
27
+ //
28
+ // There are alternative designs we could have chosen (e.g. each grad transform
29
+ // stores a weak map of Tensor -> AutogradMeta); the benefit of the TensorWrapper
30
+ // design is that we can re-use existing VariableType kernels (i.e. Autograd kernels)
31
+ // without much modification. Since a TensorWrapper looks like a regular Tensor,
32
+ // the VariableType kernel can pull out the AutogradMeta struct from where it
33
+ // expects and extend the autograd graph
34
+
35
+ struct TORCH_API TensorWrapper : public c10::TensorImpl {
36
+ explicit TensorWrapper(
37
+ c10::DispatchKeySet key_set,
38
+ Tensor value,
39
+ int64_t level,
40
+ std::shared_ptr<bool> is_alive,
41
+ bool is_immutable = false, // if true, this came from an operation that aliases an immutable tensor
42
+ bool use_value_sizes_strides = true);
43
+
44
+ void refreshMetadata();
45
+
46
+ const Tensor& value() const {
47
+ return value_;
48
+ }
49
+ std::optional<int64_t> level() const {
50
+ if (is_alive()) {
51
+ return level_;
52
+ }
53
+ return {};
54
+ }
55
+ bool is_immutable() const {
56
+ return is_immutable_;
57
+ }
58
+ bool is_alive() const;
59
+
60
+ // Overrides necessary for autograd
61
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
62
+ const c10::VariableVersion& version_counter,
63
+ bool allow_tensor_metadata_change) const override;
64
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
65
+ c10::VariableVersion&& version_counter,
66
+ bool allow_tensor_metadata_change) const override;
67
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
68
+
69
+ private:
70
+ const char* tensorimpl_type_name() const override;
71
+ Tensor value_;
72
+ int64_t level_;
73
+ bool is_immutable_;
74
+
75
+ // TensorWrapper receives a boolean flag on whether or not the Grad Interpreter
76
+ // that created it is still alive or not.
77
+ // If the Grad Interpreter is no longer alive then it attempts to behave like
78
+ // a regular Tensor.
79
+ //
80
+ // When we exit the level, this wrapper may be marked as "not alive".
81
+ // Wrappers that are not alive:
82
+ // 1) May still have autograd metadata on them
83
+ // 2) Forward dispatches to the underlying value()
84
+ std::shared_ptr<bool> is_alive_;
85
+ };
86
+
87
+ // There are two variants of makeTensorWrapper: one that accepts a level
88
+ // and one that accepts an Interpreter.
89
+ //
90
+ // The one that accepts a level tries to automatically get the life handle from the
91
+ // interpreter on the DynamicLayerStack.
92
+ // It needs to be used with caution: if the interpreter is not on the
93
+ // DynamicLayerStack, then we won't be able to find the life handle.
94
+ //
95
+ // In practice this isn't a problem: when we're constructing TensorWrapper in
96
+ // Python, the corresponding interpreter is on the stack.
97
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, int64_t level, bool is_immutable=false);
98
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, const Interpreter& interpreter, bool is_immutable=false);
99
+ TORCH_API TensorWrapper* maybeGetTensorWrapper(const Tensor& tensor);
100
+ TORCH_API void dumpTensor(std::ostream & ss, const Tensor& tensor);
101
+ TORCH_API void dumpTensorCout(const Tensor& tensor);
102
+
103
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/functorch/VmapInterpreter.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/functorch/Interpreter.h>
3
+
4
+ namespace at::functorch {
5
+
6
+ // This is the interpreter that handles the functionalize() transform.
7
+ // See NOTE: [functorch interpreter stack] for more details.
8
+
9
+ struct VmapInterpreterPtr {
10
+ explicit VmapInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Vmap); }
11
+ TransformType key() const { return base_->key(); }
12
+ int64_t level() const { return base_->level(); }
13
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
14
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
15
+ c10::SymInt batchSize() const {
16
+ return std::get<VmapInterpreterMeta>(base_->meta()).batchSize_;
17
+ }
18
+ RandomnessType randomness() const {
19
+ return std::get<VmapInterpreterMeta>(base_->meta()).randomness_;
20
+ }
21
+ private:
22
+ const Interpreter* base_;
23
+ };
24
+
25
+ } // namespace at::functorch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/Exceptions.h>
4
+
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <c10/macros/Export.h>
9
+
10
+ namespace at { namespace native {
11
+
12
+ inline int dataSize(miopenDataType_t dataType)
13
+ {
14
+ switch (dataType) {
15
+ case miopenHalf: return 2;
16
+ case miopenFloat: return 4;
17
+ case miopenBFloat16: return 2;
18
+ default: return 8;
19
+ }
20
+ }
21
+
22
+ template <typename T, miopenStatus_t (*dtor)(T*)>
23
+ struct DescriptorDeleter {
24
+ void operator()(T* x) {
25
+ if (x != nullptr) {
26
+ MIOPEN_CHECK(dtor(x));
27
+ }
28
+ }
29
+ };
30
+
31
+ // A generic class for wrapping MIOpen descriptor types. All you need
32
+ // is to give the underlying type the Descriptor_t points to (usually,
33
+ // if it's miopenTensorDescriptor_t it points to miopenTensorStruct),
34
+ // the constructor and the destructor. Subclasses are responsible
35
+ // for defining a set() function to actually set the descriptor.
36
+ //
37
+ // Descriptors default construct to a nullptr, and have a descriptor
38
+ // initialized the first time you call set() or any other initializing
39
+ // function.
40
+ template <typename T, miopenStatus_t (*ctor)(T**), miopenStatus_t (*dtor)(T*)>
41
+ // NOLINTNEXTLINE(bugprone-exception-escape)
42
+ class TORCH_CUDA_CPP_API Descriptor {
43
+ public:
44
+ // Use desc() to access the underlying descriptor pointer in
45
+ // a read-only fashion. Most client code should use this.
46
+ // If the descriptor was never initialized, this will return
47
+ // nullptr.
48
+ T* desc() const { return desc_.get(); }
49
+ T* desc() { return desc_.get(); }
50
+
51
+ // Use mut_desc() to access the underlying descriptor pointer
52
+ // if you intend to modify what it points to (e.g., using
53
+ // miopenSetFooDescriptor). This will ensure that the descriptor
54
+ // is initialized. Code in this file will use this function.
55
+ T* mut_desc() { init(); return desc_.get(); }
56
+ protected:
57
+ void init() {
58
+ if (desc_ == nullptr) {
59
+ T* raw_desc = nullptr;
60
+ MIOPEN_CHECK(ctor(&raw_desc));
61
+ desc_.reset(raw_desc);
62
+ }
63
+ }
64
+ private:
65
+ std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_;
66
+ };
67
+
68
+ class TORCH_CUDA_CPP_API TensorDescriptor : public Descriptor<
69
+ miopenTensorDescriptor,
70
+ &miopenCreateTensorDescriptor,
71
+ &miopenDestroyTensorDescriptor> {
72
+ public:
73
+ TensorDescriptor() = default;
74
+ explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) {
75
+ set(t, pad);
76
+ }
77
+
78
+ void set(const at::Tensor &t, size_t pad = 0);
79
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0);
80
+
81
+ void print();
82
+
83
+ private:
84
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride) {
85
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, stride));
86
+ }
87
+ };
88
+
89
+ std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d);
90
+
91
+ class TORCH_CUDA_CPP_API FilterDescriptor : public Descriptor<
92
+ miopenTensorDescriptor,
93
+ &miopenCreateTensorDescriptor,
94
+ &miopenDestroyTensorDescriptor> {
95
+ public:
96
+ void set(const at::Tensor &t, int64_t pad = 0) {
97
+ set(t, at::MemoryFormat::Contiguous, pad);
98
+ }
99
+
100
+ void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0);
101
+
102
+ private:
103
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride) {
104
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, stride));
105
+ }
106
+ };
107
+
108
+ struct TORCH_CUDA_CPP_API ConvolutionDescriptor
109
+ : public Descriptor<
110
+ miopenConvolutionDescriptor,
111
+ &miopenCreateConvolutionDescriptor,
112
+ &miopenDestroyConvolutionDescriptor> {
113
+ void set(miopenDataType_t dataType, miopenConvolutionMode_t c_mode, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool benchmark, bool deterministic) {
114
+ MIOPEN_CHECK(miopenInitConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, c_mode));
115
+ MIOPEN_CHECK(miopenSetConvolutionGroupCount(mut_desc(), groups));
116
+ MIOPEN_CHECK(miopenSetConvolutionAttribute(mut_desc(), MIOPEN_CONVOLUTION_ATTRIB_DETERMINISTIC, deterministic ? 1 : 0));
117
+ if (benchmark) {
118
+ MIOPEN_CHECK(miopenSetConvolutionFindMode(mut_desc(), miopenConvolutionFindModeNormal));
119
+ }
120
+ }
121
+ };
122
+
123
+ // NOLINTNEXTLINE(bugprone-exception-escape)
124
+ struct TORCH_CUDA_CPP_API DropoutDescriptor
125
+ : public Descriptor<
126
+ miopenDropoutDescriptor,
127
+ &miopenCreateDropoutDescriptor,
128
+ &miopenDestroyDropoutDescriptor> {
129
+ void set(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
130
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
131
+ MIOPEN_CHECK(miopenSetDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
132
+ }
133
+
134
+ void restore(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
135
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
136
+ MIOPEN_CHECK(miopenRestoreDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
137
+ }
138
+ };
139
+
140
+ struct TORCH_CUDA_CPP_API RNNDescriptor
141
+ : public Descriptor<miopenRNNDescriptor,
142
+ &miopenCreateRNNDescriptor,
143
+ &miopenDestroyRNNDescriptor>
144
+ {
145
+ void set(int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, miopenRNNMode_t rnn_mode,
146
+ miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
147
+ MIOPEN_CHECK(miopenSetRNNDescriptor(mut_desc(), hidden_size, num_layers, input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
148
+ }
149
+
150
+ void setWithDropout(DropoutDescriptor& dropout_desc, int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction,
151
+ miopenRNNMode_t rnn_mode, miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
152
+ MIOPEN_CHECK(miopenSetRNNDescriptor_V2(mut_desc(), hidden_size, num_layers, dropout_desc.mut_desc(), input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
153
+ }
154
+ };
155
+
156
+ union Constant
157
+ {
158
+ float f;
159
+ double d;
160
+ Constant(miopenDataType_t dataType, double value) {
161
+ if (dataType == miopenHalf || dataType == miopenFloat || dataType == miopenBFloat16) {
162
+ f = static_cast<float>(value);
163
+ } else {
164
+ d = value;
165
+ }
166
+ }
167
+ };
168
+
169
+ }} // namespace
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+ #include <string>
5
+ #include <stdexcept>
6
+ #include <sstream>
7
+
8
+ namespace at { namespace native {
9
+
10
+ class miopen_exception : public std::runtime_error {
11
+ public:
12
+ miopenStatus_t status;
13
+ miopen_exception(miopenStatus_t status, const char* msg)
14
+ : std::runtime_error(msg)
15
+ , status(status) {}
16
+ miopen_exception(miopenStatus_t status, const std::string& msg)
17
+ : std::runtime_error(msg)
18
+ , status(status) {}
19
+ };
20
+
21
+ inline void MIOPEN_CHECK(miopenStatus_t status)
22
+ {
23
+ if (status != miopenStatusSuccess) {
24
+ if (status == miopenStatusNotImplemented) {
25
+ throw miopen_exception(status, std::string(miopenGetErrorString(status)) +
26
+ ". This error may appear if you passed in a non-contiguous input.");
27
+ }
28
+ throw miopen_exception(status, miopenGetErrorString(status));
29
+ }
30
+ }
31
+
32
+ inline void HIP_CHECK(hipError_t error)
33
+ {
34
+ if (error != hipSuccess) {
35
+ std::string msg("HIP error: ");
36
+ msg += hipGetErrorString(error);
37
+ throw std::runtime_error(msg);
38
+ }
39
+ }
40
+
41
+ }} // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+ #include <c10/macros/Export.h>
5
+
6
+ namespace at::native {
7
+
8
+ TORCH_CUDA_CPP_API miopenHandle_t getMiopenHandle();
9
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <c10/macros/Export.h>
6
+
7
+ namespace at::native {
8
+
9
+ TORCH_CUDA_CPP_API miopenDataType_t getMiopenDataType(const at::Tensor& tensor);
10
+
11
+ int64_t miopen_version();
12
+
13
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <ATen/miopen/Handle.h>
6
+
7
+ namespace at { namespace native {
8
+
9
+ // This function makes tensors which have zero stride contiguous, by
10
+ // setting the strides to 1.
11
+ inline Tensor contiguousIfZeroInStrides(const Tensor& t) {
12
+ for (auto s : t.strides()) {
13
+ if (s == 0) return t.contiguous();
14
+ }
15
+ return t;
16
+ }
17
+
18
+ }}
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <miopen/miopen.h>
4
+ #include <miopen/version.h>
5
+
6
+ #if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4)
7
+ // miopen 3.4 moved find mode from private header to public header
8
+ #else
9
+ // from miopen_internal.h
10
+ extern "C" {
11
+
12
+ typedef enum
13
+ {
14
+ miopenConvolutionFindModeNormal = 1, /*!< Normal mode */
15
+ } miopenConvolutionFindMode_t;
16
+
17
+ miopenStatus_t miopenSetConvolutionFindMode(
18
+ miopenConvolutionDescriptor_t convDesc,
19
+ miopenConvolutionFindMode_t findMode);
20
+ }
21
+ #endif
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+ #include <ATen/core/TensorBase.h>
5
+
6
+ namespace at::detail {
7
+
8
+ C10_EXPORT TensorBase empty_mps(
9
+ IntArrayRef size,
10
+ std::optional<ScalarType> dtype_opt,
11
+ std::optional<Layout> layout_opt,
12
+ std::optional<Device> device_opt,
13
+ std::optional<bool> pin_memory_opt,
14
+ std::optional<c10::MemoryFormat> memory_format_opt);
15
+ C10_EXPORT TensorBase empty_mps(IntArrayRef size, const TensorOptions& options);
16
+
17
+ C10_EXPORT TensorBase empty_strided_mps(
18
+ IntArrayRef size,
19
+ IntArrayRef stride,
20
+ ScalarType dtype,
21
+ std::optional<Device> device_opt);
22
+
23
+ C10_EXPORT TensorBase empty_strided_mps(
24
+ IntArrayRef size,
25
+ IntArrayRef stride,
26
+ const TensorOptions& options);
27
+
28
+ } // namespace at::detail
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/native/Gelu.h>
5
+ #include <c10/util/Exception.h>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ struct TensorIterator;
13
+ struct TensorIteratorBase;
14
+ class TensorBase;
15
+ }
16
+
17
+ namespace at::native {
18
+
19
+ using structured_activation_fn = void (*)(TensorIteratorBase&);
20
+ using structured_activation_backward_fn = void (*)(TensorIteratorBase&);
21
+
22
+ using activation_fn = void (*)(TensorIterator&);
23
+ using activation_backward_fn = void (*)(TensorIterator&);
24
+ using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
25
+ using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
26
+ using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
27
+ using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&);
28
+ using hardsigmoid_fn = void(*)(TensorIteratorBase&);
29
+ using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&);
30
+ using hardswish_fn = void(*)(TensorIterator&);
31
+ using hardswish_backward_fn = void(*)(TensorIterator&);
32
+ using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
33
+ using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
34
+ using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
35
+ using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&);
36
+ using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool);
37
+ using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
38
+ using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
39
+ using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&);
40
+ using gelu_fn = void (*)(TensorIteratorBase&, GeluType);
41
+ using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType);
42
+ using glu_jvp_fn = void (*)(TensorIteratorBase&);
43
+
44
+ DECLARE_DISPATCH(elu_fn, elu_stub)
45
+ DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub)
46
+ DECLARE_DISPATCH(softplus_fn, softplus_stub)
47
+ DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub)
48
+ DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub)
49
+ DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub)
50
+ DECLARE_DISPATCH(threshold_fn, threshold_stub)
51
+ DECLARE_DISPATCH(gelu_fn, GeluKernel)
52
+ DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel)
53
+ DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub)
54
+ DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub)
55
+ DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub)
56
+ DECLARE_DISPATCH(hardswish_fn, hardswish_stub)
57
+ DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub)
58
+ DECLARE_DISPATCH(shrink_fn, hardshrink_stub)
59
+ DECLARE_DISPATCH(softshrink_fn, softshrink_stub)
60
+ DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub)
61
+ DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub)
62
+ DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub)
63
+ DECLARE_DISPATCH(structured_activation_fn, glu_stub)
64
+ DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub)
65
+ DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub)
66
+ DECLARE_DISPATCH(structured_activation_fn, silu_stub)
67
+ DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub)
68
+ DECLARE_DISPATCH(structured_activation_fn, mish_stub)
69
+ DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub)
70
+ DECLARE_DISPATCH(activation_fn, prelu_stub)
71
+ DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub)
72
+
73
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/ArrayRef.h>
6
+ #include <c10/util/irange.h>
7
+ #include <cmath>
8
+
9
+ namespace at::native {
10
+
11
+ using adaptive_avg_pooling2d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
12
+ using adaptive_avg_pooling2d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
13
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_fn, adaptive_avg_pool2d_kernel)
14
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_backward_fn, adaptive_avg_pool2d_backward_kernel)
15
+
16
+ using adaptive_max_pooling2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
17
+ using adaptive_max_pooling2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
18
+ DECLARE_DISPATCH(adaptive_max_pooling2d_fn, adaptive_max_pool2d_kernel)
19
+ DECLARE_DISPATCH(adaptive_max_pooling2d_backward_fn, adaptive_max_pool2d_backward_kernel)
20
+
21
+ using adaptive_avg_pooling3d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
22
+ using adaptive_avg_pooling3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
23
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_fn, adaptive_avg_pool3d_kernel)
24
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_backward_fn, adaptive_avg_pool3d_backward_kernel)
25
+
26
+ using adaptive_max_pooling3d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
27
+ using adaptive_max_pooling3d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
28
+ DECLARE_DISPATCH(adaptive_max_pooling3d_fn, adaptive_max_pool3d_kernel)
29
+ DECLARE_DISPATCH(adaptive_max_pooling3d_backward_fn, adaptive_max_pool3d_backward_kernel)
30
+
31
+ inline int64_t start_index(int64_t a, int64_t b, int64_t c) {
32
+ return (a / b) * c + ((a % b) * c) / b;
33
+ }
34
+
35
+ inline int64_t end_index(int64_t a, int64_t b, int64_t c) {
36
+ return 1 + ((a + 1) * c - 1) / b;
37
+ }
38
+
39
+ inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) {
40
+ int64_t ndim = gradOutput_.ndimension();
41
+ for (const auto i : c10::irange(1, ndim)) {
42
+ TORCH_CHECK(gradOutput_.size(i) > 0,
43
+ arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, "
44
+ "but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i,
45
+ " being empty");
46
+ }
47
+ }
48
+
49
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <optional>
4
+ #include <string_view>
5
+ #include <ATen/Config.h>
6
+ #include <ATen/native/DispatchStub.h>
7
+
8
+ // Forward declare TI
9
+ namespace at {
10
+ class Tensor;
11
+ struct TensorIterator;
12
+
13
+ namespace native {
14
+ enum class TransposeType;
15
+ }
16
+
17
+ }
18
+
19
+ namespace at::native {
20
+
21
+ enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
22
+
23
+ #if AT_BUILD_WITH_LAPACK()
24
+ // Define per-batch functions to be used in the implementation of batched
25
+ // linear algebra operations
26
+
27
+ template <class scalar_t>
28
+ void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
29
+
30
+ template <class scalar_t>
31
+ void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
32
+
33
+ template <class scalar_t, class value_t=scalar_t>
34
+ void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
35
+
36
+ template <class scalar_t>
37
+ void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
38
+
39
+ template <class scalar_t>
40
+ void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
41
+
42
+ template <class scalar_t>
43
+ void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
44
+
45
+ template <class scalar_t, class value_t = scalar_t>
46
+ void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
47
+
48
+ template <class scalar_t>
49
+ void lapackGels(char trans, int m, int n, int nrhs,
50
+ scalar_t *a, int lda, scalar_t *b, int ldb,
51
+ scalar_t *work, int lwork, int *info);
52
+
53
+ template <class scalar_t, class value_t = scalar_t>
54
+ void lapackGelsd(int m, int n, int nrhs,
55
+ scalar_t *a, int lda, scalar_t *b, int ldb,
56
+ value_t *s, value_t rcond, int *rank,
57
+ scalar_t* work, int lwork,
58
+ value_t *rwork, int* iwork, int *info);
59
+
60
+ template <class scalar_t, class value_t = scalar_t>
61
+ void lapackGelsy(int m, int n, int nrhs,
62
+ scalar_t *a, int lda, scalar_t *b, int ldb,
63
+ int *jpvt, value_t rcond, int *rank,
64
+ scalar_t *work, int lwork, value_t* rwork, int *info);
65
+
66
+ template <class scalar_t, class value_t = scalar_t>
67
+ void lapackGelss(int m, int n, int nrhs,
68
+ scalar_t *a, int lda, scalar_t *b, int ldb,
69
+ value_t *s, value_t rcond, int *rank,
70
+ scalar_t *work, int lwork,
71
+ value_t *rwork, int *info);
72
+
73
+ template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
74
+ struct lapackLstsq_impl;
75
+
76
+ template <class scalar_t, class value_t>
77
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
78
+ static void call(
79
+ char trans, int m, int n, int nrhs,
80
+ scalar_t *a, int lda, scalar_t *b, int ldb,
81
+ scalar_t *work, int lwork, int *info, // Gels flavor
82
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
83
+ value_t *s, // Gelss flavor
84
+ int *iwork // Gelsd flavor
85
+ ) {
86
+ lapackGels<scalar_t>(
87
+ trans, m, n, nrhs,
88
+ a, lda, b, ldb,
89
+ work, lwork, info);
90
+ }
91
+ };
92
+
93
+ template <class scalar_t, class value_t>
94
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
95
+ static void call(
96
+ char trans, int m, int n, int nrhs,
97
+ scalar_t *a, int lda, scalar_t *b, int ldb,
98
+ scalar_t *work, int lwork, int *info, // Gels flavor
99
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
100
+ value_t *s, // Gelss flavor
101
+ int *iwork // Gelsd flavor
102
+ ) {
103
+ lapackGelsy<scalar_t, value_t>(
104
+ m, n, nrhs,
105
+ a, lda, b, ldb,
106
+ jpvt, rcond, rank,
107
+ work, lwork, rwork, info);
108
+ }
109
+ };
110
+
111
+ template <class scalar_t, class value_t>
112
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
113
+ static void call(
114
+ char trans, int m, int n, int nrhs,
115
+ scalar_t *a, int lda, scalar_t *b, int ldb,
116
+ scalar_t *work, int lwork, int *info, // Gels flavor
117
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
118
+ value_t *s, // Gelss flavor
119
+ int *iwork // Gelsd flavor
120
+ ) {
121
+ lapackGelsd<scalar_t, value_t>(
122
+ m, n, nrhs,
123
+ a, lda, b, ldb,
124
+ s, rcond, rank,
125
+ work, lwork,
126
+ rwork, iwork, info);
127
+ }
128
+ };
129
+
130
+ template <class scalar_t, class value_t>
131
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
132
+ static void call(
133
+ char trans, int m, int n, int nrhs,
134
+ scalar_t *a, int lda, scalar_t *b, int ldb,
135
+ scalar_t *work, int lwork, int *info, // Gels flavor
136
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
137
+ value_t *s, // Gelss flavor
138
+ int *iwork // Gelsd flavor
139
+ ) {
140
+ lapackGelss<scalar_t, value_t>(
141
+ m, n, nrhs,
142
+ a, lda, b, ldb,
143
+ s, rcond, rank,
144
+ work, lwork,
145
+ rwork, info);
146
+ }
147
+ };
148
+
149
+ template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
150
+ void lapackLstsq(
151
+ char trans, int m, int n, int nrhs,
152
+ scalar_t *a, int lda, scalar_t *b, int ldb,
153
+ scalar_t *work, int lwork, int *info, // Gels flavor
154
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
155
+ value_t *s, // Gelss flavor
156
+ int *iwork // Gelsd flavor
157
+ ) {
158
+ lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
159
+ trans, m, n, nrhs,
160
+ a, lda, b, ldb,
161
+ work, lwork, info,
162
+ jpvt, rcond, rank, rwork,
163
+ s,
164
+ iwork);
165
+ }
166
+
167
+ template <class scalar_t>
168
+ void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
169
+
170
+ template <class scalar_t>
171
+ void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
172
+
173
+ template <class scalar_t>
174
+ void lapackLdlHermitian(
175
+ char uplo,
176
+ int n,
177
+ scalar_t* a,
178
+ int lda,
179
+ int* ipiv,
180
+ scalar_t* work,
181
+ int lwork,
182
+ int* info);
183
+
184
+ template <class scalar_t>
185
+ void lapackLdlSymmetric(
186
+ char uplo,
187
+ int n,
188
+ scalar_t* a,
189
+ int lda,
190
+ int* ipiv,
191
+ scalar_t* work,
192
+ int lwork,
193
+ int* info);
194
+
195
+ template <class scalar_t>
196
+ void lapackLdlSolveHermitian(
197
+ char uplo,
198
+ int n,
199
+ int nrhs,
200
+ scalar_t* a,
201
+ int lda,
202
+ int* ipiv,
203
+ scalar_t* b,
204
+ int ldb,
205
+ int* info);
206
+
207
+ template <class scalar_t>
208
+ void lapackLdlSolveSymmetric(
209
+ char uplo,
210
+ int n,
211
+ int nrhs,
212
+ scalar_t* a,
213
+ int lda,
214
+ int* ipiv,
215
+ scalar_t* b,
216
+ int ldb,
217
+ int* info);
218
+
219
+ template<class scalar_t, class value_t=scalar_t>
220
+ void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
221
+ #endif
222
+
223
+ #if AT_BUILD_WITH_BLAS()
224
+ template <class scalar_t>
225
+ void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
226
+ #endif
227
+
228
+ using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
229
+ DECLARE_DISPATCH(cholesky_fn, cholesky_stub)
230
+
231
+ using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
232
+
233
+ DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub)
234
+
235
+ using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
236
+
237
+ DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub)
238
+
239
+ using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
240
+ DECLARE_DISPATCH(geqrf_fn, geqrf_stub)
241
+
242
+ using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
243
+ DECLARE_DISPATCH(orgqr_fn, orgqr_stub)
244
+
245
+ using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
246
+ DECLARE_DISPATCH(ormqr_fn, ormqr_stub)
247
+
248
+ using linalg_eigh_fn = void (*)(
249
+ const Tensor& /*eigenvalues*/,
250
+ const Tensor& /*eigenvectors*/,
251
+ const Tensor& /*infos*/,
252
+ bool /*upper*/,
253
+ bool /*compute_eigenvectors*/);
254
+ DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub)
255
+
256
+ using lstsq_fn = void (*)(
257
+ const Tensor& /*a*/,
258
+ Tensor& /*b*/,
259
+ Tensor& /*rank*/,
260
+ Tensor& /*singular_values*/,
261
+ Tensor& /*infos*/,
262
+ double /*rcond*/,
263
+ std::string /*driver_name*/);
264
+ DECLARE_DISPATCH(lstsq_fn, lstsq_stub)
265
+
266
+ using triangular_solve_fn = void (*)(
267
+ const Tensor& /*A*/,
268
+ const Tensor& /*B*/,
269
+ bool /*left*/,
270
+ bool /*upper*/,
271
+ TransposeType /*transpose*/,
272
+ bool /*unitriangular*/);
273
+ DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub)
274
+
275
+ using lu_factor_fn = void (*)(
276
+ const Tensor& /*input*/,
277
+ const Tensor& /*pivots*/,
278
+ const Tensor& /*infos*/,
279
+ bool /*compute_pivots*/);
280
+ DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub)
281
+
282
+ using unpack_pivots_fn = void(*)(
283
+ TensorIterator& iter,
284
+ const int64_t dim_size,
285
+ const int64_t max_pivot);
286
+ DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub)
287
+
288
+ using lu_solve_fn = void (*)(
289
+ const Tensor& /*LU*/,
290
+ const Tensor& /*pivots*/,
291
+ const Tensor& /*B*/,
292
+ TransposeType /*trans*/);
293
+ DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub)
294
+
295
+ using ldl_factor_fn = void (*)(
296
+ const Tensor& /*LD*/,
297
+ const Tensor& /*pivots*/,
298
+ const Tensor& /*info*/,
299
+ bool /*upper*/,
300
+ bool /*hermitian*/);
301
+ DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub)
302
+
303
+ using svd_fn = void (*)(
304
+ const Tensor& /*A*/,
305
+ const bool /*full_matrices*/,
306
+ const bool /*compute_uv*/,
307
+ const std::optional<std::string_view>& /*driver*/,
308
+ const Tensor& /*U*/,
309
+ const Tensor& /*S*/,
310
+ const Tensor& /*Vh*/,
311
+ const Tensor& /*info*/);
312
+ DECLARE_DISPATCH(svd_fn, svd_stub)
313
+
314
+ using ldl_solve_fn = void (*)(
315
+ const Tensor& /*LD*/,
316
+ const Tensor& /*pivots*/,
317
+ const Tensor& /*result*/,
318
+ bool /*upper*/,
319
+ bool /*hermitian*/);
320
+ DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub)
321
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/TypeProperties.h>
5
+ #include <ATen/ScalarOps.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/NativeFunctions.h>
9
+ #else
10
+ #include <ATen/ops/result_type.h>
11
+ #endif
12
+
13
+ namespace at::native {
14
+
15
+ // original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to
16
+ // the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not
17
+ // match, will change them to be a common super type so comparisons are done between the same types.
18
+ // For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the
19
+ // corresponding raw_* version should be used since it was already contiguous of the right type.
20
+ inline void searchsorted_maybe_trim_input_tensors(
21
+ Tensor& trimmed_input,
22
+ Tensor& trimmed_boundaries,
23
+ Tensor& trimmed_sorter,
24
+ const Tensor& raw_input,
25
+ const Tensor& raw_boundaries,
26
+ const Tensor& raw_sorter) {
27
+ bool in_is_contiguous = raw_input.is_contiguous();
28
+ bool bd_is_contiguous = raw_boundaries.is_contiguous();
29
+ bool sort_is_contiguous = raw_sorter.is_contiguous();
30
+
31
+ if (!in_is_contiguous) {
32
+ TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due "
33
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value "
34
+ "tensor if possible. This message will only appear once per program.");
35
+ trimmed_input = raw_input.contiguous();
36
+ }
37
+ if (!bd_is_contiguous) {
38
+ TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due "
39
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary "
40
+ "tensor if possible. This message will only appear once per program.");
41
+ trimmed_boundaries = raw_boundaries.contiguous();
42
+ }
43
+ if (!sort_is_contiguous) {
44
+ TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due "
45
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter "
46
+ "tensor if possible. This message will only appear once per program.");
47
+ trimmed_sorter = raw_sorter.contiguous();
48
+ }
49
+ if (raw_input.dtype() != raw_boundaries.dtype()) {
50
+ at::native::ResultTypeState state = {};
51
+ state = at::native::update_result_type_state(raw_boundaries, state);
52
+ state = at::native::update_result_type_state(raw_input, state);
53
+ ScalarType common_stype = at::native::result_type(state);
54
+
55
+ TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined);
56
+ if (common_stype != raw_input.scalar_type()) {
57
+ trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype);
58
+ }
59
+ if (common_stype != raw_boundaries.scalar_type()) {
60
+ trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype);
61
+ }
62
+ }
63
+ }
64
+
65
+ /* unused but needed for internal jagged tensor class */
66
+ inline void searchsorted_maybe_trim_input_tensors(
67
+ Tensor& trimmed_input,
68
+ Tensor& trimmed_boundaries,
69
+ const Tensor& raw_input,
70
+ const Tensor& raw_boundaries) {
71
+ Tensor trimmed_sorter;
72
+ Tensor raw_sorter;
73
+ return searchsorted_maybe_trim_input_tensors(
74
+ trimmed_input,
75
+ trimmed_boundaries,
76
+ trimmed_sorter,
77
+ raw_input,
78
+ raw_boundaries,
79
+ raw_sorter);
80
+ }
81
+
82
+ inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) {
83
+ if (boundaries.dim() != input.dim()) {
84
+ return false;
85
+ }
86
+ const auto& dims_bd = boundaries.sizes();
87
+ const auto& dims_in = input.sizes();
88
+ for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) {
89
+ if (dims_bd[dim] != dims_in[dim]) {
90
+ return false;
91
+ }
92
+ }
93
+ return true;
94
+ }
95
+
96
+ inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) {
97
+ auto tensor = c10::scalar_to_tensor(scalar, device);
98
+ // This is to adopt the scalar promotion rules defined in native/TypeProperties.h
99
+ // So we have the same type promotion rules as binary operations.
100
+ tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
101
+ return tensor;
102
+ }
103
+
104
+ inline void searchsorted_pre_check(
105
+ const Tensor& boundaries,
106
+ const Tensor& input,
107
+ const Tensor& output,
108
+ const bool out_int32,
109
+ const bool right,
110
+ const std::optional<std::string_view> side_opt,
111
+ const Tensor& sorter) {
112
+ if (side_opt) {
113
+ const std::string_view side = *side_opt;
114
+ TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ",
115
+ "got ", side);
116
+
117
+ // assume the user has not explicitly set (right=False, side="right")
118
+ TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side "
119
+ "of ", side, " while right was True");
120
+ }
121
+
122
+ TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ",
123
+ "should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ",
124
+ "tensor device type ", input.device());
125
+
126
+ if (sorter.defined()) {
127
+ TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ",
128
+ "have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ",
129
+ "device type ", boundaries.device());
130
+
131
+ TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same "
132
+ "size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes());
133
+
134
+ TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ",
135
+ "dtype but got dtype ", sorter.scalar_type());
136
+
137
+ if (sorter.numel() > 0) {
138
+ auto minmax = sorter.aminmax();
139
+ int64_t vmin = std::get<0>(minmax).item().toLong();
140
+ int64_t vmax = std::get<1>(minmax).item().toLong();
141
+ TORCH_CHECK(vmin >= 0 && vmax < sorter.sizes().back(), "torch.searchsorted(): sorter index out of range");
142
+ }
143
+ }
144
+
145
+ TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1),
146
+ "torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ",
147
+ "boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(",
148
+ input.numel(), ")");
149
+
150
+ TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ",
151
+ "got 0 dimension");
152
+
153
+ TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input),
154
+ "torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ",
155
+ "and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ",
156
+ input.sizes());
157
+
158
+ ScalarType output_dtype = output.scalar_type();
159
+ TORCH_CHECK(
160
+ (output_dtype == ScalarType::Long && !out_int32) ||
161
+ (output_dtype == ScalarType::Int && out_int32),
162
+ "torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ",
163
+ "whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype,
164
+ " and out_int32 flag is ", (out_int32 ? "True" : "False"));
165
+
166
+ if (out_int32) {
167
+ TORCH_CHECK(boundaries.sizes().back() < INT_MAX,
168
+ "torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ",
169
+ boundaries.sizes().back());
170
+ }
171
+ }
172
+
173
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/OpMathType.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/native/TransposeType.h>
6
+ #include <c10/util/complex.h>
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/core/Scalar.h>
9
+
10
+
11
+ namespace at::native::cpublas {
12
+
13
+ namespace internal {
14
+ void normalize_last_dims(
15
+ TransposeType transa, TransposeType transb,
16
+ int64_t m, int64_t n, int64_t k,
17
+ int64_t *lda, int64_t *ldb, int64_t *ldc);
18
+ } // namespace internal
19
+
20
+ using gemm_fn = void(*)(
21
+ at::ScalarType type,
22
+ TransposeType transa, TransposeType transb,
23
+ int64_t m, int64_t n, int64_t k,
24
+ const Scalar& alpha,
25
+ const void *a, int64_t lda,
26
+ const void *b, int64_t ldb,
27
+ const Scalar& beta,
28
+ void *c, int64_t ldc);
29
+
30
+ DECLARE_DISPATCH(gemm_fn, gemm_stub)
31
+
32
+ using gemm_no_downcast_fn = void(*)(
33
+ at::ScalarType type,
34
+ TransposeType transa, TransposeType transb,
35
+ int64_t m, int64_t n, int64_t k,
36
+ const Scalar& alpha,
37
+ const void *a, int64_t lda,
38
+ const void *b, int64_t ldb,
39
+ const Scalar& beta,
40
+ void *c, int64_t ldc);
41
+
42
+ DECLARE_DISPATCH(gemm_no_downcast_fn, gemm_no_downcast_stub)
43
+
44
+ template <typename scalar_t>
45
+ void gemm(
46
+ TransposeType transa, TransposeType transb,
47
+ int64_t m, int64_t n, int64_t k,
48
+ at::opmath_type<scalar_t> alpha,
49
+ const scalar_t *a, int64_t lda,
50
+ const scalar_t *b, int64_t ldb,
51
+ at::opmath_type<scalar_t> beta,
52
+ scalar_t *c, int64_t ldc) {
53
+ internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc);
54
+ gemm_stub(
55
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
56
+ transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
57
+ }
58
+
59
+ void gemm(
60
+ TransposeType transa, TransposeType transb,
61
+ int64_t m, int64_t n, int64_t k,
62
+ double alpha,
63
+ const double *a, int64_t lda,
64
+ const double *b, int64_t ldb,
65
+ double beta,
66
+ double *c, int64_t ldc);
67
+
68
+ void gemm(
69
+ TransposeType transa, TransposeType transb,
70
+ int64_t m, int64_t n, int64_t k,
71
+ float alpha,
72
+ const float *a, int64_t lda,
73
+ const float *b, int64_t ldb,
74
+ float beta,
75
+ float *c, int64_t ldc);
76
+
77
+ void gemm(
78
+ TransposeType transa, TransposeType transb,
79
+ int64_t m, int64_t n, int64_t k,
80
+ float alpha,
81
+ const at::BFloat16 *a, int64_t lda,
82
+ const at::BFloat16 *b, int64_t ldb,
83
+ float beta,
84
+ at::BFloat16 *c, int64_t ldc);
85
+
86
+ void gemm(
87
+ TransposeType transa, TransposeType transb,
88
+ int64_t m, int64_t n, int64_t k,
89
+ const float alpha,
90
+ const at::BFloat16 *a, int64_t lda,
91
+ const at::BFloat16 *b, int64_t ldb,
92
+ const float beta,
93
+ float *c, int64_t ldc);
94
+
95
+ void gemm(
96
+ TransposeType transa, TransposeType transb,
97
+ int64_t m, int64_t n, int64_t k,
98
+ float alpha,
99
+ const at::Half *a, int64_t lda,
100
+ const at::Half *b, int64_t ldb,
101
+ float beta,
102
+ at::Half *c, int64_t ldc);
103
+
104
+ void gemm(
105
+ TransposeType transa, TransposeType transb,
106
+ int64_t m, int64_t n, int64_t k,
107
+ const float alpha,
108
+ const at::Half *a, int64_t lda,
109
+ const at::Half *b, int64_t ldb,
110
+ const float beta,
111
+ float *c, int64_t ldc);
112
+
113
+ void gemm(
114
+ TransposeType transa, TransposeType transb,
115
+ int64_t m, int64_t n, int64_t k,
116
+ c10::complex<double> alpha,
117
+ const c10::complex<double> *a, int64_t lda,
118
+ const c10::complex<double> *b, int64_t ldb,
119
+ c10::complex<double> beta,
120
+ c10::complex<double> *c, int64_t ldc);
121
+
122
+ void gemm(
123
+ TransposeType transa, TransposeType transb,
124
+ int64_t m, int64_t n, int64_t k,
125
+ c10::complex<float> alpha,
126
+ const c10::complex<float> *a, int64_t lda,
127
+ const c10::complex<float> *b, int64_t ldb,
128
+ c10::complex<float> beta,
129
+ c10::complex<float> *c, int64_t ldc);
130
+
131
+ void gemm(
132
+ TransposeType transa, TransposeType transb,
133
+ int64_t m, int64_t n, int64_t k,
134
+ int64_t alpha,
135
+ const int64_t *a, int64_t lda,
136
+ const int64_t *b, int64_t ldb,
137
+ int64_t beta,
138
+ int64_t *c, int64_t ldc);
139
+
140
+ template <typename scalar_t>
141
+ void gemm_batched(
142
+ TransposeType transa, TransposeType transb,
143
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
144
+ scalar_t alpha,
145
+ const scalar_t * const *a, int64_t lda,
146
+ const scalar_t * const *b, int64_t ldb,
147
+ const scalar_t beta,
148
+ scalar_t * const *c, int64_t ldc);
149
+
150
+ template <typename scalar_t>
151
+ void gemm_batched_with_stride(
152
+ TransposeType transa, TransposeType transb,
153
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
154
+ scalar_t alpha,
155
+ const scalar_t *a, int64_t lda, int64_t batch_stride_a,
156
+ const scalar_t *b, int64_t ldb, int64_t batch_stride_b,
157
+ scalar_t beta,
158
+ scalar_t *c, int64_t ldc, int64_t batch_stride_c);
159
+
160
+ using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy);
161
+
162
+ DECLARE_DISPATCH(axpy_fn, axpy_stub)
163
+
164
+ template<typename scalar_t>
165
+ void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){
166
+ if(n == 1)
167
+ {
168
+ incx = 1;
169
+ incy = 1;
170
+ }
171
+ axpy_stub(
172
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
173
+ n, a, x, incx, y, incy);
174
+ }
175
+
176
+ void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy);
177
+ void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy);
178
+ void axpy(int64_t n, c10::complex<double> a, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
179
+ void axpy(int64_t n, c10::complex<float> a, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
180
+
181
+ using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy);
182
+
183
+ DECLARE_DISPATCH(copy_fn, copy_stub)
184
+
185
+ template<typename scalar_t>
186
+ void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) {
187
+ if(n == 1)
188
+ {
189
+ incx = 1;
190
+ incy = 1;
191
+ }
192
+ copy_stub(
193
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
194
+ n, x, incx, y, incy);
195
+ }
196
+
197
+ void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy);
198
+ void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy);
199
+ void copy(int64_t n, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
200
+ void copy(int64_t n, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
201
+
202
+ // Batch-reduce GEMM
203
+ // Operates by the following formula:
204
+ // C = SUM(A[i] x B[i]) + C if add_C is true, i = 0 to batch size
205
+ // A Base pointer to a tensor A.
206
+ // B Base pointer to a tensor B.
207
+ // C Pointer to a tensor C (accumulation buffer).
208
+ // Note only batch size 1 is used currently
209
+ TORCH_API void brgemm(
210
+ int64_t M,
211
+ int64_t N,
212
+ int64_t K,
213
+ int64_t ld_a,
214
+ int64_t ld_b,
215
+ int64_t ld_c,
216
+ const bool add_C,
217
+ const at::Half* A,
218
+ const at::Half* B,
219
+ float* C,
220
+ bool is_vnni = true);
221
+
222
+ TORCH_API void brgemm(
223
+ int64_t M,
224
+ int64_t N,
225
+ int64_t K,
226
+ int64_t ld_a,
227
+ int64_t ld_b,
228
+ int64_t ld_c,
229
+ const bool add_C,
230
+ const at::BFloat16* A,
231
+ const at::BFloat16* B,
232
+ float* C,
233
+ bool is_vnni = true);
234
+
235
+ TORCH_API void brgemm(
236
+ int64_t M,
237
+ int64_t N,
238
+ int64_t K,
239
+ int64_t ld_a,
240
+ int64_t ld_b,
241
+ int64_t ld_c,
242
+ const bool add_C,
243
+ const float* A,
244
+ const float* B,
245
+ float* C,
246
+ bool is_vnni = false);
247
+
248
+ TORCH_API void brgemm(
249
+ int64_t M,
250
+ int64_t N,
251
+ int64_t K,
252
+ int64_t ld_a,
253
+ int64_t ld_b,
254
+ int64_t ld_c,
255
+ const bool add_C,
256
+ const unsigned char* A,
257
+ const unsigned char* B,
258
+ int32_t* C,
259
+ bool is_vnni = true);
260
+
261
+ TORCH_API void brgemm(
262
+ int64_t M,
263
+ int64_t N,
264
+ int64_t K,
265
+ int64_t ld_a,
266
+ int64_t ld_b,
267
+ int64_t ld_c,
268
+ const bool add_C,
269
+ const unsigned char* A,
270
+ const signed char* B,
271
+ int32_t* C,
272
+ bool is_vnni = true);
273
+
274
+ TORCH_API void brgemm(
275
+ int64_t M,
276
+ int64_t N,
277
+ int64_t K,
278
+ int64_t ld_a,
279
+ int64_t ld_b,
280
+ int64_t ld_c,
281
+ const bool add_C,
282
+ const signed char* A,
283
+ const signed char* B,
284
+ int32_t* C,
285
+ bool is_vnni = true);
286
+
287
+ // Release brgemm hardware context
288
+ TORCH_API void brgemm_release(bool is_vnni = true);
289
+
290
+ // Pack B matrix to get better performance if needed
291
+ TORCH_API void pack(
292
+ int64_t K,
293
+ int64_t N,
294
+ int64_t ld_in,
295
+ int64_t ld_out,
296
+ ScalarType dt_in,
297
+ ScalarType dt_out,
298
+ const void* in,
299
+ void* out);
300
+
301
+ // Whether pack is supported in the platform.
302
+ TORCH_API bool could_pack(ScalarType dt_in);
303
+
304
+ } // namespace at::native::cpublas
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <ATen/core/stack.h>
5
+ #include <ATen/core/boxing/KernelFunction.h>
6
+ #include <ATen/core/dispatch/Dispatcher.h>
7
+ #include <c10/util/Metaprogramming.h>
8
+ #include <torch/library.h>
9
+
10
+ namespace at::native {
11
+
12
+ // This function implements a boxed fallback to CPU.
13
+ // External backends can add their own custom logging on top if it to customize their own CPU fallbacks.
14
+ TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool error_on_views = false,
15
+ c10::DispatchKey cpu_dispatch_key = c10::DispatchKey::CPU);
16
+
17
+ // This is a helper function that backends can use to directly call their boxed CPU fallback
18
+ // TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands.
19
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
20
+ struct _call_fallback_fn final {};
21
+
22
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
23
+ struct _call_fallback_fn<fallback_fn, Op, symint, ReturnType(ParameterTypes...)> final {
24
+ static ReturnType call(typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
25
+ auto op = c10::Dispatcher::singleton()
26
+ // TODO: figure out how to make compiler happy without dynamic casts
27
+ .findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name)
28
+ //.findSchemaOrThrow("a", "b")
29
+ .typed<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>();
30
+ return c10::impl::BoxedKernelWrapper<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>::call(
31
+ c10::BoxedKernel::makeFromFunction<fallback_fn>(),
32
+ op,
33
+ c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset.
34
+ // TODO: get std::forward<> to work
35
+ args...
36
+ );
37
+ }
38
+ };
39
+
40
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
41
+ using call_fallback_fn_symint = _call_fallback_fn<fallback_fn, Op, true, typename Op::schema>;
42
+
43
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
44
+ using call_fallback_fn = _call_fallback_fn<fallback_fn, Op, false, typename Op::schema>;
45
+
46
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/NativeFunctions.h>
8
+ #else
9
+ #include <ATen/ops/view_as_real_native.h>
10
+ #include <ATen/ops/view_as_complex_native.h>
11
+
12
+ #include <utility>
13
+ #endif
14
+
15
+ // WARNING: this header contains non-inline functions and should be only
16
+ // included from ONE cpp file
17
+
18
+ namespace at::native {
19
+
20
+ // View tensor with new dtype, storage offset, sizes and strides
21
+ inline Tensor view_tensor(
22
+ const Tensor &tensor, ScalarType dtype,
23
+ c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) {
24
+ Storage storage = tensor.storage();
25
+ auto key_set = tensor.key_set().remove(DispatchKey::Conjugate);
26
+ auto new_tensor = detail::make_tensor<TensorImpl>(
27
+ c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype));
28
+ auto * impl = new_tensor.unsafeGetTensorImpl();
29
+ impl->set_sizes_and_strides(sizes, strides, offset);
30
+ return new_tensor;
31
+ }
32
+
33
+ inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) {
34
+ SymDimVector res(oldstride.size() + 1);
35
+ for (const auto i : c10::irange(oldstride.size())) {
36
+ res[i] = oldstride[i] * 2;
37
+ }
38
+ res.back() = 1;
39
+ return res;
40
+ }
41
+
42
+ inline Tensor _view_as_real_physical(const Tensor& self) {
43
+ TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors");
44
+ auto old_sizes = self.sym_sizes();
45
+ SymDimVector new_sizes(old_sizes.size() + 1);
46
+ std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
47
+ // last dimension will always have two elements containing the real and imag vals
48
+ new_sizes.back() = 2;
49
+ auto new_strides = computeStrideForViewAsReal(self.sym_strides());
50
+ auto new_storage_offset = self.sym_storage_offset() * 2;
51
+ const auto float_type = c10::toRealValueType(self.scalar_type());
52
+ auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides);
53
+ return real_tensor;
54
+ }
55
+
56
+ // expects as input a complex tensor and returns back a tensor
57
+ // with corresponding real dtype containing the complex values
58
+ // in the last two dimensions
59
+ Tensor view_as_real(const Tensor& self) {
60
+ TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original.");
61
+ return _view_as_real_physical(self);
62
+ }
63
+
64
+ inline SymDimVector computeStrideForViewAsComplex(SymIntArrayRef oldstride) {
65
+ const auto dim = oldstride.size();
66
+ TORCH_CHECK(dim > 0 && oldstride[dim - 1] == 1, "Tensor must have a last dimension with stride 1");
67
+
68
+ SymDimVector res(dim - 1);
69
+ for (const auto i : c10::irange(res.size())) {
70
+ TORCH_CHECK(oldstride[i] % 2 == 0, "Tensor must have a stride divisible by 2 for all but last dimension");
71
+ res[i] = oldstride[i] / 2;
72
+ }
73
+ return res;
74
+ }
75
+
76
+ // expects as input a float or double tensor with last dimension of size 2
77
+ // and returns back a tensor with corresponding complex dtype
78
+ Tensor view_as_complex(const Tensor& self) {
79
+ TORCH_CHECK(
80
+ self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf,
81
+ "view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type());
82
+
83
+ auto old_sizes = self.sym_sizes();
84
+ TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions");
85
+ TORCH_CHECK(old_sizes[old_sizes.size()-1] == 2, "Tensor must have a last dimension of size 2");
86
+ SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1);
87
+
88
+ const auto new_strides = computeStrideForViewAsComplex(self.sym_strides());
89
+ const auto complex_type = c10::toComplexType(self.scalar_type());
90
+
91
+ TORCH_CHECK(self.sym_storage_offset() % 2 == 0, "Tensor must have a storage_offset divisible by 2");
92
+ const auto new_storage_offset = self.sym_storage_offset() / 2;
93
+
94
+ return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides);
95
+ }
96
+
97
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/CompositeRandomAccessorCommon.h>
4
+
5
+ namespace at::native {
6
+
7
+ struct TupleInfoCPU {
8
+ template <typename ...Types>
9
+ using tuple = std::tuple<Types...>;
10
+
11
+ template <typename ...Types>
12
+ static constexpr auto tie(Types&... args) noexcept {
13
+ return std::tie(args...);
14
+ }
15
+ };
16
+
17
+ template <typename KeyAccessor, typename ValueAccessor>
18
+ using CompositeRandomAccessorCPU =
19
+ CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfoCPU>;
20
+
21
+ template <typename Values, typename References>
22
+ void swap(
23
+ references_holder<Values, References> rh1,
24
+ references_holder<Values, References> rh2
25
+ ) {
26
+ return std::swap(rh1.data(), rh2.data());
27
+ }
28
+
29
+ template <int N, typename Values, typename References>
30
+ auto get(references_holder<Values, References> rh) -> decltype(std::get<N>(rh.data())) {
31
+ return std::get<N>(rh.data());
32
+ }
33
+
34
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+
3
+ namespace at::native {
4
+
5
+ std::tuple<Tensor, Tensor, Tensor> slow_conv3d_backward_cpu(
6
+ const Tensor& grad_output,
7
+ const Tensor& self,
8
+ const Tensor& weight,
9
+ IntArrayRef kernel_size,
10
+ IntArrayRef stride,
11
+ IntArrayRef padding,
12
+ std::array<bool, 3> output_mask);
13
+
14
+ } // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Copy.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+
7
+ class Tensor;
8
+ struct TensorIterator;
9
+ class TensorBase;
10
+
11
+ namespace native {
12
+
13
+ using copy_fn = void (*)(TensorIterator&, bool non_blocking);
14
+
15
+ DECLARE_DISPATCH(copy_fn, copy_stub)
16
+
17
+ TORCH_API void copy_ignoring_overlaps(const TensorBase &dst, const TensorBase &src);
18
+
19
+ } // namespace native
20
+ } // namespace at
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d);
11
+
12
+ DECLARE_DISPATCH(cross_fn, cross_stub)
13
+
14
+ }} // namespace at::native
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <vector>
5
+
6
+ #include <ATen/div_rtn.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \
11
+ TORCH_CHECK( \
12
+ T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \
13
+ "Need " #T " of dimension ", \
14
+ DIM, \
15
+ " and " #T ".size[", \
16
+ DIM_SIZE, \
17
+ "] == ", \
18
+ SIZE, \
19
+ " but got input to be of shape ", \
20
+ T.sizes())
21
+
22
+ namespace at::native::internal {
23
+ namespace {
24
+ inline bool all_positive(IntArrayRef& arr) {
25
+ return std::all_of(
26
+ arr.begin(), arr.end(), [](int64_t item) { return item > 0; });
27
+ }
28
+
29
+ inline bool all_nonnegative(std::vector<int64_t>& arr) {
30
+ return std::all_of(
31
+ arr.begin(), arr.end(), [](int64_t item) { return item >= 0; });
32
+ }
33
+
34
+ } // namespace
35
+
36
+ // calculate the rear part of output tensor sizes
37
+ template <int64_t dim>
38
+ std::vector<int64_t> get_output_size(
39
+ const Tensor& input,
40
+ IntArrayRef kernel_size,
41
+ IntArrayRef stride_size,
42
+ IntArrayRef pad_size,
43
+ IntArrayRef dilation_size) {
44
+ std::vector<int64_t> sizes;
45
+ for (const auto index : c10::irange(dim)) {
46
+ sizes.push_back(
47
+ div_rtn<int64_t>(
48
+ input.size(index + input.dim() - dim) + 2 * pad_size[index] -
49
+ (dilation_size[index] * (kernel_size[index] - 1) + 1),
50
+ stride_size[index]) +
51
+ 1);
52
+ }
53
+ return sizes;
54
+ }
55
+
56
+ // calculate the sizes of output tensor
57
+ template <int64_t dim>
58
+ std::vector<int64_t> get_output_size(
59
+ const Tensor& input,
60
+ const Tensor& weight,
61
+ IntArrayRef kernel_size,
62
+ IntArrayRef stride_size,
63
+ IntArrayRef pad_size,
64
+ IntArrayRef dilation_size) {
65
+ auto output_size = get_output_size<dim>(
66
+ input, kernel_size, stride_size, pad_size, dilation_size);
67
+ output_size.insert(output_size.begin(), weight.size(0));
68
+ if (input.dim() == dim + 2) {
69
+ output_size.insert(output_size.begin(), input.size(0));
70
+ }
71
+ return output_size;
72
+ }
73
+ /*
74
+ slow_conv_dilated_shape_check - check user-input to dilated convolution
75
+ forward and backward functions.
76
+ */
77
+ template <int64_t dim>
78
+ void slow_conv_dilated_shape_check(
79
+ const Tensor& input,
80
+ const Tensor& weight,
81
+ const Tensor& bias,
82
+ const Tensor& grad_output,
83
+ IntArrayRef kernel_size,
84
+ IntArrayRef stride_size,
85
+ IntArrayRef pad_size,
86
+ IntArrayRef dilation_size) {
87
+ /*
88
+ When the following tensors are defined:
89
+
90
+ bias, grad_weight, grad_output
91
+
92
+ then these are assumed to be contiguous without checking
93
+ because of these tensors are made contiguous by calling
94
+ .contiguous() method or by resizing of zero-sized tensors in
95
+ forward/backward functions.
96
+
97
+ When grad_weight is defined then it is assumed without
98
+ checking to have the same shape as weight, see backward
99
+ functions.
100
+ */
101
+ // Check size arguments
102
+ TORCH_CHECK(
103
+ kernel_size.size() == dim,
104
+ "kernel sizes length should be ",
105
+ dim,
106
+ ", but got ",
107
+ kernel_size.size());
108
+ TORCH_CHECK(
109
+ stride_size.size() == dim,
110
+ "strides length should be ",
111
+ dim,
112
+ ", but got ",
113
+ stride_size.size());
114
+ TORCH_CHECK(
115
+ dilation_size.size() == dim,
116
+ "dilations length should be ",
117
+ dim,
118
+ ", but got ",
119
+ dilation_size.size());
120
+ TORCH_CHECK(
121
+ pad_size.size() == dim,
122
+ "pads length should be ",
123
+ dim,
124
+ ", but got ",
125
+ pad_size.size());
126
+
127
+ TORCH_CHECK(
128
+ all_positive(kernel_size),
129
+ "kernel size should be greater than zero, but got ",
130
+ kernel_size);
131
+ TORCH_CHECK(
132
+ all_positive(stride_size),
133
+ "stride should be greater than zero, but got ",
134
+ stride_size);
135
+ TORCH_CHECK(
136
+ all_positive(dilation_size),
137
+ "dilation should be greater than zero, but got ",
138
+ dilation_size);
139
+
140
+ // check input
141
+ TORCH_CHECK(input.defined(), "input must be defined");
142
+ bool is_batch = input.dim() == dim + 2;
143
+ int64_t n = (is_batch ? 2 : 1);
144
+ int64_t ndim = n + dim;
145
+ if (!is_batch) {
146
+ // input dim has to be dim + 1 if not batched
147
+ TORCH_CHECK(
148
+ input.dim() == dim + 1,
149
+ "input must be 4D or 5D tensor but got ",
150
+ input.dim(),
151
+ "D tensor");
152
+ }
153
+
154
+ // check output sizes
155
+ auto output_size = get_output_size<dim>(
156
+ input, kernel_size, stride_size, pad_size, dilation_size);
157
+
158
+ TORCH_CHECK(
159
+ all_nonnegative(output_size),
160
+ "calculated output size ",
161
+ output_size,
162
+ " is too small (all sizes must be non-negative)");
163
+
164
+ // check weight
165
+ TORCH_CHECK(weight.defined(), "weight must be defined");
166
+ TORCH_CHECK(
167
+ weight.dim() == dim + 2,
168
+ "weight must be ",
169
+ dim + 2,
170
+ "D tensor but got ",
171
+ weight.dim(),
172
+ "D tensor dim=",
173
+ dim);
174
+ TORCH_CHECK(
175
+ weight.sizes().slice(2) == kernel_size,
176
+ "weight[2:] shape ",
177
+ weight.sizes().slice(2),
178
+ " must be equal to kernel_size ",
179
+ kernel_size);
180
+
181
+ TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1));
182
+
183
+ // check bias when present
184
+ if (bias.defined()) {
185
+ TORCH_CHECK(
186
+ bias.dim() == 1,
187
+ "bias must be 1D tensor but got ",
188
+ bias.dim(),
189
+ "D tensor");
190
+ TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0));
191
+ }
192
+
193
+ // check grad_output when present
194
+ if (grad_output.defined()) {
195
+ TORCH_CHECK(
196
+ grad_output.dim() == ndim,
197
+ "grad_output must be ",
198
+ ndim,
199
+ "D tensor but got ",
200
+ grad_output.dim(),
201
+ "D tensor");
202
+ if (is_batch) {
203
+ TORCH_CHECK(
204
+ grad_output.size(0) == input.size(0),
205
+ "grad_output.size(0)=",
206
+ grad_output.size(0),
207
+ " must be input.size(0)=",
208
+ input.size(0));
209
+ }
210
+ TORCH_CHECK(
211
+ grad_output.size(n - 1) == weight.size(0),
212
+ "grad_output.size(",
213
+ n - 1,
214
+ ")=",
215
+ grad_output.size(n - 1),
216
+ " must be weight.size(0)=",
217
+ weight.size(0));
218
+ TORCH_CHECK(
219
+ grad_output.sizes().slice(n) == output_size,
220
+ "grad_output[",
221
+ n,
222
+ ":] shape",
223
+ grad_output.sizes().slice(n),
224
+ " must be equal to output size ",
225
+ output_size);
226
+ }
227
+ }
228
+
229
+ } // namespace at::native::internal
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/macros/Macros.h>
5
+
6
+ #include <atomic>
7
+ #include <utility>
8
+ #include <variant>
9
+
10
+ // Implements instruction set specific function dispatch.
11
+ //
12
+ // Kernels that may make use of specialized instruction sets (e.g. AVX2) are
13
+ // compiled multiple times with different compiler flags (e.g. -mavx2). A
14
+ // DispatchStub contains a table of function pointers for a kernel. At runtime,
15
+ // the fastest available kernel is chosen based on the features reported by
16
+ // cpuinfo.
17
+ //
18
+ // Example:
19
+ //
20
+ // In native/MyKernel.h:
21
+ // using fn_type = void(*)(const Tensor& x);
22
+ // DECLARE_DISPATCH(fn_type, stub)
23
+ //
24
+ // In native/MyKernel.cpp
25
+ // DEFINE_DISPATCH(stub);
26
+ //
27
+ // In native/cpu/MyKernel.cpp:
28
+ // namespace {
29
+ // // use anonymous namespace so that different cpu versions won't conflict
30
+ // void kernel(const Tensor& x) { ... }
31
+ // }
32
+ // REGISTER_DISPATCH(stub, &kernel);
33
+ //
34
+ // To call:
35
+ // stub(kCPU, tensor);
36
+ //
37
+ // TODO: CPU instruction set selection should be folded into whatever
38
+ // the main dispatch mechanism is.
39
+ //
40
+ // Supported device types for registration:
41
+ // - CPU: Central Processing Unit
42
+ // - CUDA: NVIDIA GPUs
43
+ // - HIP: AMD GPUs
44
+ // - MPS: Apple Silicon GPUs (Metal Performance Shaders)
45
+ // - MTIA: Meta Training and Inference Devices
46
+ // - XPU: Intel GPUs
47
+ // - HPU: Reserved for HPU (Intel Gaudi) device types
48
+ // - PrivateUse1: Reserved for private/custom device types
49
+ //
50
+ // If you want to update the list of supported devices, add a new dispatch_ptr
51
+ // member in DispatchStubImpl.h and update the get_call_ptr switch.
52
+ // As well you will need to update the inlined list in 'is_device_supported`
53
+ //
54
+ //
55
+ // ignore warnings about DispatchStub::DEFAULT, AVX, AVX2 defined elsewhere
56
+ C10_CLANG_DIAGNOSTIC_PUSH()
57
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wundefined-var-template")
58
+
59
+ namespace at::native {
60
+
61
+ enum class CPUCapability {
62
+ DEFAULT = 0,
63
+ #if defined(HAVE_VSX_CPU_DEFINITION)
64
+ VSX = 1,
65
+ #elif defined(HAVE_ZVECTOR_CPU_DEFINITION)
66
+ ZVECTOR = 1,
67
+ #elif defined(HAVE_SVE256_CPU_DEFINITION) && defined(HAVE_ARM_BF16_CPU_DEFINITION)
68
+ SVE256 = 1,
69
+ #else
70
+ AVX2 = 1,
71
+ AVX512 = 2,
72
+ #endif
73
+ NUM_OPTIONS
74
+ };
75
+
76
+ // Enum for error types
77
+ enum class ErrorType {
78
+ MissingDeviceKernel,
79
+ DeviceNotSupported
80
+ };
81
+
82
+ // Alias for the return type using std::variant
83
+ using DispatchResult = std::variant<void*, ErrorType>;
84
+
85
+ CPUCapability get_cpu_capability();
86
+
87
+ template <typename FnPtr, typename T>
88
+ struct DispatchStub;
89
+
90
+ /**
91
+ * The sole purpose of this class is to outline methods that don't need to be
92
+ * specialized or otherwise inlined and duplicated (by the compiler due to
93
+ * template expansion), since it causes size bloat if there are a significant
94
+ * number of specialization of the DispatchStub<> class.
95
+ */
96
+ struct TORCH_API DispatchStubImpl {
97
+
98
+ // The DispatchStubImpl::try_get_call_ptr() method is used to get the call
99
+ // pointer for a given device type. If the call pointer is not found,
100
+ // DispatchStubImpl::try_get_call_ptr() returns an ErrorType.
101
+ // The main difference between try_get_call_ptr() and get_call_ptr() is that
102
+ // try_get_call_ptr() will return the ErrorType and not raise an exception.
103
+ DispatchResult try_get_call_ptr(
104
+ c10::DeviceType device_type
105
+ , void *DEFAULT
106
+ #ifdef HAVE_AVX512_CPU_DEFINITION
107
+ , void *AVX512
108
+ #endif
109
+ #ifdef HAVE_AVX2_CPU_DEFINITION
110
+ , void *AVX2
111
+ #endif
112
+ #ifdef HAVE_VSX_CPU_DEFINITION
113
+ , void *VSX
114
+ #endif
115
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
116
+ , void *ZVECTOR
117
+ #endif
118
+ #ifdef HAVE_SVE256_CPU_DEFINITION
119
+ , void *SVE256
120
+ #endif
121
+ );
122
+
123
+ // Analogous to try_get_call_ptr(), but it will return the ErrorType and not
124
+ // raise an exception.
125
+ DispatchResult try_choose_cpu_impl(
126
+ void *DEFAULT
127
+ #ifdef HAVE_AVX512_CPU_DEFINITION
128
+ , void *AVX512
129
+ #endif
130
+ #ifdef HAVE_AVX2_CPU_DEFINITION
131
+ , void *AVX2
132
+ #endif
133
+ #ifdef HAVE_VSX_CPU_DEFINITION
134
+ , void *VSX
135
+ #endif
136
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
137
+ , void *ZVECTOR
138
+ #endif
139
+ #ifdef HAVE_SVE256_CPU_DEFINITION
140
+ , void *SVE256
141
+ #endif
142
+ );
143
+
144
+
145
+ void* get_call_ptr(
146
+ c10::DeviceType device_type
147
+ , void *DEFAULT
148
+ #ifdef HAVE_AVX512_CPU_DEFINITION
149
+ , void *AVX512
150
+ #endif
151
+ #ifdef HAVE_AVX2_CPU_DEFINITION
152
+ , void *AVX2
153
+ #endif
154
+ #ifdef HAVE_VSX_CPU_DEFINITION
155
+ , void *VSX
156
+ #endif
157
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
158
+ , void *ZVECTOR
159
+ #endif
160
+ #ifdef HAVE_SVE256_CPU_DEFINITION
161
+ , void *SVE256
162
+ #endif
163
+ );
164
+
165
+ /**
166
+ * The CPU Dispatch actual method is chosen in decreasing order of preference by
167
+ * DispatchStubImpl::choose_cpu_impl() in case none is found by
168
+ * DispatchStubImpl::get_call_ptr() in cpu_dispatch_ptr.
169
+ */
170
+ void* choose_cpu_impl(
171
+ void *DEFAULT
172
+ #ifdef HAVE_AVX512_CPU_DEFINITION
173
+ , void *AVX512
174
+ #endif
175
+ #ifdef HAVE_AVX2_CPU_DEFINITION
176
+ , void *AVX2
177
+ #endif
178
+ #ifdef HAVE_VSX_CPU_DEFINITION
179
+ , void *VSX
180
+ #endif
181
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
182
+ , void *ZVECTOR
183
+ #endif
184
+ #ifdef HAVE_SVE256_CPU_DEFINITION
185
+ , void *SVE256
186
+ #endif
187
+ );
188
+
189
+ // Fixing dispatch error in Windows debug builds.
190
+ // See https://github.com/pytorch/pytorch/issues/22681 for more details.
191
+ #if defined(_MSC_VER) && defined(_DEBUG)
192
+ std::atomic<void*> cpu_dispatch_ptr;
193
+ void* cuda_dispatch_ptr;
194
+ void* hip_dispatch_ptr;
195
+ void* mps_dispatch_ptr;
196
+ void* mtia_dispatch_ptr;
197
+ #if defined(USE_XPU)
198
+ void* xpu_dispatch_ptr;
199
+ #endif
200
+ void* hpu_dispatch_ptr;
201
+ void* privateuse1_dispatch_ptr;
202
+ #else
203
+ std::atomic<void*> cpu_dispatch_ptr{nullptr};
204
+ void* cuda_dispatch_ptr = nullptr;
205
+ void* hip_dispatch_ptr = nullptr;
206
+ void* mps_dispatch_ptr = nullptr;
207
+ void* mtia_dispatch_ptr = nullptr;
208
+ #if defined(USE_XPU)
209
+ void* xpu_dispatch_ptr = nullptr;
210
+ #endif
211
+ void* hpu_dispatch_ptr = nullptr;
212
+ void* privateuse1_dispatch_ptr = nullptr;
213
+ #endif
214
+ };
215
+
216
+ template <typename rT, typename T, typename... Args>
217
+ struct DispatchStub<rT (*)(Args...), T> {
218
+ using FnPtr = rT (*) (Args...);
219
+
220
+ DispatchStub() = default;
221
+ DispatchStub(const DispatchStub&) = delete;
222
+ DispatchStub& operator=(const DispatchStub&) = delete;
223
+
224
+ private:
225
+ FnPtr get_call_ptr(const c10::DeviceType device_type) {
226
+ return reinterpret_cast<FnPtr>(
227
+ impl.get_call_ptr(device_type
228
+ , reinterpret_cast<void*>(DEFAULT)
229
+ #ifdef HAVE_AVX512_CPU_DEFINITION
230
+ , reinterpret_cast<void*>(AVX512)
231
+ #endif
232
+ #ifdef HAVE_AVX2_CPU_DEFINITION
233
+ , reinterpret_cast<void*>(AVX2)
234
+ #endif
235
+ #ifdef HAVE_VSX_CPU_DEFINITION
236
+ , reinterpret_cast<void*>(VSX)
237
+ #endif
238
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
239
+ , reinterpret_cast<void*>(ZVECTOR)
240
+ #endif
241
+ #ifdef HAVE_SVE256_CPU_DEFINITION
242
+ , reinterpret_cast<void*>(SVE256)
243
+ #endif
244
+ )
245
+ );
246
+ }
247
+
248
+ public:
249
+ template <typename... ArgTypes>
250
+ rT operator()(c10::DeviceType device_type, ArgTypes&&... args) {
251
+ FnPtr call_ptr = get_call_ptr(device_type);
252
+ return (*call_ptr)(std::forward<ArgTypes>(args)...);
253
+ }
254
+
255
+ void set_cuda_dispatch_ptr(FnPtr fn_ptr) {
256
+ impl.cuda_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
257
+ }
258
+
259
+ #if defined(USE_XPU)
260
+ void set_xpu_dispatch_ptr(FnPtr fn_ptr){
261
+ impl.xpu_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
262
+ }
263
+ #endif
264
+
265
+ void set_hpu_dispatch_ptr(FnPtr fn_ptr) {
266
+ impl.hpu_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
267
+ }
268
+
269
+ void set_hip_dispatch_ptr(FnPtr fn_ptr) {
270
+ impl.hip_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
271
+ }
272
+
273
+ void set_mps_dispatch_ptr(FnPtr fn_ptr) {
274
+ impl.mps_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
275
+ }
276
+
277
+ void set_mtia_dispatch_ptr(FnPtr fn_ptr) {
278
+ impl.mtia_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
279
+ }
280
+
281
+ void set_privateuse1_dispatch_ptr(FnPtr fn_ptr) {
282
+ impl.privateuse1_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
283
+ }
284
+
285
+ // Returns true if the dispatcher has a kernel registered for this device
286
+ // type.
287
+ bool is_device_supported(const c10::DeviceType device_type) {
288
+ auto result = impl.try_get_call_ptr(device_type
289
+ , reinterpret_cast<void*>(DEFAULT)
290
+ #ifdef HAVE_AVX512_CPU_DEFINITION
291
+ , reinterpret_cast<void*>(AVX512)
292
+ #endif
293
+ #ifdef HAVE_AVX2_CPU_DEFINITION
294
+ , reinterpret_cast<void*>(AVX2)
295
+ #endif
296
+ #ifdef HAVE_VSX_CPU_DEFINITION
297
+ , reinterpret_cast<void*>(VSX)
298
+ #endif
299
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
300
+ , reinterpret_cast<void*>(ZVECTOR)
301
+ #endif
302
+ #ifdef HAVE_SVE256_CPU_DEFINITION
303
+ , reinterpret_cast<void*>(SVE256)
304
+ #endif
305
+ );
306
+ if (std::holds_alternative<ErrorType>(result)){
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+
312
+ static TORCH_API FnPtr DEFAULT;
313
+ #ifdef HAVE_AVX512_CPU_DEFINITION
314
+ static TORCH_API FnPtr AVX512;
315
+ #endif
316
+ #ifdef HAVE_AVX2_CPU_DEFINITION
317
+ static TORCH_API FnPtr AVX2;
318
+ #endif
319
+ #ifdef HAVE_VSX_CPU_DEFINITION
320
+ static TORCH_API FnPtr VSX;
321
+ #endif
322
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
323
+ static TORCH_API FnPtr ZVECTOR;
324
+ #endif
325
+ #ifdef HAVE_SVE256_CPU_DEFINITION
326
+ static TORCH_API FnPtr SVE256;
327
+ #endif
328
+ private:
329
+ DispatchStubImpl impl;
330
+ };
331
+
332
+ namespace {
333
+ template <typename DispatchStub>
334
+ struct RegisterCUDADispatch {
335
+ RegisterCUDADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
336
+ stub.set_cuda_dispatch_ptr(value);
337
+ }
338
+ };
339
+
340
+ template <typename DispatchStub>
341
+ struct RegisterXPUDispatch {
342
+ RegisterXPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){
343
+ stub.set_xpu_dispatch_ptr(value);
344
+ }
345
+ };
346
+
347
+ template <typename DispatchStub>
348
+ struct RegisterHPUDispatch {
349
+ RegisterHPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){
350
+ stub.set_hpu_dispatch_ptr(value);
351
+ }
352
+ };
353
+
354
+ template <typename DispatchStub>
355
+ struct RegisterMPSDispatch {
356
+ RegisterMPSDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
357
+ stub.set_mps_dispatch_ptr(value);
358
+ }
359
+ };
360
+
361
+ template <typename DispatchStub>
362
+ struct RegisterHIPDispatch {
363
+ RegisterHIPDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
364
+ // TODO: make this point at hip_dispatch_ptr
365
+ stub.set_cuda_dispatch_ptr(value);
366
+ }
367
+ };
368
+
369
+ template <typename DispatchStub>
370
+ struct RegisterMTIADispatch {
371
+ RegisterMTIADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
372
+ stub.set_mtia_dispatch_ptr(value);
373
+ }
374
+ };
375
+
376
+ template <typename DispatchStub>
377
+ struct RegisterPRIVATEUSE1Dispatch {
378
+ RegisterPRIVATEUSE1Dispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
379
+ stub.set_privateuse1_dispatch_ptr(value);
380
+ }
381
+ };
382
+
383
+ } // anonymous namespace
384
+ // Compiler will complain if you put things like std::tuple<Tensor, Tensor> in
385
+ // the `fn` argument of DECLARE_DISPATCH. Some possible workarounds, e.g.,
386
+ // adding parentheses and using helper struct to get rid of the parentheses, do
387
+ // not work with MSVC. So do a `using`-declaration if you need to pass in such
388
+ // `fn`, e.g., grid_sampler_2d_backward_cpu_kernel in GridSampleKernel.h.
389
+ #define DECLARE_DISPATCH(fn, name) \
390
+ struct name##_DECLARE_DISPATCH_type : DispatchStub<fn, name##_DECLARE_DISPATCH_type> { \
391
+ name##_DECLARE_DISPATCH_type() = default; \
392
+ name##_DECLARE_DISPATCH_type(const name##_DECLARE_DISPATCH_type&) = delete; \
393
+ name##_DECLARE_DISPATCH_type& operator=(const name##_DECLARE_DISPATCH_type&) = delete; \
394
+ name##_DECLARE_DISPATCH_type(name##_DECLARE_DISPATCH_type&&) = delete; \
395
+ name##_DECLARE_DISPATCH_type& operator=(name##_DECLARE_DISPATCH_type&&) = delete; \
396
+ ~name##_DECLARE_DISPATCH_type() = default; \
397
+ }; \
398
+ extern TORCH_API struct name##_DECLARE_DISPATCH_type name;
399
+
400
+ #define DEFINE_DISPATCH(name) struct name##_DECLARE_DISPATCH_type name
401
+
402
+ #define REGISTER_ARCH_DISPATCH(name, arch, fn) \
403
+ template <> name##_DECLARE_DISPATCH_type::FnPtr TORCH_API DispatchStub<name##_DECLARE_DISPATCH_type::FnPtr, struct name##_DECLARE_DISPATCH_type>::arch = fn;
404
+
405
+ #ifdef HAVE_AVX512_CPU_DEFINITION
406
+ #define REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX512, fn)
407
+ #else
408
+ #define REGISTER_AVX512_DISPATCH(name, fn)
409
+ #endif
410
+
411
+ #ifdef HAVE_AVX2_CPU_DEFINITION
412
+ #define REGISTER_AVX2_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX2, fn)
413
+ #else
414
+ #define REGISTER_AVX2_DISPATCH(name, fn)
415
+ #endif
416
+
417
+ #ifdef HAVE_VSX_CPU_DEFINITION
418
+ #define REGISTER_VSX_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, VSX, fn)
419
+ #else
420
+ #define REGISTER_VSX_DISPATCH(name, fn)
421
+ #endif
422
+
423
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
424
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, ZVECTOR, fn)
425
+ #else
426
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn)
427
+ #endif
428
+
429
+ #ifdef HAVE_SVE256_CPU_DEFINITION
430
+ #define REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, SVE256, fn)
431
+ #else
432
+ #define REGISTER_SVE256_DISPATCH(name, fn)
433
+ #endif
434
+
435
+ // Macro to register the same kernel for all CPU arch types. This is useful
436
+ // if a kernel does not benefit from being recompiled across different arch types.
437
+ #define REGISTER_ALL_CPU_DISPATCH(name, fn) \
438
+ REGISTER_ARCH_DISPATCH(name, DEFAULT, fn) \
439
+ REGISTER_AVX512_DISPATCH(name, fn) \
440
+ REGISTER_AVX2_DISPATCH(name, fn) \
441
+ REGISTER_VSX_DISPATCH(name, fn) \
442
+ REGISTER_ZVECTOR_DISPATCH(name, fn) \
443
+ REGISTER_SVE256_DISPATCH(name, fn)
444
+
445
+ #define REGISTER_NO_CPU_DISPATCH(name) \
446
+ REGISTER_ALL_CPU_DISPATCH(name, nullptr)
447
+
448
+ #define REGISTER_CUDA_DISPATCH(name, fn) \
449
+ static RegisterCUDADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
450
+
451
+ #define REGISTER_XPU_DISPATCH(name, fn) \
452
+ static RegisterXPUDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
453
+
454
+ #define REGISTER_HPU_DISPATCH(name, fn) \
455
+ static RegisterHPUDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
456
+
457
+ #define REGISTER_HIP_DISPATCH(name, fn) \
458
+ static RegisterHIPDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
459
+
460
+ #define REGISTER_MPS_DISPATCH(name, fn) \
461
+ static RegisterMPSDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
462
+
463
+ #define REGISTER_MTIA_DISPATCH(name, fn) \
464
+ static RegisterMTIADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
465
+
466
+ #define REGISTER_PRIVATEUSE1_DISPATCH(name, fn) \
467
+ static RegisterPRIVATEUSE1Dispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
468
+
469
+ // NB: This macro must be used in an actual 'cu' file; if you try using
470
+ // it from a 'cpp' file it will not work!
471
+ #if defined(__CUDACC__)
472
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
473
+ #elif defined(__HIPCC__)
474
+ // TODO: cut this over to HIP dispatch once we stop pretending that CUDA
475
+ // is HIP in the PyTorch HIPify build.
476
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
477
+ // #define REGISTER_DISPATCH(name, fn) REGISTER_HIP_DISPATCH(name, fn)
478
+ #elif defined(__OBJC__) && defined(USE_MPS)
479
+ // NB: this macro must be used from a 'mm' file in order to dispatch a MPS kernel
480
+ #define REGISTER_DISPATCH(name, fn) REGISTER_MPS_DISPATCH(name, fn)
481
+ #elif defined(CPU_CAPABILITY)
482
+ // REGISTER_DISPATCH now dispatches an AVX512 kernel to nullptr but registers other dispatches.
483
+ // ALSO_REGISTER_AVX512_DISPATCH should be used for ensuring AVX512 dispatch, among others.
484
+ // ALSO_REGISTER_SVE256_DISPATCH should be used for ensuring SVE256 dispatch, among others.
485
+ #ifdef CPU_CAPABILITY_AVX512
486
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, ((void*)(fn) ? nullptr : nullptr))
487
+ #else
488
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
489
+ #endif
490
+ #define ALSO_REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
491
+ #define ALSO_REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
492
+ #endif
493
+ } // namespace at::native
494
+
495
+ C10_CLANG_DIAGNOSTIC_POP()