FaustDerLegende commited on
Commit
87930cf
·
verified ·
1 Parent(s): 3f600b0

Upload folder using huggingface_hub (part 24)

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.12/site-packages/torch/include/ATen/native/cuda/GridSampler.h +36 -0
  2. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/GroupMM.h +17 -0
  3. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/GroupMMCommon.cuh +161 -0
  4. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/IndexKernel.h +20 -0
  5. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/IndexKernelUtils.h +70 -0
  6. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/JitLoops.cuh +191 -0
  7. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/KernelUtils.cuh +285 -0
  8. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/LaunchUtils.h +21 -0
  9. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Loops.cuh +347 -0
  10. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Math.cuh +0 -0
  11. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MemoryAccess.cuh +699 -0
  12. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MiscUtils.h +36 -0
  13. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MultiTensorApply.cuh +440 -0
  14. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Normalization.cuh +1808 -0
  15. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/PersistentSoftmax.cuh +443 -0
  16. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Pow.cuh +63 -0
  17. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Randperm.cuh +63 -0
  18. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Reduce.cuh +1415 -0
  19. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ReduceOps.h +26 -0
  20. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Resize.h +62 -0
  21. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/RowwiseScaledMM.h +19 -0
  22. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScaledBlasDeviceUtils.h +19 -0
  23. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScaledGroupMM.h +20 -0
  24. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScanKernels.h +23 -0
  25. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScanUtils.cuh +480 -0
  26. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Sort.h +22 -0
  27. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortStable.h +22 -0
  28. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortUtils.cuh +364 -0
  29. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Sorting.h +22 -0
  30. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortingCommon.cuh +198 -0
  31. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortingRadixSelect.cuh +1115 -0
  32. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorModeKernel.cuh +436 -0
  33. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorModeKernel.h +23 -0
  34. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorTopK.h +18 -0
  35. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/UniqueCub.cuh +17 -0
  36. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/UpSample.cuh +373 -0
  37. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/block_reduce.cuh +152 -0
  38. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/cuBlasCommonArgs.h +176 -0
  39. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/cutlass_common.cuh +53 -0
  40. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adagrad_impl.cuh +37 -0
  41. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adagrad_utils.cuh +144 -0
  42. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_amsgrad_impl.cuh +43 -0
  43. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_impl.cuh +41 -0
  44. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_utils.cuh +558 -0
  45. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adamw_amsgrad_impl.cuh +43 -0
  46. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adamw_impl.cuh +41 -0
  47. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/im2col.cuh +341 -0
  48. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/jit_utils.h +259 -0
  49. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/reduction_template.cuh +746 -0
  50. .venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/thread_constants.h +30 -0
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/GridSampler.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <array>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ class TensorBase;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ void launch_grid_sampler_2d_forward_kernel(
13
+ const TensorBase &output, const TensorBase &input, const TensorBase &grid,
14
+ int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
15
+
16
+ void launch_grid_sampler_3d_forward_kernel(
17
+ const TensorBase &output, const TensorBase &input, const TensorBase &grid,
18
+ int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
19
+
20
+ void launch_grid_sampler_2d_backward_kernel(
21
+ const TensorBase &grad_input, const TensorBase &grad_grid,
22
+ const TensorBase &grad_output, const TensorBase &input,
23
+ const TensorBase &grid, int64_t interpolation_mode, int64_t padding_mode,
24
+ bool align_corners, std::array<bool, 2> output_mask);
25
+
26
+ void launch_grid_sampler_3d_backward_kernel(
27
+ const TensorBase &grad_input, const TensorBase &grad_grid,
28
+ const TensorBase &grad_output, const TensorBase &input,
29
+ const TensorBase &grid, int64_t interpolation_mode, int64_t padding_mode,
30
+ bool align_corners, std::array<bool, 2> output_mask);
31
+
32
+ } // namespace at::native
33
+
34
+ #else
35
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
36
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/GroupMM.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <optional>
5
+
6
+ namespace at::cuda::detail {
7
+ TORCH_API void bf16bf16_grouped_mm(
8
+ at::Tensor mat_a, // bf16
9
+ at::Tensor mat_b, // bf16
10
+ std::optional<at::Tensor> offs,
11
+ std::optional<at::Tensor> bias, // BF16
12
+ at::Tensor& out);
13
+ } // namespace at::cuda::detail
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.12/site-packages/torch/include/ATen/native/cuda/GroupMMCommon.cuh ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cutlass/util/packed_stride.hpp>
4
+
5
+ namespace at::cuda::detail {
6
+
7
+ using Strides = std::array<int64_t, 3>;
8
+
9
+ template <
10
+ typename DtypeA,
11
+ typename DtypeB,
12
+ typename DtypeOutput,
13
+ typename DtypeScale,
14
+ typename ProblemShape,
15
+ typename StrideA,
16
+ typename StrideB,
17
+ typename StrideOutput>
18
+ __global__ void prepare_grouped_gemm_data(
19
+ DtypeA* A,
20
+ DtypeB* B,
21
+ DtypeOutput* output,
22
+ DtypeScale* scale_A,
23
+ DtypeScale* scale_B,
24
+ DtypeA** A_ptrs,
25
+ DtypeB** B_ptrs,
26
+ DtypeOutput** output_ptrs,
27
+ DtypeScale** inputA_scale_ptrs,
28
+ DtypeScale** inputB_scale_ptrs,
29
+ ProblemShape* problem_sizes,
30
+ // Strides for cutlass, cute::Stride
31
+ StrideA* stride_A,
32
+ StrideB* stride_B,
33
+ StrideOutput* stride_output,
34
+ const int32_t* offs,
35
+ int32_t M,
36
+ int32_t N,
37
+ int32_t K,
38
+ // Original strides of the input tensors
39
+ Strides tensor_StrideA,
40
+ Strides tensor_StrideB,
41
+ Strides tensor_StrideOutput,
42
+ Strides tensor_ShapeA,
43
+ Strides tensor_ShapeB,
44
+ int64_t a_scale_stride,
45
+ int64_t b_scale_stride,
46
+ bool a_row_major = true,
47
+ bool b_row_major = false) {
48
+ int32_t tid = threadIdx.x;
49
+ int32_t delta = 0;
50
+ int32_t offset = 0;
51
+ if (offs != nullptr) {
52
+ int32_t start = tid == 0 ? 0 : offs[tid - 1];
53
+ offset = offs[tid];
54
+ delta = offset - start;
55
+ CUDA_KERNEL_ASSERT(delta >=0 && "expected gemm dimension to be greater or equal 0\n");
56
+
57
+ // TMA transfers require global memory tensor addresses to be
58
+ // aligned to 16 bytes.
59
+ if (tid < blockDim.x - 1) {
60
+ // Check this requirement for input tensors, in case group
61
+ // addresses are increased along the dynamic dimension.
62
+ if ((K < 0 && a_row_major) || // 2D/2D: check along K dimension
63
+ (M < 0 && !a_row_major)) { // 3D/2D: check along N dimension
64
+ int align = 128 / cutlass::sizeof_bits<DtypeA>::value;
65
+ CUDA_KERNEL_ASSERT(
66
+ delta % align == 0 &&
67
+ "expected input tensor dynamic dimension byte size to be non-negative multiple of 16\n");
68
+ }
69
+ if ((K < 0 && !b_row_major) || // 2D/2D: check along K dimension
70
+ (N < 0 && b_row_major)) { // 3D/2D: check along N dimension
71
+ int align = 128 / cutlass::sizeof_bits<DtypeB>::value;
72
+ CUDA_KERNEL_ASSERT(
73
+ delta % align == 0 &&
74
+ "expected input tensor dynamic dimension byte size to be non-negative multiple of 16\n");
75
+ }
76
+
77
+ // Check the same requirement for output tensor (that is always
78
+ // contiguous, and in row-major layout).
79
+ if (N < 0) {
80
+ int align = 128 / cutlass::sizeof_bits<DtypeOutput>::value;
81
+ CUDA_KERNEL_ASSERT(
82
+ delta % align == 0 &&
83
+ "expected output tensor dynamic dimension byte size to be non-negative multiple of 16\n");
84
+ }
85
+ }
86
+ }
87
+ int64_t lda, ldb, ldoutput;
88
+ if (M < 0) {
89
+ // A and output is 2d
90
+ CUDA_KERNEL_ASSERT(offset <= tensor_ShapeA[0] && "expected offset to be less than tensor size\n");
91
+ M = delta;
92
+ lda = a_row_major ? tensor_StrideA[0] : tensor_StrideA[1];
93
+ ldb = b_row_major ? tensor_StrideB[1] : tensor_StrideB[2];
94
+ ldoutput = tensor_StrideOutput[0];
95
+ A_ptrs[tid] = tid == 0 ? A : A + offs[tid - 1] * tensor_StrideA[0];
96
+ if (scale_A != nullptr) {
97
+ inputA_scale_ptrs[tid] = tid == 0 ? scale_A : scale_A + offs[tid - 1];
98
+ inputB_scale_ptrs[tid] = scale_B + tid * b_scale_stride;
99
+ }
100
+ output_ptrs[tid] = tid == 0 ? output : output + offs[tid - 1] * ldoutput;
101
+ B_ptrs[tid] = B + tid * tensor_StrideB[0];
102
+ } else if (N < 0) {
103
+ CUDA_KERNEL_ASSERT(offset <= tensor_ShapeB[1] && "expected offset to be less than tensor size\n");
104
+ N = delta;
105
+ lda = a_row_major ? tensor_StrideA[1] : tensor_StrideA[2];
106
+ ldb = b_row_major ? tensor_StrideB[0] : tensor_StrideB[1]; // B is transposed
107
+ ldoutput = tensor_StrideOutput[0];
108
+ A_ptrs[tid] = A + tid * tensor_StrideA[0];
109
+ output_ptrs[tid] = tid == 0 ? output : output + offs[tid - 1];
110
+ B_ptrs[tid] = tid == 0 ? B : B + offs[tid - 1] * tensor_StrideB[1];
111
+ if (scale_A != nullptr) {
112
+ inputA_scale_ptrs[tid] = scale_A + tid * a_scale_stride;
113
+ inputB_scale_ptrs[tid] = tid == 0 ? scale_B : scale_B + offs[tid - 1];
114
+ }
115
+ } else if (K < 0) {
116
+ CUDA_KERNEL_ASSERT(offset <= tensor_ShapeA[1] && offset <= tensor_ShapeB[0] && "expected offset to be less than tensor size\n");
117
+ // A, B is 2d, output is 3d
118
+ K = delta;
119
+ lda = a_row_major ? tensor_StrideA[0] : tensor_StrideA[1];
120
+ ldb = b_row_major ? tensor_StrideB[0] : tensor_StrideB[1];
121
+ ldoutput = tensor_StrideOutput[1];
122
+ A_ptrs[tid] = tid == 0 ? A : A + offs[tid - 1] * tensor_StrideA[1];
123
+ B_ptrs[tid] = tid == 0 ? B : B + offs[tid - 1] * tensor_StrideB[0];
124
+ output_ptrs[tid] = output + tid * tensor_StrideOutput[0];
125
+ if (scale_A != nullptr) {
126
+ inputA_scale_ptrs[tid] = scale_A + tid * M;
127
+ inputB_scale_ptrs[tid] = scale_B + tid * N;
128
+ }
129
+ } else {
130
+ // A, B, output are 3D
131
+ lda = a_row_major ? tensor_StrideA[1] : tensor_StrideA[2];
132
+ ldb = b_row_major ? tensor_StrideB[1] : tensor_StrideB[2];
133
+ ldoutput = tensor_StrideOutput[1];
134
+ A_ptrs[tid] = A + tid * tensor_StrideA[0];
135
+ B_ptrs[tid] = B + tid * tensor_StrideB[0];
136
+ output_ptrs[tid] = output + tid * tensor_StrideOutput[0];
137
+ if (scale_A != nullptr) {
138
+ inputA_scale_ptrs[tid] = scale_A + tid * a_scale_stride;
139
+ inputB_scale_ptrs[tid] = scale_B + tid * b_scale_stride;
140
+ }
141
+ }
142
+ problem_sizes[tid] = ProblemShape(M, N, K);
143
+
144
+ // make_cute_packed_stride only replaces one of the stride elements with
145
+ // one the provided values in the shape arguments
146
+ // the indices of the src/dst depend on whether A/B are row-major
147
+ // so constructing shape argument with two similar lda values
148
+ // while it looks non-sensical (and it is a nonsensical shape)
149
+ // is fine for these stride construction purposes - the one that will be used
150
+ // for replacement is correct, the other one is ignored, and we don't have to
151
+ // branch on whether A/B are row-major
152
+ stride_A[tid] = cutlass::make_cute_packed_stride(StrideA{}, {lda, lda, 1});
153
+ stride_B[tid] = cutlass::make_cute_packed_stride(StrideB{}, {ldb, ldb, 1});
154
+ stride_output[tid] =
155
+ cutlass::make_cute_packed_stride(StrideOutput{}, {M, ldoutput, 1});
156
+ }
157
+ } // namespace at::cuda::detail
158
+
159
+ #else
160
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
161
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/IndexKernel.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ struct TensorIteratorBase;
8
+ class TensorBase;
9
+ }
10
+
11
+ namespace at::native {
12
+ /// @param maskPrefixSum[in,out]
13
+ void launch_masked_scatter_kernel(
14
+ const TensorBase &self, const TensorBase &mask,
15
+ const TensorBase &maskPrefixSum, const TensorBase &source);
16
+ }
17
+
18
+ #else
19
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
20
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/IndexKernelUtils.h ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+
3
+ #include <cstdint>
4
+ #include <ATen/native/TensorIterator.h>
5
+ #include <ATen/native/cuda/MemoryAccess.cuh>
6
+
7
+ namespace at::native {
8
+
9
+ template<int alignment>
10
+ inline bool fast_gather_kernel_eligible(const TensorIterator& iter, char * const out_ptr, char * const in_ptr, const size_t index_stride_bytes, const size_t element_size) {
11
+ using at::native::memory::get_alignment;
12
+ const auto index_element_size = iter.element_size(2);
13
+ //TensorIterator strides and sizes are ordered fastest moving to slowest moving,
14
+ //in contrast to regular sizes
15
+ // we need contiguous source and dst slices and aligned pointers and strides and slice size to do vectorized loads
16
+ // also we need idx to be expanded in the last dimension so we can copy entire slices
17
+ // and we need the src tensor to keep 0 stride from restriding
18
+ // (it could have been deleted by dimension collapse, in this case iterator would still be 2d
19
+ // but we cannot use fast path)
20
+
21
+ return iter.ndim() == 2 && iter.strides(2)[0]==0 && iter.strides(2)[1]==index_element_size &&
22
+ static_cast<size_t>(iter.strides(0)[0])==element_size &&
23
+ static_cast<size_t>(iter.strides(1)[0])==element_size && iter.strides(1)[1] == 0 &&
24
+ get_alignment(out_ptr) == alignment && get_alignment(in_ptr) == alignment &&
25
+ get_alignment(static_cast<size_t>(iter.shape()[0] * element_size)) == alignment &&
26
+ get_alignment(static_cast<size_t>(index_stride_bytes)) == alignment &&
27
+ get_alignment(static_cast<size_t>(iter.strides(0)[1])) == alignment;
28
+ }
29
+
30
+ // For scatter on dim=0: self is restrided (stride[dim]=0), src and index keep original strides.
31
+ // In TensorIterator ordering (fast to slow):
32
+ // dim 0 (slice): self stride = elem_size, src stride = elem_size, index stride = 0
33
+ // dim 1 (index): self stride = 0 (restrided), src stride = D*elem_size, index stride = idx_elem_size
34
+ template<int alignment>
35
+ inline bool fast_scatter_add_kernel_eligible(const TensorIterator& iter, char * const self_ptr, char * const src_ptr, const size_t self_stride_bytes, const size_t element_size) {
36
+ using at::native::memory::get_alignment;
37
+ const auto index_element_size = iter.element_size(2);
38
+ return iter.ndim() == 2 &&
39
+ iter.strides(2)[0] == 0 && iter.strides(2)[1] == index_element_size &&
40
+ static_cast<size_t>(iter.strides(0)[0]) == element_size &&
41
+ static_cast<size_t>(iter.strides(1)[0]) == element_size &&
42
+ iter.strides(0)[1] == 0 &&
43
+ get_alignment(self_ptr) == alignment && get_alignment(src_ptr) == alignment &&
44
+ get_alignment(static_cast<size_t>(iter.shape()[0] * element_size)) == alignment &&
45
+ get_alignment(self_stride_bytes) == alignment &&
46
+ get_alignment(static_cast<size_t>(iter.strides(1)[1])) == alignment;
47
+ }
48
+
49
+ template <int64_t Alignment, typename index_t>
50
+ void vectorized_gather_kernel_launch(char * out, char * inp, index_t * idx, int num_ind,
51
+ int64_t slice_size_in_bytes, int64_t ind_dim_size, int64_t inp_stride_bytes, int64_t out_stride_bytes,
52
+ bool allow_neg_indices=false);
53
+
54
+ template <int64_t Alignment, typename scalar_t, typename index_t>
55
+ void vectorized_scatter_add_kernel_launch(
56
+ scalar_t* self_data, const scalar_t* src_data, index_t* idx, int num_ind,
57
+ int64_t slice_size_in_bytes, int64_t self_dim_size,
58
+ int64_t self_stride_bytes, int64_t src_stride_bytes);
59
+
60
+ template <typename scalar_t, typename index_t>
61
+ void tma_scatter_add_kernel_launch(
62
+ scalar_t* self_data, const scalar_t* src_data, index_t* idx, int num_ind,
63
+ int D, int64_t self_dim_size,
64
+ int64_t self_stride_bytes, int64_t src_stride_bytes);
65
+
66
+ }
67
+
68
+ #else
69
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
70
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/JitLoops.cuh ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/jit_macros.h>
5
+
6
+ #if AT_USE_JITERATOR()
7
+
8
+ #include <ATen/cuda/CUDAConfig.h>
9
+
10
+ #include <ATen/OpMathType.h>
11
+ #include <ATen/TensorIterator.h>
12
+ #include <ATen/native/TensorIteratorDynamicCasting.h>
13
+
14
+ #include <ATen/native/cuda/MemoryAccess.cuh>
15
+
16
+ #include <ATen/native/cuda/CUDAJitLoops.cuh>
17
+
18
+ namespace at::native {
19
+
20
+ /* Note [Jiterator]
21
+ The "jiterator" simply just-in-time compiles the same kernels that
22
+ Loops.cuh (and CUDALoops.cuh) usually build. This reduces build time,
23
+ build size, and initial CUDA context size.
24
+
25
+ By default on non-Windows systems, it also caches compiled kernels in ~/.cache/torch/kernels.
26
+ This behavior is controlled with two environment variables:
27
+ - USE_PYTORCH_KERNEL_CACHE, if set to zero then this will disable all cache use
28
+ - PYTORCH_KERNEL_CACHE_PATH, if set specifies the folder to use for cached kernels
29
+
30
+ The jiterator currently has some limitations, however. It cannot:
31
+ - handle math on complex datatypes
32
+ - handle kernels with scalar parameters
33
+
34
+ These improvements will likely come soon.
35
+
36
+ For examples of how to use the jiterator see the i1 and gcd kernel
37
+ implementations, which pass jittable strings implementing their
38
+ operations instead of the typical CUDA functors.
39
+
40
+ To pass a runtime argument (similar to lambda captures in non-JIT kernels),
41
+ we need to pass to additional arguments to `jitted_gpu_kernel` by value.
42
+ Currently only primitive C++ types used for computation are valid.
43
+ The order of these extra arguments should be same as the order they appear
44
+ in kernel's function signature. (look at polygamma for example)
45
+
46
+ NOTE: One big restriction being that these arguments should be after the
47
+ arguments provided by TensorIterator. Eg. While capturing `n`, where
48
+ `scalar_t x` and `scalar_t y` are provided by TensorIterator,
49
+ * foo(scalar_t x, scalar_t y, int n) works!
50
+ * foo(int n, scalar_t x, scalar_y) doesn't work
51
+ * foo(scalar_t x, int n, scalar_y) doesn't work
52
+
53
+ */
54
+
55
+ // Entrypoint for jitted GPU kernels.
56
+ // Only handles elementwise unary and binary kernels with a
57
+ // common dtype and a single output.
58
+ // NOTE: this assumes the op's iterator has a common_dtype.
59
+ // NOTE: We use std::tuple instead of parameter pack
60
+ // for `extra_args` due to following
61
+ // bug on older versions of clang
62
+ // https://bugs.llvm.org/show_bug.cgi?id=23029
63
+ template <
64
+ char const* name,
65
+ typename return_type,
66
+ typename f_inputs_type,
67
+ int arity,
68
+ typename... Args>
69
+ void jitted_gpu_kernel(
70
+ TensorIteratorBase& iter,
71
+ const std::string& f,
72
+ at::cuda::jit::BinaryFuncVariant scalar_pos =
73
+ at::cuda::jit::BinaryFuncVariant::NoScalar,
74
+ at::opmath_type<f_inputs_type> scalar_val = 0,
75
+ std::tuple<Args...> extra_args = std::make_tuple()) {
76
+ // TODO: much of preamble is common to both jitted_gpu_kernel and gpu_kernel
77
+ // Maybe it could be refactored?
78
+ for (int arg = 0; arg < iter.ntensors(); arg++) {
79
+ TORCH_INTERNAL_ASSERT(
80
+ iter.device(arg).is_cuda(),
81
+ "argument ", arg, ": expected a CUDA device but found ", iter.device(arg));
82
+ }
83
+
84
+ if (iter.numel() == 0) {
85
+ return;
86
+ }
87
+
88
+ if (!iter.can_use_32bit_indexing()) {
89
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
90
+ jitted_gpu_kernel<name, return_type, f_inputs_type, arity>(
91
+ sub_iter, f, scalar_pos, scalar_val, extra_args);
92
+ }
93
+
94
+ return;
95
+ }
96
+
97
+ // Computes if dynamic casting is needed
98
+ // Dynamic casting is needed if an input's dtype differs from the common dtype
99
+ // or if the result dtype differs from the output's dtype
100
+ // Note: this is intentionally divergent from calling needs_dynamic_casting,
101
+ // which is more general and inspects a lambda to determine if dynamic
102
+ // casting is needed.
103
+ bool needs_dynamic_casting = false;
104
+
105
+ // Checks output
106
+ const ScalarType return_scalar_type = c10::CppTypeToScalarType<return_type>::value;
107
+ const auto dtype0 = iter.dtype(0);
108
+ if (dtype0 != return_scalar_type) {
109
+ needs_dynamic_casting = true;
110
+ }
111
+
112
+ // Checks input(s)
113
+ const ScalarType inputs_scalar_type = c10::CppTypeToScalarType<f_inputs_type>::value;
114
+ for (auto i = decltype(arity){1}; i < (arity + 1); ++i) {
115
+ const auto dtypei = iter.dtype(i);
116
+ if (dtypei != inputs_scalar_type) {
117
+ needs_dynamic_casting = true;
118
+ break;
119
+ }
120
+ }
121
+ if (scalar_pos == at::cuda::jit::BinaryFuncVariant::NoScalar) {
122
+ // NOTE: With `scalar_pos=NoScalar`,`scalar_val` is not used
123
+ // for computation in the generated code and hence we pass a dummy
124
+ // value of `0`.
125
+ jitted_gpu_kernel_impl<
126
+ /*name*/ name,
127
+ /*return_type=*/return_type,
128
+ /*f_inputs_type=*/f_inputs_type,
129
+ arity,
130
+ at::cuda::jit::BinaryFuncVariant::NoScalar>(
131
+ iter, f, needs_dynamic_casting, /*scalar_val=*/scalar_val, extra_args);
132
+ } else if (scalar_pos == at::cuda::jit::BinaryFuncVariant::RhsScalar) {
133
+ jitted_gpu_kernel_impl<
134
+ /*name*/ name,
135
+ /*return_type=*/return_type,
136
+ /*f_inputs_type=*/f_inputs_type,
137
+ arity,
138
+ at::cuda::jit::BinaryFuncVariant::RhsScalar>(
139
+ iter,
140
+ f,
141
+ needs_dynamic_casting,
142
+ scalar_val,
143
+ extra_args);
144
+
145
+ } else {
146
+ jitted_gpu_kernel_impl<
147
+ /*name*/ name,
148
+ /*return_type=*/return_type,
149
+ /*f_inputs_type=*/f_inputs_type,
150
+ arity,
151
+ at::cuda::jit::BinaryFuncVariant::LhsScalar>(
152
+ iter,
153
+ f,
154
+ needs_dynamic_casting,
155
+ scalar_val,
156
+ extra_args);
157
+ }
158
+ }
159
+
160
+ // TODO: support runtime state capture similar to `jitted_gpu_kernel`.
161
+ template <char const *name, typename return_type, typename f_inputs_type>
162
+ void opmath_jitted_gpu_kernel_with_scalars(TensorIteratorBase& iter, const std::string& f) {
163
+ TORCH_INTERNAL_ASSERT(iter.ntensors() == 3);
164
+ //currently jiterator only handles binary functions where both inputs are of the same type (f_inputs_type)
165
+ using opmath_t = at::opmath_type<f_inputs_type>;
166
+ if (iter.is_cpu_scalar(1)) {
167
+ auto scalar_val = iter.scalar_value<opmath_t>(1);
168
+ iter.remove_operand(1);
169
+ // TODO: When all kernels that use gpu_kernel_with_scalars are
170
+ // ported to structured, this device guard can be deleted. This
171
+ // works around incorrect device guard generation for pre-structured
172
+ // kernels device guards, but structured kernels do it right and
173
+ // we can assume the device is already set correctly
174
+ const OptionalDeviceGuard device_guard(iter.device(1));
175
+ jitted_gpu_kernel<name, return_type, f_inputs_type, 1>(iter, f, at::cuda::jit::BinaryFuncVariant::LhsScalar, scalar_val);
176
+ } else if (iter.is_cpu_scalar(2)) {
177
+ auto scalar_val = iter.scalar_value<opmath_t>(2);
178
+ iter.remove_operand(2);
179
+ jitted_gpu_kernel<name, return_type, f_inputs_type, 1>(iter, f, at::cuda::jit::BinaryFuncVariant::RhsScalar, scalar_val);
180
+ } else {
181
+ jitted_gpu_kernel<name, return_type, f_inputs_type, 2>(iter, f);
182
+ }
183
+ }
184
+
185
+ } // namespace at::native
186
+
187
+ #endif // AT_USE_JITERATOR()
188
+
189
+ #else
190
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
191
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/KernelUtils.cuh ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/headeronly/cuda/Atomic.h>
4
+ #include <torch/headeronly/cuda/KernelUtils.h>
5
+
6
+ #if !(defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))))
7
+ #include <cuda_bf16.h>
8
+ #endif
9
+
10
+ #if defined(USE_ROCM)
11
+ #include <device_functions.h>
12
+ #include <hip/hip_bf16.h>
13
+ #include <hip/hip_fp16.h>
14
+
15
+ #include <torch/headeronly/cuda/detail/ROCmMacros.h>
16
+ #endif
17
+
18
+ namespace at::native {
19
+
20
+ using torch::headeronly::fastAtomicAdd;
21
+ using torch::headeronly::fastSpecializedAtomicAdd;
22
+
23
+ __device__ __forceinline__ size_t
24
+ idx(const size_t nc,
25
+ const size_t height,
26
+ const size_t width,
27
+ const size_t h,
28
+ const size_t w) {
29
+ return (nc * height + h) * width + w;
30
+ }
31
+
32
+ // for channels-last
33
+ template <typename index_t = size_t>
34
+ __device__ __forceinline__ index_t idx_cl(
35
+ const index_t n,
36
+ const index_t h,
37
+ const index_t w,
38
+ const index_t c,
39
+ const index_t height,
40
+ const index_t width,
41
+ const index_t channel) {
42
+ return ((n * height + h) * width + w) * channel + c;
43
+ }
44
+
45
+ #ifdef USE_ROCM
46
+ // This function implements a committed store.
47
+ // Upon returning, the store is committed to global memory.
48
+ // This is useful in avoiding the need for fences.
49
+ // If multiple stores are done in a row there is option to skip
50
+ // waiting for commit for all but the last store.
51
+ template <typename T, bool wait_for_commit = true>
52
+ __device__ inline void cmtdStore(void* address, T value) {
53
+ int constexpr num_long_per_val = sizeof(value) / sizeof(long);
54
+ int constexpr num_int_per_val = sizeof(value) / sizeof(int);
55
+ int constexpr num_short_per_val = sizeof(value) / sizeof(short);
56
+ int constexpr num_char_per_val = sizeof(value) / sizeof(char);
57
+ union pnr {
58
+ T v;
59
+ long l[num_long_per_val];
60
+ int i[num_int_per_val];
61
+ short s[num_short_per_val];
62
+ char c[num_char_per_val];
63
+ } _pnr = {.v = value};
64
+ if constexpr (num_long_per_val * sizeof(long) == sizeof(value))
65
+ for (int i = 0; i < num_long_per_val; i++)
66
+ __hip_atomic_store(
67
+ reinterpret_cast<long*>(address) + i,
68
+ _pnr.l[i],
69
+ __ATOMIC_RELAXED,
70
+ __HIP_MEMORY_SCOPE_AGENT);
71
+ else if constexpr (num_int_per_val * sizeof(int) == sizeof(value))
72
+ for (int i = 0; i < num_int_per_val; i++)
73
+ __hip_atomic_store(
74
+ reinterpret_cast<int*>(address) + i,
75
+ _pnr.i[i],
76
+ __ATOMIC_RELAXED,
77
+ __HIP_MEMORY_SCOPE_AGENT);
78
+ else if constexpr (num_short_per_val * sizeof(short) == sizeof(value))
79
+ for (int i = 0; i < num_short_per_val; i++)
80
+ __hip_atomic_store(
81
+ reinterpret_cast<short*>(address) + i,
82
+ _pnr.s[i],
83
+ __ATOMIC_RELAXED,
84
+ __HIP_MEMORY_SCOPE_AGENT);
85
+ else if constexpr (num_char_per_val * sizeof(char) == sizeof(value))
86
+ for (int i = 0; i < num_char_per_val; i++)
87
+ __hip_atomic_store(
88
+ reinterpret_cast<char*>(address) + i,
89
+ _pnr.c[i],
90
+ __ATOMIC_RELAXED,
91
+ __HIP_MEMORY_SCOPE_AGENT);
92
+ if constexpr (wait_for_commit) {
93
+ __atomic_signal_fence(__ATOMIC_SEQ_CST);
94
+ #if defined(__GFX12__)
95
+ asm volatile("s_wait_storecnt(0)" ::: "memory");
96
+ #elif defined(__GFX10__) || defined(__GFX11__)
97
+ asm volatile("s_waitcnt_vscnt null, 0" ::: "memory");
98
+ #else
99
+ // Older architectures have only 'vmcnt' counter.
100
+ asm volatile("s_waitcnt vmcnt(0)" ::: "memory");
101
+ #endif
102
+ __atomic_signal_fence(__ATOMIC_SEQ_CST);
103
+ }
104
+ }
105
+
106
+ // This function implements warp-level opportunistic fastatomics
107
+ // To reduce contention on an atomicAdd, this replaces per-thread atomicAdd with
108
+ // a per-warp atomicAdd. We identify all the threads within a warp that will
109
+ // perform an atomicAdd on the same destination address and perform the addition
110
+ // on the CU. Each warp elects a leader thread which does the atomicAdd to the
111
+ // destination address.
112
+ template <class scalar_t, class index_t>
113
+ __device__ __forceinline__ void opportunistic_fastAtomicAdd(
114
+ scalar_t* self_ptr,
115
+ index_t index,
116
+ const index_t numel,
117
+ scalar_t value) {
118
+ // TODO: move the builtin checks around the point-of-use, and implement a
119
+ // fallback for their absence, so as to allow targets that implement a
120
+ // subset to derive some benefit at least
121
+ if (!__builtin_amdgcn_is_invocable(__builtin_amdgcn_mov_dpp) ||
122
+ !__builtin_amdgcn_is_invocable(
123
+ __builtin_amdgcn_flat_atomic_fadd_v2bf16) ||
124
+ !__builtin_amdgcn_is_invocable(__builtin_amdgcn_flat_atomic_fadd_v2f16))
125
+ return;
126
+ scalar_t* dst = self_ptr + index;
127
+
128
+ // pack coalesced bf16 and fp16
129
+ if constexpr (
130
+ std::is_same<scalar_t, c10::BFloat16>::value ||
131
+ std::is_same<scalar_t, c10::Half>::value) {
132
+ typedef unsigned short __attribute__((ext_vector_type(2))) vec_short2;
133
+ union ill {
134
+ unsigned int i[2];
135
+ int64_t il;
136
+ };
137
+ ill iil_, ill_oneUpDst = {};
138
+ iil_.il = (int64_t)dst;
139
+ ill_oneUpDst.i[0] = __builtin_amdgcn_mov_dpp(iil_.i[0], 0x130, 0xf, 0xf, 0);
140
+ ill_oneUpDst.i[1] = __builtin_amdgcn_mov_dpp(iil_.i[1], 0x130, 0xf, 0xf, 0);
141
+ union bfi {
142
+ scalar_t bf;
143
+ short s;
144
+ } bfi_ = {.bf = value};
145
+ bfi bfi_oneUpVal;
146
+
147
+ bfi_oneUpVal.s = __builtin_amdgcn_mov_dpp(bfi_.s, 0x130, 0xf, 0xf, 0);
148
+ auto oneUpVal = bfi_oneUpVal.bf;
149
+
150
+ __half* target_addr = reinterpret_cast<__half*>(self_ptr + index);
151
+ bool low_byte =
152
+ (reinterpret_cast<std::uintptr_t>(target_addr) % sizeof(__half2) == 0);
153
+ bool canCombnUp = (bool)(__activemask() & (1 << (threadIdx.x + 1))) &&
154
+ (low_byte && index < (numel - 1)) &&
155
+ (ill_oneUpDst.il - reinterpret_cast<int64_t>(dst) == sizeof(scalar_t));
156
+ bool canCombnDn =
157
+ (__builtin_amdgcn_mov_dpp(canCombnUp, 0x138, 0xf, 0xf, 0));
158
+
159
+ if (__lane_id() % 2 == 0) {
160
+ if (canCombnUp) {
161
+ typedef _Float16 __attribute__((ext_vector_type(2))) vec_fp162;
162
+ union bfvs {
163
+ scalar_t bf[2];
164
+ vec_short2 vs2;
165
+ vec_fp162 df16;
166
+ };
167
+ bfvs bfvs_ = {};
168
+ bfvs_.bf[0] = value;
169
+ bfvs_.bf[1] = oneUpVal;
170
+ if constexpr (std::is_same<scalar_t, c10::BFloat16>::value)
171
+ __builtin_amdgcn_flat_atomic_fadd_v2bf16((vec_short2*)dst, bfvs_.vs2);
172
+ else
173
+ __builtin_amdgcn_flat_atomic_fadd_v2f16((__half2*)dst, bfvs_.df16);
174
+ return;
175
+ }
176
+ } else {
177
+ if (canCombnDn)
178
+ return;
179
+ }
180
+ }
181
+
182
+ // not coalesced, so now let try to capture lane-matches...
183
+
184
+ if (numel > 16 /*<-hueristic threshold*/ * 64) {
185
+ // well shucks, unlikely to capture same-dest atomics in a wave.
186
+ // fall back to direct fastAtomic...
187
+ fastAtomicAdd(self_ptr, index, numel, value, true);
188
+ return;
189
+ }
190
+
191
+ // __activemask() -- finds the set of threads in the warp that are about to
192
+ // perform atomicAdd
193
+ // __match_any_sync() -- returns bit mask of the threads that have same dest
194
+ // addr
195
+ auto mask = __match_any_sync(__activemask(), (int64_t)dst);
196
+
197
+ // select a leader thread
198
+ int leader = __ffsll(mask) - 1;
199
+
200
+ scalar_t crnt_val = (scalar_t)0;
201
+ auto crnt_msk = mask >> (leader);
202
+ int crnt_idx = leader;
203
+
204
+ // __shfl is limited in the dtypes it accepts
205
+ // That's why, we need these if/else to correctly do the addition on the CU
206
+ if constexpr (sizeof(scalar_t) <= sizeof(int)) {
207
+ union punner {
208
+ int l;
209
+ scalar_t s;
210
+ };
211
+ punner pnr = {};
212
+ pnr.s = value;
213
+ while (crnt_msk != 0) {
214
+ if (crnt_msk & 1) {
215
+ punner add_val = {};
216
+ add_val.l = __shfl(pnr.l, crnt_idx);
217
+ crnt_val += add_val.s;
218
+ }
219
+ crnt_idx++;
220
+ crnt_msk = crnt_msk >> 1;
221
+ }
222
+ } else if constexpr (sizeof(scalar_t) <= sizeof(long)) {
223
+ union punner {
224
+ long l;
225
+ scalar_t s;
226
+ };
227
+ punner pnr = {};
228
+ pnr.s = value;
229
+ while (crnt_msk != 0) {
230
+ if (crnt_msk & 1) {
231
+ punner add_val = {};
232
+ add_val.l = __shfl(pnr.l, crnt_idx);
233
+ crnt_val += add_val.s;
234
+ }
235
+ crnt_idx++;
236
+ crnt_msk = crnt_msk >> 1;
237
+ }
238
+ } else if constexpr (sizeof(scalar_t) <= sizeof(long long)) {
239
+ union punner {
240
+ long long l;
241
+ scalar_t s;
242
+ };
243
+ punner pnr = {};
244
+ pnr.s = value;
245
+ while (crnt_msk != 0) {
246
+ if (crnt_msk & 1) {
247
+ punner add_val = {};
248
+ add_val.l = __shfl(pnr.l, crnt_idx);
249
+ crnt_val += add_val.s;
250
+ }
251
+ crnt_idx++;
252
+ crnt_msk = crnt_msk >> 1;
253
+ }
254
+ } else {
255
+ union punner {
256
+ long long l[2];
257
+ scalar_t s;
258
+ };
259
+ punner pnr = {};
260
+ pnr.s = value;
261
+ while (crnt_msk != 0) {
262
+ if (crnt_msk & 1) {
263
+ punner add_val = {};
264
+ add_val.l[0] = __shfl(pnr.l[0], crnt_idx);
265
+ add_val.l[1] = __shfl(pnr.l[1], crnt_idx);
266
+ crnt_val += add_val.s;
267
+ }
268
+ crnt_idx++;
269
+ crnt_msk = crnt_msk >> 1;
270
+ }
271
+ }
272
+
273
+ // Once the correct crnt_val is determined, only the leader thread does the
274
+ // update to the dest addr
275
+ if (__lane_id() == leader) {
276
+ fastAtomicAdd(self_ptr, index, numel, crnt_val, true);
277
+ }
278
+ }
279
+ #endif
280
+
281
+ } // namespace at::native
282
+
283
+ #else
284
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
285
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/LaunchUtils.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <algorithm>
4
+
5
+ namespace at::native {
6
+
7
+ // returns 2**floor(log2(n))
8
+ static int lastPow2(unsigned int n) {
9
+ n |= (n >> 1);
10
+ n |= (n >> 2);
11
+ n |= (n >> 4);
12
+ n |= (n >> 8);
13
+ n |= (n >> 16);
14
+ return std::max<int>(1, n - (n >> 1));
15
+ }
16
+
17
+ } // namespace at::native
18
+
19
+ #else
20
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
21
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Loops.cuh ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
6
+ #include <ATen/detail/FunctionTraits.h>
7
+ #include <ATen/native/TensorIterator.h>
8
+ #include <ATen/native/TensorIteratorDynamicCasting.h>
9
+ #include <ATen/native/cuda/thread_constants.h>
10
+ #include <ATen/native/cuda/MemoryAccess.cuh>
11
+
12
+ #include <c10/util/C++17.h>
13
+ #include <tuple>
14
+
15
+
16
+
17
+ namespace at::native {
18
+
19
+ template<int N>
20
+ static OffsetCalculator<N> make_input_offset_calculator(const TensorIteratorBase& iter) {
21
+ // array size can not be 0, this happens when N == 0
22
+ constexpr int array_size = std::max<int>(N, 1);
23
+ TORCH_INTERNAL_ASSERT(N == iter.ntensors() - iter.noutputs());
24
+ std::array<const int64_t*, array_size> strides;
25
+ int64_t element_sizes[array_size];
26
+ for (int i = 0; i < N; i++) {
27
+ strides[i] = iter.strides(i + iter.noutputs()).data();
28
+ element_sizes[i] = iter.element_size(i + iter.noutputs());
29
+ }
30
+ return OffsetCalculator<N>(iter.ndim(), iter.shape().data(), strides.data(), element_sizes);
31
+ }
32
+
33
+ template <int num_outputs = 1>
34
+ static OffsetCalculator<num_outputs> make_output_offset_calculator(const TensorIteratorBase& iter) {
35
+ TORCH_INTERNAL_ASSERT(num_outputs == iter.noutputs());
36
+ std::array<const int64_t*, num_outputs> strides;
37
+ int64_t element_sizes[num_outputs];
38
+ for (int i = 0; i < num_outputs; i++) {
39
+ strides[i] = iter.strides(i).data();
40
+ element_sizes[i] = iter.element_size(i);
41
+ }
42
+ return OffsetCalculator<num_outputs>(iter.ndim(), iter.shape().data(), strides.data(), element_sizes);
43
+ }
44
+
45
+ template <bool reverted_idx = false, typename func_t, typename policy_t>
46
+ __device__ inline void elementwise_kernel_helper(func_t f, policy_t policy) {
47
+ using traits = function_traits<func_t>;
48
+ using return_t = typename traits::result_type;
49
+ using args_t = typename traits::ArgsTuple;
50
+ constexpr int elems_per_thread = policy_t::tws;
51
+
52
+ int idx = blockIdx.x;
53
+ if constexpr (reverted_idx)
54
+ idx = gridDim.x - blockIdx.x - 1;
55
+
56
+ return_t results[elems_per_thread];
57
+ args_t args[elems_per_thread];
58
+
59
+ // load
60
+ policy.load(args, idx);
61
+
62
+ // compute
63
+ #pragma unroll
64
+ for (int i = 0; i < elems_per_thread; i++) {
65
+ if (policy.check_inbounds(i)) {
66
+ #if defined(__HIP__)
67
+ results[i] = c10::guts::apply(f, args[i]);
68
+ #else
69
+ results[i] = std::apply(f, args[i]);
70
+ #endif
71
+ }
72
+ }
73
+
74
+ // store
75
+ policy.store(results, idx);
76
+ }
77
+
78
+ } // namespace at::native
79
+
80
+ #include <ATen/native/cuda/CUDALoops.cuh>
81
+
82
+ namespace at:: native {
83
+
84
+ template <typename func_t>
85
+ void gpu_kernel_nocast(TensorIteratorBase& iter, const func_t& f, bool check_cast = true) {
86
+
87
+ for (int arg = 0; arg < iter.ntensors(); arg++) {
88
+ TORCH_INTERNAL_ASSERT(
89
+ iter.device(arg).is_cuda(),
90
+ "argument ", arg, ": expected a CUDA device but found ", iter.device(arg));
91
+ }
92
+
93
+ if (iter.numel() == 0) {
94
+ return;
95
+ }
96
+
97
+ if (!iter.can_use_32bit_indexing()) {
98
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
99
+ gpu_kernel_nocast(sub_iter, f, check_cast);
100
+ }
101
+ return;
102
+ }
103
+
104
+ if (check_cast) {
105
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
106
+ }
107
+ gpu_kernel_impl_nocast(iter, f);
108
+ }
109
+
110
+ template <typename func_t>
111
+ void gpu_kernel_opaque(TensorIteratorBase& iter, const func_t& f) {
112
+ gpu_kernel_nocast(iter, f, false);
113
+ }
114
+
115
+ template <typename func_t>
116
+ void gpu_kernel(TensorIteratorBase& iter, const func_t& f) {
117
+
118
+ for (int arg = 0; arg < iter.ntensors(); arg++) {
119
+ TORCH_INTERNAL_ASSERT(
120
+ iter.device(arg).is_cuda(),
121
+ "argument ", arg, ": expected a CUDA device but found ", iter.device(arg));
122
+ }
123
+
124
+ if (iter.numel() == 0) {
125
+ return;
126
+ }
127
+
128
+ if (!iter.can_use_32bit_indexing()) {
129
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
130
+ gpu_kernel(sub_iter, f);
131
+ }
132
+ return;
133
+ }
134
+
135
+ gpu_kernel_impl(iter, f);
136
+ }
137
+
138
+ template<typename arg1_t, typename arg2_t, typename return_t, typename func_t>
139
+ struct AUnaryFunctor {
140
+ using traits = function_traits<func_t>;
141
+ using opmath_arg1_t = typename traits::template arg<0>::type;
142
+ __device__ return_t operator()(arg2_t b) const {
143
+ return f(a, b);
144
+ }
145
+ // NB: scalar is stored in higher precision!
146
+ AUnaryFunctor(func_t f_, opmath_arg1_t a_): f(f_), a(a_) {}
147
+ private:
148
+ func_t f;
149
+ opmath_arg1_t a;
150
+ };
151
+
152
+ template<typename arg1_t, typename arg2_t, typename return_t, typename func_t>
153
+ struct BUnaryFunctor {
154
+ using traits = function_traits<func_t>;
155
+ using opmath_arg2_t = typename traits::template arg<1>::type;
156
+ __device__ return_t operator()(arg1_t a) const {
157
+ return f(a, b);
158
+ }
159
+ // NB: scalar is stored in higher precision!
160
+ BUnaryFunctor(func_t f_, opmath_arg2_t b_): f(f_), b(b_) {}
161
+ private:
162
+ func_t f;
163
+ opmath_arg2_t b;
164
+ };
165
+
166
+ // Though seemingly noop, this inserts casts from arg1_t to func_t's type
167
+ // (which may be higher precision), as well as casts to return_t
168
+ template <typename arg1_t, typename arg2_t, typename return_t, typename func_t>
169
+ struct BinaryFunctor {
170
+ __device__ return_t operator()(arg1_t a, arg2_t b) const {
171
+ return f(a, b);
172
+ }
173
+ BinaryFunctor(func_t f_): f(f_) {}
174
+ private:
175
+ func_t f;
176
+ };
177
+
178
+ // Unlike gpu_kernel_with_scalars, this allows you to pass a func_t which
179
+ // accepts inputs at higher precision (typically opmath_t), but then
180
+ // ensure that we load from memory at the correct precision (scalar_t)
181
+ // to avoid expensive loads. For the whole sordid story see
182
+ // https://dev-discuss.pytorch.org/t/cuda-loops-case-study-code-generation-vs-templates/302
183
+ template <typename arg1_t, typename arg2_t = arg1_t, typename return_t = arg1_t, typename func_t>
184
+ void opmath_gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) {
185
+ TORCH_INTERNAL_ASSERT(iter.ntensors() == 3);
186
+
187
+ using traits = function_traits<func_t>;
188
+ using opmath_arg1_t = typename traits::template arg<0>::type;
189
+ using opmath_arg2_t = typename traits::template arg<1>::type;
190
+ static_assert(
191
+ traits::arity == 2,
192
+ "gpu_kernel_with_scalars only supports two input arguments");
193
+
194
+ if (iter.is_cpu_scalar(1)) {
195
+ AUnaryFunctor<arg1_t, arg2_t, return_t, func_t> af(f, iter.scalar_value<opmath_arg1_t>(1));
196
+ iter.remove_operand(1);
197
+ // TODO: When all kernels that use gpu_kernel_with_scalars are
198
+ // ported to structured, this device guard can be deleted. This
199
+ // works around incorrect device guard generation for pre-structured
200
+ // kernels device guards, but structured kernels do it right and
201
+ // we can assume the device is already set correctly
202
+ const OptionalDeviceGuard device_guard(iter.device(1));
203
+ gpu_kernel(iter, af);
204
+ } else if (iter.is_cpu_scalar(2)) {
205
+ BUnaryFunctor<arg1_t, arg2_t, return_t, func_t> bf(f, iter.scalar_value<opmath_arg2_t>(2));
206
+ iter.remove_operand(2);
207
+ gpu_kernel(iter, bf);
208
+ } else {
209
+ gpu_kernel(iter, BinaryFunctor<arg1_t, arg2_t, return_t, func_t>(f));
210
+ }
211
+ }
212
+
213
+ template <typename scalar_t, typename return_t = scalar_t, typename func_t>
214
+ void opmath_symmetric_gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) {
215
+ // Use symmetric property of the functor to reduce number of kernels,
216
+ // requires f(a, b) == f(b, a)
217
+ TORCH_INTERNAL_ASSERT(iter.ntensors() == 3);
218
+
219
+ using traits = function_traits<func_t>;
220
+ using opmath_arg_t = typename traits::template arg<0>::type;
221
+ static_assert(
222
+ traits::arity == 2,
223
+ "gpu_kernel_with_scalars only supports two input arguments");
224
+ static_assert(std::is_same_v<opmath_arg_t, typename traits::template arg<1>::type>,
225
+ "f is not symmetric");
226
+
227
+ OptionalDeviceGuard device_guard;
228
+ opmath_arg_t scalar_val{};
229
+
230
+ if (iter.is_cpu_scalar(1)) {
231
+ scalar_val = iter.scalar_value<opmath_arg_t>(1);
232
+ iter.remove_operand(1);
233
+
234
+ // TODO: When all kernels that use gpu_kernel_with_scalars are
235
+ // ported to structured, this device guard can be deleted. This
236
+ // works around incorrect device guard generation for pre-structured
237
+ // kernels device guards, but structured kernels do it right and
238
+ // we can assume the device is already set correctly
239
+ device_guard.reset_device(iter.device(1));
240
+ } else if (iter.is_cpu_scalar(2)) {
241
+ scalar_val = iter.scalar_value<opmath_arg_t>(2);
242
+ iter.remove_operand(2);
243
+ }
244
+
245
+ if (iter.ninputs() == 2) {
246
+ gpu_kernel(iter, BinaryFunctor<scalar_t, scalar_t, return_t, func_t>(f));
247
+ } else {
248
+ AUnaryFunctor<scalar_t, scalar_t, return_t, func_t> unary_f(f, scalar_val);
249
+ gpu_kernel(iter, unary_f);
250
+ }
251
+ }
252
+
253
+ // Legacy variant that assumes that func_t has the correct types
254
+ // that we expect to load from memory
255
+ template <typename func_t>
256
+ void gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) {
257
+ using traits = function_traits<func_t>;
258
+ static_assert(
259
+ traits::arity == 2,
260
+ "gpu_kernel_with_scalars only supports two input arguments");
261
+ using arg1_t = typename traits::template arg<0>::type;
262
+ using arg2_t = typename traits::template arg<1>::type;
263
+ using return_t = typename traits::result_type;
264
+ opmath_gpu_kernel_with_scalars<arg1_t, arg2_t, return_t, func_t>(iter, f);
265
+ }
266
+
267
+ namespace { // functions for `gpu_kernel_multiple_outputs`.
268
+
269
+ // check the return type is `thrust::tuple`, not `std::tuple`.
270
+ template <typename T> struct is_tuple: std::false_type {};
271
+
272
+ template <typename ...T> struct is_tuple<thrust::tuple<T...>>: std::true_type {};
273
+
274
+ template <int num_outputs, typename func_t, typename array_t, typename inp_calc_t, typename out_calc_t>
275
+ C10_LAUNCH_BOUNDS_1(num_threads())
276
+ __global__ void unrolled_elementwise_kernel_for_multi_outputs(int N, func_t f, array_t data, inp_calc_t ic, out_calc_t oc) {
277
+ int remaining = N - block_work_size() * blockIdx.x;
278
+ elementwise_kernel_helper(f, memory::policies::multi_outputs_unroll<array_t, inp_calc_t, out_calc_t, num_outputs>(data, remaining, ic, oc));
279
+ }
280
+
281
+ template <int num_outputs, typename func_t, typename array_t, typename inp_calc_t, typename out_calc_t>
282
+ static inline void launch_unrolled_kernel_for_multi_outputs(int64_t N, const func_t& f, array_t data, inp_calc_t ic, out_calc_t oc) {
283
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
284
+ int64_t grid = (N + block_work_size() - 1) / block_work_size();
285
+ auto stream = at::cuda::getCurrentCUDAStream();
286
+ unrolled_elementwise_kernel_for_multi_outputs<num_outputs, func_t, array_t><<<grid, num_threads(), 0, stream>>>(N, f, data, ic, oc);
287
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
288
+ }
289
+
290
+ template <typename func_t>
291
+ void gpu_kernel_multiple_outputs_impl(TensorIteratorBase& iter, const func_t& f) {
292
+ using traits = function_traits<func_t>;
293
+ using output_t = typename traits::result_type;
294
+ static_assert(is_tuple<output_t>::value, "f's return type must be `thrust::tuple`");
295
+ constexpr int num_outputs = thrust::tuple_size<output_t>::value;
296
+ constexpr int num_inputs = traits::arity;
297
+ constexpr int ntensors = num_outputs + num_inputs;
298
+
299
+ TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
300
+ TORCH_INTERNAL_ASSERT(iter.ntensors() == ntensors);
301
+
302
+ std::array<char*, ntensors> data;
303
+ for (int i = 0; i < ntensors; i++) {
304
+ data[i] = (char*)iter.data_ptr(i);
305
+ }
306
+
307
+ int64_t numel = iter.numel();
308
+
309
+ if (iter.is_contiguous()) {
310
+ auto input_calc = TrivialOffsetCalculator<num_inputs>();
311
+ auto output_calc = TrivialOffsetCalculator<num_outputs>();
312
+ launch_unrolled_kernel_for_multi_outputs<num_outputs>(numel, f, data, input_calc, output_calc);
313
+ } else {
314
+ auto input_calc = make_input_offset_calculator<num_inputs>(iter);
315
+ auto output_calc = make_output_offset_calculator<num_outputs>(iter);
316
+ launch_unrolled_kernel_for_multi_outputs<num_outputs>(numel, f, data, input_calc, output_calc);
317
+ }
318
+ }
319
+ } // namespace
320
+
321
+ template <typename func_t>
322
+ void gpu_kernel_multiple_outputs(TensorIteratorBase& iter, const func_t& f) {
323
+ ASSERT_HOST_DEVICE_LAMBDA(func_t);
324
+
325
+ for (int arg = 0; arg < iter.ntensors(); arg++) {
326
+ TORCH_INTERNAL_ASSERT(iter.device(arg).is_cuda());
327
+ }
328
+
329
+ if (iter.numel() == 0) {
330
+ return;
331
+ }
332
+
333
+ if (!iter.can_use_32bit_indexing()) {
334
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
335
+ gpu_kernel_multiple_outputs(sub_iter, f);
336
+ }
337
+ return;
338
+ }
339
+
340
+ gpu_kernel_multiple_outputs_impl(iter, f);
341
+ }
342
+
343
+ } //namespace at::native
344
+
345
+ #else
346
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
347
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Math.cuh ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MemoryAccess.cuh ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <cstdint>
6
+ #include <type_traits>
7
+ #include <c10/core/DynamicCast.h>
8
+ #include <c10/util/Exception.h>
9
+ #include <c10/util/TypeCast.h>
10
+ #include <c10/macros/Macros.h>
11
+ #include <ATen/detail/FunctionTraits.h>
12
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
13
+ #include <ATen/native/cuda/thread_constants.h>
14
+
15
+ #include <thrust/tuple.h>
16
+
17
+ #ifdef USE_ROCM
18
+ #include <ATen/cuda/detail/ROCmMacros.cuh>
19
+ #endif
20
+
21
+ // References:
22
+ // https://devblogs.nvidia.com/cuda-pro-tip-increase-performance-with-vectorized-memory-access/
23
+
24
+ namespace at::native::memory {
25
+
26
+ namespace detail {
27
+
28
+ // What does the `static_unroll` do?
29
+ //
30
+ // We want to do something like:
31
+ //
32
+ // using args_t = typename traits::ArgsTuple;
33
+ // args_t args;
34
+ // #pragma unroll
35
+ // for (int i = 0; i < traits::arity; i++) {
36
+ // std::get<i>(args) = ....
37
+ // }
38
+ //
39
+ // but unfortunately the above code does not work because
40
+ // the template argument has to be a compile time constant
41
+ // so `static_unroll` is created to simulate `#pragma unroll`
42
+ // using template metaprogramming.
43
+
44
+ template<template<int i> typename func, int end, int current=0>
45
+ struct static_unroll {
46
+ template<typename... Args>
47
+ static inline C10_HOST_DEVICE void with_args(Args&&... args) {
48
+ func<current>::apply(std::forward<Args>(args)...);
49
+ static_unroll<func, end, current+1>::with_args(args...);
50
+ }
51
+ };
52
+
53
+ template<template<int i> typename func, int end>
54
+ struct static_unroll<func, end, end> {
55
+ template<typename... Args>
56
+ static inline C10_HOST_DEVICE void with_args(Args... /*args*/) {}
57
+ };
58
+
59
+ // helper structs to be used with static_unroll to load arguments
60
+ // one by one
61
+
62
+ template<int arg_index>
63
+ struct vectorized_load_helper {
64
+ template <typename args_t, typename policy_t>
65
+ static __device__ void apply(policy_t &self, args_t *args, int idx, int block_work_size) {
66
+ using arg_t = std::tuple_element_t<arg_index, args_t>;
67
+ // `data` hold the data_ptr for tensors [output, input0, input1, ...], so we
68
+ // need a +1 offset to get the input
69
+ auto ptr = reinterpret_cast<arg_t *>(self.data[arg_index + 1]) + block_work_size * idx;
70
+ auto args_accessor = [&args] __device__ (int thread_unroll_idx) -> arg_t & { return std::get<arg_index>(args[thread_unroll_idx]); };
71
+ self.load_single_arg(args_accessor, ptr);
72
+ }
73
+ };
74
+
75
+ #ifdef USE_ROCM
76
+ // Templated version of vectorized load helper.
77
+ // It can be used on heterogeneous input tensor element types.
78
+ template <int arg_index>
79
+ struct vectorized_templated_load_helper {
80
+ template <typename args_t, typename policy_t>
81
+ static __device__ void apply(policy_t& self, args_t* args, int idx) {
82
+ using arg_t = std::tuple_element_t<arg_index, args_t>;
83
+ // `data` hold the data_ptr for tensors [output, input0, input1, ...], so we
84
+ // need a +1 offset to get the input
85
+
86
+ // Delay pointer arithmetic to the policy loader where we know the actual
87
+ // type of the current argument.
88
+ char* ptr = (self.data[arg_index + 1]);
89
+ auto args_accessor = [&args] __device__(int thread_unroll_idx) -> arg_t& {
90
+ return std::get<arg_index>(args[thread_unroll_idx]);
91
+ };
92
+ self.template load_single_arg<arg_index>(args_accessor, ptr, idx);
93
+ }
94
+ };
95
+ #endif
96
+
97
+ template<int arg_index>
98
+ struct unroll_load_helper {
99
+ template <typename args_t, typename policy_t, typename offset_t, typename loader_t>
100
+ static __device__ void apply(policy_t &self, args_t *args, offset_t offset, loader_t loader, int j, int num_outputs) {
101
+ using arg_t = std::tuple_element_t<arg_index, args_t>;
102
+ // `data` hold the data_ptr for tensors [output, input0, input1, ...], so we
103
+ // need a +1 offset to get the input
104
+ std::get<arg_index>(args[j]) = loader.template load<arg_t>(self.data[arg_index + num_outputs], offset[arg_index], arg_index);
105
+ }
106
+ };
107
+
108
+ template <int current>
109
+ struct multi_outputs_store_helper {
110
+ template<typename data_t, typename offsets_t, typename ...Args>
111
+ C10_HOST_DEVICE static void apply(
112
+ const data_t& data,
113
+ const offsets_t& offsets,
114
+ thrust::tuple<Args...> ret) {
115
+ using T = typename thrust::tuple_element<current, thrust::tuple<Args...>>::type;
116
+ T *to = reinterpret_cast<T *>(data[current]) + offsets[current];
117
+ *to = thrust::get<current>(ret);
118
+ }
119
+ };
120
+
121
+ } // namespace detail
122
+
123
+ struct LoadWithoutCast {
124
+ template<typename scalar_t>
125
+ __device__ scalar_t load(char *base_ptr, uint32_t offset, int arg) {
126
+ return c10::load(reinterpret_cast<scalar_t *>(base_ptr) + offset);
127
+ }
128
+ };
129
+
130
+ template <int N>
131
+ struct LoadWithCast {
132
+ using array_t = std::array<at::ScalarType, std::max<int>(N, 1)>;
133
+ using size_array_t = std::array<uint32_t, std::max<int>(N, 1)>;
134
+
135
+ array_t dtypes;
136
+ size_array_t element_sizes;
137
+
138
+ LoadWithCast(const TensorIteratorBase& iter) {
139
+ CUDA_KERNEL_ASSERT(iter.ninputs() == N);
140
+ #pragma unroll
141
+ for (auto i = 0; i < N; ++i) {
142
+ this->dtypes[i] = iter.dtype(i + iter.noutputs());
143
+ element_sizes[i] = c10::elementSize(iter.dtype(i + iter.noutputs()));
144
+ }
145
+ }
146
+
147
+ template<typename scalar_t>
148
+ __device__ scalar_t load(char *base_ptr, uint32_t offset, int arg) {
149
+ void *ptr = base_ptr + element_sizes[arg] * offset;
150
+ return c10::fetch_and_cast<scalar_t>(dtypes[arg], ptr);
151
+ }
152
+ };
153
+
154
+ struct StoreWithoutCast {
155
+ template<typename scalar_t>
156
+ __device__ void store(scalar_t value, char *base_ptr, uint32_t offset, int arg = 0) {
157
+ *(reinterpret_cast<scalar_t *>(base_ptr) + offset) = value;
158
+ }
159
+ };
160
+
161
+ template <int N = 1>
162
+ struct StoreWithCast {
163
+ using array_t = std::array<at::ScalarType, std::max<int>(N, 1)>;
164
+ using size_array_t = std::array<uint32_t, std::max<int>(N, 1)>;
165
+
166
+ array_t dtypes;
167
+ size_array_t element_sizes;
168
+
169
+ StoreWithCast(const TensorIteratorBase& iter) {
170
+ CUDA_KERNEL_ASSERT(iter.noutputs() == N);
171
+ #pragma unroll
172
+ for (auto i = 0; i < N; ++i) {
173
+ this->dtypes[i] = iter.dtype(i);
174
+ element_sizes[i] = c10::elementSize(iter.dtype(i));
175
+ }
176
+ }
177
+
178
+ template<typename scalar_t>
179
+ __device__ void store(scalar_t value, char *base_ptr, uint32_t offset, int arg = 0) {
180
+ void *ptr = base_ptr + element_sizes[arg] * offset;
181
+ c10::cast_and_store<scalar_t>(dtypes[arg], ptr, value);
182
+ }
183
+ };
184
+
185
+ // aligned vector generates vectorized load/store on CUDA
186
+ template<typename scalar_t, int vec_size>
187
+ struct alignas(sizeof(scalar_t) * vec_size) aligned_vector {
188
+ scalar_t val[vec_size];
189
+ };
190
+
191
+ template <int vec_size, typename scalar_t>
192
+ __device__ aligned_vector<scalar_t, vec_size> load_vector(const scalar_t *base_ptr, uint32_t offset) {
193
+ using vec_t = aligned_vector<scalar_t, vec_size>;
194
+ auto *from = reinterpret_cast<const vec_t *>(base_ptr);
195
+ #if defined(USE_ROCM)
196
+ // NOTE: This nontemporal vectorized load is tuned for gfx942 (CDNA3, Wave64).
197
+ // Do NOT extend to gfx1250 (GFX12.5, Wave32) without first validating
198
+ // intrinsic codegen and re-benchmarking — the register layout and wave
199
+ // width differ. gfx1250 falls through to the generic path below, which
200
+ // is correctness-safe.
201
+ if(__builtin_amdgcn_processor_is("gfx942")) {
202
+ using longx2 = __attribute__((__vector_size__(4*sizeof(int)))) int;
203
+ if constexpr (sizeof(vec_t) == sizeof(int)) {
204
+ union {
205
+ vec_t v;
206
+ int i;
207
+ } tmpt = { .i = __builtin_nontemporal_load(reinterpret_cast<const int *>(&(from[offset]))) };
208
+ return tmpt.v;
209
+ }
210
+ else if constexpr (sizeof(vec_t) == sizeof(long)) {
211
+ union {
212
+ vec_t v;
213
+ long i;
214
+ } tmpt = { .i = __builtin_nontemporal_load(reinterpret_cast<const long *>(&(from[offset]))) };
215
+ return tmpt.v;
216
+ }
217
+ else if constexpr (sizeof(vec_t) == sizeof(longx2)) {
218
+ union {
219
+ vec_t v;
220
+ longx2 i;
221
+ } tmpt = { .i = __builtin_nontemporal_load(reinterpret_cast<const longx2 *>(&(from[offset]))) };
222
+ return tmpt.v;
223
+ }
224
+ }
225
+ return from[offset];
226
+ #endif
227
+ return from[offset];
228
+ }
229
+
230
+ template <int vec_size>
231
+ __device__ aligned_vector<bool, vec_size> load_vector(const bool *base_ptr, uint32_t offset) {
232
+ // See NOTE [Loading boolean values]
233
+ auto tmp = load_vector<vec_size>(reinterpret_cast<const uint8_t*>(base_ptr), offset);
234
+ aligned_vector<bool, vec_size> ret;
235
+ for (int i = 0; i < vec_size; ++i) {
236
+ ret.val[i] = bool(tmp.val[i]);
237
+ }
238
+ return ret;
239
+ }
240
+
241
+ namespace policies {
242
+
243
+ template <
244
+ int num_threads,
245
+ typename data_t,
246
+ typename inp_calc_t,
247
+ typename out_calc_t,
248
+ typename loader_t,
249
+ typename storer_t,
250
+ int elems_per_thread,
251
+ int num_outputs = 1>
252
+ struct unroll_base {
253
+ data_t data;
254
+ int remaining;
255
+ inp_calc_t input_offset_calculator;
256
+ out_calc_t output_offset_calculator;
257
+ loader_t loader;
258
+ storer_t storer;
259
+ static constexpr int tws = elems_per_thread;
260
+ static constexpr int block_work_size = elems_per_thread * num_threads;
261
+
262
+ __device__ unroll_base(
263
+ data_t data,
264
+ int remaining,
265
+ inp_calc_t ic,
266
+ out_calc_t oc,
267
+ loader_t l,
268
+ storer_t s)
269
+ : data(data),
270
+ remaining(remaining),
271
+ input_offset_calculator(ic),
272
+ output_offset_calculator(oc),
273
+ loader(l),
274
+ storer(s) {}
275
+
276
+ __device__ inline bool check_inbounds(int thread_work_elem) {
277
+ return ((int)(threadIdx.x + thread_work_elem * num_threads) < remaining);
278
+ }
279
+
280
+ template<typename args_t>
281
+ __device__ inline void load(args_t *args, int idx) {
282
+ constexpr int arity = std::tuple_size_v<args_t>;
283
+ int thread_idx = threadIdx.x;
284
+ #pragma unroll
285
+ for (int i = 0; i < elems_per_thread; i++) {
286
+ if (thread_idx < remaining) {
287
+ int linear_idx = thread_idx + block_work_size * idx;
288
+ auto offset = input_offset_calculator.get(linear_idx);
289
+ detail::static_unroll<detail::unroll_load_helper, arity>::with_args(
290
+ *this, args, offset, loader, i, num_outputs);
291
+ thread_idx += num_threads;
292
+ }
293
+ }
294
+ }
295
+
296
+ template<typename scalar_t>
297
+ __device__ inline void store(scalar_t *from, int idx) {
298
+ int thread_idx = threadIdx.x;
299
+ #pragma unroll
300
+ for (int i = 0; i < elems_per_thread; i++) {
301
+ if (thread_idx < remaining) {
302
+ int linear_idx = thread_idx + block_work_size * idx;
303
+ int offset = output_offset_calculator.get(linear_idx)[0];
304
+ storer.store(from[i], data[0], offset);
305
+ thread_idx += num_threads;
306
+ }
307
+ }
308
+ }
309
+ };
310
+
311
+ // Utility type for all users of unroll that extract the num_threads value from
312
+ // the caller scope.
313
+ template <
314
+ typename data_t,
315
+ typename inp_calc_t,
316
+ typename out_calc_t,
317
+ typename loader_t,
318
+ typename storer_t,
319
+ int elems_per_thread,
320
+ int num_outputs = 1>
321
+ using unroll = unroll_base<
322
+ num_threads(),
323
+ data_t,
324
+ inp_calc_t,
325
+ out_calc_t,
326
+ loader_t,
327
+ storer_t,
328
+ elems_per_thread,
329
+ num_outputs>;
330
+
331
+ template <int vec_size, typename data_t, int elems_per_thread> // vec_size: number of scalars, can be 1, 2, or 4.
332
+ struct vectorized {
333
+
334
+ static_assert(elems_per_thread % vec_size == 0, "The workload per thread must be a multiple of vec_size");
335
+ static constexpr int loop_size = elems_per_thread / vec_size;
336
+ static constexpr int tws = elems_per_thread;
337
+
338
+ data_t data;
339
+
340
+ __device__ vectorized(data_t data) : data(data) {}
341
+
342
+ __device__ inline constexpr bool check_inbounds(int thread_work_elem) {
343
+ return true;
344
+ }
345
+
346
+ template<typename accessor_t, typename scalar_t>
347
+ __device__ inline void load_single_arg(accessor_t to, scalar_t *from) {
348
+ int thread_idx = threadIdx.x;
349
+ #pragma unroll
350
+ for (int i = 0; i < loop_size; i++) {
351
+ int index = thread_idx + i * num_threads();
352
+ auto v = load_vector<vec_size>(from, index);
353
+ #pragma unroll
354
+ for (int j = 0; j < vec_size; j++) {
355
+ to(vec_size * i + j) = v.val[j];
356
+ }
357
+ }
358
+ }
359
+
360
+ template<typename args_t>
361
+ __device__ inline void load(args_t *args, int idx) {
362
+ constexpr int arity = std::tuple_size_v<args_t>;
363
+ detail::static_unroll<detail::vectorized_load_helper, arity>::with_args(*this, args, idx, elems_per_thread * num_threads());
364
+ }
365
+
366
+ template<typename scalar_t>
367
+ __device__ inline void store(scalar_t *from, int idx) {
368
+ using vec_t = aligned_vector<scalar_t, vec_size>;
369
+ scalar_t *to = reinterpret_cast<scalar_t *>(data[0]) + elems_per_thread * num_threads() * idx;
370
+ vec_t *to_ = reinterpret_cast<vec_t *>(to);
371
+ int thread_idx = threadIdx.x;
372
+ #pragma unroll
373
+ for (int i = 0; i < loop_size; i++) {
374
+ int index = thread_idx + i * num_threads();
375
+ vec_t v;
376
+ for (int j = 0; j < vec_size; j++) {
377
+ v.val[j] = from[vec_size * i + j];
378
+ }
379
+ to_[index] = v;
380
+ }
381
+ }
382
+ };
383
+
384
+ #ifdef USE_ROCM
385
+ // This is similar to vectorized policy above, but this one supports
386
+ // heterogeneous input tensor types as templated parameters.
387
+ // Its use should be limited to frequently used heterogeneous data types
388
+ // as each instantiation will generate a separate kernel, leading to code
389
+ // bloating if applied to all combinations supported in PyTorch. Assumption: all
390
+ // tensors are contiguous, that is: stride == sizeof(type) for all tensors.
391
+ template <
392
+ int vec_size,
393
+ typename data_t,
394
+ int elems_per_thread,
395
+ int num_threads,
396
+ typename CastToT,
397
+ typename... CastFromTs> // vec_size: number of scalars, can be 1, 2, or 4.
398
+ struct vectorized_templated {
399
+ static_assert(
400
+ elems_per_thread % vec_size == 0,
401
+ "The workload per thread must be a multiple of vec_size");
402
+ static constexpr int loop_size = elems_per_thread / vec_size;
403
+ static constexpr int tws = elems_per_thread;
404
+ static constexpr int block_work_size = elems_per_thread * num_threads;
405
+ data_t data;
406
+
407
+ __device__ vectorized_templated(data_t data) : data(data) {}
408
+
409
+ __device__ inline constexpr bool check_inbounds(int thread_work_elem) {
410
+ return true;
411
+ }
412
+
413
+ template <int arg_index, typename accessor_t>
414
+ __device__ inline void load_single_arg(accessor_t to, char* ptr, int idx) {
415
+ // extract the arg_index-th input tensor element type from the
416
+ // variadic template argument.
417
+ using CastFromT =
418
+ std::tuple_element_t<arg_index, std::tuple<CastFromTs...>>;
419
+ // Delayed pointer arithmetic from the caller: this is the place
420
+ // where we know the type of the argument.
421
+ CastFromT* block_ptr =
422
+ reinterpret_cast<CastFromT*>(ptr) + block_work_size * idx;
423
+ int thread_idx = threadIdx.x;
424
+ #pragma unroll
425
+ for (int i = 0; i < loop_size; i++) {
426
+ int index = thread_idx + i * num_threads;
427
+ auto v = load_vector<vec_size>(block_ptr, index);
428
+ #pragma unroll
429
+ for (int j = 0; j < vec_size; j++) {
430
+ to(vec_size * i + j) = c10::convert<CastToT>(v.val[j]);
431
+ }
432
+ }
433
+ }
434
+
435
+ template <typename args_t>
436
+ __device__ inline void load(args_t* args, int idx) {
437
+ constexpr int arity = std::tuple_size<args_t>::value;
438
+ detail::static_unroll<detail::vectorized_templated_load_helper, arity>::
439
+ with_args(*this, args, idx);
440
+ }
441
+
442
+ // Assume for now that from (temporary array per thread) is of the same
443
+ // type as to (destination tensor), which is the case for
444
+ // float(float,bfloat16) and functor add on float(float,float).
445
+ template <typename scalar_t>
446
+ __device__ inline void store(scalar_t* from, int idx) {
447
+ using vec_t = aligned_vector<CastToT, vec_size>;
448
+ CastToT* to = reinterpret_cast<CastToT*>(data[0]) + block_work_size * idx;
449
+ vec_t* to_ = reinterpret_cast<vec_t*>(to);
450
+ int thread_idx = threadIdx.x;
451
+ #pragma unroll
452
+ for (int i = 0; i < loop_size; i++) {
453
+ int index = thread_idx + i * num_threads;
454
+ vec_t v;
455
+ for (int j = 0; j < vec_size; j++) {
456
+ v.val[j] = from[vec_size * i + j];
457
+ }
458
+ to_[index] = v;
459
+ }
460
+ }
461
+ };
462
+ #endif
463
+
464
+ template <typename data_t, typename inp_calc_t, typename out_calc_t, int num_outputs>
465
+ struct multi_outputs_unroll {
466
+ //multi_outputs_unroll struct members and check_inbounds and load methods are copypasted from unroll struct
467
+ //we don't use inheritance because of compiler bug in cuda 10.2+
468
+ data_t data;
469
+ int remaining;
470
+ inp_calc_t input_offset_calculator;
471
+ out_calc_t output_offset_calculator;
472
+ LoadWithoutCast loader;
473
+ StoreWithoutCast storer;
474
+ static constexpr int tws = thread_work_size();
475
+
476
+ __device__ multi_outputs_unroll(data_t data, int remaining, inp_calc_t ic, out_calc_t oc):
477
+ data(data), remaining(remaining), input_offset_calculator(ic), output_offset_calculator(oc) {}
478
+
479
+ __device__ inline bool check_inbounds(int thread_work_elem) {
480
+ return ((int)(threadIdx.x + thread_work_elem*num_threads()) < remaining);
481
+ }
482
+
483
+ template<typename args_t>
484
+ __device__ inline void load(args_t *args, int idx) {
485
+ constexpr int arity = std::tuple_size_v<args_t>;
486
+ int thread_idx = threadIdx.x;
487
+ #pragma unroll
488
+ for (int i = 0; i < thread_work_size(); i++) {
489
+ if (thread_idx >= remaining) {
490
+ return;
491
+ }
492
+ int linear_idx = thread_idx + block_work_size() * idx;
493
+ auto offset = input_offset_calculator.get(linear_idx);
494
+ detail::static_unroll<detail::unroll_load_helper, arity>::with_args(*this, args, offset, loader, i, num_outputs);
495
+ thread_idx += num_threads();
496
+ }
497
+ }
498
+
499
+
500
+ template <typename return_t>
501
+ __device__ inline void store(return_t *from, int idx) {
502
+ int thread_idx = threadIdx.x;
503
+ #pragma unroll
504
+ for (int i = 0; i < thread_work_size(); i++) {
505
+ if (thread_idx >= this->remaining) {
506
+ return;
507
+ }
508
+ int linear_idx = thread_idx + block_work_size() * idx;
509
+ auto offsets = this->output_offset_calculator.get(linear_idx);
510
+ memory::detail::static_unroll<detail::multi_outputs_store_helper, num_outputs>::with_args(this->data, offsets, from[i]);
511
+ thread_idx += num_threads();
512
+ }
513
+ }
514
+ };
515
+
516
+ } // namespace policies
517
+
518
+ // This is only used in host, but we will wrap this into some templates
519
+ // which is C10_HOST_DEVICE, so we have to make this C10_HOST_DEVICE
520
+ // in order to compile
521
+ template<typename scalar_t>
522
+ inline C10_HOST_DEVICE int can_vectorize_up_to(const char *pointer) {
523
+ uint64_t address = reinterpret_cast<uint64_t>(pointer);
524
+ constexpr int vec2_alignment = std::alignment_of_v<aligned_vector<scalar_t, 2>>;
525
+ constexpr int vec4_alignment = std::alignment_of_v<aligned_vector<scalar_t, 4>>;
526
+ constexpr int vec8_alignment = std::alignment_of_v<aligned_vector<scalar_t, 8>>;
527
+ #ifdef USE_ROCM
528
+ constexpr int vec16_alignment = std::alignment_of_v<aligned_vector<scalar_t, 16>>;
529
+ constexpr int type_size = sizeof(scalar_t);
530
+ if (type_size == 1 && (address % vec16_alignment == 0)) {
531
+ return 16;
532
+ } else if (type_size <= 2 && (address % vec8_alignment == 0)) {
533
+ return 8;
534
+ } else
535
+ #else
536
+ if (address % vec8_alignment == 0) {
537
+ return 8;
538
+ } else
539
+ #endif
540
+ if (address % vec4_alignment == 0) {
541
+ return 4;
542
+ } else if (address % vec2_alignment == 0) {
543
+ return 2;
544
+ }
545
+ return 1;
546
+ }
547
+
548
+ template<typename scalar_t>
549
+ inline C10_HOST_DEVICE int can_vectorize_up_to(char *pointer) {
550
+ return can_vectorize_up_to<scalar_t>(static_cast<const char*>(pointer));
551
+ }
552
+
553
+ template<int i>
554
+ struct can_vectorize_up_to_helper {
555
+ template <typename array_t, typename traits>
556
+ static C10_HOST_DEVICE void apply(int &result, array_t pointers, traits /*_*/) {
557
+ using arg_t = typename traits::template arg<i>::type;
558
+ // `pointers` hold the data_ptr for tensors [output, input0, input1, ...], so we
559
+ // need a +1 offset to get the input
560
+ result = std::min<int>(result, can_vectorize_up_to<arg_t>(pointers[i + 1]));
561
+ }
562
+ };
563
+
564
+ template<typename func_t, typename array_t>
565
+ inline int can_vectorize_up_to(array_t pointers) {
566
+ using traits = function_traits<func_t>;
567
+ using return_t = typename traits::result_type;
568
+ constexpr int arity = traits::arity;
569
+ int result = can_vectorize_up_to<return_t>(pointers[0]);
570
+ // We need to get the type for each argument of `func_t`, this can only
571
+ // be done at compile time.
572
+ detail::static_unroll<can_vectorize_up_to_helper, arity>::with_args(result, pointers, traits());
573
+ return result;
574
+ }
575
+
576
+
577
+
578
+ template <typename T>
579
+ __inline__ size_t get_alignment(T ptr_or_size) {
580
+ auto val = reinterpret_cast<uintptr_t>(ptr_or_size);
581
+ if (val % 16 == 0) {
582
+ return 16;
583
+ } else if (val % 8 == 0) {
584
+ return 8;
585
+ } else if (val % 4 == 0) {
586
+ return 4;
587
+ } else if (val % 2 == 0) {
588
+ return 2;
589
+ } else {
590
+ return 1;
591
+ }
592
+ }
593
+
594
+ template <>
595
+ __inline__ size_t get_alignment<size_t>(size_t size) {
596
+ return get_alignment(reinterpret_cast<void*>(size));
597
+ }
598
+
599
+ template <bool Value, class... Args>
600
+ inline constexpr bool dependent_bool_value = Value;
601
+
602
+ template <class... Args>
603
+ inline constexpr bool dependent_false = dependent_bool_value<false, Args...>;
604
+
605
+ template <int Size>
606
+ union Vec;
607
+
608
+ template <>
609
+ union Vec<4> {
610
+ uint16_t u16[2];
611
+ uint32_t u32, as_scalar;
612
+ float f32;
613
+ };
614
+
615
+ template <>
616
+ union Vec<8> {
617
+ uint16_t u16[4];
618
+ uint32_t u32[2];
619
+ uint64_t u64, as_scalar;
620
+ float f32[2];
621
+ };
622
+
623
+ template <>
624
+ union alignas(16) Vec<16> {
625
+ uint16_t u16[8];
626
+ uint32_t u32[4];
627
+ uint64_t u64[2];
628
+ uint4 u128, as_scalar;
629
+ float f32[4];
630
+ };
631
+
632
+ template <int Alignment, typename T>
633
+ __device__ __inline__ Vec<Alignment> ld_vec(const T* addr) {
634
+ Vec<Alignment> vec;
635
+ if constexpr (Alignment == 16) {
636
+ #if defined(USE_ROCM)
637
+ vec.u128 = *reinterpret_cast<const uint4*>(addr);
638
+ } else if constexpr (Alignment == 8) {
639
+ vec.u64 = *reinterpret_cast<const uint64_t*>(addr);
640
+ } else if constexpr (Alignment == 4) {
641
+ vec.u32 = *reinterpret_cast<const uint32_t*>(addr);
642
+ #else
643
+ asm("ld.global.v4.u32 {%0,%1,%2,%3}, [%4];"
644
+ : "=r"(vec.u32[0]), "=r"(vec.u32[1]), "=r"(vec.u32[2]), "=r"(vec.u32[3])
645
+ : "l"(addr)
646
+ : "memory");
647
+ } else if constexpr (Alignment == 8) {
648
+ asm("ld.global.v2.u32 {%0,%1}, [%2];"
649
+ : "=r"(vec.u32[0]), "=r"(vec.u32[1])
650
+ : "l"(addr)
651
+ : "memory");
652
+ } else if constexpr (Alignment == 4) {
653
+ asm("ld.global.u32 %0, [%1];" : "=r"(vec.u32) : "l"(addr) : "memory");
654
+ #endif
655
+ } else {
656
+ static_assert(dependent_false<T>);
657
+ }
658
+ return vec;
659
+ }
660
+
661
+ template <int Alignment, typename T>
662
+ __device__ __inline__ void st_vec(T* addr, const Vec<Alignment>& vec) {
663
+ if constexpr (Alignment == 16) {
664
+ #if defined(USE_ROCM)
665
+ reinterpret_cast<uint64_t*>(addr)[0] = vec.u64[0];
666
+ reinterpret_cast<uint64_t*>(addr)[1] = vec.u64[1];
667
+ } else if constexpr (Alignment == 8) {
668
+ *reinterpret_cast<uint64_t*>(addr) = vec.u64;
669
+ } else if constexpr (Alignment == 4) {
670
+ *reinterpret_cast<uint32_t*>(addr) = vec.u32;
671
+ #else
672
+ asm("st.global.v4.u32 [%0], {%1,%2,%3,%4};"
673
+ :
674
+ : "l"(addr),
675
+ "r"(vec.u32[0]),
676
+ "r"(vec.u32[1]),
677
+ "r"(vec.u32[2]),
678
+ "r"(vec.u32[3])
679
+ : "memory");
680
+ } else if constexpr (Alignment == 8) {
681
+ asm("st.global.v2.u32 [%0], {%1,%2};"
682
+ :
683
+ : "l"(addr), "r"(vec.u32[0]), "r"(vec.u32[1])
684
+ : "memory");
685
+ } else if constexpr (Alignment == 4) {
686
+ asm("st.global.u32 [%0], %1;" : : "l"(addr), "r"(vec.u32) : "memory");
687
+ #endif
688
+ } else {
689
+ static_assert(dependent_false<T>);
690
+ }
691
+ }
692
+
693
+
694
+
695
+ } // namespace at::native::memory
696
+
697
+ #else
698
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
699
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MiscUtils.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/cuda/Exceptions.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/cuda/CUDAConfig.h>
6
+ #include <ATen/cuda/PinnedMemoryAllocator.h>
7
+
8
+
9
+ namespace at::native {
10
+
11
+ static inline int cuda_int_cast(int64_t value, const char* varname) {
12
+ auto result = static_cast<int>(value);
13
+ TORCH_CHECK(static_cast<int64_t>(result) == value,
14
+ "cuda_int_cast: The value of ", varname, "(", (long long)value,
15
+ ") is too large to fit into a int (", sizeof(int), " bytes)");
16
+ return result;
17
+ }
18
+
19
+ // Creates an array of size elements of type T, backed by pinned memory
20
+ // wrapped in a Storage
21
+ template<class T>
22
+ static inline Storage pin_memory(int64_t size) {
23
+ auto* allocator = cuda::getPinnedMemoryAllocator();
24
+ int64_t adjusted_size = size * sizeof(T);
25
+ return Storage(
26
+ Storage::use_byte_size_t(),
27
+ adjusted_size,
28
+ allocator,
29
+ /*resizable=*/false);
30
+ }
31
+
32
+ } // namespace at::native
33
+
34
+ #else
35
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
36
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/MultiTensorApply.cuh ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #if defined(USE_ROCM)
6
+ #include <ATen/record_function.h>
7
+ #endif
8
+ #include <c10/cuda/CUDAGuard.h>
9
+ #include <ATen/native/cuda/Loops.cuh>
10
+ #include <ATen/native/cuda/MemoryAccess.cuh>
11
+ #include <vector>
12
+
13
+ namespace at::native {
14
+
15
+ namespace {
16
+
17
+ static constexpr int64_t kILP = 4;
18
+ static constexpr int64_t kChunkSize = 65536;
19
+ static constexpr int64_t kBlockSize = 512;
20
+
21
+ // TODO(crcrpar): Add `n>5` for `low prec params & their higher prec copy`
22
+ // TensorListMetadata has to fit within the CUDA kernel launch argument limit.
23
+ // While CUDA 12.1, driver version R530+ and Volta+ would work with 32KB, we
24
+ // decide to be safe and only swap for CUDA 13+ during compile time. This saves
25
+ // binary size and will guarantees 32KB kernel arg space; older versions are
26
+ // still limited to 4KB. We adopt naive values for 32KB from
27
+ // https://github.com/pytorch/pytorch/pull/134373.
28
+ // TODO: The values for 32KB can very much be optimized further.
29
+ #if defined(CUDART_VERSION) && CUDART_VERSION >= 13000 && !defined(USE_ROCM)
30
+
31
+ static constexpr int32_t depth_to_max_tensors[5] = {770, 448, 336, 252, 210};
32
+ static constexpr int32_t depth_to_max_blocks[5] =
33
+ {2240, 2240, 2240, 2240, 2240};
34
+ static constexpr int32_t depth_to_max_tensors_scalarlist[5] =
35
+ {672, 448, 336, 252, 210};
36
+ static constexpr int32_t depth_to_max_tensors_scalarlist_of_complex_double[2] =
37
+ {504, 420};
38
+ using block_index_t = uint16_t;
39
+
40
+ #else
41
+
42
+ static constexpr int32_t depth_to_max_tensors[5] = {110, 64, 48, 36, 30};
43
+ static constexpr int32_t depth_to_max_blocks[5] = {320, 320, 320, 320, 320};
44
+ static constexpr int32_t depth_to_max_tensors_scalarlist[5] =
45
+ {96, 64, 48, 36, 30};
46
+ static constexpr int32_t depth_to_max_tensors_scalarlist_of_complex_double[2] =
47
+ {72, 60};
48
+ using block_index_t = unsigned char;
49
+
50
+ #endif
51
+
52
+ template <typename T>
53
+ __device__ __forceinline__ bool is_aligned(T* p) {
54
+ return ((uint64_t)p) % (kILP * sizeof(T)) == 0;
55
+ }
56
+
57
+ template <typename T>
58
+ __device__ __forceinline__ void load_store(
59
+ T* dst,
60
+ T* src,
61
+ int64_t dst_offset,
62
+ int64_t src_offset) {
63
+ using LT = at::native::memory::aligned_vector<T, kILP>;
64
+ ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset];
65
+ }
66
+
67
+ template <int n>
68
+ struct TensorListMetadata {
69
+ static constexpr int32_t max_tensors_per_launch = depth_to_max_tensors[n - 1];
70
+ static constexpr int32_t max_blocks_per_launch = depth_to_max_blocks[n - 1];
71
+ const void* addresses[n][max_tensors_per_launch];
72
+ int64_t numel_for_tensor[max_tensors_per_launch];
73
+ block_index_t block_to_tensor[max_blocks_per_launch];
74
+ int32_t block_to_chunk[max_blocks_per_launch];
75
+ int32_t start_tensor_this_launch;
76
+ };
77
+
78
+ template <typename scalar_vals_t, int n>
79
+ struct TensorListScalarListMetadata {
80
+ static constexpr int32_t max_tensors_per_launch =
81
+ depth_to_max_tensors_scalarlist[n - 1];
82
+ static constexpr int32_t max_blocks_per_launch = depth_to_max_blocks[n - 1];
83
+ const void* addresses[n][max_tensors_per_launch];
84
+ int64_t numel_for_tensor[max_tensors_per_launch];
85
+ scalar_vals_t scalar_vals[max_tensors_per_launch];
86
+ block_index_t block_to_tensor[max_blocks_per_launch];
87
+ int32_t block_to_chunk[max_blocks_per_launch];
88
+ };
89
+
90
+ // note(mkozuki): `n` of 1&2 violate the limit of cuda kernel argument size
91
+ // with `c10::complex<double>`
92
+ template <>
93
+ struct TensorListScalarListMetadata<c10::complex<double>, 1> {
94
+ static constexpr int32_t max_tensors_per_launch =
95
+ depth_to_max_tensors_scalarlist_of_complex_double[0];
96
+ static constexpr int32_t max_blocks_per_launch = depth_to_max_blocks[0];
97
+ const void* addresses[1][max_tensors_per_launch];
98
+ int64_t numel_for_tensor[max_tensors_per_launch];
99
+ c10::complex<double> scalar_vals[max_tensors_per_launch];
100
+ block_index_t block_to_tensor[max_blocks_per_launch];
101
+ int32_t block_to_chunk[max_blocks_per_launch];
102
+ };
103
+
104
+ template <>
105
+ struct TensorListScalarListMetadata<c10::complex<double>, 2> {
106
+ static constexpr int32_t max_tensors_per_launch =
107
+ depth_to_max_tensors_scalarlist_of_complex_double[1];
108
+ static constexpr int32_t max_blocks_per_launch = depth_to_max_blocks[1];
109
+ const void* addresses[2][max_tensors_per_launch];
110
+ int64_t numel_for_tensor[max_tensors_per_launch];
111
+ c10::complex<double> scalar_vals[max_tensors_per_launch];
112
+ block_index_t block_to_tensor[max_blocks_per_launch];
113
+ int32_t block_to_chunk[max_blocks_per_launch];
114
+ };
115
+
116
+ // NOTE(crcrpar): This is a conservative resolution to handle `state_steps`
117
+ // whose each element is `at::Tensor` of 1 element representing the number of
118
+ // `step`s called so far.
119
+ // We're aware this struct overflows the kernel arg limit at n=1 (4244 bytes),
120
+ // but our current fused optimizers only instantiate at n>=4 so it's not a
121
+ // concern (yet).
122
+ template <int n>
123
+ struct FusedOptimizerTensorListMetadata {
124
+ static constexpr int32_t max_tensors_per_launch = depth_to_max_tensors[n - 1];
125
+ static constexpr int32_t max_blocks_per_launch = depth_to_max_blocks[n - 1];
126
+ const void* addresses[n][max_tensors_per_launch];
127
+ int64_t numel_for_tensor[max_tensors_per_launch];
128
+ const void* state_steps_addresses[max_tensors_per_launch];
129
+ block_index_t block_to_tensor[max_blocks_per_launch];
130
+ int32_t block_to_chunk[max_blocks_per_launch];
131
+ int32_t start_tensor_this_launch;
132
+ };
133
+
134
+ template <typename T, typename U, typename... ArgTypes>
135
+ C10_LAUNCH_BOUNDS_1(kBlockSize)
136
+ __global__ void multi_tensor_apply_kernel(
137
+ T tensorListMeta,
138
+ U callable,
139
+ ArgTypes... args) {
140
+ // Hand the chunk information to the user-supplied functor to process however
141
+ // it likes.
142
+ callable(kChunkSize, tensorListMeta, args...);
143
+ }
144
+
145
+ inline void record_foreach_mta_launch() {
146
+ #if defined(USE_ROCM)
147
+ RECORD_FUNCTION("aten::_foreach_mta_launch", {});
148
+ #endif
149
+ }
150
+
151
+ } // namespace
152
+
153
+ // multi_tensor_apply enables horizontal fusion across lists of tensors.
154
+ // For example, whereas you once had a for-loop of a + b = c, where a, b,
155
+ // and c are individual tensors in lists as, bs, and cs, you can now with
156
+ // fewer kernel launches compute as + bs = cs.
157
+ //
158
+ // You can also imagine bs to be a scalar list vs a tensor list.
159
+ //
160
+ // The function below takes in tensor lists, scalars, and a callable and
161
+ // chunks up the computation to launch as few kernels as possible by iterating
162
+ // through every "chunk" in every tensor (thus the nested for loops). In the
163
+ // simplest case, everything gets bundled into just one kernel launch, but
164
+ // due to blocksize constraints, we may need to launch multiple kernels.
165
+ // Each kernel launch is defined by one tensorListMeta construct, which we
166
+ // use to track and reset the necessary metadata for each launch.
167
+ template <int depth, typename scalar_T, typename T, typename... ArgTypes>
168
+ void multi_tensor_apply(
169
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
170
+ at::ArrayRef<Scalar> scalars,
171
+ T callable,
172
+ ArgTypes... args) {
173
+ TORCH_CHECK(
174
+ tensor_lists.size() == depth,
175
+ "Number of tensor lists has to match the depth.");
176
+ const size_t n_tensors = tensor_lists[0].size();
177
+ using scalar_vals_t = typename T::opmath_t;
178
+ using metadata_t = TensorListScalarListMetadata<scalar_vals_t, depth>;
179
+ metadata_t tensorListMeta;
180
+
181
+ int loc_block_info = 0;
182
+ int loc_tensor_info = 0;
183
+ for (size_t t = 0; t < n_tensors; t++) {
184
+ // short-circuit to avoid adding empty tensors to tensorListMeta
185
+ if (tensor_lists[0][t].numel() == 0) {
186
+ continue;
187
+ }
188
+ tensorListMeta.scalar_vals[loc_tensor_info] = scalars[t].to<scalar_T>();
189
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
190
+ tensor_lists[0][t].numel();
191
+ for (int d = 0; d < depth; d++) {
192
+ tensorListMeta.addresses[d][loc_tensor_info] =
193
+ tensor_lists[d][t].const_data_ptr();
194
+ }
195
+ loc_tensor_info++;
196
+
197
+ // now we enter [chunking territory].
198
+ // we will launch a kernel when EITHER the blocks get filled up OR
199
+ // the tensors get filled up. There will always be at least one block
200
+ // per tensor since the zero-sized ones will not enter the loop, so
201
+ // the nested forloop within represents iterating through the chunks
202
+ // of a single tensor.
203
+ const auto numel = tensor_lists[0][t].numel();
204
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
205
+ for (auto chunk = 0; chunk < chunks; chunk++) {
206
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
207
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
208
+ loc_block_info++;
209
+
210
+ // a tensor is not considered full unless all its chunks have been
211
+ // processed. Use the metadata struct's own capacities: the
212
+ // c10::complex<double> specializations hold fewer tensors than
213
+ // depth_to_max_tensors_scalarlist to stay within the kernel arg limit.
214
+ const bool tensors_full =
215
+ (loc_tensor_info == metadata_t::max_tensors_per_launch &&
216
+ chunk == chunks - 1);
217
+ const bool blocks_full =
218
+ (loc_block_info == metadata_t::max_blocks_per_launch);
219
+
220
+ if (tensors_full || blocks_full) {
221
+ record_foreach_mta_launch();
222
+ multi_tensor_apply_kernel<<<
223
+ loc_block_info,
224
+ kBlockSize,
225
+ 0,
226
+ at::cuda::getCurrentCUDAStream()>>>(
227
+ tensorListMeta, callable, args...);
228
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
229
+
230
+ // Reset.
231
+ loc_block_info = 0;
232
+ // all chunks have already been handled in the kernel
233
+ if (chunk == chunks - 1) {
234
+ loc_tensor_info = 0;
235
+ } else { // blocks were full and tensor chunks remain
236
+ tensorListMeta.numel_for_tensor[0] =
237
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
238
+ tensorListMeta.scalar_vals[0] =
239
+ tensorListMeta.scalar_vals[loc_tensor_info - 1];
240
+ for (int d = 0; d < depth; d++) {
241
+ tensorListMeta.addresses[d][0] =
242
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
243
+ }
244
+ loc_tensor_info = 1;
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ // note: [finishing what we started]
251
+ // if there's remaining work to be done but the tensors/blocks aren't full
252
+ // yet we are at the end, submit the kernel to do the work!
253
+ if (loc_block_info != 0) {
254
+ record_foreach_mta_launch();
255
+ multi_tensor_apply_kernel<<<
256
+ loc_block_info,
257
+ kBlockSize,
258
+ 0,
259
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
260
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
261
+ }
262
+ }
263
+
264
+ template <int depth, typename T, typename... ArgTypes>
265
+ void multi_tensor_apply(
266
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
267
+ T callable,
268
+ ArgTypes... args) {
269
+ TORCH_CHECK(
270
+ tensor_lists.size() == depth,
271
+ "Number of tensor lists has to match the depth.");
272
+ const size_t n_tensors = tensor_lists[0].size();
273
+ using metadata_t = TensorListMetadata<depth>;
274
+ metadata_t tensorListMeta;
275
+ tensorListMeta.start_tensor_this_launch = 0;
276
+
277
+ int loc_block_info = 0;
278
+ int loc_tensor_info = 0;
279
+ int processed = 0;
280
+
281
+ for (size_t t = 0; t < n_tensors; t++) {
282
+ // short-circuit to avoid adding empty tensors to tensorListMeta
283
+ if (tensor_lists[0][t].numel() == 0) {
284
+ continue;
285
+ }
286
+ processed++;
287
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
288
+ tensor_lists[0][t].numel();
289
+ for (int d = 0; d < depth; d++) {
290
+ tensorListMeta.addresses[d][loc_tensor_info] =
291
+ tensor_lists[d][t].const_data_ptr();
292
+ }
293
+ loc_tensor_info++;
294
+
295
+ // see note: [chunking territory].
296
+ const auto numel = tensor_lists[0][t].numel();
297
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
298
+ for (auto chunk = 0; chunk < chunks; chunk++) {
299
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
300
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
301
+ loc_block_info++;
302
+
303
+ const bool tensors_full =
304
+ (loc_tensor_info == metadata_t::max_tensors_per_launch &&
305
+ chunk == chunks - 1);
306
+ const bool blocks_full =
307
+ (loc_block_info == metadata_t::max_blocks_per_launch);
308
+
309
+ if (tensors_full || blocks_full) {
310
+ record_foreach_mta_launch();
311
+ multi_tensor_apply_kernel<<<
312
+ loc_block_info,
313
+ kBlockSize,
314
+ 0,
315
+ at::cuda::getCurrentCUDAStream()>>>(
316
+ tensorListMeta, callable, args...);
317
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
318
+
319
+ // Reset.
320
+ loc_block_info = 0;
321
+ if (chunk == chunks - 1) {
322
+ loc_tensor_info = 0;
323
+ tensorListMeta.start_tensor_this_launch = processed;
324
+ } else {
325
+ tensorListMeta.numel_for_tensor[0] =
326
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
327
+ for (int d = 0; d < depth; d++) {
328
+ tensorListMeta.addresses[d][0] =
329
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
330
+ }
331
+ loc_tensor_info = 1;
332
+ tensorListMeta.start_tensor_this_launch = processed - 1;
333
+ }
334
+ }
335
+ }
336
+ }
337
+
338
+ // see note: [finishing what we started]
339
+ if (loc_block_info != 0) {
340
+ record_foreach_mta_launch();
341
+ multi_tensor_apply_kernel<<<
342
+ loc_block_info,
343
+ kBlockSize,
344
+ 0,
345
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
346
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
347
+ }
348
+ }
349
+
350
+ template <int depth, typename T, typename... ArgTypes>
351
+ void multi_tensor_apply_for_fused_optimizer(
352
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
353
+ at::TensorList state_steps,
354
+ T callable,
355
+ ArgTypes... args) {
356
+ TORCH_CHECK(
357
+ tensor_lists.size() == depth,
358
+ "Number of tensor lists has to match the depth");
359
+ const auto num_tensors = tensor_lists[0].size();
360
+ using metadata_t = FusedOptimizerTensorListMetadata<depth>;
361
+ metadata_t tensorListMeta;
362
+
363
+ int loc_block_info = 0;
364
+ int loc_tensor_info = 0;
365
+ for (const auto& tensor_index : c10::irange(num_tensors)) {
366
+ // short-circuit to avoid adding empty tensors to tensorListMeta
367
+ if (tensor_lists[0][tensor_index].numel() == 0) {
368
+ continue;
369
+ }
370
+ tensorListMeta.state_steps_addresses[loc_tensor_info] =
371
+ state_steps[tensor_index].const_data_ptr();
372
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
373
+ tensor_lists[0][tensor_index].numel();
374
+ for (const auto& d : c10::irange(depth)) {
375
+ tensorListMeta.addresses[d][loc_tensor_info] =
376
+ tensor_lists[d][tensor_index].const_data_ptr();
377
+ }
378
+ loc_tensor_info++;
379
+
380
+ // see above note: [chunking territory]
381
+ const auto numel = tensor_lists[0][tensor_index].numel();
382
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
383
+ TORCH_CHECK(chunks > -1);
384
+ for (const auto& chunk : c10::irange(chunks)) {
385
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
386
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
387
+ loc_block_info++;
388
+
389
+ const auto tensor_full =
390
+ (loc_tensor_info == metadata_t::max_tensors_per_launch &&
391
+ chunk == chunks - 1);
392
+ const auto blocks_full =
393
+ loc_block_info == metadata_t::max_blocks_per_launch;
394
+
395
+ if (tensor_full || blocks_full) {
396
+ record_foreach_mta_launch();
397
+ multi_tensor_apply_kernel<<<
398
+ loc_block_info,
399
+ kBlockSize,
400
+ 0,
401
+ at::cuda::getCurrentCUDAStream()>>>(
402
+ tensorListMeta, callable, args...);
403
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
404
+
405
+ // Reset.
406
+ loc_block_info = 0;
407
+ if (chunk == chunks - 1) {
408
+ loc_tensor_info = 0;
409
+ } else {
410
+ tensorListMeta.numel_for_tensor[0] =
411
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
412
+ tensorListMeta.state_steps_addresses[0] =
413
+ tensorListMeta.state_steps_addresses[loc_tensor_info - 1];
414
+ for (const auto& d : c10::irange(depth)) {
415
+ tensorListMeta.addresses[d][0] =
416
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
417
+ }
418
+ loc_tensor_info = 1;
419
+ }
420
+ }
421
+ }
422
+ }
423
+
424
+ // see above note: [finishing what we've started]
425
+ if (loc_block_info != 0) {
426
+ record_foreach_mta_launch();
427
+ multi_tensor_apply_kernel<<<
428
+ loc_block_info,
429
+ kBlockSize,
430
+ 0,
431
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
432
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
433
+ }
434
+ }
435
+
436
+ } // namespace at::native
437
+
438
+ #else
439
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
440
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Normalization.cuh ADDED
@@ -0,0 +1,1808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/Dispatch.h>
6
+ #include <ATen/AccumulateType.h>
7
+ #include <ATen/ceil_div.h>
8
+ #include <ATen/cuda/CUDAContext.h>
9
+ #include <ATen/cuda/DeviceUtils.cuh>
10
+ #include <ATen/native/cuda/block_reduce.cuh>
11
+ #include <ATen/native/cuda/DeviceSqrt.cuh>
12
+ #include <ATen/native/cuda/KernelUtils.cuh>
13
+ #include <ATen/native/cuda/LaunchUtils.h>
14
+ #include <c10/macros/Macros.h>
15
+ #include <utility>
16
+
17
+ #ifndef AT_PER_OPERATOR_HEADERS
18
+ #include <ATen/Functions.h>
19
+ #else
20
+ #include <ATen/ops/empty.h>
21
+ #include <ATen/ops/empty_like.h>
22
+ #include <ATen/ops/zeros.h>
23
+ #endif
24
+
25
+ namespace at::native {
26
+
27
+ // The maximum number of threads in a block
28
+ #if defined(USE_ROCM)
29
+ constexpr int MAX_BLOCK_SIZE = 1024;
30
+ #else
31
+ constexpr int MAX_BLOCK_SIZE = 512;
32
+ #endif
33
+
34
+ constexpr unsigned MAX_GRID_SIZE = 65535u;
35
+
36
+ // Number of threads in a block given an input size up to MAX_BLOCK_SIZE
37
+ static int getNumThreads(int nElem) {
38
+ #if defined(USE_ROCM)
39
+ int threadSizes[5] = { 64, 128, 256, 512, MAX_BLOCK_SIZE };
40
+ #else
41
+ int threadSizes[5] = { 32, 64, 128, 256, MAX_BLOCK_SIZE };
42
+ #endif
43
+ for (int i = 0; i != 5; ++i) {
44
+ if (nElem <= threadSizes[i]) {
45
+ return threadSizes[i];
46
+ }
47
+ }
48
+ return MAX_BLOCK_SIZE;
49
+ }
50
+
51
+ // Returns the index of the most significant 1 bit in `val`.
52
+ __device__ __forceinline__ int getMSB(int val) {
53
+ return 31 - __clz(val);
54
+ }
55
+
56
+ template <typename scalar_t, typename accscalar_t>
57
+ struct Float2 {
58
+ accscalar_t v1, v2;
59
+ __device__ Float2() = default;
60
+ __device__ Float2(scalar_t v1, scalar_t v2) : v1(static_cast<accscalar_t>(v1)), v2(static_cast<accscalar_t>(v2)) {}
61
+ __device__ Float2(int v) : v1(static_cast<accscalar_t>(v)), v2(static_cast<accscalar_t>(v)) {}
62
+ __device__ Float2& operator+=(const Float2& a) {
63
+ v1 += a.v1;
64
+ v2 += a.v2;
65
+ return *this;
66
+ }
67
+ __device__ friend Float2 operator+(Float2 a, const Float2& b) {
68
+ a += b;
69
+ return a;
70
+ }
71
+ };
72
+
73
+ template <typename scalar_t, typename accscalar_t, typename PTA>
74
+ struct GradOp {
75
+ __device__ GradOp(accscalar_t m, const PTA& i, const PTA& g)
76
+ : mean(m), input(i), grad_output(g) {}
77
+ __device__ __forceinline__ Float2<scalar_t, accscalar_t> operator()(int batch, int plane, int n) {
78
+ accscalar_t g = grad_output[batch][plane][n];
79
+ accscalar_t c = static_cast<accscalar_t>(input[batch][plane][n]) - mean;
80
+ return Float2<scalar_t, accscalar_t>(g, g * c);
81
+ }
82
+ const accscalar_t mean;
83
+ const PTA& input;
84
+ const PTA& grad_output;
85
+ };
86
+
87
+ template <typename acc_t>
88
+ struct SumReduceOp {
89
+ __device__ __forceinline__ acc_t combine(acc_t a, acc_t b) const { return a + b; }
90
+
91
+ __device__ __forceinline__ acc_t warp_shfl_down(acc_t data, int offset) const {
92
+ return WARP_SHFL_DOWN(data, offset);
93
+ }
94
+ };
95
+
96
+ template <typename scalar_t, typename accscalar_t>
97
+ struct SumReduceOp<Float2<scalar_t, accscalar_t>> {
98
+ using acc_t = Float2<scalar_t, accscalar_t>;
99
+
100
+ __device__ __forceinline__ acc_t combine(acc_t a, acc_t b) const { return a + b; }
101
+
102
+ __device__ __forceinline__ acc_t warp_shfl_down(acc_t data, int offset) const {
103
+ return {WARP_SHFL_DOWN(data.v1, offset), WARP_SHFL_DOWN(data.v2, offset)};
104
+ }
105
+ };
106
+
107
+ // Sum across (batch, x/y/z) applying Op() pointwise
108
+ // this works by first having each thread sum it's part
109
+ // of the data. Then there is a double-shuffling reduction.
110
+ // First each warp (of C10_WARP_SIZE threads) uses warpSum to reduce its
111
+ // data to the "warp leader", who writes its value into shared memory.
112
+ // Then a single warp reads the remaining (at most C10_WARP_SIZE) items
113
+ // and reduces them using another warpSum.
114
+ // The implicit assumption is that there are no more
115
+ // than C10_WARP_SIZE**2 threads.
116
+ template<typename scalar_t, typename Op, typename PTA>
117
+ __device__ scalar_t reduce(Op op, PTA tensor, int plane) {
118
+ // first the reductions each thread does separately
119
+ scalar_t sum = static_cast<scalar_t>(0);
120
+ for (int batch = threadIdx.y; batch < tensor.size(0); batch += blockDim.y) {
121
+ #if defined(USE_ROCM)
122
+ constexpr int UNRL = 4; // load deserilize factor
123
+ scalar_t tmp[UNRL];
124
+ for (int x = threadIdx.x; x < tensor.size(2); x += blockDim.x*UNRL) {
125
+ #pragma unroll
126
+ for (int u = 0; u < UNRL; u++)
127
+ tmp[u] = op(batch, plane, std::min((int)tensor.size(2)-1, (int)(x+u*blockDim.x)));
128
+ #pragma unroll
129
+ for (int u = 0; u < UNRL; u++)
130
+ if (x+u*blockDim.x < tensor.size(2))
131
+ sum += tmp[u];
132
+ }
133
+ #else
134
+ for (int x = threadIdx.x; x < tensor.size(2); x += blockDim.x) {
135
+ sum += op(batch, plane, x);
136
+ }
137
+ #endif
138
+ }
139
+ __shared__ scalar_t shared[C10_WARP_SIZE_UPPER_BOUND];
140
+ SumReduceOp<scalar_t> reduce_op;
141
+ sum = cuda_utils::BlockReduce<scalar_t, SumReduceOp<scalar_t>, cuda_utils::Block2D>(sum, reduce_op, 0, shared);
142
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
143
+ shared[0] = sum;
144
+ }
145
+ __syncthreads();
146
+ // Everyone picks it up, should be broadcast into the whole grad_input
147
+ return shared[0];
148
+ }
149
+
150
+ constexpr int ELEMENTS_PER_ITER = 4; // enables concurrency within each thread to hide latency
151
+ constexpr int ELEMENTS_PER_THREAD = 16;
152
+ constexpr int OPTIMAL_TILE_W = 32;
153
+ constexpr int MAX_H_BLOCK = 128;
154
+
155
+ __host__ void flexible_launch_configs(
156
+ const int reduction,
157
+ const int stride,
158
+ dim3 &block,
159
+ dim3 &grid,
160
+ const bool coop_flag = false) {
161
+ int block_x = std::min(lastPow2(stride), OPTIMAL_TILE_W);
162
+ int block_y = std::min(lastPow2(at::ceil_div(reduction , ELEMENTS_PER_THREAD)),
163
+ MAX_BLOCK_SIZE / block_x);
164
+ if (block_x * block_y != MAX_BLOCK_SIZE) {
165
+ block_x = std::min(lastPow2(stride), MAX_BLOCK_SIZE / block_y);
166
+ }
167
+
168
+ int grid_x = at::ceil_div(stride, block_x);
169
+ int grid_y = std::min(at::ceil_div(reduction, block_y * ELEMENTS_PER_THREAD), MAX_H_BLOCK);
170
+ if (coop_flag) {
171
+ // it's not worth having a grid reduction if the reduction dimension is not big enough
172
+ grid_y = grid_y < 8 ? 1 : grid_y;
173
+ }
174
+
175
+ block.x = block_x;
176
+ block.y = block_y;
177
+ block.z = 1;
178
+ grid.x = grid_x;
179
+ grid.y = grid_y;
180
+ grid.z = 1;
181
+ }
182
+
183
+ template<typename T, typename C>
184
+ __device__ __forceinline__ void welford_merge_element(C& count,
185
+ T& mean,
186
+ T& m2n,
187
+ const C& count_new,
188
+ const T& mean_new,
189
+ const T& m2n_new) {
190
+ T factor = T(1.0) / ::max(1, (count + count_new));
191
+ T delta0 = mean - mean_new;
192
+ mean = (mean_new * count_new + mean * count) * factor;
193
+ m2n += m2n_new + delta0 * delta0 * count_new * count * factor;
194
+ count += count_new;
195
+ }
196
+
197
+ // merge mean/m2n among threadIdx.y within block
198
+ template<typename T, typename C>
199
+ __device__ __forceinline__ void welford_merge_block_vertical(C& count,
200
+ T& mean,
201
+ T& m2n,
202
+ C* shmem_count,
203
+ T* shmem_mean,
204
+ T* shmem_m2n) {
205
+ // write to shared memory
206
+ auto address_base = threadIdx.x + threadIdx.y * blockDim.x;
207
+
208
+ #pragma unroll
209
+ for (int offset = blockDim.y/2; offset > 0; offset >>= 1) {
210
+ if (threadIdx.y < offset*2) {
211
+ shmem_mean[address_base] = mean;
212
+ shmem_m2n[address_base] = m2n;
213
+ shmem_count[address_base] = count;
214
+ }
215
+ __syncthreads();
216
+ if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) {
217
+ auto address = address_base + offset * blockDim.x;
218
+ // read shared memory back to register for reduction
219
+ auto count_new = shmem_count[address];
220
+ auto mean_new = shmem_mean[address];
221
+ auto m2n_new = shmem_m2n[address];
222
+
223
+ welford_merge_element(count, mean, m2n, count_new, mean_new, m2n_new);
224
+ }
225
+ }
226
+ }
227
+
228
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, bool train, typename index_t>
229
+ __global__ void batch_norm_transform_input_kernel(
230
+ const GenericPackedTensorAccessor<const input_scalar_t, 3, RestrictPtrTraits, index_t> input,
231
+ GenericPackedTensorAccessor<input_scalar_t, 3, RestrictPtrTraits, index_t> output,
232
+ const GenericPackedTensorAccessor<typename std::conditional_t<train, stat_accscalar_t, stat_scalar_t>, 1, RestrictPtrTraits, index_t> mean_,
233
+ const GenericPackedTensorAccessor<typename std::conditional_t<train, stat_accscalar_t, stat_scalar_t>, 1, RestrictPtrTraits, index_t> var_or_invstd,
234
+ const GenericPackedTensorAccessor<const stat_scalar_t, 1, RestrictPtrTraits, index_t> weight,
235
+ const GenericPackedTensorAccessor<const stat_scalar_t, 1, RestrictPtrTraits, index_t> bias,
236
+ stat_accscalar_t epsilon) {
237
+
238
+ index_t plane = blockIdx.x;
239
+
240
+ if (plane >= input.size(1)) {
241
+ return;
242
+ }
243
+
244
+ stat_accscalar_t gamma = weight.size(0) > 0 ? static_cast<stat_accscalar_t>(weight[plane]) : static_cast<stat_accscalar_t>(1);
245
+ stat_accscalar_t beta = bias.size(0) > 0 ? static_cast<stat_accscalar_t>(bias[plane]) : static_cast<stat_accscalar_t>(0);
246
+ stat_accscalar_t mean = static_cast<stat_accscalar_t>(mean_[plane]);
247
+ stat_accscalar_t invstd;
248
+ if (train) {
249
+ invstd = var_or_invstd[plane];
250
+ } else {
251
+ invstd = static_cast<stat_accscalar_t>(1) / device_sqrt(static_cast<stat_accscalar_t>(var_or_invstd[plane]) + epsilon);
252
+ }
253
+
254
+ index_t bs = input.size(0);
255
+ index_t fs = input.size(2);
256
+
257
+ index_t bstep = blockDim.y * gridDim.y;
258
+ for (index_t batch = threadIdx.y + blockIdx.y * blockDim.y; batch < bs; batch += bstep) {
259
+ auto o = output[batch][plane];
260
+ auto i = input[batch][plane];
261
+ for (index_t feature = threadIdx.x; feature < fs; feature += blockDim.x) {
262
+ o[feature] = static_cast<input_scalar_t>(gamma * (i[feature] - mean) * invstd + beta);
263
+ }
264
+ }
265
+ }
266
+
267
+ struct InvStd {
268
+ template <typename T>
269
+ __device__ __forceinline__ T operator()(T var, double epsilon) const {
270
+ T invstd = 0;
271
+ if (var != static_cast<T>(0) || epsilon != static_cast<T>(0)) {
272
+ invstd = static_cast<T>(1) / device_sqrt(var + epsilon);
273
+ }
274
+ return invstd;
275
+ }
276
+ };
277
+
278
+ struct Var {
279
+ template <typename T>
280
+ __device__ __forceinline__ T operator()(T var, double epsilon) const {
281
+ return var;
282
+ }
283
+ };
284
+
285
+ template <typename VarTransform, typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
286
+ __global__ void batch_norm_collect_statistics_kernel(
287
+ const GenericPackedTensorAccessor<const input_scalar_t, 3, RestrictPtrTraits, index_t> input,
288
+ const stat_accscalar_t epsilon,
289
+ const stat_accscalar_t momentum,
290
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, RestrictPtrTraits, index_t> save_mean,
291
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, RestrictPtrTraits, index_t> save_transformed_var) {
292
+
293
+ __shared__ int shared_n[2 * 2 * C10_WARP_SIZE_UPPER_BOUND + C10_WARP_SIZE_UPPER_BOUND];
294
+
295
+ int plane = blockIdx.x;
296
+ int N = input.size(0) * input.size(2);
297
+ int tid = threadIdx.x + threadIdx.y * blockDim.x;
298
+
299
+ // Compute the mean and variance across (batch, x/y/z)
300
+ // this uses the Welford (in the for loop)/parallel algorithm (to sum across the block)
301
+ // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_Online_algorithm
302
+ // and the parallel algorithm on the same page.
303
+ // We use two shuffles to reduce across the entire block.
304
+ // https://devblogs.nvidia.com/faster-parallel-reductions-kepler/ has a description.
305
+ stat_accscalar_t* shared_avg_var = (stat_accscalar_t*) &shared_n[C10_WARP_SIZE];
306
+
307
+ // first the reductions each thread does separately
308
+ stat_accscalar_t avg = 0;
309
+ stat_accscalar_t var_n = 0;
310
+ int n = 0;
311
+ for (int batch = threadIdx.y; batch < input.size(0); batch += blockDim.y) {
312
+ #if defined(USE_ROCM)
313
+ constexpr int UNRL = 4;
314
+ stat_accscalar_t v_[UNRL];
315
+ for (int x = threadIdx.x; x < input.size(2); x += blockDim.x*UNRL) {
316
+ for (int u = 0; u < UNRL; u++)
317
+ v_[u] = input[batch][plane][std::min(x+u*blockDim.x, input.size(2)-1)];
318
+ for (int u = 0; u < UNRL; u++) {
319
+ if (x+u*blockDim.x < input.size(2)) {
320
+ stat_accscalar_t d1 = v_[u] - avg;
321
+ n++;
322
+ avg += d1 / n;
323
+ var_n += d1 * (v_[u] - avg);
324
+ }
325
+ }
326
+ }
327
+ #else
328
+ for (int x = threadIdx.x; x < input.size(2); x += blockDim.x) {
329
+ stat_accscalar_t v = input[batch][plane][x];
330
+ stat_accscalar_t d1 = v - avg;
331
+ n++;
332
+ avg += d1 / n;
333
+ var_n += d1 * (v - avg);
334
+ }
335
+ #endif
336
+ }
337
+
338
+ // first warpSum to get one value per thread to
339
+ // one value per warp
340
+ for (int i = 0; i < getMSB(C10_WARP_SIZE); ++i) {
341
+ stat_accscalar_t o_avg = WARP_SHFL_XOR(avg, 1 << i, C10_WARP_SIZE);
342
+ int o_n = WARP_SHFL_XOR(n, 1 << i, C10_WARP_SIZE);
343
+ stat_accscalar_t factor = 1.0 / fmaxf(1.0, n+o_n);
344
+ var_n += WARP_SHFL_XOR(var_n, 1 << i, C10_WARP_SIZE) + (avg - o_avg) * (avg - o_avg) * n * o_n * factor;
345
+ avg = (n * avg + o_n * o_avg) * factor;
346
+ n += o_n;
347
+ }
348
+
349
+ // this writes each warps item into shared memory
350
+ // there are at most C10_WARP_SIZE items left because
351
+ // there are at most C10_WARP_SIZE**2 threads at the beginning
352
+ __syncthreads();
353
+ if (tid % C10_WARP_SIZE == 0) {
354
+ shared_n[tid / C10_WARP_SIZE] = n;
355
+ shared_avg_var[tid / C10_WARP_SIZE * 2] = avg;
356
+ shared_avg_var[tid / C10_WARP_SIZE * 2 + 1] = var_n;
357
+ }
358
+ __syncthreads();
359
+ // now have a second warpSum to reduce the intermediate values
360
+ // from shared memory to a single number. The very first
361
+ // thread writes it to shared memory.
362
+
363
+ if (tid < C10_WARP_SIZE) {
364
+ n = (tid < blockDim.x * blockDim.y / C10_WARP_SIZE ? shared_n[tid] : 0);
365
+ avg = (tid < blockDim.x * blockDim.y / C10_WARP_SIZE ? shared_avg_var[2 * tid] : stat_accscalar_t(0));
366
+ var_n = (tid < blockDim.x * blockDim.y / C10_WARP_SIZE ? shared_avg_var[2 * tid + 1] : stat_accscalar_t(0));
367
+ }
368
+ for (int i = 0; i < getMSB(C10_WARP_SIZE); ++i) {
369
+ stat_accscalar_t o_avg = WARP_SHFL_XOR(avg, 1 << i, C10_WARP_SIZE);
370
+ int o_n = WARP_SHFL_XOR(n, 1 << i, C10_WARP_SIZE);
371
+ stat_accscalar_t factor = 1.0 / fmaxf(1.0, n+o_n);
372
+ var_n += WARP_SHFL_XOR(var_n, 1 << i, C10_WARP_SIZE) + (avg - o_avg) * (avg - o_avg) * n * o_n * factor;
373
+ avg = (n * avg + o_n * o_avg) * factor;
374
+ n += o_n;
375
+ }
376
+
377
+ // Save the mean, variance, and moving averages
378
+ if (tid == 0) {
379
+ if (save_mean.data() != NULL) {
380
+ save_mean[plane] = avg;
381
+ }
382
+ if (save_transformed_var.data() != NULL) {
383
+ save_transformed_var[plane] = VarTransform{}(var_n / N, epsilon);
384
+ }
385
+ }
386
+
387
+ }
388
+
389
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
390
+ __global__ void batch_norm_backward_kernel(
391
+ const GenericPackedTensorAccessor<const input_scalar_t, 3, DefaultPtrTraits, index_t> input,
392
+ const GenericPackedTensorAccessor<const input_scalar_t, 3, DefaultPtrTraits, index_t> grad_output,
393
+ GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_input,
394
+ GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> grad_weight,
395
+ GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> grad_bias,
396
+ const GenericPackedTensorAccessor<const stat_scalar_t, 1, DefaultPtrTraits, index_t> weight,
397
+ const GenericPackedTensorAccessor<const stat_scalar_t, 1, DefaultPtrTraits, index_t> running_mean,
398
+ const GenericPackedTensorAccessor<const stat_scalar_t, 1, DefaultPtrTraits, index_t> running_var,
399
+ const GenericPackedTensorAccessor<const stat_accscalar_t, 1, DefaultPtrTraits, index_t> save_mean,
400
+ const GenericPackedTensorAccessor<const stat_accscalar_t, 1, DefaultPtrTraits, index_t> save_invstd,
401
+ bool train,
402
+ stat_accscalar_t epsilon) {
403
+
404
+ index_t plane = blockIdx.x;
405
+ index_t N = grad_output.size(0) * grad_output.size(2);
406
+
407
+ stat_accscalar_t mean, invstd;
408
+ if (train) {
409
+ mean = save_mean[plane];
410
+ invstd = save_invstd[plane];
411
+ } else {
412
+ mean = static_cast<stat_accscalar_t>(running_mean[plane]);
413
+ invstd = static_cast<stat_accscalar_t>(1) / device_sqrt(static_cast<stat_accscalar_t>(running_var[plane]) + epsilon);
414
+ }
415
+
416
+ stat_accscalar_t weight_val = weight.size(0) > 0 ? static_cast<stat_accscalar_t>(weight[plane]) : stat_accscalar_t(1);
417
+ stat_accscalar_t norm = stat_accscalar_t(1) / N;
418
+
419
+ // Compute two values across (batch, x/y/z) in one pass:
420
+ // 1. Sum(grad_output)
421
+ // 2. DotProduct(input - mean, grad_output)
422
+ GradOp<input_scalar_t, stat_accscalar_t, GenericPackedTensorAccessor<const input_scalar_t, 3, DefaultPtrTraits, index_t>> g(mean, input, grad_output);
423
+ auto res = reduce<Float2<input_scalar_t, stat_accscalar_t>>(g, grad_output, plane);
424
+
425
+ stat_accscalar_t grad_output_sum = res.v1;
426
+ stat_accscalar_t dot_p = res.v2;
427
+
428
+ stat_accscalar_t grad_mean = grad_output_sum * norm;
429
+ stat_accscalar_t proj_scale = dot_p * norm * invstd * invstd;
430
+ stat_accscalar_t grad_scale = invstd * weight_val;
431
+
432
+ if (grad_input.data() != NULL) {
433
+ for (int batch = threadIdx.y; batch < grad_output.size(0); batch += blockDim.y) {
434
+ for (int x = threadIdx.x; x < grad_output.size(2); x += blockDim.x) {
435
+ input_scalar_t go = grad_output[batch][plane][x];
436
+ if (train) {
437
+ stat_accscalar_t inp = input[batch][plane][x];
438
+ stat_accscalar_t proj = (inp - mean) * proj_scale;
439
+ grad_input[batch][plane][x] = static_cast<input_scalar_t>((go - proj - grad_mean) * grad_scale);
440
+ } else {
441
+ grad_input[batch][plane][x] = static_cast<input_scalar_t>(go * grad_scale);
442
+ }
443
+ }
444
+ }
445
+ }
446
+
447
+ if (grad_weight.size(0) > 0) {
448
+ if (threadIdx.x == 0) {
449
+ grad_weight[plane] = static_cast<stat_scalar_t>(dot_p * invstd);
450
+ }
451
+ }
452
+
453
+ if (grad_bias.size(0) > 0) {
454
+ if (threadIdx.x == 0) {
455
+ grad_bias[plane] = static_cast<stat_scalar_t>(grad_output_sum);
456
+ }
457
+ }
458
+ }
459
+
460
+ template <typename scalar_t, typename accscalar_t, typename index_t>
461
+ __global__ void batch_norm_reduce_statistics_kernel(
462
+ const GenericPackedTensorAccessor<accscalar_t, 2, RestrictPtrTraits, index_t> vec_mean,
463
+ const GenericPackedTensorAccessor<accscalar_t, 2, RestrictPtrTraits, index_t> vec_invstd,
464
+ GenericPackedTensorAccessor<accscalar_t, 1, RestrictPtrTraits, index_t> mean,
465
+ GenericPackedTensorAccessor<accscalar_t, 1, RestrictPtrTraits, index_t> invstd,
466
+ GenericPackedTensorAccessor<scalar_t, 1, RestrictPtrTraits, index_t> running_mean,
467
+ GenericPackedTensorAccessor<scalar_t, 1, RestrictPtrTraits, index_t> running_var,
468
+ const accscalar_t epsilon,
469
+ const accscalar_t momentum,
470
+ const GenericPackedTensorAccessor<scalar_t, 1, RestrictPtrTraits, index_t> counts) {
471
+
472
+ int feature_size = vec_mean.size(1);
473
+ int world_size = vec_mean.size(0);
474
+
475
+ int bid = blockIdx.x;
476
+ int tid = threadIdx.x;
477
+
478
+ // first the reductions each thread does separately
479
+ for (int i = bid*blockDim.x+tid; i < feature_size; i += gridDim.x*blockDim.x) {
480
+ accscalar_t avg = 0;
481
+ accscalar_t var_n = 0;
482
+ index_t n = 0;
483
+ for (int j = 0; j < world_size; j++) {
484
+ scalar_t count = counts[j];
485
+ accscalar_t m = vec_mean[j][i];
486
+ accscalar_t v = accscalar_t(1.0) / (vec_invstd[j][i]);
487
+ v = (v * v - epsilon) * count;
488
+ accscalar_t factor = 1.0 / (n + count);
489
+ var_n += v + (avg - m) * (avg - m) * n * count * factor;
490
+ avg = n * factor * avg + count * factor * m;
491
+ n += count;
492
+ }
493
+ mean[i] = avg;
494
+ invstd[i] = static_cast<accscalar_t>(1) / device_sqrt(var_n / n + epsilon);
495
+ if (running_mean.data() != NULL) {
496
+ running_mean[i] = static_cast<scalar_t>((1 - momentum) * running_mean[i] + momentum * avg);
497
+ }
498
+ accscalar_t unbiasedVar = var_n / (n - 1);
499
+ if (running_var.data() != NULL) {
500
+ running_var[i] = static_cast<scalar_t>((1 - momentum) * running_var[i] + momentum * unbiasedVar);
501
+ }
502
+ }
503
+
504
+ }
505
+
506
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
507
+ __global__ void batch_norm_backward_reduce_kernel(
508
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> input,
509
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_output,
510
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> mean,
511
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> invstd,
512
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy,
513
+ GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy_xmu,
514
+ GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> grad_weight,
515
+ GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> grad_bias) {
516
+
517
+ index_t plane = blockIdx.x;
518
+
519
+ stat_accscalar_t r_mean = mean[plane];
520
+ stat_accscalar_t factor = invstd[plane];
521
+
522
+ GradOp<input_scalar_t, stat_accscalar_t, GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t>> g(r_mean, input, grad_output);
523
+ auto res = reduce<Float2<input_scalar_t, stat_accscalar_t>>(g, grad_output, plane);
524
+
525
+ if (threadIdx.x == 0) {
526
+ if (grad_weight.size(0) > 0) {
527
+ grad_weight[plane] = static_cast<stat_scalar_t>(res.v2 * factor);
528
+ }
529
+ if (grad_bias.size(0) > 0) {
530
+ grad_bias[plane] = static_cast<stat_scalar_t>(res.v1);
531
+ }
532
+ if (sum_dy.size(0) > 0) {
533
+ sum_dy[plane] = static_cast<stat_accscalar_t>(res.v1);
534
+ }
535
+ if (sum_dy_xmu.size(0) > 0) {
536
+ sum_dy_xmu[plane] = static_cast<stat_accscalar_t>(res.v2);
537
+ }
538
+ }
539
+ }
540
+
541
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
542
+ __device__ __forceinline__ void batch_norm_backward_elemt_kernel_impl(
543
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> input,
544
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_output,
545
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> mean,
546
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> invstd,
547
+ const GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> weight,
548
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy,
549
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy_xmu,
550
+ GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_input,
551
+ const stat_accscalar_t norm_fct) {
552
+ index_t plane = blockIdx.x;
553
+
554
+ if (plane >= input.size(1)) {
555
+ return;
556
+ }
557
+
558
+ stat_accscalar_t m_c = mean[plane];
559
+ stat_accscalar_t m_dy_c = sum_dy[plane] * norm_fct;
560
+ stat_accscalar_t factor_1_c = invstd[plane];
561
+ stat_accscalar_t factor_2_c = weight.size(0) > 0 ? static_cast<stat_accscalar_t>(weight[plane]) : stat_accscalar_t(1);
562
+ factor_2_c *= factor_1_c;
563
+ factor_1_c = factor_1_c * factor_1_c * sum_dy_xmu[plane] * norm_fct;
564
+
565
+ index_t bs = input.size(0);
566
+ index_t fs = input.size(2);
567
+
568
+ index_t bstep = blockDim.y * gridDim.y;
569
+ for (index_t batch = threadIdx.y + blockIdx.y * blockDim.y; batch < bs; batch += bstep) {
570
+ auto g_i = grad_input[batch][plane];
571
+ auto g_o = grad_output[batch][plane];
572
+ auto i = input[batch][plane];
573
+ for (index_t feature = threadIdx.x; feature < fs; feature += blockDim.x) {
574
+ g_i[feature] = static_cast<input_scalar_t>((g_o[feature] - m_dy_c - (i[feature] - m_c) * factor_1_c) * factor_2_c);
575
+ }
576
+ }
577
+ }
578
+
579
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
580
+ __global__ void batch_norm_backward_elemt_kernel(
581
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> input,
582
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_output,
583
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> mean,
584
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> invstd,
585
+ const GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> weight,
586
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy,
587
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy_xmu,
588
+ GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_input,
589
+ const int* __restrict__ numel, const int world_size) {
590
+ int64_t total_numel = 0;
591
+ for (int i = 0; i < world_size; i ++) {
592
+ total_numel += numel[i];
593
+ }
594
+
595
+ const stat_accscalar_t norm_fct =
596
+ static_cast<stat_accscalar_t>(1) / static_cast<stat_accscalar_t>(total_numel);
597
+ batch_norm_backward_elemt_kernel_impl(
598
+ input, grad_output, mean, invstd, weight, sum_dy, sum_dy_xmu, grad_input, norm_fct);
599
+ }
600
+
601
+ template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t>
602
+ __global__ void batch_norm_backward_elemt_kernel(
603
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> input,
604
+ const GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_output,
605
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> mean,
606
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> invstd,
607
+ const GenericPackedTensorAccessor<stat_scalar_t, 1, DefaultPtrTraits, index_t> weight,
608
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy,
609
+ const GenericPackedTensorAccessor<stat_accscalar_t, 1, DefaultPtrTraits, index_t> sum_dy_xmu,
610
+ GenericPackedTensorAccessor<input_scalar_t, 3, DefaultPtrTraits, index_t> grad_input,
611
+ const stat_accscalar_t norm_fct) {
612
+ batch_norm_backward_elemt_kernel_impl(
613
+ input, grad_output, mean, invstd, weight, sum_dy, sum_dy_xmu, grad_input, norm_fct);
614
+ }
615
+
616
+ template <typename scalar_t, int64_t dim, template <typename U> class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
617
+ static GenericPackedTensorAccessor<scalar_t, dim, PtrTraits, index_t> get_packed_accessor(
618
+ const Tensor& t, std::string_view var_name) {
619
+ constexpr auto expect_type = c10::CppTypeToScalarType<typename std::remove_const_t<scalar_t>>::value;
620
+ const auto actual_type = t.scalar_type();
621
+ TORCH_CHECK(actual_type == expect_type, "Expected ", var_name,
622
+ " to have type ", expect_type, " but got ", actual_type);
623
+ return t.generic_packed_accessor<scalar_t, dim, PtrTraits, index_t>();
624
+ }
625
+
626
+ template <typename scalar_t, int64_t dim, template <typename U> class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
627
+ static GenericPackedTensorAccessor<scalar_t, dim, PtrTraits, index_t> packed_accessor_or_dummy(
628
+ const Tensor& t, std::string_view var_name) {
629
+ if (!t.defined()) {
630
+ const std::array<index_t, dim> zeros{{0}};
631
+ return GenericPackedTensorAccessor<scalar_t, dim, PtrTraits, index_t>(nullptr, zeros.data(), zeros.data());
632
+ }
633
+ return get_packed_accessor<scalar_t, dim, PtrTraits, index_t>(t, var_name);
634
+ }
635
+
636
+ template<typename input_scalar_t, typename stat_scalar_t, typename index_t>
637
+ std::tuple<Tensor, Tensor, Tensor> batch_norm_backward_cuda_template(const Tensor& grad_out_, const Tensor& input_, const Tensor& weight_,
638
+ const Tensor& running_mean_, const Tensor& running_var_, const Tensor& save_mean_, const Tensor& save_invstd_,
639
+ bool train, double epsilon, std::array<bool,3> grad_input_mask) {
640
+
641
+ using accscalar_t = at::acc_type<stat_scalar_t, true>;
642
+ Tensor grad_input_;
643
+ Tensor grad_input_reshaped;
644
+ Tensor grad_weight_;
645
+ Tensor grad_bias_;
646
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1});
647
+ auto grad_output_reshaped = grad_out_.reshape(input_reshaped.sizes());
648
+
649
+ if (grad_input_mask[0]) {
650
+ grad_input_ = at::empty_like(input_, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
651
+ grad_input_reshaped = grad_input_.view(input_reshaped.sizes());
652
+ }
653
+ if (grad_input_mask[1]) {
654
+ grad_weight_ = at::empty_like(weight_, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
655
+ }
656
+ if (grad_input_mask[2]) {
657
+ grad_bias_ = at::empty_like(weight_, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
658
+ }
659
+
660
+ auto input = get_packed_accessor<
661
+ const input_scalar_t, 3, DefaultPtrTraits, index_t>(input_reshaped, "input");
662
+ auto grad_output = get_packed_accessor<
663
+ const input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_output_reshaped, "grad_output");
664
+ auto grad_input = packed_accessor_or_dummy<
665
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_input_reshaped, "grad_input");
666
+ auto weight = packed_accessor_or_dummy<
667
+ const stat_scalar_t, 1, DefaultPtrTraits, index_t>(weight_, "weight");
668
+ auto grad_weight = packed_accessor_or_dummy<
669
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(grad_weight_, "grad_weight");
670
+ auto grad_bias = packed_accessor_or_dummy<
671
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(grad_bias_, "grad_bias");
672
+ auto running_mean = packed_accessor_or_dummy<
673
+ const stat_scalar_t, 1, DefaultPtrTraits, index_t>(running_mean_, "running_mean");
674
+ auto running_var = packed_accessor_or_dummy<
675
+ const stat_scalar_t, 1, DefaultPtrTraits, index_t>(running_var_, "running_var");
676
+ auto save_mean = packed_accessor_or_dummy<
677
+ const accscalar_t, 1, DefaultPtrTraits, index_t>(save_mean_, "save_mean");
678
+ auto save_invstd = packed_accessor_or_dummy<
679
+ const accscalar_t, 1, DefaultPtrTraits, index_t>(save_invstd_, "save_invstd");
680
+
681
+ auto stream = at::cuda::getCurrentCUDAStream();
682
+ dim3 blocks(input.size(1));
683
+ int tf = getNumThreads(input.size(2));
684
+ dim3 threads(tf, std::max<int>(1, MAX_BLOCK_SIZE/tf));
685
+
686
+ batch_norm_backward_kernel<input_scalar_t, stat_scalar_t, accscalar_t, index_t> <<<blocks, threads, 0, stream>>>
687
+ (input, grad_output, grad_input, grad_weight, grad_bias, weight, running_mean, running_var,
688
+ save_mean, save_invstd, train, epsilon);
689
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
690
+
691
+ return std::make_tuple(
692
+ std::move(grad_input_), std::move(grad_weight_), std::move(grad_bias_));
693
+ }
694
+
695
+ template<typename scalar_t, typename index_t, typename VarTransform>
696
+ void batch_norm_stats_cuda_template(
697
+ const Tensor& out_mean, const Tensor& out_invstd, const Tensor& input_, double epsilon) {
698
+
699
+ using accscalar_t = at::acc_type<scalar_t, true>;
700
+ int64_t n_input = input_.size(1);
701
+ Tensor dummy_mean_;
702
+ Tensor dummy_var_;
703
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1}); // internally we merge the feature dimensions
704
+
705
+ resize_output(out_mean, {n_input});
706
+ resize_output(out_invstd, {n_input});
707
+ auto input = get_packed_accessor<
708
+ const scalar_t, 3, RestrictPtrTraits, index_t>(input_reshaped, "input");
709
+ TORCH_INTERNAL_ASSERT(out_invstd.dim() == 1 && out_invstd.is_contiguous() &&
710
+ out_invstd.sizes()[0]);
711
+ TORCH_INTERNAL_ASSERT(out_mean.dim() == 1 && out_mean.is_contiguous() &&
712
+ out_mean.sizes()[0]);
713
+
714
+ auto mean = packed_accessor_or_dummy<
715
+ accscalar_t, 1, RestrictPtrTraits, index_t>(out_mean, "out_mean");
716
+ auto invstd = packed_accessor_or_dummy<
717
+ accscalar_t, 1, RestrictPtrTraits, index_t>(out_invstd, "out_invstd");
718
+ auto stream = at::cuda::getCurrentCUDAStream();
719
+
720
+ dim3 blocks(input.size(1));
721
+ int tf = getNumThreads(input.size(2));
722
+ dim3 threads(tf, std::max<int>(1, MAX_BLOCK_SIZE/tf));
723
+ batch_norm_collect_statistics_kernel<VarTransform, scalar_t, scalar_t, accscalar_t, index_t> <<<blocks, threads, 0, stream>>>
724
+ (input, epsilon, 0.0, mean, invstd);
725
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
726
+ }
727
+
728
+ template<typename input_scalar_t, typename stat_scalar_t, typename index_t>
729
+ void batch_norm_elemt_cuda_template(const Tensor& output_, const Tensor& input_, const Tensor& weight_,
730
+ const Tensor& bias_, const Tensor& mean_, const Tensor& invstd_) {
731
+
732
+ using stat_accscalar_t = at::acc_type<stat_scalar_t, true>;
733
+ int64_t n_input = input_.size(1);
734
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1}); // internally we merge the feature dimensions
735
+ auto output_reshaped = output_.view({input_.size(0), input_.size(1), -1});
736
+
737
+ auto input = get_packed_accessor<
738
+ const input_scalar_t, 3, RestrictPtrTraits, index_t>(input_reshaped, "input");
739
+ auto output = get_packed_accessor<
740
+ input_scalar_t, 3, RestrictPtrTraits, index_t>(output_reshaped, "output");
741
+ auto weight = packed_accessor_or_dummy<
742
+ const stat_scalar_t, 1, RestrictPtrTraits, index_t>(weight_, "weight");
743
+ auto bias = packed_accessor_or_dummy<
744
+ const stat_scalar_t, 1, RestrictPtrTraits, index_t>(bias_, "bias");
745
+ auto mean = packed_accessor_or_dummy<
746
+ stat_accscalar_t, 1, RestrictPtrTraits, index_t>(mean_, "mean");
747
+ auto invstd = packed_accessor_or_dummy<
748
+ stat_accscalar_t, 1, RestrictPtrTraits, index_t>(invstd_, "invstd");
749
+ auto stream = at::cuda::getCurrentCUDAStream();
750
+
751
+ // NOTE: We use transform_input_kernel in training mode, which ignores epsilon
752
+ const double dummy_epsilon = 1e-5;
753
+
754
+ // The input_transform kernel is pointwise, but we need to balance reading parameters (save_var/mean,
755
+ // weight/bias) - which we only do once and have a for loop afterwards - with having many threads and blocks
756
+ // and good occupancy. Quite likely, we could go with even more blocks than 1024.
757
+ // The various planes are independent, so we use blocks for them.
758
+ int tf = std::max<int>(getNumThreads(input.size(2)/4),
759
+ std::min<int>(getNumThreads(input.size(2)), 64));
760
+ int tb = std::max<int>(64/tf, 1);
761
+ dim3 blocks_trans(input.size(1), std::max<int>(1, std::min<int>((256*1024)/input.size(1),
762
+ (input.size(0)+tb-1)/tb)));
763
+ blocks_trans.y = std::min(blocks_trans.y, MAX_GRID_SIZE);
764
+ dim3 threads_trans(tf, tb);
765
+ batch_norm_transform_input_kernel<input_scalar_t, stat_scalar_t, stat_accscalar_t, true, index_t> <<<blocks_trans, threads_trans, 0, stream>>>
766
+ (input, output, mean, invstd, weight, bias, dummy_epsilon);
767
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
768
+ }
769
+
770
+ template<typename scalar_t, typename accscalar_t, typename index_t>
771
+ std::tuple<Tensor, Tensor> batch_norm_gather_stats_cuda_template(const Tensor& mean_, const Tensor& invstd_,
772
+ const Tensor& running_mean_, const Tensor& running_var_,
773
+ double momentum, double epsilon, const Tensor& counts_) {
774
+
775
+ Tensor save_mean_;
776
+ Tensor save_invstd_;
777
+
778
+ auto features = mean_.size(1);
779
+ auto input_options = mean_.options();
780
+ if (mean_.scalar_type() == at::ScalarType::Half || mean_.scalar_type() == at::ScalarType::BFloat16) {
781
+ input_options = input_options.dtype(ScalarType::Float);
782
+ }
783
+ save_mean_ = at::empty({features}, input_options);
784
+ save_invstd_ = at::empty({features}, input_options);
785
+
786
+ auto mean = packed_accessor_or_dummy<
787
+ accscalar_t, 2, RestrictPtrTraits, index_t>(mean_, "mean");
788
+ auto invstd = packed_accessor_or_dummy<
789
+ accscalar_t, 2, RestrictPtrTraits, index_t>(invstd_, "invstd");
790
+ auto running_mean = packed_accessor_or_dummy<
791
+ scalar_t, 1, RestrictPtrTraits, index_t>(running_mean_, "running_mean");
792
+ auto running_var = packed_accessor_or_dummy<
793
+ scalar_t, 1, RestrictPtrTraits, index_t>(running_var_, "running_mean");
794
+ auto counts = packed_accessor_or_dummy<
795
+ scalar_t, 1, RestrictPtrTraits, index_t>(counts_, "counts");
796
+
797
+ auto save_mean = get_packed_accessor<
798
+ accscalar_t, 1, RestrictPtrTraits, index_t>(save_mean_, "save_mean");
799
+ auto save_invstd = get_packed_accessor<
800
+ accscalar_t, 1, RestrictPtrTraits, index_t>(save_invstd_, "save_invstd");
801
+ auto stream = at::cuda::getCurrentCUDAStream();
802
+
803
+ int block = getNumThreads(features);
804
+ int grid = std::max<int>(1, features/block);
805
+ batch_norm_reduce_statistics_kernel<scalar_t, accscalar_t, index_t> <<<grid, block, 0, stream>>>
806
+ (mean, invstd, save_mean, save_invstd, running_mean, running_var, epsilon, momentum, counts);
807
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
808
+
809
+ return std::make_tuple(std::move(save_mean_), std::move(save_invstd_));
810
+ }
811
+
812
+ template<typename input_scalar_t, typename stat_scalar_t, typename index_t>
813
+ std::tuple<Tensor, Tensor, Tensor, Tensor> batch_norm_backward_reduce_cuda_template(const Tensor& grad_out_, const Tensor& input_,
814
+ const Tensor& mean_, const Tensor& invstd_, const Tensor& weight_,
815
+ const bool input_g, const bool weight_g, const bool bias_g) {
816
+
817
+ using stat_accscalar_t = at::acc_type<stat_scalar_t, true>;
818
+ int64_t n_input = input_.size(1);
819
+ Tensor sum_dy_;
820
+ Tensor sum_dy_xmu_;
821
+ Tensor grad_weight_;
822
+ Tensor grad_bias_;
823
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1}); // internally we merge the feature dimensions
824
+ auto grad_output_reshaped = grad_out_.reshape(input_reshaped.sizes());
825
+
826
+ if (input_g) {
827
+ sum_dy_ = at::empty_like(mean_, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
828
+ sum_dy_xmu_ = at::empty_like(mean_, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
829
+ }
830
+ if (weight_g) {
831
+ grad_weight_ = at::empty({n_input}, weight_.options());
832
+ }
833
+ if (bias_g) {
834
+ grad_bias_ = at::empty({n_input}, weight_.options());
835
+ }
836
+
837
+ auto input = get_packed_accessor<
838
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(input_reshaped, "input");
839
+ auto grad_output = get_packed_accessor<
840
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_output_reshaped, "grad_output");
841
+ auto grad_weight = packed_accessor_or_dummy<
842
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(grad_weight_, "grad_weight");
843
+ auto grad_bias = packed_accessor_or_dummy<
844
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(grad_bias_, "grad_bias");
845
+ auto mean = packed_accessor_or_dummy<
846
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(mean_, "mean");
847
+ auto invstd = packed_accessor_or_dummy<
848
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(invstd_, "invstd");
849
+ auto sum_dy = packed_accessor_or_dummy<
850
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_, "sum_dy");
851
+ auto sum_dy_xmu = packed_accessor_or_dummy<
852
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_xmu_, "sum_dy_xmu");
853
+
854
+ auto batch_size = input_reshaped.size(0);
855
+ auto feature_size = input_reshaped.size(2);
856
+ auto stream = at::cuda::getCurrentCUDAStream();
857
+
858
+ int warp_size = at::cuda::warp_size();
859
+ int block_y = std::min<int>(lastPow2(batch_size), MAX_BLOCK_SIZE/warp_size);
860
+ // We want block_x to be at least a warp width
861
+ int block_x = std::min<int>(std::max<int>(getNumThreads(feature_size), warp_size), MAX_BLOCK_SIZE/block_y);
862
+ const dim3 block(block_x, block_y);
863
+ const dim3 grid(n_input);
864
+
865
+ batch_norm_backward_reduce_kernel<input_scalar_t, stat_scalar_t, stat_accscalar_t, index_t> <<<grid, block, 0, stream>>>
866
+ (input, grad_output, mean, invstd, sum_dy, sum_dy_xmu, grad_weight, grad_bias);
867
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
868
+
869
+ return std::make_tuple(
870
+ std::move(sum_dy_),
871
+ std::move(sum_dy_xmu_),
872
+ std::move(grad_weight_),
873
+ std::move(grad_bias_));
874
+ }
875
+
876
+ template<typename input_scalar_t, typename stat_scalar_t, typename index_t>
877
+ Tensor batch_norm_backward_elemt_cuda_template(const Tensor& grad_out_, const Tensor& input_,
878
+ const Tensor& mean_, const Tensor& invstd_,
879
+ const Tensor& weight_, const Tensor& sum_dy_, const Tensor& sum_dy_xmu_) {
880
+
881
+ using stat_accscalar_t = at::acc_type<stat_scalar_t, true>;
882
+ int64_t n_input = input_.size(1);
883
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1}); // internally we merge the feature dimensions
884
+ auto grad_output_reshaped = grad_out_.reshape(input_reshaped.sizes());
885
+ auto grad_input_reshaped = at::empty_like(input_reshaped, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
886
+
887
+ auto input = get_packed_accessor<
888
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(input_reshaped, "input");
889
+ auto grad_input = get_packed_accessor<
890
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_input_reshaped, "grad_input");
891
+ auto grad_output = get_packed_accessor<
892
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_output_reshaped, "grad_output");
893
+ auto mean = packed_accessor_or_dummy<
894
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(mean_, "mean");
895
+ auto invstd = packed_accessor_or_dummy<
896
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(invstd_, "invstd");
897
+ auto weight = packed_accessor_or_dummy<
898
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(weight_, "weight");
899
+ auto sum_dy = packed_accessor_or_dummy<
900
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_, "sum_dy");
901
+ auto sum_dy_xmu = packed_accessor_or_dummy<
902
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_xmu_, "sum_dy_xmu");
903
+
904
+ auto stream = at::cuda::getCurrentCUDAStream();
905
+
906
+ // The kernel is pointwise, but we need to balance reading parameters (save_var/mean,
907
+ // weight/bias) - which we only do once and have a for loop afterwards - with having many threads and blocks
908
+ // and good occupancy. Quiet likely, we could go with even more blocks than 1024.
909
+ // The various planes are independent, so we use blocks for them.
910
+ int tf = std::max<int>(getNumThreads(input.size(2)/4),
911
+ std::min<int>(getNumThreads(input.size(2)), 64));
912
+ int tb = std::max<int>(64/tf, 1);
913
+ dim3 blocks_trans(input.size(1), std::max<int>(1, std::min<int>((256*1024)/input.size(1),
914
+ (input.size(0)+tb-1)/tb)));
915
+ blocks_trans.y = std::min(blocks_trans.y, MAX_GRID_SIZE);
916
+ dim3 threads_trans(tf, tb);
917
+ auto reduction_size = input_.numel() / n_input;
918
+ auto norm_fct = static_cast<stat_accscalar_t>(1.0 / reduction_size);
919
+ batch_norm_backward_elemt_kernel<input_scalar_t, stat_scalar_t, stat_accscalar_t, index_t>
920
+ <<<blocks_trans, threads_trans, 0, stream>>>
921
+ (input, grad_output, mean, invstd, weight, sum_dy, sum_dy_xmu, grad_input, norm_fct);
922
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
923
+
924
+ return grad_input_reshaped.view(input_.sizes());
925
+ }
926
+
927
+ template<typename input_scalar_t, typename stat_scalar_t, typename index_t>
928
+ Tensor batch_norm_backward_elemt_cuda_template(const Tensor& grad_out_, const Tensor& input_,
929
+ const Tensor& mean_, const Tensor& invstd_,
930
+ const Tensor& weight_, const Tensor& sum_dy_, const Tensor& sum_dy_xmu_, const Tensor& count) {
931
+
932
+ using stat_accscalar_t = at::acc_type<stat_scalar_t, true>;
933
+ int64_t n_input = input_.size(1);
934
+ auto input_reshaped = input_.reshape({input_.size(0), input_.size(1), -1}); // internally we merge the feature dimensions
935
+ auto grad_output_reshaped = grad_out_.reshape(input_reshaped.sizes());
936
+ auto grad_input_reshaped = at::empty_like(input_reshaped, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
937
+
938
+ auto input = get_packed_accessor<
939
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(input_reshaped, "input");
940
+ auto grad_input = get_packed_accessor<
941
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_input_reshaped, "grad_input");
942
+ auto grad_output = get_packed_accessor<
943
+ input_scalar_t, 3, DefaultPtrTraits, index_t>(grad_output_reshaped, "grad_output");
944
+ auto mean = packed_accessor_or_dummy<
945
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(mean_, "mean");
946
+ auto invstd = packed_accessor_or_dummy<
947
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(invstd_, "invstd");
948
+ auto weight = packed_accessor_or_dummy<
949
+ stat_scalar_t, 1, DefaultPtrTraits, index_t>(weight_, "weight");
950
+ auto sum_dy = packed_accessor_or_dummy<
951
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_, "sum_dy");
952
+ auto sum_dy_xmu = packed_accessor_or_dummy<
953
+ stat_accscalar_t, 1, DefaultPtrTraits, index_t>(sum_dy_xmu_, "sum_dy_xmu");
954
+
955
+ auto stream = at::cuda::getCurrentCUDAStream();
956
+
957
+ // The kernel is pointwise, but we need to balance reading parameters (save_var/mean,
958
+ // weight/bias) - which we only do once and have a for loop afterwards - with having many threads and blocks
959
+ // and good occupancy. Quiet likely, we could go with even more blocks than 1024.
960
+ // The various planes are independent, so we use blocks for them.
961
+ int tf = std::max<int>(getNumThreads(input.size(2)/4),
962
+ std::min<int>(getNumThreads(input.size(2)), 64));
963
+ int tb = std::max<int>(64/tf, 1);
964
+ dim3 blocks_trans(input.size(1), std::max<int>(1, std::min<int>((256*1024)/input.size(1),
965
+ (input.size(0)+tb-1)/tb)));
966
+ blocks_trans.y = std::min(blocks_trans.y, MAX_GRID_SIZE);
967
+ dim3 threads_trans(tf, tb);
968
+ batch_norm_backward_elemt_kernel<input_scalar_t, stat_scalar_t, stat_accscalar_t, index_t> <<<blocks_trans, threads_trans, 0, stream>>>
969
+ (input, grad_output, mean, invstd, weight, sum_dy, sum_dy_xmu, grad_input, count.const_data_ptr<int>(), count.numel());
970
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
971
+
972
+ return grad_input_reshaped.view(input_.sizes());
973
+ }
974
+
975
+ // welford kernel for c last tensor calculating mean/biased_variance/unbiased_variance
976
+ // original apex name: welford_kernel_c_last
977
+ template
978
+ <typename VarTransform,
979
+ typename scalar_t,
980
+ typename accscalar_t,
981
+ int PARALLEL_LOADS>
982
+ __global__ void
983
+ batch_norm_collect_statistics_channels_last_kernel(
984
+ const scalar_t* __restrict__ input,
985
+ accscalar_t* __restrict__ out_mean,
986
+ accscalar_t* __restrict__ out_invstd,
987
+ volatile accscalar_t* staging_data,
988
+ int* semaphores,
989
+ const int reduction_size,
990
+ const int stride,
991
+ accscalar_t epsilon) {
992
+ // hide latency with concurrency
993
+ accscalar_t x_mean[PARALLEL_LOADS];
994
+ accscalar_t m_2_n[PARALLEL_LOADS];
995
+ int count[PARALLEL_LOADS];
996
+
997
+ #pragma unroll
998
+ for (int i = 0; i < PARALLEL_LOADS; i++) {
999
+ x_mean[i] = accscalar_t(0);
1000
+ m_2_n[i] = accscalar_t(0);
1001
+ count[i] = accscalar_t(0);
1002
+ }
1003
+ // tensor dimension (m,c)
1004
+
1005
+ // loop along m dimension
1006
+ int inner_loop_stride = blockDim.y * gridDim.y;
1007
+
1008
+ // offset along m dimension
1009
+ int m_offset = blockIdx.y * blockDim.y + threadIdx.y;
1010
+ int c_offset = blockIdx.x * blockDim.x + threadIdx.x;
1011
+
1012
+ int loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS);
1013
+ int address_base = m_offset * stride + c_offset;
1014
+ int address_increment = inner_loop_stride * stride;
1015
+
1016
+ for (int i = 0; i < loop_count; i++) {
1017
+ accscalar_t x_math[PARALLEL_LOADS];
1018
+ accscalar_t x_count_inv[PARALLEL_LOADS];
1019
+ accscalar_t is_valid[PARALLEL_LOADS];
1020
+
1021
+ // load multiple data in
1022
+ #pragma unroll
1023
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1024
+ if (c_offset < stride && m_offset < reduction_size) {
1025
+ x_math[j] = input[address_base];
1026
+ count[j]++;
1027
+ x_count_inv[j] = accscalar_t(1) / count[j];
1028
+ is_valid[j] = accscalar_t(1);
1029
+ } else {
1030
+ x_math[j] = accscalar_t(0);
1031
+ x_count_inv[j] = accscalar_t(0);
1032
+ is_valid[j] = accscalar_t(0);
1033
+ }
1034
+ m_offset += inner_loop_stride;
1035
+ address_base += address_increment;
1036
+ }
1037
+
1038
+ // calculate mean/m2n with welford
1039
+ #pragma unroll
1040
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1041
+ accscalar_t delta0 = x_math[j] - x_mean[j];
1042
+ x_mean[j] += delta0 * x_count_inv[j];
1043
+ accscalar_t delta1 = x_math[j] - x_mean[j];
1044
+ m_2_n[j] += delta0 * delta1 * is_valid[j];
1045
+ }
1046
+ }
1047
+
1048
+ // thread reduction to accumulate mean/m_2_n/count between PARALLEL_LOADS
1049
+ #pragma unroll
1050
+ for (int j = 1; j < PARALLEL_LOADS; j++) {
1051
+ welford_merge_element(count[0], x_mean[0], m_2_n[0], count[j], x_mean[j], m_2_n[j]);
1052
+ }
1053
+
1054
+ // release x_mean / m_2_n
1055
+ auto mean_th = x_mean[0];
1056
+ auto m2_th = m_2_n[0];
1057
+ auto count_th = count[0];
1058
+
1059
+ // block-wise reduction with shared memory (since reduction cannot be done within a warp)
1060
+ static __shared__ accscalar_t shmem_mean[MAX_BLOCK_SIZE];
1061
+ static __shared__ accscalar_t shmem_m2n[MAX_BLOCK_SIZE];
1062
+ static __shared__ int shmem_count[MAX_BLOCK_SIZE];
1063
+
1064
+ welford_merge_block_vertical(count_th, mean_th, m2_th, shmem_count, shmem_mean, shmem_m2n);
1065
+
1066
+ if (gridDim.y > 1) {
1067
+ volatile accscalar_t* staging_mean = staging_data;
1068
+ volatile accscalar_t* staging_m2n = &staging_data[stride*gridDim.y];
1069
+ volatile int* staging_count = reinterpret_cast<volatile int*>(&staging_m2n[stride*gridDim.y]);
1070
+
1071
+ address_base = c_offset + blockIdx.y * stride;
1072
+ // write data to staging_data;
1073
+ if (threadIdx.y == 0 && c_offset < stride) {
1074
+ #ifndef USE_ROCM
1075
+ staging_mean[address_base] = mean_th;
1076
+ staging_m2n[address_base] = m2_th;
1077
+ staging_count[address_base] = count_th;
1078
+ #else
1079
+ // In architectures with split caches, global fences are costly.
1080
+ // Here we preempt need for fences by committing stores to global memory.
1081
+ cmtdStore<accscalar_t, false>((void*)&staging_mean[address_base], mean_th);
1082
+ cmtdStore<accscalar_t, false>((void*)&staging_m2n[address_base], m2_th);
1083
+ cmtdStore((void*)&staging_count[address_base], count_th);
1084
+ #endif
1085
+ }
1086
+
1087
+ #ifndef USE_ROCM
1088
+ __threadfence();
1089
+ #endif
1090
+ __syncthreads(); // ensuring writes to staging_ is visible to all blocks
1091
+
1092
+ __shared__ bool is_last_block_done;
1093
+ // mark block done
1094
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
1095
+ int old = atomicAdd(&semaphores[blockIdx.x], 1);
1096
+ is_last_block_done = (old == (gridDim.y-1));
1097
+ }
1098
+
1099
+ __syncthreads();
1100
+
1101
+ // check that all data is now available in global memory
1102
+ if (is_last_block_done) {
1103
+ count_th = 0;
1104
+ mean_th = accscalar_t(0.0);
1105
+ m2_th = accscalar_t(0.0);
1106
+
1107
+ for (int y = threadIdx.y; y < gridDim.y; y += blockDim.y) {
1108
+ address_base = c_offset + y * stride;
1109
+ int count_new = c_offset < stride ? staging_count[address_base] : 0;
1110
+ accscalar_t mean_new = c_offset < stride ? staging_mean[address_base] : accscalar_t(0.0);
1111
+ accscalar_t m2n_new = c_offset < stride ? staging_m2n[address_base] : accscalar_t(0.0);
1112
+
1113
+ welford_merge_element(count_th, mean_th, m2_th, count_new, mean_new, m2n_new);
1114
+ }
1115
+
1116
+ welford_merge_block_vertical(count_th, mean_th, m2_th, shmem_count, shmem_mean, shmem_m2n);
1117
+ if (threadIdx.y == 0 && c_offset < stride) {
1118
+ out_mean[c_offset] = static_cast<accscalar_t>(mean_th);
1119
+ out_invstd[c_offset] = VarTransform{}(m2_th/count_th, epsilon);
1120
+ }
1121
+ }
1122
+ } else {
1123
+ if (blockIdx.y == 0 && threadIdx.y == 0 && c_offset < stride) {
1124
+ out_mean[c_offset] = static_cast<accscalar_t>(mean_th);
1125
+ out_invstd[c_offset] = VarTransform{}(m2_th/count_th, epsilon);
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ // elementwise BN kernel
1131
+ // original apex name: batchnorm_forward_c_last_kernel
1132
+ template <
1133
+ typename scalar_t,
1134
+ typename accscalar_t,
1135
+ typename layerscalar_t,
1136
+ int PARALLEL_LOADS>
1137
+ __global__ void batch_norm_transform_input_channels_last_kernel(
1138
+ const scalar_t* __restrict__ input,
1139
+ const scalar_t* __restrict__ z,
1140
+ const accscalar_t* __restrict__ mean,
1141
+ const accscalar_t* __restrict__ inv_std,
1142
+ const layerscalar_t* __restrict__ weight,
1143
+ const layerscalar_t* __restrict__ shift,
1144
+ scalar_t* __restrict__ out,
1145
+ const int reduction_size,
1146
+ const int stride,
1147
+ const bool fuse_relu) {
1148
+ // tensor dimension (m,c)
1149
+ // loop along m dimension
1150
+ int inner_loop_stride = blockDim.y * gridDim.y;
1151
+
1152
+ // offset along m dimension
1153
+ int m_offset = blockIdx.y * blockDim.y + threadIdx.y;
1154
+ int c_offset = blockIdx.x * blockDim.x + threadIdx.x;
1155
+
1156
+ if (c_offset >= stride || m_offset >= reduction_size) {
1157
+ return;
1158
+ }
1159
+
1160
+ auto m_c = mean[c_offset];
1161
+ auto inv_std_c = static_cast<accscalar_t>(inv_std[c_offset]);
1162
+ auto w_c = weight == nullptr ? accscalar_t(1.0) : static_cast<accscalar_t>(weight[c_offset]);
1163
+ auto s_c = shift == nullptr ? accscalar_t(0.0) : static_cast<accscalar_t>(shift[c_offset]);
1164
+
1165
+ int loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS);
1166
+ int address_base = m_offset * stride + c_offset;
1167
+ int address_increment = inner_loop_stride * stride;
1168
+
1169
+ for (int i = 0; i < loop_count; i++) {
1170
+ #pragma unroll
1171
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1172
+ if (c_offset < stride && m_offset < reduction_size) {
1173
+ auto tmp = w_c * (static_cast<accscalar_t>(input[address_base]) - m_c ) * inv_std_c + s_c;
1174
+ if (z != nullptr) {
1175
+ tmp += z[address_base];
1176
+ }
1177
+ out[address_base] = (fuse_relu && tmp <= accscalar_t(0.0) ? scalar_t(0.0) : static_cast<scalar_t>(tmp));
1178
+ }
1179
+ m_offset += inner_loop_stride;
1180
+ address_base += address_increment;
1181
+ }
1182
+ }
1183
+ }
1184
+
1185
+ template<typename T>
1186
+ __device__ __forceinline__ void merge_block_vertical_backward(T& sum_dy,
1187
+ T& sum_dy_xmu,
1188
+ T* shmem_sum_dy,
1189
+ T* shmem_sum_dy_xmu) {
1190
+ // write to shared memory
1191
+ auto address_base = threadIdx.x + threadIdx.y * blockDim.x;
1192
+
1193
+ #pragma unroll
1194
+ for (int offset = blockDim.y/2; offset > 0; offset >>= 1) {
1195
+ if (threadIdx.y < offset*2) {
1196
+ shmem_sum_dy[address_base] = sum_dy;
1197
+ shmem_sum_dy_xmu[address_base] = sum_dy_xmu;
1198
+ }
1199
+ __syncthreads();
1200
+ if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) {
1201
+ auto address = address_base + offset * blockDim.x;
1202
+
1203
+ sum_dy += shmem_sum_dy[address];
1204
+ sum_dy_xmu += shmem_sum_dy_xmu[address];
1205
+ }
1206
+ }
1207
+ }
1208
+
1209
+ // batchnorm backward kernel for c last tensor
1210
+ // original apex name: reduce_bn_c_last_kernel
1211
+ template <
1212
+ int PARALLEL_LOADS,
1213
+ typename scalar_t,
1214
+ typename accscalar_t,
1215
+ typename layerscalar_t>
1216
+ __global__ void batch_norm_backward_reduce_channels_last_kernel(
1217
+ const scalar_t* __restrict__ input,
1218
+ const scalar_t* __restrict__ grad_output,
1219
+ const accscalar_t* __restrict__ mean,
1220
+ const accscalar_t* __restrict__ inv_std,
1221
+ accscalar_t* __restrict__ sum_dy_o,
1222
+ accscalar_t* __restrict__ sum_dy_xmu_o,
1223
+ layerscalar_t* __restrict__ grad_weight,
1224
+ layerscalar_t* __restrict__ grad_bias,
1225
+ volatile accscalar_t* staging_data,
1226
+ int* semaphores,
1227
+ const int reduction_size,
1228
+ const int stride) {
1229
+
1230
+ // hide latency with concurrency
1231
+ accscalar_t sum_dy[PARALLEL_LOADS];
1232
+ accscalar_t sum_dy_xmu[PARALLEL_LOADS];
1233
+
1234
+ #pragma unroll
1235
+ for (int i = 0; i < PARALLEL_LOADS; i++) {
1236
+ sum_dy[i] = accscalar_t(0);
1237
+ sum_dy_xmu[i] = accscalar_t(0);
1238
+ }
1239
+ // tensor dimension (m,c)
1240
+
1241
+ // loop along m dimension
1242
+ int inner_loop_stride = blockDim.y * gridDim.y;
1243
+
1244
+ // offset along m dimension
1245
+ int m_offset = blockIdx.y * blockDim.y + threadIdx.y;
1246
+ int c_offset = blockIdx.x * blockDim.x + threadIdx.x;
1247
+
1248
+ if (c_offset >= stride || m_offset >= reduction_size) {
1249
+ return;
1250
+ }
1251
+
1252
+ int loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS);
1253
+ int address_base = m_offset * stride + c_offset;
1254
+ int address_increment = inner_loop_stride * stride;
1255
+
1256
+ auto r_mean = mean[c_offset];
1257
+ auto factor = inv_std[c_offset];
1258
+
1259
+ for (int i = 0; i < loop_count; i++) {
1260
+ accscalar_t x_input[PARALLEL_LOADS];
1261
+ accscalar_t x_grad_output[PARALLEL_LOADS];
1262
+
1263
+ // load multiple data in
1264
+ #pragma unroll
1265
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1266
+ if (c_offset < stride && m_offset < reduction_size) {
1267
+ x_input[j] = input[address_base];
1268
+ x_grad_output[j] = grad_output[address_base];
1269
+ } else {
1270
+ x_input[j] = accscalar_t(0);
1271
+ x_grad_output[j] = accscalar_t(0);
1272
+ }
1273
+ m_offset += inner_loop_stride;
1274
+ address_base += address_increment;
1275
+ }
1276
+
1277
+ // calculate sum_dy / sum_dy_xmu
1278
+ #pragma unroll
1279
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1280
+ sum_dy[j] += x_grad_output[j];
1281
+ sum_dy_xmu[j] += x_grad_output[j] * (x_input[j] - r_mean);
1282
+ }
1283
+ }
1284
+
1285
+ // thread reduction to accumulate sum_dy / sum_dy_xmu between PARALLEL_LOADS
1286
+ #pragma unroll
1287
+ for (int j = 1; j < PARALLEL_LOADS; j++) {
1288
+ sum_dy[0] += sum_dy[j];
1289
+ sum_dy_xmu[0] += sum_dy_xmu[j];
1290
+ }
1291
+
1292
+ // release array of registers
1293
+ auto sum_dy_th = sum_dy[0];
1294
+ auto sum_dy_xmu_th = sum_dy_xmu[0];
1295
+
1296
+ // block-wise reduction with shared memory (since reduction cannot be done within a warp)
1297
+ static __shared__ accscalar_t shmem_sum_dy[MAX_BLOCK_SIZE];
1298
+ static __shared__ accscalar_t shmem_sum_dy_xmu[MAX_BLOCK_SIZE];
1299
+
1300
+ merge_block_vertical_backward(sum_dy_th, sum_dy_xmu_th, shmem_sum_dy, shmem_sum_dy_xmu);
1301
+
1302
+ if (gridDim.y > 1) {
1303
+ volatile accscalar_t* staging_sum_dy = staging_data;
1304
+ volatile accscalar_t* staging_sum_dy_xmu = &staging_data[stride*gridDim.y];
1305
+
1306
+ address_base = c_offset + blockIdx.y * stride;
1307
+ // write data to staging_data;
1308
+ if (threadIdx.y == 0 && c_offset < stride) {
1309
+ #ifndef USE_ROCM
1310
+ staging_sum_dy[address_base] = sum_dy_th;
1311
+ staging_sum_dy_xmu[address_base] = sum_dy_xmu_th;
1312
+ #else
1313
+ // In architectures with split caches, global fences are costly.
1314
+ // Here we preempt need for fences by committing stores to global memory.
1315
+ cmtdStore<accscalar_t, false>((void*)&staging_sum_dy[address_base], sum_dy_th);
1316
+ cmtdStore((void*)&staging_sum_dy_xmu[address_base], sum_dy_xmu_th);
1317
+ #endif
1318
+ }
1319
+
1320
+ #ifndef USE_ROCM
1321
+ __threadfence();
1322
+ #endif
1323
+ __syncthreads(); // ensuring writes to staging_ is visible to all blocks
1324
+
1325
+ __shared__ bool is_last_block_done;
1326
+ // mark block done
1327
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
1328
+ int old = atomicAdd(&semaphores[blockIdx.x], 1);
1329
+ is_last_block_done = (old == (gridDim.y-1));
1330
+ }
1331
+
1332
+ __syncthreads();
1333
+
1334
+ // check that all data is now available in global memory
1335
+ if (is_last_block_done) {
1336
+ sum_dy_th = accscalar_t(0.0);
1337
+ sum_dy_xmu_th = accscalar_t(0.0);
1338
+
1339
+ for (int y = threadIdx.y; y < gridDim.y; y += blockDim.y) {
1340
+ address_base = c_offset + y * stride;
1341
+ sum_dy_th += (c_offset < stride ? staging_sum_dy[address_base] : accscalar_t(0.0));
1342
+ sum_dy_xmu_th += (c_offset < stride ? staging_sum_dy_xmu[address_base] : accscalar_t(0.0));
1343
+ }
1344
+
1345
+ merge_block_vertical_backward(sum_dy_th, sum_dy_xmu_th, shmem_sum_dy, shmem_sum_dy_xmu);
1346
+ if (threadIdx.y == 0 && c_offset < stride) {
1347
+ if (grad_bias != nullptr) {
1348
+ grad_bias[c_offset] = static_cast<layerscalar_t>(sum_dy_th);
1349
+ }
1350
+ if (grad_weight != nullptr) {
1351
+ grad_weight[c_offset] = static_cast<layerscalar_t>(sum_dy_xmu_th * factor);
1352
+ }
1353
+ //mean_dy[c_offset] = sum_dy_th / reduction_size;
1354
+ //mean_dy_xmu[c_offset] = sum_dy_xmu_th / reduction_size;
1355
+ sum_dy_o[c_offset] = sum_dy_th;
1356
+ sum_dy_xmu_o[c_offset] = sum_dy_xmu_th;
1357
+ }
1358
+ }
1359
+ } else {
1360
+ if (blockIdx.y == 0 && threadIdx.y == 0 && c_offset < stride) {
1361
+ if (grad_bias != nullptr) {
1362
+ grad_bias[c_offset] = static_cast<layerscalar_t>(sum_dy_th);
1363
+ }
1364
+ if (grad_weight != nullptr) {
1365
+ grad_weight[c_offset] = static_cast<layerscalar_t>(sum_dy_xmu_th * factor);
1366
+ }
1367
+ //mean_dy[c_offset] = sum_dy_th / reduction_size;
1368
+ //mean_dy_xmu[c_offset] = sum_dy_xmu_th / reduction_size;
1369
+ sum_dy_o[c_offset] = sum_dy_th;
1370
+ sum_dy_xmu_o[c_offset] = sum_dy_xmu_th;
1371
+ }
1372
+ }
1373
+ }
1374
+
1375
+ // elementwise BN kernel
1376
+ // original apex name: batchnorm_backward_c_last_kernel
1377
+ template <
1378
+ int PARALLEL_LOADS,
1379
+ typename scalar_t,
1380
+ typename accscalar_t,
1381
+ typename layerscalar_t>
1382
+ __device__ __forceinline__ void batch_norm_backward_elemt_channels_last_kernel_impl(
1383
+ const scalar_t* __restrict__ grad_output,
1384
+ const scalar_t* __restrict__ input,
1385
+ const accscalar_t* __restrict__ mean,
1386
+ const accscalar_t* __restrict__ inv_std,
1387
+ const layerscalar_t* __restrict__ weight,
1388
+ const accscalar_t* __restrict__ sum_dy,
1389
+ const accscalar_t* __restrict__ sum_dy_xmu,
1390
+ scalar_t* __restrict__ grad_input,
1391
+ const accscalar_t norm_fct,
1392
+ const int reduction_size,
1393
+ const int stride) {
1394
+ // tensor dimension (m,c)
1395
+ // loop along m dimension
1396
+ int inner_loop_stride = blockDim.y * gridDim.y;
1397
+
1398
+ // offset along m dimension
1399
+ int m_offset = blockIdx.y * blockDim.y + threadIdx.y;
1400
+ int c_offset = blockIdx.x * blockDim.x + threadIdx.x;
1401
+
1402
+ if (c_offset >= stride || m_offset >= reduction_size) {
1403
+ return;
1404
+ }
1405
+
1406
+ auto m_c = mean[c_offset];
1407
+ auto m_dy_c = sum_dy[c_offset] * norm_fct;
1408
+ auto factor_1_c = inv_std[c_offset];
1409
+ auto factor_2_c = (weight == nullptr? accscalar_t(1.0) : static_cast<accscalar_t>(weight[c_offset])) * factor_1_c;
1410
+ factor_1_c = factor_1_c * factor_1_c * sum_dy_xmu[c_offset] * norm_fct;
1411
+
1412
+ int loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS);
1413
+ int address_base = m_offset * stride + c_offset;
1414
+ int address_increment = inner_loop_stride * stride;
1415
+
1416
+ for (int i = 0; i < loop_count; i++) {
1417
+ #pragma unroll
1418
+ for (int j = 0; j < PARALLEL_LOADS; j++) {
1419
+ if (c_offset < stride && m_offset < reduction_size) {
1420
+ grad_input[address_base] = static_cast<scalar_t>(
1421
+ (static_cast<accscalar_t>(grad_output[address_base]) - m_dy_c -
1422
+ (static_cast<accscalar_t>(input[address_base]) - m_c) * factor_1_c)
1423
+ * factor_2_c);
1424
+ }
1425
+ m_offset += inner_loop_stride;
1426
+ address_base += address_increment;
1427
+ }
1428
+ }
1429
+ }
1430
+
1431
+ template <
1432
+ int PARALLEL_LOADS,
1433
+ typename scalar_t,
1434
+ typename accscalar_t,
1435
+ typename layerscalar_t>
1436
+ __global__ void batch_norm_backward_elemt_channels_last_kernel(
1437
+ const scalar_t* __restrict__ grad_output,
1438
+ const scalar_t* __restrict__ input,
1439
+ const accscalar_t* __restrict__ mean,
1440
+ const accscalar_t* __restrict__ inv_std,
1441
+ const layerscalar_t* __restrict__ weight,
1442
+ const accscalar_t* __restrict__ sum_dy,
1443
+ const accscalar_t* __restrict__ sum_dy_xmu,
1444
+ const int* __restrict__ numel,
1445
+ scalar_t* __restrict__ grad_input,
1446
+ const int64_t world_size,
1447
+ const int reduction_size,
1448
+ const int stride) {
1449
+
1450
+ int64_t total_numel = 0;
1451
+ for (int i = 0; i < world_size; i++) {
1452
+ total_numel += numel[i];
1453
+ }
1454
+
1455
+ auto norm_fct = static_cast<accscalar_t>(1) / static_cast<accscalar_t>(total_numel);
1456
+ batch_norm_backward_elemt_channels_last_kernel_impl<PARALLEL_LOADS>(
1457
+ grad_output, input, mean, inv_std, weight, sum_dy, sum_dy_xmu,
1458
+ grad_input, norm_fct, reduction_size, stride);
1459
+ }
1460
+
1461
+ template <
1462
+ int PARALLEL_LOADS,
1463
+ typename scalar_t,
1464
+ typename accscalar_t,
1465
+ typename layerscalar_t>
1466
+ __global__ void batch_norm_backward_elemt_channels_last_kernel(
1467
+ const scalar_t* __restrict__ grad_output,
1468
+ const scalar_t* __restrict__ input,
1469
+ const accscalar_t* __restrict__ mean,
1470
+ const accscalar_t* __restrict__ inv_std,
1471
+ const layerscalar_t* __restrict__ weight,
1472
+ const accscalar_t* __restrict__ sum_dy,
1473
+ const accscalar_t* __restrict__ sum_dy_xmu,
1474
+ scalar_t* __restrict__ grad_input,
1475
+ const accscalar_t norm_fct,
1476
+ const int reduction_size,
1477
+ const int stride) {
1478
+ batch_norm_backward_elemt_channels_last_kernel_impl<PARALLEL_LOADS>(
1479
+ grad_output, input, mean, inv_std, weight, sum_dy, sum_dy_xmu,
1480
+ grad_input, norm_fct, reduction_size, stride);
1481
+ }
1482
+
1483
+ template<typename scalar_t, typename VarTransform>
1484
+ void batch_norm_stats_channels_last_cuda_template(
1485
+ const Tensor& out_mean, const Tensor& out_invstd, const Tensor& input, double epsilon) {
1486
+ using accscalar_t = at::acc_type<scalar_t, true>;
1487
+
1488
+ const auto stride = input.sizes()[1];
1489
+ const auto reduction_size = input.numel() / stride;
1490
+
1491
+ resize_output(out_mean, {stride});
1492
+ resize_output(out_invstd, {stride});
1493
+ TORCH_INTERNAL_ASSERT(out_invstd.dim() == 1 && out_invstd.is_contiguous() &&
1494
+ out_invstd.sizes()[0]);
1495
+ TORCH_INTERNAL_ASSERT(out_mean.dim() == 1 && out_mean.is_contiguous() &&
1496
+ out_mean.sizes()[0]);
1497
+
1498
+ dim3 block;
1499
+ dim3 grid;
1500
+ flexible_launch_configs(reduction_size, stride, block, grid, true);
1501
+
1502
+ at::Tensor staging_data;
1503
+ at::Tensor semaphores;
1504
+ if (grid.y > 1) {
1505
+ staging_data = at::empty({4*stride*grid.y}, out_mean.options());
1506
+ semaphores = at::zeros({grid.x}, input.options().dtype(at::kInt));
1507
+ }
1508
+
1509
+ accscalar_t* staging_data_ptr = grid.y > 1 ? staging_data.mutable_data_ptr<accscalar_t>() : nullptr;
1510
+ int* semaphores_ptr = grid.y > 1 ? semaphores.mutable_data_ptr<int>() : nullptr;
1511
+ batch_norm_collect_statistics_channels_last_kernel<VarTransform, scalar_t, accscalar_t, ELEMENTS_PER_ITER>
1512
+ <<<grid, block, 0, at::cuda::getCurrentCUDAStream()>>>(
1513
+ input.const_data_ptr<scalar_t>(),
1514
+ out_mean.mutable_data_ptr<accscalar_t>(),
1515
+ out_invstd.mutable_data_ptr<accscalar_t>(),
1516
+ staging_data_ptr,
1517
+ semaphores_ptr,
1518
+ reduction_size,
1519
+ stride,
1520
+ epsilon);
1521
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1522
+ }
1523
+
1524
+ void batch_norm_elemt_channels_last_cuda_template(
1525
+ const at::Tensor& output,
1526
+ const at::Tensor& input,
1527
+ const at::Tensor& weight,
1528
+ const at::Tensor& shift, // bias of BN
1529
+ const at::Tensor& mean,
1530
+ const at::Tensor& inv_std,
1531
+ const std::optional<at::Tensor>& z = std::nullopt, // bias after BN
1532
+ const bool fuse_relu = false) {
1533
+ const auto stride = input.sizes()[1];
1534
+ const auto reduction_size = input.numel() / stride;
1535
+
1536
+ dim3 block;
1537
+ dim3 grid;
1538
+ flexible_launch_configs(reduction_size, stride, block, grid);
1539
+
1540
+ auto stream = at::cuda::getCurrentCUDAStream();
1541
+ const auto second_dtype = weight.defined() ? weight.scalar_type() :
1542
+ (shift.defined() ? shift.scalar_type() : input.scalar_type());
1543
+
1544
+ if (input.scalar_type() != second_dtype) {
1545
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_forward", [&] {
1546
+ using accscalar_t = at::acc_type<scalar_t, true>;
1547
+ batch_norm_transform_input_channels_last_kernel<scalar_t, accscalar_t, accscalar_t, ELEMENTS_PER_ITER>
1548
+ <<<grid, block, 0, stream>>>(
1549
+ input.const_data_ptr<scalar_t>(),
1550
+ z.has_value() ? z.value().const_data_ptr<scalar_t>() : nullptr,
1551
+ mean.const_data_ptr<accscalar_t>(),
1552
+ inv_std.const_data_ptr<accscalar_t>(),
1553
+ weight.defined() ? weight.const_data_ptr<accscalar_t>() : nullptr,
1554
+ shift.defined() ? shift.const_data_ptr<accscalar_t>() : nullptr,
1555
+ output.mutable_data_ptr<scalar_t>(),
1556
+ reduction_size,
1557
+ stride,
1558
+ fuse_relu);
1559
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1560
+ });
1561
+ } else {
1562
+ if (weight.defined()){
1563
+ TORCH_CHECK(input.scalar_type() == weight.scalar_type(), "batchnorm_forward: input.scalar_type() ", input.scalar_type(),
1564
+ " is not supported with weight.scalar_type() ", weight.scalar_type());
1565
+ }
1566
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_forward", [&] {
1567
+ using accscalar_t = at::acc_type<scalar_t, true>;
1568
+ batch_norm_transform_input_channels_last_kernel<scalar_t, accscalar_t, scalar_t, ELEMENTS_PER_ITER>
1569
+ <<<grid, block, 0, stream>>>(
1570
+ input.const_data_ptr<scalar_t>(),
1571
+ z.has_value() ? z.value().const_data_ptr<scalar_t>() : nullptr,
1572
+ mean.const_data_ptr<accscalar_t>(),
1573
+ inv_std.const_data_ptr<accscalar_t>(),
1574
+ weight.defined() ? weight.const_data_ptr<scalar_t>() : nullptr,
1575
+ shift.defined() ? shift.const_data_ptr<scalar_t>(): nullptr,
1576
+ output.mutable_data_ptr<scalar_t>(),
1577
+ reduction_size,
1578
+ stride,
1579
+ fuse_relu);
1580
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1581
+ });
1582
+ }
1583
+ }
1584
+
1585
+ std::tuple<Tensor, Tensor, Tensor, Tensor>
1586
+ batch_norm_backward_reduce_cuda_channels_last_template(const at::Tensor& grad_output,
1587
+ const at::Tensor& input,
1588
+ const at::Tensor& mean,
1589
+ const at::Tensor& inv_std,
1590
+ const at::Tensor& weight,
1591
+ const bool input_g, const bool weight_g, const bool bias_g) {
1592
+ const auto stride = input.sizes()[1];
1593
+ const auto reduction_size = input.numel() / stride;
1594
+
1595
+ at::Tensor sumn_dy = at::empty({stride}, mean.options());
1596
+ at::Tensor sum_dy_xmu = at::empty({stride}, mean.options());
1597
+
1598
+ at::Tensor grad_weight;
1599
+ at::Tensor grad_bias;
1600
+ if (weight.defined()) {
1601
+ grad_weight = at::empty({stride}, weight.options());
1602
+ grad_bias = at::empty({stride}, weight.options());
1603
+ } else {
1604
+ // because I cannot return an uninitialized at::Tensor
1605
+ grad_weight = at::empty({0}, mean.options());
1606
+ grad_bias = at::empty({0}, mean.options());
1607
+ }
1608
+
1609
+ dim3 block;
1610
+ dim3 grid;
1611
+ flexible_launch_configs(reduction_size, stride, block, grid, true);
1612
+
1613
+ at::Tensor staging_data;
1614
+ at::Tensor semaphores;
1615
+ if (grid.y > 1) {
1616
+ staging_data = at::empty({2*stride*grid.y}, mean.options());
1617
+ semaphores = at::zeros({grid.x}, input.options().dtype(at::kInt));
1618
+ }
1619
+ auto stream = at::cuda::getCurrentCUDAStream();
1620
+
1621
+ if (weight.defined() && input.scalar_type() != weight.scalar_type()) {
1622
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_backward_reduce", [&] {
1623
+ using accscalar_t = at::acc_type<scalar_t, true>;
1624
+ accscalar_t* staging_data_ptr = grid.y > 1 ? staging_data.mutable_data_ptr<accscalar_t>() : nullptr;
1625
+ int* semaphores_ptr = grid.y > 1 ? semaphores.mutable_data_ptr<int>() : nullptr;
1626
+ batch_norm_backward_reduce_channels_last_kernel<ELEMENTS_PER_ITER>
1627
+ <<<grid, block, 0, stream>>>(
1628
+ input.const_data_ptr<scalar_t>(),
1629
+ grad_output.const_data_ptr<scalar_t>(),
1630
+ mean.const_data_ptr<accscalar_t>(),
1631
+ inv_std.const_data_ptr<accscalar_t>(),
1632
+ sumn_dy.mutable_data_ptr<accscalar_t>(),
1633
+ sum_dy_xmu.mutable_data_ptr<accscalar_t>(),
1634
+ grad_weight.mutable_data_ptr<accscalar_t>(),
1635
+ grad_bias.mutable_data_ptr<accscalar_t>(),
1636
+ staging_data_ptr,
1637
+ semaphores_ptr,
1638
+ reduction_size,
1639
+ stride);
1640
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1641
+ });
1642
+ } else {
1643
+ if (weight.defined()) {
1644
+ TORCH_CHECK(input.scalar_type() == weight.scalar_type(), "batchnorm_backward_reduce: input.scalar_type() ", input.scalar_type(),
1645
+ " is not supported with weight.scalar_type() ", weight.scalar_type());
1646
+ }
1647
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_backward_reduce", [&] {
1648
+ using accscalar_t = at::acc_type<scalar_t, true>;
1649
+ accscalar_t* staging_data_ptr = grid.y > 1 ? staging_data.mutable_data_ptr<accscalar_t>() : nullptr;
1650
+ int* semaphores_ptr = grid.y > 1 ? semaphores.mutable_data_ptr<int>() : nullptr;
1651
+ batch_norm_backward_reduce_channels_last_kernel<ELEMENTS_PER_ITER>
1652
+ <<<grid, block, 0, stream>>>(
1653
+ input.const_data_ptr<scalar_t>(),
1654
+ grad_output.const_data_ptr<scalar_t>(),
1655
+ mean.const_data_ptr<accscalar_t>(),
1656
+ inv_std.const_data_ptr<accscalar_t>(),
1657
+ sumn_dy.mutable_data_ptr<accscalar_t>(),
1658
+ sum_dy_xmu.mutable_data_ptr<accscalar_t>(),
1659
+ weight.defined() ? grad_weight.mutable_data_ptr<scalar_t>() : nullptr,
1660
+ weight.defined() ? grad_bias.mutable_data_ptr<scalar_t>() : nullptr,
1661
+ staging_data_ptr,
1662
+ semaphores_ptr,
1663
+ reduction_size,
1664
+ stride);
1665
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1666
+ });
1667
+ }
1668
+
1669
+ return std::make_tuple(
1670
+ std::move(sumn_dy),
1671
+ std::move(sum_dy_xmu),
1672
+ std::move(grad_weight),
1673
+ std::move(grad_bias));
1674
+ }
1675
+
1676
+ at::Tensor batch_norm_backward_elemt_channels_last_cuda_template(
1677
+ const at::Tensor& grad_output,
1678
+ const at::Tensor& input,
1679
+ const at::Tensor& mean,
1680
+ const at::Tensor& inv_std,
1681
+ const at::Tensor& weight,
1682
+ const at::Tensor& sum_dy,
1683
+ const at::Tensor& sum_dy_xmu,
1684
+ const at::Tensor& count) {
1685
+ const auto stride = input.sizes()[1];
1686
+ const auto reduction_size = input.numel() / stride;
1687
+
1688
+ // Input is guaranteed to be channels-last compatible
1689
+ at::Tensor grad_input = at::empty_like(input);
1690
+
1691
+ dim3 block;
1692
+ dim3 grid;
1693
+ flexible_launch_configs(reduction_size, stride, block, grid);
1694
+
1695
+ auto stream = at::cuda::getCurrentCUDAStream();
1696
+
1697
+ if (weight.defined() && weight.scalar_type() != input.scalar_type()) {
1698
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_backward_element", [&] {
1699
+ using accscalar_t = at::acc_type<scalar_t, true>;
1700
+ batch_norm_backward_elemt_channels_last_kernel<ELEMENTS_PER_ITER>
1701
+ <<<grid, block, 0, stream>>>(
1702
+ grad_output.const_data_ptr<scalar_t>(),
1703
+ input.const_data_ptr<scalar_t>(),
1704
+ mean.const_data_ptr<accscalar_t>(),
1705
+ inv_std.const_data_ptr<accscalar_t>(),
1706
+ weight.const_data_ptr<accscalar_t>(),
1707
+ sum_dy.const_data_ptr<accscalar_t>(),
1708
+ sum_dy_xmu.const_data_ptr<accscalar_t>(),
1709
+ count.const_data_ptr<int>(),
1710
+ grad_input.mutable_data_ptr<scalar_t>(),
1711
+ count.numel(),
1712
+ reduction_size,
1713
+ stride);
1714
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1715
+ });
1716
+ } else {
1717
+ if (weight.defined()) {
1718
+ TORCH_CHECK(input.scalar_type() == weight.scalar_type(), "batchnorm_backward_element: input.scalar_type() ", input.scalar_type(),
1719
+ " is not supported with weight.scalar_type() ", weight.scalar_type());
1720
+ }
1721
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, input.scalar_type(), "batchnorm_backward_element", [&] {
1722
+ using accscalar_t = at::acc_type<scalar_t, true>;
1723
+ batch_norm_backward_elemt_channels_last_kernel<ELEMENTS_PER_ITER>
1724
+ <<<grid, block, 0, stream>>>(
1725
+ grad_output.const_data_ptr<scalar_t>(),
1726
+ input.const_data_ptr<scalar_t>(),
1727
+ mean.const_data_ptr<accscalar_t>(),
1728
+ inv_std.const_data_ptr<accscalar_t>(),
1729
+ weight.defined() ? weight.const_data_ptr<scalar_t>() : nullptr,
1730
+ sum_dy.const_data_ptr<accscalar_t>(),
1731
+ sum_dy_xmu.const_data_ptr<accscalar_t>(),
1732
+ count.const_data_ptr<int>(),
1733
+ grad_input.mutable_data_ptr<scalar_t>(),
1734
+ count.numel(),
1735
+ reduction_size,
1736
+ stride);
1737
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1738
+ });
1739
+ }
1740
+
1741
+ return grad_input;
1742
+ }
1743
+
1744
+ at::Tensor batch_norm_backward_elemt_channels_last_cuda_template(
1745
+ const at::Tensor& grad_output,
1746
+ const at::Tensor& input,
1747
+ const at::Tensor& mean,
1748
+ const at::Tensor& inv_std,
1749
+ const at::Tensor& weight,
1750
+ const at::Tensor& sum_dy,
1751
+ const at::Tensor& sum_dy_xmu) {
1752
+ const auto stride = input.sizes()[1];
1753
+ const auto reduction_size = input.numel() / stride;
1754
+ auto norm_fct = 1.0 / reduction_size;
1755
+
1756
+ // Input is guaranteed to be channels-last compatible
1757
+ at::Tensor grad_input = at::empty_like(input);
1758
+
1759
+ dim3 block;
1760
+ dim3 grid;
1761
+ flexible_launch_configs(reduction_size, stride, block, grid);
1762
+
1763
+ auto stream = at::cuda::getCurrentCUDAStream();
1764
+
1765
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "batchnorm_backward_element", [&] {
1766
+ using accscalar_t = at::acc_type<scalar_t, true>;
1767
+
1768
+ if (weight.defined() && weight.scalar_type() != input.scalar_type()) {
1769
+ batch_norm_backward_elemt_channels_last_kernel<ELEMENTS_PER_ITER>
1770
+ <<<grid, block, 0, stream>>>(
1771
+ grad_output.const_data_ptr<scalar_t>(),
1772
+ input.const_data_ptr<scalar_t>(),
1773
+ mean.const_data_ptr<accscalar_t>(),
1774
+ inv_std.const_data_ptr<accscalar_t>(),
1775
+ weight.const_data_ptr<accscalar_t>(),
1776
+ sum_dy.const_data_ptr<accscalar_t>(),
1777
+ sum_dy_xmu.const_data_ptr<accscalar_t>(),
1778
+ grad_input.mutable_data_ptr<scalar_t>(),
1779
+ static_cast<accscalar_t>(norm_fct),
1780
+ reduction_size,
1781
+ stride);
1782
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1783
+ } else {
1784
+ batch_norm_backward_elemt_channels_last_kernel<ELEMENTS_PER_ITER>
1785
+ <<<grid, block, 0, stream>>>(
1786
+ grad_output.const_data_ptr<scalar_t>(),
1787
+ input.const_data_ptr<scalar_t>(),
1788
+ mean.const_data_ptr<accscalar_t>(),
1789
+ inv_std.const_data_ptr<accscalar_t>(),
1790
+ weight.defined() ? weight.const_data_ptr<scalar_t>() : nullptr,
1791
+ sum_dy.const_data_ptr<accscalar_t>(),
1792
+ sum_dy_xmu.const_data_ptr<accscalar_t>(),
1793
+ grad_input.mutable_data_ptr<scalar_t>(),
1794
+ static_cast<accscalar_t>(norm_fct),
1795
+ reduction_size,
1796
+ stride);
1797
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
1798
+ }
1799
+ });
1800
+
1801
+ return grad_input;
1802
+ }
1803
+
1804
+ } // namespace at::native
1805
+
1806
+ #else
1807
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1808
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/PersistentSoftmax.cuh ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cfloat>
5
+ #include <limits>
6
+ #include <stdint.h>
7
+ #include <cuda_fp16.h>
8
+ #include <c10/macros/Macros.h>
9
+
10
+ #include <ATen/cuda/DeviceUtils.cuh>
11
+
12
+ namespace {
13
+
14
+ int log2_ceil(int value) {
15
+ int log2_value = 0;
16
+ while ((1 << log2_value) < value) ++log2_value;
17
+ return log2_value;
18
+ }
19
+
20
+ template<typename T>
21
+ struct Add {
22
+ __device__ __forceinline__ T operator()(T a, T b) const {
23
+ return a + b;
24
+ }
25
+ };
26
+
27
+ template<typename T>
28
+ struct Max {
29
+ __device__ __forceinline__ T operator()(T a, T b) const {
30
+ return a < b ? b : a;
31
+ }
32
+ };
33
+
34
+ template <typename acc_t, int WARP_BATCH, int WARP_SIZE, template<typename> class ReduceOp>
35
+ __device__ __forceinline__ void warp_reduce(acc_t* sum) {
36
+ ReduceOp<acc_t> r;
37
+ #pragma unroll
38
+ for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
39
+ #pragma unroll
40
+ for (int i = 0; i < WARP_BATCH; ++i) {
41
+ acc_t b = WARP_SHFL_XOR(sum[i], offset, WARP_SIZE);
42
+ sum[i] = r(sum[i], b);
43
+ }
44
+ }
45
+ }
46
+
47
+ // The softmax_warp_* methods perform softmax forward and backward propagation on samples spanning the fast dimension.
48
+ // Each sample contains element_count scalar elements. Forward supports values up to 2048; backward supports values up to 1024.
49
+ // The template arguments have the following meaning:
50
+ // One "WARP" works on one "BATCH". One "BATCH" contains "WARP_BATCH" samples.
51
+ // WARP_BATCH is equal to 1 when element_count is large, and > 1 when element_count is small.
52
+ // A "WARP" contains "C10_WARPS_SIZE" threads, these treads are guaranteed to belong to the same warp.
53
+ // This is important because it means only __shfl_ instructions are required for reductions.
54
+ // Note that this means WARP_SIZE must be a power of two and <= architecture warp size.
55
+ // CUDA warp size is 32 for all existing GPU architectures, but there is no guarantee this will not change for future arch.
56
+ // ROCm warp size is 64 for all currently ROCm-supported GPU architectures, but this may change for future archs.
57
+ // is_log_softmax is a flag indicating whether SoftMax or LogSoftMax should be computed.
58
+ // is_masked is a flag indicating whether SoftMax or MaskedSoftMax should be computed.
59
+ // The template can be instantiated with any floating point type for the type arguments input_t, output_t and acc_t.
60
+ // This allows SoftMax to be fused with a cast immediately following the SoftMax.
61
+ // The mask should have the same shape as input, with a boolean indicate if the value is masked.
62
+ // The head_chunk_size is only used for transformer mask softmax, equals to H * D * D.
63
+ // For instance:
64
+ // input_t=half, acc_t=float, output_t=half => read half tensor, float accumulators, write half tensor.
65
+ // input_t=half, acc_t=float, output_t=float => read half tensor, float accumulators, write float tensor.
66
+ // input_t_float, acc_t=float, output_t=half => read float tensor, float accumulators, write half tensor.
67
+
68
+ template <typename input_t, typename output_t, typename acc_t, int log2_elements, bool is_log_softmax, bool is_masked, int WARP_SIZE_PARAM>
69
+ __global__ void softmax_warp_forward(output_t *dst, const input_t *src, int batch_size, int stride, int element_count, const bool *mask = nullptr, const int head_chunk_size = -1, bool is_transformer_mask = false)
70
+ {
71
+ // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_forward_kernel.
72
+ constexpr int next_power_of_two = 1 << log2_elements;
73
+ constexpr int WARP_SIZE = (next_power_of_two < WARP_SIZE_PARAM) ? next_power_of_two : WARP_SIZE_PARAM;
74
+ constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE;
75
+ constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1;
76
+
77
+ int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH;
78
+
79
+ // batch_size might not be a multiple of WARP_BATCH. Check how
80
+ // many batches have to computed within this WARP.
81
+ int local_batches = batch_size - first_batch;
82
+ if (local_batches > WARP_BATCH)
83
+ local_batches = WARP_BATCH;
84
+
85
+ // there might be multiple batches per warp. compute the index within the batch
86
+ int local_idx = threadIdx.x;
87
+ int idx_offset = first_batch * stride + local_idx;
88
+
89
+ src += idx_offset;
90
+ dst += idx_offset;
91
+
92
+ if (is_transformer_mask) {
93
+ mask += ((first_batch * stride) / head_chunk_size) * stride + local_idx;
94
+ } else {
95
+ mask += idx_offset;
96
+ }
97
+ // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop,
98
+ // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep
99
+ // the nested loops.
100
+ // This should have no impact on performance because the loops are unrolled anyway.
101
+
102
+ // load data from global memory
103
+ acc_t elements[WARP_BATCH][WARP_ITERATIONS];
104
+ for (int i = 0; i < WARP_BATCH; ++i) {
105
+ int batch_element_count = (i >= local_batches) ? 0 : element_count;
106
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
107
+ int element_index = local_idx + it * WARP_SIZE;
108
+ if (element_index < batch_element_count) {
109
+ elements[i][it] = src[i*element_count+it*WARP_SIZE];
110
+ } else {
111
+ elements[i][it] = -std::numeric_limits<acc_t>::infinity();
112
+ }
113
+ }
114
+ }
115
+
116
+ // compute max_value
117
+ acc_t max_value[WARP_BATCH];
118
+ #pragma unroll
119
+ for (int i = 0; i < WARP_BATCH; ++i) {
120
+ int batch_element_count = (i >= local_batches) ? 0 : element_count;
121
+ bool is_meaningful_max = false;
122
+ max_value[i] = elements[i][0];
123
+ #pragma unroll
124
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
125
+ if (is_masked) {
126
+ int idx = it*WARP_SIZE;
127
+ if ((idx + local_idx) < batch_element_count) {
128
+ if (!is_transformer_mask) {
129
+ idx += i*element_count;
130
+ }
131
+ if (!mask[idx]) {
132
+ max_value[i] = (is_meaningful_max && max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it];
133
+ is_meaningful_max = true;
134
+ }
135
+ }
136
+ } else {
137
+ max_value[i] = max_value[i] > elements[i][it] ? max_value[i] : elements[i][it];
138
+ }
139
+ }
140
+ if (is_masked) {
141
+ if (!is_meaningful_max) {
142
+ max_value[i] = -std::numeric_limits<acc_t>::infinity();
143
+ }
144
+ }
145
+ }
146
+ warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Max>(max_value);
147
+
148
+ acc_t sum[WARP_BATCH] { 0.0f };
149
+ #pragma unroll
150
+ for (int i = 0; i < WARP_BATCH; ++i) {
151
+ int batch_element_count = (i >= local_batches) ? 0 : element_count;
152
+ #pragma unroll
153
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
154
+ if (!is_masked) {
155
+ if (is_log_softmax) {
156
+ sum[i] += std::exp(elements[i][it] - max_value[i]);
157
+ } else {
158
+ elements[i][it] = std::exp(elements[i][it] - max_value[i]);
159
+ sum[i] += elements[i][it];
160
+ }
161
+ } else {
162
+ int idx = it*WARP_SIZE;
163
+ bool valid = (idx + local_idx) < batch_element_count;
164
+ if (!is_transformer_mask) {
165
+ idx += i*element_count;
166
+ }
167
+ if (valid) {
168
+ if (!mask[idx]) {
169
+ if (is_log_softmax) {
170
+ sum[i] += std::exp(elements[i][it] - max_value[i]);
171
+ } else {
172
+ elements[i][it] = std::exp(elements[i][it] - max_value[i]);
173
+ sum[i] += elements[i][it];
174
+ }
175
+ } else {
176
+ if (!is_log_softmax) {
177
+ // Masked values are treated as -infinity, and std::exp(-infinity) is 0.
178
+ elements[i][it] = 0;
179
+ }
180
+ }
181
+ } else {
182
+ if (!is_log_softmax) {
183
+ elements[i][it] = 0.;
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
189
+ warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Add>(sum);
190
+
191
+ // store result
192
+ #pragma unroll
193
+ for (int i = 0; i < WARP_BATCH; ++i) {
194
+ if (i >= local_batches)
195
+ break;
196
+ if (is_log_softmax) sum[i] = std::log(sum[i]);
197
+ #pragma unroll
198
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
199
+ int element_index = local_idx + it * WARP_SIZE;
200
+ if (element_index < element_count) {
201
+ if (is_log_softmax) {
202
+ dst[i*element_count+it*WARP_SIZE] = elements[i][it] - max_value[i] - sum[i];
203
+ } else if (sum[i] == 0) {
204
+ dst[i*element_count+it*WARP_SIZE] = std::numeric_limits<acc_t>::quiet_NaN();
205
+ } else {
206
+ dst[i*element_count+it*WARP_SIZE] = elements[i][it] / sum[i];
207
+ }
208
+ } else {
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ template <typename input_t, typename output_t, typename acc_t, int log2_elements, bool is_log_softmax, bool is_masked, int WARP_SIZE_PARAM>
216
+ __global__ void softmax_warp_backward(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count, const bool *mask = nullptr)
217
+ {
218
+ // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel.
219
+ constexpr int next_power_of_two = 1 << log2_elements;
220
+ constexpr int WARP_SIZE = (next_power_of_two < WARP_SIZE_PARAM) ? next_power_of_two : WARP_SIZE_PARAM;
221
+ constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE;
222
+ constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1;
223
+
224
+ int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH;
225
+
226
+ // batch_size might not be a multiple of WARP_BATCH. Check how
227
+ // many batches have to computed within this WARP.
228
+ int local_batches = batch_size - first_batch;
229
+ if (local_batches > WARP_BATCH)
230
+ local_batches = WARP_BATCH;
231
+
232
+ // there might be multiple batches per warp. compute the index within the batch
233
+ int local_idx = threadIdx.x % WARP_SIZE;
234
+
235
+ // the first element to process by the current thread
236
+ int thread_offset = first_batch * stride + local_idx;
237
+ grad += thread_offset;
238
+ output += thread_offset;
239
+ gradInput += thread_offset;
240
+ if (is_masked) {
241
+ mask += thread_offset;
242
+ }
243
+
244
+ // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop,
245
+ // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep
246
+ // the nested loops.
247
+ // This should have no impact on performance because the loops are unrolled anyway.
248
+
249
+ // load data from global memory
250
+ acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS];
251
+ acc_t output_reg[WARP_BATCH][WARP_ITERATIONS];
252
+ for (int i = 0; i < WARP_BATCH; ++i) {
253
+ int batch_element_count = (i >= local_batches) ? 0 : element_count;
254
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
255
+ int element_index = local_idx + it * WARP_SIZE;
256
+ if (element_index < batch_element_count) {
257
+ grad_reg[i][it] = grad[i*element_count+it*WARP_SIZE];
258
+ output_reg[i][it] = output[i*element_count+it*WARP_SIZE];
259
+ } else {
260
+ grad_reg[i][it] = acc_t(0);
261
+ output_reg[i][it] = acc_t(0);
262
+ }
263
+ }
264
+ }
265
+
266
+ acc_t sum[WARP_BATCH] { 0.0f };
267
+ #pragma unroll
268
+ for (int i = 0; i < WARP_BATCH; ++i) {
269
+ #pragma unroll
270
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
271
+ if (!is_masked || !mask[i*element_count+it*WARP_SIZE]) {
272
+ sum[i] += grad_reg[i][it];
273
+ }
274
+ }
275
+ }
276
+ warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Add>(sum);
277
+
278
+ // store result
279
+ #pragma unroll
280
+ for (int i = 0; i < WARP_BATCH; ++i) {
281
+ if (i >= local_batches)
282
+ break;
283
+ #pragma unroll
284
+ for (int it = 0; it < WARP_ITERATIONS; ++it) {
285
+ int element_index = local_idx + it * WARP_SIZE;
286
+ if (element_index < element_count) {
287
+ if (is_masked && mask[i*element_count+it*WARP_SIZE]) {
288
+ gradInput[i*element_count+it*WARP_SIZE] = 0;
289
+ }
290
+ // compute gradients
291
+ else if (is_log_softmax) {
292
+ gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]);
293
+ } else {
294
+ gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+
301
+ } // end of anonymous namespace
302
+
303
+ template<typename input_t, typename output_t, typename acc_t, bool is_log_softmax, bool is_masked>
304
+ void dispatch_softmax_forward(output_t *dst, const input_t *src, int softmax_elements, int softmax_elements_stride, int batch_count, const bool *mask = nullptr, int chunk_size = -1, bool is_transformer_mask = false)
305
+ {
306
+ TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 2048 );
307
+ if (softmax_elements == 0) {
308
+ return;
309
+ } else {
310
+ int log2_elements = log2_ceil(softmax_elements);
311
+ const int next_power_of_two = 1 << log2_elements;
312
+
313
+ // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_forward.
314
+ int warp_size = at::cuda::warp_size();
315
+ warp_size = (next_power_of_two < warp_size) ? next_power_of_two : warp_size;
316
+
317
+ // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_forward.
318
+ int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
319
+
320
+ // use 128 threads per block to maximize gpu utilization
321
+ constexpr int threads_per_block = 128;
322
+
323
+ int warps_per_block = (threads_per_block / warp_size);
324
+ int batches_per_block = warps_per_block * batches_per_warp;
325
+ int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
326
+ dim3 threads(warp_size, warps_per_block, 1);
327
+ // Launch code would be more elegant if C++ supported FOR CONSTEXPR
328
+ switch (log2_elements) {
329
+ #ifdef USE_ROCM
330
+ // To support ROCm amdgcnspirv target, we must compile both a 32 and 64 warpSize version of each kernel
331
+ #define LAUNCH_SOFTMAX_WARP_FORWARD(L2E) case L2E: \
332
+ if (warp_size == 64) { \
333
+ softmax_warp_forward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 64> \
334
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, \
335
+ src, batch_count, softmax_elements_stride, softmax_elements, mask, chunk_size, is_transformer_mask); \
336
+ } \
337
+ else { \
338
+ softmax_warp_forward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 32> \
339
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, \
340
+ src, batch_count, softmax_elements_stride, softmax_elements, mask, chunk_size, is_transformer_mask); \
341
+ } \
342
+ C10_CUDA_KERNEL_LAUNCH_CHECK(); \
343
+ break;
344
+ #else
345
+ #define LAUNCH_SOFTMAX_WARP_FORWARD(L2E) case L2E: \
346
+ softmax_warp_forward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 32> \
347
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, \
348
+ src, batch_count, softmax_elements_stride, softmax_elements, mask, chunk_size, is_transformer_mask); \
349
+ C10_CUDA_KERNEL_LAUNCH_CHECK(); \
350
+ break;
351
+ #endif
352
+
353
+ LAUNCH_SOFTMAX_WARP_FORWARD(0); // 1
354
+ LAUNCH_SOFTMAX_WARP_FORWARD(1); // 2
355
+ LAUNCH_SOFTMAX_WARP_FORWARD(2); // 4
356
+ LAUNCH_SOFTMAX_WARP_FORWARD(3); // 8
357
+ LAUNCH_SOFTMAX_WARP_FORWARD(4); // 16
358
+ LAUNCH_SOFTMAX_WARP_FORWARD(5); // 32
359
+ LAUNCH_SOFTMAX_WARP_FORWARD(6); // 64
360
+ LAUNCH_SOFTMAX_WARP_FORWARD(7); // 128
361
+ LAUNCH_SOFTMAX_WARP_FORWARD(8); // 256
362
+ LAUNCH_SOFTMAX_WARP_FORWARD(9); // 512
363
+ LAUNCH_SOFTMAX_WARP_FORWARD(10); // 1024
364
+ LAUNCH_SOFTMAX_WARP_FORWARD(11); // 2048
365
+ default:
366
+ break;
367
+ }
368
+ }
369
+ }
370
+
371
+ template<typename input_t, typename output_t, typename acc_t, bool is_log_softmax, bool is_masked>
372
+ void dispatch_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count, const bool *mask = nullptr)
373
+ {
374
+ TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 );
375
+ if (softmax_elements == 0) {
376
+ return;
377
+ } else {
378
+ int log2_elements = log2_ceil(softmax_elements);
379
+ const int next_power_of_two = 1 << log2_elements;
380
+
381
+ // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward.
382
+ int warp_size = at::cuda::warp_size();
383
+ warp_size = (next_power_of_two < warp_size) ? next_power_of_two : warp_size;
384
+
385
+ // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward.
386
+ int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
387
+
388
+ // use 128 threads per block to maximize gpu utilization
389
+ constexpr int threads_per_block = 128;
390
+
391
+ int warps_per_block = (threads_per_block / warp_size);
392
+ int batches_per_block = warps_per_block * batches_per_warp;
393
+ int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
394
+ dim3 threads(warp_size, warps_per_block, 1);
395
+ // Launch code would be more elegant if C++ supported FOR CONSTEXPR
396
+ switch (log2_elements) {
397
+ #ifdef USE_ROCM
398
+ // To support ROCm amdgcnspirv target, we must compile both a 32 and 64 warpSize version of each kernel
399
+ #define LAUNCH_SOFTMAX_WARP_BACKWARD(L2E) case L2E: \
400
+ if (warp_size == 64) { \
401
+ softmax_warp_backward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 64> \
402
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>> \
403
+ (grad_input, grad, output, batch_count, softmax_elements_stride, \
404
+ softmax_elements, mask); \
405
+ } \
406
+ else { \
407
+ softmax_warp_backward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 32> \
408
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>> \
409
+ (grad_input, grad, output, batch_count, softmax_elements_stride, \
410
+ softmax_elements, mask); \
411
+ } \
412
+ C10_CUDA_KERNEL_LAUNCH_CHECK(); \
413
+ break;
414
+ #else
415
+ #define LAUNCH_SOFTMAX_WARP_BACKWARD(L2E) case L2E: \
416
+ softmax_warp_backward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked, 32> \
417
+ <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>> \
418
+ (grad_input, grad, output, batch_count, softmax_elements_stride, \
419
+ softmax_elements, mask); \
420
+ C10_CUDA_KERNEL_LAUNCH_CHECK(); \
421
+ break;
422
+ #endif
423
+
424
+ LAUNCH_SOFTMAX_WARP_BACKWARD(0); // 1
425
+ LAUNCH_SOFTMAX_WARP_BACKWARD(1); // 2
426
+ LAUNCH_SOFTMAX_WARP_BACKWARD(2); // 4
427
+ LAUNCH_SOFTMAX_WARP_BACKWARD(3); // 8
428
+ LAUNCH_SOFTMAX_WARP_BACKWARD(4); // 16
429
+ LAUNCH_SOFTMAX_WARP_BACKWARD(5); // 32
430
+ LAUNCH_SOFTMAX_WARP_BACKWARD(6); // 64
431
+ LAUNCH_SOFTMAX_WARP_BACKWARD(7); // 128
432
+ LAUNCH_SOFTMAX_WARP_BACKWARD(8); // 256
433
+ LAUNCH_SOFTMAX_WARP_BACKWARD(9); // 512
434
+ LAUNCH_SOFTMAX_WARP_BACKWARD(10); // 1024
435
+ default:
436
+ break;
437
+ }
438
+ }
439
+ }
440
+
441
+ #else
442
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
443
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Pow.cuh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/Pow.h>
4
+ #include <c10/core/Scalar.h>
5
+
6
+ namespace at::native {
7
+
8
+ namespace {
9
+
10
+
11
+ // SFINAE doesn't work well with NVCC under Windows for math functions like pow and sqrt.
12
+ // So we need to define the functions with the explicit function signatures.
13
+ // As for pow, the following signatures are defined as the device function:
14
+ // pow(float, int)
15
+ // pow(double, int)
16
+ // pow(float, float)
17
+ // pow(double, double)
18
+ #if defined(_MSC_VER) || defined(_LIBCPP_VERSION)
19
+ // Functions for pow
20
+ // pow for at::Half
21
+ static inline __host__ __device__ at::Half pow_(at::Half base, at::Half exp) {
22
+ return static_cast<at::Half>(std::pow(static_cast<float>(base), static_cast<float>(exp)));
23
+ }
24
+ // pow for at::BFloat16
25
+ static inline __host__ __device__ at::BFloat16 pow_(at::BFloat16 base, at::BFloat16 exp) {
26
+ return static_cast<at::BFloat16>(std::pow(static_cast<float>(base), static_cast<float>(exp)));
27
+ }
28
+ // pow (floating, floating/int)
29
+ template <typename Base_type, typename Exp_type>
30
+ static inline __host__ __device__ typename std::enable_if_t<std::is_floating_point_v<Base_type> && (std::is_same_v<Base_type, Exp_type> || std::is_same_v<Exp_type, int>), Base_type>
31
+ pow_(Base_type base, Exp_type exp) {
32
+ return std::pow(base, exp);
33
+ }
34
+ // pow (Otherwise)
35
+ template <typename Base_type, typename Exp_type>
36
+ static inline __host__ __device__ typename std::enable_if_t<!std::is_same_v<Base_type, Exp_type> && !std::is_same_v<Exp_type, int>, Base_type>
37
+ pow_(Base_type base, Exp_type exp) {
38
+ return static_cast<Base_type>(std::pow(static_cast<double>(base), static_cast<double>(exp)));
39
+ }
40
+ #else
41
+ template <typename Base_type, typename Exp_type>
42
+ static inline __host__ __device__ Base_type pow_(Base_type base, Exp_type exp) {
43
+ return ::pow(base, exp);
44
+ }
45
+ #endif
46
+
47
+ template <typename T>
48
+ static inline __host__ __device__ std::enable_if_t<std::is_integral_v<T>, T> pow_(
49
+ T base, T exp) {
50
+ return at::native::powi(base, exp);
51
+ }
52
+
53
+ template <typename T>
54
+ static inline __host__ __device__ c10::complex<T> pow_(c10::complex<T> base, c10::complex<T> exp) {
55
+ return c10_complex_math::pow(base, exp);
56
+ }
57
+
58
+ } // namespace
59
+ } // namespace at::native
60
+
61
+ #else
62
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
63
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Randperm.cuh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <ATen/cuda/CUDAGeneratorImpl.h>
3
+ #include <ATen/cuda/CUDAGraphsUtils.cuh>
4
+ #include <ATen/Utils.h>
5
+
6
+ #include <curand.h>
7
+ #include <curand_kernel.h>
8
+ #include <curand_philox4x32_x.h>
9
+
10
+ namespace {
11
+
12
+ // See note [Algorithm of randperm]
13
+ template<typename T, typename scalar_t>
14
+ __global__ void randperm_handle_duplicate_keys_kernel(T *keys, scalar_t *data, T mask, int n, at::PhiloxCudaState philox_args) {
15
+ int tid = threadIdx.x + blockDim.x * blockIdx.x;
16
+
17
+ // find the beginning of islands
18
+ if (tid >= n - 1) return; // out of range
19
+ if ((keys[tid] & mask) != (keys[tid + 1] & mask)) return; // not in an island
20
+ if (tid != 0 && (keys[tid] & mask) == (keys[tid - 1] & mask)) return; // not the beginning of an island
21
+
22
+ // find the size of islands
23
+ int island_size = 0;
24
+ do { island_size++; }
25
+ while ((tid + island_size < n) && (keys[tid + island_size] & mask) == (keys[tid] & mask));
26
+
27
+ // do random permutation inside each island.
28
+ data += tid;
29
+ const auto [seed, offset] = at::cuda::philox::unpack(philox_args);
30
+ curandStatePhilox4_32_10_t state;
31
+ curand_init(seed, tid, offset, &state);
32
+ for (int i = island_size - 1; i > 0; i--) {
33
+ unsigned int r = curand(&state) % (i + 1);
34
+ if (i != r) {
35
+ scalar_t tmp = data[i];
36
+ data[i] = data[r];
37
+ data[r] = tmp;
38
+ }
39
+ }
40
+ }
41
+
42
+ // See note [Algorithm of randperm]
43
+ template<typename T, typename scalar_t>
44
+ void randperm_handle_duplicate_keys(T *keys, scalar_t *data, int bits, int64_t n, std::optional<at::Generator> &gen_) {
45
+ auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(gen_, at::cuda::detail::getDefaultCUDAGenerator());
46
+ int64_t counter_offset = n;
47
+ at::PhiloxCudaState rng_engine_inputs;
48
+ {
49
+ // See Note [Acquire lock when using random generators]
50
+ std::lock_guard<std::mutex> lock(gen->mutex_);
51
+ rng_engine_inputs = gen->philox_cuda_state(counter_offset);
52
+ }
53
+ T mask = static_cast<T>((1UL << bits) - 1);
54
+ randperm_handle_duplicate_keys_kernel<<<(n + 511) / 512, 512, 0, at::cuda::getCurrentCUDAStream()>>>(
55
+ keys, data, mask, n, rng_engine_inputs);
56
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
57
+ }
58
+
59
+ }
60
+
61
+ #else
62
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
63
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Reduce.cuh ADDED
@@ -0,0 +1,1415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/cuda/DeviceUtils.cuh>
6
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
7
+ #include <ATen/detail/FunctionTraits.h>
8
+ #include <ATen/native/TensorIterator.h>
9
+ #include <ATen/native/cuda/thread_constants.h>
10
+ #include <ATen/native/cuda/MemoryAccess.cuh>
11
+ #include <ATen/OpMathType.h>
12
+ #include <c10/macros/Macros.h>
13
+ #include <c10/cuda/CUDACachingAllocator.h>
14
+ #include <array>
15
+ #include <functional>
16
+ #include <iosfwd>
17
+ #include <type_traits>
18
+ #include <utility>
19
+ #include <thrust/pair.h>
20
+
21
+ #include <ATen/native/cuda/jit_utils.h>
22
+ #include <ATen/native/cuda/KernelUtils.cuh>
23
+
24
+ namespace at::native {
25
+
26
+ static inline int64_t div_up(int64_t a, int64_t b) {
27
+ return (a + b - 1) / b;
28
+ }
29
+
30
+ // returns floor(log2(n))
31
+ static inline int last_pow2(int n) {
32
+ n |= (n >> 1);
33
+ n |= (n >> 2);
34
+ n |= (n >> 4);
35
+ n |= (n >> 8);
36
+ n |= (n >> 16);
37
+ return std::max(1, n - (n >> 1));
38
+ }
39
+
40
+ // returns reduced fraction numerator & denominator
41
+ C10_HOST_DEVICE static void reduce_fraction(size_t &numerator, size_t &denominator) {
42
+ // get GCD of num and denom using Euclid's algorithm.
43
+ // Can replace this with std::gcd if we ever support c++17.
44
+ size_t a = denominator;
45
+ size_t b = numerator;
46
+ while (b != 0) {
47
+ a %= b;
48
+ // swap(a,b)
49
+ size_t tmp = a;
50
+ a = b;
51
+ b = tmp;
52
+ }
53
+
54
+ // a is now the GCD
55
+ numerator /= a;
56
+ denominator /= a;
57
+ }
58
+
59
+ //template for changing MAX_NUM_THREADS based on op dtype
60
+ template <typename T>
61
+ struct mnt_wrapper {
62
+ static constexpr int MAX_NUM_THREADS = 512;
63
+ };
64
+
65
+ template <>
66
+ struct mnt_wrapper <c10::complex<double>>{
67
+ static constexpr int MAX_NUM_THREADS = 256;
68
+ };
69
+
70
+ constexpr int max_reduce_threads(c10::ScalarType type) {
71
+ return type == kComplexDouble ? 256 : 512;
72
+ }
73
+
74
+ struct ReduceConfig {
75
+ static constexpr int BLOCK_X = 0;
76
+ static constexpr int BLOCK_Y = 1;
77
+ static constexpr int CTA = 2;
78
+
79
+ ReduceConfig(int element_size_bytes, int num_outputs, int num_inputs)
80
+ : element_size_bytes(element_size_bytes)
81
+ , num_inputs(num_inputs)
82
+ , num_outputs(num_outputs) {}
83
+ int element_size_bytes;
84
+ int num_inputs;
85
+ int num_outputs;
86
+ int step_input = 1;
87
+ int step_output = 1;
88
+ int ctas_per_output = 1;
89
+ int input_mult[3] = {0, 0, 0};
90
+ int output_mult[2] = {0, 0};
91
+
92
+ int block_width;
93
+ int block_height;
94
+ int num_threads;
95
+
96
+ bool vectorize_input = false;
97
+ int output_vec_size = 1;
98
+
99
+ template <typename T>
100
+ void set_block_dimension(int64_t dim0, int64_t dim1) {
101
+ const int max_num_threads = mnt_wrapper<T>::MAX_NUM_THREADS / output_vec_size;
102
+ int dim0_pow2 = dim0 < max_num_threads ? static_cast<int>(last_pow2(dim0)) : max_num_threads;
103
+ int dim1_pow2 = dim1 < max_num_threads ? static_cast<int>(last_pow2(dim1)) : max_num_threads;
104
+ block_width = std::min(dim0_pow2, int(at::cuda::warp_size()));
105
+ block_height = std::min(dim1_pow2, int(max_num_threads / block_width));
106
+ block_width = std::min(dim0_pow2, int(max_num_threads / block_height));
107
+ num_threads = block_width * block_height;
108
+ }
109
+
110
+ int split_input(int parallelism) {
111
+ int step = step_input;
112
+ step_input *= parallelism;
113
+ return step;
114
+ }
115
+
116
+ int split_output(int parallelism) {
117
+ int step = step_output;
118
+ step_output *= parallelism;
119
+ return step;
120
+ }
121
+
122
+ dim3 block() const {
123
+ return dim3(block_width, block_height);
124
+ }
125
+
126
+ dim3 grid() const {
127
+ return dim3(div_up(num_outputs / output_vec_size, step_output), ctas_per_output);
128
+ }
129
+
130
+ C10_HOST_DEVICE bool should_block_x_reduce() const {
131
+ return input_mult[BLOCK_X] != 0;
132
+ }
133
+
134
+ C10_HOST_DEVICE bool should_block_y_reduce() const {
135
+ return input_mult[BLOCK_Y] != 0;
136
+ }
137
+
138
+ C10_HOST_DEVICE bool should_global_reduce() const {
139
+ return input_mult[CTA] != 0;
140
+ }
141
+
142
+ C10_DEVICE bool should_store(int output_idx) const {
143
+ return output_idx < num_outputs &&
144
+ (!should_block_x_reduce() || threadIdx.x == 0) &&
145
+ (!should_block_y_reduce() || threadIdx.y == 0);
146
+ }
147
+
148
+ C10_DEVICE bool should_reduce_tail() const {
149
+ return (!should_block_y_reduce() || threadIdx.y == 0) &&
150
+ (!should_global_reduce() || blockIdx.y == 0);
151
+ }
152
+
153
+ C10_HOST_DEVICE int input_idx() const {
154
+ int lane = threadIdx.x;
155
+ int warp = threadIdx.y;
156
+ int cta2 = blockIdx.y;
157
+ return (lane * input_mult[BLOCK_X] +
158
+ warp * input_mult[BLOCK_Y] +
159
+ cta2 * input_mult[CTA]);
160
+ }
161
+
162
+ template <int output_vec_size>
163
+ C10_HOST_DEVICE int output_idx() const {
164
+ int lane = threadIdx.x;
165
+ int warp = threadIdx.y;
166
+ int cta1 = blockIdx.x;
167
+ return (lane * output_mult[BLOCK_X] +
168
+ warp * output_mult[BLOCK_Y] +
169
+ cta1 * step_output) * output_vec_size;
170
+ }
171
+
172
+ C10_DEVICE int shared_memory_offset(int offset) const {
173
+ return threadIdx.x + (threadIdx.y + offset) * blockDim.x;
174
+ }
175
+
176
+ C10_DEVICE int staging_memory_offset(int cta2) const {
177
+ int offset = cta2 + blockIdx.x * gridDim.y;
178
+ if (!should_block_x_reduce()) {
179
+ offset = threadIdx.x + offset * blockDim.x;
180
+ }
181
+ return offset;
182
+ }
183
+
184
+ int shared_memory_size() const {
185
+ if (!should_block_y_reduce() &&
186
+ (!should_block_x_reduce() ||
187
+ block_width <= at::cuda::warp_size())) {
188
+ return 0;
189
+ }
190
+ return element_size_bytes * num_threads * output_vec_size;
191
+ }
192
+
193
+ int64_t global_memory_size() const {
194
+ if (!should_global_reduce()) {
195
+ return 0;
196
+ }
197
+ auto size = (int64_t)element_size_bytes * num_outputs * ctas_per_output;
198
+ if (!should_block_x_reduce()) {
199
+ size *= block().x * output_vec_size;
200
+ }
201
+ return size;
202
+ }
203
+
204
+ int semaphore_size() const {
205
+ if (!should_global_reduce()) {
206
+ return 0;
207
+ }
208
+ return sizeof(int) * grid().x;
209
+ }
210
+
211
+ int values_per_thread() const {
212
+ return div_up(num_inputs, step_input);
213
+ }
214
+
215
+ int mock_values_per_thread(int parallelism) {
216
+ return div_up(num_inputs, step_input * parallelism);
217
+ }
218
+ };
219
+
220
+ std::ostream& operator<<(std::ostream& out, const ReduceConfig& config);
221
+
222
+ template<int nt, int output_vec_size, typename R>
223
+ C10_LAUNCH_BOUNDS_2(nt, 4)
224
+ __global__ void reduce_kernel(R reduction) {
225
+ reduction.template run<output_vec_size>();
226
+ }
227
+
228
+ template <typename index_t>
229
+ static OffsetCalculator<2, index_t> make_output_calculator(const TensorIterator& iter) {
230
+ int num_reduce_dims = iter.num_reduce_dims();
231
+ int num_output_dims = iter.ndim() - num_reduce_dims;
232
+ int input_index = iter.ntensors() - 1;
233
+ int output_index = 0;
234
+ std::array<const int64_t*, 2> strides = {
235
+ iter.strides(output_index).data() + num_reduce_dims,
236
+ iter.strides(input_index).data() + num_reduce_dims,
237
+ };
238
+ auto shape = iter.shape().data() + num_reduce_dims;
239
+ return OffsetCalculator<2, index_t>(num_output_dims, shape, strides.data());
240
+ }
241
+
242
+ template <typename index_t>
243
+ static OffsetCalculator<1, index_t> make_input_calculator(const TensorIterator& iter) {
244
+ int num_reduce_dims = iter.num_reduce_dims();
245
+ int input_index = iter.ntensors() - 1;
246
+ std::array<const int64_t*, 1> strides = {
247
+ iter.strides(input_index).data(),
248
+ };
249
+ return OffsetCalculator<1, index_t>(num_reduce_dims, iter.shape().data(), strides.data());
250
+ }
251
+
252
+ template <typename out_scalar_t, typename func_t>
253
+ struct func_wrapper_t {
254
+ using arg_t = typename binary_function_traits<func_t>::arg1_t;
255
+ using scalar_t = typename binary_function_traits<func_t>::arg2_t;
256
+
257
+ func_t combine;
258
+ static inline __device__ out_scalar_t project(arg_t arg) {
259
+ return (out_scalar_t) arg;
260
+ }
261
+ static inline __device__ arg_t warp_shfl_down(arg_t arg, int offset) {
262
+ return WARP_SHFL_DOWN(arg, offset);
263
+ }
264
+
265
+ static __device__ arg_t translate_idx(arg_t acc, int64_t /*idx*/) {
266
+ return acc;
267
+ }
268
+
269
+ func_wrapper_t(const func_t& op) : combine(op) {
270
+ }
271
+
272
+ // wrap a normal reduction that ignores the index
273
+ __device__ arg_t reduce(arg_t acc, scalar_t val, int64_t idx) const {
274
+ return combine(acc, val);
275
+ }
276
+ };
277
+
278
+ template <typename scalar_t, typename func_t>
279
+ func_wrapper_t<scalar_t, func_t> func_wrapper(const func_t& op) {
280
+ return func_wrapper_t<scalar_t, func_t> { op };
281
+ }
282
+
283
+ template <typename scalar_t, typename out_scalar_t=scalar_t>
284
+ struct ReduceJitOp {
285
+ //ReduceJitOp is almost like ReduceOp, but it doesn't have ops functor that specifies reduction operations
286
+ //Maybe we can find a way to unify ReduceOp and ReduceJitOp
287
+ using InputCalculator = OffsetCalculator<1, uint32_t>;
288
+ using OutputCalculator = OffsetCalculator<2, uint32_t>;
289
+ //TODO for now arg_t is always opmath_t of the input, later we'll need to change it
290
+ using arg_t = at::opmath_type<scalar_t>;
291
+
292
+ //TODO - ReduceJitOp will probably need to be changed for reductions that need full functor,
293
+ //not just wrapper
294
+ arg_t ident;
295
+ ReduceConfig config;
296
+ InputCalculator input_calc;
297
+ OutputCalculator output_calc;
298
+ const void* src;
299
+ const char* dst[2]; //it accepts at most two destinations
300
+ // acc_buf used for accumulation among sub Tensor Iterator when accumulation on
301
+ // output is not permissible
302
+ void* acc_buf;
303
+ // cta_buf used for accumulation between blocks during global reduction
304
+ void* cta_buf;
305
+ int* semaphores;
306
+ int64_t base_idx;
307
+ bool accumulate;
308
+ bool final_output;
309
+ int noutputs;
310
+
311
+ ReduceJitOp(
312
+ ReduceConfig config,
313
+ InputCalculator input_calc,
314
+ OutputCalculator output_calc,
315
+ const void* src,
316
+ char* dst0,
317
+ std::optional<char*> dst1,
318
+ void* acc_buf,
319
+ void* cta_buf,
320
+ int* semaphores,
321
+ arg_t ident,
322
+ int noutputs,
323
+ int64_t base_idx)
324
+ : ident(ident),
325
+ config(config),
326
+ input_calc(input_calc),
327
+ output_calc(output_calc),
328
+ src(src),
329
+ acc_buf(acc_buf),
330
+ cta_buf(cta_buf),
331
+ semaphores(semaphores),
332
+ base_idx(base_idx),
333
+ noutputs(noutputs) {
334
+ dst[0] = dst0;
335
+ if (dst1.has_value()) {
336
+ dst[1] = dst1.value();
337
+ }
338
+ }
339
+ };
340
+
341
+ template <typename scalar_t, typename ops_t, typename index_t, typename out_scalar_t=scalar_t, int vt0=4, int input_vec_size=vt0>
342
+ struct ReduceOp {
343
+ using traits = function_traits<decltype(&ops_t::reduce)>;
344
+ using arg_t = typename std::decay<typename traits::template arg<0>::type>::type;
345
+
346
+ using InputCalculator = OffsetCalculator<1, index_t>;
347
+ using OutputCalculator = OffsetCalculator<2, index_t>;
348
+
349
+ static constexpr bool can_accumulate_in_output =
350
+ std::is_convertible_v<arg_t, out_scalar_t>
351
+ && std::is_convertible_v<out_scalar_t, arg_t>;
352
+
353
+ ops_t ops;
354
+ arg_t ident;
355
+ ReduceConfig config;
356
+ InputCalculator input_calc;
357
+ OutputCalculator output_calc;
358
+ const void* src;
359
+ const char* dst[2]; //it accepts at most two destinations
360
+ // acc_buf used for accumulation among sub Tensor Iterator when accumulation on
361
+ // output is not permissible
362
+ void* acc_buf;
363
+ // cta_buf used for accumulation between blocks during global reduction
364
+ void* cta_buf;
365
+ int* semaphores;
366
+ int64_t base_idx;
367
+ bool accumulate;
368
+ bool final_output;
369
+ int noutputs;
370
+
371
+ ReduceOp(
372
+ ops_t ops,
373
+ ReduceConfig config,
374
+ InputCalculator input_calc,
375
+ OutputCalculator output_calc,
376
+ const void* src,
377
+ char* dst0,
378
+ std::optional<char*> dst1,
379
+ void* acc_buf,
380
+ void* cta_buf,
381
+ int* semaphores,
382
+ arg_t ident,
383
+ int noutputs,
384
+ int64_t base_idx)
385
+ : ops(ops),
386
+ ident(ident),
387
+ config(config),
388
+ input_calc(input_calc),
389
+ output_calc(output_calc),
390
+ src(src),
391
+ acc_buf(acc_buf),
392
+ cta_buf(cta_buf),
393
+ semaphores(semaphores),
394
+ base_idx(base_idx),
395
+ noutputs(noutputs) {
396
+ dst[0] = dst0;
397
+ if (dst1.has_value()) {
398
+ dst[1] = dst1.value();
399
+ }
400
+ }
401
+
402
+ template <int output_vec_size>
403
+ C10_DEVICE void run() const {
404
+ extern __shared__ char shared_memory[];
405
+ index_t output_idx = config.output_idx<output_vec_size>();
406
+ index_t input_idx = config.input_idx();
407
+ auto base_offsets1 = output_calc.get(output_idx)[1];
408
+
409
+ using arg_vec_t = std::array<arg_t, output_vec_size>;
410
+ arg_vec_t value;
411
+
412
+ if (output_idx < config.num_outputs && input_idx < config.num_inputs) {
413
+ const scalar_t* input_slice = (const scalar_t*)((const char*)src + base_offsets1);
414
+ value = thread_reduce<output_vec_size>(input_slice);
415
+ }
416
+
417
+ if (config.should_block_x_reduce()) {
418
+ value = block_x_reduce<output_vec_size>(value, shared_memory);
419
+ }
420
+ if (config.should_block_y_reduce()) {
421
+ value = block_y_reduce<output_vec_size>(value, shared_memory);
422
+ }
423
+ using out_ptr_vec_t = std::array<out_scalar_t*, output_vec_size>;
424
+ using offset_vec_t = std::array<index_t, output_vec_size>;
425
+ offset_vec_t base_offsets;
426
+ out_ptr_vec_t out;
427
+
428
+ #pragma unroll
429
+ for (int i = 0; i < output_vec_size; i++) {
430
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
431
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
432
+ }
433
+
434
+ arg_vec_t* acc = nullptr;
435
+ if (acc_buf != nullptr) {
436
+ size_t numerator = sizeof(arg_t);
437
+ size_t denominator = sizeof(out_scalar_t);
438
+ reduce_fraction(numerator, denominator);
439
+ acc = (arg_vec_t*)((char*)acc_buf + (base_offsets[0] * numerator / denominator));
440
+ }
441
+
442
+ if (config.should_global_reduce()) {
443
+ value = global_reduce<output_vec_size>(value, acc, shared_memory);
444
+ } else if (config.should_store(output_idx)) {
445
+ if (accumulate) {
446
+ #pragma unroll
447
+ for (int i = 0; i < output_vec_size; i++) {
448
+ value[i] = ops.translate_idx(value[i], base_idx);
449
+ }
450
+ }
451
+
452
+ if (acc == nullptr) {
453
+ if (accumulate) {
454
+ value = accumulate_in_output<output_vec_size, can_accumulate_in_output>(out, value);
455
+ }
456
+ if (final_output) {
457
+ set_results_to_output<output_vec_size>(value, base_offsets);
458
+ } else {
459
+ #pragma unroll
460
+ for (int i = 0; i < output_vec_size; i++) {
461
+ *(out[i]) = get_accumulated_output<can_accumulate_in_output>(out[i], value[i]);
462
+ }
463
+ }
464
+ } else {
465
+ if (accumulate) {
466
+ #pragma unroll
467
+ for (int i = 0; i < output_vec_size; i++) {
468
+ value[i] = ops.combine((*acc)[i], value[i]);
469
+ }
470
+ }
471
+ if (final_output) {
472
+ set_results_to_output<output_vec_size>(value, base_offsets);
473
+ } else {
474
+ *acc = value;
475
+ }
476
+ }
477
+ }
478
+ }
479
+
480
+ template <int output_vec_size>
481
+ C10_DEVICE std::array<arg_t, output_vec_size> thread_reduce(const scalar_t* data) const {
482
+ if (config.vectorize_input) {
483
+ CUDA_KERNEL_ASSERT(output_vec_size == 1);
484
+ // reduce at the header of input_slice where memory is not aligned,
485
+ // so that thread_reduce will have an aligned memory to work on.
486
+ return {input_vectorized_thread_reduce_impl(data)};
487
+ } else {
488
+ index_t element_stride = input_calc.strides_[0][0] / sizeof(scalar_t);
489
+ bool is_contiguous = (input_calc.dims == 1 && element_stride == 1);
490
+ if (is_contiguous) {
491
+ return thread_reduce_impl<output_vec_size>(data, [](index_t idx) { return idx; });
492
+ } else if (input_calc.dims == 1) {
493
+ return thread_reduce_impl<output_vec_size>(data, [&](index_t idx) { return idx * element_stride; });
494
+ } else {
495
+ return thread_reduce_impl<output_vec_size>(data, [&](index_t idx) { return input_calc.get(idx)[0] / sizeof(scalar_t); });
496
+ }
497
+ }
498
+ }
499
+
500
+ C10_DEVICE arg_t input_vectorized_thread_reduce_impl(const scalar_t* data) const {
501
+ index_t end = config.num_inputs;
502
+
503
+ // Handle the head of input slice where data is not aligned
504
+ arg_t value = ident;
505
+ constexpr int align_bytes = alignof(at::native::memory::aligned_vector<scalar_t, input_vec_size>);
506
+ constexpr int align_elements = align_bytes / sizeof(scalar_t);
507
+ int shift = ((uint64_t)data) % align_bytes / sizeof(scalar_t);
508
+ if (shift > 0) {
509
+ data -= shift;
510
+ end += shift;
511
+ if(threadIdx.x >= shift && threadIdx.x < align_elements && config.should_reduce_tail()){
512
+ value = ops.reduce(value, c10::load(data + threadIdx.x), threadIdx.x - shift);
513
+ }
514
+ end -= align_elements;
515
+ data += align_elements;
516
+ shift = align_elements - shift;
517
+ }
518
+
519
+ // Do the vectorized reduction
520
+ using load_t = at::native::memory::aligned_vector<scalar_t, input_vec_size>;
521
+
522
+ index_t idx = config.input_idx();
523
+ const index_t stride = config.step_input;
524
+
525
+ // Multiple accumulators to remove dependency between unrolled loops.
526
+ arg_t value_list[input_vec_size];
527
+ value_list[0] = value;
528
+
529
+ #pragma unroll
530
+ for (int i = 1; i < input_vec_size; i++) {
531
+ value_list[i] = ident;
532
+ }
533
+
534
+ while (idx * input_vec_size + input_vec_size - 1 < end) {
535
+ const auto values_vec = memory::load_vector<input_vec_size>(data, idx);
536
+ #pragma unroll
537
+ for (index_t i = 0; i < input_vec_size; i++) {
538
+ value_list[i] = ops.reduce(value_list[i], values_vec.val[i], shift + idx * input_vec_size + i);
539
+ }
540
+ idx += stride;
541
+ }
542
+
543
+ // tail
544
+ index_t tail_start = end - end % input_vec_size;
545
+ if (config.should_reduce_tail()) {
546
+ int idx = tail_start + threadIdx.x;
547
+ if (idx < end) {
548
+ const auto value = c10::load(data + idx);
549
+ value_list[0] = ops.reduce(value_list[0], value, idx + shift);
550
+ }
551
+ }
552
+
553
+ // combine accumulators
554
+ #pragma unroll
555
+ for (int i = 1; i < input_vec_size; i++) {
556
+ value_list[0] = ops.combine(value_list[0], value_list[i]);
557
+ }
558
+ return value_list[0];
559
+ }
560
+
561
+ template <int output_vec_size, typename offset_calc_t>
562
+ C10_DEVICE std::array<arg_t, output_vec_size> thread_reduce_impl(const scalar_t* data_, offset_calc_t calc) const {
563
+ index_t idx = config.input_idx();
564
+ const index_t end = config.num_inputs;
565
+ const index_t stride = config.step_input;
566
+
567
+ using arg_vec_t = std::array<arg_t, output_vec_size>;
568
+ using load_t = at::native::memory::aligned_vector<scalar_t, output_vec_size>;
569
+
570
+ // Multiple accumulators to remove dependency between unrolled loops.
571
+ arg_vec_t value_list[vt0];
572
+
573
+ #pragma unroll
574
+ for (int i = 0; i < vt0; i++) {
575
+ #pragma unroll
576
+ for (int j = 0; j < output_vec_size; j++) {
577
+ value_list[i][j] = ident;
578
+ }
579
+ }
580
+
581
+ load_t values[vt0];
582
+
583
+ while (idx + (vt0 - 1) * stride < end) {
584
+ #pragma unroll
585
+ for (index_t i = 0; i < vt0; i++) {
586
+ const auto offset = calc(idx + i * stride) / output_vec_size;
587
+ values[i] = memory::load_vector<output_vec_size>(data_, offset);
588
+ }
589
+ #pragma unroll
590
+ for (index_t i = 0; i < vt0; i++) {
591
+ #pragma unroll
592
+ for (index_t j = 0; j < output_vec_size; j++) {
593
+ value_list[i][j] = ops.reduce(value_list[i][j], values[i].val[j], idx + i * stride);
594
+ }
595
+ }
596
+ idx += stride * vt0;
597
+ }
598
+
599
+ // tail
600
+ int idx_ = idx;
601
+ #pragma unroll
602
+ for (index_t i = 0; i < vt0; i++) {
603
+ if (idx >= end) {
604
+ break;
605
+ }
606
+ const auto offset = calc(idx) / output_vec_size;
607
+ values[i] = memory::load_vector<output_vec_size>(data_, offset);
608
+ idx += stride;
609
+ }
610
+ idx = idx_;
611
+ #pragma unroll
612
+ for (index_t i = 0; i < vt0; i++) {
613
+ if (idx >= end) {
614
+ break;
615
+ }
616
+ #pragma unroll
617
+ for (index_t j = 0; j < output_vec_size; j++) {
618
+ value_list[i][j] = ops.reduce(value_list[i][j], values[i].val[j], idx);
619
+ }
620
+ idx += stride;
621
+ }
622
+
623
+ // combine accumulators
624
+ #pragma unroll
625
+ for (int i = 1; i < vt0; i++) {
626
+ #pragma unroll
627
+ for (index_t j = 0; j < output_vec_size; j++) {
628
+ value_list[0][j] = ops.combine(value_list[0][j], value_list[i][j]);
629
+ }
630
+ }
631
+ return value_list[0];
632
+ }
633
+
634
+ template <int output_vec_size>
635
+ C10_DEVICE std::array<arg_t, output_vec_size> block_x_reduce(std::array<arg_t, output_vec_size> value, char* shared_memory) const {
636
+ using args_vec_t = std::array<arg_t, output_vec_size>;
637
+ int dim_x = blockDim.x;
638
+ args_vec_t* shared = (args_vec_t*)shared_memory;
639
+ if (dim_x > C10_WARP_SIZE) {
640
+ int address_base = threadIdx.x + threadIdx.y*blockDim.x;
641
+ shared[address_base] = value;
642
+ for (int offset = dim_x/2; offset >= C10_WARP_SIZE; offset >>= 1) {
643
+ __syncthreads();
644
+ if (threadIdx.x < offset && threadIdx.x + offset < blockDim.x) {
645
+ args_vec_t other = shared[address_base + offset];
646
+ #pragma unroll
647
+ for (int i = 0; i < output_vec_size; i++) {
648
+ value[i] = ops.combine(value[i], other[i]);
649
+ }
650
+ shared[address_base] = value;
651
+ }
652
+ }
653
+ dim_x = C10_WARP_SIZE;
654
+ }
655
+
656
+ __syncthreads();
657
+ // Intra-warp reduction, fix CUDA to have offset decreasing for better numerics
658
+ // matching Triton, etc.
659
+ #if defined(USE_ROCM)
660
+ for (int offset = 1; offset < dim_x; offset <<= 1) {
661
+ #else
662
+ for (int offset = dim_x >> 1; offset > 0; offset >>= 1) {
663
+ #endif
664
+ #pragma unroll
665
+ for (int i = 0; i < output_vec_size; i++) {
666
+ arg_t other = ops.warp_shfl_down(value[i], offset);
667
+ value[i] = ops.combine(value[i], other);
668
+ }
669
+ }
670
+ return value;
671
+ }
672
+
673
+ template <int output_vec_size>
674
+ C10_DEVICE std::array<arg_t, output_vec_size> block_y_reduce(std::array<arg_t, output_vec_size> value, char* shared_memory) const {
675
+ using args_vec_t = std::array<arg_t, output_vec_size>;
676
+ args_vec_t* shared = (args_vec_t*)shared_memory;
677
+ shared[config.shared_memory_offset(0)] = value;
678
+ for (int offset = blockDim.y / 2; offset > 0; offset >>= 1) {
679
+ __syncthreads();
680
+ if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) {
681
+ args_vec_t other = shared[config.shared_memory_offset(offset)];
682
+ #pragma unroll
683
+ for (int i = 0; i < output_vec_size; i++) {
684
+ value[i] = ops.combine(value[i], other[i]);
685
+ }
686
+ shared[config.shared_memory_offset(0)] = value;
687
+ }
688
+ }
689
+ return value;
690
+ }
691
+
692
+ C10_DEVICE bool mark_block_finished() const {
693
+ __shared__ bool is_last_block_done_shared;
694
+
695
+ __syncthreads();
696
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
697
+ int prev_blocks_finished = atomicAdd(&semaphores[blockIdx.x], 1);
698
+ is_last_block_done_shared = (prev_blocks_finished == gridDim.y - 1);
699
+ }
700
+
701
+ __syncthreads();
702
+
703
+ return is_last_block_done_shared;
704
+ }
705
+
706
+ template <int output_vec_size, bool can_acc>
707
+ C10_DEVICE std::array<arg_t, output_vec_size> accumulate_in_output(
708
+ std::array<out_scalar_t*, output_vec_size> out,
709
+ std::array<arg_t, output_vec_size> value,
710
+ typename std::enable_if_t<can_acc>* = nullptr
711
+ ) const {
712
+ std::array<arg_t, output_vec_size> ret;
713
+ #pragma unroll
714
+ for (int i = 0; i < output_vec_size; i++) {
715
+ ret[i] = ops.combine(*(out[i]), value[i]);
716
+ }
717
+ return ret;
718
+ }
719
+
720
+ template <bool can_acc>
721
+ C10_DEVICE out_scalar_t get_accumulated_output(
722
+ out_scalar_t* out, arg_t value,
723
+ typename std::enable_if_t<can_acc>* = nullptr
724
+ ) const {
725
+ CUDA_KERNEL_ASSERT(!final_output);
726
+ return (out_scalar_t)value;
727
+ }
728
+
729
+ // This function should never be called --
730
+ // it's the version of `accumulate_in_output`
731
+ // when accumulation in the output is not possible.
732
+ template <int output_vec_size, bool can_acc>
733
+ C10_DEVICE std::array<arg_t, output_vec_size> accumulate_in_output(
734
+ std::array<out_scalar_t*, output_vec_size>,
735
+ std::array<arg_t, output_vec_size>,
736
+ typename std::enable_if_t<!can_acc>* = nullptr
737
+ ) const {
738
+ CUDA_KERNEL_ASSERT(false);
739
+ return {arg_t{}};
740
+ }
741
+
742
+ // This function should never be called --
743
+ // it's the version of `get_accumulated_output`
744
+ // when accumulation in the output is not possible.
745
+ template <bool can_acc>
746
+ C10_DEVICE out_scalar_t get_accumulated_output(
747
+ out_scalar_t* out, arg_t value,
748
+ typename std::enable_if_t<!can_acc>* = nullptr
749
+ ) const {
750
+ CUDA_KERNEL_ASSERT(false);
751
+ return *out;
752
+ }
753
+
754
+ template<class T>
755
+ C10_DEVICE void set_results(const T x, const index_t base_offset) const {
756
+ CUDA_KERNEL_ASSERT(noutputs == 1);
757
+ auto res = (out_scalar_t*)((char*)dst[0] + base_offset);
758
+ *res = x;
759
+ }
760
+
761
+ //Currently implemented for max of two outputs
762
+ template<class T1, class T2>
763
+ C10_DEVICE void set_results(const thrust::pair<T1, T2> x, const index_t base_offset) const {
764
+ if (noutputs >= 1) {
765
+ auto res0 = (T1*)((char*)dst[0] + base_offset);
766
+ *res0 = x.first;
767
+ }
768
+ if (noutputs >= 2) {
769
+ // base offset is computed assuming element size being sizeof(T1), so we need to make a
770
+ // correction to obtain the correct base offset
771
+ auto res1 = (T2*) ((char *) dst[1] + base_offset / sizeof(T1) * sizeof(T2));
772
+ *res1 = x.second;
773
+ }
774
+ }
775
+
776
+ template <int output_vec_size>
777
+ C10_DEVICE void set_results_to_output(std::array<arg_t, output_vec_size> value, std::array<index_t, output_vec_size> base_offset) const {
778
+ CUDA_KERNEL_ASSERT(final_output);
779
+ #pragma unroll
780
+ for (int i = 0; i < output_vec_size; i++) {
781
+ set_results(ops.project(value[i]), base_offset[i]);
782
+ }
783
+ }
784
+
785
+ template <int output_vec_size>
786
+ C10_DEVICE std::array<arg_t, output_vec_size> global_reduce(std::array<arg_t, output_vec_size> value, std::array<arg_t, output_vec_size> *acc, char* shared_memory) const {
787
+ using arg_vec_t = std::array<arg_t, output_vec_size>;
788
+ using out_ptr_vec_t = std::array<out_scalar_t*, output_vec_size>;
789
+ using offset_vec_t = std::array<index_t, output_vec_size>;
790
+
791
+ arg_vec_t* reduce_buffer = (arg_vec_t*)cta_buf;
792
+ index_t output_idx = config.output_idx<output_vec_size>();
793
+ offset_vec_t base_offsets;
794
+ out_ptr_vec_t out;
795
+
796
+ #pragma unroll
797
+ for (int i = 0; i < output_vec_size; i++) {
798
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
799
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
800
+ }
801
+
802
+ bool should_store = config.should_store(output_idx);
803
+ if (should_store) {
804
+ index_t offset = config.staging_memory_offset(blockIdx.y);
805
+ #ifndef USE_ROCM
806
+ reduce_buffer[offset] = value;
807
+ #else // [CMTSTRS]
808
+ // In architectures with split caches, global fences are costly.
809
+ // Here we preempt need for fences by committing stores to global memory.
810
+ cmtdStore(&reduce_buffer[offset], value);
811
+ #endif
812
+ }
813
+
814
+ #ifndef USE_ROCM // skip fence if store are committed [CMTSTRS]
815
+ __threadfence(); // make sure writes are globally visible
816
+ #endif
817
+ __syncthreads(); // if multiple warps in this block wrote to staging, make sure they're all done
818
+ bool is_last_block_done = mark_block_finished();
819
+
820
+ if (is_last_block_done) {
821
+ #ifndef USE_ROCM // skip fence if store are committed [CMTSTRS]
822
+ __threadfence(); // complete the acquire pattern after atomic
823
+ #endif
824
+ for (auto &v : value) {
825
+ v = ident;
826
+ }
827
+ if (config.should_block_x_reduce()) {
828
+ index_t input_offset = threadIdx.x + threadIdx.y * blockDim.x;
829
+ index_t step = blockDim.x * blockDim.y;
830
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
831
+ index_t idx = config.staging_memory_offset(input_offset);
832
+ arg_vec_t next = reduce_buffer[idx];
833
+ #pragma unroll
834
+ for (int i = 0; i < output_vec_size; i++) {
835
+ value[i] = ops.combine(value[i], next[i]);
836
+ }
837
+ }
838
+ } else {
839
+ #if defined(USE_ROCM) && ROCM_VERSION <= 71300
840
+ index_t input_offset = threadIdx.y;
841
+ index_t step = blockDim.y;
842
+ #define PRFCH 4
843
+ for (; input_offset < config.ctas_per_output; input_offset += step*PRFCH) {
844
+ arg_vec_t next[PRFCH];
845
+ #pragma unroll
846
+ for (int u = 0; (u < PRFCH) && (input_offset + u*step < config.ctas_per_output); u++) {
847
+ index_t idx = config.staging_memory_offset(input_offset + u*step);
848
+ next[u] = reduce_buffer[idx];
849
+ }
850
+ for (int u = 0; (u < PRFCH) && (input_offset + u*step < config.ctas_per_output); u++) {
851
+ #pragma unroll
852
+ for (int i = 0; i < output_vec_size; i++) {
853
+ value[i] = ops.combine(value[i], next[u][i]);
854
+ }
855
+ }
856
+ }
857
+ #else
858
+ #if defined(USE_ROCM)
859
+ int input_offset = threadIdx.y;
860
+ int step = blockDim.y;
861
+ #pragma unroll
862
+ #else
863
+ index_t input_offset = threadIdx.y;
864
+ index_t step = blockDim.y;
865
+ #endif
866
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
867
+ index_t idx = config.staging_memory_offset(input_offset);
868
+ arg_vec_t next = reduce_buffer[idx];
869
+ #pragma unroll
870
+ for (int i = 0; i < output_vec_size; i++) {
871
+ value[i] = ops.combine(value[i], next[i]);
872
+ }
873
+ }
874
+ #endif
875
+ }
876
+ value = block_y_reduce<output_vec_size>(value, shared_memory);
877
+ if (config.should_block_x_reduce()) {
878
+ value = block_x_reduce<output_vec_size>(value, shared_memory);
879
+ }
880
+ if (should_store) {
881
+ if (accumulate) {
882
+ #pragma unroll
883
+ for (int i = 0; i < output_vec_size; i++) {
884
+ value[i] = ops.translate_idx(value[i], base_idx);
885
+ }
886
+ }
887
+
888
+ if (acc == nullptr) {
889
+ if (accumulate) {
890
+ value = accumulate_in_output<output_vec_size, can_accumulate_in_output>(out, value);
891
+ }
892
+ if (final_output) {
893
+ set_results_to_output<output_vec_size>(value, base_offsets);
894
+ } else {
895
+ #pragma unroll
896
+ for (int i = 0; i < output_vec_size; i++) {
897
+ *(out[i]) = get_accumulated_output<can_accumulate_in_output>(out[i], value[i]);
898
+ }
899
+ }
900
+ } else {
901
+ if (accumulate) {
902
+ #pragma unroll
903
+ for (int i = 0; i < output_vec_size; i++) {
904
+ value[i] = ops.combine((*acc)[i], value[i]);
905
+ }
906
+ }
907
+ if (final_output) {
908
+ set_results_to_output<output_vec_size>(value, base_offsets);
909
+ } else {
910
+ *acc = value;
911
+ }
912
+ }
913
+ }
914
+ }
915
+
916
+ return value;
917
+ }
918
+ };
919
+
920
+ template<int max_threads, typename R>
921
+ static void launch_reduce_kernel(const ReduceConfig& config, const R& reduction) {
922
+ dim3 block = config.block();
923
+ dim3 grid = config.grid();
924
+
925
+ auto stream = at::cuda::getCurrentCUDAStream();
926
+ int shared_memory = config.shared_memory_size();
927
+
928
+ switch(config.output_vec_size) {
929
+ case 4:
930
+ reduce_kernel<max_threads / 4, 4, R><<<grid, block, shared_memory, stream>>>(reduction);
931
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
932
+ break;
933
+ case 2:
934
+ reduce_kernel<max_threads / 2, 2, R><<<grid, block, shared_memory, stream>>>(reduction);
935
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
936
+ break;
937
+ default:
938
+ reduce_kernel<max_threads / 1, 1, R><<<grid, block, shared_memory, stream>>>(reduction);
939
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
940
+ }
941
+ }
942
+
943
+ inline void launch_jitted_reduce_kernel(
944
+ std::mutex &jiterator_mutex,
945
+ std::array<at::cuda::jit::NvrtcFunction, 3> &fn_cache,
946
+ const at::cuda::jit::KernelDescriptor &desc,
947
+ int vt0, const ReduceConfig& config, const void *reduction) {
948
+ dim3 block = config.block();
949
+ dim3 grid = config.grid();
950
+
951
+ int shared_memory = config.shared_memory_size();
952
+ at::cuda::jit::NvrtcFunction* fn_ptr;
953
+ switch(config.output_vec_size) {
954
+ case 4:
955
+ fn_ptr = &fn_cache[0];
956
+ break;
957
+ case 2:
958
+ fn_ptr = &fn_cache[1];
959
+ break;
960
+ default:
961
+ fn_ptr = &fn_cache[2];
962
+ }
963
+ if (!fn_ptr->function) {
964
+ int max_threads_codegen =
965
+ max_reduce_threads(desc.f_inputs_type) / config.output_vec_size;
966
+ auto code = at::cuda::jit::generate_reduction_code(
967
+ desc, vt0, true, false, config.output_vec_size, max_threads_codegen);
968
+
969
+ *fn_ptr = at::cuda::jit::jit_pwise_function(code, "reduction_" + desc.name);
970
+ }
971
+ constexpr int kernel_args = 1;
972
+ const void* args[kernel_args];
973
+ args[0] = reduction;
974
+ at::cuda::jit::launch_jitted_pwise_function(*fn_ptr, args, grid, block, shared_memory);
975
+ }
976
+
977
+
978
+ class AccumulationBuffer {
979
+ public:
980
+ AccumulationBuffer() = default;
981
+
982
+ AccumulationBuffer(size_t acc_t_size, size_t out_t_size, char* out_ptr, int64_t size) {
983
+ out_ptr_ = (char*)out_ptr;
984
+ if (out_t_size >= acc_t_size) {
985
+ // reusing output buffer for accumulation.
986
+ acc_ptr_ = (char*)out_ptr;
987
+ numerator_ = 1;
988
+ denominator_ = 1;
989
+ } else {
990
+ auto& allocator = *c10::cuda::CUDACachingAllocator::get();
991
+ buffer_ = allocator.allocate(size);
992
+ acc_ptr_ = (char*)buffer_.get();
993
+ numerator_ = acc_t_size;
994
+ denominator_ = out_t_size;
995
+ reduce_fraction(numerator_, denominator_);
996
+ }
997
+ }
998
+
999
+ char* get_acc_slice(char* out_ptr) {
1000
+ if (acc_ptr_ == nullptr) {
1001
+ return nullptr;
1002
+ }
1003
+ return acc_ptr_ + ((out_ptr - out_ptr_) * numerator_ / denominator_);
1004
+ }
1005
+
1006
+ private:
1007
+ char* acc_ptr_ = nullptr;
1008
+ char* out_ptr_ = nullptr;
1009
+ size_t numerator_;
1010
+ size_t denominator_;
1011
+ at::DataPtr buffer_;
1012
+ };
1013
+
1014
+ template <typename scalar_t>
1015
+ int get_output_vec_size(const TensorIterator &iter) {
1016
+ int vec_size = 4;
1017
+ auto update_vec_size = [&vec_size](uint64_t n) {
1018
+ while(n % vec_size != 0) {
1019
+ vec_size /= 2;
1020
+ }
1021
+ };
1022
+
1023
+ uint64_t base_address = reinterpret_cast<uint64_t>(iter.data_ptr(iter.noutputs())) / sizeof(scalar_t);
1024
+ update_vec_size(base_address);
1025
+
1026
+ const int output_index = iter.num_reduce_dims();
1027
+ update_vec_size(iter.shape()[output_index]);
1028
+
1029
+ int j = 0;
1030
+ for(auto i : iter.strides(iter.noutputs())) {
1031
+ if (j != output_index) {
1032
+ update_vec_size(i / sizeof(scalar_t));
1033
+ }
1034
+ j++;
1035
+ }
1036
+ return vec_size;
1037
+ }
1038
+
1039
+ template<typename arg_t, typename scalar_t, int vt0, int input_vec_size=vt0>
1040
+ ReduceConfig setReduceConfig(const TensorIterator& iter){
1041
+ // Start by assuming that each thread handles a single output and all
1042
+ // the inputs for that output.
1043
+ int64_t num_outputs = iter.num_output_elements();
1044
+ int64_t inputs_per_output = iter.numel() / num_outputs;
1045
+ int input_index = iter.ntensors() - 1;
1046
+
1047
+ auto config = ReduceConfig(sizeof(arg_t), num_outputs, inputs_per_output);
1048
+
1049
+ int64_t dim0;
1050
+ int64_t dim1;
1051
+ int64_t fastest_moving_stride;
1052
+ bool reduction_on_fastest_striding_dimension;
1053
+
1054
+ if (iter.ndim() > 0) {
1055
+ // Adjust block size to map block width to fastest changing dimension of input
1056
+ // tensor. This grants the best possible memory accessing pattern, given that
1057
+ // for non-contiguous tensor with space in between, we cannot have perfect
1058
+ // memory coalescing.
1059
+ reduction_on_fastest_striding_dimension =
1060
+ (iter.num_reduce_dims() == iter.ndim()) ||
1061
+ (iter.strides(/*arg=*/input_index)[0] <
1062
+ iter.strides(/*arg=*/input_index)[iter.num_reduce_dims()]);
1063
+ // Notice that dim0 & dim1 does NOT guarantee any launch configuration here!
1064
+ // dim0 & dim1 are more like the upper bound of the block dimension. The
1065
+ // actual launch config and reduction scheme is determined by setting values
1066
+ // to `config.input_mult` and `config.output_mult`.
1067
+ // We try to max out dim1 so that we have enough threads per CTA to deliver
1068
+ // performance for larger problem size.
1069
+ if (reduction_on_fastest_striding_dimension) {
1070
+ // Map block.x to the fastest reducing dimension. It implies:
1071
+ // 1. block_x_reduce is required.
1072
+ // 2. block.y now max out to num_outputs.
1073
+ dim0 = inputs_per_output;
1074
+ dim1 = num_outputs;
1075
+ fastest_moving_stride = iter.strides(/*arg=*/input_index)[0];
1076
+ } else {
1077
+ // Map block.x to the fastest non reducing dimension. It implies:
1078
+ // 1. block_x_reduce is turned off.
1079
+ // 2. block.y now max out to inputs_per_output.
1080
+ dim0 = num_outputs;
1081
+ dim1 = inputs_per_output;
1082
+ fastest_moving_stride = iter.strides(/*arg=*/input_index)[iter.num_reduce_dims()];
1083
+ }
1084
+ } else {
1085
+ reduction_on_fastest_striding_dimension = true;
1086
+ fastest_moving_stride = sizeof(scalar_t);
1087
+ dim0 = 1;
1088
+ dim1 = 1;
1089
+ }
1090
+
1091
+ // We do vectorization to gain better memory access, there are two cases which we call
1092
+ // "vectorize along input" and "vectorize along output". Note that the "input/output"
1093
+ // here does not mean we are vectorizing load/store instructions. We always only vectorize
1094
+ // load instructions.
1095
+ //
1096
+ // Case 1: "vectorize along input"
1097
+ // This case happens when we are reducing along fastest moving dimension. In such case, threads
1098
+ // with the same threadIdx.y works on the same reduction cooperatively and will produce results
1099
+ // for the same output. In such case, values in each loaded vector always correspond to the same output.
1100
+ //
1101
+ // Case 2: "vectorize along output"
1102
+ // This case happens when the fastest moving dimension is not the dimension of reduction. In such case,
1103
+ // threads with different threadIdx.x are independent and will produce results for different outputs.
1104
+ // In such case, values in each loaded vector always correspond to different outputs.
1105
+ if (fastest_moving_stride == sizeof(scalar_t)) {
1106
+ if (reduction_on_fastest_striding_dimension && dim0 >= 128 && iter.num_reduce_dims() == 1) {
1107
+ // Case 1: "vectorize along input"
1108
+ // Note that if vt0 < ReduceConfig::vec_size, then this means the register pressure could be high, in such case,
1109
+ // we should avoid vectorization.
1110
+ config.vectorize_input = true;
1111
+ dim0 /= input_vec_size;
1112
+ } else if (!reduction_on_fastest_striding_dimension) {
1113
+ // Case 2: "vectorize along output"
1114
+ config.output_vec_size = get_output_vec_size<scalar_t>(iter);
1115
+ dim0 /= config.output_vec_size;
1116
+ }
1117
+ }
1118
+
1119
+ // Adjust block_width and block_height
1120
+ config.set_block_dimension<scalar_t>(dim0, dim1);
1121
+
1122
+ int block_width = config.block_width;
1123
+ int block_height = config.block_height;
1124
+
1125
+ if (iter.ndim() == 0 || reduction_on_fastest_striding_dimension) {
1126
+ // Split the input across lanes if the input is contiguous in the reduced
1127
+ // dimension. This will require reduction between threads using warp
1128
+ // shuffle instructions and shared memory (if block_width > C10_WARP_SIZE).
1129
+ config.input_mult[0] = config.split_input(block_width);
1130
+ } else {
1131
+ // Otherwise split the output across lanes in a warp.
1132
+ config.output_mult[0] = config.split_output(block_width);
1133
+ }
1134
+
1135
+ #ifdef USE_ROCM
1136
+ constexpr int min_values_per_thread = 128;
1137
+ #else
1138
+ constexpr int min_values_per_thread = 16;
1139
+ #endif
1140
+ constexpr int max_values_per_thread = 256;
1141
+
1142
+ const int warp_split_threshold =
1143
+ std::min<int>(block_height * 16, max_values_per_thread);
1144
+ bool split_across_warps = config.values_per_thread() >= warp_split_threshold;
1145
+ const int num_mp =
1146
+ at::cuda::getCurrentDeviceProperties()->multiProcessorCount;
1147
+
1148
+ if (split_across_warps) {
1149
+ // Divide the input across warps in a thread-block, if that leaves at least
1150
+ // 16 elements to be summed by each thread. This will require inter-warp
1151
+ // reduction using shared memory.
1152
+ config.input_mult[1] = config.split_input(block_height);
1153
+ } else {
1154
+ // Otherwise, each warp handles a separate output.
1155
+ config.output_mult[1] = config.split_output(block_height);
1156
+ }
1157
+
1158
+ int max_threads_per_mp =
1159
+ at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor;
1160
+ const int blocks_per_sm = max_threads_per_mp / config.num_threads;
1161
+ const int target_grid_size = num_mp * blocks_per_sm;
1162
+ int grid = config.grid().x;
1163
+ if (config.input_mult[1] != 0 && config.values_per_thread() >= max_values_per_thread && grid <= target_grid_size) {
1164
+ // Divide the input across thread-blocks if the amount of work per-thread
1165
+ // is large enough and the size of the output is small enough. This will
1166
+ // require a reduction using global memory.
1167
+ // If we decide to split input across blocks, as long as we can get enough
1168
+ // number of blocks (`target_grid_size`) to balance SM, we should still
1169
+ // make the number of values per thread large for best performance.
1170
+ int ctas_per_output1 = div_up(target_grid_size, grid);
1171
+ int ctas_per_output2 = div_up(config.values_per_thread(), min_values_per_thread);
1172
+ int ctas_per_output3 = div_up(config.values_per_thread(), max_values_per_thread);
1173
+ // We want the minimum of ctas_per_output1 and ctas_per_output2, so that each thread can have
1174
+ // a large number of values to deal with. But we don't want values_per_thread to be larger than
1175
+ // max_values_per_thread
1176
+ config.ctas_per_output = std::clamp<int>(ctas_per_output1, ctas_per_output3, ctas_per_output2);
1177
+ if (config.ctas_per_output > 1) {
1178
+ #ifdef USE_ROCM
1179
+ // Set min ctas value as 64. Having more reductions (i.e less values_per_thread) seems to improve perf.
1180
+ config.ctas_per_output = std::max(config.ctas_per_output, 64);
1181
+ #endif
1182
+ config.input_mult[2] = config.split_input(config.ctas_per_output);
1183
+ }
1184
+ }
1185
+ return config;
1186
+ };
1187
+
1188
+ template <typename scalar_t, typename out_scalar_t, int vt0=4, int input_vec_size=vt0, typename ops_t, typename ident_t=double>
1189
+ inline void gpu_reduce_kernel(TensorIterator& iter, const ops_t& ops, ident_t ident=0,
1190
+ AccumulationBuffer* acc_buf_ptr=nullptr, int64_t base_idx=0) {
1191
+ AT_ASSERT(iter.numel() > 0 && iter.ntensors() - iter.noutputs() == 1 && iter.noutputs() >= 1);
1192
+
1193
+ using traits = function_traits<decltype(&ops_t::reduce)>;
1194
+ using arg_t = typename traits::template arg<0>::type;
1195
+ // at::Half/at::ComplexHalf overflows easily as it's range is very small.
1196
+ // So when scalar_t and out_scalar_t are at::Half/at::ComplexHalf, we
1197
+ // set can_accumulate_in_output to False.
1198
+ static constexpr bool is_inp_out_type_half_or_chalf =
1199
+ (std::is_same_v<at::Half, scalar_t> &&
1200
+ std::is_same_v<at::Half, out_scalar_t>) ||
1201
+ (std::is_same_v<c10::complex<Half>, scalar_t> &&
1202
+ std::is_same_v<c10::complex<Half>, out_scalar_t>);
1203
+ // at::BFloat16 has lower precision and can lead to rounding errors.
1204
+ // So when scalar_t and out_scalar_t are at::BFloat16, we
1205
+ // set can_accumulate_in_output to False.
1206
+ static constexpr bool is_inp_out_type_bfloat16 =
1207
+ (std::is_same_v<at::BFloat16, scalar_t> &&
1208
+ std::is_same_v<at::BFloat16, out_scalar_t>);
1209
+ static constexpr bool can_accumulate_in_output =
1210
+ std::is_convertible_v<arg_t, out_scalar_t> &&
1211
+ !(is_inp_out_type_half_or_chalf || is_inp_out_type_bfloat16);
1212
+
1213
+ bool can_use_32bit_indexing = iter.can_use_32bit_indexing();
1214
+ std::unique_ptr<AccumulationBuffer> owned_buf_ptr;
1215
+ // The acc_buf_ptr is a shared pointer. It is create at the first entrance and
1216
+ // reused by all recursive function calls.
1217
+ if (acc_buf_ptr == NULL) {
1218
+ // acc_buf_ptr holds buffer used for accumulation among multiple sub_iter
1219
+ // when accumulation in output is not possible.
1220
+ if (!can_accumulate_in_output && !can_use_32bit_indexing) {
1221
+ int64_t output_memory_size = iter.element_size(0);
1222
+ for (int dim = 0; dim < iter.ndim(); dim++) {
1223
+ output_memory_size = std::max(output_memory_size, iter.shape()[dim] * iter.strides(0)[dim]);
1224
+ }
1225
+ output_memory_size /= iter.element_size(0); //iter.strides is in bytes
1226
+ owned_buf_ptr.reset(new AccumulationBuffer(sizeof(arg_t),
1227
+ sizeof(out_scalar_t),
1228
+ (char*) iter.data_ptr(0),
1229
+ output_memory_size * sizeof(arg_t)));
1230
+ } else {
1231
+ owned_buf_ptr.reset(new AccumulationBuffer());
1232
+ }
1233
+ acc_buf_ptr = owned_buf_ptr.get();
1234
+ }
1235
+
1236
+ if (!can_use_32bit_indexing) {
1237
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
1238
+ int64_t sub_iter_base_idx = sub_iter.view_offsets()[0];
1239
+
1240
+ gpu_reduce_kernel<scalar_t, out_scalar_t, vt0, input_vec_size>(sub_iter, ops, ident,
1241
+ acc_buf_ptr, sub_iter_base_idx);
1242
+ }
1243
+ return;
1244
+ }
1245
+
1246
+ const char* in_data = (char*)iter.data_ptr(iter.ntensors() - 1);
1247
+ char* out_data = (char*)iter.data_ptr(0);
1248
+ const auto noutputs = iter.noutputs();
1249
+ std::optional<char*> out_data_extra;
1250
+ if (noutputs > 1) {
1251
+ out_data_extra = (char*)iter.data_ptr(1);
1252
+ } else {
1253
+ out_data_extra = std::nullopt;
1254
+ }
1255
+ char* acc_data = acc_buf_ptr->get_acc_slice(out_data);
1256
+
1257
+ ReduceConfig config = setReduceConfig<arg_t, scalar_t, vt0, input_vec_size>(iter);
1258
+ at::DataPtr buffer;
1259
+ at::DataPtr semaphores;
1260
+ if (config.should_global_reduce()) {
1261
+ auto& allocator = *c10::cuda::CUDACachingAllocator::get();
1262
+ buffer = allocator.allocate(config.global_memory_size());
1263
+ semaphores = allocator.allocate(config.semaphore_size());
1264
+
1265
+ auto stream = at::cuda::getCurrentCUDAStream();
1266
+ AT_CUDA_CHECK(cudaMemsetAsync(semaphores.get(), 0, config.semaphore_size(), stream));
1267
+ }
1268
+
1269
+ AT_ASSERT(can_use_32bit_indexing);
1270
+ auto output_calc = make_output_calculator<uint32_t>(iter);
1271
+ auto input_calc = make_input_calculator<uint32_t>(iter);
1272
+ auto reduce = ReduceOp<scalar_t, ops_t, uint32_t, out_scalar_t, vt0, input_vec_size>(
1273
+ ops,
1274
+ config,
1275
+ input_calc,
1276
+ output_calc,
1277
+ in_data,
1278
+ out_data,
1279
+ out_data_extra,
1280
+ acc_data,
1281
+ buffer.get(),
1282
+ (int*)semaphores.get(),
1283
+ ident,
1284
+ noutputs,
1285
+ base_idx);
1286
+ reduce.accumulate = iter.should_accumulate();
1287
+ reduce.final_output = iter.is_final_output();
1288
+
1289
+ launch_reduce_kernel<mnt_wrapper<scalar_t>::MAX_NUM_THREADS>(config, reduce);
1290
+ }
1291
+
1292
+ //TODO this is 100 lines of almost-copy-paste, because we have to have different template args for this function
1293
+ //try unifying with gpu_reduce_kernel
1294
+ template <char const* name, typename scalar_t, typename out_scalar_t, int vt0=4, typename ident_t=double>
1295
+ inline void jitted_gpu_reduce_kernel(TensorIterator& iter, const std::string& func, ident_t ident=0,
1296
+ AccumulationBuffer* acc_buf_ptr=nullptr, int64_t base_idx=0) {
1297
+ AT_ASSERT(iter.numel() > 0 && iter.ntensors() - iter.noutputs() == 1 && iter.noutputs() >= 1);
1298
+
1299
+ //TODO - this will be different for more complicated reductions, but for now reductions using
1300
+ //func_wrapper all have arg_t = opmath
1301
+ using arg_t = at::opmath_type<scalar_t>;
1302
+ // at::Half/at::ComplexHalf overflows easily as it's range is very small.
1303
+ // So when scalar_t and out_scalar_t are at::Half/at::ComplexHalf, we
1304
+ // set can_accumulate_in_output to False.
1305
+ static constexpr bool is_inp_out_type_half_or_chalf =
1306
+ (std::is_same_v<at::Half, scalar_t> &&
1307
+ std::is_same_v<at::Half, out_scalar_t> ) ||
1308
+ (std::is_same_v<c10::complex<Half>, scalar_t> &&
1309
+ std::is_same_v<c10::complex<Half>, out_scalar_t>);
1310
+ // at::BFloat16 has lower precision and can lead to rounding errors.
1311
+ // So when scalar_t and out_scalar_t are at::BFloat16, we
1312
+ // set can_accumulate_in_output to False.
1313
+ static constexpr bool is_inp_out_type_bfloat16 =
1314
+ (std::is_same_v<at::BFloat16, scalar_t> &&
1315
+ std::is_same_v<at::BFloat16, out_scalar_t>);
1316
+ static constexpr bool can_accumulate_in_output =
1317
+ std::is_convertible_v<arg_t, out_scalar_t> &&
1318
+ !(is_inp_out_type_half_or_chalf || is_inp_out_type_bfloat16);
1319
+
1320
+ bool can_use_32bit_indexing = iter.can_use_32bit_indexing();
1321
+ std::unique_ptr<AccumulationBuffer> owned_buf_ptr;
1322
+
1323
+ // The acc_buf_ptr is a shared pointer. It is create at the first entrance and
1324
+ // reused by all recursive function calls.
1325
+ if (acc_buf_ptr == NULL) {
1326
+ // acc_buf_ptr holds buffer used for accumulation among multiple sub_iter
1327
+ // when accumulation in output is not possible.
1328
+ if (!can_accumulate_in_output && !can_use_32bit_indexing) {
1329
+ int64_t output_memory_size = iter.element_size(0);
1330
+ for (int dim = 0; dim < iter.ndim(); dim++) {
1331
+ output_memory_size = std::max(output_memory_size, iter.shape()[dim] * iter.strides(0)[dim]);
1332
+ }
1333
+ output_memory_size /= iter.element_size(0); //iter.strides is in bytes
1334
+ owned_buf_ptr.reset(new AccumulationBuffer(sizeof(out_scalar_t), //TODO
1335
+ sizeof(out_scalar_t),
1336
+ (char*) iter.data_ptr(0),
1337
+ output_memory_size * sizeof(out_scalar_t))); //TODO
1338
+ } else {
1339
+ owned_buf_ptr.reset(new AccumulationBuffer());
1340
+ }
1341
+ acc_buf_ptr = owned_buf_ptr.get();
1342
+ }
1343
+
1344
+ if (!can_use_32bit_indexing) {
1345
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
1346
+ int64_t sub_iter_base_idx = sub_iter.view_offsets()[0];
1347
+
1348
+ jitted_gpu_reduce_kernel<name, scalar_t, out_scalar_t, vt0>(sub_iter, func, ident,
1349
+ acc_buf_ptr, sub_iter_base_idx);
1350
+ }
1351
+ return;
1352
+ }
1353
+
1354
+ //TODO - for now we support a single input, we may be able to relax this constraint
1355
+ const char* in_data = (char*)iter.data_ptr(iter.ntensors() - 1);
1356
+ char* out_data = (char*)iter.data_ptr(0);
1357
+ const auto noutputs = iter.noutputs();
1358
+ std::optional<char*> out_data_extra;
1359
+ if (noutputs > 1) {
1360
+ out_data_extra = (char*)iter.data_ptr(1);
1361
+ } else {
1362
+ out_data_extra = std::nullopt;
1363
+ }
1364
+ char* acc_data = acc_buf_ptr->get_acc_slice(out_data);
1365
+
1366
+ ReduceConfig config = setReduceConfig<arg_t, scalar_t, vt0>(iter);
1367
+
1368
+ at::DataPtr buffer;
1369
+ at::DataPtr semaphores;
1370
+ if (config.should_global_reduce()) {
1371
+ auto& allocator = *c10::cuda::CUDACachingAllocator::get();
1372
+ buffer = allocator.allocate(config.global_memory_size());
1373
+ semaphores = allocator.allocate(config.semaphore_size());
1374
+
1375
+ auto stream = at::cuda::getCurrentCUDAStream();
1376
+ AT_CUDA_CHECK(cudaMemsetAsync(semaphores.get(), 0, config.semaphore_size(), stream));
1377
+ }
1378
+
1379
+ AT_ASSERT(can_use_32bit_indexing);
1380
+ auto output_calc = make_output_calculator<uint32_t>(iter);
1381
+ auto input_calc = make_input_calculator<uint32_t>(iter);
1382
+ auto reduce = ReduceJitOp<scalar_t, out_scalar_t>(
1383
+ config,
1384
+ input_calc,
1385
+ output_calc,
1386
+ in_data,
1387
+ out_data,
1388
+ out_data_extra,
1389
+ acc_data,
1390
+ buffer.get(),
1391
+ (int*)semaphores.get(),
1392
+ ident,
1393
+ noutputs,
1394
+ base_idx);
1395
+ reduce.accumulate = iter.should_accumulate();
1396
+ reduce.final_output = iter.is_final_output();
1397
+
1398
+ constexpr int nInputs = 1;
1399
+ constexpr int nOutputs = 1;
1400
+ static auto desc = at::cuda::jit::make_kernel_descriptor<
1401
+ out_scalar_t, scalar_t>(name, func, nInputs, nOutputs);
1402
+
1403
+ static std::mutex jiterator_mutex;
1404
+ static std::vector<std::array<at::cuda::jit::NvrtcFunction, 3>> fn_cache(c10::cuda::device_count());
1405
+ auto &cache = fn_cache[iter.device().index()];
1406
+
1407
+ launch_jitted_reduce_kernel(
1408
+ jiterator_mutex, cache, desc, vt0, config, &reduce);
1409
+ }
1410
+
1411
+ } // namespace at::native
1412
+
1413
+ #else
1414
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1415
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ReduceOps.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+
3
+ namespace at {
4
+ struct TensorIterator;
5
+ }
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at::native {
12
+
13
+ void norm_launch_kernel(TensorIterator &iter, double val);
14
+ void powsum_launch_kernel(TensorIterator &iter, double val);
15
+ void min_launch_kernel(TensorIterator &iter);
16
+ void max_launch_kernel(TensorIterator &iter);
17
+ void aminmax_launch_kernel(TensorIterator &iter);
18
+ void min_all_launch_kernel(TensorIterator &iter);
19
+ void max_all_launch_kernel(TensorIterator &iter);
20
+ void aminmax_allreduce_launch_kernel(TensorIterator &iter);
21
+
22
+ } // namespace at::native
23
+
24
+ #else
25
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
26
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Resize.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/EmptyTensor.h>
5
+ #include <ATen/native/ResizeCommon.h>
6
+
7
+ #include <c10/cuda/CUDAGuard.h>
8
+
9
+ namespace at::native {
10
+
11
+ TORCH_CUDA_CPP_API void resize_bytes_cuda(StorageImpl* storage, size_t size_bytes);
12
+ TORCH_CUDA_CPP_API void resize_bytes_cuda_with_addr(
13
+ StorageImpl* storage,
14
+ size_t size_bytes,
15
+ void* addr);
16
+
17
+ static inline void maybe_resize_storage_cuda(TensorImpl* self, size_t new_size_bytes) {
18
+ // It does not make sense to try to resize a storage
19
+ // to hold 0 elements, and this can break
20
+ // if storage_offset is positive but
21
+ // new_size is 0, so just bail in that case
22
+ // (same comment is in Resize.h)
23
+ if (self->numel() == 0) {
24
+ return;
25
+ }
26
+
27
+ const Storage &storage = self->unsafe_storage();
28
+ TORCH_CHECK(storage, "Tensor: invalid null storage");
29
+ if (new_size_bytes > storage.nbytes()) {
30
+ resize_bytes_cuda(storage.unsafeGetStorageImpl(), new_size_bytes);
31
+ }
32
+ }
33
+
34
+ inline TensorImpl* resize_impl_cuda_(
35
+ TensorImpl* self,
36
+ IntArrayRef size,
37
+ at::OptionalIntArrayRef stride) {
38
+ if (self->sizes() == size && (!stride || self->strides() == stride)) {
39
+ return self;
40
+ }
41
+ const auto itemsize = self->dtype().itemsize();
42
+ const auto storage_offset = self->storage_offset();
43
+ size_t storage_size = 1;
44
+ if (stride) {
45
+ self->set_sizes_and_strides(size, *stride);
46
+ storage_size = at::detail::computeStorageNbytes(
47
+ size, *stride, itemsize, storage_offset);
48
+ } else {
49
+ self->set_sizes_contiguous(size);
50
+ storage_size = at::detail::computeStorageNbytesContiguous(
51
+ size, itemsize, storage_offset);
52
+ }
53
+ maybe_resize_storage_cuda(self, storage_size);
54
+
55
+ return self;
56
+ }
57
+
58
+ }
59
+
60
+ #else
61
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
62
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/RowwiseScaledMM.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <optional>
5
+
6
+ namespace at::cuda::detail {
7
+ TORCH_API void f8f8bf16_rowwise(
8
+ at::Tensor XQ, // FP8
9
+ at::Tensor WQ, // FP8
10
+ at::Tensor x_scale, // FP32
11
+ at::Tensor w_scale, // FP32
12
+ std::optional<at::Tensor> bias, // BF16
13
+ bool use_fast_accum,
14
+ at::Tensor& out);
15
+ } // namespace at::cuda::detail
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.12/site-packages/torch/include/ATen/native/cuda/ScaledBlasDeviceUtils.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/macros/Export.h>
5
+
6
+ namespace at::native::scaled {
7
+
8
+ // True if the current device supports torch._scaled_mm / torch._scaled_grouped_mm.
9
+ // On CUDA: with no flags, allows SM >= 9.0 or SM 8.9 (Ada/L4). With sm90_only
10
+ // and/or sm100_only set, checks for a matching SM major version (OR semantics
11
+ // if both are set). On ROCm, sm90_only and sm100_only are ignored.
12
+ TORCH_CUDA_CPP_API
13
+ bool scaled_mm_arch_allowed(bool sm90_only = false, bool sm100_only = false);
14
+
15
+ } // namespace at::native::scaled
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.12/site-packages/torch/include/ATen/native/cuda/ScaledGroupMM.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <optional>
5
+
6
+ namespace at::cuda::detail {
7
+ TORCH_API void f8f8bf16_grouped_mm(
8
+ at::Tensor mat_a, // FP8
9
+ at::Tensor mat_b, // FP8
10
+ at::Tensor scale_a, // FP32
11
+ at::Tensor scale_b, // FP32
12
+ std::optional<at::Tensor> offs,
13
+ std::optional<at::Tensor> bias, // BF16
14
+ bool use_fast_accum,
15
+ at::Tensor& out);
16
+ } // namespace at::cuda::detail
17
+
18
+ #else
19
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
20
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScanKernels.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+
8
+ namespace native {
9
+
10
+ // NOTE: these functions require output tensors to be contiguous
11
+ void launch_cummax_cuda_kernel(const TensorBase& self, const TensorBase& values,
12
+ const TensorBase& indices, int64_t dim);
13
+ void launch_cummin_cuda_kernel(const TensorBase& self, const TensorBase& values,
14
+ const TensorBase& indices, int64_t dim);
15
+ void launch_logcumsumexp_cuda_kernel(const TensorBase& result, const TensorBase& self, int64_t dim);
16
+ void launch_cumsum_cuda_kernel(const TensorBase& result, const TensorBase& self, int64_t dim);
17
+ void launch_cumprod_cuda_kernel(const TensorBase& result, const TensorBase& self, int64_t dim);
18
+
19
+ }} // namespace at::native
20
+
21
+ #else
22
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
23
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/ScanUtils.cuh ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/NumericUtils.h>
4
+ #include <ATen/core/TensorBase.h>
5
+ #include <ATen/cuda/cub.cuh>
6
+ #include <ATen/cuda/CUDAContext.h>
7
+
8
+ #include <c10/util/Load.h>
9
+ #include <limits>
10
+ #include <cmath>
11
+
12
+ namespace at::native {
13
+
14
+ template <typename integer>
15
+ constexpr inline integer ceil_div(integer n, integer m) {
16
+ return (n + m - 1) / m;
17
+ }
18
+
19
+ template <typename integer>
20
+ constexpr inline integer get_log_num_threads_x_inner_scan(integer num_rows, integer row_size) {
21
+ integer log_num_threads_x = 0;
22
+ integer log_num_threads_y = 0;
23
+ while (((integer)1 << log_num_threads_x) < row_size) {
24
+ ++log_num_threads_x;
25
+ }
26
+ while (((integer)1 << log_num_threads_y) < num_rows) {
27
+ ++log_num_threads_y;
28
+ }
29
+ // we want to keep the ratio between the x-threads and y-threads about the same as
30
+ // the ratio between the row_size and num_rows, but the total number of threads in
31
+ // a block should be about 512
32
+ integer diff = log_num_threads_x - log_num_threads_y;
33
+ // 9 is from log2(512)
34
+ log_num_threads_x = ((integer)9 + diff) / (integer)2;
35
+ // I found that in having larger log_num_threads_x can give significant speed up in some cases,
36
+ // but detrimental in another case, so just keep the lower bound to be log2(16) == 4 to make it
37
+ // similar to the previous implementation
38
+ // Keeping the upper bound to be log2(512) == 9 as the maximum number of threads in a block.
39
+ log_num_threads_x = std::clamp(log_num_threads_x, (integer)4, (integer)9);
40
+ return log_num_threads_x;
41
+ }
42
+
43
+ template<typename scalar_t, typename idx_t, typename BinaryOperation>
44
+ __device__ void binary_op_update(const scalar_t lhs, scalar_t& rhs, const idx_t lhs_idx, idx_t& rhs_idx, BinaryOperation binary_op) {
45
+ if(!at::_isnan(rhs) && (at::_isnan(lhs) || !binary_op(rhs, lhs))) {
46
+ rhs = lhs;
47
+ rhs_idx = lhs_idx;
48
+ }
49
+ }
50
+ /* Perform an inclusive scan along the innermost dimension of a tensor.
51
+ *
52
+ * - num_rows is the size of the flattened outer dimensions;
53
+ * - row_size is the size of the innermost dimension;
54
+ *
55
+ * The outer dimensions of the tensor are considered as a single dimension, i.e. the tensor is
56
+ * considered as having 'num_rows' rows of size 'row_size'.
57
+ * Each thread block processes one or more sets of contiguous rows (processing multiple rows
58
+ * per thread block is quicker than processing a single row, especially for short rows).
59
+ */
60
+ template<typename scalar_t, class BinaryFunction>
61
+ __global__ void tensor_kernel_scan_innermost_dim_with_indices(const scalar_t *self_, scalar_t *values_, int64_t *indices_,
62
+ int num_rows, int row_size,
63
+ const uint32_t num_threads, const uint32_t log_num_threads_x,
64
+ scalar_t init, BinaryFunction binary_op) {
65
+ // dynamic memory allocation for vbuf and ibuf
66
+ alignas(sizeof(double)) extern __shared__ char buf[];
67
+ scalar_t* vbuf = reinterpret_cast<scalar_t*>(buf); // the size is num_threads * 2
68
+ int64_t* ibuf = reinterpret_cast<int64_t*>(vbuf + num_threads * 2);
69
+ const uint32_t num_threads_x = 1 << log_num_threads_x;
70
+ scalar_t* row_buf = vbuf + 2 * num_threads_x * threadIdx.y;
71
+ int64_t* row_idx_buf = ibuf + 2 * num_threads_x * threadIdx.y;
72
+
73
+ for (int block_row = blockIdx.x * blockDim.y;
74
+ block_row < num_rows;
75
+ block_row += blockDim.y * gridDim.x) {
76
+ int row = block_row + threadIdx.y;
77
+ const scalar_t *row_self = self_ + row * row_size;
78
+ scalar_t *row_values = values_ + row * row_size;
79
+ int64_t *row_indices = indices_ + row * row_size;
80
+ scalar_t block_total = init;
81
+ int64_t block_idx_final = 0;
82
+ const bool row_exists = row < num_rows;
83
+ // Perform scan on one block at a time, keeping track of the total value of
84
+ // all blocks processed so far.
85
+ for (int block_col = 0; block_col < row_size; block_col += 2 * num_threads_x) {
86
+ // Load data into shared memory (two values per thread).
87
+ int col1 = block_col + threadIdx.x;
88
+ int col2 = block_col + num_threads_x + threadIdx.x;
89
+ if (row_exists) {
90
+ if (col1 < row_size) {
91
+ row_buf[threadIdx.x] = c10::load(&row_self[col1]);
92
+ row_idx_buf[threadIdx.x] = col1;
93
+ } else {
94
+ row_buf[threadIdx.x] = init;
95
+ // No need to set the index here as the value in init will never be selected
96
+ }
97
+
98
+ if (col2 < row_size) {
99
+ row_buf[num_threads_x + threadIdx.x] = c10::load(&row_self[col2]);
100
+ row_idx_buf[num_threads_x + threadIdx.x] = col2;
101
+ } else {
102
+ row_buf[num_threads_x + threadIdx.x] = init;
103
+ // No need to set the index here as the value in init will never be selected
104
+ }
105
+
106
+ // Add the total value of all previous blocks to the first value of this block.
107
+ if (threadIdx.x == 0) {
108
+ binary_op_update(block_total, row_buf[0], block_idx_final, row_idx_buf[0], binary_op);
109
+ }
110
+ }
111
+ __syncthreads();
112
+
113
+ // Parallel reduction with Sklansky method. The diagram can be seen on this paper:
114
+ // https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back
115
+ for (uint32_t s = 1; s <= num_threads_x; s <<= 1) {
116
+ if (row_exists) {
117
+ uint32_t a = (threadIdx.x / s) * (2 * s) + s;
118
+ uint32_t ti = a + (threadIdx.x % s);
119
+ uint32_t si = a - 1;
120
+ binary_op_update(row_buf[si], row_buf[ti], row_idx_buf[si], row_idx_buf[ti], binary_op);
121
+ }
122
+ __syncthreads();
123
+ }
124
+
125
+ // Write back to output.
126
+ if (row_exists) {
127
+ if (col1 < row_size){
128
+ row_values[col1] = row_buf[threadIdx.x];
129
+ row_indices[col1] = row_idx_buf[threadIdx.x];
130
+ }
131
+ if (col2 < row_size) {
132
+ row_values[col2] = row_buf[num_threads_x + threadIdx.x];
133
+ row_indices[col2] = row_idx_buf[num_threads_x + threadIdx.x];
134
+ }
135
+ }
136
+ block_total = row_buf[2 * num_threads_x - 1];
137
+ block_idx_final = row_idx_buf[2 * num_threads_x - 1];
138
+ __syncthreads();
139
+ }
140
+ }
141
+ }
142
+
143
+ /* Perform an inclusive scan along an outer dimension of a tensor.
144
+ *
145
+ * - num_orows is the size of the flattened outer dimensions;
146
+ * - num_irows is the size of the flattened inner dimensions;
147
+ * - row_size is the size of the dimension along which to compute the variance;
148
+ *
149
+ * The dimensions to the outside and inside of the specified dimension are considered as flattened.
150
+ * Thread blocks with the same blockIdx.y process an "outer row" (i.e. an element of the flattened
151
+ * outer dimensions, which contains several "inner rows").
152
+ * Each thread processes a single inner row at a time.
153
+ */
154
+ template<typename scalar_t, class BinaryFunction>
155
+ __global__ void tensor_kernel_scan_outer_dim_with_indices(const scalar_t *self_, scalar_t *values_, int64_t *indices_,
156
+ const uint32_t num_orows, const uint32_t num_irows, const uint32_t row_size, scalar_t init, BinaryFunction binary_op) {
157
+ for (uint32_t orow = blockIdx.x; orow < num_orows; orow += gridDim.x) {
158
+ for (uint32_t irow = blockIdx.y * blockDim.x + threadIdx.x; irow < num_irows; irow += gridDim.y * blockDim.x) {
159
+ const scalar_t *self = self_ + orow * row_size * num_irows + irow;
160
+ scalar_t *values = values_ + orow * row_size * num_irows + irow;
161
+ int64_t *indices = indices_ + orow * row_size * num_irows + irow;
162
+ scalar_t out = init;
163
+ int64_t out_idx = 0;
164
+
165
+ for (auto col = decltype(row_size){0}; col < row_size; ++col) {
166
+ const auto val = c10::load(self);
167
+ if(at::_isnan(val) || (!at::_isnan(out) && binary_op(val, out))) {
168
+ out = val;
169
+ out_idx = col;
170
+ }
171
+ *values = out;
172
+ *indices = out_idx;
173
+ self += num_irows;
174
+ values += num_irows;
175
+ indices += num_irows;
176
+ }
177
+ }
178
+ }
179
+ }
180
+
181
+ inline void check_fits_in_unsigned(int64_t val, const char* name) {
182
+ constexpr auto umax = std::numeric_limits<uint32_t>::max();
183
+ TORCH_CHECK(
184
+ val >= 0 && val <= umax, name, " must fit in a 32-bit uint32_t value");
185
+ }
186
+
187
+
188
+ template<typename scalar_t, class BinaryFunction>
189
+ __host__ void scan_outer_dim_with_indices(
190
+ const TensorBase& self, const TensorBase& values, const TensorBase& indices,
191
+ int dim, scalar_t init, BinaryFunction binary_op) {
192
+ int64_t row_size = self.size(dim);
193
+ auto sizes = self.sizes();
194
+
195
+ // Treat all outer dimensions (i.e. dim_ < dim) as one.
196
+ const int64_t num_orows = c10::multiply_integers(sizes.begin(), sizes.begin() + dim);
197
+
198
+ // Treat all inner dimensions (i.e. dim > dimension) as one.
199
+ const int64_t num_irows = c10::multiply_integers(sizes.begin() + dim + 1, sizes.end());
200
+ //for performance reasons, cuda kernels use uint32_t for loops over irows, orows and row,
201
+ //make sure that input is not bigger than supported by uint32_t
202
+ check_fits_in_unsigned(num_irows, "num_irows");
203
+ check_fits_in_unsigned(num_orows, "num_orows");
204
+ check_fits_in_unsigned(row_size, "row_size");
205
+
206
+
207
+ dim3 threads(std::min(512, int(num_irows)));
208
+ int64_t maxGridDim = at::cuda::getCurrentDeviceProperties()->maxGridSize[1];
209
+ dim3 grid(std::min(maxGridDim, num_orows), std::min(maxGridDim, ceil_div(num_irows, int64_t{threads.x})));
210
+ tensor_kernel_scan_outer_dim_with_indices<scalar_t><<<grid, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
211
+ self.const_data_ptr<scalar_t>(), values.mutable_data_ptr<scalar_t>(), indices.mutable_data_ptr<int64_t>(),
212
+ num_orows, num_irows, row_size, init, binary_op);
213
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
214
+ }
215
+
216
+ template <typename scalar_t, class BinaryFunction>
217
+ __host__ void scan_innermost_dim_with_indices(
218
+ const TensorBase& self, const TensorBase& values, const TensorBase& indices,
219
+ scalar_t init, BinaryFunction binary_op) {
220
+ int ndim = self.dim();
221
+ // Treat all outer dimensions as a single dimension.
222
+ int row_size = self.size(ndim - 1);
223
+ int num_rows = self.numel() / row_size;
224
+
225
+ // assuming max_num_threads per block is 512
226
+ const uint32_t num_threads = 512;
227
+ const uint32_t log_num_threads_x = get_log_num_threads_x_inner_scan<uint32_t>(num_rows, row_size);
228
+ const uint32_t num_threads_x = (1 << log_num_threads_x);
229
+ const uint32_t num_threads_y = num_threads / num_threads_x;
230
+ dim3 threads(num_threads_x, num_threads_y);
231
+ dim3 grid(std::min(at::cuda::getCurrentDeviceProperties()->maxGridSize[0], ceil_div(num_rows, int(threads.y))));
232
+
233
+ const uint32_t mem_size = 2 * num_threads * (sizeof(scalar_t) + sizeof(int64_t));
234
+ tensor_kernel_scan_innermost_dim_with_indices<scalar_t><<<grid, threads, mem_size,
235
+ at::cuda::getCurrentCUDAStream()>>>(
236
+ self.const_data_ptr<scalar_t>(), values.mutable_data_ptr<scalar_t>(), indices.mutable_data_ptr<int64_t>(),
237
+ num_rows, row_size, num_threads, log_num_threads_x, init, binary_op);
238
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
239
+ }
240
+
241
+ template<typename scalar_t, typename BinaryFunction>
242
+ void scan_dim_with_indices(const TensorBase& self, const TensorBase& values, const TensorBase& indices, //int64_t dim) {
243
+ int64_t dim, scalar_t init, BinaryFunction binary_op) {
244
+ int ndim = self.dim();
245
+ auto self_ = self.expect_contiguous();
246
+ TORCH_INTERNAL_ASSERT(values.is_contiguous() && indices.is_contiguous());
247
+ if (dim == ndim - 1) {
248
+ scan_innermost_dim_with_indices<scalar_t>(*self_, values, indices, init, binary_op);
249
+ } else {
250
+ scan_outer_dim_with_indices<scalar_t>(*self_, values, indices, dim, init, binary_op);
251
+ }
252
+ }
253
+
254
+ // TODO: The implementation of `tensor_kernel_scan_outer_dim` and
255
+ // `tensor_kernel_scan_innermost_dim` is similar to
256
+ // `tensor_kernel_scan_outer_dim_with_indices`
257
+ // `tensor_kernel_scan_outer_dim_with_indices` and should be refactored to
258
+ // remove the duplication.
259
+
260
+ /* Perform an inclusive scan along an outer dimension of a tensor.
261
+ *
262
+ * - num_orows is the size of the flattened outer dimensions;
263
+ * - num_irows is the size of the flattened inner dimensions;
264
+ * - row_size is the size of the dimension along which to scan;
265
+ *
266
+ * The dimensions to the outside and inside of the specified dimension are considered as flattened.
267
+ * Thread blocks with the same blockIdx.y process an "outer row" (i.e. an element of the flattened
268
+ * outer dimensions, which contains several "inner rows").
269
+ * Each thread processes a single inner row at a time.
270
+ */
271
+ template<typename scalar_t, typename index_t, class BinaryOp>
272
+ __global__ void tensor_kernel_scan_outer_dim(scalar_t *tgt_, const scalar_t *src_,
273
+ const uint32_t num_orows, const uint32_t num_irows, const uint32_t row_size,
274
+ const scalar_t init, BinaryOp binary_op)
275
+ {
276
+ for (uint32_t orow = blockIdx.x; orow < num_orows; orow += gridDim.x) {
277
+ for (uint32_t irow = blockIdx.y * blockDim.x + threadIdx.x; irow < num_irows; irow += gridDim.y * blockDim.x) {
278
+ const scalar_t *src = src_ + static_cast<index_t>(orow) * row_size * num_irows + irow;
279
+ scalar_t *tgt = tgt_ + (index_t) orow * row_size * num_irows + irow;
280
+ scalar_t acc = init;
281
+
282
+ for (uint32_t col = 0; col < row_size; ++col) {
283
+ acc = binary_op(acc, c10::load(src));
284
+ *tgt = acc;
285
+
286
+ src += num_irows;
287
+ tgt += num_irows;
288
+ }
289
+ }
290
+ }
291
+ }
292
+
293
+ /* Perform an inclusive scan along the innermost dimension of a tensor.
294
+ *
295
+ * - num_rows is the size of the flattened outer dimensions;
296
+ * - row_size is the size of the innermost dimension;
297
+ *
298
+ * The outer dimensions of the tensor are considered as a single dimension, i.e. the tensor is
299
+ * considered as having 'num_rows' rows of size 'row_size'.
300
+ * Each thread block processes one or more sets of contiguous rows (processing multiple rows
301
+ * per thread block is quicker than processing a single row, especially for short rows).
302
+ */
303
+ template<typename T, typename index_t, class BinaryFunction>
304
+ __device__ void tensor_kernel_scan_innermost_dim_impl(T* row_buf, T *tgt_, const T *src_,
305
+ const uint32_t num_rows, const uint32_t row_size,
306
+ const uint32_t log_num_threads_x,
307
+ T init, BinaryFunction binary_op){
308
+ const index_t num_threads_x = 1 << log_num_threads_x;
309
+ for (index_t block_row = blockIdx.x * (index_t) blockDim.y;
310
+ block_row < num_rows;
311
+ block_row += blockDim.y * gridDim.x) {
312
+ index_t row = block_row + (index_t) threadIdx.y;
313
+ T block_total = init;
314
+
315
+ const T *row_src = src_ + row * row_size;
316
+ T *row_tgt = tgt_ + row * row_size;
317
+ const bool row_exists = row < num_rows;
318
+
319
+ // Perform scan on one block at a time, keeping track of the total value of
320
+ // all blocks processed so far.
321
+ for (index_t block_col = 0; block_col < row_size; block_col += 2 * num_threads_x) {
322
+ // Load data into shared memory (two values per thread).
323
+ index_t col1 = block_col + (index_t) threadIdx.x;
324
+ index_t col2 = block_col + num_threads_x + (index_t) threadIdx.x;
325
+ if (row_exists) {
326
+ if (col1 < row_size) {
327
+ row_buf[threadIdx.x] = row_src[col1];
328
+ } else {
329
+ row_buf[threadIdx.x] = init;
330
+ }
331
+
332
+ if (col2 < row_size) {
333
+ row_buf[num_threads_x + threadIdx.x] = row_src[col2];
334
+ } else {
335
+ row_buf[num_threads_x + threadIdx.x] = init;
336
+ }
337
+
338
+ // Add the total value of all previous blocks to the first value of this block.
339
+ if (threadIdx.x == 0) {
340
+ row_buf[0] = binary_op(row_buf[0], block_total);
341
+ }
342
+ }
343
+ __syncthreads();
344
+
345
+ // Parallel reduction with Sklansky method. The diagram can be seen on this paper:
346
+ // https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back
347
+ for (int m = 0; m <= log_num_threads_x; ++m) {
348
+ if (row_exists) {
349
+ index_t s = 1 << m; // s = 2 ^ m
350
+ auto a = static_cast<index_t>((threadIdx.x >> m) << (m + 1)) | s; // a = (threadIdx.x / s) * (2 * s) + s
351
+ index_t ti = a + (threadIdx.x % s);
352
+ index_t si = a - 1;
353
+ row_buf[ti] = binary_op(row_buf[ti], row_buf[si]);
354
+ }
355
+ __syncthreads();
356
+ }
357
+
358
+ // Write back to output.
359
+ if (row_exists) {
360
+ if (col1 < row_size) row_tgt[col1] = row_buf[threadIdx.x];
361
+ if (col2 < row_size) row_tgt[col2] = row_buf[num_threads_x + threadIdx.x];
362
+ }
363
+ block_total = row_buf[2 * num_threads_x - 1];
364
+ __syncthreads();
365
+ }
366
+ }
367
+ }
368
+
369
+ template <
370
+ typename T,
371
+ class BinaryFunction>
372
+ __global__ void tensor_kernel_scan_innermost_dim(
373
+ T* tgt_,
374
+ const T* src_,
375
+ const uint32_t num_rows,
376
+ const uint32_t row_size,
377
+ const uint32_t log_num_threads_x,
378
+ T init,
379
+ BinaryFunction binary_op) {
380
+ alignas(sizeof(double)) extern __shared__ char sbuf[];
381
+ T* sbuf2 = reinterpret_cast<T*>(sbuf);
382
+ const uint32_t num_threads_x = 1 << log_num_threads_x;
383
+ T* row_buf = reinterpret_cast<T*>(sbuf2 + num_threads_x * 2 * threadIdx.y);
384
+ if (num_rows * (size_t) row_size <= UINT_MAX) {
385
+ tensor_kernel_scan_innermost_dim_impl<T, uint32_t>(
386
+ row_buf, tgt_, src_, num_rows, row_size, log_num_threads_x, init, binary_op);
387
+ } else {
388
+ tensor_kernel_scan_innermost_dim_impl<T, size_t>(
389
+ row_buf, tgt_, src_, num_rows, row_size, log_num_threads_x, init, binary_op);
390
+ }
391
+ }
392
+
393
+
394
+ template<typename scalar_t, class BinaryFunction>
395
+ __host__ void scan_outer_dim(const TensorBase& self, const TensorBase& result,
396
+ int dim, scalar_t init, BinaryFunction binary_op) {
397
+ const int64_t row_size = self.size(dim);
398
+ auto sizes = self.sizes();
399
+
400
+ // Treat all outer dimensions (i.e. dim_ < dim) as one.
401
+ const int64_t num_orows = c10::multiply_integers(sizes.begin(), sizes.begin() + dim);
402
+
403
+ // Treat all inner dimensions (i.e. dim > dimension) as one.
404
+ const int64_t num_irows = c10::multiply_integers(sizes.begin() + dim + 1, sizes.end());
405
+
406
+ dim3 threads(std::min(512, int(num_irows)));
407
+ int64_t maxGridDim = at::cuda::getCurrentDeviceProperties()->maxGridSize[1];
408
+ dim3 grid(std::min(maxGridDim, num_orows), std::min(maxGridDim, ceil_div(num_irows, int64_t{threads.x})));
409
+
410
+ check_fits_in_unsigned(num_irows, "num_irows");
411
+ check_fits_in_unsigned(num_orows, "num_orows");
412
+ check_fits_in_unsigned(row_size, "row_size");
413
+ if (static_cast<size_t>(num_irows) * num_orows * row_size <= UINT_MAX) {
414
+ tensor_kernel_scan_outer_dim<scalar_t, uint32_t><<<grid, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
415
+ result.mutable_data_ptr<scalar_t>(), self.const_data_ptr<scalar_t>(),
416
+ num_orows, num_irows, row_size, init, binary_op);
417
+ } else {
418
+ tensor_kernel_scan_outer_dim<scalar_t, size_t><<<grid, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
419
+ result.mutable_data_ptr<scalar_t>(), self.const_data_ptr<scalar_t>(),
420
+ num_orows, num_irows, row_size, init, binary_op);
421
+ }
422
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
423
+ }
424
+
425
+ template <typename scalar_t, class BinaryFunction>
426
+ void scan_innermost_dim(const TensorBase& self, const TensorBase& result,
427
+ scalar_t init, BinaryFunction binary_op) {
428
+ int64_t ndim = self.dim();
429
+ // Treat all outer dimensions as a single dimension.
430
+ int64_t row_size = self.size(ndim - 1);
431
+ int64_t num_rows = self.numel() / row_size;
432
+
433
+ // assuming max_num_threads per block is 512
434
+ const uint32_t num_threads = 512;
435
+ const uint32_t log_num_threads_x = get_log_num_threads_x_inner_scan<uint32_t>(num_rows, row_size);
436
+ const uint32_t num_threads_x = (1 << log_num_threads_x);
437
+ const uint32_t num_threads_y = num_threads / num_threads_x;
438
+ dim3 threads(num_threads_x, num_threads_y);
439
+ int64_t maxGridDim = at::cuda::getCurrentDeviceProperties()->maxGridSize[0];
440
+ dim3 grid(std::min(maxGridDim, ceil_div(num_rows, int64_t{threads.y})));
441
+
442
+ check_fits_in_unsigned(num_rows, "Number of rows (self.numel()/self.size(self.dim()-1))");
443
+ check_fits_in_unsigned(row_size, "row_size");
444
+
445
+ tensor_kernel_scan_innermost_dim<scalar_t><<<grid, threads, num_threads * 2 * sizeof(scalar_t),
446
+ at::cuda::getCurrentCUDAStream()>>>(
447
+ result.mutable_data_ptr<scalar_t>(), self.const_data_ptr<scalar_t>(),
448
+ num_rows, row_size, log_num_threads_x, init, binary_op);
449
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
450
+ }
451
+
452
+ template<typename scalar_t, typename BinaryFunction>
453
+ void scan_dim(const TensorBase& self, const TensorBase& result,
454
+ int64_t dim, scalar_t init, BinaryFunction binary_op) {
455
+ int ndim = self.dim();
456
+ auto self_ = self.expect_contiguous();
457
+ TORCH_INTERNAL_ASSERT(result.is_contiguous());
458
+
459
+ if (self.numel() == self.size(dim)) {
460
+ if constexpr (std::is_same_v<BinaryFunction, std::plus<scalar_t>>) {
461
+ if (C10_UNLIKELY(at::globalContext().deterministicAlgorithms()) && (self.is_floating_point() || self.is_complex())) {
462
+ cuda::cub::inclusive_deterministic_scan(self_->const_data_ptr<scalar_t>(), result.mutable_data_ptr<scalar_t>(), binary_op, self.numel());
463
+ } else {
464
+ cuda::cub::inclusive_scan(self_->const_data_ptr<scalar_t>(), result.mutable_data_ptr<scalar_t>(), binary_op, self.numel());
465
+ }
466
+ } else {
467
+ cuda::cub::inclusive_scan(self_->const_data_ptr<scalar_t>(), result.mutable_data_ptr<scalar_t>(), binary_op, self.numel());
468
+ }
469
+ } else if (dim == ndim - 1) {
470
+ scan_innermost_dim<scalar_t>(*self_, result, init, binary_op);
471
+ } else {
472
+ scan_outer_dim<scalar_t>(*self_, result, dim, init, binary_op);
473
+ }
474
+ }
475
+
476
+ } // namespace at::native
477
+
478
+ #else
479
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
480
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Sort.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+ #include <ATen/core/TensorBase.h>
5
+ #include <ATen/native/cuda/SortStable.h>
6
+
7
+
8
+ namespace at::native {
9
+
10
+ inline bool should_use_small_sort(const TensorBase &self, int64_t dim) {
11
+ return self.size(dim) <= 4096;
12
+ }
13
+
14
+ void sortKeyValueInplace(
15
+ const TensorBase &key, const TensorBase &value, int64_t dim,
16
+ bool descending, bool stable=false);
17
+
18
+ } // namespace at::native
19
+
20
+ #else
21
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
22
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortStable.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <cstdint>
5
+
6
+ namespace at::native {
7
+
8
+ // Stable-sort self into values, and set indices to the
9
+ // inverse-permutation from values back to self.
10
+ // Output tensors must be pre-allocated and contiguous.
11
+ void launch_stable_sort_kernel(
12
+ const TensorBase& self,
13
+ int64_t dim,
14
+ bool descending,
15
+ const TensorBase& values,
16
+ const TensorBase& indices);
17
+
18
+ } // namespace at::native
19
+
20
+ #else
21
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
22
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortUtils.cuh ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/macros/Macros.h>
4
+
5
+ #include <ATen/cuda/cub.cuh>
6
+ #include <ATen/cuda/detail/TensorInfo.cuh>
7
+ #include <ATen/cuda/CUDAContext.h>
8
+ #include <ATen/cuda/DeviceUtils.cuh>
9
+ #include <ATen/native/cuda/SortingCommon.cuh>
10
+ #include <ATen/native/cuda/Sort.h>
11
+ #include <ATen/native/StridedRandomAccessor.h>
12
+
13
+ #if defined(USE_ROCM)
14
+ // ROCm: WarpMergeSort available and tested on ROCm 7.0+
15
+ // ROCM_VERSION encoding: MAJOR*10000 + MINOR*100 + PATCH
16
+ #define HAS_WARP_MERGE_SORT() (ROCM_VERSION >= 70000)
17
+ #else
18
+ // CUDA: WarpMergeSort available since CUDA 11.6
19
+ #define HAS_WARP_MERGE_SORT() (CUDA_VERSION >= 11060)
20
+ #endif
21
+
22
+
23
+ namespace at::native {
24
+
25
+ template <typename T>
26
+ __device__ inline void swapVars(T& t1, T& t2) {
27
+ T tmp = t1;
28
+ t1 = t2;
29
+ t2 = tmp;
30
+ }
31
+
32
+ template <typename Comparator, typename K, typename V>
33
+ __device__ inline void bitonicSwap(K& kA, V& vA, bool& validA,
34
+ K& kB, V& vB, bool& validB,
35
+ bool dir,
36
+ const Comparator& comp) {
37
+ // Invalid entries always sort to the end
38
+ bool swap = (comp(kA, kB) && validA) || !validB;
39
+ if (swap == dir) {
40
+ swapVars(kA, kB);
41
+ swapVars(vA, vB);
42
+ swapVars(validA, validB);
43
+ }
44
+ };
45
+
46
+ template <int Power2SortSize, typename IndexType, typename Comparator,
47
+ typename K, typename V>
48
+ __device__ inline void bitonicSort(K *keys,
49
+ V *values,
50
+ bool *valid,
51
+ const Comparator& comp) {
52
+ #if !defined(USE_ROCM)
53
+ #pragma unroll
54
+ #endif
55
+ for (unsigned int size = 2; size < Power2SortSize; size *= 2) {
56
+ bool flag = ((threadIdx.x & (size / 2)) != 0);
57
+
58
+ #if !defined(USE_ROCM)
59
+ #pragma unroll
60
+ #endif
61
+ for (unsigned int stride = size / 2; stride > 0; stride /= 2) {
62
+
63
+ __syncthreads();
64
+
65
+ unsigned int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1));
66
+ bitonicSwap<Comparator, K, V>(
67
+ keys[pos], values[pos], valid[pos],
68
+ keys[pos + stride], values[pos + stride], valid[pos + stride],
69
+ flag, comp);
70
+ }
71
+ }
72
+
73
+ #if !defined(USE_ROCM)
74
+ #pragma unroll
75
+ #endif
76
+ for (unsigned int stride = Power2SortSize / 2; stride > 0; stride /= 2) {
77
+
78
+ __syncthreads();
79
+
80
+ unsigned int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1));
81
+ bitonicSwap<Comparator, K, V>(
82
+ keys[pos], values[pos], valid[pos],
83
+ keys[pos + stride], values[pos + stride], valid[pos + stride],
84
+ false, comp);
85
+ }
86
+
87
+ __syncthreads();
88
+
89
+ }
90
+
91
+ // at::cuda::detail::TensorInfo version
92
+ // Sorts (key, value) pairs (in different tensors) in-place; i.e.,
93
+ // modifies the input `keys` and `values`
94
+ template <int KeyDims, int ValueDims, int block_dim_x, int max_block_dim_y,
95
+ typename K, typename V, typename Comparator, typename IndexType>
96
+ C10_LAUNCH_BOUNDS_1(block_dim_x * max_block_dim_y)
97
+ __global__ void
98
+ bitonicSortKVInPlace(at::cuda::detail::TensorInfo<K, IndexType> keys,
99
+ IndexType keySlices,
100
+ IndexType keySliceSize,
101
+ IndexType keySliceStride,
102
+ at::cuda::detail::TensorInfo<V, IndexType> values,
103
+ IndexType valueSliceStride,
104
+ Comparator comp) {
105
+ // Find the slice of the tensor that we are sorting
106
+ // NOTE: blockDim.y may be less max_block_dim_y
107
+ const IndexType blockIndex = getLinearBlockId<IndexType>();
108
+ const IndexType linearIndex = blockIndex * blockDim.y + threadIdx.y;
109
+
110
+ // If the entire block is out of bounds exit early
111
+ if (blockIndex * blockDim.y >= keySlices) {
112
+ return;
113
+ }
114
+ // It's also possible for some rows of a block to be out of bounds
115
+ // but all thread need to run for __syncthreads to work.
116
+ const bool row_valid = linearIndex < keySlices;
117
+
118
+ constexpr int items_per_thread = 2;
119
+ constexpr int Power2SortSize = block_dim_x * items_per_thread;
120
+
121
+ // Storage for max_block_dim_y sorts performed in parallel
122
+ __shared__ K blockSharedKeys[max_block_dim_y][Power2SortSize];
123
+ __shared__ V blockSharedValues[max_block_dim_y][Power2SortSize];
124
+ __shared__ bool blockSharedValid[max_block_dim_y][Power2SortSize];
125
+
126
+ auto sharedKeys = blockSharedKeys[threadIdx.y];
127
+ auto sharedValues = blockSharedValues[threadIdx.y];
128
+ auto sharedValid = blockSharedValid[threadIdx.y];
129
+
130
+ const IndexType keyStartOffset =
131
+ at::cuda::detail::IndexToOffset<K, IndexType, KeyDims>::get(linearIndex, keys);
132
+ const IndexType valueStartOffset =
133
+ at::cuda::detail::IndexToOffset<V, IndexType, ValueDims>::get(linearIndex, values);
134
+
135
+ // Load 2 values per thread into the shared workspace
136
+ #pragma unroll
137
+ for (int k = 0; k < items_per_thread; ++k) {
138
+ auto idx = threadIdx.x + k * blockDim.x;
139
+ bool valid = row_valid && idx < keySliceSize;
140
+
141
+ sharedKeys[idx] = valid ?
142
+ keys.data[idx * keySliceStride + keyStartOffset] : K{};
143
+ sharedValues[idx] = valid ?
144
+ values.data[idx * valueSliceStride + valueStartOffset] : V{};
145
+ sharedValid[idx] = valid;
146
+ }
147
+
148
+ // Sort!
149
+ bitonicSort<Power2SortSize, IndexType>(
150
+ sharedKeys, sharedValues, sharedValid, comp);
151
+
152
+ if (!row_valid) {
153
+ return;
154
+ }
155
+
156
+ // Store outputs
157
+ #pragma unroll
158
+ for (int k = 0; k < items_per_thread; ++k) {
159
+ auto idx = threadIdx.x + k * blockDim.x;
160
+ if (idx < keySliceSize) {
161
+ keys.data[idx * keySliceStride + keyStartOffset] = sharedKeys[idx];
162
+ values.data[idx * valueSliceStride + valueStartOffset] = sharedValues[idx];
163
+ }
164
+ }
165
+ }
166
+
167
+ #if HAS_WARP_MERGE_SORT()
168
+
169
+ // Note [warp merge sort WARP_SIZE template param]
170
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
171
+ // warpMergeSortKVInPlace was written assuming C10_WARP_SIZE is a constexpr.
172
+ // In torch/headeronly/macros/Macros.h, C10_WARP_SIZE is 32 for CUDA, and on
173
+ // ROCm it will be 32 or 64 based on the current compile-time gfx target.
174
+ // Ideally, warpSize should be used instead of C10_WARP_SIZE in device code, but
175
+ // C10_WARP_SIZE within this kernel has been used as a template parameter for
176
+ // some device functions. Therefore, a template param for WARP_SIZE was added.
177
+ template <int KeyDims, int ValueDims, int sort_size, int max_block_dim_y,
178
+ typename K, typename V, typename Comparator, typename IndexType,
179
+ int WARP_SIZE>
180
+ C10_LAUNCH_BOUNDS_1(WARP_SIZE * max_block_dim_y)
181
+ __global__ void
182
+ warpMergeSortKVInPlace(
183
+ at::cuda::detail::TensorInfo<K, IndexType> keys,
184
+ IndexType keySlices,
185
+ IndexType keySliceSize,
186
+ IndexType keySliceStride,
187
+ at::cuda::detail::TensorInfo<V, IndexType> values,
188
+ IndexType valueSliceStride,
189
+ Comparator comp,
190
+ K invalid_key) {
191
+ // Find the slice of the tensor that we are sorting
192
+ // NOTE: blockDim.y may be less max_block_dim_y
193
+ const IndexType blockIndex = getLinearBlockId<IndexType>();
194
+ const IndexType linearIndex = blockIndex * blockDim.y + threadIdx.y;
195
+
196
+ // If this row is out of bounds exit early
197
+ if (linearIndex >= keySlices) {
198
+ return;
199
+ }
200
+
201
+ const IndexType keyStartOffset =
202
+ at::cuda::detail::IndexToOffset<K, IndexType, KeyDims>::get(linearIndex, keys);
203
+ const IndexType valueStartOffset =
204
+ at::cuda::detail::IndexToOffset<V, IndexType, ValueDims>::get(linearIndex, values);
205
+
206
+ K *keys_slice = &keys.data[keyStartOffset];
207
+ V *values_slice = &values.data[valueStartOffset];
208
+
209
+ StridedRandomAccessor<K, IndexType> keys_iter(keys_slice, keySliceStride);
210
+ StridedRandomAccessor<V, IndexType> values_iter(values_slice, valueSliceStride);
211
+
212
+ namespace cub = ROCM_HIPCUB(at_cuda_detail::cub);
213
+
214
+ CUDA_KERNEL_ASSERT(blockDim.x == WARP_SIZE);
215
+ CUDA_KERNEL_ASSERT(blockDim.y <= max_block_dim_y);
216
+ constexpr int items_per_thread = sort_size / WARP_SIZE;
217
+ static_assert(
218
+ items_per_thread * WARP_SIZE == sort_size,
219
+ "sort_size must be a multiple of WARP_SIZE template param");
220
+
221
+
222
+ using LoadKeys = cub::WarpLoad<K, items_per_thread, cub::WARP_LOAD_TRANSPOSE>;
223
+ using LoadValues = cub::WarpLoad<V, items_per_thread, cub::WARP_LOAD_TRANSPOSE>;
224
+ using Sort = cub::WarpMergeSort<K, items_per_thread, WARP_SIZE, V>;
225
+ using StoreKeys = cub::WarpStore<K, items_per_thread, cub::WARP_STORE_TRANSPOSE>;
226
+ using StoreValues = cub::WarpStore<V, items_per_thread, cub::WARP_STORE_TRANSPOSE>;
227
+
228
+ __shared__ union {
229
+ typename LoadKeys::TempStorage load_keys;
230
+ typename LoadValues::TempStorage load_values;
231
+ typename Sort::TempStorage sort;
232
+ typename StoreKeys::TempStorage store_keys;
233
+ typename StoreValues::TempStorage store_values;
234
+ } tmp_storage[max_block_dim_y];
235
+
236
+ auto& warp_storage = tmp_storage[threadIdx.y];
237
+
238
+ // Load inputs
239
+ K local_keys[items_per_thread];
240
+ V local_values[items_per_thread];
241
+
242
+ const auto invalid_value = V{};
243
+ LoadKeys(warp_storage.load_keys).Load(keys_iter, local_keys, keySliceSize, invalid_key);
244
+ WARP_SYNC();
245
+ LoadValues(warp_storage.load_values).Load(values_iter, local_values, keySliceSize, invalid_value);
246
+ WARP_SYNC();
247
+
248
+ // Sort! We use stable sort to ensure that invalid values are never
249
+ // sorted before valid values. In testing it performed the same as
250
+ // .Sort, so there is no down-side.
251
+ Sort(warp_storage.sort).StableSort(
252
+ local_keys, local_values, comp, keySliceSize, invalid_key);
253
+ WARP_SYNC();
254
+
255
+ // Store outputs
256
+ StoreKeys(warp_storage.store_keys).Store(keys_iter, local_keys, keySliceSize);
257
+ WARP_SYNC();
258
+ StoreValues(warp_storage.store_values).Store(values_iter, local_values, keySliceSize);
259
+ }
260
+
261
+ #endif // HAS_WARP_MERGE_SORT()
262
+
263
+ template <int KeyDims, int ValueDims,
264
+ int block_size, int items_per_thread,
265
+ typename K, typename V, typename IndexType>
266
+ C10_LAUNCH_BOUNDS_1(block_size)
267
+ __global__ void
268
+ radixSortKVInPlace(at::cuda::detail::TensorInfo<K, IndexType> keys,
269
+ IndexType keySlices,
270
+ IndexType keySliceSize,
271
+ IndexType keySliceStride,
272
+ at::cuda::detail::TensorInfo<V, IndexType> values,
273
+ IndexType valueSliceStride,
274
+ bool descending) {
275
+ static_assert(block_size > 0, "");
276
+
277
+ // Find the slice of the tensor that we are sorting
278
+ const IndexType linearIndex = getLinearBlockId<IndexType>();
279
+ // Tiling the slices could have us be out of bounds, if there are a
280
+ // lot of slices to sort
281
+ if (linearIndex >= keySlices) {
282
+ return;
283
+ }
284
+
285
+ const IndexType keyStartOffset =
286
+ at::cuda::detail::IndexToOffset<K, IndexType, KeyDims>::get(linearIndex, keys);
287
+ const IndexType valueStartOffset =
288
+ at::cuda::detail::IndexToOffset<V, IndexType, ValueDims>::get(linearIndex, values);
289
+
290
+ K *keys_slice = &keys.data[keyStartOffset];
291
+ V *values_slice = &values.data[valueStartOffset];
292
+
293
+ StridedRandomAccessor<K, IndexType> keys_iter(keys_slice, keySliceStride);
294
+ StridedRandomAccessor<V, IndexType> values_iter(values_slice, valueSliceStride);
295
+
296
+ namespace cub = ROCM_HIPCUB(at_cuda_detail::cub);
297
+
298
+ using key_t = typename at::cuda::cub::detail::cuda_type<K>::type;
299
+ using LoadKeys = cub::BlockLoad<K, block_size, items_per_thread,
300
+ cub::BlockLoadAlgorithm::BLOCK_LOAD_TRANSPOSE>;
301
+ using LoadValues = cub::BlockLoad<V, block_size, items_per_thread,
302
+ cub::BlockLoadAlgorithm::BLOCK_LOAD_TRANSPOSE>;
303
+ using Sort = cub::BlockRadixSort<key_t, block_size, items_per_thread, V>;
304
+ using StoreKeys = cub::BlockStore<K, block_size, items_per_thread,
305
+ cub::BLOCK_STORE_TRANSPOSE>;
306
+ using StoreValues = cub::BlockStore<V, block_size, items_per_thread,
307
+ cub::BLOCK_STORE_TRANSPOSE>;
308
+
309
+ __shared__ union {
310
+ typename LoadKeys::TempStorage load_keys;
311
+ typename LoadValues::TempStorage load_values;
312
+ typename Sort::TempStorage sort;
313
+ typename StoreKeys::TempStorage store_keys;
314
+ typename StoreValues::TempStorage store_values;
315
+ } tmp_storage;
316
+
317
+ // cub's Block operations operate on a fixed number of items, but the
318
+ // actual slice we are sorting might be smaller. So, we need to make
319
+ // up the difference with keys that will always sort higher.
320
+ const K invalid_key = [descending] {
321
+ using radix_t = typename cub::Traits<key_t>::UnsignedBits;
322
+ union {
323
+ K key;
324
+ radix_t radix;
325
+ } tmp;
326
+ tmp.radix = descending ?
327
+ cub::Traits<key_t>::LOWEST_KEY :
328
+ cub::Traits<key_t>::MAX_KEY;
329
+ return tmp.key;
330
+ }();
331
+ const V invalid_value = static_cast<V>(0);
332
+
333
+ // Load inputs
334
+ K local_keys[items_per_thread];
335
+ V local_values[items_per_thread];
336
+
337
+ LoadKeys(tmp_storage.load_keys).Load(keys_iter, local_keys, keySliceSize, invalid_key);
338
+ __syncthreads();
339
+ LoadValues(tmp_storage.load_values).Load(values_iter, local_values, keySliceSize, invalid_value);
340
+ __syncthreads();
341
+
342
+ // Sort!
343
+ if (descending) {
344
+ Sort(tmp_storage.sort).SortDescending(
345
+ reinterpret_cast<key_t (&)[items_per_thread]>(local_keys),
346
+ local_values);
347
+ } else {
348
+ Sort(tmp_storage.sort).Sort(
349
+ reinterpret_cast<key_t (&)[items_per_thread]>(local_keys),
350
+ local_values);
351
+ }
352
+ __syncthreads();
353
+
354
+ // Store outputs
355
+ StoreKeys(tmp_storage.store_keys).Store(keys_iter, local_keys, keySliceSize);
356
+ __syncthreads();
357
+ StoreValues(tmp_storage.store_values).Store(values_iter, local_values, keySliceSize);
358
+ }
359
+
360
+ } // namespace at::native
361
+
362
+ #else
363
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
364
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Sorting.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ void launch_kthvalue_kernel(
12
+ const TensorBase &values, const TensorBase &indices,
13
+ const TensorBase &self, int64_t dim, int64_t k);
14
+ void launch_median_kernel(
15
+ const TensorBase &vals, const TensorBase &inds,
16
+ const TensorBase &in, int64_t dim, bool ignore_nan);
17
+
18
+ } // namespace at::native
19
+
20
+ #else
21
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
22
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortingCommon.cuh ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <ATen/ceil_div.h>
5
+ #include <ATen/NumericUtils.h>
6
+ #include <c10/macros/Macros.h>
7
+ #include <stdlib.h>
8
+ #include <ATen/cuda/detail/IndexUtils.cuh>
9
+ #include <ATen/cuda/detail/TensorInfo.cuh>
10
+
11
+ namespace at::native {
12
+
13
+ // Is this questionable namespace pollution?
14
+ #if defined(USE_ROCM)
15
+ constexpr int MAX_BLOCK_SIZE = 256;
16
+
17
+ #else
18
+ constexpr int MAX_BLOCK_SIZE = 1024;
19
+ #endif
20
+
21
+ // Maximum size per grid dimension that we assume (compute capability >= 2.0)
22
+ constexpr int64_t MAX_GRID_SIZE = 65535LL;
23
+
24
+ inline bool getGridFromTiles(int64_t gridTiles, dim3& grid) {
25
+ if (gridTiles > MAX_GRID_SIZE * MAX_GRID_SIZE * MAX_GRID_SIZE) {
26
+ return false;
27
+ }
28
+
29
+ int64_t gridX = gridTiles > MAX_GRID_SIZE ? MAX_GRID_SIZE : gridTiles;
30
+ int64_t gridY = 1;
31
+ int64_t gridZ = 1;
32
+
33
+ if (gridTiles > MAX_GRID_SIZE) {
34
+ gridTiles = ceil_div(gridTiles, MAX_GRID_SIZE);
35
+ gridY = gridTiles > MAX_GRID_SIZE ? MAX_GRID_SIZE : gridTiles;
36
+
37
+ if (gridTiles > MAX_GRID_SIZE) {
38
+ gridTiles = ceil_div(gridTiles, MAX_GRID_SIZE);
39
+ gridZ = gridTiles > MAX_GRID_SIZE ? MAX_GRID_SIZE : gridTiles;
40
+ }
41
+ }
42
+
43
+ grid = dim3(gridX, gridY, gridZ);
44
+ return true;
45
+ }
46
+
47
+ template <typename scalar_t, bool handleNaN = false>
48
+ struct GTOp {
49
+ __device__ bool operator()(const scalar_t& lhs, const scalar_t& rhs) const {
50
+ return (handleNaN && at::_isnan(lhs) && !at::_isnan(rhs)) ||
51
+ (static_cast<scalar_t>(lhs) > static_cast<scalar_t>(rhs));
52
+ }
53
+ };
54
+
55
+ template <typename scalar_t, bool handleNaN = false>
56
+ struct LTOp {
57
+ __device__ bool operator()(const scalar_t& lhs, const scalar_t& rhs) const {
58
+ return (handleNaN && at::_isnan(rhs) && !at::_isnan(lhs)) ||
59
+ (static_cast<scalar_t>(lhs) < static_cast<scalar_t>(rhs));
60
+ }
61
+ };
62
+
63
+ template <typename index_t>
64
+ __device__ __forceinline__ index_t getLinearBlockId() {
65
+ return blockIdx.z * gridDim.y * gridDim.x + blockIdx.y * gridDim.x +
66
+ blockIdx.x;
67
+ }
68
+
69
+ // For slice sorting in Thrust; extracts a slice index from a linear
70
+ // index and uses that for comparison
71
+ struct SliceComp {
72
+ SliceComp(int64_t size) : sliceSize(size) {}
73
+
74
+ __device__ bool operator()(const int64_t& a, const int64_t& b) const {
75
+ // Since the slices are guaranteed to be innermost,
76
+ // the segment is just via int64_t division
77
+ int64_t segA = a / sliceSize;
78
+ int64_t segB = b / sliceSize;
79
+ return segA < segB;
80
+ }
81
+
82
+ const int64_t sliceSize;
83
+ };
84
+
85
+ // For sorting in Thurst; extracts a within-slice index from a linear index
86
+ struct GlobalIndexToPerSliceIndex {
87
+ GlobalIndexToPerSliceIndex(int64_t size) : sliceSize(size) {}
88
+
89
+ __device__ inline void operator()(int64_t& v) const {
90
+ v = v % sliceSize;
91
+ }
92
+
93
+ const int64_t sliceSize;
94
+ };
95
+
96
+ // Returns 2^(ceil(lg(n)) from Stanford bit twiddling hacks
97
+ inline uint64_t nextHighestPowerOf2(uint64_t n) {
98
+ n--;
99
+ n |= n >> 1;
100
+ n |= n >> 2;
101
+ n |= n >> 4;
102
+ n |= n >> 8;
103
+ n |= n >> 16;
104
+ #ifndef _MSC_VER
105
+ n |= n >> 32;
106
+ #endif
107
+ n++;
108
+
109
+ return n;
110
+ }
111
+
112
+
113
+ // WARNING: This function assumes input tensors are contiguous
114
+ template <typename scalar_t, typename index_t, typename Launcher>
115
+ void run_launcher(
116
+ const TensorBase &values,
117
+ const TensorBase &indices,
118
+ const TensorBase &self,
119
+ int64_t dim,
120
+ Launcher l) {
121
+ auto self_info = cuda::detail::getTensorInfo<const scalar_t, index_t>(self);
122
+ auto values_info = cuda::detail::getTensorInfo<scalar_t, index_t>(values);
123
+ auto indices_info = cuda::detail::getTensorInfo<int64_t, index_t>(indices);
124
+
125
+ int64_t slice_size = self.size(dim);
126
+ /* We use these structures solely to find the offset to */
127
+ /* each slice we are operating on */
128
+ self_info.reduceDim(dim);
129
+ values_info.reduceDim(dim);
130
+ indices_info.reduceDim(dim);
131
+
132
+ /* Collapse all other dims */
133
+ int collapse_self_dim = self_info.collapseDims(dim);
134
+ int collapse_values_dim = values_info.collapseDims(dim);
135
+ int collapse_indices_dim = indices_info.collapseDims(dim);
136
+
137
+ int64_t num_slices = 1;
138
+ for (int i = 0; i < self_info.dims; ++i) {
139
+ num_slices *= self_info.sizes[i];
140
+ }
141
+
142
+ /* This is used as a template parameter to calculate indices. */
143
+ /* We only specialize it if all collapsed dim sizes are the */
144
+ /* same; otherwise, we use -1 which is the specialization */
145
+ /* parameter for arbitrary dimensions */
146
+ int all_dims = self_info.dims;
147
+ if (values_info.dims != all_dims || indices_info.dims != all_dims) {
148
+ all_dims = -1;
149
+ }
150
+
151
+ if (all_dims == 1) {
152
+ l.template launch<scalar_t, index_t, 1>(
153
+ values_info,
154
+ collapse_values_dim,
155
+ indices_info,
156
+ collapse_indices_dim,
157
+ self_info,
158
+ collapse_self_dim,
159
+ num_slices,
160
+ slice_size);
161
+ } else if (all_dims == 2) {
162
+ l.template launch<scalar_t, index_t, 2>(
163
+ values_info,
164
+ collapse_values_dim,
165
+ indices_info,
166
+ collapse_indices_dim,
167
+ self_info,
168
+ collapse_self_dim,
169
+ num_slices,
170
+ slice_size);
171
+ } else if (all_dims == 3) {
172
+ l.template launch<scalar_t, index_t, 3>(
173
+ values_info,
174
+ collapse_values_dim,
175
+ indices_info,
176
+ collapse_indices_dim,
177
+ self_info,
178
+ collapse_self_dim,
179
+ num_slices,
180
+ slice_size);
181
+ } else {
182
+ l.template launch<scalar_t, index_t, -1>(
183
+ values_info,
184
+ collapse_values_dim,
185
+ indices_info,
186
+ collapse_indices_dim,
187
+ self_info,
188
+ collapse_self_dim,
189
+ num_slices,
190
+ slice_size);
191
+ }
192
+ }
193
+
194
+ } // namespace at::native
195
+
196
+ #else
197
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
198
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/SortingRadixSelect.cuh ADDED
@@ -0,0 +1,1115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <ATen/ceil_div.h>
3
+ #include <c10/macros/Macros.h>
4
+ #include <ATen/cuda/AsmUtils.cuh>
5
+ #include <ATen/cuda/Atomic.cuh>
6
+ #include <ATen/cuda/DeviceUtils.cuh>
7
+ #include <type_traits>
8
+
9
+ namespace at::native {
10
+
11
+ template <typename scalar_t>
12
+ struct TopKTypeConfig {};
13
+
14
+ template <>
15
+ struct TopKTypeConfig<float> {
16
+ typedef uint32_t RadixType;
17
+
18
+ // Converts a float to an integer representation with the same
19
+ // sorting; i.e., for floats f1, f2:
20
+ // if f1 < f2 then convert(f1) < convert(f2)
21
+ // We use this to enable radix selection of floating-point values.
22
+ // This also gives a relative order for NaNs, but that's ok, as they
23
+ // will all be adjacent
24
+ // neg inf: signbit=1 exp=ff fraction=0 --> radix = 0 00 ff..
25
+ // pos inf: signbit=0 exp=ff fraction=0 --> radix = 1 ff 00..
26
+ // pos nan: signbit=0 exp=ff fraction>0 --> radix = 1 ff x>0
27
+ // neg nan: signbit=1 exp=ff fraction>0 --> radix = 0 00 x<ff...
28
+ static inline __device__ RadixType convert(float v) {
29
+ RadixType x = __float_as_int(v);
30
+ RadixType mask = (x & 0x80000000) ? 0xffffffff : 0x80000000;
31
+
32
+ return (v == v) ? (x ^ mask) : 0xffffffff;
33
+ }
34
+
35
+ static inline __device__ float deconvert(RadixType v) {
36
+ RadixType mask = (v & 0x80000000) ? 0x80000000 : 0xffffffff;
37
+
38
+ return __int_as_float(v ^ mask);
39
+ }
40
+ };
41
+
42
+ template <>
43
+ struct TopKTypeConfig<uint8_t> {
44
+ typedef uint32_t RadixType;
45
+
46
+ static inline __device__ RadixType convert(uint8_t v) {
47
+ return v;
48
+ }
49
+
50
+ static inline __device__ uint8_t deconvert(RadixType v) {
51
+ return v;
52
+ }
53
+ };
54
+
55
+ template <>
56
+ struct TopKTypeConfig<int8_t> {
57
+ typedef uint32_t RadixType;
58
+
59
+ static inline __device__ RadixType convert(int8_t v) {
60
+ return 128u + v;
61
+ }
62
+
63
+ static inline __device__ int8_t deconvert(RadixType v) {
64
+ return v - 128;
65
+ }
66
+ };
67
+
68
+ template <>
69
+ struct TopKTypeConfig<int16_t> {
70
+ typedef uint32_t RadixType;
71
+
72
+ static inline __device__ RadixType convert(int16_t v) {
73
+ static_assert(sizeof(short) == 2, "");
74
+ return 32768u + v;
75
+ }
76
+
77
+ static inline __device__ int16_t deconvert(RadixType v) {
78
+ return v - 32768;
79
+ }
80
+ };
81
+
82
+ template <>
83
+ struct TopKTypeConfig<int32_t> {
84
+ typedef uint32_t RadixType;
85
+
86
+ static inline __device__ RadixType convert(int32_t v) {
87
+ static_assert(sizeof(int) == 4, "");
88
+ return 2147483648u + v;
89
+ }
90
+
91
+ static inline __device__ int32_t deconvert(RadixType v) {
92
+ return v - 2147483648u;
93
+ }
94
+ };
95
+
96
+ template <>
97
+ struct TopKTypeConfig<int64_t> {
98
+ typedef uint64_t RadixType;
99
+
100
+ static inline __device__ RadixType convert(int64_t v) {
101
+ static_assert(sizeof(int64_t) == 8, "");
102
+ return 9223372036854775808ull + v;
103
+ }
104
+
105
+ static inline __device__ int64_t deconvert(RadixType v) {
106
+ return v - 9223372036854775808ull;
107
+ }
108
+ };
109
+
110
+ template <>
111
+ struct TopKTypeConfig<double> {
112
+ typedef uint64_t RadixType;
113
+
114
+ static inline __device__ RadixType convert(double v) {
115
+ RadixType x = __double_as_longlong(v);
116
+ RadixType mask = -((x >> 63)) | 0x8000000000000000;
117
+ return (v == v) ? (x ^ mask) : 0xffffffffffffffff;
118
+ }
119
+
120
+ static inline __device__ double deconvert(RadixType v) {
121
+ RadixType mask = ((v >> 63) - 1) | 0x8000000000000000;
122
+ return __longlong_as_double(v ^ mask);
123
+ }
124
+ };
125
+
126
+ template <>
127
+ struct TopKTypeConfig<at::Half> {
128
+ typedef uint32_t RadixType;
129
+
130
+ static inline __device__ RadixType convert(at::Half v) {
131
+ RadixType x = __half_as_ushort(v);
132
+ RadixType mask = (x & 0x00008000) ? 0x0000ffff : 0x00008000;
133
+ return (static_cast<float>(v) == static_cast<float>(v)) ? (x ^ mask) : 0xffff;
134
+ }
135
+
136
+ static inline __device__ at::Half deconvert(RadixType v) {
137
+ RadixType mask = (v & 0x00008000) ? 0x00008000 : 0x0000ffff;
138
+ return __ushort_as_half(v ^ mask);
139
+ }
140
+ };
141
+
142
+ template <>
143
+ struct TopKTypeConfig<at::BFloat16> {
144
+ typedef uint32_t RadixType;
145
+
146
+ static inline __device__ RadixType convert(at::BFloat16 v) {
147
+ RadixType x = v.x;
148
+ RadixType mask = (x & 0x00008000) ? 0x0000ffff : 0x00008000;
149
+ return (static_cast<float>(v) == static_cast<float>(v)) ? (x ^ mask) : 0xffff;
150
+ }
151
+
152
+ static inline __device__ at::BFloat16 deconvert(RadixType v) {
153
+ RadixType mask = (v & 0x00008000) ? 0x00008000 : 0x0000ffff;
154
+ at::BFloat16 r;
155
+ r.x = (v ^ mask);
156
+ return r;
157
+ }
158
+ };
159
+
160
+ // Over what radix we are selecting values
161
+ constexpr int RADIX_BITS = 2; // digits are base-(2 ^ RADIX_BITS)
162
+ constexpr int RADIX_SIZE = 4; // 2 ^ RADIX_BITS
163
+ constexpr int RADIX_MASK = (RADIX_SIZE - 1);
164
+
165
+ #ifndef USE_ROCM
166
+ // This function counts the distribution of all input values in a
167
+ // slice we are selecting by radix digit at `radixDigitPos`, but only
168
+ // those that pass the filter `((v & desiredMask) == desired)`.
169
+ // This produces and broadcasts the seen counts for a single block only.
170
+ // `smem` must have at least `RadixSize` elements.
171
+ template <
172
+ typename scalar_t,
173
+ typename bitwise_t,
174
+ typename index_t,
175
+ typename CountType,
176
+ int RadixSize,
177
+ int RadixBits>
178
+ __device__ void countRadixUsingMask(
179
+ CountType counts[RadixSize],
180
+ CountType* smem,
181
+ bitwise_t desired,
182
+ bitwise_t desiredMask,
183
+ int radixDigitPos,
184
+ index_t sliceSize,
185
+ index_t withinSliceStride,
186
+ const scalar_t* data) {
187
+ // Clear out per-thread counts from a previous round
188
+ #pragma unroll
189
+ for (int i = 0; i < RadixSize; ++i) {
190
+ counts[i] = 0;
191
+ }
192
+
193
+ if (threadIdx.x < RadixSize) {
194
+ smem[threadIdx.x] = 0;
195
+ }
196
+ __syncthreads();
197
+
198
+ // Scan over all the data. Upon a read, the warp will accumulate
199
+ // counts per each digit in the radix using warp voting.
200
+ // Must be called outside of loop to ensure all threads participate
201
+ unsigned mask = WARP_BALLOT(threadIdx.x < sliceSize);
202
+ for (index_t i = threadIdx.x; i < sliceSize;) {
203
+ bitwise_t val =
204
+ TopKTypeConfig<scalar_t>::convert(doLdg(&data[i * withinSliceStride]));
205
+
206
+ bool hasVal = ((val & desiredMask) == desired);
207
+ bitwise_t digitInRadix = at::cuda::Bitfield<bitwise_t>::getBitfield(
208
+ val, radixDigitPos, RadixBits);
209
+
210
+ #pragma unroll
211
+ for (uint32_t j = 0; j < RadixSize; ++j) {
212
+ bool vote = hasVal && (digitInRadix == j);
213
+ counts[j] += __popc(WARP_BALLOT(vote, mask));
214
+ }
215
+ i += blockDim.x;
216
+ mask = WARP_BALLOT(i < sliceSize, mask);
217
+ }
218
+
219
+ // Now, for each warp, sum values
220
+ // Note: uint64_t on Linux is unsigned long, but CUDA atomicAdd expects
221
+ // unsigned long long. We use reinterpret_cast for compatibility.
222
+ if (at::cuda::getLaneId() == 0) {
223
+ #pragma unroll
224
+ for (uint32_t i = 0; i < RadixSize; ++i) {
225
+ if constexpr (std::is_same_v<CountType, uint64_t>) {
226
+ atomicAdd(reinterpret_cast<unsigned long long*>(smem) + i,
227
+ static_cast<unsigned long long>(counts[i]));
228
+ } else {
229
+ atomicAdd(&smem[i], counts[i]);
230
+ }
231
+ }
232
+ }
233
+
234
+ __syncthreads();
235
+
236
+ // For each thread, read in the total counts
237
+ #pragma unroll
238
+ for (uint32_t i = 0; i < RadixSize; ++i) {
239
+ counts[i] = smem[i];
240
+ }
241
+
242
+ __syncthreads();
243
+ }
244
+
245
+ // This finds the unique value `v` that matches the pattern
246
+ // ((v & desired) == desiredMask) in our sorted int format
247
+ template <typename scalar_t, typename bitwise_t, typename index_t>
248
+ __device__ scalar_t findPattern(
249
+ scalar_t* smem,
250
+ const scalar_t* data,
251
+ index_t sliceSize,
252
+ index_t withinSliceStride,
253
+ bitwise_t desired,
254
+ bitwise_t desiredMask) {
255
+ if (threadIdx.x < 2) {
256
+ smem[threadIdx.x] = static_cast<scalar_t>(0);
257
+ }
258
+ __syncthreads();
259
+
260
+ // All threads participate in the loop, in order to sync on the flag
261
+ index_t numIterations = round_up(sliceSize, static_cast<index_t>(blockDim.x));
262
+ for (index_t i = threadIdx.x; i < numIterations; i += blockDim.x) {
263
+ bool inRange = (i < sliceSize);
264
+ scalar_t v = inRange ? doLdg(&data[i * withinSliceStride])
265
+ : static_cast<scalar_t>(0);
266
+
267
+ if (inRange &&
268
+ ((TopKTypeConfig<scalar_t>::convert(v) & desiredMask) == desired)) {
269
+ // There should not be conflicts if we are using findPattern,
270
+ // since the result is unique
271
+ smem[0] = static_cast<scalar_t>(1);
272
+ smem[1] = v; // can't use val as the flag, since it could be 0
273
+ }
274
+
275
+ __syncthreads();
276
+
277
+ scalar_t found = smem[0];
278
+ scalar_t val = smem[1];
279
+
280
+ __syncthreads();
281
+
282
+ // Check to see if a thread found the value
283
+ if (found != static_cast<scalar_t>(0)) {
284
+ // all threads return this value
285
+ return val;
286
+ }
287
+ }
288
+
289
+ // should not get here
290
+ CUDA_KERNEL_ASSERT(false);
291
+ return static_cast<scalar_t>(0);
292
+ }
293
+
294
+ #else
295
+
296
+ /*
297
+ This implementation of radixSelect optimizes the k-th element selection
298
+ algorithm by dynamically utilizing shared memory to cache input data when
299
+ possible, significantly reducing global memory traffic during the iterative bit
300
+ discovery process. The radixSelect algorithm finds the k-th element by
301
+ iteratively uncovering its bit pattern through multiple passes over the data.
302
+ Each pass determines 2 bits of the target value's bitmap (up to 16 passes for
303
+ float32 inputs). As iterations progress, the number of relevant values decreases
304
+ by approximately 4× per pass, assuming uniform bit distribution. While initially
305
+ the input data may be too large to fit in shared memory, it often becomes
306
+ cacheable after a few filtering iterations as the data size shrinks. This
307
+ implementation introduces dynamic shared memory caching that checks at each
308
+ iteration whether the filtered data fits within available LDS (a few KB's
309
+ allocated for this purpose). When the data fits, it is cached to shared memory,
310
+ eliminating redundant global memory reads in subsequent operations within that
311
+ iteration. New kernel functions countRadixUsingMaskDataSmem and findPatternSmem
312
+ were introduced to seamlessly handle both cached (LDS) and non-cached (global
313
+ memory) data paths. These variants maintain backward compatibility with the
314
+ original algorithm and automatically fall back to global memory access when data
315
+ exceeds LDS capacity.
316
+ */
317
+
318
+ // this is the main loop of the countRadixUsingMask function that counts the
319
+ // distribution of the bits in the radix digit at `radixDigitPos` to
320
+ // `radixDigitPos`+RADIX_BITS-1. DataAccessor is a function that returns the
321
+ // input data value at index i. It could potentially be a global memory accessor
322
+ // or a shared memory accessor.
323
+ template <
324
+ typename scalar_t,
325
+ typename bitwise_t,
326
+ typename index_t,
327
+ typename CountType,
328
+ int RadixSize,
329
+ int RadixBits,
330
+ bool prefetch,
331
+ typename DataAccessor>
332
+ __device__ __forceinline__ void countRadixLoop(
333
+ CountType counts[RadixSize], // counts[i] will be the number of matching
334
+ // elements ((val & desiredMask) == desired)
335
+ // that have the digits [radixDigitPos,
336
+ // radixDigitPos+RADIX_BITS-1] set to i.
337
+ bitwise_t
338
+ desired, // combined with desiredMask to filter relevant elements. A
339
+ // value is relevant if ((val & desiredMask) == desired).
340
+ bitwise_t
341
+ desiredMask, // combined with desired to filter relevant elements. A
342
+ // value is relevant if ((val & desiredMask) == desired).
343
+ int radixDigitPos, // the position of the radix digit.
344
+ index_t loopBound, // the upper bound of the loop.
345
+ DataAccessor&& getData) { // a function that returns the input data value at
346
+ // index i. It could potentially be a global
347
+ // memory accessor or a shared memory accessor.
348
+
349
+ // the kernel consists of two parts:
350
+ // phase 1: processing 4 elements at an iteration.
351
+ // phase 2: processing 1 element at an iteration.
352
+
353
+ constexpr index_t unroll_factor = 4;
354
+ index_t unroll_segment =
355
+ (loopBound / (blockDim.x * unroll_factor)) * blockDim.x * unroll_factor;
356
+
357
+ // phase 1: processing 4 elements at an iteration.
358
+
359
+ for (index_t i = threadIdx.x * unroll_factor; i < unroll_segment;
360
+ i += blockDim.x * unroll_factor) {
361
+
362
+ // prefetch 4 elements.
363
+ scalar_t v0 = getData(i);
364
+ scalar_t v1 = getData(i + 1);
365
+ scalar_t v2 = getData(i + 2);
366
+ scalar_t v3 = getData(i + 3);
367
+
368
+ // convert the values to bitwise_t.
369
+ bitwise_t val0 = TopKTypeConfig<scalar_t>::convert(v0);
370
+ bitwise_t val1 = TopKTypeConfig<scalar_t>::convert(v1);
371
+ bitwise_t val2 = TopKTypeConfig<scalar_t>::convert(v2);
372
+ bitwise_t val3 = TopKTypeConfig<scalar_t>::convert(v3);
373
+
374
+ // check if the values match the desired pattern.
375
+ bool hasVal0 = ((val0 & desiredMask) == desired);
376
+ bool hasVal1 = ((val1 & desiredMask) == desired);
377
+ bool hasVal2 = ((val2 & desiredMask) == desired);
378
+ bool hasVal3 = ((val3 & desiredMask) == desired);
379
+
380
+ // get the bits [radixDigitPos, radixDigitPos+RADIX_BITS-1] of the values.
381
+ bitwise_t digitInRadix0 = at::cuda::Bitfield<bitwise_t>::getBitfield(
382
+ val0, radixDigitPos, RadixBits);
383
+ bitwise_t digitInRadix1 = at::cuda::Bitfield<bitwise_t>::getBitfield(
384
+ val1, radixDigitPos, RadixBits);
385
+ bitwise_t digitInRadix2 = at::cuda::Bitfield<bitwise_t>::getBitfield(
386
+ val2, radixDigitPos, RadixBits);
387
+ bitwise_t digitInRadix3 = at::cuda::Bitfield<bitwise_t>::getBitfield(
388
+ val3, radixDigitPos, RadixBits);
389
+
390
+ // counting across the warp.
391
+ #pragma unroll
392
+ for (uint32_t j = 0; j < RadixSize; ++j) {
393
+ // checking pattern match & digit match.
394
+ bool vote0 = hasVal0 && (digitInRadix0 == j);
395
+ bool vote1 = hasVal1 && (digitInRadix1 == j);
396
+ bool vote2 = hasVal2 && (digitInRadix2 == j);
397
+ bool vote3 = hasVal3 && (digitInRadix3 == j);
398
+
399
+ // how many threads in this warp found digitInRadix == j while matching
400
+ // the desired pattern?
401
+ counts[j] += __popcll(WARP_BALLOT(vote0)) + __popcll(WARP_BALLOT(vote1)) +
402
+ __popcll(WARP_BALLOT(vote2)) + __popcll(WARP_BALLOT(vote3));
403
+ }
404
+ }
405
+
406
+ // phase 2: processing 1 element at an iteration.
407
+
408
+ // prefetching pattern if prefetch is true.
409
+ // prefetching pattern is only useful for global memory access.
410
+ scalar_t v_curr;
411
+ if constexpr (prefetch) {
412
+ v_curr = unroll_segment + threadIdx.x < loopBound
413
+ ? getData(unroll_segment + threadIdx.x)
414
+ : static_cast<scalar_t>(0);
415
+ }
416
+ for (index_t i = unroll_segment + threadIdx.x;
417
+ i < loopBound;
418
+ i += blockDim.x) {
419
+ scalar_t v_local; // the current element.
420
+ scalar_t v_next; // the next element. Used for prefetching.
421
+
422
+ if constexpr (prefetch) {
423
+ // prefetch the next element.
424
+ v_local = v_curr;
425
+ v_next = i + blockDim.x < loopBound ? getData(i + blockDim.x)
426
+ : static_cast<scalar_t>(0);
427
+ }
428
+ else {
429
+ v_local = getData(i); // if no prefetching, just get the current element.
430
+ }
431
+
432
+ bitwise_t val = TopKTypeConfig<scalar_t>::convert(v_local);
433
+ // check if bit pattern matches the pattern we have already discovered for
434
+ // topk value v.
435
+ bool hasVal = ((val & desiredMask) == desired);
436
+ // get the bits [radixDigitPos, radixDigitPos+RADIX_BITS-1] of the value
437
+ // v.
438
+ bitwise_t digitInRadix = at::cuda::Bitfield<bitwise_t>::getBitfield(
439
+ val, radixDigitPos, RadixBits);
440
+
441
+ // counting across the warp.
442
+ #pragma unroll
443
+ for (uint32_t j = 0; j < RadixSize; ++j) {
444
+ // checking pattern match & digit match.
445
+ bool vote = hasVal && (digitInRadix == j);
446
+ // how many threads in this warp found digitInRadix == j while matching
447
+ // the desired pattern?
448
+ counts[j] += __popcll(WARP_BALLOT(vote));
449
+ }
450
+
451
+ if constexpr (prefetch) {
452
+ v_curr = v_next; // closing the prefetching loop.
453
+ }
454
+ }
455
+ }
456
+
457
+ // Aggregates radix matches across all warps and distributes results back to all threads.
458
+ // Uses double-buffering via buffer_index (0 or 1) to alternate between two smem segments,
459
+ // preventing race conditions between concurrent iterations. Since countRadixUsingMaskDataSmem
460
+ // performs __syncthreads() internally, at most two loop iterations can be in flight
461
+ // simultaneously, so two buffers are sufficient. buffer_index is toggled after each
462
+ // countRadixUsingMaskDataSmem invocation.
463
+ template <
464
+ typename CountType,
465
+ int RadixSize,
466
+ int RadixBits>
467
+ __device__ __forceinline__ void countRadixAggregateCounts(
468
+ CountType counts[RadixSize], // counts[i] will be the number of matching
469
+ // elements ((val & desiredMask) == desired)
470
+ // that have the digits [radixDigitPos,
471
+ // radixDigitPos+RADIX_BITS-1] set to i.
472
+ CountType* smem, // shared memory for inter-warp reduction of counts.
473
+ int buffer_index){ // buffer index for smem.
474
+
475
+ // Maximum number of warps per workgroup. HIP workgroups have at most 1024 threads.
476
+ // Warp size is at least 32 (can be 64 on some architectures), so we use 32 for safety.
477
+ // This sizes shared memory buffers to accommodate all possible warps: 1024/32 = 32.
478
+ constexpr uint MAX_WARPS = 1024/C10_WARP_SIZE_LOWER_BOUND;
479
+ const int buffer_offset = buffer_index * MAX_WARPS * RadixSize; // offset of the buffer in smem.
480
+ const uint WARP_BITS = __builtin_ctz(C10_WARP_SIZE);
481
+
482
+ const uint num_warps = blockDim.x >> WARP_BITS; // Actual number of warps in this block
483
+ const uint warp_id = threadIdx.x >> WARP_BITS; // = threadIdx.x / C10_WARP_SIZE
484
+ const int lane_id = at::cuda::getLaneId(); // = threadIdx.x % C10_WARP_SIZE
485
+
486
+ // Stage 1: Each warp's lane 0 stores its counts in smem.
487
+ // Layout after Stage 1: [warp0: all radix bins], [warp1: all radix bins], ...
488
+ // this layout starts from index buffer_offset.
489
+ if (lane_id == 0) {
490
+ #pragma unroll
491
+ for (uint32_t i = 0; i < RadixSize; ++i) {
492
+ smem[
493
+ buffer_offset
494
+ + warp_id * RadixSize
495
+ + i
496
+ ] = counts[i];
497
+ }
498
+ }
499
+
500
+ __syncthreads(); // wait for all warps to finish storing their counts to smem.
501
+
502
+ // Stage 2: Warp0 performs reduction for all bins.
503
+ // Layout after Stage 2: [final radix0 sum], [final radix1 sum], ..., [final radix(RadixSize-1) sum]
504
+ // this layout starts from index buffer_offset.
505
+ if (warp_id == 0 && lane_id < RadixSize) {
506
+ CountType sum = 0;
507
+ #pragma unroll
508
+ for (int w = 0; w < num_warps; ++w) {
509
+ sum += smem[
510
+ buffer_offset
511
+ + w * RadixSize
512
+ + lane_id
513
+ ];
514
+ }
515
+ smem[buffer_offset + lane_id] = sum;
516
+ }
517
+
518
+ __syncthreads(); // Wait for warp 0 to finish reduction.
519
+
520
+ // Stage 3: Each thread reads the final counts from smem.
521
+ #pragma unroll
522
+ for (uint32_t i = 0; i < RadixSize; ++i) {
523
+ counts[i] = smem[buffer_offset + i];
524
+ }
525
+ }
526
+
527
+ // This function counts the distribution of all input values in a
528
+ // slice we are selecting by radix digit at `radixDigitPos`, but only
529
+ // those that pass the filter `((v & desiredMask) == desired)`.
530
+ // This produces and broadcasts the seen counts for a single block only.
531
+ // `smem` must have at least `RadixSize` elements.
532
+ // this is an smem-friendly version of the countRadixUsingMask function.
533
+ // it works when data is in global memory or in shared memory.
534
+ template <
535
+ typename scalar_t,
536
+ typename bitwise_t,
537
+ typename index_t,
538
+ typename CountType,
539
+ int RadixSize,
540
+ int RadixBits>
541
+ __device__ void countRadixUsingMaskDataSmem(
542
+ CountType
543
+ counts[RadixSize], // counts[i] will be the number of matching elements
544
+ // ((val & desiredMask) == desired) that have the
545
+ // digits [radixDigitPos, radixDigitPos+RADIX_BITS-1]
546
+ // set to i in the warp.
547
+ CountType* smem, // shared memory for inter-warp reduction of counts.
548
+ int buffer_index, // buffer index for smem.
549
+ bitwise_t
550
+ desired, // combined with desiredMask to filter relevant elements. An
551
+ // element is relevant if ((val & desiredMask) == desired).
552
+ bitwise_t
553
+ desiredMask, // combined with desired to filter relevant elements. An
554
+ // element is relevant if ((val & desiredMask) == desired).
555
+ int radixDigitPos, // position of the radix digit.
556
+ index_t sliceSize, // size of the input slice.
557
+ index_t withinSliceStride, // stride of the input slice.
558
+ const scalar_t* data, // input data. This is global memory.
559
+ const scalar_t*
560
+ dataSmem, // input data stored in shared memory. This is shared memory.
561
+ // It is not initialized if dataSmemSize == 0.
562
+ int dataSmemSize) { // input data size stored in shared memory. dataSmemSize
563
+ // > 0 if dataSmem is filled.
564
+
565
+ // Clear out per-thread counts from a previous round
566
+ #pragma unroll
567
+ for (int i = 0; i < RadixSize; ++i) {
568
+ counts[i] = 0; // initialize counts to 0.
569
+ }
570
+
571
+ // count the distribution of the bits in the radix digit at `radixDigitPos` to
572
+ // `radixDigitPos`+RADIX_BITS-1 for values that match the desired pattern
573
+ // ((val & desiredMask) == desired). counts[] will hold the results for the
574
+ // current warp.
575
+ if (dataSmemSize >
576
+ 0) { // if shared memory is filled, use dataSmem as the input data.
577
+ countRadixLoop<scalar_t, bitwise_t, index_t, CountType, RadixSize, RadixBits, /*prefetch =*/ false>(
578
+ counts,
579
+ desired,
580
+ desiredMask,
581
+ radixDigitPos,
582
+ dataSmemSize,
583
+ [&](index_t i) -> scalar_t { return dataSmem[i]; });
584
+ } else { // if shared memory is not filled, fall back to global memory.
585
+ countRadixLoop<scalar_t, bitwise_t, index_t, CountType, RadixSize, RadixBits, /*prefetch =*/ true>(
586
+ counts,
587
+ desired,
588
+ desiredMask,
589
+ radixDigitPos,
590
+ sliceSize,
591
+ [&](index_t i) -> scalar_t {
592
+ return doLdg(&data[i * withinSliceStride]);
593
+ });
594
+ }
595
+
596
+ // aggregate counts across all warps and distribute results back to all threads.
597
+ countRadixAggregateCounts<CountType, RadixSize, RadixBits>(
598
+ counts,
599
+ smem,
600
+ buffer_index);
601
+ }
602
+
603
+ // This is the main loop of the findPattern function that finds the unique value
604
+ // that matches the pattern ((val & desired) == desiredMask) in the input data.
605
+ // DataAccessor is a function that returns the input data value at index i.
606
+ // It could potentially be a global memory accessor or a shared memory accessor.
607
+ template <
608
+ typename scalar_t,
609
+ typename bitwise_t,
610
+ typename index_t,
611
+ typename DataAccessor>
612
+ __device__ __forceinline__ scalar_t findPatternLoop(
613
+ scalar_t* smem, // shared memory for inter-thread communication of the found
614
+ // value.
615
+ bitwise_t
616
+ desired, // combined with desiredMask to filter relevant elements. An
617
+ // element is relevant if ((val & desiredMask) == desired).
618
+ bitwise_t
619
+ desiredMask, // combined with desired to filter relevant elements. An
620
+ // element is relevant if ((val & desiredMask) == desired).
621
+ index_t loopBound, // the upper bound of the loop.
622
+ DataAccessor&&
623
+ getData) { // a function that returns the input data value at index i.
624
+
625
+ // TODO: this loop has two areas for improvement:
626
+ // 1. no need to synchronize two times at each iteration. The assumption
627
+ // here is that the
628
+ // data is unique. So we can have the loop truncated to the part that
629
+ // smem is filled. We then do __syncthreads outside the loop. The current
630
+ // early termination is probably costing us way more performance than
631
+ // it's worth. If synchronization is moved outside the loop, we no longer
632
+ // need to pad loopbound to round_up(loopbound, blockDim.x).
633
+ // 2. given this loop is potentially reading from global memory, we can
634
+ // prefetch the next value
635
+ // to improve performance. But it should not have a significant impact
636
+ // unless point 1 above is addressed.
637
+
638
+ // we pad loopbound to round_up(loopbound, blockDim.x) to make sure all
639
+ // threads in the block participate in the synchronization.
640
+ for (index_t i = threadIdx.x;
641
+ i < round_up(loopBound, static_cast<index_t>(blockDim.x));
642
+ i += blockDim.x) {
643
+ bool inRange = (i < loopBound);
644
+ scalar_t v = inRange ? getData(i) : static_cast<scalar_t>(0);
645
+
646
+ if (inRange &&
647
+ ((TopKTypeConfig<scalar_t>::convert(v) & desiredMask) == desired)) {
648
+ // There should not be conflicts if we are using findPattern,
649
+ // since the result is unique
650
+ smem[0] = static_cast<scalar_t>(1); // set the flag to 1.
651
+ smem[1] = v; // store the value in smem. can't use val as the flag, since
652
+ // it could be 0.
653
+ }
654
+
655
+ __syncthreads(); // wait for all threads in the warp to finish setting the
656
+ // flag and storing the value.
657
+
658
+ scalar_t found = smem[0]; // read the flag from smem.
659
+ scalar_t val = smem[1]; // read the value from smem.
660
+
661
+ __syncthreads(); // wait for all threads in the warp to finish reading the
662
+ // flag and value.
663
+
664
+ // Checking to see if a thread found the value. If so, all threads return
665
+ // this value.
666
+ if (found != static_cast<scalar_t>(0)) {
667
+ return val;
668
+ }
669
+ }
670
+
671
+ CUDA_KERNEL_ASSERT(false); // should not get here.
672
+ return static_cast<scalar_t>(0); // to make sure the compiler is happy.
673
+ }
674
+
675
+ // This function finds the unique value that matches the pattern
676
+ // ((val & desired) == desiredMask) in the input data.
677
+ // this is an smem-friendly version of the findPattern function.
678
+ // It works when data is in global memory or in shared memory.
679
+ template <typename scalar_t, typename bitwise_t, typename index_t>
680
+ __device__ scalar_t findPatternDataSmem(
681
+ scalar_t* smem, // shared memory for inter-thread communication of the found
682
+ // value.
683
+ const scalar_t* data, // input data.
684
+ index_t sliceSize, // size of the input slice.
685
+ index_t withinSliceStride, // stride of the input slice.
686
+ bitwise_t
687
+ desired, // combined with desiredMask to filter relevant elements. An
688
+ // element is relevant if ((val & desiredMask) == desired).
689
+ bitwise_t
690
+ desiredMask, // combined with desired to filter relevant elements. An
691
+ // element is relevant if ((val & desiredMask) == desired).
692
+ const scalar_t* dataSmem, // input data stored in shared memory.
693
+ index_t dataSmemSize) { // input data size stored in shared memory.
694
+
695
+ // Ensure all threads have finished reading from smem before overwriting it.
696
+ // countRadixAggregateCounts Stage 3 reads from smem[buffer_offset + i];
697
+ // when buffer_offset == 0, those locations overlap with smem[0]/smem[1]
698
+ // written below. Warp 0 (which writes smem[0]/smem[1]) may get ahead of
699
+ // lagging warps still in Stage 3. Syncing here (rather than at the end of
700
+ // Stage 3) is cheaper because findPatternDataSmem is called at most once per
701
+ // radixSelect invocation, only when a unique element is found (count == 1).
702
+ __syncthreads();
703
+
704
+ // initialize smem to 0.
705
+ // smem[0] is a flag to indicate if a value has been found.
706
+ // smem[1] is the found value.
707
+ if (threadIdx.x < 2) {
708
+ smem[threadIdx.x] = static_cast<scalar_t>(0);
709
+ }
710
+
711
+ __syncthreads(); // all threads in the block wait for smem to be initialized.
712
+
713
+ if (dataSmemSize >
714
+ 0) { // if shared memory is filled, use dataSmem as the input data.
715
+ return findPatternLoop<scalar_t, bitwise_t, index_t>(
716
+ smem, desired, desiredMask, dataSmemSize, [&](index_t i) -> scalar_t {
717
+ return dataSmem[i];
718
+ });
719
+ } else { // if shared memory is not filled, fall back to global memory.
720
+ return findPatternLoop<scalar_t, bitwise_t, index_t>(
721
+ smem, desired, desiredMask, sliceSize, [&](index_t i) -> scalar_t {
722
+ return doLdg(&data[i * withinSliceStride]);
723
+ });
724
+ }
725
+
726
+ return static_cast<scalar_t>(
727
+ 0); // should not get here. This is to make sure the compiler is happy.
728
+ }
729
+
730
+ // This function fills the shared memory dataSmem with the input data.
731
+ // It is called at each iteration of the main loop of the radixSelect function.
732
+ //
733
+ // Four possible scenarios:
734
+ // 1. dataSmem is already filled (dataSmemSize > 0). This means at a previous
735
+ // iteration
736
+ // we have filled the shared memory with the input data. We return.
737
+ // 2. dataSmem is not filled (dataSmemSize == 0) and the input data is small
738
+ // enough to
739
+ // fit into shared memory (sliceSize <= dataSmemCap). If this case
740
+ // happens, it should happen at the first iteration. In this case, we put
741
+ // all the data into shared memory.
742
+ // 3. dataSmem is not filled (dataSmemSize == 0) and the input data, although
743
+ // not fitting
744
+ // into shared memory originally (otherwise we would have ended up in case
745
+ // 2), now fits into shared memory (dataSizeRemaining <= dataSmemCap). In
746
+ // this case, filter the data using the desired pattern ((val &
747
+ // desiredMask) == desired) and put the filtered data into shared memory.
748
+ // 4. None of the above. Data does not fit into shared memory. We return. The
749
+ // situation
750
+ // may change in the next iteration.
751
+ template <typename scalar_t, typename bitwise_t, typename index_t>
752
+ __device__ __forceinline__ void fillDataSmem(
753
+ scalar_t* dataSmem, // shared memory to store the input data.
754
+ index_t
755
+ dataSmemCap, // max number of elements that can be stored in dataSmem.
756
+ index_t
757
+ dataSizeRemaining, // number of relevant elements remaining. We put data
758
+ // on dataSmem once dataSizeRemaining <= dataSmemCap.
759
+ index_t& dataSmemSize, // actual number of elements in dataSmem.
760
+ index_t sliceSize, // size of the input slice.
761
+ index_t withinSliceStride, // stride of the input slice.
762
+ const scalar_t* data, // input data.
763
+ bitwise_t
764
+ desired, // combined with desiredMask to filter relevant elements. An
765
+ // element is relevant if ((val & desiredMask) == desired).
766
+ bitwise_t
767
+ desiredMask, // combined with desired to filter relevant elements. An
768
+ // element is relevant if ((val & desiredMask) == desired).
769
+ int& DataSmemWriteIndex // index used to write data to dataSmem. Incremented
770
+ // atomically. Shared by all threads in the block.
771
+ ) {
772
+ if (dataSmemSize > 0)
773
+ return; // already filled
774
+
775
+ if (sliceSize <= dataSmemCap) { // if the input data is small enough, put all
776
+ // of it into shared memory.
777
+
778
+ // reading from global memory. Prefetching to improve performance.
779
+ scalar_t v = static_cast<scalar_t>(0);
780
+ if (threadIdx.x < sliceSize)
781
+ v = doLdg(&data[threadIdx.x * withinSliceStride]);
782
+ for (index_t i = threadIdx.x; i < sliceSize; i += blockDim.x) {
783
+ scalar_t v_next = (i + blockDim.x) < sliceSize
784
+ ? doLdg(&data[(i + blockDim.x) * withinSliceStride])
785
+ : static_cast<scalar_t>(0);
786
+ dataSmem[i] = v;
787
+ v = v_next; // closing the prefetching loop.
788
+ }
789
+
790
+ __syncthreads(); // wait for all threads in the block to finish writing to
791
+ // dataSmem.
792
+
793
+ if (threadIdx.x == 0) {
794
+ dataSmemSize = sliceSize; // thread 0 updates dataSmemSize to the size of
795
+ // the input slice.
796
+ }
797
+
798
+ __syncthreads(); // wait for all threads in the block to see the updated
799
+ // dataSmemSize.
800
+
801
+ } else if (dataSizeRemaining <= dataSmemCap) { // if data did not fit
802
+ // originally, but now it does.
803
+ // if this is the case, data needs to be filtered so only the relevant data
804
+ // is stored in dataSmem. Each warp performs an internal counting of the
805
+ // number of elements that match the desired pattern. Then reserves slots in
806
+ // dataSmem for the matching elements by atomically incrementing
807
+ // DataSmemWriteIndex. Finally, each thread within the warp writes its value
808
+ // to the appropriate slot in dataSmem. This is done to minimize the amount
809
+ // of time each warp spends waiting for others.
810
+
811
+ int lane_id = at::cuda::getLaneId(); // = threadIdx.x % WARP_SIZE
812
+
813
+ // prefetching from global memory.
814
+ scalar_t v = threadIdx.x < sliceSize
815
+ ? doLdg(&data[threadIdx.x * withinSliceStride])
816
+ : static_cast<scalar_t>(0);
817
+
818
+ for (index_t i = threadIdx.x; i < sliceSize;
819
+ i += blockDim.x) {
820
+ scalar_t v_next = (i + blockDim.x) < sliceSize
821
+ ? doLdg(&data[(i + blockDim.x) * withinSliceStride])
822
+ : static_cast<scalar_t>(0);
823
+
824
+ bool match =
825
+ (TopKTypeConfig<scalar_t>::convert(v) & desiredMask) == desired;
826
+
827
+ // Warp-level ballot
828
+ uint64_t ballot = WARP_BALLOT(
829
+ match); // what threads in this warp match the desired pattern?
830
+ int warp_count = __popcll(
831
+ ballot); // how many threads in this warp match the desired pattern?
832
+
833
+ int warp_base = 0; // base index to write data to dataSmem shared by all
834
+ // threads in the warp.
835
+ if (lane_id == 0 &&
836
+ warp_count >
837
+ 0) { // warp_count > 0 means there are matching elements in this
838
+ // warp. Only thread 0 in the warp needs to do this.
839
+ warp_base = atomicAdd(
840
+ &DataSmemWriteIndex,
841
+ warp_count); // reserve warp_count slots in dataSmem for this warp,
842
+ // and get the base index.
843
+ }
844
+ warp_base = __shfl(
845
+ warp_base, 0); // broadcast the warp_base to all threads in the warp.
846
+
847
+ if (match) { // if the current thread has a matching value, store the
848
+ // value in dataSmem.
849
+ uint64_t my_mask =
850
+ (1ULL << lane_id) - 1; // a bitmask: [0, 0, 0, ..., 0, 1, 1, 1, ...,
851
+ // 1] with (64-lane_id) 0s and lane_id 1s.
852
+ int my_offset = __popcll(
853
+ ballot & my_mask); // count the number of threads that have matches
854
+ // to the right of the current thread in bitmask.
855
+ dataSmem[warp_base + my_offset] = v; // store the value in dataSmem.
856
+ }
857
+
858
+ v = v_next; // closing the prefetching loop.
859
+ }
860
+
861
+ __syncthreads(); // wait for all threads in the block to finish writing to
862
+ // dataSmem.
863
+
864
+ if (threadIdx.x == 0) {
865
+ dataSmemSize = DataSmemWriteIndex; // thread 0 updates dataSmemSize to the
866
+ // number of elements in dataSmem.
867
+ }
868
+
869
+ __syncthreads(); // all threads in the block wait for dataSmemSize to be
870
+ // updated.
871
+ }
872
+ }
873
+
874
+ #endif
875
+
876
+ // Returns the top-Kth element found in the data using radix selection
877
+ template <typename scalar_t, typename bitwise_t, typename index_t>
878
+ __device__ void radixSelect(
879
+ const scalar_t* data,
880
+ index_t k,
881
+ bool largest,
882
+ index_t sliceSize,
883
+ index_t withinSliceStride,
884
+ index_t* smem,
885
+ scalar_t* topK) {
886
+ // Per-thread buckets into which we accumulate digit counts in our
887
+ // radix
888
+ //
889
+ // counts must be index_t to safely handle sliceSize > INT_MAX.
890
+ index_t counts[RADIX_SIZE];
891
+
892
+ #ifdef USE_ROCM
893
+
894
+ // this kernel reads all the data at most (sizeof(scalar_t)*2/RADIX_BITS + 1)
895
+ // times. if data fits into shared memory, we can avoid reading data from
896
+ // global memory. if not, we may still be able to put the filtered data, after
897
+ // a few iterations, into shared memory. after every pass, relevant data is
898
+ // likely reduced by a factor of RADIX_SIZE. dataSmem is used to store the
899
+ // relevant data.
900
+ constexpr index_t DATA_SMEM_BYTES = 3 *
901
+ 1024; // 3KB is a good compromise between memory usage and performance.
902
+ constexpr index_t dataSmemCap =
903
+ DATA_SMEM_BYTES /
904
+ sizeof(
905
+ scalar_t); // max number of elements that can be stored in dataSmem.
906
+ __shared__ scalar_t dataSmem[dataSmemCap];
907
+ __shared__ index_t dataSmemSize; // actual number of elements in dataSmem.
908
+ __shared__ index_t
909
+ dataSizeRemaining; // number of relevant elements remaining. We put data
910
+ // on dataSmem once dataSizeRemaining <= dataSmemCap.
911
+ __shared__ int DataSmemWriteIndex; // index used to write data to dataSmem.
912
+
913
+ if (threadIdx.x == 0) {
914
+ dataSmemSize = 0;
915
+ DataSmemWriteIndex = 0;
916
+ dataSizeRemaining = sliceSize;
917
+ }
918
+
919
+ __syncthreads(); // so the initialization is visible to all threads in the
920
+ // blocks.
921
+
922
+ // buffer index for smem. We use two segments of smem for inter-warp communication of counts.
923
+ // Given the counting operation in countRadixUsingMaskDataSmem performs __syncthreads() internally,
924
+ // we need to alternate between the at most two segments of smem to avoid race conditions.
925
+ // No more than two iterations of the loop will be "in flight" at any given time because
926
+ // of the __syncthreads() in countRadixUsingMaskDataSmem.
927
+ // buffer_index is either 0 or 1. It is toggled after each countRadixUsingMaskDataSmem invocation.
928
+ int buffer_index = 0;
929
+
930
+ #endif
931
+
932
+ // We only consider elements x such that (x & desiredMask) == desired
933
+ // Initially, we consider all elements of the array, so the above
934
+ // statement is true regardless of input.
935
+ bitwise_t desired = 0;
936
+ bitwise_t desiredMask = 0;
937
+
938
+ // We are looking for the top kToFind-th element when iterating over
939
+ // digits; this count gets reduced by elimination when counting
940
+ // successive digits
941
+ index_t kToFind = k;
942
+
943
+ // We start at the most significant digit in our radix, scanning
944
+ // through to the least significant digit
945
+ for (int digitPos = sizeof(scalar_t) * 8 - RADIX_BITS; digitPos >= 0;
946
+ digitPos -= RADIX_BITS) {
947
+ // Count radix distribution for the current position and reduce
948
+ // across all threads
949
+
950
+ #ifdef USE_ROCM
951
+
952
+ // fill dataSmem with the input data if not already filled.
953
+ fillDataSmem<scalar_t, bitwise_t, index_t>(
954
+ dataSmem,
955
+ dataSmemCap,
956
+ dataSizeRemaining,
957
+ dataSmemSize,
958
+ sliceSize,
959
+ withinSliceStride,
960
+ data,
961
+ desired,
962
+ desiredMask,
963
+ DataSmemWriteIndex);
964
+
965
+ // count the distribution of the bits in the radix digit at `digitPos` to
966
+ // `digitPos`+RADIX_BITS-1
967
+ countRadixUsingMaskDataSmem<
968
+ scalar_t,
969
+ bitwise_t,
970
+ index_t,
971
+ index_t,
972
+ RADIX_SIZE,
973
+ RADIX_BITS>(
974
+ counts,
975
+ smem,
976
+ buffer_index,
977
+ desired,
978
+ desiredMask,
979
+ digitPos,
980
+ sliceSize,
981
+ withinSliceStride,
982
+ data,
983
+ dataSmem,
984
+ dataSmemSize);
985
+
986
+ buffer_index ^= 1; // toggle buffer index.
987
+
988
+ #else
989
+ countRadixUsingMask<
990
+ scalar_t,
991
+ bitwise_t,
992
+ index_t,
993
+ index_t,
994
+ RADIX_SIZE,
995
+ RADIX_BITS>(
996
+ counts,
997
+ smem,
998
+ desired,
999
+ desiredMask,
1000
+ digitPos,
1001
+ sliceSize,
1002
+ withinSliceStride,
1003
+ data);
1004
+
1005
+ #endif
1006
+ auto found_unique = [&](int i, index_t count) -> bool {
1007
+ /* All threads have the same value in counts here, so all */
1008
+ /* threads will return from the function. */
1009
+ if (count == 1 && kToFind == 1) {
1010
+ /* There is a unique answer. */
1011
+ desired = at::cuda::Bitfield<bitwise_t>::setBitfield(
1012
+ desired, i, digitPos, RADIX_BITS);
1013
+ desiredMask = at::cuda::Bitfield<bitwise_t>::setBitfield(
1014
+ desiredMask, RADIX_MASK, digitPos, RADIX_BITS);
1015
+
1016
+ /* The answer is now the unique element v such that: */
1017
+ /* (v & desiredMask) == desired */
1018
+ /* However, we do not yet know what the actual element is. We */
1019
+ /* need to perform a search through the data to find the */
1020
+ /* element that matches this pattern. */
1021
+
1022
+ #ifndef USE_ROCM
1023
+
1024
+ *topK = findPattern<scalar_t, bitwise_t, index_t>(
1025
+ (scalar_t*)smem,
1026
+ data,
1027
+ sliceSize,
1028
+ withinSliceStride,
1029
+ desired,
1030
+ desiredMask);
1031
+
1032
+ #else
1033
+ // find the unique value that matches the desired pattern
1034
+ *topK = findPatternDataSmem<scalar_t, bitwise_t, index_t>(
1035
+ (scalar_t*)smem,
1036
+ data,
1037
+ sliceSize,
1038
+ withinSliceStride,
1039
+ desired,
1040
+ desiredMask,
1041
+ dataSmem,
1042
+ dataSmemSize);
1043
+ #endif
1044
+ return true;
1045
+ }
1046
+ return false;
1047
+ };
1048
+ auto found_non_unique = [&](int i, index_t count) -> bool {
1049
+ if (count >= kToFind) {
1050
+ desired = at::cuda::Bitfield<bitwise_t>::setBitfield(
1051
+ desired, i, digitPos, RADIX_BITS);
1052
+ desiredMask = at::cuda::Bitfield<bitwise_t>::setBitfield(
1053
+ desiredMask, RADIX_MASK, digitPos, RADIX_BITS);
1054
+
1055
+ #ifdef USE_ROCM
1056
+ if (dataSmemSize == 0) { // we only care about updating
1057
+ // dataSizeRemaining when dataSmem is empty.
1058
+ if (threadIdx.x == 0) {
1059
+ // this bucket has count >= kToFind elements. This means topK is in
1060
+ // this bucket and the number of elements with value & desiredMask
1061
+ // == desired (which is the relevant data) equals count. so we
1062
+ // update dataSizeRemaining to count.
1063
+ dataSizeRemaining = count;
1064
+ }
1065
+ __syncthreads();
1066
+ }
1067
+ #endif
1068
+ /* The top-Kth element v must now be one such that: */
1069
+ /* (v & desiredMask == desired) */
1070
+ /* but we haven't narrowed it down; we must check the next */
1071
+ /* least-significant digit */
1072
+ return true;
1073
+ }
1074
+ kToFind -= count;
1075
+ return false; // continue the loop
1076
+ };
1077
+
1078
+ // All threads participate in the comparisons below to know the
1079
+ // final result
1080
+ if (largest) {
1081
+ // Process in descending order
1082
+ #pragma unroll
1083
+ for (int i = RADIX_SIZE - 1; i >= 0; --i) {
1084
+ index_t count = counts[i];
1085
+ if (found_unique(i, count)) {
1086
+ return;
1087
+ }
1088
+ if (found_non_unique(i, count)) {
1089
+ break;
1090
+ }
1091
+ }
1092
+ } else {
1093
+ // Process in ascending order
1094
+ #pragma unroll
1095
+ for (int i = 0; i < RADIX_SIZE; ++i) {
1096
+ index_t count = counts[i];
1097
+ if (found_unique(i, count)) {
1098
+ return;
1099
+ }
1100
+ if (found_non_unique(i, count)) {
1101
+ break;
1102
+ }
1103
+ }
1104
+ }
1105
+ } // end digitPos for
1106
+
1107
+ // There is no unique result, but there is a non-unique result
1108
+ // matching `desired` exactly
1109
+ *topK = TopKTypeConfig<scalar_t>::deconvert(desired);
1110
+ }
1111
+ } // namespace at::native
1112
+
1113
+ #else
1114
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1115
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorModeKernel.cuh ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/cuda/detail/IndexUtils.cuh>
5
+ #include <ATen/native/cuda/Loops.cuh>
6
+ #include <ATen/native/cuda/SortingCommon.cuh>
7
+ #include <ATen/native/cuda/block_reduce.cuh>
8
+
9
+ namespace at::native {
10
+
11
+ // Used for a segmented reduction
12
+ struct ModeUnsignedBoolPair {
13
+ unsigned int val;
14
+ bool flag;
15
+ };
16
+
17
+ // In the kernel below, we have a common pattern of reducing (unsigned int,
18
+ // unsigned int) pairs of data
19
+ struct ModeUnsignedPair {
20
+ unsigned int val;
21
+ unsigned int index;
22
+ };
23
+
24
+ // Inclusive Scan via an upsweep/downsweep mechanism. Assumes:
25
+ //
26
+ // 1. Power2ScanSize is a power of 2. This code still works for collections that
27
+ // do not exactly contain a power of 2 number of elements, simply round up to
28
+ // the nearest power of 2 and then call.
29
+ //
30
+ // 2. That there are two-elements per thread, i.e. the size of the smem storage
31
+ // is 2 * blockDim.x * sizeof(T).
32
+ //
33
+ // Consider a (+)-Scan on the following elements:
34
+ //
35
+ // Upsweep:
36
+ //
37
+ // 0 1 2 3 4 5 6 7
38
+ // 1 5 9 13
39
+ // 6 22
40
+ // 28
41
+ //
42
+ // Downsweep:
43
+ // 15
44
+ // 3 10 21
45
+ template <int Power2ScanSize, typename T, class BinaryOp>
46
+ __device__ void inclusivePrefixScan(T* smem, BinaryOp binop) {
47
+ // Reduce step ("upsweep")
48
+ #pragma unroll
49
+ for (int stride = 1; stride < Power2ScanSize; stride <<= 1) {
50
+ int index = (threadIdx.x + 1) * stride * 2 - 1;
51
+ if (index < Power2ScanSize) {
52
+ smem[index] = binop(smem[index], smem[index - stride]);
53
+ }
54
+ __syncthreads();
55
+ }
56
+
57
+ // Post-reduce step ("downsweep")
58
+ #pragma unroll
59
+ for (int stride = Power2ScanSize / 4; stride > 0; stride >>= 1) {
60
+ int index = (threadIdx.x + 1) * stride * 2 - 1;
61
+ if ((index + stride) < Power2ScanSize) {
62
+ smem[index + stride] = binop(smem[index + stride], smem[index]);
63
+ }
64
+ __syncthreads();
65
+ }
66
+ }
67
+
68
+ // Block-wide reduction where each thread locally reduces N
69
+ // values before letting a single warp take over - assumes
70
+ // threadVals is in registers, not shared memory
71
+ //
72
+ // If smem is not used again, there is no need to __syncthreads before this
73
+ // call. However, if smem will be used, e.g., this function is called in a loop,
74
+ // then __syncthreads is needed either before or afterwards to prevent non-0
75
+ // threads overriding smem in the next loop before num-0 thread reads from it.
76
+ template <int N, typename T, typename ReduceOp>
77
+ __device__ T reduceBlockWithNThreadLocalReductions(
78
+ T* smem,
79
+ T threadVals[N],
80
+ const unsigned int numVals,
81
+ ReduceOp reduceOp,
82
+ T init) {
83
+ int offset = threadIdx.x * N;
84
+ T local = offset < numVals ? threadVals[0] : init;
85
+
86
+ #pragma unroll
87
+ for (int i = 1; i < N; ++i) {
88
+ ++offset;
89
+ T next = offset < numVals ? threadVals[i] : init;
90
+ local = reduceOp.combine(local, next);
91
+ }
92
+
93
+ return cuda_utils::BlockReduce(local, reduceOp, init, smem);
94
+ }
95
+
96
+ template <typename T>
97
+ __device__ inline void swapVars(T& t1, T& t2) {
98
+ T tmp = t1;
99
+ t1 = t2;
100
+ t2 = tmp;
101
+ }
102
+
103
+ template <typename Comparator, typename K, typename V>
104
+ __device__ inline void bitonicSwap(
105
+ K& kA,
106
+ V& vA,
107
+ bool& validA,
108
+ K& kB,
109
+ V& vB,
110
+ bool& validB,
111
+ bool dir,
112
+ const Comparator& comp) {
113
+ // Invalid entries always sort to the end
114
+ bool swap = (comp(kA, kB) && validA) || !validB;
115
+ if (swap == dir) {
116
+ swapVars(kA, kB);
117
+ swapVars(vA, vB);
118
+ swapVars(validA, validB);
119
+ }
120
+ };
121
+
122
+ template <typename Comparator, typename K>
123
+ __device__ inline void bitonicSwapKeys(
124
+ K& kA,
125
+ bool& validA,
126
+ K& kB,
127
+ bool& validB,
128
+ bool dir,
129
+ const Comparator& comp) {
130
+ bool swap = (comp(kA, kB) && validA) || !validB;
131
+ if (swap == dir) {
132
+ swapVars(kA, kB);
133
+ swapVars(validA, validB);
134
+ }
135
+ }
136
+
137
+ template <
138
+ typename K,
139
+ typename IndexType,
140
+ int Power2SortSize,
141
+ typename Comparator>
142
+ __device__ inline void bitonicSortKeys(
143
+ K keys[Power2SortSize],
144
+ bool valid[Power2SortSize],
145
+ const Comparator& comp) {
146
+ #if !defined(USE_ROCM)
147
+ #pragma unroll
148
+ #endif
149
+ for (unsigned int size = 2; size < Power2SortSize; size *= 2) {
150
+ bool flag = ((threadIdx.x & (size / 2)) != 0);
151
+
152
+ #if !defined(USE_ROCM)
153
+ #pragma unroll
154
+ #endif
155
+ for (unsigned int stride = size / 2; stride > 0; stride /= 2) {
156
+ __syncthreads();
157
+
158
+ unsigned int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1));
159
+ bitonicSwapKeys<Comparator, K>(
160
+ keys[pos],
161
+ valid[pos],
162
+ keys[pos + stride],
163
+ valid[pos + stride],
164
+ flag,
165
+ comp);
166
+ }
167
+ }
168
+
169
+ #if !defined(USE_ROCM)
170
+ #pragma unroll
171
+ #endif
172
+ for (unsigned int stride = Power2SortSize / 2; stride > 0; stride /= 2) {
173
+ __syncthreads();
174
+
175
+ unsigned int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1));
176
+ bitonicSwapKeys<Comparator, K>(
177
+ keys[pos],
178
+ valid[pos],
179
+ keys[pos + stride],
180
+ valid[pos + stride],
181
+ false,
182
+ comp);
183
+ }
184
+
185
+ __syncthreads();
186
+ }
187
+
188
+ // The mode kernel has the following characteristics: It uses internal shared
189
+ // memory buffers of Power2Size, which must be greater than the number of
190
+ // elements. Additionally, there is one block for every slice to calculate the
191
+ // mode for, and in each block there is one thread for every two elements.
192
+ //
193
+ // Both sorted and positions are assumed to be contiguous Tensors with the mode
194
+ // dimension as the innermost dim, such that we can get the particular slice for
195
+ // a Tensor via its linear block dimension * the slice size.
196
+ template <typename T, unsigned int Power2Size>
197
+ __launch_bounds__(1024, 1)
198
+ __global__ void compute_mode(
199
+ const T* input,
200
+ at::cuda::detail::TensorInfo<T, unsigned int> values,
201
+ at::cuda::detail::TensorInfo<int64_t, unsigned int> indices,
202
+ int64_t sliceSize,
203
+ int64_t slices) {
204
+ int tidx = threadIdx.x;
205
+ int stidx = blockDim.x + threadIdx.x; // Second index this thread responsible for
206
+
207
+ // First, we need to calculate the offset into the sorted Tensor that
208
+ // represents the start of the slice for this block to calculate the mode for.
209
+ // This offset is a combination of the gridIndices, and the number of elements
210
+ // in the slice.
211
+ unsigned int blockId = getLinearBlockId<unsigned int>();
212
+ unsigned int linearOffset = blockId * sliceSize;
213
+
214
+ if (blockId >= slices) {
215
+ return;
216
+ }
217
+
218
+ // shmem is a dynamically sized buffer we will use throughout the kernel to
219
+ // handle computation efficiently. The size of this shmem must be
220
+ // sizeof(T) * Power2Size + (2 * sizeof(unsigned int) * Power2Size)
221
+ //
222
+ // Initially, the buffer will be organized as follows:
223
+ //
224
+ // [smem (slice elements) | bmem (valid indices) | <scratch space>]
225
+ extern __shared__ char shmem[];
226
+
227
+ // smem represents a proportion of the shared memory buffer that is used to
228
+ // store the elements from the slice:
229
+ T* smem = reinterpret_cast<T*>(shmem);
230
+
231
+ // Each thread loads up to two elements from the Tensor into shared memory
232
+ if (tidx < sliceSize) {
233
+ smem[tidx] = c10::load(&input[linearOffset + tidx]);
234
+ }
235
+ if (stidx < sliceSize) {
236
+ smem[stidx] = c10::load(&input[linearOffset + stidx]);
237
+ }
238
+
239
+ // Next, we initialize a boolean region of the buffer, offset by the loaded
240
+ // element smem region
241
+ bool* bmem = reinterpret_cast<bool*>(&smem[Power2Size]);
242
+
243
+ // The first use of this region stores bmem[i] = i < sliceSize to mark the
244
+ // valid components in the smem buffer
245
+ bmem[tidx] = tidx < sliceSize;
246
+ bmem[stidx] = stidx < sliceSize;
247
+ __syncthreads(); // barrier for smem, bmem initialization
248
+
249
+ // First, sort the input slice in ascending order. smem contains the input
250
+ // elements, and bmem marks the valid indices
251
+ bitonicSortKeys<T, unsigned int, Power2Size>(
252
+ smem, bmem, [&] GPU_LAMBDA(const auto& a, const auto& b) {
253
+ return a < b;
254
+ });
255
+ __syncthreads(); // make no assumptions that the sort syncs at end
256
+
257
+ // The next step of our algorithm is performing a block-wide comparison of
258
+ // neighboring elements. In particular, given an sorted input slice A, we
259
+ // produce an output slice B, such that B[i] = 1 if A[i-i] != A[i], otherwise
260
+ // 0.
261
+ //
262
+ // Given the input A = [0, 0, 1, 1, 2, 2, 2, 4, 5, 6, 6, 7, 8]
263
+ // B = [1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1]
264
+ //
265
+ // In particular, we can think of B[i] true indicating the start of a sequence
266
+ // of equal values in the sorted list. Similarly, we will also store the
267
+ // negation of B, which we'll call C. In particular, we can think of C[i] =
268
+ // true iff A[i-1] == A[i] in our original sorted slice.
269
+ //
270
+ // C = [0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
271
+
272
+ // We overwrite bmem, and treat the rest of shared memory as a buffer of
273
+ // (index, flag) pairs where the index represents values from C, and the flag
274
+ // represents values from B.
275
+ //
276
+ // [smem (sorted slice) | ubpmem (index, flag pairs)]
277
+
278
+ struct ModeUnsignedBoolPair* ubpmem =
279
+ reinterpret_cast<struct ModeUnsignedBoolPair*>(&smem[Power2Size]);
280
+
281
+ if (tidx == 0) {
282
+ ubpmem[0].flag = true;
283
+ ubpmem[0].val = 0;
284
+ }
285
+
286
+ // Compares elements (0, 1), (2, 3), ... and sets 1, 3, ...
287
+ ubpmem[tidx * 2 + 1].flag =
288
+ smem[tidx * 2] != smem[tidx * 2 + 1]; // (0, 1), (1, 2), etc.
289
+ ubpmem[tidx * 2 + 1].val = !ubpmem[tidx * 2 + 1].flag;
290
+
291
+ // Compares elements (1, 2), (3, 4), ... and sets 2, 4, ...
292
+ if (((tidx + 1) * 2) < Power2Size) {
293
+ ubpmem[(tidx + 1) * 2].flag =
294
+ smem[((tidx + 1) * 2) - 1] != smem[(tidx + 1) * 2];
295
+ ubpmem[(tidx + 1) * 2].val = !ubpmem[(tidx + 1) * 2].flag;
296
+ }
297
+ __syncthreads(); // barrier for ubpmem initialization
298
+
299
+ // Next, we perform a segmented prefix sum on the neighboring elements, where
300
+ // the presence of a one indicates the start of a segment. In this case B acts
301
+ // as the segment start flags, and C is the buffer to be summed:
302
+ //
303
+ // Input (C) = [0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
304
+ // Flag (B) = [1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1]
305
+ // Output (C) = [0, 1, 0, 1, 0, 1, 2, 0, 0, 0, 1, 0, 0]
306
+ //
307
+ // Afterwards, the (index) components of the ubpmem buffer contain the lengths
308
+ // of the segments (minus 1), i.e. the counts of each element in the original
309
+ // input.
310
+ inclusivePrefixScan<Power2Size>(
311
+ ubpmem, [=] GPU_LAMBDA(const auto& a, const auto& b) {
312
+ ModeUnsignedBoolPair c;
313
+ c.val = a.flag ? a.val : a.val + b.val;
314
+ c.flag = a.flag | b.flag;
315
+ return c;
316
+ });
317
+ // assumes scan syncs at the end
318
+
319
+ // Next, we reinterpret the ubpmem buffer as pairs of unsigned integers (i.e.
320
+ // we treat the boolean flag regions as integers). We initialize these to
321
+ // represent indices, and we'll call this buffer I
322
+ struct ModeUnsignedPair* uupmem =
323
+ reinterpret_cast<struct ModeUnsignedPair*>(ubpmem);
324
+
325
+ // At this point, we need to find the maximum element in lengths buffer C.
326
+ // This element will represent the count (-1) of the mode. Because of the
327
+ // way we have set up the problem, the index where this mode occurs will
328
+ // also be the location of the mode value in the sorted array, e.g.
329
+ //
330
+ // smem = [0, 0, 1, 1, 1, 2]
331
+ // C = [0, 1, 0, 1, 2, 0]
332
+ // I = [0, 1, 2, 3, 4, 5]
333
+ // ^
334
+ // maximum value, also aligned with mode = 1
335
+ //
336
+ // We perform a block wide max-reduction of the C buffer, but we also need the
337
+ // indices to come along with it, so we utilize the uupmem construction.
338
+ //
339
+ // At the end we need to return the ModeUnsignedPair containing index = 4, val
340
+ // = 2, which represents the max
341
+
342
+ // In practice, we will make each thread locally reduce 2 values in its
343
+ // registers prior to the global block-wide reduction. Note that instead of
344
+ // tidx/stidx, we utilize tidx * 2, tidx * 2 + 1, so each thread deals with
345
+ // adjacent elements. This is because the reduce code below relies on thread
346
+ // elements to be adjacent.
347
+ struct ModeUnsignedPair uup[2];
348
+ uup[0].index = tidx * 2;
349
+ uup[0].val = ubpmem[tidx * 2].val;
350
+ uup[1].index = tidx * 2 + 1;
351
+ uup[1].val = ubpmem[tidx * 2 + 1].val;
352
+ __syncthreads();
353
+
354
+ struct ModeUnsignedPair max = {0, 0};
355
+
356
+ struct MaxOp {
357
+ inline __device__ ModeUnsignedPair combine(ModeUnsignedPair a, ModeUnsignedPair b) const {
358
+ return b.val > a.val ? b : a;
359
+ }
360
+
361
+ inline __device__ ModeUnsignedPair warp_shfl_down(ModeUnsignedPair acc, int offset) const {
362
+ ModeUnsignedPair ret;
363
+ ret.index = WARP_SHFL_DOWN(acc.index, offset);
364
+ ret.val = WARP_SHFL_DOWN(acc.val, offset);
365
+ return ret;
366
+ }
367
+ } max_op;
368
+
369
+ max = reduceBlockWithNThreadLocalReductions<2>(
370
+ uupmem,
371
+ uup,
372
+ sliceSize,
373
+ max_op,
374
+ max);
375
+
376
+ // Store the mode in shared memory for use in finding the mode in the input
377
+ // slice
378
+ __shared__ T mode;
379
+
380
+ // Given the above constraints, the mode is the value at the reduced index in
381
+ // the original sorted element buffer
382
+ if (tidx == 0) {
383
+ mode = smem[max.index];
384
+ }
385
+ __syncthreads(); // broadcast mode
386
+
387
+ // Finally, we need to find "an" index of the mode in the input
388
+ // Tensor. The API does not constrain which index we pick, but here
389
+ // we always pick the largest index. We store the index if the value
390
+ // is the mode, or 0 otherwise. Then find the maximum value.
391
+ //
392
+ // Again we reduce 2 elements in the thread's registers prior to the
393
+ // block-wide reduction
394
+ unsigned mode_index[2] = {0u, 0u};
395
+ if (tidx * 2 < sliceSize) {
396
+ const unsigned idx = tidx * 2;
397
+ mode_index[0] = c10::load(&input[linearOffset + idx]) == mode ? idx : 0u;
398
+ }
399
+ if (tidx * 2 + 1 < sliceSize) {
400
+ const unsigned idx = tidx * 2 + 1;
401
+ mode_index[1] = c10::load(&input[linearOffset + idx]) == mode ? idx : 0u;
402
+ }
403
+
404
+ struct MaxIndexOp {
405
+ inline __device__ unsigned combine(unsigned a, unsigned b) const {
406
+ return b > a ? b : a;
407
+ }
408
+
409
+ inline __device__ unsigned warp_shfl_down(unsigned acc, int offset) const {
410
+ return WARP_SHFL_DOWN(acc, offset);
411
+ }
412
+ } max_index_op;
413
+
414
+ int64_t index = reduceBlockWithNThreadLocalReductions<2>(
415
+ reinterpret_cast<unsigned*>(&shmem[0]),
416
+ mode_index,
417
+ sliceSize,
418
+ max_index_op,
419
+ 0u);
420
+
421
+ // Finally, we have the mode, and an index where it occurs. We use a single
422
+ // thread to place this in the appropriate output position
423
+ if (tidx == 0) {
424
+ unsigned int outputOffset =
425
+ at::cuda::detail::IndexToOffset<T, unsigned int, -1>::get(
426
+ blockId, values);
427
+ values.data[outputOffset] = mode;
428
+ indices.data[outputOffset] = index;
429
+ }
430
+ }
431
+
432
+ } // namespace at::native
433
+
434
+ #else
435
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
436
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorModeKernel.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ void launch_fused_mode_kernel(
12
+ const TensorBase &values, const TensorBase &indices,
13
+ const TensorBase &self, int64_t slice_size, int64_t slices);
14
+
15
+ void launch_apply_mode_kernel(
16
+ const TensorBase &values, const TensorBase &indices,
17
+ const TensorBase &self, int64_t dim, int64_t ndim);
18
+
19
+ } // namespace at::native
20
+
21
+ #else
22
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
23
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/TensorTopK.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+ void launch_gather_topk_kernel(
11
+ const TensorBase& self,
12
+ int64_t k, int64_t dim, bool largest,
13
+ const TensorBase& values, const TensorBase& indices);
14
+ }
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.12/site-packages/torch/include/ATen/native/cuda/UniqueCub.cuh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <ATen/core/Tensor.h>
3
+
4
+ namespace at::native::internal {
5
+
6
+ template <typename scalar_t>
7
+ std::tuple<Tensor, Tensor, Tensor> unique_cuda_template(
8
+ const Tensor& self,
9
+ const bool consecutive,
10
+ const bool return_inverse,
11
+ const bool return_counts);
12
+
13
+ } // namespace at::native::internal
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.12/site-packages/torch/include/ATen/native/cuda/UpSample.cuh ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/TensorAccessor.h>
4
+ #include <ATen/cuda/Atomic.cuh>
5
+
6
+ #include <c10/util/ArrayRef.h>
7
+ #include <c10/util/SmallVector.h>
8
+ #include <c10/util/OptionalArrayRef.h>
9
+
10
+ #include <math.h>
11
+ #include <optional>
12
+
13
+ namespace at::native {
14
+
15
+ namespace upsample {
16
+ // TODO: Remove duplicate declaration.
17
+ TORCH_API c10::SmallVector<int64_t, 3> compute_output_size(
18
+ c10::IntArrayRef input_size, // Full input tensor size.
19
+ at::OptionalIntArrayRef output_size,
20
+ std::optional<c10::ArrayRef<double>> scale_factors);
21
+ } // namespace upsample
22
+
23
+ namespace upsample_cuda {
24
+
25
+ // TODO: Remove duplication with Upsample.h (CPU).
26
+ inline std::optional<double> get_scale_value(std::optional<c10::ArrayRef<double>> scales, int idx) {
27
+ if (!scales) {
28
+ return std::nullopt;
29
+ }
30
+ return scales->at(idx);
31
+ }
32
+
33
+ } // namespace upsample_cuda
34
+
35
+
36
+ /* TODO: move this to a common place */
37
+ template <typename scalar_t>
38
+ __device__ inline scalar_t min(scalar_t a, scalar_t b) {
39
+ return a < b ? a : b;
40
+ }
41
+
42
+ template <typename scalar_t>
43
+ __device__ inline scalar_t max(scalar_t a, scalar_t b) {
44
+ return a > b ? a : b;
45
+ }
46
+
47
+ // NOTE [ Nearest neighbor upsampling kernel implementation ]
48
+ //
49
+ // The nearest neighbor upsampling kernel implementation is symmetrical as
50
+ // expected. We launch kernels with threads mapping to destination tensors where
51
+ // kernels write data to, each thread reads data from the source tensor, this
52
+ // means:
53
+ // 1. In the forward kernel,
54
+ // src_xxx refers to properties of input tensors;
55
+ // dst_xxx refers to properties of output tensors;
56
+ // scale_factor is the ratio of src_size to dst_size;
57
+ // 2. In the backward kernel,
58
+ // src_xxx refers to properties of grad_output tensors;
59
+ // dst_xxx refers to properties of grad_input tensors;
60
+ // scale_factor is the ratio of src_size to dst_size;
61
+ //
62
+ // Because of this, we need to take the reciprocal of the scale defined by
63
+ // upsample layer during forward path. The motivation is to avoid slow
64
+ // division in the kernel code, so we can use faster multiplication instead.
65
+ // This is not necessary during backward path, since the scale_factor is already
66
+ // the reciprocal of corresponding scale_factor used in the forward path due to
67
+ // the swap of source and destination tensor.
68
+ //
69
+ // Similarly, since the mapping from grad_input to grad_output during backward
70
+ // is the reverse of the mapping of output to input, we need to have opposite
71
+ // mapping functions to compute the source index.
72
+
73
+ // see NOTE [ Nearest neighbor upsampling kernel implementation ]
74
+ template <typename accscalar_t>
75
+ __host__ __forceinline__ accscalar_t compute_scales_value(
76
+ const std::optional<double> scale,
77
+ int64_t src_size,
78
+ int64_t dst_size) {
79
+ // FIXME: remove magic > 0 after we ensure no models were serialized with -1 defaults.
80
+ return (scale.has_value() && scale.value() > 0.) ? (accscalar_t)(1.0 / scale.value())
81
+ : (accscalar_t)src_size / dst_size;
82
+ }
83
+
84
+ // see NOTE [ Nearest neighbor upsampling kernel implementation ]
85
+ template <typename accscalar_t>
86
+ __host__ __forceinline__ accscalar_t compute_scales_value_backwards(
87
+ const std::optional<double> scale,
88
+ int64_t src_size,
89
+ int64_t dst_size) {
90
+ // FIXME: remove magic > 0 after we ensure no models were serialized with -1 defaults.
91
+ return (scale.has_value() && scale.value() > 0.) ? (accscalar_t)scale.value()
92
+ : (accscalar_t)src_size / dst_size;
93
+ }
94
+
95
+ template <typename accscalar_t>
96
+ __host__ __forceinline__ accscalar_t area_pixel_compute_scale(
97
+ int input_size,
98
+ int output_size,
99
+ bool align_corners,
100
+ const std::optional<double> scale) {
101
+ if(align_corners) {
102
+ if(output_size > 1) {
103
+ return (accscalar_t)(input_size - 1) / (output_size - 1);
104
+ }
105
+ else {
106
+ return static_cast<accscalar_t>(0);
107
+ }
108
+ }
109
+ else{
110
+ return compute_scales_value<accscalar_t>(scale, input_size, output_size);
111
+ }
112
+ }
113
+
114
+ template <typename accscalar_t>
115
+ __device__ __forceinline__ accscalar_t area_pixel_compute_source_index(
116
+ accscalar_t scale,
117
+ int dst_index,
118
+ bool align_corners,
119
+ bool cubic) {
120
+ if (align_corners) {
121
+ return scale * dst_index;
122
+ } else {
123
+ accscalar_t src_idx = scale * (dst_index + static_cast<accscalar_t>(0.5)) -
124
+ static_cast<accscalar_t>(0.5);
125
+ // See Note[Follow Opencv resize logic]
126
+ return (!cubic && src_idx < static_cast<accscalar_t>(0))
127
+ ? static_cast<accscalar_t>(0)
128
+ : src_idx;
129
+ }
130
+ }
131
+
132
+ // see NOTE [ Nearest neighbor upsampling kernel implementation ]
133
+ __device__ __forceinline__ int nearest_neighbor_compute_source_index(
134
+ const float scale,
135
+ int dst_index,
136
+ int input_size) {
137
+ // index_f32 = (output_index) * scale
138
+ // input_index = round(index_f32)
139
+ // Same as a buggy OpenCV INTER_NEAREST
140
+ // We keep this method for BC and consider as deprecated.
141
+ // See nearest_neighbor_exact_compute_source_index as replacement
142
+ const int src_index =
143
+ min(static_cast<int>(floorf((dst_index) * scale)), input_size - 1);
144
+ return src_index;
145
+ }
146
+
147
+ __device__ __forceinline__ int nearest_neighbor_exact_compute_source_index(
148
+ const float scale,
149
+ int dst_index,
150
+ int input_size) {
151
+ // index_f32 = (output_index + 0.5) * scale - 0.5
152
+ // input_index = round(index_f32)
153
+ // Same as Pillow and Scikit-Image/Scipy ndi.zoom
154
+ const int src_index =
155
+ min(static_cast<int>(floorf((dst_index + static_cast<float>(0.5)) * scale)), input_size - 1);
156
+ return src_index;
157
+ }
158
+
159
+ // see NOTE [ Nearest neighbor upsampling kernel implementation ]
160
+ __device__ __forceinline__ int nearest_neighbor_bw_compute_source_index(
161
+ const float scale,
162
+ int dst_index,
163
+ int output_size) {
164
+ // Equivalent to buggy OpenCV INTER_NEAREST
165
+ // We keep this method for BC and consider as deprecated.
166
+ // See nearest_neighbor_exact_bw_compute_source_index as replacement
167
+ const int src_index =
168
+ min(static_cast<int>(ceilf(dst_index * scale)), output_size);
169
+ return src_index;
170
+ }
171
+
172
+ // see NOTE [ Nearest neighbor upsampling kernel implementation ]
173
+ __device__ __forceinline__ int nearest_neighbor_exact_bw_compute_source_index(
174
+ const float scale,
175
+ int dst_index,
176
+ int output_size) {
177
+ // Equivalent to Pillow and Scikit-Image/Scipy ndi.zoom
178
+ const int src_index =
179
+ min(static_cast<int>(ceilf(dst_index * scale - static_cast<float>(0.5))), output_size);
180
+ return src_index;
181
+ }
182
+
183
+ /* Used by UpSampleBicubic2d.cu */
184
+ template <typename scalar_t>
185
+ __device__ __forceinline__ scalar_t upsample_get_value_bounded(
186
+ const PackedTensorAccessor64<const scalar_t, 4>& data,
187
+ int batch,
188
+ int channel,
189
+ int height,
190
+ int width,
191
+ int y,
192
+ int x) {
193
+ int access_y = max(min(y, height - 1), 0);
194
+ int access_x = max(min(x, width - 1), 0);
195
+ return data[batch][channel][access_y][access_x];
196
+ }
197
+
198
+ /* Used by UpSampleBicubic2d.cu */
199
+ template <typename scalar_t, typename accscalar_t>
200
+ __device__ __forceinline__ void upsample_increment_value_bounded(
201
+ PackedTensorAccessor64<scalar_t, 4>& data,
202
+ int batch,
203
+ int channel,
204
+ int height,
205
+ int width,
206
+ int y,
207
+ int x,
208
+ accscalar_t value) {
209
+ int access_y = max(min(y, height - 1), 0);
210
+ int access_x = max(min(x, width - 1), 0);
211
+ /* TODO: result here is truncated to scalar_t,
212
+ check: https://github.com/pytorch/pytorch/pull/19630#discussion_r281426912
213
+ */
214
+ gpuAtomicAddNoReturn(
215
+ &data[batch][channel][access_y][access_x], static_cast<scalar_t>(value));
216
+ }
217
+
218
+ // Based on
219
+ // https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
220
+ template <typename accscalar_t>
221
+ __device__ __forceinline__ accscalar_t cubic_convolution1(
222
+ accscalar_t x,
223
+ accscalar_t A) {
224
+ return ((A + 2) * x - (A + 3)) * x * x + 1;
225
+ }
226
+
227
+ template <typename accscalar_t>
228
+ __device__ __forceinline__ accscalar_t cubic_convolution2(
229
+ accscalar_t x,
230
+ accscalar_t A) {
231
+ return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A;
232
+ }
233
+
234
+ template <typename accscalar_t>
235
+ __device__ __forceinline__ void get_cubic_upsampling_coefficients(
236
+ accscalar_t coeffs[4],
237
+ accscalar_t t) {
238
+ accscalar_t A = -0.75;
239
+
240
+ accscalar_t x1 = t;
241
+ coeffs[0] = cubic_convolution2<accscalar_t>(x1 + 1.0, A);
242
+ coeffs[1] = cubic_convolution1<accscalar_t>(x1, A);
243
+
244
+ // opposite coefficients
245
+ accscalar_t x2 = 1.0 - t;
246
+ coeffs[2] = cubic_convolution1<accscalar_t>(x2, A);
247
+ coeffs[3] = cubic_convolution2<accscalar_t>(x2 + 1.0, A);
248
+ }
249
+
250
+ template <typename scalar_t, typename accscalar_t>
251
+ __device__ __forceinline__ accscalar_t cubic_interp1d(
252
+ scalar_t x0,
253
+ scalar_t x1,
254
+ scalar_t x2,
255
+ scalar_t x3,
256
+ accscalar_t t) {
257
+ accscalar_t coeffs[4];
258
+ get_cubic_upsampling_coefficients<accscalar_t>(coeffs, t);
259
+
260
+ return x0 * coeffs[0] + x1 * coeffs[1] + x2 * coeffs[2] + x3 * coeffs[3];
261
+ }
262
+
263
+ namespace upsample_antialias {
264
+
265
+ // taken from
266
+ // https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/
267
+ // src/libImaging/Resample.c#L20-L29
268
+ struct BilinearFilterFunctor {
269
+
270
+ template <typename accscalar_t>
271
+ __device__ accscalar_t operator()(accscalar_t x) const {
272
+ if (x < 0) {
273
+ x = -x;
274
+ }
275
+ if (x < 1) {
276
+ return 1 - x;
277
+ }
278
+ return 0;
279
+ }
280
+
281
+ static constexpr int size = 2;
282
+ };
283
+
284
+ // taken from
285
+ // https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/
286
+ // src/libImaging/Resample.c#L46-L62
287
+ struct BicubicFilterFunctor {
288
+
289
+ template <typename accscalar_t>
290
+ __device__ accscalar_t operator()(accscalar_t x) const {
291
+ // https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
292
+ const accscalar_t a = -0.5;
293
+ if (x < 0) {
294
+ x = -x;
295
+ }
296
+ if (x < 1) {
297
+ return ((a + 2) * x - (a + 3)) * x * x + 1;
298
+ }
299
+ if (x < 2) {
300
+ return (((x - 5) * x + 8) * x - 4) * a;
301
+ }
302
+ return 0;
303
+ }
304
+
305
+ static constexpr int size = 4;
306
+ };
307
+
308
+ template <typename accscalar_t>
309
+ __device__ __forceinline__ void _compute_weights_span(
310
+ const int i,
311
+ const int input_size,
312
+ const accscalar_t scale,
313
+ const accscalar_t support,
314
+ int& xmin,
315
+ int& xsize,
316
+ accscalar_t& center) {
317
+ center = scale * (i + static_cast<accscalar_t>(0.5));
318
+ xmin = max(static_cast<int>(center - support + static_cast<accscalar_t>(0.5)), static_cast<int>(0));
319
+ xsize = min(static_cast<int>(center + support + static_cast<accscalar_t>(0.5)), input_size) - xmin;
320
+ }
321
+
322
+ template <typename scalar_t, typename accscalar_t, typename interp_filter_t>
323
+ __device__ __forceinline__ void _compute_weights(
324
+ scalar_t* wt_ptr,
325
+ const accscalar_t scale,
326
+ int interp_size,
327
+ const interp_filter_t& interp_filter,
328
+ accscalar_t xmin_m_center,
329
+ int xsize) {
330
+
331
+ accscalar_t invscale = (scale >= 1.0) ? 1.0 / scale : 1.0;
332
+ accscalar_t total_w = 0.0;
333
+ int j = 0;
334
+ for (j = 0; j < xsize; j++) {
335
+ accscalar_t w = interp_filter((j + xmin_m_center + static_cast<accscalar_t>(0.5)) * invscale);
336
+ wt_ptr[j] = static_cast<scalar_t>(w);
337
+ total_w += w;
338
+ }
339
+ for (j = 0; j < xsize; j++) {
340
+ if (total_w != 0.0) {
341
+ wt_ptr[j] /= total_w;
342
+ }
343
+ }
344
+ for (; j < interp_size; j++) {
345
+ wt_ptr[j] = static_cast<scalar_t>(0.0);
346
+ }
347
+ }
348
+
349
+ template <typename scalar_t, typename accscalar_t>
350
+ __device__ __forceinline__ accscalar_t interpolate_aa_single_dim(
351
+ const scalar_t* src,
352
+ const scalar_t* weights,
353
+ int size) {
354
+ accscalar_t t = static_cast<accscalar_t>(*src);
355
+ accscalar_t wts = static_cast<accscalar_t>(weights[0]);
356
+ accscalar_t output = t * wts;
357
+
358
+ int j = 1;
359
+ for (; j < size; j++) {
360
+ wts = static_cast<accscalar_t>(weights[j]);
361
+ t = static_cast<accscalar_t>(*(src + j));
362
+ output += t * wts;
363
+ }
364
+ return output;
365
+ }
366
+
367
+ }
368
+
369
+ } // namespace at::native
370
+
371
+ #else
372
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
373
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/block_reduce.cuh ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/SharedReduceOps.h>
5
+ #include <ATen/cuda/DeviceUtils.cuh>
6
+
7
+ namespace at::native::cuda_utils {
8
+
9
+ constexpr int kCUDABlockReduceNumThreads = 512;
10
+ // Algorithmic limitation: BlockReduce does two WarpReduce calls, each
11
+ // of which reduces C10_WARP_SIZE elements. So, at most
12
+ // C10_WARP_SIZE**2 elements can be reduced at a time.
13
+ // NOTE: This is >= the max block size on current hardware anyway (1024).
14
+ // ROCm NOTE: C10_WARP_SIZE should only be used inside device functions,
15
+ // and kCUDABlockReduceMaxThreads is a host-side variable.
16
+ #ifdef USE_ROCM
17
+ static int kCUDABlockReduceMaxThreads() {
18
+ return at::cuda::warp_size() * at::cuda::warp_size();
19
+ }
20
+ #else
21
+ constexpr int kCUDABlockReduceMaxThreads() {
22
+ return C10_WARP_SIZE * C10_WARP_SIZE;
23
+ }
24
+ #endif
25
+
26
+ // Sums `val` across all threads in a warp.
27
+ //
28
+ // Assumptions:
29
+ // - The size of each block should be a multiple of `C10_WARP_SIZE`
30
+ template <typename T>
31
+ __inline__ __device__ T WarpReduceSum(T val) {
32
+ #pragma unroll
33
+ for (int offset = (C10_WARP_SIZE >> 1); offset > 0; offset >>= 1) {
34
+ val += WARP_SHFL_DOWN(val, offset);
35
+ }
36
+ return val;
37
+ }
38
+
39
+ // Picks the maximum `val` across all threads in a warp.
40
+ //
41
+ // Assumptions:
42
+ // - The size of each block should be a multiple of `C10_WARP_SIZE`
43
+ template <typename T>
44
+ __inline__ __device__ T WarpReduceMax(T val) {
45
+ #pragma unroll
46
+ for (int offset = (C10_WARP_SIZE >> 1); offset > 0; offset >>= 1) {
47
+ val = max_propagate_nan(val, WARP_SHFL_DOWN(val, offset));
48
+ }
49
+ return val;
50
+ }
51
+
52
+ struct Block1D {
53
+ static __forceinline__ __device__ int Tid() { return threadIdx.x; }
54
+
55
+ static __forceinline__ __device__ int Warps() {
56
+ return blockDim.x / C10_WARP_SIZE;
57
+ }
58
+ };
59
+
60
+ struct Block2D {
61
+ static __forceinline__ __device__ int Tid() {
62
+ return threadIdx.x + threadIdx.y * blockDim.x;
63
+ }
64
+
65
+ static __forceinline__ __device__ int Warps() {
66
+ return blockDim.x * blockDim.y / C10_WARP_SIZE;
67
+ }
68
+ };
69
+
70
+ // Sums `val` across all threads in a block.
71
+ //
72
+ // Warning: the return value is only valid for thread 0.
73
+ // Assumptions:
74
+ // - The size of each block should be a multiple of `C10_WARP_SIZE`
75
+ // - `shared` should be a pointer to shared memory with size of, at least,
76
+ // `sizeof(T) * number_of_warps`
77
+ template <typename T, typename B = Block1D>
78
+ __inline__ __device__ T BlockReduceSum(T val, T* shared) {
79
+ const int tid = B::Tid();
80
+ const int lid = tid % C10_WARP_SIZE;
81
+ const int wid = tid / C10_WARP_SIZE;
82
+ val = WarpReduceSum(val);
83
+ __syncthreads(); // prevent races when BlockReduces are called in a row.
84
+ if (lid == 0) {
85
+ shared[wid] = val;
86
+ }
87
+ __syncthreads();
88
+ val = (tid < B::Warps()) ? shared[lid] : T(0);
89
+ if (wid == 0) {
90
+ val = WarpReduceSum(val);
91
+ }
92
+ return val;
93
+ }
94
+
95
+ // Picks out the maximum `val` across all threads in a block.
96
+ //
97
+ // Warning: the return value is only valid for thread 0.
98
+ // Assumptions:
99
+ // - The size of each block should be a multiple of `C10_WARP_SIZE`
100
+ // - `shared` should be a pointer to shared memory with size of, at least,
101
+ // `sizeof(T) * number_of_warps`
102
+ template <typename T, typename B = Block1D>
103
+ __inline__ __device__ T BlockReduceMax(T val, T* shared) {
104
+ const int tid = B::Tid();
105
+ const int lid = tid % C10_WARP_SIZE;
106
+ const int wid = tid / C10_WARP_SIZE;
107
+ val = WarpReduceMax(val);
108
+ __syncthreads(); // prevent races when BlockReduces are called in a row.
109
+ if (lid == 0) {
110
+ shared[wid] = val;
111
+ }
112
+ __syncthreads();
113
+ val = (tid < B::Warps()) ? shared[lid] : T(std::numeric_limits<T>::lowest());
114
+ if (wid == 0) {
115
+ val = WarpReduceMax(val);
116
+ }
117
+ return val;
118
+ }
119
+
120
+ template <typename T, class ReduceOp>
121
+ __inline__ __device__ T WarpReduce(T val, const ReduceOp& op) {
122
+ #pragma unroll
123
+ for (int offset = (C10_WARP_SIZE >> 1); offset > 0; offset >>= 1) {
124
+ val = op.combine(val, op.warp_shfl_down(val, offset));
125
+ }
126
+ return val;
127
+ }
128
+
129
+ template <typename T, class ReduceOp, typename B = Block1D>
130
+ __inline__ __device__ T
131
+ BlockReduce(T val, const ReduceOp& op, const T& identity_element, T* shared) {
132
+ const int tid = B::Tid();
133
+ const int lid = tid % C10_WARP_SIZE;
134
+ const int wid = tid / C10_WARP_SIZE;
135
+ val = WarpReduce(val, op);
136
+ __syncthreads(); // prevent races when BlockReduces are called in a row.
137
+ if (lid == 0) {
138
+ shared[wid] = val;
139
+ }
140
+ __syncthreads();
141
+ val = (tid < B::Warps()) ? shared[lid] : identity_element;
142
+ if (wid == 0) {
143
+ val = WarpReduce(val, op);
144
+ }
145
+ return val;
146
+ }
147
+
148
+ } // namespace at::native::cuda_utils
149
+
150
+ #else
151
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
152
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/cuBlasCommonArgs.h ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+
6
+ namespace at::native {
7
+
8
+ using at::blas::ScalingType;
9
+ using at::blas::SwizzleType;
10
+
11
+ namespace {
12
+
13
+ // TODO: https://github.com/pytorch/pytorch/pull/59380#pullrequestreview-725310492
14
+ c10::MaybeOwned<Tensor> inline resolve_conj_if_indicated(const Tensor& tensor, bool resolve_conj) {
15
+ if (resolve_conj && tensor.is_conj()) {
16
+ return c10::MaybeOwned<Tensor>::owned(tensor.resolve_conj());
17
+ } else {
18
+ return c10::MaybeOwned<Tensor>::borrowed(tensor);
19
+ }
20
+ }
21
+
22
+ c10::MaybeOwned<Tensor> inline prepare_matrix_for_cublas(const Tensor& tensor, bool& transpose_tensor, bool transpose_result) {
23
+ if (tensor.is_non_overlapping_and_dense()) { // common case
24
+ transpose_tensor = tensor.is_contiguous();
25
+ return resolve_conj_if_indicated(tensor, transpose_result ? transpose_tensor : !transpose_tensor);
26
+ }
27
+ IntArrayRef tensor_strides = tensor.strides();
28
+ IntArrayRef tensor_sizes = tensor.sizes();
29
+ if ((tensor_strides[0] == 1) && (tensor_strides[1] >= std::max<int64_t>(1, tensor_sizes[0]))) {
30
+ transpose_tensor = false;
31
+ return resolve_conj_if_indicated(tensor, !transpose_result);
32
+ } else if ((tensor_strides[1] == 1) && (tensor_strides[0] >= std::max<int64_t>(1, tensor_sizes[1]))) {
33
+ transpose_tensor = true;
34
+ return resolve_conj_if_indicated(tensor, transpose_result);
35
+ } else {
36
+ transpose_tensor = true;
37
+ return c10::MaybeOwned<Tensor>::owned(tensor.clone(at::MemoryFormat::Contiguous));
38
+ }
39
+ }
40
+
41
+ c10::MaybeOwned<Tensor> inline prepare_matrix_for_cublas(const Tensor& tensor, bool& transpose_tensor) {
42
+ if (tensor.is_non_overlapping_and_dense()) { // common case
43
+ transpose_tensor = tensor.is_contiguous();
44
+ return resolve_conj_if_indicated(tensor, true);
45
+ }
46
+
47
+ IntArrayRef tensor_strides = tensor.strides();
48
+ IntArrayRef tensor_sizes = tensor.sizes();
49
+ if ((tensor_strides[0] == 1) && (tensor_strides[1] >= std::max<int64_t>(1, tensor_sizes[0]))) {
50
+ transpose_tensor = false;
51
+ return resolve_conj_if_indicated(tensor, true);
52
+ } else if ((tensor_strides[1] == 1) && (tensor_strides[0] >= std::max<int64_t>(1, tensor_sizes[1]))) {
53
+ transpose_tensor = true;
54
+ return resolve_conj_if_indicated(tensor, true);
55
+ } else {
56
+ transpose_tensor = true;
57
+ return c10::MaybeOwned<Tensor>::owned(tensor.clone(at::MemoryFormat::Contiguous));
58
+ }
59
+ }
60
+
61
+ } // namespace
62
+
63
+ /**
64
+ * @brief Prepares matrices for CUBLAS operation
65
+ *
66
+ * This constructor prepares tensors for CUBLAS
67
+ * The main difference is that PyTorch uses row-major as the default and
68
+ * CUBLAS expects column-major.
69
+ *
70
+ * @details
71
+ * To enable row-major output while using CUBLAS,
72
+ * we use the mathematical identity that (A × B)^T = B^T × A^T.
73
+ *
74
+ * Transpose in this context refers to Cublas's(Fortran) definition of transpose (row-major)
75
+ * T = row-major, N = col-major
76
+ *
77
+ * Example:
78
+ * For matrices A (M×K)(row-major) and B (K×N)(row-major):
79
+ * - Standard multiplication: A × B = (M×K) × (K×N) = M×N result (row-major)
80
+ * - Using our transpose trick: (B^T × A^T) = (N×K)(T) × (K×M)(T) = N×M(N)
81
+ * - However, since the output form cublas is column-major this is
82
+ * - equivalent to an output of size MxN row-major as expected
83
+ *
84
+ * The transpose flags are derived from the layouts of the passed in tensors
85
+ *
86
+ * If the operands are in packed float4 format, `k`, `lda` and `ldb` are adjusted
87
+ * to their unpacked values to match what cuBLAS expects.
88
+ *
89
+ * @param mat1 First input matrix
90
+ * @param mat2 Second input matrix
91
+ * @param c Output matrix (result)
92
+ * @param scale_a Optional scaling factor for first matrix
93
+ * @param scale_b Optional scaling factor for second matrix
94
+ * @param scale_result Optional scaling factor for result
95
+ */
96
+ struct cublasCommonArgs {
97
+ cublasCommonArgs(
98
+ const Tensor& mat1,
99
+ const Tensor& mat2,
100
+ Tensor& c,
101
+ const std::optional<Tensor>& scale_a = std::nullopt,
102
+ const std::optional<Tensor>& scale_b = std::nullopt,
103
+ const std::optional<Tensor>& scale_result = std::nullopt,
104
+ const std::optional<ScalingType>& scaling_choice_a = std::nullopt,
105
+ const std::optional<ScalingType>& scaling_choice_b = std::nullopt) {
106
+ bool transpose_result = false, transpose_a = false, transpose_b = false;
107
+ result = prepare_matrix_for_cublas(c, transpose_result);
108
+ mata = prepare_matrix_for_cublas(transpose_result ? mat2 : mat1, transpose_a, transpose_result);
109
+ matb = prepare_matrix_for_cublas(transpose_result ? mat1 : mat2, transpose_b, transpose_result);
110
+
111
+ // Handle scale tensors if provided
112
+ if (scale_a && scale_b) {
113
+ // By default since we return in row-major we run the gemm
114
+ // as B.T @ A.T, check transpose_result to determine if we flip the scales
115
+ scale_mata_ptr = transpose_result ? scale_b->data_ptr() : scale_a->data_ptr();
116
+ scale_mata_dtype = transpose_result ? scale_b->scalar_type() : scale_a->scalar_type();
117
+ scaling_mata_type = transpose_result ? scaling_choice_b : scaling_choice_a;
118
+ scale_matb_ptr = transpose_result ? scale_a->data_ptr() : scale_b->data_ptr();
119
+ scale_matb_dtype = transpose_result ? scale_a->scalar_type() : scale_b->scalar_type();
120
+ scaling_matb_type = transpose_result ? scaling_choice_a : scaling_choice_b;
121
+ }
122
+
123
+ if (scale_result) {
124
+ scale_result_ptr = scale_result->data_ptr();
125
+ scale_result_dtype = scale_result->scalar_type();
126
+ }
127
+
128
+ // Update transpose flags
129
+ if (transpose_result) {
130
+ transpose_a = !transpose_a;
131
+ transpose_b = !transpose_b;
132
+ }
133
+
134
+ auto sizes_a = mata->sizes();
135
+ auto sizes_b = matb->sizes();
136
+
137
+ m = sizes_a[transpose_result ? 1 : 0];
138
+ k = sizes_a[transpose_result ? 0 : 1];
139
+ n = sizes_b[transpose_result ? 0 : 1];
140
+ lda = mata->stride((transpose_a == transpose_result) ? 1 : 0);
141
+ ldb = matb->stride((transpose_b == transpose_result) ? 1 : 0);
142
+ result_ld = result->stride(transpose_result ? 0 : 1);
143
+ transa = transpose_a ? mata->is_conj() ? 'c' : 't' : 'n';
144
+ transb = transpose_b ? matb->is_conj() ? 'c' : 't' : 'n';
145
+
146
+ // cuBLAS expects unpacked values of `k`, `lda` and `ldb`, adjust for 4x2 packing
147
+ // if the gemm operands are in packed float4
148
+ if (mat1.dtype() == at::kFloat4_e2m1fn_x2 && mat2.dtype() == at::kFloat4_e2m1fn_x2) {
149
+ k = k * 2;
150
+ lda = lda * 2;
151
+ ldb = ldb * 2;
152
+ }
153
+ }
154
+
155
+ // Matrix members
156
+ char transa, transb;
157
+ int64_t m, n, k;
158
+ int64_t lda, ldb, result_ld;
159
+ c10::MaybeOwned<Tensor> mata, matb, result;
160
+
161
+ // Scale members
162
+ void* scale_mata_ptr = nullptr;
163
+ void* scale_matb_ptr = nullptr;
164
+ void* scale_result_ptr = nullptr;
165
+ std::optional<c10::ScalarType> scale_mata_dtype;
166
+ std::optional<ScalingType> scaling_mata_type;
167
+ std::optional<c10::ScalarType> scale_matb_dtype;
168
+ std::optional<ScalingType> scaling_matb_type;
169
+ std::optional<c10::ScalarType> scale_result_dtype;
170
+ };
171
+
172
+ } // namespace at::native
173
+
174
+ #else
175
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
176
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/cutlass_common.cuh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/Exception.h>
5
+ #include <cutlass/cutlass.h>
6
+
7
+ namespace at::cuda::detail {
8
+
9
+ template <typename Kernel>
10
+ struct enable_2x_kernel_for_sm89 : Kernel {
11
+ template <typename... Args>
12
+ CUTLASS_DEVICE static void invoke(Args&&... args) {
13
+ #if defined __CUDA_ARCH__ && __CUDA_ARCH__ == 890
14
+ Kernel::invoke(std::forward<Args>(args)...);
15
+ #endif
16
+ }
17
+ };
18
+
19
+ template <typename Kernel>
20
+ struct enable_3x_kernel_for_sm9x : Kernel {
21
+ template <typename... Args>
22
+ CUTLASS_DEVICE void operator()(Args&&... args) {
23
+ #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 900 && __CUDA_ARCH__ < 1000
24
+ Kernel::operator()(std::forward<Args>(args)...);
25
+ #endif
26
+ }
27
+ };
28
+
29
+ template <typename Kernel>
30
+ struct enable_3x_kernel_for_sm10 : Kernel {
31
+ template <typename... Args>
32
+ CUTLASS_DEVICE void operator()(Args&&... args) {
33
+ #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 1000 && __CUDA_ARCH__ < 1200
34
+ Kernel::operator()(std::forward<Args>(args)...);
35
+ #endif
36
+ }
37
+ };
38
+
39
+ template <typename Kernel>
40
+ struct enable_3x_kernel_for_sm10_or_later : Kernel {
41
+ template <typename... Args>
42
+ CUTLASS_DEVICE void operator()(Args&&... args) {
43
+ #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 1000
44
+ Kernel::operator()(std::forward<Args>(args)...);
45
+ #endif
46
+ }
47
+ };
48
+
49
+ } // namespace at::cuda::detail
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.12/site-packages/torch/include/ATen/native/cuda/fused_adagrad_impl.cuh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adagrad_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList state_sums,
11
+ at::TensorList state_steps,
12
+ const double lr,
13
+ const double lr_decay,
14
+ const double weight_decay,
15
+ const double eps,
16
+ const bool maximize,
17
+ const std::optional<at::Tensor>& grad_scale,
18
+ const std::optional<at::Tensor>& found_inf);
19
+
20
+ void _fused_adagrad_cuda_impl_(
21
+ at::TensorList params,
22
+ at::TensorList grads,
23
+ at::TensorList state_sums,
24
+ at::TensorList state_steps,
25
+ const at::Tensor& lr,
26
+ const double lr_decay,
27
+ const double weight_decay,
28
+ const double eps,
29
+ const bool maximize,
30
+ const std::optional<at::Tensor>& grad_scale,
31
+ const std::optional<at::Tensor>& found_inf);
32
+
33
+ } // namespace at::native
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adagrad_utils.cuh ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/cuda/ForeachFunctors.cuh>
5
+ #include <ATen/native/cuda/MultiTensorApply.cuh>
6
+
7
+ namespace at::native {
8
+
9
+ namespace {
10
+
11
+ constexpr uint8_t kParamIdx = 0;
12
+ constexpr uint8_t kGradIdx = 1;
13
+ constexpr uint8_t kStateSumIdx = 2;
14
+
15
+ template <typename scalar_t, typename opmath_t>
16
+ C10_DEVICE inline void adagrad_math(
17
+ scalar_t r_args[3][kILP],
18
+ const double& corrected_lr,
19
+ const double& weight_decay,
20
+ const double& eps,
21
+ const bool& maximize,
22
+ const float* grad_scale_ptr,
23
+ const float* found_inf_ptr) {
24
+ #pragma unroll
25
+ for (int ii = 0; ii < kILP; ++ii) {
26
+ opmath_t param = static_cast<opmath_t>(r_args[kParamIdx][ii]);
27
+ opmath_t grad = static_cast<opmath_t>(r_args[kGradIdx][ii]);
28
+ opmath_t state_sum = static_cast<opmath_t>(r_args[kStateSumIdx][ii]);
29
+
30
+ if (grad_scale_ptr) {
31
+ grad /= (static_cast<double>(*grad_scale_ptr));
32
+ }
33
+ const opmath_t grad_to_store = grad;
34
+ if (maximize) {
35
+ grad = -grad;
36
+ }
37
+ if (weight_decay != 0) {
38
+ grad += param * weight_decay; // Can I change this to use std::fma?
39
+ }
40
+ state_sum += grad * grad; // Can I change this to use std::fma?
41
+ param = param - corrected_lr * grad / (std::sqrt(state_sum) + eps);
42
+
43
+ r_args[kParamIdx][ii] = param;
44
+ if (grad_scale_ptr) {
45
+ r_args[kGradIdx][ii] = grad_to_store;
46
+ }
47
+ r_args[kStateSumIdx][ii] = state_sum;
48
+ }
49
+ }
50
+
51
+ template <typename scalar_t>
52
+ struct FusedAdagradMathFunctor {
53
+ using opmath_t = at::opmath_type<scalar_t>;
54
+
55
+ C10_DEVICE __forceinline__ void operator()(
56
+ int64_t chunk_size,
57
+ FusedOptimizerTensorListMetadata<3>& tl,
58
+ const float* lr_ptr,
59
+ const double& lr,
60
+ const double& lr_decay,
61
+ const double& weight_decay,
62
+ const double& eps,
63
+ const bool& maximize,
64
+ const float* grad_scale_ptr,
65
+ const float* found_inf_ptr) {
66
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
67
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
68
+ const double lr_double = lr_ptr ? *lr_ptr : lr;
69
+
70
+ if (found_inf_ptr && *found_inf_ptr == 1) {
71
+ return;
72
+ }
73
+
74
+ const auto corrected_lr = [&]() -> double {
75
+ auto* step_count =
76
+ reinterpret_cast<const float*>(tl.state_steps_addresses[tensor_loc]);
77
+ const auto denom = 1 + (*step_count - 1) * lr_decay;
78
+ const auto corrected_lr = lr_double / denom;
79
+ return corrected_lr;
80
+ }();
81
+
82
+ scalar_t* args[3];
83
+ scalar_t r_args[3][kILP];
84
+ const auto n = tl.numel_for_tensor[tensor_loc] -
85
+ static_cast<int64_t>(chunk_idx * chunk_size);
86
+
87
+ const bool all_aligned{
88
+ init_args<3>(args, tl, chunk_idx, chunk_size, tensor_loc)};
89
+
90
+ if ((n % kILP == 0) && (chunk_size % kILP == 0) && all_aligned) {
91
+ for (int64_t i_start = threadIdx.x;
92
+ i_start * kILP < n && i_start * kILP < chunk_size;
93
+ i_start += blockDim.x) {
94
+ load_store(r_args[kParamIdx], args[kParamIdx], 0, i_start);
95
+ load_store(r_args[kGradIdx], args[kGradIdx], 0, i_start);
96
+ load_store(r_args[kStateSumIdx], args[kStateSumIdx], 0, i_start);
97
+
98
+ adagrad_math<scalar_t, opmath_t>(
99
+ r_args,
100
+ corrected_lr,
101
+ weight_decay,
102
+ eps,
103
+ maximize,
104
+ grad_scale_ptr,
105
+ found_inf_ptr);
106
+
107
+ load_store(args[kParamIdx], r_args[kParamIdx], i_start, 0);
108
+ if (grad_scale_ptr) {
109
+ load_store(args[kGradIdx], r_args[kGradIdx], i_start, 0);
110
+ }
111
+ load_store(args[kStateSumIdx], r_args[kStateSumIdx], i_start, 0);
112
+ }
113
+ } else {
114
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
115
+ i_start += blockDim.x * kILP) {
116
+ load_args<3>(r_args, args, i_start, chunk_size, n);
117
+
118
+ adagrad_math<scalar_t, opmath_t>(
119
+ r_args,
120
+ corrected_lr,
121
+ weight_decay,
122
+ eps,
123
+ maximize,
124
+ grad_scale_ptr,
125
+ found_inf_ptr);
126
+
127
+ #pragma unroll
128
+ for (int i = 0; i < 3; i++) {
129
+ if (i != kGradIdx || grad_scale_ptr) {
130
+ store_args(args[i], r_args[i], i_start, chunk_size, n);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ };
137
+
138
+ } // namespace
139
+
140
+ } // namespace at::native
141
+
142
+ #else
143
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
144
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_amsgrad_impl.cuh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adam_amsgrad_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList max_exp_avg_sqs,
13
+ at::TensorList state_steps,
14
+ const double lr,
15
+ const double beta1,
16
+ const double beta2,
17
+ const double weight_decay,
18
+ const double eps,
19
+ const bool maximize,
20
+ const std::optional<at::Tensor>& grad_scale,
21
+ const std::optional<at::Tensor>& found_inf);
22
+
23
+ void _fused_adam_amsgrad_cuda_impl_(
24
+ at::TensorList params,
25
+ at::TensorList grads,
26
+ at::TensorList exp_avgs,
27
+ at::TensorList exp_avg_sqs,
28
+ at::TensorList max_exp_avg_sqs,
29
+ at::TensorList state_steps,
30
+ const at::Tensor& lr,
31
+ const double beta1,
32
+ const double beta2,
33
+ const double weight_decay,
34
+ const double eps,
35
+ const bool maximize,
36
+ const std::optional<at::Tensor>& grad_scale,
37
+ const std::optional<at::Tensor>& found_inf);
38
+
39
+ } // namespace at::native
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_impl.cuh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adam_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList state_steps,
13
+ const double lr,
14
+ const double beta1,
15
+ const double beta2,
16
+ const double weight_decay,
17
+ const double eps,
18
+ const bool maximize,
19
+ const std::optional<at::Tensor>& grad_scale,
20
+ const std::optional<at::Tensor>& found_inf);
21
+
22
+ void _fused_adam_cuda_impl_(
23
+ at::TensorList params,
24
+ at::TensorList grads,
25
+ at::TensorList exp_avgs,
26
+ at::TensorList exp_avg_sqs,
27
+ at::TensorList state_steps,
28
+ const at::Tensor& lr,
29
+ const double beta1,
30
+ const double beta2,
31
+ const double weight_decay,
32
+ const double eps,
33
+ const bool maximize,
34
+ const std::optional<at::Tensor>& grad_scale,
35
+ const std::optional<at::Tensor>& found_inf);
36
+
37
+ } // namespace at::native
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adam_utils.cuh ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/cuda/ForeachFunctors.cuh>
5
+ #include <ATen/native/cuda/MultiTensorApply.cuh>
6
+ #include <ATen/native/cuda/Pow.cuh>
7
+ #include <type_traits>
8
+ #include <utility>
9
+
10
+ namespace at::native {
11
+
12
+ enum class ADAM_MODE : uint8_t { ORIGINAL = 0, ADAMW = 1 };
13
+
14
+ // Validates the dtype configuration for mixed-precision fused Adam/AdamW.
15
+ //
16
+ // Currently the only supported configuration is:
17
+ // params/grads: float32
18
+ // optimizer states (exp_avg, exp_avg_sq, ...): bfloat16
19
+ //
20
+ // This specific configuration (fp32 params + bf16 optimizer states) has been
21
+ // validated end-to-end in large-scale training runs (e.g. DeepSeek-V3 671B)
22
+ // and is the only one for which training convergence has been demonstrated.
23
+ // Additional mixed-precision configurations (e.g. float16 states) can be
24
+ // enabled here once convergence is verified for those as well.
25
+ //
26
+ // Only [0] is checked because within-list dtype homogeneity is guaranteed by
27
+ // _check_tensors_share_device_and_dtype (with skip_cross_list_dtype_check)
28
+ // and the Python-side grouping in
29
+ // _group_tensors_by_first_tensors_device_and_dtype.
30
+ inline void validate_mixed_precision_dtypes(
31
+ at::TensorList params,
32
+ at::TensorList grads,
33
+ at::TensorList exp_avgs,
34
+ at::TensorList exp_avg_sqs,
35
+ const char* op_name) {
36
+ TORCH_CHECK(
37
+ params[0].scalar_type() == at::kFloat,
38
+ op_name,
39
+ " requires float32 params, got ",
40
+ params[0].scalar_type());
41
+ TORCH_CHECK(
42
+ grads[0].scalar_type() == at::kFloat,
43
+ op_name,
44
+ " requires float32 grads, got ",
45
+ grads[0].scalar_type());
46
+ TORCH_CHECK(
47
+ exp_avgs[0].scalar_type() == at::kBFloat16,
48
+ op_name,
49
+ " requires bfloat16 optimizer states, got ",
50
+ exp_avgs[0].scalar_type());
51
+ TORCH_CHECK(
52
+ exp_avg_sqs[0].scalar_type() == at::kBFloat16,
53
+ op_name,
54
+ " requires bfloat16 optimizer states, got ",
55
+ exp_avg_sqs[0].scalar_type());
56
+ }
57
+
58
+ inline void validate_mixed_precision_dtypes(
59
+ at::TensorList params,
60
+ at::TensorList grads,
61
+ at::TensorList exp_avgs,
62
+ at::TensorList exp_avg_sqs,
63
+ at::TensorList max_exp_avg_sqs,
64
+ const char* op_name) {
65
+ validate_mixed_precision_dtypes(
66
+ params, grads, exp_avgs, exp_avg_sqs, op_name);
67
+ TORCH_CHECK(
68
+ max_exp_avg_sqs[0].scalar_type() == at::kBFloat16,
69
+ op_name,
70
+ " requires bfloat16 max_exp_avg_sqs, got ",
71
+ max_exp_avg_sqs[0].scalar_type());
72
+ }
73
+
74
+ namespace {
75
+
76
+ constexpr uint8_t kParamIdx = 0;
77
+ constexpr uint8_t kGradIdx = 1;
78
+ constexpr uint8_t kExpAvgIdx = 2;
79
+ constexpr uint8_t kExpAvgSqIdx = 3;
80
+ constexpr uint8_t kMaxExpAvgSqIdx = 4;
81
+
82
+ template <
83
+ typename scalar_type,
84
+ typename opmath_t,
85
+ int depth,
86
+ ADAM_MODE adam_mode,
87
+ bool amsgrad>
88
+ C10_DEVICE inline void adam_math(
89
+ scalar_type r_args[depth][kILP],
90
+ const opmath_t& lr,
91
+ const opmath_t& beta1,
92
+ const opmath_t& beta2,
93
+ const opmath_t& weight_decay,
94
+ const opmath_t& eps,
95
+ const bool& maximize,
96
+ const float* grad_scale_ptr,
97
+ const float* found_inf_ptr,
98
+ const opmath_t& bias_correction1,
99
+ const opmath_t& bias_correction2_sqrt) {
100
+ static_assert(depth == 4 || depth == 5);
101
+ #pragma unroll
102
+ for (int ii = 0; ii < kILP; ii++) {
103
+ // Load values.
104
+ auto param = static_cast<opmath_t>(r_args[kParamIdx][ii]);
105
+ auto grad = static_cast<opmath_t>(r_args[kGradIdx][ii]);
106
+ auto exp_avg = static_cast<opmath_t>(r_args[kExpAvgIdx][ii]);
107
+ auto exp_avg_sq = static_cast<opmath_t>(r_args[kExpAvgSqIdx][ii]);
108
+ opmath_t max_exp_avg_sq;
109
+ if constexpr (amsgrad) {
110
+ max_exp_avg_sq = static_cast<opmath_t>(r_args[kMaxExpAvgSqIdx][ii]);
111
+ }
112
+
113
+ // Scale gradient for AMP.
114
+ if (grad_scale_ptr) {
115
+ grad /= (static_cast<opmath_t>(*grad_scale_ptr));
116
+ }
117
+ const opmath_t grad_to_store = grad;
118
+
119
+ if (maximize) {
120
+ grad = -grad;
121
+ }
122
+
123
+ // Update param, grad, 1st and 2nd order momentum.
124
+ if (weight_decay != 0) {
125
+ if constexpr (adam_mode == ADAM_MODE::ORIGINAL) {
126
+ grad += param * weight_decay;
127
+ } else if constexpr (adam_mode == ADAM_MODE::ADAMW) {
128
+ param -= lr * weight_decay * param;
129
+ }
130
+ }
131
+ exp_avg = std::fma(beta1, exp_avg, std::fma(-beta1, grad, grad));
132
+ exp_avg_sq =
133
+ std::fma(beta2, exp_avg_sq, std::fma(-beta2, grad * grad, grad * grad));
134
+ const opmath_t step_size = lr / bias_correction1;
135
+ opmath_t denom;
136
+ if constexpr (amsgrad) {
137
+ max_exp_avg_sq = std::max(max_exp_avg_sq, exp_avg_sq);
138
+ denom = (std::sqrt(max_exp_avg_sq) / bias_correction2_sqrt) + eps;
139
+ } else {
140
+ denom = (std::sqrt(exp_avg_sq) / bias_correction2_sqrt) + eps;
141
+ }
142
+ param -= step_size * exp_avg / denom;
143
+
144
+ // Store results.
145
+ r_args[kParamIdx][ii] = param;
146
+ if (grad_scale_ptr) {
147
+ r_args[kGradIdx][ii] = grad_to_store;
148
+ }
149
+ r_args[kExpAvgIdx][ii] = exp_avg;
150
+ r_args[kExpAvgSqIdx][ii] = exp_avg_sq;
151
+ if constexpr (amsgrad) {
152
+ r_args[kMaxExpAvgSqIdx][ii] = max_exp_avg_sq;
153
+ }
154
+ }
155
+ }
156
+
157
+ // [note: Conditional Gradient Store when `optimizer.step` is called by
158
+ // GradScaler] When a user is training their model(s) with an FP16 AMP recipe,
159
+ // parameter updates are done via `grad_scaler.step(optimizer)` instead of
160
+ // `optimizer.step()`. For most optimizers, GradScaler unscales gradients on
161
+ // behalf of those optimizers. Also, before `.step`, it makes sure that all the
162
+ // gradients involved are finite, which incurs a device sync. On the other hand,
163
+ // fused optimizers set their member variable of `_step_supports_amp_scaling` to
164
+ // `True` in order to remove the device sync above. This means that fused
165
+ // optimizers have to have their CUDA kernels (a) unscale gradients and (b) skip
166
+ // parameter updates accordingly. To be functionally on par with `torch.optim`
167
+ // optimizers and `_multi_tensor` ones, the kernel below writes out gradients
168
+ // only when `grad_scale_ptr != nullptr.
169
+ template <typename scalar_type, int depth, ADAM_MODE adam_mode, bool amsgrad>
170
+ struct FusedAdamMathFunctor {
171
+ static_assert(
172
+ depth == 4 || depth == 5,
173
+ "depth of 4 for Adam, depth of 5 for Adam with AMSGrad.");
174
+ using opmath_t = at::opmath_type<scalar_type>;
175
+
176
+ C10_DEVICE __forceinline__ void operator()(
177
+ int64_t chunk_size,
178
+ FusedOptimizerTensorListMetadata<depth>& tl,
179
+ const float* lr_ptr,
180
+ const double& lr,
181
+ const double& beta1,
182
+ const double& beta2,
183
+ const double& weight_decay,
184
+ const double& eps,
185
+ const bool& maximize,
186
+ const float* grad_scale_ptr,
187
+ const float* found_inf_ptr) {
188
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
189
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
190
+
191
+ const auto lr_opmath =
192
+ lr_ptr ? static_cast<opmath_t>(*lr_ptr) : static_cast<opmath_t>(lr);
193
+ const auto beta1_opmath = static_cast<opmath_t>(beta1);
194
+ const auto beta2_opmath = static_cast<opmath_t>(beta2);
195
+ const auto weight_decay_opmath = static_cast<opmath_t>(weight_decay);
196
+ const auto eps_opmath = static_cast<opmath_t>(eps);
197
+
198
+ if (found_inf_ptr && *found_inf_ptr == 1) {
199
+ return;
200
+ }
201
+ const auto [bias_correction1, bias_correction2_sqrt] =
202
+ [&]() -> std::pair<opmath_t, opmath_t> {
203
+ auto step_count = static_cast<opmath_t>(*reinterpret_cast<const float*>(
204
+ tl.state_steps_addresses[tensor_loc]));
205
+
206
+ const opmath_t bias_correction1 =
207
+ 1 - at::native::pow_(beta1_opmath, step_count);
208
+
209
+ const opmath_t bias_correction2 =
210
+ 1 - at::native::pow_(beta2_opmath, step_count);
211
+ const opmath_t bias_correction2_sqrt = std::sqrt(bias_correction2);
212
+
213
+ return {bias_correction1, bias_correction2_sqrt};
214
+ }();
215
+
216
+ scalar_type* args[depth];
217
+ scalar_type r_args[depth][kILP];
218
+ const auto n = tl.numel_for_tensor[tensor_loc] - chunk_idx * chunk_size;
219
+
220
+ const bool all_aligned{
221
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc)};
222
+
223
+ if ((n % kILP == 0) && (chunk_size % kILP == 0) && all_aligned) {
224
+ for (int64_t i_start = threadIdx.x;
225
+ i_start * kILP < n && i_start * kILP < chunk_size;
226
+ i_start += blockDim.x) {
227
+ #pragma unroll
228
+ for (int i = 0; i < depth; i++) {
229
+ load_store(r_args[i], args[i], 0, i_start);
230
+ }
231
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
232
+ r_args,
233
+ lr_opmath,
234
+ beta1_opmath,
235
+ beta2_opmath,
236
+ weight_decay_opmath,
237
+ eps_opmath,
238
+ maximize,
239
+ grad_scale_ptr,
240
+ found_inf_ptr,
241
+ bias_correction1,
242
+ bias_correction2_sqrt);
243
+ #pragma unroll
244
+ for (int i = 0; i < depth; i++) {
245
+ if (i != kGradIdx || grad_scale_ptr) {
246
+ load_store(args[i], r_args[i], i_start, 0);
247
+ }
248
+ }
249
+ }
250
+ } else {
251
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
252
+ i_start += blockDim.x * kILP) {
253
+ load_args<depth>(r_args, args, i_start, chunk_size, n);
254
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
255
+ r_args,
256
+ lr_opmath,
257
+ beta1_opmath,
258
+ beta2_opmath,
259
+ weight_decay_opmath,
260
+ eps_opmath,
261
+ maximize,
262
+ grad_scale_ptr,
263
+ found_inf_ptr,
264
+ bias_correction1,
265
+ bias_correction2_sqrt);
266
+ #pragma unroll
267
+ for (int i = 0; i < depth; i++) {
268
+ if (i != kGradIdx || grad_scale_ptr) {
269
+ store_args(args[i], r_args[i], i_start, chunk_size, n);
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+ };
276
+
277
+ template <
278
+ typename scalar_type,
279
+ typename param_type,
280
+ typename grad_type,
281
+ typename exp_avg_type,
282
+ typename exp_avg_sq_type,
283
+ typename max_exp_avg_sq_type,
284
+ int depth,
285
+ ADAM_MODE adam_mode,
286
+ bool amsgrad>
287
+ struct FusedAdamMathFunctorMP {
288
+ static_assert(
289
+ depth == 4 || depth == 5,
290
+ "depth of 4 for Adam, depth of 5 for Adam with AMSGrad.");
291
+ using opmath_t = at::opmath_type<scalar_type>;
292
+ C10_DEVICE __forceinline__ void operator()(
293
+ int64_t chunk_size,
294
+ FusedOptimizerTensorListMetadata<depth>& tl,
295
+ const float* lr_ptr,
296
+ const double& lr,
297
+ const double& beta1,
298
+ const double& beta2,
299
+ const double& weight_decay,
300
+ const double& eps,
301
+ const bool& maximize,
302
+ const float* grad_scale_ptr,
303
+ const float* found_inf_ptr) {
304
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
305
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
306
+ const double lr_double = lr_ptr ? *lr_ptr : lr;
307
+
308
+ if (found_inf_ptr && *found_inf_ptr == 1) {
309
+ return;
310
+ }
311
+ const auto [bias_correction1, bias_correction2_sqrt] =
312
+ [&]() -> std::pair<double, double> {
313
+ auto* step_count =
314
+ reinterpret_cast<const float*>(tl.state_steps_addresses[tensor_loc]);
315
+ const auto bias_correction1 = 1 - at::native::pow_(beta1, *step_count);
316
+ const auto bias_correction2 = 1 - at::native::pow_(beta2, *step_count);
317
+ const auto bias_correction2_sqrt = std::sqrt(bias_correction2);
318
+ return {bias_correction1, bias_correction2_sqrt};
319
+ }();
320
+
321
+ param_type* param_args;
322
+ grad_type* grad_args;
323
+ exp_avg_type* exp_avg_args;
324
+ exp_avg_sq_type* exp_avg_sq_args;
325
+ [[maybe_unused]] max_exp_avg_sq_type* max_exp_avg_sq_args;
326
+
327
+ // r_args represents the state when everything is casted to scalar_type
328
+ // to be passed into the adam_math function. scalar_type is our operation
329
+ // math type.
330
+ scalar_type r_args[depth][kILP];
331
+
332
+ // n = total numel of tensor - what's already been processed
333
+ // so n = numel in current tensor not yet processed
334
+ const auto n = tl.numel_for_tensor[tensor_loc] - chunk_idx * chunk_size;
335
+
336
+ bool all_aligned = init_args_mixed_prec<
337
+ depth,
338
+ param_type,
339
+ grad_type,
340
+ exp_avg_type,
341
+ exp_avg_sq_type>(
342
+ &param_args,
343
+ &grad_args,
344
+ &exp_avg_args,
345
+ &exp_avg_sq_args,
346
+ tl,
347
+ chunk_idx,
348
+ chunk_size,
349
+ tensor_loc);
350
+ if constexpr (amsgrad) {
351
+ max_exp_avg_sq_args =
352
+ (max_exp_avg_sq_type*)tl.addresses[kMaxExpAvgSqIdx][tensor_loc] +
353
+ chunk_idx * chunk_size;
354
+ all_aligned = all_aligned && is_aligned(max_exp_avg_sq_args);
355
+ }
356
+ if ((n % kILP == 0) && (chunk_size % kILP == 0) && all_aligned) {
357
+ for (int64_t i_start = threadIdx.x;
358
+ i_start * kILP < n && i_start * kILP < chunk_size;
359
+ i_start += blockDim.x) {
360
+ if constexpr (!std::is_same_v<scalar_type, param_type>) {
361
+ scalar_type casted_param_args[kILP];
362
+ for (int ii = 0; ii < kILP; ii++) {
363
+ casted_param_args[ii] =
364
+ static_cast<scalar_type>(param_args[ii + i_start * kILP]);
365
+ }
366
+ load_store(r_args[kParamIdx], casted_param_args, 0, 0);
367
+ } else {
368
+ load_store(r_args[kParamIdx], (scalar_type*)param_args, 0, i_start);
369
+ }
370
+ if constexpr (!std::is_same_v<scalar_type, grad_type>) {
371
+ scalar_type casted_grad_args[kILP];
372
+ for (int ii = 0; ii < kILP; ii++) {
373
+ casted_grad_args[ii] =
374
+ static_cast<scalar_type>(grad_args[ii + i_start * kILP]);
375
+ }
376
+ load_store(r_args[kGradIdx], casted_grad_args, 0, 0);
377
+ } else {
378
+ load_store(r_args[kGradIdx], (scalar_type*)grad_args, 0, i_start);
379
+ }
380
+ if constexpr (!std::is_same_v<scalar_type, exp_avg_type>) {
381
+ scalar_type casted_exp_avg_args[kILP];
382
+ for (int ii = 0; ii < kILP; ii++) {
383
+ casted_exp_avg_args[ii] =
384
+ static_cast<scalar_type>(exp_avg_args[ii + i_start * kILP]);
385
+ }
386
+ load_store(r_args[kExpAvgIdx], casted_exp_avg_args, 0, 0);
387
+ } else {
388
+ load_store(
389
+ r_args[kExpAvgIdx], (scalar_type*)exp_avg_args, 0, i_start);
390
+ }
391
+ if constexpr (!std::is_same_v<scalar_type, exp_avg_sq_type>) {
392
+ scalar_type casted_exp_avg_sq_args[kILP];
393
+ for (int ii = 0; ii < kILP; ii++) {
394
+ casted_exp_avg_sq_args[ii] =
395
+ static_cast<scalar_type>(exp_avg_sq_args[ii + i_start * kILP]);
396
+ }
397
+ load_store(r_args[kExpAvgSqIdx], casted_exp_avg_sq_args, 0, 0);
398
+ } else {
399
+ load_store(
400
+ r_args[kExpAvgSqIdx], (scalar_type*)exp_avg_sq_args, 0, i_start);
401
+ }
402
+ if constexpr (amsgrad) {
403
+ if constexpr (!std::is_same_v<scalar_type, max_exp_avg_sq_type>) {
404
+ scalar_type casted[kILP];
405
+ for (int ii = 0; ii < kILP; ii++) {
406
+ casted[ii] = static_cast<scalar_type>(
407
+ max_exp_avg_sq_args[ii + i_start * kILP]);
408
+ }
409
+ load_store(r_args[kMaxExpAvgSqIdx], casted, 0, 0);
410
+ } else {
411
+ load_store(
412
+ r_args[kMaxExpAvgSqIdx],
413
+ (scalar_type*)max_exp_avg_sq_args,
414
+ 0,
415
+ i_start);
416
+ }
417
+ }
418
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
419
+ r_args,
420
+ lr_double,
421
+ beta1,
422
+ beta2,
423
+ weight_decay,
424
+ eps,
425
+ maximize,
426
+ grad_scale_ptr,
427
+ found_inf_ptr,
428
+ bias_correction1,
429
+ bias_correction2_sqrt);
430
+ if constexpr (!std::is_same_v<scalar_type, param_type>) {
431
+ param_type casted_r_args[kILP];
432
+ for (int ii = 0; ii < kILP; ii++) {
433
+ casted_r_args[ii] = static_cast<param_type>(r_args[kParamIdx][ii]);
434
+ }
435
+ load_store(param_args, casted_r_args, i_start, 0);
436
+ } else {
437
+ load_store(param_args, (param_type*)r_args[kParamIdx], i_start, 0);
438
+ }
439
+ if constexpr (!std::is_same_v<scalar_type, exp_avg_type>) {
440
+ exp_avg_type casted_r_args[kILP];
441
+ for (int ii = 0; ii < kILP; ii++) {
442
+ casted_r_args[ii] =
443
+ static_cast<exp_avg_type>(r_args[kExpAvgIdx][ii]);
444
+ }
445
+ load_store(exp_avg_args, casted_r_args, i_start, 0);
446
+ } else {
447
+ load_store(
448
+ exp_avg_args, (exp_avg_type*)r_args[kExpAvgIdx], i_start, 0);
449
+ }
450
+ if constexpr (!std::is_same_v<scalar_type, exp_avg_sq_type>) {
451
+ exp_avg_sq_type casted_r_args[kILP];
452
+ for (int ii = 0; ii < kILP; ii++) {
453
+ casted_r_args[ii] =
454
+ static_cast<exp_avg_sq_type>(r_args[kExpAvgSqIdx][ii]);
455
+ }
456
+ load_store(exp_avg_sq_args, casted_r_args, i_start, 0);
457
+ } else {
458
+ load_store(
459
+ exp_avg_sq_args,
460
+ (exp_avg_sq_type*)r_args[kExpAvgSqIdx],
461
+ i_start,
462
+ 0);
463
+ }
464
+ if constexpr (amsgrad) {
465
+ if constexpr (!std::is_same_v<scalar_type, max_exp_avg_sq_type>) {
466
+ max_exp_avg_sq_type casted[kILP];
467
+ for (int ii = 0; ii < kILP; ii++) {
468
+ casted[ii] =
469
+ static_cast<max_exp_avg_sq_type>(r_args[kMaxExpAvgSqIdx][ii]);
470
+ }
471
+ load_store(max_exp_avg_sq_args, casted, i_start, 0);
472
+ } else {
473
+ load_store(
474
+ max_exp_avg_sq_args,
475
+ (max_exp_avg_sq_type*)r_args[kMaxExpAvgSqIdx],
476
+ i_start,
477
+ 0);
478
+ }
479
+ }
480
+ if (grad_scale_ptr) {
481
+ if constexpr (!std::is_same_v<scalar_type, grad_type>) {
482
+ grad_type casted_r_args[kILP];
483
+ for (int ii = 0; ii < kILP; ii++) {
484
+ casted_r_args[ii] = static_cast<grad_type>(r_args[kGradIdx][ii]);
485
+ }
486
+ load_store(grad_args, casted_r_args, i_start, 0);
487
+ } else {
488
+ load_store(grad_args, (grad_type*)r_args[kGradIdx], i_start, 0);
489
+ }
490
+ }
491
+ }
492
+ } else {
493
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
494
+ i_start += blockDim.x * kILP) {
495
+ load_args<
496
+ scalar_type,
497
+ param_type,
498
+ grad_type,
499
+ exp_avg_type,
500
+ exp_avg_sq_type>(
501
+ r_args,
502
+ param_args,
503
+ grad_args,
504
+ exp_avg_args,
505
+ exp_avg_sq_args,
506
+ i_start,
507
+ chunk_size,
508
+ n);
509
+ if constexpr (amsgrad) {
510
+ #pragma unroll
511
+ for (int ii = 0; ii < kILP; ii++) {
512
+ const auto i = i_start + threadIdx.x + ii * blockDim.x;
513
+ r_args[kMaxExpAvgSqIdx][ii] = 0;
514
+ if (i < n && i < chunk_size) {
515
+ r_args[kMaxExpAvgSqIdx][ii] =
516
+ static_cast<scalar_type>(max_exp_avg_sq_args[i]);
517
+ }
518
+ }
519
+ }
520
+ adam_math<scalar_type, opmath_t, depth, adam_mode, amsgrad>(
521
+ r_args,
522
+ lr_double,
523
+ beta1,
524
+ beta2,
525
+ weight_decay,
526
+ eps,
527
+ maximize,
528
+ grad_scale_ptr,
529
+ found_inf_ptr,
530
+ bias_correction1,
531
+ bias_correction2_sqrt);
532
+ store_args(param_args, r_args[kParamIdx], i_start, chunk_size, n);
533
+ store_args(exp_avg_args, r_args[kExpAvgIdx], i_start, chunk_size, n);
534
+ store_args(
535
+ exp_avg_sq_args, r_args[kExpAvgSqIdx], i_start, chunk_size, n);
536
+ if constexpr (amsgrad) {
537
+ store_args(
538
+ max_exp_avg_sq_args,
539
+ r_args[kMaxExpAvgSqIdx],
540
+ i_start,
541
+ chunk_size,
542
+ n);
543
+ }
544
+ if (grad_scale_ptr) {
545
+ store_args(grad_args, r_args[kGradIdx], i_start, chunk_size, n);
546
+ }
547
+ }
548
+ }
549
+ }
550
+ };
551
+
552
+ } // namespace
553
+
554
+ } // namespace at::native
555
+
556
+ #else
557
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
558
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adamw_amsgrad_impl.cuh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adamw_amsgrad_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList max_exp_avg_sqs,
13
+ at::TensorList state_steps,
14
+ const double lr,
15
+ const double beta1,
16
+ const double beta2,
17
+ const double weight_decay,
18
+ const double eps,
19
+ const bool maximize,
20
+ const std::optional<at::Tensor>& grad_scale,
21
+ const std::optional<at::Tensor>& found_inf);
22
+
23
+ void _fused_adamw_amsgrad_cuda_impl_(
24
+ at::TensorList params,
25
+ at::TensorList grads,
26
+ at::TensorList exp_avgs,
27
+ at::TensorList exp_avg_sqs,
28
+ at::TensorList max_exp_avg_sqs,
29
+ at::TensorList state_steps,
30
+ const at::Tensor& lr,
31
+ const double beta1,
32
+ const double beta2,
33
+ const double weight_decay,
34
+ const double eps,
35
+ const bool maximize,
36
+ const std::optional<at::Tensor>& grad_scale,
37
+ const std::optional<at::Tensor>& found_inf);
38
+
39
+ } // namespace at::native
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/fused_adamw_impl.cuh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ void _fused_adamw_cuda_impl_(
8
+ at::TensorList params,
9
+ at::TensorList grads,
10
+ at::TensorList exp_avgs,
11
+ at::TensorList exp_avg_sqs,
12
+ at::TensorList state_steps,
13
+ const double lr,
14
+ const double beta1,
15
+ const double beta2,
16
+ const double weight_decay,
17
+ const double eps,
18
+ const bool maximize,
19
+ const std::optional<at::Tensor>& grad_scale,
20
+ const std::optional<at::Tensor>& found_inf);
21
+
22
+ void _fused_adamw_cuda_impl_(
23
+ at::TensorList params,
24
+ at::TensorList grads,
25
+ at::TensorList exp_avgs,
26
+ at::TensorList exp_avg_sqs,
27
+ at::TensorList state_steps,
28
+ const at::Tensor& lr,
29
+ const double beta1,
30
+ const double beta2,
31
+ const double weight_decay,
32
+ const double eps,
33
+ const bool maximize,
34
+ const std::optional<at::Tensor>& grad_scale,
35
+ const std::optional<at::Tensor>& found_inf);
36
+
37
+ } // namespace at::native
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/im2col.cuh ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/AccumulateType.h>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/cuda/detail/KernelUtils.h>
7
+
8
+ #include <c10/macros/Macros.h>
9
+
10
+ namespace at::native {
11
+
12
+ using namespace at::cuda::detail;
13
+
14
+ // Kernel for fast unfold+copy
15
+ // (borrowed from Caffe:
16
+ // https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu)
17
+ // CUDA_NUM_THREADS = 1024
18
+
19
+ template <typename dt>
20
+ C10_LAUNCH_BOUNDS_1(1024)
21
+ __global__ void im2col_kernel(
22
+ const int64_t n,
23
+ const dt* data_im,
24
+ const int64_t height,
25
+ const int64_t width,
26
+ const int64_t kernel_height,
27
+ const int64_t kernel_width,
28
+ const int64_t pad_height,
29
+ const int64_t pad_width,
30
+ const int64_t stride_height,
31
+ const int64_t stride_width,
32
+ const int64_t dilation_height,
33
+ const int64_t dilation_width,
34
+ const int64_t height_col,
35
+ const int64_t width_col,
36
+ dt* data_col) {
37
+ CUDA_KERNEL_LOOP_TYPE(index, n, int64_t) {
38
+ int64_t w_out = index % width_col;
39
+
40
+ int64_t idx = index / width_col;
41
+
42
+ int64_t h_out = idx % height_col;
43
+ int64_t channel_in = idx / height_col;
44
+ int64_t channel_out = channel_in * kernel_height * kernel_width;
45
+ int64_t h_in = h_out * stride_height - pad_height;
46
+ int64_t w_in = w_out * stride_width - pad_width;
47
+
48
+ dt* col = data_col + (channel_out * height_col + h_out) * width_col + w_out;
49
+ const dt* im = data_im + (channel_in * height + h_in) * width + w_in;
50
+
51
+ for (int64_t i = 0; i < kernel_height; ++i) {
52
+ for (int64_t j = 0; j < kernel_width; ++j) {
53
+ int64_t h = h_in + i * dilation_height;
54
+ int64_t w = w_in + j * dilation_width;
55
+ *col = (h >= 0 && w >= 0 && h < height && w < width)
56
+ ? im[i * dilation_height * width + j * dilation_width]
57
+ : static_cast<dt>(0);
58
+ col += height_col * width_col;
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ template <typename dt>
65
+ void im2col(
66
+ cudaStream_t stream,
67
+ const dt* data_im,
68
+ const int64_t channels,
69
+ const int64_t height,
70
+ const int64_t width,
71
+ const int64_t height_col,
72
+ const int64_t width_col,
73
+ const int64_t kernel_height,
74
+ const int64_t kernel_width,
75
+ const int64_t pad_height,
76
+ const int64_t pad_width,
77
+ const int64_t stride_height,
78
+ const int64_t stride_width,
79
+ const int64_t dilation_height,
80
+ const int64_t dilation_width,
81
+ dt* data_col) {
82
+ // We are going to launch channels * height_col * width_col kernels, each
83
+ // kernel responsible for copying a single-channel grid.
84
+ int64_t num_kernels = channels * height_col * width_col;
85
+ // Launch CUDA_NUM_THREADS = 1024
86
+ im2col_kernel<<<GET_BLOCKS(num_kernels), 1024, 0, stream>>>(
87
+ num_kernels,
88
+ data_im,
89
+ height,
90
+ width,
91
+ kernel_height,
92
+ kernel_width,
93
+ pad_height,
94
+ pad_width,
95
+ stride_height,
96
+ stride_width,
97
+ dilation_height,
98
+ dilation_width,
99
+ height_col,
100
+ width_col,
101
+ data_col);
102
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
103
+ }
104
+
105
+ template <typename accT, typename dt>
106
+ __forceinline__ __device__ void col2im_device(
107
+ const int64_t index,
108
+ const dt* data_col,
109
+ const int64_t height,
110
+ const int64_t width,
111
+ const int64_t kernel_h,
112
+ const int64_t kernel_w,
113
+ const int64_t pad_height,
114
+ const int64_t pad_width,
115
+ const int64_t stride_height,
116
+ const int64_t stride_width,
117
+ const int64_t dilation_height,
118
+ const int64_t dilation_width,
119
+ const int64_t height_col,
120
+ const int64_t width_col,
121
+ dt* data_im) {
122
+ accT val = static_cast<accT>(0);
123
+ const int64_t w_im = index % width + pad_width;
124
+ const int64_t h_im = (index / width) % height + pad_height;
125
+ const int64_t c_im = index / (width * height);
126
+ int64_t kernel_extent_w = (kernel_w - 1) * dilation_width + 1;
127
+ int64_t kernel_extent_h = (kernel_h - 1) * dilation_height + 1;
128
+ // compute the start and end of the output
129
+ const int64_t w_col_start = (w_im < kernel_extent_w)
130
+ ? 0
131
+ : (w_im - kernel_extent_w) / stride_width + 1;
132
+ const int64_t w_col_end = ::min(w_im / stride_width + 1, width_col);
133
+ const int64_t h_col_start = (h_im < kernel_extent_h)
134
+ ? 0
135
+ : (h_im - kernel_extent_h) / stride_height + 1;
136
+ const int64_t h_col_end = ::min(h_im / stride_height + 1, height_col);
137
+
138
+ // TODO: use LCM of stride and dilation to avoid unnecessary loops
139
+ for (int64_t h_col = h_col_start; h_col < h_col_end; h_col += 1) {
140
+ for (int64_t w_col = w_col_start; w_col < w_col_end; w_col += 1) {
141
+ int64_t h_k = (h_im - h_col * stride_height);
142
+ int64_t w_k = (w_im - w_col * stride_width);
143
+ if (h_k % dilation_height == 0 && w_k % dilation_width == 0) {
144
+ h_k /= dilation_height;
145
+ w_k /= dilation_width;
146
+ int64_t data_col_index =
147
+ (((c_im * kernel_h + h_k) * kernel_w + w_k) * height_col +
148
+ h_col) *
149
+ width_col +
150
+ w_col;
151
+ val += data_col[data_col_index];
152
+ }
153
+ }
154
+ }
155
+ data_im[index] = static_cast<dt>(val);
156
+ }
157
+
158
+ template <typename dt, typename accT>
159
+ C10_LAUNCH_BOUNDS_1(512)
160
+ __global__ void col2im_kernel(
161
+ const int64_t n,
162
+ const dt* data_col,
163
+ const int64_t height,
164
+ const int64_t width,
165
+ const int64_t kernel_h,
166
+ const int64_t kernel_w,
167
+ const int64_t pad_height,
168
+ const int64_t pad_width,
169
+ const int64_t stride_height,
170
+ const int64_t stride_width,
171
+ const int64_t dilation_height,
172
+ const int64_t dilation_width,
173
+ const int64_t height_col,
174
+ const int64_t width_col,
175
+ dt* data_im) {
176
+ CUDA_KERNEL_LOOP(index, n) {
177
+ col2im_device<accT>(
178
+ index,
179
+ data_col,
180
+ height,
181
+ width,
182
+ kernel_h,
183
+ kernel_w,
184
+ pad_height,
185
+ pad_width,
186
+ stride_height,
187
+ stride_width,
188
+ dilation_height,
189
+ dilation_width,
190
+ height_col,
191
+ width_col,
192
+ data_im);
193
+ }
194
+ }
195
+
196
+ template <typename dt, typename accT>
197
+ void col2im(
198
+ cudaStream_t stream,
199
+ const dt* data_col,
200
+ const int64_t channels,
201
+ const int64_t height,
202
+ const int64_t width,
203
+ const int64_t height_col,
204
+ const int64_t width_col,
205
+ const int64_t patch_height,
206
+ const int64_t patch_width,
207
+ const int64_t pad_height,
208
+ const int64_t pad_width,
209
+ const int64_t stride_height,
210
+ const int64_t stride_width,
211
+ const int64_t dilation_height,
212
+ const int64_t dilation_width,
213
+ dt* data_im) {
214
+ int64_t num_kernels = channels * height * width;
215
+ // To avoid involving atomic operations, we will launch one kernel per
216
+ // bottom dimension, and then in the kernel add up the top dimensions.
217
+ // CUDA_NUM_THREADS = 1024
218
+ col2im_kernel<dt, accT>
219
+ <<<GET_BLOCKS(num_kernels, 512), 512, 0, stream>>>(
220
+ num_kernels,
221
+ data_col,
222
+ height,
223
+ width,
224
+ patch_height,
225
+ patch_width,
226
+ pad_height,
227
+ pad_width,
228
+ stride_height,
229
+ stride_width,
230
+ dilation_height,
231
+ dilation_width,
232
+ height_col,
233
+ width_col,
234
+ data_im);
235
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
236
+ }
237
+
238
+ template <typename dt>
239
+ C10_LAUNCH_BOUNDS_1(512)
240
+ __global__ void col2im_batched_kernel(
241
+ const int64_t n,
242
+ const dt* data_col,
243
+ const int64_t col_batch_stride,
244
+ const int64_t nbatch,
245
+ const int64_t height,
246
+ const int64_t width,
247
+ const int64_t kernel_h,
248
+ const int64_t kernel_w,
249
+ const int64_t pad_height,
250
+ const int64_t pad_width,
251
+ const int64_t stride_height,
252
+ const int64_t stride_width,
253
+ const int64_t dilation_height,
254
+ const int64_t dilation_width,
255
+ const int64_t height_col,
256
+ const int64_t width_col,
257
+ dt* data_im,
258
+ const int64_t im_batch_stride) {
259
+ using accT = at::acc_type<dt, /*is_cuda*/true>;
260
+ const auto im_numel = n * nbatch;
261
+
262
+ CUDA_KERNEL_LOOP_TYPE(index, im_numel, int64_t) {
263
+ const auto ibatch = index / n;
264
+ const auto slice_index = index % n;
265
+
266
+ col2im_device<accT>(
267
+ slice_index,
268
+ data_col + ibatch * col_batch_stride,
269
+ height,
270
+ width,
271
+ kernel_h,
272
+ kernel_w,
273
+ pad_height,
274
+ pad_width,
275
+ stride_height,
276
+ stride_width,
277
+ dilation_height,
278
+ dilation_width,
279
+ height_col,
280
+ width_col,
281
+ data_im + ibatch * im_batch_stride);
282
+ }
283
+ }
284
+
285
+ template <typename dt>
286
+ void col2im_batched(
287
+ cudaStream_t stream,
288
+ const dt* data_col,
289
+ const int64_t col_batch_stride,
290
+ const int64_t nbatch,
291
+ const int64_t channels,
292
+ const int64_t height,
293
+ const int64_t width,
294
+ const int64_t height_col,
295
+ const int64_t width_col,
296
+ const int64_t patch_height,
297
+ const int64_t patch_width,
298
+ const int64_t pad_height,
299
+ const int64_t pad_width,
300
+ const int64_t stride_height,
301
+ const int64_t stride_width,
302
+ const int64_t dilation_height,
303
+ const int64_t dilation_width,
304
+ dt* data_im,
305
+ const int64_t im_batch_stride) {
306
+ const int64_t num_kernels = channels * height * width;
307
+ const int64_t output_numel = nbatch * num_kernels;
308
+ if (output_numel == 0) {
309
+ return; // No work to do
310
+ }
311
+
312
+ // To avoid involving atomic operations, we will launch one kernel per
313
+ // bottom dimension, and then in the kernel add up the top dimensions.
314
+ // CUDA_NUM_THREADS = 1024
315
+ col2im_batched_kernel<<<GET_BLOCKS(output_numel, 512), 512, 0, stream>>>(
316
+ num_kernels,
317
+ data_col,
318
+ col_batch_stride,
319
+ nbatch,
320
+ height,
321
+ width,
322
+ patch_height,
323
+ patch_width,
324
+ pad_height,
325
+ pad_width,
326
+ stride_height,
327
+ stride_width,
328
+ dilation_height,
329
+ dilation_width,
330
+ height_col,
331
+ width_col,
332
+ data_im,
333
+ im_batch_stride);
334
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
335
+ }
336
+
337
+ } // namespace at::native
338
+
339
+ #else
340
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
341
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/jit_utils.h ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+
6
+ #include <c10/util/irange.h>
7
+ #include <ATen/jit_macros.h>
8
+ #include <ATen/cuda/detail/LazyNVRTC.h>
9
+
10
+ namespace at::cuda::jit {
11
+
12
+ enum class BinaryFuncVariant {NoScalar, RhsScalar, LhsScalar};
13
+
14
+ struct NvrtcFunction {
15
+ CUmodule module = CUmodule();
16
+ CUfunction function = nullptr;
17
+ };
18
+
19
+ struct KernelDescriptor {
20
+ std::string name;
21
+ std::string f;
22
+ c10::ScalarType f_inputs_type;
23
+ c10::ScalarType result_type;
24
+ c10::SmallVector<c10::ScalarType> extra_args_types;
25
+ int nInputs, nOutputs;
26
+ };
27
+
28
+ // Helper function to return a vector<string>
29
+ // corresponding to the type of the arguments in parameter pack.
30
+ template <typename... Args>
31
+ c10::SmallVector<at::ScalarType> get_extra_args_types() {
32
+ return {c10::CppTypeToScalarType<Args>::value ...};
33
+ }
34
+
35
+ template <
36
+ typename result_type,
37
+ typename f_inputs_type,
38
+ typename... ExtraArgs>
39
+ KernelDescriptor make_kernel_descriptor(
40
+ std::string name,
41
+ std::string f,
42
+ int nInputs,
43
+ int nOutputs) {
44
+ KernelDescriptor ret;
45
+ ret.name = std::move(name);
46
+ ret.f = std::move(f);
47
+ ret.f_inputs_type = c10::CppTypeToScalarType<f_inputs_type>::value;
48
+ ret.result_type = c10::CppTypeToScalarType<result_type>::value;
49
+ ret.extra_args_types = get_extra_args_types<ExtraArgs...>();
50
+ ret.nInputs = nInputs;
51
+ ret.nOutputs = nOutputs;
52
+ return ret;
53
+ }
54
+
55
+ inline int can_vectorize_up_to(size_t default_alignment, void *pointer) {
56
+ auto ip = reinterpret_cast<uintptr_t>(pointer);
57
+ #ifdef USE_ROCM
58
+ if ((default_alignment == 1) && (ip % (16 * default_alignment) == 0)) {
59
+ return 16;
60
+ }
61
+ if ((default_alignment <= 2) && (ip % (8 * default_alignment) == 0)) {
62
+ return 8;
63
+ }
64
+ #else
65
+ if (ip % (8 * default_alignment) == 0) {
66
+ return 8;
67
+ }
68
+ #endif
69
+ if (ip % (4 * default_alignment) == 0) {
70
+ return 4;
71
+ }
72
+ if (ip % (2 * default_alignment) == 0) {
73
+ return 2;
74
+ }
75
+ return 1;
76
+ }
77
+
78
+ inline int can_vectorize_up_to(const KernelDescriptor &desc, c10::ArrayRef<char*> pointers) {
79
+ TORCH_INTERNAL_ASSERT(desc.nOutputs == 1);
80
+ TORCH_INTERNAL_ASSERT(static_cast<int64_t>(pointers.size()) == 1 + desc.nInputs);
81
+
82
+ // Deals with output
83
+ auto result_size = c10::scalarTypeToTypeMeta(desc.result_type).itemsize();
84
+ auto result = can_vectorize_up_to(result_size, pointers[0]);
85
+
86
+ // Incorporates input(s)
87
+ auto input_size = c10::scalarTypeToTypeMeta(desc.f_inputs_type).itemsize();
88
+ for (auto i : c10::irange(1, pointers.size())) {
89
+ result = std::min(result, can_vectorize_up_to(input_size, pointers[i]));
90
+ }
91
+
92
+ return result;
93
+ }
94
+
95
+ //FIXME - this are defined in Loops.cuh, but including Loops.cuh here would lead to circular includes Loops.cuh -> CUDALoops.cuh -> jit_utils.h -> Loops.cuh
96
+ #ifdef USE_ROCM
97
+ #define JIT_THREAD_WORK_SIZE 4
98
+ #else
99
+ #define JIT_THREAD_WORK_SIZE 8
100
+ #endif
101
+
102
+ int calc_io_size(
103
+ const int nInputs,
104
+ const int nOutputs,
105
+ const c10::ScalarType& inputs_type,
106
+ const c10::ScalarType& result_type);
107
+
108
+ int calc_thread_work_size(
109
+ const int nInputs,
110
+ const int nOutputs,
111
+ const c10::ScalarType& inputs_type,
112
+ const c10::ScalarType& result_type);
113
+
114
+ std::string generate_code(
115
+ int nInputs,
116
+ int nOutputs,
117
+ const std::string& func,
118
+ const std::string& name,
119
+ const std::string& f_inputs_type,
120
+ const std::string& compute_type,
121
+ const std::string& result_type,
122
+ bool contiguous,
123
+ bool dynamic_casting,
124
+ BinaryFuncVariant scalar_pos,
125
+ c10::SmallVector<std::string>& extra_args_typenames,
126
+ int thread_work_size=JIT_THREAD_WORK_SIZE,
127
+ bool vectorized=false,
128
+ int vec_size=0,
129
+ bool return_by_ref=false);
130
+
131
+ std::string generate_code(
132
+ const KernelDescriptor &desc,
133
+ bool contiguous,
134
+ bool dynamic_casting,
135
+ BinaryFuncVariant scalar_pos,
136
+ int thread_work_size=JIT_THREAD_WORK_SIZE,
137
+ bool vectorized=false,
138
+ int vec_size=0,
139
+ bool return_by_ref=false);
140
+
141
+ std::string generate_reduction_code(
142
+ int nOutputs,
143
+ const std::string& func,
144
+ const std::string& name,
145
+ const int vt0,
146
+ const std::string& f_inputs_type,
147
+ const std::string& reduction_accum_type,
148
+ const std::string& result_type,
149
+ bool contiguous,
150
+ bool vectorized,
151
+ int vec_size,
152
+ int max_threads_codegen);
153
+
154
+ std::string generate_reduction_code(
155
+ const KernelDescriptor &desc,
156
+ const int vt0,
157
+ bool contiguous,
158
+ bool vectorized,
159
+ int vec_size,
160
+ int max_threads_codegen);
161
+
162
+ NvrtcFunction jit_pwise_function(
163
+ const std::string& code,
164
+ const std::string& kernel_name);
165
+
166
+ void launch_jitted_pwise_function(
167
+ NvrtcFunction function,
168
+ const void* args[],
169
+ const dim3 nBlocks,
170
+ const dim3 kBlockSize,
171
+ const int smem=0);
172
+
173
+ template <typename T>
174
+ struct delayed_false : std::false_type {
175
+ };
176
+
177
+ // Defines type names
178
+ // NOTE: General case is instantiated only for invalid types.
179
+ // All the valid types have specialization using the TYPE_NAME_FN
180
+ // macro below.
181
+ template <typename T>
182
+ inline std::string typeName() {
183
+ // we can't use static_assert(false) directly as the
184
+ // program will be not compiled even if the template is not
185
+ // instantiated, so we use `delayed_false`
186
+ // to make sure compiler doesn't eagerly raise
187
+ // fail this assertion.
188
+ static_assert(delayed_false<T>::value, "invalid type for jiterator");
189
+ return "void";
190
+ }
191
+
192
+ #define TYPE_NAME_FN(ctype, name) \
193
+ template <> inline std::string typeName<ctype>(){ \
194
+ return std::string(#ctype); \
195
+ }
196
+
197
+ AT_FORALL_SCALAR_TYPES(TYPE_NAME_FN)
198
+ #undef TYPE_NAME_FN
199
+ // JIT uses std::complex directly, because nvRTC compile programs
200
+ // with -default-device, so there is no such issue like:
201
+ // "std::sin(complex) is __host__ only"
202
+ template <> inline std::string typeName<bool>(){
203
+ return "bool";
204
+ }
205
+ template <> inline std::string typeName<c10::complex<at::Half>>(){
206
+ return "std::complex<at::Half>";
207
+ }
208
+ template <> inline std::string typeName<c10::complex<at::BFloat16>>(){
209
+ return "std::complex<at::BFloat16>";
210
+ }
211
+ template <> inline std::string typeName<c10::complex<float>>(){
212
+ return "std::complex<float>";
213
+ }
214
+ template <> inline std::string typeName<c10::complex<double>>(){
215
+ return "std::complex<double>";
216
+ }
217
+ template <> inline std::string typeName<at::Half>(){
218
+ return "at::Half";
219
+ }
220
+ template <> inline std::string typeName<at::BFloat16>(){
221
+ return "at::BFloat16";
222
+ }
223
+ template <> inline std::string typeName<at::Float8_e5m2>(){
224
+ return "at::Float8_e5m2";
225
+ }
226
+ template <> inline std::string typeName<at::Float8_e4m3fn>(){
227
+ return "at::Float8_e4m3fn";
228
+ }
229
+ template <> inline std::string typeName<at::Float8_e5m2fnuz>() {
230
+ return "at::Float8_e5m2fnuz";
231
+ }
232
+ template <> inline std::string typeName<at::Float8_e4m3fnuz>() {
233
+ return "at::Float8_e4m3fnuz";
234
+ }
235
+ template <> inline std::string typeName<at::Float8_e8m0fnu>() {
236
+ // TODO(#146647): Can the code here be made generic for any scalartype?
237
+ return "at::Float8_e8m0fnu";
238
+ }
239
+
240
+ #define TYPE_NAME_CASE(ctype, scalartype) \
241
+ case scalartype: return typeName<ctype>();
242
+ inline std::string typeName(ScalarType t) {
243
+ switch (t) {
244
+ AT_FORALL_SCALAR_TYPES_V2(
245
+ AT_WRAP(TYPE_NAME_CASE),
246
+ AT_EXPAND(AT_ALL_SCALAR_TYPES_WITH_COMPLEX))
247
+ default:
248
+ TORCH_CHECK(false, "invalid type for jiterator");
249
+ }
250
+ }
251
+ #undef TYPE_NAME_CASE
252
+
253
+ TORCH_CUDA_CPP_API void initializeCudaContext();
254
+
255
+ } // namespace at::cuda::jit
256
+
257
+ #else
258
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
259
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/reduction_template.cuh ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ namespace at::cuda {
3
+ //windows doesn't like large string literals, so split in two
4
+ const std::string reduction_template_0 = R"ESCAPE(
5
+ #define C10_HOST_DEVICE __host__ __device__
6
+ #define C10_DEVICE __device__
7
+ #if defined(__clang__) && defined(__HIP__)
8
+ #define USE_ROCM 1
9
+ #ifndef __forceinline__
10
+ #define __forceinline__ inline __attribute__((always_inline))
11
+ #endif
12
+ // until ROCm support for kernel asserts is restored
13
+ #define assert(expr) (static_cast<void>(0))
14
+ #endif
15
+
16
+ template <typename T>
17
+ __device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
18
+ {
19
+ #if defined(__clang__) && defined(__HIP__)
20
+ return __shfl_down(value, delta, width);
21
+ #else
22
+ return __shfl_down_sync(mask, value, delta, width);
23
+ #endif
24
+ }
25
+
26
+
27
+ #if ${complex}
28
+ template <typename T>
29
+ __device__ __forceinline__ std::complex<T> WARP_SHFL_DOWN(std::complex<T> value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
30
+ {
31
+ return std::complex<T>(
32
+ #if defined(__clang__) && defined(__HIP__)
33
+ __shfl_down(value.real(), delta, width),
34
+ __shfl_down(value.imag(), delta, width));
35
+ #else
36
+ __shfl_down_sync(mask, value.real(), delta, width),
37
+ __shfl_down_sync(mask, value.imag(), delta, width));
38
+ #endif
39
+ }
40
+ #endif
41
+
42
+ // aligned vector generates vectorized load/store on CUDA
43
+ template<typename scalar_t, int vec_size>
44
+ struct alignas(sizeof(scalar_t) * vec_size) aligned_vector {
45
+ scalar_t val[vec_size];
46
+ };
47
+
48
+
49
+ C10_HOST_DEVICE static void reduce_fraction(size_t &numerator, size_t &denominator) {
50
+ // get GCD of num and denom using Euclid's algorithm.
51
+ // Can replace this with std::gcd if we ever support c++17.
52
+ size_t a = denominator;
53
+ size_t b = numerator;
54
+ while (b != 0) {
55
+ a %= b;
56
+ // swap(a,b)
57
+ size_t tmp = a;
58
+ a = b;
59
+ b = tmp;
60
+ }
61
+
62
+ // a is now the GCD
63
+ numerator /= a;
64
+ denominator /= a;
65
+ }
66
+
67
+
68
+
69
+
70
+ struct ReduceConfig {
71
+ //has to match host-side ReduceConfig in the eager code
72
+ static constexpr int BLOCK_X = 0;
73
+ static constexpr int BLOCK_Y = 1;
74
+ static constexpr int CTA = 2;
75
+
76
+ static constexpr int input_vec_size = 4;
77
+ int element_size_bytes;
78
+ int num_inputs;
79
+ int num_outputs;
80
+ int step_input = 1;
81
+ int step_output = 1;
82
+ int ctas_per_output = 1;
83
+ int input_mult[3] = {0, 0, 0};
84
+ int output_mult[2] = {0, 0};
85
+
86
+ int block_width;
87
+ int block_height;
88
+ int num_threads;
89
+
90
+ bool vectorize_input = false;
91
+ int output_vec_size = 1;
92
+
93
+ C10_HOST_DEVICE bool should_block_x_reduce() const {
94
+ return input_mult[BLOCK_X] != 0;
95
+ }
96
+
97
+ C10_HOST_DEVICE bool should_block_y_reduce() const {
98
+ return input_mult[BLOCK_Y] != 0;
99
+ }
100
+
101
+ C10_HOST_DEVICE bool should_global_reduce() const {
102
+ return input_mult[CTA] != 0;
103
+ }
104
+
105
+ C10_DEVICE bool should_store(int output_idx) const {
106
+ return output_idx < num_outputs &&
107
+ (!should_block_x_reduce() || threadIdx.x == 0) &&
108
+ (!should_block_y_reduce() || threadIdx.y == 0);
109
+ }
110
+
111
+ C10_DEVICE bool should_reduce_tail() const {
112
+ return (!should_block_y_reduce() || threadIdx.y == 0) &&
113
+ (!should_global_reduce() || blockIdx.y == 0);
114
+ }
115
+
116
+ C10_HOST_DEVICE int input_idx() const {
117
+ int lane = threadIdx.x;
118
+ int warp = threadIdx.y;
119
+ int cta2 = blockIdx.y;
120
+ return (lane * input_mult[BLOCK_X] +
121
+ warp * input_mult[BLOCK_Y] +
122
+ cta2 * input_mult[CTA]);
123
+ }
124
+
125
+ template <int output_vec_size>
126
+ C10_HOST_DEVICE int output_idx() const {
127
+ int lane = threadIdx.x;
128
+ int warp = threadIdx.y;
129
+ int cta1 = blockIdx.x;
130
+ return (lane * output_mult[BLOCK_X] +
131
+ warp * output_mult[BLOCK_Y] +
132
+ cta1 * step_output) * output_vec_size;
133
+ }
134
+
135
+ C10_DEVICE int shared_memory_offset(int offset) const {
136
+ return threadIdx.x + (threadIdx.y + offset) * blockDim.x;
137
+ }
138
+
139
+ C10_DEVICE int staging_memory_offset(int cta2) const {
140
+ int offset = cta2 + blockIdx.x * gridDim.y;
141
+ if (!should_block_x_reduce()) {
142
+ offset = threadIdx.x + offset * blockDim.x;
143
+ }
144
+ return offset;
145
+ }
146
+
147
+
148
+ };
149
+
150
+
151
+ //TODO this will need to be different for more generic reduction functions
152
+ namespace reducer {
153
+
154
+ using scalar_t = ${scalar_type};
155
+ using arg_t = ${reduction_accum_type};
156
+ using out_scalar_t = ${result_type};
157
+
158
+
159
+ inline __device__ ${functor}
160
+
161
+ inline __device__ out_scalar_t project(arg_t arg) {
162
+ return (out_scalar_t) arg;
163
+ }
164
+
165
+ inline __device__ arg_t warp_shfl_down(arg_t arg, int offset) {
166
+ return WARP_SHFL_DOWN(arg, offset);
167
+ }
168
+
169
+ inline __device__ arg_t translate_idx(arg_t acc, int64_t /*idx*/) {
170
+ return acc;
171
+ }
172
+
173
+ // wrap a normal reduction that ignores the index
174
+ inline __device__ arg_t reduce(arg_t acc, arg_t val, int64_t idx) {
175
+ return combine(acc, val);
176
+ }
177
+ }
178
+
179
+
180
+ struct ReduceJitOp {
181
+ using scalar_t = ${scalar_type};
182
+ using arg_t = ${reduction_accum_type};
183
+ using out_scalar_t = ${result_type};
184
+
185
+ using InputCalculator = OffsetCalculator<1>;
186
+ using OutputCalculator = OffsetCalculator<2>;
187
+
188
+ // static constexpr bool can_accumulate_in_output =
189
+ // std::is_convertible_v<arg_t, out_scalar_t>
190
+ // && std::is_convertible_v<out_scalar_t, arg_t>;
191
+
192
+ static constexpr int input_vec_size = ReduceConfig::input_vec_size;
193
+
194
+ arg_t ident;
195
+ ReduceConfig config;
196
+ InputCalculator input_calc;
197
+ OutputCalculator output_calc;
198
+ const void* src;
199
+ const char* dst[2]; //it accepts at most two destinations
200
+ // acc_buf used for accumulation among sub Tensor Iterator when accumulation on
201
+ // output is not permissible
202
+ void* acc_buf;
203
+ // cta_buf used for accumulation between blocks during global reduction
204
+ void* cta_buf;
205
+ int* semaphores;
206
+ int64_t base_idx;
207
+ bool accumulate;
208
+ bool final_output;
209
+ int noutputs;
210
+
211
+
212
+ C10_DEVICE void run() const {
213
+ extern __shared__ char shared_memory[];
214
+ uint32_t output_idx = config.output_idx<${output_vec_size}>();
215
+ uint32_t input_idx = config.input_idx();
216
+ auto base_offsets1 = output_calc.get(output_idx)[1];
217
+
218
+ using arg_vec_t = Array<arg_t, ${output_vec_size}>;
219
+ arg_vec_t value;
220
+
221
+ if (output_idx < config.num_outputs && input_idx < config.num_inputs) {
222
+ const scalar_t* input_slice = (const scalar_t*)((const char*)src + base_offsets1);
223
+
224
+ value = thread_reduce<${output_vec_size}>(input_slice);
225
+ }
226
+
227
+ if (config.should_block_x_reduce()) {
228
+ value = block_x_reduce<${output_vec_size}>(value, shared_memory);
229
+ }
230
+
231
+ if (config.should_block_y_reduce()) {
232
+ value = block_y_reduce<${output_vec_size}>(value, shared_memory);
233
+ }
234
+ using out_ptr_vec_t = Array<out_scalar_t*, ${output_vec_size}>;
235
+ using offset_vec_t = Array<uint32_t, ${output_vec_size}>;
236
+ offset_vec_t base_offsets;
237
+ out_ptr_vec_t out;
238
+
239
+ #pragma unroll
240
+ for (int i = 0; i < ${output_vec_size}; i++) {
241
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
242
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
243
+ }
244
+
245
+ arg_vec_t* acc = nullptr;
246
+ if (acc_buf != nullptr) {
247
+ size_t numerator = sizeof(arg_t);
248
+ size_t denominator = sizeof(out_scalar_t);
249
+ reduce_fraction(numerator, denominator);
250
+ acc = (arg_vec_t*)((char*)acc_buf + (base_offsets[0] * numerator / denominator));
251
+ }
252
+
253
+ if (config.should_global_reduce()) {
254
+ value = global_reduce<${output_vec_size}>(value, acc, shared_memory);
255
+ } else if (config.should_store(output_idx)) {
256
+ if (accumulate) {
257
+ #pragma unroll
258
+ for (int i = 0; i < ${output_vec_size}; i++) {
259
+ value[i] = reducer::translate_idx(value[i], base_idx);
260
+ }
261
+ }
262
+
263
+ if (acc == nullptr) {
264
+ if (accumulate) {
265
+ value = accumulate_in_output<${output_vec_size}>(out, value);
266
+ }
267
+ if (final_output) {
268
+ set_results_to_output<${output_vec_size}>(value, base_offsets);
269
+ } else {
270
+ #pragma unroll
271
+ for (int i = 0; i < ${output_vec_size}; i++) {
272
+ *(out[i]) = get_accumulated_output(out[i], value[i]);
273
+ }
274
+ }
275
+ } else {
276
+ if (accumulate) {
277
+ #pragma unroll
278
+ for (int i = 0; i < ${output_vec_size}; i++) {
279
+ value[i] = reducer::combine((*acc)[i], value[i]);
280
+ }
281
+ }
282
+ if (final_output) {
283
+ set_results_to_output<${output_vec_size}>(value, base_offsets);
284
+ } else {
285
+ *acc = value;
286
+ }
287
+ }
288
+ }
289
+ }
290
+
291
+ template <int output_vec_size>
292
+ C10_DEVICE Array<arg_t, output_vec_size> thread_reduce(const scalar_t* data) const {
293
+ if (config.vectorize_input) {
294
+ assert(output_vec_size == 1);
295
+ // reduce at the header of input_slice where memory is not aligned,
296
+ // so that thread_reduce will have an aligned memory to work on.
297
+ return {input_vectorized_thread_reduce_impl(data)};
298
+ } else {
299
+ uint32_t element_stride = input_calc.strides_[0][0] / sizeof(scalar_t);
300
+ bool is_contiguous = (input_calc.dims == 1 && element_stride == 1);
301
+ if (is_contiguous) {
302
+ return thread_reduce_impl<output_vec_size>(data, [](uint32_t idx) { return idx; });
303
+ } else if (input_calc.dims == 1) {
304
+ return thread_reduce_impl<output_vec_size>(data, [&](uint32_t idx) { return idx * element_stride; });
305
+ } else {
306
+ return thread_reduce_impl<output_vec_size>(data, [&](uint32_t idx) { return input_calc.get(idx)[0] / sizeof(scalar_t); });
307
+ }
308
+ }
309
+ }
310
+
311
+ C10_DEVICE arg_t input_vectorized_thread_reduce_impl(const scalar_t* data) const {
312
+ uint32_t end = config.num_inputs;
313
+
314
+ // Handle the head of input slice where data is not aligned
315
+ arg_t value = ident;
316
+ constexpr int align_bytes = alignof(aligned_vector<scalar_t, input_vec_size>);
317
+ constexpr int align_elements = align_bytes / sizeof(scalar_t);
318
+ int shift = ((int64_t)data) % align_bytes / sizeof(scalar_t);
319
+ if (shift > 0) {
320
+ data -= shift;
321
+ end += shift;
322
+ if(threadIdx.x >= shift && threadIdx.x < align_elements && config.should_reduce_tail()){
323
+ value = reducer::reduce(value, data[threadIdx.x], threadIdx.x - shift);
324
+ }
325
+ end -= align_elements;
326
+ data += align_elements;
327
+ shift = align_elements - shift;
328
+ }
329
+
330
+ // Do the vectorized reduction
331
+ using load_t = aligned_vector<scalar_t, input_vec_size>;
332
+
333
+ uint32_t idx = config.input_idx();
334
+ const uint32_t stride = config.step_input;
335
+
336
+ // Multiple accumulators to remove dependency between unrolled loops.
337
+ arg_t value_list[input_vec_size];
338
+ value_list[0] = value;
339
+
340
+ #pragma unroll
341
+ for (int i = 1; i < input_vec_size; i++) {
342
+ value_list[i] = ident;
343
+ }
344
+
345
+ scalar_t values[input_vec_size];
346
+
347
+ load_t *values_vector = reinterpret_cast<load_t*>(&values[0]);
348
+
349
+ while (idx * input_vec_size + input_vec_size - 1 < end) {
350
+ *values_vector = reinterpret_cast<const load_t*>(data)[idx];
351
+ #pragma unroll
352
+ for (uint32_t i = 0; i < input_vec_size; i++) {
353
+ value_list[i] = reducer::reduce(value_list[i], values[i], shift + idx * input_vec_size + i);
354
+ }
355
+ idx += stride;
356
+ }
357
+
358
+ // tail
359
+ uint32_t tail_start = end - end % input_vec_size;
360
+ if (config.should_reduce_tail()) {
361
+ int idx = tail_start + threadIdx.x;
362
+ if (idx < end) {
363
+ value_list[0] = reducer::reduce(value_list[0], data[idx], idx + shift);
364
+ }
365
+ }
366
+
367
+ // combine accumulators
368
+ #pragma unroll
369
+ for (int i = 1; i < input_vec_size; i++) {
370
+ value_list[0] = reducer::combine(value_list[0], value_list[i]);
371
+ }
372
+ return value_list[0];
373
+ }
374
+
375
+ template <int output_vec_size, typename offset_calc_t>
376
+ C10_DEVICE Array<arg_t, output_vec_size> thread_reduce_impl(const scalar_t* data_, offset_calc_t calc) const {
377
+ uint32_t idx = config.input_idx();
378
+ const uint32_t end = config.num_inputs;
379
+ const uint32_t stride = config.step_input;
380
+ const int vt0=${vt0};
381
+
382
+ using arg_vec_t = Array<arg_t, output_vec_size>;
383
+ using load_t = aligned_vector<scalar_t, output_vec_size>;
384
+ const load_t* data = reinterpret_cast<const load_t*>(data_);
385
+
386
+ // Multiple accumulators to remove dependency between unrolled loops.
387
+ arg_vec_t value_list[vt0];
388
+
389
+ #pragma unroll
390
+ for (int i = 0; i < vt0; i++) {
391
+ #pragma unroll
392
+ for (int j = 0; j < output_vec_size; j++) {
393
+ value_list[i][j] = ident;
394
+ }
395
+ }
396
+
397
+ load_t values[vt0];
398
+
399
+ while (idx + (vt0 - 1) * stride < end) {
400
+ #pragma unroll
401
+ for (uint32_t i = 0; i < vt0; i++) {
402
+ values[i] = data[calc(idx + i * stride) / output_vec_size];
403
+ }
404
+ #pragma unroll
405
+ for (uint32_t i = 0; i < vt0; i++) {
406
+ #pragma unroll
407
+ for (uint32_t j = 0; j < output_vec_size; j++) {
408
+ value_list[i][j] = reducer::reduce(value_list[i][j], values[i].val[j], idx + i * stride);
409
+ }
410
+ }
411
+ idx += stride * vt0;
412
+ }
413
+
414
+ // tail
415
+ int idx_ = idx;
416
+ #pragma unroll
417
+ for (uint32_t i = 0; i < vt0; i++) {
418
+ if (idx >= end) {
419
+ break;
420
+ }
421
+ values[i] = data[calc(idx) / output_vec_size];
422
+ idx += stride;
423
+ }
424
+ idx = idx_;
425
+ #pragma unroll
426
+ for (uint32_t i = 0; i < vt0; i++) {
427
+ if (idx >= end) {
428
+ break;
429
+ }
430
+ #pragma unroll
431
+ for (uint32_t j = 0; j < output_vec_size; j++) {
432
+ value_list[i][j] = reducer::reduce(value_list[i][j], values[i].val[j], idx);
433
+ }
434
+ idx += stride;
435
+ }
436
+
437
+ // combine accumulators
438
+ #pragma unroll
439
+ for (int i = 1; i < vt0; i++) {
440
+ #pragma unroll
441
+ for (uint32_t j = 0; j < output_vec_size; j++) {
442
+ value_list[0][j] = reducer::combine(value_list[0][j], value_list[i][j]);
443
+ }
444
+ }
445
+ return value_list[0];
446
+ }
447
+ template <int output_vec_size>
448
+ C10_DEVICE Array<arg_t, output_vec_size> block_x_reduce(Array<arg_t, output_vec_size> value, char* shared_memory) const {
449
+ using args_vec_t = Array<arg_t, output_vec_size>;
450
+ int dim_x = blockDim.x;
451
+ args_vec_t* shared = (args_vec_t*)shared_memory;
452
+ if (dim_x > warpSize) {
453
+ int address_base = threadIdx.x + threadIdx.y*blockDim.x;
454
+ shared[address_base] = value;
455
+ for (int offset = dim_x/2; offset >= warpSize; offset >>= 1) {
456
+ __syncthreads();
457
+ if (threadIdx.x < offset && threadIdx.x + offset < blockDim.x) {
458
+ args_vec_t other = shared[address_base + offset];
459
+ #pragma unroll
460
+ for (int i = 0; i < output_vec_size; i++) {
461
+ value[i] = reducer::combine(value[i], other[i]);
462
+ }
463
+ shared[address_base] = value;
464
+ }
465
+ }
466
+ dim_x = warpSize;
467
+ }
468
+
469
+ __syncthreads();
470
+
471
+ #if defined(USE_ROCM) || defined(FBCODE_CAFFE2)
472
+ for (int offset = 1; offset < dim_x; offset <<= 1) {
473
+ #else
474
+ for (int offset = dim_x >> 1; offset > 0; offset >>= 1) {
475
+ #endif
476
+ #pragma unroll
477
+ for (int i = 0; i < output_vec_size; i++) {
478
+ arg_t other = reducer::warp_shfl_down(value[i], offset);
479
+ value[i] = reducer::combine(value[i], other);
480
+ }
481
+ }
482
+ return value;
483
+ }
484
+
485
+ template <int output_vec_size>
486
+ C10_DEVICE Array<arg_t, output_vec_size> block_y_reduce(Array<arg_t, output_vec_size> value, char* shared_memory) const {
487
+ using args_vec_t = Array<arg_t, output_vec_size>;
488
+ args_vec_t* shared = (args_vec_t*)shared_memory;
489
+ shared[config.shared_memory_offset(0)] = value;
490
+ for (int offset = blockDim.y / 2; offset > 0; offset >>= 1) {
491
+ __syncthreads();
492
+ if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) {
493
+ args_vec_t other = shared[config.shared_memory_offset(offset)];
494
+ #pragma unroll
495
+ for (int i = 0; i < output_vec_size; i++) {
496
+ value[i] = reducer::combine(value[i], other[i]);
497
+ }
498
+ shared[config.shared_memory_offset(0)] = value;
499
+ }
500
+ }
501
+ return value;
502
+ }
503
+ )ESCAPE";
504
+
505
+ const std::string reduction_template_1 = R"ESCAPE(
506
+
507
+ C10_DEVICE bool mark_block_finished() const {
508
+ __shared__ bool is_last_block_done_shared;
509
+
510
+ __syncthreads();
511
+ if (threadIdx.x == 0 && threadIdx.y == 0) {
512
+ int prev_blocks_finished = atomicAdd(&semaphores[blockIdx.x], 1);
513
+ is_last_block_done_shared = (prev_blocks_finished == gridDim.y - 1);
514
+ }
515
+
516
+ __syncthreads();
517
+
518
+ return is_last_block_done_shared;
519
+ }
520
+
521
+ template <int output_vec_size>
522
+ C10_DEVICE Array<arg_t, output_vec_size> accumulate_in_output(
523
+ Array<out_scalar_t*, output_vec_size> out,
524
+ Array<arg_t, output_vec_size> value
525
+ ) const {
526
+ Array<arg_t, output_vec_size> ret;
527
+ #pragma unroll
528
+ for (int i = 0; i < output_vec_size; i++) {
529
+ ret[i] = reducer::combine(*(out[i]), value[i]);
530
+ }
531
+ return ret;
532
+ }
533
+
534
+
535
+ C10_DEVICE out_scalar_t get_accumulated_output(
536
+ out_scalar_t* out, arg_t value
537
+ ) const {
538
+ assert(!final_output);
539
+ return (out_scalar_t)value;
540
+ }
541
+
542
+ template<class T>
543
+ C10_DEVICE void set_results(const T x, const uint32_t base_offset) const {
544
+ assert(noutputs == 1);
545
+ auto res = (out_scalar_t*)((char*)dst[0] + base_offset);
546
+ *res = x;
547
+ }
548
+
549
+ //TODO - multi-output reduction - we won't be able to use thrust::pair
550
+ //just explicitly specify typed output reads/writes
551
+ //Currently implemented for max of two outputs
552
+ // template<class T1, class T2>
553
+ // C10_DEVICE void set_results(const thrust::pair<T1, T2> x, const index_t base_offset) const {
554
+ // if (noutputs >= 1) {
555
+ // auto res0 = (T1*)((char*)dst[0] + base_offset);
556
+ // *res0 = x.first;
557
+ // }
558
+ // if (noutputs >= 2) {
559
+ // // base offset is computed assuming element size being sizeof(T1), so we need to make a
560
+ // // correction to obtain the correct base offset
561
+ // auto res1 = (T2*) ((char *) dst[1] + base_offset / sizeof(T1) * sizeof(T2));
562
+ // *res1 = x.second;
563
+ // }
564
+ // }
565
+
566
+ template <int output_vec_size>
567
+ C10_DEVICE void set_results_to_output(Array<arg_t, output_vec_size> value, Array<uint32_t, output_vec_size> base_offset) const {
568
+ assert(final_output);
569
+ #pragma unroll
570
+ for (int i = 0; i < output_vec_size; i++) {
571
+ set_results(reducer::project(value[i]), base_offset[i]);
572
+ }
573
+ }
574
+
575
+ #ifdef USE_ROCM
576
+ // This function implements a committed store.
577
+ // Upon returning, the store is committed to global memory.
578
+ // This is useful in avoiding the need for fences.
579
+ // If multiple stores are done in a row there is option to skip
580
+ // waiting for commit for all but the last store.
581
+ template <typename T, bool wait_for_commit = true>
582
+ __device__ inline void cmtdStore(void* address, T value) const {
583
+ int constexpr num_long_per_val = sizeof(value)/sizeof(long);
584
+ int constexpr num_int_per_val = sizeof(value)/sizeof(int);
585
+ int constexpr num_short_per_val = sizeof(value)/sizeof(short);
586
+ int constexpr num_char_per_val = sizeof(value)/sizeof(char);
587
+ union pnr { T v;
588
+ long l[num_long_per_val];
589
+ int i[num_int_per_val];
590
+ short s[num_short_per_val];
591
+ char c[num_char_per_val]; }
592
+ _pnr = {.v = value };
593
+ if constexpr (num_long_per_val*sizeof(long) == sizeof(value))
594
+ for (int i=0; i<num_long_per_val; i++)
595
+ __hip_atomic_store(reinterpret_cast<long *>(address)+i, _pnr.l[i], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
596
+ else if constexpr (num_int_per_val*sizeof(int) == sizeof(value))
597
+ for (int i=0; i<num_int_per_val; i++)
598
+ __hip_atomic_store(reinterpret_cast<int *>(address)+i, _pnr.i[i], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
599
+ else if constexpr (num_short_per_val*sizeof(short) == sizeof(value))
600
+ for (int i=0; i<num_short_per_val; i++)
601
+ __hip_atomic_store(reinterpret_cast<short *>(address)+i, _pnr.s[i], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
602
+ else if constexpr (num_char_per_val*sizeof(char) == sizeof(value))
603
+ for (int i=0; i<num_char_per_val; i++)
604
+ __hip_atomic_store(reinterpret_cast<char *>(address)+i, _pnr.c[i], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
605
+ if constexpr (wait_for_commit)
606
+ {
607
+ __atomic_signal_fence(__ATOMIC_SEQ_CST);
608
+ #if defined(__GFX12__)
609
+ asm volatile("s_wait_storecnt(0)" ::: "memory");
610
+ #elif defined(__GFX10__) || defined(__GFX11__)
611
+ asm volatile("s_waitcnt_vscnt null, 0" ::: "memory");
612
+ #else
613
+ // Older architectures have only 'vmcnt' counter.
614
+ asm volatile("s_waitcnt vmcnt(0)" ::: "memory");
615
+ #endif
616
+ __atomic_signal_fence(__ATOMIC_SEQ_CST);
617
+ }
618
+ }
619
+ #endif
620
+
621
+ template <int output_vec_size>
622
+ C10_DEVICE Array<arg_t, output_vec_size> global_reduce(Array<arg_t, output_vec_size> value, Array<arg_t, output_vec_size> *acc, char* shared_memory) const {
623
+ using arg_vec_t = Array<arg_t, output_vec_size>;
624
+ using out_ptr_vec_t = Array<out_scalar_t*, output_vec_size>;
625
+ using offset_vec_t = Array<uint32_t, output_vec_size>;
626
+
627
+ arg_vec_t* reduce_buffer = (arg_vec_t*)cta_buf;
628
+ uint32_t output_idx = config.output_idx<output_vec_size>();
629
+ offset_vec_t base_offsets;
630
+ out_ptr_vec_t out;
631
+
632
+ #pragma unroll
633
+ for (int i = 0; i < output_vec_size; i++) {
634
+ base_offsets[i] = output_calc.get(output_idx + i)[0];
635
+ out[i] = (out_scalar_t*)((char*)dst[0] + base_offsets[i]);
636
+ }
637
+
638
+ bool should_store = config.should_store(output_idx);
639
+ if (should_store) {
640
+ uint32_t offset = config.staging_memory_offset(blockIdx.y);
641
+ #ifndef USE_ROCM
642
+ reduce_buffer[offset] = value;
643
+ #else // [CMTSTRS]
644
+ // In architectures with split caches, global fences are costly.
645
+ // Here we preempt need for fences by committing stores to global memory.
646
+ cmtdStore(&reduce_buffer[offset], value);
647
+ #endif // [CMTSTRS]
648
+ }
649
+
650
+ #ifndef USE_ROCM // skip fence if store are committed [CMTSTRS]
651
+ __threadfence(); // make sure writes are globally visible
652
+ #endif
653
+ __syncthreads(); // if multiple warps in this block wrote to staging, make sure they're all done
654
+ bool is_last_block_done = mark_block_finished();
655
+
656
+ if (is_last_block_done) {
657
+ #ifndef USE_ROCM // skip fence if store are committed [CMTSTRS]
658
+ __threadfence(); //complete acquire pattern
659
+ #endif
660
+ value = ident;
661
+ if (config.should_block_x_reduce()) {
662
+ uint32_t input_offset = threadIdx.x + threadIdx.y * blockDim.x;
663
+ uint32_t step = blockDim.x * blockDim.y;
664
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
665
+ uint32_t idx = config.staging_memory_offset(input_offset);
666
+ arg_vec_t next = reduce_buffer[idx];
667
+ #pragma unroll
668
+ for (int i = 0; i < output_vec_size; i++) {
669
+ value[i] = reducer::combine(value[i], next[i]);
670
+ }
671
+ }
672
+ } else {
673
+ uint32_t input_offset = threadIdx.y;
674
+ uint32_t step = blockDim.y;
675
+ for (; input_offset < config.ctas_per_output; input_offset += step) {
676
+ uint32_t idx = config.staging_memory_offset(input_offset);
677
+ arg_vec_t next = reduce_buffer[idx];
678
+ #pragma unroll
679
+ for (int i = 0; i < output_vec_size; i++) {
680
+ value[i] = reducer::combine(value[i], next[i]);
681
+ }
682
+ }
683
+ }
684
+ value = block_y_reduce(value, shared_memory);
685
+ if (config.should_block_x_reduce()) {
686
+ value = block_x_reduce<output_vec_size>(value, shared_memory);
687
+ }
688
+ if (should_store) {
689
+ if (accumulate) {
690
+ #pragma unroll
691
+ for (int i = 0; i < output_vec_size; i++) {
692
+ value[i] = reducer::translate_idx(value[i], base_idx);
693
+ }
694
+ }
695
+
696
+ if (acc == nullptr) {
697
+ if (accumulate) {
698
+ value = accumulate_in_output<output_vec_size>(out, value);
699
+ }
700
+ if (final_output) {
701
+ set_results_to_output<output_vec_size>(value, base_offsets);
702
+ } else {
703
+ #pragma unroll
704
+ for (int i = 0; i < output_vec_size; i++) {
705
+ *(out[i]) = get_accumulated_output(out[i], value[i]);
706
+ }
707
+ }
708
+ } else {
709
+ if (accumulate) {
710
+ #pragma unroll
711
+ for (int i = 0; i < output_vec_size; i++) {
712
+ value[i] = reducer::combine((*acc)[i], value[i]);
713
+ }
714
+ }
715
+ if (final_output) {
716
+ set_results_to_output<output_vec_size>(value, base_offsets);
717
+ } else {
718
+ *acc = value;
719
+ }
720
+ }
721
+ }
722
+ }
723
+
724
+ return value;
725
+ }
726
+ };
727
+
728
+ extern "C"
729
+ __launch_bounds__(${max_threads_lb}, 4)
730
+ __global__ void reduction_${name}_kernel(ReduceJitOp r){
731
+ r.run();
732
+ }
733
+ )ESCAPE";
734
+
735
+ const std::string reduction_template = reduction_template_0 + reduction_template_1;
736
+
737
+
738
+ const std::string &get_reduction_template() {
739
+ return reduction_template;
740
+ }
741
+
742
+ } // namespace at::cuda
743
+
744
+ #else
745
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
746
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/thread_constants.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/macros/Macros.h>
4
+
5
+ // Marks a lambda as executable on both the host and device. The __host__
6
+ // attribute is important so that we can access static type information from
7
+ // the host, even if the function is typically only executed on the device.
8
+ #ifndef GPU_LAMBDA
9
+ #define GPU_LAMBDA __host__ __device__
10
+ #endif
11
+
12
+ #if defined(USE_ROCM)
13
+ constexpr int num_threads() {
14
+ return 256;
15
+ }
16
+
17
+ constexpr int thread_work_size() { return 4; }
18
+ #else
19
+ constexpr uint32_t num_threads() {
20
+ return C10_WARP_SIZE * 4;
21
+ }
22
+
23
+ constexpr int thread_work_size() { return 8; }
24
+ #endif
25
+
26
+ constexpr int block_work_size() { return thread_work_size() * num_threads(); }
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)