jasonfan commited on
Commit
d9d56a0
·
verified ·
1 Parent(s): 7b498b6

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. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h +102 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/packed_params.h +78 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h +95 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/batch_norm.h +43 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/AtomicAddFloat.h +42 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/CatKernel.h +17 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ChannelShuffleKernel.h +19 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/CopyKernel.h +19 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/DepthwiseConvKernel.h +26 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/DistributionTemplates.h +430 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Elu.h +79 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Gelu.h +88 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/GridSamplerKernel.h +39 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/IndexKernelUtils.h +90 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Intrinsics.h +38 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/IsContiguous.h +69 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/LogAddExp.h +66 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/LogSoftmaxKernelImpl.h +342 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Loops.h +400 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/MaxUnpoolKernel.h +19 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/PixelShuffleKernel.h +19 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Reduce.h +315 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ReduceUtils.h +242 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h +32 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SampledAddmmKernel.h +17 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SerialStackImpl.h +151 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SoftmaxKernel.h +33 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SpmmReduceKernel.h +27 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/StackKernel.h +17 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/UpSampleKernelAVXAntialias.h +1381 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/WeightNormKernel.h +25 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/avx_mathfun.h +527 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/int_mm_kernel.h +43 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/mixed_data_type.h +46 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/moments_utils.h +216 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/utils.h +225 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/zmath.h +255 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Activation.h +25 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/BinaryInternal.h +49 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CUDAJitLoops.cuh +332 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CUDALoops.cuh +1136 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CompositeRandomAccessor.h +41 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Copy.h +16 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CuFFTPlanCache.h +499 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CuFFTUtils.h +80 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/DeviceSqrt.cuh +30 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/DistributionTemplates.h +702 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Distributions.h +30 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/EmbeddingBackwardKernel.cuh +26 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/ForeachFunctors.cuh +743 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/core/QScheme.h>
6
+
7
+ #ifdef USE_FBGEMM
8
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi")
9
+ #include <fbgemm/Fbgemm.h>
10
+ #include <fbgemm/FbgemmSparse.h>
11
+ #include <ATen/native/ao_sparse/quantized/cpu/packed_params.h>
12
+ C10_DIAGNOSTIC_POP()
13
+
14
+
15
+ namespace ao::sparse {
16
+
17
+ struct TORCH_API PackedLinearWeight
18
+ : public LinearPackedParamsBase {
19
+ PackedLinearWeight(std::unique_ptr<fbgemm::BCSRMatrix<int8_t>> w,
20
+ std::optional<at::Tensor> bias,
21
+ std::vector<int32_t> col_offsets,
22
+ std::vector<float> w_scale,
23
+ std::vector<int32_t> w_zp,
24
+ c10::QScheme q_scheme,
25
+ const int64_t out_features_block_size /* block sparsity size across output_features */,
26
+ const int64_t in_features_block_size /* block sparsity size across input_features */)
27
+ : LinearPackedParamsBase(
28
+ out_features_block_size,
29
+ in_features_block_size),
30
+ w(std::move(w)),
31
+ bias_(std::move(bias)),
32
+ col_offsets(std::move(col_offsets)),
33
+ w_scale(std::move(w_scale)),
34
+ w_zp(std::move(w_zp)),
35
+ q_scheme(q_scheme) {}
36
+ std::unique_ptr<fbgemm::BCSRMatrix<int8_t>> w;
37
+ std::optional<at::Tensor> bias_;
38
+ std::vector<int32_t> col_offsets;
39
+ std::vector<float> w_scale;
40
+ std::vector<int32_t> w_zp;
41
+ c10::QScheme q_scheme;
42
+
43
+ at::Tensor apply(
44
+ const at::Tensor& input,
45
+ double output_scale,
46
+ int64_t output_zero_point) override;
47
+ at::Tensor apply_relu(
48
+ const at::Tensor& input,
49
+ double output_scale,
50
+ int64_t output_zero_point) override;
51
+
52
+ at::Tensor apply_dynamic(const at::Tensor& input) override {
53
+ TORCH_INTERNAL_ASSERT(
54
+ false,
55
+ "Sparse quantized dynamic linear with fused relu is not yet "
56
+ "supported on qnnpack backend.");
57
+ return at::Tensor();
58
+ }
59
+ at::Tensor apply_dynamic_relu(const at::Tensor& input) override {
60
+ TORCH_INTERNAL_ASSERT(
61
+ false,
62
+ "Sparse quantized dynamic linear with fused relu is not yet "
63
+ "supported on qnnpack backend.");
64
+ return at::Tensor();
65
+ }
66
+
67
+ LinearPackedSerializationType unpack() override;
68
+
69
+ BCSRSerializationType serialize() override;
70
+
71
+ static c10::intrusive_ptr<LinearPackedParamsBase> deserialize(
72
+ const BCSRSerializationType& serialized);
73
+
74
+ std::optional<at::Tensor> bias() override {
75
+ return bias_;
76
+ }
77
+
78
+ static c10::intrusive_ptr<LinearPackedParamsBase> prepack(
79
+ const at::Tensor& weight,
80
+ const std::optional<at::Tensor>& bias,
81
+ const int64_t out_features_block_size,
82
+ const int64_t in_features_block_size);
83
+
84
+ private:
85
+ template <bool ReluFused>
86
+ at::Tensor apply_impl(
87
+ const at::Tensor& input,
88
+ double output_scale,
89
+ int64_t output_zero_point);
90
+ };
91
+
92
+ } // namespace ao::sparse
93
+
94
+ #endif // USE_FBGEMM
95
+
96
+ namespace ao::sparse {
97
+ int register_linear_params();
98
+ } // namespace ao::sparse
99
+
100
+ #else
101
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
102
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/packed_params.h ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstdint>
5
+
6
+ #include <ATen/core/ivalue.h>
7
+ #include <c10/util/Exception.h>
8
+
9
+ namespace ao::sparse {
10
+
11
+ // <Weight, bias, out_features_block_size, in_features_block_size>
12
+ using LinearPackedSerializationType =
13
+ std::tuple<at::Tensor, std::optional<at::Tensor>, std::vector<int64_t>>;
14
+
15
+ #define SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION 2
16
+
17
+ using BCSRSerializationType =
18
+ std::tuple<
19
+ int64_t, // Serialization Version
20
+ std::optional<at::Tensor>, // Bias
21
+ int64_t, // Out Features (Row) Block Size
22
+ int64_t, // In Features (Column) Block Size
23
+ at::Tensor, // Weight Scales (single element vector if per-tensor) (float)
24
+ at::Tensor, // Wrapper for Weight Zero Points (single element vector if per-tensor) (int8_t)
25
+ bool, // Quantization Scheme (true: per tensor, false: per channel)
26
+ at::Tensor, // Wrapper for Row Block Indices (int8_t, int16_t, or int32_t)
27
+ at::Tensor, // Wrapper for Column Block Indices (int8_t, int16_t, or int32_t)
28
+ at::Tensor, // Wrapper for Non-Zero Weight Values, each +128 (uint8_t)
29
+ int64_t, // Number of Output Channels
30
+ int64_t // Number of Input Channels
31
+ >;
32
+
33
+ using BCSR =
34
+ std::tuple<
35
+ std::vector<int8_t>, // Non-Zero Weight Values
36
+ std::vector<int32_t>, // Compressed Row Block Indices
37
+ std::vector<int32_t> // Column Block Indices
38
+ >;
39
+
40
+ struct LinearPackedParamsBase : public torch::jit::CustomClassHolder {
41
+ public:
42
+ LinearPackedParamsBase(
43
+ const int64_t out_features_block_size,
44
+ const int64_t in_features_block_size)
45
+ : out_features_block_size_(out_features_block_size),
46
+ in_features_block_size_(in_features_block_size) {}
47
+
48
+ virtual at::Tensor apply(
49
+ const at::Tensor& input,
50
+ double output_scale,
51
+ int64_t output_zero_point) = 0;
52
+ virtual at::Tensor apply_relu(
53
+ const at::Tensor& input,
54
+ double output_scale,
55
+ int64_t output_zero_point) = 0;
56
+
57
+ virtual at::Tensor apply_dynamic(const at::Tensor& input) = 0;
58
+ virtual at::Tensor apply_dynamic_relu(const at::Tensor& input) = 0;
59
+
60
+ virtual LinearPackedSerializationType unpack() = 0;
61
+
62
+ virtual BCSRSerializationType serialize() = 0;
63
+
64
+ virtual std::optional<at::Tensor> bias() = 0;
65
+
66
+ virtual void set_bias(const std::optional<at::Tensor>& bias) {
67
+ TORCH_CHECK(false, "set_bias is not implemented for this packed parameter type");
68
+ }
69
+
70
+ protected:
71
+ const int64_t out_features_block_size_, in_features_block_size_;
72
+ };
73
+
74
+ } // namespace ao::sparse
75
+
76
+ #else
77
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
78
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/core/QScheme.h>
6
+
7
+ #ifdef USE_PYTORCH_QNNPACK
8
+ // TODO: Refacto QnnpackUtils.h so as to separate code
9
+ // needed for quantized op from the generic qnnpack specific
10
+ // quantization utilities.
11
+ #include <ATen/native/ao_sparse/quantized/cpu/packed_params.h>
12
+ #include <ATen/native/quantized/cpu/QnnpackUtils.h>
13
+ #include <pack_block_sparse.h>
14
+
15
+ namespace ao::sparse {
16
+
17
+ struct TORCH_API PackedLinearWeightQnnp : public LinearPackedParamsBase {
18
+ PackedLinearWeightQnnp(const at::Tensor& weight, const std::optional<at::Tensor>& bias, const int64_t out_features_block_size /* block sparsity size across output_features */, const int64_t in_features_block_size /* block sparsity size across input_features */);
19
+ explicit PackedLinearWeightQnnp(const BCSRSerializationType& serialized);
20
+ std::optional<at::Tensor> orig_bias_;
21
+ // Separate copy of bias exist so that we can fill in zeros when
22
+ // optional bias does not exist. This is to compy with qnnpack operator that
23
+ // expects bias to be present.
24
+ // In case bias is present bias_ is just a reference to orig_bias_
25
+ at::Tensor bias_;
26
+ c10::QScheme q_scheme_;
27
+ double input_scale_{};
28
+ std::unique_ptr<qnnpack::BCSRMatrix> bcsr_matrix_;
29
+ at::Tensor w_scales_;
30
+ std::vector<uint8_t> w_zero_points_;
31
+ std::vector<float> requantization_scales_;
32
+ std::unique_ptr<pytorch_qnnp_operator, QnnpackOperatorDeleter>
33
+ sparse_linear_op_{nullptr};
34
+ int64_t output_channels_;
35
+ int64_t input_channels_;
36
+ // Deserialized Tensors are stored to maintain the lifetime of underlying
37
+ // BCSR data.
38
+ // These are left empty if PackedLinearWeightQnnp is created via prepacking
39
+ // rather than deserializing.
40
+ at::Tensor deserialized_bcsr_row_block_indices_;
41
+ at::Tensor deserialized_bcsr_col_block_indices_;
42
+ at::Tensor deserialized_bcsr_weight_values_;
43
+
44
+ at::Tensor apply(
45
+ const at::Tensor& input,
46
+ double output_scale,
47
+ int64_t output_zero_point) override {
48
+ TORCH_CHECK(
49
+ false, "Static quantized sparse linear unimplemented on QNNPACK");
50
+ }
51
+ at::Tensor apply_relu(
52
+ const at::Tensor& input,
53
+ double output_scale,
54
+ int64_t output_zero_point) override {
55
+ TORCH_CHECK(
56
+ false, "Static quantized sparse linear unimplemented on QNNPACK");
57
+ }
58
+
59
+ at::Tensor apply_dynamic(const at::Tensor& input) override;
60
+ at::Tensor apply_dynamic_relu(const at::Tensor& input) override;
61
+
62
+ LinearPackedSerializationType unpack() override;
63
+
64
+ BCSRSerializationType serialize() override;
65
+
66
+ static c10::intrusive_ptr<LinearPackedParamsBase> deserialize(
67
+ const BCSRSerializationType& serialized);
68
+
69
+ std::optional<at::Tensor> bias() override {
70
+ return orig_bias_;
71
+ }
72
+
73
+ static c10::intrusive_ptr<LinearPackedParamsBase> prepack(
74
+ const at::Tensor& weight,
75
+ const std::optional<at::Tensor>& bias,
76
+ const int64_t out_features_block_size,
77
+ const int64_t in_features_block_size);
78
+
79
+ private:
80
+ template <bool ReluFused>
81
+ at::Tensor apply_impl(
82
+ const at::Tensor& input,
83
+ double output_scale,
84
+ int64_t output_zero_point);
85
+ template <bool ReluFused>
86
+ at::Tensor apply_dynamic_impl(const at::Tensor& input);
87
+ };
88
+
89
+ } // namespace ao::sparse
90
+
91
+ #endif // USE_PYTORCH_QNNPACK
92
+
93
+ #else
94
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
95
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/batch_norm.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ using batch_norm_fn = void (*)(Tensor&, const Tensor&, const Tensor&,
10
+ const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double);
11
+ using batch_norm_collect_stats_fn = void (*)(Tensor&, Tensor&, const Tensor&);
12
+ using batch_norm_backward_fn = void(*)(Tensor&, Tensor&, Tensor&, const Tensor&,
13
+ const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double);
14
+
15
+ DECLARE_DISPATCH(batch_norm_fn, batch_norm_cpu_stub)
16
+ DECLARE_DISPATCH(batch_norm_collect_stats_fn, batch_norm_cpu_collect_stats_stub)
17
+ DECLARE_DISPATCH(batch_norm_backward_fn, batch_norm_cpu_backward_stub)
18
+
19
+ // TensorAccessor when it is defined to work around undefined...
20
+ template <typename scalar_t>
21
+ static TensorAccessor<scalar_t, 1> conditional_accessor_1d(const Tensor& t) {
22
+ if (! t.defined()) {
23
+ return TensorAccessor<scalar_t, 1>(nullptr, nullptr, nullptr);
24
+ }
25
+ return t.accessor<scalar_t, 1>();
26
+ }
27
+
28
+ template <typename scalar_t>
29
+ static scalar_t* conditional_data_ptr(const Tensor& t) {
30
+ if constexpr (std::is_const_v<scalar_t>) {
31
+ return t.defined() ? t.contiguous().const_data_ptr<scalar_t>()
32
+ : nullptr;
33
+ } else {
34
+ return t.defined() ? t.contiguous().data_ptr<scalar_t>()
35
+ : nullptr;
36
+ }
37
+ }
38
+
39
+ } // namespace at::native
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/AtomicAddFloat.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #ifndef ATOMIC_ADD_FLOAT
3
+ #define ATOMIC_ADD_FLOAT
4
+
5
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__aarch64__))
6
+ #include <ATen/native/cpu/Intrinsics.h>
7
+ #else
8
+ #define _mm_pause()
9
+ #endif
10
+
11
+ #include <atomic>
12
+
13
+ static inline void cpu_atomic_add_float(float* dst, float fvalue)
14
+ {
15
+ typedef union {
16
+ unsigned intV;
17
+ float floatV;
18
+ } uf32_t;
19
+
20
+ uf32_t new_value, old_value;
21
+ std::atomic<unsigned>* dst_intV = (std::atomic<unsigned>*)dst;
22
+
23
+ old_value.floatV = *dst;
24
+ new_value.floatV = old_value.floatV + fvalue;
25
+
26
+ unsigned* old_intV = &old_value.intV;
27
+ while (!std::atomic_compare_exchange_strong(dst_intV, old_intV, new_value.intV)) {
28
+ #ifdef __aarch64__
29
+ __asm__ __volatile__("yield;" : : : "memory");
30
+ #else
31
+ _mm_pause();
32
+ #endif
33
+ old_value.floatV = *dst;
34
+ new_value.floatV = old_value.floatV + fvalue;
35
+ }
36
+ }
37
+
38
+ #endif
39
+
40
+ #else
41
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
42
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/CatKernel.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <ATen/core/IListRef.h>
7
+
8
+ namespace at::native {
9
+
10
+ using cat_serial_fn = void(*)(const Tensor &, const MaterializedITensorListRef&, int64_t);
11
+ DECLARE_DISPATCH(cat_serial_fn, cat_serial_stub)
12
+
13
+ } // namespace at::native
14
+
15
+ #else
16
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
17
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ChannelShuffleKernel.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ class TensorBase;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ using channel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t);
13
+ DECLARE_DISPATCH(channel_shuffle_fn, channel_shuffle_kernel)
14
+
15
+ } // at::native
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/CopyKernel.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/TensorIterator.h>
5
+
6
+ namespace at {
7
+ struct TensorIteratorBase;
8
+
9
+ namespace native {
10
+ inline namespace CPU_CAPABILITY {
11
+
12
+ void direct_copy_kernel(TensorIteratorBase &iter);
13
+ void copy_kernel(TensorIterator& iter, bool /*non_blocking*/);
14
+
15
+ }}} // namespace at::native::CPU_CAPABILITY
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/DepthwiseConvKernel.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/ArrayRef.h>
6
+
7
+ /*
8
+ Depthwise 3x3 Winograd convolution operator
9
+ */
10
+
11
+ namespace at {
12
+ class Tensor;
13
+
14
+ namespace native {
15
+
16
+ using convolution_depthwise3x3_winograd_fn =
17
+ Tensor (*)(const Tensor &, const Tensor &, const Tensor &, IntArrayRef, IntArrayRef, int64_t);
18
+
19
+ DECLARE_DISPATCH(convolution_depthwise3x3_winograd_fn, convolution_depthwise3x3_winograd_stub)
20
+
21
+ } // namespace native
22
+ } // namespace at
23
+
24
+ #else
25
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
26
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/DistributionTemplates.h ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/CPUApplyUtils.h>
5
+ #include <ATen/Dispatch.h>
6
+ #include <ATen/Dispatch_v2.h>
7
+ #include <ATen/ExpandBase.h>
8
+ #include <ATen/core/DistributionsHelper.h>
9
+ #include <ATen/native/TensorIterator.h>
10
+ #include <ATen/native/cpu/Loops.h>
11
+ #include <mutex>
12
+
13
+ #ifdef CPU_CAPABILITY_AVX2
14
+ #include <ATen/native/cpu/avx_mathfun.h>
15
+ #include <c10/util/irange.h>
16
+ #endif
17
+
18
+
19
+
20
+
21
+ namespace at::native::templates::cpu {
22
+ namespace {
23
+
24
+ // ==================================================== Random ========================================================
25
+
26
+ template<typename RNG>
27
+ void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG generator) {
28
+ AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cpu", AT_WRAP([&] {
29
+ std::lock_guard<std::mutex> lock(generator->mutex_);
30
+ cpu_serial_kernel(iter, [range, base, generator]() -> scalar_t {
31
+ uniform_int_from_to_distribution<scalar_t> random(range, base);
32
+ return random(generator);
33
+ });
34
+ }), kBool, kHalf, kBFloat16, AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES));
35
+ }
36
+
37
+ // This is the special kernel to handle single specific case:
38
+ // from(inclusive) = std::numeric_limits<int64_t>::lowest()
39
+ // to(exclusive) = None (= std::numeric_limits<int64_t>::max() + 1)
40
+ template<typename RNG>
41
+ void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG generator) {
42
+ AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cpu", [&] {
43
+ if constexpr (std::is_same_v<scalar_t, int64_t> ||
44
+ std::is_same_v<scalar_t, double> ||
45
+ std::is_same_v<scalar_t, float> ||
46
+ std::is_same_v<scalar_t, at::BFloat16>) {
47
+ std::lock_guard<std::mutex> lock(generator->mutex_);
48
+ cpu_serial_kernel(iter, [generator]() -> scalar_t {
49
+ uniform_int_full_range_distribution<scalar_t> random;
50
+ return random(generator);
51
+ });
52
+ } else {
53
+ TORCH_CHECK(false, "random_full_64_bits_range_kernel_cpu handles only int64, double, float and bfloat16");
54
+ }
55
+ });
56
+ }
57
+
58
+ template<typename RNG>
59
+ struct RandomFromToKernel {
60
+ void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional<Generator> gen) {
61
+ random_from_to_kernel(iter, range, base, check_generator<RNG>(gen));
62
+ }
63
+ void operator()(TensorIteratorBase& iter, std::optional<Generator> gen) {
64
+ random_full_64_bits_range_kernel(iter, check_generator<RNG>(gen));
65
+ }
66
+ };
67
+
68
+ template<typename RNG>
69
+ void random_kernel(TensorIteratorBase& iter, RNG generator) {
70
+ std::lock_guard<std::mutex> lock(generator->mutex_);
71
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cpu", [&] {
72
+ cpu_serial_kernel(iter, [generator]() -> scalar_t {
73
+ uniform_int_distribution<scalar_t> random;
74
+ return random(generator);
75
+ });
76
+ });
77
+ }
78
+
79
+ template<typename RNG>
80
+ struct RandomKernel {
81
+ void operator()(TensorIteratorBase& iter, std::optional<Generator> gen) {
82
+ random_kernel(iter, check_generator<RNG>(gen));
83
+ }
84
+ };
85
+
86
+ // ==================================================== Normal ========================================================
87
+
88
+ #ifdef CPU_CAPABILITY_AVX2
89
+ void normal_fill_16_AVX2(float *data,
90
+ const __m256* two_pi,
91
+ const __m256* one,
92
+ const __m256* minus_two,
93
+ const __m256* mean,
94
+ const __m256* std_v) {
95
+ const __m256 u1 = _mm256_sub_ps(*one, _mm256_loadu_ps(data));
96
+ const __m256 u2 = _mm256_loadu_ps(data + 8);
97
+ // sincos256_ps and log256_ps are from avx_mathfun.h
98
+ const __m256 radius = _mm256_sqrt_ps(_mm256_mul_ps(*minus_two, log256_ps(u1)));
99
+ const __m256 theta = _mm256_mul_ps(*two_pi, u2);
100
+ __m256 sintheta, costheta;
101
+ sincos256_ps(theta, &sintheta, &costheta);
102
+ const __m256 n1 = _mm256_mul_ps(radius, costheta);
103
+ const __m256 n2 = _mm256_mul_ps(radius, sintheta);
104
+ _mm256_storeu_ps(data, _mm256_fmadd_ps(n1, *std_v, *mean));
105
+ _mm256_storeu_ps(data + 8, _mm256_fmadd_ps(n2, *std_v, *mean));
106
+ }
107
+
108
+ template<typename RNG>
109
+ void normal_fill_AVX2(const TensorBase &self, const float mean, const float std, RNG generator) {
110
+ float *data = self.data_ptr<float>();
111
+ auto size = self.numel();
112
+ std::lock_guard<std::mutex> lock(generator->mutex_);
113
+ for (const auto i : c10::irange(size)) {
114
+ at::uniform_real_distribution<float> uniform(0, 1);
115
+ data[i] = uniform(generator);
116
+ }
117
+ const __m256 two_pi = _mm256_set1_ps(2.0f * c10::pi<double>);
118
+ const __m256 one = _mm256_set1_ps(1.0f);
119
+ const __m256 minus_two = _mm256_set1_ps(-2.0f);
120
+ const __m256 mean_v = _mm256_set1_ps(mean);
121
+ const __m256 std_v = _mm256_set1_ps(std);
122
+
123
+ for (int64_t i = 0; i < size - 15; i += 16) {
124
+ normal_fill_16_AVX2(data + i, &two_pi, &one, &minus_two, &mean_v, &std_v);
125
+ }
126
+
127
+ if (size % 16 != 0) {
128
+ // Recompute the last 16 values.
129
+ data = data + size - 16;
130
+ for (const auto i : c10::irange(16)) {
131
+ at::uniform_real_distribution<float> uniform(0, 1);
132
+ data[i] = uniform(generator);
133
+ }
134
+ normal_fill_16_AVX2(data, &two_pi, &one, &minus_two, &mean_v, &std_v);
135
+ }
136
+ }
137
+ #endif
138
+
139
+ template <typename scalar_t>
140
+ void normal_fill_16(scalar_t *data, const scalar_t mean, const scalar_t std) {
141
+ for (const auto j : c10::irange(8)) {
142
+ const scalar_t u1 = 1 - data[j]; // [0, 1) -> (0, 1] for log.
143
+ const scalar_t u2 = data[j + 8];
144
+ const scalar_t radius = std::sqrt(-2 * std::log(u1));
145
+ const scalar_t theta = 2.0f * c10::pi<double> * u2;
146
+ data[j] = radius * std::cos(theta) * std + mean;
147
+ data[j + 8] = radius * std::sin(theta) * std + mean;
148
+ }
149
+ }
150
+
151
+ #if defined(__VSX__) || defined(CPU_CAPABILITY_VSX)
152
+ static void normal_fill_16_VSX(float *data,const Vectorized<float> &two_pi,const Vectorized<float> &one,const Vectorized<float> &minus_two,const Vectorized<float> &mean,const Vectorized<float> &std) {
153
+ using Vec = Vectorized<float>;
154
+ Vec u1=one-Vec::loadu(data);
155
+ Vec u2=Vec::loadu(data+8);
156
+ Vec radius=(minus_two * u1.log());
157
+ radius=radius.sqrt();
158
+ Vec theta=two_pi * u2;
159
+ Vec output_vec=radius * theta.cos() * std + mean;
160
+ Vec output_vec2=radius * theta.sin() * std + mean;
161
+ output_vec.store(data);
162
+ output_vec2.store(data+8);
163
+ }
164
+
165
+ template <typename scalar_t, typename RNG>
166
+ void normal_fill_VSX(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
167
+ float *data = self.data_ptr<float>();
168
+ auto size = self.numel();
169
+ std::lock_guard<std::mutex> lock(generator->mutex_);
170
+ for (const auto i : c10::irange(size)) {
171
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
172
+ data[i] = uniform(generator);
173
+ }
174
+
175
+ using Vec = Vectorized<float>;
176
+ const Vec two_pi = Vec(2.0f * c10::pi<double>);
177
+ const Vec one = Vec(1.0f);
178
+ const Vec minus_two = Vec(-2.0f);
179
+ const Vec var_vec = Vec(std);
180
+ const Vec mean_vec = Vec(mean);
181
+
182
+ for (int64_t i = 0; i < size - 15; i += 16) {
183
+ if(Vec::size()==8) {
184
+ normal_fill_16_VSX(data + i, two_pi, one, minus_two, mean_vec, var_vec);
185
+ }
186
+ else{
187
+ normal_fill_16<scalar_t>(data + i, mean, std);
188
+ }
189
+ }
190
+ if (size % 16 != 0) {
191
+ // Recompute the last 16 values.
192
+ data = data + size - 16;
193
+ for (const auto i : c10::irange(16)) {
194
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
195
+ data[i] = uniform(generator);
196
+ }
197
+ if(Vec::size()==8){
198
+ normal_fill_16_VSX(data, two_pi, one, minus_two, mean_vec, var_vec);
199
+ }
200
+ else{
201
+ normal_fill_16<scalar_t>(data, mean, std);
202
+ }
203
+ }
204
+ }
205
+ #endif //VSX
206
+
207
+ template <typename scalar_t, typename RNG>
208
+ void normal_fill(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
209
+ scalar_t *data = self.data_ptr<scalar_t>();
210
+ auto size = self.numel();
211
+ std::lock_guard<std::mutex> lock(generator->mutex_);
212
+ for (const auto i : c10::irange(size)) {
213
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
214
+ data[i] = uniform(generator);
215
+ }
216
+
217
+ for (int64_t i = 0; i < size - 15; i += 16) {
218
+ normal_fill_16<scalar_t>(data + i, mean, std);
219
+ }
220
+ if (size % 16 != 0) {
221
+ // Recompute the last 16 values.
222
+ data = data + size - 16;
223
+ for (const auto i : c10::irange(16)) {
224
+ at::uniform_real_distribution<scalar_t> uniform(0, 1);
225
+ data[i] = uniform(generator);
226
+ }
227
+ normal_fill_16<scalar_t>(data, mean, std);
228
+ }
229
+ }
230
+
231
+ template<typename RNG>
232
+ void normal_kernel(const TensorBase &self, double mean, double std, RNG generator) {
233
+ auto size = self.numel();
234
+ if (self.scalar_type() == ScalarType::Float && size >= 16 && self.is_contiguous()) {
235
+ #ifdef CPU_CAPABILITY_AVX2
236
+ normal_fill_AVX2(self, static_cast<float>(mean), static_cast<float>(std), generator);
237
+ #elif defined(__VSX__) || defined(CPU_CAPABILITY_VSX)
238
+ normal_fill_VSX(self, static_cast<float>(mean), static_cast<float>(std), generator);
239
+ #else
240
+ normal_fill(self, static_cast<float>(mean), static_cast<float>(std), generator);
241
+ #endif
242
+ } else {
243
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, self.scalar_type(), "normal_kernel_cpu", [&] {
244
+ if (size >= 16 && self.is_contiguous()) {
245
+ normal_fill<scalar_t>(self, static_cast<scalar_t>(mean), static_cast<scalar_t>(std), generator);
246
+ } else {
247
+ auto iter = TensorIterator::borrowing_nullary_op(self);
248
+ std::lock_guard<std::mutex> lock(generator->mutex_);
249
+ cpu_serial_kernel(iter, [mean, std, generator]() -> scalar_t {
250
+ at::normal_distribution<double> normal(mean, std);
251
+ return static_cast<scalar_t>(normal(generator));
252
+ });
253
+ }
254
+ });
255
+ }
256
+ }
257
+
258
+ template<typename RNG>
259
+ struct NormalKernel {
260
+ void operator()(Tensor& self, double mean, double std, std::optional<Generator> gen) {
261
+ normal_kernel(self, mean, std, check_generator<RNG>(gen));
262
+ }
263
+ };
264
+
265
+ // ==================================================== Uniform =======================================================
266
+
267
+ template<typename RNG>
268
+ void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG generator) {
269
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "uniform_kernel_cpu", [&]() {
270
+ std::lock_guard<std::mutex> lock(generator->mutex_);
271
+ auto from = static_cast<scalar_t>(from_);
272
+ auto to = static_cast<scalar_t>(to_);
273
+ at::uniform_real_distribution<scalar_t> uniform(from, to);
274
+ cpu_serial_kernel(iter, [&uniform, generator]() -> scalar_t {
275
+ return static_cast<scalar_t>(uniform(generator));
276
+ });
277
+ });
278
+ }
279
+
280
+ template<typename RNG>
281
+ struct UniformKernel {
282
+ void operator()(TensorIteratorBase& iter, double from, double to, std::optional<Generator> gen) {
283
+ uniform_kernel(iter, from, to, check_generator<RNG>(gen));
284
+ }
285
+ };
286
+
287
+ // ==================================================== Cauchy ========================================================
288
+
289
+ template<typename RNG>
290
+ void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, RNG generator) {
291
+ AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "cauchy_cpu", [&]() {
292
+ std::lock_guard<std::mutex> lock(generator->mutex_);
293
+ at::cauchy_distribution<double> cauchy(median, sigma);
294
+ cpu_serial_kernel(iter, [&cauchy, generator]() -> scalar_t {
295
+ return static_cast<scalar_t>(cauchy(generator));
296
+ });
297
+ });
298
+ }
299
+
300
+ template<typename RNG>
301
+ struct CauchyKernel {
302
+ void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional<Generator> gen) {
303
+ cauchy_kernel(iter, median, sigma, check_generator<RNG>(gen));
304
+ }
305
+ };
306
+
307
+ // ================================================== LogNormal =======================================================
308
+
309
+ template<typename RNG>
310
+ void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, RNG generator) {
311
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cpu", [&]() {
312
+ std::lock_guard<std::mutex> lock(generator->mutex_);
313
+ at::lognormal_distribution<double> logNormal(mean, std);
314
+ cpu_serial_kernel(iter, [&logNormal, generator]() -> scalar_t {
315
+ return static_cast<scalar_t>(logNormal(generator));
316
+ });
317
+ });
318
+ }
319
+
320
+ template<typename RNG>
321
+ struct LogNormalKernel {
322
+ void operator()(TensorIteratorBase& iter, double mean, double std, std::optional<Generator> gen) {
323
+ log_normal_kernel(iter, mean, std, check_generator<RNG>(gen));
324
+ }
325
+ };
326
+
327
+ // =================================================== Geometric ======================================================
328
+
329
+ template<typename RNG>
330
+ void geometric_kernel(TensorIteratorBase& iter, double p, RNG generator) {
331
+ AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cpu", [&]() {
332
+ std::lock_guard<std::mutex> lock(generator->mutex_);
333
+ at::geometric_distribution<double> geometric(p);
334
+ cpu_serial_kernel(iter, [&geometric, generator]() -> scalar_t {
335
+ return static_cast<scalar_t>(geometric(generator));
336
+ });
337
+ });
338
+ }
339
+
340
+ template<typename RNG>
341
+ struct GeometricKernel {
342
+ void operator()(TensorIteratorBase& iter, double p, std::optional<Generator> gen) {
343
+ geometric_kernel(iter, p, check_generator<RNG>(gen));
344
+ }
345
+ };
346
+
347
+ // ================================================== Exponential =====================================================
348
+
349
+ template<typename RNG>
350
+ void exponential_kernel(TensorIteratorBase& iter, double lambda, RNG generator) {
351
+ TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype());
352
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cpu", [&]() {
353
+ std::lock_guard<std::mutex> lock(generator->mutex_);
354
+ at::exponential_distribution<double> exponential(lambda);
355
+ cpu_serial_kernel(iter, [&exponential, generator]() -> scalar_t {
356
+ return static_cast<scalar_t>(exponential(generator));
357
+ });
358
+ });
359
+ }
360
+
361
+ template<typename RNG>
362
+ struct ExponentialKernel {
363
+ void operator()(TensorIteratorBase& iter, double lambda, std::optional<Generator> gen) {
364
+ exponential_kernel(iter, lambda, check_generator<RNG>(gen));
365
+ }
366
+ };
367
+
368
+ // ================================================== Bernoulli =======================================================
369
+
370
+ template<typename RNG>
371
+ void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG generator) {
372
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
373
+ self.scalar_type(), "bernoulli_tensor_cpu_self_", [&] {
374
+ // See Note [Acquire lock when using random generators]
375
+ std::lock_guard<std::mutex> lock(generator->mutex_);
376
+ using self_t = scalar_t;
377
+ auto p_cpu = p_.to(kCPU);
378
+ auto p = expand_inplace(self, p_cpu);
379
+ auto iter = TensorIteratorConfig()
380
+ .add_output(self)
381
+ .add_const_input(*p)
382
+ .check_all_same_dtype(false)
383
+ .build();
384
+ if (p->scalar_type() == kDouble) {
385
+ cpu_serial_kernel(iter, [&](const double p_val) -> self_t {
386
+ at::bernoulli_distribution<double> bernoulli(p_val);
387
+ return static_cast<self_t>(bernoulli(generator));
388
+ });
389
+ } else {
390
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half,
391
+ p->scalar_type(), "bernoulli_tensor_cpu_p_", [&] {
392
+ using p_t = scalar_t;
393
+ cpu_serial_kernel(iter, [&](const p_t p_val) -> self_t {
394
+ at::bernoulli_distribution<float> bernoulli(p_val);
395
+ return static_cast<self_t>(bernoulli(generator));
396
+ });
397
+ });
398
+ }
399
+ });
400
+ }
401
+
402
+ template<typename RNG>
403
+ void bernoulli_kernel(const TensorBase &self, double p, RNG generator) {
404
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
405
+ self.scalar_type(), "bernoulli_scalar_cpu_", [&] {
406
+ // See Note [Acquire lock when using random generators]
407
+ std::lock_guard<std::mutex> lock(generator->mutex_);
408
+ auto iter = TensorIterator::borrowing_nullary_op(self);
409
+ cpu_serial_kernel(iter, [p, generator]() -> scalar_t {
410
+ at::bernoulli_distribution<double> bernoulli(p);
411
+ return static_cast<scalar_t>(bernoulli(generator));
412
+ });
413
+ });
414
+ }
415
+
416
+ template<typename RNG>
417
+ struct BernoulliKernel {
418
+ void operator()(const TensorBase &self, double p, std::optional<Generator> gen) {
419
+ bernoulli_kernel(self, p, check_generator<RNG>(gen));
420
+ }
421
+ void operator()(const TensorBase &self, const TensorBase &p_, std::optional<Generator> gen) {
422
+ bernoulli_kernel(self, p_, check_generator<RNG>(gen));
423
+ }
424
+ };
425
+
426
+ }}
427
+
428
+ #else
429
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
430
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Elu.h ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // On Windows, math.h needs to be included with _USE_MATH_DEFINES defined to
5
+ // access constants such as M_SQRT2 and M_2_SQRTPI.
6
+ #ifdef _WIN32
7
+ #define _USE_MATH_DEFINES
8
+ #include <cmath>
9
+ #endif // _WIN32
10
+
11
+ #include <ATen/cpu/vec/vec.h>
12
+ #include <c10/util/BFloat16.h> // For c10::is_reduced_floating_point_v.
13
+
14
+ namespace at::native {
15
+ inline namespace CPU_CAPABILITY {
16
+ /**
17
+ * Return a function object that calculates ELU with the given
18
+ * parameters on its input element. ParamT is the type of the input
19
+ * and output to the ELU, and MathT is the type (possibly
20
+ * higher-precision, e.g. float if ParamT is reduced-precision float)
21
+ * in which to do intermediate calculations.
22
+ */
23
+ template <typename ParamT, typename MathT=ParamT>
24
+ auto get_scalar_elu_elementwise_func(MathT alpha, MathT scale, MathT input_scale) {
25
+ const auto negcoef = alpha * scale;
26
+ const auto poscoef = scale;
27
+ const auto negiptcoef = input_scale;
28
+ return [negcoef, negiptcoef, poscoef](ParamT a) -> ParamT {
29
+ return MathT(a) < MathT(0)
30
+ ? std::expm1(MathT(a) * negiptcoef) * negcoef
31
+ : MathT(a) * poscoef;
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Return a function object that calculates ELU with the given
37
+ * parameters on its input element. The function object takes and
38
+ * returns Vectorized<T>.
39
+ */
40
+ template <typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
41
+ auto get_vectorized_elu_elementwise_func(T alpha, T scale, T input_scale) {
42
+ const vec::Vectorized<T> negcoef_vec(alpha * scale);
43
+ const vec::Vectorized<T> poscoef_vec(scale);
44
+ const vec::Vectorized<T> negiptcoef_vec(input_scale);
45
+ const vec::Vectorized<T> zero_vec(static_cast<T>(0));
46
+ return [negcoef_vec, poscoef_vec, negiptcoef_vec, zero_vec](vec::Vectorized<T> a) -> vec::Vectorized<T> {
47
+ const auto cmp = a >= zero_vec;
48
+ if (!cmp.zero_mask()) {
49
+ return a * poscoef_vec;
50
+ } else {
51
+ return vec::Vectorized<T>::blendv((a * negiptcoef_vec).expm1() * negcoef_vec, a * poscoef_vec, cmp);
52
+ }
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Return a function object that calculates ELU with the given
58
+ * parameters on its input element. The function object takes and
59
+ * returns Vectorized<ParamT>, and Vectorized<MathT> is the type
60
+ * (possibly higher-precision) in which to do intermediate
61
+ * calculations.
62
+ */
63
+ template <typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
64
+ auto get_vectorized_elu_elementwise_func(float alpha, float scale, float input_scale) {
65
+ // Takes float->float.
66
+ const auto float_func = get_vectorized_elu_elementwise_func<float>(alpha, scale, input_scale);
67
+ return [float_func](vec::Vectorized<T> a) -> vec::Vectorized<T> {
68
+ auto [a0, a1] = vec::convert_to_float<T>(a);
69
+ auto res0 = float_func(a0);
70
+ auto res1 = float_func(a1);
71
+ return vec::convert_from_float<T>(res0, res1);
72
+ };
73
+ }
74
+ } // namespace CPU_CAPABILITY
75
+ } // namespace at::native
76
+
77
+ #else
78
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
79
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Gelu.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // On Windows, math.h needs to be included with _USE_MATH_DEFINES defined to
5
+ // access constants such as M_SQRT2 and M_2_SQRTPI.
6
+ #ifdef _WIN32
7
+ #define _USE_MATH_DEFINES
8
+ #include <cmath>
9
+ #include <math.h>
10
+ #endif // _WIN32
11
+
12
+ #include <ATen/cpu/vec/vec.h>
13
+ #include <c10/util/BFloat16.h> // For c10::is_reduced_floating_point_v.
14
+
15
+ namespace at::native {
16
+ inline namespace CPU_CAPABILITY {
17
+ constexpr double kGeluBeta = M_SQRT2 * M_2_SQRTPI * 0.5;
18
+ constexpr double kGeluKappa = 0.044715;
19
+
20
+ template <typename T>
21
+ using reduced_fp_to_float_t = std::conditional_t<c10::is_reduced_floating_point_v<T>, float, T>;
22
+
23
+ template <typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
24
+ float reduced_fp_to_float(T x) {
25
+ return float(x);
26
+ }
27
+
28
+ template <typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
29
+ T reduced_fp_to_float(T x) {
30
+ return x;
31
+ }
32
+
33
+ template <typename T>
34
+ T scalar_gelu_approximated_with_tanh(T x) {
35
+ using opmath_t = reduced_fp_to_float_t<T>;
36
+ auto x_float = reduced_fp_to_float(x);
37
+ auto x_cube = x_float * x_float * x_float;
38
+ auto inner = opmath_t(kGeluBeta) * (x_float + opmath_t(kGeluKappa) * x_cube);
39
+ return opmath_t(0.5) * x_float * (opmath_t(1) + std::tanh(inner));
40
+ }
41
+
42
+ template <typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
43
+ vec::Vectorized<T> vectorized_gelu_approximated_with_tanh(vec::Vectorized<T> x) {
44
+ const vec::Vectorized<T> kPointFiveVec(T(0.5));
45
+ const vec::Vectorized<T> kOneVec(T(1));
46
+ const vec::Vectorized<T> kGeluBetaVec((T(kGeluBeta)));
47
+ const vec::Vectorized<T> kGeluKappaVec((T(kGeluKappa)));
48
+ auto x_cube = x * x * x;
49
+ vec::Vectorized<T> inner_vec = kGeluBetaVec * (x + kGeluKappaVec * x_cube);
50
+ return kPointFiveVec * x * (kOneVec + inner_vec.tanh());
51
+ }
52
+
53
+ template <typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
54
+ vec::Vectorized<T> vectorized_gelu_approximated_with_tanh(vec::Vectorized<T> x) {
55
+ auto [x0, x1] = at::vec::convert_to_float<T>(x);
56
+ return at::vec::convert_from_float<T>(
57
+ vectorized_gelu_approximated_with_tanh(x0),
58
+ vectorized_gelu_approximated_with_tanh(x1));
59
+ }
60
+
61
+
62
+ template <typename T>
63
+ T scalar_gelu(T x) {
64
+ using opmath_t = reduced_fp_to_float_t<T>;
65
+ const auto kAlpha = opmath_t(M_SQRT1_2);
66
+ return reduced_fp_to_float(x) * opmath_t(0.5) * (opmath_t(1) + std::erf(reduced_fp_to_float(x) * kAlpha));
67
+ }
68
+
69
+ template<typename T, std::enable_if_t<!c10::is_reduced_floating_point_v<T>, bool> = true>
70
+ vec::Vectorized<T> vectorized_gelu(vec::Vectorized<T> x) {
71
+ const vec::Vectorized<T> kAlphaVec(T(M_SQRT1_2));
72
+ const vec::Vectorized<T> kOneVec(T(1));
73
+ const vec::Vectorized<T> kPointFiveVec(T(0.5));
74
+ return x * kPointFiveVec * (kOneVec + (x * kAlphaVec).erf());
75
+ }
76
+
77
+ template<typename T, std::enable_if_t<c10::is_reduced_floating_point_v<T>, bool> = true>
78
+ vec::Vectorized<T> vectorized_gelu(vec::Vectorized<T> x) {
79
+ auto [x0, x1] = at::vec::convert_to_float<T>(x);
80
+ return at::vec::convert_from_float<T>(vectorized_gelu(x0), vectorized_gelu(x1));
81
+ }
82
+
83
+ } // namespace CPU_CAPABILITY
84
+ } // namespace at::native
85
+
86
+ #else
87
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
88
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/GridSamplerKernel.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ #include <array>
7
+ #include <cstdint>
8
+
9
+ namespace at {
10
+ class TensorBase;
11
+ }
12
+
13
+ namespace at::native {
14
+
15
+ using forward_2d_fn = void (*) (
16
+ const TensorBase &output,
17
+ const TensorBase &input,
18
+ const TensorBase &grid,
19
+ int64_t interpolation_mode,
20
+ int64_t padding_mode,
21
+ bool align_corners);
22
+ using backward_2d_fn = void (*) (
23
+ const TensorBase &grad_input,
24
+ const TensorBase &grad_grid,
25
+ const TensorBase &grad_output,
26
+ const TensorBase &input,
27
+ const TensorBase &grid,
28
+ int64_t interpolation_mode,
29
+ int64_t padding_mode,
30
+ bool align_corners,
31
+ std::array<bool, 2> output_mask);
32
+ DECLARE_DISPATCH(forward_2d_fn, grid_sampler_2d_cpu_kernel)
33
+ DECLARE_DISPATCH(backward_2d_fn, grid_sampler_2d_backward_cpu_kernel)
34
+
35
+ } // namespace at::native
36
+
37
+ #else
38
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
39
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/IndexKernelUtils.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/TensorIterator.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ namespace at::native {
7
+
8
+ inline bool is_constant_index(int ntensor, const int64_t* strides) {
9
+ AT_ASSERT(ntensor >= 3);
10
+ for (const auto arg : c10::irange(2, ntensor)) {
11
+ if (strides[arg] != 0) {
12
+ return false;
13
+ }
14
+ }
15
+ return true;
16
+ }
17
+
18
+
19
+ struct Indexer {
20
+ Indexer(int64_t num_indexers, char** indexers, const int64_t* indexer_strides,
21
+ IntArrayRef original_sizes, IntArrayRef original_strides)
22
+ : num_indexers(num_indexers)
23
+ , indexers(indexers)
24
+ , indexer_strides(indexer_strides)
25
+ , original_strides(original_strides.data())
26
+ , original_sizes(original_sizes.data()) {
27
+ AT_ASSERT(static_cast<int64_t>(original_strides.size()) == num_indexers);
28
+ AT_ASSERT(static_cast<int64_t>(original_sizes.size()) == num_indexers);
29
+ }
30
+
31
+ int64_t num_indexers;
32
+ char** indexers;
33
+ const int64_t* indexer_strides;
34
+ const int64_t* original_strides;
35
+ const int64_t* original_sizes;
36
+
37
+ int64_t get(int64_t idx) {
38
+ int64_t offset = 0;
39
+ for (const auto j : c10::irange(num_indexers)) {
40
+ int64_t value = *(int64_t*)&indexers[j][idx * indexer_strides[j]];
41
+ int64_t size = original_sizes[j];
42
+ TORCH_CHECK_INDEX(value >= -size && value < size,
43
+ "index ", value, " is out of bounds for dimension ", j, " with size ", size);
44
+ if (value < 0) {
45
+ value += size;
46
+ }
47
+ offset += value * original_strides[j];
48
+ }
49
+ return offset;
50
+ }
51
+ };
52
+
53
+ template <typename scalar_t, typename func_t>
54
+ void cpu_index_kernel(TensorIteratorBase& iter, IntArrayRef index_size, IntArrayRef index_stride,
55
+ const func_t& f, bool serial_execution=false)
56
+ {
57
+ int ntensor = iter.ntensors();
58
+ // When launch the index parallel version, set a relative small grain size less than the INTERNAL::GRAIN_SIZE
59
+ // to make the whole available thread numbers get more balanced work load and a better cache location.
60
+ // The grain size here is chosen by the op benchmark to overcome the thread launch overhead
61
+ const int index_parallel_grain_size = 3000;
62
+ auto loop = [&](char** data, const int64_t* strides, int64_t n) {
63
+ auto indexer = Indexer(ntensor - 2, &data[2], &strides[2], index_size, index_stride);
64
+ char* dst = data[0];
65
+ char* src = data[1];
66
+ if (is_constant_index(ntensor, strides)) {
67
+ // specialization for when every element uses the same index
68
+ int64_t offset = indexer.get(0);
69
+ for (const auto i : c10::irange(n)) {
70
+ f(dst + strides[0] * i, src + strides[1] * i, offset);
71
+ }
72
+ } else {
73
+ for (const auto i : c10::irange(n)) {
74
+ int64_t offset = indexer.get(i);
75
+ f(dst + strides[0] * i, src + strides[1] * i, offset);
76
+ }
77
+ }
78
+ };
79
+ if (serial_execution) {
80
+ iter.serial_for_each(loop, {0, iter.numel()});
81
+ } else {
82
+ iter.for_each(loop, index_parallel_grain_size);
83
+ }
84
+ }
85
+ } // at
86
+ // native
87
+
88
+ #else
89
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
90
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Intrinsics.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #if defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
5
+ /* Clang-compatible compiler, targeting x86/x86-64 */
6
+ #include <x86intrin.h>
7
+ #elif defined(_MSC_VER)
8
+ /* Microsoft C/C++-compatible compiler */
9
+ #include <intrin.h>
10
+ #if _MSC_VER <= 1900
11
+ #define _mm256_extract_epi64(X, Y) (((uint64_t*)&X)[Y])
12
+ #endif
13
+ #elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
14
+ /* GCC-compatible compiler, targeting x86/x86-64 */
15
+ #include <x86intrin.h>
16
+ #elif defined(__GNUC__) && defined(__ARM_NEON__)
17
+ /* GCC-compatible compiler, targeting ARM with NEON */
18
+ #include <arm_neon.h>
19
+ #elif defined(__GNUC__) && defined(__IWMMXT__)
20
+ /* GCC-compatible compiler, targeting ARM with WMMX */
21
+ #include <mmintrin.h>
22
+ #elif (defined(__GNUC__) || defined(__xlC__)) && \
23
+ (defined(__VEC__) || defined(__ALTIVEC__))
24
+ /* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */
25
+ #include <altivec.h>
26
+ /* We need to undef those tokens defined by <altivec.h> to avoid conflicts
27
+ with the C++ types. => Can still use __bool/__vector */
28
+ #undef bool
29
+ #undef vector
30
+ #undef pixel
31
+ #elif defined(__GNUC__) && defined(__SPE__)
32
+ /* GCC-compatible compiler, targeting PowerPC with SPE */
33
+ #include <spe.h>
34
+ #endif
35
+
36
+ #else
37
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
38
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/IsContiguous.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at::native { inline namespace CPU_CAPABILITY {
5
+
6
+ // n: number of function arguments (arity)
7
+ // traits: function_traits (see FunctionTraits.h)
8
+ // s: index of scalar argument or -1
9
+ template <int n, int stride_index, typename traits, int s=-1>
10
+ struct IsContiguous {
11
+ static bool eval(const int64_t* strides) {
12
+ using type = typename traits::template arg<n - 1>::type;
13
+ return strides[stride_index] == (s == n ? 0 : sizeof(type)) &&
14
+ IsContiguous<n - 1, stride_index - 1, traits, s>::eval(strides);
15
+ }
16
+ };
17
+
18
+ // will be called when there is an output exists
19
+ template <typename traits, int s>
20
+ struct IsContiguous<0, 0, traits, s> {
21
+ static bool eval(const int64_t* strides) {
22
+ return strides[0] == sizeof(typename traits::result_type);
23
+ }
24
+ };
25
+
26
+ // will be called when there is no output
27
+ template <typename traits, int s>
28
+ struct IsContiguous<0, -1, traits, s> {
29
+ static bool eval(const int64_t* /*strides*/) {
30
+ return true;
31
+ }
32
+ };
33
+
34
+ // output and all inputs are contiguous
35
+ template <
36
+ typename traits,
37
+ std::enable_if_t<std::is_void_v<typename traits::result_type>>* =
38
+ nullptr>
39
+ static inline bool is_contiguous(const int64_t* strides) {
40
+ return IsContiguous<traits::arity, traits::arity - 1, traits>::eval(strides);
41
+ }
42
+
43
+ template <typename traits,
44
+ std::enable_if_t<!std::is_void_v<typename traits::result_type>>* = nullptr>
45
+ static inline bool is_contiguous(const int64_t* strides) {
46
+ return IsContiguous<traits::arity, traits::arity, traits>::eval(strides);
47
+ }
48
+
49
+ // input at `s` is scalar (stride 0); output and other inputs are contiguous
50
+ // NB: output is typically at strides[0] so first input corresponds to s=1
51
+ template <typename traits, int s,
52
+ std::enable_if_t<std::is_void_v<typename traits::result_type>>* = nullptr>
53
+ static inline bool is_contiguous_scalar(const int64_t* strides) {
54
+ static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
55
+ return IsContiguous<traits::arity, traits::arity - 1, traits, s>::eval(strides);
56
+ }
57
+
58
+ template <typename traits, int s,
59
+ std::enable_if_t<!std::is_void_v<typename traits::result_type>>* = nullptr>
60
+ static inline bool is_contiguous_scalar(const int64_t* strides) {
61
+ static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
62
+ return IsContiguous<traits::arity, traits::arity, traits, s>::eval(strides);
63
+ }
64
+
65
+ }}
66
+
67
+ #else
68
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
69
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/LogAddExp.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/complex.h>
5
+ #include <ATen/NumericUtils.h>
6
+
7
+ namespace at::native {
8
+ inline namespace CPU_CAPABILITY {
9
+
10
+ // custom min and max to be used in logcumsumexp for complex arguments
11
+ template <typename scalar_t>
12
+ std::pair<c10::complex<scalar_t>, c10::complex<scalar_t>> _logcumsumexp_minmax(c10::complex<scalar_t> x, c10::complex<scalar_t> y) {
13
+ if (at::_isnan(y)) { // either real is nan or imag is nan
14
+ return std::make_pair(y, y);
15
+ } else if (at::_isnan(x)) { // either real is nan or imag is nan
16
+ return std::make_pair(x, x);
17
+ } else {
18
+ return (x.real() < y.real()) ? std::make_pair(x, y) : std::make_pair(y, x);
19
+ }
20
+ }
21
+
22
+ template <typename scalar_t>
23
+ scalar_t _log_add_exp_helper(scalar_t x, scalar_t y) {
24
+ // Reference : https://www.tensorflow.org/api_docs/python/tf/math/cumulative_logsumexp
25
+ scalar_t min = at::_isnan(y) ? y : std::min(x, y); // std::min returns first arg if one of the args is nan
26
+ scalar_t max = at::_isnan(y) ? y : std::max(x, y); // std::max returns first arg if one of the args is nan
27
+ if (min != max || std::isfinite(min)) {
28
+ // nan will be propagated here
29
+ return std::log1p(std::exp(min - max)) + max;
30
+ } else {
31
+ // special case to correctly handle infinite cases
32
+ return x;
33
+ }
34
+ }
35
+
36
+ template <typename scalar_t>
37
+ c10::complex<scalar_t> _log_add_exp_helper(const c10::complex<scalar_t>& x, const c10::complex<scalar_t>& y) {
38
+ auto [min, max] = _logcumsumexp_minmax<scalar_t>(x, y);
39
+ auto min_real = std::real(min);
40
+ auto max_real = std::real(max);
41
+
42
+ if (at::_isnan(min)) { // either real is nan or imag is nan
43
+ // handling the "infectious" NaNs
44
+ return {std::numeric_limits<scalar_t>::quiet_NaN(), std::numeric_limits<scalar_t>::quiet_NaN()};
45
+ } else if (!std::isfinite(min_real) && (min_real == max_real)) {
46
+ if (min_real < 0) {
47
+ // handle the -inf case, the imaginary part here does not really matter as the exp(value)
48
+ // will be around 0.0 and the angle (i.e. the imaginary part) cannot be determined.
49
+ // It does not matter if we're taking the exp of this value
50
+ return min;
51
+ } else {
52
+ // handle the +inf case, we don't need the special precision for log1p for small values
53
+ // and to avoid producing nan in case of real(max) == real(min) == +inf
54
+ return std::log(std::exp(min) + std::exp(max));
55
+ }
56
+ } else {
57
+ return std::log1p(std::exp(min - max)) + max;
58
+ }
59
+ }
60
+
61
+ } // end namespace
62
+ } //end at::native
63
+
64
+ #else
65
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
66
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/LogSoftmaxKernelImpl.h ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/Parallel.h>
6
+ #include <ATen/cpu/vec/functional.h>
7
+ #include <ATen/cpu/vec/vec.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #include <algorithm>
11
+ #include <cmath>
12
+ #include <cstdint>
13
+ #include <limits>
14
+ #include <memory>
15
+ #include <type_traits>
16
+
17
+ namespace at::native {
18
+ inline namespace CPU_CAPABILITY {
19
+ template <typename scalar_t>
20
+ int64_t vec_log_softmax_lastdim_chunk_size(int64_t grain_size, int64_t outer_size, int64_t dim_size) {
21
+ // Coincidentally, at::internal::GRAIN_SIZE is 32768, which is equal to the
22
+ // size of L1D cache on many processors. Some processors have 48 KB L1D cache
23
+ // nowadays, so maybe in the future, we can leverage the knowledge of a
24
+ // machine's L1D cache size.
25
+ int64_t MAX_CHUNK_SIZE = std::max<int64_t>(
26
+ 1,
27
+ grain_size / (sizeof(scalar_t) * dim_size));
28
+ return std::min<int64_t>(MAX_CHUNK_SIZE, outer_size);
29
+ }
30
+
31
+ template <typename scalar_t>
32
+ void serial_vec_log_softmax_lastdim_range(
33
+ const scalar_t* input_data_base,
34
+ scalar_t* output_data_base,
35
+ int64_t dim_size,
36
+ int64_t chunk_size,
37
+ int64_t begin,
38
+ int64_t end) {
39
+ if (end <= begin) {
40
+ return;
41
+ }
42
+ using Vec = vec::Vectorized<vec::vec_scalar_t<scalar_t>>;
43
+ // MSVC requires such a declaration of dynamic arrays
44
+ // Source: https://stackoverflow.com/a/33423538
45
+ auto tmp_sum_scalar = std::make_unique<scalar_t[]>(chunk_size);
46
+ auto max_input_arr = std::make_unique<scalar_t[]>(chunk_size);
47
+ for (int64_t ii = begin; ii < end; ii += chunk_size) {
48
+ int64_t loop_end = chunk_size;
49
+ if (ii + chunk_size > end) {
50
+ loop_end = end - ii;
51
+ }
52
+ for (const auto j : c10::irange(loop_end)) {
53
+ int64_t i = ii + j;
54
+ const scalar_t* input_data = input_data_base + i * dim_size;
55
+ max_input_arr[j] = vec::reduce_all<scalar_t>(
56
+ [](Vec& x, Vec& y) { return vec::maximum(x, y); },
57
+ input_data,
58
+ dim_size);
59
+ }
60
+ for (const auto j : c10::irange(loop_end)) {
61
+ int64_t i = ii + j;
62
+ const scalar_t* input_data = input_data_base + i * dim_size;
63
+ scalar_t max_input = max_input_arr[j];
64
+ tmp_sum_scalar[j] = vec::map_reduce_all<scalar_t>(
65
+ [max_input](Vec x) { return (x - Vec(max_input)).exp(); },
66
+ [](Vec x, Vec y) { return x + y; },
67
+ input_data,
68
+ dim_size);
69
+ }
70
+ // See [Note AVX-SSE transitions] for why this should call the
71
+ // vectorized version (aside from perf improvements).
72
+ vec::map(
73
+ [](Vec x) { return x.log(); },
74
+ tmp_sum_scalar.get(),
75
+ tmp_sum_scalar.get(),
76
+ loop_end);
77
+ for (const auto j : c10::irange(loop_end)) {
78
+ int64_t i = ii + j;
79
+ const scalar_t* input_data = input_data_base + i * dim_size;
80
+ scalar_t* output_data = output_data_base + i * dim_size;
81
+ scalar_t tmp_sum = tmp_sum_scalar[j];
82
+ scalar_t max_input = max_input_arr[j];
83
+
84
+ // It's necessary to keep the order of the operations below.
85
+ // In some cases that input is large digits and the difference
86
+ // is small, if we compute `max_input` plus `tmp_sum` before,
87
+ // there would be a numerical problem. See an example in
88
+ // https://github.com/pytorch/pytorch/issues/11752#issuecomment-422883379
89
+ vec::map(
90
+ [tmp_sum, max_input](Vec x) {
91
+ return x - Vec(max_input) - Vec(tmp_sum);
92
+ },
93
+ output_data,
94
+ input_data,
95
+ dim_size);
96
+ }
97
+ }
98
+ }
99
+
100
+ // Can't include ATen/Parallel.h.
101
+ // TODO: find a way to have only one copy of divup.
102
+ inline int64_t divup(int64_t x, int64_t y) {
103
+ return (x + y - 1) / y;
104
+ }
105
+
106
+ template <typename scalar_t, int64_t BLOCK_SIZE = 128 * 1024>
107
+ std::pair<int64_t,int64_t> vec_logsoftmax_chunk_size_and_num_chunks(int64_t inner_size, int64_t dim_size) {
108
+ using Vec = vec::Vectorized<scalar_t>;
109
+ int64_t MAX_CHUNK_SIZE = std::max<int64_t>(BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size());
110
+ MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size();
111
+ int64_t CHUNK_SIZE = std::min<int64_t>(MAX_CHUNK_SIZE, inner_size);
112
+ int64_t num_chunks = divup(inner_size, CHUNK_SIZE);
113
+ return {CHUNK_SIZE, num_chunks};
114
+ }
115
+
116
+ template <typename scalar_t>
117
+ std::enable_if_t<std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
118
+ serial_vec_logsoftmax_range(
119
+ const scalar_t* input_data_base,
120
+ scalar_t* output_data_base,
121
+ int64_t inner_size,
122
+ int64_t chunk_size,
123
+ int64_t num_chunks,
124
+ int64_t dim_size,
125
+ int64_t begin,
126
+ int64_t end) {
127
+ using Vec = vec::Vectorized<scalar_t>;
128
+ // thread local temp buffer which holds vertical reduction result: max and sum.
129
+ auto buffer = std::make_unique<scalar_t []>(chunk_size * 2);
130
+ scalar_t* input_max_data = buffer.get();
131
+ scalar_t* tmp_sum_data = buffer.get() + chunk_size;
132
+
133
+ for (int64_t i = begin; i < end; i++) {
134
+ int64_t outer_idx = i / num_chunks;
135
+ int64_t k = i % num_chunks;
136
+ int64_t inner_idx_begin = k * chunk_size;
137
+ int64_t size = std::min(chunk_size, inner_size - inner_idx_begin);
138
+
139
+ // init
140
+ Vec zero_vec = Vec(scalar_t(0));
141
+ Vec min_vec = Vec(-std::numeric_limits<scalar_t>::infinity());
142
+ int64_t d0 = 0;
143
+ for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) {
144
+ min_vec.store(input_max_data + d0);
145
+ zero_vec.store(tmp_sum_data + d0);
146
+ }
147
+ for (; d0 < size; d0++) {
148
+ input_max_data[d0] = -std::numeric_limits<scalar_t>::infinity();
149
+ tmp_sum_data[d0] = scalar_t(0);
150
+ }
151
+
152
+ // compute max
153
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
154
+ const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size
155
+ + dim_idx * inner_size + inner_idx_begin;
156
+
157
+ int64_t d1 = 0;
158
+ for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) {
159
+ Vec data_vec = Vec::loadu(input_ptr + d1);
160
+ Vec max_vec = Vec::loadu(input_max_data + d1);
161
+ max_vec = Vec::blendv(max_vec, data_vec, data_vec > max_vec);
162
+ max_vec.store(input_max_data + d1);
163
+ }
164
+ for (; d1 < size; d1++) {
165
+ scalar_t data_val = input_ptr[d1];
166
+ scalar_t max_val = input_max_data[d1];
167
+ input_max_data[d1] = data_val > max_val ? data_val : max_val;
168
+ }
169
+ }
170
+
171
+ // compute sum of (x - max).exp()
172
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
173
+ const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size
174
+ + dim_idx * inner_size + inner_idx_begin;
175
+
176
+ int64_t d2 = 0;
177
+ for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) {
178
+ Vec data_vec = Vec::loadu(input_ptr + d2);
179
+ Vec sum_vec = Vec::loadu(tmp_sum_data + d2);
180
+ Vec max_vec = Vec::loadu(input_max_data + d2);
181
+ sum_vec += (data_vec - max_vec).exp();
182
+ sum_vec.store(tmp_sum_data + d2);
183
+ }
184
+ for (; d2 < size; d2++) {
185
+ scalar_t data_val = input_ptr[d2];
186
+ scalar_t max_val = input_max_data[d2];
187
+ tmp_sum_data[d2] += std::exp(data_val - max_val);
188
+ }
189
+ }
190
+
191
+ // apply log
192
+ vec::map([](Vec x) { return x.log(); }, tmp_sum_data, tmp_sum_data, size);
193
+
194
+ // compute x - max - sum
195
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
196
+ int64_t offset = outer_idx * dim_size * inner_size + dim_idx * inner_size + inner_idx_begin;
197
+ const scalar_t* input_ptr = input_data_base + offset;
198
+ scalar_t* output_ptr = output_data_base + offset;
199
+
200
+ int64_t d3 = 0;
201
+ for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) {
202
+ Vec data_vec = Vec::loadu(input_ptr + d3);
203
+ Vec max_vec = Vec::loadu(input_max_data + d3);
204
+ Vec sum_vec = Vec::loadu(tmp_sum_data + d3);
205
+ Vec out_vec = data_vec - max_vec - sum_vec;
206
+ out_vec.store(output_ptr + d3);
207
+ }
208
+ for (; d3 < size; d3++) {
209
+ output_ptr[d3] = input_ptr[d3] - input_max_data[d3] - tmp_sum_data[d3];
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ template <typename scalar_t>
216
+ std::enable_if_t<!std::is_same_v<scalar_t, at::opmath_type<scalar_t>>, void>
217
+ serial_vec_logsoftmax_range(
218
+ const scalar_t* input_data_base,
219
+ scalar_t* output_data_base,
220
+ int64_t inner_size,
221
+ int64_t chunk_size,
222
+ int64_t num_chunks,
223
+ int64_t dim_size,
224
+ int64_t begin,
225
+ int64_t end) {
226
+ using Vec = vec::Vectorized<scalar_t>;
227
+ using fVec = vec::Vectorized<float>;
228
+ auto buffer = std::make_unique<float []>(chunk_size * 2);
229
+ float* input_max_data = buffer.get();
230
+ float* tmp_sum_data = buffer.get() + chunk_size;
231
+
232
+ // thread local buffer that holds input data in float32 to save next 2 dtype conversion
233
+ auto input_buffer = std::make_unique<float []>(dim_size * chunk_size);
234
+ float* input_buffer_data = input_buffer.get();
235
+
236
+ // init
237
+ for (int64_t i = begin; i < end; i++) {
238
+ int64_t outer_idx = i / num_chunks;
239
+ int64_t k = i % num_chunks;
240
+ int64_t inner_idx_begin = k * chunk_size;
241
+ int64_t size = std::min(chunk_size, inner_size - inner_idx_begin);
242
+
243
+ fVec zero_fvec = fVec(float(0));
244
+ fVec min_fvec = fVec(-std::numeric_limits<float>::infinity());
245
+ int64_t d0 = 0;
246
+ for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) {
247
+ min_fvec.store(input_max_data + d0);
248
+ min_fvec.store(input_max_data + d0 + fVec::size());
249
+ zero_fvec.store(tmp_sum_data + d0);
250
+ zero_fvec.store(tmp_sum_data + d0 + fVec::size());
251
+ }
252
+ for (; d0 < size; d0++) {
253
+ input_max_data[d0] = -std::numeric_limits<float>::infinity();
254
+ tmp_sum_data[d0] = float(0);
255
+ }
256
+
257
+ // compute max
258
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
259
+ const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size
260
+ + dim_idx * inner_size + inner_idx_begin;
261
+ float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size;
262
+
263
+ int64_t d1 = 0;
264
+ for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) {
265
+ Vec data_vec = Vec::loadu(input_ptr + d1);
266
+ auto [data_fvec0, data_fvec1] = vec::convert_to_float<scalar_t>(data_vec);
267
+ fVec max_fvec0 = fVec::loadu(input_max_data + d1);
268
+ fVec max_fvec1 = fVec::loadu(input_max_data + d1 + fVec::size());
269
+ max_fvec0 = fVec::blendv(max_fvec0, data_fvec0, data_fvec0 > max_fvec0);
270
+ max_fvec1 = fVec::blendv(max_fvec1, data_fvec1, data_fvec1 > max_fvec1);
271
+ max_fvec0.store(input_max_data + d1);
272
+ max_fvec1.store(input_max_data + d1 + fVec::size());
273
+
274
+ // cache the 'converted' float input
275
+ data_fvec0.store(input_buffer_ptr + d1);
276
+ data_fvec1.store(input_buffer_ptr + d1 + fVec::size());
277
+ }
278
+ for (; d1 < size; d1++) {
279
+ float data_val = float(input_ptr[d1]);
280
+ float max_val = input_max_data[d1];
281
+ input_max_data[d1] = data_val > max_val ? data_val : max_val;
282
+ input_buffer_ptr[d1] = data_val;
283
+ }
284
+ }
285
+
286
+ // compute sum of (x - max).exp()
287
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
288
+ float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size;
289
+
290
+ int64_t d2 = 0;
291
+ for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) {
292
+ fVec data_fvec0 = fVec::loadu(input_buffer_ptr + d2);
293
+ fVec data_fvec1 = fVec::loadu(input_buffer_ptr + d2 + fVec::size());
294
+ fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d2);
295
+ fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d2 + fVec::size());
296
+ fVec max_fvec0 = fVec::loadu(input_max_data + d2);
297
+ fVec max_fvec1 = fVec::loadu(input_max_data + d2 + fVec::size());
298
+ sum_fvec0 += (data_fvec0 - max_fvec0).exp();
299
+ sum_fvec1 += (data_fvec1 - max_fvec1).exp();
300
+ sum_fvec0.store(tmp_sum_data + d2);
301
+ sum_fvec1.store(tmp_sum_data + d2 + fVec::size());
302
+ }
303
+ for (; d2 < size; d2++) {
304
+ float data_val = input_buffer_ptr[d2];
305
+ float max_val = input_max_data[d2];
306
+ tmp_sum_data[d2] += std::exp(data_val - max_val);
307
+ }
308
+ }
309
+
310
+ // apply log
311
+ vec::map([](fVec x) { return x.log(); }, tmp_sum_data, tmp_sum_data, size);
312
+
313
+ // compute x - max - sum
314
+ for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) {
315
+ float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size;
316
+ scalar_t* output_ptr = output_data_base + outer_idx * dim_size * inner_size
317
+ + dim_idx * inner_size + inner_idx_begin;
318
+
319
+ int64_t d3 = 0;
320
+ for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) {
321
+ fVec data_fvec0 = fVec::loadu(input_buffer_ptr + d3);
322
+ fVec data_fvec1 = fVec::loadu(input_buffer_ptr + d3 + fVec::size());
323
+ fVec max_fvec0 = fVec::loadu(input_max_data + d3);
324
+ fVec max_fvec1 = fVec::loadu(input_max_data + d3 + fVec::size());
325
+ fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d3);
326
+ fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d3 + fVec::size());
327
+ fVec out_fvec0 = data_fvec0 - max_fvec0 - sum_fvec0;
328
+ fVec out_fvec1 = data_fvec1 - max_fvec1 - sum_fvec1;
329
+ Vec out_vec = vec::convert_from_float<scalar_t>(out_fvec0, out_fvec1);
330
+ out_vec.store(output_ptr + d3);
331
+ }
332
+ for (; d3 < size; d3++) {
333
+ output_ptr[d3] = scalar_t(input_buffer_ptr[d3] - input_max_data[d3] - tmp_sum_data[d3]);
334
+ }
335
+ }
336
+ }
337
+ } // namespace CPU_CAPABILITY
338
+ }} // namespace at::native
339
+
340
+ #else
341
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
342
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Loops.h ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // This file provides two functions to help write elementwise kernels:
5
+ //
6
+ // cpu_kernel(TensorIterator iter, <lambda>)
7
+ // cpu_kernel_vec(TensorIterator iter, <lambda>, <vec_lambda>)
8
+ //
9
+ // Both functions may generate vectorized code. The cpu_kernel implementation
10
+ // relies on the compiler's auto-vectorization. The cpu_kernel_vec
11
+ // implementation uses x86 SIMD intrinsics when available. These functions
12
+ // are only intended to be used in the ATen/native/cpu subdirectory, since files
13
+ // in other directories are not compiled with AVX/AVX2 enabled. See README.md
14
+ // for more details.
15
+ //
16
+ // For example, to write a multiplication kernel for float:
17
+ //
18
+ // cpu_kernel(iter, [](float a, float b) { return a * b; });
19
+ //
20
+ // Or you may write:
21
+ //
22
+ // cpu_kernel_vec(iter,
23
+ // [](float a, float b) { return a * b; },
24
+ // [](Vectorized<float> a, Vectorized<float> b) { return a * b; });
25
+ //
26
+ // See BinaryOpsKernel.cpp for the complete implementation
27
+ //
28
+ //
29
+
30
+ #include <cstdint>
31
+ #include <c10/util/C++17.h>
32
+ #include <c10/util/Load.h>
33
+ #include <c10/util/irange.h>
34
+ #include <ATen/detail/FunctionTraits.h>
35
+ #include <ATen/native/cpu/IsContiguous.h>
36
+ #include <ATen/native/TensorIterator.h>
37
+ #include <ATen/native/TensorIteratorDynamicCasting.h>
38
+ #include <ATen/cpu/vec/vec.h>
39
+
40
+ #include <tuple>
41
+ #include <utility>
42
+
43
+ namespace at::native { inline namespace CPU_CAPABILITY {
44
+
45
+ using namespace vec;
46
+
47
+ template <typename traits, std::size_t... INDEX>
48
+ typename traits::ArgsTuple
49
+ dereference_impl(char* C10_RESTRICT data[], const int64_t* strides, int64_t i,
50
+ std::index_sequence<INDEX...> /*unused*/) {
51
+ return std::make_tuple(
52
+ c10::load<typename traits::template arg<INDEX>::type>(
53
+ data[INDEX] + i * strides[INDEX])...);
54
+ }
55
+
56
+ template <typename traits>
57
+ typename traits::ArgsTuple
58
+ dereference(char* C10_RESTRICT data[], const int64_t* strides, int64_t i) {
59
+ using Indices = std::make_index_sequence<traits::arity>;
60
+ return dereference_impl<traits>(data, strides, i, Indices{});
61
+ }
62
+
63
+ template <typename traits, std::size_t... INDEX>
64
+ typename traits::ArgsTuple
65
+ dereference_vec_impl(char* C10_RESTRICT data[],
66
+ const typename traits::result_type& opt_scalar,
67
+ size_t S,
68
+ int64_t i,
69
+ std::index_sequence<INDEX...> /*unused*/) {
70
+ using Vec = typename traits::result_type;
71
+ using scalar_t = typename Vec::value_type;
72
+ return std::make_tuple(
73
+ S == INDEX + 1 ?
74
+ opt_scalar :
75
+ Vec::loadu(data[INDEX] + i * sizeof(scalar_t))...);
76
+ }
77
+
78
+ template <typename traits>
79
+ typename traits::ArgsTuple
80
+ dereference_vec(char* C10_RESTRICT data[], const typename traits::result_type& opt_scalar, size_t S, int64_t i) {
81
+ using Indices = std::make_index_sequence<traits::arity>;
82
+ return dereference_vec_impl<traits>(data, opt_scalar, S, i, Indices{});
83
+ }
84
+
85
+ template <typename func_t,
86
+ std::enable_if_t<!std::is_void_v<typename function_traits<func_t>::result_type>>* = nullptr>
87
+ inline void
88
+ execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) {
89
+ using traits = function_traits<func_t>;
90
+ using result_type = typename traits::result_type;
91
+ for (; i < n; i++) {
92
+ result_type* out_ptr = (result_type*)(data[0] + i * strides[0]);
93
+ *out_ptr = std::apply(op, dereference<traits>(
94
+ &data[1],
95
+ &strides[1],
96
+ i));
97
+ }
98
+ }
99
+
100
+ template <typename func_t,
101
+ std::enable_if_t<std::is_void_v<typename function_traits<func_t>::result_type>>* = nullptr>
102
+ inline void
103
+ execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) {
104
+ using traits = function_traits<func_t>;
105
+ for (; i < n; i++) {
106
+ std::apply(op, dereference<traits>(
107
+ &data[0],
108
+ &strides[0],
109
+ i));
110
+ }
111
+ }
112
+
113
+ // Basic loop operation (one output, N inputs). May be auto-vectorized
114
+ // by the compiler. Supports inputs and outputs of different types.
115
+ template <typename func_t>
116
+ inline void
117
+ basic_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) {
118
+ using traits = function_traits<func_t>;
119
+ constexpr int ntensors = traits::arity + 1;
120
+
121
+ // Copying strides to temporary array helps auto vectorization in older GCC
122
+ // versions.
123
+ int64_t strides[ntensors];
124
+ for (const auto arg : c10::irange(ntensors)) {
125
+ strides[arg] = strides_[arg];
126
+ }
127
+
128
+ execute_op(data, strides, i, n, std::forward<func_t>(op));
129
+ }
130
+
131
+ // the recursive variadic template for iterating over the returned tuple
132
+ template<class T, size_t N>
133
+ struct TupleOutput {
134
+ static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i,
135
+ const T &tuple) {
136
+ TupleOutput<T, N - 1>::handle(data, strides, i, tuple);
137
+
138
+ auto output = std::get<N - 1>(tuple);
139
+ using output_type = decltype(output);
140
+ output_type * out_ptr = (output_type *)(data[N - 1] + i * strides[N - 1]);
141
+ *out_ptr = output;
142
+ }
143
+ };
144
+
145
+ // Base case for the above recursive template
146
+ template<class T>
147
+ struct TupleOutput<T, 1> {
148
+ static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i,
149
+ const T &tuple) {
150
+ auto output = std::get<0>(tuple);
151
+ using output_type = decltype(output);
152
+ output_type* out_ptr = (output_type *)(data[0] + i * strides[0]);
153
+ *out_ptr = output;
154
+ }
155
+ };
156
+
157
+ template<class... Args>
158
+ void handle_tuple_outputs(char* C10_RESTRICT data[],
159
+ const int64_t* strides,
160
+ int64_t i,
161
+ const std::tuple<Args...> &tuple) {
162
+ TupleOutput<decltype(tuple), sizeof...(Args)>::handle(data, strides, i, tuple);
163
+ }
164
+
165
+ // Loop operation for `cpu_kernel_multiple_outputs`.
166
+ // 1. Use `std::apply` to make dynamic method invocation
167
+ // for the lambda passed in `cpu_kernel_multiple_outputs`.
168
+ // 2. Iterate over the members of the returned tuple, set the corresponding
169
+ // output tensor by the tuple member in `handle_tuple_outputs` function.
170
+ template <typename func_t>
171
+ inline void
172
+ multiple_outputs_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) {
173
+ using traits = function_traits<func_t>;
174
+
175
+ using result_type = typename traits::result_type;
176
+ constexpr int num_outputs = std::tuple_size_v<result_type>;
177
+ constexpr int ntensors = traits::arity + num_outputs;
178
+
179
+ // Copying strides to temporary array helps auto vectorization in older GCC
180
+ // versions.
181
+ int64_t strides[ntensors];
182
+ for (const auto arg : c10::irange(ntensors)) {
183
+ strides[arg] = strides_[arg];
184
+ }
185
+
186
+ for (; i < n; i++) {
187
+ auto output = std::apply(op, dereference<traits>(
188
+ &data[num_outputs],
189
+ &strides[num_outputs],
190
+ i));
191
+ handle_tuple_outputs(data, strides, i, output);
192
+ }
193
+ }
194
+
195
+ // Explicitly vectorized loop implementation. All inputs and outputs must be
196
+ // the same type and contiguous with one exception: a single input may be
197
+ // a scalar (stride 0). It's position is indicated by the argument `S`. If `S`
198
+ // is 0, then there are no scalar inputs.
199
+ template <typename func_t, typename vec_func_t>
200
+ inline void
201
+ vectorized_loop(char** C10_RESTRICT data_, int64_t n, int64_t S, func_t&& op, vec_func_t&& vop) {
202
+ using traits = function_traits<vec_func_t>;
203
+ using scalar_t = typename function_traits<func_t>::result_type;
204
+ using Vec = Vectorized<scalar_t>;
205
+ constexpr int ntensors = traits::arity + 1;
206
+
207
+ char* C10_RESTRICT data[ntensors];
208
+ for (const auto arg : c10::irange(ntensors)) {
209
+ data[arg] = data_[arg];
210
+ }
211
+
212
+ Vec opt_scalar = Vec(S > 0 ? c10::load((scalar_t*)data[S]) : scalar_t(0));
213
+ int64_t i = 0;
214
+ for (; i <= n - 2 * Vec::size(); i += 2 * Vec::size()) {
215
+ auto args1 = dereference_vec<traits>(&data[1], opt_scalar, S, i);
216
+ auto args2 = dereference_vec<traits>(&data[1], opt_scalar, S, i + Vec::size());
217
+ auto out1 = std::apply(vop, std::move(args1));
218
+ auto out2 = std::apply(vop, std::move(args2));
219
+ out1.store(data[0] + i * sizeof(scalar_t));
220
+ out2.store(data[0] + (i + Vec::size()) * sizeof(scalar_t));
221
+ }
222
+ if (i < n) {
223
+ int64_t strides[ntensors];
224
+ for (const auto arg : c10::irange(ntensors)) {
225
+ strides[arg] = (S > 0 && arg == S) ? 0 : sizeof(scalar_t);
226
+ }
227
+ basic_loop(data, strides, i, n, std::forward<func_t>(op));
228
+ }
229
+ }
230
+
231
+
232
+ template <typename traits, typename cb_t>
233
+ inline void unroll_contiguous_scalar_checks(
234
+ const int64_t* /*strides*/,
235
+ std::index_sequence<> /*unused*/,
236
+ cb_t&& cb) {
237
+ cb(0);
238
+ }
239
+
240
+ template <typename traits, typename cb_t, size_t INDEX0, size_t ...INDEX>
241
+ inline void unroll_contiguous_scalar_checks(
242
+ const int64_t* strides,
243
+ std::index_sequence<INDEX0, INDEX...> /*unused*/,
244
+ cb_t&& cb) {
245
+ if (is_contiguous_scalar<traits, INDEX0 + 1>(strides)) {
246
+ cb(INDEX0 + 1);
247
+ } else {
248
+ unroll_contiguous_scalar_checks<traits>(strides, std::index_sequence<INDEX...>{}, std::forward<cb_t>(cb));
249
+ }
250
+ }
251
+
252
+ template <typename op_t, typename vop_t>
253
+ struct VectorizedLoop2d {
254
+ op_t op;
255
+ vop_t vop;
256
+
257
+ using traits = function_traits<op_t>;
258
+ static constexpr int ntensors = traits::arity + 1;
259
+ using data_t = std::array<char*, ntensors>;
260
+
261
+ VectorizedLoop2d(op_t op, vop_t vop):
262
+ op(std::move(op)), vop(std::move(vop)) {}
263
+
264
+ static void advance(data_t &data, const int64_t *outer_strides) {
265
+ for (const auto arg : c10::irange(data.size())) {
266
+ data[arg] += outer_strides[arg];
267
+ }
268
+ }
269
+
270
+ void operator()(char** base, const int64_t *strides, int64_t size0, int64_t size1) {
271
+ data_t data;
272
+ std::copy_n(base, ntensors, data.data());
273
+ const int64_t *outer_strides = &strides[ntensors];
274
+
275
+ if (is_contiguous<traits>(strides)) {
276
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
277
+ vectorized_loop(data.data(), size0, 0, op, vop);
278
+ advance(data, outer_strides);
279
+ }
280
+ } else {
281
+ using Indices = std::make_index_sequence<traits::arity>;
282
+ unroll_contiguous_scalar_checks<traits>(strides, Indices{}, [&](size_t idx) {
283
+ if (idx) {
284
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
285
+ vectorized_loop(data.data(), size0, idx, op, vop);
286
+ advance(data, outer_strides);
287
+ }
288
+ } else {
289
+ for ([[maybe_unused]] const auto i : c10::irange(size1)) {
290
+ basic_loop(data.data(), strides, 0, size0, op);
291
+ advance(data, outer_strides);
292
+ }
293
+ }
294
+ });
295
+ }
296
+ }
297
+ };
298
+
299
+ template <typename op_t, typename vop_t>
300
+ VectorizedLoop2d<op_t, vop_t> make_vectorized_loop2d(
301
+ op_t &&op, vop_t &&vop) {
302
+ return VectorizedLoop2d<op_t, vop_t>(std::forward<op_t>(op), std::forward<vop_t>(vop));
303
+ }
304
+
305
+ template <typename func_t>
306
+ void cpu_kernel(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) {
307
+ using traits = function_traits<func_t>;
308
+ // this could be extended to work with void return types
309
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
310
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
311
+ // dynamic casting not currently supported on CPU
312
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
313
+
314
+ iter.for_each([&](char** data, const int64_t* strides, int64_t n) {
315
+ // basic loop can handle 1d slices with arbitrary strides, and 1d slices is all that
316
+ // iter.for_each is ever sending to the loop lambda
317
+ basic_loop(data, strides, 0, n, op);
318
+ }, grain_size);
319
+ iter.cast_outputs();
320
+ }
321
+
322
+ // This function helps write elementwise kernels that requires multiple outputs.
323
+ // It follows the similar structure of cpu_kernel.
324
+ // Instead of `basic_loop` function, a new `multiple_outputs_loop` function is
325
+ // manipulated to handle multiple return values.
326
+ // For now `needs_dynamic_casting` check is not added as the passed lambda (`func_t`)
327
+ // of `multiple_outputs_loop` returns `std::tuple` instead of `scalar_t`.
328
+ // The `gpu_kernel_multiple_outputs` is also implemented without this check,
329
+ // We could extend `needs_dynamic_casting` to support both `std::tuple` and
330
+ // `thrust::tuple` in the future.
331
+ template <typename func_t>
332
+ void cpu_kernel_multiple_outputs(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) {
333
+ using traits = function_traits<func_t>;
334
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
335
+
336
+ iter.for_each([&](char** data, const int64_t* strides, int64_t n) {
337
+ multiple_outputs_loop(data, strides, 0, n, op);
338
+ }, grain_size);
339
+ iter.cast_outputs();
340
+ }
341
+
342
+ template <bool check_dynamic_cast=true, typename func_t, typename vec_func_t>
343
+ void cpu_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, int64_t grain_size = at::internal::GRAIN_SIZE) {
344
+ using traits = function_traits<func_t>;
345
+ // this could be extended to work with void return types
346
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
347
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
348
+ // dynamic casting not currently supported on CPU, but some kernels (like Fill)
349
+ // explicitly dynamic_cast, so we give the opt-out of checking.
350
+ if constexpr (check_dynamic_cast) {
351
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
352
+ }
353
+
354
+ iter.for_each(make_vectorized_loop2d(std::forward<func_t>(op), std::forward<vec_func_t>(vop)), grain_size);
355
+ iter.cast_outputs();
356
+ }
357
+
358
+ template <typename func_t>
359
+ void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op, const Range& range) {
360
+ using traits = function_traits<func_t>;
361
+ constexpr bool result_void = std::is_void_v<typename traits::result_type>;
362
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity &&
363
+ ((result_void && iter.noutputs() == 0) || (!result_void && iter.noutputs() == 1)));
364
+ // dynamic casting not currently supported on CPU
365
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
366
+
367
+ iter.serial_for_each([&](char** data, const int64_t* strides, int64_t n) {
368
+ basic_loop(data, strides, 0, n, op);
369
+ }, range);
370
+ iter.cast_outputs();
371
+ }
372
+
373
+ template <typename func_t>
374
+ void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op) {
375
+ cpu_serial_kernel(iter, std::forward<func_t>(op), {0, iter.numel()});
376
+ }
377
+
378
+ template <typename func_t, typename vec_func_t>
379
+ void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, const Range& range) {
380
+ using traits = function_traits<func_t>;
381
+ // this could be extended to work with void return types
382
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
383
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
384
+ // dynamic casting not currently supported on CPU
385
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
386
+
387
+ iter.serial_for_each(make_vectorized_loop2d(std::forward<func_t>(op), std::forward<vec_func_t>(vop)), range);
388
+ iter.cast_outputs();
389
+ }
390
+
391
+ template <typename func_t, typename vec_func_t>
392
+ void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop) {
393
+ cpu_serial_kernel_vec(iter, std::forward<func_t>(op), std::forward<vec_func_t>(vop), {0, iter.numel()});
394
+ }
395
+
396
+ }} // namespace at::native::<anonymous>
397
+
398
+ #else
399
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
400
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/MaxUnpoolKernel.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using max_unpooling_fn = void(*)(Tensor&, const Tensor&, const Tensor&);
11
+
12
+ DECLARE_DISPATCH(max_unpooling_fn, max_unpool2d_kernel)
13
+ DECLARE_DISPATCH(max_unpooling_fn, max_unpool3d_kernel)
14
+
15
+ }} // at::native
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/PixelShuffleKernel.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ using pixel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t);
12
+ DECLARE_DISPATCH(pixel_shuffle_fn, pixel_shuffle_kernel)
13
+ DECLARE_DISPATCH(pixel_shuffle_fn, pixel_unshuffle_kernel)
14
+
15
+ } // at::native
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/Reduce.h ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/cpu/Loops.h>
5
+ #include <ATen/Parallel.h>
6
+ #include <c10/util/TypeList.h>
7
+ #include <c10/core/Scalar.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #include <type_traits>
11
+
12
+ namespace at::native { inline namespace CPU_CAPABILITY {
13
+
14
+ using namespace vec;
15
+
16
+ #define VEC_LOOP_HEADER(func_t, data) \
17
+ using scalar_t = typename function_traits<func_t>::result_type; \
18
+ using Vec = Vectorized<scalar_t>; \
19
+ char* out_ptr = data[0]; \
20
+ (void) out_ptr;
21
+
22
+ // reduction that is contiguous over the input in dim 0
23
+ template <typename traits>
24
+ inline bool is_contiguous_reduction(const int64_t* strides) {
25
+ return strides[0] == 0 &&
26
+ strides[1] == sizeof(typename traits::arg2_t);
27
+ }
28
+
29
+ // reduction that is contiguous over the input in dim 1
30
+ template <typename traits>
31
+ inline bool is_outer_reduction(const int64_t* strides) {
32
+ return strides[0] == 0 &&
33
+ strides[2] == sizeof(typename traits::result_type) &&
34
+ strides[3] == sizeof(typename traits::arg2_t);
35
+ }
36
+
37
+ template <typename func_t, typename vec_func_t>
38
+ inline void vectorized_reduction(char** data, int64_t n, int64_t stride,
39
+ func_t op, vec_func_t vop, bool reduce) {
40
+ VEC_LOOP_HEADER(func_t, data)
41
+ const char* in1_ptr = data[1];
42
+ Vec acc[4];
43
+ for (const auto j : c10::irange(4)) {
44
+ acc[j] = Vec::loadu(in1_ptr + j * Vec::size() * sizeof(scalar_t));
45
+ }
46
+ for (const auto i : c10::irange(1, n)) {
47
+ const char* ptr = in1_ptr + stride * i;
48
+ acc[0] = vop(acc[0], Vec::loadu(ptr + (0 * Vec::size() * sizeof(scalar_t))));
49
+ acc[1] = vop(acc[1], Vec::loadu(ptr + (1 * Vec::size() * sizeof(scalar_t))));
50
+ acc[2] = vop(acc[2], Vec::loadu(ptr + (2 * Vec::size() * sizeof(scalar_t))));
51
+ acc[3] = vop(acc[3], Vec::loadu(ptr + (3 * Vec::size() * sizeof(scalar_t))));
52
+ }
53
+ if (reduce) {
54
+ scalar_t buffer[Vec::size()];
55
+ acc[0] = vop(vop(acc[0], acc[1]), vop(acc[2], acc[3]));
56
+ acc[0].store(buffer);
57
+ for (const auto j : c10::irange(1, Vec::size())) {
58
+ buffer[0] = op(buffer[0], buffer[j]);
59
+ }
60
+ auto dst = (scalar_t*)out_ptr;
61
+ *dst = op(*dst, buffer[0]);
62
+ } else {
63
+ for (const auto j : c10::irange(4)) {
64
+ auto dst = out_ptr + j * Vec::size() * sizeof(scalar_t);
65
+ acc[j] = vop(acc[j], Vec::loadu(dst));
66
+ acc[j].store(dst);
67
+ }
68
+ }
69
+ }
70
+
71
+ template <typename F>
72
+ inline void UNARY_OUTER_LOOP(char* data[2], const int64_t strides[2], int64_t n, F f) {
73
+ for ([[maybe_unused]] const auto j : c10::irange(n)) {
74
+ f();
75
+ data[0] += strides[0];
76
+ data[1] += strides[1];
77
+ }
78
+ }
79
+
80
+ // computes the reduction out = op(out, in)
81
+ template <typename func_t, typename vec_func_t>
82
+ inline void vectorized_inner_reduction(char** data, int64_t n, func_t op, vec_func_t vop) {
83
+ VEC_LOOP_HEADER(func_t, data)
84
+ constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t);
85
+ int64_t count = n / (4 * Vec::size());
86
+ if (count > 0) {
87
+ vectorized_reduction(data, count, vector_stride, op, vop, /*reduce=*/true);
88
+ }
89
+ char* ptrs[3] = { data[0], data[0], data[1] };
90
+ int64_t strides[] = { 0, 0, sizeof(scalar_t) };
91
+ basic_loop(ptrs, strides, count * 4 * Vec::size(), n, op);
92
+ }
93
+
94
+ // computes the reduction out = op(out, in)
95
+ template <typename func_t, typename vec_func_t>
96
+ inline void vectorized_outer_reduction(char** data, int64_t inner_stride, int64_t size0, int64_t size1, func_t op, vec_func_t vop) {
97
+ VEC_LOOP_HEADER(func_t, data)
98
+
99
+ // reduce down each column of 4 * Vec::size() elements.
100
+ constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t);
101
+ int64_t outer_stride[2] = { vector_stride, vector_stride };
102
+ UNARY_OUTER_LOOP(data, outer_stride, size1 / (4 * Vec::size()), [&] {
103
+ vectorized_reduction(data, size0, inner_stride, op, vop, /*reduce=*/false);
104
+ });
105
+
106
+ // reduce down the remaining columns
107
+ int64_t step[] = { sizeof(scalar_t), sizeof(scalar_t) };
108
+ int64_t remaining = size1 % (4 * Vec::size());
109
+ UNARY_OUTER_LOOP(data, step, remaining, [&] {
110
+ char* ptrs[3] = { data[0], data[0], data[1] };
111
+ int64_t strides[] = { 0, 0, inner_stride };
112
+ basic_loop(ptrs, strides, 0, size0, op);
113
+ });
114
+ }
115
+
116
+ template<typename traits, typename res_t>
117
+ static void set_result(const int index, const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
118
+ // static_assert(std::is_same_v<res_t, typename traits::arg2_t>, "data types must match");
119
+ if (index < num_outputs) {
120
+ char *out = (char *) iter.data_ptr(index);
121
+ *(res_t *) out = result;
122
+ }
123
+ }
124
+
125
+ template<typename traits, typename res_t>
126
+ static void set_results(const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
127
+ AT_ASSERT(num_outputs == 1);
128
+ set_result<traits>(0, result, iter, num_outputs);
129
+ }
130
+
131
+ template<typename traits, std::size_t i = 0, typename... tuple_t>
132
+ inline std::enable_if_t<i == sizeof...(tuple_t), std::size_t>
133
+ for_each_in_tuple(const std::tuple<tuple_t...>& /*t*/, const TensorIteratorBase& /*iter*/, const int /*num_outputs*/) {
134
+ return i;
135
+ }
136
+
137
+ template<typename traits, std::size_t i = 0, typename... tuple_t>
138
+ inline std::enable_if_t<i < sizeof...(tuple_t), std::size_t>
139
+ for_each_in_tuple(const std::tuple<tuple_t...>& t, const TensorIteratorBase &iter, const int num_outputs) {
140
+ if (i < (size_t)num_outputs) {
141
+ set_result<traits>(i, std::get<i>(t), iter, num_outputs);
142
+ return for_each_in_tuple<traits, i + 1, tuple_t...>(t, iter, num_outputs);
143
+ }
144
+ return i;
145
+ }
146
+
147
+ template<typename traits, typename... res_t>
148
+ static void set_results(const std::tuple<res_t...>& result, const TensorIteratorBase &iter, const int num_outputs) {
149
+ AT_ASSERT(num_outputs >= 1);
150
+ std::size_t result_size = for_each_in_tuple<traits>(result, iter, num_outputs);
151
+ AT_ASSERT((size_t)num_outputs == result_size);
152
+ }
153
+
154
+ template <typename T, typename... Args>
155
+ struct all_same : std::conjunction<
156
+ std::is_same<T, Args>...
157
+ > {};
158
+
159
+ // data_t is the input/output data type.
160
+ // acc_t is a type that contains all the necessary data
161
+ // to continue reducing.
162
+ // index_t is a one-dimensional index
163
+ //
164
+ // ops_t is such that &ops_t::reduce, &ops_t::combine, and &ops_t::project exist and satisfy
165
+ // the following.
166
+ // reduce: (acc_t, data_t, index_t) -> acc_t adds one data point to the accumulated value.
167
+ // combine: (acc_t, acc_t) -> acc_t combines two accumulated values into one.
168
+ // project: acc_t -> out_t finishes the reduction, getting the required output.
169
+ //
170
+ // Additionally, acc_t must be default-constructible:
171
+ // acc_t {} is an identity for combine,
172
+ // and project(acc_t {}) is the value of the operation on zero elements.
173
+ //
174
+ // The point of `combine` is to support parallelization -
175
+ // the idea is to one sequence of `reduce` calls per thread of execution,
176
+ // and then to combine them at the end with `combine`.
177
+ //
178
+ // If there is more than one output element,
179
+ // our parallelization strategy is to use one thread for each of them,
180
+ // which means that `combine` will never be called.
181
+ //
182
+ // If, on the other hand, there is only one, then we split the input into
183
+ // into several pieces, reduce each separately, and then combine them.
184
+
185
+ template <typename ops_t, typename init_t>
186
+ void binary_kernel_reduce(TensorIteratorBase& iter, ops_t ops, init_t init) {
187
+ using rf_t = decltype(&ops_t::reduce);
188
+ using cf_t = decltype(&ops_t::combine);
189
+ using pf_t = decltype(&ops_t::project);
190
+ using r_traits = binary_function_traits<rf_t>;
191
+ using c_traits = binary_function_traits<cf_t>;
192
+ using p_traits = unary_function_traits<pf_t>;
193
+ using acc_t = typename p_traits::arg1_t;
194
+ using data_t = typename r_traits::arg2_t;
195
+ static_assert(
196
+ all_same<
197
+ acc_t,
198
+ init_t,
199
+ typename r_traits::arg1_t,
200
+ typename r_traits::result_type,
201
+ typename c_traits::arg1_t,
202
+ typename c_traits::arg2_t,
203
+ typename c_traits::result_type>::value,
204
+ "all accumulate types must match");
205
+ static_assert(
206
+ std::is_default_constructible_v<acc_t>,
207
+ "the accumulate type must be default-constructible"
208
+ );
209
+ const int num_outputs = iter.noutputs();
210
+ iter.foreach_reduced_elt([&ops, &init, num_outputs](TensorIteratorBase &sub_iter) {
211
+ auto reduction_body = [&ops, &sub_iter, num_outputs](acc_t acc, int64_t begin, int64_t end) -> acc_t {
212
+ int ntensors = sub_iter.ntensors();
213
+ sub_iter.serial_for_each([&acc, &ops, num_outputs, ntensors, begin](char** data, const int64_t* strides, int64_t size) {
214
+ AT_ASSERT(ntensors - num_outputs == 1);
215
+ char *in = data[ntensors - 1];
216
+ int64_t stride = strides[ntensors - 1];
217
+ for (const auto i : c10::irange(size)) {
218
+ acc = ops.reduce(acc, c10::load<data_t>(in), begin + i);
219
+ in += stride;
220
+ }
221
+ }, {begin, end});
222
+ return ops.translate_idx(acc, sub_iter.view_offsets()[0]);
223
+ };
224
+ acc_t total_acc = init;
225
+ auto numel = sub_iter.numel();
226
+ if (numel < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 ||
227
+ at::in_parallel_region()) {
228
+ total_acc = reduction_body(total_acc, 0, numel);
229
+ } else {
230
+ int max_threads = at::get_num_threads();
231
+ AT_ASSERT(max_threads > 0);
232
+ static_assert(
233
+ !std::is_same_v<acc_t, bool>,
234
+ "Concurrently modifying different references into std::vector<bool> is UB."
235
+ );
236
+ std::vector<acc_t> buffer((unsigned)max_threads, init);
237
+ at::parallel_for(0, numel, internal::GRAIN_SIZE,
238
+ [&](int64_t begin, int64_t end) {
239
+ auto& acc = buffer[at::get_thread_num()];
240
+ acc = reduction_body(acc, begin, end);
241
+ }
242
+ );
243
+ for (const auto i : c10::irange(max_threads)) {
244
+ total_acc = ops.combine(total_acc, buffer[i]);
245
+ }
246
+ }
247
+ set_results<r_traits>(ops.project(total_acc), sub_iter, num_outputs);
248
+ });
249
+ }
250
+
251
+ template <typename func_t, typename vec_func_t>
252
+ void binary_kernel_reduce_vec(TensorIteratorBase& iter, func_t op, vec_func_t vop, double ident = 0) {
253
+ using traits = binary_function_traits<func_t>;
254
+ static_assert(
255
+ all_same<
256
+ typename traits::result_type,
257
+ typename traits::arg1_t,
258
+ typename traits::arg2_t>::value,
259
+ "all types must match");
260
+
261
+ iter.output_base().fill_(ident);
262
+ iter.parallel_reduce([&](char** data, const int64_t* strides, int64_t size0, int64_t size1) {
263
+ int64_t outer_strides[] = { strides[2], strides[3] };
264
+ if (is_contiguous_reduction<traits>(strides)) {
265
+ // input is contiguous in dim 0, output is reduced in dim 0
266
+ UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
267
+ vectorized_inner_reduction(data, size0, op, vop);
268
+ });
269
+ } else if (is_outer_reduction<traits>(strides)) {
270
+ // input and output are contiguous in dim 1
271
+ int64_t inner_stride = strides[1]; // stride of input in dim 0
272
+ vectorized_outer_reduction(data, inner_stride, size0, size1, op, vop);
273
+ } else {
274
+ UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
275
+ char* ptrs[3] = { data[0], data[0], data[1] };
276
+ int64_t inner_strides[3] = { strides[0], strides[0], strides[1] };
277
+ basic_loop(ptrs, inner_strides, 0, size0, op);
278
+ });
279
+ }
280
+ });
281
+ }
282
+
283
+ // when reduction is on most inner dimension (dim 0 in TensorIterator)
284
+ // and input has contiguous most inner dimension, `binary_kernel_reduce_lastdim`
285
+ // can be used.
286
+ inline bool is_reduce_lastdim(TensorIteratorBase& iter) {
287
+ return iter.num_reduce_dims() == 1 && iter.is_dim_reduced(0)
288
+ && iter.ninputs() == 1 && iter.strides(1)[0] == iter.element_size(1);
289
+ }
290
+
291
+ template <typename reduce_func_t>
292
+ void binary_kernel_reduce_lastdim(TensorIteratorBase& iter, reduce_func_t reduce_op) {
293
+ auto shape = iter.shape();
294
+ int64_t dim_size = shape[0];
295
+ int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / dim_size);
296
+ TensorIterator sub_iter(iter);
297
+ // create sub iterator to parallel on all non-reduce-dims
298
+ sub_iter.narrow(0, 0, 1);
299
+ auto loop = [&](char** data, const int64_t* strides, int64_t size) {
300
+ char* out = data[0];
301
+ char* in = data[1];
302
+ for (int64_t i = 0; i < size; ++i) {
303
+ reduce_op(out, in, dim_size);
304
+ out += strides[0];
305
+ in += strides[1];
306
+ }
307
+ };
308
+ sub_iter.for_each(loop, grain_size);
309
+ }
310
+
311
+ }} // namespace at::native::<anonymous>
312
+
313
+ #else
314
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
315
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ReduceUtils.h ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/NumericUtils.h>
6
+ #include <ATen/cpu/vec/vec.h>
7
+ #include <ATen/cpu/vec/functional.h>
8
+ #include <ATen/native/ReductionType.h>
9
+ #include <c10/util/irange.h>
10
+ #include <ATen/OpMathType.h>
11
+ #include <ATen/native/cpu/utils.h>
12
+
13
+ namespace at::native {
14
+ inline namespace CPU_CAPABILITY {
15
+
16
+ using namespace vec;
17
+
18
+ #define AT_DISPATCH_REDUCTION_TYPES(op, ...) \
19
+ [&] { \
20
+ switch (op) { \
21
+ case ReductionType::SUM: { \
22
+ static constexpr auto reduce = ReductionType::SUM; \
23
+ return __VA_ARGS__(); \
24
+ } \
25
+ case ReductionType::MEAN: { \
26
+ static constexpr auto reduce = ReductionType::MEAN; \
27
+ return __VA_ARGS__(); \
28
+ } \
29
+ case ReductionType::MIN: { \
30
+ static constexpr auto reduce = ReductionType::MIN; \
31
+ return __VA_ARGS__(); \
32
+ } \
33
+ case ReductionType::MAX: { \
34
+ static constexpr auto reduce = ReductionType::MAX; \
35
+ return __VA_ARGS__(); \
36
+ } \
37
+ case ReductionType::PROD: { \
38
+ static constexpr auto reduce = ReductionType::PROD; \
39
+ return __VA_ARGS__(); \
40
+ } \
41
+ } \
42
+ }()
43
+
44
+ template <typename scalar_t, ReductionType reduce>
45
+ inline vec_scalar_t<scalar_t> init_value() {
46
+ using acc_t = vec_scalar_t<scalar_t>;
47
+ acc_t val;
48
+ if (reduce == ReductionType::SUM ||
49
+ reduce == ReductionType::MEAN) {
50
+ val = static_cast<acc_t>(0);
51
+ } else if (reduce == ReductionType::PROD) {
52
+ val = static_cast<acc_t>(1);
53
+ } else if (reduce == ReductionType::MAX) {
54
+ val = -std::numeric_limits<acc_t>::infinity();
55
+ } else {
56
+ TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN);
57
+ val = std::numeric_limits<acc_t>::infinity();
58
+ }
59
+ return val;
60
+ }
61
+
62
+ template <typename scalar_t, ReductionType reduce>
63
+ inline vec_scalar_t<scalar_t> init_value(const std::optional<Scalar>& initial) {
64
+ using acc_t = vec_scalar_t<scalar_t>;
65
+ if (initial.has_value()) {
66
+ return initial.value().to<acc_t>();
67
+ } else {
68
+ return init_value<scalar_t, reduce>();
69
+ }
70
+ }
71
+
72
+ template <typename scalar_t>
73
+ inline void init(scalar_t* out, int64_t size, const vec_scalar_t<scalar_t>& val) {
74
+ using Vec = Vectorized<vec_scalar_t<scalar_t>>;
75
+ map<scalar_t>(
76
+ [val](Vec x) { return Vec(val); },
77
+ out,
78
+ out,
79
+ size);
80
+ }
81
+
82
+ template <typename scalar_t, ReductionType reduce>
83
+ inline void init(scalar_t* out, int64_t size, const std::optional<Scalar>& initial) {
84
+ using acc_t = vec_scalar_t<scalar_t>;
85
+ acc_t val = init_value<scalar_t, reduce>(initial);
86
+ init(out, size, val);
87
+ }
88
+
89
+ // overload with `include_self`, used by scatter_reduce
90
+ template <typename scalar_t, ReductionType reduce>
91
+ inline void init(scalar_t* out, int64_t size, bool include_self = false) {
92
+ using acc_t = vec_scalar_t<scalar_t>;
93
+ if (!include_self) {
94
+ acc_t val = init_value<scalar_t, reduce>();
95
+ init(out, size, val);
96
+ }
97
+ }
98
+
99
+ template <typename scalar_t, ReductionType reduce>
100
+ inline void _init(scalar_t* self_ptr, at::opmath_type<scalar_t>* buffer_ptr, int64_t size, bool include_self) {
101
+ if (!include_self) {
102
+ init<at::opmath_type<scalar_t>, reduce>(buffer_ptr, size, include_self);
103
+ } else {
104
+ vec::convert(self_ptr, buffer_ptr, size);
105
+ }
106
+ }
107
+
108
+ template <typename scalar_t>
109
+ inline std::enable_if_t<!std::is_same_v<scalar_t, Vec2>, scalar_t>
110
+ _max(const scalar_t& x, const scalar_t& y) {
111
+ return at::_isnan(y) ? y : std::max(x, y);
112
+ }
113
+
114
+ template <typename scalar_t>
115
+ inline Vectorized<scalar_t> _max(const Vectorized<scalar_t>& x, const Vectorized<scalar_t>& y) {
116
+ // vec::maximum propagates NaN
117
+ return vec::maximum(x, y);
118
+ }
119
+
120
+ template <typename vec_t>
121
+ inline std::enable_if_t<std::is_same_v<vec_t, Vec2>, Vec2>
122
+ _max(const vec_t& x, const vec_t& y) {
123
+ // vec::maximum propagates NaN
124
+ return maximum(x, y);
125
+ }
126
+
127
+ template <typename scalar_t>
128
+ inline std::enable_if_t<!std::is_same_v<scalar_t, Vec2>, scalar_t>
129
+ _min(const scalar_t& x, const scalar_t& y) {
130
+ return at::_isnan(y) ? y : std::min(x, y);
131
+ }
132
+
133
+ template <typename scalar_t>
134
+ inline Vectorized<scalar_t> _min(const Vectorized<scalar_t>& x, const Vectorized<scalar_t>& y) {
135
+ // vec::minimum propagates NaN
136
+ return vec::minimum(x, y);
137
+ }
138
+
139
+ template <typename vec_t>
140
+ inline std::enable_if_t<std::is_same_v<vec_t, Vec2>, Vec2>
141
+ _min(const vec_t& x, const vec_t& y) {
142
+ // vec::minimum propagates NaN
143
+ return minimum(x, y);
144
+ }
145
+
146
+ template <typename scalar_t, typename accumut, typename Op,
147
+ typename std::enable_if_t<is_reduced_floating_point_v<scalar_t>, int> = 0>
148
+ inline void map_acc(
149
+ const Op& vec_fun,
150
+ accumut* output_data,
151
+ const accumut* input_data,
152
+ const scalar_t* input_data2,
153
+ int64_t size) {
154
+ using Vec = vec::Vectorized<scalar_t>;
155
+ using aVec = vec::Vectorized<accumut>;
156
+ int64_t d = 0;
157
+ constexpr int64_t kVecSize = Vec::size();
158
+ constexpr int64_t kaVecSize = aVec::size();
159
+ for (d = 0; d < size - (size % kVecSize); d += kVecSize) {
160
+ Vec data2_vec = Vec::loadu(input_data2 + d);
161
+ auto [data2_avec0, data2_avec1] = convert_to_float<scalar_t>(data2_vec);
162
+ aVec input_vec0 = aVec::loadu(input_data + d);
163
+ aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize);
164
+ vec_fun(input_vec0, data2_avec0).store(output_data + d);
165
+ vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize);
166
+ }
167
+ if (size - d > 0) {
168
+ int64_t tail_size = size - d;
169
+ Vec data2_vec = Vec::loadu(input_data2 + d, tail_size);
170
+ auto [data2_avec0, data2_avec1] = convert_to_float<scalar_t>(data2_vec);
171
+ if (tail_size > kaVecSize) {
172
+ aVec input_vec0 = aVec::loadu(input_data + d);
173
+ aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize, tail_size - kaVecSize);
174
+ vec_fun(input_vec0, data2_avec0).store(output_data + d);
175
+ vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize, tail_size - kaVecSize);
176
+ } else {
177
+ aVec input_vec0 = aVec::loadu(input_data + d, tail_size);
178
+ vec_fun(input_vec0, data2_avec0).store(output_data + d, tail_size);
179
+ }
180
+ }
181
+ }
182
+
183
+ // for Max and Min, propagate NaN:
184
+ template <typename T, ReductionType reduce>
185
+ inline T update(const T& x, const T& y) {
186
+ if (reduce == ReductionType::SUM ||
187
+ reduce == ReductionType::MEAN) {
188
+ return x + y;
189
+ } else if (reduce == ReductionType::PROD) {
190
+ return x * y;
191
+ } else if (reduce == ReductionType::MAX) {
192
+ return _max(x, y);
193
+ } else {
194
+ TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN);
195
+ return _min(x, y);
196
+ }
197
+ }
198
+
199
+ template <typename scalar_t, ReductionType reduce>
200
+ inline void update(scalar_t* out, const scalar_t* data, int64_t K) {
201
+ using Vec = vec::Vectorized<vec_scalar_t<scalar_t>>;
202
+ map2<scalar_t>(
203
+ [](Vec x, Vec y) { return update<Vec, reduce>(x, y); },
204
+ out,
205
+ out,
206
+ data,
207
+ K);
208
+ }
209
+
210
+ template <typename scalar_t, ReductionType reduce,
211
+ typename std::enable_if_t<is_reduced_floating_point_v<scalar_t>, int> = 0>
212
+ inline void update(at::opmath_type<scalar_t>* out, const scalar_t* data, int64_t K) {
213
+ using opmath_t = at::opmath_type<scalar_t>;
214
+ using Vec = vec::Vectorized<opmath_t>;
215
+ map_acc<scalar_t, opmath_t>(
216
+ [](Vec x, Vec y) { return update<Vec, reduce>(x, y); },
217
+ out,
218
+ out,
219
+ data,
220
+ K);
221
+ }
222
+
223
+ template <typename scalar_t, ReductionType reduce>
224
+ inline void write(scalar_t* out, int64_t count, int64_t K) {
225
+ using Vec = vec::Vectorized<vec_scalar_t<scalar_t>>;
226
+ if (reduce == ReductionType::MEAN) {
227
+ if (count > 0) {
228
+ vec::map<scalar_t>(
229
+ [count](Vec x) { return x / Vec(count); },
230
+ out,
231
+ out,
232
+ K);
233
+ }
234
+ }
235
+ }
236
+
237
+ } // namespace CPU_CAPABILITY
238
+ } // namespace at::native
239
+
240
+ #else
241
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
242
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/BFloat16.h>
7
+ #include <c10/util/Half.h>
8
+
9
+ namespace at::native {
10
+ #if !defined(C10_MOBILE)
11
+ using fp16_gemv_fn = void(*)(int, int, float, const Half*, int, const Half*, int, float, Half*, int);
12
+ DECLARE_DISPATCH(fp16_gemv_fn, fp16_gemv_trans_stub)
13
+
14
+ using bf16_gemv_fn = void(*)(int, int, BFloat16, const BFloat16*, int, const BFloat16*, int, BFloat16, BFloat16*, int);
15
+ DECLARE_DISPATCH(bf16_gemv_fn, bf16_gemv_trans_stub)
16
+
17
+ using fp16_dot_fn = float(*)(const int64_t, const Half*, const int64_t, const Half*, const int64_t);
18
+ DECLARE_DISPATCH(fp16_dot_fn, fp16_dot_stub)
19
+
20
+ using bf16_dot_fn = float(*)(const int64_t, const BFloat16*, const int64_t, const BFloat16*, const int64_t);
21
+ DECLARE_DISPATCH(bf16_dot_fn, bf16_dot_stub)
22
+
23
+ inline namespace CPU_CAPABILITY {
24
+ float fp16_dot_with_fp32_arith(const Half* vec1, const Half* vec2, int64_t len);
25
+ float bf16_dot_with_fp32_arith(const BFloat16* vec1, const BFloat16* vec2, int64_t len);
26
+ } // inline namespace CPU_CAPABILITY
27
+ #endif // !defined(C10_MOBILE)
28
+ } // namespace at::native
29
+
30
+ #else
31
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
32
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SampledAddmmKernel.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ using sampled_addmm_sparse_csr_fn = void(*)(const Tensor&, const Tensor&, const Scalar&, const Scalar&, const Tensor&);
10
+
11
+ DECLARE_DISPATCH(sampled_addmm_sparse_csr_fn, sampled_addmm_sparse_csr_stub)
12
+
13
+ } // at::native
14
+
15
+ #else
16
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
17
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SerialStackImpl.h ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright 2004-present Facebook. All Rights Reserved.
3
+ #pragma once
4
+
5
+ #include <ATen/core/Tensor.h>
6
+
7
+ #include <ATen/MemoryOverlap.h>
8
+ #include <ATen/Parallel.h>
9
+ #include <ATen/TensorIterator.h>
10
+ #include <ATen/cpu/vec/functional.h>
11
+ #include <ATen/cpu/vec/vec.h>
12
+ #include <c10/util/irange.h>
13
+
14
+ namespace at::native::detail {
15
+
16
+ struct InputMeta {
17
+ void* data_ptr;
18
+ int64_t inner_size;
19
+
20
+ InputMeta(const Tensor& t, int64_t dim, int64_t inner)
21
+ : data_ptr(t.data_ptr()), inner_size(t.sizes()[dim] * inner) {}
22
+ };
23
+
24
+ // This kernel is used by two TensorList types:
25
+ // 1. stack_serial_kernel uses at::ArrayRef<Tensor>
26
+ // 2. Static runtime calls this kernel directly (csrc/jit/runtime/static/ops.cpp) with
27
+ // ProcessedNodeInputWrapper.
28
+ // When making changes, make sure that they are compatible with both types!
29
+ template <typename scalar_t, typename TensorListType>
30
+ void stack_serial_kernel_impl(Tensor& result, TensorListType tensors, int64_t dim) {
31
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
32
+ dim >= 0 && dim <= result.dim(),
33
+ "dim out of range in stack_serial_kernel_impl");
34
+ int64_t outer =
35
+ result.numel() / (result.sizes()[dim] * result.strides()[dim]);
36
+ scalar_t* result_data = result.data_ptr<scalar_t>();
37
+ int64_t ninputs = tensors.size();
38
+ std::vector<InputMeta> inputs;
39
+ inputs.reserve(ninputs);
40
+ for (const auto& tensor : tensors) {
41
+ inputs.emplace_back(tensor, dim, tensor.strides()[dim]);
42
+ }
43
+
44
+ using Vec = vec::Vectorized<scalar_t>;
45
+ scalar_t* result_ptr = result_data;
46
+ for (const auto i : c10::irange(outer)) {
47
+ for (const auto j : c10::irange(ninputs)) {
48
+ int64_t local_inner = inputs[j].inner_size;
49
+ scalar_t* input_ptr = (scalar_t*)(inputs[j].data_ptr) + i * local_inner;
50
+
51
+ if (local_inner < Vec::size()) {
52
+ for (const auto k : c10::irange(local_inner)) {
53
+ result_ptr[k] = input_ptr[k];
54
+ }
55
+ } else {
56
+ vec::map(
57
+ [](Vec x) { return x; }, result_ptr, input_ptr, local_inner);
58
+ }
59
+ result_ptr += local_inner;
60
+ }
61
+ }
62
+ }
63
+
64
+ // Checks to see whether native stack can be invoked under these conditions:
65
+ // - result and input tensors are contiguous
66
+ // - only one thread is used
67
+ // - no type promotion has to occur
68
+ // - tensors dtype is Double or Float
69
+ template <typename TensorListType>
70
+ bool can_use_native_serial_stack_impl(Tensor& result, TensorListType tensors, int64_t dim) {
71
+ TORCH_CHECK(!tensors.empty(), "expected a non-empty list of Tensors");
72
+ const Tensor& first_tensor = tensors[0];
73
+ // stack dimension should be in range [0,firstTensor.dim())
74
+ // dim == firstTensor.dim() is a valid input, but it is handled by default code path
75
+ // that uses unsqueeze
76
+ if (dim >= first_tensor.dim()) return false;
77
+ // Native stack doesn't apply any tensor is skipped.
78
+ if (first_tensor.numel() == 0 && first_tensor.dim() == 1) return false;
79
+ // there should be no type promotion
80
+ if (result.dtype() != first_tensor.dtype()) return false;
81
+
82
+ auto first_tensor_mem_format = first_tensor.suggest_memory_format();
83
+ ScalarType dtype = first_tensor.scalar_type();
84
+
85
+ if (!result.is_contiguous(first_tensor_mem_format)) {
86
+ return false;
87
+ }
88
+
89
+ // fast path only works for Double and Float
90
+ if (dtype != ScalarType::Double && dtype != ScalarType::Float) {
91
+ return false;
92
+ }
93
+
94
+ // check remainder of inputs
95
+ #ifndef STRIP_ERROR_MESSAGES
96
+ auto const &first_tensor_shape = first_tensor.sizes();
97
+ #endif
98
+ for (const auto i : c10::irange(1, tensors.size())) {
99
+ auto const &tensor = tensors[i];
100
+ TORCH_CHECK(tensors[i].sizes() == first_tensor.sizes(),
101
+ "stack expects each tensor to be equal size, but got ", first_tensor_shape,
102
+ " at entry 0 and ", tensor.sizes(), " at entry ", i);
103
+
104
+ // every tensor must be contiguous
105
+ // tensor sizes and strides must be the same
106
+ // there should be no type promotion
107
+ if (!tensor.is_contiguous(first_tensor_mem_format) ||
108
+ tensor.strides() != first_tensor.strides() ||
109
+ tensor.dtype() != dtype) {
110
+ return false;
111
+ }
112
+ }
113
+
114
+ // fast native stack should only be used when it is not worth using multiple threads
115
+ // or there is only one thread. Note that we aren't checking result.numel() here because
116
+ // it may not have been resized and we want to defer that cost till later.
117
+ int64_t numel_in_stack = first_tensor.numel() * tensors.size();
118
+ return numel_in_stack < at::internal::GRAIN_SIZE || at::get_num_threads() == 1;
119
+ }
120
+
121
+ template <typename TensorListType, bool should_skip_overlap_check>
122
+ struct CanUseNativeSerialStack;
123
+
124
+ template <typename TensorListType>
125
+ struct CanUseNativeSerialStack<TensorListType, false> {
126
+ static bool call(Tensor& result, TensorListType tensors, int64_t dim) {
127
+ // Inputs cannot alias the output tensor
128
+ for (const auto i : c10::irange(tensors.size())) {
129
+ auto lap = at::get_overlap_status(result, tensors[i]);
130
+ TORCH_CHECK(lap != at::MemOverlapStatus::Partial &&
131
+ lap != at::MemOverlapStatus::Full, 0,
132
+ "unsupported operation: the input tensors cannot refer to any of the "
133
+ "output memory locations. Found overlap in input tensor ", i);
134
+ }
135
+
136
+ return can_use_native_serial_stack_impl(result, tensors, dim);
137
+ }
138
+ };
139
+
140
+ template <typename TensorListType>
141
+ struct CanUseNativeSerialStack<TensorListType, true> {
142
+ static bool call(Tensor& result, TensorListType tensors, int64_t dim) {
143
+ return can_use_native_serial_stack_impl(result, tensors, dim);
144
+ }
145
+ };
146
+
147
+ } // namespace at::native::detail
148
+
149
+ #else
150
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
151
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SoftmaxKernel.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <cstdint>
6
+
7
+ namespace at {
8
+ class Tensor;
9
+
10
+ namespace native {
11
+
12
+ using forward_fn = void (*)(const Tensor&, const Tensor&);
13
+ using backward_fn = void(*)(const Tensor &, const Tensor &, const Tensor&);
14
+
15
+ DECLARE_DISPATCH(forward_fn, softmax_lastdim_kernel)
16
+ DECLARE_DISPATCH(forward_fn, log_softmax_lastdim_kernel)
17
+ DECLARE_DISPATCH(backward_fn, softmax_backward_lastdim_kernel)
18
+ DECLARE_DISPATCH(backward_fn, log_softmax_backward_lastdim_kernel)
19
+
20
+ using forward_fn_with_dim = void(*)(const Tensor &, const Tensor &, const int64_t);
21
+ using backward_fn_with_dim =
22
+ void (*)(const Tensor&, const Tensor&, const Tensor&, const int64_t);
23
+
24
+ DECLARE_DISPATCH(forward_fn_with_dim, softmax_kernel)
25
+ DECLARE_DISPATCH(forward_fn_with_dim, log_softmax_kernel)
26
+ DECLARE_DISPATCH(backward_fn_with_dim, softmax_backward_kernel)
27
+ DECLARE_DISPATCH(backward_fn_with_dim, log_softmax_backward_kernel)
28
+ }
29
+ }
30
+
31
+ #else
32
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
33
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/SpmmReduceKernel.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <ATen/native/ReductionType.h>
7
+
8
+ namespace at::native {
9
+
10
+ using spmm_reduce_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
11
+ using spmm_reduce_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
12
+ using spmm_reduce_backward_input_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
13
+ using spmm_reduce_backward_input_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
14
+ using spmm_reduce_backward_other_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op);
15
+
16
+ DECLARE_DISPATCH(spmm_reduce_fn, spmm_reduce_stub)
17
+ DECLARE_DISPATCH(spmm_reduce_arg_fn, spmm_reduce_arg_stub)
18
+ DECLARE_DISPATCH(spmm_reduce_backward_input_fn, spmm_reduce_backward_input_stub)
19
+ DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_input_arg_stub)
20
+ DECLARE_DISPATCH(spmm_reduce_backward_other_fn, spmm_reduce_backward_other_stub)
21
+ DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_other_arg_stub)
22
+
23
+ } // at::native
24
+
25
+ #else
26
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
27
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/StackKernel.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright 2004-present Facebook. All Rights Reserved.
3
+ #pragma once
4
+
5
+ #include <ATen/core/Tensor.h>
6
+ #include <ATen/native/DispatchStub.h>
7
+
8
+ namespace at::native {
9
+
10
+ using stack_serial_fn = void(*)(Tensor &, TensorList, int64_t);
11
+ DECLARE_DISPATCH(stack_serial_fn, stack_serial_stub)
12
+
13
+ } // namespace at::native
14
+
15
+ #else
16
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
17
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/UpSampleKernelAVXAntialias.h ADDED
@@ -0,0 +1,1381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /*
3
+ The Python Imaging Library (PIL) is
4
+
5
+ Copyright © 1997-2011 by Secret Labs AB
6
+ Copyright © 1995-2011 by Fredrik Lundh
7
+
8
+ Pillow is the friendly PIL fork. It is
9
+
10
+ Copyright © 2010-2022 by Alex Clark and contributors
11
+
12
+ Like PIL, Pillow is licensed under the open source HPND License
13
+ */
14
+
15
+ // This code is heavily inspired from PILLOW-SIMD's implementation:
16
+ // https://github.com/uploadcare/pillow-simd/blob/simd/master/src/libImaging/Resample.c
17
+
18
+ #pragma once
19
+ #ifdef CPU_CAPABILITY_AVX2
20
+ // TODO: This file only supports AVX2. We could split the AVX kernels into
21
+ // smaller logical blocks in order to port them into the Vec.h logic. This would
22
+ // allow to support other vectorization architectures and perhaps also support
23
+ // the non-vectorized fallback (we'd need to make sure it's not slower than the
24
+ // current fallback).
25
+
26
+ #include <ATen/core/Tensor.h>
27
+ #include <ATen/cpu/vec/intrinsics.h>
28
+ #include <c10/util/irange.h>
29
+
30
+ #ifndef AT_PER_OPERATOR_HEADERS
31
+ #include <ATen/Functions.h>
32
+ #else
33
+ #include <ATen/ops/empty.h>
34
+ #endif
35
+
36
+
37
+ namespace {
38
+
39
+ inline __m128i mm_cvtsi32_si128(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) {
40
+ int32_t v;
41
+ if (i32_aligned) {
42
+ v = *(const int32_t*)ptr;
43
+ } else {
44
+ std::memcpy(&v, ptr, 4);
45
+ }
46
+ return _mm_cvtsi32_si128(v);
47
+ }
48
+
49
+ inline __m128i mm_cvtepu8_epi32(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) {
50
+ return _mm_cvtepu8_epi32(mm_cvtsi32_si128(ptr, i32_aligned));
51
+ }
52
+
53
+ inline void _write_endline_rgb_as_uint32(
54
+ uint8_t* C10_RESTRICT output,
55
+ uint32_t data
56
+ ) {
57
+ // data is (R G B X), output is (X1 X2 X3 | R1 B1 G1 R2 ...)
58
+ // Here we explicitly set X as R1
59
+ uint8_t* data_ptr = reinterpret_cast<uint8_t*>(&data);
60
+ data_ptr[3] = output[3];
61
+ std::memcpy(output, data_ptr, 4);
62
+ }
63
+
64
+ at::Tensor unpack_rgb(const at::Tensor& packed_tensor) {
65
+ // Convert a "packed" tensor (typically RGBRGBRGB if channels_last) into
66
+ // RGBARGBARGBA format where A is hard-coded to 0. Each pixel is encoded
67
+ // into as 32 bits. This generalizes to num_channels <= 4 and also works for
68
+ // non-channels_last tensors.
69
+
70
+ const uint8_t* packed = (const uint8_t*)packed_tensor.const_data_ptr<uint8_t>();
71
+ auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2);
72
+ auto num_channels = packed_tensor.size(0);
73
+
74
+ constexpr int rgba_size = 4;
75
+ auto unpacked_tensor = at::empty({rgba_size, packed_tensor.size(1), packed_tensor.size(2)}, at::CPU(at::kByte));
76
+ uint8_t* unpacked = (uint8_t*) unpacked_tensor.data_ptr<uint8_t>();
77
+
78
+ auto stride_i = packed_tensor.stride(2);
79
+ auto stride_j = packed_tensor.stride(0);
80
+
81
+ for (const auto i : c10::irange(num_pixels)) {
82
+ for (const auto j : c10::irange(rgba_size)) {
83
+ unpacked[rgba_size * i + j] = (j < num_channels) ? packed[stride_i * i + stride_j * j] : 0;
84
+ }
85
+ }
86
+ return unpacked_tensor;
87
+ }
88
+
89
+ void pack_rgb(
90
+ const at::Tensor& unpacked_tensor, // IN
91
+ const at::Tensor& packed_tensor // OUT
92
+ ) {
93
+ // Convert from unpacked channels last 3-channels or 4-channels tensor into original data layout.
94
+
95
+ uint8_t* unpacked = (uint8_t*)unpacked_tensor.data_ptr<uint8_t>();
96
+ uint8_t* packed = (uint8_t*)packed_tensor.data_ptr<uint8_t>();
97
+ auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2);
98
+ auto num_channels = packed_tensor.size(0);
99
+
100
+ auto unpacked_increment = unpacked_tensor.size(0);
101
+ auto packed_increment = packed_tensor.stride(2);
102
+ auto packed_stride = packed_tensor.stride(0);
103
+
104
+ TORCH_INTERNAL_ASSERT(unpacked_increment == 3 || unpacked_increment == 4);
105
+
106
+ for ([[maybe_unused]] const auto i : c10::irange(num_pixels)) {
107
+ for (const auto j : c10::irange(num_channels)) {
108
+ packed[j * packed_stride] = unpacked[j];
109
+ }
110
+ unpacked += unpacked_increment;
111
+ packed += packed_increment;
112
+ }
113
+ }
114
+
115
+ void ImagingResampleHorizontalConvolution8u4x(
116
+ uint8_t* C10_RESTRICT lineOut0,
117
+ uint8_t* C10_RESTRICT lineOut1,
118
+ uint8_t* C10_RESTRICT lineOut2,
119
+ uint8_t* C10_RESTRICT lineOut3,
120
+ int64_t out_xsize,
121
+ const uint8_t* C10_RESTRICT lineIn0,
122
+ const uint8_t* C10_RESTRICT lineIn1,
123
+ const uint8_t* C10_RESTRICT lineIn2,
124
+ const uint8_t* C10_RESTRICT lineIn3,
125
+ int64_t in_xsize,
126
+ const int64_t* idx_ptr_xmin,
127
+ const int64_t* idx_ptr_size,
128
+ const int16_t* kk,
129
+ int kmax,
130
+ unsigned int coefs_precision,
131
+ int64_t num_channels,
132
+ bool is_last_line);
133
+
134
+ void ImagingResampleHorizontalConvolution8u(
135
+ uint8_t* C10_RESTRICT lineOut,
136
+ int64_t out_xsize,
137
+ const uint8_t* C10_RESTRICT lineIn,
138
+ int64_t in_xsize,
139
+ const int64_t* idx_ptr_xmin,
140
+ const int64_t* idx_ptr_size,
141
+ const int16_t* kk,
142
+ int kmax,
143
+ unsigned int coefs_precision,
144
+ int64_t num_channels,
145
+ bool is_last_line);
146
+
147
+ void ImagingResampleVerticalConvolution8u(
148
+ uint8_t* C10_RESTRICT lineOut,
149
+ const uint8_t* C10_RESTRICT lineIn,
150
+ int64_t xsize,
151
+ int64_t ids_min,
152
+ int64_t ids_size,
153
+ const int16_t* k,
154
+ unsigned int coefs_precision,
155
+ int64_t num_channels);
156
+
157
+ template<int num_channels>
158
+ void ImagingResampleHorizontal(
159
+ const at::Tensor & unpacked_output,
160
+ const at::Tensor & unpacked_input,
161
+ int ksize,
162
+ const std::vector<at::Tensor>& horiz_indices_weights,
163
+ unsigned int horiz_weights_precision) {
164
+
165
+ // Interpolation horizontal pass: we compute x-axis (image width) interpolation outputs.
166
+
167
+ // Input data is stored as
168
+ // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...]
169
+ // Weights are float values computed for each output pixel and rescaled to uint16:
170
+ // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]]
171
+ // We want to compute the output as following:
172
+ // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...]
173
+ // where
174
+ // oR[yoffset + i] = r[yoffset + xmin[i]] * w[i, 0] + ... + r[yoffset + xmin[i] + K-1] * w[i, K-1]
175
+ // oG[yoffset + i] = g[yoffset + xmin[i]] * w[i, 0] + ... + g[yoffset + xmin[i] + K-1] * w[i, K-1]
176
+ // oB[yoffset + i] = b[yoffset + xmin[i]] * w[i, 0] + ... + b[yoffset + xmin[i] + K-1] * w[i, K-1]
177
+ //
178
+
179
+ // TODO: we may want to merge that into the fallback code (currently called
180
+ // basic_loop_aa_horizontal<uint8_t>)
181
+ // Although this may not be needed if / when we port all this code to use
182
+ // Vec.h since this would potentially give us another fall-back implem
183
+
184
+ const int16_t* kk = (int16_t*)(horiz_indices_weights[3].const_data_ptr<double>());
185
+
186
+ auto xout = unpacked_output.size(2);
187
+ auto yout = unpacked_output.size(1);
188
+ auto xin = unpacked_input.size(2);
189
+ TORCH_INTERNAL_ASSERT(num_channels == unpacked_input.size(0));
190
+
191
+ const int64_t* idx_ptr_xmin = horiz_indices_weights[0].const_data_ptr<int64_t>();
192
+ const int64_t* idx_ptr_size = horiz_indices_weights[1].const_data_ptr<int64_t>();
193
+
194
+ uint8_t* unpacked_output_p = unpacked_output.data_ptr<uint8_t>();
195
+ const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr<uint8_t>();
196
+
197
+ int64_t yy = 0;
198
+ auto xout_stride = xout * num_channels;
199
+ auto xin_stride = xin * num_channels;
200
+ for (; yy < yout - 3; yy += 4) {
201
+ ImagingResampleHorizontalConvolution8u4x(
202
+ unpacked_output_p + yy * xout_stride,
203
+ unpacked_output_p + (yy + 1) * xout_stride,
204
+ unpacked_output_p + (yy + 2) * xout_stride,
205
+ unpacked_output_p + (yy + 3) * xout_stride,
206
+ xout,
207
+ unpacked_input_p + yy * xin_stride,
208
+ unpacked_input_p + (yy + 1) * xin_stride,
209
+ unpacked_input_p + (yy + 2) * xin_stride,
210
+ unpacked_input_p + (yy + 3) * xin_stride,
211
+ xin,
212
+ idx_ptr_xmin,
213
+ idx_ptr_size,
214
+ kk,
215
+ ksize,
216
+ horiz_weights_precision,
217
+ num_channels,
218
+ yy + 3 == yout - 1);
219
+ }
220
+ for (; yy < yout; yy++) {
221
+ ImagingResampleHorizontalConvolution8u(
222
+ unpacked_output_p + yy * xout_stride,
223
+ xout,
224
+ unpacked_input_p + yy * xin_stride,
225
+ xin,
226
+ idx_ptr_xmin,
227
+ idx_ptr_size,
228
+ kk,
229
+ ksize,
230
+ horiz_weights_precision,
231
+ num_channels,
232
+ yy == yout - 1);
233
+ }
234
+ }
235
+
236
+ void ImagingResampleVertical(
237
+ const at::Tensor & unpacked_output,
238
+ const at::Tensor & unpacked_input,
239
+ int ksize,
240
+ const std::vector<at::Tensor>& vert_indices_weights,
241
+ unsigned int vert_weights_precision) {
242
+
243
+ // Interpolation vertical pass: we compute y-axis interpolation outputs.
244
+ // Input data is stored as
245
+ // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...]
246
+ // Weights are float values computed for each output pixel and rescaled to uint16:
247
+ // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]]
248
+ // We want to compute the output as following:
249
+ // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...]
250
+ // where
251
+ // oR[xoffset + i] = r[xoffset + ymin[i]] * w[i, 0] + ... + r[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
252
+ // oG[xoffset + i] = g[xoffset + ymin[i]] * w[i, 0] + ... + g[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
253
+ // oB[xoffset + i] = b[xoffset + ymin[i]] * w[i, 0] + ... + b[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1]
254
+
255
+ // TODO: we may want to merge that into the fallback code (currently called
256
+ // basic_loop_aa_vertical<uint8_t>)
257
+ // Although this may not be needed if / when we port all this code to use
258
+ // Vec.h since this would potentially give us another fall-back implem
259
+ const int16_t* kk = (int16_t*)(vert_indices_weights[3].const_data_ptr<double>());
260
+
261
+ const int64_t* idx_ptr_xmin = vert_indices_weights[0].const_data_ptr<int64_t>();
262
+ const int64_t* idx_ptr_size = vert_indices_weights[1].const_data_ptr<int64_t>();
263
+
264
+ uint8_t* unpacked_output_p = unpacked_output.data_ptr<uint8_t>();
265
+ const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr<uint8_t>();
266
+
267
+ auto xout = unpacked_output.size(2);
268
+ auto yout = unpacked_output.size(1);
269
+ const auto num_channels = unpacked_input.size(0);
270
+ TORCH_INTERNAL_ASSERT(num_channels == unpacked_output.size(0));
271
+
272
+ auto xout_stride = xout * num_channels;
273
+ for (const auto yy : c10::irange(yout)) {
274
+ const auto* k = &kk[yy * ksize];
275
+ auto ids_min = idx_ptr_xmin[yy];
276
+ auto ids_size = idx_ptr_size[yy];
277
+ ImagingResampleVerticalConvolution8u(
278
+ unpacked_output_p + yy * xout_stride,
279
+ unpacked_input_p,
280
+ xout,
281
+ ids_min,
282
+ ids_size,
283
+ k,
284
+ vert_weights_precision,
285
+ num_channels);
286
+ }
287
+ }
288
+
289
+ // This is the only public entry point in this file. It supports bilinear or bicubic
290
+ // mode for uint8 dtype when C <= 4, with or without antialias. The
291
+ // implem is based on PIL-SIMD.
292
+ // Its equivalent implementation (fallback) for when AVX isn't supported or when
293
+ // C > 4 is separable_upsample_generic_Nd_kernel_impl() There are a bunch of
294
+ // future improvement that can be done: look for the TODOs in this file.
295
+ // For details on how the weights are computed and how the multiplications are
296
+ // run on int (instead of float weights), see
297
+ // [ Weights computation for uint8_t and multiplication trick ]
298
+ // For details on how the AVX kernels are implemented, see
299
+ // https://gist.github.com/NicolasHug/47c97d731f05eaad5694c173849b86f5
300
+ // See also [ Support for antialias=False as a subcase of antialias=True ] to
301
+ // learn more about how the antialias=False case is computed. The same holds
302
+ // here: all these kernels are general enough to handle an arbitrary number of
303
+ // weights, but when aa=False they could be optimized further.
304
+ template <typename scale_type, class F>
305
+ void upsample_avx_bilinear_bicubic_uint8(
306
+ const at::Tensor& input_,
307
+ const at::Tensor& output,
308
+ bool align_corners,
309
+ const scale_type& scales,
310
+ bool antialias) {
311
+ auto batch_size = input_.size(0);
312
+ auto num_channels = input_.size(1);
313
+ auto xin = input_.size(3);
314
+ auto yin = input_.size(2);
315
+ auto xout = output.size(3);
316
+ auto yout = output.size(2);
317
+
318
+ if (xin == xout && yin == yout) {
319
+ output.copy_(input_);
320
+ return;
321
+ }
322
+
323
+ at::Tensor input = input_;
324
+ if (!(input.is_contiguous() || input.is_contiguous(at::MemoryFormat::ChannelsLast))) {
325
+ // If input is not contiguous with memory format channels first or channels last,
326
+ // we explicitly convert the input to contiguous channels last memory format.
327
+ // This simplifies the rest of the code and let us assume that the format is only contiguous channels first or channels last,
328
+ // Most tensors going through this `if` block won't need to go through unpacking, but those having C < 3 may
329
+ // have to (this means 2 copies are made). We could avoid the extra copy by handling non-contiguous input
330
+ // directly within unpack_rgb() and pack_rgb(), but initial attempts showed that this is fairly complex.
331
+ input = input.contiguous(at::MemoryFormat::ChannelsLast);
332
+ }
333
+
334
+ auto need_horizontal = xout != xin;
335
+ auto need_vertical = yout != yin;
336
+
337
+ int ksize_horiz, ksize_vert;
338
+ std::vector<at::Tensor> horiz_indices_weights, vert_indices_weights;
339
+ unsigned int horiz_weights_precision, vert_weights_precision;
340
+
341
+ bool skip_unpacking = (num_channels == 3 || num_channels == 4) && input.is_contiguous(at::MemoryFormat::ChannelsLast);
342
+ bool skip_packing = (num_channels == 3 || num_channels == 4) && output.is_contiguous(at::MemoryFormat::ChannelsLast);
343
+
344
+ if (need_horizontal) {
345
+ int interp_dim = 3;
346
+ auto stride = skip_unpacking ? num_channels : 4;
347
+ std::tie(horiz_indices_weights, ksize_horiz, horiz_weights_precision) =
348
+ F::compute_index_ranges_int16_weights(
349
+ /*input_size=*/xin,
350
+ /*output_size=*/xout,
351
+ /*stride=*/stride,
352
+ /*ndims=*/4,
353
+ /*reshape_dim=*/interp_dim,
354
+ /*align_corners=*/align_corners,
355
+ /*opt_scale=*/scales[interp_dim - 2],
356
+ /*antialias=*/antialias,
357
+ /*align_i32=*/true);
358
+ }
359
+
360
+ if (need_vertical) {
361
+ int interp_dim = 2;
362
+ auto stride = skip_unpacking ? num_channels * xout : 4 * xout;
363
+ std::tie(vert_indices_weights, ksize_vert, vert_weights_precision) =
364
+ F::compute_index_ranges_int16_weights(
365
+ /*input_size=*/yin,
366
+ /*output_size=*/yout,
367
+ /*stride=*/stride,
368
+ /*ndims=*/4,
369
+ /*reshape_dim=*/interp_dim,
370
+ /*align_corners=*/align_corners,
371
+ /*opt_scale=*/scales[interp_dim - 2],
372
+ /*antialias=*/antialias,
373
+ /*align_i32=*/true);
374
+ }
375
+
376
+ at::Tensor buffer_horiz, buffer_vert;
377
+ // Minor optimization: we can avoid allocating an extra buffer if we're performing
378
+ // horizontal-only or vertical-only interpolation, and if the tensor doesn't
379
+ // need repacking
380
+ if (need_horizontal && (need_vertical || !skip_packing)) {
381
+ auto c = skip_unpacking ? num_channels : 4;
382
+ buffer_horiz = at::empty({c, yin, xout}, input.options());
383
+ }
384
+ if (need_vertical && !skip_packing) {
385
+ auto c = skip_unpacking ? num_channels : 4;
386
+ buffer_vert = at::empty({c, yout, xout}, input.options());
387
+ }
388
+
389
+ for (const auto i : c10::irange(batch_size)) {
390
+
391
+ at::Tensor unpacked_input = skip_unpacking ? input[i] : unpack_rgb(input[i]);
392
+ at::Tensor unpacked_output;
393
+
394
+ if (need_horizontal) {
395
+ at::Tensor unpacked_output_temp = (need_vertical || !skip_packing) ? buffer_horiz : output[i];
396
+
397
+ if (skip_unpacking && num_channels == 3) {
398
+ ImagingResampleHorizontal<3>(
399
+ unpacked_output_temp,
400
+ unpacked_input,
401
+ ksize_horiz,
402
+ horiz_indices_weights,
403
+ horiz_weights_precision);
404
+ } else {
405
+ ImagingResampleHorizontal<4>(
406
+ unpacked_output_temp,
407
+ unpacked_input,
408
+ ksize_horiz,
409
+ horiz_indices_weights,
410
+ horiz_weights_precision);
411
+ }
412
+ unpacked_output = unpacked_input = unpacked_output_temp;
413
+ }
414
+ if (need_vertical) {
415
+ unpacked_output = skip_packing ? output[i] : buffer_vert;
416
+
417
+ ImagingResampleVertical(
418
+ unpacked_output,
419
+ unpacked_input,
420
+ ksize_vert,
421
+ vert_indices_weights,
422
+ vert_weights_precision
423
+ );
424
+ }
425
+
426
+ TORCH_INTERNAL_ASSERT(unpacked_output.defined());
427
+
428
+ if (!skip_packing) {
429
+ pack_rgb(unpacked_output, output[i]);
430
+ }
431
+ }
432
+ }
433
+
434
+ void ImagingResampleHorizontalConvolution8u4x(
435
+ uint8_t* C10_RESTRICT lineOut0,
436
+ uint8_t* C10_RESTRICT lineOut1,
437
+ uint8_t* C10_RESTRICT lineOut2,
438
+ uint8_t* C10_RESTRICT lineOut3,
439
+ int64_t out_xsize,
440
+ const uint8_t* C10_RESTRICT lineIn0,
441
+ const uint8_t* C10_RESTRICT lineIn1,
442
+ const uint8_t* C10_RESTRICT lineIn2,
443
+ const uint8_t* C10_RESTRICT lineIn3,
444
+ int64_t in_xsize,
445
+ const int64_t* idx_ptr_xmin,
446
+ const int64_t* idx_ptr_size,
447
+ const int16_t* kk,
448
+ int kmax,
449
+ unsigned int coefs_precision,
450
+ int64_t num_channels,
451
+ bool is_last_line) {
452
+
453
+ // Interpolation horizontal pass processing together 4 vertical lines.
454
+ // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA
455
+ // we can encode 4 values as a single uint32 value.
456
+ // - We split the size of weight vector for a given output index as a sum:
457
+ // ids_size = num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1.
458
+ // - We load and process 4 weights values in a loop ("block 4") then we process 2 weights values
459
+ // in another loop ("block 2") and finally we process 1 weights value in the final loop ("block 1").
460
+
461
+ // Define shuffling masks (low/high) for num_channels 4 and 3
462
+ // Mask low casts lower half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA:
463
+ // [r1 g1 b1 a1 r2 g2 b2 a2 ... | R1 G1 B1 A1 R2 G2 B2 A2 ... ] ->
464
+ // [r1 0 r2 0 g1 0 g2 0 b1 0 b2 0 a1 0 a2 0 | R1 0 R2 0 G1 0 G2 0 B1 0 B2 0 A1 0 A2 0]
465
+ // Mask high casts upper half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA::
466
+ // [ ... r3 g3 b3 a3 r4 g4 b4 a4 | ... R3 G3 B3 A3 R4 G4 B4 A4 ] ->
467
+ // [r3 0 r4 0 g3 0 g4 0 b3 0 b4 0 a3 0 a4 0 | R3 0 R4 0 G3 0 G4 0 B3 0 B4 0 A3 0 A4 0]
468
+
469
+ const auto mask_low_c4 = _mm256_set_epi8(
470
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0,
471
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
472
+ const auto mask_high_c4 = _mm256_set_epi8(
473
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
474
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8);
475
+ const auto mask_low_c3 = _mm256_set_epi8(
476
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0,
477
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
478
+ const auto mask_high_c3 = _mm256_set_epi8(
479
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
480
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6);
481
+
482
+ const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4;
483
+ const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4;
484
+
485
+ const auto stride = num_channels * sizeof(uint8_t);
486
+
487
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
488
+
489
+ // out_xsize = output width, out_x = output x index
490
+ // ids_min is the input offset index corresponding to out_x
491
+ // ids_size is the interpolation size for out_x
492
+
493
+ // Let's precompute ids_size limits for block 4 and block 2.
494
+ //
495
+ // In block 4 (4 means we process 4 weight values together), we read input data
496
+ // with _mm_loadu_si128, i.e. 16 bytes, per one line:
497
+ // lineIn0 + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min)
498
+ // --> i <= ids_size - 16.0 / stride
499
+ // Strict boundary:
500
+ // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta
501
+ // Soft boundary for reading inside the buffer except its boundaries:
502
+ // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft
503
+ // RGBA: b4_delta = b4_delta_soft = 3
504
+ // RGB : b4_delta = 5
505
+ // RGB : b4_delta_soft = 4
506
+ const auto b4_delta = (stride == 4) ? 3 : (is_last_line ? 5 : 4);
507
+
508
+ // In block 2 (2 means we process 2 weights values together), we read input data
509
+ // with _mm_loadl_epi64, i.e. 8 bytes, per one line:
510
+ // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min)
511
+ // --> i <= ids_size - 8.0 / stride
512
+ // Strict boundary:
513
+ // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta
514
+ // Soft boundary for reading inside the buffer except its boundaries:
515
+ // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft
516
+ // RGBA: b2_delta = b2_delta_soft = 1
517
+ // RGB : b2_delta = 2
518
+ // RGB : b2_delta_soft = 1
519
+ const auto b2_delta = (stride == 4) ? 1 : (is_last_line ? 2 : 1);
520
+
521
+ const auto max_out_x_strided = out_xsize * stride;
522
+ const auto max_in_x_strided = in_xsize * stride;
523
+
524
+ const auto zero = _mm256_setzero_si256();
525
+ const auto initial = _mm256_set1_epi32(1 << (coefs_precision - 1));
526
+
527
+ for (const auto out_x : c10::irange(out_xsize)) {
528
+ const auto ids_min = idx_ptr_xmin[out_x];
529
+ const auto ids_size = idx_ptr_size[out_x];
530
+ const auto * k = &kk[out_x * kmax];
531
+ int64_t i = 0;
532
+
533
+ auto sss0 = initial;
534
+ auto sss1 = initial;
535
+
536
+ const auto * lineIn0_min = lineIn0 + ids_min;
537
+ const auto * lineIn1_min = lineIn1 + ids_min;
538
+ const auto * lineIn2_min = lineIn2 + ids_min;
539
+ const auto * lineIn3_min = lineIn3 + ids_min;
540
+
541
+ // block 4
542
+ for (; i < ids_size - b4_delta; i += 4) {
543
+ // Load 4 values from weight vector
544
+ // mmk0 = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
545
+ // mmk1 = [wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ...]
546
+ const auto mmk0 = _mm256_set1_epi32(*(int32_t*)&k[i]);
547
+ const auto mmk1 = _mm256_set1_epi32(*(int32_t*)&k[i + 2]);
548
+
549
+ // RGBA: Load 8 pixels (4 per line) from input lines 0 and 1:
550
+ // source = [
551
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
552
+ // R0 G0 B0 A0 R1 G1 B1 A1 R2 G2 B2 A2 R3 G3 B3 A3
553
+ // ]
554
+ // RGB: Load 10 pixels (5 per line)
555
+ // source = [
556
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
557
+ // R0 G0 B0 R1 G1 B1 R2 G2 B2 R3 G3 B3 R4 G4 B4 R5
558
+ // ]
559
+ auto source = _mm256_inserti128_si256(_mm256_castsi128_si256(
560
+ _mm_loadu_si128((__m128i *) (lineIn0_min + stride * i))),
561
+ _mm_loadu_si128((__m128i *) (lineIn1_min + stride * i)), 1);
562
+
563
+ // Apply mask_low:
564
+ // RGBA:
565
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0]
566
+ // RGB:
567
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0]
568
+ auto pix1 = _mm256_shuffle_epi8(source, mask_low);
569
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
570
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk0));
571
+
572
+ // Apply mask_high:
573
+ // RGBA:
574
+ // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 A2 0 A3 0]
575
+ // RGB:
576
+ // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 0 0 0 0]
577
+ auto pix2 = _mm256_shuffle_epi8(source, mask_high);
578
+ // Compute output value as C += w2 * C2 + w3 * C3 for each channel in 32-bit precision
579
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix2, mmk1));
580
+
581
+ // Same as above to next lines 2 and 3:
582
+ auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
583
+ _mm_loadu_si128((__m128i *) (lineIn2_min + stride * i))),
584
+ _mm_loadu_si128((__m128i *) (lineIn3_min + stride * i)), 1);
585
+ auto pix3 = _mm256_shuffle_epi8(source2, mask_low);
586
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix3, mmk0));
587
+ auto pix4 = _mm256_shuffle_epi8(source2, mask_high);
588
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix4, mmk1));
589
+ }
590
+
591
+ // block 2
592
+ for (; i < ids_size - b2_delta; i += 2) {
593
+ // Load 2 values from weight vector
594
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
595
+ const auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]);
596
+
597
+ // Load 4 pixels (2 per line) from input lines 0 and 1:
598
+ // RGBA: source1 = [
599
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
600
+ // R0 G0 B0 A0 R1 G1 B1 A1 0 0 0 0 0 0 0 0
601
+ // ]
602
+ // RGB: source1 = [
603
+ // r0 g0 b0 r1 g1 b1 r2 0 0 0 0 0 0 0 0
604
+ // R0 G0 B0 R1 G1 B1 R2 0 0 0 0 0 0 0 0
605
+ // ]
606
+ auto source1 = _mm256_inserti128_si256(_mm256_castsi128_si256(
607
+ _mm_loadl_epi64((__m128i *) (lineIn0_min + stride * i))),
608
+ _mm_loadl_epi64((__m128i *) (lineIn1_min + stride * i)), 1);
609
+ // Apply mask_low:
610
+ // RGBA:
611
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0]
612
+ // RGB:
613
+ // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0]
614
+ auto pix1 = _mm256_shuffle_epi8(source1, mask_low);
615
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
616
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
617
+
618
+ // Same as above for lines 2 and 3:
619
+ auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
620
+ _mm_loadl_epi64((__m128i *) (lineIn2_min + stride * i))),
621
+ _mm_loadl_epi64((__m128i *) (lineIn3_min + stride * i)), 1);
622
+ auto pix2 = _mm256_shuffle_epi8(source2, mask_low);
623
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
624
+ }
625
+
626
+ // block 1
627
+ const auto i32_aligned = num_channels == 4;
628
+ for (; i < ids_size - 1; i++) {
629
+ // Load 1 value from weight vector
630
+ // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...]
631
+ const auto mmk = _mm256_set1_epi32(k[i]);
632
+
633
+ // Load 2 pixels (one per line) from input lines 0 and 1:
634
+ // RGBA: pix1 = [
635
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0
636
+ // R0 0 0 0 G0 0 0 0 B0 0 0 0 A0 0 0 0
637
+ // ]
638
+ // RGB: pix1 = [
639
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0
640
+ // R0 0 0 0 G0 0 0 0 B0 0 0 0 R1 0 0 0
641
+ // ]
642
+ auto pix1 = _mm256_inserti128_si256(_mm256_castsi128_si256(
643
+ mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)),
644
+ mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1);
645
+ // Compute output value as C += w0 * C0 for each channel in 32-bit precision
646
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
647
+
648
+ // Same as above for lines 2 and 3
649
+ auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256(
650
+ mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned)),
651
+ mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned), 1);
652
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
653
+ }
654
+
655
+ if (i == ids_size - 1) {
656
+ // last element
657
+ auto mmk = _mm256_set1_epi32(k[i]);
658
+ // For num_channels == 3 (3 bytes = one pixel) we tolerate to read 4 bytes
659
+ // lines 0, 1 and 2 won't go out of allocated memory bounds
660
+ auto pix = _mm256_inserti128_si256(_mm256_castsi128_si256(
661
+ mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)),
662
+ mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1);
663
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix, mmk));
664
+
665
+ auto p0 = mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned);
666
+ __m128i p1;
667
+ if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) {
668
+ uint8_t input[4];
669
+ std::memcpy(input, lineIn3_min + stride * i, 3);
670
+ p1 = mm_cvtepu8_epi32(input, true);
671
+ } else {
672
+ p1 = mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned);
673
+ }
674
+ auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256(p0), p1, 1);
675
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
676
+ }
677
+
678
+ // Convert fixed point values back to integers (truncating)
679
+ sss0 = _mm256_srai_epi32(sss0, coefs_precision);
680
+ sss1 = _mm256_srai_epi32(sss1, coefs_precision);
681
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
682
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0)
683
+ sss0 = _mm256_packs_epi32(sss0, zero);
684
+ sss1 = _mm256_packs_epi32(sss1, zero);
685
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
686
+ // (a a b b c c d d) -> (a b c d 0 0 0 0)
687
+ sss0 = _mm256_packus_epi16(sss0, zero);
688
+ sss1 = _mm256_packus_epi16(sss1, zero);
689
+
690
+ // Write the output into single uint32
691
+ // (a b c d) -> x_uint32
692
+ auto o0 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss0));
693
+ auto o1 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss0, 1));
694
+ auto o2 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss1));
695
+ auto o3 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss1, 1));
696
+
697
+ const auto out_x_strided = stride * out_x;
698
+
699
+ if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) {
700
+ // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write
701
+ // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1).
702
+ // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct
703
+ // value which was previously computed by another line. In other words, it means that we can not overwrite
704
+ // it by simply writing 4 bytes from the register to the output. We'll do the following:
705
+ // v----------|
706
+ // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...]
707
+ // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1)
708
+ // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1)
709
+ // Output = [... R G B | R1 G1 B1 R2 ...]
710
+
711
+ _write_endline_rgb_as_uint32(lineOut0 + out_x_strided, o0);
712
+ _write_endline_rgb_as_uint32(lineOut1 + out_x_strided, o1);
713
+ _write_endline_rgb_as_uint32(lineOut2 + out_x_strided, o2);
714
+
715
+ if (C10_UNLIKELY(is_last_line)) {
716
+ // When we handle the last line, we can not access the next 4 bytes
717
+ // as they are out of memory bounds.
718
+ std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, num_channels);
719
+ } else {
720
+ _write_endline_rgb_as_uint32(lineOut3 + out_x_strided, o3);
721
+ }
722
+ } else if (num_channels == 3) {
723
+ // Memcpy 4-bytes is faster than 3-bytes and here
724
+ // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value
725
+ // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...)
726
+ std::memcpy(lineOut0 + out_x_strided, (uint8_t *) &o0, 4);
727
+ std::memcpy(lineOut1 + out_x_strided, (uint8_t *) &o1, 4);
728
+ std::memcpy(lineOut2 + out_x_strided, (uint8_t *) &o2, 4);
729
+ std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, 4);
730
+ } else {
731
+ // num_channels = 4 -> lineOutX + out_x_strided should be uint32 aligned
732
+ *(uint32_t *)(lineOut0 + out_x_strided) = o0;
733
+ *(uint32_t *)(lineOut1 + out_x_strided) = o1;
734
+ *(uint32_t *)(lineOut2 + out_x_strided) = o2;
735
+ *(uint32_t *)(lineOut3 + out_x_strided) = o3;
736
+ }
737
+ }
738
+ }
739
+
740
+ void ImagingResampleHorizontalConvolution8u(
741
+ uint8_t* C10_RESTRICT lineOut,
742
+ int64_t out_xsize,
743
+ const uint8_t* C10_RESTRICT lineIn,
744
+ int64_t in_xsize,
745
+ const int64_t* idx_ptr_xmin,
746
+ const int64_t* idx_ptr_size,
747
+ const int16_t* kk,
748
+ int kmax,
749
+ unsigned int coefs_precision,
750
+ int64_t num_channels,
751
+ bool is_last_line) {
752
+
753
+ // Interpolation horizontal pass processing only one vertical line.
754
+ // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA
755
+ // we can encode 4 values as a single uint32 value.
756
+ // - We split the size of weight vector for a given output index as a sum:
757
+ // ids_size = num_blocks_8 * 8 + num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1
758
+ // - We load and process 8 weights values in a loop ("block 8") then 4 weights and 2 weights values in
759
+ // in another loops ("block 4" and "block 2") and finally we process 1 weight value in the final loop ("block 1").
760
+
761
+ // Define various shuffling masks
762
+ const auto kmask_low = _mm256_set_epi8(
763
+ 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8,
764
+ 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0);
765
+ const auto kmask_high = _mm256_set_epi8(
766
+ 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12,
767
+ 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4);
768
+ const auto kmask_hl = _mm256_set_epi8(
769
+ 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4,
770
+ 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0);
771
+
772
+ const auto mask_low_c4 = _mm256_set_epi8(
773
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0,
774
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
775
+ const auto mask_high_c4 = _mm256_set_epi8(
776
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
777
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8);
778
+ const auto mask_low_c3 = _mm256_set_epi8(
779
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0,
780
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
781
+ const auto mask_high_c3 = _mm256_set_epi8(
782
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
783
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6);
784
+ const auto mask_hl_c3 = _mm256_set_epi8(
785
+ -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
786
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
787
+ const auto mask_hl_c4 = _mm256_set_epi8(
788
+ -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8,
789
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
790
+
791
+ const auto mask_low128_c3 = _mm_set_epi8(
792
+ -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0);
793
+ const auto mask_low128_c4 = _mm_set_epi8(
794
+ -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0);
795
+
796
+ const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4;
797
+ const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4;
798
+ const auto mask_hl = (num_channels == 3) ? mask_hl_c3 : mask_hl_c4;
799
+ const auto mask_low128 = (num_channels == 3) ? mask_low128_c3 : mask_low128_c4;
800
+
801
+ // out_xsize = output width, out_x = output x index
802
+ // ids_min is the input offset index corresponding to out_x
803
+ // ids_size is the interpolation size for out_x
804
+
805
+ const auto stride = num_channels * sizeof(uint8_t);
806
+ const auto zero = _mm_setzero_si128();
807
+
808
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
809
+
810
+ // Let's precompute ids_size limits for block 8, block 4 and block 2
811
+ //
812
+ // In block 8 (8 means we process 8 weight values together), we read at
813
+ // most 32 bytes input data (16 + 16 bytes for RGBA and 12 + 16 bytes for RGB)
814
+ // lineIn + stride * (i + ids_min) + 32 <= lineIn + stride * (ids_size + ids_min)
815
+ // --> i <= ids_size - 32.0 / stride
816
+ // Strict boundary:
817
+ // --> i < ids_size + 1 - int(ceil(32.0 / stride)) = ids_size - b8_delta
818
+ // Soft boundary for reading inside the buffer except its boundaries:
819
+ // --> i < ids_size + 1 - int(32.0 / stride) = ids_size - b8_delta_soft
820
+ // RGBA: b8_delta = b8_delta_soft = 7
821
+ // RGB : b8_delta = 10
822
+ // RGB : b8_delta_soft = 9
823
+ const auto b8_delta = (stride == 4) ? 7 : (is_last_line ? 10 : 9);
824
+
825
+ // In block 4 (4 means we process 4 weight values together), we read
826
+ // 16 bytes of input data.
827
+ // lineIn + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min)
828
+ // --> i <= ids_size - 16.0 / stride
829
+ // Strict boundary:
830
+ // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta
831
+ // Soft boundary for reading inside the buffer except its boundaries:
832
+ // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft
833
+ // RGBA: b4_delta = b4_delta_soft = 3
834
+ // RGB : b4_delta = 5
835
+ // RGB : b4_delta_soft = 4
836
+ const auto b4_delta = (stride == 4) ? 3 : (is_last_line ? 5 : 4);
837
+
838
+ // In block 2 (2 means we process 2 weight values together), we read
839
+ // 8 bytes of input data.
840
+ // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min)
841
+ // --> i <= ids_size - 8.0 / stride
842
+ // Strict boundary:
843
+ // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta
844
+ // Soft boundary for reading inside the buffer except its boundaries:
845
+ // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft
846
+ // RGBA: b2_delta = b2_delta_soft = 1
847
+ // RGB : b2_delta = 2
848
+ // RGB : b2_delta_soft = 1
849
+ const auto b2_delta = (stride == 4) ? 1 : (is_last_line ? 2 : 1);
850
+
851
+ const auto max_out_x_strided = out_xsize * stride;
852
+ const auto max_in_x_strided = in_xsize * stride;
853
+
854
+ for (const auto out_x : c10::irange(out_xsize)) {
855
+ __m128i sss;
856
+ const auto ids_min = idx_ptr_xmin[out_x];
857
+ const auto ids_size = idx_ptr_size[out_x];
858
+ const auto * k = &kk[out_x * kmax];
859
+ int64_t i = 0;
860
+
861
+ const auto * lineIn_min = lineIn + ids_min;
862
+
863
+ if (ids_size < 8) {
864
+ sss = _mm_set1_epi32(1 << (coefs_precision - 1));
865
+ } else {
866
+ // Lower part will be added to higher, use only half of the error
867
+ auto sss256 = _mm256_set1_epi32(1 << (coefs_precision - 2));
868
+
869
+ // block 8
870
+ for (; i < ids_size - b8_delta; i += 8) {
871
+ // Load 8 values from weight vector
872
+ auto tmp = _mm_loadu_si128((__m128i*)&k[i]);
873
+ // ksource = [
874
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7
875
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7
876
+ // ]
877
+ auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
878
+
879
+ // RGBA: Load 8 pixels from input:
880
+ // source = [
881
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
882
+ // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7
883
+ // ]
884
+ // RGB: Load 10 pixels from input (however we can process only 8 pixels):
885
+ // source = [
886
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
887
+ // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9
888
+ // ]
889
+ auto source = _mm256_inserti128_si256(_mm256_castsi128_si256(
890
+ _mm_loadu_si128((__m128i *) (lineIn_min + stride * i))),
891
+ _mm_loadu_si128((__m128i *) (lineIn_min + stride * (i + 4))), 1);
892
+
893
+ // Extract lower part of each lane, cast to epi16 and reorder RGBARGBA -> RRGGBBAA
894
+ // RGBA: pix1 = [
895
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0
896
+ // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 a4 0 a5 0
897
+ // ]
898
+ // RGB: pix1 = [
899
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0
900
+ // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 0 0 0 0
901
+ // ]
902
+ auto pix1 = _mm256_shuffle_epi8(source, mask_low);
903
+ // mmk1 = [
904
+ // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ...
905
+ // wl_4 wh_4 wl_5 wh_5 wl_4 wh_4 wl_5 wh_5 ... ...
906
+ // ]
907
+ auto mmk1 = _mm256_shuffle_epi8(ksource, kmask_low);
908
+ // Compute output value as
909
+ // C += w0 * C0 + w1 * C1
910
+ // C += w4 * C4 + w5 * C5 for each channel in 32-bit precision
911
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix1, mmk1));
912
+
913
+ // Same as above for higher part of each lane
914
+ auto pix2 = _mm256_shuffle_epi8(source, mask_high);
915
+ auto mmk2 = _mm256_shuffle_epi8(ksource, kmask_high);
916
+ // Compute output value as
917
+ // C += w2 * C2 + w3 * C3
918
+ // C += w6 * C6 + w7 * C7 for each channel in 32-bit precision
919
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix2, mmk2));
920
+ }
921
+
922
+ // block 4
923
+ for (; i < ids_size - b4_delta; i += 4) {
924
+ // Load 4 values from weight vector
925
+ auto tmp = _mm_loadl_epi64((__m128i *) &k[i]);
926
+ // ksource = [
927
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0
928
+ // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0
929
+ // ]
930
+ auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
931
+
932
+ // Load pixels from input line
933
+ tmp = _mm_loadu_si128((__m128i *) (lineIn_min + stride * i));
934
+ // RGBA: source = [
935
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
936
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
937
+ // ]
938
+ // RGB: source = [
939
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
940
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
941
+ // ]
942
+ auto source = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1);
943
+
944
+ // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA
945
+ // RGBA: pix = [
946
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0
947
+ // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0
948
+ // ]
949
+ // RGB: pix = [
950
+ // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0
951
+ // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0
952
+ // ]
953
+ auto pix = _mm256_shuffle_epi8(source, mask_hl);
954
+ // mmk = [
955
+ // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ...
956
+ // wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ... ...
957
+ // ]
958
+ auto mmk = _mm256_shuffle_epi8(ksource, kmask_hl);
959
+ // Compute output value as
960
+ // C += w0 * C0 + w1 * C1
961
+ // C += w2 * C2 + w3 * C3 for each channel in 32-bit precision
962
+ sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix, mmk));
963
+ }
964
+
965
+ // Sum results between the lanes
966
+ sss = _mm_add_epi32(
967
+ _mm256_extracti128_si256(sss256, 0),
968
+ _mm256_extracti128_si256(sss256, 1));
969
+ }
970
+
971
+ // block 2
972
+ for (; i < ids_size - b2_delta; i += 2) {
973
+ // Load 2 values from weight vector
974
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...]
975
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
976
+ // Load pixels from input line
977
+ // RGBA: source = [
978
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
979
+ // ]
980
+ // RGB: source = [
981
+ // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0
982
+ // ]
983
+ auto source = _mm_loadl_epi64((__m128i *) (lineIn_min + stride * i));
984
+ // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA
985
+ auto pix = _mm_shuffle_epi8(source, mask_low128);
986
+ // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision
987
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
988
+ }
989
+
990
+ // block 1
991
+ const auto i32_aligned = num_channels == 4;
992
+ for (; i < ids_size - 1; i++) {
993
+ // Load 1 value from weight vector
994
+ // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...]
995
+ auto mmk = _mm_set1_epi32(k[i]);
996
+ // Load one pixel from input line
997
+ // RGBA: pix = [
998
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0
999
+ // ]
1000
+ // RGB: pix = [
1001
+ // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0
1002
+ // ]
1003
+ auto pix = mm_cvtepu8_epi32(lineIn_min + stride * i, i32_aligned);
1004
+ // Compute output value as C += w0 * C0 for each channel in 32-bit precision
1005
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1006
+ }
1007
+
1008
+ if (i == ids_size - 1) {
1009
+ // last element
1010
+ auto mmk = _mm_set1_epi32(k[i]);
1011
+ __m128i pix;
1012
+ auto p = lineIn_min + stride * i;
1013
+ if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) {
1014
+ uint8_t input[4];
1015
+ std::memcpy(input, p, 3);
1016
+ pix = mm_cvtepu8_epi32(input, true);
1017
+ } else {
1018
+ pix = mm_cvtepu8_epi32(p, i32_aligned);
1019
+ }
1020
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1021
+ }
1022
+
1023
+ // Convert fixed point values back to integers (truncating)
1024
+ sss = _mm_srai_epi32(sss, coefs_precision);
1025
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1026
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0)
1027
+ sss = _mm_packs_epi32(sss, zero);
1028
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1029
+ // (a a b b c c d d) -> (a b c d 0 0 0 0)
1030
+ sss = _mm_packus_epi16(sss, zero);
1031
+ // Write the output into single uint32
1032
+ // (a b c d) -> x_uint32
1033
+ auto o = _mm_cvtsi128_si32(sss);
1034
+ const auto out_x_strided = stride * out_x;
1035
+ if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) {
1036
+ if (C10_UNLIKELY(is_last_line)) {
1037
+ // When we handle the last line, we can not access the next 4 bytes
1038
+ // as they are out of memory bounds.
1039
+ std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 3);
1040
+ } else {
1041
+ // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write
1042
+ // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1).
1043
+ // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct
1044
+ // value which was previously computed by another line. In other words, it means that we can not overwrite
1045
+ // it by simply writing 4 bytes from the register to the output. We'll do the following:
1046
+ // v----------|
1047
+ // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...]
1048
+ // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1)
1049
+ // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1)
1050
+ // Output = [... R G B | R1 G1 B1 R2 ...]
1051
+ _write_endline_rgb_as_uint32(lineOut + out_x_strided, o);
1052
+ }
1053
+ } else if (num_channels == 3) {
1054
+ // Memcpy 4-bytes is faster than 3-bytes and here
1055
+ // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value
1056
+ // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...)
1057
+ std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 4);
1058
+ } else {
1059
+ // num_channels = 4 -> lineOut + out_x_strided should be uint32 aligned
1060
+ *(uint32_t *)(lineOut + out_x_strided) = o;
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ void ImagingResampleVerticalConvolution8u(
1066
+ uint8_t* C10_RESTRICT lineOut,
1067
+ const uint8_t* C10_RESTRICT lineIn,
1068
+ int64_t xsize,
1069
+ int64_t ids_min,
1070
+ int64_t ids_size,
1071
+ const int16_t* k,
1072
+ unsigned int coefs_precision,
1073
+ int64_t num_channels) {
1074
+
1075
+ // Interpolation vertical pass processing one line.
1076
+ // - We process x-axis data with blocks of 8, 2 and 1
1077
+ // - We split the size of weight vector for a given output index as a sum: K = n * 2 + m.
1078
+
1079
+ // xsize = output width, also equals to input width
1080
+ // ids_size = interpolation size
1081
+ // ids_min = input y start index
1082
+ const auto stride = num_channels * sizeof(uint8_t);
1083
+
1084
+ TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4);
1085
+
1086
+ const int64_t data_size = xsize * stride;
1087
+ const int64_t data_stride = stride;
1088
+ constexpr auto vec_size = 256 / 8;
1089
+
1090
+ const auto initial = _mm_set1_epi32(1 << (coefs_precision - 1));
1091
+ const auto initial_256 = _mm256_set1_epi32(1 << (coefs_precision - 1));
1092
+ const auto zero = _mm_setzero_si128();
1093
+ const auto zero_256 = _mm256_setzero_si256();
1094
+
1095
+ int64_t j = 0;
1096
+ // block 8
1097
+ const auto b8_usable_vec_stride = (vec_size / data_stride) * data_stride;
1098
+ for (; j < data_size - vec_size; j += b8_usable_vec_stride) {
1099
+ auto sss0 = initial_256;
1100
+ auto sss1 = initial_256;
1101
+ auto sss2 = initial_256;
1102
+ auto sss3 = initial_256;
1103
+ int64_t i = 0;
1104
+ const auto * lineIn_min = lineIn + j + ids_min;
1105
+
1106
+ for (; i < ids_size - 1; i += 2) {
1107
+ // Load 2 values from weight vector
1108
+ auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]);
1109
+
1110
+ // RGBA: Load 8 pixels per line
1111
+ // source1 = [
1112
+ // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3
1113
+ // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7
1114
+ // ]
1115
+ // RGB: Load 10 pixels per line (however we can process only 8 pixels):
1116
+ // source1 = [
1117
+ // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5
1118
+ // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9
1119
+ // ]
1120
+ auto source1 =
1121
+ _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * i));
1122
+ auto source2 =
1123
+ _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * (i + 1)));
1124
+
1125
+ // Interleave source1 and source2 from the low half of each 128-bit lane
1126
+ // and cast the result to epi16
1127
+ // RGBA: pix1 = [
1128
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1129
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0
1130
+ // ]
1131
+ // RGB: pix1 = [
1132
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1133
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0
1134
+ // ]
1135
+ auto source_lo = _mm256_unpacklo_epi8(source1, source2);
1136
+ auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256);
1137
+ // Compute output value as
1138
+ // C += w0 * c0 + w1 * C0
1139
+ // C += w0 * c1 + w1 * C1 for each channel in 32-bit precision
1140
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
1141
+
1142
+ // RGBA: pix2 = [
1143
+ // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 a2 0 A2 0
1144
+ // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 a3 0 A3 0
1145
+ // ]
1146
+ // RGB: pix2 = [
1147
+ // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 0 0 0 0
1148
+ // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 0 0 0 0
1149
+ // ]
1150
+ auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256);
1151
+ // Compute output value as
1152
+ // C += w0 * c2 + w1 * C2
1153
+ // C += w0 * c3 + w1 * C3 for each channel in 32-bit precision
1154
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
1155
+
1156
+ // Same as above for the high half of each 128-bit lane
1157
+ auto source_hi = _mm256_unpackhi_epi8(source1, source2);
1158
+ auto pix3 = _mm256_unpacklo_epi8(source_hi, zero_256);
1159
+ sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk));
1160
+ auto pix4 = _mm256_unpackhi_epi8(source_hi, zero_256);
1161
+ sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk));
1162
+ }
1163
+ // Same processing as above but with a single weight value
1164
+ for (; i < ids_size; i += 1) {
1165
+ auto mmk = _mm256_set1_epi32(k[i]);
1166
+
1167
+ auto source1 = _mm256_loadu_si256((__m256i*)(lineIn_min + i * data_size));
1168
+
1169
+ auto source_lo = _mm256_unpacklo_epi8(source1, zero_256);
1170
+ auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256);
1171
+ sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk));
1172
+ auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256);
1173
+ sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk));
1174
+
1175
+ auto source_hi = _mm256_unpackhi_epi8(source1, zero_256);
1176
+ auto pix3 = _mm256_unpacklo_epi8(source_hi, _mm256_setzero_si256());
1177
+ sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk));
1178
+ auto pix4 = _mm256_unpackhi_epi8(source_hi, _mm256_setzero_si256());
1179
+ sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk));
1180
+ }
1181
+ // Convert fixed point values back to integers (truncating)
1182
+ sss0 = _mm256_srai_epi32(sss0, coefs_precision);
1183
+ sss1 = _mm256_srai_epi32(sss1, coefs_precision);
1184
+ sss2 = _mm256_srai_epi32(sss2, coefs_precision);
1185
+ sss3 = _mm256_srai_epi32(sss3, coefs_precision);
1186
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1187
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1188
+ sss0 = _mm256_packs_epi32(sss0, sss1);
1189
+ sss2 = _mm256_packs_epi32(sss2, sss3);
1190
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1191
+ // (a a b b c c d d) -> (a b c d)
1192
+ sss0 = _mm256_packus_epi16(sss0, sss2);
1193
+
1194
+ // Stores 32 bytes
1195
+ _mm256_storeu_si256((__m256i*)(lineOut + j), sss0);
1196
+ }
1197
+
1198
+ // TODO: Do we also need block 4 ???
1199
+ // block 2
1200
+ const auto b2_usable_vec_stride = (8 / data_stride) * data_stride;
1201
+ for (; j < data_size - vec_size / 4; j += b2_usable_vec_stride) {
1202
+ auto sss0 = initial;
1203
+ auto sss1 = initial;
1204
+ int64_t i = 0;
1205
+ const auto * lineIn_min = lineIn + j + ids_min;
1206
+
1207
+ for (; i < ids_size - 1; i += 2) {
1208
+ // Load 2 values from weight vector
1209
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ]
1210
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1211
+
1212
+ // Load 2 pixels per line
1213
+ // RGBA: source1 = [
1214
+ // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0
1215
+ // ]
1216
+ // RGB: source1 = [
1217
+ // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0
1218
+ // ]
1219
+ auto source1 = _mm_loadl_epi64((__m128i *) (lineIn_min + i * data_size));
1220
+ auto source2 = _mm_loadl_epi64((__m128i *) (lineIn_min + (i + 1) * data_size));
1221
+ // Interleave source1 and source2 and cast the result to epi16
1222
+ // RGBA: pix = [
1223
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1224
+ // ]
1225
+ // RGB: pix = [
1226
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1227
+ // ]
1228
+ auto source = _mm_unpacklo_epi8(source1, source2);
1229
+ auto pix = _mm_unpacklo_epi8(source, zero);
1230
+ // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision
1231
+ sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix, mmk));
1232
+ // RGBA: pix = [
1233
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0
1234
+ // ]
1235
+ // RGB: pix = [
1236
+ // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0
1237
+ // ]
1238
+ pix = _mm_unpackhi_epi8(source, zero);
1239
+ // Compute output value as C += w0 * c1 + w1 * C1 for each channel in 32-bit precision
1240
+ sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix, mmk));
1241
+ }
1242
+ // Same processing as above but with a single weight value
1243
+ for (; i < ids_size; i += 1) {
1244
+ auto mmk = _mm_set1_epi32(k[i]);
1245
+
1246
+ auto source1 = _mm_loadl_epi64((__m128i*) (lineIn_min + i * data_size));
1247
+
1248
+ auto source = _mm_unpacklo_epi8(source1, zero);
1249
+ auto pix1 = _mm_unpacklo_epi8(source, zero);
1250
+ sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix1, mmk));
1251
+ auto pix2 = _mm_unpackhi_epi8(source, zero);
1252
+ sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix2, mmk));
1253
+ }
1254
+ // Convert fixed point values back to integers (truncating)
1255
+ sss0 = _mm_srai_epi32(sss0, coefs_precision);
1256
+ sss1 = _mm_srai_epi32(sss1, coefs_precision);
1257
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1258
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1259
+ sss0 = _mm_packs_epi32(sss0, sss1);
1260
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1261
+ // (a a b b c c d d) -> (a b c d)
1262
+ sss0 = _mm_packus_epi16(sss0, sss0);
1263
+ // Store 2 pixels to the output
1264
+ _mm_storel_epi64((__m128i*)(lineOut + j), sss0);
1265
+ }
1266
+
1267
+ // block 1
1268
+ const auto b1_usable_vec_stride = (4 / data_stride) * data_stride;
1269
+ const auto i32_aligned = num_channels == 4;
1270
+ for (; j < data_size - 4; j += b1_usable_vec_stride) {
1271
+ auto sss = initial;
1272
+ int64_t i = 0;
1273
+ const auto * lineIn_min = lineIn + j + ids_min;
1274
+
1275
+ for (; i < ids_size - 1; i += 2) {
1276
+ // Load 2 values from weight vector
1277
+ // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ]
1278
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1279
+
1280
+ // Load one pixel per line
1281
+ // RGBA: source1 = [
1282
+ // r0 g0 b0 a0 0 0 0 0 0 0 0 0 0 0 0 0
1283
+ // ]
1284
+ // RGB: source1 = [
1285
+ // r0 g0 b0 r1 0 0 0 0 0 0 0 0 0 0 0 0
1286
+ // ]
1287
+ auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned);
1288
+ auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned);
1289
+
1290
+ // Interleave source1 and source2 and cast the result to epi16
1291
+ // RGBA: pix = [
1292
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0
1293
+ // ]
1294
+ // RGB: pix = [
1295
+ // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0
1296
+ // ]
1297
+ auto source = _mm_unpacklo_epi8(source1, source2);
1298
+ auto pix = _mm_unpacklo_epi8(source, zero);
1299
+ // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision
1300
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1301
+ }
1302
+
1303
+ for (; i < ids_size; i++) {
1304
+ auto mmk = _mm_set1_epi32(k[i]);
1305
+ auto pix = mm_cvtepu8_epi32(lineIn_min + i * data_size, i32_aligned);
1306
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1307
+ }
1308
+ sss = _mm_srai_epi32(sss, coefs_precision);
1309
+ sss = _mm_packs_epi32(sss, zero);
1310
+ sss = _mm_packus_epi16(sss, zero);
1311
+
1312
+ auto o = _mm_cvtsi128_si32(sss);
1313
+
1314
+ // Here we write 4 bytes to the output even if num_channels < 4, e.g o = {r,g,b,X} for num_channels=3
1315
+ // It is OK to write 4th byte (e.g. X) as on the next step we will overwrite it with new data.
1316
+ // We also won't go out of bounds of lineOut memory allocation
1317
+ std::memcpy(lineOut + j, (uint8_t *) &o, 4);
1318
+ }
1319
+
1320
+ for (; j < data_size; j += data_stride) {
1321
+ auto sss = initial;
1322
+ int64_t i = 0;
1323
+ const auto * lineIn_min = lineIn + j + ids_min;
1324
+ // For RGBA we can use (ids_size - 1) as tighter limit but for RGB we can read outside memory boundary
1325
+ // for the last remaining line
1326
+ for (; i < ids_size - 2; i += 2) {
1327
+ // Load two coefficients at once
1328
+ auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]);
1329
+
1330
+ // Load 2 lines
1331
+ auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned);
1332
+ auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned);
1333
+
1334
+ auto source = _mm_unpacklo_epi8(source1, source2);
1335
+ auto pix = _mm_unpacklo_epi8(source, zero);
1336
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1337
+ }
1338
+
1339
+ // Same processing as above but with a single weight value
1340
+ for (; i < ids_size; i++) {
1341
+ auto mmk = _mm_set1_epi32(k[i]);
1342
+
1343
+ const uint8_t * p = lineIn_min + i * data_size;
1344
+ __m128i pix;
1345
+ // There is no much perf gain using more detailed condition like
1346
+ // num_channels == 3 && ids_min + j + data_size * i + 4 >= in_max_size
1347
+ // const int64_t in_max_size = data_size * in_ysize;
1348
+ if (num_channels == 3) {
1349
+ uint8_t input[4];
1350
+ std::memcpy(input, p, 3);
1351
+ pix = mm_cvtepu8_epi32(input, true);
1352
+ } else {
1353
+ pix = mm_cvtepu8_epi32(p, true);
1354
+ }
1355
+ sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk));
1356
+ }
1357
+
1358
+ // Convert fixed point values back to integers (truncating)
1359
+ sss = _mm_srai_epi32(sss, coefs_precision);
1360
+ // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation
1361
+ // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d)
1362
+ sss = _mm_packs_epi32(sss, zero);
1363
+ // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation
1364
+ // (a a b b c c d d) -> (a b c d)
1365
+ sss = _mm_packus_epi16(sss, zero);
1366
+ // Store one pixel to the output
1367
+ auto o = _mm_cvtsi128_si32(sss);
1368
+ if (num_channels == 3 && C10_UNLIKELY(j + 4 >= data_size)) {
1369
+ std::memcpy(lineOut + j, (uint8_t *) &o, 3);
1370
+ } else {
1371
+ std::memcpy(lineOut + j, (uint8_t *) &o, 4);
1372
+ }
1373
+ }
1374
+ }
1375
+
1376
+ } // anonymous namespace
1377
+ #endif // CPU_CAPABILITY_AVX2
1378
+
1379
+ #else
1380
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1381
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/WeightNormKernel.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ class TensorBase;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ using weight_norm_fn = void(*)(
13
+ TensorBase&, TensorBase&, const TensorBase&, const TensorBase&, int64_t);
14
+ using weight_norm_backward_fn = void(*)(
15
+ TensorBase&, TensorBase&, const TensorBase&, const TensorBase&,
16
+ const TensorBase&, const TensorBase&, int64_t);
17
+
18
+ DECLARE_DISPATCH(weight_norm_fn, weight_norm_stub)
19
+ DECLARE_DISPATCH(weight_norm_backward_fn, weight_norm_backward_stub)
20
+
21
+ } // namespace at::native
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/avx_mathfun.h ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ /*
4
+ AVX implementation of sin, cos, sincos, exp and log
5
+
6
+ Based on "sse_mathfun.h", by Julien Pommier
7
+ http://gruntthepeon.free.fr/ssemath/
8
+
9
+ Copyright (C) 2012 Giovanni Garberoglio
10
+ Interdisciplinary Laboratory for Computational Science (LISC)
11
+ Fondazione Bruno Kessler and University of Trento
12
+ via Sommarive, 18
13
+ I-38123 Trento (Italy)
14
+
15
+ This software is provided 'as-is', without any express or implied
16
+ warranty. In no event will the authors be held liable for any damages
17
+ arising from the use of this software.
18
+
19
+ Permission is granted to anyone to use this software for any purpose,
20
+ including commercial applications, and to alter it and redistribute it
21
+ freely, subject to the following restrictions:
22
+
23
+ 1. The origin of this software must not be misrepresented; you must not
24
+ claim that you wrote the original software. If you use this software
25
+ in a product, an acknowledgment in the product documentation would be
26
+ appreciated but is not required.
27
+ 2. Altered source versions must be plainly marked as such, and must not be
28
+ misrepresented as being the original software.
29
+ 3. This notice may not be removed or altered from any source distribution.
30
+
31
+ (this is the zlib license)
32
+ */
33
+
34
+ #include <ATen/native/cpu/Intrinsics.h>
35
+
36
+ /* The original source of this file has been modified. */
37
+ #if defined(CPU_CAPABILITY_AVX2)
38
+
39
+ #if defined(__GNUC__)
40
+ # define ALIGN32_BEG __attribute__((aligned(32)))
41
+ #elif defined(_WIN32)
42
+ # define ALIGN32_BEG __declspec(align(32))
43
+ #endif
44
+
45
+ typedef __m256 v8sf; // vector of 8 float (avx2)
46
+ typedef __m256i v8si; // vector of 8 int (avx2)
47
+
48
+ /* declare some AVX constants -- why can't I figure a better way to do that? */
49
+ #define _PS256_CONST(Name, Val) \
50
+ static const ALIGN32_BEG float _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
51
+ #define _PI32_CONST256(Name, Val) \
52
+ static const ALIGN32_BEG int _pi32_256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
53
+ #define _PS256_CONST_TYPE(Name, Type, Val) \
54
+ static const ALIGN32_BEG Type _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val }
55
+
56
+ _PS256_CONST(1 , 1.0f);
57
+ _PS256_CONST(0p5, 0.5f);
58
+ /* the smallest non denormalized float number */
59
+ _PS256_CONST_TYPE(min_norm_pos, int, 0x00800000);
60
+ _PS256_CONST_TYPE(mant_mask, int, 0x7f800000);
61
+ _PS256_CONST_TYPE(inv_mant_mask, int, ~0x7f800000);
62
+
63
+ _PS256_CONST_TYPE(sign_mask, int, (int)0x80000000);
64
+ _PS256_CONST_TYPE(inv_sign_mask, int, ~0x80000000);
65
+
66
+ _PI32_CONST256(0, 0);
67
+ _PI32_CONST256(1, 1);
68
+ _PI32_CONST256(inv1, ~1);
69
+ _PI32_CONST256(2, 2);
70
+ _PI32_CONST256(4, 4);
71
+ _PI32_CONST256(0x7f, 0x7f);
72
+
73
+ _PS256_CONST(cephes_SQRTHF, 0.707106781186547524);
74
+ _PS256_CONST(cephes_log_p0, 7.0376836292E-2);
75
+ _PS256_CONST(cephes_log_p1, - 1.1514610310E-1);
76
+ _PS256_CONST(cephes_log_p2, 1.1676998740E-1);
77
+ _PS256_CONST(cephes_log_p3, - 1.2420140846E-1);
78
+ _PS256_CONST(cephes_log_p4, + 1.4249322787E-1);
79
+ _PS256_CONST(cephes_log_p5, - 1.6668057665E-1);
80
+ _PS256_CONST(cephes_log_p6, + 2.0000714765E-1);
81
+ _PS256_CONST(cephes_log_p7, - 2.4999993993E-1);
82
+ _PS256_CONST(cephes_log_p8, + 3.3333331174E-1);
83
+ _PS256_CONST(cephes_log_q1, -2.12194440e-4);
84
+ _PS256_CONST(cephes_log_q2, 0.693359375);
85
+
86
+
87
+ /* natural logarithm computed for 8 simultaneous float
88
+ return NaN for x <= 0
89
+ */
90
+ inline v8sf log256_ps(v8sf x) {
91
+ v8si imm0;
92
+ v8sf one = *(v8sf*)_ps256_1;
93
+
94
+ //v8sf invalid_mask = _mm256_cmple_ps(x, _mm256_setzero_ps());
95
+ v8sf invalid_mask = _mm256_cmp_ps(x, _mm256_setzero_ps(), _CMP_LE_OS);
96
+
97
+ x = _mm256_max_ps(x, *(v8sf*)_ps256_min_norm_pos); /* cut off denormalized stuff */
98
+
99
+ // can be done with AVX2
100
+ imm0 = _mm256_srli_epi32(_mm256_castps_si256(x), 23);
101
+
102
+ /* keep only the fractional part */
103
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_mant_mask);
104
+ x = _mm256_or_ps(x, *(v8sf*)_ps256_0p5);
105
+
106
+ // this is again another AVX2 instruction
107
+ imm0 = _mm256_sub_epi32(imm0, *(v8si*)_pi32_256_0x7f);
108
+ v8sf e = _mm256_cvtepi32_ps(imm0);
109
+
110
+ e = _mm256_add_ps(e, one);
111
+
112
+ /* part2:
113
+ if( x < SQRTHF ) {
114
+ e -= 1;
115
+ x = x + x - 1.0;
116
+ } else { x = x - 1.0; }
117
+ */
118
+ //v8sf mask = _mm256_cmplt_ps(x, *(v8sf*)_ps256_cephes_SQRTHF);
119
+ v8sf mask = _mm256_cmp_ps(x, *(v8sf*)_ps256_cephes_SQRTHF, _CMP_LT_OS);
120
+ v8sf tmp = _mm256_and_ps(x, mask);
121
+ x = _mm256_sub_ps(x, one);
122
+ e = _mm256_sub_ps(e, _mm256_and_ps(one, mask));
123
+ x = _mm256_add_ps(x, tmp);
124
+
125
+ v8sf z = _mm256_mul_ps(x,x);
126
+
127
+ v8sf y = *(v8sf*)_ps256_cephes_log_p0;
128
+ y = _mm256_mul_ps(y, x);
129
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p1);
130
+ y = _mm256_mul_ps(y, x);
131
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p2);
132
+ y = _mm256_mul_ps(y, x);
133
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p3);
134
+ y = _mm256_mul_ps(y, x);
135
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p4);
136
+ y = _mm256_mul_ps(y, x);
137
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p5);
138
+ y = _mm256_mul_ps(y, x);
139
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p6);
140
+ y = _mm256_mul_ps(y, x);
141
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p7);
142
+ y = _mm256_mul_ps(y, x);
143
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p8);
144
+ y = _mm256_mul_ps(y, x);
145
+
146
+ y = _mm256_mul_ps(y, z);
147
+
148
+ tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q1);
149
+ y = _mm256_add_ps(y, tmp);
150
+
151
+
152
+ tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
153
+ y = _mm256_sub_ps(y, tmp);
154
+
155
+ tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q2);
156
+ x = _mm256_add_ps(x, y);
157
+ x = _mm256_add_ps(x, tmp);
158
+ x = _mm256_or_ps(x, invalid_mask); // negative arg will be NAN
159
+ return x;
160
+ }
161
+
162
+ _PS256_CONST(exp_hi, 88.3762626647949f);
163
+ _PS256_CONST(exp_lo, -88.3762626647949f);
164
+
165
+ _PS256_CONST(cephes_LOG2EF, 1.44269504088896341);
166
+ _PS256_CONST(cephes_exp_C1, 0.693359375);
167
+ _PS256_CONST(cephes_exp_C2, -2.12194440e-4);
168
+
169
+ _PS256_CONST(cephes_exp_p0, 1.9875691500E-4);
170
+ _PS256_CONST(cephes_exp_p1, 1.3981999507E-3);
171
+ _PS256_CONST(cephes_exp_p2, 8.3334519073E-3);
172
+ _PS256_CONST(cephes_exp_p3, 4.1665795894E-2);
173
+ _PS256_CONST(cephes_exp_p4, 1.6666665459E-1);
174
+ _PS256_CONST(cephes_exp_p5, 5.0000001201E-1);
175
+
176
+ inline v8sf exp256_ps(v8sf x) {
177
+ v8sf tmp = _mm256_setzero_ps(), fx;
178
+ v8si imm0;
179
+ v8sf one = *(v8sf*)_ps256_1;
180
+
181
+ x = _mm256_min_ps(x, *(v8sf*)_ps256_exp_hi);
182
+ x = _mm256_max_ps(x, *(v8sf*)_ps256_exp_lo);
183
+
184
+ /* express exp(x) as exp(g + n*log(2)) */
185
+ fx = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_LOG2EF);
186
+ fx = _mm256_add_ps(fx, *(v8sf*)_ps256_0p5);
187
+
188
+ /* how to perform a floorf with SSE: just below */
189
+ //imm0 = _mm256_cvttps_epi32(fx);
190
+ //tmp = _mm256_cvtepi32_ps(imm0);
191
+
192
+ tmp = _mm256_floor_ps(fx);
193
+
194
+ /* if greater, subtract 1 */
195
+ //v8sf mask = _mm256_cmpgt_ps(tmp, fx);
196
+ v8sf mask = _mm256_cmp_ps(tmp, fx, _CMP_GT_OS);
197
+ mask = _mm256_and_ps(mask, one);
198
+ fx = _mm256_sub_ps(tmp, mask);
199
+
200
+ tmp = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C1);
201
+ v8sf z = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C2);
202
+ x = _mm256_sub_ps(x, tmp);
203
+ x = _mm256_sub_ps(x, z);
204
+
205
+ z = _mm256_mul_ps(x,x);
206
+
207
+ v8sf y = *(v8sf*)_ps256_cephes_exp_p0;
208
+ y = _mm256_mul_ps(y, x);
209
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p1);
210
+ y = _mm256_mul_ps(y, x);
211
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p2);
212
+ y = _mm256_mul_ps(y, x);
213
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p3);
214
+ y = _mm256_mul_ps(y, x);
215
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p4);
216
+ y = _mm256_mul_ps(y, x);
217
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p5);
218
+ y = _mm256_mul_ps(y, z);
219
+ y = _mm256_add_ps(y, x);
220
+ y = _mm256_add_ps(y, one);
221
+
222
+ /* build 2^n */
223
+ imm0 = _mm256_cvttps_epi32(fx);
224
+ // another two AVX2 instructions
225
+ imm0 = _mm256_add_epi32(imm0, *(v8si*)_pi32_256_0x7f);
226
+ imm0 = _mm256_slli_epi32(imm0, 23);
227
+ v8sf pow2n = _mm256_castsi256_ps(imm0);
228
+ y = _mm256_mul_ps(y, pow2n);
229
+ return y;
230
+ }
231
+
232
+ _PS256_CONST(minus_cephes_DP1, -0.78515625);
233
+ _PS256_CONST(minus_cephes_DP2, -2.4187564849853515625e-4);
234
+ _PS256_CONST(minus_cephes_DP3, -3.77489497744594108e-8);
235
+ _PS256_CONST(sincof_p0, -1.9515295891E-4);
236
+ _PS256_CONST(sincof_p1, 8.3321608736E-3);
237
+ _PS256_CONST(sincof_p2, -1.6666654611E-1);
238
+ _PS256_CONST(coscof_p0, 2.443315711809948E-005);
239
+ _PS256_CONST(coscof_p1, -1.388731625493765E-003);
240
+ _PS256_CONST(coscof_p2, 4.166664568298827E-002);
241
+ _PS256_CONST(cephes_FOPI, 1.27323954473516); // 4 / M_PI
242
+
243
+
244
+ /* evaluation of 8 sines at once using AVX intrinsics
245
+
246
+ The code is the exact rewriting of the cephes sinf function.
247
+ Precision is excellent as long as x < 8192 (I did not bother to
248
+ take into account the special handling they have for greater values
249
+ -- it does not return garbage for arguments over 8192, though, but
250
+ the extra precision is missing).
251
+
252
+ Note that it is such that sinf((float)M_PI) = 8.74e-8, which is the
253
+ surprising but correct result.
254
+
255
+ */
256
+ inline v8sf sin256_ps(v8sf x) { // any x
257
+ v8sf xmm1, xmm2 = _mm256_setzero_ps(), xmm3, sign_bit, y;
258
+ v8si imm0, imm2;
259
+
260
+ sign_bit = x;
261
+ /* take the absolute value */
262
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
263
+ /* extract the sign bit (upper one) */
264
+ sign_bit = _mm256_and_ps(sign_bit, *(v8sf*)_ps256_sign_mask);
265
+
266
+ /* scale by 4/Pi */
267
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
268
+
269
+ /*
270
+ Here we start a series of integer operations, which are in the
271
+ realm of AVX2.
272
+ If we don't have AVX, let's perform them using SSE2 directives
273
+ */
274
+
275
+ /* store the integer part of y in mm0 */
276
+ imm2 = _mm256_cvttps_epi32(y);
277
+ /* j=(j+1) & (~1) (see the cephes sources) */
278
+ // another two AVX2 instruction
279
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
280
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
281
+ y = _mm256_cvtepi32_ps(imm2);
282
+
283
+ /* get the swap sign flag */
284
+ imm0 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_4);
285
+ imm0 = _mm256_slli_epi32(imm0, 29);
286
+ /* get the polynom selection mask
287
+ there is one polynom for 0 <= x <= Pi/4
288
+ and another one for Pi/4<x<=Pi/2
289
+
290
+ Both branches will be computed.
291
+ */
292
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
293
+ imm2 = _mm256_cmpeq_epi32(imm2,*(v8si*)_pi32_256_0);
294
+
295
+ v8sf swap_sign_bit = _mm256_castsi256_ps(imm0);
296
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
297
+ sign_bit = _mm256_xor_ps(sign_bit, swap_sign_bit);
298
+
299
+ /* The magic pass: "Extended precision modular arithmetic"
300
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
301
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
302
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
303
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
304
+ xmm1 = _mm256_mul_ps(y, xmm1);
305
+ xmm2 = _mm256_mul_ps(y, xmm2);
306
+ xmm3 = _mm256_mul_ps(y, xmm3);
307
+ x = _mm256_add_ps(x, xmm1);
308
+ x = _mm256_add_ps(x, xmm2);
309
+ x = _mm256_add_ps(x, xmm3);
310
+
311
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
312
+ y = *(v8sf*)_ps256_coscof_p0;
313
+ v8sf z = _mm256_mul_ps(x,x);
314
+
315
+ y = _mm256_mul_ps(y, z);
316
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
317
+ y = _mm256_mul_ps(y, z);
318
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
319
+ y = _mm256_mul_ps(y, z);
320
+ y = _mm256_mul_ps(y, z);
321
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
322
+ y = _mm256_sub_ps(y, tmp);
323
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
324
+
325
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
326
+
327
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
328
+ y2 = _mm256_mul_ps(y2, z);
329
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
330
+ y2 = _mm256_mul_ps(y2, z);
331
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
332
+ y2 = _mm256_mul_ps(y2, z);
333
+ y2 = _mm256_mul_ps(y2, x);
334
+ y2 = _mm256_add_ps(y2, x);
335
+
336
+ /* select the correct result from the two polynoms */
337
+ xmm3 = poly_mask;
338
+ y2 = _mm256_and_ps(xmm3, y2); //, xmm3);
339
+ y = _mm256_andnot_ps(xmm3, y);
340
+ y = _mm256_add_ps(y,y2);
341
+ /* update the sign */
342
+ y = _mm256_xor_ps(y, sign_bit);
343
+
344
+ return y;
345
+ }
346
+
347
+ /* almost the same as sin_ps */
348
+ inline v8sf cos256_ps(v8sf x) { // any x
349
+ v8sf xmm1, xmm2 = _mm256_setzero_ps(), xmm3, y;
350
+ v8si imm0, imm2;
351
+
352
+ /* take the absolute value */
353
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
354
+
355
+ /* scale by 4/Pi */
356
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
357
+
358
+ /* store the integer part of y in mm0 */
359
+ imm2 = _mm256_cvttps_epi32(y);
360
+ /* j=(j+1) & (~1) (see the cephes sources) */
361
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
362
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
363
+ y = _mm256_cvtepi32_ps(imm2);
364
+ imm2 = _mm256_sub_epi32(imm2, *(v8si*)_pi32_256_2);
365
+
366
+ /* get the swap sign flag */
367
+ imm0 = _mm256_andnot_si256(imm2, *(v8si*)_pi32_256_4);
368
+ imm0 = _mm256_slli_epi32(imm0, 29);
369
+ /* get the polynom selection mask */
370
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
371
+ imm2 = _mm256_cmpeq_epi32(imm2, *(v8si*)_pi32_256_0);
372
+
373
+ v8sf sign_bit = _mm256_castsi256_ps(imm0);
374
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
375
+
376
+ /* The magic pass: "Extended precision modular arithmetic"
377
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
378
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
379
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
380
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
381
+ xmm1 = _mm256_mul_ps(y, xmm1);
382
+ xmm2 = _mm256_mul_ps(y, xmm2);
383
+ xmm3 = _mm256_mul_ps(y, xmm3);
384
+ x = _mm256_add_ps(x, xmm1);
385
+ x = _mm256_add_ps(x, xmm2);
386
+ x = _mm256_add_ps(x, xmm3);
387
+
388
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
389
+ y = *(v8sf*)_ps256_coscof_p0;
390
+ v8sf z = _mm256_mul_ps(x,x);
391
+
392
+ y = _mm256_mul_ps(y, z);
393
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
394
+ y = _mm256_mul_ps(y, z);
395
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
396
+ y = _mm256_mul_ps(y, z);
397
+ y = _mm256_mul_ps(y, z);
398
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
399
+ y = _mm256_sub_ps(y, tmp);
400
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
401
+
402
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
403
+
404
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
405
+ y2 = _mm256_mul_ps(y2, z);
406
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
407
+ y2 = _mm256_mul_ps(y2, z);
408
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
409
+ y2 = _mm256_mul_ps(y2, z);
410
+ y2 = _mm256_mul_ps(y2, x);
411
+ y2 = _mm256_add_ps(y2, x);
412
+
413
+ /* select the correct result from the two polynoms */
414
+ xmm3 = poly_mask;
415
+ y2 = _mm256_and_ps(xmm3, y2); //, xmm3);
416
+ y = _mm256_andnot_ps(xmm3, y);
417
+ y = _mm256_add_ps(y,y2);
418
+ /* update the sign */
419
+ y = _mm256_xor_ps(y, sign_bit);
420
+
421
+ return y;
422
+ }
423
+
424
+ /* since sin256_ps and cos256_ps are almost identical, sincos256_ps could replace both of them..
425
+ it is almost as fast, and gives you a free cosine with your sine */
426
+ inline void sincos256_ps(v8sf x, v8sf *s, v8sf *c) {
427
+
428
+ v8sf xmm1, xmm2, xmm3 = _mm256_setzero_ps(), sign_bit_sin, y;
429
+ v8si imm0, imm2, imm4;
430
+
431
+ sign_bit_sin = x;
432
+ /* take the absolute value */
433
+ x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask);
434
+ /* extract the sign bit (upper one) */
435
+ sign_bit_sin = _mm256_and_ps(sign_bit_sin, *(v8sf*)_ps256_sign_mask);
436
+
437
+ /* scale by 4/Pi */
438
+ y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI);
439
+
440
+ /* store the integer part of y in imm2 */
441
+ imm2 = _mm256_cvttps_epi32(y);
442
+
443
+ /* j=(j+1) & (~1) (see the cephes sources) */
444
+ imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1);
445
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1);
446
+
447
+ y = _mm256_cvtepi32_ps(imm2);
448
+ imm4 = imm2;
449
+
450
+ /* get the swap sign flag for the sine */
451
+ imm0 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_4);
452
+ imm0 = _mm256_slli_epi32(imm0, 29);
453
+ //v8sf swap_sign_bit_sin = _mm256_castsi256_ps(imm0);
454
+
455
+ /* get the polynom selection mask for the sine*/
456
+ imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_2);
457
+ imm2 = _mm256_cmpeq_epi32(imm2, *(v8si*)_pi32_256_0);
458
+ //v8sf poly_mask = _mm256_castsi256_ps(imm2);
459
+
460
+ v8sf swap_sign_bit_sin = _mm256_castsi256_ps(imm0);
461
+ v8sf poly_mask = _mm256_castsi256_ps(imm2);
462
+
463
+ /* The magic pass: "Extended precision modular arithmetic"
464
+ x = ((x - y * DP1) - y * DP2) - y * DP3; */
465
+ xmm1 = *(v8sf*)_ps256_minus_cephes_DP1;
466
+ xmm2 = *(v8sf*)_ps256_minus_cephes_DP2;
467
+ xmm3 = *(v8sf*)_ps256_minus_cephes_DP3;
468
+ xmm1 = _mm256_mul_ps(y, xmm1);
469
+ xmm2 = _mm256_mul_ps(y, xmm2);
470
+ xmm3 = _mm256_mul_ps(y, xmm3);
471
+ x = _mm256_add_ps(x, xmm1);
472
+ x = _mm256_add_ps(x, xmm2);
473
+ x = _mm256_add_ps(x, xmm3);
474
+
475
+ imm4 = _mm256_sub_epi32(imm4, *(v8si*)_pi32_256_2);
476
+ imm4 = _mm256_andnot_si256(imm4, *(v8si*)_pi32_256_4);
477
+ imm4 = _mm256_slli_epi32(imm4, 29);
478
+
479
+ v8sf sign_bit_cos = _mm256_castsi256_ps(imm4);
480
+
481
+ sign_bit_sin = _mm256_xor_ps(sign_bit_sin, swap_sign_bit_sin);
482
+
483
+ /* Evaluate the first polynom (0 <= x <= Pi/4) */
484
+ v8sf z = _mm256_mul_ps(x,x);
485
+ y = *(v8sf*)_ps256_coscof_p0;
486
+
487
+ y = _mm256_mul_ps(y, z);
488
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p1);
489
+ y = _mm256_mul_ps(y, z);
490
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_coscof_p2);
491
+ y = _mm256_mul_ps(y, z);
492
+ y = _mm256_mul_ps(y, z);
493
+ v8sf tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5);
494
+ y = _mm256_sub_ps(y, tmp);
495
+ y = _mm256_add_ps(y, *(v8sf*)_ps256_1);
496
+
497
+ /* Evaluate the second polynom (Pi/4 <= x <= 0) */
498
+
499
+ v8sf y2 = *(v8sf*)_ps256_sincof_p0;
500
+ y2 = _mm256_mul_ps(y2, z);
501
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p1);
502
+ y2 = _mm256_mul_ps(y2, z);
503
+ y2 = _mm256_add_ps(y2, *(v8sf*)_ps256_sincof_p2);
504
+ y2 = _mm256_mul_ps(y2, z);
505
+ y2 = _mm256_mul_ps(y2, x);
506
+ y2 = _mm256_add_ps(y2, x);
507
+
508
+ /* select the correct result from the two polynoms */
509
+ xmm3 = poly_mask;
510
+ v8sf ysin2 = _mm256_and_ps(xmm3, y2);
511
+ v8sf ysin1 = _mm256_andnot_ps(xmm3, y);
512
+ y2 = _mm256_sub_ps(y2,ysin2);
513
+ y = _mm256_sub_ps(y, ysin1);
514
+
515
+ xmm1 = _mm256_add_ps(ysin1,ysin2);
516
+ xmm2 = _mm256_add_ps(y,y2);
517
+
518
+ /* update the sign */
519
+ *s = _mm256_xor_ps(xmm1, sign_bit_sin);
520
+ *c = _mm256_xor_ps(xmm2, sign_bit_cos);
521
+ }
522
+
523
+ #endif // CPU_CAPABILITY_AVX2
524
+
525
+ #else
526
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
527
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/int_mm_kernel.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ using weight_to_int4pack_fn = void (*)(const Tensor&, const Tensor&);
10
+ using int4pack_mm_fn =
11
+ void (*)(const Tensor&, const Tensor&, const Tensor&, int, const Tensor&);
12
+ using int8pack_mm_fn =
13
+ void (*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&);
14
+ using dyn_quant_pack_4bit_weight_fn = void (*)(
15
+ Tensor&,
16
+ const Tensor&,
17
+ const Tensor&,
18
+ const std::optional<Tensor>& bias,
19
+ const int64_t,
20
+ const int64_t,
21
+ const int64_t);
22
+ using dyn_quant_matmul_4bit_fn = void (*)(
23
+ const Tensor&,
24
+ const Tensor&,
25
+ const Tensor&,
26
+ const int64_t,
27
+ const int64_t,
28
+ const int64_t,
29
+ const int64_t);
30
+
31
+ DECLARE_DISPATCH(weight_to_int4pack_fn, weight_to_int4pack_stub)
32
+ DECLARE_DISPATCH(int4pack_mm_fn, int4pack_mm_stub)
33
+ DECLARE_DISPATCH(int8pack_mm_fn, int8pack_mm_stub)
34
+ DECLARE_DISPATCH(
35
+ dyn_quant_pack_4bit_weight_fn,
36
+ dyn_quant_pack_4bit_weight_stub)
37
+ DECLARE_DISPATCH(dyn_quant_matmul_4bit_fn, dyn_quant_matmul_4bit_stub)
38
+
39
+ } // namespace at::native
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/mixed_data_type.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+
6
+ namespace at::native {
7
+
8
+ inline ScalarType first_type() {
9
+ return ScalarType::Undefined;
10
+ }
11
+
12
+ template <typename... Args>
13
+ inline ScalarType first_type(const Tensor& arg, const Args&... parameters) {
14
+ return arg.defined() ? arg.scalar_type() : first_type(parameters...);
15
+ }
16
+
17
+ template <typename... Args>
18
+ inline bool is_mixed_type(const Tensor& input, const Args&... parameters) {
19
+ const auto parameter_type = first_type(parameters...);
20
+ return ((parameter_type != ScalarType::Undefined) &&
21
+ (parameter_type != input.scalar_type()));
22
+ }
23
+
24
+ // currently on CPU, mixed data type is only supported
25
+ // when input is 'BFloat16' or 'Half' and parameters are 'Float'
26
+ inline void check_mixed_data_type(const Tensor& input) {
27
+ TORCH_CHECK(at::isReducedFloatingType(input.scalar_type()),
28
+ "mixed dtype (CPU): all inputs must share same datatype.");
29
+ }
30
+
31
+ template <typename... Args>
32
+ inline void check_mixed_data_type(const Tensor& input, const Tensor& parameter, const Args&... parameters) {
33
+ TORCH_CHECK(!parameter.defined() || parameter.scalar_type() == ScalarType::Float,
34
+ "mixed dtype (CPU): expect parameter to have scalar type of Float");
35
+ check_mixed_data_type(input, parameters...);
36
+ }
37
+
38
+ inline ScalarType param_scalar_type(const Tensor& t, bool is_mixed_type) {
39
+ return is_mixed_type ? ScalarType::Float : t.scalar_type();
40
+ }
41
+
42
+ } // namespace at::native
43
+
44
+ #else
45
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
46
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/moments_utils.h ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <cstring>
6
+ #include <utility>
7
+
8
+ #include <ATen/Parallel.h>
9
+ #include <ATen/OpMathType.h>
10
+ #include <ATen/cpu/vec/vec.h>
11
+ #include <ATen/native/cpu/utils.h>
12
+ #include <c10/util/irange.h>
13
+
14
+ namespace at::native {
15
+ inline namespace CPU_CAPABILITY {
16
+
17
+ template<typename T> using opmath_t = at::opmath_type<T>;
18
+
19
+ constexpr int64_t kChunkSize = 16;
20
+
21
+ template <typename T>
22
+ void AddMoments(
23
+ int64_t m0_add,
24
+ const T& m1_add,
25
+ const T& m2_add,
26
+ int64_t& m0,
27
+ T& m1,
28
+ T& m2) {
29
+ const int64_t n = m0 + m0_add;
30
+ const T c = n == 0 ? static_cast<T>(0) : static_cast<T>(m0_add) / static_cast<T>(n);
31
+ const T delta = m1_add - m1;
32
+ m1 += c * delta;
33
+ m2 += m2_add + delta * delta * c * static_cast<T>(m0);
34
+ m0 = n;
35
+ }
36
+
37
+ template <typename T>
38
+ C10_ALWAYS_INLINE void AddMomentsVec(
39
+ int64_t m0_add,
40
+ const vec::Vectorized<T>& m1_add,
41
+ const vec::Vectorized<T>& m2_add,
42
+ int64_t& m0,
43
+ vec::Vectorized<T>& m1,
44
+ vec::Vectorized<T>& m2) {
45
+ using Vec = vec::Vectorized<T>;
46
+ const int64_t n = m0 + m0_add;
47
+ const T c = n == 0 ? static_cast<T>(0) : static_cast<T>(m0_add) / static_cast<T>(n);
48
+ const Vec c_vec(c);
49
+ const Vec delta = m1_add - m1;
50
+ const Vec m2_tmp = m2 + m2_add;
51
+ const Vec c_vec_delta = c_vec * delta;
52
+ const Vec m0_delta = delta * Vec(static_cast<T>(m0));
53
+ m1 = m1 + c_vec_delta;
54
+ m2 = fmadd(m0_delta, c_vec_delta, m2_tmp);
55
+ m0 = n;
56
+ }
57
+
58
+ template <typename T>
59
+ inline std::enable_if_t<std::is_same_v<T, opmath_t<T>>, void>
60
+ UpdateMomentsVec(
61
+ int64_t m0,
62
+ const T* X_ptr,
63
+ const std::array<vec::Vectorized<opmath_t<T>>, kChunkSize>& c_vecs,
64
+ int64_t& m0_stk0,
65
+ vec::Vectorized<opmath_t<T>>& m1_stk0,
66
+ vec::Vectorized<opmath_t<T>>& m2_stk0) {
67
+ using Vec = vec::Vectorized<opmath_t<T>>;
68
+ Vec m1_vec(0);
69
+ Vec m2_vec(0);
70
+ for (const auto j : c10::irange(m0)) {
71
+ const Vec x_vec = Vec::loadu(X_ptr + j * Vec::size());
72
+ const Vec tmpVec = c_vecs[j];
73
+ const Vec delta_vec = x_vec - m1_vec;
74
+ m1_vec = fmadd(tmpVec, delta_vec, m1_vec);
75
+ const Vec tmpVec2 = x_vec - m1_vec;
76
+ m2_vec = fmadd(delta_vec, tmpVec2, m2_vec);
77
+ }
78
+ AddMomentsVec(m0, m1_vec, m2_vec, m0_stk0, m1_stk0, m2_stk0);
79
+ }
80
+
81
+ // each bfloat16/half vector will be converted to two float vectors,
82
+ // and accumulated successively on m1_stk0/m2_stk0.
83
+ template <typename T>
84
+ inline std::enable_if_t<!std::is_same_v<T, at::opmath_type<T>>, void>
85
+ UpdateMomentsVec(
86
+ int64_t m0,
87
+ const T* X_ptr,
88
+ const std::array<vec::Vectorized<at::opmath_type<T>>, kChunkSize>& c_vecs,
89
+ int64_t& m0_stk0,
90
+ vec::Vectorized<at::opmath_type<T>>& m1_stk0,
91
+ vec::Vectorized<at::opmath_type<T>>& m2_stk0) {
92
+ using Vec = vec::Vectorized<T>;
93
+ using fVec = vec::Vectorized<at::opmath_type<T>>;
94
+ fVec m1_fvec0(0), m1_fvec1(0);
95
+ fVec m2_fvec0(0), m2_fvec1(0);
96
+ for (const auto j : c10::irange(m0)) {
97
+ const Vec x_bvec = Vec::loadu(X_ptr + j * Vec::size());
98
+ const fVec tmpVec = c_vecs[j];
99
+ auto [x_fvec0, x_fvec1] = convert_to_float<T>(x_bvec);
100
+ const fVec delta_fvec0 = x_fvec0 - m1_fvec0;
101
+ const fVec delta_fvec1 = x_fvec1 - m1_fvec1;
102
+ m1_fvec0 = fmadd(delta_fvec0, tmpVec, m1_fvec0);
103
+ m1_fvec1 = fmadd(delta_fvec1, tmpVec, m1_fvec1);
104
+ const fVec delta_fvec2 = x_fvec0 - m1_fvec0;
105
+ const fVec delta_fvec3 = x_fvec1 - m1_fvec1;
106
+ m2_fvec0 = fmadd(delta_fvec0, delta_fvec2, m2_fvec0);
107
+ m2_fvec1 = fmadd(delta_fvec1, delta_fvec3, m2_fvec1);
108
+ }
109
+ AddMomentsVec(m0, m1_fvec0, m2_fvec0, m0_stk0, m1_stk0, m2_stk0);
110
+ AddMomentsVec(m0, m1_fvec1, m2_fvec1, m0_stk0, m1_stk0, m2_stk0);
111
+ }
112
+
113
+ // Compute rowwise moments by Welford algorithm and cascade sum to improve
114
+ // numerical stability.
115
+ // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
116
+ // https://en.wikipedia.org/wiki/Pairwise_summation
117
+ template <typename T, int64_t kMaxDepth>
118
+ std::pair<opmath_t<T>, opmath_t<T>> RowwiseMomentsImpl(const T* X, int64_t N, int64_t ddof = 0) {
119
+ using math_t = opmath_t<T>;
120
+
121
+ constexpr int64_t kVecSize = vec::Vectorized<T>::size();
122
+ constexpr int64_t kAccVecSize = vec::Vectorized<math_t>::size();
123
+ const int64_t n = N / kVecSize;
124
+ const int64_t m = divup(n, kChunkSize);
125
+ const int64_t depth = utils::CeilLog2(m);
126
+
127
+ using Vec = vec::Vectorized<math_t>;
128
+ const Vec kZeroVec(math_t(0));
129
+ std::array<int64_t, kMaxDepth> m0_stk = {{0}};
130
+ std::array<Vec, kMaxDepth> m1_stk;
131
+ m1_stk.fill(kZeroVec);
132
+ std::array<Vec, kMaxDepth> m2_stk;
133
+ m2_stk.fill(kZeroVec);
134
+
135
+ for (const auto i : c10::irange(m)) {
136
+ const T* X_ptr = X + i * kChunkSize * kVecSize;
137
+ const int64_t m0 = std::min(kChunkSize, n - i * kChunkSize);
138
+ static std::array<Vec, kChunkSize> c_vecs = ([]() {
139
+ std::array<Vec, kChunkSize> result;
140
+ for (const auto i : c10::irange(kChunkSize)) {
141
+ result[i] = Vec(math_t(1) / static_cast<math_t>(i + 1));
142
+ }
143
+ return result;
144
+ })();
145
+ UpdateMomentsVec(m0, X_ptr, c_vecs, m0_stk[0], m1_stk[0], m2_stk[0]);
146
+
147
+ int64_t mask = i + 1;
148
+ for (int64_t j = 1; j < depth && (mask & 1) == 0; ++j) {
149
+ AddMomentsVec(
150
+ m0_stk[j - 1],
151
+ m1_stk[j - 1],
152
+ m2_stk[j - 1],
153
+ m0_stk[j],
154
+ m1_stk[j],
155
+ m2_stk[j]);
156
+ m0_stk[j - 1] = 0;
157
+ m1_stk[j - 1] = kZeroVec;
158
+ m2_stk[j - 1] = kZeroVec;
159
+ mask >>= 1;
160
+ }
161
+ }
162
+ for (const auto i : c10::irange(1, depth)) {
163
+ AddMomentsVec(
164
+ m0_stk[i], m1_stk[i], m2_stk[i], m0_stk[0], m1_stk[0], m2_stk[0]);
165
+ }
166
+
167
+ std::array<math_t, kAccVecSize> m1_arr{};
168
+ std::array<math_t, kAccVecSize> m2_arr{};
169
+ m1_stk[0].store(m1_arr.data());
170
+ m2_stk[0].store(m2_arr.data());
171
+
172
+ int64_t m0 = 0;
173
+ math_t m1 = 0;
174
+ math_t m2 = 0;
175
+ for (int64_t i = n * kVecSize; i < N; ++i) {
176
+ math_t x = static_cast<math_t>(X[i]);
177
+ const math_t delta = x - m1;
178
+ ++m0;
179
+ m1 += delta / static_cast<math_t>(m0);
180
+ m2 += delta * (x - m1);
181
+ }
182
+ // for BFloat16, each vector in m1_arr/m2_arr holds 2*n accumulated result
183
+ int64_t m0_add = n * kVecSize / kAccVecSize;
184
+ for (const auto i : c10::irange(kAccVecSize)) {
185
+ AddMoments(m0_add, m1_arr[i], m2_arr[i], m0, m1, m2);
186
+ }
187
+
188
+ return std::make_pair(m1, m2 / static_cast<math_t>(N - ddof));
189
+ }
190
+
191
+ template <typename T>
192
+ std::pair<opmath_t<T>, opmath_t<T>> RowwiseMoments(const T* X, int64_t N, int64_t ddof = 0) {
193
+ using Vec = vec::Vectorized<T>;
194
+ constexpr int64_t kVecSize = Vec::size();
195
+ const int64_t n = N / kVecSize;
196
+ const int64_t m = divup(n, kChunkSize);
197
+ const int64_t depth = utils::CeilLog2(m);
198
+ if (depth <= 4) {
199
+ return RowwiseMomentsImpl<T, 4>(X, N, ddof);
200
+ } else if (depth <= 8) {
201
+ return RowwiseMomentsImpl<T, 8>(X, N, ddof);
202
+ } else if (depth <= 16) {
203
+ return RowwiseMomentsImpl<T, 16>(X, N, ddof);
204
+ } else if (depth <= 32) {
205
+ return RowwiseMomentsImpl<T, 32>(X, N, ddof);
206
+ } else {
207
+ return RowwiseMomentsImpl<T, 64>(X, N, ddof);
208
+ }
209
+ }
210
+
211
+ } // namespace CPU_CAPABILITY
212
+ } // namespace at::native
213
+
214
+ #else
215
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
216
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/utils.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/core/TensorAccessor.h>
6
+ #include <ATen/cpu/vec/vec.h>
7
+ #include <c10/util/llvmMathExtras.h>
8
+
9
+ #ifdef USE_FBGEMM
10
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi")
11
+ #include <fbgemm/Fbgemm.h>
12
+ C10_DIAGNOSTIC_POP()
13
+ #endif
14
+
15
+ namespace at::native {
16
+
17
+ template <typename T>
18
+ inline void _store(T* dst, at::vec::Vectorized<T> src) {
19
+ src.store(dst);
20
+ }
21
+
22
+ inline void _store(at::BFloat16* dst, at::vec::Vectorized<float> src) {
23
+ auto res = at::vec::convert_float_bfloat16(src, src);
24
+ res.store(dst, at::vec::Vectorized<float>::size());
25
+ }
26
+
27
+ inline void _store(at::Half* dst, at::vec::Vectorized<float> src) {
28
+ auto res = at::vec::convert_float_half(src, src);
29
+ res.store(dst, at::vec::Vectorized<float>::size());
30
+ }
31
+
32
+ inline namespace CPU_CAPABILITY {
33
+
34
+ template <typename T>
35
+ inline T data_index_init(T offset) {
36
+ return offset;
37
+ }
38
+
39
+ template <typename T, typename... Args>
40
+ inline T data_index_init(T offset, T& x, const T& X, Args&&... args) {
41
+ offset = data_index_init(offset, std::forward<Args>(args)...);
42
+ x = offset % X;
43
+ return offset / X;
44
+ }
45
+
46
+ inline bool data_index_step() {
47
+ return true;
48
+ }
49
+
50
+ template <typename T, typename... Args>
51
+ inline bool data_index_step(T& x, const T& X, Args&&... args) {
52
+ if (data_index_step(std::forward<Args>(args)...)) {
53
+ x = ((x + 1) == X) ? 0 : (x + 1);
54
+ return x == 0;
55
+ }
56
+ return false;
57
+ }
58
+
59
+ // Helper struct for bfloat16/float16 vectorization
60
+ // Useful when you need float as immediate dtype or accumulate dtype
61
+ using namespace vec;
62
+ struct Vec2 {
63
+ Vectorized<float> val0, val1;
64
+ Vec2(Vectorized<float> v0, Vectorized<float> v1) : val0(v0), val1(v1) {}
65
+ Vec2(float v) : val0(v), val1(v) {}
66
+ static Vec2 loadu(const BFloat16* ptr) {
67
+ auto [v0, v1] = convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr));
68
+ return {v0, v1};
69
+ }
70
+ static Vec2 loadu(const Half* ptr) {
71
+ auto [v0, v1] = convert_half_float(Vectorized<Half>::loadu(ptr));
72
+ return {v0, v1};
73
+ }
74
+ static Vec2 loadu(const float* ptr) {
75
+ return {Vectorized<float>::loadu(ptr), Vectorized<float>::loadu(ptr + Vectorized<float>::size())};
76
+ }
77
+ void store(BFloat16* ptr) const {
78
+ Vectorized<BFloat16> val = convert_float_bfloat16(val0, val1);
79
+ val.store(ptr);
80
+ }
81
+ void store(Half* ptr) const {
82
+ Vectorized<Half> val = convert_float_half(val0, val1);
83
+ val.store(ptr);
84
+ }
85
+ void store(float* ptr) const {
86
+ val0.store(ptr);
87
+ val1.store(ptr + Vectorized<float>::size());
88
+ }
89
+ };
90
+ inline Vec2 operator+(const Vec2& a, const Vec2& b) { return {a.val0 + b.val0, a.val1 + b.val1}; }
91
+ inline Vec2 operator*(const Vec2& a, const Vec2& b) { return {a.val0 * b.val0, a.val1 * b.val1}; }
92
+ inline Vec2 operator-(const Vec2& a, const Vec2& b) { return {a.val0 - b.val0, a.val1 - b.val1}; }
93
+ inline Vec2 operator/(const Vec2& a, const Vec2& b) { return {a.val0 / b.val0, a.val1 / b.val1}; }
94
+ inline Vec2 maximum(const Vec2& a, const Vec2& b) { return {vec::maximum(a.val0, b.val0), vec::maximum(a.val1, b.val1)}; }
95
+ inline Vec2 minimum(const Vec2& a, const Vec2& b) { return {vec::minimum(a.val0, b.val0), vec::minimum(a.val1, b.val1)}; }
96
+
97
+ template <typename scalar_t> struct VectorizedType { using type = Vectorized<scalar_t>; };
98
+ template <> struct VectorizedType<BFloat16> { using type = Vec2; };
99
+ template <> struct VectorizedType<Half> { using type = Vec2; };
100
+ template <typename scalar_t> using VecType = typename VectorizedType<scalar_t>::type;
101
+
102
+ // Helper for mixed data type parameter Vec::load
103
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const BFloat16* ptr) {
104
+ return convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr));
105
+ }
106
+
107
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const Half* ptr) {
108
+ return convert_half_float(Vectorized<Half>::loadu(ptr));
109
+ }
110
+
111
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const float* ptr) {
112
+ using Vec = Vectorized<float>;
113
+ return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size()));
114
+ }
115
+
116
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const BFloat16* ptr, int64_t count) {
117
+ return convert_bfloat16_float(Vectorized<BFloat16>::loadu(ptr, count));
118
+ }
119
+
120
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const Half* ptr, int64_t count) {
121
+ return convert_half_float(Vectorized<Half>::loadu(ptr, count));
122
+ }
123
+
124
+ inline std::tuple<Vectorized<float>, Vectorized<float>> load2f(const float* ptr, int64_t count) {
125
+ using Vec = Vectorized<float>;
126
+ if (count > Vec::size()) {
127
+ return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size(), count - Vec::size()));
128
+ } else {
129
+ return std::make_tuple(Vec::loadu(ptr, count), Vec(0));
130
+ }
131
+ }
132
+
133
+ } // namespace
134
+
135
+ namespace utils {
136
+
137
+ template <typename T>
138
+ T CeilLog2(const T& x) {
139
+ if (x <= 2) {
140
+ return 1;
141
+ }
142
+ // Last set bit is floor(log2(x)), floor + 1 is ceil
143
+ // except when x is an exact powers of 2, so subtract 1 first
144
+ return static_cast<T>(llvm::findLastSet(static_cast<uint64_t>(x) - 1)) + 1;
145
+ }
146
+
147
+ // matrix transpose:
148
+ // src has shape of M by N, with leading dimension of ld_src
149
+ // dst has shape of N by M, with leading dimension of ld_dst
150
+ template <typename T>
151
+ inline void transpose(int64_t M, int64_t N, const T* src, int64_t ld_src, T* dst, int64_t ld_dst) {
152
+ for (int64_t j = 0; j < N; j++) {
153
+ for (int64_t i = 0; i < M; i++) {
154
+ dst[j * ld_dst + i] = c10::load(&(src[i * ld_src + j]));
155
+ }
156
+ }
157
+ }
158
+
159
+ #ifdef USE_FBGEMM
160
+ template <>
161
+ inline void transpose<float>(int64_t M, int64_t N, const float* src, int64_t ld_src, float* dst, int64_t ld_dst) {
162
+ TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM.");
163
+ fbgemm::transpose_simd<float>(M, N, src, ld_src, dst, ld_dst);
164
+ }
165
+
166
+ template <>
167
+ inline void transpose<uint16_t>(int64_t M, int64_t N, const uint16_t* src, int64_t ld_src, uint16_t* dst, int64_t ld_dst) {
168
+ TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM.");
169
+ fbgemm::transpose_simd<uint16_t>(M, N, src, ld_src, dst, ld_dst);
170
+ }
171
+
172
+ template <>
173
+ inline void transpose<uint8_t>(int64_t M, int64_t N, const uint8_t* src, int64_t ld_src, uint8_t* dst, int64_t ld_dst) {
174
+ TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM.");
175
+ fbgemm::transpose_simd<uint8_t>(M, N, src, ld_src, dst, ld_dst);
176
+ }
177
+ #endif
178
+
179
+ template <typename index_t, typename F>
180
+ inline void parallel_sparse_csr(
181
+ const TensorAccessor<index_t, 1>& crow_acc,
182
+ const int64_t M,
183
+ const int64_t nnz,
184
+ const F& f) {
185
+ TORCH_CHECK(crow_acc.size(0) == M + 1);
186
+
187
+ // directly parallel on `M` may lead to load imbalance,
188
+ // statically determine thread partition here to average payload
189
+ // for each thread.
190
+ int num_threads = at::get_num_threads();
191
+ std::vector<int64_t> thread_splits(num_threads + 1, M);
192
+
193
+ int64_t thread_averge_payload = std::max((int64_t)1, divup(nnz, num_threads));
194
+
195
+ thread_splits[0] = 0;
196
+ int64_t sum = 0;
197
+ int64_t t = 1;
198
+ for (const auto m : c10::irange(M)) {
199
+ int64_t row_start = crow_acc[m];
200
+ int64_t row_end = crow_acc[m + 1];
201
+ sum += row_end - row_start;
202
+ if (sum > t * thread_averge_payload) {
203
+ thread_splits[t] = m;
204
+ t++;
205
+ }
206
+ }
207
+ // need to restore the last index,
208
+ // due to rounding error when calculating `thread_averge_payload`.
209
+ thread_splits[num_threads] = M;
210
+
211
+ at::parallel_for(0, num_threads, 1, [&](int64_t cbegin, int64_t cend) {
212
+ int tid = at::get_thread_num();
213
+ int64_t begin = thread_splits[tid];
214
+ int64_t end = thread_splits[tid + 1];
215
+ f(begin, end);
216
+ });
217
+ }
218
+
219
+ } // namespace utils
220
+
221
+ } // namespace at::native
222
+
223
+ #else
224
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
225
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cpu/zmath.h ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // Complex number math operations that act as no-ops for other dtypes.
5
+ #include <c10/util/complex.h>
6
+ #include <c10/util/MathConstants.h>
7
+ #include<ATen/NumericUtils.h>
8
+
9
+ namespace at::native {
10
+ inline namespace CPU_CAPABILITY {
11
+
12
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
13
+ inline VALUE_TYPE zabs (SCALAR_TYPE z) {
14
+ return z;
15
+ }
16
+
17
+ template<>
18
+ inline c10::complex<float> zabs <c10::complex<float>> (c10::complex<float> z) {
19
+ return c10::complex<float>(std::abs(z));
20
+ }
21
+
22
+ template<>
23
+ inline float zabs <c10::complex<float>, float> (c10::complex<float> z) {
24
+ return std::abs(z);
25
+ }
26
+
27
+ template<>
28
+ inline c10::complex<double> zabs <c10::complex<double>> (c10::complex<double> z) {
29
+ return c10::complex<double>(std::abs(z));
30
+ }
31
+
32
+ template<>
33
+ inline double zabs <c10::complex<double>, double> (c10::complex<double> z) {
34
+ return std::abs(z);
35
+ }
36
+
37
+ // This overload corresponds to non-complex dtypes.
38
+ // The function is consistent with its NumPy equivalent
39
+ // for non-complex dtypes where `pi` is returned for
40
+ // negative real numbers and `0` is returned for 0 or positive
41
+ // real numbers.
42
+ // Note: `nan` is propagated.
43
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
44
+ inline VALUE_TYPE angle_impl (SCALAR_TYPE z) {
45
+ if (at::_isnan(z)) {
46
+ return z;
47
+ }
48
+ return z < 0 ? c10::pi<double> : 0;
49
+ }
50
+
51
+ template<>
52
+ inline c10::complex<float> angle_impl <c10::complex<float>> (c10::complex<float> z) {
53
+ return c10::complex<float>(std::arg(z), 0.0);
54
+ }
55
+
56
+ template<>
57
+ inline float angle_impl <c10::complex<float>, float> (c10::complex<float> z) {
58
+ return std::arg(z);
59
+ }
60
+
61
+ template<>
62
+ inline c10::complex<double> angle_impl <c10::complex<double>> (c10::complex<double> z) {
63
+ return c10::complex<double>(std::arg(z), 0.0);
64
+ }
65
+
66
+ template<>
67
+ inline double angle_impl <c10::complex<double>, double> (c10::complex<double> z) {
68
+ return std::arg(z);
69
+ }
70
+
71
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
72
+ constexpr VALUE_TYPE real_impl (SCALAR_TYPE z) {
73
+ return z; //No-Op
74
+ }
75
+
76
+ template<>
77
+ constexpr c10::complex<float> real_impl <c10::complex<float>> (c10::complex<float> z) {
78
+ return c10::complex<float>(z.real(), 0.0);
79
+ }
80
+
81
+ template<>
82
+ constexpr float real_impl <c10::complex<float>, float> (c10::complex<float> z) {
83
+ return z.real();
84
+ }
85
+
86
+ template<>
87
+ constexpr c10::complex<double> real_impl <c10::complex<double>> (c10::complex<double> z) {
88
+ return c10::complex<double>(z.real(), 0.0);
89
+ }
90
+
91
+ template<>
92
+ constexpr double real_impl <c10::complex<double>, double> (c10::complex<double> z) {
93
+ return z.real();
94
+ }
95
+
96
+ template <typename SCALAR_TYPE, typename VALUE_TYPE=SCALAR_TYPE>
97
+ constexpr VALUE_TYPE imag_impl (SCALAR_TYPE /*z*/) {
98
+ return 0;
99
+ }
100
+
101
+ template<>
102
+ constexpr c10::complex<float> imag_impl <c10::complex<float>> (c10::complex<float> z) {
103
+ return c10::complex<float>(z.imag(), 0.0);
104
+ }
105
+
106
+ template<>
107
+ constexpr float imag_impl <c10::complex<float>, float> (c10::complex<float> z) {
108
+ return z.imag();
109
+ }
110
+
111
+ template<>
112
+ constexpr c10::complex<double> imag_impl <c10::complex<double>> (c10::complex<double> z) {
113
+ return c10::complex<double>(z.imag(), 0.0);
114
+ }
115
+
116
+ template<>
117
+ constexpr double imag_impl <c10::complex<double>, double> (c10::complex<double> z) {
118
+ return z.imag();
119
+ }
120
+
121
+ template <typename TYPE>
122
+ inline TYPE conj_impl (TYPE z) {
123
+ return z; //No-Op
124
+ }
125
+
126
+ template<>
127
+ inline c10::complex<at::Half> conj_impl <c10::complex<at::Half>> (c10::complex<at::Half> z) {
128
+ return c10::complex<at::Half>{z.real(), -z.imag()};
129
+ }
130
+
131
+ template<>
132
+ inline c10::complex<float> conj_impl <c10::complex<float>> (c10::complex<float> z) {
133
+ return c10::complex<float>(z.real(), -z.imag());
134
+ }
135
+
136
+ template<>
137
+ inline c10::complex<double> conj_impl <c10::complex<double>> (c10::complex<double> z) {
138
+ return c10::complex<double>(z.real(), -z.imag());
139
+ }
140
+
141
+ template <typename TYPE>
142
+ inline TYPE ceil_impl (TYPE z) {
143
+ return std::ceil(z);
144
+ }
145
+
146
+ template <>
147
+ inline c10::complex<float> ceil_impl (c10::complex<float> z) {
148
+ return c10::complex<float>(std::ceil(z.real()), std::ceil(z.imag()));
149
+ }
150
+
151
+ template <>
152
+ inline c10::complex<double> ceil_impl (c10::complex<double> z) {
153
+ return c10::complex<double>(std::ceil(z.real()), std::ceil(z.imag()));
154
+ }
155
+
156
+ template<typename T>
157
+ inline c10::complex<T> sgn_impl (c10::complex<T> z) {
158
+ if (z == c10::complex<T>(0, 0)) {
159
+ return c10::complex<T>(0, 0);
160
+ } else {
161
+ return z / zabs(z);
162
+ }
163
+ }
164
+
165
+ template <typename TYPE>
166
+ inline TYPE floor_impl (TYPE z) {
167
+ return std::floor(z);
168
+ }
169
+
170
+ template <>
171
+ inline c10::complex<float> floor_impl (c10::complex<float> z) {
172
+ return c10::complex<float>(std::floor(z.real()), std::floor(z.imag()));
173
+ }
174
+
175
+ template <>
176
+ inline c10::complex<double> floor_impl (c10::complex<double> z) {
177
+ return c10::complex<double>(std::floor(z.real()), std::floor(z.imag()));
178
+ }
179
+
180
+ template <typename TYPE>
181
+ inline TYPE round_impl (TYPE z) {
182
+ return std::nearbyint(z);
183
+ }
184
+
185
+ template <>
186
+ inline c10::complex<float> round_impl (c10::complex<float> z) {
187
+ return c10::complex<float>(std::nearbyint(z.real()), std::nearbyint(z.imag()));
188
+ }
189
+
190
+ template <>
191
+ inline c10::complex<double> round_impl (c10::complex<double> z) {
192
+ return c10::complex<double>(std::nearbyint(z.real()), std::nearbyint(z.imag()));
193
+ }
194
+
195
+ template <typename TYPE>
196
+ inline TYPE trunc_impl (TYPE z) {
197
+ return std::trunc(z);
198
+ }
199
+
200
+ template <>
201
+ inline c10::complex<float> trunc_impl (c10::complex<float> z) {
202
+ return c10::complex<float>(std::trunc(z.real()), std::trunc(z.imag()));
203
+ }
204
+
205
+ template <>
206
+ inline c10::complex<double> trunc_impl (c10::complex<double> z) {
207
+ return c10::complex<double>(std::trunc(z.real()), std::trunc(z.imag()));
208
+ }
209
+
210
+ template <typename TYPE, std::enable_if_t<!c10::is_complex<TYPE>::value, int> = 0>
211
+ inline TYPE max_impl (TYPE a, TYPE b) {
212
+ if (_isnan<TYPE>(a) || _isnan<TYPE>(b)) {
213
+ return std::numeric_limits<TYPE>::quiet_NaN();
214
+ } else {
215
+ return std::max(a, b);
216
+ }
217
+ }
218
+
219
+ template <typename TYPE, std::enable_if_t<c10::is_complex<TYPE>::value, int> = 0>
220
+ inline TYPE max_impl (TYPE a, TYPE b) {
221
+ if (_isnan<TYPE>(a)) {
222
+ return a;
223
+ } else if (_isnan<TYPE>(b)) {
224
+ return b;
225
+ } else {
226
+ return std::abs(a) > std::abs(b) ? a : b;
227
+ }
228
+ }
229
+
230
+ template <typename TYPE, std::enable_if_t<!c10::is_complex<TYPE>::value, int> = 0>
231
+ inline TYPE min_impl (TYPE a, TYPE b) {
232
+ if (_isnan<TYPE>(a) || _isnan<TYPE>(b)) {
233
+ return std::numeric_limits<TYPE>::quiet_NaN();
234
+ } else {
235
+ return std::min(a, b);
236
+ }
237
+ }
238
+
239
+ template <typename TYPE, std::enable_if_t<c10::is_complex<TYPE>::value, int> = 0>
240
+ inline TYPE min_impl (TYPE a, TYPE b) {
241
+ if (_isnan<TYPE>(a)) {
242
+ return a;
243
+ } else if (_isnan<TYPE>(b)) {
244
+ return b;
245
+ } else {
246
+ return std::abs(a) < std::abs(b) ? a : b;
247
+ }
248
+ }
249
+
250
+ } // end namespace
251
+ } //end at::native
252
+
253
+ #else
254
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
255
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Activation.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/native/Activation.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ struct TensorIteratorBase;
8
+ class TensorBase;
9
+ }
10
+
11
+ namespace at::native {
12
+
13
+ void launch_glu_backward_kernel(const TensorIteratorBase& iter,
14
+ int64_t gI_stride, int64_t I_stride);
15
+
16
+ void launch_log_sigmoid_forward_kernel(TensorIteratorBase& iter);
17
+
18
+ void GeluCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate);
19
+ void GeluBackwardCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate);
20
+
21
+ } // namespace at::native
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/BinaryInternal.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // DON'T include this except from Binary*.cu files. It should not leak into
3
+ // headers.
4
+ #pragma once
5
+ #define TORCH_ASSERT_NO_OPERATORS
6
+ #include <ATen/AccumulateType.h>
7
+ #include <ATen/Dispatch.h>
8
+ #include <ATen/native/BinaryOps.h>
9
+ #include <ATen/native/DispatchStub.h>
10
+ #include <ATen/native/TensorIterator.h>
11
+ #include <c10/cuda/CUDAGuard.h>
12
+ #include <c10/cuda/CUDAMathCompat.h>
13
+ #include <c10/util/TypeSafeSignMath.h>
14
+ #include <ATen/native/cuda/JitLoops.cuh>
15
+ #include <ATen/native/cuda/Loops.cuh>
16
+
17
+ #include <type_traits>
18
+
19
+ namespace at::native::binary_internal {
20
+
21
+ template <typename scalar_t>
22
+ struct DivFunctor {
23
+ __device__ scalar_t operator()(scalar_t a, scalar_t b) const {
24
+ return a / b;
25
+ }
26
+ };
27
+
28
+ template <typename T>
29
+ struct MulFunctor {
30
+ __device__ T operator()(T a, T b) const {
31
+ return a * b;
32
+ }
33
+ };
34
+
35
+ // Workaround for the error: '*' in boolean context, suggest '&&' instead
36
+ // [-Werror=int-in-bool-context]
37
+ template <>
38
+ struct MulFunctor<bool> {
39
+ __device__ bool operator()(bool a, bool b) const {
40
+ return a && b;
41
+ }
42
+ };
43
+ void div_true_kernel_cuda(TensorIteratorBase& iter);
44
+ void div_trunc_kernel_cuda(TensorIteratorBase& iter);
45
+ } // namespace at::native::binary_internal
46
+
47
+ #else
48
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
49
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CUDAJitLoops.cuh ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/jit_macros.h>
4
+
5
+ // Jiterator functions are guarded behind this macro
6
+ #if AT_USE_JITERATOR()
7
+
8
+ #include <ATen/OpMathType.h>
9
+ #include <ATen/TensorIterator.h>
10
+ #include <ATen/cuda/CUDAContext.h>
11
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
12
+ #include <ATen/native/cuda/jit_utils.h>
13
+ #include <ATen/native/cuda/MemoryAccess.cuh>
14
+ #include <ATen/native/cuda/thread_constants.h>
15
+
16
+ #include <ATen/native/cuda/Loops.cuh>
17
+
18
+ #include <c10/macros/Macros.h>
19
+ #include <c10/core/ScalarType.h>
20
+ #include <c10/util/SmallBuffer.h>
21
+
22
+ #include <array>
23
+ #include <initializer_list>
24
+ #include <type_traits>
25
+ #include <tuple>
26
+ #include <mutex>
27
+
28
+ namespace at::native {
29
+
30
+ template <typename Tuple, std::size_t... I>
31
+ // warning : unused parameter when tuple is empty.
32
+ constexpr auto tuple_to_array_helper(const Tuple& t [[maybe_unused]], std::index_sequence<I...> seq) {
33
+ constexpr auto size = seq.size();
34
+ return std::array<const void*, size>{static_cast<const void*>(&std::get<I>(t))...};
35
+ }
36
+
37
+ // Helper function convert tuple to std::array<const void*, N>
38
+ // for passing the arguments to CUDA Kernel
39
+ // NOTE: We capture tuple by reference,
40
+ // so the pointers in returned array are only valid
41
+ // till tuple is alive.
42
+ template <typename ...Args>
43
+ constexpr auto tuple_to_array(const std::tuple<Args...>& extra_args) {
44
+ constexpr auto tuple_size = sizeof...(Args);
45
+ return tuple_to_array_helper(extra_args, std::make_index_sequence<tuple_size>{});
46
+ }
47
+
48
+ struct JittedVecKernelCache {
49
+ // Different kernels are compiled depending on what we're vectorizing up to (1, 2 or 4 elements)
50
+ at::cuda::jit::NvrtcFunction vec1;
51
+ at::cuda::jit::NvrtcFunction vec2;
52
+ at::cuda::jit::NvrtcFunction vec4;
53
+ at::cuda::jit::NvrtcFunction vec8;
54
+ #ifdef USE_ROCM
55
+ at::cuda::jit::NvrtcFunction vec16;
56
+ #endif
57
+
58
+ };
59
+
60
+ struct JittedKernelVariantCache {
61
+ JittedVecKernelCache vec;
62
+ at::cuda::jit::NvrtcFunction noncontiguous;
63
+ at::cuda::jit::NvrtcFunction dynamic_contiguous;
64
+ at::cuda::jit::NvrtcFunction dynamic_noncontiguous;
65
+ };
66
+
67
+ inline c10::SmallBuffer<const void*, 64> pack_kernel_args(
68
+ std::initializer_list<const void*> args,
69
+ c10::ArrayRef<const void*> extra_args) {
70
+ c10::SmallBuffer<const void*, 64> ret(args.size() + extra_args.size());
71
+ std::copy(args.begin(), args.end(), ret.data());
72
+ std::copy(extra_args.begin(), extra_args.end(), ret.data() + args.size());
73
+ return ret;
74
+ }
75
+
76
+ template<typename array_t,
77
+ typename inp_calc_t,
78
+ typename out_calc_t,
79
+ typename loader_t,
80
+ typename storer_t>
81
+ void launch_jitted_unrolled_kernel(
82
+ std::mutex &jiterator_mutex,
83
+ at::cuda::jit::NvrtcFunction &fn_cache,
84
+ const at::cuda::jit::KernelDescriptor &desc,
85
+ int64_t N,
86
+ array_t data,
87
+ inp_calc_t ic,
88
+ out_calc_t oc,
89
+ loader_t l,
90
+ storer_t s,
91
+ bool contiguous,
92
+ at::cuda::jit::BinaryFuncVariant scalar_pos,
93
+ const void* scalar_val,
94
+ c10::ArrayRef<const void*> extra_args) {
95
+
96
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
97
+
98
+ int tws = at::cuda::jit::calc_thread_work_size(desc.nInputs, desc.nOutputs, desc.f_inputs_type, desc.result_type);
99
+ int bws = tws * num_threads();
100
+ //casting result to int is always safe, intermediate is int64 and won't overflow
101
+ const uint32_t grid = (N + bws - 1) / bws;
102
+
103
+ if (!fn_cache.function) {
104
+ const std::lock_guard<std::mutex> lock{jiterator_mutex};
105
+ if (!fn_cache.function) {
106
+ constexpr bool dynamic_casting = !std::is_same<decltype(l), memory::LoadWithoutCast>() ||
107
+ !std::is_same<decltype(s), memory::StoreWithoutCast>();
108
+ auto code = at::cuda::jit::generate_code(
109
+ desc, contiguous, dynamic_casting, scalar_pos, tws);
110
+ fn_cache = at::cuda::jit::jit_pwise_function(code, desc.name);
111
+ }
112
+ }
113
+
114
+ auto args = pack_kernel_args({&N, &data, &ic, &oc, &l, &s, scalar_val}, extra_args);
115
+ at::cuda::jit::launch_jitted_pwise_function(fn_cache, args.data(), {grid, 1u, 1u},
116
+ {num_threads(), 1u, 1u});
117
+ }
118
+
119
+ template<int arity, typename array_t>
120
+ void launch_jitted_vectorized_kernel(
121
+ std::mutex &jiterator_mutex, JittedVecKernelCache &fn_cache,
122
+ const at::cuda::jit::KernelDescriptor &desc, int64_t N, array_t data,
123
+ at::cuda::jit::BinaryFuncVariant scalar_pos,
124
+ const void *scalar_val, c10::ArrayRef<const void*> extra_args) {
125
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
126
+
127
+ int tws = at::cuda::jit::calc_thread_work_size(desc.nInputs, desc.nOutputs, desc.f_inputs_type, desc.result_type);
128
+ int bws = tws * num_threads();
129
+ // N is still int64_t for the computation, but it's always safe to cast result to int
130
+ const uint32_t grid = (N + bws - 1) / bws;
131
+
132
+ int vec_size = at::cuda::jit::can_vectorize_up_to(
133
+ desc, c10::ArrayRef<char*>(data.data(), data.size()));
134
+
135
+ #ifndef USE_ROCM
136
+ const auto input_size = c10::scalarTypeToTypeMeta(desc.f_inputs_type).itemsize();
137
+ const int optimal_vec_size = 16 / static_cast<int>(input_size);
138
+ vec_size = std::min<int>(optimal_vec_size, vec_size);
139
+ // Here we purposely omit vec8 for 1-byte data because of a bug in NVCC
140
+ // that causes some numerical mismatches with uint8 on sm80 and sm90.
141
+ // TODO: Revisit this after CUDA 12.8 update.
142
+ if (input_size < 2) {
143
+ vec_size = std::min<int>(vec_size, 4);
144
+ }
145
+ #endif
146
+
147
+ // Different kernels are compiled depending on what we're vectorizing up to (1, 2 or 4 elements)
148
+ // fn_ptr is set to the appropriate function based on the vec size and GPU used
149
+ at::cuda::jit::NvrtcFunction* fn_ptr = nullptr;
150
+
151
+ #ifdef USE_ROCM
152
+ if (vec_size == 16) {
153
+ fn_ptr = &fn_cache.vec16;
154
+ } else
155
+ #endif
156
+ if (vec_size == 8) {
157
+ fn_ptr = &fn_cache.vec8;
158
+ } else if (vec_size == 4) {
159
+ fn_ptr = &fn_cache.vec4;
160
+ } else if (vec_size == 2) {
161
+ fn_ptr = &fn_cache.vec2;
162
+ } else if (vec_size ==1) {
163
+ fn_ptr = &fn_cache.vec1;
164
+ } else {
165
+ TORCH_INTERNAL_ASSERT(false, "unexpected vec_size for jitter vectorized kernel");
166
+ }
167
+
168
+ bool vectorized = vec_size > 1;
169
+
170
+ if (!fn_ptr->function) {
171
+ const std::lock_guard<std::mutex> lock{jiterator_mutex};
172
+ if (!fn_ptr->function) { // cache miss!
173
+
174
+ // Generates program
175
+ auto code = at::cuda::jit::generate_code(
176
+ desc, /*contiguous=*/true, /*dynamic_casting=*/false,
177
+ scalar_pos, tws, vectorized, vec_size);
178
+ std::string kernel_name = vectorized ? desc.name + "_vectorized" + std::to_string(vec_size) : desc.name;
179
+
180
+ // Acquires the program
181
+ *fn_ptr = at::cuda::jit::jit_pwise_function(code, kernel_name);
182
+ }
183
+ }
184
+
185
+ if (vectorized) {
186
+ auto args = pack_kernel_args({&N, &data, scalar_val}, extra_args);
187
+ at::cuda::jit::launch_jitted_pwise_function(
188
+ *fn_ptr, args.data(), {grid, 1u, 1u}, {num_threads(), 1u, 1u});
189
+ } else {
190
+ // NVCC complains about unused variables l and s.
191
+ // It should be false positive in most cases, so we suppress the warnings.
192
+ #pragma nv_diagnostic push
193
+ #pragma nv_diag_suppress 177
194
+ auto ic = TrivialOffsetCalculator<arity>();
195
+ auto oc = TrivialOffsetCalculator<1>();
196
+ auto l = memory::LoadWithoutCast();
197
+ auto s = memory::StoreWithoutCast();
198
+
199
+ auto args = pack_kernel_args(
200
+ {&N, &data, &ic, &oc, &l, &s, scalar_val}, extra_args);
201
+ at::cuda::jit::launch_jitted_pwise_function(
202
+ *fn_ptr, args.data(), {grid, 1u, 1u}, {num_threads(), 1u, 1u});
203
+ #pragma nv_diagnostic pop
204
+ }
205
+ }
206
+
207
+ template <int arity>
208
+ void jitted_gpu_kernel_generic(
209
+ std::mutex &jiterator_mutex,
210
+ JittedKernelVariantCache &cache,
211
+ const at::cuda::jit::KernelDescriptor &desc,
212
+ at::cuda::jit::BinaryFuncVariant scalar_pos,
213
+ c10::ArrayRef<const void*> extra_args,
214
+ TensorIteratorBase& iter,
215
+ const bool dynamic_casting,
216
+ const void *scalar_val) {
217
+ TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
218
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == arity);
219
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
220
+
221
+ constexpr int ntensors = arity + 1;
222
+ std::array<char*, ntensors> data;
223
+ for (auto i : c10::irange(ntensors)) {
224
+ data[i] = (char*)iter.data_ptr(i);
225
+ }
226
+
227
+ int64_t numel = iter.numel();
228
+ bool contiguous = iter.is_contiguous();
229
+
230
+ // Decides which of 4 kernel types to launch
231
+ // Variations are:
232
+ // - Case 1: no dynamic casting and contiguous
233
+ // - Case 2: no dynamic casting and noncontiguous
234
+ // - Case 3: dynamic casting and contiguous
235
+ // - Case 4: dynamic casting and noncontiguous
236
+ // These cases align with the non-jitted CUDALoops.cuh cases in gpu_kernel_impl
237
+
238
+ if (!dynamic_casting) {
239
+ if (contiguous) {
240
+ // Case 1: no dynamic casting and contiguous
241
+ launch_jitted_vectorized_kernel<arity>(
242
+ jiterator_mutex, cache.vec, desc,
243
+ numel, data, scalar_pos, scalar_val, extra_args);
244
+ return;
245
+ }
246
+
247
+ // Case 2: no dynamic casting and noncontiguous
248
+ auto input_offset_calculator = make_input_offset_calculator<arity>(iter);
249
+ auto output_offset_calculator = make_output_offset_calculator(iter);
250
+ auto loader = memory::LoadWithoutCast();
251
+ auto storer = memory::StoreWithoutCast();
252
+ launch_jitted_unrolled_kernel(
253
+ jiterator_mutex, cache.noncontiguous, desc, numel, data,
254
+ input_offset_calculator, output_offset_calculator, loader,
255
+ storer, contiguous, scalar_pos, scalar_val, extra_args);
256
+ return;
257
+ }
258
+
259
+ // Cases 3 and 4 are handled below
260
+ // Both require construction of a storer (this asserts 1 output) and one or more loaders
261
+
262
+ // Creates store cast to output (the zeroth tensor in TensorIterator)
263
+ auto storer = memory::StoreWithCast<1>(iter);
264
+
265
+ // Creates load casts from inputs (note offset indexing into the iterators 1...n tensors)
266
+ auto loader = memory::LoadWithCast<arity>(iter);
267
+
268
+ if (contiguous) {
269
+ // Case 3: dynamic casting and contiguous
270
+ auto input_offset_calculator = TrivialOffsetCalculator<arity>();
271
+ auto output_offset_calculator = TrivialOffsetCalculator<1>();
272
+ launch_jitted_unrolled_kernel(
273
+ jiterator_mutex, cache.dynamic_contiguous, desc, numel, data, input_offset_calculator,
274
+ output_offset_calculator, loader, storer, contiguous, scalar_pos, scalar_val, extra_args);
275
+ return;
276
+ }
277
+
278
+ // Case 4: dynamic casting and noncontiguous
279
+ auto input_offset_calculator = make_input_offset_calculator<arity>(iter);
280
+ auto output_offset_calculator = make_output_offset_calculator(iter);
281
+ launch_jitted_unrolled_kernel(
282
+ jiterator_mutex, cache.dynamic_noncontiguous, desc, numel, data, input_offset_calculator,
283
+ output_offset_calculator, loader, storer, contiguous, scalar_pos, scalar_val, extra_args);
284
+ }
285
+
286
+ // NOTE: static to reduce chances of name collision.
287
+ template <
288
+ char const* name,
289
+ typename result_type,
290
+ typename f_inputs_type,
291
+ int arity,
292
+ at::cuda::jit::BinaryFuncVariant scalar_pos =
293
+ at::cuda::jit::BinaryFuncVariant::NoScalar,
294
+ typename... ExtraArgs>
295
+ static void jitted_gpu_kernel_impl(
296
+ TensorIteratorBase& iter,
297
+ const std::string &f,
298
+ const bool dynamic_casting,
299
+ at::opmath_type<f_inputs_type> scalar_val,
300
+ const std::tuple<ExtraArgs...>& extra_args) {
301
+
302
+ // TODO: Memory use can probably be optimized by reusing kernels across GPUs with
303
+ // the same compute capability
304
+ static std::mutex jiterator_mutex;
305
+ static std::vector<JittedKernelVariantCache> device_caches(c10::cuda::device_count());
306
+
307
+ constexpr int nInputs = arity;
308
+ constexpr int nOutputs = 1; // TODO: Support more than 1 output
309
+ static const auto desc = at::cuda::jit::make_kernel_descriptor<
310
+ result_type, f_inputs_type, ExtraArgs...>(name, f, nInputs, nOutputs);
311
+
312
+ auto &cache = device_caches[iter.device().index()];
313
+ auto extra_args_array = tuple_to_array(extra_args);
314
+ return jitted_gpu_kernel_generic<arity>(
315
+ jiterator_mutex,
316
+ cache,
317
+ desc,
318
+ scalar_pos,
319
+ extra_args_array,
320
+ iter,
321
+ dynamic_casting,
322
+ &scalar_val
323
+ );
324
+ }
325
+
326
+ } // at::native
327
+
328
+ #endif // AT_USE_JITERATOR()
329
+
330
+ #else
331
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
332
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CUDALoops.cuh ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // This file provides two functions to help write GPU elementwise kernels:
5
+ //
6
+ // gpu_kernel(TensorIterator iter, <lambda>)
7
+ // gpu_kernel_with_scalars(TensorIterator iter, <lambda>)
8
+ //
9
+ // The gpu_kernel_with_scalars generates specializations that support a
10
+ // single scalar CPU argument, such as from `cuda_tensor + 5`. The CPU scalar
11
+ // is lifted to a kernel parameter instead of copying to device memory.
12
+ // This should be used in conjunction with TensorIterator::allow_cpu_scalars_,
13
+ // which is the default for TensorIterator::binary_op. Otherwise, all inputs
14
+ // and the output must be on the GPU.
15
+ //
16
+ // For example, to write a reciprocal kernel for GPU float Tensors:
17
+ //
18
+ // gpu_kernel(iter, []GPU_LAMBDA(float a) {
19
+ // return 1.0f / a;
20
+ // });
21
+ //
22
+ // To write a multiplication kernel for GPU float Tensors where one argument
23
+ // may be a CPU scalar:
24
+ //
25
+ // gpu_kernel_with_scalars(iter, []GPU_LAMBDA(float a, float b) {
26
+ // return a * b;
27
+ // });
28
+ //
29
+ // See BinaryOpsKernel.cu for the complete implementation
30
+ //
31
+
32
+ #include <array>
33
+ #include <tuple>
34
+ #include <type_traits>
35
+
36
+ #include <ATen/cuda/CUDAContext.h>
37
+ #include <ATen/detail/FunctionTraits.h>
38
+ #include <ATen/native/TensorIterator.h>
39
+ #include <c10/core/DynamicCast.h>
40
+ #include <c10/core/ScalarType.h>
41
+ #include <c10/macros/Macros.h>
42
+ #include <c10/util/TypeCast.h>
43
+
44
+ #ifdef __NVCC__
45
+ #define ASSERT_HOST_DEVICE_LAMBDA(type) \
46
+ static_assert( \
47
+ __nv_is_extended_host_device_lambda_closure_type(type), \
48
+ #type " must be a __host__ __device__ lambda")
49
+ #else
50
+ #define ASSERT_HOST_DEVICE_LAMBDA(type)
51
+ #endif
52
+
53
+ namespace at::native {
54
+
55
+ #ifdef USE_ROCM
56
+ // Custom configuration for vectorized elementwise kernel
57
+ // with template instantiation.
58
+ namespace vectorized_templated_config {
59
+ constexpr int num_threads() {
60
+ return 512;
61
+ }
62
+
63
+ constexpr int elems_per_thread() {
64
+ return 32;
65
+ }
66
+
67
+ constexpr int block_work_size() {
68
+ return elems_per_thread() * num_threads();
69
+ }
70
+ } // namespace vectorized_templated_config
71
+ #endif
72
+
73
+ template <typename args_t, size_t... Is>
74
+ constexpr auto sum_of_sizes(args_t args, std::index_sequence<Is...>) {
75
+ if constexpr (sizeof...(Is) == 0) {
76
+ return 0;
77
+ } else {
78
+ return (sizeof(std::tuple_element_t<Is, args_t>) + ...);
79
+ }
80
+ }
81
+
82
+ #ifdef USE_ROCM
83
+ template <int io_sizes>
84
+ constexpr auto elems_per_thread(){
85
+ if constexpr (io_sizes == 1) {
86
+ return 16;
87
+ } else if constexpr (io_sizes < 4) {
88
+ return 8;
89
+ } else {
90
+ return 4;
91
+ }
92
+ }
93
+ #else
94
+ template <int io_sizes>
95
+ constexpr auto elems_per_thread(){
96
+ if constexpr (io_sizes == 1) {
97
+ return 16;
98
+ } else {
99
+ return 8;
100
+ }
101
+ }
102
+ #endif
103
+
104
+
105
+ //thread work size of 8 regresses the perf of elementwise kernel on cuda
106
+ //this doesn't change ROCm behavior as thread_work_size is already 4 on ROCm
107
+ constexpr int elementwise_thread_work_size() {return 4;}
108
+ constexpr int elementwise_block_work_size() {
109
+ return elementwise_thread_work_size() * num_threads();
110
+ }
111
+
112
+ template <int io_sizes>
113
+ constexpr auto io_block_work_size() {
114
+ return num_threads() * elems_per_thread<io_sizes>();
115
+ }
116
+
117
+ #ifdef USE_ROCM
118
+ template <typename args_t, size_t... Is>
119
+ constexpr auto input_size(args_t args, std::index_sequence<Is...>) {
120
+ if constexpr (sizeof...(Is) == 0) {
121
+ return 0;
122
+ } else {
123
+ return sizeof(std::tuple_element_t<0, args_t>);
124
+ }
125
+ }
126
+
127
+ template <int vec_size, int io_size>
128
+ constexpr auto calc_optimal_vec_size() {
129
+ static_assert(vec_size != 0);
130
+ static_assert(io_size != 0);
131
+ if constexpr (io_size == 1 && vec_size >= 16) {
132
+ return 16;
133
+ } else if constexpr (io_size <= 2 && vec_size >= 8) {
134
+ return 8;
135
+ } else if constexpr (io_size <= 4 && vec_size >= 4) {
136
+ return 4;
137
+ } else if constexpr (vec_size >= 4) {
138
+ return 4;
139
+ } else if constexpr (vec_size >= 2) {
140
+ return 2;
141
+ } else {
142
+ return 1;
143
+ }
144
+ }
145
+ #endif
146
+
147
+ template <typename func_t>
148
+ constexpr auto calc_io_size(){
149
+ using traits = function_traits<func_t>;
150
+ using args_t = typename traits::ArgsTuple;
151
+ #ifdef USE_ROCM
152
+ constexpr auto input_size = at::native::input_size(args_t{}, std::make_index_sequence<std::tuple_size_v<args_t>>{});
153
+ constexpr auto output_size = sizeof(typename traits::result_type);
154
+ return (input_size > 0) ? ((input_size < output_size) ? input_size : output_size) : output_size;
155
+ #else
156
+ constexpr auto input_size = at::native::sum_of_sizes(args_t{}, std::make_index_sequence<std::tuple_size_v<args_t>>{});
157
+ constexpr auto output_size = sizeof(typename traits::result_type);
158
+ return input_size + output_size;
159
+ #endif
160
+ }
161
+
162
+ #ifndef USE_ROCM
163
+ // To save on binary size of libtorch_cuda.so, we split the vectorized_elementwise_kernel
164
+ // into two: one for vec_size=8 and one for vec_size=[2, 4], since vec8 is going to be
165
+ // used on sm_90 and sm_100 exclusively.
166
+ template <int vec_size, typename func_t, typename array_t>
167
+ C10_LAUNCH_BOUNDS_1(num_threads())
168
+ __global__ void vectorized_elementwise_kernel(int N, func_t f, array_t data) {
169
+ if constexpr (vec_size == 8) {
170
+ #if __CUDA_ARCH__ == 900 || __CUDA_ARCH__ == 1000
171
+ using traits = function_traits<func_t>;
172
+ constexpr auto io_size = calc_io_size<func_t>();
173
+ int remaining = N - io_block_work_size<io_size>() * blockIdx.x;
174
+
175
+ if (remaining < io_block_work_size<io_size>()) { // if this block handles the reminder,
176
+ // just do a naive unrolled loop
177
+ auto input_calc = TrivialOffsetCalculator<traits::arity>();
178
+ auto output_calc = TrivialOffsetCalculator<1>();
179
+ auto loader = memory::LoadWithoutCast();
180
+ auto storer = memory::StoreWithoutCast();
181
+ auto policy = memory::policies::unroll<
182
+ array_t,
183
+ decltype(input_calc),
184
+ decltype(output_calc),
185
+ memory::LoadWithoutCast,
186
+ memory::StoreWithoutCast,
187
+ elems_per_thread<io_size>()>(
188
+ data, remaining, input_calc, output_calc, loader, storer);
189
+ elementwise_kernel_helper(f, policy);
190
+ } else { // if this block has a full `block_work_size` data to handle, use
191
+ // vectorized memory access
192
+ elementwise_kernel_helper(
193
+ f, memory::policies::vectorized<vec_size, array_t, elems_per_thread<io_size>()>(data));
194
+ }
195
+ #endif // __CUDA_ARCH__ == 900 || __CUDA_ARCH__ == 1000
196
+ } else {
197
+ using traits = function_traits<func_t>;
198
+ constexpr auto io_size = calc_io_size<func_t>();
199
+ int remaining = N - io_block_work_size<io_size>() * blockIdx.x;
200
+
201
+ if (remaining < io_block_work_size<io_size>()) { // if this block handles the reminder,
202
+ // just do a naive unrolled loop
203
+ auto input_calc = TrivialOffsetCalculator<traits::arity>();
204
+ auto output_calc = TrivialOffsetCalculator<1>();
205
+ auto loader = memory::LoadWithoutCast();
206
+ auto storer = memory::StoreWithoutCast();
207
+ auto policy = memory::policies::unroll<
208
+ array_t,
209
+ decltype(input_calc),
210
+ decltype(output_calc),
211
+ memory::LoadWithoutCast,
212
+ memory::StoreWithoutCast,
213
+ elems_per_thread<io_size>()>(
214
+ data, remaining, input_calc, output_calc, loader, storer);
215
+ elementwise_kernel_helper(f, policy);
216
+ } else { // if this block has a full `block_work_size` data to handle, use
217
+ // vectorized memory access
218
+ elementwise_kernel_helper(
219
+ f, memory::policies::vectorized<vec_size, array_t, elems_per_thread<io_size>()>(data));
220
+ }
221
+ }
222
+ }
223
+
224
+ #else // USE_ROCM
225
+ template <int vec_size, typename func_t, typename array_t>
226
+ C10_LAUNCH_BOUNDS_1(num_threads())
227
+ __global__ void vectorized_elementwise_kernel(int N, func_t f, array_t data) {
228
+ using traits = function_traits<func_t>;
229
+ constexpr auto io_size = calc_io_size<func_t>();
230
+ #if defined(USE_ROCM) && defined(__gfx942__)
231
+ // Similar check in launch_vectorized_kernel() as well. Both should be in sync.
232
+ constexpr int tws = 16;
233
+ #else
234
+ constexpr int tws = elems_per_thread<io_size>();
235
+ #endif
236
+ constexpr int bws = tws * num_threads();
237
+ int remaining = N - bws * blockIdx.x;
238
+
239
+ if (remaining < bws) { // if this block handles the reminder,
240
+ // just do a naive unrolled loop
241
+ auto input_calc = TrivialOffsetCalculator<traits::arity>();
242
+ auto output_calc = TrivialOffsetCalculator<1>();
243
+ auto loader = memory::LoadWithoutCast();
244
+ auto storer = memory::StoreWithoutCast();
245
+ auto policy = memory::policies::unroll<
246
+ array_t,
247
+ decltype(input_calc),
248
+ decltype(output_calc),
249
+ memory::LoadWithoutCast,
250
+ memory::StoreWithoutCast,
251
+ tws>(
252
+ data, remaining, input_calc, output_calc, loader, storer);
253
+ elementwise_kernel_helper(f, policy);
254
+ } else { // if this block has a full `block_work_size` data to handle, use
255
+ // vectorized memory access
256
+ constexpr auto optimal_vec_size = calc_optimal_vec_size<vec_size, io_size>();
257
+ elementwise_kernel_helper(
258
+ f, memory::policies::vectorized<optimal_vec_size, array_t, tws>(data));
259
+ }
260
+ }
261
+ #endif // USE_ROCM
262
+
263
+ template <
264
+ typename func_t,
265
+ typename array_t,
266
+ int elems_per_thread,
267
+ typename inp_calc_t,
268
+ typename out_calc_t,
269
+ typename loader_t,
270
+ typename storer_t>
271
+ C10_LAUNCH_BOUNDS_1(num_threads())
272
+ __global__ void unrolled_elementwise_kernel(
273
+ int N,
274
+ func_t f,
275
+ array_t data,
276
+ inp_calc_t ic,
277
+ out_calc_t oc,
278
+ loader_t l,
279
+ storer_t s) {
280
+ int remaining = N - elems_per_thread * num_threads() * blockIdx.x;
281
+ auto policy = memory::policies::
282
+ unroll<array_t, inp_calc_t, out_calc_t, loader_t, storer_t, elems_per_thread>(
283
+ data, remaining, ic, oc, l, s);
284
+ elementwise_kernel_helper(f, policy);
285
+ }
286
+
287
+ // this function assume trivial 1d and no dynamic casting
288
+ template <typename func_t, typename array_t>
289
+ static inline void launch_vectorized_kernel(
290
+ int64_t N,
291
+ const func_t& f,
292
+ array_t data) {
293
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
294
+ using traits = function_traits<func_t>;
295
+ constexpr auto io_size = calc_io_size<func_t>();
296
+ auto stream = at::cuda::getCurrentCUDAStream();
297
+ #ifdef USE_ROCM
298
+ int vec_size = memory::can_vectorize_up_to<func_t>(data);
299
+ c10::DeviceIndex curDevice = -1;
300
+ AT_CUDA_CHECK(c10::cuda::GetDevice(&curDevice));
301
+ // Similar check in vectorized_elementwise_kernel() as well. Both should be in sync.
302
+ int tws = at::detail::getCUDAHooks().isGPUArch({"gfx942"}, curDevice) ? 16 : elems_per_thread<io_size>();
303
+ #else
304
+ using cpp_type = typename function_traits<func_t>::result_type;
305
+ const uint16_t max_vec_size = memory::can_vectorize_up_to<func_t>(data);
306
+ uint16_t vec_size = 16 / static_cast<uint16_t>(sizeof(cpp_type));
307
+ vec_size = std::min<uint16_t>(vec_size, max_vec_size);
308
+ // Here we purposely omit vec8 for 1-byte data because of a bug in NVCC
309
+ // that causes some numerical mismatches with uint8 on sm80 and sm90.
310
+ // TODO: Revisit this after CUDA 12.8 update.
311
+ cudaDeviceProp* p = at::cuda::getDeviceProperties(stream.device().index());
312
+ const int computeCapability = p->major * 10 + p->minor;
313
+ if (computeCapability != 90 && computeCapability != 100) {
314
+ vec_size = std::min<uint16_t>(vec_size, 4);
315
+ }
316
+ if constexpr (sizeof(cpp_type) < 2) {
317
+ vec_size = std::min<uint16_t>(vec_size, 4);
318
+ }
319
+ int tws = elems_per_thread<io_size>();
320
+ #endif
321
+ int bws = tws * num_threads();
322
+ int64_t grid = (N + bws - 1) / bws;
323
+ switch (vec_size) {
324
+ #ifdef USE_ROCM
325
+ case 16:
326
+ vectorized_elementwise_kernel<16, func_t, array_t>
327
+ <<<grid, num_threads(), 0, stream>>>(N, f, data);
328
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
329
+ break;
330
+ #endif
331
+ case 8:
332
+ vectorized_elementwise_kernel<8, func_t, array_t>
333
+ <<<grid, num_threads(), 0, stream>>>(N, f, data);
334
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
335
+ break;
336
+ case 4:
337
+ vectorized_elementwise_kernel<4, func_t, array_t>
338
+ <<<grid, num_threads(), 0, stream>>>(N, f, data);
339
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
340
+ break;
341
+ case 2:
342
+ vectorized_elementwise_kernel<2, func_t, array_t>
343
+ <<<grid, num_threads(), 0, stream>>>(N, f, data);
344
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
345
+ break;
346
+ case 1: {
347
+ auto input_calc = TrivialOffsetCalculator<traits::arity>();
348
+ auto output_calc = TrivialOffsetCalculator<1>();
349
+ auto loader = memory::LoadWithoutCast();
350
+ auto storer = memory::StoreWithoutCast();
351
+ int64_t grid_unrolled = (N + elementwise_block_work_size() - 1) / elementwise_block_work_size();
352
+ unrolled_elementwise_kernel<func_t, array_t, elementwise_thread_work_size()>
353
+ <<<grid_unrolled, num_threads(), 0, stream>>>(
354
+ N, f, data, input_calc, output_calc, loader, storer);
355
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
356
+ break;
357
+ }
358
+ default:
359
+ TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size");
360
+ }
361
+ }
362
+
363
+ #ifdef USE_ROCM
364
+ template <
365
+ int vec_size,
366
+ typename func_t,
367
+ typename array_t,
368
+ typename inp_calc_t,
369
+ typename out_calc_t,
370
+ typename loader_t,
371
+ typename storer_t,
372
+ typename OutputType,
373
+ typename... InputTypes>
374
+ C10_LAUNCH_BOUNDS_1(vectorized_templated_config::num_threads())
375
+ __global__ void vectorized_templated_elementwise_kernel(
376
+ int N,
377
+ func_t f,
378
+ array_t data,
379
+ inp_calc_t inp_calc,
380
+ out_calc_t out_calc,
381
+ loader_t loader,
382
+ storer_t storer) {
383
+ int remaining = N -
384
+ vectorized_templated_config::block_work_size() *
385
+ (gridDim.x - blockIdx.x - 1);
386
+ constexpr bool reverted_idx = true;
387
+
388
+ if (remaining <
389
+ vectorized_templated_config::block_work_size()) { // if this block handles
390
+ // the reminder,
391
+ // just do a naive unrolled loop
392
+ auto policy = memory::policies::unroll_base<
393
+ vectorized_templated_config::num_threads(),
394
+ array_t,
395
+ inp_calc_t,
396
+ out_calc_t,
397
+ loader_t,
398
+ storer_t,
399
+ vectorized_templated_config::elems_per_thread()>(
400
+ data, remaining, inp_calc, out_calc, loader, storer);
401
+ elementwise_kernel_helper<reverted_idx>(f, policy);
402
+ } else { // if this block has a full `block_work_size` data to handle, use
403
+ // vectorized memory access
404
+ auto policy = memory::policies::vectorized_templated<
405
+ vec_size,
406
+ array_t,
407
+ vectorized_templated_config::elems_per_thread(),
408
+ vectorized_templated_config::num_threads(),
409
+ OutputType,
410
+ InputTypes...>(data);
411
+ elementwise_kernel_helper<reverted_idx>(f, policy);
412
+ }
413
+ }
414
+
415
+ // This function assume trivial 1d and supports template specialization
416
+ // to avoid dynamic casting.
417
+ // Input vectorization size is based on runtime information, i.e.
418
+ // the actual data types of the input and output tensor and cannot
419
+ // be determined using the functor type, as in regular non-templated
420
+ // vectorized kernels. The caller is in charge of selecting the correct input
421
+ // vectorization length.
422
+ template <
423
+ typename func_t,
424
+ typename array_t,
425
+ typename inp_calc_t,
426
+ typename out_calc_t,
427
+ typename loader_t,
428
+ typename storer_t,
429
+ typename OutputType,
430
+ typename... InputTypes>
431
+ static inline void launch_vectorized_templated_kernel(
432
+ int64_t N,
433
+ const func_t& f,
434
+ array_t data,
435
+ inp_calc_t ic,
436
+ out_calc_t oc,
437
+ loader_t l,
438
+ storer_t s) {
439
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
440
+ int64_t grid = (N + vectorized_templated_config::block_work_size() - 1) /
441
+ vectorized_templated_config::block_work_size();
442
+ auto stream = at::cuda::getCurrentCUDAStream();
443
+ int vec_size = memory::can_vectorize_up_to<func_t>(data);
444
+ switch (vec_size) {
445
+ case 8:
446
+ vectorized_templated_elementwise_kernel<
447
+ 8,
448
+ func_t,
449
+ array_t,
450
+ inp_calc_t,
451
+ out_calc_t,
452
+ loader_t,
453
+ storer_t,
454
+ OutputType,
455
+ InputTypes...>
456
+ <<<grid, vectorized_templated_config::num_threads(), 0, stream>>>(
457
+ N, f, data, ic, oc, l, s);
458
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
459
+ break;
460
+ case 4:
461
+ vectorized_templated_elementwise_kernel<
462
+ 4,
463
+ func_t,
464
+ array_t,
465
+ inp_calc_t,
466
+ out_calc_t,
467
+ loader_t,
468
+ storer_t,
469
+ OutputType,
470
+ InputTypes...>
471
+ <<<grid, vectorized_templated_config::num_threads(), 0, stream>>>(
472
+ N, f, data, ic, oc, l, s);
473
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
474
+ break;
475
+ case 2:
476
+ vectorized_templated_elementwise_kernel<
477
+ 2,
478
+ func_t,
479
+ array_t,
480
+ inp_calc_t,
481
+ out_calc_t,
482
+ loader_t,
483
+ storer_t,
484
+ OutputType,
485
+ InputTypes...>
486
+ <<<grid, vectorized_templated_config::num_threads(), 0, stream>>>(
487
+ N, f, data, ic, oc, l, s);
488
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
489
+ break;
490
+ default:
491
+ // vector size 1 is not handled as part of vectorize_templated kernel
492
+ TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size");
493
+ }
494
+ }
495
+ #endif
496
+
497
+ template <
498
+ typename func_t,
499
+ typename array_t,
500
+ typename inp_calc_t,
501
+ typename out_calc_t,
502
+ typename loader_t,
503
+ typename storer_t>
504
+ static inline void launch_unrolled_kernel(
505
+ int64_t N,
506
+ const func_t& f,
507
+ array_t data,
508
+ inp_calc_t ic,
509
+ out_calc_t oc,
510
+ loader_t l,
511
+ storer_t s) {
512
+ TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
513
+
514
+ int64_t grid = (N + elementwise_block_work_size() - 1) / elementwise_block_work_size();
515
+ auto stream = at::cuda::getCurrentCUDAStream();
516
+ unrolled_elementwise_kernel<func_t, array_t, elementwise_thread_work_size()>
517
+ <<<grid, num_threads(), 0, stream>>>(N, f, data, ic, oc, l, s);
518
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
519
+ }
520
+
521
+ template <int nt, int vt, typename func_t>
522
+ C10_LAUNCH_BOUNDS_2(nt, 4)
523
+ __global__ void elementwise_kernel(int N, func_t f) {
524
+ int tid = threadIdx.x;
525
+ int nv = nt * vt;
526
+ int idx = nv * blockIdx.x + tid;
527
+ #pragma unroll
528
+ for (int i = 0; i < vt; i++) {
529
+ if (idx < N) {
530
+ f(idx);
531
+ idx += nt;
532
+ }
533
+ }
534
+ }
535
+
536
+ template <int nt, int vt, typename func_t>
537
+ static void launch_legacy_kernel(int64_t N, const func_t& f) {
538
+ TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits<int32_t>::max());
539
+ if (N == 0) {
540
+ return;
541
+ }
542
+ dim3 block(nt);
543
+ dim3 grid((N + block.x * vt - 1) / (block.x * vt));
544
+ auto stream = at::cuda::getCurrentCUDAStream();
545
+ elementwise_kernel<nt, vt, func_t><<<grid, block, 0, stream>>>(N, f);
546
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
547
+ }
548
+
549
+ #ifdef USE_ROCM
550
+ template <int nt, int vt, typename func_t>
551
+ C10_LAUNCH_BOUNDS_2(nt, 4)
552
+ __global__ void elementwise_kernel_manual_unroll(int N, func_t f) {
553
+ int tid = threadIdx.x;
554
+ constexpr int nv = nt * vt;
555
+ int idx = nv * blockIdx.x + tid;
556
+ if ((idx + nt*(vt-1)) < N) {
557
+ f(idx, true);
558
+ } else {
559
+ #pragma unroll
560
+ for (int i = 0; i < vt; i++) {
561
+ if (idx < N) {
562
+ f(idx, false);
563
+ idx += nt;
564
+ }
565
+ }
566
+ }
567
+ }
568
+
569
+ template <int nt, int vt, typename func_t>
570
+ static void launch_legacy_kernel_manual_unroll(int64_t N, const func_t& f) {
571
+ TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits<int32_t>::max());
572
+ if (N == 0) {
573
+ return;
574
+ }
575
+ dim3 block(nt);
576
+ dim3 grid((N + block.x * vt - 1) / (block.x * vt));
577
+ auto stream = at::cuda::getCurrentCUDAStream();
578
+ elementwise_kernel_manual_unroll<nt, vt, func_t><<<grid, block, 0, stream>>>(N, f);
579
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
580
+ }
581
+ #endif
582
+
583
+ template <typename traits, typename func_t, typename index_t, size_t... INDEX>
584
+ C10_HOST_DEVICE typename traits::result_type invoke_impl(
585
+ const func_t& f,
586
+ char* const C10_RESTRICT data[],
587
+ const index_t strides[],
588
+ int i,
589
+ std::index_sequence<INDEX...>) {
590
+ (void)strides;
591
+ (void)i;
592
+ return f(c10::load<typename traits::template arg<INDEX>::type>(
593
+ data[INDEX] + i * strides[INDEX])...);
594
+ }
595
+
596
+ template <
597
+ typename func_t,
598
+ typename index_t,
599
+ typename traits = function_traits<func_t>>
600
+ C10_HOST_DEVICE typename traits::result_type invoke(
601
+ const func_t& f,
602
+ char* const C10_RESTRICT data[],
603
+ const index_t strides[],
604
+ int i) {
605
+ using Indices = std::make_index_sequence<traits::arity>;
606
+ return invoke_impl<traits>(f, data, strides, i, Indices{});
607
+ }
608
+
609
+ template <typename traits, typename func_t, typename index_t, size_t... I>
610
+ C10_HOST_DEVICE typename traits::result_type invoke_impl(
611
+ const func_t& f,
612
+ char* const C10_RESTRICT data[],
613
+ const index_t strides[],
614
+ const ScalarType dtypes[],
615
+ int i,
616
+ std::index_sequence<I...>) {
617
+ (void)strides;
618
+ (void)i;
619
+ return f(c10::fetch_and_cast<typename traits::template arg<I>::type>(
620
+ dtypes[I], data[I] + i * strides[I])...);
621
+ }
622
+
623
+ template <
624
+ typename func_t,
625
+ typename index_t,
626
+ typename traits = function_traits<func_t>>
627
+ C10_HOST_DEVICE typename traits::result_type invoke(
628
+ const func_t& f,
629
+ char* const C10_RESTRICT data[],
630
+ const index_t strides[],
631
+ const ScalarType dtypes[],
632
+ int i) {
633
+ using Indices = std::make_index_sequence<traits::arity>;
634
+ return invoke_impl<traits>(f, data, strides, dtypes, i, Indices{});
635
+ }
636
+
637
+ template <typename func_t>
638
+ void gpu_kernel_impl_nocast(TensorIteratorBase& iter, const func_t& f) {
639
+ using traits = function_traits<func_t>;
640
+ using arg0_t = typename traits::result_type;
641
+ constexpr int ntensors = traits::arity + 1;
642
+
643
+ TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
644
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
645
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
646
+ TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
647
+
648
+ std::array<char*, ntensors> data;
649
+ for (int i = 0; i < ntensors; i++) {
650
+ data[i] = (char*)iter.data_ptr(i);
651
+ }
652
+
653
+ int64_t numel = iter.numel();
654
+
655
+ bool contiguous = iter.is_contiguous();
656
+
657
+ if (contiguous) {
658
+ return launch_vectorized_kernel(numel, f, data);
659
+ }
660
+ auto offset_calc = ::make_offset_calculator<traits::arity + 1>(iter);
661
+ #ifndef USE_ROCM
662
+ constexpr int unroll_factor = sizeof(arg0_t) >= 4 ? 2 : 4;
663
+ launch_legacy_kernel<128, unroll_factor>(numel, [=] GPU_LAMBDA(int idx) {
664
+ auto offsets = offset_calc.get(idx);
665
+ arg0_t* out = (arg0_t*)(data[0] + offsets[0]);
666
+ *out = invoke(f, &data[1], &offsets[1], 1);
667
+ });
668
+ #else
669
+ constexpr int unroll_factor = sizeof(arg0_t) >= 4 ? 4 : 8;
670
+ constexpr int grp_sz = 128;
671
+ launch_legacy_kernel_manual_unroll<grp_sz, unroll_factor>(numel, [=] GPU_LAMBDA(int idx, bool unrl) {
672
+ if (unrl) {
673
+ if constexpr (unroll_factor == 4) {
674
+ auto offsets0 = offset_calc.get(idx);
675
+ auto offsets1 = offset_calc.get(idx+grp_sz);
676
+ auto offsets2 = offset_calc.get(idx+grp_sz*2);
677
+ auto offsets3 = offset_calc.get(idx+grp_sz*3);
678
+ arg0_t* out0 = (arg0_t*)(data[0] + offsets0[0]);
679
+ arg0_t* out1 = (arg0_t*)(data[0] + offsets1[0]);
680
+ arg0_t* out2 = (arg0_t*)(data[0] + offsets2[0]);
681
+ arg0_t* out3 = (arg0_t*)(data[0] + offsets3[0]);
682
+ auto tmp0 = invoke(f, &data[1], &offsets0[1], 1);
683
+ auto tmp1 = invoke(f, &data[1], &offsets1[1], 1);
684
+ auto tmp2 = invoke(f, &data[1], &offsets2[1], 1);
685
+ auto tmp3 = invoke(f, &data[1], &offsets3[1], 1);
686
+ *out0 = tmp0;
687
+ *out1 = tmp1;
688
+ *out2 = tmp2;
689
+ *out3 = tmp3;
690
+ } else {
691
+ auto offsets0 = offset_calc.get(idx);
692
+ auto offsets1 = offset_calc.get(idx+grp_sz);
693
+ auto offsets2 = offset_calc.get(idx+grp_sz*2);
694
+ auto offsets3 = offset_calc.get(idx+grp_sz*3);
695
+ auto offsets4 = offset_calc.get(idx+grp_sz*4);
696
+ auto offsets5 = offset_calc.get(idx+grp_sz*5);
697
+ auto offsets6 = offset_calc.get(idx+grp_sz*6);
698
+ auto offsets7 = offset_calc.get(idx+grp_sz*7);
699
+ arg0_t* out0 = (arg0_t*)(data[0] + offsets0[0]);
700
+ arg0_t* out1 = (arg0_t*)(data[0] + offsets1[0]);
701
+ arg0_t* out2 = (arg0_t*)(data[0] + offsets2[0]);
702
+ arg0_t* out3 = (arg0_t*)(data[0] + offsets3[0]);
703
+ arg0_t* out4 = (arg0_t*)(data[0] + offsets4[0]);
704
+ arg0_t* out5 = (arg0_t*)(data[0] + offsets5[0]);
705
+ arg0_t* out6 = (arg0_t*)(data[0] + offsets6[0]);
706
+ arg0_t* out7 = (arg0_t*)(data[0] + offsets7[0]);
707
+ auto tmp0 = invoke(f, &data[1], &offsets0[1], 1);
708
+ auto tmp1 = invoke(f, &data[1], &offsets1[1], 1);
709
+ auto tmp2 = invoke(f, &data[1], &offsets2[1], 1);
710
+ auto tmp3 = invoke(f, &data[1], &offsets3[1], 1);
711
+ auto tmp4 = invoke(f, &data[1], &offsets4[1], 1);
712
+ auto tmp5 = invoke(f, &data[1], &offsets5[1], 1);
713
+ auto tmp6 = invoke(f, &data[1], &offsets6[1], 1);
714
+ auto tmp7 = invoke(f, &data[1], &offsets7[1], 1);
715
+ *out0 = tmp0;
716
+ *out1 = tmp1;
717
+ *out2 = tmp2;
718
+ *out3 = tmp3;
719
+ *out4 = tmp4;
720
+ *out5 = tmp5;
721
+ *out6 = tmp6;
722
+ *out7 = tmp7;
723
+ }
724
+ } else {
725
+ auto offsets = offset_calc.get(idx);
726
+ arg0_t* out = (arg0_t*)(data[0] + offsets[0]);
727
+ *out = invoke(f, &data[1], &offsets[1], 1);
728
+ }
729
+ });
730
+ #endif
731
+ }
732
+
733
+ #ifdef USE_ROCM
734
+ namespace {
735
+ template <
736
+ typename TupleLike,
737
+ typename FirstParamTy,
738
+ typename SecondParamTy,
739
+ size_t arity,
740
+ size_t arg_num = 0>
741
+ struct check_binary_functor_types_for_specialization {
742
+ constexpr static inline bool check() {
743
+ if constexpr (arity != 2)
744
+ return false;
745
+ if constexpr (arg_num == 0) {
746
+ using SelectedType = std::tuple_element_t<arg_num, TupleLike>;
747
+ if constexpr (std::is_same_v<FirstParamTy, SelectedType>)
748
+ return check_binary_functor_types_for_specialization<
749
+ TupleLike,
750
+ FirstParamTy,
751
+ SecondParamTy,
752
+ arity,
753
+ arg_num + 1>::check();
754
+ } else if constexpr (arg_num == 1) {
755
+ using SelectedType2 = std::tuple_element_t<arg_num, TupleLike>;
756
+ if constexpr (std::is_same_v<SecondParamTy, SelectedType2>)
757
+ return check_binary_functor_types_for_specialization<
758
+ TupleLike,
759
+ FirstParamTy,
760
+ SecondParamTy,
761
+ arity,
762
+ arg_num + 1>::check();
763
+ }
764
+ return false;
765
+ }
766
+ };
767
+
768
+ // Bottom case: if we got this far, assume correct type matching except
769
+ // when there are no arguments (arity == 0).
770
+ template <
771
+ typename TupleLike,
772
+ typename FirstParamTy,
773
+ typename SecondParamTy,
774
+ size_t arity>
775
+ struct check_binary_functor_types_for_specialization<
776
+ TupleLike,
777
+ FirstParamTy,
778
+ SecondParamTy,
779
+ arity,
780
+ arity> {
781
+ constexpr static inline bool check() {
782
+ if constexpr (arity != 0)
783
+ return true;
784
+ return false;
785
+ }
786
+ };
787
+
788
+ template <typename TupleLike, typename FirstParamTy, typename SecondParamTy>
789
+ struct check_binary_functor_types_for_specialization<
790
+ TupleLike,
791
+ FirstParamTy,
792
+ SecondParamTy,
793
+ 0,
794
+ 0> {
795
+ constexpr static inline bool check() {
796
+ return false;
797
+ }
798
+ };
799
+
800
+ // The following is a list of type specializations for vectorized_templated
801
+ // elementwise kernel. The three types refer to runtime types of the output
802
+ // tensor, first tensor argument, and the second tensor argument used for a
803
+ // binary functor.
804
+ constexpr std::array rt_binary_specializations = {
805
+ std::array<c10::ScalarType, 3>(
806
+ {c10::CppTypeToScalarType<float>::value,
807
+ c10::CppTypeToScalarType<float>::value,
808
+ c10::CppTypeToScalarType<BFloat16>::value}),
809
+ std::array<c10::ScalarType, 3>(
810
+ {c10::CppTypeToScalarType<float>::value,
811
+ c10::CppTypeToScalarType<BFloat16>::value,
812
+ c10::CppTypeToScalarType<float>::value}),
813
+ std::array<c10::ScalarType, 3>(
814
+ {c10::CppTypeToScalarType<BFloat16>::value,
815
+ c10::CppTypeToScalarType<BFloat16>::value,
816
+ c10::CppTypeToScalarType<float>::value}),
817
+ std::array<c10::ScalarType, 3>(
818
+ {c10::CppTypeToScalarType<float>::value,
819
+ c10::CppTypeToScalarType<float>::value,
820
+ c10::CppTypeToScalarType<Half>::value}),
821
+ std::array<c10::ScalarType, 3>(
822
+ {c10::CppTypeToScalarType<float>::value,
823
+ c10::CppTypeToScalarType<Half>::value,
824
+ c10::CppTypeToScalarType<float>::value}),
825
+ std::array<c10::ScalarType, 3>(
826
+ {c10::CppTypeToScalarType<Half>::value,
827
+ c10::CppTypeToScalarType<Half>::value,
828
+ c10::CppTypeToScalarType<float>::value})};
829
+
830
+ bool check_binary_rt_types_for_specialization(TensorIteratorBase& iter) {
831
+ if (iter.ninputs() != 2)
832
+ return false;
833
+ for (auto spec : rt_binary_specializations)
834
+ if (iter.dtype(0) == spec[0] && iter.input_dtype(0) == spec[1] &&
835
+ iter.input_dtype(1) == spec[2])
836
+ return true;
837
+ return false;
838
+ }
839
+
840
+ template <int arg_index>
841
+ struct type_specialized_kernel_launcher {
842
+ template <
843
+ typename func_t,
844
+ typename array_t,
845
+ typename inp_calc_t,
846
+ typename out_calc_t,
847
+ typename loader_t,
848
+ typename storer_t>
849
+ static void apply(
850
+ ScalarType ret_t,
851
+ ScalarType arg0_t,
852
+ ScalarType arg1_t,
853
+ int64_t numel,
854
+ func_t f,
855
+ array_t data,
856
+ inp_calc_t input_offset_calculator,
857
+ out_calc_t output_offset_calculator,
858
+ loader_t loader,
859
+ storer_t storer) {
860
+ constexpr ScalarType sret_t = rt_binary_specializations[arg_index][0];
861
+ constexpr ScalarType sarg0_t = rt_binary_specializations[arg_index][1];
862
+ constexpr ScalarType sarg1_t = rt_binary_specializations[arg_index][2];
863
+ if (ret_t == sret_t && arg0_t == sarg0_t && arg1_t == sarg1_t) {
864
+ using cret_t = c10::impl::ScalarTypeToCPPTypeT<sret_t>;
865
+ using carg0_t = c10::impl::ScalarTypeToCPPTypeT<sarg0_t>;
866
+ using carg1_t = c10::impl::ScalarTypeToCPPTypeT<sarg1_t>;
867
+ launch_vectorized_templated_kernel<
868
+ func_t,
869
+ array_t,
870
+ inp_calc_t,
871
+ out_calc_t,
872
+ loader_t,
873
+ storer_t,
874
+ cret_t,
875
+ carg0_t,
876
+ carg1_t>(
877
+ numel,
878
+ f,
879
+ data,
880
+ input_offset_calculator,
881
+ output_offset_calculator,
882
+ loader,
883
+ storer);
884
+ }
885
+ }
886
+ };
887
+
888
+ template <int arg_index>
889
+ struct type_specialized_broadcast_kernel_launcher {
890
+ template <
891
+ typename func_t,
892
+ typename array_t,
893
+ typename dtypes_t,
894
+ typename calc_t>
895
+ static void apply(
896
+ int64_t numel,
897
+ func_t f,
898
+ array_t data,
899
+ dtypes_t dtypes,
900
+ calc_t offset_calc) {
901
+ using traits = function_traits<func_t>;
902
+ using ret_t = typename traits::result_type;
903
+ using arg0_t = typename traits::template arg<0>::type;
904
+ using arg1_t = typename traits::template arg<1>::type;
905
+ if (dtypes[0] == rt_binary_specializations[arg_index][0] &&
906
+ dtypes[1] == rt_binary_specializations[arg_index][1] &&
907
+ dtypes[2] == rt_binary_specializations[arg_index][2]) {
908
+ using ret_cpp_t = c10::impl::ScalarTypeToCPPTypeT<rt_binary_specializations[arg_index][0]>;
909
+ using arg0_cpp_t = c10::impl::ScalarTypeToCPPTypeT<rt_binary_specializations[arg_index][1]>;
910
+ using arg1_cpp_t = c10::impl::ScalarTypeToCPPTypeT<rt_binary_specializations[arg_index][2]>;
911
+ constexpr int grp_sz = 128;
912
+ launch_legacy_kernel_manual_unroll<grp_sz, 4>(numel, [=] GPU_LAMBDA(int idx, bool unrl) {
913
+ if (unrl) {
914
+ auto offsets0 = offset_calc.get(idx);
915
+ auto offsets1 = offset_calc.get(idx + grp_sz);
916
+ auto offsets2 = offset_calc.get(idx + grp_sz * 2);
917
+ auto offsets3 = offset_calc.get(idx + grp_sz * 3);
918
+ void* out0 = data[0] + offsets0[0];
919
+ void* out1 = data[0] + offsets1[0];
920
+ void* out2 = data[0] + offsets2[0];
921
+ void* out3 = data[0] + offsets3[0];
922
+ auto u = c10::load<arg0_cpp_t>(data[1] + offsets0[1]);
923
+ auto v = c10::load<arg1_cpp_t>(data[2] + offsets0[2]);
924
+ ret_t result0 = f(c10::convert<arg0_t>(u), c10::convert<arg1_t>(v));
925
+ auto u1 = c10::load<arg0_cpp_t>(data[1] + offsets1[1]);
926
+ auto v1 = c10::load<arg1_cpp_t>(data[2]+ offsets1[2]);
927
+ ret_t result1 = f(c10::convert<arg0_t>(u1), c10::convert<arg1_t>(v1));
928
+ auto u2 = c10::load<arg0_cpp_t>(data[1] + offsets2[1]);
929
+ auto v2 = c10::load<arg1_cpp_t>(data[2] + offsets2[2]);
930
+ ret_t result2 = f(c10::convert<arg0_t>(u2), c10::convert<arg1_t>(v2));
931
+ auto u3 = c10::load<arg0_cpp_t>(data[1] + offsets3[1]);
932
+ auto v3 = c10::load<arg1_cpp_t>(data[2] + offsets3[2]);
933
+ ret_t result3 = f(c10::convert<arg0_t>(u3), c10::convert<arg1_t>(v3));
934
+ *(ret_cpp_t*)out0 = c10::convert<ret_cpp_t>(result0);
935
+ *(ret_cpp_t*)out1 = c10::convert<ret_cpp_t>(result1);
936
+ *(ret_cpp_t*)out2 = c10::convert<ret_cpp_t>(result2);
937
+ *(ret_cpp_t*)out3 = c10::convert<ret_cpp_t>(result3);
938
+ } else {
939
+ auto offsets = offset_calc.get(idx);
940
+ void* out = data[0] + offsets[0];
941
+ auto u = c10::load<arg0_cpp_t>(data[1] + offsets[1]);
942
+ auto v = c10::load<arg1_cpp_t>(data[2] + offsets[2]);
943
+ ret_t result = f(c10::convert<arg0_t>(u), c10::convert<arg1_t>(v));
944
+ *(ret_cpp_t*)out = c10::convert<ret_cpp_t>(result);
945
+ }
946
+ });
947
+ }
948
+ }
949
+ };
950
+
951
+ } // namespace
952
+ #endif
953
+
954
+ template <typename func_t>
955
+ void gpu_kernel_impl(TensorIteratorBase& iter, const func_t& f) {
956
+ if (!needs_dynamic_casting<func_t>::check(iter)) {
957
+ return gpu_kernel_impl_nocast(iter, f);
958
+ }
959
+ using traits = function_traits<func_t>;
960
+ using arg0_t = typename traits::result_type;
961
+ constexpr int ntensors = traits::arity + 1;
962
+
963
+ TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
964
+ TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
965
+ TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
966
+
967
+ std::array<char*, ntensors> data;
968
+ for (int i = 0; i < ntensors; i++) {
969
+ data[i] = (char*)iter.data_ptr(i);
970
+ }
971
+
972
+ int64_t numel = iter.numel();
973
+
974
+ bool contiguous = iter.is_contiguous();
975
+
976
+ if (contiguous) {
977
+ #ifdef USE_ROCM
978
+ // Attempt to call specialized vectorized elementwise kernel
979
+ // that enables interleaving.
980
+ if (check_binary_rt_types_for_specialization(iter) &&
981
+ memory::can_vectorize_up_to<func_t>(data) > 1) {
982
+ // constexpr to reduce the amount of kernels generated for
983
+ // vectorized templated elementwise and limit which functors are actually
984
+ // applied to the load and store at compile time.
985
+ using func_tuple = typename traits::ArgsTuple;
986
+ if constexpr (
987
+ std::is_same_v<float, arg0_t> && traits::arity == 2 &&
988
+ check_binary_functor_types_for_specialization<
989
+ func_tuple,
990
+ float,
991
+ float,
992
+ traits::arity,
993
+ /*arg_num=*/0>::check()) {
994
+ // If we got here, we know we are in one of the specialized cases. We
995
+ // need to translate the runtime type to a statically known type. This
996
+ // is effectively hoisting to the host the switch over runtime type in
997
+ // the kernel in fetch_and_cast. Loader, storer, offset calculators are
998
+ // only needed for the reminder loop.
999
+ auto input_offset_calculator = TrivialOffsetCalculator<traits::arity>();
1000
+ auto output_offset_calculator = TrivialOffsetCalculator<1>();
1001
+ auto loader = memory::LoadWithCast<traits::arity>(iter);
1002
+ auto storer = memory::StoreWithCast<1>(iter);
1003
+ memory::detail::static_unroll<
1004
+ type_specialized_kernel_launcher,
1005
+ rt_binary_specializations.size()>::
1006
+ with_args(
1007
+ iter.dtype(0),
1008
+ iter.input_dtype(0),
1009
+ iter.input_dtype(1),
1010
+ numel,
1011
+ f,
1012
+ data,
1013
+ input_offset_calculator,
1014
+ output_offset_calculator,
1015
+ loader,
1016
+ storer);
1017
+ return;
1018
+ }
1019
+ }
1020
+ std::array<ScalarType, ntensors> dtypes;
1021
+ auto inner_strides = iter.get_inner_strides();
1022
+ std::array<int, ntensors> strides;
1023
+ for (int i = 0; i < ntensors; i++) {
1024
+ dtypes[i] = iter.dtype(i);
1025
+ strides[i] = inner_strides[i];
1026
+ }
1027
+ constexpr int grp_sz = 128;
1028
+ launch_legacy_kernel_manual_unroll<grp_sz, 4>(numel, [=] GPU_LAMBDA(int idx, bool unrl) {
1029
+ if (unrl) {
1030
+ void* out0 = data[0] + strides[0] * idx;
1031
+ void* out1 = data[0] + strides[0] * (idx + grp_sz);
1032
+ void* out2 = data[0] + strides[0] * (idx + grp_sz * 2);
1033
+ void* out3 = data[0] + strides[0] * (idx + grp_sz * 3);
1034
+ arg0_t result0 = invoke(f, &data[1], &strides[1], &dtypes[1], idx);
1035
+ arg0_t result1 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz));
1036
+ arg0_t result2 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz * 2));
1037
+ arg0_t result3 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz * 3));
1038
+ c10::cast_and_store<arg0_t>(dtypes[0], out0, result0);
1039
+ c10::cast_and_store<arg0_t>(dtypes[0], out1, result1);
1040
+ c10::cast_and_store<arg0_t>(dtypes[0], out2, result2);
1041
+ c10::cast_and_store<arg0_t>(dtypes[0], out3, result3);
1042
+ } else {
1043
+ void* out = data[0] + strides[0] * idx;
1044
+ arg0_t result = invoke(f, &data[1], &strides[1], &dtypes[1], idx);
1045
+ c10::cast_and_store<arg0_t>(dtypes[0], out, result);
1046
+ }
1047
+ });
1048
+ #else
1049
+ auto loader = memory::LoadWithCast<traits::arity>(iter);
1050
+ auto storer = memory::StoreWithCast<1>(iter);
1051
+ auto input_offset_calculator = TrivialOffsetCalculator<traits::arity>();
1052
+ auto output_offset_calculator = TrivialOffsetCalculator<1>();
1053
+ launch_unrolled_kernel(
1054
+ numel,
1055
+ f,
1056
+ data,
1057
+ input_offset_calculator,
1058
+ output_offset_calculator,
1059
+ loader,
1060
+ storer);
1061
+ #endif
1062
+ } else {
1063
+ std::array<ScalarType, ntensors> dtypes;
1064
+ for (int i = 0; i < ntensors; i++) {
1065
+ dtypes[i] = iter.dtype(i);
1066
+ }
1067
+ auto offset_calc = ::make_offset_calculator<traits::arity + 1>(iter);
1068
+ #ifdef USE_ROCM
1069
+ if (check_binary_rt_types_for_specialization(iter)) {
1070
+ // constexpr to reduce the amount of kernels generated for
1071
+ // broadcast elementwise with mexed dtypes and limit which functors are actually
1072
+ // applied to the load and store at compile time.
1073
+ using func_tuple = typename traits::ArgsTuple;
1074
+ if constexpr (
1075
+ std::is_same_v<float, arg0_t> && traits::arity == 2 &&
1076
+ check_binary_functor_types_for_specialization<
1077
+ func_tuple,
1078
+ float,
1079
+ float,
1080
+ traits::arity,
1081
+ /*arg_num=*/0>::check()) {
1082
+ memory::detail::static_unroll<
1083
+ type_specialized_broadcast_kernel_launcher,
1084
+ rt_binary_specializations.size()>::with_args(
1085
+ numel,
1086
+ f,
1087
+ data,
1088
+ dtypes,
1089
+ offset_calc
1090
+ );
1091
+ return;
1092
+ }
1093
+ }
1094
+
1095
+ constexpr int grp_sz = 128;
1096
+ launch_legacy_kernel_manual_unroll<grp_sz, 4>(numel, [=] GPU_LAMBDA(int idx, bool unrl) {
1097
+ if (unrl) {
1098
+ auto offsets0 = offset_calc.get(idx);
1099
+ auto offsets1 = offset_calc.get(idx + grp_sz);
1100
+ auto offsets2 = offset_calc.get(idx + grp_sz * 2);
1101
+ auto offsets3 = offset_calc.get(idx + grp_sz * 3);
1102
+ void* out0 = data[0] + offsets0[0];
1103
+ void* out1 = data[0] + offsets1[0];
1104
+ void* out2 = data[0] + offsets2[0];
1105
+ void* out3 = data[0] + offsets3[0];
1106
+ arg0_t result0 = invoke(f, &data[1], &offsets0[1], &dtypes[1], 1);
1107
+ arg0_t result1 = invoke(f, &data[1], &offsets1[1], &dtypes[1], 1);
1108
+ arg0_t result2 = invoke(f, &data[1], &offsets2[1], &dtypes[1], 1);
1109
+ arg0_t result3 = invoke(f, &data[1], &offsets3[1], &dtypes[1], 1);
1110
+ c10::cast_and_store<arg0_t>(dtypes[0], out0, result0);
1111
+ c10::cast_and_store<arg0_t>(dtypes[0], out1, result1);
1112
+ c10::cast_and_store<arg0_t>(dtypes[0], out2, result2);
1113
+ c10::cast_and_store<arg0_t>(dtypes[0], out3, result3);
1114
+ } else {
1115
+ auto offsets = offset_calc.get(idx);
1116
+ void* out = data[0] + offsets[0];
1117
+ arg0_t result = invoke(f, &data[1], &offsets[1], &dtypes[1], 1);
1118
+ c10::cast_and_store<arg0_t>(dtypes[0], out, result);
1119
+ }
1120
+ });
1121
+ #else
1122
+ launch_legacy_kernel<128, 4>(numel, [=] GPU_LAMBDA(int idx) {
1123
+ auto offsets = offset_calc.get(idx);
1124
+ void* out = data[0] + offsets[0];
1125
+ arg0_t result = invoke(f, &data[1], &offsets[1], &dtypes[1], 1);
1126
+ c10::cast_and_store<arg0_t>(dtypes[0], out, result);
1127
+ });
1128
+ #endif
1129
+ }
1130
+ }
1131
+
1132
+ } // namespace at::native
1133
+
1134
+ #else
1135
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1136
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CompositeRandomAccessor.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/CompositeRandomAccessorCommon.h>
5
+ #include <thrust/swap.h>
6
+ #include <thrust/tuple.h>
7
+
8
+ namespace at { namespace native {
9
+
10
+ struct TupleInfoCPU {
11
+ template <typename ...Types>
12
+ using tuple = thrust::tuple<Types...>;
13
+
14
+ template <typename ...Types>
15
+ static constexpr auto tie(Types&... args) noexcept {
16
+ return thrust::tie(args...);
17
+ }
18
+ };
19
+
20
+ template <typename KeyAccessor, typename ValueAccessor>
21
+ using CompositeRandomAccessorCPU =
22
+ CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfoCPU>;
23
+
24
+ template <typename Values, typename References>
25
+ void swap(
26
+ references_holder<Values, References> rh1,
27
+ references_holder<Values, References> rh2
28
+ ) {
29
+ return thrust::swap(rh1.data(), rh2.data());
30
+ }
31
+
32
+ template <int N, typename Values, typename References>
33
+ auto get(references_holder<Values, References> rh) -> decltype(thrust::get<N>(rh.data())) {
34
+ return thrust::get<N>(rh.data());
35
+ }
36
+
37
+ }} // namespace at::native
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Copy.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at {
5
+ struct TensorIteratorBase;
6
+
7
+ namespace native {
8
+
9
+ void direct_copy_kernel_cuda(TensorIteratorBase& iter);
10
+
11
+ }
12
+ } // namespace at
13
+
14
+ #else
15
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
16
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CuFFTPlanCache.h ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <ATen/Config.h>
3
+ #include <ATen/core/DimVector.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/native/cuda/CuFFTUtils.h>
6
+ #include <ATen/native/utils/ParamsHash.h>
7
+ #include <c10/util/accumulate.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #include <cufft.h>
11
+ #include <cufftXt.h>
12
+
13
+ #include <limits>
14
+ #include <list>
15
+ #include <sstream>
16
+ #include <stdexcept>
17
+ #include <string>
18
+ #include <unordered_map>
19
+
20
+ namespace at::native::detail {
21
+
22
+ // Enum representing the FFT type
23
+ enum class CuFFTTransformType : int8_t {
24
+ C2C, // Complex-to-complex
25
+ R2C, // Real-to-complex
26
+ C2R, // Complex-to-real
27
+ };
28
+
29
+ // This struct is used to let us easily compute hashes of the
30
+ // parameters.
31
+ // It will be the **key** to the plan cache.
32
+ struct CuFFTParams
33
+ {
34
+ int64_t signal_ndim_; // between 1 and max_rank, i.e., 1 <= signal_ndim <= 3
35
+ // These include additional batch dimension as well.
36
+ int64_t sizes_[max_rank + 1];
37
+ int64_t input_strides_[max_rank + 1];
38
+ int64_t output_strides_[max_rank + 1];
39
+ CuFFTTransformType fft_type_;
40
+ ScalarType value_type_;
41
+
42
+ CuFFTParams() = default;
43
+
44
+ CuFFTParams(IntArrayRef in_strides, IntArrayRef out_strides,
45
+ IntArrayRef signal_sizes, CuFFTTransformType fft_type, ScalarType value_type) {
46
+ // Padding bits must be zeroed for hashing
47
+ memset(this, 0, sizeof(*this));
48
+ signal_ndim_ = signal_sizes.size() - 1;
49
+ fft_type_ = fft_type;
50
+ value_type_ = value_type;
51
+
52
+ TORCH_INTERNAL_ASSERT(in_strides.size() == signal_sizes.size());
53
+ TORCH_INTERNAL_ASSERT(out_strides.size() == signal_sizes.size());
54
+ TORCH_INTERNAL_ASSERT(1 <= signal_ndim_ && signal_ndim_ <= max_rank);
55
+
56
+ std::copy(signal_sizes.cbegin(), signal_sizes.cend(), sizes_);
57
+ std::copy(in_strides.cbegin(), in_strides.cend(), input_strides_);
58
+ std::copy(out_strides.cbegin(), out_strides.cend(), output_strides_);
59
+ }
60
+ };
61
+
62
+ static_assert(std::is_trivial_v<CuFFTParams> );
63
+
64
+ // Returns true if the transform type has complex input
65
+ inline bool cufft_complex_input(CuFFTTransformType type) {
66
+ switch (type) {
67
+ case CuFFTTransformType::C2C:
68
+ case CuFFTTransformType::C2R:
69
+ return true;
70
+
71
+ case CuFFTTransformType::R2C:
72
+ return false;
73
+ }
74
+ TORCH_INTERNAL_ASSERT(false);
75
+ }
76
+
77
+ // Returns true if the transform type has complex output
78
+ inline bool cufft_complex_output(CuFFTTransformType type) {
79
+ switch (type) {
80
+ case CuFFTTransformType::C2C:
81
+ case CuFFTTransformType::R2C:
82
+ return true;
83
+
84
+ case CuFFTTransformType::C2R:
85
+ return false;
86
+ }
87
+ TORCH_INTERNAL_ASSERT(false);
88
+ }
89
+
90
+ // Create transform type enum from bools representing if input and output are complex
91
+ inline CuFFTTransformType GetCuFFTTransformType(bool complex_input, bool complex_output) {
92
+ if (complex_input && complex_output) {
93
+ return CuFFTTransformType::C2C;
94
+ } else if (complex_input && !complex_output) {
95
+ return CuFFTTransformType::C2R;
96
+ } else if (!complex_input && complex_output) {
97
+ return CuFFTTransformType::R2C;
98
+ }
99
+ TORCH_INTERNAL_ASSERT(false, "Real to real FFTs are not supported");
100
+ }
101
+
102
+
103
+ class CuFFTHandle {
104
+ ::cufftHandle handle_;
105
+ public:
106
+
107
+ CuFFTHandle() {
108
+ CUFFT_CHECK(cufftCreate(&handle_));
109
+ }
110
+
111
+ ::cufftHandle & get() { return handle_; }
112
+ const ::cufftHandle & get() const { return handle_; }
113
+
114
+ ~CuFFTHandle() {
115
+ // Not using fftDestroy() for rocFFT to work around double freeing of handles
116
+ #if !defined(USE_ROCM)
117
+ cufftDestroy(handle_);
118
+ #endif
119
+ }
120
+ };
121
+
122
+ __forceinline__
123
+ static bool is_pow_of_two(int64_t x) {
124
+ return (x & (x - 1)) == 0;
125
+ }
126
+
127
+ using cufft_size_type = long long int;
128
+
129
+ using CuFFTDimVector = c10::SmallVector<cufft_size_type, at::kDimVectorStaticSize>;
130
+
131
+ // Struct representing a tensor in CuFFT's data layout for planning transforms
132
+ // See NOTE [ cuFFT Embedded Strides ].
133
+ struct CuFFTDataLayout {
134
+ CuFFTDimVector embed;
135
+ cufft_size_type stride, dist;
136
+ bool must_clone, simple;
137
+ };
138
+
139
+ // Returns a cufft embedding for a contiguous signal of the given size.
140
+ // e.g. if the input is cloned, this will be the resulting data layout
141
+ // See NOTE [ cuFFT Embedded Strides ].
142
+ inline CuFFTDataLayout cufft_simple_embed(IntArrayRef sizes, bool onesided) {
143
+ CuFFTDataLayout layout;
144
+ layout.simple = true;
145
+ layout.must_clone = false;
146
+ layout.embed.assign(sizes.cbegin() + 1, sizes.cend());
147
+ if (onesided) {
148
+ layout.embed.back() = sizes.back() / 2 + 1;
149
+ }
150
+ layout.stride = 1;
151
+ layout.dist = 1;
152
+ for (const auto& len : layout.embed) {
153
+ layout.dist *= len;
154
+ }
155
+ return layout;
156
+ }
157
+
158
+ // Convert strides to a CuFFT embedded representation.
159
+ // If strides cannot be embedded, returns a simple layout and sets must_clone flag
160
+ // See NOTE [ cuFFT Embedded Strides ].
161
+ inline CuFFTDataLayout as_cufft_embed(IntArrayRef strides, IntArrayRef sizes, bool onesided) {
162
+ const auto signal_ndim = strides.size() - 1;
163
+ CuFFTDataLayout layout;
164
+ auto last_stride = strides[signal_ndim];
165
+ layout.must_clone = (last_stride <= 0);
166
+
167
+ const auto last_dim_size = onesided ?
168
+ sizes[signal_ndim] / 2 + 1 : sizes[signal_ndim];
169
+ const auto signal_numel = c10::multiply_integers(sizes.slice(1, sizes.size() - 2)) * last_dim_size;
170
+
171
+ // Zero stides are not allowed, even if the batch size is one.
172
+ // If that happens just set a dummy case
173
+ if (sizes[0] == 1) {
174
+ layout.dist = signal_numel;
175
+ } else if (strides[0] == 0) {
176
+ layout.must_clone = true;
177
+ } else {
178
+ layout.dist = strides[0];
179
+ }
180
+
181
+ // Calculate the embedding shape, or set must_clone if the strides cannot be embedded
182
+ layout.embed.resize(signal_ndim);
183
+ for (auto i = signal_ndim - 1; !layout.must_clone && i > 0; i--) {
184
+ auto stride = strides[i];
185
+ if (sizes[i] == 1) {
186
+ layout.embed[i] = 1;
187
+ } else if (stride > 0 && stride % last_stride == 0) {
188
+ layout.embed[i] = stride / last_stride;
189
+ last_stride = stride;
190
+ } else {
191
+ layout.must_clone = true;
192
+ }
193
+ }
194
+
195
+ if (layout.must_clone) {
196
+ // If the input needs to be cloned, assume it will be contiguous
197
+ layout = cufft_simple_embed(sizes, onesided);
198
+ layout.must_clone = true;
199
+ } else {
200
+ layout.embed[0] = sizes[1];
201
+ layout.stride = strides[signal_ndim];
202
+ // Determine if layout represents a simple embedding (contiguous data)
203
+ layout.simple = [&] {
204
+ for (const auto i : c10::irange(1, signal_ndim - 1)) {
205
+ if (layout.embed[i] != sizes[i + 1]) {
206
+ return false;
207
+ }
208
+ }
209
+
210
+ return (layout.stride == 1 && layout.dist == signal_numel &&
211
+ layout.embed.back() == last_dim_size);
212
+ }();
213
+ }
214
+ return layout;
215
+ }
216
+
217
+ // This class contains all the information needed to execute a cuFFT plan:
218
+ // 1. the plan
219
+ // 2. whether to clone input before executing the plan
220
+ // 3. the workspace size needed
221
+ //
222
+ // This class will be the **value** in the plan cache.
223
+ // It **owns** the raw plan via a unique_ptr.
224
+ class CuFFTConfig {
225
+ public:
226
+
227
+ // Only move semantics is enough for this class. Although we already use
228
+ // unique_ptr for the plan, still remove copy constructor and assignment op so
229
+ // we don't accidentally copy and take perf hit.
230
+ CuFFTConfig(const CuFFTConfig&) = delete;
231
+ CuFFTConfig& operator=(CuFFTConfig const&) = delete;
232
+
233
+ explicit CuFFTConfig(const CuFFTParams& params):
234
+ CuFFTConfig(
235
+ IntArrayRef(params.input_strides_, params.signal_ndim_ + 1),
236
+ IntArrayRef(params.output_strides_, params.signal_ndim_ + 1),
237
+ IntArrayRef(params.sizes_, params.signal_ndim_ + 1),
238
+ params.fft_type_,
239
+ params.value_type_) {}
240
+
241
+ // For complex types, strides are in units of 2 * element_size(dtype)
242
+ // sizes are for the full signal, including batch size and always two-sided
243
+ CuFFTConfig(IntArrayRef in_strides, IntArrayRef out_strides,
244
+ IntArrayRef sizes, CuFFTTransformType fft_type, ScalarType dtype):
245
+ fft_type_(fft_type), value_type_(dtype) {
246
+
247
+ // signal sizes (excluding batch dim)
248
+ CuFFTDimVector signal_sizes(sizes.begin() + 1, sizes.end());
249
+
250
+ // input batch size
251
+ const int64_t batch = sizes[0];
252
+ const int64_t signal_ndim = sizes.size() - 1;
253
+
254
+ // Since cuFFT has limited non-unit stride support and various constraints, we
255
+ // use a flag to keep track throughout this function to see if we need to
256
+ // input = input.clone();
257
+
258
+ #if defined(USE_ROCM)
259
+ // clone input to avoid issues with hipfft clobering the input and failing tests
260
+ clone_input = true;
261
+ #else
262
+ clone_input = false;
263
+ #endif
264
+
265
+ // For half, base strides on the real part of real-to-complex and
266
+ // complex-to-real transforms are not supported. Since our output is always
267
+ // contiguous, only need to check real-to-complex case.
268
+ if (dtype == ScalarType::Half) {
269
+ // cuFFT on half requires compute capability of at least SM_53
270
+ auto dev_prop = at::cuda::getCurrentDeviceProperties();
271
+ TORCH_CHECK(dev_prop->major >= 5 && !(dev_prop->major == 5 && dev_prop->minor < 3),
272
+ "cuFFT doesn't support signals of half type with compute "
273
+ "capability less than SM_53, but the device containing input half "
274
+ "tensor only has SM_", dev_prop->major, dev_prop->minor);
275
+ for (const auto i : c10::irange(signal_ndim)) {
276
+ TORCH_CHECK(is_pow_of_two(sizes[i + 1]),
277
+ "cuFFT only supports dimensions whose sizes are powers of two when"
278
+ " computing in half precision, but got a signal size of",
279
+ sizes.slice(1));
280
+ }
281
+ clone_input |= in_strides.back() != 1;
282
+ }
283
+
284
+ CuFFTDataLayout in_layout;
285
+ if (clone_input) {
286
+ in_layout = cufft_simple_embed(sizes, fft_type == CuFFTTransformType::C2R);
287
+ } else {
288
+ in_layout = as_cufft_embed(in_strides, sizes, fft_type == CuFFTTransformType::C2R);
289
+ }
290
+ auto out_layout = as_cufft_embed(out_strides, sizes, fft_type == CuFFTTransformType::R2C);
291
+ TORCH_INTERNAL_ASSERT(!out_layout.must_clone, "Out strides cannot be represented as CuFFT embedding");
292
+ clone_input |= in_layout.must_clone;
293
+
294
+ // Check if we can take advantage of simple data layout.
295
+ //
296
+ // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu.
297
+
298
+ const bool simple_layout = in_layout.simple && out_layout.simple;
299
+ cudaDataType itype, otype, exec_type;
300
+ const auto complex_input = cufft_complex_input(fft_type);
301
+ const auto complex_output = cufft_complex_output(fft_type);
302
+ if (dtype == ScalarType::Float) {
303
+ itype = complex_input ? CUDA_C_32F : CUDA_R_32F;
304
+ otype = complex_output ? CUDA_C_32F : CUDA_R_32F;
305
+ exec_type = CUDA_C_32F;
306
+ } else if (dtype == ScalarType::Double) {
307
+ itype = complex_input ? CUDA_C_64F : CUDA_R_64F;
308
+ otype = complex_output ? CUDA_C_64F : CUDA_R_64F;
309
+ exec_type = CUDA_C_64F;
310
+ } else if (dtype == ScalarType::Half) {
311
+ itype = complex_input ? CUDA_C_16F : CUDA_R_16F;
312
+ otype = complex_output ? CUDA_C_16F : CUDA_R_16F;
313
+ exec_type = CUDA_C_16F;
314
+ } else {
315
+ TORCH_CHECK(false, "cuFFT doesn't support tensor of type: ", dtype);
316
+ }
317
+
318
+ // disable auto allocation of workspace to use THC allocator
319
+ CUFFT_CHECK(cufftSetAutoAllocation(plan(), /* autoAllocate */ 0));
320
+
321
+ size_t ws_size_t;
322
+
323
+ // make plan
324
+ if (simple_layout) {
325
+ // If with unit-stride, we tell cuFFT by setting inembed == onembed == NULL.
326
+ // In such case, cuFFT ignores istride, ostride, idist, and odist
327
+ // by assuming istride = ostride = 1.
328
+ //
329
+ // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu.
330
+ CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(),
331
+ /* inembed */ nullptr, /* base_istride */ 1, /* idist */ 1, itype,
332
+ /* onembed */ nullptr, /* base_ostride */ 1, /* odist */ 1, otype,
333
+ batch, &ws_size_t, exec_type));
334
+ } else {
335
+ CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(),
336
+ in_layout.embed.data(), in_layout.stride, in_layout.dist, itype,
337
+ out_layout.embed.data(), out_layout.stride, out_layout.dist, otype,
338
+ batch, &ws_size_t, exec_type));
339
+ }
340
+ ws_size = static_cast<int64_t>(ws_size_t);
341
+ }
342
+
343
+ const cufftHandle &plan() const { return plan_ptr.get(); }
344
+
345
+ CuFFTTransformType transform_type() const { return fft_type_; }
346
+ ScalarType data_type() const { return value_type_; }
347
+ bool should_clone_input() const { return clone_input; }
348
+ int64_t workspace_size() const { return ws_size; }
349
+
350
+ private:
351
+ CuFFTHandle plan_ptr;
352
+ bool clone_input;
353
+ int64_t ws_size;
354
+ CuFFTTransformType fft_type_;
355
+ ScalarType value_type_;
356
+ };
357
+
358
+ #if defined(USE_ROCM)
359
+ // Note that the max plan number for CUDA version < 10 has to be 1023
360
+ // due to a bug that fails on the 1024th plan
361
+ constexpr int64_t CUFFT_MAX_PLAN_NUM = 1023;
362
+ constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = CUFFT_MAX_PLAN_NUM;
363
+ #else
364
+ constexpr int64_t CUFFT_MAX_PLAN_NUM = std::numeric_limits<int64_t>::max();
365
+ // The default max cache size chosen for CUDA version > 10 is arbitrary.
366
+ // This number puts a limit on how big of a plan cache should we maintain by
367
+ // default. Users can always configure it via cufft_set_plan_cache_max_size.
368
+ constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = 4096;
369
+ #endif
370
+ static_assert(0 <= CUFFT_MAX_PLAN_NUM && CUFFT_MAX_PLAN_NUM <= std::numeric_limits<int64_t>::max(),
371
+ "CUFFT_MAX_PLAN_NUM not in size_t range");
372
+ static_assert(CUFFT_DEFAULT_CACHE_SIZE >= 0 && CUFFT_DEFAULT_CACHE_SIZE <= CUFFT_MAX_PLAN_NUM,
373
+ "CUFFT_DEFAULT_CACHE_SIZE not in [0, CUFFT_MAX_PLAN_NUM] range");
374
+
375
+ // This cache assumes that the mapping from key to value never changes.
376
+ // This is **NOT** thread-safe. Please use a mutex when using it **AND** the
377
+ // value returned from try_emplace_value.
378
+ // The contract of using this cache is that try_emplace_value should only be
379
+ // used when the max_size is positive.
380
+ class CuFFTParamsLRUCache {
381
+ public:
382
+ using kv_t = typename std::pair<CuFFTParams, CuFFTConfig>;
383
+ using map_t = typename std::unordered_map<std::reference_wrapper<CuFFTParams>,
384
+ typename std::list<kv_t>::iterator,
385
+ ParamsHash<CuFFTParams>,
386
+ ParamsEqual<CuFFTParams>>;
387
+ using map_kkv_iter_t = typename map_t::iterator;
388
+
389
+
390
+ CuFFTParamsLRUCache() : CuFFTParamsLRUCache(CUFFT_DEFAULT_CACHE_SIZE) {}
391
+
392
+ CuFFTParamsLRUCache(int64_t max_size) {
393
+ _set_max_size(max_size);
394
+ }
395
+
396
+ CuFFTParamsLRUCache(CuFFTParamsLRUCache&& other) noexcept :
397
+ _usage_list(std::move(other._usage_list)),
398
+ _cache_map(std::move(other._cache_map)),
399
+ _max_size(other._max_size) {}
400
+
401
+ CuFFTParamsLRUCache& operator=(CuFFTParamsLRUCache&& other) noexcept {
402
+ _usage_list = std::move(other._usage_list);
403
+ _cache_map = std::move(other._cache_map);
404
+ _max_size = other._max_size;
405
+ return *this;
406
+ }
407
+
408
+ // If key is in this cache, return the cached config. Otherwise, emplace the
409
+ // config in this cache and return it.
410
+ // Return const reference because CuFFTConfig shouldn't be tampered with once
411
+ // created.
412
+ const CuFFTConfig &lookup(CuFFTParams params) {
413
+ AT_ASSERT(_max_size > 0);
414
+
415
+ map_kkv_iter_t map_it = _cache_map.find(params);
416
+ // Hit, put to list front
417
+ if (map_it != _cache_map.end()) {
418
+ _usage_list.splice(_usage_list.begin(), _usage_list, map_it->second);
419
+ return map_it->second->second;
420
+ }
421
+
422
+ // Miss
423
+ // remove if needed
424
+ if (_usage_list.size() >= _max_size) {
425
+ auto last = _usage_list.end();
426
+ last--;
427
+ _cache_map.erase(last->first);
428
+ _usage_list.pop_back();
429
+ }
430
+
431
+ // construct new plan at list front, then insert into _cache_map
432
+ _usage_list.emplace_front(std::piecewise_construct,
433
+ std::forward_as_tuple(params),
434
+ std::forward_as_tuple(params));
435
+ auto kv_it = _usage_list.begin();
436
+ _cache_map.emplace(std::piecewise_construct,
437
+ std::forward_as_tuple(kv_it->first),
438
+ std::forward_as_tuple(kv_it));
439
+ return kv_it->second;
440
+ }
441
+
442
+ void clear() {
443
+ _cache_map.clear();
444
+ _usage_list.clear();
445
+ }
446
+
447
+ void resize(int64_t new_size) {
448
+ _set_max_size(new_size);
449
+ auto cur_size = _usage_list.size();
450
+ if (cur_size > _max_size) {
451
+ auto delete_it = _usage_list.end();
452
+ for (size_t i = 0; i < cur_size - _max_size; i++) {
453
+ delete_it--;
454
+ _cache_map.erase(delete_it->first);
455
+ }
456
+ _usage_list.erase(delete_it, _usage_list.end());
457
+ }
458
+ }
459
+
460
+ size_t size() const { return _cache_map.size(); }
461
+
462
+ size_t max_size() const noexcept { return _max_size; }
463
+
464
+ std::mutex mutex;
465
+
466
+ private:
467
+ // Only sets size and does value check. Does not resize the data structures.
468
+ void _set_max_size(int64_t new_size) {
469
+ // We check that 0 <= new_size <= CUFFT_MAX_PLAN_NUM here. Since
470
+ // CUFFT_MAX_PLAN_NUM is of type size_t, we need to do non-negativity check
471
+ // first.
472
+ TORCH_CHECK(new_size >= 0,
473
+ "cuFFT plan cache size must be non-negative, but got ", new_size);
474
+ TORCH_CHECK(new_size <= CUFFT_MAX_PLAN_NUM,
475
+ "cuFFT plan cache size can not be larger than ", CUFFT_MAX_PLAN_NUM, ", but got ", new_size);
476
+ _max_size = static_cast<size_t>(new_size);
477
+ }
478
+
479
+ std::list<kv_t> _usage_list;
480
+ map_t _cache_map;
481
+ size_t _max_size;
482
+ };
483
+
484
+ // Since ATen is separated into CPU build and CUDA build, we need a way to call
485
+ // these functions only when CUDA is loaded. We use CUDA hooks for this purpose
486
+ // (at cuda/detail/CUDAHooks.cpp), and call the hooked functions from the actual
487
+ // native function counterparts (at native/SpectralOps.cpp), i.e.,
488
+ // _cufft_get_plan_cache_max_size, _cufft_set_plan_cache_max_size
489
+ // _cufft_get_plan_cache_size, and _cufft_clear_plan_cache.
490
+ int64_t cufft_get_plan_cache_max_size_impl(DeviceIndex device_index);
491
+ void cufft_set_plan_cache_max_size_impl(DeviceIndex device_index, int64_t max_size);
492
+ int64_t cufft_get_plan_cache_size_impl(DeviceIndex device_index);
493
+ void cufft_clear_plan_cache_impl(DeviceIndex device_index);
494
+
495
+ } // namespace at::native::detail
496
+
497
+ #else
498
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
499
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/CuFFTUtils.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+
6
+ #include <string>
7
+ #include <stdexcept>
8
+ #include <sstream>
9
+ #include <cufft.h>
10
+ #include <cufftXt.h>
11
+
12
+ namespace at { namespace native {
13
+
14
+ // This means that max dim is 3 + 2 = 5 with batch dimension and possible
15
+ // complex dimension
16
+ constexpr int max_rank = 3;
17
+
18
+ static inline std::string _cudaGetErrorEnum(cufftResult error)
19
+ {
20
+ switch (error)
21
+ {
22
+ case CUFFT_SUCCESS:
23
+ return "CUFFT_SUCCESS";
24
+ case CUFFT_INVALID_PLAN:
25
+ return "CUFFT_INVALID_PLAN";
26
+ case CUFFT_ALLOC_FAILED:
27
+ return "CUFFT_ALLOC_FAILED";
28
+ case CUFFT_INVALID_TYPE:
29
+ return "CUFFT_INVALID_TYPE";
30
+ case CUFFT_INVALID_VALUE:
31
+ return "CUFFT_INVALID_VALUE";
32
+ case CUFFT_INTERNAL_ERROR:
33
+ return "CUFFT_INTERNAL_ERROR";
34
+ case CUFFT_EXEC_FAILED:
35
+ return "CUFFT_EXEC_FAILED";
36
+ case CUFFT_SETUP_FAILED:
37
+ return "CUFFT_SETUP_FAILED";
38
+ case CUFFT_INVALID_SIZE:
39
+ return "CUFFT_INVALID_SIZE";
40
+ case CUFFT_UNALIGNED_DATA:
41
+ return "CUFFT_UNALIGNED_DATA";
42
+ case CUFFT_INVALID_DEVICE:
43
+ return "CUFFT_INVALID_DEVICE";
44
+ case CUFFT_NO_WORKSPACE:
45
+ return "CUFFT_NO_WORKSPACE";
46
+ case CUFFT_NOT_IMPLEMENTED:
47
+ return "CUFFT_NOT_IMPLEMENTED";
48
+ #if CUDA_VERSION <= 12090
49
+ case CUFFT_INCOMPLETE_PARAMETER_LIST:
50
+ return "CUFFT_INCOMPLETE_PARAMETER_LIST";
51
+ case CUFFT_PARSE_ERROR:
52
+ return "CUFFT_PARSE_ERROR";
53
+ #endif
54
+ #if !defined(USE_ROCM) && CUDA_VERSION <= 12090
55
+ case CUFFT_LICENSE_ERROR:
56
+ return "CUFFT_LICENSE_ERROR";
57
+ #endif
58
+ case CUFFT_NOT_SUPPORTED:
59
+ return "CUFFT_NOT_SUPPORTED";
60
+ default:
61
+ std::ostringstream ss;
62
+ ss << "unknown error " << error;
63
+ return ss.str();
64
+ }
65
+ }
66
+
67
+ static inline void CUFFT_CHECK(cufftResult error)
68
+ {
69
+ if (error != CUFFT_SUCCESS) {
70
+ std::ostringstream ss;
71
+ ss << "cuFFT error: " << _cudaGetErrorEnum(error);
72
+ TORCH_CHECK(false, ss.str());
73
+ }
74
+ }
75
+
76
+ }} // at::native
77
+
78
+ #else
79
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
80
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/DeviceSqrt.cuh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at::native {
5
+ #if defined(USE_ROCM)
6
+ // take these out when ROCm implements std:: math functions
7
+ #include <math.h>
8
+ template <typename scalar_t>
9
+ static __forceinline__ __device__ scalar_t device_sqrt(scalar_t val);
10
+
11
+ template <>
12
+ __forceinline__ __device__ float device_sqrt(float val) {
13
+ return ::sqrtf(val);
14
+ }
15
+
16
+ template <>
17
+ __forceinline__ __device__ double device_sqrt(double val) {
18
+ return ::sqrt(val);
19
+ }
20
+ #else
21
+ template<typename scalar_t>
22
+ __forceinline__ __device__ double device_sqrt(scalar_t val) {
23
+ return std::sqrt(val);
24
+ }
25
+ #endif
26
+ } // namespace at::native
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/DistributionTemplates.h ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/AccumulateType.h>
5
+ #include <ATen/Dispatch.h>
6
+ #include <ATen/Dispatch_v2.h>
7
+ #include <ATen/ExpandBase.h>
8
+ #include <ATen/OpMathType.h>
9
+ #include <ATen/native/TensorIterator.h>
10
+ #include <ATen/native/cuda/Loops.cuh>
11
+ #include <c10/util/Half.h>
12
+ #include <ATen/cuda/CUDAApplyUtils.cuh>
13
+ #include <ATen/cuda/CUDAContext.h>
14
+ #include <ATen/cuda/detail/OffsetCalculator.cuh>
15
+ #include <ATen/cuda/CUDAGraphsUtils.cuh>
16
+ #include <ATen/detail/FunctionTraits.h>
17
+ #include <ATen/core/DistributionsHelper.h>
18
+
19
+ #include <curand.h>
20
+ #include <curand_kernel.h>
21
+ #include <curand_philox4x32_x.h>
22
+ #include <cstdint>
23
+ #include <limits>
24
+ #include <utility>
25
+ #include <mutex>
26
+ #include <tuple>
27
+ #include <type_traits>
28
+
29
+ namespace at {
30
+ namespace native {
31
+ namespace {
32
+
33
+ // launch bounds used for kernels utilizing TensorIterator
34
+ const uint32_t block_size_bound = 256;
35
+ const uint32_t grid_size_bound = 4;
36
+ // At the time of writing, there is no curand_* call that increments the offset by more than 4.
37
+ // See: https://docs.nvidia.com/cuda/archive/11.8.0/curand/group__DEVICE.html
38
+ const uint32_t max_generator_offsets_per_curand_call = 4;
39
+
40
+ // utility function that calculates proper philox_offset
41
+ // for distributions utilizing TensorIterator. For distributions using
42
+ // TensorIterator, we are using a grid-stride loop with each
43
+ // thread yielding one element per thread. For the edge of the grid-stride
44
+ // loop, if the tensor size is large, the unroll loop will kick in and the float4
45
+ // from curand4 will start getting utilized (for common tensor sizes, we end up
46
+ // using rand.x from each thread). The philox_offset calculation was changed to
47
+ // (number of elements per thread * maximum generator increment per "curand_*" call), which makes
48
+ // sure that philox offset increment is not less than the number of randoms used
49
+ // in each thread.
50
+ std::tuple<uint64_t, dim3, dim3> calc_execution_policy(const int64_t total_elements, const uint32_t unroll_factor) {
51
+ const uint64_t numel = static_cast<uint64_t>(total_elements);
52
+ const uint32_t block_size = block_size_bound;
53
+ dim3 dim_block(block_size);
54
+ dim3 grid((numel + block_size - 1) / block_size);
55
+ uint32_t blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor / block_size;
56
+ grid.x = std::min(
57
+ static_cast<uint32_t>(at::cuda::getCurrentDeviceProperties()->multiProcessorCount) * blocks_per_sm,
58
+ grid.x);
59
+ //number of times random will be generated per thread, to offset philox counter in thc random state
60
+ uint64_t counter_offset = ((numel - 1) / (block_size * grid.x * unroll_factor) + 1) * max_generator_offsets_per_curand_call;
61
+ return std::make_tuple(counter_offset, grid, dim_block);
62
+ }
63
+
64
+ // grid stride loop kernel for distributions
65
+ template<typename accscalar_t, int unroll_factor, typename dist_t, typename transform_t>
66
+ C10_LAUNCH_BOUNDS_2(block_size_bound, grid_size_bound)
67
+ __global__ void distribution_elementwise_grid_stride_kernel(int64_t numel,
68
+ PhiloxCudaState philox_args,
69
+ const dist_t dist_func,
70
+ const transform_t transform_func) {
71
+ auto [seed, offset] = at::cuda::philox::unpack(philox_args);
72
+ int64_t idx = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x;
73
+ curandStatePhilox4_32_10_t state;
74
+ curand_init(seed, idx, offset, &state);
75
+
76
+ int64_t rounded_size = ((numel - 1)/(blockDim.x * gridDim.x * unroll_factor)+1) *
77
+ blockDim.x * gridDim.x * unroll_factor;
78
+ for(int64_t linear_index = idx; linear_index < rounded_size; linear_index += blockDim.x * gridDim.x * unroll_factor) {
79
+ auto rand = dist_func(&state);
80
+ #pragma unroll
81
+ for (int ii = 0; ii < unroll_factor; ii++) {
82
+ int64_t li = linear_index + blockDim.x * gridDim.x * ii;
83
+ if (li < numel) {
84
+ transform_func(li, static_cast<accscalar_t>((&rand.x)[ii]));
85
+ }
86
+ }
87
+ __syncthreads();
88
+ }
89
+ }
90
+
91
+ /**
92
+ * distribution_nullary_kernel is analogous to gpu_kernel in
93
+ * ATen/native/cuda/Loops.cuh. Like gpu_kernel, it uses
94
+ * TensorIterator to launch a kernel. However, the differences are
95
+ * - it launches a grid-stride loop based kernel. The kernel is not
96
+ * generic like elementwise_kernel in Loops.cuh and is specialized
97
+ * for the distribution kernels here.
98
+ * - For big size tensors, we can launch multiple kernels recursively
99
+ * (i.e. if (!iter.can_use_32bit_indexing())) and hence, the philox
100
+ * offset calculation is done in this function.
101
+ *
102
+ * FIXME: Can we specialize elementwise_kernel and launch_kernel in Loops.cuh
103
+ * to have grid-stride loop kernel and then use that to launch our distribution
104
+ * kernels? Note that we need a grid-stride loop kernel because, we found by testing
105
+ * that it achieves peak effective bandwidth.
106
+ */
107
+ template<typename scalar_t,
108
+ typename accscalar_t,
109
+ typename dist_func_return_t,
110
+ typename RNG,
111
+ typename dist_t,
112
+ typename transform_t>
113
+ void distribution_nullary_kernel(at::TensorIteratorBase& iter,
114
+ RNG gen,
115
+ const dist_t& dist_func,
116
+ const transform_t transform_func) {
117
+ const int unroll_factor = sizeof(dist_func_return_t) / sizeof(accscalar_t);
118
+ TORCH_CHECK(unroll_factor >= 1, "unroll_factor must be >= 1.");
119
+ int64_t numel = iter.numel();
120
+ if (numel == 0) {
121
+ return;
122
+ }
123
+
124
+ auto [counter_offset, grid, block] = calc_execution_policy(numel, unroll_factor);
125
+ PhiloxCudaState rng_engine_inputs;
126
+ {
127
+ // See Note [Acquire lock when using random generators]
128
+ std::lock_guard<std::mutex> lock(gen->mutex_);
129
+ rng_engine_inputs = gen->philox_cuda_state(counter_offset);
130
+ }
131
+
132
+ if (!iter.can_use_32bit_indexing()) {
133
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
134
+ distribution_nullary_kernel<scalar_t, accscalar_t, dist_func_return_t>(sub_iter,
135
+ gen, dist_func, transform_func);
136
+ }
137
+ return;
138
+ }
139
+
140
+ char* out_data = (char*)iter.data_ptr(0);
141
+
142
+ auto stream = at::cuda::getCurrentCUDAStream();
143
+ if (iter.is_trivial_1d()) {
144
+ auto strides = iter.get_inner_strides();
145
+ int stride0 = strides[0];
146
+ distribution_elementwise_grid_stride_kernel<accscalar_t, unroll_factor><<<grid, block, 0, stream>>>(
147
+ numel,
148
+ rng_engine_inputs,
149
+ dist_func,
150
+ [=]__device__(int idx, accscalar_t rand) {
151
+ scalar_t* out = (scalar_t*)&out_data[stride0 * idx];
152
+ *out = transform_func(rand);
153
+ }
154
+ );
155
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
156
+ } else {
157
+ auto offset_calc = make_offset_calculator<1>(iter);
158
+ distribution_elementwise_grid_stride_kernel<accscalar_t, unroll_factor><<<grid, block, 0, stream>>>(
159
+ numel,
160
+ rng_engine_inputs,
161
+ dist_func,
162
+ [=]__device__(int idx, accscalar_t rand) {
163
+ auto offsets = offset_calc.get(idx);
164
+ scalar_t* out = (scalar_t*)&out_data[offsets[0]];
165
+ *out = transform_func(rand);
166
+ }
167
+ );
168
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
169
+ }
170
+ }
171
+
172
+ // Binary kernel
173
+ template <typename func_t, typename inp_offset_calc_t, typename out_offset_calc_t>
174
+ __global__ void distribution_binary_elementwise_kernel(
175
+ int numel,
176
+ func_t f,
177
+ PhiloxCudaState philox_args,
178
+ typename function_traits<func_t>::result_type *output_data,
179
+ const typename function_traits<func_t>::template arg<1>::type *input_data_1,
180
+ const typename function_traits<func_t>::template arg<2>::type *input_data_2,
181
+ inp_offset_calc_t inp_calc,
182
+ out_offset_calc_t out_calc) {
183
+ auto seeds = at::cuda::philox::unpack(philox_args);
184
+
185
+ using input_t_1 = typename function_traits<func_t>::template arg<1>::type;
186
+ using input_t_2 = typename function_traits<func_t>::template arg<2>::type;
187
+
188
+ input_t_1 inputs_1[thread_work_size()];
189
+ input_t_2 inputs_2[thread_work_size()];
190
+
191
+ int base_index = block_work_size() * blockIdx.x;
192
+ int remaining = std::min<int>(numel - base_index, block_work_size());
193
+
194
+ curandStatePhilox4_32_10_t state;
195
+ curand_init(std::get<0>(seeds),
196
+ blockIdx.x * blockDim.x + threadIdx.x,
197
+ std::get<1>(seeds),
198
+ &state);
199
+
200
+ // load data into registers
201
+ int thread_idx = threadIdx.x;
202
+ #pragma unroll
203
+ for (int i = 0; i < thread_work_size(); i++) {
204
+ if (thread_idx >= remaining) {
205
+ break;
206
+ }
207
+ int input_idx = thread_idx + base_index;
208
+ auto offsets = inp_calc.get(input_idx);
209
+ inputs_1[i] = input_data_1[offsets[0]];
210
+ inputs_2[i] = input_data_2[offsets[1]];
211
+
212
+ thread_idx += num_threads();
213
+ }
214
+
215
+ // compute and store
216
+ thread_idx = threadIdx.x;
217
+ #pragma unroll
218
+ for (int i = 0; i < thread_work_size(); i++) {
219
+ if (thread_idx >= remaining) {
220
+ break;
221
+ }
222
+ int input_idx = thread_idx + base_index;
223
+ auto offsets = out_calc.get(input_idx);
224
+ output_data[offsets[0]] = f(state, inputs_1[i], inputs_2[i]);
225
+ thread_idx += num_threads();
226
+ }
227
+ }
228
+
229
+ template <typename func_t>
230
+ void distribution_binary_kernel(TensorIteratorBase &iter, PhiloxCudaState philox_args, const func_t &f) {
231
+ static_assert(std::is_same_v<typename function_traits<func_t>::template arg<0>::type, curandStatePhilox4_32_10_t&>, "the first argument of functor must be curandStatePhilox4_32_10_t");
232
+ using input_t_1 = typename function_traits<func_t>::template arg<1>::type;
233
+ using input_t_2 = typename function_traits<func_t>::template arg<2>::type;
234
+ using output_t = typename function_traits<func_t>::result_type;
235
+
236
+ if (!iter.can_use_32bit_indexing()) {
237
+ for (auto& sub_iter : iter.with_32bit_indexing()) {
238
+ distribution_binary_kernel(sub_iter, philox_args, f);
239
+ }
240
+ return;
241
+ }
242
+
243
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(iter.can_use_32bit_indexing());
244
+
245
+ int64_t numel = iter.numel();
246
+ if (numel == 0) {
247
+ return;
248
+ }
249
+
250
+ output_t *output_data = static_cast<output_t *>(iter.data_ptr(0));
251
+ const input_t_1 *input_data_1 = static_cast<const input_t_1 *>(iter.data_ptr(1));
252
+ const input_t_2 *input_data_2 = static_cast<const input_t_2 *>(iter.data_ptr(2));
253
+
254
+ int64_t grid = (numel + block_work_size() - 1) / block_work_size();
255
+ auto stream = at::cuda::getCurrentCUDAStream();
256
+
257
+ if (iter.is_contiguous()) {
258
+ distribution_binary_elementwise_kernel<<<grid,num_threads(), 0, stream>>>(
259
+ numel, f, philox_args, output_data, input_data_1, input_data_2,
260
+ TrivialOffsetCalculator<2>(), TrivialOffsetCalculator<1>());
261
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
262
+ } else {
263
+ distribution_binary_elementwise_kernel<<<grid, num_threads(), 0, stream>>>(
264
+ numel, f, philox_args, output_data, input_data_1, input_data_2,
265
+ make_input_offset_calculator<2>(iter), make_output_offset_calculator(iter));
266
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
267
+ }
268
+ }
269
+
270
+ } // namespace
271
+ }} // namespace at::native
272
+
273
+
274
+ namespace at {
275
+ namespace native {
276
+ namespace templates {
277
+ namespace cuda {
278
+
279
+ // ==================================================== Random ========================================================
280
+
281
+ template<typename RNG>
282
+ void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG gen) {
283
+ #ifdef FBCODE_CAFFE2
284
+ AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cuda", AT_WRAP([&] {
285
+ if ((
286
+ std::is_same_v<scalar_t, int64_t> ||
287
+ std::is_same_v<scalar_t, double> ||
288
+ std::is_same_v<scalar_t, float> ||
289
+ std::is_same_v<scalar_t, at::BFloat16>) && range >= 1ULL << 32)
290
+ {
291
+ // define lambda to mod with range and add base
292
+ auto random_func = [range, base] __device__ (uint64_t rand) {
293
+ return transformation::uniform_int_from_to<scalar_t>(rand, range, base);
294
+ };
295
+ distribution_nullary_kernel<scalar_t, uint64_t, ulonglong2>(iter,
296
+ gen,
297
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 {
298
+ ulonglong2 ret;
299
+ uint4 rand_val = curand4(state);
300
+ ret.x = (static_cast<uint64_t>(rand_val.x) << 32) | rand_val.y;
301
+ ret.y = (static_cast<uint64_t>(rand_val.z) << 32) | rand_val.w;
302
+ return ret;
303
+ },
304
+ random_func);
305
+ } else {
306
+ auto random_func = [range, base] __device__ (uint32_t rand) {
307
+ return transformation::uniform_int_from_to<scalar_t>(rand, range, base);
308
+ };
309
+ distribution_nullary_kernel<scalar_t, uint32_t, uint4>(iter,
310
+ gen,
311
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 {
312
+ return curand4(state);
313
+ },
314
+ random_func);
315
+ }
316
+ }), AT_EXPAND(AT_ALL_TYPES), kBool, kHalf, kBFloat16, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES));
317
+ #else
318
+ AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cuda", AT_WRAP([&] {
319
+ if (range >= 1ULL << 28) // allow approx 5% skew in uniform int generation using %
320
+ {
321
+ // define lambda to mod with range and add base
322
+ auto random_func = [range, base] __device__ (uint64_t rand) {
323
+ return transformation::uniform_int_from_to<scalar_t>(rand, range, base);
324
+ };
325
+ distribution_nullary_kernel<scalar_t, uint64_t, ulonglong2>(iter,
326
+ gen,
327
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 {
328
+ ulonglong2 ret;
329
+ uint4 rand_val = curand4(state);
330
+ ret.x = (static_cast<uint64_t>(rand_val.x) << 32) | rand_val.y;
331
+ ret.y = (static_cast<uint64_t>(rand_val.z) << 32) | rand_val.w;
332
+ return ret;
333
+ },
334
+ random_func);
335
+ } else {
336
+ auto random_func = [range, base] __device__ (uint32_t rand) {
337
+ return transformation::uniform_int_from_to<scalar_t>(rand, range, base);
338
+ };
339
+ distribution_nullary_kernel<scalar_t, uint32_t, uint4>(iter,
340
+ gen,
341
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 {
342
+ return curand4(state);
343
+ },
344
+ random_func);
345
+ }
346
+ }), AT_EXPAND(AT_ALL_TYPES), kBool, kHalf, kBFloat16, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES));
347
+ #endif
348
+ }
349
+
350
+ // This is the special kernel to handle single specific case:
351
+ // from(inclusive) = std::numeric_limits<int64_t>::lowest()
352
+ // to(exclusive) = None (= std::numeric_limits<int64_t>::max() + 1)
353
+ template<typename RNG>
354
+ void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG gen) {
355
+ AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cuda", [&] {
356
+ if (std::is_same_v<scalar_t, int64_t> ||
357
+ std::is_same_v<scalar_t, double> ||
358
+ std::is_same_v<scalar_t, float> ||
359
+ std::is_same_v<scalar_t, at::BFloat16>) {
360
+ auto random_func = [] __device__ (uint64_t rand) {
361
+ return transformation::uniform_int_full_range<scalar_t>(rand);
362
+ };
363
+ distribution_nullary_kernel<scalar_t, uint64_t, ulonglong2>(iter,
364
+ gen,
365
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 {
366
+ ulonglong2 ret;
367
+ uint4 rand_val = curand4(state);
368
+ ret.x = (static_cast<uint64_t>(rand_val.x) << 32) | rand_val.y;
369
+ ret.y = (static_cast<uint64_t>(rand_val.z) << 32) | rand_val.w;
370
+ return ret;
371
+ },
372
+ random_func);
373
+ } else {
374
+ TORCH_CHECK(false, "random_full_64_bits_range_kernel_cuda handles only int64, double, float and bfloat16");
375
+ }
376
+ });
377
+ }
378
+
379
+ template<typename RNG>
380
+ struct RandomFromToKernel {
381
+ void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional<Generator> gen) {
382
+ random_from_to_kernel(iter, range, base, check_generator<RNG>(gen));
383
+ }
384
+ void operator()(TensorIteratorBase& iter, std::optional<Generator> gen) {
385
+ random_full_64_bits_range_kernel(iter, check_generator<RNG>(gen));
386
+ }
387
+ };
388
+
389
+ template<typename RNG>
390
+ void random_kernel(TensorIteratorBase& iter, RNG gen) {
391
+ AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cuda", [&] {
392
+ if (std::is_same_v<scalar_t, double> || std::is_same_v<scalar_t, int64_t>) {
393
+ auto random_func = [] __device__ (uint64_t rand) {
394
+ return transformation::uniform_int<scalar_t>(rand);
395
+ };
396
+ distribution_nullary_kernel<scalar_t, uint64_t, ulonglong2>(iter, gen,
397
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 {
398
+ ulonglong2 ret;
399
+ uint4 rand_val = curand4(state);
400
+ ret.x = (static_cast<uint64_t>(rand_val.x) << 32) | rand_val.y;
401
+ ret.y = (static_cast<uint64_t>(rand_val.z) << 32) | rand_val.w;
402
+ return ret;
403
+ },
404
+ random_func);
405
+ } else {
406
+ auto random_func = [] __device__ (uint32_t rand) {
407
+ return transformation::uniform_int<scalar_t>(rand);
408
+ };
409
+ distribution_nullary_kernel<scalar_t, uint32_t, uint4>(iter,
410
+ gen,
411
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 {
412
+ return curand4(state);
413
+ },
414
+ random_func);
415
+ }
416
+ });
417
+ }
418
+
419
+ template<typename RNG>
420
+ struct RandomKernel {
421
+ void operator()(TensorIteratorBase& iter, RNG gen) {
422
+ random_kernel(iter, gen);
423
+ }
424
+ };
425
+
426
+ // ====================================================================================================================
427
+
428
+ template<typename scalar_t, typename accscalar_t, typename RNG, typename transform_t>
429
+ void uniform_and_transform(TensorIteratorBase& iter, RNG gen, transform_t transform) {
430
+ if (std::is_same_v<scalar_t, double>) {
431
+ distribution_nullary_kernel<scalar_t, accscalar_t, double2>(iter,
432
+ gen,
433
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> double2 { return curand_uniform2_double(state); },
434
+ transform);
435
+ } else {
436
+ distribution_nullary_kernel<scalar_t, accscalar_t, float4>(iter,
437
+ gen,
438
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> float4 { return curand_uniform4(state); },
439
+ transform);
440
+ }
441
+ }
442
+
443
+ template<typename scalar_t, typename accscalar_t, typename RNG, typename transform_t>
444
+ void normal_and_transform(TensorIteratorBase& iter, RNG gen, transform_t transform) {
445
+ if (std::is_same_v<scalar_t, double>) {
446
+ distribution_nullary_kernel<scalar_t, accscalar_t, double2>(iter,
447
+ gen,
448
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> double2 { return curand_normal2_double(state); },
449
+ transform);
450
+ } else {
451
+ distribution_nullary_kernel<scalar_t, accscalar_t, float4>(iter,
452
+ gen,
453
+ [] __device__ (curandStatePhilox4_32_10_t* state) -> float4 { return curand_normal4(state); },
454
+ transform);
455
+ }
456
+ }
457
+
458
+ // ==================================================== Normal ========================================================
459
+
460
+ template<typename RNG>
461
+ void normal_kernel(const TensorBase &self, double mean_, double std_, RNG gen) {
462
+ auto iter = TensorIterator::borrowing_nullary_op(self);
463
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "normal_kernel_cuda", [&] {
464
+ using accscalar_t = at::acc_type<scalar_t, true>;
465
+ auto mean = static_cast<accscalar_t>(mean_);
466
+ auto std = static_cast<accscalar_t>(std_);
467
+ // define lambda to multiply std and add mean
468
+ auto normal_func = [mean, std] __device__ (accscalar_t rand) {
469
+ return static_cast<scalar_t>(transformation::normal<accscalar_t>(rand, mean, std));
470
+ };
471
+ normal_and_transform<scalar_t, accscalar_t>(iter, gen, normal_func);
472
+ });
473
+ }
474
+
475
+ template<typename RNG>
476
+ struct NormalKernel {
477
+ void operator()(const TensorBase &self, double mean, double std, std::optional<Generator> gen) {
478
+ normal_kernel(self, mean, std, check_generator<RNG>(gen));
479
+ }
480
+ };
481
+
482
+ // ==================================================== Uniform ========================================================
483
+
484
+ template<typename RNG>
485
+ void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG gen) {
486
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "uniform_kernel_cuda", [&] {
487
+ auto from = static_cast<scalar_t>(from_);
488
+ auto to = static_cast<scalar_t>(to_);
489
+ using opmath_t = at::opmath_type<scalar_t>;
490
+ auto range = static_cast<opmath_t>(to-from);
491
+ // define lambda to reverse bounds, multiply 'range' and add 'from_'
492
+ auto uniform_func = [range, from, to] __device__ (opmath_t rand) {
493
+ // Compute output value before reversing the bounds
494
+ // BEFORE TOUCHING THIS CODE READ: https://github.com/pytorch/pytorch/issues/96947
495
+ auto value = static_cast<scalar_t>(rand * range + from);
496
+ // reverse the bounds of curand4 from (0, 1] to [0, 1)
497
+ // Note that this method is from legacy THCTensorRandom and is likely to give
498
+ // you more 0-s, since, the probability of getting 1-s is higher than 0-s and
499
+ // by reversing the bounds, we are flipping the probabilities of 1-s and 0-s.
500
+ // BEFORE TOUCHING THIS CODE READ: https://github.com/pytorch/pytorch/issues/16706
501
+ auto reverse_bound_value = value == to ? from : value;
502
+ return reverse_bound_value;
503
+ };
504
+ uniform_and_transform<scalar_t, opmath_t>(iter, gen, uniform_func);
505
+ });
506
+ }
507
+
508
+ template<typename RNG>
509
+ struct UniformKernel {
510
+ void operator()(TensorIteratorBase& iter, double from, double to, std::optional<Generator> gen) {
511
+ uniform_kernel(iter, from, to, check_generator<RNG>(gen));
512
+ }
513
+ };
514
+
515
+ // ================================================== LogNormal =======================================================
516
+
517
+ template<typename RNG>
518
+ void log_normal_kernel(TensorIteratorBase& iter, double mean_, double std_, RNG gen) {
519
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cuda", [&] {
520
+ using accscalar_t = at::acc_type<scalar_t, true>;
521
+ auto mean = static_cast<accscalar_t>(mean_);
522
+ auto std = static_cast<accscalar_t>(std_);
523
+ // define lambda for log_normal transformation
524
+ auto log_normal_func = [mean, std] __device__ (accscalar_t rand) {
525
+ return static_cast<scalar_t>(transformation::log_normal<accscalar_t>(transformation::normal<accscalar_t>(rand, mean, std)));
526
+ };
527
+ normal_and_transform<scalar_t, accscalar_t>(iter, gen, log_normal_func);
528
+ });
529
+ }
530
+
531
+ template<typename RNG>
532
+ struct LogNormalKernel {
533
+ void operator()(TensorIteratorBase& iter, double mean, double std, std::optional<Generator> gen) {
534
+ log_normal_kernel(iter, mean, std, check_generator<RNG>(gen));
535
+ }
536
+ };
537
+
538
+ // =================================================== Geometric ======================================================
539
+
540
+ template<typename RNG>
541
+ void geometric_kernel(TensorIteratorBase& iter, double p, RNG gen) {
542
+ AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cuda", [&] {
543
+ using accscalar_t = at::DiscreteDistributionType<scalar_t>::type;
544
+ // define lambda for geometric transformation
545
+ auto geometric_func = [p] __device__ (accscalar_t rand) {
546
+ return static_cast<scalar_t>(transformation::geometric<accscalar_t>(rand, p));
547
+ };
548
+ uniform_and_transform<scalar_t, accscalar_t>(iter, gen, geometric_func);
549
+ });
550
+ }
551
+
552
+ template<typename RNG>
553
+ struct GeometricKernel {
554
+ void operator()(TensorIteratorBase& iter, double p, std::optional<Generator> gen) {
555
+ geometric_kernel(iter, p, check_generator<RNG>(gen));
556
+ }
557
+ };
558
+
559
+ // ================================================== Exponential =====================================================
560
+
561
+ template<typename RNG>
562
+ void exponential_kernel(TensorIteratorBase& iter, double lambda_, RNG gen) {
563
+ TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype());
564
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cuda", [&] {
565
+ using accscalar_t = at::acc_type<scalar_t, true>;
566
+ auto lambda = static_cast<accscalar_t>(lambda_);
567
+ // define lambda for exponential transformation
568
+ auto exponential_func = [lambda] __device__ (accscalar_t rand) {
569
+ return static_cast<scalar_t>(transformation::exponential<accscalar_t>(rand, lambda));
570
+ };
571
+ uniform_and_transform<scalar_t, accscalar_t>(iter, gen, exponential_func);
572
+ });
573
+ }
574
+
575
+ template<typename RNG>
576
+ struct ExponentialKernel {
577
+ void operator()(TensorIteratorBase& iter, double lambda, std::optional<Generator> gen) {
578
+ exponential_kernel(iter, lambda, check_generator<RNG>(gen));
579
+ }
580
+ };
581
+
582
+ // ==================================================== Cauchy ========================================================
583
+
584
+ template<typename RNG>
585
+ void cauchy_kernel(TensorIteratorBase& iter, double median_, double sigma_, RNG gen) {
586
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "cauchy_cuda", [&] {
587
+ using accscalar_t = at::acc_type<scalar_t, true>;
588
+ auto median = static_cast<accscalar_t>(median_);
589
+ auto sigma = static_cast<accscalar_t>(sigma_);
590
+ // define lambda for cauchy transformation
591
+ auto cauchy_func = [median, sigma] __device__ (accscalar_t rand) {
592
+ return static_cast<scalar_t>(transformation::cauchy<accscalar_t>(rand, median, sigma));
593
+ };
594
+ uniform_and_transform<scalar_t, accscalar_t>(iter, gen, cauchy_func);
595
+ });
596
+ }
597
+
598
+ template<typename RNG>
599
+ struct CauchyKernel {
600
+ void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional<Generator> gen) {
601
+ cauchy_kernel(iter, median, sigma, check_generator<RNG>(gen));
602
+ }
603
+ };
604
+
605
+ // ==================================================== Bernoulli =====================================================
606
+
607
+ template<typename scalar_t, typename prob_t>
608
+ void bernoulli_tensor_cuda_kernel(
609
+ const TensorBase &ret, const at::TensorBase &p,
610
+ PhiloxCudaState philox_args) {
611
+ auto functor = [philox_args] __device__(
612
+ int n, scalar_t& v1, scalar_t& v2, scalar_t& v3, scalar_t& v4,
613
+ const prob_t& p1, const prob_t& p2, const prob_t& p3, const prob_t& p4) {
614
+ auto seeds = at::cuda::philox::unpack(philox_args);
615
+ curandStatePhilox4_32_10_t state;
616
+ curand_init(std::get<0>(seeds),
617
+ blockIdx.x * blockDim.x + threadIdx.x,
618
+ std::get<1>(seeds),
619
+ &state);
620
+
621
+ // See Note [Register spilling in curand call for CUDA < 10]
622
+ float4 rand = curand_uniform4(&state);
623
+ switch (n) {
624
+ case 4: {
625
+ CUDA_KERNEL_ASSERT(0 <= p4 && p4 <= 1);
626
+ v4 = static_cast<scalar_t>(rand.w <= p4);
627
+ [[fallthrough]];
628
+ }
629
+ case 3: {
630
+ CUDA_KERNEL_ASSERT(0 <= p3 && p3 <= 1);
631
+ v3 = static_cast<scalar_t>(rand.z <= p3);
632
+ [[fallthrough]];
633
+ }
634
+ case 2: {
635
+ CUDA_KERNEL_ASSERT(0 <= p2 && p2 <= 1);
636
+ v2 = static_cast<scalar_t>(rand.y <= p2);
637
+ [[fallthrough]];
638
+ }
639
+ case 1: {
640
+ CUDA_KERNEL_ASSERT(0 <= p1 && p1 <= 1);
641
+ v1 = static_cast<scalar_t>(rand.x <= p1);
642
+ }
643
+ }
644
+ };
645
+ // The template argument `4` below indicates that we want to operate on four
646
+ // element at each time. See NOTE [ CUDA_tensor_applyN helpers ] for details.
647
+ at::cuda::CUDA_tensor_apply2<scalar_t, const prob_t, 4, decltype(functor),
648
+ /*max_threads_per_block=*/512,
649
+ /*min_blocks_per_sm==*/2>(ret, p, functor);
650
+ }
651
+
652
+ template<typename RNG>
653
+ void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG gen) {
654
+ PhiloxCudaState rng_engine_inputs;
655
+ {
656
+ // See Note [Acquire lock when using random generators]
657
+ std::lock_guard<std::mutex> lock(gen->mutex_);
658
+ rng_engine_inputs = gen->philox_cuda_state(10);
659
+ }
660
+ TORCH_CHECK(at::isFloatingType(p_.scalar_type()), "expected probabilities tensor to have floating type, got ", p_.scalar_type());
661
+ // cast probabilities tensor to double for double `self` tensor, and to `float` for everything else
662
+ const auto p_type = self.dtype() == at::kDouble ? at::kDouble : at::kFloat;
663
+ auto p_cuda = p_.to(TensorOptions().device(self.device()).dtype(p_type));
664
+ auto p = expand_inplace(self, p_cuda);
665
+ AT_DISPATCH_ALL_TYPES_AND3(
666
+ at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, self.scalar_type(), "bernoulli_tensor_cuda_self_", [&] {
667
+ if (std::is_same_v<scalar_t, double>) {
668
+ return bernoulli_tensor_cuda_kernel<double, double>(self, *p, rng_engine_inputs);
669
+ } else {
670
+ return bernoulli_tensor_cuda_kernel<scalar_t, float>(self, *p, rng_engine_inputs);
671
+ }
672
+ });
673
+ }
674
+
675
+ template<typename RNG>
676
+ void bernoulli_kernel(TensorIteratorBase& iter, double p, RNG gen) {
677
+ AT_DISPATCH_ALL_TYPES_AND3(
678
+ at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "bernoulli_scalar_cuda_", [&] {
679
+ using accscalar_t = at::DiscreteDistributionType<scalar_t>::type;
680
+ // define lambda for bernoulli transformation
681
+ auto bernoulli_func = [p] __device__ (accscalar_t rand) {
682
+ return static_cast<scalar_t>(transformation::bernoulli<accscalar_t>(rand, p));
683
+ };
684
+ uniform_and_transform<scalar_t, accscalar_t>(iter, gen, bernoulli_func);
685
+ });
686
+ }
687
+
688
+ template<typename RNG>
689
+ struct BernoulliKernel {
690
+ void operator()(TensorIteratorBase& iter, double p, std::optional<Generator> gen) {
691
+ bernoulli_kernel(iter, p, check_generator<RNG>(gen));
692
+ }
693
+ void operator()(const TensorBase &self, const TensorBase &p_, std::optional<Generator> gen) {
694
+ bernoulli_kernel(self, p_, check_generator<RNG>(gen));
695
+ }
696
+ };
697
+
698
+ }}}}
699
+
700
+ #else
701
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
702
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/Distributions.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at {
5
+ struct CUDAGeneratorImpl;
6
+ struct TensorIteratorBase;
7
+ class TensorBase;
8
+
9
+ namespace native {
10
+
11
+ void launch_poisson_cuda_kernel(
12
+ const TensorBase &ret, const TensorBase &lambda, CUDAGeneratorImpl *gen);
13
+
14
+ void launch_gamma_kernel(
15
+ const TensorBase &ret, const TensorBase &alpha, CUDAGeneratorImpl *gen);
16
+
17
+ void launch_binomial_cuda_kernel(
18
+ TensorIteratorBase &iter, CUDAGeneratorImpl *gen);
19
+
20
+ void launch_dirichlet_kernel(TensorIteratorBase &iter);
21
+
22
+ void launch_standard_gamma_grad_kernel(TensorIteratorBase &iter);
23
+
24
+ void launch_dirichlet_grad_kernel(TensorIteratorBase &iter);
25
+
26
+ }} // namespace at::native
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/EmbeddingBackwardKernel.cuh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/cuda/Atomic.cuh>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <ATen/TensorUtils.h>
7
+
8
+ namespace at::native {
9
+
10
+ Tensor embedding_backward_cuda_kernel(
11
+ const Tensor &grad,
12
+ const Tensor &orig_indices,
13
+ const Tensor &sorted_indices,
14
+ const Tensor &count,
15
+ int64_t num_weights,
16
+ int padding_idx = -1,
17
+ bool mode_mean = false,
18
+ const Tensor &offset2bag = Tensor(),
19
+ const Tensor &bag_size = Tensor(),
20
+ const Tensor &per_sample_weights = Tensor());
21
+
22
+ } // namespace at::native
23
+
24
+ #else
25
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
26
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/cuda/ForeachFunctors.cuh ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/OpMathType.h>
4
+ #include <ATen/native/ForeachUtils.h>
5
+ #include <ATen/native/cuda/MultiTensorApply.cuh>
6
+ #include <ATen/native/cuda/Pow.cuh>
7
+
8
+ namespace at::native {
9
+
10
+ namespace {
11
+
12
+ // TODO(crcrpar): Handle version bump in codegen.
13
+ // rel:
14
+ // https://github.com/pytorch/pytorch/blob/9cf84347767c8abb8feba18a9a1baba321eeb8b9/tools/autograd/gen_inplace_or_view_type.py#L481-L482
15
+ inline void increment_version(TensorList tensors) {
16
+ for (const auto& t : tensors) {
17
+ t.unsafeGetTensorImpl()->bump_version();
18
+ }
19
+ }
20
+
21
+ // Initializes args and checks if all args are aligned
22
+ template <int depth, typename T>
23
+ __device__ bool init_args(
24
+ T** args,
25
+ TensorListMetadata<depth>& tl,
26
+ const int64_t chunk_idx,
27
+ const int64_t chunk_size,
28
+ const int64_t tensor_loc) {
29
+ bool all_aligned = true;
30
+ for (int i = 0; i < depth; i++) {
31
+ args[i] = (T*)tl.addresses[i][tensor_loc];
32
+ args[i] += chunk_idx * chunk_size;
33
+
34
+ if (!is_aligned(args[i])) {
35
+ all_aligned = false;
36
+ }
37
+ }
38
+ return all_aligned;
39
+ }
40
+
41
+ // Initializes args and checks if all args are aligned
42
+ template <int depth, typename T, typename T2>
43
+ __device__ bool init_args(
44
+ T** args,
45
+ TensorListScalarListMetadata<T2, depth>& tl,
46
+ const int64_t chunk_idx,
47
+ const int64_t chunk_size,
48
+ const int64_t tensor_loc) {
49
+ bool all_aligned = true;
50
+ for (int i = 0; i < depth; i++) {
51
+ args[i] = (T*)tl.addresses[i][tensor_loc];
52
+ args[i] += chunk_idx * chunk_size;
53
+
54
+ if (!is_aligned(args[i])) {
55
+ all_aligned = false;
56
+ }
57
+ }
58
+ return all_aligned;
59
+ }
60
+
61
+ template <int depth, typename T>
62
+ __device__ bool init_args(
63
+ T** args,
64
+ FusedOptimizerTensorListMetadata<depth>& tl,
65
+ const int64_t chunk_idx,
66
+ const int64_t chunk_size,
67
+ const int64_t tensor_loc) {
68
+ bool all_aligned = true;
69
+ for (int i = 0; i < depth; i++) {
70
+ args[i] = (T*)tl.addresses[i][tensor_loc];
71
+ args[i] += chunk_idx * chunk_size;
72
+
73
+ if (!is_aligned(args[i])) {
74
+ all_aligned = false;
75
+ }
76
+ }
77
+ return all_aligned;
78
+ }
79
+
80
+ template <int depth, typename T>
81
+ __device__ void load_args(
82
+ T r_args[][kILP],
83
+ T** args,
84
+ const int64_t i_start,
85
+ const int64_t chunk_size,
86
+ const int64_t n) {
87
+ #pragma unroll
88
+ for (int ii = 0; ii < kILP; ii++) {
89
+ const auto i = i_start + threadIdx.x + ii * blockDim.x;
90
+ for (int r_index = 0; r_index < depth; r_index++) {
91
+ r_args[r_index][ii] = 0;
92
+ if (i < n && i < chunk_size) {
93
+ r_args[r_index][ii] = args[r_index][i];
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ template <typename T>
100
+ __device__ void store_args(
101
+ T* dst,
102
+ T* src,
103
+ const int64_t i_start,
104
+ const int64_t chunk_size,
105
+ const int64_t n) {
106
+ #pragma unroll
107
+ for (int ii = 0; ii < kILP; ii++) {
108
+ const int64_t i = i_start + threadIdx.x + ii * blockDim.x;
109
+ if (i < n && i < chunk_size)
110
+ dst[i] = src[ii];
111
+ }
112
+ }
113
+
114
+ template <int res_arg_index, typename Op, typename T, typename opmath_t>
115
+ __device__ __forceinline__ void binary_op_scalar(
116
+ T r_args[][kILP],
117
+ T** args,
118
+ opmath_t scalar,
119
+ const int64_t n,
120
+ const int64_t chunk_size,
121
+ const bool all_aligned,
122
+ Op op) {
123
+ // to make things simple, we put aligned case in a different code path
124
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
125
+ for (int64_t i_start = threadIdx.x;
126
+ i_start * kILP < n && i_start * kILP < chunk_size;
127
+ i_start += blockDim.x) {
128
+ // load
129
+ load_store(r_args[0], args[0], 0, i_start);
130
+ #pragma unroll
131
+ for (int ii = 0; ii < kILP; ii++) {
132
+ r_args[0][ii] = static_cast<T>(
133
+ op(static_cast<opmath_t>(r_args[0][ii]),
134
+ static_cast<opmath_t>(scalar)));
135
+ }
136
+ // store
137
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
138
+ }
139
+ } else {
140
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
141
+ i_start += blockDim.x * kILP) {
142
+ // Regardless if depth is 1 (for inplace) or 2 (for out of place), r_args
143
+ // has depth 1
144
+ load_args<1>(r_args, args, i_start, chunk_size, n);
145
+ #pragma unroll
146
+ for (int ii = 0; ii < kILP; ii++) {
147
+ r_args[0][ii] = static_cast<T>(
148
+ op(static_cast<opmath_t>(r_args[0][ii]),
149
+ static_cast<opmath_t>(scalar)));
150
+ }
151
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
152
+ }
153
+ }
154
+ }
155
+
156
+ template <int res_arg_index, typename Op, typename T, typename opmath_t>
157
+ __device__ __forceinline__ void pointwise_op_scalar(
158
+ T r_args[][kILP],
159
+ T** args,
160
+ opmath_t scalar,
161
+ const int64_t n,
162
+ const int64_t chunk_size,
163
+ const bool all_aligned,
164
+ Op op) {
165
+ // to make things simple, we put aligned case in a different code path
166
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
167
+ for (int64_t i_start = threadIdx.x;
168
+ i_start * kILP < n && i_start * kILP < chunk_size;
169
+ i_start += blockDim.x) {
170
+ // load
171
+ load_store(r_args[0], args[0], 0, i_start);
172
+ load_store(r_args[1], args[1], 0, i_start);
173
+ load_store(r_args[2], args[2], 0, i_start);
174
+ #pragma unroll
175
+ for (int ii = 0; ii < kILP; ii++) {
176
+ r_args[0][ii] = static_cast<T>(
177
+ static_cast<opmath_t>(r_args[0][ii]) +
178
+ scalar *
179
+ op(static_cast<opmath_t>(r_args[1][ii]),
180
+ static_cast<opmath_t>(r_args[2][ii])));
181
+ }
182
+ // store
183
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
184
+ }
185
+ } else {
186
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
187
+ i_start += blockDim.x * kILP) {
188
+ // Regardless if depth is 3 (for inplace) or 4 (for out of place), r_args
189
+ // has depth 3
190
+ load_args<3>(r_args, args, i_start, chunk_size, n);
191
+ #pragma unroll
192
+ for (int ii = 0; ii < kILP; ii++) {
193
+ r_args[0][ii] = static_cast<T>(
194
+ static_cast<opmath_t>(r_args[0][ii]) +
195
+ scalar *
196
+ op(static_cast<opmath_t>(r_args[1][ii]),
197
+ static_cast<opmath_t>(r_args[2][ii])));
198
+ }
199
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
200
+ }
201
+ }
202
+ }
203
+
204
+ //
205
+ // Binary Functors
206
+ //
207
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
208
+ struct BinaryOpScalarFunctor {
209
+ using opmath_t = at::opmath_type<T>;
210
+ template <typename Op>
211
+ __device__ __forceinline__ void operator()(
212
+ int64_t chunk_size,
213
+ TensorListMetadata<depth>& tl,
214
+ Op op,
215
+ opmath_t scalar) {
216
+ const int tensor_loc = tl.block_to_tensor[blockIdx.x];
217
+ const int chunk_idx = tl.block_to_chunk[blockIdx.x];
218
+ auto n = tl.numel_for_tensor[tensor_loc];
219
+
220
+ T* args[depth];
221
+ const bool all_aligned =
222
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
223
+ n -= chunk_idx * chunk_size;
224
+ T r_args[r_args_depth][kILP];
225
+
226
+ binary_op_scalar<res_arg_index>(
227
+ r_args, args, scalar, n, chunk_size, all_aligned, op);
228
+ }
229
+ };
230
+
231
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
232
+ struct BinaryOpScalarListFunctor {
233
+ using opmath_t = at::opmath_type<T>;
234
+ template <typename Op>
235
+ __device__ __forceinline__ void operator()(
236
+ int64_t chunk_size,
237
+ TensorListScalarListMetadata<opmath_t, depth>& tl,
238
+ Op op) {
239
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
240
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
241
+ auto n = tl.numel_for_tensor[tensor_loc];
242
+
243
+ T* args[depth];
244
+ const bool all_aligned =
245
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
246
+ opmath_t scalar = tl.scalar_vals[tensor_loc];
247
+ n -= chunk_idx * chunk_size;
248
+ T r_args[r_args_depth][kILP];
249
+
250
+ binary_op_scalar<res_arg_index>(
251
+ r_args, args, scalar, n, chunk_size, all_aligned, op);
252
+ }
253
+ };
254
+
255
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
256
+ struct BinaryOpListAlphaFunctor {
257
+ using opmath_t = at::opmath_type<T>;
258
+ template <typename Op>
259
+ __device__ __forceinline__ void operator()(
260
+ int64_t chunk_size,
261
+ TensorListMetadata<depth>& tl,
262
+ Op op,
263
+ opmath_t alpha) {
264
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
265
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
266
+ auto n = tl.numel_for_tensor[tensor_loc];
267
+
268
+ T* args[depth];
269
+ const bool all_aligned =
270
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
271
+ n -= chunk_idx * chunk_size;
272
+ T r_args[r_args_depth][kILP];
273
+
274
+ // to make things simple, we put aligned case in a different code path
275
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
276
+ for (int64_t i_start = threadIdx.x;
277
+ i_start * kILP < n && i_start * kILP < chunk_size;
278
+ i_start += blockDim.x) {
279
+ // load
280
+ load_store(r_args[0], args[0], 0, i_start);
281
+ load_store(r_args[1], args[1], 0, i_start);
282
+ #pragma unroll
283
+ for (int ii = 0; ii < kILP; ii++) {
284
+ r_args[0][ii] = static_cast<T>(
285
+ op(static_cast<opmath_t>(r_args[0][ii]),
286
+ alpha * static_cast<opmath_t>(r_args[1][ii])));
287
+ }
288
+ // store
289
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
290
+ }
291
+ } else {
292
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
293
+ i_start += blockDim.x * kILP) {
294
+ load_args<r_args_depth>(r_args, args, i_start, chunk_size, n);
295
+ #pragma unroll
296
+ for (int ii = 0; ii < kILP; ii++) {
297
+ r_args[0][ii] = static_cast<T>(
298
+ op(static_cast<opmath_t>(r_args[0][ii]),
299
+ alpha * static_cast<opmath_t>(r_args[1][ii])));
300
+ }
301
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
302
+ }
303
+ }
304
+ }
305
+ };
306
+
307
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
308
+ struct BinaryOpScalarTensorFunctor {
309
+ using opmath_t = at::opmath_type<T>;
310
+ template <typename Op>
311
+ __device__ __forceinline__ void operator()(
312
+ int64_t chunk_size,
313
+ TensorListMetadata<depth>& tl,
314
+ Op op,
315
+ T* scalar,
316
+ opmath_t alpha) {
317
+ const int tensor_loc = tl.block_to_tensor[blockIdx.x];
318
+ const int chunk_idx = tl.block_to_chunk[blockIdx.x];
319
+ auto n = tl.numel_for_tensor[tensor_loc];
320
+
321
+ T* args[depth];
322
+ const bool all_aligned =
323
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
324
+ n -= chunk_idx * chunk_size;
325
+ T r_args[r_args_depth][kILP];
326
+
327
+ // to make things simple, we put aligned case in a different code path
328
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
329
+ for (int64_t i_start = threadIdx.x;
330
+ i_start * kILP < n && i_start * kILP < chunk_size;
331
+ i_start += blockDim.x) {
332
+ // load
333
+ load_store(r_args[0], args[0], 0, i_start);
334
+ #pragma unroll
335
+ for (int ii = 0; ii < kILP; ii++) {
336
+ r_args[0][ii] = static_cast<T>(op(
337
+ static_cast<opmath_t>(r_args[0][ii]),
338
+ static_cast<opmath_t>(alpha) * static_cast<opmath_t>(*scalar)));
339
+ }
340
+ // store
341
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
342
+ }
343
+ } else {
344
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
345
+ i_start += blockDim.x * kILP) {
346
+ // Regardless if depth is 1 (for inplace) or 2 (for out of place),
347
+ // r_args has depth 1
348
+ load_args<1>(r_args, args, i_start, chunk_size, n);
349
+ #pragma unroll
350
+ for (int ii = 0; ii < kILP; ii++) {
351
+ r_args[0][ii] = static_cast<T>(op(
352
+ static_cast<opmath_t>(r_args[0][ii]),
353
+ static_cast<opmath_t>(alpha) * static_cast<opmath_t>(*scalar)));
354
+ }
355
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
356
+ }
357
+ }
358
+ }
359
+ };
360
+
361
+ //
362
+ // Unary Functors
363
+ //
364
+
365
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
366
+ struct ZeroFunctor {
367
+ __device__ __forceinline__ void operator()(
368
+ int64_t chunk_size,
369
+ TensorListMetadata<1>& tl) {
370
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
371
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
372
+ auto n = tl.numel_for_tensor[tensor_loc];
373
+
374
+ T* args[depth];
375
+ const auto all_aligned =
376
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
377
+ n -= chunk_idx * chunk_size;
378
+ T r_args[r_args_depth][kILP];
379
+
380
+ // to make things simple, we put aligned case in a different code path
381
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
382
+ for (int64_t i_start = threadIdx.x;
383
+ i_start * kILP < n && i_start * kILP < chunk_size;
384
+ i_start += blockDim.x) {
385
+ #pragma unroll
386
+ for (int ii = 0; ii < kILP; ii++) {
387
+ r_args[0][ii] = 0;
388
+ }
389
+ // store
390
+ load_store(args[0], r_args[0], i_start, 0);
391
+ }
392
+ } else {
393
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
394
+ i_start += blockDim.x * kILP) {
395
+ #pragma unroll
396
+ for (int ii = 0; ii < kILP; ii++) {
397
+ r_args[0][ii] = 0;
398
+ }
399
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
400
+ }
401
+ }
402
+ }
403
+ };
404
+
405
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
406
+ struct UnaryOpFunctor {
407
+ using opmath_t = at::opmath_type<T>;
408
+ template <typename Op>
409
+ __device__ __forceinline__ void operator()(
410
+ int64_t chunk_size,
411
+ TensorListMetadata<depth>& tl,
412
+ Op op) {
413
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
414
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
415
+ auto n = tl.numel_for_tensor[tensor_loc];
416
+
417
+ T* args[depth];
418
+ bool all_aligned =
419
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
420
+ n -= chunk_idx * chunk_size;
421
+ T r_args[r_args_depth][kILP];
422
+
423
+ // to make things simple, we put aligned case in a different code path
424
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
425
+ for (int64_t i_start = threadIdx.x;
426
+ i_start * kILP < n && i_start * kILP < chunk_size;
427
+ i_start += blockDim.x) {
428
+ // load
429
+ load_store(r_args[0], args[0], 0, i_start);
430
+ #pragma unroll
431
+ for (int ii = 0; ii < kILP; ii++) {
432
+ r_args[0][ii] =
433
+ static_cast<T>(op(static_cast<opmath_t>(r_args[0][ii])));
434
+ }
435
+ // store
436
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
437
+ }
438
+ } else {
439
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
440
+ i_start += blockDim.x * kILP) {
441
+ load_args<r_args_depth>(r_args, args, i_start, chunk_size, n);
442
+ #pragma unroll
443
+ for (int ii = 0; ii < kILP; ii++) {
444
+ r_args[0][ii] =
445
+ static_cast<T>(op(static_cast<opmath_t>(r_args[0][ii])));
446
+ }
447
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
448
+ }
449
+ }
450
+ }
451
+ };
452
+
453
+ //
454
+ // Pointwise Functors
455
+ //
456
+
457
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
458
+ struct PointwiseOpScalarFunctor {
459
+ using opmath_t = at::opmath_type<T>;
460
+ template <typename Op>
461
+ __device__ __forceinline__ void operator()(
462
+ int64_t chunk_size,
463
+ TensorListMetadata<depth>& tl,
464
+ Op op,
465
+ opmath_t scalar) {
466
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
467
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
468
+ auto n = tl.numel_for_tensor[tensor_loc];
469
+
470
+ T* args[depth];
471
+ const bool all_aligned =
472
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
473
+ n -= chunk_idx * chunk_size;
474
+ T r_args[r_args_depth][kILP];
475
+
476
+ pointwise_op_scalar<res_arg_index>(
477
+ r_args, args, scalar, n, chunk_size, all_aligned, op);
478
+ }
479
+ };
480
+
481
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
482
+ struct PointwiseOpScalarListFunctor {
483
+ using opmath_t = at::opmath_type<T>;
484
+ template <typename Op>
485
+ __device__ __forceinline__ void operator()(
486
+ int64_t chunk_size,
487
+ TensorListScalarListMetadata<opmath_t, depth>& tl,
488
+ Op op) {
489
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
490
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
491
+ auto n = tl.numel_for_tensor[tensor_loc];
492
+
493
+ T* args[depth];
494
+ const bool all_aligned =
495
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
496
+ opmath_t scalar = tl.scalar_vals[tensor_loc];
497
+ n -= chunk_idx * chunk_size;
498
+ T r_args[r_args_depth][kILP];
499
+
500
+ pointwise_op_scalar<res_arg_index>(
501
+ r_args, args, scalar, n, chunk_size, all_aligned, op);
502
+ }
503
+ };
504
+
505
+ template <typename T, int depth>
506
+ struct PointwiseOpListFunctor {
507
+ using opmath_t = at::opmath_type<T>;
508
+ template <typename Op>
509
+ __device__ __forceinline__ void operator()(
510
+ int64_t chunk_size,
511
+ TensorListMetadata<depth>& tl,
512
+ Op op) {
513
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
514
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
515
+ auto n = tl.numel_for_tensor[tensor_loc];
516
+
517
+ T* args[depth];
518
+ const bool all_aligned =
519
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
520
+ n -= chunk_idx * chunk_size;
521
+ T r_args[depth - 1][kILP];
522
+
523
+ // to make things simple, we put aligned case in a different code path
524
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
525
+ for (int64_t i_start = threadIdx.x;
526
+ i_start * kILP < n && i_start * kILP < chunk_size;
527
+ i_start += blockDim.x) {
528
+ // load
529
+ load_store(r_args[0], args[0], 0, i_start);
530
+ load_store(r_args[1], args[1], 0, i_start);
531
+ #pragma unroll
532
+ for (int ii = 0; ii < kILP; ii++) {
533
+ r_args[0][ii] = static_cast<T>(
534
+ op(static_cast<opmath_t>(r_args[0][ii]),
535
+ static_cast<opmath_t>(r_args[1][ii])));
536
+ }
537
+ // store
538
+ load_store(args[2], r_args[0], i_start, 0);
539
+ }
540
+ } else {
541
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
542
+ i_start += blockDim.x * kILP) {
543
+ load_args<depth - 1>(r_args, args, i_start, chunk_size, n);
544
+ #pragma unroll
545
+ for (int ii = 0; ii < kILP; ii++) {
546
+ r_args[0][ii] = static_cast<T>(
547
+ op(static_cast<opmath_t>(r_args[0][ii]),
548
+ static_cast<opmath_t>(r_args[1][ii])));
549
+ }
550
+ store_args(args[2], r_args[0], i_start, chunk_size, n);
551
+ }
552
+ }
553
+ }
554
+ };
555
+
556
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
557
+ struct TernaryOpListFunctor {
558
+ using opmath_t = at::opmath_type<T>;
559
+ template <typename Op>
560
+ __device__ __forceinline__ void operator()(
561
+ int64_t chunk_size,
562
+ TensorListMetadata<depth>& tl,
563
+ Op op) {
564
+ static_assert(depth == 3 || depth == 4, "");
565
+ static_assert(depth >= r_args_depth, "");
566
+ static_assert(res_arg_index == depth - 1 || res_arg_index == 0, "");
567
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
568
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
569
+ auto n = tl.numel_for_tensor[tensor_loc];
570
+
571
+ T* args[depth];
572
+ const bool all_aligned =
573
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
574
+ n -= chunk_idx * chunk_size;
575
+ T r_args[r_args_depth][kILP];
576
+
577
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
578
+ for (int64_t i_start = threadIdx.x;
579
+ i_start * kILP < n && i_start * kILP < chunk_size;
580
+ i_start += blockDim.x) {
581
+ load_store(r_args[0], args[0], 0, i_start);
582
+ load_store(r_args[1], args[1], 0, i_start);
583
+ load_store(r_args[2], args[2], 0, i_start);
584
+ #pragma unroll
585
+ for (int ii = 0; ii < kILP; ii++) {
586
+ r_args[0][ii] =
587
+ op(static_cast<opmath_t>(r_args[0][ii]),
588
+ static_cast<opmath_t>(r_args[1][ii]),
589
+ static_cast<opmath_t>(r_args[2][ii]));
590
+ }
591
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
592
+ }
593
+ } else {
594
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
595
+ i_start += blockDim.x * kILP) {
596
+ load_args<r_args_depth>(r_args, args, i_start, chunk_size, n);
597
+ #pragma unroll
598
+ for (int ii = 0; ii < kILP; ii++) {
599
+ r_args[0][ii] =
600
+ op(static_cast<opmath_t>(r_args[0][ii]),
601
+ static_cast<opmath_t>(r_args[1][ii]),
602
+ static_cast<opmath_t>(r_args[2][ii]));
603
+ }
604
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
605
+ }
606
+ }
607
+ }
608
+ };
609
+
610
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
611
+ struct TernaryOpScalarFunctor {
612
+ using opmath_t = at::opmath_type<T>;
613
+ template <typename Op>
614
+ __device__ __forceinline__ void operator()(
615
+ int64_t chunk_size,
616
+ TensorListMetadata<depth>& tl,
617
+ Op op,
618
+ opmath_t alpha) {
619
+ static_assert(depth == 2 || depth == 3, "");
620
+ static_assert(depth >= r_args_depth, "");
621
+ static_assert(res_arg_index == depth - 1 || res_arg_index == 0, "");
622
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
623
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
624
+ auto n = tl.numel_for_tensor[tensor_loc];
625
+
626
+ T* args[depth];
627
+ const bool all_aligned =
628
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
629
+ n -= chunk_idx * chunk_size;
630
+ T r_args[r_args_depth][kILP];
631
+
632
+ // to make things simple, we put aligned case in a different code path
633
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
634
+ for (int64_t i_start = threadIdx.x;
635
+ i_start * kILP < n && i_start * kILP < chunk_size;
636
+ i_start += blockDim.x) {
637
+ // load
638
+ load_store(r_args[0], args[0], 0, i_start);
639
+ load_store(r_args[1], args[1], 0, i_start);
640
+ #pragma unroll
641
+ for (int ii = 0; ii < kILP; ii++) {
642
+ r_args[0][ii] =
643
+ op(static_cast<opmath_t>(r_args[0][ii]),
644
+ static_cast<opmath_t>(r_args[1][ii]),
645
+ alpha);
646
+ }
647
+ // store
648
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
649
+ }
650
+ } else {
651
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
652
+ i_start += blockDim.x * kILP) {
653
+ load_args<r_args_depth>(r_args, args, i_start, chunk_size, n);
654
+ #pragma unroll
655
+ for (int ii = 0; ii < kILP; ii++) {
656
+ r_args[0][ii] =
657
+ op(static_cast<opmath_t>(r_args[0][ii]),
658
+ static_cast<opmath_t>(r_args[1][ii]),
659
+ alpha);
660
+ }
661
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
662
+ }
663
+ }
664
+ }
665
+ };
666
+
667
+ template <typename T, int depth, int r_args_depth, int res_arg_index>
668
+ struct TernaryOpScalarListFunctor {
669
+ using opmath_t = at::opmath_type<T>;
670
+ template <typename Op>
671
+ __device__ __forceinline__ void operator()(
672
+ int64_t chunk_size,
673
+ TensorListScalarListMetadata<opmath_t, depth>& tl,
674
+ Op op) {
675
+ static_assert(depth == 2 || depth == 3, "");
676
+ static_assert(depth >= r_args_depth, "");
677
+ static_assert(res_arg_index == depth - 1 || res_arg_index == 0, "");
678
+ const auto tensor_loc = tl.block_to_tensor[blockIdx.x];
679
+ const auto chunk_idx = tl.block_to_chunk[blockIdx.x];
680
+ auto n = tl.numel_for_tensor[tensor_loc];
681
+
682
+ T* args[depth];
683
+ const bool all_aligned =
684
+ init_args<depth>(args, tl, chunk_idx, chunk_size, tensor_loc);
685
+ n -= chunk_idx * chunk_size;
686
+ T r_args[r_args_depth][kILP];
687
+ const opmath_t scalar = tl.scalar_vals[tensor_loc];
688
+
689
+ // to make things simple, we put aligned case in a different code path
690
+ if (n % kILP == 0 && chunk_size % kILP == 0 && all_aligned) {
691
+ for (int64_t i_start = threadIdx.x;
692
+ i_start * kILP < n && i_start * kILP < chunk_size;
693
+ i_start += blockDim.x) {
694
+ // load
695
+ load_store(r_args[0], args[0], 0, i_start);
696
+ load_store(r_args[1], args[1], 0, i_start);
697
+ #pragma unroll
698
+ for (int ii = 0; ii < kILP; ii++) {
699
+ r_args[0][ii] =
700
+ op(static_cast<opmath_t>(r_args[0][ii]),
701
+ static_cast<opmath_t>(r_args[1][ii]),
702
+ scalar);
703
+ }
704
+ // store
705
+ load_store(args[res_arg_index], r_args[0], i_start, 0);
706
+ }
707
+ } else {
708
+ for (int64_t i_start = 0; i_start < n && i_start < chunk_size;
709
+ i_start += blockDim.x * kILP) {
710
+ load_args<r_args_depth>(r_args, args, i_start, chunk_size, n);
711
+ #pragma unroll
712
+ for (int ii = 0; ii < kILP; ii++) {
713
+ r_args[0][ii] =
714
+ op(static_cast<opmath_t>(r_args[0][ii]),
715
+ static_cast<opmath_t>(r_args[1][ii]),
716
+ scalar);
717
+ }
718
+ store_args(args[res_arg_index], r_args[0], i_start, chunk_size, n);
719
+ }
720
+ }
721
+ }
722
+ };
723
+
724
+ template <typename T>
725
+ struct power_functor {
726
+ C10_DEVICE T operator()(const T& a, const T& b) const {
727
+ return at::native::pow_(a, b);
728
+ }
729
+ };
730
+
731
+ template <typename T>
732
+ struct reverse_power_functor {
733
+ C10_DEVICE T operator()(const T& a, const T& b) const {
734
+ return at::native::pow_(b, a);
735
+ }
736
+ };
737
+
738
+ } // namespace
739
+ } // namespace at::native
740
+
741
+ #else
742
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
743
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)