jasonfan commited on
Commit
186a49e
·
verified ·
1 Parent(s): dfcd861

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. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAApplyUtils.cuh +542 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDABlas.h +398 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAConfig.h +25 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAContext.h +14 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAContextLight.h +116 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDADataType.h +107 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDADevice.h +28 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAEvent.h +336 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h +185 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraph.h +100 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh +58 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGreenContext.h +43 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAScaledBlas.h +179 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparse.h +41 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseBlas.h +325 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h +257 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh +20 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAUtils.h +25 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CachingHostAllocator.h +75 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh +126 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/EmptyTensor.h +49 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/Exceptions.h +235 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/MemPool.h +50 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/NumericLimits.cuh +126 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PeerToPeerAccess.h +18 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PhiloxCudaState.h +10 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PhiloxUtils.cuh +9 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PinnedMemoryAllocator.h +15 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/ScanUtils.cuh +83 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/Sleep.h +23 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/ThrustAllocator.h +28 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub-RadixSortPairs.cuh +79 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub.cuh +576 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub.h +98 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub_definitions.cuh +34 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/BLASConstants.h +16 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/CUDAHooks.h +76 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/DeviceThreadHandles.h +156 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/IndexUtils.cuh +41 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/IntegerDivider.cuh +129 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/KernelUtils.h +42 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/LazyNVRTC.h +16 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/OffsetCalculator.cuh +141 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/PhiloxCudaStateRaw.cuh +48 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/TensorInfo.cuh +121 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/UnpackRaw.cuh +39 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/jiterator.h +45 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/jiterator_impl.h +255 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/llvm_jit_strings.h +19 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/tunable/GemmCommon.h +705 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAApplyUtils.cuh ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/ApplyGridUtils.cuh>
5
+ #include <ATen/cuda/detail/IndexUtils.cuh>
6
+ #include <ATen/core/TensorBase.h>
7
+ #include <ATen/ceil_div.h>
8
+ #include <ATen/cuda/Atomic.cuh>
9
+ #include <ATen/cuda/CUDAContext.h>
10
+ #include <c10/macros/Macros.h>
11
+ #include <ATen/native/Copy.h>
12
+
13
+ #include <math.h>
14
+
15
+ //
16
+ // This file contains pointwise operation functions and kernels that
17
+ // work on both contiguous and non-contiguous tensor arguments of
18
+ // arbitrary (up to MAX_CUTORCH_DIMS) dimensioned arguments without
19
+ // copying or temporary storage.
20
+ //
21
+
22
+ /*
23
+ NOTE [ CUDA_tensor_applyN helpers ]
24
+
25
+ The following CUDA_tensor_applyN (where N currently can be 1, 2, 3, or 4)
26
+ functions apply a pointwise operator to N tensor(s).
27
+
28
+ The calling convention is
29
+
30
+ 1. The template arguments should be, sequentially,
31
+ - First N typename args specify the scalar types of each of the N tensors.
32
+ - (Optional) `int step` arg specifies the number of elements processed
33
+ together at the same time.
34
+ Default is 1.
35
+ - A usually omitted (i.e., inferred) typename arg specifies the type of the
36
+ function/functor applied on `N * step` values in each iteration of each
37
+ CUDA thread.
38
+ 2. The arguments should be, sequentially,
39
+ - N tensors
40
+ - op: a function/functor that processes `N * step` values at the same time.
41
+ - If `step == 1`, it must have signature
42
+ `void(*)(scalar1_t&, scalar2_t&, ..., scalarN_t&)`, where
43
+ `scalar*_t`s are the first N typename template args, and the inputs
44
+ are the `N` values from the `N` tensors retrieved at a common index.
45
+ - Otherwise, it must must have signature
46
+ void(*)(int n, scalar1_t&, scalar1_t&, ..., scalar1_t&, // repeat `step` times
47
+ scalar2_t&, scalar2_t&, ..., scalar2_t&, // repeat `step` times
48
+ ...,
49
+ scalarN_t&, scalarN_t&, ..., scalarN_t&) // repeat `step` times
50
+ Different from `step == 1` case, it processes `N * step` values taken
51
+ from `step` common indices. Moreover, the first input `n` represents the
52
+ number of valid indices (it will always have `0 < n <= step`). It will
53
+ almost always be `step`, but at the boundary we may not have full `step`
54
+ elements and `n` can be a lesser value.
55
+
56
+ E.g., if `step == 4` and `N == 2`, `op` could be
57
+
58
+ [](int n, scalar1_t &u1, scalar1_t &u2, scalar1_t &u3, scalar1_t &u4,
59
+ scalar2_t &v1, scalar2_t &v2, scalar2_t &v3, scalar2_t &v4) {
60
+ // Only process u1, ..., un and v1, ..., vn.
61
+ // So if `n == 3`, `u4` and `v4` need not to be considered.
62
+ }
63
+
64
+ In both cases, the references can actually be const, but at least one of
65
+ them should be non-const in order to write the output.
66
+ - (Optional, but recommended) N TensorArgType args that specify for each
67
+ tensor whether `op` reads AND writes ] (i.e., TensorArgType::ReadWrite),
68
+ or only reads (i.e., TensorArgType::ReadOnly).
69
+ Default is TensorArgType::ReadWrite for first Tensor, and
70
+ TensorArgType::ReadOnly for the rest.
71
+
72
+ E.g.,
73
+
74
+ to compute a = b^2 for a and b of same dtype, we can call
75
+
76
+ CUDA_tensor_apply2<scalar, scalar>(
77
+ a, b,
78
+ [] __device__ (scalar &a_val, const scalar &b_val) { a_val = b_val * b_val; }
79
+ );
80
+
81
+ to work on 2 values at the same time, we can call
82
+
83
+ CUDA_tensor_apply2<scalar1, scalar2, 2>(
84
+ a, b,
85
+ [] __device__ (int n, scalar1 &a_val1, scalar1 &a_val2,
86
+ const scalar2 &b_val1, const scalar2 &b_val2) {
87
+ // call special vectorized op here, or just do elementwise and enjoy unrolling...
88
+ // if n == 1, only process a_val1 and b_val1
89
+ }
90
+ );
91
+ */
92
+
93
+ namespace at::cuda {
94
+
95
+ // TODO: combine with TensorArg? So far that's been for debugging, and this is functional...
96
+ enum class TensorArgType { ReadWrite, ReadOnly };
97
+
98
+ namespace {
99
+
100
+ // Rearrange dimensions for pointwise operations so that strides are in
101
+ // decreasing order as much as possible, so that kernels have better memory
102
+ // access patterns.
103
+ //
104
+ // For example, consider a binary operation on two "transposed" 2-dim tensors:
105
+ // sizes: 256 512
106
+ // aInfo->strides: 1 256
107
+ // bInfo->strides: 1 256
108
+ //
109
+ // Given this, each concurrent memory access inside kernelPointwiseApply2() is
110
+ // exactly 256 elements apart, resulting in poor performance.
111
+ //
112
+ // This function exchanges dimensions so that memory access is contiguous:
113
+ // sizes: 512 256
114
+ // aInfo->strides: 256 1
115
+ // bInfo->strides: 256 1
116
+ //
117
+ // (Actually, it becomes even better because now collapseDims() can turn each
118
+ // input into one contiguous array.)
119
+ //
120
+ // In general, given M (<=4) TensorInfo's with N dimensions, we can view each
121
+ // strides[i] (0 <= i < N) as an M-tuple. Given each pair i < j, we exchange
122
+ // strides[i] and [j] if
123
+ // (1) strides[i][k] < strides[j][k] for some k (0 <= k < M)
124
+ // (exchanging them will benefit input #k), and
125
+ // (2) strides[i][k] <= strieds[j][k] for all k
126
+ // (exchanging them will not make any input worse).
127
+ template <typename T1, typename IndexType,
128
+ typename T2 = void, typename T3 = void, typename T4 = void>
129
+ inline void rearrangeDims(detail::TensorInfo<T1, IndexType>* aInfo,
130
+ detail::TensorInfo<T2, IndexType>* bInfo = nullptr,
131
+ detail::TensorInfo<T3, IndexType>* cInfo = nullptr,
132
+ detail::TensorInfo<T4, IndexType>* dInfo = nullptr) {
133
+ int numInfos = 1;
134
+ int dims = aInfo->dims;
135
+ IndexType *sizes[4] = { aInfo->sizes, };
136
+ IndexType *strides[4] = { aInfo->strides, };
137
+
138
+ if (bInfo != nullptr) {
139
+ ++numInfos;
140
+ if (bInfo->dims != dims) return;
141
+ sizes[1] = bInfo->sizes;
142
+ strides[1] = bInfo->strides;
143
+ }
144
+
145
+ if (cInfo != nullptr) {
146
+ ++numInfos;
147
+ if (cInfo->dims != dims) return;
148
+ sizes[2] = cInfo->sizes;
149
+ strides[2] = cInfo->strides;
150
+ }
151
+
152
+ if (dInfo != nullptr) {
153
+ ++numInfos;
154
+ if (dInfo->dims != dims) return;
155
+ sizes[3] = dInfo->sizes;
156
+ strides[3] = dInfo->strides;
157
+ }
158
+
159
+ // Bail out if sizes do not match: we are using "deprecated pointwise
160
+ // behavior" among tensors of different shapes but same number of elements.
161
+ for (int i = 1; i < numInfos; ++i) {
162
+ for (int j = 0; j < dims; ++j) {
163
+ if (sizes[i][j] != sizes[0][j]) return;
164
+ }
165
+ }
166
+
167
+ for (int i = 0; i < dims - 1; ++i) {
168
+ // No need to consider dimensions of size 1.
169
+ if (sizes[0][i] == 1) continue;
170
+
171
+ for (int j = i + 1; j < dims; ++j) {
172
+ if (sizes[0][j] == 1) continue;
173
+
174
+ // Compare the relative sizes of strides between dim #i and dim #j.
175
+ bool hasIncreasingStrides = false;
176
+ bool hasDecreasingStrides = false;
177
+
178
+ for (int k = 0; k < numInfos; k++) {
179
+ IndexType stride_i = strides[k][i];
180
+ IndexType stride_j = strides[k][j];
181
+ if (stride_i < stride_j) {
182
+ hasIncreasingStrides = true;
183
+ } else if (stride_i > stride_j) {
184
+ hasDecreasingStrides = true;
185
+ }
186
+ }
187
+
188
+ if (hasIncreasingStrides && !hasDecreasingStrides) {
189
+ for (int k = 0; k < numInfos; k++) {
190
+ IndexType size = sizes[k][i];
191
+ sizes[k][i] = sizes[k][j];
192
+ sizes[k][j] = size;
193
+
194
+ IndexType stride = strides[k][i];
195
+ strides[k][i] = strides[k][j];
196
+ strides[k][j] = stride;
197
+ }
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ // The `remaining_steps` argument is used to support Op that operates on
204
+ // multiple elements at the same time. Generally, the strategy of ApplyOpN is to
205
+ // 1. Initialize `remaining_steps = step`, where `step` is the template arg of
206
+ // CUDA_tensor_applyN helpers. The input arg `n` to `apply()` represents the
207
+ // number of elements in bound for this call. It will almost always equal to
208
+ // `step` except at boundaries.
209
+ // 2. If `remaining_steps > 0` convert the current linearIndex to offset (if in
210
+ // bound), and recursively call `ApplyOpN` with `remaining_steps - 1`.
211
+ // 3. At `remaining_steps = 0`,
212
+ // if `step = 1`, call `op(tensor1_val, tensor2_val, ...)`;
213
+ // if `step > 1`, call `op(n, tensor1_val1, tensor1_val2, ..., tesor1_valstep,
214
+ // tensor2_val1, tensor2_val2, ..., tesor2_valstep,
215
+ // ...
216
+ // tensorN_val1, tensorN_val2, ..., tesorN_valstep);`
217
+ //
218
+ // See NOTE [ CUDA_tensor_applyN helpers ] above for how Op may look like.
219
+
220
+ template <typename Op,
221
+ typename scalar,
222
+ typename IndexType,
223
+ int ADims,
224
+ int remaining_steps,
225
+ typename... Offsets>
226
+ struct ApplyOp1 {
227
+ __device__ __forceinline__
228
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
229
+ IndexType linearIndex, Offsets... aOffsets) {
230
+ // Convert `linearIndex` into an offset of `a`
231
+ const IndexType aOffset = sizeof...(Offsets) < n ?
232
+ detail::IndexToOffset<scalar, IndexType, ADims>::get(linearIndex, a) : 0;
233
+
234
+ ApplyOp1<Op, scalar, IndexType, ADims, remaining_steps - 1, const IndexType, Offsets...>::apply(
235
+ a, op, n, linearIndex + 1, aOffsets..., aOffset
236
+ );
237
+ }
238
+ };
239
+
240
+ // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
241
+ // We don't need to pass in how many elements need to processed in this case.
242
+ template <typename Op,
243
+ typename scalar,
244
+ typename IndexType,
245
+ int ADims,
246
+ typename Offset>
247
+ struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offset> {
248
+ __device__ __forceinline__
249
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op,
250
+ int n, IndexType linearIndex, Offset offset) {
251
+ op(a.data[offset]);
252
+ }
253
+ };
254
+
255
+ template <typename Op,
256
+ typename scalar,
257
+ typename IndexType,
258
+ int ADims,
259
+ typename... Offsets>
260
+ struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offsets...> {
261
+ __device__ __forceinline__
262
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
263
+ IndexType linearIndex, Offsets... offsets) {
264
+ op(n, a.data[offsets]...);
265
+ }
266
+ };
267
+
268
+ template <typename Op,
269
+ typename scalar,
270
+ typename IndexType,
271
+ int ADims,
272
+ int step>
273
+ #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
274
+ C10_LAUNCH_BOUNDS_2(AT_APPLY_THREADS_PER_BLOCK, AT_APPLY_BLOCKS_PER_SM)
275
+ #endif
276
+ __global__ void kernelPointwiseApply1(detail::TensorInfo<scalar, IndexType> a,
277
+ IndexType totalElements, const Op op) {
278
+ for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
279
+ linearIndex < totalElements;
280
+ linearIndex += gridDim.x * blockDim.x * step) {
281
+ ApplyOp1<Op, scalar, IndexType, ADims, step>::apply(
282
+ a, op, ::min(step, static_cast<int>(totalElements - linearIndex)), linearIndex);
283
+ }
284
+ }
285
+
286
+
287
+ template <typename Op,
288
+ typename scalar1,
289
+ typename scalar2,
290
+ typename IndexType,
291
+ int ADims,
292
+ int BDims,
293
+ int remaining_steps,
294
+ typename... Offsets>
295
+ struct ApplyOp2 {
296
+ __device__ __forceinline__
297
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
298
+ detail::TensorInfo<scalar2, IndexType> &b,
299
+ const Op &op, int64_t n, IndexType linearIndex,
300
+ Offsets... aOffsets, Offsets... bOffsets) {
301
+ // Convert `linearIndex` into an offset of `a`
302
+ const IndexType aOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
303
+ detail::IndexToOffset<scalar1, IndexType, ADims>::get(linearIndex, a) : 0;
304
+
305
+ // Convert `linearIndex` into an offset of `b`
306
+ const IndexType bOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
307
+ detail::IndexToOffset<scalar2, IndexType, BDims>::get(linearIndex, b) : 0;
308
+
309
+ ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, remaining_steps - 1, const IndexType, Offsets...>::apply(
310
+ a, b, op, n, linearIndex + 1, aOffsets..., aOffset, bOffsets..., bOffset
311
+ );
312
+ }
313
+ };
314
+
315
+ // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
316
+ // We don't need to pass in how many elements need to processed in this case.
317
+ template <typename Op,
318
+ typename scalar1,
319
+ typename scalar2,
320
+ typename IndexType,
321
+ int ADims,
322
+ int BDims,
323
+ typename Offset>
324
+ struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offset> {
325
+ __device__ __forceinline__
326
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
327
+ detail::TensorInfo<scalar2, IndexType> &b,
328
+ const Op &op, int /*n*/, IndexType /*linearIndex*/,
329
+ Offset aOffset, Offset bOffset) {
330
+ op(a.data[aOffset], b.data[bOffset]);
331
+ }
332
+ };
333
+
334
+ template <typename Op,
335
+ typename scalar1,
336
+ typename scalar2,
337
+ typename IndexType,
338
+ int ADims,
339
+ int BDims,
340
+ typename... Offsets>
341
+ struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offsets...> {
342
+ __device__ __forceinline__
343
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
344
+ detail::TensorInfo<scalar2, IndexType> &b,
345
+ const Op &op, int n, IndexType linearIndex,
346
+ Offsets... aOffsets, Offsets... bOffsets) {
347
+ op(n, a.data[aOffsets]..., b.data[bOffsets]...);
348
+ }
349
+ };
350
+
351
+ template <typename Op,
352
+ typename scalar1,
353
+ typename scalar2,
354
+ typename IndexType,
355
+ int ADims, int BDims,
356
+ int step,
357
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
358
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
359
+ #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
360
+ C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm)
361
+ #endif
362
+ __global__ void
363
+ kernelPointwiseApply2(detail::TensorInfo<scalar1, IndexType> a,
364
+ detail::TensorInfo<scalar2, IndexType> b,
365
+ IndexType totalElements,
366
+ const Op op) {
367
+ for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
368
+ linearIndex < totalElements;
369
+ linearIndex += gridDim.x * blockDim.x * step) {
370
+ ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, step>::apply(
371
+ a, b, op, ::min(step, static_cast<int>(totalElements - linearIndex)),
372
+ linearIndex);
373
+ }
374
+ }
375
+
376
+ } // anonymous namespace
377
+
378
+ template <typename scalar1, typename scalar2, int step, typename Op,
379
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
380
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
381
+ inline bool CUDA_tensor_apply2(at::TensorBase a,
382
+ at::TensorBase b,
383
+ const Op op,
384
+ TensorArgType aType = TensorArgType::ReadWrite,
385
+ TensorArgType bType = TensorArgType::ReadOnly) {
386
+ TORCH_CHECK(a.device().is_cuda() && b.device().is_cuda(),
387
+ "CUDA_tensor_apply2: Expected tensors to have CUDA DeviceType, but got "
388
+ "tensors with type ", a.device().type(), " and ", b.device().type());
389
+ int64_t totalElements = a.numel();
390
+
391
+ if (totalElements != b.numel()) {
392
+ return false;
393
+ }
394
+
395
+ if (a.dim() > MAX_TENSORINFO_DIMS ||
396
+ b.dim() > MAX_TENSORINFO_DIMS) {
397
+ return false;
398
+ }
399
+
400
+ if (a.numel() == 0) {
401
+ // Empty tensor; do nothing
402
+ return true;
403
+ }
404
+ const dim3 block = getApplyBlock(max_threads_per_block);
405
+
406
+ dim3 grid;
407
+ auto curDevice = current_device();
408
+ if (curDevice == -1) return false;
409
+ if (!getApplyGrid<step>(totalElements, grid, curDevice, max_threads_per_block)) {
410
+ return false;
411
+ }
412
+
413
+ /*
414
+ Expands readable/writable tensors whose indices may be "overlapped."
415
+ This ensures that each element of the tensor is operated on once and only
416
+ once.
417
+ */
418
+ TensorBase oldA;
419
+ TensorBase oldB;
420
+
421
+ if (aType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(a)) {
422
+ // Must perform in contiguous space
423
+ oldA = std::exchange(a, a.contiguous());
424
+ }
425
+ if (bType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(b)) {
426
+ // Must perform in contiguous space
427
+ oldB = std::exchange(b, b.contiguous());
428
+ }
429
+
430
+ // It is possible that the tensor dimensions are able to be collapsed,
431
+ // and thus we can reduce the actual code complexity of the copy by
432
+ // exploiting this knowledge statically, since the div/mod is the
433
+ // most expensive part of the operation, more so than memory accesses.
434
+ // For instance, when copying a non-contiguous to a contiguous tensor
435
+ // (or vice versa), the contiguous tensor can be collapsed to one
436
+ // dimension, and the loop to translate the linear index to the array
437
+ // index can be similarly collapsed. That is what this unrolling is for.
438
+
439
+ #define HANDLE_CASE(TYPE, A, B) \
440
+ kernelPointwiseApply2<Op, \
441
+ scalar1, \
442
+ scalar2, \
443
+ TYPE, A, B, step, \
444
+ max_threads_per_block, \
445
+ min_blocks_per_sm> \
446
+ <<<grid, block, 0, at::cuda::getCurrentCUDAStream(curDevice)>>>( \
447
+ aInfo, bInfo, static_cast<TYPE>(totalElements), op); \
448
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
449
+
450
+ #define HANDLE_B_CASE(TYPE, A, B) { \
451
+ switch (B) { \
452
+ case 1: \
453
+ HANDLE_CASE(TYPE, A, 1); \
454
+ break; \
455
+ case 2: \
456
+ HANDLE_CASE(TYPE, A, 2); \
457
+ break; \
458
+ default: \
459
+ HANDLE_CASE(TYPE, A, -1); \
460
+ break; \
461
+ } \
462
+ }
463
+
464
+ #define HANDLE_A_CASE(TYPE, A, B) { \
465
+ switch (A) { \
466
+ case 1: \
467
+ HANDLE_B_CASE(TYPE, 1, B); \
468
+ break; \
469
+ case 2: \
470
+ HANDLE_B_CASE(TYPE, 2, B); \
471
+ break; \
472
+ default: \
473
+ HANDLE_B_CASE(TYPE, -1, B); \
474
+ break; \
475
+ } \
476
+ }
477
+
478
+ if (detail::canUse32BitIndexMath(a) &&
479
+ detail::canUse32BitIndexMath(b)) {
480
+ detail::TensorInfo<scalar1, unsigned int> aInfo =
481
+ detail::getTensorInfo<scalar1, unsigned int>(a);
482
+
483
+ detail::TensorInfo<scalar2, unsigned int> bInfo =
484
+ detail::getTensorInfo<scalar2, unsigned int>(b);
485
+ rearrangeDims(&aInfo, &bInfo);
486
+ aInfo.collapseDims();
487
+ bInfo.collapseDims();
488
+
489
+ HANDLE_A_CASE(unsigned int, aInfo.dims, bInfo.dims);
490
+ } else {
491
+ detail::TensorInfo<scalar1, uint64_t> aInfo =
492
+ detail::getTensorInfo<scalar1, uint64_t>(a);
493
+
494
+ detail::TensorInfo<scalar2, uint64_t> bInfo =
495
+ detail::getTensorInfo<scalar2, uint64_t>(b);
496
+ rearrangeDims(&aInfo, &bInfo);
497
+ aInfo.collapseDims();
498
+ bInfo.collapseDims();
499
+
500
+ /*
501
+ Only instantiates the all 1D special case and the fallback all nD case for
502
+ large (64-bit indexed) tensors to reduce compilation time.
503
+ */
504
+ if (aInfo.dims == 1 && bInfo.dims == 1) {
505
+ HANDLE_CASE(uint64_t, 1, 1);
506
+ } else {
507
+ HANDLE_CASE(uint64_t, -1, -1);
508
+ }
509
+ }
510
+ #undef HANDLE_CASE
511
+ #undef HANDLE_B_CASE
512
+ #undef HANDLE_A_CASE
513
+
514
+ if (oldA.defined()) {
515
+ at::native::copy_ignoring_overlaps(oldA, a);
516
+ }
517
+
518
+ if (oldB.defined()) {
519
+ at::native::copy_ignoring_overlaps(oldB, b);
520
+ }
521
+
522
+ return true;
523
+ }
524
+
525
+ /* Provides default step = 1 to CUDA_tensor_apply2. */
526
+ template <typename scalar1, typename scalar2, typename Op,
527
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
528
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
529
+ inline bool CUDA_tensor_apply2(const at::TensorBase &a,
530
+ const at::TensorBase &b,
531
+ const Op op,
532
+ TensorArgType aType = TensorArgType::ReadWrite,
533
+ TensorArgType bType = TensorArgType::ReadOnly) {
534
+ return CUDA_tensor_apply2<scalar1, scalar2, 1, Op,
535
+ max_threads_per_block, min_blocks_per_sm>(a, b, op, aType, bType);
536
+ }
537
+
538
+ } // namespace at::cuda
539
+
540
+ #else
541
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
542
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDABlas.h ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ /*
4
+ Provides a subset of CUDA BLAS functions as templates:
5
+
6
+ gemm<Dtype>(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c,
7
+ ldc)
8
+
9
+ gemv<Dtype>(transa, m, n, alpha, a, lda, x, incx, beta, y, incy)
10
+
11
+ dot<Dtype>(n, x, incx, y, incy, result)
12
+
13
+ where Dtype is double, float, at::Half or at::BFloat16 (ROCm, NOT for dot).
14
+ The functions are available in at::cuda::blas namespace.
15
+ */
16
+
17
+ #include <ATen/cuda/CUDAContext.h>
18
+ #include <ATen/BlasBackend.h>
19
+ #include <ATen/OpMathType.h>
20
+
21
+ namespace at::cuda::blas {
22
+
23
+ // RAII guard that sets the CuBLAS pointer mode and restores it to
24
+ // its previous value when the guard is destroyed
25
+ class PointerModeGuard {
26
+ public:
27
+ PointerModeGuard(cublasHandle_t handle, cublasPointerMode_t mode) :
28
+ handle(handle) {
29
+ TORCH_CUDABLAS_CHECK(cublasGetPointerMode(handle, &previous_mode));
30
+ TORCH_CUDABLAS_CHECK(cublasSetPointerMode(handle, mode));
31
+ }
32
+
33
+ ~PointerModeGuard() {
34
+ cublasSetPointerMode(handle, previous_mode);
35
+ }
36
+
37
+ private:
38
+ cublasHandle_t handle;
39
+ cublasPointerMode_t previous_mode{};
40
+ };
41
+
42
+ /* LEVEL 3 BLAS FUNCTIONS */
43
+
44
+ #define CUDABLAS_GEMM_ARGTYPES(Dtype) CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, Dtype)
45
+
46
+ #define CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype) \
47
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
48
+ const Dtype *a, int64_t lda, const Dtype *b, int64_t ldb, at::opmath_type<Dtype> beta,\
49
+ C_Dtype *c, int64_t ldc
50
+
51
+ #define CUDABLAS_GEMM_ARGS(Dtype) transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc
52
+
53
+ #define CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT \
54
+ ((std::is_same<Dtype, at::Half>::value || std::is_same<Dtype, at::BFloat16>::value) && std::is_same<C_Dtype, float>::value)
55
+
56
+ template <typename Dtype, typename C_Dtype = Dtype, typename std::enable_if<!CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT, Dtype>::type* = nullptr>
57
+ inline void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) {
58
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm: not implemented");
59
+ }
60
+
61
+ template <typename Dtype, typename C_Dtype, typename std::enable_if<CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT, Dtype>::type* = nullptr>
62
+ void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype));
63
+
64
+ template <>
65
+ void gemm<double>(CUDABLAS_GEMM_ARGTYPES(double));
66
+ template <>
67
+ void gemm<float>(CUDABLAS_GEMM_ARGTYPES(float));
68
+ template <>
69
+ void gemm<c10::complex<double>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<double>));
70
+ template <>
71
+ void gemm<c10::complex<float>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<float>));
72
+ template <>
73
+ void gemm<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
74
+ template <>
75
+ void gemm<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
76
+ template<>
77
+ void gemm<at::Half, float>(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float));
78
+ template<>
79
+ void gemm<at::BFloat16, float>(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float));
80
+
81
+ template <typename Dtype, typename C_Dtype = Dtype>
82
+ inline void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) {
83
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm_internal: not implemented");
84
+ }
85
+
86
+ template <>
87
+ void gemm_internal<double>(CUDABLAS_GEMM_ARGTYPES(double));
88
+ template <>
89
+ void gemm_internal<float>(CUDABLAS_GEMM_ARGTYPES(float));
90
+ template <>
91
+ void gemm_internal<c10::complex<double>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<double>));
92
+ template <>
93
+ void gemm_internal<c10::complex<float>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<float>));
94
+ template <>
95
+ void gemm_internal<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
96
+ template <>
97
+ void gemm_internal<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
98
+ template<>
99
+ void gemm_internal<at::Half, float>(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float));
100
+ template<>
101
+ void gemm_internal<at::BFloat16, float>(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float));
102
+
103
+ enum GEMMAndBiasActivationEpilogue {
104
+ None,
105
+ RELU,
106
+ GELU,
107
+ };
108
+
109
+ // NOTE: GELU activation is not supported prior to CUDA 11.4 and will
110
+ // do nothing if passed in that case.
111
+ template <typename Dtype, typename C_Dtype = Dtype>
112
+ bool gemm_and_bias(
113
+ bool transpose_mat1,
114
+ bool transpose_mat2,
115
+ int64_t m,
116
+ int64_t n,
117
+ int64_t k,
118
+ at::opmath_type<Dtype> alpha_val,
119
+ const Dtype* mat1_ptr,
120
+ int64_t mat1_ld,
121
+ const Dtype* mat2_ptr,
122
+ int64_t mat2_ld,
123
+ const Dtype* bias,
124
+ C_Dtype* result_ptr,
125
+ int64_t result_ld,
126
+ GEMMAndBiasActivationEpilogue activation = GEMMAndBiasActivationEpilogue::None);
127
+
128
+ void int8_gemm(
129
+ bool transpose_mat1,
130
+ bool transpose_mat2,
131
+ int64_t m,
132
+ int64_t n,
133
+ int64_t k,
134
+ const int8_t* mat1_ptr,
135
+ int64_t mat1_ld,
136
+ const int8_t* mat2_ptr,
137
+ int64_t mat2_ld,
138
+ int32_t* result_ptr,
139
+ int64_t result_ld);
140
+
141
+ void scaled_gemm(
142
+ char transa,
143
+ char transb,
144
+ int64_t m,
145
+ int64_t n,
146
+ int64_t k,
147
+ const void* mat1_ptr,
148
+ const void* mat1_scale_ptr,
149
+ int64_t mat1_ld,
150
+ ScalarType mat1_dtype,
151
+ ScalarType mat1_scale_dtype,
152
+ at::blas::ScalingType mat1_scaling_type,
153
+ const void* mat2_ptr,
154
+ const void* mat2_scale_ptr,
155
+ int64_t mat2_ld,
156
+ ScalarType mat2_dtype,
157
+ ScalarType mat2_scale_dtype,
158
+ at::blas::ScalingType mat2_scaling_type,
159
+ const void* bias_ptr,
160
+ ScalarType bias_dtype,
161
+ void* result_ptr,
162
+ const void* result_scale_ptr,
163
+ int64_t result_ld,
164
+ ScalarType result_dtype,
165
+ bool use_fast_accum,
166
+ const std::optional<Tensor>& alpha);
167
+
168
+ #define CUDABLAS_BGEMM_ARGTYPES(Dtype) CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, Dtype)
169
+
170
+ #define CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype) \
171
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
172
+ const Dtype *a, int64_t lda, int64_t stridea, \
173
+ const Dtype *b, int64_t ldb, int64_t strideb, \
174
+ at::opmath_type<Dtype> beta, C_Dtype *c, int64_t ldc, int64_t stridec, int64_t num_batches
175
+
176
+ #define CUDABLAS_BGEMM_ARGS(Dtype) \
177
+ transa, transb, m, n, k, alpha, a, lda, stridea, b, ldb, strideb, beta, c, ldc, stridec, num_batches
178
+
179
+ template <typename Dtype, typename C_Dtype = Dtype, typename std::enable_if<!CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT, Dtype>::type* = nullptr>
180
+ inline void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) {
181
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm: not implemented");
182
+ }
183
+
184
+ template <typename Dtype, typename C_Dtype, typename std::enable_if<CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT, Dtype>::type* = nullptr>
185
+ void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype));
186
+
187
+ template <>
188
+ void bgemm<double>(CUDABLAS_BGEMM_ARGTYPES(double));
189
+ template <>
190
+ void bgemm<float>(CUDABLAS_BGEMM_ARGTYPES(float));
191
+ template <>
192
+ void bgemm<c10::complex<double>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<double>));
193
+ template <>
194
+ void bgemm<c10::complex<float>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<float>));
195
+ template <>
196
+ void bgemm<at::Half>(CUDABLAS_BGEMM_ARGTYPES(at::Half));
197
+ template <>
198
+ void bgemm<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
199
+ template<>
200
+ void bgemm<at::Half, float>(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float));
201
+ template<>
202
+ void bgemm<at::BFloat16, float>(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float));
203
+
204
+ template <typename Dtype, typename C_Dtype = Dtype>
205
+ inline void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) {
206
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm_internal: not implemented");
207
+ }
208
+
209
+ template <>
210
+ void bgemm_internal<double>(CUDABLAS_BGEMM_ARGTYPES(double));
211
+ template <>
212
+ void bgemm_internal<float>(CUDABLAS_BGEMM_ARGTYPES(float));
213
+ template <>
214
+ void bgemm_internal<c10::complex<double>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<double>));
215
+ template <>
216
+ void bgemm_internal<c10::complex<float>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<float>));
217
+ template <>
218
+ void bgemm_internal<at::Half>(CUDABLAS_BGEMM_ARGTYPES(at::Half));
219
+ template <>
220
+ void bgemm_internal<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
221
+ template<>
222
+ void bgemm_internal<at::Half, float>(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float));
223
+ template<>
224
+ void bgemm_internal<at::BFloat16, float>(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float));
225
+
226
+ #define CUDABLAS_TRSM_ARGTYPES(Dtype) \
227
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
228
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
229
+ const Dtype *alpha, const Dtype *A, int lda, Dtype *B, int ldb
230
+
231
+ template <typename Dtype>
232
+ inline void trsm(CUDABLAS_TRSM_ARGTYPES(Dtype)) {
233
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsm: not implemented");
234
+ }
235
+
236
+ template <>
237
+ TORCH_CUDA_CU_API void trsm<float>(CUDABLAS_TRSM_ARGTYPES(float));
238
+ template <>
239
+ TORCH_CUDA_CU_API void trsm<double>(CUDABLAS_TRSM_ARGTYPES(double));
240
+ template <>
241
+ TORCH_CUDA_CU_API void trsm<c10::complex<float>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<float>));
242
+ template <>
243
+ TORCH_CUDA_CU_API void trsm<c10::complex<double>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<double>));
244
+
245
+ #define CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype) \
246
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
247
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
248
+ const Dtype *alpha, Dtype *A[], int lda, Dtype *B[], int ldb, \
249
+ int batchCount
250
+
251
+ template <typename Dtype>
252
+ inline void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype)) {
253
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsmBatched: not implemented");
254
+ }
255
+
256
+ template <>
257
+ TORCH_CUDA_CU_API void trsmBatched<float>(CUDABLAS_TRSM_BATCHED_ARGTYPES(float));
258
+ template <>
259
+ TORCH_CUDA_CU_API void trsmBatched<double>(CUDABLAS_TRSM_BATCHED_ARGTYPES(double));
260
+ template <>
261
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<float>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<float>));
262
+ template <>
263
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<double>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<double>));
264
+
265
+ /* LEVEL 2 BLAS FUNCTIONS */
266
+
267
+ #define CUDABLAS_GEMV_ARGTYPES(Dtype) \
268
+ char trans, int64_t m, int64_t n, Dtype alpha, const Dtype *a, int64_t lda, \
269
+ const Dtype *x, int64_t incx, Dtype beta, Dtype *y, int64_t incy
270
+
271
+ template <typename Dtype>
272
+ inline void gemv(CUDABLAS_GEMV_ARGTYPES(Dtype)) {
273
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::gemv: not implemented");
274
+ }
275
+
276
+ template <>
277
+ void gemv<double>(CUDABLAS_GEMV_ARGTYPES(double));
278
+ template <>
279
+ void gemv<float>(CUDABLAS_GEMV_ARGTYPES(float));
280
+ template <>
281
+ void gemv<c10::complex<double>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<double>));
282
+ template <>
283
+ void gemv<c10::complex<float>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<float>));
284
+ template <>
285
+ void gemv<at::Half>(CUDABLAS_GEMV_ARGTYPES(at::Half));
286
+ template <>
287
+ void gemv<at::BFloat16>(CUDABLAS_GEMV_ARGTYPES(at::BFloat16));
288
+
289
+ /* LEVEL 1 BLAS FUNCTIONS */
290
+
291
+ #define CUDABLAS_DOT_ARGTYPES(Dtype) \
292
+ cublasHandle_t handle, int n, const Dtype *x, int incx, const Dtype *y, \
293
+ int incy, Dtype *result
294
+
295
+ template <typename Dtype>
296
+ inline void dot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
297
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::dot: not implemented");
298
+ }
299
+
300
+ template <>
301
+ void dot<double>(CUDABLAS_DOT_ARGTYPES(double));
302
+ template <>
303
+ void dot<float>(CUDABLAS_DOT_ARGTYPES(float));
304
+ template <>
305
+ void dot<at::Half>(CUDABLAS_DOT_ARGTYPES(at::Half));
306
+ template <>
307
+ void dot<at::BFloat16>(CUDABLAS_DOT_ARGTYPES(at::BFloat16));
308
+ template <>
309
+ void dot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
310
+ template <>
311
+ void dot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
312
+
313
+ template <typename Dtype>
314
+ inline void vdot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
315
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::vdot: not implemented");
316
+ }
317
+
318
+ template <>
319
+ void vdot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
320
+ template <>
321
+ void vdot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
322
+
323
+ #define CUDABLAS_GETRS_ARGTYPES(Dtype) \
324
+ cublasHandle_t handle, cublasOperation_t trans, \
325
+ int n, int nrhs, Dtype** dA_array, int lda, int* ipiv_array, \
326
+ Dtype** dB_array, int ldb, int* info_array, int batchsize
327
+
328
+ #define CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype) \
329
+ cublasHandle_t handle, int m, int n, Dtype **A_array, int lda, \
330
+ Dtype **tau_array, int *info, int batchsize
331
+
332
+ #define CUDABLAS_GETRF_ARGTYPES(Dtype) \
333
+ int n, Dtype** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize
334
+
335
+ #define CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype) \
336
+ cublasHandle_t handle, cublasOperation_t trans, \
337
+ int m, int n, int nrhs, Dtype** dA_array, int ldda, \
338
+ Dtype** dC_array, int lddc, int* info, int *devInfoArray, int batchSize
339
+
340
+ template<class Dtype>
341
+ void getrsBatched(CUDABLAS_GETRS_ARGTYPES(Dtype)) {
342
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::getrsBatched: not implemented");
343
+ }
344
+ template<>
345
+ TORCH_CUDA_CU_API void getrsBatched<float>(CUDABLAS_GETRS_ARGTYPES(float));
346
+ template<>
347
+ TORCH_CUDA_CU_API void getrsBatched<double>(CUDABLAS_GETRS_ARGTYPES(double));
348
+ template<>
349
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<float>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<float>));
350
+ template<>
351
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<double>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<double>));
352
+
353
+ template <class Dtype>
354
+ void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype)) {
355
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::geqrfBatched: not implemented");
356
+ }
357
+ template <>
358
+ TORCH_CUDA_CU_API void geqrfBatched<float>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(float));
359
+ template <>
360
+ TORCH_CUDA_CU_API void geqrfBatched<double>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(double));
361
+ template <>
362
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<double>>(
363
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<double>));
364
+ template <>
365
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<float>>(
366
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<float>));
367
+
368
+ template<class Dtype>
369
+ void getrfBatched(CUDABLAS_GETRF_ARGTYPES(Dtype)) {
370
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::getrfBatched: not implemented");
371
+ }
372
+ template<>
373
+ TORCH_CUDA_CU_API void getrfBatched<float>(CUDABLAS_GETRF_ARGTYPES(float));
374
+ template<>
375
+ TORCH_CUDA_CU_API void getrfBatched<double>(CUDABLAS_GETRF_ARGTYPES(double));
376
+ template<>
377
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<double>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<double>));
378
+ template<>
379
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<float>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<float>));
380
+
381
+ template <class Dtype>
382
+ void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype)) {
383
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::gelsBatched: not implemented");
384
+ }
385
+ template<>
386
+ TORCH_CUDA_CU_API void gelsBatched<double>(CUDABLAS_GELS_BATCHED_ARGTYPES(double));
387
+ template<>
388
+ TORCH_CUDA_CU_API void gelsBatched<float>(CUDABLAS_GELS_BATCHED_ARGTYPES(float));
389
+ template<>
390
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<double>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<double>));
391
+ template<>
392
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<float>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<float>));
393
+
394
+ } // namespace at::cuda::blas
395
+
396
+ #else
397
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
398
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAConfig.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // Test these using #if AT_CUDNN_ENABLED(), not #ifdef, so that it's
5
+ // obvious if you forgot to include Config.h
6
+ // c.f. https://stackoverflow.com/questions/33759787/generating-an-error-if-checked-boolean-macro-is-not-defined
7
+ //
8
+ // NB: This header MUST NOT be included from other headers; it should
9
+ // only be included from C++ files.
10
+ #define AT_CUDNN_ENABLED() 1
11
+ #define AT_CUSPARSELT_ENABLED() 1
12
+ #define AT_HIPSPARSELT_ENABLED() 0
13
+ #define AT_ROCM_ENABLED() 0
14
+ #define AT_MAGMA_ENABLED() 1
15
+
16
+ // Needed for hipMAGMA to correctly identify implementation
17
+ #if (AT_ROCM_ENABLED() && AT_MAGMA_ENABLED())
18
+ #define HAVE_HIP 1
19
+ #endif
20
+
21
+ #define NVCC_FLAGS_EXTRA "-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90"
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAContext.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAContextLight.h>
5
+
6
+ // Preserved for BC, as many files depend on these includes
7
+ #include <ATen/Context.h>
8
+ #include <c10/cuda/CUDAStream.h>
9
+ #include <c10/util/Logging.h>
10
+ #include <ATen/cuda/Exceptions.h>
11
+
12
+ #else
13
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
14
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAContextLight.h ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ // Light-weight version of CUDAContext.h with fewer transitive includes
4
+
5
+ #include <cstdint>
6
+ #include <map>
7
+ #include <shared_mutex>
8
+
9
+ #include <cuda_runtime_api.h>
10
+ #include <cusparse.h>
11
+ #include <cublas_v2.h>
12
+
13
+ // cublasLT was introduced in CUDA 10.1 but we enable only for 11.1 that also
14
+ // added bf16 support
15
+ #include <cublasLt.h>
16
+
17
+ #ifdef CUDART_VERSION
18
+ #include <cusolverDn.h>
19
+ #endif
20
+
21
+ #if defined(USE_CUDSS)
22
+ #include <cudss.h>
23
+ #endif
24
+
25
+ #if defined(USE_ROCM)
26
+ #include <hipsolver/hipsolver.h>
27
+ #endif
28
+
29
+ #include <c10/core/Allocator.h>
30
+ #include <c10/cuda/CUDAFunctions.h>
31
+
32
+ namespace c10 {
33
+ struct Allocator;
34
+ }
35
+
36
+ namespace at::cuda {
37
+
38
+ /*
39
+ A common CUDA interface for ATen.
40
+
41
+ This interface is distinct from CUDAHooks, which defines an interface that links
42
+ to both CPU-only and CUDA builds. That interface is intended for runtime
43
+ dispatch and should be used from files that are included in both CPU-only and
44
+ CUDA builds.
45
+
46
+ CUDAContext, on the other hand, should be preferred by files only included in
47
+ CUDA builds. It is intended to expose CUDA functionality in a consistent
48
+ manner.
49
+
50
+ This means there is some overlap between the CUDAContext and CUDAHooks, but
51
+ the choice of which to use is simple: use CUDAContext when in a CUDA-only file,
52
+ use CUDAHooks otherwise.
53
+
54
+ Note that CUDAContext simply defines an interface with no associated class.
55
+ It is expected that the modules whose functions compose this interface will
56
+ manage their own state. There is only a single CUDA context/state.
57
+ */
58
+
59
+ /**
60
+ * DEPRECATED: use device_count() instead
61
+ */
62
+ inline int64_t getNumGPUs() {
63
+ return c10::cuda::device_count();
64
+ }
65
+
66
+ /**
67
+ * CUDA is available if we compiled with CUDA, and there are one or more
68
+ * devices. If we compiled with CUDA but there is a driver problem, etc.,
69
+ * this function will report CUDA is not available (rather than raise an error.)
70
+ */
71
+ inline bool is_available() {
72
+ return c10::cuda::device_count() > 0;
73
+ }
74
+
75
+ TORCH_CUDA_CPP_API cudaDeviceProp* getCurrentDeviceProperties();
76
+
77
+ TORCH_CUDA_CPP_API int warp_size();
78
+
79
+ TORCH_CUDA_CPP_API cudaDeviceProp* getDeviceProperties(c10::DeviceIndex device);
80
+
81
+ TORCH_CUDA_CPP_API bool canDeviceAccessPeer(
82
+ c10::DeviceIndex device,
83
+ c10::DeviceIndex peer_device);
84
+
85
+ TORCH_CUDA_CPP_API c10::Allocator* getCUDADeviceAllocator();
86
+
87
+ /* Handles */
88
+ TORCH_CUDA_CPP_API cusparseHandle_t getCurrentCUDASparseHandle();
89
+ TORCH_CUDA_CPP_API cublasHandle_t getCurrentCUDABlasHandle();
90
+ TORCH_CUDA_CPP_API cublasLtHandle_t getCurrentCUDABlasLtHandle();
91
+
92
+ TORCH_CUDA_CPP_API void clearCublasWorkspaces();
93
+ struct WorkspaceMapWithMutex {
94
+ std::map<std::tuple<void*, void*>, at::DataPtr> map;
95
+ std::shared_mutex mutex;
96
+ };
97
+
98
+ TORCH_CUDA_CPP_API WorkspaceMapWithMutex& cublas_handle_stream_to_workspace();
99
+ TORCH_CUDA_CPP_API WorkspaceMapWithMutex& cublaslt_handle_stream_to_workspace();
100
+ TORCH_CUDA_CPP_API size_t getChosenWorkspaceSize();
101
+ TORCH_CUDA_CPP_API size_t getCUDABlasLtWorkspaceSize();
102
+ TORCH_CUDA_CPP_API void* getCUDABlasLtWorkspace();
103
+
104
+ #if defined(CUDART_VERSION) || defined(USE_ROCM)
105
+ TORCH_CUDA_CPP_API cusolverDnHandle_t getCurrentCUDASolverDnHandle();
106
+ #endif
107
+
108
+ #if defined(USE_CUDSS)
109
+ TORCH_CUDA_CPP_API cudssHandle_t getCurrentCudssHandle();
110
+ #endif
111
+
112
+ } // namespace at::cuda
113
+
114
+ #else
115
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
116
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDADataType.h ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/ScalarType.h>
5
+
6
+ #include <cuda.h>
7
+ #include <library_types.h>
8
+
9
+ namespace at::cuda {
10
+
11
+ template <typename scalar_t>
12
+ cudaDataType getCudaDataType() {
13
+ static_assert(false && sizeof(scalar_t), "Cannot convert type to cudaDataType.");
14
+ return {};
15
+ }
16
+
17
+ template<> inline cudaDataType getCudaDataType<at::Half>() {
18
+ return CUDA_R_16F;
19
+ }
20
+ template<> inline cudaDataType getCudaDataType<float>() {
21
+ return CUDA_R_32F;
22
+ }
23
+ template<> inline cudaDataType getCudaDataType<double>() {
24
+ return CUDA_R_64F;
25
+ }
26
+ template<> inline cudaDataType getCudaDataType<c10::complex<c10::Half>>() {
27
+ return CUDA_C_16F;
28
+ }
29
+ template<> inline cudaDataType getCudaDataType<c10::complex<float>>() {
30
+ return CUDA_C_32F;
31
+ }
32
+ template<> inline cudaDataType getCudaDataType<c10::complex<double>>() {
33
+ return CUDA_C_64F;
34
+ }
35
+
36
+ template<> inline cudaDataType getCudaDataType<uint8_t>() {
37
+ return CUDA_R_8U;
38
+ }
39
+ template<> inline cudaDataType getCudaDataType<int8_t>() {
40
+ return CUDA_R_8I;
41
+ }
42
+ template<> inline cudaDataType getCudaDataType<int>() {
43
+ return CUDA_R_32I;
44
+ }
45
+
46
+ template<> inline cudaDataType getCudaDataType<int16_t>() {
47
+ return CUDA_R_16I;
48
+ }
49
+ template<> inline cudaDataType getCudaDataType<int64_t>() {
50
+ return CUDA_R_64I;
51
+ }
52
+ template<> inline cudaDataType getCudaDataType<at::BFloat16>() {
53
+ return CUDA_R_16BF;
54
+ }
55
+
56
+ inline cudaDataType ScalarTypeToCudaDataType(const c10::ScalarType& scalar_type) {
57
+ switch (scalar_type) {
58
+ case c10::ScalarType::Byte:
59
+ return CUDA_R_8U;
60
+ case c10::ScalarType::Char:
61
+ return CUDA_R_8I;
62
+ case c10::ScalarType::Int:
63
+ return CUDA_R_32I;
64
+ case c10::ScalarType::Half:
65
+ return CUDA_R_16F;
66
+ case c10::ScalarType::Float:
67
+ return CUDA_R_32F;
68
+ case c10::ScalarType::Double:
69
+ return CUDA_R_64F;
70
+ case c10::ScalarType::ComplexHalf:
71
+ return CUDA_C_16F;
72
+ case c10::ScalarType::ComplexFloat:
73
+ return CUDA_C_32F;
74
+ case c10::ScalarType::ComplexDouble:
75
+ return CUDA_C_64F;
76
+ case c10::ScalarType::Short:
77
+ return CUDA_R_16I;
78
+ case c10::ScalarType::Long:
79
+ return CUDA_R_64I;
80
+ case c10::ScalarType::BFloat16:
81
+ return CUDA_R_16BF;
82
+ #if !defined(USE_ROCM) || ROCM_VERSION >= 60300
83
+ case c10::ScalarType::Float8_e4m3fn:
84
+ return CUDA_R_8F_E4M3;
85
+ case c10::ScalarType::Float8_e5m2:
86
+ return CUDA_R_8F_E5M2;
87
+ #endif
88
+ #if defined(USE_ROCM)
89
+ case c10::ScalarType::Float8_e4m3fnuz:
90
+ return HIP_R_8F_E4M3_FNUZ;
91
+ case c10::ScalarType::Float8_e5m2fnuz:
92
+ return HIP_R_8F_E5M2_FNUZ;
93
+ #endif
94
+ #if (defined(CUDA_VERSION) && CUDA_VERSION >= 12080) || (defined(USE_ROCM) && ROCM_VERSION >= 70000)
95
+ case c10::ScalarType::Float4_e2m1fn_x2:
96
+ return CUDA_R_4F_E2M1;
97
+ #endif
98
+ default:
99
+ TORCH_INTERNAL_ASSERT(false, "Cannot convert ScalarType ", scalar_type, " to cudaDataType.")
100
+ }
101
+ }
102
+
103
+ } // namespace at::cuda
104
+
105
+ #else
106
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
107
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDADevice.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/Exceptions.h>
5
+
6
+ #include <cuda.h>
7
+ #include <cuda_runtime.h>
8
+
9
+ namespace at::cuda {
10
+
11
+ inline Device getDeviceFromPtr(void* ptr) {
12
+ cudaPointerAttributes attr{};
13
+
14
+ AT_CUDA_CHECK(cudaPointerGetAttributes(&attr, ptr));
15
+
16
+ #if !defined(USE_ROCM)
17
+ TORCH_CHECK(attr.type != cudaMemoryTypeUnregistered,
18
+ "The specified pointer resides on host memory and is not registered with any CUDA device.");
19
+ #endif
20
+
21
+ return {c10::DeviceType::CUDA, static_cast<DeviceIndex>(attr.device)};
22
+ }
23
+
24
+ } // namespace at::cuda
25
+
26
+ #else
27
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
28
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAEvent.h ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/ATenCUDAGeneral.h>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/cuda/Exceptions.h>
7
+ #include <c10/core/impl/GPUTrace.h>
8
+ #include <c10/cuda/CUDAGuard.h>
9
+ #include <c10/cuda/CUDAStream.h>
10
+ #include <c10/util/Exception.h>
11
+
12
+ #include <cuda_runtime_api.h>
13
+
14
+ #include <cstdint>
15
+ #include <utility>
16
+
17
+ /*
18
+ * `cudaEventExternal` is a torch-specific flag that is used to
19
+ * indicate that the CUDAEvent will be used only for synchronization
20
+ * with work outside of the cuda graph, rather than creation of
21
+ * cross-stream dependencies within a cuda graph. Resources:
22
+ * https://docs.nvidia.com/cuda/archive/12.9.0/cuda-c-programming-guide/index.html#cross-stream-dependencies-and-events
23
+ * https://docs.nvidia.com/cuda/archive/12.9.0/cuda-runtime-api/group__CUDART__TYPES.html#group__CUDART__TYPES_1g3457b81d1d32c6a00f6132fbc2693d47
24
+ * https://docs.nvidia.com/cuda/archive/12.9.0/cuda-runtime-api/group__CUDART__TYPES.html#group__CUDART__TYPES_1g0c23426b7252eaa9cef695859991304e
25
+ */
26
+ #define cudaEventExternal 0x08
27
+
28
+ namespace at::cuda {
29
+
30
+ /*
31
+ * CUDAEvents are movable not copyable wrappers around CUDA's events.
32
+ *
33
+ * CUDAEvents are constructed lazily when first recorded unless it is
34
+ * reconstructed from a cudaIpcEventHandle_t. The event has a device, and this
35
+ * device is acquired from the first recording stream. However, if reconstructed
36
+ * from a handle, the device should be explicitly specified; or if ipc_handle() is
37
+ * called before the event is ever recorded, it will use the current device.
38
+ * Later streams that record the event must match this device.
39
+ */
40
+ struct TORCH_CUDA_CPP_API CUDAEvent {
41
+ // Constructors
42
+ // Default value for `flags` is specified below - it's cudaEventDisableTiming
43
+ CUDAEvent() noexcept = default;
44
+ CUDAEvent(unsigned int flags) noexcept : flags_{flags} {}
45
+
46
+ CUDAEvent(
47
+ DeviceIndex device_index, const cudaIpcEventHandle_t* handle) : device_index_(device_index) {
48
+ CUDAGuard guard(device_index_);
49
+
50
+ AT_CUDA_CHECK(cudaIpcOpenEventHandle(&event_, *handle));
51
+ is_created_ = true;
52
+ }
53
+
54
+ // Note: event destruction done on creating device to avoid creating a
55
+ // CUDA context on other devices.
56
+ ~CUDAEvent() {
57
+ try {
58
+ if (is_created_) {
59
+ CUDAGuard guard(device_index_);
60
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
61
+ if (C10_UNLIKELY(interp)) {
62
+ (*interp)->trace_gpu_event_deletion(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
63
+ }
64
+ AT_CUDA_CHECK(cudaEventDestroy(event_));
65
+ }
66
+ } catch (...) { /* No throw */ }
67
+ }
68
+
69
+ CUDAEvent(const CUDAEvent&) = delete;
70
+ CUDAEvent& operator=(const CUDAEvent&) = delete;
71
+
72
+ CUDAEvent(CUDAEvent&& other) noexcept { moveHelper(std::move(other)); }
73
+ CUDAEvent& operator=(CUDAEvent&& other) noexcept {
74
+ if (this != &other) {
75
+ moveHelper(std::move(other));
76
+ }
77
+ return *this;
78
+ }
79
+
80
+ operator cudaEvent_t() const { return event(); }
81
+
82
+ // Less than operator (to allow use in sets)
83
+ friend bool operator<(const CUDAEvent& left, const CUDAEvent& right) {
84
+ return left.event_ < right.event_;
85
+ }
86
+
87
+ std::optional<at::Device> device() const {
88
+ if (is_created_) {
89
+ return at::Device(at::kCUDA, device_index_);
90
+ } else {
91
+ return {};
92
+ }
93
+ }
94
+
95
+ bool isCreated() const { return is_created_; }
96
+ DeviceIndex device_index() const {return device_index_;}
97
+ cudaEvent_t event() const { return event_; }
98
+
99
+ // Note: cudaEventQuery can be safely called from any device
100
+ bool query() const {
101
+ if (!is_created_) {
102
+ return true;
103
+ }
104
+
105
+ cudaError_t err = cudaEventQuery(event_);
106
+ if (err == cudaSuccess) {
107
+ return true;
108
+ } else if (err != cudaErrorNotReady) {
109
+ C10_CUDA_CHECK(err);
110
+ } else {
111
+ // ignore and clear the error if not ready
112
+ (void)cudaGetLastError();
113
+ }
114
+
115
+ return false;
116
+ }
117
+
118
+ void record() { record(getCurrentCUDAStream()); }
119
+
120
+ void recordOnce(const CUDAStream& stream) {
121
+ if (!was_recorded_) record(stream);
122
+ }
123
+
124
+ // Note: cudaEventRecord must be called on the same device as the event.
125
+ void record(const CUDAStream& stream) {
126
+ if (!is_created_) {
127
+ createEvent(stream.device_index());
128
+ }
129
+
130
+ TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_,
131
+ " does not match recording stream's device ", stream.device_index(), ".");
132
+ CUDAGuard guard(device_index_);
133
+
134
+ #ifndef USE_ROCM
135
+ // it is an error to use cudaEventRecordExternal when not doing stream capture
136
+ unsigned int flags = (c10::cuda::currentStreamCaptureStatusMayInitCtx() != c10::cuda::CaptureStatus::None && external_) ? cudaEventRecordExternal : cudaEventRecordDefault;
137
+ AT_CUDA_CHECK(cudaEventRecordWithFlags(event_, stream, flags));
138
+ #else
139
+ AT_CUDA_CHECK(cudaEventRecord(event_, stream));
140
+ #endif
141
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
142
+ if (C10_UNLIKELY(interp)) {
143
+ (*interp)->trace_gpu_event_record(at::kCUDA,
144
+ reinterpret_cast<uintptr_t>(event_),
145
+ reinterpret_cast<uintptr_t>(stream.stream())
146
+ );
147
+ }
148
+ was_recorded_ = true;
149
+ }
150
+
151
+ // Note: cudaStreamWaitEvent must be called on the same device as the stream.
152
+ // The event has no actual GPU resources associated with it.
153
+ void block(const CUDAStream& stream) {
154
+ if (is_created_) {
155
+ CUDAGuard guard(stream.device_index());
156
+ #ifndef USE_ROCM
157
+ // it is an error to use cudaEventWaitExternal when not doing stream capture
158
+ unsigned int flags = (c10::cuda::currentStreamCaptureStatusMayInitCtx() != c10::cuda::CaptureStatus::None && external_) ? cudaEventWaitExternal : cudaEventWaitDefault;
159
+ AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_, flags));
160
+ #else
161
+ AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_));
162
+ #endif
163
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
164
+ if (C10_UNLIKELY(interp)) {
165
+ (*interp)->trace_gpu_event_wait(at::kCUDA,
166
+ reinterpret_cast<uintptr_t>(event_),
167
+ reinterpret_cast<uintptr_t>(stream.stream())
168
+ );
169
+ }
170
+ }
171
+ }
172
+
173
+ // Note: cudaEventElapsedTime can be safely called from any device
174
+ float elapsed_time(const CUDAEvent& other) const {
175
+ TORCH_CHECK_VALUE(
176
+ !(flags_ & cudaEventDisableTiming) && !(other.flags_ & cudaEventDisableTiming),
177
+ "Both events must be created with argument 'enable_timing=True'.");
178
+ TORCH_CHECK_VALUE(
179
+ is_created_ && other.isCreated(),
180
+ "Both events must be recorded before calculating elapsed time.");
181
+ TORCH_CHECK(
182
+ query() && other.query(),
183
+ "Both events must be completed before calculating elapsed time.");
184
+
185
+ float time_ms = 0;
186
+ // We do not strictly have to set the device index to the same as our event,
187
+ // but if we don't and the current device is not initialized, it will
188
+ // create a new cuda context, which will consume a lot of memory.
189
+ CUDAGuard guard(device_index_);
190
+ // raise cudaErrorNotReady if either event is recorded but not yet completed
191
+ AT_CUDA_CHECK(cudaEventElapsedTime(&time_ms, event_, other.event_));
192
+ return time_ms;
193
+ }
194
+
195
+ // Note: cudaEventSynchronize can be safely called from any device
196
+ void synchronize() const {
197
+ if (is_created_) {
198
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
199
+ if (C10_UNLIKELY(interp)) {
200
+ (*interp)->trace_gpu_event_synchronization(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
201
+ }
202
+ AT_CUDA_CHECK(cudaEventSynchronize(event_));
203
+ }
204
+ }
205
+
206
+ // Note: cudaIpcGetEventHandle must be called on the same device as the event
207
+ void ipc_handle(cudaIpcEventHandle_t * handle) {
208
+ if (!is_created_) {
209
+ // this CUDAEvent object was initially constructed from flags but event_
210
+ // is not created yet.
211
+ createEvent(getCurrentCUDAStream().device_index());
212
+ }
213
+ CUDAGuard guard(device_index_);
214
+ AT_CUDA_CHECK(cudaIpcGetEventHandle(handle, event_));
215
+ }
216
+
217
+ private:
218
+ unsigned int flags_ = cudaEventDisableTiming;
219
+ bool is_created_ = false;
220
+ bool was_recorded_ = false;
221
+ bool external_ = false;
222
+ DeviceIndex device_index_ = -1;
223
+ cudaEvent_t event_{};
224
+
225
+ void createEvent(DeviceIndex device_index) {
226
+ external_ = (flags_ & cudaEventExternal) != 0;
227
+ #ifdef USE_ROCM
228
+ TORCH_CHECK(!external_, "External events are disallowed in rocm");
229
+ #endif
230
+ flags_ &= ~cudaEventExternal;
231
+ device_index_ = device_index;
232
+ CUDAGuard guard(device_index_);
233
+ AT_CUDA_CHECK(cudaEventCreateWithFlags(&event_, flags_));
234
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
235
+ if (C10_UNLIKELY(interp)) {
236
+ (*interp)->trace_gpu_event_creation(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
237
+ }
238
+ is_created_ = true;
239
+ }
240
+
241
+ void moveHelper(CUDAEvent&& other) {
242
+ // Transfer ownership of all state from other to this
243
+ flags_ = other.flags_;
244
+ is_created_ = other.is_created_;
245
+ was_recorded_ = other.was_recorded_;
246
+ external_ = other.external_;
247
+ device_index_ = other.device_index_;
248
+ event_ = other.event_;
249
+
250
+ // Reset other to a valid empty state to prevent double-free
251
+ // The moved-from object must not attempt to destroy the event
252
+ other.is_created_ = false;
253
+ other.event_ = cudaEvent_t{};
254
+ }
255
+ };
256
+
257
+ // EventPool - Thread-safe pool of CUDA events to avoid expensive cudaEventCreate
258
+ // calls. cudaEventCreate when concurrently invoked from multiple threads can be
259
+ // very expensive (especially on certain device/driver combinations).
260
+ using CUDAEventPtr =
261
+ std::unique_ptr<CUDAEvent, std::function<void(CUDAEvent*)>>;
262
+
263
+ class EventPool {
264
+ public:
265
+ EventPool() : pools_(at::cuda::device_count()) {}
266
+
267
+ CUDAEventPtr get(const DeviceIndex device) {
268
+ // If the device is invalid, return a default event and no pooling
269
+ if (device < 0 || device >= (DeviceIndex)pools_.size()) {
270
+ auto deleter = [](CUDAEvent* event) {
271
+ delete event;
272
+ };
273
+ return CUDAEventPtr(
274
+ std::make_unique<CUDAEvent>(cudaEventDisableTiming).release(), deleter);
275
+ }
276
+
277
+ auto& pool = pools_[device];
278
+
279
+ // Create a destructor that returns the event to the appropriate device pool
280
+ auto destructor = [&pool](CUDAEvent* event) noexcept {
281
+ if (event != nullptr) {
282
+ std::lock_guard<std::mutex> lock(pool.mutex_);
283
+ pool.event_pool_.emplace_back(event);
284
+ }
285
+ };
286
+
287
+ {
288
+ std::lock_guard<std::mutex> lock(pool.mutex_);
289
+ if (!pool.event_pool_.empty()) {
290
+ auto event = std::move(pool.event_pool_.back());
291
+ pool.event_pool_.pop_back();
292
+ return CUDAEventPtr(event.release(), destructor);
293
+ }
294
+ }
295
+
296
+ return CUDAEventPtr(
297
+ std::make_unique<CUDAEvent>(cudaEventDisableTiming).release(),
298
+ destructor);
299
+ }
300
+
301
+ void empty_cache() {
302
+ for (auto& pool : pools_) {
303
+ std::lock_guard<std::mutex> lock(pool.mutex_);
304
+ pool.event_pool_.clear();
305
+ }
306
+ }
307
+
308
+ void init_num_events(const size_t num_events) {
309
+ for (DeviceIndex device_idx = 0; device_idx < at::cuda::device_count(); ++device_idx) {
310
+ CUDAGuard device_guard(device_idx);
311
+ std::vector<CUDAEventPtr> temp_events;
312
+ temp_events.reserve(num_events);
313
+ for (size_t i = 0; i < num_events; ++i) {
314
+ auto event = get(device_idx);
315
+ // Record the event to ensure it's properly initialized
316
+ event->record();
317
+ temp_events.emplace_back(std::move(event));
318
+ }
319
+ // Events will be returned to pool when temp_events is destroyed
320
+ }
321
+ }
322
+
323
+ private:
324
+ struct alignas(64) PerDevicePool {
325
+ alignas(64) std::mutex mutex_;
326
+ std::vector<std::unique_ptr<CUDAEvent>> event_pool_;
327
+ };
328
+
329
+ std::vector<PerDevicePool> pools_;
330
+ };
331
+
332
+ } // namespace at::cuda
333
+
334
+ #else
335
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
336
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Context.h>
5
+ #include <ATen/core/Generator.h>
6
+ #include <ATen/core/TensorBase.h>
7
+ #include <ATen/cuda/PhiloxCudaState.h>
8
+ #include <atomic>
9
+ #include <memory>
10
+ #include <unordered_set>
11
+ namespace at {
12
+
13
+ namespace cuda {
14
+ struct CUDAGraph;
15
+ }
16
+
17
+ /**
18
+ * Note [CUDA Graph-safe RNG states]
19
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
+ *
21
+ * Strategy:
22
+ * ~~~~~~~~~
23
+ * (It helps to look at
24
+ * cuda/detail/PhiloxCudaStateRaw.cuh and
25
+ * cuda/detail/UnpackRaw.cuh
26
+ * while you read this.)
27
+ *
28
+ * A CUDA graph containing multiple RNG ops behaves like a
29
+ * single giant kernel from the perspective of ops external
30
+ * to the graph. During graph capture, logic in CUDAGeneratorImpl
31
+ * records the total of all offset increments that occur in the
32
+ * graphed region, and records the final total as the offset for
33
+ * the entire graph.
34
+ *
35
+ * When the graph reruns, the logic that reruns it
36
+ * increments this device's CUDA generator's offset
37
+ * by that total.
38
+ *
39
+ * Meanwhile, within the graph, at capture time, instead of
40
+ * populating PhiloxCudaStates with the uint64_t offset pulled
41
+ * directly from the global state, PhiloxCudaState uses a pointer
42
+ * to a one-element stream-local int64_t device tensor
43
+ * holding an initial offset value, and a uint64_t holding an
44
+ * intra-graph offset. (The intra-graph offset starts from zero
45
+ * when capture begins.) In each consumer kernel,
46
+ * at::cuda::philox::unpack computes the offset to use for this kernel
47
+ * as intra-graph offset + *initial offset.
48
+ *
49
+ * When the graph reruns, the logic that reruns it first
50
+ * fill_s the initial offset tensor with this device's
51
+ * CUDA generator's current offset.
52
+ *
53
+ * The control flow above ensures graphed execution is bitwise
54
+ * identical to eager execution as long as RNG ops are enqueued
55
+ * from a single thread, even if RNG ops and graphs containing
56
+ * RNG ops are enqueued and run simultaneously on multiple streams.
57
+ *
58
+ * Usage:
59
+ * ~~~~~~
60
+ * PhiloxCudaState in this file, and unpack() in
61
+ * cuda/CUDAGraphsUtils.cuh allow non-divergent use of
62
+ * CUDAGeneratorImpl whether graph capture is underway or not.
63
+ *
64
+ * Each PhiloxCudaState instance should be used for one and only one
65
+ * consumer kernel.
66
+ *
67
+ * Example (see e.g. native/cuda/Dropout.cu):
68
+ *
69
+ * #include <ATen/cuda/CUDAGeneratorImpl.h>
70
+ * #include <ATen/cuda/CUDAGraphsUtils.cuh>
71
+ *
72
+ * __global__ void kernel(..., PhiloxCudaState philox_args) {
73
+ * auto seeds = at::cuda::philox::unpack(philox_args);
74
+ * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x;
75
+ * curandStatePhilox4_32_10_t state;
76
+ * curand_init(std::get<0>(seeds), // seed
77
+ * idx, // per-thread subsequence
78
+ * std::get<1>(seeds), // offset in subsequence
79
+ * &state);
80
+ * ...
81
+ * }
82
+ *
83
+ * host_caller(...) {
84
+ * PhiloxCudaState rng_engine_inputs;
85
+ * {
86
+ * // See Note [Acquire lock when using random generators]
87
+ * std::lock_guard<std::mutex> lock(gen->mutex_);
88
+ *
89
+ * // gen could be HostState or DevState here! No divergent code needed!
90
+ * rng_engine_inputs = gen->philox_cuda_state(offset_increment);
91
+ * }
92
+ * kernel<<<...>>>(..., rng_engine_inputs);
93
+ * }
94
+ *
95
+ */
96
+
97
+ struct CUDAGeneratorState : public c10::intrusive_ptr_target {
98
+ uint64_t seed_;
99
+ uint64_t philox_offset_per_thread_;
100
+ uint64_t offset_intragraph_;
101
+ bool capturing_{};
102
+ std::unordered_set<cuda::CUDAGraph*> registered_graphs_;
103
+ at::TensorBase seed_extragraph_;
104
+ at::TensorBase offset_extragraph_;
105
+
106
+ CUDAGeneratorState(
107
+ uint64_t seed = default_rng_seed_val,
108
+ uint64_t philox_offset_per_thread = 0,
109
+ uint64_t offset_intragraph = 0)
110
+ : seed_(seed),
111
+ philox_offset_per_thread_(philox_offset_per_thread),
112
+ offset_intragraph_(offset_intragraph) {}
113
+
114
+ void increase(uint64_t increment);
115
+
116
+ void register_graph(cuda::CUDAGraph* graph);
117
+ void unregister_graph(cuda::CUDAGraph* graph);
118
+
119
+ void capture_prologue();
120
+ // capture_epilogue returns the wholegraph_increment
121
+ uint64_t capture_epilogue();
122
+ void replay_prologue(uint64_t wholegraph_increment);
123
+ c10::intrusive_ptr<CUDAGeneratorState> clone();
124
+ };
125
+
126
+ struct TORCH_CUDA_CPP_API CUDAGeneratorImpl : public c10::GeneratorImpl {
127
+ // Constructors
128
+ CUDAGeneratorImpl(DeviceIndex device_index = -1);
129
+ CUDAGeneratorImpl(
130
+ DeviceIndex device_index,
131
+ c10::intrusive_ptr<CUDAGeneratorState> state_);
132
+ ~CUDAGeneratorImpl() override = default;
133
+
134
+ // CUDAGeneratorImpl methods
135
+ std::shared_ptr<CUDAGeneratorImpl> clone() const;
136
+ void set_current_seed(uint64_t seed) override;
137
+ void set_offset(uint64_t offset) override;
138
+ uint64_t get_offset() const override;
139
+ uint64_t current_seed() const override;
140
+ uint64_t seed() override;
141
+ void set_state(const c10::TensorImpl& new_state) override;
142
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
143
+ void graphsafe_set_state(
144
+ const c10::intrusive_ptr<GeneratorImpl>& state) override;
145
+ c10::intrusive_ptr<c10::GeneratorImpl> graphsafe_get_state() const override;
146
+
147
+ void set_philox_offset_per_thread(uint64_t offset);
148
+ uint64_t philox_offset_per_thread() const;
149
+
150
+ void register_graph(cuda::CUDAGraph* graph);
151
+ void unregister_graph(cuda::CUDAGraph* graph);
152
+
153
+ // Generates a PhiloxCudaState with a specified increment, and increment
154
+ // current state
155
+ PhiloxCudaState philox_cuda_state(uint64_t increment);
156
+
157
+ bool reset_rnn_state() {
158
+ return !no_reset_rnn_state_.test_and_set();
159
+ }
160
+
161
+ // Temporarily accommodates call sites that use philox_engine_inputs.
162
+ // Allows incremental refactor of call sites to use philox_cuda_state.
163
+ std::pair<uint64_t, uint64_t> philox_engine_inputs(uint64_t increment);
164
+
165
+ static c10::DeviceType device_type();
166
+
167
+ private:
168
+ CUDAGeneratorImpl* clone_impl() const override;
169
+
170
+ c10::intrusive_ptr<CUDAGeneratorState> state_;
171
+ std::atomic_flag no_reset_rnn_state_;
172
+ };
173
+
174
+ namespace cuda::detail {
175
+
176
+ TORCH_CUDA_CPP_API const Generator& getDefaultCUDAGenerator(
177
+ DeviceIndex device_index = -1);
178
+ TORCH_CUDA_CPP_API Generator createCUDAGenerator(DeviceIndex device_index = -1);
179
+
180
+ } // namespace cuda::detail
181
+ } // namespace at
182
+
183
+ #else
184
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
185
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraph.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/core/Device.h>
6
+ #include <c10/cuda/CUDACachingAllocator.h>
7
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
8
+ #include <c10/cuda/CUDAStream.h>
9
+ #include <c10/util/flat_hash_map.h>
10
+
11
+ namespace at {
12
+
13
+ struct Generator;
14
+ struct CUDAGeneratorImpl;
15
+ struct CUDAGeneratorState;
16
+
17
+ namespace cuda {
18
+
19
+ // Standalone way to get a unique mempool id usable as a pool=... argument
20
+ // to CUDAGraph::capture_begin
21
+ TORCH_CUDA_CPP_API MempoolId_t graph_pool_handle();
22
+
23
+ struct TORCH_CUDA_CPP_API CUDAGraph {
24
+ CUDAGraph(bool keep_graph=false);
25
+ ~CUDAGraph();
26
+
27
+ // See Note [Explicit Registration of Generators to the CUDA Graph]
28
+ void register_generator_state(c10::intrusive_ptr<at::CUDAGeneratorState> state);
29
+ void register_generator_state(const at::Generator& generator);
30
+ void capture_begin(
31
+ MempoolId_t pool = {0, 0},
32
+ cudaStreamCaptureMode capture_mode = cudaStreamCaptureModeGlobal);
33
+ void capture_end();
34
+ void instantiate();
35
+ void replay();
36
+ void reset();
37
+ MempoolId_t pool();
38
+ void enable_debug_mode();
39
+ void debug_dump(const std::string& debug_path);
40
+ cudaGraph_t raw_cuda_graph();
41
+ cudaGraphExec_t raw_cuda_graph_exec();
42
+
43
+ protected:
44
+ cudaGraph_t graph_ = nullptr;
45
+ cudaGraphExec_t graph_exec_ = nullptr;
46
+
47
+ // internal states so reset() can do its best cleaning up
48
+
49
+ // Set to true in capture_end if cudaStreamEndCapture succeeded
50
+ // Set back to false after instantiate() unless keep_graph=True or
51
+ // enable_debug_mode() was called on any CUDAGraph instance.
52
+ bool has_graph_ = false;
53
+ // Set to true in capture_end if cudaStreamEndCapture succeeded
54
+ bool capture_ended_ = false;
55
+ // Set to true in capture_end if cudaGraphInstantiate succeeded
56
+ bool has_graph_exec_ = false;
57
+
58
+ // the ID assigned by cuda during graph capture,
59
+ // used to identify when a stream is participating in capture
60
+ CaptureId_t capture_id_ = 0;
61
+
62
+ // uuid used to request a particular private mempool from CUDACachingAllocator.
63
+ // By default, this will be set to {id_, 0}.
64
+ //
65
+ // If capture_begin is called with "pool=other_graph.pool()", this graph's mempool_id_
66
+ // will be set to the other graph's mempool_id_, and therefore share a mempool with the
67
+ // other graph.
68
+ //
69
+ // If capture_begin is called with "pool=handle" where "handle" came from graph_pool_handle(),
70
+ // it will share a mempool with any other captures that used "pool=handle".
71
+ //
72
+ // Sharing a mempool across graphs saves memory, and it's safe if you
73
+ // know you'll replay those graphs in the same order you captured them.
74
+ MempoolId_t mempool_id_;
75
+
76
+ // Stream on which capture began
77
+ at::cuda::CUDAStream capture_stream_;
78
+
79
+ // multiple generator states and their wholegraph_increments in this graph
80
+ // that are managed by the CUDA Graph
81
+ ska::flat_hash_map<c10::intrusive_ptr<at::CUDAGeneratorState>, uint64_t>
82
+ captured_generator_states_;
83
+
84
+ // Device where capture occurred. Right now, for simplicity, we require all ops
85
+ // in a capture to run on the same device, but this is a limitation of CUDAGraph,
86
+ // not CUDA itself. We can straightforwardly modify CUDAGraph to support multi-device
87
+ // captures if needed.
88
+ // init capture_dev_ as UNDEFINED_DEVICE to check that it stores the real device id in the destructor
89
+ static constexpr c10::DeviceIndex UNDEFINED_DEVICE = -1;
90
+ c10::DeviceIndex capture_dev_{UNDEFINED_DEVICE};
91
+
92
+ bool keep_graph_;
93
+ };
94
+
95
+ } // namespace cuda
96
+ } // namespace at
97
+
98
+ #else
99
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
100
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAGeneratorImpl.h>
5
+ #include <ATen/cuda/CUDAEvent.h>
6
+ #include <ATen/cuda/PhiloxUtils.cuh>
7
+ #include <ATen/cuda/detail/CUDAHooks.h>
8
+ #include <ATen/detail/CUDAHooksInterface.h>
9
+ #include <c10/core/StreamGuard.h>
10
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
11
+ #include <c10/cuda/CUDAGuard.h>
12
+
13
+ // c10/cuda/CUDAGraphsC10Utils.h has utils used by both c10 and aten.
14
+ // This file adds utils used by aten only.
15
+
16
+ namespace at::cuda {
17
+
18
+ using CaptureId_t = c10::cuda::CaptureId_t;
19
+ using CaptureStatus = c10::cuda::CaptureStatus;
20
+
21
+ // Use this version where you don't want to create a CUDA context if none exists.
22
+ inline CaptureStatus currentStreamCaptureStatus() {
23
+ // don't create a context if we don't have to
24
+ if (c10::cuda::hasPrimaryContext(c10::cuda::current_device())) {
25
+ return c10::cuda::currentStreamCaptureStatusMayInitCtx();
26
+ } else {
27
+ return CaptureStatus::None;
28
+ }
29
+ }
30
+
31
+ inline void assertNotCapturing(const std::string& attempt) {
32
+ auto status = currentStreamCaptureStatus();
33
+ TORCH_CHECK(status == CaptureStatus::None,
34
+ attempt,
35
+ " during CUDA graph capture. If you need this call to be captured, "
36
+ "please file an issue. "
37
+ "Current cudaStreamCaptureStatus: ",
38
+ status);
39
+ }
40
+
41
+ inline void errorIfCapturingCudnnBenchmark(const std::string& version_specific) {
42
+ auto status = currentStreamCaptureStatus();
43
+ TORCH_CHECK(status == CaptureStatus::None,
44
+ "Current cudaStreamCaptureStatus: ",
45
+ status,
46
+ "\nCapturing ",
47
+ version_specific,
48
+ "is prohibited. Possible causes of this error:\n"
49
+ "1. No warmup iterations occurred before capture.\n"
50
+ "2. The convolutions you're trying to capture use dynamic shapes, "
51
+ "in which case capturing them is generally prohibited.");
52
+ }
53
+
54
+ } // namespace at::cuda
55
+
56
+ #else
57
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
58
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGreenContext.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/cuda/CUDAEvent.h>
4
+ #include <cuda.h>
5
+
6
+ // Forward declare green context as opaque ptr
7
+ typedef struct CUgreenCtx_st* CUgreenCtx;
8
+
9
+ namespace at::cuda {
10
+
11
+ class TORCH_CUDA_CPP_API GreenContext {
12
+ public:
13
+ // Green context creation
14
+ static std::unique_ptr<GreenContext> create(
15
+ uint32_t num_sms,
16
+ std::optional<uint32_t> device_id);
17
+ ~GreenContext() noexcept;
18
+
19
+ // Delete copy constructor and assignment
20
+ GreenContext(const GreenContext&) = delete;
21
+ GreenContext& operator=(const GreenContext&) = delete;
22
+
23
+ // Make this context current
24
+ void setContext();
25
+
26
+ void popContext();
27
+
28
+ private:
29
+ GreenContext(uint32_t device_id, uint32_t num_sms);
30
+ // Implement move operations
31
+ GreenContext(GreenContext&& other) noexcept;
32
+ GreenContext& operator=(GreenContext&& other) noexcept;
33
+
34
+ int32_t device_id_ = -1;
35
+ CUgreenCtx green_ctx_ = nullptr;
36
+ CUcontext context_ = nullptr;
37
+ cudaStream_t parent_stream_ = nullptr;
38
+ };
39
+ } // namespace at::cuda
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAScaledBlas.h ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <cstdint>
3
+ #include <c10/util/typeid.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/SmallVector.h>
6
+ #include <c10/core/Scalar.h>
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/util/Exception.h>
9
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
10
+ #include <ATen/core/Tensor.h>
11
+ #include <ATen/core/NamedTensor.h>
12
+ #include <ATen/Dispatch.h>
13
+ #include <ATen/ExpandUtils.h>
14
+ #include <ATen/OpMathType.h>
15
+ #include <ATen/TensorUtils.h>
16
+ #include <ATen/cuda/CUDABlas.h>
17
+ #include <ATen/cuda/tunable/Tunable.h>
18
+ #include <ATen/cuda/tunable/TunableGemm.h>
19
+ #include <ATen/native/Resize.h>
20
+ #include <c10/util/MaybeOwned.h>
21
+ #include <ATen/native/GroupedMMUtils.h>
22
+ #include <ATen/native/cuda/RowwiseScaledMM.h>
23
+ #include <ATen/native/cuda/ScaledGroupMM.h>
24
+ #include <ATen/native/cuda/GroupMM.h>
25
+ #include <ATen/ceil_div.h>
26
+
27
+ #ifdef USE_FBGEMM_GENAI
28
+ #include <fbgemm_gpu/torch_ops.h>
29
+ #endif
30
+
31
+ #ifndef AT_PER_OPERATOR_HEADERS
32
+ #include <ATen/Functions.h>
33
+ #include <ATen/NativeFunctions.h>
34
+ #else
35
+ #include <ATen/ops/_addmm_activation_native.h>
36
+ #include <ATen/ops/_efficientzerotensor.h>
37
+ #include <ATen/ops/_scaled_mm_native.h>
38
+ #include <ATen/ops/_unsafe_view_native.h>
39
+ #include <ATen/ops/abs.h>
40
+ #include <ATen/ops/addmm_native.h>
41
+ #include <ATen/ops/addmv_native.h>
42
+ #include <ATen/ops/baddbmm_native.h>
43
+ #include <ATen/ops/bmm_native.h>
44
+ #include <ATen/ops/copy_native.h>
45
+ #include <ATen/ops/dot_native.h>
46
+ #include <ATen/ops/empty.h>
47
+ #include <ATen/ops/empty_strided.h>
48
+ #include <ATen/ops/gelu.h>
49
+ #include <ATen/ops/max.h>
50
+ #include <ATen/ops/mm_native.h>
51
+ #include <ATen/ops/mul.h>
52
+ #include <ATen/ops/relu.h>
53
+ #include <ATen/ops/ones.h>
54
+ #include <ATen/ops/scalar_tensor_native.h>
55
+ #include <ATen/ops/vdot_native.h>
56
+ #endif
57
+
58
+ using at::blas::ScalingType;
59
+ using at::blas::SwizzleType;
60
+
61
+ namespace at::cuda::scaled {
62
+
63
+ static bool _scaled_mm_allowed_device(bool sm90_only=false, bool sm100_only=false) {
64
+ #ifdef USE_ROCM
65
+ static const std::vector<std::string> archs = {
66
+ "gfx942",
67
+ #if ROCM_VERSION >= 60300
68
+ "gfx1200", "gfx1201",
69
+ #endif
70
+ #if ROCM_VERSION >= 60500
71
+ "gfx950"
72
+ #endif
73
+ };
74
+ return at::detail::getCUDAHooks().isGPUArch(archs);
75
+ #else
76
+ auto dprops = at::cuda::getCurrentDeviceProperties();
77
+
78
+ if (sm90_only || sm100_only) {
79
+ return (sm90_only && dprops->major == 9) || (sm100_only && dprops->major == 10);
80
+ } else {
81
+ return dprops->major >= 9 || (dprops->major == 8 && dprops->minor == 9);
82
+ }
83
+ #endif
84
+ }
85
+
86
+ #ifdef USE_ROCM
87
+ static bool _scaled_mm_is_fnuz() {
88
+ return at::detail::getCUDAHooks().isGPUArch({"gfx942"});
89
+ }
90
+ #endif
91
+ /**
92
+ * Track concrete implementations available
93
+ */
94
+ enum class ScaledGemmImplementation {
95
+ NONE = 0,
96
+ TENSORWISE_TENSORWISE = 1,
97
+ ROWWISE_ROWWISE = 2,
98
+ BLOCK_128x128_1x128 = 3,
99
+ BLOCK_1x128_128x128 = 4,
100
+ BLOCK_1x128_1x128 = 5,
101
+ MXFP8_MXFP8 = 6,
102
+ NVFP4_NVFP4 = 7,
103
+ NVFP4_NVFP4_SINGLE_SCALE = 8,
104
+ MXFP4_MXFP4 = 9,
105
+ };
106
+
107
+ /**
108
+ * Convert passed int (enum) from python back into a
109
+ * strictly-typed enum
110
+ */
111
+ template <class EnumType, class ArrayType>
112
+ std::vector<EnumType> convert_int_to_enum(ArrayType& v) {
113
+ std::vector<EnumType> converted;
114
+ converted.reserve(v.size());
115
+
116
+ for (auto vi : v) {
117
+ converted.push_back(static_cast<EnumType>(vi));
118
+ }
119
+ return converted;
120
+ }
121
+
122
+ bool check_tensorwise_recipe(c10::ScalarType,
123
+ std::vector<ScalingType>&,
124
+ ArrayRef<Tensor>&,
125
+ c10::ScalarType,
126
+ std::vector<ScalingType>&,
127
+ ArrayRef<Tensor>&);
128
+
129
+
130
+ bool check_rowwise_recipe(c10::ScalarType,
131
+ std::vector<ScalingType>&,
132
+ ArrayRef<Tensor>&,
133
+ c10::ScalarType,
134
+ std::vector<ScalingType>&,
135
+ ArrayRef<Tensor>&);
136
+
137
+ bool check_nvfp4_recipe(c10::ScalarType,
138
+ std::vector<ScalingType>&,
139
+ ArrayRef<Tensor>&,
140
+ c10::ScalarType,
141
+ std::vector<ScalingType>&,
142
+ ArrayRef<Tensor>&);
143
+
144
+ bool check_nvfp4_recipe_single_scale
145
+ (c10::ScalarType,
146
+ std::vector<ScalingType>&,
147
+ ArrayRef<Tensor>&,
148
+ c10::ScalarType,
149
+ std::vector<ScalingType>&,
150
+ ArrayRef<Tensor>&);
151
+
152
+ bool check_deepseek_recipe(ScalingType,
153
+ ScalingType,
154
+ c10::ScalarType,
155
+ std::vector<ScalingType>&,
156
+ ArrayRef<Tensor>&,
157
+ c10::ScalarType,
158
+ std::vector<ScalingType>&,
159
+ ArrayRef<Tensor>&);
160
+
161
+ bool check_mxfp8_recipe(c10::ScalarType,
162
+ std::vector<ScalingType>&,
163
+ ArrayRef<Tensor>&,
164
+ c10::ScalarType,
165
+ std::vector<ScalingType>&,
166
+ ArrayRef<Tensor>&);
167
+
168
+ bool check_mxfp4_recipe(c10::ScalarType,
169
+ std::vector<ScalingType>&,
170
+ ArrayRef<Tensor>&,
171
+ c10::ScalarType,
172
+ std::vector<ScalingType>&,
173
+ ArrayRef<Tensor>&);
174
+
175
+ } // namespace at::native::cuda::blas::scaled
176
+
177
+ #else
178
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
179
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparse.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #if defined(USE_ROCM)
6
+ #include <hipsparse/hipsparse-version.h>
7
+ #define HIPSPARSE_VERSION ((hipsparseVersionMajor*100000) + (hipsparseVersionMinor*100) + hipsparseVersionPatch)
8
+ #endif
9
+
10
+
11
+ // cuSparse Generic API spsv function was added in CUDA 11.3.0
12
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11500)
13
+ #define AT_USE_CUSPARSE_GENERIC_SPSV() 1
14
+ #else
15
+ #define AT_USE_CUSPARSE_GENERIC_SPSV() 0
16
+ #endif
17
+
18
+ // cuSparse Generic API spsm function was added in CUDA 11.3.1
19
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11600)
20
+ #define AT_USE_CUSPARSE_GENERIC_SPSM() 1
21
+ #else
22
+ #define AT_USE_CUSPARSE_GENERIC_SPSM() 0
23
+ #endif
24
+
25
+ // cuSparse Generic API sddmm function was added in CUDA 11.2.1 (cuSparse version 11400)
26
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11400)
27
+ #define AT_USE_CUSPARSE_GENERIC_SDDMM() 1
28
+ #else
29
+ #define AT_USE_CUSPARSE_GENERIC_SDDMM() 0
30
+ #endif
31
+
32
+ // BSR triangular solve functions were added in hipSPARSE 1.11.2 (ROCm 4.5.0)
33
+ #if defined(CUDART_VERSION) || defined(USE_ROCM)
34
+ #define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 1
35
+ #else
36
+ #define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 0
37
+ #endif
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseBlas.h ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ /*
5
+ Provides a subset of cuSPARSE functions as templates:
6
+
7
+ csrgeam2<scalar_t>(...)
8
+
9
+ where scalar_t is double, float, c10::complex<double> or c10::complex<float>.
10
+ The functions are available in at::cuda::sparse namespace.
11
+ */
12
+
13
+ #include <ATen/cuda/CUDAContext.h>
14
+ #include <ATen/cuda/CUDASparse.h>
15
+
16
+ // NOLINTBEGIN(misc-misplaced-const)
17
+ namespace at::cuda::sparse {
18
+
19
+ #define CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t) \
20
+ cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \
21
+ const cusparseMatDescr_t descrA, int nnzA, \
22
+ const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \
23
+ const int *csrSortedColIndA, const scalar_t *beta, \
24
+ const cusparseMatDescr_t descrB, int nnzB, \
25
+ const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \
26
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
27
+ const scalar_t *csrSortedValC, const int *csrSortedRowPtrC, \
28
+ const int *csrSortedColIndC, size_t *pBufferSizeInBytes
29
+
30
+ template <typename scalar_t>
31
+ inline void csrgeam2_bufferSizeExt(
32
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t)) {
33
+ TORCH_INTERNAL_ASSERT(
34
+ false,
35
+ "at::cuda::sparse::csrgeam2_bufferSizeExt: not implemented for ",
36
+ typeid(scalar_t).name());
37
+ }
38
+
39
+ template <>
40
+ void csrgeam2_bufferSizeExt<float>(
41
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(float));
42
+ template <>
43
+ void csrgeam2_bufferSizeExt<double>(
44
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(double));
45
+ template <>
46
+ void csrgeam2_bufferSizeExt<c10::complex<float>>(
47
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex<float>));
48
+ template <>
49
+ void csrgeam2_bufferSizeExt<c10::complex<double>>(
50
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex<double>));
51
+
52
+ #define CUSPARSE_CSRGEAM2_NNZ_ARGTYPES() \
53
+ cusparseHandle_t handle, int m, int n, const cusparseMatDescr_t descrA, \
54
+ int nnzA, const int *csrSortedRowPtrA, const int *csrSortedColIndA, \
55
+ const cusparseMatDescr_t descrB, int nnzB, const int *csrSortedRowPtrB, \
56
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
57
+ int *csrSortedRowPtrC, int *nnzTotalDevHostPtr, void *workspace
58
+
59
+ template <typename scalar_t>
60
+ inline void csrgeam2Nnz(CUSPARSE_CSRGEAM2_NNZ_ARGTYPES()) {
61
+ TORCH_CUDASPARSE_CHECK(cusparseXcsrgeam2Nnz(
62
+ handle,
63
+ m,
64
+ n,
65
+ descrA,
66
+ nnzA,
67
+ csrSortedRowPtrA,
68
+ csrSortedColIndA,
69
+ descrB,
70
+ nnzB,
71
+ csrSortedRowPtrB,
72
+ csrSortedColIndB,
73
+ descrC,
74
+ csrSortedRowPtrC,
75
+ nnzTotalDevHostPtr,
76
+ workspace));
77
+ }
78
+
79
+ #define CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t) \
80
+ cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \
81
+ const cusparseMatDescr_t descrA, int nnzA, \
82
+ const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \
83
+ const int *csrSortedColIndA, const scalar_t *beta, \
84
+ const cusparseMatDescr_t descrB, int nnzB, \
85
+ const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \
86
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
87
+ scalar_t *csrSortedValC, int *csrSortedRowPtrC, int *csrSortedColIndC, \
88
+ void *pBuffer
89
+
90
+ template <typename scalar_t>
91
+ inline void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t)) {
92
+ TORCH_INTERNAL_ASSERT(
93
+ false,
94
+ "at::cuda::sparse::csrgeam2: not implemented for ",
95
+ typeid(scalar_t).name());
96
+ }
97
+
98
+ template <>
99
+ void csrgeam2<float>(CUSPARSE_CSRGEAM2_ARGTYPES(float));
100
+ template <>
101
+ void csrgeam2<double>(CUSPARSE_CSRGEAM2_ARGTYPES(double));
102
+ template <>
103
+ void csrgeam2<c10::complex<float>>(
104
+ CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex<float>));
105
+ template <>
106
+ void csrgeam2<c10::complex<double>>(
107
+ CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex<double>));
108
+
109
+ #define CUSPARSE_BSRMM_ARGTYPES(scalar_t) \
110
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
111
+ cusparseOperation_t transA, cusparseOperation_t transB, int mb, int n, \
112
+ int kb, int nnzb, const scalar_t *alpha, \
113
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
114
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
115
+ const scalar_t *B, int ldb, const scalar_t *beta, scalar_t *C, int ldc
116
+
117
+ template <typename scalar_t>
118
+ inline void bsrmm(CUSPARSE_BSRMM_ARGTYPES(scalar_t)) {
119
+ TORCH_INTERNAL_ASSERT(
120
+ false,
121
+ "at::cuda::sparse::bsrmm: not implemented for ",
122
+ typeid(scalar_t).name());
123
+ }
124
+
125
+ template <>
126
+ void bsrmm<float>(CUSPARSE_BSRMM_ARGTYPES(float));
127
+ template <>
128
+ void bsrmm<double>(CUSPARSE_BSRMM_ARGTYPES(double));
129
+ template <>
130
+ void bsrmm<c10::complex<float>>(CUSPARSE_BSRMM_ARGTYPES(c10::complex<float>));
131
+ template <>
132
+ void bsrmm<c10::complex<double>>(CUSPARSE_BSRMM_ARGTYPES(c10::complex<double>));
133
+
134
+ #define CUSPARSE_BSRMV_ARGTYPES(scalar_t) \
135
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
136
+ cusparseOperation_t transA, int mb, int nb, int nnzb, \
137
+ const scalar_t *alpha, const cusparseMatDescr_t descrA, \
138
+ const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \
139
+ int blockDim, const scalar_t *x, const scalar_t *beta, scalar_t *y
140
+
141
+ template <typename scalar_t>
142
+ inline void bsrmv(CUSPARSE_BSRMV_ARGTYPES(scalar_t)) {
143
+ TORCH_INTERNAL_ASSERT(
144
+ false,
145
+ "at::cuda::sparse::bsrmv: not implemented for ",
146
+ typeid(scalar_t).name());
147
+ }
148
+
149
+ template <>
150
+ void bsrmv<float>(CUSPARSE_BSRMV_ARGTYPES(float));
151
+ template <>
152
+ void bsrmv<double>(CUSPARSE_BSRMV_ARGTYPES(double));
153
+ template <>
154
+ void bsrmv<c10::complex<float>>(CUSPARSE_BSRMV_ARGTYPES(c10::complex<float>));
155
+ template <>
156
+ void bsrmv<c10::complex<double>>(CUSPARSE_BSRMV_ARGTYPES(c10::complex<double>));
157
+
158
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
159
+
160
+ #define CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t) \
161
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
162
+ cusparseOperation_t transA, int mb, int nnzb, \
163
+ const cusparseMatDescr_t descrA, scalar_t *bsrValA, \
164
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
165
+ bsrsv2Info_t info, int *pBufferSizeInBytes
166
+
167
+ template <typename scalar_t>
168
+ inline void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t)) {
169
+ TORCH_INTERNAL_ASSERT(
170
+ false,
171
+ "at::cuda::sparse::bsrsv2_bufferSize: not implemented for ",
172
+ typeid(scalar_t).name());
173
+ }
174
+
175
+ template <>
176
+ void bsrsv2_bufferSize<float>(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(float));
177
+ template <>
178
+ void bsrsv2_bufferSize<double>(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(double));
179
+ template <>
180
+ void bsrsv2_bufferSize<c10::complex<float>>(
181
+ CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex<float>));
182
+ template <>
183
+ void bsrsv2_bufferSize<c10::complex<double>>(
184
+ CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex<double>));
185
+
186
+ #define CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t) \
187
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
188
+ cusparseOperation_t transA, int mb, int nnzb, \
189
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
190
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
191
+ bsrsv2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer
192
+
193
+ template <typename scalar_t>
194
+ inline void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t)) {
195
+ TORCH_INTERNAL_ASSERT(
196
+ false,
197
+ "at::cuda::sparse::bsrsv2_analysis: not implemented for ",
198
+ typeid(scalar_t).name());
199
+ }
200
+
201
+ template <>
202
+ void bsrsv2_analysis<float>(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(float));
203
+ template <>
204
+ void bsrsv2_analysis<double>(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(double));
205
+ template <>
206
+ void bsrsv2_analysis<c10::complex<float>>(
207
+ CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex<float>));
208
+ template <>
209
+ void bsrsv2_analysis<c10::complex<double>>(
210
+ CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex<double>));
211
+
212
+ #define CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t) \
213
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
214
+ cusparseOperation_t transA, int mb, int nnzb, const scalar_t *alpha, \
215
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
216
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
217
+ bsrsv2Info_t info, const scalar_t *x, scalar_t *y, \
218
+ cusparseSolvePolicy_t policy, void *pBuffer
219
+
220
+ template <typename scalar_t>
221
+ inline void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t)) {
222
+ TORCH_INTERNAL_ASSERT(
223
+ false,
224
+ "at::cuda::sparse::bsrsv2_solve: not implemented for ",
225
+ typeid(scalar_t).name());
226
+ }
227
+
228
+ template <>
229
+ void bsrsv2_solve<float>(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(float));
230
+ template <>
231
+ void bsrsv2_solve<double>(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(double));
232
+ template <>
233
+ void bsrsv2_solve<c10::complex<float>>(
234
+ CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex<float>));
235
+ template <>
236
+ void bsrsv2_solve<c10::complex<double>>(
237
+ CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex<double>));
238
+
239
+ #define CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t) \
240
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
241
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
242
+ int nnzb, const cusparseMatDescr_t descrA, scalar_t *bsrValA, \
243
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
244
+ bsrsm2Info_t info, int *pBufferSizeInBytes
245
+
246
+ template <typename scalar_t>
247
+ inline void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t)) {
248
+ TORCH_INTERNAL_ASSERT(
249
+ false,
250
+ "at::cuda::sparse::bsrsm2_bufferSize: not implemented for ",
251
+ typeid(scalar_t).name());
252
+ }
253
+
254
+ template <>
255
+ void bsrsm2_bufferSize<float>(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(float));
256
+ template <>
257
+ void bsrsm2_bufferSize<double>(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(double));
258
+ template <>
259
+ void bsrsm2_bufferSize<c10::complex<float>>(
260
+ CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex<float>));
261
+ template <>
262
+ void bsrsm2_bufferSize<c10::complex<double>>(
263
+ CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex<double>));
264
+
265
+ #define CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t) \
266
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
267
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
268
+ int nnzb, const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
269
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
270
+ bsrsm2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer
271
+
272
+ template <typename scalar_t>
273
+ inline void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t)) {
274
+ TORCH_INTERNAL_ASSERT(
275
+ false,
276
+ "at::cuda::sparse::bsrsm2_analysis: not implemented for ",
277
+ typeid(scalar_t).name());
278
+ }
279
+
280
+ template <>
281
+ void bsrsm2_analysis<float>(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(float));
282
+ template <>
283
+ void bsrsm2_analysis<double>(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(double));
284
+ template <>
285
+ void bsrsm2_analysis<c10::complex<float>>(
286
+ CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex<float>));
287
+ template <>
288
+ void bsrsm2_analysis<c10::complex<double>>(
289
+ CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex<double>));
290
+
291
+ #define CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t) \
292
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
293
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
294
+ int nnzb, const scalar_t *alpha, const cusparseMatDescr_t descrA, \
295
+ const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \
296
+ int blockDim, bsrsm2Info_t info, const scalar_t *B, int ldb, \
297
+ scalar_t *X, int ldx, cusparseSolvePolicy_t policy, void *pBuffer
298
+
299
+ template <typename scalar_t>
300
+ inline void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t)) {
301
+ TORCH_INTERNAL_ASSERT(
302
+ false,
303
+ "at::cuda::sparse::bsrsm2_solve: not implemented for ",
304
+ typeid(scalar_t).name());
305
+ }
306
+
307
+ template <>
308
+ void bsrsm2_solve<float>(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(float));
309
+ template <>
310
+ void bsrsm2_solve<double>(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(double));
311
+ template <>
312
+ void bsrsm2_solve<c10::complex<float>>(
313
+ CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex<float>));
314
+ template <>
315
+ void bsrsm2_solve<c10::complex<double>>(
316
+ CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex<double>));
317
+
318
+ #endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE
319
+
320
+ } // namespace at::cuda::sparse
321
+ // NOLINTEND(misc-misplaced-const)
322
+
323
+ #else
324
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
325
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/cuda/CUDASparse.h>
7
+
8
+ #include <c10/core/ScalarType.h>
9
+
10
+ #if defined(USE_ROCM)
11
+ #include <type_traits>
12
+ #endif
13
+
14
+ namespace at::cuda::sparse {
15
+
16
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
17
+ struct CuSparseDescriptorDeleter {
18
+ void operator()(T* x) {
19
+ if (x != nullptr) {
20
+ TORCH_CUDASPARSE_CHECK(destructor(x));
21
+ }
22
+ }
23
+ };
24
+
25
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
26
+ class CuSparseDescriptor {
27
+ public:
28
+ T* descriptor() const {
29
+ return descriptor_.get();
30
+ }
31
+ T* descriptor() {
32
+ return descriptor_.get();
33
+ }
34
+
35
+ protected:
36
+ std::unique_ptr<T, CuSparseDescriptorDeleter<T, destructor>> descriptor_;
37
+ };
38
+
39
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
40
+ struct ConstCuSparseDescriptorDeleter {
41
+ void operator()(T* x) {
42
+ if (x != nullptr) {
43
+ TORCH_CUDASPARSE_CHECK(destructor(x));
44
+ }
45
+ }
46
+ };
47
+
48
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
49
+ class ConstCuSparseDescriptor {
50
+ public:
51
+ T* descriptor() const {
52
+ return descriptor_.get();
53
+ }
54
+ T* descriptor() {
55
+ return descriptor_.get();
56
+ }
57
+
58
+ protected:
59
+ std::unique_ptr<T, ConstCuSparseDescriptorDeleter<T, destructor>> descriptor_;
60
+ };
61
+
62
+ #if defined(USE_ROCM)
63
+ using cusparseMatDescr = std::remove_pointer_t<hipsparseMatDescr_t>;
64
+ using cusparseDnMatDescr = std::remove_pointer_t<hipsparseDnMatDescr_t>;
65
+ using cusparseDnVecDescr = std::remove_pointer_t<hipsparseDnVecDescr_t>;
66
+ using cusparseSpMatDescr = std::remove_pointer_t<hipsparseSpMatDescr_t>;
67
+ using cusparseSpMatDescr = std::remove_pointer_t<hipsparseSpMatDescr_t>;
68
+ using cusparseSpGEMMDescr = std::remove_pointer_t<hipsparseSpGEMMDescr_t>;
69
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
70
+ using bsrsv2Info = std::remove_pointer_t<bsrsv2Info_t>;
71
+ using bsrsm2Info = std::remove_pointer_t<bsrsm2Info_t>;
72
+ #endif
73
+ #endif
74
+
75
+ // NOTE: This is only needed for CUDA 11 and earlier, since CUDA 12 introduced
76
+ // API for const descriptors
77
+ cusparseStatus_t destroyConstDnMat(const cusparseDnMatDescr* dnMatDescr);
78
+
79
+ class TORCH_CUDA_CPP_API CuSparseMatDescriptor
80
+ : public CuSparseDescriptor<cusparseMatDescr, &cusparseDestroyMatDescr> {
81
+ public:
82
+ CuSparseMatDescriptor() {
83
+ cusparseMatDescr_t raw_descriptor = nullptr;
84
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
85
+ descriptor_.reset(raw_descriptor);
86
+ }
87
+
88
+ CuSparseMatDescriptor(bool upper, bool unit) {
89
+ cusparseFillMode_t fill_mode =
90
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
91
+ cusparseDiagType_t diag_type =
92
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
93
+ cusparseMatDescr_t raw_descriptor = nullptr;
94
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
95
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatFillMode(raw_descriptor, fill_mode));
96
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatDiagType(raw_descriptor, diag_type));
97
+ descriptor_.reset(raw_descriptor);
98
+ }
99
+ };
100
+
101
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
102
+
103
+ class TORCH_CUDA_CPP_API CuSparseBsrsv2Info
104
+ : public CuSparseDescriptor<bsrsv2Info, &cusparseDestroyBsrsv2Info> {
105
+ public:
106
+ CuSparseBsrsv2Info() {
107
+ bsrsv2Info_t raw_descriptor = nullptr;
108
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsv2Info(&raw_descriptor));
109
+ descriptor_.reset(raw_descriptor);
110
+ }
111
+ };
112
+
113
+ class TORCH_CUDA_CPP_API CuSparseBsrsm2Info
114
+ : public CuSparseDescriptor<bsrsm2Info, &cusparseDestroyBsrsm2Info> {
115
+ public:
116
+ CuSparseBsrsm2Info() {
117
+ bsrsm2Info_t raw_descriptor = nullptr;
118
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsm2Info(&raw_descriptor));
119
+ descriptor_.reset(raw_descriptor);
120
+ }
121
+ };
122
+
123
+ #endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE
124
+
125
+ cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type);
126
+
127
+ class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor
128
+ : public ConstCuSparseDescriptor<
129
+ cusparseDnMatDescr,
130
+ &cusparseDestroyDnMat> {
131
+ public:
132
+ explicit CuSparseDnMatDescriptor(
133
+ const Tensor& input,
134
+ int64_t batch_offset = -1);
135
+ };
136
+
137
+ class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor
138
+ : public ConstCuSparseDescriptor<
139
+ const cusparseDnMatDescr,
140
+ &destroyConstDnMat> {
141
+ public:
142
+ explicit CuSparseConstDnMatDescriptor(
143
+ const Tensor& input,
144
+ int64_t batch_offset = -1);
145
+ cusparseDnMatDescr* unsafe_mutable_descriptor() const {
146
+ return const_cast<cusparseDnMatDescr*>(descriptor());
147
+ }
148
+ cusparseDnMatDescr* unsafe_mutable_descriptor() {
149
+ return const_cast<cusparseDnMatDescr*>(descriptor());
150
+ }
151
+ };
152
+
153
+ class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor
154
+ : public ConstCuSparseDescriptor<
155
+ cusparseDnVecDescr,
156
+ &cusparseDestroyDnVec> {
157
+ public:
158
+ explicit CuSparseDnVecDescriptor(const Tensor& input);
159
+ };
160
+
161
+ class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor
162
+ : public ConstCuSparseDescriptor<
163
+ cusparseSpMatDescr,
164
+ &cusparseDestroySpMat> {};
165
+
166
+ class TORCH_CUDA_CPP_API CuSparseSpMatCsrDescriptor
167
+ : public CuSparseSpMatDescriptor {
168
+ public:
169
+ explicit CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset = -1);
170
+
171
+ std::tuple<int64_t, int64_t, int64_t> get_size() {
172
+ int64_t rows = 0, cols = 0, nnz = 0;
173
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatGetSize(
174
+ this->descriptor(),
175
+ &rows,
176
+ &cols,
177
+ &nnz));
178
+ return std::make_tuple(rows, cols, nnz);
179
+ }
180
+
181
+ void set_tensor(const Tensor& input) {
182
+ auto crow_indices = input.crow_indices();
183
+ auto col_indices = input.col_indices();
184
+ auto values = input.values();
185
+
186
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous());
187
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous());
188
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous());
189
+ TORCH_CUDASPARSE_CHECK(cusparseCsrSetPointers(
190
+ this->descriptor(),
191
+ crow_indices.data_ptr(),
192
+ col_indices.data_ptr(),
193
+ values.data_ptr()));
194
+ }
195
+
196
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
197
+ void set_mat_fill_mode(bool upper) {
198
+ cusparseFillMode_t fill_mode =
199
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
200
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
201
+ this->descriptor(),
202
+ CUSPARSE_SPMAT_FILL_MODE,
203
+ &fill_mode,
204
+ sizeof(fill_mode)));
205
+ }
206
+
207
+ void set_mat_diag_type(bool unit) {
208
+ cusparseDiagType_t diag_type =
209
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
210
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
211
+ this->descriptor(),
212
+ CUSPARSE_SPMAT_DIAG_TYPE,
213
+ &diag_type,
214
+ sizeof(diag_type)));
215
+ }
216
+ #endif
217
+ };
218
+
219
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
220
+ class TORCH_CUDA_CPP_API CuSparseSpSVDescriptor
221
+ : public CuSparseDescriptor<cusparseSpSVDescr, &cusparseSpSV_destroyDescr> {
222
+ public:
223
+ CuSparseSpSVDescriptor() {
224
+ cusparseSpSVDescr_t raw_descriptor = nullptr;
225
+ TORCH_CUDASPARSE_CHECK(cusparseSpSV_createDescr(&raw_descriptor));
226
+ descriptor_.reset(raw_descriptor);
227
+ }
228
+ };
229
+ #endif
230
+
231
+ #if AT_USE_CUSPARSE_GENERIC_SPSM()
232
+ class TORCH_CUDA_CPP_API CuSparseSpSMDescriptor
233
+ : public CuSparseDescriptor<cusparseSpSMDescr, &cusparseSpSM_destroyDescr> {
234
+ public:
235
+ CuSparseSpSMDescriptor() {
236
+ cusparseSpSMDescr_t raw_descriptor = nullptr;
237
+ TORCH_CUDASPARSE_CHECK(cusparseSpSM_createDescr(&raw_descriptor));
238
+ descriptor_.reset(raw_descriptor);
239
+ }
240
+ };
241
+ #endif
242
+
243
+ class TORCH_CUDA_CPP_API CuSparseSpGEMMDescriptor
244
+ : public CuSparseDescriptor<cusparseSpGEMMDescr, &cusparseSpGEMM_destroyDescr> {
245
+ public:
246
+ CuSparseSpGEMMDescriptor() {
247
+ cusparseSpGEMMDescr_t raw_descriptor = nullptr;
248
+ TORCH_CUDASPARSE_CHECK(cusparseSpGEMM_createDescr(&raw_descriptor));
249
+ descriptor_.reset(raw_descriptor);
250
+ }
251
+ };
252
+
253
+ } // namespace at::cuda::sparse
254
+
255
+ #else
256
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
257
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/util/Half.h>
6
+
7
+ #include <cuda.h>
8
+ #include <cuda_runtime.h>
9
+ #include <cuda_fp16.h>
10
+
11
+ namespace at {
12
+ template <>
13
+ inline __half* Tensor::data() const {
14
+ return reinterpret_cast<__half*>(data<Half>());
15
+ }
16
+ } // namespace at
17
+
18
+ #else
19
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
20
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAUtils.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAContext.h>
5
+
6
+ namespace at::cuda {
7
+
8
+ // Check if every tensor in a list of tensors matches the current
9
+ // device.
10
+ inline bool check_device(ArrayRef<Tensor> ts) {
11
+ if (ts.empty()) {
12
+ return true;
13
+ }
14
+ Device curDevice = Device(kCUDA, current_device());
15
+ for (const Tensor& t : ts) {
16
+ if (t.device() != curDevice) return false;
17
+ }
18
+ return true;
19
+ }
20
+
21
+ } // namespace at::cuda
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/CachingHostAllocator.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/CachingHostAllocator.h>
5
+ #include <c10/core/Allocator.h>
6
+ #include <c10/cuda/CUDAStream.h>
7
+ #include <c10/util/Deprecated.h>
8
+
9
+ namespace at::cuda {
10
+
11
+ //
12
+ // A caching allocator for CUDA host allocations (pinned memory).
13
+ //
14
+ // This provides a drop-in replacement for THCudaHostAllocator, which reuses
15
+ // freed pinned (page-locked) memory allocations. This avoids device
16
+ // synchronizations due to cudaFreeHost calls.
17
+ //
18
+ // To ensure correct behavior, THCCachingHostAllocator_recordEvent must be
19
+ // called anytime a pointer from this allocator is used in a cudaMemcpyAsync
20
+ // call between host and device, and passed the corresponding context from the
21
+ // allocation. This is currently invoked by at::native::copy_kernel_cuda.
22
+ //
23
+ C10_DEPRECATED_MESSAGE(
24
+ "at::cuda::getCachingHostAllocator() is deprecated. Please use at::getHostAllocator(at::kCUDA) instead.")
25
+ inline TORCH_CUDA_CPP_API at::HostAllocator* getCachingHostAllocator() {
26
+ return at::getHostAllocator(at::kCUDA);
27
+ }
28
+
29
+ // Records an event in the specified stream. The allocation corresponding to the
30
+ // input `ptr`/`ctx` will not be reused until the event has occurred.
31
+ C10_DEPRECATED_MESSAGE(
32
+ "at::cuda::CachingHostAllocator_recordEvent(...) is deprecated. Please use at::getHostAllocator(at::kCUDA)->record_event(...) instead.")
33
+ inline TORCH_CUDA_CPP_API bool CachingHostAllocator_recordEvent(
34
+ void* ptr,
35
+ void* ctx,
36
+ c10::cuda::CUDAStream stream) {
37
+ return getHostAllocator(at::kCUDA)->record_event(ptr, ctx, stream.unwrap());
38
+ }
39
+
40
+ // Releases cached pinned memory allocations via cudaHostFree
41
+ C10_DEPRECATED_MESSAGE(
42
+ "at::cuda::CachingHostAllocator_emptyCache() is deprecated. Please use at::getHostAllocator(at::kCUDA)->empty_cache() instead.")
43
+ inline TORCH_CUDA_CPP_API void CachingHostAllocator_emptyCache() {
44
+ getHostAllocator(at::kCUDA)->empty_cache();
45
+ }
46
+
47
+ C10_DEPRECATED_MESSAGE(
48
+ "at::cuda::HostAlloc(...) is deprecated. Please use at::getHostAllocator(at::kCUDA)->allocate(...) instead.")
49
+ inline TORCH_CUDA_CPP_API at::DataPtr HostAlloc(size_t size) {
50
+ return getHostAllocator(at::kCUDA)->allocate(size);
51
+ }
52
+
53
+ C10_DEPRECATED_MESSAGE(
54
+ "at::cuda::CachingHostAllocator_getStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->get_stats() instead.")
55
+ inline TORCH_CUDA_CPP_API at::HostStats CachingHostAllocator_getStats() {
56
+ return getHostAllocator(at::kCUDA)->get_stats();
57
+ }
58
+
59
+ C10_DEPRECATED_MESSAGE(
60
+ "at::cuda::CachingHostAllocator_resetAccumulatedStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->reset_accumulated_stats() instead.")
61
+ inline TORCH_CUDA_CPP_API void CachingHostAllocator_resetAccumulatedStats() {
62
+ getHostAllocator(at::kCUDA)->reset_accumulated_stats();
63
+ }
64
+
65
+ C10_DEPRECATED_MESSAGE(
66
+ "at::cuda::CachingHostAllocator_resetPeakStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->reset_peak_stats() instead.")
67
+ inline TORCH_CUDA_CPP_API void CachingHostAllocator_resetPeakStats() {
68
+ getHostAllocator(at::kCUDA)->reset_peak_stats();
69
+ }
70
+
71
+ } // namespace at::cuda
72
+
73
+ #else
74
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
75
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cuda.h>
5
+ #include <c10/util/complex.h>
6
+ #include <c10/util/Half.h>
7
+
8
+ __device__ __forceinline__ unsigned int ACTIVE_MASK()
9
+ {
10
+ #if !defined(USE_ROCM)
11
+ return __activemask();
12
+ #else
13
+ // will be ignored anyway
14
+ return 0xffffffff;
15
+ #endif
16
+ }
17
+
18
+ __device__ __forceinline__ void WARP_SYNC(unsigned mask = 0xffffffff) {
19
+ #if !defined(USE_ROCM)
20
+ return __syncwarp(mask);
21
+ #endif
22
+ }
23
+
24
+ #if defined(USE_ROCM)
25
+ __device__ __forceinline__ unsigned long long int WARP_BALLOT(int predicate)
26
+ {
27
+ return __ballot(predicate);
28
+ }
29
+ #else
30
+ __device__ __forceinline__ unsigned int WARP_BALLOT(int predicate, unsigned int mask = 0xffffffff)
31
+ {
32
+ #if !defined(USE_ROCM)
33
+ return __ballot_sync(mask, predicate);
34
+ #else
35
+ return __ballot(predicate);
36
+ #endif
37
+ }
38
+ #endif
39
+
40
+ template <typename T>
41
+ __device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff)
42
+ {
43
+ #if !defined(USE_ROCM)
44
+ return __shfl_xor_sync(mask, value, laneMask, width);
45
+ #else
46
+ return __shfl_xor(value, laneMask, width);
47
+ #endif
48
+ }
49
+
50
+ template <typename T>
51
+ __device__ __forceinline__ T WARP_SHFL(T value, int srcLane, int width = warpSize, unsigned int mask = 0xffffffff)
52
+ {
53
+ #if !defined(USE_ROCM)
54
+ return __shfl_sync(mask, value, srcLane, width);
55
+ #else
56
+ return __shfl(value, srcLane, width);
57
+ #endif
58
+ }
59
+
60
+ template <typename T>
61
+ __device__ __forceinline__ T WARP_SHFL_UP(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
62
+ {
63
+ #if !defined(USE_ROCM)
64
+ return __shfl_up_sync(mask, value, delta, width);
65
+ #else
66
+ return __shfl_up(value, delta, width);
67
+ #endif
68
+ }
69
+
70
+ template <typename T>
71
+ __device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
72
+ {
73
+ #if !defined(USE_ROCM)
74
+ return __shfl_down_sync(mask, value, delta, width);
75
+ #else
76
+ return __shfl_down(value, delta, width);
77
+ #endif
78
+ }
79
+
80
+ #if defined(USE_ROCM)
81
+ template<>
82
+ __device__ __forceinline__ int64_t WARP_SHFL_DOWN<int64_t>(int64_t value, unsigned int delta, int width , unsigned int mask)
83
+ {
84
+ //(HIP doesn't support int64_t). Trick from https://devblogs.nvidia.com/faster-parallel-reductions-kepler/
85
+ int2 a = *reinterpret_cast<int2*>(&value);
86
+ a.x = __shfl_down(a.x, delta);
87
+ a.y = __shfl_down(a.y, delta);
88
+ return *reinterpret_cast<int64_t*>(&a);
89
+ }
90
+ #endif
91
+
92
+ template<>
93
+ __device__ __forceinline__ c10::Half WARP_SHFL_DOWN<c10::Half>(c10::Half value, unsigned int delta, int width, unsigned int mask)
94
+ {
95
+ return c10::Half(WARP_SHFL_DOWN<unsigned short>(value.x, delta, width, mask), c10::Half::from_bits_t{});
96
+ }
97
+
98
+ template <typename T>
99
+ __device__ __forceinline__ c10::complex<T> WARP_SHFL_DOWN(c10::complex<T> value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
100
+ {
101
+ #if !defined(USE_ROCM)
102
+ return c10::complex<T>(
103
+ __shfl_down_sync(mask, value.real_, delta, width),
104
+ __shfl_down_sync(mask, value.imag_, delta, width));
105
+ #else
106
+ return c10::complex<T>(
107
+ __shfl_down(value.real_, delta, width),
108
+ __shfl_down(value.imag_, delta, width));
109
+ #endif
110
+ }
111
+
112
+ /**
113
+ * For CC 3.5+, perform a load using __ldg
114
+ */
115
+ template <typename T>
116
+ __device__ __forceinline__ T doLdg(const T* p) {
117
+ #if __CUDA_ARCH__ >= 350 && !defined(USE_ROCM)
118
+ return __ldg(p);
119
+ #else
120
+ return *p;
121
+ #endif
122
+ }
123
+
124
+ #else
125
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
126
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/EmptyTensor.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+
5
+ namespace at::detail {
6
+
7
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
8
+ IntArrayRef size,
9
+ ScalarType dtype,
10
+ std::optional<Device> device_opt,
11
+ std::optional<c10::MemoryFormat> memory_format_opt);
12
+
13
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
14
+ IntArrayRef size,
15
+ std::optional<ScalarType> dtype_opt,
16
+ std::optional<Layout> layout_opt,
17
+ std::optional<Device> device_opt,
18
+ std::optional<bool> pin_memory_opt,
19
+ std::optional<c10::MemoryFormat> memory_format_opt);
20
+
21
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
22
+ IntArrayRef size,
23
+ const TensorOptions &options);
24
+
25
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
26
+ IntArrayRef size,
27
+ IntArrayRef stride,
28
+ ScalarType dtype,
29
+ std::optional<Device> device_opt);
30
+
31
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
32
+ IntArrayRef size,
33
+ IntArrayRef stride,
34
+ std::optional<ScalarType> dtype_opt,
35
+ std::optional<Layout> layout_opt,
36
+ std::optional<Device> device_opt,
37
+ std::optional<bool> pin_memory_opt);
38
+
39
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
40
+ IntArrayRef size,
41
+ IntArrayRef stride,
42
+ const TensorOptions &options);
43
+
44
+
45
+ } // namespace at::detail
46
+
47
+ #else
48
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
49
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/Exceptions.h ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cublas_v2.h>
5
+ #include <cusparse.h>
6
+ #include <c10/macros/Export.h>
7
+
8
+ #if !defined(USE_ROCM)
9
+ #include <cusolver_common.h>
10
+ #else
11
+ #include <hipsolver/hipsolver.h>
12
+ #endif
13
+
14
+ #if defined(USE_CUDSS)
15
+ #include <cudss.h>
16
+ #endif
17
+
18
+ #include <ATen/Context.h>
19
+ #include <c10/util/Exception.h>
20
+ #include <c10/cuda/CUDAException.h>
21
+
22
+
23
+ namespace c10 {
24
+
25
+ class CuDNNError : public c10::Error {
26
+ using Error::Error;
27
+ };
28
+
29
+ } // namespace c10
30
+
31
+ #define AT_CUDNN_FRONTEND_CHECK(EXPR, ...) \
32
+ do { \
33
+ auto error_object = EXPR; \
34
+ if (!error_object.is_good()) { \
35
+ TORCH_CHECK_WITH(CuDNNError, false, \
36
+ "cuDNN Frontend error: ", error_object.get_message()); \
37
+ } \
38
+ } while (0) \
39
+
40
+ #define AT_CUDNN_CHECK_WITH_SHAPES(EXPR, ...) AT_CUDNN_CHECK(EXPR, "\n", ##__VA_ARGS__)
41
+
42
+ // See Note [CHECK macro]
43
+ #define AT_CUDNN_CHECK(EXPR, ...) \
44
+ do { \
45
+ cudnnStatus_t status = EXPR; \
46
+ if (status != CUDNN_STATUS_SUCCESS) { \
47
+ if (status == CUDNN_STATUS_NOT_SUPPORTED) { \
48
+ TORCH_CHECK_WITH(CuDNNError, false, \
49
+ "cuDNN error: ", \
50
+ cudnnGetErrorString(status), \
51
+ ". This error may appear if you passed in a non-contiguous input.", ##__VA_ARGS__); \
52
+ } else { \
53
+ TORCH_CHECK_WITH(CuDNNError, false, \
54
+ "cuDNN error: ", cudnnGetErrorString(status), ##__VA_ARGS__); \
55
+ } \
56
+ } \
57
+ } while (0)
58
+
59
+ namespace at::cuda::blas {
60
+ C10_EXPORT const char* _cublasGetErrorEnum(cublasStatus_t error);
61
+ } // namespace at::cuda::blas
62
+
63
+ #define TORCH_CUDABLAS_CHECK(EXPR) \
64
+ do { \
65
+ cublasStatus_t __err = EXPR; \
66
+ TORCH_CHECK(__err == CUBLAS_STATUS_SUCCESS, \
67
+ "CUDA error: ", \
68
+ at::cuda::blas::_cublasGetErrorEnum(__err), \
69
+ " when calling `" #EXPR "`"); \
70
+ } while (0)
71
+
72
+ const char *cusparseGetErrorString(cusparseStatus_t status);
73
+
74
+ #define TORCH_CUDASPARSE_CHECK(EXPR) \
75
+ do { \
76
+ cusparseStatus_t __err = EXPR; \
77
+ TORCH_CHECK(__err == CUSPARSE_STATUS_SUCCESS, \
78
+ "CUDA error: ", \
79
+ cusparseGetErrorString(__err), \
80
+ " when calling `" #EXPR "`"); \
81
+ } while (0)
82
+
83
+ #if defined(USE_CUDSS)
84
+ namespace at::cuda::cudss {
85
+ C10_EXPORT const char* cudssGetErrorMessage(cudssStatus_t error);
86
+ } // namespace at::cuda::solver
87
+
88
+ #define TORCH_CUDSS_CHECK(EXPR) \
89
+ do { \
90
+ cudssStatus_t __err = EXPR; \
91
+ if (__err == CUDSS_STATUS_EXECUTION_FAILED) { \
92
+ TORCH_CHECK_LINALG( \
93
+ false, \
94
+ "cudss error: ", \
95
+ at::cuda::cudss::cudssGetErrorMessage(__err), \
96
+ ", when calling `" #EXPR "`", \
97
+ ". This error may appear if the input matrix contains NaN. ");\
98
+ } else { \
99
+ TORCH_CHECK( \
100
+ __err == CUDSS_STATUS_SUCCESS, \
101
+ "cudss error: ", \
102
+ at::cuda::cudss::cudssGetErrorMessage(__err), \
103
+ ", when calling `" #EXPR "`. "); \
104
+ } \
105
+ } while (0)
106
+ #else
107
+ #define TORCH_CUDSS_CHECK(EXPR) EXPR
108
+ #endif
109
+
110
+ namespace at::cuda::solver {
111
+ #if !defined(USE_ROCM)
112
+
113
+ C10_EXPORT const char* cusolverGetErrorMessage(cusolverStatus_t status);
114
+
115
+ constexpr const char* _cusolver_backend_suggestion = \
116
+ "If you keep seeing this error, you may use " \
117
+ "`torch.backends.cuda.preferred_linalg_library()` to try " \
118
+ "linear algebra operators with other supported backends. " \
119
+ "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library";
120
+
121
+ // When cuda >= 11.5, cusolver normally finishes execution and sets info array indicating convergence issue.
122
+ #define TORCH_CUSOLVER_CHECK(EXPR) \
123
+ do { \
124
+ cusolverStatus_t __err = EXPR; \
125
+ if (__err == CUSOLVER_STATUS_INVALID_VALUE) { \
126
+ TORCH_CHECK_LINALG( \
127
+ false, \
128
+ "cusolver error: ", \
129
+ at::cuda::solver::cusolverGetErrorMessage(__err), \
130
+ ", when calling `" #EXPR "`", \
131
+ ". This error may appear if the input matrix contains NaN. ", \
132
+ at::cuda::solver::_cusolver_backend_suggestion); \
133
+ } else { \
134
+ TORCH_CHECK( \
135
+ __err == CUSOLVER_STATUS_SUCCESS, \
136
+ "cusolver error: ", \
137
+ at::cuda::solver::cusolverGetErrorMessage(__err), \
138
+ ", when calling `" #EXPR "`. ", \
139
+ at::cuda::solver::_cusolver_backend_suggestion); \
140
+ } \
141
+ } while (0)
142
+
143
+ #else // defined(USE_ROCM)
144
+
145
+ C10_EXPORT const char* hipsolverGetErrorMessage(hipsolverStatus_t status);
146
+
147
+ constexpr const char* _hipsolver_backend_suggestion = \
148
+ "If you keep seeing this error, you may use " \
149
+ "`torch.backends.cuda.preferred_linalg_library()` to try " \
150
+ "linear algebra operators with other supported backends. " \
151
+ "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library";
152
+
153
+ #define TORCH_CUSOLVER_CHECK(EXPR) \
154
+ do { \
155
+ hipsolverStatus_t __err = EXPR; \
156
+ if (__err == HIPSOLVER_STATUS_INVALID_VALUE) { \
157
+ TORCH_CHECK_LINALG( \
158
+ false, \
159
+ "hipsolver error: ", \
160
+ at::cuda::solver::hipsolverGetErrorMessage(__err), \
161
+ ", when calling `" #EXPR "`", \
162
+ ". This error may appear if the input matrix contains NaN. ", \
163
+ at::cuda::solver::_hipsolver_backend_suggestion); \
164
+ } else { \
165
+ TORCH_CHECK( \
166
+ __err == HIPSOLVER_STATUS_SUCCESS, \
167
+ "hipsolver error: ", \
168
+ at::cuda::solver::hipsolverGetErrorMessage(__err), \
169
+ ", when calling `" #EXPR "`. ", \
170
+ at::cuda::solver::_hipsolver_backend_suggestion); \
171
+ } \
172
+ } while (0)
173
+ #endif
174
+ } // namespace at::cuda::solver
175
+
176
+ #define AT_CUDA_CHECK(EXPR) C10_CUDA_CHECK(EXPR)
177
+
178
+ // For CUDA Driver API
179
+ //
180
+ // This is here instead of in c10 because NVRTC is loaded dynamically via a stub
181
+ // in ATen, and we need to use its nvrtcGetErrorString.
182
+ // See NOTE [ USE OF NVRTC AND DRIVER API ].
183
+ #if !defined(USE_ROCM)
184
+
185
+ #define AT_CUDA_DRIVER_CHECK(EXPR) \
186
+ do { \
187
+ CUresult __err = EXPR; \
188
+ if (__err != CUDA_SUCCESS) { \
189
+ const char* err_str; \
190
+ [[maybe_unused]] CUresult get_error_str_err = \
191
+ at::globalContext().getNVRTC().cuGetErrorString(__err, &err_str); \
192
+ if (get_error_str_err != CUDA_SUCCESS) { \
193
+ TORCH_CHECK(false, "CUDA driver error: unknown error"); \
194
+ } else { \
195
+ TORCH_CHECK(false, "CUDA driver error: ", err_str); \
196
+ } \
197
+ } \
198
+ } while (0)
199
+
200
+ #else
201
+
202
+ #define AT_CUDA_DRIVER_CHECK(EXPR) \
203
+ do { \
204
+ CUresult __err = EXPR; \
205
+ if (__err != CUDA_SUCCESS) { \
206
+ TORCH_CHECK(false, "CUDA driver error: ", static_cast<int>(__err)); \
207
+ } \
208
+ } while (0)
209
+
210
+ #endif
211
+
212
+ // For CUDA NVRTC
213
+ //
214
+ // Note: As of CUDA 10, nvrtc error code 7, NVRTC_ERROR_BUILTIN_OPERATION_FAILURE,
215
+ // incorrectly produces the error string "NVRTC unknown error."
216
+ // The following maps it correctly.
217
+ //
218
+ // This is here instead of in c10 because NVRTC is loaded dynamically via a stub
219
+ // in ATen, and we need to use its nvrtcGetErrorString.
220
+ // See NOTE [ USE OF NVRTC AND DRIVER API ].
221
+ #define AT_CUDA_NVRTC_CHECK(EXPR) \
222
+ do { \
223
+ nvrtcResult __err = EXPR; \
224
+ if (__err != NVRTC_SUCCESS) { \
225
+ if (static_cast<int>(__err) != 7) { \
226
+ TORCH_CHECK(false, "CUDA NVRTC error: ", at::globalContext().getNVRTC().nvrtcGetErrorString(__err)); \
227
+ } else { \
228
+ TORCH_CHECK(false, "CUDA NVRTC error: NVRTC_ERROR_BUILTIN_OPERATION_FAILURE"); \
229
+ } \
230
+ } \
231
+ } while (0)
232
+
233
+ #else
234
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
235
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/MemPool.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/Allocator.h>
5
+ #include <c10/cuda/CUDACachingAllocator.h>
6
+
7
+ namespace at::cuda {
8
+
9
+ // Keep BC only
10
+ using c10::CaptureId_t;
11
+ using c10::MempoolId_t;
12
+
13
+ // MemPool represents a pool of memory in a caching allocator. Currently,
14
+ // it's just the ID of the pool object maintained in the CUDACachingAllocator.
15
+ //
16
+ // An allocator pointer can be passed to the MemPool to define how the
17
+ // allocations should be done in the pool. For example: using a different
18
+ // system allocator such as ncclMemAlloc.
19
+ struct TORCH_CUDA_CPP_API MemPool {
20
+ MemPool(
21
+ c10::cuda::CUDACachingAllocator::CUDAAllocator* allocator = nullptr,
22
+ bool is_user_created = true,
23
+ bool use_on_oom = false,
24
+ bool no_split = false);
25
+ MemPool(const MemPool&) = delete;
26
+ MemPool(MemPool&&) = default;
27
+ MemPool& operator=(const MemPool&) = delete;
28
+ MemPool& operator=(MemPool&&) = default;
29
+ ~MemPool();
30
+
31
+ MempoolId_t id();
32
+ c10::cuda::CUDACachingAllocator::CUDAAllocator* allocator();
33
+ int use_count();
34
+ c10::DeviceIndex device();
35
+ static MempoolId_t graph_pool_handle(bool is_user_created = true);
36
+
37
+ private:
38
+ static std::atomic<CaptureId_t> uid_;
39
+ static std::atomic<CaptureId_t> uuid_;
40
+ c10::cuda::CUDACachingAllocator::CUDAAllocator* allocator_;
41
+ bool is_user_created_;
42
+ MempoolId_t id_;
43
+ c10::DeviceIndex device_;
44
+ };
45
+
46
+ } // namespace at::cuda
47
+
48
+ #else
49
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
50
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/NumericLimits.cuh ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cuda.h>
5
+ #include <limits.h>
6
+ #include <math.h>
7
+ #include <float.h>
8
+
9
+ // NumericLimits.cuh is a holder for numeric limits definitions of commonly used
10
+ // types. This header is very specific to ROCm HIP and may be removed in the future.
11
+ // This header is derived from the legacy THCNumerics.cuh.
12
+
13
+ // The lower_bound and upper_bound constants are same as lowest and max for
14
+ // integral types, but are -inf and +inf for floating point types. They are
15
+ // useful in implementing min, max, etc.
16
+
17
+ namespace at {
18
+
19
+ template <typename T>
20
+ struct numeric_limits {
21
+ };
22
+
23
+ // WARNING: the following at::numeric_limits definitions are there only to support
24
+ // HIP compilation for the moment. Use std::numeric_limits if you are not
25
+ // compiling for ROCm.
26
+ // from @colesbury: "The functions on numeric_limits aren't marked with
27
+ // __device__ which is why they don't work with ROCm. CUDA allows them
28
+ // because they're constexpr."
29
+
30
+ namespace {
31
+ // ROCm doesn't like INFINITY too.
32
+ constexpr double inf = INFINITY;
33
+ }
34
+
35
+ template <>
36
+ struct numeric_limits<bool> {
37
+ static inline __host__ __device__ bool lowest() { return false; }
38
+ static inline __host__ __device__ bool max() { return true; }
39
+ static inline __host__ __device__ bool lower_bound() { return false; }
40
+ static inline __host__ __device__ bool upper_bound() { return true; }
41
+ };
42
+
43
+ template <>
44
+ struct numeric_limits<uint8_t> {
45
+ static inline __host__ __device__ uint8_t lowest() { return 0; }
46
+ static inline __host__ __device__ uint8_t max() { return UINT8_MAX; }
47
+ static inline __host__ __device__ uint8_t lower_bound() { return 0; }
48
+ static inline __host__ __device__ uint8_t upper_bound() { return UINT8_MAX; }
49
+ };
50
+
51
+ template <>
52
+ struct numeric_limits<int8_t> {
53
+ static inline __host__ __device__ int8_t lowest() { return INT8_MIN; }
54
+ static inline __host__ __device__ int8_t max() { return INT8_MAX; }
55
+ static inline __host__ __device__ int8_t lower_bound() { return INT8_MIN; }
56
+ static inline __host__ __device__ int8_t upper_bound() { return INT8_MAX; }
57
+ };
58
+
59
+ template <>
60
+ struct numeric_limits<int16_t> {
61
+ static inline __host__ __device__ int16_t lowest() { return INT16_MIN; }
62
+ static inline __host__ __device__ int16_t max() { return INT16_MAX; }
63
+ static inline __host__ __device__ int16_t lower_bound() { return INT16_MIN; }
64
+ static inline __host__ __device__ int16_t upper_bound() { return INT16_MAX; }
65
+ };
66
+
67
+ template <>
68
+ struct numeric_limits<int32_t> {
69
+ static inline __host__ __device__ int32_t lowest() { return INT32_MIN; }
70
+ static inline __host__ __device__ int32_t max() { return INT32_MAX; }
71
+ static inline __host__ __device__ int32_t lower_bound() { return INT32_MIN; }
72
+ static inline __host__ __device__ int32_t upper_bound() { return INT32_MAX; }
73
+ };
74
+
75
+ template <>
76
+ struct numeric_limits<int64_t> {
77
+ #ifdef _MSC_VER
78
+ static inline __host__ __device__ int64_t lowest() { return _I64_MIN; }
79
+ static inline __host__ __device__ int64_t max() { return _I64_MAX; }
80
+ static inline __host__ __device__ int64_t lower_bound() { return _I64_MIN; }
81
+ static inline __host__ __device__ int64_t upper_bound() { return _I64_MAX; }
82
+ #else
83
+ static inline __host__ __device__ int64_t lowest() { return INT64_MIN; }
84
+ static inline __host__ __device__ int64_t max() { return INT64_MAX; }
85
+ static inline __host__ __device__ int64_t lower_bound() { return INT64_MIN; }
86
+ static inline __host__ __device__ int64_t upper_bound() { return INT64_MAX; }
87
+ #endif
88
+ };
89
+
90
+ template <>
91
+ struct numeric_limits<at::Half> {
92
+ static inline __host__ __device__ at::Half lowest() { return at::Half(0xFBFF, at::Half::from_bits()); }
93
+ static inline __host__ __device__ at::Half max() { return at::Half(0x7BFF, at::Half::from_bits()); }
94
+ static inline __host__ __device__ at::Half lower_bound() { return at::Half(0xFC00, at::Half::from_bits()); }
95
+ static inline __host__ __device__ at::Half upper_bound() { return at::Half(0x7C00, at::Half::from_bits()); }
96
+ };
97
+
98
+ template <>
99
+ struct numeric_limits<at::BFloat16> {
100
+ static inline __host__ __device__ at::BFloat16 lowest() { return at::BFloat16(0xFF7F, at::BFloat16::from_bits()); }
101
+ static inline __host__ __device__ at::BFloat16 max() { return at::BFloat16(0x7F7F, at::BFloat16::from_bits()); }
102
+ static inline __host__ __device__ at::BFloat16 lower_bound() { return at::BFloat16(0xFF80, at::BFloat16::from_bits()); }
103
+ static inline __host__ __device__ at::BFloat16 upper_bound() { return at::BFloat16(0x7F80, at::BFloat16::from_bits()); }
104
+ };
105
+
106
+ template <>
107
+ struct numeric_limits<float> {
108
+ static inline __host__ __device__ float lowest() { return -FLT_MAX; }
109
+ static inline __host__ __device__ float max() { return FLT_MAX; }
110
+ static inline __host__ __device__ float lower_bound() { return -static_cast<float>(inf); }
111
+ static inline __host__ __device__ float upper_bound() { return static_cast<float>(inf); }
112
+ };
113
+
114
+ template <>
115
+ struct numeric_limits<double> {
116
+ static inline __host__ __device__ double lowest() { return -DBL_MAX; }
117
+ static inline __host__ __device__ double max() { return DBL_MAX; }
118
+ static inline __host__ __device__ double lower_bound() { return -inf; }
119
+ static inline __host__ __device__ double upper_bound() { return inf; }
120
+ };
121
+
122
+ } // namespace at
123
+
124
+ #else
125
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
126
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PeerToPeerAccess.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <c10/macros/Macros.h>
3
+ #include <c10/core/Device.h>
4
+ #include <cstdint>
5
+
6
+ namespace at::cuda {
7
+ namespace detail {
8
+ void init_p2p_access_cache(int64_t num_devices);
9
+ }
10
+
11
+ TORCH_CUDA_CPP_API bool get_p2p_access(c10::DeviceIndex source_dev, c10::DeviceIndex dest_dev);
12
+ TORCH_CUDA_CPP_API bool get_fabric_access(c10::DeviceIndex device);
13
+
14
+ } // namespace at::cuda
15
+
16
+ #else
17
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
18
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PhiloxCudaState.h ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstdint>
5
+
6
+ #include <ATen/cuda/detail/PhiloxCudaStateRaw.cuh>
7
+
8
+ #else
9
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
10
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PhiloxUtils.cuh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/PhiloxCudaState.h>
5
+ #include <ATen/cuda/detail/UnpackRaw.cuh>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/PinnedMemoryAllocator.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CachingHostAllocator.h>
5
+
6
+ namespace at::cuda {
7
+
8
+ inline TORCH_CUDA_CPP_API at::HostAllocator* getPinnedMemoryAllocator() {
9
+ return at::getHostAllocator(at::kCUDA);
10
+ }
11
+ } // namespace at::cuda
12
+
13
+ #else
14
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
15
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/ScanUtils.cuh ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ceil_div.h>
5
+ #include <ATen/cuda/DeviceUtils.cuh>
6
+ #include <ATen/cuda/AsmUtils.cuh>
7
+ #include <c10/macros/Macros.h>
8
+
9
+ // Collection of in-kernel scan / prefix sum utilities
10
+
11
+ namespace at::cuda {
12
+
13
+ // Inclusive prefix sum for binary vars using intra-warp voting +
14
+ // shared memory
15
+ template <typename T, bool KillWARDependency, class BinaryFunction>
16
+ __device__ void inclusiveBinaryPrefixScan(T* smem, bool in, T* out, BinaryFunction binop) {
17
+ // Within-warp, we use warp voting.
18
+ #if defined (USE_ROCM)
19
+ unsigned long long int vote = WARP_BALLOT(in);
20
+ T index = __popcll(getLaneMaskLe() & vote);
21
+ T carry = __popcll(vote);
22
+ #else
23
+ T vote = WARP_BALLOT(in);
24
+ T index = __popc(getLaneMaskLe() & vote);
25
+ T carry = __popc(vote);
26
+ #endif
27
+
28
+ int warp = threadIdx.x / C10_WARP_SIZE;
29
+
30
+ // Per each warp, write out a value
31
+ if (getLaneId() == 0) {
32
+ smem[warp] = carry;
33
+ }
34
+
35
+ __syncthreads();
36
+
37
+ // Sum across warps in one thread. This appears to be faster than a
38
+ // warp shuffle scan for CC 3.0+
39
+ if (threadIdx.x == 0) {
40
+ int current = 0;
41
+ for (int i = 0; i < blockDim.x / C10_WARP_SIZE; ++i) {
42
+ T v = smem[i];
43
+ smem[i] = binop(smem[i], current);
44
+ current = binop(current, v);
45
+ }
46
+ }
47
+
48
+ __syncthreads();
49
+
50
+ // load the carry from the preceding warp
51
+ if (warp >= 1) {
52
+ index = binop(index, smem[warp - 1]);
53
+ }
54
+
55
+ *out = index;
56
+
57
+ if (KillWARDependency) {
58
+ __syncthreads();
59
+ }
60
+ }
61
+
62
+ // Exclusive prefix sum for binary vars using intra-warp voting +
63
+ // shared memory
64
+ template <typename T, bool KillWARDependency, class BinaryFunction>
65
+ __device__ void exclusiveBinaryPrefixScan(T* smem, bool in, T* out, T* carry, BinaryFunction binop) {
66
+ inclusiveBinaryPrefixScan<T, false, BinaryFunction>(smem, in, out, binop);
67
+
68
+ // Inclusive to exclusive
69
+ *out -= (T) in;
70
+
71
+ // The outgoing carry for all threads is the last warp's sum
72
+ *carry = smem[at::ceil_div<int>(blockDim.x, C10_WARP_SIZE) - 1];
73
+
74
+ if (KillWARDependency) {
75
+ __syncthreads();
76
+ }
77
+ }
78
+
79
+ } // namespace at::cuda
80
+
81
+ #else
82
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
83
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/Sleep.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/macros/Export.h>
4
+ #include <cstdint>
5
+
6
+ namespace at::cuda {
7
+
8
+ // enqueues a kernel that spins for the specified number of cycles
9
+ TORCH_CUDA_CU_API void sleep(int64_t cycles);
10
+
11
+ // enqueues a kernel that spins until a flag is cleared by a
12
+ // corresponding call to clear_flag()
13
+ TORCH_CUDA_CU_API void busy_wait_for_flag();
14
+ TORCH_CUDA_CU_API void clear_flag();
15
+
16
+ // flushes instruction cache for ROCm; no-op for CUDA
17
+ TORCH_CUDA_CU_API void flush_icache();
18
+
19
+ } // namespace at::cuda
20
+
21
+ #else
22
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
23
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/ThrustAllocator.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstddef>
5
+ #include <c10/cuda/CUDACachingAllocator.h>
6
+
7
+ namespace at::cuda {
8
+
9
+ /// Allocator for Thrust to re-route its internal device allocations
10
+ /// to the THC allocator
11
+ class ThrustAllocator {
12
+ public:
13
+ typedef char value_type;
14
+
15
+ char* allocate(std::ptrdiff_t size) {
16
+ return static_cast<char*>(c10::cuda::CUDACachingAllocator::raw_alloc(size));
17
+ }
18
+
19
+ void deallocate(char* p, size_t size) {
20
+ c10::cuda::CUDACachingAllocator::raw_delete(p);
21
+ }
22
+ };
23
+
24
+ } // namespace at::cuda
25
+
26
+ #else
27
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
28
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub-RadixSortPairs.cuh ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #define TORCH_ASSERT_NO_OPERATORS
5
+ #include <ATen/cuda/CUDAConfig.h>
6
+ #include <ATen/cuda/cub.cuh>
7
+
8
+ namespace at::cuda::cub::detail {
9
+
10
+ template <typename key_t, int value_size>
11
+ void radix_sort_pairs_impl(
12
+ const key_t* keys_in,
13
+ key_t* keys_out,
14
+ const OpaqueType<value_size>* values_in,
15
+ OpaqueType<value_size>* values_out,
16
+ int64_t n,
17
+ bool descending,
18
+ int64_t begin_bit,
19
+ int64_t end_bit) {
20
+ TORCH_CHECK(
21
+ n <= std::numeric_limits<int>::max(),
22
+ "cub sort does not support sorting more than INT_MAX elements");
23
+ using key_t_ = typename detail::cuda_type<key_t>::type;
24
+
25
+ auto allocator = c10::cuda::CUDACachingAllocator::get();
26
+ c10::DataPtr keys_out_owner;
27
+
28
+ if (keys_out == nullptr) {
29
+ keys_out_owner = allocator->allocate(n * sizeof(key_t));
30
+ keys_out = reinterpret_cast<key_t*>(keys_out_owner.get());
31
+ }
32
+
33
+ const key_t_* keys_in_ = reinterpret_cast<const key_t_*>(keys_in);
34
+ key_t_* keys_out_ = reinterpret_cast<key_t_*>(keys_out);
35
+
36
+ if (descending) {
37
+ CUB_WRAPPER(
38
+ NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortPairsDescending,
39
+ keys_in_,
40
+ keys_out_,
41
+ values_in,
42
+ values_out,
43
+ n,
44
+ begin_bit,
45
+ end_bit,
46
+ c10::cuda::getCurrentCUDAStream());
47
+ } else {
48
+ CUB_WRAPPER(
49
+ NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortPairs,
50
+ keys_in_,
51
+ keys_out_,
52
+ values_in,
53
+ values_out,
54
+ n,
55
+ begin_bit,
56
+ end_bit,
57
+ c10::cuda::getCurrentCUDAStream());
58
+ }
59
+ }
60
+
61
+ #define AT_INSTANTIATE_SORT_PAIRS(key_t, value_size) \
62
+ template void radix_sort_pairs_impl( \
63
+ const key_t* keys_in, \
64
+ key_t* keys_out, \
65
+ const OpaqueType<value_size>* values_in, \
66
+ OpaqueType<value_size>* values_out, \
67
+ int64_t n, \
68
+ bool descending, \
69
+ int64_t begin_bit, \
70
+ int64_t end_bit);
71
+
72
+ #define AT_INSTANTIATE_SORT_PAIRS_8(scalar_t, ScalarType) \
73
+ AT_INSTANTIATE_SORT_PAIRS(scalar_t, 8)
74
+
75
+ } // namespace at::cuda::cub::detail
76
+
77
+ #else
78
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
79
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub.cuh ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/cuda/cub.h>
4
+
5
+ #include <cstddef>
6
+ #include <type_traits>
7
+ #include <iterator>
8
+ #include <limits>
9
+
10
+ #ifndef USE_ROCM
11
+ #include <cuda/std/functional>
12
+ #endif
13
+
14
+ #include <ATen/cuda/cub_definitions.cuh>
15
+ #include <ATen/cuda/CUDAContextLight.h>
16
+
17
+ #if USE_GLOBAL_CUB_WRAPPED_NAMESPACE()
18
+
19
+ #include <cub/cub.cuh>
20
+
21
+ #else
22
+
23
+ // include cub in a safe manner, see:
24
+ // https://github.com/pytorch/pytorch/pull/55292
25
+ #undef CUB_NS_POSTFIX //undef to avoid redefinition warnings
26
+ #undef CUB_NS_PREFIX
27
+ #undef CUB_NS_QUALIFIER
28
+ #define CUB_NS_PREFIX namespace at_cuda_detail {
29
+ #define CUB_NS_POSTFIX }
30
+ #define CUB_NS_QUALIFIER ::at_cuda_detail::cub
31
+ #include <cub/cub.cuh>
32
+ #undef CUB_NS_POSTFIX
33
+ #undef CUB_NS_PREFIX
34
+ #undef CUB_NS_QUALIFIER
35
+
36
+ #endif
37
+
38
+ #include <ATen/cuda/Exceptions.h>
39
+ #include <c10/cuda/CUDACachingAllocator.h>
40
+ #include <c10/cuda/CUDAStream.h>
41
+
42
+ // handle the temporary storage and 'twice' calls for cub API
43
+ #define CUB_WRAPPER(func, ...) do { \
44
+ size_t temp_storage_bytes = 0; \
45
+ AT_CUDA_CHECK(func(nullptr, temp_storage_bytes, __VA_ARGS__)); \
46
+ auto& caching_allocator = *::c10::cuda::CUDACachingAllocator::get(); \
47
+ auto temp_storage = caching_allocator.allocate(temp_storage_bytes); \
48
+ AT_CUDA_CHECK(func(temp_storage.get(), temp_storage_bytes, __VA_ARGS__));\
49
+ } while (false)
50
+
51
+ #ifdef USE_ROCM
52
+ #define NO_ROCM(x)
53
+ #define ROCM_HIPCUB(x) ::hipcub
54
+ #else
55
+ #define NO_ROCM(x) x
56
+ #define ROCM_HIPCUB(x) x
57
+ #endif
58
+
59
+ #if CUB_V3_PLUS()
60
+ #include <thrust/iterator/transform_iterator.h>
61
+ #include <thrust/iterator/counting_iterator.h>
62
+ #include <thrust/iterator/constant_iterator.h>
63
+ #define ATEN_CUB_TRANSFORM_ITERATOR(ValueType, ...) ::thrust::transform_iterator<__VA_ARGS__>
64
+ #define ATEN_CUB_COUNTING_ITERATOR(...) ::thrust::counting_iterator<__VA_ARGS__>
65
+ #define ATEN_CUB_CONSTANT_ITERATOR(...) ::thrust::constant_iterator<__VA_ARGS__>
66
+ #define ATEN_CUB_MAXIMUM() ::cuda::maximum<>()
67
+ #else
68
+ #define ATEN_CUB_TRANSFORM_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::TransformInputIterator<__VA_ARGS__>
69
+ #define ATEN_CUB_COUNTING_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::CountingInputIterator<__VA_ARGS__>
70
+ #define ATEN_CUB_CONSTANT_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::ConstantInputIterator<__VA_ARGS__>
71
+ #define ATEN_CUB_MAXIMUM() NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::Max()
72
+ #endif
73
+
74
+ #if defined(USE_ROCM)
75
+
76
+ // backport https://github.com/NVIDIA/cub/pull/306 for c10::BFloat16
77
+
78
+ template <>
79
+ struct ROCM_HIPCUB(cub)::FpLimits<c10::BFloat16>
80
+ {
81
+ static __host__ __device__ __forceinline__ c10::BFloat16 Max() {
82
+ unsigned short max_word = 0x7F7F;
83
+ return reinterpret_cast<c10::BFloat16&>(max_word);
84
+ }
85
+
86
+ static __host__ __device__ __forceinline__ c10::BFloat16 Lowest() {
87
+ unsigned short lowest_word = 0xFF7F;
88
+ return reinterpret_cast<c10::BFloat16&>(lowest_word);
89
+ }
90
+ };
91
+
92
+ template <>
93
+ struct ROCM_HIPCUB(cub)::NumericTraits<c10::BFloat16>:
94
+ ROCM_HIPCUB(cub)::BaseTraits<ROCM_HIPCUB(cub)::FLOATING_POINT, true, false, unsigned short, c10::BFloat16> {};
95
+
96
+ #endif
97
+
98
+ #if !defined(USE_ROCM)
99
+ namespace at::native {
100
+ namespace cub = ::at_cuda_detail::cub;
101
+ } // namespace at::native
102
+ #endif
103
+
104
+ namespace at::cuda::cub {
105
+
106
+ namespace detail {
107
+
108
+ template<typename T>
109
+ struct cuda_type {
110
+ using type = T;
111
+ };
112
+ template<>
113
+ struct cuda_type<c10::Half> {
114
+ using type = __half;
115
+ };
116
+
117
+ #if !defined(USE_ROCM)
118
+
119
+ template<>
120
+ struct cuda_type<c10::BFloat16> {
121
+ using type = __nv_bfloat16;
122
+ };
123
+
124
+ #elif defined(USE_ROCM)
125
+
126
+ template<>
127
+ struct cuda_type<c10::BFloat16> {
128
+ using type = hip_bfloat16;
129
+ };
130
+
131
+ #endif
132
+
133
+ } // namespace detail
134
+
135
+ template<typename key_t, typename value_t, typename OffsetIteratorT>
136
+ inline void segmented_sort_pairs(
137
+ const key_t *keys_in, key_t *keys_out,
138
+ const value_t *values_in, value_t *values_out,
139
+ int64_t num_elements, int64_t num_segments,
140
+ OffsetIteratorT begin_offsets, OffsetIteratorT end_offsets,
141
+ bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8
142
+ ) {
143
+ TORCH_CHECK(num_elements <= std::numeric_limits<int>::max(),
144
+ "cub sort does not support sorting more than INT_MAX elements");
145
+ TORCH_CHECK(num_segments <= std::numeric_limits<int>::max(),
146
+ "cub sort does not support sorting more than INT_MAX elements");
147
+ using key_t_ = typename detail::cuda_type<key_t>::type;
148
+
149
+ auto allocator = c10::cuda::CUDACachingAllocator::get();
150
+ c10::DataPtr keys_out_owner;
151
+
152
+ if (keys_out == nullptr) {
153
+ keys_out_owner = allocator->allocate(num_elements * sizeof(key_t));
154
+ keys_out = reinterpret_cast<key_t *>(keys_out_owner.get());
155
+ }
156
+
157
+ const key_t_ *keys_in_ = reinterpret_cast<const key_t_*>(keys_in);
158
+ key_t_ *keys_out_ = reinterpret_cast<key_t_*>(keys_out);
159
+
160
+ if (descending) {
161
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSegmentedRadixSort::SortPairsDescending,
162
+ keys_in_, keys_out_, values_in, values_out,
163
+ num_elements, num_segments, begin_offsets, end_offsets,
164
+ begin_bit, end_bit, c10::cuda::getCurrentCUDAStream());
165
+ } else {
166
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSegmentedRadixSort::SortPairs,
167
+ keys_in_, keys_out_, values_in, values_out,
168
+ num_elements, num_segments, begin_offsets, end_offsets,
169
+ begin_bit, end_bit, c10::cuda::getCurrentCUDAStream());
170
+ }
171
+ }
172
+
173
+ template <typename KeysInputIteratorT, typename ValuesInputIteratorT, typename ValuesOutputIteratorT, typename NumSelectedIteratorT>
174
+ inline void unique_by_key(
175
+ KeysInputIteratorT keys_in, ValuesInputIteratorT values_in,
176
+ ValuesOutputIteratorT values_out,
177
+ NumSelectedIteratorT num_selected, int64_t num_input_items)
178
+ {
179
+ // TODO: use thrust::discard_iterator to handle null keys_out when https://github.com/NVIDIA/cub/issues/406 is fixed.
180
+ using KeyT = typename std::iterator_traits<KeysInputIteratorT>::value_type;
181
+ auto allocator = c10::cuda::CUDACachingAllocator::get();
182
+ c10::DataPtr keys_out_owner;
183
+ keys_out_owner = allocator->allocate(num_input_items * sizeof(KeyT));
184
+ auto keys_out_ = static_cast<KeyT *>(keys_out_owner.get());
185
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSelect::UniqueByKey,
186
+ keys_in, values_in, keys_out_, values_out, num_selected, num_input_items, c10::cuda::getCurrentCUDAStream());
187
+ }
188
+
189
+ namespace impl {
190
+
191
+ template<typename InputIteratorT1, typename InputIteratorT2, typename OutputIteratorT, class ScanOpT>
192
+ C10_LAUNCH_BOUNDS_1(1)
193
+ __global__ void transform_vals(InputIteratorT1 a, InputIteratorT2 b, OutputIteratorT out, ScanOpT scan_op){
194
+ // NOTE: out here not the final scan output, but an intermediate of the accumulation type.
195
+ using acc_t = typename std::iterator_traits<OutputIteratorT>::value_type;
196
+ *out = scan_op(static_cast<acc_t>(*a), static_cast<acc_t>(*b));
197
+ }
198
+
199
+ // even though cub is supposed to support tensors with int_max elements, in reality it doesn't,
200
+ // so split at int_max/2
201
+ constexpr int max_cub_size = std::numeric_limits<int>::max() / 2 + 1; // 2**30
202
+ }
203
+
204
+ // non synchronizing cub call
205
+ // even though cub is supposed to support tensors with int_max elements, in reality it doesn't,
206
+ // so split at int_max/2
207
+ template<typename InputIteratorT, typename OutputIteratorT, typename ScanOpT, int max_cub_size=impl::max_cub_size>
208
+ inline void inclusive_scan(InputIteratorT input, OutputIteratorT output, ScanOpT scan_op, int64_t num_items) {
209
+ #if defined(USE_ROCM)
210
+ //For ROCm, use hipCUB chained iterators
211
+ CUB_WRAPPER(NO_ROCM(detail)::hipcub::DeviceScan::InclusiveScan,
212
+ input,
213
+ output,
214
+ scan_op,
215
+ num_items,
216
+ at::cuda::getCurrentCUDAStream());
217
+ C10_HIP_KERNEL_LAUNCH_CHECK();
218
+ #else
219
+ // non synchronizing cub call
220
+ // even though cub is supposed to support tensors with int_max elements, in reality it doesn't,
221
+ // so split at int_max/2
222
+ int size_cub = std::min<int64_t>(num_items, max_cub_size);
223
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::InclusiveScan,
224
+ input,
225
+ output,
226
+ scan_op,
227
+ size_cub,
228
+ at::cuda::getCurrentCUDAStream());
229
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
230
+ using input_t = typename std::iterator_traits<InputIteratorT>::value_type;
231
+ for (int64_t i = max_cub_size; i < num_items; i += max_cub_size) {
232
+ auto allocator = c10::cuda::CUDACachingAllocator::get();
233
+ c10::DataPtr first_elem = allocator->allocate(sizeof(input_t));
234
+ auto first_elem_ptr = reinterpret_cast<input_t *>(first_elem.get());
235
+
236
+ size_cub = std::min<int64_t>(num_items - i, max_cub_size);
237
+ impl::transform_vals<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>(
238
+ output + i - 1,
239
+ input + i,
240
+ first_elem_ptr,
241
+ scan_op);
242
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
243
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan,
244
+ input + i + 1,
245
+ output + i,
246
+ scan_op,
247
+ ::at_cuda_detail::cub::FutureValue<input_t>(first_elem_ptr),
248
+ size_cub,
249
+ at::cuda::getCurrentCUDAStream());
250
+ }
251
+ #endif
252
+ }
253
+
254
+ # if defined(CUDA_VERSION) || defined(USE_ROCM)
255
+
256
+ template<typename T>
257
+ struct BlockPrefixCallbackOp
258
+ {
259
+ public:
260
+ T running_total;
261
+
262
+ __host__ __device__ BlockPrefixCallbackOp(T running_total) : running_total(running_total) {}
263
+
264
+ // Callback operator to be entered by the first warp of threads in the block.
265
+ // Thread-0 is responsible for returning a value for seeding the block-wide scan.
266
+ __host__ __device__ T operator()(T block_aggregate)
267
+ {
268
+ T old_prefix = running_total;
269
+ running_total += block_aggregate;
270
+ return old_prefix;
271
+ }
272
+ };
273
+
274
+ template<int BLOCK_THREADS, int ITEMS_PER_THREAD, typename T>
275
+ __global__ void final_scan_kernel(const T* d_in, T* d_out, T* agg, int64_t nelem, int iters_per_cta) {
276
+ int64_t offset = BLOCK_THREADS * ITEMS_PER_THREAD * iters_per_cta * (int64_t)blockIdx.x;
277
+ int64_t remaining = nelem - offset;
278
+ if (remaining <= 0) {
279
+ return;
280
+ }
281
+
282
+ d_in += offset;
283
+ d_out += offset;
284
+
285
+ using BlockLoadT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockLoad<T, BLOCK_THREADS, ITEMS_PER_THREAD, ROCM_HIPCUB(at_cuda_detail::cub)::BLOCK_LOAD_WARP_TRANSPOSE>;
286
+
287
+ // Specialize BlockStore type for our thread block (uses warp-striped loads for coalescing, then transposes in shared
288
+ // memory to a blocked arrangement)
289
+ using BlockStoreT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockStore<T, BLOCK_THREADS, ITEMS_PER_THREAD, ROCM_HIPCUB(at_cuda_detail::cub)::BLOCK_STORE_WARP_TRANSPOSE>;
290
+
291
+ // Specialize BlockScan type for our thread block
292
+ using BlockScanT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockScan<T, BLOCK_THREADS, ROCM_HIPCUB(at_cuda_detail::cub)::BLOCK_SCAN_WARP_SCANS>;
293
+ using BlockReduceT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockReduce<T, BLOCK_THREADS>;
294
+
295
+
296
+ // Shared memory
297
+ __shared__ union TempStorage
298
+ {
299
+ typename BlockLoadT::TempStorage load;
300
+ typename BlockStoreT::TempStorage store;
301
+ typename BlockScanT::TempStorage scan;
302
+ typename BlockReduceT::TempStorage reduce;
303
+ } temp_storage;
304
+
305
+ // load agg and reduce my starting value
306
+ T agg_data;
307
+ agg_data = threadIdx.x >= blockIdx.x ? T(0) : agg[threadIdx.x];
308
+ // if there are fewer threads than previous values to be read,
309
+ // read another value
310
+ if (threadIdx.x + blockDim.x < blockIdx.x) {
311
+ agg_data += agg[threadIdx.x + blockDim.x];
312
+ }
313
+ T aggregate = BlockReduceT(temp_storage.reduce).Sum(agg_data);
314
+ __syncthreads();
315
+ BlockPrefixCallbackOp prefix_op(aggregate);
316
+
317
+
318
+ // Per-thread tile data
319
+ T data[ITEMS_PER_THREAD];
320
+
321
+ for (int i=0; i<iters_per_cta; i++){
322
+ // Load items into a blocked arrangement
323
+ if (remaining >= BLOCK_THREADS * ITEMS_PER_THREAD) {
324
+ BlockLoadT(temp_storage.load).Load(d_in, data);
325
+ } else {
326
+ #pragma unroll
327
+ for (int j=0; j<ITEMS_PER_THREAD; j++) {
328
+ data[j] = 0;
329
+ }
330
+ BlockLoadT(temp_storage.load).Load(d_in, data, remaining);
331
+ }
332
+
333
+ // Barrier for smem reuse
334
+ __syncthreads();
335
+
336
+ // Compute inclusive prefix sum
337
+ BlockScanT(temp_storage.scan).InclusiveSum(data, data, prefix_op);
338
+
339
+ // Barrier for smem reuse
340
+ __syncthreads();
341
+
342
+ // Store items from a blocked arrangement
343
+ if (remaining >= BLOCK_THREADS * ITEMS_PER_THREAD) {
344
+ BlockStoreT(temp_storage.store).Store(d_out, data);
345
+ } else {
346
+ BlockStoreT(temp_storage.store).Store(d_out, data, remaining);
347
+ }
348
+ d_in += BLOCK_THREADS * ITEMS_PER_THREAD;
349
+ d_out += BLOCK_THREADS * ITEMS_PER_THREAD;
350
+ remaining -= BLOCK_THREADS * ITEMS_PER_THREAD;
351
+ if (remaining <= 0) return;
352
+ __syncthreads();
353
+ }
354
+
355
+ }
356
+
357
+ template <typename T, typename aggT, bool nonzero>
358
+ struct TransformFunctor {
359
+ __device__ aggT operator()(T value) const {
360
+ if constexpr (!nonzero) {
361
+ return value;
362
+ } else {
363
+ return (value != T(0)) ? 1 : 0;
364
+ }
365
+ }
366
+ };
367
+
368
+ template<int BLOCK_THREADS, int ITEMS_PER_THREAD, bool nonzero, typename T, typename aggT>
369
+ __global__ void calc_block_sums(const T * d_in, aggT * agg, int64_t nelem, int iters_per_cta){
370
+ int64_t offset = BLOCK_THREADS * ITEMS_PER_THREAD * iters_per_cta * (int64_t)blockIdx.x;
371
+ int64_t remaining = nelem - offset;
372
+ if (remaining <= 0) {
373
+ return;
374
+ }
375
+ d_in += offset;
376
+
377
+ using BlockLoadT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockLoad<aggT, BLOCK_THREADS, ITEMS_PER_THREAD, ROCM_HIPCUB(at_cuda_detail::cub)::BLOCK_LOAD_STRIPED>;
378
+ using BlockReduceT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockReduce<aggT, BLOCK_THREADS>;
379
+ // Shared memory
380
+ __shared__ union TempStorage
381
+ {
382
+ typename BlockLoadT::TempStorage load;
383
+ typename BlockReduceT::TempStorage reduce;
384
+ } temp_storage;
385
+ aggT data[ITEMS_PER_THREAD];
386
+ aggT agg_val = 0;
387
+ TransformFunctor<T, aggT, nonzero> transform_functor;
388
+ auto iter_in = ATEN_CUB_TRANSFORM_ITERATOR(aggT, TransformFunctor<T, aggT, nonzero>, const T*)(d_in, transform_functor);
389
+ for (int i=0; i<iters_per_cta; i++){
390
+ if (remaining >= BLOCK_THREADS * ITEMS_PER_THREAD) {
391
+ BlockLoadT(temp_storage.load).Load(iter_in, data);
392
+ __syncthreads();
393
+ agg_val += BlockReduceT(temp_storage.reduce).Sum(data);
394
+
395
+ } else {
396
+ BlockLoadT(temp_storage.load).Load(iter_in, data, remaining, aggT(0));
397
+ __syncthreads();
398
+ agg_val += BlockReduceT(temp_storage.reduce).Sum(data);
399
+ }
400
+ iter_in += BLOCK_THREADS * ITEMS_PER_THREAD;
401
+ remaining -= BLOCK_THREADS * ITEMS_PER_THREAD;
402
+ if (remaining <= 0) {
403
+ // for nonzeros we need to write out last blocks
404
+ // accumulated value to be able to compute
405
+ // total number of nonzeros
406
+ if (nonzero && threadIdx.x == 0) {
407
+ agg[blockIdx.x] = agg_val;
408
+ }
409
+ return;
410
+ }
411
+ __syncthreads();
412
+
413
+ }
414
+ if (threadIdx.x == 0) {
415
+ agg[blockIdx.x] = agg_val;
416
+ }
417
+
418
+ }
419
+
420
+ template <typename T>
421
+ struct NonZeroOp {
422
+ __host__ __device__ __forceinline__ int operator()(const T& a) const {
423
+ return (a != T(0));
424
+ }
425
+ };
426
+
427
+ template<int size>
428
+ constexpr int block_threads(){
429
+ if constexpr (size >=16) {
430
+ return 128;
431
+ } else if constexpr (size >=8) {
432
+ return 256;
433
+ } else {
434
+ return 512;
435
+ }
436
+ }
437
+
438
+ template<typename scalar_t, typename ScanOpT>
439
+ inline void inclusive_deterministic_scan(const scalar_t * input, scalar_t * output, ScanOpT scan_op, int64_t num_items) {
440
+ static_assert(std::is_same_v<ScanOpT, std::plus<scalar_t>>, "");
441
+ constexpr int BLOCK_THREADS = block_threads<sizeof(scalar_t)>();
442
+ constexpr int ITEMS_PER_THREAD = 16;
443
+ auto grid_size = (num_items + BLOCK_THREADS * ITEMS_PER_THREAD - 1) / (BLOCK_THREADS * ITEMS_PER_THREAD);
444
+ const int64_t num_sms = at::cuda::getCurrentDeviceProperties()->multiProcessorCount;
445
+
446
+ const int iters_per_cta = (grid_size + num_sms - 1)/num_sms;
447
+ grid_size = std::min(num_sms, grid_size);
448
+ // simple reduction in scan kernel handles at most 2 items per thread
449
+ TORCH_INTERNAL_ASSERT(2 * BLOCK_THREADS >= grid_size);
450
+ auto& allocator = *c10::cuda::CUDACachingAllocator::get();
451
+ auto agg = allocator.allocate(grid_size * sizeof(scalar_t));
452
+ calc_block_sums<BLOCK_THREADS, ITEMS_PER_THREAD, false>
453
+ <<<grid_size, BLOCK_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>(
454
+ input, (scalar_t*)agg.get(), num_items, iters_per_cta);
455
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
456
+ final_scan_kernel<BLOCK_THREADS, ITEMS_PER_THREAD>
457
+ <<<grid_size, BLOCK_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>(
458
+ input, output, (scalar_t*)agg.get(), num_items, iters_per_cta);
459
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
460
+ }
461
+
462
+ #endif
463
+
464
+ template<typename InputIteratorT, typename OutputIteratorT, typename ScanOpT, typename InitValueT, int max_cub_size=impl::max_cub_size>
465
+ inline void exclusive_scan(InputIteratorT input, OutputIteratorT output, ScanOpT scan_op, InitValueT init_value, int64_t num_items) {
466
+ #if defined(USE_ROCM)
467
+ //For ROCm, use hipCUB chained iterators
468
+ CUB_WRAPPER(NO_ROCM(detail)::hipcub::DeviceScan::ExclusiveScan,
469
+ input,
470
+ output,
471
+ scan_op,
472
+ init_value,
473
+ num_items,
474
+ at::cuda::getCurrentCUDAStream());
475
+ C10_HIP_KERNEL_LAUNCH_CHECK();
476
+ #else
477
+ // non synchronizing cub call
478
+ // even though cub is supposed to support tensors with int_max elements, in reality it doesn't,
479
+ // so split at int_max/2
480
+ int size_cub = std::min<int64_t>(num_items, max_cub_size);
481
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan,
482
+ input,
483
+ output,
484
+ scan_op,
485
+ init_value,
486
+ size_cub,
487
+ at::cuda::getCurrentCUDAStream());
488
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
489
+ for (int64_t i = max_cub_size; i < num_items; i += max_cub_size) {
490
+ auto allocator = c10::cuda::CUDACachingAllocator::get();
491
+ c10::DataPtr first_elem = allocator->allocate(sizeof(InitValueT));
492
+ auto first_elem_ptr = reinterpret_cast<InitValueT *>(first_elem.get());
493
+
494
+ size_cub = std::min<int64_t>(num_items - i, max_cub_size);
495
+ impl::transform_vals<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>(
496
+ output + i - 1,
497
+ input + i - 1,
498
+ first_elem_ptr,
499
+ scan_op);
500
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
501
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan,
502
+ input + i,
503
+ output + i,
504
+ scan_op,
505
+ ::at_cuda_detail::cub::FutureValue<InitValueT>(first_elem_ptr),
506
+ size_cub,
507
+ at::cuda::getCurrentCUDAStream());
508
+ }
509
+ #endif
510
+ }
511
+
512
+
513
+ template <typename KeysInputIteratorT, typename ValuesInputIteratorT, typename ValuesOutputIteratorT>
514
+ inline void inclusive_sum_by_key(KeysInputIteratorT keys, ValuesInputIteratorT input, ValuesOutputIteratorT output, int64_t num_items) {
515
+ TORCH_CHECK(num_items <= std::numeric_limits<int>::max(),
516
+ "cub InclusiveSumByKey does not support more than INT_MAX elements");
517
+ #if !defined(USE_ROCM)
518
+ CUB_WRAPPER(at_cuda_detail::cub::DeviceScan::InclusiveSumByKey,
519
+ keys, input, output, num_items, NO_ROCM(::cuda)::std::equal_to<>(), at::cuda::getCurrentCUDAStream());
520
+ #else
521
+ CUB_WRAPPER(cub::DeviceScan::InclusiveSumByKey,
522
+ keys, input, output, num_items, hipcub::Equality(), at::cuda::getCurrentCUDAStream());
523
+ #endif
524
+ }
525
+
526
+ template <typename KeysInputIteratorT, typename ValuesInputIteratorT, typename ValuesOutputIteratorT, typename ScanOpT>
527
+ inline void inclusive_scan_by_key(KeysInputIteratorT keys, ValuesInputIteratorT input, ValuesOutputIteratorT output, ScanOpT scan_op, int64_t num_items) {
528
+ TORCH_CHECK(num_items <= std::numeric_limits<int>::max(),
529
+ "cub InclusiveSumByKey does not support more than INT_MAX elements");
530
+ #if !defined(USE_ROCM)
531
+ CUB_WRAPPER(at_cuda_detail::cub::DeviceScan::InclusiveScanByKey,
532
+ keys, input, output, scan_op, num_items, NO_ROCM(::cuda)::std::equal_to<>(), at::cuda::getCurrentCUDAStream());
533
+ #else
534
+ CUB_WRAPPER(cub::DeviceScan::InclusiveScanByKey,
535
+ keys, input, output, scan_op, num_items, hipcub::Equality(), at::cuda::getCurrentCUDAStream());
536
+ #endif
537
+ }
538
+
539
+
540
+ template <typename InputIteratorT, typename OutputIteratorT, typename NumSelectedIteratorT>
541
+ void unique(InputIteratorT input, OutputIteratorT output,
542
+ NumSelectedIteratorT num_selected_out, int64_t num_items) {
543
+ TORCH_CHECK(num_items <= std::numeric_limits<int>::max(),
544
+ "cub unique does not support more than INT_MAX elements");
545
+ CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSelect::Unique,
546
+ input, output, num_selected_out, num_items, at::cuda::getCurrentCUDAStream());
547
+ }
548
+
549
+ template <typename InputIteratorT, typename OutputIteratorT, typename CountsOutputIteratorT,
550
+ typename LengthOutputIteratorT>
551
+ void run_length_encode(InputIteratorT input, OutputIteratorT output, CountsOutputIteratorT counts_out,
552
+ LengthOutputIteratorT length_out, int64_t num_items) {
553
+ TORCH_CHECK(num_items <= std::numeric_limits<int>::max(),
554
+ "cub run_length_encode does not support more than INT_MAX elements");
555
+ CUB_WRAPPER(
556
+ NO_ROCM(at_cuda_detail)::cub::DeviceRunLengthEncode::Encode,
557
+ input, output, counts_out, length_out, num_items,
558
+ at::cuda::getCurrentCUDAStream());
559
+ }
560
+
561
+ template <typename InputIteratorT, typename OutputIteratorT, typename ReductionOpT, typename T>
562
+ void reduce(InputIteratorT input, OutputIteratorT output, int64_t num_items, ReductionOpT op, T init) {
563
+ TORCH_CHECK(num_items <= std::numeric_limits<int>::max(),
564
+ "cub reduce does not support more than INT_MAX elements");
565
+ CUB_WRAPPER(
566
+ NO_ROCM(at_cuda_detail)::cub::DeviceReduce::Reduce,
567
+ input, output, num_items, op, init,
568
+ at::cuda::getCurrentCUDAStream());
569
+
570
+ }
571
+
572
+ } // namespace at::cuda::cub
573
+
574
+ #else
575
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
576
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+ #include <c10/core/ScalarType.h>
5
+ #include <ATen/cuda/CUDAConfig.h>
6
+
7
+ // NOTE: These templates are intentionally not defined in this header,
8
+ // which avoids re-compiling them for each translation unit. If you get
9
+ // a link error, you need to add an explicit instantiation for your
10
+ // types in cub.cu
11
+
12
+ namespace at::cuda::cub {
13
+
14
+ inline int get_num_bits(uint64_t max_key) {
15
+ int num_bits = 1;
16
+ while (max_key > 1) {
17
+ max_key >>= 1;
18
+ num_bits++;
19
+ }
20
+ return num_bits;
21
+ }
22
+
23
+ namespace detail {
24
+
25
+ // radix_sort_pairs doesn't interact with value_t other than to copy
26
+ // the data, so we can save template instantiations by reinterpreting
27
+ // it as an opaque type.
28
+ // We use native integer types for 1/2/4/8-byte values to reduce
29
+ // register usage in CUDA kernels. For sizes > 8 fall back to char array.
30
+ template <int N> struct alignas(N) OpaqueType { char data[N]; };
31
+ template <> struct alignas(1) OpaqueType<1> { uint8_t data; };
32
+ template <> struct alignas(2) OpaqueType<2> { uint16_t data; };
33
+ template <> struct alignas(4) OpaqueType<4> { uint32_t data; };
34
+ template <> struct alignas(8) OpaqueType<8> { uint64_t data; };
35
+
36
+ template<typename key_t, int value_size>
37
+ void radix_sort_pairs_impl(
38
+ const key_t *keys_in, key_t *keys_out,
39
+ const OpaqueType<value_size> *values_in, OpaqueType<value_size> *values_out,
40
+ int64_t n, bool descending, int64_t begin_bit, int64_t end_bit);
41
+
42
+ } // namespace detail
43
+
44
+ template<typename key_t, typename value_t>
45
+ void radix_sort_pairs(
46
+ const key_t *keys_in, key_t *keys_out,
47
+ const value_t *values_in, value_t *values_out,
48
+ int64_t n, bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8) {
49
+ static_assert(std::is_trivially_copyable_v<value_t> ||
50
+ AT_ROCM_ENABLED(), // ROCm incorrectly fails this check for vector types
51
+ "radix_sort_pairs value type must be trivially copyable");
52
+ // Make value type opaque, so all inputs of a certain size use the same template instantiation
53
+ using opaque_t = detail::OpaqueType<sizeof(value_t)>;
54
+ static_assert(sizeof(value_t) <= 8 && (sizeof(value_t) & (sizeof(value_t) - 1)) == 0,
55
+ "This size of value_t is not instantiated. Please instantiate it in cub.cu"
56
+ " and modify this check.");
57
+ static_assert(sizeof(value_t) == alignof(value_t), "Expected value_t to be size-aligned");
58
+ detail::radix_sort_pairs_impl(
59
+ keys_in, keys_out,
60
+ reinterpret_cast<const opaque_t*>(values_in),
61
+ reinterpret_cast<opaque_t*>(values_out),
62
+ n, descending, begin_bit, end_bit);
63
+ }
64
+
65
+ template<typename key_t>
66
+ void radix_sort_keys(
67
+ const key_t *keys_in, key_t *keys_out,
68
+ int64_t n, bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8);
69
+
70
+ // NOTE: Intermediate sums will be truncated to input_t precision
71
+ template <typename input_t, typename output_t>
72
+ void inclusive_sum_truncating(const input_t *input, output_t *output, int64_t n);
73
+
74
+ template <typename scalar_t>
75
+ void inclusive_sum(const scalar_t *input, scalar_t *output, int64_t n) {
76
+ return inclusive_sum_truncating(input, output, n);
77
+ }
78
+
79
+ // NOTE: Sums are done is common_type<input_t, output_t>
80
+ template <typename input_t, typename output_t>
81
+ void exclusive_sum_in_common_type(const input_t *input, output_t *output, int64_t n);
82
+
83
+ template <typename scalar_t>
84
+ void exclusive_sum(const scalar_t *input, scalar_t *output, int64_t n) {
85
+ return exclusive_sum_in_common_type(input, output, n);
86
+ }
87
+
88
+ void mask_exclusive_sum(const uint8_t *mask, int64_t *output_idx, int64_t n);
89
+ inline void mask_exclusive_sum(const bool *mask, int64_t *output_idx, int64_t n) {
90
+ return mask_exclusive_sum(
91
+ reinterpret_cast<const uint8_t*>(mask), output_idx, n);
92
+ }
93
+
94
+ } // namespace at::cuda::cub
95
+
96
+ #else
97
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
98
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/cub_definitions.cuh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #if !defined(USE_ROCM)
5
+ #include <cuda.h> // for CUDA_VERSION
6
+ #endif
7
+
8
+ #if !defined(USE_ROCM)
9
+ #include <cub/version.cuh>
10
+ #else
11
+ #define CUB_VERSION 200001
12
+ #endif
13
+
14
+ // cub support for CUB_WRAPPED_NAMESPACE is added to cub 1.13.1 in:
15
+ // https://github.com/NVIDIA/cub/pull/326
16
+ // CUB_WRAPPED_NAMESPACE is defined globally in cmake/Dependencies.cmake
17
+ // starting from CUDA 11.5
18
+ #if defined(CUB_WRAPPED_NAMESPACE) || defined(THRUST_CUB_WRAPPED_NAMESPACE)
19
+ #define USE_GLOBAL_CUB_WRAPPED_NAMESPACE() true
20
+ #else
21
+ #define USE_GLOBAL_CUB_WRAPPED_NAMESPACE() false
22
+ #endif
23
+
24
+ // There were many bc-breaking changes in major version release of CCCL v3.0.0
25
+ // Please see https://nvidia.github.io/cccl/cccl/3.0_migration_guide.html
26
+ #if CUB_VERSION >= 200800
27
+ #define CUB_V3_PLUS() true
28
+ #else
29
+ #define CUB_V3_PLUS() false
30
+ #endif
31
+
32
+ #else
33
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
34
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/BLASConstants.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/TensorBase.h>
5
+
6
+ namespace at::cuda::detail {
7
+
8
+ float *get_cublas_device_one();
9
+ float *get_cublas_device_zero();
10
+ float *get_user_alpha_ptr();
11
+
12
+ } // namespace at::cuda::detail
13
+
14
+ #else
15
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
16
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/CUDAHooks.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/detail/CUDAHooksInterface.h>
5
+
6
+ #include <ATen/Generator.h>
7
+
8
+ // TODO: No need to have this whole header, we can just put it all in
9
+ // the cpp file
10
+
11
+ namespace at::cuda::detail {
12
+
13
+ // Set the callback to initialize Magma, which is set by
14
+ // torch_cuda_cu. This indirection is required so magma_init is called
15
+ // in the same library where Magma will be used.
16
+ TORCH_CUDA_CPP_API void set_magma_init_fn(void (*magma_init_fn)());
17
+
18
+
19
+ // The real implementation of CUDAHooksInterface
20
+ struct CUDAHooks : public at::CUDAHooksInterface {
21
+ CUDAHooks(at::CUDAHooksArgs /*unused*/) {}
22
+ void init() const override;
23
+ Device getDeviceFromPtr(void* data) const override;
24
+ bool isPinnedPtr(const void* data) const override;
25
+ const Generator& getDefaultGenerator(
26
+ DeviceIndex device_index = -1) const override;
27
+ Generator getNewGenerator(
28
+ DeviceIndex device_index = -1) const override;
29
+ bool hasCUDA() const override;
30
+ bool hasMAGMA() const override;
31
+ bool hasCuDNN() const override;
32
+ bool hasCuSOLVER() const override;
33
+ bool hasCuBLASLt() const override;
34
+ bool hasROCM() const override;
35
+ bool hasCKSDPA() const override;
36
+ bool hasCKGEMM() const override;
37
+ const at::cuda::NVRTC& nvrtc() const override;
38
+ DeviceIndex current_device() const override;
39
+ bool isBuilt() const override {return true;}
40
+ bool isAvailable() const override {return hasCUDA();}
41
+ bool hasPrimaryContext(DeviceIndex device_index) const override;
42
+ Allocator* getCUDADeviceAllocator() const override;
43
+ Allocator* getPinnedMemoryAllocator() const override;
44
+ bool compiledWithCuDNN() const override;
45
+ bool compiledWithMIOpen() const override;
46
+ bool supportsDilatedConvolutionWithCuDNN() const override;
47
+ bool supportsDepthwiseConvolutionWithCuDNN() const override;
48
+ bool supportsBFloat16ConvolutionWithCuDNNv8() const override;
49
+ bool supportsBFloat16RNNWithCuDNN() const override;
50
+ bool hasCUDART() const override;
51
+ long versionCUDART() const override;
52
+ long versionCuDNN() const override;
53
+ long versionRuntimeCuDNN() const override;
54
+ long versionCuDNNFrontend() const override;
55
+ long versionMIOpen() const override;
56
+ std::string showConfig() const override;
57
+ double batchnormMinEpsilonCuDNN() const override;
58
+ int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex device_index) const override;
59
+ void cuFFTSetPlanCacheMaxSize(DeviceIndex device_index, int64_t max_size) const override;
60
+ int64_t cuFFTGetPlanCacheSize(DeviceIndex device_index) const override;
61
+ void cuFFTClearPlanCache(DeviceIndex device_index) const override;
62
+ int getNumGPUs() const override;
63
+ DeviceIndex deviceCount() const override;
64
+ DeviceIndex getCurrentDevice() const override;
65
+
66
+ #ifdef USE_ROCM
67
+ bool isGPUArch(const std::vector<std::string>& archs, DeviceIndex device_index = -1) const override;
68
+ #endif
69
+ void deviceSynchronize(DeviceIndex device_index) const override;
70
+ };
71
+
72
+ } // at::cuda::detail
73
+
74
+ #else
75
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
76
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/DeviceThreadHandles.h ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Some stateful GPU libraries, such as cuDNN, cuBLAS, use handles to store states.
3
+ // These handles are tied to device, and these libraries requires/recommends not to
4
+ // share handles across host threads.
5
+ //
6
+ // These libraries recommend using one handle per host thread. We may not want to do
7
+ // this because threads are relatively light-weight, but creating and destroying
8
+ // handles is expensive (destroying the handle causes synchronizations). DataParallel,
9
+ // for example, creates new threads for each forward pass.
10
+ //
11
+ // This file implements a handle pool mechanism. The handle pool returns handles on
12
+ // demand as threads request them. If all existing handles in the pool are in use,
13
+ // it creates a new one. As threads terminate, they release handles back into the pool.
14
+ // In this way, the handle pool never creates more handles than the high-water mark of
15
+ // active threads, so it's efficient with DataParallel.
16
+
17
+ #pragma once
18
+
19
+ #include <unordered_map>
20
+ #include <vector>
21
+ #include <utility>
22
+ #include <mutex>
23
+ #include <memory>
24
+
25
+ #include <c10/util/Exception.h>
26
+
27
+ namespace at::cuda { namespace {
28
+
29
+ template <typename Handle_t, void Create(Handle_t *), void Destroy(Handle_t)>
30
+ struct DeviceThreadHandlePool : public std::enable_shared_from_this<DeviceThreadHandlePool<Handle_t, Create, Destroy>> {
31
+
32
+ struct Handle {
33
+ Handle_t handle;
34
+ Handle(bool create = false) : handle(nullptr)
35
+ {
36
+ if(create) Create(&handle);
37
+ }
38
+ // std::vector.emplace() and push_back() may route through temporaries and call
39
+ // copy/move constructors along the way. If this is the case, we don't want
40
+ // the destructors of temporaries to call cudnnDestroy on the handle.
41
+ // We can achieve safety (for the narrow case of stashing within std::vectors)
42
+ // by making Handle moveable but not copyable, and transferring handle ownership
43
+ // to the latest constructed object. This is not a substitute for full-blown
44
+ // reference counting, but reference counting may be overkill here.
45
+ // Another alternative is to wrap the saved Handles in unique_ptrs, i.e.,
46
+ // unordered_map<int, vector<unique_ptr<Handle>>> created_handles;
47
+ Handle(const Handle& rhs) = delete;
48
+ // Following https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom
49
+ Handle(Handle&& rhs) noexcept : Handle() { std::swap(handle, rhs.handle); }
50
+ // operator= takes argument by value
51
+ Handle& operator=(Handle rhs) { std::swap(handle, rhs.handle); return *this; }
52
+ ~Handle() {
53
+ if(handle) Destroy(handle);
54
+ }
55
+ };
56
+
57
+ std::mutex mutex;
58
+
59
+ // Handles are lazily created as different threads request them,
60
+ // but are never destroyed until the end of the process.
61
+ // The maximum number of handles this process will create for each device is equal
62
+ // to the high-water mark of the number of concurrently active threads that request
63
+ // handles for that device.
64
+ // When threads terminate, they release their handles back into the pool for reuse.
65
+ // Otherwise, new handles would be created every time new threads were spawned,
66
+ // resulting in poor performance for Python modules that repeatedly or frequently
67
+ // spawned new sets of threads (like DataParallel, which creates a new set of threads
68
+ // for each forward pass).
69
+ //
70
+ // To prevent potential deadlocks, we explicitly choose not to cap the number
71
+ // of handles that are created per device.
72
+ // Example of danger: If we cap the max handles at 4, and 5 threads are sharing a device,
73
+ // only 4 can make forward progress at any time. The other 4 will not release their
74
+ // handles until they exit, so the fifth cannot make progress until then. This is
75
+ // not a problem...UNLESS all 5 threads attempt some sort of synchronization at an
76
+ // intermediate point (ie, before any of them have exited). We have no way to anticipate
77
+ // or enforce that user threads will not attempt such intermediate synchronization.
78
+ // The only way to ensure safety is to avoid imposing a cap on the number of handles.
79
+ std::unordered_map<int, std::vector<Handle>> created_handles;
80
+ std::unordered_map<int, std::vector<Handle_t>> available_handles;
81
+
82
+ // PoolWindow lazily creates and caches the handles that a particular thread is using,
83
+ // so in the common case handle access doesn't incur either handle creation or a mutex lock.
84
+ class PoolWindow
85
+ {
86
+ public:
87
+ PoolWindow(std::shared_ptr<DeviceThreadHandlePool> parent): weak_parent(std::move(parent)) {}
88
+ ~PoolWindow(){ release(); }
89
+
90
+ Handle_t reserve(int device)
91
+ {
92
+ // If this thread already has a handle for this device, return it
93
+ if(my_handles.find(device) != my_handles.end())
94
+ return my_handles[device];
95
+
96
+ // otherwise, either grab a handle from the pool if one is available,
97
+ // or if not, create a new one.
98
+ auto parent = weak_parent.lock();
99
+ TORCH_CHECK(parent, "Cannot create handle during program termination");
100
+ std::lock_guard<std::mutex> guard(parent->mutex);
101
+
102
+ if(parent->available_handles[device].size() > 0)
103
+ {
104
+ my_handles[device] = parent->available_handles[device].back();
105
+ parent->available_handles[device].pop_back();
106
+ }
107
+ else
108
+ {
109
+ // In local testing, I do observe that emplace_back sometimes routes through temporaries
110
+ // that incur move-constructor and destructor calls. See comments in Handle above.
111
+ parent->created_handles[device].emplace_back(true /*create*/);
112
+ my_handles[device] = parent->created_handles[device].back().handle;
113
+ }
114
+
115
+ return my_handles[device];
116
+ }
117
+
118
+ private:
119
+ // Stores the per-device handles currently owned by this thread
120
+ std::unordered_map<int, Handle_t> my_handles;
121
+
122
+ std::weak_ptr<DeviceThreadHandlePool> weak_parent;
123
+
124
+ // Called by the destructor. Releases this thread's handles back into the pool.
125
+ void release() {
126
+ if(!my_handles.empty()) {
127
+ auto parent = weak_parent.lock();
128
+ if (!parent) {
129
+ // If this thread exits after atexit handlers have completed, the
130
+ // cuda context itself may be invalid, so we must leak the handles.
131
+ return;
132
+ }
133
+
134
+ std::lock_guard<std::mutex> guard(parent->mutex);
135
+ for(auto d_h : my_handles)
136
+ parent->available_handles[d_h.first].push_back(d_h.second);
137
+ }
138
+ }
139
+ };
140
+
141
+ // Warning:
142
+ // If you want to change this function, be aware that this function will be called
143
+ // by multiple threads and there is no mutex guarding the call of this function, so
144
+ // make sure your implementation is thread-safe.
145
+ PoolWindow *newPoolWindow() {
146
+ // The returned pointer will be owned by a thread local variable
147
+ // so that different threads does not share the same PoolWindow.
148
+ return new PoolWindow(this->shared_from_this());
149
+ }
150
+ };
151
+
152
+ }} // namespace at::cuda::detail::<anonymous>
153
+
154
+ #else
155
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
156
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/IndexUtils.cuh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/TensorBase.h>
5
+ #include <ATen/cuda/detail/TensorInfo.cuh>
6
+ #include <ATen/native/CanUse32BitIndexMath.h>
7
+
8
+ namespace at::cuda::detail {
9
+
10
+ TORCH_CUDA_CU_API bool maybeOverlappingIndices(const at::TensorBase &t);
11
+ using at::native::canUse32BitIndexMath;
12
+
13
+ template <typename scalar, typename IndexType>
14
+ TensorInfo<scalar, IndexType>
15
+ getTensorInfo(const at::TensorBase &t) {
16
+ IndexType sz[MAX_TENSORINFO_DIMS];
17
+ IndexType st[MAX_TENSORINFO_DIMS];
18
+
19
+ int dims = t.dim();
20
+ for (int i = 0; i < dims; ++i) {
21
+ sz[i] = t.size(i);
22
+ st[i] = t.stride(i);
23
+ }
24
+
25
+ scalar* data_ptr = nullptr;
26
+
27
+ if constexpr (std::is_const_v<scalar>) {
28
+ data_ptr = t.const_data_ptr<scalar>();
29
+ } else {
30
+ data_ptr = t.mutable_data_ptr<scalar>();
31
+ }
32
+
33
+ return TensorInfo<scalar, IndexType>(
34
+ data_ptr, dims, sz, st);
35
+ }
36
+
37
+ } // namespace at::cuda::detail
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/IntegerDivider.cuh ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <assert.h>
5
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
6
+ #include <cuda_runtime.h>
7
+ #endif
8
+
9
+ namespace at::cuda::detail {
10
+
11
+ // A utility class to implement integer division by multiplication, given a fixed
12
+ // divisor.
13
+ //
14
+ // WARNING: The fast divider algorithm is only implemented for unsigned int;
15
+ // otherwise we default to plain integer division. For unsigned int,
16
+ // we further assume that the dividend is at most INT32_MAX. Thus,
17
+ // IntDivider must NOT be used for general integer division.
18
+ //
19
+ // This reduced range is enough for our purpose, and it allows us to
20
+ // slightly simplify the computation.
21
+ //
22
+ // (NOTE: Below, "2^k" denotes exponentiation, i.e., 1<<k.)
23
+ //
24
+ // For any N-bit unsigned integer d (> 0), we can find a "magic number" m (2^N
25
+ // <= m < 2^(N+1)) and shift s such that:
26
+ //
27
+ // \floor(n / d) = \floor((m * n) / 2^(N+s)).
28
+ //
29
+ // Given such m and s, the integer division can be then implemented as:
30
+ //
31
+ // let m' = m - 2^N // 0 <= m' < 2^N
32
+ //
33
+ // fast_integer_division(n):
34
+ // // Multiply two N-bit unsigned integers: the result is a 2N-bit unsigned
35
+ // // integer. Then take the higher N bits.
36
+ // t = (m' * n) >> N
37
+ //
38
+ // // Here we use the fact that n is less than 2^(N-1): otherwise the value
39
+ // // of (t + n) may not fit in an N-bit integer.
40
+ // return (t + n) >> s
41
+ //
42
+ // Finding such a magic number is surprisingly easy:
43
+ //
44
+ // s = \ceil(\log_2 d)
45
+ // m' = \floor(2^N * (2^s - d) / d) + 1 // Need 2N-bit integer arithmetic.
46
+ //
47
+ // See also:
48
+ // - Division by Invariant Integers Using Multiplication,
49
+ // Torbjörn Granlund and Peter L. Montgomery, 1994.
50
+ //
51
+ // - http://www.hackersdelight.org/magic.htm
52
+ //
53
+ // - http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html
54
+
55
+ // Result of div/mod operation stored together.
56
+ template <typename Value>
57
+ struct DivMod {
58
+ Value div, mod;
59
+
60
+ C10_HOST_DEVICE DivMod(Value div, Value mod) : div(div), mod(mod) { }
61
+ };
62
+
63
+ // Base case: we only have an implementation for uint32_t for now. For
64
+ // everything else, we use plain division.
65
+ template <typename Value>
66
+ struct IntDivider {
67
+ IntDivider() = default;
68
+ IntDivider(Value d) : divisor(d) { }
69
+
70
+ C10_HOST_DEVICE inline Value div(Value n) const { return n / divisor; }
71
+ C10_HOST_DEVICE inline Value mod(Value n) const { return n % divisor; }
72
+ C10_HOST_DEVICE inline DivMod<Value> divmod(Value n) const {
73
+ return DivMod<Value>(n / divisor, n % divisor);
74
+ }
75
+
76
+ Value divisor;
77
+ };
78
+
79
+ // Implement fast integer division.
80
+ template <>
81
+ struct IntDivider<unsigned int> {
82
+ static_assert(sizeof(unsigned int) == 4, "Assumes 32-bit unsigned int.");
83
+
84
+ IntDivider() = default;
85
+
86
+ IntDivider(unsigned int d) : divisor(d) {
87
+ assert(divisor >= 1 && divisor <= INT32_MAX);
88
+
89
+ // TODO: gcc/clang has __builtin_clz() but it's not portable.
90
+ for (shift = 0; shift < 32; shift++) if ((1U << shift) >= divisor) break;
91
+
92
+ uint64_t one = 1;
93
+ uint64_t magic = ((one << 32) * ((one << shift) - divisor)) / divisor + 1;
94
+ m1 = magic;
95
+ assert(m1 > 0 && m1 == magic); // m1 must fit in 32 bits.
96
+ }
97
+
98
+ C10_HOST_DEVICE inline unsigned int div(unsigned int n) const {
99
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
100
+ // 't' is the higher 32-bits of unsigned 32-bit multiplication of 'n' and
101
+ // 'm1'.
102
+ unsigned int t = __umulhi(n, m1);
103
+ return (t + n) >> shift;
104
+ #else
105
+ // Using uint64_t so that the addition does not overflow.
106
+ uint64_t t = ((uint64_t) n * m1) >> 32;
107
+ return (t + n) >> shift;
108
+ #endif
109
+ }
110
+
111
+ C10_HOST_DEVICE inline unsigned int mod(unsigned int n) const {
112
+ return n - div(n) * divisor;
113
+ }
114
+
115
+ C10_HOST_DEVICE inline DivMod<unsigned int> divmod(unsigned int n) const {
116
+ unsigned int q = div(n);
117
+ return DivMod<unsigned int>(q, n - q * divisor);
118
+ }
119
+
120
+ unsigned int divisor; // d above.
121
+ unsigned int m1; // Magic number: m' above.
122
+ unsigned int shift; // Shift amounts.
123
+ };
124
+
125
+ } // namespace at::cuda::detail
126
+
127
+ #else
128
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
129
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/KernelUtils.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <limits>
5
+ #include <c10/util/Exception.h>
6
+
7
+ namespace at::cuda::detail {
8
+
9
+ // CUDA: grid stride looping
10
+ //
11
+ // int64_t _i_n_d_e_x specifically prevents overflow in the loop increment.
12
+ // If input.numel() < INT_MAX, _i_n_d_e_x < INT_MAX, except after the final
13
+ // iteration of the loop where _i_n_d_e_x += blockDim.x * gridDim.x can be
14
+ // greater than INT_MAX. But in that case _i_n_d_e_x >= n, so there are no
15
+ // further iterations and the overflowed value in i=_i_n_d_e_x is not used.
16
+ #define CUDA_KERNEL_LOOP_TYPE(i, n, index_type) \
17
+ int64_t _i_n_d_e_x = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; \
18
+ for (index_type i=_i_n_d_e_x; _i_n_d_e_x < (n); _i_n_d_e_x+=blockDim.x * gridDim.x, i=_i_n_d_e_x)
19
+
20
+ #define CUDA_KERNEL_LOOP(i, n) CUDA_KERNEL_LOOP_TYPE(i, n, int)
21
+
22
+
23
+ // Use 1024 threads per block, which requires cuda sm_2x or above
24
+ constexpr int CUDA_NUM_THREADS = 1024;
25
+
26
+ // CUDA: number of blocks for threads.
27
+ inline int GET_BLOCKS(const int64_t N, const int64_t max_threads_per_block=CUDA_NUM_THREADS) {
28
+ TORCH_INTERNAL_ASSERT(N > 0, "CUDA kernel launch blocks must be positive, but got N=", N);
29
+ constexpr int64_t max_int = std::numeric_limits<int>::max();
30
+
31
+ // Round up division for positive number that cannot cause integer overflow
32
+ auto block_num = (N - 1) / max_threads_per_block + 1;
33
+ TORCH_INTERNAL_ASSERT(block_num <= max_int, "Can't schedule too many blocks on CUDA device");
34
+
35
+ return static_cast<int>(block_num);
36
+ }
37
+
38
+ } // namespace at::cuda::detail
39
+
40
+ #else
41
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
42
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/LazyNVRTC.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/detail/CUDAHooksInterface.h>
4
+ namespace at::cuda {
5
+ // Forward-declares at::cuda::NVRTC
6
+ struct NVRTC;
7
+
8
+ namespace detail {
9
+ extern NVRTC lazyNVRTC;
10
+ } // namespace detail
11
+
12
+ } // namespace at::cuda
13
+
14
+ #else
15
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
16
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/OffsetCalculator.cuh ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <cstdint>
6
+ #include <type_traits>
7
+ #include <c10/macros/Macros.h>
8
+ #include <ATen/native/TensorIterator.h>
9
+ #include <ATen/cuda/detail/IntegerDivider.cuh>
10
+
11
+ // If element_sizes is nullptr, then the strides will be in bytes, otherwise
12
+ // the strides will be in # of elements.
13
+ // Operands that share the same shape, but may have different strides.
14
+ // OffsetCalculator iterates the tensor in a column-major order
15
+
16
+ #if defined(USE_ROCM)
17
+ constexpr int MAX_DIMS = 16;
18
+ #else
19
+ constexpr int MAX_DIMS = 25;
20
+ #endif
21
+
22
+ template <int NARGS, typename index_t = uint32_t, bool signed_strides = false>
23
+ struct OffsetCalculator {
24
+ // We allow having negative strides to implement some operations like torch.flip
25
+ using stride_t = std::conditional_t<signed_strides,
26
+ std::make_signed_t<index_t>,
27
+ index_t>;
28
+ // The offset for each argument. Wrapper around fixed-size array.
29
+ // On CUDA, zero sized array is not allowed, so when we are handling nullary
30
+ // operators, we need to create a size 1 offset to avoid compiler failure.
31
+ // This size 1 offset is just a placeholder, and we will not use it.
32
+ using offset_type = std::array<stride_t, std::max<int>(NARGS, 1)>;
33
+
34
+ // if element_sizes is nullptr, then the strides will be in bytes, otherwise
35
+ // the strides will be in # of elements.
36
+ OffsetCalculator(int dims, const int64_t* sizes, const int64_t* const* strides, const int64_t* element_sizes=nullptr) : dims(dims) {
37
+ TORCH_CHECK(dims <= MAX_DIMS, "tensor has too many (>", MAX_DIMS, ") dims");
38
+ for (int i=0; i < dims; i++){
39
+ sizes_[i] = at::cuda::detail::IntDivider<index_t>(sizes[i]);
40
+ for (int arg = 0; arg < NARGS; arg++) {
41
+ int64_t element_size = (element_sizes == nullptr ? 1LL : element_sizes[arg]);
42
+ strides_[i][arg] = strides[arg][i] / element_size;
43
+ }
44
+ }
45
+ }
46
+
47
+ C10_HOST_DEVICE offset_type get(index_t linear_idx) const {
48
+ offset_type offsets;
49
+
50
+ #if defined(USE_ROCM)
51
+ if ((dims > 0) && (dims <= 2)) {
52
+ auto divmod = sizes_[0].divmod(linear_idx);
53
+ #pragma unroll
54
+ for (int arg = 0; arg < NARGS; arg++)
55
+ offsets[arg] = divmod.mod * strides_[0][arg];
56
+ if (dims >= 2) {
57
+ divmod = sizes_[1].divmod(divmod.div);
58
+ #pragma unroll
59
+ for (int arg = 0; arg < NARGS; arg++)
60
+ offsets[arg] += divmod.mod * strides_[1][arg];
61
+ }
62
+ // [...]
63
+ return offsets;
64
+ }
65
+ #endif
66
+
67
+ #pragma unroll
68
+ for (int arg = 0; arg < NARGS; arg++) {
69
+ offsets[arg] = 0;
70
+ }
71
+
72
+ #pragma unroll
73
+ for (int dim = 0; dim < MAX_DIMS; ++dim) {
74
+ if (dim == dims) {
75
+ break;
76
+ }
77
+ auto divmod = sizes_[dim].divmod(linear_idx);
78
+ linear_idx = divmod.div;
79
+
80
+ #pragma unroll
81
+ for (int arg = 0; arg < NARGS; arg++) {
82
+ offsets[arg] += divmod.mod * strides_[dim][arg];
83
+ }
84
+
85
+ }
86
+ return offsets;
87
+ }
88
+
89
+ int dims;
90
+ at::cuda::detail::IntDivider<index_t> sizes_[MAX_DIMS];
91
+ stride_t strides_[MAX_DIMS][std::max<int>(NARGS, 1)];
92
+ };
93
+
94
+ template <int NARGS, typename index_t = uint32_t>
95
+ struct TrivialOffsetCalculator {
96
+ // The offset for each argument. Wrapper around fixed-size array.
97
+ // The offsets are in # of elements, not in bytes.
98
+ // On CUDA, zero sized array is not allowed, so when we are handling nullary
99
+ // operators, we need to create a size 1 offset to avoid compiler failure.
100
+ // This size 1 offset is just a placeholder, and we will not use it.
101
+ using offset_type = std::array<index_t, std::max<int>(NARGS, 1)>;
102
+
103
+ C10_HOST_DEVICE offset_type get(index_t linear_idx) const {
104
+ offset_type offsets;
105
+ #pragma unroll
106
+ for (int arg = 0; arg < NARGS; arg++) {
107
+ offsets[arg] = linear_idx;
108
+ }
109
+ return offsets;
110
+ }
111
+ };
112
+
113
+ // Make an OffsetCalculator with byte offsets
114
+ template<int N, bool signed_strides = false>
115
+ static OffsetCalculator<N, uint32_t, signed_strides> make_offset_calculator(const at::TensorIteratorBase& iter) {
116
+ TORCH_INTERNAL_ASSERT(N <= iter.ntensors());
117
+ std::array<const int64_t*, N> strides;
118
+ for (int i = 0; i < N; i++) {
119
+ strides[i] = iter.strides(i).data();
120
+ }
121
+ return OffsetCalculator<N, uint32_t, signed_strides>(iter.ndim(), iter.shape().data(), strides.data());
122
+ }
123
+
124
+ // Make an OffsetCalculator with element offsets
125
+ template<int N, bool signed_strides = false>
126
+ static OffsetCalculator<N, uint32_t, signed_strides> make_element_offset_calculator(
127
+ const at::TensorIteratorBase& iter) {
128
+ TORCH_INTERNAL_ASSERT(N <= iter.ntensors());
129
+ std::array<const int64_t*, N> strides;
130
+ std::array<int64_t, N> element_sizes;
131
+ for (int i = 0; i < N; i++) {
132
+ strides[i] = iter.strides(i).data();
133
+ element_sizes[i] = iter.element_size(i);
134
+ }
135
+ return OffsetCalculator<N, uint32_t, signed_strides>(
136
+ iter.ndim(), iter.shape().data(), strides.data(), element_sizes.data());
137
+ }
138
+
139
+ #else
140
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
141
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/PhiloxCudaStateRaw.cuh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // No "#pragma once" because this is a raw definition that can be copied by jit codegen.
3
+ // Eager mode clients should not include this file directly, instead,
4
+ // they should #include <ATen/cuda/PhiloxCudaState.h>, which has a #pragma once.
5
+
6
+ // Stores RNG state values. Passed as a kernel argument.
7
+ // See Note [CUDA Graph-safe RNG states].
8
+ //
9
+ // The raw definition lives in its own file so jit codegen can easily copy it.
10
+ namespace at {
11
+
12
+ struct PhiloxCudaState {
13
+ PhiloxCudaState() = default;
14
+ // Called if graph capture is not underway
15
+ PhiloxCudaState(uint64_t seed,
16
+ uint64_t offset) {
17
+ seed_.val = seed;
18
+ offset_.val = offset;
19
+ }
20
+ // Called if graph capture is underway
21
+ PhiloxCudaState(int64_t* seed,
22
+ int64_t* offset_extragraph,
23
+ uint64_t offset_intragraph) {
24
+ seed_.ptr = seed;
25
+ offset_.ptr = offset_extragraph;
26
+ offset_intragraph_ = offset_intragraph;
27
+ captured_ = true;
28
+ }
29
+
30
+ // Public members, directly accessible by at::cuda::philox::unpack.
31
+ // If we made them private with getters/setters, the getters/setters
32
+ // would have to be __device__, and we can't declare __device__ in ATen.
33
+ union Payload {
34
+ uint64_t val;
35
+ int64_t* ptr;
36
+ };
37
+
38
+ Payload seed_{};
39
+ Payload offset_{};
40
+ uint64_t offset_intragraph_ = 0;
41
+ bool captured_ = false;
42
+ };
43
+
44
+ } // namespace at
45
+
46
+ #else
47
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
48
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/TensorInfo.cuh ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/CollapseDims.h>
5
+
6
+ namespace at::cuda::detail {
7
+
8
+ #define MAX_TENSORINFO_DIMS 25
9
+
10
+ // CUDA kernel argument that defines tensor layout
11
+ template <typename T, typename IndexType>
12
+ struct TensorInfo {
13
+ TensorInfo();
14
+ TensorInfo(T* p,
15
+ int dim,
16
+ IndexType sz[MAX_TENSORINFO_DIMS],
17
+ IndexType st[MAX_TENSORINFO_DIMS]);
18
+
19
+ // Set the size of the given dimension to 1, as if it were a
20
+ // reduction dim (allows you to calculate offsets of the reduction
21
+ // slice)
22
+ void reduceDim(int dim);
23
+
24
+ // See note on [collapse dims].
25
+ int collapseDims(const int excludeDim = -1);
26
+
27
+ // Contiguous tensors of more than one dimension are collapsed down
28
+ // to one tensor
29
+ __host__ __device__ inline bool isContiguous() const {
30
+ return (dims == 1 && strides[0] == 1);
31
+ }
32
+
33
+ T* data;
34
+ IndexType sizes[MAX_TENSORINFO_DIMS];
35
+ IndexType strides[MAX_TENSORINFO_DIMS];
36
+ int dims;
37
+ };
38
+
39
+ template <typename T, typename IndexType>
40
+ TensorInfo<T, IndexType>::TensorInfo() {
41
+ data = nullptr;
42
+ dims = 0;
43
+ }
44
+
45
+ template <typename T, typename IndexType>
46
+ TensorInfo<T, IndexType>::TensorInfo(T* p,
47
+ int dim,
48
+ IndexType sz[MAX_TENSORINFO_DIMS],
49
+ IndexType st[MAX_TENSORINFO_DIMS]) {
50
+ data = p;
51
+ dims = dim;
52
+ TORCH_CHECK(dims < MAX_TENSORINFO_DIMS, "CUDA Tensors cannot have more than 25 dimensions");
53
+
54
+ for (int i = 0; i < dim; ++i) {
55
+ sizes[i] = sz[i];
56
+ strides[i] = st[i];
57
+ }
58
+ }
59
+
60
+ template <typename T, typename IndexType>
61
+ void
62
+ TensorInfo<T, IndexType>::reduceDim(int dim) {
63
+ TORCH_CHECK(dim < dims && dim >= 0, "expected dim between 0 and dims - 1");
64
+ sizes[dim] = 1;
65
+ }
66
+
67
+ template <typename T, typename IndexType>
68
+ int
69
+ TensorInfo<T, IndexType>::collapseDims(const int excludeDim) {
70
+ auto result = at::collapse_dims(sizes, strides, dims, excludeDim);
71
+ dims = std::get<1>(result);
72
+ return std::get<0>(result);
73
+ }
74
+
75
+ // Translate a linear index for the apply to a T* offset;
76
+ // specialized on `Dims` to reduce nvcc compilation time
77
+ template <typename T, typename IndexType, int Dims>
78
+ struct IndexToOffset {
79
+ static __host__ __device__ IndexType get(
80
+ IndexType linearId,
81
+ const TensorInfo<T, IndexType>& info) {
82
+
83
+ IndexType offset = 0;
84
+
85
+ // Uses static dims
86
+ for (int i = Dims - 1; i > 0; --i) {
87
+ IndexType curDimIndex = linearId % info.sizes[i];
88
+ IndexType curDimOffset = curDimIndex * info.strides[i];
89
+ offset += curDimOffset;
90
+ linearId /= info.sizes[i];
91
+ }
92
+
93
+ return offset + linearId * info.strides[0];
94
+ }
95
+ };
96
+
97
+ // Uses dynamic (runtime) instead of static (compile time) dims
98
+ template <typename T, typename IndexType>
99
+ struct IndexToOffset<T, IndexType, -1> {
100
+ static inline __host__ __device__ IndexType get(
101
+ IndexType linearId,
102
+ const TensorInfo<T, IndexType>& info) {
103
+
104
+ IndexType offset = 0;
105
+
106
+ for (int i = info.dims - 1; i > 0; --i) {
107
+ IndexType curDimIndex = linearId % info.sizes[i];
108
+ IndexType curDimOffset = curDimIndex * info.strides[i];
109
+ offset += curDimOffset;
110
+ linearId /= info.sizes[i];
111
+ }
112
+
113
+ return offset + linearId * info.strides[0];
114
+ }
115
+ };
116
+
117
+ } // namespace at::cuda::detail
118
+
119
+ #else
120
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
121
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/detail/UnpackRaw.cuh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // No "#pragma once" because this is a raw definition that can be copied by jit codegen.
3
+ // Eager mode clients should not include this file directly, instead,
4
+ // they should #include <ATen/cuda/PhiloxUtils.cuh>, which has a #pragma once.
5
+
6
+ namespace at::cuda::philox {
7
+
8
+ // In-kernel call to retrieve philox seed and offset from a PhiloxCudaState instance whether
9
+ // that instance was created with graph capture underway or not.
10
+ // See Note [CUDA Graph-safe RNG states].
11
+ //
12
+ // We can't write a __device__ function in CUDAGeneratorImpl.h, because it's in ATen.
13
+ // Also, whatever call unpacks PhiloxCudaState in consumer kernels must be inlineable.
14
+ // Easiest thing that comes to mind is, define a __device__ unpack helper here, in ATen/cuda.
15
+ //
16
+ // The raw definition lives in its own file so jit codegen can easily copy it.
17
+ __host__ __device__ __forceinline__ std::tuple<uint64_t, uint64_t>
18
+ unpack(at::PhiloxCudaState arg) {
19
+ if (arg.captured_) {
20
+ // static_cast avoids "warning: invalid narrowing conversion from "long" to "unsigned long".
21
+ // *(arg.offset_.ptr) is a broadcast load of a single int64_t to the entire kernel.
22
+ // For most threads' reads it will hit in cache, so it shouldn't hurt performance.
23
+ return std::make_tuple(static_cast<uint64_t>(*arg.seed_.ptr), static_cast<uint64_t>(*(arg.offset_.ptr) + arg.offset_intragraph_));
24
+ } else {
25
+ return std::make_tuple(arg.seed_.val, arg.offset_.val);
26
+ }
27
+ }
28
+
29
+ // Adapted from TE
30
+ // extract seed and offset from PhiloxCudaState
31
+ __global__ void unpack_cudnn(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr);
32
+
33
+ void unpack_cudnn_wrapper(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr, cudaStream_t stream);
34
+
35
+ } // namespace at::cuda::philox
36
+
37
+ #else
38
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
39
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/jiterator.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/jit_macros.h>
4
+
5
+ #if AT_USE_JITERATOR()
6
+
7
+ #include <c10/macros/Export.h>
8
+ #include <c10/util/SmallVector.h>
9
+ #include <ATen/core/Tensor.h>
10
+
11
+ #include <string>
12
+ #include <vector>
13
+
14
+ namespace at::cuda {
15
+
16
+ TORCH_CUDA_CPP_API c10::SmallVector<at::Tensor> CompileAndLaunchKernel(
17
+ const std::string& code_string,
18
+ const std::string& kernel_name,
19
+ const int num_outputs,
20
+ const c10::SmallVector<at::Tensor>& tensors,
21
+ const c10::SmallVector<at::Scalar>& extra_args,
22
+ bool return_by_ref);
23
+
24
+ } // namespace at::cuda
25
+
26
+ #else
27
+
28
+ namespace at::cuda {
29
+
30
+ TORCH_CUDA_CPP_API c10::SmallVector<at::Tensor> CompileAndLaunchKernel(
31
+ const std::string& code_string,
32
+ const std::string& kernel_name,
33
+ const int num_outputs,
34
+ const c10::SmallVector<at::Tensor>& tensors,
35
+ const c10::SmallVector<at::Scalar>& extra_args,
36
+ bool return_by_ref) {
37
+ TORCH_CHECK(false, "Jiterator is not supported");
38
+ }
39
+ } // namespace at::cuda
40
+
41
+ #endif // AT_USE_JITERATOR()
42
+
43
+ #else
44
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
45
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/jiterator_impl.h ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/jit_macros.h>
4
+
5
+ #if AT_USE_JITERATOR()
6
+
7
+ #include <ATen/native/TensorIterator.h>
8
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
9
+ #include <ATen/native/cuda/jit_utils.h>
10
+ #include <ATen/native/cuda/MemoryAccess.cuh>
11
+ #include <ATen/native/cuda/JitLoops.cuh>
12
+
13
+ #include <array>
14
+ #include <string>
15
+ #include <variant>
16
+ #include <vector>
17
+
18
+ namespace at::native {
19
+
20
+
21
+ #define AT_FOR_8_CASES(_) \
22
+ _(1) \
23
+ _(2) \
24
+ _(3) \
25
+ _(4) \
26
+ _(5) \
27
+ _(6) \
28
+ _(7) \
29
+ _(8)
30
+
31
+ #define AT_FOR_8_CASES_WITH_COMMA(_) \
32
+ _(1) , \
33
+ _(2) , \
34
+ _(3) , \
35
+ _(4) , \
36
+ _(5) , \
37
+ _(6) , \
38
+ _(7) , \
39
+ _(8)
40
+
41
+ c10::SmallVector<std::string> get_extra_args_typenames(const c10::SmallVector<at::Scalar>& extra_args) {
42
+ c10::SmallVector<std::string> args_typenames(extra_args.size());
43
+ for (const auto i : c10::irange(extra_args.size())) {
44
+ args_typenames[i] = at::cuda::jit::typeName(extra_args[i].type());
45
+ }
46
+ return args_typenames;
47
+ }
48
+
49
+ int can_vectorize_up_to(at::ScalarType type, char* pointer) {
50
+ switch(type) {
51
+ #define DEFINE_CASE(ctype, scalartype) \
52
+ case ScalarType::scalartype : return memory::can_vectorize_up_to<ctype>(pointer);
53
+
54
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_CASE)
55
+ #undef DEFINE_CASE
56
+
57
+ default: TORCH_INTERNAL_ASSERT(false, "Unrecognized ScalarType: ", type);
58
+ }
59
+ }
60
+
61
+ // jitted version of the above
62
+ // See Note [Jiterator], this relies on the assumptions enumerated there
63
+ int jitted_can_vectorize_up_to(const TensorIteratorBase& iter) {
64
+ const at::ScalarType common_dtype = iter.common_dtype();
65
+ const at::ScalarType result_dtype = common_dtype;
66
+
67
+ // Deals with output
68
+ int result = can_vectorize_up_to(result_dtype, static_cast<char*>(iter.data_ptr(0)));
69
+
70
+ // Incorporates input(s)
71
+ for (auto i = 1; i < iter.ntensors(); ++i) {
72
+ result = std::min<int>(result, can_vectorize_up_to(common_dtype, static_cast<char*>(iter.data_ptr(i))));
73
+ }
74
+
75
+ return result;
76
+ }
77
+
78
+ template<bool IS_INPUT, int N>
79
+ static std::unique_ptr<OffsetCalculator<N>> make_unique_offset_calculator(
80
+ const TensorIteratorBase& iter) {
81
+ // array size can not be 0, this happens when N == 0
82
+ constexpr int array_size = std::max<int>(N, 1);
83
+ TORCH_INTERNAL_ASSERT(N == (IS_INPUT ? iter.ninputs() : iter.noutputs()));
84
+
85
+ std::array<const int64_t*, array_size> strides;
86
+ int64_t element_sizes[array_size];
87
+ for (int i = 0; i < N; i++) {
88
+ int index = IS_INPUT ? i + iter.noutputs() : i;
89
+ strides[i] = iter.strides(index).data();
90
+ element_sizes[i] = iter.element_size(index);
91
+ }
92
+ return std::make_unique<OffsetCalculator<N>>(iter.ndim(), iter.shape().data(), strides.data(), element_sizes);
93
+ }
94
+
95
+ template <bool IS_INPUT>
96
+ struct OffsetCalculatorVariant {
97
+ #define DEFINE_CASE(index) std::unique_ptr<OffsetCalculator<index>>
98
+ using OffsetCalculatorTypes = std::variant<
99
+ AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE)
100
+ >;
101
+ #undef DEFINE_CASE
102
+
103
+ OffsetCalculatorVariant(const TensorIteratorBase& iter) {
104
+ int num = IS_INPUT ? iter.ninputs() : iter.noutputs();
105
+
106
+ switch(num) {
107
+ #define DEFINE_CASE(index) \
108
+ case index : v = make_unique_offset_calculator<IS_INPUT, index>(iter); break;
109
+
110
+ AT_FOR_8_CASES(DEFINE_CASE)
111
+ #undef DEFINE_CASE
112
+ default:
113
+ TORCH_CHECK(false, "OffsetCalculatorVariant is not implemented for num_tensor = ", num);
114
+ }
115
+ }
116
+
117
+ void* data_ptr() {
118
+ return std::visit([](auto & v){ return static_cast<void*>(v.get()); }, v);
119
+ }
120
+
121
+ private:
122
+ OffsetCalculatorTypes v{};
123
+ };
124
+
125
+ struct ArrayVariant {
126
+ // works for up to 8 input + 8 outputs
127
+ #define DEFINE_CASE(index) std::array<char*, index>, std::array<char*, index+8>
128
+ using ArrayTypes = std::variant<
129
+ AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE)
130
+ >;
131
+ #undef DEFINE_CASE
132
+
133
+ ArrayVariant(const TensorIteratorBase& iter) {
134
+ int ntensors = iter.ntensors();
135
+ switch(ntensors) {
136
+ #define DEFINE_CASE(index) \
137
+ case index: array = std::array<char*, index>{}; break; \
138
+ case index+8: array = std::array<char*, index+8>{}; break;
139
+
140
+ AT_FOR_8_CASES(DEFINE_CASE)
141
+ #undef DEFINE_CASE
142
+
143
+ default:
144
+ TORCH_CHECK(false, "ArrayVariant is not implemented for ntensors = ", ntensors);
145
+ }
146
+
147
+ std::visit([&](auto& a) {
148
+ for (auto i = 0; i < ntensors; ++i) {
149
+ a[i] = (char*)iter.data_ptr(i);
150
+ }
151
+ }, array);
152
+ }
153
+
154
+ void* data_ptr() {
155
+ return std::visit([](auto & a){ return static_cast<void*>(&a); }, array);
156
+ }
157
+
158
+ private:
159
+ ArrayTypes array;
160
+ };
161
+
162
+ struct TrivialOffsetCalculatorVariant {
163
+ #define DEFINE_CASE(index) TrivialOffsetCalculator<index>
164
+ using TrivialOffsetCalculatorTypes = std::variant<
165
+ AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE)
166
+ >;
167
+ #undef DEFINE_CASE
168
+
169
+ TrivialOffsetCalculatorVariant(int num) {
170
+ switch(num) {
171
+ #define DEFINE_CASE(index) \
172
+ case index: v = TrivialOffsetCalculator<index>(); break;
173
+
174
+ AT_FOR_8_CASES(DEFINE_CASE)
175
+ #undef DEFINE_CASE
176
+
177
+ default:
178
+ TORCH_CHECK(false, "TrivialOffsetCalculatorVariant is not implemented for num_tensors = ", num);
179
+ }
180
+ }
181
+
182
+ void* data_ptr() {
183
+ return std::visit([](auto & v){ return static_cast<void*>(&v); }, v);
184
+ }
185
+
186
+ private:
187
+ TrivialOffsetCalculatorTypes v{};
188
+ };
189
+
190
+ struct LoadWithCastVariant {
191
+ #define DEFINE_CASE(index) std::unique_ptr<memory::LoadWithCast<index>>
192
+ using LoadWithCastPtr = std::variant<
193
+ AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE)
194
+ >;
195
+ #undef DEFINE_CASE
196
+
197
+ LoadWithCastVariant(const TensorIteratorBase& iter) {
198
+ int arity = iter.ninputs();
199
+ switch(arity) {
200
+ #define DEFINE_CASE(index) \
201
+ case index: v = std::make_unique<memory::LoadWithCast<index>>(iter); break;
202
+
203
+ AT_FOR_8_CASES(DEFINE_CASE)
204
+ #undef DEFINE_CASE
205
+
206
+ default:
207
+ TORCH_CHECK(false, "LoadWithCastVariant is not implemented for ninputs = ", arity);
208
+ }
209
+ }
210
+
211
+ void* data_ptr() {
212
+ return std::visit([](auto & v){ return static_cast<void*>(v.get()); }, v);
213
+ }
214
+
215
+ private:
216
+ LoadWithCastPtr v{};
217
+ };
218
+
219
+ struct StoreWithCastVariant {
220
+ #define DEFINE_CASE(index) std::unique_ptr<memory::StoreWithCast<index>>
221
+ using StoreWithCastPtr = std::variant<
222
+ AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE)
223
+ >;
224
+ #undef DEFINE_CASE
225
+
226
+ StoreWithCastVariant(const TensorIteratorBase& iter) {
227
+ int num = iter.noutputs();
228
+ switch(num) {
229
+ #define DEFINE_CASE(index) \
230
+ case index: v = std::make_unique<memory::StoreWithCast<index>>(iter); break;
231
+
232
+ AT_FOR_8_CASES(DEFINE_CASE)
233
+ #undef DEFINE_CASE
234
+
235
+ default:
236
+ TORCH_CHECK(false, "StoreWithCastVariant is not implemented for noutputs = ", num);
237
+ }
238
+ }
239
+
240
+ void* data_ptr() {
241
+ return std::visit([](auto & v){ return static_cast<void*>(v.get()); }, v);
242
+ }
243
+
244
+ private:
245
+ StoreWithCastPtr v{};
246
+ };
247
+
248
+ } // namespace at::native
249
+
250
+
251
+ #endif // AT_USE_JITERATOR()
252
+
253
+ #else
254
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
255
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/llvm_jit_strings.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+ #include <c10/macros/Export.h>
6
+
7
+ namespace at::cuda {
8
+
9
+ TORCH_CUDA_CPP_API const std::string &get_traits_string();
10
+ TORCH_CUDA_CPP_API const std::string &get_cmath_string();
11
+ TORCH_CUDA_CPP_API const std::string &get_complex_body_string();
12
+ TORCH_CUDA_CPP_API const std::string &get_complex_half_body_string();
13
+ TORCH_CUDA_CPP_API const std::string &get_complex_math_string();
14
+
15
+ } // namespace at::cuda
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/cuda/tunable/GemmCommon.h ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Original TunableOp is from onnxruntime.
3
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
4
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
5
+ // Copyright (c) Microsoft Corporation.
6
+ // Licensed under the MIT license.
7
+ //
8
+ // Adapting TunableOp into PyTorch
9
+ // Copyright (c) Advanced Micro Devices, Inc.
10
+ //
11
+ #pragma once
12
+
13
+ #include <string>
14
+ #include <c10/core/ScalarType.h>
15
+
16
+ #include <ATen/cuda/tunable/TunableOp.h>
17
+ #include <ATen/cuda/tunable/Tunable.h>
18
+ #include <ATen/cuda/CUDABlas.h>
19
+ #include <ATen/cuda/Exceptions.h>
20
+ #include <c10/util/StringUtil.h>
21
+
22
+ #ifndef AT_PER_OPERATOR_HEADERS
23
+ #include <ATen/Functions.h>
24
+ #include <ATen/NativeFunctions.h>
25
+ #else
26
+ #include <ATen/ops/allclose.h>
27
+ #include <ATen/ops/from_blob.h>
28
+ #endif
29
+ #include <ATen/OpMathType.h>
30
+ #include <fmt/printf.h>
31
+
32
+ namespace at::cuda::tunable {
33
+
34
+ using at::blas::ScalingType;
35
+
36
+ enum class BlasOp {
37
+ N = 0,
38
+ T = 1
39
+ };
40
+
41
+ inline char BlasOpToString(BlasOp op) {
42
+ switch (op) {
43
+ case BlasOp::N:
44
+ return 'N';
45
+ case BlasOp::T:
46
+ return 'T';
47
+ }
48
+ TORCH_CHECK(false, "unrecognized BlasOp");
49
+ return 'N';
50
+ }
51
+
52
+ template <typename T>
53
+ inline const char* BLASTypeName(T v) {
54
+ return "unknown";
55
+ }
56
+
57
+ template <>
58
+ inline const char* BLASTypeName(float v) {
59
+ return "f32_r";
60
+ }
61
+
62
+ template <>
63
+ inline const char* BLASTypeName(double v) {
64
+ return "f64_r";
65
+ }
66
+
67
+ template <>
68
+ inline const char* BLASTypeName(BFloat16 v) {
69
+ return "bf16_r";
70
+ }
71
+
72
+ template <>
73
+ inline const char* BLASTypeName(Half v) {
74
+ return "f16_r";
75
+ }
76
+
77
+ //https://github.com/ROCm/hipBLASLt/blob/develop/library/src/include/auxiliary.hpp#L175
78
+ template <>
79
+ inline const char* BLASTypeName(Float8_e4m3fn v) {
80
+ return "f8_r";
81
+ }
82
+
83
+ template <>
84
+ inline const char* BLASTypeName(Float8_e5m2 v) {
85
+ return "bf8_r";
86
+ }
87
+
88
+ template <>
89
+ inline const char* BLASTypeName(Float8_e4m3fnuz v) {
90
+ return "f8_fnuz_r";
91
+ }
92
+
93
+ template <>
94
+ inline const char* BLASTypeName(Float8_e5m2fnuz v) {
95
+ return "bf8_fnuz_r";
96
+ }
97
+
98
+ template <>
99
+ inline const char* BLASTypeName(c10::complex<double> v) {
100
+ return "f64_r";
101
+ }
102
+
103
+ template <>
104
+ inline const char* BLASTypeName(c10::complex<float> v) {
105
+ return "f32_r";
106
+ }
107
+
108
+ inline std::string ScalarTypeToBLASType(c10::ScalarType scalar_type) {
109
+ std::string BLASType;
110
+ switch (scalar_type) {
111
+ case c10::ScalarType::Float:{
112
+ BLASType = "f32_r";
113
+ break;
114
+ }
115
+ case c10::ScalarType::Double:{
116
+ BLASType = "f64_r";
117
+ break;
118
+ }
119
+ case c10::ScalarType::BFloat16:{
120
+ BLASType = "bf16_r";
121
+ break;
122
+ }
123
+ case c10::ScalarType::Half: {
124
+ BLASType = "f16_r";
125
+ break;
126
+ }
127
+ case c10::ScalarType::Float8_e4m3fn: {
128
+ BLASType = "f8_r";
129
+ break;
130
+ }
131
+ case c10::ScalarType::Float8_e5m2: {
132
+ BLASType = "bf8_r";
133
+ break;
134
+ }
135
+ case c10::ScalarType::Float8_e4m3fnuz: {
136
+ BLASType = "f8_fnuz_r";
137
+ break;
138
+ }
139
+ case c10::ScalarType::Float8_e5m2fnuz: {
140
+ BLASType = "bf8_fnuz_r";
141
+ break;
142
+ }
143
+ case c10::ScalarType::ComplexFloat:{
144
+ BLASType = "f32_c";
145
+ break;
146
+ }
147
+ case c10::ScalarType::ComplexDouble:{
148
+ BLASType = "f64_c";
149
+ break;
150
+ }
151
+ default:
152
+ BLASType = "unknown";
153
+ }
154
+ return BLASType;
155
+
156
+ }
157
+
158
+ // Similar to Compute Type in GemmRocblas.h
159
+ template <typename T>
160
+ inline std::string ComputeTypeFor() {
161
+ return "Unknown ComputeType";
162
+ }
163
+
164
+ // This is a union of the compute types for
165
+ // ROCBLAS and hipBLASLt.
166
+ template <>
167
+ inline std::string ComputeTypeFor<float>() {
168
+ if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) != at::Float32Precision::TF32) {
169
+ return "f32_r";
170
+ } else {
171
+ return "xf32_r";
172
+ }
173
+ }
174
+
175
+ template <>
176
+ inline std::string ComputeTypeFor<double>() {
177
+ return "f64_r";
178
+ }
179
+
180
+ template <>
181
+ inline std::string ComputeTypeFor<Half>() {
182
+ return "f32_r";
183
+ }
184
+
185
+ template <>
186
+ inline std::string ComputeTypeFor<BFloat16>() {
187
+ return "f32_r";
188
+ }
189
+
190
+ template <>
191
+ inline std::string ComputeTypeFor<c10::complex<float>>() {
192
+ return "f32_c";
193
+ }
194
+
195
+ template <>
196
+ inline std::string ComputeTypeFor<c10::complex<double>>() {
197
+ return "f64_c";
198
+ }
199
+
200
+ template <>
201
+ inline std::string ComputeTypeFor<Float8_e4m3fn>() {
202
+ return "f32_r";
203
+ }
204
+
205
+ template <>
206
+ inline std::string ComputeTypeFor<Float8_e5m2>() {
207
+ return "f32_r";
208
+ }
209
+
210
+ template <>
211
+ inline std::string ComputeTypeFor<Float8_e4m3fnuz>() {
212
+ return "f32_r";
213
+ }
214
+
215
+ template <>
216
+ inline std::string ComputeTypeFor<Float8_e5m2fnuz>() {
217
+ return "f32_r";
218
+ }
219
+
220
+ // Convert opmath_type<T> to string
221
+ template <typename T>
222
+ inline std::string to_string_opmath(const at::opmath_type<T>& value) {
223
+ if constexpr (std::is_same_v<at::opmath_type<T>, c10::complex<float>> ||
224
+ std::is_same_v<at::opmath_type<T>, c10::complex<double>>) {
225
+ return fmt::format("({:.4f}, {:.4f})", value.real(), value.imag());
226
+ } else {
227
+ return fmt::format("{:.4f}", value);
228
+ }
229
+ }
230
+
231
+ // convert activation epilogue to string
232
+ inline std::string to_string_epilogue(const at::cuda::blas::GEMMAndBiasActivationEpilogue& value) {
233
+ switch (value) {
234
+ case at::cuda::blas::GEMMAndBiasActivationEpilogue::None:
235
+ return std::string("None");
236
+ break;
237
+ case at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU:
238
+ return std::string("RELU");
239
+ break;
240
+ case cuda::blas::GEMMAndBiasActivationEpilogue::GELU:
241
+ return std::string("GELU");
242
+ break;
243
+ default:
244
+ return std::string("unknown");
245
+ }
246
+ }
247
+
248
+ namespace detail {
249
+
250
+ static bool NumericalCheck(ScalarType dtype, void* c, void* other_c, int64_t size, const NumericalCheckConfig& config) {
251
+
252
+ if (!config.enabled) {
253
+ return true; // skip when disabled
254
+ }
255
+
256
+ auto options = at::TensorOptions().dtype(dtype).device(at::kCUDA);
257
+ at::Tensor ref = at::from_blob(c, {size}, options);
258
+ at::Tensor oth = at::from_blob(other_c, {size}, options);
259
+ at::Tensor ref_float = ref.to(at::kFloat);
260
+ at::Tensor oth_float = oth.to(at::kFloat);
261
+
262
+ const bool ok = at::allclose(ref_float, oth_float, config.rtol, config.atol);
263
+ if (ok) {
264
+ TUNABLE_LOG3("├──verify numerics: PASSED with atol=", config.atol, ", rtol=", config.rtol);
265
+ } else {
266
+ TUNABLE_LOG3("├──verify numerics: FAILED with atol=", config.atol, ", rtol=", config.rtol);
267
+ }
268
+ return ok;
269
+ }
270
+
271
+ }
272
+
273
+ // Note on GetSizeA et al.
274
+ // Tensors can be dense or arbitrarily strided. We only need our copies to be large enough.
275
+ // Our copies must be at least as large as the m n k shapes dictate, but could be larger
276
+ // depending on the lda ldb ldc values. Similarly for the batched case.
277
+
278
+ template <typename T>
279
+ struct GemmParams : OpParams {
280
+ GemmParams() = default;
281
+
282
+ std::string BLASSignature() const override {
283
+ std::string alpha_str = to_string_opmath<T>(alpha);
284
+ std::string beta_str = to_string_opmath<T>(beta);
285
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
286
+ "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, bias_type: %s, compute_type: %s }",
287
+ m, n, k, lda, ldb, ldc, ldc, alpha_str, beta_str, transa, transb,
288
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>(), ComputeTypeFor<T>());
289
+ }
290
+
291
+ std::string Signature() const override {
292
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc);
293
+ }
294
+
295
+ size_t GetSizeA() const {
296
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
297
+ size_t size_dense = m * k;
298
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
299
+ }
300
+
301
+ size_t GetSizeB() const {
302
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
303
+ size_t size_dense = k * n;
304
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
305
+ }
306
+
307
+ size_t GetSizeC() const {
308
+ size_t size_stride = ldc * n;
309
+ size_t size_dense = m * n;
310
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
311
+ }
312
+
313
+ size_t GetSize(bool duplicate_inputs) const {
314
+ size_t size = GetSizeC();
315
+ if (duplicate_inputs) {
316
+ size += GetSizeA();
317
+ size += GetSizeB();
318
+ }
319
+ return size;
320
+ }
321
+
322
+ GemmParams* DeepCopy(bool duplicate_inputs) const {
323
+ GemmParams* copy = new GemmParams;
324
+ *copy = *this;
325
+ c10::DeviceIndex device = 0;
326
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
327
+ size_t c_size = GetSizeC();
328
+ copy->c = static_cast<T*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
329
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
330
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
331
+ if (duplicate_inputs) {
332
+ size_t a_size = GetSizeA();
333
+ size_t b_size = GetSizeB();
334
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
335
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
336
+ copy->duplicate_inputs_ = true;
337
+ }
338
+ return copy;
339
+ }
340
+
341
+ // only call on object returned by DeepCopy
342
+ void Delete() {
343
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
344
+ if (duplicate_inputs_) {
345
+ // NOLINTNEXTLINE(*const-cast*)
346
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
347
+ // NOLINTNEXTLINE(*const-cast*)
348
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
349
+ }
350
+ }
351
+
352
+ TuningStatus NumericalCheck(GemmParams<T> *other) {
353
+ auto* ctx = getTuningContext();
354
+ auto cfg = ctx->GetNumericalCheckConfig();
355
+ auto c_dtype = c10::CppTypeToScalarType<T>::value;
356
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL;
357
+ }
358
+
359
+ char transa{};
360
+ char transb{};
361
+ int64_t m{};
362
+ int64_t n{};
363
+ int64_t k{};
364
+ at::opmath_type<T> alpha;
365
+ const T* a{};
366
+ int64_t lda{};
367
+ const T* b{};
368
+ int64_t ldb{};
369
+ at::opmath_type<T> beta;
370
+ T* c{};
371
+ int64_t ldc{};
372
+ private:
373
+ bool duplicate_inputs_{false};
374
+ };
375
+
376
+ template <typename T>
377
+ struct GemmAndBiasParams : OpParams {
378
+ std::string BLASSignature() const override {
379
+ std::string alpha_str = to_string_opmath<T>(alpha);
380
+ std::string activation_str = to_string_epilogue(activation);
381
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
382
+ "alpha: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, activation: %s, bias_type: %s, scale_type: %s, compute_type: %s }",
383
+ m, n, k, lda, ldb, ldc, ldc, alpha_str, transa, transb,
384
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), activation_str, BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>(), ComputeTypeFor<T>());
385
+ }
386
+
387
+ std::string Signature() const override {
388
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc);
389
+ }
390
+
391
+ size_t GetSizeA() const {
392
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
393
+ size_t size_dense = m * k;
394
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
395
+ }
396
+
397
+ size_t GetSizeB() const {
398
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
399
+ size_t size_dense = k * n;
400
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
401
+ }
402
+
403
+ size_t GetSizeC() const {
404
+ size_t size_stride = ldc * n;
405
+ size_t size_dense = m * n;
406
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
407
+ }
408
+
409
+ size_t GetSize(bool duplicate_inputs) const {
410
+ size_t size = GetSizeC();
411
+ if (duplicate_inputs) {
412
+ size += GetSizeA();
413
+ size += GetSizeB();
414
+ }
415
+ return size;
416
+ }
417
+
418
+ GemmAndBiasParams* DeepCopy(bool duplicate_inputs) const {
419
+ GemmAndBiasParams* copy = new GemmAndBiasParams;
420
+ *copy = *this;
421
+ c10::DeviceIndex device = 0;
422
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
423
+ size_t c_size = GetSizeC();
424
+ copy->c = static_cast<T*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
425
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
426
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
427
+ if (duplicate_inputs) {
428
+ size_t a_size = GetSizeA();
429
+ size_t b_size = GetSizeB();
430
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
431
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
432
+ copy->duplicate_inputs_ = true;
433
+ }
434
+ return copy;
435
+ }
436
+
437
+ // only call on object returned by DeepCopy
438
+ void Delete() {
439
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
440
+ if (duplicate_inputs_) {
441
+ // NOLINTNEXTLINE(*const-cast)
442
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
443
+ // NOLINTNEXTLINE(*const-cast)
444
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
445
+ }
446
+ }
447
+
448
+ TuningStatus NumericalCheck(GemmAndBiasParams<T> *other) {
449
+ auto* ctx = getTuningContext();
450
+ auto cfg = ctx->GetNumericalCheckConfig();
451
+ auto c_dtype = c10::CppTypeToScalarType<T>::value;
452
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL;
453
+ }
454
+
455
+ char transa{};
456
+ char transb{};
457
+ int64_t m{};
458
+ int64_t n{};
459
+ int64_t k{};
460
+ at::opmath_type<T> alpha{};
461
+ const T* a{};
462
+ int64_t lda{};
463
+ const T* b{};
464
+ int64_t ldb{};
465
+ T* c{};
466
+ int64_t ldc{};
467
+ const T* bias{};
468
+ at::cuda::blas::GEMMAndBiasActivationEpilogue activation{};
469
+ private:
470
+ bool duplicate_inputs_{false};
471
+ };
472
+
473
+ template <typename T, typename C_Dtype = T>
474
+ struct GemmStridedBatchedParams : OpParams {
475
+ std::string BLASSignature() const override {
476
+ std::string alpha_str = to_string_opmath<T>(alpha);
477
+ std::string beta_str = to_string_opmath<T>(beta);
478
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: %ld, stride_b: %ld, stride_c: %ld, stride_d: %ld, "
479
+ "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: %ld, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, compute_type: %s }",
480
+ m, n, k, lda, ldb, ldc, ldc, stride_a, stride_b, stride_c, stride_c, alpha_str, beta_str, transa, transb, batch,
481
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<C_Dtype>(C_Dtype{}), BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>());
482
+ }
483
+
484
+ std::string Signature() const override {
485
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_B_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, batch, lda, ldb, ldc);
486
+ }
487
+
488
+ size_t GetSizeA() const {
489
+ size_t size_stride = stride_a * batch;
490
+ size_t size_dense = m * k * batch;
491
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
492
+ }
493
+
494
+ size_t GetSizeB() const {
495
+ size_t size_stride = stride_b * batch;
496
+ size_t size_dense = k * n * batch;
497
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
498
+ }
499
+
500
+ size_t GetSizeC() const {
501
+ size_t size_stride = stride_c * batch;
502
+ size_t size_dense = m * n * batch;
503
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
504
+ }
505
+
506
+ size_t GetSize(bool duplicate_inputs) const {
507
+ size_t size = GetSizeC();
508
+ if (duplicate_inputs) {
509
+ size += GetSizeA();
510
+ size += GetSizeB();
511
+ }
512
+ return size;
513
+ }
514
+
515
+ GemmStridedBatchedParams* DeepCopy(bool duplicate_inputs) const {
516
+ GemmStridedBatchedParams* copy = new GemmStridedBatchedParams;
517
+ *copy = *this;
518
+ c10::DeviceIndex device = 0;
519
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
520
+ size_t c_size = GetSizeC();
521
+ copy->c = static_cast<C_Dtype*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
522
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
523
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
524
+ if (duplicate_inputs) {
525
+ size_t a_size = GetSizeA();
526
+ size_t b_size = GetSizeB();
527
+ // NOLINTNEXTLINE(*const-cast*)
528
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
529
+ // NOLINTNEXTLINE(*const-cast*)
530
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
531
+ copy->duplicate_inputs_ = true;
532
+ }
533
+ return copy;
534
+ }
535
+
536
+ // only call on object returned by DeepCopy
537
+ void Delete() {
538
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
539
+ if (duplicate_inputs_) {
540
+ // NOLINTNEXTLINE(*const-cast*)
541
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
542
+ // NOLINTNEXTLINE(*const-cast*)
543
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
544
+ }
545
+ }
546
+
547
+ TuningStatus NumericalCheck(GemmStridedBatchedParams<T> *other) {
548
+ auto* ctx = getTuningContext();
549
+ auto cfg = ctx->GetNumericalCheckConfig();
550
+ auto c_dtype = c10::CppTypeToScalarType<C_Dtype>::value;
551
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL;
552
+ }
553
+
554
+ char transa{};
555
+ char transb{};
556
+ int64_t m{};
557
+ int64_t n{};
558
+ int64_t k{};
559
+ at::opmath_type<T> alpha{};
560
+ const T* a{};
561
+ int64_t lda{};
562
+ int64_t stride_a{};
563
+ const T* b{};
564
+ int64_t ldb{};
565
+ int64_t stride_b{};
566
+ at::opmath_type<T> beta;
567
+ C_Dtype* c{};
568
+ int64_t ldc{};
569
+ int64_t stride_c{};
570
+ int64_t batch{};
571
+ private:
572
+ bool duplicate_inputs_{false};
573
+ };
574
+
575
+ template <typename T>
576
+ struct ScaledGemmParams : OpParams {
577
+ ScaledGemmParams() = default;
578
+
579
+ std::string BLASSignature() const override {
580
+ // Excluding use_fast_accum and use_rowise booleans for now
581
+ if (bias_ptr == nullptr) {
582
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
583
+ "transA: %c, transB: %c, batch_count: 1, scaleA: f32_r, scaleB: f32_r, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, compute_type: %s }",
584
+ m, n, k, lda, ldb, ldc, ldc, transa, transb,
585
+ ScalarTypeToBLASType(a_dtype), ScalarTypeToBLASType(b_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(c_dtype),
586
+ ComputeTypeFor<T>(), ComputeTypeFor<T>());
587
+ }
588
+ else {
589
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
590
+ "transA: %c, transB: %c, batch_count: 1, scaleA: f32_r, scaleB: f32_r, a_type: %s, b_type: %s, c_type: %s, d_type: %s, bias_type: %s, scale_type: %s, compute_type: %s }",
591
+ m, n, k, lda, ldb, ldc, ldc, transa, transb,
592
+ ScalarTypeToBLASType(a_dtype), ScalarTypeToBLASType(b_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(bias_dtype),
593
+ ComputeTypeFor<T>(), ComputeTypeFor<T>());
594
+ }
595
+ }
596
+
597
+ std::string Signature() const override {
598
+ // In Blas.cpp, code defaults to a bias_dtype of Half even when there is no bias vector.
599
+ // Search for this line::
600
+ // params.bias_dtype = bias ? bias->scalar_type() : isFloat8Type(out_dtype_) ? at::ScalarType::Half : out_dtype_;
601
+ //
602
+ // In TunableOp, we must distinguish in param signature these two cases: with and without a bias vector.
603
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld_rw_%d_bias_%s",
604
+ transa, transb, m, n, k, lda, ldb, ldc,
605
+ a_scaling_type == ScalingType::RowWise && b_scaling_type == ScalingType::RowWise,
606
+ bias_ptr == nullptr ? "None" : at::toString(bias_dtype));
607
+ }
608
+
609
+ size_t GetSizeA() const {
610
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
611
+ size_t size_dense = m * k;
612
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
613
+ }
614
+
615
+ size_t GetSizeB() const {
616
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
617
+ size_t size_dense = k * n;
618
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
619
+ }
620
+
621
+ size_t GetSizeC() const {
622
+ size_t size_stride = ldc * n;
623
+ size_t size_dense = m * n;
624
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
625
+ }
626
+
627
+ size_t GetSize(bool duplicate_inputs) const {
628
+ size_t size = GetSizeC();
629
+ if (duplicate_inputs) {
630
+ size += GetSizeA();
631
+ size += GetSizeB();
632
+ }
633
+ return size;
634
+ }
635
+
636
+ ScaledGemmParams* DeepCopy(bool duplicate_inputs) const {
637
+ ScaledGemmParams* copy = new ScaledGemmParams;
638
+ *copy = *this;
639
+ c10::DeviceIndex device = 0;
640
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
641
+ size_t c_size = GetSizeC();
642
+ copy->c = c10::cuda::CUDACachingAllocator::raw_alloc(c_size);
643
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
644
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
645
+ if (duplicate_inputs) {
646
+ size_t a_size = GetSizeA();
647
+ size_t b_size = GetSizeB();
648
+ copy->a = c10::cuda::CUDACachingAllocator::raw_alloc(a_size);
649
+ copy->b = c10::cuda::CUDACachingAllocator::raw_alloc(b_size);
650
+ copy->duplicate_inputs_ = true;
651
+ }
652
+ return copy;
653
+ }
654
+
655
+ // only call on object returned by DeepCopy
656
+ void Delete() {
657
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
658
+ if (duplicate_inputs_) {
659
+ // NOLINTNEXTLINE(*const-cast*)
660
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<void*>(a));
661
+ // NOLINTNEXTLINE(*const-cast*)
662
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<void*>(b));
663
+ }
664
+ }
665
+
666
+ TuningStatus NumericalCheck(ScaledGemmParams<T> *other) {
667
+ auto* ctx = getTuningContext();
668
+ auto cfg = ctx->GetNumericalCheckConfig();
669
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL;
670
+ }
671
+
672
+ char transa{};
673
+ char transb{};
674
+ int64_t m{};
675
+ int64_t n{};
676
+ int64_t k{};
677
+ const void* a{};
678
+ const void* a_scale_ptr{};
679
+ int64_t lda{};
680
+ ScalarType a_dtype{};
681
+ ScalarType a_scale_dtype{};
682
+ ScalingType a_scaling_type{};
683
+ const void* b{};
684
+ const void* b_scale_ptr{};
685
+ int64_t ldb{};
686
+ ScalarType b_dtype{};
687
+ ScalarType b_scale_dtype{};
688
+ ScalingType b_scaling_type{};
689
+ const void* bias_ptr{};
690
+ ScalarType bias_dtype{};
691
+ void* c{};
692
+ const void* c_scale_ptr{};
693
+ int64_t ldc{};
694
+ ScalarType c_dtype{};
695
+ void* amax_ptr{};
696
+ bool use_fast_accum{};
697
+ private:
698
+ bool duplicate_inputs_{false};
699
+ };
700
+
701
+ } // namespace at::cuda::tunable
702
+
703
+ #else
704
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
705
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)