ZTWHHH commited on
Commit
4c31227
·
verified ·
1 Parent(s): ef4327e

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. .gitattributes +1 -0
  2. parrot/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda122.so +3 -0
  3. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/ATenCUDAGeneral.h +9 -0
  4. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDABlas.h +305 -0
  5. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h +138 -0
  6. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraph.h +80 -0
  7. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh +59 -0
  8. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h +266 -0
  9. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh +15 -0
  10. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAUtils.h +20 -0
  11. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh +115 -0
  12. wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/NumericLimits.cuh +121 -0
  13. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h +92 -0
  14. wemm/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h +41 -0
  15. wemm/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +320 -0
  16. wemm/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h +117 -0
  17. wemm/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h +167 -0
  18. wemm/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h +164 -0
  19. wemm/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h +46 -0
  20. wemm/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h +97 -0
  21. wemm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h +34 -0
  22. wemm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h +263 -0
  23. wemm/lib/python3.10/site-packages/torch/include/ATen/native/ConvUtils.h +405 -0
  24. wemm/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h +15 -0
  25. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h +14 -0
  26. wemm/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h +233 -0
  27. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Distance.h +20 -0
  28. wemm/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h +366 -0
  29. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Distributions.h +518 -0
  30. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Fill.h +21 -0
  31. wemm/lib/python3.10/site-packages/torch/include/ATen/native/FractionalMaxPooling.h +80 -0
  32. wemm/lib/python3.10/site-packages/torch/include/ATen/native/FunctionOfAMatrixUtils.h +20 -0
  33. wemm/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h +298 -0
  34. wemm/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h +109 -0
  35. wemm/lib/python3.10/site-packages/torch/include/ATen/native/IndexingUtils.h +160 -0
  36. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h +48 -0
  37. wemm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebra.h +18 -0
  38. wemm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h +624 -0
  39. wemm/lib/python3.10/site-packages/torch/include/ATen/native/LossMulti.h +72 -0
  40. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Math.h +0 -0
  41. wemm/lib/python3.10/site-packages/torch/include/ATen/native/MathBitFallThroughLists.h +71 -0
  42. wemm/lib/python3.10/site-packages/torch/include/ATen/native/MaxPooling.h +44 -0
  43. wemm/lib/python3.10/site-packages/torch/include/ATen/native/NonEmptyUtils.h +27 -0
  44. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Normalization.h +12 -0
  45. wemm/lib/python3.10/site-packages/torch/include/ATen/native/PointwiseOps.h +28 -0
  46. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Pool.h +336 -0
  47. wemm/lib/python3.10/site-packages/torch/include/ATen/native/Pow.h +69 -0
  48. wemm/lib/python3.10/site-packages/torch/include/ATen/native/RNN.h +53 -0
  49. wemm/lib/python3.10/site-packages/torch/include/ATen/native/ReduceAllOps.h +16 -0
  50. wemm/lib/python3.10/site-packages/torch/include/ATen/native/ReduceOpsUtils.h +447 -0
.gitattributes CHANGED
@@ -225,3 +225,4 @@ wemm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_met
225
  wemm/lib/python3.10/site-packages/torch/lib/libcudnn.so.8 filter=lfs diff=lfs merge=lfs -text
226
  wemm/lib/python3.10/site-packages/numpy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
227
  wemm/lib/python3.10/site-packages/sentencepiece/_sentencepiece.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
225
  wemm/lib/python3.10/site-packages/torch/lib/libcudnn.so.8 filter=lfs diff=lfs merge=lfs -text
226
  wemm/lib/python3.10/site-packages/numpy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
227
  wemm/lib/python3.10/site-packages/sentencepiece/_sentencepiece.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
