jasonfan commited on
Commit
94ee59d
·
verified ·
1 Parent(s): d9d56a0

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/native/cuda/fused_adam_utils.cuh +205 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/fused_adamw_amsgrad_impl.cuh +43 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/fused_adamw_impl.cuh +41 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/im2col.cuh +341 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/jit_utils.h +254 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/reduction_template.cuh +689 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/thread_constants.h +30 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/vol2col.cuh +267 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_collection.h +37 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_template.h +164 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_bgemm.h +21 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_gemm.h +30 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_gemm_template.h +413 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_group_gemm.h +24 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_types.h +80 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_kernels.h +48 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_pack.h +114 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_ukernel_interface.h +226 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/Conv.h +59 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/FusionUtils.h +58 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/Attr.h +468 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/DnnlExt.h +599 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/LRUCache.h +115 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/Utils.h +172 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/oneDNN.h +225 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/oneDNNContext.h +95 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/qconv.h +115 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/qlinear.h +96 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/Copy.h +19 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/MPSGraphSequoiaOps.h +46 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/MetalShaderLibrary.h +202 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/OperationUtils.h +801 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/TensorFactory.h +19 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Activation.h +21 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/EmbeddingBag.h +53 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/GridSampler.h +30 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/LinearAlgebra.h +27 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Pooling.h +66 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Shape.h +23 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/TensorCompare.h +12 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/UpSample.h +17 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/BinaryKernel.h +15 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamAmsgradKernelImpl.h +43 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamKernelImpl.h +40 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamWAmsgradKernelImpl.h +42 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamWKernelImpl.h +41 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/MultiTensorApply.h +367 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mtia/EmptyTensor.h +47 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/nested/NestedTensorBinaryOps.h +23 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/nested/NestedTensorMath.h +84 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/fused_adam_utils.cuh ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/cuda/ForeachFunctors.cuh>
5
+ #include <ATen/native/cuda/MultiTensorApply.cuh>
6
+ #include <ATen/native/cuda/Pow.cuh>
7
+ #include <utility>
8
+
9
+ namespace at::native {
10
+
11
+ enum class ADAM_MODE : uint8_t { ORIGINAL = 0, ADAMW = 1 };
12
+
13
+ namespace {
14
+
15
+ constexpr uint8_t kParamIdx = 0;
16
+ constexpr uint8_t kGradIdx = 1;
17
+ constexpr uint8_t kExpAvgIdx = 2;
18
+ constexpr uint8_t kExpAvgSqIdx = 3;
19
+ constexpr uint8_t kMaxExpAvgSqIdx = 4;
20
+
21
+ template <
22
+ typename scalar_type,
23
+ typename opmath_t,
24
+ int depth,
25
+ ADAM_MODE adam_mode,
26
+ bool amsgrad>
27
+ C10_DEVICE inline void adam_math(
28
+ scalar_type r_args[depth][kILP],
29
+ const double& lr,
30
+ const double& beta1,
31
+ const double& beta2,
32
+ const double& weight_decay,
33
+ const double& eps,
34
+ const bool& maximize,
35
+ const float* grad_scale_ptr,
36
+ const float* found_inf_ptr,
37
+ const opmath_t& bias_correction1,
38
+ const opmath_t& bias_correction2_sqrt) {
39
+ static_assert(depth == 4 || depth == 5);
40
+ #pragma unroll
41
+ for (int ii = 0; ii < kILP; ii++) {
42
+ // Load values.
43
+ opmath_t param = static_cast<opmath_t>(r_args[kParamIdx][ii]);
44
+ opmath_t grad = static_cast<opmath_t>(r_args[kGradIdx][ii]);
45
+ if (grad_scale_ptr) {
46
+ grad /= (static_cast<double>(*grad_scale_ptr));
47
+ }
48
+ const opmath_t grad_to_store = grad;
49
+ if (maximize) {
50
+ grad = -grad;
51
+ }
52
+ opmath_t exp_avg = static_cast<opmath_t>(r_args[kExpAvgIdx][ii]);
53
+ opmath_t exp_avg_sq = static_cast<opmath_t>(r_args[kExpAvgSqIdx][ii]);
54
+ opmath_t max_exp_avg_sq;
55
+ if (amsgrad) {
56
+ max_exp_avg_sq = static_cast<opmath_t>(r_args[kMaxExpAvgSqIdx][ii]);
57
+ }
58
+ // Update param, grad, 1st and 2nd order momentum.
59
+ if (weight_decay != 0) {
60
+ if constexpr (adam_mode == ADAM_MODE::ORIGINAL) {
61
+ grad += param * weight_decay;
62
+ } else if constexpr (adam_mode == ADAM_MODE::ADAMW) {
63
+ param -= lr * weight_decay * param;
64
+ }
65
+ }
66
+ // todo(crcrpar): use lerp
67
+ // ref: https://developer.nvidia.com/blog/lerp-faster-cuda/
68
+ exp_avg = beta1 * exp_avg + (1 - beta1) * grad;
69
+ exp_avg_sq = beta2 * exp_avg_sq + (1 - beta2) * grad * grad;
70
+ const opmath_t step_size = lr / bias_correction1;
71
+ opmath_t denom;
72
+ if (amsgrad) {
73
+ max_exp_avg_sq = std::max(max_exp_avg_sq, exp_avg_sq);
74
+ denom = (std::sqrt(max_exp_avg_sq) / bias_correction2_sqrt) + eps;
75
+ } else {
76
+ denom = (std::sqrt(exp_avg_sq) / bias_correction2_sqrt) + eps;
77
+ }
78
+ param -= step_size * exp_avg / denom;
79
+
80
+ // Store results.
81
+ r_args[kParamIdx][ii] = param;
82
+ if (grad_scale_ptr) {
83
+ r_args[kGradIdx][ii] = grad_to_store;
84
+ }
85
+ r_args[kExpAvgIdx][ii] = exp_avg;
86
+ r_args[kExpAvgSqIdx][ii] = exp_avg_sq;
87
+ if (amsgrad) {
88
+ r_args[kMaxExpAvgSqIdx][ii] = max_exp_avg_sq;
89
+ }
90
+ }
91
+ }
92
+
93
+ // [note: Conditional Gradient Store when `optimizer.step` is called by
94
+ // GradScaler] When a user is training their model(s) with an FP16 AMP recipe,
95
+ // parameter updates are done via `grad_scaler.step(optimizer)` instead of
96
+ // `optimizer.step()`. For most optimizers, GradScaler unscales gradients on
97
+ // behalf of those optimizers. Also, before `.step`, it makes sure that all the
98
+ // gradients involved are finite, which incurs a device sync. On the other hand,
99
+ // fused optimizers set their member variable of `_step_supports_amp_scaling` to
100
+ // `True` in order to remove the device sync above. This means that fused
101
+ // optimizers have to have their CUDA kernels (a) unscale gradients and (b) skip
102
+ // parameter updates accordingly. To be functionally on par with `torch.optim`
103
+ // optimizers and `_multi_tensor` ones, the kernel below writes out gradients
104
+ // only when `grad_scale_ptr != nullptr.
105
+ template <typename scalar_type, int depth, ADAM_MODE adam_mode, bool amsgrad>
106
+ struct FusedAdamMathFunctor {
107
+ static_assert(
108
+ depth == 4 || depth == 5,
109
+ "depth of 4 for Adam, depth of 5 for Adam with AMSGrad.");
110
+ using opmath_t = at::opmath_type<scalar_type>;
111
+ C10_DEVICE __forceinline__ void operator()(
112
+ int64_t chunk_size,
113
+ FusedOptimizerTensorListMetadata<depth>& tl,
114
+ const float* lr_ptr,
115
+ const double& lr,
116
+ const double& beta1,
117
+ const double& beta2,
118
+ const double& weight_decay,
119
+ const double& eps,
120
+ const bool& maximize,
121
+ const float* grad_scale_ptr,
122
+ const float* found_inf_ptr) {
123
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
124
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
125
+ const double lr_double = lr_ptr ? *lr_ptr : lr;
126
+
127
+ if (found_inf_ptr && *found_inf_ptr == 1) {
128
+ return;
129
+ }
130
+ const auto [bias_correction1, bias_correction2_sqrt] =
131
+ [&]() -> std::pair<double, double> {
132
+ auto* step_count =
133
+ reinterpret_cast<const float*>(tl.state_steps_addresses[tensor_loc]);
134
+ const auto bias_correction1 = 1 - at::native::pow_(beta1, *step_count);
135
+ const auto bias_correction2 = 1 - at::native::pow_(beta2, *step_count);
136
+ const auto bias_correction2_sqrt = std::sqrt(bias_correction2);
137
+ return {bias_correction1, bias_correction2_sqrt};
138
+ }();
139
+
140
+ scalar_type* args[depth];
141
+ scalar_type r_args[depth][kILP];
142
+ const auto n = tl.numel_for_tensor[tensor_loc] - chunk_idx * chunk_size;
143
+
144
+ const bool all_aligned{
145
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc)};
146
+ if ((n % kILP == 0) && (chunk_size % kILP == 0) && all_aligned) {
147
+ for (int64_t i_start = threadIdx.x;
148
+ i_start * kILP < n && i_start * kILP < chunk_size;
149
+ i_start += blockDim.x) {
150
+ #pragma unroll
151
+ for (int i = 0; i < depth; i++) {
152
+ load_store(r_args[i], args[i], 0, i_start);
153
+ }
154
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
155
+ r_args,
156
+ lr_double,
157
+ beta1,
158
+ beta2,
159
+ weight_decay,
160
+ eps,
161
+ maximize,
162
+ grad_scale_ptr,
163
+ found_inf_ptr,
164
+ bias_correction1,
165
+ bias_correction2_sqrt);
166
+ #pragma unroll
167
+ for (int i = 0; i < depth; i++) {
168
+ if (i != kGradIdx || grad_scale_ptr) {
169
+ load_store(args[i], r_args[i], i_start, 0);
170
+ }
171
+ }
172
+ }
173
+ } else {
174
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
175
+ i_start += blockDim.x * kILP) {
176
+ load_args<depth>(r_args, args, i_start, chunk_size, n);
177
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
178
+ r_args,
179
+ lr_double,
180
+ beta1,
181
+ beta2,
182
+ weight_decay,
183
+ eps,
184
+ maximize,
185
+ grad_scale_ptr,
186
+ found_inf_ptr,
187
+ bias_correction1,
188
+ bias_correction2_sqrt);
189
+ #pragma unroll
190
+ for (int i = 0; i < depth; i++) {
191
+ if (i != kGradIdx || grad_scale_ptr) {
192
+ store_args(args[i], r_args[i], i_start, chunk_size, n);
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+ };
199
+ } // namespace
200
+
201
+ } // namespace at::native
202
+
203
+ #else
204
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
205
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/fused_adamw_amsgrad_impl.cuh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adamw_amsgrad_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList max_exp_avg_sqs,
13
+ at::TensorList state_steps,
14
+ const double lr,
15
+ const double beta1,
16
+ const double beta2,
17
+ const double weight_decay,
18
+ const double eps,
19
+ const bool maximize,
20
+ const std::optional<at::Tensor>& grad_scale,
21
+ const std::optional<at::Tensor>& found_inf);
22
+
23
+ void _fused_adamw_amsgrad_cuda_impl_(
24
+ at::TensorList params,
25
+ at::TensorList grads,
26
+ at::TensorList exp_avgs,
27
+ at::TensorList exp_avg_sqs,
28
+ at::TensorList max_exp_avg_sqs,
29
+ at::TensorList state_steps,
30
+ const at::Tensor& lr,
31
+ const double beta1,
32
+ const double beta2,
33
+ const double weight_decay,
34
+ const double eps,
35
+ const bool maximize,
36
+ const std::optional<at::Tensor>& grad_scale,
37
+ const std::optional<at::Tensor>& found_inf);
38
+
39
+ } // namespace at::native
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/native/cuda/fused_adamw_impl.cuh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adamw_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList state_steps,
13
+ const double lr,
14
+ const double beta1,
15
+ const double beta2,
16
+ const double weight_decay,
17
+ const double eps,
18
+ const bool maximize,
19
+ const std::optional<at::Tensor>& grad_scale,
20
+ const std::optional<at::Tensor>& found_inf);
21
+
22
+ void _fused_adamw_cuda_impl_(
23
+ at::TensorList params,
24
+ at::TensorList grads,
25
+ at::TensorList exp_avgs,
26
+ at::TensorList exp_avg_sqs,
27
+ at::TensorList state_steps,
28
+ const at::Tensor& lr,
29
+ const double beta1,
30
+ const double beta2,
31
+ const double weight_decay,
32
+ const double eps,
33
+ const bool maximize,
34
+ const std::optional<at::Tensor>& grad_scale,
35
+ const std::optional<at::Tensor>& found_inf);
36
+
37
+ } // namespace at::native
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/native/cuda/im2col.cuh ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/AccumulateType.h>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/cuda/detail/KernelUtils.h>
7
+
8
+ #include <c10/macros/Macros.h>
9
+
10
+ namespace at::native {
11
+
12
+ using namespace at::cuda::detail;
13
+
14
+ // Kernel for fast unfold+copy
15
+ // (borrowed from Caffe:
16
+ // https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu)
17
+ // CUDA_NUM_THREADS = 1024
18
+
19
+ template <typename dt>
20
+ C10_LAUNCH_BOUNDS_1(1024)
21
+ __global__ void im2col_kernel(
22
+ const int64_t n,
23
+ const dt* data_im,
24
+ const int64_t height,
25
+ const int64_t width,
26
+ const int64_t kernel_height,
27
+ const int64_t kernel_width,
28
+ const int64_t pad_height,
29
+ const int64_t pad_width,
30
+ const int64_t stride_height,
31
+ const int64_t stride_width,
32
+ const int64_t dilation_height,
33
+ const int64_t dilation_width,
34
+ const int64_t height_col,
35
+ const int64_t width_col,
36
+ dt* data_col) {
37
+ CUDA_KERNEL_LOOP_TYPE(index, n, int64_t) {
38
+ int64_t w_out = index % width_col;
39
+
40
+ int64_t idx = index / width_col;
41
+
42
+ int64_t h_out = idx % height_col;
43
+ int64_t channel_in = idx / height_col;
44
+ int64_t channel_out = channel_in * kernel_height * kernel_width;
45
+ int64_t h_in = h_out * stride_height - pad_height;
46
+ int64_t w_in = w_out * stride_width - pad_width;
47
+
48
+ dt* col = data_col + (channel_out * height_col + h_out) * width_col + w_out;
49
+ const dt* im = data_im + (channel_in * height + h_in) * width + w_in;
50
+
51
+ for (int64_t i = 0; i < kernel_height; ++i) {
52
+ for (int64_t j = 0; j < kernel_width; ++j) {
53
+ int64_t h = h_in + i * dilation_height;
54
+ int64_t w = w_in + j * dilation_width;
55
+ *col = (h >= 0 && w >= 0 && h < height && w < width)
56
+ ? im[i * dilation_height * width + j * dilation_width]
57
+ : static_cast<dt>(0);
58
+ col += height_col * width_col;
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ template <typename dt>
65
+ void im2col(
66
+ cudaStream_t stream,
67
+ const dt* data_im,
68
+ const int64_t channels,
69
+ const int64_t height,
70
+ const int64_t width,
71
+ const int64_t height_col,
72
+ const int64_t width_col,
73
+ const int64_t kernel_height,
74
+ const int64_t kernel_width,
75
+ const int64_t pad_height,
76
+ const int64_t pad_width,
77
+ const int64_t stride_height,
78
+ const int64_t stride_width,
79
+ const int64_t dilation_height,
80
+ const int64_t dilation_width,
81
+ dt* data_col) {
82
+ // We are going to launch channels * height_col * width_col kernels, each
83
+ // kernel responsible for copying a single-channel grid.
84
+ int64_t num_kernels = channels * height_col * width_col;
85
+ // Launch CUDA_NUM_THREADS = 1024
86
+ im2col_kernel<<<GET_BLOCKS(num_kernels), 1024, 0, stream>>>(
87
+ num_kernels,
88
+ data_im,
89
+ height,
90
+ width,
91
+ kernel_height,
92
+ kernel_width,
93
+ pad_height,
94
+ pad_width,
95
+ stride_height,
96
+ stride_width,
97
+ dilation_height,
98
+ dilation_width,
99
+ height_col,
100
+ width_col,
101
+ data_col);
102
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
103
+ }
104
+
105
+ template <typename accT, typename dt>
106
+ __forceinline__ __device__ void col2im_device(
107
+ const int64_t index,
108
+ const dt* data_col,
109
+ const int64_t height,
110
+ const int64_t width,
111
+ const int64_t kernel_h,
112
+ const int64_t kernel_w,
113
+ const int64_t pad_height,
114
+ const int64_t pad_width,
115
+ const int64_t stride_height,
116
+ const int64_t stride_width,
117
+ const int64_t dilation_height,
118
+ const int64_t dilation_width,
119
+ const int64_t height_col,
120
+ const int64_t width_col,
121
+ dt* data_im) {
122
+ accT val = static_cast<accT>(0);
123
+ const int64_t w_im = index % width + pad_width;
124
+ const int64_t h_im = (index / width) % height + pad_height;
125
+ const int64_t c_im = index / (width * height);
126
+ int64_t kernel_extent_w = (kernel_w - 1) * dilation_width + 1;
127
+ int64_t kernel_extent_h = (kernel_h - 1) * dilation_height + 1;
128
+ // compute the start and end of the output
129
+ const int64_t w_col_start = (w_im < kernel_extent_w)
130
+ ? 0
131
+ : (w_im - kernel_extent_w) / stride_width + 1;
132
+ const int64_t w_col_end = ::min(w_im / stride_width + 1, width_col);
133
+ const int64_t h_col_start = (h_im < kernel_extent_h)
134
+ ? 0
135
+ : (h_im - kernel_extent_h) / stride_height + 1;
136
+ const int64_t h_col_end = ::min(h_im / stride_height + 1, height_col);
137
+
138
+ // TODO: use LCM of stride and dilation to avoid unnecessary loops
139
+ for (int64_t h_col = h_col_start; h_col < h_col_end; h_col += 1) {
140
+ for (int64_t w_col = w_col_start; w_col < w_col_end; w_col += 1) {
141
+ int64_t h_k = (h_im - h_col * stride_height);
142
+ int64_t w_k = (w_im - w_col * stride_width);
143
+ if (h_k % dilation_height == 0 && w_k % dilation_width == 0) {
144
+ h_k /= dilation_height;
145
+ w_k /= dilation_width;
146
+ int64_t data_col_index =
147
+ (((c_im * kernel_h + h_k) * kernel_w + w_k) * height_col +
148
+ h_col) *
149
+ width_col +
150
+ w_col;
151
+ val += data_col[data_col_index];
152
+ }
153
+ }
154
+ }
155
+ data_im[index] = static_cast<dt>(val);
156
+ }
157
+
158
+ template <typename dt, typename accT>
159
+ C10_LAUNCH_BOUNDS_1(512)
160
+ __global__ void col2im_kernel(
161
+ const int64_t n,
162
+ const dt* data_col,
163
+ const int64_t height,
164
+ const int64_t width,
165
+ const int64_t kernel_h,
166
+ const int64_t kernel_w,
167
+ const int64_t pad_height,
168
+ const int64_t pad_width,
169
+ const int64_t stride_height,
170
+ const int64_t stride_width,
171
+ const int64_t dilation_height,
172
+ const int64_t dilation_width,
173
+ const int64_t height_col,
174
+ const int64_t width_col,
175
+ dt* data_im) {
176
+ CUDA_KERNEL_LOOP(index, n) {
177
+ col2im_device<accT>(
178
+ index,
179
+ data_col,
180
+ height,
181
+ width,
182
+ kernel_h,
183
+ kernel_w,
184
+ pad_height,
185
+ pad_width,
186
+ stride_height,
187
+ stride_width,
188
+ dilation_height,
189
+ dilation_width,
190
+ height_col,
191
+ width_col,
192
+ data_im);
193
+ }
194
+ }
195
+
196
+ template <typename dt, typename accT>
197
+ void col2im(
198
+ cudaStream_t stream,
199
+ const dt* data_col,
200
+ const int64_t channels,
201
+ const int64_t height,
202
+ const int64_t width,
203
+ const int64_t height_col,
204
+ const int64_t width_col,
205
+ const int64_t patch_height,
206
+ const int64_t patch_width,
207
+ const int64_t pad_height,
208
+ const int64_t pad_width,
209
+ const int64_t stride_height,
210
+ const int64_t stride_width,
211
+ const int64_t dilation_height,
212
+ const int64_t dilation_width,
213
+ dt* data_im) {
214
+ int64_t num_kernels = channels * height * width;
215
+ // To avoid involving atomic operations, we will launch one kernel per
216
+ // bottom dimension, and then in the kernel add up the top dimensions.
217
+ // CUDA_NUM_THREADS = 1024
218
+ col2im_kernel<dt, accT>
219
+ <<<GET_BLOCKS(num_kernels, 512), 512, 0, stream>>>(
220
+ num_kernels,
221
+ data_col,
222
+ height,
223
+ width,
224
+ patch_height,
225
+ patch_width,
226
+ pad_height,
227
+ pad_width,
228
+ stride_height,
229
+ stride_width,
230
+ dilation_height,
231
+ dilation_width,
232
+ height_col,
233
+ width_col,
234
+ data_im);
235
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
236
+ }
237
+
238
+ template <typename dt>
239
+ C10_LAUNCH_BOUNDS_1(512)
240
+ __global__ void col2im_batched_kernel(
241
+ const int64_t n,
242
+ const dt* data_col,
243
+ const int64_t col_batch_stride,
244
+ const int64_t nbatch,
245
+ const int64_t height,
246
+ const int64_t width,
247
+ const int64_t kernel_h,
248
+ const int64_t kernel_w,
249
+ const int64_t pad_height,
250
+ const int64_t pad_width,
251
+ const int64_t stride_height,
252
+ const int64_t stride_width,
253
+ const int64_t dilation_height,
254
+ const int64_t dilation_width,
255
+ const int64_t height_col,
256
+ const int64_t width_col,
257
+ dt* data_im,
258
+ const int64_t im_batch_stride) {
259
+ using accT = at::acc_type<dt, /*is_cuda*/true>;
260
+ const auto im_numel = n * nbatch;
261
+
262
+ CUDA_KERNEL_LOOP_TYPE(index, im_numel, int64_t) {
263
+ const auto ibatch = index / n;
264
+ const auto slice_index = index % n;
265
+
266
+ col2im_device<accT>(
267
+ slice_index,
268
+ data_col + ibatch * col_batch_stride,
269
+ height,
270
+ width,
271
+ kernel_h,
272
+ kernel_w,
273
+ pad_height,
274
+ pad_width,
275
+ stride_height,
276
+ stride_width,
277
+ dilation_height,
278
+ dilation_width,
279
+ height_col,
280
+ width_col,
281
+ data_im + ibatch * im_batch_stride);
282
+ }
283
+ }
284
+
285
+ template <typename dt>
286
+ void col2im_batched(
287
+ cudaStream_t stream,
288
+ const dt* data_col,
289
+ const int64_t col_batch_stride,
290
+ const int64_t nbatch,
291
+ const int64_t channels,
292
+ const int64_t height,
293
+ const int64_t width,
294
+ const int64_t height_col,
295
+ const int64_t width_col,
296
+ const int64_t patch_height,
297
+ const int64_t patch_width,
298
+ const int64_t pad_height,
299
+ const int64_t pad_width,
300
+ const int64_t stride_height,
301
+ const int64_t stride_width,
302
+ const int64_t dilation_height,
303
+ const int64_t dilation_width,
304
+ dt* data_im,
305
+ const int64_t im_batch_stride) {
306
+ const int64_t num_kernels = channels * height * width;
307
+ const int64_t output_numel = nbatch * num_kernels;
308
+ if (output_numel == 0) {
309
+ return; // No work to do
310
+ }
311
+
312
+ // To avoid involving atomic operations, we will launch one kernel per
313
+ // bottom dimension, and then in the kernel add up the top dimensions.
314
+ // CUDA_NUM_THREADS = 1024
315
+ col2im_batched_kernel<<<GET_BLOCKS(output_numel, 512), 512, 0, stream>>>(
316
+ num_kernels,
317
+ data_col,
318
+ col_batch_stride,
319
+ nbatch,
320
+ height,
321
+ width,
322
+ patch_height,
323
+ patch_width,
324
+ pad_height,
325
+ pad_width,
326
+ stride_height,
327
+ stride_width,
328
+ dilation_height,
329
+ dilation_width,
330
+ height_col,
331
+ width_col,
332
+ data_im,
333
+ im_batch_stride);
334
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
335
+ }
336
+
337
+ } // namespace at::native
338
+
339
+ #else
340
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
341
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/jit_utils.h ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+
6
+ #include <c10/util/irange.h>
7
+ #include <ATen/jit_macros.h>
8
+ #include <ATen/cuda/detail/LazyNVRTC.h>
9
+
10
+ namespace at::cuda::jit {
11
+
12
+ enum class BinaryFuncVariant {NoScalar, RhsScalar, LhsScalar};
13
+
14
+ struct NvrtcFunction {
15
+ CUmodule module = CUmodule();
16
+ CUfunction function = nullptr;
17
+ };
18
+
19
+ struct KernelDescriptor {
20
+ std::string name;
21
+ std::string f;
22
+ c10::ScalarType f_inputs_type;
23
+ c10::ScalarType result_type;
24
+ c10::SmallVector<c10::ScalarType> extra_args_types;
25
+ int nInputs, nOutputs;
26
+ };
27
+
28
+ // Helper function to return a vector<string>
29
+ // corresponding to the type of the arguments in parameter pack.
30
+ template <typename... Args>
31
+ c10::SmallVector<at::ScalarType> get_extra_args_types() {
32
+ return {c10::CppTypeToScalarType<Args>::value ...};
33
+ }
34
+
35
+ template <
36
+ typename result_type,
37
+ typename f_inputs_type,
38
+ typename... ExtraArgs>
39
+ KernelDescriptor make_kernel_descriptor(
40
+ std::string name,
41
+ std::string f,
42
+ int nInputs,
43
+ int nOutputs) {
44
+ KernelDescriptor ret;
45
+ ret.name = std::move(name);
46
+ ret.f = std::move(f);
47
+ ret.f_inputs_type = c10::CppTypeToScalarType<f_inputs_type>::value;
48
+ ret.result_type = c10::CppTypeToScalarType<result_type>::value;
49
+ ret.extra_args_types = get_extra_args_types<ExtraArgs...>();
50
+ ret.nInputs = nInputs;
51
+ ret.nOutputs = nOutputs;
52
+ return ret;
53
+ }
54
+
55
+ inline int can_vectorize_up_to(size_t default_alignment, void *pointer) {
56
+ auto ip = reinterpret_cast<uintptr_t>(pointer);
57
+ #ifdef USE_ROCM
58
+ if ((default_alignment == 1) && (ip % (16 * default_alignment) == 0)) {
59
+ return 16;
60
+ }
61
+ if ((default_alignment <= 2) && (ip % (8 * default_alignment) == 0)) {
62
+ return 8;
63
+ }
64
+ #else
65
+ if (ip % (8 * default_alignment) == 0) {
66
+ return 8;
67
+ }
68
+ #endif
69
+ if (ip % (4 * default_alignment) == 0) {
70
+ return 4;
71
+ }
72
+ if (ip % (2 * default_alignment) == 0) {
73
+ return 2;
74
+ }
75
+ return 1;
76
+ }
77
+
78
+ inline int can_vectorize_up_to(const KernelDescriptor &desc, c10::ArrayRef<char*> pointers) {
79
+ TORCH_INTERNAL_ASSERT(desc.nOutputs == 1);
80
+ TORCH_INTERNAL_ASSERT(static_cast<int64_t>(pointers.size()) == 1 + desc.nInputs);
81
+
82
+ // Deals with output
83
+ auto result_size = c10::scalarTypeToTypeMeta(desc.result_type).itemsize();
84
+ auto result = can_vectorize_up_to(result_size, pointers[0]);
85
+
86
+ // Incorporates input(s)
87
+ auto input_size = c10::scalarTypeToTypeMeta(desc.f_inputs_type).itemsize();
88
+ for (auto i : c10::irange(1, pointers.size())) {
89
+ result = std::min(result, can_vectorize_up_to(input_size, pointers[i]));
90
+ }
91
+
92
+ return result;
93
+ }
94
+
95
+ //FIXME - this are defined in Loops.cuh, but including Loops.cuh here would lead to circular includes Loops.cuh -> CUDALoops.cuh -> jit_utils.h -> Loops.cuh
96
+ #ifdef USE_ROCM
97
+ #define JIT_THREAD_WORK_SIZE 4
98
+ #else
99
+ #define JIT_THREAD_WORK_SIZE 8
100
+ #endif
101
+
102
+ int calc_io_size(
103
+ const int nInputs,
104
+ const int nOutputs,
105
+ const c10::ScalarType& inputs_type,
106
+ const c10::ScalarType& result_type);
107
+
108
+ int calc_thread_work_size(
109
+ const int nInputs,
110
+ const int nOutputs,
111
+ const c10::ScalarType& inputs_type,
112
+ const c10::ScalarType& result_type);
113
+
114
+ std::string generate_code(
115
+ int nInputs,
116
+ int nOutputs,
117
+ const std::string& func,
118
+ const std::string& name,
119
+ const std::string& f_inputs_type,
120
+ const std::string& compute_type,
121
+ const std::string& result_type,
122
+ bool contiguous,
123
+ bool dynamic_casting,
124
+ BinaryFuncVariant scalar_pos,
125
+ c10::SmallVector<std::string>& extra_args_typenames,
126
+ int thread_work_size=JIT_THREAD_WORK_SIZE,
127
+ bool vectorized=false,
128
+ int vec_size=0,
129
+ bool return_by_ref=false);
130
+
131
+ std::string generate_code(
132
+ const KernelDescriptor &desc,
133
+ bool contiguous,
134
+ bool dynamic_casting,
135
+ BinaryFuncVariant scalar_pos,
136
+ int thread_work_size=JIT_THREAD_WORK_SIZE,
137
+ bool vectorized=false,
138
+ int vec_size=0,
139
+ bool return_by_ref=false);
140
+
141
+ std::string generate_reduction_code(
142
+ int nOutputs,
143
+ const std::string& func,
144
+ const std::string& name,
145
+ const int vt0,
146
+ const std::string& f_inputs_type,
147
+ const std::string& reduction_accum_type,
148
+ const std::string& result_type,
149
+ bool contiguous,
150
+ bool vectorized,
151
+ int vec_size,
152
+ int max_threads_codegen);
153
+
154
+ std::string generate_reduction_code(
155
+ const KernelDescriptor &desc,
156
+ const int vt0,
157
+ bool contiguous,
158
+ bool vectorized,
159
+ int vec_size,
160
+ int max_threads_codegen);
161
+
162
+ NvrtcFunction jit_pwise_function(
163
+ const std::string& code,
164
+ const std::string& kernel_name);
165
+
166
+ void launch_jitted_pwise_function(
167
+ NvrtcFunction function,
168
+ const void* args[],
169
+ const dim3 nBlocks,
170
+ const dim3 kBlockSize,
171
+ const int smem=0);
172
+
173
+ template <typename T>
174
+ struct delayed_false : std::false_type {
175
+ };
176
+
177
+ // Defines type names
178
+ // NOTE: General case is instantiated only for invalid types.
179
+ // All the valid types have specialization using the TYPE_NAME_FN
180
+ // macro below.
181
+ template <typename T>
182
+ inline std::string typeName() {
183
+ // we can't use static_assert(false) directly as the
184
+ // program will be not compiled even if the template is not
185
+ // instantiated, so we use `delayed_false`
186
+ // to make sure compiler doesn't eagerly raise
187
+ // fail this assertion.
188
+ static_assert(delayed_false<T>::value, "invalid type for jiterator");
189
+ return "void";
190
+ }
191
+
192
+ #define TYPE_NAME_FN(ctype, name) \
193
+ template <> inline std::string typeName<ctype>(){ \
194
+ return std::string(#ctype); \
195
+ }
196
+
197
+ AT_FORALL_SCALAR_TYPES(TYPE_NAME_FN)
198
+ #undef TYPE_NAME_FN
199
+ // JIT uses std::complex directly, because nvRTC compile programs
200
+ // with -default-device, so there is no such issue like:
201
+ // "std::sin(complex) is __host__ only"
202
+ template <> inline std::string typeName<bool>(){
203
+ return "bool";
204
+ }
205
+ template <> inline std::string typeName<c10::complex<at::Half>>(){
206
+ return "std::complex<at::Half>";
207
+ }
208
+ template <> inline std::string typeName<c10::complex<float>>(){
209
+ return "std::complex<float>";
210
+ }
211
+ template <> inline std::string typeName<c10::complex<double>>(){
212
+ return "std::complex<double>";
213
+ }
214
+ template <> inline std::string typeName<at::Half>(){
215
+ return "at::Half";
216
+ }
217
+ template <> inline std::string typeName<at::BFloat16>(){
218
+ return "at::BFloat16";
219
+ }
220
+ template <> inline std::string typeName<at::Float8_e5m2>(){
221
+ return "at::Float8_e5m2";
222
+ }
223
+ template <> inline std::string typeName<at::Float8_e4m3fn>(){
224
+ return "at::Float8_e4m3fn";
225
+ }
226
+ template <> inline std::string typeName<at::Float8_e5m2fnuz>() {
227
+ return "at::Float8_e5m2fnuz";
228
+ }
229
+ template <> inline std::string typeName<at::Float8_e4m3fnuz>() {
230
+ return "at::Float8_e4m3fnuz";
231
+ }
232
+ template <> inline std::string typeName<at::Float8_e8m0fnu>() {
233
+ // TODO(#146647): Can the code here be made generic for any scalartype?
234
+ return "at::Float8_e8m0fnu";
235
+ }
236
+
237
+ #define TYPE_NAME_CASE(ctype, scalartype) \
238
+ case ScalarType::scalartype: return typeName<ctype>();
239
+ inline std::string typeName(ScalarType t) {
240
+ switch (t) {
241
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(TYPE_NAME_CASE)
242
+ default:
243
+ TORCH_CHECK(false, "invalid type for jiterator");
244
+ }
245
+ }
246
+ #undef TYPE_NAME_CASE
247
+
248
+ TORCH_CUDA_CPP_API void initializeCudaContext();
249
+
250
+ } // namespace at::cuda::jit
251
+
252
+ #else
253
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
254
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/reduction_template.cuh ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ namespace at::cuda {
3
+ //windows doesn't like large string literals, so split in two
4
+ const std::string reduction_template_0 = R"ESCAPE(
5
+ #define C10_HOST_DEVICE __host__ __device__
6
+ #define C10_DEVICE __device__
7
+ #if defined(__clang__) && defined(__HIP__)
8
+ #ifndef __forceinline__
9
+ #define __forceinline__ inline __attribute__((always_inline))
10
+ #endif
11
+ // until ROCm support for kernel asserts is restored
12
+ #define assert(expr) (static_cast<void>(0))
13
+ #endif
14
+
15
+ template <typename T>
16
+ __device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
17
+ {
18
+ #if defined(__clang__) && defined(__HIP__)
19
+ return __shfl_down(value, delta, width);
20
+ #else
21
+ return __shfl_down_sync(mask, value, delta, width);
22
+ #endif
23
+ }
24
+
25
+
26
+ #if ${complex}
27
+ template <typename T>
28
+ __device__ __forceinline__ std::complex<T> WARP_SHFL_DOWN(std::complex<T> value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
29
+ {
30
+ return std::complex<T>(
31
+ #if defined(__clang__) && defined(__HIP__)
32
+ __shfl_down(value.real(), delta, width),
33
+ __shfl_down(value.imag(), delta, width));
34
+ #else
35
+ __shfl_down_sync(mask, value.real(), delta, width),
36
+ __shfl_down_sync(mask, value.imag(), delta, width));
37
+ #endif
38
+ }
39
+ #endif
40
+
41
+ // aligned vector generates vectorized load/store on CUDA
42
+ template<typename scalar_t, int vec_size>
43
+ struct alignas(sizeof(scalar_t) * vec_size) aligned_vector {
44
+ scalar_t val[vec_size];
45
+ };
46
+
47
+
48
+ C10_HOST_DEVICE static void reduce_fraction(size_t &numerator, size_t &denominator) {
49
+ // get GCD of num and denom using Euclid's algorithm.
50
+ // Can replace this with std::gcd if we ever support c++17.
51
+ size_t a = denominator;
52
+ size_t b = numerator;
53
+ while (b != 0) {
54
+ a %= b;
55
+ // swap(a,b)
56
+ size_t tmp = a;
57
+ a = b;
58
+ b = tmp;
59
+ }
60
+
61
+ // a is now the GCD
62
+ numerator /= a;
63
+ denominator /= a;
64
+ }
65
+
66
+
67
+
68
+
69
+ struct ReduceConfig {
70
+ //has to match host-side ReduceConfig in the eager code
71
+ static constexpr int BLOCK_X = 0;
72
+ static constexpr int BLOCK_Y = 1;
73
+ static constexpr int CTA = 2;
74
+
75
+ static constexpr int input_vec_size = 4;
76
+ int element_size_bytes;
77
+ int num_inputs;
78
+ int num_outputs;
79
+ int step_input = 1;
80
+ int step_output = 1;
81
+ int ctas_per_output = 1;
82
+ int input_mult[3] = {0, 0, 0};
83
+ int output_mult[2] = {0, 0};
84
+
85
+ int block_width;
86
+ int block_height;
87
+ int num_threads;
88
+
89
+ bool vectorize_input = false;
90
+ int output_vec_size = 1;
91
+
92
+ C10_HOST_DEVICE bool should_block_x_reduce() const {
93
+ return input_mult[BLOCK_X] != 0;
94
+ }
95
+
96
+ C10_HOST_DEVICE bool should_block_y_reduce() const {
97
+ return input_mult[BLOCK_Y] != 0;
98
+ }
99
+
100
+ C10_HOST_DEVICE bool should_global_reduce() const {
101
+ return input_mult[CTA] != 0;
102
+ }
103
+
104
+ C10_DEVICE bool should_store(int output_idx) const {
105
+ return output_idx < num_outputs &&
106
+ (!should_block_x_reduce() || threadIdx.x == 0) &&
107
+ (!should_block_y_reduce() || threadIdx.y == 0);
108
+ }
109
+
110
+ C10_DEVICE bool should_reduce_tail() const {
111
+ return (!should_block_y_reduce() || threadIdx.y == 0) &&
112
+ (!should_global_reduce() || blockIdx.y == 0);
113
+ }
114
+
115
+ C10_HOST_DEVICE int input_idx() const {
116
+ int lane = threadIdx.x;
117
+ int warp = threadIdx.y;
118
+ int cta2 = blockIdx.y;
119
+ return (lane * input_mult[BLOCK_X] +
120
+ warp * input_mult[BLOCK_Y] +
121
+ cta2 * input_mult[CTA]);
122
+ }
123
+
124
+ template <int output_vec_size>
125
+ C10_HOST_DEVICE int output_idx() const {
126
+ int lane = threadIdx.x;
127
+ int warp = threadIdx.y;
128
+ int cta1 = blockIdx.x;
129
+ return (lane * output_mult[BLOCK_X] +
130
+ warp * output_mult[BLOCK_Y] +
131
+ cta1 * step_output) * output_vec_size;
132
+ }
133
+
134
+ C10_DEVICE int shared_memory_offset(int offset) const {
135
+ return threadIdx.x + (threadIdx.y + offset) * blockDim.x;
136
+ }
137
+
138
+ C10_DEVICE int staging_memory_offset(int cta2) const {
139
+ int offset = cta2 + blockIdx.x * gridDim.y;
140
+ if (!should_block_x_reduce()) {
141
+ offset = threadIdx.x + offset * blockDim.x;
142
+ }
143
+ return offset;
144
+ }
145
+
146
+
147
+ };
148
+
149
+
150
+ //TODO this will need to be different for more generic reduction functions
151
+ namespace reducer {
152
+
153
+ using scalar_t = ${scalar_type};
154
+ using arg_t = ${reduction_accum_type};
155
+ using out_scalar_t = ${result_type};
156
+
157
+
158
+ inline __device__ ${functor}
159
+
160
+ inline __device__ out_scalar_t project(arg_t arg) {
161
+ return (out_scalar_t) arg;
162
+ }
163
+
164
+ inline __device__ arg_t warp_shfl_down(arg_t arg, int offset) {
165
+ return WARP_SHFL_DOWN(arg, offset);
166
+ }
167
+
168
+ inline __device__ arg_t translate_idx(arg_t acc, int64_t /*idx*/) {
169
+ return acc;
170
+ }
171
+
172
+ // wrap a normal reduction that ignores the index
173
+ inline __device__ arg_t reduce(arg_t acc, arg_t val, int64_t idx) {
174
+ return combine(acc, val);
175
+ }
176
+ }
177
+
178
+
179
+ struct ReduceJitOp {
180
+ using scalar_t = ${scalar_type};
181
+ using arg_t = ${reduction_accum_type};
182
+ using out_scalar_t = ${result_type};
183
+
184
+ using InputCalculator = OffsetCalculator<1>;
185
+ using OutputCalculator = OffsetCalculator<2>;
186
+
187
+ // static constexpr bool can_accumulate_in_output =
188
+ // std::is_convertible_v<arg_t, out_scalar_t>
189
+ // && std::is_convertible_v<out_scalar_t, arg_t>;
190
+
191
+ static constexpr int input_vec_size = ReduceConfig::input_vec_size;
192
+
193
+ arg_t ident;
194
+ ReduceConfig config;
195
+ InputCalculator input_calc;
196
+ OutputCalculator output_calc;
197
+ const void* src;
198
+ const char* dst[2]; //it accepts at most two destinations
199
+ // acc_buf used for accumulation among sub Tensor Iterator when accumulation on
200
+ // output is not permissible
201
+ void* acc_buf;
202
+ // cta_buf used for accumulation between blocks during global reduction
203
+ void* cta_buf;
204
+ int* semaphores;
205
+ int64_t base_idx;
206
+ bool accumulate;
207
+ bool final_output;
208
+ int noutputs;
209
+
210
+
211
+ C10_DEVICE void run() const {
212
+ extern __shared__ char shared_memory[];
213
+ uint32_t output_idx = config.output_idx<${output_vec_size}>();
214
+ uint32_t input_idx = config.input_idx();
215
+ auto base_offsets1 = output_calc.get(output_idx)[1];
216
+
217
+ using arg_vec_t = Array<arg_t, ${output_vec_size}>;
218
+ arg_vec_t value;
219
+
220
+ if (output_idx < config.num_outputs && input_idx < config.num_inputs) {
221
+ const scalar_t* input_slice = (const scalar_t*)((const char*)src + base_offsets1);
222
+
223
+ value = thread_reduce<${output_vec_size}>(input_slice);
224
+ }
225
+
226
+ if (config.should_block_y_reduce()) {
227
+ value = block_y_reduce<${output_vec_size}>(value, shared_memory);
228
+ }
229
+ if (config.should_block_x_reduce()) {
230
+ value = block_x_reduce<${output_vec_size}>(value, shared_memory);
231
+ }
232
+
233
+ using out_ptr_vec_t = Array<out_scalar_t*, ${output_vec_size}>;
234
+ using offset_vec_t = Array<uint32_t, ${output_vec_size}>;
235
+ offset_vec_t base_offsets;
236
+ out_ptr_vec_t out;
237
+
238
+ #pragma unroll
239
+ for (int i = 0; i < ${output_vec_size}; i++) {
240
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
241
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
242
+ }
243
+
244
+ arg_vec_t* acc = nullptr;
245
+ if (acc_buf != nullptr) {
246
+ size_t numerator = sizeof(arg_t);
247
+ size_t denominator = sizeof(out_scalar_t);
248
+ reduce_fraction(numerator, denominator);
249
+ acc = (arg_vec_t*)((char*)acc_buf + (base_offsets[0] * numerator / denominator));
250
+ }
251
+
252
+ if (config.should_global_reduce()) {
253
+ value = global_reduce<${output_vec_size}>(value, acc, shared_memory);
254
+ } else if (config.should_store(output_idx)) {
255
+ if (accumulate) {
256
+ #pragma unroll
257
+ for (int i = 0; i < ${output_vec_size}; i++) {
258
+ value[i] = reducer::translate_idx(value[i], base_idx);
259
+ }
260
+ }
261
+
262
+ if (acc == nullptr) {
263
+ if (accumulate) {
264
+ value = accumulate_in_output<${output_vec_size}>(out, value);
265
+ }
266
+ if (final_output) {
267
+ set_results_to_output<${output_vec_size}>(value, base_offsets);
268
+ } else {
269
+ #pragma unroll
270
+ for (int i = 0; i < ${output_vec_size}; i++) {
271
+ *(out[i]) = get_accumulated_output(out[i], value[i]);
272
+ }
273
+ }
274
+ } else {
275
+ if (accumulate) {
276
+ #pragma unroll
277
+ for (int i = 0; i < ${output_vec_size}; i++) {
278
+ value[i] = reducer::combine((*acc)[i], value[i]);
279
+ }
280
+ }
281
+ if (final_output) {
282
+ set_results_to_output<${output_vec_size}>(value, base_offsets);
283
+ } else {
284
+ *acc = value;
285
+ }
286
+ }
287
+ }
288
+ }
289
+
290
+ template <int output_vec_size>
291
+ C10_DEVICE Array<arg_t, output_vec_size> thread_reduce(const scalar_t* data) const {
292
+ if (config.vectorize_input) {
293
+ assert(output_vec_size == 1);
294
+ // reduce at the header of input_slice where memory is not aligned,
295
+ // so that thread_reduce will have an aligned memory to work on.
296
+ return {input_vectorized_thread_reduce_impl(data)};
297
+ } else {
298
+ uint32_t element_stride = input_calc.strides_[0][0] / sizeof(scalar_t);
299
+ bool is_contiguous = (input_calc.dims == 1 && element_stride == 1);
300
+ if (is_contiguous) {
301
+ return thread_reduce_impl<output_vec_size>(data, [](uint32_t idx) { return idx; });
302
+ } else if (input_calc.dims == 1) {
303
+ return thread_reduce_impl<output_vec_size>(data, [&](uint32_t idx) { return idx * element_stride; });
304
+ } else {
305
+ return thread_reduce_impl<output_vec_size>(data, [&](uint32_t idx) { return input_calc.get(idx)[0] / sizeof(scalar_t); });
306
+ }
307
+ }
308
+ }
309
+
310
+ C10_DEVICE arg_t input_vectorized_thread_reduce_impl(const scalar_t* data) const {
311
+ uint32_t end = config.num_inputs;
312
+
313
+ // Handle the head of input slice where data is not aligned
314
+ arg_t value = ident;
315
+ constexpr int align_bytes = alignof(aligned_vector<scalar_t, input_vec_size>);
316
+ constexpr int align_elements = align_bytes / sizeof(scalar_t);
317
+ int shift = ((int64_t)data) % align_bytes / sizeof(scalar_t);
318
+ if (shift > 0) {
319
+ data -= shift;
320
+ end += shift;
321
+ if(threadIdx.x >= shift && threadIdx.x < align_elements && config.should_reduce_tail()){
322
+ value = reducer::reduce(value, data[threadIdx.x], threadIdx.x - shift);
323
+ }
324
+ end -= align_elements;
325
+ data += align_elements;
326
+ shift = align_elements - shift;
327
+ }
328
+
329
+ // Do the vectorized reduction
330
+ using load_t = aligned_vector<scalar_t, input_vec_size>;
331
+
332
+ uint32_t idx = config.input_idx();
333
+ const uint32_t stride = config.step_input;
334
+
335
+ // Multiple accumulators to remove dependency between unrolled loops.
336
+ arg_t value_list[input_vec_size];
337
+ value_list[0] = value;
338
+
339
+ #pragma unroll
340
+ for (int i = 1; i < input_vec_size; i++) {
341
+ value_list[i] = ident;
342
+ }
343
+
344
+ scalar_t values[input_vec_size];
345
+
346
+ load_t *values_vector = reinterpret_cast<load_t*>(&values[0]);
347
+
348
+ while (idx * input_vec_size + input_vec_size - 1 < end) {
349
+ *values_vector = reinterpret_cast<const load_t*>(data)[idx];
350
+ #pragma unroll
351
+ for (uint32_t i = 0; i < input_vec_size; i++) {
352
+ value_list[i] = reducer::reduce(value_list[i], values[i], shift + idx * input_vec_size + i);
353
+ }
354
+ idx += stride;
355
+ }
356
+
357
+ // tail
358
+ uint32_t tail_start = end - end % input_vec_size;
359
+ if (config.should_reduce_tail()) {
360
+ int idx = tail_start + threadIdx.x;
361
+ if (idx < end) {
362
+ value_list[0] = reducer::reduce(value_list[0], data[idx], idx + shift);
363
+ }
364
+ }
365
+
366
+ // combine accumulators
367
+ #pragma unroll
368
+ for (int i = 1; i < input_vec_size; i++) {
369
+ value_list[0] = reducer::combine(value_list[0], value_list[i]);
370
+ }
371
+ return value_list[0];
372
+ }
373
+
374
+ template <int output_vec_size, typename offset_calc_t>
375
+ C10_DEVICE Array<arg_t, output_vec_size> thread_reduce_impl(const scalar_t* data_, offset_calc_t calc) const {
376
+ uint32_t idx = config.input_idx();
377
+ const uint32_t end = config.num_inputs;
378
+ const uint32_t stride = config.step_input;
379
+ const int vt0=${vt0};
380
+
381
+ using arg_vec_t = Array<arg_t, output_vec_size>;
382
+ using load_t = aligned_vector<scalar_t, output_vec_size>;
383
+ const load_t* data = reinterpret_cast<const load_t*>(data_);
384
+
385
+ // Multiple accumulators to remove dependency between unrolled loops.
386
+ arg_vec_t value_list[vt0];
387
+
388
+ #pragma unroll
389
+ for (int i = 0; i < vt0; i++) {
390
+ #pragma unroll
391
+ for (int j = 0; j < output_vec_size; j++) {
392
+ value_list[i][j] = ident;
393
+ }
394
+ }
395
+
396
+ load_t values[vt0];
397
+
398
+ while (idx + (vt0 - 1) * stride < end) {
399
+ #pragma unroll
400
+ for (uint32_t i = 0; i < vt0; i++) {
401
+ values[i] = data[calc(idx + i * stride) / output_vec_size];
402
+ }
403
+ #pragma unroll
404
+ for (uint32_t i = 0; i < vt0; i++) {
405
+ #pragma unroll
406
+ for (uint32_t j = 0; j < output_vec_size; j++) {
407
+ value_list[i][j] = reducer::reduce(value_list[i][j], values[i].val[j], idx + i * stride);
408
+ }
409
+ }
410
+ idx += stride * vt0;
411
+ }
412
+
413
+ // tail
414
+ int idx_ = idx;
415
+ #pragma unroll
416
+ for (uint32_t i = 0; i < vt0; i++) {
417
+ if (idx >= end) {
418
+ break;
419
+ }
420
+ values[i] = data[calc(idx) / output_vec_size];
421
+ idx += stride;
422
+ }
423
+ idx = idx_;
424
+ #pragma unroll
425
+ for (uint32_t i = 0; i < vt0; i++) {
426
+ if (idx >= end) {
427
+ break;
428
+ }
429
+ #pragma unroll
430
+ for (uint32_t j = 0; j < output_vec_size; j++) {
431
+ value_list[i][j] = reducer::reduce(value_list[i][j], values[i].val[j], idx);
432
+ }
433
+ idx += stride;
434
+ }
435
+
436
+ // combine accumulators
437
+ #pragma unroll
438
+ for (int i = 1; i < vt0; i++) {
439
+ #pragma unroll
440
+ for (uint32_t j = 0; j < output_vec_size; j++) {
441
+ value_list[0][j] = reducer::combine(value_list[0][j], value_list[i][j]);
442
+ }
443
+ }
444
+ return value_list[0];
445
+ }
446
+ template <int output_vec_size>
447
+ C10_DEVICE Array<arg_t, output_vec_size> block_x_reduce(Array<arg_t, output_vec_size> value, char* shared_memory) const {
448
+ using args_vec_t = Array<arg_t, output_vec_size>;
449
+ int dim_x = blockDim.x;
450
+ args_vec_t* shared = (args_vec_t*)shared_memory;
451
+ if (dim_x > warpSize) {
452
+ int address_base = threadIdx.x + threadIdx.y*blockDim.x;
453
+ shared[address_base] = value;
454
+ for (int offset = dim_x/2; offset >= warpSize; offset >>= 1) {
455
+ __syncthreads();
456
+ if (threadIdx.x < offset && threadIdx.x + offset < blockDim.x) {
457
+ args_vec_t other = shared[address_base + offset];
458
+ #pragma unroll
459
+ for (int i = 0; i < output_vec_size; i++) {
460
+ value[i] = reducer::combine(value[i], other[i]);
461
+ }
462
+ shared[address_base] = value;
463
+ }
464
+ }
465
+ dim_x = warpSize;
466
+ }
467
+
468
+ __syncthreads();
469
+
470
+ #if defined(USE_ROCM) || defined(FBCODE_CAFFE2)
471
+ for (int offset = 1; offset < dim_x; offset <<= 1) {
472
+ #else
473
+ for (int offset = dim_x >> 1; offset > 0; offset >>= 1) {
474
+ #endif
475
+ #pragma unroll
476
+ for (int i = 0; i < output_vec_size; i++) {
477
+ arg_t other = reducer::warp_shfl_down(value[i], offset);
478
+ value[i] = reducer::combine(value[i], other);
479
+ }
480
+ }
481
+ return value;
482
+ }
483
+
484
+ template <int output_vec_size>
485
+ C10_DEVICE Array<arg_t, output_vec_size> block_y_reduce(Array<arg_t, output_vec_size> value, char* shared_memory) const {
486
+ using args_vec_t = Array<arg_t, output_vec_size>;
487
+ args_vec_t* shared = (args_vec_t*)shared_memory;
488
+ shared[config.shared_memory_offset(0)] = value;
489
+ for (int offset = blockDim.y / 2; offset > 0; offset >>= 1) {
490
+ __syncthreads();
491
+ if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) {
492
+ args_vec_t other = shared[config.shared_memory_offset(offset)];
493
+ #pragma unroll
494
+ for (int i = 0; i < output_vec_size; i++) {
495
+ value[i] = reducer::combine(value[i], other[i]);
496
+ }
497
+ shared[config.shared_memory_offset(0)] = value;
498
+ }
499
+ }
500
+ return value;
501
+ }
502
+ )ESCAPE";
503
+
504
+ const std::string reduction_template_1 = R"ESCAPE(
505
+
506
+ C10_DEVICE bool mark_block_finished() const {
507
+ __shared__ bool is_last_block_done_shared;
508
+
509
+ __syncthreads();
510
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
511
+ int prev_blocks_finished = atomicAdd(&semaphores[blockIdx.x], 1);
512
+ is_last_block_done_shared = (prev_blocks_finished == gridDim.y - 1);
513
+ }
514
+
515
+ __syncthreads();
516
+
517
+ return is_last_block_done_shared;
518
+ }
519
+
520
+ template <int output_vec_size>
521
+ C10_DEVICE Array<arg_t, output_vec_size> accumulate_in_output(
522
+ Array<out_scalar_t*, output_vec_size> out,
523
+ Array<arg_t, output_vec_size> value
524
+ ) const {
525
+ Array<arg_t, output_vec_size> ret;
526
+ #pragma unroll
527
+ for (int i = 0; i < output_vec_size; i++) {
528
+ ret[i] = reducer::combine(*(out[i]), value[i]);
529
+ }
530
+ return ret;
531
+ }
532
+
533
+
534
+ C10_DEVICE out_scalar_t get_accumulated_output(
535
+ out_scalar_t* out, arg_t value
536
+ ) const {
537
+ assert(!final_output);
538
+ return (out_scalar_t)value;
539
+ }
540
+
541
+ template<class T>
542
+ C10_DEVICE void set_results(const T x, const uint32_t base_offset) const {
543
+ assert(noutputs == 1);
544
+ auto res = (out_scalar_t*)((char*)dst[0] + base_offset);
545
+ *res = x;
546
+ }
547
+
548
+ //TODO - multi-output reduction - we won't be able to use thrust::pair
549
+ //just explicitly specify typed output reads/writes
550
+ //Currently implemented for max of two outputs
551
+ // template<class T1, class T2>
552
+ // C10_DEVICE void set_results(const thrust::pair<T1, T2> x, const index_t base_offset) const {
553
+ // if (noutputs >= 1) {
554
+ // auto res0 = (T1*)((char*)dst[0] + base_offset);
555
+ // *res0 = x.first;
556
+ // }
557
+ // if (noutputs >= 2) {
558
+ // // base offset is computed assuming element size being sizeof(T1), so we need to make a
559
+ // // correction to obtain the correct base offset
560
+ // auto res1 = (T2*) ((char *) dst[1] + base_offset / sizeof(T1) * sizeof(T2));
561
+ // *res1 = x.second;
562
+ // }
563
+ // }
564
+
565
+ template <int output_vec_size>
566
+ C10_DEVICE void set_results_to_output(Array<arg_t, output_vec_size> value, Array<uint32_t, output_vec_size> base_offset) const {
567
+ assert(final_output);
568
+ #pragma unroll
569
+ for (int i = 0; i < output_vec_size; i++) {
570
+ set_results(reducer::project(value[i]), base_offset[i]);
571
+ }
572
+ }
573
+
574
+ template <int output_vec_size>
575
+ C10_DEVICE Array<arg_t, output_vec_size> global_reduce(Array<arg_t, output_vec_size> value, Array<arg_t, output_vec_size> *acc, char* shared_memory) const {
576
+ using arg_vec_t = Array<arg_t, output_vec_size>;
577
+ using out_ptr_vec_t = Array<out_scalar_t*, output_vec_size>;
578
+ using offset_vec_t = Array<uint32_t, output_vec_size>;
579
+
580
+ arg_vec_t* reduce_buffer = (arg_vec_t*)cta_buf;
581
+ uint32_t output_idx = config.output_idx<output_vec_size>();
582
+ offset_vec_t base_offsets;
583
+ out_ptr_vec_t out;
584
+
585
+ #pragma unroll
586
+ for (int i = 0; i < output_vec_size; i++) {
587
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
588
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
589
+ }
590
+
591
+ bool should_store = config.should_store(output_idx);
592
+ if (should_store) {
593
+ uint32_t offset = config.staging_memory_offset(blockIdx.y);
594
+ reduce_buffer[offset] = value;
595
+ }
596
+
597
+ __threadfence(); // make sure writes are globally visible
598
+ __syncthreads(); // if multiple warps in this block wrote to staging, make sure they're all done
599
+ bool is_last_block_done = mark_block_finished();
600
+
601
+ if (is_last_block_done) {
602
+ __threadfence(); //complete acquire pattern
603
+ value = ident;
604
+ if (config.should_block_x_reduce()) {
605
+ uint32_t input_offset = threadIdx.x + threadIdx.y * blockDim.x;
606
+ uint32_t step = blockDim.x * blockDim.y;
607
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
608
+ uint32_t idx = config.staging_memory_offset(input_offset);
609
+ arg_vec_t next = reduce_buffer[idx];
610
+ #pragma unroll
611
+ for (int i = 0; i < output_vec_size; i++) {
612
+ value[i] = reducer::combine(value[i], next[i]);
613
+ }
614
+ }
615
+ } else {
616
+ uint32_t input_offset = threadIdx.y;
617
+ uint32_t step = blockDim.y;
618
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
619
+ uint32_t idx = config.staging_memory_offset(input_offset);
620
+ arg_vec_t next = reduce_buffer[idx];
621
+ #pragma unroll
622
+ for (int i = 0; i < output_vec_size; i++) {
623
+ value[i] = reducer::combine(value[i], next[i]);
624
+ }
625
+ }
626
+ }
627
+ value = block_y_reduce(value, shared_memory);
628
+ if (config.should_block_x_reduce()) {
629
+ value = block_x_reduce<output_vec_size>(value, shared_memory);
630
+ }
631
+ if (should_store) {
632
+ if (accumulate) {
633
+ #pragma unroll
634
+ for (int i = 0; i < output_vec_size; i++) {
635
+ value[i] = reducer::translate_idx(value[i], base_idx);
636
+ }
637
+ }
638
+
639
+ if (acc == nullptr) {
640
+ if (accumulate) {
641
+ value = accumulate_in_output<output_vec_size>(out, value);
642
+ }
643
+ if (final_output) {
644
+ set_results_to_output<output_vec_size>(value, base_offsets);
645
+ } else {
646
+ #pragma unroll
647
+ for (int i = 0; i < output_vec_size; i++) {
648
+ *(out[i]) = get_accumulated_output(out[i], value[i]);
649
+ }
650
+ }
651
+ } else {
652
+ if (accumulate) {
653
+ #pragma unroll
654
+ for (int i = 0; i < output_vec_size; i++) {
655
+ value[i] = reducer::combine((*acc)[i], value[i]);
656
+ }
657
+ }
658
+ if (final_output) {
659
+ set_results_to_output<output_vec_size>(value, base_offsets);
660
+ } else {
661
+ *acc = value;
662
+ }
663
+ }
664
+ }
665
+ }
666
+
667
+ return value;
668
+ }
669
+ };
670
+
671
+ extern "C"
672
+ __launch_bounds__(${max_threads_lb}, 4)
673
+ __global__ void reduction_${name}_kernel(ReduceJitOp r){
674
+ r.run();
675
+ }
676
+ )ESCAPE";
677
+
678
+ const std::string reduction_template = reduction_template_0 + reduction_template_1;
679
+
680
+
681
+ const std::string &get_reduction_template() {
682
+ return reduction_template;
683
+ }
684
+
685
+ } // namespace at::cuda
686
+
687
+ #else
688
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
689
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/thread_constants.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/macros/Macros.h>
4
+
5
+ // Marks a lambda as executable on both the host and device. The __host__
6
+ // attribute is important so that we can access static type information from
7
+ // the host, even if the function is typically only executed on the device.
8
+ #ifndef GPU_LAMBDA
9
+ #define GPU_LAMBDA __host__ __device__
10
+ #endif
11
+
12
+ #if defined(USE_ROCM)
13
+ constexpr int num_threads() {
14
+ return 256;
15
+ }
16
+
17
+ constexpr int thread_work_size() { return 4; }
18
+ #else
19
+ constexpr uint32_t num_threads() {
20
+ return C10_WARP_SIZE * 4;
21
+ }
22
+
23
+ constexpr int thread_work_size() { return 8; }
24
+ #endif
25
+
26
+ constexpr int block_work_size() { return thread_work_size() * num_threads(); }
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/vol2col.cuh ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/cuda/detail/KernelUtils.h>
6
+ #include <ATen/cuda/detail/IndexUtils.cuh>
7
+ #include <ATen/cuda/detail/TensorInfo.cuh>
8
+
9
+ #include <c10/macros/Macros.h>
10
+
11
+ namespace at::native {
12
+
13
+ using namespace at::cuda::detail;
14
+
15
+ // Kernel for fast unfold+copy on volumes
16
+ template <typename T>
17
+ C10_LAUNCH_BOUNDS_1(1024)
18
+ __global__ void vol2col_kernel(
19
+ const int64_t n,
20
+ const T* data_vol,
21
+ const int depth,
22
+ const int height,
23
+ const int width,
24
+ const int ksize_t,
25
+ const int ksize_h,
26
+ const int ksize_w,
27
+ const int pad_t,
28
+ const int pad_h,
29
+ const int pad_w,
30
+ const int stride_t,
31
+ const int stride_h,
32
+ const int stride_w,
33
+ const int dilation_t,
34
+ const int dilation_h,
35
+ const int dilation_w,
36
+ const int depth_col,
37
+ const int height_col,
38
+ const int width_col,
39
+ T* data_col) {
40
+ CUDA_KERNEL_LOOP_TYPE(index, n, int64_t) {
41
+ auto w_out = index % width_col;
42
+ index /= width_col;
43
+ auto h_out = index % height_col;
44
+ index /= height_col;
45
+ auto t_out = index % depth_col;
46
+ auto channel_in = index / depth_col;
47
+ auto channel_out = channel_in * ksize_t * ksize_h * ksize_w;
48
+ auto t_in = t_out * stride_t - pad_t;
49
+ auto h_in = h_out * stride_h - pad_h;
50
+ auto w_in = w_out * stride_w - pad_w;
51
+ data_col +=
52
+ ((channel_out * depth_col + t_out) * height_col + h_out) * width_col +
53
+ w_out;
54
+ data_vol += ((channel_in * depth + t_in) * height + h_in) * width + w_in;
55
+ for (int i = 0; i < ksize_t; ++i) {
56
+ for (int j = 0; j < ksize_h; ++j) {
57
+ for (int k = 0; k < ksize_w; ++k) {
58
+ auto t = t_in + i * dilation_t;
59
+ auto h = h_in + j * dilation_h;
60
+ auto w = w_in + k * dilation_w;
61
+ *data_col = (t >= 0 && h >= 0 && w >= 0 && t < depth && h < height &&
62
+ w < width)
63
+ ? data_vol
64
+ [i * dilation_t * height * width + j * dilation_h * width +
65
+ k * dilation_w]
66
+ : static_cast<T>(0);
67
+ data_col += depth_col * height_col * width_col;
68
+ }
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ template <typename T>
75
+ void vol2col(
76
+ cudaStream_t stream,
77
+ const T* data_vol,
78
+ const int channels,
79
+ const int depth,
80
+ const int height,
81
+ const int width,
82
+ const int depth_col,
83
+ const int height_col,
84
+ const int width_col,
85
+ const int ksize_t,
86
+ const int ksize_h,
87
+ const int ksize_w,
88
+ const int pad_t,
89
+ const int pad_h,
90
+ const int pad_w,
91
+ const int stride_t,
92
+ const int stride_h,
93
+ const int stride_w,
94
+ const int dilation_t,
95
+ const int dilation_h,
96
+ const int dilation_w,
97
+ T* data_col) {
98
+ // We are going to launch channels * depth_col * height_col * width_col
99
+ // kernels, each kernel responsible for copying a single-channel grid.
100
+ // We cast an operand to int64 so that the product will not overflow
101
+ const auto num_kernels = static_cast<int64_t>(channels) * depth_col * height_col * width_col;
102
+ // Launch
103
+ vol2col_kernel<<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>>(
104
+ num_kernels,
105
+ data_vol,
106
+ depth,
107
+ height,
108
+ width,
109
+ ksize_t,
110
+ ksize_h,
111
+ ksize_w,
112
+ pad_t,
113
+ pad_h,
114
+ pad_w,
115
+ stride_t,
116
+ stride_h,
117
+ stride_w,
118
+ dilation_t,
119
+ dilation_h,
120
+ dilation_w,
121
+ depth_col,
122
+ height_col,
123
+ width_col,
124
+ data_col);
125
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
126
+ }
127
+
128
+ template <typename T, typename accT>
129
+ __global__ void vol2im_kernel(
130
+ const int64_t n,
131
+ const T* data_col,
132
+ const unsigned depth,
133
+ const unsigned height,
134
+ const unsigned width,
135
+ const unsigned channels,
136
+ const unsigned kernel_t,
137
+ const unsigned kernel_h,
138
+ const unsigned kernel_w,
139
+ const unsigned pad_t,
140
+ const unsigned pad_h,
141
+ const unsigned pad_w,
142
+ const unsigned stride_t,
143
+ const unsigned stride_h,
144
+ const unsigned stride_w,
145
+ const unsigned dilation_t,
146
+ const unsigned dilation_h,
147
+ const unsigned dilation_w,
148
+ const unsigned depth_col,
149
+ const unsigned height_col,
150
+ const unsigned width_col,
151
+ T* data_vol) {
152
+ CUDA_KERNEL_LOOP(index, n) {
153
+ accT val = static_cast<accT>(0);
154
+ const auto w_im = index % width + pad_w;
155
+ const auto h_im = (index / width) % height + pad_h;
156
+ const auto t_im = (index / width / height) % depth + pad_t;
157
+ const auto c_im = index / (width * height * depth);
158
+ auto kernel_extent_w = (kernel_w - 1) * dilation_w + 1;
159
+ auto kernel_extent_h = (kernel_h - 1) * dilation_h + 1;
160
+ auto kernel_extent_t = (kernel_t - 1) * dilation_t + 1;
161
+ // compute the start and end of the output
162
+ const auto w_col_start =
163
+ (w_im < kernel_extent_w) ? 0 : (w_im - kernel_extent_w) / stride_w + 1;
164
+ const auto w_col_end = std::min(w_im / stride_w + 1, width_col);
165
+ const auto h_col_start =
166
+ (h_im < kernel_extent_h) ? 0 : (h_im - kernel_extent_h) / stride_h + 1;
167
+ const auto h_col_end = std::min(h_im / stride_h + 1, height_col);
168
+ const auto t_col_start =
169
+ (t_im < kernel_extent_t) ? 0 : (t_im - kernel_extent_t) / stride_t + 1;
170
+ const auto t_col_end = std::min(t_im / stride_t + 1, depth_col);
171
+ // TODO: use LCM of stride and dilation to avoid unnecessary loops
172
+ for (unsigned t_col = t_col_start; t_col < t_col_end; t_col += 1) {
173
+ for (unsigned h_col = h_col_start; h_col < h_col_end; h_col += 1) {
174
+ for (unsigned w_col = w_col_start; w_col < w_col_end; w_col += 1) {
175
+ uint64_t t_k = (t_im - t_col * stride_t);
176
+ uint64_t h_k = (h_im - h_col * stride_h);
177
+ uint64_t w_k = (w_im - w_col * stride_w);
178
+ if (t_k % dilation_t == 0 && h_k % dilation_h == 0 &&
179
+ w_k % dilation_w == 0) {
180
+ t_k /= dilation_t;
181
+ h_k /= dilation_h;
182
+ w_k /= dilation_w;
183
+ const int64_t idx_k =
184
+ ((c_im * kernel_t + t_k) * kernel_h + h_k) * kernel_w + w_k;
185
+ const int64_t data_col_index =
186
+ ((idx_k * depth_col + t_col) *
187
+ height_col + h_col) *
188
+ width_col + w_col;
189
+ val += data_col[data_col_index];
190
+ }
191
+ }
192
+ }
193
+ }
194
+ data_vol[index] = static_cast<T>(val);
195
+ }
196
+ }
197
+
198
+ template <typename T, typename accT>
199
+ void col2vol(
200
+ cudaStream_t stream,
201
+ const T* data_col,
202
+ const int64_t channels,
203
+ const int64_t depth,
204
+ const int64_t height,
205
+ const int64_t width,
206
+ const int64_t output_depth,
207
+ const int64_t output_height,
208
+ const int64_t output_width,
209
+ const int64_t patch_t,
210
+ const int64_t patch_h,
211
+ const int64_t patch_w,
212
+ const int64_t pad_t,
213
+ const int64_t pad_h,
214
+ const int64_t pad_w,
215
+ const int64_t stride_t,
216
+ const int64_t stride_h,
217
+ const int64_t stride_w,
218
+ const int64_t dilation_t,
219
+ const int64_t dilation_h,
220
+ const int64_t dilation_w,
221
+ T* data_vol) {
222
+ const auto num_kernels = channels * depth * height * width;
223
+
224
+ auto check_fits_in_unsigned =
225
+ [](int64_t val, const char * name) {
226
+ constexpr auto umax = std::numeric_limits<unsigned>::max();
227
+ TORCH_CHECK(val >= 0 && val <= umax,
228
+ name, " must fit in a 32-bit unsigned value");
229
+ };
230
+ check_fits_in_unsigned(num_kernels, "input size");
231
+ check_fits_in_unsigned(
232
+ channels * patch_t * patch_h * patch_w, "channels x kernel size");
233
+
234
+ // To avoid involving atomic operations, we will launch one kernel per
235
+ // bottom dimension, and then in the kernel add up the top dimensions.
236
+ vol2im_kernel<T, accT>
237
+ <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>>(
238
+ num_kernels,
239
+ data_col,
240
+ depth,
241
+ height,
242
+ width,
243
+ channels,
244
+ patch_t,
245
+ patch_h,
246
+ patch_w,
247
+ pad_t,
248
+ pad_h,
249
+ pad_w,
250
+ stride_t,
251
+ stride_h,
252
+ stride_w,
253
+ dilation_t,
254
+ dilation_h,
255
+ dilation_w,
256
+ output_depth,
257
+ output_height,
258
+ output_width,
259
+ data_vol);
260
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
261
+ }
262
+
263
+ } // namespace at::native
264
+
265
+ #else
266
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
267
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_collection.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/hip/HIPBlas.h>
6
+
7
+ namespace at::native {
8
+ void bgemm_kernel_bf16bf16bf16_256_256x256x32_32x32_4x4_8x32x1_8x32x1_1x16x1x16_4_Intrawave_v4(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
9
+ void bgemm_kernel_bf16bf16bf16_256_256x256x32_32x32_4x4_16x16x1_16x16x1_1x16x1x16_4_Intrawave_v4(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
10
+ void bgemm_kernel_bf16bf16bf16_256_256x256x32_32x32_4x4_4x64x1_4x64x1_1x16x1x16_4_Intrawave_v3(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
11
+ void bgemm_kernel_bf16bf16bf16_256_256x256x32_32x32_4x4_4x64x1_4x64x1_1x16x1x16_4_Intrawave_v5(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
12
+ void bgemm_kernel_bf16bf16bf16_256_224x256x64_16x16_7x8_8x32x1_8x32x1_1x16x1x16_4_Intrawave_v3(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
13
+ void bgemm_kernel_bf16bf16bf16_256_256x224x64_16x16_8x7_8x32x1_8x32x1_1x32x1x8_4_Intrawave_v3(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
14
+ void bgemm_kernel_bf16bf16bf16_256_128x128x64_32x32_2x2_8x32x1_8x32x1_1x16x1x16_4_Intrawave_v3(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
15
+ void bgemm_kernel_bf16bf16bf16_256_128x128x64_32x32_2x2_8x32x1_8x32x1_1x16x1x16_4_Intrawave_v5(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
16
+ void bgemm_kernel_bf16bf16bf16_256_128x128x64_32x32_2x2_8x32x1_8x32x1_1x16x1x16_4_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
17
+ void bgemm_kernel_bf16bf16bf16_128_32x16x64_16x16_1x1_8x16x1_8x16x1_1x16x1x8_2_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
18
+ void bgemm_kernel_bf16bf16bf16_64_16x16x64_16x16_1x1_8x8x1_8x8x1_1x16x1x4_4_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
19
+ void bgemm_kernel_bf16bf16bf16_128_16x32x64_16x16_1x1_8x16x1_8x16x1_1x16x1x8_4_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
20
+ void bgemm_kernel_bf16bf16bf16_128_16x32x64_16x16_1x1_16x8x1_16x8x1_1x16x1x8_4_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
21
+ void bgemm_kernel_bf16bf16bf16_128_16x32x64_16x16_1x1_32x4x1_32x4x1_1x16x1x8_4_Intrawave_v1(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
22
+ void bgemm_kernel_bf16bf16bf16_256_256x16x64_16x16_4x1_8x32x1_8x16x1_1x32x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
23
+ void bgemm_kernel_bf16bf16bf16_256_256x16x64_16x16_4x1_16x16x1_16x8x1_1x32x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
24
+ void bgemm_kernel_bf16bf16bf16_256_256x16x64_16x16_4x1_32x8x1_32x4x1_1x32x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
25
+ void bgemm_kernel_bf16bf16bf16_128_128x16x64_16x16_4x1_8x16x1_8x16x1_1x16x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
26
+ void bgemm_kernel_bf16bf16bf16_128_64x16x64_16x16_2x1_8x16x1_8x16x1_1x16x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
27
+ void bgemm_kernel_bf16bf16bf16_128_32x16x64_16x16_1x1_8x16x1_8x16x1_1x16x1x8_2_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
28
+ void bgemm_kernel_bf16bf16bf16_64_16x16x64_16x16_1x1_8x8x1_8x8x1_1x16x1x4_4_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
29
+ void bgemm_kernel_bf16bf16bf16_128_16x32x64_16x16_1x1_8x16x1_8x16x1_1x16x1x8_4_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
30
+ void bgemm_kernel_bf16bf16bf16_128_16x64x64_16x16_1x2_8x16x1_8x16x1_1x16x1x8_4_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
31
+ void bgemm_kernel_bf16bf16bf16_128_16x128x64_16x16_1x4_8x16x1_8x16x1_1x16x1x8_4_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
32
+ void bgemm_kernel_bf16bf16bf16_256_16x256x64_16x16_1x4_8x16x1_8x16x1_1x16x1x16_4_Intrawave_v2(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
33
+
34
+ }; // namespace at::native
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_template.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #undef __HIP_NO_HALF_CONVERSIONS__
3
+
4
+
5
+ #include <ATen/OpMathType.h>
6
+ #include <ATen/hip/HIPBlas.h>
7
+ #include <ATen/native/hip/ck_types.h>
8
+ #include <c10/util/Exception.h>
9
+ #include <ck/ck.hpp>
10
+ #include <ck/tensor_operation/gpu/device/tensor_layout.hpp>
11
+ #include <ck/tensor_operation/gpu/device/gemm_specialization.hpp>
12
+ #include <ck/tensor_operation/gpu/device/impl/device_batched_gemm_multiple_d_xdl_cshuffle_v3.hpp>
13
+ #include <ck/tensor_operation/gpu/element/element_wise_operation.hpp>
14
+
15
+ #include <ck/library/utility/check_err.hpp>
16
+ #include <ck/library/utility/device_memory.hpp>
17
+ #include <ck/library/utility/host_tensor.hpp>
18
+ #include <ck/library/utility/host_tensor_generator.hpp>
19
+ #include <ck/library/reference_tensor_operation/cpu/reference_batched_gemm.hpp>
20
+ #include <ck/library/utility/literals.hpp>
21
+
22
+ namespace at::native {
23
+
24
+ // Define commonly used types.
25
+ template <ck::index_t... Is>
26
+ using S = ck::Sequence<Is...>;
27
+
28
+ using BF16 = ck::bhalf_t;
29
+ using F32 = float;
30
+
31
+ using AccDataType = F32;
32
+ using DsDataType = ck::Tuple<>;
33
+ using CDataType = BF16;
34
+ using CShuffleDataType = BF16;
35
+ using DsLayout = ck::Tuple<>;
36
+ using CLayout = Row;
37
+
38
+ using PassThrough = ck::tensor_operation::element_wise::PassThrough;
39
+ using AElementOp = PassThrough;
40
+ using BElementOp = PassThrough;
41
+ using CDEElementOp = PassThrough;
42
+
43
+ using Row = ck::tensor_layout::gemm::RowMajor;
44
+ using Col = ck::tensor_layout::gemm::ColumnMajor;
45
+
46
+ template <
47
+ typename A_DATA_TYPE,
48
+ typename B_DATA_TYPE,
49
+ int BLOCK_SIZE,
50
+ int MBLOCK,
51
+ int NBLOCK,
52
+ int KBLOCK,
53
+ int AK1,
54
+ int BK1,
55
+ int WAVE_TILE_M,
56
+ int WAVE_TILE_N,
57
+ int WAVE_MAP_M,
58
+ int WAVE_MAP_N,
59
+ typename ABLOCK_TRANSFER,
60
+ int ABLOCK_TRANSFER_SSPV,
61
+ int ABLOCK_TRANSFER_DSPV_K1,
62
+ typename BBLOCK_TRANSFER,
63
+ int BBLOCK_TRANSFER_SSPV,
64
+ int BBLOCK_TRANSFER_SSPV_K1,
65
+ int CSHUFFLE_MXDL_PWPS,
66
+ int CSHUFFLE_NXDL_PWPS,
67
+ typename CSHUFFLEBLOCK_TRANSFER,
68
+ typename CDESHUFFLEBLOCK_TRANSFER,
69
+ ck::BlockGemmPipelineScheduler LOOP_SCHED,
70
+ ck::BlockGemmPipelineVersion PIPELINE_VERSION,
71
+ ck::tensor_operation::device::GemmSpecialization GEMM_SPEC =
72
+ ck::tensor_operation::device::GemmSpecialization::MNPadding,
73
+ bool TRANSA = false,
74
+ bool TRANSB = false>
75
+ void bgemm_kernel_impl(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)) {
76
+
77
+ using ADataType = typename CkMathType<A_DATA_TYPE>::dtype;
78
+ using BDataType = typename CkMathType<B_DATA_TYPE>::dtype;
79
+
80
+ using ALayout = typename CkTensorLayout<TRANSA, TRANSB>::a_layout;
81
+ using BLayout = typename CkTensorLayout<TRANSA, TRANSB>::b_layout;
82
+
83
+ auto a_element_op = AElementOp{};
84
+ auto b_element_op = BElementOp{};
85
+ auto cde_element_op = CDEElementOp{};
86
+
87
+ auto gemm = ck::tensor_operation::device::DeviceBatchedGemmMultiD_Xdl_CShuffle_V3<
88
+ ALayout, // ALayout
89
+ BLayout, // BLayout
90
+ DsLayout, // DsLayout
91
+ CLayout, // CLayout
92
+ ADataType, // ADataType
93
+ BDataType, // BDataType
94
+ DsDataType, // DsDataType
95
+ CDataType, // CDataType
96
+ AccDataType, // AccDataType
97
+ CShuffleDataType, // CshuffleType
98
+ AElementOp, // AElementwiseOperation
99
+ BElementOp, // BElementwiseOperation
100
+ CDEElementOp, // CElementwiseOperation
101
+ GEMM_SPEC, // GEMMSpecialization
102
+ BLOCK_SIZE, // BlockSize
103
+ MBLOCK, // MPerBlock
104
+ NBLOCK, // NPerBlock
105
+ KBLOCK, // KPerBlock
106
+ AK1, // AK1
107
+ BK1, // BK1
108
+ WAVE_TILE_M, // MPerXDL
109
+ WAVE_TILE_N, // NPerXDL
110
+ WAVE_MAP_M, // MXdlPerWave
111
+ WAVE_MAP_N, // NXdlPerWave
112
+ ABLOCK_TRANSFER, // ABlockTransferThreadClusterLengths_AK0_M_AK1
113
+ S<1, 0, 2>, // ABlockTransferThreadClusterArrangeOrder
114
+ S<1, 0, 2>, // ABlockTransferSrcAccessOrder
115
+ 2, // ABlockTransferSrcVectorDim
116
+ ABLOCK_TRANSFER_SSPV, // ABlockTransferSrcScalarPerVector
117
+ ABLOCK_TRANSFER_DSPV_K1, // ABlockTransferDstScalarPerVector_AK1
118
+ 0, // ABlockLdsExtraM
119
+ BBLOCK_TRANSFER, // BBlockTransferThreadClusterLengths_BK0_N_BK1
120
+ S<1, 0, 2>, // BBlockTransferThreadClusterArrangeOrder
121
+ S<1, 0, 2>, // BBlockTransferSrcAccessOrder
122
+ 2, // BBlockTransferSrcVectorDim
123
+ BBLOCK_TRANSFER_SSPV, // BBlockTransferSrcScalarPerVector
124
+ BBLOCK_TRANSFER_SSPV_K1, // BBlockTransferDstScalarPerVector_BK1
125
+ 0, // BBlockLdsAddExtraN
126
+ CSHUFFLE_MXDL_PWPS, // CShuffleMXdlPerWavePerShuffle
127
+ CSHUFFLE_NXDL_PWPS, // CShuffleNXdlPerWavePerShuffle
128
+ CSHUFFLEBLOCK_TRANSFER, // CShuffleBlockTransferClusterLengths_MBlock_MPerBlock_NBlock_NPerBlock
129
+ CDESHUFFLEBLOCK_TRANSFER, // CDEShuffleBlockTransferScalarPerVectors
130
+ LOOP_SCHED, // BlockGemmPipelineScheduler
131
+ PIPELINE_VERSION // BlockGemmPipelineVersion
132
+ >{};
133
+ auto invoker = gemm.MakeInvoker();
134
+ auto argument = gemm.MakeArgument(
135
+ b, // A and B are swapped for CK
136
+ a,
137
+ {},
138
+ c,
139
+ n,
140
+ m,
141
+ k,
142
+ num_batches,
143
+ ldb,
144
+ lda,
145
+ {},
146
+ ldc,
147
+ n * k, // batch_stride_a
148
+ m * k, // batch_stride_b
149
+ {},
150
+ m * n, // batch_stride_c
151
+ a_element_op,
152
+ b_element_op,
153
+ cde_element_op
154
+ );
155
+ TORCH_CHECK(gemm.IsSupportedArgument(argument), "wrong! device_gemm with the specified compilation parameters does not support this GEMM problem");
156
+ auto stream = at::cuda::getCurrentHIPStream().stream();
157
+ invoker.Run(argument, StreamConfig{stream, false});
158
+ }
159
+
160
+ }; // namespace at::native
161
+
162
+ #else
163
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
164
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_bgemm.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/hip/HIPBlas.h>
6
+
7
+ namespace at::native {
8
+
9
+ template <typename Dtype, typename C_Dtype = Dtype>
10
+ inline void bgemm_internal_ck(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) {
11
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas_bgemm_internal_ck: not implemented");
12
+ }
13
+
14
+ template <>
15
+ void bgemm_internal_ck<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
16
+
17
+ } // namespace at::native
18
+
19
+ #else
20
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
21
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_gemm.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/hip/HIPBlas.h>
6
+ namespace at::native {
7
+
8
+
9
+ template <typename Dtype>
10
+ inline void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
11
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas_gemm_internal_ck: not implemented");
12
+ }
13
+
14
+ #if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM)
15
+ template <>
16
+ void gemm_internal_ck<double>(CUDABLAS_GEMM_ARGTYPES(double));
17
+ template <>
18
+ void gemm_internal_ck<float>(CUDABLAS_GEMM_ARGTYPES(float));
19
+ template <>
20
+ void gemm_internal_ck<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
21
+ template <>
22
+ void gemm_internal_ck<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
23
+ #endif
24
+
25
+
26
+ } // namespace at::native
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_gemm_template.h ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /*
3
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ * All rights reserved.
5
+ *
6
+ * This source code is licensed under the BSD-style license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ */
9
+ #undef __HIP_NO_HALF_CONVERSIONS__
10
+ #include <cstdlib>
11
+ #include <initializer_list>
12
+ #include <numeric>
13
+
14
+ #include <ATen/ATen.h>
15
+ #include <ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h>
16
+ #include <ATen/native/hip/ck_gemm.h>
17
+ #include <ATen/native/hip/ck_types.h>
18
+ #include <c10/util/Exception.h>
19
+ #include <ck/ck.hpp>
20
+ #include <ck/tensor_operation/gpu/device/gemm_specialization.hpp>
21
+ #include <ck/tensor_operation/gpu/device/tensor_layout.hpp>
22
+ #include <ck/tensor_operation/gpu/element/element_wise_operation.hpp>
23
+ #include <ck/utility/data_type.hpp>
24
+
25
+ #include <ck/library/reference_tensor_operation/cpu/reference_gemm.hpp>
26
+ #include <ck/library/utility/check_err.hpp>
27
+ #include <ck/library/utility/device_memory.hpp>
28
+ #include <ck/library/utility/fill.hpp>
29
+ #include <ck/library/utility/host_tensor.hpp>
30
+ #include <ck/library/utility/host_tensor_generator.hpp>
31
+ #include <ck/library/utility/literals.hpp>
32
+
33
+ #include <ck/tensor_operation/gpu/device/impl/device_gemm_multiple_d_xdl_cshuffle_v3.hpp>
34
+ #include <ck/tensor_operation/gpu/device/impl/device_gemm_wmma.hpp>
35
+
36
+ // Define commonly used types.
37
+ template <ck::index_t... Is>
38
+ using S = ck::Sequence<Is...>;
39
+
40
+ using Row = ck::tensor_layout::gemm::RowMajor;
41
+ using Col = ck::tensor_layout::gemm::ColumnMajor;
42
+ using PassThrough = ck::tensor_operation::element_wise::PassThrough;
43
+
44
+ namespace at::native {
45
+
46
+ // Elementwise Operators
47
+ struct AlphaBetaAdd
48
+ {
49
+ AlphaBetaAdd(float alpha, float beta) : alpha_(alpha), beta_(beta){};
50
+
51
+ template <typename C, typename AB>
52
+ __host__ __device__ constexpr void operator()(C& c, const AB& ab) const;
53
+
54
+ template<>
55
+ __host__ __device__ constexpr void operator()<float, float>
56
+ (float& c, const float& ab) const
57
+ {
58
+ c = alpha_ * ab;
59
+ };
60
+
61
+ template<>
62
+ __host__ __device__ constexpr void operator()<ck::bhalf_t, ck::bhalf_t>
63
+ (ck::bhalf_t& c, const ck::bhalf_t& ab) const
64
+ {
65
+ c = alpha_ * ab;
66
+ };
67
+
68
+ template<>
69
+ __host__ __device__ constexpr void operator()<ck::half_t, ck::half_t>
70
+ (ck::half_t& c, const ck::half_t& ab) const
71
+ {
72
+ c = alpha_ * ab;
73
+ };
74
+
75
+ float alpha_;
76
+ // TODO: Leaving for now, will use later
77
+ float beta_;
78
+ };
79
+
80
+ template <
81
+ typename Dtype,
82
+ int BLOCK_SIZE,
83
+ int MBLOCK,
84
+ int NBLOCK,
85
+ int KBLOCK,
86
+ int AK1,
87
+ int BK1,
88
+ int MPER_XDL,
89
+ int NPER_XDL,
90
+ int MPER_WAVE,
91
+ int NPER_WAVE,
92
+ typename ABLOCK_CLUSTER_LENS,
93
+ typename ABLOCK_CLUSTER_ORDER,
94
+ typename ABLOCK_SRC_ORDER,
95
+ int ABLOCK_VECTOR_DIM,
96
+ int ABLOCK_SCALAR_VEC,
97
+ int ABLOCK_SCALAR_VEC_AK1,
98
+ bool ABLOCK_LDS_EXTRAM,
99
+ typename BBLOCK_CLUSTER_LENS,
100
+ typename BBLOCK_CLUSTER_ORDER,
101
+ typename BBLOCK_SRC_ORDER,
102
+ int BBLOCK_VECTOR_DIM,
103
+ int BBLOCK_SCALAR_VEC,
104
+ int BBLOCK_SCALAR_VEC_AK1,
105
+ bool BBLOCK_LDS_EXTRAN,
106
+ int CMPER_WAVE,
107
+ int CNPER_WAVE,
108
+ typename BLOCK_CLUSTER_LENS,
109
+ typename CDE_SCALAR_VEC,
110
+ bool PADDING = false,
111
+ bool TRANSA = false,
112
+ bool TRANSB = false>
113
+ void gemm_impl(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
114
+ // Get input information.
115
+ int M = m;
116
+ int N = n;
117
+ int K = k;
118
+
119
+ int StrideA = lda;
120
+ int StrideB = ldb;
121
+ int StrideC = ldc;
122
+
123
+ int KBatch = 1;
124
+
125
+ float falpha = alpha;
126
+ float fbeta = beta;
127
+
128
+ using ADataType = typename CkMathType<Dtype>::dtype;
129
+ using BDataType = typename CkMathType<Dtype>::dtype;
130
+ using CDataType = typename CkMathType<Dtype>::dtype;
131
+ using DDataType = typename CkMathType<Dtype>::dtype;
132
+
133
+ using AccDataType = float;
134
+ using CShuffleDataType = typename CkMathType<Dtype>::dtype;
135
+
136
+ using ALayout = typename CkTensorLayout<TRANSA, TRANSB>::a_layout;
137
+ using BLayout = typename CkTensorLayout<TRANSA, TRANSB>::b_layout;
138
+
139
+ using DLayout = Row;
140
+ using CLayout = Row;
141
+
142
+ using AElementOp = PassThrough;
143
+ using BElementOp = PassThrough;
144
+ using CElementOp = AlphaBetaAdd;
145
+
146
+
147
+ static constexpr auto GemmDefault =
148
+ ck::tensor_operation::device::GemmSpecialization::Default;
149
+ static constexpr auto GemmMNKPadding =
150
+ ck::tensor_operation::device::GemmSpecialization::MNKPadding;
151
+ static constexpr auto GemmSpec = PADDING ? GemmMNKPadding : GemmDefault;
152
+
153
+
154
+ using DeviceGemmInstance =
155
+ ck::tensor_operation::device::DeviceGemmMultiD_Xdl_CShuffle_V3<ALayout,
156
+ BLayout,
157
+ ck::Tuple<>,
158
+ CLayout,
159
+ ADataType,
160
+ BDataType,
161
+ ck::Tuple<>,
162
+ CDataType,
163
+ AccDataType,
164
+ CShuffleDataType,
165
+ AElementOp,
166
+ BElementOp,
167
+ CElementOp,
168
+ GemmSpec,
169
+ BLOCK_SIZE,
170
+ MBLOCK,
171
+ NBLOCK,
172
+ KBLOCK,
173
+ AK1,
174
+ BK1,
175
+ MPER_XDL,
176
+ NPER_XDL,
177
+ MPER_WAVE,
178
+ NPER_WAVE,
179
+ ABLOCK_CLUSTER_LENS,
180
+ ABLOCK_CLUSTER_ORDER,
181
+ ABLOCK_SRC_ORDER,
182
+ ABLOCK_VECTOR_DIM,
183
+ ABLOCK_SCALAR_VEC,
184
+ ABLOCK_SCALAR_VEC_AK1,
185
+ ABLOCK_LDS_EXTRAM,
186
+ BBLOCK_CLUSTER_LENS,
187
+ BBLOCK_CLUSTER_ORDER,
188
+ BBLOCK_SRC_ORDER,
189
+ BBLOCK_VECTOR_DIM,
190
+ BBLOCK_SCALAR_VEC,
191
+ BBLOCK_SCALAR_VEC_AK1,
192
+ BBLOCK_LDS_EXTRAN,
193
+ CMPER_WAVE,
194
+ CNPER_WAVE,
195
+ BLOCK_CLUSTER_LENS,
196
+ CDE_SCALAR_VEC>;
197
+
198
+
199
+ auto gemm = DeviceGemmInstance{};
200
+ auto invoker = gemm.MakeInvoker();
201
+
202
+ auto a_element_op = AElementOp{};
203
+ auto b_element_op = BElementOp{};
204
+ auto c_element_op = CElementOp{alpha, beta};
205
+
206
+
207
+ using DDataArrayType = std::array<const void*, 0>;
208
+ DDataArrayType DDataArray;
209
+
210
+ // We swap A and B inputs here as a temporary workaround
211
+ auto argument = gemm.MakeArgument(
212
+ reinterpret_cast<const void*>(b),
213
+ reinterpret_cast<const void*>(a),
214
+ DDataArray,
215
+ reinterpret_cast<void*>(c),
216
+ N,
217
+ M,
218
+ K,
219
+ StrideB,
220
+ StrideA,
221
+ std::array<ck::index_t, 0>{},
222
+ StrideC,
223
+ KBatch,
224
+ a_element_op,
225
+ b_element_op,
226
+ c_element_op);
227
+
228
+
229
+ TORCH_CHECK(gemm.IsSupportedArgument(argument), "wrong! device_gemm with the specified compilation parameters does not support this GEMM problem");
230
+
231
+
232
+ auto stream = at::cuda::getCurrentHIPStream().stream();
233
+ invoker.Run(argument, StreamConfig{stream, false});
234
+ }
235
+
236
+
237
+ template <
238
+ typename Dtype,
239
+ int BLOCK_SIZE,
240
+ int MBLOCK,
241
+ int NBLOCK,
242
+ int KBLOCK,
243
+ int K1,
244
+ int MPER_WMMA,
245
+ int NPER_WMMA,
246
+ int MPER_WAVE,
247
+ int NPER_WAVE,
248
+ typename ABLOCK_CLUSTER_LENS,
249
+ typename ABLOCK_CLUSTER_ORDER,
250
+ typename ABLOCK_SRC_ORDER,
251
+ int ABLOCK_VECTOR_DIM,
252
+ int ABLOCK_SCALAR_VEC,
253
+ int ABLOCK_SCALAR_VEC_K1,
254
+ bool ABLOCK_LDS_EXTRAM,
255
+ typename BBLOCK_CLUSTER_LENS,
256
+ typename BBLOCK_CLUSTER_ORDER,
257
+ typename BBLOCK_SRC_ORDER,
258
+ int BBLOCK_VECTOR_DIM,
259
+ int BBLOCK_SCALAR_VEC,
260
+ int BBLOCK_SCALAR_VEC_AK1,
261
+ bool BBLOCK_LDS_EXTRAN,
262
+ int CMPER_WAVE,
263
+ int CNPER_WAVE,
264
+ typename CBLOCK_CLUSTER_LENS,
265
+ int CNPER_BLOCK,
266
+ bool PADDING = false,
267
+ bool TRANSA = false,
268
+ bool TRANSB = false>
269
+ void gemm_impl_wmma(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
270
+ // Get input information.
271
+ int M = m;
272
+ int N = n;
273
+ int K = k;
274
+
275
+ int StrideA = lda;
276
+ int StrideB = ldb;
277
+ int StrideC = ldc;
278
+
279
+ int KBatch = 1;
280
+
281
+ float falpha = alpha;
282
+ float fbeta = beta;
283
+
284
+ using ADataType = typename CkMathType<Dtype>::dtype;
285
+ using BDataType = typename CkMathType<Dtype>::dtype;
286
+ using CDataType = typename CkMathType<Dtype>::dtype;
287
+ using DDataType = typename CkMathType<Dtype>::dtype;
288
+
289
+ using AccDataType = float;
290
+ using CShuffleDataType = typename CkMathType<Dtype>::dtype;
291
+
292
+ using ALayout = typename CkTensorLayout<TRANSA, TRANSB>::a_layout;
293
+ using BLayout = typename CkTensorLayout<TRANSA, TRANSB>::b_layout;
294
+
295
+ using DLayout = Row;
296
+ using CLayout = Row;
297
+
298
+ using AElementOp = PassThrough;
299
+ using BElementOp = PassThrough;
300
+ using CElementOp = PassThrough;
301
+
302
+
303
+ static constexpr auto GemmDefault =
304
+ ck::tensor_operation::device::GemmSpecialization::Default;
305
+ static constexpr auto GemmMNKPadding =
306
+ ck::tensor_operation::device::GemmSpecialization::MNKPadding;
307
+ static constexpr auto GemmSpec = PADDING ? GemmMNKPadding : GemmDefault;
308
+
309
+
310
+ using DeviceGemmInstance =
311
+ ck::tensor_operation::device::DeviceGemmWmma_CShuffle<ALayout,
312
+ BLayout,
313
+ CLayout,
314
+ ADataType,
315
+ BDataType,
316
+ CDataType,
317
+ AccDataType,
318
+ CShuffleDataType,
319
+ AElementOp,
320
+ BElementOp,
321
+ CElementOp,
322
+ GemmSpec,
323
+ 1, // NumPrefetch
324
+ BLOCK_SIZE,
325
+ MBLOCK,
326
+ NBLOCK,
327
+ KBLOCK,
328
+ K1,
329
+ MPER_WMMA,
330
+ NPER_WMMA,
331
+ MPER_WAVE,
332
+ NPER_WAVE,
333
+ ABLOCK_CLUSTER_LENS,
334
+ ABLOCK_CLUSTER_ORDER,
335
+ ABLOCK_SRC_ORDER,
336
+ ABLOCK_VECTOR_DIM,
337
+ ABLOCK_SCALAR_VEC,
338
+ ABLOCK_SCALAR_VEC_K1,
339
+ ABLOCK_LDS_EXTRAM,
340
+ BBLOCK_CLUSTER_LENS,
341
+ BBLOCK_CLUSTER_ORDER,
342
+ BBLOCK_SRC_ORDER,
343
+ BBLOCK_VECTOR_DIM,
344
+ BBLOCK_SCALAR_VEC,
345
+ BBLOCK_SCALAR_VEC_AK1,
346
+ BBLOCK_LDS_EXTRAN,
347
+ CMPER_WAVE,
348
+ CNPER_WAVE,
349
+ CBLOCK_CLUSTER_LENS,
350
+ CNPER_BLOCK>;
351
+
352
+ auto gemm = DeviceGemmInstance{};
353
+ auto invoker = gemm.MakeInvoker();
354
+
355
+ auto a_element_op = AElementOp{};
356
+ auto b_element_op = BElementOp{};
357
+ auto c_element_op = CElementOp{};
358
+
359
+
360
+ using DDataArrayType = std::array<const void*, 0>;
361
+ DDataArrayType DDataArray;
362
+
363
+ // We swap A and B inputs here as a temporary workaround
364
+ auto argument = gemm.MakeArgument(
365
+ reinterpret_cast<const ADataType*>(b),
366
+ reinterpret_cast<const BDataType*>(a),
367
+ reinterpret_cast<CDataType*>(c),
368
+ N,
369
+ M,
370
+ K,
371
+ StrideB,
372
+ StrideA,
373
+ StrideC,
374
+ b_element_op,
375
+ a_element_op,
376
+ c_element_op);
377
+
378
+
379
+ if(!gemm.IsSupportedArgument(argument))
380
+ {
381
+ printf("error shape = %ld %ld %ld TRANSA=%d TRANSB=%d \n",
382
+ n, m, k,TRANSA, TRANSB);
383
+ TORCH_CHECK(false, "wrong! device_gemm with the specified compilation parameters does not support this GEMM problem");
384
+ }
385
+
386
+
387
+ auto stream = at::cuda::getCurrentHIPStream().stream();
388
+ #if 1
389
+ invoker.Run(argument, StreamConfig{stream, false});
390
+ #else
391
+ float ave_time = invoker.Run(argument, StreamConfig{stream, true});
392
+ std::size_t flop = std::size_t(2) * M * N * K;
393
+
394
+ std::size_t num_btype =
395
+ sizeof(ADataType) * M * K + sizeof(BDataType) * K * N + sizeof(CDataType) * M * N;
396
+
397
+ float tflops = static_cast<float>(flop) / 1.E9 / ave_time;
398
+
399
+ float gb_per_sec = num_btype / 1.E6 / ave_time;
400
+
401
+ std::cout << "Perf: " << std::setw(10) << ave_time << " ms, " << tflops << " TFlops, "
402
+ << gb_per_sec << " GB/s, " << N <<" " <<M<<" " << k <<" "
403
+ << "stride: "<<StrideA <<" "<<StrideB <<" "<<StrideC <<" "
404
+ << gemm.GetTypeString()
405
+ << std::endl;
406
+ #endif
407
+ }
408
+
409
+ } // namespace at::native
410
+
411
+ #else
412
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
413
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_group_gemm.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/core/ScalarType.h>
6
+ #include <optional>
7
+
8
+ namespace at {
9
+ namespace hip {
10
+ namespace detail {
11
+ void group_gemm_ck(
12
+ const at::Tensor& mat_a,
13
+ const at::Tensor& mat_b,
14
+ const std::optional<at::Tensor>& offs,
15
+ const std::optional<at::Tensor>& bias,
16
+ at::Tensor& out);
17
+
18
+ } // namespace detail
19
+ } // namespace hip
20
+ } // namespace at
21
+
22
+ #else
23
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
24
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/hip/ck_types.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /*
3
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ * All rights reserved.
5
+ *
6
+ * This source code is licensed under the BSD-style license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ */
9
+
10
+ // work around CK assuming only a single FP8 interpretation at a time
11
+ #if(defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__)) && __HIP_DEVICE_COMPILE__
12
+ #define CK_USE_FNUZ_FP8 1
13
+ #undef CK_USE_OCP_FP8
14
+ #elif __HIP_DEVICE_COMPILE__
15
+ #undef CK_USE_FNUZ_FP8
16
+ #define CK_USE_OCP_FP8 1
17
+ #endif
18
+
19
+ #include <ATen/ATen.h>
20
+ #include <ck/ck.hpp>
21
+ #include <ck/tensor_operation/gpu/device/tensor_layout.hpp>
22
+ #include <ck/utility/data_type.hpp>
23
+
24
+ using Row = ck::tensor_layout::gemm::RowMajor;
25
+ using Col = ck::tensor_layout::gemm::ColumnMajor;
26
+
27
+ namespace at::native {
28
+
29
+ template <typename T>
30
+ struct CkMathType {
31
+ using dtype = T;
32
+ };
33
+
34
+ template <>
35
+ struct CkMathType<at::BFloat16> {
36
+ using dtype = ck::bhalf_t;
37
+ };
38
+
39
+ template <>
40
+ struct CkMathType<at::Half> {
41
+ using dtype = ck::half_t;
42
+ };
43
+
44
+ template <bool A, bool B>
45
+ struct CkTensorLayout {
46
+ // default goes to row-wise for now
47
+ using a_layout = Row;
48
+ using b_layout = Row;
49
+ };
50
+
51
+ // True denotes transpose is necessary. Default is Col, so return Row
52
+ template <>
53
+ struct CkTensorLayout<true, true> {
54
+ using a_layout = Col;
55
+ using b_layout = Col;
56
+ };
57
+
58
+ template <>
59
+ struct CkTensorLayout<true, false> {
60
+ using a_layout = Row;
61
+ using b_layout = Col;
62
+ };
63
+
64
+ template <>
65
+ struct CkTensorLayout<false, true> {
66
+ using a_layout = Col;
67
+ using b_layout = Row;
68
+ };
69
+
70
+ template <>
71
+ struct CkTensorLayout<false, false> {
72
+ using a_layout = Row;
73
+ using b_layout = Row;
74
+ };
75
+
76
+ } // namespace at::native
77
+
78
+ #else
79
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
80
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_kernels.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/Config.h>
4
+ #include <ATen/core/Tensor.h>
5
+ #if AT_KLEIDIAI_ENABLED()
6
+
7
+ namespace at::native::kleidiai {
8
+
9
+ /**
10
+ * @brief Rearranges the quantized weight to support kleidiai inference
11
+ * @param bl Groupsize for quantization should be multiple of 32
12
+ */
13
+ void kai_pack_int4_rhs(
14
+ const Tensor& weight_packed,
15
+ const Tensor& weight,
16
+ const Tensor& scales,
17
+ const std::optional<Tensor>& bias,
18
+ const int64_t n,
19
+ const int64_t k,
20
+ const int64_t bl);
21
+
22
+ /**
23
+ * @brief Outputs the buffer size for the packed weights
24
+ * @param bl Groupsize for quantization. 32 for groupwise , 0 for channelwise
25
+ */
26
+ size_t kai_pack_rhs_int4_size(
27
+ const int64_t n,
28
+ const int64_t k,
29
+ const int64_t bl,
30
+ at::ScalarType tensor_dtype = at::kFloat);
31
+
32
+ /**
33
+ * @brief Run 2 operations ( Input quantize and pack -> 4 bit Matmul )
34
+ */
35
+ void kai_quant_pack_lhs_int4_mm(
36
+ const Tensor& output,
37
+ const Tensor& input,
38
+ const Tensor& weight,
39
+ const int64_t m,
40
+ const int64_t n,
41
+ const int64_t k,
42
+ const int64_t bl);
43
+ } // namespace at::native::kleidiai
44
+ #endif
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/native/kleidiai/kai_pack.h ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/Config.h>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/ops/empty.h>
6
+ #include <torch/library.h>
7
+ #if AT_KLEIDIAI_ENABLED()
8
+
9
+ namespace at::native::kleidiai {
10
+
11
+ template <typename T>
12
+ void kai_pack_rhs_groupwise_int4(
13
+ T& kernel,
14
+ const Tensor& weight_packed,
15
+ const Tensor& weight,
16
+ const Tensor& scales,
17
+ const std::optional<Tensor>& bias,
18
+ const int64_t n,
19
+ const int64_t k,
20
+ const int64_t bl,
21
+ const int64_t rhs_stride,
22
+ const int64_t scale_stride) {
23
+ const auto& ukernel = kernel.ukernel;
24
+ const size_t nr = ukernel.get_nr();
25
+ const size_t kr = ukernel.get_kr();
26
+ const size_t sr = ukernel.get_sr();
27
+ auto weight_packed_data =
28
+ reinterpret_cast<uint8_t*>(weight_packed.data_ptr());
29
+ const auto weight_data = weight.data_ptr<uint8_t>();
30
+ auto scales_data = scales.const_data_ptr();
31
+
32
+ if (weight_data == nullptr) {
33
+ AT_ERROR("kai_pack_rhs_channelwise_int4: Weight data pointer is null");
34
+ }
35
+
36
+ if (scales_data == nullptr) {
37
+ AT_ERROR("kai_pack_rhs_channelwise_int4: Scales data pointer is null");
38
+ }
39
+
40
+ float* bias_ptr =
41
+ bias.has_value() ? bias.value().to(kFloat).data_ptr<float>() : NULL;
42
+ auto& params = kernel.rhs_pack_params;
43
+
44
+ kernel.kai_run_rhs_pack(
45
+ /*num_groups=*/1,
46
+ n,
47
+ k,
48
+ nr,
49
+ kr,
50
+ sr,
51
+ bl,
52
+ (const uint8_t*)(weight_data),
53
+ rhs_stride,
54
+ bias_ptr,
55
+ scales_data,
56
+ scale_stride,
57
+ weight_packed_data,
58
+ 0,
59
+ &params);
60
+ }
61
+
62
+ template <typename T>
63
+ void kai_pack_rhs_channelwise_int4(
64
+ T& kernel,
65
+ const Tensor& weight_packed,
66
+ const Tensor& weight,
67
+ const Tensor& scales,
68
+ const std::optional<Tensor>& bias,
69
+ const int64_t n,
70
+ const int64_t k) {
71
+ const auto& ukernel = kernel.ukernel;
72
+ const size_t nr = ukernel.get_nr();
73
+ const size_t kr = ukernel.get_kr();
74
+ const size_t sr = ukernel.get_sr();
75
+ auto weight_packed_data =
76
+ reinterpret_cast<uint8_t*>(weight_packed.data_ptr());
77
+ const auto weight_data = weight.data_ptr<uint8_t>();
78
+
79
+ const auto scales_data = scales.to(kFloat).data_ptr<float>();
80
+
81
+ if (weight_data == nullptr) {
82
+ AT_ERROR("kai_pack_rhs_channelwise_int4: Weight data pointer is null");
83
+ }
84
+
85
+ if (scales_data == nullptr) {
86
+ AT_ERROR("kai_pack_rhs_channelwise_int4: Scales data pointer is null");
87
+ }
88
+
89
+ float* bias_ptr =
90
+ bias.has_value() ? bias.value().to(kFloat).data_ptr<float>() : NULL;
91
+ auto& params = kernel.rhs_pack_params;
92
+
93
+ kernel.kai_run_rhs_pack(
94
+ /*num_groups=*/1,
95
+ n,
96
+ k,
97
+ nr,
98
+ kr,
99
+ sr,
100
+ (const uint8_t*)(weight_data),
101
+ (const float*)(bias_ptr),
102
+ (const float*)(scales_data),
103
+ weight_packed_data,
104
+ 0,
105
+ &params);
106
+ }
107
+
108
+ } // namespace at::native::kleidiai
109
+
110
+ #endif
111
+
112
+ #else
113
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
114
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_ukernel_interface.h ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/Config.h>
4
+ #if AT_KLEIDIAI_ENABLED()
5
+ #include <unordered_map>
6
+
7
+ #include <kai/kai_common.h>
8
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4c32p/kai_matmul_clamp_f32_qai8dxp1x8_qsi4c32p8x8_1x8x32_neon_dotprod.h>
9
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4c32p/kai_matmul_clamp_f32_qai8dxp4x8_qsi4c32p8x8_4x8x32_neon_i8mm.h>
10
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4c32p/kai_matmul_clamp_f32_qai8dxp_qsi4c32p_interface.h>
11
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/kai_matmul_clamp_f32_qai8dxp1x8_qsi4cxp8x8_1x8x32_neon_dotprod.h>
12
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm.h>
13
+ #include <kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi4cxp/kai_matmul_clamp_f32_qai8dxp_qsi4cxp_interface.h>
14
+ #include <kai/ukernels/matmul/matmul_clamp_bf16_qai8dxp_qsi4cxp/kai_matmul_clamp_bf16_qai8dxp1x8_qsi4cxp8x8_1x8_neon_dotprod.h>
15
+ #include <kai/ukernels/matmul/matmul_clamp_bf16_qai8dxp_qsi4cxp/kai_matmul_clamp_bf16_qai8dxp4x8_qsi4cxp8x8_8x8_neon_i8mm.h>
16
+ #include <kai/ukernels/matmul/matmul_clamp_bf16_qai8dxp_qsi4cxp/kai_matmul_clamp_bf16_qai8dxp_qsi4cxp_interface.h>
17
+ #include <kai/ukernels/matmul/pack/kai_lhs_quant_pack_qai8dxp_f32.h>
18
+ #include <kai/ukernels/matmul/pack/kai_lhs_quant_pack_qai8dxp_bf16_neon.h>
19
+ #include <kai/ukernels/matmul/pack/kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0.h>
20
+ #include <kai/ukernels/matmul/pack/kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0.h>
21
+
22
+ namespace at::native::kleidiai {
23
+
24
+ enum class kai_kernel_id {
25
+ // FP32 inputs, 4-bit weights, FP32 output
26
+ matmul_clamp_f32_qai8dxp1x8_qsi4c32p8x8_1x8x32_neon_dotprod =
27
+ 0, // Groupwise 4-bit GEMV (per-group scales, NEON DOTPROD)
28
+ matmul_clamp_f32_qai8dxp4x8_qsi4c32p4x8_4x8x32_neon_i8mm =
29
+ 1, // Groupwise 4-bit GEMM (per-group scales, NEON I8MM)
30
+ matmul_clamp_f32_qai8dxp1x8_qsi4cxp8x8_1x8x32_neon_dotprod =
31
+ 2, // Channelwise 4-bit GEMV (per-channel scales, NEON DOTPROD)
32
+ matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm =
33
+ 3, // Channelwise 4-bit GEMM (per-channel scales, NEON I8MM)
34
+
35
+ // BF16 inputs, 4-bit weights, BF16 output
36
+ matmul_clamp_bf16_qai8dxp1x8_qsi4cxp8x8_1x8_neon_dotprod =
37
+ 4, // Channelwise 4-bit GEMV with BF16 input/output
38
+ matmul_clamp_bf16_qai8dxp4x8_qsi4cxp8x8_8x8_neon_i8mm =
39
+ 5 // Channelwise 4-bit GEMM with BF16 input/output
40
+ };
41
+
42
+ // Channelwise Kernel mapping
43
+ struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp {
44
+ struct kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel ukernel;
45
+ struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params rhs_pack_params;
46
+ size_t (*kai_get_lhs_packed_size)(
47
+ size_t m,
48
+ size_t k,
49
+ size_t mr,
50
+ size_t kr,
51
+ size_t sr);
52
+ size_t (*kai_get_rhs_packed_size)(
53
+ size_t n,
54
+ size_t k,
55
+ size_t nr,
56
+ size_t kr,
57
+ size_t sr);
58
+ void (*kai_run_lhs_quant_pack)(
59
+ size_t m,
60
+ size_t k,
61
+ size_t mr,
62
+ size_t kr,
63
+ size_t sr,
64
+ size_t m_idx_start,
65
+ const float* lhs,
66
+ size_t lhs_stride,
67
+ void* lhs_packed);
68
+ void (*kai_run_rhs_pack)(
69
+ size_t num_groups,
70
+ size_t n,
71
+ size_t k,
72
+ size_t nr,
73
+ size_t kr,
74
+ size_t sr,
75
+ const uint8_t* rhs,
76
+ const float* bias,
77
+ const float* scale,
78
+ void* rhs_packed,
79
+ size_t extra_bytes,
80
+ const struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params* params);
81
+ size_t(*kai_get_lhs_quant_pack_offset)(
82
+ size_t m_idx, size_t k, size_t mr, size_t kr, size_t sr
83
+ );
84
+
85
+ kai_matmul_ukernel_f32_qa8dxp_qs4cxp(
86
+ const kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel& kernel)
87
+ : ukernel(kernel),
88
+ kai_get_lhs_packed_size(
89
+ &kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32),
90
+ kai_get_rhs_packed_size(
91
+ &kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qs4cxs1s0),
92
+ kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32),
93
+ kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4cxp_qs4cxs1s0),
94
+ kai_get_lhs_quant_pack_offset(&kai_get_lhs_packed_offset_lhs_quant_pack_qai8dxp_f32){}
95
+ };
96
+
97
+ struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp
98
+ kai_select_channelwise_matmul_ukernel(const kai_kernel_id id);
99
+
100
+ // bf16 Channelwise Kernel mapping
101
+ struct kai_matmul_ukernel_bf16_qa8dxp_qs4cxp {
102
+ struct kai_matmul_clamp_bf16_qai8dxp_qsi4cxp_ukernel ukernel;
103
+ struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params rhs_pack_params;
104
+ size_t (*kai_get_lhs_packed_size)(
105
+ size_t m,
106
+ size_t k,
107
+ size_t mr,
108
+ size_t kr,
109
+ size_t sr);
110
+ size_t (*kai_get_rhs_packed_size)(
111
+ size_t n,
112
+ size_t k,
113
+ size_t nr,
114
+ size_t kr,
115
+ size_t sr);
116
+ void (*kai_run_lhs_quant_pack)(
117
+ size_t m,
118
+ size_t k,
119
+ size_t mr,
120
+ size_t kr,
121
+ size_t sr,
122
+ size_t m_idx_start,
123
+ const void* lhs,
124
+ size_t lhs_stride,
125
+ void* lhs_packed);
126
+ void (*kai_run_rhs_pack)(
127
+ size_t num_groups,
128
+ size_t n,
129
+ size_t k,
130
+ size_t nr,
131
+ size_t kr,
132
+ size_t sr,
133
+ const uint8_t* rhs,
134
+ const float* bias,
135
+ const float* scale,
136
+ void* rhs_packed,
137
+ size_t extra_bytes,
138
+ const struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params* params);
139
+ size_t(*kai_get_lhs_quant_pack_offset)(
140
+ size_t m_idx, size_t k, size_t mr, size_t kr, size_t sr
141
+ );
142
+
143
+ kai_matmul_ukernel_bf16_qa8dxp_qs4cxp(
144
+ const kai_matmul_clamp_bf16_qai8dxp_qsi4cxp_ukernel& kernel)
145
+ : ukernel(kernel),
146
+ kai_get_lhs_packed_size(
147
+ &kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_bf16_neon),
148
+ kai_get_rhs_packed_size(
149
+ &kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qs4cxs1s0),
150
+ kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_bf16_neon),
151
+ kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4cxp_qs4cxs1s0),
152
+ kai_get_lhs_quant_pack_offset(&kai_get_lhs_packed_offset_lhs_quant_pack_qai8dxp_bf16_neon){}
153
+ };
154
+
155
+ struct kai_matmul_ukernel_bf16_qa8dxp_qs4cxp
156
+ kai_select_bf16_channelwise_matmul_ukernel(const kai_kernel_id id);
157
+
158
+ // Groupwise Kernel mapping
159
+ struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p {
160
+ struct kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel ukernel;
161
+ struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params rhs_pack_params;
162
+ size_t (*kai_get_lhs_packed_size)(
163
+ size_t m,
164
+ size_t k,
165
+ size_t mr,
166
+ size_t kr,
167
+ size_t sr);
168
+ size_t (*kai_get_rhs_packed_size)(
169
+ size_t n,
170
+ size_t k,
171
+ size_t nr,
172
+ size_t kr,
173
+ size_t sr,
174
+ size_t bl,
175
+ enum kai_datatype scale_dt);
176
+ void (*kai_run_lhs_quant_pack)(
177
+ size_t m,
178
+ size_t k,
179
+ size_t mr,
180
+ size_t kr,
181
+ size_t sr,
182
+ size_t m_idx_start,
183
+ const float* lhs,
184
+ size_t lhs_stride,
185
+ void* lhs_packed);
186
+ void (*kai_run_rhs_pack)(
187
+ size_t num_groups,
188
+ size_t n,
189
+ size_t k,
190
+ size_t nr,
191
+ size_t kr,
192
+ size_t sr,
193
+ size_t bl,
194
+ const uint8_t* rhs,
195
+ size_t rhs_stride,
196
+ const float* bias,
197
+ const void* scale,
198
+ size_t scale_stride,
199
+ void* rhs_packed,
200
+ size_t extra_bytes,
201
+ const struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params* params);
202
+ size_t(*kai_get_lhs_quant_pack_offset)(
203
+ size_t m_idx, size_t k, size_t mr, size_t kr, size_t sr
204
+ );
205
+
206
+ kai_matmul_ukernel_f32_qa8dxp_qs4c32p(
207
+ const kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel& kernel)
208
+ : ukernel(kernel),
209
+ kai_get_lhs_packed_size(
210
+ &kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32),
211
+ kai_get_rhs_packed_size(
212
+ &kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0),
213
+ kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32),
214
+ kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0),
215
+ kai_get_lhs_quant_pack_offset(&kai_get_lhs_packed_offset_lhs_quant_pack_qai8dxp_f32) {}
216
+ };
217
+
218
+ struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p kai_select_groupwise_matmul_ukernel(
219
+ const kai_kernel_id id);
220
+
221
+ } // namespace at::native::kleidiai
222
+ #endif
223
+
224
+ #else
225
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
226
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/Conv.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+ #include <ATen/Tensor.h>
6
+ #include <ATen/core/List.h>
7
+
8
+ #if AT_MKLDNN_ENABLED()
9
+
10
+ namespace at::native::xpu {
11
+ C10_API Tensor convolution_pointwise(
12
+ const Tensor& input_t,
13
+ const Tensor& weight_t,
14
+ const std::optional<Tensor>& bias_opt,
15
+ IntArrayRef padding,
16
+ IntArrayRef stride,
17
+ IntArrayRef dilation,
18
+ int64_t groups,
19
+ std::string_view attr,
20
+ torch::List<std::optional<at::Scalar>> scalars,
21
+ std::optional<std::string_view> algorithm);
22
+
23
+ C10_API Tensor convolution_pointwise_binary(
24
+ const Tensor& input_t,
25
+ const Tensor& other_t,
26
+ const Tensor& weight_t,
27
+ const std::optional<Tensor>& bias_opt,
28
+ IntArrayRef padding,
29
+ IntArrayRef stride,
30
+ IntArrayRef dilation,
31
+ int64_t groups,
32
+ std::string_view binary_attr,
33
+ std::optional<at::Scalar> alpha,
34
+ std::optional<std::string_view> unary_attr,
35
+ torch::List<std::optional<at::Scalar>> unary_scalars,
36
+ std::optional<std::string_view> unary_algorithm);
37
+
38
+ C10_API Tensor& convolution_pointwise_binary_(
39
+ Tensor& other_t,
40
+ const Tensor& input_t,
41
+ const Tensor& weight_t,
42
+ const std::optional<Tensor>& bias_opt,
43
+ IntArrayRef padding,
44
+ IntArrayRef stride,
45
+ IntArrayRef dilation,
46
+ int64_t groups,
47
+ std::string_view binary_attr,
48
+ std::optional<at::Scalar> alpha,
49
+ std::optional<std::string_view> unary_attr,
50
+ torch::List<std::optional<at::Scalar>> unary_scalars,
51
+ std::optional<std::string_view> unary_algorithm);
52
+
53
+ } // namespace at::native::xpu
54
+
55
+ #endif // AT_MKLDNN_ENABLED()
56
+
57
+ #else
58
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
59
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/FusionUtils.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <detail/oneDNN.h>
4
+
5
+ //
6
+ // This header file provides utility functions for constructing and managing
7
+ // oneDNN attributes used in fusion operations on XPU devices. These utilities
8
+ // include functions for creating unary and binary post-operations attributes,
9
+ // as well as mapping string representations of operations to oneDNN attributes.
10
+ //
11
+
12
+ namespace at::native::xpu {
13
+ at::native::onednn::Attr& unary_attr_with_arg(
14
+ onednn::Attr& attr,
15
+ std::string_view unary,
16
+ torch::List<std::optional<at::Scalar>> scalars,
17
+ std::optional<std::string_view> algorithm);
18
+
19
+ at::native::onednn::Attr& string_to_unary_attr(
20
+ onednn::Attr& attr,
21
+ std::string_view unary);
22
+
23
+ at::native::onednn::Attr& construct_unary_attr(
24
+ onednn::Attr& attr,
25
+ std::string_view unary,
26
+ torch::List<std::optional<at::Scalar>> scalars,
27
+ std::optional<std::string_view> algorithm);
28
+
29
+ template <bool is_matmul = false>
30
+ onednn::Attr& construct_binary_attr(
31
+ onednn::Attr& attr,
32
+ std::string_view binary,
33
+ const Tensor& other) {
34
+ if (binary == "mul") {
35
+ attr.append_post_binary<is_matmul>(attr.kind_with_binary_mul, other);
36
+ } else if (binary == "sub") {
37
+ attr.append_post_binary<is_matmul>(attr.kind_with_binary_sub, other);
38
+ } else if (binary == "div") {
39
+ attr.append_post_binary<is_matmul>(attr.kind_with_binary_div, other);
40
+ } else if (binary == "add") {
41
+ attr.append_post_binary<is_matmul>(attr.kind_with_binary_add, other);
42
+ } else if (binary == "sum") {
43
+ attr.append_post_sum(1.f, 1.f, 0);
44
+ } else {
45
+ TORCH_CHECK(
46
+ binary == "none",
47
+ "Binary attr ",
48
+ binary,
49
+ "is not supported for conv/linear post binary fusion");
50
+ }
51
+ return attr;
52
+ }
53
+
54
+ } // namespace at::native::xpu
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/native/mkldnn/xpu/detail/Attr.h ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ATen.h>
5
+ #include <ATen/native/mkldnn/xpu/detail/Utils.h>
6
+ #include <ATen/native/mkldnn/xpu/detail/oneDNNContext.h>
7
+ #include <oneapi/dnnl/dnnl.hpp>
8
+ #include <oneapi/dnnl/dnnl_types.h>
9
+
10
+ namespace at::native::onednn {
11
+ /* oneDNN quantization usage:
12
+ https://oneapi-src.github.io/oneDNN/dev_guide_attributes_quantization.html#
13
+
14
+ src_fp32 = scale_src * (src_int8 - zero_point)
15
+ wei_fp32 = scale_wei * (wei_int8 - zero_point)
16
+ dst_fp32 = scale_dst * (dst_int8 - zero_point)
17
+ fp32 Convolution: dst_fp32 = src_fp32 * wei_fp32
18
+ Int8 Convolution: dst_fp32 = (src_int8 * wei_int8) * (scale_src * scale_wei)
19
+ Int8 Convolution: dst_int8 = 1 / scale_dst * dst_fp32;
20
+
21
+ Considering zero-point (asymmetric):
22
+ dst_fp32 = (src_int8 - src_zp) * src_sc * wei_int8 * wei_sc
23
+ dst_sc * (dst_int8 - dst_zp) = (src_int8 - src_zp) * wei_int8 * src_sc *
24
+ wei_sc
25
+ dst_int8 = (src_int8 - src_zp) * wei_int8 * src_sc * wei_sc / dst_sc +
26
+ dst_zp
27
+
28
+ considering bias:
29
+ fp32 Convolution: dst_fp32 = src_fp32 * wei_fp32 + bias
30
+ Int8 Convolution: dst_fp32 = (src_int8 * wei_int8) * (scale_src * scale_wei)
31
+ + bias Int8 Convolution: dst_fp32 = (src_int8 * wei_int8 + bias/(scale_src *
32
+ scale_wei)) * (scale_src * scale_wei) Int8 Convolution: dst_int8 = 1 /
33
+ scale_dst * dst_fp32;
34
+ */
35
+
36
+ /*
37
+ oneDNN postops usage:
38
+ Currently, oneDNN supports 5 kinds of post ops. More details can be referred
39
+ to oneDNN doc.
40
+ https://oneapi-src.github.io/oneDNN/dev_guide_attributes_post_ops.html#doxid-dev-guide-attributes-post-ops-1dev-guide-attributes-post-ops-eltwise
41
+
42
+ 0. without post ops
43
+ dst = Conv(src, wei) + bias;
44
+ dst_int8 = 1/q_scale * dst; q_scale is the op output quantization scale
45
+ fp32 API: Attr attr;
46
+ int8 API: Attr attr(q_scale);
47
+
48
+ 1. append eltwise post op
49
+ dst = elt_scale * Eltwise{conv_scale * [Conv(src, wei) + bias], alpha, beta}
50
+ dst_int8 = 1/q_scale * dst;
51
+ fp32 API:
52
+ Attr attr;
53
+ attr.append_post_eltwise(1.f, conv_scale, 0.f, kind_with_linear)
54
+ attr.append_post_eltwise(elt_scale, alpha, beta, eltwise_algorithm)
55
+ int8 API:
56
+ Attr attr(q_scale);
57
+ attr.append_post_eltwise(1.f, conv_scale, 0.f, kind_with_linear)
58
+ attr.append_post_eltwise(elt_scale, alpha, beta, eltwise_algorithm)
59
+
60
+ 2. append sum post op
61
+ dst = conv_scale * Conv(src, wei) + sum_scale * (dst - zp)
62
+ dst_int8 = 1/q_scale * dst;
63
+ fp32 API:
64
+ Attr attr;
65
+ attr.append_post_eltwise(1.f, conv_scale, 0.f, kind_with_linear)
66
+ attr.append_post_sum(sum_scale)
67
+ int8 API:
68
+ Attr attr(q_scale);
69
+ attr.append_post_eltwise(1.f, conv_scale, 0.f, kind_with_linear)
70
+ attr.append_post_sum(sum_scale)
71
+
72
+ 3. append binary post op
73
+ dst = Binary[Conv(src, wei)]
74
+
75
+ */
76
+ using kind_t = dnnl::primitive::kind;
77
+ struct PostOpParam {
78
+ // eltwise post op constructor
79
+ PostOpParam(
80
+ float scale,
81
+ float alpha,
82
+ float beta,
83
+ dnnl::algorithm algo,
84
+ kind_t kind)
85
+ : scale_(scale), alpha_(alpha), beta_(beta), algo_(algo), kind_(kind) {}
86
+ // sum post op constructor
87
+ PostOpParam(float scale, kind_t kind) : scale_(scale), kind_(kind) {}
88
+ // sum post op with zp
89
+ PostOpParam(float scale, int64_t zero_point, kind_t kind)
90
+ : scale_(scale), zero_point_(zero_point), kind_(kind) {}
91
+ // binary post op constructor
92
+ PostOpParam(
93
+ at::Tensor& binary,
94
+ dnnl::memory::desc& binary_md,
95
+ dnnl::memory::desc& expected_md,
96
+ dnnl::algorithm algo,
97
+ kind_t kind)
98
+ : binary_(binary),
99
+ meta_(binary_md),
100
+ expected_meta_(expected_md),
101
+ algo_(algo),
102
+ kind_(kind) {}
103
+ // prelu post op constructor
104
+ PostOpParam(int mask, kind_t kind) : mask_(mask), kind_(kind) {}
105
+
106
+ // post sum or binary with scale post op constructor
107
+ PostOpParam(
108
+ at::Tensor& binary,
109
+ float scale,
110
+ dnnl::algorithm algo,
111
+ kind_t kind)
112
+ : scale_(scale), binary_(binary), algo_(algo), kind_(kind) {}
113
+
114
+ // for int8 sum/eltwise
115
+ float scale_ = 1.0;
116
+ int64_t zero_point_ = 0;
117
+ // for eltwise
118
+ float alpha_ = 0.0;
119
+ float beta_ = 0.0;
120
+ // for binary
121
+ at::Tensor binary_ = at::Tensor();
122
+ at::Tensor expected_binary_ = at::Tensor();
123
+ void* binary_ptr_ = nullptr;
124
+ dnnl::memory::desc meta_ = dnnl::memory::desc();
125
+ dnnl::memory::desc expected_meta_ = dnnl::memory::desc();
126
+ // for prelu
127
+ int mask_ = 0;
128
+ // common
129
+ dnnl::algorithm algo_ = dnnl::algorithm::eltwise_relu;
130
+ kind_t kind_ = kind_t::eltwise;
131
+ };
132
+
133
+ class Attr {
134
+ public:
135
+ Attr() : q_scale_(1.f) {}
136
+ Attr(float q_scale, int64_t zp = 0) : q_scale_(q_scale), q_zero_point_(zp) {}
137
+
138
+ /***** eltwise *****/
139
+ dnnl::algorithm kind_with_relu = dnnl::algorithm::eltwise_relu;
140
+ dnnl::algorithm kind_with_sigmoid = dnnl::algorithm::eltwise_logistic;
141
+ dnnl::algorithm kind_with_gelu_tanh = dnnl::algorithm::eltwise_gelu_tanh;
142
+ dnnl::algorithm kind_with_gelu_erf = dnnl::algorithm::eltwise_gelu_erf;
143
+ dnnl::algorithm kind_with_mish = dnnl::algorithm::eltwise_mish;
144
+ dnnl::algorithm kind_with_linear = dnnl::algorithm::eltwise_linear;
145
+ dnnl::algorithm kind_with_swish = dnnl::algorithm::eltwise_swish;
146
+ dnnl::algorithm kind_with_sqrt = dnnl::algorithm::eltwise_sqrt;
147
+ dnnl::algorithm kind_with_tanh = dnnl::algorithm::eltwise_tanh;
148
+ dnnl::algorithm kind_with_square = dnnl::algorithm::eltwise_square;
149
+ dnnl::algorithm kind_with_abs = dnnl::algorithm::eltwise_abs;
150
+ dnnl::algorithm kind_with_exp = dnnl::algorithm::eltwise_exp;
151
+ dnnl::algorithm kind_with_log = dnnl::algorithm::eltwise_log;
152
+ dnnl::algorithm kind_with_round = dnnl::algorithm::eltwise_round;
153
+ dnnl::algorithm kind_with_hardswish = dnnl::algorithm::eltwise_hardswish;
154
+ dnnl::algorithm kind_with_soft_relu = dnnl::algorithm::eltwise_soft_relu;
155
+ dnnl::algorithm kind_with_elu = dnnl::algorithm::eltwise_elu;
156
+ dnnl::algorithm kind_with_pow = dnnl::algorithm::eltwise_pow;
157
+ dnnl::algorithm kind_with_clip = dnnl::algorithm::eltwise_clip;
158
+ // note: hardsigmoid seems oneDNN still not support
159
+ dnnl::algorithm kind_with_hardsigmoid = dnnl::algorithm::eltwise_hardsigmoid;
160
+
161
+ /***** binary *****/
162
+ dnnl::algorithm kind_with_binary_mul = dnnl::algorithm::binary_mul;
163
+ dnnl::algorithm kind_with_binary_add = dnnl::algorithm::binary_add;
164
+ dnnl::algorithm kind_with_binary_sub = dnnl::algorithm::binary_sub;
165
+ dnnl::algorithm kind_with_binary_div = dnnl::algorithm::binary_div;
166
+ dnnl::algorithm kind_with_binary_eq = dnnl::algorithm::binary_eq;
167
+ dnnl::algorithm kind_with_binary_ne = dnnl::algorithm::binary_ne;
168
+ dnnl::algorithm kind_with_binary_ge = dnnl::algorithm::binary_ge;
169
+ dnnl::algorithm kind_with_binary_gt = dnnl::algorithm::binary_gt;
170
+ dnnl::algorithm kind_with_binary_le = dnnl::algorithm::binary_le;
171
+ dnnl::algorithm kind_with_binary_lt = dnnl::algorithm::binary_lt;
172
+ dnnl::algorithm kind_with_binary_max = dnnl::algorithm::binary_max;
173
+ dnnl::algorithm kind_with_binary_min = dnnl::algorithm::binary_min;
174
+
175
+ // append sum post op
176
+ Attr& append_post_sum(
177
+ float sum_scale,
178
+ float sum_q_scale = 1.f,
179
+ int64_t zp = 0) {
180
+ ops_params_.push_back(
181
+ PostOpParam(/*scale_sum*/ sum_scale * sum_q_scale, zp, kind_t::sum));
182
+ return *this;
183
+ }
184
+
185
+ // append eltwise post op
186
+ Attr& append_post_eltwise(
187
+ float scale,
188
+ float alpha,
189
+ float beta,
190
+ dnnl::algorithm algo) {
191
+ ops_params_.push_back(
192
+ PostOpParam(scale, alpha, beta, algo, kind_t::eltwise));
193
+ return *this;
194
+ }
195
+
196
+ // append binary post op
197
+ template <bool is_matmul = false>
198
+ Attr& append_post_binary(dnnl::algorithm algo, const at::Tensor& binary) {
199
+ auto binary_ = binary.is_quantized() ? at::dequantize(binary) : binary;
200
+ bool binary_is_channels_last =
201
+ (binary_.suggest_memory_format() == at::MemoryFormat::ChannelsLast ||
202
+ binary_.suggest_memory_format() == at::MemoryFormat::ChannelsLast3d);
203
+
204
+ if constexpr (!is_matmul) {
205
+ binary_ = binary_is_channels_last ? binary_ : binary_.contiguous();
206
+ }
207
+ dnnl::memory::desc md = get_onednn_md(binary_);
208
+ auto expected_md = dnnl::memory::desc(
209
+ md.get_dims(), md.get_data_type(), dnnl::memory::format_tag::any);
210
+ if constexpr (is_matmul) {
211
+ ops_params_.push_back(PostOpParam(binary_, md, md, algo, kind_t::binary));
212
+ } else {
213
+ ops_params_.push_back(
214
+ PostOpParam(binary_, md, expected_md, algo, kind_t::binary));
215
+ }
216
+
217
+ return *this;
218
+ }
219
+
220
+ Attr& append_scale_binary(
221
+ dnnl::algorithm algo,
222
+ at::Tensor binary,
223
+ float scale,
224
+ float sum_q_scale = 1.f,
225
+ int64_t zp = 0) {
226
+ ops_params_.push_back(PostOpParam(
227
+ binary, /*scale_sum*/ scale * sum_q_scale, algo, kind_t::binary));
228
+ return *this;
229
+ }
230
+
231
+ // append bias with binary_add method (only used for QConv now)
232
+ Attr& append_bias(const at::Tensor& binary, const int ndimension) {
233
+ // In PyTorch, bias are in shape of [OC],
234
+ // we expand its shape according to Conv dimension
235
+ // Conv1d [OC, 1, 1], Conv2d [1, OC, 1, ,1], Conv3d [1, OC, 1, 1, 1]
236
+ at::Tensor binary_ = binary.contiguous();
237
+ dnnl::memory::desc binary_md;
238
+ switch (ndimension) {
239
+ case 1:
240
+ binary_md = dnnl::memory::desc(
241
+ {binary.size(0), 1, 1},
242
+ dnnl::memory::data_type::f32,
243
+ dnnl::memory::format_tag::abc);
244
+ break;
245
+ case 2:
246
+ binary_md = dnnl::memory::desc(
247
+ {1, binary.size(0), 1, 1},
248
+ dnnl::memory::data_type::f32,
249
+ dnnl::memory::format_tag::abcd);
250
+ break;
251
+ case 3:
252
+ binary_md = dnnl::memory::desc(
253
+ {1, binary.size(0), 1, 1, 1},
254
+ dnnl::memory::data_type::f32,
255
+ dnnl::memory::format_tag::abcde);
256
+ break;
257
+ default:
258
+ TORCH_INTERNAL_ASSERT(
259
+ 0, "XPU only supports append_bias for Conv1d, Conv2d and Conv3d.");
260
+ }
261
+ // In this case, expected_md = binary_md
262
+ ops_params_.push_back(PostOpParam(
263
+ binary_, binary_md, binary_md, kind_with_binary_add, kind_t::binary));
264
+ return *this;
265
+ }
266
+
267
+ // append prelu post op
268
+ Attr& append_post_prelu(int mask) {
269
+ ops_params_.push_back(PostOpParam(mask, kind_t::prelu));
270
+ return *this;
271
+ }
272
+
273
+ dnnl::post_ops extract_post_ops(const at::Tensor& dst) {
274
+ // this function is used to extract post ops params from the ops_params_
275
+ // and put them into onednn post ops
276
+ for (size_t i = 0; i < ops_params_.size(); ++i) {
277
+ kind_t kind = ops_params_[i].kind_;
278
+ switch (kind) {
279
+ case kind_t::eltwise: {
280
+ dnnl::algorithm algo = ops_params_[i].algo_;
281
+ float alpha = ops_params_[i].alpha_;
282
+ float beta = ops_params_[i].beta_;
283
+ dnnl_post_ops_.append_eltwise(algo, alpha, beta);
284
+ break;
285
+ }
286
+ case kind_t::sum: {
287
+ float scale = ops_params_[i].scale_;
288
+ int64_t zero_point = ops_params_[i].zero_point_;
289
+ // TODO [Asymmetric]:
290
+ // Post-sum zp for gpu is not supported currently
291
+ dnnl_post_ops_.append_sum(scale, zero_point);
292
+ break;
293
+ }
294
+ case kind_t::binary: {
295
+ dnnl::algorithm algo = ops_params_[i].algo_;
296
+ auto expected_md = ops_params_[i].expected_meta_;
297
+ // In this case user may create src1 memory descriptor with
298
+ // format_tag::any or set a specific tag. However, in later case if
299
+ // tags mismatch with dst, it would result in suboptimal performance.
300
+ // So here we use format_tag::any to make sure the fast can be
301
+ // selected.
302
+ // Thus we use expected_md (with format_any) here to create pd instead
303
+ // of original md
304
+ dnnl_post_ops_.append_binary(algo, expected_md);
305
+ break;
306
+ }
307
+ default:
308
+ break;
309
+ }
310
+ }
311
+
312
+ return dnnl_post_ops_;
313
+ }
314
+
315
+ bool with_sum() {
316
+ for (size_t i = 0; i < ops_params_.size(); ++i) {
317
+ if (ops_params_[i].kind_ == kind_t::sum) {
318
+ return true;
319
+ }
320
+ }
321
+ return false;
322
+ }
323
+
324
+ bool with_binary() {
325
+ for (size_t i = 0; i < ops_params_.size(); ++i) {
326
+ if (ops_params_[i].kind_ == kind_t::binary) {
327
+ return true;
328
+ }
329
+ }
330
+ return false;
331
+ }
332
+
333
+ void construct_post_binary(
334
+ dnnl::primitive_desc& pd,
335
+ std::unordered_map<int, dnnl::memory>& args) {
336
+ // This function is used to construct binary memory desc in binary post ops.
337
+ // According to oneDNN doc, the binary tensor can be in shape of
338
+ // [1, 1, 1, 1], tensor broadcast
339
+ // [1, C, 1, 1], channel broadcast
340
+ // [dst.shape], no broadcast and eltwise-wise binary operations on dst
341
+
342
+ auto& engine = GpuEngineManager::Instance().get_engine();
343
+ for (size_t i = 0; i < ops_params_.size(); ++i) {
344
+ kind_t kind = ops_params_[i].kind_;
345
+ if (kind == kind_t::binary) {
346
+ dnnl::memory binary_m;
347
+ auto binary = ops_params_[i].binary_;
348
+ auto md = ops_params_[i].meta_;
349
+ // query expected_md to achieve peak performance
350
+ auto expected_md = pd.query_md(
351
+ dnnl::query::exec_arg_md,
352
+ DNNL_ARG_ATTR_MULTIPLE_POST_OP(i) | DNNL_ARG_SRC_1);
353
+
354
+ binary_m = at::native::onednn::make_onednn_memory(
355
+ md, engine, binary.data_ptr());
356
+
357
+ args.insert(
358
+ {DNNL_ARG_ATTR_MULTIPLE_POST_OP(i) | DNNL_ARG_SRC_1, binary_m});
359
+ }
360
+ }
361
+ }
362
+
363
+ float q_scale_ = 1.0; // the scale used to quantize the fused result from fp32
364
+ // to int8, only works for int8 case
365
+ int64_t q_zero_point_ = 0;
366
+ std::vector<PostOpParam> ops_params_; // series of post ops
367
+ dnnl::post_ops dnnl_post_ops_;
368
+ };
369
+
370
+ static inline void construct_attr_for_unary(
371
+ const std::string_view& unary_post_op,
372
+ const torch::List<std::optional<at::Scalar>>& unary_post_op_args,
373
+ const std::string_view& unary_post_op_algorithm,
374
+ at::native::onednn::Attr& attr) {
375
+ if (unary_post_op == "relu") {
376
+ attr = attr.append_post_eltwise(
377
+ /* eltwise_scale */ 1.f,
378
+ /* alpha */ 0.f,
379
+ /* beta */ 0.f,
380
+ attr.kind_with_relu);
381
+ } else if (unary_post_op == "leaky_relu") {
382
+ auto alpha = unary_post_op_args[0].value().to<float>();
383
+ attr = attr.append_post_eltwise(1.0, alpha, 0.f, attr.kind_with_relu);
384
+ } else if (unary_post_op == "tanh") {
385
+ attr = attr.append_post_eltwise(1.0f, 0.0f, 0.0f, attr.kind_with_tanh);
386
+ } else if (unary_post_op == "gelu") {
387
+ auto post_algorithm = unary_post_op_algorithm == "none"
388
+ ? attr.kind_with_gelu_erf
389
+ : attr.kind_with_gelu_tanh;
390
+ attr = attr.append_post_eltwise(1.0f, 0.0f, 0.0f, post_algorithm);
391
+ } else if (unary_post_op == "hardtanh") {
392
+ auto alpha = unary_post_op_args[0].value().to<float>();
393
+ auto beta = unary_post_op_args[1].value().to<float>();
394
+ attr = attr.append_post_eltwise(1.0, alpha, beta, attr.kind_with_clip);
395
+ } else if (unary_post_op == "hardswish") {
396
+ attr = attr.append_post_eltwise(
397
+ 1.0f, 1.f / 6.f, 1.f / 2.f, attr.kind_with_hardswish);
398
+ } else if (unary_post_op == "swish") {
399
+ attr = attr.append_post_eltwise(1.0f, 1.0f, 0.0f, attr.kind_with_swish);
400
+ } else {
401
+ TORCH_CHECK(
402
+ unary_post_op == "none",
403
+ "onednn qlinear: unsupported unary post op",
404
+ unary_post_op);
405
+ }
406
+ }
407
+
408
+ static inline void construct_attr_by_post_op(
409
+ const std::string_view& binary_post_op,
410
+ double binary_alpha,
411
+ double input1_scale,
412
+ int64_t input1_zero_point,
413
+ std::optional<at::Tensor> accum,
414
+ const std::string_view& unary_post_op,
415
+ const torch::List<std::optional<at::Scalar>>& unary_post_op_args,
416
+ const std::string_view& unary_post_op_algorithm,
417
+ at::native::onednn::Attr& attr) {
418
+ bool is_none_post_op =
419
+ (binary_post_op == "none" && unary_post_op == "none"); // not post-ops
420
+ bool is_unary_post_op_only =
421
+ (binary_post_op == "none" && unary_post_op != "none"); // ex., conv + relu
422
+ bool is_valid_binary_combination =
423
+ (binary_post_op == "add" || binary_post_op == "sum") &&
424
+ (unary_post_op == "none" || unary_post_op == "relu");
425
+ TORCH_INTERNAL_ASSERT(
426
+ is_unary_post_op_only || is_none_post_op || is_valid_binary_combination,
427
+ "Please provide valid combination of unary post operators and binary post operators");
428
+
429
+ if (binary_post_op == "none") {
430
+ construct_attr_for_unary(
431
+ unary_post_op, unary_post_op_args, unary_post_op_algorithm, attr);
432
+ } else if (binary_post_op == "sum") {
433
+ if (unary_post_op == "none") {
434
+ if (input1_zero_point != 0)
435
+ attr = attr.append_post_eltwise(
436
+ /*scale*/ 1.f,
437
+ /*alpha*/ 1.f,
438
+ -input1_zero_point * input1_scale,
439
+ attr.kind_with_linear);
440
+ attr = attr.append_post_sum(1, input1_scale, /*input1_zero_point*/ 0);
441
+ } else if (unary_post_op == "relu") {
442
+ if (input1_zero_point != 0)
443
+ attr = attr.append_post_eltwise(
444
+ /*scale*/ 1.f,
445
+ /*alpha*/ 1.f,
446
+ -input1_zero_point * input1_scale,
447
+ attr.kind_with_linear);
448
+ attr = attr.append_post_sum(1, input1_scale, /*input1_zero_point*/ 0);
449
+ attr = attr.append_post_eltwise(
450
+ /* scale */ 1.f,
451
+ /* alpha */ 0.f,
452
+ /* beta */ 0.f,
453
+ attr.kind_with_relu);
454
+ }
455
+ } else if (binary_post_op == "add") {
456
+ TORCH_CHECK(accum.has_value());
457
+ attr = attr.append_post_binary(attr.kind_with_binary_add, accum.value());
458
+ if (unary_post_op == "relu") {
459
+ attr = attr.append_post_eltwise(1.f, 0.f, 0.f, attr.kind_with_relu);
460
+ }
461
+ }
462
+ }
463
+
464
+ } // namespace at::native::onednn
465
+
466
+ #else
467
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
468
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/DnnlExt.h ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ATen.h>
5
+
6
+ #include <ATen/native/mkldnn/xpu/detail/LRUCache.h>
7
+ #include <ATen/native/mkldnn/xpu/detail/Utils.h>
8
+ #include <ATen/native/mkldnn/xpu/detail/oneDNNContext.h>
9
+
10
+ #include <oneapi/dnnl/dnnl.h>
11
+ #include <oneapi/dnnl/dnnl.hpp>
12
+
13
+ namespace std {
14
+
15
+ template <>
16
+ struct hash<dnnl::memory::dims> {
17
+ size_t operator()(dnnl::memory::dims const& vec) const {
18
+ size_t seed = vec.size();
19
+ for (auto& i : vec) {
20
+ seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
21
+ }
22
+ return seed;
23
+ }
24
+ };
25
+
26
+ } // namespace std
27
+
28
+ using namespace dnnl;
29
+
30
+ namespace at::native::onednn {
31
+
32
+ class primitive_ext : public primitive {
33
+ static constexpr int max_args = 12;
34
+
35
+ public:
36
+ primitive_ext(const primitive& base) : primitive(base) {}
37
+ primitive_ext(primitive&& base) : primitive(std::move(base)) {}
38
+
39
+ /// Returns a memory descriptor.
40
+ ///
41
+ /// @note
42
+ /// There are also convenience methods
43
+ /// #dnnl::primitive_desc_base::src_desc(),
44
+ /// #dnnl::primitive_desc_base::dst_desc(), and others.
45
+ ///
46
+ /// @param what The kind of parameter to query; can be
47
+ /// #dnnl::query::src_md, #dnnl::query::dst_md, etc.
48
+ /// @param idx Index of the parameter. For example, convolution bias can
49
+ /// be queried with what = #dnnl::query::weights_md and idx = 1.
50
+ /// @returns The requested memory descriptor.
51
+ /// @returns A zero memory descriptor if the primitive does not have a
52
+ /// parameter of the specified kind or index.
53
+ const_dnnl_memory_desc_t query_md(query what, int idx = 0) const {
54
+ std::vector<query> valid_q{
55
+ query::src_md,
56
+ query::diff_src_md,
57
+ query::weights_md,
58
+ query::diff_weights_md,
59
+ query::dst_md,
60
+ query::diff_dst_md,
61
+ query::workspace_md,
62
+ query::scratchpad_md,
63
+ query::exec_arg_md};
64
+ if (!std::any_of(valid_q.cbegin(), valid_q.cend(), [=](query q) {
65
+ return what == q;
66
+ }))
67
+ DNNL_THROW_ERROR(
68
+ dnnl_invalid_arguments, "memory descriptor query is invalid");
69
+
70
+ const_dnnl_memory_desc_t cdesc = dnnl_primitive_desc_query_md(
71
+ this->get_primitive_desc(), dnnl::convert_to_c(what), idx);
72
+
73
+ return cdesc ? cdesc : nullptr;
74
+ }
75
+
76
+ /// Returns a source memory descriptor.
77
+ /// @param idx Source index.
78
+ /// @returns Source memory descriptor.
79
+ /// @returns A zero memory descriptor if the primitive does not have a
80
+ /// source parameter with index @p idx.
81
+ const_dnnl_memory_desc_t src_desc(int idx) const {
82
+ return query_md(query::src_md, idx);
83
+ }
84
+
85
+ /// Returns a destination memory descriptor.
86
+ /// @param idx Destination index.
87
+ /// @returns Destination memory descriptor.
88
+ /// @returns A zero memory descriptor if the primitive does not have a
89
+ /// destination parameter with index @p idx.
90
+ const_dnnl_memory_desc_t dst_desc(int idx) const {
91
+ return query_md(query::dst_md, idx);
92
+ }
93
+
94
+ /// Returns a weights memory descriptor.
95
+ /// @param idx Weights index.
96
+ /// @returns Weights memory descriptor.
97
+ /// @returns A zero memory descriptor if the primitive does not have a
98
+ /// weights parameter with index @p idx.
99
+ const_dnnl_memory_desc_t weights_desc(int idx) const {
100
+ return query_md(query::weights_md, idx);
101
+ }
102
+
103
+ /// Returns a diff source memory descriptor.
104
+ /// @param idx Diff source index.
105
+ /// @returns Diff source memory descriptor.
106
+ /// @returns A zero memory descriptor if the primitive does not have a
107
+ /// diff source parameter with index @p idx.
108
+ const_dnnl_memory_desc_t diff_src_desc(int idx) const {
109
+ return query_md(query::diff_src_md, idx);
110
+ }
111
+
112
+ /// Returns a diff destination memory descriptor.
113
+ /// @param idx Diff destination index.
114
+ /// @returns Diff destination memory descriptor.
115
+ /// @returns A zero memory descriptor if the primitive does not have a
116
+ /// diff destination parameter with index @p idx.
117
+ const_dnnl_memory_desc_t diff_dst_desc(int idx) const {
118
+ return query_md(query::diff_dst_md, idx);
119
+ }
120
+
121
+ /// Returns a diff weights memory descriptor.
122
+ /// @param idx Diff weights index.
123
+ /// @returns Diff weights memory descriptor.
124
+ /// @returns A zero memory descriptor if the primitive does not have a
125
+ /// diff weights parameter with index @p idx.
126
+ const_dnnl_memory_desc_t diff_weights_desc(int idx) const {
127
+ return query_md(query::diff_weights_md, idx);
128
+ }
129
+
130
+ const_dnnl_memory_desc_t exec_arg_desc(int idx) const {
131
+ return query_md(query::exec_arg_md, idx);
132
+ }
133
+
134
+ // Separate versions without the index argument for documentation
135
+ // purposes.
136
+
137
+ /// Returns a source memory descriptor.
138
+ /// @returns Source memory descriptor.
139
+ /// @returns A zero memory descriptor if the primitive does not have a
140
+ /// source parameter.
141
+ const_dnnl_memory_desc_t src_desc() const {
142
+ return src_desc(0);
143
+ }
144
+
145
+ /// Returns a destination memory descriptor.
146
+ /// @returns Destination memory descriptor.
147
+ /// @returns A zero memory descriptor if the primitive does not have a
148
+ /// destination parameter.
149
+ const_dnnl_memory_desc_t dst_desc() const {
150
+ return dst_desc(0);
151
+ }
152
+
153
+ /// Returns a weights memory descriptor.
154
+ /// @returns Weights memory descriptor.
155
+ /// @returns A zero memory descriptor if the primitive does not have a
156
+ /// weights parameter.
157
+ const_dnnl_memory_desc_t weights_desc() const {
158
+ return weights_desc(0);
159
+ }
160
+
161
+ /// Returns a diff source memory descriptor.
162
+ /// @returns Diff source memory descriptor.
163
+ /// @returns A zero memory descriptor if the primitive does not have a
164
+ /// diff source memory with.
165
+ const_dnnl_memory_desc_t diff_src_desc() const {
166
+ return diff_src_desc(0);
167
+ }
168
+
169
+ /// Returns a diff destination memory descriptor.
170
+ /// @returns Diff destination memory descriptor.
171
+ /// @returns A zero memory descriptor if the primitive does not have a
172
+ /// diff destination parameter.
173
+ const_dnnl_memory_desc_t diff_dst_desc() const {
174
+ return diff_dst_desc(0);
175
+ }
176
+
177
+ /// Returns a diff weights memory descriptor.
178
+ /// @returns Diff weights memory descriptor.
179
+ /// @returns A zero memory descriptor if the primitive does not have a
180
+ /// diff weights parameter.
181
+ const_dnnl_memory_desc_t diff_weights_desc() const {
182
+ return diff_weights_desc(0);
183
+ }
184
+
185
+ /// Returns the workspace memory descriptor.
186
+ /// @returns Workspace memory descriptor.
187
+ /// @returns A zero memory descriptor if the primitive does not require
188
+ /// workspace parameter.
189
+ const_dnnl_memory_desc_t workspace_desc() const {
190
+ return query_md(query::workspace_md, 0);
191
+ }
192
+
193
+ /// Returns the scratchpad memory descriptor.
194
+ /// @returns scratchpad memory descriptor.
195
+ /// @returns A zero memory descriptor if the primitive does not require
196
+ /// scratchpad parameter.
197
+ /// @sa @ref dev_guide_attributes_scratchpad
198
+ const_dnnl_memory_desc_t scratchpad_desc() const {
199
+ return query_md(query::scratchpad_md, 0);
200
+ }
201
+
202
+ inline memory make_memory(
203
+ const_dnnl_memory_desc_t md_t,
204
+ const engine& aengine,
205
+ void* handle = DNNL_MEMORY_ALLOCATE) const {
206
+ sycl_interop::memory_kind kind = dnnl::sycl_interop::memory_kind::usm;
207
+ dnnl_memory_t c_memory;
208
+ error::wrap_c_api(
209
+ dnnl_sycl_interop_memory_create(
210
+ &c_memory, md_t, aengine.get(), convert_to_c(kind), handle),
211
+ "could not create a memory");
212
+ return memory(c_memory);
213
+ }
214
+
215
+ memory make_src(const engine& aengine, void* handle = DNNL_MEMORY_ALLOCATE)
216
+ const {
217
+ return make_memory(src_desc(), aengine, handle);
218
+ }
219
+
220
+ memory make_weight(const engine& aengine, void* handle = DNNL_MEMORY_ALLOCATE)
221
+ const {
222
+ return make_memory(weights_desc(), aengine, handle);
223
+ }
224
+
225
+ memory make_bias(const engine& aengine, void* handle = DNNL_MEMORY_ALLOCATE)
226
+ const {
227
+ return make_memory(weights_desc(1), aengine, handle);
228
+ }
229
+
230
+ memory make_dst(const engine& aengine, void* handle = DNNL_MEMORY_ALLOCATE)
231
+ const {
232
+ return make_memory(dst_desc(), aengine, handle);
233
+ }
234
+
235
+ memory make_scratchpad(
236
+ const engine& aengine,
237
+ void* handle = DNNL_MEMORY_ALLOCATE) const {
238
+ return make_memory(scratchpad_desc(), aengine, handle);
239
+ }
240
+
241
+ size_t get_scratchpad_size() const {
242
+ return dnnl_memory_desc_get_size(scratchpad_desc());
243
+ }
244
+
245
+ memory make_args(int arg_class, const engine& aengine, void* handle) const {
246
+ switch (arg_class) {
247
+ case DNNL_ARG_SRC:
248
+ return make_src(aengine, handle);
249
+ case DNNL_ARG_WEIGHTS:
250
+ return make_weight(aengine, handle);
251
+ case DNNL_ARG_SCRATCHPAD:
252
+ return make_scratchpad(aengine, handle);
253
+ case DNNL_ARG_DST:
254
+ return make_dst(aengine, handle);
255
+ case DNNL_ARG_BIAS:
256
+ return make_bias(aengine, handle);
257
+ default:
258
+ TORCH_INTERNAL_ASSERT(
259
+ false, "unsupported argument class for primitive_ext");
260
+ }
261
+ }
262
+
263
+ template <typename M>
264
+ void set_attribute(int slot, int arg_class, void* handle, M constructor) {
265
+ if (mem_arg_cache[slot])
266
+ mem_arg_cache[slot].set_data_handle(handle);
267
+ else {
268
+ mem_arg_cache[slot] = constructor();
269
+ c_args[slot].arg = arg_class;
270
+ c_args[slot].memory = mem_arg_cache[slot].get();
271
+ }
272
+ }
273
+
274
+ sycl::event execute(
275
+ const stream& astream,
276
+ const engine& aengine,
277
+ std::vector<std::pair<int, void*>>&& handles,
278
+ int slot_off = 2) {
279
+ auto off = slot_off;
280
+ for (const auto& p : handles) {
281
+ auto& m_arg = mem_arg_cache[off];
282
+ if (m_arg)
283
+ m_arg.set_data_handle(p.second);
284
+ else {
285
+ m_arg = make_args(p.first, aengine, p.second);
286
+ c_args[off].arg = p.first;
287
+ c_args[off].memory = m_arg.get();
288
+ }
289
+ ++off;
290
+ }
291
+
292
+ sycl::event return_event;
293
+ std::vector<sycl::event> deps{};
294
+ error::wrap_c_api(
295
+ dnnl_sycl_interop_primitive_execute(
296
+ this->get(), astream.get(), off, c_args, &deps, &return_event),
297
+ "could not execute a primitive");
298
+ return return_event;
299
+ }
300
+
301
+ private:
302
+ memory mem_arg_cache[max_args];
303
+ dnnl_exec_arg_t c_args[max_args];
304
+ };
305
+
306
+ // Specifies the combined data types of input and weight tensors.
307
+ // For example, f32 means both input and weight are FP32,
308
+ // bf16_int4 means input is BF16 and weight is INT4.
309
+ enum class joint_dtypes_t { f32 = 0, f16, bf16, int8, f16_int4, bf16_int4 };
310
+
311
+ // Specifies the transposition state of input and weight tensors.
312
+ // Convention: first letter = input, second letter = weight.
313
+ // 'n' = not transposed, 't' = transposed.
314
+ // For example, 'nt' means input is not transposed, weight is transposed.
315
+ enum class trans_type_t { nn = 0, nt, tn, tt };
316
+
317
+ // Specifies the type and placement of bias in the computation.
318
+ // 'none' = no bias,
319
+ // 'scalar' = a single scalar bias applied to all elements,
320
+ // 'm' = per-row bias (typically matched to input rows),
321
+ // 'n' = per-column bias (typically matched to output channels),
322
+ // 'mn' = full bias matrix matching the output dimensions.
323
+ enum class bias_type_t { none = 0, scalar, m, n, mn };
324
+
325
+ template <typename T>
326
+ T concat(const T& t1, at::ScalarType d) {
327
+ T t;
328
+ t.insert(t.end(), t1.begin(), t1.end());
329
+ t.push_back((int64_t)d);
330
+
331
+ return t;
332
+ }
333
+
334
+ template <typename T>
335
+ T concat(const T& t1, bool b) {
336
+ T t;
337
+ t.insert(t.end(), t1.begin(), t1.end());
338
+ t.push_back(b);
339
+
340
+ return t;
341
+ }
342
+
343
+ template <typename T>
344
+ T concat(const T& t1, int b) {
345
+ T t;
346
+ t.insert(t.end(), t1.begin(), t1.end());
347
+ t.push_back(b);
348
+
349
+ return t;
350
+ }
351
+
352
+ template <typename T>
353
+ T concat(const T& t1, const T& t2) {
354
+ T t;
355
+ t.insert(t.end(), t1.begin(), t1.end());
356
+ t.insert(t.end(), t2.begin(), t2.end());
357
+
358
+ return t;
359
+ }
360
+
361
+ template <typename T1, typename T2, typename... Ts>
362
+ T1 concat(const T1& t1, const T2& t2, const Ts&... ts) {
363
+ return concat(concat(t1, t2), ts...);
364
+ }
365
+
366
+ template <joint_dtypes_t Ts>
367
+ struct onednn_types_mapper;
368
+
369
+ template <>
370
+ struct onednn_types_mapper<joint_dtypes_t::f16_int4> {
371
+ static inline std::tuple<dnnl::memory::data_type, dnnl::memory::data_type>
372
+ get() {
373
+ return std::make_tuple(
374
+ dnnl::memory::data_type::f16, dnnl::memory::data_type::u4);
375
+ }
376
+ };
377
+
378
+ template <>
379
+ struct onednn_types_mapper<joint_dtypes_t::bf16_int4> {
380
+ static inline std::tuple<dnnl::memory::data_type, dnnl::memory::data_type>
381
+ get() {
382
+ return std::make_tuple(
383
+ dnnl::memory::data_type::bf16, dnnl::memory::data_type::u4);
384
+ }
385
+ };
386
+
387
+ // TODO: bias types maybe not right
388
+ static inline dnnl::memory::dims get_bias_type(
389
+ bias_type_t b_dims,
390
+ const int m,
391
+ const int n) {
392
+ switch (b_dims) {
393
+ case bias_type_t::none:
394
+ return {0};
395
+ case bias_type_t::scalar:
396
+ return {1, 1};
397
+ case bias_type_t::m:
398
+ return {m, 1};
399
+ case bias_type_t::n:
400
+ return {1, n};
401
+ case bias_type_t::mn:
402
+ return {m, n};
403
+ default:
404
+ TORCH_INTERNAL_ASSERT(false, "unsupported bias type ...");
405
+ }
406
+ }
407
+
408
+ // TODO: use template specialization on struct
409
+ template <trans_type_t Tt>
410
+ inline void get_strides(
411
+ memory::dims& src_strides,
412
+ memory::dims& wei_strides,
413
+ memory::dims& dst_strides,
414
+ const int64_t lda,
415
+ const int64_t ldb,
416
+ const int64_t ldc) {}
417
+
418
+ template <>
419
+ inline void get_strides<trans_type_t::nt>(
420
+ memory::dims& src_strides,
421
+ memory::dims& wei_strides,
422
+ memory::dims& dst_strides,
423
+ const int64_t lda,
424
+ const int64_t ldb,
425
+ const int64_t ldc) {
426
+ src_strides = {lda, 1};
427
+ wei_strides = {1, ldb};
428
+ dst_strides = {ldc, 1};
429
+ }
430
+
431
+ using primitive_cache =
432
+ at::native::onednn::lru_cache<memory::dims, primitive_ext>;
433
+
434
+ template <trans_type_t Tt, joint_dtypes_t Ts, typename F>
435
+ struct matmul_primitive_cache_t {
436
+ static inline primitive_ext& get(
437
+ const int m,
438
+ const int n,
439
+ const int k,
440
+ const int64_t lda,
441
+ const int64_t ldb,
442
+ const int64_t ldc,
443
+ const bias_type_t
444
+ b_dims, // for shapeless bias, not put it into template parameter
445
+ const int device_id,
446
+ F f_attr,
447
+ const int64_t scale_group_size,
448
+ const int64_t zp_group_size) {
449
+ auto& cached = get_cache(device_id);
450
+ memory::dims src_strides, wei_strides, dst_strides;
451
+ get_strides<Tt>(src_strides, wei_strides, dst_strides, lda, ldb, ldc);
452
+ auto pri_key = at::native::onednn::concat(
453
+ src_strides,
454
+ wei_strides,
455
+ m,
456
+ n,
457
+ k,
458
+ int(b_dims),
459
+ int(scale_group_size),
460
+ int(zp_group_size));
461
+ auto iter = cached.find(pri_key);
462
+ if (iter == cached.end()) {
463
+ auto [src_dt, wei_dt] = onednn_types_mapper<Ts>::get();
464
+ auto bias_dims = get_bias_type(b_dims, m, n);
465
+
466
+ auto src_md = memory::desc({m, k}, src_dt, src_strides);
467
+ auto wei_md = memory::desc({k, n}, wei_dt, wei_strides);
468
+ auto dst_md = memory::desc({m, n}, src_dt, dst_strides);
469
+ auto bias_format = b_dims == bias_type_t::none
470
+ ? dnnl::memory::format_tag::undef
471
+ : dnnl::memory::format_tag::ab;
472
+ auto bias_md =
473
+ memory::desc(bias_dims, src_dt, bias_format); // {m, n} or {1, n}
474
+
475
+ primitive_attr pattr;
476
+ f_attr(pattr);
477
+
478
+ dnnl::matmul::primitive_desc matmul_pd;
479
+ auto aengine =
480
+ at::native::onednn::GpuEngineManager::Instance().get_engine(
481
+ device_id);
482
+ if (b_dims == bias_type_t::none) {
483
+ matmul_pd = dnnl::matmul::primitive_desc(
484
+ aengine, src_md, wei_md, dst_md, pattr);
485
+ } else {
486
+ matmul_pd = dnnl::matmul::primitive_desc(
487
+ aengine, src_md, wei_md, bias_md, dst_md, pattr);
488
+ }
489
+
490
+ return cached.insert({pri_key, primitive_ext(dnnl::matmul(matmul_pd))})
491
+ .first->second;
492
+ } else {
493
+ return iter->second;
494
+ }
495
+ }
496
+
497
+ private:
498
+ static constexpr int max_cache_capacity = 512;
499
+ // if default constructor of primitive cache could read the environment
500
+ // variable then it'll save a lot of trouble
501
+ static inline thread_local std::array<primitive_cache, 16> mappings;
502
+
503
+ // this won't be needed if primitive_cache have good default constructor
504
+ static inline primitive_cache& get_cache(const int device_id) {
505
+ auto& mapping = mappings[device_id];
506
+ if (mapping.max_size() == 0) {
507
+ mapping.resize(max_cache_capacity);
508
+ }
509
+ return mapping;
510
+ }
511
+ };
512
+
513
+ template <joint_dtypes_t Ts, typename F>
514
+ static inline primitive_ext& matmul_primitive_create_and_cache(
515
+ const trans_type_t Tt,
516
+ const bias_type_t b_dims,
517
+ const int m,
518
+ const int n,
519
+ const int k,
520
+ const int64_t lda,
521
+ const int64_t ldb,
522
+ const int64_t ldc,
523
+ const int device_id,
524
+ F attr,
525
+ const int64_t scale_group_size,
526
+ const int64_t zp_group_size) {
527
+ switch (Tt) {
528
+ case trans_type_t::nt:
529
+ return matmul_primitive_cache_t<trans_type_t::nt, Ts, F>::get(
530
+ m,
531
+ n,
532
+ k,
533
+ lda,
534
+ ldb,
535
+ ldc,
536
+ b_dims,
537
+ device_id,
538
+ attr,
539
+ scale_group_size,
540
+ zp_group_size);
541
+ default:
542
+ TORCH_INTERNAL_ASSERT(false, "unsupported trans type ...");
543
+ }
544
+ }
545
+
546
+ template <typename F>
547
+ static inline primitive_ext& matmul_primitive_create_and_cache(
548
+ const joint_dtypes_t Ts,
549
+ const trans_type_t Tt,
550
+ const bias_type_t b_dims,
551
+ const int m,
552
+ const int n,
553
+ const int k,
554
+ const int64_t lda,
555
+ const int64_t ldb, // is weight ldb necessary?
556
+ const int64_t ldc,
557
+ const int device_id,
558
+ F attr,
559
+ const int64_t scale_group_size = 0,
560
+ const int64_t zp_group_size = 0) {
561
+ switch (Ts) {
562
+ case joint_dtypes_t::f16_int4:
563
+ return matmul_primitive_create_and_cache<joint_dtypes_t::f16_int4, F>(
564
+ Tt,
565
+ b_dims,
566
+ m,
567
+ n,
568
+ k,
569
+ lda,
570
+ ldb,
571
+ ldc,
572
+ device_id,
573
+ attr,
574
+ scale_group_size,
575
+ zp_group_size);
576
+ case joint_dtypes_t::bf16_int4:
577
+ return matmul_primitive_create_and_cache<joint_dtypes_t::bf16_int4, F>(
578
+ Tt,
579
+ b_dims,
580
+ m,
581
+ n,
582
+ k,
583
+ lda,
584
+ ldb,
585
+ ldc,
586
+ device_id,
587
+ attr,
588
+ scale_group_size,
589
+ zp_group_size);
590
+ default:
591
+ TORCH_INTERNAL_ASSERT(false, "Only support int4 ...");
592
+ }
593
+ }
594
+
595
+ } // namespace at::native::onednn
596
+
597
+ #else
598
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
599
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/LRUCache.h ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <iterator>
5
+ #include <list>
6
+ #include <unordered_map>
7
+ #include <utility>
8
+
9
+ namespace at::native::onednn {
10
+
11
+ template <
12
+ class key_t,
13
+ class value_t,
14
+ template <typename...> class map_t = std::unordered_map>
15
+ class lru_cache {
16
+ public:
17
+ using value_type = std::pair<key_t, value_t>;
18
+ using list_type = std::list<value_type>;
19
+ using list_iter = typename list_type::iterator;
20
+ using map_type = map_t<key_t, list_iter>;
21
+ using const_list_iter = typename list_type::const_iterator;
22
+ using size_type = typename list_type::size_type;
23
+
24
+ explicit lru_cache(size_type capacity) : capacity_(capacity) {}
25
+ lru_cache() : capacity_(0) {}
26
+
27
+ [[nodiscard]] size_type size() const noexcept {
28
+ return map_.size();
29
+ }
30
+ [[nodiscard]] size_type max_size() const noexcept {
31
+ return capacity_;
32
+ }
33
+ [[nodiscard]] bool empty() const noexcept {
34
+ return vlist_.empty();
35
+ }
36
+
37
+ void resize(size_type new_capacity) {
38
+ capacity_ = new_capacity;
39
+ trim();
40
+ }
41
+
42
+ list_iter begin() noexcept {
43
+ return vlist_.begin();
44
+ }
45
+ const_list_iter begin() const noexcept {
46
+ return vlist_.begin();
47
+ }
48
+ list_iter end() noexcept {
49
+ return vlist_.end();
50
+ }
51
+ const_list_iter end() const noexcept {
52
+ return vlist_.end();
53
+ }
54
+
55
+ void clear() noexcept {
56
+ map_.clear();
57
+ vlist_.clear();
58
+ }
59
+
60
+ void swap(lru_cache& other) noexcept {
61
+ using std::swap;
62
+ swap(vlist_, other.vlist_);
63
+ swap(map_, other.map_);
64
+ swap(capacity_, other.capacity_);
65
+ }
66
+
67
+ list_iter find(const key_t& key) {
68
+ auto it = map_.find(key);
69
+ if (it == map_.end())
70
+ return end();
71
+ vlist_.splice(vlist_.begin(), vlist_, it->second);
72
+ return it->second;
73
+ }
74
+
75
+ std::pair<list_iter, bool> insert(const value_type& value) {
76
+ auto it = map_.find(value.first);
77
+ if (it != map_.end()) {
78
+ // Move existing to front
79
+ vlist_.splice(vlist_.begin(), vlist_, it->second);
80
+ return {it->second, false};
81
+ }
82
+
83
+ // Insert new at front
84
+ vlist_.emplace_front(value);
85
+ map_[value.first] = vlist_.begin();
86
+
87
+ trim();
88
+
89
+ return {vlist_.begin(), true};
90
+ }
91
+
92
+ list_iter erase(list_iter pos) {
93
+ map_.erase(pos->first);
94
+ return vlist_.erase(pos);
95
+ }
96
+
97
+ private:
98
+ void trim() {
99
+ while (map_.size() > capacity_) {
100
+ auto last = std::prev(vlist_.end());
101
+ map_.erase(last->first);
102
+ vlist_.pop_back();
103
+ }
104
+ }
105
+
106
+ list_type vlist_;
107
+ map_type map_;
108
+ size_type capacity_;
109
+ };
110
+
111
+ } // namespace at::native::onednn
112
+
113
+ #else
114
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
115
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/Utils.h ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/ATen.h>
4
+ #include <ATen/Tensor.h>
5
+ #include <ATen/core/Tensor.h>
6
+ #include <iostream>
7
+
8
+ #include <ATen/core/grad_mode.h>
9
+ #include <c10/core/MemoryFormat.h>
10
+ #include <oneapi/dnnl/dnnl.hpp>
11
+ #include <oneapi/dnnl/dnnl_graph.hpp>
12
+ #include <oneapi/dnnl/dnnl_graph_sycl.hpp>
13
+ #include <oneapi/dnnl/dnnl_sycl.hpp>
14
+ #include <oneapi/dnnl/dnnl_version.h>
15
+
16
+ #include <ATen/native/mkldnn/xpu/detail/oneDNNContext.h>
17
+
18
+ #define ONEDNN_SUPPORT_DETERMINISTIC \
19
+ (DNNL_VERSION_MAJOR >= 3 && DNNL_VERSION_MINOR >= 4)
20
+
21
+ namespace at::native::onednn {
22
+
23
+ dnnl::memory::format_tag get_dnnl_default_format(
24
+ int ndims,
25
+ bool is_channels_last = false,
26
+ bool allow_undef = false);
27
+
28
+ dnnl::memory::data_type get_onednn_dtype(
29
+ const at::Tensor& tensor,
30
+ bool allow_undef = false);
31
+
32
+ dnnl::memory::data_type get_onednn_dtype_include_double(
33
+ const at::Tensor& tensor,
34
+ bool allow_undef = false);
35
+
36
+ bool is_supported_onednn_dtype(const at::Tensor& tensor);
37
+
38
+ dnnl::memory::dims get_onednn_dims(const at::Tensor& tensor);
39
+
40
+ dnnl::memory::dims get_onednn_strides(const at::Tensor& tensor);
41
+ dnnl::memory::desc get_onednn_md(const at::Tensor& tensor);
42
+
43
+ bool onednn_strides_check(const at::Tensor& src);
44
+ bool is_broadcast(const at::Tensor& t);
45
+ void undo_broadcast_on_batch(at::Tensor& m1, at::Tensor& m2);
46
+ void undo_broadcast(at::Tensor& tensor);
47
+
48
+ bool is_onednn_matmul_strides(const at::Tensor& tensor);
49
+
50
+ bool is_broadcast_from_other_to_self(
51
+ const at::Tensor& self,
52
+ const at::Tensor& other);
53
+
54
+ at::MemoryFormat get_cl_tag_by_ndim(const int64_t ndim);
55
+
56
+ void apply_tf32_if_allowed(dnnl::primitive_attr& primitive_attr);
57
+
58
+ bool binary_valid(
59
+ const at::Tensor& self,
60
+ const at::Tensor& other,
61
+ bool is_fusion = false);
62
+
63
+ bool use_channels_last_for_conv(
64
+ const at::Tensor& src,
65
+ const at::Tensor& weight);
66
+
67
+ dnnl::memory::format_tag conv_src_fmt(
68
+ const int64_t ndim,
69
+ const bool is_channels_last = false);
70
+
71
+ dnnl::memory::dims compatible_weight_dims(
72
+ const int64_t ndim,
73
+ const int64_t groups,
74
+ const int64_t oc,
75
+ const int64_t ic,
76
+ const IntArrayRef wsizes);
77
+
78
+ dnnl::memory::format_tag conv_weight_fmt(
79
+ const int64_t ndim,
80
+ const bool grouped = false,
81
+ const bool is_channels_last = false);
82
+
83
+ template <typename Vec>
84
+ dnnl::memory::dims compatible_dilation(Vec&& dilation) {
85
+ dnnl::memory::dims ret = dilation.vec();
86
+ for (auto it = ret.begin(); it != ret.end(); it++) {
87
+ *it -= 1;
88
+ }
89
+ return ret;
90
+ }
91
+
92
+ inline std::vector<int64_t> padding_r(
93
+ IntArrayRef padding,
94
+ IntArrayRef output_padding) {
95
+ // ConvTranspose padding adjustment
96
+ //
97
+ // PyTorch uses padding/output_padding:
98
+ // osize = (isize - 1) * stride - 2 * padding + dilation * (kernel_size - 1)
99
+ // + output_padding + 1
100
+ //
101
+ // MKLDNN uses padding_l/padding_r:
102
+ // osize = (isize - 1) * stride - padding_l - padding_r + dilation *
103
+ // (kernel_size - 1) + 1
104
+ //
105
+ // So: padding_l = padding, padding_r = padding - output_padding
106
+ //
107
+ auto dim = padding.size();
108
+ std::vector<int64_t> pad_r(dim);
109
+ for (const auto d : c10::irange(dim)) {
110
+ pad_r[d] = padding[d] - output_padding[d];
111
+ }
112
+ return pad_r;
113
+ }
114
+
115
+ template <typename T>
116
+ dnnl::memory dnnl_memory_from_host_scalar(
117
+ T host_value,
118
+ Tensor& holder,
119
+ dnnl::engine& engine) {
120
+ auto options = at::TensorOptions()
121
+ .dtype(c10::CppTypeToScalarType<T>::value)
122
+ .device(kXPU);
123
+ holder = at::empty({1}, options).fill_(host_value);
124
+ dnnl::memory::desc md = get_onednn_md(holder);
125
+ dnnl::memory mem = make_onednn_memory(md, engine, holder.data_ptr());
126
+ return mem;
127
+ }
128
+
129
+ struct PartitionCache {
130
+ std::unordered_map<std::bitset<32>, dnnl::graph::partition> partition_map_{};
131
+
132
+ // The first 8 bits are reserved
133
+ // bit 0: is int8
134
+ // bit 1: is uint8
135
+ // bit 2: fp16(0) / bf16(1)
136
+ // bit 3: is fp32
137
+ // bit 4: is sdpa pattern
138
+ // bit 5: is sdpa backward pattern
139
+ // bit 6-7: reserved for future use
140
+ // The rest of the bits depend upon the arguments provided
141
+ // However, down the line, we might have different bitsets for different
142
+ // patterns
143
+ enum class BitType : uint8_t {
144
+ Int8 = 0,
145
+ Uint8 = 1,
146
+ Bfloat16 = 2,
147
+ Float32 = 3,
148
+ SdpaPattern = 4,
149
+ SdpaBwdPattern = 5
150
+ };
151
+
152
+ dnnl::graph::partition& insert_partition_cache(
153
+ std::bitset<32>& patternID,
154
+ dnnl::graph::partition& p) {
155
+ partition_map_[patternID] = std::move(p);
156
+ return partition_map_[patternID];
157
+ }
158
+ std::optional<std::reference_wrapper<dnnl::graph::partition>> find_partition(
159
+ std::bitset<32>& patternID) {
160
+ auto iter = partition_map_.find(patternID);
161
+ if (iter != partition_map_.end()) {
162
+ return iter->second;
163
+ }
164
+ return std::nullopt;
165
+ }
166
+ };
167
+
168
+ } // namespace at::native::onednn
169
+
170
+ #else
171
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
172
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/oneDNN.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ATen.h>
5
+ #include <ATen/BlasBackend.h>
6
+ #include <ATen/native/mkldnn/xpu/detail/Attr.h>
7
+ #include <ATen/native/mkldnn/xpu/detail/Utils.h>
8
+ #include <ATen/native/mkldnn/xpu/detail/oneDNNContext.h>
9
+
10
+ namespace at::native::onednn {
11
+
12
+ TORCH_API sycl::event matmul(
13
+ at::Tensor& result,
14
+ const at::Tensor& mat1,
15
+ const at::Tensor& mat2,
16
+ const at::Tensor& b_raw,
17
+ bool m2_trans,
18
+ Attr attr,
19
+ const std::vector<sycl::event>& deps = {});
20
+
21
+ TORCH_API sycl::event convolution(
22
+ at::Tensor& dst,
23
+ const at::Tensor& src,
24
+ const at::Tensor& weight,
25
+ const at::Tensor& bia,
26
+ IntArrayRef padding_front_top_left,
27
+ IntArrayRef padding_back_bottom_right,
28
+ IntArrayRef stride,
29
+ IntArrayRef dilation,
30
+ int64_t groups,
31
+ Attr& attr,
32
+ const std::vector<sycl::event>& deps = {});
33
+
34
+ TORCH_API sycl::event convolution_backward_weights(
35
+ at::Tensor& diff_weight,
36
+ at::Tensor& diff_bia,
37
+ const at::Tensor& diff_dst,
38
+ const at::Tensor& src,
39
+ IntArrayRef diff_weight_aten_size,
40
+ IntArrayRef padding_front_top_left,
41
+ IntArrayRef padding_back_bottom_right,
42
+ IntArrayRef stride,
43
+ IntArrayRef dilation,
44
+ int64_t groups,
45
+ const std::vector<sycl::event>& deps = {});
46
+
47
+ TORCH_API sycl::event convolution_backward_data(
48
+ at::Tensor& diff_src,
49
+ const at::Tensor& diff_dst,
50
+ const at::Tensor& weight,
51
+ IntArrayRef padding_front_top_left,
52
+ IntArrayRef padding_back_bottom_right,
53
+ IntArrayRef stride,
54
+ IntArrayRef dilation,
55
+ int64_t groups,
56
+ bool bias_defined,
57
+ const std::vector<sycl::event>& deps = {});
58
+
59
+ TORCH_API sycl::event deconvolution(
60
+ at::Tensor& dst,
61
+ const at::Tensor& src,
62
+ const at::Tensor& weight,
63
+ const at::Tensor& bia,
64
+ IntArrayRef stride,
65
+ IntArrayRef padding,
66
+ IntArrayRef dst_padding,
67
+ IntArrayRef dilation,
68
+ int64_t groups,
69
+ Attr& attr,
70
+ const std::vector<sycl::event>& deps = {});
71
+
72
+ TORCH_API sycl::event deconvolution_backward_data(
73
+ at::Tensor& diff_src,
74
+ const at::Tensor& diff_dst,
75
+ const at::Tensor& weight,
76
+ IntArrayRef stride,
77
+ IntArrayRef padding,
78
+ IntArrayRef dst_padding,
79
+ IntArrayRef dilation,
80
+ int64_t groups,
81
+ bool bias_defined,
82
+ const std::vector<sycl::event>& deps = {});
83
+
84
+ TORCH_API sycl::event deconvolution_backward_weights(
85
+ at::Tensor& diff_weight,
86
+ at::Tensor& diff_bia,
87
+ const at::Tensor& diff_dst,
88
+ const at::Tensor& src,
89
+ IntArrayRef stride,
90
+ IntArrayRef padding,
91
+ IntArrayRef dst_padding,
92
+ IntArrayRef dilation,
93
+ int64_t groups,
94
+ const std::vector<sycl::event>& deps = {});
95
+
96
+ TORCH_API void woq_matmul_int4(
97
+ at::Tensor& result, // dst, [M, N]
98
+ const at::Tensor& mat1_, // src, [M, K]
99
+ const at::Tensor& mat2_, // quantized weight, [K/8, N]
100
+ const at::Tensor& scale, // [K/group_size, N]
101
+ const at::Tensor& zp, // [k/group_size, N]
102
+ int64_t group_size,
103
+ bool pri_cache = true);
104
+
105
+ dnnl::memory::dims conv_dst_size(
106
+ int64_t ndim,
107
+ IntArrayRef src_tz,
108
+ IntArrayRef wgh_tz,
109
+ IntArrayRef padding_front_top_left,
110
+ IntArrayRef padding_back_bottom_right,
111
+ IntArrayRef stride,
112
+ IntArrayRef dilation);
113
+
114
+ dnnl::memory::dims deconv_dst_size(
115
+ IntArrayRef src_size,
116
+ IntArrayRef wgh_size,
117
+ IntArrayRef padding,
118
+ IntArrayRef stride,
119
+ IntArrayRef dilation,
120
+ IntArrayRef dst_padding,
121
+ int64_t groups);
122
+
123
+ at::Tensor quantized_convolution(
124
+ at::Tensor act,
125
+ double act_scale,
126
+ int64_t act_zero_point,
127
+ at::Tensor weight,
128
+ at::Tensor weight_scales,
129
+ at::Tensor weight_zero_points,
130
+ std::optional<at::Tensor> bias,
131
+ torch::List<int64_t> stride,
132
+ torch::List<int64_t> padding,
133
+ torch::List<int64_t> dilation,
134
+ bool transposed,
135
+ int64_t groups,
136
+ at::Tensor output,
137
+ double inv_output_scale,
138
+ int64_t output_zero_point,
139
+ std::optional<at::Tensor> accum,
140
+ double accum_scale,
141
+ int64_t accum_zero_point,
142
+ std::optional<c10::ScalarType> output_dtype,
143
+ std::optional<std::string_view> binary_attr,
144
+ std::optional<at::Scalar> binary_alpha,
145
+ std::optional<std::string_view> unary_attr,
146
+ torch::List<std::optional<at::Scalar>> unary_scalars,
147
+ std::optional<std::string_view> unary_algorithm);
148
+
149
+ void quantized_matmul(
150
+ at::Tensor mat1, // act
151
+ double input_scale,
152
+ int64_t input_zero_point,
153
+ at::Tensor mat2, // weight
154
+ at::Tensor& weight_scales,
155
+ at::Tensor& weight_zero_points,
156
+ at::Tensor& b_raw,
157
+ at::Tensor result, // output
158
+ double output_scale,
159
+ int64_t output_zero_point,
160
+ std::optional<c10::ScalarType> output_dtype,
161
+ std::optional<at::Tensor> other, // extra input for binary-post-op
162
+ double other_scale,
163
+ int64_t other_zero_point,
164
+ const std::string_view& binary_post_op,
165
+ double binary_alpha,
166
+ const std::string_view& unary_post_op,
167
+ torch::List<std::optional<at::Scalar>>& unary_post_op_args,
168
+ std::string_view unary_post_op_algorithm,
169
+ bool m2_trnas);
170
+
171
+ void sdpa(
172
+ int batch_size,
173
+ int seq_len_q,
174
+ int seq_len_kv,
175
+ int num_head_q,
176
+ int num_head_kv,
177
+ int head_dim_qk,
178
+ int head_dim_v,
179
+ const Tensor& query,
180
+ const Tensor& key,
181
+ const Tensor& value,
182
+ std::optional<at::Tensor> attn_mask,
183
+ bool is_causal,
184
+ float softmax_scale,
185
+ const Tensor& attention,
186
+ bool compute_logsumexp,
187
+ const Tensor& logsumexp);
188
+
189
+ void sdpa_backward(
190
+ int batch_size,
191
+ int num_head_q,
192
+ int num_head_kv,
193
+ int seq_len_q,
194
+ int seq_len_kv,
195
+ int head_dim_qk,
196
+ int head_dim_v,
197
+ const Tensor& grad_out,
198
+ const Tensor& query,
199
+ const Tensor& key,
200
+ const Tensor& value,
201
+ const Tensor& out,
202
+ const Tensor& logsumexp,
203
+ std::optional<at::Tensor> attn_mask,
204
+ bool is_causal,
205
+ double scale,
206
+ Tensor& grad_query,
207
+ Tensor& grad_key,
208
+ Tensor& grad_value);
209
+
210
+ sycl::event scaled_matmul(
211
+ const Tensor& mat1,
212
+ const Tensor& mat2,
213
+ Tensor& result,
214
+ const Tensor& scale_a,
215
+ const Tensor& scale_b,
216
+ at::blas::ScalingType scaling_choice_a,
217
+ at::blas::ScalingType scaling_choice_b,
218
+ const std::optional<at::Tensor>& bias,
219
+ const std::optional<at::Tensor>& scale_result,
220
+ bool use_fast_accum);
221
+ } // namespace at::native::onednn
222
+
223
+ #else
224
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
225
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/detail/oneDNNContext.h ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+
6
+ #include <c10/core/Device.h>
7
+ #include <c10/util/flat_hash_map.h>
8
+ #include <c10/xpu/XPUFunctions.h>
9
+ #include <c10/xpu/XPUStream.h>
10
+
11
+ #include <oneapi/dnnl/dnnl.hpp>
12
+ #include <oneapi/dnnl/dnnl_sycl.hpp>
13
+ #include <vector>
14
+
15
+ namespace at::native::onednn {
16
+
17
+ TORCH_XPU_API dnnl::memory make_onednn_memory(
18
+ dnnl::memory::desc md,
19
+ dnnl::engine& engine,
20
+ void* ptr);
21
+
22
+ // Keep non-static and non-inline
23
+ bool set_onednn_verbose(int level);
24
+
25
+ // GpuEngineManager singleton
26
+ struct TORCH_XPU_API GpuEngineManager {
27
+ static GpuEngineManager& Instance(); // Singleton
28
+
29
+ dnnl::engine& get_engine(
30
+ DeviceIndex device_index = c10::xpu::current_device()) {
31
+ c10::xpu::check_device_index(device_index);
32
+ return *engine_pool[device_index];
33
+ }
34
+
35
+ dnnl::engine& get_engine(const Device& device) {
36
+ TORCH_INTERNAL_ASSERT(device.type() == kXPU);
37
+ return get_engine(device.index());
38
+ }
39
+
40
+ GpuEngineManager(GpuEngineManager const&) = delete;
41
+ GpuEngineManager& operator=(GpuEngineManager const&) = delete;
42
+ GpuEngineManager(GpuEngineManager&&) = default;
43
+ GpuEngineManager& operator=(GpuEngineManager&&) = default;
44
+
45
+ protected:
46
+ GpuEngineManager();
47
+ ~GpuEngineManager() = default;
48
+
49
+ private:
50
+ std::vector<std::shared_ptr<dnnl::engine>> engine_pool;
51
+ };
52
+
53
+ // GpuStreamManager singleton
54
+ struct TORCH_XPU_API GpuStreamManager {
55
+ static GpuStreamManager& Instance(); // Singleton
56
+
57
+ dnnl::stream& get_stream(
58
+ DeviceIndex device_index = c10::xpu::current_device()) {
59
+ auto stream = c10::xpu::getCurrentXPUStream(device_index);
60
+ auto priority = stream.priority();
61
+ if (stream_pool[device_index][priority].find(stream) ==
62
+ stream_pool[device_index][priority].end()) {
63
+ stream_pool[device_index][priority][stream] =
64
+ std::make_shared<dnnl::stream>(dnnl::sycl_interop::make_stream(
65
+ GpuEngineManager::Instance().get_engine(device_index),
66
+ stream.queue()));
67
+ }
68
+ return *stream_pool[device_index][priority][stream];
69
+ }
70
+
71
+ GpuStreamManager(GpuStreamManager const&) = delete;
72
+ GpuStreamManager& operator=(GpuStreamManager const&) = delete;
73
+ GpuStreamManager(GpuStreamManager&&) = default;
74
+ GpuStreamManager& operator=(GpuStreamManager&&) = default;
75
+
76
+ protected:
77
+ GpuStreamManager() {
78
+ c10::DeviceIndex device_count = c10::xpu::device_count_ensure_non_zero();
79
+ stream_pool.resize(device_count);
80
+ }
81
+ ~GpuStreamManager() = default;
82
+
83
+ private:
84
+ using stream_hash_map =
85
+ ska::flat_hash_map<c10::xpu::XPUStream, std::shared_ptr<dnnl::stream>>;
86
+ std::vector<
87
+ std::array<stream_hash_map, c10::xpu::max_compile_time_stream_priorities>>
88
+ stream_pool;
89
+ };
90
+
91
+ } // namespace at::native::onednn
92
+
93
+ #else
94
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
95
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/qconv.h ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+ #include <ATen/Tensor.h>
6
+
7
+ namespace at::native::xpu {
8
+ class QConvoneDNNXPU final {
9
+ public:
10
+ C10_API static at::Tensor run_pointwise(
11
+ at::Tensor act,
12
+ double act_scale,
13
+ int64_t act_zero_point,
14
+ at::Tensor weight,
15
+ at::Tensor weight_scales,
16
+ at::Tensor weight_zero_points,
17
+ std::optional<at::Tensor> bias,
18
+ torch::List<int64_t> stride,
19
+ torch::List<int64_t> padding,
20
+ torch::List<int64_t> dilation,
21
+ int64_t groups,
22
+ double inv_output_scale,
23
+ int64_t output_zero_point,
24
+ std::optional<c10::ScalarType> output_dtype,
25
+ std::string_view attr,
26
+ torch::List<std::optional<at::Scalar>> scalars,
27
+ std::optional<std::string_view> algorithm);
28
+
29
+ C10_API static at::Tensor run_pointwise_tensor(
30
+ at::Tensor act,
31
+ at::Tensor act_scale,
32
+ at::Tensor act_zero_point,
33
+ at::Tensor weight,
34
+ at::Tensor weight_scales,
35
+ at::Tensor weight_zero_points,
36
+ std::optional<at::Tensor> bias,
37
+ torch::List<int64_t> stride,
38
+ torch::List<int64_t> padding,
39
+ torch::List<int64_t> dilation,
40
+ int64_t groups,
41
+ double output_scale,
42
+ int64_t output_zero_point,
43
+ std::optional<c10::ScalarType> output_dtype,
44
+ std::string_view attr,
45
+ torch::List<std::optional<at::Scalar>> scalars,
46
+ std::optional<std::string_view> algorithm);
47
+
48
+ C10_API static at::Tensor run_pointwise_binary(
49
+ at::Tensor act,
50
+ double act_scale,
51
+ int64_t act_zero_point,
52
+ at::Tensor weight,
53
+ at::Tensor weight_scales,
54
+ at::Tensor weight_zero_points,
55
+ at::Tensor accum,
56
+ std::optional<at::Tensor> bias,
57
+ torch::List<int64_t> stride,
58
+ torch::List<int64_t> padding,
59
+ torch::List<int64_t> dilation,
60
+ int64_t groups,
61
+ double output_scale,
62
+ int64_t output_zero_point,
63
+ std::optional<c10::ScalarType> output_dtype,
64
+ double accum_scale,
65
+ int64_t accum_zero_point,
66
+ std::string_view binary_attr,
67
+ std::optional<at::Scalar> alpha,
68
+ std::optional<std::string_view> unary_attr,
69
+ torch::List<std::optional<at::Scalar>> unary_scalars,
70
+ std::optional<std::string_view> unary_algorithm);
71
+
72
+ C10_API static at::Tensor run_pointwise_binary_tensor(
73
+ at::Tensor act,
74
+ at::Tensor act_scale,
75
+ at::Tensor act_zero_point,
76
+ at::Tensor weight,
77
+ at::Tensor weight_scales,
78
+ at::Tensor weight_zero_points,
79
+ at::Tensor accum,
80
+ std::optional<at::Tensor> bias,
81
+ torch::List<int64_t> stride,
82
+ torch::List<int64_t> padding,
83
+ torch::List<int64_t> dilation,
84
+ int64_t groups,
85
+ double output_scale,
86
+ int64_t output_zero_point,
87
+ std::optional<c10::ScalarType> output_dtype,
88
+ double accum_scale,
89
+ int64_t accum_zero_point,
90
+ std::string_view binary_attr,
91
+ std::optional<at::Scalar> alpha,
92
+ std::optional<std::string_view> unary_attr,
93
+ torch::List<std::optional<at::Scalar>> unary_scalars,
94
+ std::optional<std::string_view> unary_algorithm);
95
+
96
+ static inline c10::ScalarType qconv_decide_out_dtype(
97
+ const at::Tensor& act,
98
+ const std::optional<c10::ScalarType> output_dtype);
99
+
100
+ static at::Tensor qconv_prepack_xpu(
101
+ at::Tensor weight,
102
+ at::Tensor weight_scales,
103
+ double input_scale,
104
+ int64_t input_zero_point,
105
+ torch::List<int64_t> stride,
106
+ torch::List<int64_t> padding,
107
+ torch::List<int64_t> dilation,
108
+ int64_t groups,
109
+ std::optional<torch::List<int64_t>> input_shape);
110
+ };
111
+
112
+ } // namespace at::native::xpu
113
+ #else
114
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
115
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mkldnn/xpu/qlinear.h ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+ #include <ATen/Tensor.h>
6
+ #include <ATen/core/List.h>
7
+
8
+ namespace at::native::xpu {
9
+
10
+ class QLinearOnednnXPU final {
11
+ public:
12
+ C10_API static Tensor q_linear_pointwise(
13
+ Tensor act,
14
+ double act_scale,
15
+ int64_t act_zero_point,
16
+ Tensor weight,
17
+ Tensor weight_scales,
18
+ Tensor weight_zero_points,
19
+ std::optional<Tensor> bias,
20
+ double output_scale,
21
+ int64_t output_zero_point,
22
+ std::optional<c10::ScalarType> output_dtype,
23
+ std::string_view post_op_name,
24
+ torch::List<std::optional<at::Scalar>> post_op_args,
25
+ std::string_view post_op_algorithm);
26
+
27
+ C10_API static Tensor q_linear_pointwise_tensor(
28
+ Tensor act,
29
+ Tensor act_scale,
30
+ Tensor act_zero_point,
31
+ Tensor weight,
32
+ Tensor weight_scales,
33
+ Tensor weight_zero_points,
34
+ std::optional<Tensor> bias,
35
+ double output_scale,
36
+ int64_t output_zero_point,
37
+ std::optional<c10::ScalarType> output_dtype,
38
+ std::string_view post_op_name,
39
+ torch::List<std::optional<at::Scalar>> post_op_args,
40
+ std::string_view post_op_algorithm);
41
+
42
+ C10_API static Tensor q_linear_pointwise_binary(
43
+ Tensor act,
44
+ double act_scale,
45
+ int64_t act_zero_point,
46
+ Tensor weight,
47
+ Tensor weight_scales,
48
+ Tensor weight_zero_points,
49
+ std::optional<at::Tensor> other,
50
+ std::optional<Tensor> bias,
51
+ double output_scale,
52
+ int64_t output_zero_point,
53
+ std::optional<c10::ScalarType> output_dtype,
54
+ double other_scale,
55
+ int64_t other_zero_point,
56
+ std::string_view binary_post_op,
57
+ double binary_alpha,
58
+ std::string_view unary_post_op,
59
+ torch::List<std::optional<at::Scalar>> unary_post_op_args,
60
+ std::string_view unary_post_op_algorithm);
61
+
62
+ C10_API static Tensor q_linear_pointwise_binary_tensor(
63
+ Tensor act,
64
+ Tensor act_scale,
65
+ Tensor act_zero_point,
66
+ Tensor weight,
67
+ Tensor weight_scales,
68
+ Tensor weight_zero_points,
69
+ std::optional<at::Tensor> other,
70
+ std::optional<Tensor> bias,
71
+ double output_scale,
72
+ int64_t output_zero_point,
73
+ std::optional<c10::ScalarType> output_dtype,
74
+ double other_scale,
75
+ int64_t other_zero_point,
76
+ std::string_view binary_post_op,
77
+ double binary_alpha,
78
+ std::string_view unary_post_op,
79
+ torch::List<std::optional<at::Scalar>> unary_post_op_args,
80
+ std::string_view unary_post_op_algorithm);
81
+
82
+ C10_API static Tensor q_linear_prepack_onednn(
83
+ at::Tensor weight,
84
+ std::optional<torch::List<int64_t>> input_shape);
85
+
86
+ static inline c10::ScalarType qlinear_decide_out_dtype(
87
+ const at::Tensor& act,
88
+ const std::optional<c10::ScalarType> output_dtype);
89
+
90
+ }; // class QLinearOnednnXPU
91
+
92
+ } // namespace at::native::xpu
93
+
94
+ #else
95
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
96
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/Copy.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/core/Tensor.h>
6
+
7
+ namespace at::native::mps {
8
+
9
+ at::Tensor& mps_copy_(
10
+ at::Tensor& dst,
11
+ const at::Tensor& src,
12
+ bool non_blocking);
13
+ void copy_blit_mps(void* dst, const void* src, size_t size);
14
+
15
+ } // namespace at::native::mps
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/native/mps/MPSGraphSequoiaOps.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
5
+
6
+ #if !defined(__MAC_15_0) && (!defined(MAC_OS_X_VERSION_15_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_15_0))
7
+
8
+ @interface MPSNDArrayIdentity : MPSNDArrayUnaryKernel
9
+ - (MPSNDArray* __nullable)reshapeWithCommandBuffer:(__nullable id<MTLCommandBuffer>)cmdBuf
10
+ sourceArray:(MPSNDArray* __nonnull)sourceArray
11
+ shape:(MPSShape* __nonnull)shape
12
+ destinationArray:(MPSNDArray* __nullable)destinationArray;
13
+ @end
14
+
15
+ @interface MPSNDArrayDescriptor ()
16
+ @property(readwrite, nonatomic) BOOL preferPackedRows;
17
+ @end
18
+
19
+ @interface MPSNDArray ()
20
+ - (nonnull instancetype)initWithBuffer:(id<MTLBuffer> _Nonnull)buffer
21
+ offset:(NSUInteger)offset
22
+ descriptor:(MPSNDArrayDescriptor* _Nonnull)descriptor;
23
+ - (MPSNDArray* __nullable)arrayViewWithShape:(MPSShape* _Nullable)shape strides:(MPSShape* _Nonnull)strides;
24
+ @end
25
+
26
+ typedef NS_ENUM(NSInteger, MTLMathMode) {
27
+ MTLMathModeSafe = 0,
28
+ MTLMathModeRelaxed = 1,
29
+ MTLMathModeFast = 2,
30
+ };
31
+
32
+ typedef NS_ENUM(NSInteger, MTLMathFloatingPointFunctions) {
33
+ MTLMathFloatingPointFunctionsFast = 0,
34
+ MTLMathFloatingPointFunctionsPrecise = 1,
35
+ };
36
+
37
+ @interface MTLCompileOptions ()
38
+ @property(readwrite, nonatomic) MTLMathMode mathMode;
39
+ @property(readwrite, nonatomic) MTLMathFloatingPointFunctions mathFloatingPointFunctions;
40
+ @end
41
+
42
+ #endif
43
+
44
+ #else
45
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
46
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/MetalShaderLibrary.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #ifdef __OBJC__
4
+ #include <Metal/Metal.h>
5
+ typedef id<MTLLibrary> MTLLibrary_t;
6
+ typedef id<MTLFunction> MTLFunction_t;
7
+ typedef id<MTLComputePipelineState> MTLComputePipelineState_t;
8
+ typedef id<MTLComputeCommandEncoder> MTLComputeCommandEncoder_t;
9
+ #else
10
+ typedef void MTLCompileOptions;
11
+ typedef void* MTLLibrary_t;
12
+ typedef void* MTLFunction_t;
13
+ typedef void* MTLComputePipelineState_t;
14
+ typedef void* MTLComputeCommandEncoder_t;
15
+ #endif
16
+
17
+ #include <c10/core/Scalar.h>
18
+ #include <c10/util/OptionalArrayRef.h>
19
+ #include <functional>
20
+ #include <optional>
21
+ #include <type_traits>
22
+ #include <unordered_map>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ // Forward declaration of TensorBase and TensorIteratorBase
27
+ namespace at {
28
+ class TensorBase;
29
+ struct TensorIteratorBase;
30
+ } // namespace at
31
+
32
+ namespace at::native::mps {
33
+
34
+ namespace detail {
35
+ template <typename T>
36
+ class has_size_type {
37
+ template <typename U>
38
+ static constexpr std::true_type check(typename U::size_type*);
39
+ template <typename>
40
+ static constexpr std::false_type check(...);
41
+
42
+ public:
43
+ static constexpr bool value = decltype(check<T>(nullptr))::value;
44
+ };
45
+
46
+ template <typename T>
47
+ constexpr bool has_size_type_v = has_size_type<T>::value;
48
+
49
+ } // namespace detail
50
+
51
+ // Returns `gpuAddress` of respective `id<MTLBuffer>` plus storage offset
52
+ void* get_tensor_gpu_address(const at::TensorBase&);
53
+
54
+ class MetalKernelFunction {
55
+ public:
56
+ MetalKernelFunction(MTLComputePipelineState_t cps_, MTLFunction_t f_);
57
+ ~MetalKernelFunction();
58
+ MetalKernelFunction(MetalKernelFunction&) = delete;
59
+ // Shader properties
60
+ uint64_t getMaxThreadsPerThreadgroup() const;
61
+ uint64_t getThreadExecutionWidth() const;
62
+ uint64_t getStaticThreadGroupMemoryLength() const;
63
+ void runCommandBlock(std::function<void(void)> f);
64
+ // Methods below should be called from runCommandBlock function
65
+ void startEncoding();
66
+ void setArg(unsigned idx, const at::TensorBase& t);
67
+ void setArg(unsigned idx, const void* ptr, uint64_t size);
68
+ template <
69
+ typename T,
70
+ typename = std::enable_if_t<
71
+ std::is_integral_v<T> || std::is_same_v<T, float> ||
72
+ (std::is_class_v<T> && std::is_trivially_copyable_v<T> &&
73
+ !detail::has_size_type_v<T>)>>
74
+ inline void setArg(unsigned idx, const T val) {
75
+ setArg(idx, &val, sizeof(T));
76
+ }
77
+
78
+ template <
79
+ typename Container,
80
+ typename = std::enable_if_t<detail::has_size_type_v<Container>>>
81
+ inline void setArg(unsigned idx, const Container& values) {
82
+ setArg(
83
+ idx,
84
+ values.data(),
85
+ values.size() * sizeof(typename Container::value_type));
86
+ }
87
+ void dispatch(
88
+ uint64_t length,
89
+ std::optional<uint64_t> groupSize = std::nullopt);
90
+ void dispatch(
91
+ c10::ArrayRef<uint64_t> length,
92
+ c10::OptionalArrayRef<uint64_t> groupSize = std::nullopt);
93
+
94
+ private:
95
+ MTLComputePipelineState_t cps;
96
+ MTLFunction_t func;
97
+ MTLComputeCommandEncoder_t encoder = nullptr;
98
+ };
99
+
100
+ class MetalShaderLibrary {
101
+ public:
102
+ MetalShaderLibrary(std::string src)
103
+ : shaderSource(std::move(src)), nparams(0), compile_options(nullptr) {}
104
+ MetalShaderLibrary(std::string src, unsigned nparams_)
105
+ : shaderSource(std::move(src)),
106
+ nparams(nparams_),
107
+ compile_options(nullptr) {}
108
+ MetalShaderLibrary(
109
+ std::string src,
110
+ unsigned nparams_,
111
+ MTLCompileOptions* compile_options_)
112
+ : shaderSource(std::move(src)),
113
+ nparams(nparams_),
114
+ compile_options(compile_options_) {}
115
+ MetalShaderLibrary(const MetalShaderLibrary&) = delete;
116
+ virtual ~MetalShaderLibrary();
117
+ std::vector<std::string> getFunctionNames();
118
+ std::shared_ptr<MetalKernelFunction> getKernelFunction(
119
+ const std::string& name);
120
+ // Returns a raw pointer to the kernel function for use in C APIs
121
+ MetalKernelFunction* getCachedKernelFunctionPtr(const std::string& name);
122
+ inline MTLComputePipelineState_t getPipelineStateForFunc(
123
+ const std::string& fname) {
124
+ return getLibraryPipelineState(getLibrary(), fname).first;
125
+ }
126
+ MTLComputePipelineState_t getPipelineStateForFunc(
127
+ const std::string& fname,
128
+ const std::initializer_list<std::string>& params) {
129
+ return getLibraryPipelineState(getLibrary(params), fname).first;
130
+ }
131
+ inline MTLFunction_t getMTLFunction(const std::string& fname) {
132
+ return getLibraryPipelineState(getLibrary(), fname).second;
133
+ }
134
+ MTLFunction_t getMTLFunction(
135
+ const std::string& fname,
136
+ const std::initializer_list<std::string>& params) {
137
+ return getLibraryPipelineState(getLibrary(params), fname).second;
138
+ }
139
+ static MetalShaderLibrary& getBundledLibrary();
140
+ void exec_unary_kernel(
141
+ TensorIteratorBase& iter,
142
+ const std::string& name,
143
+ const std::optional<c10::Scalar> alpha = std::nullopt,
144
+ const std::optional<c10::ScalarType> scalar_arg_type = std::nullopt);
145
+ void exec_binary_kernel(
146
+ TensorIteratorBase& iter,
147
+ const std::string& name,
148
+ const std::optional<c10::Scalar> alpha = std::nullopt,
149
+ const std::optional<c10::ScalarType> scalar_arg_type = std::nullopt);
150
+ void exec_ternary_kernel(TensorIteratorBase& iter, const std::string& name);
151
+
152
+ template <typename T>
153
+ void exec_unary_kernel_with_params(
154
+ TensorIteratorBase& iter,
155
+ const std::string& name,
156
+ T params,
157
+ const std::string& params_type_name);
158
+ template <typename T>
159
+ void exec_binary_kernel_with_params(
160
+ TensorIteratorBase& iter,
161
+ const std::string& name,
162
+ T params,
163
+ const std::string& params_type_name);
164
+
165
+ protected:
166
+ virtual MTLLibrary_t getLibrary();
167
+ virtual MTLLibrary_t getLibrary(
168
+ const std::initializer_list<std::string>& params);
169
+ MTLLibrary_t library = nullptr;
170
+
171
+ private:
172
+ std::pair<MTLComputePipelineState_t, MTLFunction_t> getLibraryPipelineState(
173
+ MTLLibrary_t lib,
174
+ const std::string& fname);
175
+ MTLLibrary_t compileLibrary(const std::string& src);
176
+ std::string shaderSource;
177
+ unsigned nparams;
178
+ MTLCompileOptions* compile_options;
179
+ std::unordered_map<std::string, MTLLibrary_t> libMap;
180
+ std::unordered_map<
181
+ std::string,
182
+ std::pair<MTLComputePipelineState_t, MTLFunction_t>>
183
+ cplMap;
184
+ // Cache for kernel functions returned by getCachedKernelFunctionPtr
185
+ std::unordered_map<std::string, std::unique_ptr<MetalKernelFunction>>
186
+ kernelCache;
187
+ };
188
+
189
+ class DynamicMetalShaderLibrary : public MetalShaderLibrary {
190
+ public:
191
+ DynamicMetalShaderLibrary(const std::string& src) : MetalShaderLibrary(src) {
192
+ // Compile right away
193
+ getLibrary();
194
+ }
195
+ ~DynamicMetalShaderLibrary() override;
196
+ };
197
+
198
+ } // namespace at::native::mps
199
+
200
+ #else
201
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
202
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/OperationUtils.h ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <initializer_list>
7
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
8
+ #include <ATen/Tensor.h>
9
+ #include <ATen/TensorIterator.h>
10
+ #include <ATen/Utils.h>
11
+ #include <ATen/mps/MPSProfiler.h>
12
+ #include <ATen/mps/MPSStream.h>
13
+ #include <ATen/native/mps/MetalShaderLibrary.h>
14
+ #include <ATen/native/mps/TensorFactory.h>
15
+ #include <c10/core/ScalarType.h>
16
+ #include <fmt/format.h>
17
+ #include <torch/library.h>
18
+ #include <unordered_map>
19
+
20
+ #ifndef AT_PER_OPERATOR_HEADERS
21
+ #include <ATen/Functions.h>
22
+ #include <ATen/NativeFunctions.h>
23
+ #else
24
+ #include <ATen/ops/empty.h>
25
+ #include <ATen/ops/empty_like.h>
26
+ #include <ATen/ops/zeros.h>
27
+ #include <ATen/ops/zeros_like.h>
28
+ #endif
29
+
30
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
31
+
32
+ @interface MPSGraph (PyTorchFixups)
33
+ - (MPSGraphTensor*)minimumWithNaNPropagationAndIntFallbackWithPrimaryTensor:(MPSGraphTensor*)primaryTensor
34
+ secondaryTensor:(MPSGraphTensor*)secondaryTensor
35
+ name:(NSString*)name;
36
+
37
+ - (MPSGraphTensor*)maximumWithNaNPropagationAndIntFallbackWithPrimaryTensor:(MPSGraphTensor*)primaryTensor
38
+ secondaryTensor:(MPSGraphTensor*)secondaryTensor
39
+ name:(NSString*)name;
40
+ @end
41
+
42
+ using namespace at::mps;
43
+
44
+ namespace at::native::mps {
45
+
46
+ struct MPSScalar {
47
+ id<MTLBuffer> getMTLBuffer() const {
48
+ return __builtin_bit_cast(id<MTLBuffer>, buffer.get());
49
+ }
50
+
51
+ size_t size = 0;
52
+ ScalarType type = ScalarType::Undefined;
53
+ c10::DataPtr buffer; // stores MTLBuffer (frees buffer if MPSScalar instance goes out of scope)
54
+ union {
55
+ float f; // MPS doesn't support 'double'
56
+ at::Half h;
57
+ int64_t i;
58
+ bool b;
59
+ c10::complex<float> cf;
60
+ c10::complex<at::Half> ch;
61
+ at::BFloat16 bf16;
62
+ } value{};
63
+ };
64
+
65
+ void runMPSGraph(MPSStream* mpsStream, MPSGraph* mpsGraph, NSDictionary* feeds, NSDictionary* results);
66
+
67
+ MPSDataType getMPSDataType(ScalarType scalar_type);
68
+ static inline MPSDataType getMPSDataType(const TensorBase& t) {
69
+ return getMPSDataType(t.scalar_type());
70
+ }
71
+ MPSDataType getMPSScalarType(ScalarType scalar_type);
72
+ static inline MPSDataType getMPSScalarType(const TensorBase& t) {
73
+ return getMPSScalarType(t.scalar_type());
74
+ }
75
+ MPSScalar getMPSScalar(const Scalar& scalar, ScalarType type);
76
+ std::string getMPSTypeString(ScalarType scalar_type, bool short_name = false);
77
+ static inline std::string getMPSTypeString(const TensorBase& t, bool short_name = false) {
78
+ return getMPSTypeString(t.scalar_type(), short_name);
79
+ }
80
+ std::string scalarToMetalTypeString(const c10::ScalarType& scalar_type);
81
+ static inline std::string scalarToMetalTypeString(const TensorBase& t) {
82
+ return scalarToMetalTypeString(t.scalar_type());
83
+ }
84
+ NSArray<NSNumber*>* getTensorAxes(const TensorBase& t);
85
+ NSArray<NSNumber*>* getTensorAxes(const IntArrayRef& sizes, at::OptionalIntArrayRef dim);
86
+ std::string getMPSShapeString(MPSShape* shape);
87
+ std::string getTensorsStringKey(const TensorList& tensors, bool short_dtype = true, bool exclude_shape = false);
88
+ std::string to_hex_key(float);
89
+ std::string getArrayRefString(const IntArrayRef s);
90
+ // use has_storage() on the returned tensor to determine if src actually is a view
91
+ Tensor gatherViewTensor(const Tensor& src, Tensor& dst);
92
+ Tensor& scatterViewTensor(const Tensor& src, Tensor& output);
93
+ MPSGraphTensor* castToIHFTypes(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor, const TensorBase& input);
94
+ MPSGraphTensor* castFromIHFTypes(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor, const TensorBase& input);
95
+
96
+ MPSNDArray* getStridedMPSNDArray(const TensorBase& src, MPSNDArray* srcNDArray);
97
+ MPSNDArray* getMPSNDArray(const TensorBase& t, const IntArrayRef& sizes = {}, const IntArrayRef& strides = {});
98
+ MPSNDArray* getMPSNDArray(const TensorBase& t, MPSShape* sizes = nil, MPSShape* strides = nil);
99
+ // The MPSShape could vary based on memory format
100
+ Tensor getTensorView(const Tensor& t, MPSShape* shape);
101
+ MPSShape* getMPSShape(const TensorBase& t, c10::MemoryFormat memory_format = MemoryFormat::Contiguous);
102
+ MPSShape* getMPSShape(IntArrayRef sizes, c10::MemoryFormat memory_format = MemoryFormat::Contiguous);
103
+
104
+ // Determines whether a tensor is too large to use MPSGraph
105
+ bool isTooLargeForMPSGraph(const Tensor& tensor, bool useMPSStridedAPI = true);
106
+
107
+ static inline id<MTLBuffer> getMTLBufferStorage(const TensorBase& tensor) {
108
+ return __builtin_bit_cast(id<MTLBuffer>, tensor.storage().data());
109
+ }
110
+
111
+ class Placeholder {
112
+ public:
113
+ Placeholder() : _placeholder(nullptr), _value(nullptr), _tensor(Tensor()) {}
114
+ Placeholder(MPSGraphTensor* mpsGraphTensor) : _placeholder(mpsGraphTensor), _value(nullptr), _tensor(Tensor()) {}
115
+ Placeholder(MPSGraphTensor* mpsGraphTensor, MPSNDArray* mpsNDArray);
116
+ Placeholder(MPSGraphTensor* mpsGraphTensor,
117
+ const Tensor& self,
118
+ MPSShape* mpsShape = nullptr,
119
+ bool gatherTensorData = true,
120
+ MPSDataType dataType = MPSDataTypeInvalid,
121
+ bool useMPSStridedAPI = true);
122
+ MPSGraphTensor* getMPSGraphTensor() {
123
+ return _placeholder;
124
+ }
125
+ MPSGraphTensorData* getMPSGraphTensorData() {
126
+ return _value;
127
+ }
128
+ bool isIntermediate() {
129
+ return _value == nullptr;
130
+ }
131
+
132
+ private:
133
+ MPSGraphTensor* _placeholder;
134
+ MPSGraphTensorData* _value;
135
+ Tensor _tensor;
136
+ };
137
+
138
+ void resize_tensor(Tensor* output);
139
+ Tensor wrapped_scalar_tensor_mps(const Scalar& scalar, const Device device);
140
+ MPSGraphTensor* convertNHWCtoNCHW(MPSGraph* mpsGraph, MPSGraphTensor* tensor);
141
+ MPSGraphTensor* castMPSTensor(MPSGraph* mpsGraph, MPSGraphTensor* tensor, ScalarType toType);
142
+ MPSGraphTensor* castMPSTensor(MPSGraph* mpsGraph, MPSGraphTensor* tensor, MPSDataType toType);
143
+ MPSGraphTensorData* getMPSGraphTensorData(MPSGraph* mpsGraph, MPSStream* mpsStream, const TensorBase& tensor);
144
+ MPSGraphTensorData* getMPSGraphTensorFromScalar(MPSStream* mpsStream, MPSScalar& scalar);
145
+
146
+ MPSGraph* make_mps_graph();
147
+
148
+ MPSGraphTensor* mpsGraphUnrankedPlaceHolder(MPSGraph* mpsGraph, MPSDataType dataType);
149
+ MPSGraphTensor* mpsGraphRankedPlaceHolder(MPSGraph* mpsGraph, MPSDataType dataType, MPSShape* mpsShape);
150
+ MPSGraphTensor* mpsGraphRankedPlaceHolder(MPSGraph* mpsGraph, const TensorBase& tensor);
151
+ MPSGraphTensor* mpsGraphScalarPlaceHolder(MPSGraph* mpsGraph, MPSDataType dataType);
152
+ MPSGraphTensor* mpsGraphScalarPlaceHolder(MPSGraph* mpsGraph, const Scalar& scalar);
153
+
154
+ std::string get_mem_format_string(c10::MemoryFormat memory_format);
155
+
156
+ using MPSCacheKey = uint64_t;
157
+
158
+ struct MPSCachedKernel {
159
+ MPSCachedKernel(NSObject* object) : _object([object retain]) {}
160
+ virtual ~MPSCachedKernel() {
161
+ [_object release];
162
+ _object = nullptr;
163
+ }
164
+
165
+ // Delete copy constructor and assignment
166
+ MPSCachedKernel(const MPSCachedKernel&) = delete;
167
+ void operator=(const MPSCachedKernel&) = delete;
168
+
169
+ template <typename T>
170
+ inline T* kernel() const {
171
+ return (T*)_object;
172
+ }
173
+
174
+ private:
175
+ NSObject* _object = nullptr;
176
+ };
177
+
178
+ // derive this class to cache a graph and its inputs/outputs
179
+ // can be used to store any NSObject
180
+ struct MPSCachedGraph {
181
+ MPSCachedGraph(NSObject* object) : _object([object retain]) {}
182
+ virtual ~MPSCachedGraph() {
183
+ [_object release];
184
+ _object = nullptr;
185
+ }
186
+
187
+ template <typename T>
188
+ inline T* as() {
189
+ return static_cast<T*>(this);
190
+ }
191
+
192
+ MPSGraph* graph() const {
193
+ return (MPSGraph*)_object;
194
+ }
195
+ NSObject* object() const {
196
+ return _object;
197
+ }
198
+
199
+ private:
200
+ NSObject* _object = nullptr;
201
+ };
202
+
203
+ struct MPSUnaryCachedGraph : public MPSCachedGraph {
204
+ MPSUnaryCachedGraph(MPSGraph* graph) : MPSCachedGraph(graph) {}
205
+ MPSGraphTensor* inputTensor_ = nil;
206
+ MPSGraphTensor* outputTensor_ = nil;
207
+ };
208
+
209
+ struct MPSUnaryGradCachedGraph : public MPSCachedGraph {
210
+ MPSUnaryGradCachedGraph(MPSGraph* graph) : MPSCachedGraph(graph) {}
211
+ MPSGraphTensor* gradOutputTensor_ = nil;
212
+ MPSGraphTensor* inputTensor_ = nil;
213
+ MPSGraphTensor* outputTensor_ = nil; // some backward input is actually the forward's output
214
+ MPSGraphTensor* gradInputTensor_ = nil;
215
+ };
216
+
217
+ struct MPSBinaryCachedGraph : public MPSCachedGraph {
218
+ MPSBinaryCachedGraph(MPSGraph* graph) : MPSCachedGraph(graph) {}
219
+ MPSGraphTensor* inputTensor_ = nil;
220
+ MPSGraphTensor* otherTensor_ = nil;
221
+ MPSGraphTensor* outputTensor_ = nil;
222
+ };
223
+
224
+ struct MPSBinaryGradCachedGraph : public MPSCachedGraph {
225
+ MPSBinaryGradCachedGraph(MPSGraph* graph) : MPSCachedGraph(graph) {}
226
+ MPSGraphTensor* gradOutputTensor_ = nil;
227
+ MPSGraphTensor* inputTensor_ = nil;
228
+ MPSGraphTensor* otherTensor_ = nil;
229
+ MPSGraphTensor* gradInputTensor_ = nil;
230
+ };
231
+
232
+ struct MPSKernelCache {
233
+ typedef MPSCachedKernel* (^CreateCachedKernelBlock)();
234
+
235
+ struct CacheEntry {
236
+ CacheEntry(const std::string& key, MPSCachedKernel* cachedKernel) : cachedKernel_(cachedKernel), key_(key) {}
237
+ MPSCachedKernel* cachedKernel_ = nullptr;
238
+ std::string key_;
239
+ };
240
+
241
+ public:
242
+ static MPSKernelCache* getInstance() {
243
+ if (_instance_cache == nullptr) {
244
+ _instance_cache = new MPSKernelCache();
245
+ }
246
+ return _instance_cache;
247
+ }
248
+
249
+ ~MPSKernelCache() {
250
+ dispatch_release(serialQueue_);
251
+ for (const auto& i : cache_) {
252
+ delete i.second.cachedKernel_;
253
+ }
254
+ }
255
+
256
+ // Disallow the copy constructor and operator= functions
257
+ MPSKernelCache(const MPSKernelCache&) = delete;
258
+ void operator=(const MPSKernelCache&) = delete;
259
+
260
+ MPSCachedKernel* CreateCachedKernel(const std::string& key, CreateCachedKernelBlock createCacheBlock) {
261
+ __block MPSCachedKernel* cachedKernel = nil;
262
+ MPSCacheKey hash = std::hash<std::string>{}(key);
263
+ dispatch_sync_with_rethrow(serialQueue_, ^() {
264
+ if (cache_.count(hash) != 0) {
265
+ auto& entry = cache_.at(hash);
266
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached kernel!\n");
267
+ cachedKernel = entry.cachedKernel_;
268
+ } else {
269
+ cachedKernel = createCacheBlock();
270
+ CacheEntry entry(key, cachedKernel);
271
+ cache_.emplace(hash, entry);
272
+ }
273
+ });
274
+ return cachedKernel;
275
+ }
276
+ template <typename T>
277
+ inline T* CreateCachedKernelAs(const std::string& key, CreateCachedKernelBlock createCacheBlock) {
278
+ return static_cast<T*>(CreateCachedKernel(key, createCacheBlock));
279
+ }
280
+
281
+ MPSCachedKernel* LookUp(const std::string& key) const {
282
+ __block MPSCachedKernel* cachedKernel = nil;
283
+
284
+ MPSCacheKey hash = std::hash<std::string>{}(key);
285
+ dispatch_sync_with_rethrow(serialQueue_, ^() {
286
+ if (cache_.count(hash) != 0) {
287
+ auto& entry = cache_.at(hash);
288
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached kernel!\n");
289
+ cachedKernel = entry.cachedKernel_;
290
+ }
291
+ });
292
+ return cachedKernel;
293
+ }
294
+
295
+ template <typename T>
296
+ inline T* LookUpAs(const std::string& key) const {
297
+ return static_cast<T*>(LookUp(key));
298
+ }
299
+
300
+ private:
301
+ MPSKernelCache() {
302
+ serialQueue_ = dispatch_queue_create("kernel cache queue", DISPATCH_QUEUE_SERIAL);
303
+ }
304
+
305
+ static MPSKernelCache* _instance_cache;
306
+ std::unordered_map<MPSCacheKey, CacheEntry> cache_;
307
+ dispatch_queue_t serialQueue_ = nullptr;
308
+ };
309
+
310
+ // Common template for creating cached kernel if missing
311
+ template <typename T>
312
+ inline T* LookUpOrCreateCachedKernel(const std::string& key, std::function<MPSKernel*()> instantiate) {
313
+ auto cache_ = MPSKernelCache::getInstance();
314
+ if (auto rc = cache_->LookUpAs<T>(key)) {
315
+ return rc;
316
+ }
317
+ return cache_->CreateCachedKernelAs<T>(key, ^mps::MPSCachedKernel*() {
318
+ auto k_ = new mps::MPSCachedKernel(instantiate());
319
+ return k_;
320
+ });
321
+ }
322
+
323
+ // TODO: Improve the overall design of MPSGraphCache.
324
+ // https://github.com/pytorch/pytorch/issues/77176
325
+ // Cache holding various keys mapped to graphs
326
+ struct MPSGraphCache {
327
+ typedef MPSCachedGraph* (^CreateCachedGraphBlock)();
328
+
329
+ struct CacheEntry {
330
+ CacheEntry(const std::string& key, MPSCachedGraph* cachedGraph) : cachedGraph_(cachedGraph), key_(key) {}
331
+ MPSCachedGraph* cachedGraph_ = nullptr;
332
+ std::string key_;
333
+ };
334
+
335
+ public:
336
+ static MPSGraphCache* getInstance() {
337
+ if (_instance_cache == nullptr) {
338
+ _instance_cache = new MPSGraphCache();
339
+ }
340
+ return _instance_cache;
341
+ }
342
+
343
+ ~MPSGraphCache() {
344
+ dispatch_release(serialQueue_);
345
+
346
+ for (const auto& i : cache_) {
347
+ delete i.second.cachedGraph_;
348
+ }
349
+ }
350
+
351
+ // Disallow the copy constructor and operator= functions
352
+ MPSGraphCache(const MPSGraphCache&) = delete;
353
+ void operator=(const MPSGraphCache&) = delete;
354
+
355
+ MPSCachedGraph* CreateCachedGraph(const std::string& key, CreateCachedGraphBlock createCacheBlock) {
356
+ __block MPSCachedGraph* cachedGraph = nil;
357
+
358
+ MPSCacheKey hash = std::hash<std::string>{}(key);
359
+
360
+ dispatch_sync_with_rethrow(serialQueue_, ^() {
361
+ // verify the cached entry doesn't already exist
362
+ if (cache_.count(hash) != 0) {
363
+ auto& entry = cache_.at(hash);
364
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached graph!\n");
365
+ cachedGraph = entry.cachedGraph_;
366
+ } else {
367
+ cachedGraph = createCacheBlock();
368
+ CacheEntry entry(key, cachedGraph);
369
+ cache_.emplace(hash, entry);
370
+ profileCachedGraph(entry);
371
+ }
372
+ });
373
+ return cachedGraph;
374
+ }
375
+
376
+ template <typename T>
377
+ inline T* CreateCachedGraphAs(const std::string& key, CreateCachedGraphBlock createCacheBlock) {
378
+ return static_cast<T*>(CreateCachedGraph(key, createCacheBlock));
379
+ }
380
+
381
+ MPSCachedGraph* LookUp(const std::string& key) const {
382
+ __block MPSCachedGraph* cachedGraph = nullptr;
383
+
384
+ MPSCacheKey hash = std::hash<std::string>{}(key);
385
+
386
+ dispatch_sync(serialQueue_, ^() {
387
+ if (cache_.count(hash) != 0) {
388
+ auto& entry = cache_.at(hash);
389
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(key == entry.key_, "Key collision in the MPS cached graph!\n");
390
+ cachedGraph = entry.cachedGraph_;
391
+ profileCachedGraph(entry);
392
+ }
393
+ });
394
+ return cachedGraph;
395
+ }
396
+
397
+ template <typename T>
398
+ inline T* LookUpAs(const std::string& key) const {
399
+ return static_cast<T*>(LookUp(key));
400
+ }
401
+
402
+ private:
403
+ MPSGraphCache() {
404
+ serialQueue_ = dispatch_queue_create("cache queue", DISPATCH_QUEUE_SERIAL);
405
+ }
406
+ // this is defined in OperationUtils.mm to not include
407
+ // MPSProfiler.h in header OperationUtils.h
408
+ void profileCachedGraph(const CacheEntry& cacheEntry) const;
409
+
410
+ static MPSGraphCache* _instance_cache;
411
+ std::unordered_map<MPSCacheKey, CacheEntry> cache_;
412
+ dispatch_queue_t serialQueue_ = nullptr;
413
+ };
414
+
415
+ // Common template for creating graph with a specified cache if missing
416
+ template <typename T>
417
+ inline T* LookUpOrCreateCachedGraph(const std::string& key, std::function<void(MPSGraph*, T*)> instantiate) {
418
+ auto cache_ = MPSGraphCache::getInstance();
419
+ if (auto rc = cache_->LookUpAs<T>(key)) {
420
+ return rc;
421
+ }
422
+ return cache_->CreateCachedGraphAs<T>(key, ^mps::MPSCachedGraph*() {
423
+ T* newCachedGraph = nil;
424
+ @autoreleasepool {
425
+ // Initialize graph
426
+ auto mpsGraph = mps::make_mps_graph();
427
+ newCachedGraph = new T(mpsGraph);
428
+ instantiate(mpsGraph, newCachedGraph);
429
+ }
430
+ return newCachedGraph;
431
+ });
432
+ }
433
+
434
+ // Common math operations
435
+ MPSGraphTensor* log1p(MPSGraph* mpsGraph, MPSGraphTensor* inputTensor);
436
+
437
+ /**
438
+ * Returns distance from lowest to highest element offset in given tensor.
439
+ */
440
+ size_t compute_storage_numel_distance(const TensorBase& t);
441
+
442
+ /**
443
+ * Checks whether tensor is mapped to a contiguous area in the storage.
444
+ */
445
+ inline bool is_dense_in_storage(const TensorBase& t) {
446
+ return compute_storage_numel_distance(t) == static_cast<size_t>(t.numel());
447
+ }
448
+
449
+ template <typename encoder_t,
450
+ typename = std::enable_if_t<std::is_same_v<id<MTLComputeCommandEncoder>, encoder_t> ||
451
+ std::is_same_v<id<MTLArgumentEncoder>, encoder_t>>>
452
+ static inline void mtl_setBuffer(encoder_t encoder, const TensorBase& t, unsigned idx) {
453
+ if (C10_UNLIKELY(t.device().type() == kCPU)) {
454
+ if constexpr (std::is_same_v<id<MTLComputeCommandEncoder>, encoder_t>) {
455
+ TORCH_CHECK(t.dim() == 0, "Passed CPU tensor to MPS op");
456
+ // MPS does not support doubles, silently downcast CPU scalar to float
457
+ if (C10_UNLIKELY(t.scalar_type() == kDouble)) {
458
+ auto val = static_cast<float>(*reinterpret_cast<const double*>(t.const_data_ptr()));
459
+ [encoder setBytes:&val length:sizeof(val) atIndex:idx];
460
+ return;
461
+ }
462
+ if (C10_UNLIKELY(t.scalar_type() == kComplexDouble)) {
463
+ auto val = static_cast<c10::complex<float>>(*reinterpret_cast<const c10::complex<double>*>(t.const_data_ptr()));
464
+ [encoder setBytes:&val length:sizeof(val) atIndex:idx];
465
+ return;
466
+ }
467
+ [encoder setBytes:t.storage().data() length:t.element_size() atIndex:idx];
468
+ } else {
469
+ TORCH_CHECK(false, "Passed CPU tensor to MPS op");
470
+ }
471
+ return;
472
+ }
473
+ [encoder setBuffer:getMTLBufferStorage(t) offset:t.storage_offset() * t.element_size() atIndex:idx];
474
+ }
475
+
476
+ // Implementation of setBytes for containers vs trivially copiable types must be separate
477
+ // Containers like `std::array` could have been uploaded directly, but `c10::ArrayRef`,
478
+ // while trivially copiable, includes padding which if copied as Metal shader parameters
479
+ // might overwrite other values
480
+ template <
481
+ typename T,
482
+ typename = std::enable_if_t<std::is_integral_v<T> || std::is_same_v<T, float> ||
483
+ (std::is_class_v<T> && std::is_trivially_copyable_v<T> && !detail::has_size_type_v<T>)>>
484
+ static inline void mtl_setBytes(id<MTLComputeCommandEncoder> encoder, const T val, unsigned idx) {
485
+ [encoder setBytes:&val length:sizeof(T) atIndex:idx];
486
+ }
487
+
488
+ template <typename Container, typename = std::enable_if_t<detail::has_size_type_v<Container>>>
489
+ static inline void mtl_setBytes(id<MTLComputeCommandEncoder> encoder, const Container& values, unsigned idx) {
490
+ [encoder setBytes:values.data() length:sizeof(typename Container::value_type) * values.size() atIndex:idx];
491
+ }
492
+
493
+ static inline void mtl_setBytes(id<MTLComputeCommandEncoder> encoder, const MPSScalar& s, unsigned idx) {
494
+ [encoder setBytes:&s.value length:s.size atIndex:idx];
495
+ }
496
+
497
+ static size_t iter_tensor_offset(TensorIteratorBase& iter, unsigned idx) {
498
+ // At the moment, MPS storage data is not the real GPU pointer, but rather a pointer to id<MTLBuffer> object
499
+ // But TensorIterator constructs data_ptr as if base was just a raw pointer
500
+ // Workaround this problem by computing an offset from the start of the tensor, which works for both
501
+ // tensor views and sliced 64-bit iterators
502
+ return reinterpret_cast<size_t>(iter.data_ptr(idx)) -
503
+ reinterpret_cast<size_t>(iter.tensor_base(idx).storage().data());
504
+ }
505
+
506
+ static inline void bind_iter_tensors(id<MTLComputeCommandEncoder> encoder,
507
+ TensorIteratorBase& iter,
508
+ std::optional<size_t> ntensors = std::nullopt) {
509
+ for (auto idx : c10::irange(ntensors.value_or(iter.ntensors()))) {
510
+ auto& t = iter.tensor_base(idx);
511
+ // Handle CPU scalars
512
+ if (C10_UNLIKELY(t.device().type() == kCPU)) {
513
+ mtl_setBuffer(encoder, t, idx);
514
+ continue;
515
+ }
516
+ auto offs = iter_tensor_offset(iter, idx);
517
+ [encoder setBuffer:getMTLBufferStorage(t) offset:offs atIndex:idx];
518
+ }
519
+ }
520
+
521
+ namespace detail {
522
+ template <typename T>
523
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, const T& val, unsigned idx) {
524
+ mtl_setBytes(encoder, val, idx);
525
+ }
526
+
527
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, id<MTLBuffer> val, unsigned idx) {
528
+ [encoder setBuffer:val offset:0 atIndex:idx];
529
+ }
530
+
531
+ template <>
532
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, const Tensor& val, unsigned idx) {
533
+ mtl_setBuffer(encoder, val, idx);
534
+ }
535
+
536
+ template <>
537
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, const std::optional<Tensor>& val, unsigned idx) {
538
+ if (val.has_value()) {
539
+ mtl_setBuffer(encoder, val.value(), idx);
540
+ }
541
+ }
542
+
543
+ template <>
544
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, const TensorBase& val, unsigned idx) {
545
+ mtl_setBuffer(encoder, val, idx);
546
+ }
547
+ // MPS does not support doubles, so cast it down to float before passing as an argument
548
+ template <>
549
+ inline void mtl_setArg(id<MTLComputeCommandEncoder> encoder, const double& val, unsigned idx) {
550
+ float val_f = static_cast<float>(val);
551
+ mtl_setBytes(encoder, val_f, idx);
552
+ }
553
+ } // namespace detail
554
+
555
+ template <unsigned idx = 0, typename T>
556
+ static inline void mtl_setArgs(id<MTLComputeCommandEncoder> encoder, const T& val) {
557
+ detail::mtl_setArg(encoder, val, idx);
558
+ }
559
+
560
+ template <unsigned idx = 0, typename T, typename... Args>
561
+ static inline void mtl_setArgs(id<MTLComputeCommandEncoder> encoder, const T& val, Args&&... args) {
562
+ detail::mtl_setArg(encoder, val, idx);
563
+ mtl_setArgs<idx + 1>(encoder, std::forward<Args>(args)...);
564
+ }
565
+
566
+ static inline void mtl_dispatch1DJob(id<MTLComputeCommandEncoder> encoder,
567
+ id<MTLComputePipelineState> cplState,
568
+ NSUInteger length) {
569
+ static_assert(sizeof(NSUInteger) == sizeof(uint64_t));
570
+ const auto maxThreadsPerGroup = [cplState maxTotalThreadsPerThreadgroup];
571
+ auto size = MTLSizeMake(length, 1, 1);
572
+ auto threadGroupSize = MTLSizeMake(std::min(maxThreadsPerGroup, length), 1, 1);
573
+ [encoder dispatchThreads:size threadsPerThreadgroup:threadGroupSize];
574
+ }
575
+
576
+ id<MTLBuffer> generateKernelDataOffsets(id<MTLComputeCommandEncoder> commandEncoder,
577
+ const TensorIteratorBase& iter,
578
+ bool use_64bit_index = false);
579
+
580
+ inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1) {
581
+ return @{p1.getMPSGraphTensor() : p1.getMPSGraphTensorData()};
582
+ }
583
+
584
+ inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2) {
585
+ return @{
586
+ p1.getMPSGraphTensor() : p1.getMPSGraphTensorData(),
587
+ p2.getMPSGraphTensor() : p2.getMPSGraphTensorData(),
588
+ };
589
+ }
590
+
591
+ inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2, Placeholder& p3) {
592
+ return @{
593
+ p1.getMPSGraphTensor() : p1.getMPSGraphTensorData(),
594
+ p2.getMPSGraphTensor() : p2.getMPSGraphTensorData(),
595
+ p3.getMPSGraphTensor() : p3.getMPSGraphTensorData(),
596
+ };
597
+ }
598
+
599
+ inline NSDictionary* dictionaryFromPlaceholders(Placeholder& p1, Placeholder& p2, Placeholder& p3, Placeholder& p4) {
600
+ return @{
601
+ p1.getMPSGraphTensor() : p1.getMPSGraphTensorData(),
602
+ p2.getMPSGraphTensor() : p2.getMPSGraphTensorData(),
603
+ p3.getMPSGraphTensor() : p3.getMPSGraphTensorData(),
604
+ p4.getMPSGraphTensor() : p4.getMPSGraphTensorData(),
605
+ };
606
+ }
607
+
608
+ inline void runMPSGraph(MPSStream* stream, MPSGraph* graph, NSDictionary* feeds, Placeholder& result) {
609
+ runMPSGraph(stream, graph, feeds, dictionaryFromPlaceholders(result));
610
+ }
611
+
612
+ // MPS yet to support double types, but starting from MacOS 14, supports bfloat16
613
+ inline bool supportedFloatingType(ScalarType dtype) {
614
+ return dtype == kFloat || dtype == kHalf || dtype == kBFloat16;
615
+ }
616
+
617
+ inline bool supportedFloatingType(const TensorBase& t) {
618
+ return supportedFloatingType(t.scalar_type());
619
+ }
620
+
621
+ inline bool supportedFloatingOrComplexType(ScalarType dtype) {
622
+ if (dtype == kComplexFloat || dtype == kComplexHalf) {
623
+ return true;
624
+ }
625
+ return supportedFloatingType(dtype);
626
+ }
627
+ inline bool supportedFloatingOrComplexType(const TensorBase& t) {
628
+ return supportedFloatingOrComplexType(t.scalar_type());
629
+ }
630
+
631
+ inline bool needsGather(const TensorBase& t) {
632
+ static const bool is_macOS_15_0_or_newer = is_macos_13_or_newer(MacOSVersion::MACOS_VER_15_0_PLUS);
633
+ return !is_macOS_15_0_or_newer && (!t.is_contiguous() || t.storage_offset());
634
+ }
635
+
636
+ template <typename T>
637
+ void MetalShaderLibrary::exec_unary_kernel_with_params(TensorIteratorBase& iter,
638
+ const std::string& name,
639
+ T params,
640
+ const std::string& params_type_name) {
641
+ using namespace at::mps;
642
+ // Decompose 64-bit tensor into 32-bit ones
643
+ if (!iter.can_use_32bit_indexing()) {
644
+ for (auto&& sub_iter : iter.with_32bit_indexing()) {
645
+ exec_unary_kernel_with_params(sub_iter, name, params, params_type_name);
646
+ }
647
+ return;
648
+ }
649
+
650
+ auto inputTensor = iter.input(0);
651
+ auto outputTensor = iter.output(0);
652
+ uint32_t length = iter.numel();
653
+ if (length == 0) {
654
+ return;
655
+ }
656
+ auto kernel_name = fmt::format("{}_{}_{}_{}{}",
657
+ name,
658
+ iter.is_contiguous() ? "dense" : "strided",
659
+ scalarToMetalTypeString(outputTensor),
660
+ scalarToMetalTypeString(inputTensor),
661
+ fmt::format("_{}", params_type_name));
662
+ @autoreleasepool {
663
+ auto cplState = getPipelineStateForFunc(kernel_name);
664
+
665
+ MPSStream* mpsStream = getCurrentMPSStream();
666
+ dispatch_sync(mpsStream->queue(), ^() {
667
+ auto computeEncoder = mpsStream->commandEncoder();
668
+
669
+ getMPSProfiler().beginProfileKernel(cplState, name, {inputTensor});
670
+
671
+ [computeEncoder setComputePipelineState:cplState];
672
+ bind_iter_tensors(computeEncoder, iter);
673
+ if (!iter.is_contiguous()) {
674
+ mtl_setArgs<2>(computeEncoder,
675
+ outputTensor.sizes(),
676
+ inputTensor.strides(),
677
+ outputTensor.strides(),
678
+ inputTensor.ndimension());
679
+ }
680
+ detail::mtl_setArg(computeEncoder, params, iter.is_contiguous() ? 2 : 6);
681
+ mtl_dispatch1DJob(computeEncoder, cplState, length);
682
+
683
+ getMPSProfiler().endProfileKernel(cplState);
684
+ });
685
+ }
686
+ }
687
+
688
+ template <typename T>
689
+ void MetalShaderLibrary::exec_binary_kernel_with_params(TensorIteratorBase& iter,
690
+ const std::string& name,
691
+ T params,
692
+ const std::string& params_type_name) {
693
+ using namespace mps;
694
+ // TODO: Figure a better place to downcast double scalars (probably in tensor iterator itself?)
695
+ // Right now running something like 1.0-torch.rand(5, device='mps') will create iterator with
696
+ // double as common dtype (because Python floating point are always 64-bit values)
697
+ TORCH_CHECK(iter.output().scalar_type() != at::kDouble, "float64 is not supported on MPS");
698
+
699
+ // Skip for empty iterators
700
+ if (iter.numel() == 0) {
701
+ return;
702
+ }
703
+
704
+ // Decompose 64-bit tensor into 32-bit ones
705
+ if (!iter.can_use_32bit_indexing()) {
706
+ for (auto&& sub_iter : iter.with_32bit_indexing()) {
707
+ exec_binary_kernel_with_params(sub_iter, name, params, params_type_name);
708
+ }
709
+ return;
710
+ }
711
+
712
+ auto convert_double_scalar = [](Tensor& t) {
713
+ if (t.dim() != 0) {
714
+ return;
715
+ }
716
+ if (t.scalar_type() == kDouble) {
717
+ t = t.to(kFloat);
718
+ } else if (t.scalar_type() == kComplexDouble) {
719
+ t = t.to(kComplexFloat);
720
+ }
721
+ };
722
+
723
+ Tensor input = iter.input(0);
724
+ Tensor other = iter.input(1);
725
+ Tensor out = iter.output();
726
+
727
+ convert_double_scalar(input);
728
+ convert_double_scalar(other);
729
+
730
+ MPSStream* mpsStream = getCurrentMPSStream();
731
+ const auto cast_needed = input.scalar_type() != other.scalar_type();
732
+ const auto suffix = iter.is_contiguous() ? "dense" : "strided";
733
+ // TODO: Implicitly pass both input and output types to non-cast kernels
734
+ const auto kernel_name = cast_needed
735
+ ? fmt::format("{}_{}_cast_{}_{}", name, suffix, scalarToMetalTypeString(out), params_type_name)
736
+ : fmt::format("{}_{}_{}_{}_{}",
737
+ name,
738
+ suffix,
739
+ scalarToMetalTypeString(out),
740
+ scalarToMetalTypeString(input),
741
+ params_type_name);
742
+ dispatch_sync_with_rethrow(mpsStream->queue(), ^() {
743
+ @autoreleasepool {
744
+ auto computeEncoder = mpsStream->commandEncoder();
745
+ auto binaryPSO = getPipelineStateForFunc(kernel_name);
746
+ // this function call is a no-op if MPS Profiler is not enabled
747
+ getMPSProfiler().beginProfileKernel(binaryPSO, kernel_name, {input, other});
748
+ [computeEncoder setComputePipelineState:binaryPSO];
749
+ // Set input and output tensors
750
+ bind_iter_tensors(computeEncoder, iter);
751
+ // Iterator is contiguous if all of its elements are dense in storage,
752
+ // i.e. it's true for both row-first and column-first tensors
753
+ if (iter.is_contiguous()) {
754
+ detail::mtl_setArg(computeEncoder, params, 3);
755
+ if (cast_needed) {
756
+ std::array<int, 4> size_and_types = {static_cast<int>(c10::elementSize(input.scalar_type())),
757
+ static_cast<int>(c10::elementSize(other.scalar_type())),
758
+ static_cast<int>(input.scalar_type()),
759
+ static_cast<int>(other.scalar_type())};
760
+ mtl_setBytes(computeEncoder, size_and_types, 4);
761
+ }
762
+ } else {
763
+ // Please note that shapes and strides of the iterator might be
764
+ // different than that of its operands, for example binary op
765
+ // between 4x4 tensor and scalar will result in 1D 16 element iterator
766
+ std::array<int, 4> ndim_and_types = {iter.ndim(),
767
+ static_cast<int>(input.scalar_type()),
768
+ static_cast<int>(other.scalar_type()),
769
+ static_cast<int>(out.scalar_type())};
770
+ mtl_setArgs<3>(
771
+ computeEncoder, params, iter.shape(), iter.strides(0), iter.strides(1), iter.strides(2), ndim_and_types);
772
+ }
773
+ mtl_dispatch1DJob(computeEncoder, binaryPSO, iter.numel());
774
+ getMPSProfiler().endProfileKernel(binaryPSO);
775
+ }
776
+ });
777
+ }
778
+
779
+ // Checks if one tensor is broadcastable into another
780
+ static bool is_dense_broadcastable(const Tensor& from, const Tensor& into) {
781
+ if (!from.is_contiguous() || !into.is_contiguous()) {
782
+ return false;
783
+ }
784
+ bool checking_squeezable_dims = false;
785
+ for (const auto dim : c10::irange(from.ndimension())) {
786
+ if (checking_squeezable_dims) {
787
+ if (from.size(-dim - 1) == 1) {
788
+ continue;
789
+ }
790
+ return false;
791
+ }
792
+ checking_squeezable_dims = from.size(-dim - 1) != into.size(-dim - 1);
793
+ }
794
+ return true;
795
+ }
796
+
797
+ } // namespace at::native::mps
798
+
799
+ #else
800
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
801
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/TensorFactory.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #define AT_DISPATCH_MPS_TYPES(TYPE, NAME, ...) \
5
+ AT_DISPATCH_SWITCH( \
6
+ TYPE, \
7
+ NAME, \
8
+ AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__) AT_DISPATCH_CASE( \
9
+ at::ScalarType::Half, \
10
+ __VA_ARGS__) AT_DISPATCH_CASE(at::ScalarType::BFloat16, __VA_ARGS__) \
11
+ AT_DISPATCH_CASE(at::ScalarType::Long, __VA_ARGS__) \
12
+ AT_DISPATCH_CASE(at::ScalarType::Int, __VA_ARGS__) \
13
+ AT_DISPATCH_CASE(at::ScalarType::Short, __VA_ARGS__) \
14
+ AT_DISPATCH_CASE(at::ScalarType::Char, __VA_ARGS__) \
15
+ AT_DISPATCH_CASE(at::ScalarType::Byte, __VA_ARGS__))
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/native/mps/kernels/Activation.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ template <typename T>
5
+ struct ELUParams {
6
+ T alpha;
7
+ T scale;
8
+ T input_scale;
9
+ };
10
+
11
+ template <typename T>
12
+ struct ELUBackwardParams {
13
+ T alpha;
14
+ T scale;
15
+ T input_scale;
16
+ bool is_result;
17
+ };
18
+
19
+ #else
20
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
21
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/EmbeddingBag.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ #ifdef __METAL__
6
+ enum class EmbeddingBagMode { SUM = 0, MEAN, MAX };
7
+ #else
8
+ #include <ATen/native/EmbeddingBag.h>
9
+ using at::native::EmbeddingBagMode;
10
+ #endif
11
+
12
+ template <typename idx_type_t = uint32_t>
13
+ struct EmbeddingBagParams {
14
+ ::c10::metal::array<idx_type_t, 2> weight_strides;
15
+ ::c10::metal::array<idx_type_t, 2> output_strides;
16
+ ::c10::metal::array<idx_type_t, 2> max_indices_strides;
17
+
18
+ bool use_per_sample_weights;
19
+ idx_type_t per_sample_weights_stride;
20
+
21
+ idx_type_t num_indices;
22
+ idx_type_t num_bags;
23
+ idx_type_t feature_size;
24
+ idx_type_t num_weights;
25
+
26
+ EmbeddingBagMode mode;
27
+ int64_t padding_idx;
28
+ };
29
+
30
+ template <typename idx_type_t = uint32_t>
31
+ struct EmbeddingBagBackwardParams {
32
+ ::c10::metal::array<idx_type_t, 2> weight_grad_strides;
33
+ ::c10::metal::array<idx_type_t, 2> output_grad_strides;
34
+ ::c10::metal::array<idx_type_t, 2> max_indices_strides;
35
+ bool use_per_sample_weights;
36
+ idx_type_t per_sample_weights_stride;
37
+ idx_type_t feature_size;
38
+ EmbeddingBagMode mode;
39
+ int64_t padding_idx;
40
+ };
41
+
42
+ template <typename idx_type_t = uint32_t>
43
+ struct EmbeddingBagPerSampleWeightsBackwardParams {
44
+ ::c10::metal::array<idx_type_t, 2> output_grad_strides;
45
+ ::c10::metal::array<idx_type_t, 2> weight_strides;
46
+ idx_type_t per_sample_weights_grad_stride;
47
+ idx_type_t feature_size;
48
+ int64_t padding_idx;
49
+ };
50
+
51
+ #else
52
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
53
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/GridSampler.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ #ifdef __METAL__
6
+ enum class GridSamplerInterpolation { Bilinear, Nearest, Bicubic };
7
+ enum class GridSamplerPadding { Zeros, Border, Reflection };
8
+ #else
9
+ #include <ATen/native/GridSamplerUtils.h>
10
+ using at::native::GridSamplerInterpolation;
11
+ using at::native::GridSamplerPadding;
12
+ #endif
13
+
14
+ template <unsigned N = 5, typename idx_type_t = int32_t>
15
+ struct GridSamplerParams {
16
+ int32_t sampler_dims;
17
+ ::c10::metal::array<idx_type_t, N> output_sizes;
18
+ ::c10::metal::array<idx_type_t, N> output_strides;
19
+ ::c10::metal::array<idx_type_t, N> input_sizes;
20
+ ::c10::metal::array<idx_type_t, N> input_strides;
21
+ ::c10::metal::array<idx_type_t, N> grid_sizes;
22
+ ::c10::metal::array<idx_type_t, N> grid_strides;
23
+ GridSamplerInterpolation interpolation_mode;
24
+ GridSamplerPadding padding_mode;
25
+ bool align_corners;
26
+ };
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/LinearAlgebra.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ template <unsigned N = c10::metal::max_ndim>
6
+ struct OrgqrParams {
7
+ int32_t num_batch_dims;
8
+
9
+ uint32_t m;
10
+ uint32_t n;
11
+ uint32_t k;
12
+
13
+ ::c10::metal::array<uint32_t, N> A_strides;
14
+ ::c10::metal::array<uint32_t, N> tau_strides;
15
+ ::c10::metal::array<uint32_t, N> H_strides;
16
+ ::c10::metal::array<uint32_t, N> H_sizes;
17
+ };
18
+
19
+ struct UnpackPivotsParams {
20
+ uint32_t perm_batch_stride;
21
+ uint32_t pivots_batch_stride;
22
+ uint32_t dim_size;
23
+ };
24
+
25
+ #else
26
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
27
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Pooling.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ // N is the maximum allowed number of dimensions in the input and outputs. The
6
+ // maximum allowed pooling dimensions is N-2, because the input may have up to 2
7
+ // leading dimensions that are not pooled. To support up to 3-D pooling, N=5 is
8
+ // the default.
9
+ template <unsigned N = 5, typename idx_type_t = int32_t>
10
+ struct PoolingParams {
11
+ int32_t dims;
12
+ int32_t pooling_dims;
13
+ ::c10::metal::array<idx_type_t, N> input_sizes;
14
+ ::c10::metal::array<idx_type_t, N> input_strides;
15
+ ::c10::metal::array<idx_type_t, N> output_sizes;
16
+ ::c10::metal::array<idx_type_t, N> output_strides;
17
+ ::c10::metal::array<idx_type_t, N> indices_sizes;
18
+ ::c10::metal::array<idx_type_t, N> indices_strides;
19
+ ::c10::metal::array<idx_type_t, N - 2> kernel_size;
20
+ ::c10::metal::array<idx_type_t, N - 2> stride;
21
+ ::c10::metal::array<idx_type_t, N - 2> padding;
22
+ ::c10::metal::array<idx_type_t, N - 2> dilation;
23
+ bool return_indices;
24
+ };
25
+
26
+ template <unsigned N = 5, typename idx_type_t = int32_t>
27
+ struct AvgPoolingParams {
28
+ int32_t dims;
29
+ int32_t pooling_dims;
30
+ ::c10::metal::array<idx_type_t, N> input_sizes;
31
+ ::c10::metal::array<idx_type_t, N> input_strides;
32
+ ::c10::metal::array<idx_type_t, N> output_sizes;
33
+ ::c10::metal::array<idx_type_t, N> output_strides;
34
+ ::c10::metal::array<idx_type_t, N - 2> kernel_size;
35
+ ::c10::metal::array<idx_type_t, N - 2> stride;
36
+ ::c10::metal::array<idx_type_t, N - 2> padding;
37
+ bool count_include_pad;
38
+ bool has_divisor_override;
39
+ int32_t divisor_override;
40
+ };
41
+
42
+ template <unsigned N = 5, typename idx_type_t = int32_t>
43
+ struct PoolingBackwardParams {
44
+ int32_t dims;
45
+ int32_t pooling_dims;
46
+ ::c10::metal::array<idx_type_t, N> grad_input_sizes;
47
+ ::c10::metal::array<idx_type_t, N> grad_input_strides;
48
+ ::c10::metal::array<idx_type_t, N> grad_output_sizes;
49
+ ::c10::metal::array<idx_type_t, N> grad_output_strides;
50
+ ::c10::metal::array<idx_type_t, N> indices_strides;
51
+ };
52
+
53
+ template <unsigned N = 5, typename idx_type_t = int32_t>
54
+ struct MaxUnpoolingParams {
55
+ int32_t dims;
56
+ int32_t pooling_dims;
57
+ ::c10::metal::array<idx_type_t, N> input_sizes;
58
+ ::c10::metal::array<idx_type_t, N> input_strides;
59
+ ::c10::metal::array<idx_type_t, N> output_sizes;
60
+ ::c10::metal::array<idx_type_t, N> output_strides;
61
+ ::c10::metal::array<idx_type_t, N> indices_strides;
62
+ };
63
+
64
+ #else
65
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
66
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Shape.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ template <typename idx_type_t = int64_t, unsigned N = c10::metal::max_ndim>
6
+ struct CatSharedParams {
7
+ int32_t ndim;
8
+ int32_t cat_dim;
9
+ ::c10::metal::array<idx_type_t, N> output_strides;
10
+ ::c10::metal::array<idx_type_t, N> output_sizes;
11
+ };
12
+
13
+ template <typename idx_type_t = int64_t, unsigned N = c10::metal::max_ndim>
14
+ struct CatInputParams {
15
+ idx_type_t cat_dim_offset;
16
+ idx_type_t input_element_offset;
17
+ ::c10::metal::array<idx_type_t, N> input_strides;
18
+ ::c10::metal::array<idx_type_t, N> input_sizes;
19
+ };
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/native/mps/kernels/TensorCompare.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ template <typename T>
5
+ struct ClampScalarParams {
6
+ T min;
7
+ T max;
8
+ };
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/UpSample.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/metal/common.h>
4
+
5
+ template <unsigned N = 5>
6
+ struct UpsampleParams {
7
+ ::c10::metal::array<uint64_t, N> input_strides;
8
+ ::c10::metal::array<uint64_t, N> input_sizes;
9
+ ::c10::metal::array<uint64_t, N> output_strides;
10
+ ::c10::metal::array<uint64_t, N> output_sizes;
11
+ ::c10::metal::array<float, N - 2> scales;
12
+ bool align_corners;
13
+ };
14
+
15
+ #else
16
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
17
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/BinaryKernel.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at::native::mps {
5
+ void binary_op_kernel(
6
+ const std::string func_name,
7
+ const Tensor& input,
8
+ const Tensor& other,
9
+ const Tensor& output,
10
+ const std::optional<Scalar> alpha = std::nullopt);
11
+ } // namespace at::native::mps
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/native/mps/operations/FusedAdamAmsgradKernelImpl.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native::mps {
6
+
7
+ void _fused_adam_amsgrad_mps_impl_(
8
+ TensorList params,
9
+ TensorList grads,
10
+ TensorList exp_avgs,
11
+ TensorList exp_avg_sqs,
12
+ TensorList max_exp_avg_sqs,
13
+ TensorList state_steps,
14
+ const double lr,
15
+ const double beta1,
16
+ const double beta2,
17
+ const double weight_decay,
18
+ const double eps,
19
+ const bool maximize,
20
+ const std::optional<Tensor>& grad_scale,
21
+ const std::optional<Tensor>& found_inf);
22
+
23
+ void _fused_adam_amsgrad_mps_impl_(
24
+ TensorList params,
25
+ TensorList grads,
26
+ TensorList exp_avgs,
27
+ TensorList exp_avg_sqs,
28
+ TensorList max_exp_avg_sqs,
29
+ TensorList state_steps,
30
+ const at::Tensor& lr,
31
+ const double beta1,
32
+ const double beta2,
33
+ const double weight_decay,
34
+ const double eps,
35
+ const bool maximize,
36
+ const std::optional<at::Tensor>& grad_scale,
37
+ const std::optional<at::Tensor>& found_inf);
38
+
39
+ } // namespace at::native::mps
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/native/mps/operations/FusedAdamKernelImpl.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native::mps {
6
+
7
+ void _fused_adam_mps_impl_(
8
+ TensorList params,
9
+ TensorList grads,
10
+ TensorList exp_avgs,
11
+ TensorList exp_avg_sqs,
12
+ TensorList state_steps,
13
+ const double lr,
14
+ const double beta1,
15
+ const double beta2,
16
+ const double weight_decay,
17
+ const double eps,
18
+ const bool maximize,
19
+ const std::optional<Tensor>& grad_scale,
20
+ const std::optional<Tensor>& found_inf);
21
+
22
+ void _fused_adam_mps_impl_(
23
+ TensorList params,
24
+ TensorList grads,
25
+ TensorList exp_avgs,
26
+ TensorList exp_avg_sqs,
27
+ TensorList state_steps,
28
+ const Tensor& lr,
29
+ const double beta1,
30
+ const double beta2,
31
+ const double weight_decay,
32
+ const double eps,
33
+ const bool maximize,
34
+ const std::optional<Tensor>& grad_scale,
35
+ const std::optional<Tensor>& found_inf);
36
+ } // namespace at::native::mps
37
+
38
+ #else
39
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
40
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamWAmsgradKernelImpl.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native::mps {
6
+
7
+ void _fused_adamw_amsgrad_mps_impl_(
8
+ TensorList params,
9
+ TensorList grads,
10
+ TensorList exp_avgs,
11
+ TensorList exp_avg_sqs,
12
+ TensorList max_exp_avg_sqs,
13
+ TensorList state_steps,
14
+ const double lr,
15
+ const double beta1,
16
+ const double beta2,
17
+ const double weight_decay,
18
+ const double eps,
19
+ const bool maximize,
20
+ const std::optional<Tensor>& grad_scale,
21
+ const std::optional<Tensor>& found_inf);
22
+
23
+ void _fused_adamw_amsgrad_mps_impl_(
24
+ TensorList params,
25
+ TensorList grads,
26
+ TensorList exp_avgs,
27
+ TensorList exp_avg_sqs,
28
+ TensorList max_exp_avg_sqs,
29
+ TensorList state_steps,
30
+ const Tensor& lr,
31
+ const double beta1,
32
+ const double beta2,
33
+ const double weight_decay,
34
+ const double eps,
35
+ const bool maximize,
36
+ const std::optional<Tensor>& grad_scale,
37
+ const std::optional<Tensor>& found_inf);
38
+ } // namespace at::native::mps
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/native/mps/operations/FusedAdamWKernelImpl.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native::mps {
6
+
7
+ void _fused_adamw_mps_impl_(
8
+ TensorList params,
9
+ TensorList grads,
10
+ TensorList exp_avgs,
11
+ TensorList exp_avg_sqs,
12
+ TensorList state_steps,
13
+ const double lr,
14
+ const double beta1,
15
+ const double beta2,
16
+ const double weight_decay,
17
+ const double eps,
18
+ const bool maximize,
19
+ const std::optional<Tensor>& grad_scale,
20
+ const std::optional<Tensor>& found_inf);
21
+
22
+ void _fused_adamw_mps_impl_(
23
+ TensorList params,
24
+ TensorList grads,
25
+ TensorList exp_avgs,
26
+ TensorList exp_avg_sqs,
27
+ TensorList state_steps,
28
+ const Tensor& lr,
29
+ const double beta1,
30
+ const double beta2,
31
+ const double weight_decay,
32
+ const double eps,
33
+ const bool maximize,
34
+ const std::optional<Tensor>& grad_scale,
35
+ const std::optional<Tensor>& found_inf);
36
+
37
+ } // namespace at::native::mps
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/native/mps/operations/MultiTensorApply.h ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/mps/MPSProfiler.h>
5
+ #include <ATen/native/mps/OperationUtils.h>
6
+
7
+ static_assert(sizeof(bool) == 1);
8
+
9
+ namespace at::native::mps {
10
+
11
+ static constexpr int64_t kChunkSize = 65536;
12
+ static constexpr int64_t kmaxThreadGroups = 32;
13
+ static constexpr int64_t kmaxTensors = 32;
14
+
15
+ struct MetadataArguments { // the size of this struct must be less than 4 kilobytes
16
+ uint64_t numels[kmaxTensors];
17
+ uint64_t threadgroup_to_tensor[kmaxThreadGroups];
18
+ uint64_t threadgroup_to_chunk[kmaxThreadGroups];
19
+ };
20
+
21
+ struct FusedAdamEncodingFunctor {
22
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
23
+ id<MTLBuffer>& tensorArgumentBuffer,
24
+ const MetadataArguments& metadata_arguments,
25
+ const double lr,
26
+ const double beta1,
27
+ const double beta2,
28
+ const double weight_decay,
29
+ const double eps,
30
+ const bool maximize) const {
31
+ mtl_setArgs(
32
+ computeEncoder, tensorArgumentBuffer, metadata_arguments, lr, beta1, beta2, weight_decay, eps, maximize);
33
+ }
34
+
35
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
36
+ id<MTLBuffer>& tensorArgumentBuffer,
37
+ const MetadataArguments& metadata_arguments,
38
+ const at::Tensor& lr,
39
+ const double beta1,
40
+ const double beta2,
41
+ const double weight_decay,
42
+ const double eps,
43
+ const bool maximize) const {
44
+ mtl_setArgs(
45
+ computeEncoder, tensorArgumentBuffer, metadata_arguments, lr, beta1, beta2, weight_decay, eps, maximize);
46
+ }
47
+ };
48
+
49
+ template <bool momentum>
50
+ struct FusedSgdEncodingFunctor {};
51
+
52
+ template <>
53
+ struct FusedSgdEncodingFunctor<true> {
54
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
55
+ id<MTLBuffer>& tensorArgumentBuffer,
56
+ const MetadataArguments& metadata_arguments,
57
+ const double weight_decay,
58
+ const double momentum,
59
+ const double lr,
60
+ const double dampening,
61
+ const bool nesterov,
62
+ const bool maximize,
63
+ const bool is_first_step) const {
64
+ mtl_setArgs(computeEncoder,
65
+ tensorArgumentBuffer,
66
+ metadata_arguments,
67
+ weight_decay,
68
+ momentum,
69
+ lr,
70
+ dampening,
71
+ nesterov,
72
+ maximize,
73
+ is_first_step);
74
+ }
75
+
76
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
77
+ id<MTLBuffer>& tensorArgumentBuffer,
78
+ const MetadataArguments& metadata_arguments,
79
+ const double weight_decay,
80
+ const double momentum,
81
+ const at::Tensor& lr,
82
+ const double dampening,
83
+ const bool nesterov,
84
+ const bool maximize,
85
+ const bool is_first_step) const {
86
+ mtl_setArgs(computeEncoder,
87
+ tensorArgumentBuffer,
88
+ metadata_arguments,
89
+ weight_decay,
90
+ momentum,
91
+ lr,
92
+ dampening,
93
+ nesterov,
94
+ maximize,
95
+ is_first_step);
96
+ }
97
+ };
98
+
99
+ template <>
100
+ struct FusedSgdEncodingFunctor<false> {
101
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
102
+ id<MTLBuffer>& tensorArgumentBuffer,
103
+ const MetadataArguments& metadata_arguments,
104
+ const double weight_decay,
105
+ const double lr,
106
+ const bool maximize) const {
107
+ mtl_setArgs(computeEncoder, tensorArgumentBuffer, metadata_arguments, weight_decay, lr, maximize);
108
+ }
109
+
110
+ void operator()(id<MTLComputeCommandEncoder>& computeEncoder,
111
+ id<MTLBuffer>& tensorArgumentBuffer,
112
+ const MetadataArguments& metadata_arguments,
113
+ const double weight_decay,
114
+ const at::Tensor& lr,
115
+ const bool maximize) const {
116
+ mtl_setArgs(computeEncoder, tensorArgumentBuffer, metadata_arguments, weight_decay, lr, maximize);
117
+ }
118
+ };
119
+
120
+ std::pair<id<MTLComputePipelineState>, id<MTLFunction>> getFusedAdamCPLState(const std::string& fname);
121
+ template <int depth, uint32_t kThreadGroupSize, typename encoder_func_t, typename... ArgTypes>
122
+ static void multi_tensor_apply_for_fused_optimizer(const std::string& kernel_name,
123
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
124
+ at::TensorList state_steps,
125
+ encoder_func_t encode,
126
+ ArgTypes... args) {
127
+ const auto num_tensors = tensor_lists[0].size();
128
+
129
+ if (num_tensors == 0) {
130
+ return;
131
+ }
132
+
133
+ TORCH_CHECK(tensor_lists.size() == depth, "Number of tensor lists has to match the depth");
134
+ for (const auto& d : c10::irange(depth)) {
135
+ const auto scalar_type = tensor_lists[d][0].scalar_type();
136
+ TORCH_CHECK(scalar_type == kFloat || scalar_type == kHalf || scalar_type == kBFloat16,
137
+ "Only float, bfloat and half are supported");
138
+ }
139
+
140
+ id<MTLDevice> device = MPSDevice::getInstance()->device();
141
+ MPSStream* mpsStream = getCurrentMPSStream();
142
+
143
+ // Remove comment for debugging
144
+ /*
145
+ mpsStream->addCompletedHandler(^(id<MTLCommandBuffer> cb) {
146
+ [cb.logs enumerateObjectsUsingBlock:^(NSString* log, NSUInteger idx, BOOL* stop) {
147
+ NSLog(@"MPSStream: %@", log);
148
+ }
149
+ ];
150
+ });
151
+ */
152
+
153
+ dispatch_sync_with_rethrow(mpsStream->queue(), ^() {
154
+ @autoreleasepool {
155
+ id<MTLComputeCommandEncoder> computeEncoder = mpsStream->commandEncoder();
156
+ auto [fusedOptimizerPSO, fusedOptimizerFunc] = getFusedAdamCPLState(kernel_name);
157
+
158
+ // this function call is a no-op if MPS Profiler is not enabled
159
+ getMPSProfiler().beginProfileKernel(fusedOptimizerPSO, kernel_name, {tensor_lists[0]});
160
+
161
+ [computeEncoder setComputePipelineState:fusedOptimizerPSO];
162
+
163
+ // BufferIndex is the index in the kernel function
164
+ auto tensorArgumentEncoder = [[fusedOptimizerFunc newArgumentEncoderWithBufferIndex:0] autorelease];
165
+ id<MTLBuffer> tensorArgumentBuffer = [[device newBufferWithLength:tensorArgumentEncoder.encodedLength
166
+ options:0] autorelease];
167
+ [tensorArgumentEncoder setArgumentBuffer:tensorArgumentBuffer offset:0];
168
+
169
+ int64_t tensor_loc = 0;
170
+ int64_t threadgroup_loc = 0;
171
+ MetadataArguments metadata_arguments;
172
+
173
+ for (const auto tensor_index : c10::irange(num_tensors)) {
174
+ // short-circuit to avoid adding empty tensors to tensorListMeta
175
+ if (tensor_lists[0][tensor_index].numel() == 0) {
176
+ continue;
177
+ }
178
+
179
+ for (const auto& d : c10::irange(depth)) {
180
+ mtl_setBuffer(tensorArgumentEncoder, tensor_lists[d][tensor_index], d * kmaxTensors + tensor_loc);
181
+ [computeEncoder useResource:getMTLBufferStorage(tensor_lists[d][tensor_index])
182
+ usage:MTLResourceUsageRead | MTLResourceUsageWrite];
183
+ }
184
+ if (!state_steps.empty()) {
185
+ mtl_setBuffer(tensorArgumentEncoder, state_steps[tensor_index], depth * kmaxTensors + tensor_loc);
186
+ [computeEncoder useResource:getMTLBufferStorage(state_steps[tensor_index]) usage:MTLResourceUsageRead];
187
+ }
188
+ metadata_arguments.numels[tensor_loc] = tensor_lists[0][tensor_index].numel();
189
+
190
+ tensor_loc++;
191
+
192
+ const auto numel = tensor_lists[0][tensor_index].numel();
193
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
194
+ TORCH_CHECK(chunks > -1);
195
+
196
+ for (const auto& chunk : c10::irange(chunks)) {
197
+ metadata_arguments.threadgroup_to_tensor[threadgroup_loc] = tensor_loc - 1;
198
+ metadata_arguments.threadgroup_to_chunk[threadgroup_loc] = chunk;
199
+
200
+ threadgroup_loc++;
201
+
202
+ const auto tensor_full = tensor_loc == kmaxTensors && chunk == chunks - 1;
203
+ // Reach the maximum threadgroups per dispatch
204
+ const auto blocks_full = threadgroup_loc == kmaxThreadGroups;
205
+
206
+ if (tensor_full || blocks_full) {
207
+ encode(computeEncoder, tensorArgumentBuffer, metadata_arguments, args...);
208
+ MTLSize gridSize = MTLSizeMake(threadgroup_loc, 1, 1);
209
+ uint32_t maxThreadsPerGroup = [fusedOptimizerPSO maxTotalThreadsPerThreadgroup];
210
+ MTLSize threadGroupSize = MTLSizeMake(std::min(maxThreadsPerGroup, kThreadGroupSize), 1, 1);
211
+ [computeEncoder dispatchThreadgroups:gridSize threadsPerThreadgroup:threadGroupSize];
212
+
213
+ // Reset
214
+ threadgroup_loc = 0;
215
+ if (chunk == chunks - 1) {
216
+ // last chunk
217
+ tensor_loc = 0;
218
+ tensorArgumentBuffer = [[device newBufferWithLength:tensorArgumentEncoder.encodedLength
219
+ options:0] autorelease];
220
+ [tensorArgumentEncoder setArgumentBuffer:tensorArgumentBuffer offset:0];
221
+ } else {
222
+ // reuse the current tensor since the current one isn't done.
223
+ metadata_arguments.numels[0] = metadata_arguments.numels[tensor_loc - 1];
224
+
225
+ tensorArgumentBuffer = [[device newBufferWithLength:tensorArgumentEncoder.encodedLength
226
+ options:0] autorelease];
227
+ [tensorArgumentEncoder setArgumentBuffer:tensorArgumentBuffer offset:0];
228
+
229
+ for (const auto& d : c10::irange(depth)) {
230
+ mtl_setBuffer(tensorArgumentEncoder, tensor_lists[d][tensor_index], d * kmaxTensors);
231
+ [computeEncoder useResource:getMTLBufferStorage(tensor_lists[d][tensor_index])
232
+ usage:MTLResourceUsageWrite | MTLResourceUsageRead];
233
+ }
234
+ if (!state_steps.empty()) {
235
+ mtl_setBuffer(tensorArgumentEncoder, state_steps[tensor_index], depth * kmaxTensors);
236
+ [computeEncoder useResource:getMTLBufferStorage(state_steps[tensor_index]) usage:MTLResourceUsageRead];
237
+ }
238
+ tensor_loc = 1;
239
+ }
240
+ }
241
+ }
242
+ }
243
+
244
+ if (threadgroup_loc != 0) {
245
+ encode(computeEncoder, tensorArgumentBuffer, metadata_arguments, args...);
246
+ MTLSize gridSize = MTLSizeMake(threadgroup_loc, 1, 1);
247
+ uint32_t maxThreadsPerGroup = [fusedOptimizerPSO maxTotalThreadsPerThreadgroup];
248
+ MTLSize threadGroupSize = MTLSizeMake(std::min(maxThreadsPerGroup, kThreadGroupSize), 1, 1);
249
+ [computeEncoder dispatchThreadgroups:gridSize threadsPerThreadgroup:threadGroupSize];
250
+ }
251
+
252
+ getMPSProfiler().endProfileKernel(fusedOptimizerPSO);
253
+ }
254
+ });
255
+ }
256
+
257
+ std::pair<id<MTLComputePipelineState>, id<MTLFunction>> getAmpCPLState(const std::string& fname);
258
+ template <int depth, typename... ArgTypes>
259
+ void multi_tensor_apply(const std::string& kernel_name,
260
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
261
+ ArgTypes... args) {
262
+ const auto num_tensors = tensor_lists[0].size();
263
+ if (num_tensors == 0) {
264
+ return;
265
+ }
266
+
267
+ TORCH_CHECK(tensor_lists.size() == depth, "Number of tensor lists must match depth.");
268
+
269
+ id<MTLDevice> device = MPSDevice::getInstance()->device();
270
+ MPSStream* mpsStream = getCurrentMPSStream();
271
+
272
+ dispatch_sync_with_rethrow(mpsStream->queue(), ^() {
273
+ @autoreleasepool {
274
+ id<MTLComputeCommandEncoder> computeEncoder = mpsStream->commandEncoder();
275
+ auto [pipeline, function] = getAmpCPLState(kernel_name);
276
+ [computeEncoder setComputePipelineState:pipeline];
277
+
278
+ id<MTLArgumentEncoder> argumentEncoder = [function newArgumentEncoderWithBufferIndex:0];
279
+ auto tensorArgumentBuffer = [[device newBufferWithLength:argumentEncoder.encodedLength options:0] autorelease];
280
+ [argumentEncoder setArgumentBuffer:tensorArgumentBuffer offset:0];
281
+
282
+ int tensor_loc = 0;
283
+ int threadgroup_loc = 0;
284
+ MetadataArguments metadata_arguments;
285
+ std::memset(&metadata_arguments, 0, sizeof(metadata_arguments));
286
+
287
+ for (size_t t = 0; t < num_tensors; t++) {
288
+ if (tensor_lists[0][t].numel() == 0)
289
+ continue;
290
+
291
+ // bind each tensor in this list to the correct slots across depths
292
+ for (int d = 0; d < depth; d++) {
293
+ mtl_setBuffer(argumentEncoder, tensor_lists[d][t], d * kmaxTensors + tensor_loc);
294
+ [computeEncoder useResource:getMTLBufferStorage(tensor_lists[d][t])
295
+ usage:(MTLResourceUsageRead | MTLResourceUsageWrite)];
296
+ }
297
+
298
+ // save number of elements for this tensor
299
+ metadata_arguments.numels[tensor_loc] = tensor_lists[0][t].numel();
300
+ int currentTensorIndex = tensor_loc;
301
+ tensor_loc++;
302
+
303
+ const auto numel = tensor_lists[0][t].numel();
304
+ const auto chunks = numel / kChunkSize + ((numel % kChunkSize) ? 1 : 0);
305
+
306
+ // process tensor in chunks based on max chunk size
307
+ for (uint chunk = 0; chunk < chunks; chunk++) {
308
+ metadata_arguments.threadgroup_to_tensor[threadgroup_loc] = currentTensorIndex;
309
+ metadata_arguments.threadgroup_to_chunk[threadgroup_loc] = chunk;
310
+ threadgroup_loc++;
311
+
312
+ // dispatch when we've filled the threadgroup array or finished the chunks
313
+ const bool dispatch_now = (threadgroup_loc == kmaxThreadGroups) || (chunk == chunks - 1);
314
+ if (dispatch_now) {
315
+ // check for a partial dispatch (i.e. more chunks remain for the current tensor)
316
+ bool partial = (chunk != chunks - 1);
317
+ uint carried_numels = 0;
318
+ if (partial) {
319
+ carried_numels = metadata_arguments.numels[currentTensorIndex];
320
+ }
321
+
322
+ mtl_setArgs(computeEncoder, tensorArgumentBuffer, metadata_arguments, args...);
323
+ MTLSize gridSize = MTLSizeMake(threadgroup_loc, 1, 1);
324
+ uint32_t maxThreads = [pipeline maxTotalThreadsPerThreadgroup];
325
+ MTLSize threadGroupSize = MTLSizeMake(std::min(maxThreads, (uint32_t)64), 1, 1);
326
+ [computeEncoder dispatchThreadgroups:gridSize threadsPerThreadgroup:threadGroupSize];
327
+
328
+ // prepare for the next batch: reset threadgroup count and create a new buffer
329
+ threadgroup_loc = 0;
330
+ tensorArgumentBuffer = [[device newBufferWithLength:argumentEncoder.encodedLength options:0] autorelease];
331
+ [argumentEncoder setArgumentBuffer:tensorArgumentBuffer offset:0];
332
+
333
+ if (partial) {
334
+ // for a partial dispatch, rebind the partially processed tensor to slot 0
335
+ // so that its metadata is in the correct location
336
+ for (int d = 0; d < depth; d++) {
337
+ mtl_setBuffer(argumentEncoder, tensor_lists[d][t], d * kmaxTensors + 0);
338
+ [computeEncoder useResource:getMTLBufferStorage(tensor_lists[d][t])
339
+ usage:(MTLResourceUsageRead | MTLResourceUsageWrite)];
340
+ }
341
+ metadata_arguments.numels[0] = carried_numels;
342
+ // the currently processed tensor now lives at index 0
343
+ currentTensorIndex = 0;
344
+ tensor_loc = 1;
345
+ } else {
346
+ tensor_loc = 0;
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ if (threadgroup_loc != 0) {
353
+ mtl_setArgs(computeEncoder, tensorArgumentBuffer, metadata_arguments, args...);
354
+ MTLSize gridSize = MTLSizeMake(threadgroup_loc, 1, 1);
355
+ uint32_t maxThreads = [pipeline maxTotalThreadsPerThreadgroup];
356
+ MTLSize threadGroupSize = MTLSizeMake(std::min(maxThreads, static_cast<uint32_t>(64)), 1, 1);
357
+ [computeEncoder dispatchThreadgroups:gridSize threadsPerThreadgroup:threadGroupSize];
358
+ }
359
+ }
360
+ });
361
+ }
362
+
363
+ } // namespace at::native::mps
364
+
365
+ #else
366
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
367
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/mtia/EmptyTensor.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+
3
+ #pragma once
4
+ #include <ATen/core/TensorBase.h>
5
+
6
+ namespace at::detail {
7
+
8
+ TensorBase empty_mtia(
9
+ IntArrayRef size,
10
+ ScalarType dtype,
11
+ std::optional<Device> device_opt,
12
+ std::optional<c10::MemoryFormat> memory_format_opt);
13
+
14
+ TensorBase empty_mtia(
15
+ IntArrayRef size,
16
+ std::optional<ScalarType> dtype_opt,
17
+ std::optional<Layout> layout_opt,
18
+ std::optional<Device> device_opt,
19
+ std::optional<bool> pin_memory_opt,
20
+ std::optional<c10::MemoryFormat> memory_format_opt);
21
+
22
+ TensorBase empty_mtia(IntArrayRef size, const TensorOptions& options);
23
+
24
+ TensorBase empty_strided_mtia(
25
+ IntArrayRef size,
26
+ IntArrayRef stride,
27
+ ScalarType dtype,
28
+ std::optional<Device> device_opt);
29
+
30
+ TensorBase empty_strided_mtia(
31
+ IntArrayRef size,
32
+ IntArrayRef stride,
33
+ std::optional<ScalarType> dtype_opt,
34
+ std::optional<Layout> layout_opt,
35
+ std::optional<Device> device_opt,
36
+ std::optional<bool> pin_memory_opt);
37
+
38
+ TensorBase empty_strided_mtia(
39
+ IntArrayRef size,
40
+ IntArrayRef stride,
41
+ const TensorOptions& options);
42
+
43
+ } // namespace at::detail
44
+
45
+ #else
46
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
47
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/nested/NestedTensorBinaryOps.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/ATen_fwd.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ enum class NESTED_DENSE_OP : uint8_t { ADD, MUL };
10
+
11
+ using nested_dense_elementwise_fn = void (*)(
12
+ Tensor& result,
13
+ const Tensor& self,
14
+ const Tensor& other,
15
+ const NESTED_DENSE_OP& op);
16
+
17
+ DECLARE_DISPATCH(nested_dense_elementwise_fn, nested_dense_elementwise_stub)
18
+
19
+ } // namespace at::native
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/native/nested/NestedTensorMath.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/ATen_fwd.h>
5
+ #include <ATen/NestedTensorImpl.h>
6
+ #include <c10/macros/Macros.h>
7
+
8
+ namespace at::native {
9
+
10
+ TORCH_API Tensor NestedTensor_to_padded_tensor_generic(
11
+ const Tensor& t,
12
+ double padding,
13
+ OptionalIntArrayRef output_size);
14
+
15
+ template <typename Func>
16
+ Tensor map_nt(const Tensor& nt, Func f) {
17
+ auto* nt_impl = get_nested_tensor_impl(nt);
18
+ const auto& sizes = nt_impl->get_nested_sizes();
19
+ return at::detail::make_tensor<NestedTensorImpl>(f(nt_impl->get_buffer()), sizes);
20
+ }
21
+ template <typename Func>
22
+ Tensor map_nt_binary(const Tensor& nt_1, const Tensor& nt_2, Func f){
23
+ auto* nt_impl_1 = get_nested_tensor_impl(nt_1);
24
+ auto* nt_impl_2 = get_nested_tensor_impl(nt_2);
25
+ const auto& sizes = nt_impl_1->get_nested_sizes();
26
+ return at::detail::make_tensor<NestedTensorImpl>(f(nt_impl_1->get_buffer(), nt_impl_2->get_buffer()), sizes);
27
+ }
28
+
29
+ C10_ALWAYS_INLINE std::pair<int64_t, int64_t> _check_nested_layer_norm_inputs(
30
+ const NestedTensorImpl& input,
31
+ IntArrayRef normalized_shape,
32
+ const Tensor& weight /* optional */,
33
+ const Tensor& bias /* optional */) {
34
+
35
+ const size_t normalized_ndim = normalized_shape.size();
36
+ TORCH_CHECK(
37
+ normalized_ndim >= 1,
38
+ "Expected normalized_shape to be at least 1-dimensional, i.e., ",
39
+ "containing at least one element, but got normalized_shape = ",
40
+ normalized_shape);
41
+ TORCH_CHECK(
42
+ !weight.defined() || weight.sizes().equals(normalized_shape),
43
+ "Expected weight to be of same shape as normalized_shape, but got ",
44
+ "weight of shape ",
45
+ weight.sizes(),
46
+ " and normalized_shape = ",
47
+ normalized_shape);
48
+ TORCH_CHECK(
49
+ !bias.defined() || bias.sizes().equals(normalized_shape),
50
+ "Expected bias to be of same shape as normalized_shape, but got ",
51
+ "bias of shape ",
52
+ bias.sizes(),
53
+ " and normalized_shape = ",
54
+ normalized_shape);
55
+
56
+ // Check that the normalized_shape has the exact same sizes as the last dimensions from the NestedTensor input
57
+ // Also, compute M and N considering the idiosyncrasies of NestedTensors
58
+ int64_t N = 1;
59
+ for (const auto i: c10::irange(normalized_ndim)) {
60
+ TORCH_CHECK(
61
+ input.opt_size(-normalized_ndim + i).has_value(),
62
+ "normalized_shape extends into irregular dimensions for the nested tensor"
63
+ );
64
+ TORCH_CHECK(
65
+ normalized_shape[i] == input.opt_size(-normalized_ndim + i),
66
+ "The shape at dimension ",
67
+ i,
68
+ "of normalized_shape doesn't match the input"
69
+ );
70
+ N *= normalized_shape[i];
71
+ }
72
+
73
+ const int64_t M = input.numel() / N;
74
+
75
+ return std::make_pair(M, N);
76
+ }
77
+
78
+ Tensor reshape_nested(const Tensor& self, IntArrayRef proposed_shape);
79
+
80
+ } // namespace at::native
81
+
82
+ #else
83
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
84
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)