ADAPT-Chase commited on
Commit
c7b507e
·
verified ·
1 Parent(s): 3e85a59

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/KernelUtils.h +37 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/LazyNVRTC.h +11 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/OffsetCalculator.cuh +118 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/PhiloxCudaStateRaw.cuh +43 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/TensorInfo.cuh +116 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/UnpackRaw.cuh +34 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmCommon.h +685 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmHipblaslt.h +663 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmRocblas.h +273 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/StreamTimer.h +50 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/Tunable.h +241 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/TunableGemm.h +323 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/TunableOp.h +430 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h +31 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h +18 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h +383 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h +135 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/AtomicAddFloat.h +37 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/CatKernel.h +12 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ChannelShuffleKernel.h +14 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/CopyKernel.h +14 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/DepthwiseConvKernel.h +21 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/DistributionTemplates.h +425 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Gelu.h +74 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/GridSamplerKernel.h +34 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/IndexKernelUtils.h +85 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Intrinsics.h +33 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/IsContiguous.h +64 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/LogAddExp.h +61 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Loops.h +395 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/MaxUnpoolKernel.h +14 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/PixelShuffleKernel.h +14 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Reduce.h +310 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ReduceUtils.h +238 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h +21 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SampledAddmmKernel.h +12 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SerialStackImpl.h +146 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SoftmaxKernel.h +28 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SpmmReduceKernel.h +22 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/StackKernel.h +12 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/UpSampleKernelAVXAntialias.h +1376 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/WeightNormKernel.h +20 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/avx_mathfun.h +522 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/int_mm_kernel.h +38 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/mixed_data_type.h +41 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/moments_utils.h +202 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/utils.h +212 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/zmath.h +250 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Activation.h +20 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/BinaryInternal.h +44 -0
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/KernelUtils.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <limits>
4
+ #include <c10/util/Exception.h>
5
+
6
+ namespace at::cuda::detail {
7
+
8
+ // CUDA: grid stride looping
9
+ //
10
+ // int64_t _i_n_d_e_x specifically prevents overflow in the loop increment.
11
+ // If input.numel() < INT_MAX, _i_n_d_e_x < INT_MAX, except after the final
12
+ // iteration of the loop where _i_n_d_e_x += blockDim.x * gridDim.x can be
13
+ // greater than INT_MAX. But in that case _i_n_d_e_x >= n, so there are no
14
+ // further iterations and the overflowed value in i=_i_n_d_e_x is not used.
15
+ #define CUDA_KERNEL_LOOP_TYPE(i, n, index_type) \
16
+ int64_t _i_n_d_e_x = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; \
17
+ for (index_type i=_i_n_d_e_x; _i_n_d_e_x < (n); _i_n_d_e_x+=blockDim.x * gridDim.x, i=_i_n_d_e_x)
18
+
19
+ #define CUDA_KERNEL_LOOP(i, n) CUDA_KERNEL_LOOP_TYPE(i, n, int)
20
+
21
+
22
+ // Use 1024 threads per block, which requires cuda sm_2x or above
23
+ constexpr int CUDA_NUM_THREADS = 1024;
24
+
25
+ // CUDA: number of blocks for threads.
26
+ inline int GET_BLOCKS(const int64_t N, const int64_t max_threads_per_block=CUDA_NUM_THREADS) {
27
+ TORCH_INTERNAL_ASSERT(N > 0, "CUDA kernel launch blocks must be positive, but got N=", N);
28
+ constexpr int64_t max_int = std::numeric_limits<int>::max();
29
+
30
+ // Round up division for positive number that cannot cause integer overflow
31
+ auto block_num = (N - 1) / max_threads_per_block + 1;
32
+ TORCH_INTERNAL_ASSERT(block_num <= max_int, "Can't schedule too many blocks on CUDA device");
33
+
34
+ return static_cast<int>(block_num);
35
+ }
36
+
37
+ } // namespace at::cuda::detail
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/LazyNVRTC.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/detail/CUDAHooksInterface.h>
3
+ namespace at::cuda {
4
+ // Forward-declares at::cuda::NVRTC
5
+ struct NVRTC;
6
+
7
+ namespace detail {
8
+ extern NVRTC lazyNVRTC;
9
+ } // namespace detail
10
+
11
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/OffsetCalculator.cuh ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <array>
4
+ #include <cstdint>
5
+ #include <type_traits>
6
+ #include <c10/macros/Macros.h>
7
+ #include <ATen/native/TensorIterator.h>
8
+ #include <ATen/cuda/detail/IntegerDivider.cuh>
9
+
10
+ // If element_sizes is nullptr, then the strides will be in bytes, otherwise
11
+ // the strides will be in # of elements.
12
+ // Operands that share the same shape, but may have different strides.
13
+ // OffsetCalculator iterates the tensor in a column-major order
14
+
15
+ #if defined(USE_ROCM)
16
+ constexpr int MAX_DIMS = 16;
17
+ #else
18
+ constexpr int MAX_DIMS = 25;
19
+ #endif
20
+
21
+ template <int NARGS, typename index_t = uint32_t, bool signed_strides = false>
22
+ struct OffsetCalculator {
23
+ // We allow having negative strides to implement some operations like torch.flip
24
+ using stride_t = std::conditional_t<signed_strides,
25
+ std::make_signed_t<index_t>,
26
+ index_t>;
27
+ // The offset for each argument. Wrapper around fixed-size array.
28
+ // On CUDA, zero sized array is not allowed, so when we are handling nullary
29
+ // operators, we need to create a size 1 offset to avoid compiler failure.
30
+ // This size 1 offset is just a placeholder, and we will not use it.
31
+ using offset_type = std::array<stride_t, std::max<int>(NARGS, 1)>;
32
+
33
+ // if element_sizes is nullptr, then the strides will be in bytes, otherwise
34
+ // the strides will be in # of elements.
35
+ OffsetCalculator(int dims, const int64_t* sizes, const int64_t* const* strides, const int64_t* element_sizes=nullptr) : dims(dims) {
36
+ TORCH_CHECK(dims <= MAX_DIMS, "tensor has too many (>", MAX_DIMS, ") dims");
37
+ for (int i=0; i < dims; i++){
38
+ sizes_[i] = at::cuda::detail::IntDivider<index_t>(sizes[i]);
39
+ for (int arg = 0; arg < NARGS; arg++) {
40
+ int64_t element_size = (element_sizes == nullptr ? 1LL : element_sizes[arg]);
41
+ strides_[i][arg] = strides[arg][i] / element_size;
42
+ }
43
+ }
44
+ }
45
+
46
+ C10_HOST_DEVICE offset_type get(index_t linear_idx) const {
47
+ offset_type offsets;
48
+ #pragma unroll
49
+ for (int arg = 0; arg < NARGS; arg++) {
50
+ offsets[arg] = 0;
51
+ }
52
+
53
+ #pragma unroll
54
+ for (int dim = 0; dim < MAX_DIMS; ++dim) {
55
+ if (dim == dims) {
56
+ break;
57
+ }
58
+ auto divmod = sizes_[dim].divmod(linear_idx);
59
+ linear_idx = divmod.div;
60
+
61
+ #pragma unroll
62
+ for (int arg = 0; arg < NARGS; arg++) {
63
+ offsets[arg] += divmod.mod * strides_[dim][arg];
64
+ }
65
+
66
+ }
67
+ return offsets;
68
+ }
69
+
70
+ int dims;
71
+ at::cuda::detail::IntDivider<index_t> sizes_[MAX_DIMS];
72
+ stride_t strides_[MAX_DIMS][std::max<int>(NARGS, 1)];
73
+ };
74
+
75
+ template <int NARGS, typename index_t = uint32_t>
76
+ struct TrivialOffsetCalculator {
77
+ // The offset for each argument. Wrapper around fixed-size array.
78
+ // The offsets are in # of elements, not in bytes.
79
+ // On CUDA, zero sized array is not allowed, so when we are handling nullary
80
+ // operators, we need to create a size 1 offset to avoid compiler failure.
81
+ // This size 1 offset is just a placeholder, and we will not use it.
82
+ using offset_type = std::array<index_t, std::max<int>(NARGS, 1)>;
83
+
84
+ C10_HOST_DEVICE offset_type get(index_t linear_idx) const {
85
+ offset_type offsets;
86
+ #pragma unroll
87
+ for (int arg = 0; arg < NARGS; arg++) {
88
+ offsets[arg] = linear_idx;
89
+ }
90
+ return offsets;
91
+ }
92
+ };
93
+
94
+ // Make an OffsetCalculator with byte offsets
95
+ template<int N, bool signed_strides = false>
96
+ static OffsetCalculator<N, uint32_t, signed_strides> make_offset_calculator(const at::TensorIteratorBase& iter) {
97
+ TORCH_INTERNAL_ASSERT(N <= iter.ntensors());
98
+ std::array<const int64_t*, N> strides;
99
+ for (int i = 0; i < N; i++) {
100
+ strides[i] = iter.strides(i).data();
101
+ }
102
+ return OffsetCalculator<N, uint32_t, signed_strides>(iter.ndim(), iter.shape().data(), strides.data());
103
+ }
104
+
105
+ // Make an OffsetCalculator with element offsets
106
+ template<int N, bool signed_strides = false>
107
+ static OffsetCalculator<N, uint32_t, signed_strides> make_element_offset_calculator(
108
+ const at::TensorIteratorBase& iter) {
109
+ TORCH_INTERNAL_ASSERT(N <= iter.ntensors());
110
+ std::array<const int64_t*, N> strides;
111
+ std::array<int64_t, N> element_sizes;
112
+ for (int i = 0; i < N; i++) {
113
+ strides[i] = iter.strides(i).data();
114
+ element_sizes[i] = iter.element_size(i);
115
+ }
116
+ return OffsetCalculator<N, uint32_t, signed_strides>(
117
+ iter.ndim(), iter.shape().data(), strides.data(), element_sizes.data());
118
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/PhiloxCudaStateRaw.cuh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // No "#pragma once" because this is a raw definition that can be copied by jit codegen.
2
+ // Eager mode clients should not include this file directly, instead,
3
+ // they should #include <ATen/cuda/PhiloxCudaState.h>, which has a #pragma once.
4
+
5
+ // Stores RNG state values. Passed as a kernel argument.
6
+ // See Note [CUDA Graph-safe RNG states].
7
+ //
8
+ // The raw definition lives in its own file so jit codegen can easily copy it.
9
+ namespace at {
10
+
11
+ struct PhiloxCudaState {
12
+ PhiloxCudaState() = default;
13
+ // Called if graph capture is not underway
14
+ PhiloxCudaState(uint64_t seed,
15
+ uint64_t offset) {
16
+ seed_.val = seed;
17
+ offset_.val = offset;
18
+ }
19
+ // Called if graph capture is underway
20
+ PhiloxCudaState(int64_t* seed,
21
+ int64_t* offset_extragraph,
22
+ uint32_t offset_intragraph) {
23
+ seed_.ptr = seed;
24
+ offset_.ptr = offset_extragraph;
25
+ offset_intragraph_ = offset_intragraph;
26
+ captured_ = true;
27
+ }
28
+
29
+ // Public members, directly accessible by at::cuda::philox::unpack.
30
+ // If we made them private with getters/setters, the getters/setters
31
+ // would have to be __device__, and we can't declare __device__ in ATen.
32
+ union Payload {
33
+ uint64_t val;
34
+ int64_t* ptr;
35
+ };
36
+
37
+ Payload seed_{};
38
+ Payload offset_{};
39
+ uint32_t offset_intragraph_ = 0;
40
+ bool captured_ = false;
41
+ };
42
+
43
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/TensorInfo.cuh ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/CollapseDims.h>
4
+
5
+ namespace at::cuda::detail {
6
+
7
+ #define MAX_TENSORINFO_DIMS 25
8
+
9
+ // CUDA kernel argument that defines tensor layout
10
+ template <typename T, typename IndexType>
11
+ struct TensorInfo {
12
+ TensorInfo();
13
+ TensorInfo(T* p,
14
+ int dim,
15
+ IndexType sz[MAX_TENSORINFO_DIMS],
16
+ IndexType st[MAX_TENSORINFO_DIMS]);
17
+
18
+ // Set the size of the given dimension to 1, as if it were a
19
+ // reduction dim (allows you to calculate offsets of the reduction
20
+ // slice)
21
+ void reduceDim(int dim);
22
+
23
+ // See note on [collapse dims].
24
+ int collapseDims(const int excludeDim = -1);
25
+
26
+ // Contiguous tensors of more than one dimension are collapsed down
27
+ // to one tensor
28
+ __host__ __device__ inline bool isContiguous() const {
29
+ return (dims == 1 && strides[0] == 1);
30
+ }
31
+
32
+ T* data;
33
+ IndexType sizes[MAX_TENSORINFO_DIMS];
34
+ IndexType strides[MAX_TENSORINFO_DIMS];
35
+ int dims;
36
+ };
37
+
38
+ template <typename T, typename IndexType>
39
+ TensorInfo<T, IndexType>::TensorInfo() {
40
+ data = nullptr;
41
+ dims = 0;
42
+ }
43
+
44
+ template <typename T, typename IndexType>
45
+ TensorInfo<T, IndexType>::TensorInfo(T* p,
46
+ int dim,
47
+ IndexType sz[MAX_TENSORINFO_DIMS],
48
+ IndexType st[MAX_TENSORINFO_DIMS]) {
49
+ data = p;
50
+ dims = dim;
51
+ TORCH_CHECK(dims < MAX_TENSORINFO_DIMS, "CUDA Tensors cannot have more than 25 dimensions");
52
+
53
+ for (int i = 0; i < dim; ++i) {
54
+ sizes[i] = sz[i];
55
+ strides[i] = st[i];
56
+ }
57
+ }
58
+
59
+ template <typename T, typename IndexType>
60
+ void
61
+ TensorInfo<T, IndexType>::reduceDim(int dim) {
62
+ TORCH_CHECK(dim < dims && dim >= 0, "expected dim between 0 and dims - 1");
63
+ sizes[dim] = 1;
64
+ }
65
+
66
+ template <typename T, typename IndexType>
67
+ int
68
+ TensorInfo<T, IndexType>::collapseDims(const int excludeDim) {
69
+ auto result = at::collapse_dims(sizes, strides, dims, excludeDim);
70
+ dims = std::get<1>(result);
71
+ return std::get<0>(result);
72
+ }
73
+
74
+ // Translate a linear index for the apply to a T* offset;
75
+ // specialized on `Dims` to reduce nvcc compilation time
76
+ template <typename T, typename IndexType, int Dims>
77
+ struct IndexToOffset {
78
+ static __host__ __device__ IndexType get(
79
+ IndexType linearId,
80
+ const TensorInfo<T, IndexType>& info) {
81
+
82
+ IndexType offset = 0;
83
+
84
+ // Uses static dims
85
+ for (int i = Dims - 1; i > 0; --i) {
86
+ IndexType curDimIndex = linearId % info.sizes[i];
87
+ IndexType curDimOffset = curDimIndex * info.strides[i];
88
+ offset += curDimOffset;
89
+ linearId /= info.sizes[i];
90
+ }
91
+
92
+ return offset + linearId * info.strides[0];
93
+ }
94
+ };
95
+
96
+ // Uses dynamic (runtime) instead of static (compiletime) dims
97
+ template <typename T, typename IndexType>
98
+ struct IndexToOffset<T, IndexType, -1> {
99
+ static inline __host__ __device__ IndexType get(
100
+ IndexType linearId,
101
+ const TensorInfo<T, IndexType>& info) {
102
+
103
+ IndexType offset = 0;
104
+
105
+ for (int i = info.dims - 1; i > 0; --i) {
106
+ IndexType curDimIndex = linearId % info.sizes[i];
107
+ IndexType curDimOffset = curDimIndex * info.strides[i];
108
+ offset += curDimOffset;
109
+ linearId /= info.sizes[i];
110
+ }
111
+
112
+ return offset + linearId * info.strides[0];
113
+ }
114
+ };
115
+
116
+ } // namespace at::cuda::detail
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/detail/UnpackRaw.cuh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // No "#pragma once" because this is a raw definition that can be copied by jit codegen.
2
+ // Eager mode clients should not include this file directly, instead,
3
+ // they should #include <ATen/cuda/PhiloxUtils.cuh>, which has a #pragma once.
4
+
5
+ namespace at::cuda::philox {
6
+
7
+ // In-kernel call to retrieve philox seed and offset from a PhiloxCudaState instance whether
8
+ // that instance was created with graph capture underway or not.
9
+ // See Note [CUDA Graph-safe RNG states].
10
+ //
11
+ // We can't write a __device__ function in CUDAGeneratorImpl.h, because it's in ATen.
12
+ // Also, whatever call unpacks PhiloxCudaState in consumer kernels must be inlineable.
13
+ // Easiest thing that comes to mind is, define a __device__ unpack helper here, in ATen/cuda.
14
+ //
15
+ // The raw definition lives in its own file so jit codegen can easily copy it.
16
+ __host__ __device__ __forceinline__ std::tuple<uint64_t, uint64_t>
17
+ unpack(at::PhiloxCudaState arg) {
18
+ if (arg.captured_) {
19
+ // static_cast avoids "warning: invalid narrowing conversion from "long" to "unsigned long".
20
+ // *(arg.offset_.ptr) is a broadcast load of a single int64_t to the entire kernel.
21
+ // For most threads' reads it will hit in cache, so it shouldn't hurt performance.
22
+ return std::make_tuple(static_cast<uint64_t>(*arg.seed_.ptr), static_cast<uint64_t>(*(arg.offset_.ptr) + arg.offset_intragraph_));
23
+ } else {
24
+ return std::make_tuple(arg.seed_.val, arg.offset_.val);
25
+ }
26
+ }
27
+
28
+ // Adapted from TE
29
+ // extract seed and offset from PhiloxCudaState
30
+ __global__ void unpack_cudnn(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr);
31
+
32
+ void unpack_cudnn_wrapper(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr, cudaStream_t stream);
33
+
34
+ } // namespace at::cuda::philox
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmCommon.h ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original TunableOp is from onnxruntime.
2
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
3
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ //
7
+ // Adapting TunableOp into PyTorch
8
+ // Copyright (c) Advanced Micro Devices, Inc.
9
+ //
10
+ #pragma once
11
+
12
+ #include <string>
13
+ #include <c10/core/ScalarType.h>
14
+
15
+ #include <ATen/cuda/tunable/TunableOp.h>
16
+ #include <ATen/cuda/CUDABlas.h>
17
+ #include <ATen/cuda/Exceptions.h>
18
+ #include <c10/util/StringUtil.h>
19
+
20
+ #ifndef AT_PER_OPERATOR_HEADERS
21
+ #include <ATen/Functions.h>
22
+ #include <ATen/NativeFunctions.h>
23
+ #else
24
+ #include <ATen/ops/allclose.h>
25
+ #include <ATen/ops/from_blob.h>
26
+ #endif
27
+ #include <ATen/OpMathType.h>
28
+ #include <fmt/printf.h>
29
+
30
+ namespace at::cuda::tunable {
31
+
32
+ enum class BlasOp {
33
+ N = 0,
34
+ T = 1
35
+ };
36
+
37
+ inline char BlasOpToString(BlasOp op) {
38
+ switch (op) {
39
+ case BlasOp::N:
40
+ return 'N';
41
+ case BlasOp::T:
42
+ return 'T';
43
+ }
44
+ TORCH_CHECK(false, "unrecognized BlasOp");
45
+ return 'N';
46
+ }
47
+
48
+ template <typename T>
49
+ inline const char* BLASTypeName(T v) {
50
+ return "unknown";
51
+ }
52
+
53
+ template <>
54
+ inline const char* BLASTypeName(float v) {
55
+ return "f32_r";
56
+ }
57
+
58
+ template <>
59
+ inline const char* BLASTypeName(double v) {
60
+ return "f64_r";
61
+ }
62
+
63
+ template <>
64
+ inline const char* BLASTypeName(BFloat16 v) {
65
+ return "bf16_r";
66
+ }
67
+
68
+ template <>
69
+ inline const char* BLASTypeName(Half v) {
70
+ return "f16_r";
71
+ }
72
+
73
+ //https://github.com/ROCm/hipBLASLt/blob/develop/library/src/include/auxiliary.hpp#L175
74
+ template <>
75
+ inline const char* BLASTypeName(Float8_e4m3fn v) {
76
+ return "f8_r";
77
+ }
78
+
79
+ template <>
80
+ inline const char* BLASTypeName(Float8_e5m2 v) {
81
+ return "bf8_r";
82
+ }
83
+
84
+ template <>
85
+ inline const char* BLASTypeName(Float8_e4m3fnuz v) {
86
+ return "f8_fnuz_r";
87
+ }
88
+
89
+ template <>
90
+ inline const char* BLASTypeName(Float8_e5m2fnuz v) {
91
+ return "bf8_fnuz_r";
92
+ }
93
+
94
+ template <>
95
+ inline const char* BLASTypeName(c10::complex<double> v) {
96
+ return "f64_r";
97
+ }
98
+
99
+ template <>
100
+ inline const char* BLASTypeName(c10::complex<float> v) {
101
+ return "f32_r";
102
+ }
103
+
104
+ inline std::string ScalarTypeToBLASType(c10::ScalarType scalar_type) {
105
+ std::string BLASType;
106
+ switch (scalar_type) {
107
+ case c10::ScalarType::Float:{
108
+ BLASType = "f32_r";
109
+ break;
110
+ }
111
+ case c10::ScalarType::Double:{
112
+ BLASType = "f64_r";
113
+ break;
114
+ }
115
+ case c10::ScalarType::BFloat16:{
116
+ BLASType = "bf16_r";
117
+ break;
118
+ }
119
+ case c10::ScalarType::Half: {
120
+ BLASType = "f16_r";
121
+ break;
122
+ }
123
+ case c10::ScalarType::Float8_e4m3fn: {
124
+ BLASType = "f8_r";
125
+ break;
126
+ }
127
+ case c10::ScalarType::Float8_e5m2: {
128
+ BLASType = "bf8_r";
129
+ break;
130
+ }
131
+ case c10::ScalarType::Float8_e4m3fnuz: {
132
+ BLASType = "f8_fnuz_r";
133
+ break;
134
+ }
135
+ case c10::ScalarType::Float8_e5m2fnuz: {
136
+ BLASType = "bf8_fnuz_r";
137
+ break;
138
+ }
139
+ case c10::ScalarType::ComplexFloat:{
140
+ BLASType = "f32_c";
141
+ break;
142
+ }
143
+ case c10::ScalarType::ComplexDouble:{
144
+ BLASType = "f64_c";
145
+ break;
146
+ }
147
+ default:
148
+ BLASType = "unknown";
149
+ }
150
+ return BLASType;
151
+ }
152
+
153
+ // Similar to Compute Type in GemmRocblas.h
154
+ template <typename T>
155
+ inline std::string ComputeTypeFor() {
156
+ return "Unknown ComputeType";
157
+ }
158
+
159
+ // This is a union of the compute types for
160
+ // ROCBLAS and hipBLASLt.
161
+ template <>
162
+ inline std::string ComputeTypeFor<float>() {
163
+ if (!at::globalContext().allowTF32CuBLAS()) {
164
+ return "f32_r";
165
+ } else {
166
+ return "xf32_r";
167
+ }
168
+ }
169
+
170
+ template <>
171
+ inline std::string ComputeTypeFor<double>() {
172
+ return "f64_r";
173
+ }
174
+
175
+ template <>
176
+ inline std::string ComputeTypeFor<Half>() {
177
+ return "f32_r";
178
+ }
179
+
180
+ template <>
181
+ inline std::string ComputeTypeFor<BFloat16>() {
182
+ return "f32_r";
183
+ }
184
+
185
+ template <>
186
+ inline std::string ComputeTypeFor<c10::complex<float>>() {
187
+ return "f32_c";
188
+ }
189
+
190
+ template <>
191
+ inline std::string ComputeTypeFor<c10::complex<double>>() {
192
+ return "f64_c";
193
+ }
194
+
195
+ template <>
196
+ inline std::string ComputeTypeFor<Float8_e4m3fn>() {
197
+ return "f32_r";
198
+ }
199
+
200
+ template <>
201
+ inline std::string ComputeTypeFor<Float8_e5m2>() {
202
+ return "f32_r";
203
+ }
204
+
205
+ template <>
206
+ inline std::string ComputeTypeFor<Float8_e4m3fnuz>() {
207
+ return "f32_r";
208
+ }
209
+
210
+ template <>
211
+ inline std::string ComputeTypeFor<Float8_e5m2fnuz>() {
212
+ return "f32_r";
213
+ }
214
+
215
+ // Convert opmath_type<T> to string
216
+ template <typename T>
217
+ inline std::string to_string_opmath(const at::opmath_type<T>& value) {
218
+ if constexpr (std::is_same_v<at::opmath_type<T>, c10::complex<float>> ||
219
+ std::is_same_v<at::opmath_type<T>, c10::complex<double>>) {
220
+ return fmt::format("({:.4f}, {:.4f})", value.real(), value.imag());
221
+ } else {
222
+ return fmt::format("{:.4f}", value);
223
+ }
224
+ }
225
+
226
+ // convert activation epilogue to string
227
+ inline std::string to_string_epilogue(const at::cuda::blas::GEMMAndBiasActivationEpilogue& value) {
228
+ switch (value) {
229
+ case at::cuda::blas::GEMMAndBiasActivationEpilogue::None:
230
+ return std::string("None");
231
+ break;
232
+ case at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU:
233
+ return std::string("RELU");
234
+ break;
235
+ case cuda::blas::GEMMAndBiasActivationEpilogue::GELU:
236
+ return std::string("GELU");
237
+ break;
238
+ default:
239
+ return std::string("unknown");
240
+ }
241
+ }
242
+
243
+ namespace detail {
244
+
245
+ static bool NumericalCheck(ScalarType dtype, void* c, void* other_c, int64_t size) {
246
+ auto options = at::TensorOptions().dtype(dtype).device(at::kCUDA);
247
+ // comparison done as 1D tensor
248
+ at::Tensor ref = at::from_blob(c, {size}, options);
249
+ at::Tensor oth = at::from_blob(other_c, {size}, options);
250
+ at::Tensor ref_float = ref.to(at::kFloat);
251
+ at::Tensor oth_float = oth.to(at::kFloat);
252
+ std::vector<double> atols{1e-1, 1e-2, 1e-3, 1e-4, 1e-5};
253
+ std::vector<double> rtols{1e-1, 1e-2, 1e-3, 1e-4, 1e-5};
254
+ double last_succeed_atol = 1;
255
+ double last_succeed_rtol = 1;
256
+ for (auto& atol : atols) {
257
+ for (auto& rtol : rtols) {
258
+ if (at::allclose(ref_float, oth_float, rtol, atol)) {
259
+ last_succeed_atol = atol;
260
+ last_succeed_rtol = rtol;
261
+ }
262
+ }
263
+ }
264
+ if (last_succeed_atol == 1) {
265
+ return false;
266
+ }
267
+ else {
268
+ TUNABLE_LOG3("├──verify numerics: atol=", last_succeed_atol, ", rtol=", last_succeed_rtol);
269
+ }
270
+
271
+ return true;
272
+ }
273
+
274
+ }
275
+
276
+ // Note on GetSizeA et al.
277
+ // Tensors can be dense or arbitrarily strided. We only need our copies to be large enough.
278
+ // Our copies must be at least as large as the m n k shapes dictate, but could be larger
279
+ // depending on the lda ldb ldc values. Similarly for the batched case.
280
+
281
+ template <typename T>
282
+ struct GemmParams : OpParams {
283
+ GemmParams() = default;
284
+
285
+ std::string BLASSignature() const override {
286
+ std::string alpha_str = to_string_opmath<T>(alpha);
287
+ std::string beta_str = to_string_opmath<T>(beta);
288
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
289
+ "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, bias_type: %s, compute_type: %s }",
290
+ m, n, k, lda, ldb, ldc, ldc, alpha_str, beta_str, transa, transb,
291
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>(), ComputeTypeFor<T>());
292
+ }
293
+
294
+ std::string Signature() const override {
295
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc);
296
+ }
297
+
298
+ size_t GetSizeA() const {
299
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
300
+ size_t size_dense = m * k;
301
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
302
+ }
303
+
304
+ size_t GetSizeB() const {
305
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
306
+ size_t size_dense = k * n;
307
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
308
+ }
309
+
310
+ size_t GetSizeC() const {
311
+ size_t size_stride = ldc * n;
312
+ size_t size_dense = m * n;
313
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
314
+ }
315
+
316
+ size_t GetSize(bool duplicate_inputs) const {
317
+ size_t size = GetSizeC();
318
+ if (duplicate_inputs) {
319
+ size += GetSizeA();
320
+ size += GetSizeB();
321
+ }
322
+ return size;
323
+ }
324
+
325
+ GemmParams* DeepCopy(bool duplicate_inputs) const {
326
+ GemmParams* copy = new GemmParams;
327
+ *copy = *this;
328
+ c10::DeviceIndex device = 0;
329
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
330
+ size_t c_size = GetSizeC();
331
+ copy->c = static_cast<T*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
332
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
333
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
334
+ if (duplicate_inputs) {
335
+ size_t a_size = GetSizeA();
336
+ size_t b_size = GetSizeB();
337
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
338
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
339
+ copy->duplicate_inputs_ = true;
340
+ }
341
+ return copy;
342
+ }
343
+
344
+ // only call on object returned by DeepCopy
345
+ void Delete() {
346
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
347
+ if (duplicate_inputs_) {
348
+ // NOLINTNEXTLINE(*const-cast*)
349
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
350
+ // NOLINTNEXTLINE(*const-cast*)
351
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
352
+ }
353
+ }
354
+
355
+ TuningStatus NumericalCheck(GemmParams<T> *other) {
356
+ auto c_dtype = c10::CppTypeToScalarType<T>::value;
357
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T)) ? OK : FAIL;
358
+ }
359
+
360
+ char transa{};
361
+ char transb{};
362
+ int64_t m{};
363
+ int64_t n{};
364
+ int64_t k{};
365
+ at::opmath_type<T> alpha;
366
+ const T* a{};
367
+ int64_t lda{};
368
+ const T* b{};
369
+ int64_t ldb{};
370
+ at::opmath_type<T> beta;
371
+ T* c{};
372
+ int64_t ldc{};
373
+ private:
374
+ bool duplicate_inputs_{false};
375
+ };
376
+
377
+ template <typename T>
378
+ struct GemmAndBiasParams : OpParams {
379
+ std::string BLASSignature() const override {
380
+ std::string alpha_str = to_string_opmath<T>(alpha);
381
+ std::string activation_str = to_string_epilogue(activation);
382
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
383
+ "alpha: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, activation: %s, bias_type: %s, scale_type: %s, compute_type: %s }",
384
+ m, n, k, lda, ldb, ldc, ldc, alpha_str, transa, transb,
385
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), activation_str, BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>(), ComputeTypeFor<T>());
386
+ }
387
+
388
+ std::string Signature() const override {
389
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc);
390
+ }
391
+
392
+ size_t GetSizeA() const {
393
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
394
+ size_t size_dense = m * k;
395
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
396
+ }
397
+
398
+ size_t GetSizeB() const {
399
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
400
+ size_t size_dense = k * n;
401
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
402
+ }
403
+
404
+ size_t GetSizeC() const {
405
+ size_t size_stride = ldc * n;
406
+ size_t size_dense = m * n;
407
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
408
+ }
409
+
410
+ size_t GetSize(bool duplicate_inputs) const {
411
+ size_t size = GetSizeC();
412
+ if (duplicate_inputs) {
413
+ size += GetSizeA();
414
+ size += GetSizeB();
415
+ }
416
+ return size;
417
+ }
418
+
419
+ GemmAndBiasParams* DeepCopy(bool duplicate_inputs) const {
420
+ GemmAndBiasParams* copy = new GemmAndBiasParams;
421
+ *copy = *this;
422
+ c10::DeviceIndex device = 0;
423
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
424
+ size_t c_size = GetSizeC();
425
+ copy->c = static_cast<T*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
426
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
427
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
428
+ if (duplicate_inputs) {
429
+ size_t a_size = GetSizeA();
430
+ size_t b_size = GetSizeB();
431
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
432
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
433
+ copy->duplicate_inputs_ = true;
434
+ }
435
+ return copy;
436
+ }
437
+
438
+ // only call on object returned by DeepCopy
439
+ void Delete() {
440
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
441
+ if (duplicate_inputs_) {
442
+ // NOLINTNEXTLINE(*const-cast)
443
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
444
+ // NOLINTNEXTLINE(*const-cast)
445
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
446
+ }
447
+ }
448
+
449
+ TuningStatus NumericalCheck(GemmAndBiasParams<T> *other) {
450
+ auto c_dtype = c10::CppTypeToScalarType<T>::value;
451
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T)) ? OK : FAIL;
452
+ }
453
+
454
+ char transa{};
455
+ char transb{};
456
+ int64_t m{};
457
+ int64_t n{};
458
+ int64_t k{};
459
+ at::opmath_type<T> alpha{};
460
+ const T* a{};
461
+ int64_t lda{};
462
+ const T* b{};
463
+ int64_t ldb{};
464
+ T* c{};
465
+ int64_t ldc{};
466
+ const T* bias{};
467
+ at::cuda::blas::GEMMAndBiasActivationEpilogue activation{};
468
+ private:
469
+ bool duplicate_inputs_{false};
470
+ };
471
+
472
+ template <typename T>
473
+ struct GemmStridedBatchedParams : OpParams {
474
+ std::string BLASSignature() const override {
475
+ std::string alpha_str = to_string_opmath<T>(alpha);
476
+ std::string beta_str = to_string_opmath<T>(beta);
477
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: %ld, stride_b: %ld, stride_c: %ld, stride_d: %ld, "
478
+ "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: %ld, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, compute_type: %s }",
479
+ m, n, k, lda, ldb, ldc, ldc, stride_a, stride_b, stride_c, stride_c, alpha_str, beta_str, transa, transb, batch,
480
+ BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), BLASTypeName<T>(T{}), ComputeTypeFor<T>(), ComputeTypeFor<T>());
481
+ }
482
+
483
+ std::string Signature() const override {
484
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_B_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, batch, lda, ldb, ldc);
485
+ }
486
+
487
+ size_t GetSizeA() const {
488
+ size_t size_stride = stride_a * batch;
489
+ size_t size_dense = m * k * batch;
490
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
491
+ }
492
+
493
+ size_t GetSizeB() const {
494
+ size_t size_stride = stride_b * batch;
495
+ size_t size_dense = k * n * batch;
496
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
497
+ }
498
+
499
+ size_t GetSizeC() const {
500
+ size_t size_stride = stride_c * batch;
501
+ size_t size_dense = m * n * batch;
502
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
503
+ }
504
+
505
+ size_t GetSize(bool duplicate_inputs) const {
506
+ size_t size = GetSizeC();
507
+ if (duplicate_inputs) {
508
+ size += GetSizeA();
509
+ size += GetSizeB();
510
+ }
511
+ return size;
512
+ }
513
+
514
+ GemmStridedBatchedParams* DeepCopy(bool duplicate_inputs) const {
515
+ GemmStridedBatchedParams* copy = new GemmStridedBatchedParams;
516
+ *copy = *this;
517
+ c10::DeviceIndex device = 0;
518
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
519
+ size_t c_size = GetSizeC();
520
+ copy->c = static_cast<T*>(c10::cuda::CUDACachingAllocator::raw_alloc(c_size));
521
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
522
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
523
+ if (duplicate_inputs) {
524
+ size_t a_size = GetSizeA();
525
+ size_t b_size = GetSizeB();
526
+ // NOLINTNEXTLINE(*const-cast*)
527
+ copy->a = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(a_size));
528
+ // NOLINTNEXTLINE(*const-cast*)
529
+ copy->b = static_cast<const T*>(c10::cuda::CUDACachingAllocator::raw_alloc(b_size));
530
+ copy->duplicate_inputs_ = true;
531
+ }
532
+ return copy;
533
+ }
534
+
535
+ // only call on object returned by DeepCopy
536
+ void Delete() {
537
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
538
+ if (duplicate_inputs_) {
539
+ // NOLINTNEXTLINE(*const-cast*)
540
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(a));
541
+ // NOLINTNEXTLINE(*const-cast*)
542
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<T*>(b));
543
+ }
544
+ }
545
+
546
+ TuningStatus NumericalCheck(GemmStridedBatchedParams<T> *other) {
547
+ auto c_dtype = c10::CppTypeToScalarType<T>::value;
548
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T)) ? OK : FAIL;
549
+ }
550
+
551
+ char transa{};
552
+ char transb{};
553
+ int64_t m{};
554
+ int64_t n{};
555
+ int64_t k{};
556
+ at::opmath_type<T> alpha{};
557
+ const T* a{};
558
+ int64_t lda{};
559
+ int64_t stride_a{};
560
+ const T* b{};
561
+ int64_t ldb{};
562
+ int64_t stride_b{};
563
+ at::opmath_type<T> beta;
564
+ T* c{};
565
+ int64_t ldc{};
566
+ int64_t stride_c{};
567
+ int64_t batch{};
568
+ private:
569
+ bool duplicate_inputs_{false};
570
+ };
571
+
572
+ template <typename T>
573
+ struct ScaledGemmParams : OpParams {
574
+ ScaledGemmParams() = default;
575
+
576
+ std::string BLASSignature() const override {
577
+ // Excluding use_fast_accum and use_rowise booleans for now
578
+ return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, "
579
+ "transA: %c, transB: %c, batch_count: 1, scaleA: f32_r, scaleB: f32_r, a_type: %s, b_type: %s, c_type: %s, d_type: %s, bias_type: %s, scale_type: %s, compute_type: %s }",
580
+ m, n, k, lda, ldb, ldc, ldc, transa, transb,
581
+ ScalarTypeToBLASType(a_dtype), ScalarTypeToBLASType(b_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(bias_dtype),
582
+ ComputeTypeFor<T>(), ComputeTypeFor<T>());
583
+ }
584
+
585
+ std::string Signature() const override {
586
+ // In Blas.cpp, code defaults to a bias_dtype of Half even when there is no bias vector.
587
+ // Search for this line::
588
+ // params.bias_dtype = bias ? bias->scalar_type() : isFloat8Type(out_dtype_) ? at::ScalarType::Half : out_dtype_;
589
+ //
590
+ // In TunableOp, we must distinguish in param signature these two cases: with and without a bias vector.
591
+ return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld_rw_%d_bias_%s",
592
+ transa, transb, m, n, k, lda, ldb, ldc, use_rowwise,
593
+ bias_ptr == nullptr ? "None" : at::toString(bias_dtype));
594
+ }
595
+
596
+ size_t GetSizeA() const {
597
+ size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m);
598
+ size_t size_dense = m * k;
599
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
600
+ }
601
+
602
+ size_t GetSizeB() const {
603
+ size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k);
604
+ size_t size_dense = k * n;
605
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
606
+ }
607
+
608
+ size_t GetSizeC() const {
609
+ size_t size_stride = ldc * n;
610
+ size_t size_dense = m * n;
611
+ return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense);
612
+ }
613
+
614
+ size_t GetSize(bool duplicate_inputs) const {
615
+ size_t size = GetSizeC();
616
+ if (duplicate_inputs) {
617
+ size += GetSizeA();
618
+ size += GetSizeB();
619
+ }
620
+ return size;
621
+ }
622
+
623
+ ScaledGemmParams* DeepCopy(bool duplicate_inputs) const {
624
+ ScaledGemmParams* copy = new ScaledGemmParams;
625
+ *copy = *this;
626
+ c10::DeviceIndex device = 0;
627
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&device));
628
+ size_t c_size = GetSizeC();
629
+ copy->c = c10::cuda::CUDACachingAllocator::raw_alloc(c_size);
630
+ AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync(
631
+ copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true));
632
+ if (duplicate_inputs) {
633
+ size_t a_size = GetSizeA();
634
+ size_t b_size = GetSizeB();
635
+ copy->a = c10::cuda::CUDACachingAllocator::raw_alloc(a_size);
636
+ copy->b = c10::cuda::CUDACachingAllocator::raw_alloc(b_size);
637
+ copy->duplicate_inputs_ = true;
638
+ }
639
+ return copy;
640
+ }
641
+
642
+ // only call on object returned by DeepCopy
643
+ void Delete() {
644
+ c10::cuda::CUDACachingAllocator::raw_delete(c);
645
+ if (duplicate_inputs_) {
646
+ // NOLINTNEXTLINE(*const-cast*)
647
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<void*>(a));
648
+ // NOLINTNEXTLINE(*const-cast*)
649
+ c10::cuda::CUDACachingAllocator::raw_delete(const_cast<void*>(b));
650
+ }
651
+ }
652
+
653
+ TuningStatus NumericalCheck(ScaledGemmParams<T> *other) {
654
+ return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T)) ? OK : FAIL;
655
+ }
656
+
657
+ char transa{};
658
+ char transb{};
659
+ int64_t m{};
660
+ int64_t n{};
661
+ int64_t k{};
662
+ const void* a{};
663
+ const void* a_scale_ptr{};
664
+ int64_t lda{};
665
+ ScalarType a_dtype{};
666
+ ScalarType a_scale_dtype{};
667
+ const void* b{};
668
+ const void* b_scale_ptr{};
669
+ int64_t ldb{};
670
+ ScalarType b_dtype{};
671
+ ScalarType b_scale_dtype{};
672
+ const void* bias_ptr{};
673
+ ScalarType bias_dtype{};
674
+ void* c{};
675
+ const void* c_scale_ptr{};
676
+ int64_t ldc{};
677
+ ScalarType c_dtype{};
678
+ void* amax_ptr{};
679
+ bool use_fast_accum{};
680
+ bool use_rowwise{};
681
+ private:
682
+ bool duplicate_inputs_{false};
683
+ };
684
+
685
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmHipblaslt.h ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/cuda/CUDAContext.h>
7
+ #include <ATen/cuda/CUDADataType.h>
8
+ #include <ATen/cuda/tunable/TunableOp.h>
9
+ #include <ATen/cuda/tunable/GemmCommon.h>
10
+ #include <c10/cuda/CUDACachingAllocator.h>
11
+ #include <c10/util/StringUtil.h>
12
+ #include <fmt/printf.h>
13
+
14
+ #include <hipblaslt/hipblaslt.h>
15
+ #include <hipblaslt/hipblaslt-ext.hpp>
16
+
17
+ #define TORCH_HIPBLASLT_CHECK(EXPR) \
18
+ do { \
19
+ hipblasStatus_t __err = EXPR; \
20
+ TORCH_CHECK(__err == HIPBLAS_STATUS_SUCCESS, \
21
+ "hipblaslt error: ", \
22
+ hipblasStatusToString(__err), \
23
+ " when calling `" #EXPR "`"); \
24
+ } while (0)
25
+
26
+ namespace at::cuda::tunable {
27
+
28
+ template <typename T>
29
+ constexpr hipDataType HipDataTypeFor();
30
+
31
+ template <>
32
+ constexpr hipDataType HipDataTypeFor<float>() {
33
+ return HIP_R_32F;
34
+ }
35
+
36
+ template <>
37
+ constexpr hipDataType HipDataTypeFor<Half>() {
38
+ return HIP_R_16F;
39
+ }
40
+
41
+ template <>
42
+ constexpr hipDataType HipDataTypeFor<BFloat16>() {
43
+ return HIP_R_16BF;
44
+ }
45
+
46
+ template <>
47
+ constexpr hipDataType HipDataTypeFor<double>() {
48
+ return HIP_R_64F;
49
+ }
50
+
51
+ template <>
52
+ constexpr hipDataType HipDataTypeFor<c10::Float8_e4m3fnuz>() {
53
+ return HIP_R_8F_E4M3_FNUZ;
54
+ }
55
+
56
+ template <>
57
+ constexpr hipDataType HipDataTypeFor<c10::Float8_e5m2fnuz>() {
58
+ return HIP_R_8F_E5M2_FNUZ;
59
+ }
60
+
61
+ // This code is instantiated regardless of ROCm version.
62
+ // Prior to ROCm 6.3, we hard-code the known enum values.
63
+ template <>
64
+ constexpr hipDataType HipDataTypeFor<c10::Float8_e4m3fn>() {
65
+ #if ROCM_VERSION >= 60300
66
+ return HIP_R_8F_E4M3;
67
+ #else
68
+ return static_cast<hipDataType>(28);
69
+ #endif
70
+ }
71
+
72
+ template <>
73
+ constexpr hipDataType HipDataTypeFor<c10::Float8_e5m2>() {
74
+ #if ROCM_VERSION >= 60300
75
+ return HIP_R_8F_E5M2;
76
+ #else
77
+ return static_cast<hipDataType>(29);
78
+ #endif
79
+ }
80
+
81
+ // This type is not intended for matrix types but rather a scale factor.
82
+ // Return a dummy value to satisfy linker.
83
+ template <>
84
+ constexpr hipDataType HipDataTypeFor<c10::Float8_e8m0fnu>() {
85
+ return static_cast<hipDataType>(500);
86
+ }
87
+
88
+ template <typename T>
89
+ int GetBatchFromParams(const GemmParams<T>* params) {
90
+ return 1;
91
+ }
92
+
93
+ template <typename T>
94
+ int GetBatchFromParams(const GemmAndBiasParams<T>* params) {
95
+ return 1;
96
+ }
97
+
98
+ template <typename T>
99
+ int GetBatchFromParams(const GemmStridedBatchedParams<T>* params) {
100
+ return params->batch;
101
+ }
102
+
103
+ template <typename T>
104
+ int GetBatchFromParams(const ScaledGemmParams<T>* params) {
105
+ return 1;
106
+ }
107
+
108
+ template <typename T>
109
+ int GetStrideAFromParams(const GemmParams<T>* params) {
110
+ return 1;
111
+ }
112
+
113
+ template <typename T>
114
+ int GetStrideAFromParams(const GemmAndBiasParams<T>* params) {
115
+ return 1;
116
+ }
117
+
118
+ template <typename T>
119
+ int GetStrideAFromParams(const GemmStridedBatchedParams<T>* params) {
120
+ return params->stride_a;
121
+ }
122
+
123
+ template <typename T>
124
+ int GetStrideAFromParams(const ScaledGemmParams<T>* params) {
125
+ return 1;
126
+ }
127
+
128
+ template <typename T>
129
+ int GetStrideBFromParams(const GemmParams<T>* params) {
130
+ return 1;
131
+ }
132
+
133
+ template <typename T>
134
+ int GetStrideBFromParams(const GemmAndBiasParams<T>* params) {
135
+ return 1;
136
+ }
137
+
138
+ template <typename T>
139
+ int GetStrideBFromParams(const GemmStridedBatchedParams<T>* params) {
140
+ return params->stride_b;
141
+ }
142
+
143
+ template <typename T>
144
+ int GetStrideBFromParams(const ScaledGemmParams<T>* params) {
145
+ return 1;
146
+ }
147
+
148
+ template <typename T>
149
+ int GetStrideCFromParams(const GemmParams<T>* params) {
150
+ return 1;
151
+ }
152
+
153
+ template <typename T>
154
+ int GetStrideCFromParams(const GemmAndBiasParams<T>* params) {
155
+ return 1;
156
+ }
157
+
158
+ template <typename T>
159
+ int GetStrideCFromParams(const GemmStridedBatchedParams<T>* params) {
160
+ return params->stride_c;
161
+ }
162
+
163
+ template <typename T>
164
+ int GetStrideCFromParams(const ScaledGemmParams<T>* params) {
165
+ return 1;
166
+ }
167
+
168
+ template <typename T>
169
+ float GetAlphaFromParams(const GemmParams<T>* params) {
170
+ return params->alpha;
171
+ }
172
+
173
+ template <typename T>
174
+ float GetAlphaFromParams(const GemmAndBiasParams<T>* params) {
175
+ return params->alpha;
176
+ }
177
+
178
+ template <typename T>
179
+ float GetAlphaFromParams(const GemmStridedBatchedParams<T>* params) {
180
+ return params->alpha;
181
+ }
182
+
183
+ template <typename T>
184
+ float GetAlphaFromParams(const ScaledGemmParams<T>* params) {
185
+ return 1.0;
186
+ }
187
+
188
+ template <typename T>
189
+ float GetBetaFromParams(const GemmParams<T>* params) {
190
+ return params->beta;
191
+ }
192
+
193
+ template <typename T>
194
+ float GetBetaFromParams(const GemmAndBiasParams<T>* params) {
195
+ return 0.0;
196
+ }
197
+
198
+ template <typename T>
199
+ float GetBetaFromParams(const GemmStridedBatchedParams<T>* params) {
200
+ return params->beta;
201
+ }
202
+
203
+ template <typename T>
204
+ float GetBetaFromParams(const ScaledGemmParams<T>* params) {
205
+ return 0.0;
206
+ }
207
+
208
+ template <typename T>
209
+ bool GetUseRowwiseFromParams(const GemmParams<T>* params) {
210
+ return false;
211
+ }
212
+
213
+ template <typename T>
214
+ bool GetUseRowwiseFromParams(const GemmAndBiasParams<T>* params) {
215
+ return false;
216
+ }
217
+
218
+ template <typename T>
219
+ bool GetUseRowwiseFromParams(const GemmStridedBatchedParams<T>* params) {
220
+ return false;
221
+ }
222
+
223
+ template <typename T>
224
+ bool GetUseRowwiseFromParams(const ScaledGemmParams<T>* params) {
225
+ return params->use_rowwise;
226
+ }
227
+
228
+ template <typename T>
229
+ const void* GetAScalePointerFromParams(const GemmParams<T>* params) {
230
+ return nullptr;
231
+ }
232
+
233
+ template <typename T>
234
+ const void* GetAScalePointerFromParams(const GemmAndBiasParams<T>* params) {
235
+ return nullptr;
236
+ }
237
+
238
+ template <typename T>
239
+ const void* GetAScalePointerFromParams(const GemmStridedBatchedParams<T>* params) {
240
+ return nullptr;
241
+ }
242
+
243
+ template <typename T>
244
+ const void* GetAScalePointerFromParams(const ScaledGemmParams<T>* params) {
245
+ return params->a_scale_ptr;
246
+ }
247
+
248
+ template <typename T>
249
+ const void* GetBScalePointerFromParams(const GemmParams<T>* params) {
250
+ return nullptr;
251
+ }
252
+
253
+ template <typename T>
254
+ const void* GetBScalePointerFromParams(const GemmAndBiasParams<T>* params) {
255
+ return nullptr;
256
+ }
257
+
258
+ template <typename T>
259
+ const void* GetBScalePointerFromParams(const GemmStridedBatchedParams<T>* params) {
260
+ return nullptr;
261
+ }
262
+
263
+ template <typename T>
264
+ const void* GetBScalePointerFromParams(const ScaledGemmParams<T>* params) {
265
+ return params->b_scale_ptr;
266
+ }
267
+
268
+ template <typename T>
269
+ const void* GetDScalePointerFromParams(const GemmParams<T>* params) {
270
+ return nullptr;
271
+ }
272
+
273
+ template <typename T>
274
+ const void* GetDScalePointerFromParams(const GemmAndBiasParams<T>* params) {
275
+ return nullptr;
276
+ }
277
+
278
+ template <typename T>
279
+ const void* GetDScalePointerFromParams(const GemmStridedBatchedParams<T>* params) {
280
+ return nullptr;
281
+ }
282
+
283
+ template <typename T>
284
+ const void* GetDScalePointerFromParams(const ScaledGemmParams<T>* params) {
285
+ return params->c_scale_ptr;
286
+ }
287
+
288
+ template <typename T>
289
+ const void* GetBiasPointerFromParams(const GemmParams<T>* params) {
290
+ return nullptr;
291
+ }
292
+
293
+ template <typename T>
294
+ const void* GetBiasPointerFromParams(const GemmAndBiasParams<T>* params) {
295
+ return params->bias;
296
+ }
297
+
298
+ template <typename T>
299
+ const void* GetBiasPointerFromParams(const GemmStridedBatchedParams<T>* params) {
300
+ return nullptr;
301
+ }
302
+
303
+ template <typename T>
304
+ const void* GetBiasPointerFromParams(const ScaledGemmParams<T>* params) {
305
+ return params->bias_ptr;
306
+ }
307
+
308
+ template <typename T>
309
+ hipDataType GetBiasTypeFromParams(const GemmParams<T>* params) {
310
+ return HIP_R_32F;
311
+ }
312
+
313
+ template <typename T>
314
+ hipDataType GetBiasTypeFromParams(const GemmAndBiasParams<T>* params) {
315
+ return HipDataTypeFor<T>();
316
+ }
317
+
318
+ template <typename T>
319
+ hipDataType GetBiasTypeFromParams(const GemmStridedBatchedParams<T>* params) {
320
+ return HIP_R_32F;
321
+ }
322
+
323
+ template <typename T>
324
+ hipDataType GetBiasTypeFromParams(const ScaledGemmParams<T>* params) {
325
+ return at::cuda::ScalarTypeToCudaDataType(params->bias_dtype);
326
+ }
327
+
328
+ template <typename T>
329
+ at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmParams<T>* params) {
330
+ return at::cuda::blas::GEMMAndBiasActivationEpilogue::None;
331
+ }
332
+
333
+ template <typename T>
334
+ at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmAndBiasParams<T>* params) {
335
+ return params->activation;
336
+ }
337
+
338
+ template <typename T>
339
+ at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmStridedBatchedParams<T>* params) {
340
+ return at::cuda::blas::GEMMAndBiasActivationEpilogue::None;
341
+ }
342
+
343
+ template <typename T>
344
+ at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const ScaledGemmParams<T>* params) {
345
+ return at::cuda::blas::GEMMAndBiasActivationEpilogue::None;
346
+ }
347
+
348
+ static hipblasOperation_t _hipblasOpFromChar(char op) {
349
+ switch (op) {
350
+ case 'n':
351
+ case 'N':
352
+ return HIPBLAS_OP_N;
353
+ case 't':
354
+ case 'T':
355
+ return HIPBLAS_OP_T;
356
+ case 'c':
357
+ case 'C':
358
+ return HIPBLAS_OP_C;
359
+ }
360
+ TORCH_CHECK(false,
361
+ "_hipblasOpFromChar input should be 't', 'n' or 'c' but got `", op, "`");
362
+ }
363
+
364
+ static char _charFromhipblasOp(hipblasOperation_t op) {
365
+ switch (op) {
366
+ case HIPBLAS_OP_N:
367
+ return 'N';
368
+ case HIPBLAS_OP_T:
369
+ return 'T';
370
+ case HIPBLAS_OP_C:
371
+ return 'C';
372
+ }
373
+ TORCH_CHECK(false,
374
+ "_charFromhipblasOp input should be HIPBLAS_OP_N/T/C but got `", op, "`");
375
+ }
376
+
377
+ static hipblasOperation_t MapLayoutToHipBlasLt(BlasOp layout) {
378
+ if (layout == BlasOp::N) {
379
+ return HIPBLAS_OP_N;
380
+ }
381
+ return HIPBLAS_OP_T;
382
+ }
383
+
384
+ static size_t GetHipblasltWorkspaceSize() {
385
+ static const char * env = getenv("HIPBLASLT_WORKSPACE_SIZE");
386
+ // 256MB is max workspace size allowed for hipblaslt
387
+ // hipblaslt-bench uses 32MB
388
+ // recommendation from hipblaslt author was 76MB
389
+ // TunableOp hipBLASLt workspace size is aligned with
390
+ // PyTorch's default in CUDABlas.cpp (_parseChosenWorkspaceSize)
391
+ size_t workspace_size = 76*1024;
392
+ if (env) {
393
+ try {
394
+ workspace_size = std::stoi(env);
395
+ } catch(std::invalid_argument const& e) {
396
+ TORCH_WARN("invalid HIPBLASLT_WORKSPACE_SIZE,",
397
+ " using default workspace size of ", workspace_size, " KiB.");
398
+ } catch(std::out_of_range const& e) {
399
+ TORCH_WARN("HIPBLASLT_WORKSPACE_SIZE out of range,",
400
+ " using default workspace size of ", workspace_size, " KiB.");
401
+ }
402
+ }
403
+ return workspace_size * 1024;
404
+ }
405
+
406
+ template <typename T, cublasStatus_t (*destructor)(T*)>
407
+ struct HipBlasLtDeleter {
408
+ void operator()(T* x) {
409
+ if (x != nullptr) {
410
+ TORCH_CUDABLAS_CHECK(destructor(x));
411
+ }
412
+ }
413
+ };
414
+
415
+ template <typename T, hipblasStatus_t (*destructor)(T*)>
416
+ class HipBlasLtDescriptor {
417
+ public:
418
+ T* descriptor() const {
419
+ return descriptor_.get();
420
+ }
421
+ T* descriptor() {
422
+ return descriptor_.get();
423
+ }
424
+
425
+ protected:
426
+ std::unique_ptr<T, HipBlasLtDeleter<T, destructor>> descriptor_;
427
+ };
428
+
429
+ class HipBlasLtMatmulDescriptor : public HipBlasLtDescriptor<
430
+ hipblasLtMatmulDescOpaque_t,
431
+ &hipblasLtMatmulDescDestroy> {
432
+ public:
433
+ HipBlasLtMatmulDescriptor(
434
+ hipblasComputeType_t compute_type,
435
+ hipDataType scale_type) {
436
+ hipblasLtMatmulDesc_t raw_descriptor = nullptr;
437
+ TORCH_HIPBLASLT_CHECK(
438
+ hipblasLtMatmulDescCreate(&raw_descriptor, compute_type, scale_type));
439
+ descriptor_.reset(raw_descriptor);
440
+ }
441
+ template <typename T>
442
+ inline void setAttribute(hipblasLtMatmulDescAttributes_t attr, const T value) {
443
+ TORCH_HIPBLASLT_CHECK(::hipblasLtMatmulDescSetAttribute(descriptor(), attr, &value, sizeof(T)));
444
+ }
445
+ };
446
+
447
+ template <typename AT, typename BT, typename CT, BlasOp ALayout, BlasOp BLayout, typename ParamsT>
448
+ class HipblasltGemmOp : public Callable<ParamsT> {
449
+ public:
450
+ HipblasltGemmOp(hipblasLtMatmulAlgo_t algo) : algo_{algo} {}
451
+
452
+ TuningStatus Call(const ParamsT* params) override {
453
+ hipblasOperation_t transa_outer = MapLayoutToHipBlasLt(ALayout);
454
+ hipblasOperation_t transb_outer = MapLayoutToHipBlasLt(BLayout);
455
+ auto a_datatype = HipDataTypeFor<AT>();
456
+ auto b_datatype = HipDataTypeFor<BT>();
457
+ auto in_out_datatype = HipDataTypeFor<CT>();
458
+ auto opa = _hipblasOpFromChar(params->transa);
459
+ auto opb = _hipblasOpFromChar(params->transb);
460
+
461
+ TORCH_CHECK(transa_outer == opa && transb_outer == opb, "trans mismatch, shouldn't happen");
462
+
463
+ float alpha = GetAlphaFromParams<CT>(params);
464
+ float beta = GetBetaFromParams<CT>(params);
465
+
466
+ hipblasLtMatrixLayout_t mat_a, mat_b, mat_c;
467
+ if (opa == HIPBLAS_OP_N) {
468
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_a, a_datatype, params->m, params->k, params->lda));
469
+ }
470
+ else {
471
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_a, a_datatype, params->k, params->m, params->lda));
472
+ }
473
+ if (opb == HIPBLAS_OP_N) {
474
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_b, b_datatype, params->k, params->n, params->ldb));
475
+ }
476
+ else {
477
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_b, b_datatype, params->n, params->k, params->ldb));
478
+ }
479
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_c, in_out_datatype, params->m, params->n, params->ldc));
480
+
481
+ // specific to batched gemmm
482
+ int batch = GetBatchFromParams<CT>(params);
483
+ if (batch > 1) {
484
+ int64_t stride_a = GetStrideAFromParams<CT>(params);
485
+ int64_t stride_b = GetStrideBFromParams<CT>(params);
486
+ int64_t stride_c = GetStrideCFromParams<CT>(params);
487
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
488
+ mat_a, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch)));
489
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
490
+ mat_a, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_a, sizeof(stride_a)));
491
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
492
+ mat_b, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch)));
493
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
494
+ mat_b, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_b, sizeof(stride_b)));
495
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
496
+ mat_c, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch)));
497
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute(
498
+ mat_c, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_c, sizeof(stride_c)));
499
+ }
500
+
501
+ HipBlasLtMatmulDescriptor matmul(HIPBLAS_COMPUTE_32F, HIP_R_32F);
502
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_TRANSA, opa);
503
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_TRANSB, opb);
504
+
505
+ // specific to scaled gemm
506
+ const void* mat1_scale_ptr = GetAScalePointerFromParams<CT>(params);
507
+ const void* mat2_scale_ptr = GetBScalePointerFromParams<CT>(params);
508
+ const void* result_scale_ptr = GetDScalePointerFromParams<CT>(params);
509
+ if (mat1_scale_ptr && mat2_scale_ptr) {
510
+ #ifdef HIPBLASLT_VEC_EXT
511
+ if (GetUseRowwiseFromParams<CT>(params)) {
512
+ // swapped
513
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER_VEC_EXT, mat2_scale_ptr);
514
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER_VEC_EXT, mat1_scale_ptr);
515
+ }
516
+ else
517
+ #endif
518
+ {
519
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER, mat1_scale_ptr);
520
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER, mat2_scale_ptr);
521
+ }
522
+ }
523
+ if (result_scale_ptr) {
524
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_D_SCALE_POINTER, result_scale_ptr);
525
+ }
526
+
527
+ const void* bias_ptr = GetBiasPointerFromParams<CT>(params);
528
+ auto bias_datatype = GetBiasTypeFromParams<CT>(params);
529
+ if (bias_ptr) {
530
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_BIAS_POINTER, bias_ptr);
531
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_BIAS_DATA_TYPE, bias_datatype);
532
+ auto activation = GetActivationFromParams<CT>(params);
533
+ if (activation == at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU) {
534
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_RELU_BIAS);
535
+ }
536
+ else if (activation == at::cuda::blas::GEMMAndBiasActivationEpilogue::GELU) {
537
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_GELU_BIAS);
538
+ }
539
+ else {
540
+ matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_BIAS);
541
+ }
542
+ }
543
+
544
+ size_t workspace_size = GetHipblasltWorkspaceSize();
545
+
546
+ auto op_handle = at::cuda::getCurrentCUDABlasLtHandle();
547
+
548
+ size_t ret_workspace_size = 0;
549
+ auto status = hipblaslt_ext::matmulIsAlgoSupported(op_handle,
550
+ matmul.descriptor(),
551
+ &alpha,
552
+ mat_a,
553
+ mat_b,
554
+ &beta,
555
+ mat_c,
556
+ mat_c,
557
+ algo_,
558
+ ret_workspace_size);
559
+
560
+ if (status == HIPBLAS_STATUS_SUCCESS) {
561
+ if (ret_workspace_size >= workspace_size) {
562
+ return FAIL;
563
+ }
564
+ }
565
+ else {
566
+ return FAIL;
567
+ }
568
+
569
+ void* workspace_buffer = nullptr;
570
+ if (workspace_size > 0) {
571
+ workspace_buffer = c10::cuda::CUDACachingAllocator::raw_alloc(workspace_size);
572
+ }
573
+
574
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatmul(op_handle,
575
+ matmul.descriptor(),
576
+ &alpha,
577
+ params->a,
578
+ mat_a,
579
+ params->b,
580
+ mat_b,
581
+ &beta,
582
+ params->c,
583
+ mat_c,
584
+ params->c,
585
+ mat_c,
586
+ &algo_,
587
+ workspace_buffer,
588
+ workspace_size,
589
+ at::cuda::getCurrentCUDAStream()));
590
+
591
+ //TORCH_HIPBLASLT_CHECK(hipblasLtMatmulDescDestroy(matmul));
592
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_a));
593
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_b));
594
+ TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_c));
595
+ if (workspace_size > 0) {
596
+ c10::cuda::CUDACachingAllocator::raw_delete(workspace_buffer);
597
+ }
598
+ return OK;
599
+ }
600
+
601
+ private:
602
+ hipblasLtMatmulAlgo_t algo_;
603
+ };
604
+
605
+ template <typename AT, typename BT, typename CT, BlasOp ALayout, BlasOp BLayout, typename ParamsT>
606
+ auto GetHipBlasLtTypeStringAndOps() {
607
+ hipblasOperation_t transa_outer = MapLayoutToHipBlasLt(ALayout);
608
+ hipblasOperation_t transb_outer = MapLayoutToHipBlasLt(BLayout);
609
+ auto a_datatype = HipDataTypeFor<AT>();
610
+ auto b_datatype = HipDataTypeFor<BT>();
611
+ auto in_out_datatype = HipDataTypeFor<CT>();
612
+ std::vector<hipblasLtMatmulHeuristicResult_t> heuristic_result;
613
+
614
+ hipblasLtHandle_t handle;
615
+ TORCH_HIPBLASLT_CHECK(hipblasLtCreate(&handle));
616
+ TORCH_HIPBLASLT_CHECK(hipblaslt_ext::getAllAlgos(handle,
617
+ hipblaslt_ext::GemmType::HIPBLASLT_GEMM,
618
+ transa_outer,
619
+ transb_outer,
620
+ a_datatype,
621
+ b_datatype,
622
+ in_out_datatype,
623
+ in_out_datatype,
624
+ HIPBLAS_COMPUTE_32F,
625
+ heuristic_result));
626
+ TORCH_HIPBLASLT_CHECK(hipblasLtDestroy(handle));
627
+
628
+ int returned_algo_count = heuristic_result.size();
629
+ std::vector<std::pair<std::string, std::unique_ptr<Callable<ParamsT>>>> ret;
630
+ for (int i = 0; i < returned_algo_count; i++) {
631
+ auto algo = heuristic_result[i].algo;
632
+ int algo_index = hipblaslt_ext::getIndexFromAlgo(algo);
633
+ auto callable = std::make_unique<HipblasltGemmOp<AT, BT, CT, ALayout, BLayout, ParamsT>>(algo);
634
+ std::string type_string = fmt::sprintf("Gemm_Hipblaslt_%d", algo_index);
635
+ ret.emplace_back(type_string, std::move(callable));
636
+ }
637
+
638
+ return ret;
639
+ }
640
+
641
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
642
+ auto GetHipBlasLtGemmTypeStringAndOps() {
643
+ return GetHipBlasLtTypeStringAndOps<T, T, T, ALayout, BLayout, GemmParams<T>>();
644
+ }
645
+
646
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
647
+ auto GetHipBlasLtGemmAndBiasTypeStringAndOps() {
648
+ return GetHipBlasLtTypeStringAndOps<T, T, T, ALayout, BLayout, GemmAndBiasParams<T>>();
649
+ }
650
+
651
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
652
+ auto GetHipBlasLtGemmStridedBatchedTypeStringAndOps() {
653
+ return GetHipBlasLtTypeStringAndOps<T, T, T, ALayout, BLayout, GemmStridedBatchedParams<T>>();
654
+ }
655
+
656
+ template <typename AT, typename BT, typename CT, BlasOp ALayout, BlasOp BLayout>
657
+ auto GetHipBlasLtScaledGemmTypeStringAndOps() {
658
+ return GetHipBlasLtTypeStringAndOps<AT, BT, CT, ALayout, BLayout, ScaledGemmParams<CT>>();
659
+ }
660
+
661
+ #undef TORCH_HIPBLASLT_CHECK
662
+
663
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/GemmRocblas.h ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/cuda/CUDAContext.h>
7
+ #include <ATen/cuda/tunable/TunableOp.h>
8
+ #include <ATen/cuda/tunable/GemmCommon.h>
9
+ #include <c10/util/StringUtil.h>
10
+ #include <fmt/printf.h>
11
+
12
+ #define ROCBLAS_BETA_FEATURES_API
13
+ #include <rocblas/rocblas.h>
14
+
15
+ #define TORCH_ROCBLAS_CHECK(EXPR) \
16
+ do { \
17
+ rocblas_status __err = EXPR; \
18
+ TORCH_CHECK(__err == rocblas_status_success, \
19
+ "rocblas error: ", \
20
+ rocblas_status_to_string(__err), \
21
+ " when calling `" #EXPR "`"); \
22
+ } while (0)
23
+
24
+ namespace at::cuda::tunable {
25
+
26
+ template <typename T>
27
+ constexpr rocblas_datatype RocBlasDataTypeFor();
28
+
29
+ template <>
30
+ constexpr rocblas_datatype RocBlasDataTypeFor<float>() {
31
+ return rocblas_datatype_f32_r;
32
+ }
33
+
34
+ template <>
35
+ constexpr rocblas_datatype RocBlasDataTypeFor<double>() {
36
+ return rocblas_datatype_f64_r;
37
+ }
38
+
39
+ template <>
40
+ constexpr rocblas_datatype RocBlasDataTypeFor<Half>() {
41
+ return rocblas_datatype_f16_r;
42
+ }
43
+
44
+ template <>
45
+ constexpr rocblas_datatype RocBlasDataTypeFor<BFloat16>() {
46
+ return rocblas_datatype_bf16_r;
47
+ }
48
+
49
+ template <>
50
+ constexpr rocblas_datatype RocBlasDataTypeFor<c10::complex<float>>() {
51
+ return rocblas_datatype_f32_c;
52
+ }
53
+
54
+ template <>
55
+ constexpr rocblas_datatype RocBlasDataTypeFor<c10::complex<double>>() {
56
+ return rocblas_datatype_f64_c;
57
+ }
58
+
59
+ template <typename T>
60
+ constexpr rocblas_datatype RocBlasComputeTypeFor();
61
+
62
+ template <>
63
+ constexpr rocblas_datatype RocBlasComputeTypeFor<float>() {
64
+ return rocblas_datatype_f32_r;
65
+ }
66
+
67
+ template <>
68
+ constexpr rocblas_datatype RocBlasComputeTypeFor<double>() {
69
+ return rocblas_datatype_f64_r;
70
+ }
71
+
72
+ template <>
73
+ constexpr rocblas_datatype RocBlasComputeTypeFor<Half>() {
74
+ // Note that we're returning the _compute_ type for a given datatype.
75
+ // As of 12/2022, using compute type FP16 for 16-bit floats was much
76
+ // slower than using compute type FP32. So we use FP32 compute even for
77
+ // FP16 datatypes. This is how GEMM is implemented even in the function
78
+ // rocblasGemmHelper (see fpgeneric.h)
79
+ return rocblas_datatype_f32_r;
80
+ }
81
+
82
+ template <>
83
+ constexpr rocblas_datatype RocBlasComputeTypeFor<BFloat16>() {
84
+ // Note that we're returning the _compute_ type for a given datatype.
85
+ // As of 12/2022, using compute type FP16 for 16-bit floats was much
86
+ // slower than using compute type FP32. So we use FP32 compute even for
87
+ // BF16 datatypes. This is how GEMM is implemented even in the function
88
+ // rocblasGemmHelper (see fpgeneric.h)
89
+ return rocblas_datatype_f32_r;
90
+ }
91
+
92
+ template <>
93
+ constexpr rocblas_datatype RocBlasComputeTypeFor<c10::complex<float>>() {
94
+ return rocblas_datatype_f32_c;
95
+ }
96
+
97
+ template <>
98
+ constexpr rocblas_datatype RocBlasComputeTypeFor<c10::complex<double>>() {
99
+ return rocblas_datatype_f64_c;
100
+ }
101
+
102
+ template <typename T>
103
+ auto DoCastForHalfOrBfloat16(const T fp) {
104
+ return fp;
105
+ }
106
+
107
+ template <>
108
+ inline auto DoCastForHalfOrBfloat16<Half>(const Half fp) {
109
+ // alpha and beta should be the same as compute_type, in Half case it is float.
110
+ float h = fp;
111
+ return h;
112
+ }
113
+
114
+ template <>
115
+ inline auto DoCastForHalfOrBfloat16<BFloat16>(const BFloat16 fp) {
116
+ // alpha and beta should be the same as compute_type, in bfloat16 case it is float.
117
+ float h = fp;
118
+ return h;
119
+ }
120
+
121
+ static rocblas_operation _rocblasOpFromChar(char op) {
122
+ switch (op) {
123
+ case 'n':
124
+ case 'N':
125
+ return rocblas_operation_none;
126
+ case 't':
127
+ case 'T':
128
+ return rocblas_operation_transpose;
129
+ case 'c':
130
+ case 'C':
131
+ return rocblas_operation_conjugate_transpose;
132
+ }
133
+ TORCH_CHECK(false,
134
+ "_rocblasOpFromChar input should be 't', 'n' or 'c' but got `", op, "`");
135
+ }
136
+
137
+ template <typename T>
138
+ class RocblasGemmOp : public Callable<GemmParams<T>> {
139
+ public:
140
+ RocblasGemmOp(int solution) : solution_{solution} {}
141
+
142
+ TuningStatus Call(const GemmParams<T>* params) override {
143
+ auto input_output_type = RocBlasDataTypeFor<T>();
144
+ auto compute_type = RocBlasComputeTypeFor<T>();
145
+ auto h_a = DoCastForHalfOrBfloat16(params->alpha);
146
+ auto h_b = DoCastForHalfOrBfloat16(params->beta);
147
+ auto status = rocblas_gemm_ex(
148
+ (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(),
149
+ _rocblasOpFromChar(params->transa),
150
+ _rocblasOpFromChar(params->transb),
151
+ params->m, params->n, params->k,
152
+ &h_a,
153
+ params->a, input_output_type, params->lda,
154
+ params->b, input_output_type, params->ldb,
155
+ &h_b,
156
+ params->c, input_output_type, params->ldc,
157
+ params->c, input_output_type, params->ldc,
158
+ compute_type,
159
+ rocblas_gemm_algo_solution_index,
160
+ solution_,
161
+ rocblas_gemm_flags_none);
162
+ if (status != rocblas_status_success) {
163
+ return FAIL;
164
+ }
165
+ return OK;
166
+ }
167
+
168
+ private:
169
+ int solution_;
170
+ };
171
+
172
+ template <typename T>
173
+ auto GetRocBlasGemmTypeStringAndOps() {
174
+ rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle();
175
+ int solution_size;
176
+ auto input_output_type = RocBlasDataTypeFor<T>();
177
+ auto compute_type = RocBlasComputeTypeFor<T>();
178
+ // Get the number of available solutions
179
+ TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle,
180
+ input_output_type,
181
+ input_output_type,
182
+ compute_type,
183
+ rocblas_gemm_flags_none,
184
+ nullptr,
185
+ &solution_size));
186
+ std::vector<int> solutions(solution_size);
187
+ // Get the list of available solutions
188
+ TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle,
189
+ input_output_type,
190
+ input_output_type,
191
+ compute_type,
192
+ rocblas_gemm_flags_none,
193
+ solutions.data(),
194
+ &solution_size));
195
+ std::vector<std::pair<std::string, std::unique_ptr<Callable<GemmParams<T>>>>> ret;
196
+ for (size_t i = 0; i < solutions.size(); ++i) {
197
+ auto callable = std::make_unique<RocblasGemmOp<T>>(solutions[i]);
198
+ ret.emplace_back(std::make_pair(fmt::sprintf("Gemm_Rocblas_%d", solutions[i]), std::move(callable)));
199
+ }
200
+ return ret;
201
+ }
202
+
203
+ template <typename T>
204
+ class RocblasGemmStridedBatchedOp : public Callable<GemmStridedBatchedParams<T>> {
205
+ public:
206
+ RocblasGemmStridedBatchedOp(int solution) : solution_{solution} {}
207
+
208
+ TuningStatus Call(const GemmStridedBatchedParams<T>* params) override {
209
+ auto input_output_type = RocBlasDataTypeFor<T>();
210
+ auto compute_type = RocBlasComputeTypeFor<T>();
211
+ auto h_a = DoCastForHalfOrBfloat16(params->alpha);
212
+ auto h_b = DoCastForHalfOrBfloat16(params->beta);
213
+ auto status = rocblas_gemm_strided_batched_ex(
214
+ (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(),
215
+ _rocblasOpFromChar(params->transa),
216
+ _rocblasOpFromChar(params->transb),
217
+ params->m, params->n, params->k,
218
+ &h_a,
219
+ params->a, input_output_type, params->lda, params->stride_a,
220
+ params->b, input_output_type, params->ldb, params->stride_b,
221
+ &h_b,
222
+ params->c, input_output_type, params->ldc, params->stride_c,
223
+ params->c, input_output_type, params->ldc, params->stride_c,
224
+ params->batch,
225
+ compute_type,
226
+ rocblas_gemm_algo_solution_index,
227
+ solution_,
228
+ rocblas_gemm_flags_none);
229
+ if (status != rocblas_status_success) {
230
+ return FAIL;
231
+ }
232
+ return OK;
233
+ }
234
+
235
+ private:
236
+ int solution_;
237
+ };
238
+
239
+ template <typename T>
240
+ auto GetRocBlasGemmStridedBatchedTypeStringAndOps() {
241
+ rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle();
242
+ int solution_size;
243
+ auto input_output_type = RocBlasDataTypeFor<T>();
244
+ auto compute_type = RocBlasComputeTypeFor<T>();
245
+ // Get the number of available solutions
246
+ TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle,
247
+ input_output_type,
248
+ input_output_type,
249
+ compute_type,
250
+ rocblas_gemm_flags_none,
251
+ nullptr,
252
+ &solution_size));
253
+ std::vector<int> solutions(solution_size);
254
+ // Get the list of available solutions
255
+ TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle,
256
+ input_output_type,
257
+ input_output_type,
258
+ compute_type,
259
+ rocblas_gemm_flags_none,
260
+ solutions.data(),
261
+ &solution_size));
262
+ // Sort the solutions in ascending order to make the solution vector deterministic across runs
263
+ std::sort(solutions.begin(), solutions.end());
264
+
265
+ std::vector<std::pair<std::string, std::unique_ptr<Callable<GemmStridedBatchedParams<T>>>>> ret;
266
+ for (size_t i = 0; i < solutions.size(); ++i) {
267
+ auto callable = std::make_unique<RocblasGemmStridedBatchedOp<T>>(solutions[i]);
268
+ ret.emplace_back(std::make_pair(c10::str("Gemm_Rocblas_", solutions[i]), std::move(callable)));
269
+ }
270
+ return ret;
271
+ }
272
+
273
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/StreamTimer.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original TunableOp is from onnxruntime.
2
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
3
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ //
7
+ // Adapting TunableOp into PyTorch
8
+ // Copyright (c) Advanced Micro Devices, Inc.
9
+ //
10
+ #pragma once
11
+
12
+ #include <cuda_runtime.h>
13
+
14
+ #include <ATen/cuda/tunable/Tunable.h>
15
+
16
+ namespace at::cuda::tunable {
17
+
18
+ class StreamTimer : public ITimer {
19
+ public:
20
+ StreamTimer();
21
+ ~StreamTimer() override;
22
+
23
+ void Start() override;
24
+
25
+ void End() override;
26
+
27
+ float Duration() override;
28
+
29
+ private:
30
+ cudaEvent_t start_{};
31
+ cudaEvent_t end_{};
32
+ };
33
+
34
+ class StreamTimerNoSync : public ITimer {
35
+ public:
36
+ StreamTimerNoSync();
37
+ ~StreamTimerNoSync() override;
38
+
39
+ void Start() override;
40
+
41
+ void End() override;
42
+
43
+ float Duration() override;
44
+
45
+ private:
46
+ cudaEvent_t start_{};
47
+ cudaEvent_t end_{};
48
+ };
49
+
50
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/Tunable.h ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original TunableOp is from onnxruntime.
2
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
3
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ //
7
+ // Adapting TunableOp into PyTorch
8
+ // Copyright (c) Advanced Micro Devices, Inc.
9
+ //
10
+ #pragma once
11
+
12
+ #include <c10/util/CallOnce.h>
13
+ #include <c10/util/StringUtil.h>
14
+ #include <c10/util/env.h>
15
+
16
+ #include <fstream>
17
+ #include <functional>
18
+ #include <iostream>
19
+ #include <memory>
20
+ #include <mutex>
21
+ #include <string>
22
+ #include <unordered_map>
23
+ #include <unordered_set>
24
+ #include <utility>
25
+
26
+ #define TUNABLE_LOGV(LEVEL, ...) getTuningContext()->Log(LEVEL, __VA_ARGS__)
27
+ #define TUNABLE_LOG1(...) TUNABLE_LOGV(1, __VA_ARGS__)
28
+ #define TUNABLE_LOG2(...) TUNABLE_LOGV(2, __VA_ARGS__)
29
+ #define TUNABLE_LOG3(...) TUNABLE_LOGV(3, __VA_ARGS__)
30
+
31
+ namespace at::cuda::tunable {
32
+
33
+ enum TORCH_CUDA_CPP_API TuningStatus {
34
+ OK = 0,
35
+ FAIL = 1,
36
+ UNSUPPORTED = 2,
37
+ };
38
+
39
+ // Mapping from params signature to kernel id
40
+ class TORCH_CUDA_CPP_API ResultEntry {
41
+ public:
42
+ explicit ResultEntry(std::string key, double time) : key_(std::move(key)), time_(time) {}
43
+ explicit ResultEntry(std::string key, double time, const std::string& blas_sig ) : key_(std::move(key)), time_(time), blas_sig_(blas_sig) {}
44
+ bool operator==(const ResultEntry& other) { return key_ == other.key_; }
45
+ bool operator!=(const ResultEntry& other) { return key_ != other.key_; }
46
+ operator std::string () { return key_; }
47
+ std::string GetKey() const { return key_; }
48
+ double GetTime() const { return time_; }
49
+ friend std::ostream& operator<<(std::ostream& stream, const ResultEntry& entry);
50
+ static ResultEntry Null() { return ResultEntry("Null", 0.0); }
51
+ static ResultEntry Default() { return ResultEntry("Default", 0.0); }
52
+
53
+ private:
54
+ std::string key_;
55
+ double time_;
56
+ std::string blas_sig_;
57
+ };
58
+
59
+ typedef std::unordered_map<std::string, ResultEntry> KernelMap;
60
+ typedef std::unordered_map<std::string, KernelMap> ResultsMap;
61
+ typedef std::unordered_map<std::string, std::unordered_set<std::string>> UntunedMap;
62
+
63
+ struct TORCH_CUDA_CPP_API TuningResults {
64
+ // Validates if these results are compatible with the libraries
65
+ std::unordered_map<std::string, std::string> validators;
66
+
67
+ // Mapping from Callable signature to Callable's tuning result
68
+ ResultsMap results;
69
+ };
70
+
71
+ class TORCH_CUDA_CPP_API TuningResultsManager {
72
+ public:
73
+ TuningResultsManager() = default;
74
+ ~TuningResultsManager() = default;
75
+
76
+ KernelMap Lookup(const std::string& op_signature);
77
+
78
+ ResultEntry Lookup(const std::string& op_signature, const std::string& params_signature);
79
+
80
+ void AddImpl(const std::string& op_signature,
81
+ const std::string& params_signature,
82
+ ResultEntry best,
83
+ KernelMap& kernel_map);
84
+
85
+ void Add(const std::string& op_signature,
86
+ const std::string& params_signature,
87
+ ResultEntry best);
88
+
89
+ void Delete(const std::string& op_signature, const std::string& params_signature);
90
+
91
+ void DisjointMergeImpl(
92
+ const std::string& op_signature,
93
+ const KernelMap& kernel_map,
94
+ /*out*/ ResultsMap& results);
95
+
96
+ void Load(const ResultsMap& results_to_load);
97
+
98
+ ResultsMap Dump();
99
+
100
+ void DisjointMerge(const std::string& op_signature, const KernelMap& kernel_map);
101
+
102
+ size_t GetSize();
103
+
104
+ void RecordUntuned( std::ofstream& untuned_file, const std::string& op_signature,
105
+ const std::string& params_signature, const std::string& blas_signature);
106
+ private:
107
+ std::mutex lock_;
108
+ ResultsMap results_;
109
+ UntunedMap untuned_results_;
110
+
111
+ };
112
+
113
+ class TORCH_CUDA_CPP_API TuningResultsValidator {
114
+ public:
115
+ using GetFunc = std::function<std::string()>;
116
+ using ValidateFunc = std::function<TuningStatus(const std::string&)>;
117
+ using GetValidateFuncs = std::unordered_map<std::string, std::pair<GetFunc, ValidateFunc>>;
118
+
119
+ TuningResultsValidator();
120
+ ~TuningResultsValidator() = default;
121
+
122
+ std::unordered_map<std::string, std::string> GetAllValidators() const;
123
+ TuningStatus ValidateAll(const std::unordered_map<std::string, std::string>& to_validate) const;
124
+ void RegisterValidator(const std::string& key, const GetFunc& gf, const ValidateFunc& vf);
125
+
126
+ protected:
127
+ static std::string GetPyTorchVersion() ;
128
+ TuningStatus ValidatePyTorchVersion(const std::string& value) const;
129
+
130
+ public:
131
+ static constexpr const std::array mandatory_keys{"PT_VERSION"};
132
+
133
+ private:
134
+ GetValidateFuncs validators_;
135
+ };
136
+
137
+ class TORCH_CUDA_CPP_API TuningContext {
138
+ public:
139
+ TuningContext();
140
+ ~TuningContext();
141
+ TuningContext(TuningContext &) = delete;
142
+ TuningContext(TuningContext &&) = delete;
143
+ TuningContext &operator=(TuningContext &) = delete;
144
+ TuningContext &operator=(TuningContext &&) = delete;
145
+
146
+ void EnableTunableOp(bool value);
147
+ bool IsTunableOpEnabled() const;
148
+
149
+ void EnableTuning(bool value);
150
+ bool IsTuningEnabled() const;
151
+
152
+ void EnableRecordUntuned(bool value);
153
+ bool IsRecordUntunedEnabled() const;
154
+ std::ofstream& GetUntunedFile();
155
+
156
+ void EnableNumericsCheck(bool value);
157
+ bool IsNumericsCheckEnabled() const;
158
+
159
+ void SetMaxTuningDurationMs(int max_duration_ms);
160
+ int GetMaxTuningDurationMs() const;
161
+
162
+ void SetMaxTuningIterations(int max_iter);
163
+ int GetMaxTuningIterations() const;
164
+
165
+ void SetMaxWarmupDurationMs(int max_duration_ms);
166
+ int GetMaxWarmupDurationMs() const;
167
+
168
+ void SetMaxWarmupIterations(int max_iter);
169
+ int GetMaxWarmupIterations() const;
170
+
171
+ void EnableICacheFlush(bool value);
172
+ bool IsICacheFlushEnabled() const;
173
+
174
+ void SetRotatingBufferSize(int size);
175
+ int GetRotatingBufferSize() const;
176
+
177
+ TuningResultsManager& GetTuningResultsManager();
178
+
179
+ TuningResultsValidator& GetTuningResultsValidator();
180
+
181
+ TuningResults GetTuningResults();
182
+
183
+ TuningStatus LoadTuningResults(const TuningResults& tr);
184
+
185
+ void SetFilename(const std::string& filename, bool insert_device_ordinal=false);
186
+ std::string GetFilename() const;
187
+
188
+ void WriteFileOnExit(bool value);
189
+
190
+ bool ReadFile(const std::string& filename={});
191
+ bool WriteFile(const std::string& filename={});
192
+
193
+ template<class... Types>
194
+ void Log(int level, Types... args) {
195
+ if (GetLogOkay() && GetLogLevel() >= level) {
196
+ GetLog() << c10::str(args...) << std::endl;
197
+ }
198
+ }
199
+
200
+ private:
201
+ std::string GetLogFilename() const;
202
+ int GetLogLevel() const;
203
+ bool GetLogOkay() const;
204
+ std::ostream& GetLog() const;
205
+
206
+ bool enable_;
207
+ bool tuning_enable_;
208
+ bool record_untuned_enable_;
209
+ bool manager_initialized_;
210
+ bool write_file_on_exit_;
211
+ bool numerics_check_enable_;
212
+ int max_tuning_duration_ms_;
213
+ int max_tuning_iterations_;
214
+ int max_warmup_duration_ms_;
215
+ int max_warmup_iterations_;
216
+ bool icache_flush_;
217
+ int rotating_buffer_size_;
218
+ mutable TuningResultsManager manager_;
219
+ mutable c10::once_flag manager_init_once_;
220
+ TuningResultsValidator validator_;
221
+ std::string filename_;
222
+ std::ofstream untuned_file_;
223
+ size_t results_count_from_input_file_;
224
+ bool is_shutting_down_;
225
+ };
226
+
227
+ TORCH_CUDA_CPP_API TuningContext* getTuningContext();
228
+
229
+ class ITimer {
230
+ public:
231
+ ITimer() = default;
232
+ virtual ~ITimer() = default;
233
+
234
+ virtual void Start() = 0;
235
+ virtual void End() = 0;
236
+
237
+ /// Computes the elapsed time in milliseconds between Start() and End()
238
+ virtual float Duration() = 0;
239
+ };
240
+
241
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/TunableGemm.h ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original TunableOp is from onnxruntime.
2
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
3
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ //
7
+ // Adapting TunableOp into PyTorch
8
+ // Copyright (c) Advanced Micro Devices, Inc.
9
+ //
10
+ #pragma once
11
+
12
+ #include <ATen/cuda/tunable/GemmCommon.h>
13
+ #ifdef USE_ROCM
14
+ #include <ATen/cuda/tunable/GemmHipblaslt.h>
15
+ #include <ATen/cuda/tunable/GemmRocblas.h>
16
+ #endif
17
+ #include <ATen/cuda/tunable/TunableOp.h>
18
+ #include <c10/cuda/CUDACachingAllocator.h>
19
+ #include <c10/util/Float8_e4m3fn.h>
20
+ #include <c10/util/Float8_e4m3fnuz.h>
21
+ #include <c10/util/Float8_e5m2.h>
22
+ #include <c10/util/Float8_e5m2fnuz.h>
23
+ #include <c10/util/Float8_e8m0fnu.h>
24
+ #include <c10/util/StringUtil.h>
25
+ #include <fmt/printf.h>
26
+
27
+ namespace at::cuda::tunable {
28
+
29
+ template <typename T>
30
+ class DefaultGemmOp : public Callable<GemmParams<T>> {
31
+ public:
32
+ TuningStatus Call(const GemmParams<T>* params) override {
33
+ at::cuda::blas::gemm_internal<T>(
34
+ params->transa, params->transb,
35
+ params->m, params->n, params->k,
36
+ params->alpha,
37
+ params->a, params->lda,
38
+ params->b, params->ldb,
39
+ params->beta,
40
+ params->c, params->ldc);
41
+ return OK;
42
+ }
43
+ };
44
+
45
+ static bool _transposeBoolFromChar(char op) {
46
+ return op == 't' || op == 'T';
47
+ }
48
+
49
+ template <typename T>
50
+ class DefaultGemmAndBiasOp : public Callable<GemmAndBiasParams<T>> {
51
+ public:
52
+ TuningStatus Call(const GemmAndBiasParams<T>* params) override {
53
+ at::cuda::blas::gemm_and_bias<T>(
54
+ _transposeBoolFromChar(params->transa),
55
+ _transposeBoolFromChar(params->transb),
56
+ params->m, params->n, params->k,
57
+ params->alpha,
58
+ params->a, params->lda,
59
+ params->b, params->ldb,
60
+ params->bias,
61
+ params->c, params->ldc,
62
+ params->activation);
63
+ return OK;
64
+ }
65
+ };
66
+
67
+ template <typename T>
68
+ class DefaultGemmStridedBatchedOp : public Callable<GemmStridedBatchedParams<T>> {
69
+ public:
70
+ TuningStatus Call(const GemmStridedBatchedParams<T>* params) override {
71
+ at::cuda::blas::bgemm_internal<T>(
72
+ params->transa, params->transb,
73
+ params->m, params->n, params->k,
74
+ params->alpha,
75
+ params->a, params->lda, params->stride_a,
76
+ params->b, params->ldb, params->stride_b,
77
+ params->beta,
78
+ params->c, params->ldc, params->stride_c,
79
+ params->batch);
80
+ return OK;
81
+ }
82
+ };
83
+
84
+ template <typename T>
85
+ class DefaultScaledGemmOp : public Callable<ScaledGemmParams<T>> {
86
+ public:
87
+ TuningStatus Call(const ScaledGemmParams<T>* params) override {
88
+ at::cuda::blas::scaled_gemm(
89
+ params->transa,
90
+ params->transb,
91
+ params->m,
92
+ params->n,
93
+ params->k,
94
+ params->a,
95
+ params->a_scale_ptr,
96
+ params->lda,
97
+ params->a_dtype,
98
+ params->a_scale_dtype,
99
+ params->b,
100
+ params->b_scale_ptr,
101
+ params->ldb,
102
+ params->b_dtype,
103
+ params->b_scale_dtype,
104
+ params->bias_ptr,
105
+ params->bias_dtype,
106
+ params->c,
107
+ params->c_scale_ptr,
108
+ params->ldc,
109
+ params->c_dtype,
110
+ params->use_fast_accum,
111
+ params->use_rowwise);
112
+ return OK;
113
+ }
114
+ };
115
+
116
+ template <typename T>
117
+ inline bool IsZero(T v) {
118
+ return v == 0.0f;
119
+ }
120
+
121
+ template <>
122
+ inline bool IsZero(BFloat16 v) {
123
+ return v.x == 0;
124
+ }
125
+
126
+ template <>
127
+ inline bool IsZero(Half v) {
128
+ return float(v) == 0.0f;
129
+ }
130
+
131
+ template <>
132
+ inline bool IsZero(c10::complex<double> v) {
133
+ return v == 0.0;
134
+ }
135
+
136
+ template <>
137
+ inline bool IsZero(c10::complex<float> v) {
138
+ return v == 0.0f;
139
+ }
140
+
141
+ template <typename T>
142
+ inline const char* TypeName(T v) {
143
+ return "unknown";
144
+ }
145
+
146
+ template <>
147
+ inline const char* TypeName(float v) {
148
+ return "float";
149
+ }
150
+
151
+ template <>
152
+ inline const char* TypeName(double v) {
153
+ return "double";
154
+ }
155
+
156
+ template <>
157
+ inline const char* TypeName(BFloat16 v) {
158
+ return "BFloat16";
159
+ }
160
+
161
+ template <>
162
+ inline const char* TypeName(Half v) {
163
+ return "Half";
164
+ }
165
+
166
+ template <>
167
+ inline const char* TypeName(Float8_e4m3fn v) {
168
+ return "Float8_e4m3fn";
169
+ }
170
+
171
+ template <>
172
+ inline const char* TypeName(Float8_e5m2 v) {
173
+ return "Float8_e5m2";
174
+ }
175
+
176
+ template <>
177
+ inline const char* TypeName(Float8_e4m3fnuz v) {
178
+ return "Float8_e4m3fnuz";
179
+ }
180
+
181
+ template <>
182
+ inline const char* TypeName(Float8_e5m2fnuz v) {
183
+ return "Float8_e5m2fnuz";
184
+ }
185
+
186
+ template <>
187
+ inline const char* TypeName(Float8_e8m0fnu v) {
188
+ return "Float8_e8m0fnu";
189
+ }
190
+
191
+ template <>
192
+ inline const char* TypeName(c10::complex<double> v) {
193
+ return "c10::complex<double>";
194
+ }
195
+
196
+ template <>
197
+ inline const char* TypeName(c10::complex<float> v) {
198
+ return "c10::complex<float>";
199
+ }
200
+
201
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
202
+ class GemmTunableOp : public TunableOp<GemmParams<T>> {
203
+ public:
204
+ GemmTunableOp() {
205
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmOp<T>>());
206
+
207
+ #ifdef USE_ROCM
208
+ static const auto env_rocblas = c10::utils::check_env("PYTORCH_TUNABLEOP_ROCBLAS_ENABLED");
209
+ if (!env_rocblas.has_value() || env_rocblas.value()) {
210
+ for (auto&& [name, op] : GetRocBlasGemmTypeStringAndOps<T>()) {
211
+ this->RegisterOp(std::move(name), std::move(op));
212
+ }
213
+ }
214
+
215
+ static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED");
216
+ if (!env_hipblaslt.has_value() || env_hipblaslt.value()) {
217
+ // disallow tuning of hipblaslt with c10::complex
218
+ if constexpr (
219
+ !std::is_same_v<T, c10::complex<float>> &&
220
+ !std::is_same_v<T, c10::complex<double>>) {
221
+ for (auto&& [name, op] : GetHipBlasLtGemmTypeStringAndOps<T, ALayout, BLayout>()) {
222
+ this->RegisterOp(std::move(name), std::move(op));
223
+ }
224
+ }
225
+ }
226
+ #endif
227
+
228
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmOp<T>>());
229
+ }
230
+
231
+ std::string Signature() override {
232
+ return fmt::sprintf("GemmTunableOp_%s_%c%c", TypeName<T>(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout));
233
+ }
234
+ };
235
+
236
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
237
+ class GemmAndBiasTunableOp : public TunableOp<GemmAndBiasParams<T>> {
238
+ public:
239
+ GemmAndBiasTunableOp() {
240
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmAndBiasOp<T>>());
241
+
242
+ #ifdef USE_ROCM
243
+ static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED");
244
+ if (!env_hipblaslt.has_value() || env_hipblaslt.value()) {
245
+ // disallow tuning of hipblaslt with c10::complex
246
+ if constexpr (
247
+ !std::is_same_v<T, c10::complex<float>> &&
248
+ !std::is_same_v<T, c10::complex<double>>) {
249
+ for (auto&& [name, op] : GetHipBlasLtGemmAndBiasTypeStringAndOps<T, ALayout, BLayout>()) {
250
+ this->RegisterOp(std::move(name), std::move(op));
251
+ }
252
+ }
253
+ }
254
+ #endif
255
+
256
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmAndBiasOp<T>>());
257
+ }
258
+
259
+ std::string Signature() override {
260
+ return fmt::sprintf("GemmAndBiasTunableOp_%s_%c%c", TypeName<T>(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout));
261
+ }
262
+ };
263
+
264
+ template <typename T, BlasOp ALayout, BlasOp BLayout>
265
+ class GemmStridedBatchedTunableOp : public TunableOp<GemmStridedBatchedParams<T>> {
266
+ public:
267
+ GemmStridedBatchedTunableOp() {
268
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmStridedBatchedOp<T>>());
269
+
270
+ #ifdef USE_ROCM
271
+ static const auto env_rocblas = c10::utils::check_env("PYTORCH_TUNABLEOP_ROCBLAS_ENABLED");
272
+ if (!env_rocblas.has_value() || env_rocblas.value()) {
273
+ for (auto&& [name, op] : GetRocBlasGemmStridedBatchedTypeStringAndOps<T>()) {
274
+ this->RegisterOp(std::move(name), std::move(op));
275
+ }
276
+ }
277
+
278
+ static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED");
279
+ if (!env_hipblaslt.has_value() || env_hipblaslt.value()) {
280
+ // disallow tuning of hipblaslt with c10::complex
281
+ if constexpr (
282
+ !std::is_same_v<T, c10::complex<float>> &&
283
+ !std::is_same_v<T, c10::complex<double>>) {
284
+ for (auto&& [name, op] : GetHipBlasLtGemmStridedBatchedTypeStringAndOps<T, ALayout, BLayout>()) {
285
+ this->RegisterOp(std::move(name), std::move(op));
286
+ }
287
+ }
288
+ }
289
+ #endif
290
+
291
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultGemmStridedBatchedOp<T>>());
292
+ }
293
+
294
+ std::string Signature() override {
295
+ return fmt::sprintf("GemmStridedBatchedTunableOp_%s_%c%c", TypeName<T>(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout));
296
+ }
297
+ };
298
+
299
+ template <typename AT, typename BT, typename CT, BlasOp ALayout, BlasOp BLayout>
300
+ class ScaledGemmTunableOp : public TunableOp<ScaledGemmParams<CT>> {
301
+ public:
302
+ ScaledGemmTunableOp() {
303
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultScaledGemmOp<CT>>());
304
+
305
+ #ifdef USE_ROCM
306
+ for (auto&& [name, op] : GetHipBlasLtScaledGemmTypeStringAndOps<AT, BT, CT, ALayout, BLayout>()) {
307
+ this->RegisterOp(std::move(name), std::move(op));
308
+ }
309
+ #endif
310
+
311
+ this->RegisterOp(std::string("Default"), std::make_unique<DefaultScaledGemmOp<CT>>());
312
+ }
313
+
314
+ std::string Signature() override {
315
+ return fmt::sprintf("ScaledGemmTunableOp_%s_%s_%s_%c%c",
316
+ TypeName<AT>(AT{}),
317
+ TypeName<BT>(BT{}),
318
+ TypeName<CT>(CT{}),
319
+ BlasOpToString(ALayout), BlasOpToString(BLayout));
320
+ }
321
+ };
322
+
323
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/tunable/TunableOp.h ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original TunableOp is from onnxruntime.
2
+ // https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h
3
+ // https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ //
7
+ // Adapting TunableOp into PyTorch
8
+ // Copyright (c) Advanced Micro Devices, Inc.
9
+ //
10
+ #pragma once
11
+
12
+ #include <ATen/cuda/tunable/Tunable.h>
13
+ #include <ATen/cuda/tunable/StreamTimer.h>
14
+ #include <ATen/cuda/Sleep.h>
15
+ #include <c10/cuda/CUDACachingAllocator.h>
16
+
17
+ #ifndef _WIN32
18
+ #include <cxxabi.h>
19
+ #endif
20
+
21
+ #include <string>
22
+ #include <unordered_map>
23
+ #include <vector>
24
+ #include <deque>
25
+
26
+ namespace at::cuda::tunable {
27
+
28
+ template <typename ParamsT>
29
+ class Callable {
30
+ public:
31
+ virtual ~Callable() = default;
32
+ virtual TuningStatus Call(const ParamsT*) {
33
+ return FAIL;
34
+ }
35
+ virtual TuningStatus IsSupported(const ParamsT* params) {
36
+ return Call(params);
37
+ }
38
+ };
39
+
40
+ namespace {
41
+
42
+ /** http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance */
43
+
44
+ class Stats {
45
+ public:
46
+ Stats() {
47
+ _n = 0UL;
48
+ _mean = 0.0;
49
+ _M2 = 0.0;
50
+ _sum = 0.0;
51
+ _min = 0.0;
52
+ _max = 0.0;
53
+ }
54
+
55
+ void sample_value(const double x) {
56
+ double delta = 0;
57
+ _sum = _sum + x;
58
+ if (0UL == _n) {
59
+ _min = x;
60
+ _max = x;
61
+ }
62
+ else {
63
+ _min = _min < x ? _min : x;
64
+ _max = _max > x ? _max : x;
65
+ }
66
+ _n = _n + 1UL;
67
+ delta = x - _mean;
68
+ _mean = _mean + delta/_n;
69
+ _M2 = _M2 + delta * (x - _mean);
70
+ }
71
+
72
+ double variance() const {
73
+ return _M2/(_n-1);
74
+ }
75
+
76
+ double stddev() const {
77
+ return std::sqrt(variance());
78
+ }
79
+
80
+ unsigned long _n;
81
+ double _mean;
82
+ double _M2;
83
+ double _sum;
84
+ double _min;
85
+ double _max;
86
+ };
87
+
88
+ class FixedSizeStack {
89
+ private:
90
+ std::deque<std::string> stack;
91
+ const size_t max_size;
92
+
93
+ public:
94
+ FixedSizeStack(size_t size) : max_size(size) {}
95
+
96
+ void push(const std::string& value) {
97
+ if (stack.size() >= max_size) {
98
+ stack.pop_front(); // Remove the oldest entry
99
+ }
100
+ stack.push_back(value); // Add new entry
101
+ }
102
+
103
+ auto rbegin() { return stack.rbegin(); }
104
+ auto rend() { return stack.rend(); }
105
+ };
106
+
107
+ } // anonymous namespace
108
+
109
+ template <typename ParamsT>
110
+ class TunableOp {
111
+ public:
112
+ virtual ~TunableOp() = default;
113
+
114
+ TuningStatus operator()(const ParamsT* params) {
115
+ ResultEntry result = ResultEntry::Null();
116
+ TuningContext* ctx = getTuningContext();
117
+ if (ctx->IsTunableOpEnabled()) {
118
+ auto& mgr = ctx->GetTuningResultsManager();
119
+ auto op_sig = Signature();
120
+ auto params_sig = params->Signature();
121
+ auto blas_sig = params->BLASSignature();
122
+ result = mgr.Lookup(op_sig, params_sig);
123
+ // If there is not previous tuning result been found, we do the tuning iff tuning is enabled
124
+ if (result == ResultEntry::Null()) {
125
+ if (ctx->IsTuningEnabled()) {
126
+ result = FindFastest(params);
127
+ mgr.Add(op_sig, params_sig, result);
128
+ }
129
+ else if (ctx->IsRecordUntunedEnabled()) {
130
+ // or record the gemm into file
131
+ mgr.RecordUntuned(ctx->GetUntunedFile(), op_sig, params_sig, blas_sig);
132
+ }
133
+ }
134
+ }
135
+ else {
136
+ result = ResultEntry::Default();
137
+ }
138
+ if (result == ResultEntry::Null()) {
139
+ TUNABLE_LOG2("no result, using default");
140
+ result = ResultEntry::Default();
141
+ }
142
+ auto iter = ops_.find(result);
143
+ TORCH_CHECK(iter != ops_.end());
144
+ return iter->second->Call(params);
145
+ }
146
+
147
+ virtual std::string Signature() {
148
+ // According to C++17 standard https://wg21.link/n4659 section 15.7.4
149
+ // > if the operand of typeid refers to the
150
+ // > object under construction or destruction, typeid yields the std::type_info object representing the constructor
151
+ // > or destructor’s class.
152
+ // So delay the op signature generation.
153
+ c10::call_once(signature_init_once_, [this]() { signature_ = CreateSignature(); });
154
+ return signature_;
155
+ }
156
+
157
+ protected:
158
+ void RegisterOp(const std::string& name, std::unique_ptr<Callable<ParamsT>> op) {
159
+ this->op_names_.emplace_back(name);
160
+ this->ops_.emplace(name, std::move(op));
161
+ }
162
+
163
+ private:
164
+ static void WarmUp(Callable<ParamsT> *op, const std::vector<ParamsT*> &param, size_t num_iter, size_t &offset) {
165
+ TuningContext* ctx = getTuningContext();
166
+ bool do_flush = ctx->IsICacheFlushEnabled();
167
+ for (size_t i = 0; i < num_iter; i++) {
168
+ if (do_flush) {
169
+ at::cuda::flush_icache();
170
+ }
171
+ TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK);
172
+ }
173
+ }
174
+
175
+ static double ProfileSimple(Callable<ParamsT> *op, const std::vector<ParamsT*> &param, size_t num_iter, size_t &offset) {
176
+ TuningContext* ctx = getTuningContext();
177
+ bool do_flush = ctx->IsICacheFlushEnabled();
178
+ StreamTimerNoSync timer{};
179
+
180
+ // Small Mandatory Warmup
181
+ // Reduces outliers
182
+ for (size_t i = 0; i < 2; i++) {
183
+ TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK);
184
+ }
185
+
186
+ timer.Start();
187
+ for (size_t i = 0; i < num_iter; i++) {
188
+ if (do_flush) {
189
+ at::cuda::flush_icache();
190
+ }
191
+ TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK);
192
+ }
193
+ timer.End();
194
+ return timer.Duration() / num_iter;
195
+ }
196
+
197
+ static Stats ProfileStats(Callable<ParamsT> *op, const std::vector<ParamsT*> &param, size_t num_iter, size_t &offset) {
198
+ TuningContext* ctx = getTuningContext();
199
+ bool do_flush = ctx->IsICacheFlushEnabled();
200
+ std::vector<StreamTimerNoSync> timer(num_iter);
201
+
202
+ // Small Mandatory Warmup
203
+ // Reduces outliers
204
+ for (size_t i = 0; i < 2; i++) {
205
+ TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK);
206
+ }
207
+
208
+ for (size_t i = 0; i < num_iter; i++) {
209
+ timer[i].Start();
210
+ TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK);
211
+ timer[i].End();
212
+ if (do_flush) {
213
+ at::cuda::flush_icache();
214
+ }
215
+ }
216
+ Stats s;
217
+ for (size_t i = 0; i < num_iter; i++) {
218
+ s.sample_value(timer[i].Duration());
219
+ }
220
+ return s;
221
+ }
222
+
223
+ protected:
224
+ virtual ResultEntry FindFastest(const ParamsT* params) {
225
+ TuningContext* ctx = getTuningContext();
226
+ auto op_sig = Signature();
227
+ auto params_sig = params->Signature();
228
+ auto blas_sig = params->BLASSignature();
229
+ TUNABLE_LOG2("finding fastest for ", op_sig, '(', params_sig, ')', " out of ", op_names_.size(), " candidates");
230
+ auto min_duration_ms = std::numeric_limits<double>::infinity();
231
+ std::string id_name = "Default";
232
+ ParamsT* reference_params = nullptr;
233
+ auto top_solns = FixedSizeStack(5);
234
+
235
+ // numeric check option is controlled by non-static env var, so check it once per tuned operator
236
+ bool do_numerics_check = ctx->IsNumericsCheckEnabled();
237
+
238
+ // calcaulte a reference answer for numerical check
239
+ if (do_numerics_check) {
240
+ reference_params = params->DeepCopy(false);
241
+ TORCH_CHECK(ops_[ResultEntry::Default()]->Call(reference_params) == OK);
242
+ }
243
+
244
+ // need copies of params to reuse
245
+ // make as many copies as will fill the requested rotating buffer size, if requested
246
+ // rotating_size guaranteed to be >= 0 even though GetRotatingBufferSize() returns int
247
+ size_t rotating_size = ctx->GetRotatingBufferSize();
248
+ bool use_buffer_rotation = (rotating_size > 0);
249
+ size_t param_size = params->GetSize(use_buffer_rotation);
250
+ size_t param_count = (rotating_size / param_size) + 1;
251
+ constexpr size_t MB = 1024ull*1024;
252
+ if (use_buffer_rotation) {
253
+ TUNABLE_LOG2("Rotating buffer ", rotating_size/MB, " MiB. ",
254
+ "Needed Size: ", param_size/MB, " MiB. ",
255
+ "Needed number of param copies: ", param_count);
256
+ }
257
+ TORCH_CHECK(param_count > 0);
258
+
259
+ std::vector<ParamsT*> reusable_params(param_count);
260
+ for (size_t i = 0; i < param_count; i++) {
261
+ reusable_params[i] = params->DeepCopy(use_buffer_rotation);
262
+ }
263
+
264
+ // for rotating buffer
265
+ size_t offset = 0;
266
+
267
+ for (size_t i = 0; i < op_names_.size(); i++) {
268
+ auto* candidate = ops_[op_names_[i]].get(); // borrow pointer
269
+
270
+ if (do_numerics_check) {
271
+ ParamsT* numerical_params = params->DeepCopy(false);
272
+ auto status = candidate->Call(numerical_params);
273
+ if (status != OK) {
274
+ numerical_params->Delete();
275
+ TUNABLE_LOG3("├──unsupported id=", i, ", ", op_sig, '(', params_sig, ") ", op_names_[i]);
276
+ continue;
277
+ }
278
+ status = reference_params->NumericalCheck(numerical_params);
279
+ numerical_params->Delete();
280
+ if (status != OK) {
281
+ TUNABLE_LOG3("├──numerics check failed for id=", i, ", ", op_sig, '(', params_sig, ") ", op_names_[i]);
282
+ continue;
283
+ }
284
+ }
285
+ else {
286
+ auto status = candidate->Call(reusable_params[0]);
287
+ if (status != OK) {
288
+ TUNABLE_LOG3("├──unsupported id=", i, ", ", op_sig, '(', params_sig, ") ", op_names_[i]);
289
+ continue;
290
+ }
291
+ }
292
+
293
+ // collect a small profile
294
+ int approx_num_iter = 3;
295
+ auto s = ProfileStats(candidate, reusable_params, approx_num_iter, offset);
296
+ double approx_duration = s._mean;
297
+ // bail if too slow
298
+ if (approx_duration > 1.5 * min_duration_ms) {
299
+ TUNABLE_LOG3("├──skip slow instance id=", i, ", ", op_sig, '(', params_sig, ") ", op_names_[i]);
300
+ continue;
301
+ }
302
+
303
+ // 2nd phase skip, more aggressive
304
+ approx_num_iter = 10;
305
+ s = ProfileStats(candidate, reusable_params, approx_num_iter, offset);
306
+ approx_duration = s._mean;
307
+ // bail if too slow
308
+ if (approx_duration > 1.15 * min_duration_ms) {
309
+ TUNABLE_LOG3("├──2nd skip slow instance id=", i, ", ", op_sig, '(', params_sig, ") ", op_names_[i]);
310
+ continue;
311
+ }
312
+
313
+ // for warmup does user set max duration, max iters, or both?
314
+ // warmup is skipped by default, i.e. warmup_iter = 0
315
+ // warmup will be set to the non-zero value of max_warmup_duration
316
+ // or max_warmup_iter
317
+ // if both are non-zero, we take the smaller of the two.
318
+ double max_warmup_duration = ctx->GetMaxWarmupDurationMs();
319
+ int max_warmup_iter = ctx->GetMaxWarmupIterations();
320
+ int warmup_iter = 0; // default
321
+ if (max_warmup_duration > 0) {
322
+ int duration_iters = max_warmup_duration / approx_duration;
323
+ if (max_warmup_iter > 0) {
324
+ warmup_iter = std::min(max_warmup_iter, duration_iters);
325
+ }
326
+ else {
327
+ warmup_iter = duration_iters;
328
+ }
329
+ }
330
+ else if (max_warmup_iter > 0) {
331
+ warmup_iter = max_warmup_iter;
332
+ }
333
+
334
+ // for tuning does user set max duration, max iters, or both?
335
+ double max_tuning_duration = ctx->GetMaxTuningDurationMs();
336
+ int max_tuning_iter = ctx->GetMaxTuningIterations();
337
+ int tuning_iter = 100; // default
338
+ if (max_tuning_duration > 0) {
339
+ int duration_iters = max_tuning_duration / approx_duration;
340
+ if (max_tuning_iter > 0) {
341
+ tuning_iter = std::min(max_tuning_iter, duration_iters);
342
+ }
343
+ else {
344
+ tuning_iter = duration_iters;
345
+ }
346
+ }
347
+ else if (max_tuning_iter > 0) {
348
+ tuning_iter = max_tuning_iter;
349
+ }
350
+ // tuning must run at least 1 iteration
351
+ tuning_iter = std::max(1, tuning_iter);
352
+
353
+ // do the full warmup followed by tuning
354
+ double warmup_ms = warmup_iter * approx_duration;
355
+ double tuning_ms = tuning_iter * approx_duration;
356
+ TUNABLE_LOG3("├──tuning using "
357
+ "warmup iters ", warmup_iter, " [", warmup_ms, " ms] "
358
+ "and tuning iters ", tuning_iter, " [", tuning_ms, " ms] ",
359
+ "instance id=", i, ", ", op_sig, "(", params_sig, ") ", op_names_[i]);
360
+ TUNABLE_LOG3("├──offset at ", offset);
361
+ WarmUp(candidate, reusable_params, warmup_iter, offset);
362
+ s = ProfileStats(candidate, reusable_params, tuning_iter, offset);
363
+ auto s_stddev = s.stddev();
364
+ // Assume normal distribution.
365
+ // Solution with smallest mean + 2*sigma will be a better solution?
366
+ // if ((s._mean + 2*s_stddev) < (min_duration_ms + 2*min_stddev_ms)) {
367
+ if (s._mean < min_duration_ms) {
368
+ TUNABLE_LOG3("├──found better instance id=", i, ". " , s._mean, "ms. ", op_names_[i],
369
+ " min ", s._min,
370
+ " max ", s._max,
371
+ " mean ", s._mean,
372
+ " std ", s_stddev);
373
+ min_duration_ms = s._mean;
374
+ id_name = op_names_[i];
375
+ std::string current_soln = std::to_string(s._mean) + " " + op_names_[i];
376
+ top_solns.push(current_soln);
377
+ }
378
+ else {
379
+ TUNABLE_LOG3("├──found slower instance id=", i, ". " , s._mean, "ms. ", op_names_[i],
380
+ " min ", s._min,
381
+ " max ", s._max,
382
+ " mean ", s._mean,
383
+ " std ", s_stddev);
384
+ }
385
+ }
386
+
387
+ for (size_t i = 0; i < reusable_params.size(); i++) {
388
+ reusable_params[i]->Delete();
389
+ }
390
+ if (reference_params) {
391
+ reference_params->Delete();
392
+ }
393
+
394
+ TUNABLE_LOG2("└──found fastest for ", op_sig, '(', params_sig, ") ", id_name);
395
+ TUNABLE_LOG2("└──top five solutions for ", op_sig, '(', params_sig, ") ");
396
+ for (auto it = top_solns.rbegin(); it != top_solns.rend(); ++it) {
397
+ TUNABLE_LOG2(" ", *it);
398
+ }
399
+ return ResultEntry(id_name, min_duration_ms, blas_sig);
400
+ }
401
+
402
+ private:
403
+ std::string CreateSignature() {
404
+ #ifndef _WIN32
405
+ const auto* name = typeid(*this).name();
406
+ // NOLINTNEXTLINE(*array*)
407
+ char buf[256];
408
+ size_t buf_len = 256;
409
+ abi::__cxa_demangle(name, buf, &buf_len, nullptr);
410
+ buf[255] = '\0';
411
+ return buf;
412
+ #else
413
+ return typeid(*this).name();
414
+ #endif
415
+ }
416
+
417
+ mutable c10::once_flag signature_init_once_;
418
+ std::string signature_;
419
+
420
+ std::unordered_map<std::string, std::unique_ptr<Callable<ParamsT>>> ops_;
421
+ std::vector<std::string> op_names_;
422
+ };
423
+
424
+ struct OpParams {
425
+ virtual ~OpParams() = default;
426
+ virtual std::string Signature() const = 0;
427
+ virtual std::string BLASSignature() const = 0;
428
+ };
429
+
430
+ } // namespace at::cuda::tunable
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <c10/core/DeviceType.h>
5
+
6
+ // Use of c10::hip namespace here makes hipification easier, because
7
+ // I don't have to also fix namespaces. Sorry!
8
+ namespace c10::hip {
9
+
10
+ // Takes a valid HIPAllocator (of any sort) and turns it into
11
+ // an allocator pretending to be a CUDA allocator. See
12
+ // Note [Masquerading as CUDA]
13
+ class HIPAllocatorMasqueradingAsCUDA final : public Allocator {
14
+ Allocator* allocator_;
15
+ public:
16
+ explicit HIPAllocatorMasqueradingAsCUDA(Allocator* allocator)
17
+ : allocator_(allocator) {}
18
+ DataPtr allocate(size_t size) override {
19
+ DataPtr r = allocator_->allocate(size);
20
+ r.unsafe_set_device(Device(c10::DeviceType::CUDA, r.device().index()));
21
+ return r;
22
+ }
23
+ DeleterFnPtr raw_deleter() const override {
24
+ return allocator_->raw_deleter();
25
+ }
26
+ void copy_data(void* dest, const void* src, std::size_t count) const final {
27
+ allocator_->copy_data(dest, src, count);
28
+ }
29
+ };
30
+
31
+ } // namespace c10::hip
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/hip/HIPCachingAllocator.h>
4
+ #include <ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h>
5
+ #include <ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h>
6
+
7
+ namespace c10 {
8
+ // forward declaration
9
+ class DataPtr;
10
+ namespace hip {
11
+ namespace HIPCachingAllocatorMasqueradingAsCUDA {
12
+
13
+ C10_HIP_API Allocator* get();
14
+ C10_HIP_API void recordStreamMasqueradingAsCUDA(const DataPtr& ptr, HIPStreamMasqueradingAsCUDA stream);
15
+
16
+ } // namespace HIPCachingAllocatorMasqueradingAsCUDA
17
+ } // namespace hip
18
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/hip/HIPConfig.h>
4
+
5
+ // The includes of HIPGuard.h
6
+ #include <c10/hip/impl/HIPGuardImpl.h>
7
+ #include <c10/hip/HIPMacros.h>
8
+ #include <c10/core/DeviceType.h>
9
+ #include <c10/core/impl/InlineDeviceGuard.h>
10
+ #include <c10/core/impl/InlineStreamGuard.h>
11
+ #include <c10/util/Exception.h>
12
+
13
+ #include <c10/hip/impl/HIPGuardImpl.h>
14
+
15
+ #include <ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h>
16
+ #include <ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h>
17
+
18
+ // Use of c10::hip namespace here makes hipification easier, because
19
+ // I don't have to also fix namespaces. Sorry!
20
+ namespace c10 { namespace hip {
21
+
22
+ // Note [Masquerading as CUDA]
23
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
24
+ // c10_hip is very easy to understand: it is HIPified from c10_cuda,
25
+ // and anywhere you said CUDA, the source code now says HIP. HIPified
26
+ // PyTorch is much harder to understand: it is HIPified from regular
27
+ // PyTorch, yes, but NO source-to-source translation from CUDA to
28
+ // HIP occurs; instead, anywhere we see "CUDA", it actually means "HIP".
29
+ // For example, when you use HIPified PyTorch, you say x.cuda() to
30
+ // move a tensor onto ROCm device. We call this situation "HIP
31
+ // masquerading as CUDA".
32
+ //
33
+ // This leads to a very awkward situation when we want to call c10_hip
34
+ // code from PyTorch, since c10_hip is expecting things to be called
35
+ // HIP, but PyTorch is calling them CUDA (masquerading as HIP). To
36
+ // fix this impedance mismatch, we have MasqueradingAsCUDA variants
37
+ // for all c10_hip classes. These translate between the "HIP" and "CUDA
38
+ // masquerading as HIP" worlds. For example,
39
+ // HIPGuardImplMasqueradingAsCUDA (this file) provides something like a
40
+ // HIPGuardImpl, but it reports its DeviceType as CUDA (e.g., type()
41
+ // returns CUDA, getDevice() reports the current HIP device as a CUDA
42
+ // device.)
43
+ //
44
+ // We should be able to delete all of these classes entirely once
45
+ // we switch PyTorch to calling a HIP a HIP.
46
+ //
47
+ // When you add a new MasqueradingAsCUDA class/function, you need to
48
+ // also update the rewrite rules in torch/utils/hipify/cuda_to_hip_mappings.py
49
+ //
50
+ //
51
+ //
52
+ // By the way, note that the cpp file associated with this also
53
+ // *overwrites* the entry in the DeviceGuardImpl registry for CUDA with
54
+ // this HIP implementation.
55
+
56
+ struct HIPGuardImplMasqueradingAsCUDA final : public c10::impl::DeviceGuardImplInterface {
57
+ static constexpr c10::DeviceType static_type = c10::DeviceType::CUDA;
58
+ HIPGuardImplMasqueradingAsCUDA() {}
59
+ HIPGuardImplMasqueradingAsCUDA(c10::DeviceType t) {
60
+ TORCH_INTERNAL_ASSERT(t == c10::DeviceType::CUDA);
61
+ }
62
+ c10::DeviceType type() const override {
63
+ return c10::DeviceType::CUDA;
64
+ }
65
+ Device exchangeDevice(Device d) const override {
66
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
67
+ Device old_device = getDevice();
68
+ if (old_device.index() != d.index()) {
69
+ C10_HIP_CHECK(hipSetDevice(d.index()));
70
+ }
71
+ return old_device;
72
+ }
73
+ Device getDevice() const override {
74
+ int device;
75
+ C10_HIP_CHECK(hipGetDevice(&device));
76
+ return Device(c10::DeviceType::CUDA, device);
77
+ }
78
+ void setDevice(Device d) const override {
79
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
80
+ C10_HIP_CHECK(hipSetDevice(d.index()));
81
+ }
82
+ void uncheckedSetDevice(Device d) const noexcept override {
83
+ C10_HIP_CHECK_WARN(hipSetDevice(d.index()));
84
+ }
85
+ Stream getStream(Device d) const override {
86
+ return getCurrentHIPStreamMasqueradingAsCUDA(d.index()).unwrap();
87
+ }
88
+ Stream getDefaultStream(Device d) const override {
89
+ return getDefaultHIPStreamMasqueradingAsCUDA(d.index());
90
+ }
91
+ Stream getNewStream(Device d, int priority = 0) const override {
92
+ return getStreamFromPoolMasqueradingAsCUDA(priority, d.index());
93
+ }
94
+ Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false) const override {
95
+ return getStreamFromPoolMasqueradingAsCUDA(isHighPriority, d.index());
96
+ }
97
+ Stream exchangeStream(Stream s) const override {
98
+ HIPStreamMasqueradingAsCUDA cs(s);
99
+ auto old_stream = getCurrentHIPStreamMasqueradingAsCUDA(s.device().index());
100
+ setCurrentHIPStreamMasqueradingAsCUDA(cs);
101
+ return old_stream.unwrap();
102
+ }
103
+ DeviceIndex deviceCount() const noexcept override {
104
+ int deviceCnt;
105
+ hipError_t _err;
106
+ _err = hipGetDeviceCount(&deviceCnt);
107
+ if(_err != hipErrorNoDevice && _err != hipSuccess)
108
+ C10_HIP_CHECK(_err);
109
+ return deviceCnt;
110
+ }
111
+
112
+ // Event-related functions
113
+ // Note: hipEventCreateWithFlags should be called on the same device as
114
+ // the recording stream's device.
115
+ void createEvent(
116
+ hipEvent_t* hip_event,
117
+ const EventFlag flag) const {
118
+ // Maps PyTorch's Event::Flag to HIP flag
119
+ auto hip_flag = hipEventDefault;
120
+ switch (flag) {
121
+ case EventFlag::PYTORCH_DEFAULT:
122
+ hip_flag = hipEventDisableTiming;
123
+ break;
124
+ case EventFlag::BACKEND_DEFAULT:
125
+ hip_flag = hipEventDefault;
126
+ break;
127
+ default:
128
+ TORCH_CHECK(false, "HIP event received unknown flag");
129
+ }
130
+
131
+ C10_HIP_CHECK(hipEventCreateWithFlags(hip_event, hip_flag));
132
+ }
133
+
134
+ void destroyEvent(
135
+ void* event,
136
+ const DeviceIndex device_index) const noexcept override {
137
+ if (!event) return;
138
+ auto hip_event = static_cast<hipEvent_t>(event);
139
+ int orig_device;
140
+ C10_HIP_CHECK_WARN(hipGetDevice(&orig_device));
141
+ C10_HIP_CHECK_WARN(hipSetDevice(device_index));
142
+ C10_HIP_CHECK_WARN(hipEventDestroy(hip_event));
143
+ C10_HIP_CHECK_WARN(hipSetDevice(orig_device));
144
+ }
145
+
146
+ void record(void** event,
147
+ const Stream& stream,
148
+ const DeviceIndex device_index,
149
+ const EventFlag flag) const override {
150
+ TORCH_CHECK(device_index == -1 || device_index == stream.device_index(),
151
+ "Event device index ",
152
+ device_index,
153
+ " does not match recording stream's device index ",
154
+ stream.device_index(),
155
+ ".");
156
+
157
+ hipEvent_t hip_event = static_cast<hipEvent_t>(*event);
158
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
159
+
160
+ // Moves to stream's device to record
161
+ const auto orig_device = getDevice();
162
+ setDevice(stream.device());
163
+
164
+ // Creates the event (lazily)
165
+ if (!hip_event) createEvent(&hip_event, flag);
166
+ C10_HIP_CHECK(hipEventRecord(hip_event, hip_stream));
167
+ // Makes the void* point to the (possibly just allocated) HIP event
168
+ *event = hip_event;
169
+
170
+ // Resets device
171
+ setDevice(orig_device);
172
+ }
173
+
174
+ void block(
175
+ void* event,
176
+ const Stream& stream) const override {
177
+ if (!event) return;
178
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
179
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
180
+ const auto orig_device = getDevice();
181
+ setDevice(stream.device());
182
+ C10_HIP_CHECK(hipStreamWaitEvent(
183
+ hip_stream,
184
+ hip_event,
185
+ /*flags (must be zero)=*/ 0));
186
+ setDevice(orig_device);
187
+ }
188
+
189
+ bool queryEvent(void* event) const override {
190
+ if (!event) return true;
191
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
192
+ const hipError_t err = hipEventQuery(hip_event);
193
+ if (err != hipErrorNotReady) C10_HIP_CHECK(err);
194
+ else {
195
+ // ignore and clear the error if not ready
196
+ (void)hipGetLastError();
197
+ }
198
+ return (err == hipSuccess);
199
+ }
200
+
201
+ // Stream-related functions
202
+ bool queryStream(const Stream& stream) const override {
203
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
204
+ return hip_stream.query();
205
+ }
206
+
207
+ void synchronizeStream(const Stream& stream) const override {
208
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
209
+ hip_stream.synchronize();
210
+ }
211
+
212
+ void synchronizeEvent(void* event) const override {
213
+ if (!event)
214
+ return;
215
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
216
+ C10_HIP_CHECK(hipEventSynchronize(hip_event));
217
+ }
218
+
219
+ // Note: synchronizeDevice can be safely called from any device
220
+ void synchronizeDevice(const c10::DeviceIndex device_index) const override {
221
+ int orig_device{-1};
222
+ C10_HIP_CHECK(hipGetDevice(&orig_device));
223
+ C10_HIP_CHECK(hipSetDevice(device_index));
224
+ C10_HIP_CHECK(hipDeviceSynchronize());
225
+ C10_HIP_CHECK(hipSetDevice(orig_device));
226
+ }
227
+
228
+ void recordDataPtrOnStream(
229
+ const c10::DataPtr& data_ptr,
230
+ const Stream& stream) const override {
231
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
232
+ HIPCachingAllocatorMasqueradingAsCUDA::recordStreamMasqueradingAsCUDA(data_ptr, hip_stream);
233
+ }
234
+
235
+ double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
236
+ const override {
237
+ TORCH_CHECK(
238
+ event1 && event2,
239
+ "Both events must be recorded before calculating elapsed time.");
240
+ int orig_device;
241
+ C10_HIP_CHECK(hipGetDevice(&orig_device));
242
+ C10_HIP_CHECK(hipSetDevice(device_index));
243
+ hipEvent_t hip_event1 = static_cast<hipEvent_t>(event1);
244
+ hipEvent_t hip_event2 = static_cast<hipEvent_t>(event2);
245
+ float time_ms = 0;
246
+ // raise hipErrorNotReady if either event is recorded but not yet completed
247
+ C10_HIP_CHECK(hipEventElapsedTime(&time_ms, hip_event1, hip_event2));
248
+ C10_HIP_CHECK(hipSetDevice(orig_device));
249
+ return static_cast<double>(time_ms);
250
+ }
251
+ };
252
+
253
+ // All of the guards which have HIPGuardImpl burned in need to also have
254
+ // variants using HIPGuardImplMasqueradingAsCUDA.
255
+
256
+ /// This code is all a direct copy from c10/cuda/HIPGuardMasqueradingAsCUDA.h, but with
257
+ /// the correct InlineDeviceGuard burned in. Sorry about the
258
+ /// copy-pasting.
259
+
260
+ struct HIPGuardMasqueradingAsCUDA {
261
+ explicit HIPGuardMasqueradingAsCUDA() = delete;
262
+ explicit HIPGuardMasqueradingAsCUDA(DeviceIndex device_index) : guard_(device_index) {}
263
+ explicit HIPGuardMasqueradingAsCUDA(Device device) : guard_(device) {}
264
+
265
+ HIPGuardMasqueradingAsCUDA(const HIPGuardMasqueradingAsCUDA&) = delete;
266
+ HIPGuardMasqueradingAsCUDA& operator=(const HIPGuardMasqueradingAsCUDA&) = delete;
267
+ HIPGuardMasqueradingAsCUDA(HIPGuardMasqueradingAsCUDA&& other) = delete;
268
+ HIPGuardMasqueradingAsCUDA& operator=(HIPGuardMasqueradingAsCUDA&& other) = delete;
269
+
270
+ void set_device(Device device) { guard_.set_device(device); }
271
+ void reset_device(Device device) { guard_.reset_device(device); }
272
+ void set_index(DeviceIndex device_index) { guard_.set_index(device_index); }
273
+ Device original_device() const { return guard_.original_device(); }
274
+ Device current_device() const { return guard_.current_device(); }
275
+
276
+ private:
277
+ c10::impl::InlineDeviceGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
278
+ };
279
+
280
+ struct OptionalHIPGuardMasqueradingAsCUDA {
281
+ explicit OptionalHIPGuardMasqueradingAsCUDA() : guard_() {}
282
+ explicit OptionalHIPGuardMasqueradingAsCUDA(std::optional<Device> device_opt) : guard_(device_opt) {}
283
+ explicit OptionalHIPGuardMasqueradingAsCUDA(std::optional<DeviceIndex> device_index_opt) : guard_(device_index_opt) {}
284
+
285
+ OptionalHIPGuardMasqueradingAsCUDA(const OptionalHIPGuardMasqueradingAsCUDA&) = delete;
286
+ OptionalHIPGuardMasqueradingAsCUDA& operator=(const OptionalHIPGuardMasqueradingAsCUDA&) = delete;
287
+ OptionalHIPGuardMasqueradingAsCUDA(OptionalHIPGuardMasqueradingAsCUDA&& other) = delete;
288
+ OptionalHIPGuardMasqueradingAsCUDA& operator=(OptionalHIPGuardMasqueradingAsCUDA&& other) = delete;
289
+
290
+ void set_device(Device device) { guard_.set_device(device); }
291
+ void reset_device(Device device) { guard_.reset_device(device); }
292
+ void set_index(DeviceIndex device_index) { guard_.set_index(device_index); }
293
+ std::optional<Device> original_device() const { return guard_.original_device(); }
294
+ std::optional<Device> current_device() const { return guard_.current_device(); }
295
+ void reset() { guard_.reset(); }
296
+
297
+ private:
298
+ c10::impl::InlineOptionalDeviceGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
299
+ };
300
+
301
+ struct HIPStreamGuardMasqueradingAsCUDA {
302
+ explicit HIPStreamGuardMasqueradingAsCUDA() = delete;
303
+ explicit HIPStreamGuardMasqueradingAsCUDA(Stream stream) : guard_(stream) {}
304
+ HIPStreamGuardMasqueradingAsCUDA(const HIPStreamGuardMasqueradingAsCUDA&) = delete;
305
+ HIPStreamGuardMasqueradingAsCUDA& operator=(const HIPStreamGuardMasqueradingAsCUDA&) = delete;
306
+ HIPStreamGuardMasqueradingAsCUDA(HIPStreamGuardMasqueradingAsCUDA&& other) = delete;
307
+ HIPStreamGuardMasqueradingAsCUDA& operator=(HIPStreamGuardMasqueradingAsCUDA&& other) = delete;
308
+
309
+ void reset_stream(Stream stream) { guard_.reset_stream(stream); }
310
+
311
+ HIPStreamMasqueradingAsCUDA original_stream() const {
312
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, guard_.original_stream());
313
+ }
314
+ HIPStreamMasqueradingAsCUDA current_stream() const {
315
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, guard_.current_stream());
316
+ }
317
+
318
+ Device current_device() const { return guard_.current_device(); }
319
+ Device original_device() const { return guard_.original_device(); }
320
+
321
+ private:
322
+ c10::impl::InlineStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
323
+ };
324
+
325
+ struct OptionalHIPStreamGuardMasqueradingAsCUDA {
326
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA() : guard_() {}
327
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA(Stream stream) : guard_(stream) {}
328
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA(std::optional<Stream> stream_opt) : guard_(stream_opt) {}
329
+
330
+ OptionalHIPStreamGuardMasqueradingAsCUDA(const OptionalHIPStreamGuardMasqueradingAsCUDA&) = delete;
331
+ OptionalHIPStreamGuardMasqueradingAsCUDA& operator=(const OptionalHIPStreamGuardMasqueradingAsCUDA&) = delete;
332
+ OptionalHIPStreamGuardMasqueradingAsCUDA(OptionalHIPStreamGuardMasqueradingAsCUDA&& other) = delete;
333
+ OptionalHIPStreamGuardMasqueradingAsCUDA& operator=(OptionalHIPStreamGuardMasqueradingAsCUDA&& other) = delete;
334
+
335
+ void reset_stream(Stream stream) { guard_.reset_stream(stream); }
336
+
337
+ std::optional<HIPStreamMasqueradingAsCUDA> original_stream() const {
338
+ auto r = guard_.original_stream();
339
+ if (r.has_value()) {
340
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, r.value());
341
+ } else {
342
+ return std::nullopt;
343
+ }
344
+ }
345
+
346
+ std::optional<HIPStreamMasqueradingAsCUDA> current_stream() const {
347
+ auto r = guard_.current_stream();
348
+ if (r.has_value()) {
349
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, r.value());
350
+ } else {
351
+ return std::nullopt;
352
+ }
353
+ }
354
+
355
+ void reset() { guard_.reset(); }
356
+
357
+ private:
358
+ c10::impl::InlineOptionalStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
359
+ };
360
+
361
+ struct HIPMultiStreamGuardMasqueradingAsCUDA {
362
+ explicit HIPMultiStreamGuardMasqueradingAsCUDA(ArrayRef<HIPStreamMasqueradingAsCUDA> streams)
363
+ : guard_(unwrapStreams(streams)) {}
364
+
365
+ HIPMultiStreamGuardMasqueradingAsCUDA(const HIPMultiStreamGuardMasqueradingAsCUDA&) = delete;
366
+ HIPMultiStreamGuardMasqueradingAsCUDA& operator=(const HIPMultiStreamGuardMasqueradingAsCUDA&) = delete;
367
+ HIPMultiStreamGuardMasqueradingAsCUDA(HIPMultiStreamGuardMasqueradingAsCUDA&& other) = delete;
368
+ HIPMultiStreamGuardMasqueradingAsCUDA& operator=(HIPMultiStreamGuardMasqueradingAsCUDA&& other) = delete;
369
+
370
+ private:
371
+ c10::impl::InlineMultiStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
372
+
373
+ static std::vector<Stream> unwrapStreams(ArrayRef<HIPStreamMasqueradingAsCUDA> hipStreams) {
374
+ std::vector<Stream> streams;
375
+ streams.reserve(hipStreams.size());
376
+ for (const HIPStreamMasqueradingAsCUDA& hipStream : hipStreams) {
377
+ streams.push_back(hipStream);
378
+ }
379
+ return streams;
380
+ }
381
+ };
382
+
383
+ }} // namespace c10::hip
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/hip/HIPStream.h>
4
+
5
+ // Use of c10::hip namespace here makes hipification easier, because
6
+ // I don't have to also fix namespaces. Sorry!
7
+ namespace c10 { namespace hip {
8
+
9
+ // See Note [Masquerading as CUDA] for motivation
10
+
11
+ class HIPStreamMasqueradingAsCUDA {
12
+ public:
13
+
14
+ enum Unchecked { UNCHECKED };
15
+
16
+ explicit HIPStreamMasqueradingAsCUDA(Stream stream)
17
+ : HIPStreamMasqueradingAsCUDA(UNCHECKED, stream) {
18
+ // We did the coercion unchecked; check that it was right.
19
+ TORCH_CHECK(stream.device().is_cuda() /* !!! */);
20
+ }
21
+
22
+ explicit HIPStreamMasqueradingAsCUDA(Unchecked, Stream stream)
23
+ // Unsafely coerce the "CUDA" stream into a HIP stream
24
+ : stream_(
25
+ HIPStream(
26
+ Stream(
27
+ Stream::UNSAFE,
28
+ Device(c10::DeviceType::HIP, stream.device_index()),
29
+ stream.id())
30
+ )
31
+ ) {}
32
+
33
+ // New constructor, just for this. Does NOT coerce.
34
+ explicit HIPStreamMasqueradingAsCUDA(HIPStream stream) : stream_(stream) {}
35
+
36
+ bool operator==(const HIPStreamMasqueradingAsCUDA& other) const noexcept {
37
+ return stream_ == other.stream_;
38
+ }
39
+
40
+ bool operator!=(const HIPStreamMasqueradingAsCUDA& other) const noexcept {
41
+ return stream_ != other.stream_;
42
+ }
43
+
44
+ operator hipStream_t() const { return stream_.stream(); }
45
+
46
+ operator Stream() const {
47
+ // Unsafely coerce HIP stream into a "CUDA" stream
48
+ return Stream(Stream::UNSAFE, device(), id());
49
+ }
50
+
51
+ DeviceIndex device_index() const { return stream_.device_index(); }
52
+
53
+ // Unsafely coerce HIP device into CUDA device
54
+ c10::DeviceType device_type() const { return c10::DeviceType::CUDA; }
55
+
56
+ Device device() const {
57
+ // Unsafely coerce HIP device into CUDA device
58
+ return Device(c10::DeviceType::CUDA, stream_.device_index());
59
+ }
60
+
61
+ StreamId id() const { return stream_.id(); }
62
+ bool query() const { return stream_.query(); }
63
+ void synchronize() const { stream_.synchronize(); }
64
+ int priority() const { return stream_.priority(); }
65
+ hipStream_t stream() const { return stream_.stream(); }
66
+
67
+ Stream unwrap() const {
68
+ // Unsafely coerce HIP stream into "CUDA" stream
69
+ return Stream(Stream::UNSAFE, device(), id());
70
+ }
71
+
72
+ c10::StreamData3 pack3() const noexcept {
73
+ // Unsafely coerce HIP stream into "CUDA" stream before packing
74
+ return unwrap().pack3();
75
+ }
76
+
77
+ static HIPStreamMasqueradingAsCUDA unpack3(StreamId stream_id,
78
+ DeviceIndex device_index,
79
+ c10::DeviceType device_type) {
80
+ // NB: constructor manages CUDA->HIP translation for us
81
+ return HIPStreamMasqueradingAsCUDA(Stream::unpack3(
82
+ stream_id, device_index, device_type));
83
+ }
84
+
85
+ static std::tuple<int, int> priority_range() { return HIPStream::priority_range(); }
86
+
87
+ // New method, gets the underlying HIPStream
88
+ HIPStream hip_stream() const { return stream_; }
89
+
90
+ private:
91
+ HIPStream stream_;
92
+ };
93
+
94
+ HIPStreamMasqueradingAsCUDA
95
+ inline getStreamFromPoolMasqueradingAsCUDA(const bool isHighPriority = false, DeviceIndex device = -1) {
96
+ return HIPStreamMasqueradingAsCUDA(getStreamFromPool(isHighPriority, device));
97
+ }
98
+
99
+ HIPStreamMasqueradingAsCUDA
100
+ inline getStreamFromPoolMasqueradingAsCUDA(const int priority, DeviceIndex device = -1) {
101
+ return HIPStreamMasqueradingAsCUDA(getStreamFromPool(priority, device));
102
+ }
103
+
104
+ HIPStreamMasqueradingAsCUDA
105
+ inline getStreamFromExternalMasqueradingAsCUDA(hipStream_t ext_stream, DeviceIndex device) {
106
+ return HIPStreamMasqueradingAsCUDA(getStreamFromExternal(ext_stream, device));
107
+ }
108
+
109
+ inline HIPStreamMasqueradingAsCUDA getDefaultHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) {
110
+ return HIPStreamMasqueradingAsCUDA(getDefaultHIPStream(device_index));
111
+ }
112
+
113
+ inline HIPStreamMasqueradingAsCUDA getCurrentHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) {
114
+ return HIPStreamMasqueradingAsCUDA(getCurrentHIPStream(device_index));
115
+ }
116
+
117
+ inline void setCurrentHIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA stream) {
118
+ setCurrentHIPStream(stream.hip_stream());
119
+ }
120
+
121
+ inline std::ostream& operator<<(std::ostream& stream, const HIPStreamMasqueradingAsCUDA& s) {
122
+ stream << s.hip_stream() << " (masquerading as CUDA)";
123
+ return stream;
124
+ }
125
+
126
+ }} // namespace c10::hip
127
+
128
+ namespace std {
129
+ template <>
130
+ struct hash<c10::hip::HIPStreamMasqueradingAsCUDA> {
131
+ size_t operator()(c10::hip::HIPStreamMasqueradingAsCUDA s) const noexcept {
132
+ return std::hash<c10::Stream>{}(s.unwrap());
133
+ }
134
+ };
135
+ } // namespace std
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/AtomicAddFloat.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef ATOMIC_ADD_FLOAT
2
+ #define ATOMIC_ADD_FLOAT
3
+
4
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__aarch64__))
5
+ #include <ATen/native/cpu/Intrinsics.h>
6
+ #else
7
+ #define _mm_pause()
8
+ #endif
9
+
10
+ #include <atomic>
11
+
12
+ static inline void cpu_atomic_add_float(float* dst, float fvalue)
13
+ {
14
+ typedef union {
15
+ unsigned intV;
16
+ float floatV;
17
+ } uf32_t;
18
+
19
+ uf32_t new_value, old_value;
20
+ std::atomic<unsigned>* dst_intV = (std::atomic<unsigned>*)(dst);
21
+
22
+ old_value.floatV = *dst;
23
+ new_value.floatV = old_value.floatV + fvalue;
24
+
25
+ unsigned* old_intV = (unsigned*)(&old_value.intV);
26
+ while (!std::atomic_compare_exchange_strong(dst_intV, old_intV, new_value.intV)) {
27
+ #ifdef __aarch64__
28
+ __asm__ __volatile__("yield;" : : : "memory");
29
+ #else
30
+ _mm_pause();
31
+ #endif
32
+ old_value.floatV = *dst;
33
+ new_value.floatV = old_value.floatV + fvalue;
34
+ }
35
+ }
36
+
37
+ #endif
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/CatKernel.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/core/IListRef.h>
6
+
7
+ namespace at::native {
8
+
9
+ using cat_serial_fn = void(*)(const Tensor &, const MaterializedITensorListRef&, int64_t);
10
+ DECLARE_DISPATCH(cat_serial_fn, cat_serial_stub)
11
+
12
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ChannelShuffleKernel.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/DispatchStub.h>
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ using channel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t);
12
+ DECLARE_DISPATCH(channel_shuffle_fn, channel_shuffle_kernel)
13
+
14
+ } // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/CopyKernel.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/TensorIterator.h>
4
+
5
+ namespace at {
6
+ struct TensorIteratorBase;
7
+
8
+ namespace native {
9
+ inline namespace CPU_CAPABILITY {
10
+
11
+ void direct_copy_kernel(TensorIteratorBase &iter);
12
+ void copy_kernel(TensorIterator& iter, bool /*non_blocking*/);
13
+
14
+ }}} // namespace at::native::CPU_CAPABILITY
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/DepthwiseConvKernel.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/util/ArrayRef.h>
5
+
6
+ /*
7
+ Depthwise 3x3 Winograd convolution operator
8
+ */
9
+
10
+ namespace at {
11
+ class Tensor;
12
+
13
+ namespace native {
14
+
15
+ using convolution_depthwise3x3_winograd_fn =
16
+ Tensor (*)(const Tensor &, const Tensor &, const Tensor &, IntArrayRef, IntArrayRef, int64_t);
17
+
18
+ DECLARE_DISPATCH(convolution_depthwise3x3_winograd_fn, convolution_depthwise3x3_winograd_stub)
19
+
20
+ } // namespace native
21
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/DistributionTemplates.h ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/CPUApplyUtils.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/Dispatch_v2.h>
6
+ #include <ATen/ExpandBase.h>
7
+ #include <ATen/core/DistributionsHelper.h>
8
+ #include <ATen/native/TensorIterator.h>
9
+ #include <ATen/native/cpu/Loops.h>
10
+ #include <mutex>
11
+
12
+ #ifdef CPU_CAPABILITY_AVX2
13
+ #include <ATen/native/cpu/avx_mathfun.h>
14
+ #include <c10/util/irange.h>
15
+ #endif
16
+
17
+
18
+
19
+
20
+ namespace at::native::templates::cpu {
21
+ namespace {
22
+
23
+ // ==================================================== Random ========================================================
24
+
25
+ template<typename RNG>
26
+ void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG generator) {
27
+ AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cpu", AT_WRAP([&] {
28
+ std::lock_guard<std::mutex> lock(generator->mutex_);
29
+ cpu_serial_kernel(iter, [range, base, generator]() -> scalar_t {
30
+ uniform_int_from_to_distribution<scalar_t> random(range, base);
31
+ return random(generator);
32
+ });
33
+ }), kBool, kHalf, kBFloat16, AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES));
34
+ }
35
+
36
+ // This is the special kernel to handle single specific case:
37
+ // from(inclusive) = std::numeric_limits<int64_t>::lowest()
38
+ // to(exclusive) = None (= std::numeric_limits<int64_t>::max() + 1)
39
+ template<typename RNG>
40
+ void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG generator) {
41
+ AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cpu", [&] {
42
+ if constexpr (std::is_same_v<scalar_t, int64_t> ||
43
+ std::is_same_v<scalar_t, double> ||
44
+ std::is_same_v<scalar_t, float> ||
45
+ std::is_same_v<scalar_t, at::BFloat16>) {
46
+ std::lock_guard<std::mutex> lock(generator->mutex_);
47
+ cpu_serial_kernel(iter, [generator]() -> scalar_t {
48
+ uniform_int_full_range_distribution<scalar_t> random;
49
+ return random(generator);
50
+ });
51
+ } else {
52
+ TORCH_CHECK(false, "random_full_64_bits_range_kernel_cpu handles only int64, double, float and bfloat16");
53
+ }
54
+ });
55
+ }
56
+
57
+ template<typename RNG>
58
+ struct RandomFromToKernel {
59
+ void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional<Generator> gen) {
60
+ random_from_to_kernel(iter, range, base, check_generator<RNG>(gen));
61
+ }
62
+ void operator()(TensorIteratorBase& iter, std::optional<Generator> gen) {
63
+ random_full_64_bits_range_kernel(iter, check_generator<RNG>(gen));
64
+ }
65
+ };
66
+
67
+ template<typename RNG>
68
+ void random_kernel(TensorIteratorBase& iter, RNG generator) {
69
+ std::lock_guard<std::mutex> lock(generator->mutex_);
70
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cpu", [&] {
71
+ cpu_serial_kernel(iter, [generator]() -> scalar_t {
72
+ uniform_int_distribution<scalar_t> random;
73
+ return random(generator);
74
+ });
75
+ });
76
+ }
77
+
78
+ template<typename RNG>
79
+ struct RandomKernel {
80
+ void operator()(TensorIteratorBase& iter, std::optional<Generator> gen) {
81
+ random_kernel(iter, check_generator<RNG>(gen));
82
+ }
83
+ };
84
+
85
+ // ==================================================== Normal ========================================================
86
+
87
+ #ifdef CPU_CAPABILITY_AVX2
88
+ static void normal_fill_16_AVX2(float *data,
89
+ const __m256* two_pi,
90
+ const __m256* one,
91
+ const __m256* minus_two,
92
+ const __m256* mean,
93
+ const __m256* std_v) {
94
+ const __m256 u1 = _mm256_sub_ps(*one, _mm256_loadu_ps(data));
95
+ const __m256 u2 = _mm256_loadu_ps(data + 8);
96
+ // sincos256_ps and log256_ps are from avx_mathfun.h
97
+ const __m256 radius = _mm256_sqrt_ps(_mm256_mul_ps(*minus_two, log256_ps(u1)));
98
+ const __m256 theta = _mm256_mul_ps(*two_pi, u2);
99
+ __m256 sintheta, costheta;
100
+ sincos256_ps(theta, &sintheta, &costheta);
101
+ const __m256 n1 = _mm256_mul_ps(radius, costheta);
102
+ const __m256 n2 = _mm256_mul_ps(radius, sintheta);
103
+ _mm256_storeu_ps(data, _mm256_fmadd_ps(n1, *std_v, *mean));
104
+ _mm256_storeu_ps(data + 8, _mm256_fmadd_ps(n2, *std_v, *mean));
105
+ }
106
+
107
+ template<typename RNG>
108
+ void normal_fill_AVX2(const TensorBase &self, const float mean, const float std, RNG generator) {
109
+ float *data = self.data_ptr<float>();
110
+ auto size = self.numel();
111
+ std::lock_guard<std::mutex> lock(generator->mutex_);
112
+ for (const auto i : c10::irange(size)) {
113
+ at::uniform_real_distribution<float> uniform(0, 1);
114
+ data[i] = uniform(generator);
115
+ }
116
+ const __m256 two_pi = _mm256_set1_ps(2.0f * c10::pi<double>);
117
+ const __m256 one = _mm256_set1_ps(1.0f);
118
+ const __m256 minus_two = _mm256_set1_ps(-2.0f);
119
+ const __m256 mean_v = _mm256_set1_ps(mean);
120
+ const __m256 std_v = _mm256_set1_ps(std);
121
+
122
+ for (int64_t i = 0; i < size - 15; i += 16) {
123
+ normal_fill_16_AVX2(data + i, &two_pi, &one, &minus_two, &mean_v, &std_v);
124
+ }
125
+
126
+ if (size % 16 != 0) {
127
+ // Recompute the last 16 values.
128
+ data = data + size - 16;
129
+ for (const auto i : c10::irange(16)) {
130
+ at::uniform_real_distribution<float> uniform(0, 1);
131
+ data[i] = uniform(generator);
132
+ }
133
+ normal_fill_16_AVX2(data, &two_pi, &one, &minus_two, &mean_v, &std_v);
134
+ }
135
+ }
136
+ #endif
137
+
138
+ template <typename scalar_t>
139
+ static void normal_fill_16(scalar_t *data, const scalar_t mean, const scalar_t std) {
140
+ for (const auto j : c10::irange(8)) {
141
+ const scalar_t u1 = 1 - data[j]; // [0, 1) -> (0, 1] for log.
142
+ const scalar_t u2 = data[j + 8];
143
+ const scalar_t radius = std::sqrt(-2 * std::log(u1));
144
+ const scalar_t theta = 2.0f * c10::pi<double> * u2;
145
+ data[j] = radius * std::cos(theta) * std + mean;
146
+ data[j + 8] = radius * std::sin(theta) * std + mean;
147
+ }
148
+ }
149
+
150
+ #if defined(__VSX__) || defined(CPU_CAPABILITY_VSX)
151
+ static void normal_fill_16_VSX(float *data,const Vectorized<float> &two_pi,const Vectorized<float> &one,const Vectorized<float> &minus_two,const Vectorized<float> &mean,const Vectorized<float> &std) {
152
+ using Vec = Vectorized<float>;
153
+ Vec u1=one-Vec::loadu(data);
154
+ Vec u2=Vec::loadu(data+8);
155
+ Vec radius=(minus_two * u1.log());
156
+ radius=radius.sqrt();
157
+ Vec theta=two_pi * u2;
158
+ Vec output_vec=radius * theta.cos() * std + mean;
159
+ Vec output_vec2=radius * theta.sin() * std + mean;
160
+ output_vec.store(data);
161
+ output_vec2.store(data+8);
162
+ }
163
+
164
+ template <typename scalar_t, typename RNG>
165
+ void normal_fill_VSX(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
166
+ float *data = self.data_ptr<float>();
167
+ auto size = self.numel();
168
+ std::lock_guard<std::mutex> lock(generator->mutex_);
169
+ for (const auto i : c10::irange(size)) {
170
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
171
+ data[i] = uniform(generator);
172
+ }
173
+
174
+ using Vec = Vectorized<float>;
175
+ const Vec two_pi = Vec(2.0f * c10::pi<double>);
176
+ const Vec one = Vec(1.0f);
177
+ const Vec minus_two = Vec(-2.0f);
178
+ const Vec var_vec = Vec(std);
179
+ const Vec mean_vec = Vec(mean);
180
+
181
+ for (int64_t i = 0; i < size - 15; i += 16) {
182
+ if(Vec::size()==8) {
183
+ normal_fill_16_VSX(data + i, two_pi, one, minus_two, mean_vec, var_vec);
184
+ }
185
+ else{
186
+ normal_fill_16<scalar_t>(data + i, mean, std);
187
+ }
188
+ }
189
+ if (size % 16 != 0) {
190
+ // Recompute the last 16 values.
191
+ data = data + size - 16;
192
+ for (const auto i : c10::irange(16)) {
193
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
194
+ data[i] = uniform(generator);
195
+ }
196
+ if(Vec::size()==8){
197
+ normal_fill_16_VSX(data, two_pi, one, minus_two, mean_vec, var_vec);
198
+ }
199
+ else{
200
+ normal_fill_16<scalar_t>(data, mean, std);
201
+ }
202
+ }
203
+ }
204
+ #endif //VSX
205
+
206
+ template <typename scalar_t, typename RNG>
207
+ void normal_fill(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
208
+ scalar_t *data = self.data_ptr<scalar_t>();
209
+ auto size = self.numel();
210
+ std::lock_guard<std::mutex> lock(generator->mutex_);
211
+ for (const auto i : c10::irange(size)) {
212
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
213
+ data[i] = uniform(generator);
214
+ }
215
+
216
+ for (int64_t i = 0; i < size - 15; i += 16) {
217
+ normal_fill_16<scalar_t>(data + i, mean, std);
218
+ }
219
+ if (size % 16 != 0) {
220
+ // Recompute the last 16 values.
221
+ data = data + size - 16;
222
+ for (const auto i : c10::irange(16)) {
223
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
224
+ data[i] = uniform(generator);
225
+ }
226
+ normal_fill_16<scalar_t>(data, mean, std);
227
+ }
228
+ }
229
+
230
+ template<typename RNG>
231
+ void normal_kernel(const TensorBase &self, double mean, double std, RNG generator) {
232
+ auto size = self.numel();
233
+ if (self.scalar_type() == ScalarType::Float && size >= 16 && self.is_contiguous()) {
234
+ #ifdef CPU_CAPABILITY_AVX2
235
+ normal_fill_AVX2(self, static_cast<float>(mean), static_cast<float>(std), generator);
236
+ #elif defined(__VSX__) || defined(CPU_CAPABILITY_VSX)
237
+ normal_fill_VSX(self, static_cast<float>(mean), static_cast<float>(std), generator);
238
+ #else
239
+ normal_fill(self, static_cast<float>(mean), static_cast<float>(std), generator);
240
+ #endif
241
+ } else {
242
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, self.scalar_type(), "normal_kernel_cpu", [&] {
243
+ if (size >= 16 && self.is_contiguous()) {
244
+ normal_fill<scalar_t>(self, static_cast<scalar_t>(mean), static_cast<scalar_t>(std), generator);
245
+ } else {
246
+ auto iter = TensorIterator::borrowing_nullary_op(self);
247
+ std::lock_guard<std::mutex> lock(generator->mutex_);
248
+ cpu_serial_kernel(iter, [mean, std, generator]() -> scalar_t {
249
+ at::normal_distribution<double> normal(mean, std);
250
+ return static_cast<scalar_t>(normal(generator));
251
+ });
252
+ }
253
+ });
254
+ }
255
+ }
256
+
257
+ template<typename RNG>
258
+ struct NormalKernel {
259
+ void operator()(Tensor& self, double mean, double std, std::optional<Generator> gen) {
260
+ normal_kernel(self, mean, std, check_generator<RNG>(gen));
261
+ }
262
+ };
263
+
264
+ // ==================================================== Uniform =======================================================
265
+
266
+ template<typename RNG>
267
+ void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG generator) {
268
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "uniform_kernel_cpu", [&]() {
269
+ std::lock_guard<std::mutex> lock(generator->mutex_);
270
+ auto from = static_cast<scalar_t>(from_);
271
+ auto to = static_cast<scalar_t>(to_);
272
+ at::uniform_real_distribution<scalar_t> uniform(from, to);
273
+ cpu_serial_kernel(iter, [&uniform, generator]() -> scalar_t {
274
+ return static_cast<scalar_t>(uniform(generator));
275
+ });
276
+ });
277
+ }
278
+
279
+ template<typename RNG>
280
+ struct UniformKernel {
281
+ void operator()(TensorIteratorBase& iter, double from, double to, std::optional<Generator> gen) {
282
+ uniform_kernel(iter, from, to, check_generator<RNG>(gen));
283
+ }
284
+ };
285
+
286
+ // ==================================================== Cauchy ========================================================
287
+
288
+ template<typename RNG>
289
+ void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, RNG generator) {
290
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "cauchy_cpu", [&]() {
291
+ std::lock_guard<std::mutex> lock(generator->mutex_);
292
+ at::cauchy_distribution<double> cauchy(median, sigma);
293
+ cpu_serial_kernel(iter, [&cauchy, generator]() -> scalar_t {
294
+ return static_cast<scalar_t>(cauchy(generator));
295
+ });
296
+ });
297
+ }
298
+
299
+ template<typename RNG>
300
+ struct CauchyKernel {
301
+ void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional<Generator> gen) {
302
+ cauchy_kernel(iter, median, sigma, check_generator<RNG>(gen));
303
+ }
304
+ };
305
+
306
+ // ================================================== LogNormal =======================================================
307
+
308
+ template<typename RNG>
309
+ void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, RNG generator) {
310
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cpu", [&]() {
311
+ std::lock_guard<std::mutex> lock(generator->mutex_);
312
+ at::lognormal_distribution<double> logNormal(mean, std);
313
+ cpu_serial_kernel(iter, [&logNormal, generator]() -> scalar_t {
314
+ return static_cast<scalar_t>(logNormal(generator));
315
+ });
316
+ });
317
+ }
318
+
319
+ template<typename RNG>
320
+ struct LogNormalKernel {
321
+ void operator()(TensorIteratorBase& iter, double mean, double std, std::optional<Generator> gen) {
322
+ log_normal_kernel(iter, mean, std, check_generator<RNG>(gen));
323
+ }
324
+ };
325
+
326
+ // =================================================== Geometric ======================================================
327
+
328
+ template<typename RNG>
329
+ void geometric_kernel(TensorIteratorBase& iter, double p, RNG generator) {
330
+ AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cpu", [&]() {
331
+ std::lock_guard<std::mutex> lock(generator->mutex_);
332
+ at::geometric_distribution<double> geometric(p);
333
+ cpu_serial_kernel(iter, [&geometric, generator]() -> scalar_t {
334
+ return static_cast<scalar_t>(geometric(generator));
335
+ });
336
+ });
337
+ }
338
+
339
+ template<typename RNG>
340
+ struct GeometricKernel {
341
+ void operator()(TensorIteratorBase& iter, double p, std::optional<Generator> gen) {
342
+ geometric_kernel(iter, p, check_generator<RNG>(gen));
343
+ }
344
+ };
345
+
346
+ // ================================================== Exponential =====================================================
347
+
348
+ template<typename RNG>
349
+ void exponential_kernel(TensorIteratorBase& iter, double lambda, RNG generator) {
350
+ TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype());
351
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cpu", [&]() {
352
+ std::lock_guard<std::mutex> lock(generator->mutex_);
353
+ at::exponential_distribution<double> exponential(lambda);
354
+ cpu_serial_kernel(iter, [&exponential, generator]() -> scalar_t {
355
+ return static_cast<scalar_t>(exponential(generator));
356
+ });
357
+ });
358
+ }
359
+
360
+ template<typename RNG>
361
+ struct ExponentialKernel {
362
+ void operator()(TensorIteratorBase& iter, double lambda, std::optional<Generator> gen) {
363
+ exponential_kernel(iter, lambda, check_generator<RNG>(gen));
364
+ }
365
+ };
366
+
367
+ // ================================================== Bernoulli =======================================================
368
+
369
+ template<typename RNG>
370
+ void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG generator) {
371
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
372
+ self.scalar_type(), "bernoulli_tensor_cpu_self_", [&] {
373
+ // See Note [Acquire lock when using random generators]
374
+ std::lock_guard<std::mutex> lock(generator->mutex_);
375
+ using self_t = scalar_t;
376
+ auto p_cpu = p_.to(kCPU);
377
+ auto p = expand_inplace(self, p_cpu);
378
+ auto iter = TensorIteratorConfig()
379
+ .add_output(self)
380
+ .add_const_input(*p)
381
+ .check_all_same_dtype(false)
382
+ .build();
383
+ if (p->scalar_type() == kDouble) {
384
+ cpu_serial_kernel(iter, [&](const double p_val) -> self_t {
385
+ at::bernoulli_distribution<double> bernoulli(p_val);
386
+ return static_cast<self_t>(bernoulli(generator));
387
+ });
388
+ } else {
389
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half,
390
+ p->scalar_type(), "bernoulli_tensor_cpu_p_", [&] {
391
+ using p_t = scalar_t;
392
+ cpu_serial_kernel(iter, [&](const p_t p_val) -> self_t {
393
+ at::bernoulli_distribution<float> bernoulli(p_val);
394
+ return static_cast<self_t>(bernoulli(generator));
395
+ });
396
+ });
397
+ }
398
+ });
399
+ }
400
+
401
+ template<typename RNG>
402
+ void bernoulli_kernel(const TensorBase &self, double p, RNG generator) {
403
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
404
+ self.scalar_type(), "bernoulli_scalar_cpu_", [&] {
405
+ // See Note [Acquire lock when using random generators]
406
+ std::lock_guard<std::mutex> lock(generator->mutex_);
407
+ auto iter = TensorIterator::borrowing_nullary_op(self);
408
+ cpu_serial_kernel(iter, [p, generator]() -> scalar_t {
409
+ at::bernoulli_distribution<double> bernoulli(p);
410
+ return static_cast<scalar_t>(bernoulli(generator));
411
+ });
412
+ });
413
+ }
414
+
415
+ template<typename RNG>
416
+ struct BernoulliKernel {
417
+ void operator()(const TensorBase &self, double p, std::optional<Generator> gen) {
418
+ bernoulli_kernel(self, p, check_generator<RNG>(gen));
419
+ }
420
+ void operator()(const TensorBase &self, const TensorBase &p_, std::optional<Generator> gen) {
421
+ bernoulli_kernel(self, p_, check_generator<RNG>(gen));
422
+ }
423
+ };
424
+
425
+ }}
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Gelu.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cpu/vec/vec.h>
4
+ #include <c10/util/BFloat16.h> // For c10::is_reduced_floating_point_v.
5
+
6
+ namespace at::native {
7
+ constexpr double kGeluBeta = M_SQRT2 * M_2_SQRTPI * 0.5;
8
+ constexpr double kGeluKappa = 0.044715;
9
+
10
+ template <typename T>
11
+ using reduced_fp_to_float_t = std::conditional_t<c10::is_reduced_floating_point_v<T>, float, T>;
12
+
13
+ template <typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
14
+ float reduced_fp_to_float(T x) {
15
+ return float(x);
16
+ }
17
+
18
+ template <typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
19
+ T reduced_fp_to_float(T x) {
20
+ return x;
21
+ }
22
+
23
+ template <typename T>
24
+ T scalar_gelu_approximated_with_tanh(T x) {
25
+ using opmath_t = reduced_fp_to_float_t<T>;
26
+ auto x_float = reduced_fp_to_float(x);
27
+ auto x_cube = x_float * x_float * x_float;
28
+ auto inner = opmath_t(kGeluBeta) * (x_float + opmath_t(kGeluKappa) * x_cube);
29
+ return opmath_t(0.5) * x_float * (opmath_t(1) + std::tanh(inner));
30
+ }
31
+
32
+ template <typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
33
+ vec::Vectorized<T> vectorized_gelu_approximated_with_tanh(vec::Vectorized<T> x) {
34
+ const vec::Vectorized<T> kPointFiveVec(T(0.5));
35
+ const vec::Vectorized<T> kOneVec(T(1));
36
+ const vec::Vectorized<T> kGeluBetaVec((T(kGeluBeta)));
37
+ const vec::Vectorized<T> kGeluKappaVec((T(kGeluKappa)));
38
+ auto x_cube = x * x * x;
39
+ vec::Vectorized<T> inner_vec = kGeluBetaVec * (x + kGeluKappaVec * x_cube);
40
+ return kPointFiveVec * x * (kOneVec + inner_vec.tanh());
41
+ }
42
+
43
+ template <typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
44
+ vec::Vectorized<T> vectorized_gelu_approximated_with_tanh(vec::Vectorized<T> x) {
45
+ auto [x0, x1] = at::vec::convert_to_float<T>(x);
46
+ return at::vec::convert_from_float<T>(
47
+ vectorized_gelu_approximated_with_tanh(x0),
48
+ vectorized_gelu_approximated_with_tanh(x1));
49
+ }
50
+
51
+
52
+ template <typename T>
53
+ T scalar_gelu(T x) {
54
+ using opmath_t = reduced_fp_to_float_t<T>;
55
+ const auto kAlpha = opmath_t(M_SQRT1_2);
56
+ return reduced_fp_to_float(x) * opmath_t(0.5) * (opmath_t(1) + std::erf(reduced_fp_to_float(x) * kAlpha));
57
+ }
58
+
59
+ template<typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
60
+ vec::Vectorized<T> vectorized_gelu(vec::Vectorized<T> x) {
61
+ const vec::Vectorized<T> kAlphaVec(T(M_SQRT1_2));
62
+ const vec::Vectorized<T> kOneVec(T(1));
63
+ const vec::Vectorized<T> kPointFiveVec(T(0.5));
64
+ return x * kPointFiveVec * (kOneVec + (x * kAlphaVec).erf());
65
+ }
66
+
67
+ template<typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
68
+ vec::Vectorized<T> vectorized_gelu(vec::Vectorized<T> x) {
69
+ auto [x0, x1] = at::vec::convert_to_float<T>(x);
70
+ return at::vec::convert_from_float<T>(vectorized_gelu(x0), vectorized_gelu(x1));
71
+ }
72
+
73
+
74
+ } // namespace
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/GridSamplerKernel.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ #include <array>
6
+ #include <cstdint>
7
+
8
+ namespace at {
9
+ class TensorBase;
10
+ }
11
+
12
+ namespace at::native {
13
+
14
+ using forward_2d_fn = void (*) (
15
+ const TensorBase &output,
16
+ const TensorBase &input,
17
+ const TensorBase &grid,
18
+ int64_t interpolation_mode,
19
+ int64_t padding_mode,
20
+ bool align_corners);
21
+ using backward_2d_fn = void (*) (
22
+ const TensorBase &grad_input,
23
+ const TensorBase &grad_grid,
24
+ const TensorBase &grad_output,
25
+ const TensorBase &input,
26
+ const TensorBase &grid,
27
+ int64_t interpolation_mode,
28
+ int64_t padding_mode,
29
+ bool align_corners,
30
+ std::array<bool, 2> output_mask);
31
+ DECLARE_DISPATCH(forward_2d_fn, grid_sampler_2d_cpu_kernel)
32
+ DECLARE_DISPATCH(backward_2d_fn, grid_sampler_2d_backward_cpu_kernel)
33
+
34
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/IndexKernelUtils.h ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/TensorIterator.h>
3
+ #include <c10/util/irange.h>
4
+
5
+ namespace at::native {
6
+
7
+ inline bool is_constant_index(int ntensor, const int64_t* strides) {
8
+ AT_ASSERT(ntensor >= 3);
9
+ for (const auto arg : c10::irange(2, ntensor)) {
10
+ if (strides[arg] != 0) {
11
+ return false;
12
+ }
13
+ }
14
+ return true;
15
+ }
16
+
17
+
18
+ struct Indexer {
19
+ Indexer(int64_t num_indexers, char** indexers, const int64_t* indexer_strides,
20
+ IntArrayRef original_sizes, IntArrayRef original_strides)
21
+ : num_indexers(num_indexers)
22
+ , indexers(indexers)
23
+ , indexer_strides(indexer_strides)
24
+ , original_strides(original_strides.data())
25
+ , original_sizes(original_sizes.data()) {
26
+ AT_ASSERT(static_cast<int64_t>(original_strides.size()) == num_indexers);
27
+ AT_ASSERT(static_cast<int64_t>(original_sizes.size()) == num_indexers);
28
+ }
29
+
30
+ int64_t num_indexers;
31
+ char** indexers;
32
+ const int64_t* indexer_strides;
33
+ const int64_t* original_strides;
34
+ const int64_t* original_sizes;
35
+
36
+ int64_t get(int64_t idx) {
37
+ int64_t offset = 0;
38
+ for (const auto j : c10::irange(num_indexers)) {
39
+ int64_t value = *(int64_t*)&indexers[j][idx * indexer_strides[j]];
40
+ int64_t size = original_sizes[j];
41
+ TORCH_CHECK_INDEX(value >= -size && value < size,
42
+ "index ", value, " is out of bounds for dimension ", j, " with size ", size);
43
+ if (value < 0) {
44
+ value += size;
45
+ }
46
+ offset += value * original_strides[j];
47
+ }
48
+ return offset;
49
+ }
50
+ };
51
+
52
+ template <typename scalar_t, typename func_t>
53
+ void cpu_index_kernel(TensorIteratorBase& iter, IntArrayRef index_size, IntArrayRef index_stride,
54
+ const func_t& f, bool serial_execution=false)
55
+ {
56
+ int ntensor = iter.ntensors();
57
+ // When launch the index parallel version, set a relative small grain size less than the INTERNAL::GRAIN_SIZE
58
+ // to make the whole available thread numbers get more balanced work load and a better cache location.
59
+ // The grain size here is chosen by the op benchmark to overcome the thread launch overhead
60
+ const int index_parallel_grain_size = 3000;
61
+ auto loop = [&](char** data, const int64_t* strides, int64_t n) {
62
+ auto indexer = Indexer(ntensor - 2, &data[2], &strides[2], index_size, index_stride);
63
+ char* dst = data[0];
64
+ char* src = data[1];
65
+ if (is_constant_index(ntensor, strides)) {
66
+ // specialization for when every element uses the same index
67
+ int64_t offset = indexer.get(0);
68
+ for (const auto i : c10::irange(n)) {
69
+ f(dst + strides[0] * i, src + strides[1] * i, offset);
70
+ }
71
+ } else {
72
+ for (const auto i : c10::irange(n)) {
73
+ int64_t offset = indexer.get(i);
74
+ f(dst + strides[0] * i, src + strides[1] * i, offset);
75
+ }
76
+ }
77
+ };
78
+ if (serial_execution) {
79
+ iter.serial_for_each(loop, {0, iter.numel()});
80
+ } else {
81
+ iter.for_each(loop, index_parallel_grain_size);
82
+ }
83
+ }
84
+ } // at
85
+ // native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Intrinsics.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #if defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
4
+ /* Clang-compatible compiler, targeting x86/x86-64 */
5
+ #include <x86intrin.h>
6
+ #elif defined(_MSC_VER)
7
+ /* Microsoft C/C++-compatible compiler */
8
+ #include <intrin.h>
9
+ #if _MSC_VER <= 1900
10
+ #define _mm256_extract_epi64(X, Y) (((uint64_t*)&X)[Y])
11
+ #endif
12
+ #elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
13
+ /* GCC-compatible compiler, targeting x86/x86-64 */
14
+ #include <x86intrin.h>
15
+ #elif defined(__GNUC__) && defined(__ARM_NEON__)
16
+ /* GCC-compatible compiler, targeting ARM with NEON */
17
+ #include <arm_neon.h>
18
+ #elif defined(__GNUC__) && defined(__IWMMXT__)
19
+ /* GCC-compatible compiler, targeting ARM with WMMX */
20
+ #include <mmintrin.h>
21
+ #elif (defined(__GNUC__) || defined(__xlC__)) && \
22
+ (defined(__VEC__) || defined(__ALTIVEC__))
23
+ /* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */
24
+ #include <altivec.h>
25
+ /* We need to undef those tokens defined by <altivec.h> to avoid conflicts
26
+ with the C++ types. => Can still use __bool/__vector */
27
+ #undef bool
28
+ #undef vector
29
+ #undef pixel
30
+ #elif defined(__GNUC__) && defined(__SPE__)
31
+ /* GCC-compatible compiler, targeting PowerPC with SPE */
32
+ #include <spe.h>
33
+ #endif
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/IsContiguous.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ namespace at::native { inline namespace CPU_CAPABILITY {
4
+
5
+ // n: number of function arguments (arity)
6
+ // traits: function_traits (see FunctionTraits.h)
7
+ // s: index of scalar argument or -1
8
+ template <int n, int stride_index, typename traits, int s=-1>
9
+ struct IsContiguous {
10
+ static bool eval(const int64_t* strides) {
11
+ using type = typename traits::template arg<n - 1>::type;
12
+ return strides[stride_index] == (s == n ? 0 : sizeof(type)) &&
13
+ IsContiguous<n - 1, stride_index - 1, traits, s>::eval(strides);
14
+ }
15
+ };
16
+
17
+ // will be called when there is an output exists
18
+ template <typename traits, int s>
19
+ struct IsContiguous<0, 0, traits, s> {
20
+ static bool eval(const int64_t* strides) {
21
+ return strides[0] == sizeof(typename traits::result_type);
22
+ }
23
+ };
24
+
25
+ // will be called when there is no output
26
+ template <typename traits, int s>
27
+ struct IsContiguous<0, -1, traits, s> {
28
+ static bool eval(const int64_t* /*strides*/) {
29
+ return true;
30
+ }
31
+ };
32
+
33
+ // output and all inputs are contiguous
34
+ template <
35
+ typename traits,
36
+ std::enable_if_t<std::is_void_v<typename traits::result_type>>* =
37
+ nullptr>
38
+ static inline bool is_contiguous(const int64_t* strides) {
39
+ return IsContiguous<traits::arity, traits::arity - 1, traits>::eval(strides);
40
+ }
41
+
42
+ template <typename traits,
43
+ std::enable_if_t<!std::is_void_v<typename traits::result_type>>* = nullptr>
44
+ static inline bool is_contiguous(const int64_t* strides) {
45
+ return IsContiguous<traits::arity, traits::arity, traits>::eval(strides);
46
+ }
47
+
48
+ // input at `s` is scalar (stride 0); output and other inputs are contiguous
49
+ // NB: output is typically at strides[0] so first input corresponds to s=1
50
+ template <typename traits, int s,
51
+ std::enable_if_t<std::is_void_v<typename traits::result_type>>* = nullptr>
52
+ static inline bool is_contiguous_scalar(const int64_t* strides) {
53
+ static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
54
+ return IsContiguous<traits::arity, traits::arity - 1, traits, s>::eval(strides);
55
+ }
56
+
57
+ template <typename traits, int s,
58
+ std::enable_if_t<!std::is_void_v<typename traits::result_type>>* = nullptr>
59
+ static inline bool is_contiguous_scalar(const int64_t* strides) {
60
+ static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
61
+ return IsContiguous<traits::arity, traits::arity, traits, s>::eval(strides);
62
+ }
63
+
64
+ }}
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/LogAddExp.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/complex.h>
4
+ #include <ATen/NumericUtils.h>
5
+
6
+ namespace at::native {
7
+ inline namespace CPU_CAPABILITY {
8
+
9
+ // custom min and max to be used in logcumsumexp for complex arguments
10
+ template <typename scalar_t>
11
+ std::pair<c10::complex<scalar_t>, c10::complex<scalar_t>> _logcumsumexp_minmax(c10::complex<scalar_t> x, c10::complex<scalar_t> y) {
12
+ if (at::_isnan(y)) { // either real is nan or imag is nan
13
+ return std::make_pair(y, y);
14
+ } else if (at::_isnan(x)) { // either real is nan or imag is nan
15
+ return std::make_pair(x, x);
16
+ } else {
17
+ return (x.real() < y.real()) ? std::make_pair(x, y) : std::make_pair(y, x);
18
+ }
19
+ }
20
+
21
+ template <typename scalar_t>
22
+ scalar_t _log_add_exp_helper(scalar_t x, scalar_t y) {
23
+ // Reference : https://www.tensorflow.org/api_docs/python/tf/math/cumulative_logsumexp
24
+ scalar_t min = at::_isnan(y) ? y : std::min(x, y); // std::min returns first arg if one of the args is nan
25
+ scalar_t max = at::_isnan(y) ? y : std::max(x, y); // std::max returns first arg if one of the args is nan
26
+ if (min != max || std::isfinite(min)) {
27
+ // nan will be propagated here
28
+ return std::log1p(std::exp(min - max)) + max;
29
+ } else {
30
+ // special case to correctly handle infinite cases
31
+ return x;
32
+ }
33
+ }
34
+
35
+ template <typename scalar_t>
36
+ c10::complex<scalar_t> _log_add_exp_helper(const c10::complex<scalar_t>& x, const c10::complex<scalar_t>& y) {
37
+ auto [min, max] = _logcumsumexp_minmax<scalar_t>(x, y);
38
+ auto min_real = std::real(min);
39
+ auto max_real = std::real(max);
40
+
41
+ if (at::_isnan(min)) { // either real is nan or imag is nan
42
+ // handling the "infectious" NaNs
43
+ return {std::numeric_limits<scalar_t>::quiet_NaN(), std::numeric_limits<scalar_t>::quiet_NaN()};
44
+ } else if (!std::isfinite(min_real) && (min_real == max_real)) {
45
+ if (min_real < 0) {
46
+ // handle the -inf case, the imaginary part here does not really matter as the exp(value)
47
+ // will be around 0.0 and the angle (i.e. the imaginary part) cannot be determined.
48
+ // It does not matter if we're taking the exp of this value
49
+ return min;
50
+ } else {
51
+ // handle the +inf case, we don't need the special precision for log1p for small values
52
+ // and to avoid producing nan in case of real(max) == real(min) == +inf
53
+ return std::log(std::exp(min) + std::exp(max));
54
+ }
55
+ } else {
56
+ return std::log1p(std::exp(min - max)) + max;
57
+ }
58
+ }
59
+
60
+ } // end namespace
61
+ } //end at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Loops.h ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // This file provides two functions to help write elementwise kernels:
4
+ //
5
+ // cpu_kernel(TensorIterator iter, <lambda>)
6
+ // cpu_kernel_vec(TensorIterator iter, <lambda>, <vec_lambda>)
7
+ //
8
+ // Both functions may generate vectorized code. The cpu_kernel implementation
9
+ // relies on the compiler's auto-vectorization. The cpu_kernel_vec
10
+ // implementation uses x86 SIMD intrinsics when available. These functions
11
+ // are only intended to be used in the ATen/native/cpu subdirectory, since files
12
+ // in other directories are not compiled with AVX/AVX2 enabled. See README.md
13
+ // for more details.
14
+ //
15
+ // For example, to write a multiplication kernel for float:
16
+ //
17
+ // cpu_kernel(iter, [](float a, float b) { return a * b; });
18
+ //
19
+ // Or you may write:
20
+ //
21
+ // cpu_kernel_vec(iter,
22
+ // [](float a, float b) { return a * b; },
23
+ // [](Vectorized<float> a, Vectorized<float> b) { return a * b; });
24
+ //
25
+ // See BinaryOpsKernel.cpp for the complete implementation
26
+ //
27
+ //
28
+
29
+ #include <cstdint>
30
+ #include <c10/util/C++17.h>
31
+ #include <c10/util/Load.h>
32
+ #include <c10/util/irange.h>
33
+ #include <ATen/detail/FunctionTraits.h>
34
+ #include <ATen/native/cpu/IsContiguous.h>
35
+ #include <ATen/native/TensorIterator.h>
36
+ #include <ATen/native/TensorIteratorDynamicCasting.h>
37
+ #include <ATen/cpu/vec/vec.h>
38
+
39
+ #include <tuple>
40
+ #include <utility>
41
+
42
+ namespace at::native { inline namespace CPU_CAPABILITY {
43
+
44
+ using namespace vec;
45
+
46
+ template <typename traits, std::size_t... INDEX>
47
+ typename traits::ArgsTuple
48
+ dereference_impl(char* C10_RESTRICT data[], const int64_t* strides, int64_t i,
49
+ std::index_sequence<INDEX...>) {
50
+ return std::make_tuple(
51
+ c10::load<typename traits::template arg<INDEX>::type>(
52
+ data[INDEX] + i * strides[INDEX])...);
53
+ }
54
+
55
+ template <typename traits>
56
+ typename traits::ArgsTuple
57
+ dereference(char* C10_RESTRICT data[], const int64_t* strides, int64_t i) {
58
+ using Indices = std::make_index_sequence<traits::arity>;
59
+ return dereference_impl<traits>(data, strides, i, Indices{});
60
+ }
61
+
62
+ template <typename traits, std::size_t... INDEX>
63
+ typename traits::ArgsTuple
64
+ dereference_vec_impl(char* C10_RESTRICT data[],
65
+ const typename traits::result_type& opt_scalar,
66
+ size_t S,
67
+ int64_t i,
68
+ std::index_sequence<INDEX...>) {
69
+ using Vec = typename traits::result_type;
70
+ using scalar_t = typename Vec::value_type;
71
+ return std::make_tuple(
72
+ S == INDEX + 1 ?
73
+ opt_scalar :
74
+ Vec::loadu(data[INDEX] + i * sizeof(scalar_t))...);
75
+ }
76
+
77
+ template <typename traits>
78
+ typename traits::ArgsTuple
79
+ dereference_vec(char* C10_RESTRICT data[], const typename traits::result_type& opt_scalar, size_t S, int64_t i) {
80
+ using Indices = std::make_index_sequence<traits::arity>;
81
+ return dereference_vec_impl<traits>(data, opt_scalar, S, i, Indices{});
82
+ }
83
+
84
+ template <typename func_t,
85
+ std::enable_if_t<!std::is_void_v<typename function_traits<func_t>::result_type>>* = nullptr>
86
+ inline void
87
+ execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) {
88
+ using traits = function_traits<func_t>;
89
+ using result_type = typename traits::result_type;
90
+ for (; i < n; i++) {
91
+ result_type* out_ptr = (result_type*)(data[0] + i * strides[0]);
92
+ *out_ptr = c10::guts::apply(op, dereference<traits>(
93
+ &data[1],
94
+ &strides[1],
95
+ i));
96
+ }
97
+ }
98
+
99
+ template <typename func_t,
100
+ std::enable_if_t<std::is_void_v<typename function_traits<func_t>::result_type>>* = nullptr>
101
+ inline void
102
+ execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) {
103
+ using traits = function_traits<func_t>;
104
+ for (; i < n; i++) {
105
+ c10::guts::apply(op, dereference<traits>(
106
+ &data[0],
107
+ &strides[0],
108
+ i));
109
+ }
110
+ }
111
+
112
+ // Basic loop operation (one output, N inputs). May be auto-vectorized
113
+ // by the compiler. Supports inputs and outputs of different types.
114
+ template <typename func_t>
115
+ inline void
116
+ basic_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) {
117
+ using traits = function_traits<func_t>;
118
+ constexpr int ntensors = traits::arity + 1;
119
+
120
+ // Copying strides to temporary array helps auto vectorization in older GCC
121
+ // versions.
122
+ int64_t strides[ntensors];
123
+ for (const auto arg : c10::irange(ntensors)) {
124
+ strides[arg] = strides_[arg];
125
+ }
126
+
127
+ execute_op(data, strides, i, n, std::forward<func_t>(op));
128
+ }
129
+
130
+ // the recursive variadic template for iterating over the returned tuple
131
+ template<class T, size_t N>
132
+ struct TupleOutput {
133
+ static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i,
134
+ const T &tuple) {
135
+ TupleOutput<T, N - 1>::handle(data, strides, i, tuple);
136
+
137
+ auto output = std::get<N - 1>(tuple);
138
+ using output_type = decltype(output);
139
+ output_type * out_ptr = (output_type *)(data[N - 1] + i * strides[N - 1]);
140
+ *out_ptr = output;
141
+ }
142
+ };
143
+
144
+ // Base case for the above recursive template
145
+ template<class T>
146
+ struct TupleOutput<T, 1> {
147
+ static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i,
148
+ const T &tuple) {
149
+ auto output = std::get<0>(tuple);
150
+ using output_type = decltype(output);
151
+ output_type* out_ptr = (output_type *)(data[0] + i * strides[0]);
152
+ *out_ptr = output;
153
+ }
154
+ };
155
+
156
+ template<class... Args>
157
+ void handle_tuple_outputs(char* C10_RESTRICT data[],
158
+ const int64_t* strides,
159
+ int64_t i,
160
+ const std::tuple<Args...> &tuple) {
161
+ TupleOutput<decltype(tuple), sizeof...(Args)>::handle(data, strides, i, tuple);
162
+ }
163
+
164
+ // Loop operation for `cpu_kernel_multiple_outputs`.
165
+ // 1. Use `c10::guts::apply` to make dynamic method invocation
166
+ // for the lambda passed in `cpu_kernel_multiple_outputs`.
167
+ // 2. Iterate over the members of the returned tuple, set the corresponding
168
+ // output tensor by the tuple member in `handle_tuple_outputs` function.
169
+ template <typename func_t>
170
+ inline void
171
+ multiple_outputs_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) {
172
+ using traits = function_traits<func_t>;
173
+
174
+ using result_type = typename traits::result_type;
175
+ constexpr int num_outputs = std::tuple_size_v<result_type>;
176
+ constexpr int ntensors = traits::arity + num_outputs;
177
+
178
+ // Copying strides to temporary array helps auto vectorization in older GCC
179
+ // versions.
180
+ int64_t strides[ntensors];
181
+ for (const auto arg : c10::irange(ntensors)) {
182
+ strides[arg] = strides_[arg];
183
+ }
184
+
185
+ for (; i < n; i++) {
186
+ auto output = c10::guts::apply(op, dereference<traits>(
187
+ &data[num_outputs],
188
+ &strides[num_outputs],
189
+ i));
190
+ handle_tuple_outputs(data, strides, i, output);
191
+ }
192
+ }
193
+
194
+ // Explicitly vectorized loop implementation. All inputs and outputs must be
195
+ // the same type and contiguous with one exception: a single input may be
196
+ // a scalar (stride 0). It's position is indicated by the argument `S`. If `S`
197
+ // is 0, then there are no scalar inputs.
198
+ template <typename func_t, typename vec_func_t>
199
+ inline void
200
+ vectorized_loop(char** C10_RESTRICT data_, int64_t n, int64_t S, func_t&& op, vec_func_t&& vop) {
201
+ using traits = function_traits<vec_func_t>;
202
+ using scalar_t = typename function_traits<func_t>::result_type;
203
+ using Vec = Vectorized<scalar_t>;
204
+ constexpr int ntensors = traits::arity + 1;
205
+
206
+ char* C10_RESTRICT data[ntensors];
207
+ for (const auto arg : c10::irange(ntensors)) {
208
+ data[arg] = data_[arg];
209
+ }
210
+
211
+ Vec opt_scalar = Vec(S > 0 ? c10::load((scalar_t*)data[S]) : scalar_t(0));
212
+ int64_t i = 0;
213
+ for (; i <= n - 2 * Vec::size(); i += 2 * Vec::size()) {
214
+ auto args1 = dereference_vec<traits>(&data[1], opt_scalar, S, i);
215
+ auto args2 = dereference_vec<traits>(&data[1], opt_scalar, S, i + Vec::size());
216
+ auto out1 = c10::guts::apply(vop, std::move(args1));
217
+ auto out2 = c10::guts::apply(vop, std::move(args2));
218
+ out1.store(data[0] + i * sizeof(scalar_t));
219
+ out2.store(data[0] + (i + Vec::size()) * sizeof(scalar_t));
220
+ }
221
+ if (i < n) {
222
+ int64_t strides[ntensors];
223
+ for (const auto arg : c10::irange(ntensors)) {
224
+ strides[arg] = (S > 0 && arg == S) ? 0 : sizeof(scalar_t);
225
+ }
226
+ basic_loop(data, strides, i, n, std::forward<func_t>(op));
227
+ }
228
+ }
229
+
230
+
231
+ template <typename traits, typename cb_t>
232
+ inline void unroll_contiguous_scalar_checks(
233
+ const int64_t* /*strides*/,
234
+ std::index_sequence<>,
235
+ cb_t&& cb) {
236
+ cb(0);
237
+ }
238
+
239
+ template <typename traits, typename cb_t, size_t INDEX0, size_t ...INDEX>
240
+ inline void unroll_contiguous_scalar_checks(
241
+ const int64_t* strides,
242
+ std::index_sequence<INDEX0, INDEX...>,
243
+ cb_t&& cb) {
244
+ if (is_contiguous_scalar<traits, INDEX0 + 1>(strides)) {
245
+ cb(INDEX0 + 1);
246
+ } else {
247
+ unroll_contiguous_scalar_checks<traits>(strides, std::index_sequence<INDEX...>{}, std::forward<cb_t>(cb));
248
+ }
249
+ }
250
+
251
+ template <typename op_t, typename vop_t>
252
+ struct VectorizedLoop2d {
253
+ op_t op;
254
+ vop_t vop;
255
+
256
+ using traits = function_traits<op_t>;
257
+ static constexpr int ntensors = traits::arity + 1;
258
+ using data_t = std::array<char*, ntensors>;
259
+
260
+ VectorizedLoop2d(op_t op, vop_t vop):
261
+ op(std::move(op)), vop(std::move(vop)) {}
262
+
263
+ static void advance(data_t &data, const int64_t *outer_strides) {
264
+ for (const auto arg : c10::irange(data.size())) {
265
+ data[arg] += outer_strides[arg];
266
+ }
267
+ }
268
+
269
+ void operator()(char** base, const int64_t *strides, int64_t size0, int64_t size1) {
270
+ data_t data;
271
+ std::copy_n(base, ntensors, data.data());
272
+ const int64_t *outer_strides = &strides[ntensors];
273
+
274
+ if (is_contiguous<traits>(strides)) {
275
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
276
+ vectorized_loop(data.data(), size0, 0, op, vop);
277
+ advance(data, outer_strides);
278
+ }
279
+ } else {
280
+ using Indices = std::make_index_sequence<traits::arity>;
281
+ unroll_contiguous_scalar_checks<traits>(strides, Indices{}, [&](size_t idx) {
282
+ if (idx) {
283
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
284
+ vectorized_loop(data.data(), size0, idx, op, vop);
285
+ advance(data, outer_strides);
286
+ }
287
+ } else {
288
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
289
+ basic_loop(data.data(), strides, 0, size0, op);
290
+ advance(data, outer_strides);
291
+ }
292
+ }
293
+ });
294
+ }
295
+ }
296
+ };
297
+
298
+ template <typename op_t, typename vop_t>
299
+ VectorizedLoop2d<op_t, vop_t> make_vectorized_loop2d(
300
+ op_t &&op, vop_t &&vop) {
301
+ return VectorizedLoop2d<op_t, vop_t>(std::forward<op_t>(op), std::forward<vop_t>(vop));
302
+ }
303
+
304
+ template <typename func_t>
305
+ void cpu_kernel(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) {
306
+ using traits = function_traits<func_t>;
307
+ // this could be extended to work with void return types
308
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
309
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
310
+ // dynamic casting not currently supported on CPU
311
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
312
+
313
+ iter.for_each([&](char** data, const int64_t* strides, int64_t n) {
314
+ // basic loop can handle 1d slices with arbitrary strides, and 1d slices is all that
315
+ // iter.for_each is ever sending to the loop lambda
316
+ basic_loop(data, strides, 0, n, op);
317
+ }, grain_size);
318
+ iter.cast_outputs();
319
+ }
320
+
321
+ // This function helps write elementwise kernels that requires multiple outputs.
322
+ // It follows the similar structure of cpu_kernel.
323
+ // Instead of `basic_loop` function, a new `multiple_outputs_loop` function is
324
+ // manipulated to handle multiple return values.
325
+ // For now `needs_dynamic_casting` check is not added as the passed lambda (`func_t`)
326
+ // of `multiple_outputs_loop` returns `std::tuple` instead of `scalar_t`.
327
+ // The `gpu_kernel_multiple_outputs` is also implemented without this check,
328
+ // We could extend `needs_dynamic_casting` to support both `std::tuple` and
329
+ // `thrust::tuple` in the future.
330
+ template <typename func_t>
331
+ void cpu_kernel_multiple_outputs(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) {
332
+ using traits = function_traits<func_t>;
333
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
334
+
335
+ iter.for_each([&](char** data, const int64_t* strides, int64_t n) {
336
+ multiple_outputs_loop(data, strides, 0, n, op);
337
+ }, grain_size);
338
+ iter.cast_outputs();
339
+ }
340
+
341
+ template <bool check_dynamic_cast=true, typename func_t, typename vec_func_t>
342
+ void cpu_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, int64_t grain_size = at::internal::GRAIN_SIZE) {
343
+ using traits = function_traits<func_t>;
344
+ // this could be extended to work with void return types
345
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
346
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
347
+ // dynamic casting not currently supported on CPU, but some kernels (like Fill)
348
+ // explicitly dynamic_cast, so we give the opt-out of checking.
349
+ if constexpr (check_dynamic_cast) {
350
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
351
+ }
352
+
353
+ iter.for_each(make_vectorized_loop2d(std::forward<func_t>(op), std::forward<vec_func_t>(vop)), grain_size);
354
+ iter.cast_outputs();
355
+ }
356
+
357
+ template <typename func_t>
358
+ void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op, const Range& range) {
359
+ using traits = function_traits<func_t>;
360
+ constexpr bool result_void = std::is_void_v<typename traits::result_type>;
361
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity &&
362
+ ((result_void && iter.noutputs() == 0) || (!result_void && iter.noutputs() == 1)));
363
+ // dynamic casting not currently supported on CPU
364
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
365
+
366
+ iter.serial_for_each([&](char** data, const int64_t* strides, int64_t n) {
367
+ basic_loop(data, strides, 0, n, op);
368
+ }, range);
369
+ iter.cast_outputs();
370
+ }
371
+
372
+ template <typename func_t>
373
+ void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op) {
374
+ cpu_serial_kernel(iter, std::forward<func_t>(op), {0, iter.numel()});
375
+ }
376
+
377
+ template <typename func_t, typename vec_func_t>
378
+ void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, const Range& range) {
379
+ using traits = function_traits<func_t>;
380
+ // this could be extended to work with void return types
381
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
382
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
383
+ // dynamic casting not currently supported on CPU
384
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
385
+
386
+ iter.serial_for_each(make_vectorized_loop2d(std::forward<func_t>(op), std::forward<vec_func_t>(vop)), range);
387
+ iter.cast_outputs();
388
+ }
389
+
390
+ template <typename func_t, typename vec_func_t>
391
+ void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop) {
392
+ cpu_serial_kernel_vec(iter, std::forward<func_t>(op), std::forward<vec_func_t>(vop), {0, iter.numel()});
393
+ }
394
+
395
+ }} // namespace at::native::<anonymous>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/MaxUnpoolKernel.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/DispatchStub.h>
3
+
4
+ namespace at {
5
+ class Tensor;
6
+
7
+ namespace native {
8
+
9
+ using max_unpooling_fn = void(*)(Tensor&, const Tensor&, const Tensor&);
10
+
11
+ DECLARE_DISPATCH(max_unpooling_fn, max_unpool2d_kernel)
12
+ DECLARE_DISPATCH(max_unpooling_fn, max_unpool3d_kernel)
13
+
14
+ }} // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/PixelShuffleKernel.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/DispatchStub.h>
3
+
4
+ namespace at {
5
+ class TensorBase;
6
+ }
7
+
8
+ namespace at::native {
9
+
10
+ using pixel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t);
11
+ DECLARE_DISPATCH(pixel_shuffle_fn, pixel_shuffle_kernel)
12
+ DECLARE_DISPATCH(pixel_shuffle_fn, pixel_unshuffle_kernel)
13
+
14
+ } // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/Reduce.h ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/cpu/Loops.h>
4
+ #include <ATen/Parallel.h>
5
+ #include <c10/util/TypeList.h>
6
+ #include <c10/core/Scalar.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ #include <type_traits>
10
+
11
+ namespace at::native { inline namespace CPU_CAPABILITY {
12
+
13
+ using namespace vec;
14
+
15
+ #define VEC_LOOP_HEADER(func_t, data) \
16
+ using scalar_t = typename function_traits<func_t>::result_type; \
17
+ using Vec = Vectorized<scalar_t>; \
18
+ char* out_ptr = data[0]; \
19
+ (void) out_ptr;
20
+
21
+ // reduction that is contiguous over the input in dim 0
22
+ template <typename traits>
23
+ inline bool is_contiguous_reduction(const int64_t* strides) {
24
+ return strides[0] == 0 &&
25
+ strides[1] == sizeof(typename traits::arg2_t);
26
+ }
27
+
28
+ // reduction that is contiguous over the input in dim 1
29
+ template <typename traits>
30
+ inline bool is_outer_reduction(const int64_t* strides) {
31
+ return strides[0] == 0 &&
32
+ strides[2] == sizeof(typename traits::result_type) &&
33
+ strides[3] == sizeof(typename traits::arg2_t);
34
+ }
35
+
36
+ template <typename func_t, typename vec_func_t>
37
+ inline void vectorized_reduction(char** data, int64_t n, int64_t stride,
38
+ func_t op, vec_func_t vop, bool reduce) {
39
+ VEC_LOOP_HEADER(func_t, data)
40
+ const char* in1_ptr = data[1];
41
+ Vec acc[4];
42
+ for (const auto j : c10::irange(4)) {
43
+ acc[j] = Vec::loadu(in1_ptr + j * Vec::size() * sizeof(scalar_t));
44
+ }
45
+ for (const auto i : c10::irange(1, n)) {
46
+ const char* ptr = in1_ptr + stride * i;
47
+ acc[0] = vop(acc[0], Vec::loadu(ptr + (0 * Vec::size() * sizeof(scalar_t))));
48
+ acc[1] = vop(acc[1], Vec::loadu(ptr + (1 * Vec::size() * sizeof(scalar_t))));
49
+ acc[2] = vop(acc[2], Vec::loadu(ptr + (2 * Vec::size() * sizeof(scalar_t))));
50
+ acc[3] = vop(acc[3], Vec::loadu(ptr + (3 * Vec::size() * sizeof(scalar_t))));
51
+ }
52
+ if (reduce) {
53
+ scalar_t buffer[Vec::size()];
54
+ acc[0] = vop(vop(acc[0], acc[1]), vop(acc[2], acc[3]));
55
+ acc[0].store(buffer);
56
+ for (const auto j : c10::irange(1, Vec::size())) {
57
+ buffer[0] = op(buffer[0], buffer[j]);
58
+ }
59
+ auto dst = (scalar_t*)out_ptr;
60
+ *dst = op(*dst, buffer[0]);
61
+ } else {
62
+ for (const auto j : c10::irange(4)) {
63
+ auto dst = out_ptr + j * Vec::size() * sizeof(scalar_t);
64
+ acc[j] = vop(acc[j], Vec::loadu(dst));
65
+ acc[j].store(dst);
66
+ }
67
+ }
68
+ }
69
+
70
+ template <typename F>
71
+ inline void UNARY_OUTER_LOOP(char* data[2], const int64_t strides[2], int64_t n, F f) {
72
+ for ([[maybe_unused]] const auto j : c10::irange(n)) {
73
+ f();
74
+ data[0] += strides[0];
75
+ data[1] += strides[1];
76
+ }
77
+ }
78
+
79
+ // computes the reduction out = op(out, in)
80
+ template <typename func_t, typename vec_func_t>
81
+ inline void vectorized_inner_reduction(char** data, int64_t n, func_t op, vec_func_t vop) {
82
+ VEC_LOOP_HEADER(func_t, data)
83
+ constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t);
84
+ int64_t count = n / (4 * Vec::size());
85
+ if (count > 0) {
86
+ vectorized_reduction(data, count, vector_stride, op, vop, /*reduce=*/true);
87
+ }
88
+ char* ptrs[3] = { data[0], data[0], data[1] };
89
+ int64_t strides[] = { 0, 0, sizeof(scalar_t) };
90
+ basic_loop(ptrs, strides, count * 4 * Vec::size(), n, op);
91
+ }
92
+
93
+ // computes the reduction out = op(out, in)
94
+ template <typename func_t, typename vec_func_t>
95
+ inline void vectorized_outer_reduction(char** data, int64_t inner_stride, int64_t size0, int64_t size1, func_t op, vec_func_t vop) {
96
+ VEC_LOOP_HEADER(func_t, data)
97
+
98
+ // reduce down each column of 4 * Vec::size() elements.
99
+ constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t);
100
+ int64_t outer_stride[2] = { vector_stride, vector_stride };
101
+ UNARY_OUTER_LOOP(data, outer_stride, size1 / (4 * Vec::size()), [&] {
102
+ vectorized_reduction(data, size0, inner_stride, op, vop, /*reduce=*/false);
103
+ });
104
+
105
+ // reduce down the remaining columns
106
+ int64_t step[] = { sizeof(scalar_t), sizeof(scalar_t) };
107
+ int64_t remaining = size1 % (4 * Vec::size());
108
+ UNARY_OUTER_LOOP(data, step, remaining, [&] {
109
+ char* ptrs[3] = { data[0], data[0], data[1] };
110
+ int64_t strides[] = { 0, 0, inner_stride };
111
+ basic_loop(ptrs, strides, 0, size0, op);
112
+ });
113
+ }
114
+
115
+ template<typename traits, typename res_t>
116
+ static void set_result(const int index, const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
117
+ // static_assert(std::is_same_v<res_t, typename traits::arg2_t>, "data types must match");
118
+ if (index < num_outputs) {
119
+ char *out = (char *) iter.data_ptr(index);
120
+ *(res_t *) out = result;
121
+ }
122
+ }
123
+
124
+ template<typename traits, typename res_t>
125
+ static void set_results(const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
126
+ AT_ASSERT(num_outputs == 1);
127
+ set_result<traits>(0, result, iter, num_outputs);
128
+ }
129
+
130
+ template<typename traits, std::size_t i = 0, typename... tuple_t>
131
+ inline std::enable_if_t<i == sizeof...(tuple_t), std::size_t>
132
+ for_each_in_tuple(const std::tuple<tuple_t...>& /*t*/, const TensorIteratorBase& /*iter*/, const int /*num_outputs*/) {
133
+ return i;
134
+ }
135
+
136
+ template<typename traits, std::size_t i = 0, typename... tuple_t>
137
+ inline std::enable_if_t<i < sizeof...(tuple_t), std::size_t>
138
+ for_each_in_tuple(const std::tuple<tuple_t...>& t, const TensorIteratorBase &iter, const int num_outputs) {
139
+ if (i < (size_t)num_outputs) {
140
+ set_result<traits>(i, std::get<i>(t), iter, num_outputs);
141
+ return for_each_in_tuple<traits, i + 1, tuple_t...>(t, iter, num_outputs);
142
+ }
143
+ return i;
144
+ }
145
+
146
+ template<typename traits, typename... res_t>
147
+ static void set_results(const std::tuple<res_t...>& result, const TensorIteratorBase &iter, const int num_outputs) {
148
+ AT_ASSERT(num_outputs >= 1);
149
+ std::size_t result_size = for_each_in_tuple<traits>(result, iter, num_outputs);
150
+ AT_ASSERT((size_t)num_outputs == result_size);
151
+ }
152
+
153
+ template <typename T, typename... Args>
154
+ struct all_same : std::conjunction<
155
+ std::is_same<T, Args>...
156
+ > {};
157
+
158
+ // data_t is the input/output data type.
159
+ // acc_t is a type that contains all the necessary data
160
+ // to continue reducing.
161
+ // index_t is a one-dimensional index
162
+ //
163
+ // ops_t is such that &ops_t::reduce, &ops_t::combine, and &ops_t::project exist and satisfy
164
+ // the following.
165
+ // reduce: (acc_t, data_t, index_t) -> acc_t adds one data point to the accumulated value.
166
+ // combine: (acc_t, acc_t) -> acc_t combines two accumulated values into one.
167
+ // project: acc_t -> out_t finishes the reduction, getting the required output.
168
+ //
169
+ // Additionally, acc_t must be default-constructible:
170
+ // acc_t {} is an identity for combine,
171
+ // and project(acc_t {}) is the value of the operation on zero elements.
172
+ //
173
+ // The point of `combine` is to support parallelization -
174
+ // the idea is to one sequence of `reduce` calls per thread of execution,
175
+ // and then to combine them at the end with `combine`.
176
+ //
177
+ // If there is more than one output element,
178
+ // our parallelization strategy is to use one thread for each of them,
179
+ // which means that `combine` will never be called.
180
+ //
181
+ // If, on the other hand, there is only one, then we split the input into
182
+ // into several pieces, reduce each separately, and then combine them.
183
+
184
+ template <typename ops_t, typename init_t>
185
+ void binary_kernel_reduce(TensorIteratorBase& iter, ops_t ops, init_t init) {
186
+ using rf_t = decltype(&ops_t::reduce);
187
+ using cf_t = decltype(&ops_t::combine);
188
+ using pf_t = decltype(&ops_t::project);
189
+ using r_traits = binary_function_traits<rf_t>;
190
+ using c_traits = binary_function_traits<cf_t>;
191
+ using p_traits = unary_function_traits<pf_t>;
192
+ using acc_t = typename p_traits::arg1_t;
193
+ using data_t = typename r_traits::arg2_t;
194
+ static_assert(
195
+ all_same<
196
+ acc_t,
197
+ init_t,
198
+ typename r_traits::arg1_t,
199
+ typename r_traits::result_type,
200
+ typename c_traits::arg1_t,
201
+ typename c_traits::arg2_t,
202
+ typename c_traits::result_type>::value,
203
+ "all accumulate types must match");
204
+ static_assert(
205
+ std::is_default_constructible_v<acc_t>,
206
+ "the accumulate type must be default-constructible"
207
+ );
208
+ const int num_outputs = iter.noutputs();
209
+ iter.foreach_reduced_elt([&ops, &init, num_outputs](TensorIteratorBase &sub_iter) {
210
+ auto reduction_body = [&ops, &sub_iter, num_outputs](acc_t acc, int64_t begin, int64_t end) -> acc_t {
211
+ int ntensors = sub_iter.ntensors();
212
+ sub_iter.serial_for_each([&acc, &ops, num_outputs, ntensors, begin](char** data, const int64_t* strides, int64_t size) {
213
+ AT_ASSERT(ntensors - num_outputs == 1);
214
+ char *in = data[ntensors - 1];
215
+ int64_t stride = strides[ntensors - 1];
216
+ for (const auto i : c10::irange(size)) {
217
+ acc = ops.reduce(acc, c10::load<data_t>(in), begin + i);
218
+ in += stride;
219
+ }
220
+ }, {begin, end});
221
+ return ops.translate_idx(acc, sub_iter.view_offsets()[0]);
222
+ };
223
+ acc_t total_acc = init;
224
+ auto numel = sub_iter.numel();
225
+ if (numel < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 ||
226
+ at::in_parallel_region()) {
227
+ total_acc = reduction_body(total_acc, 0, numel);
228
+ } else {
229
+ int max_threads = at::get_num_threads();
230
+ AT_ASSERT(max_threads > 0);
231
+ static_assert(
232
+ !std::is_same_v<acc_t, bool>,
233
+ "Concurrently modifying different references into std::vector<bool> is UB."
234
+ );
235
+ std::vector<acc_t> buffer((unsigned)max_threads, init);
236
+ at::parallel_for(0, numel, internal::GRAIN_SIZE,
237
+ [&](int64_t begin, int64_t end) {
238
+ auto& acc = buffer[at::get_thread_num()];
239
+ acc = reduction_body(acc, begin, end);
240
+ }
241
+ );
242
+ for (const auto i : c10::irange(max_threads)) {
243
+ total_acc = ops.combine(total_acc, buffer[i]);
244
+ }
245
+ }
246
+ set_results<r_traits>(ops.project(total_acc), sub_iter, num_outputs);
247
+ });
248
+ }
249
+
250
+ template <typename func_t, typename vec_func_t>
251
+ void binary_kernel_reduce_vec(TensorIteratorBase& iter, func_t op, vec_func_t vop, double ident = 0) {
252
+ using traits = binary_function_traits<func_t>;
253
+ static_assert(
254
+ all_same<
255
+ typename traits::result_type,
256
+ typename traits::arg1_t,
257
+ typename traits::arg2_t>::value,
258
+ "all types must match");
259
+
260
+ iter.output_base().fill_(ident);
261
+ iter.parallel_reduce([&](char** data, const int64_t* strides, int64_t size0, int64_t size1) {
262
+ int64_t outer_strides[] = { strides[2], strides[3] };
263
+ if (is_contiguous_reduction<traits>(strides)) {
264
+ // input is contiguous in dim 0, output is reduced in dim 0
265
+ UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
266
+ vectorized_inner_reduction(data, size0, op, vop);
267
+ });
268
+ } else if (is_outer_reduction<traits>(strides)) {
269
+ // input and output are contiguous in dim 1
270
+ int64_t inner_stride = strides[1]; // stride of input in dim 0
271
+ vectorized_outer_reduction(data, inner_stride, size0, size1, op, vop);
272
+ } else {
273
+ UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
274
+ char* ptrs[3] = { data[0], data[0], data[1] };
275
+ int64_t inner_strides[3] = { strides[0], strides[0], strides[1] };
276
+ basic_loop(ptrs, inner_strides, 0, size0, op);
277
+ });
278
+ }
279
+ });
280
+ }
281
+
282
+ // when reduction is on most inner dimension (dim 0 in TensorIterator)
283
+ // and input has contiguous most inner dimension, `binary_kernel_reduce_lastdim`
284
+ // can be used.
285
+ inline bool is_reduce_lastdim(TensorIteratorBase& iter) {
286
+ return iter.num_reduce_dims() == 1 && iter.is_dim_reduced(0)
287
+ && iter.ninputs() == 1 && iter.strides(1)[0] == iter.element_size(1);
288
+ }
289
+
290
+ template <typename reduce_func_t>
291
+ void binary_kernel_reduce_lastdim(TensorIteratorBase& iter, reduce_func_t reduce_op) {
292
+ auto shape = iter.shape();
293
+ int64_t dim_size = shape[0];
294
+ int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / dim_size);
295
+ TensorIterator sub_iter(iter);
296
+ // create sub iterator to parallel on all non-reduce-dims
297
+ sub_iter.narrow(0, 0, 1);
298
+ auto loop = [&](char** data, const int64_t* strides, int64_t size) {
299
+ char* out = data[0];
300
+ char* in = data[1];
301
+ for (int64_t i = 0; i < size; ++i) {
302
+ reduce_op(out, in, dim_size);
303
+ out += strides[0];
304
+ in += strides[1];
305
+ }
306
+ };
307
+ sub_iter.for_each(loop, grain_size);
308
+ }
309
+
310
+ }} // namespace at::native::<anonymous>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ReduceUtils.h ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Parallel.h>
4
+ #include <ATen/NumericUtils.h>
5
+ #include <ATen/cpu/vec/vec.h>
6
+ #include <ATen/cpu/vec/functional.h>
7
+ #include <ATen/native/ReductionType.h>
8
+ #include <c10/util/irange.h>
9
+ #include <ATen/OpMathType.h>
10
+ #include <ATen/native/cpu/utils.h>
11
+ #include <ATen/OpMathType.h>
12
+
13
+ namespace at::native {
14
+ inline namespace CPU_CAPABILITY {
15
+
16
+ using namespace vec;
17
+
18
+ #define AT_DISPATCH_REDUCTION_TYPES(op, ...) \
19
+ [&] { \
20
+ switch (op) { \
21
+ case ReductionType::SUM: { \
22
+ static constexpr auto reduce = ReductionType::SUM; \
23
+ return __VA_ARGS__(); \
24
+ } \
25
+ case ReductionType::MEAN: { \
26
+ static constexpr auto reduce = ReductionType::MEAN; \
27
+ return __VA_ARGS__(); \
28
+ } \
29
+ case ReductionType::MIN: { \
30
+ static constexpr auto reduce = ReductionType::MIN; \
31
+ return __VA_ARGS__(); \
32
+ } \
33
+ case ReductionType::MAX: { \
34
+ static constexpr auto reduce = ReductionType::MAX; \
35
+ return __VA_ARGS__(); \
36
+ } \
37
+ case ReductionType::PROD: { \
38
+ static constexpr auto reduce = ReductionType::PROD; \
39
+ return __VA_ARGS__(); \
40
+ } \
41
+ } \
42
+ }()
43
+
44
+ template <typename scalar_t, ReductionType reduce>
45
+ inline vec_scalar_t<scalar_t> init_value() {
46
+ using acc_t = vec_scalar_t<scalar_t>;
47
+ acc_t val;
48
+ if (reduce == ReductionType::SUM ||
49
+ reduce == ReductionType::MEAN) {
50
+ val = static_cast<acc_t>(0);
51
+ } else if (reduce == ReductionType::PROD) {
52
+ val = static_cast<acc_t>(1);
53
+ } else if (reduce == ReductionType::MAX) {
54
+ val = -std::numeric_limits<acc_t>::infinity();
55
+ } else {
56
+ TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN);
57
+ val = std::numeric_limits<acc_t>::infinity();
58
+ }
59
+ return val;
60
+ }
61
+
62
+ template <typename scalar_t, ReductionType reduce>
63
+ inline vec_scalar_t<scalar_t> init_value(const std::optional<Scalar>& initial) {
64
+ using acc_t = vec_scalar_t<scalar_t>;
65
+ if (initial.has_value()) {
66
+ return initial.value().to<acc_t>();
67
+ } else {
68
+ return init_value<scalar_t, reduce>();
69
+ }
70
+ }
71
+
72
+ template <typename scalar_t>
73
+ inline void init(scalar_t* out, int64_t size, const vec_scalar_t<scalar_t>& val) {
74
+ using Vec = Vectorized<vec_scalar_t<scalar_t>>;
75
+ map<scalar_t>(
76
+ [val](Vec x) { return Vec(val); },
77
+ out,
78
+ out,
79
+ size);
80
+ }
81
+
82
+ template <typename scalar_t, ReductionType reduce>
83
+ inline void init(scalar_t* out, int64_t size, const std::optional<Scalar>& initial) {
84
+ using acc_t = vec_scalar_t<scalar_t>;
85
+ acc_t val = init_value<scalar_t, reduce>(initial);
86
+ init(out, size, val);
87
+ }
88
+
89
+ // overload with `include_self`, used by scatter_reduce
90
+ template <typename scalar_t, ReductionType reduce>
91
+ inline void init(scalar_t* out, int64_t size, bool include_self = false) {
92
+ using acc_t = vec_scalar_t<scalar_t>;
93
+ if (!include_self) {
94
+ acc_t val = init_value<scalar_t, reduce>();
95
+ init(out, size, val);
96
+ }
97
+ }
98
+
99
+ template <typename scalar_t, ReductionType reduce>
100
+ inline void _init(scalar_t* self_ptr, at::opmath_type<scalar_t>* buffer_ptr, int64_t size, bool include_self) {
101
+ if (!include_self) {
102
+ init<at::opmath_type<scalar_t>, reduce>(buffer_ptr, size, include_self);
103
+ } else {
104
+ vec::convert(self_ptr, buffer_ptr, size);
105
+ }
106
+ }
107
+
108
+ template <typename scalar_t>
109
+ inline std::enable_if_t<!std::is_same_v<scalar_t, Vec2>, scalar_t>
110
+ _max(const scalar_t& x, const scalar_t& y) {
111
+ return at::_isnan(y) ? y : std::max(x, y);
112
+ }
113
+
114
+ template <typename scalar_t>
115
+ inline Vectorized<scalar_t> _max(const Vectorized<scalar_t>& x, const Vectorized<scalar_t>& y) {
116
+ // vec::maximum propagates NaN
117
+ return vec::maximum(x, y);
118
+ }
119
+
120
+ template <typename vec_t>
121
+ inline std::enable_if_t<std::is_same_v<vec_t, Vec2>, Vec2>
122
+ _max(const vec_t& x, const vec_t& y) {
123
+ // vec::maximum propagates NaN
124
+ return maximum(x, y);
125
+ }
126
+
127
+ template <typename scalar_t>
128
+ inline std::enable_if_t<!std::is_same_v<scalar_t, Vec2>, scalar_t>
129
+ _min(const scalar_t& x, const scalar_t& y) {
130
+ return at::_isnan(y) ? y : std::min(x, y);
131
+ }
132
+
133
+ template <typename scalar_t>
134
+ inline Vectorized<scalar_t> _min(const Vectorized<scalar_t>& x, const Vectorized<scalar_t>& y) {
135
+ // vec::minimum propagates NaN
136
+ return vec::minimum(x, y);
137
+ }
138
+
139
+ template <typename vec_t>
140
+ inline std::enable_if_t<std::is_same_v<vec_t, Vec2>, Vec2>
141
+ _min(const vec_t& x, const vec_t& y) {
142
+ // vec::minimum propagates NaN
143
+ return minimum(x, y);
144
+ }
145
+
146
+ template <typename scalar_t, typename accumut, typename Op,
147
+ typename std::enable_if_t<is_reduced_floating_point_v<scalar_t>, int> = 0>
148
+ inline void map_acc(
149
+ const Op& vec_fun,
150
+ accumut* output_data,
151
+ const accumut* input_data,
152
+ const scalar_t* input_data2,
153
+ int64_t size) {
154
+ using Vec = vec::Vectorized<scalar_t>;
155
+ using aVec = vec::Vectorized<accumut>;
156
+ int64_t d = 0;
157
+ constexpr int64_t kVecSize = Vec::size();
158
+ constexpr int64_t kaVecSize = aVec::size();
159
+ for (d = 0; d < size - (size % kVecSize); d += kVecSize) {
160
+ Vec data2_vec = Vec::loadu(input_data2 + d);
161
+ auto [data2_avec0, data2_avec1] = convert_to_float<scalar_t>(data2_vec);
162
+ aVec input_vec0 = aVec::loadu(input_data + d);
163
+ aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize);
164
+ vec_fun(input_vec0, data2_avec0).store(output_data + d);
165
+ vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize);
166
+ }
167
+ if (size - d > 0) {
168
+ int64_t tail_size = size - d;
169
+ Vec data2_vec = Vec::loadu(input_data2 + d, tail_size);
170
+ auto [data2_avec0, data2_avec1] = convert_to_float<scalar_t>(data2_vec);
171
+ if (tail_size > kaVecSize) {
172
+ aVec input_vec0 = aVec::loadu(input_data + d);
173
+ aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize, tail_size - kaVecSize);
174
+ vec_fun(input_vec0, data2_avec0).store(output_data + d);
175
+ vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize, tail_size - kaVecSize);
176
+ } else {
177
+ aVec input_vec0 = aVec::loadu(input_data + d, tail_size);
178
+ vec_fun(input_vec0, data2_avec0).store(output_data + d, tail_size);
179
+ }
180
+ }
181
+ }
182
+
183
+ // for Max and Min, propagate NaN:
184
+ template <typename T, ReductionType reduce>
185
+ inline T update(const T& x, const T& y) {
186
+ if (reduce == ReductionType::SUM ||
187
+ reduce == ReductionType::MEAN) {
188
+ return x + y;
189
+ } else if (reduce == ReductionType::PROD) {
190
+ return x * y;
191
+ } else if (reduce == ReductionType::MAX) {
192
+ return _max(x, y);
193
+ } else {
194
+ TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN);
195
+ return _min(x, y);
196
+ }
197
+ }
198
+
199
+ template <typename scalar_t, ReductionType reduce>
200
+ inline void update(scalar_t* out, const scalar_t* data, int64_t K) {
201
+ using Vec = vec::Vectorized<vec_scalar_t<scalar_t>>;
202
+ map2<scalar_t>(
203
+ [](Vec x, Vec y) { return update<Vec, reduce>(x, y); },
204
+ out,
205
+ out,
206
+ data,
207
+ K);
208
+ }
209
+
210
+ template <typename scalar_t, ReductionType reduce,
211
+ typename std::enable_if_t<is_reduced_floating_point_v<scalar_t>, int> = 0>
212
+ inline void update(at::opmath_type<scalar_t>* out, const scalar_t* data, int64_t K) {
213
+ using opmath_t = at::opmath_type<scalar_t>;
214
+ using Vec = vec::Vectorized<opmath_t>;
215
+ map_acc<scalar_t, opmath_t>(
216
+ [](Vec x, Vec y) { return update<Vec, reduce>(x, y); },
217
+ out,
218
+ out,
219
+ data,
220
+ K);
221
+ }
222
+
223
+ template <typename scalar_t, ReductionType reduce>
224
+ inline void write(scalar_t* out, int64_t count, int64_t K) {
225
+ using Vec = vec::Vectorized<vec_scalar_t<scalar_t>>;
226
+ if (reduce == ReductionType::MEAN) {
227
+ if (count > 0) {
228
+ vec::map<scalar_t>(
229
+ [count](Vec x) { return x / Vec(count); },
230
+ out,
231
+ out,
232
+ K);
233
+ }
234
+ }
235
+ }
236
+
237
+ } // namespace CPU_CAPABILITY
238
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/BFloat16.h>
6
+ #include <c10/util/Half.h>
7
+
8
+ namespace at::native {
9
+ #if !defined(C10_MOBILE)
10
+ using fp16_gemv_fn = void(*)(int, int, float, const Half*, int, const Half*, int, float, Half*, int);
11
+ DECLARE_DISPATCH(fp16_gemv_fn, fp16_gemv_trans_stub)
12
+
13
+ using bf16_gemv_fn = void(*)(int, int, BFloat16, const BFloat16*, int, const BFloat16*, int, BFloat16, BFloat16*, int);
14
+ DECLARE_DISPATCH(bf16_gemv_fn, bf16_gemv_trans_stub)
15
+
16
+ inline namespace CPU_CAPABILITY {
17
+ float fp16_dot_with_fp32_arith(const Half* vec1, const Half* vec2, int64_t len);
18
+ float bf16_dot_with_fp32_arith(const BFloat16* vec1, const BFloat16* vec2, int64_t len);
19
+ } // inline namespace CPU_CAPABILITY
20
+ #endif // !defined(C10_MOBILE)
21
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SampledAddmmKernel.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace at::native {
7
+
8
+ using sampled_addmm_sparse_csr_fn = void(*)(const Tensor&, const Tensor&, const Scalar&, const Scalar&, const Tensor&);
9
+
10
+ DECLARE_DISPATCH(sampled_addmm_sparse_csr_fn, sampled_addmm_sparse_csr_stub)
11
+
12
+ } // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SerialStackImpl.h ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2004-present Facebook. All Rights Reserved.
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+
6
+ #include <ATen/MemoryOverlap.h>
7
+ #include <ATen/Parallel.h>
8
+ #include <ATen/TensorIterator.h>
9
+ #include <ATen/cpu/vec/functional.h>
10
+ #include <ATen/cpu/vec/vec.h>
11
+ #include <c10/util/irange.h>
12
+
13
+ namespace at::native::detail {
14
+
15
+ struct InputMeta {
16
+ void* data_ptr;
17
+ int64_t inner_size;
18
+
19
+ InputMeta(const Tensor& t, int64_t dim, int64_t inner)
20
+ : data_ptr(t.data_ptr()), inner_size(t.sizes()[dim] * inner) {}
21
+ };
22
+
23
+ // This kernel is used by two TensorList types:
24
+ // 1. stack_serial_kernel uses at::ArrayRef<Tensor>
25
+ // 2. Static runtime calls this kernel directly (csrc/jit/runtime/static/ops.cpp) with
26
+ // ProcessedNodeInputWrapper.
27
+ // When making changes, make sure that they are compatible with both types!
28
+ template <typename scalar_t, typename TensorListType>
29
+ void stack_serial_kernel_impl(Tensor& result, TensorListType tensors, int64_t dim) {
30
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
31
+ dim >= 0 && dim <= result.dim(),
32
+ "dim out of range in stack_serial_kernel_impl");
33
+ int64_t outer =
34
+ result.numel() / (result.sizes()[dim] * result.strides()[dim]);
35
+ scalar_t* result_data = result.data_ptr<scalar_t>();
36
+ int64_t ninputs = tensors.size();
37
+ std::vector<InputMeta> inputs;
38
+ inputs.reserve(ninputs);
39
+ for (const auto& tensor : tensors) {
40
+ inputs.emplace_back(tensor, dim, tensor.strides()[dim]);
41
+ }
42
+
43
+ using Vec = vec::Vectorized<scalar_t>;
44
+ scalar_t* result_ptr = result_data;
45
+ for (const auto i : c10::irange(outer)) {
46
+ for (const auto j : c10::irange(ninputs)) {
47
+ int64_t local_inner = inputs[j].inner_size;
48
+ scalar_t* input_ptr = (scalar_t*)(inputs[j].data_ptr) + i * local_inner;
49
+
50
+ if (local_inner < Vec::size()) {
51
+ for (const auto k : c10::irange(local_inner)) {
52
+ result_ptr[k] = input_ptr[k];
53
+ }
54
+ } else {
55
+ vec::map(
56
+ [](Vec x) { return x; }, result_ptr, input_ptr, local_inner);
57
+ }
58
+ result_ptr += local_inner;
59
+ }
60
+ }
61
+ }
62
+
63
+ // Checks to see whether native stack can be invoked under these conditions:
64
+ // - result and input tensors are contiguous
65
+ // - only one thread is used
66
+ // - no type promotion has to occur
67
+ // - tensors dtype is Double or Float
68
+ template <typename TensorListType>
69
+ bool can_use_native_serial_stack_impl(Tensor& result, TensorListType tensors, int64_t dim) {
70
+ TORCH_CHECK(tensors.size() > 0, "expected a non-empty list of Tensors");
71
+ const Tensor& first_tensor = tensors[0];
72
+ // stack dimension should be in range [0,firstTensor.dim())
73
+ // dim == firstTensor.dim() is a valid input, but it is handled by default code path
74
+ // that uses unsqueeze
75
+ if (dim >= first_tensor.dim()) return false;
76
+ // Native stack doesn't apply any tensor is skipped.
77
+ if (first_tensor.numel() == 0 && first_tensor.dim() == 1) return false;
78
+ // there should be no type promotion
79
+ if (result.dtype() != first_tensor.dtype()) return false;
80
+
81
+ auto first_tensor_mem_format = first_tensor.suggest_memory_format();
82
+ ScalarType dtype = first_tensor.scalar_type();
83
+
84
+ if (!result.is_contiguous(first_tensor_mem_format)) {
85
+ return false;
86
+ }
87
+
88
+ // fast path only works for Double and Float
89
+ if (dtype != ScalarType::Double && dtype != ScalarType::Float) {
90
+ return false;
91
+ }
92
+
93
+ // check remainder of inputs
94
+ #ifndef STRIP_ERROR_MESSAGES
95
+ auto const &first_tensor_shape = first_tensor.sizes();
96
+ #endif
97
+ for (const auto i : c10::irange(1, tensors.size())) {
98
+ auto const &tensor = tensors[i];
99
+ TORCH_CHECK(tensors[i].sizes() == first_tensor.sizes(),
100
+ "stack expects each tensor to be equal size, but got ", first_tensor_shape,
101
+ " at entry 0 and ", tensor.sizes(), " at entry ", i);
102
+
103
+ // every tensor must be contiguous
104
+ // tensor sizes and strides must be the same
105
+ // there should be no type promotion
106
+ if (!tensor.is_contiguous(first_tensor_mem_format) ||
107
+ tensor.strides() != first_tensor.strides() ||
108
+ tensor.dtype() != dtype) {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ // fast native stack should only be used when it is not worth using multiple threads
114
+ // or there is only one thread. Note that we aren't checking result.numel() here because
115
+ // it may not have been resized and we want to defer that cost till later.
116
+ int64_t numel_in_stack = first_tensor.numel() * tensors.size();
117
+ return numel_in_stack < at::internal::GRAIN_SIZE || at::get_num_threads() == 1;
118
+ }
119
+
120
+ template <typename TensorListType, bool should_skip_overlap_check>
121
+ struct CanUseNativeSerialStack;
122
+
123
+ template <typename TensorListType>
124
+ struct CanUseNativeSerialStack<TensorListType, false> {
125
+ static bool call(Tensor& result, TensorListType tensors, int64_t dim) {
126
+ // Inputs cannot alias the output tensor
127
+ for (const auto i : c10::irange(tensors.size())) {
128
+ auto lap = at::get_overlap_status(result, tensors[i]);
129
+ TORCH_CHECK(lap != at::MemOverlapStatus::Partial &&
130
+ lap != at::MemOverlapStatus::Full, 0,
131
+ "unsupported operation: the input tensors cannot refer to any of the "
132
+ "output memory locations. Found overlap in input tensor ", i);
133
+ }
134
+
135
+ return can_use_native_serial_stack_impl(result, tensors, dim);
136
+ }
137
+ };
138
+
139
+ template <typename TensorListType>
140
+ struct CanUseNativeSerialStack<TensorListType, true> {
141
+ static bool call(Tensor& result, TensorListType tensors, int64_t dim) {
142
+ return can_use_native_serial_stack_impl(result, tensors, dim);
143
+ }
144
+ };
145
+
146
+ } // namespace at::native::detail
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SoftmaxKernel.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ class Tensor;
8
+
9
+ namespace native {
10
+
11
+ using forward_fn = void (*)(const Tensor&, const Tensor&);
12
+ using backward_fn = void(*)(const Tensor &, const Tensor &, const Tensor&);
13
+
14
+ DECLARE_DISPATCH(forward_fn, softmax_lastdim_kernel)
15
+ DECLARE_DISPATCH(forward_fn, log_softmax_lastdim_kernel)
16
+ DECLARE_DISPATCH(backward_fn, softmax_backward_lastdim_kernel)
17
+ DECLARE_DISPATCH(backward_fn, log_softmax_backward_lastdim_kernel)
18
+
19
+ using forward_fn_with_dim = void(*)(const Tensor &, const Tensor &, const int64_t);
20
+ using backward_fn_with_dim =
21
+ void (*)(const Tensor&, const Tensor&, const Tensor&, const int64_t);
22
+
23
+ DECLARE_DISPATCH(forward_fn_with_dim, softmax_kernel)
24
+ DECLARE_DISPATCH(forward_fn_with_dim, log_softmax_kernel)
25
+ DECLARE_DISPATCH(backward_fn_with_dim, softmax_backward_kernel)
26
+ DECLARE_DISPATCH(backward_fn_with_dim, log_softmax_backward_kernel)
27
+ }
28
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/SpmmReduceKernel.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/native/ReductionType.h>
6
+
7
+ namespace at::native {
8
+
9
+ using spmm_reduce_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
10
+ using spmm_reduce_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
11
+ using spmm_reduce_backward_input_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
12
+ using spmm_reduce_backward_input_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
13
+ using spmm_reduce_backward_other_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
14
+
15
+ DECLARE_DISPATCH(spmm_reduce_fn, spmm_reduce_stub)
16
+ DECLARE_DISPATCH(spmm_reduce_arg_fn, spmm_reduce_arg_stub)
17
+ DECLARE_DISPATCH(spmm_reduce_backward_input_fn, spmm_reduce_backward_input_stub)
18
+ DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_input_arg_stub)
19
+ DECLARE_DISPATCH(spmm_reduce_backward_other_fn, spmm_reduce_backward_other_stub)
20
+ DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_other_arg_stub)
21
+
22
+ } // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/StackKernel.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2004-present Facebook. All Rights Reserved.
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ using stack_serial_fn = void(*)(Tensor &, TensorList, int64_t);
10
+ DECLARE_DISPATCH(stack_serial_fn, stack_serial_stub)
11
+
12
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/UpSampleKernelAVXAntialias.h ADDED
@@ -0,0 +1,1376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ The Python Imaging Library (PIL) is
3
+
4
+ Copyright © 1997-2011 by Secret Labs AB
5
+ Copyright © 1995-2011 by Fredrik Lundh
6
+
7
+ Pillow is the friendly PIL fork. It is
8
+
9
+ Copyright © 2010-2022 by Alex Clark and contributors
10
+
11
+ Like PIL, Pillow is licensed under the open source HPND License
12
+ */
13
+
14
+ // This code is heavily inspired from PILLOW-SIMD's implementation:
15
+ // https://github.com/uploadcare/pillow-simd/blob/simd/master/src/libImaging/Resample.c
16
+
17
+ #pragma once
18
+ #ifdef CPU_CAPABILITY_AVX2
19
+ // TODO: This file only supports AVX2. We could split the AVX kernels into
20
+ // smaller logical blocks in order to port them into the Vec.h logic. This would
21
+ // allow to support other vectorization architectures and perhaps also support
22
+ // the non-vectorized fallback (we'd need to make sure it's not slower than the
23
+ // current fallback).
24
+
25
+ #include <ATen/core/Tensor.h>
26
+ #include <ATen/cpu/vec/intrinsics.h>
27
+ #include <c10/util/irange.h>
28
+
29
+ #ifndef AT_PER_OPERATOR_HEADERS
30
+ #include <ATen/Functions.h>
31
+ #else
32
+ #include <ATen/ops/empty.h>
33
+ #endif
34
+
35
+
36
+ namespace {
37
+
38
+ static inline __m128i mm_cvtsi32_si128(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) {
39
+ int32_t v;
40
+ if (i32_aligned) {
41
+ v = *(const int32_t*)ptr;
42
+ } else {
43
+ std::memcpy(&v, ptr, 4);
44
+ }
45
+ return _mm_cvtsi32_si128(v);
46
+ }
47
+
48
+ static inline __m128i mm_cvtepu8_epi32(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) {
49
+ return _mm_cvtepu8_epi32(mm_cvtsi32_si128(ptr, i32_aligned));
50
+ }
51
+
52
+ static inline void _write_endline_rgb_as_uint32(
53
+ uint8_t* C10_RESTRICT output,
54
+ uint32_t data
55
+ ) {
56
+ // data is (R G B X), output is (X1 X2 X3 | R1 B1 G1 R2 ...)
57
+ // Here we explicitly set X as R1
58
+ uint8_t* data_ptr = reinterpret_cast<uint8_t*>(&data);
59
+ data_ptr[3] = output[3];
60
+ std::memcpy(output, data_ptr, 4);
61
+ }
62
+
63
+ at::Tensor unpack_rgb(const at::Tensor& packed_tensor) {
64
+ // Convert a "packed" tensor (typically RGBRGBRGB if channels_last) into
65
+ // RGBARGBARGBA format where A is hard-coded to 0. Each pixel is encoded
66
+ // into as 32 bits. This generalizes to num_channels <= 4 and also works for
67
+ // non-channels_last tensors.
68
+
69
+ const uint8_t* packed = (const uint8_t*)packed_tensor.const_data_ptr<uint8_t>();
70
+ auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2);
71
+ auto num_channels = packed_tensor.size(0);
72
+
73
+ constexpr int rgba_size = 4;
74
+ auto unpacked_tensor = at::empty({rgba_size, packed_tensor.size(1), packed_tensor.size(2)}, at::CPU(at::kByte));
75
+ uint8_t* unpacked = (uint8_t*) unpacked_tensor.data_ptr<uint8_t>();
76
+
77
+ auto stride_i = packed_tensor.stride(2);
78
+ auto stride_j = packed_tensor.stride(0);
79
+
80
+ for (const auto i : c10::irange(num_pixels)) {
81
+ for (const auto j : c10::irange(rgba_size)) {
82
+ unpacked[rgba_size * i + j] = (j < num_channels) ? packed[stride_i * i + stride_j * j] : 0;
83
+ }
84
+ }
85
+ return unpacked_tensor;
86
+ }
87
+
88
+ void pack_rgb(
89
+ const at::Tensor& unpacked_tensor, // IN
90
+ const at::Tensor& packed_tensor // OUT
91
+ ) {
92
+ // Convert from unpacked channels last 3-channels or 4-channels tensor into original data layout.
93
+
94
+ uint8_t* unpacked = (uint8_t*)unpacked_tensor.data_ptr<uint8_t>();
95
+ uint8_t* packed = (uint8_t*)packed_tensor.data_ptr<uint8_t>();
96
+ auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2);
97
+ auto num_channels = packed_tensor.size(0);
98
+
99
+ auto unpacked_increment = unpacked_tensor.size(0);
100
+ auto packed_increment = packed_tensor.stride(2);
101
+ auto packed_stride = packed_tensor.stride(0);
102
+
103
+ TORCH_INTERNAL_ASSERT(unpacked_increment == 3 || unpacked_increment == 4);
104
+
105
+ for ([[maybe_unused]] const auto i : c10::irange(num_pixels)) {
106
+ for (const auto j : c10::irange(num_channels)) {
107
+ packed[j * packed_stride] = unpacked[j];
108
+ }
109
+ unpacked += unpacked_increment;
110
+ packed += packed_increment;
111
+ }
112
+ }
113
+
114
+ void ImagingResampleHorizontalConvolution8u4x(
115
+ uint8_t* C10_RESTRICT lineOut0,
116
+ uint8_t* C10_RESTRICT lineOut1,
117
+ uint8_t* C10_RESTRICT lineOut2,
118
+ uint8_t* C10_RESTRICT lineOut3,
119
+ int64_t out_xsize,
120
+ const uint8_t* C10_RESTRICT lineIn0,
121
+ const uint8_t* C10_RESTRICT lineIn1,
122
+ const uint8_t* C10_RESTRICT lineIn2,
123
+ const uint8_t* C10_RESTRICT lineIn3,
124
+ int64_t in_xsize,
125
+ const int64_t* idx_ptr_xmin,
126
+ const int64_t* idx_ptr_size,
127
+ const int16_t* kk,
128
+ int kmax,
129
+ unsigned int coefs_precision,
130
+ int64_t num_channels,
131
+ bool is_last_line);
132
+
133
+ void ImagingResampleHorizontalConvolution8u(
134
+ uint8_t* C10_RESTRICT lineOut,
135
+ int64_t out_xsize,
136
+ const uint8_t* C10_RESTRICT lineIn,
137
+ int64_t in_xsize,
138
+ const int64_t* idx_ptr_xmin,
139
+ const int64_t* idx_ptr_size,
140
+ const int16_t* kk,
141
+ int kmax,
142
+ unsigned int coefs_precision,
143
+ int64_t num_channels,
144
+ bool is_last_line);
145
+
146
+ void ImagingResampleVerticalConvolution8u(
147
+ uint8_t* C10_RESTRICT lineOut,
148
+ const uint8_t* C10_RESTRICT lineIn,
149
+ int64_t xsize,
150
+ int64_t ids_min,
151
+ int64_t ids_size,
152
+ const int16_t* k,
153
+ unsigned int coefs_precision,
154
+ int64_t num_channels);
155
+
156
+ template<int num_channels>
157
+ void ImagingResampleHorizontal(
158
+ const at::Tensor & unpacked_output,
159
+ const at::Tensor & unpacked_input,
160
+ int ksize,
161
+ const std::vector<at::Tensor>& horiz_indices_weights,
162
+ unsigned int horiz_weights_precision) {
163
+
164
+ // Interpolation horizontal pass: we compute x-axis (image width) interpolation outputs.
165
+
166
+ // Input data is stored as
167
+ // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...]
168
+ // Weights are float values computed for each output pixel and rescaled to uint16:
169
+ // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]]
170
+ // We want to compute the output as following:
171
+ // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...]
172
+ // where
173
+ // oR[yoffset + i] = r[yoffset + xmin[i]] * w[i, 0] + ... + r[yoffset + xmin[i] + K-1] * w[i, K-1]
174
+ // oG[yoffset + i] = g[yoffset + xmin[i]] * w[i, 0] + ... + g[yoffset + xmin[i] + K-1] * w[i, K-1]
175
+ // oB[yoffset + i] = b[yoffset + xmin[i]] * w[i, 0] + ... + b[yoffset + xmin[i] + K-1] * w[i, K-1]
176
+ //
177
+
178
+ // TODO: we may want to merge that into the fallback code (currently called
179
+ // basic_loop_aa_horizontal<uint8_t>)
180
+ // Although this may not be needed if / when we port all this code to use
181
+ // Vec.h since this would potentially give us another fall-back implem
182
+
183
+ const int16_t* kk = (int16_t*)(horiz_indices_weights[3].const_data_ptr<double>());
184
+
185
+ auto xout = unpacked_output.size(2);
186
+ auto yout = unpacked_output.size(1);
187
+ auto xin = unpacked_input.size(2);
188
+ TORCH_INTERNAL_ASSERT(num_channels == unpacked_input.size(0));
189
+
190
+ const int64_t* idx_ptr_xmin = horiz_indices_weights[0].const_data_ptr<int64_t>();
191
+ const int64_t* idx_ptr_size = horiz_indices_weights[1].const_data_ptr<int64_t>();
192
+
193
+ uint8_t* unpacked_output_p = unpacked_output.data_ptr<uint8_t>();
194
+ const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr<uint8_t>();
195
+
196
+ int64_t yy = 0;
197
+ auto xout_stride = xout * num_channels;
198
+ auto xin_stride = xin * num_channels;
199
+ for (; yy < yout - 3; yy += 4) {
200
+ ImagingResampleHorizontalConvolution8u4x(
201
+ unpacked_output_p + yy * xout_stride,
202
+ unpacked_output_p + (yy + 1) * xout_stride,
203
+ unpacked_output_p + (yy + 2) * xout_stride,
204
+ unpacked_output_p + (yy + 3) * xout_stride,
205
+ xout,
206
+ unpacked_input_p + yy * xin_stride,
207
+ unpacked_input_p + (yy + 1) * xin_stride,
208
+ unpacked_input_p + (yy + 2) * xin_stride,
209
+ unpacked_input_p + (yy + 3) * xin_stride,
210
+ xin,
211
+ idx_ptr_xmin,
212
+ idx_ptr_size,
213
+ kk,
214
+ ksize,
215
+ horiz_weights_precision,
216
+ num_channels,
217
+ yy + 3 == yout - 1);
218
+ }
219
+ for (; yy < yout; yy++) {
220
+ ImagingResampleHorizontalConvolution8u(
221
+ unpacked_output_p + yy * xout_stride,
222
+ xout,
223
+ unpacked_input_p + yy * xin_stride,
224
+ xin,
225
+ idx_ptr_xmin,
226
+ idx_ptr_size,
227
+ kk,
228
+ ksize,
229
+ horiz_weights_precision,
230
+ num_channels,
231
+ yy == yout - 1);
232
+ }
233
+ }
234
+
235
+ void ImagingResampleVertical(
236
+ const at::Tensor & unpacked_output,
237
+ const at::Tensor & unpacked_input,
238
+ int ksize,
239
+ const std::vector<at::Tensor>& vert_indices_weights,
240
+ unsigned int vert_weights_precision) {
241
+
242
+ // Interpolation vertical pass: we compute y-axis interpolation outputs.
243
+ // Input data is stored as
244
+ // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...]
245
+ // Weights are float values computed for each output pixel and rescaled to uint16:
246
+ // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]]
247
+ // We want to compute the output as following:
248
+ // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...]
249
+ // where
250
+ // oR[xoffset + i] = r[xoffset + ymin[i]] * w[i, 0] + ... + r[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
251
+ // oG[xoffset + i] = g[xoffset + ymin[i]] * w[i, 0] + ... + g[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
252
+ // oB[xoffset + i] = b[xoffset + ymin[i]] * w[i, 0] + ... + b[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
253
+
254
+ // TODO: we may want to merge that into the fallback code (currently called
255
+ // basic_loop_aa_vertical<uint8_t>)
256
+ // Although this may not be needed if / when we port all this code to use
257
+ // Vec.h since this would potentially give us another fall-back implem
258
+ const int16_t* kk = (int16_t*)(vert_indices_weights[3].const_data_ptr<double>());
259
+
260
+ const int64_t* idx_ptr_xmin = vert_indices_weights[0].const_data_ptr<int64_t>();
261
+ const int64_t* idx_ptr_size = vert_indices_weights[1].const_data_ptr<int64_t>();
262
+
263
+ uint8_t* unpacked_output_p = unpacked_output.data_ptr<uint8_t>();
264
+ const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr<uint8_t>();
265
+
266
+ auto xout = unpacked_output.size(2);
267
+ auto yout = unpacked_output.size(1);
268
+ const auto num_channels = unpacked_input.size(0);
269
+ TORCH_INTERNAL_ASSERT(num_channels == unpacked_output.size(0));
270
+
271
+ auto xout_stride = xout * num_channels;
272
+ for (const auto yy : c10::irange(yout)) {
273
+ const auto* k = &kk[yy * ksize];
274
+ auto ids_min = idx_ptr_xmin[yy];
275
+ auto ids_size = idx_ptr_size[yy];
276
+ ImagingResampleVerticalConvolution8u(
277
+ unpacked_output_p + yy * xout_stride,
278
+ unpacked_input_p,
279
+ xout,
280
+ ids_min,
281
+ ids_size,
282
+ k,
283
+ vert_weights_precision,
284
+ num_channels);
285
+ }
286
+ }
287
+
288
+ // This is the only public entry point in this file. It supports bilinear or bicubic
289
+ // mode for uint8 dtype when C <= 4, with or without antialias. The
290
+ // implem is based on PIL-SIMD.
291
+ // Its equivalent implementation (fallback) for when AVX isn't supported or when
292
+ // C > 4 is separable_upsample_generic_Nd_kernel_impl() There are a bunch of
293
+ // future improvement that can be done: look for the TODOs in this file.
294
+ // For details on how the weights are computed and how the multiplications are
295
+ // run on int (instead of float weights), see
296
+ // [ Weights computation for uint8_t and multiplication trick ]
297
+ // For details on how the AVX kernels are implemented, see
298
+ // https://gist.github.com/NicolasHug/47c97d731f05eaad5694c173849b86f5
299
+ // See also [ Support for antialias=False as a subcase of antialias=True ] to
300
+ // learn more about how the antialias=False case is computed. The same holds
301
+ // here: all these kernels are general enough to handle an arbitrary number of
302
+ // weights, but when aa=False they could be optimized further.
303
+ template <typename scale_type, class F>
304
+ void upsample_avx_bilinear_bicubic_uint8(
305
+ const at::Tensor& input_,
306
+ const at::Tensor& output,
307
+ bool align_corners,
308
+ const scale_type& scales,
309
+ bool antialias) {
310
+ auto batch_size = input_.size(0);
311
+ auto num_channels = input_.size(1);
312
+ auto xin = input_.size(3);
313
+ auto yin = input_.size(2);
314
+ auto xout = output.size(3);
315
+ auto yout = output.size(2);
316
+
317
+ if (xin == xout && yin == yout) {
318
+ output.copy_(input_);
319
+ return;
320
+ }
321
+
322
+ at::Tensor input = input_;
323
+ if (!(input.is_contiguous() || input.is_contiguous(at::MemoryFormat::ChannelsLast))) {
324
+ // If input is not contiguous with memory format channels first or channels last,
325
+ // we explicitly convert the input to contiguous channels last memory format.
326
+ // This simplifies the rest of the code and let us assume that the format is only contiguous channels first or channels last,
327
+ // Most tensors going through this `if` block won't need to go through unpacking, but those having C < 3 may
328
+ // have to (this means 2 copies are made). We could avoid the extra copy by handling non-contiguous input
329
+ // directly within unpack_rgb() and pack_rgb(), but initial attempts showed that this is fairly complex.
330
+ input = input.contiguous(at::MemoryFormat::ChannelsLast);
331
+ }
332
+
333
+ auto need_horizontal = xout != xin;
334
+ auto need_vertical = yout != yin;
335
+
336
+ int ksize_horiz, ksize_vert;
337
+ std::vector<at::Tensor> horiz_indices_weights, vert_indices_weights;
338
+ unsigned int horiz_weights_precision, vert_weights_precision;
339
+
340
+ bool skip_unpacking = (num_channels == 3 || num_channels == 4) && input.is_contiguous(at::MemoryFormat::ChannelsLast);
341
+ bool skip_packing = (num_channels == 3 || num_channels == 4) && output.is_contiguous(at::MemoryFormat::ChannelsLast);
342
+
343
+ if (need_horizontal) {
344
+ int interp_dim = 3;
345
+ auto stride = (skip_unpacking) ? num_channels : 4;
346
+ std::tie(horiz_indices_weights, ksize_horiz, horiz_weights_precision) =
347
+ F::compute_index_ranges_int16_weights(
348
+ /*input_size=*/xin,
349
+ /*output_size=*/xout,
350
+ /*stride=*/stride,
351
+ /*ndims=*/4,
352
+ /*reshape_dim=*/interp_dim,
353
+ /*align_corners=*/align_corners,
354
+ /*opt_scale=*/scales[interp_dim - 2],
355
+ /*antialias=*/antialias,
356
+ /*align_i32=*/true);
357
+ }
358
+
359
+ if (need_vertical) {
360
+ int interp_dim = 2;
361
+ auto stride = (skip_unpacking) ? num_channels * xout : 4 * xout;
362
+ std::tie(vert_indices_weights, ksize_vert, vert_weights_precision) =
363
+ F::compute_index_ranges_int16_weights(
364
+ /*input_size=*/yin,
365
+ /*output_size=*/yout,
366
+ /*stride=*/stride,
367
+ /*ndims=*/4,
368
+ /*reshape_dim=*/interp_dim,
369
+ /*align_corners=*/align_corners,
370
+ /*opt_scale=*/scales[interp_dim - 2],
371
+ /*antialias=*/antialias,
372
+ /*align_i32=*/true);
373
+ }
374
+
375
+ at::Tensor buffer_horiz, buffer_vert;
376
+ // Minor optimization: we can avoid allocating an extra buffer if we're performing
377
+ // horizontal-only or vertical-only interpolation, and if the tensor doesn't
378
+ // need repacking
379
+ if (need_horizontal && (need_vertical || !skip_packing)) {
380
+ auto c = (skip_unpacking) ? num_channels : 4;
381
+ buffer_horiz = at::empty({c, yin, xout}, input.options());
382
+ }
383
+ if (need_vertical && !skip_packing) {
384
+ auto c = (skip_unpacking) ? num_channels : 4;
385
+ buffer_vert = at::empty({c, yout, xout}, input.options());
386
+ }
387
+
388
+ for (const auto i : c10::irange(batch_size)) {
389
+
390
+ at::Tensor unpacked_input = (skip_unpacking) ? input[i] : unpack_rgb(input[i]);
391
+ at::Tensor unpacked_output;
392
+
393
+ if (need_horizontal) {
394
+ at::Tensor unpacked_output_temp = (need_vertical || !skip_packing) ? buffer_horiz : output[i];
395
+
396
+ if (skip_unpacking && num_channels == 3) {
397
+ ImagingResampleHorizontal<3>(
398
+ unpacked_output_temp,
399
+ unpacked_input,
400
+ ksize_horiz,
401
+ horiz_indices_weights,
402
+ horiz_weights_precision);
403
+ } else {
404
+ ImagingResampleHorizontal<4>(
405
+ unpacked_output_temp,
406
+ unpacked_input,
407
+ ksize_horiz,
408
+ horiz_indices_weights,
409
+ horiz_weights_precision);
410
+ }
411
+ unpacked_output = unpacked_input = unpacked_output_temp;
412
+ }
413
+ if (need_vertical) {
414
+ unpacked_output = (skip_packing) ? output[i] : buffer_vert;
415
+
416
+ ImagingResampleVertical(
417
+ unpacked_output,
418
+ unpacked_input,
419
+ ksize_vert,
420
+ vert_indices_weights,
421
+ vert_weights_precision
422
+ );
423
+ }
424
+
425
+ TORCH_INTERNAL_ASSERT(unpacked_output.defined());
426
+
427
+ if (!skip_packing) {
428
+ pack_rgb(unpacked_output, output[i]);
429
+ }
430
+ }
431
+ }
432
+
433
+ void ImagingResampleHorizontalConvolution8u4x(
434
+ uint8_t* C10_RESTRICT lineOut0,
435
+ uint8_t* C10_RESTRICT lineOut1,
436
+ uint8_t* C10_RESTRICT lineOut2,
437
+ uint8_t* C10_RESTRICT lineOut3,
438
+ int64_t out_xsize,
439
+ const uint8_t* C10_RESTRICT lineIn0,
440
+ const uint8_t* C10_RESTRICT lineIn1,
441
+ const uint8_t* C10_RESTRICT lineIn2,
442
+ const uint8_t* C10_RESTRICT lineIn3,
443
+ int64_t in_xsize,
444
+ const int64_t* idx_ptr_xmin,
445
+ const int64_t* idx_ptr_size,
446
+ const int16_t* kk,
447
+ int kmax,
448
+ unsigned int coefs_precision,
449
+ int64_t num_channels,
450
+ bool is_last_line) {
451
+
452
+ // Interpolation horizontal pass processing together 4 vertical lines.
453
+ // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA
454
+ // we can encode 4 values as a single uint32 value.
455
+ // - We split the size of weight vector for a given output index as a sum:
456
+ // ids_size = num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1.
457
+ // - We load and process 4 weights values in a loop ("block 4") then we process 2 weights values
458
+ // in another loop ("block 2") and finally we process 1 weights value in the final loop ("block 1").
459
+
460
+ // Define shuffling masks (low/high) for num_channels 4 and 3
461
+ // Mask low casts lower half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA:
462
+ // [r1 g1 b1 a1 r2 g2 b2 a2 ... | R1 G1 B1 A1 R2 G2 B2 A2 ... ] ->
463
+ // [r1 0 r2 0 g1 0 g2 0 b1 0 b2 0 a1 0 a2 0 | R1 0 R2 0 G1 0 G2 0 B1 0 B2 0 A1 0 A2 0]
464
+ // Mask high casts upper half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA::
465
+ // [ ... r3 g3 b3 a3 r4 g4 b4 a4 | ... R3 G3 B3 A3 R4 G4 B4 A4 ] ->
466
+ // [r3 0 r4 0 g3 0 g4 0 b3 0 b4 0 a3 0 a4 0 | R3 0 R4 0 G3 0 G4 0 B3 0 B4 0 A3 0 A4 0]
467
+
468
+ const auto mask_low_c4 = _mm256_set_epi8(
469
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0,
470
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
471
+ const auto mask_high_c4 = _mm256_set_epi8(
472
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
473
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8);
474
+ const auto mask_low_c3 = _mm256_set_epi8(
475
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0,
476
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
477
+ const auto mask_high_c3 = _mm256_set_epi8(
478
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
479
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6);
480
+
481
+ const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4;
482
+ const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4;
483
+
484
+ const auto stride = num_channels * sizeof(uint8_t);
485
+
486
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
487
+
488
+ // out_xsize = output width, out_x = output x index
489
+ // ids_min is the input offset index corresponding to out_x
490
+ // ids_size is the interpolation size for out_x
491
+
492
+ // Let's precompute ids_size limits for block 4 and block 2.
493
+ //
494
+ // In block 4 (4 means we process 4 weight values together), we read input data
495
+ // with _mm_loadu_si128, i.e. 16 bytes, per one line:
496
+ // lineIn0 + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min)
497
+ // --> i <= ids_size - 16.0 / stride
498
+ // Strict boundary:
499
+ // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta
500
+ // Soft boundary for reading inside the buffer except its boundaries:
501
+ // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft
502
+ // RGBA: b4_delta = b4_delta_soft = 3
503
+ // RGB : b4_delta = 5
504
+ // RGB : b4_delta_soft = 4
505
+ const auto b4_delta = (stride == 4) ? 3 : ((is_last_line) ? 5 : 4);
506
+
507
+ // In block 2 (2 means we process 2 weights values together), we read input data
508
+ // with _mm_loadl_epi64, i.e. 8 bytes, per one line:
509
+ // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min)
510
+ // --> i <= ids_size - 8.0 / stride
511
+ // Strict boundary:
512
+ // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta
513
+ // Soft boundary for reading inside the buffer except its boundaries:
514
+ // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft
515
+ // RGBA: b2_delta = b2_delta_soft = 1
516
+ // RGB : b2_delta = 2
517
+ // RGB : b2_delta_soft = 1
518
+ const auto b2_delta = (stride == 4) ? 1 : ((is_last_line) ? 2 : 1);
519
+
520
+ const auto max_out_x_strided = out_xsize * stride;
521
+ const auto max_in_x_strided = in_xsize * stride;
522
+
523
+ const auto zero = _mm256_setzero_si256();
524
+ const auto initial = _mm256_set1_epi32(1 << (coefs_precision - 1));
525
+
526
+ for (const auto out_x : c10::irange(out_xsize)) {
527
+ const auto ids_min = idx_ptr_xmin[out_x];
528
+ const auto ids_size = idx_ptr_size[out_x];
529
+ const auto * k = &kk[out_x * kmax];
530
+ int64_t i = 0;
531
+
532
+ auto sss0 = initial;
533
+ auto sss1 = initial;
534
+
535
+ const auto * lineIn0_min = lineIn0 + ids_min;
536
+ const auto * lineIn1_min = lineIn1 + ids_min;
537
+ const auto * lineIn2_min = lineIn2 + ids_min;
538
+ const auto * lineIn3_min = lineIn3 + ids_min;
539
+
540
+ // block 4
541
+ for (; i < ids_size - b4_delta; i += 4) {
542
+ // Load 4 values from weight vector
543
+ // mmk0 = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
544
+ // mmk1 = [wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ...]
545
+ const auto mmk0 = _mm256_set1_epi32(*(int32_t*)&k[i]);
546
+ const auto mmk1 = _mm256_set1_epi32(*(int32_t*)&k[i + 2]);
547
+
548
+ // RGBA: Load 8 pixels (4 per line) from input lines 0 and 1:
549
+ // source = [
550
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
551
+ // R0 G0 B0 A0 R1 G1 B1 A1 R2 G2 B2 A2 R3 G3 B3 A3
552
+ // ]
553
+ // RGB: Load 10 pixels (5 per line)
554
+ // source = [
555
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
556
+ // R0 G0 B0 R1 G1 B1 R2 G2 B2 R3 G3 B3 R4 G4 B4 R5
557
+ // ]
558
+ auto source = _mm256_inserti128_si256(_mm256_castsi128_si256(
559
+ _mm_loadu_si128((__m128i *) (lineIn0_min + stride * i))),
560
+ _mm_loadu_si128((__m128i *) (lineIn1_min + stride * i)), 1);
561
+
562
+ // Apply mask_low:
563
+ // RGBA:
564
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0]
565
+ // RGB:
566
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0]
567
+ auto pix1 = _mm256_shuffle_epi8(source, mask_low);
568
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
569
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk0));
570
+
571
+ // Apply mask_high:
572
+ // RGBA:
573
+ // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 A2 0 A3 0]
574
+ // RGB:
575
+ // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 0 0 0 0]
576
+ auto pix2 = _mm256_shuffle_epi8(source, mask_high);
577
+ // Compute output value as C += w2 * C2 + w3 * C3 for each channel in 32-bit precision
578
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix2, mmk1));
579
+
580
+ // Same as above to next lines 2 and 3:
581
+ auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
582
+ _mm_loadu_si128((__m128i *) (lineIn2_min + stride * i))),
583
+ _mm_loadu_si128((__m128i *) (lineIn3_min + stride * i)), 1);
584
+ auto pix3 = _mm256_shuffle_epi8(source2, mask_low);
585
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix3, mmk0));
586
+ auto pix4 = _mm256_shuffle_epi8(source2, mask_high);
587
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix4, mmk1));
588
+ }
589
+
590
+ // block 2
591
+ for (; i < ids_size - b2_delta; i += 2) {
592
+ // Load 2 values from weight vector
593
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
594
+ const auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]);
595
+
596
+ // Load 4 pixels (2 per line) from input lines 0 and 1:
597
+ // RGBA: source1 = [
598
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
599
+ // R0 G0 B0 A0 R1 G1 B1 A1 0 0 0 0 0 0 0 0
600
+ // ]
601
+ // RGB: source1 = [
602
+ // r0 g0 b0 r1 g1 b1 r2 0 0 0 0 0 0 0 0
603
+ // R0 G0 B0 R1 G1 B1 R2 0 0 0 0 0 0 0 0
604
+ // ]
605
+ auto source1 = _mm256_inserti128_si256(_mm256_castsi128_si256(
606
+ _mm_loadl_epi64((__m128i *) (lineIn0_min + stride * i))),
607
+ _mm_loadl_epi64((__m128i *) (lineIn1_min + stride * i)), 1);
608
+ // Apply mask_low:
609
+ // RGBA:
610
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0]
611
+ // RGB:
612
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0]
613
+ auto pix1 = _mm256_shuffle_epi8(source1, mask_low);
614
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
615
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
616
+
617
+ // Same as above for lines 2 and 3:
618
+ auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
619
+ _mm_loadl_epi64((__m128i *) (lineIn2_min + stride * i))),
620
+ _mm_loadl_epi64((__m128i *) (lineIn3_min + stride * i)), 1);
621
+ auto pix2 = _mm256_shuffle_epi8(source2, mask_low);
622
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
623
+ }
624
+
625
+ // block 1
626
+ const auto i32_aligned = num_channels == 4;
627
+ for (; i < ids_size - 1; i++) {
628
+ // Load 1 value from weight vector
629
+ // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...]
630
+ const auto mmk = _mm256_set1_epi32(k[i]);
631
+
632
+ // Load 2 pixels (one per line) from input lines 0 and 1:
633
+ // RGBA: pix1 = [
634
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0
635
+ // R0 0 0 0 G0 0 0 0 B0 0 0 0 A0 0 0 0
636
+ // ]
637
+ // RGB: pix1 = [
638
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0
639
+ // R0 0 0 0 G0 0 0 0 B0 0 0 0 R1 0 0 0
640
+ // ]
641
+ auto pix1 = _mm256_inserti128_si256(_mm256_castsi128_si256(
642
+ mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)),
643
+ mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1);
644
+ // Compute output value as C += w0 * C0 for each channel in 32-bit precision
645
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
646
+
647
+ // Same as above for lines 2 and 3
648
+ auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
649
+ mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned)),
650
+ mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned), 1);
651
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
652
+ }
653
+
654
+ if (i == ids_size - 1) {
655
+ // last element
656
+ auto mmk = _mm256_set1_epi32(k[i]);
657
+ // For num_channels == 3 (3 bytes = one pixel) we tolerate to read 4 bytes
658
+ // lines 0, 1 and 2 wont go out of allocated memory bounds
659
+ auto pix = _mm256_inserti128_si256(_mm256_castsi128_si256(
660
+ mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)),
661
+ mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1);
662
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix, mmk));
663
+
664
+ auto p0 = mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned);
665
+ __m128i p1;
666
+ if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) {
667
+ uint8_t input[4];
668
+ std::memcpy(input, lineIn3_min + stride * i, 3);
669
+ p1 = mm_cvtepu8_epi32(input, true);
670
+ } else {
671
+ p1 = mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned);
672
+ }
673
+ auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256(p0), p1, 1);
674
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
675
+ }
676
+
677
+ // Convert fixed point values back to integers (truncating)
678
+ sss0 = _mm256_srai_epi32(sss0, coefs_precision);
679
+ sss1 = _mm256_srai_epi32(sss1, coefs_precision);
680
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
681
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0)
682
+ sss0 = _mm256_packs_epi32(sss0, zero);
683
+ sss1 = _mm256_packs_epi32(sss1, zero);
684
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
685
+ // (a a b b c c d d) -> (a b c d 0 0 0 0)
686
+ sss0 = _mm256_packus_epi16(sss0, zero);
687
+ sss1 = _mm256_packus_epi16(sss1, zero);
688
+
689
+ // Write the output into single uint32
690
+ // (a b c d) -> x_uint32
691
+ auto o0 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss0));
692
+ auto o1 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss0, 1));
693
+ auto o2 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss1));
694
+ auto o3 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss1, 1));
695
+
696
+ const auto out_x_strided = stride * out_x;
697
+
698
+ if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) {
699
+ // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write
700
+ // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1).
701
+ // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct
702
+ // value which was previously computed by another line. In other words, it means that we can not overwrite
703
+ // it by simply writing 4 bytes from the register to the output. We'll do the following:
704
+ // v----------|
705
+ // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...]
706
+ // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1)
707
+ // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1)
708
+ // Output = [... R G B | R1 G1 B1 R2 ...]
709
+
710
+ _write_endline_rgb_as_uint32(lineOut0 + out_x_strided, o0);
711
+ _write_endline_rgb_as_uint32(lineOut1 + out_x_strided, o1);
712
+ _write_endline_rgb_as_uint32(lineOut2 + out_x_strided, o2);
713
+
714
+ if (C10_UNLIKELY(is_last_line)) {
715
+ // When we handle the last line, we can not access the next 4 bytes
716
+ // as they are out of memory bounds.
717
+ std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, num_channels);
718
+ } else {
719
+ _write_endline_rgb_as_uint32(lineOut3 + out_x_strided, o3);
720
+ }
721
+ } else if (num_channels == 3) {
722
+ // Memcpy 4-bytes is faster than 3-bytes and here
723
+ // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value
724
+ // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...)
725
+ std::memcpy(lineOut0 + out_x_strided, (uint8_t *) &o0, 4);
726
+ std::memcpy(lineOut1 + out_x_strided, (uint8_t *) &o1, 4);
727
+ std::memcpy(lineOut2 + out_x_strided, (uint8_t *) &o2, 4);
728
+ std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, 4);
729
+ } else {
730
+ // num_channels = 4 -> lineOutX + out_x_strided should be uint32 aligned
731
+ *(uint32_t *)(lineOut0 + out_x_strided) = o0;
732
+ *(uint32_t *)(lineOut1 + out_x_strided) = o1;
733
+ *(uint32_t *)(lineOut2 + out_x_strided) = o2;
734
+ *(uint32_t *)(lineOut3 + out_x_strided) = o3;
735
+ }
736
+ }
737
+ }
738
+
739
+ void ImagingResampleHorizontalConvolution8u(
740
+ uint8_t* C10_RESTRICT lineOut,
741
+ int64_t out_xsize,
742
+ const uint8_t* C10_RESTRICT lineIn,
743
+ int64_t in_xsize,
744
+ const int64_t* idx_ptr_xmin,
745
+ const int64_t* idx_ptr_size,
746
+ const int16_t* kk,
747
+ int kmax,
748
+ unsigned int coefs_precision,
749
+ int64_t num_channels,
750
+ bool is_last_line) {
751
+
752
+ // Interpolation horizontal pass processing only one vertical line.
753
+ // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA
754
+ // we can encode 4 values as a single uint32 value.
755
+ // - We split the size of weight vector for a given output index as a sum:
756
+ // ids_size = num_blocks_8 * 8 + num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1
757
+ // - We load and process 8 weights values in a loop ("block 8") then 4 weights and 2 weights values in
758
+ // in another loops ("block 4" and "block 2") and finally we process 1 weight value in the final loop ("block 1").
759
+
760
+ // Define various shuffling masks
761
+ const auto kmask_low = _mm256_set_epi8(
762
+ 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8,
763
+ 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0);
764
+ const auto kmask_high = _mm256_set_epi8(
765
+ 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12,
766
+ 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4);
767
+ const auto kmask_hl = _mm256_set_epi8(
768
+ 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4,
769
+ 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0);
770
+
771
+ const auto mask_low_c4 = _mm256_set_epi8(
772
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0,
773
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
774
+ const auto mask_high_c4 = _mm256_set_epi8(
775
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
776
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8);
777
+ const auto mask_low_c3 = _mm256_set_epi8(
778
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0,
779
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
780
+ const auto mask_high_c3 = _mm256_set_epi8(
781
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
782
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6);
783
+ const auto mask_hl_c3 = _mm256_set_epi8(
784
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
785
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
786
+ const auto mask_hl_c4 = _mm256_set_epi8(
787
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
788
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
789
+
790
+ const auto mask_low128_c3 = _mm_set_epi8(
791
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
792
+ const auto mask_low128_c4 = _mm_set_epi8(
793
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
794
+
795
+ const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4;
796
+ const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4;
797
+ const auto mask_hl = (num_channels == 3) ? mask_hl_c3 : mask_hl_c4;
798
+ const auto mask_low128 = (num_channels == 3) ? mask_low128_c3 : mask_low128_c4;
799
+
800
+ // out_xsize = output width, out_x = output x index
801
+ // ids_min is the input offset index corresponding to out_x
802
+ // ids_size is the interpolation size for out_x
803
+
804
+ const auto stride = num_channels * sizeof(uint8_t);
805
+ const auto zero = _mm_setzero_si128();
806
+
807
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
808
+
809
+ // Let's precompute ids_size limits for block 8, block 4 and block 2
810
+ //
811
+ // In block 8 (8 means we process 8 weight values together), we read at
812
+ // most 32 bytes input data (16 + 16 bytes for RGBA and 12 + 16 bytes for RGB)
813
+ // lineIn + stride * (i + ids_min) + 32 <= lineIn + stride * (ids_size + ids_min)
814
+ // --> i <= ids_size - 32.0 / stride
815
+ // Strict boundary:
816
+ // --> i < ids_size + 1 - int(ceil(32.0 / stride)) = ids_size - b8_delta
817
+ // Soft boundary for reading inside the buffer except its boundaries:
818
+ // --> i < ids_size + 1 - int(32.0 / stride) = ids_size - b8_delta_soft
819
+ // RGBA: b8_delta = b8_delta_soft = 7
820
+ // RGB : b8_delta = 10
821
+ // RGB : b8_delta_soft = 9
822
+ const auto b8_delta = (stride == 4) ? 7 : ((is_last_line) ? 10 : 9);
823
+
824
+ // In block 4 (4 means we process 4 weight values together), we read
825
+ // 16 bytes of input data.
826
+ // lineIn + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min)
827
+ // --> i <= ids_size - 16.0 / stride
828
+ // Strict boundary:
829
+ // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta
830
+ // Soft boundary for reading inside the buffer except its boundaries:
831
+ // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft
832
+ // RGBA: b4_delta = b4_delta_soft = 3
833
+ // RGB : b4_delta = 5
834
+ // RGB : b4_delta_soft = 4
835
+ const auto b4_delta = (stride == 4) ? 3 : ((is_last_line) ? 5 : 4);
836
+
837
+ // In block 2 (2 means we process 2 weight values together), we read
838
+ // 8 bytes of input data.
839
+ // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min)
840
+ // --> i <= ids_size - 8.0 / stride
841
+ // Strict boundary:
842
+ // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta
843
+ // Soft boundary for reading inside the buffer except its boundaries:
844
+ // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft
845
+ // RGBA: b2_delta = b2_delta_soft = 1
846
+ // RGB : b2_delta = 2
847
+ // RGB : b2_delta_soft = 1
848
+ const auto b2_delta = (stride == 4) ? 1 : ((is_last_line) ? 2 : 1);
849
+
850
+ const auto max_out_x_strided = out_xsize * stride;
851
+ const auto max_in_x_strided = in_xsize * stride;
852
+
853
+ for (const auto out_x : c10::irange(out_xsize)) {
854
+ __m128i sss;
855
+ const auto ids_min = idx_ptr_xmin[out_x];
856
+ const auto ids_size = idx_ptr_size[out_x];
857
+ const auto * k = &kk[out_x * kmax];
858
+ int64_t i = 0;
859
+
860
+ const auto * lineIn_min = lineIn + ids_min;
861
+
862
+ if (ids_size < 8) {
863
+ sss = _mm_set1_epi32(1 << (coefs_precision - 1));
864
+ } else {
865
+ // Lower part will be added to higher, use only half of the error
866
+ auto sss256 = _mm256_set1_epi32(1 << (coefs_precision - 2));
867
+
868
+ // block 8
869
+ for (; i < ids_size - b8_delta; i += 8) {
870
+ // Load 8 values from weight vector
871
+ auto tmp = _mm_loadu_si128((__m128i*)&k[i]);
872
+ // ksource = [
873
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7
874
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7
875
+ // ]
876
+ auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
877
+
878
+ // RGBA: Load 8 pixels from input:
879
+ // source = [
880
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
881
+ // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7
882
+ // ]
883
+ // RGB: Load 10 pixels from input (however we can process only 8 pixels):
884
+ // source = [
885
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
886
+ // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9
887
+ // ]
888
+ auto source = _mm256_inserti128_si256(_mm256_castsi128_si256(
889
+ _mm_loadu_si128((__m128i *) (lineIn_min + stride * i))),
890
+ _mm_loadu_si128((__m128i *) (lineIn_min + stride * (i + 4))), 1);
891
+
892
+ // Extract lower part of each lane, cast to epi16 and reoder RGBARGBA -> RRGGBBAA
893
+ // RGBA: pix1 = [
894
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0
895
+ // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 a4 0 a5 0
896
+ // ]
897
+ // RGB: pix1 = [
898
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0
899
+ // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 0 0 0 0
900
+ // ]
901
+ auto pix1 = _mm256_shuffle_epi8(source, mask_low);
902
+ // mmk1 = [
903
+ // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ...
904
+ // wl_4 wh_4 wl_5 wh_5 wl_4 wh_4 wl_5 wh_5 ... ...
905
+ // ]
906
+ auto mmk1 = _mm256_shuffle_epi8(ksource, kmask_low);
907
+ // Compute output value as
908
+ // C += w0 * C0 + w1 * C1
909
+ // C += w4 * C4 + w5 * C5 for each channel in 32-bit precision
910
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix1, mmk1));
911
+
912
+ // Same as above for higher part of each lane
913
+ auto pix2 = _mm256_shuffle_epi8(source, mask_high);
914
+ auto mmk2 = _mm256_shuffle_epi8(ksource, kmask_high);
915
+ // Compute output value as
916
+ // C += w2 * C2 + w3 * C3
917
+ // C += w6 * C6 + w7 * C7 for each channel in 32-bit precision
918
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix2, mmk2));
919
+ }
920
+
921
+ // block 4
922
+ for (; i < ids_size - b4_delta; i += 4) {
923
+ // Load 4 values from weight vector
924
+ auto tmp = _mm_loadl_epi64((__m128i *) &k[i]);
925
+ // ksource = [
926
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0
927
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0
928
+ // ]
929
+ auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
930
+
931
+ // Load pixels from input line
932
+ tmp = _mm_loadu_si128((__m128i *) (lineIn_min + stride * i));
933
+ // RGBA: source = [
934
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
935
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
936
+ // ]
937
+ // RGB: source = [
938
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
939
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
940
+ // ]
941
+ auto source = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
942
+
943
+ // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA
944
+ // RGBA: pix = [
945
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0
946
+ // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0
947
+ // ]
948
+ // RGB: pix = [
949
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0
950
+ // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0
951
+ // ]
952
+ auto pix = _mm256_shuffle_epi8(source, mask_hl);
953
+ // mmk = [
954
+ // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ...
955
+ // wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ... ...
956
+ // ]
957
+ auto mmk = _mm256_shuffle_epi8(ksource, kmask_hl);
958
+ // Compute output value as
959
+ // C += w0 * C0 + w1 * C1
960
+ // C += w2 * C2 + w3 * C3 for each channel in 32-bit precision
961
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix, mmk));
962
+ }
963
+
964
+ // Sum results between the lanes
965
+ sss = _mm_add_epi32(
966
+ _mm256_extracti128_si256(sss256, 0),
967
+ _mm256_extracti128_si256(sss256, 1));
968
+ }
969
+
970
+ // block 2
971
+ for (; i < ids_size - b2_delta; i += 2) {
972
+ // Load 2 values from weight vector
973
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
974
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
975
+ // Load pixels from input line
976
+ // RGBA: source = [
977
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
978
+ // ]
979
+ // RGB: source = [
980
+ // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0
981
+ // ]
982
+ auto source = _mm_loadl_epi64((__m128i *) (lineIn_min + stride * i));
983
+ // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA
984
+ auto pix = _mm_shuffle_epi8(source, mask_low128);
985
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
986
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
987
+ }
988
+
989
+ // block 1
990
+ const auto i32_aligned = num_channels == 4;
991
+ for (; i < ids_size - 1; i++) {
992
+ // Load 1 value from weight vector
993
+ // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...]
994
+ auto mmk = _mm_set1_epi32(k[i]);
995
+ // Load one pixel from input line
996
+ // RGBA: pix = [
997
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0
998
+ // ]
999
+ // RGB: pix = [
1000
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0
1001
+ // ]
1002
+ auto pix = mm_cvtepu8_epi32(lineIn_min + stride * i, i32_aligned);
1003
+ // Compute output value as C += w0 * C0 for each channel in 32-bit precision
1004
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1005
+ }
1006
+
1007
+ if (i == ids_size - 1) {
1008
+ // last element
1009
+ auto mmk = _mm_set1_epi32(k[i]);
1010
+ __m128i pix;
1011
+ auto p = lineIn_min + stride * i;
1012
+ if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) {
1013
+ uint8_t input[4];
1014
+ std::memcpy(input, p, 3);
1015
+ pix = mm_cvtepu8_epi32(input, true);
1016
+ } else {
1017
+ pix = mm_cvtepu8_epi32(p, i32_aligned);
1018
+ }
1019
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1020
+ }
1021
+
1022
+ // Convert fixed point values back to integers (truncating)
1023
+ sss = _mm_srai_epi32(sss, coefs_precision);
1024
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1025
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0)
1026
+ sss = _mm_packs_epi32(sss, zero);
1027
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1028
+ // (a a b b c c d d) -> (a b c d 0 0 0 0)
1029
+ sss = _mm_packus_epi16(sss, zero);
1030
+ // Write the output into single uint32
1031
+ // (a b c d) -> x_uint32
1032
+ auto o = _mm_cvtsi128_si32(sss);
1033
+ const auto out_x_strided = stride * out_x;
1034
+ if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) {
1035
+ if (C10_UNLIKELY(is_last_line)) {
1036
+ // When we handle the last line, we can not access the next 4 bytes
1037
+ // as they are out of memory bounds.
1038
+ std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 3);
1039
+ } else {
1040
+ // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write
1041
+ // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1).
1042
+ // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct
1043
+ // value which was previously computed by another line. In other words, it means that we can not overwrite
1044
+ // it by simply writing 4 bytes from the register to the output. We'll do the following:
1045
+ // v----------|
1046
+ // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...]
1047
+ // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1)
1048
+ // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1)
1049
+ // Output = [... R G B | R1 G1 B1 R2 ...]
1050
+ _write_endline_rgb_as_uint32(lineOut + out_x_strided, o);
1051
+ }
1052
+ } else if (num_channels == 3) {
1053
+ // Memcpy 4-bytes is faster than 3-bytes and here
1054
+ // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value
1055
+ // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...)
1056
+ std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 4);
1057
+ } else {
1058
+ // num_channels = 4 -> lineOut + out_x_strided should be uint32 aligned
1059
+ *(uint32_t *)(lineOut + out_x_strided) = o;
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ void ImagingResampleVerticalConvolution8u(
1065
+ uint8_t* C10_RESTRICT lineOut,
1066
+ const uint8_t* C10_RESTRICT lineIn,
1067
+ int64_t xsize,
1068
+ int64_t ids_min,
1069
+ int64_t ids_size,
1070
+ const int16_t* k,
1071
+ unsigned int coefs_precision,
1072
+ int64_t num_channels) {
1073
+
1074
+ // Interpolation vertical pass processing one line.
1075
+ // - We process x-axis data with blocks of 8, 2 and 1
1076
+ // - We split the size of weight vector for a given output index as a sum: K = n * 2 + m.
1077
+
1078
+ // xsize = output width, also equals to input width
1079
+ // ids_size = interpolation size
1080
+ // ids_min = input y start index
1081
+ const auto stride = num_channels * sizeof(uint8_t);
1082
+
1083
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
1084
+
1085
+ const int64_t data_size = xsize * stride;
1086
+ const int64_t data_stride = stride;
1087
+ constexpr auto vec_size = 256 / 8;
1088
+
1089
+ const auto initial = _mm_set1_epi32(1 << (coefs_precision - 1));
1090
+ const auto initial_256 = _mm256_set1_epi32(1 << (coefs_precision - 1));
1091
+ const auto zero = _mm_setzero_si128();
1092
+ const auto zero_256 = _mm256_setzero_si256();
1093
+
1094
+ int64_t j = 0;
1095
+ // block 8
1096
+ const auto b8_usable_vec_stride = (vec_size / data_stride) * data_stride;
1097
+ for (; j < data_size - vec_size; j += b8_usable_vec_stride) {
1098
+ auto sss0 = initial_256;
1099
+ auto sss1 = initial_256;
1100
+ auto sss2 = initial_256;
1101
+ auto sss3 = initial_256;
1102
+ int64_t i = 0;
1103
+ const auto * lineIn_min = lineIn + j + ids_min;
1104
+
1105
+ for (; i < ids_size - 1; i += 2) {
1106
+ // Load 2 values from weight vector
1107
+ auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]);
1108
+
1109
+ // RGBA: Load 8 pixels per line
1110
+ // source1 = [
1111
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
1112
+ // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7
1113
+ // ]
1114
+ // RGB: Load 10 pixels per line (however we can process only 8 pixels):
1115
+ // source1 = [
1116
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
1117
+ // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9
1118
+ // ]
1119
+ auto source1 =
1120
+ _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * i));
1121
+ auto source2 =
1122
+ _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * (i + 1)));
1123
+
1124
+ // Interleave source1 and source2 from the low half of each 128-bit lane
1125
+ // and cast the result to epi16
1126
+ // RGBA: pix1 = [
1127
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1128
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0
1129
+ // ]
1130
+ // RGB: pix1 = [
1131
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1132
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0
1133
+ // ]
1134
+ auto source_lo = _mm256_unpacklo_epi8(source1, source2);
1135
+ auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256);
1136
+ // Compute output value as
1137
+ // C += w0 * c0 + w1 * C0
1138
+ // C += w0 * c1 + w1 * C1 for each channel in 32-bit precision
1139
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
1140
+
1141
+ // RGBA: pix2 = [
1142
+ // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 a2 0 A2 0
1143
+ // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 a3 0 A3 0
1144
+ // ]
1145
+ // RGB: pix2 = [
1146
+ // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 0 0 0 0
1147
+ // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 0 0 0 0
1148
+ // ]
1149
+ auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256);
1150
+ // Compute output value as
1151
+ // C += w0 * c2 + w1 * C2
1152
+ // C += w0 * c3 + w1 * C3 for each channel in 32-bit precision
1153
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
1154
+
1155
+ // Same as above for the high half of each 128-bit lane
1156
+ auto source_hi = _mm256_unpackhi_epi8(source1, source2);
1157
+ auto pix3 = _mm256_unpacklo_epi8(source_hi, zero_256);
1158
+ sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk));
1159
+ auto pix4 = _mm256_unpackhi_epi8(source_hi, zero_256);
1160
+ sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk));
1161
+ }
1162
+ // Same processing as above but with a single weight value
1163
+ for (; i < ids_size; i += 1) {
1164
+ auto mmk = _mm256_set1_epi32(k[i]);
1165
+
1166
+ auto source1 = _mm256_loadu_si256((__m256i*)(lineIn_min + i * data_size));
1167
+
1168
+ auto source_lo = _mm256_unpacklo_epi8(source1, zero_256);
1169
+ auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256);
1170
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
1171
+ auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256);
1172
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
1173
+
1174
+ auto source_hi = _mm256_unpackhi_epi8(source1, zero_256);
1175
+ auto pix3 = _mm256_unpacklo_epi8(source_hi, _mm256_setzero_si256());
1176
+ sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk));
1177
+ auto pix4 = _mm256_unpackhi_epi8(source_hi, _mm256_setzero_si256());
1178
+ sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk));
1179
+ }
1180
+ // Convert fixed point values back to integers (truncating)
1181
+ sss0 = _mm256_srai_epi32(sss0, coefs_precision);
1182
+ sss1 = _mm256_srai_epi32(sss1, coefs_precision);
1183
+ sss2 = _mm256_srai_epi32(sss2, coefs_precision);
1184
+ sss3 = _mm256_srai_epi32(sss3, coefs_precision);
1185
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1186
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1187
+ sss0 = _mm256_packs_epi32(sss0, sss1);
1188
+ sss2 = _mm256_packs_epi32(sss2, sss3);
1189
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1190
+ // (a a b b c c d d) -> (a b c d)
1191
+ sss0 = _mm256_packus_epi16(sss0, sss2);
1192
+
1193
+ // Stores 32 bytes
1194
+ _mm256_storeu_si256((__m256i*)(lineOut + j), sss0);
1195
+ }
1196
+
1197
+ // TODO: Do we also need block 4 ???
1198
+ // block 2
1199
+ const auto b2_usable_vec_stride = (8 / data_stride) * data_stride;
1200
+ for (; j < data_size - vec_size / 4; j += b2_usable_vec_stride) {
1201
+ auto sss0 = initial;
1202
+ auto sss1 = initial;
1203
+ int64_t i = 0;
1204
+ const auto * lineIn_min = lineIn + j + ids_min;
1205
+
1206
+ for (; i < ids_size - 1; i += 2) {
1207
+ // Load 2 values from weight vector
1208
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ]
1209
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1210
+
1211
+ // Load 2 pixels per line
1212
+ // RGBA: source1 = [
1213
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
1214
+ // ]
1215
+ // RGB: source1 = [
1216
+ // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0
1217
+ // ]
1218
+ auto source1 = _mm_loadl_epi64((__m128i *) (lineIn_min + i * data_size));
1219
+ auto source2 = _mm_loadl_epi64((__m128i *) (lineIn_min + (i + 1) * data_size));
1220
+ // Interleave source1 and source2 and cast the result to epi16
1221
+ // RGBA: pix = [
1222
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1223
+ // ]
1224
+ // RGB: pix = [
1225
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1226
+ // ]
1227
+ auto source = _mm_unpacklo_epi8(source1, source2);
1228
+ auto pix = _mm_unpacklo_epi8(source, zero);
1229
+ // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision
1230
+ sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix, mmk));
1231
+ // RGBA: pix = [
1232
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0
1233
+ // ]
1234
+ // RGB: pix = [
1235
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0
1236
+ // ]
1237
+ pix = _mm_unpackhi_epi8(source, zero);
1238
+ // Compute output value as C += w0 * c1 + w1 * C1 for each channel in 32-bit precision
1239
+ sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix, mmk));
1240
+ }
1241
+ // Same processing as above but with a single weight value
1242
+ for (; i < ids_size; i += 1) {
1243
+ auto mmk = _mm_set1_epi32(k[i]);
1244
+
1245
+ auto source1 = _mm_loadl_epi64((__m128i*) (lineIn_min + i * data_size));
1246
+
1247
+ auto source = _mm_unpacklo_epi8(source1, zero);
1248
+ auto pix1 = _mm_unpacklo_epi8(source, zero);
1249
+ sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix1, mmk));
1250
+ auto pix2 = _mm_unpackhi_epi8(source, zero);
1251
+ sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix2, mmk));
1252
+ }
1253
+ // Convert fixed point values back to integers (truncating)
1254
+ sss0 = _mm_srai_epi32(sss0, coefs_precision);
1255
+ sss1 = _mm_srai_epi32(sss1, coefs_precision);
1256
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1257
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1258
+ sss0 = _mm_packs_epi32(sss0, sss1);
1259
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1260
+ // (a a b b c c d d) -> (a b c d)
1261
+ sss0 = _mm_packus_epi16(sss0, sss0);
1262
+ // Store 2 pixels to the output
1263
+ _mm_storel_epi64((__m128i*)(lineOut + j), sss0);
1264
+ }
1265
+
1266
+ // block 1
1267
+ const auto b1_usable_vec_stride = (4 / data_stride) * data_stride;
1268
+ const auto i32_aligned = num_channels == 4;
1269
+ for (; j < data_size - 4; j += b1_usable_vec_stride) {
1270
+ auto sss = initial;
1271
+ int64_t i = 0;
1272
+ const auto * lineIn_min = lineIn + j + ids_min;
1273
+
1274
+ for (; i < ids_size - 1; i += 2) {
1275
+ // Load 2 values from weight vector
1276
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ]
1277
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1278
+
1279
+ // Load one pixel per line
1280
+ // RGBA: source1 = [
1281
+ // r0 g0 b0 a0 0 0 0 0 0 0 0 0 0 0 0 0
1282
+ // ]
1283
+ // RGB: source1 = [
1284
+ // r0 g0 b0 r1 0 0 0 0 0 0 0 0 0 0 0 0
1285
+ // ]
1286
+ auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned);
1287
+ auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned);
1288
+
1289
+ // Interleave source1 and source2 and cast the result to epi16
1290
+ // RGBA: pix = [
1291
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1292
+ // ]
1293
+ // RGB: pix = [
1294
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1295
+ // ]
1296
+ auto source = _mm_unpacklo_epi8(source1, source2);
1297
+ auto pix = _mm_unpacklo_epi8(source, zero);
1298
+ // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision
1299
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1300
+ }
1301
+
1302
+ for (; i < ids_size; i++) {
1303
+ auto mmk = _mm_set1_epi32(k[i]);
1304
+ auto pix = mm_cvtepu8_epi32(lineIn_min + i * data_size, i32_aligned);
1305
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1306
+ }
1307
+ sss = _mm_srai_epi32(sss, coefs_precision);
1308
+ sss = _mm_packs_epi32(sss, zero);
1309
+ sss = _mm_packus_epi16(sss, zero);
1310
+
1311
+ auto o = _mm_cvtsi128_si32(sss);
1312
+
1313
+ // Here we write 4 bytes to the output even if num_channels < 4, e.g o = {r,g,b,X} for num_channels=3
1314
+ // It is OK to write 4th byte (e.g. X) as on the next step we will overwrite it with new data.
1315
+ // We also wont go out of bounds of lineOut memory allocation
1316
+ std::memcpy(lineOut + j, (uint8_t *) &o, 4);
1317
+ }
1318
+
1319
+ for (; j < data_size; j += data_stride) {
1320
+ auto sss = initial;
1321
+ int64_t i = 0;
1322
+ const auto * lineIn_min = lineIn + j + ids_min;
1323
+ // For RGBA we can use (ids_size - 1) as tighter limit but for RGB we can read outside memory boundary
1324
+ // for the last remaining line
1325
+ for (; i < ids_size - 2; i += 2) {
1326
+ // Load two coefficients at once
1327
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1328
+
1329
+ // Load 2 lines
1330
+ auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned);
1331
+ auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned);
1332
+
1333
+ auto source = _mm_unpacklo_epi8(source1, source2);
1334
+ auto pix = _mm_unpacklo_epi8(source, zero);
1335
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1336
+ }
1337
+
1338
+ // Same processing as above but with a single weight value
1339
+ for (; i < ids_size; i++) {
1340
+ auto mmk = _mm_set1_epi32(k[i]);
1341
+
1342
+ const uint8_t * p = lineIn_min + i * data_size;
1343
+ __m128i pix;
1344
+ // There is no much perf gain using more detailed condition like
1345
+ // num_channels == 3 && ids_min + j + data_size * i + 4 >= in_max_size
1346
+ // const int64_t in_max_size = data_size * in_ysize;
1347
+ if (num_channels == 3) {
1348
+ uint8_t input[4];
1349
+ std::memcpy(input, p, 3);
1350
+ pix = mm_cvtepu8_epi32(input, true);
1351
+ } else {
1352
+ pix = mm_cvtepu8_epi32(p, true);
1353
+ }
1354
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1355
+ }
1356
+
1357
+ // Convert fixed point values back to integers (truncating)
1358
+ sss = _mm_srai_epi32(sss, coefs_precision);
1359
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1360
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1361
+ sss = _mm_packs_epi32(sss, zero);
1362
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1363
+ // (a a b b c c d d) -> (a b c d)
1364
+ sss = _mm_packus_epi16(sss, zero);
1365
+ // Store one pixel to the output
1366
+ auto o = _mm_cvtsi128_si32(sss);
1367
+ if (num_channels == 3 && C10_UNLIKELY(j + 4 >= data_size)) {
1368
+ std::memcpy(lineOut + j, (uint8_t *) &o, 3);
1369
+ } else {
1370
+ std::memcpy(lineOut + j, (uint8_t *) &o, 4);
1371
+ }
1372
+ }
1373
+ }
1374
+
1375
+ } // anonymous namespace
1376
+ #endif // CPU_CAPABILITY_AVX2
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/WeightNormKernel.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/DispatchStub.h>
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ using weight_norm_fn = void(*)(
12
+ TensorBase&, TensorBase&, const TensorBase&, const TensorBase&, int64_t);
13
+ using weight_norm_backward_fn = void(*)(
14
+ TensorBase&, TensorBase&, const TensorBase&, const TensorBase&,
15
+ const TensorBase&, const TensorBase&, int64_t);
16
+
17
+ DECLARE_DISPATCH(weight_norm_fn, weight_norm_stub)
18
+ DECLARE_DISPATCH(weight_norm_backward_fn, weight_norm_backward_stub)
19
+
20
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/avx_mathfun.h ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ /*
3
+ AVX implementation of sin, cos, sincos, exp and log
4
+
5
+ Based on "sse_mathfun.h", by Julien Pommier
6
+ http://gruntthepeon.free.fr/ssemath/
7
+
8
+ Copyright (C) 2012 Giovanni Garberoglio
9
+ Interdisciplinary Laboratory for Computational Science (LISC)
10
+ Fondazione Bruno Kessler and University of Trento
11
+ via Sommarive, 18
12
+ I-38123 Trento (Italy)
13
+
14
+ This software is provided 'as-is', without any express or implied
15
+ warranty. In no event will the authors be held liable for any damages
16
+ arising from the use of this software.
17
+
18
+ Permission is granted to anyone to use this software for any purpose,
19
+ including commercial applications, and to alter it and redistribute it
20
+ freely, subject to the following restrictions:
21
+
22
+ 1. The origin of this software must not be misrepresented; you must not
23
+ claim that you wrote the original software. If you use this software
24
+ in a product, an acknowledgment in the product documentation would be
25
+ appreciated but is not required.
26
+ 2. Altered source versions must be plainly marked as such, and must not be
27
+ misrepresented as being the original software.
28
+ 3. This notice may not be removed or altered from any source distribution.
29
+
30
+ (this is the zlib license)
31
+ */
32
+
33
+ #include <ATen/native/cpu/Intrinsics.h>
34
+
35
+ /* The original source of this file has been modified. */
36
+ #if defined(CPU_CAPABILITY_AVX2)
37
+
38
+ #if defined(__GNUC__)
39
+ # define ALIGN32_BEG __attribute__((aligned(32)))
40
+ #elif defined(_WIN32)
41
+ # define ALIGN32_BEG __declspec(align(32))
42
+ #endif
43
+
44
+ typedef __m256 v8sf; // vector of 8 float (avx2)
45
+ typedef __m256i v8si; // vector of 8 int (avx2)
46
+
47
+ /* declare some AVX constants -- why can't I figure a better way to do that? */
48
+ #define _PS256_CONST(Name, Val) \
49
+ static const ALIGN32_BEG float _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
50
+ #define _PI32_CONST256(Name, Val) \
51
+ static const ALIGN32_BEG int _pi32_256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
52
+ #define _PS256_CONST_TYPE(Name, Type, Val) \
53
+ static const ALIGN32_BEG Type _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
54
+
55
+ _PS256_CONST(1 , 1.0f);
56
+ _PS256_CONST(0p5, 0.5f);
57
+ /* the smallest non denormalized float number */
58
+ _PS256_CONST_TYPE(min_norm_pos, int, 0x00800000);
59
+ _PS256_CONST_TYPE(mant_mask, int, 0x7f800000);
60
+ _PS256_CONST_TYPE(inv_mant_mask, int, ~0x7f800000);
61
+
62
+ _PS256_CONST_TYPE(sign_mask, int, (int)0x80000000);
63
+ _PS256_CONST_TYPE(inv_sign_mask, int, ~0x80000000);
64
+
65
+ _PI32_CONST256(0, 0);
66
+ _PI32_CONST256(1, 1);
67
+ _PI32_CONST256(inv1, ~1);
68
+ _PI32_CONST256(2, 2);
69
+ _PI32_CONST256(4, 4);
70
+ _PI32_CONST256(0x7f, 0x7f);
71
+
72
+ _PS256_CONST(cephes_SQRTHF, 0.707106781186547524);
73
+ _PS256_CONST(cephes_log_p0, 7.0376836292E-2);
74
+ _PS256_CONST(cephes_log_p1, - 1.1514610310E-1);
75
+ _PS256_CONST(cephes_log_p2, 1.1676998740E-1);
76
+ _PS256_CONST(cephes_log_p3, - 1.2420140846E-1);
77
+ _PS256_CONST(cephes_log_p4, + 1.4249322787E-1);
78
+ _PS256_CONST(cephes_log_p5, - 1.6668057665E-1);
79
+ _PS256_CONST(cephes_log_p6, + 2.0000714765E-1);
80
+ _PS256_CONST(cephes_log_p7, - 2.4999993993E-1);
81
+ _PS256_CONST(cephes_log_p8, + 3.3333331174E-1);
82
+ _PS256_CONST(cephes_log_q1, -2.12194440e-4);
83
+ _PS256_CONST(cephes_log_q2, 0.693359375);
84
+
85
+
86
+ /* natural logarithm computed for 8 simultaneous float
87
+ return NaN for x <= 0
88
+ */
89
+ inline v8sf log256_ps(v8sf x) {
90
+ v8si imm0;
91
+ v8sf one = *(v8sf*)_ps256_1;
92
+
93
+ //v8sf invalid_mask = _mm256_cmple_ps(x, _mm256_setzero_ps());
94
+ v8sf invalid_mask = _mm256_cmp_ps(x, _mm256_setzero_ps(), _CMP_LE_OS);
95
+
96
+ x = _mm256_max_ps(x, *(v8sf*)_ps256_min_norm_pos); /* cut off denormalized stuff */
97
+
98
+ // can be done with AVX2
99
+ imm0 = _mm256_srli_epi32(_mm256_castps_si256(x), 23);
100
+
101
+ /* keep only the fractional part */
102
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_mant_mask);
103
+ x = _mm256_or_ps(x, *(v8sf*)_ps256_0p5);
104
+
105
+ // this is again another AVX2 instruction
106
+ imm0 = _mm256_sub_epi32(imm0, *(v8si*)_pi32_256_0x7f);
107
+ v8sf e = _mm256_cvtepi32_ps(imm0);
108
+
109
+ e = _mm256_add_ps(e, one);
110
+
111
+ /* part2:
112
+ if( x < SQRTHF ) {
113
+ e -= 1;
114
+ x = x + x - 1.0;
115
+ } else { x = x - 1.0; }
116
+ */
117
+ //v8sf mask = _mm256_cmplt_ps(x, *(v8sf*)_ps256_cephes_SQRTHF);
118
+ v8sf mask = _mm256_cmp_ps(x, *(v8sf*)_ps256_cephes_SQRTHF, _CMP_LT_OS);
119
+ v8sf tmp = _mm256_and_ps(x, mask);
120
+ x = _mm256_sub_ps(x, one);
121
+ e = _mm256_sub_ps(e, _mm256_and_ps(one, mask));
122
+ x = _mm256_add_ps(x, tmp);
123
+
124
+ v8sf z = _mm256_mul_ps(x,x);
125
+
126
+ v8sf y = *(v8sf*)_ps256_cephes_log_p0;
127
+ y = _mm256_mul_ps(y, x);
128
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p1);
129
+ y = _mm256_mul_ps(y, x);
130
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p2);
131
+ y = _mm256_mul_ps(y, x);
132
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p3);
133
+ y = _mm256_mul_ps(y, x);
134
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p4);
135
+ y = _mm256_mul_ps(y, x);
136
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p5);
137
+ y = _mm256_mul_ps(y, x);
138
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p6);
139
+ y = _mm256_mul_ps(y, x);
140
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p7);
141
+ y = _mm256_mul_ps(y, x);
142
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p8);
143
+ y = _mm256_mul_ps(y, x);
144
+
145
+ y = _mm256_mul_ps(y, z);
146
+
147
+ tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q1);
148
+ y = _mm256_add_ps(y, tmp);
149
+
150
+
151
+ tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
152
+ y = _mm256_sub_ps(y, tmp);
153
+
154
+ tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q2);
155
+ x = _mm256_add_ps(x, y);
156
+ x = _mm256_add_ps(x, tmp);
157
+ x = _mm256_or_ps(x, invalid_mask); // negative arg will be NAN
158
+ return x;
159
+ }
160
+
161
+ _PS256_CONST(exp_hi, 88.3762626647949f);
162
+ _PS256_CONST(exp_lo, -88.3762626647949f);
163
+
164
+ _PS256_CONST(cephes_LOG2EF, 1.44269504088896341);
165
+ _PS256_CONST(cephes_exp_C1, 0.693359375);
166
+ _PS256_CONST(cephes_exp_C2, -2.12194440e-4);
167
+
168
+ _PS256_CONST(cephes_exp_p0, 1.9875691500E-4);
169
+ _PS256_CONST(cephes_exp_p1, 1.3981999507E-3);
170
+ _PS256_CONST(cephes_exp_p2, 8.3334519073E-3);
171
+ _PS256_CONST(cephes_exp_p3, 4.1665795894E-2);
172
+ _PS256_CONST(cephes_exp_p4, 1.6666665459E-1);
173
+ _PS256_CONST(cephes_exp_p5, 5.0000001201E-1);
174
+
175
+ inline v8sf exp256_ps(v8sf x) {
176
+ v8sf tmp = _mm256_setzero_ps(), fx;
177
+ v8si imm0;
178
+ v8sf one = *(v8sf*)_ps256_1;
179
+
180
+ x = _mm256_min_ps(x, *(v8sf*)_ps256_exp_hi);
181
+ x = _mm256_max_ps(x, *(v8sf*)_ps256_exp_lo);
182
+
183
+ /* express exp(x) as exp(g + n*log(2)) */
184
+ fx = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_LOG2EF);
185
+ fx = _mm256_add_ps(fx, *(v8sf*)_ps256_0p5);
186
+
187
+ /* how to perform a floorf with SSE: just below */
188
+ //imm0 = _mm256_cvttps_epi32(fx);
189
+ //tmp = _mm256_cvtepi32_ps(imm0);
190
+
191
+ tmp = _mm256_floor_ps(fx);
192
+
193
+ /* if greater, subtract 1 */
194
+ //v8sf mask = _mm256_cmpgt_ps(tmp, fx);
195
+ v8sf mask = _mm256_cmp_ps(tmp, fx, _CMP_GT_OS);
196
+ mask = _mm256_and_ps(mask, one);
197
+ fx = _mm256_sub_ps(tmp, mask);
198
+
199
+ tmp = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C1);
200
+ v8sf z = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C2);
201
+ x = _mm256_sub_ps(x, tmp);
202
+ x = _mm256_sub_ps(x, z);
203
+
204
+ z = _mm256_mul_ps(x,x);
205
+
206
+ v8sf y = *(v8sf*)_ps256_cephes_exp_p0;
207
+ y = _mm256_mul_ps(y, x);
208
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p1);
209
+ y = _mm256_mul_ps(y, x);
210
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p2);
211
+ y = _mm256_mul_ps(y, x);
212
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p3);
213
+ y = _mm256_mul_ps(y, x);
214
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p4);
215
+ y = _mm256_mul_ps(y, x);
216
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p5);
217
+ y = _mm256_mul_ps(y, z);
218
+ y = _mm256_add_ps(y, x);
219
+ y = _mm256_add_ps(y, one);
220
+
221
+ /* build 2^n */
222
+ imm0 = _mm256_cvttps_epi32(fx);
223
+ // another two AVX2 instructions
224
+ imm0 = _mm256_add_epi32(imm0, *(v8si*)_pi32_256_0x7f);
225
+ imm0 = _mm256_slli_epi32(imm0, 23);
226
+ v8sf pow2n = _mm256_castsi256_ps(imm0);
227
+ y = _mm256_mul_ps(y, pow2n);
228
+ return y;
229
+ }
230
+
231
+ _PS256_CONST(minus_cephes_DP1, -0.78515625);
232
+ _PS256_CONST(minus_cephes_DP2, -2.4187564849853515625e-4);
233
+ _PS256_CONST(minus_cephes_DP3, -3.77489497744594108e-8);
234
+ _PS256_CONST(sincof_p0, -1.9515295891E-4);
235
+ _PS256_CONST(sincof_p1, 8.3321608736E-3);
236
+ _PS256_CONST(sincof_p2, -1.6666654611E-1);
237
+ _PS256_CONST(coscof_p0, 2.443315711809948E-005);
238
+ _PS256_CONST(coscof_p1, -1.388731625493765E-003);
239
+ _PS256_CONST(coscof_p2, 4.166664568298827E-002);
240
+ _PS256_CONST(cephes_FOPI, 1.27323954473516); // 4 / M_PI
241
+
242
+
243
+ /* evaluation of 8 sines at onces using AVX intrinsics
244
+
245
+ The code is the exact rewriting of the cephes sinf function.
246
+ Precision is excellent as long as x < 8192 (I did not bother to
247
+ take into account the special handling they have for greater values
248
+ -- it does not return garbage for arguments over 8192, though, but
249
+ the extra precision is missing).
250
+
251
+ Note that it is such that sinf((float)M_PI) = 8.74e-8, which is the
252
+ surprising but correct result.
253
+
254
+ */
255
+ inline v8sf sin256_ps(v8sf x) { // any x
256
+ v8sf xmm1, xmm2 = _mm256_setzero_ps(), xmm3, sign_bit, y;
257
+ v8si imm0, imm2;
258
+
259
+ sign_bit = x;
260
+ /* take the absolute value */
261
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
262
+ /* extract the sign bit (upper one) */
263
+ sign_bit = _mm256_and_ps(sign_bit, *(v8sf*)_ps256_sign_mask);
264
+
265
+ /* scale by 4/Pi */
266
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
267
+
268
+ /*
269
+ Here we start a series of integer operations, which are in the
270
+ realm of AVX2.
271
+ If we don't have AVX, let's perform them using SSE2 directives
272
+ */
273
+
274
+ /* store the integer part of y in mm0 */
275
+ imm2 = _mm256_cvttps_epi32(y);
276
+ /* j=(j+1) & (~1) (see the cephes sources) */
277
+ // another two AVX2 instruction
278
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
279
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
280
+ y = _mm256_cvtepi32_ps(imm2);
281
+
282
+ /* get the swap sign flag */
283
+ imm0 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_4);
284
+ imm0 = _mm256_slli_epi32(imm0, 29);
285
+ /* get the polynom selection mask
286
+ there is one polynom for 0 <= x <= Pi/4
287
+ and another one for Pi/4<x<=Pi/2
288
+
289
+ Both branches will be computed.
290
+ */
291
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
292
+ imm2 = _mm256_cmpeq_epi32(imm2,*(v8si*)_pi32_256_0);
293
+
294
+ v8sf swap_sign_bit = _mm256_castsi256_ps(imm0);
295
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
296
+ sign_bit = _mm256_xor_ps(sign_bit, swap_sign_bit);
297
+
298
+ /* The magic pass: "Extended precision modular arithmetic"
299
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
300
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
301
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
302
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
303
+ xmm1 = _mm256_mul_ps(y, xmm1);
304
+ xmm2 = _mm256_mul_ps(y, xmm2);
305
+ xmm3 = _mm256_mul_ps(y, xmm3);
306
+ x = _mm256_add_ps(x, xmm1);
307
+ x = _mm256_add_ps(x, xmm2);
308
+ x = _mm256_add_ps(x, xmm3);
309
+
310
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
311
+ y = *(v8sf*)_ps256_coscof_p0;
312
+ v8sf z = _mm256_mul_ps(x,x);
313
+
314
+ y = _mm256_mul_ps(y, z);
315
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
316
+ y = _mm256_mul_ps(y, z);
317
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
318
+ y = _mm256_mul_ps(y, z);
319
+ y = _mm256_mul_ps(y, z);
320
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
321
+ y = _mm256_sub_ps(y, tmp);
322
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
323
+
324
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
325
+
326
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
327
+ y2 = _mm256_mul_ps(y2, z);
328
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
329
+ y2 = _mm256_mul_ps(y2, z);
330
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
331
+ y2 = _mm256_mul_ps(y2, z);
332
+ y2 = _mm256_mul_ps(y2, x);
333
+ y2 = _mm256_add_ps(y2, x);
334
+
335
+ /* select the correct result from the two polynoms */
336
+ xmm3 = poly_mask;
337
+ y2 = _mm256_and_ps(xmm3, y2); //, xmm3);
338
+ y = _mm256_andnot_ps(xmm3, y);
339
+ y = _mm256_add_ps(y,y2);
340
+ /* update the sign */
341
+ y = _mm256_xor_ps(y, sign_bit);
342
+
343
+ return y;
344
+ }
345
+
346
+ /* almost the same as sin_ps */
347
+ inline v8sf cos256_ps(v8sf x) { // any x
348
+ v8sf xmm1, xmm2 = _mm256_setzero_ps(), xmm3, y;
349
+ v8si imm0, imm2;
350
+
351
+ /* take the absolute value */
352
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
353
+
354
+ /* scale by 4/Pi */
355
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
356
+
357
+ /* store the integer part of y in mm0 */
358
+ imm2 = _mm256_cvttps_epi32(y);
359
+ /* j=(j+1) & (~1) (see the cephes sources) */
360
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
361
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
362
+ y = _mm256_cvtepi32_ps(imm2);
363
+ imm2 = _mm256_sub_epi32(imm2, *(v8si*)_pi32_256_2);
364
+
365
+ /* get the swap sign flag */
366
+ imm0 = _mm256_andnot_si256(imm2, *(v8si*)_pi32_256_4);
367
+ imm0 = _mm256_slli_epi32(imm0, 29);
368
+ /* get the polynom selection mask */
369
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
370
+ imm2 = _mm256_cmpeq_epi32(imm2, *(v8si*)_pi32_256_0);
371
+
372
+ v8sf sign_bit = _mm256_castsi256_ps(imm0);
373
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
374
+
375
+ /* The magic pass: "Extended precision modular arithmetic"
376
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
377
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
378
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
379
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
380
+ xmm1 = _mm256_mul_ps(y, xmm1);
381
+ xmm2 = _mm256_mul_ps(y, xmm2);
382
+ xmm3 = _mm256_mul_ps(y, xmm3);
383
+ x = _mm256_add_ps(x, xmm1);
384
+ x = _mm256_add_ps(x, xmm2);
385
+ x = _mm256_add_ps(x, xmm3);
386
+
387
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
388
+ y = *(v8sf*)_ps256_coscof_p0;
389
+ v8sf z = _mm256_mul_ps(x,x);
390
+
391
+ y = _mm256_mul_ps(y, z);
392
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
393
+ y = _mm256_mul_ps(y, z);
394
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
395
+ y = _mm256_mul_ps(y, z);
396
+ y = _mm256_mul_ps(y, z);
397
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
398
+ y = _mm256_sub_ps(y, tmp);
399
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
400
+
401
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
402
+
403
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
404
+ y2 = _mm256_mul_ps(y2, z);
405
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
406
+ y2 = _mm256_mul_ps(y2, z);
407
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
408
+ y2 = _mm256_mul_ps(y2, z);
409
+ y2 = _mm256_mul_ps(y2, x);
410
+ y2 = _mm256_add_ps(y2, x);
411
+
412
+ /* select the correct result from the two polynoms */
413
+ xmm3 = poly_mask;
414
+ y2 = _mm256_and_ps(xmm3, y2); //, xmm3);
415
+ y = _mm256_andnot_ps(xmm3, y);
416
+ y = _mm256_add_ps(y,y2);
417
+ /* update the sign */
418
+ y = _mm256_xor_ps(y, sign_bit);
419
+
420
+ return y;
421
+ }
422
+
423
+ /* since sin256_ps and cos256_ps are almost identical, sincos256_ps could replace both of them..
424
+ it is almost as fast, and gives you a free cosine with your sine */
425
+ inline void sincos256_ps(v8sf x, v8sf *s, v8sf *c) {
426
+
427
+ v8sf xmm1, xmm2, xmm3 = _mm256_setzero_ps(), sign_bit_sin, y;
428
+ v8si imm0, imm2, imm4;
429
+
430
+ sign_bit_sin = x;
431
+ /* take the absolute value */
432
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
433
+ /* extract the sign bit (upper one) */
434
+ sign_bit_sin = _mm256_and_ps(sign_bit_sin, *(v8sf*)_ps256_sign_mask);
435
+
436
+ /* scale by 4/Pi */
437
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
438
+
439
+ /* store the integer part of y in imm2 */
440
+ imm2 = _mm256_cvttps_epi32(y);
441
+
442
+ /* j=(j+1) & (~1) (see the cephes sources) */
443
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
444
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
445
+
446
+ y = _mm256_cvtepi32_ps(imm2);
447
+ imm4 = imm2;
448
+
449
+ /* get the swap sign flag for the sine */
450
+ imm0 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_4);
451
+ imm0 = _mm256_slli_epi32(imm0, 29);
452
+ //v8sf swap_sign_bit_sin = _mm256_castsi256_ps(imm0);
453
+
454
+ /* get the polynom selection mask for the sine*/
455
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
456
+ imm2 = _mm256_cmpeq_epi32(imm2, *(v8si*)_pi32_256_0);
457
+ //v8sf poly_mask = _mm256_castsi256_ps(imm2);
458
+
459
+ v8sf swap_sign_bit_sin = _mm256_castsi256_ps(imm0);
460
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
461
+
462
+ /* The magic pass: "Extended precision modular arithmetic"
463
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
464
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
465
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
466
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
467
+ xmm1 = _mm256_mul_ps(y, xmm1);
468
+ xmm2 = _mm256_mul_ps(y, xmm2);
469
+ xmm3 = _mm256_mul_ps(y, xmm3);
470
+ x = _mm256_add_ps(x, xmm1);
471
+ x = _mm256_add_ps(x, xmm2);
472
+ x = _mm256_add_ps(x, xmm3);
473
+
474
+ imm4 = _mm256_sub_epi32(imm4, *(v8si*)_pi32_256_2);
475
+ imm4 = _mm256_andnot_si256(imm4, *(v8si*)_pi32_256_4);
476
+ imm4 = _mm256_slli_epi32(imm4, 29);
477
+
478
+ v8sf sign_bit_cos = _mm256_castsi256_ps(imm4);
479
+
480
+ sign_bit_sin = _mm256_xor_ps(sign_bit_sin, swap_sign_bit_sin);
481
+
482
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
483
+ v8sf z = _mm256_mul_ps(x,x);
484
+ y = *(v8sf*)_ps256_coscof_p0;
485
+
486
+ y = _mm256_mul_ps(y, z);
487
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
488
+ y = _mm256_mul_ps(y, z);
489
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
490
+ y = _mm256_mul_ps(y, z);
491
+ y = _mm256_mul_ps(y, z);
492
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
493
+ y = _mm256_sub_ps(y, tmp);
494
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
495
+
496
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
497
+
498
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
499
+ y2 = _mm256_mul_ps(y2, z);
500
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
501
+ y2 = _mm256_mul_ps(y2, z);
502
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
503
+ y2 = _mm256_mul_ps(y2, z);
504
+ y2 = _mm256_mul_ps(y2, x);
505
+ y2 = _mm256_add_ps(y2, x);
506
+
507
+ /* select the correct result from the two polynoms */
508
+ xmm3 = poly_mask;
509
+ v8sf ysin2 = _mm256_and_ps(xmm3, y2);
510
+ v8sf ysin1 = _mm256_andnot_ps(xmm3, y);
511
+ y2 = _mm256_sub_ps(y2,ysin2);
512
+ y = _mm256_sub_ps(y, ysin1);
513
+
514
+ xmm1 = _mm256_add_ps(ysin1,ysin2);
515
+ xmm2 = _mm256_add_ps(y,y2);
516
+
517
+ /* update the sign */
518
+ *s = _mm256_xor_ps(xmm1, sign_bit_sin);
519
+ *c = _mm256_xor_ps(xmm2, sign_bit_cos);
520
+ }
521
+
522
+ #endif // CPU_CAPABILITY_AVX2
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/int_mm_kernel.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace at::native {
7
+
8
+ using weight_to_int4pack_fn = void (*)(const Tensor&, const Tensor&);
9
+ using int4pack_mm_fn =
10
+ void (*)(const Tensor&, const Tensor&, const Tensor&, int, const Tensor&);
11
+ using int8pack_mm_fn =
12
+ void (*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&);
13
+ using dyn_quant_pack_4bit_weight_fn = void (*)(
14
+ Tensor&,
15
+ const Tensor&,
16
+ const Tensor&,
17
+ const std::optional<Tensor>& bias,
18
+ const int64_t,
19
+ const int64_t,
20
+ const int64_t);
21
+ using dyn_quant_matmul_4bit_fn = void (*)(
22
+ const Tensor&,
23
+ const Tensor&,
24
+ const Tensor&,
25
+ const int64_t,
26
+ const int64_t,
27
+ const int64_t,
28
+ const int64_t);
29
+
30
+ DECLARE_DISPATCH(weight_to_int4pack_fn, weight_to_int4pack_stub)
31
+ DECLARE_DISPATCH(int4pack_mm_fn, int4pack_mm_stub)
32
+ DECLARE_DISPATCH(int8pack_mm_fn, int8pack_mm_stub)
33
+ DECLARE_DISPATCH(
34
+ dyn_quant_pack_4bit_weight_fn,
35
+ dyn_quant_pack_4bit_weight_stub)
36
+ DECLARE_DISPATCH(dyn_quant_matmul_4bit_fn, dyn_quant_matmul_4bit_stub)
37
+
38
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/mixed_data_type.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace at::native {
6
+
7
+ inline ScalarType first_type() {
8
+ return ScalarType::Undefined;
9
+ }
10
+
11
+ template <typename... Args>
12
+ inline ScalarType first_type(const Tensor& arg, const Args&... parameters) {
13
+ return arg.defined() ? arg.scalar_type() : first_type(parameters...);
14
+ }
15
+
16
+ template <typename... Args>
17
+ inline bool is_mixed_type(const Tensor& input, const Args&... parameters) {
18
+ const auto parameter_type = first_type(parameters...);
19
+ return ((parameter_type != ScalarType::Undefined) &&
20
+ (parameter_type != input.scalar_type()));
21
+ }
22
+
23
+ // currently on CPU, mixed data type is only supported
24
+ // when input is 'BFloat16' or 'Half' and parameters are 'Float'
25
+ inline void check_mixed_data_type(const Tensor& input) {
26
+ TORCH_CHECK(at::isReducedFloatingType(input.scalar_type()),
27
+ "mixed dtype (CPU): all inputs must share same datatype.");
28
+ }
29
+
30
+ template <typename... Args>
31
+ inline void check_mixed_data_type(const Tensor& input, const Tensor& parameter, const Args&... parameters) {
32
+ TORCH_CHECK(!parameter.defined() || parameter.scalar_type() == ScalarType::Float,
33
+ "mixed dtype (CPU): expect parameter to have scalar type of Float");
34
+ check_mixed_data_type(input, parameters...);
35
+ }
36
+
37
+ inline ScalarType param_scalar_type(const Tensor& t, bool is_mixed_type) {
38
+ return is_mixed_type ? ScalarType::Float : t.scalar_type();
39
+ }
40
+
41
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/moments_utils.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <array>
4
+ #include <cstring>
5
+ #include <utility>
6
+
7
+ #include <ATen/Parallel.h>
8
+ #include <ATen/OpMathType.h>
9
+ #include <ATen/cpu/vec/vec.h>
10
+ #include <ATen/native/cpu/utils.h>
11
+ #include <c10/util/SmallVector.h>
12
+ #include <c10/util/irange.h>
13
+
14
+ namespace at::native {
15
+ inline namespace CPU_CAPABILITY {
16
+
17
+ template<typename T> using opmath_t = at::opmath_type<T>;
18
+
19
+ constexpr int64_t kChunkSize = 16;
20
+
21
+ template <typename T>
22
+ void AddMoments(
23
+ int64_t m0_add,
24
+ const T& m1_add,
25
+ const T& m2_add,
26
+ int64_t& m0,
27
+ T& m1,
28
+ T& m2) {
29
+ const int64_t n = m0 + m0_add;
30
+ const T c = n == 0 ? static_cast<T>(0) : static_cast<T>(m0_add) / static_cast<T>(n);
31
+ const T delta = m1_add - m1;
32
+ m1 += c * delta;
33
+ m2 += m2_add + delta * delta * c * static_cast<T>(m0);
34
+ m0 = n;
35
+ }
36
+
37
+ template <typename T>
38
+ C10_ALWAYS_INLINE void AddMomentsVec(
39
+ int64_t m0_add,
40
+ const vec::Vectorized<T>& m1_add,
41
+ const vec::Vectorized<T>& m2_add,
42
+ int64_t& m0,
43
+ vec::Vectorized<T>& m1,
44
+ vec::Vectorized<T>& m2) {
45
+ using Vec = vec::Vectorized<T>;
46
+ const int64_t n = m0 + m0_add;
47
+ const T c = n == 0 ? static_cast<T>(0) : static_cast<T>(m0_add) / static_cast<T>(n);
48
+ const Vec c_vec(c);
49
+ const Vec delta = m1_add - m1;
50
+ m1 += c_vec * delta;
51
+ m2 += m2_add + delta * delta * c_vec * Vec(static_cast<T>(m0));
52
+ m0 = n;
53
+ }
54
+
55
+ template <typename T>
56
+ inline std::enable_if_t<std::is_same_v<T, opmath_t<T>>, void>
57
+ UpdateMomentsVec(
58
+ int64_t m0,
59
+ const T* X_ptr,
60
+ const std::array<vec::Vectorized<opmath_t<T>>, kChunkSize>& c_vecs,
61
+ int64_t& m0_stk0,
62
+ vec::Vectorized<opmath_t<T>>& m1_stk0,
63
+ vec::Vectorized<opmath_t<T>>& m2_stk0) {
64
+ using Vec = vec::Vectorized<opmath_t<T>>;
65
+ Vec m1_vec(0);
66
+ Vec m2_vec(0);
67
+ for (const auto j : c10::irange(m0)) {
68
+ const Vec x_vec = Vec::loadu(X_ptr + j * Vec::size());
69
+ const Vec delta_vec = x_vec - m1_vec;
70
+ m1_vec += delta_vec * c_vecs[j];
71
+ m2_vec += delta_vec * (x_vec - m1_vec);
72
+ }
73
+ AddMomentsVec(m0, m1_vec, m2_vec, m0_stk0, m1_stk0, m2_stk0);
74
+ }
75
+
76
+ // each bfloat16/half vector will be converted to two float vectors,
77
+ // and accumulated successively on m1_stk0/m2_stk0.
78
+ template <typename T>
79
+ inline std::enable_if_t<!std::is_same_v<T, at::opmath_type<T>>, void>
80
+ UpdateMomentsVec(
81
+ int64_t m0,
82
+ const T* X_ptr,
83
+ const std::array<vec::Vectorized<at::opmath_type<T>>, kChunkSize>& c_vecs,
84
+ int64_t& m0_stk0,
85
+ vec::Vectorized<at::opmath_type<T>>& m1_stk0,
86
+ vec::Vectorized<at::opmath_type<T>>& m2_stk0) {
87
+ using Vec = vec::Vectorized<T>;
88
+ using fVec = vec::Vectorized<at::opmath_type<T>>;
89
+ fVec m1_fvec0(0), m1_fvec1(0);
90
+ fVec m2_fvec0(0), m2_fvec1(0);
91
+ for (const auto j : c10::irange(m0)) {
92
+ const Vec x_bvec = Vec::loadu(X_ptr + j * Vec::size());
93
+ auto [x_fvec0, x_fvec1] = convert_to_float<T>(x_bvec);
94
+ const fVec delta_fvec0 = x_fvec0 - m1_fvec0;
95
+ const fVec delta_fvec1 = x_fvec1 - m1_fvec1;
96
+ m1_fvec0 += delta_fvec0 * c_vecs[j];
97
+ m1_fvec1 += delta_fvec1 * c_vecs[j];
98
+ m2_fvec0 += delta_fvec0 * (x_fvec0 - m1_fvec0);
99
+ m2_fvec1 += delta_fvec1 * (x_fvec1 - m1_fvec1);
100
+ }
101
+ AddMomentsVec(m0, m1_fvec0, m2_fvec0, m0_stk0, m1_stk0, m2_stk0);
102
+ AddMomentsVec(m0, m1_fvec1, m2_fvec1, m0_stk0, m1_stk0, m2_stk0);
103
+ }
104
+
105
+ // Compute rowwise moments by Welford algorithm and cascade sum to improve
106
+ // numerical stability.
107
+ // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
108
+ // https://en.wikipedia.org/wiki/Pairwise_summation
109
+ template <typename T, int64_t kMaxDepth>
110
+ std::pair<opmath_t<T>, opmath_t<T>> RowwiseMomentsImpl(const T* X, int64_t N, int64_t ddof = 0) {
111
+ using math_t = opmath_t<T>;
112
+
113
+ constexpr int64_t kVecSize = vec::Vectorized<T>::size();
114
+ constexpr int64_t kAccVecSize = vec::Vectorized<math_t>::size();
115
+ const int64_t n = N / kVecSize;
116
+ const int64_t m = divup(n, kChunkSize);
117
+ const int64_t depth = utils::CeilLog2(m);
118
+
119
+ using Vec = vec::Vectorized<math_t>;
120
+ const Vec kZeroVec(math_t(0));
121
+ c10::SmallVector<int64_t, kMaxDepth> m0_stk(depth, 0);
122
+ c10::SmallVector<Vec, kMaxDepth> m1_stk(depth, kZeroVec);
123
+ c10::SmallVector<Vec, kMaxDepth> m2_stk(depth, kZeroVec);
124
+
125
+ for (const auto i : c10::irange(m)) {
126
+ const T* X_ptr = X + i * kChunkSize * kVecSize;
127
+ const int64_t m0 = std::min(kChunkSize, n - i * kChunkSize);
128
+ static std::array<Vec, kChunkSize> c_vecs = ([]() {
129
+ std::array<Vec, kChunkSize> result;
130
+ for (const auto i : c10::irange(kChunkSize)) {
131
+ result[i] = Vec(math_t(1) / static_cast<math_t>(i + 1));
132
+ }
133
+ return result;
134
+ })();
135
+ UpdateMomentsVec(m0, X_ptr, c_vecs, m0_stk[0], m1_stk[0], m2_stk[0]);
136
+
137
+ int64_t mask = i + 1;
138
+ for (int64_t j = 1; j < depth && (mask & 1) == 0; ++j) {
139
+ AddMomentsVec(
140
+ m0_stk[j - 1],
141
+ m1_stk[j - 1],
142
+ m2_stk[j - 1],
143
+ m0_stk[j],
144
+ m1_stk[j],
145
+ m2_stk[j]);
146
+ m0_stk[j - 1] = 0;
147
+ m1_stk[j - 1] = kZeroVec;
148
+ m2_stk[j - 1] = kZeroVec;
149
+ mask >>= 1;
150
+ }
151
+ }
152
+ for (const auto i : c10::irange(1, depth)) {
153
+ AddMomentsVec(
154
+ m0_stk[i], m1_stk[i], m2_stk[i], m0_stk[0], m1_stk[0], m2_stk[0]);
155
+ }
156
+
157
+ std::array<math_t, kAccVecSize> m1_arr{};
158
+ std::array<math_t, kAccVecSize> m2_arr{};
159
+ m1_stk[0].store(m1_arr.data());
160
+ m2_stk[0].store(m2_arr.data());
161
+
162
+ int64_t m0 = 0;
163
+ math_t m1 = 0;
164
+ math_t m2 = 0;
165
+ for (int64_t i = n * kVecSize; i < N; ++i) {
166
+ math_t x = static_cast<math_t>(X[i]);
167
+ const math_t delta = x - m1;
168
+ ++m0;
169
+ m1 += delta / static_cast<math_t>(m0);
170
+ m2 += delta * (x - m1);
171
+ }
172
+ // for BFloat16, each vector in m1_arr/m2_arr holds 2*n accumulated result
173
+ int64_t m0_add = n * kVecSize / kAccVecSize;
174
+ for (const auto i : c10::irange(kAccVecSize)) {
175
+ AddMoments(m0_add, m1_arr[i], m2_arr[i], m0, m1, m2);
176
+ }
177
+
178
+ return std::make_pair(m1, m2 / static_cast<math_t>(N - ddof));
179
+ }
180
+
181
+ template <typename T>
182
+ std::pair<opmath_t<T>, opmath_t<T>> RowwiseMoments(const T* X, int64_t N, int64_t ddof = 0) {
183
+ using Vec = vec::Vectorized<T>;
184
+ constexpr int64_t kVecSize = Vec::size();
185
+ const int64_t n = N / kVecSize;
186
+ const int64_t m = divup(n, kChunkSize);
187
+ const int64_t depth = utils::CeilLog2(m);
188
+ if (depth <= 4) {
189
+ return RowwiseMomentsImpl<T, 4>(X, N, ddof);
190
+ } else if (depth <= 8) {
191
+ return RowwiseMomentsImpl<T, 8>(X, N, ddof);
192
+ } else if (depth <= 16) {
193
+ return RowwiseMomentsImpl<T, 16>(X, N, ddof);
194
+ } else if (depth <= 32) {
195
+ return RowwiseMomentsImpl<T, 32>(X, N, ddof);
196
+ } else {
197
+ return RowwiseMomentsImpl<T, 64>(X, N, ddof);
198
+ }
199
+ }
200
+
201
+ } // namespace CPU_CAPABILITY
202
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/utils.h ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Parallel.h>
4
+ #include <ATen/core/TensorAccessor.h>
5
+ #include <ATen/cpu/vec/vec.h>
6
+ #include <c10/util/llvmMathExtras.h>
7
+
8
+ #ifdef USE_FBGEMM
9
+ #include <fbgemm/Fbgemm.h>
10
+ #endif
11
+
12
+ namespace at::native {
13
+
14
+ template <typename T>
15
+ inline void _store(T* dst, at::vec::Vectorized<T> src) {
16
+ src.store(dst);
17
+ }
18
+
19
+ inline void _store(at::BFloat16* dst, at::vec::Vectorized<float> src) {
20
+ auto res = at::vec::convert_float_bfloat16(src, src);
21
+ res.store(dst, at::vec::Vectorized<float>::size());
22
+ }
23
+
24
+ inline void _store(at::Half* dst, at::vec::Vectorized<float> src) {
25
+ auto res = at::vec::convert_float_half(src, src);
26
+ res.store(dst, at::vec::Vectorized<float>::size());
27
+ }
28
+
29
+ inline namespace CPU_CAPABILITY {
30
+
31
+ template <typename T>
32
+ inline T data_index_init(T offset) {
33
+ return offset;
34
+ }
35
+
36
+ template <typename T, typename... Args>
37
+ inline T data_index_init(T offset, T& x, const T& X, Args&&... args) {
38
+ offset = data_index_init(offset, std::forward<Args>(args)...);
39
+ x = offset % X;
40
+ return offset / X;
41
+ }
42
+
43
+ inline bool data_index_step() {
44
+ return true;
45
+ }
46
+
47
+ template <typename T, typename... Args>
48
+ inline bool data_index_step(T& x, const T& X, Args&&... args) {
49
+ if (data_index_step(std::forward<Args>(args)...)) {
50
+ x = ((x + 1) == X) ? 0 : (x + 1);
51
+ return x == 0;
52
+ }
53
+ return false;
54
+ }
55
+
56
+ // Helper struct for bfloat16/float16 vectorization
57
+ // Useful when you need float as immediate dtype or accumulate dtype
58
+ using namespace vec;
59
+ struct Vec2 {
60
+ Vectorized<float> val0, val1;
61
+ Vec2(Vectorized<float> v0, Vectorized<float> v1) : val0(v0), val1(v1) {}
62
+ Vec2(float v) : val0(v), val1(v) {}
63
+ static Vec2 loadu(const BFloat16* ptr) {
64
+ auto [v0, v1] = convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr));
65
+ return {v0, v1};
66
+ }
67
+ static Vec2 loadu(const Half* ptr) {
68
+ auto [v0, v1] = convert_half_float(Vectorized<Half>::loadu(ptr));
69
+ return {v0, v1};
70
+ }
71
+ static Vec2 loadu(const float* ptr) {
72
+ return {Vectorized<float>::loadu(ptr), Vectorized<float>::loadu(ptr + Vectorized<float>::size())};
73
+ }
74
+ void store(BFloat16* ptr) const {
75
+ Vectorized<BFloat16> val = convert_float_bfloat16(val0, val1);
76
+ val.store(ptr);
77
+ }
78
+ void store(Half* ptr) const {
79
+ Vectorized<Half> val = convert_float_half(val0, val1);
80
+ val.store(ptr);
81
+ }
82
+ void store(float* ptr) const {
83
+ val0.store(ptr);
84
+ val1.store(ptr + Vectorized<float>::size());
85
+ }
86
+ };
87
+ inline Vec2 operator+(const Vec2& a, const Vec2& b) { return {a.val0 + b.val0, a.val1 + b.val1}; }
88
+ inline Vec2 operator*(const Vec2& a, const Vec2& b) { return {a.val0 * b.val0, a.val1 * b.val1}; }
89
+ inline Vec2 operator-(const Vec2& a, const Vec2& b) { return {a.val0 - b.val0, a.val1 - b.val1}; }
90
+ inline Vec2 operator/(const Vec2& a, const Vec2& b) { return {a.val0 / b.val0, a.val1 / b.val1}; }
91
+ inline Vec2 maximum(const Vec2& a, const Vec2& b) { return {vec::maximum(a.val0, b.val0), vec::maximum(a.val1, b.val1)}; }
92
+ inline Vec2 minimum(const Vec2& a, const Vec2& b) { return {vec::minimum(a.val0, b.val0), vec::minimum(a.val1, b.val1)}; }
93
+
94
+ template <typename scalar_t> struct VectorizedType { using type = Vectorized<scalar_t>; };
95
+ template <> struct VectorizedType<BFloat16> { using type = Vec2; };
96
+ template <> struct VectorizedType<Half> { using type = Vec2; };
97
+ template <typename scalar_t> using VecType = typename VectorizedType<scalar_t>::type;
98
+
99
+ // Helper for mixed data type parameter Vec::load
100
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const BFloat16* ptr) {
101
+ return convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr));
102
+ }
103
+
104
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const Half* ptr) {
105
+ return convert_half_float(Vectorized<Half>::loadu(ptr));
106
+ }
107
+
108
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const float* ptr) {
109
+ using Vec = Vectorized<float>;
110
+ return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size()));
111
+ }
112
+
113
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const BFloat16* ptr, int64_t count) {
114
+ return convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr, count));
115
+ }
116
+
117
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const Half* ptr, int64_t count) {
118
+ return convert_half_float(Vectorized<Half>::loadu(ptr, count));
119
+ }
120
+
121
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const float* ptr, int64_t count) {
122
+ using Vec = Vectorized<float>;
123
+ if (count > Vec::size()) {
124
+ return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size(), count - Vec::size()));
125
+ } else {
126
+ return std::make_tuple(Vec::loadu(ptr, count), Vec(0));
127
+ }
128
+ }
129
+
130
+ } // namespace
131
+
132
+ namespace utils {
133
+
134
+ template <typename T>
135
+ T CeilLog2(const T& x) {
136
+ if (x <= 2) {
137
+ return 1;
138
+ }
139
+ // Last set bit is floor(log2(x)), floor + 1 is ceil
140
+ // except when x is an exact powers of 2, so subtract 1 first
141
+ return static_cast<T>(llvm::findLastSet(static_cast<uint64_t>(x) - 1)) + 1;
142
+ }
143
+
144
+ // matrix transpose:
145
+ // src has shape of M by N, with leading dimension of ld_src
146
+ // dst has shape of N by M, with leading dimension of ld_dst
147
+ template <typename T>
148
+ inline void transpose(int64_t M, int64_t N, const T* src, int64_t ld_src, T* dst, int64_t ld_dst) {
149
+ for (int64_t j = 0; j < N; j++) {
150
+ for (int64_t i = 0; i < M; i++) {
151
+ dst[j * ld_dst + i] = c10::load(&(src[i * ld_src + j]));
152
+ }
153
+ }
154
+ }
155
+
156
+ #ifdef USE_FBGEMM
157
+ template <>
158
+ inline void transpose<float>(int64_t M, int64_t N, const float* src, int64_t ld_src, float* dst, int64_t ld_dst) {
159
+ TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM.");
160
+ fbgemm::transpose_simd<float>(M, N, src, ld_src, dst, ld_dst);
161
+ }
162
+
163
+ template <>
164
+ inline void transpose<uint16_t>(int64_t M, int64_t N, const uint16_t* src, int64_t ld_src, uint16_t* dst, int64_t ld_dst) {
165
+ TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM.");
166
+ fbgemm::transpose_simd<uint16_t>(M, N, src, ld_src, dst, ld_dst);
167
+ }
168
+ #endif
169
+
170
+ template <typename index_t, typename F>
171
+ inline void parallel_sparse_csr(
172
+ const TensorAccessor<index_t, 1>& crow_acc,
173
+ const int64_t M,
174
+ const int64_t nnz,
175
+ const F& f) {
176
+ TORCH_CHECK(crow_acc.size(0) == M + 1);
177
+
178
+ // directly parallel on `M` may lead to load imbalance,
179
+ // statically determine thread partition here to average payload
180
+ // for each thread.
181
+ int num_threads = at::get_num_threads();
182
+ std::vector<int64_t> thread_splits(num_threads + 1, M);
183
+
184
+ int64_t thread_averge_payload = std::max((int64_t)1, divup(nnz, num_threads));
185
+
186
+ thread_splits[0] = 0;
187
+ int64_t sum = 0;
188
+ int64_t t = 1;
189
+ for (const auto m : c10::irange(M)) {
190
+ int64_t row_start = crow_acc[m];
191
+ int64_t row_end = crow_acc[m + 1];
192
+ sum += row_end - row_start;
193
+ if (sum > t * thread_averge_payload) {
194
+ thread_splits[t] = m;
195
+ t++;
196
+ }
197
+ }
198
+ // need to restore the last index,
199
+ // due to rounding error when calculating `thread_averge_payload`.
200
+ thread_splits[num_threads] = M;
201
+
202
+ at::parallel_for(0, num_threads, 1, [&](int64_t cbegin, int64_t cend) {
203
+ int tid = at::get_thread_num();
204
+ int64_t begin = thread_splits[tid];
205
+ int64_t end = thread_splits[tid + 1];
206
+ f(begin, end);
207
+ });
208
+ }
209
+
210
+ } // namespace utils
211
+
212
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cpu/zmath.h ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Complex number math operations that act as no-ops for other dtypes.
4
+ #include <c10/util/complex.h>
5
+ #include <c10/util/MathConstants.h>
6
+ #include<ATen/NumericUtils.h>
7
+
8
+ namespace at::native {
9
+ inline namespace CPU_CAPABILITY {
10
+
11
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
12
+ inline VALUE_TYPE zabs (SCALAR_TYPE z) {
13
+ return z;
14
+ }
15
+
16
+ template<>
17
+ inline c10::complex<float> zabs <c10::complex<float>> (c10::complex<float> z) {
18
+ return c10::complex<float>(std::abs(z));
19
+ }
20
+
21
+ template<>
22
+ inline float zabs <c10::complex<float>, float> (c10::complex<float> z) {
23
+ return std::abs(z);
24
+ }
25
+
26
+ template<>
27
+ inline c10::complex<double> zabs <c10::complex<double>> (c10::complex<double> z) {
28
+ return c10::complex<double>(std::abs(z));
29
+ }
30
+
31
+ template<>
32
+ inline double zabs <c10::complex<double>, double> (c10::complex<double> z) {
33
+ return std::abs(z);
34
+ }
35
+
36
+ // This overload corresponds to non-complex dtypes.
37
+ // The function is consistent with its NumPy equivalent
38
+ // for non-complex dtypes where `pi` is returned for
39
+ // negative real numbers and `0` is returned for 0 or positive
40
+ // real numbers.
41
+ // Note: `nan` is propagated.
42
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
43
+ inline VALUE_TYPE angle_impl (SCALAR_TYPE z) {
44
+ if (at::_isnan(z)) {
45
+ return z;
46
+ }
47
+ return z < 0 ? c10::pi<double> : 0;
48
+ }
49
+
50
+ template<>
51
+ inline c10::complex<float> angle_impl <c10::complex<float>> (c10::complex<float> z) {
52
+ return c10::complex<float>(std::arg(z), 0.0);
53
+ }
54
+
55
+ template<>
56
+ inline float angle_impl <c10::complex<float>, float> (c10::complex<float> z) {
57
+ return std::arg(z);
58
+ }
59
+
60
+ template<>
61
+ inline c10::complex<double> angle_impl <c10::complex<double>> (c10::complex<double> z) {
62
+ return c10::complex<double>(std::arg(z), 0.0);
63
+ }
64
+
65
+ template<>
66
+ inline double angle_impl <c10::complex<double>, double> (c10::complex<double> z) {
67
+ return std::arg(z);
68
+ }
69
+
70
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
71
+ constexpr VALUE_TYPE real_impl (SCALAR_TYPE z) {
72
+ return z; //No-Op
73
+ }
74
+
75
+ template<>
76
+ constexpr c10::complex<float> real_impl <c10::complex<float>> (c10::complex<float> z) {
77
+ return c10::complex<float>(z.real(), 0.0);
78
+ }
79
+
80
+ template<>
81
+ constexpr float real_impl <c10::complex<float>, float> (c10::complex<float> z) {
82
+ return z.real();
83
+ }
84
+
85
+ template<>
86
+ constexpr c10::complex<double> real_impl <c10::complex<double>> (c10::complex<double> z) {
87
+ return c10::complex<double>(z.real(), 0.0);
88
+ }
89
+
90
+ template<>
91
+ constexpr double real_impl <c10::complex<double>, double> (c10::complex<double> z) {
92
+ return z.real();
93
+ }
94
+
95
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
96
+ constexpr VALUE_TYPE imag_impl (SCALAR_TYPE /*z*/) {
97
+ return 0;
98
+ }
99
+
100
+ template<>
101
+ constexpr c10::complex<float> imag_impl <c10::complex<float>> (c10::complex<float> z) {
102
+ return c10::complex<float>(z.imag(), 0.0);
103
+ }
104
+
105
+ template<>
106
+ constexpr float imag_impl <c10::complex<float>, float> (c10::complex<float> z) {
107
+ return z.imag();
108
+ }
109
+
110
+ template<>
111
+ constexpr c10::complex<double> imag_impl <c10::complex<double>> (c10::complex<double> z) {
112
+ return c10::complex<double>(z.imag(), 0.0);
113
+ }
114
+
115
+ template<>
116
+ constexpr double imag_impl <c10::complex<double>, double> (c10::complex<double> z) {
117
+ return z.imag();
118
+ }
119
+
120
+ template <typename TYPE>
121
+ inline TYPE conj_impl (TYPE z) {
122
+ return z; //No-Op
123
+ }
124
+
125
+ template<>
126
+ inline c10::complex<at::Half> conj_impl <c10::complex<at::Half>> (c10::complex<at::Half> z) {
127
+ return c10::complex<at::Half>{z.real(), -z.imag()};
128
+ }
129
+
130
+ template<>
131
+ inline c10::complex<float> conj_impl <c10::complex<float>> (c10::complex<float> z) {
132
+ return c10::complex<float>(z.real(), -z.imag());
133
+ }
134
+
135
+ template<>
136
+ inline c10::complex<double> conj_impl <c10::complex<double>> (c10::complex<double> z) {
137
+ return c10::complex<double>(z.real(), -z.imag());
138
+ }
139
+
140
+ template <typename TYPE>
141
+ inline TYPE ceil_impl (TYPE z) {
142
+ return std::ceil(z);
143
+ }
144
+
145
+ template <>
146
+ inline c10::complex<float> ceil_impl (c10::complex<float> z) {
147
+ return c10::complex<float>(std::ceil(z.real()), std::ceil(z.imag()));
148
+ }
149
+
150
+ template <>
151
+ inline c10::complex<double> ceil_impl (c10::complex<double> z) {
152
+ return c10::complex<double>(std::ceil(z.real()), std::ceil(z.imag()));
153
+ }
154
+
155
+ template<typename T>
156
+ inline c10::complex<T> sgn_impl (c10::complex<T> z) {
157
+ if (z == c10::complex<T>(0, 0)) {
158
+ return c10::complex<T>(0, 0);
159
+ } else {
160
+ return z / zabs(z);
161
+ }
162
+ }
163
+
164
+ template <typename TYPE>
165
+ inline TYPE floor_impl (TYPE z) {
166
+ return std::floor(z);
167
+ }
168
+
169
+ template <>
170
+ inline c10::complex<float> floor_impl (c10::complex<float> z) {
171
+ return c10::complex<float>(std::floor(z.real()), std::floor(z.imag()));
172
+ }
173
+
174
+ template <>
175
+ inline c10::complex<double> floor_impl (c10::complex<double> z) {
176
+ return c10::complex<double>(std::floor(z.real()), std::floor(z.imag()));
177
+ }
178
+
179
+ template <typename TYPE>
180
+ inline TYPE round_impl (TYPE z) {
181
+ return std::nearbyint(z);
182
+ }
183
+
184
+ template <>
185
+ inline c10::complex<float> round_impl (c10::complex<float> z) {
186
+ return c10::complex<float>(std::nearbyint(z.real()), std::nearbyint(z.imag()));
187
+ }
188
+
189
+ template <>
190
+ inline c10::complex<double> round_impl (c10::complex<double> z) {
191
+ return c10::complex<double>(std::nearbyint(z.real()), std::nearbyint(z.imag()));
192
+ }
193
+
194
+ template <typename TYPE>
195
+ inline TYPE trunc_impl (TYPE z) {
196
+ return std::trunc(z);
197
+ }
198
+
199
+ template <>
200
+ inline c10::complex<float> trunc_impl (c10::complex<float> z) {
201
+ return c10::complex<float>(std::trunc(z.real()), std::trunc(z.imag()));
202
+ }
203
+
204
+ template <>
205
+ inline c10::complex<double> trunc_impl (c10::complex<double> z) {
206
+ return c10::complex<double>(std::trunc(z.real()), std::trunc(z.imag()));
207
+ }
208
+
209
+ template <typename TYPE, std::enable_if_t<!c10::is_complex<TYPE>::value, int> = 0>
210
+ inline TYPE max_impl (TYPE a, TYPE b) {
211
+ if (_isnan<TYPE>(a) || _isnan<TYPE>(b)) {
212
+ return std::numeric_limits<TYPE>::quiet_NaN();
213
+ } else {
214
+ return std::max(a, b);
215
+ }
216
+ }
217
+
218
+ template <typename TYPE, std::enable_if_t<c10::is_complex<TYPE>::value, int> = 0>
219
+ inline TYPE max_impl (TYPE a, TYPE b) {
220
+ if (_isnan<TYPE>(a)) {
221
+ return a;
222
+ } else if (_isnan<TYPE>(b)) {
223
+ return b;
224
+ } else {
225
+ return std::abs(a) > std::abs(b) ? a : b;
226
+ }
227
+ }
228
+
229
+ template <typename TYPE, std::enable_if_t<!c10::is_complex<TYPE>::value, int> = 0>
230
+ inline TYPE min_impl (TYPE a, TYPE b) {
231
+ if (_isnan<TYPE>(a) || _isnan<TYPE>(b)) {
232
+ return std::numeric_limits<TYPE>::quiet_NaN();
233
+ } else {
234
+ return std::min(a, b);
235
+ }
236
+ }
237
+
238
+ template <typename TYPE, std::enable_if_t<c10::is_complex<TYPE>::value, int> = 0>
239
+ inline TYPE min_impl (TYPE a, TYPE b) {
240
+ if (_isnan<TYPE>(a)) {
241
+ return a;
242
+ } else if (_isnan<TYPE>(b)) {
243
+ return b;
244
+ } else {
245
+ return std::abs(a) < std::abs(b) ? a : b;
246
+ }
247
+ }
248
+
249
+ } // end namespace
250
+ } //end at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/Activation.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/Activation.h>
3
+ #include <cstdint>
4
+
5
+ namespace at {
6
+ struct TensorIteratorBase;
7
+ class TensorBase;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ void launch_glu_backward_kernel(const TensorIteratorBase& iter,
13
+ int64_t gI_stride, int64_t I_stride);
14
+
15
+ void launch_log_sigmoid_forward_kernel(TensorIteratorBase& iter);
16
+
17
+ void GeluCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate);
18
+ void GeluBackwardCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate);
19
+
20
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/cuda/BinaryInternal.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // DON'T include this except from Binary*.cu files. It should not leak into
2
+ // headers.
3
+ #pragma once
4
+ #define TORCH_ASSERT_NO_OPERATORS
5
+ #include <ATen/AccumulateType.h>
6
+ #include <ATen/Dispatch.h>
7
+ #include <ATen/native/BinaryOps.h>
8
+ #include <ATen/native/DispatchStub.h>
9
+ #include <ATen/native/TensorIterator.h>
10
+ #include <c10/cuda/CUDAGuard.h>
11
+ #include <c10/cuda/CUDAMathCompat.h>
12
+ #include <c10/util/TypeSafeSignMath.h>
13
+ #include <ATen/native/cuda/JitLoops.cuh>
14
+ #include <ATen/native/cuda/Loops.cuh>
15
+
16
+ #include <type_traits>
17
+
18
+ namespace at::native::binary_internal {
19
+
20
+ template <typename scalar_t>
21
+ struct DivFunctor {
22
+ __device__ scalar_t operator()(scalar_t a, scalar_t b) const {
23
+ return a / b;
24
+ }
25
+ };
26
+
27
+ template <typename T>
28
+ struct MulFunctor {
29
+ __device__ T operator()(T a, T b) const {
30
+ return a * b;
31
+ }
32
+ };
33
+
34
+ // Workaround for the error: '*' in boolean context, suggest '&&' instead
35
+ // [-Werror=int-in-bool-context]
36
+ template <>
37
+ struct MulFunctor<bool> {
38
+ __device__ bool operator()(bool a, bool b) const {
39
+ return a && b;
40
+ }
41
+ };
42
+ void div_true_kernel_cuda(TensorIteratorBase& iter);
43
+ void div_trunc_kernel_cuda(TensorIteratorBase& iter);
44
+ } // namespace at::native::binary_internal