228
+ parrot/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda122.so filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda122.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16b8578667eb6836c6b7923a3b3508d62809e4e91429674a0c3ab97cf60c5349
3
+ size 14561032
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/ATenCUDAGeneral.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <cuda_runtime.h>
5
+ #include <cuda_fp16.h>
6
+
7
+ #include <c10/macros/Export.h>
8
+
9
+ // Use TORCH_CUDA_CPP_API or TORCH_CUDA_CU_API for exports from this folder
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDABlas.h ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ /*
3
+ Provides a subset of CUDA BLAS functions as templates:
4
+
5
+ gemm<Dtype>(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c,
6
+ ldc)
7
+
8
+ gemv<Dtype>(transa, m, n, alpha, a, lda, x, incx, beta, y, incy)
9
+
10
+ dot<Dtype>(n, x, incx, y, incy, result)
11
+
12
+ where Dtype is double, float, at::Half or at::BFloat16 (ROCm, NOT for dot).
13
+ The functions are available in at::cuda::blas namespace.
14
+ */
15
+
16
+ #include <ATen/cuda/CUDAContext.h>
17
+ #include <ATen/OpMathType.h>
18
+
19
+ namespace at {
20
+ namespace cuda {
21
+ namespace blas {
22
+
23
+ // RAII guard that sets the CuBLAS pointer mode and restores it to
24
+ // its previous value when the guard is destroyed
25
+ class PointerModeGuard {
26
+ public:
27
+ PointerModeGuard(cublasHandle_t handle, cublasPointerMode_t mode) :
28
+ handle(handle) {
29
+ TORCH_CUDABLAS_CHECK(cublasGetPointerMode(handle, &previous_mode));
30
+ TORCH_CUDABLAS_CHECK(cublasSetPointerMode(handle, mode));
31
+ }
32
+
33
+ ~PointerModeGuard() {
34
+ cublasSetPointerMode(handle, previous_mode);
35
+ }
36
+
37
+ private:
38
+ cublasHandle_t handle;
39
+ cublasPointerMode_t previous_mode;
40
+ };
41
+
42
+ /* LEVEL 3 BLAS FUNCTIONS */
43
+
44
+ #define CUDABLAS_GEMM_ARGTYPES(Dtype) \
45
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
46
+ const Dtype *a, int64_t lda, const Dtype *b, int64_t ldb, at::opmath_type<Dtype> beta,\
47
+ Dtype *c, int64_t ldc
48
+
49
+ template <typename Dtype>
50
+ inline void gemm(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
51
+ AT_ERROR("at::cuda::blas::gemm: not implemented for ", typeid(Dtype).name());
52
+ }
53
+
54
+ template <>
55
+ void gemm<double>(CUDABLAS_GEMM_ARGTYPES(double));
56
+ template <>
57
+ void gemm<float>(CUDABLAS_GEMM_ARGTYPES(float));
58
+ #if !defined(USE_ROCM) || (defined(USE_ROCM) && ROCM_VERSION >= 21000)
59
+ template <>
60
+ void gemm<c10::complex<double>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<double>));
61
+ #endif
62
+ #if !defined(USE_ROCM) || (defined(USE_ROCM) && ROCM_VERSION >= 21000)
63
+ template <>
64
+ void gemm<c10::complex<float>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<float>));
65
+ #endif
66
+ template <>
67
+ void gemm<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
68
+ template <>
69
+ void gemm<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
70
+
71
+ #if !defined(USE_ROCM) && !defined(_MSC_VER)
72
+ enum GEMMAndBiasActivationEpilogue {
73
+ None,
74
+ RELU,
75
+ GELU,
76
+ };
77
+
78
+ // NOTE: GELU activation is not supported prior to CUDA 11.4 and will
79
+ // do nothing if passed in that case.
80
+ template <typename Dtype>
81
+ void gemm_and_bias(
82
+ bool transpose_mat1,
83
+ bool transpose_mat2,
84
+ int64_t m,
85
+ int64_t n,
86
+ int64_t k,
87
+ at::opmath_type<Dtype> alpha_val,
88
+ const Dtype* mat1_ptr,
89
+ int64_t mat1_ld,
90
+ const Dtype* mat2_ptr,
91
+ int64_t mat2_ld,
92
+ const Dtype* bias,
93
+ Dtype* result_ptr,
94
+ int64_t result_ld,
95
+ GEMMAndBiasActivationEpilogue activation = GEMMAndBiasActivationEpilogue::None);
96
+ #endif
97
+
98
+ #define CUDABLAS_BGEMM_ARGTYPES(Dtype) \
99
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
100
+ const Dtype *a, int64_t lda, int64_t stridea, \
101
+ const Dtype *b, int64_t ldb, int64_t strideb, \
102
+ at::opmath_type<Dtype> beta, Dtype *c, int64_t ldc, int64_t stridec, int64_t num_batches
103
+
104
+ template <typename Dtype>
105
+ inline void bgemm(CUDABLAS_BGEMM_ARGTYPES(Dtype)) {
106
+ AT_ERROR("at::cuda::blas::bgemm: not implemented for ", typeid(Dtype).name());
107
+ }
108
+
109
+ template <>
110
+ void bgemm<double>(CUDABLAS_BGEMM_ARGTYPES(double));
111
+ template <>
112
+ void bgemm<float>(CUDABLAS_BGEMM_ARGTYPES(float));
113
+ template <>
114
+ void bgemm<c10::complex<double>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<double>));
115
+ template <>
116
+ void bgemm<c10::complex<float>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<float>));
117
+ template <>
118
+ void bgemm<at::Half>(CUDABLAS_BGEMM_ARGTYPES(at::Half));
119
+ template <>
120
+ void bgemm<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
121
+
122
+ #define CUDABLAS_TRSM_ARGTYPES(Dtype) \
123
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
124
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
125
+ const Dtype *alpha, const Dtype *A, int lda, Dtype *B, int ldb
126
+
127
+ template <typename Dtype>
128
+ inline void trsm(CUDABLAS_TRSM_ARGTYPES(Dtype)) {
129
+ TORCH_INTERNAL_ASSERT(false, "at::cuda::blas::trsm: not implemented for ", typeid(Dtype).name());
130
+ }
131
+
132
+ template <>
133
+ TORCH_CUDA_CU_API void trsm<float>(CUDABLAS_TRSM_ARGTYPES(float));
134
+ template <>
135
+ TORCH_CUDA_CU_API void trsm<double>(CUDABLAS_TRSM_ARGTYPES(double));
136
+ template <>
137
+ TORCH_CUDA_CU_API void trsm<c10::complex<float>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<float>));
138
+ template <>
139
+ TORCH_CUDA_CU_API void trsm<c10::complex<double>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<double>));
140
+
141
+ #define CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype) \
142
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
143
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
144
+ const Dtype *alpha, Dtype *A[], int lda, Dtype *B[], int ldb, \
145
+ int batchCount
146
+
147
+ template <typename Dtype>
148
+ inline void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype)) {
149
+ TORCH_INTERNAL_ASSERT(
150
+ false,
151
+ "at::cuda::blas::trsmBatched: not implemented for ",
152
+ typeid(Dtype).name());
153
+ }
154
+
155
+ template <>
156
+ TORCH_CUDA_CU_API void trsmBatched<float>(CUDABLAS_TRSM_BATCHED_ARGTYPES(float));
157
+ template <>
158
+ TORCH_CUDA_CU_API void trsmBatched<double>(CUDABLAS_TRSM_BATCHED_ARGTYPES(double));
159
+ template <>
160
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<float>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<float>));
161
+ template <>
162
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<double>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<double>));
163
+
164
+ /* LEVEL 2 BLAS FUNCTIONS */
165
+
166
+ #define CUDABLAS_GEMV_ARGTYPES(Dtype) \
167
+ char trans, int64_t m, int64_t n, Dtype alpha, const Dtype *a, int64_t lda, \
168
+ const Dtype *x, int64_t incx, Dtype beta, Dtype *y, int64_t incy
169
+
170
+ template <typename Dtype>
171
+ inline void gemv(CUDABLAS_GEMV_ARGTYPES(Dtype)) {
172
+ AT_ERROR("at::cuda::blas::gemv: not implemented for ", typeid(Dtype).name());
173
+ }
174
+
175
+ template <>
176
+ void gemv<double>(CUDABLAS_GEMV_ARGTYPES(double));
177
+ template <>
178
+ void gemv<float>(CUDABLAS_GEMV_ARGTYPES(float));
179
+ #if !defined(USE_ROCM) || (defined(USE_ROCM) && ROCM_VERSION >= 21000)
180
+ template <>
181
+ void gemv<c10::complex<double>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<double>));
182
+ template <>
183
+ void gemv<c10::complex<float>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<float>));
184
+ #endif
185
+ template <>
186
+ void gemv<at::Half>(CUDABLAS_GEMV_ARGTYPES(at::Half));
187
+ template <>
188
+ void gemv<at::BFloat16>(CUDABLAS_GEMV_ARGTYPES(at::BFloat16));
189
+
190
+ /* LEVEL 1 BLAS FUNCTIONS */
191
+
192
+ #define CUDABLAS_DOT_ARGTYPES(Dtype) \
193
+ cublasHandle_t handle, int n, const Dtype *x, int incx, const Dtype *y, \
194
+ int incy, Dtype *result
195
+
196
+ template <typename Dtype>
197
+ inline void dot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
198
+ AT_ERROR("at::cuda::blas::dot: not implemented for ", typeid(Dtype).name());
199
+ }
200
+
201
+ template <>
202
+ void dot<double>(CUDABLAS_DOT_ARGTYPES(double));
203
+ template <>
204
+ void dot<float>(CUDABLAS_DOT_ARGTYPES(float));
205
+ template <>
206
+ void dot<at::Half>(CUDABLAS_DOT_ARGTYPES(at::Half));
207
+ template <>
208
+ void dot<at::BFloat16>(CUDABLAS_DOT_ARGTYPES(at::BFloat16));
209
+ template <>
210
+ void dot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
211
+ template <>
212
+ void dot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
213
+
214
+ template <typename Dtype>
215
+ inline void vdot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
216
+ AT_ERROR("at::cuda::blas::vdot: not implemented for ", typeid(Dtype).name());
217
+ }
218
+
219
+ template <>
220
+ void vdot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
221
+ template <>
222
+ void vdot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
223
+
224
+ // This guards blocks use of getrsBatched, geqrfBatched, getrfBatched on platforms other than cuda
225
+ #ifdef CUDART_VERSION
226
+
227
+ #define CUDABLAS_GETRS_ARGTYPES(Dtype) \
228
+ cublasHandle_t handle, cublasOperation_t trans, \
229
+ int n, int nrhs, Dtype** dA_array, int lda, int* ipiv_array, \
230
+ Dtype** dB_array, int ldb, int* info_array, int batchsize
231
+
232
+ template<class Dtype>
233
+ void getrsBatched(CUDABLAS_GETRS_ARGTYPES(Dtype)) {
234
+ TORCH_INTERNAL_ASSERT(false, "at::cuda::blas::getrsBatched: not implemented for ",
235
+ typeid(Dtype).name());
236
+ }
237
+ template<>
238
+ TORCH_CUDA_CU_API void getrsBatched<float>(CUDABLAS_GETRS_ARGTYPES(float));
239
+ template<>
240
+ TORCH_CUDA_CU_API void getrsBatched<double>(CUDABLAS_GETRS_ARGTYPES(double));
241
+ template<>
242
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<float>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<float>));
243
+ template<>
244
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<double>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<double>));
245
+
246
+ #define CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype) \
247
+ cublasHandle_t handle, int m, int n, Dtype **A_array, int lda, \
248
+ Dtype **tau_array, int *info, int batchsize
249
+
250
+ template <class Dtype>
251
+ void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype)) {
252
+ TORCH_INTERNAL_ASSERT(
253
+ false,
254
+ "at::cuda::blas::geqrfBatched: not implemented for ",
255
+ typeid(Dtype).name());
256
+ }
257
+ template <>
258
+ TORCH_CUDA_CU_API void geqrfBatched<float>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(float));
259
+ template <>
260
+ TORCH_CUDA_CU_API void geqrfBatched<double>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(double));
261
+ template <>
262
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<double>>(
263
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<double>));
264
+ template <>
265
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<float>>(
266
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<float>));
267
+
268
+ #define CUDABLAS_GETRF_ARGTYPES(Dtype) \
269
+ int n, Dtype** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize
270
+
271
+ template<class Dtype>
272
+ void getrfBatched(CUDABLAS_GETRF_ARGTYPES(Dtype)) {
273
+ TORCH_CHECK(false, "at::cuda::blas::getrfBatched: not implemented for ", typeid(Dtype).name());
274
+ }
275
+ template<>
276
+ TORCH_CUDA_CU_API void getrfBatched<float>(CUDABLAS_GETRF_ARGTYPES(float));
277
+ template<>
278
+ TORCH_CUDA_CU_API void getrfBatched<double>(CUDABLAS_GETRF_ARGTYPES(double));
279
+ template<>
280
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<double>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<double>));
281
+ template<>
282
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<float>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<float>));
283
+
284
+ #define CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype) \
285
+ cublasHandle_t handle, cublasOperation_t trans, int m, int n, int nrhs, Dtype** dA_array, int ldda, Dtype** dC_array, int lddc, int* info, int *devInfoArray, int batchSize
286
+
287
+ template <class Dtype>
288
+ void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype)) {
289
+ TORCH_INTERNAL_ASSERT(false, "at::cuda::blas::gelsBatched: not implemented for ", typeid(Dtype).name());
290
+ }
291
+
292
+ template<>
293
+ TORCH_CUDA_CU_API void gelsBatched<double>(CUDABLAS_GELS_BATCHED_ARGTYPES(double));
294
+ template<>
295
+ TORCH_CUDA_CU_API void gelsBatched<float>(CUDABLAS_GELS_BATCHED_ARGTYPES(float));
296
+ template<>
297
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<double>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<double>));
298
+ template<>
299
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<float>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<float>));
300
+
301
+ #endif // CUDART_VERSION
302
+
303
+ } // namespace blas
304
+ } // namespace cuda
305
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Generator.h>
4
+ #include <ATen/cuda/detail/PhiloxCudaStateRaw.cuh>
5
+ #include <ATen/Context.h>
6
+ #include <limits>
7
+ #include <atomic>
8
+
9
+ namespace at {
10
+ /**
11
+ * Note [CUDA Graph-safe RNG states]
12
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13
+ *
14
+ * Strategy:
15
+ * ~~~~~~~~~
16
+ * (It helps to look at
17
+ * cuda/detail/PhiloxCudaStateRaw.cuh and
18
+ * cuda/detail/UnpackRaw.cuh
19
+ * while you read this.)
20
+ *
21
+ * A CUDA graph containing multiple RNG ops behaves like a
22
+ * single giant kernel from the perspective of ops external
23
+ * to the graph. During graph capture, logic in CUDAGeneratorImpl
24
+ * records the total of all offset increments that occur in the
25
+ * graphed region, and records the final total as the offset for
26
+ * the entire graph.
27
+ *
28
+ * When the graph reruns, the logic that reruns it
29
+ * increments this device's CUDA generator's offset
30
+ * by that total.
31
+ *
32
+ * Meanwhile, within the graph, at capture time, instead of
33
+ * populating PhiloxCudaStates with the uint64_t offset pulled
34
+ * directly from the global state, PhiloxCudaState uses a pointer
35
+ * to a one-element stream-local int64_t device tensor
36
+ * holding an initial offset value, and a uint64_t holding an
37
+ * intra-graph offset. (The intra-graph offset starts from zero
38
+ * when capture begins.) In each consumer kernel,
39
+ * at::cuda::philox::unpack computes the offset to use for this kernel
40
+ * as intra-graph offset + *initial offset.
41
+ *
42
+ * When the graph reruns, the logic that reruns it first
43
+ * fill_s the initial offset tensor with this device's
44
+ * CUDA generator's current offset.
45
+ *
46
+ * The control flow above ensures graphed execution is bitwise
47
+ * identical to eager execution as long as RNG ops are enqueued
48
+ * from a single thread, even if RNG ops and graphs containing
49
+ * RNG ops are enqueued and run simultaneously on multiple streams.
50
+ *
51
+ * Usage:
52
+ * ~~~~~~
53
+ * PhiloxCudaState in this file, and unpack() in
54
+ * cuda/CUDAGraphsUtils.cuh allow non-divergent use of
55
+ * CUDAGeneratorImpl whether graph capture is underway or not.
56
+ *
57
+ * Each PhiloxCudaState instance should be used for one and only one
58
+ * consumer kernel.
59
+ *
60
+ * Example (see e.g. native/cuda/Dropout.cu):
61
+ *
62
+ * #include <ATen/cuda/CUDAGeneratorImpl.h>
63
+ * #include <ATen/cuda/CUDAGraphsUtils.cuh>
64
+ *
65
+ * __global__ void kernel(..., PhiloxCudaState philox_args) {
66
+ * auto seeds = at::cuda::philox::unpack(philox_args);
67
+ * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x;
68
+ * curandStatePhilox4_32_10_t state;
69
+ * curand_init(std::get<0>(seeds), // seed
70
+ * idx, // per-thread subsequence
71
+ * std::get<1>(seeds), // offset in subsequence
72
+ * &state);
73
+ * ...
74
+ * }
75
+ *
76
+ * host_caller(...) {
77
+ * PhiloxCudaState rng_engine_inputs;
78
+ * {
79
+ * // See Note [Acquire lock when using random generators]
80
+ * std::lock_guard<std::mutex> lock(gen->mutex_);
81
+ *
82
+ * // gen could be HostState or DevState here! No divergent code needed!
83
+ * rng_engine_inputs = gen->philox_cuda_state(offset_increment);
84
+ * }
85
+ * kernel<<<...>>>(..., rng_engine_inputs);
86
+ * }
87
+ *
88
+ */
89
+
90
+ struct TORCH_CUDA_CPP_API CUDAGeneratorImpl : public c10::GeneratorImpl {
91
+ // Constructors
92
+ CUDAGeneratorImpl(DeviceIndex device_index = -1);
93
+ ~CUDAGeneratorImpl() override = default;
94
+
95
+ // CUDAGeneratorImpl methods
96
+ std::shared_ptr<CUDAGeneratorImpl> clone() const;
97
+ void set_current_seed(uint64_t seed) override;
98
+ uint64_t current_seed() const override;
99
+ uint64_t seed() override;
100
+ void set_state(const c10::TensorImpl& new_state) override;
101
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
102
+ void set_philox_offset_per_thread(uint64_t offset);
103
+ uint64_t philox_offset_per_thread() const;
104
+ void capture_prologue(int64_t* seed_extragraph, int64_t* offset_extragraph);
105
+ uint64_t capture_epilogue();
106
+ PhiloxCudaState philox_cuda_state(uint64_t increment);
107
+
108
+ bool reset_rnn_state() {
109
+ return !no_reset_rnn_state_.test_and_set();
110
+ }
111
+
112
+ // Temporarily accommodates call sites that use philox_engine_inputs.
113
+ // Allows incremental refactor of call sites to use philox_cuda_state.
114
+ std::pair<uint64_t, uint64_t> philox_engine_inputs(uint64_t increment);
115
+
116
+ static DeviceType device_type();
117
+
118
+ private:
119
+ CUDAGeneratorImpl* clone_impl() const override;
120
+ uint64_t seed_ = default_rng_seed_val;
121
+ uint64_t philox_offset_per_thread_ = 0;
122
+ int64_t* seed_extragraph_{};
123
+ int64_t* offset_extragraph_{};
124
+ uint32_t offset_intragraph_ = 0;
125
+ bool graph_expects_this_gen_ = false;
126
+ std::atomic_flag no_reset_rnn_state_;
127
+ };
128
+
129
+ namespace cuda {
130
+ namespace detail {
131
+
132
+ TORCH_CUDA_CPP_API const Generator& getDefaultCUDAGenerator(
133
+ DeviceIndex device_index = -1);
134
+ TORCH_CUDA_CPP_API Generator createCUDAGenerator(DeviceIndex device_index = -1);
135
+
136
+ } // namespace detail
137
+ } // namespace cuda
138
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraph.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/core/Device.h>
5
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
6
+ #include <c10/cuda/CUDAStream.h>
7
+
8
+ namespace at {
9
+
10
+ struct CUDAGeneratorImpl;
11
+
12
+ namespace cuda {
13
+
14
+ // Standalone way to get a unique mempool id usable as a pool=... argument
15
+ // to CUDAGraph::capture_begin
16
+ TORCH_CUDA_CPP_API MempoolId_t graph_pool_handle();
17
+
18
+ struct TORCH_CUDA_CPP_API CUDAGraph {
19
+ CUDAGraph();
20
+ ~CUDAGraph();
21
+
22
+ void capture_begin(MempoolId_t pool={0, 0});
23
+ void capture_end();
24
+ void replay();
25
+ void reset();
26
+ MempoolId_t pool();
27
+ void enable_debug_mode();
28
+ void debug_dump(const std::string& debug_path);
29
+
30
+ protected:
31
+ #if !defined(USE_ROCM) || ROCM_VERSION >= 50300
32
+ cudaGraph_t graph_ = NULL;
33
+ cudaGraphExec_t graph_exec_ = NULL;
34
+ #endif
35
+
36
+ // internal states so reset() can do its best cleaning up
37
+ // Set to true in capture_end if cudaStreamEndCapture succeeded
38
+ // Set back to false soon after, when graph_ is consumed by cudaGraphInstantiate
39
+ // to create graph_exec_, then graph_ is deleted
40
+ bool has_graph_ = false;
41
+ // Set to true in capture_end if cudaGraphInstantiate succeeded
42
+ bool has_graph_exec_ = false;
43
+
44
+ // uuid of this instance's current capture, retrieved from Cuda
45
+ CaptureId_t id_;
46
+
47
+ // uuid used to request a particular private mempool from CUDACachingAllocator.
48
+ // By default, this will be set to {id_, 0}.
49
+ //
50
+ // If capture_begin is called with "pool=other_graph.pool()", this graph's mempool_id_
51
+ // will be set to the other graph's mempool_id_, and therefore share a mempool with the
52
+ // other graph.
53
+ //
54
+ // If capture_begin is called with "pool=handle" where "handle" came from graph_pool_handle(),
55
+ // it will share a mempool with any other captures that used "pool=handle".
56
+ //
57
+ // Sharing a mempool across graphs saves memory, and it's safe if you
58
+ // know you'll replay those graphs in the same order you captured them.
59
+ MempoolId_t mempool_id_;
60
+
61
+ // Stream on which capture began
62
+ at::cuda::CUDAStream capture_stream_;
63
+
64
+ // Default generator on device where capture began
65
+ at::CUDAGeneratorImpl* capture_gen_;
66
+
67
+ // Device where capture occurred. Right now, for simplicity, we require all ops
68
+ // in a capture to run on the same device, but this is a limitation of CUDAGraph,
69
+ // not CUDA itself. We can straightforwardly modify CUDAGraph to support multi-device
70
+ // captures if needed.
71
+ int capture_dev_;
72
+
73
+ // RNG state trackers
74
+ at::Tensor seed_extragraph_;
75
+ at::Tensor offset_extragraph_;
76
+ uint64_t wholegraph_increment_;
77
+ };
78
+
79
+ } // namespace cuda
80
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAGeneratorImpl.h>
4
+ #include <ATen/cuda/CUDAEvent.h>
5
+ #include <ATen/cuda/detail/UnpackRaw.cuh>
6
+ #include <ATen/cuda/detail/CUDAHooks.h>
7
+ #include <ATen/detail/CUDAHooksInterface.h>
8
+ #include <c10/core/StreamGuard.h>
9
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
10
+ #include <c10/cuda/CUDAGuard.h>
11
+
12
+ // c10/cuda/CUDAGraphsC10Utils.h has utils used by both c10 and aten.
13
+ // This file adds utils used by aten only.
14
+
15
+ namespace at {
16
+ namespace cuda {
17
+
18
+ using CaptureId_t = c10::cuda::CaptureId_t;
19
+ using CaptureStatus = c10::cuda::CaptureStatus;
20
+
21
+ // Use this version where you don't want to create a CUDA context if none exists.
22
+ inline CaptureStatus currentStreamCaptureStatus() {
23
+ #if !defined(USE_ROCM) || ROCM_VERSION >= 50300
24
+ // don't create a context if we don't have to
25
+ if (at::cuda::detail::hasPrimaryContext(c10::cuda::current_device())) {
26
+ return c10::cuda::currentStreamCaptureStatusMayInitCtx();
27
+ } else {
28
+ return CaptureStatus::None;
29
+ }
30
+ #else
31
+ return CaptureStatus::None;
32
+ #endif
33
+ }
34
+
35
+ inline void assertNotCapturing(std::string attempt) {
36
+ auto status = currentStreamCaptureStatus();
37
+ TORCH_CHECK(status == CaptureStatus::None,
38
+ attempt,
39
+ " during CUDA graph capture. If you need this call to be captured, "
40
+ "please file an issue. "
41
+ "Current cudaStreamCaptureStatus: ",
42
+ status);
43
+ }
44
+
45
+ inline void errorIfCapturingCudnnBenchmark(std::string version_specific) {
46
+ auto status = currentStreamCaptureStatus();
47
+ TORCH_CHECK(status == CaptureStatus::None,
48
+ "Current cudaStreamCaptureStatus: ",
49
+ status,
50
+ "\nCapturing ",
51
+ version_specific,
52
+ "is prohibited. Possible causes of this error:\n"
53
+ "1. No warmup iterations occurred before capture.\n"
54
+ "2. The convolutions you're trying to capture use dynamic shapes, "
55
+ "in which case capturing them is generally prohibited.");
56
+ }
57
+
58
+ } // namespace cuda
59
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/cuda/CUDASparse.h>
6
+
7
+ #include <c10/core/ScalarType.h>
8
+
9
+ #if defined(USE_ROCM)
10
+ #include <type_traits>
11
+ #endif
12
+
13
+ namespace at {
14
+ namespace cuda {
15
+ namespace sparse {
16
+
17
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
18
+ struct CuSparseDescriptorDeleter {
19
+ void operator()(T* x) {
20
+ if (x != nullptr) {
21
+ TORCH_CUDASPARSE_CHECK(destructor(x));
22
+ }
23
+ }
24
+ };
25
+
26
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
27
+ class CuSparseDescriptor {
28
+ public:
29
+ T* descriptor() const {
30
+ return descriptor_.get();
31
+ }
32
+ T* descriptor() {
33
+ return descriptor_.get();
34
+ }
35
+
36
+ protected:
37
+ std::unique_ptr<T, CuSparseDescriptorDeleter<T, destructor>> descriptor_;
38
+ };
39
+
40
+ #if AT_USE_CUSPARSE_CONST_DESCRIPTORS()
41
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
42
+ struct ConstCuSparseDescriptorDeleter {
43
+ void operator()(T* x) {
44
+ if (x != nullptr) {
45
+ TORCH_CUDASPARSE_CHECK(destructor(x));
46
+ }
47
+ }
48
+ };
49
+
50
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
51
+ class ConstCuSparseDescriptor {
52
+ public:
53
+ T* descriptor() const {
54
+ return descriptor_.get();
55
+ }
56
+ T* descriptor() {
57
+ return descriptor_.get();
58
+ }
59
+
60
+ protected:
61
+ std::unique_ptr<T, ConstCuSparseDescriptorDeleter<T, destructor>> descriptor_;
62
+ };
63
+ #endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS
64
+
65
+ #if defined(USE_ROCM)
66
+ // hipSPARSE doesn't define this
67
+ using cusparseMatDescr = std::remove_pointer<cusparseMatDescr_t>::type;
68
+ using cusparseDnMatDescr = std::remove_pointer<cusparseDnMatDescr_t>::type;
69
+ using cusparseDnVecDescr = std::remove_pointer<cusparseDnVecDescr_t>::type;
70
+ using cusparseSpMatDescr = std::remove_pointer<cusparseSpMatDescr_t>::type;
71
+ using cusparseSpMatDescr = std::remove_pointer<cusparseSpMatDescr_t>::type;
72
+ using cusparseSpGEMMDescr = std::remove_pointer<cusparseSpGEMMDescr_t>::type;
73
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
74
+ using bsrsv2Info = std::remove_pointer<bsrsv2Info_t>::type;
75
+ using bsrsm2Info = std::remove_pointer<bsrsm2Info_t>::type;
76
+ #endif
77
+ #endif
78
+
79
+ class TORCH_CUDA_CPP_API CuSparseMatDescriptor
80
+ : public CuSparseDescriptor<cusparseMatDescr, &cusparseDestroyMatDescr> {
81
+ public:
82
+ CuSparseMatDescriptor() {
83
+ cusparseMatDescr_t raw_descriptor;
84
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
85
+ descriptor_.reset(raw_descriptor);
86
+ }
87
+
88
+ CuSparseMatDescriptor(bool upper, bool unit) {
89
+ cusparseFillMode_t fill_mode =
90
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
91
+ cusparseDiagType_t diag_type =
92
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
93
+ cusparseMatDescr_t raw_descriptor;
94
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
95
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatFillMode(raw_descriptor, fill_mode));
96
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatDiagType(raw_descriptor, diag_type));
97
+ descriptor_.reset(raw_descriptor);
98
+ }
99
+ };
100
+
101
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
102
+
103
+ class TORCH_CUDA_CPP_API CuSparseBsrsv2Info
104
+ : public CuSparseDescriptor<bsrsv2Info, &cusparseDestroyBsrsv2Info> {
105
+ public:
106
+ CuSparseBsrsv2Info() {
107
+ bsrsv2Info_t raw_descriptor;
108
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsv2Info(&raw_descriptor));
109
+ descriptor_.reset(raw_descriptor);
110
+ }
111
+ };
112
+
113
+ class TORCH_CUDA_CPP_API CuSparseBsrsm2Info
114
+ : public CuSparseDescriptor<bsrsm2Info, &cusparseDestroyBsrsm2Info> {
115
+ public:
116
+ CuSparseBsrsm2Info() {
117
+ bsrsm2Info_t raw_descriptor;
118
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsm2Info(&raw_descriptor));
119
+ descriptor_.reset(raw_descriptor);
120
+ }
121
+ };
122
+
123
+ #endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE
124
+
125
+ #if AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API()
126
+
127
+ cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type);
128
+
129
+ #if AT_USE_HIPSPARSE_GENERIC_52_API() || \
130
+ (AT_USE_CUSPARSE_GENERIC_API() && AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS())
131
+ class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor
132
+ : public CuSparseDescriptor<cusparseDnMatDescr, &cusparseDestroyDnMat> {
133
+ public:
134
+ explicit CuSparseDnMatDescriptor(const Tensor& input, int64_t batch_offset = -1);
135
+ };
136
+
137
+ class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor
138
+ : public CuSparseDescriptor<cusparseDnVecDescr, &cusparseDestroyDnVec> {
139
+ public:
140
+ explicit CuSparseDnVecDescriptor(const Tensor& input);
141
+ };
142
+
143
+ class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor
144
+ : public CuSparseDescriptor<cusparseSpMatDescr, &cusparseDestroySpMat> {};
145
+
146
+ //AT_USE_HIPSPARSE_GENERIC_52_API() || (AT_USE_CUSPARSE_GENERIC_API() && AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS())
147
+
148
+ #elif AT_USE_CUSPARSE_CONST_DESCRIPTORS()
149
+ class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor
150
+ : public ConstCuSparseDescriptor<
151
+ cusparseDnMatDescr,
152
+ &cusparseDestroyDnMat> {
153
+ public:
154
+ explicit CuSparseDnMatDescriptor(
155
+ const Tensor& input,
156
+ int64_t batch_offset = -1);
157
+ };
158
+
159
+ class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor
160
+ : public ConstCuSparseDescriptor<
161
+ cusparseDnVecDescr,
162
+ &cusparseDestroyDnVec> {
163
+ public:
164
+ explicit CuSparseDnVecDescriptor(const Tensor& input);
165
+ };
166
+
167
+ class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor
168
+ : public ConstCuSparseDescriptor<
169
+ cusparseSpMatDescr,
170
+ &cusparseDestroySpMat> {};
171
+ #endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS()
172
+
173
+ class TORCH_CUDA_CPP_API CuSparseSpMatCsrDescriptor
174
+ : public CuSparseSpMatDescriptor {
175
+ public:
176
+ explicit CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset = -1);
177
+
178
+ std::tuple<int64_t, int64_t, int64_t> get_size() {
179
+ int64_t rows, cols, nnz;
180
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatGetSize(
181
+ this->descriptor(),
182
+ &rows,
183
+ &cols,
184
+ &nnz));
185
+ return std::make_tuple(rows, cols, nnz);
186
+ }
187
+
188
+ void set_tensor(const Tensor& input) {
189
+ auto crow_indices = input.crow_indices();
190
+ auto col_indices = input.col_indices();
191
+ auto values = input.values();
192
+
193
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous());
194
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous());
195
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous());
196
+ TORCH_CUDASPARSE_CHECK(cusparseCsrSetPointers(
197
+ this->descriptor(),
198
+ crow_indices.data_ptr(),
199
+ col_indices.data_ptr(),
200
+ values.data_ptr()));
201
+ }
202
+
203
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
204
+ void set_mat_fill_mode(bool upper) {
205
+ cusparseFillMode_t fill_mode =
206
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
207
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
208
+ this->descriptor(),
209
+ CUSPARSE_SPMAT_FILL_MODE,
210
+ &fill_mode,
211
+ sizeof(fill_mode)));
212
+ }
213
+
214
+ void set_mat_diag_type(bool unit) {
215
+ cusparseDiagType_t diag_type =
216
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
217
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
218
+ this->descriptor(),
219
+ CUSPARSE_SPMAT_DIAG_TYPE,
220
+ &diag_type,
221
+ sizeof(diag_type)));
222
+ }
223
+ #endif
224
+ };
225
+
226
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
227
+ class TORCH_CUDA_CPP_API CuSparseSpSVDescriptor
228
+ : public CuSparseDescriptor<cusparseSpSVDescr, &cusparseSpSV_destroyDescr> {
229
+ public:
230
+ CuSparseSpSVDescriptor() {
231
+ cusparseSpSVDescr_t raw_descriptor;
232
+ TORCH_CUDASPARSE_CHECK(cusparseSpSV_createDescr(&raw_descriptor));
233
+ descriptor_.reset(raw_descriptor);
234
+ }
235
+ };
236
+ #endif
237
+
238
+ #if AT_USE_CUSPARSE_GENERIC_SPSM()
239
+ class TORCH_CUDA_CPP_API CuSparseSpSMDescriptor
240
+ : public CuSparseDescriptor<cusparseSpSMDescr, &cusparseSpSM_destroyDescr> {
241
+ public:
242
+ CuSparseSpSMDescriptor() {
243
+ cusparseSpSMDescr_t raw_descriptor;
244
+ TORCH_CUDASPARSE_CHECK(cusparseSpSM_createDescr(&raw_descriptor));
245
+ descriptor_.reset(raw_descriptor);
246
+ }
247
+ };
248
+ #endif
249
+
250
+ #if (defined(USE_ROCM) && ROCM_VERSION >= 50200) || !defined(USE_ROCM)
251
+ class TORCH_CUDA_CPP_API CuSparseSpGEMMDescriptor
252
+ : public CuSparseDescriptor<cusparseSpGEMMDescr, &cusparseSpGEMM_destroyDescr> {
253
+ public:
254
+ CuSparseSpGEMMDescriptor() {
255
+ cusparseSpGEMMDescr_t raw_descriptor;
256
+ TORCH_CUDASPARSE_CHECK(cusparseSpGEMM_createDescr(&raw_descriptor));
257
+ descriptor_.reset(raw_descriptor);
258
+ }
259
+ };
260
+ #endif
261
+
262
+ #endif // AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API()
263
+
264
+ } // namespace sparse
265
+ } // namespace cuda
266
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/util/Half.h>
5
+
6
+ #include <cuda.h>
7
+ #include <cuda_runtime.h>
8
+ #include <cuda_fp16.h>
9
+
10
+ namespace at {
11
+ template <>
12
+ inline __half* Tensor::data() const {
13
+ return reinterpret_cast<__half*>(data<Half>());
14
+ }
15
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/CUDAUtils.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAContext.h>
4
+
5
+ namespace at { namespace cuda {
6
+
7
+ // Check if every tensor in a list of tensors matches the current
8
+ // device.
9
+ inline bool check_device(ArrayRef<Tensor> ts) {
10
+ if (ts.empty()) {
11
+ return true;
12
+ }
13
+ Device curDevice = Device(kCUDA, current_device());
14
+ for (const Tensor& t : ts) {
15
+ if (t.device() != curDevice) return false;
16
+ }
17
+ return true;
18
+ }
19
+
20
+ }} // namespace at::cuda
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <c10/util/complex.h>
5
+ #include <c10/util/Half.h>
6
+
7
+ __device__ __forceinline__ unsigned int ACTIVE_MASK()
8
+ {
9
+ #if !defined(USE_ROCM)
10
+ return __activemask();
11
+ #else
12
+ // will be ignored anyway
13
+ return 0xffffffff;
14
+ #endif
15
+ }
16
+
17
+ #if defined(USE_ROCM)
18
+ __device__ __forceinline__ unsigned long long int WARP_BALLOT(int predicate)
19
+ {
20
+ return __ballot(predicate);
21
+ }
22
+ #else
23
+ __device__ __forceinline__ unsigned int WARP_BALLOT(int predicate, unsigned int mask = 0xffffffff)
24
+ {
25
+ #if !defined(USE_ROCM)
26
+ return __ballot_sync(mask, predicate);
27
+ #else
28
+ return __ballot(predicate);
29
+ #endif
30
+ }
31
+ #endif
32
+
33
+ template <typename T>
34
+ __device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff)
35
+ {
36
+ #if !defined(USE_ROCM)
37
+ return __shfl_xor_sync(mask, value, laneMask, width);
38
+ #else
39
+ return __shfl_xor(value, laneMask, width);
40
+ #endif
41
+ }
42
+
43
+ template <typename T>
44
+ __device__ __forceinline__ T WARP_SHFL(T value, int srcLane, int width = warpSize, unsigned int mask = 0xffffffff)
45
+ {
46
+ #if !defined(USE_ROCM)
47
+ return __shfl_sync(mask, value, srcLane, width);
48
+ #else
49
+ return __shfl(value, srcLane, width);
50
+ #endif
51
+ }
52
+
53
+ template <typename T>
54
+ __device__ __forceinline__ T WARP_SHFL_UP(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
55
+ {
56
+ #if !defined(USE_ROCM)
57
+ return __shfl_up_sync(mask, value, delta, width);
58
+ #else
59
+ return __shfl_up(value, delta, width);
60
+ #endif
61
+ }
62
+
63
+ template <typename T>
64
+ __device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
65
+ {
66
+ #if !defined(USE_ROCM)
67
+ return __shfl_down_sync(mask, value, delta, width);
68
+ #else
69
+ return __shfl_down(value, delta, width);
70
+ #endif
71
+ }
72
+
73
+ #if defined(USE_ROCM)
74
+ template<>
75
+ __device__ __forceinline__ int64_t WARP_SHFL_DOWN<int64_t>(int64_t value, unsigned int delta, int width , unsigned int mask)
76
+ {
77
+ //(HIP doesn't support int64_t). Trick from https://devblogs.nvidia.com/faster-parallel-reductions-kepler/
78
+ int2 a = *reinterpret_cast<int2*>(&value);
79
+ a.x = __shfl_down(a.x, delta);
80
+ a.y = __shfl_down(a.y, delta);
81
+ return *reinterpret_cast<int64_t*>(&a);
82
+ }
83
+ #endif
84
+
85
+ template<>
86
+ __device__ __forceinline__ c10::Half WARP_SHFL_DOWN<c10::Half>(c10::Half value, unsigned int delta, int width, unsigned int mask)
87
+ {
88
+ return c10::Half(WARP_SHFL_DOWN<unsigned short>(value.x, delta, width, mask), c10::Half::from_bits_t{});
89
+ }
90
+
91
+ template <typename T>
92
+ __device__ __forceinline__ c10::complex<T> WARP_SHFL_DOWN(c10::complex<T> value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
93
+ {
94
+ #if !defined(USE_ROCM)
95
+ return c10::complex<T>(
96
+ __shfl_down_sync(mask, value.real_, delta, width),
97
+ __shfl_down_sync(mask, value.imag_, delta, width));
98
+ #else
99
+ return c10::complex<T>(
100
+ __shfl_down(value.real_, delta, width),
101
+ __shfl_down(value.imag_, delta, width));
102
+ #endif
103
+ }
104
+
105
+ /**
106
+ * For CC 3.5+, perform a load using __ldg
107
+ */
108
+ template <typename T>
109
+ __device__ __forceinline__ T doLdg(const T* p) {
110
+ #if __CUDA_ARCH__ >= 350 && !defined(USE_ROCM)
111
+ return __ldg(p);
112
+ #else
113
+ return *p;
114
+ #endif
115
+ }
wemm/lib/python3.10/site-packages/torch/include/ATen/cuda/NumericLimits.cuh ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <limits.h>
5
+ #include <math.h>
6
+ #include <float.h>
7
+
8
+ // NumericLimits.cuh is a holder for numeric limits definitions of commonly used
9
+ // types. This header is very specific to ROCm HIP and may be removed in the future.
10
+ // This header is derived from the legacy THCNumerics.cuh.
11
+
12
+ // The lower_bound and upper_bound constants are same as lowest and max for
13
+ // integral types, but are -inf and +inf for floating point types. They are
14
+ // useful in implementing min, max, etc.
15
+
16
+ namespace at {
17
+
18
+ template <typename T>
19
+ struct numeric_limits {
20
+ };
21
+
22
+ // WARNING: the following at::numeric_limits definitions are there only to support
23
+ // HIP compilation for the moment. Use std::numeric_limits if you are not
24
+ // compiling for ROCm.
25
+ // from @colesbury: "The functions on numeric_limits aren't marked with
26
+ // __device__ which is why they don't work with ROCm. CUDA allows them
27
+ // because they're constexpr."
28
+
29
+ namespace {
30
+ // ROCm doesn't like INFINITY too.
31
+ constexpr double inf = INFINITY;
32
+ }
33
+
34
+ template <>
35
+ struct numeric_limits<bool> {
36
+ static inline __host__ __device__ bool lowest() { return false; }
37
+ static inline __host__ __device__ bool max() { return true; }
38
+ static inline __host__ __device__ bool lower_bound() { return false; }
39
+ static inline __host__ __device__ bool upper_bound() { return true; }
40
+ };
41
+
42
+ template <>
43
+ struct numeric_limits<uint8_t> {
44
+ static inline __host__ __device__ uint8_t lowest() { return 0; }
45
+ static inline __host__ __device__ uint8_t max() { return UINT8_MAX; }
46
+ static inline __host__ __device__ uint8_t lower_bound() { return 0; }
47
+ static inline __host__ __device__ uint8_t upper_bound() { return UINT8_MAX; }
48
+ };
49
+
50
+ template <>
51
+ struct numeric_limits<int8_t> {
52
+ static inline __host__ __device__ int8_t lowest() { return INT8_MIN; }
53
+ static inline __host__ __device__ int8_t max() { return INT8_MAX; }
54
+ static inline __host__ __device__ int8_t lower_bound() { return INT8_MIN; }
55
+ static inline __host__ __device__ int8_t upper_bound() { return INT8_MAX; }
56
+ };
57
+
58
+ template <>
59
+ struct numeric_limits<int16_t> {
60
+ static inline __host__ __device__ int16_t lowest() { return INT16_MIN; }
61
+ static inline __host__ __device__ int16_t max() { return INT16_MAX; }
62
+ static inline __host__ __device__ int16_t lower_bound() { return INT16_MIN; }
63
+ static inline __host__ __device__ int16_t upper_bound() { return INT16_MAX; }
64
+ };
65
+
66
+ template <>
67
+ struct numeric_limits<int32_t> {
68
+ static inline __host__ __device__ int32_t lowest() { return INT32_MIN; }
69
+ static inline __host__ __device__ int32_t max() { return INT32_MAX; }
70
+ static inline __host__ __device__ int32_t lower_bound() { return INT32_MIN; }
71
+ static inline __host__ __device__ int32_t upper_bound() { return INT32_MAX; }
72
+ };
73
+
74
+ template <>
75
+ struct numeric_limits<int64_t> {
76
+ #ifdef _MSC_VER
77
+ static inline __host__ __device__ int64_t lowest() { return _I64_MIN; }
78
+ static inline __host__ __device__ int64_t max() { return _I64_MAX; }
79
+ static inline __host__ __device__ int64_t lower_bound() { return _I64_MIN; }
80
+ static inline __host__ __device__ int64_t upper_bound() { return _I64_MAX; }
81
+ #else
82
+ static inline __host__ __device__ int64_t lowest() { return INT64_MIN; }
83
+ static inline __host__ __device__ int64_t max() { return INT64_MAX; }
84
+ static inline __host__ __device__ int64_t lower_bound() { return INT64_MIN; }
85
+ static inline __host__ __device__ int64_t upper_bound() { return INT64_MAX; }
86
+ #endif
87
+ };
88
+
89
+ template <>
90
+ struct numeric_limits<at::Half> {
91
+ static inline __host__ __device__ at::Half lowest() { return at::Half(0xFBFF, at::Half::from_bits()); }
92
+ static inline __host__ __device__ at::Half max() { return at::Half(0x7BFF, at::Half::from_bits()); }
93
+ static inline __host__ __device__ at::Half lower_bound() { return at::Half(0xFC00, at::Half::from_bits()); }
94
+ static inline __host__ __device__ at::Half upper_bound() { return at::Half(0x7C00, at::Half::from_bits()); }
95
+ };
96
+
97
+ template <>
98
+ struct numeric_limits<at::BFloat16> {
99
+ static inline __host__ __device__ at::BFloat16 lowest() { return at::BFloat16(0xFF7F, at::BFloat16::from_bits()); }
100
+ static inline __host__ __device__ at::BFloat16 max() { return at::BFloat16(0x7F7F, at::BFloat16::from_bits()); }
101
+ static inline __host__ __device__ at::BFloat16 lower_bound() { return at::BFloat16(0xFF80, at::BFloat16::from_bits()); }
102
+ static inline __host__ __device__ at::BFloat16 upper_bound() { return at::BFloat16(0x7F80, at::BFloat16::from_bits()); }
103
+ };
104
+
105
+ template <>
106
+ struct numeric_limits<float> {
107
+ static inline __host__ __device__ float lowest() { return -FLT_MAX; }
108
+ static inline __host__ __device__ float max() { return FLT_MAX; }
109
+ static inline __host__ __device__ float lower_bound() { return -static_cast<float>(inf); }
110
+ static inline __host__ __device__ float upper_bound() { return static_cast<float>(inf); }
111
+ };
112
+
113
+ template <>
114
+ struct numeric_limits<double> {
115
+ static inline __host__ __device__ double lowest() { return -DBL_MAX; }
116
+ static inline __host__ __device__ double max() { return DBL_MAX; }
117
+ static inline __host__ __device__ double lower_bound() { return -inf; }
118
+ static inline __host__ __device__ double upper_bound() { return inf; }
119
+ };
120
+
121
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/string_view.h>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ struct TensorIterator;
13
+ struct TensorIteratorBase;
14
+ class TensorBase;
15
+ }
16
+
17
+ namespace at { namespace native {
18
+
19
+ // These constants control the approximation behavior of gelu function.
20
+ enum GeluType {
21
+ None, // Baseline Gelu
22
+ Tanh, // Tahn Gelu Approximation
23
+ END
24
+ };
25
+
26
+ static GeluType get_gelutype_enum(const c10::string_view approximate) {
27
+ if (approximate == "none") {
28
+ return GeluType::None;
29
+ } else if (approximate == "tanh") {
30
+ return GeluType::Tanh;
31
+ } else {
32
+ TORCH_CHECK(false, "approximate argument must be either none or tanh.");
33
+ }
34
+ }
35
+
36
+ using structured_activation_fn = void (*)(TensorIteratorBase&);
37
+ using structured_activation_backward_fn = void (*)(TensorIteratorBase&);
38
+
39
+ using activation_fn = void (*)(TensorIterator&);
40
+ using activation_backward_fn = void (*)(TensorIterator&);
41
+ using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
42
+ using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
43
+ using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
44
+ using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&);
45
+ using hardsigmoid_fn = void(*)(TensorIteratorBase&);
46
+ using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&);
47
+ using hardswish_fn = void(*)(TensorIterator&);
48
+ using hardswish_backward_fn = void(*)(TensorIterator&);
49
+ using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
50
+ using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
51
+ using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
52
+ using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&);
53
+ using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool);
54
+ using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
55
+ using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
56
+ using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&);
57
+ using gelu_fn = void (*)(TensorIteratorBase&, GeluType);
58
+ using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType);
59
+ using glu_jvp_fn = void (*)(TensorIteratorBase&);
60
+
61
+ DECLARE_DISPATCH(elu_fn, elu_stub);
62
+ DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub);
63
+ DECLARE_DISPATCH(softplus_fn, softplus_stub);
64
+ DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub);
65
+ DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub);
66
+ DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub);
67
+ DECLARE_DISPATCH(threshold_fn, threshold_stub);
68
+ DECLARE_DISPATCH(gelu_fn, GeluKernel);
69
+ DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel);
70
+ DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub);
71
+ DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub);
72
+ DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub);
73
+ DECLARE_DISPATCH(hardswish_fn, hardswish_stub);
74
+ DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub);
75
+ DECLARE_DISPATCH(shrink_fn, hardshrink_stub);
76
+ DECLARE_DISPATCH(softshrink_fn, softshrink_stub);
77
+ DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub);
78
+ DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub);
79
+ DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub);
80
+ DECLARE_DISPATCH(structured_activation_fn, glu_stub);
81
+ DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub);
82
+ DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub);
83
+ DECLARE_DISPATCH(structured_activation_fn, silu_stub);
84
+ DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub);
85
+ DECLARE_DISPATCH(structured_activation_fn, mish_stub);
86
+ DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub);
87
+ DECLARE_DISPATCH(activation_fn, prelu_stub);
88
+ DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub);
89
+
90
+ } // namespace native
91
+
92
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/ArrayRef.h>
6
+ #include <c10/util/irange.h>
7
+ #include <cmath>
8
+
9
+ namespace at {
10
+
11
+ namespace native {
12
+
13
+ using adaptive_avg_pooling_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
14
+ using adaptive_avg_pooling_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
15
+ DECLARE_DISPATCH(adaptive_avg_pooling_fn, adaptive_avg_pool2d_kernel);
16
+ DECLARE_DISPATCH(adaptive_avg_pooling_backward_fn, adaptive_avg_pool2d_backward_kernel);
17
+
18
+ using adaptive_max_pooling_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
19
+ using adaptive_max_pooling_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
20
+ DECLARE_DISPATCH(adaptive_max_pooling_fn, adaptive_max_pool2d_kernel);
21
+ DECLARE_DISPATCH(adaptive_max_pooling_backward_fn, adaptive_max_pool2d_backward_kernel);
22
+
23
+ static inline int64_t start_index(int64_t a, int64_t b, int64_t c) {
24
+ return (a / b) * c + ((a % b) * c) / b;
25
+ }
26
+
27
+ static inline int64_t end_index(int64_t a, int64_t b, int64_t c) {
28
+ return 1 + ((a + 1) * c - 1) / b;
29
+ }
30
+
31
+ static inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) {
32
+ int64_t ndim = gradOutput_.ndimension();
33
+ for (const auto i : c10::irange(1, ndim)) {
34
+ TORCH_CHECK(gradOutput_.size(i) > 0,
35
+ arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, "
36
+ "but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i,
37
+ " being empty");
38
+ }
39
+ }
40
+
41
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Optional.h>
4
+ #include <ATen/Config.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ // Forward declare TI
8
+ namespace at {
9
+ class Tensor;
10
+ struct TensorIterator;
11
+
12
+ namespace native {
13
+ enum class TransposeType;
14
+ }
15
+
16
+ }
17
+
18
+ namespace at { namespace native {
19
+
20
+ enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
21
+
22
+ #if AT_BUILD_WITH_LAPACK()
23
+ // Define per-batch functions to be used in the implementation of batched
24
+ // linear algebra operations
25
+
26
+ template <class scalar_t>
27
+ void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
28
+
29
+ template <class scalar_t>
30
+ void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
31
+
32
+ template <class scalar_t, class value_t=scalar_t>
33
+ void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
34
+
35
+ template <class scalar_t>
36
+ void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
37
+
38
+ template <class scalar_t>
39
+ void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
40
+
41
+ template <class scalar_t>
42
+ void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
43
+
44
+ template <class scalar_t, class value_t = scalar_t>
45
+ void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
46
+
47
+ template <class scalar_t>
48
+ void lapackGels(char trans, int m, int n, int nrhs,
49
+ scalar_t *a, int lda, scalar_t *b, int ldb,
50
+ scalar_t *work, int lwork, int *info);
51
+
52
+ template <class scalar_t, class value_t = scalar_t>
53
+ void lapackGelsd(int m, int n, int nrhs,
54
+ scalar_t *a, int lda, scalar_t *b, int ldb,
55
+ value_t *s, value_t rcond, int *rank,
56
+ scalar_t* work, int lwork,
57
+ value_t *rwork, int* iwork, int *info);
58
+
59
+ template <class scalar_t, class value_t = scalar_t>
60
+ void lapackGelsy(int m, int n, int nrhs,
61
+ scalar_t *a, int lda, scalar_t *b, int ldb,
62
+ int *jpvt, value_t rcond, int *rank,
63
+ scalar_t *work, int lwork, value_t* rwork, int *info);
64
+
65
+ template <class scalar_t, class value_t = scalar_t>
66
+ void lapackGelss(int m, int n, int nrhs,
67
+ scalar_t *a, int lda, scalar_t *b, int ldb,
68
+ value_t *s, value_t rcond, int *rank,
69
+ scalar_t *work, int lwork,
70
+ value_t *rwork, int *info);
71
+
72
+ template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
73
+ struct lapackLstsq_impl;
74
+
75
+ template <class scalar_t, class value_t>
76
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
77
+ static void call(
78
+ char trans, int m, int n, int nrhs,
79
+ scalar_t *a, int lda, scalar_t *b, int ldb,
80
+ scalar_t *work, int lwork, int *info, // Gels flavor
81
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
82
+ value_t *s, // Gelss flavor
83
+ int *iwork // Gelsd flavor
84
+ ) {
85
+ lapackGels<scalar_t>(
86
+ trans, m, n, nrhs,
87
+ a, lda, b, ldb,
88
+ work, lwork, info);
89
+ }
90
+ };
91
+
92
+ template <class scalar_t, class value_t>
93
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
94
+ static void call(
95
+ char trans, int m, int n, int nrhs,
96
+ scalar_t *a, int lda, scalar_t *b, int ldb,
97
+ scalar_t *work, int lwork, int *info, // Gels flavor
98
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
99
+ value_t *s, // Gelss flavor
100
+ int *iwork // Gelsd flavor
101
+ ) {
102
+ lapackGelsy<scalar_t, value_t>(
103
+ m, n, nrhs,
104
+ a, lda, b, ldb,
105
+ jpvt, rcond, rank,
106
+ work, lwork, rwork, info);
107
+ }
108
+ };
109
+
110
+ template <class scalar_t, class value_t>
111
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
112
+ static void call(
113
+ char trans, int m, int n, int nrhs,
114
+ scalar_t *a, int lda, scalar_t *b, int ldb,
115
+ scalar_t *work, int lwork, int *info, // Gels flavor
116
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
117
+ value_t *s, // Gelss flavor
118
+ int *iwork // Gelsd flavor
119
+ ) {
120
+ lapackGelsd<scalar_t, value_t>(
121
+ m, n, nrhs,
122
+ a, lda, b, ldb,
123
+ s, rcond, rank,
124
+ work, lwork,
125
+ rwork, iwork, info);
126
+ }
127
+ };
128
+
129
+ template <class scalar_t, class value_t>
130
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
131
+ static void call(
132
+ char trans, int m, int n, int nrhs,
133
+ scalar_t *a, int lda, scalar_t *b, int ldb,
134
+ scalar_t *work, int lwork, int *info, // Gels flavor
135
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
136
+ value_t *s, // Gelss flavor
137
+ int *iwork // Gelsd flavor
138
+ ) {
139
+ lapackGelss<scalar_t, value_t>(
140
+ m, n, nrhs,
141
+ a, lda, b, ldb,
142
+ s, rcond, rank,
143
+ work, lwork,
144
+ rwork, info);
145
+ }
146
+ };
147
+
148
+ template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
149
+ void lapackLstsq(
150
+ char trans, int m, int n, int nrhs,
151
+ scalar_t *a, int lda, scalar_t *b, int ldb,
152
+ scalar_t *work, int lwork, int *info, // Gels flavor
153
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
154
+ value_t *s, // Gelss flavor
155
+ int *iwork // Gelsd flavor
156
+ ) {
157
+ lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
158
+ trans, m, n, nrhs,
159
+ a, lda, b, ldb,
160
+ work, lwork, info,
161
+ jpvt, rcond, rank, rwork,
162
+ s,
163
+ iwork);
164
+ }
165
+
166
+ template <class scalar_t>
167
+ void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
168
+
169
+ template <class scalar_t>
170
+ void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
171
+
172
+ template <class scalar_t>
173
+ void lapackLdlHermitian(
174
+ char uplo,
175
+ int n,
176
+ scalar_t* a,
177
+ int lda,
178
+ int* ipiv,
179
+ scalar_t* work,
180
+ int lwork,
181
+ int* info);
182
+
183
+ template <class scalar_t>
184
+ void lapackLdlSymmetric(
185
+ char uplo,
186
+ int n,
187
+ scalar_t* a,
188
+ int lda,
189
+ int* ipiv,
190
+ scalar_t* work,
191
+ int lwork,
192
+ int* info);
193
+
194
+ template <class scalar_t>
195
+ void lapackLdlSolveHermitian(
196
+ char uplo,
197
+ int n,
198
+ int nrhs,
199
+ scalar_t* a,
200
+ int lda,
201
+ int* ipiv,
202
+ scalar_t* b,
203
+ int ldb,
204
+ int* info);
205
+
206
+ template <class scalar_t>
207
+ void lapackLdlSolveSymmetric(
208
+ char uplo,
209
+ int n,
210
+ int nrhs,
211
+ scalar_t* a,
212
+ int lda,
213
+ int* ipiv,
214
+ scalar_t* b,
215
+ int ldb,
216
+ int* info);
217
+
218
+ template<class scalar_t, class value_t=scalar_t>
219
+ void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
220
+ #endif
221
+
222
+ #if AT_BUILD_WITH_BLAS()
223
+ template <class scalar_t>
224
+ void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
225
+ #endif
226
+
227
+ using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
228
+ DECLARE_DISPATCH(cholesky_fn, cholesky_stub);
229
+
230
+ using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
231
+
232
+ DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub);
233
+
234
+ using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
235
+
236
+ DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub);
237
+
238
+ using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
239
+ DECLARE_DISPATCH(geqrf_fn, geqrf_stub);
240
+
241
+ using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
242
+ DECLARE_DISPATCH(orgqr_fn, orgqr_stub);
243
+
244
+ using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
245
+ DECLARE_DISPATCH(ormqr_fn, ormqr_stub);
246
+
247
+ using linalg_eigh_fn = void (*)(
248
+ const Tensor& /*eigenvalues*/,
249
+ const Tensor& /*eigenvectors*/,
250
+ const Tensor& /*infos*/,
251
+ bool /*upper*/,
252
+ bool /*compute_eigenvectors*/);
253
+ DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub);
254
+
255
+ using lstsq_fn = void (*)(
256
+ const Tensor& /*a*/,
257
+ Tensor& /*b*/,
258
+ Tensor& /*rank*/,
259
+ Tensor& /*singular_values*/,
260
+ Tensor& /*infos*/,
261
+ double /*rcond*/,
262
+ std::string /*driver_name*/);
263
+ DECLARE_DISPATCH(lstsq_fn, lstsq_stub);
264
+
265
+ using triangular_solve_fn = void (*)(
266
+ const Tensor& /*A*/,
267
+ const Tensor& /*B*/,
268
+ bool /*left*/,
269
+ bool /*upper*/,
270
+ TransposeType /*transpose*/,
271
+ bool /*unitriangular*/);
272
+ DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub);
273
+
274
+ using lu_factor_fn = void (*)(
275
+ const Tensor& /*input*/,
276
+ const Tensor& /*pivots*/,
277
+ const Tensor& /*infos*/,
278
+ bool /*compute_pivots*/);
279
+ DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub);
280
+
281
+ using unpack_pivots_fn = void(*)(
282
+ TensorIterator& iter,
283
+ const int64_t dim_size,
284
+ const int64_t max_pivot);
285
+ DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub);
286
+
287
+ using lu_solve_fn = void (*)(
288
+ const Tensor& /*LU*/,
289
+ const Tensor& /*pivots*/,
290
+ const Tensor& /*B*/,
291
+ TransposeType /*trans*/);
292
+ DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub);
293
+
294
+ using ldl_factor_fn = void (*)(
295
+ const Tensor& /*LD*/,
296
+ const Tensor& /*pivots*/,
297
+ const Tensor& /*info*/,
298
+ bool /*upper*/,
299
+ bool /*hermitian*/);
300
+ DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub);
301
+
302
+ using svd_fn = void (*)(
303
+ const Tensor& /*A*/,
304
+ const bool /*full_matrices*/,
305
+ const bool /*compute_uv*/,
306
+ const c10::optional<c10::string_view>& /*driver*/,
307
+ const Tensor& /*U*/,
308
+ const Tensor& /*S*/,
309
+ const Tensor& /*Vh*/,
310
+ const Tensor& /*info*/);
311
+ DECLARE_DISPATCH(svd_fn, svd_stub);
312
+
313
+ using ldl_solve_fn = void (*)(
314
+ const Tensor& /*LD*/,
315
+ const Tensor& /*pivots*/,
316
+ const Tensor& /*result*/,
317
+ bool /*upper*/,
318
+ bool /*hermitian*/);
319
+ DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub);
320
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/core/Scalar.h>
6
+
7
+ namespace at {
8
+ struct TensorIterator;
9
+ struct TensorIteratorBase;
10
+ }
11
+
12
+ namespace at { namespace native {
13
+
14
+ inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
15
+ TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
16
+ "Boolean alpha only supported for Boolean results.");
17
+ TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
18
+ || alpha.isIntegral(true),
19
+ "For integral input tensors, argument alpha must not be a floating point number.");
20
+ TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
21
+ "For non-complex input tensors, argument alpha must not be a complex number.")
22
+ }
23
+
24
+ // Basic checking for all sub functions.
25
+ inline void sub_check(const TensorBase& self, const TensorBase& other) {
26
+ TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
27
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
28
+ "Use the `^` or `logical_xor()` operator instead.")
29
+ TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
30
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
31
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
32
+ }
33
+
34
+ inline void sub_check(const TensorBase& self, const Scalar& scalar) {
35
+ TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
36
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
37
+ "Use the `^` or `logical_xor()` operator instead.")
38
+ TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
39
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
40
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
41
+ }
42
+
43
+ using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
44
+ using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
45
+ using structured_binary_fn = void(*)(TensorIteratorBase&);
46
+
47
+ using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
48
+ using binary_fn_double = void(*)(TensorIterator&, double);
49
+ using binary_fn = void(*)(TensorIterator&);
50
+ using binary_clamp_fn_alpha =
51
+ void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
52
+
53
+ // NB: codegenned
54
+ DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub);
55
+
56
+ DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub);
57
+ DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub);
58
+ DECLARE_DISPATCH(structured_binary_fn, mul_stub);
59
+ DECLARE_DISPATCH(structured_binary_fn, div_true_stub);
60
+ DECLARE_DISPATCH(structured_binary_fn, div_floor_stub);
61
+ DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub);
62
+ DECLARE_DISPATCH(structured_binary_fn, atan2_stub);
63
+ DECLARE_DISPATCH(structured_binary_fn, remainder_stub);
64
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub);
65
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub);
66
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub);
67
+ DECLARE_DISPATCH(structured_binary_fn, lshift_stub);
68
+ DECLARE_DISPATCH(structured_binary_fn, rshift_stub);
69
+ DECLARE_DISPATCH(binary_fn, logical_xor_stub);
70
+ DECLARE_DISPATCH(binary_fn, logical_and_stub);
71
+ DECLARE_DISPATCH(binary_fn, logical_or_stub);
72
+ DECLARE_DISPATCH(structured_binary_fn, lt_stub);
73
+ DECLARE_DISPATCH(structured_binary_fn, le_stub);
74
+ DECLARE_DISPATCH(structured_binary_fn, gt_stub);
75
+ DECLARE_DISPATCH(structured_binary_fn, ge_stub);
76
+ DECLARE_DISPATCH(structured_binary_fn, eq_stub);
77
+ DECLARE_DISPATCH(structured_binary_fn, ne_stub);
78
+ DECLARE_DISPATCH(binary_fn, max_elementwise_stub);
79
+ DECLARE_DISPATCH(binary_fn, min_elementwise_stub);
80
+ DECLARE_DISPATCH(structured_binary_fn, maximum_stub);
81
+ DECLARE_DISPATCH(structured_binary_fn, minimum_stub);
82
+ DECLARE_DISPATCH(structured_binary_fn, fmax_stub);
83
+ DECLARE_DISPATCH(structured_binary_fn, fmin_stub);
84
+ DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub);
85
+ DECLARE_DISPATCH(binary_fn_double, huber_stub);
86
+ DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub);
87
+ DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub);
88
+ DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub);
89
+ DECLARE_DISPATCH(structured_binary_fn, mse_stub);
90
+ DECLARE_DISPATCH(structured_binary_fn, fmod_stub);
91
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub);
92
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub);
93
+ DECLARE_DISPATCH(structured_binary_fn, gcd_stub);
94
+ DECLARE_DISPATCH(structured_binary_fn, lcm_stub);
95
+ DECLARE_DISPATCH(structured_binary_fn, hypot_stub);
96
+ DECLARE_DISPATCH(structured_binary_fn, igamma_stub);
97
+ DECLARE_DISPATCH(structured_binary_fn, igammac_stub);
98
+ DECLARE_DISPATCH(structured_binary_fn, nextafter_stub);
99
+ DECLARE_DISPATCH(structured_binary_fn, heaviside_stub);
100
+ DECLARE_DISPATCH(structured_binary_fn, copysign_stub);
101
+ DECLARE_DISPATCH(structured_binary_fn, xlogy_stub);
102
+ DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub);
103
+ DECLARE_DISPATCH(structured_binary_fn, zeta_stub);
104
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub);
105
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub);
106
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub);
107
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub);
108
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub);
109
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub);
110
+ DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub);
111
+ DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub);
112
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub);
113
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub);
114
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub);
115
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub);
116
+
117
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/TypeProperties.h>
5
+ #include <ATen/ScalarOps.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/NativeFunctions.h>
9
+ #else
10
+ #include <ATen/ops/result_type.h>
11
+ #endif
12
+
13
+ namespace at {
14
+ namespace native {
15
+
16
+ // original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to
17
+ // the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not
18
+ // match, will change them to be a common super type so comparisons are done between the same types.
19
+ // For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the
20
+ // corresponding raw_* version should be used since it was already contiguous of the right type.
21
+ inline void searchsorted_maybe_trim_input_tensors(
22
+ Tensor& trimmed_input,
23
+ Tensor& trimmed_boundaries,
24
+ Tensor& trimmed_sorter,
25
+ const Tensor& raw_input,
26
+ const Tensor& raw_boundaries,
27
+ const Tensor& raw_sorter) {
28
+ bool in_is_contiguous = raw_input.is_contiguous();
29
+ bool bd_is_contiguous = raw_boundaries.is_contiguous();
30
+ bool sort_is_contiguous = raw_sorter.is_contiguous();
31
+
32
+ if (!in_is_contiguous) {
33
+ TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due "
34
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value "
35
+ "tensor if possible. This message will only appear once per program.");
36
+ trimmed_input = raw_input.contiguous();
37
+ }
38
+ if (!bd_is_contiguous) {
39
+ TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due "
40
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary "
41
+ "tensor if possible. This message will only appear once per program.");
42
+ trimmed_boundaries = raw_boundaries.contiguous();
43
+ }
44
+ if (!sort_is_contiguous) {
45
+ TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due "
46
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter "
47
+ "tensor if possible. This message will only appear once per program.");
48
+ trimmed_sorter = raw_sorter.contiguous();
49
+ }
50
+ if (raw_input.dtype() != raw_boundaries.dtype()) {
51
+ at::native::ResultTypeState state = {};
52
+ state = at::native::update_result_type_state(raw_boundaries, state);
53
+ state = at::native::update_result_type_state(raw_input, state);
54
+ ScalarType common_stype = at::native::result_type(state);
55
+
56
+ TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined);
57
+ if (common_stype != raw_input.scalar_type()) {
58
+ trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype);
59
+ }
60
+ if (common_stype != raw_boundaries.scalar_type()) {
61
+ trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype);
62
+ }
63
+ }
64
+ }
65
+
66
+ /* unused but needed for internal jagged tensor class */
67
+ inline void searchsorted_maybe_trim_input_tensors(
68
+ Tensor& trimmed_input,
69
+ Tensor& trimmed_boundaries,
70
+ const Tensor& raw_input,
71
+ const Tensor& raw_boundaries) {
72
+ Tensor trimmed_sorter;
73
+ Tensor raw_sorter;
74
+ return searchsorted_maybe_trim_input_tensors(
75
+ trimmed_input,
76
+ trimmed_boundaries,
77
+ trimmed_sorter,
78
+ raw_input,
79
+ raw_boundaries,
80
+ raw_sorter);
81
+ }
82
+
83
+ inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) {
84
+ if (boundaries.dim() != input.dim()) {
85
+ return false;
86
+ }
87
+ const auto& dims_bd = boundaries.sizes();
88
+ const auto& dims_in = input.sizes();
89
+ for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) {
90
+ if (dims_bd[dim] != dims_in[dim]) {
91
+ return false;
92
+ }
93
+ }
94
+ return true;
95
+ }
96
+
97
+ inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) {
98
+ auto tensor = c10::scalar_to_tensor(scalar, device);
99
+ // This is to adopt the scalar promotion rules defined in native/TypeProperties.h
100
+ // So we have the same type promotion rules as binary operations.
101
+ tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
102
+ return tensor;
103
+ }
104
+
105
+ inline void searchsorted_pre_check(
106
+ const Tensor& boundaries,
107
+ const Tensor& input,
108
+ const Tensor& output,
109
+ const bool out_int32,
110
+ const bool right,
111
+ const c10::optional<c10::string_view> side_opt,
112
+ const Tensor& sorter) {
113
+ if (side_opt) {
114
+ const c10::string_view side = *side_opt;
115
+ TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ",
116
+ "got ", side);
117
+
118
+ // assume the user has not explicitly set (right=False, side="right")
119
+ TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side "
120
+ "of ", side, " while right was True");
121
+ }
122
+
123
+ TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ",
124
+ "should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ",
125
+ "tensor device type ", input.device());
126
+
127
+ if (sorter.defined()) {
128
+ TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ",
129
+ "have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ",
130
+ "device type ", boundaries.device());
131
+
132
+ TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same "
133
+ "size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes());
134
+
135
+ TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ",
136
+ "dtype but got dtype ", sorter.scalar_type());
137
+ }
138
+
139
+ TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1),
140
+ "torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ",
141
+ "boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(",
142
+ input.numel(), ")");
143
+
144
+ TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ",
145
+ "got 0 dimension");
146
+
147
+ TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input),
148
+ "torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ",
149
+ "and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ",
150
+ input.sizes());
151
+
152
+ ScalarType output_dtype = output.scalar_type();
153
+ TORCH_CHECK(
154
+ (output_dtype == ScalarType::Long && !out_int32) ||
155
+ (output_dtype == ScalarType::Int && out_int32),
156
+ "torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ",
157
+ "whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype,
158
+ " and out_int32 flag is ", (out_int32 ? "True" : "False"));
159
+
160
+ if (out_int32) {
161
+ TORCH_CHECK(boundaries.sizes().back() < INT_MAX,
162
+ "torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ",
163
+ boundaries.sizes().back());
164
+ }
165
+ }
166
+
167
+ }}
wemm/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/OpMathType.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/native/TransposeType.h>
6
+ #include <c10/util/complex.h>
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/core/Scalar.h>
9
+
10
+ namespace at {
11
+ namespace native {
12
+ namespace cpublas {
13
+
14
+ namespace internal {
15
+ void normalize_last_dims(
16
+ TransposeType transa, TransposeType transb,
17
+ int64_t m, int64_t n, int64_t k,
18
+ int64_t *lda, int64_t *ldb, int64_t *ldc);
19
+ } // namespace internal
20
+
21
+ using gemm_fn = void(*)(
22
+ at::ScalarType type,
23
+ TransposeType transa, TransposeType transb,
24
+ int64_t m, int64_t n, int64_t k,
25
+ const Scalar& alpha,
26
+ const void *a, int64_t lda,
27
+ const void *b, int64_t ldb,
28
+ const Scalar& beta,
29
+ void *c, int64_t ldc);
30
+
31
+ DECLARE_DISPATCH(gemm_fn, gemm_stub);
32
+
33
+ template <typename scalar_t>
34
+ void gemm(
35
+ TransposeType transa, TransposeType transb,
36
+ int64_t m, int64_t n, int64_t k,
37
+ at::opmath_type<scalar_t> alpha,
38
+ const scalar_t *a, int64_t lda,
39
+ const scalar_t *b, int64_t ldb,
40
+ at::opmath_type<scalar_t> beta,
41
+ scalar_t *c, int64_t ldc) {
42
+ internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc);
43
+ gemm_stub(
44
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
45
+ transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
46
+ }
47
+
48
+ void gemm(
49
+ TransposeType transa, TransposeType transb,
50
+ int64_t m, int64_t n, int64_t k,
51
+ double alpha,
52
+ const double *a, int64_t lda,
53
+ const double *b, int64_t ldb,
54
+ double beta,
55
+ double *c, int64_t ldc);
56
+
57
+ void gemm(
58
+ TransposeType transa, TransposeType transb,
59
+ int64_t m, int64_t n, int64_t k,
60
+ float alpha,
61
+ const float *a, int64_t lda,
62
+ const float *b, int64_t ldb,
63
+ float beta,
64
+ float *c, int64_t ldc);
65
+
66
+ void gemm(
67
+ TransposeType transa, TransposeType transb,
68
+ int64_t m, int64_t n, int64_t k,
69
+ float alpha,
70
+ const at::BFloat16 *a, int64_t lda,
71
+ const at::BFloat16 *b, int64_t ldb,
72
+ float beta,
73
+ at::BFloat16 *c, int64_t ldc);
74
+
75
+ void gemm(
76
+ TransposeType transa, TransposeType transb,
77
+ int64_t m, int64_t n, int64_t k,
78
+ c10::complex<double> alpha,
79
+ const c10::complex<double> *a, int64_t lda,
80
+ const c10::complex<double> *b, int64_t ldb,
81
+ c10::complex<double> beta,
82
+ c10::complex<double> *c, int64_t ldc);
83
+
84
+ void gemm(
85
+ TransposeType transa, TransposeType transb,
86
+ int64_t m, int64_t n, int64_t k,
87
+ c10::complex<float> alpha,
88
+ const c10::complex<float> *a, int64_t lda,
89
+ const c10::complex<float> *b, int64_t ldb,
90
+ c10::complex<float> beta,
91
+ c10::complex<float> *c, int64_t ldc);
92
+
93
+ void gemm(
94
+ TransposeType transa, TransposeType transb,
95
+ int64_t m, int64_t n, int64_t k,
96
+ int64_t alpha,
97
+ const int64_t *a, int64_t lda,
98
+ const int64_t *b, int64_t ldb,
99
+ int64_t beta,
100
+ int64_t *c, int64_t ldc);
101
+
102
+ template <typename scalar_t>
103
+ void gemm_batched(
104
+ TransposeType transa, TransposeType transb,
105
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
106
+ scalar_t alpha,
107
+ const scalar_t * const *a, int64_t lda,
108
+ const scalar_t * const *b, int64_t ldb,
109
+ const scalar_t beta,
110
+ scalar_t * const *c, int64_t ldc);
111
+
112
+ template <typename scalar_t>
113
+ void gemm_batched_with_stride(
114
+ TransposeType transa, TransposeType transb,
115
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
116
+ scalar_t alpha,
117
+ const scalar_t *a, int64_t lda, int64_t batch_stride_a,
118
+ const scalar_t *b, int64_t ldb, int64_t batch_stride_b,
119
+ scalar_t beta,
120
+ scalar_t *c, int64_t ldc, int64_t batch_stride_c);
121
+
122
+ using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy);
123
+
124
+ DECLARE_DISPATCH(axpy_fn, axpy_stub);
125
+
126
+ template<typename scalar_t>
127
+ void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){
128
+ if(n == 1)
129
+ {
130
+ incx = 1;
131
+ incy = 1;
132
+ }
133
+ axpy_stub(
134
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
135
+ n, a, x, incx, y, incy);
136
+ }
137
+
138
+ void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy);
139
+ void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy);
140
+ void axpy(int64_t n, c10::complex<double> a, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
141
+ void axpy(int64_t n, c10::complex<float> a, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
142
+
143
+ using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy);
144
+
145
+ DECLARE_DISPATCH(copy_fn, copy_stub);
146
+
147
+ template<typename scalar_t>
148
+ void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) {
149
+ if(n == 1)
150
+ {
151
+ incx = 1;
152
+ incy = 1;
153
+ }
154
+ copy_stub(
155
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
156
+ n, x, incx, y, incy);
157
+ }
158
+
159
+ void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy);
160
+ void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy);
161
+ void copy(int64_t n, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
162
+ void copy(int64_t n, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
163
+
164
+ }}} // namespace at::native::cpublas
wemm/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <ATen/core/stack.h>
5
+ #include <ATen/core/boxing/KernelFunction.h>
6
+ #include <ATen/core/dispatch/Dispatcher.h>
7
+ #include <c10/util/Metaprogramming.h>
8
+ #include <torch/library.h>
9
+
10
+ namespace at { namespace native {
11
+
12
+ // This function implements a boxed fallback to CPU.
13
+ // External backends can add their own custom logging on top if it to customize their own CPU fallbacks.
14
+ TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
15
+
16
+ // This is a helper function that backends can use to directly call their boxed CPU fallback
17
+ // TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands.
18
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
19
+ struct _call_fallback_fn final {};
20
+
21
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
22
+ struct _call_fallback_fn<fallback_fn, Op, symint, ReturnType(ParameterTypes...)> final {
23
+ static ReturnType call(typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
24
+ auto op = c10::Dispatcher::singleton()
25
+ // TODO: figure out how to make compiler happy without dynamic casts
26
+ .findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name)
27
+ //.findSchemaOrThrow("a", "b")
28
+ .typed<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>();
29
+ return c10::impl::BoxedKernelWrapper<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>::call(
30
+ c10::BoxedKernel::makeFromFunction<fallback_fn>(),
31
+ op,
32
+ c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset.
33
+ // TODO: get std::forward<> to work
34
+ args...
35
+ );
36
+ }
37
+ };
38
+
39
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
40
+ using call_fallback_fn_symint = _call_fallback_fn<fallback_fn, Op, true, typename Op::schema>;
41
+
42
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
43
+ using call_fallback_fn = _call_fallback_fn<fallback_fn, Op, false, typename Op::schema>;
44
+
45
+ } // namespace native
46
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/NativeFunctions.h>
8
+ #else
9
+ #include <ATen/ops/view_as_real_native.h>
10
+ #include <ATen/ops/view_as_complex_native.h>
11
+
12
+ #include <utility>
13
+ #endif
14
+
15
+ // WARNING: this header contains non-inline functions and should be only
16
+ // included from ONE cpp file
17
+
18
+ namespace at { namespace native {
19
+
20
+ // View tensor with new dtype, storage offset, sizes and strides
21
+ inline Tensor view_tensor(
22
+ const Tensor &tensor, ScalarType dtype,
23
+ c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) {
24
+ Storage storage = tensor.storage();
25
+ auto key_set = tensor.key_set().remove(DispatchKey::Conjugate);
26
+ auto new_tensor = detail::make_tensor<TensorImpl>(
27
+ c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype));
28
+ auto * impl = new_tensor.unsafeGetTensorImpl();
29
+ impl->set_sizes_and_strides(sizes, strides, offset);
30
+ return new_tensor;
31
+ }
32
+
33
+ inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) {
34
+ SymDimVector res(oldstride.size() + 1);
35
+ for (const auto i : c10::irange(oldstride.size())) {
36
+ res[i] = oldstride[i] * 2;
37
+ }
38
+ res.back() = 1;
39
+ return res;
40
+ }
41
+
42
+ Tensor _view_as_real_physical(const Tensor& self) {
43
+ TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors");
44
+ auto old_sizes = self.sym_sizes();
45
+ SymDimVector new_sizes(old_sizes.size() + 1);
46
+ std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
47
+ // last dimension will always have two elements containing the real and imag vals
48
+ new_sizes.back() = 2;
49
+ auto new_strides = computeStrideForViewAsReal(self.sym_strides());
50
+ auto new_storage_offset = self.sym_storage_offset() * 2;
51
+ const auto float_type = c10::toRealValueType(self.scalar_type());
52
+ auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides);
53
+ return real_tensor;
54
+ }
55
+
56
+ // expects as input a complex tensor and returns back a tensor
57
+ // with corresponding real dtype containing the complex values
58
+ // in the last two dimensions
59
+ Tensor view_as_real(const Tensor& self) {
60
+ TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original.");
61
+ return _view_as_real_physical(self);
62
+ }
63
+
64
+ inline SymDimVector computeStrideForViewAsComplex(SymIntArrayRef oldstride) {
65
+ const int64_t dim = oldstride.size();
66
+ TORCH_CHECK(oldstride[dim-1] == 1, "Tensor must have a last dimension with stride 1");
67
+
68
+ SymDimVector res(dim - 1);
69
+ for (const auto i : c10::irange(res.size())) {
70
+ TORCH_CHECK(oldstride[i] % 2 == 0, "Tensor must have a stride divisible by 2 for all but last dimension");
71
+ res[i] = oldstride[i] / 2;
72
+ }
73
+ return res;
74
+ }
75
+
76
+ // expects as input a float or double tensor with last dimension of size 2
77
+ // and returns back a tensor with corresponding complex dtype
78
+ Tensor view_as_complex(const Tensor& self) {
79
+ TORCH_CHECK(
80
+ self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf,
81
+ "view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type());
82
+
83
+ auto old_sizes = self.sym_sizes();
84
+ TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions");
85
+ TORCH_CHECK(old_sizes[old_sizes.size()-1] == 2, "Tensor must have a last dimension of size 2");
86
+ SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1);
87
+
88
+ const auto new_strides = computeStrideForViewAsComplex(self.sym_strides());
89
+ const auto complex_type = c10::toComplexType(self.scalar_type());
90
+
91
+ TORCH_CHECK(self.sym_storage_offset() % 2 == 0, "Tensor must have a storage_offset divisible by 2");
92
+ const auto new_storage_offset = self.sym_storage_offset() / 2;
93
+
94
+ return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides);
95
+ }
96
+
97
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/CompositeRandomAccessorCommon.h>
4
+
5
+ namespace at { namespace native {
6
+
7
+ struct TupleInfoCPU {
8
+ template <typename ...Types>
9
+ using tuple = std::tuple<Types...>;
10
+
11
+ template <typename ...Types>
12
+ static constexpr auto tie(Types&... args) noexcept {
13
+ return std::tie(args...);
14
+ }
15
+ };
16
+
17
+ template <typename KeyAccessor, typename ValueAccessor>
18
+ using CompositeRandomAccessorCPU =
19
+ CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfoCPU>;
20
+
21
+ template <typename Values, typename References>
22
+ void swap(
23
+ references_holder<Values, References> rh1,
24
+ references_holder<Values, References> rh2
25
+ ) {
26
+ return std::swap(rh1.data(), rh2.data());
27
+ }
28
+
29
+ template <int N, typename Values, typename References>
30
+ auto get(references_holder<Values, References> rh) -> decltype(std::get<N>(rh.data())) {
31
+ return std::get<N>(rh.data());
32
+ }
33
+
34
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <utility>
2
+
3
+ #pragma once
4
+
5
+ namespace at { namespace native {
6
+
7
+ namespace {
8
+
9
+ // operator_brackets_proxy is used in
10
+ // CompositeRandomAccessor in place of operator[].
11
+ // For some iterators, references returned by operator[]
12
+ // could become invalid, operator_brackets_proxy tries to
13
+ // resolve that by making accessor[n] to be equivalent to
14
+ // *(accessor + n).
15
+ template <typename Accessor>
16
+ class operator_brackets_proxy {
17
+ using reference = typename std::iterator_traits<Accessor>::reference;
18
+ using value_type = typename std::iterator_traits<Accessor>::value_type;
19
+
20
+ public:
21
+ C10_HOST_DEVICE
22
+ operator_brackets_proxy(Accessor const& accessor)
23
+ : accessor(accessor)
24
+ {}
25
+
26
+ C10_HOST_DEVICE
27
+ operator reference() {
28
+ return *accessor;
29
+ }
30
+
31
+ C10_HOST_DEVICE
32
+ reference operator*() {
33
+ return *accessor;
34
+ }
35
+
36
+ C10_HOST_DEVICE
37
+ operator_brackets_proxy& operator=(value_type const& val) {
38
+ *accessor = val;
39
+ return *this;
40
+ }
41
+
42
+ private:
43
+ Accessor accessor;
44
+ };
45
+
46
+ }
47
+
48
+ // references_holder is used as a surrogate for the
49
+ // references type from std::iterator_traits in CompositeRandomAccessor.
50
+ // It is assumed in CompositeRandomAccessor that
51
+ // References = tuple<Types&...>,
52
+ // Values = tuple<Types...> by default,
53
+ // but they could be anything as long as References could be
54
+ // cast to Values.
55
+ // If you plan to use it with STL, for example, you will need to
56
+ // define 'swap` and `get`(aka std::get) methods.
57
+ template <typename Values, typename References>
58
+ class references_holder {
59
+ public:
60
+ using values = Values;
61
+ using references = References;
62
+
63
+ C10_HOST_DEVICE
64
+ references_holder(references refs)
65
+ : refs{std::move(refs)}
66
+ {}
67
+
68
+ C10_HOST_DEVICE
69
+ operator references() {
70
+ return refs;
71
+ }
72
+
73
+ C10_HOST_DEVICE
74
+ operator values() {
75
+ return refs;
76
+ }
77
+
78
+ C10_HOST_DEVICE
79
+ references_holder& operator=(values vals) {
80
+ refs = vals;
81
+ return *this;
82
+ }
83
+
84
+ C10_HOST_DEVICE
85
+ references& data() {
86
+ return refs;
87
+ }
88
+
89
+ protected:
90
+ references refs;
91
+ };
92
+
93
+ // CompositeRandomAccessor is essentially a simplified version of
94
+ // a random access iterator over two random access iterators.
95
+ // TupleInfo should contain a variadic type `tuple`, and a method `tie`,
96
+ // which constructs a tuple of references from a variadic list of arguments.
97
+ template <typename KeyAccessor, typename ValueAccessor, typename TupleInfo>
98
+ class CompositeRandomAccessor {
99
+ using self_type = CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfo>;
100
+
101
+ using key_accessor_value_type =
102
+ typename std::iterator_traits<KeyAccessor>::value_type;
103
+ using value_accessor_value_type =
104
+ typename std::iterator_traits<ValueAccessor>::value_type;
105
+ using key_accessor_reference_type =
106
+ typename std::iterator_traits<KeyAccessor>::reference;
107
+ using value_accessor_reference_type =
108
+ typename std::iterator_traits<ValueAccessor>::reference;
109
+
110
+ using composite_value_type = typename TupleInfo::template tuple<
111
+ key_accessor_value_type,
112
+ value_accessor_value_type>;
113
+ using composite_reference = typename TupleInfo::template tuple<
114
+ key_accessor_reference_type,
115
+ value_accessor_reference_type>;
116
+
117
+ public:
118
+ using value_type = composite_value_type;
119
+ using reference = references_holder<composite_value_type, composite_reference>;
120
+ // Note that CompositeRandomAccessor does not hold key and values
121
+ // in a specific datastrcture, which means that a pointer to a (key, value)
122
+ // is not defined. Hence we just use a pointer type of the KeyAccessor.
123
+ using pointer = typename std::iterator_traits<KeyAccessor>::pointer;
124
+ using difference_type = typename std::iterator_traits<KeyAccessor>::difference_type;
125
+ using iterator_category = std::random_access_iterator_tag;
126
+
127
+ C10_HOST_DEVICE
128
+ CompositeRandomAccessor() = default;
129
+
130
+ C10_HOST_DEVICE
131
+ CompositeRandomAccessor(KeyAccessor keys, ValueAccessor values)
132
+ : keys(keys), values(values)
133
+ {}
134
+
135
+ // Pointer-like operations {
136
+ C10_HOST_DEVICE
137
+ reference operator*() const {
138
+ return TupleInfo::tie(*keys, *values);
139
+ }
140
+
141
+ // operator->() is supposed to return a pointer type.
142
+ // Since CompositeRandomAccessor does not hold pointers to pairs,
143
+ // we just return a pointer to a key.
144
+ C10_HOST_DEVICE
145
+ auto* operator->() const {
146
+ return keys.operator->();
147
+ }
148
+
149
+ C10_HOST_DEVICE
150
+ reference operator[](difference_type idx) {
151
+ return operator_brackets_proxy<self_type>(
152
+ CompositeRandomAccessor(keys + idx, values + idx)
153
+ );
154
+ }
155
+ // }
156
+
157
+ // Prefix/postfix increment/decrement {
158
+ C10_HOST_DEVICE
159
+ CompositeRandomAccessor& operator++() {
160
+ ++keys;
161
+ ++values;
162
+ return *this;
163
+ }
164
+
165
+ C10_HOST_DEVICE
166
+ CompositeRandomAccessor operator++(int) {
167
+ CompositeRandomAccessor copy(*this);
168
+ ++*this;
169
+ return copy;
170
+ }
171
+
172
+ C10_HOST_DEVICE
173
+ CompositeRandomAccessor& operator--() {
174
+ --keys;
175
+ --values;
176
+ return *this;
177
+ }
178
+
179
+ C10_HOST_DEVICE
180
+ CompositeRandomAccessor operator--(int) {
181
+ CompositeRandomAccessor copy(*this);
182
+ --*this;
183
+ return copy;
184
+ }
185
+ // }
186
+
187
+ // Arithmetic operations {
188
+ C10_HOST_DEVICE
189
+ CompositeRandomAccessor& operator+=(difference_type offset) {
190
+ keys += offset;
191
+ values += offset;
192
+ return *this;
193
+ }
194
+
195
+ C10_HOST_DEVICE
196
+ CompositeRandomAccessor operator+(difference_type offset) const {
197
+ return CompositeRandomAccessor(keys + offset, values + offset);
198
+ }
199
+
200
+ C10_HOST_DEVICE
201
+ friend CompositeRandomAccessor operator+(
202
+ difference_type offset,
203
+ const CompositeRandomAccessor& accessor
204
+ ) {
205
+ return accessor + offset;
206
+ }
207
+
208
+ C10_HOST_DEVICE
209
+ CompositeRandomAccessor& operator-=(difference_type offset) {
210
+ keys -= offset;
211
+ values -= offset;
212
+ return *this;
213
+ }
214
+
215
+ C10_HOST_DEVICE
216
+ CompositeRandomAccessor operator-(difference_type offset) const {
217
+ return CompositeRandomAccessor(keys - offset, values - offset);
218
+ }
219
+
220
+ C10_HOST_DEVICE
221
+ difference_type operator-(const CompositeRandomAccessor& other) const {
222
+ return keys - other.keys;
223
+ }
224
+ // }
225
+
226
+ // Comparison operators {
227
+ C10_HOST_DEVICE
228
+ bool operator==(const CompositeRandomAccessor& other) const {
229
+ return keys == other.keys;
230
+ }
231
+
232
+ C10_HOST_DEVICE
233
+ bool operator!=(const CompositeRandomAccessor& other) const {
234
+ return keys != other.keys;
235
+ }
236
+
237
+ C10_HOST_DEVICE
238
+ bool operator<(const CompositeRandomAccessor& other) const {
239
+ return keys < other.keys;
240
+ }
241
+
242
+ C10_HOST_DEVICE
243
+ bool operator<=(const CompositeRandomAccessor& other) const {
244
+ return keys <= other.keys;
245
+ }
246
+
247
+ C10_HOST_DEVICE
248
+ bool operator>(const CompositeRandomAccessor& other) const {
249
+ return keys > other.keys;
250
+ }
251
+
252
+ C10_HOST_DEVICE
253
+ bool operator>=(const CompositeRandomAccessor& other) const {
254
+ return keys >= other.keys;
255
+ }
256
+ // }
257
+
258
+ protected:
259
+ KeyAccessor keys;
260
+ ValueAccessor values;
261
+ };
262
+
263
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/ConvUtils.h ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/TensorUtils.h>
4
+ #include <ATen/detail/CUDAHooksInterface.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <c10/util/env.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ namespace at { namespace native {
10
+
11
+ using conv_depthwise2d_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
12
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
13
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 2>);
14
+ DECLARE_DISPATCH(conv_depthwise2d_backward_fn, conv_depthwise2d_backward_stub);
15
+ using conv_depthwise3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
16
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
17
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
18
+ DECLARE_DISPATCH(conv_depthwise3d_backward_fn, conv_depthwise3d_backward_stub);
19
+ using cudnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
20
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
21
+ at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
22
+ DECLARE_DISPATCH(cudnn_convolution_backward_fn, cudnn_convolution_backward_stub);
23
+ using mps_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
24
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
25
+ at::IntArrayRef, int64_t, std::array<bool,3>);
26
+ DECLARE_DISPATCH(mps_convolution_backward_fn, mps_convolution_backward_stub);
27
+ using cudnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
28
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
29
+ at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
30
+ DECLARE_DISPATCH(cudnn_convolution_transpose_backward_fn, cudnn_convolution_transpose_backward_stub);
31
+ using miopen_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
32
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
33
+ at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
34
+ DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_convolution_backward_stub);
35
+ using miopen_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
36
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
37
+ at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
38
+ DECLARE_DISPATCH(miopen_convolution_transpose_backward_fn, miopen_convolution_transpose_backward_stub);
39
+ using miopen_depthwise_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
40
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
41
+ at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
42
+ DECLARE_DISPATCH(miopen_depthwise_convolution_backward_fn, miopen_depthwise_convolution_backward_stub);
43
+ using mkldnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
44
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
45
+ at::IntArrayRef, int64_t, std::array<bool,3>);
46
+ DECLARE_DISPATCH(mkldnn_convolution_backward_fn, mkldnn_convolution_backward_stub);
47
+ using mkldnn_convolution_transpose_fn = Tensor(*)(const Tensor&, const Tensor&, const c10::optional<Tensor>&,
48
+ IntArrayRef, IntArrayRef, IntArrayRef, IntArrayRef, int64_t);
49
+ DECLARE_DISPATCH(mkldnn_convolution_transpose_fn, mkldnn_convolution_transpose_stub);
50
+ using mkldnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
51
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
52
+ at::IntArrayRef, at::IntArrayRef, int64_t, std::array<bool,3>);
53
+ DECLARE_DISPATCH(mkldnn_convolution_transpose_backward_fn, mkldnn_convolution_transpose_backward_stub);
54
+ using slow_conv_dilated2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
55
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
56
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
57
+ DECLARE_DISPATCH(slow_conv_dilated2d_backward_fn, slow_conv_dilated2d_backward_stub);
58
+ using slow_conv_dilated3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
59
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
60
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
61
+ DECLARE_DISPATCH(slow_conv_dilated3d_backward_fn, slow_conv_dilated3d_backward_stub);
62
+ using slow_conv_transpose2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
63
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
64
+ at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
65
+ DECLARE_DISPATCH(slow_conv_transpose2d_backward_fn, slow_conv_transpose2d_backward_stub);
66
+ using slow_conv_transpose3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
67
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
68
+ at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
69
+ DECLARE_DISPATCH(slow_conv_transpose3d_backward_fn, slow_conv_transpose3d_backward_stub);
70
+
71
+ namespace {
72
+ static bool cudnnv8_heuristic_mode_b = c10::utils::check_env("TORCH_CUDNN_USE_HEURISTIC_MODE_B") == true;
73
+ }
74
+
75
+ static inline bool cudnnv8_enabled_check_debug() {
76
+ static bool cudnnv8_flag = c10::utils::check_env("TORCH_CUDNN_V8_API_DISABLED") != true;
77
+ static bool cudnnv8_debug = c10::utils::check_env("TORCH_CUDNN_V8_API_DEBUG") == true;
78
+ static uint8_t cudnnv8_debugcount = 0;
79
+ if (cudnnv8_debug == 1 && cudnnv8_debugcount < 10) {
80
+ TORCH_WARN("TORCH_CUDNN_V8_DEBUG ON, V8 ON: ", cudnnv8_flag, " TORCH_CUDNN_USE_HEURISTIC_MODE B: ", cudnnv8_heuristic_mode_b);
81
+ cudnnv8_debugcount++;
82
+ }
83
+ return cudnnv8_flag == 1;
84
+ }
85
+
86
+ static inline bool cudnnv8_use_heur_mode_b() {
87
+ return cudnnv8_heuristic_mode_b;
88
+ }
89
+
90
+ // Keep in sync with py::enum_ in Module.cpp
91
+ enum class ConvBackend {
92
+ CudaDepthwise2d,
93
+ CudaDepthwise3d,
94
+ Cudnn,
95
+ CudnnTranspose,
96
+ Empty,
97
+ Miopen,
98
+ MiopenDepthwise,
99
+ MiopenTranspose,
100
+ Mkldnn,
101
+ MkldnnTranspose,
102
+ MkldnnEmpty,
103
+ NnpackSpatial,
104
+ Overrideable,
105
+ Slow2d,
106
+ Slow3d,
107
+ SlowDilated2d,
108
+ SlowDilated3d,
109
+ SlowTranspose2d,
110
+ SlowTranspose3d,
111
+ Winograd3x3Depthwise,
112
+ Xnnpack2d,
113
+ Mps,
114
+ MpsTranspose,
115
+ };
116
+
117
+ // Overload for selecting the convolution backend from the full set of convolution inputs.
118
+ // This overload is exposed to python for testing, etc.
119
+ TORCH_API ConvBackend select_conv_backend(
120
+ const Tensor& input, const Tensor& weight, const c10::optional<Tensor>& bias_opt,
121
+ IntArrayRef stride, SymIntArrayRef padding, IntArrayRef dilation,
122
+ bool transposed, SymIntArrayRef output_padding, int64_t groups, const at::OptionalSymIntArrayRef bias_sizes_opt);
123
+
124
+ TORCH_API at::MemoryFormat _determine_backend_memory_format(const Tensor& input,
125
+ const Tensor& weight,
126
+ const ConvBackend backend);
127
+
128
+ // ---------------------------------------------------------------------
129
+ //
130
+ // Math
131
+ //
132
+ // ---------------------------------------------------------------------
133
+
134
+ constexpr int input_batch_size_dim = 0; // also grad_input
135
+ constexpr int input_channels_dim = 1;
136
+ constexpr int output_batch_size_dim = 0; // also grad_output
137
+ constexpr int output_channels_dim = 1;
138
+ constexpr int weight_output_channels_dim = 0;
139
+ constexpr int weight_input_channels_dim = 1;
140
+
141
+ // Often written as 2 + max_dim (extra dims for batch size and channels)
142
+ constexpr int max_dim = 3;
143
+
144
+ // ---------------------------------------------------------------------
145
+ //
146
+ // Checking
147
+ //
148
+ // ---------------------------------------------------------------------
149
+
150
+ // Used on pad, stride and dilation
151
+ static void check_args(CheckedFrom c, IntArrayRef args, size_t expected_size, const char* arg_name)
152
+ {
153
+ TORCH_CHECK(args.size() <= expected_size,
154
+ "Too many ", arg_name, " values (", args.size(), ") supplied, expecting ",
155
+ expected_size, " (while checking arguments for ", c, ")");
156
+ TORCH_CHECK(args.size() >= expected_size,
157
+ "Not enough ", arg_name, " values (", args.size(), ") supplied, expecting ",
158
+ expected_size, " (while checking arguments for ", c, ")");
159
+
160
+ auto num_negative_values = std::count_if(args.begin(), args.end(), [](int x){return x < 0;});
161
+ if (num_negative_values > 0){
162
+ std::stringstream ss;
163
+ ss << arg_name << " should be greater than zero but got (";
164
+ std::copy(args.begin(), args.end() - 1, std::ostream_iterator<int>(ss,", "));
165
+ ss << args.back() << ")" << " (while checking arguments for " << c << ")";
166
+ AT_ERROR(ss.str());
167
+ }
168
+ }
169
+
170
+
171
+ // NOTE [ Convolution checks ]
172
+ //
173
+ // NB: For many call sites, it is not strictly necessary to check all of
174
+ // these relationships (for example, for forward convolution, we compute
175
+ // the size of output ourselves, so we don't actually need to check
176
+ // output. However, writing a single function that does everything
177
+ // means we get to reuse it for both forwards and all backwards
178
+ // variants, even when the set of "real" inputs varies. The magic of
179
+ // relational computing!
180
+ //
181
+ // (There is one downside, which is that it is slightly harder to write
182
+ // error messages which are able to distinguish between real inputs
183
+ // (which the user can change) and computed inputs (which the user can
184
+ // only indirectly affect). It would be an interesting exercise to
185
+ // come up with a general framework to handle such situations.)
186
+ static void convolution_shape_check(
187
+ CheckedFrom c,
188
+ const TensorGeometryArg& input, const TensorGeometryArg& weight, const TensorGeometryArg& output,
189
+ IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups)
190
+ {
191
+ check_args(c, padding, input->dim() - 2, "padding");
192
+ check_args(c, stride, padding.size(), "stride");
193
+ check_args(c, dilation, padding.size(), "dilation");
194
+
195
+ // Input
196
+ checkDimRange(c, input, 3, 6 /* exclusive */);
197
+ checkSize_symint(c, input, input_channels_dim, weight->size(1) * groups);
198
+
199
+ // Weight
200
+ checkSameDim(c, input, weight);
201
+
202
+ // TODO: check that output->size() matches output_sizes
203
+ // TODO: check that weight matches output->sizes()
204
+ checkSameDim(c, input, output);
205
+ }
206
+
207
+ // NB: conv_output_size and conv_input_size are not bijections,
208
+ // as conv_output_size loses information; this is why conv_input_size
209
+ // takes an extra output_padding argument to resolve the ambiguity.
210
+
211
+ template <typename T>
212
+ static inline std::vector<T> _conv_output_size(
213
+ ArrayRef<T> input_size, ArrayRef<T> weight_size,
214
+ ArrayRef<T> padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
215
+ ) {
216
+ // ASSERT(input_size.size() > 2)
217
+ // ASSERT(input_size.size() == weight_size.size())
218
+ bool has_dilation = !dilation.empty();
219
+ auto dim = input_size.size();
220
+ std::vector<T> output_size(dim);
221
+ output_size[0] = input_size[input_batch_size_dim];
222
+ output_size[1] = weight_size[weight_output_channels_dim];
223
+ for (const auto d : c10::irange(2, dim)) {
224
+ auto dilation_ = has_dilation ? dilation[d - 2] : 1;
225
+ auto kernel = dilation_ * (weight_size[d] - 1) + 1;
226
+ output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1;
227
+ }
228
+ return output_size;
229
+ }
230
+
231
+ static inline std::vector<int64_t> conv_output_size(
232
+ IntArrayRef input_size, IntArrayRef weight_size,
233
+ IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
234
+ ) {
235
+ return _conv_output_size(input_size, weight_size, padding, stride, dilation);
236
+ }
237
+
238
+ static inline std::vector<c10::SymInt> conv_output_size(
239
+ SymIntArrayRef input_size, SymIntArrayRef weight_size,
240
+ SymIntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
241
+ ) {
242
+ return _conv_output_size(input_size, weight_size, padding, stride, dilation);
243
+ }
244
+
245
+ template <typename T>
246
+ std::vector<T> _conv_input_size(
247
+ ArrayRef<T> output_size, ArrayRef<T> weight_size,
248
+ ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
249
+ ) {
250
+ // ASSERT(output_size.size() > 2)
251
+ // ASSERT(output_size.size() == weight_size.size())
252
+ auto dim = output_size.size();
253
+ std::vector<T> input_size(dim);
254
+ input_size[0] = output_size[output_batch_size_dim];
255
+ input_size[1] = weight_size[weight_input_channels_dim] * groups;
256
+ for (const auto d : c10::irange(2, dim)) {
257
+ auto kernel = (weight_size[d] - 1) * dilation[d - 2] + 1;
258
+ input_size[d] = (output_size[d] - 1) * stride[d - 2] - (padding[d - 2] * 2) +
259
+ kernel + output_padding[d - 2];
260
+ }
261
+ return input_size;
262
+ }
263
+
264
+ static inline std::vector<c10::SymInt> conv_input_size(
265
+ SymIntArrayRef output_size, SymIntArrayRef weight_size,
266
+ SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
267
+ ) {
268
+ return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
269
+ }
270
+
271
+ static inline std::vector<int64_t> conv_input_size(
272
+ IntArrayRef output_size, IntArrayRef weight_size,
273
+ IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
274
+ ) {
275
+ return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
276
+ }
277
+
278
+ template <typename T>
279
+ std::vector<T> _conv_weight_size(
280
+ ArrayRef<T> input_size, ArrayRef<T> output_size,
281
+ ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
282
+ ) {
283
+ auto dim = input_size.size();
284
+ std::vector<T> weight_size(dim);
285
+ weight_size[0] = output_size[1];
286
+ weight_size[1] = input_size[1] / groups;
287
+ for (const auto d : c10::irange(2, dim)) {
288
+ auto kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2]
289
+ + padding[d - 2] * 2 - output_padding[d - 2];
290
+ weight_size[d] = (kernel - 1) / dilation[d - 2] + 1;
291
+ }
292
+ return weight_size;
293
+ }
294
+
295
+ static inline std::vector<c10::SymInt> conv_weight_size(
296
+ SymIntArrayRef input_size, SymIntArrayRef output_size,
297
+ SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
298
+ ) {
299
+ return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
300
+ }
301
+
302
+ static inline std::vector<int64_t> conv_weight_size(
303
+ IntArrayRef input_size, IntArrayRef output_size,
304
+ IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
305
+ ) {
306
+ return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
307
+ }
308
+
309
+ static inline Tensor reshape_bias(int64_t dim, const Tensor& bias) {
310
+ std::vector<int64_t> shape(dim, 1);
311
+ shape[1] = -1;
312
+ return bias.reshape(shape);
313
+ }
314
+
315
+ static inline at::MemoryFormat cudnn_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) {
316
+ // disable NHWC for float64 input.
317
+ if (!at::detail::getCUDAHooks().compiledWithCuDNN() ||
318
+ input.scalar_type() == at::kDouble ||
319
+ weight.scalar_type() == at::kDouble) {
320
+ return at::MemoryFormat::Contiguous;
321
+ }
322
+ long cudnn_version = at::detail::getCUDAHooks().versionCuDNN();
323
+ auto input_memory_format = input.suggest_memory_format();
324
+ auto weight_memory_format = weight.suggest_memory_format();
325
+ auto weight_ndim = weight.ndimension();
326
+
327
+ bool can_use_cudnn_channels_last_2d = (cudnn_version >= 7603) && (weight_ndim == 4) && (
328
+ (input_memory_format == at::MemoryFormat::ChannelsLast) ||
329
+ (weight_memory_format == at::MemoryFormat::ChannelsLast)
330
+ );
331
+ if (can_use_cudnn_channels_last_2d) {
332
+ return at::MemoryFormat::ChannelsLast;
333
+ }
334
+
335
+ bool can_use_cudnn_channels_last_3d = (cudnn_version >= 8005) && (weight_ndim == 5) && (
336
+ (input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
337
+ (weight_memory_format == at::MemoryFormat::ChannelsLast3d)
338
+ );
339
+ if (can_use_cudnn_channels_last_3d) {
340
+ return at::MemoryFormat::ChannelsLast3d;
341
+ }
342
+
343
+ return at::MemoryFormat::Contiguous;
344
+ }
345
+
346
+ static inline bool miopen_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
347
+ // disable NHWC for float64 input.
348
+ if (!at::detail::getCUDAHooks().compiledWithMIOpen() ||
349
+ input.scalar_type() == at::kDouble ||
350
+ weight.scalar_type() == at::kDouble) {
351
+ return false;
352
+ }
353
+
354
+ auto input_memory_format = input.suggest_memory_format();
355
+ auto weight_memory_format = weight.suggest_memory_format();
356
+
357
+ bool can_use_miopen_channels_last_2d = (
358
+ (input_memory_format == at::MemoryFormat::ChannelsLast) ||
359
+ (weight_memory_format == at::MemoryFormat::ChannelsLast)
360
+ );
361
+
362
+ bool can_use_miopen_channels_last_3d = false;
363
+
364
+ return can_use_miopen_channels_last_2d || can_use_miopen_channels_last_3d;
365
+ }
366
+
367
+ static inline bool mkldnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
368
+
369
+ // disable NHWC for float64 input.
370
+ if (input.scalar_type() == at::kDouble ||
371
+ weight.scalar_type() == at::kDouble) {
372
+ return false;
373
+ }
374
+
375
+ // disable NHWC for MkldnnCPU tensor.
376
+ if (input.is_mkldnn() || weight.is_mkldnn()) {
377
+ return false;
378
+ }
379
+
380
+ auto input_memory_format = input.suggest_memory_format();
381
+ auto weight_memory_format = weight.suggest_memory_format();
382
+
383
+ bool can_use_mkldnn_channels_last_2d =
384
+ (input_memory_format == at::MemoryFormat::ChannelsLast) ||
385
+ (weight_memory_format == at::MemoryFormat::ChannelsLast);
386
+
387
+ // TODO: add channels last 3d support
388
+ bool can_use_mkldnn_channels_last_3d = false;
389
+
390
+ return can_use_mkldnn_channels_last_2d || can_use_mkldnn_channels_last_3d;
391
+ }
392
+
393
+ static inline bool thnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
394
+
395
+ auto input_memory_format = input.suggest_memory_format();
396
+ auto weight_memory_format = weight.suggest_memory_format();
397
+
398
+ bool can_use_thnn_channels_last_2d = input.device().is_cpu() && (
399
+ (input_memory_format == at::MemoryFormat::ChannelsLast) || (
400
+ weight_memory_format == at::MemoryFormat::ChannelsLast));
401
+
402
+ return can_use_thnn_channels_last_2d;
403
+ }
404
+
405
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+
3
+ namespace at {
4
+ namespace native {
5
+
6
+ std::tuple<Tensor, Tensor, Tensor> slow_conv3d_backward_cpu(
7
+ const Tensor& grad_output,
8
+ const Tensor& self,
9
+ const Tensor& weight,
10
+ IntArrayRef kernel_size,
11
+ IntArrayRef stride,
12
+ IntArrayRef padding,
13
+ std::array<bool, 3> output_mask);
14
+
15
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d);
11
+
12
+ DECLARE_DISPATCH(cross_fn, cross_stub);
13
+
14
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <vector>
5
+
6
+ #include <ATen/div_rtn.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \
11
+ TORCH_CHECK( \
12
+ T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \
13
+ "Need " #T " of dimension ", \
14
+ DIM, \
15
+ " and " #T ".size[", \
16
+ DIM_SIZE, \
17
+ "] == ", \
18
+ SIZE, \
19
+ " but got input to be of shape ", \
20
+ T.sizes())
21
+
22
+ namespace at {
23
+ namespace native {
24
+ namespace internal {
25
+ namespace {
26
+ inline bool all_positive(IntArrayRef& arr) {
27
+ return std::all_of(
28
+ arr.begin(), arr.end(), [](int64_t item) { return item > 0; });
29
+ }
30
+
31
+ inline bool all_nonnegative(std::vector<int64_t>& arr) {
32
+ return std::all_of(
33
+ arr.begin(), arr.end(), [](int64_t item) { return item >= 0; });
34
+ }
35
+
36
+ } // namespace
37
+
38
+ // calculate the rear part of output tensor sizes
39
+ template <int64_t dim>
40
+ std::vector<int64_t> get_output_size(
41
+ const Tensor& input,
42
+ IntArrayRef kernel_size,
43
+ IntArrayRef stride_size,
44
+ IntArrayRef pad_size,
45
+ IntArrayRef dilation_size) {
46
+ std::vector<int64_t> sizes;
47
+ for (const auto index : c10::irange(dim)) {
48
+ sizes.push_back(
49
+ div_rtn<int64_t>(
50
+ input.size(index + input.dim() - dim) + 2 * pad_size[index] -
51
+ (dilation_size[index] * (kernel_size[index] - 1) + 1),
52
+ stride_size[index]) +
53
+ 1);
54
+ }
55
+ return sizes;
56
+ }
57
+
58
+ // calculate the sizes of output tensor
59
+ template <int64_t dim>
60
+ std::vector<int64_t> get_output_size(
61
+ const Tensor& input,
62
+ const Tensor& weight,
63
+ IntArrayRef kernel_size,
64
+ IntArrayRef stride_size,
65
+ IntArrayRef pad_size,
66
+ IntArrayRef dilation_size) {
67
+ auto output_size = get_output_size<dim>(
68
+ input, kernel_size, stride_size, pad_size, dilation_size);
69
+ output_size.insert(output_size.begin(), weight.size(0));
70
+ if (input.dim() == dim + 2) {
71
+ output_size.insert(output_size.begin(), input.size(0));
72
+ }
73
+ return output_size;
74
+ }
75
+ /*
76
+ slow_conv_dilated_shape_check - check user-input to dilated convolution
77
+ forward and backward functions.
78
+ */
79
+ template <int64_t dim>
80
+ void slow_conv_dilated_shape_check(
81
+ const Tensor& input,
82
+ const Tensor& weight,
83
+ const Tensor& bias,
84
+ const Tensor& grad_output,
85
+ IntArrayRef kernel_size,
86
+ IntArrayRef stride_size,
87
+ IntArrayRef pad_size,
88
+ IntArrayRef dilation_size) {
89
+ /*
90
+ When the following tensors are defined:
91
+
92
+ bias, grad_weight, grad_output
93
+
94
+ then these are assumed to be contiguous without checking
95
+ because of these tensors are made contiguous by calling
96
+ .contiguous() method or by resizing of zero-sized tensors in
97
+ forward/backward functions.
98
+
99
+ When grad_weight is defined then it is assumed without
100
+ checking to have the same shape as weight, see backward
101
+ functions.
102
+ */
103
+ // Check size arguments
104
+ TORCH_CHECK(
105
+ kernel_size.size() == dim,
106
+ "kernel sizes length should be ",
107
+ dim,
108
+ ", but got ",
109
+ kernel_size.size());
110
+ TORCH_CHECK(
111
+ stride_size.size() == dim,
112
+ "strides length should be ",
113
+ dim,
114
+ ", but got ",
115
+ stride_size.size());
116
+ TORCH_CHECK(
117
+ dilation_size.size() == dim,
118
+ "dilations length should be ",
119
+ dim,
120
+ ", but got ",
121
+ dilation_size.size());
122
+ TORCH_CHECK(
123
+ pad_size.size() == dim,
124
+ "pads length should be ",
125
+ dim,
126
+ ", but got ",
127
+ pad_size.size());
128
+
129
+ TORCH_CHECK(
130
+ all_positive(kernel_size),
131
+ "kernel size should be greater than zero, but got ",
132
+ kernel_size);
133
+ TORCH_CHECK(
134
+ all_positive(stride_size),
135
+ "stride should be greater than zero, but got ",
136
+ stride_size);
137
+ TORCH_CHECK(
138
+ all_positive(dilation_size),
139
+ "dilation should be greater than zero, but got ",
140
+ dilation_size);
141
+
142
+ // check input
143
+ TORCH_CHECK(input.defined(), "input must be defined");
144
+ bool is_batch = input.dim() == dim + 2;
145
+ int64_t n = (is_batch ? 2 : 1);
146
+ int64_t ndim = n + dim;
147
+ if (!is_batch) {
148
+ // input dim has to be dim + 1 if not batched
149
+ TORCH_CHECK(
150
+ input.dim() == dim + 1,
151
+ "input must be 4D or 5D tensor but got ",
152
+ input.dim(),
153
+ "D tensor");
154
+ }
155
+
156
+ // check output sizes
157
+ auto output_size = get_output_size<dim>(
158
+ input, kernel_size, stride_size, pad_size, dilation_size);
159
+
160
+ TORCH_CHECK(
161
+ all_nonnegative(output_size),
162
+ "calculated output size ",
163
+ output_size,
164
+ " is too small (all sizes must be non-negative)");
165
+
166
+ // check weight
167
+ TORCH_CHECK(weight.defined(), "weight must be defined");
168
+ TORCH_CHECK(
169
+ weight.dim() == dim + 2,
170
+ "weight must be ",
171
+ dim + 2,
172
+ "D tensor but got ",
173
+ weight.dim(),
174
+ "D tensor dim=",
175
+ dim);
176
+ TORCH_CHECK(
177
+ weight.sizes().slice(2) == kernel_size,
178
+ "weight[2:] shape ",
179
+ weight.sizes().slice(2),
180
+ " must be equal to kernel_size ",
181
+ kernel_size);
182
+
183
+ TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1));
184
+
185
+ // check bias when present
186
+ if (bias.defined()) {
187
+ TORCH_CHECK(
188
+ bias.dim() == 1,
189
+ "bias must be 1D tensor but got ",
190
+ bias.dim(),
191
+ "D tensor");
192
+ TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0));
193
+ }
194
+
195
+ // check grad_output when present
196
+ if (grad_output.defined()) {
197
+ TORCH_CHECK(
198
+ grad_output.dim() == ndim,
199
+ "grad_output must be ",
200
+ ndim,
201
+ "D tensor but got ",
202
+ grad_output.dim(),
203
+ "D tensor");
204
+ if (is_batch) {
205
+ TORCH_CHECK(
206
+ grad_output.size(0) == input.size(0),
207
+ "grad_output.size(0)=",
208
+ grad_output.size(0),
209
+ " must be input.size(0)=",
210
+ input.size(0));
211
+ }
212
+ TORCH_CHECK(
213
+ grad_output.size(n - 1) == weight.size(0),
214
+ "grad_output.size(",
215
+ n - 1,
216
+ ")=",
217
+ grad_output.size(n - 1),
218
+ " must be weight.size(0)=",
219
+ weight.size(0));
220
+ TORCH_CHECK(
221
+ grad_output.sizes().slice(n) == output_size,
222
+ "grad_output[",
223
+ n,
224
+ ":] shape",
225
+ grad_output.sizes().slice(n),
226
+ " must be equal to output size ",
227
+ output_size);
228
+ }
229
+ }
230
+
231
+ } // namespace internal
232
+ } // namespace native
233
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Distance.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using pdist_forward_fn = void(*)(Tensor&, const Tensor&, const double p);
11
+ using pdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
12
+ using cdist_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p);
13
+ using cdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
14
+
15
+ DECLARE_DISPATCH(pdist_forward_fn, pdist_forward_stub);
16
+ DECLARE_DISPATCH(pdist_backward_fn, pdist_backward_stub);
17
+ DECLARE_DISPATCH(cdist_fn, cdist_stub);
18
+ DECLARE_DISPATCH(cdist_backward_fn, cdist_backward_stub);
19
+
20
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/Generator.h>
6
+ #include <ATen/ExpandUtils.h>
7
+ #include <ATen/Tensor.h>
8
+ #include <ATen/MemoryOverlap.h>
9
+ #include <ATen/NamedTensorUtils.h>
10
+ #include <ATen/native/Resize.h>
11
+ #include <ATen/native/TensorIterator.h>
12
+ #include <c10/util/Optional.h>
13
+ #include <limits>
14
+ #include <cmath>
15
+
16
+ #ifndef AT_PER_OPERATOR_HEADERS
17
+ #include <ATen/Functions.h>
18
+ #else
19
+ #include <ATen/ops/empty_like.h>
20
+ #include <ATen/ops/empty.h>
21
+ #include <ATen/ops/full.h>
22
+ #include <ATen/ops/view_as_real.h>
23
+ #endif
24
+
25
+ namespace at {
26
+ namespace native {
27
+ namespace templates {
28
+
29
+ // ==================================================== Random ========================================================
30
+
31
+ // The purpose of `update_from` and `update_to` is to find the closest valid int64_t number that can be used as actual `from`.
32
+ // The current implementation of `random_` uses uint64_t arithmetics and casts the result to the target dtype(scalar_t).
33
+ // This casting can result in generating numbers that happen to be greater or equal to `to` value. For instance:
34
+ //
35
+ // auto actual = torch::empty({3, 3}, torch::half);
36
+ // actual.random_(0, 65504);
37
+ //
38
+ // If random's uint64_t arithmetics produces 65503 as a random value after casting to torch::half it becomes 65504
39
+ // and violates the requirement that random value must be less than `to`. To resolve this issue `update_from` and `update_to`
40
+ // moves `from` to the right and `to` to the left to the next closest value that won't go outside [from, to) after casting to
41
+ // the target dtype. For `to` = 65504 it moves left for (1 << (log2(to) - 11 + 1)) = 32 and becomes 65472, which is previous
42
+ // available number for torch::half dtype.
43
+ template<typename scalar_t>
44
+ int64_t update_from(int64_t from) {
45
+ static_assert(
46
+ std::is_floating_point<scalar_t>::value ||
47
+ std::is_same<scalar_t, at::Half>::value ||
48
+ std::is_same<scalar_t, at::BFloat16>::value, "scalar_t must be floating-point type");
49
+ const auto from_plus_1 = static_cast<int64_t>(static_cast<scalar_t>(from + 1));
50
+ if (from_plus_1 < from) {
51
+ int64_t from_ = std::abs(from + 1);
52
+ int n = 0;
53
+ while (from_ >>= 1) ++n;
54
+ // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
55
+ from = from_plus_1 + (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
56
+ }
57
+ return from;
58
+ }
59
+
60
+ template<typename scalar_t>
61
+ int64_t update_to(int64_t to) {
62
+ static_assert(
63
+ std::is_floating_point<scalar_t>::value ||
64
+ std::is_same<scalar_t, at::Half>::value ||
65
+ std::is_same<scalar_t, at::BFloat16>::value, "scalar_t must be floating-point type");
66
+ const auto to_minus_1 = static_cast<int64_t>(static_cast<scalar_t>(to - 1));
67
+ if (to_minus_1 >= to) {
68
+ int64_t to_ = std::abs(to - 1);
69
+ int n = 0;
70
+ while (to_ >>= 1) ++n;
71
+ // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
72
+ to = to_minus_1 - (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
73
+ }
74
+ return to;
75
+ }
76
+
77
+ template<template<typename> class random_kernel, typename RNG>
78
+ at::Tensor& random_impl(at::Tensor& self, c10::optional<Generator> generator) {
79
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
80
+ random_kernel<RNG>()(iter, generator);
81
+ return self;
82
+ }
83
+
84
+ #define CHECK_OUT_OF_BOUNDS(var, name, min, max, dtype) \
85
+ TORCH_CHECK(var >= min && var <= max, name , " is out of bounds for ", dtype); \
86
+
87
+ #define WARN_OUT_OF_BOUNDS(var, name, digits, dtype) \
88
+ if (var < -(1LL << digits) || var > (1LL << digits)) { \
89
+ TORCH_WARN(name , " is out of bounds [-(2^", digits, "), 2^", digits, "]. ", \
90
+ "Due to precision limitations ", dtype, " can support discrete uniform distribution only within this range. ", \
91
+ "This warning will become an error in version 1.7 release, please fix the code in advance"); \
92
+ }
93
+
94
+ static void check_from_to_in_range(int64_t from, int64_t to_inc, caffe2::TypeMeta dtype) {
95
+ const auto scalar_type = typeMetaToScalarType(dtype);
96
+ if (isFloatingType(scalar_type)) {
97
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, scalar_type, "check_random_fp_bounds", [&] {
98
+ const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
99
+ const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
100
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
101
+ CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
102
+
103
+ constexpr auto digits = std::numeric_limits<scalar_t>::digits;
104
+ WARN_OUT_OF_BOUNDS(from, "from", digits, dtype);
105
+ WARN_OUT_OF_BOUNDS(to_inc, "to - 1", digits, dtype);
106
+ });
107
+ } else if (isIntegralType(scalar_type, /*includeBool=*/true)) {
108
+ AT_DISPATCH_INTEGRAL_TYPES_AND(at::ScalarType::Bool, scalar_type, "check_random_integral_bounds", [&]() {
109
+ const auto min = static_cast<int64_t>(std::numeric_limits<scalar_t>::lowest());
110
+ const auto max = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
111
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
112
+ CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
113
+ });
114
+ } else {
115
+ TORCH_CHECK(false, "check_random_bounds handles only integral, floating-point and boolean types");
116
+ }
117
+ }
118
+
119
+ template<template<typename> class random_from_to_kernel, typename RNG>
120
+ at::Tensor& random_from_to_impl(at::Tensor& self, int64_t from, c10::optional<int64_t> to_opt, c10::optional<Generator> generator) {
121
+ uint64_t range = 0;
122
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
123
+ if (to_opt.has_value()) {
124
+ // [from, to)
125
+ int64_t to = *to_opt;
126
+ TORCH_CHECK(from < to, "random_ expects 'from' to be less than 'to', but got from=", from, " >= to=", to);
127
+ if (isFloatingType(iter.dtype())) {
128
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_update_from_to", [&] {
129
+ from = update_from<scalar_t>(from);
130
+ to = update_to<scalar_t>(to);
131
+ TORCH_CHECK(from < to, "random_ expects 'from' casted to dtype to be less than 'to' casted to dtype, but got from=", from, " >= to=", to);
132
+ });
133
+ }
134
+ check_from_to_in_range(from, to - 1, self.dtype());
135
+ range = static_cast<uint64_t>(to) - static_cast<uint64_t>(from);
136
+ random_from_to_kernel<RNG>()(iter, range, from, generator);
137
+ } else if (from != std::numeric_limits<int64_t>::lowest()) {
138
+ // [from, std::numeric_limits<int64_t>::max()]
139
+ int64_t to_inc = 0;
140
+ if (isFloatingType(iter.dtype())) {
141
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_from_to_range_calc", [&] {
142
+ constexpr int64_t scalar_t_max = static_cast<int64_t>(1) << std::numeric_limits<scalar_t>::digits;
143
+ to_inc = scalar_t_max > std::numeric_limits<int64_t>::max() ? std::numeric_limits<int64_t>::max() : static_cast<int64_t>(scalar_t_max);
144
+ from = update_from<scalar_t>(from);
145
+ TORCH_CHECK(from < to_inc, "random_ expects 'from' casted to dtype to be less than or equal to 'to_inc' casted to dtype, but got from=", from, " > to_inc=", to_inc);
146
+ });
147
+ } else if (isIntegralType(iter.dtype(), /*includeBool=*/true)) {
148
+ AT_DISPATCH_INTEGRAL_TYPES_AND(at::ScalarType::Bool, self.scalar_type(), "random_from_to_range_calc", [&] {
149
+ if (std::is_same<scalar_t, bool>::value) {
150
+ to_inc = static_cast<int64_t>(true);
151
+ } else {
152
+ to_inc = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
153
+ }
154
+ });
155
+ } else {
156
+ TORCH_CHECK(false, "random_from_to_impl handles only integral, floating-point and boolean types");
157
+ }
158
+ check_from_to_in_range(from, to_inc, self.dtype());
159
+ range = static_cast<uint64_t>(to_inc) - static_cast<uint64_t>(from) + 1;
160
+ random_from_to_kernel<RNG>()(iter, range, from, generator);
161
+ } else {
162
+ // [std::numeric_limits<int64_t>::lowest(), std::numeric_limits<int64_t>::max()]
163
+ // range = 2^64
164
+ random_from_to_kernel<RNG>()(iter, generator);
165
+ }
166
+ return self;
167
+ }
168
+
169
+ // ==================================================== Normal ========================================================
170
+
171
+ #define CHECK_NORMAL_TENSOR_STD(std) \
172
+ do { \
173
+ TORCH_CHECK( \
174
+ !std.is_complex(), \
175
+ "normal expects standard deviation to be non-complex"); \
176
+ TORCH_CHECK( \
177
+ std.numel() == 0 || std.is_meta() || std.min().ge(0).item<bool>(), \
178
+ "normal expects all elements of std >= 0.0"); \
179
+ } while (0)
180
+
181
+ #define CHECK_NORMAL_STD(std) \
182
+ TORCH_CHECK(std >= 0.0, "normal expects std >= 0.0, but found std ", std);
183
+
184
+ template<template<typename> class normal_kernel, typename RNG>
185
+ Tensor& normal_impl_(Tensor& self, double mean, double std, c10::optional<Generator> gen) {
186
+ CHECK_NORMAL_STD(std);
187
+ if (self.is_complex()) {
188
+ auto float_tensor = at::view_as_real(self);
189
+ // variance for normal distribution of the real and imaginary values
190
+ // is half of the input variance
191
+ normal_kernel<RNG>()(float_tensor, mean, std/(std::sqrt(2)), gen);
192
+ } else {
193
+ normal_kernel<RNG>()(self, mean, std, gen);
194
+ }
195
+ return self;
196
+ }
197
+
198
+ template<template<typename> class normal_kernel, typename RNG>
199
+ Tensor& normal_out_impl(Tensor& output, const Tensor& mean, double std, c10::optional<Generator> gen) {
200
+ CHECK_NORMAL_STD(std);
201
+ auto std_tensor = at::empty_like(output, MemoryFormat::Contiguous);
202
+ auto shape = at::infer_size(mean.sizes(), std_tensor.sizes());
203
+ at::native::resize_output(output, shape);
204
+ normal_impl_<normal_kernel, RNG>(output, 0, std, gen);
205
+ output.add_(mean);
206
+ return output;
207
+ }
208
+
209
+ template<template<typename> class normal_kernel, typename RNG>
210
+ Tensor& normal_out_impl(Tensor& output, double mean, const Tensor& std, c10::optional<Generator> gen) {
211
+ CHECK_NORMAL_TENSOR_STD(std);
212
+ auto mean_tensor = at::full({}, mean, output.options());
213
+ auto shape = at::infer_size(mean_tensor.sizes(), std.sizes());
214
+ at::native::resize_output(output, shape);
215
+ normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
216
+ // CUDA NB: addcmul_out copies the tensor to be added into the output.
217
+ // The previous function here was addcmul_out(output, mean_tensor, output, std, 1);
218
+ // The third argument is not a constant reference and hence the samples in output are overwritten.
219
+ // Consequently, the computation performed is mean_tensor + mean_tensor * std instead of mean_tensor + output * std
220
+ output.mul_(std).add_(mean_tensor);
221
+ return output;
222
+ }
223
+
224
+ template<template<typename> class normal_kernel, typename RNG>
225
+ Tensor& normal_out_impl(Tensor& output, const Tensor& mean, const Tensor& std, c10::optional<Generator> gen) {
226
+ CHECK_NORMAL_TENSOR_STD(std);
227
+ auto shape = at::infer_size(mean.sizes(), std.sizes());
228
+ at::native::resize_output(output, shape);
229
+ normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
230
+ // CUDA NB: addcmul_out copies the tensor to be added into the output.
231
+ // The previous function here was addcmul_out(output, mean, output, std, 1);
232
+ // The third argument is not a constant reference and hence the samples in output are overwritten.
233
+ // Consequently, the computation performed is mean + mean * std instead of mean + output * std
234
+ output.mul_(std).add_(mean);
235
+ return output;
236
+ }
237
+
238
+ template<template<typename> class normal_kernel, typename RNG>
239
+ Tensor normal_impl(const Tensor& mean, double std, c10::optional<Generator> gen) {
240
+ CHECK_NORMAL_STD(std);
241
+ Tensor ret = at::empty_like(mean, MemoryFormat::Contiguous);
242
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
243
+ return ret;
244
+ }
245
+
246
+ template<template<typename> class normal_kernel, typename RNG>
247
+ Tensor normal_impl(double mean, const Tensor& std, c10::optional<Generator> gen) {
248
+ CHECK_NORMAL_TENSOR_STD(std);
249
+ Tensor ret = at::empty_like(std, MemoryFormat::Contiguous);
250
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
251
+ return ret;
252
+ }
253
+
254
+ template<template<typename> class normal_kernel, typename RNG>
255
+ Tensor normal_impl(const Tensor& mean, const Tensor& std, c10::optional<Generator> gen) {
256
+ CHECK_NORMAL_TENSOR_STD(std);
257
+ auto shape = at::infer_size(mean.sizes(), std.sizes());
258
+ Tensor ret = at::empty(shape, mean.options(), MemoryFormat::Contiguous);
259
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
260
+ return ret;
261
+ }
262
+
263
+ // ==================================================== Uniform =======================================================
264
+
265
+ template<template<typename> class uniform_kernel, typename RNG>
266
+ at::Tensor& uniform_impl_(at::Tensor& self, double from, double to, c10::optional<Generator> generator) {
267
+ if (self.is_complex()) {
268
+ auto float_tensor = at::view_as_real(self);
269
+ uniform_impl_<uniform_kernel, RNG>(float_tensor, from, to, generator);
270
+ } else {
271
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "check_uniform_bounds", [&] {
272
+ const auto dtype = self.dtype();
273
+ const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
274
+ const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
275
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
276
+ CHECK_OUT_OF_BOUNDS(to, "to", min, max, dtype);
277
+ TORCH_CHECK(from <= to, "uniform_ expects to return a [from, to) range, but found from=", from, " > to=", to);
278
+ TORCH_CHECK((to - from) <= std::numeric_limits<scalar_t>::max(),
279
+ "uniform_ expects to-from <= std::numeric_limits<", toString(self.scalar_type()),
280
+ ">::max(), but found to=", to, " and from=", from,
281
+ " which result in to-from to exceed the limit");
282
+ from = std::min(std::max(from, min), max);
283
+ to = std::max(std::min(to, max), min);
284
+ });
285
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
286
+ uniform_kernel<RNG>()(iter, from, to, generator);
287
+ }
288
+ return self;
289
+ }
290
+
291
+ // ================================================== LogNormal =======================================================
292
+
293
+ template<template<typename> class log_normal_kernel, typename RNG>
294
+ at::Tensor& log_normal_impl_(at::Tensor& self, double mean, double std, c10::optional<Generator> gen) {
295
+ TORCH_CHECK(std > 0.0, "log_normal_ expects std > 0.0, but found std=", std);
296
+ auto iter = TensorIterator::borrowing_nullary_op(self);
297
+ log_normal_kernel<RNG>()(iter, mean, std, gen);
298
+ return self;
299
+ }
300
+
301
+ // =================================================== Geometric ======================================================
302
+
303
+ template<template<typename> class geometric_kernel, typename RNG>
304
+ Tensor& geometric_impl_(Tensor& self, double p, c10::optional<Generator> gen) {
305
+ TORCH_CHECK(0 < p && p < 1, "geometric_ expects p to be in (0, 1), but got p=", p);
306
+ auto iter = TensorIterator::borrowing_nullary_op(self);
307
+ geometric_kernel<RNG>()(iter, p, gen);
308
+ return self;
309
+ }
310
+
311
+ // ================================================== Exponential =====================================================
312
+
313
+ template<template<typename> class exponential_kernel, typename RNG>
314
+ Tensor& exponential_impl_(Tensor& self, double lambda, c10::optional<Generator> gen) {
315
+ TORCH_CHECK(lambda > 0.0, "exponential_ expects lambda > 0.0, but found lambda=", lambda);
316
+ auto iter = TensorIterator::borrowing_nullary_op(self);
317
+ exponential_kernel<RNG>()(iter, lambda, gen);
318
+ return self;
319
+ }
320
+
321
+ // ==================================================== Cauchy ========================================================
322
+
323
+ template<template<typename> class cauchy_kernel, typename RNG>
324
+ Tensor& cauchy_impl_(Tensor& self, double median, double sigma, c10::optional<Generator> gen) {
325
+ // TODO: instead of variable name 'sigma', use 'gamma' or 'scale'
326
+ // the variance, squared sigma, is undefined for cauchy distribution
327
+ TORCH_CHECK(sigma > 0.0, "cauchy_ expects sigma > 0.0, but found sigma=", sigma);
328
+ TORCH_CHECK(at::isFloatingType(self.scalar_type()), "Cauchy distribution is a continuous probability distribution. dtype must be a floating point but you specified ", self.dtype());
329
+ auto iter = TensorIterator::borrowing_nullary_op(self);
330
+ cauchy_kernel<RNG>()(iter, median, sigma, gen);
331
+ return self;
332
+ }
333
+
334
+ // ==================================================== Bernoulli =====================================================
335
+
336
+ template<template<typename> class bernoulli_tensor_kernel, typename RNG>
337
+ Tensor& bernoulli_impl_(Tensor& self, const Tensor& p_, c10::optional<Generator> gen) {
338
+ NoNamesGuard guard;
339
+ at::assert_no_internal_overlap(self);
340
+ bernoulli_tensor_kernel<RNG>()(self, p_, gen);
341
+ return self;
342
+ }
343
+
344
+ template<template<typename> class bernoulli_scalar_kernel, typename RNG>
345
+ Tensor& bernoulli_impl_(Tensor& self, double p, c10::optional<Generator> gen) {
346
+ TORCH_CHECK(0 <= p && p <= 1, "bernoulli_ expects p to be in [0, 1], but got p=", p);
347
+ at::assert_no_internal_overlap(self);
348
+ bernoulli_scalar_kernel<RNG>()(self, p, gen);
349
+ return self;
350
+ }
351
+
352
+ template<template<typename> class bernoulli_tensor_kernel, typename RNG>
353
+ Tensor& bernoulli_out_impl(Tensor& result, const Tensor& self, c10::optional<Generator> gen) {
354
+ // result.resize_as_(self) requires self to have same dtype as result, so we
355
+ // use resize_ instead.
356
+ // TODO: Fix resize_as_. See pytorch/pytorch#11665.
357
+ result.resize_(self.sizes());
358
+ bernoulli_impl_<bernoulli_tensor_kernel, RNG>(result, self, gen);
359
+ namedinference::propagate_names(result, self);
360
+ return result;
361
+ }
362
+
363
+ #undef CHECK_OUT_OF_BOUNDS
364
+ #undef WARN_OUT_OF_BOUNDS
365
+
366
+ }}}
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Distributions.h ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/Math.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/MathConstants.h>
6
+
7
+ // ROCM hcc doesn't work well with using std:: in kernel functions
8
+ #if defined(__CUDA_ARCH__)
9
+ #include <c10/cuda/CUDAMathCompat.h>
10
+ #define compat_exp c10::cuda::compat::exp
11
+ #define compat_ceil c10::cuda::compat::ceil
12
+ #define compat_floor c10::cuda::compat::floor
13
+ #define compat_log c10::cuda::compat::log
14
+ #define compat_pow c10::cuda::compat::pow
15
+ #define compat_sqrt c10::cuda::compat::sqrt
16
+ #define compat_tan c10::cuda::compat::tan
17
+ #define compat_abs c10::cuda::compat::abs
18
+ #define compat_log1p c10::cuda::compat::log1p
19
+ #elif defined(__HIPCC__)
20
+ #include <c10/hip/HIPMathCompat.h>
21
+ #define compat_exp c10::hip::compat::exp
22
+ #define compat_ceil c10::hip::compat::ceil
23
+ #define compat_floor c10::hip::compat::floor
24
+ #define compat_log c10::hip::compat::log
25
+ #define compat_pow c10::hip::compat::pow
26
+ #define compat_sqrt c10::hip::compat::sqrt
27
+ #define compat_tan c10::hip::compat::tan
28
+ #define compat_abs c10::hip::compat::abs
29
+ #define compat_log1p c10::hip::compat::log1p
30
+ #else
31
+ #define compat_exp std::exp
32
+ #define compat_ceil std::ceil
33
+ #define compat_floor std::floor
34
+ #define compat_log std::log
35
+ #define compat_pow std::pow
36
+ #define compat_sqrt std::sqrt
37
+ #define compat_tan std::tan
38
+ #define compat_abs std::abs
39
+ #define compat_log1p std::log1p
40
+ #endif
41
+
42
+ namespace {
43
+
44
+ #if !defined(__CUDA_ARCH__) && !defined(__HIPCC__)
45
+ // we cannot use std::isnan directly due to some incompatibility of
46
+ // gcc constexpr'ing and nvcc
47
+ using std::isnan;
48
+ #endif
49
+
50
+ // Here sampler_t should be function type scalar_t(void). For gpu
51
+ // "sampler" is a device function, but since ROCM doesn't have
52
+ // equivalent to nvstd::function, we use a template type parameter to
53
+ // capture it.
54
+ template<typename scalar_t, typename sampler_t>
55
+ struct BaseSampler {
56
+ sampler_t sampler;
57
+ C10_DEVICE BaseSampler(const sampler_t& sampler): sampler(sampler) {}
58
+ C10_DEVICE scalar_t sample() {
59
+ return sampler();
60
+ }
61
+ };
62
+
63
+ // The function `sample_gamma` is
64
+ // is adapted from Numpy's distributions.c implementation.
65
+ // It is MIT licensed, so here is the copyright:
66
+
67
+ /* Copyright 2005 Robert Kern (robert.kern@gmail.com)
68
+ *
69
+ * Permission is hereby granted, free of charge, to any person obtaining a
70
+ * copy of this software and associated documentation files (the
71
+ * "Software"), to deal in the Software without restriction, including
72
+ * without limitation the rights to use, copy, modify, merge, publish,
73
+ * distribute, sublicense, and/or sell copies of the Software, and to
74
+ * permit persons to whom the Software is furnished to do so, subject to
75
+ * the following conditions:
76
+ *
77
+ * The above copyright notice and this permission notice shall be included
78
+ * in all copies or substantial portions of the Software.
79
+ *
80
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
81
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
82
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
83
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
84
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
85
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
86
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87
+ */
88
+
89
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t, typename normal_sampler_t>
90
+ C10_DEVICE scalar_t sample_gamma(scalar_t alpha, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform, BaseSampler<accscalar_t, normal_sampler_t>& standard_normal) {
91
+ accscalar_t scale = 1.0f;
92
+
93
+ // Boost alpha for higher acceptance probability.
94
+ if (alpha < 1.0f) {
95
+ if (alpha == 0.f) return 0.f;
96
+ scale *= compat_pow(1 - standard_uniform.sample(), 1.0f / alpha);
97
+ alpha += 1.0f;
98
+ }
99
+
100
+ // This implements the acceptance-rejection method of Marsaglia and Tsang (2000)
101
+ // doi:10.1145/358407.358414
102
+ const accscalar_t d = alpha - 1.0f / 3.0f;
103
+ const accscalar_t c = 1.0f / compat_sqrt(9.0f * d);
104
+ for (;;) {
105
+ accscalar_t x, y;
106
+ do {
107
+ x = standard_normal.sample();
108
+ y = 1.0f + c * x;
109
+ } while (y <= 0);
110
+ const accscalar_t v = y * y * y;
111
+ const accscalar_t u = 1 - standard_uniform.sample();
112
+ const accscalar_t xx = x * x;
113
+ if (u < 1.0f - 0.0331f * xx * xx)
114
+ return static_cast<scalar_t>(scale * d * v);
115
+ if (compat_log(u) < 0.5f * xx + d * (1.0f - v + compat_log(v)))
116
+ return static_cast<scalar_t>(scale * d * v);
117
+ }
118
+ }
119
+
120
+ /* the functions stirling_approx_tail, binomial_inversion, and btrs are adapted
121
+ * from TensorFlow's random_binomial_op.cc implementation. That code is under
122
+ * copyright: 2019 The TensorFlow Authors.
123
+ *
124
+ * It was released under the Apache License, Version 2.0 (the "License"), available at:
125
+ * http://www.apache.org/licenses/LICENSE-2.0
126
+ */
127
+
128
+ template<typename scalar_t>
129
+ C10_DEVICE scalar_t stirling_approx_tail(scalar_t k) {
130
+ const static scalar_t kTailValues[] = {
131
+ 0.0810614667953272,
132
+ 0.0413406959554092,
133
+ 0.0276779256849983,
134
+ 0.02079067210376509,
135
+ 0.0166446911898211,
136
+ 0.0138761288230707,
137
+ 0.0118967099458917,
138
+ 0.0104112652619720,
139
+ 0.00925546218271273,
140
+ 0.00833056343336287
141
+ };
142
+ if (k <= 9) {
143
+ return kTailValues[static_cast<size_t>(k)];
144
+ }
145
+ scalar_t kp1sq = (k + 1) * (k + 1);
146
+ return (1.0 / 12 - (1.0 / 360 - 1.0 / 1260 / kp1sq) / kp1sq) / (k + 1);
147
+ }
148
+
149
+
150
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
151
+ C10_DEVICE scalar_t binomial_inversion(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
152
+ accscalar_t U;
153
+ accscalar_t geom_sum = 0;
154
+ scalar_t num_geom = 0;
155
+
156
+ accscalar_t logprob = compat_log1p(-prob);
157
+
158
+ while (1) {
159
+ U = standard_uniform.sample();
160
+ accscalar_t geom = compat_ceil(compat_log(U) / logprob);
161
+ geom_sum += geom;
162
+ if (geom_sum > count) {
163
+ break;
164
+ }
165
+ num_geom = num_geom + 1;
166
+ }
167
+ return num_geom;
168
+ }
169
+
170
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
171
+ C10_DEVICE scalar_t btrs(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
172
+ scalar_t k;
173
+ accscalar_t U, V, us;
174
+
175
+ // This is spq in the paper.
176
+ const accscalar_t stddev = compat_sqrt(count * prob * (1 - prob));
177
+
178
+ // Other coefficients for Transformed Rejection sampling.
179
+ const accscalar_t b = 1.15 + 2.53 * stddev;
180
+ const accscalar_t a = -0.0873 + 0.0248 * b + 0.01 * prob;
181
+ const accscalar_t c = count * prob + 0.5;
182
+ const accscalar_t v_r = 0.92 - 4.2 / b;
183
+ const accscalar_t r = prob / (1 - prob);
184
+
185
+ const accscalar_t alpha = (2.83 + 5.1 / b) * stddev;
186
+ const accscalar_t m = compat_floor((count + 1) * prob);
187
+
188
+ while (1) {
189
+ U = standard_uniform.sample() - 0.5;
190
+ V = standard_uniform.sample();
191
+
192
+ us = 0.5 - compat_abs(U);
193
+ k = static_cast<scalar_t>(compat_floor((2 * a / us + b) * U + c));
194
+
195
+ // Reject non-sensical answers.
196
+ if (k < 0 || k > count) {
197
+ continue;
198
+ }
199
+ // Region for which the box is tight, and we can return our calculated value.
200
+ // This should happen 0.86 * v_r times. In the limit as n * p is large,
201
+ // the acceptance rate converges to ~79% (and in the lower regime it is ~24%).
202
+ if (us >= 0.07 && V <= v_r) {
203
+ return k;
204
+ }
205
+
206
+ // This deviates from Hormann's BTRS algorithm, as there is a log missing.
207
+ // For all (u, v) pairs outside of the bounding box, this calculates the
208
+ // transformed-reject ratio.
209
+ V = compat_log(V * alpha / (a / (us * us) + b));
210
+ accscalar_t upperbound =
211
+ ((m + 0.5) * compat_log((m + 1) / (r * (count - m + 1))) +
212
+ (count + 1) * compat_log((count - m + 1) / (count - k + 1)) +
213
+ (k + 0.5) * compat_log(r * (count - k + 1) / (k + 1)) +
214
+ stirling_approx_tail<accscalar_t>(m) + stirling_approx_tail<accscalar_t>(count - m) -
215
+ stirling_approx_tail<accscalar_t>(k) - stirling_approx_tail<accscalar_t>(count - k));
216
+
217
+ if (V <= upperbound) {
218
+ return k;
219
+ }
220
+ }
221
+ }
222
+
223
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
224
+ C10_DEVICE scalar_t sample_binomial(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
225
+ if (count <= 0.0 || prob <= 0.0) {
226
+ return 0;
227
+ } else if (prob >= 1.0) {
228
+ return count;
229
+ } else if (prob <= 0.5) {
230
+ if (count * prob >= 10.0) {
231
+ // btrs
232
+ return btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
233
+ } else {
234
+ // binomial inversion
235
+ return binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
236
+ }
237
+ } else if (prob > 0.5) {
238
+ scalar_t qprob = 1.0 - prob;
239
+ if (count * qprob >= 10.0) {
240
+ // btrs
241
+ return count - btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
242
+ } else {
243
+ // count - binomial inversion
244
+ return count - binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
245
+ }
246
+ } else {
247
+ // prob is nan?
248
+ return static_cast<scalar_t>(NAN);
249
+ }
250
+ }
251
+
252
+ /*
253
+ * This function is derived from the implementation of the digamma function in the Cephes Math Library.
254
+ * See note [3-Clause BSD License for the Cephes Math Library] in ATen/native/Math.h.
255
+ */
256
+ template<typename scalar_t, typename accscalar_t>
257
+ C10_DEVICE static inline scalar_t digamma_one(scalar_t x) {
258
+ constexpr accscalar_t PSI_10 = 2.25175258906672110764;
259
+ if (x == 0) {
260
+ return INFINITY;
261
+ }
262
+ accscalar_t additional_summand = 0;
263
+ int x_is_integer = x == compat_floor(x);
264
+ if (x < 0) {
265
+ if (x_is_integer) {
266
+ return INFINITY;
267
+ }
268
+ // it is more standard to write this as recursion, but
269
+ // nvcc does not like that
270
+ additional_summand = -c10::pi<scalar_t> /
271
+ compat_tan(c10::pi<scalar_t> * x);
272
+ x = 1 - x;
273
+ }
274
+
275
+ // Push x to be >= 10
276
+ accscalar_t result = 0;
277
+ while (x < 10) {
278
+ result -= 1 / x;
279
+ x += 1;
280
+ }
281
+ if (x == 10) {
282
+ return result + PSI_10 + additional_summand;
283
+ }
284
+
285
+ // Compute asymptotic digamma
286
+ static const accscalar_t A[] = {
287
+ 8.33333333333333333333E-2,
288
+ -2.10927960927960927961E-2,
289
+ 7.57575757575757575758E-3,
290
+ -4.16666666666666666667E-3,
291
+ 3.96825396825396825397E-3,
292
+ -8.33333333333333333333E-3,
293
+ 8.33333333333333333333E-2,
294
+ };
295
+
296
+ accscalar_t y = 0;
297
+ if (x < 1.0e17f) {
298
+ accscalar_t z = 1.0 / (x * x);
299
+ y = z * polevl<accscalar_t>(z, A, 6);
300
+ }
301
+ return static_cast<scalar_t>(
302
+ result + compat_log(x) - (0.5f / x) - y + additional_summand);
303
+ }
304
+
305
+ // Computes the reparameterized gradient -(d/dalpha cdf(x;alpha)) / pdf(x;alpha)
306
+ // for random number x drawn from a standard Gamma distribution Gamma(alpha).
307
+ template <typename scalar_t, typename accscalar_t>
308
+ C10_HOST_DEVICE scalar_t standard_gamma_grad_one(scalar_t alpha_, scalar_t x_) {
309
+ // Use a Taylor series expansion for small x.
310
+ accscalar_t x = static_cast<accscalar_t>(x_);
311
+ accscalar_t alpha = static_cast<accscalar_t>(alpha_);
312
+ if (x < 0.8f) {
313
+ accscalar_t numer = 1;
314
+ accscalar_t denom = alpha;
315
+ auto series1 = numer / denom;
316
+ auto series2 = numer / (denom * denom);
317
+ for (int i = 1; i <= 5; ++i) {
318
+ numer *= -x / static_cast<accscalar_t>(i);
319
+ denom += 1;
320
+ series1 += numer / denom;
321
+ series2 += numer / (denom * denom);
322
+ }
323
+ const auto pow_x_alpha = compat_pow(x, alpha);
324
+ const auto gamma_pdf = compat_pow(x, alpha - 1) * compat_exp(-x);
325
+ const auto gamma_cdf = pow_x_alpha * series1;
326
+ const auto gamma_cdf_alpha =
327
+ (compat_log(x) - digamma_one<accscalar_t, accscalar_t>(alpha)) *
328
+ gamma_cdf -
329
+ pow_x_alpha * series2;
330
+ const auto result = -gamma_cdf_alpha / gamma_pdf;
331
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : static_cast<scalar_t>(result);
332
+ }
333
+
334
+ // Use a Rice saddle point expansion for large alpha.
335
+ if (alpha > 8.0f) {
336
+ if (0.9f * alpha <= x && x <= 1.1f * alpha) {
337
+ const auto numer_1 = 1 + 24 * alpha * (1 + 12 * alpha);
338
+ const auto numer_2 = 1440 * (alpha * alpha) + 6 * x * (53 - 120 * x)
339
+ - 65 * x * x / alpha + alpha * (107 + 3600 * x);
340
+ const auto denom = 1244160 * (alpha * alpha) * (alpha * alpha);
341
+ return static_cast<scalar_t>(numer_1 * numer_2 / denom);
342
+ }
343
+ const auto denom = compat_sqrt(8 * alpha);
344
+ const auto term2 = denom / (alpha - x);
345
+ const auto term3 = compat_pow(
346
+ x - alpha - alpha * compat_log(x / alpha),
347
+ static_cast<accscalar_t>(-1.5));
348
+ const auto term23 = (x < alpha) ? term2 - term3 : term2 + term3;
349
+ const auto term1 = compat_log(x / alpha) * term23 -
350
+ compat_sqrt(2 / alpha) * (alpha + x) / ((alpha - x) * (alpha - x));
351
+ const auto stirling = 1 + 1 / (12 * alpha) * (1 + 1 / (24 * alpha));
352
+ const auto numer = x * term1;
353
+ return static_cast<scalar_t>(-stirling * numer / denom);
354
+ }
355
+
356
+ // Use a bivariate rational approximation to the reparameterized gradient.
357
+ const auto u = compat_log(x / alpha);
358
+ const auto v = compat_log(alpha);
359
+ static const accscalar_t coef_uv[3][8] = {
360
+ {0.16009398, -0.094634809, 0.025146376, -0.0030648343,
361
+ 1, 0.32668115, 0.10406089, 0.0014179084},
362
+ {0.53487893, 0.1298071, 0.065735949, -0.0015649758,
363
+ 0.16639465, 0.020070113, -0.0035938915, -0.00058392623},
364
+ {0.040121004, -0.0065914022, -0.0026286047, -0.0013441777,
365
+ 0.017050642, -0.0021309326, 0.00085092367, -1.5247877e-07},
366
+ };
367
+ accscalar_t coef_v[8];
368
+ for (int i = 0; i < 8; ++ i) {
369
+ coef_v[i] = coef_uv[0][i] + u * (coef_uv[1][i] + u * coef_uv[2][i]);
370
+ }
371
+ const auto p = coef_v[0] + v * (coef_v[1] + v * (coef_v[2] + v * coef_v[3]));
372
+ const auto q = coef_v[4] + v * (coef_v[5] + v * (coef_v[6] + v * coef_v[7]));
373
+ return static_cast<scalar_t>(compat_exp(p / q));
374
+ }
375
+
376
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
377
+ // Assumes x is close to zero and uses a Taylor expansion.
378
+ template <typename scalar_t, typename accscalar_t>
379
+ C10_DEVICE static inline scalar_t _beta_grad_alpha_small(scalar_t x, scalar_t alpha, scalar_t beta) {
380
+ const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha)
381
+ - digamma_one<scalar_t, accscalar_t>(alpha + beta) - compat_log(x);
382
+ scalar_t numer = 1;
383
+ scalar_t series = numer / alpha * (factor + 1 / alpha);
384
+ for (int i = 1; i <= 10; ++i) {
385
+ scalar_t casted_i = static_cast<scalar_t>(i);
386
+ numer *= (casted_i - beta) * x / casted_i;
387
+ const scalar_t denom = alpha + casted_i;
388
+ series += numer / denom * (factor + 1 / denom);
389
+ }
390
+ const scalar_t result = x * compat_pow(1 - x, -beta) * series;
391
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
392
+ }
393
+
394
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt beta.
395
+ // Assumes x is close to zero and uses a Taylor expansion.
396
+ template <typename scalar_t, typename accscalar_t>
397
+ C10_DEVICE static inline scalar_t _beta_grad_beta_small(scalar_t x, scalar_t alpha, scalar_t beta) {
398
+ const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha + beta) - digamma_one<scalar_t, accscalar_t>(beta);
399
+ scalar_t numer = 1, betas = 1, dbetas = 0, series = factor / alpha;
400
+ for (int i = 1; i <= 8; ++i) {
401
+ scalar_t casted_i = static_cast<scalar_t>(i);
402
+ numer *= -x / casted_i;
403
+ dbetas = dbetas * (beta - casted_i) + betas;
404
+ betas = betas * (beta - casted_i);
405
+ series += numer / (alpha + casted_i) * (dbetas + factor * betas);
406
+ }
407
+ const scalar_t result = -compat_pow(1 - x, 1 - beta) * series;
408
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
409
+ }
410
+
411
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
412
+ // Assumes alpha and beta are both large and uses a Rice saddle point expansion.
413
+ // To ensure numerical stability, this computation is performed at higher precision.
414
+ template<typename scalar_t, typename accscalar_t>
415
+ C10_DEVICE static inline scalar_t _beta_grad_alpha_mid(accscalar_t x, accscalar_t alpha, accscalar_t beta) {
416
+ const accscalar_t total = alpha + beta;
417
+ const accscalar_t mean = alpha / total;
418
+ const accscalar_t std = compat_sqrt(alpha * beta / (total + 1)) / total;
419
+ if (mean - 0.1 * std <= x && x <= mean + 0.1 * std) {
420
+ // Avoid the singularity at x = mean.
421
+ const accscalar_t poly = 47 * x * (beta * beta) * (beta * beta) + alpha * (
422
+ (43 + 20 * (16 + 27 * beta) * x) * (beta * beta) * beta + alpha * (
423
+ 3 * (59 + 180 * beta - 90 * x) * (beta * beta) + alpha * (
424
+ (453 + 1620 * beta * (1 - x) - 455 * x) * beta + alpha * (
425
+ 8 * (1 - x) * (135 * beta - 11)))));
426
+ const accscalar_t prefactor_num = (1 + 12 * alpha) * (1 + 12 * beta) / (total * total);
427
+ const accscalar_t prefactor_den = 12960 * alpha * alpha * alpha * beta * beta * (1 + 12 * total);
428
+ return prefactor_num / (1 - x) * poly / prefactor_den;
429
+ }
430
+ const accscalar_t prefactor = -x / compat_sqrt(2 * alpha * beta / total);
431
+ const accscalar_t stirling = (1 + 1 / (12 * alpha) + 1 / (288 * alpha * alpha))
432
+ * (1 + 1 / (12 * beta) + 1 / (288 * beta * beta))
433
+ / (1 + 1 / (12 * total) + 1 / (288 * total * total));
434
+ const accscalar_t term1_num = 2 * (alpha * alpha) * (x - 1) + alpha * beta * (x - 1) - x * (beta * beta);
435
+ const accscalar_t axbx = alpha * (x - 1) + beta * x;
436
+ const accscalar_t term1_den = compat_sqrt(2 * alpha / beta) * compat_pow(total, static_cast<accscalar_t>(1.5f)) * axbx * axbx;
437
+ const accscalar_t term1 = term1_num / term1_den;
438
+ const accscalar_t term2 = 0.5f * compat_log(alpha / (total * x));
439
+ const accscalar_t term3_num = compat_sqrt(8 * alpha * beta / total);
440
+ const accscalar_t term3_den = beta * x + alpha * (x - 1);
441
+ const accscalar_t term3 = term3_num / term3_den;
442
+ const accscalar_t term4_base = beta * compat_log(beta / (total * (1 - x))) +
443
+ alpha * compat_log(alpha / (total * x));
444
+ const accscalar_t term4 = compat_pow(term4_base, static_cast<accscalar_t>(-1.5f));
445
+ const accscalar_t term1234 = term1 + term2 * (term3 + (x < mean ? term4 : -term4));
446
+ return static_cast<scalar_t>(stirling * prefactor * term1234);
447
+ }
448
+
449
+ // Computes a scaled reparameterized gradient
450
+ // -(d/dalpha cdf(x;alpha,beta)) / pdf(x;alpha,beta) / (1-x)
451
+ // for random number x drawn from a Beta distribution Beta(alpha,beta).
452
+ // This function inputs total=alpha+beta to make it easy to implement
453
+ // Dirichlet reparameterized gradients in terms of Betas.
454
+ template<typename scalar_t, typename accscalar_t>
455
+ C10_HOST_DEVICE static inline scalar_t dirichlet_grad_one(scalar_t x, scalar_t alpha, scalar_t total) {
456
+ accscalar_t x_ = static_cast<accscalar_t>(x);
457
+ accscalar_t alpha_ = static_cast<accscalar_t>(alpha);
458
+ accscalar_t total_ = static_cast<accscalar_t>(total);
459
+
460
+ const scalar_t beta = total - alpha;
461
+ const accscalar_t beta_ = total_ - alpha_;
462
+ const scalar_t boundary = total * x * (1 - x);
463
+
464
+ // Use an asymptotic approximation for x close to 0.
465
+ if (x <= 0.5f && boundary < 2.5f) {
466
+ return _beta_grad_alpha_small<scalar_t, accscalar_t>(x, alpha, beta);
467
+ }
468
+
469
+ // Use an asymptotic approximation for x close to 1.
470
+ if (x >= 0.5f && boundary < 0.75f) {
471
+ return -_beta_grad_beta_small<scalar_t, accscalar_t>(1 - x, beta, alpha);
472
+ }
473
+
474
+ // Use an asymptotic approximation when alpha and (total - alpha) are both large.
475
+ if (alpha > 6 && beta > 6) {
476
+ return _beta_grad_alpha_mid<scalar_t, accscalar_t>(x_, alpha_, beta_);
477
+ }
478
+
479
+ // Use a rational correction to an analytic approximation.
480
+ static const accscalar_t c[2][3][3][4] = {
481
+ {{{1.003668233, -0.01061107488, -0.0657888334, 0.01201642863},
482
+ {0.6336835991, -0.3557432599, 0.05486251648, -0.001465281033},
483
+ {-0.03276231906, 0.004474107445, 0.002429354597, -0.0001557569013}},
484
+ {{0.221950385, -0.3187676331, 0.01799915743, 0.01074823814},
485
+ {-0.2951249643, 0.06219954479, 0.01535556598, 0.001550077057},
486
+ {0.02155310298, 0.004170831599, 0.001292462449, 6.976601077e-05}},
487
+ {{-0.05980841433, 0.008441916499, 0.01085618172, 0.002319392565},
488
+ {0.02911413504, 0.01400243777, -0.002721828457, 0.000751041181},
489
+ {0.005900514878, -0.001936558688, -9.495446725e-06, 5.385558597e-05}}},
490
+ {{{1, -0.02924021934, -0.04438342661, 0.007285809825},
491
+ {0.6357567472, -0.3473456711, 0.05454656494, -0.002407477521},
492
+ {-0.03301322327, 0.004845219414, 0.00231480583, -0.0002307248149}},
493
+ {{0.5925320577, -0.1757678135, 0.01505928619, 0.000564515273},
494
+ {0.1014815858, -0.06589186703, 0.01272886114, -0.0007316646956},
495
+ {-0.007258481865, 0.001096195486, 0.0003934994223, -4.12701925e-05}},
496
+ {{0.06469649321, -0.0236701437, 0.002902096474, -5.896963079e-05},
497
+ {0.001925008108, -0.002869809258, 0.0008000589141, -6.063713228e-05},
498
+ {-0.0003477407336, 6.959756487e-05, 1.097287507e-05, -1.650964693e-06}}},
499
+ };
500
+ const accscalar_t u = compat_log(x_);
501
+ const accscalar_t a = compat_log(alpha_) - u;
502
+ const accscalar_t b = compat_log(total_) - a;
503
+ const accscalar_t pow_u[3] = {1, u, u * u};
504
+ const accscalar_t pow_a[3] = {1, a, a * a};
505
+ accscalar_t p = 0.0;
506
+ accscalar_t q = 0.0;
507
+ for (int i = 0; i < 3; ++i) {
508
+ for (int j = 0; j < 3; ++j) {
509
+ const accscalar_t ua = pow_u[i] * pow_a[j];
510
+ p += ua * (c[0][i][j][0] + b * (c[0][i][j][1] + b * (c[0][i][j][2] + b * c[0][i][j][3])));
511
+ q += ua * (c[1][i][j][0] + b * (c[1][i][j][1] + b * (c[1][i][j][2] + b * c[1][i][j][3])));
512
+ }
513
+ }
514
+ const accscalar_t approx = x_ * (digamma_one<scalar_t, accscalar_t>(total_) - digamma_one<scalar_t, accscalar_t>(alpha_)) / beta_;
515
+ return static_cast<scalar_t>(p / q * approx);
516
+ }
517
+
518
+ } // namespace
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Fill.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Functions that fill Tensors with constants. Implementations are in Fill.cpp.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ class Tensor;
13
+ struct TensorIterator;
14
+
15
+ namespace native {
16
+
17
+ DECLARE_DISPATCH(void(*)(TensorIterator&, const c10::Scalar&), fill_stub);
18
+
19
+ Tensor& fill_out(Tensor& self, const Scalar& value);
20
+
21
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/FractionalMaxPooling.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/TensorUtils.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ namespace at { namespace native {
7
+
8
+ template<typename scalar_t>
9
+ static inline std::vector<int> generate_intervals(
10
+ scalar_t sample,
11
+ int64_t inputSize,
12
+ int64_t outputSize,
13
+ int64_t poolSize) {
14
+ std::vector<int> sequence(outputSize);
15
+ if (outputSize > 1) {
16
+ scalar_t alpha = static_cast<scalar_t>(inputSize - poolSize) /
17
+ static_cast<scalar_t>(outputSize - 1);
18
+
19
+ for (const auto i : c10::irange(outputSize - 1)) {
20
+ sequence[i] =
21
+ static_cast<int>((i + sample) * alpha) - static_cast<int>(sample * alpha);
22
+ }
23
+ }
24
+ if (outputSize > 0) {
25
+ sequence[outputSize - 1] = inputSize - poolSize;
26
+ }
27
+ return sequence;
28
+ }
29
+
30
+ template <int64_t ndim>
31
+ static inline void fractional_max_pool_check_shape(
32
+ const Tensor& input,
33
+ const Tensor& randomSamples) {
34
+
35
+ TORCH_CHECK(
36
+ input.scalar_type() == randomSamples.scalar_type(),
37
+ "Expect _random_samples to have the same dtype as input");
38
+
39
+ int64_t ndimension = randomSamples.ndimension();
40
+ TORCH_CHECK(
41
+ ndimension == 3,
42
+ "Expect _random_samples to have 3 dimensions, got ", ndimension);
43
+
44
+ int64_t N = randomSamples.size(0);
45
+ int64_t C = randomSamples.size(1);
46
+ int64_t D = randomSamples.size(2);
47
+
48
+ int64_t input_batch, input_channel;
49
+ if (ndim == 2) {
50
+ // fractional_max_pool2d
51
+ if (input.ndimension() == 3) {
52
+ input_batch = 1;
53
+ input_channel = input.size(0);
54
+ } else {
55
+ input_batch = input.size(0);
56
+ input_channel = input.size(1);
57
+ }
58
+ } else {
59
+ // factional_max_pool3d
60
+ if (input.ndimension() == 4) {
61
+ input_batch = 1;
62
+ input_channel = input.size(0);
63
+ } else {
64
+ input_batch = input.size(0);
65
+ input_channel = input.size(1);
66
+ }
67
+ }
68
+
69
+ TORCH_CHECK(
70
+ N >= input_batch,
71
+ "Expect _random_samples.size(0) no less then input batch size.");
72
+ TORCH_CHECK(
73
+ C == input_channel,
74
+ "Expect _random_samples.size(1) equals to input channel size.");
75
+ TORCH_CHECK(
76
+ D == ndim,
77
+ "Expect _random_samples.size(2) equals to ", ndim, "; got ", D, ".");
78
+ }
79
+
80
+ }} // at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/FunctionOfAMatrixUtils.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ struct TensorIterator;
8
+
9
+ namespace native {
10
+
11
+ using _compute_linear_combination_fn = void(*)(
12
+ TensorIterator& iter,
13
+ int64_t in_stride,
14
+ int64_t coeff_stride,
15
+ int64_t num_summations
16
+ );
17
+
18
+ DECLARE_DISPATCH(_compute_linear_combination_fn, _compute_linear_combination_stub);
19
+
20
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <cmath>
5
+ #include <cstdint>
6
+ #include <utility>
7
+
8
+ #include <ATen/native/GridSamplerUtils.h>
9
+
10
+ namespace at { namespace native {
11
+
12
+ using detail::GridSamplerInterpolation;
13
+ using detail::GridSamplerPadding;
14
+
15
+ // Unnormalizes a coordinate from the -1 to +1 scale to its pixel index value,
16
+ // where we view each pixel as an area between (idx - 0.5) and (idx + 0.5).
17
+ // if align_corners: -1 and +1 get sent to the centers of the corner pixels
18
+ // -1 --> 0
19
+ // +1 --> (size - 1)
20
+ // scale_factor = (size - 1) / 2
21
+ // if not align_corners: -1 and +1 get sent to the image edges
22
+ // -1 --> -0.5
23
+ // +1 --> (size - 1) + 0.5 == size - 0.5
24
+ // scale_factor = size / 2
25
+ template <typename scalar_t>
26
+ static inline scalar_t grid_sampler_unnormalize(scalar_t coord, int64_t size,
27
+ bool align_corners) {
28
+ if (align_corners) {
29
+ // unnormalize coord from [-1, 1] to [0, size - 1]
30
+ return ((coord + 1) / 2) * (size - 1);
31
+ } else {
32
+ // unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
33
+ return ((coord + 1) * size - 1) / 2;
34
+ }
35
+ }
36
+
37
+ // grid_sampler_unnormalize_set_grad works the same as grid_sampler_unnormalize
38
+ // except that it also returns the `d output / d input` via pointer argument
39
+ // `grad_in`.
40
+ // This is useful in the backward pass of grid_sampler.
41
+ template <typename scalar_t>
42
+ static inline scalar_t grid_sampler_unnormalize_set_grad(scalar_t coord, int64_t size,
43
+ bool align_corners, scalar_t *grad_in) {
44
+ if (align_corners) {
45
+ // unnormalize coord from [-1, 1] to [0, size - 1]
46
+ *grad_in = static_cast<scalar_t>(size - 1) / 2;
47
+ return ((coord + 1) / 2) * (size - 1);
48
+ } else {
49
+ // unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
50
+ *grad_in = static_cast<scalar_t>(size) / 2;
51
+ return ((coord + 1) * size - 1) / 2;
52
+ }
53
+ }
54
+
55
+ // Clips coordinates to between 0 and clip_limit - 1
56
+ template<typename scalar_t>
57
+ static inline scalar_t clip_coordinates(scalar_t in, int64_t clip_limit) {
58
+ return std::min(static_cast<scalar_t>(clip_limit - 1), std::max(in, static_cast<scalar_t>(0)));
59
+ }
60
+
61
+ // clip_coordinates_set_grad works similarly to clip_coordinates except that
62
+ // it also returns the `d output / d input` via pointer argument `grad_in`.
63
+ // This is useful in the backward pass of grid_sampler.
64
+ template<typename scalar_t>
65
+ static inline scalar_t clip_coordinates_set_grad(scalar_t in, int64_t clip_limit,
66
+ scalar_t *grad_in) {
67
+ // Note that it is important for the gradient calculation that borders
68
+ // are considered out of bounds.
69
+ if (in <= static_cast<scalar_t>(0)) {
70
+ *grad_in = static_cast<scalar_t>(0);
71
+ return static_cast<scalar_t>(0);
72
+ } else {
73
+ scalar_t max = static_cast<scalar_t>(clip_limit - 1);
74
+ if (in >= max) {
75
+ *grad_in = static_cast<scalar_t>(0);
76
+ return max;
77
+ } else {
78
+ *grad_in = static_cast<scalar_t>(1);
79
+ return in;
80
+ }
81
+ }
82
+ }
83
+
84
+ // Reflects coordinates until they fall between low and high (inclusive).
85
+ // The bounds are passed as twice their value so that half-integer values
86
+ // can be represented as ints.
87
+ template<typename scalar_t>
88
+ static inline scalar_t reflect_coordinates(scalar_t in, int64_t twice_low,
89
+ int64_t twice_high) {
90
+ if (twice_low == twice_high) {
91
+ return static_cast<scalar_t>(0);
92
+ }
93
+ scalar_t min = static_cast<scalar_t>(twice_low) / 2;
94
+ scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
95
+ in = std::fabs(in - min);
96
+ // `fmod` returns same sign as `in`, which is positive after the `fabs` above.
97
+ scalar_t extra = std::fmod(in, span);
98
+ int flips = static_cast<int>(std::floor(in / span));
99
+ if (flips % 2 == 0) {
100
+ return extra + min;
101
+ } else {
102
+ return span - extra + min;
103
+ }
104
+ }
105
+
106
+ // reflect_coordinates_set_grad works similarly to reflect_coordinates except
107
+ // that it also returns the `d output / d input` via pointer argument
108
+ // `grad_in`.
109
+ // This is useful in the backward pass of grid_sampler.
110
+ template<typename scalar_t>
111
+ static inline scalar_t reflect_coordinates_set_grad(scalar_t in, int64_t twice_low,
112
+ int64_t twice_high, scalar_t *grad_in) {
113
+ if (twice_low == twice_high) {
114
+ *grad_in = static_cast<scalar_t>(0);
115
+ return static_cast<scalar_t>(0);
116
+ }
117
+ int grad_in_mult_;
118
+ scalar_t min = static_cast<scalar_t>(twice_low) / 2;
119
+ scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
120
+ in = in - min;
121
+ if (in < static_cast<scalar_t>(0)) {
122
+ grad_in_mult_ = -1;
123
+ in = -in;
124
+ } else {
125
+ grad_in_mult_ = 1;
126
+ }
127
+ // `fmod` returns same sign as `in`, which is positive after the `if` above.
128
+ scalar_t extra = std::fmod(in, span);
129
+ int flips = static_cast<int>(std::floor(in / span));
130
+ if (flips % 2 == 0) {
131
+ *grad_in = static_cast<scalar_t>(grad_in_mult_);
132
+ return extra + min;
133
+ } else {
134
+ *grad_in = static_cast<scalar_t>(-grad_in_mult_);
135
+ return span - extra + min;
136
+ }
137
+ }
138
+
139
+ // Mapping the out-of-boundary points back into boundary
140
+ // This would only affect padding_mode=border or reflection
141
+ template<typename scalar_t>
142
+ static inline scalar_t compute_coordinates(scalar_t coord, int64_t size,
143
+ GridSamplerPadding padding_mode,
144
+ bool align_corners) {
145
+ if (padding_mode == GridSamplerPadding::Border) {
146
+ // clip coordinates to image borders
147
+ coord = clip_coordinates(coord, size);
148
+ } else if (padding_mode == GridSamplerPadding::Reflection) {
149
+ // reflect coordinates by image borders
150
+ if (align_corners) {
151
+ coord = reflect_coordinates(coord, 0, 2*(size - 1));
152
+ } else {
153
+ coord = reflect_coordinates(coord, -1, 2*size - 1);
154
+ }
155
+ // clip coordinates to image borders
156
+ coord = clip_coordinates(coord, size);
157
+ }
158
+ return coord;
159
+ }
160
+
161
+ // Computes the pixel source index value for a grid coordinate
162
+ template <typename scalar_t>
163
+ static inline scalar_t grid_sampler_compute_source_index(
164
+ scalar_t coord,
165
+ int64_t size,
166
+ GridSamplerPadding padding_mode,
167
+ bool align_corners) {
168
+ coord = grid_sampler_unnormalize(coord, size, align_corners);
169
+ coord = compute_coordinates(coord, size, padding_mode, align_corners);
170
+ return coord;
171
+ }
172
+
173
+ // grid_sampler_compute_source_index_set_grad works similarly to
174
+ // grid_sampler_compute_source_index except that it also returns the
175
+ // `d output / d input` via pointer argument `grad_in`.
176
+ // This is useful in the backward pass of grid_sampler.
177
+ template <typename scalar_t>
178
+ static inline scalar_t grid_sampler_compute_source_index_set_grad(
179
+ scalar_t coord,
180
+ int64_t size,
181
+ GridSamplerPadding padding_mode,
182
+ bool align_corners,
183
+ scalar_t *grad_in) {
184
+ scalar_t grad_clip, grad_refl;
185
+ coord = grid_sampler_unnormalize_set_grad(coord, size, align_corners, grad_in);
186
+ if (padding_mode == GridSamplerPadding::Border) {
187
+ // clip coordinates to image borders
188
+ coord = clip_coordinates_set_grad(coord, size, &grad_clip);
189
+ *grad_in = (*grad_in) * grad_clip;
190
+ } else if (padding_mode == GridSamplerPadding::Reflection) {
191
+ // reflect coordinates by image borders
192
+ if (align_corners) {
193
+ coord = reflect_coordinates_set_grad(coord, 0, 2*(size - 1), &grad_refl);
194
+ } else {
195
+ coord = reflect_coordinates_set_grad(coord, -1, 2*size - 1, &grad_refl);
196
+ }
197
+ // clip coordinates to image borders
198
+ coord = clip_coordinates_set_grad(coord, size, &grad_clip);
199
+ *grad_in = (*grad_in) * grad_refl * grad_clip;
200
+ }
201
+ return coord;
202
+ }
203
+
204
+ static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) {
205
+ return h >= 0 && h < H && w >= 0 && w < W;
206
+ }
207
+
208
+ static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) {
209
+ return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W;
210
+ }
211
+
212
+ template<typename scalar_t>
213
+ static inline scalar_t get_value_bounded(
214
+ scalar_t* data,
215
+ scalar_t x,
216
+ scalar_t y,
217
+ int64_t W,
218
+ int64_t H,
219
+ int64_t sW,
220
+ int64_t sH,
221
+ GridSamplerPadding padding_mode,
222
+ bool align_corners) {
223
+
224
+ x = compute_coordinates(x, W, padding_mode, align_corners);
225
+ y = compute_coordinates(y, H, padding_mode, align_corners);
226
+
227
+ int64_t ix = static_cast<int64_t>(x);
228
+ int64_t iy = static_cast<int64_t>(y);
229
+
230
+ if (within_bounds_2d(iy, ix, H, W)) {
231
+ return data[iy * sH + ix * sW];
232
+ }
233
+ return static_cast<scalar_t>(0);
234
+ }
235
+
236
+ template<typename scalar_t>
237
+ static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w,
238
+ int64_t sH, int64_t sW, int64_t H, int64_t W,
239
+ scalar_t delta) {
240
+ if (within_bounds_2d(h, w, H, W)) {
241
+ data[h * sH + w * sW] += delta;
242
+ }
243
+ }
244
+
245
+ template<typename scalar_t>
246
+ static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w,
247
+ int64_t sD, int64_t sH, int64_t sW,
248
+ int64_t D, int64_t H, int64_t W,
249
+ scalar_t delta) {
250
+ if (within_bounds_3d(d, h, w, D, H, W)) {
251
+ data[d * sD + h * sH + w * sW] += delta;
252
+ }
253
+ }
254
+
255
+ template<typename scalar_t>
256
+ static inline void add_value_bounded(
257
+ scalar_t* data,
258
+ scalar_t x,
259
+ scalar_t y,
260
+ int64_t W,
261
+ int64_t H,
262
+ int64_t sW,
263
+ int64_t sH,
264
+ scalar_t delta,
265
+ GridSamplerPadding padding_mode,
266
+ bool align_corners) {
267
+
268
+ x = compute_coordinates(x, W, padding_mode, align_corners);
269
+ y = compute_coordinates(y, H, padding_mode, align_corners);
270
+
271
+ int64_t ix = static_cast<int64_t>(x);
272
+ int64_t iy = static_cast<int64_t>(y);
273
+
274
+ safe_add_2d(data, iy, ix, sH, sW, H, W, delta);
275
+ }
276
+
277
+ // Calculate the differential of the cubic convolution, i.e. `d coeff / d x`
278
+ template<typename scalar_t>
279
+ static inline void get_cubic_coefficients_grad(
280
+ scalar_t coeffs[4],
281
+ scalar_t t) {
282
+
283
+ // Must be the same as forward calculation in
284
+ // aten/src/ATen/native/UpSample.h:get_cubic_upsample_coefficients
285
+ scalar_t A = -0.75;
286
+
287
+ scalar_t x;
288
+ x = -1 - t; // 1 < x = |-1 - tx| < 2
289
+ coeffs[0] = (-3 * A * x - 10 * A ) * x - 8 * A;
290
+ x = -t; // x = |0 - tx| <= 1
291
+ coeffs[1] = (-3 * (A + 2) * x - 2 * (A + 3)) * x;
292
+ x = 1 - t; // x = |1 - tx| <= 1
293
+ coeffs[2] = (3 * (A + 2) * x - 2 * (A + 3)) * x;
294
+ x = 2 - t; // 1 < x = |2 - tx| < 2
295
+ coeffs[3] = (3 * A * x - 10 * A) * x + 8 * A;
296
+ }
297
+
298
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // See NOTE: [Tensor vs. TensorBase]
4
+ // https://github.com/pytorch/pytorch/pull/66979
5
+ #include <ATen/core/TensorBase.h>
6
+ #include <ATen/native/TensorProperties.h>
7
+ #include <ATen/native/CanUse32BitIndexMath.h>
8
+
9
+ namespace at { namespace native {
10
+
11
+ namespace detail {
12
+
13
+ enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic};
14
+ enum class GridSamplerPadding {Zeros, Border, Reflection};
15
+
16
+ } // namespace detail
17
+
18
+ using detail::GridSamplerInterpolation;
19
+ using detail::GridSamplerPadding;
20
+
21
+ namespace {
22
+
23
+ // See NOTE [ grid_sampler Native Functions ].
24
+ void check_grid_sampler_common(
25
+ const TensorBase& input,
26
+ const TensorBase& grid
27
+ ) {
28
+ auto input_opt = input.options();
29
+ auto grid_opt = grid.options();
30
+
31
+ TORCH_CHECK(
32
+ input.defined(),
33
+ "grid_sampler(): expected input to not be undefined");
34
+ TORCH_CHECK(
35
+ grid.defined(),
36
+ "grid_sampler(): expected grid to not be undefined");
37
+ TORCH_CHECK(
38
+ input_opt.device() == grid_opt.device(),
39
+ "grid_sampler(): expected input and grid to be on same device, but input "
40
+ "is on ", input_opt.device(), " and grid is on ", grid_opt.device());
41
+ TORCH_CHECK(
42
+ input_opt.layout() == kStrided && grid_opt.layout() == kStrided,
43
+ "grid_sampler(): expected input and grid to have torch.strided layout, but "
44
+ "input has ", input_opt.layout(), " and grid has ", grid_opt.layout());
45
+ TORCH_CHECK(
46
+ input.size(0) == grid.size(0),
47
+ "grid_sampler(): expected grid and input to have same batch size, but got "
48
+ "input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes());
49
+ TORCH_CHECK(
50
+ grid.size(-1) == input.dim() - 2,
51
+ "grid_sampler(): expected grid to have size ", input.dim() - 2, " in last "
52
+ "dimension, but got grid with sizes ", grid.sizes());
53
+
54
+ for (const auto i : c10::irange(2, input.dim())) {
55
+ TORCH_CHECK(input.size(i) > 0,
56
+ "grid_sampler(): expected input to have non-empty spatial dimensions, "
57
+ "but input has sizes ", input.sizes(), " with dimension ", i, " being "
58
+ "empty");
59
+ }
60
+ }
61
+
62
+ // See NOTE [ grid_sampler Native Functions ].
63
+ void check_grid_sampler_2d(
64
+ const TensorBase& input,
65
+ const TensorBase& grid
66
+ ) {
67
+ TORCH_CHECK(
68
+ input.dim() == 4 && input.dim() == grid.dim(),
69
+ "grid_sampler(): expected 4D input and grid with same number of "
70
+ "dimensions, but got input with sizes ", input.sizes(),
71
+ " and grid with sizes ", grid.sizes());
72
+ }
73
+
74
+ // See NOTE [ grid_sampler Native Functions ].
75
+ void check_grid_sampler_3d(
76
+ const TensorBase& input,
77
+ const TensorBase& grid,
78
+ int64_t interpolation_mode
79
+ ) {
80
+ TORCH_CHECK(
81
+ input.dim() == 5 && input.dim() == grid.dim(),
82
+ "grid_sampler(): expected 5D input and grid with same number of "
83
+ "dimensions, but got input with sizes ", input.sizes(),
84
+ " and grid with sizes ", grid.sizes());
85
+ TORCH_CHECK(
86
+ !(input.dim() == 5 &&
87
+ static_cast<GridSamplerInterpolation>(interpolation_mode) ==
88
+ GridSamplerInterpolation::Bicubic),
89
+ "grid_sampler(): bicubic interpolation only supports 4D input");
90
+ }
91
+
92
+ // See NOTE [ grid_sampler Native Functions ].
93
+ // cudnn does not support inputs larger than 1024.
94
+ bool cond_cudnn_grid_sampler(
95
+ const TensorBase& input,
96
+ const TensorBase& grid
97
+ ) {
98
+ return (
99
+ at::native::cudnn_is_acceptable(input) &&
100
+ at::native::cudnn_is_acceptable(grid) &&
101
+ at::native::canUse32BitIndexMath(input) &&
102
+ at::native::canUse32BitIndexMath(grid) &&
103
+ input.dim() == 4 &&
104
+ input.sym_size(1) <= 1024);
105
+ }
106
+
107
+ } // anonymous namespace
108
+
109
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/IndexingUtils.h ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/ExpandUtils.h>
3
+ #include <ATen/native/CanUse32BitIndexMath.h>
4
+ #include <ATen/native/TensorIterator.h>
5
+ #include <ATen/core/IListRef.h>
6
+ #include <c10/util/irange.h>
7
+
8
+ namespace at { namespace native {
9
+
10
+ [[noreturn]]
11
+ static void invalid_mask(const Tensor & self, int64_t idx, const Tensor & mask, int64_t maskIdx) {
12
+ TORCH_CHECK_INDEX(false, "The shape of the mask ", mask.sizes(), " at index ", maskIdx,
13
+ " does not match the shape of the indexed tensor ", self.sizes(), " at index ", idx);
14
+ }
15
+
16
+
17
+ static C10_UNUSED std::vector<Tensor> expandTensors(const Tensor & self, IOptTensorListRef indices) {
18
+ // If indices come in as ByteTensor or BoolTensor (masks), expand them into the equivalent indexing by LongTensors
19
+ std::vector<Tensor> result;
20
+ for (const auto& index_opt : indices) {
21
+ if (!index_opt.has_value()) {
22
+ result.emplace_back();
23
+ } else {
24
+ const auto& index = *index_opt;
25
+ if (index.scalar_type() == kByte || index.scalar_type() == kBool) {
26
+ if (index.scalar_type() == kByte) {
27
+ TORCH_WARN("indexing with dtype torch.uint8 is now deprecated," \
28
+ " please use a dtype torch.bool instead.");
29
+ }
30
+ // The sizes of the ByteTensor mask or bool tensor must match the sizes of the
31
+ // corresponding dimensions in self
32
+ for (const auto j : c10::irange(index.dim())) {
33
+ int64_t srcIdx = result.size() + j;
34
+ if (index.size(j) != self.size(srcIdx)) {
35
+ invalid_mask(self, srcIdx, index, j);
36
+ }
37
+ }
38
+ // Replace with nonzeros
39
+ auto nonzero = index.nonzero();
40
+ for (const auto j : c10::irange(index.dim())) {
41
+ result.emplace_back(nonzero.select(1, j));
42
+ }
43
+ } else {
44
+ result.emplace_back(std::move(index));
45
+ }
46
+ }
47
+ }
48
+ return result;
49
+ }
50
+
51
+ static C10_UNUSED void checkIndexTensorTypes(IOptTensorListRef indices, bool allow_int=false) {
52
+ for (const auto& tensor : indices) {
53
+ if (tensor.has_value() && tensor->defined()) {
54
+ auto scalarType = tensor->scalar_type();
55
+ if (allow_int) {
56
+ if (scalarType != kLong && scalarType != kByte && scalarType != kBool && scalarType != kInt) {
57
+ TORCH_CHECK_INDEX(false, "tensors used as indices must be long, int, byte or bool tensors");
58
+ }
59
+ } else {
60
+ if (scalarType != kLong && scalarType != kByte && scalarType != kBool) {
61
+ TORCH_CHECK_INDEX(false, "tensors used as indices must be long, byte or bool tensors");
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+
68
+ inline torch::List<c10::optional<Tensor>> toListOfOptionalTensors(ArrayRef<Tensor> list) {
69
+ torch::List<c10::optional<Tensor>> result;
70
+ result.reserve(list.size());
71
+ for (const Tensor& a : list) {
72
+ result.push_back(a);
73
+ }
74
+ return result;
75
+ }
76
+
77
+ inline torch::List<c10::optional<Tensor>> toListOfOptionalTensors(ArrayRef<IValue> list) {
78
+ torch::List<c10::optional<Tensor>> result;
79
+ result.reserve(list.size());
80
+ for (const IValue& a : list) {
81
+ result.push_back(a.isTensor() ? c10::optional<Tensor>(a.toTensor()) : c10::optional<Tensor>());
82
+ }
83
+ return result;
84
+ }
85
+
86
+ static C10_UNUSED bool hasContiguousSubspace(TensorList tl) {
87
+ // true if all the non-null tensors are adjacent
88
+ auto isDefined = [](const Tensor & tensor){ return tensor.defined(); };
89
+ auto isNull = [](const Tensor & tensor){ return !tensor.defined(); };
90
+ auto start = std::find_if(tl.begin(), tl.end(), isDefined);
91
+ auto stop = std::find_if(tl.rbegin(), tl.rend(), isDefined);
92
+ auto it = std::find_if(start, stop.base(), isNull);
93
+ return it == stop.base();
94
+ }
95
+
96
+
97
+ // Transposes the tensor and indices together so that all the non-null indices
98
+ // index the first k dimensions of the tensor. Returns the transposed tensor
99
+ // and the reordered indices. For example:
100
+ // transposeToFront(tensor, {nullptr, a, nullptr, b})
101
+ // returns
102
+ // tensor.permute([1, 3, 0, 2]), {a, b, nullptr, nullptr}
103
+ static C10_UNUSED std::tuple<Tensor, std::vector<Tensor>>
104
+ transposeToFront(Tensor self, TensorList indices) {
105
+ std::vector<int64_t> dims;
106
+ std::vector<Tensor> transposedIndices;
107
+ dims.reserve(self.dim());
108
+ for (const auto i : c10::irange(self.dim())) {
109
+ if (indices[i].defined()) {
110
+ dims.push_back(i);
111
+ transposedIndices.emplace_back(indices[i]);
112
+ }
113
+ }
114
+ for (const auto i : c10::irange(self.dim())) {
115
+ if (!indices[i].defined()) {
116
+ dims.push_back(i);
117
+ transposedIndices.emplace_back();
118
+ }
119
+ }
120
+ return std::make_tuple(self.permute(dims), std::move(transposedIndices));
121
+ }
122
+
123
+ inline std::tuple<Tensor, std::vector<Tensor>, std::vector<int64_t>>
124
+ transposeToFrontAndInvPerm(Tensor self, TensorList indices) {
125
+ std::vector<int64_t> dims;
126
+ std::vector<int64_t> invPerm;
127
+ std::vector<Tensor> transposedIndices;
128
+ dims.reserve(self.dim());
129
+ invPerm.resize(self.dim());
130
+ for (const auto i : c10::irange(self.dim())) {
131
+ if (indices[i].defined()) {
132
+ dims.push_back(i);
133
+ transposedIndices.emplace_back(indices[i]);
134
+ }
135
+ }
136
+ for (const auto i : c10::irange(self.dim())) {
137
+ if (!indices[i].defined()) {
138
+ dims.push_back(i);
139
+ transposedIndices.emplace_back();
140
+ }
141
+ }
142
+ for (const auto i : c10::irange(self.dim())) {
143
+ invPerm[dims[i]] = i;
144
+ }
145
+ return std::make_tuple(self.permute(dims), std::move(transposedIndices), std::move(invPerm));
146
+ }
147
+
148
+ struct AdvancedIndex {
149
+ AdvancedIndex(const Tensor& src, TensorList indices);
150
+
151
+ Tensor src;
152
+ std::vector<Tensor> indices;
153
+ DimVector indexed_sizes;
154
+ DimVector indexed_strides;
155
+ int64_t dims_before;
156
+ int64_t dims_after;
157
+ };
158
+
159
+
160
+ }}
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/TensorIterator.h>
6
+ #include <c10/core/Scalar.h>
7
+
8
+ namespace at {
9
+ namespace native {
10
+
11
+ template <typename scalar_t>
12
+ C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(scalar_t weight) {
13
+ return std::abs(weight) < scalar_t(0.5);
14
+ }
15
+ template <typename scalar_t>
16
+ C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(c10::complex<scalar_t> weight) {
17
+ // Avoid the sqrt in abs(weight)
18
+ return (weight.real() * weight.real() + weight.imag() * weight.imag()) < scalar_t(0.25);
19
+ }
20
+
21
+ template <typename scalar_t, typename weight_t>
22
+ C10_HOST_DEVICE C10_ALWAYS_INLINE scalar_t lerp(scalar_t self_, scalar_t end_, weight_t weight_) {
23
+ using opmath_t = at::opmath_type<scalar_t>;
24
+ using opmath_weight_t = at::opmath_type<weight_t>;
25
+
26
+ opmath_t self = self_;
27
+ opmath_t end = end_;
28
+ opmath_weight_t weight = weight_;
29
+
30
+ // Conditional for better numeric. This has been discussed in
31
+ // https://github.com/pytorch/pytorch/pull/18871
32
+ return is_lerp_weight_small(weight)
33
+ ? self + weight * (end - self)
34
+ : end - (end - self) * (opmath_t(1) - weight);
35
+ }
36
+
37
+ using lerp_fn_scalar = void (*)(
38
+ at::TensorIteratorBase& iter,
39
+ const Scalar& weight);
40
+
41
+ using lerp_fn_tensor = void (*)(
42
+ at::TensorIteratorBase& iter);
43
+
44
+ DECLARE_DISPATCH(lerp_fn_scalar, lerp_kernel_scalar_weight);
45
+ DECLARE_DISPATCH(lerp_fn_tensor, lerp_kernel_tensor_weight);
46
+
47
+ } // namespace native
48
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebra.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/util/Optional.h>
5
+
6
+ namespace c10 {
7
+ class Scalar;
8
+ }
9
+
10
+ namespace at {
11
+ struct TensorIterator;
12
+ }
13
+
14
+ namespace at { namespace native {
15
+
16
+ using addr_fn = void (*)(TensorIterator &, const Scalar& beta, const Scalar& alpha);
17
+ DECLARE_DISPATCH(addr_fn, addr_stub);
18
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/ScalarType.h>
4
+ #include <c10/util/irange.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/strides.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <ATen/ExpandUtils.h>
9
+ #include <ATen/TensorUtils.h>
10
+ #include <ATen/native/TensorIterator.h>
11
+ #include <ATen/native/TransposeType.h>
12
+ #include <limits>
13
+ #include <type_traits>
14
+ #include <sstream>
15
+ #include <cstring>
16
+ #include <cctype>
17
+
18
+ #ifndef AT_PER_OPERATOR_HEADERS
19
+ #include <ATen/Functions.h>
20
+ #else
21
+ #include <ATen/ops/arange.h>
22
+ #include <ATen/ops/empty.h>
23
+ #include <ATen/ops/empty_like.h>
24
+ #include <ATen/ops/empty_strided.h>
25
+ #include <ATen/ops/zeros.h>
26
+ #endif
27
+
28
+ namespace at { namespace native {
29
+
30
+ static inline c10::MaybeOwned<Tensor> expect_resolved_conj(const Tensor& tensor) {
31
+ if (tensor.is_conj()) {
32
+ return c10::MaybeOwned<Tensor>::owned(tensor.resolve_conj());
33
+ } else {
34
+ return c10::MaybeOwned<Tensor>::borrowed(tensor);
35
+ }
36
+ }
37
+
38
+ static inline DimVector batched_matrix_contiguous_strides(
39
+ const IntArrayRef sizes,
40
+ const bool f_contig = false) {
41
+ // f_contig chooses between the strides of a batch of Fortran (F-contiguous)
42
+ // and C-contiguous matrices
43
+ auto strides = c10::contiguous_strides(sizes);
44
+ auto dim = strides.size();
45
+
46
+ if (f_contig && dim >= 2) {
47
+ // Fix the strides of the last two dimensions, so that we return
48
+ // C-contiguous batches of F-contiguous matrices.
49
+ strides[dim - 1] = std::max(sizes[dim - 2], static_cast<int64_t>(1));
50
+ strides[dim - 2] = 1;
51
+ }
52
+ return strides;
53
+ }
54
+
55
+ /*
56
+ * Clones a Tensor so that the following conditions hold:
57
+ * If we think of a Tensor of having size (B, M, N), where B is any number
58
+ * of batch dimensions, then:
59
+ * - Each (M, N) matrix is in column major form
60
+ * - Let Tensor P have size (B, M, N) and Q have size (B, M', N').
61
+ * Then when laid out in memory, the M by N matrix starting at
62
+ * P.data_ptr()[B * M * N] is of the same corresponding batch as the M' by N'
63
+ * matrix starting at Q.data_ptr()[B * M' * N'].
64
+ */
65
+ static inline Tensor cloneBatchedColumnMajor(const Tensor& src) {
66
+ // If src is already in batched column major format, then
67
+ // this will be efficient (no reordering of the data will occur)
68
+ // because the first transpose will make the tensor contiguous,
69
+ // and cloning a contiguous tensor is fast.
70
+ auto result = src.mT().clone(at::MemoryFormat::Contiguous);
71
+ result.transpose_(-2, -1);
72
+ return result;
73
+ }
74
+
75
+ /*
76
+ * contig chooses between C-contig (true) and F-contig (false)
77
+ */
78
+ static inline c10::MaybeOwned<Tensor> borrow_else_clone(const bool cond, const Tensor& borrow, const Tensor& clone, const bool contig) {
79
+ return cond ? c10::MaybeOwned<Tensor>::borrowed(borrow)
80
+ : c10::MaybeOwned<Tensor>::owned(contig ? clone.clone(MemoryFormat::Contiguous)
81
+ : cloneBatchedColumnMajor(clone));
82
+ }
83
+
84
+ /*
85
+ * This method is designed to be a faster alternative to
86
+ * `cloneBatchedColumnMajor` with some additional features,
87
+ * namely:
88
+ * 1. It uses `copy` instead of `clone` which could be much faster.
89
+ * 2. `nrows` parameter used to create inputs with the number of rows larger
90
+ * than the original input, which is required for some LAPACK/MAGMA methods.
91
+ * 3. `desired_batch_size` is used to create copies with the batch size
92
+ * which is either the original batch size of the input, or its larger
93
+ * broadcasted shape.
94
+ */
95
+ static inline Tensor copyBatchedColumnMajor(const Tensor& src, int64_t nrows = -1,
96
+ at::OptionalIntArrayRef desired_batch_sizes = c10::nullopt) {
97
+ nrows = (nrows == -1) ? src.size(-2) : nrows;
98
+ auto copy_sizes = desired_batch_sizes.has_value()
99
+ ? desired_batch_sizes.value().vec()
100
+ : IntArrayRef(src.sizes().data(), src.dim() - 2).vec();
101
+ copy_sizes.insert(copy_sizes.end(), {nrows, src.size(-1)});
102
+ const auto copy_strides = batched_matrix_contiguous_strides(copy_sizes, /*f-contig*/true);
103
+ auto copy = at::empty_strided(copy_sizes, copy_strides, src.options());
104
+ copy.narrow(-2, 0, src.size(-2)).copy_(src);
105
+ return copy;
106
+ }
107
+
108
+ /*
109
+ * Given batches of matrices with arbitrary batch dim,
110
+ * computes the number of batches.
111
+ */
112
+ static inline int64_t batchCount(const Tensor& batched_matrices) {
113
+ int64_t result = 1;
114
+ for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
115
+ result *= batched_matrices.size(i);
116
+ }
117
+ return result;
118
+ }
119
+
120
+ // Computes the number of elements of a matrix in a batched matrix tensor
121
+ static inline int64_t matrixStride(const Tensor& batched_matrices) {
122
+ return batched_matrices.size(-1) * batched_matrices.size(-2);
123
+ }
124
+
125
+ // Validates input shapes for operations on batches of square matrices (inverse, cholesky, symeig, eig)
126
+ static inline void checkIsMatrix(const Tensor& A, const char* const f_name, const char* const arg_name = "A") {
127
+ TORCH_CHECK(A.dim() >= 2, f_name, ": The input tensor ", arg_name, " must have at least 2 dimensions.");
128
+ }
129
+ static inline void squareCheckInputs(const Tensor& self, const char* const f_name, const char* const arg_name = "A") {
130
+ checkIsMatrix(self, f_name, arg_name);
131
+ TORCH_CHECK(self.size(-1) == self.size(-2),
132
+ f_name,
133
+ ": ", arg_name, " must be batches of square matrices, "
134
+ "but they are ", self.size(-2), " by ", self.size(-1), " matrices");
135
+ }
136
+
137
+ static inline void checkInputsSolver(const Tensor& A,
138
+ const Tensor& B,
139
+ const bool left,
140
+ const char* const f_name) {
141
+ squareCheckInputs(A, f_name, "A");
142
+ checkIsMatrix(B, f_name, "B");
143
+ TORCH_CHECK(left ? A.size(-2) == B.size(-2) : A.size(-1) == B.size(-1),
144
+ f_name, ": Incompatible shapes of A and B for the equation ",
145
+ left ? "AX = B" : "XA = B",
146
+ " (", A.size(-2), "x", A.size(-1), " and ", B.size(-2), "x", B.size(-1), ")");
147
+ }
148
+
149
+ static inline bool is_row_or_column_contiguous(const Tensor& t) {
150
+ // This could be made more general, similar to how it's checked in matmul, which would allow to
151
+ // ellide the copy with strides such as (6, 12, 1, 3) or (3, 1, 9), but this is quite tricky.
152
+ // We choose to be conservative for simplicity
153
+ return t.is_contiguous() || t.transpose(-2, -1).is_contiguous();
154
+ }
155
+
156
+ static inline TransposeType to_transpose_type(const bool contig, const bool conj) {
157
+ if (conj) {
158
+ if (contig) { TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); }
159
+ else { return TransposeType::ConjTranspose; }
160
+ } else {
161
+ if (contig) { return TransposeType::NoTranspose; }
162
+ else { return TransposeType::Transpose; }
163
+ }
164
+ }
165
+
166
+
167
+ // This function is designed to be used with linear algebra methods that minimize
168
+ // L(ax - b) = 0, where L is generally the identity map (`solve`, for example)
169
+ // or the L2 norm (`lstsq`).
170
+ // It is expected that `a` and `b` are contiguous tensors of column-major matrices
171
+ // (so that a.view({-1, a.size(-2), a.size(-1)}) succeeds, same for `b`),
172
+ // with the following additional properties:
173
+ //
174
+ // 1. a.dim() == b.dim()
175
+ // 2. a.shape[:-2] broadcasts over b.shape[:-2]
176
+ // 3. a.size(i) <= b.size(i) for i=0,..., a.dim() - 3 (only for batch dimensions)
177
+ //
178
+ // MAGMA/LAPACK modify tensor `a` in-place, and the main goal of this method
179
+ // is to be memory efficient, which means that if there exists an index i such that
180
+ // a.shape[i] < b.shape[i], 0 <= i <= a.dim() - 3,
181
+ // then instead of materializing copies of `a` in the broadcasted shape, we keep
182
+ // a buffer copy of `a` along with flags that check whether specific batch dimension
183
+ // indices for `a` were already accessed. If they were, we copy the data from the buffer
184
+ // into `a`. The number of copies does not exceed
185
+ // prod(max(a.shape[:-2], b.shape[:-2]) - a.shape[:-2] + 1)
186
+ // and this value is attained by tensors with non-empty batch dimensions.
187
+ //
188
+ // func_t `f` is a callable that is being supplied with
189
+ // scalar_t* a_working_ptr, scalar_t* b_working_ptr, int64_t a_linear_batch_idx.
190
+ // a_working_ptr and b_working_ptr can directly be passed to LAPACK/MAGMA routines,
191
+ // and a_linear_batch_idx is an index in the 3d representation which corresponds to
192
+ // the memory a_working_ptr points to, in other words:
193
+ // a_working_ptr == a.view({-1, a.size(-2), a.size(-1)}.select(0, a_linear_batch_idx).data_ptr<scalar_t>();
194
+ // a_linear_batch_idx is useful to store metadata related to `a`, such as, for example,
195
+ // its rank or singular values (see linalg_lstsq).
196
+ template<typename scalar_t, typename func_t>
197
+ void batch_iterator_with_broadcasting(const Tensor& a, const Tensor& b, const func_t& f) {
198
+ IntArrayRef a_batch_sizes(a.sizes().data(), a.dim() - 2);
199
+ IntArrayRef b_batch_sizes(b.sizes().data(), b.dim() - 2);
200
+
201
+ auto a_linear_batch_idx = at::arange(batchCount(a)).view(a_batch_sizes);
202
+ auto b_linear_batch_idx = at::arange(batchCount(b)).view(b_batch_sizes);
203
+
204
+ TensorIterator iter = TensorIteratorConfig()
205
+ .set_check_mem_overlap(false)
206
+ .check_all_same_dtype(false)
207
+ .resize_outputs(false)
208
+ .add_output(b_linear_batch_idx)
209
+ .add_input(a_linear_batch_idx)
210
+ .build();
211
+
212
+ auto m = a.size(-2);
213
+ auto n = a.size(-1);
214
+ auto a_3d = a.view({batchCount(a), m, n});
215
+ auto b_3d = b.view({batchCount(b), b.size(-2), b.size(-1)});
216
+
217
+ auto a_broadcasts_over_b = (a_batch_sizes != b_batch_sizes);
218
+ Tensor a_buffer, a_was_accessed, a_buffer_3d;
219
+ std::function<void(int64_t)> check_if_copy_needed_for_a
220
+ = [](int64_t /*a_curr_linear_batch_idx*/){};
221
+ if (a_broadcasts_over_b) {
222
+ a_buffer = at::empty_strided(a.sizes(), a.strides(), a.options())
223
+ .copy_(a);
224
+ a_was_accessed = at::zeros(batchCount(a), at::kBool);
225
+ a_buffer_3d = a_buffer.view({batchCount(a), m, n});
226
+ check_if_copy_needed_for_a = [&](int64_t a_curr_linear_batch_idx) {
227
+ auto* a_was_accessed_flag = a_was_accessed
228
+ .select(0, a_curr_linear_batch_idx)
229
+ .data_ptr<bool>();
230
+ if (!(*a_was_accessed_flag)) {
231
+ *a_was_accessed_flag = true;
232
+ }
233
+ else {
234
+ a_3d.select(0, a_curr_linear_batch_idx)
235
+ .copy_(a_buffer_3d.select(0, a_curr_linear_batch_idx));
236
+ }
237
+ };
238
+ }
239
+
240
+ auto loop = [&](char** data, const int64_t* strides, int64_t nelems) {
241
+ auto* b_batch_idx_ptr = data[0];
242
+ auto* a_batch_idx_ptr = data[1];
243
+
244
+ for (const auto elem C10_UNUSED : c10::irange(nelems)) {
245
+ auto b_curr_linear_batch_idx = *reinterpret_cast<int64_t*>(b_batch_idx_ptr);
246
+ auto a_curr_linear_batch_idx = *reinterpret_cast<int64_t*>(a_batch_idx_ptr);
247
+
248
+ check_if_copy_needed_for_a(a_curr_linear_batch_idx);
249
+
250
+ auto* a_working_ptr = a_3d.select(0, a_curr_linear_batch_idx)
251
+ .data_ptr<scalar_t>();
252
+ auto* b_working_ptr = b_3d.select(0, b_curr_linear_batch_idx)
253
+ .data_ptr<scalar_t>();
254
+ f(a_working_ptr, b_working_ptr, a_curr_linear_batch_idx);
255
+
256
+ b_batch_idx_ptr += strides[0];
257
+ a_batch_idx_ptr += strides[1];
258
+ }
259
+ };
260
+ iter.serial_for_each(loop, {0, batchCount(b)});
261
+ }
262
+
263
+ // Returns the epsilon value for floating types except half
264
+ static inline double _get_epsilon(const ScalarType& sc_type) {
265
+ switch (sc_type) {
266
+ case at::ScalarType::Float:
267
+ return static_cast<double>(std::numeric_limits<float>::epsilon());
268
+ case at::ScalarType::Double:
269
+ return std::numeric_limits<double>::epsilon();
270
+ default:
271
+ AT_ERROR("This function doesn't handle types other than float and double");
272
+ }
273
+ }
274
+
275
+ // Validates input shapes and devices
276
+ // for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve)
277
+ static inline void linearSolveCheckInputs(const Tensor& self, const Tensor& A, const char* name) {
278
+ TORCH_CHECK(self.device() == A.device(),
279
+ "Expected b and A to be on the same device, but found b on ",
280
+ self.device(), " and A on ", A.device(), " instead.");
281
+
282
+ TORCH_CHECK(self.scalar_type() == A.scalar_type(),
283
+ "Expected b and A to have the same dtype, but found b of type ",
284
+ self.scalar_type(), " and A of type ", A.scalar_type(), " instead.");
285
+
286
+ TORCH_CHECK(A.size(-1) == A.size(-2),
287
+ "A must be batches of square matrices, "
288
+ "but they are ", A.size(-2), " by ", A.size(-1), " matrices");
289
+
290
+ TORCH_CHECK(A.size(-1) == self.size(-2),
291
+ "Incompatible matrix sizes for ", name, ": each A "
292
+ "matrix is ", A.size(-1), " by ", A.size(-1),
293
+ " but each b matrix is ", self.size(-2), " by ", self.size(-1));
294
+ }
295
+
296
+ static inline void checkFloatingOrComplex(const Tensor& t, const char* const f_name, const bool allow_low_precision_dtypes=true) {
297
+ auto dtype = t.scalar_type();
298
+ TORCH_CHECK((at::isFloatingType(dtype) || at::isComplexType(dtype)),
299
+ f_name, ": Expected a floating point or complex tensor as input. Got ", dtype);
300
+ if (!allow_low_precision_dtypes) {
301
+ TORCH_CHECK(dtype == kFloat || dtype == kDouble || dtype == kComplexFloat || dtype == kComplexDouble,
302
+ f_name, ": Low precision dtypes not supported. Got ", dtype);
303
+ }
304
+ }
305
+
306
+
307
+ // Checks if all the Tensors in a TensorList are of the same dimensions
308
+ static inline void checkAllSameDim(TensorList tensors, int64_t dim) {
309
+ for (auto &t : tensors) {
310
+ TORCH_CHECK(t.dim() == dim, "Tensor dimension is ", t.dim(), ", expected ", dim, " instead.");
311
+ }
312
+ }
313
+
314
+ static inline std::tuple<std::vector<int64_t>, std::vector<int64_t>> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2) {
315
+ // broadcast the batch dimensions of arg1 and arg2.
316
+ IntArrayRef arg1_batch_sizes(arg1.sizes().data(), arg1.ndimension() - 2);
317
+ IntArrayRef arg2_batch_sizes(arg2.sizes().data(), arg2.ndimension() - 2);
318
+ std::vector<int64_t> expand_batch_portion = infer_size(arg1_batch_sizes, arg2_batch_sizes);
319
+
320
+ std::vector<int64_t> arg1_expand_size({expand_batch_portion});
321
+ arg1_expand_size.insert(arg1_expand_size.end(), { arg1.size(-2), arg1.size(-1) });
322
+
323
+ std::vector<int64_t> arg2_expand_size({expand_batch_portion});
324
+ arg2_expand_size.insert(arg2_expand_size.end(), { arg2.size(-2), arg2.size(-1) });
325
+ return std::make_tuple(std::move(arg1_expand_size), std::move(arg2_expand_size));
326
+ }
327
+
328
+ static inline std::tuple<Tensor,Tensor> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2, const char* name) {
329
+ // If there's no name we assume we don't want to check the errors
330
+ if (name != nullptr) {
331
+ linearSolveCheckInputs(arg1, arg2, name);
332
+ }
333
+
334
+ std::vector<int64_t> arg1_expand_size, arg2_expand_size;
335
+ std::tie(arg1_expand_size, arg2_expand_size) = at::native::_linalg_broadcast_batch_dims(arg1, arg2);
336
+
337
+ auto arg1_broadcasted = arg1_expand_size == arg1.sizes() ? arg1 : arg1.expand(arg1_expand_size);
338
+ auto arg2_broadcasted = arg2_expand_size == arg2.sizes() ? arg2 : arg2.expand(arg2_expand_size);
339
+ return std::make_tuple(arg1_broadcasted, arg2_broadcasted);
340
+ }
341
+
342
+ static inline std::vector<int64_t> broadcast_batch_size(const Tensor& t1, const Tensor& t2, int64_t n_batch_dims) {
343
+ IntArrayRef t1_batch_sizes(t1.sizes().data(), n_batch_dims);
344
+ IntArrayRef t2_batch_sizes(t2.sizes().data(), n_batch_dims);
345
+ auto broadcasted_batch_sizes = infer_size(t1_batch_sizes, t2_batch_sizes);
346
+ return broadcasted_batch_sizes;
347
+ }
348
+
349
+ // Return a permutation with the given axes moved to the end.
350
+ static inline Tensor _move_to_end(const Tensor& self, IntArrayRef axes) {
351
+ const std::vector<int64_t> a = axes.vec();
352
+ const int64_t ndim = self.ndimension();
353
+ std::vector<int64_t> perm;
354
+
355
+ for (const auto i : c10::irange(ndim)) {
356
+ auto it = std::find(a.begin(), a.end(), i);
357
+ if (it == a.end()) {
358
+ perm.push_back(i);
359
+ }
360
+ }
361
+ for (auto i : a) {
362
+ perm.push_back(i);
363
+ }
364
+
365
+ TORCH_CHECK((int64_t)perm.size() == ndim,
366
+ "duplicate or invalid axis in 'dim' argument for tensor with ndim==", ndim);
367
+
368
+ return self.permute(perm);
369
+ }
370
+
371
+ // parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced)
372
+ static inline std::tuple<bool, bool> _parse_qr_mode(c10::string_view mode) {
373
+ bool compute_q;
374
+ bool reduced;
375
+ if (mode == "reduced") {
376
+ compute_q = true;
377
+ reduced = true;
378
+ } else if (mode == "complete") {
379
+ compute_q = true;
380
+ reduced = false;
381
+ } else if (mode == "r") {
382
+ compute_q = false;
383
+ reduced = true; // this is actually irrelevant in this mode
384
+ } else {
385
+ TORCH_CHECK(false, "qr received unrecognized mode '", mode,
386
+ "' but expected one of 'reduced' (default), 'r', or 'complete'");
387
+ }
388
+ return std::make_tuple(compute_q, reduced);
389
+ }
390
+
391
+ // Function to compute sizes, strides and the extra columns for the Q matrix in the QR Decomposition
392
+ static inline std::tuple<DimVector, DimVector, int64_t> _compute_geometry_for_Q(
393
+ const Tensor& input,
394
+ bool reduced) {
395
+ int64_t m = input.size(-2), n = input.size(-1);
396
+ int64_t n_columns_q;
397
+
398
+ // We need to compute the required size of Q based on the `reduced` option
399
+ DimVector q_sizes(input.sizes());
400
+ if (!reduced && m > n) {
401
+ q_sizes[input.dim() - 1] = m;
402
+ n_columns_q = m;
403
+ } else {
404
+ q_sizes[input.dim() - 1] = n;
405
+ n_columns_q = std::min(m, n);
406
+ }
407
+ auto q_strides = batched_matrix_contiguous_strides(q_sizes, /*f-contig*/true);
408
+ return std::make_tuple(q_sizes, q_strides, n_columns_q);
409
+ }
410
+
411
+ static inline bool svd_uses_cusolver(const Tensor& A) {
412
+ // if cusolver is available, it is used unconditionally
413
+ return A.is_cuda()
414
+ && at::globalContext().hasCuSOLVER()
415
+ && at::globalContext().linalgPreferredBackend() != at::LinalgBackend::Magma;
416
+ }
417
+
418
+
419
+ // Function used instead of .to so that the original strides are retained
420
+ // .to doesn't retain strides and make the output tensor contiguous
421
+ static inline Tensor same_stride_to(const Tensor& original_tensor, const at::TensorOptions& options) {
422
+ auto strided_to = at::empty_strided(original_tensor.sizes(),
423
+ original_tensor.strides(),
424
+ options);
425
+ strided_to.copy_(original_tensor);
426
+ return strided_to;
427
+ }
428
+
429
+ // Creates a dimension permutation array that can be given to `at::permute()`, which will shift
430
+ // the two specified dimensions to the end of a tensor, without changing the order of
431
+ // the other dimensions. `dim1` will be placed at the very end, and `dim0` will be
432
+ // placed just to the left of it.
433
+ //
434
+ // For instance, given a 4-D tensor, dimensions 1 and 3 can be shifted to the end by
435
+ // calling `create_dim_backshift_permutation(1, 3, 4)`. The resulting vector will
436
+ // be `vec(0, 2, 1, 3)`.
437
+ static inline std::vector<int64_t> create_dim_backshift_permutation(int64_t dim0, int64_t dim1, int64_t ndim) {
438
+ TORCH_CHECK(
439
+ (dim0 != dim1) && (dim0 < ndim) && (dim0 >= 0) && (dim1 < ndim) && (dim1 >= 0),
440
+ "duplicate or invalid dimensions");
441
+ std::vector<int64_t> permutation(ndim);
442
+ int64_t cur_permuted_dim = 0;
443
+ for (const auto dim_ind : c10::irange(ndim)) {
444
+ if ((dim_ind != dim0) && (dim_ind != dim1)) {
445
+ permutation[cur_permuted_dim++] = dim_ind;
446
+ }
447
+ }
448
+ permutation[cur_permuted_dim++] = dim0;
449
+ permutation[cur_permuted_dim] = dim1;
450
+ return permutation;
451
+ }
452
+
453
+ // Creates a dimension permutation array that can be given to `at::permute()`, which
454
+ // will reverse a given permutation.
455
+ // The reverse permutation array is created by swapping the indices and their
456
+ // associated values from the given permutation array.
457
+ static inline std::vector<int64_t> create_reverse_permutation(std::vector<int64_t> permutation) {
458
+ int64_t ndim = permutation.size();
459
+ std::vector<int64_t> reverse_permutation(ndim);
460
+ for (const auto dim_ind : c10::irange(ndim)) {
461
+ reverse_permutation[permutation[dim_ind]] = dim_ind;
462
+ }
463
+ return reverse_permutation;
464
+ }
465
+
466
+ // Compute R-work array size for MAGMA/LAPACK cgesdd/zgesdd
467
+ // See https://github.com/Reference-LAPACK/lapack/blob/122506cd8b6ce050a200920c3d4c0b153b150fd8/SRC/cgesdd.f#L186
468
+ static inline int64_t computeLRWorkDim(const char jobz, int64_t m, int64_t n) {
469
+ auto mn = std::min(m, n);
470
+ auto mx = std::max(m, n);
471
+ if (jobz == 'N') {
472
+ #ifdef __APPLE__
473
+ // According to `vecLib.framework/Headers/clapack.h` Accelerate.framework is based on LAPACK 3.2.1
474
+ return 7 * mn;
475
+ #else
476
+ // These setting is valid for on LAPACK 3.6+
477
+ return 5 * mn;
478
+ #endif
479
+ }
480
+ if (mx > 10 * mn) {
481
+ return 5 * mn * mn + 5 * mn;
482
+ }
483
+ return std::max(5 * mn * mn + 5 * mn, 2 * mx * mn + 2 * mn * mn + mn);
484
+ }
485
+
486
+ // This function checks whether the uplo argument input is valid
487
+ // Allowed strings are "u", "U", "l", "L"
488
+ static inline void checkUplo(const c10::string_view uplo) {
489
+ // To use std::toupper safely with plain chars (or signed chars), the argument should first be converted to unsigned char
490
+ char uplo_uppercase = static_cast<char>(std::toupper(static_cast<unsigned char>(uplo[0])));
491
+ TORCH_CHECK(uplo.size() == 1 && (uplo_uppercase == 'U' || uplo_uppercase == 'L'),
492
+ "Expected UPLO argument to be 'L' or 'U', but got ", uplo);
493
+ }
494
+
495
+ static inline void checkSameDevice(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
496
+ TORCH_CHECK(
497
+ result.device() == input.device(),
498
+ fn_name,
499
+ ": Expected ", result_name, " and input tensors to be on the same device, but got ",
500
+ result_name, " on ", result.device(), " and input on ", input.device());
501
+ }
502
+
503
+ // Check the dtype of result and input tensors (for _out variants).
504
+ // Most linear algebra functions have the same dtype for input and output
505
+ // (either floating or complex type input), so we can check whether input's dtype can be casted to result's dtype.
506
+ // According to https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-does-out-work-in-pytorch
507
+ // c10::canCast is used for checking the "safe copy" dtype requirements.
508
+ static inline void checkLinalgCompatibleDtype(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
509
+ bool can_cast = c10::canCast(input.scalar_type(), result.scalar_type());
510
+ TORCH_CHECK(
511
+ can_cast,
512
+ fn_name,
513
+ ": Expected ", result_name, " to be safely castable from ", input.scalar_type(), " dtype, but got ",
514
+ result_name, " with dtype ", result.scalar_type());
515
+ }
516
+
517
+ // Alternatively, we can check whether the specific expected output type (result_type) can be safely casted to out tensor dtype (out_type)
518
+ static inline void checkLinalgCompatibleDtype(const std::string& fn_name, ScalarType out_type, ScalarType result_type, const std::string& out_name = "result") {
519
+ bool can_cast = c10::canCast(result_type, out_type);
520
+ TORCH_CHECK(
521
+ can_cast,
522
+ fn_name,
523
+ ": Expected ", out_name, " to be safely castable from ", result_type, " dtype, but got ",
524
+ out_name, " with dtype ", out_type);
525
+ }
526
+
527
+ static inline void checkNotComplexTolerance(const Tensor& tol, const c10::string_view f_name, const c10::string_view tol_name) {
528
+ TORCH_CHECK(!at::isComplexType(tol.scalar_type()),
529
+ f_name, ": ", tol_name, " tensor of complex type is not supported. Got ", tol.scalar_type());
530
+ }
531
+
532
+ /*
533
+ Two types of 'other' tensors are supported when solving
534
+ a system of linear equations matmul(input, x) = other:
535
+ * 1-dimensional (1D) tensor or batch of 1D tensors (vector case)
536
+ * 2-dimensional (2D) tensor or batch of 2D tensors (matrix case).
537
+ The original torch.solve supported only the matrix case, while NumPy works for both cases.
538
+ For the batched input we need to be able to distinguish them.
539
+ Let input.shape = (batch_dimensions, m, n), then 'other' is of vector type if other.shape == (batch_dimensions, m).
540
+ This rule is compatible with NumPy, see https://github.com/numpy/numpy/blob/v1.20.0/numpy/linalg/linalg.py#L384-L389
541
+ */
542
+ static inline bool linalg_solve_is_vector_rhs(const Tensor& input, const Tensor& other) {
543
+ auto expected_batched_rhs_shape = IntArrayRef(input.sizes().data(), input.dim() - 1); // input.shape[:-1]
544
+ bool vector_case = other.dim() == 1 || (input.dim() - 1 == other.dim() && other.sizes().equals(expected_batched_rhs_shape));
545
+ return vector_case;
546
+ }
547
+
548
+ /*
549
+ Computes linear indices for a tensor with original_shape to access its elements like it was a materialized broadcast tensor.
550
+ */
551
+ static inline Tensor get_linear_indices(int64_t numel, IntArrayRef original_shape, IntArrayRef broadcast_shape) {
552
+ TensorOptions options = at::TensorOptions().dtype(at::kLong).device(at::kCPU);
553
+ return at::arange(numel, options).view(original_shape).broadcast_to(broadcast_shape).contiguous();
554
+ }
555
+
556
+ class BroadcastLinearIndices {
557
+ private:
558
+ Tensor linear_indices_;
559
+ bool is_broadcasting_;
560
+
561
+ public:
562
+ BroadcastLinearIndices(
563
+ int64_t numel,
564
+ IntArrayRef original_shape,
565
+ IntArrayRef broadcast_shape) : is_broadcasting_(!original_shape.equals(broadcast_shape)) {
566
+ // The assumption is that the broadcast_shape is a materialized broadcast
567
+ // shape of the original_shape. We need to compute the linear indices
568
+ // compatible with the original_shape to access the elements in the original
569
+ // tensor corresponding to the broadcast tensor.
570
+ if (is_broadcasting_) {
571
+ linear_indices_ =
572
+ get_linear_indices(numel, original_shape, broadcast_shape);
573
+ }
574
+ }
575
+ int64_t operator()(int64_t broadcast_linear_index) {
576
+ return is_broadcasting_
577
+ ? linear_indices_.data_ptr<int64_t>()[broadcast_linear_index]
578
+ : broadcast_linear_index;
579
+ }
580
+ };
581
+
582
+ static inline bool is_blas_compatible_column_major_order(const Tensor& input) {
583
+ IntArrayRef input_strides = input.strides();
584
+ IntArrayRef input_sizes = input.sizes();
585
+ auto ndim = input.dim();
586
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
587
+ if (ndim > 3) {
588
+ return input.transpose(-2, -1).is_contiguous();
589
+ }
590
+ auto leading_dimension = input_strides[ndim - 1];
591
+ auto rows = input_sizes[ndim - 2];
592
+ bool batch_stride_compatible = true;
593
+ if (ndim == 3) {
594
+ auto cols = input_sizes[ndim - 1];
595
+ batch_stride_compatible =
596
+ input_strides[ndim - 3] >= leading_dimension * cols;
597
+ }
598
+ return (input_strides[ndim - 2] == 1) &&
599
+ (leading_dimension >= std::max<int64_t>(1, rows)) &&
600
+ batch_stride_compatible;
601
+ }
602
+
603
+ static inline bool is_blas_compatible_row_major_order(const Tensor& input) {
604
+ IntArrayRef input_strides = input.strides();
605
+ IntArrayRef input_sizes = input.sizes();
606
+ auto ndim = input.dim();
607
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
608
+ if (ndim > 3) {
609
+ return input.is_contiguous();
610
+ }
611
+ auto leading_dimension = input_strides[ndim - 2];
612
+ auto cols = input_sizes[ndim - 1];
613
+ bool batch_stride_compatible = true;
614
+ if (ndim == 3) {
615
+ auto rows = input_sizes[ndim - 2];
616
+ batch_stride_compatible =
617
+ input_strides[ndim - 3] >= leading_dimension * rows;
618
+ }
619
+ return (input_strides[ndim - 1] == 1) &&
620
+ (leading_dimension >= std::max<int64_t>(1, cols)) &&
621
+ batch_stride_compatible;
622
+ }
623
+
624
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/LossMulti.h ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/AccumulateType.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/TensorUtils.h>
6
+
7
+ namespace at { namespace native {
8
+ namespace {
9
+ static C10_UNUSED void multilabel_margin_loss_shape_check(
10
+ int64_t& nframe,
11
+ int64_t& dim,
12
+ const int64_t& ndims,
13
+ TensorArg& target_arg,
14
+ const Tensor& input,
15
+ const Tensor& target) {
16
+ bool valid_inputs = (ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0;
17
+ TORCH_CHECK(
18
+ valid_inputs,
19
+ "Expected non-empty vector or matrix with optional 0-dim batch size, but got: ",
20
+ input.sizes());
21
+
22
+ if (ndims <= 1) {
23
+ nframe = 1;
24
+ dim = ndims == 0 ? 1 : input.size(0);
25
+ TORCH_CHECK(
26
+ valid_inputs && target.dim() <= 1 && target.numel() == dim,
27
+ "inconsistent size ",
28
+ target.sizes(),
29
+ " for ",
30
+ target_arg);
31
+ } else {
32
+ nframe = input.size(0);
33
+ dim = input.size(1);
34
+ TORCH_CHECK(
35
+ valid_inputs && target.dim() == 2 && target.size(0) == nframe &&
36
+ target.size(1) == dim,
37
+ "inconsistent size ",
38
+ target.sizes(),
39
+ " for ",
40
+ target_arg);
41
+ }
42
+ }
43
+
44
+ static C10_UNUSED void multi_margin_loss_shape_check(
45
+ int64_t& nframe,
46
+ int64_t& dim,
47
+ const int64_t& ndims,
48
+ TensorArg& target_arg,
49
+ const Tensor& input,
50
+ const Tensor& target) {
51
+ bool valid_inputs = (ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0;
52
+ if (ndims <= 1) {
53
+ nframe = 1;
54
+ dim = ndims == 0 ? 1 : input.size(0);
55
+ } else {
56
+ nframe = input.size(0);
57
+ dim = input.size(1);
58
+ }
59
+
60
+ TORCH_CHECK(
61
+ valid_inputs,
62
+ "Expected non-empty vector or matrix with optional 0-dim batch size, but got: ",
63
+ input.sizes());
64
+ TORCH_CHECK(
65
+ valid_inputs && target.dim() <= 1 && target.numel() == nframe,
66
+ "inconsistent target size, got: ",
67
+ target.sizes());
68
+ }
69
+
70
+
71
+ } // anonymous namespace
72
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Math.h ADDED
The diff for this file is too large to render. See raw diff
 
wemm/lib/python3.10/site-packages/torch/include/ATen/native/MathBitFallThroughLists.h ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ namespace at {
4
+ // views and their in-place version ops
5
+ #define TORCH_VIEW_FNS(m) \
6
+ m.impl("as_strided_", torch::CppFunction::makeFallthrough()); \
7
+ m.impl("detach", torch::CppFunction::makeFallthrough()); \
8
+ m.impl("detach_", torch::CppFunction::makeFallthrough()); \
9
+ m.impl("diagonal", torch::CppFunction::makeFallthrough()); \
10
+ m.impl("expand", torch::CppFunction::makeFallthrough()); \
11
+ m.impl("expand_as", torch::CppFunction::makeFallthrough()); \
12
+ m.impl("movedim.int", torch::CppFunction::makeFallthrough()); \
13
+ m.impl("movedim.intlist", torch::CppFunction::makeFallthrough()); \
14
+ m.impl("narrow", torch::CppFunction::makeFallthrough()); \
15
+ m.impl("permute", torch::CppFunction::makeFallthrough()); \
16
+ m.impl("select.Dimname", torch::CppFunction::makeFallthrough()); \
17
+ m.impl("select.int", torch::CppFunction::makeFallthrough()); \
18
+ m.impl("squeeze", torch::CppFunction::makeFallthrough()); \
19
+ m.impl("squeeze_", torch::CppFunction::makeFallthrough()); \
20
+ m.impl("transpose.int", torch::CppFunction::makeFallthrough()); \
21
+ m.impl("transpose.Dimname", torch::CppFunction::makeFallthrough()); \
22
+ m.impl("transpose_", torch::CppFunction::makeFallthrough()); \
23
+ m.impl("t", torch::CppFunction::makeFallthrough()); \
24
+ m.impl("t_", torch::CppFunction::makeFallthrough()); \
25
+ m.impl("real", torch::CppFunction::makeFallthrough()); \
26
+ m.impl("imag", torch::CppFunction::makeFallthrough()); \
27
+ m.impl("view_as_real", torch::CppFunction::makeFallthrough()); \
28
+ m.impl("unflatten.int", torch::CppFunction::makeFallthrough()); \
29
+ m.impl("unflatten.Dimname", torch::CppFunction::makeFallthrough()); \
30
+ m.impl("unfold", torch::CppFunction::makeFallthrough()); \
31
+ m.impl("unsqueeze", torch::CppFunction::makeFallthrough()); \
32
+ m.impl("unsqueeze_", torch::CppFunction::makeFallthrough()); \
33
+ m.impl("view_as", torch::CppFunction::makeFallthrough()); \
34
+ m.impl("unbind.int", torch::CppFunction::makeFallthrough()); \
35
+ m.impl("unbind.Dimname", torch::CppFunction::makeFallthrough()); \
36
+ m.impl("split.Tensor", torch::CppFunction::makeFallthrough()); \
37
+ m.impl("split_with_sizes", torch::CppFunction::makeFallthrough()); \
38
+ m.impl("swapaxes", torch::CppFunction::makeFallthrough()); \
39
+ m.impl("swapdims", torch::CppFunction::makeFallthrough()); \
40
+ m.impl("chunk", torch::CppFunction::makeFallthrough()); \
41
+ m.impl("reshape", torch::CppFunction::makeFallthrough()); \
42
+ m.impl("alias", torch::CppFunction::makeFallthrough()); \
43
+ m.impl("hsplit.int", torch::CppFunction::makeFallthrough()); \
44
+ m.impl("hsplit.array", torch::CppFunction::makeFallthrough()); \
45
+ m.impl("dsplit.int", torch::CppFunction::makeFallthrough()); \
46
+ m.impl("dsplit.array", torch::CppFunction::makeFallthrough()); \
47
+ m.impl("vsplit.int", torch::CppFunction::makeFallthrough()); \
48
+ m.impl("vsplit.array", torch::CppFunction::makeFallthrough()); \
49
+ m.impl("conj", torch::CppFunction::makeFallthrough()); \
50
+ m.impl("_conj", torch::CppFunction::makeFallthrough()); \
51
+ m.impl("_unsafe_view", torch::CppFunction::makeFallthrough()); \
52
+ m.impl("resize_", torch::CppFunction::makeFallthrough());
53
+
54
+ #define TENSOR_UTILITIES_AND_CONSTRUCTORS(m) \
55
+ m.impl("empty_like", torch::CppFunction::makeFallthrough()); \
56
+ m.impl("empty.memory_format", torch::CppFunction::makeFallthrough()); \
57
+ m.impl("empty.out", torch::CppFunction::makeFallthrough()); \
58
+ m.impl("empty_strided", torch::CppFunction::makeFallthrough()); \
59
+ m.impl("full_like", torch::CppFunction::makeFallthrough()); \
60
+ m.impl("stride.int", torch::CppFunction::makeFallthrough()); \
61
+ m.impl("stride.Dimname", torch::CppFunction::makeFallthrough()); \
62
+ m.impl("size.int", torch::CppFunction::makeFallthrough()); \
63
+ m.impl("size.Dimname", torch::CppFunction::makeFallthrough()); \
64
+ m.impl("is_complex", torch::CppFunction::makeFallthrough()); \
65
+ m.impl("is_floating_point", torch::CppFunction::makeFallthrough()); \
66
+ m.impl("requires_grad_", torch::CppFunction::makeFallthrough());
67
+ }
68
+
69
+ #define TORCH_VIEW_FNS_NATIVE_FN_REGISTRATION(m) \
70
+ m.impl("as_strided", torch::CppFunction::makeFallthrough()); \
71
+ m.impl("view", torch::CppFunction::makeFallthrough());
wemm/lib/python3.10/site-packages/torch/include/ATen/native/MaxPooling.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at {
8
+ namespace native {
9
+
10
+ // TODO(Heitor) Template by dimension
11
+ struct PoolingParams1D {
12
+ int64_t NB; // Number of batches
13
+ int64_t NC; // Number of channels
14
+ int64_t IW; // Input width
15
+ int64_t OW; // Output width
16
+ int64_t KW; // Kernel width
17
+ int64_t SJ; // Column stride
18
+ int64_t PJ; // Column padding
19
+ int64_t DJ; // Column dilation
20
+
21
+ // Return index of input element for the given kernel and output index
22
+ inline int64_t index(int64_t kj, int64_t oj) const {
23
+ return oj * SJ + kj * DJ - PJ;
24
+ }
25
+
26
+ // Return index of first output within bounds for this kernel index
27
+ inline int64_t valid_output_start(int64_t kj) const {
28
+ int64_t ij = index(kj, 0);;
29
+ return ij < 0 ? at::divup(-ij, SJ) : 0;
30
+ }
31
+
32
+ // Return index one past last output within bounds for this kernel index
33
+ inline int64_t valid_output_end(int64_t kj) const {
34
+ int64_t ij = index(kj, OW - 1);
35
+ return ij >= IW ? OW - at::divup(ij - (IW - 1), SJ) : OW;
36
+ }
37
+ };
38
+
39
+ using pooling_fn = void (*)(Tensor&, const Tensor&, const PoolingParams1D&);
40
+
41
+ DECLARE_DISPATCH(pooling_fn, max_pool1d_stub);
42
+
43
+ } // namespace native
44
+ } // namespace at
wemm/lib/python3.10/site-packages/torch/include/ATen/native/NonEmptyUtils.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/TensorBase.h>
2
+ #include <algorithm>
3
+ #include <vector>
4
+
5
+ namespace at { namespace native {
6
+
7
+ inline int64_t ensure_nonempty_dim(int64_t dim) {
8
+ return std::max<int64_t>(dim, 1);
9
+ }
10
+
11
+ inline int64_t ensure_nonempty_size(const TensorBase &t, int64_t dim) {
12
+ return t.dim() == 0 ? 1 : t.size(dim);
13
+ }
14
+
15
+ inline int64_t ensure_nonempty_stride(const TensorBase &t, int64_t dim) {
16
+ return t.dim() == 0 ? 1 : t.stride(dim);
17
+ }
18
+
19
+ using IdxVec = std::vector<int64_t>;
20
+ inline IdxVec ensure_nonempty_vec(IdxVec vec) {
21
+ if (vec.empty()) {
22
+ vec.push_back(1);
23
+ }
24
+ return vec;
25
+ }
26
+
27
+ }} // namespace at::native
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Normalization.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/TensorIterator.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace at {
7
+ namespace native {
8
+
9
+ using renorm_scale_factor_fn = void (*) (TensorIteratorBase& iter, double maxnorm);
10
+ DECLARE_DISPATCH(renorm_scale_factor_fn, renorm_scale_factor_stub);
11
+
12
+ }} // namespace at::native
wemm/lib/python3.10/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
wemm/lib/python3.10/site-packages/torch/include/ATen/native/Pool.h ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {
12
+ namespace native {
13
+
14
+ using max_pool2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input,
15
+ int kW, int kH, int dW, int dH, int padW, int padH, int dilationW, int dilationH);
16
+ using max_pool2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
17
+
18
+ DECLARE_DISPATCH(max_pool2d_fn, max_pool2d_kernel);
19
+ DECLARE_DISPATCH(max_pool2d_backward_fn, max_pool2d_backward_kernel);
20
+
21
+ // averge pooling has same signature for forward and backward
22
+ using avg_pool2d_fn = void(*)(const Tensor& output, const Tensor& input, int64_t kW, int64_t kH,
23
+ int64_t dW, int64_t dH, int64_t padW, int64_t padH, bool count_include_pad, c10::optional<int64_t> divisor_override);
24
+ using avg_pool2d_backward_fn = void(*)(const Tensor& output, const Tensor& input, int kW, int kH,
25
+ int dW, int dH, int padW, int padH, bool count_include_pad, c10::optional<int64_t> divisor_override);
26
+
27
+ DECLARE_DISPATCH(avg_pool2d_fn, avg_pool2d_kernel);
28
+ DECLARE_DISPATCH(avg_pool2d_backward_fn, avg_pool2d_backward_kernel);
29
+
30
+ namespace {
31
+
32
+ template <typename dest_t, typename src_t>
33
+ static inline dest_t
34
+ safe_downcast(src_t v)
35
+ {
36
+ TORCH_CHECK(std::numeric_limits<dest_t>::min() <= v && v <= std::numeric_limits<dest_t>::max(),
37
+ "integer out of range");
38
+
39
+ return static_cast<dest_t>(v);
40
+ }
41
+
42
+ template<typename T>
43
+ static inline T pooling_output_shape_pad_lr(
44
+ T inputSize, T kernelSize, T pad_l, T pad_r, T stride, T dilation,
45
+ bool ceil_mode) {
46
+ T outputSize = div_rtn<T>(
47
+ inputSize + pad_l + pad_r - dilation * (kernelSize - 1) - 1 +
48
+ (ceil_mode ? stride - 1 : 0), stride) + 1;
49
+ if (ceil_mode) {
50
+ // ensure that the last pooling starts inside the image
51
+ // needed to avoid problems in ceil mode
52
+ if ((outputSize - 1) * stride >= inputSize + pad_l) {
53
+ --outputSize;
54
+ }
55
+ }
56
+ return outputSize;
57
+ }
58
+
59
+ template<typename T>
60
+ static inline T pooling_output_shape(
61
+ T inputSize, T kernelSize, T pad, T stride, T dilation, bool ceil_mode) {
62
+ TORCH_CHECK(stride != 0, "stride should not be zero");
63
+ TORCH_CHECK(pad >= 0,
64
+ "pad must be non-negative, but got pad: ", pad);
65
+ TORCH_CHECK(pad <= kernelSize / 2,
66
+ "pad should be at most half of kernel size, but got pad=",
67
+ pad, " and kernel_size=", kernelSize)
68
+ return pooling_output_shape_pad_lr(
69
+ inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode);
70
+ }
71
+
72
+ template <typename T>
73
+ std::pair<T, T> _pooling_same_mode_padding_lr(
74
+ T inputSize, T kernelSize, int64_t stride, int64_t dilation) {
75
+ // NOTE: with strides, the output shape is ceil(inputSize/stride)
76
+ auto total_padding = T(dilation) * (kernelSize - 1);
77
+
78
+ // Prefer symmetric padding if possible
79
+ if (stride > 2 && (total_padding % 2 == 1)) {
80
+ // The floor in the output size calculation gives us a little wiggle room
81
+ auto wiggle_room = inputSize % stride - 1;
82
+ if (wiggle_room > 0) {
83
+ total_padding = total_padding - 1;
84
+ }
85
+ }
86
+
87
+ auto left = total_padding / 2;
88
+ return {left, total_padding - left};
89
+ }
90
+
91
+ inline std::pair<int64_t, int64_t> pooling_same_mode_padding_lr(
92
+ int64_t inputSize, int64_t kernelSize, int64_t stride, int64_t dilation) {
93
+ return _pooling_same_mode_padding_lr(inputSize, kernelSize, stride, dilation);
94
+ }
95
+
96
+ inline std::pair<c10::SymInt, c10::SymInt> pooling_same_mode_padding_lr(
97
+ c10::SymInt inputSize, c10::SymInt kernelSize, int64_t stride, int64_t dilation) {
98
+ return _pooling_same_mode_padding_lr(std::move(inputSize), std::move(kernelSize), stride, dilation);
99
+ }
100
+
101
+ // AveragePool2d/DilatedMaxPool2d (forward)
102
+ static inline void
103
+ pool2d_shape_check(
104
+ const Tensor& input,
105
+ int kH, int kW, int dH, int dW, int padH, int padW, int dilationH, int dilationW,
106
+ int64_t nInputPlane,
107
+ int64_t inputHeight, int64_t inputWidth,
108
+ int64_t outputHeight, int64_t outputWidth, MemoryFormat memory_format)
109
+ {
110
+ const int64_t ndim = input.ndimension();
111
+ const int64_t nOutputPlane = nInputPlane;
112
+
113
+ TORCH_CHECK(kW > 0 && kH > 0,
114
+ "kernel size should be greater than zero, but got ",
115
+ "kH: ", kH, " kW: ", kW);
116
+ TORCH_CHECK(dW > 0 && dH > 0,
117
+ "stride should be greater than zero, but got "
118
+ "dH: ", dH, " dW: ", dW);
119
+ TORCH_CHECK(dilationH > 0 && dilationW > 0,
120
+ "dilation should be greater than zero, but got ",
121
+ "dilationH: ", dilationH, " dilationW: ", dilationW);
122
+
123
+ bool valid_dims = input.size(1) != 0 && input.size(2) != 0;
124
+ if (memory_format == at::MemoryFormat::ChannelsLast){
125
+ // Expect tensor in NHWC format and allow 0-dim only for N.
126
+ TORCH_CHECK((ndim == 4 && valid_dims && input.size(3) != 0),
127
+ "Expected 4D (batch mode) tensor expected for input with channels_last layout"
128
+ " with optional 0 dim batch size for input, but got: ", input.sizes());
129
+ } else {
130
+ TORCH_CHECK((ndim == 3 && input.size(0) != 0 && valid_dims) ||
131
+ (ndim == 4 && valid_dims && input.size(3) != 0),
132
+ "Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got:",
133
+ input.sizes());
134
+ }
135
+
136
+ TORCH_CHECK(kW/2 >= padW && kH/2 >= padH,
137
+ "pad should be smaller than or equal to half of kernel size, but got ",
138
+ "padW = ", padW, ", padH = ", padH, ", kW = ", kW, ", kH = ", kH);
139
+
140
+ TORCH_CHECK(outputWidth >= 1 && outputHeight >= 1,
141
+ "Given input size: (",
142
+ nInputPlane, "x", inputHeight, "x", inputWidth, "). ",
143
+ "Calculated output size: (",
144
+ nOutputPlane, "x", outputHeight, "x", outputWidth, "). ",
145
+ "Output size is too small");
146
+ }
147
+
148
+ // DilatedMaxPool2d (backward)
149
+ static inline void
150
+ max_pool2d_backward_shape_check(
151
+ const Tensor& input,
152
+ const Tensor& gradOutput,
153
+ const Tensor& indices,
154
+ int kH, int kW, int dH, int dW, int padH, int padW, int dilationH, int dilationW,
155
+ int64_t nInputPlane,
156
+ int64_t inputHeight, int64_t inputWidth,
157
+ int64_t outputHeight, int64_t outputWidth, MemoryFormat memory_format)
158
+ {
159
+ pool2d_shape_check(
160
+ input,
161
+ kH, kW, dH, dW, padH, padW, dilationH, dilationW,
162
+ nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, memory_format);
163
+
164
+ const int64_t ndim = input.ndimension();
165
+ const int64_t nOutputPlane = nInputPlane;
166
+
167
+ check_dim_size(gradOutput, ndim, ndim-3, nOutputPlane);
168
+ check_dim_size(gradOutput, ndim, ndim-2, outputHeight);
169
+ check_dim_size(gradOutput, ndim, ndim-1, outputWidth);
170
+
171
+ check_dim_size(indices, ndim, ndim-3, nOutputPlane);
172
+ check_dim_size(indices, ndim, ndim-2, outputHeight);
173
+ check_dim_size(indices, ndim, ndim-1, outputWidth);
174
+ }
175
+
176
+ // AveragePool2d (backward)
177
+ static inline void
178
+ avg_pool2d_backward_shape_check(
179
+ const Tensor& input,
180
+ const Tensor& gradOutput,
181
+ int64_t /*nbatch*/,
182
+ int kH, int kW, int dH, int dW, int padH, int padW,
183
+ int64_t nInputPlane,
184
+ int64_t inputHeight, int64_t inputWidth,
185
+ int64_t outputHeight, int64_t outputWidth,
186
+ MemoryFormat memory_format)
187
+ {
188
+ pool2d_shape_check(
189
+ input,
190
+ kH, kW, dH, dW, padH, padW, 1, 1,
191
+ nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth,
192
+ memory_format);
193
+
194
+ const int64_t ndim = input.ndimension();
195
+ const int64_t nOutputPlane = nInputPlane;
196
+
197
+ check_dim_size(gradOutput, ndim, ndim-3, nOutputPlane);
198
+ check_dim_size(gradOutput, ndim, ndim-2, outputHeight);
199
+ check_dim_size(gradOutput, ndim, ndim-1, outputWidth);
200
+ }
201
+
202
+ // AveragePool3d/DilatedMaxPool3d (forward)
203
+ static inline void
204
+ pool3d_shape_check(
205
+ const Tensor& input,
206
+ int64_t nslices,
207
+ int kT, int kH, int kW,
208
+ int dT, int dH, int dW,
209
+ int pT, int pH, int pW,
210
+ int dilationT, int dilationH, int dilationW,
211
+ int64_t itime, int64_t iheight, int64_t iwidth,
212
+ int64_t otime, int64_t oheight, int64_t owidth,
213
+ const char *fn_name,
214
+ bool check_input_size=false)
215
+ {
216
+ const int64_t ndim = input.ndimension();
217
+
218
+ TORCH_CHECK(kT > 0 && kW > 0 && kH > 0,
219
+ "kernel size should be greater than zero, but got ",
220
+ "kT: ", kT, " kH: ", kH, " kW: ", kW);
221
+ TORCH_CHECK(dT > 0 && dW > 0 && dH > 0,
222
+ "stride should be greater than zero, but got ",
223
+ "dT: ", dT, " dH: ", dH, " dW: ", dW);
224
+ TORCH_CHECK(dilationT > 0 && dilationW > 0 && dilationH > 0,
225
+ "dilation should be greater than zero, but got ",
226
+ "dilationT: ", dilationT, " dilationH: ", dilationH, " dilationW: ", dilationW);
227
+
228
+ TORCH_CHECK(ndim == 4 || ndim == 5,
229
+ fn_name, ": Expected 4D or 5D tensor for input, but got: ", input.sizes());
230
+
231
+ for (const auto i : c10::irange(ndim)) {
232
+ if (ndim == 5 && i == 0) {
233
+ // size of batch-dim can be 0.
234
+ continue;
235
+ }
236
+ TORCH_CHECK(
237
+ input.size(i) > 0,
238
+ fn_name,
239
+ ": Expected input's non-batch dimensions to have positive length,"
240
+ " but input has a shape of ",
241
+ input.sizes(),
242
+ " and non-batch dimension ",
243
+ input.size(i),
244
+ " has length zero!")
245
+ }
246
+
247
+ if (check_input_size) { // AveragePool3d
248
+ TORCH_CHECK(itime >= kT && iheight >= kH && iwidth >= kW,
249
+ "input image ", "(T: ", itime, " H: ", iheight, " W: ", iwidth, ") smaller than ",
250
+ "kernel size ", "(kT: ", kT, " kH: ", kH, " kW: ", kW, ")");
251
+ }
252
+
253
+ TORCH_CHECK(kT/2 >= pT && kW/2 >= pW && kH/2 >= pH,
254
+ "pad should be smaller than or equal to half of kernel size, but got "
255
+ "kT: ", kT, " kW: ", kW, " kH: ", kH, " padT: ", pT, " padW: ", pW, " padH: ", pH);
256
+
257
+ TORCH_CHECK(otime >= 1 && owidth >= 1 && oheight >= 1,
258
+ "Given input size: (",
259
+ nslices,"x", itime, "x", iheight, "x", iwidth, "). ",
260
+ "Calculated output size: (",
261
+ nslices, "x", otime, "x", oheight, "x", owidth, "). ",
262
+ "Output size is too small");
263
+ }
264
+
265
+ static inline void
266
+ max_pool3d_backward_shape_check(
267
+ const Tensor& input,
268
+ const Tensor& gradOutput,
269
+ const Tensor& indices,
270
+ int64_t nslices,
271
+ int kT, int kH, int kW,
272
+ int dT, int dH, int dW,
273
+ int pT, int pH, int pW,
274
+ int dilationT, int dilationH, int dilationW,
275
+ int64_t itime, int64_t iheight, int64_t iwidth,
276
+ int64_t otime, int64_t oheight, int64_t owidth,
277
+ const char* fn_name)
278
+ {
279
+ const int64_t ndim = input.ndimension();
280
+
281
+ pool3d_shape_check(
282
+ input,
283
+ nslices,
284
+ kT, kH, kW,
285
+ dT, dH, dW,
286
+ pT, pH, pW,
287
+ dilationT, dilationH, dilationW,
288
+ itime, iheight, iwidth,
289
+ otime, oheight, owidth, fn_name);
290
+
291
+ check_dim_size(gradOutput, ndim, ndim-4, nslices);
292
+ check_dim_size(gradOutput, ndim, ndim-3, otime);
293
+ check_dim_size(gradOutput, ndim, ndim-2, oheight);
294
+ check_dim_size(gradOutput, ndim, ndim-1, owidth);
295
+
296
+ check_dim_size(indices, ndim, ndim-4, nslices);
297
+ check_dim_size(indices, ndim, ndim-3, otime);
298
+ check_dim_size(indices, ndim, ndim-2, oheight);
299
+ check_dim_size(indices, ndim, ndim-1, owidth);
300
+ }
301
+
302
+ static inline void
303
+ avg_pool3d_backward_shape_check(
304
+ const Tensor& input,
305
+ const Tensor& gradOutput,
306
+ int64_t nslices,
307
+ int kT, int kH, int kW,
308
+ int dT, int dH, int dW,
309
+ int pT, int pH, int pW,
310
+ int64_t itime, int64_t iheight, int64_t iwidth,
311
+ int64_t otime, int64_t oheight, int64_t owidth,
312
+ const char *fn_name)
313
+ {
314
+ const int64_t ndim = input.ndimension();
315
+
316
+ pool3d_shape_check(
317
+ input,
318
+ nslices,
319
+ kT, kH, kW,
320
+ dT, dH, dW,
321
+ pT, pH, pW,
322
+ 1, 1, 1,
323
+ itime, iheight, iwidth,
324
+ otime, oheight, owidth,
325
+ fn_name, true);
326
+
327
+ check_dim_size(gradOutput, ndim, ndim-4, nslices);
328
+ check_dim_size(gradOutput, ndim, ndim-3, otime);
329
+ check_dim_size(gradOutput, ndim, ndim-2, oheight);
330
+ check_dim_size(gradOutput, ndim, ndim-1, owidth);
331
+ }
332
+
333
+ } // namespace
334
+
335
+ } // at::native
336
+ } // at
wemm/lib/python3.10/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
+ typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
27
+ static 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
+ typename std::enable_if<std::is_integral<T>::value && !std::is_signed<T>::value, T>::type* = nullptr>
41
+ static inline HOST_DEVICE T powi(T a, T b) {
42
+ return powi_impl(a, b);
43
+ }
44
+
45
+ template <class T,
46
+ typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, T>::type* = nullptr>
47
+ static 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
wemm/lib/python3.10/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 { namespace 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
wemm/lib/python3.10/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 { namespace 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
+ }}
wemm/lib/python3.10/site-packages/torch/include/ATen/native/ReduceOpsUtils.h ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { namespace 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
+ static 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 c10::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 c10::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
+ static 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
+ static inline Tensor integer_upcast(const Tensor& self, c10::optional<ScalarType> dtype) {
106
+ ScalarType scalarType = self.scalar_type();
107
+ ScalarType upcast_scalarType = dtype.value_or(at::isIntegralType(scalarType, /*includeBool=*/true) ? ScalarType::Long : scalarType);
108
+ return self.toType(upcast_scalarType);
109
+ }
110
+
111
+ using DimMask = TensorIterator::DimMask;
112
+
113
+ static DimVector make_dim_vector(OptionalIntArrayRef opt_dims, int64_t ndim) {
114
+ if (opt_dims.has_value()) {
115
+ return DimVector(opt_dims.value());
116
+ } else {
117
+ std::vector<int64_t> all_dims(ndim);
118
+ std::iota(all_dims.begin(), all_dims.end(), 0);
119
+ return DimVector(all_dims);
120
+ }
121
+ }
122
+
123
+ static DimMask make_dim_mask(OptionalIntArrayRef opt_dims, int64_t ndim) {
124
+ DimMask mask;
125
+ if (opt_dims.has_value()) {
126
+ auto dims = opt_dims.value();
127
+ if (dims.empty()) {
128
+ mask = DimMask().flip();
129
+ } else {
130
+ mask = at::dim_list_to_bitset(dims, ndim);
131
+ }
132
+ } else {
133
+ mask = DimMask().flip();
134
+ }
135
+ return mask;
136
+ }
137
+
138
+ inline DimVector shape_from_dim_mask(const Tensor& self, DimMask mask, bool keepdim) {
139
+ auto shape = DimVector(self.sizes());
140
+ for (int dim = shape.size() - 1; dim >= 0; dim--) {
141
+ if (mask[dim]) {
142
+ if (keepdim) {
143
+ shape[dim] = 1;
144
+ } else {
145
+ shape.erase(shape.begin() + dim);
146
+ }
147
+ }
148
+ }
149
+ return shape;
150
+ }
151
+
152
+ static void resize_reduction_result(
153
+ Tensor& result, const Tensor& self, DimMask mask, bool keepdim,
154
+ ScalarType /*dtype*/)
155
+ {
156
+ auto shape = shape_from_dim_mask(self, mask, keepdim);
157
+ 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.");
158
+ at::native::resize_output(result, shape);
159
+ }
160
+
161
+ inline Tensor create_reduction_result(
162
+ const Tensor& self, at::OptionalIntArrayRef dim, bool keepdim, ScalarType dtype
163
+ ) {
164
+ DimMask mask = make_dim_mask(dim, self.dim());
165
+ auto shape = shape_from_dim_mask(self, mask, keepdim);
166
+ return at::empty(shape, self.options().dtype(dtype));
167
+ }
168
+
169
+ static Tensor review_reduce_result(const Tensor& result, int ndim, DimMask mask, bool keepdim) {
170
+ if (keepdim) {
171
+ return result;
172
+ }
173
+ auto shape = DimVector(result.sizes());
174
+ auto stride = DimVector(result.strides());
175
+ for (const auto dim : c10::irange(ndim)) {
176
+ if (mask[dim]) {
177
+ shape.insert(shape.begin() + dim, 1);
178
+ stride.insert(stride.begin() + dim, 0);
179
+ }
180
+ }
181
+ return result.as_strided(shape, stride);
182
+ }
183
+
184
+ static TensorIterator make_reduction(
185
+ const char* name, Tensor& result, const Tensor& self,
186
+ at::OptionalIntArrayRef dim_opt,
187
+ bool keepdim, ScalarType in_dtype, ScalarType out_dtype) {
188
+ // check that result type and dtype match if provided
189
+ TORCH_CHECK(
190
+ !result.defined() || result.scalar_type() == out_dtype,
191
+ name, ": provided dtype must match dtype of result. Got ",
192
+ toString(result.scalar_type()),
193
+ " and ",
194
+ toString(out_dtype),
195
+ ".");
196
+ // dim={} performs an all-reduce, same as dim=None
197
+ IntArrayRef dim = dim_opt.value_or(IntArrayRef{});
198
+ int64_t ndim = self.dim();
199
+ auto mask = make_dim_mask(dim, ndim);
200
+ resize_reduction_result(result, self, mask, keepdim, out_dtype);
201
+ auto viewed_result = review_reduce_result(result, ndim, mask, keepdim);
202
+ namedinference::propagate_names_for_reduction(result, self, dim, keepdim);
203
+ if (self.scalar_type() == in_dtype) {
204
+ return TensorIterator::reduce_op(viewed_result, self);
205
+ }
206
+ return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
207
+ }
208
+
209
+ static C10_UNUSED TensorIterator make_reduction(
210
+ const char* name, Tensor& result, const Tensor& self,
211
+ at::OptionalIntArrayRef dim, bool keepdim, ScalarType out_dtype) {
212
+ // special case for type promotion in mixed precision, improves computational
213
+ // efficiency.
214
+ // not generalize this to common mismatched input/output types to avoid cross
215
+ // product of templated kernel launches.
216
+ const bool gpu_lowp_to_f32 = (
217
+ self.is_cuda() && (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) && out_dtype == kFloat);
218
+ auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type()
219
+ : self.is_complex() ? c10::toComplexType(out_dtype)
220
+ : out_dtype;
221
+ return make_reduction(name, result, self, dim, keepdim, in_dtype, out_dtype);
222
+ }
223
+
224
+ static TensorIterator make_reduction(
225
+ const char* name, Tensor& result1, Tensor& result2, const Tensor& self,
226
+ at::OptionalIntArrayRef dim_opt, bool keepdim, ScalarType dtype1,
227
+ ScalarType dtype2) {
228
+ // check that result type and dtype match if provided
229
+ TORCH_CHECK(
230
+ (!result1.defined() || result1.scalar_type() == dtype1) && (!result2.defined() || result2.scalar_type() == dtype2),
231
+ name, ": provided dtype must match dtype of result. Got ",
232
+ toString(result1.scalar_type()), toString(result2.scalar_type()),
233
+ " and ",
234
+ toString(dtype1), toString(dtype2),
235
+ ".");
236
+
237
+ // dim={} performs an all-reduce, same as dim=None
238
+ auto dim = dim_opt.value_or(IntArrayRef{});
239
+ int64_t ndim = self.dim();
240
+ DimMask mask = make_dim_mask(dim, ndim);
241
+ resize_reduction_result(result1, self, mask, keepdim, dtype1);
242
+ auto viewed_result1 = review_reduce_result(result1, ndim, mask, keepdim);
243
+
244
+ resize_reduction_result(result2, self, mask, keepdim, dtype2);
245
+ auto viewed_result2 = review_reduce_result(result2, ndim, mask, keepdim);
246
+
247
+ namedinference::propagate_names_for_reduction(result1, self, dim, keepdim);
248
+ namedinference::propagate_names_for_reduction(result2, self, dim, keepdim);
249
+
250
+ // special case for type promotion in mixed precision, improves computational
251
+ // efficiency.
252
+ // We don't generalize this to common mismatched input/output types to avoid cross
253
+ // product of templated kernel launches.
254
+ if (self.scalar_type() == dtype1 ||
255
+ (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
256
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
257
+ }
258
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
259
+ }
260
+
261
+ static C10_UNUSED TensorIterator make_reduction(
262
+ const char* name, Tensor& result1, Tensor& result2, const Tensor& self,
263
+ at::OptionalIntArrayRef dim, bool keepdim, ScalarType dtype) {
264
+ return make_reduction(name, result1, result2, self, dim, keepdim, dtype, dtype);
265
+ }
266
+
267
+ static void zero_numel_check_dims(const Tensor& self, const int64_t dim, const char *fn_name) {
268
+ if (self.ndimension() == 0) {
269
+ TORCH_CHECK_INDEX(dim == 0 || dim == -1, fn_name,
270
+ ": Expected reduction dim -1 or 0 for scalar but got ", dim);
271
+ }
272
+ else {
273
+ TORCH_CHECK_INDEX(self.size(dim) != 0, fn_name,
274
+ ": Expected reduction dim ", dim, " to have non-zero size.");
275
+ }
276
+ }
277
+
278
+ static void zero_numel_check_dims(const Tensor& self, const IntArrayRef dim, const char *fn_name) {
279
+ TORCH_CHECK(
280
+ !dim.empty(),
281
+ fn_name, ": Expected reduction dim to be specified for input.numel() == 0. ",
282
+ "Specify the reduction dim with the 'dim' argument.");
283
+ for (const int64_t d : dim) {
284
+ zero_numel_check_dims(self, d, fn_name);
285
+ }
286
+ }
287
+
288
+ static std::vector<int64_t> get_zero_numel_tensor_size(
289
+ const Tensor& self,
290
+ const int64_t dim,
291
+ const bool keepdim,
292
+ const char* fn_name) {
293
+ TORCH_INTERNAL_ASSERT(self.numel() == 0, fn_name, ": Expected self.numel() == 0.");
294
+ zero_numel_check_dims(self, dim, fn_name);
295
+ std::vector<int64_t> sizes;
296
+ if (keepdim) {
297
+ sizes = self.sizes().vec();
298
+ sizes[dim] = 1;
299
+ }
300
+ else {
301
+ for (const auto d : c10::irange(self.dim())) {
302
+ if (d != dim) {
303
+ sizes.push_back(self.sizes()[d]);
304
+ }
305
+ }
306
+ }
307
+ return sizes;
308
+ }
309
+
310
+ // Resize the result tensor and indices when result.numel() == 0 depending on values of
311
+ // dim and keepdim for returning tensors containing reduction results.
312
+ // This function should be called when you are reducing a zero-numel tensor and want to
313
+ // resize the output and return it. This function exists for resizing zero-numel
314
+ // tensors when the size of the reduction dimension is non-zero.
315
+ static C10_UNUSED void zero_numel_tensor_resize(Tensor& result, Tensor& result_indices,
316
+ const Tensor& self, const int64_t dim,
317
+ const bool keepdim, const char *fn_name) {
318
+ auto sizes = get_zero_numel_tensor_size(self, dim, keepdim, fn_name);
319
+ at::native::resize_output(result, sizes);
320
+ at::native::resize_output(result_indices, sizes);
321
+ }
322
+
323
+ inline ScalarType get_dtype_from_self(
324
+ const Tensor& self,
325
+ const c10::optional<ScalarType>& dtype,
326
+ bool promote_integers) {
327
+ if (dtype.has_value()) {
328
+ return dtype.value();
329
+ }
330
+ ScalarType src_type = self.scalar_type();
331
+ if (promote_integers && at::isIntegralType(src_type, /*includeBool=*/true)) {
332
+ return kLong;
333
+ }
334
+ return src_type;
335
+ }
336
+
337
+ inline ScalarType get_dtype_from_result(Tensor& result, c10::optional<ScalarType> dtype) {
338
+ 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.");
339
+ if (dtype.has_value()) {
340
+ return dtype.value();
341
+ } else {
342
+ return result.scalar_type();
343
+ }
344
+ }
345
+
346
+
347
+ } // native
348
+
349
+ namespace meta {
350
+
351
+ static C10_UNUSED DimVector get_reduction_shape(
352
+ const Tensor& self,
353
+ IntArrayRef dims,
354
+ bool keepdim) {
355
+ auto mask = native::make_dim_mask(dims, self.dim());
356
+ return native::shape_from_dim_mask(self, mask, keepdim);
357
+ }
358
+
359
+ static void resize_reduction(
360
+ impl::MetaBase& meta,
361
+ const Tensor& self,
362
+ OptionalIntArrayRef opt_dims,
363
+ bool keepdim,
364
+ ScalarType out_dtype) {
365
+ DimVector dims_ = at::native::make_dim_vector(opt_dims, self.dim());
366
+ maybe_wrap_dims(dims_, self.dim());
367
+ auto shape = get_reduction_shape(self, dims_, keepdim);
368
+ meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
369
+ namedinference::propagate_names_for_reduction(
370
+ meta.maybe_get_output(), self, dims_, keepdim);
371
+ }
372
+
373
+ static void resize_reduction_with_indices(
374
+ impl::MetaBase& meta,
375
+ const Tensor& self,
376
+ IntArrayRef dims,
377
+ bool keepdim,
378
+ ScalarType out_dtype) {
379
+ DimVector dims_(dims);
380
+ maybe_wrap_dims(dims_, self.dim());
381
+ auto shape = get_reduction_shape(self, dims_, keepdim);
382
+ meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
383
+ meta.set_output_raw_strided(1, shape, {}, self.options().dtype(kLong));
384
+ namedinference::propagate_names_for_reduction(
385
+ meta.maybe_get_output(0), self, dims_, keepdim);
386
+ namedinference::propagate_names_for_reduction(
387
+ meta.maybe_get_output(1), self, dims_, keepdim);
388
+ }
389
+
390
+ static TensorIterator make_reduction(
391
+ const Tensor& self,
392
+ const Tensor& result,
393
+ OptionalIntArrayRef opt_dims,
394
+ bool keepdim,
395
+ ScalarType in_dtype) {
396
+ int64_t ndim = self.dim();
397
+ auto mask = at::native::make_dim_mask(opt_dims, ndim);
398
+ auto viewed_result =
399
+ at::native::review_reduce_result(result, ndim, mask, keepdim);
400
+ if (self.scalar_type() == in_dtype) {
401
+ return TensorIterator::reduce_op(viewed_result, self);
402
+ }
403
+ return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
404
+ }
405
+
406
+ static TensorIterator make_reduction(
407
+ const Tensor& self,
408
+ const Tensor& result1,
409
+ const Tensor& result2,
410
+ IntArrayRef dims,
411
+ bool keepdim,
412
+ ScalarType dtype1,
413
+ ScalarType /*dtype2*/) {
414
+ int64_t ndim = self.dim();
415
+ auto mask = at::native::make_dim_mask(dims, ndim);
416
+ auto viewed_result1 = at::native::review_reduce_result(result1, ndim, mask, keepdim);
417
+ auto viewed_result2 = at::native::review_reduce_result(result2, ndim, mask, keepdim);
418
+ // special case for type promotion in mixed precision, improves computational efficiency.
419
+ // We don't generalize this to common mismatched input/output types to avoid cross product
420
+ // of templated kernel launches.
421
+ if (self.scalar_type() == dtype1 ||
422
+ (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
423
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
424
+ }
425
+ return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
426
+ }
427
+
428
+ static C10_UNUSED TensorIterator make_reduction_from_out_ty(
429
+ const Tensor& self,
430
+ const Tensor& result,
431
+ OptionalIntArrayRef opt_dims,
432
+ bool keepdim,
433
+ ScalarType out_dtype) {
434
+ // special case for type promotion in mixed precision, improves computational
435
+ // efficiency.
436
+ // not generalize this to common mismatched input/output types to avoid cross
437
+ // product of templated kernel launches.
438
+ const bool gpu_lowp_to_f32 =
439
+ (self.is_cuda() &&
440
+ (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) &&
441
+ out_dtype == kFloat);
442
+ auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type() : out_dtype;
443
+ return make_reduction(self, result, opt_dims, keepdim, in_dtype);
444
+ }
445
+
446
+ } // namespace meta
447
+ } // namespace at