ADAPT-Chase commited on
Commit
93db040
·
verified ·
1 Parent(s): 544cd04

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/native/PixelShuffle.h +46 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/PointwiseOps.h +28 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Pool.h +361 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Pow.h +69 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RNN.h +53 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RangeFactories.h +12 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RangeUtils.h +45 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceAllOps.h +16 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceOps.h +56 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceOpsUtils.h +468 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReductionType.h +40 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Repeat.h +48 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Resize.h +205 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ResizeCommon.h +75 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ScatterGatherChecks.h +128 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SegmentReduce.h +50 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SharedReduceOps.h +545 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SobolEngineOpsUtils.h +55 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Sorting.h +28 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SortingUtils.h +88 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SparseTensorUtils.h +190 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SpectralOpsUtils.h +84 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/StridedRandomAccessor.h +301 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorAdvancedIndexing.h +102 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorAdvancedIndexingUtils.h +109 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorCompare.h +56 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorConversions.h +31 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorDimApply.h +67 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorFactories.h +169 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorIterator.h +2 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorIteratorDynamicCasting.h +52 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorProperties.h +12 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorShape.h +145 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorTransformations.h +35 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TopKImpl.h +98 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TransposeType.h +23 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TriangularOpsUtils.h +57 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TypeProperties.h +20 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UnaryOps.h +129 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Unfold2d.h +48 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Unfold3d.h +49 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UnfoldBackward.h +110 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UpSample.h +510 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/batch_norm.h +38 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/group_norm.h +42 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/im2col.h +149 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/im2col_shape_check.h +232 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/layer_norm.h +141 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/verbose_wrapper.h +8 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/vol2col.h +109 -0
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/PixelShuffle.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+ #include <c10/util/Exception.h>
3
+
4
+ namespace at::native {
5
+
6
+ inline void check_pixel_shuffle_shapes(const Tensor& self, int64_t upscale_factor) {
7
+ TORCH_CHECK(self.dim() >= 3,
8
+ "pixel_shuffle expects input to have at least 3 dimensions, but got input with ",
9
+ self.dim(), " dimension(s)");
10
+ TORCH_CHECK(upscale_factor > 0,
11
+ "pixel_shuffle expects a positive upscale_factor, but got ",
12
+ upscale_factor);
13
+ int64_t c = self.size(-3);
14
+ int64_t upscale_factor_squared = upscale_factor * upscale_factor;
15
+ TORCH_CHECK(c % upscale_factor_squared == 0,
16
+ "pixel_shuffle expects its input's 'channel' dimension to be divisible by the square of "
17
+ "upscale_factor, but input.size(-3)=", c, " is not divisible by ", upscale_factor_squared);
18
+ }
19
+
20
+ inline void check_pixel_unshuffle_shapes(const Tensor& self, int64_t downscale_factor) {
21
+ TORCH_CHECK(
22
+ self.dim() >= 3,
23
+ "pixel_unshuffle expects input to have at least 3 dimensions, but got input with ",
24
+ self.dim(),
25
+ " dimension(s)");
26
+ TORCH_CHECK(
27
+ downscale_factor > 0,
28
+ "pixel_unshuffle expects a positive downscale_factor, but got ",
29
+ downscale_factor);
30
+ int64_t h = self.size(-2);
31
+ int64_t w = self.size(-1);
32
+ TORCH_CHECK(
33
+ h % downscale_factor == 0,
34
+ "pixel_unshuffle expects height to be divisible by downscale_factor, but input.size(-2)=",
35
+ h,
36
+ " is not divisible by ",
37
+ downscale_factor);
38
+ TORCH_CHECK(
39
+ w % downscale_factor == 0,
40
+ "pixel_unshuffle expects width to be divisible by downscale_factor, but input.size(-1)=",
41
+ w,
42
+ " is not divisible by ",
43
+ downscale_factor);
44
+ }
45
+
46
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/PointwiseOps.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Ternary and higher-order pointwise operations
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace c10 {
7
+ class Scalar;
8
+ }
9
+
10
+ namespace at {
11
+
12
+ struct TensorIterator;
13
+ struct TensorIteratorBase;
14
+
15
+ namespace native {
16
+
17
+ using pointwise_fn = void (*)(TensorIterator&, const Scalar& scalar);
18
+ using structured_pointwise_fn = void (*)(TensorIteratorBase&, const Scalar& scalar);
19
+ using pointwise_fn_double = void (*)(TensorIterator&, const Scalar&, double);
20
+
21
+ DECLARE_DISPATCH(structured_pointwise_fn, addcmul_stub)
22
+ DECLARE_DISPATCH(structured_pointwise_fn, addcdiv_stub)
23
+ DECLARE_DISPATCH(pointwise_fn_double, smooth_l1_backward_stub)
24
+ DECLARE_DISPATCH(pointwise_fn_double, huber_backward_stub)
25
+ DECLARE_DISPATCH(pointwise_fn, mse_backward_stub)
26
+
27
+ } // namespace native
28
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Pool.h ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+ #include <ATen/div_rtn.h>
3
+ #include <ATen/TensorUtils.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/irange.h>
6
+
7
+ #include <utility>
8
+
9
+ #pragma once
10
+
11
+ namespace at::native {
12
+
13
+ using max_pool2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input,
14
+ int kW, int kH, int dW, int dH, int padW, int padH, int dilationW, int dilationH);
15
+ using max_pool2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
16
+
17
+ DECLARE_DISPATCH(max_pool2d_fn, max_pool2d_kernel)
18
+ DECLARE_DISPATCH(max_pool2d_backward_fn, max_pool2d_backward_kernel)
19
+
20
+ // averge pooling has same signature for forward and backward
21
+ using avg_pool2d_fn = void(*)(const Tensor& output, const Tensor& input, int64_t kW, int64_t kH,
22
+ int64_t dW, int64_t dH, int64_t padW, int64_t padH, bool count_include_pad, std::optional<int64_t> divisor_override);
23
+ using avg_pool2d_backward_fn = void(*)(const Tensor& output, const Tensor& input, int kW, int kH,
24
+ int dW, int dH, int padW, int padH, bool count_include_pad, std::optional<int64_t> divisor_override);
25
+
26
+ DECLARE_DISPATCH(avg_pool2d_fn, avg_pool2d_kernel)
27
+ DECLARE_DISPATCH(avg_pool2d_backward_fn, avg_pool2d_backward_kernel)
28
+
29
+ // averge pooling has same signature for forward and backward
30
+ using avg_pool3d_fn = void(*)(const Tensor& output, const Tensor& input,
31
+ int64_t kW, int64_t kH, int64_t kD, int64_t dW, int64_t dH, int64_t dD,
32
+ int64_t padW, int64_t padH, int64_t padD, bool count_include_pad,
33
+ std::optional<int64_t> divisor_override);
34
+ using avg_pool3d_backward_fn = void(*)(const Tensor& output, const Tensor& input,
35
+ int kW, int kH, int kD, int dW, int dH, int dD,
36
+ int padW, int padH, int padD, bool count_include_pad,
37
+ std::optional<int64_t> divisor_override);
38
+
39
+ DECLARE_DISPATCH(avg_pool3d_fn, avg_pool3d_kernel)
40
+ DECLARE_DISPATCH(avg_pool3d_backward_fn, avg_pool3d_backward_kernel)
41
+
42
+ using max_pool3d_fn = void(*)(Tensor& output, Tensor& indices, const Tensor& input,
43
+ int kW, int kH, int kD, int dW, int dH, int dD, int pW, int pH, int pD, int dilationW, int dilationH, int dilationD);
44
+ using max_pool3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
45
+
46
+ DECLARE_DISPATCH(max_pool3d_fn, max_pool3d_kernel)
47
+ DECLARE_DISPATCH(max_pool3d_backward_fn, max_pool3d_backward_kernel)
48
+ namespace {
49
+
50
+ template <typename dest_t, typename src_t>
51
+ inline dest_t
52
+ safe_downcast(src_t v)
53
+ {
54
+ TORCH_CHECK(std::numeric_limits<dest_t>::min() <= v && v <= std::numeric_limits<dest_t>::max(),
55
+ "integer out of range");
56
+
57
+ return static_cast<dest_t>(v);
58
+ }
59
+
60
+ template<typename T>
61
+ inline T pooling_output_shape_pad_lr(
62
+ T inputSize, T kernelSize, T pad_l, T pad_r, T stride, T dilation,
63
+ bool ceil_mode) {
64
+ T outputSize = div_rtn<T>(
65
+ inputSize + pad_l + pad_r - dilation * (kernelSize - 1) - 1 +
66
+ (ceil_mode ? stride - 1 : 0), stride) + 1;
67
+ if (ceil_mode) {
68
+ // ensure that the last pooling starts inside the image
69
+ // needed to avoid problems in ceil mode
70
+ if ((outputSize - 1) * stride >= inputSize + pad_l) {
71
+ --outputSize;
72
+ }
73
+ }
74
+ return outputSize;
75
+ }
76
+
77
+ template<typename T>
78
+ inline T pooling_output_shape(
79
+ T inputSize, T kernelSize, T pad, T stride, T dilation, bool ceil_mode) {
80
+ TORCH_CHECK(stride != 0, "stride should not be zero");
81
+ TORCH_CHECK(pad >= 0,
82
+ "pad must be non-negative, but got pad: ", pad);
83
+ TORCH_CHECK(pad <= ((kernelSize - 1) * dilation + 1) / 2,
84
+ "pad should be at most half of effective kernel size, but got pad=",
85
+ pad, ", kernel_size=", kernelSize, " and dilation=", dilation)
86
+ return pooling_output_shape_pad_lr(
87
+ inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode);
88
+ }
89
+
90
+ template <typename T>
91
+ std::pair<T, T> _pooling_same_mode_padding_lr(
92
+ T inputSize, T kernelSize, T stride, T dilation) {
93
+ // NOTE: with strides, the output shape is ceil(inputSize/stride)
94
+ auto total_padding = T(dilation) * (kernelSize - 1);
95
+
96
+ // Prefer symmetric padding if possible
97
+ if (stride > 2 && (total_padding % 2 == 1)) {
98
+ // The floor in the output size calculation gives us a little wiggle room
99
+ auto wiggle_room = inputSize % stride - 1;
100
+ if (wiggle_room > 0) {
101
+ total_padding = total_padding - 1;
102
+ }
103
+ }
104
+
105
+ auto left = total_padding / 2;
106
+ return {left, total_padding - left};
107
+ }
108
+
109
+ inline std::pair<int64_t, int64_t> pooling_same_mode_padding_lr(
110
+ int64_t inputSize, int64_t kernelSize, int64_t stride, int64_t dilation) {
111
+ return _pooling_same_mode_padding_lr(inputSize, kernelSize, stride, dilation);
112
+ }
113
+
114
+ inline std::pair<c10::SymInt, c10::SymInt> pooling_same_mode_padding_lr(
115
+ c10::SymInt inputSize, c10::SymInt kernelSize, c10::SymInt stride, c10::SymInt dilation) {
116
+ return _pooling_same_mode_padding_lr(std::move(inputSize), std::move(kernelSize), std::move(stride), std::move(dilation));
117
+ }
118
+
119
+ // AveragePool2d/DilatedMaxPool2d (forward)
120
+ inline void
121
+ pool2d_shape_check(
122
+ const Tensor& input,
123
+ int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW, int64_t dilationH, int64_t dilationW,
124
+ int64_t nInputPlane,
125
+ int64_t inputHeight, int64_t inputWidth,
126
+ int64_t outputHeight, int64_t outputWidth, MemoryFormat memory_format)
127
+ {
128
+ const int64_t ndim = input.ndimension();
129
+ #ifndef STRIP_ERROR_MESSAGES
130
+ const int64_t nOutputPlane = nInputPlane;
131
+ #endif
132
+
133
+ TORCH_CHECK(kW > 0 && kH > 0,
134
+ "kernel size should be greater than zero, but got ",
135
+ "kH: ", kH, " kW: ", kW);
136
+ TORCH_CHECK(dW > 0 && dH > 0,
137
+ "stride should be greater than zero, but got "
138
+ "dH: ", dH, " dW: ", dW);
139
+ TORCH_CHECK(dilationH > 0 && dilationW > 0,
140
+ "dilation should be greater than zero, but got ",
141
+ "dilationH: ", dilationH, " dilationW: ", dilationW);
142
+
143
+ bool valid_dims = input.size(1) != 0 && input.size(2) != 0;
144
+ if (memory_format == at::MemoryFormat::ChannelsLast){
145
+ // Expect tensor in NHWC format and allow 0-dim only for N.
146
+ TORCH_CHECK((ndim == 4 && valid_dims && input.size(3) != 0),
147
+ "Expected 4D (batch mode) tensor expected for input with channels_last layout"
148
+ " with optional 0 dim batch size for input, but got: ", input.sizes());
149
+ } else {
150
+ TORCH_CHECK((ndim == 3 && input.size(0) != 0 && valid_dims) ||
151
+ (ndim == 4 && valid_dims && input.size(3) != 0),
152
+ "Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got:",
153
+ input.sizes());
154
+ }
155
+
156
+ TORCH_CHECK(kW/2 >= padW && kH/2 >= padH,
157
+ "pad should be smaller than or equal to half of kernel size, but got ",
158
+ "padW = ", padW, ", padH = ", padH, ", kW = ", kW, ", kH = ", kH);
159
+
160
+ TORCH_CHECK(outputWidth >= 1 && outputHeight >= 1,
161
+ "Given input size: (",
162
+ nInputPlane, "x", inputHeight, "x", inputWidth, "). ",
163
+ "Calculated output size: (",
164
+ nOutputPlane, "x", outputHeight, "x", outputWidth, "). ",
165
+ "Output size is too small");
166
+ }
167
+
168
+ // DilatedMaxPool2d (backward)
169
+ inline void
170
+ max_pool2d_backward_shape_check(
171
+ const Tensor& input,
172
+ const Tensor& gradOutput,
173
+ const Tensor& indices,
174
+ int kH, int kW, int dH, int dW, int padH, int padW, int dilationH, int dilationW,
175
+ int64_t nInputPlane,
176
+ int64_t inputHeight, int64_t inputWidth,
177
+ int64_t outputHeight, int64_t outputWidth, MemoryFormat memory_format)
178
+ {
179
+ pool2d_shape_check(
180
+ input,
181
+ kH, kW, dH, dW, padH, padW, dilationH, dilationW,
182
+ nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, memory_format);
183
+
184
+ const int64_t ndim = input.ndimension();
185
+ const int64_t nOutputPlane = nInputPlane;
186
+
187
+ check_dim_size(gradOutput, ndim, ndim-3, nOutputPlane);
188
+ check_dim_size(gradOutput, ndim, ndim-2, outputHeight);
189
+ check_dim_size(gradOutput, ndim, ndim-1, outputWidth);
190
+
191
+ check_dim_size(indices, ndim, ndim-3, nOutputPlane);
192
+ check_dim_size(indices, ndim, ndim-2, outputHeight);
193
+ check_dim_size(indices, ndim, ndim-1, outputWidth);
194
+
195
+ if (ndim == 4) {
196
+ const int64_t batchSize = input.size(0);
197
+ check_dim_size(gradOutput, ndim, 0, batchSize);
198
+ check_dim_size(indices, ndim, 0, batchSize);
199
+ }
200
+ }
201
+
202
+ // AveragePool2d (backward)
203
+ inline void
204
+ avg_pool2d_backward_shape_check(
205
+ const Tensor& input,
206
+ const Tensor& gradOutput,
207
+ int64_t /*nbatch*/,
208
+ int kH, int kW, int dH, int dW, int padH, int padW,
209
+ int64_t nInputPlane,
210
+ int64_t inputHeight, int64_t inputWidth,
211
+ int64_t outputHeight, int64_t outputWidth,
212
+ MemoryFormat memory_format)
213
+ {
214
+ pool2d_shape_check(
215
+ input,
216
+ kH, kW, dH, dW, padH, padW, 1, 1,
217
+ nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth,
218
+ memory_format);
219
+
220
+ const int64_t ndim = input.ndimension();
221
+ const int64_t nOutputPlane = nInputPlane;
222
+
223
+ check_dim_size(gradOutput, ndim, ndim-3, nOutputPlane);
224
+ check_dim_size(gradOutput, ndim, ndim-2, outputHeight);
225
+ check_dim_size(gradOutput, ndim, ndim-1, outputWidth);
226
+ }
227
+
228
+ // AveragePool3d/DilatedMaxPool3d (forward)
229
+ inline void
230
+ pool3d_shape_check(
231
+ const Tensor& input,
232
+ int64_t nslices,
233
+ int kT, int kH, int kW,
234
+ int dT, int dH, int dW,
235
+ int pT, int pH, int pW,
236
+ int dilationT, int dilationH, int dilationW,
237
+ int64_t itime, int64_t iheight, int64_t iwidth,
238
+ int64_t otime, int64_t oheight, int64_t owidth,
239
+ const char *fn_name,
240
+ bool check_input_size=false)
241
+ {
242
+ const int64_t ndim = input.ndimension();
243
+
244
+ TORCH_CHECK(kT > 0 && kW > 0 && kH > 0,
245
+ "kernel size should be greater than zero, but got ",
246
+ "kT: ", kT, " kH: ", kH, " kW: ", kW);
247
+ TORCH_CHECK(dT > 0 && dW > 0 && dH > 0,
248
+ "stride should be greater than zero, but got ",
249
+ "dT: ", dT, " dH: ", dH, " dW: ", dW);
250
+ TORCH_CHECK(dilationT > 0 && dilationW > 0 && dilationH > 0,
251
+ "dilation should be greater than zero, but got ",
252
+ "dilationT: ", dilationT, " dilationH: ", dilationH, " dilationW: ", dilationW);
253
+
254
+ TORCH_CHECK(ndim == 4 || ndim == 5,
255
+ fn_name, ": Expected 4D or 5D tensor for input, but got: ", input.sizes());
256
+
257
+ for (const auto i : c10::irange(ndim)) {
258
+ if (ndim == 5 && i == 0) {
259
+ // size of batch-dim can be 0.
260
+ continue;
261
+ }
262
+ TORCH_CHECK(
263
+ input.size(i) > 0,
264
+ fn_name,
265
+ ": Expected input's non-batch dimensions to have positive length,"
266
+ " but input has a shape of ",
267
+ input.sizes(),
268
+ " and non-batch dimension ",
269
+ input.size(i),
270
+ " has length zero!")
271
+ }
272
+
273
+ if (check_input_size) { // AveragePool3d
274
+ TORCH_CHECK(itime >= kT && iheight >= kH && iwidth >= kW,
275
+ "input image ", "(T: ", itime, " H: ", iheight, " W: ", iwidth, ") smaller than ",
276
+ "kernel size ", "(kT: ", kT, " kH: ", kH, " kW: ", kW, ")");
277
+ }
278
+
279
+ TORCH_CHECK(kT/2 >= pT && kW/2 >= pW && kH/2 >= pH,
280
+ "pad should be smaller than or equal to half of kernel size, but got "
281
+ "kT: ", kT, " kW: ", kW, " kH: ", kH, " padT: ", pT, " padW: ", pW, " padH: ", pH);
282
+
283
+ TORCH_CHECK(otime >= 1 && owidth >= 1 && oheight >= 1,
284
+ "Given input size: (",
285
+ nslices,"x", itime, "x", iheight, "x", iwidth, "). ",
286
+ "Calculated output size: (",
287
+ nslices, "x", otime, "x", oheight, "x", owidth, "). ",
288
+ "Output size is too small");
289
+ }
290
+
291
+ inline void
292
+ max_pool3d_backward_shape_check(
293
+ const Tensor& input,
294
+ const Tensor& gradOutput,
295
+ const Tensor& indices,
296
+ int64_t nslices,
297
+ int kT, int kH, int kW,
298
+ int dT, int dH, int dW,
299
+ int pT, int pH, int pW,
300
+ int dilationT, int dilationH, int dilationW,
301
+ int64_t itime, int64_t iheight, int64_t iwidth,
302
+ int64_t otime, int64_t oheight, int64_t owidth,
303
+ const char* fn_name)
304
+ {
305
+ const int64_t ndim = input.ndimension();
306
+
307
+ pool3d_shape_check(
308
+ input,
309
+ nslices,
310
+ kT, kH, kW,
311
+ dT, dH, dW,
312
+ pT, pH, pW,
313
+ dilationT, dilationH, dilationW,
314
+ itime, iheight, iwidth,
315
+ otime, oheight, owidth, fn_name);
316
+
317
+ check_dim_size(gradOutput, ndim, ndim-4, nslices);
318
+ check_dim_size(gradOutput, ndim, ndim-3, otime);
319
+ check_dim_size(gradOutput, ndim, ndim-2, oheight);
320
+ check_dim_size(gradOutput, ndim, ndim-1, owidth);
321
+
322
+ check_dim_size(indices, ndim, ndim-4, nslices);
323
+ check_dim_size(indices, ndim, ndim-3, otime);
324
+ check_dim_size(indices, ndim, ndim-2, oheight);
325
+ check_dim_size(indices, ndim, ndim-1, owidth);
326
+ }
327
+
328
+ inline void
329
+ avg_pool3d_backward_shape_check(
330
+ const Tensor& input,
331
+ const Tensor& gradOutput,
332
+ int64_t nslices,
333
+ int kT, int kH, int kW,
334
+ int dT, int dH, int dW,
335
+ int pT, int pH, int pW,
336
+ int64_t itime, int64_t iheight, int64_t iwidth,
337
+ int64_t otime, int64_t oheight, int64_t owidth,
338
+ const char *fn_name)
339
+ {
340
+ const int64_t ndim = input.ndimension();
341
+
342
+ pool3d_shape_check(
343
+ input,
344
+ nslices,
345
+ kT, kH, kW,
346
+ dT, dH, dW,
347
+ pT, pH, pW,
348
+ 1, 1, 1,
349
+ itime, iheight, iwidth,
350
+ otime, oheight, owidth,
351
+ fn_name, true);
352
+
353
+ check_dim_size(gradOutput, ndim, ndim-4, nslices);
354
+ check_dim_size(gradOutput, ndim, ndim-3, otime);
355
+ check_dim_size(gradOutput, ndim, ndim-2, oheight);
356
+ check_dim_size(gradOutput, ndim, ndim-1, owidth);
357
+ }
358
+
359
+ } // anonymous namespace
360
+
361
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Pow.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace c10 {
6
+ class Scalar;
7
+ }
8
+
9
+ namespace at {
10
+
11
+ struct TensorIterator;
12
+ struct TensorIteratorBase;
13
+
14
+ namespace native {
15
+
16
+ #if defined(__CUDACC__) || defined(__HIPCC__)
17
+ #define HOST_DEVICE __host__ __device__
18
+ #else
19
+ #define HOST_DEVICE
20
+ #endif
21
+
22
+ // integral power in pytorch allows for negative exponents, giving truncated integral results.
23
+ // e.g. since 2**-1==0.5, the truncated integral result is zero. 1**negative_exponent is the
24
+ // only non-zero result.
25
+ template <class T,
26
+ std::enable_if_t<std::is_integral_v<T>, T>* = nullptr>
27
+ inline HOST_DEVICE __ubsan_ignore_signed_int_overflow__ T powi_impl(T a, T b) {
28
+ T result = 1;
29
+ while (b) {
30
+ if (b & 1) {
31
+ result *= a;
32
+ }
33
+ b /= 2;
34
+ a *= a;
35
+ }
36
+ return result;
37
+ }
38
+
39
+ template <class T,
40
+ std::enable_if_t<std::is_integral_v<T> && !std::is_signed_v<T>, T>* = nullptr>
41
+ inline HOST_DEVICE T powi(T a, T b) {
42
+ return powi_impl(a, b);
43
+ }
44
+
45
+ template <class T,
46
+ std::enable_if_t<std::is_integral_v<T> && std::is_signed_v<T>, T>* = nullptr>
47
+ inline HOST_DEVICE T powi(T a, T b) {
48
+ if ( b < 0 ) {
49
+ if ( a == 1 ) {
50
+ return 1;
51
+ } else if ( a == -1 ) {
52
+ auto negative = (-b) % static_cast<T>(2);
53
+ return negative ? -1 : 1;
54
+ } else {
55
+ return 0;
56
+ }
57
+ }
58
+ return powi_impl(a, b);
59
+ }
60
+
61
+ using pow_tensor_tensor_fn = void (*)(TensorIteratorBase&);
62
+ using pow_tensor_scalar_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
63
+
64
+ DECLARE_DISPATCH(pow_tensor_tensor_fn, pow_tensor_tensor_stub)
65
+ DECLARE_DISPATCH(pow_tensor_scalar_fn, pow_tensor_scalar_stub)
66
+
67
+ } // namespace native
68
+
69
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RNN.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace at::native {
7
+
8
+ using lstm_fn = void(*)(Tensor&, Tensor&, Tensor&, const Tensor&, TensorList, TensorList, bool, int64_t, double, bool, bool, bool);
9
+ using rnn_fn = void(*)(Tensor&, Tensor&, const Tensor&, const Tensor&, TensorList, bool, int64_t, double, bool, bool, bool);
10
+ using lstm_packed_fn = void(*)(Tensor&, Tensor&, Tensor&, const Tensor&, const Tensor&, TensorList, TensorList, bool, int64_t, double, bool, bool);
11
+ using rnn_packed_fn = void(*)(Tensor&, Tensor&, const Tensor&, const Tensor&, const Tensor&, TensorList, bool, int64_t, double, bool, bool);
12
+
13
+ DECLARE_DISPATCH(lstm_fn, lstm_cudnn_stub)
14
+ DECLARE_DISPATCH(lstm_fn, lstm_miopen_stub)
15
+ DECLARE_DISPATCH(lstm_fn, lstm_mkldnn_stub)
16
+ DECLARE_DISPATCH(rnn_fn, gru_cudnn_stub)
17
+ DECLARE_DISPATCH(rnn_fn, gru_miopen_stub)
18
+ DECLARE_DISPATCH(rnn_fn, rnn_tanh_cudnn_stub)
19
+ DECLARE_DISPATCH(rnn_fn, rnn_tanh_miopen_stub)
20
+ DECLARE_DISPATCH(rnn_fn, rnn_relu_cudnn_stub)
21
+ DECLARE_DISPATCH(rnn_fn, rnn_relu_miopen_stub)
22
+ DECLARE_DISPATCH(lstm_packed_fn, lstm_packed_cudnn_stub)
23
+ DECLARE_DISPATCH(lstm_packed_fn, lstm_packed_miopen_stub)
24
+ DECLARE_DISPATCH(rnn_packed_fn, gru_packed_cudnn_stub)
25
+ DECLARE_DISPATCH(rnn_packed_fn, gru_packed_miopen_stub)
26
+ DECLARE_DISPATCH(rnn_packed_fn, rnn_tanh_packed_cudnn_stub)
27
+ DECLARE_DISPATCH(rnn_packed_fn, rnn_tanh_packed_miopen_stub)
28
+ DECLARE_DISPATCH(rnn_packed_fn, rnn_relu_packed_cudnn_stub)
29
+ DECLARE_DISPATCH(rnn_packed_fn, rnn_relu_packed_miopen_stub)
30
+
31
+ inline void check_attributes(const Tensor& input, const TensorList& params, const TensorList& hiddens, bool check_dtype=false) {
32
+ auto input_device = input.device();
33
+ auto input_dtype = input.scalar_type();
34
+
35
+ auto check_tensors = [&](const std::string& name, const Tensor& t) {
36
+ if (!t.defined()) return;
37
+ auto t_device = t.device();
38
+ TORCH_CHECK(input_device == t_device,
39
+ "Input and ", name, " tensors are not at the same device, found input tensor at ",
40
+ input_device, " and ", name, " tensor at ", t_device);
41
+ if (check_dtype) {
42
+ auto t_dtype = t.scalar_type();
43
+ TORCH_CHECK(input_dtype == t_dtype,
44
+ "Input and ", name, " tensors are not the same dtype, found input tensor with ",
45
+ input_dtype, " and ", name, " tensor with ", t_dtype);
46
+ }
47
+ };
48
+
49
+ for (const auto& h : hiddens) check_tensors("hidden", h);
50
+ for (const auto& p : params) check_tensors("parameter", p);
51
+ }
52
+
53
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RangeFactories.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/native/DispatchStub.h>
2
+ #include <c10/core/Scalar.h>
3
+
4
+ namespace at {
5
+ struct TensorIterator;
6
+
7
+ namespace native {
8
+
9
+ DECLARE_DISPATCH(void(*)(TensorIterator&, const Scalar&, const Scalar&, const Scalar&), arange_stub)
10
+ DECLARE_DISPATCH(void(*)(TensorIterator&, const Scalar&, const Scalar&, int64_t), linspace_stub)
11
+
12
+ }} // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/RangeUtils.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/AccumulateType.h>
2
+ #include <c10/core/Scalar.h>
3
+ #include <limits>
4
+
5
+ namespace at {
6
+
7
+ namespace native {
8
+
9
+ template <typename scalar_t>
10
+ int64_t compute_arange_size(const Scalar& start, const Scalar& end, const Scalar& step) {
11
+ using accscalar_t = at::acc_type<scalar_t, false>;
12
+ auto xstart = start.to<accscalar_t>();
13
+ auto xend = end.to<accscalar_t>();
14
+ auto xstep = step.to<accscalar_t>();
15
+
16
+ TORCH_CHECK(xstep > 0 || xstep < 0, "step must be nonzero");
17
+ TORCH_CHECK(std::isfinite(static_cast<double>(xstart)) &&
18
+ std::isfinite(static_cast<double>(xend)),
19
+ "unsupported range: ", xstart, " -> ", xend);
20
+ TORCH_CHECK(((xstep > 0) && (xend >= xstart)) || ((xstep < 0) && (xend <= xstart)),
21
+ "upper bound and larger bound inconsistent with step sign");
22
+
23
+ // we use double precision for (start - end) / step
24
+ // to compute size_d for consistency across devices.
25
+ // The problem with using accscalar_t is that accscalar_t might be float32 on gpu for a float32 scalar_t,
26
+ // but double on cpu for the same,
27
+ // and the effective output size starts differing on CPU vs GPU because of precision issues, which
28
+ // we dont want.
29
+ // the corner-case we do want to take into account is int64_t, which has higher precision than double
30
+ double size_d;
31
+ if constexpr (std::is_same_v<scalar_t, int64_t>) {
32
+ int64_t sgn = (xstep > 0) - (xstep < 0);
33
+ size_d = std::ceil((xend - xstart + xstep - sgn) / xstep);
34
+ } else {
35
+ size_d = std::ceil(static_cast<double>(end.to<double>() - start.to<double>())
36
+ / step.to<double>());
37
+ }
38
+
39
+ TORCH_CHECK(size_d >= 0 && size_d <= static_cast<double>(std::numeric_limits<int64_t>::max()),
40
+ "invalid size, possible overflow?");
41
+
42
+ return static_cast<int64_t>(size_d);
43
+ }
44
+
45
+ }} // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceAllOps.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ using reduce_all_fn = void (*)(Tensor & result, const Tensor & self);
12
+ using reduce_min_max_fn = void (*)(Tensor & max_result, Tensor & min_result, const Tensor & self);
13
+ DECLARE_DISPATCH(reduce_all_fn, min_all_stub)
14
+ DECLARE_DISPATCH(reduce_all_fn, max_all_stub)
15
+
16
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceOps.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/util/ArrayRef.h>
5
+ #include <optional>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ struct TensorIterator;
13
+ class Tensor;
14
+ }
15
+
16
+ namespace at::native {
17
+
18
+ using reduce_fn = void(*)(TensorIterator &);
19
+
20
+ DECLARE_DISPATCH(reduce_fn, sum_stub)
21
+ DECLARE_DISPATCH(reduce_fn, nansum_stub)
22
+ DECLARE_DISPATCH(reduce_fn, prod_stub)
23
+ DECLARE_DISPATCH(reduce_fn, mean_stub)
24
+ DECLARE_DISPATCH(reduce_fn, and_stub)
25
+ DECLARE_DISPATCH(reduce_fn, or_stub)
26
+ DECLARE_DISPATCH(reduce_fn, min_values_stub)
27
+ DECLARE_DISPATCH(reduce_fn, max_values_stub)
28
+ DECLARE_DISPATCH(reduce_fn, argmax_stub)
29
+ DECLARE_DISPATCH(reduce_fn, argmin_stub)
30
+
31
+ using reduce_std_var_function =
32
+ void (*)(TensorIterator&, double correction, bool take_sqrt);
33
+ DECLARE_DISPATCH(reduce_std_var_function, std_var_stub)
34
+
35
+ using reduce_norm_fn =
36
+ void (*)(Tensor&, const Tensor&, const c10::Scalar&, std::optional<int64_t>);
37
+ DECLARE_DISPATCH(reduce_norm_fn, norm_kernel)
38
+
39
+ using reduce_fn_flag = void(*)(TensorIterator &, const c10::Scalar&);
40
+ DECLARE_DISPATCH(reduce_fn_flag, norm_stub)
41
+
42
+ using structured_cum_fn = void (*)(const Tensor&, const Tensor&, int64_t);
43
+ using cum_fn = void (*)(Tensor&, const Tensor&, int64_t);
44
+ DECLARE_DISPATCH(structured_cum_fn, cumsum_stub)
45
+ DECLARE_DISPATCH(structured_cum_fn, cumprod_stub)
46
+ DECLARE_DISPATCH(cum_fn, logcumsumexp_stub)
47
+
48
+ DECLARE_DISPATCH(void (*)(const Tensor&, int64_t, bool, Tensor&, Tensor&), aminmax_stub)
49
+ DECLARE_DISPATCH(void (*)(const Tensor&, Tensor&, Tensor&), aminmax_allreduce_stub)
50
+
51
+ // Used in cuda/Normalization.cu
52
+ TORCH_API std::tuple<Tensor&,Tensor&> var_mean_out(
53
+ Tensor &result1, Tensor &result2, const Tensor &self, IntArrayRef dim,
54
+ int64_t correction, bool keepdim);
55
+
56
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReduceOpsUtils.h ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <limits>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/Resize.h>
6
+ #include <ATen/native/TensorIterator.h>
7
+ #include <ATen/native/NonEmptyUtils.h>
8
+ #include <ATen/WrapDimUtilsMulti.h>
9
+ #include <c10/core/ScalarType.h>
10
+ #include <c10/util/irange.h>
11
+
12
+ #ifndef AT_PER_OPERATOR_HEADERS
13
+ #include <ATen/Functions.h>
14
+ #else
15
+ #include <ATen/ops/empty.h>
16
+ #include <ATen/ops/scalar_tensor.h>
17
+ #endif
18
+
19
+ namespace at::native {
20
+
21
+ // Maximum and minimum possible scalar values, including infinities
22
+ template <typename scalar_t>
23
+ constexpr scalar_t upper_bound() {
24
+ using lim = std::numeric_limits<scalar_t>;
25
+ return lim::has_infinity ? lim::infinity() : lim::max();
26
+ }
27
+
28
+ template <typename scalar_t>
29
+ constexpr scalar_t lower_bound() {
30
+ using lim = std::numeric_limits<scalar_t>;
31
+ return lim::has_infinity ? -lim::infinity() : lim::lowest();
32
+ }
33
+
34
+ inline Tensor restride_dim(
35
+ const Tensor& src, int64_t dim,
36
+ IntArrayRef replacement_shape
37
+ ) {
38
+ auto strides = ensure_nonempty_vec(src.strides().vec());
39
+ strides[dim] = 0;
40
+ return src.as_strided(replacement_shape, strides);
41
+ }
42
+
43
+ inline void _dimreduce_setup(const Tensor &result, const Tensor &self,
44
+ int64_t dim) {
45
+ IntArrayRef self_sizes = self.sizes();
46
+ std::vector<int64_t> result_sizes;
47
+ result_sizes.insert(result_sizes.end(), self_sizes.begin(), self_sizes.end());
48
+ result_sizes[dim] = 1;
49
+ result.resize_(result_sizes);
50
+ }
51
+
52
+ inline bool _dimreduce_return_trivial(const Tensor &result, const Tensor &self,
53
+ const Scalar& ident, int64_t dim, bool keepdim) {
54
+ if (self.numel() == 1 && self.ndimension() == 0) {
55
+ result.resize_({});
56
+ result.fill_(self);
57
+ return true;
58
+ }
59
+ // Return identity
60
+ if (self.numel() == 0) {
61
+ _dimreduce_setup(result, self, dim);
62
+ result.fill_(ident);
63
+ if (!keepdim) result.squeeze_(dim);
64
+ return true;
65
+ }
66
+ return false;
67
+ }
68
+
69
+ inline bool _dimreduce_return_trivial_no_ident(Tensor &result, const Tensor &self,
70
+ int64_t /*dim*/, bool /*keepdim*/, const char* /*fn_name*/) {
71
+ if (self.numel() == 1 && self.ndimension() == 0) {
72
+ result.resize_({});
73
+ result.fill_(self);
74
+ return true;
75
+ }
76
+
77
+ return false;
78
+ }
79
+
80
+ inline std::optional<Tensor> _allreduce_return_trivial(
81
+ const Tensor& self,
82
+ const Scalar& ident) {
83
+ // Return identity
84
+ if (self.numel() == 0) {
85
+ return at::scalar_tensor(ident, self.options());
86
+ }
87
+ return std::nullopt;
88
+ }
89
+
90
+ #define OPTION_TYPE_EQUALITY_CHECK(option, out, self) \
91
+ { \
92
+ TORCH_CHECK(\
93
+ out.option() == self.option(),\
94
+ "expected ", #option, " ",\
95
+ self.option(),\
96
+ " but found ", out.option())\
97
+ }
98
+
99
+ inline void check_scalar_type_device_layout_equal(const Tensor& out, const Tensor& self) {
100
+ OPTION_TYPE_EQUALITY_CHECK(scalar_type, out, self);
101
+ OPTION_TYPE_EQUALITY_CHECK(device, out.options(), self.options());
102
+ OPTION_TYPE_EQUALITY_CHECK(layout, out.options(), self.options());
103
+ }
104
+
105
+ inline Tensor integer_upcast(const Tensor& self, std::optional<ScalarType> dtype) {
106
+ ScalarType scalarType = self.scalar_type();
107
+ TORCH_CHECK(!isBarebonesUnsignedType(scalarType), "integer upcasting for uint16, uint32 and uint64 is not currently implemented");
108
+ ScalarType upcast_scalarType = dtype.value_or(at::isIntegralType(scalarType, /*includeBool=*/true) ? ScalarType::Long : scalarType);
109
+ return self.toType(upcast_scalarType);
110
+ }
111
+
112
+ using DimMask = TensorIterator::DimMask;
113
+
114
+ inline DimVector make_dim_vector(OptionalIntArrayRef opt_dims, int64_t ndim) {
115
+ if (opt_dims.has_value()) {
116
+ return DimVector(opt_dims.value());
117
+ } else {
118
+ std::vector<int64_t> all_dims(ndim);
119
+ std::iota(all_dims.begin(), all_dims.end(), 0);
120
+ return DimVector(all_dims);
121
+ }
122
+ }
123
+
124
+ inline DimMask make_dim_mask(OptionalIntArrayRef opt_dims, int64_t ndim, bool allow_empty_dims=false) {
125
+ DimMask mask;
126
+ if (opt_dims.has_value()) {
127
+ auto dims = opt_dims.value();
128
+ if (dims.empty() && !allow_empty_dims) {
129
+ mask = DimMask().flip();
130
+ } else {
131
+ mask = at::dim_list_to_bitset(dims, ndim);
132
+ }
133
+ } else {
134
+ mask = DimMask().flip();
135
+ }
136
+ return mask;
137
+ }
138
+
139
+ inline DimVector shape_from_dim_mask(const Tensor& self, DimMask mask, bool keepdim) {
140
+ auto shape = DimVector(self.sizes());
141
+ for (int dim = shape.size() - 1; dim >= 0; dim--) {
142
+ if (mask[dim]) {
143
+ if (keepdim) {
144
+ shape[dim] = 1;
145
+ } else {
146
+ shape.erase(shape.begin() + dim);
147
+ }
148
+ }
149
+ }
150
+ return shape;
151
+ }
152
+
153
+ inline void resize_reduction_result(
154
+ Tensor& result, const Tensor& self, DimMask mask, bool keepdim,
155
+ ScalarType /*dtype*/)
156
+ {
157
+ auto shape = shape_from_dim_mask(self, mask, keepdim);
158
+ TORCH_CHECK(result.defined(), "Cannot create a new tensor inside a reduction op. You likely tried to call an operator with an out argument but the out argument was an undefined tensor.");
159
+ at::native::resize_output(result, shape);
160
+ }
161
+
162
+ inline Tensor create_reduction_result(
163
+ const Tensor& self, at::OptionalIntArrayRef dim, bool keepdim, ScalarType dtype
164
+ ) {
165
+ DimMask mask = make_dim_mask(dim, self.dim());
166
+ auto shape = shape_from_dim_mask(self, mask, keepdim);
167
+ return at::empty(shape, self.options().dtype(dtype));
168
+ }
169
+
170
+ inline Tensor review_reduce_result(const Tensor& result, int ndim, DimMask mask, bool keepdim) {
171
+ if (keepdim) {
172
+ return result;
173
+ }
174
+ auto shape = DimVector(result.sizes());
175
+ auto stride = DimVector(result.strides());
176
+ for (const auto dim : c10::irange(ndim)) {
177
+ if (mask[dim]) {
178
+ shape.insert(shape.begin() + dim, 1);
179
+ stride.insert(stride.begin() + dim, 0);
180
+ }
181
+ }
182
+ return result.as_strided(shape, stride);
183
+ }
184
+
185
+ inline TensorIterator make_reduction(
186
+ const char* name, Tensor& result, const Tensor& self,
187
+ at::OptionalIntArrayRef dim_opt,
188
+ bool keepdim, ScalarType in_dtype, ScalarType out_dtype) {
189
+ // check that result type and dtype match if provided
190
+ TORCH_CHECK(
191
+ !result.defined() || result.scalar_type() == out_dtype,
192
+ name, ": provided dtype must match dtype of result. Got ",
193
+ toString(result.scalar_type()),
194
+ " and ",
195
+ toString(out_dtype),
196
+ ".");
197
+ // dim={} performs an all-reduce, same as dim=None
198
+ IntArrayRef dim = dim_opt.value_or(IntArrayRef{});
199
+ int64_t ndim = self.dim();
200
+ auto mask = make_dim_mask(dim, ndim);
201
+ resize_reduction_result(result, self, mask, keepdim, out_dtype);
202
+ auto viewed_result = review_reduce_result(result, ndim, mask, keepdim);
203
+ namedinference::propagate_names_for_reduction(result, self, dim, keepdim);
204
+ if (self.scalar_type() == in_dtype) {
205
+ return TensorIterator::reduce_op(viewed_result, self);
206
+ }
207
+ return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
208
+ }
209
+
210
+ [[maybe_unused]] inline TensorIterator make_reduction(
211
+ const char* name,
212
+ Tensor& result,
213
+ const Tensor& self,
214
+ at::OptionalIntArrayRef dim,
215
+ bool keepdim,
216
+ ScalarType out_dtype) {
217
+ // special case for type promotion in mixed precision, improves computational
218
+ // efficiency.
219
+ // not generalize this to common mismatched input/output types to avoid cross
220
+ // product of templated kernel launches.
221
+ const bool gpu_lowp_to_f32 = (
222
+ (self.is_cuda() || self.is_xpu()) && (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) && out_dtype == kFloat);
223
+ auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type()
224
+ : self.is_complex() ? c10::toComplexType(out_dtype)
225
+ : out_dtype;
226
+ return make_reduction(name, result, self, dim, keepdim, in_dtype, out_dtype);
227
+ }
228
+
229
+ inline TensorIterator make_reduction(
230
+ const char* name, Tensor& result1, Tensor& result2, const Tensor& self,
231
+ at::OptionalIntArrayRef dim_opt, bool keepdim, ScalarType dtype1,
232
+ ScalarType dtype2) {
233
+ // check that result type and dtype match if provided
234
+ TORCH_CHECK(
235
+ (!result1.defined() || result1.scalar_type() == dtype1) && (!result2.defined() || result2.scalar_type() == dtype2),
236
+ name, ": provided dtype must match dtype of result. Got ",
237
+ toString(result1.scalar_type()), toString(result2.scalar_type()),
238
+ " and ",
239
+ toString(dtype1), toString(dtype2),
240
+ ".");
241
+
242
+ // dim={} performs an all-reduce, same as dim=None
243
+ auto dim = dim_opt.value_or(IntArrayRef{});
244
+ int64_t ndim = self.dim();
245
+ DimMask mask = make_dim_mask(dim, ndim);
246
+ resize_reduction_result(result1, self, mask, keepdim, dtype1);
247
+ auto viewed_result1 = review_reduce_result(result1, ndim, mask, keepdim);
248
+
249
+ resize_reduction_result(result2, self, mask, keepdim, dtype2);
250
+ auto viewed_result2 = review_reduce_result(result2, ndim, mask, keepdim);
251
+
252
+ namedinference::propagate_names_for_reduction(result1, self, dim, keepdim);
253
+ namedinference::propagate_names_for_reduction(result2, self, dim, keepdim);
254
+
255
+ // special case for type promotion in mixed precision, improves computational
256
+ // efficiency.
257
+ // We don't generalize this to common mismatched input/output types to avoid cross
258
+ // product of templated kernel launches.
259
+ if (self.scalar_type() == dtype1 ||
260
+ (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
261
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
262
+ }
263
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
264
+ }
265
+
266
+ [[maybe_unused]] inline TensorIterator make_reduction(
267
+ const char* name,
268
+ Tensor& result1,
269
+ Tensor& result2,
270
+ const Tensor& self,
271
+ at::OptionalIntArrayRef dim,
272
+ bool keepdim,
273
+ ScalarType dtype) {
274
+ return make_reduction(name, result1, result2, self, dim, keepdim, dtype, dtype);
275
+ }
276
+
277
+ inline void zero_numel_check_dims(const Tensor& self, const int64_t dim, const char *fn_name) {
278
+ if (self.ndimension() == 0) {
279
+ TORCH_CHECK_INDEX(dim == 0 || dim == -1, fn_name,
280
+ ": Expected reduction dim -1 or 0 for scalar but got ", dim);
281
+ }
282
+ else {
283
+ TORCH_CHECK_INDEX(self.size(dim) != 0, fn_name,
284
+ ": Expected reduction dim ", dim, " to have non-zero size.");
285
+ }
286
+ }
287
+
288
+ inline void zero_numel_check_dims(const Tensor& self, const IntArrayRef dim, const char *fn_name) {
289
+ TORCH_CHECK(
290
+ !dim.empty(),
291
+ fn_name, ": Expected reduction dim to be specified for input.numel() == 0. ",
292
+ "Specify the reduction dim with the 'dim' argument.");
293
+ for (const int64_t d : dim) {
294
+ zero_numel_check_dims(self, d, fn_name);
295
+ }
296
+ }
297
+
298
+ inline std::vector<int64_t> get_zero_numel_tensor_size(
299
+ const Tensor& self,
300
+ const int64_t dim,
301
+ const bool keepdim,
302
+ const char* fn_name) {
303
+ TORCH_INTERNAL_ASSERT(self.numel() == 0, fn_name, ": Expected self.numel() == 0.");
304
+ zero_numel_check_dims(self, dim, fn_name);
305
+ std::vector<int64_t> sizes;
306
+ if (keepdim) {
307
+ sizes = self.sizes().vec();
308
+ sizes[dim] = 1;
309
+ }
310
+ else {
311
+ for (const auto d : c10::irange(self.dim())) {
312
+ if (d != dim) {
313
+ sizes.push_back(self.sizes()[d]);
314
+ }
315
+ }
316
+ }
317
+ return sizes;
318
+ }
319
+
320
+ // Resize the result tensor and indices when result.numel() == 0 depending on values of
321
+ // dim and keepdim for returning tensors containing reduction results.
322
+ // This function should be called when you are reducing a zero-numel tensor and want to
323
+ // resize the output and return it. This function exists for resizing zero-numel
324
+ // tensors when the size of the reduction dimension is non-zero.
325
+ [[maybe_unused]] inline void zero_numel_tensor_resize(
326
+ Tensor& result,
327
+ Tensor& result_indices,
328
+ const Tensor& self,
329
+ const int64_t dim,
330
+ const bool keepdim,
331
+ const char* fn_name) {
332
+ auto sizes = get_zero_numel_tensor_size(self, dim, keepdim, fn_name);
333
+ at::native::resize_output(result, sizes);
334
+ at::native::resize_output(result_indices, sizes);
335
+ }
336
+
337
+ inline ScalarType get_dtype_from_self(
338
+ const Tensor& self,
339
+ const std::optional<ScalarType>& dtype,
340
+ bool promote_integers) {
341
+ if (dtype.has_value()) {
342
+ return dtype.value();
343
+ }
344
+ ScalarType src_type = self.scalar_type();
345
+ if (promote_integers && at::isIntegralType(src_type, /*includeBool=*/true)) {
346
+ return kLong;
347
+ }
348
+ return src_type;
349
+ }
350
+
351
+ inline ScalarType get_dtype_from_result(Tensor& result, std::optional<ScalarType> dtype) {
352
+ TORCH_CHECK(result.defined(), "Cannot create a new tensor inside a reduction op. You likely tried to call an operator with an out argument but the out argument was an undefined tensor.");
353
+ if (dtype.has_value()) {
354
+ return dtype.value();
355
+ } else {
356
+ return result.scalar_type();
357
+ }
358
+ }
359
+
360
+
361
+ } // namespace at::native
362
+
363
+ namespace at::meta {
364
+
365
+ [[maybe_unused]] inline DimVector get_reduction_shape(
366
+ const Tensor& self,
367
+ IntArrayRef dims,
368
+ bool keepdim,
369
+ bool allow_empty_dims = false) {
370
+ auto mask = native::make_dim_mask(dims, self.dim(), allow_empty_dims);
371
+ return native::shape_from_dim_mask(self, mask, keepdim);
372
+ }
373
+
374
+ inline void resize_reduction(
375
+ impl::MetaBase& meta,
376
+ const Tensor& self,
377
+ OptionalIntArrayRef opt_dims,
378
+ bool keepdim,
379
+ ScalarType out_dtype,
380
+ bool allow_empty_dims=false) {
381
+ DimVector dims_ = at::native::make_dim_vector(opt_dims, self.dim());
382
+ maybe_wrap_dims(dims_, self.dim());
383
+ auto shape = get_reduction_shape(self, dims_, keepdim, allow_empty_dims);
384
+ if (self.layout() == kStrided) {
385
+ meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
386
+ } else if (shape.empty()) {
387
+ meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype).layout(kStrided));
388
+ } else {
389
+ TORCH_CHECK(false, "resize_reduction: support for output with ", self.layout(), " layout is not implemented yet");
390
+ }
391
+ namedinference::propagate_names_for_reduction(
392
+ meta.maybe_get_output(), self, dims_, keepdim);
393
+ }
394
+
395
+ inline void resize_reduction_with_indices(
396
+ impl::MetaBase& meta,
397
+ const Tensor& self,
398
+ IntArrayRef dims,
399
+ bool keepdim,
400
+ ScalarType out_dtype) {
401
+ DimVector dims_(dims);
402
+ maybe_wrap_dims(dims_, self.dim());
403
+ auto shape = get_reduction_shape(self, dims_, keepdim);
404
+ meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
405
+ meta.set_output_raw_strided(1, shape, {}, self.options().dtype(kLong));
406
+ namedinference::propagate_names_for_reduction(
407
+ meta.maybe_get_output(0), self, dims_, keepdim);
408
+ namedinference::propagate_names_for_reduction(
409
+ meta.maybe_get_output(1), self, dims_, keepdim);
410
+ }
411
+
412
+ inline TensorIterator make_reduction(
413
+ const Tensor& self,
414
+ const Tensor& result,
415
+ OptionalIntArrayRef opt_dims,
416
+ bool keepdim,
417
+ ScalarType in_dtype) {
418
+ int64_t ndim = self.dim();
419
+ auto mask = at::native::make_dim_mask(opt_dims, ndim);
420
+ auto viewed_result =
421
+ at::native::review_reduce_result(result, ndim, mask, keepdim);
422
+ if (self.scalar_type() == in_dtype) {
423
+ return TensorIterator::reduce_op(viewed_result, self);
424
+ }
425
+ return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
426
+ }
427
+
428
+ inline TensorIterator make_reduction(
429
+ const Tensor& self,
430
+ const Tensor& result1,
431
+ const Tensor& result2,
432
+ IntArrayRef dims,
433
+ bool keepdim,
434
+ ScalarType dtype1,
435
+ ScalarType /*dtype2*/) {
436
+ int64_t ndim = self.dim();
437
+ auto mask = at::native::make_dim_mask(dims, ndim);
438
+ auto viewed_result1 = at::native::review_reduce_result(result1, ndim, mask, keepdim);
439
+ auto viewed_result2 = at::native::review_reduce_result(result2, ndim, mask, keepdim);
440
+ // special case for type promotion in mixed precision, improves computational efficiency.
441
+ // We don't generalize this to common mismatched input/output types to avoid cross product
442
+ // of templated kernel launches.
443
+ if (self.scalar_type() == dtype1 ||
444
+ (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
445
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
446
+ }
447
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
448
+ }
449
+
450
+ [[maybe_unused]] inline TensorIterator make_reduction_from_out_ty(
451
+ const Tensor& self,
452
+ const Tensor& result,
453
+ OptionalIntArrayRef opt_dims,
454
+ bool keepdim,
455
+ ScalarType out_dtype) {
456
+ // special case for type promotion in mixed precision, improves computational
457
+ // efficiency.
458
+ // not generalize this to common mismatched input/output types to avoid cross
459
+ // product of templated kernel launches.
460
+ const bool gpu_lowp_to_f32 =
461
+ (self.is_cuda() &&
462
+ (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) &&
463
+ out_dtype == kFloat);
464
+ auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type() : out_dtype;
465
+ return make_reduction(self, result, opt_dims, keepdim, in_dtype);
466
+ }
467
+
468
+ } // namespace at::meta
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ReductionType.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Scalar.h>
4
+
5
+ namespace at::native {
6
+
7
+ enum class ReductionType {MAX, MEAN, MIN, SUM, PROD};
8
+
9
+ inline ReductionType get_reduction_enum(const std::string_view& reduce) {
10
+ if (reduce == "max" || reduce == "amax") {
11
+ return ReductionType::MAX;
12
+ } else if (reduce == "mean") {
13
+ return ReductionType::MEAN;
14
+ } else if (reduce == "min" || reduce == "amin") {
15
+ return ReductionType::MIN;
16
+ } else if (reduce == "sum") {
17
+ return ReductionType::SUM;
18
+ } else if (reduce == "prod") {
19
+ return ReductionType::PROD;
20
+ } else {
21
+ TORCH_CHECK(false, "reduce argument must be either sum, prod, mean, amax or amin, got ", reduce);
22
+ }
23
+ }
24
+
25
+ // used for `scatter_reduce`, old options for BC.
26
+ inline ReductionType get_operator_enum(const std::string_view reduce, bool use_new_options) {
27
+ if (use_new_options) {
28
+ return get_reduction_enum(reduce);
29
+ } else {
30
+ if (reduce == "add") {
31
+ return ReductionType::SUM;
32
+ } else if (reduce == "multiply") {
33
+ return ReductionType::PROD;
34
+ } else {
35
+ TORCH_CHECK(false, "reduce argument must be either add or multiply.")
36
+ }
37
+ }
38
+ }
39
+
40
+ } // at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Repeat.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/TensorOperators.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/Functions.h>
8
+ #else
9
+ #include <ATen/ops/empty.h>
10
+ #include <ATen/ops/empty_like.h>
11
+ #endif
12
+
13
+ namespace at::native {
14
+
15
+ template <
16
+ typename index_t,
17
+ void compute(const index_t*, const int64_t*, index_t*, int64_t, int64_t)>
18
+ static inline Tensor repeat_interleave_common(
19
+ const Tensor& repeats,
20
+ std::optional<int64_t> output_size) {
21
+ TORCH_CHECK(
22
+ repeats.dim() == 1, "repeat_interleave only accept 1D vector as repeat");
23
+ TORCH_CHECK(
24
+ repeats.scalar_type() == at::kLong || repeats.scalar_type() == at::kInt,
25
+ "repeats has to be Long or Int tensor");
26
+ if (repeats.size(0) == 0) {
27
+ return at::empty_like(repeats, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
28
+ }
29
+ Tensor repeats_ = repeats.contiguous();
30
+ Tensor cumsum = repeats.cumsum(0);
31
+ int64_t total = 0;
32
+ if (output_size.has_value()) {
33
+ total = output_size.value();
34
+ } else {
35
+ total = cumsum[-1].item<int64_t>();
36
+ TORCH_CHECK(
37
+ (repeats >= 0).all().item<uint8_t>(), "repeats can not be negative");
38
+ }
39
+
40
+ Tensor result = at::empty({total}, repeats.options());
41
+ const index_t* repeat_ptr = repeats_.const_data_ptr<index_t>();
42
+ const int64_t* cumsum_ptr = cumsum.const_data_ptr<int64_t>();
43
+ index_t* result_ptr = result.data_ptr<index_t>();
44
+ compute(repeat_ptr, cumsum_ptr, result_ptr, repeats.size(0), total);
45
+ return result;
46
+ }
47
+
48
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Resize.h ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/ResizeCommon.h>
5
+ #include <ATen/EmptyTensor.h>
6
+ #include <ATen/TensorUtils.h>
7
+
8
+ #include <c10/core/CPUAllocator.h>
9
+ #include <c10/core/SymBool.h>
10
+
11
+ #include <utility>
12
+
13
+
14
+ namespace at::native {
15
+
16
+ // TODO: make all operations that resize given outputs use this function
17
+ // for consistency and maintainability.
18
+ // Some operations like `cat` might not be able to make the use of
19
+ // resize_output directly. For more details to understand how it works in `cat`,
20
+ // see https://github.com/pytorch/pytorch/pull/62560#discussion_r687363362
21
+ // Resizes outputs
22
+ // Functions accepting output tensors, like with the "out" kwarg, should
23
+ // call this function to handle resizing their output tensor.
24
+ // Issues a warning if the output tensor has one or more elements and
25
+ // needs resizing
26
+ // NOTE: In the future the warning will become an error
27
+ // Returns a bool saying whether or not the resize actually happened or not
28
+ TORCH_API bool resize_output(const Tensor& output, IntArrayRef shape);
29
+ // WARNING: Do NOT call this directly. If you are resizing an output and want
30
+ // to support dynamic shapes call at::resize__symint and resize_output_check_symint.
31
+ // For more details, see: https://github.com/pytorch/pytorch/pull/111530/files#r1365845272
32
+ TORCH_API bool resize_output_symint(const Tensor& output, SymIntArrayRef shape);
33
+
34
+ // Utility for resize_output
35
+ // Returns a bool saying resize should happen or not and
36
+ // raises a warning if resizing for one or more elements
37
+ TORCH_API bool resize_output_check(const Tensor& output, IntArrayRef shape);
38
+ TORCH_API bool resize_output_check_symint(const Tensor& output, SymIntArrayRef shape);
39
+
40
+ TORCH_API void resize_bytes_cpu(StorageImpl* storage, size_t size_bytes);
41
+ TORCH_API void resize_bytes_meta(StorageImpl* storage, c10::SymInt size_bytes);
42
+ TORCH_API void resize_bytes_nocuda(const Storage& storage, const c10::SymInt& size_bytes);
43
+
44
+ inline void maybe_resize_storage_cpu(TensorImpl* self, size_t new_size_bytes) {
45
+ // It does not make sense to try to resize a storage
46
+ // to hold 0 elements, and this can break
47
+ // if storage_offset is positive but
48
+ // new_size is 0, so just bail in that case
49
+ // (same comment is in cuda/Resize.h)
50
+ if (self->numel() == 0) {
51
+ return;
52
+ }
53
+
54
+ const Storage& storage = self->unsafe_storage();
55
+ if (!storage) {
56
+ auto new_storage = c10::make_intrusive<StorageImpl>(
57
+ StorageImpl::use_byte_size_t(),
58
+ new_size_bytes,
59
+ c10::GetCPUAllocator(),
60
+ true);
61
+ self->set_storage_keep_dtype(std::move(new_storage));
62
+ } else if (new_size_bytes > storage.nbytes()) {
63
+ resize_bytes_cpu(storage.unsafeGetStorageImpl(), new_size_bytes);
64
+ }
65
+ }
66
+
67
+ TORCH_API TensorImpl* resize_impl_cpu_(
68
+ TensorImpl* self,
69
+ IntArrayRef size,
70
+ at::OptionalIntArrayRef stride,
71
+ bool resize_storage = true);
72
+
73
+ template <typename T>
74
+ T maybe_convert_symint(c10::SymInt) = delete;
75
+
76
+ template <>
77
+ inline c10::SymInt maybe_convert_symint(c10::SymInt x) { return x; }
78
+
79
+ template <>
80
+ inline int64_t maybe_convert_symint(c10::SymInt x) { return x.guard_int(__FILE__, __LINE__); }
81
+
82
+ template <typename T>
83
+ inline void checkInBoundsForStorage(
84
+ ArrayRef<T> size,
85
+ ArrayRef<T> stride,
86
+ T storage_offset,
87
+ const caffe2::TypeMeta& data_type,
88
+ const Storage& new_storage) {
89
+ T storage_size_bytes, storage_size_plus_offset_bytes;
90
+ if (stride.data()) {
91
+ storage_size_bytes =
92
+ at::detail::computeStorageNbytes(size, stride, data_type.itemsize());
93
+ storage_size_plus_offset_bytes = at::detail::computeStorageNbytes(
94
+ size, stride, data_type.itemsize(), storage_offset);
95
+ } else {
96
+ storage_size_bytes =
97
+ at::detail::computeStorageNbytesContiguous(size, data_type.itemsize());
98
+ storage_size_plus_offset_bytes = at::detail::computeStorageNbytesContiguous(
99
+ size, data_type.itemsize(), storage_offset);
100
+ }
101
+ // It's ok to always evaluate to False for this early return for SymInts because
102
+ // (1) maybe_convert_symint below only installs guard for int64_t case
103
+ // (2) we check for this condition in the TORCH_MAYBE_SYM_CHECK below
104
+ if (TORCH_GUARD_SIZE_OBLIVIOUS(sym_eq(storage_size_bytes, 0))) {
105
+ // NB: (a tensor with arbitrary 0 dims)'s storage can have any numel.
106
+ return;
107
+ }
108
+ T new_storage_size_bytes = maybe_convert_symint<T>(new_storage.sym_nbytes());
109
+ TORCH_MAYBE_SYM_CHECK(
110
+ sym_eq(storage_size_bytes, 0) || sym_le(storage_size_plus_offset_bytes, new_storage_size_bytes),
111
+ "setStorage: sizes ",
112
+ size,
113
+ ", strides ",
114
+ stride,
115
+ ","
116
+ " storage offset ",
117
+ storage_offset,
118
+ ", and itemsize ",
119
+ data_type.itemsize(),
120
+ " requiring a storage size of ",
121
+ storage_size_plus_offset_bytes,
122
+ " are out of bounds for storage of size ",
123
+ new_storage_size_bytes);
124
+ }
125
+
126
+ template <typename T>
127
+ inline void checkSetStorage(Tensor& result, Storage storage, T storage_offset,
128
+ ArrayRef<T> size, ArrayRef<T> stride, bool check_offset_in_bounds = true) {
129
+ // FIXME: stride should be optional
130
+ if (stride.data()) {
131
+ TORCH_CHECK(size.size() == stride.size(), "unequal size length (", size.size(),
132
+ ") and stride length (", stride.size(), ")");
133
+ }
134
+
135
+ #ifdef DEBUG
136
+ TORCH_CHECK(size.size() <= INT_MAX, "size length (", size.size(), ") greater than INT_MAX");
137
+ #endif
138
+
139
+ // storageOffset
140
+ TORCH_CHECK(
141
+ storage_offset >= 0, "Tensor: invalid storage offset ", storage_offset);
142
+
143
+ // set_storage_{device} (except set_storage_meta__symint)
144
+ // will (unsafely) set the storage offset and then call resize_impl that
145
+ // handles resizing the storage However, resize_impl will only resize the
146
+ // storage if the sizes/strides changed. For the case that the sizes/strides
147
+ // remain unchanged, the storage offset is not properly validated, so we do
148
+ // that here.
149
+ if (check_offset_in_bounds) {
150
+ auto result_tensor_impl = result.unsafeGetTensorImpl();
151
+ bool size_unchanged = result_tensor_impl->generic_sizes<T>() == size;
152
+ bool stride_unchanged = stride.data()
153
+ ? result_tensor_impl->generic_strides<T>() == stride
154
+ : true;
155
+ if (size_unchanged && stride_unchanged) {
156
+ checkInBoundsForStorage(
157
+ size, stride, storage_offset, result.dtype(), storage);
158
+ }
159
+ }
160
+
161
+ // storage: note this can't be replaced with result.set_(storage) as the semantics of that
162
+ // function is to set the tensor size to be equal to the size of the storage.
163
+ if (!result.storage().is_alias_of(storage)) {
164
+ // Caffe2 might have tensors whose storages are null, but we
165
+ // don't allow it in PyTorch.
166
+ TORCH_INTERNAL_ASSERT(storage);
167
+ TORCH_INTERNAL_ASSERT(result.storage());
168
+
169
+ // We used to allow this, but this breaks device caching.
170
+ // Let's put an actual error message for this one.
171
+ TORCH_CHECK(result.storage().device() == storage.device(),
172
+ "Attempted to set the storage of a tensor on device \"", result.storage().device(),
173
+ "\" to a storage on different device \"", storage.device(),
174
+ "\". This is no longer allowed; the devices must match.");
175
+ result.unsafeGetTensorImpl()->set_storage_keep_dtype(std::move(storage));
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Set self's sizes, strides, and storage_offset.
181
+ * (size, stride, storage_offset) must be in bounds for self's storage.
182
+ */
183
+ template <typename T>
184
+ inline void setStrided(
185
+ const Tensor& self,
186
+ ArrayRef<T> size,
187
+ ArrayRef<T> stride,
188
+ T storage_offset) {
189
+ TORCH_CHECK(size.size() == stride.size(), "mismatch in length of strides and shape");
190
+ for (const auto& val : stride) {
191
+ TORCH_CHECK(val >= 0,
192
+ "as_strided: Negative strides are not supported at the moment, "
193
+ "got strides: ", stride);
194
+ }
195
+
196
+ auto* self_ = self.unsafeGetTensorImpl();
197
+ checkInBoundsForStorage(
198
+ size, stride, storage_offset, self_->dtype(), self_->storage());
199
+
200
+ /* storage offset */
201
+ TORCH_CHECK(storage_offset >= 0, "Tensor: invalid storage offset ", storage_offset);
202
+ self_->set_sizes_and_strides(size, stride, storage_offset);
203
+ }
204
+
205
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ResizeCommon.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/TensorFactories.h>
5
+ #include <ATen/NamedTensorUtils.h>
6
+ #include <c10/util/irange.h>
7
+
8
+ #ifndef AT_PER_OPERATOR_HEADERS
9
+ #include <ATen/NativeFunctions.h>
10
+ #else
11
+ #include <ATen/ops/empty.h>
12
+ #endif
13
+
14
+ namespace at::native {
15
+
16
+ template <typename T>
17
+ inline T storage_size_for(ArrayRef<T> size, ArrayRef<T> stride) {
18
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(size.size() == stride.size(),
19
+ "storage_size_for(size, stride) requires that size and stride ",
20
+ "have the same size as a precondition.");
21
+ T storage_size = 1;
22
+ for (const auto dim : c10::irange(size.size())) {
23
+ if (size[dim] == 0) {
24
+ storage_size = 0;
25
+ break;
26
+ }
27
+ storage_size += (size[dim] - 1) * stride[dim];
28
+ }
29
+ return storage_size;
30
+ }
31
+
32
+ inline const Tensor& resize_named_tensor_(
33
+ const Tensor& self,
34
+ IntArrayRef size,
35
+ std::optional<MemoryFormat> optional_memory_format) {
36
+ TORCH_INTERNAL_ASSERT(self.has_names());
37
+ TORCH_CHECK(
38
+ self.sizes() == size,
39
+ "Cannot resize named tensor with resize_ or resize_as_ (tried to resize "
40
+ "Tensor",
41
+ self.names(),
42
+ " with size ",
43
+ self.sizes(),
44
+ " to ",
45
+ size,
46
+ "). This may be caused by passing a named tensor ",
47
+ "as an `out=` argument; please ensure that the sizes are the same. ");
48
+ TORCH_CHECK(
49
+ !optional_memory_format.has_value(),
50
+ "Unsupported memory format for named tensor resize ",
51
+ optional_memory_format.value());
52
+ return self;
53
+ }
54
+
55
+ // For deterministic output, fill new elements that were added after a storage
56
+ // resize with NaN or MAX_INT. `old_storage_nbytes` is the size of the storage
57
+ // before the resize happened.
58
+ inline const Tensor& fill_resize_deterministic_(const Tensor& tensor, int64_t old_storage_nbytes) {
59
+ const at::Storage& storage = tensor.unsafeGetTensorImpl()->unsafe_storage();
60
+ int64_t new_storage_nbytes = storage.nbytes();
61
+ int64_t old_storage_numel = old_storage_nbytes / tensor.itemsize();
62
+ int64_t new_storage_numel = new_storage_nbytes / tensor.itemsize();
63
+ if (new_storage_numel > old_storage_numel) {
64
+ at::Tensor tensor_view = at::empty({}, at::TensorOptions().dtype(tensor.scalar_type()).device(tensor.device()));
65
+ tensor_view.set_(
66
+ storage,
67
+ /*storage_offset=*/old_storage_numel,
68
+ /*size=*/{new_storage_numel - old_storage_numel},
69
+ /*stride=*/{1});
70
+ at::native::fill_empty_deterministic_(tensor_view);
71
+ }
72
+ return tensor;
73
+ }
74
+
75
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ScatterGatherChecks.h ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <vector>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/ReduceOpsUtils.h>
6
+ #include <c10/util/irange.h>
7
+
8
+ namespace at::native {
9
+
10
+ namespace {
11
+
12
+ // checks whether index.dtype == int64
13
+ // and self.dtype == src.dtype if src is a Tensor
14
+ inline void scatter_gather_dtype_check(
15
+ const std::string& method_name,
16
+ const Tensor& self,
17
+ const Tensor& index,
18
+ const std::optional<Tensor>& src_opt = std::nullopt
19
+ ) {
20
+ if (index.numel() != 0) {
21
+ TORCH_CHECK(
22
+ index.scalar_type() == at::ScalarType::Long,
23
+ method_name, "(): Expected dtype int64 for index"
24
+ );
25
+ }
26
+
27
+ if (src_opt.has_value()) {
28
+ const auto& src = src_opt.value();
29
+ TORCH_CHECK(
30
+ self.scalar_type() == src.scalar_type(),
31
+ method_name, "(): Expected self.dtype to be equal to src.dtype"
32
+ );
33
+ }
34
+ }
35
+
36
+ // Used for `gather`-like methods
37
+ // Note: self means the input tensor here
38
+ // Test:
39
+ // 1. index.size(d) <= self.size(d) for all d != dim
40
+ // 2. index.dim() == self.dim()
41
+ inline void gather_shape_check(const Tensor& self, int64_t dim,
42
+ const Tensor& index
43
+ ) {
44
+ auto self_dims = ensure_nonempty_dim(self.dim());
45
+ TORCH_CHECK(self_dims == ensure_nonempty_dim(index.dim()),
46
+ "Index tensor must have the same number of dimensions as input tensor"
47
+ );
48
+
49
+ for (const auto i : c10::irange(self_dims)) {
50
+ if (i != dim) {
51
+ TORCH_CHECK(
52
+ ensure_nonempty_size(index, i) <= ensure_nonempty_size(self, i),
53
+ "Size does not match at dimension ", i,
54
+ " expected index ", index.sizes(),
55
+ " to be no larger than self ", self.sizes(),
56
+ " apart from dimension ", dim
57
+ );
58
+ }
59
+ }
60
+ }
61
+
62
+ // Used for `scatter` and `scatter_add`
63
+ // Tests:
64
+ // 1. index.size(d) <= self.size(d) for all d != dim
65
+ // 2. index.size(d) <= src.size(d) for all d if src is a Tensor
66
+ // 3. index.dim() == self.dim() == src.dim()
67
+ inline void scatter_shape_check(
68
+ const Tensor& self, int64_t dim, const Tensor& index,
69
+ const std::optional<Tensor>& src_opt = std::nullopt
70
+ ) {
71
+ if (index.numel() == 0) return;
72
+ TORCH_CHECK(
73
+ ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()),
74
+ "Index tensor must have the same number of dimensions as self tensor"
75
+ );
76
+
77
+ bool is_wrong_shape = false;
78
+ int64_t self_dims = ensure_nonempty_dim(self.dim());
79
+
80
+ // Check: index.size(d) <= self.size(d) for all d != dim
81
+ for (const auto d : c10::irange(self_dims)) {
82
+ int64_t index_d_size = ensure_nonempty_size(index, d);
83
+ if (d == dim) continue;
84
+ if (index_d_size > ensure_nonempty_size(self, d)) {
85
+ is_wrong_shape = true;
86
+ break;
87
+ }
88
+ }
89
+
90
+ // Check: index.size(d) <= src.size(d) for all d if src is Tensor
91
+ if (!is_wrong_shape && src_opt.has_value()) {
92
+ const auto& src = src_opt.value();
93
+ for (const auto d : c10::irange(self_dims)) {
94
+ int64_t index_d_size = ensure_nonempty_size(index, d);
95
+ if (index_d_size > ensure_nonempty_size(src, d)) {
96
+ is_wrong_shape = true;
97
+ break;
98
+ }
99
+ }
100
+ }
101
+
102
+ if (src_opt.has_value()) {
103
+ const auto& src = src_opt.value();
104
+
105
+ TORCH_CHECK(
106
+ ensure_nonempty_dim(src.dim()) == ensure_nonempty_dim(index.dim()),
107
+ "Index tensor must have the same number of dimensions as src tensor"
108
+ );
109
+
110
+ TORCH_CHECK(!is_wrong_shape,
111
+ "Expected index ", index.sizes(),
112
+ " to be no larger than self ", self.sizes(),
113
+ " apart from dimension ", dim,
114
+ " and to be no larger size than src ", src.sizes()
115
+ );
116
+ }
117
+ else {
118
+ TORCH_CHECK(!is_wrong_shape,
119
+ "Expected index ", index.sizes(),
120
+ " to be no larger than self ", self.sizes(),
121
+ " apart from dimension ", dim
122
+ );
123
+ }
124
+ }
125
+
126
+ } // anonymous namespace
127
+
128
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SegmentReduce.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/native/ReductionType.h>
5
+ #include <c10/core/Scalar.h>
6
+ #include <optional>
7
+
8
+ namespace at {
9
+ class Tensor;
10
+
11
+ namespace native {
12
+
13
+ using segment_reduce_lengths_fn = Tensor (*)(
14
+ ReductionType,
15
+ const Tensor&,
16
+ const Tensor&,
17
+ int64_t,
18
+ const std::optional<Scalar>&);
19
+ DECLARE_DISPATCH(segment_reduce_lengths_fn, _segment_reduce_lengths_stub)
20
+
21
+ using segment_reduce_offsets_fn = Tensor (*)(
22
+ ReductionType,
23
+ const Tensor&,
24
+ const Tensor&,
25
+ int64_t,
26
+ const std::optional<Scalar>&);
27
+ DECLARE_DISPATCH(segment_reduce_offsets_fn, _segment_reduce_offsets_stub)
28
+
29
+ using segment_reduce_lengths_backward_fn = Tensor (*)(
30
+ const Tensor&,
31
+ const Tensor&,
32
+ const Tensor&,
33
+ ReductionType,
34
+ const Tensor&,
35
+ int64_t,
36
+ const std::optional<Scalar>&);
37
+ DECLARE_DISPATCH(segment_reduce_lengths_backward_fn, _segment_reduce_lengths_backward_stub)
38
+
39
+ using segment_reduce_offsets_backward_fn = Tensor (*)(
40
+ const Tensor&,
41
+ const Tensor&,
42
+ const Tensor&,
43
+ ReductionType,
44
+ const Tensor&,
45
+ int64_t,
46
+ const std::optional<Scalar>&);
47
+ DECLARE_DISPATCH(segment_reduce_offsets_backward_fn, _segment_reduce_offsets_backward_stub)
48
+
49
+ } // namespace native
50
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SharedReduceOps.h ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // Please note that this file is
3
+ // used across both CPU and GPU.
4
+
5
+ #include <type_traits>
6
+ #include <complex>
7
+ #include <c10/macros/Macros.h>
8
+ #include <ATen/detail/FunctionTraits.h>
9
+ #include <ATen/NumericUtils.h>
10
+ #include <ATen/OpMathType.h>
11
+ #if defined(__CUDACC__)
12
+ #include <ATen/cuda/DeviceUtils.cuh>
13
+ #include <ATen/native/cuda/DeviceSqrt.cuh>
14
+ #elif defined(__HIPCC__)
15
+ #include <ATen/hip/DeviceUtils.cuh>
16
+ #include <ATen/native/hip/DeviceSqrt.cuh>
17
+ #endif
18
+ #if defined(__CUDACC__) || defined(__HIPCC__)
19
+ #include <thrust/pair.h>
20
+ #else
21
+ #include <cmath>
22
+ #define device_sqrt std::sqrt
23
+ #endif
24
+ #if defined(__CUDACC__) || defined(__HIPCC__)
25
+ template <typename scalar_t>
26
+ inline C10_DEVICE scalar_t max_propagate_nan(scalar_t a, scalar_t b) {
27
+ #if defined(__HIPCC__)
28
+ // TODO: remove this special case for HIP when issue is fixed:
29
+ // https://github.com/ROCm-Developer-Tools/HIP/issues/2209
30
+ scalar_t max = at::_isnan(a) ? a : (at::_isnan(b) ? b : std::max(a, b));
31
+ #else
32
+ scalar_t max = at::_isnan(b) ? b : std::max(a, b);
33
+ #endif
34
+ return max;
35
+ }
36
+ template <typename scalar_t>
37
+ inline C10_DEVICE scalar_t min_propagate_nan(scalar_t a, scalar_t b) {
38
+ #if defined(__HIPCC__)
39
+ // TODO: remove this special case for HIP when issue is fixed:
40
+ // https://github.com/ROCm-Developer-Tools/HIP/issues/2209
41
+ scalar_t min = at::_isnan(a) ? a : (at::_isnan(b) ? b : std::min(a, b));
42
+ #else
43
+ scalar_t min = at::_isnan(b) ? b : std::min(a, b);
44
+ #endif
45
+ return min;
46
+ }
47
+ #define MAX(X, Y) max_propagate_nan(X,Y)
48
+ #define MIN(X, Y) min_propagate_nan(X,Y)
49
+ #else
50
+ #include <ATen/native/cpu/zmath.h>
51
+ #define MAX(X, Y) max_impl(X,Y)
52
+ #define MIN(X, Y) min_impl(X,Y)
53
+ #endif
54
+
55
+ // ROCM hcc doesn't work well with using std:: in kernel functions
56
+ #if defined(__CUDA_ARCH__)
57
+ #include <c10/cuda/CUDAMathCompat.h>
58
+ #define compat_pow c10::cuda::compat::pow
59
+ #elif defined(__HIPCC__)
60
+ #include <c10/hip/HIPMathCompat.h>
61
+ #define compat_pow c10::hip::compat::pow
62
+ #else
63
+ #define compat_pow std::pow
64
+ #endif
65
+
66
+ namespace at::native {
67
+
68
+ namespace detail {
69
+
70
+ #if defined(__CUDACC__) || defined(__HIPCC__)
71
+ template <typename T1, typename T2> using pair = thrust::pair<T1, T2>;
72
+ #else
73
+ template <typename T1, typename T2> using pair = std::pair<T1, T2>;
74
+ #endif
75
+
76
+ } // namespace detail
77
+
78
+ template <typename scalar_t, typename index_t>
79
+ struct WelfordData {
80
+ scalar_t mean;
81
+ scalar_t m2;
82
+ index_t n;
83
+ scalar_t nf;
84
+
85
+ C10_HOST_DEVICE WelfordData() : mean(0), m2(0), n(0), nf(0) {}
86
+
87
+ C10_HOST_DEVICE WelfordData(
88
+ scalar_t mean,
89
+ scalar_t m2,
90
+ index_t n,
91
+ scalar_t nf)
92
+ : mean(mean), m2(m2), n(n), nf(nf) {}
93
+ };
94
+
95
+
96
+ template <typename scalar_t, typename acc_scalar_t, typename index_t, typename res_t>
97
+ struct WelfordOps {
98
+ acc_scalar_t correction;
99
+ bool take_sqrt;
100
+ public:
101
+ using acc_t = WelfordData<acc_scalar_t, index_t>;
102
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, index_t /*idx*/) const {
103
+ // We accumulate n in index_t to avoid cumulative rounding error, but still
104
+ // need nf for use in combine where int32 may overflow.
105
+ index_t new_n = acc.n + 1;
106
+ acc_scalar_t new_nf = static_cast<acc_scalar_t>(new_n);
107
+ acc_scalar_t delta = data - acc.mean;
108
+ acc_scalar_t new_mean = acc.mean + delta / new_nf;
109
+ acc_scalar_t new_delta = data - new_mean;
110
+ return {
111
+ new_mean,
112
+ acc.m2 + delta * new_delta,
113
+ new_n,
114
+ new_nf,
115
+ };
116
+ }
117
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
118
+ if (a.nf == 0) {
119
+ return b;
120
+ }
121
+ if (b.nf == 0) {
122
+ return a;
123
+ }
124
+ acc_scalar_t delta = b.mean - a.mean;
125
+ acc_scalar_t new_count = a.nf + b.nf;
126
+ acc_scalar_t nb_over_n = b.nf / new_count;
127
+ return {
128
+ a.mean + delta * nb_over_n,
129
+ a.m2 + b.m2 + delta * delta * a.nf * nb_over_n,
130
+ // setting acc.n as -1 since acc.n might not be able to represent the count
131
+ // correctly within its range, setting it to -1 to avoid confusion
132
+ -1,
133
+ new_count
134
+ };
135
+ }
136
+ inline C10_DEVICE res_t project(acc_t acc) const __ubsan_ignore_float_divide_by_zero__ {
137
+ const auto mean = static_cast<scalar_t>(acc.mean);
138
+ const auto divisor = acc.nf > correction ? acc.nf - correction : 0;
139
+ const auto var = acc.m2 / divisor;
140
+ res_t results(take_sqrt ? device_sqrt(var) : var, mean);
141
+ return results;
142
+ }
143
+
144
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
145
+ return acc;
146
+ }
147
+
148
+ #if defined(__CUDACC__) || defined(__HIPCC__)
149
+ inline __device__ acc_t warp_shfl_down(acc_t acc, int offset) const {
150
+ return {
151
+ WARP_SHFL_DOWN(acc.mean, offset)
152
+ , WARP_SHFL_DOWN(acc.m2, offset)
153
+ , WARP_SHFL_DOWN(acc.n, offset)
154
+ , WARP_SHFL_DOWN(acc.nf, offset)
155
+ };
156
+ }
157
+ #endif
158
+ C10_HOST_DEVICE WelfordOps(acc_scalar_t correction, bool take_sqrt)
159
+ : correction(correction), take_sqrt(take_sqrt) {}
160
+ };
161
+
162
+ template <typename scalar_t, typename acc_t=scalar_t, typename factor_t=acc_t, typename out_t = acc_t>
163
+ struct MeanOps {
164
+ factor_t factor;
165
+
166
+ inline C10_DEVICE acc_t reduce(acc_t a, scalar_t b, int64_t /*idx*/) const {
167
+ return combine(a, static_cast<acc_t>(b));
168
+ }
169
+
170
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
171
+ return a + b;
172
+ }
173
+
174
+ inline C10_DEVICE out_t project(acc_t a) const {
175
+ return a * factor;
176
+ }
177
+
178
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
179
+ return acc;
180
+ }
181
+
182
+ #if defined(__CUDACC__) || defined(__HIPCC__)
183
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t data, int offset) const {
184
+ return WARP_SHFL_DOWN(data, offset);
185
+ }
186
+ #endif
187
+
188
+ MeanOps(factor_t factor): factor(factor) {
189
+ }
190
+ };
191
+
192
+ // This accumulator template is used to calculate the minimum absolute value of
193
+ // a set of numbers.
194
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
195
+ // value. These types differ for complex number input support.
196
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
197
+ struct AbsMinOps {
198
+
199
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
200
+ return MIN(acc, static_cast<acc_t>(std::abs(at::opmath_type<scalar_t>(data))));
201
+ }
202
+
203
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
204
+ return MIN(a, b);
205
+ }
206
+
207
+ inline C10_DEVICE out_t project(acc_t a) const {
208
+ return a;
209
+ }
210
+
211
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
212
+ return acc;
213
+ }
214
+
215
+ #if defined(__CUDACC__) || defined(__HIPCC__)
216
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
217
+ return WARP_SHFL_DOWN(acc, offset);
218
+ }
219
+ #endif
220
+ };
221
+
222
+ // This accumulator template is used to calculate the maximum absolute value of
223
+ // a set of numbers.
224
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
225
+ // value. These types differ for complex number input support.
226
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
227
+ struct AbsMaxOps {
228
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
229
+ return MAX(acc, static_cast<acc_t>(std::abs(at::opmath_type<scalar_t>(data))));
230
+ }
231
+
232
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
233
+ return MAX(a, b);
234
+ }
235
+
236
+ inline C10_DEVICE out_t project(acc_t a) const {
237
+ return a;
238
+ }
239
+
240
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
241
+ return acc;
242
+ }
243
+
244
+ #if defined(__CUDACC__) || defined(__HIPCC__)
245
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
246
+ return WARP_SHFL_DOWN(acc, offset);
247
+ }
248
+ #endif
249
+ };
250
+
251
+ // This accumulator template is used to calculate the norm of the absolute value
252
+ // of a set of numbers.
253
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
254
+ // value. These types differ for complex number input support.
255
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
256
+ struct NormOps {
257
+ acc_t norm_;
258
+
259
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
260
+ return acc + compat_pow(static_cast<acc_t>(std::abs(at::opmath_type<scalar_t>(data))), norm_);
261
+ }
262
+
263
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
264
+ return a + b;
265
+ }
266
+
267
+ inline C10_DEVICE out_t project(acc_t a) const {
268
+ return compat_pow(a, static_cast<acc_t>(1.0) / norm_);
269
+ }
270
+
271
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
272
+ return acc;
273
+ }
274
+
275
+ #if defined(__CUDACC__) || defined(__HIPCC__)
276
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
277
+ return WARP_SHFL_DOWN(acc, offset);
278
+ }
279
+ #endif
280
+
281
+ NormOps(acc_t norm_): norm_(norm_) {
282
+ }
283
+ };
284
+
285
+ // This accumulator template is used to calculate the order zero norm of the
286
+ // absolute value of a set of numbers.
287
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
288
+ // value. These types differ for complex number input support.
289
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
290
+ struct NormZeroOps {
291
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
292
+ return acc + (data == static_cast<scalar_t>(0) ? static_cast<acc_t>(0) : static_cast<acc_t>(1));
293
+ }
294
+
295
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
296
+ return a + b;
297
+ }
298
+
299
+ inline C10_DEVICE out_t project(acc_t a) const {
300
+ return a;
301
+ }
302
+
303
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
304
+ return acc;
305
+ }
306
+
307
+
308
+ #if defined(__CUDACC__) || defined(__HIPCC__)
309
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
310
+ return WARP_SHFL_DOWN(acc, offset);
311
+ }
312
+ #endif
313
+ };
314
+
315
+ // This accumulator template is used to calculate the order one norm of the
316
+ // absolute value of a set of numbers.
317
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
318
+ // value. These types differ for complex number input support.
319
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
320
+ struct NormOneOps {
321
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
322
+ return acc + static_cast<acc_t>(std::abs(at::opmath_type<scalar_t>(data)));
323
+ }
324
+
325
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
326
+ return a + b;
327
+ }
328
+
329
+ inline C10_DEVICE out_t project(acc_t a) const {
330
+ return a;
331
+ }
332
+
333
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
334
+ return acc;
335
+ }
336
+
337
+ #if defined(__CUDACC__) || defined(__HIPCC__)
338
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
339
+ return WARP_SHFL_DOWN(acc, offset);
340
+ }
341
+ #endif
342
+ };
343
+
344
+
345
+ template<typename acc_t>
346
+ struct AbsSwitch {};
347
+
348
+ template<typename scalar_t, typename acc_t>
349
+ inline C10_DEVICE acc_t abs_if_complex(scalar_t data, AbsSwitch<acc_t>) {
350
+ return static_cast<acc_t>(data);
351
+ }
352
+
353
+ template<typename scalar_t, typename acc_t>
354
+ inline C10_DEVICE acc_t abs_if_complex(std::complex<scalar_t> data, AbsSwitch<acc_t>) {
355
+ return static_cast<acc_t>(std::abs(data));
356
+ }
357
+
358
+ template<typename scalar_t, typename acc_t>
359
+ inline C10_DEVICE acc_t abs_if_complex(c10::complex<scalar_t> data, AbsSwitch<acc_t>) {
360
+ return static_cast<acc_t>(std::abs(at::opmath_type<c10::complex<scalar_t>>(data)));
361
+ }
362
+
363
+ // This accumulator template is used to calculate the order two norm of the
364
+ // absolute value of a set of numbers.
365
+ // `scalar_t` is the type of the input and `acc_t` is the type of the accumulated
366
+ // value. These types differ for complex number input support.
367
+ template <typename scalar_t, typename acc_t = scalar_t, typename out_t = acc_t>
368
+ struct NormTwoOps {
369
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const {
370
+ acc_t data_ = abs_if_complex(data, AbsSwitch<acc_t>());
371
+ return acc + data_ * data_;
372
+ }
373
+
374
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
375
+ return a + b;
376
+ }
377
+
378
+ inline C10_DEVICE out_t project(acc_t a) const {
379
+ return device_sqrt(a);
380
+ }
381
+
382
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
383
+ return acc;
384
+ }
385
+
386
+ #if defined(__CUDACC__) || defined(__HIPCC__)
387
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
388
+ return WARP_SHFL_DOWN(acc, offset);
389
+ }
390
+ #endif
391
+ };
392
+
393
+ template <typename acc_t, typename data_t>
394
+ struct NanSumOps {
395
+ inline C10_DEVICE acc_t reduce(acc_t a, data_t b, int64_t /*idx*/) const {
396
+ return a + (at::_isnan(b) ? acc_t{0.} : acc_t{b});
397
+ }
398
+
399
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
400
+ return a + b;
401
+ }
402
+
403
+ inline C10_DEVICE data_t project(acc_t a) const {
404
+ return data_t{a};
405
+ }
406
+
407
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
408
+ return acc;
409
+ }
410
+
411
+ #if defined(__CUDACC__) || defined(__HIPCC__)
412
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t data, int offset) const {
413
+ return WARP_SHFL_DOWN(data, offset);
414
+ }
415
+ #endif
416
+ };
417
+
418
+ namespace detail {
419
+
420
+ template <typename scalar_t>
421
+ struct LessOrNan {
422
+ C10_DEVICE bool operator () (scalar_t a, scalar_t b, int64_t idx_a, int64_t idx_b) const {
423
+ // If (a == b), then choose the one with lower idx, else min(a, b)
424
+ if (at::_isnan(a)) {
425
+ if (at::_isnan(b)) {
426
+ return idx_a < idx_b;
427
+ }
428
+ return true;
429
+ }
430
+ return (a == b) ? idx_a < idx_b : (a < b);
431
+ }
432
+ };
433
+
434
+ template <typename scalar_t>
435
+ struct GreaterOrNan {
436
+ C10_DEVICE bool operator () (scalar_t a, scalar_t b, int64_t idx_a, int64_t idx_b) const {
437
+ // If (a == b), then choose the one with lower idx, else max(a, b)
438
+ if (at::_isnan(a)) {
439
+ if (at::_isnan(b)) {
440
+ return idx_a < idx_b;
441
+ }
442
+ return true;
443
+ }
444
+ return (a == b) ? idx_a < idx_b : (a > b);
445
+ }
446
+ };
447
+
448
+ template <typename comp_t>
449
+ struct MinMaxReductionOps {
450
+ using scalar_t = typename binary_function_traits<comp_t>::arg1_t;
451
+ using index_t = int64_t;
452
+ using arg_t = detail::pair<scalar_t, index_t>;
453
+
454
+ static C10_DEVICE arg_t project(arg_t arg) {
455
+ return arg;
456
+ }
457
+
458
+ static C10_DEVICE arg_t reduce(arg_t arg, scalar_t val, int64_t idx) {
459
+ return comp_t{}(arg.first, val, arg.second, idx) ? arg : arg_t(val, idx);
460
+ }
461
+
462
+ static C10_DEVICE arg_t combine(arg_t a, arg_t b) {
463
+ return comp_t{}(a.first, b.first, a.second, b.second) ? a : b;
464
+ }
465
+
466
+ static C10_DEVICE arg_t translate_idx(arg_t a, int64_t base_idx) {
467
+ return {a.first, a.second + base_idx};
468
+ }
469
+
470
+ #if defined(__CUDACC__) || defined(__HIPCC__)
471
+ static C10_DEVICE arg_t warp_shfl_down(arg_t arg, int offset) {
472
+ return arg_t(WARP_SHFL_DOWN(arg.first, offset),
473
+ WARP_SHFL_DOWN(arg.second, offset));
474
+ }
475
+ #endif
476
+ };
477
+
478
+ template <typename comp_t>
479
+ struct ArgReductionOps : public MinMaxReductionOps<comp_t> {
480
+ using typename MinMaxReductionOps<comp_t>::scalar_t;
481
+ using typename MinMaxReductionOps<comp_t>::index_t;
482
+ using typename MinMaxReductionOps<comp_t>::arg_t;
483
+
484
+ static C10_DEVICE index_t project(arg_t arg) {
485
+ return arg.second;
486
+ }
487
+ };
488
+
489
+ } // namespace detail
490
+
491
+ template <typename scalar_t>
492
+ struct ArgMaxOps :
493
+ public detail::ArgReductionOps<detail::GreaterOrNan<scalar_t>> {
494
+ };
495
+
496
+ template <typename scalar_t>
497
+ struct ArgMinOps :
498
+ public detail::ArgReductionOps<detail::LessOrNan<scalar_t>> {
499
+ };
500
+
501
+ template <typename scalar_t>
502
+ struct MinOps :
503
+ public detail::MinMaxReductionOps<detail::LessOrNan<scalar_t>> {
504
+ };
505
+
506
+ template <typename scalar_t>
507
+ struct MaxOps :
508
+ public detail::MinMaxReductionOps<detail::GreaterOrNan<scalar_t>> {
509
+ };
510
+
511
+ template <typename scalar_t, typename acc_scalar_t, typename index_t>
512
+ struct MinMaxOps {
513
+ using acc_t = detail::pair<acc_scalar_t, acc_scalar_t>;
514
+ inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, index_t /*idx*/) const {
515
+ return combine(acc, {data, data});
516
+ }
517
+
518
+ inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const {
519
+ auto min_val = (at::_isnan(a.first) || a.first < b.first) ? a.first : b.first;
520
+ auto max_val = (at::_isnan(a.second) || a.second > b.second) ? a.second : b.second;
521
+
522
+ return {min_val, max_val};
523
+ }
524
+
525
+ inline C10_DEVICE acc_t project(acc_t acc) const {
526
+ return acc;
527
+ }
528
+
529
+ static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) {
530
+ return acc;
531
+ }
532
+
533
+ #if defined(__CUDACC__) || defined(__HIPCC__)
534
+ inline C10_DEVICE acc_t warp_shfl_down(acc_t acc, int offset) const {
535
+ return {
536
+ WARP_SHFL_DOWN(acc.first, offset), WARP_SHFL_DOWN(acc.second, offset)
537
+ };
538
+ }
539
+ #endif
540
+ };
541
+
542
+ } // namespace at::native
543
+
544
+ #undef MAX
545
+ #undef MIN
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SobolEngineOpsUtils.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// This file contains some tensor-agnostic operations to be used in the
2
+ /// core functions of the `SobolEngine`
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ #ifndef AT_PER_OPERATOR_HEADERS
6
+ #include <ATen/Functions.h>
7
+ #else
8
+ #include <ATen/ops/arange.h>
9
+ #include <ATen/ops/mul.h>
10
+ #include <ATen/ops/pow.h>
11
+ #endif
12
+
13
+ namespace at::native::sobol_utils {
14
+
15
+ /// Function to return the minimum of number of bits to represent the integer `n`
16
+ inline int64_t bit_length(const int64_t n) {
17
+ int64_t nbits, nloc;
18
+ for (nloc = n, nbits = 0; nloc > 0; nloc /= 2, nbits++);
19
+ return nbits;
20
+ }
21
+
22
+ /// Function to get the position of the rightmost zero in the bit representation of an integer
23
+ /// This value is the zero-indexed position
24
+ inline int64_t rightmost_zero(const int64_t n) {
25
+ int64_t z, i;
26
+ for (z = n, i = 0; z % 2 == 1; z /= 2, i++);
27
+ return i;
28
+ }
29
+
30
+ /// Function to get a subsequence of bits in the representation of an integer starting from
31
+ /// `pos` and of length `length`
32
+ inline int64_t bitsubseq(const int64_t n, const int64_t pos, const int64_t length) {
33
+ return (n >> pos) & ((1 << length) - 1);
34
+ }
35
+
36
+ /// Function to perform the inner product between a batched square matrix and a power of 2 vector
37
+ inline at::Tensor cdot_pow2(const at::Tensor& bmat) {
38
+ at::Tensor inter = at::arange(bmat.size(-1) - 1, -1, -1, bmat.options());
39
+ inter = at::pow(2, inter).expand_as(bmat);
40
+ return at::mul(inter, bmat).sum(-1);
41
+ }
42
+
43
+ /// All definitions below this point are data. These are constant, and should not be modified
44
+ /// without notice
45
+
46
+ constexpr int64_t MAXDIM = 21201;
47
+ constexpr int64_t MAXDEG = 18;
48
+ constexpr int64_t MAXBIT = 30;
49
+ constexpr int64_t LARGEST_NUMBER = 1 << MAXBIT;
50
+ constexpr float RECIPD = 1.0 / LARGEST_NUMBER;
51
+
52
+ extern const int64_t poly[MAXDIM];
53
+ extern const int64_t initsobolstate[MAXDIM][MAXDEG];
54
+
55
+ } // namespace at::native::sobol_utils
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Sorting.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 TensorBase;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ enum class QUANTILE_INTERPOLATION_MODE : uint8_t {
13
+ LINEAR,
14
+ LOWER,
15
+ HIGHER,
16
+ MIDPOINT,
17
+ NEAREST
18
+ };
19
+
20
+ using sort_fn = void(*)(const TensorBase&, const TensorBase&, const TensorBase&, int64_t, bool, bool);
21
+ using topk_fn = void(*)(const TensorBase&, const TensorBase&, const TensorBase&, int64_t, int64_t, bool, bool);
22
+
23
+ DECLARE_DISPATCH(sort_fn, sort_stub)
24
+ DECLARE_DISPATCH(topk_fn, topk_stub)
25
+
26
+ void _fill_indices(const TensorBase &indices, int64_t dim);
27
+
28
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SortingUtils.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/NumericUtils.h>
4
+ #include <ATen/native/Resize.h>
5
+ #include <c10/util/irange.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/Functions.h>
9
+ #else
10
+ #include <ATen/ops/empty.h>
11
+ #endif
12
+
13
+ namespace at::native {
14
+
15
+ // ensure we get good values and indices for kthvalue, mode
16
+ // this will always be with the reducing dim as 1-d
17
+ inline void _reduction_with_indices_allocate_or_resize_output(
18
+ Tensor& values,
19
+ Tensor& indices,
20
+ const Tensor& self,
21
+ int64_t dim_,
22
+ bool keepdim) {
23
+ int64_t dim = maybe_wrap_dim(dim_, self.dim(), /*wrap_scalar=*/true);
24
+ auto result_sizes = self.sizes().vec();
25
+ if (!result_sizes.empty()) {
26
+ result_sizes[dim] = 1;
27
+ }
28
+ if (values.defined()) {
29
+ TORCH_CHECK(
30
+ self.options().type_equal(values.options()),
31
+ "output values must be of same type as input");
32
+ if (!keepdim && values.dim() == self.dim() - 1) {
33
+ // unsqueeze to preserve passed in noncontiguous tensor in resize
34
+ values.unsqueeze_(dim);
35
+ }
36
+ resize_output(values, result_sizes);
37
+ } else {
38
+ values = at::empty(result_sizes, self.options());
39
+ }
40
+ if (indices.defined()) {
41
+ TORCH_CHECK(
42
+ indices.dtype() == kLong, "output indices must be of scalar type Long");
43
+ TORCH_CHECK(
44
+ indices.device() == self.device(),
45
+ "output indices must be on same device as input");
46
+ if (!keepdim && indices.dim() == self.dim() - 1) {
47
+ // unsqueeze to preserve passed in noncontiguous tensor in resize
48
+ indices.unsqueeze_(dim);
49
+ }
50
+ resize_output(indices, result_sizes);
51
+ } else {
52
+ indices = at::empty(result_sizes, self.options().dtype(kLong));
53
+ }
54
+ }
55
+
56
+ // ensure we get good values and indices for topk
57
+ inline void _allocate_or_resize_output_with_indices(
58
+ Tensor& values,
59
+ Tensor& indices,
60
+ const Tensor& self,
61
+ int64_t dim_,
62
+ int64_t k) {
63
+ int64_t dim = maybe_wrap_dim(dim_, self.dim(), /*wrap_scalar=*/true);
64
+ auto result_sizes = self.sizes().vec();
65
+ if (!result_sizes.empty()) {
66
+ result_sizes[dim] = k;
67
+ }
68
+ if (values.defined()) {
69
+ TORCH_CHECK(
70
+ self.options().type_equal(values.options()),
71
+ "output values must be of same type as input");
72
+ values.resize_(result_sizes);
73
+ } else {
74
+ values = at::empty(result_sizes, self.options());
75
+ }
76
+ if (indices.defined()) {
77
+ TORCH_CHECK(
78
+ indices.dtype() == kLong, "output indices must be of scalar type Long");
79
+ TORCH_CHECK(
80
+ indices.device() == self.device(),
81
+ "output indices must be on same device as input");
82
+ indices.resize_(result_sizes);
83
+ } else {
84
+ indices = at::empty(result_sizes, self.options().dtype(kLong));
85
+ }
86
+ }
87
+
88
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SparseTensorUtils.h ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Parallel.h>
4
+ #include <ATen/SparseTensorImpl.h>
5
+ #include <ATen/core/Tensor.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/Functions.h>
9
+ #else
10
+ #include <ATen/ops/empty.h>
11
+ #include <ATen/ops/tensor.h>
12
+ #endif
13
+
14
+ namespace at::sparse {
15
+
16
+ // Just for documentary purposes
17
+ using SparseTensor = Tensor;
18
+ using SparseType = Type;
19
+
20
+ // This is an internal utility function for getting at the SparseTensorImpl,
21
+ // so that we can write sparse tensor specific accessors for special fields
22
+ // in SparseTensor. You should only use this for writing low level
23
+ // setters/getters for SparseTensorImpl fields; otherwise, you should use
24
+ // the low level setters/getters that were implemented using this.
25
+ //
26
+ // This may be called repeatedly, so make sure it's pretty cheap.
27
+ inline SparseTensorImpl* get_sparse_impl(const SparseTensor& self) {
28
+ TORCH_INTERNAL_ASSERT(
29
+ self.is_sparse(), "_internal_get_SparseTensorImpl: not a sparse tensor");
30
+ return static_cast<SparseTensorImpl*>(self.unsafeGetTensorImpl());
31
+ }
32
+
33
+ // Takes indices and values and directly puts them into the sparse tensor, no
34
+ // copy. This used to be called THSTensor_(_move)
35
+ inline void alias_into_sparse(
36
+ const SparseTensor& self,
37
+ const Tensor& indices,
38
+ const Tensor& values) {
39
+ get_sparse_impl(self)->set_indices_and_values_unsafe(indices, values);
40
+ }
41
+
42
+ // Take indices and values and makes a (data) copy of them to put into the
43
+ // sparse indices/values. This used to be called THSTensor_(_set)
44
+ inline void copy_into_sparse(
45
+ const SparseTensor& self,
46
+ const Tensor& indices,
47
+ const Tensor& values,
48
+ bool non_blocking) {
49
+ alias_into_sparse(
50
+ self,
51
+ indices.to(self._indices().options(), non_blocking, /*copy=*/true),
52
+ values.to(self._values().options(), non_blocking, /*copy=*/true));
53
+ }
54
+
55
+ // TODO: put this into the public API
56
+ inline bool is_same_tensor(const Tensor& lhs, const Tensor& rhs) {
57
+ return lhs.unsafeGetTensorImpl() == rhs.unsafeGetTensorImpl();
58
+ }
59
+
60
+ inline bool is_same_density(const SparseTensor& self, const SparseTensor& src) {
61
+ return self.sparse_dim() == src.sparse_dim() &&
62
+ self.dense_dim() == src.dense_dim();
63
+ }
64
+
65
+ // Give us a new values tensor, with the same dimensionality
66
+ // as 'values' but with a new number of non-zero elements.
67
+ // TODO: Expose this for real in ATen, some day?
68
+ // NB: Doesn't preserve data.
69
+ inline Tensor new_values_with_size_of(const Tensor& values, int64_t nnz) {
70
+ std::vector<int64_t> size = values.sizes().vec();
71
+ size[0] = nnz;
72
+ return at::empty(size, values.options());
73
+ }
74
+
75
+ // NOTE [ Flatten Sparse Indices ]
76
+ // This helper function flattens a sparse indices tensor (a Tensor) into a 1D
77
+ // indices tensor. E.g.,
78
+ // input = [[2, 4, 0],
79
+ // [3, 1, 10]]
80
+ // full_size = [2, 12]
81
+ // output = [ 2 * 12 + 3, 4 * 12 + 1, 0 * 12 + 10 ] = [27, 49, 10]
82
+ //
83
+ // In other words, assuming that each `indices[i, :]` is a valid index to a
84
+ // tensor `t` of shape `full_size`. This returns the corresponding indices to
85
+ // the flattened tensor `t.reshape( prod(full_size[:indices.size(0)]), -1 )`.
86
+ // if forceClone is true, the result will forced to be a clone of self.
87
+ // if force_clone is true, the result will forced to be a clone of self.
88
+ TORCH_API Tensor flatten_indices(
89
+ const Tensor& indices,
90
+ IntArrayRef full_size,
91
+ bool force_clone = false);
92
+
93
+ // Flatten sparse tensor's indices from nD to 1D, similar to NOTE [ Flatten
94
+ // Sparse Indices ], except this one allows partial flatten: only flatten on
95
+ // specified dims. Note that the flatten indices might be uncoalesced if
96
+ // dims_to_flatten.size() < sparse_dim. Also if input indices is already
97
+ // coalesced, the flattened indices will also be sorted.
98
+ //
99
+ // args:
100
+ // indices: sparse tensor indices
101
+ // sizes: sparse tensor sizes
102
+ // dims_to_flatten: a list of dim index to flatten
103
+ //
104
+ // Ex1:
105
+ // indices = [[2, 4, 0],
106
+ // [3, 1, 3]]
107
+ // sizes = [2, 12]
108
+ // dims_to_flatten = [0, 1]
109
+ // new_indices = [ 2 * 12 + 3, 4 * 12 + 1, 0 * 12 + 3 ] = [27, 49, 3]
110
+ //
111
+ // Ex2:
112
+ // dims_to_flatten = [1]
113
+ // new_indices = [ 3, 1, 3 ] # uncoalesced
114
+ TORCH_API Tensor flatten_indices_by_dims(
115
+ const Tensor& indices,
116
+ const IntArrayRef& sizes,
117
+ const IntArrayRef& dims_to_flatten);
118
+
119
+ // Find the CSR representation for a row `indices` from the COO format
120
+ TORCH_API Tensor coo_to_csr(const int64_t* indices, int64_t dim, int64_t nnz);
121
+
122
+ TORCH_API Tensor zeros_like_with_indices(const Tensor& t);
123
+
124
+ template <size_t static_shape_max_len>
125
+ class TensorGeometryHolder {
126
+ using geometry_holder_t = std::array<int64_t, static_shape_max_len>;
127
+
128
+ public:
129
+ explicit TensorGeometryHolder(
130
+ IntArrayRef sizes,
131
+ IntArrayRef strides,
132
+ TensorOptions options = {}) {
133
+ std::copy(sizes.begin(), sizes.end(), t_sizes.begin());
134
+ std::copy(strides.begin(), strides.end(), t_strides.begin());
135
+ }
136
+
137
+ explicit TensorGeometryHolder(const Tensor& t)
138
+ : TensorGeometryHolder(t.sizes(), t.strides()) {}
139
+
140
+ auto operator*() const {
141
+ return std::make_tuple(t_sizes, t_strides);
142
+ }
143
+
144
+ private:
145
+ geometry_holder_t t_sizes;
146
+ geometry_holder_t t_strides;
147
+ };
148
+
149
+ template <>
150
+ class TensorGeometryHolder<0> {
151
+ using geometry_holder_t = Tensor;
152
+
153
+ public:
154
+ explicit TensorGeometryHolder(
155
+ IntArrayRef sizes,
156
+ IntArrayRef strides,
157
+ TensorOptions options) {
158
+ const int64_t t_ndims = sizes.size();
159
+ const auto cpu_options = TensorOptions(options).dtype(kLong).device(kCPU);
160
+ Tensor t_sizes_and_strides_cpu = at::empty({2, t_ndims}, cpu_options);
161
+ t_sizes_and_strides_cpu.select(0, 0).copy_(at::tensor(sizes, cpu_options));
162
+ t_sizes_and_strides_cpu.select(0, 1).copy_(
163
+ at::tensor(strides, cpu_options));
164
+ const Tensor t_sizes_and_strides =
165
+ t_sizes_and_strides_cpu.to(options.device());
166
+ t_sizes = t_sizes_and_strides.select(0, 0);
167
+ t_strides = t_sizes_and_strides.select(0, 1);
168
+ }
169
+
170
+ explicit TensorGeometryHolder(const Tensor& t)
171
+ : TensorGeometryHolder(t.sizes(), t.strides(), t.options()) {}
172
+
173
+ auto operator*() const {
174
+ return std::make_tuple(
175
+ t_sizes.template data_ptr<int64_t>(),
176
+ t_strides.template data_ptr<int64_t>());
177
+ }
178
+
179
+ private:
180
+ geometry_holder_t t_sizes;
181
+ geometry_holder_t t_strides;
182
+ };
183
+
184
+ // Return all indices of a tensor with the given shape.
185
+ //
186
+ // full_coo_indices(shape) is equivalent to
187
+ // torch.ones(shape).nonzero().transpose(-2, -1) but much faster.
188
+ TORCH_API Tensor full_coo_indices(IntArrayRef sizes, TensorOptions options);
189
+
190
+ } // namespace at::sparse
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/SpectralOpsUtils.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+ #include <stdexcept>
5
+ #include <sstream>
6
+ #include <c10/core/ScalarType.h>
7
+ #include <c10/util/ArrayRef.h>
8
+ #include <c10/util/Exception.h>
9
+ #include <ATen/native/DispatchStub.h>
10
+ #include <ATen/core/TensorBase.h>
11
+
12
+ namespace at::native {
13
+
14
+ // Normalization types used in _fft_with_size
15
+ enum class fft_norm_mode {
16
+ none, // No normalization
17
+ by_root_n, // Divide by sqrt(signal_size)
18
+ by_n, // Divide by signal_size
19
+ };
20
+
21
+ // NOTE [ Fourier Transform Conjugate Symmetry ]
22
+ //
23
+ // Real-to-complex Fourier transform satisfies the conjugate symmetry. That is,
24
+ // assuming X is the transformed K-dimensionsal signal, we have
25
+ //
26
+ // X[i_1, ..., i_K] = X[j_i, ..., j_K]*,
27
+ //
28
+ // where j_k = (N_k - i_k) mod N_k, N_k being the signal size at dim k,
29
+ // * is the conjugate operator.
30
+ //
31
+ // Therefore, in such cases, FFT libraries return only roughly half of the
32
+ // values to avoid redundancy:
33
+ //
34
+ // X[:, :, ..., :floor(N / 2) + 1]
35
+ //
36
+ // This is also the assumption in cuFFT and MKL. In ATen SpectralOps, such
37
+ // halved signal will also be returned by default (flag onesided=True).
38
+ // The following infer_ft_real_to_complex_onesided_size function calculates the
39
+ // onesided size from the twosided size.
40
+ //
41
+ // Note that this loses some information about the size of signal at last
42
+ // dimension. E.g., both 11 and 10 maps to 6. Hence, the following
43
+ // infer_ft_complex_to_real_onesided_size function takes in optional parameter
44
+ // to infer the twosided size from given onesided size.
45
+ //
46
+ // cuFFT doc: http://docs.nvidia.com/cuda/cufft/index.html#multi-dimensional
47
+ // MKL doc: https://software.intel.com/en-us/mkl-developer-reference-c-dfti-complex-storage-dfti-real-storage-dfti-conjugate-even-storage#CONJUGATE_EVEN_STORAGE
48
+
49
+ inline int64_t infer_ft_real_to_complex_onesided_size(int64_t real_size) {
50
+ return (real_size / 2) + 1;
51
+ }
52
+
53
+ inline int64_t infer_ft_complex_to_real_onesided_size(int64_t complex_size,
54
+ int64_t expected_size=-1) {
55
+ int64_t base = (complex_size - 1) * 2;
56
+ if (expected_size < 0) {
57
+ return base + 1;
58
+ } else if (base == expected_size) {
59
+ return base;
60
+ } else if (base + 1 == expected_size) {
61
+ return base + 1;
62
+ } else {
63
+ std::ostringstream ss;
64
+ ss << "expected real signal size " << expected_size << " is incompatible "
65
+ << "with onesided complex frequency size " << complex_size;
66
+ TORCH_CHECK(false, ss.str());
67
+ }
68
+ }
69
+
70
+ using fft_fill_with_conjugate_symmetry_fn =
71
+ void (*)(ScalarType dtype, IntArrayRef mirror_dims, IntArrayRef half_sizes,
72
+ IntArrayRef in_strides, const void* in_data,
73
+ IntArrayRef out_strides, void* out_data);
74
+ DECLARE_DISPATCH(fft_fill_with_conjugate_symmetry_fn, fft_fill_with_conjugate_symmetry_stub)
75
+
76
+ // In real-to-complex transform, cuFFT and MKL only fill half of the values
77
+ // due to conjugate symmetry. This function fills in the other half of the full
78
+ // fft by using the Hermitian symmetry in the signal.
79
+ // self should be the shape of the full signal and dims.back() should be the
80
+ // one-sided dimension.
81
+ // See NOTE [ Fourier Transform Conjugate Symmetry ]
82
+ TORCH_API void _fft_fill_with_conjugate_symmetry_(const Tensor& self, IntArrayRef dims);
83
+
84
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/StridedRandomAccessor.h ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ namespace at::native {
4
+
5
+ // (Const)StridedRandomAccessor is a
6
+ // (const) random access iterator defined over
7
+ // a strided array.
8
+
9
+ // The traits below are to introduce __restrict__
10
+ // modifier on different platforms.
11
+
12
+ template <typename T>
13
+ struct DefaultPtrTraits {
14
+ using PtrType = T*;
15
+ };
16
+
17
+ #if (defined(_WIN32) || defined(_WIN64))
18
+ #define RESTRICT __restrict
19
+ #else
20
+ #define RESTRICT __restrict__
21
+ #endif
22
+
23
+ template <typename T>
24
+ struct RestrictPtrTraits {
25
+ using PtrType = T* RESTRICT;
26
+ };
27
+
28
+ template <
29
+ typename T,
30
+ typename index_t = int64_t,
31
+ template <typename U> class PtrTraits = DefaultPtrTraits
32
+ >
33
+ class ConstStridedRandomAccessor {
34
+ public:
35
+ using difference_type = index_t;
36
+ using value_type = const T;
37
+ using pointer = const typename PtrTraits<T>::PtrType;
38
+ using reference = const value_type&;
39
+ using iterator_category = std::random_access_iterator_tag;
40
+
41
+ using PtrType = typename PtrTraits<T>::PtrType;
42
+ using index_type = index_t;
43
+
44
+ // Constructors {
45
+ C10_HOST_DEVICE
46
+ ConstStridedRandomAccessor(PtrType ptr, index_t stride)
47
+ : ptr{ptr}, stride{stride}
48
+ {}
49
+
50
+ C10_HOST_DEVICE
51
+ explicit ConstStridedRandomAccessor(PtrType ptr)
52
+ : ptr{ptr}, stride{static_cast<index_t>(1)}
53
+ {}
54
+
55
+ C10_HOST_DEVICE
56
+ ConstStridedRandomAccessor()
57
+ : ptr{nullptr}, stride{static_cast<index_t>(1)}
58
+ {}
59
+ // }
60
+
61
+ // Pointer-like operations {
62
+ C10_HOST_DEVICE
63
+ reference operator*() const {
64
+ return *ptr;
65
+ }
66
+
67
+ C10_HOST_DEVICE
68
+ const value_type* operator->() const {
69
+ return reinterpret_cast<const value_type*>(ptr);
70
+ }
71
+
72
+ C10_HOST_DEVICE
73
+ reference operator[](index_t idx) const {
74
+ return ptr[idx * stride];
75
+ }
76
+ // }
77
+
78
+ // Prefix/postfix increment/decrement {
79
+ C10_HOST_DEVICE
80
+ ConstStridedRandomAccessor& operator++() {
81
+ ptr += stride;
82
+ return *this;
83
+ }
84
+
85
+ C10_HOST_DEVICE
86
+ ConstStridedRandomAccessor operator++(int) {
87
+ ConstStridedRandomAccessor copy(*this);
88
+ ++*this;
89
+ return copy;
90
+ }
91
+
92
+ C10_HOST_DEVICE
93
+ ConstStridedRandomAccessor& operator--() {
94
+ ptr -= stride;
95
+ return *this;
96
+ }
97
+
98
+ C10_HOST_DEVICE
99
+ ConstStridedRandomAccessor operator--(int) {
100
+ ConstStridedRandomAccessor copy(*this);
101
+ --*this;
102
+ return copy;
103
+ }
104
+ // }
105
+
106
+ // Arithmetic operations {
107
+ C10_HOST_DEVICE
108
+ ConstStridedRandomAccessor& operator+=(index_t offset) {
109
+ ptr += offset * stride;
110
+ return *this;
111
+ }
112
+
113
+ C10_HOST_DEVICE
114
+ ConstStridedRandomAccessor operator+(index_t offset) const {
115
+ return ConstStridedRandomAccessor(ptr + offset * stride, stride);
116
+ }
117
+
118
+ C10_HOST_DEVICE
119
+ friend ConstStridedRandomAccessor operator+(
120
+ index_t offset,
121
+ const ConstStridedRandomAccessor& accessor
122
+ ) {
123
+ return accessor + offset;
124
+ }
125
+
126
+ C10_HOST_DEVICE
127
+ ConstStridedRandomAccessor& operator-=(index_t offset) {
128
+ ptr -= offset * stride;
129
+ return *this;
130
+ }
131
+
132
+ C10_HOST_DEVICE
133
+ ConstStridedRandomAccessor operator-(index_t offset) const {
134
+ return ConstStridedRandomAccessor(ptr - offset * stride, stride);
135
+ }
136
+
137
+ // Note that this operator is well-defined when `this` and `other`
138
+ // represent the same sequences, i.e. when
139
+ // 1. this.stride == other.stride,
140
+ // 2. |other - this| / this.stride is an Integer.
141
+ C10_HOST_DEVICE
142
+ difference_type operator-(const ConstStridedRandomAccessor& other) const {
143
+ return (ptr - other.ptr) / stride;
144
+ }
145
+ // }
146
+
147
+ // Comparison operators {
148
+ C10_HOST_DEVICE
149
+ bool operator==(const ConstStridedRandomAccessor& other) const {
150
+ return (ptr == other.ptr) && (stride == other.stride);
151
+ }
152
+
153
+ C10_HOST_DEVICE
154
+ bool operator!=(const ConstStridedRandomAccessor& other) const {
155
+ return !(*this == other);
156
+ }
157
+
158
+ C10_HOST_DEVICE
159
+ bool operator<(const ConstStridedRandomAccessor& other) const {
160
+ return ptr < other.ptr;
161
+ }
162
+
163
+ C10_HOST_DEVICE
164
+ bool operator<=(const ConstStridedRandomAccessor& other) const {
165
+ return (*this < other) || (*this == other);
166
+ }
167
+
168
+ C10_HOST_DEVICE
169
+ bool operator>(const ConstStridedRandomAccessor& other) const {
170
+ return !(*this <= other);
171
+ }
172
+
173
+ C10_HOST_DEVICE
174
+ bool operator>=(const ConstStridedRandomAccessor& other) const {
175
+ return !(*this < other);
176
+ }
177
+ // }
178
+
179
+ protected:
180
+ PtrType ptr;
181
+ index_t stride;
182
+ };
183
+
184
+ template <
185
+ typename T,
186
+ typename index_t = int64_t,
187
+ template <typename U> class PtrTraits = DefaultPtrTraits
188
+ >
189
+ class StridedRandomAccessor
190
+ : public ConstStridedRandomAccessor<T, index_t, PtrTraits> {
191
+ public:
192
+ using difference_type = index_t;
193
+ using value_type = T;
194
+ using pointer = typename PtrTraits<T>::PtrType;
195
+ using reference = value_type&;
196
+
197
+ using BaseType = ConstStridedRandomAccessor<T, index_t, PtrTraits>;
198
+ using PtrType = typename PtrTraits<T>::PtrType;
199
+
200
+ // Constructors {
201
+ C10_HOST_DEVICE
202
+ StridedRandomAccessor(PtrType ptr, index_t stride)
203
+ : BaseType(ptr, stride)
204
+ {}
205
+
206
+ C10_HOST_DEVICE
207
+ explicit StridedRandomAccessor(PtrType ptr)
208
+ : BaseType(ptr)
209
+ {}
210
+
211
+ C10_HOST_DEVICE
212
+ StridedRandomAccessor()
213
+ : BaseType()
214
+ {}
215
+ // }
216
+
217
+ // Pointer-like operations {
218
+ C10_HOST_DEVICE
219
+ reference operator*() const {
220
+ return *this->ptr;
221
+ }
222
+
223
+ C10_HOST_DEVICE
224
+ value_type* operator->() const {
225
+ return reinterpret_cast<value_type*>(this->ptr);
226
+ }
227
+
228
+ C10_HOST_DEVICE
229
+ reference operator[](index_t idx) const {
230
+ return this->ptr[idx * this->stride];
231
+ }
232
+ // }
233
+
234
+ // Prefix/postfix increment/decrement {
235
+ C10_HOST_DEVICE
236
+ StridedRandomAccessor& operator++() {
237
+ this->ptr += this->stride;
238
+ return *this;
239
+ }
240
+
241
+ C10_HOST_DEVICE
242
+ StridedRandomAccessor operator++(int) {
243
+ StridedRandomAccessor copy(*this);
244
+ ++*this;
245
+ return copy;
246
+ }
247
+
248
+ C10_HOST_DEVICE
249
+ StridedRandomAccessor& operator--() {
250
+ this->ptr -= this->stride;
251
+ return *this;
252
+ }
253
+
254
+ C10_HOST_DEVICE
255
+ StridedRandomAccessor operator--(int) {
256
+ StridedRandomAccessor copy(*this);
257
+ --*this;
258
+ return copy;
259
+ }
260
+ // }
261
+
262
+ // Arithmetic operations {
263
+ C10_HOST_DEVICE
264
+ StridedRandomAccessor& operator+=(index_t offset) {
265
+ this->ptr += offset * this->stride;
266
+ return *this;
267
+ }
268
+
269
+ C10_HOST_DEVICE
270
+ StridedRandomAccessor operator+(index_t offset) const {
271
+ return StridedRandomAccessor(this->ptr + offset * this->stride, this->stride);
272
+ }
273
+
274
+ C10_HOST_DEVICE
275
+ friend StridedRandomAccessor operator+(
276
+ index_t offset,
277
+ const StridedRandomAccessor& accessor
278
+ ) {
279
+ return accessor + offset;
280
+ }
281
+
282
+ C10_HOST_DEVICE
283
+ StridedRandomAccessor& operator-=(index_t offset) {
284
+ this->ptr -= offset * this->stride;
285
+ return *this;
286
+ }
287
+
288
+ C10_HOST_DEVICE
289
+ StridedRandomAccessor operator-(index_t offset) const {
290
+ return StridedRandomAccessor(this->ptr - offset * this->stride, this->stride);
291
+ }
292
+
293
+ // Note that here we call BaseType::operator- version
294
+ C10_HOST_DEVICE
295
+ difference_type operator-(const BaseType& other) const {
296
+ return (static_cast<const BaseType&>(*this) - other);
297
+ }
298
+ // }
299
+ };
300
+
301
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorAdvancedIndexing.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Indexing tensors by tensors
4
+
5
+ #include <ATen/core/List.h>
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/native/DispatchStub.h>
8
+ #include <ATen/native/ReductionType.h>
9
+
10
+ namespace at {
11
+ struct TensorIterator;
12
+ }
13
+
14
+ namespace at::native {
15
+
16
+ using index_put_with_sort_fn = void (*)(
17
+ Tensor&,
18
+ const c10::List<std::optional<Tensor>>&,
19
+ const Tensor&,
20
+ bool accumulate,
21
+ bool unsafe);
22
+ using index_put_with_sort_quantized_fn = void (*)(
23
+ Tensor& self,
24
+ const c10::List<std::optional<Tensor>>& indices,
25
+ const Tensor& value,
26
+ double scale,
27
+ int zero_point,
28
+ bool unsafe);
29
+ using gather_fn = void (*)(
30
+ const Tensor& result,
31
+ const Tensor& self,
32
+ int64_t dim,
33
+ const Tensor& index);
34
+ using scatter_fn = void (*)(
35
+ const Tensor& self,
36
+ int64_t dim,
37
+ const Tensor& index,
38
+ const Tensor& src);
39
+ using scatter_fill_fn = void (*)(
40
+ const Tensor& self,
41
+ int64_t dim,
42
+ const Tensor& index,
43
+ const Scalar& src);
44
+ using scatter_add_fn = void (*)(
45
+ const Tensor& self,
46
+ int64_t dim,
47
+ const Tensor& index,
48
+ const Tensor& src);
49
+ using scatter_reduce_fn = void (*)(
50
+ const Tensor& self,
51
+ const int64_t dim,
52
+ const Tensor& index,
53
+ const Tensor& src,
54
+ const ReductionType& reduce);
55
+ using scatter_scalar_reduce_fn = void (*)(
56
+ const Tensor& self,
57
+ const int64_t dim,
58
+ const Tensor& index,
59
+ const Scalar& value,
60
+ const ReductionType& reduce);
61
+ using scatter_reduce_two_fn = void (*)(
62
+ const Tensor& self,
63
+ const int64_t dim,
64
+ const Tensor& index,
65
+ const Tensor& src,
66
+ const ReductionType& reduce);
67
+
68
+ DECLARE_DISPATCH(index_put_with_sort_fn, index_put_with_sort_stub)
69
+ DECLARE_DISPATCH(
70
+ index_put_with_sort_quantized_fn,
71
+ index_put_with_sort_quantized_stub)
72
+ DECLARE_DISPATCH(gather_fn, gather_stub)
73
+ DECLARE_DISPATCH(scatter_fn, scatter_stub)
74
+ DECLARE_DISPATCH(scatter_fill_fn, scatter_fill_stub)
75
+ DECLARE_DISPATCH(scatter_add_fn, scatter_add_stub)
76
+ DECLARE_DISPATCH(scatter_reduce_fn, scatter_reduce_stub)
77
+ DECLARE_DISPATCH(scatter_scalar_reduce_fn, scatter_scalar_reduce_stub)
78
+ DECLARE_DISPATCH(scatter_reduce_two_fn, scatter_reduce_two_stub)
79
+
80
+ TORCH_API Tensor& index_out(
81
+ Tensor& result,
82
+ const Tensor& self,
83
+ const c10::List<std::optional<at::Tensor>>& indices);
84
+
85
+ using scatter_add_expanded_index_fn =
86
+ void (*)(const Tensor&, const Tensor&, const Tensor&);
87
+ using scatter_reduce_expanded_index_fn = void (*)(
88
+ const Tensor&,
89
+ const Tensor&,
90
+ const Tensor&,
91
+ const ReductionType& reduce,
92
+ bool);
93
+ using gather_expanded_index_fn =
94
+ void (*)(const Tensor&, const Tensor&, const Tensor&);
95
+
96
+ DECLARE_DISPATCH(scatter_add_expanded_index_fn, scatter_add_expanded_index_stub)
97
+ DECLARE_DISPATCH(
98
+ scatter_reduce_expanded_index_fn,
99
+ scatter_reduce_expanded_index_stub)
100
+ DECLARE_DISPATCH(gather_expanded_index_fn, gather_expanded_index_stub)
101
+
102
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorAdvancedIndexingUtils.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/native/IndexingUtils.h>
4
+ #include <ATen/native/TensorIterator.h>
5
+
6
+ namespace at::native {
7
+ namespace {
8
+ #ifndef STRIP_ERROR_MESSAGES
9
+ inline std::string shapes_as_str(TensorList tensors) {
10
+ std::ostringstream os;
11
+ bool first = true;
12
+ for (auto& tensor : tensors) {
13
+ if (tensor.defined()) {
14
+ if (!first) {
15
+ os << ", ";
16
+ }
17
+ os << tensor.sizes();
18
+ first = false;
19
+ }
20
+ }
21
+ return os.str();
22
+ }
23
+ #endif
24
+ } // anonymous namespace
25
+
26
+ inline std::tuple<bool, Tensor> canDispatchToMaskedFill(
27
+ const Tensor& self,
28
+ const torch::List<std::optional<at::Tensor>>& indices,
29
+ const Tensor& value) {
30
+ if (!(value.numel() == 1 && value.device().is_cpu())) {
31
+ return std::make_tuple(false, Tensor());
32
+ }
33
+ int64_t num_ind = 0;
34
+ Tensor mask;
35
+ auto self_device = self.device();
36
+ for (const std::optional<Tensor>& i : indices) {
37
+ if (!i.has_value() || !(*i).defined()) {
38
+ num_ind++;
39
+ } else {
40
+ const Tensor& index = *i;
41
+ if ((index.scalar_type() != kByte && index.scalar_type() != kBool) ||
42
+ index.device() != self_device || mask.defined()) {
43
+ return std::make_tuple(false, Tensor());
44
+ } else {
45
+ mask = index;
46
+ for (const auto j : c10::irange(index.dim())) {
47
+ int64_t srcIdx = num_ind + j;
48
+ TORCH_CHECK_INDEX(
49
+ index.size(j) == self.size(srcIdx),
50
+ "The shape of the mask ",
51
+ index.sizes(),
52
+ " at index ",
53
+ j,
54
+ " does not match the shape of the indexed tensor ",
55
+ self.sizes(),
56
+ " at index ",
57
+ srcIdx);
58
+ }
59
+ num_ind += mask.ndimension();
60
+ }
61
+ }
62
+ }
63
+ for ([[maybe_unused]] const auto i :
64
+ c10::irange(num_ind, self.ndimension())) {
65
+ mask = mask.unsqueeze(-1);
66
+ }
67
+ return std::make_tuple(true, mask);
68
+ }
69
+
70
+ inline AdvancedIndex make_info(Tensor self, IOptTensorListRef orig) {
71
+ checkIndexTensorTypes(orig, /*allow_int*/ true);
72
+ // first expand BoolTensor (masks) or ByteTensor (masks) into 1 or more
73
+ // LongTensors
74
+ auto indices = expandTensors(self, orig);
75
+ // next broadcast all index tensors together
76
+ try {
77
+ indices = expand_outplace(indices);
78
+ } catch (std::exception& e) {
79
+ TORCH_CHECK_INDEX(
80
+ false,
81
+ "shape mismatch: indexing tensors could not be broadcast together"
82
+ " with shapes ",
83
+ shapes_as_str(indices));
84
+ }
85
+ // add missing null Tensors so that it matches self.dim()
86
+ while (indices.size() < (size_t)self.dim()) {
87
+ indices.emplace_back();
88
+ }
89
+ // if the non-null indices are not all adjacent, transpose self and indices
90
+ // together so that they're adjacent at the front
91
+ if (!hasContiguousSubspace(indices)) {
92
+ std::tie(self, indices) = transposeToFront(self, indices);
93
+ }
94
+ // Ensure indices are on the same device as self
95
+ for (auto& indice : indices) {
96
+ if (indice.defined() && indice.device() != self.device()) {
97
+ indice = indice.to(self.device());
98
+ }
99
+ }
100
+ for (auto& indice : indices) {
101
+ if (indice.defined() && indice.dtype() == at::kInt) {
102
+ indice = indice.to(at::kLong);
103
+ }
104
+ }
105
+
106
+ return AdvancedIndex(self, indices);
107
+ }
108
+
109
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorCompare.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace c10 {
6
+ class Scalar;
7
+ }
8
+
9
+ namespace at {
10
+ class Tensor;
11
+ struct TensorIterator;
12
+ struct TensorIteratorBase;
13
+ } // namespace at
14
+
15
+ namespace at::native {
16
+
17
+ using reduce_minmax_fn =
18
+ void (*)(Tensor&, Tensor&, const Tensor&, int64_t, bool);
19
+ using structured_reduce_minmax_fn =
20
+ void (*)(const Tensor&, const Tensor&, const Tensor&, int64_t, bool);
21
+
22
+ DECLARE_DISPATCH(structured_reduce_minmax_fn, max_stub)
23
+ DECLARE_DISPATCH(structured_reduce_minmax_fn, min_stub)
24
+
25
+ using where_fn = void (*)(TensorIterator&);
26
+ DECLARE_DISPATCH(where_fn, where_kernel)
27
+
28
+ using is_infinity_op_fn = void (*)(TensorIteratorBase&);
29
+ DECLARE_DISPATCH(is_infinity_op_fn, isposinf_stub)
30
+ DECLARE_DISPATCH(is_infinity_op_fn, isneginf_stub)
31
+
32
+ using mode_fn = void (*)(Tensor&, Tensor&, const Tensor&, int64_t, bool);
33
+ DECLARE_DISPATCH(mode_fn, mode_stub)
34
+
35
+ using clamp_tensor_fn = void (*)(TensorIteratorBase&);
36
+ DECLARE_DISPATCH(clamp_tensor_fn, clamp_stub)
37
+
38
+ namespace detail {
39
+ enum class ClampLimits { Min, Max, MinMax };
40
+ }
41
+
42
+ DECLARE_DISPATCH(
43
+ void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&),
44
+ clamp_scalar_stub)
45
+ DECLARE_DISPATCH(
46
+ void (*)(TensorIteratorBase&, c10::Scalar),
47
+ clamp_min_scalar_stub)
48
+ DECLARE_DISPATCH(
49
+ void (*)(TensorIteratorBase&, c10::Scalar),
50
+ clamp_max_scalar_stub)
51
+
52
+ using isin_default_fn =
53
+ void (*)(const Tensor&, const Tensor&, bool, const Tensor&);
54
+ DECLARE_DISPATCH(isin_default_fn, isin_default_stub)
55
+
56
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorConversions.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Device.h>
4
+ #include <c10/core/Layout.h>
5
+ #include <c10/core/MemoryFormat.h>
6
+ #include <c10/core/ScalarType.h>
7
+ #include <optional>
8
+
9
+ namespace at {
10
+ class Tensor;
11
+ namespace native {
12
+ bool to_will_alias(
13
+ const Tensor& self,
14
+ std::optional<ScalarType> dtype,
15
+ std::optional<Layout> layout,
16
+ std::optional<Device> device,
17
+ bool copy,
18
+ std::optional<c10::MemoryFormat> optional_memory_format);
19
+
20
+ Tensor to_meta(const Tensor& tensor);
21
+ std::optional<Tensor> to_meta(const std::optional<Tensor>& tensor);
22
+ std::vector<Tensor> to_meta(at::ITensorListRef t_list);
23
+ Tensor dense_to_sparse_with_mask(
24
+ const Tensor& self,
25
+ const Tensor& mask,
26
+ std::optional<c10::Layout> layout,
27
+ OptionalIntArrayRef blocksize,
28
+ std::optional<int64_t> dense_dim_opt);
29
+
30
+ } // namespace native
31
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorDimApply.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <c10/util/irange.h>
4
+
5
+ namespace at::native {
6
+ // input tensors are non-zero dim and non-empty
7
+ template <typename T1, typename T2, typename Function>
8
+
9
+ void tensor_dim_apply3(
10
+ const Tensor& self,
11
+ Tensor& values,
12
+ Tensor& indices,
13
+ int64_t dim,
14
+ Function func) {
15
+ int ndims = self.dim();
16
+ int tensor_dim_apply_has_finished = 0;
17
+ std::vector<int64_t> counter(ndims, 0);
18
+ const T1* self_data = self.const_data_ptr<T1>();
19
+ T1* values_data = values.data_ptr<T1>();
20
+ T2* indices_data = indices.data_ptr<T2>();
21
+ int64_t self_stride = self.stride(dim);
22
+ int64_t values_stride = values.stride(dim);
23
+ int64_t indices_stride = indices.stride(dim);
24
+ int self_dim_size = self.size(dim);
25
+
26
+ while (!tensor_dim_apply_has_finished) {
27
+ func(
28
+ self_data,
29
+ values_data,
30
+ indices_data,
31
+ self_dim_size,
32
+ self_stride,
33
+ values_stride,
34
+ indices_stride);
35
+ if (ndims == 1) {
36
+ break;
37
+ }
38
+ for (const auto dim_i : c10::irange(ndims)) {
39
+ if (dim_i == dim) {
40
+ if (dim_i == (ndims - 1)) {
41
+ tensor_dim_apply_has_finished = 1;
42
+ break;
43
+ }
44
+ continue;
45
+ }
46
+ counter[dim_i]++;
47
+ self_data += self.stride(dim_i);
48
+ values_data += values.stride(dim_i);
49
+ indices_data += indices.stride(dim_i);
50
+
51
+ if (counter[dim_i] == self.size(dim_i)) {
52
+ if (dim_i == ndims - 1) {
53
+ tensor_dim_apply_has_finished = 1;
54
+ break;
55
+ } else {
56
+ self_data -= counter[dim_i] * self.stride(dim_i);
57
+ values_data -= counter[dim_i] * values.stride(dim_i);
58
+ indices_data -= counter[dim_i] * indices.stride(dim_i);
59
+ counter[dim_i] = 0;
60
+ }
61
+ } else {
62
+ break;
63
+ }
64
+ }
65
+ }
66
+ }
67
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorFactories.h ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Dispatch.h>
4
+ #include <ATen/Dispatch_v2.h>
5
+ #include <ATen/EmptyTensor.h>
6
+ #include <ATen/TensorIterator.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <ATen/native/DispatchStub.h>
9
+
10
+ #ifndef AT_PER_OPERATOR_HEADERS
11
+ #include <ATen/Functions.h>
12
+ #else
13
+ #include <ATen/ops/scalar_tensor.h>
14
+ #endif
15
+
16
+ namespace at::native {
17
+ // Different combinations of row, col, and offset can lead to two cases:
18
+ //
19
+ // Case 1 - Trapezoid (Triangle as a special case): row + offset <= col
20
+ // Example A: offset > 0
21
+ // 1 1 0 0 0
22
+ // 1 1 1 0 0
23
+ // 1 1 1 1 0
24
+ // Example B: offset <= 0
25
+ // 0 0 0
26
+ // 1 0 0
27
+ // 1 1 0
28
+ // In this case, we calculate the number of elements in the first row and
29
+ // last row of the tril respectively, and then compute the tril size.
30
+ //
31
+ // Case 2 - Trapezoid + Rectangle: row + offset > col
32
+ // Example:
33
+ // 1 1 0
34
+ // 1 1 1
35
+ // 1 1 1
36
+ // In this case, we first calculate the size of top trapezoid, and then
37
+ // calculate the size of the bottom rectangle.
38
+ inline int64_t get_tril_size(int64_t row, int64_t col, int64_t offset) {
39
+ // If either dimension is 0 then the there is no tril
40
+ if (row == 0 || col == 0) {
41
+ return 0;
42
+ }
43
+ // number of elements in the first row of the tril
44
+ auto m_first_row = offset > 0 ? std::min<int64_t>(col, 1 + offset)
45
+ : // upper bounded by col
46
+ row + offset > 0; // either 0 or 1
47
+ // number of elements in the last row of the tril, bounded by [0, col]
48
+ auto m_last_row = std::max<int64_t>(0, std::min<int64_t>(col, row + offset));
49
+ // number of rows, bounded by [0, row]
50
+ auto n_row_all = std::max<int64_t>(0, std::min<int64_t>(row, row + offset));
51
+ auto n_row_trapezoid = (m_last_row - m_first_row + 1);
52
+
53
+ // calculate # of elements in the top trapezoid
54
+ auto tril_size = (m_first_row + m_last_row) * n_row_trapezoid >> 1;
55
+
56
+ // calculate # of elements in the bottom rectangle if there is any
57
+ auto diff_row = n_row_all - n_row_trapezoid;
58
+ if (diff_row > 0) {
59
+ tril_size += diff_row * col;
60
+ }
61
+
62
+ return tril_size;
63
+ }
64
+
65
+ inline void check_args(
66
+ int64_t row,
67
+ int64_t col,
68
+ std::optional<Layout> layout_opt) {
69
+ TORCH_CHECK(row >= 0, "row must be non-negative, got", row);
70
+ TORCH_CHECK(col >= 0, "col must be non-negative, got", col);
71
+ if (layout_opt.has_value()) {
72
+ TORCH_CHECK(
73
+ *layout_opt == at::kStrided,
74
+ "only support layout=torch.strided, got",
75
+ *layout_opt)
76
+ }
77
+ }
78
+
79
+ using at::check_size_nonnegative;
80
+
81
+ // assumes maximum value in created tensor is n-1 (e.g., torch.randperm(n))
82
+ inline void check_supported_max_int_with_precision(
83
+ int64_t n,
84
+ const Tensor& tensor) {
85
+ // match defined() to behavior of checks below
86
+ TORCH_CHECK(
87
+ at::scalar_tensor(n > 0 ? n - 1 : n, tensor.options()).defined(),
88
+ "n is too large for result tensor type: '",
89
+ tensor.toString(),
90
+ "'");
91
+
92
+ // Ensure sufficient precision for floating point representation.
93
+ switch (tensor.scalar_type()) {
94
+ case at::ScalarType::Half:
95
+ TORCH_CHECK(
96
+ n <= (int64_t(1) << 11) + 1,
97
+ "n cannot be greater than 2049 for Half type.");
98
+ break;
99
+ case at::ScalarType::Float:
100
+ TORCH_CHECK(
101
+ n <= (int64_t(1) << 24) + 1,
102
+ "n cannot be greater than 2^24+1 for Float type.");
103
+ break;
104
+ case at::ScalarType::Double: // Unlikely to happen, but doesn't hurt to
105
+ // check
106
+ TORCH_CHECK(
107
+ n <= (int64_t(1) << 53) + 1,
108
+ "n cannot be greater than 2^53+1 for Double type.");
109
+ break;
110
+ default:
111
+ break;
112
+ }
113
+ }
114
+
115
+ // Called by `empty*` functions when deterministic algorithms are enabled to
116
+ // fill the tensor with NaN if it is floating point or complex type, or fill
117
+ // with max value if it is integer type
118
+ inline Tensor& fill_empty_deterministic_(Tensor& tensor) {
119
+ if (tensor.is_floating_point() || tensor.is_complex()) {
120
+ AT_DISPATCH_V2(
121
+ tensor.scalar_type(),
122
+ "fill_empty_deterministic_",
123
+ AT_WRAP([&]() {
124
+ tensor.fill_(std::numeric_limits<scalar_t>::quiet_NaN());
125
+ }),
126
+ AT_EXPAND(AT_FLOATING_TYPES),
127
+ AT_EXPAND(AT_COMPLEX_TYPES),
128
+ AT_EXPAND(AT_FLOAT8_TYPES),
129
+ kBFloat16,
130
+ kHalf,
131
+ kComplexHalf);
132
+ } else {
133
+ AT_DISPATCH_V2(
134
+ tensor.scalar_type(),
135
+ "fill_empty_deterministic_",
136
+ AT_WRAP([&]() { tensor.fill_(std::numeric_limits<scalar_t>::max()); }),
137
+ kBool,
138
+ AT_EXPAND(AT_INTEGRAL_TYPES_V2));
139
+ }
140
+ return tensor;
141
+ }
142
+
143
+ // The ZeroTensor allocator ignores whatever allocation is requested and always
144
+ // gives you nullptr
145
+ struct ZeroTensorAllocator final : public at::Allocator {
146
+ ZeroTensorAllocator(at::Device device) : device_(device) {}
147
+ ~ZeroTensorAllocator() override = default;
148
+ static void deleter(void* const pointer) {
149
+ TORCH_INTERNAL_ASSERT(!pointer);
150
+ }
151
+ DataPtr allocate(const size_t /*nbytes*/) override {
152
+ return {nullptr, nullptr, &deleter, device_};
153
+ }
154
+ DeleterFnPtr raw_deleter() const override {
155
+ return deleter;
156
+ }
157
+ void copy_data(
158
+ void* dest [[maybe_unused]],
159
+ const void* src [[maybe_unused]],
160
+ std::size_t count [[maybe_unused]]) const final {}
161
+ at::Device device_;
162
+ };
163
+
164
+ using binary_fn = void (*)(TensorIterator&);
165
+
166
+ DECLARE_DISPATCH(binary_fn, complex_stub)
167
+ DECLARE_DISPATCH(binary_fn, polar_stub)
168
+
169
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorIterator.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <ATen/TensorIterator.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorIteratorDynamicCasting.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/detail/FunctionTraits.h>
4
+ #include <ATen/native/TensorIterator.h>
5
+ #include <c10/core/ScalarType.h>
6
+ #include <complex>
7
+ #include <type_traits>
8
+
9
+ // This file includes utilities for dynamic_casting done by TensorIterator, see
10
+ // CUDALoops.cuh and Loops.h.
11
+
12
+ // dynamic_casting handles when the types expected by the iterator do not match
13
+ // the types of the arguments to the function that is being called. On CUDA, the
14
+ // cast is currently pushed down into the kernel (for performance reasons). On
15
+ // CPU, there is currently an internal assert that a dynamic_cast is not needed.
16
+
17
+ namespace at::native {
18
+
19
+ // `needs_dynamic_casting` compares the types expected by iterator
20
+ // (i.e. dtypes of the operands) with the actual type of the arguments
21
+ // (and returns) of func_t
22
+ template <typename func_t, int nargs = function_traits<func_t>::arity>
23
+ struct needs_dynamic_casting {
24
+ static bool check(TensorIteratorBase& iter) {
25
+ using traits = function_traits<func_t>;
26
+ using cpp_type = typename traits::template arg<nargs - 1>::type;
27
+ using cpp_map = c10::CppTypeToScalarType<cpp_type>;
28
+
29
+ if (iter.input_dtype(nargs - 1) != cpp_map::value) {
30
+ return true;
31
+ }
32
+ return needs_dynamic_casting<func_t, nargs - 1>::check(iter);
33
+ }
34
+ };
35
+
36
+ template <typename func_t>
37
+ struct needs_dynamic_casting<func_t, 0> {
38
+ static bool check(TensorIteratorBase& iter) {
39
+ using traits = function_traits<func_t>;
40
+ using cpp_type = typename traits::result_type;
41
+
42
+ // we could assert output numbers are correct here, but checks
43
+ // (including arity) are currently pushed outside of this struct.
44
+ if constexpr (std::is_void_v<cpp_type>) {
45
+ return false;
46
+ } else {
47
+ return iter.dtype(0) != c10::CppTypeToScalarType<cpp_type>::value;
48
+ }
49
+ }
50
+ };
51
+
52
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorProperties.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // See NOTE: [Tensor vs. TensorBase]
4
+ namespace at {
5
+ class TensorBase;
6
+ }
7
+
8
+ namespace at::native {
9
+
10
+ TORCH_API bool cudnn_is_acceptable(const TensorBase& self);
11
+
12
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorShape.h ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/IListRef.h>
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ namespace at::native {
7
+
8
+ TORCH_API at::Tensor clone_preserve_strides(const at::Tensor& self);
9
+
10
+ inline bool cat_should_skip_tensor(const Tensor& t) {
11
+ return t.sym_numel() == 0 && t.dim() == 1;
12
+ }
13
+
14
+ // Check to see if the shape of tensors is compatible
15
+ // for being concatenated along a given dimension.
16
+ inline void check_cat_shape_except_dim(
17
+ const Tensor& first,
18
+ const Tensor& second,
19
+ int64_t dimension,
20
+ int64_t index) {
21
+ int64_t first_dims = first.dim();
22
+ int64_t second_dims = second.dim();
23
+ TORCH_CHECK(
24
+ first_dims == second_dims,
25
+ "Tensors must have same number of dimensions: got ",
26
+ first_dims,
27
+ " and ",
28
+ second_dims);
29
+ for (const auto dim : c10::irange(first_dims)) {
30
+ if (dim == dimension) {
31
+ continue;
32
+ }
33
+ int64_t first_dim_size = first.sizes()[dim];
34
+ int64_t second_dim_size = second.sizes()[dim];
35
+ TORCH_CHECK(
36
+ first_dim_size == second_dim_size,
37
+ "Sizes of tensors must match except in dimension ",
38
+ dimension,
39
+ ". Expected size ",
40
+ static_cast<long long>(first_dim_size),
41
+ " but got size ",
42
+ static_cast<long long>(second_dim_size),
43
+ " for tensor number ",
44
+ index,
45
+ " in the list.");
46
+ }
47
+ }
48
+
49
+ inline void check_cat_no_zero_dim(const MaterializedITensorListRef& tensors) {
50
+ [[maybe_unused]] int64_t i = 0;
51
+ for (const Tensor& t : tensors) {
52
+ TORCH_CHECK(
53
+ t.dim() > 0,
54
+ "zero-dimensional tensor (at position ",
55
+ i,
56
+ ") cannot be concatenated");
57
+ i++;
58
+ }
59
+ }
60
+
61
+ inline int64_t get_num_splits(
62
+ const Tensor& self,
63
+ int64_t split_size,
64
+ int64_t dim) {
65
+ TORCH_CHECK(self.dim() != 0, "split expects at least a 1-dimensional tensor");
66
+ TORCH_CHECK(
67
+ split_size >= 0,
68
+ "split expects split_size be non-negative, but got split_size=",
69
+ split_size);
70
+ int64_t dim_size = self.size(dim);
71
+ TORCH_CHECK(
72
+ split_size > 0 || dim_size == 0,
73
+ "split_size can only be 0 if dimension size is 0, "
74
+ "but got dimension size of ",
75
+ dim_size);
76
+ // if split_size is 0 and dimension size is 0, there is 1 split.
77
+ int64_t num_splits = 1;
78
+ if (split_size != 0) {
79
+ // ensuring num_splits is at least 1 makes consistent the case where
80
+ // split_size > dim_size (returns a single split). We might want to error
81
+ // here, but keep it for BC.
82
+ num_splits = std::max<int64_t>((dim_size + split_size - 1) / split_size, 1);
83
+ }
84
+ return num_splits;
85
+ }
86
+
87
+ inline bool have_same_ndims(TensorList tensors) {
88
+ auto ndim = tensors[0].dim();
89
+ for (const auto tensor_idx : c10::irange(tensors.size())) {
90
+ if (tensors[tensor_idx].dim() != ndim) {
91
+ return false;
92
+ }
93
+ }
94
+ return true;
95
+ }
96
+
97
+ inline void leading_dimension_matches(TensorList tensors, int64_t dim) {
98
+ auto tensor_zero_size = tensors[0].sizes();
99
+ std::vector<c10::SymInt> leading_dim_sizes(
100
+ tensor_zero_size.begin(), tensor_zero_size.begin() + dim);
101
+ for (const auto i : c10::irange(tensors.size())) {
102
+ at::Tensor tensor = tensors[i];
103
+ for (const auto j : c10::irange(dim)) {
104
+ TORCH_CHECK(
105
+ tensor.size(j) == leading_dim_sizes[j],
106
+ "_chunk_cat expects same sizes of 0,...,dim-1 dimensions for all tensors");
107
+ }
108
+ }
109
+ }
110
+
111
+ inline int64_t preprocess_chunk_cat_inputs(
112
+ TensorList tensors,
113
+ int64_t dim,
114
+ int64_t num_chunks) {
115
+ TORCH_CHECK(num_chunks >= 1, "_chunk_cat expects positive num_chunks");
116
+ TORCH_CHECK(
117
+ !tensors.empty(), "_chunk_cat expects a non-empty input tensor list");
118
+ auto expected_dtype = tensors[0].dtype();
119
+ auto expected_device = tensors[0].device();
120
+ for (const auto i : c10::irange(tensors.size())) {
121
+ TORCH_CHECK(tensors[i].numel() > 0, "_chunk_cat expects non-empty tensor");
122
+ TORCH_CHECK(
123
+ tensors[i].dtype() == expected_dtype,
124
+ "_chunk_cat expects all input tensors with the same dtype");
125
+ TORCH_CHECK(
126
+ tensors[i].device() == expected_device,
127
+ "_chunk_cat expects all inputs tensors on the same device");
128
+ }
129
+ if (have_same_ndims(tensors)) {
130
+ dim = maybe_wrap_dim(dim, tensors[0].dim());
131
+ } else {
132
+ TORCH_CHECK(
133
+ dim >= 0,
134
+ "_chunk_cat expects non-negative dim when input tensors have different ndims")
135
+ for (const auto i : c10::irange(tensors.size())) {
136
+ TORCH_CHECK(
137
+ dim < tensors[i].ndimension(),
138
+ "_chunk_cat expects dim < ndim for all input tensors");
139
+ }
140
+ }
141
+ leading_dimension_matches(tensors, dim);
142
+ return dim;
143
+ }
144
+
145
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TensorTransformations.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+
3
+ #ifndef AT_PER_OPERATOR_HEADERS
4
+ #include <ATen/Functions.h>
5
+ #else
6
+ #include <ATen/ops/roll.h>
7
+ #endif
8
+
9
+ #include <c10/util/Exception.h>
10
+
11
+ namespace at::native {
12
+
13
+ static inline Tensor roll_common(
14
+ const Tensor& self,
15
+ IntArrayRef shifts,
16
+ IntArrayRef dims) {
17
+ TORCH_CHECK(!shifts.empty(), "`shifts` required");
18
+ if (dims.empty() && shifts.size() == 1) {
19
+ auto flattened = self.contiguous().view(self.numel());
20
+ return roll(flattened, shifts[0], 0).view(self.sizes());
21
+ }
22
+ TORCH_CHECK(
23
+ shifts.size() == dims.size(),
24
+ "shifts and dimensions must align. shifts: ",
25
+ shifts.size(),
26
+ ", dims:",
27
+ dims.size());
28
+ AT_ASSERT(dims.size() > 1);
29
+ auto tail_shifts = shifts.slice(1);
30
+ auto tail_dims = dims.slice(1);
31
+ auto first_dim_rolled = roll(self, shifts[0], dims[0]);
32
+ return at::roll(first_dim_rolled, tail_shifts, tail_dims);
33
+ }
34
+
35
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TopKImpl.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/TensorAccessor.h>
3
+ #include <ATen/NumericUtils.h>
4
+
5
+ namespace at::native {
6
+
7
+ #ifdef CPU_CAPABILITY
8
+ inline namespace CPU_CAPABILITY {
9
+ #else
10
+ inline namespace DEFAULT {
11
+ #endif
12
+
13
+ // Core topk loop, shared between CPU and QuantizedCPU
14
+ template <typename scalar_t, typename accscalar_t>
15
+ void topk_impl_loop(
16
+ const int64_t mode_values_stride,
17
+ const int64_t mode_indices_stride,
18
+ const int64_t tmp_values_stride,
19
+ const int64_t k,
20
+ const int64_t dim_size,
21
+ const bool largest,
22
+ const bool sorted,
23
+ char** data, const int64_t* strides, const int64_t n) {
24
+
25
+ // If k is zero, then output values and indices are empty tensors
26
+ // So iterating over other dims is pointless
27
+ if (k == 0) {
28
+ return;
29
+ }
30
+ using elem_t = std::pair<accscalar_t, int64_t>;
31
+ std::vector<elem_t> queue(dim_size);
32
+ for (const auto i : c10::irange(n)) {
33
+ TensorAccessor<scalar_t, 1> mode_values(
34
+ reinterpret_cast<scalar_t*>(data[0] + i * strides[0]),
35
+ &k, &mode_values_stride);
36
+ TensorAccessor<int64_t, 1> mode_indices(
37
+ reinterpret_cast<int64_t*>(data[1] + i * strides[1]),
38
+ &k, &mode_indices_stride);
39
+ TensorAccessor<const scalar_t, 1> tmp_values(
40
+ reinterpret_cast<scalar_t*>(data[2] + i * strides[2]),
41
+ &dim_size, &tmp_values_stride);
42
+
43
+ auto n_2 = dim_size;
44
+ auto use_partial_sort = k * 64 <= n_2;
45
+
46
+ for (const auto j : c10::irange(n_2)) {
47
+ queue[j].first = tmp_values[j];
48
+ queue[j].second = j;
49
+ }
50
+
51
+ // we want nan to be sorted as top for numpy compatibility
52
+ if (use_partial_sort) {
53
+ if (largest) {
54
+ std::partial_sort(queue.begin(), queue.begin() + k, queue.end(),
55
+ [](const elem_t& x, const elem_t& y) -> bool {
56
+ return ((_isnan<accscalar_t>(x.first) && !_isnan<accscalar_t>(y.first)) || (x.first > y.first));
57
+ });
58
+ } else {
59
+ std::partial_sort(queue.begin(), queue.begin() + k, queue.end(),
60
+ [](const elem_t& x, const elem_t& y) -> bool {
61
+ return ((!_isnan<accscalar_t>(x.first) && _isnan<accscalar_t>(y.first)) || (x.first < y.first));
62
+ });
63
+ }
64
+ } else {
65
+ if (largest) {
66
+ std::nth_element(queue.begin(), queue.begin() + k - 1, queue.end(),
67
+ [](const elem_t& x, const elem_t& y) -> bool {
68
+ return ((_isnan<accscalar_t>(x.first) && !_isnan<accscalar_t>(y.first)) || (x.first > y.first));
69
+ });
70
+ if (sorted) {
71
+ std::sort(queue.begin(), queue.begin() + k - 1,
72
+ [](const elem_t& x, const elem_t& y) -> bool {
73
+ return ((_isnan<accscalar_t>(x.first) && !_isnan<accscalar_t>(y.first)) || (x.first > y.first));
74
+ });
75
+ }
76
+ } else {
77
+ std::nth_element(queue.begin(), queue.begin() + k -1, queue.end(),
78
+ [](const elem_t& x, const elem_t& y) -> bool {
79
+ return ((!_isnan<accscalar_t>(x.first) && _isnan<accscalar_t>(y.first)) || (x.first < y.first));
80
+ });
81
+ if (sorted) {
82
+ std::sort(queue.begin(), queue.begin() + k -1,
83
+ [](const elem_t& x, const elem_t& y) -> bool {
84
+ return ((!_isnan<accscalar_t>(x.first) && _isnan<accscalar_t>(y.first)) || (x.first < y.first));
85
+ });
86
+ }
87
+ }
88
+ }
89
+
90
+ for (const auto j : c10::irange(k)) {
91
+ mode_values[j] = queue[j].first;
92
+ mode_indices[j] = queue[j].second;
93
+ }
94
+ }
95
+ }
96
+
97
+ } // namespace CPU_CAPABILITY
98
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TransposeType.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/util/Exception.h>
3
+
4
+ namespace at::native {
5
+
6
+ // Used as an interface between the different BLAS-like libraries
7
+ enum class TransposeType {
8
+ NoTranspose,
9
+ Transpose,
10
+ ConjTranspose,
11
+ };
12
+
13
+ // Transforms TransposeType into the BLAS / LAPACK format
14
+ static inline char to_blas(TransposeType trans) {
15
+ switch (trans) {
16
+ case TransposeType::Transpose: return 'T';
17
+ case TransposeType::NoTranspose: return 'N';
18
+ case TransposeType::ConjTranspose: return 'C';
19
+ }
20
+ TORCH_INTERNAL_ASSERT(false, "Invalid transpose type");
21
+ }
22
+
23
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TriangularOpsUtils.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+ #include <ATen/native/LinearAlgebraUtils.h>
3
+
4
+ namespace at::native {
5
+
6
+ /*
7
+ * Given batches of matrices with arbitrary batch dim,
8
+ * computes the number of batches for Triu and Tril. This ignores stride 0 dimension
9
+ */
10
+ static inline int64_t batchCountTrilTriu(const Tensor& batched_matrices) {
11
+ int64_t result = 1;
12
+ for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
13
+ if (batched_matrices.stride(i) != 0) {
14
+ result *= batched_matrices.size(i);
15
+ }
16
+ }
17
+ return result;
18
+ }
19
+
20
+ /* Checks a necessary property for the triu and tril implementations, hence the name.
21
+ * Here batch contiguity is checked for tensors with greater than 4 dimensions.
22
+ * Contiguous tensors and tensors with less than 3 dimensions pass this check
23
+ */
24
+ static inline std::tuple<bool, Tensor> checkTrilTriuBatchContiguous(const Tensor& tensor, bool allow_zero_stride) {
25
+ // Complete contiguity is the most desired property, which is why
26
+ // we return true if the tensor is contiguous
27
+ if (tensor.is_contiguous()) {
28
+ auto default_strides_for_size = batched_matrix_contiguous_strides(tensor.sizes());
29
+ if (tensor.strides() == default_strides_for_size) {
30
+ return std::make_tuple(true, tensor);
31
+ } else {
32
+ return std::make_tuple(false, tensor.as_strided(tensor.sizes(), default_strides_for_size));
33
+ }
34
+ }
35
+
36
+ int64_t dims = tensor.dim();
37
+
38
+ // Tensors with dimension less than 4 are handled by default
39
+ if (allow_zero_stride && dims <= 3) {
40
+ return std::make_tuple(true, tensor);
41
+ }
42
+
43
+ int64_t expected_stride = tensor.size(-1) * tensor.size(-2);
44
+ for (int64_t i = dims - 3; i >= 0; i--) {
45
+ // Skip trivial dimension;
46
+ if (allow_zero_stride && i == 0 && (tensor.stride(i) == 0 || tensor.size(i) == 1)) {
47
+ continue;
48
+ }
49
+ if (expected_stride != tensor.stride(i)) {
50
+ return std::make_tuple(false, tensor.contiguous());
51
+ }
52
+ expected_stride *= tensor.size(i);
53
+ }
54
+ return std::make_tuple(true, tensor);
55
+ }
56
+
57
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/TypeProperties.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/core/IListRef.h>
5
+
6
+ namespace at::native {
7
+
8
+ struct ResultTypeState {
9
+ c10::ScalarType dimResult = ScalarType::Undefined;
10
+ c10::ScalarType wrappedResult = ScalarType::Undefined;
11
+ c10::ScalarType zeroResult = ScalarType::Undefined;
12
+ };
13
+
14
+ TORCH_API ResultTypeState update_result_type_state(const Tensor& tensor, const ResultTypeState& in_state);
15
+ TORCH_API ResultTypeState update_result_type_state(const Scalar& scalar, const ResultTypeState& in_state);
16
+ TORCH_API ScalarType result_type(const ResultTypeState& state);
17
+
18
+ TORCH_API ScalarType result_type(ITensorListRef tensors);
19
+
20
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UnaryOps.h ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/Generator.h>
5
+ #include <c10/core/Scalar.h>
6
+
7
+ namespace at {
8
+ class Tensor;
9
+ class TensorBase;
10
+ struct TensorIteratorBase;
11
+ }
12
+
13
+ namespace at::native {
14
+
15
+ using unary_fn = void(*)(TensorIteratorBase&);
16
+ using unary_fn_with_scalar = void(*)(TensorIteratorBase&, const Scalar& a);
17
+
18
+ inline namespace CPU_CAPABILITY {
19
+ void conj_kernel(TensorIteratorBase &iter);
20
+ void neg_kernel(TensorIteratorBase &iter);
21
+ void reciprocal_kernel(TensorIteratorBase &iter);
22
+ void rsqrt_kernel(TensorIteratorBase& iter);
23
+ void sqrt_kernel(TensorIteratorBase& iter);
24
+ } // namespace CPU_CAPABILITY
25
+
26
+ DECLARE_DISPATCH(unary_fn, abs_stub)
27
+ DECLARE_DISPATCH(unary_fn, angle_stub)
28
+ DECLARE_DISPATCH(unary_fn, conj_physical_stub)
29
+ DECLARE_DISPATCH(unary_fn, acos_stub)
30
+ DECLARE_DISPATCH(unary_fn, acosh_stub)
31
+ DECLARE_DISPATCH(unary_fn, asinh_stub)
32
+ DECLARE_DISPATCH(unary_fn, atanh_stub)
33
+ DECLARE_DISPATCH(unary_fn, asin_stub)
34
+ DECLARE_DISPATCH(unary_fn, atan_stub)
35
+ DECLARE_DISPATCH(unary_fn, bitwise_not_stub)
36
+ DECLARE_DISPATCH(unary_fn, logical_not_stub)
37
+ DECLARE_DISPATCH(unary_fn, ceil_stub)
38
+ DECLARE_DISPATCH(unary_fn, cos_stub)
39
+ DECLARE_DISPATCH(unary_fn, cosh_stub)
40
+ DECLARE_DISPATCH(unary_fn, digamma_stub)
41
+ DECLARE_DISPATCH(unary_fn, special_entr_stub)
42
+ DECLARE_DISPATCH(unary_fn, special_erfcx_stub)
43
+ DECLARE_DISPATCH(unary_fn, erf_stub)
44
+ DECLARE_DISPATCH(unary_fn, erfc_stub)
45
+ DECLARE_DISPATCH(unary_fn, erfinv_stub)
46
+ DECLARE_DISPATCH(unary_fn, exp_stub)
47
+ DECLARE_DISPATCH(unary_fn, exp2_stub)
48
+ DECLARE_DISPATCH(unary_fn, expm1_stub)
49
+ DECLARE_DISPATCH(unary_fn, floor_stub)
50
+ DECLARE_DISPATCH(unary_fn, frac_stub)
51
+ DECLARE_DISPATCH(unary_fn, frexp_stub)
52
+ DECLARE_DISPATCH(unary_fn, i0_stub)
53
+ DECLARE_DISPATCH(unary_fn, special_i0e_stub)
54
+ DECLARE_DISPATCH(unary_fn, special_i1_stub)
55
+ DECLARE_DISPATCH(unary_fn, special_i1e_stub)
56
+ DECLARE_DISPATCH(unary_fn, log_stub)
57
+ DECLARE_DISPATCH(unary_fn, log10_stub)
58
+ DECLARE_DISPATCH(unary_fn, log1p_stub)
59
+ DECLARE_DISPATCH(unary_fn, log2_stub)
60
+ DECLARE_DISPATCH(unary_fn, special_ndtri_stub)
61
+ DECLARE_DISPATCH(unary_fn, special_log_ndtr_stub)
62
+ DECLARE_DISPATCH(unary_fn, neg_stub)
63
+
64
+ DECLARE_DISPATCH(unary_fn, reciprocal_stub)
65
+ DECLARE_DISPATCH(unary_fn, round_stub)
66
+ DECLARE_DISPATCH(unary_fn, rsqrt_stub)
67
+ DECLARE_DISPATCH(unary_fn, sigmoid_stub)
68
+ DECLARE_DISPATCH(unary_fn_with_scalar, logit_stub)
69
+ DECLARE_DISPATCH(unary_fn, sign_stub)
70
+ DECLARE_DISPATCH(unary_fn, signbit_stub)
71
+ DECLARE_DISPATCH(unary_fn, sgn_stub)
72
+ DECLARE_DISPATCH(unary_fn, sin_stub)
73
+ DECLARE_DISPATCH(unary_fn, sinc_stub)
74
+ DECLARE_DISPATCH(unary_fn, sinh_stub)
75
+ DECLARE_DISPATCH(unary_fn, sqrt_stub)
76
+ DECLARE_DISPATCH(unary_fn, tan_stub)
77
+ DECLARE_DISPATCH(unary_fn, tanh_stub)
78
+ DECLARE_DISPATCH(unary_fn, trigamma_stub)
79
+ DECLARE_DISPATCH(unary_fn, trunc_stub)
80
+ DECLARE_DISPATCH(unary_fn, lgamma_stub)
81
+ DECLARE_DISPATCH(unary_fn, special_airy_ai_stub)
82
+ DECLARE_DISPATCH(unary_fn, special_bessel_j0_stub)
83
+ DECLARE_DISPATCH(unary_fn, special_bessel_j1_stub)
84
+ DECLARE_DISPATCH(unary_fn, special_bessel_y0_stub)
85
+ DECLARE_DISPATCH(unary_fn, special_bessel_y1_stub)
86
+ DECLARE_DISPATCH(unary_fn, special_modified_bessel_i0_stub)
87
+ DECLARE_DISPATCH(unary_fn, special_modified_bessel_i1_stub)
88
+ DECLARE_DISPATCH(unary_fn, special_modified_bessel_k0_stub)
89
+ DECLARE_DISPATCH(unary_fn, special_modified_bessel_k1_stub)
90
+ DECLARE_DISPATCH(unary_fn, special_scaled_modified_bessel_k0_stub)
91
+ DECLARE_DISPATCH(unary_fn, special_scaled_modified_bessel_k1_stub)
92
+ DECLARE_DISPATCH(unary_fn, special_spherical_bessel_j0_stub)
93
+
94
+ // NB: these are actually defined in Distribution
95
+ DECLARE_DISPATCH(void(*)(const TensorBase&, const TensorBase&, std::optional<Generator>), bernoulli_tensor_stub)
96
+ DECLARE_DISPATCH(void(*)(const TensorBase&, const double, std::optional<Generator>), bernoulli_scalar_stub)
97
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const double, const double, std::optional<Generator>), cauchy_stub)
98
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const double, std::optional<Generator>), exponential_stub)
99
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const double, std::optional<Generator>), geometric_stub)
100
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const double, const double, std::optional<Generator>), log_normal_stub)
101
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const double, const double, std::optional<Generator>), uniform_stub)
102
+ DECLARE_DISPATCH(void(*)(const TensorBase&, const double, const double, std::optional<Generator>), normal_stub)
103
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const uint64_t, const int64_t, std::optional<Generator>), random_from_to_stub)
104
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, std::optional<Generator>), random_full_64_bits_range_stub)
105
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, std::optional<Generator>), random_stub)
106
+
107
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const int64_t, const double), kaiser_window_stub)
108
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const int64_t), polygamma_stub)
109
+ DECLARE_DISPATCH(void(*)(TensorIteratorBase&, const Scalar& a, const Scalar& b), clamp_stub)
110
+ DECLARE_DISPATCH(
111
+ void (*)(Tensor&, const Tensor&, int64_t, std::optional<Generator>),
112
+ multinomial_with_replacement_stub)
113
+ DECLARE_DISPATCH(
114
+ void (*)(
115
+ TensorIteratorBase&,
116
+ std::optional<double>,
117
+ std::optional<double>,
118
+ std::optional<double>),
119
+ nan_to_num_stub)
120
+ DECLARE_DISPATCH(void (*)(TensorIteratorBase&, int64_t), round_decimals_stub)
121
+
122
+ // Missing unary functions
123
+ // digamma
124
+ // lgamma
125
+ // erfinv
126
+ // clone
127
+ // contiguous
128
+ // zero
129
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Unfold2d.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/core/ScalarType.h>
5
+ #include <cstdint>
6
+
7
+ namespace at::native {
8
+
9
+ using unfold2d_copy_fn = void (*)(
10
+ ScalarType dtype,
11
+ void *finput,
12
+ const void *input,
13
+ int64_t kH,
14
+ int64_t kW,
15
+ int64_t dH,
16
+ int64_t dW,
17
+ int64_t padH,
18
+ int64_t padW,
19
+ int64_t n_input_plane,
20
+ int64_t input_height,
21
+ int64_t input_width,
22
+ int64_t output_height,
23
+ int64_t output_width,
24
+ bool is_channels_last
25
+ );
26
+
27
+ using unfold2d_acc_fn = void (*)(
28
+ ScalarType dtype,
29
+ void *finput,
30
+ void *input,
31
+ int64_t kH,
32
+ int64_t kW,
33
+ int64_t dH,
34
+ int64_t dW,
35
+ int64_t padH,
36
+ int64_t padW,
37
+ int64_t n_input_plane,
38
+ int64_t input_height,
39
+ int64_t input_width,
40
+ int64_t output_height,
41
+ int64_t output_width,
42
+ bool is_channels_last
43
+ );
44
+
45
+ DECLARE_DISPATCH(unfold2d_copy_fn, unfolded2d_copy_stub)
46
+ DECLARE_DISPATCH(unfold2d_acc_fn, unfolded2d_acc_stub)
47
+
48
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Unfold3d.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/ScalarType.h>
4
+
5
+ namespace at::native {
6
+
7
+ void Unfold3dCopyCPU(
8
+ ScalarType dtype,
9
+ const void *src,
10
+ int64_t C,
11
+ int64_t X_D,
12
+ int64_t X_H,
13
+ int64_t X_W,
14
+ int64_t Y_D,
15
+ int64_t Y_H,
16
+ int64_t Y_W,
17
+ int64_t kernel_d,
18
+ int64_t kernel_h,
19
+ int64_t kernel_w,
20
+ int64_t stride_d,
21
+ int64_t stride_h,
22
+ int64_t stride_w,
23
+ int64_t pad_d,
24
+ int64_t pad_h,
25
+ int64_t pad_w,
26
+ void* dst);
27
+
28
+ void Unfold3dAccCPU(
29
+ ScalarType dtype,
30
+ const void *src,
31
+ int64_t C,
32
+ int64_t X_D,
33
+ int64_t X_H,
34
+ int64_t X_W,
35
+ int64_t Y_D,
36
+ int64_t Y_H,
37
+ int64_t Y_W,
38
+ int64_t kernel_d,
39
+ int64_t kernel_h,
40
+ int64_t kernel_w,
41
+ int64_t stride_d,
42
+ int64_t stride_h,
43
+ int64_t stride_w,
44
+ int64_t pad_d,
45
+ int64_t pad_h,
46
+ int64_t pad_w,
47
+ void *dst);
48
+
49
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UnfoldBackward.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/TensorIterator.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <ATen/native/NonEmptyUtils.h>
7
+
8
+ #ifndef AT_PER_OPERATOR_HEADERS
9
+ #include <ATen/Functions.h>
10
+ #else
11
+ #include <ATen/ops/arange.h>
12
+ #endif
13
+
14
+ namespace at::native {
15
+
16
+ using unfold_backward_fn = void (*)(
17
+ Tensor& grad_in,
18
+ const Tensor& grad,
19
+ int64_t dim,
20
+ int64_t size,
21
+ int64_t step
22
+ );
23
+
24
+ DECLARE_DISPATCH(unfold_backward_fn, unfold_backward_stub)
25
+
26
+ namespace {
27
+
28
+ // Note on naming: it is unconventional.
29
+ // grad_in does not mean that it is a gradient wrt to input,
30
+ // grad_in/grad_out is just an input/output of unfold_backward kernel.
31
+
32
+ [[maybe_unused]] static TensorIterator _make_unfold_backward_iter_over_grad_out(
33
+ Tensor& grad_out,
34
+ const Tensor& grad_in,
35
+ int64_t dim,
36
+ int64_t size,
37
+ int64_t step) {
38
+ dim = maybe_wrap_dim(dim, grad_out.dim());
39
+ // last dim stores the folds
40
+
41
+ auto grad_out_dim_size = ensure_nonempty_size(grad_out, dim);
42
+ auto grad_in_dim_size = ensure_nonempty_size(grad_in, dim);
43
+ // dictates the number of elements to iterate over
44
+ // in dimension `dim`
45
+ auto iter_dim_size = std::min(
46
+ grad_out_dim_size,
47
+ (grad_in_dim_size - 1) * step + size
48
+ );
49
+
50
+ /* prepare grad_out for TensorIterator { */
51
+ auto grad_out_strides = ensure_nonempty_vec(grad_out.strides().vec());
52
+ auto grad_out_sizes = ensure_nonempty_vec(grad_out.sizes().vec());
53
+ grad_out_sizes[dim] = iter_dim_size;
54
+ auto grad_out_restrided = grad_out.as_strided(
55
+ grad_out_sizes, grad_out_strides
56
+ );
57
+ /* } */
58
+
59
+ /* prepare grad_in for TensorIterator { */
60
+ auto grad_in_strides = ensure_nonempty_vec(grad_in.strides().vec());
61
+ auto grad_in_sizes = ensure_nonempty_vec(grad_in.sizes().vec());
62
+
63
+ // set strides for dim to 0
64
+ // and size to 1 because
65
+ // this dimension is indexed inside the kernel
66
+ grad_in_strides[dim] = 0;
67
+ grad_in_sizes[dim] = 1;
68
+
69
+ grad_in_strides.pop_back();
70
+ grad_in_sizes.pop_back();
71
+
72
+ auto grad_in_restrided = grad_in.squeeze(-1).as_strided(
73
+ grad_in_sizes, grad_in_strides
74
+ );
75
+ /* } */
76
+
77
+ // During the TensorIterator iteration we have to know
78
+ // i_dim in grad_out[i_1,...,i_dim,...i_n],
79
+ // idx_dim stores this information
80
+ /* prepare idx_dim for TensorIterator { */
81
+ auto idx_dim = at::arange(
82
+ 0, iter_dim_size, grad_in.options().dtype(at::kLong)
83
+ );
84
+
85
+ auto grad_out_dim = ensure_nonempty_dim(grad_out.dim());
86
+
87
+ auto idx_dim_strides = std::vector<int64_t>(grad_out_dim, 0);
88
+ auto idx_dim_sizes = std::vector<int64_t>(grad_out_dim, 1);
89
+
90
+ idx_dim_strides[dim] = 1;
91
+ idx_dim_sizes[dim] = iter_dim_size;
92
+
93
+ // idx_dim size will broadcast over determined by grad_out sizes in TensorIterator
94
+ auto idx_dim_restrided = idx_dim.as_strided(idx_dim_sizes, idx_dim_strides);
95
+ /* } */
96
+
97
+ auto iter = TensorIteratorConfig()
98
+ .set_check_mem_overlap(false)
99
+ .check_all_same_dtype(false)
100
+ .resize_outputs(false)
101
+ .add_owned_output(grad_out_restrided)
102
+ .add_owned_const_input(grad_in_restrided)
103
+ .add_owned_const_input(idx_dim_restrided)
104
+ .build();
105
+
106
+ return iter;
107
+ }
108
+ }
109
+
110
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/UpSample.h ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cmath>
4
+
5
+ #include <ATen/OpMathType.h>
6
+ #include <ATen/TensorUtils.h>
7
+ #include <ATen/OpMathType.h>
8
+ #include <ATen/core/Tensor.h>
9
+ #include <ATen/cpu/vec/functional.h>
10
+ #include <ATen/cpu/vec/vec.h>
11
+ #include <ATen/native/DispatchStub.h>
12
+ #include <ATen/native/cpu/utils.h>
13
+
14
+ /**
15
+ * Note [compute_scales_value]
16
+ * Note [area_pixel_compute_scale]
17
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18
+ * Interpolate with scale_factor can have different behaviors
19
+ * depending on the value of recompute_scale_factor:
20
+ *
21
+ * - With recompute_scale_factor = True (current default behavior):
22
+ * the scale_factor, when provided by the user, are used to calculate
23
+ * the output size. The input size and the computed output_size
24
+ * are then used to infer new values for the scales which are
25
+ * used in the interpolation. Because floating-point math is not exact,
26
+ * this may be a different value from the user-supplied scales.
27
+ *
28
+ * - With recompute_scale_factor = False (which will be the default
29
+ * behavior starting 1.5.0):
30
+ * the behavior follows opencv logic, and the scales provided by
31
+ * the user are the ones used in the interpolation calculations.
32
+ *
33
+ * If the scales are not provided or if they are provided but
34
+ * recompute_scale_factor is set to True (default behavior), the scales
35
+ * are computed from the input and the output size;
36
+ *
37
+ *
38
+ * When the scales are inferred from the input and output sizes,
39
+ * we view each pixel as an area, idx + 0.5 as its center index.
40
+ * Here is an example formula in 1D case.
41
+ * if align_corners: center of two corner pixel areas are preserved,
42
+ * (0.5, 0.5) -> (0.5, 0.5),
43
+ * (input_size - 0.5, 0.5) -> (output_size - 0.5)
44
+ * scale = (input_size - 0.5 - 0.5) / (output_size - 0.5 - 0.5)
45
+ * src_index + 0.5 - 0.5 = scale * (dst_index + 0.5 - 0.5)
46
+ * if not align_corners: the whole range is scaled accordingly
47
+ * scale = input_size / output_size
48
+ * src_idx + 0.5 = scale * (dst_index + 0.5)
49
+ */
50
+
51
+ namespace at::native {
52
+
53
+ namespace upsample {
54
+
55
+ TORCH_API c10::SmallVector<int64_t, 3> compute_output_size(
56
+ c10::IntArrayRef input_size, // Full input tensor size.
57
+ at::OptionalIntArrayRef output_size,
58
+ std::optional<c10::ArrayRef<double>> scale_factors);
59
+
60
+ inline std::optional<double> get_scale_value(std::optional<c10::ArrayRef<double>> scales, int idx) {
61
+ if (!scales) {
62
+ return std::nullopt;
63
+ }
64
+ return scales->at(idx);
65
+ }
66
+
67
+ } // namespace upsample
68
+
69
+ using scale_t = std::optional<double>;
70
+ using upsampling_nearest1d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_w);
71
+ using _upsampling_nearest_exact1d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_w);
72
+ using upsampling_nearest2d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_h, scale_t scales_w);
73
+ using _upsampling_nearest_exact2d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_h, scale_t scales_w);
74
+ using upsampling_nearest3d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_d, scale_t scales_h, scale_t scales_w);
75
+ using _upsampling_nearest_exact3d = void(*)(const Tensor& output, const Tensor& input, scale_t scales_d, scale_t scales_h, scale_t scales_w);
76
+ using upsampling_linear1d = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_w);
77
+ using upsampling_bilinear2d = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_h, scale_t scales_w);
78
+ using _upsampling_bilinear2d_aa = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_h, scale_t scales_w);
79
+ using upsampling_trilinear3d = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_d, scale_t scales_h, scale_t scales_w);
80
+ using upsampling_bicubic2d = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_h, scale_t scales_w);
81
+ using _upsampling_bicubic2d_aa = void(*)(const Tensor& output, const Tensor& input, bool align_corners, scale_t scales_h, scale_t scales_w);
82
+ DECLARE_DISPATCH(upsampling_nearest1d, upsample_nearest1d_kernel)
83
+ DECLARE_DISPATCH(_upsampling_nearest_exact1d, _upsample_nearest_exact1d_kernel)
84
+ DECLARE_DISPATCH(upsampling_nearest2d, upsample_nearest2d_kernel)
85
+ DECLARE_DISPATCH(_upsampling_nearest_exact2d, _upsample_nearest_exact2d_kernel)
86
+ DECLARE_DISPATCH(upsampling_nearest3d, upsample_nearest3d_kernel)
87
+ DECLARE_DISPATCH(_upsampling_nearest_exact3d, _upsample_nearest_exact3d_kernel)
88
+ DECLARE_DISPATCH(upsampling_nearest1d, upsample_nearest1d_backward_kernel)
89
+ DECLARE_DISPATCH(_upsampling_nearest_exact1d, _upsample_nearest_exact1d_backward_kernel)
90
+ DECLARE_DISPATCH(upsampling_nearest2d, upsample_nearest2d_backward_kernel)
91
+ DECLARE_DISPATCH(_upsampling_nearest_exact2d, _upsample_nearest_exact2d_backward_kernel)
92
+ DECLARE_DISPATCH(upsampling_nearest3d, upsample_nearest3d_backward_kernel)
93
+ DECLARE_DISPATCH(_upsampling_nearest_exact3d, _upsample_nearest_exact3d_backward_kernel)
94
+ DECLARE_DISPATCH(upsampling_linear1d, upsample_linear1d_kernel)
95
+ DECLARE_DISPATCH(upsampling_bilinear2d, upsample_bilinear2d_kernel)
96
+ DECLARE_DISPATCH(_upsampling_bilinear2d_aa, _upsample_bilinear2d_aa_kernel)
97
+ DECLARE_DISPATCH(upsampling_trilinear3d, upsample_trilinear3d_kernel)
98
+ DECLARE_DISPATCH(upsampling_linear1d, upsample_linear1d_backward_kernel)
99
+ DECLARE_DISPATCH(upsampling_bilinear2d, upsample_bilinear2d_backward_kernel)
100
+ DECLARE_DISPATCH(_upsampling_bilinear2d_aa, _upsample_bilinear2d_aa_backward_kernel)
101
+ DECLARE_DISPATCH(upsampling_trilinear3d, upsample_trilinear3d_backward_kernel)
102
+ DECLARE_DISPATCH(upsampling_bicubic2d, upsample_bicubic2d_kernel)
103
+ DECLARE_DISPATCH(_upsampling_bicubic2d_aa, _upsample_bicubic2d_aa_kernel)
104
+ DECLARE_DISPATCH(_upsampling_bicubic2d_aa, _upsample_bicubic2d_aa_backward_kernel)
105
+
106
+ [[maybe_unused]] inline std::array<int64_t, 3> upsample_1d_common_check(
107
+ IntArrayRef input_size,
108
+ IntArrayRef output_size) {
109
+ TORCH_CHECK(
110
+ output_size.size() == 1,
111
+ "It is expected output_size equals to 1, but got size ",
112
+ output_size.size());
113
+
114
+ TORCH_CHECK(
115
+ input_size.size() == 3,
116
+ "It is expected input_size equals to 3, but got size ",
117
+ input_size.size());
118
+
119
+ int64_t output_width = output_size[0];
120
+
121
+ int64_t nbatch = input_size[0];
122
+ int64_t channels = input_size[1];
123
+ int64_t input_width = input_size[2];
124
+
125
+ TORCH_CHECK(
126
+ input_width > 0 && output_width > 0,
127
+ "Input and output sizes should be greater than 0, but got input (W: ",
128
+ input_width,
129
+ ") and output (W: ",
130
+ output_width,
131
+ ")");
132
+
133
+ return {nbatch, channels, output_width};
134
+ }
135
+
136
+ [[maybe_unused]] inline std::array<int64_t, 4> upsample_2d_common_check(
137
+ IntArrayRef input_size,
138
+ IntArrayRef output_size) {
139
+ TORCH_CHECK(
140
+ output_size.size() == 2,
141
+ "It is expected output_size equals to 2, but got size ",
142
+ output_size.size());
143
+
144
+ TORCH_CHECK(
145
+ input_size.size() == 4,
146
+ "It is expected input_size equals to 4, but got size ",
147
+ input_size.size());
148
+
149
+ int64_t output_height = output_size[0];
150
+ int64_t output_width = output_size[1];
151
+
152
+ int64_t nbatch = input_size[0];
153
+ int64_t channels = input_size[1];
154
+ int64_t input_height = input_size[2];
155
+ int64_t input_width = input_size[3];
156
+
157
+ TORCH_CHECK(
158
+ input_height > 0 && input_width > 0 && output_height > 0 &&
159
+ output_width > 0,
160
+ "Input and output sizes should be greater than 0,"
161
+ " but got input (H: ",
162
+ input_height,
163
+ ", W: ",
164
+ input_width,
165
+ ") output (H: ",
166
+ output_height,
167
+ ", W: ",
168
+ output_width,
169
+ ")");
170
+
171
+ return {nbatch, channels, output_height, output_width};
172
+ }
173
+
174
+ [[maybe_unused]] inline std::array<int64_t, 5> upsample_3d_common_check(
175
+ IntArrayRef input_size,
176
+ IntArrayRef output_size) {
177
+ TORCH_CHECK(
178
+ output_size.size() == 3,
179
+ "It is expected output_size equals to 3, but got size ",
180
+ output_size.size());
181
+
182
+ TORCH_CHECK(
183
+ input_size.size() == 5,
184
+ "It is expected input_size equals to 5, but got size ",
185
+ input_size.size());
186
+
187
+ int64_t output_depth = output_size[0];
188
+ int64_t output_height = output_size[1];
189
+ int64_t output_width = output_size[2];
190
+
191
+ int64_t nbatch = input_size[0];
192
+ int64_t channels = input_size[1];
193
+ int64_t input_depth = input_size[2];
194
+ int64_t input_height = input_size[3];
195
+ int64_t input_width = input_size[4];
196
+
197
+ TORCH_CHECK(
198
+ input_depth > 0 && input_height > 0 && input_width > 0 &&
199
+ output_depth > 0 && output_height > 0 && output_width > 0,
200
+ "Input and output sizes should be greater than 0, but got input (D: ",
201
+ input_depth,
202
+ ", H: ",
203
+ input_height,
204
+ ", W: ",
205
+ input_width,
206
+ ") output (D: ",
207
+ output_depth,
208
+ ", H: ",
209
+ output_height,
210
+ ", W: ",
211
+ output_width,
212
+ ")");
213
+
214
+
215
+ return {nbatch, channels, output_depth, output_height, output_width};
216
+ }
217
+
218
+ inline void upsample_2d_shape_check(
219
+ const Tensor& input,
220
+ const Tensor& grad_output,
221
+ int64_t nbatch,
222
+ int64_t nchannels,
223
+ int64_t input_height,
224
+ int64_t input_width,
225
+ int64_t output_height,
226
+ int64_t output_width) {
227
+ TORCH_CHECK(
228
+ input_height > 0 && input_width > 0 && output_height > 0 &&
229
+ output_width > 0,
230
+ "Input and output sizes should be greater than 0,"
231
+ " but got input (H: ",
232
+ input_height,
233
+ ", W: ",
234
+ input_width,
235
+ ") output (H: ",
236
+ output_height,
237
+ ", W: ",
238
+ output_width,
239
+ ")");
240
+
241
+ if (input.defined()) {
242
+ // Allow for empty batch size but not other dimensions
243
+ TORCH_CHECK(
244
+ (input.numel() != 0 ||
245
+ (input.size(1) != 0 && input.size(2) != 0 && input.size(3) != 0)
246
+ ) &&
247
+ input.dim() == 4,
248
+ "Non-empty 4D data tensor expected but got a tensor with sizes ",
249
+ input.sizes());
250
+ } else if (grad_output.defined()) {
251
+ check_dim_size(grad_output, 4, 0, nbatch);
252
+ check_dim_size(grad_output, 4, 1, nchannels);
253
+ check_dim_size(grad_output, 4, 2, output_height);
254
+ check_dim_size(grad_output, 4, 3, output_width);
255
+ }
256
+ }
257
+
258
+ template <typename scalar_t>
259
+ inline scalar_t compute_scales_value(
260
+ const std::optional<double> scale,
261
+ int64_t input_size,
262
+ int64_t output_size) {
263
+ // see Note [compute_scales_value]
264
+ // FIXME: remove magic > 0 after we ensure no models were serialized with -1 defaults.
265
+ return (scale.has_value() && scale.value() > 0.)
266
+ ? static_cast<scalar_t>(1.0 / scale.value())
267
+ : (static_cast<scalar_t>(input_size) / output_size);
268
+ }
269
+
270
+ template <typename scalar_t>
271
+ inline scalar_t area_pixel_compute_scale(
272
+ int64_t input_size,
273
+ int64_t output_size,
274
+ bool align_corners,
275
+ const std::optional<double> scale) {
276
+ // see Note [area_pixel_compute_scale]
277
+ if(align_corners) {
278
+ if(output_size > 1) {
279
+ return static_cast<scalar_t>(input_size - 1) / (output_size - 1);
280
+ } else {
281
+ return static_cast<scalar_t>(0);
282
+ }
283
+ } else {
284
+ return compute_scales_value<scalar_t>(scale, input_size, output_size);
285
+ }
286
+ }
287
+
288
+ template <typename scalar_t>
289
+ inline scalar_t area_pixel_compute_source_index(
290
+ scalar_t scale,
291
+ int64_t dst_index,
292
+ bool align_corners,
293
+ bool cubic) {
294
+ if (align_corners) {
295
+ return scale * dst_index;
296
+ } else {
297
+ scalar_t src_idx = scale * (dst_index + static_cast<scalar_t>(0.5)) -
298
+ static_cast<scalar_t>(0.5);
299
+ // [Note] Follow Opencv resize logic:
300
+ // We allow negative src_idx here and later will use
301
+ // dx = src_idx - floorf(src_idx)
302
+ // to compute the "distance"(which affects weights).
303
+ // For linear modes, weight distribution doesn't matter
304
+ // for negative indices as they use 2 pixels to interpolate.
305
+ // For example, [-1, 0], they both use pixel 0 value so it
306
+ // doesn't affect if we bound the src_idx to 0 or not.
307
+ // TODO: Our current linear mode impls use unbound indices
308
+ // where we should and then remove this cubic flag.
309
+ // This matters in cubic mode, as we might need [-1, 0, 1, 2]
310
+ // to interpolate and the weights can be affected.
311
+ return (!cubic && src_idx < static_cast<scalar_t>(0)) ? scalar_t(0)
312
+ : src_idx;
313
+ }
314
+ }
315
+
316
+ inline int64_t nearest_neighbor_compute_source_index(
317
+ const float scale,
318
+ int64_t dst_index,
319
+ int64_t input_size) {
320
+ // Index computation matching OpenCV INTER_NEAREST
321
+ // which is buggy and kept for BC
322
+ const int64_t src_index =
323
+ std::min(static_cast<int64_t>(floorf(dst_index * scale)), input_size - 1);
324
+ return src_index;
325
+ }
326
+
327
+ inline int64_t nearest_neighbor_exact_compute_source_index(
328
+ const float scale,
329
+ int64_t dst_index,
330
+ int64_t input_size) {
331
+ // index_f32 = (output_index + 0.5) * scale - 0.5
332
+ // input_index = round(index_f32)
333
+ // Same as Pillow and Scikit-Image/Scipy ndi.zoom
334
+ const int64_t src_index =
335
+ std::min(static_cast<int64_t>(floorf((dst_index + 0.5) * scale)), input_size - 1);
336
+ return src_index;
337
+ }
338
+
339
+ inline int64_t nearest_idx(
340
+ int64_t output_index,
341
+ int64_t input_size,
342
+ int64_t output_size,
343
+ std::optional<double> scales) {
344
+ // This method specificly treats cases: output_size == input_size or
345
+ // output_size == 2 * input_size, that we would like to get rid of
346
+ // We keep this method for BC and consider as deprecated.
347
+ // See nearest_exact_idx as replacement
348
+ if (output_size == input_size) {
349
+ // scale_factor = 1, simply copy
350
+ return output_index;
351
+ } else if (output_size == 2 * input_size) {
352
+ // scale_factor = 2, shift input index
353
+ return output_index >> 1;
354
+ } else {
355
+ float scale = compute_scales_value<float>(scales, input_size, output_size);
356
+ return nearest_neighbor_compute_source_index(scale, output_index, input_size);
357
+ }
358
+ }
359
+
360
+ inline int64_t nearest_exact_idx(
361
+ int64_t output_index,
362
+ int64_t input_size,
363
+ int64_t output_size,
364
+ std::optional<double> scales) {
365
+ float scale = compute_scales_value<float>(scales, input_size, output_size);
366
+ return nearest_neighbor_exact_compute_source_index(scale, output_index, input_size);
367
+ }
368
+
369
+ // Define a typedef to dispatch to nearest_idx or nearest_exact_idx
370
+ typedef int64_t (*nearest_idx_fn_t)(int64_t, int64_t, int64_t, std::optional<double>);
371
+
372
+ template <typename scalar_t>
373
+ scalar_t upsample_get_value_bounded(
374
+ scalar_t* data,
375
+ int64_t width,
376
+ int64_t height,
377
+ int64_t x,
378
+ int64_t y) {
379
+ int64_t access_x = std::max(std::min(x, width - 1), static_cast<int64_t>(0));
380
+ int64_t access_y = std::max(std::min(y, height - 1), static_cast<int64_t>(0));
381
+ return data[access_y * width + access_x];
382
+ }
383
+
384
+ template <typename scalar_t>
385
+ void upsample_increment_value_bounded(
386
+ scalar_t* data,
387
+ int64_t width,
388
+ int64_t height,
389
+ int64_t x,
390
+ int64_t y,
391
+ scalar_t value) {
392
+ int64_t access_x = std::max(std::min(x, width - 1), static_cast<int64_t>(0));
393
+ int64_t access_y = std::max(std::min(y, height - 1), static_cast<int64_t>(0));
394
+ data[access_y * width + access_x] += value;
395
+ }
396
+
397
+ // Based on
398
+ // https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
399
+ template <typename scalar_t>
400
+ scalar_t cubic_convolution1(scalar_t x, scalar_t A) {
401
+ return ((A + 2) * x - (A + 3)) * x * x + 1;
402
+ }
403
+
404
+ template <typename scalar_t>
405
+ scalar_t cubic_convolution2(scalar_t x, scalar_t A) {
406
+ return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A;
407
+ }
408
+
409
+ template <typename scalar_t>
410
+ void get_cubic_upsample_coefficients(
411
+ scalar_t coeffs[4],
412
+ scalar_t t) {
413
+ scalar_t A = -0.75;
414
+
415
+ scalar_t x1 = t;
416
+ coeffs[0] = cubic_convolution2<scalar_t>(x1 + 1.0, A);
417
+ coeffs[1] = cubic_convolution1<scalar_t>(x1, A);
418
+
419
+ // opposite coefficients
420
+ scalar_t x2 = 1.0 - t;
421
+ coeffs[2] = cubic_convolution1<scalar_t>(x2, A);
422
+ coeffs[3] = cubic_convolution2<scalar_t>(x2 + 1.0, A);
423
+ }
424
+
425
+ template <typename scalar_t>
426
+ inline scalar_t cubic_interp1d(
427
+ scalar_t x0,
428
+ scalar_t x1,
429
+ scalar_t x2,
430
+ scalar_t x3,
431
+ scalar_t t) {
432
+ scalar_t coeffs[4];
433
+ get_cubic_upsample_coefficients<scalar_t>(coeffs, t);
434
+
435
+ return x0 * coeffs[0] + x1 * coeffs[1] + x2 * coeffs[2] + x3 * coeffs[3];
436
+ }
437
+
438
+ // when `real_input_index` becomes larger than the range the floating point
439
+ // type can accurately represent, the type casting to `int64_t` might exceed
440
+ // `input_size`, causing overflow. So we guard it with `std::min` below.
441
+ template<typename scalar_t, typename opmath_t>
442
+ inline void guard_index_and_lambda(const opmath_t& real_input_index, const int64_t& input_size, int64_t& input_index, scalar_t& lambda) {
443
+ input_index = std::min(static_cast<int64_t>(floorf(real_input_index)), input_size - 1);
444
+ lambda = std::min(
445
+ std::max(real_input_index - input_index, static_cast<opmath_t>(0)),
446
+ static_cast<opmath_t>(1)
447
+ );
448
+ }
449
+
450
+ template<typename scalar_t, typename opmath_t>
451
+ inline void compute_source_index_and_lambda(
452
+ int64_t& input_index0,
453
+ int64_t& input_index1,
454
+ scalar_t& lambda0,
455
+ scalar_t& lambda1,
456
+ opmath_t ratio,
457
+ int64_t output_index,
458
+ int64_t input_size,
459
+ int64_t output_size,
460
+ bool align_corners) {
461
+ if (output_size == input_size) {
462
+ // scale_factor = 1, simply copy
463
+ input_index0 = output_index;
464
+ input_index1 = output_index;
465
+ lambda0 = static_cast<scalar_t>(1);
466
+ lambda1 = static_cast<scalar_t>(0);
467
+ } else {
468
+ const auto real_input_index =
469
+ area_pixel_compute_source_index<opmath_t>(
470
+ ratio, output_index, align_corners, /*cubic=*/false);
471
+ guard_index_and_lambda(real_input_index, input_size, input_index0, lambda1);
472
+ int64_t offset = (input_index0 < input_size - 1) ? 1 : 0;
473
+ input_index1 = input_index0 + offset;
474
+ lambda0 = static_cast<scalar_t>(1.) - lambda1;
475
+ }
476
+ }
477
+
478
+ // It will not be used by data types other than BFloat16 and Half.
479
+ template <typename scalar_in, typename scalar_out,
480
+ typename std::enable_if_t<!is_reduced_floating_point_v<scalar_out> || !std::is_same_v<scalar_in, float>, int> = 0>
481
+ void inline apply_grad_input(scalar_in* buffer_ptr, scalar_out* gin, int64_t size) {
482
+ TORCH_CHECK((is_reduced_floating_point_v<scalar_out>),
483
+ "Upsample backward only support BFloat16 and Half in the lower precision data types on CPU.")
484
+ TORCH_CHECK((std::is_same_v<scalar_in, float>),
485
+ "Upsample backward should use float as acc buffer for BFloat16 and Half grad input on CPU.")
486
+ return;
487
+ }
488
+
489
+ template <typename scalar_in, typename scalar_out,
490
+ typename std::enable_if_t<is_reduced_floating_point_v<scalar_out> && std::is_same_v<scalar_in, float>, int> = 0>
491
+ void inline apply_grad_input(scalar_in* buffer_ptr, scalar_out* gin, int64_t size) {
492
+ using bVec = Vectorized<scalar_out>;
493
+ using fVec = Vectorized<float>;
494
+ int64_t d = 0;
495
+ for (; d < size - (size % bVec::size()); d += bVec::size()) {
496
+ bVec gin_bvec = bVec::loadu(gin + d);
497
+ auto [gin_fvec0, gin_fvec1] = convert_to_float<scalar_out>(gin_bvec);
498
+ gin_fvec0 += fVec::loadu(buffer_ptr + d);
499
+ gin_fvec1 += fVec::loadu(buffer_ptr + d + fVec::size());
500
+ fVec(0).store(buffer_ptr + d);
501
+ fVec(0).store(buffer_ptr + d + fVec::size());
502
+ convert_from_float<scalar_out>(gin_fvec0, gin_fvec1).store(gin + d);
503
+ }
504
+ for (; d < size; d++) {
505
+ gin[d] += buffer_ptr[d];
506
+ buffer_ptr[d] = 0;
507
+ }
508
+ }
509
+
510
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/batch_norm.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 batch_norm_fn = void (*)(Tensor&, const Tensor&, const Tensor&,
9
+ const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double);
10
+ using batch_norm_collect_stats_fn = void (*)(Tensor&, Tensor&, const Tensor&);
11
+ using batch_norm_backward_fn = void(*)(Tensor&, Tensor&, Tensor&, const Tensor&,
12
+ const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double);
13
+
14
+ DECLARE_DISPATCH(batch_norm_fn, batch_norm_cpu_stub)
15
+ DECLARE_DISPATCH(batch_norm_collect_stats_fn, batch_norm_cpu_collect_stats_stub)
16
+ DECLARE_DISPATCH(batch_norm_backward_fn, batch_norm_cpu_backward_stub)
17
+
18
+ // TensorAccessor when it is defined to work around undefined...
19
+ template <typename scalar_t>
20
+ static TensorAccessor<scalar_t, 1> conditional_accessor_1d(const Tensor& t) {
21
+ if (! t.defined()) {
22
+ return TensorAccessor<scalar_t, 1>(nullptr, nullptr, nullptr);
23
+ }
24
+ return t.accessor<scalar_t, 1>();
25
+ }
26
+
27
+ template <typename scalar_t>
28
+ static scalar_t* conditional_data_ptr(const Tensor& t) {
29
+ if constexpr (std::is_const_v<scalar_t>) {
30
+ return t.defined() ? t.contiguous().const_data_ptr<scalar_t>()
31
+ : nullptr;
32
+ } else {
33
+ return t.defined() ? t.contiguous().data_ptr<scalar_t>()
34
+ : nullptr;
35
+ }
36
+ }
37
+
38
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/group_norm.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (*)(
12
+ const Tensor& /* X */,
13
+ const Tensor& /* gamma */,
14
+ const Tensor& /* beta */,
15
+ int64_t /* N */,
16
+ int64_t /* C */,
17
+ int64_t /* HxW */,
18
+ int64_t /* group */,
19
+ double /* eps */,
20
+ Tensor& /* Y */,
21
+ Tensor& /* mean */,
22
+ Tensor& /* rstd */);
23
+
24
+ using backward_fn = void (*)(
25
+ const Tensor& /* dY */,
26
+ const Tensor& /* X */,
27
+ const Tensor& /* mean */,
28
+ const Tensor& /* rstd */,
29
+ const Tensor& /* gamma */,
30
+ int64_t /* N */,
31
+ int64_t /* C */,
32
+ int64_t /* HxW */,
33
+ int64_t /* group */,
34
+ Tensor& /* dX */,
35
+ Tensor& /* dgamma */,
36
+ Tensor& /* dbeta */);
37
+
38
+ DECLARE_DISPATCH(forward_fn, GroupNormKernel)
39
+ DECLARE_DISPATCH(backward_fn, GroupNormBackwardKernel)
40
+
41
+ } // namespace native
42
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/im2col.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/TensorUtils.h>
5
+ #include <ATen/Utils.h>
6
+ #include <ATen/Parallel.h>
7
+ #include <ATen/native/cpu/utils.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #include <algorithm>
11
+
12
+ namespace at::native {
13
+
14
+ template <typename T>
15
+ static void im2col(
16
+ const T* data_im,
17
+ const int64_t channels,
18
+ const int64_t height,
19
+ const int64_t width,
20
+ const int64_t output_height,
21
+ const int64_t output_width,
22
+ const int64_t kernel_h,
23
+ const int64_t kernel_w,
24
+ const int64_t pad_h,
25
+ const int64_t pad_w,
26
+ const int64_t stride_h,
27
+ const int64_t stride_w,
28
+ const int64_t dilation_h,
29
+ const int64_t dilation_w,
30
+ T* data_col,
31
+ bool is_channels_last = false) {
32
+ const int64_t height_col = output_height;
33
+ const int64_t width_col = output_width;
34
+ const int64_t channels_col = channels * kernel_h * kernel_w;
35
+
36
+ if (is_channels_last) {
37
+ at::parallel_for(0, height_col * width_col, 0, [&](int64_t begin, int64_t end) {
38
+ int64_t h_col{0}, w_col{0};
39
+ data_index_init(begin, h_col, height_col, w_col, width_col);
40
+
41
+ for (const auto i_col : c10::irange(begin, end)) {
42
+ for (const auto h_offset : c10::irange(kernel_h)) {
43
+ int64_t h_im = h_col * stride_h - pad_h + h_offset * dilation_h;
44
+ for (const auto w_offset : c10::irange(kernel_w)) {
45
+ int64_t w_im = w_col * stride_w - pad_w + w_offset * dilation_w;
46
+
47
+ const T* slice_im = data_im + (h_im * width + w_im) * channels;
48
+ T* slice_col = data_col + (i_col * kernel_h * kernel_w + h_offset * kernel_w + w_offset) * channels;
49
+
50
+ if (h_im >= 0 && w_im >= 0 && h_im < height && w_im < width) {
51
+ std::copy_n(slice_im, channels, slice_col);
52
+ } else {
53
+ std::fill_n(slice_col, channels, T(0));
54
+ }
55
+ }
56
+ }
57
+
58
+ // move the next index
59
+ data_index_step(h_col, height_col, w_col, width_col);
60
+ }
61
+ });
62
+ } else {
63
+ at::parallel_for(0, channels_col, 0, [&](int64_t begin, int64_t end) {
64
+ int64_t c_im{0}, h_offset{0}, w_offset{0};
65
+ data_index_init(begin, c_im, channels, h_offset, kernel_h, w_offset, kernel_w);
66
+
67
+ for (const auto c_col : c10::irange(begin, end)) {
68
+ for (const auto h_col : c10::irange(height_col)) {
69
+ int64_t h_im = h_col * stride_h - pad_h + h_offset * dilation_h;
70
+ for (const auto w_col : c10::irange(width_col)) {
71
+ int64_t w_im = w_col * stride_w - pad_w + w_offset * dilation_w;
72
+ data_col[(c_col * height_col + h_col) * width_col + w_col] =
73
+ (h_im >= 0 && w_im >= 0 && h_im < height && w_im < width)
74
+ ? c10::load(&(data_im[(c_im * height + h_im) * width + w_im]))
75
+ : static_cast<T>(0);
76
+ }
77
+ }
78
+
79
+ // move to the next index
80
+ data_index_step(c_im, channels, h_offset, kernel_h, w_offset, kernel_w);
81
+ }
82
+ });
83
+ }
84
+ }
85
+
86
+ template <typename T>
87
+ static void col2im(
88
+ const T* data_col,
89
+ const int64_t channels,
90
+ const int64_t height,
91
+ const int64_t width,
92
+ const int64_t output_height,
93
+ const int64_t output_width,
94
+ const int64_t kernel_h,
95
+ const int64_t kernel_w,
96
+ const int64_t pad_h,
97
+ const int64_t pad_w,
98
+ const int64_t stride_h,
99
+ const int64_t stride_w,
100
+ const int64_t dilation_h,
101
+ const int64_t dilation_w,
102
+ T* data_im,
103
+ bool is_channels_last = false) {
104
+ std::fill_n(data_im, height * width * channels, T(0));
105
+
106
+ const int64_t height_col = output_height;
107
+ const int64_t width_col = output_width;
108
+ const int64_t channels_col = channels * kernel_h * kernel_w;
109
+
110
+ if (is_channels_last) {
111
+ for (const auto h_col : c10::irange(height_col)) {
112
+ for (const auto w_col : c10::irange(width_col)) {
113
+ for (const auto h_offset : c10::irange(kernel_h)) {
114
+ int64_t h_im = h_col * stride_h - pad_h + h_offset * dilation_h;
115
+ for (const auto w_offset : c10::irange(kernel_w)) {
116
+ int64_t w_im = w_col * stride_w - pad_w + w_offset * dilation_w;
117
+
118
+ T* slice_im = data_im + (h_im * width + w_im) * channels;
119
+ const T* slice_col = data_col + ((h_col * width_col + w_col) * kernel_h * kernel_w
120
+ + h_offset * kernel_w + w_offset) * channels;
121
+
122
+ if (h_im >= 0 && h_im < height && w_im >= 0 && w_im < width) {
123
+ std::transform(slice_col, slice_col + channels, slice_im, slice_im, std::plus<T>());
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ } else {
130
+ for (const auto c_col : c10::irange(channels_col)) {
131
+ int64_t w_offset = c_col % kernel_w;
132
+ int64_t h_offset = (c_col / kernel_w) % kernel_h;
133
+ int64_t c_im = c_col / kernel_h / kernel_w;
134
+
135
+ for (const auto h_col : c10::irange(height_col)) {
136
+ int64_t h_im = h_col * stride_h - pad_h + h_offset * dilation_h;
137
+ for (const auto w_col : c10::irange(width_col)) {
138
+ int64_t w_im = w_col * stride_w - pad_w + w_offset * dilation_w;
139
+
140
+ if (h_im >= 0 && h_im < height && w_im >= 0 && w_im < width)
141
+ data_im[(c_im * height + h_im) * width + w_im] +=
142
+ data_col[(c_col * height_col + h_col) * width_col + w_col];
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/im2col_shape_check.h ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/TensorUtils.h>
4
+ #include <ATen/div_rtn.h>
5
+
6
+ namespace at::native {
7
+
8
+ inline void col2im_shape_check(
9
+ const Tensor& input,
10
+ const Tensor& grad_output,
11
+ int64_t output_height,
12
+ int64_t output_width,
13
+ int64_t kernel_height,
14
+ int64_t kernel_width,
15
+ int64_t dilation_height,
16
+ int64_t dilation_width,
17
+ int64_t pad_height,
18
+ int64_t pad_width,
19
+ int64_t stride_height,
20
+ int64_t stride_width) {
21
+ TORCH_CHECK(
22
+ kernel_width > 0 && kernel_height > 0,
23
+ "kernel size should be greater than zero, but got kernel_height: ",
24
+ kernel_height,
25
+ " kernel_width: ",
26
+ kernel_width);
27
+ TORCH_CHECK(
28
+ stride_width > 0 && stride_height > 0,
29
+ "stride should be greater than zero, but got stride_height: ",
30
+ stride_height,
31
+ " stride_width: ",
32
+ stride_width);
33
+ TORCH_CHECK(
34
+ dilation_width > 0 && dilation_height > 0,
35
+ "dilation should be greater than zero, but got dilation_height: ",
36
+ dilation_height,
37
+ " dilation_width: ",
38
+ dilation_width);
39
+ TORCH_CHECK(
40
+ pad_width >= 0 && pad_height >= 0,
41
+ "padding should be non-negative, but got pad_height: ",
42
+ pad_height,
43
+ " pad_width: ",
44
+ pad_width);
45
+
46
+
47
+ int64_t ndim = input.ndimension();
48
+ // allow dim=0 only the batch dimension.
49
+ TORCH_CHECK(
50
+ (ndim == 2 && input.size(0) != 0 && input.size(1) != 0) ||
51
+ (ndim == 3 && input.size(1) != 0 && input.size(2) != 0),
52
+ "Expected 2D or 3D (batch mode) tensor for input with possibly 0 batch size and non-zero dimensions for input, but got: ",
53
+ input.sizes());
54
+
55
+ int64_t batch_dim = (ndim == 3) ? 0 : -1;
56
+ int64_t n_input_plane = input.size(batch_dim + 1);
57
+
58
+ if (n_input_plane % (kernel_width * kernel_height) != 0) {
59
+ TORCH_CHECK(false,
60
+ "Expected size of input's dimension 1 to be divisible by the "
61
+ "product of kernel_size, but got input.size(1)=",
62
+ n_input_plane,
63
+ " and kernel_size=(",
64
+ kernel_height,
65
+ ", ",
66
+ kernel_width,
67
+ ").");
68
+ }
69
+
70
+ int64_t input_length = input.size(batch_dim + 2);
71
+ int64_t n_blocks_height =
72
+ div_rtn<int64_t>(
73
+ output_height + 2 * pad_height -
74
+ dilation_height * (kernel_height - 1) - 1,
75
+ stride_height) +
76
+ 1;
77
+ int64_t n_blocks_width = div_rtn<int64_t>(
78
+ output_width + 2 * pad_width -
79
+ dilation_width * (kernel_width - 1) - 1,
80
+ stride_width) +
81
+ 1;
82
+
83
+ if (input_length != (n_blocks_height * n_blocks_width)) {
84
+ TORCH_CHECK(false,
85
+ "Given output_size=(",
86
+ output_height,
87
+ ", ",
88
+ output_width,
89
+ "), kernel_size=(",
90
+ kernel_height,
91
+ ", ",
92
+ kernel_width,
93
+ "), dilation=(",
94
+ dilation_height,
95
+ ", ",
96
+ dilation_width,
97
+ "), padding=(",
98
+ pad_height,
99
+ ", ",
100
+ pad_width,
101
+ "), stride=(",
102
+ stride_height,
103
+ ", ",
104
+ stride_width,
105
+ "), expected size of input's dimension 2 to match the calculated number of ",
106
+ "sliding blocks ",
107
+ n_blocks_height,
108
+ " * ",
109
+ n_blocks_width,
110
+ " = ",
111
+ (n_blocks_height * n_blocks_width),
112
+ ", but got input.size(2)=",
113
+ input_length,
114
+ ".");
115
+ }
116
+
117
+ TORCH_CHECK(
118
+ n_blocks_height >= 1 && n_blocks_width >= 1,
119
+ "Given output_size=(", output_height, ", ", output_width, "), ",
120
+ "kernel_size=(", kernel_height, ", ", kernel_width, "), ",
121
+ "dilation=(", dilation_height, ", ", dilation_width, "), ",
122
+ "padding=(", pad_height, ", ", pad_width, "), ",
123
+ "stride=(", stride_height, ", ", stride_width, "), ",
124
+ "calculated shape of the array of sliding blocks as ",
125
+ "(", n_blocks_height, ", ", n_blocks_width, "), ",
126
+ "which is too small (non-positive)");
127
+
128
+ if (output_width < 1 || output_height < 1) {
129
+ TORCH_CHECK(false,
130
+ "Expected output spatial size to be positive, but got: output_size=(",
131
+ output_height,
132
+ ", ",
133
+ output_width,
134
+ ").");
135
+ }
136
+ }
137
+
138
+ inline void im2col_shape_check(
139
+ const Tensor& input,
140
+ const Tensor& grad_output,
141
+ int64_t kernel_height,
142
+ int64_t kernel_width,
143
+ int64_t dilation_height,
144
+ int64_t dilation_width,
145
+ int64_t pad_height,
146
+ int64_t pad_width,
147
+ int64_t stride_height,
148
+ int64_t stride_width) {
149
+ TORCH_CHECK(
150
+ kernel_width > 0 && kernel_height > 0,
151
+ "kernel size should be greater than zero, but got kernel_height: ",
152
+ kernel_height,
153
+ " kernel_width: ",
154
+ kernel_width);
155
+
156
+ TORCH_CHECK(
157
+ dilation_width > 0 && dilation_height > 0,
158
+ "dilation should be greater than zero, but got dilation_height: ",
159
+ dilation_height,
160
+ " dilation_width: ",
161
+ dilation_width);
162
+
163
+ TORCH_CHECK(
164
+ pad_width >= 0 && pad_height >= 0,
165
+ "padding should be non-negative, but got pad_height: ",
166
+ pad_height,
167
+ " pad_width: ",
168
+ pad_width);
169
+
170
+ TORCH_CHECK(
171
+ stride_width > 0 && stride_height > 0,
172
+ "stride should be greater than zero, but got stride_height: ",
173
+ stride_height,
174
+ " stride_width: ",
175
+ stride_width);
176
+
177
+ int64_t ndim = input.ndimension();
178
+
179
+ // allow dim=0 only the batch dimension.
180
+ bool valid_dims = input.size(1) != 0 && input.size(2) != 0;
181
+ TORCH_CHECK(
182
+ (ndim == 3 && input.size(0) && valid_dims) ||
183
+ (ndim == 4 && valid_dims && input.size(3) != 0),
184
+ "Expected 3D or 4D (batch mode) tensor with possibly 0 batch size and other non-zero dimensions for input, but got: ",
185
+ input.sizes());
186
+
187
+ int64_t dim_batch = 0;
188
+
189
+ if (ndim == 3) {
190
+ dim_batch = -1;
191
+ }
192
+
193
+ int64_t input_height = input.size(dim_batch + 2);
194
+ int64_t input_width = input.size(dim_batch + 3);
195
+ int64_t output_height = div_rtn<int64_t>(
196
+ input_height + 2 * pad_height -
197
+ (dilation_height * (kernel_height - 1) + 1),
198
+ stride_height) +
199
+ 1;
200
+ int64_t output_width = div_rtn<int64_t>(
201
+ input_width + 2 * pad_width -
202
+ (dilation_width * (kernel_width - 1) + 1),
203
+ stride_width) +
204
+ 1;
205
+
206
+ if (output_height < 1 || output_width < 1) {
207
+ TORCH_CHECK(false,
208
+ "Given input with spatial size (",
209
+ input_height,
210
+ ", ",
211
+ input_height,
212
+ "), kernel_size=(",
213
+ kernel_height,
214
+ ", ",
215
+ kernel_width,
216
+ "), dilation=(",
217
+ dilation_height,
218
+ ", ",
219
+ dilation_width,
220
+ "), padding=(",
221
+ pad_height,
222
+ ", ",
223
+ pad_width,
224
+ "), calculated shape of the array of sliding blocks as (",
225
+ output_height,
226
+ ", ",
227
+ output_width,
228
+ "), but its components must be at least one.");
229
+ }
230
+ }
231
+
232
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/layer_norm.h ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/accumulate.h>
6
+
7
+ namespace at::native {
8
+
9
+ namespace {
10
+
11
+ C10_ALWAYS_INLINE void _check_rms_norm_inputs_symint(
12
+ const Tensor& input,
13
+ c10::SymIntArrayRef normalized_shape,
14
+ const Tensor& weight /* optional */) {
15
+
16
+ const int normalized_ndim = normalized_shape.size();
17
+ TORCH_CHECK(
18
+ normalized_ndim >= 1,
19
+ "Expected normalized_shape to be at least 1-dimensional, i.e., ",
20
+ "containing at least one element, but got normalized_shape = ",
21
+ normalized_shape);
22
+ TORCH_CHECK(
23
+ !weight.defined() || weight.sym_sizes().equals(normalized_shape),
24
+ "Expected weight to be of same shape as normalized_shape, but got ",
25
+ "weight of shape ",
26
+ weight.sym_sizes(),
27
+ " and normalized_shape = ",
28
+ normalized_shape);
29
+
30
+ const auto input_ndim = input.dim();
31
+ const auto input_shape = input.sym_sizes();
32
+ if (input_ndim < normalized_ndim ||
33
+ !input_shape.slice(input_ndim - normalized_ndim)
34
+ .equals(normalized_shape)) {
35
+ std::stringstream ss;
36
+ ss << "Given normalized_shape=" << normalized_shape
37
+ << ", expected input with shape [*";
38
+ for (auto size : normalized_shape) {
39
+ ss << ", " << size;
40
+ }
41
+ ss << "], but got input of size" << input_shape;
42
+ TORCH_CHECK(false, ss.str());
43
+ }
44
+ }
45
+
46
+ C10_ALWAYS_INLINE std::pair<int64_t, int64_t> _check_layer_norm_inputs(
47
+ const Tensor& input,
48
+ IntArrayRef normalized_shape,
49
+ const Tensor& weight /* optional */,
50
+ const Tensor& bias /* optional */) {
51
+
52
+ const int normalized_ndim = normalized_shape.size();
53
+ TORCH_CHECK(
54
+ normalized_ndim >= 1,
55
+ "Expected normalized_shape to be at least 1-dimensional, i.e., ",
56
+ "containing at least one element, but got normalized_shape = ",
57
+ normalized_shape);
58
+ TORCH_CHECK(
59
+ !weight.defined() || weight.sizes().equals(normalized_shape),
60
+ "Expected weight to be of same shape as normalized_shape, but got ",
61
+ "weight of shape ",
62
+ weight.sizes(),
63
+ " and normalized_shape = ",
64
+ normalized_shape);
65
+ TORCH_CHECK(
66
+ !bias.defined() || bias.sizes().equals(normalized_shape),
67
+ "Expected bias to be of same shape as normalized_shape, but got ",
68
+ "bias of shape ",
69
+ bias.sizes(),
70
+ " and normalized_shape = ",
71
+ normalized_shape);
72
+
73
+ const auto input_shape = input.sizes();
74
+ const auto input_ndim = input.dim();
75
+
76
+ if (input_ndim < normalized_ndim ||
77
+ !input_shape.slice(input_ndim - normalized_ndim)
78
+ .equals(normalized_shape)) {
79
+ std::stringstream ss;
80
+ ss << "Given normalized_shape=" << normalized_shape
81
+ << ", expected input with shape [*";
82
+ for (auto size : normalized_shape) {
83
+ ss << ", " << size;
84
+ }
85
+ ss << "], but got input of size" << input_shape;
86
+ TORCH_CHECK(false, ss.str());
87
+ }
88
+
89
+ const int axis = input_ndim - normalized_ndim;
90
+ const int64_t M =
91
+ c10::multiply_integers(input_shape.cbegin(), input_shape.cbegin() + axis);
92
+ const int64_t N =
93
+ c10::multiply_integers(input_shape.cbegin() + axis, input_shape.cend());
94
+
95
+ return std::make_pair(M, N);
96
+ }
97
+
98
+ } // namespace
99
+
100
+ void layer_norm_cpu_out(
101
+ at::Tensor& out,
102
+ const at::Tensor& input,
103
+ const Tensor& gamma,
104
+ const Tensor& beta,
105
+ double eps,
106
+ int64_t M,
107
+ int64_t N);
108
+
109
+ Tensor rms_norm_symint(
110
+ const Tensor& input,
111
+ c10::SymIntArrayRef normalized_shape,
112
+ const std::optional<Tensor>& weight_opt /* optional */,
113
+ std::optional<double> eps);
114
+
115
+ using forward_fn = void (*)(
116
+ const Tensor& /* X */,
117
+ const Tensor& /* gamma */,
118
+ const Tensor& /* beta */,
119
+ int64_t /* M */,
120
+ int64_t /* N */,
121
+ double /* eps */,
122
+ Tensor* /* Y */,
123
+ Tensor* /* mean */,
124
+ Tensor* /* rstd */);
125
+
126
+ using backward_fn = void (*)(
127
+ const Tensor& /* dY */,
128
+ const Tensor& /* X */,
129
+ const Tensor& /* mean */,
130
+ const Tensor& /* rstd */,
131
+ const Tensor& /* gamma */,
132
+ int64_t /* M */,
133
+ int64_t /* N */,
134
+ Tensor* /* dX */,
135
+ Tensor* /* dgamma */,
136
+ Tensor* /* dbeta */);
137
+
138
+ DECLARE_DISPATCH(forward_fn, LayerNormKernel)
139
+ DECLARE_DISPATCH(backward_fn, LayerNormBackwardKernel)
140
+
141
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/verbose_wrapper.h ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Export.h>
4
+
5
+ namespace torch::verbose {
6
+ TORCH_API int _mkl_set_verbose(int enable);
7
+ TORCH_API int _mkldnn_set_verbose(int level);
8
+ } // namespace torch::verbose
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/vol2col.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstring>
4
+
5
+ namespace at::native {
6
+
7
+ template <typename T>
8
+ void vol2col(
9
+ const T* data_vol,
10
+ const int64_t channels,
11
+ const int64_t depth,
12
+ const int64_t height,
13
+ const int64_t width,
14
+ const int64_t depth_col,
15
+ const int64_t height_col,
16
+ const int64_t width_col,
17
+ const int64_t kT,
18
+ const int64_t kernel_height,
19
+ const int64_t kernel_width,
20
+ const int64_t pT,
21
+ const int64_t pH,
22
+ const int64_t pW,
23
+ const int64_t dT,
24
+ const int64_t dH,
25
+ const int64_t dW,
26
+ const int64_t dilationT,
27
+ const int64_t dilationH,
28
+ const int64_t dilationW,
29
+ T* data_col) {
30
+ int64_t c, t, h, w;
31
+ int64_t channels_col = channels * kT * kernel_height * kernel_width;
32
+ for (c = 0; c < channels_col; ++c) {
33
+ int64_t w_offset = c % kernel_width;
34
+ int64_t h_offset = (c / kernel_width) % kernel_height;
35
+ int64_t t_offset = (c / kernel_width / kernel_height) % kT;
36
+ int64_t c_vol = c / kT / kernel_height / kernel_width;
37
+ for (t = 0; t < depth_col; ++t) {
38
+ int64_t t_pad = t * dT - pT + t_offset * dilationT;
39
+ for (h = 0; h < height_col; ++h) {
40
+ int64_t h_pad = h * dH - pH + h_offset * dilationH;
41
+ for (w = 0; w < width_col; ++w) {
42
+ int64_t w_pad = w * dW - pW + w_offset * dilationW;
43
+ if (t_pad >= 0 && t_pad < depth && h_pad >= 0 && h_pad < height &&
44
+ w_pad >= 0 && w_pad < width)
45
+ data_col[((c * depth_col + t) * height_col + h) * width_col + w] =
46
+ data_vol
47
+ [((c_vol * depth + t_pad) * height + h_pad) * width +
48
+ w_pad];
49
+ else
50
+ data_col[((c * depth_col + t) * height_col + h) * width_col + w] =
51
+ 0;
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ template <typename T>
59
+ void col2vol(
60
+ const T* data_col,
61
+ const int64_t channels,
62
+ const int64_t depth,
63
+ const int64_t height,
64
+ const int64_t width,
65
+ const int64_t out_depth,
66
+ const int64_t out_height,
67
+ const int64_t out_width,
68
+ const int64_t kT,
69
+ const int64_t kernel_height,
70
+ const int64_t kernel_width,
71
+ const int64_t pT,
72
+ const int64_t pH,
73
+ const int64_t pW,
74
+ const int64_t dT,
75
+ const int64_t dH,
76
+ const int64_t dW,
77
+ const int64_t dilationT,
78
+ const int64_t dilationH,
79
+ const int64_t dilationW,
80
+ T* data_vol) {
81
+ memset(data_vol, 0, sizeof(T) * depth * height * width * channels);
82
+ int64_t depth_col = out_depth;
83
+ int64_t height_col = out_height;
84
+ int64_t width_col = out_width;
85
+ int64_t channels_col = channels * kT * kernel_height * kernel_width;
86
+ for (int64_t c = 0; c < channels_col; ++c) {
87
+ int64_t w_offset = c % kernel_width;
88
+ int64_t h_offset = (c / kernel_width) % kernel_height;
89
+ int64_t t_offset = (c / kernel_width / kernel_height) % kT;
90
+ int64_t c_vol = c / kT / kernel_height / kernel_width;
91
+ for (int64_t t = 0; t < depth_col; ++t) {
92
+ int64_t t_pad = t * dT - pT + t_offset * dilationT;
93
+ for (int64_t h = 0; h < height_col; ++h) {
94
+ int64_t h_pad = h * dH - pH + h_offset * dilationH;
95
+ for (int64_t w = 0; w < width_col; ++w) {
96
+ int64_t w_pad = w * dW - pW + w_offset * dilationW;
97
+ if (t_pad >= 0 && t_pad < depth && h_pad >= 0 && h_pad < height &&
98
+ w_pad >= 0 && w_pad < width)
99
+ data_vol
100
+ [((c_vol * depth + t_pad) * height + h_pad) * width + w_pad] +=
101
+ data_col
102
+ [((c * depth_col + t) * height_col + h) * width_col + w];
103
+ }
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ } // namespace at::native