Sumitwarrior7 commited on
Commit
92013f8
·
verified ·
1 Parent(s): 6a478f8

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. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h +212 -0
  2. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h +46 -0
  3. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h +14 -0
  4. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h +18 -0
  5. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h +23 -0
  6. .venv/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h +33 -0
  7. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h +33 -0
  8. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/IndexKernels.h +225 -0
  9. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h +442 -0
  10. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h +73 -0
  11. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h +91 -0
  12. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h +110 -0
  13. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h +66 -0
  14. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h +187 -0
  15. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h +76 -0
  16. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h +472 -0
  17. .venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h +171 -0
  18. .venv/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_kernels.h +48 -0
  19. .venv/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_pack.h +114 -0
  20. .venv/lib/python3.10/site-packages/torch/include/ATen/native/kleidiai/kai_ukernel_interface.h +226 -0
  21. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/Copy.h +19 -0
  22. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/MPSGraphSequoiaOps.h +51 -0
  23. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/MetalShaderLibrary.h +203 -0
  24. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/OperationUtils.h +801 -0
  25. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/TensorFactory.h +19 -0
  26. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Activation.h +21 -0
  27. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/EmbeddingBag.h +53 -0
  28. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/GridSampler.h +30 -0
  29. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/LinearAlgebra.h +28 -0
  30. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Pooling.h +66 -0
  31. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/Shape.h +23 -0
  32. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/TensorCompare.h +12 -0
  33. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/UpSample.h +17 -0
  34. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/BinaryKernel.h +15 -0
  35. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamAmsgradKernelImpl.h +43 -0
  36. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamKernelImpl.h +40 -0
  37. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamWAmsgradKernelImpl.h +42 -0
  38. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/FusedAdamWKernelImpl.h +41 -0
  39. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/operations/MultiTensorApply.h +367 -0
  40. .venv/lib/python3.10/site-packages/torch/include/ATen/native/mtia/EmptyTensor.h +47 -0
  41. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/flash_attn/flash_api.h +101 -0
  42. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/flash_attn/static_switch.h +112 -0
  43. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma.h +105 -0
  44. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_base.h +188 -0
  45. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_multistage.h +773 -0
  46. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_pipelined.h +407 -0
  47. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/find_default_mma.h +172 -0
  48. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_accum_lambda_iterator.h +359 -0
  49. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_from_smem.h +1953 -0
  50. .venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/epilogue_predicated_tile_iterator.h +757 -0
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/Exceptions.h>
5
+
6
+ #include <ATen/miopen/miopen-wrapper.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <ATen/TensorUtils.h>
9
+ #include <c10/macros/Export.h>
10
+
11
+ namespace at { namespace native {
12
+
13
+ std::string miopenTypeToString(miopenDataType_t dtype);
14
+
15
+ inline int dataSize(miopenDataType_t dataType)
16
+ {
17
+ switch (dataType) {
18
+ case miopenHalf: return 2;
19
+ case miopenFloat: return 4;
20
+ case miopenBFloat16: return 2;
21
+ default: return 8;
22
+ }
23
+ }
24
+
25
+ // See NOTE [ cudnn fixSizeOneDimStride ] in aten/src/ATen/cudnn/Descriptors.h
26
+ template <typename T>
27
+ static inline void fixSizeOneDimStride(int dim, const T *size, T *stride, bool nhwc) {
28
+ int64_t z = 1;
29
+ int index = 0;
30
+ std::vector<int> permutation(dim);
31
+
32
+ if (nhwc) {
33
+ permutation[index++] = 1;
34
+ }
35
+ for (int d = dim-1; d > 1; d--) {
36
+ permutation[index++] = d;
37
+ }
38
+ if (!nhwc) {
39
+ permutation[index++] = 1;
40
+ }
41
+ permutation[index++] = 0;
42
+ for (int d : permutation) {
43
+ if (size[d] == 1) {
44
+ stride[d] = z;
45
+ } else {
46
+ z *= size[d];
47
+ }
48
+ }
49
+ }
50
+
51
+ template <typename T, miopenStatus_t (*dtor)(T*)>
52
+ struct DescriptorDeleter {
53
+ void operator()(T* x) {
54
+ if (x != nullptr) {
55
+ MIOPEN_CHECK(dtor(x));
56
+ }
57
+ }
58
+ };
59
+
60
+ // A generic class for wrapping MIOpen descriptor types. All you need
61
+ // is to give the underlying type the Descriptor_t points to (usually,
62
+ // if it's miopenTensorDescriptor_t it points to miopenTensorStruct),
63
+ // the constructor and the destructor. Subclasses are responsible
64
+ // for defining a set() function to actually set the descriptor.
65
+ //
66
+ // Descriptors default construct to a nullptr, and have a descriptor
67
+ // initialized the first time you call set() or any other initializing
68
+ // function.
69
+ template <typename T, miopenStatus_t (*ctor)(T**), miopenStatus_t (*dtor)(T*)>
70
+ // NOLINTNEXTLINE(bugprone-exception-escape)
71
+ class TORCH_CUDA_CPP_API Descriptor {
72
+ public:
73
+ // Use desc() to access the underlying descriptor pointer in
74
+ // a read-only fashion. Most client code should use this.
75
+ // If the descriptor was never initialized, this will return
76
+ // nullptr.
77
+ T* desc() const { return desc_.get(); }
78
+ T* desc() { return desc_.get(); }
79
+
80
+ // Use mut_desc() to access the underlying descriptor pointer
81
+ // if you intend to modify what it points to (e.g., using
82
+ // miopenSetFooDescriptor). This will ensure that the descriptor
83
+ // is initialized. Code in this file will use this function.
84
+ T* mut_desc() { init(); return desc_.get(); }
85
+ protected:
86
+ void init() {
87
+ if (desc_ == nullptr) {
88
+ T* raw_desc = nullptr;
89
+ MIOPEN_CHECK(ctor(&raw_desc));
90
+ desc_.reset(raw_desc);
91
+ }
92
+ }
93
+ private:
94
+ std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_;
95
+ };
96
+
97
+ class TORCH_CUDA_CPP_API TensorDescriptor : public Descriptor<
98
+ miopenTensorDescriptor,
99
+ &miopenCreateTensorDescriptor,
100
+ &miopenDestroyTensorDescriptor> {
101
+ public:
102
+ TensorDescriptor() = default;
103
+ explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) {
104
+ set(t, pad);
105
+ }
106
+
107
+ // See Note [CuDNN broadcast padding]
108
+ void set(const at::Tensor &t, size_t pad = 0);
109
+ void set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad = 0);
110
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0);
111
+
112
+ void print();
113
+
114
+ private:
115
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad, bool nhwc);
116
+
117
+ void set(miopenDataType_t dataType, int dim, size_t* size, size_t* stride, bool nhwc) {
118
+ std::vector<size_t> strides_copy(stride, stride + dim);
119
+ fixSizeOneDimStride<size_t>(dim, size, strides_copy.data(), nhwc);
120
+ // Use V2 API which supports 64-bit size/stride for large tensors
121
+ MIOPEN_CHECK(miopenSetTensorDescriptorV2(mut_desc(), dataType, dim, size, strides_copy.data()));
122
+ }
123
+ };
124
+
125
+ std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d);
126
+
127
+ class TORCH_CUDA_CPP_API FilterDescriptor : public Descriptor<
128
+ miopenTensorDescriptor,
129
+ &miopenCreateTensorDescriptor,
130
+ &miopenDestroyTensorDescriptor> {
131
+ public:
132
+ void set(const at::Tensor &t, int64_t pad = 0) {
133
+ set(t, at::MemoryFormat::Contiguous, pad);
134
+ }
135
+
136
+ void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0);
137
+
138
+ private:
139
+ void set(miopenDataType_t dataType, int dim, size_t* size, size_t* stride, bool nhwc) {
140
+ std::vector<size_t> strides_copy(stride, stride + dim);
141
+ fixSizeOneDimStride<size_t>(dim, size, strides_copy.data(), nhwc);
142
+ // Use V2 API which supports 64-bit size/stride for large tensors
143
+ MIOPEN_CHECK(miopenSetTensorDescriptorV2(mut_desc(), dataType, dim, size, strides_copy.data()));
144
+ }
145
+ };
146
+
147
+ struct TORCH_CUDA_CPP_API ConvolutionDescriptor
148
+ : public Descriptor<
149
+ miopenConvolutionDescriptor,
150
+ &miopenCreateConvolutionDescriptor,
151
+ &miopenDestroyConvolutionDescriptor> {
152
+ void set(miopenDataType_t dataType, miopenConvolutionMode_t c_mode, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool benchmark, bool deterministic) {
153
+ MIOPEN_CHECK(miopenInitConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, c_mode));
154
+ MIOPEN_CHECK(miopenSetConvolutionGroupCount(mut_desc(), groups));
155
+ MIOPEN_CHECK(miopenSetConvolutionAttribute(mut_desc(), MIOPEN_CONVOLUTION_ATTRIB_DETERMINISTIC, deterministic ? 1 : 0));
156
+ if (benchmark) {
157
+ MIOPEN_CHECK(miopenSetConvolutionFindMode(mut_desc(), miopenConvolutionFindModeNormal));
158
+ }
159
+ }
160
+ };
161
+
162
+ // NOLINTNEXTLINE(bugprone-exception-escape)
163
+ struct TORCH_CUDA_CPP_API DropoutDescriptor
164
+ : public Descriptor<
165
+ miopenDropoutDescriptor,
166
+ &miopenCreateDropoutDescriptor,
167
+ &miopenDestroyDropoutDescriptor> {
168
+ void set(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
169
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
170
+ MIOPEN_CHECK(miopenSetDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
171
+ }
172
+
173
+ void restore(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
174
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
175
+ MIOPEN_CHECK(miopenRestoreDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
176
+ }
177
+ };
178
+
179
+ struct TORCH_CUDA_CPP_API RNNDescriptor
180
+ : public Descriptor<miopenRNNDescriptor,
181
+ &miopenCreateRNNDescriptor,
182
+ &miopenDestroyRNNDescriptor>
183
+ {
184
+ void set(int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, miopenRNNMode_t rnn_mode,
185
+ miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
186
+ MIOPEN_CHECK(miopenSetRNNDescriptor(mut_desc(), hidden_size, num_layers, input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
187
+ }
188
+
189
+ void setWithDropout(DropoutDescriptor& dropout_desc, int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction,
190
+ miopenRNNMode_t rnn_mode, miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
191
+ MIOPEN_CHECK(miopenSetRNNDescriptor_V2(mut_desc(), hidden_size, num_layers, dropout_desc.mut_desc(), input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
192
+ }
193
+ };
194
+
195
+ union Constant
196
+ {
197
+ float f;
198
+ double d;
199
+ Constant(miopenDataType_t dataType, double value) {
200
+ if (dataType == miopenHalf || dataType == miopenFloat || dataType == miopenBFloat16) {
201
+ f = static_cast<float>(value);
202
+ } else {
203
+ d = value;
204
+ }
205
+ }
206
+ };
207
+
208
+ }} // namespace
209
+
210
+ #else
211
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
212
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <string>
6
+ #include <stdexcept>
7
+ #include <sstream>
8
+
9
+ namespace at { namespace native {
10
+
11
+ class miopen_exception : public std::runtime_error {
12
+ public:
13
+ miopenStatus_t status;
14
+ miopen_exception(miopenStatus_t status, const char* msg)
15
+ : std::runtime_error(msg)
16
+ , status(status) {}
17
+ miopen_exception(miopenStatus_t status, const std::string& msg)
18
+ : std::runtime_error(msg)
19
+ , status(status) {}
20
+ };
21
+
22
+ inline void MIOPEN_CHECK(miopenStatus_t status)
23
+ {
24
+ if (status != miopenStatusSuccess) {
25
+ if (status == miopenStatusNotImplemented) {
26
+ throw miopen_exception(status, std::string(miopenGetErrorString(status)) +
27
+ ". This error may appear if you passed in a non-contiguous input.");
28
+ }
29
+ throw miopen_exception(status, miopenGetErrorString(status));
30
+ }
31
+ }
32
+
33
+ inline void HIP_CHECK(hipError_t error)
34
+ {
35
+ if (error != hipSuccess) {
36
+ std::string msg("HIP error: ");
37
+ msg += hipGetErrorString(error);
38
+ throw std::runtime_error(msg);
39
+ }
40
+ }
41
+
42
+ }} // namespace at::native
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)
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <c10/macros/Export.h>
6
+
7
+ namespace at::native {
8
+
9
+ TORCH_CUDA_CPP_API miopenHandle_t getMiopenHandle();
10
+ } // namespace at::native
11
+
12
+ #else
13
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
14
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <c10/macros/Export.h>
7
+
8
+ namespace at::native {
9
+
10
+ TORCH_CUDA_CPP_API miopenDataType_t getMiopenDataType(const at::Tensor& tensor);
11
+
12
+ int64_t miopen_version();
13
+
14
+ } // namespace at::native
15
+
16
+ #else
17
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
18
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <ATen/miopen/Handle.h>
7
+
8
+ namespace at { namespace native {
9
+
10
+ // This function makes tensors which have zero stride contiguous, by
11
+ // setting the strides to 1.
12
+ inline Tensor contiguousIfZeroInStrides(const Tensor& t) {
13
+ for (auto s : t.strides()) {
14
+ if (s == 0) return t.contiguous();
15
+ }
16
+ return t;
17
+ }
18
+
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)
.venv/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // Enable MIOpen Beta APIs including miopenSetTensorDescriptorV2 which supports
5
+ // 64-bit tensor dimensions/strides for large tensors (numel > INT32_MAX).
6
+ // Reference: https://github.com/ROCm/MIOpen/pull/2838
7
+ #ifndef MIOPEN_BETA_API
8
+ #define MIOPEN_BETA_API 1
9
+ #endif
10
+
11
+ #include <miopen/miopen.h>
12
+ #include <miopen/version.h>
13
+
14
+ #if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4)
15
+ // miopen 3.4 moved find mode from private header to public header
16
+ #else
17
+ // from miopen_internal.h
18
+ extern "C" {
19
+
20
+ typedef enum
21
+ {
22
+ miopenConvolutionFindModeNormal = 1, /*!< Normal mode */
23
+ } miopenConvolutionFindMode_t;
24
+
25
+ miopenStatus_t miopenSetConvolutionFindMode(
26
+ miopenConvolutionDescriptor_t convDesc,
27
+ miopenConvolutionFindMode_t findMode);
28
+ }
29
+ #endif
30
+
31
+ #else
32
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
33
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/core/TensorBase.h>
6
+
7
+ namespace at::detail {
8
+
9
+ C10_EXPORT TensorBase empty_mps(
10
+ IntArrayRef size,
11
+ std::optional<ScalarType> dtype_opt,
12
+ std::optional<Layout> layout_opt,
13
+ std::optional<Device> device_opt,
14
+ std::optional<bool> pin_memory_opt,
15
+ std::optional<c10::MemoryFormat> memory_format_opt);
16
+ C10_EXPORT TensorBase empty_mps(IntArrayRef size, const TensorOptions& options);
17
+
18
+ C10_EXPORT TensorBase empty_strided_mps(
19
+ IntArrayRef size,
20
+ IntArrayRef stride,
21
+ ScalarType dtype,
22
+ std::optional<Device> device_opt);
23
+
24
+ C10_EXPORT TensorBase empty_strided_mps(
25
+ IntArrayRef size,
26
+ IntArrayRef stride,
27
+ const TensorOptions& options);
28
+
29
+ } // namespace at::detail
30
+
31
+ #else
32
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
33
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/IndexKernels.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at::mps {
5
+
6
+ static const char* SCATTER_OPS_TEMPLATE = R"METAL_SCATTER(
7
+ template<typename Y, typename X>
8
+ Y cast(const X x);
9
+
10
+ template<>
11
+ {1} cast<{1}, {0}>(const {0} x) {{
12
+ return {2};
13
+ }}
14
+
15
+ kernel void scatter_kernel_n(uint linear_index [[thread_position_in_grid]],
16
+ constant void * src_ [[buffer(0)]],
17
+ device void * dst_ [[buffer(1)]],
18
+ constant uint32_t * size [[buffer(2)]],
19
+ constant uint32_t * stride [[buffer(3)]],
20
+ constant uint32_t & numel [[buffer(4)]],
21
+ constant int32_t & ndim [[buffer(5)]]) {{
22
+ if (linear_index >= numel) return;
23
+
24
+ constant {0} * src = (constant {0} *)src_;
25
+ device {1} * dst = (device {1} *)dst_;
26
+
27
+ uint64_t dst_offs = 0;
28
+ auto dst_idx = linear_index;
29
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
30
+ dst_offs += stride[dim] * (dst_idx % size[dim]);
31
+ dst_idx /= size[dim];
32
+ }}
33
+
34
+ dst[dst_offs] = cast<{1}>(src[linear_index]);
35
+ }}
36
+
37
+ kernel void scatter_kernel_4(uint linear_index [[thread_position_in_grid]],
38
+ constant void * src_ [[buffer(0)]],
39
+ device void * dst_ [[buffer(1)]],
40
+ constant packed_uint4 & size [[buffer(2)]],
41
+ constant packed_uint4 & stride [[buffer(3)]],
42
+ constant uint32_t & numel [[buffer(4)]]) {{
43
+ if (linear_index >= numel) return;
44
+
45
+ constant {0} * src = (constant {0} *)src_;
46
+ device {1} * dst = (device {1} *)dst_;
47
+
48
+ packed_uint4 local_index;
49
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
50
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
51
+ local_index.z = linear_index / size[3] % size[2];
52
+ local_index.w = linear_index % size[3];
53
+
54
+ const packed_uint4 strided_index = local_index * stride;
55
+ dst[strided_index.x + strided_index.y + strided_index.z + strided_index.w] = cast<{1}>(src[linear_index]);
56
+ }}
57
+
58
+ kernel void scatter_kernel_3(uint linear_index [[thread_position_in_grid]],
59
+ constant void * src_ [[buffer(0)]],
60
+ device void * dst_ [[buffer(1)]],
61
+ constant packed_uint3 & size [[buffer(2)]],
62
+ constant packed_uint3 & stride [[buffer(3)]],
63
+ constant uint32_t & numel [[buffer(4)]]) {{
64
+ if (linear_index >= numel) return;
65
+
66
+ constant {0} * src = (constant {0} *)src_;
67
+ device {1} * dst = (device {1} *)dst_;
68
+
69
+ packed_uint3 local_index;
70
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
71
+ local_index.y = linear_index / size[2] % size[1];
72
+ local_index.z = linear_index % size[2];
73
+
74
+ const packed_uint3 strided_index = local_index * stride;
75
+ dst[strided_index.x + strided_index.y + strided_index.z] = cast<{1}>(src[linear_index]);
76
+ }}
77
+
78
+ kernel void scatter_kernel_2(uint linear_index [[thread_position_in_grid]],
79
+ constant void * src_ [[buffer(0)]],
80
+ device void * dst_ [[buffer(1)]],
81
+ constant packed_uint2 & size [[buffer(2)]],
82
+ constant packed_uint2 & stride [[buffer(3)]],
83
+ constant uint32_t & numel [[buffer(4)]]) {{
84
+ if (linear_index >= numel) return;
85
+
86
+ constant {0} * src = (constant {0} *)src_;
87
+ device {1} * dst = (device {1} *)dst_;
88
+
89
+ packed_uint2 local_index;
90
+ local_index.x = linear_index / size[1] % size[0];
91
+ local_index.y = linear_index % size[1];
92
+
93
+ const packed_uint2 strided_index = local_index * stride;
94
+ dst[strided_index.x + strided_index.y] = cast<{1}>(src[linear_index]);
95
+ }}
96
+
97
+ kernel void scatter_kernel_1(uint linear_index [[thread_position_in_grid]],
98
+ constant void * src_ [[buffer(0)]],
99
+ device void * dst_ [[buffer(1)]],
100
+ constant int & size [[buffer(2)]],
101
+ constant int & stride [[buffer(3)]],
102
+ constant uint32_t & numel [[buffer(4)]]) {{
103
+ if (linear_index >= numel) return;
104
+
105
+ constant {0} * src = (constant {0} *)src_;
106
+ device {1} * dst = (device {1} *)dst_;
107
+
108
+ const int local_index = linear_index % size;
109
+ const int strided_index = local_index * stride;
110
+ dst[strided_index] = cast<{1}>(src[linear_index]);
111
+ }}
112
+ )METAL_SCATTER";
113
+
114
+ static const char* GATHER_OPS_TEMPLATE = R"METAL_GATHER(
115
+ template<typename Y, typename X>
116
+ Y cast(const X x);
117
+
118
+ template<>
119
+ {1} cast<{1}, {0}>(const {0} x) {{
120
+ return {2};
121
+ }}
122
+
123
+ kernel void gather_kernel_n(uint linear_index [[thread_position_in_grid]],
124
+ constant void * src_ [[buffer(0)]],
125
+ device void * dst_ [[buffer(1)]],
126
+ constant uint32_t * size [[buffer(2)]],
127
+ constant uint32_t * stride [[buffer(3)]],
128
+ constant uint32_t & numel [[buffer(4)]],
129
+ constant int32_t & ndim [[buffer(5)]]) {{
130
+ if (linear_index >= numel) return;
131
+
132
+ constant {0} * src = (constant {0} *)src_;
133
+ device {1} * dst = (device {1} *)dst_;
134
+
135
+ uint64_t src_offs = 0;
136
+ auto src_idx = linear_index;
137
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
138
+ src_offs += stride[dim] * (src_idx % size[dim]);
139
+ src_idx /= size[dim];
140
+ }}
141
+
142
+ dst[linear_index] = cast<{1}>(src[src_offs]);
143
+ }}
144
+
145
+ kernel void gather_kernel_4(uint linear_index [[thread_position_in_grid]],
146
+ constant void * src_ [[buffer(0)]],
147
+ device void * dst_ [[buffer(1)]],
148
+ constant packed_uint4 & size [[buffer(2)]],
149
+ constant packed_uint4 & stride [[buffer(3)]],
150
+ constant uint32_t & numel [[buffer(4)]]) {{
151
+ if (linear_index >= numel) return;
152
+
153
+ constant {0} * src = (constant {0} *)src_;
154
+ device {1} * dst = (device {1} *)dst_;
155
+
156
+ packed_uint4 local_index;
157
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
158
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
159
+ local_index.z = linear_index / size[3] % size[2];
160
+ local_index.w = linear_index % size[3];
161
+
162
+ const packed_uint4 strided_index = local_index * stride;
163
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z + strided_index.w]);
164
+ }}
165
+
166
+ kernel void gather_kernel_3(uint linear_index [[thread_position_in_grid]],
167
+ constant void * src_ [[buffer(0)]],
168
+ device void * dst_ [[buffer(1)]],
169
+ constant packed_uint3 & size [[buffer(2)]],
170
+ constant packed_uint3 & stride [[buffer(3)]],
171
+ constant uint32_t & numel [[buffer(4)]]) {{
172
+ if (linear_index >= numel) return;
173
+
174
+ constant {0} * src = (constant {0} *)src_;
175
+ device {1} * dst = (device {1} *)dst_;
176
+
177
+ packed_uint3 local_index;
178
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
179
+ local_index.y = linear_index / size[2] % size[1];
180
+ local_index.z = linear_index % size[2];
181
+
182
+ const packed_uint3 strided_index = local_index * stride;
183
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z]);
184
+ }}
185
+
186
+ kernel void gather_kernel_2(uint linear_index [[thread_position_in_grid]],
187
+ constant void * src_ [[buffer(0)]],
188
+ device void * dst_ [[buffer(1)]],
189
+ constant packed_uint2 & size [[buffer(2)]],
190
+ constant packed_uint2 & stride [[buffer(3)]],
191
+ constant uint32_t & numel [[buffer(4)]]) {{
192
+ if (linear_index >= numel) return;
193
+
194
+ constant {0} * src = (constant {0} *)src_;
195
+ device {1} * dst = (device {1} *)dst_;
196
+
197
+ packed_uint2 local_index;
198
+ local_index.x = linear_index / size[1] % size[0];
199
+ local_index.y = linear_index % size[1];
200
+
201
+ const packed_uint2 strided_index = local_index * stride;
202
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y]);
203
+ }}
204
+
205
+ kernel void gather_kernel_1(uint linear_index [[thread_position_in_grid]],
206
+ constant void * src_ [[buffer(0)]],
207
+ device void * dst_ [[buffer(1)]],
208
+ constant int & size [[buffer(2)]],
209
+ constant int & stride [[buffer(3)]],
210
+ constant uint32_t & numel [[buffer(4)]]) {{
211
+ if (linear_index >= numel) return;
212
+
213
+ constant {0} * src = (constant {0} *)src_;
214
+ device {1} * dst = (device {1} *)dst_;
215
+
216
+ const int local_index = linear_index % size;
217
+ const int strided_index = local_index * stride;
218
+ dst[linear_index] = cast<{1}>(src[strided_index]);
219
+ }}
220
+ )METAL_GATHER";
221
+ } // namespace at::mps
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)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/mps/MPSAllocatorInterface.h>
7
+ #include <ATen/mps/MPSEvent.h>
8
+ #include <ATen/mps/MPSStream.h>
9
+
10
+ #include <c10/util/flat_hash_map.h>
11
+ #include <mach/vm_page_size.h>
12
+ #include <cstdio>
13
+ #include <mutex>
14
+ #include <set>
15
+ #include <unordered_set>
16
+
17
+ // this implementation is based on CUDACachingAllocator.
18
+ // It utilizes Metal Heaps to improve the performance with buffer allocation.
19
+ // Do not include this header. Use MPSAllocatorInterface.h instead.
20
+ // TODO: Unify the logic with CUDACachingAllocator and remove redundant code.
21
+ namespace at::mps::HeapAllocator {
22
+
23
+ static const size_t kMaxSmallAlloc = MB(1); // largest "small" allocation is 1 MiB
24
+ static const size_t kMinLargeAlloc = MB(10); // allocations between 1 and 10 MiB may use kLargeHeap
25
+ static const size_t kRoundLarge = MB(2); // round up large allocations to 2 MiB
26
+ static const size_t kSmallHeap = MB(8); // "small" allocations are packed in 8 MiB heaps
27
+ static const size_t kLargeHeap = MB(32); // "large" allocations may be packed in 32 MiB heaps
28
+ static const size_t kXLargeHeapD =
29
+ MB(128); // "extra large" allocations on Discrete devices may be packed in 128 MiB heaps
30
+ static const size_t kXLargeHeapU =
31
+ MB(1024); // "extra large" allocations on Unified devices may be packed in 1 GiB heaps
32
+ static const size_t kMaxScalarAlloc = (sizeof(int64_t)); // largest "scalar" allocation
33
+
34
+ // buffer pools could be customized with a combination of usage flags
35
+ enum UsageFlags : uint32_t {
36
+ PRIVATE = 0,
37
+ SMALL = (1 << 0), // small heaps have sizes of kSmallHeap, and large ones kLargeHeap
38
+ SHARED = (1 << 1), // shared pools allocated on devices with unified memory; otherwise, private between host/device
39
+ MANAGED = (1 << 2), // managed storage mode
40
+ HAZARD = (1 << 3), // enables Automatic Hazard Tracking for the resources allocated on the pool
41
+ SCALAR = (1 << 4), // used to import CPU scalar values to GPU and use them in MPS Stream
42
+ };
43
+ // debug verbosity flags
44
+ enum DebugVerbosity : uint32_t {
45
+ SILENT = 0,
46
+ PROFILING = (1 << 0), // print generic profiling data for total system memory usage
47
+ ALLOCATIONS = (1 << 1), // print buffer allocations
48
+ RECYCLES = (1 << 2), // print buffer recycling
49
+ RELEASES = (1 << 3), // print buffer releases
50
+ LARGE_ONLY = (1 << 4), // only log large buffer pool transactions
51
+ };
52
+
53
+ struct HeapBlock;
54
+
55
+ struct BufferBlock {
56
+ id<MTLBuffer> buffer;
57
+ void* cpu_ptr = nullptr; // stores the pointer to CPU mapping of a Shared MTLBuffer
58
+ size_t size; // size after alignment
59
+ size_t requested_size; // requested size (before alignment)
60
+ // buffer shape is used for retrieving base of views in cached graphs
61
+ std::vector<int64_t> shape;
62
+ bool in_use = false;
63
+ HeapBlock* heap;
64
+ id_t buf_id;
65
+ // counter to candidate least recently used buffers for garbage collection
66
+ uint32_t gc_count = 0;
67
+ uint32_t use_count = 0;
68
+ // counter to assign unique ids to buffer blocks
69
+ static uint64_t buffer_counter;
70
+ // Metal events used to sync GPU/CPU operations on the shared-storage buffers
71
+ MPSEventPtr event;
72
+
73
+ BufferBlock(size_t Size, size_t RequestedSize = 0, const id<MTLBuffer> Buffer = nullptr, HeapBlock* Heap = nullptr)
74
+ : buffer(Buffer), size(Size), requested_size(RequestedSize), heap(Heap), buf_id(Buffer ? ++buffer_counter : 0) {}
75
+
76
+ static bool Comparator(const BufferBlock* a, const BufferBlock* b) {
77
+ return (a->size != b->size) ? a->size < b->size : (uintptr_t)a->buffer < (uintptr_t)b->buffer;
78
+ }
79
+ static size_t alignUp(size_t Size, size_t Alignment) {
80
+ assert(((Alignment - 1) & Alignment) == 0);
81
+ return ((Size + Alignment - 1) & ~(Alignment - 1));
82
+ }
83
+ uint32_t retainCount() const {
84
+ return [buffer retainCount];
85
+ }
86
+ };
87
+ typedef bool (*BufferComparison)(const BufferBlock*, const BufferBlock*);
88
+
89
+ struct BufferPool;
90
+ struct AllocParams {
91
+ AllocParams(size_t Alloc_Size, size_t Requested_Size, BufferPool* Pool)
92
+ : search_key(Alloc_Size), pool(Pool), requested_size(Requested_Size) {}
93
+ size_t size() const {
94
+ return search_key.size;
95
+ }
96
+
97
+ BufferBlock search_key;
98
+ BufferPool* pool;
99
+ BufferBlock* buffer_block = nullptr;
100
+ size_t requested_size;
101
+ // true if we exceed the low watermark limit. In this case
102
+ // we apply strategies to relieve the pressure before allocation.
103
+ bool has_memory_pressure = false;
104
+ // true if we're allocating on a unified memory device
105
+ bool has_unified_memory = true;
106
+ };
107
+
108
+ struct HeapBlock {
109
+ id<MTLHeap> heap;
110
+ struct {
111
+ size_t total, available;
112
+ } size;
113
+ BufferPool* pool;
114
+ unsigned int n_buffers = 0;
115
+ id_t heap_id;
116
+ // indicates if we split this heap to sub-allocate 'several' buffers (otherwise single buffer)
117
+ bool is_split;
118
+ // counter to assign unique ids to heap blocks
119
+ static uint64_t heap_counter;
120
+
121
+ HeapBlock(size_t Size, const id<MTLHeap> Heap = nullptr, BufferPool* Pool = nullptr)
122
+ : heap(Heap),
123
+ size({.total = Size, .available = Size}),
124
+ pool(Pool),
125
+ heap_id(Heap ? ++heap_counter : 0),
126
+ is_split(true) {}
127
+
128
+ static MTLResourceOptions getOptions(uint32_t usage) {
129
+ // TODO: check the caching performance of write-combined mode
130
+ MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache;
131
+
132
+ if (usage & UsageFlags::MANAGED)
133
+ options |= MTLResourceStorageModeManaged;
134
+ else if (usage & UsageFlags::SHARED)
135
+ options |= MTLResourceStorageModeShared;
136
+ else
137
+ options |= MTLResourceStorageModePrivate;
138
+
139
+ options |=
140
+ (usage & UsageFlags::HAZARD) ? MTLResourceHazardTrackingModeTracked : MTLResourceHazardTrackingModeUntracked;
141
+
142
+ return options;
143
+ }
144
+
145
+ static HeapBlock* createHeapBlock(AllocParams& params, id<MTLDevice> device, uint32_t usage) {
146
+ HeapBlock* heapBlock = nullptr;
147
+ bool is_split = true;
148
+ const size_t size = params.size();
149
+ MTLHeapDescriptor* d = [MTLHeapDescriptor new];
150
+ if (d) {
151
+ const size_t kXLargeHeap = params.has_unified_memory ? kXLargeHeapU : kXLargeHeapD;
152
+ if (size <= kMaxSmallAlloc) {
153
+ d.size = kSmallHeap;
154
+ } else if (size < kMinLargeAlloc) {
155
+ d.size = kLargeHeap;
156
+ } else if (size < kXLargeHeap / 2 && !params.has_memory_pressure) {
157
+ d.size = kXLargeHeap;
158
+ } else {
159
+ d.size = kRoundLarge * ((size + kRoundLarge - 1) / kRoundLarge);
160
+ is_split = false;
161
+ }
162
+ d.storageMode = (usage & UsageFlags::SHARED) ? MTLStorageModeShared : MTLStorageModePrivate;
163
+ d.cpuCacheMode = MTLCPUCacheModeDefaultCache;
164
+ // this automatically handles Metal buffer access synchronizations at the
165
+ // cost of slightly lower performance.
166
+ d.hazardTrackingMode =
167
+ (usage & UsageFlags::HAZARD) ? MTLHazardTrackingModeTracked : MTLHazardTrackingModeUntracked;
168
+ d.resourceOptions = getOptions(usage);
169
+ d.type = MTLHeapTypeAutomatic;
170
+ id<MTLHeap> heap = [device newHeapWithDescriptor:d];
171
+ if (heap) {
172
+ [heap setPurgeableState:MTLPurgeableStateNonVolatile];
173
+ const size_t heap_size = heapAvailableSize(heap);
174
+ heapBlock = new HeapBlock(heap_size, heap, params.pool);
175
+ if (heapBlock) {
176
+ heapBlock->is_split = is_split;
177
+ }
178
+ }
179
+ [d release];
180
+ }
181
+ return heapBlock;
182
+ }
183
+ static bool Comparator(const HeapBlock* a, const HeapBlock* b) {
184
+ return (a->size.available != b->size.available) ? a->size.available < b->size.available
185
+ : (uintptr_t)a->heap < (uintptr_t)b->heap;
186
+ }
187
+ static NSUInteger heapAvailableSize(id<MTLHeap> heap, size_t Alignment = vm_page_size) {
188
+ return [heap maxAvailableSizeWithAlignment:Alignment];
189
+ }
190
+ NSUInteger Size() {
191
+ return [heap size];
192
+ }
193
+ id<MTLBuffer> newMTLBuffer(size_t length, uint32_t usage) {
194
+ id<MTLBuffer> buf = [heap newBufferWithLength:length options:getOptions(usage)];
195
+ if (buf) {
196
+ updateAvailableSize();
197
+ n_buffers++;
198
+ }
199
+ return buf;
200
+ }
201
+ // returns the retainCount before releasing the buffer
202
+ uint32_t releaseMTLBuffer(id<MTLBuffer>& buffer) {
203
+ const uint32_t retainCount = [buffer retainCount];
204
+ [buffer release];
205
+ buffer = nil;
206
+ updateAvailableSize();
207
+ n_buffers--;
208
+ return retainCount;
209
+ }
210
+ // returns the retainCount before releasing the heap
211
+ uint32_t releaseMTLHeap() {
212
+ const uint32_t retainCount = [heap retainCount];
213
+ TORCH_INTERNAL_ASSERT(!n_buffers); // assert if heap isn't empty
214
+ [heap setPurgeableState:MTLPurgeableStateEmpty];
215
+ [heap release];
216
+ heap = nil;
217
+ size.available = 0;
218
+ return retainCount;
219
+ }
220
+ uint32_t retainCount() const {
221
+ return [heap retainCount];
222
+ }
223
+ void updateAvailableSize() {
224
+ size.available = heapAvailableSize(heap);
225
+ }
226
+ };
227
+ typedef bool (*HeapComparison)(const HeapBlock*, const HeapBlock*);
228
+
229
+ struct BufferPool {
230
+ enum class Kind {
231
+ PRIVATE_SMALL,
232
+ PRIVATE_LARGE,
233
+ SHARED_SMALL,
234
+ SHARED_LARGE,
235
+ SCALAR,
236
+ };
237
+
238
+ BufferPool(const id<MTLDevice> Device, uint32_t Usage)
239
+ : device(Device), usage(Usage), heaps(HeapBlock::Comparator), available_buffers(BufferBlock::Comparator) {}
240
+
241
+ const id<MTLDevice> device;
242
+ // usage flags to customize the pool for various purposes (see UsageFlags enum)
243
+ const uint32_t usage;
244
+ // total number of buffers in the pool
245
+ uint32_t n_buffers = 0;
246
+ // total allocations size on this pool
247
+ size_t allocated_size = 0;
248
+ // total memory available in the pool
249
+ size_t available_size = 0;
250
+ // list of heaps ordered by their "available" (not total) memory size
251
+ std::set<HeapBlock*, HeapComparison> heaps;
252
+ // list of only "available" buffers in the pool (i.e., buffers not in-use)
253
+ std::set<BufferBlock*, BufferComparison> available_buffers;
254
+ // list of buffers that are in a state of "limbo" where they've already been freed
255
+ // from PyTorch-side, but were not returned to pool due to still being
256
+ // in-use by command buffers with retainCount > 1. In this state, the buffer is
257
+ // neither ready to be recycled, nor could be returned to pool as available.
258
+ // These buffers will be returned to pool once the command buffer's
259
+ // completionHandler callbacks are called.
260
+ std::unordered_set<BufferBlock*> buffers_pending_free;
261
+ // list of heaps pending size update
262
+ std::unordered_set<HeapBlock*> heaps_pending_update;
263
+ };
264
+
265
+ class MPSHeapAllocatorImpl {
266
+ public:
267
+ explicit MPSHeapAllocatorImpl()
268
+ : m_device(at::mps::MPSDevice::getInstance()->device()),
269
+ m_max_buffer_size([m_device maxBufferLength]),
270
+ m_stream(getDefaultMPSStream()),
271
+ m_event_pool(getMPSEventPool()) {
272
+ init_allocator();
273
+ }
274
+ ~MPSHeapAllocatorImpl() {
275
+ emptyCache();
276
+ }
277
+ // interface exposed to at::Allocator
278
+ id<MTLBuffer> malloc(size_t size, uint32_t usage);
279
+ // frees a buffer and returns it into buffer pool
280
+ void free(void* ptr);
281
+ // releases all the cached buffers and their associated heaps
282
+ void emptyCache();
283
+ // free inactive buffers that are pending to be freed
284
+ void freeInactiveBuffers();
285
+ // returns true if buffer was allocated from the shared pool
286
+ bool isSharedBuffer(const void* ptr);
287
+ // get the requested unaligned size of an MTLBuffer
288
+ ssize_t getUnalignedBufferSize(const void* ptr);
289
+ // set the shape of a base tensor from a view tensor
290
+ void setBufferShape(const void* ptr, const IntArrayRef& shape);
291
+ // retrieve the shape of a base tensor from a view tensor
292
+ IntArrayRef getBufferShape(const void* ptr);
293
+ // get the unique ID of the buffer
294
+ id_t getBufferId(const void* ptr);
295
+ // allocate a buffer from a specialized pool to import CPU scalars into GPU
296
+ id<MTLBuffer> allocScalarBufferWithValue(void* value, size_t size);
297
+ // returns a CPU-mapping of the input buffer and its retainCount,
298
+ // if only it has Shared storage-mode and allocated on MPSAllocator
299
+ std::pair<const void*, uint32_t> getSharedBufferPtr(const void* buffer);
300
+ // records events for a list of MTLBuffers (list is used to lock the mutex once)
301
+ // returns true if records any event (given if passed buffers exist and are shared-storage)
302
+ bool recordEvents(c10::ArrayRef<const void*> buffers);
303
+ // waits for the event to signal the completion of GPU execution
304
+ // on the passed shared buffers (list is used to lock the mutex once)
305
+ // returns true if actually waited on any event
306
+ bool waitForEvents(c10::ArrayRef<const void*> buffers);
307
+ // this indicates how far (in Megabytes) the current total allocations are from the
308
+ // low watermark limit which is used to detect if we're under memory pressure
309
+ // This returns zero if we've reached the low watermark limit
310
+ ssize_t getLowWatermarkValue();
311
+ // (see m_low_watermark_ratio for description)
312
+ void setLowWatermarkRatio(double ratio);
313
+ // (see m_high_watermark_ratio for description)
314
+ void setHighWatermarkRatio(double ratio);
315
+ // (see m_low_watermark_limit for description)
316
+ size_t getLowWatermarkLimit() const {
317
+ return m_low_watermark_limit;
318
+ }
319
+ // (see m_max_total_allowed_size for description)
320
+ size_t getHighWatermarkLimit() const {
321
+ return m_max_total_allowed_size;
322
+ }
323
+ // (see m_total_allocated_memory for description)
324
+ size_t getTotalAllocatedMemory() const {
325
+ return m_total_allocated_memory;
326
+ }
327
+ // (see m_current_allocated_memory for description)
328
+ size_t getCurrentAllocatedMemory() const {
329
+ return m_current_allocated_memory;
330
+ }
331
+ // total GPU memory allocated in the process by Metal driver; including
332
+ // implicit allocations from MPS/MPSGraph frameworks and MPSHeapAllocatorImpl.
333
+ size_t getDriverAllocatedMemory() const {
334
+ return current_allocated_size();
335
+ }
336
+ // recommended Max memory for Metal
337
+ size_t getRecommendedMaxMemory() const {
338
+ return max_device_size();
339
+ }
340
+ // (see enum DebugVerbosity for description)
341
+ uint32_t getDebugVerbosity() const {
342
+ return m_debug_verbosity;
343
+ }
344
+ // returns the device that we allocate from
345
+ inline id<MTLDevice> Device() const {
346
+ return m_device;
347
+ }
348
+
349
+ inline std::string format_size(uint64_t size) const;
350
+
351
+ private:
352
+ // (see m_high_watermark_ratio for description)
353
+ constexpr static double default_high_watermark_ratio = 1.7;
354
+ // we set the allowed upper bound to twice the size of recommendedMaxWorkingSetSize.
355
+ constexpr static double default_high_watermark_upper_bound = 2.0;
356
+ // (see m_low_watermark_ratio for description)
357
+ // on unified memory, we could allocate beyond the recommendedMaxWorkingSetSize
358
+ constexpr static double default_low_watermark_ratio_unified = 1.4;
359
+ constexpr static double default_low_watermark_ratio_discrete = 1.0;
360
+
361
+ const id<MTLDevice> m_device;
362
+ std::recursive_mutex m_mutex;
363
+ // allocated buffers by device pointer
364
+ ska::flat_hash_map<const void*, BufferBlock*> m_allocated_buffers;
365
+ // using a container for pools to simplify iterating them
366
+ ska::flat_hash_map<BufferPool::Kind, std::unique_ptr<BufferPool>> m_pools;
367
+ // total memory allocated by HeapAllocator (including blocks in pools)
368
+ size_t m_total_allocated_memory = 0;
369
+ // currently active memory allocations in use (i.e., blocks not in pools)
370
+ size_t m_current_allocated_memory = 0;
371
+ // max buffer size allowed by Metal
372
+ size_t m_max_buffer_size = 0;
373
+ // maximum total size allowed to be allocated
374
+ size_t m_max_total_allowed_size = 0;
375
+ // high watermark ratio is a hard limit for the total allowed allocations
376
+ // 0. : disables high watermark limit (may cause system failure if system-wide OOM occurs)
377
+ // 1. : recommended maximum allocation size (i.e., device.recommendedMaxWorkingSetSize)
378
+ // >1.: allows limits beyond the device.recommendedMaxWorkingSetSize
379
+ // e.g., value 0.95 means we allocate up to 95% of recommended maximum
380
+ // allocation size; beyond that, the allocations would fail with OOM error.
381
+ double m_high_watermark_ratio;
382
+ // low watermark ratio is a soft limit to attempt limiting memory allocations up to the lower watermark
383
+ // level by garbage collection or committing command buffers more frequently (a.k.a, adaptive commit).
384
+ // Value between 0 to m_high_watermark_ratio (setting 0.0 disables adaptive commit and garbage collection)
385
+ // e.g., value 0.9 means we 'attempt' to limit allocations up to 90% of recommended maximum
386
+ // allocation size.
387
+ double m_low_watermark_ratio;
388
+ // low watermark size limit (in Bytes) at the time we initialize the allocator
389
+ size_t m_low_watermark_limit;
390
+ // use "PYTORCH_DEBUG_MPS_ALLOCATOR" env-var to set debug verbosity
391
+ uint32_t m_debug_verbosity;
392
+ // default MPS stream
393
+ MPSStream* m_stream;
394
+ // we hold a reference to MPSEventPool so it could get destroyed after MPSAllocator
395
+ std::shared_ptr<MPSEventPool> m_event_pool;
396
+
397
+ void init_allocator();
398
+ void init_buffer_pools();
399
+ HeapBlock* get_free_heap(AllocParams& params);
400
+ bool get_free_buffer(AllocParams& params);
401
+ BufferBlock* get_allocated_buffer_block(const void* ptr);
402
+ BufferBlock* alloc_buffer_block(size_t size, uint32_t usage);
403
+ bool alloc_buffer(AllocParams& params);
404
+ void free_buffer(BufferBlock* buffer_block);
405
+ // returns true if the container heap is also released
406
+ bool release_buffer(BufferBlock* buffer_block, bool remove_empty_heap = true);
407
+ void release_buffers(BufferPool& pool);
408
+ bool release_available_cached_buffers(AllocParams& params);
409
+ bool release_cached_buffers();
410
+ // free unused cached blocks to reclaim GPU memory if memory pressure is high
411
+ void garbage_collect_cached_buffers(AllocParams& params);
412
+ // returns the suitable buffer pool type for the usage or
413
+ // requested/allocated sizes
414
+ BufferPool& get_pool(size_t requested_size, size_t aligned_size, uint32_t usage);
415
+ // returns the aligned allocation size that is optimized
416
+ // for the buffers to get reused frequently
417
+ size_t get_allocation_size(size_t size, uint32_t usage) const;
418
+ // maximum size of device memory available for allocation in current process
419
+ // Note: the recommendedMaxWorkingSetSize is typically 75% of the total system memory.
420
+ size_t max_device_size() const {
421
+ return [m_device recommendedMaxWorkingSetSize];
422
+ }
423
+ // there are implicit allocations from MPS backend, so we need to query the 'device' for
424
+ // total allocated size instead of manually tracking in MPSAllocator
425
+ size_t current_allocated_size() const {
426
+ return [m_device currentAllocatedSize];
427
+ }
428
+
429
+ bool trigger_memory_callbacks(BufferBlock* buffer_block, IMpsAllocatorCallback::EventType event) const {
430
+ for (const auto& name : MPSAllocatorCallbacksRegistry()->Keys()) {
431
+ MPSAllocatorCallbacksRegistry()->Create(name)->executeMPSAllocatorCallback(
432
+ buffer_block ? buffer_block->buffer : nullptr, event);
433
+ }
434
+ return true;
435
+ }
436
+ };
437
+
438
+ } // namespace at::mps::HeapAllocator
439
+
440
+ #else
441
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
442
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2023 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/core/ATen_fwd.h>
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/util/Registry.h>
9
+
10
+ #define MB(x) (x * 1048576UL)
11
+
12
+ namespace at::mps {
13
+
14
+ // this is a public interface to access MPSAllocator.
15
+ // Do not declare methods that would depend on MPS or Metal frameworks.
16
+ class IMPSAllocator : public c10::Allocator {
17
+ public:
18
+ // see the comments in MPSAllocator.h for the description of these methods.
19
+ virtual void emptyCache() const = 0;
20
+ virtual void freeInactiveBuffers() const = 0;
21
+ virtual ssize_t getUnalignedBufferSize(const void* ptr) const = 0;
22
+ virtual IntArrayRef getBufferShape(const void* ptr) const = 0;
23
+ virtual id_t getBufferId(const void* ptr) const = 0;
24
+ virtual void setBufferShape(const void* ptr, const IntArrayRef& shape)
25
+ const = 0;
26
+ virtual bool isSharedBuffer(const void* ptr) const = 0;
27
+ virtual bool isSharedStorageSupported() const = 0;
28
+ virtual c10::DataPtr allocScalarBufferWithValue(void* value, size_t size)
29
+ const = 0;
30
+ virtual std::string formatSize(size_t size) const = 0;
31
+ virtual void setLowWatermarkRatio(double ratio) const = 0;
32
+ virtual void setHighWatermarkRatio(double ratio) const = 0;
33
+ virtual ssize_t getLowWatermarkValue() const = 0;
34
+ virtual size_t getLowWatermarkLimit() const = 0;
35
+ virtual size_t getHighWatermarkLimit() const = 0;
36
+ virtual size_t getTotalAllocatedMemory() const = 0;
37
+ virtual size_t getCurrentAllocatedMemory() const = 0;
38
+ virtual size_t getDriverAllocatedMemory() const = 0;
39
+ virtual size_t getRecommendedMaxMemory() const = 0;
40
+ virtual std::pair<const void*, uint32_t> getSharedBufferPtr(
41
+ const void* ptr) const = 0;
42
+ virtual bool recordEvents(c10::ArrayRef<const void*> buffers) const = 0;
43
+ virtual bool waitForEvents(c10::ArrayRef<const void*> buffers) const = 0;
44
+ };
45
+
46
+ class IMpsAllocatorCallback {
47
+ public:
48
+ enum class EventType {
49
+ ALLOCATED, // buffer got allocated to be used immediately
50
+ RECYCLED, // buffer pulled from free list to be reused
51
+ FREED, // buffer put to free list for future recycling
52
+ RELEASED, // buffer memory released
53
+ ALLOCATION_FAILED // buffer allocation failed
54
+ };
55
+ virtual ~IMpsAllocatorCallback() = default;
56
+ virtual void executeMPSAllocatorCallback(void* ptr, EventType event) = 0;
57
+ };
58
+
59
+ // MPS allocator will execute every registered callback when a block of memory
60
+ // is freed.
61
+ TORCH_DECLARE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback);
62
+ #define REGISTER_MPS_ALLOCATOR_CALLBACK(name, ...) \
63
+ C10_REGISTER_CLASS(MPSAllocatorCallbacksRegistry, name, __VA_ARGS__)
64
+
65
+ IMPSAllocator* getIMPSAllocator(bool sharedAllocator = false);
66
+
67
+ bool isMPSPinnedPtr(const void* data);
68
+
69
+ } // namespace at::mps
70
+
71
+ #else
72
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
73
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/Device.h>
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/macros/Macros.h>
8
+ #include <c10/util/Exception.h>
9
+
10
+ #ifdef __OBJC__
11
+ #include <Foundation/Foundation.h>
12
+ #include <Metal/Metal.h>
13
+ typedef id<MTLDevice> MTLDevice_t;
14
+ #else
15
+ typedef void* MTLDevice_t;
16
+ #endif
17
+
18
+ namespace at::mps {
19
+
20
+ // Helper enum to check if a MPSGraph op is supported in a given macOS version
21
+ enum class MacOSVersion : uint32_t {
22
+ MACOS_VER_14_4_PLUS = 0,
23
+ MACOS_VER_15_0_PLUS,
24
+ MACOS_VER_15_1_PLUS,
25
+ MACOS_VER_15_2_PLUS,
26
+ MACOS_VER_26_0_PLUS,
27
+ };
28
+
29
+ //-----------------------------------------------------------------
30
+ // MPSDevice
31
+ //
32
+ // MPSDevice is a singleton class that returns the default device
33
+ //-----------------------------------------------------------------
34
+
35
+ class TORCH_API MPSDevice {
36
+ public:
37
+ /**
38
+ * MPSDevice should not be cloneable.
39
+ */
40
+ MPSDevice(MPSDevice& other) = delete;
41
+ /**
42
+ * MPSDevice should not be assignable.
43
+ */
44
+ void operator=(const MPSDevice&) = delete;
45
+ /**
46
+ * Gets single instance of the Device.
47
+ */
48
+ static MPSDevice* getInstance();
49
+ /**
50
+ * Returns the single device.
51
+ */
52
+ MTLDevice_t device() {
53
+ return _mtl_device;
54
+ }
55
+ /**
56
+ * Returns whether running on Ventura or newer
57
+ */
58
+ bool isMacOS13Plus(MacOSVersion version) const;
59
+
60
+ /**
61
+ * Returns device name
62
+ */
63
+ std::string getName() const;
64
+
65
+ /**
66
+ * Returns number of GPU cores.
67
+ * 1 Core = 16 ExecutionUnit x 8 ALU x 24 threads
68
+ */
69
+ unsigned getCoreCount() const;
70
+
71
+ ~MPSDevice();
72
+
73
+ private:
74
+ static MPSDevice* _device;
75
+ MTLDevice_t _mtl_device;
76
+ MPSDevice();
77
+ };
78
+
79
+ TORCH_API bool is_available();
80
+ TORCH_API bool is_macos_13_or_newer(MacOSVersion version);
81
+ TORCH_API at::Allocator* GetMPSAllocator(bool useSharedAllocator = false);
82
+
83
+ inline Device getDeviceFromPtr(void* ptr) {
84
+ return {c10::DeviceType::MPS, 0};
85
+ }
86
+
87
+ } // namespace at::mps
88
+
89
+ #else
90
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
91
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2023 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/mps/MPSStream.h>
7
+ #include <ctime>
8
+ #include <stack>
9
+
10
+ namespace at::mps {
11
+
12
+ // NOTE: don't create instances of this class directly.
13
+ // Use MPSEventPool to acquire instances of MPSEvent.
14
+ class MPSEvent {
15
+ public:
16
+ explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing);
17
+ ~MPSEvent();
18
+
19
+ // records an event on the stream
20
+ void record(bool needsLock, bool syncEvent = false);
21
+ // makes all future work submitted to the stream wait for this event.
22
+ bool wait(bool needsLock, bool syncEvent = false);
23
+ // schedules a notifyListener callback for the event.
24
+ bool notify(bool needsLock, MTLSharedEventNotificationBlock block);
25
+ // checks if events are already signaled.
26
+ bool query() const;
27
+ // blocks the CPU thread until all the GPU work that were scheduled
28
+ // prior to recording this event are completed.
29
+ bool synchronize();
30
+ // resets this event with new parameters in case it gets reused from the event
31
+ // pool
32
+ void reset(MPSStream* stream, bool enable_timing);
33
+ // returns the unique ID of the event instance
34
+ id_t getID() const {
35
+ return m_id;
36
+ }
37
+ // returns the completion timestamp of the event
38
+ uint64_t getCompletionTime() const {
39
+ return m_completion_time;
40
+ }
41
+ // if already recorded, waits for cpu_sync_cv to be signaled
42
+ void waitForCpuSync();
43
+
44
+ private:
45
+ id_t m_id;
46
+ // enables measuring the completion time of the notifyListener of this event
47
+ bool m_enable_timing;
48
+ uint64_t m_signalCounter = 0;
49
+ MPSStream* m_stream = nullptr;
50
+ MTLSharedEvent_t m_event = nullptr;
51
+ MTLSharedEventListener* m_listener = nullptr;
52
+ // used to sync the events created on this Stream with CPU
53
+ std::mutex m_cpu_sync_mutex{};
54
+ std::condition_variable m_cpu_sync_cv{};
55
+ // CondVar predicate to sync the events created on this Stream with CPU
56
+ bool m_cpu_sync_completed = false;
57
+ // used to compute elapsed time
58
+ uint64_t m_completion_time = 0;
59
+
60
+ void recordLocked(bool syncEvent);
61
+ bool waitLocked(bool syncEvent);
62
+ bool notifyLocked(MTLSharedEventNotificationBlock block);
63
+ void notifyCpuSync();
64
+ static uint64_t getTime() {
65
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
66
+ }
67
+ };
68
+
69
+ typedef std::unique_ptr<MPSEvent, std::function<void(MPSEvent*)>> MPSEventPtr;
70
+
71
+ class MPSEventPool {
72
+ public:
73
+ explicit MPSEventPool(MPSStream* default_stream);
74
+ ~MPSEventPool();
75
+
76
+ MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream);
77
+ void emptyCache();
78
+
79
+ // these are mainly used for MPSHooks and torch.mps.Event() bindings
80
+ id_t acquireEvent(bool enable_timing);
81
+ void releaseEvent(id_t event_id);
82
+ void recordEvent(id_t event_id, bool syncEvent);
83
+ void waitForEvent(id_t event_id, bool syncEvent);
84
+ void synchronizeEvent(id_t event_id);
85
+ bool queryEvent(id_t event_id);
86
+ // returns elapsed time between two recorded events in milliseconds
87
+ double elapsedTime(id_t start_event_id, id_t end_event_id);
88
+
89
+ private:
90
+ MPSStream* m_default_stream = nullptr;
91
+ std::recursive_mutex m_mutex;
92
+ std::stack<std::unique_ptr<MPSEvent>> m_pool{};
93
+ // dictionary to associate event IDs with event objects
94
+ // used to retain in-use events out of the pool
95
+ // for torch.mps.Event() bindings.
96
+ std::unordered_map<id_t, MPSEventPtr> m_in_use_events{};
97
+ uint64_t m_event_counter = 0;
98
+ std::function<void(MPSEvent*)> m_default_deleter;
99
+
100
+ MPSEvent* getInUseEvent(id_t event_id, bool locked = true);
101
+ };
102
+
103
+ // shared_ptr is used to get MPSEventPool destroyed after dependent instances
104
+ std::shared_ptr<MPSEventPool> getMPSEventPool();
105
+
106
+ } // namespace at::mps
107
+
108
+ #else
109
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
110
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/core/Generator.h>
7
+ #include <ATen/core/PhiloxRNGEngine.h>
8
+ #include <c10/core/GeneratorImpl.h>
9
+ #include <optional>
10
+
11
+ namespace at {
12
+ namespace mps::detail {
13
+
14
+ constexpr uint32_t PHILOX_STATE_N = 7;
15
+ struct rng_data_pod {
16
+ std::array<uint32_t, PHILOX_STATE_N> state{1};
17
+ uint64_t seed = default_rng_seed_val;
18
+ };
19
+
20
+ TORCH_API const Generator& getDefaultMPSGenerator();
21
+ TORCH_API Generator
22
+ createMPSGenerator(uint64_t seed_val = default_rng_seed_val);
23
+
24
+ } // namespace mps::detail
25
+
26
+ struct TORCH_API MPSGeneratorImpl : public c10::GeneratorImpl {
27
+ // Constructors
28
+ MPSGeneratorImpl(uint64_t seed_in = default_rng_seed_val);
29
+ ~MPSGeneratorImpl() override = default;
30
+
31
+ // MPSGeneratorImpl methods
32
+ std::shared_ptr<MPSGeneratorImpl> clone() const;
33
+ void set_current_seed(uint64_t seed) override;
34
+ void set_offset(uint64_t offset) override;
35
+ uint64_t get_offset() const override;
36
+ uint64_t current_seed() const override;
37
+ uint64_t seed() override;
38
+ void set_state(const c10::TensorImpl& new_state) override;
39
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
40
+ void update_philox_counters();
41
+
42
+ void set_engine(at::Philox4_32 engine) {
43
+ engine_ = engine;
44
+ }
45
+ at::Philox4_32 engine() {
46
+ return engine_;
47
+ }
48
+ uint32_t* state_data() {
49
+ return data_.state.data();
50
+ }
51
+ static DeviceType device_type() {
52
+ return DeviceType::MPS;
53
+ }
54
+
55
+ private:
56
+ mps::detail::rng_data_pod data_;
57
+ at::Philox4_32 engine_;
58
+
59
+ MPSGeneratorImpl* clone_impl() const override;
60
+ };
61
+
62
+ } // namespace at
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)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/Context.h>
6
+ #include <ATen/mps/MPSEvent.h>
7
+ #include <ATen/mps/MPSStream.h>
8
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
9
+ #include <c10/macros/Macros.h>
10
+ #include <c10/util/Exception.h>
11
+
12
+ #ifdef __OBJC__
13
+ #include <Foundation/Foundation.h>
14
+ #include <Metal/Metal.h>
15
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
16
+ #endif
17
+
18
+ #include <ATen/Tensor.h>
19
+ #include <c10/core/MemoryFormat.h>
20
+ #include <c10/core/Storage.h>
21
+ #include <c10/core/TensorImpl.h>
22
+ #include <c10/core/UndefinedTensorImpl.h>
23
+ #include <c10/util/intrusive_ptr.h>
24
+ #include <sys/_types/_size_t.h>
25
+ #include <memory>
26
+
27
+ namespace at::mps {
28
+
29
+ typedef MPSEvent* mpsEvent_t;
30
+
31
+ // TODO: Move the MPSGuardImpl to inherit from NoOpDeviceGuardImpl
32
+ // https://github.com/pytorch/pytorch/issues/77170
33
+ struct TORCH_API MPSGuardImpl final
34
+ : public c10::impl::DeviceGuardImplInterface {
35
+ static constexpr c10::DeviceType static_type = c10::DeviceType::MPS;
36
+
37
+ // constructor
38
+ MPSGuardImpl() {}
39
+ explicit MPSGuardImpl(c10::DeviceType t) {
40
+ TORCH_CHECK(
41
+ t == DeviceType::MPS,
42
+ "MPSGuardImpl initialized with non-MPS DeviceType: ",
43
+ t);
44
+ }
45
+
46
+ // returns the type
47
+ c10::DeviceType type() const override {
48
+ return c10::DeviceType::MPS;
49
+ }
50
+
51
+ Device exchangeDevice(Device d) const override {
52
+ return Device(c10::DeviceType::MPS, 0);
53
+ }
54
+
55
+ Device getDevice() const override {
56
+ return Device(c10::DeviceType::MPS, 0);
57
+ }
58
+
59
+ std::optional<Device> uncheckedGetDevice() const noexcept {
60
+ return Device(c10::DeviceType::MPS, 0);
61
+ }
62
+
63
+ void setDevice(Device d) const override {
64
+ TORCH_CHECK(d.is_mps(), "Expected a MPS device, but got ", d);
65
+ }
66
+
67
+ void uncheckedSetDevice(Device d) const noexcept override {
68
+ // TODO: Currently setting only device 0
69
+ }
70
+
71
+ Stream getStream(Device d) const override {
72
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
73
+ }
74
+
75
+ Stream getNewStream(Device, int priority = 0) const override {
76
+ (void)priority;
77
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
78
+ }
79
+
80
+ Stream getDefaultStream(Device d) const override {
81
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
82
+ }
83
+
84
+ // NB: These do NOT set the current device
85
+ Stream exchangeStream(Stream s) const override {
86
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
87
+ }
88
+ DeviceIndex deviceCount() const noexcept override {
89
+ if (at::hasMPS()) {
90
+ // TODO: extend it for multi-device case
91
+ return 1;
92
+ } else {
93
+ return 0;
94
+ }
95
+ }
96
+
97
+ // Event-related functions
98
+ void createEvent(mpsEvent_t* event, const EventFlag flag) const;
99
+
100
+ void destroyEvent(void* event, const DeviceIndex device_index)
101
+ const noexcept override;
102
+
103
+ void record(
104
+ void** event,
105
+ const Stream& stream,
106
+ const DeviceIndex device_index,
107
+ const EventFlag flag) const override;
108
+
109
+ void block(void* event, const Stream& stream) const override;
110
+
111
+ bool queryEvent(void* event) const override;
112
+
113
+ void synchronizeEvent(void* event) const override;
114
+
115
+ double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
116
+ const override;
117
+
118
+ void synchronizeDevice(const DeviceIndex device_index) const override;
119
+ };
120
+
121
+ /// A variant of OptionalDeviceGuard that is specialized for MPS.
122
+ struct OptionalMPSGuard {
123
+ explicit OptionalMPSGuard() : guard_() {}
124
+
125
+ explicit OptionalMPSGuard(std::optional<Device> device_opt)
126
+ : guard_(device_opt) {}
127
+
128
+ /// Set the current MPS device to the passed device index, if it is not
129
+ /// nullopt
130
+ explicit OptionalMPSGuard(std::optional<DeviceIndex> device_index_opt)
131
+ : guard_(device_index_opt) {}
132
+
133
+ // Copy is not allowed
134
+ OptionalMPSGuard(const OptionalMPSGuard&) = delete;
135
+ OptionalMPSGuard& operator=(const OptionalMPSGuard&) = delete;
136
+ OptionalMPSGuard(OptionalMPSGuard&& other) = delete;
137
+ OptionalMPSGuard& operator=(OptionalMPSGuard&& other) = delete;
138
+
139
+ /// Sets the MPS device to the given device, initializing the guard if it
140
+ /// is not already initialized. Errors if the given device is not a MPS
141
+ /// device.
142
+ void set_device(Device device) {
143
+ guard_.set_device(device);
144
+ }
145
+
146
+ /// Sets the MPS device to the given device, initializing the guard if it is
147
+ /// not already initialized. Errors if the given device is not a MPS device.
148
+ void reset_device(Device device) {
149
+ guard_.reset_device(device);
150
+ }
151
+
152
+ /// Sets the MPS device to the given device index, initializing the guard if
153
+ /// it is not already initialized.
154
+ void set_index(DeviceIndex device_index) {
155
+ guard_.set_index(device_index);
156
+ }
157
+
158
+ /// Returns the device that was set immediately prior to initialization of the
159
+ /// guard, or nullopt if the guard is uninitialized.
160
+ std::optional<Device> original_device() const {
161
+ return guard_.original_device();
162
+ }
163
+
164
+ /// Returns the most recent device that was set using this device guard,
165
+ /// either from construction, or via set_device, if the guard is initialized,
166
+ /// or nullopt if the guard is uninitialized.
167
+ std::optional<Device> current_device() const {
168
+ return guard_.current_device();
169
+ }
170
+
171
+ /// Restore the original MPS device, resetting this guard to uninitialized
172
+ /// state.
173
+ void reset() {
174
+ guard_.reset();
175
+ }
176
+
177
+ private:
178
+ c10::impl::InlineOptionalDeviceGuard<MPSGuardImpl> guard_;
179
+ };
180
+
181
+ C10_REGISTER_GUARD_IMPL(MPS, MPSGuardImpl)
182
+
183
+ } // namespace at::mps
184
+
185
+ #else
186
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
187
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/Generator.h>
7
+ #include <ATen/detail/MPSHooksInterface.h>
8
+ #include <ATen/mps/MPSEvent.h>
9
+ #include <optional>
10
+
11
+ namespace at::mps {
12
+
13
+ // The real implementation of MPSHooksInterface
14
+ struct MPSHooks : public at::MPSHooksInterface {
15
+ MPSHooks(at::MPSHooksArgs) {}
16
+ void init() const override;
17
+
18
+ // MPSDevice interface
19
+ bool hasMPS() const override;
20
+ bool isOnMacOSorNewer(unsigned major, unsigned minor) const override;
21
+
22
+ Device getDeviceFromPtr(void* data) const override;
23
+
24
+ // MPSGeneratorImpl interface
25
+ const Generator& getDefaultGenerator(
26
+ DeviceIndex device_index = -1) const override;
27
+ Generator getNewGenerator(DeviceIndex device_index = -1) const override;
28
+
29
+ // MPSStream interface
30
+ void deviceSynchronize() const override;
31
+ void commitStream() const override;
32
+ void* getCommandBuffer() const override;
33
+ void* getDispatchQueue() const override;
34
+
35
+ // MPSAllocator interface
36
+ Allocator* getMPSDeviceAllocator() const override;
37
+ void emptyCache() const override;
38
+ size_t getCurrentAllocatedMemory() const override;
39
+ size_t getDriverAllocatedMemory() const override;
40
+ size_t getRecommendedMaxMemory() const override;
41
+ void setMemoryFraction(double ratio) const override;
42
+ bool isPinnedPtr(const void* data) const override;
43
+ Allocator* getPinnedMemoryAllocator() const override;
44
+
45
+ // MPSProfiler interface
46
+ void profilerStartTrace(const std::string& mode, bool waitUntilCompleted)
47
+ const override;
48
+ void profilerStopTrace() const override;
49
+
50
+ // MPSEvent interface
51
+ uint32_t acquireEvent(bool enable_timing) const override;
52
+ void releaseEvent(uint32_t event_id) const override;
53
+ void recordEvent(uint32_t event_id) const override;
54
+ void waitForEvent(uint32_t event_id) const override;
55
+ void synchronizeEvent(uint32_t event_id) const override;
56
+ bool queryEvent(uint32_t event_id) const override;
57
+ double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id)
58
+ const override;
59
+
60
+ bool isBuilt() const override {
61
+ return true;
62
+ }
63
+ bool isAvailable() const override {
64
+ return hasMPS();
65
+ }
66
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
67
+ // When MPS is available, it is always in use for the one device.
68
+ return true;
69
+ }
70
+ };
71
+
72
+ } // namespace at::mps
73
+
74
+ #else
75
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
76
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/Tensor.h>
7
+ #include <ATen/mps/MPSAllocatorInterface.h>
8
+ #include <ATen/mps/MPSStream.h>
9
+
10
+ #include <os/log.h>
11
+ #include <os/signpost.h>
12
+
13
+ #include <atomic>
14
+ #include <ctime>
15
+ #include <sstream>
16
+ #include <string>
17
+ #include <unordered_map>
18
+ #include <utility>
19
+
20
+ #ifndef __OBJC__
21
+ typedef void* MTLCaptureManager;
22
+ #endif
23
+
24
+ namespace at::mps {
25
+
26
+ namespace Profiler {
27
+
28
+ struct BaseInfo {
29
+ // profiling info types
30
+ enum class Type {
31
+ GRAPH,
32
+ KERNEL,
33
+ COPY,
34
+ CPU_FALLBACK,
35
+ };
36
+
37
+ BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle)
38
+ : type(infoType), profileId(Id), handle(Handle) {}
39
+ virtual ~BaseInfo() = default;
40
+
41
+ // type of profiling info
42
+ Type type;
43
+ // unique profile ID for execution instances of operations or copies
44
+ uint64_t profileId;
45
+ // ID generated by os_signpost
46
+ // since it's possible to use event and interval-based signposts at the
47
+ // same time, we need separate IDs for each.
48
+ os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0;
49
+ // accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime -
50
+ // GPUStartTime")
51
+ std::atomic<double> totalGpuTime{0.0};
52
+ // accumulated Scheduling time in ms (obtained from CompletionHandler's
53
+ // "KernelEndTime - KernelStartTime")
54
+ std::atomic<double> totalSchedulingTime{0.0};
55
+ // indicates if the operation or copy execution has completed
56
+ std::atomic_bool completed{false};
57
+ // handle used to identify the profile info's instance (usually the pointer)
58
+ const uintptr_t handle;
59
+
60
+ virtual const std::string toString(
61
+ double gpuTime = 0,
62
+ double schedulingTime = 0) const;
63
+ // builds a string for a tensor (format: Device:ScalarType[tensor.sizes()])
64
+ static std::string buildTensorString(
65
+ const Tensor& tensor,
66
+ bool includeBufferId = false);
67
+ static uint64_t getTime() {
68
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
69
+ }
70
+ };
71
+
72
+ struct OperationInfo : BaseInfo {
73
+ OperationInfo(
74
+ const void* Handle,
75
+ bool IsGraph,
76
+ uint64_t Id,
77
+ const std::string& StrKey)
78
+ : BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)),
79
+ strKey(StrKey) {}
80
+
81
+ uint64_t runCount = 0;
82
+ std::string strKey;
83
+
84
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
85
+ const override;
86
+
87
+ // builds a string for a kernel
88
+ static std::string buildKernelString(
89
+ const std::string& kernelName,
90
+ const TensorList& tensors,
91
+ bool includeBufferId = false) {
92
+ std::stringstream kernelStr;
93
+ kernelStr << kernelName;
94
+ for (const Tensor& tensor : tensors) {
95
+ kernelStr << ':' << BaseInfo::buildTensorString(tensor, includeBufferId);
96
+ }
97
+ return kernelStr.str();
98
+ }
99
+ };
100
+
101
+ struct CpuFbInfo : BaseInfo {
102
+ CpuFbInfo(uint64_t Id, const std::string& OpName)
103
+ : BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {}
104
+
105
+ uint64_t runCount = 0;
106
+ // the current and total overhead of copies in bytes required to convert the
107
+ // Op's input tensors from MPS to CPU and then output from CPU back to MPS
108
+ size_t currentCopyOverhead = 0;
109
+ size_t totalCopyOverhead = 0;
110
+ std::string opName;
111
+ std::string strKey;
112
+ uint64_t startTime = 0;
113
+
114
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
115
+ const override;
116
+
117
+ void updateCopyOverhead(const TensorList& tensors) {
118
+ currentCopyOverhead = 0;
119
+ for (const Tensor& tensor : tensors) {
120
+ if (tensor.defined()) {
121
+ currentCopyOverhead += tensor.nbytes();
122
+ }
123
+ }
124
+ totalCopyOverhead += currentCopyOverhead;
125
+ }
126
+ };
127
+
128
+ struct CopyInfo : BaseInfo {
129
+ enum class Kind {
130
+ MPS_TO_MPS,
131
+ MPS_TO_CPU,
132
+ CPU_TO_MPS,
133
+ };
134
+
135
+ CopyInfo(
136
+ const void* Handle,
137
+ size_t Length,
138
+ uint64_t Id,
139
+ bool IsNonBlocking,
140
+ bool UsesBlitter)
141
+ : BaseInfo(Type::COPY, Id, uintptr_t(Handle)),
142
+ kind(Kind::MPS_TO_MPS),
143
+ length(Length),
144
+ isNonBlocking(IsNonBlocking),
145
+ usesBlitter(UsesBlitter) {}
146
+
147
+ Kind kind;
148
+ size_t length;
149
+ bool isNonBlocking;
150
+ bool usesBlitter;
151
+ std::string srcStrKey;
152
+ std::string dstStrKey;
153
+ // for copies that don't use blitters, we measure CPU time
154
+ uint64_t startTime = 0;
155
+
156
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
157
+ const override;
158
+
159
+ static std::string buildTensorString(
160
+ const void* buffer,
161
+ const OptionalTensorRef tensor,
162
+ bool includeBufferId = false);
163
+
164
+ static bool isStorageOnMPS(
165
+ const void* buffer,
166
+ const OptionalTensorRef tensor) {
167
+ if (tensor.has_value()) {
168
+ return tensor->device().type() == at::kMPS;
169
+ }
170
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer);
171
+ // getUnalignedBufferSize() returns -1 if input buffer is not on MPS device
172
+ return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0;
173
+ }
174
+
175
+ static Kind getCopyKind(
176
+ const void* srcBuffer,
177
+ const void* dstBuffer,
178
+ const OptionalTensorRef srcTensor,
179
+ const OptionalTensorRef dstTensor) {
180
+ const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor);
181
+ const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor);
182
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS);
183
+ if (isSrcOnMPS && !isDstOnMPS) {
184
+ return Kind::MPS_TO_CPU;
185
+ } else if (!isSrcOnMPS && isDstOnMPS) {
186
+ return Kind::CPU_TO_MPS;
187
+ }
188
+ return Kind::MPS_TO_MPS;
189
+ }
190
+ };
191
+
192
+ struct CopyStat : CopyInfo {
193
+ explicit CopyStat(std::string CopyKindStr)
194
+ : CopyInfo(nullptr, 0, 0, false, false),
195
+ kindStr(std::move(CopyKindStr)) {}
196
+ // total number of copies
197
+ size_t totalCount = 0;
198
+ // number of Scalar copies (i.e., less than sizeof(int64))
199
+ size_t scalarsCount = 0;
200
+ // number of blocking copies (i.e., require syncing to GPU)
201
+ size_t blockingCount = 0;
202
+ // number of copies that used memcpy(), instead of Metal Blit Encoder
203
+ size_t memcpyCount = 0;
204
+ // accumulated GPU time in ms for the scalar copies
205
+ std::atomic<double> scalarsGpuTime{0.0};
206
+ // copy kind in string type
207
+ std::string kindStr;
208
+ };
209
+
210
+ class MPSProfiler {
211
+ public:
212
+ // lower 16 bits used for profiler options
213
+ enum ProfileOptions : uint32_t {
214
+ OPTIONS_NONE = 0,
215
+ // ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK,
216
+ // etc.) (used for convenience to not compute bit flags by OR-ing manually)
217
+ // trace all signpost types using events
218
+ ALL_SIGNPOST_EVENTS = (1 << 0),
219
+ // trace all signpost types using intervals
220
+ ALL_SIGNPOST_INTERVALS = (1 << 1),
221
+ // always wait for command buffer to finish executing after each commit
222
+ WAIT_UNTIL_COMPLETED = (1 << 2),
223
+ // for interval-based signposts, include the scheduling portion of
224
+ // Graph/Kernel/Copy executions as well.
225
+ // if flag is disable, only "GPU run time" is included in interval,
226
+ // and not schedule time.
227
+ INCLUDE_SCHEDULE_INTERVAL = (1 << 3),
228
+
229
+ // use these if you need to trace signposts types individually (rarely
230
+ // required) trace signpost using intervals
231
+ USE_INTERVALS = (1 << 4),
232
+ // trace signpost by emitting events
233
+ USE_EVENTS = (1 << 5),
234
+ // used for sanity check (Change this when new option added)
235
+ OPTIONS_COUNT = (USE_EVENTS << 1) - 1,
236
+ };
237
+
238
+ // when adding new types, #define the type string in MPSProfiler.mm as well.
239
+ // upper 16 bits used for event types
240
+ enum SignpostTypes : uint32_t {
241
+ SIGNPOST_NONE = 0,
242
+ // trace signposts for PyTorch operation executions
243
+ RUN_OPERATION = (1 << 16),
244
+ // trace signposts for blitter copies
245
+ BLIT_COPY = (1 << 17),
246
+ // trace signposts for ops that fall back on CPU
247
+ CPU_FALLBACK = (1 << 18),
248
+ // used for sanity check (Change this when new type added)
249
+ SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1,
250
+ };
251
+
252
+ enum LogOptions : uint32_t {
253
+ LOG_NONE = 0,
254
+
255
+ // Info logging options during execution
256
+ // -------------------------------------
257
+ // prints operation info (id/key/run_count) during execution
258
+ OPERATION_INFO = (1 << 0),
259
+ // prints copy info (src/dst tensors/buffers, size, etc.) during execution
260
+ COPY_INFO = (1 << 1),
261
+ // prints CPU Fallback info (id/runCount/opName/copyOverhead) during
262
+ // execution
263
+ CPU_FALLBACK_INFO = (1 << 2),
264
+
265
+ // Profiling Statistics logging options when process terminates
266
+ // ------------------------------------------------------------
267
+ // prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before
268
+ // process terminates this is convenient to not combine following stats bit
269
+ // flags manually
270
+ ALL_STATS = (1 << 3),
271
+ // prints operation stats (GPU times, run count, etc.) before process
272
+ // terminates
273
+ OPERATION_STATS = (1 << 4),
274
+ // prints copies stats (GPU times, copy kinds, sizes, etc.) before process
275
+ // terminates
276
+ COPY_STATS = (1 << 5),
277
+ // prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies
278
+ // for tensors, etc.) before process terminates
279
+ CPU_FALLBACK_STATS = (1 << 6),
280
+
281
+ // Metadata format options when logging the info
282
+ // ---------------------------------------------
283
+ // if enabled, includes GPU run time in metadata (i.e.,
284
+ // GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324
285
+ // ms])
286
+ INCLUDE_GPU_TIME = (1 << 7),
287
+ // if enabled, includes GPU scheduling time in metadata separately
288
+ // (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers)
289
+ // e.g., [GPU=0.324 ms, KRNL=0.036 ms]
290
+ INCLUDE_KERNEL_TIME = (1 << 8),
291
+ // if enabled, includes the unique buffer ID in metadata for the storage
292
+ // of a tensor that was allocated on MPSAllocator. This is useful (along
293
+ // with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are
294
+ // involved with various operations.
295
+ INCLUDE_BUFFER_ID = (1 << 9),
296
+
297
+ // used for sanity check (Change this when new option added)
298
+ LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1,
299
+ };
300
+
301
+ explicit MPSProfiler();
302
+ ~MPSProfiler();
303
+
304
+ // the handle is either "MPSGraph*" or "id<MTLComputePipelineState>" for Metal
305
+ // Kernels the beginProfile*() functions return a profileId which is unique
306
+ // per graph/kernel/copy
307
+ uint64_t beginProfileKernel(
308
+ const void* handle,
309
+ const std::string& strKey,
310
+ bool isGraph);
311
+ uint64_t beginProfileKernel(
312
+ const void* handle,
313
+ const std::string& kernelName,
314
+ const TensorList& tensors);
315
+ uint64_t beginProfileCopy(
316
+ const void* srcBuffer,
317
+ const void* dstBuffer,
318
+ const OptionalTensorRef srcTensor,
319
+ const OptionalTensorRef dstTensor,
320
+ size_t length,
321
+ bool isNonBlocking,
322
+ bool usesBlitter = true);
323
+ uint64_t beginProfileCPUFallback(
324
+ const std::string& opName,
325
+ const TensorList& tensors);
326
+ void beginProfileGPUInterval(const void* handle);
327
+
328
+ void endProfileCopy(uint64_t profileId, SyncType syncType);
329
+ void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE);
330
+ void endProfileCPUFallback(const std::string& opName);
331
+
332
+ // these are used to hook into Python bindings for torch.mps.profiler module.
333
+ // this enables generating OS Signpost traces from MPSProfiler on-demand
334
+ // during runtime (instead of environment variables).
335
+ // The "mode" could be either "interval", "event", or both "interval,event"
336
+ // for interval-based and/or event-based signpost tracing.
337
+ void StartTrace(const std::string& mode, bool waitUntilCompleted);
338
+ void StopTrace();
339
+
340
+ // Abstractions for GPU trace capturing
341
+ bool isCaptureEnabled() const;
342
+ bool isCapturing() const;
343
+ void startCapture(const std::string& name, MPSStream* stream = nullptr);
344
+ void stopCapture(MPSStream* stream = nullptr);
345
+
346
+ // convenience functions to indicate whether signpost tracing or
347
+ // logging are enabled for the SignpostTypes
348
+ bool isOperationProfilingEnabled() const {
349
+ return (m_signpost_types & SignpostTypes::RUN_OPERATION) ||
350
+ (m_log_options &
351
+ (LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS));
352
+ }
353
+ bool isCopyProfilingEnabled() const {
354
+ return (m_signpost_types & SignpostTypes::BLIT_COPY) ||
355
+ (m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS));
356
+ }
357
+ bool isCPUFallbackProfilingEnabled() const {
358
+ return (m_signpost_types & SignpostTypes::CPU_FALLBACK) ||
359
+ (m_log_options &
360
+ (LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS));
361
+ }
362
+ bool isSignpostTracingEnabled() const {
363
+ return (m_signpost_types != SignpostTypes::SIGNPOST_NONE);
364
+ }
365
+
366
+ private:
367
+ // indicates what type of signpost types are enabled and traced by MPS
368
+ // profiler.
369
+ uint32_t m_signpost_types = 0;
370
+ uint32_t m_profile_options = 0;
371
+ uint32_t m_log_options = 0;
372
+ uint64_t m_kernel_counter = 0;
373
+ uint64_t m_graph_counter = 0;
374
+ uint64_t m_cpu_fb_counter = 0;
375
+ uint64_t m_copy_counter = 0;
376
+ // technically, it's possible to trace both events and intervals at the same
377
+ // time so we use separate os_log categories for them
378
+ os_log_t m_os_log_events;
379
+ os_log_t m_os_log_intervals;
380
+ // stats logging could run either from destructor or signal handler
381
+ // so this is used to check if logging has already started.
382
+ std::atomic_bool hasLoggedStats{false};
383
+ // indicates there are pending completionHandler callbacks that haven't been
384
+ // called yet.
385
+ std::atomic_bool hasPendingCompletionHandlers{false};
386
+ // used to capture sigint signal to log profiling stats
387
+ static struct sigaction currentSigint, previousSigint;
388
+
389
+ // We use the following lists for two reasons:
390
+ // 1- for interval-based signposts the "begin" point won't be in same function
391
+ // as the "end" point where we need to be able to retrieve signpost's info
392
+ // 2- if Operations info need to be logged when process ends using
393
+ // LogOptions::OPERATION_INFO.
394
+
395
+ // the pointer key for this map is either "MPSGraph*" or
396
+ // "id<MTLComputePipelineState>" for Metal Kernels this list is retained and
397
+ // could be logged along with aggregate profiling numbers when the process
398
+ // ends.
399
+ std::unordered_map<uintptr_t, std::unique_ptr<OperationInfo>>
400
+ m_op_info_list{};
401
+ // the string key for this map is the op name that we fall back to execute on
402
+ // CPU this list is retained and could be logged along with aggregate
403
+ // profiling numbers when the process ends.
404
+ std::unordered_map<std::string, std::unique_ptr<CpuFbInfo>>
405
+ m_cpu_fb_info_list{};
406
+ // this list contains the info for copies, and its key is the unique profileId
407
+ // which is generated from m_copy_counter
408
+ // The copyInfo list is not retained.
409
+ std::unordered_map<uint64_t, std::unique_ptr<CopyInfo>> m_copy_info_list{};
410
+ // a short list that contains copy stats
411
+ std::unordered_map<CopyInfo::Kind, std::unique_ptr<CopyStat>>
412
+ m_copy_stat_list{};
413
+
414
+ mutable MTLCaptureManager* captureManager = nil;
415
+ unsigned captureCount = 0;
416
+
417
+ void initialize();
418
+ void beginProfileExecution(BaseInfo& info, bool cpuExecution = false);
419
+ void endProfileExecution(
420
+ BaseInfo& info,
421
+ os_signpost_id_t event_signpost_id,
422
+ os_signpost_id_t interval_signpost_id,
423
+ double gpuTime,
424
+ double schedulingTime);
425
+ void addProfilerScheduledHandler(BaseInfo& info);
426
+ void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType);
427
+ void emitSignpostEvent(
428
+ SignpostTypes signpost_type,
429
+ os_signpost_id_t signpost_id,
430
+ const std::string& msg) const;
431
+ void beginSignpostInterval(
432
+ SignpostTypes signpost_type,
433
+ os_signpost_id_t signpost_id,
434
+ const std::string& msg) const;
435
+ void endSignpostInterval(
436
+ SignpostTypes signpost_type,
437
+ os_signpost_id_t signpost_id) const;
438
+
439
+ void updateCopyStats(
440
+ const CopyInfo& copyInfo,
441
+ double gpuTime,
442
+ double schedulingTime);
443
+ // returns true if logging the profiling info "during the execution" is
444
+ // enabled
445
+ bool isProfileInfoLoggingEnabled(
446
+ BaseInfo::Type infoType,
447
+ bool isExecutionEnded);
448
+ // logs all the profiling stats that are enabled
449
+ void logProfilingStats();
450
+ // logs kernel profiling stats when the process ends.
451
+ void logOperationsProfilingStats(std::FILE* f) const;
452
+ // logs CPU Fallback profiling stats when the process ends.
453
+ void logCPUFallbackProfilingStats(std::FILE* f) const;
454
+ // logs copy profiling stats when the process ends.
455
+ void logCopyProfilingStats(std::FILE* f) const;
456
+
457
+ os_signpost_id_t generateSignpostId(
458
+ os_signpost_type_t signpostType,
459
+ const void* ptr = nullptr);
460
+ static SignpostTypes getSignpostType(BaseInfo::Type infoType);
461
+ static void handleIntSignal(int signal);
462
+ };
463
+
464
+ } // namespace Profiler
465
+
466
+ Profiler::MPSProfiler& getMPSProfiler();
467
+
468
+ } // namespace at::mps
469
+
470
+ #else
471
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
472
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <cstdint>
7
+ #include <utility>
8
+
9
+ #include <ATen/mps/MPSDevice.h>
10
+ #include <c10/core/DeviceGuard.h>
11
+ #include <c10/core/Stream.h>
12
+ #include <c10/util/Exception.h>
13
+
14
+ #ifdef __OBJC__
15
+ #include <Foundation/Foundation.h>
16
+ #include <Metal/Metal.h>
17
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
18
+ #include <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
19
+ typedef MPSCommandBuffer* MPSCommandBuffer_t;
20
+ typedef id<MTLCommandQueue> MTLCommandQueue_t;
21
+ typedef id<MTLComputeCommandEncoder> MTLComputeCommandEncoder_t;
22
+ typedef id<MTLSharedEvent> MTLSharedEvent_t;
23
+ typedef id<MTLDevice> MTLDevice_t;
24
+ typedef id<MTLBuffer> MTLBuffer_t;
25
+ #else
26
+ #include <dispatch/dispatch.h>
27
+ typedef void* MPSCommandBuffer_t;
28
+ typedef void* MPSGraph;
29
+ typedef void* MPSGraphExecutionDescriptor;
30
+ typedef void* MPSGraphCompilationDescriptor;
31
+ typedef void* MTLCommandQueue_t;
32
+ typedef void* MTLComputeCommandEncoder_t;
33
+ typedef void* MTLSharedEvent_t;
34
+ typedef void* MTLDevice_t;
35
+ typedef void* MTLBuffer_t;
36
+ typedef void* MTLCommandBufferHandler;
37
+ typedef void* NSDictionary;
38
+ #define nil NULL
39
+ #endif
40
+
41
+ namespace at::mps {
42
+
43
+ //-----------------------------------------------------------------
44
+ // MPSStream
45
+ //-----------------------------------------------------------------
46
+
47
+ enum class SyncType {
48
+ NONE, // no commit to command buffer
49
+ COMMIT, // commit and flush the command buffer
50
+ COMMIT_AND_WAIT, // flush and wait for command buffer execution to finish
51
+ COMMIT_AND_CONTINUE, // commit and continue with a new underlying command buffer
52
+ COMMIT_ADAPTIVE, // commit adaptively based on available memory
53
+ };
54
+
55
+ class TORCH_API MPSStream {
56
+ public:
57
+ enum Unchecked { UNCHECKED };
58
+
59
+ /// Construct a MPSStream from a Stream. This construction is checked,
60
+ /// and will raise an error if the Stream is not, in fact, a MPS stream.
61
+ explicit MPSStream(Stream stream);
62
+
63
+ ~MPSStream();
64
+
65
+ MTLCommandQueue_t commandQueue() const {
66
+ return _commandQueue;
67
+ }
68
+
69
+ dispatch_queue_t queue() const {
70
+ return _serialQueue;
71
+ }
72
+
73
+ MPSCommandBuffer_t commandBuffer();
74
+ MTLComputeCommandEncoder_t commandEncoder();
75
+ void endKernelCoalescing();
76
+ void synchronize(SyncType syncType);
77
+ void fill(MTLBuffer_t buffer, uint8_t value, size_t length, size_t offset, SyncType syncType = SyncType::NONE);
78
+ void copy(MTLBuffer_t srcBuffer,
79
+ MTLBuffer_t dstBuffer,
80
+ size_t length,
81
+ size_t srcOffset,
82
+ size_t dstOffset,
83
+ uint64_t profileId,
84
+ SyncType syncType = SyncType::NONE);
85
+ void copy_and_sync(MTLBuffer_t srcBuffer,
86
+ MTLBuffer_t dstBuffer,
87
+ size_t length,
88
+ size_t srcOffset,
89
+ size_t dstOffset,
90
+ bool non_blocking,
91
+ uint64_t profileId);
92
+ void executeMPSGraph(MPSGraph* mpsGraph,
93
+ NSDictionary* feeds,
94
+ NSDictionary* results,
95
+ SyncType syncType = SyncType::NONE);
96
+ void addCompletedHandler(MTLCommandBufferHandler block);
97
+
98
+ /// Get the MPS device index that this stream is associated with.
99
+ c10::DeviceIndex device_index() const {
100
+ return _stream.device_index();
101
+ }
102
+
103
+ MTLCommandQueue_t stream() const {
104
+ return _commandQueue;
105
+ }
106
+
107
+ MTLDevice_t device() const;
108
+
109
+ /// Explicit conversion to Stream.
110
+ Stream unwrap() const {
111
+ return _stream;
112
+ }
113
+
114
+ MTLBuffer_t getErrorBuffer();
115
+ void checkLastError();
116
+
117
+ private:
118
+ Stream _stream;
119
+ MTLCommandQueue_t _commandQueue = nil;
120
+ MPSCommandBuffer_t _commandBuffer = nil;
121
+ MPSCommandBuffer_t _prevCommandBuffer = nil;
122
+ MTLComputeCommandEncoder_t _commandEncoder = nil;
123
+ MPSGraphExecutionDescriptor* _executionDescriptor = nil;
124
+ MPSGraphCompilationDescriptor* _compilationDescriptor = nil;
125
+ dispatch_queue_t _serialQueue = nullptr;
126
+ // CommitAndContinue is enabled by default
127
+ bool _enableCommitAndContinue = true;
128
+ // Buffer that contains last raised error
129
+ MTLBuffer_t _errorBuffer = nil;
130
+
131
+ // use synchronize() to access any of these commit functions outside MPSStream
132
+ void commit();
133
+ void commitAndWait();
134
+ void commitAndContinue();
135
+ void flush();
136
+ };
137
+
138
+ /**
139
+ * Get the current MPS stream
140
+ */
141
+ TORCH_API MPSStream* getCurrentMPSStream();
142
+
143
+ /**
144
+ * Get the default MPS stream
145
+ */
146
+ TORCH_API MPSStream* getDefaultMPSStream();
147
+
148
+ //-----------------------------------------------------------------
149
+ // MPSStreamImpl
150
+ //-----------------------------------------------------------------
151
+
152
+ class TORCH_API MPSStreamImpl {
153
+ public:
154
+ /**
155
+ * Gets single instance of the MPSStream.
156
+ */
157
+ static MPSStream* getInstance();
158
+
159
+ private:
160
+ static MPSStream* _stream;
161
+ MPSStreamImpl();
162
+ };
163
+
164
+ #ifdef __OBJC__
165
+ void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)());
166
+ #endif
167
+ } // namespace at::mps
168
+
169
+ #else
170
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
171
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/MPSGraphSequoiaOps.h ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #define MTLLanguageVersion3_2 ((MTLLanguageVersion)((3 << 16) + 2))
43
+ #endif // Building for target older than MacOS-15
44
+
45
+ #if !defined(__MAC_26_0) && (!defined(MAC_OS_X_VERSION_26_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_26_0))
46
+ #define MTLLanguageVersion4_0 ((MTLLanguageVersion)((4 << 16) + 0))
47
+ #endif // Building for target older than MacOS-26
48
+
49
+ #else
50
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
51
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/MetalShaderLibrary.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ void setErrorBufferIndex(unsigned idx);
69
+ template <
70
+ typename T,
71
+ typename = std::enable_if_t<
72
+ std::is_integral_v<T> || std::is_same_v<T, float> ||
73
+ (std::is_class_v<T> && std::is_trivially_copyable_v<T> &&
74
+ !detail::has_size_type_v<T>)>>
75
+ inline void setArg(unsigned idx, const T val) {
76
+ setArg(idx, &val, sizeof(T));
77
+ }
78
+
79
+ template <
80
+ typename Container,
81
+ typename = std::enable_if_t<detail::has_size_type_v<Container>>>
82
+ inline void setArg(unsigned idx, const Container& values) {
83
+ setArg(
84
+ idx,
85
+ values.data(),
86
+ values.size() * sizeof(typename Container::value_type));
87
+ }
88
+ void dispatch(
89
+ uint64_t length,
90
+ std::optional<uint64_t> groupSize = std::nullopt);
91
+ void dispatch(
92
+ c10::ArrayRef<uint64_t> length,
93
+ c10::OptionalArrayRef<uint64_t> groupSize = std::nullopt);
94
+
95
+ private:
96
+ MTLComputePipelineState_t cps;
97
+ MTLFunction_t func;
98
+ MTLComputeCommandEncoder_t encoder = nullptr;
99
+ };
100
+
101
+ class MetalShaderLibrary {
102
+ public:
103
+ MetalShaderLibrary(std::string src)
104
+ : shaderSource(std::move(src)), nparams(0), compile_options(nullptr) {}
105
+ MetalShaderLibrary(std::string src, unsigned nparams_)
106
+ : shaderSource(std::move(src)),
107
+ nparams(nparams_),
108
+ compile_options(nullptr) {}
109
+ MetalShaderLibrary(
110
+ std::string src,
111
+ unsigned nparams_,
112
+ MTLCompileOptions* compile_options_)
113
+ : shaderSource(std::move(src)),
114
+ nparams(nparams_),
115
+ compile_options(compile_options_) {}
116
+ MetalShaderLibrary(const MetalShaderLibrary&) = delete;
117
+ virtual ~MetalShaderLibrary();
118
+ std::vector<std::string> getFunctionNames();
119
+ std::shared_ptr<MetalKernelFunction> getKernelFunction(
120
+ const std::string& name);
121
+ // Returns a raw pointer to the kernel function for use in C APIs
122
+ MetalKernelFunction* getCachedKernelFunctionPtr(const std::string& name);
123
+ inline MTLComputePipelineState_t getPipelineStateForFunc(
124
+ const std::string& fname) {
125
+ return getLibraryPipelineState(getLibrary(), fname).first;
126
+ }
127
+ MTLComputePipelineState_t getPipelineStateForFunc(
128
+ const std::string& fname,
129
+ const std::initializer_list<std::string>& params) {
130
+ return getLibraryPipelineState(getLibrary(params), fname).first;
131
+ }
132
+ inline MTLFunction_t getMTLFunction(const std::string& fname) {
133
+ return getLibraryPipelineState(getLibrary(), fname).second;
134
+ }
135
+ MTLFunction_t getMTLFunction(
136
+ const std::string& fname,
137
+ const std::initializer_list<std::string>& params) {
138
+ return getLibraryPipelineState(getLibrary(params), fname).second;
139
+ }
140
+ static MetalShaderLibrary& getBundledLibrary();
141
+ void exec_unary_kernel(
142
+ TensorIteratorBase& iter,
143
+ const std::string& name,
144
+ const std::optional<c10::Scalar> alpha = std::nullopt,
145
+ const std::optional<c10::ScalarType> scalar_arg_type = std::nullopt);
146
+ void exec_binary_kernel(
147
+ TensorIteratorBase& iter,
148
+ const std::string& name,
149
+ const std::optional<c10::Scalar> alpha = std::nullopt,
150
+ const std::optional<c10::ScalarType> scalar_arg_type = std::nullopt);
151
+ void exec_ternary_kernel(TensorIteratorBase& iter, const std::string& name);
152
+
153
+ template <typename T>
154
+ void exec_unary_kernel_with_params(
155
+ TensorIteratorBase& iter,
156
+ const std::string& name,
157
+ T params,
158
+ const std::string& params_type_name);
159
+ template <typename T>
160
+ void exec_binary_kernel_with_params(
161
+ TensorIteratorBase& iter,
162
+ const std::string& name,
163
+ T params,
164
+ const std::string& params_type_name);
165
+
166
+ protected:
167
+ virtual MTLLibrary_t getLibrary();
168
+ virtual MTLLibrary_t getLibrary(
169
+ const std::initializer_list<std::string>& params);
170
+ MTLLibrary_t library = nullptr;
171
+
172
+ private:
173
+ std::pair<MTLComputePipelineState_t, MTLFunction_t> getLibraryPipelineState(
174
+ MTLLibrary_t lib,
175
+ const std::string& fname);
176
+ MTLLibrary_t compileLibrary(const std::string& src);
177
+ std::string shaderSource;
178
+ unsigned nparams;
179
+ MTLCompileOptions* compile_options;
180
+ std::unordered_map<std::string, MTLLibrary_t> libMap;
181
+ std::unordered_map<
182
+ std::string,
183
+ std::pair<MTLComputePipelineState_t, MTLFunction_t>>
184
+ cplMap;
185
+ // Cache for kernel functions returned by getCachedKernelFunctionPtr
186
+ std::unordered_map<std::string, std::unique_ptr<MetalKernelFunction>>
187
+ kernelCache;
188
+ };
189
+
190
+ class DynamicMetalShaderLibrary : public MetalShaderLibrary {
191
+ public:
192
+ DynamicMetalShaderLibrary(const std::string& src) : MetalShaderLibrary(src) {
193
+ // Compile right away
194
+ getLibrary();
195
+ }
196
+ ~DynamicMetalShaderLibrary() override;
197
+ };
198
+
199
+ } // namespace at::native::mps
200
+
201
+ #else
202
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
203
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/mps/kernels/LinearAlgebra.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 m2;
11
+ uint32_t n;
12
+ uint32_t k;
13
+
14
+ ::c10::metal::array<uint32_t, N> A_strides;
15
+ ::c10::metal::array<uint32_t, N> tau_strides;
16
+ ::c10::metal::array<uint32_t, N> H_strides;
17
+ ::c10::metal::array<uint32_t, N> H_sizes;
18
+ };
19
+
20
+ struct UnpackPivotsParams {
21
+ uint32_t perm_batch_stride;
22
+ uint32_t pivots_batch_stride;
23
+ uint32_t dim_size;
24
+ };
25
+
26
+ #else
27
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
28
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/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)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/flash_attn/flash_api.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstddef>
4
+
5
+ #include <namespace_config.h>
6
+ #include <ATen/core/Tensor.h>
7
+ #include <c10/util/Exception.h>
8
+
9
+ namespace FLASH_NAMESPACE {
10
+
11
+ TORCH_API
12
+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor>
13
+ mha_fwd(const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
14
+ const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
15
+ const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
16
+ std::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
17
+ std::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
18
+ const float p_dropout,
19
+ const float softmax_scale,
20
+ bool is_causal,
21
+ int window_size_left,
22
+ int window_size_right,
23
+ const float softcap,
24
+ const bool return_softmax,
25
+ std::optional<at::Generator> gen_);
26
+
27
+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor>
28
+ mha_varlen_fwd(const at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
29
+ const at::Tensor &k, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
30
+ const at::Tensor &v, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
31
+ std::optional<at::Tensor> &out_, // total_q x num_heads x head_size, total_k := \sum_{i=0}^{b} s_i
32
+ const at::Tensor &cu_seqlens_q, // b+1
33
+ const at::Tensor &cu_seqlens_k, // b+1
34
+ std::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
35
+ std::optional<at::Tensor> &block_table_, // batch_size x max_num_blocks_per_seq
36
+ std::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
37
+ int max_seqlen_q,
38
+ const int max_seqlen_k,
39
+ const float p_dropout,
40
+ const float softmax_scale,
41
+ const bool zero_tensors,
42
+ bool is_causal,
43
+ int window_size_left,
44
+ int window_size_right,
45
+ const float softcap,
46
+ const bool return_softmax,
47
+ std::optional<at::Generator> gen_);
48
+
49
+
50
+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor>
51
+ mha_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
52
+ const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
53
+ const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
54
+ const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
55
+ const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
56
+ const at::Tensor &softmax_lse, // b x h x seqlen_q
57
+ std::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
58
+ std::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
59
+ std::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
60
+ std::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
61
+ const float p_dropout, // probability to drop
62
+ const float softmax_scale,
63
+ const bool is_causal,
64
+ int window_size_left,
65
+ int window_size_right,
66
+ const float softcap,
67
+ const bool deterministic,
68
+ const at::Tensor philox_seed,
69
+ const at::Tensor philox_offset);
70
+
71
+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor>
72
+ mha_varlen_bwd(const at::Tensor &dout, // total_q x num_heads, x head_size
73
+ const at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
74
+ const at::Tensor &k, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
75
+ const at::Tensor &v, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
76
+ const at::Tensor &out, // total_q x num_heads x head_size
77
+ const at::Tensor &softmax_lse, // b x h x s softmax logsumexp
78
+ std::optional<at::Tensor> &dq_, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
79
+ std::optional<at::Tensor> &dk_, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
80
+ std::optional<at::Tensor> &dv_, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
81
+ const at::Tensor &cu_seqlens_q, // b+1
82
+ const at::Tensor &cu_seqlens_k, // b+1
83
+ std::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
84
+ const int max_seqlen_q,
85
+ const int max_seqlen_k, // max sequence length to choose the kernel
86
+ const float p_dropout, // probability to drop
87
+ const float softmax_scale,
88
+ const bool zero_tensors,
89
+ const bool is_causal,
90
+ int window_size_left,
91
+ int window_size_right,
92
+ const float softcap,
93
+ const bool deterministic,
94
+ const at::Tensor philox_seed,
95
+ const at::Tensor philox_offset);
96
+
97
+ } // namespace FLASH_NAMESPACE
98
+
99
+ #else
100
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
101
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/flash_attn/static_switch.h ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Inspired by
3
+ // https://github.com/NVIDIA/DALI/blob/main/include/dali/core/static_switch.h
4
+ // and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Dispatch.h
5
+
6
+ #pragma once
7
+
8
+ /// @param COND - a boolean expression to switch by
9
+ /// @param CONST_NAME - a name given for the constexpr bool variable.
10
+ /// @param ... - code to execute for true and false
11
+ ///
12
+ /// Usage:
13
+ /// ```
14
+ /// BOOL_SWITCH(flag, BoolConst, [&] {
15
+ /// some_function<BoolConst>(...);
16
+ /// });
17
+ /// ```
18
+
19
+ #define BOOL_SWITCH(COND, CONST_NAME, ...) \
20
+ [&] { \
21
+ if (COND) { \
22
+ constexpr static bool CONST_NAME = true; \
23
+ return __VA_ARGS__(); \
24
+ } else { \
25
+ constexpr static bool CONST_NAME = false; \
26
+ return __VA_ARGS__(); \
27
+ } \
28
+ }()
29
+
30
+ #ifdef FLASHATTENTION_DISABLE_DROPOUT
31
+ #define DROPOUT_SWITCH(COND, CONST_NAME, ...) \
32
+ [&] { \
33
+ constexpr static bool CONST_NAME = false; \
34
+ return __VA_ARGS__(); \
35
+ }()
36
+ #else
37
+ #define DROPOUT_SWITCH BOOL_SWITCH
38
+ #endif
39
+
40
+ #ifdef FLASHATTENTION_DISABLE_ALIBI
41
+ #define ALIBI_SWITCH(COND, CONST_NAME, ...) \
42
+ [&] { \
43
+ constexpr static bool CONST_NAME = false; \
44
+ return __VA_ARGS__(); \
45
+ }()
46
+ #else
47
+ #define ALIBI_SWITCH BOOL_SWITCH
48
+ #endif
49
+
50
+ #ifdef FLASHATTENTION_DISABLE_UNEVEN_K
51
+ #define EVENK_SWITCH(COND, CONST_NAME, ...) \
52
+ [&] { \
53
+ constexpr static bool CONST_NAME = true; \
54
+ return __VA_ARGS__(); \
55
+ }()
56
+ #else
57
+ #define EVENK_SWITCH BOOL_SWITCH
58
+ #endif
59
+
60
+ #ifdef FLASHATTENTION_DISABLE_LOCAL
61
+ #define LOCAL_SWITCH(COND, CONST_NAME, ...) \
62
+ [&] { \
63
+ constexpr static bool CONST_NAME = false; \
64
+ return __VA_ARGS__(); \
65
+ }()
66
+ #else
67
+ #define LOCAL_SWITCH BOOL_SWITCH
68
+ #endif
69
+
70
+ #define FP16_SWITCH(COND, ...) \
71
+ [&] { \
72
+ if (COND) { \
73
+ using elem_type = cutlass::half_t; \
74
+ return __VA_ARGS__(); \
75
+ } else { \
76
+ using elem_type = cutlass::bfloat16_t; \
77
+ return __VA_ARGS__(); \
78
+ } \
79
+ }()
80
+
81
+ #define HEADDIM_SWITCH(HEADDIM, ...) \
82
+ [&] { \
83
+ if (HEADDIM <= 32) { \
84
+ constexpr static int kHeadDim = 32; \
85
+ return __VA_ARGS__(); \
86
+ } else if (HEADDIM <= 64) { \
87
+ constexpr static int kHeadDim = 64; \
88
+ return __VA_ARGS__(); \
89
+ } else if (HEADDIM <= 96) { \
90
+ constexpr static int kHeadDim = 96; \
91
+ return __VA_ARGS__(); \
92
+ } else if (HEADDIM <= 128) { \
93
+ constexpr static int kHeadDim = 128; \
94
+ return __VA_ARGS__(); \
95
+ } else if (HEADDIM <= 160) { \
96
+ constexpr static int kHeadDim = 160; \
97
+ return __VA_ARGS__(); \
98
+ } else if (HEADDIM <= 192) { \
99
+ constexpr static int kHeadDim = 192; \
100
+ return __VA_ARGS__(); \
101
+ } else if (HEADDIM <= 224) { \
102
+ constexpr static int kHeadDim = 224; \
103
+ return __VA_ARGS__(); \
104
+ } else if (HEADDIM <= 256) { \
105
+ constexpr static int kHeadDim = 256; \
106
+ return __VA_ARGS__(); \
107
+ } \
108
+ }()
109
+
110
+ #else
111
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
112
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma.h ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
10
+
11
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_multistage.h>
12
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_pipelined.h>
13
+
14
+ #include <cutlass/gemm/threadblock/mma_multistage.h>
15
+ #include <cutlass/gemm/threadblock/mma_pipelined.h>
16
+ template <typename Mma, int kMaxK>
17
+ struct MakeCustomMma;
18
+
19
+ template <
20
+ typename Shape,
21
+ typename IteratorA,
22
+ typename SmemIteratorA,
23
+ cutlass::arch::CacheOperation::Kind CacheOpA,
24
+ typename IteratorB,
25
+ typename SmemIteratorB,
26
+ cutlass::arch::CacheOperation::Kind CacheOpB,
27
+ typename ElementC,
28
+ typename LayoutC,
29
+ typename Policy,
30
+ int Stages,
31
+ cutlass::gemm::SharedMemoryClearOption SharedMemoryClear,
32
+ int kMaxK>
33
+ struct MakeCustomMma<
34
+ cutlass::gemm::threadblock::MmaMultistage<
35
+ Shape,
36
+ IteratorA,
37
+ SmemIteratorA,
38
+ CacheOpA,
39
+ IteratorB,
40
+ SmemIteratorB,
41
+ CacheOpB,
42
+ ElementC,
43
+ LayoutC,
44
+ Policy,
45
+ Stages,
46
+ SharedMemoryClear>,
47
+ kMaxK> {
48
+ // Reduce the number of stages if we don't need that many
49
+ static int constexpr kStages =
50
+ kMaxK == cutlass::platform::numeric_limits<int>::max()
51
+ ? Stages
52
+ : cutlass::const_min(
53
+ Stages,
54
+ (kMaxK + int(Shape::kK) - 1) / int(Shape::kK));
55
+ using Mma = cutlass::gemm::threadblock::CustomMmaMultistage<
56
+ Shape,
57
+ IteratorA,
58
+ SmemIteratorA,
59
+ CacheOpA,
60
+ IteratorB,
61
+ SmemIteratorB,
62
+ CacheOpB,
63
+ ElementC,
64
+ LayoutC,
65
+ Policy,
66
+ kStages,
67
+ SharedMemoryClear,
68
+ kMaxK>;
69
+ };
70
+
71
+ template <
72
+ typename Shape,
73
+ typename IteratorA,
74
+ typename SmemIteratorA,
75
+ typename IteratorB,
76
+ typename SmemIteratorB,
77
+ typename ElementC,
78
+ typename LayoutC,
79
+ typename Policy,
80
+ int kMaxK>
81
+ struct MakeCustomMma<
82
+ cutlass::gemm::threadblock::MmaPipelined<
83
+ Shape,
84
+ IteratorA,
85
+ SmemIteratorA,
86
+ IteratorB,
87
+ SmemIteratorB,
88
+ ElementC,
89
+ LayoutC,
90
+ Policy>,
91
+ kMaxK> {
92
+ using Mma = cutlass::gemm::threadblock::CustomMmaPipelined<
93
+ Shape,
94
+ IteratorA,
95
+ SmemIteratorA,
96
+ IteratorB,
97
+ SmemIteratorB,
98
+ ElementC,
99
+ LayoutC,
100
+ Policy>;
101
+ };
102
+
103
+ #else
104
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
105
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_base.h ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /***************************************************************************************************
3
+ * Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights
4
+ *reserved. SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice,
10
+ *this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ * this list of conditions and the following disclaimer in the documentation
14
+ * and/or other materials provided with the distribution.
15
+ *
16
+ * 3. Neither the name of the copyright holder nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ *POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ **************************************************************************************************/
33
+ /*! \file
34
+ \brief Template for a double-buffered threadblock-scoped GEMM kernel.
35
+ */
36
+
37
+ #pragma once
38
+
39
+ #include <cutlass/aligned_buffer.h>
40
+ #include <cutlass/arch/memory.h>
41
+ #include <cutlass/array.h>
42
+ #include <cutlass/cutlass.h>
43
+ #include <cutlass/gemm/gemm.h>
44
+ #include <cutlass/gemm/threadblock/mma_base.h>
45
+ #include <cutlass/matrix_shape.h>
46
+ #include <cutlass/numeric_types.h>
47
+
48
+ ////////////////////////////////////////////////////////////////////////////////
49
+
50
+ namespace cutlass {
51
+ namespace gemm {
52
+ namespace threadblock {
53
+
54
+ ////////////////////////////////////////////////////////////////////////////////
55
+
56
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
57
+ /// instructions.
58
+ template <
59
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
60
+ typename Shape_,
61
+ /// Policy describing tuning details (concept: MmaPolicy)
62
+ typename Policy_,
63
+ /// Number of stages,
64
+ int Stages,
65
+ /// Used for partial specialization
66
+ typename Enable = bool>
67
+ class CustomMmaBase {
68
+ public:
69
+ ///< Size of the Gemm problem - concept: gemm::GemmShape<>
70
+ using Shape = Shape_;
71
+
72
+ ///< Policy describing tuning details
73
+ using Policy = Policy_;
74
+
75
+ //
76
+ // Dependent types
77
+ //
78
+
79
+ /// Warp-level Mma
80
+ using Operator = typename Policy::Operator;
81
+
82
+ /// Shape describing the overall GEMM computed from shared memory
83
+ /// by each warp.
84
+ using WarpGemm = typename Policy::Operator::Shape;
85
+
86
+ /// Shape describing the number of warps filling the CTA
87
+ using WarpCount = GemmShape<
88
+ Shape::kM / WarpGemm::kM,
89
+ Shape::kN / WarpGemm::kN,
90
+ Shape::kK / WarpGemm::kK>;
91
+
92
+ /// Number of warp-level GEMM operations
93
+ static int const kWarpGemmIterations =
94
+ (WarpGemm::kK / Operator::Policy::MmaShape::kK);
95
+
96
+ /// Number of stages
97
+ static int const kStages = Stages;
98
+
99
+ //
100
+ // Nested structs
101
+ //
102
+
103
+ /// Shared storage object needed by threadblock-scoped GEMM
104
+ template <typename Element, typename OperandShape, typename OperandLayout>
105
+ struct OperandSharedStorage {
106
+ AlignedBuffer<Element, OperandShape::kCount> buffer;
107
+ using TensorRef = TensorRef<Element, OperandLayout>;
108
+
109
+ CUTLASS_DEVICE
110
+ static OperandLayout Layout() {
111
+ return OperandLayout::packed({OperandShape::kRow, OperandShape::kColumn});
112
+ }
113
+
114
+ /// Returns a TensorRef to the operand
115
+ CUTLASS_HOST_DEVICE
116
+ TensorRef ref() {
117
+ return TensorRef{buffer.data(), Layout()};
118
+ }
119
+ };
120
+
121
+ /// Shape of the A matrix operand in shared memory
122
+ using ShapeA = MatrixShape<
123
+ Shape::kM + Policy::SmemPaddingA::kRow,
124
+ Shape::kK * kStages + Policy::SmemPaddingA::kColumn>;
125
+
126
+ /// Shape of the B matrix operand in shared memory
127
+ using ShapeB = MatrixShape<
128
+ Shape::kK * kStages + Policy::SmemPaddingB::kRow,
129
+ Shape::kN + Policy::SmemPaddingB::kColumn>;
130
+
131
+ using SharedStorageA = OperandSharedStorage<
132
+ typename Operator::ElementA,
133
+ ShapeA,
134
+ typename Operator::LayoutA>;
135
+ using SharedStorageB = OperandSharedStorage<
136
+ typename Operator::ElementB,
137
+ ShapeB,
138
+ typename Operator::LayoutB>;
139
+ using TensorRefA = typename SharedStorageA::TensorRef;
140
+ using TensorRefB = typename SharedStorageB::TensorRef;
141
+
142
+ struct SharedStorage {
143
+ /// Buffer for A operand
144
+ SharedStorageA operand_A;
145
+
146
+ /// Buffer for B operand
147
+ SharedStorageB operand_B;
148
+ };
149
+
150
+ protected:
151
+ //
152
+ // Data members
153
+ //
154
+
155
+ /// Iterator to load a warp-scoped tile of A operand from shared memory
156
+ typename Operator::IteratorA warp_tile_iterator_A_;
157
+
158
+ /// Iterator to load a warp-scoped tile of B operand from shared memory
159
+ typename Operator::IteratorB warp_tile_iterator_B_;
160
+
161
+ public:
162
+ /// Construct from tensor references
163
+ CUTLASS_DEVICE
164
+ CustomMmaBase(
165
+ ///< Shared storage needed for internal use by threadblock-scoped GEMM
166
+ SharedStorageA& shared_storageA,
167
+ SharedStorageB& shared_storageB,
168
+ ///< ID within the threadblock
169
+ int thread_idx,
170
+ ///< ID of warp
171
+ int warp_idx,
172
+ ///< ID of each thread within a warp
173
+ int lane_idx)
174
+ : warp_tile_iterator_A_(shared_storageA.ref(), lane_idx),
175
+ warp_tile_iterator_B_(shared_storageB.ref(), lane_idx) {}
176
+ };
177
+
178
+ /////////////////////////////////////////////////////////////////////////////////////////////////
179
+
180
+ } // namespace threadblock
181
+ } // namespace gemm
182
+ } // namespace cutlass
183
+
184
+ /////////////////////////////////////////////////////////////////////////////////////////////////
185
+
186
+ #else
187
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
188
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_multistage.h ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /***************************************************************************************************
3
+ * Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights
4
+ *reserved. SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice,
10
+ *this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ * this list of conditions and the following disclaimer in the documentation
14
+ * and/or other materials provided with the distribution.
15
+ *
16
+ * 3. Neither the name of the copyright holder nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ *POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ **************************************************************************************************/
33
+ /*! \file
34
+ \brief Template for a double-buffered threadblock-scoped GEMM kernel.
35
+ */
36
+
37
+ #pragma once
38
+
39
+ #include <cutlass/aligned_buffer.h>
40
+ #include <cutlass/arch/cache_operation.h>
41
+ #include <cutlass/arch/memory.h>
42
+ #include <cutlass/arch/mma.h>
43
+ #include <cutlass/array.h>
44
+ #include <cutlass/cutlass.h>
45
+ #include <cutlass/gemm/gemm.h>
46
+ #include <cutlass/matrix_shape.h>
47
+ #include <cutlass/numeric_types.h>
48
+
49
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_base.h>
50
+
51
+ /////////////////////////////////////////////////////////////////////////////////////////////////
52
+
53
+ namespace cutlass {
54
+ namespace gemm {
55
+ namespace threadblock {
56
+
57
+ /////////////////////////////////////////////////////////////////////////////////////////////////
58
+
59
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
60
+ /// instructions.
61
+ template <
62
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
63
+ typename Shape_,
64
+ /// Iterates over tiles of A operand in global memory
65
+ // (concept: ReadableTileIterator | ForwardTileIterator |
66
+ // MaskedTileIterator)
67
+ typename IteratorA_,
68
+ /// Iterates over tiles of A operand in shared memory
69
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
70
+ typename SmemIteratorA_,
71
+ /// Cache operation for operand A
72
+ cutlass::arch::CacheOperation::Kind CacheOpA,
73
+ /// Iterates over tiles of B operand in global memory
74
+ // (concept: ReadableTileIterator | ForwardTileIterator |
75
+ // MaskedTileIterator)
76
+ typename IteratorB_,
77
+ /// Iterates over tiles of B operand in shared memory
78
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
79
+ typename SmemIteratorB_,
80
+ /// Cache operation for operand B
81
+ cutlass::arch::CacheOperation::Kind CacheOpB,
82
+ /// Data type of accumulator matrix
83
+ typename ElementC_,
84
+ /// Data type of accumulator matrix
85
+ typename LayoutC_,
86
+ /// Policy describing tuning details (concept: MmaPolicy)
87
+ typename Policy_,
88
+ /// Number of stages,
89
+ int Stages,
90
+ /// Use zfill or predicate for out-of-bound cp.async
91
+ SharedMemoryClearOption SharedMemoryClear = SharedMemoryClearOption::kNone,
92
+ /// Upper boundon the K dimension
93
+ int kMaxK = cutlass::platform::numeric_limits<int>::max(),
94
+ /// Used for partial specialization
95
+ typename Enable = bool>
96
+ class CustomMmaMultistage : public CustomMmaBase<Shape_, Policy_, Stages> {
97
+ public:
98
+ ///< Base class
99
+ using Base = CustomMmaBase<Shape_, Policy_, Stages>;
100
+ ///< Size of the Gemm problem - concept: gemm::GemmShape<>
101
+ using Shape = Shape_;
102
+ ///< Iterates over tiles of A operand in global memory
103
+ using IteratorA = IteratorA_;
104
+ ///< Iterates over tiles of B operand in global memory
105
+ using IteratorB = IteratorB_;
106
+ ///< Data type of accumulator matrix
107
+ using ElementC = ElementC_;
108
+ ///< Layout of accumulator matrix
109
+ using LayoutC = LayoutC_;
110
+ ///< Policy describing tuning details
111
+ using Policy = Policy_;
112
+
113
+ using SmemIteratorA = SmemIteratorA_;
114
+ using SmemIteratorB = SmemIteratorB_;
115
+
116
+ static cutlass::arch::CacheOperation::Kind const kCacheOpA = CacheOpA;
117
+ static cutlass::arch::CacheOperation::Kind const kCacheOpB = CacheOpB;
118
+
119
+ //
120
+ // Dependent types
121
+ //
122
+
123
+ /// Fragment of accumulator tile
124
+ using FragmentC = typename Policy::Operator::FragmentC;
125
+
126
+ /// Warp-level Mma
127
+ using Operator = typename Policy::Operator;
128
+
129
+ /// Minimum architecture is Sm80 to support cp.async
130
+ using ArchTag = arch::Sm80;
131
+
132
+ /// Complex transform on A operand
133
+ static ComplexTransform const kTransformA = Operator::kTransformA;
134
+
135
+ /// Complex transform on B operand
136
+ static ComplexTransform const kTransformB = Operator::kTransformB;
137
+
138
+ /// Internal structure exposed for introspection.
139
+ struct Detail {
140
+ static_assert(
141
+ Base::kWarpGemmIterations > 1,
142
+ "The pipelined structure requires at least two warp-level "
143
+ "GEMM operations.");
144
+
145
+ /// Number of cp.async instructions to load one stage of operand A
146
+ static int const AsyncCopyIterationsPerStageA =
147
+ IteratorA::ThreadMap::Iterations::kCount;
148
+
149
+ /// Number of cp.async instructions to load one stage of operand B
150
+ static int const AsyncCopyIterationsPerStageB =
151
+ IteratorB::ThreadMap::Iterations::kCount;
152
+
153
+ /// Number of stages
154
+ static int const kStages = Stages;
155
+
156
+ /// Number of cp.async instructions to load on group of operand A
157
+ static int const kAccessesPerGroupA =
158
+ (AsyncCopyIterationsPerStageA + Base::kWarpGemmIterations - 1) /
159
+ Base::kWarpGemmIterations;
160
+
161
+ /// Number of cp.async instructions to load on group of operand B
162
+ static int const kAccessesPerGroupB =
163
+ (AsyncCopyIterationsPerStageB + Base::kWarpGemmIterations - 1) /
164
+ Base::kWarpGemmIterations;
165
+ };
166
+
167
+ static bool const kSmemContainsEntireMat = kMaxK <= Shape::kK * Stages;
168
+ static constexpr int kNumStagesConcurrentLoad =
169
+ kSmemContainsEntireMat ? Stages : Stages - 1;
170
+
171
+ private:
172
+ using WarpLoadedFragmentA = typename Operator::FragmentA;
173
+ using WarpLoadedFragmentB = typename Operator::FragmentB;
174
+ using WarpTransformedFragmentA = typename Operator::TransformedFragmentA;
175
+ using WarpTransformedFragmentB = typename Operator::TransformedFragmentB;
176
+
177
+ private:
178
+ //
179
+ // Data members
180
+ //
181
+
182
+ /// Iterator to write threadblock-scoped tile of A operand to shared memory
183
+ SmemIteratorA smem_iterator_A_;
184
+
185
+ /// Iterator to write threadblock-scoped tile of B operand to shared memory
186
+ SmemIteratorB smem_iterator_B_;
187
+
188
+ bool prologue_done_;
189
+
190
+ // Set to `True` to ensure the accumulator will be zero outside the GEMM
191
+ // footprint
192
+ bool zero_outside_bounds_;
193
+
194
+ public:
195
+ /// Construct from tensor references
196
+ CUTLASS_DEVICE
197
+ CustomMmaMultistage(
198
+ ///< Shared storage needed for internal use by threadblock-scoped GEMM
199
+ typename Base::SharedStorageA& shared_storageA,
200
+ typename Base::SharedStorageB& shared_storageB,
201
+ ///< ID within the threadblock
202
+ int thread_idx,
203
+ ///< ID of warp
204
+ int warp_idx,
205
+ ///< ID of each thread within a warp
206
+ int lane_idx)
207
+ : Base(shared_storageA, shared_storageB, thread_idx, warp_idx, lane_idx),
208
+ smem_iterator_A_(shared_storageA.ref(), thread_idx),
209
+ smem_iterator_B_(shared_storageB.ref(), thread_idx),
210
+ prologue_done_(false),
211
+ zero_outside_bounds_(false) {
212
+ // Compute warp location within threadblock tile by mapping the warp_id to
213
+ // three coordinates:
214
+ // _m: the warp's position within the threadblock along the M dimension
215
+ // _n: the warp's position within the threadblock along the N dimension
216
+ // _k: the warp's position within the threadblock along the K dimension
217
+
218
+ int warp_idx_mn = warp_idx % (Base::WarpCount::kM * Base::WarpCount::kN);
219
+ int warp_idx_k = warp_idx / (Base::WarpCount::kM * Base::WarpCount::kN);
220
+
221
+ int warp_idx_m = warp_idx_mn % Base::WarpCount::kM;
222
+ int warp_idx_n = warp_idx_mn / Base::WarpCount::kM;
223
+
224
+ // Add per-warp offsets in units of warp-level tiles
225
+ this->warp_tile_iterator_A_.add_tile_offset(
226
+ {warp_idx_m, Base::kWarpGemmIterations * warp_idx_k});
227
+ this->warp_tile_iterator_B_.add_tile_offset(
228
+ {Base::kWarpGemmIterations * warp_idx_k, warp_idx_n});
229
+ }
230
+ CUTLASS_DEVICE
231
+ CustomMmaMultistage(
232
+ ///< Shared storage needed for internal use by threadblock-scoped GEMM
233
+ typename Base::SharedStorage& st,
234
+ ///< ID within the threadblock
235
+ int thread_idx,
236
+ ///< ID of warp
237
+ int warp_idx,
238
+ ///< ID of each thread within a warp
239
+ int lane_idx)
240
+ : CustomMmaMultistage(
241
+ st.operand_A,
242
+ st.operand_B,
243
+ thread_idx,
244
+ warp_idx,
245
+ lane_idx) {}
246
+
247
+ CUTLASS_DEVICE
248
+ void set_prologue_done(bool value) {
249
+ prologue_done_ = value;
250
+ }
251
+
252
+ CUTLASS_DEVICE
253
+ void set_zero_outside_bounds(bool value) {
254
+ zero_outside_bounds_ = value;
255
+ }
256
+
257
+ template <bool kLoadA = true, bool kLoadB = true>
258
+ CUTLASS_DEVICE static void prologue(
259
+ typename Base::SharedStorage& shared_storage,
260
+ ///< iterator over A operand in global memory
261
+ IteratorA iterator_A,
262
+ ///< iterator over B operand in global memory
263
+ IteratorB iterator_B,
264
+ int thread_idx,
265
+ int problem_size_k) {
266
+ prologue<kLoadA, kLoadB>(
267
+ shared_storage.operand_A,
268
+ shared_storage.operand_B,
269
+ iterator_A,
270
+ iterator_B,
271
+ thread_idx,
272
+ problem_size_k);
273
+ }
274
+
275
+ template <bool kLoadA = true, bool kLoadB = true>
276
+ CUTLASS_DEVICE static void prologue(
277
+ typename Base::SharedStorageA& shared_storageA,
278
+ typename Base::SharedStorageB& shared_storageB,
279
+ ///< iterator over A operand in global memory
280
+ IteratorA iterator_A,
281
+ ///< iterator over B operand in global memory
282
+ IteratorB iterator_B,
283
+ int thread_idx,
284
+ int problem_size_k) {
285
+ SmemIteratorA smem_iterator_A(shared_storageA.ref(), thread_idx);
286
+ SmemIteratorB smem_iterator_B(shared_storageB.ref(), thread_idx);
287
+ int32_t iter = (problem_size_k + Base::Shape::kK - 1) / Base::Shape::kK;
288
+ _prologue<kLoadA, kLoadB>(
289
+ iterator_A, iterator_B, iter, smem_iterator_A, smem_iterator_B);
290
+ }
291
+
292
+ CUTLASS_DEVICE
293
+ void copy_tiles_and_advance(
294
+ IteratorA& iterator_A,
295
+ IteratorB& iterator_B,
296
+ int group_start_A = 0,
297
+ int group_start_B = 0) {
298
+ iterator_A.set_iteration_index(
299
+ group_start_A * IteratorA::kAccessesPerVector);
300
+ this->smem_iterator_A_.set_iteration_index(group_start_A);
301
+
302
+ // Async Copy for operand A
303
+ CUTLASS_PRAGMA_UNROLL
304
+ for (int j = 0; j < Detail::kAccessesPerGroupA; ++j) {
305
+ if (group_start_A + j < Detail::AsyncCopyIterationsPerStageA) {
306
+ typename IteratorA::AccessType* dst_ptr =
307
+ reinterpret_cast<typename IteratorA::AccessType*>(
308
+ this->smem_iterator_A_.get());
309
+
310
+ int const kSrcBytes = sizeof_bits<typename IteratorA::Element>::value *
311
+ IteratorA::ThreadMap::kElementsPerAccess /
312
+ IteratorA::kAccessesPerVector / 8;
313
+
314
+ CUTLASS_PRAGMA_UNROLL
315
+ for (int v = 0; v < IteratorA::kAccessesPerVector; ++v) {
316
+ auto gmem_ptr = iterator_A.get();
317
+
318
+ if (zero_outside_bounds_ ||
319
+ SharedMemoryClear == SharedMemoryClearOption::kZfill) {
320
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpA>(
321
+ dst_ptr + v, gmem_ptr, iterator_A.valid());
322
+ } else {
323
+ cutlass::arch::cp_async<kSrcBytes, kCacheOpA>(
324
+ dst_ptr + v, gmem_ptr, iterator_A.valid());
325
+ }
326
+
327
+ ++iterator_A;
328
+ }
329
+
330
+ ++this->smem_iterator_A_;
331
+ }
332
+ }
333
+
334
+ iterator_B.set_iteration_index(
335
+ group_start_B * IteratorB::kAccessesPerVector);
336
+ this->smem_iterator_B_.set_iteration_index(group_start_B);
337
+
338
+ // Async Copy for operand B
339
+ CUTLASS_PRAGMA_UNROLL
340
+ for (int j = 0; j < Detail::kAccessesPerGroupB; ++j) {
341
+ if (group_start_B + j < Detail::AsyncCopyIterationsPerStageB) {
342
+ typename IteratorB::AccessType* dst_ptr =
343
+ reinterpret_cast<typename IteratorB::AccessType*>(
344
+ this->smem_iterator_B_.get());
345
+
346
+ int const kSrcBytes = sizeof_bits<typename IteratorB::Element>::value *
347
+ IteratorB::ThreadMap::kElementsPerAccess /
348
+ IteratorB::kAccessesPerVector / 8;
349
+
350
+ CUTLASS_PRAGMA_UNROLL
351
+ for (int v = 0; v < IteratorB::kAccessesPerVector; ++v) {
352
+ auto gmem_ptr = iterator_B.get();
353
+
354
+ if (zero_outside_bounds_ ||
355
+ SharedMemoryClear == SharedMemoryClearOption::kZfill) {
356
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpB>(
357
+ dst_ptr + v, gmem_ptr, iterator_B.valid());
358
+ } else {
359
+ cutlass::arch::cp_async<kSrcBytes, kCacheOpB>(
360
+ dst_ptr + v, gmem_ptr, iterator_B.valid());
361
+ }
362
+
363
+ ++iterator_B;
364
+ }
365
+ ++this->smem_iterator_B_;
366
+ }
367
+ }
368
+ }
369
+
370
+ template <bool kLoadA = true, bool kLoadB = true>
371
+ CUTLASS_DEVICE static void _prologue(
372
+ IteratorA& iterator_A,
373
+ IteratorB& iterator_B,
374
+ int32_t& gemm_k_iterations,
375
+ SmemIteratorA& smem_iterator_A_,
376
+ SmemIteratorB& smem_iterator_B_) {
377
+ // Issue several complete stages
378
+ CUTLASS_PRAGMA_UNROLL
379
+ for (int stage = 0; stage < kNumStagesConcurrentLoad;
380
+ ++stage, --gemm_k_iterations) {
381
+ iterator_A.clear_mask(gemm_k_iterations == 0);
382
+ iterator_B.clear_mask(gemm_k_iterations == 0);
383
+
384
+ iterator_A.set_iteration_index(0);
385
+ smem_iterator_A_.set_iteration_index(0);
386
+
387
+ // Async Copy for operand A
388
+ CUTLASS_PRAGMA_UNROLL
389
+ for (int j = 0; j < Detail::AsyncCopyIterationsPerStageA; ++j) {
390
+ typename IteratorA::AccessType* dst_ptr =
391
+ reinterpret_cast<typename IteratorA::AccessType*>(
392
+ smem_iterator_A_.get());
393
+
394
+ CUTLASS_PRAGMA_UNROLL
395
+ for (int v = 0; v < IteratorA::kAccessesPerVector; ++v) {
396
+ int const kSrcBytes =
397
+ sizeof_bits<typename IteratorA::Element>::value *
398
+ IteratorA::ThreadMap::kElementsPerAccess /
399
+ IteratorA::kAccessesPerVector / 8;
400
+
401
+ int src_bytes = (iterator_A.valid() ? kSrcBytes : 0);
402
+
403
+ if (kLoadA) {
404
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpA>(
405
+ dst_ptr + v, iterator_A.get(), iterator_A.valid());
406
+ }
407
+
408
+ ++iterator_A;
409
+ }
410
+
411
+ ++smem_iterator_A_;
412
+ }
413
+
414
+ iterator_B.set_iteration_index(0);
415
+ smem_iterator_B_.set_iteration_index(0);
416
+
417
+ // Async Copy for operand B
418
+ CUTLASS_PRAGMA_UNROLL
419
+ for (int j = 0; j < Detail::AsyncCopyIterationsPerStageB; ++j) {
420
+ typename IteratorB::AccessType* dst_ptr =
421
+ reinterpret_cast<typename IteratorB::AccessType*>(
422
+ smem_iterator_B_.get());
423
+
424
+ CUTLASS_PRAGMA_UNROLL
425
+ for (int v = 0; v < IteratorB::kAccessesPerVector; ++v) {
426
+ int const kSrcBytes =
427
+ sizeof_bits<typename IteratorB::Element>::value *
428
+ IteratorB::ThreadMap::kElementsPerAccess /
429
+ IteratorB::kAccessesPerVector / 8;
430
+
431
+ if (kLoadB) {
432
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpB>(
433
+ dst_ptr + v, iterator_B.get(), iterator_B.valid());
434
+ }
435
+
436
+ ++iterator_B;
437
+ }
438
+
439
+ ++smem_iterator_B_;
440
+ }
441
+
442
+ // Move to the next stage
443
+ iterator_A.add_tile_offset({0, 1});
444
+ iterator_B.add_tile_offset({1, 0});
445
+
446
+ smem_iterator_A_.add_tile_offset({0, 1});
447
+ smem_iterator_B_.add_tile_offset({1, 0});
448
+
449
+ // Defines the boundary of a stage of cp.async.
450
+ cutlass::arch::cp_async_fence();
451
+ }
452
+ }
453
+
454
+ /// Perform a threadblock-scoped matrix multiply-accumulate
455
+ CUTLASS_DEVICE
456
+ void operator()(
457
+ ///< problem size of GEMM
458
+ int gemm_k_iterations,
459
+ ///< destination accumulator tile
460
+ FragmentC& accum,
461
+ ///< iterator over A operand in global memory
462
+ IteratorA iterator_A,
463
+ ///< iterator over B operand in global memory
464
+ IteratorB iterator_B,
465
+ ///< initial value of accumulator
466
+ FragmentC const& src_accum) {
467
+ //
468
+ // Prologue
469
+ //
470
+
471
+ if (!prologue_done_) {
472
+ _prologue<true, true>(
473
+ iterator_A,
474
+ iterator_B,
475
+ gemm_k_iterations,
476
+ smem_iterator_A_,
477
+ smem_iterator_B_);
478
+ } else if (!kSmemContainsEntireMat) {
479
+ _prologue<false, false>(
480
+ iterator_A,
481
+ iterator_B,
482
+ gemm_k_iterations,
483
+ smem_iterator_A_,
484
+ smem_iterator_B_);
485
+ } else {
486
+ gemm_k_iterations -= kNumStagesConcurrentLoad;
487
+ }
488
+
489
+ // Perform accumulation in the 'd' output operand
490
+ accum = src_accum;
491
+
492
+ //
493
+ // Clear the remaining tiles of SMEM. This is a functional requirement for
494
+ // some kernels so that all accumulator elements outside the GEMM footprint
495
+ // are zero.
496
+ //
497
+
498
+ if (SharedMemoryClear == SharedMemoryClearOption::kClearLastStage) {
499
+ /// Iterator to write threadblock-scoped tile of A operand to shared
500
+ /// memory
501
+ SmemIteratorA last_smem_iterator_A(this->smem_iterator_A_);
502
+
503
+ typename IteratorA::AccessType zero_A;
504
+ zero_A.clear();
505
+
506
+ last_smem_iterator_A.set_iteration_index(0);
507
+
508
+ // Async Copy for operand A
509
+ CUTLASS_PRAGMA_UNROLL
510
+ for (int j = 0; j < Detail::AsyncCopyIterationsPerStageA; ++j) {
511
+ typename IteratorA::AccessType* dst_ptr =
512
+ reinterpret_cast<typename IteratorA::AccessType*>(
513
+ last_smem_iterator_A.get());
514
+
515
+ *dst_ptr = zero_A;
516
+
517
+ ++last_smem_iterator_A;
518
+ }
519
+
520
+ /// Iterator to write threadblock-scoped tile of B operand to shared
521
+ /// memory
522
+ SmemIteratorB last_smem_iterator_B(this->smem_iterator_B_);
523
+ typename IteratorB::AccessType zero_B;
524
+
525
+ zero_B.clear();
526
+ last_smem_iterator_B.set_iteration_index(0);
527
+
528
+ // Async Copy for operand B
529
+ CUTLASS_PRAGMA_UNROLL
530
+ for (int j = 0; j < Detail::AsyncCopyIterationsPerStageB; ++j) {
531
+ typename IteratorB::AccessType* dst_ptr =
532
+ reinterpret_cast<typename IteratorB::AccessType*>(
533
+ last_smem_iterator_B.get());
534
+
535
+ *dst_ptr = zero_B;
536
+
537
+ ++last_smem_iterator_B;
538
+ }
539
+ }
540
+
541
+ // Waits until kStages-2 stages have committed.
542
+ cutlass::arch::cp_async_wait<kNumStagesConcurrentLoad - 1>();
543
+ __syncthreads();
544
+
545
+ // Pair of fragments used to overlap shared memory loads and math
546
+ // instructions
547
+ WarpLoadedFragmentA warp_loaded_frag_A[2];
548
+ WarpLoadedFragmentB warp_loaded_frag_B[2];
549
+ WarpTransformedFragmentA warp_transformed_frag_A[2];
550
+ WarpTransformedFragmentB warp_transformed_frag_B[2];
551
+
552
+ Operator warp_mma;
553
+
554
+ this->warp_tile_iterator_A_.set_kgroup_index(0);
555
+ this->warp_tile_iterator_B_.set_kgroup_index(0);
556
+
557
+ this->warp_tile_iterator_A_.load(warp_loaded_frag_A[0]);
558
+ this->warp_tile_iterator_B_.load(warp_loaded_frag_B[0]);
559
+
560
+ ++this->warp_tile_iterator_A_;
561
+ ++this->warp_tile_iterator_B_;
562
+
563
+ iterator_A.clear_mask(gemm_k_iterations == 0);
564
+ iterator_B.clear_mask(gemm_k_iterations == 0);
565
+
566
+ int smem_write_stage_idx = Base::kStages - 1;
567
+ int smem_read_stage_idx = 0;
568
+
569
+ warp_mma.transform(
570
+ warp_transformed_frag_A[0],
571
+ warp_transformed_frag_B[0],
572
+ warp_loaded_frag_A[0],
573
+ warp_loaded_frag_B[0]);
574
+
575
+ // tf32x3 kernels use staging accumulation. warp_mma uses a temporary
576
+ // accumulator and this temporary accumulator is added to the final
577
+ // accumulator once in every mainloop iteration.
578
+ plus<FragmentC> plus_accum;
579
+
580
+ FragmentC tmp_accum;
581
+
582
+ if (platform::is_same<
583
+ typename Operator::MathOperator,
584
+ arch::OpMultiplyAddFastF32>::value ||
585
+ platform::is_same<
586
+ typename Operator::MathOperator,
587
+ arch::OpMultiplyAddComplexFastF32>::value) {
588
+ tmp_accum.clear();
589
+ }
590
+
591
+ //
592
+ // Mainloop
593
+ //
594
+
595
+ CUTLASS_GEMM_LOOP
596
+ for (; gemm_k_iterations > (-kNumStagesConcurrentLoad);) {
597
+ //
598
+ // Loop over GEMM K dimension
599
+ //
600
+
601
+ // Computes a warp-level GEMM on data held in shared memory
602
+ // Each "warp_mma_k" refers to a warp-level matrix multiply-accumulate
603
+ CUTLASS_PRAGMA_UNROLL
604
+ for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations;
605
+ ++warp_mma_k) {
606
+ // Load warp-level tiles from shared memory, wrapping to k offset if
607
+ // this is the last group as the case may be.
608
+
609
+ this->warp_tile_iterator_A_.set_kgroup_index(
610
+ (warp_mma_k + 1) % Base::kWarpGemmIterations);
611
+ this->warp_tile_iterator_B_.set_kgroup_index(
612
+ (warp_mma_k + 1) % Base::kWarpGemmIterations);
613
+
614
+ // In case of a non-circular buffer ("kSmemContainsEntireMat")
615
+ // make sure we don't load out of bounds data.
616
+ if (!kSmemContainsEntireMat ||
617
+ gemm_k_iterations > (-kNumStagesConcurrentLoad) ||
618
+ warp_mma_k < Base::kWarpGemmIterations - 1) {
619
+ this->warp_tile_iterator_A_.load(
620
+ warp_loaded_frag_A[(warp_mma_k + 1) % 2]);
621
+ this->warp_tile_iterator_B_.load(
622
+ warp_loaded_frag_B[(warp_mma_k + 1) % 2]);
623
+ }
624
+
625
+ ++this->warp_tile_iterator_A_;
626
+ ++this->warp_tile_iterator_B_;
627
+
628
+ if (warp_mma_k > 0)
629
+ warp_mma.transform(
630
+ warp_transformed_frag_A[warp_mma_k % 2],
631
+ warp_transformed_frag_B[warp_mma_k % 2],
632
+ warp_loaded_frag_A[warp_mma_k % 2],
633
+ warp_loaded_frag_B[warp_mma_k % 2]);
634
+
635
+ if (platform::is_same<
636
+ typename Operator::MathOperator,
637
+ arch::OpMultiplyAddFastF32>::value ||
638
+ platform::is_same<
639
+ typename Operator::MathOperator,
640
+ arch::OpMultiplyAddComplexFastF32>::value) {
641
+ warp_mma(
642
+ tmp_accum,
643
+ warp_transformed_frag_A[warp_mma_k % 2],
644
+ warp_transformed_frag_B[warp_mma_k % 2],
645
+ tmp_accum);
646
+
647
+ if (warp_mma_k == 0) {
648
+ accum = plus_accum(accum, tmp_accum);
649
+ tmp_accum.clear();
650
+ }
651
+ } else {
652
+ warp_mma(
653
+ accum,
654
+ warp_transformed_frag_A[warp_mma_k % 2],
655
+ warp_transformed_frag_B[warp_mma_k % 2],
656
+ accum);
657
+ }
658
+
659
+ // Issue global->shared copies for the this stage
660
+ if (!kSmemContainsEntireMat &&
661
+ warp_mma_k < Base::kWarpGemmIterations - 1) {
662
+ int group_start_iteration_A, group_start_iteration_B;
663
+
664
+ group_start_iteration_A = warp_mma_k * Detail::kAccessesPerGroupA;
665
+ group_start_iteration_B = warp_mma_k * Detail::kAccessesPerGroupB;
666
+
667
+ copy_tiles_and_advance(
668
+ iterator_A,
669
+ iterator_B,
670
+ group_start_iteration_A,
671
+ group_start_iteration_B);
672
+ }
673
+
674
+ if (warp_mma_k + 2 == Base::kWarpGemmIterations) {
675
+ if (!kSmemContainsEntireMat) {
676
+ int group_start_iteration_A, group_start_iteration_B;
677
+ group_start_iteration_A =
678
+ (warp_mma_k + 1) * Detail::kAccessesPerGroupA;
679
+ group_start_iteration_B =
680
+ (warp_mma_k + 1) * Detail::kAccessesPerGroupB;
681
+
682
+ copy_tiles_and_advance(
683
+ iterator_A,
684
+ iterator_B,
685
+ group_start_iteration_A,
686
+ group_start_iteration_B);
687
+ }
688
+
689
+ // Inserts a memory fence between stages of cp.async instructions.
690
+ cutlass::arch::cp_async_fence();
691
+
692
+ // Waits until kStages-2 stages have committed.
693
+ cutlass::arch::cp_async_wait<kNumStagesConcurrentLoad - 1>();
694
+ __syncthreads();
695
+
696
+ // Move to the next stage
697
+ iterator_A.add_tile_offset({0, 1});
698
+ iterator_B.add_tile_offset({1, 0});
699
+
700
+ this->smem_iterator_A_.add_tile_offset({0, 1});
701
+ this->smem_iterator_B_.add_tile_offset({1, 0});
702
+
703
+ // Add negative offsets to return iterators to the 'start' of the
704
+ // circular buffer in shared memory
705
+ if (smem_write_stage_idx == (Base::kStages - 1)) {
706
+ this->smem_iterator_A_.add_tile_offset({0, -Base::kStages});
707
+ this->smem_iterator_B_.add_tile_offset({-Base::kStages, 0});
708
+ smem_write_stage_idx = 0;
709
+ } else {
710
+ ++smem_write_stage_idx;
711
+ }
712
+
713
+ if (!kSmemContainsEntireMat &&
714
+ smem_read_stage_idx == (Base::kStages - 1)) {
715
+ this->warp_tile_iterator_A_.add_tile_offset(
716
+ {0,
717
+ -Base::kStages * Policy::kPartitionsK *
718
+ Base::kWarpGemmIterations});
719
+ this->warp_tile_iterator_B_.add_tile_offset(
720
+ {-Base::kStages * Policy::kPartitionsK *
721
+ Base::kWarpGemmIterations,
722
+ 0});
723
+ smem_read_stage_idx = 0;
724
+ } else {
725
+ ++smem_read_stage_idx;
726
+ }
727
+
728
+ --gemm_k_iterations;
729
+ iterator_A.clear_mask(gemm_k_iterations == 0);
730
+ iterator_B.clear_mask(gemm_k_iterations == 0);
731
+ }
732
+
733
+ // Do any conversions feeding the first stage at the end of the loop so
734
+ // we can start right away on mma instructions
735
+ if (warp_mma_k + 1 == Base::kWarpGemmIterations)
736
+ warp_mma.transform(
737
+ warp_transformed_frag_A[(warp_mma_k + 1) % 2],
738
+ warp_transformed_frag_B[(warp_mma_k + 1) % 2],
739
+ warp_loaded_frag_A[(warp_mma_k + 1) % 2],
740
+ warp_loaded_frag_B[(warp_mma_k + 1) % 2]);
741
+ }
742
+ }
743
+
744
+ if (platform::is_same<
745
+ typename Operator::MathOperator,
746
+ arch::OpMultiplyAddFastF32>::value ||
747
+ platform::is_same<
748
+ typename Operator::MathOperator,
749
+ arch::OpMultiplyAddComplexFastF32>::value) {
750
+ accum = plus_accum(accum, tmp_accum);
751
+ }
752
+
753
+ if (SharedMemoryClear == SharedMemoryClearOption::kZfill) {
754
+ // commit and drain all pending and predicated cp.async pnz from the GEMM
755
+ // mainloop
756
+ cutlass::arch::cp_async_fence();
757
+ cutlass::arch::cp_async_wait<0>();
758
+ __syncthreads();
759
+ }
760
+ }
761
+ };
762
+
763
+ /////////////////////////////////////////////////////////////////////////////////////////////////
764
+
765
+ } // namespace threadblock
766
+ } // namespace gemm
767
+ } // namespace cutlass
768
+
769
+ /////////////////////////////////////////////////////////////////////////////////////////////////
770
+
771
+ #else
772
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
773
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_pipelined.h ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /***************************************************************************************************
3
+ * Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights
4
+ *reserved. SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice,
10
+ *this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ * this list of conditions and the following disclaimer in the documentation
14
+ * and/or other materials provided with the distribution.
15
+ *
16
+ * 3. Neither the name of the copyright holder nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ *POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ **************************************************************************************************/
33
+ /*! \file
34
+ \brief Template for a double-buffered threadblock-scoped GEMM kernel.
35
+ */
36
+
37
+ #pragma once
38
+
39
+ #include <cutlass/aligned_buffer.h>
40
+ #include <cutlass/array.h>
41
+ #include <cutlass/cutlass.h>
42
+ #include <cutlass/numeric_conversion.h>
43
+
44
+ #include <cutlass/matrix_shape.h>
45
+ #include <cutlass/numeric_types.h>
46
+
47
+ #include <cutlass/gemm/gemm.h>
48
+
49
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_base.h>
50
+
51
+ /////////////////////////////////////////////////////////////////////////////////////////////////
52
+
53
+ namespace cutlass {
54
+ namespace gemm {
55
+ namespace threadblock {
56
+
57
+ /////////////////////////////////////////////////////////////////////////////////////////////////
58
+
59
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
60
+ /// instructions.
61
+ template <
62
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
63
+ typename Shape_,
64
+ /// Iterates over tiles of A operand in global memory
65
+ // (concept: ReadableTileIterator | ForwardTileIterator |
66
+ // MaskedTileIterator)
67
+ typename IteratorA_,
68
+ /// Iterates over tiles of A operand in shared memory
69
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
70
+ typename SmemIteratorA_,
71
+ /// Iterates over tiles of B operand in global memory
72
+ // (concept: ReadableTileIterator | ForwardTileIterator |
73
+ // MaskedTileIterator)
74
+ typename IteratorB_,
75
+ /// Iterates over tiles of B operand in shared memory
76
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
77
+ typename SmemIteratorB_,
78
+ /// Data type of accumulator matrix
79
+ typename ElementC_,
80
+ /// Data type of accumulator matrix
81
+ typename LayoutC_,
82
+ /// Policy describing tuning details (concept: MmaPolicy)
83
+ typename Policy_,
84
+ /// Transformation applied to A operand
85
+ typename TransformA_ = NumericArrayConverter<
86
+ typename SmemIteratorA_::Element,
87
+ typename IteratorA_::Element,
88
+ IteratorA_::Fragment::kElements>,
89
+ ///
90
+ /// Transformation applied to B operand
91
+ typename TransformB_ = NumericArrayConverter<
92
+ typename SmemIteratorB_::Element,
93
+ typename IteratorB_::Element,
94
+ IteratorB_::Fragment::kElements>,
95
+ /// Used for partial specialization
96
+ typename Enable = bool>
97
+ class CustomMmaPipelined : public CustomMmaBase<Shape_, Policy_, 2> {
98
+ public:
99
+ ///< Base class
100
+ using Base = CustomMmaBase<Shape_, Policy_, 2>;
101
+
102
+ using Shape =
103
+ Shape_; ///< Size of the Gemm problem - concept: gemm::GemmShape<>
104
+ using IteratorA =
105
+ IteratorA_; ///< Iterates over tiles of A operand in global memory
106
+ using IteratorB =
107
+ IteratorB_; ///< Iterates over tiles of B operand in global memory
108
+ using ElementC = ElementC_; ///< Data type of accumulator matrix
109
+ using LayoutC = LayoutC_; ///< Layout of accumulator matrix
110
+ using Policy = Policy_; ///< Policy describing tuning details
111
+
112
+ using SmemIteratorA = SmemIteratorA_;
113
+ using SmemIteratorB = SmemIteratorB_;
114
+
115
+ using TransformA = TransformA_;
116
+ using TransformB = TransformB_;
117
+
118
+ //
119
+ // Dependent types
120
+ //
121
+
122
+ /// Fragment of operand A loaded from global memory
123
+ using FragmentA = typename IteratorA::Fragment;
124
+
125
+ /// Fragment of operand B loaded from global memory
126
+ using FragmentB = typename IteratorB::Fragment;
127
+
128
+ /// Fragment of accumulator tile
129
+ using FragmentC = typename Policy::Operator::FragmentC;
130
+
131
+ /// Warp-level Mma
132
+ using Operator = typename Policy::Operator;
133
+
134
+ /// Obtain the arch tag from the warp-level operator
135
+ using ArchTag = typename Policy::Operator::ArchTag;
136
+
137
+ /// Complex transform on A operand
138
+ static ComplexTransform const kTransformA = Operator::kTransformA;
139
+
140
+ /// Complex transform on B operand
141
+ static ComplexTransform const kTransformB = Operator::kTransformB;
142
+
143
+ // statically assert kStages for MmaPipelined is two (Double-buffered pipeline)
144
+ static_assert(
145
+ (Base::kStages == 2),
146
+ "MmaPipelined requires kStages set to value 2");
147
+
148
+ static bool const kSmemContainsEntireMat = false;
149
+
150
+ private:
151
+ using WarpFragmentA = typename Operator::FragmentA;
152
+ using WarpFragmentB = typename Operator::FragmentB;
153
+
154
+ protected:
155
+ /// Iterator to write threadblock-scoped tile of A operand to shared memory
156
+ SmemIteratorA smem_iterator_A_;
157
+
158
+ /// Iterator to write threadblock-scoped tile of B operand to shared memory
159
+ SmemIteratorB smem_iterator_B_;
160
+
161
+ public:
162
+ /// Construct from tensor references
163
+ CUTLASS_DEVICE
164
+ CustomMmaPipelined(
165
+ typename Base::SharedStorageA& shared_storageA,
166
+ typename Base::SharedStorageB& shared_storageB,
167
+ int thread_idx, ///< ID within the threadblock
168
+ int warp_idx, ///< ID of warp
169
+ int lane_idx ///< ID of each thread within a warp
170
+ )
171
+ : Base(shared_storageA, shared_storageB, thread_idx, warp_idx, lane_idx),
172
+ smem_iterator_A_(shared_storageA.ref(), thread_idx),
173
+ smem_iterator_B_(shared_storageB.ref(), thread_idx) {
174
+ // Compute warp location within threadblock tile by mapping the warp_id to
175
+ // three coordinates:
176
+ // _m: the warp's position within the threadblock along the M dimension
177
+ // _n: the warp's position within the threadblock along the N dimension
178
+ // _k: the warp's position within the threadblock along the K dimension
179
+
180
+ int warp_idx_mn = warp_idx % (Base::WarpCount::kM * Base::WarpCount::kN);
181
+ int warp_idx_k = warp_idx / (Base::WarpCount::kM * Base::WarpCount::kN);
182
+
183
+ int warp_idx_m = warp_idx_mn % Base::WarpCount::kM;
184
+ int warp_idx_n = warp_idx_mn / Base::WarpCount::kM;
185
+
186
+ // Add per-warp offsets in units of warp-level tiles
187
+ this->warp_tile_iterator_A_.add_tile_offset(
188
+ {warp_idx_m, Base::kWarpGemmIterations * warp_idx_k});
189
+ this->warp_tile_iterator_B_.add_tile_offset(
190
+ {Base::kWarpGemmIterations * warp_idx_k, warp_idx_n});
191
+ }
192
+ CUTLASS_DEVICE
193
+ CustomMmaPipelined(
194
+ ///< Shared storage needed for internal use by threadblock-scoped GEMM
195
+ typename Base::SharedStorage& st,
196
+ ///< ID within the threadblock
197
+ int thread_idx,
198
+ ///< ID of warp
199
+ int warp_idx,
200
+ ///< ID of each thread within a warp
201
+ int lane_idx)
202
+ : CustomMmaPipelined(
203
+ st.operand_A,
204
+ st.operand_B,
205
+ thread_idx,
206
+ warp_idx,
207
+ lane_idx) {}
208
+
209
+ CUTLASS_DEVICE
210
+ void set_prologue_done(bool value) {
211
+ // NOT IMPLEMENTED FOR PIPELINED
212
+ }
213
+
214
+ CUTLASS_DEVICE
215
+ void set_zero_outside_bounds(bool value) {
216
+ // NOT NEEDED FOR PIPELINED
217
+ // shared memory will always be zero-filled
218
+ }
219
+
220
+ template <bool kLoadA = true, bool kLoadB = true>
221
+ CUTLASS_DEVICE static void prologue(
222
+ typename Base::SharedStorage& shared_storage,
223
+ ///< iterator over A operand in global memory
224
+ IteratorA iterator_A,
225
+ ///< iterator over B operand in global memory
226
+ IteratorB iterator_B,
227
+ int thread_idx,
228
+ int problem_size_k) {
229
+ prologue<kLoadA, kLoadB>(
230
+ shared_storage.operand_A,
231
+ shared_storage.operand_B,
232
+ iterator_A,
233
+ iterator_B,
234
+ thread_idx,
235
+ problem_size_k);
236
+ }
237
+
238
+ template <bool kLoadA = true, bool kLoadB = true>
239
+ CUTLASS_DEVICE static void prologue(
240
+ typename Base::SharedStorageA& shared_storageA,
241
+ typename Base::SharedStorageB& shared_storageB,
242
+ ///< iterator over A operand in global memory
243
+ IteratorA iterator_A,
244
+ ///< iterator over B operand in global memory
245
+ IteratorB iterator_B,
246
+ int thread_idx,
247
+ int problem_size_k) {
248
+ // NOT IMPLEMENTED FOR PIPELINED
249
+ }
250
+
251
+ /// Perform a threadblock-scoped matrix multiply-accumulate
252
+ CUTLASS_DEVICE
253
+ void operator()(
254
+ int gemm_k_iterations, ///< number of iterations of the mainloop
255
+ FragmentC& accum, ///< destination accumulator tile
256
+ IteratorA iterator_A, ///< iterator over A operand in global memory
257
+ IteratorB iterator_B, ///< iterator over B operand in global memory
258
+ FragmentC const& src_accum, ///< source accumulator tile
259
+ TransformA transform_A =
260
+ TransformA(), ///< transformation applied to A fragment
261
+ TransformB transform_B =
262
+ TransformB()) { ///< transformation applied to B fragment
263
+
264
+ //
265
+ // Prologue
266
+ //
267
+
268
+ // Perform accumulation in the 'd' output operand
269
+ accum = src_accum;
270
+
271
+ FragmentA tb_frag_A;
272
+ FragmentB tb_frag_B;
273
+
274
+ tb_frag_A.clear();
275
+ tb_frag_B.clear();
276
+
277
+ // The last kblock is loaded in the prolog
278
+ iterator_A.load(tb_frag_A);
279
+ iterator_B.load(tb_frag_B);
280
+
281
+ ++iterator_A;
282
+ ++iterator_B;
283
+
284
+ this->smem_iterator_A_.store(transform_A(tb_frag_A));
285
+ this->smem_iterator_B_.store(transform_B(tb_frag_B));
286
+
287
+ ++this->smem_iterator_A_;
288
+ ++this->smem_iterator_B_;
289
+
290
+ __syncthreads();
291
+
292
+ // Pair of fragments used to overlap shared memory loads and math
293
+ // instructions
294
+ WarpFragmentA warp_frag_A[2];
295
+ WarpFragmentB warp_frag_B[2];
296
+
297
+ this->warp_tile_iterator_A_.set_kgroup_index(0);
298
+ this->warp_tile_iterator_B_.set_kgroup_index(0);
299
+
300
+ this->warp_tile_iterator_A_.load(warp_frag_A[0]);
301
+ this->warp_tile_iterator_B_.load(warp_frag_B[0]);
302
+
303
+ ++this->warp_tile_iterator_A_;
304
+ ++this->warp_tile_iterator_B_;
305
+
306
+ Operator warp_mma;
307
+
308
+ int smem_write_stage_idx = 1;
309
+
310
+ // Avoid reading out of bounds
311
+ iterator_A.clear_mask(gemm_k_iterations <= 1);
312
+ iterator_B.clear_mask(gemm_k_iterations <= 1);
313
+
314
+ // Issue loads during the first warp-level matrix multiply-add *AFTER*
315
+ // issuing shared memory loads (which have the tighest latency requirement).
316
+
317
+ //
318
+ // Mainloop
319
+ //
320
+
321
+ // Note: The main loop does not support Base::kWarpGemmIterations == 2.
322
+ CUTLASS_GEMM_LOOP
323
+ for (; gemm_k_iterations > 0; --gemm_k_iterations) {
324
+ //
325
+ // Loop over GEMM K dimension
326
+ //
327
+
328
+ CUTLASS_PRAGMA_UNROLL
329
+ for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations;
330
+ ++warp_mma_k) {
331
+ // Load warp-level tiles from shared memory, wrapping to k offset if
332
+ // this is the last group as the case may be.
333
+
334
+ if (warp_mma_k == Base::kWarpGemmIterations - 1) {
335
+ // Write fragments to shared memory
336
+ this->smem_iterator_A_.store(transform_A(tb_frag_A));
337
+
338
+ this->smem_iterator_B_.store(transform_B(tb_frag_B));
339
+
340
+ __syncthreads();
341
+
342
+ ++this->smem_iterator_A_;
343
+ ++this->smem_iterator_B_;
344
+
345
+ // Add negative offsets to return iterators to the 'start' of the
346
+ // circular buffer in shared memory
347
+ if (smem_write_stage_idx == 1) {
348
+ this->smem_iterator_A_.add_tile_offset({0, -Base::kStages});
349
+ this->smem_iterator_B_.add_tile_offset({-Base::kStages, 0});
350
+ } else {
351
+ this->warp_tile_iterator_A_.add_tile_offset(
352
+ {0,
353
+ -Base::kStages * Policy::kPartitionsK *
354
+ Base::kWarpGemmIterations});
355
+ this->warp_tile_iterator_B_.add_tile_offset(
356
+ {-Base::kStages * Policy::kPartitionsK *
357
+ Base::kWarpGemmIterations,
358
+ 0});
359
+ }
360
+
361
+ smem_write_stage_idx ^= 1;
362
+ }
363
+
364
+ this->warp_tile_iterator_A_.set_kgroup_index(
365
+ (warp_mma_k + 1) % Base::kWarpGemmIterations);
366
+ this->warp_tile_iterator_B_.set_kgroup_index(
367
+ (warp_mma_k + 1) % Base::kWarpGemmIterations);
368
+
369
+ this->warp_tile_iterator_A_.load(warp_frag_A[(warp_mma_k + 1) % 2]);
370
+ this->warp_tile_iterator_B_.load(warp_frag_B[(warp_mma_k + 1) % 2]);
371
+
372
+ ++this->warp_tile_iterator_A_;
373
+ ++this->warp_tile_iterator_B_;
374
+
375
+ if (warp_mma_k == 0) {
376
+ iterator_A.load(tb_frag_A);
377
+ iterator_B.load(tb_frag_B);
378
+
379
+ ++iterator_A;
380
+ ++iterator_B;
381
+
382
+ // Avoid reading out of bounds if this was the last loop iteration
383
+ iterator_A.clear_mask(gemm_k_iterations <= 2);
384
+ iterator_B.clear_mask(gemm_k_iterations <= 2);
385
+ }
386
+
387
+ warp_mma(
388
+ accum,
389
+ warp_frag_A[warp_mma_k % 2],
390
+ warp_frag_B[warp_mma_k % 2],
391
+ accum);
392
+ }
393
+ }
394
+ }
395
+ };
396
+
397
+ /////////////////////////////////////////////////////////////////////////////////////////////////
398
+
399
+ } // namespace threadblock
400
+ } // namespace gemm
401
+ } // namespace cutlass
402
+
403
+ /////////////////////////////////////////////////////////////////////////////////////////////////
404
+
405
+ #else
406
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
407
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/find_default_mma.h ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /*! \file
10
+ \brief Cutlass provides helper template functions to figure out the right
11
+ data structures to instantiate to run a GEMM with various parameters (see
12
+ `cutlass/gemm/threadblock/default_mma.h`). However, due to template
13
+ instantiation priority rules, it will only create an MmaMultiStage with
14
+ kStages=3 (otherwise creates an MmePipelined - which is not compatible with
15
+ FastF32). kStages=3 uses too much shared memory and we want to use kStages=2,
16
+ so we just copy-pasted some code from `default_mma.h` and
17
+ `default_mma_core.h` files and wrapped this template to allow our use case.
18
+
19
+ This is really only for the FastF32 case - aka using TensorCores with fp32.
20
+ */
21
+
22
+ #pragma once
23
+
24
+ #include <cutlass/gemm/threadblock/default_mma.h>
25
+ #include <cutlass/gemm/threadblock/default_mma_core_simt.h>
26
+ #include <cutlass/gemm/threadblock/default_mma_core_sm70.h>
27
+ #include <cutlass/gemm/threadblock/default_mma_core_sm75.h>
28
+ #include <cutlass/gemm/threadblock/default_mma_core_sm80.h>
29
+
30
+ namespace cutlass {
31
+ namespace gemm {
32
+ namespace threadblock {
33
+
34
+ template <
35
+ /// Element type for A matrix operand
36
+ typename ElementA,
37
+ /// Layout type for A matrix operand
38
+ typename LayoutA,
39
+ /// Access granularity of A matrix in units of elements
40
+ int kAlignmentA,
41
+ /// Element type for B matrix operand
42
+ typename ElementB,
43
+ /// Layout type for B matrix operand
44
+ typename LayoutB,
45
+ /// Access granularity of B matrix in units of elements
46
+ int kAlignmentB,
47
+ /// Element type for internal accumulation
48
+ typename ElementAccumulator,
49
+ /// Layout type for C and D matrix operand
50
+ typename LayoutC,
51
+ /// Operator class tag
52
+ typename OperatorClass,
53
+ /// Tag indicating architecture to tune for
54
+ typename ArchTag,
55
+ /// Threadblock-level tile size (concept: GemmShape)
56
+ typename ThreadblockShape,
57
+ /// Warp-level tile size (concept: GemmShape)
58
+ typename WarpShape,
59
+ /// Instruction-level tile size (concept: GemmShape)
60
+ typename InstructionShape,
61
+ /// Number of stages used in the pipelined mainloop
62
+ int Stages,
63
+ /// Operation performed by GEMM
64
+ typename Operator,
65
+ typename Enable_ = void>
66
+ struct FindDefaultMma {
67
+ static constexpr bool AccumulatorsInRowMajor = false;
68
+ static constexpr SharedMemoryClearOption SharedMemoryClear =
69
+ SharedMemoryClearOption::kNone;
70
+ using DefaultMma = cutlass::gemm::threadblock::DefaultMma<
71
+ ElementA,
72
+ LayoutA,
73
+ kAlignmentA,
74
+ ElementB,
75
+ LayoutB,
76
+ kAlignmentB,
77
+ ElementAccumulator,
78
+ LayoutC,
79
+ OperatorClass,
80
+ ArchTag,
81
+ ThreadblockShape,
82
+ WarpShape,
83
+ InstructionShape,
84
+ Stages,
85
+ Operator,
86
+ AccumulatorsInRowMajor,
87
+ SharedMemoryClear>;
88
+ };
89
+
90
+ /// Specialization for sm80 / FastF32 / multistage with kStages=2
91
+ template <
92
+ typename ElementA_,
93
+ /// Layout type for A matrix operand
94
+ typename LayoutA_,
95
+ /// Access granularity of A matrix in units of elements
96
+ int kAlignmentA,
97
+ typename ElementB_,
98
+ /// Layout type for B matrix operand
99
+ typename LayoutB_,
100
+ /// Access granularity of B matrix in units of elements
101
+ int kAlignmentB,
102
+ typename ElementAccumulator,
103
+ /// Threadblock-level tile size (concept: GemmShape)
104
+ typename ThreadblockShape,
105
+ /// Warp-level tile size (concept: GemmShape)
106
+ typename WarpShape,
107
+ /// Instruction-level tile size (concept: GemmShape)
108
+ typename InstructionShape,
109
+ int kStages,
110
+ typename Operator>
111
+ struct FindDefaultMma<
112
+ ElementA_,
113
+ LayoutA_,
114
+ kAlignmentA,
115
+ ElementB_,
116
+ LayoutB_,
117
+ kAlignmentB,
118
+ ElementAccumulator,
119
+ layout::RowMajor,
120
+ arch::OpClassTensorOp,
121
+ arch::Sm80,
122
+ ThreadblockShape,
123
+ WarpShape,
124
+ InstructionShape,
125
+ kStages,
126
+ Operator,
127
+ typename cutlass::platform::enable_if<(kAlignmentA > 1)>::type> {
128
+ using LayoutC = layout::RowMajor;
129
+ using OperatorClass = arch::OpClassTensorOp;
130
+ using ArchTag = arch::Sm80;
131
+
132
+ using DefaultMma_ = cutlass::gemm::threadblock::DefaultMma<
133
+ ElementA_,
134
+ LayoutA_,
135
+ kAlignmentA,
136
+ ElementB_,
137
+ LayoutB_,
138
+ kAlignmentB,
139
+ ElementAccumulator,
140
+ LayoutC,
141
+ OperatorClass,
142
+ ArchTag,
143
+ ThreadblockShape,
144
+ WarpShape,
145
+ InstructionShape,
146
+ 3,
147
+ Operator>;
148
+ struct DefaultMma : DefaultMma_ {
149
+ using MmaCore_ = typename DefaultMma_::MmaCore;
150
+ // Define the threadblock-scoped multistage matrix multiply
151
+ using ThreadblockMma = cutlass::gemm::threadblock::MmaMultistage<
152
+ typename MmaCore_::Shape,
153
+ typename DefaultMma_::IteratorA,
154
+ typename MmaCore_::SmemIteratorA,
155
+ MmaCore_::kCacheOpA,
156
+ typename DefaultMma_::IteratorB,
157
+ typename MmaCore_::SmemIteratorB,
158
+ MmaCore_::kCacheOpB,
159
+ ElementAccumulator,
160
+ LayoutC,
161
+ typename MmaCore_::MmaPolicy,
162
+ kStages>;
163
+ };
164
+ };
165
+
166
+ } // namespace threadblock
167
+ } // namespace gemm
168
+ } // namespace cutlass
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)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_accum_lambda_iterator.h ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
10
+
11
+ #include <cutlass/functional.h>
12
+ #include <cutlass/gemm/warp/mma_simt_tile_iterator.h>
13
+ #include <cutlass/gemm/warp/mma_tensor_op_tile_iterator_sm70.h>
14
+ #include <cutlass/gemm/warp/mma_tensor_op_tile_iterator_sm80.h>
15
+ #include <cutlass/matrix_shape.h>
16
+
17
+ /*
18
+ TensorCores have different accumulator layouts.
19
+ This file provides a class to easily map the accumulator
20
+ i-th element with the corresponding matrix row/col.
21
+ */
22
+
23
+ template <typename T, typename accum_t, int kWarpSize>
24
+ struct AccumLambdaIteratorSm80 {
25
+ static_assert(
26
+ cutlass::platform::
27
+ is_same<typename T::Layout, cutlass::layout::RowMajor>::value,
28
+ "only RowMajor is supported");
29
+
30
+ using Policy = typename T::Policy;
31
+ using InstructionShape = typename T::InstructionShape;
32
+ using OpDelta = typename T::OpDelta;
33
+ using Shape = typename T::Shape;
34
+ static int const kElementsPerAccess = InstructionShape::kN / 4;
35
+ static int const kRowsPerTile = 8;
36
+ static int const kAccumulatorRows = InstructionShape::kM / kRowsPerTile;
37
+
38
+ static cutlass::MatrixCoord CUTLASS_DEVICE get_lane_offset(
39
+ int8_t lane_id,
40
+ int8_t warp_id,
41
+ typename T::TensorCoord const& tile_offset) {
42
+ int quad = (lane_id >> 2);
43
+ int lane_in_quad = (lane_id & 3);
44
+ return cutlass::MatrixCoord(
45
+ quad + tile_offset.row() * Shape::kRow,
46
+ lane_in_quad * kElementsPerAccess +
47
+ tile_offset.column() * Shape::kColumn);
48
+ }
49
+
50
+ template <typename FA, typename FB, typename FC>
51
+ CUTLASS_DEVICE static void iterateRows(
52
+ cutlass::MatrixCoord& lane_offset,
53
+ FA beginRow,
54
+ FB op,
55
+ FC endRow) {
56
+ // See cutlass/gemm/warp/mma_tensor_op_tile_iterator.h
57
+ CUTLASS_PRAGMA_UNROLL
58
+ for (int mma_m = 0; mma_m < Policy::MmaIterations::kRow; ++mma_m) {
59
+ CUTLASS_PRAGMA_UNROLL
60
+ for (int row = 0; row < kAccumulatorRows; ++row) {
61
+ int accum_m = mma_m * InstructionShape::kM * OpDelta::kRow +
62
+ row * kRowsPerTile + lane_offset.row();
63
+ beginRow(accum_m);
64
+
65
+ CUTLASS_PRAGMA_UNROLL
66
+ for (int mma_n = 0; mma_n < Policy::MmaIterations::kColumn; ++mma_n) {
67
+ int mma_accum_start = kAccumulatorRows * kElementsPerAccess *
68
+ (mma_n * Policy::MmaIterations::kRow + mma_m);
69
+ CUTLASS_PRAGMA_UNROLL
70
+ for (int col = 0; col < kElementsPerAccess; ++col) {
71
+ int accum_n = mma_n * InstructionShape::kN * OpDelta::kColumn +
72
+ col + lane_offset.column();
73
+ int idx = mma_accum_start + row * kElementsPerAccess + col;
74
+ op(accum_m, accum_n, idx);
75
+ }
76
+ }
77
+
78
+ endRow(accum_m);
79
+ }
80
+ }
81
+ }
82
+
83
+ template <typename DT, typename F>
84
+ CUTLASS_DEVICE static bool reduceSameRow(int lane_id, DT& myValue, F fn) {
85
+ // In each warp, 4 threads will work on the same row
86
+ // - the ones with the same `quad`
87
+ auto otherV = __shfl_xor_sync(0xffffffff, myValue, 1);
88
+ myValue = fn(myValue, otherV);
89
+ otherV = __shfl_xor_sync(0xffffffff, myValue, 2);
90
+ myValue = fn(myValue, otherV);
91
+ int lane_in_quad = (lane_id & 3);
92
+ return lane_in_quad == 0;
93
+ }
94
+ };
95
+
96
+ template <typename T, typename accum_t, int kWarpSize>
97
+ struct AccumLambdaIteratorSm70 {
98
+ static_assert(
99
+ cutlass::platform::
100
+ is_same<typename T::Layout, cutlass::layout::RowMajor>::value,
101
+ "only RowMajor is supported");
102
+
103
+ using Policy = typename T::Policy;
104
+ using InstructionShape = typename T::InstructionShape;
105
+ using OpDelta = typename T::OpDelta;
106
+ using Shape = typename T::Shape;
107
+ using Element = accum_t;
108
+
109
+ static int const kElementsPerPartial = 4;
110
+ using EleShapePerPatial = typename cutlass::platform::conditional<
111
+ cutlass::platform::is_same<Element, float>::value,
112
+ cutlass::MatrixShape<2, 2>,
113
+ cutlass::MatrixShape<1, 4>>::type;
114
+ static int const kElementsPerMma = 8;
115
+ static int const kAccumulatorPatials = 2;
116
+ using QuadShapePerPatialMma = cutlass::MatrixShape<4, 4>;
117
+
118
+ static cutlass::MatrixCoord CUTLASS_DEVICE get_lane_offset(
119
+ int8_t lane_id,
120
+ int8_t warp_id,
121
+ typename T::TensorCoord const& tile_offset) {
122
+ int quad = (lane_id >> 2);
123
+ int lane_in_quad = (lane_id & 3);
124
+ int accum_m, accum_n;
125
+
126
+ if (cutlass::platform::is_same<Element, float>::value) {
127
+ // (quad[2],quad[0])+lane_in_quad[0]
128
+ accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 + (lane_in_quad & 1);
129
+ // (quad[1])+lane_in_quad[1]
130
+ accum_n =
131
+ ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials +
132
+ (lane_in_quad & 2);
133
+ } else {
134
+ accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 +
135
+ lane_in_quad; // (quad[2],quad[0])
136
+ accum_n = ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials;
137
+ }
138
+ return cutlass::MatrixCoord(
139
+ accum_m + tile_offset.row() * Shape::kRow,
140
+ accum_n + tile_offset.column() * Shape::kColumn);
141
+ }
142
+
143
+ template <typename DT, typename F>
144
+ CUTLASS_DEVICE static bool reduceSameRow(int lane_id, DT& myValue, F fn) {
145
+ static_assert(
146
+ cutlass::platform::is_same<Element, float>::value,
147
+ "update to support non-float accum");
148
+ // https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#warp-level-matrix-fragment-mma-884-f16
149
+ // T0 & T2 share same line within a quad
150
+ auto otherV = __shfl_xor_sync(0xffffffff, myValue, 1 << 1);
151
+ myValue = fn(myValue, otherV);
152
+ // quad 0 and quad 2 are on the same lines
153
+ otherV = __shfl_xor_sync(0xffffffff, myValue, 1 << 3);
154
+ myValue = fn(myValue, otherV);
155
+ return (lane_id & ((1 << 1) | (1 << 3))) == 0;
156
+ }
157
+
158
+ template <typename FA, typename FB, typename FC>
159
+ CUTLASS_DEVICE static void iterateRows(
160
+ cutlass::MatrixCoord& lane_offset,
161
+ FA beginRow,
162
+ FB op,
163
+ FC endRow) {
164
+ CUTLASS_PRAGMA_UNROLL
165
+ for (int tile_m = 0; tile_m < Policy::TileIterations::kRow; ++tile_m) {
166
+ CUTLASS_PRAGMA_UNROLL
167
+ for (int mma_m = 0; mma_m < Policy::MmaIterations::kRow; ++mma_m) {
168
+ CUTLASS_PRAGMA_UNROLL
169
+ for (int m = 0; m < EleShapePerPatial::kRow; ++m) {
170
+ int accum_m = tile_m * Policy::InterleavedTile::kRow +
171
+ mma_m * QuadShapePerPatialMma::kRow + m * 2 + lane_offset.row();
172
+ beginRow(accum_m);
173
+
174
+ CUTLASS_PRAGMA_UNROLL
175
+ for (int tile_n = 0; tile_n < Policy::TileIterations::kColumn;
176
+ ++tile_n) {
177
+ CUTLASS_PRAGMA_UNROLL
178
+ for (int mma_n = 0; mma_n < Policy::MmaIterations::kColumn;
179
+ ++mma_n) {
180
+ CUTLASS_PRAGMA_UNROLL
181
+ for (int p = 0; p < kAccumulatorPatials; ++p) {
182
+ CUTLASS_PRAGMA_UNROLL
183
+ for (int n = 0; n < EleShapePerPatial::kColumn; ++n) {
184
+ int mma_accum_start =
185
+ (((tile_n * Policy::TileIterations::kRow + tile_m) *
186
+ Policy::MmaIterations::kColumn +
187
+ mma_n) *
188
+ Policy::MmaIterations::kRow +
189
+ mma_m) *
190
+ kElementsPerMma;
191
+ int accum_n = tile_n * Policy::InterleavedTile::kColumn +
192
+ mma_n * QuadShapePerPatialMma::kColumn +
193
+ p * Policy::InterleavedTile::kColumn / 2 + n +
194
+ lane_offset.column();
195
+ int idx = mma_accum_start + p * kElementsPerPartial +
196
+ m * EleShapePerPatial::kColumn + n;
197
+ op(accum_m, accum_n, idx);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ endRow(accum_m);
203
+ }
204
+ }
205
+ }
206
+ }
207
+ };
208
+
209
+ template <typename T, typename accum_t, int kWarpSize>
210
+ struct AccumLambdaIteratorSimt {
211
+ using Policy = typename T::Policy;
212
+ using Iterations = typename T::Iterations;
213
+ using Element = typename T::Element;
214
+ using Delta = typename T::Delta;
215
+ using Shape = typename T::Shape;
216
+ static_assert(
217
+ cutlass::platform::
218
+ is_same<typename T::Layout, cutlass::layout::RowMajor>::value,
219
+ "only RowMajor is supported");
220
+
221
+ template <typename DT, typename F>
222
+ CUTLASS_DEVICE static bool reduceSameRow(int lane_id, DT& myValue, F fn) {
223
+ CUTLASS_PRAGMA_UNROLL
224
+ for (int bit = 1; bit < Policy::WarpShape::kColumn; bit *= 2) {
225
+ auto otherV = __shfl_xor_sync(0xffffffff, myValue, bit);
226
+ myValue = fn(myValue, otherV);
227
+ }
228
+ return (lane_id & (Policy::WarpShape::kColumn - 1)) == 0;
229
+ }
230
+
231
+ template <typename FA, typename FB, typename FC>
232
+ CUTLASS_DEVICE static void iterateRows(
233
+ cutlass::MatrixCoord& lane_offset,
234
+ FA beginRow,
235
+ FB op,
236
+ FC endRow) {
237
+ CUTLASS_PRAGMA_UNROLL
238
+ for (int mma_m = 0; mma_m < Iterations::kRow; ++mma_m) {
239
+ CUTLASS_PRAGMA_UNROLL
240
+ for (int m = 0; m < Policy::LaneMmaShape::kM; ++m) {
241
+ int accum_m = mma_m * Delta::kRow + m + lane_offset.row();
242
+ beginRow(accum_m);
243
+
244
+ CUTLASS_PRAGMA_UNROLL
245
+ for (int mma_n = 0; mma_n < Iterations::kColumn; ++mma_n) {
246
+ int accum_n =
247
+ mma_n * Policy::WarpShape::kColumn * Policy::LaneMmaShape::kN +
248
+ lane_offset.column();
249
+ CUTLASS_PRAGMA_UNROLL
250
+ for (int n = 0; n < Policy::LaneMmaShape::kN; ++n) {
251
+ int idx = n +
252
+ Policy::LaneMmaShape::kN *
253
+ (mma_n +
254
+ Iterations::kColumn *
255
+ (m + mma_m * Policy::LaneMmaShape::kM));
256
+ op(accum_m, accum_n + n, idx);
257
+ }
258
+ }
259
+ endRow(accum_m);
260
+ }
261
+ }
262
+ }
263
+
264
+ static cutlass::MatrixCoord CUTLASS_DEVICE get_lane_offset(
265
+ int8_t lane_id,
266
+ int8_t warp_id,
267
+ typename T::TensorCoord const& tile_offset) {
268
+ static_assert(
269
+ cutlass::platform::is_same<
270
+ typename Policy::LaneLayout,
271
+ cutlass::layout::RowMajorInterleaved<1>>::value,
272
+ "");
273
+ typename Policy::LaneLayout lane_layout = Policy::get_lane_layout();
274
+
275
+ cutlass::MatrixCoord lane_offset = lane_layout.inverse(lane_id) *
276
+ cutlass::MatrixCoord(Policy::LaneMmaShape::kM,
277
+ Policy::LaneMmaShape::kN);
278
+ return lane_offset +
279
+ tile_offset * cutlass::MatrixCoord(Shape::kRow, Shape::kColumn);
280
+ }
281
+ };
282
+
283
+ template <typename T, typename accum_t, int kWarpSize>
284
+ struct DefaultMmaAccumLambdaIterator;
285
+
286
+ // Simt
287
+ template <typename S, typename P, typename accum_t, int kWarpSize>
288
+ struct DefaultMmaAccumLambdaIterator<
289
+ cutlass::gemm::warp::MmaSimtTileIterator<
290
+ S,
291
+ cutlass::gemm::Operand::kC,
292
+ accum_t,
293
+ cutlass::layout::RowMajor,
294
+ P,
295
+ 1,
296
+ 1>,
297
+ accum_t,
298
+ kWarpSize> {
299
+ using WarpIterator = typename cutlass::gemm::warp::MmaSimtTileIterator<
300
+ S,
301
+ cutlass::gemm::Operand::kC,
302
+ accum_t,
303
+ cutlass::layout::RowMajor,
304
+ P,
305
+ 1,
306
+ 1>;
307
+ using Iterator = AccumLambdaIteratorSimt<WarpIterator, accum_t, kWarpSize>;
308
+ };
309
+
310
+ // TensorOp - Volta
311
+ template <typename S1, typename S2, typename accum_t, int kWarpSize>
312
+ struct DefaultMmaAccumLambdaIterator<
313
+ cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator<
314
+ S1,
315
+ accum_t,
316
+ cutlass::layout::RowMajor,
317
+ S2,
318
+ cutlass::MatrixShape<1, 1>>,
319
+ accum_t,
320
+ kWarpSize> {
321
+ using WarpIterator =
322
+ typename cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator<
323
+ S1,
324
+ accum_t,
325
+ cutlass::layout::RowMajor,
326
+ S2,
327
+ cutlass::MatrixShape<1, 1>>;
328
+ using Iterator = AccumLambdaIteratorSm70<WarpIterator, accum_t, kWarpSize>;
329
+ };
330
+
331
+ // TensorOp - Sm75+
332
+ template <
333
+ typename S1,
334
+ typename S2,
335
+ typename S3,
336
+ typename accum_t,
337
+ int kWarpSize>
338
+ struct DefaultMmaAccumLambdaIterator<
339
+ cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator<
340
+ S1,
341
+ accum_t,
342
+ cutlass::layout::RowMajor,
343
+ S2,
344
+ S3>,
345
+ accum_t,
346
+ kWarpSize> {
347
+ using WarpIterator =
348
+ typename cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator<
349
+ S1,
350
+ accum_t,
351
+ cutlass::layout::RowMajor,
352
+ S2,
353
+ S3>;
354
+ using Iterator = AccumLambdaIteratorSm80<WarpIterator, accum_t, kWarpSize>;
355
+ };
356
+
357
+ #else
358
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
359
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_from_smem.h ADDED
@@ -0,0 +1,1953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /***************************************************************************************************
3
+ * Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights
4
+ *reserved. SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice,
10
+ *this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ * this list of conditions and the following disclaimer in the documentation
14
+ * and/or other materials provided with the distribution.
15
+ *
16
+ * 3. Neither the name of the copyright holder nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ *POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ **************************************************************************************************/
33
+ /*! \file
34
+ \brief Template for a double-buffered threadblock-scoped GEMM kernel.
35
+ */
36
+
37
+ #pragma once
38
+
39
+ #include <cutlass/aligned_buffer.h>
40
+ #include <cutlass/arch/memory.h>
41
+ #include <cutlass/array.h>
42
+ #include <cutlass/cutlass.h>
43
+ #include <cutlass/epilogue/thread/linear_combination.h>
44
+ #include <cutlass/epilogue/threadblock/default_epilogue_simt.h>
45
+ #include <cutlass/epilogue/threadblock/default_epilogue_tensor_op.h>
46
+ #include <cutlass/epilogue/threadblock/default_epilogue_volta_tensor_op.h>
47
+ #include <cutlass/functional.h>
48
+ #include <cutlass/gemm/gemm.h>
49
+ #include <cutlass/gemm/warp/mma_tensor_op_fragment_iterator.h>
50
+ #include <cutlass/matrix_shape.h>
51
+ #include <cutlass/numeric_conversion.h>
52
+ #include <cutlass/numeric_types.h>
53
+ #include <cutlass/platform/platform.h>
54
+ #include <cutlass/transform/threadblock/vector_iterator.h>
55
+
56
+ #include <cutlass/epilogue/threadblock/epilogue_smem_accumulator.h>
57
+ #include <cutlass/gemm/threadblock/mma_base.h>
58
+ #include <cutlass/gemm/warp/mma_tensor_op_tile_access_iterator.h>
59
+ #include <cutlass/gemm/threadblock/mma_pipelined.h>
60
+ #include <cutlass/gemm/threadblock/mma_multistage.h>
61
+
62
+ #include <ATen/native/transformers/cuda/mem_eff_attention/epilogue/epilogue_thread_apply_logsumexp.h>
63
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm_kernel_utils.h>
64
+ #include <ATen/native/transformers/cuda/mem_eff_attention/iterators/make_residual_last.h>
65
+ #include <ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_accum_lambda_iterator.h>
66
+
67
+ #include <ATen/native/transformers/cuda/mem_eff_attention/iterators/default_warp_iterator_from_smem.h>
68
+ #include <ATen/native/transformers/cuda/mem_eff_attention/iterators/make_residual_last.h>
69
+ #include <ATen/native/transformers/cuda/mem_eff_attention/iterators/transpose_warp_iterator.h>
70
+ #include <ATen/native/transformers/cuda/mem_eff_attention/iterators/warp_iterator_from_smem.h>
71
+
72
+ /////////////////////////////////////////////////////////////////////////////////////////////////
73
+
74
+ namespace cutlass {
75
+ namespace gemm {
76
+ namespace threadblock {
77
+
78
+ /// Shared storage object needed by accumulator
79
+ /// From 13_two_tensor_op_fusion/threadblock/b2b_mma_base_smem_accumulator.h
80
+ template <
81
+ typename Shape_,
82
+ typename Element_,
83
+ typename Layout_,
84
+ typename Padding_>
85
+ class AccumulatorSharedStorage {
86
+ public:
87
+ //
88
+ // Type definitions
89
+ //
90
+ using Shape = Shape_;
91
+ using Element = Element_;
92
+ using Layout = Layout_;
93
+ using Padding = Padding_;
94
+
95
+ /// Tensor reference to the accumulator
96
+ using TensorRefAccum = cutlass::TensorRef<Element, Layout>;
97
+
98
+ /// Shape of the accumulator matrix in shared memory
99
+ using ShapeAccum = cutlass::
100
+ MatrixShape<Shape::kM + Padding::kRow, Shape::kN + Padding::kColumn>;
101
+
102
+ public:
103
+ //
104
+ // Data members
105
+ //
106
+
107
+ /// Buffer for accumulator
108
+ cutlass::AlignedBuffer<Element, ShapeAccum::kCount> accum;
109
+
110
+ public:
111
+ //
112
+ // Methods
113
+ //
114
+
115
+ /// Returns a layout object for the Accum matrix
116
+ CUTLASS_DEVICE
117
+ static Layout LayoutAccum() {
118
+ return Layout::packed({ShapeAccum::kRow, ShapeAccum::kColumn});
119
+ }
120
+
121
+ /// Returns a TensorRef to the Accumulator
122
+ CUTLASS_HOST_DEVICE
123
+ TensorRefAccum accum_ref() {
124
+ return TensorRefAccum{accum.data(), LayoutAccum()};
125
+ }
126
+ };
127
+
128
+ ////////////////////////////////////////////////////////////////////////////////
129
+ // Taken from
130
+ // https://github.com/NVIDIA/cutlass/blob/master/examples/13_two_tensor_op_fusion/threadblock/b2b_mma_base_smem_accumulator.h
131
+ ////////////////////////////////////////////////////////////////////////////////
132
+
133
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
134
+ /// instructions.
135
+ template <
136
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
137
+ typename Shape_,
138
+ // Maximum K dimension - also the dimension of the shared-memory
139
+ // holding `OperandA`
140
+ int kMaxK_,
141
+ /// Policy describing tuning details (concept: MmaPolicy)
142
+ typename Policy_,
143
+ /// Number of stages,
144
+ int Stages,
145
+ /// Layout in shared-memory of operand A
146
+ typename SmemLayoutA,
147
+ /// Used for partial specialization
148
+ typename Enable = bool>
149
+ class MmaBaseFromSharedMemory {
150
+ public:
151
+ ///< Size of the Gemm problem - concept: gemm::GemmShape<>
152
+ using Shape = Shape_;
153
+ static constexpr int kMaxK = kMaxK_;
154
+
155
+ ///< Policy describing tuning details
156
+ using Policy = Policy_;
157
+
158
+ //
159
+ // Dependent types
160
+ //
161
+
162
+ /// Warp-level Mma
163
+ using Operator = typename Policy::Operator;
164
+
165
+ /// Shape describing the overall GEMM computed from shared memory
166
+ /// by each warp.
167
+ using WarpGemm = typename Policy::Operator::Shape;
168
+
169
+ /// Shape describing the number of warps filling the CTA
170
+ using WarpCount = GemmShape<
171
+ Shape::kM / WarpGemm::kM,
172
+ Shape::kN / WarpGemm::kN,
173
+ Shape::kK / WarpGemm::kK>;
174
+ using WarpCount1 = WarpCount;
175
+
176
+ /// Number of warp-level GEMM operations
177
+ static int const kWarpGemmIterations =
178
+ (WarpGemm::kK / Operator::Policy::MmaShape::kK);
179
+ static int const kWarpGemmIterations1 = kWarpGemmIterations;
180
+
181
+ /// Number of stages
182
+ static int const kStages = Stages;
183
+
184
+ /// If this is true, we fill the entire shmem buffer at start
185
+ /// and don't need to iterate through it in a circular fashion
186
+ static bool const kSmemContainsEntireB = kMaxK <= Shape::kK * kStages;
187
+
188
+ /// Tensor reference to the A operand
189
+ using TensorRefA = TensorRef<typename Operator::ElementA, SmemLayoutA>;
190
+
191
+ /// Tensor reference to the B operand
192
+ using TensorRefB =
193
+ TensorRef<typename Operator::ElementB, typename Operator::LayoutB>;
194
+
195
+ //
196
+ // Nested structs
197
+ //
198
+
199
+ /// Shared storage object needed by threadblock-scoped GEMM
200
+ class SharedStorage {
201
+ public:
202
+ //
203
+ // Type definitions
204
+ //
205
+
206
+ /// Shape of the B matrix operand in shared memory
207
+ using ShapeB = MatrixShape<
208
+ Shape::kK * kStages + Policy::SmemPaddingB::kRow,
209
+ Shape::kN + Policy::SmemPaddingB::kColumn>;
210
+
211
+ public:
212
+ //
213
+ // Data members
214
+ //
215
+
216
+ /// Buffer for B operand
217
+ AlignedBuffer<typename Operator::ElementB, ShapeB::kCount> operand_B;
218
+
219
+ public:
220
+ //
221
+ // Methods
222
+ //
223
+
224
+ /// Returns a layout object for the B matrix
225
+ CUTLASS_HOST_DEVICE
226
+ static typename Operator::LayoutB LayoutB() {
227
+ return Operator::LayoutB::packed({ShapeB::kRow, ShapeB::kColumn});
228
+ }
229
+
230
+ /// Returns a TensorRef to the B operand
231
+ CUTLASS_HOST_DEVICE
232
+ TensorRefB operand_B_ref() {
233
+ return TensorRefB{operand_B.data(), LayoutB()};
234
+ }
235
+ };
236
+
237
+ protected:
238
+ //
239
+ // Data members
240
+ //
241
+
242
+ // /// Iterator to load a warp-scoped tile of A operand from shared memory
243
+ // typename Operator::IteratorA warp_tile_iterator_A_;
244
+
245
+ /// Iterator to load a warp-scoped tile of B operand from shared memory
246
+ typename Operator::IteratorB warp_tile_iterator_B_;
247
+
248
+ public:
249
+ /// Construct from tensor references
250
+ CUTLASS_DEVICE
251
+ MmaBaseFromSharedMemory(
252
+ ///< Shared storage needed for internal use by threadblock-scoped GEMM
253
+ TensorRefB& b_tile,
254
+ ///< ID within the threadblock
255
+ int thread_idx,
256
+ ///< ID of warp
257
+ int warp_idx,
258
+ ///< ID of each thread within a warp
259
+ int lane_idx)
260
+ : warp_tile_iterator_B_(b_tile, lane_idx) {}
261
+ };
262
+
263
+ namespace {
264
+
265
+ // has necessary trait compliance with WarpIteratorFromSmem but doesn't do
266
+ // anything, can be default initialized, and uses fragment that takes up
267
+ // (almost) no space. this warp iterator is selected at compile time when
268
+ // elementwise on-the-fly scaling for operand A is disabled, in which case
269
+ // operations related to loading scale factors for operand A get wiped out by
270
+ // the compiler.
271
+ template <typename TensorRef>
272
+ class NoOpWarpIteratorScale {
273
+ public:
274
+ // in pipelined+multistage MMA implementations we keep an array of fragments.
275
+ // if we aren't using scaling we don't want to waste registers on fragments
276
+ // of scale elements, so ideally this would be sized 0.
277
+ // Since arrays of zero-sized objects are not allowed, using size as 1.
278
+ // The compiler will most likely wipe it out anyways.
279
+ using Fragment = cutlass::Array<char, 1>;
280
+
281
+ CUTLASS_HOST_DEVICE
282
+ NoOpWarpIteratorScale() {}
283
+
284
+ CUTLASS_HOST_DEVICE
285
+ NoOpWarpIteratorScale(TensorRef const&, int) {}
286
+
287
+ CUTLASS_HOST_DEVICE
288
+ NoOpWarpIteratorScale& add_tile_offset(
289
+ typename TensorRef::TensorCoord const&) {
290
+ return *this;
291
+ }
292
+
293
+ CUTLASS_HOST_DEVICE
294
+ NoOpWarpIteratorScale& operator++() {
295
+ return *this;
296
+ }
297
+
298
+ CUTLASS_DEVICE
299
+ void load(Fragment&) const {}
300
+ };
301
+
302
+ // if scaling is enabled, performs fragment elementwise multiplication between
303
+ // fragment and its scaling factor.
304
+ template <typename Fragment, typename FragmentScale, bool ScalingEnabled>
305
+ class FragmentElementwiseScaler;
306
+
307
+ // specialization for scaling being enabled.
308
+ template <typename Fragment, typename FragmentScale>
309
+ class FragmentElementwiseScaler<Fragment, FragmentScale, true> {
310
+ public:
311
+ // cast scale_frag to correct type then apply elementwise to fragment
312
+ CUTLASS_DEVICE
313
+ static Fragment apply(Fragment frag, FragmentScale const& scale_frag) {
314
+ Fragment converted_scale_frag = cutlass::NumericArrayConverter<
315
+ typename Fragment::Element,
316
+ typename FragmentScale::Element,
317
+ FragmentScale::kElements>()(scale_frag);
318
+ return cutlass::multiplies<Fragment>()(frag, converted_scale_frag);
319
+ }
320
+ };
321
+
322
+ // specialization for scaling being disabled. doesn't do anything and should
323
+ // just get wiped out by the compiler.
324
+ template <typename Fragment, typename FragmentScale>
325
+ class FragmentElementwiseScaler<Fragment, FragmentScale, false> {
326
+ public:
327
+ CUTLASS_DEVICE
328
+ static Fragment apply(Fragment frag, FragmentScale const&) {
329
+ return frag;
330
+ }
331
+ };
332
+ } // namespace
333
+
334
+ ////////////////////////////////////////////////////////////////////////////////
335
+ // Taken from
336
+ // https://github.com/NVIDIA/cutlass/blob/master/examples/13_two_tensor_op_fusion/threadblock/b2b_mma_pipelined_smem_accumulator.h
337
+ ////////////////////////////////////////////////////////////////////////////////
338
+
339
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
340
+ /// instructions.
341
+ template <
342
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
343
+ typename Shape_,
344
+ // BEGIN smem
345
+ /// Iterates over the intermediate accumulator tile in shared memory
346
+ typename WarpIteratorA_,
347
+ /// whether or not to perform elementwise multiplication of A
348
+ // by another matrix (A_scale) that is also kept in shared memory prior
349
+ // to matmul A @ B
350
+ bool ScaleOperandA_,
351
+ /// Max GEMM problem size in K dimension
352
+ int MaxK,
353
+ /// Iterates over tiles of B operand in global memory
354
+ // (concept: ReadableTileIterator | ForwardTileIterator |
355
+ // MaskedTileIterator)
356
+ typename IteratorB_,
357
+ /// Iterates over tiles of B operand in shared memory
358
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
359
+ typename SmemIteratorB_,
360
+ /// Data type of accumulator matrix
361
+ typename ElementC_,
362
+ /// Data type of accumulator matrix
363
+ typename LayoutC_,
364
+ /// Policy describing tuning details (concept: MmaPolicy)
365
+ typename Policy_,
366
+ /// Transformation applied to B operand
367
+ typename TransformB_ = NumericArrayConverter<
368
+ typename SmemIteratorB_::Element,
369
+ typename IteratorB_::Element,
370
+ IteratorB_::Fragment::kElements>,
371
+ /// Used for partial specialization
372
+ typename Enable = bool>
373
+ class MmaPipelinedFromSharedMemory : public MmaBaseFromSharedMemory<
374
+ Shape_,
375
+ MaxK,
376
+ Policy_,
377
+ 2,
378
+ typename WarpIteratorA_::Layout> {
379
+ public:
380
+ ///< Base class
381
+ using Base = MmaBaseFromSharedMemory<
382
+ Shape_,
383
+ MaxK,
384
+ Policy_,
385
+ 2,
386
+ typename WarpIteratorA_::Layout>;
387
+
388
+ using Shape =
389
+ Shape_; ///< Size of the Gemm problem - concept: gemm::GemmShape<>
390
+ static constexpr bool ScaleOperandA = ScaleOperandA_;
391
+
392
+ using WarpIteratorA = WarpIteratorA_;
393
+ ///< loads fragments of A_scale from shared memory if operand A scaling is
394
+ ///< enabled. otherwise no-op.
395
+ using WarpIteratorAScale = typename cutlass::platform::conditional<
396
+ ScaleOperandA,
397
+ WarpIteratorA,
398
+ NoOpWarpIteratorScale<typename WarpIteratorA::TensorRef>>::type;
399
+
400
+ using IteratorB =
401
+ IteratorB_; ///< Iterates over tiles of B operand in global memory
402
+ using ElementC = ElementC_; ///< Data type of accumulator matrix
403
+ using LayoutC = LayoutC_; ///< Layout of accumulator matrix
404
+ using Policy = Policy_; ///< Policy describing tuning details
405
+
406
+ using SmemIteratorB = SmemIteratorB_;
407
+
408
+ using TransformB = TransformB_;
409
+
410
+ //
411
+ // Dependent types
412
+ //
413
+
414
+ /// Fragment of operand B loaded from global memory
415
+ using FragmentB = typename IteratorB::Fragment;
416
+
417
+ /// Fragment of accumulator tile
418
+ using FragmentC = typename Policy::Operator::FragmentC;
419
+
420
+ /// Warp-level Mma
421
+ using Operator = typename Policy::Operator;
422
+
423
+ /// Obtain the arch tag from the warp-level operator
424
+ using ArchTag = typename Policy::Operator::ArchTag;
425
+
426
+ /// Complex transform on B operand
427
+ static ComplexTransform const kTransformB = Operator::kTransformB;
428
+
429
+ // statically assert kStages for MmaPipelined is two (Double-buffered pipeline)
430
+ static_assert(
431
+ (Base::kStages == 2),
432
+ "MmaPipelined requires kStages set to value 2");
433
+
434
+ private:
435
+ using WarpFragmentA = typename Operator::FragmentA;
436
+
437
+ /// fragment type of OperandA elementwise scaling matrix. (almost) empty
438
+ /// if operand A scaling is disabled.
439
+ using WarpFragmentAScale = typename WarpIteratorAScale::Fragment;
440
+
441
+ using WarpFragmentB = typename Operator::FragmentB;
442
+
443
+ /// applies scaling factor to operand A fragment if operand A scaling is
444
+ /// enabled. otherwise no-op.
445
+ using FragmentAScaler = FragmentElementwiseScaler<
446
+ WarpFragmentA,
447
+ WarpFragmentAScale,
448
+ ScaleOperandA>;
449
+
450
+ protected:
451
+ // /// Iterator to write threadblock-scoped tile of A operand to shared memory
452
+ // SmemIteratorA smem_iterator_A_;
453
+
454
+ /// Iterator to write threadblock-scoped tile of B operand to shared memory
455
+ SmemIteratorB smem_iterator_B_;
456
+
457
+ /// Iterator to load a warp-scoped tile of A operand from intermediate
458
+ /// accumulator tile
459
+ WarpIteratorA warp_tile_iterator_A_;
460
+
461
+ /// Iterator to load a warp-scoped tile of A_scale from intermediate
462
+ /// accumulator tile (only used if ScaleOperandA_ is true)
463
+ WarpIteratorAScale warp_tile_iterator_A_scale_;
464
+
465
+ public:
466
+ /// constructor for MMA with operand A scaling enabled.
467
+ CUTLASS_DEVICE
468
+ MmaPipelinedFromSharedMemory(
469
+ typename Base::TensorRefA a, // Operand A in shared memory
470
+ typename Base::TensorRefA a_scale, // Operand A_scale in shared memory
471
+ typename Base::TensorRefB
472
+ b_staging, // staging memory for loading tiles of B
473
+ int thread_idx,
474
+ int warp_idx,
475
+ int lane_idx)
476
+ : Base(b_staging, thread_idx, warp_idx, lane_idx),
477
+ warp_tile_iterator_A_(a, lane_idx),
478
+ warp_tile_iterator_A_scale_(a_scale, lane_idx),
479
+ smem_iterator_B_(b_staging, thread_idx) {
480
+ // Compute warp location within threadblock tile by mapping the warp_id to
481
+ // three coordinates:
482
+ // _m: the warp's position within the threadblock along the M dimension
483
+ // _n: the warp's position within the threadblock along the N dimension
484
+ // _k: the warp's position within the threadblock along the K dimension
485
+ int warp_idx_mn = warp_idx % (Base::WarpCount::kM * Base::WarpCount::kN);
486
+ int warp_idx_k = warp_idx / (Base::WarpCount::kM * Base::WarpCount::kN);
487
+ int warp_idx_m = warp_idx_mn % Base::WarpCount::kM;
488
+ int warp_idx_n = warp_idx_mn / Base::WarpCount::kM;
489
+
490
+ // Add per-warp offsets in units of warp-level tiles
491
+ this->warp_tile_iterator_A_.add_tile_offset(
492
+ {warp_idx_m, Base::kWarpGemmIterations * warp_idx_k});
493
+ this->warp_tile_iterator_A_scale_.add_tile_offset(
494
+ {warp_idx_m, Base::kWarpGemmIterations * warp_idx_k});
495
+ this->warp_tile_iterator_B_.add_tile_offset(
496
+ {Base::kWarpGemmIterations * warp_idx_k, warp_idx_n});
497
+ }
498
+
499
+ /// Construct from tensor references
500
+ CUTLASS_DEVICE
501
+ MmaPipelinedFromSharedMemory(
502
+ typename Base::TensorRefA a, ///< Operand A in shared memory
503
+ typename Base::TensorRefB b_staging, ///< staging memory for loading B
504
+ int thread_idx, ///< ID within the threadblock
505
+ int warp_idx, ///< ID of warp
506
+ int lane_idx) ///< ID of each thread within a warp
507
+ : Base(b_staging, thread_idx, warp_idx, lane_idx),
508
+ warp_tile_iterator_A_(a, lane_idx),
509
+ smem_iterator_B_(b_staging, thread_idx) {
510
+ // Compute warp location within threadblock tile by mapping the warp_id to
511
+ // three coordinates:
512
+ // _m: the warp's position within the threadblock along the M dimension
513
+ // _n: the warp's position within the threadblock along the N dimension
514
+ // _k: the warp's position within the threadblock along the K dimension
515
+
516
+ int warp_idx_mn = warp_idx % (Base::WarpCount::kM * Base::WarpCount::kN);
517
+ int warp_idx_k = warp_idx / (Base::WarpCount::kM * Base::WarpCount::kN);
518
+
519
+ int warp_idx_m = warp_idx_mn % Base::WarpCount::kM;
520
+ int warp_idx_n = warp_idx_mn / Base::WarpCount::kM;
521
+
522
+ // Add per-warp offsets in units of warp-level tiles
523
+ this->warp_tile_iterator_A_.add_tile_offset(
524
+ {warp_idx_m, Base::kWarpGemmIterations * warp_idx_k});
525
+ this->warp_tile_iterator_B_.add_tile_offset(
526
+ {Base::kWarpGemmIterations * warp_idx_k, warp_idx_n});
527
+ }
528
+
529
+ // For API compatibility with MmaMultistageFromSharedMemory
530
+ // but not supported as it worsens perf: older gpus < sm80 don't
531
+ // support async transfers and have to waste registers
532
+ CUTLASS_DEVICE
533
+ void set_prologue_done(bool value) {}
534
+ CUTLASS_DEVICE
535
+ static void prologue(
536
+ typename Base::SharedStorage& shared_storage,
537
+ IteratorB iterator_B1,
538
+ int thread_idx,
539
+ int problem_size_0_n) {}
540
+
541
+ /// Perform a threadblock-scoped matrix multiply-accumulate
542
+ CUTLASS_DEVICE
543
+ void operator()(
544
+ int gemm_k_iterations, ///< number of iterations of the mainloop
545
+ FragmentC& accum, ///< destination accumulator tile
546
+ // IteratorA iterator_A, ///< iterator over A
547
+ // operand in global memory
548
+ IteratorB iterator_B, ///< iterator over B operand in global memory
549
+ FragmentC const& src_accum, ///< source accumulator tile
550
+ // TransformA transform_A = TransformA(), ///< transformation
551
+ // applied to A fragment
552
+ TransformB transform_B =
553
+ TransformB()) { ///< transformation applied to B fragment
554
+
555
+ //
556
+ // Prologue
557
+ //
558
+
559
+ // Perform accumulation in the 'd' output operand
560
+ accum = src_accum;
561
+
562
+ FragmentB tb_frag_B;
563
+
564
+ tb_frag_B.clear();
565
+
566
+ // The last kblock is loaded in the prolog
567
+ iterator_B.set_residual_tile(gemm_k_iterations == 1);
568
+ iterator_B.load(tb_frag_B);
569
+
570
+ ++iterator_B;
571
+
572
+ this->smem_iterator_B_.store(transform_B(tb_frag_B));
573
+
574
+ ++this->smem_iterator_B_;
575
+
576
+ __syncthreads();
577
+
578
+ // remember that WarpFragmentAScale and WarpIteratorAScale are empty/no-op
579
+ // if scaling is disabled.
580
+
581
+ // Pair of fragments used to overlap shared memory loads and math
582
+ // instructions
583
+ WarpFragmentA warp_frag_A[2];
584
+ WarpFragmentAScale warp_frag_A_scale[2];
585
+ WarpFragmentB warp_frag_B[2];
586
+ warp_frag_A[0].clear();
587
+ warp_frag_A_scale[0].clear();
588
+ warp_frag_B[0].clear();
589
+
590
+ this->warp_tile_iterator_B_.set_kgroup_index(0);
591
+
592
+ this->warp_tile_iterator_A_.load(warp_frag_A[0]);
593
+ this->warp_tile_iterator_A_scale_.load(warp_frag_A_scale[0]);
594
+ this->warp_tile_iterator_B_.load(warp_frag_B[0]);
595
+
596
+ ++this->warp_tile_iterator_A_;
597
+ ++this->warp_tile_iterator_A_scale_;
598
+ ++this->warp_tile_iterator_B_;
599
+
600
+ Operator warp_mma;
601
+
602
+ int smem_write_stage_idx = 1;
603
+
604
+ // Avoid reading out of bounds
605
+ iterator_B.set_residual_tile(gemm_k_iterations == 2);
606
+ iterator_B.clear_mask(gemm_k_iterations <= 1);
607
+
608
+ // Issue loads during the first warp-level matrix multiply-add *AFTER*
609
+ // issuing shared memory loads (which have the tightest latency
610
+ // requirement).
611
+
612
+ //
613
+ // Mainloop
614
+ //
615
+
616
+ // Note: The main loop does not support Base::kWarpGemmIterations == 2.
617
+ CUTLASS_GEMM_LOOP
618
+ for (; gemm_k_iterations > 0; --gemm_k_iterations) {
619
+ //
620
+ // Loop over GEMM K dimension
621
+ //
622
+
623
+ CUTLASS_PRAGMA_UNROLL
624
+ for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations;
625
+ ++warp_mma_k) {
626
+ // Load warp-level tiles from shared memory, wrapping to k offset if
627
+ // this is the last group as the case may be.
628
+ bool hasNext = true;
629
+
630
+ if (warp_mma_k == Base::kWarpGemmIterations - 1) {
631
+ if (gemm_k_iterations > 1) {
632
+ // Write fragments to shared memory
633
+ this->smem_iterator_B_.store(transform_B(tb_frag_B));
634
+ }
635
+
636
+ __syncthreads();
637
+
638
+ ++this->smem_iterator_B_;
639
+
640
+ // Add negative offsets to return iterators to the 'start' of the
641
+ // circular buffer in shared memory SMEM: Don't reset iterator A, as
642
+ // we are continuing our iteration at this point
643
+ if (smem_write_stage_idx == 1) {
644
+ this->smem_iterator_B_.add_tile_offset({-Base::kStages, 0});
645
+ } else {
646
+ this->warp_tile_iterator_B_.add_tile_offset(
647
+ {-Base::kStages * Policy::kPartitionsK *
648
+ Base::kWarpGemmIterations,
649
+ 0});
650
+ }
651
+
652
+ smem_write_stage_idx ^= 1;
653
+ hasNext = gemm_k_iterations > 1;
654
+ }
655
+
656
+ // Only read the next if we need to
657
+ if (hasNext) {
658
+ this->warp_tile_iterator_B_.set_kgroup_index(
659
+ (warp_mma_k + 1) % Base::kWarpGemmIterations);
660
+
661
+ this->warp_tile_iterator_A_.load(warp_frag_A[(warp_mma_k + 1) % 2]);
662
+ this->warp_tile_iterator_A_scale_.load(
663
+ warp_frag_A_scale[(warp_mma_k + 1) % 2]);
664
+ this->warp_tile_iterator_B_.load(warp_frag_B[(warp_mma_k + 1) % 2]);
665
+
666
+ ++this->warp_tile_iterator_A_;
667
+ ++this->warp_tile_iterator_A_scale_;
668
+ ++this->warp_tile_iterator_B_;
669
+
670
+ if (warp_mma_k == 0) {
671
+ iterator_B.load(tb_frag_B);
672
+
673
+ ++iterator_B;
674
+
675
+ // Avoid reading out of bounds if this was the last loop iteration
676
+ iterator_B.set_residual_tile(gemm_k_iterations == 3);
677
+ iterator_B.clear_mask(gemm_k_iterations <= 2);
678
+ }
679
+ }
680
+
681
+ warp_mma(
682
+ accum,
683
+ FragmentAScaler::apply(
684
+ warp_frag_A[warp_mma_k % 2], warp_frag_A_scale[warp_mma_k % 2]),
685
+ warp_frag_B[warp_mma_k % 2],
686
+ accum);
687
+ }
688
+ }
689
+ }
690
+ };
691
+
692
+ ////////////////////////////////////////////////////////////////////////////////
693
+ // Taken from
694
+ // https://github.com/NVIDIA/cutlass/blob/master/examples/13_two_tensor_op_fusion/threadblock/b2b_mma_multistage_smem_accumulator.h
695
+ ////////////////////////////////////////////////////////////////////////////////
696
+
697
+ /// Structure to compute the matrix product targeting CUDA cores and SIMT math
698
+ /// instructions.
699
+ template <
700
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
701
+ typename Shape1_,
702
+ /// Iterates over the intermediate accumulator tile in shared memory
703
+ typename WarpIteratorA1_,
704
+ /// whether or not to perform elementwise multiplication of A
705
+ // by another matrix (A_scale) that is also kept in shared memory prior
706
+ // to matmul A @ B
707
+ bool ScaleOperandA_,
708
+ /// Iterates over tiles of B operand in global memory
709
+ // (concept: ReadableTileIterator | ForwardTileIterator |
710
+ // MaskedTileIterator)
711
+ typename IteratorB1_,
712
+ /// Iterates over tiles of B operand in shared memory
713
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
714
+ typename SmemIteratorB1_,
715
+ /// Cache operation for operand B
716
+ cutlass::arch::CacheOperation::Kind CacheOpB1,
717
+ /// Data type of accumulator matrix
718
+ typename ElementC_,
719
+ /// Data type of accumulator matrix
720
+ typename LayoutC_,
721
+ /// Policy describing tuning details (concept: MmaPolicy)
722
+ typename Policy1_,
723
+ /// Number of stages,
724
+ int Stages_,
725
+ int kMaxK_,
726
+ /// Used for partial specialization
727
+ typename Enable = bool>
728
+ class MmaMultistageFromSharedMemory : public MmaBaseFromSharedMemory<
729
+ Shape1_,
730
+ kMaxK_,
731
+ Policy1_,
732
+ Stages_,
733
+ typename WarpIteratorA1_::Layout> {
734
+ public:
735
+ ///< Base class
736
+ using Base = MmaBaseFromSharedMemory<
737
+ Shape1_,
738
+ kMaxK_,
739
+ Policy1_,
740
+ Stages_,
741
+ typename WarpIteratorA1_::Layout>;
742
+
743
+ ///< Size of the Gemm problem - concept: gemm::GemmShape<>
744
+ using Shape1 = Shape1_;
745
+ ///< Iterates over tiles of B operand in global memory
746
+ using IteratorB1 = IteratorB1_;
747
+ using IteratorB = IteratorB1;
748
+ ///< Policy describing tuning details
749
+ using Policy1 = Policy1_;
750
+
751
+ using SmemIteratorB1 = SmemIteratorB1_;
752
+ using WarpIteratorA1 = WarpIteratorA1_; ///< Iterates over the intermediate
753
+ ///< accumulator tile in shared memory
754
+ static constexpr bool ScaleOperandA = ScaleOperandA_;
755
+
756
+ ///< warp level iterator over A_scale matrix tile kept in shared memory.
757
+ ///< if elementwise A scaling is disabled then everything this does is no-op.
758
+ using WarpIteratorAScale = typename cutlass::platform::conditional<
759
+ ScaleOperandA,
760
+ WarpIteratorA1,
761
+ NoOpWarpIteratorScale<typename WarpIteratorA1::TensorRef>>::type;
762
+ ///< Data type of accumulator matrix
763
+ using ElementC = ElementC_;
764
+ ///< Layout of accumulator matrix
765
+ using LayoutC = LayoutC_;
766
+
767
+ static cutlass::arch::CacheOperation::Kind const kCacheOpB1 = CacheOpB1;
768
+ static constexpr bool kSmemContainsEntireB = Base::kSmemContainsEntireB;
769
+
770
+ //
771
+ // Dependent types
772
+ //
773
+
774
+ /// Fragment of accumulator tile
775
+ using FragmentC1 = typename Policy1::Operator::FragmentC;
776
+ using FragmentC = FragmentC1;
777
+
778
+ /// Warp-level Mma
779
+ using Operator1 = typename Policy1::Operator;
780
+
781
+ /// Minimum architecture is Sm80 to support cp.async
782
+ using ArchTag = arch::Sm80;
783
+
784
+ /// Complex transform on B operand
785
+ static ComplexTransform const kTransformB1 = Operator1::kTransformB;
786
+
787
+ /// Internal structure exposed for introspection.
788
+ struct Detail {
789
+ static_assert(
790
+ Base::kWarpGemmIterations1 > 1,
791
+ "The pipelined structure requires at least two warp-level "
792
+ "GEMM operations.");
793
+
794
+ /// Number of cp.async instructions to load one stage of operand B
795
+ static int const TBLoadIterationsB1 =
796
+ IteratorB1::ThreadMap::Iterations::kCount;
797
+
798
+ /// Number of cp.async instructions to load on group of operand B
799
+ static int const kAccessesPerGroupB1 =
800
+ (TBLoadIterationsB1 + Base::kWarpGemmIterations1 - 1) /
801
+ Base::kWarpGemmIterations1;
802
+ };
803
+
804
+ static constexpr int kNumStagesConcurrentLoad =
805
+ kSmemContainsEntireB ? Base::kStages : Base::kStages - 1;
806
+
807
+ private:
808
+ using WarpLoadedFragmentA1 = typename Operator1::FragmentA;
809
+ /// fragment of OperandA scale matrix. if operand A scaling is disabled this
810
+ /// is (almost) empty.
811
+ using WarpLoadedFragmentA1Scale = typename WarpIteratorAScale::Fragment;
812
+ using WarpLoadedFragmentB1 = typename Operator1::FragmentB;
813
+ using WarpTransformedFragmentA1 = typename Operator1::TransformedFragmentA;
814
+ using WarpTransformedFragmentB1 = typename Operator1::TransformedFragmentB;
815
+
816
+ /// applies elementwise scaling to fragment of A. if operand A scaling is
817
+ /// disabled this is a no-op.
818
+ using FragmentAScaler = FragmentElementwiseScaler<
819
+ WarpLoadedFragmentA1,
820
+ WarpLoadedFragmentA1Scale,
821
+ ScaleOperandA>;
822
+
823
+ private:
824
+ //
825
+ // Data members
826
+ //
827
+
828
+ /// Iterator to load a warp-scoped tile of A1 operand from intermediate
829
+ /// accumulator tile
830
+ WarpIteratorA1 warp_tile_iterator_A1_;
831
+
832
+ /// Iterator to load a warp-scoped tile of A1_scale operand from shared memory
833
+ /// if operand A scaling is disabled everything this does is a no-op.
834
+ WarpIteratorAScale warp_tile_iterator_A1_scale_;
835
+
836
+ /// Iterator to write threadblock-scoped tile of B operand to shared memory
837
+ SmemIteratorB1 smem_iterator_B1_;
838
+
839
+ bool prologue_done_;
840
+
841
+ public:
842
+ /// constructor for MMA with operand A scaling enabled.
843
+ CUTLASS_DEVICE
844
+ MmaMultistageFromSharedMemory(
845
+ typename Base::TensorRefA a,
846
+ typename Base::TensorRefA a_scale,
847
+ typename Base::TensorRefB b_tile,
848
+ int thread_idx,
849
+ int warp_idx,
850
+ int lane_idx)
851
+ : Base(b_tile, thread_idx, warp_idx, lane_idx),
852
+ warp_tile_iterator_A1_(a, lane_idx),
853
+ warp_tile_iterator_A1_scale_(a_scale, lane_idx),
854
+ smem_iterator_B1_(b_tile, thread_idx),
855
+ prologue_done_(false) {
856
+ // Compute warp location within threadblock tile by mapping the warp_id to
857
+ // three coordinates:
858
+ // _m: the warp's position within the threadblock along the M dimension
859
+ // _n: the warp's position within the threadblock along the N dimension
860
+ // _k: the warp's position within the threadblock along the K dimension
861
+ int warp_idx_mn_1 =
862
+ warp_idx % (Base::WarpCount1::kM * Base::WarpCount1::kN);
863
+ int warp_idx_k_1 = warp_idx / (Base::WarpCount1::kM * Base::WarpCount1::kN);
864
+ int warp_idx_m_1 = warp_idx_mn_1 % Base::WarpCount1::kM;
865
+ int warp_idx_n_1 = warp_idx_mn_1 / Base::WarpCount1::kM;
866
+
867
+ // Add per-warp offsets in units of warp-level tiles
868
+ warp_tile_iterator_A1_.add_tile_offset(
869
+ {warp_idx_m_1, Base::kWarpGemmIterations1 * warp_idx_k_1});
870
+ warp_tile_iterator_A1_scale_.add_tile_offset(
871
+ {warp_idx_m_1, Base::kWarpGemmIterations1 * warp_idx_k_1});
872
+ this->warp_tile_iterator_B_.add_tile_offset(
873
+ {Base::kWarpGemmIterations1 * warp_idx_k_1, warp_idx_n_1});
874
+ }
875
+
876
+ /// Construct from tensor references
877
+ CUTLASS_DEVICE
878
+ MmaMultistageFromSharedMemory(
879
+ typename Base::TensorRefA a,
880
+ typename Base::TensorRefB b_tile,
881
+ ///< ID within the threadblock
882
+ int thread_idx,
883
+ ///< ID of warp
884
+ int warp_idx,
885
+ ///< ID of each thread within a warp
886
+ int lane_idx)
887
+ : Base(b_tile, thread_idx, warp_idx, lane_idx),
888
+ warp_tile_iterator_A1_(a, lane_idx),
889
+ smem_iterator_B1_(b_tile, thread_idx),
890
+ prologue_done_(false) {
891
+ // Compute warp location within threadblock tile by mapping the warp_id to
892
+ // three coordinates:
893
+ // _m: the warp's position within the threadblock along the M dimension
894
+ // _n: the warp's position within the threadblock along the N dimension
895
+ // _k: the warp's position within the threadblock along the K dimension
896
+
897
+ int warp_idx_mn_1 =
898
+ warp_idx % (Base::WarpCount1::kM * Base::WarpCount1::kN);
899
+ int warp_idx_k_1 = warp_idx / (Base::WarpCount1::kM * Base::WarpCount1::kN);
900
+
901
+ int warp_idx_m_1 = warp_idx_mn_1 % Base::WarpCount1::kM;
902
+ int warp_idx_n_1 = warp_idx_mn_1 / Base::WarpCount1::kM;
903
+
904
+ // Add per-warp offsets in units of warp-level tiles
905
+ warp_tile_iterator_A1_.add_tile_offset(
906
+ {warp_idx_m_1, Base::kWarpGemmIterations1 * warp_idx_k_1});
907
+ this->warp_tile_iterator_B_.add_tile_offset(
908
+ {Base::kWarpGemmIterations1 * warp_idx_k_1, warp_idx_n_1});
909
+ }
910
+
911
+ CUTLASS_DEVICE
912
+ void set_prologue_done(bool value) {
913
+ prologue_done_ = value;
914
+ }
915
+
916
+ CUTLASS_DEVICE
917
+ static void prologue(
918
+ typename Base::SharedStorage& shared_storage,
919
+ IteratorB iterator_B1,
920
+ int thread_idx,
921
+ int problem_size_0_n) {
922
+ SmemIteratorB1 smem_iterator_B1(shared_storage.operand_B_ref(), thread_idx);
923
+ _prologue(
924
+ iterator_B1,
925
+ (problem_size_0_n + Base::Shape::kK - 1) / Base::Shape::kK,
926
+ smem_iterator_B1);
927
+ }
928
+
929
+ CUTLASS_DEVICE
930
+ void copy_tiles_and_advance_1(
931
+ IteratorB1& iterator_B1,
932
+ int group_start_B1 = 0) {
933
+ iterator_B1.set_iteration_index(
934
+ group_start_B1 * IteratorB1::kAccessesPerVector);
935
+ this->smem_iterator_B1_.set_iteration_index(group_start_B1);
936
+
937
+ // Load for operand B
938
+ CUTLASS_PRAGMA_UNROLL
939
+ for (int j = 0; j < Detail::kAccessesPerGroupB1; ++j) {
940
+ if (group_start_B1 + j < Detail::TBLoadIterationsB1) {
941
+ typename IteratorB1::AccessType* dst_ptr =
942
+ reinterpret_cast<typename IteratorB1::AccessType*>(
943
+ this->smem_iterator_B1_.get());
944
+
945
+ int const kSrcBytes = sizeof_bits<typename IteratorB1::Element>::value *
946
+ IteratorB1::ThreadMap::kElementsPerAccess /
947
+ IteratorB1::kAccessesPerVector / 8;
948
+
949
+ CUTLASS_PRAGMA_UNROLL
950
+ for (int v = 0; v < IteratorB1::kAccessesPerVector; ++v) {
951
+ auto gmem_ptr = iterator_B1.get();
952
+
953
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpB1>(
954
+ dst_ptr + v, gmem_ptr, iterator_B1.valid());
955
+
956
+ ++iterator_B1;
957
+ }
958
+ ++this->smem_iterator_B1_;
959
+ }
960
+ }
961
+ }
962
+
963
+ CUTLASS_DEVICE
964
+ static void _prologue(
965
+ IteratorB& iterator_B1,
966
+ int32_t gemm_k_iterations_1,
967
+ SmemIteratorB1& smem_iterator_B1_) {
968
+ // Issue several complete stages
969
+ CUTLASS_PRAGMA_UNROLL
970
+ for (int stage = 0; stage < kNumStagesConcurrentLoad;
971
+ ++stage, --gemm_k_iterations_1) {
972
+ iterator_B1.set_residual_tile(gemm_k_iterations_1 == 1);
973
+ iterator_B1.clear_mask(gemm_k_iterations_1 == 0);
974
+
975
+ iterator_B1.set_iteration_index(0);
976
+ smem_iterator_B1_.set_iteration_index(0);
977
+
978
+ // Load for operand B
979
+ CUTLASS_PRAGMA_UNROLL
980
+ for (int j = 0; j < Detail::TBLoadIterationsB1; ++j) {
981
+ typename IteratorB1::AccessType* dst_ptr =
982
+ reinterpret_cast<typename IteratorB1::AccessType*>(
983
+ smem_iterator_B1_.get());
984
+
985
+ CUTLASS_PRAGMA_UNROLL
986
+ for (int v = 0; v < IteratorB1::kAccessesPerVector; ++v) {
987
+ int const kSrcBytes =
988
+ sizeof_bits<typename IteratorB1::Element>::value *
989
+ IteratorB1::ThreadMap::kElementsPerAccess /
990
+ IteratorB1::kAccessesPerVector / 8;
991
+
992
+ cutlass::arch::cp_async_zfill<kSrcBytes, kCacheOpB1>(
993
+ dst_ptr + v, iterator_B1.get(), iterator_B1.valid());
994
+
995
+ ++iterator_B1;
996
+ }
997
+
998
+ ++smem_iterator_B1_;
999
+ }
1000
+
1001
+ // Move to the next stage
1002
+ iterator_B1.add_tile_offset({1, 0});
1003
+
1004
+ smem_iterator_B1_.add_tile_offset({1, 0});
1005
+
1006
+ // Defines the boundary of a stage of cp.async.
1007
+ cutlass::arch::cp_async_fence();
1008
+ }
1009
+ iterator_B1.set_residual_tile(gemm_k_iterations_1 == 1);
1010
+ iterator_B1.clear_mask(gemm_k_iterations_1 == 0);
1011
+ }
1012
+
1013
+ /// Perform a threadblock-scoped matrix multiply-accumulate
1014
+ CUTLASS_DEVICE
1015
+ void operator()(
1016
+ ///< problem size of GEMM
1017
+ int gemm_k_iterations_1_,
1018
+ ///< destination accumulator tile
1019
+ FragmentC1& accum,
1020
+ ///< iterator over B1 operand in global memory
1021
+ IteratorB1 iterator_B1,
1022
+ ///< initial value of accumulator
1023
+ FragmentC1 const& src_accum) {
1024
+ // 2nd Gemm
1025
+
1026
+ //
1027
+ // Prologue
1028
+ //
1029
+ // Perform accumulation in the 'd' output operand
1030
+ accum = src_accum;
1031
+
1032
+ if (!prologue_done_) {
1033
+ _prologue(iterator_B1, gemm_k_iterations_1_, smem_iterator_B1_);
1034
+ } else if (!kSmemContainsEntireB) {
1035
+ // Restore the iterators increments
1036
+
1037
+ int gemm_k_iterations_1 = gemm_k_iterations_1_;
1038
+ // Issue several complete stages
1039
+ CUTLASS_PRAGMA_UNROLL
1040
+ for (int stage = 0; stage < kNumStagesConcurrentLoad;
1041
+ ++stage, --gemm_k_iterations_1) {
1042
+ iterator_B1.set_iteration_index(0);
1043
+ this->smem_iterator_B1_.set_iteration_index(0);
1044
+
1045
+ // Load for operand B
1046
+ CUTLASS_PRAGMA_UNROLL
1047
+ for (int j = 0; j < Detail::TBLoadIterationsB1; ++j) {
1048
+ CUTLASS_PRAGMA_UNROLL
1049
+ for (int v = 0; v < IteratorB1::kAccessesPerVector; ++v) {
1050
+ ++iterator_B1;
1051
+ }
1052
+ ++this->smem_iterator_B1_;
1053
+ }
1054
+ iterator_B1.add_tile_offset({1, 0});
1055
+ this->smem_iterator_B1_.add_tile_offset({1, 0});
1056
+ }
1057
+ iterator_B1.set_residual_tile(gemm_k_iterations_1 <= 1);
1058
+ iterator_B1.clear_mask(gemm_k_iterations_1 <= 0);
1059
+ }
1060
+
1061
+ // DEPBAR+SYNC
1062
+ cutlass::arch::cp_async_wait<kNumStagesConcurrentLoad - 1>();
1063
+ __syncthreads();
1064
+
1065
+ // remember that WarpFragmentAScale and WarpIteratorAScale are no-op/empty
1066
+ // if scaling is disabled.
1067
+
1068
+ // Pair of fragments used to overlap shared memory loads and math
1069
+ // instructions
1070
+ WarpLoadedFragmentA1 warp_loaded_frag_A1[2];
1071
+ WarpLoadedFragmentA1Scale warp_loaded_frag_A1_scale[2];
1072
+ WarpLoadedFragmentB1 warp_loaded_frag_B1[2];
1073
+ WarpTransformedFragmentA1 warp_transformed_frag_A1[2];
1074
+ WarpTransformedFragmentB1 warp_transformed_frag_B1[2];
1075
+
1076
+ Operator1 warp_mma1;
1077
+
1078
+ warp_tile_iterator_A1_.load(warp_loaded_frag_A1[0]);
1079
+ ++warp_tile_iterator_A1_;
1080
+
1081
+ warp_tile_iterator_A1_scale_.load(warp_loaded_frag_A1_scale[0]);
1082
+ ++warp_tile_iterator_A1_scale_;
1083
+
1084
+ this->warp_tile_iterator_B_.set_kgroup_index(0);
1085
+ this->warp_tile_iterator_B_.load(warp_loaded_frag_B1[0]);
1086
+ ++this->warp_tile_iterator_B_;
1087
+
1088
+ int smem_write_stage_idx = Base::kStages - 1;
1089
+ int smem_read_stage_idx = 0;
1090
+
1091
+ warp_mma1.transform(
1092
+ warp_transformed_frag_A1[0],
1093
+ warp_transformed_frag_B1[0],
1094
+ FragmentAScaler::apply(
1095
+ warp_loaded_frag_A1[0], warp_loaded_frag_A1_scale[0]),
1096
+ warp_loaded_frag_B1[0]);
1097
+
1098
+ // tf32x3 kernels use staging accumulation. warp_mma uses a temporary
1099
+ // accumulator and this temporary accumulator is added to the final
1100
+ // accumulator once in every mainloop iteration.
1101
+ plus<FragmentC1> plus_accum;
1102
+
1103
+ FragmentC1 tmp_accum;
1104
+
1105
+ if (platform::is_same<
1106
+ typename Operator1::MathOperator,
1107
+ arch::OpMultiplyAddFastF32>::value ||
1108
+ platform::is_same<
1109
+ typename Operator1::MathOperator,
1110
+ arch::OpMultiplyAddComplexFastF32>::value) {
1111
+ tmp_accum.clear();
1112
+ }
1113
+
1114
+ //
1115
+ // Mainloop
1116
+ //
1117
+
1118
+ CUTLASS_PRAGMA_UNROLL
1119
+ for (int gemm_k_iterations_1 = gemm_k_iterations_1_ - (Base::kStages - 1);
1120
+ gemm_k_iterations_1 > (-Base::kStages + 1);
1121
+ gemm_k_iterations_1--) {
1122
+ //
1123
+ // Loop over GEMM K dimension
1124
+ //
1125
+
1126
+ // Computes a warp-level GEMM on data held in shared memory
1127
+ // Each "warp_mma_k" refers to a warp-level matrix multiply-accumulate
1128
+ CUTLASS_PRAGMA_UNROLL
1129
+ for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations1;
1130
+ ++warp_mma_k) {
1131
+ // Load warp-level tile from accumulator fragment (A)
1132
+ // or shared memory (operand B)
1133
+ this->warp_tile_iterator_B_.set_kgroup_index(
1134
+ (warp_mma_k + 1) % Base::kWarpGemmIterations1);
1135
+ // skip warp tile loading for the last kgroup (we are out of the buf)
1136
+ if (gemm_k_iterations_1 > (-Base::kStages + 2) ||
1137
+ warp_mma_k < Base::kWarpGemmIterations1 - 1) {
1138
+ warp_tile_iterator_A1_.load(
1139
+ warp_loaded_frag_A1[(warp_mma_k + 1) % 2]);
1140
+ warp_tile_iterator_A1_scale_.load(
1141
+ warp_loaded_frag_A1_scale[(warp_mma_k + 1) % 2]);
1142
+ this->warp_tile_iterator_B_.load(
1143
+ warp_loaded_frag_B1[(warp_mma_k + 1) % 2]);
1144
+ }
1145
+ ++warp_tile_iterator_A1_;
1146
+ ++warp_tile_iterator_A1_scale_;
1147
+ ++this->warp_tile_iterator_B_;
1148
+
1149
+ if (warp_mma_k > 0)
1150
+ warp_mma1.transform(
1151
+ warp_transformed_frag_A1[warp_mma_k % 2],
1152
+ warp_transformed_frag_B1[warp_mma_k % 2],
1153
+ FragmentAScaler::apply(
1154
+ warp_loaded_frag_A1[warp_mma_k % 2],
1155
+ warp_loaded_frag_A1_scale[warp_mma_k % 2]),
1156
+ warp_loaded_frag_B1[warp_mma_k % 2]);
1157
+
1158
+ if (platform::is_same<
1159
+ typename Operator1::MathOperator,
1160
+ arch::OpMultiplyAddFastF32>::value ||
1161
+ platform::is_same<
1162
+ typename Operator1::MathOperator,
1163
+ arch::OpMultiplyAddComplexFastF32>::value) {
1164
+ warp_mma1(
1165
+ tmp_accum,
1166
+ warp_transformed_frag_A1[warp_mma_k % 2],
1167
+ warp_transformed_frag_B1[warp_mma_k % 2],
1168
+ tmp_accum);
1169
+
1170
+ if (warp_mma_k == 0) {
1171
+ accum = plus_accum(accum, tmp_accum);
1172
+ tmp_accum.clear();
1173
+ }
1174
+ } else {
1175
+ warp_mma1(
1176
+ accum,
1177
+ warp_transformed_frag_A1[warp_mma_k % 2],
1178
+ warp_transformed_frag_B1[warp_mma_k % 2],
1179
+ accum);
1180
+ }
1181
+
1182
+ // Issue global->shared copies for the this stage
1183
+ if (warp_mma_k < Base::kWarpGemmIterations1 - 1) {
1184
+ int group_start_iteration_B1;
1185
+
1186
+ group_start_iteration_B1 = warp_mma_k * Detail::kAccessesPerGroupB1;
1187
+
1188
+ if (!kSmemContainsEntireB) {
1189
+ copy_tiles_and_advance_1(iterator_B1, group_start_iteration_B1);
1190
+ }
1191
+ }
1192
+
1193
+ if (warp_mma_k + 2 == Base::kWarpGemmIterations1) {
1194
+ int group_start_iteration_B1;
1195
+ group_start_iteration_B1 =
1196
+ (warp_mma_k + 1) * Detail::kAccessesPerGroupB1;
1197
+
1198
+ if (!kSmemContainsEntireB) {
1199
+ copy_tiles_and_advance_1(iterator_B1, group_start_iteration_B1);
1200
+ }
1201
+
1202
+ // Inserts a memory fence between stages of cp.async instructions.
1203
+ cutlass::arch::cp_async_fence();
1204
+
1205
+ // Waits until kStages-2 stages have committed.
1206
+ arch::cp_async_wait<kNumStagesConcurrentLoad - 1>();
1207
+ __syncthreads();
1208
+
1209
+ // Move to the next stage
1210
+ iterator_B1.add_tile_offset({1, 0});
1211
+
1212
+ this->smem_iterator_B1_.add_tile_offset({1, 0});
1213
+
1214
+ // Add negative offsets to return iterators to the 'start' of the
1215
+ // circular buffer in shared memory
1216
+ if (!kSmemContainsEntireB) {
1217
+ if (smem_write_stage_idx == (Base::kStages - 1)) {
1218
+ this->smem_iterator_B1_.add_tile_offset({-Base::kStages, 0});
1219
+ smem_write_stage_idx = 0;
1220
+ } else {
1221
+ ++smem_write_stage_idx;
1222
+ }
1223
+
1224
+ if (smem_read_stage_idx == (Base::kStages - 1)) {
1225
+ this->warp_tile_iterator_B_.add_tile_offset(
1226
+ {-Base::kStages * Policy1::kPartitionsK *
1227
+ Base::kWarpGemmIterations1,
1228
+ 0});
1229
+ smem_read_stage_idx = 0;
1230
+ } else {
1231
+ ++smem_read_stage_idx;
1232
+ }
1233
+ }
1234
+
1235
+ iterator_B1.set_residual_tile(gemm_k_iterations_1 == 2);
1236
+ iterator_B1.clear_mask(gemm_k_iterations_1 == 1);
1237
+ }
1238
+
1239
+ // Do any conversions feeding the first stage at the end of the loop so
1240
+ // we can start right away on mma instructions
1241
+ if (warp_mma_k + 1 == Base::kWarpGemmIterations1)
1242
+ warp_mma1.transform(
1243
+ warp_transformed_frag_A1[(warp_mma_k + 1) % 2],
1244
+ warp_transformed_frag_B1[(warp_mma_k + 1) % 2],
1245
+ FragmentAScaler::apply(
1246
+ warp_loaded_frag_A1[(warp_mma_k + 1) % 2],
1247
+ warp_loaded_frag_A1_scale[(warp_mma_k + 1) % 2]),
1248
+ warp_loaded_frag_B1[(warp_mma_k + 1) % 2]);
1249
+ }
1250
+ }
1251
+
1252
+ if (platform::is_same<
1253
+ typename Operator1::MathOperator,
1254
+ arch::OpMultiplyAddFastF32>::value ||
1255
+ platform::is_same<
1256
+ typename Operator1::MathOperator,
1257
+ arch::OpMultiplyAddComplexFastF32>::value) {
1258
+ accum = plus_accum(accum, tmp_accum);
1259
+ }
1260
+ }
1261
+ };
1262
+
1263
+ // Converts a "regular" Mma into their counterpart from shared memory
1264
+ template <
1265
+ typename Mma_,
1266
+ int kMaxK,
1267
+ typename WarpIteratorA_,
1268
+ /// whether or not to apply elementwise multiplication of operand A by
1269
+ /// another matrix in shared memory before usage in A @ B
1270
+ bool kScaleOperandA,
1271
+ bool kTransposeA = false>
1272
+ struct DefaultMmaFromSharedMemory;
1273
+
1274
+ // Mma pipelined
1275
+ template <
1276
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
1277
+ typename Shape_,
1278
+ /// Iterates over tiles of A operand in global memory
1279
+ // (concept: ReadableTileIterator | ForwardTileIterator |
1280
+ // MaskedTileIterator)
1281
+ typename IteratorA_,
1282
+ /// Iterates over tiles of A operand in shared memory
1283
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
1284
+ typename SmemIteratorA_,
1285
+ typename WarpIteratorA_,
1286
+ /// Iterates over tiles of B operand in global memory
1287
+ // (concept: ReadableTileIterator | ForwardTileIterator |
1288
+ // MaskedTileIterator)
1289
+ typename IteratorB_,
1290
+ /// Iterates over tiles of B operand in shared memory
1291
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
1292
+ typename SmemIteratorB_,
1293
+ /// Data type of accumulator matrix
1294
+ typename ElementC_,
1295
+ /// Data type of accumulator matrix
1296
+ typename LayoutC_,
1297
+ /// Policy describing tuning details (concept: MmaPolicy)
1298
+ typename Policy_,
1299
+ /// Transformation applied to A operand
1300
+ typename TransformA_,
1301
+ /// Transformation applied to B operand
1302
+ typename TransformB_,
1303
+ // Max MMA problem size K
1304
+ int kMaxK,
1305
+ /// whether or not to apply elementwise multiplication of operand A by
1306
+ /// another matrix in shared memory before usage in A @ B
1307
+ bool kScaleOperandA,
1308
+ bool kTransposeA>
1309
+ struct DefaultMmaFromSharedMemory<
1310
+ MmaPipelined<
1311
+ Shape_,
1312
+ IteratorA_,
1313
+ SmemIteratorA_,
1314
+ IteratorB_,
1315
+ SmemIteratorB_,
1316
+ ElementC_,
1317
+ LayoutC_,
1318
+ Policy_,
1319
+ TransformA_,
1320
+ TransformB_>,
1321
+ kMaxK,
1322
+ WarpIteratorA_,
1323
+ kScaleOperandA,
1324
+ kTransposeA> {
1325
+ using RegularMma = MmaPipelined<
1326
+ Shape_,
1327
+ IteratorA_,
1328
+ SmemIteratorA_,
1329
+ IteratorB_,
1330
+ SmemIteratorB_,
1331
+ ElementC_,
1332
+ LayoutC_,
1333
+ Policy_,
1334
+ TransformA_,
1335
+ TransformB_>;
1336
+
1337
+ using WarpShape = typename Policy_::Operator::Shape;
1338
+ using InstructionShape = typename Policy_::Operator::InstructionShape;
1339
+ using ArchMmaOperator = typename Policy_::Operator;
1340
+
1341
+ static constexpr bool kIsTransposedA = false;
1342
+ using WarpIteratorA = WarpIteratorA_;
1343
+ using IteratorB =
1344
+ typename cutlass::transform::threadblock::MakeIteratorResidualLast<
1345
+ IteratorB_>::Iterator;
1346
+
1347
+ using Mma = typename cutlass::gemm::threadblock::MmaPipelinedFromSharedMemory<
1348
+ Shape_,
1349
+ WarpIteratorA,
1350
+ kScaleOperandA,
1351
+ kMaxK,
1352
+ IteratorB,
1353
+ SmemIteratorB_,
1354
+ ElementC_,
1355
+ LayoutC_,
1356
+ Policy_>;
1357
+ };
1358
+
1359
+ template <
1360
+ /// Size of the Gemm problem - concept: gemm::GemmShape<>
1361
+ typename Shape_,
1362
+ /// Iterates over tiles of A operand in global memory
1363
+ // (concept: ReadableTileIterator | ForwardTileIterator |
1364
+ // MaskedTileIterator)
1365
+ typename IteratorA_,
1366
+ /// Iterates over tiles of A operand in shared memory
1367
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
1368
+ typename SmemIteratorA_,
1369
+ typename WarpIteratorA_,
1370
+ /// Cache operation for operand A
1371
+ cutlass::arch::CacheOperation::Kind CacheOpA,
1372
+ /// Iterates over tiles of B operand in global memory
1373
+ // (concept: ReadableTileIterator | ForwardTileIterator |
1374
+ // MaskedTileIterator)
1375
+ typename IteratorB_,
1376
+ /// Iterates over tiles of B operand in shared memory
1377
+ /// (concept: WriteableTileIterator | RandomAccessTileIterator)
1378
+ typename SmemIteratorB_,
1379
+ /// Cache operation for operand B
1380
+ cutlass::arch::CacheOperation::Kind CacheOpB,
1381
+ /// Data type of accumulator matrix
1382
+ typename ElementC_,
1383
+ /// Data type of accumulator matrix
1384
+ typename LayoutC_,
1385
+ /// Policy describing tuning details (concept: MmaPolicy)
1386
+ typename Policy_,
1387
+ /// Number of stages,
1388
+ int Stages,
1389
+ /// Use zfill or predicate for out-of-bound cp.async
1390
+ SharedMemoryClearOption SharedMemoryClear,
1391
+ int kMaxK,
1392
+ /// whether or not to apply elementwise multiplication of operand A by
1393
+ /// another matrix in shared memory before usage in A @ B
1394
+ bool kScaleOperandA,
1395
+ bool kTransposeA>
1396
+ struct DefaultMmaFromSharedMemory<
1397
+ MmaMultistage<
1398
+ Shape_,
1399
+ IteratorA_,
1400
+ SmemIteratorA_,
1401
+ CacheOpA,
1402
+ IteratorB_,
1403
+ SmemIteratorB_,
1404
+ CacheOpB,
1405
+ ElementC_,
1406
+ LayoutC_,
1407
+ Policy_,
1408
+ Stages,
1409
+ SharedMemoryClear>,
1410
+ kMaxK,
1411
+ WarpIteratorA_,
1412
+ kScaleOperandA,
1413
+ kTransposeA> {
1414
+ using RegularMma = MmaMultistage<
1415
+ Shape_,
1416
+ IteratorA_,
1417
+ SmemIteratorA_,
1418
+ CacheOpA,
1419
+ IteratorB_,
1420
+ SmemIteratorB_,
1421
+ CacheOpB,
1422
+ ElementC_,
1423
+ LayoutC_,
1424
+ Policy_,
1425
+ Stages,
1426
+ SharedMemoryClear>;
1427
+
1428
+ using WarpShape = typename Policy_::Operator::Shape;
1429
+ using InstructionShape = typename Policy_::Operator::InstructionShape;
1430
+ using WarpIteratorTranspose = TransposeWarpIterator<WarpIteratorA_>;
1431
+ static constexpr bool kIsTransposedA =
1432
+ WarpIteratorTranspose::kSupportsTranspose && kTransposeA;
1433
+ using WarpIteratorA = typename platform::conditional<
1434
+ kIsTransposedA,
1435
+ typename WarpIteratorTranspose::Iterator,
1436
+ WarpIteratorA_>::type;
1437
+
1438
+ // Reduce the number of stages if we don't need that many
1439
+ static int constexpr kStagesMax =
1440
+ (kMaxK + int(Shape_::kK) - 1) / int(Shape_::kK);
1441
+ static int constexpr kStages = cutlass::const_min(Stages, kStagesMax);
1442
+
1443
+ using IteratorB =
1444
+ typename cutlass::transform::threadblock::MakeIteratorResidualLast<
1445
+ IteratorB_>::Iterator;
1446
+ using Mma =
1447
+ typename cutlass::gemm::threadblock::MmaMultistageFromSharedMemory<
1448
+ Shape_,
1449
+ WarpIteratorA,
1450
+ kScaleOperandA,
1451
+ IteratorB,
1452
+ SmemIteratorB_,
1453
+ RegularMma::kCacheOpB,
1454
+ ElementC_,
1455
+ LayoutC_,
1456
+ Policy_,
1457
+ kStages,
1458
+ kMaxK>;
1459
+ };
1460
+
1461
+ /////////////////////////////////////////////////////////////////////////////////////////////////
1462
+
1463
+ template <
1464
+ typename IteratorC,
1465
+ typename Operator,
1466
+ typename scalar_t,
1467
+ typename WarpShape_,
1468
+ typename ThreadblockShape_>
1469
+ struct B2bGemm;
1470
+
1471
+ // Tensor Cores >= Sm75 specialization (Ampere ...)
1472
+ template < /// Size of the matrix to load (concept: MatrixShape)
1473
+ typename Shape_,
1474
+ /// Element type
1475
+ typename Element_,
1476
+ /// Layout of operand in memory
1477
+ typename Layout_,
1478
+ /// Shape of one matrix product operation (concept: MatrixShape)
1479
+ typename InstructionShape_,
1480
+ /// Interval between adjacent *MMA instructions (in units of MMA
1481
+ /// instructions, concept: MatrixShape)
1482
+ typename OpDelta_,
1483
+ typename Operator,
1484
+ typename scalar_t,
1485
+ typename WarpShape_,
1486
+ typename ThreadblockShape_>
1487
+ struct B2bGemm<
1488
+ cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator<
1489
+ Shape_,
1490
+ Element_,
1491
+ Layout_,
1492
+ InstructionShape_,
1493
+ OpDelta_>,
1494
+ Operator,
1495
+ scalar_t,
1496
+ WarpShape_,
1497
+ ThreadblockShape_> {
1498
+ using IteratorC =
1499
+ typename cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator<
1500
+ Shape_,
1501
+ Element_,
1502
+ Layout_,
1503
+ InstructionShape_,
1504
+ OpDelta_>;
1505
+ using FragmentC = typename IteratorC::Fragment;
1506
+ using InstructionShape = InstructionShape_;
1507
+ using WarpShape = WarpShape_;
1508
+ using ThreadblockShape = ThreadblockShape_;
1509
+ using accum_t = Element_;
1510
+ using lse_scalar_t = float;
1511
+
1512
+ using SmemAccumulatorLayout = cutlass::layout::RowMajor;
1513
+
1514
+ // Iterator to load accumulators (results of matmul in registers)
1515
+ using FragmentIteratorAccumulator =
1516
+ cutlass::epilogue::warp::FragmentIteratorTensorOp<
1517
+ WarpShape,
1518
+ InstructionShape,
1519
+ accum_t,
1520
+ typename Operator::Policy::Operator::FragmentC,
1521
+ cutlass::layout::RowMajor>;
1522
+
1523
+ // Iterator to store to shared-memory
1524
+ using SmemIteratorD0 = typename cutlass::epilogue::warp::TileIteratorTensorOp<
1525
+ WarpShape,
1526
+ InstructionShape,
1527
+ scalar_t, // accum_t,
1528
+ SmemAccumulatorLayout>;
1529
+ using AccumulatorSharedStorage =
1530
+ cutlass::gemm::threadblock::AccumulatorSharedStorage<
1531
+ ThreadblockShape,
1532
+ typename SmemIteratorD0::Element,
1533
+ typename SmemIteratorD0::TensorLayout,
1534
+ typename SmemIteratorD0::Padding>;
1535
+ // We need to provide an operation for the epilogue. Let's create an
1536
+ // operation that does nothing (ScaleType::Nothing), just converts
1537
+ // from accum_t (float) -> scalar_t (can be half)
1538
+ using OutputOpNoOp = cutlass::epilogue::thread::LinearCombination<
1539
+ typename SmemIteratorD0::Element, // ElementOutput
1540
+ FragmentIteratorAccumulator::Fragment::kElements,
1541
+ accum_t, // ElementAccumulator
1542
+ typename SmemIteratorD0::Element, // ElementCompute
1543
+ cutlass::epilogue::thread::ScaleType::Nothing>;
1544
+ using Epilogue = cutlass::epilogue::threadblock::EpilogueSmemAccumulator<
1545
+ SmemIteratorD0,
1546
+ FragmentIteratorAccumulator,
1547
+ SmemIteratorD0, // ScaleBiasIterator - not used
1548
+ OutputOpNoOp>;
1549
+
1550
+ // Epilogue 2: with LSE (for backwards pass)
1551
+ static int const kElementsPerAccess = 2; // TODO: Why 2?
1552
+ using IteratorAccumulatorLSE =
1553
+ cutlass::transform::threadblock::VectorIterator<
1554
+ cutlass::transform::threadblock::PredicatedVectorAccessIterator<
1555
+ // Shape
1556
+ cutlass::MatrixShape<ThreadblockShape::kM, ThreadblockShape::kN>,
1557
+ // WarpShape
1558
+ cutlass::MatrixShape<WarpShape::kM, WarpShape::kN>,
1559
+ lse_scalar_t,
1560
+ cutlass::layout::RowMajor,
1561
+ kElementsPerAccess>>;
1562
+ using EpilogueOpApplyLSE = cutlass::epilogue::thread::ApplyLogSumExp<
1563
+ scalar_t, // ElementOutput_
1564
+ lse_scalar_t, // ElementLSE_
1565
+ accum_t, // ElementAccumulator_
1566
+ accum_t, // ElementCompute_
1567
+ 128 / cutlass::sizeof_bits<scalar_t>::value
1568
+ // FragmentIteratorAccumulator::Fragment::kElements
1569
+ // InstructionShape::kM * InstructionShape::kN / 32
1570
+ >;
1571
+ using EpilogueWithLSE =
1572
+ cutlass::epilogue::threadblock::EpilogueSmemAccumulator<
1573
+ SmemIteratorD0,
1574
+ FragmentIteratorAccumulator,
1575
+ IteratorAccumulatorLSE,
1576
+ EpilogueOpApplyLSE>;
1577
+
1578
+ static void CUTLASS_DEVICE accumToSmem(
1579
+ AccumulatorSharedStorage& shared_storage,
1580
+ FragmentC const& accum,
1581
+ int lane_id,
1582
+ cutlass::MatrixCoord const& tile_coords) {
1583
+ SmemIteratorD0 smem_iterator_attn(shared_storage.accum_ref(), lane_id);
1584
+ smem_iterator_attn.add_tile_offset(
1585
+ tile_coords *
1586
+ cutlass::MatrixCoord{
1587
+ SmemIteratorD0::TileIterations::kRow,
1588
+ SmemIteratorD0::TileIterations::kColumn});
1589
+ Epilogue epilogue;
1590
+ epilogue(OutputOpNoOp({}), smem_iterator_attn, accum);
1591
+ }
1592
+
1593
+ static void CUTLASS_DEVICE accumApplyLSEToSmem(
1594
+ AccumulatorSharedStorage& shared_storage,
1595
+ FragmentC& accum,
1596
+ lse_scalar_t const* lse,
1597
+ int32_t lse_extents,
1598
+ int thread_id,
1599
+ int warp_id,
1600
+ int lane_id,
1601
+ cutlass::MatrixCoord const& tile_coords) {
1602
+ constexpr int32_t kAlignLSE = 32;
1603
+ IteratorAccumulatorLSE iterator_lse(
1604
+ lse,
1605
+ {(int32_t)0, (int32_t)ceil_div(lse_extents, kAlignLSE) * kAlignLSE},
1606
+ thread_id,
1607
+ warp_id,
1608
+ cutlass::MatrixCoord{0, 0} // offset
1609
+ );
1610
+
1611
+ SmemIteratorD0 smem_iterator_attn(shared_storage.accum_ref(), lane_id);
1612
+ smem_iterator_attn.add_tile_offset(
1613
+ tile_coords *
1614
+ cutlass::MatrixCoord{
1615
+ SmemIteratorD0::TileIterations::kRow,
1616
+ SmemIteratorD0::TileIterations::kColumn});
1617
+ EpilogueWithLSE epilogue;
1618
+ EpilogueOpApplyLSE minus_lse_exp({});
1619
+ epilogue(
1620
+ minus_lse_exp,
1621
+ smem_iterator_attn,
1622
+ accum,
1623
+ // scale - unused
1624
+ iterator_lse,
1625
+ // bias
1626
+ iterator_lse);
1627
+ }
1628
+ };
1629
+
1630
+ // Volta Specialization
1631
+ // only supported for f16
1632
+ template <typename Operator, typename WarpShape_, typename ThreadblockShape_>
1633
+ struct B2bGemm<
1634
+ cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator<
1635
+ cutlass::MatrixShape<32, 32>,
1636
+ float,
1637
+ cutlass::layout::RowMajor,
1638
+ cutlass::gemm::GemmShape<16, 16, 4>,
1639
+ cutlass::MatrixShape<1, 1>>,
1640
+ Operator,
1641
+ cutlass::half_t,
1642
+ WarpShape_,
1643
+ ThreadblockShape_> {
1644
+ using IteratorC =
1645
+ cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator<
1646
+ cutlass::MatrixShape<32, 32>,
1647
+ float,
1648
+ cutlass::layout::RowMajor,
1649
+ cutlass::gemm::GemmShape<16, 16, 4>,
1650
+ cutlass::MatrixShape<1, 1>>;
1651
+ using scalar_t = cutlass::half_t;
1652
+ using accum_t = IteratorC::Element;
1653
+ using WarpShape = WarpShape_;
1654
+ using ThreadblockShape = ThreadblockShape_;
1655
+ using FragmentC = IteratorC::Fragment;
1656
+ using lse_scalar_t = float;
1657
+
1658
+ // Storage in shared-memory for Q.Kt
1659
+ using SmemAccumulatorLayout =
1660
+ cutlass::layout::RowMajorVoltaTensorOpMultiplicandCrosswise<16, 32>;
1661
+ using AccumulatorSharedStorage =
1662
+ cutlass::gemm::threadblock::AccumulatorSharedStorage<
1663
+ ThreadblockShape,
1664
+ scalar_t,
1665
+ SmemAccumulatorLayout,
1666
+ cutlass::MatrixShape<0, 0> // Padding
1667
+ >;
1668
+ using TensorRef = cutlass::TensorRef<scalar_t, SmemAccumulatorLayout>;
1669
+ using Policy = typename IteratorC::Policy;
1670
+ using Element = accum_t;
1671
+ // Those are MmaVoltaTensorOpAccumulatorTileIterator private fields
1672
+ // Let's copy their values
1673
+ static int const kElementsPerPartial = 4;
1674
+ using EleShapePerPatial = typename cutlass::platform::conditional<
1675
+ cutlass::platform::is_same<Element, float>::value,
1676
+ cutlass::MatrixShape<2, 2>,
1677
+ cutlass::MatrixShape<1, 4>>::type;
1678
+ static int const kElementsPerMma = 8;
1679
+ static int const kAccumulatorPatials = 2;
1680
+ using QuadShapePerPatialMma = cutlass::MatrixShape<4, 4>;
1681
+
1682
+ static void CUTLASS_DEVICE accumToSmem(
1683
+ AccumulatorSharedStorage& shared_storage,
1684
+ FragmentC const& accum,
1685
+ int lane_id,
1686
+ cutlass::MatrixCoord const& tile_coords) {
1687
+ // ctor - from MmaVoltaTensorOpAccumulatorTileIterator
1688
+ TensorRef ref_(shared_storage.accum_ref());
1689
+ int quad = (lane_id >> 2);
1690
+ int lane_in_quad = (lane_id & 3);
1691
+ int accum_m, accum_n;
1692
+
1693
+ if (cutlass::platform::is_same<Element, float>::value) {
1694
+ // (quad[2],quad[0])+lane_in_quad[0]
1695
+ accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 + (lane_in_quad & 1);
1696
+ // (quad[1])+lane_in_quad[1]
1697
+ accum_n =
1698
+ ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials +
1699
+ (lane_in_quad & 2);
1700
+ } else {
1701
+ accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 +
1702
+ lane_in_quad; // (quad[2],quad[0])
1703
+ accum_n = ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials;
1704
+ }
1705
+ cutlass::MatrixCoord lane_offset(accum_m, accum_n);
1706
+
1707
+ // Tile offset
1708
+ ref_.add_coord_offset(
1709
+ tile_coords *
1710
+ cutlass::MatrixCoord(
1711
+ {IteratorC::Shape::kRow, IteratorC::Shape::kColumn}));
1712
+
1713
+ using AccessType = cutlass::Array<scalar_t, EleShapePerPatial::kColumn>;
1714
+
1715
+ // store - from MmaVoltaTensorOpAccumulatorTileIterator
1716
+ CUTLASS_PRAGMA_UNROLL
1717
+ for (int tile_n = 0; tile_n < Policy::TileIterations::kColumn; ++tile_n) {
1718
+ CUTLASS_PRAGMA_UNROLL
1719
+ for (int tile_m = 0; tile_m < Policy::TileIterations::kRow; ++tile_m) {
1720
+ CUTLASS_PRAGMA_UNROLL
1721
+ for (int mma_n = 0; mma_n < Policy::MmaIterations::kColumn; ++mma_n) {
1722
+ CUTLASS_PRAGMA_UNROLL
1723
+ for (int mma_m = 0; mma_m < Policy::MmaIterations::kRow; ++mma_m) {
1724
+ int mma_accum_start =
1725
+ (((tile_n * Policy::TileIterations::kRow + tile_m) *
1726
+ Policy::MmaIterations::kColumn +
1727
+ mma_n) *
1728
+ Policy::MmaIterations::kRow +
1729
+ mma_m) *
1730
+ kElementsPerMma;
1731
+
1732
+ CUTLASS_PRAGMA_UNROLL
1733
+ for (int p = 0; p < kAccumulatorPatials; ++p) {
1734
+ CUTLASS_PRAGMA_UNROLL
1735
+ for (int m = 0; m < EleShapePerPatial::kRow; ++m) {
1736
+ int accum_m = tile_m * Policy::InterleavedTile::kRow +
1737
+ mma_m * QuadShapePerPatialMma::kRow + m * 2;
1738
+ int accum_n = tile_n * Policy::InterleavedTile::kColumn +
1739
+ mma_n * QuadShapePerPatialMma::kColumn +
1740
+ p * Policy::InterleavedTile::kColumn / 2;
1741
+ int r = (accum_m + lane_offset.row());
1742
+ AccessType to_store;
1743
+ CUTLASS_PRAGMA_UNROLL
1744
+ for (int n = 0; n < EleShapePerPatial::kColumn; ++n) {
1745
+ int idx = mma_accum_start + p * kElementsPerPartial +
1746
+ m * EleShapePerPatial::kColumn + n;
1747
+ int c = (accum_n + n + lane_offset.column());
1748
+ to_store[n] = scalar_t(accum[idx]);
1749
+ }
1750
+ int c = (accum_n + lane_offset.column());
1751
+ assert(r < 32);
1752
+ assert(c < 32);
1753
+ *reinterpret_cast<AccessType*>(
1754
+ ref_.data() + ref_.offset({r, c})) = to_store;
1755
+ }
1756
+ }
1757
+ }
1758
+ }
1759
+ }
1760
+ }
1761
+ }
1762
+
1763
+ static void CUTLASS_DEVICE accumApplyLSEToSmem(
1764
+ AccumulatorSharedStorage& shared_storage,
1765
+ typename IteratorC::Fragment& accum,
1766
+ lse_scalar_t const* lse,
1767
+ int lse_extent,
1768
+ int thread_id,
1769
+ int warp_id,
1770
+ int lane_id,
1771
+ cutlass::MatrixCoord const& tile_coords) {
1772
+ // Non-optimized way to apply LSE to registers
1773
+ // NOTE: accum is attn.T
1774
+ // TODO: Optimize for each architecture
1775
+ static constexpr int WarpSize = 32;
1776
+ using AccumLambdaIterator =
1777
+ typename DefaultMmaAccumLambdaIterator<IteratorC, accum_t, WarpSize>::
1778
+ Iterator;
1779
+ auto lane_offset =
1780
+ AccumLambdaIterator::get_lane_offset(lane_id, warp_id, tile_coords);
1781
+
1782
+ cutlass::Array<lse_scalar_t, IteratorC::Fragment::kElements> lse_prefetched;
1783
+ lse_prefetched.clear();
1784
+ int rowIdx = 0;
1785
+ int colIdx = 0;
1786
+ AccumLambdaIterator::iterateRows(
1787
+ lane_offset,
1788
+ [&](int accum_m) {
1789
+ ++rowIdx;
1790
+ colIdx = 0;
1791
+ },
1792
+ [&](int accum_m, int accum_n, int idx) {
1793
+ if (rowIdx == 1) {
1794
+ lse_prefetched[colIdx] = accum_n < lse_extent
1795
+ ? lse[accum_n]
1796
+ : platform::numeric_limits<accum_t>::infinity();
1797
+ }
1798
+ accum[idx] = expf(accum[idx] - lse_prefetched[colIdx]);
1799
+ ++colIdx;
1800
+ },
1801
+ [&](int accum_m) {});
1802
+ accumToSmem(shared_storage, accum, lane_id, tile_coords);
1803
+ }
1804
+ };
1805
+
1806
+ // Simt Specialization
1807
+ // for f32 on Sm70-Sm75 and f16/f32 below
1808
+
1809
+ template <
1810
+ typename Operator,
1811
+ typename OperatorPolicy,
1812
+ typename scalar_t,
1813
+ typename WarpShape_,
1814
+ typename ThreadblockShape_>
1815
+ struct B2bGemm<
1816
+ cutlass::gemm::warp::MmaSimtTileIterator<
1817
+ cutlass::MatrixShape<32, 32>,
1818
+ cutlass::gemm::Operand::kC,
1819
+ float,
1820
+ cutlass::layout::RowMajor,
1821
+ OperatorPolicy,
1822
+ 1,
1823
+ 1>,
1824
+ Operator,
1825
+ scalar_t,
1826
+ WarpShape_,
1827
+ ThreadblockShape_> {
1828
+ using IteratorC = cutlass::gemm::warp::MmaSimtTileIterator<
1829
+ cutlass::MatrixShape<32, 32>,
1830
+ cutlass::gemm::Operand::kC,
1831
+ float,
1832
+ cutlass::layout::RowMajor,
1833
+ OperatorPolicy,
1834
+ 1,
1835
+ 1>;
1836
+ using accum_t = typename IteratorC::Element;
1837
+ using WarpShape = WarpShape_;
1838
+ using ThreadblockShape = ThreadblockShape_;
1839
+ using FragmentC = typename IteratorC::Fragment;
1840
+ using lse_scalar_t = float;
1841
+
1842
+ // Storage in shared-memory for Q.Kt
1843
+ using AccumulatorSharedStorage =
1844
+ cutlass::gemm::threadblock::AccumulatorSharedStorage<
1845
+ ThreadblockShape,
1846
+ scalar_t,
1847
+ cutlass::layout::ColumnMajor,
1848
+ cutlass::MatrixShape<0, 0> // Padding
1849
+ >;
1850
+
1851
+ static void CUTLASS_DEVICE accumToSmem(
1852
+ AccumulatorSharedStorage& shared_storage,
1853
+ FragmentC const& accum,
1854
+ int lane_id,
1855
+ cutlass::MatrixCoord const& tile_coords) {
1856
+ using Policy = typename IteratorC::Policy;
1857
+ using Element = typename IteratorC::Element;
1858
+ using Iterations = typename IteratorC::Iterations;
1859
+ using Delta = typename IteratorC::Delta;
1860
+
1861
+ auto ref_ = shared_storage.accum_ref();
1862
+ // ctor - MmaSimtTileIterator
1863
+ // compute offset based on thread ID and lane layout
1864
+ typename Policy::LaneLayout lane_layout = Policy::get_lane_layout();
1865
+
1866
+ MatrixCoord lane_offset = lane_layout.inverse(lane_id) *
1867
+ MatrixCoord(Policy::LaneMmaShape::kM, Policy::LaneMmaShape::kN);
1868
+
1869
+ ref_.add_coord_offset(lane_offset);
1870
+
1871
+ // Tile offset
1872
+ ref_.add_coord_offset(
1873
+ tile_coords *
1874
+ cutlass::MatrixCoord(
1875
+ {IteratorC::Shape::kRow, IteratorC::Shape::kColumn}));
1876
+
1877
+ // store - MmaSimtTileIterator
1878
+ CUTLASS_PRAGMA_UNROLL
1879
+ for (int mma_n = 0; mma_n < Iterations::kColumn; ++mma_n) {
1880
+ CUTLASS_PRAGMA_UNROLL
1881
+ for (int n = 0; n < Policy::LaneMmaShape::kN; ++n) {
1882
+ CUTLASS_PRAGMA_UNROLL
1883
+ for (int mma_m = 0; mma_m < Iterations::kRow; ++mma_m) {
1884
+ CUTLASS_PRAGMA_UNROLL
1885
+ for (int m = 0; m < Policy::LaneMmaShape::kM; ++m) {
1886
+ int r =
1887
+ Policy::LaneMmaShape::kM * (mma_m * Policy::WarpShape::kRow) +
1888
+ m;
1889
+ int c = mma_n * Delta::kColumn + n;
1890
+ int idx = n +
1891
+ Policy::LaneMmaShape::kN *
1892
+ (mma_n +
1893
+ Iterations::kColumn *
1894
+ (m + mma_m * Policy::LaneMmaShape::kM));
1895
+ ref_.at({r, c}) = scalar_t(accum[idx]);
1896
+ }
1897
+ }
1898
+ }
1899
+ }
1900
+ }
1901
+
1902
+ static void CUTLASS_DEVICE accumApplyLSEToSmem(
1903
+ AccumulatorSharedStorage& shared_storage,
1904
+ typename IteratorC::Fragment& accum,
1905
+ lse_scalar_t const* lse,
1906
+ int lse_extent,
1907
+ int thread_id,
1908
+ int warp_id,
1909
+ int lane_id,
1910
+ cutlass::MatrixCoord const& tile_coords) {
1911
+ // Non-optimized way to apply LSE to registers
1912
+ // NOTE: accum is attn.T
1913
+ // TODO: Optimize for each architecture
1914
+ static constexpr int WarpSize = 32;
1915
+ using AccumLambdaIterator =
1916
+ typename DefaultMmaAccumLambdaIterator<IteratorC, accum_t, WarpSize>::
1917
+ Iterator;
1918
+ auto lane_offset =
1919
+ AccumLambdaIterator::get_lane_offset(lane_id, warp_id, tile_coords);
1920
+
1921
+ cutlass::Array<lse_scalar_t, IteratorC::Fragment::kElements> lse_prefetched;
1922
+ lse_prefetched.clear();
1923
+ int rowIdx = 0;
1924
+ int colIdx = 0;
1925
+ AccumLambdaIterator::iterateRows(
1926
+ lane_offset,
1927
+ [&](int accum_m) {
1928
+ ++rowIdx;
1929
+ colIdx = 0;
1930
+ },
1931
+ [&](int accum_m, int accum_n, int idx) {
1932
+ if (rowIdx == 1) {
1933
+ lse_prefetched[colIdx] = accum_n < lse_extent
1934
+ ? lse[accum_n]
1935
+ : platform::numeric_limits<accum_t>::infinity();
1936
+ }
1937
+ accum[idx] = expf(accum[idx] - lse_prefetched[colIdx]);
1938
+ ++colIdx;
1939
+ },
1940
+ [&](int accum_m) {});
1941
+ accumToSmem(shared_storage, accum, lane_id, tile_coords);
1942
+ }
1943
+ };
1944
+
1945
+ } // namespace threadblock
1946
+ } // namespace gemm
1947
+ } // namespace cutlass
1948
+
1949
+ /////////////////////////////////////////////////////////////////////////////////////////////////
1950
+
1951
+ #else
1952
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1953
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.10/site-packages/torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/epilogue_predicated_tile_iterator.h ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /***************************************************************************************************
3
+ * Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights
4
+ *reserved. SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice,
10
+ *this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ * this list of conditions and the following disclaimer in the documentation
14
+ * and/or other materials provided with the distribution.
15
+ *
16
+ * 3. Neither the name of the copyright holder nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ *POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ **************************************************************************************************/
33
+ /*! \file
34
+ \brief Epilogue iterator that supports prefetching
35
+
36
+ Mostly copied from <cutlass/epilogue/threadblock/predicated_tile_iterator.h>
37
+ */
38
+
39
+ #pragma once
40
+
41
+ #include <cutlass/arch/arch.h>
42
+ #include <cutlass/arch/memory.h>
43
+ #include <cutlass/array.h>
44
+ #include <cutlass/cutlass.h>
45
+ #include <cutlass/epilogue/threadblock/output_tile_thread_map.h>
46
+ #include <cutlass/epilogue/threadblock/predicated_tile_iterator_params.h>
47
+ #include <cutlass/layout/matrix.h>
48
+ #include <cutlass/layout/tensor.h>
49
+ #include <cutlass/matrix_shape.h>
50
+ #include <cutlass/numeric_types.h>
51
+ #include <cutlass/tensor_ref.h>
52
+ #include <cutlass/transform/pitch_linear_thread_map.h>
53
+
54
+ ////////////////////////////////////////////////////////////////////////////////
55
+
56
+ namespace cutlass {
57
+
58
+ ////////////////////////////////////////////////////////////////////////////////
59
+
60
+ namespace epilogue {
61
+ namespace threadblock {
62
+
63
+ ////////////////////////////////////////////////////////////////////////////////
64
+
65
+ /// Tile iterator used to load and store output tile from global memory in
66
+ /// epilogue.
67
+ ///
68
+ /// Satisfies: ReadableTileIterator | PredicatedTileIterator |
69
+ /// ForwardTileIterator
70
+ ///
71
+ template <
72
+ typename ThreadMap_, ///< Thread map (concept: OutputTileThreadMap)
73
+ typename Element_, ///< Element data type
74
+ bool ScatterD = false, ///< Scatter D operand or not
75
+ bool UseCUDAStore = false>
76
+ class PredicatedTileIteratorPrefetch {
77
+ public:
78
+ using ThreadMap = ThreadMap_;
79
+ using Shape = typename ThreadMap::Shape;
80
+
81
+ using Element = Element_;
82
+
83
+ using Layout = layout::RowMajor;
84
+ using TensorRef = TensorRef<Element, Layout>;
85
+ using ConstTensorRef = typename TensorRef::ConstTensorRef;
86
+
87
+ using Index = typename Layout::Index;
88
+ using LongIndex = typename Layout::LongIndex;
89
+ using TensorCoord = MatrixCoord;
90
+
91
+ static int const kElementsPerAccess = ThreadMap::kElementsPerAccess;
92
+ static int const kThreads = ThreadMap::kThreads;
93
+ static int const kIterations = ThreadMap::Count::kTile;
94
+
95
+ static_assert(
96
+ ThreadMap::Iterations::kRow > 0,
97
+ "ThreadMap::Iterations::kRow must be > 0");
98
+ static_assert(
99
+ ThreadMap::Iterations::kGroup > 0,
100
+ "ThreadMap::Iterations::kGroup must be > 0");
101
+ static_assert(
102
+ ThreadMap::Iterations::kCluster > 0,
103
+ "ThreadMap::Iterations::kCluster must be > 0");
104
+ static_assert(
105
+ ThreadMap::Iterations::kColumn > 0,
106
+ "ThreadMap::Iterations::kColumn must be > 0");
107
+
108
+ /// Fragment object
109
+ using Fragment = Array<
110
+ Element,
111
+ ThreadMap::Iterations::kColumn * ThreadMap::Iterations::kRow *
112
+ ThreadMap::Iterations::kGroup * ThreadMap::Iterations::kCluster *
113
+ ThreadMap::kElementsPerAccess>;
114
+
115
+ /// Memory access size
116
+ using AccessType = AlignedArray<Element, ThreadMap::kElementsPerAccess>;
117
+
118
+ //
119
+ // Parameters struct
120
+ //
121
+
122
+ /// Uses a non-template class
123
+ struct Params : PredicatedTileIteratorParams {
124
+ using Base = PredicatedTileIteratorParams;
125
+
126
+ CUTLASS_HOST_DEVICE
127
+ Params() {}
128
+
129
+ CUTLASS_HOST_DEVICE
130
+ Params(Layout const& layout)
131
+ : PredicatedTileIteratorParams(
132
+ layout.stride(0) * int(sizeof(AccessType)) / kElementsPerAccess,
133
+ make_OutputTileThreadMapDesc<ThreadMap>()) {}
134
+
135
+ CUTLASS_HOST_DEVICE
136
+ Params(Base const& base) : Base(base) {}
137
+ };
138
+
139
+ /// Mask object
140
+ struct Mask {
141
+ static int const kCount = ThreadMap::Iterations::kColumn;
142
+
143
+ /// Predicate state
144
+ bool predicates[kCount];
145
+
146
+ //
147
+ // Mask
148
+ //
149
+ CUTLASS_HOST_DEVICE
150
+ Mask() {
151
+ enable();
152
+ }
153
+
154
+ ///< Efficiently disables all accesses guarded by mask
155
+ CUTLASS_HOST_DEVICE void clear() {
156
+ CUTLASS_PRAGMA_UNROLL
157
+ for (int i = 0; i < kCount; ++i) {
158
+ predicates[i] = false;
159
+ }
160
+ }
161
+
162
+ ///< CUTLASS_HOST_DEVICE enables all accesses guarded by mask
163
+ CUTLASS_DEVICE void enable() {
164
+ CUTLASS_PRAGMA_UNROLL
165
+ for (int i = 0; i < kCount; ++i) {
166
+ predicates[i] = true;
167
+ }
168
+ }
169
+ };
170
+
171
+ private:
172
+ //
173
+ // Data members
174
+ //
175
+
176
+ /// Parameters structure containing reference and precomputed state.
177
+ PredicatedTileIteratorParams params_;
178
+
179
+ /// Byte-level pointer
180
+ uint8_t* byte_pointer_;
181
+
182
+ /// Array of boolean values to contain steady-state predicates
183
+ Mask mask_;
184
+
185
+ /// Extent of the matrix tile in rows
186
+ Index extent_row_;
187
+
188
+ /// Extent of the matrix tile in rows
189
+ Index extent_column_;
190
+
191
+ /// A thread's starting row position (assuming steady-state predicates have
192
+ /// been computed)
193
+ Index thread_start_row_;
194
+
195
+ /// A thread's starting column
196
+ Index thread_start_column_;
197
+
198
+ /// Internal state counter
199
+ int state_[3];
200
+
201
+ /// Scatter indices
202
+ int const* indices_;
203
+
204
+ //
205
+ // Static asserts about internal strides
206
+ //
207
+
208
+ static_assert(sizeof(extent_row_) == 4, "Expected 32b extents");
209
+ static_assert(sizeof(thread_start_row_) == 4, "Expected 32b extents");
210
+ static_assert(
211
+ sizeof(PredicatedTileIteratorParams::stride) == 8,
212
+ "Expected 64b strides");
213
+
214
+ private:
215
+ //
216
+ // Methods
217
+ //
218
+
219
+ public:
220
+ //
221
+ // Methods
222
+ //
223
+
224
+ /// Constructor
225
+ CUTLASS_DEVICE
226
+ PredicatedTileIteratorPrefetch(
227
+ PredicatedTileIteratorParams const& params,
228
+ Element* pointer,
229
+ TensorCoord extent,
230
+ int thread_idx,
231
+ TensorCoord threadblock_offset = TensorCoord(),
232
+ int const* indices = nullptr)
233
+ : params_(params), indices_(indices) {
234
+ TensorCoord thread_offset =
235
+ ThreadMap::initial_offset(thread_idx) + threadblock_offset;
236
+
237
+ extent_row_ = extent.row();
238
+ extent_column_ = extent.column();
239
+
240
+ thread_start_row_ = thread_offset.row();
241
+ thread_start_column_ = thread_offset.column();
242
+
243
+ // Initialize predicates
244
+ CUTLASS_PRAGMA_UNROLL
245
+ for (int c = 0; c < ThreadMap::Iterations::kColumn; ++c) {
246
+ mask_.predicates[c] =
247
+ ((thread_offset.column() + ThreadMap::Delta::kColumn * c) <
248
+ extent.column());
249
+ }
250
+
251
+ // Null pointer performs no accesses
252
+ if (!pointer) {
253
+ mask_.clear();
254
+ }
255
+
256
+ if (ScatterD && !indices) {
257
+ mask_.clear();
258
+ }
259
+
260
+ // Initialize pointer
261
+ byte_pointer_ = reinterpret_cast<uint8_t*>(pointer) +
262
+ LongIndex(thread_offset.row()) * LongIndex(params_.stride) +
263
+ LongIndex(thread_offset.column()) * sizeof(AccessType) /
264
+ kElementsPerAccess;
265
+
266
+ if (ScatterD) {
267
+ byte_pointer_ = reinterpret_cast<uint8_t*>(pointer) +
268
+ LongIndex(thread_offset.column()) * sizeof(AccessType) /
269
+ kElementsPerAccess;
270
+ }
271
+
272
+ // Initialize internal state counter
273
+ state_[0] = state_[1] = state_[2] = 0;
274
+ }
275
+
276
+ /// Adds a pointer offset in units of Element
277
+ CUTLASS_HOST_DEVICE
278
+ void add_pointer_offset(LongIndex pointer_offset) {
279
+ byte_pointer_ += pointer_offset * sizeof_bits<Element>::value / 8;
280
+ }
281
+
282
+ CUTLASS_DEVICE
283
+ void prefetch_all() {
284
+ CUTLASS_PRAGMA_UNROLL
285
+ for (int iter = 0; iter < kIterations; ++iter) {
286
+ prefetch();
287
+ ++(*this);
288
+ }
289
+ }
290
+
291
+ CUTLASS_DEVICE
292
+ void prefetch() {
293
+ uint8_t* byte_pointer = byte_pointer_;
294
+
295
+ CUTLASS_PRAGMA_UNROLL
296
+ for (int cluster = 0; cluster < ThreadMap::Iterations::kCluster;
297
+ ++cluster) {
298
+ CUTLASS_PRAGMA_UNROLL
299
+ for (int group = 0; group < ThreadMap::Iterations::kGroup; ++group) {
300
+ CUTLASS_PRAGMA_UNROLL
301
+ for (int row = 0; row < ThreadMap::Iterations::kRow; ++row) {
302
+ int row_offset = row * ThreadMap::Delta::kRow +
303
+ group * ThreadMap::Delta::kGroup +
304
+ cluster * ThreadMap::Delta::kCluster;
305
+
306
+ AccessType* memory_pointer =
307
+ reinterpret_cast<AccessType*>(byte_pointer);
308
+
309
+ CUTLASS_PRAGMA_UNROLL
310
+ for (int column = 0; column < ThreadMap::Iterations::kColumn;
311
+ ++column) {
312
+ // on windows using unsigned long here gives the error
313
+ // error: asm operand type size(4) does not match
314
+ // type/size implied by constraint 'l'
315
+ uint64_t addr = (uint64_t)((void*)&memory_pointer
316
+ [column * ThreadMap::Delta::kColumn /
317
+ kElementsPerAccess]);
318
+ asm volatile("prefetch.global.L1 [ %1 ];" : "=l"(addr) : "l"(addr));
319
+ }
320
+
321
+ if (row + 1 < ThreadMap::Iterations::kRow) {
322
+ if (!ScatterD) {
323
+ byte_pointer += params_.increment_row;
324
+ }
325
+ }
326
+ }
327
+
328
+ if (group + 1 < ThreadMap::Iterations::kGroup) {
329
+ byte_pointer += params_.increment_group;
330
+ }
331
+ }
332
+
333
+ if (cluster + 1 < ThreadMap::Iterations::kCluster) {
334
+ byte_pointer += params_.increment_cluster;
335
+ }
336
+ }
337
+ }
338
+
339
+ /// Loads a fragment from memory
340
+ CUTLASS_DEVICE
341
+ void load_with_byte_offset(Fragment& frag, int64_t byte_offset) const {
342
+ uint8_t* byte_pointer = byte_pointer_;
343
+ AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag);
344
+
345
+ CUTLASS_PRAGMA_UNROLL
346
+ for (int cluster = 0; cluster < ThreadMap::Iterations::kCluster;
347
+ ++cluster) {
348
+ CUTLASS_PRAGMA_UNROLL
349
+ for (int group = 0; group < ThreadMap::Iterations::kGroup; ++group) {
350
+ CUTLASS_PRAGMA_UNROLL
351
+ for (int row = 0; row < ThreadMap::Iterations::kRow; ++row) {
352
+ int frag_row_idx =
353
+ (row +
354
+ ThreadMap::Iterations::kRow *
355
+ (group + ThreadMap::Iterations::kGroup * cluster));
356
+
357
+ int row_offset = row * ThreadMap::Delta::kRow +
358
+ group * ThreadMap::Delta::kGroup +
359
+ cluster * ThreadMap::Delta::kCluster;
360
+
361
+ bool row_guard = ((row_offset + thread_start_row_) < extent_row_);
362
+
363
+ AccessType* memory_pointer =
364
+ reinterpret_cast<AccessType*>(byte_pointer + byte_offset);
365
+
366
+ if (ScatterD && row_guard) {
367
+ assert(indices_);
368
+
369
+ memory_pointer = reinterpret_cast<AccessType*>(
370
+ byte_pointer + byte_offset +
371
+ LongIndex(indices_[row_offset + thread_start_row_]) *
372
+ LongIndex(params_.stride));
373
+ }
374
+
375
+ CUTLASS_PRAGMA_UNROLL
376
+ for (int column = 0; column < ThreadMap::Iterations::kColumn;
377
+ ++column) {
378
+ bool guard = row_guard && mask_.predicates[column];
379
+
380
+ cutlass::arch::global_load<AccessType, sizeof(AccessType)>(
381
+ frag_ptr
382
+ [frag_row_idx * ThreadMap::Iterations::kColumn + column],
383
+ (void*)&memory_pointer
384
+ [column * ThreadMap::Delta::kColumn / kElementsPerAccess],
385
+ guard);
386
+ }
387
+
388
+ if (row + 1 < ThreadMap::Iterations::kRow) {
389
+ if (!ScatterD) {
390
+ byte_pointer += params_.increment_row;
391
+ }
392
+ }
393
+ }
394
+
395
+ if (group + 1 < ThreadMap::Iterations::kGroup) {
396
+ byte_pointer += params_.increment_group;
397
+ }
398
+ }
399
+
400
+ if (cluster + 1 < ThreadMap::Iterations::kCluster) {
401
+ byte_pointer += params_.increment_cluster;
402
+ }
403
+ }
404
+ }
405
+
406
+ /// Loads a fragment from memory
407
+ CUTLASS_DEVICE
408
+ void load(Fragment& frag) const {
409
+ load_with_byte_offset(frag, 0);
410
+ }
411
+
412
+ /// Stores a fragment to memory
413
+ CUTLASS_DEVICE
414
+ void store_with_byte_offset(Fragment const& frag, int64_t byte_offset) const {
415
+ uint8_t* byte_pointer = byte_pointer_;
416
+ AccessType const* frag_ptr = reinterpret_cast<AccessType const*>(&frag);
417
+
418
+ CUTLASS_PRAGMA_UNROLL
419
+ for (int cluster = 0; cluster < ThreadMap::Iterations::kCluster;
420
+ ++cluster) {
421
+ CUTLASS_PRAGMA_UNROLL
422
+ for (int group = 0; group < ThreadMap::Iterations::kGroup; ++group) {
423
+ CUTLASS_PRAGMA_UNROLL
424
+ for (int row = 0; row < ThreadMap::Iterations::kRow; ++row) {
425
+ int frag_row_idx =
426
+ (row +
427
+ ThreadMap::Iterations::kRow *
428
+ (group + ThreadMap::Iterations::kGroup * cluster));
429
+
430
+ int row_offset = row * ThreadMap::Delta::kRow +
431
+ group * ThreadMap::Delta::kGroup +
432
+ cluster * ThreadMap::Delta::kCluster;
433
+
434
+ bool row_guard = ((row_offset + thread_start_row_) < extent_row_);
435
+
436
+ AccessType* memory_pointer =
437
+ reinterpret_cast<AccessType*>(byte_pointer + byte_offset);
438
+
439
+ if (ScatterD && row_guard) {
440
+ assert(indices_);
441
+
442
+ memory_pointer = reinterpret_cast<AccessType*>(
443
+ byte_pointer + byte_offset +
444
+ LongIndex(indices_[row_offset + thread_start_row_]) *
445
+ LongIndex(params_.stride));
446
+ }
447
+
448
+ CUTLASS_PRAGMA_UNROLL
449
+ for (int column = 0; column < ThreadMap::Iterations::kColumn;
450
+ ++column) {
451
+ bool guard = row_guard && mask_.predicates[column];
452
+
453
+ if (UseCUDAStore) {
454
+ if (guard) {
455
+ memory_pointer
456
+ [column * ThreadMap::Delta::kColumn / kElementsPerAccess] =
457
+ frag_ptr
458
+ [frag_row_idx * ThreadMap::Iterations::kColumn +
459
+ column];
460
+ }
461
+ } else {
462
+ cutlass::arch::global_store<AccessType, sizeof(AccessType)>(
463
+ frag_ptr
464
+ [frag_row_idx * ThreadMap::Iterations::kColumn + column],
465
+ (void*)&memory_pointer
466
+ [column * ThreadMap::Delta::kColumn / kElementsPerAccess],
467
+ guard);
468
+ }
469
+ }
470
+
471
+ if (row + 1 < ThreadMap::Iterations::kRow) {
472
+ if (!ScatterD) {
473
+ byte_pointer += params_.increment_row;
474
+ }
475
+ }
476
+ }
477
+
478
+ if (group + 1 < ThreadMap::Iterations::kGroup) {
479
+ byte_pointer += params_.increment_group;
480
+ }
481
+ }
482
+
483
+ if (cluster + 1 < ThreadMap::Iterations::kCluster) {
484
+ byte_pointer += params_.increment_cluster;
485
+ }
486
+ }
487
+ }
488
+
489
+ /// Stores a fragment to memory
490
+ CUTLASS_DEVICE
491
+ void store(Fragment const& frag) const {
492
+ store_with_byte_offset(frag, 0);
493
+ }
494
+
495
+ /// Loads a fragment from memory
496
+ CUTLASS_DEVICE
497
+ void downsample_load_with_byte_offset(
498
+ Fragment& frag,
499
+ int64_t byte_offset,
500
+ int convolution_P,
501
+ int convolution_Q,
502
+ int add_P,
503
+ int add_Q,
504
+ int problem_N) const {
505
+ uint8_t* byte_pointer = byte_pointer_;
506
+ AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag);
507
+
508
+ CUTLASS_PRAGMA_UNROLL
509
+ for (int cluster = 0; cluster < ThreadMap::Iterations::kCluster;
510
+ ++cluster) {
511
+ CUTLASS_PRAGMA_UNROLL
512
+ for (int group = 0; group < ThreadMap::Iterations::kGroup; ++group) {
513
+ CUTLASS_PRAGMA_UNROLL
514
+ for (int row = 0; row < ThreadMap::Iterations::kRow; ++row) {
515
+ int frag_row_idx =
516
+ (row +
517
+ ThreadMap::Iterations::kRow *
518
+ (group + ThreadMap::Iterations::kGroup * cluster));
519
+
520
+ int row_offset = row * ThreadMap::Delta::kRow +
521
+ group * ThreadMap::Delta::kGroup +
522
+ cluster * ThreadMap::Delta::kCluster;
523
+
524
+ bool row_guard = ((row_offset + thread_start_row_) < extent_row_);
525
+
526
+ int output_row = row_offset + thread_start_row_;
527
+ int output_N = output_row / (convolution_P * convolution_Q);
528
+ int output_PQ = output_row % (convolution_P * convolution_Q);
529
+ int output_P = output_PQ / convolution_Q;
530
+ int output_Q = output_PQ % convolution_Q;
531
+
532
+ int input_row = output_N * 2 * convolution_P * 2 * convolution_Q +
533
+ (2 * output_P + add_P) * 2 * convolution_Q + 2 * output_Q + add_Q;
534
+
535
+ int64_t byte_offset =
536
+ (input_row - output_row) * problem_N * sizeof(float);
537
+
538
+ AccessType* memory_pointer =
539
+ reinterpret_cast<AccessType*>(byte_pointer + byte_offset);
540
+
541
+ CUTLASS_PRAGMA_UNROLL
542
+ for (int column = 0; column < ThreadMap::Iterations::kColumn;
543
+ ++column) {
544
+ bool guard = row_guard && mask_.predicates[column];
545
+
546
+ cutlass::arch::global_load<AccessType, sizeof(AccessType)>(
547
+ frag_ptr
548
+ [frag_row_idx * ThreadMap::Iterations::kColumn + column],
549
+ (void*)&memory_pointer
550
+ [column * ThreadMap::Delta::kColumn / kElementsPerAccess],
551
+ guard);
552
+ }
553
+
554
+ if (row + 1 < ThreadMap::Iterations::kRow) {
555
+ byte_pointer += params_.increment_row;
556
+ }
557
+ }
558
+
559
+ if (group + 1 < ThreadMap::Iterations::kGroup) {
560
+ byte_pointer += params_.increment_group;
561
+ }
562
+ }
563
+
564
+ if (cluster + 1 < ThreadMap::Iterations::kCluster) {
565
+ byte_pointer += params_.increment_cluster;
566
+ }
567
+ }
568
+ }
569
+
570
+ /// Loads a fragment from memory
571
+ CUTLASS_DEVICE
572
+ void upsample_load_with_byte_offset(
573
+ Fragment& frag,
574
+ int64_t byte_offset,
575
+ int convolution_P,
576
+ int convolution_Q,
577
+ int add_P,
578
+ int add_Q,
579
+ int problem_N) const {
580
+ uint8_t* byte_pointer = byte_pointer_;
581
+ AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag);
582
+
583
+ CUTLASS_PRAGMA_UNROLL
584
+ for (int cluster = 0; cluster < ThreadMap::Iterations::kCluster;
585
+ ++cluster) {
586
+ CUTLASS_PRAGMA_UNROLL
587
+ for (int group = 0; group < ThreadMap::Iterations::kGroup; ++group) {
588
+ CUTLASS_PRAGMA_UNROLL
589
+ for (int row = 0; row < ThreadMap::Iterations::kRow; ++row) {
590
+ int frag_row_idx =
591
+ (row +
592
+ ThreadMap::Iterations::kRow *
593
+ (group + ThreadMap::Iterations::kGroup * cluster));
594
+
595
+ int row_offset = row * ThreadMap::Delta::kRow +
596
+ group * ThreadMap::Delta::kGroup +
597
+ cluster * ThreadMap::Delta::kCluster;
598
+
599
+ bool row_guard = ((row_offset + thread_start_row_) < extent_row_);
600
+
601
+ int output_row = row_offset + thread_start_row_;
602
+ int output_N = output_row / (convolution_P * convolution_Q);
603
+ int output_PQ = output_row % (convolution_P * convolution_Q);
604
+ int output_P = output_PQ / convolution_Q;
605
+ int output_Q = output_PQ % convolution_Q;
606
+ int row_add_P = add_P;
607
+ int row_add_Q = add_Q;
608
+ if (output_P > convolution_P - 2)
609
+ row_add_P = 0;
610
+ if (output_Q > convolution_Q - 2)
611
+ row_add_Q = 0;
612
+
613
+ int input_row = output_N * (convolution_P / 2) * (convolution_Q / 2) +
614
+ ((output_P + row_add_P) / 2) * (convolution_Q / 2) +
615
+ (output_Q + row_add_Q) / 2;
616
+
617
+ int64_t byte_offset =
618
+ (input_row - output_row) * problem_N * sizeof(float);
619
+
620
+ AccessType* memory_pointer =
621
+ reinterpret_cast<AccessType*>(byte_pointer + byte_offset);
622
+
623
+ CUTLASS_PRAGMA_UNROLL
624
+ for (int column = 0; column < ThreadMap::Iterations::kColumn;
625
+ ++column) {
626
+ bool guard = row_guard && mask_.predicates[column];
627
+
628
+ cutlass::arch::global_load<AccessType, sizeof(AccessType)>(
629
+ frag_ptr
630
+ [frag_row_idx * ThreadMap::Iterations::kColumn + column],
631
+ (void*)&memory_pointer
632
+ [column * ThreadMap::Delta::kColumn / kElementsPerAccess],
633
+ guard);
634
+ }
635
+
636
+ if (row + 1 < ThreadMap::Iterations::kRow) {
637
+ byte_pointer += params_.increment_row;
638
+ }
639
+ }
640
+
641
+ if (group + 1 < ThreadMap::Iterations::kGroup) {
642
+ byte_pointer += params_.increment_group;
643
+ }
644
+ }
645
+
646
+ if (cluster + 1 < ThreadMap::Iterations::kCluster) {
647
+ byte_pointer += params_.increment_cluster;
648
+ }
649
+ }
650
+ }
651
+
652
+ CUTLASS_DEVICE
653
+ MatrixCoord thread_start() const {
654
+ return MatrixCoord(thread_start_row_, thread_start_column_);
655
+ }
656
+
657
+ /// Need to get the thread start row from the tile iterator
658
+ CUTLASS_DEVICE
659
+ int32_t thread_start_row() const {
660
+ return thread_start_row_;
661
+ }
662
+
663
+ /// Need to get the thread start row from the tile iterator
664
+ CUTLASS_DEVICE
665
+ int32_t thread_start_column() const {
666
+ return thread_start_column_;
667
+ }
668
+
669
+ /// Extent of the matrix in rows
670
+ CUTLASS_DEVICE
671
+ Index extent_row() const {
672
+ return extent_row_;
673
+ }
674
+
675
+ /// Extent of the matrix in columns
676
+ CUTLASS_DEVICE
677
+ Index extent_column() const {
678
+ return extent_column_;
679
+ }
680
+
681
+ /// Advances to the next position to load or store
682
+ CUTLASS_HOST_DEVICE
683
+ PredicatedTileIteratorPrefetch& operator++() {
684
+ ++state_[0];
685
+
686
+ if (!ScatterD) {
687
+ byte_pointer_ += params_.advance_row;
688
+ }
689
+
690
+ thread_start_row_ += ThreadMap::Shape::kRow;
691
+
692
+ if (state_[0] == ThreadMap::Count::kRow) {
693
+ state_[0] = 0;
694
+ ++state_[1];
695
+ byte_pointer_ += params_.advance_group;
696
+
697
+ thread_start_row_ += (ThreadMap::Shape::kGroup - 1) *
698
+ ThreadMap::Shape::kRow * ThreadMap::Count::kRow;
699
+
700
+ if (state_[1] == ThreadMap::Count::kGroup) {
701
+ state_[1] = 0;
702
+ ++state_[2];
703
+ byte_pointer_ += params_.advance_cluster;
704
+
705
+ thread_start_row_ += ThreadMap::Count::kGroup *
706
+ ThreadMap::Shape::kGroup * ThreadMap::Count::kRow *
707
+ ThreadMap::Shape::kRow;
708
+
709
+ if (state_[2] == ThreadMap::Count::kCluster) {
710
+ state_[2] = 0;
711
+ byte_pointer_ += params_.advance_tile;
712
+ }
713
+ }
714
+ }
715
+
716
+ return *this;
717
+ }
718
+
719
+ ///< Efficiently disables all accesses guarded by mask
720
+ CUTLASS_DEVICE void clear_mask() {
721
+ mask_.clear();
722
+ }
723
+
724
+ ///< Efficiently enables all accesses guarded by mask
725
+ CUTLASS_DEVICE void enable_mask() {
726
+ mask_.enable();
727
+ }
728
+
729
+ ///< Sets the mask
730
+ CUTLASS_DEVICE void get_mask(Mask& mask) const {
731
+ mask = mask_;
732
+ }
733
+
734
+ ///< Sets the mask
735
+ CUTLASS_DEVICE void set_mask(Mask const& mask) {
736
+ mask_ = mask;
737
+ }
738
+ };
739
+
740
+ template <typename IT>
741
+ struct MakePrefetchableIterator {
742
+ using Iterator = PredicatedTileIteratorPrefetch<
743
+ typename IT::ThreadMap,
744
+ typename IT::Element>;
745
+ };
746
+
747
+ ///////////////////////////////////////////////////////////////////////////////
748
+
749
+ } // namespace threadblock
750
+ } // namespace epilogue
751
+ } // namespace cutlass
752
+
753
+ ////////////////////////////////////////////////////////////////////////////////
754
+
755
+ #else
756
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
757
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)