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

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchedFallback.h +81 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h +169 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h +126 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/DynamicLayer.h +124 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h +22 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/Interpreter.h +209 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h +187 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/Macros.h +3 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/PlumbingHelper.h +63 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/TensorWrapper.h +103 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/VmapInterpreter.h +25 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Descriptors.h +149 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Exceptions.h +41 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Handle.h +9 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Types.h +12 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Utils.h +18 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/miopen-wrapper.h +21 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/EmptyTensor.h +28 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/IndexKernels.h +220 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSAllocator.h +438 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h +68 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSDevice.h +73 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSEvent.h +105 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h +61 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSGuardImpl.h +179 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSHooks.h +69 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSProfiler.h +467 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSStream.h +158 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Activation.h +73 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/AdaptivePooling.h +49 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/AmpKernels.h +28 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +321 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BinaryOps.h +119 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BucketizationUtils.h +173 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CPUBlas.h +279 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CPUFallback.h +46 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CanUse32BitIndexMath.h +13 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ComplexHelper.h +97 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h +34 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h +263 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ConvUtils.h +440 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ConvolutionMM3d.h +14 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Copy.h +20 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Cross.h +14 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h +229 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DispatchStub.h +478 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Distance.h +20 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DistributionTemplates.h +394 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Distributions.h +518 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/EmbeddingBag.h +153 -0
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchedFallback.h ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/ATen.h>
9
+ #include <ATen/core/op_registration/op_registration.h>
10
+ #include <torch/library.h>
11
+
12
+ namespace at::functorch {
13
+
14
+ // This file contains code for the vmap fallback (also known as the
15
+ // BatchedTensor fallback or the Batched fallback). This code runs
16
+ // when an operation doesn't have a batching rule implemented.
17
+
18
+ // If an operator doesn't have a batching rule implemented then we fallback
19
+ // to this implementation. The fallback doesn't work on out= variants or
20
+ // view operations; that is, it works for out-of-place operations and
21
+ // in-place non-view operations.
22
+ //
23
+ // For out-of-place operations, the fallback effectively takes all of the
24
+ // BatchedTensors in `stack`, slices them, and runs `op` on all of the
25
+ // corresponding slices to produce slices of the outputs. The output slices
26
+ // then get `torch.stack`ed to create the
27
+ // final returns.
28
+ //
29
+ // The performance of the fallback is not very good because it introduces an
30
+ // extra copy from stacking the sliced outputs. Because of this, we prefer to
31
+ // write batching rules for operators whenever possible.
32
+ void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
33
+ void batchedNestedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
34
+
35
+ void vmapErrorFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
36
+
37
+ // The vmap fallback emits a warning by default, but it may be disabled if
38
+ // the user finds it to be too annoying.
39
+ TORCH_API bool isVmapFallbackWarningEnabled();
40
+ TORCH_API void setVmapFallbackWarningEnabled(bool enabled);
41
+
42
+ // Used for testing. The vmap fallback is enabled by default. When it is disabled,
43
+ // it raises an error.
44
+ TORCH_API bool isVmapFallbackEnabled();
45
+ TORCH_API void setVmapFallbackEnabled(bool enabled);
46
+
47
+ template <typename A> A vector_to_result(const std::vector<IValue>& buffer) {
48
+ return buffer[0].to<A>();
49
+ }
50
+ template <typename A, typename B> std::tuple<A, B> vector_to_result(const std::vector<IValue>& buffer) {
51
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>());
52
+ }
53
+ template <typename A, typename B, typename C> std::tuple<A, B, C> vector_to_result(const std::vector<IValue>& buffer) {
54
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>(), buffer[2].to<B>());
55
+ }
56
+
57
+ // slow_fallback is a way to call the vmap fallback inside some boxed kernel.
58
+ // There is probably some better way to metaprogram this.
59
+ template <typename Ret>
60
+ Ret slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
61
+ std::vector<IValue> stack(args.begin(), args.end());
62
+ batchedTensorForLoopFallback(op, &stack);
63
+ return vector_to_result<Ret>(stack);
64
+ }
65
+
66
+ template <typename A, typename B>
67
+ std::tuple<A, B> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
68
+ std::vector<IValue> stack(args.begin(), args.end());
69
+ batchedTensorForLoopFallback(op, &stack);
70
+ return vector_to_result<A, B>(stack);
71
+ }
72
+
73
+ template <typename A, typename B, typename C>
74
+ std::tuple<A, B, C> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
75
+ std::vector<IValue> stack(args.begin(), args.end());
76
+ batchedTensorForLoopFallback(op, &stack);
77
+ return vector_to_result<A, B, C>(stack);
78
+ }
79
+
80
+
81
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <bitset>
10
+
11
+ #include <ATen/ArrayRef.h>
12
+ #include <ATen/SmallVector.h>
13
+ #include <ATen/Tensor.h>
14
+
15
+ namespace at::functorch {
16
+
17
+ using Tensor = at::Tensor;
18
+
19
+ // We assume this in a few other places in the codebase,
20
+ // but there isn't a centralized definition.
21
+ constexpr int64_t kVmapMaxTensorDims = 64;
22
+
23
+ // The valid vmap levels range from [0, 64). This effectively means that we
24
+ // support a maximum of 64 nested vmaps.
25
+ constexpr int64_t kVmapNumLevels = 64;
26
+
27
+ // Store this number of elements of BatchDims on the stack. Most people will
28
+ // probably use <= 5 nested vmaps, but adjust this number as necessary.
29
+ constexpr int64_t kBatchDimsStackSize = 5;
30
+
31
+ // A BatchedTensorImpl holds an underlying Tensor and a single batch dim
32
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
33
+ // BatchedTensorImpl.
34
+ //
35
+ // The batch dimensions are treated as being "private"; they are not user-visible.
36
+ // For example, in the following Tensor,
37
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
38
+ // dimension 0 is batch dimension.
39
+ //
40
+ // bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public)
41
+ // dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7) tensor.
42
+ struct TORCH_API BatchedTensorImpl : public c10::TensorImpl {
43
+ explicit BatchedTensorImpl(at::DispatchKeySet key_set, Tensor value, int64_t dim, int64_t level);
44
+
45
+ // Returns batch dimension of this tensor
46
+ int64_t bdim() const { return bdim_; }
47
+
48
+ // Returns batch dimension of this tensor
49
+ int64_t level() const { return level_; }
50
+
51
+ // BatchedTensorImpl wraps a Tensor
52
+ const Tensor& value() const { return value_; }
53
+
54
+ // Given a public dimension index, return the dimension index in the underlying
55
+ // value() tensor.
56
+ // For example, if we have
57
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
58
+ // bt.actualDim(0) -> 1
59
+ // bt.actualDim(1) -> 2
60
+ // bt.actualDim(2) -> 3
61
+ // bt.actualDim(3) -> Error
62
+ int64_t actualDim(int64_t dim, bool wrap_dim = true) const;
63
+
64
+ IntArrayRef sizes_custom() const override;
65
+ SymIntArrayRef sym_sizes_custom() const override;
66
+ int64_t size_custom(int64_t d) const override;
67
+ c10::SymInt sym_size_custom(int64_t d) const override;
68
+ // We have to override this because we opted into CustomStrides
69
+ IntArrayRef strides_custom() const override;
70
+ SymIntArrayRef sym_strides_custom() const override;
71
+ // Override a bunch of methods inherited from TensorImpl to return error messages.
72
+ bool is_contiguous_custom(at::MemoryFormat memory_format=at::MemoryFormat::Contiguous) const override;
73
+ void set_size(int64_t dim, int64_t new_size) override;
74
+ void set_stride(int64_t dim, int64_t new_stride) override;
75
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
76
+ const c10::VariableVersion& version_counter,
77
+ bool allow_tensor_metadata_change) const override;
78
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
79
+ c10::VariableVersion&& version_counter,
80
+ bool allow_tensor_metadata_change) const override;
81
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
82
+ #ifdef DEBUG
83
+ bool has_storage() const override;
84
+ #endif
85
+
86
+ void refreshTensorMetadata();
87
+
88
+ // Used in torchdim. torchdim uses non-lexical BatchedTensor; the way it
89
+ // accomplishes this is a hack where it is able to modify the levels of
90
+ // BatchedTensor to match the level of the current vmap transform.
91
+ void _unsafe_set_level(int64_t level) {
92
+ level_ = level;
93
+ }
94
+
95
+ // Used in batching rule for in-place view operations that can change
96
+ // the index of the bdim (think squeeze_, unsqueeze_)
97
+ void unsafe_set_bdim(int64_t bdim) {
98
+ // NB: you MUST call refreshTensorMetadata after doing this.
99
+ bdim_ = bdim;
100
+ }
101
+ private:
102
+ // see NOTE: [BatchedTensorImpl levels invariant]
103
+ void checkInvariants() const;
104
+ const char* tensorimpl_type_name() const override;
105
+
106
+ Tensor value_;
107
+
108
+ int64_t level_;
109
+ int64_t bdim_;
110
+ };
111
+
112
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
113
+ // BatchedTensorImpl.
114
+ inline bool isBatchedTensor(const Tensor& tensor) {
115
+ return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::FuncTorchBatched) ||
116
+ tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::BatchedNestedTensor);
117
+ }
118
+
119
+ // It is unsafe to call this on a Tensor that is not backed by a
120
+ // BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible.
121
+ inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) {
122
+ return static_cast<BatchedTensorImpl*>(tensor.unsafeGetTensorImpl());
123
+ }
124
+
125
+ inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) {
126
+ if (!isBatchedTensor(tensor)) {
127
+ return nullptr;
128
+ }
129
+ return unsafeGetBatchedImpl(tensor);
130
+ }
131
+
132
+ // Returns a bitset. If bit i is set, then that means dim i is a batchdim.
133
+ inline std::bitset<kVmapMaxTensorDims> createBatchDimBitset(int64_t dim) {
134
+ std::bitset<kVmapMaxTensorDims> is_bdim;
135
+ is_bdim.set(dim);
136
+ return is_bdim;
137
+ }
138
+
139
+ // Creates a bitset for the given level
140
+ inline std::bitset<kVmapNumLevels> createVmapLevelsBitset(int64_t level) {
141
+ std::bitset<kVmapNumLevels> result;
142
+ result.set(level);
143
+ return result;
144
+ }
145
+
146
+ // Use this to construct a BatchedTensor from a regular Tensor
147
+ TORCH_API Tensor makeBatched(Tensor tensor, int64_t dim, int64_t level);
148
+
149
+ // Adds a batch dim to `tensor`, returning a BatchedTensor
150
+ TORCH_API Tensor addBatchDim(Tensor tensor, int64_t dim, int64_t level);
151
+
152
+ // Certain dispatch keys must be propagated to the BatchedTensor (or, in general,
153
+ // any wrapper Tensor subclasses). This is because there are methods on Tensor
154
+ // that skip dispatch and check for the presence of a dispatch key (e.g. is_cpu()).
155
+ // TODO: should probably contain more (or all?) backend keys
156
+ constexpr DispatchKeySet kKeysToPropagateToWrapper({
157
+ DispatchKey::Negative,
158
+ DispatchKey::Conjugate,
159
+ DispatchKey::XLA,
160
+ DispatchKey::CUDA,
161
+ DispatchKey::CPU,
162
+ });
163
+
164
+ inline DispatchKeySet getKeysToPropagateToWrapper(const Tensor& tensor, DispatchKeySet to_propagate=kKeysToPropagateToWrapper) {
165
+ auto key_set = tensor.unsafeGetTensorImpl()->key_set();
166
+ return key_set & kKeysToPropagateToWrapper;
167
+ }
168
+
169
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/Tensor.h>
9
+ #include <ATen/VmapGeneratedPlumbing.h>
10
+
11
+ // This file contains template metaprogramming things that are used for our
12
+ // batching rules.
13
+ //
14
+ // See NOTE: [vmap plumbing] for more details on why this is necessary.
15
+ // The plumbing has a bunch of metaprogramming hacks for determining the signature
16
+ // of a batching rule from the signature of the operator, many of which use the
17
+ // helper functions in this file.
18
+
19
+ namespace at::functorch {
20
+
21
+ // Metaprogramming things
22
+ template <class... Items> using typelist = c10::guts::typelist::typelist<Items...>;
23
+ template <class TypeList> using head_t = c10::guts::typelist::head_t<TypeList>;
24
+ template <class TL1, class TL2> using concat_t = c10::guts::typelist::concat_t<TL1, TL2>;
25
+ template <typename T> class debug_t;
26
+
27
+ // tail operation
28
+ template<class TypeList>
29
+ struct tail final {
30
+ static_assert(c10::guts::false_t<TypeList>::value,
31
+ "In typelist::tail<T>, the T argument must be typelist<...>.");
32
+ };
33
+ template<class Head, class... Tail>
34
+ struct tail<typelist<Head, Tail...>> final {
35
+ using type = typelist<Tail...>;
36
+ };
37
+ template<class TypeList> using tail_t = typename tail<TypeList>::type;
38
+
39
+ template <class First, class Second, class Next, class Tail>
40
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext {
41
+ using type = Next;
42
+ };
43
+ template <class Next, class Tail>
44
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor, std::optional<int64_t>, Next, Tail> {
45
+ using type = Tail;
46
+ };
47
+ template <class Next, class Tail>
48
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const Tensor&, std::optional<int64_t>, Next, Tail> {
49
+ using type = Tail;
50
+ };
51
+ template <class Next, class Tail>
52
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor&, std::optional<int64_t>, Next, Tail> {
53
+ using type = Tail;
54
+ };
55
+ template <class Next, class Tail>
56
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>, std::optional<int64_t>, Next, Tail> {
57
+ using type = Tail;
58
+ };
59
+ template <class Next, class Tail>
60
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
61
+ using type = Tail;
62
+ };
63
+ template <class Next, class Tail>
64
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
65
+ using type = Tail;
66
+ };
67
+ template <class Next, class Tail>
68
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::vector<Tensor>, std::optional<int64_t>, Next, Tail> {
69
+ using type = Tail;
70
+ };
71
+ template <class TypeList> struct RemoveBatchDimAfterTensor {
72
+ using first = head_t<TypeList>;
73
+ using next = tail_t<TypeList>;
74
+ using second = head_t<next>;
75
+ using tail = tail_t<next>;
76
+
77
+ using type = concat_t<
78
+ typelist<first>,
79
+ typename RemoveBatchDimAfterTensor<
80
+ typename IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<first, second, next, tail>::type
81
+ >::type
82
+ >;
83
+ };
84
+ template <class Type> struct RemoveBatchDimAfterTensor<typelist<Type>> {
85
+ using type = typelist<Type>;
86
+ };
87
+ template <> struct RemoveBatchDimAfterTensor<typelist<>> {
88
+ using type = typelist<>;
89
+ };
90
+ template<class TypeList> using remove_batch_dim_after_tensor_t = typename RemoveBatchDimAfterTensor<TypeList>::type;
91
+
92
+ template <typename T> struct UnpackSingleItemTuple {
93
+ using type = T;
94
+ };
95
+ template <typename T> struct UnpackSingleItemTuple<std::tuple<T>> {
96
+ using type = T;
97
+ };
98
+ template <typename T> using unpack_single_item_tuple_t = typename UnpackSingleItemTuple<T>::type;
99
+
100
+ template <typename Return, typename TupleArgs> struct BuildFunctionHelper;
101
+ template <typename Return, typename... Args> struct BuildFunctionHelper<Return, std::tuple<Args...>> {
102
+ using type = Return(Args...);
103
+ };
104
+ template <typename Return, typename TL>
105
+ struct BuildFunction {
106
+ using type = typename BuildFunctionHelper<Return, c10::guts::typelist::to_tuple_t<TL>>::type;
107
+ };
108
+ template <typename Return, typename TL> using build_function_t = typename BuildFunction<Return, TL>::type;
109
+
110
+
111
+ template <typename batch_rule_t> struct ToOperatorType {
112
+ using batch_rule_return_type = typename c10::guts::function_traits<batch_rule_t>::return_type;
113
+ using batch_rule_parameter_types = typename c10::guts::function_traits<batch_rule_t>::parameter_types;
114
+
115
+ using operator_parameter_types = remove_batch_dim_after_tensor_t<batch_rule_parameter_types>;
116
+ using operator_return_type =
117
+ unpack_single_item_tuple_t<
118
+ c10::guts::typelist::to_tuple_t<
119
+ remove_batch_dim_after_tensor_t<
120
+ c10::guts::typelist::from_tuple_t<batch_rule_return_type>>>>;
121
+
122
+ using type = build_function_t<operator_return_type, operator_parameter_types>;
123
+ };
124
+ template <typename batch_rule_t> using to_operator_t = typename ToOperatorType<batch_rule_t>::type;
125
+
126
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/DynamicLayer.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+ #include <ATen/functorch/Macros.h>
9
+ #include <c10/core/DispatchKey.h>
10
+ #include <ATen/core/function_schema.h>
11
+ #include <optional>
12
+ #include <c10/core/impl/LocalDispatchKeySet.h>
13
+ #include <ATen/functorch/Interpreter.h>
14
+ #include <ATen/functorch/VmapInterpreter.h>
15
+ #include <ATen/functorch/ADInterpreters.h>
16
+ #include <ATen/functorch/FunctionalizeInterpreter.h>
17
+
18
+ // Forward declared
19
+ namespace c10 { struct AutogradMetaInterface; }
20
+
21
+ namespace at::functorch {
22
+
23
+ // This file contains the implementation of functorch's interpreter stack.
24
+ // See NOTE: [functorch interpreter stack] first before reading on.
25
+ //
26
+ // NB: the functorch interpreter stack is also referred to as:
27
+ // - the "dynamic layer stack" -- an older name for "interpreter" was
28
+ // "dynamic layer".
29
+ // - the "functorch mode stack". You can think of each functorch transform as a
30
+ // "mode" (in the same sense as torch_dispatch mode or torch_function mode),
31
+ // and functorch being an implementation of a "mode stack" where the modes
32
+ // may be arbitrary composed.
33
+
34
+ // DynamicLayer is basically the same thing as an Interpreter.
35
+ // It represents a functorch transform and it holds an Interpreter,
36
+ // which contains metadata related to the transform and instructions on
37
+ // how to perform the transform.
38
+ //
39
+ // TODO: we can excise DynamicLayer in favor of Interpreter,
40
+ // But I am going to leave it for now as a compatiblity shim to avoid
41
+ // needing to refactor a lot of callsites...
42
+ struct TORCH_API DynamicLayer {
43
+ explicit DynamicLayer(
44
+ TransformType transform_type,
45
+ int64_t layerId,
46
+ std::optional<c10::SymInt> batchSize = std::nullopt,
47
+ std::optional<RandomnessType> randomness = std::nullopt,
48
+ std::optional<bool> prev_grad_mode = std::nullopt,
49
+ std::optional<bool> pre_fwd_grad_mode = std::nullopt,
50
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
51
+
52
+ TransformType key() const;
53
+ int64_t layerId() const;
54
+
55
+ const Interpreter& interpreter() const { return interpreter_; }
56
+ Interpreter& interpreter() { return interpreter_; }
57
+
58
+ // Only valid for vmap
59
+ c10::SymInt batchSize() const;
60
+ RandomnessType randomness() const;
61
+
62
+ private:
63
+ Interpreter interpreter_;
64
+ };
65
+
66
+ TORCH_API int64_t initAndPushDynamicLayer(
67
+ TransformType transform_type,
68
+ std::optional<c10::SymInt> batch_size = std::nullopt,
69
+ std::optional<RandomnessType> randomness = std::nullopt,
70
+ std::optional<bool> prev_grad_mode = std::nullopt,
71
+ std::optional<bool> prev_fwd_grad_mode = std::nullopt,
72
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
73
+ TORCH_API DynamicLayer popDynamicLayerAndDeleteMetadata();
74
+ TORCH_API std::optional<DynamicLayer> maybeCurrentDynamicLayer();
75
+ TORCH_API const std::vector<DynamicLayer>& getDynamicLayerStack();
76
+ TORCH_API void setDynamicLayerStack(const std::vector<DynamicLayer>& stack);
77
+ TORCH_API void setDynamicLayerFrontBackKeysIncluded(bool included);
78
+
79
+ // NOTE: [Life handles and lexically scoped transforms]
80
+ // functorch transforms are lexically scoped.
81
+ // Given a level, we store a "life handle" that is a boolean that tells us if the
82
+ // transform with that level is active or not.
83
+ //
84
+ // functorch's TensorWrapper (for grad transforms) stores a life handle.
85
+ // If a TensorWrapper escapes from the scope of the transform, then somehow
86
+ // it must know it escaped; it can tell by querying the life handle.
87
+ TORCH_API const std::shared_ptr<bool>& getLifeHandleForLevel(int64_t level);
88
+
89
+ // Returns if an operator is in-place. An operator is inplace if:
90
+ // 1. The first argument is a Tensor and it is being written to
91
+ // 2. The first argument is being returned
92
+ // 3. No other arguments are aliased
93
+ // Here is an example of an in-place operator:
94
+ // add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
95
+ TORCH_API bool isInplaceOp(const c10::FunctionSchema& schema);
96
+
97
+ // Given the indices of unwrapped inputs and the schema, this returns the indices of any outputs that should remain unwrapped
98
+ TORCH_API std::optional<size_t> findAliasedOutput(const FunctionSchema& schema, const int64_t immutable_input);
99
+
100
+ TORCH_API Tensor unwrapIfDead(const Tensor& tensor);
101
+ TORCH_API bool isDeadTensorWrapper(const Tensor& tensor);
102
+
103
+ // Pretty printers
104
+ TORCH_API std::ostream& operator<<(std::ostream& os, const DynamicLayer& layer);
105
+ TORCH_API std::ostream& operator<<(std::ostream& os, const std::vector<DynamicLayer>& dynamicLayerStack);
106
+
107
+ // While a functorch transform is active, torch.autograd.function._SingleLevelFunction
108
+ // is disabled by default. The following two APIs are APIs for enabling
109
+ // it. These are not user-facing APIs. We can delete this in the future, but
110
+ // it is useful for debugging when something goes wrong with the
111
+ // autograd.Function <> functorch interaction, which uses _SingleLevelFunction,
112
+ // because it leads to loud errors if something is incorrect.
113
+ TORCH_API void setSingleLevelAutogradFunctionAllowed(bool allowed);
114
+ TORCH_API bool getSingleLevelAutogradFunctionAllowed();
115
+
116
+ // While a functorch grad transform is active, Tensor.requires_grad_() gets
117
+ // disabled. These two functions are the mechanism to controlling that.
118
+ TORCH_API void setInplaceRequiresGradAllowed(bool allowed);
119
+ TORCH_API bool getInplaceRequiresGradAllowed();
120
+
121
+ TORCH_API DynamicLayer popDynamicLayer();
122
+ TORCH_API int64_t pushDynamicLayer(DynamicLayer&& layer);
123
+
124
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/functorch/Interpreter.h>
3
+
4
+ namespace at::functorch {
5
+
6
+ // This is the interpreter that handles the functionalize() transform.
7
+ // See NOTE: [functorch interpreter stack] for more details.
8
+
9
+ struct FunctionalizeInterpreterPtr {
10
+ explicit FunctionalizeInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Functionalize); }
11
+ TransformType key() const { return base_->key(); }
12
+ int64_t level() const { return base_->level(); }
13
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
14
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
15
+ bool functionalizeAddBackViews() const {
16
+ return std::get<FunctionalizeInterpreterMeta>(base_->meta()).functionalizeAddBackViews_;
17
+ }
18
+ private:
19
+ const Interpreter* base_;
20
+ };
21
+
22
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/Interpreter.h ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/functorch/Macros.h>
4
+ #include <ATen/core/dispatch/Dispatcher.h>
5
+ #include <c10/core/impl/LocalDispatchKeySet.h>
6
+ #include <optional>
7
+ #include <bitset>
8
+ #include <utility>
9
+ #include <variant>
10
+
11
+ namespace at::functorch {
12
+
13
+ // NOTE: [functorch interpreter stack]
14
+ //
15
+ // functorch's dispatching system uses a stack of interpreters.
16
+ // Historically we've referred to this as the "DynamicLayerStack".
17
+ //
18
+ // An interpreter is something that reads in the code it is passed
19
+ // and then executes it. We have a different interpreter per-transform:
20
+ // the "VmapInterpreter" is responsible for reading in operators (like aten::mv)
21
+ // and executing the batched version of it (the batching rule for aten::mv).
22
+ //
23
+ // Concretely, each interpreter is responsible for two things:
24
+ //
25
+ // 1) process(ophandle, stack)
26
+ // Given an operator handle and a stack of arguments, the interpreter is
27
+ // responsible for figuring out how to execute the operation under the semantics
28
+ // of the interpreter. For e.g. VmapInterpreter, this is figuring out how to call
29
+ // the batching rule.
30
+ //
31
+ // The batching rules are stored as kernels on the FuncTorchBatched key, so the way
32
+ // VmapInterpreter calls the batching rule is roughly: (A) exclude all
33
+ // dispatch keys aside from the Batched key, (B) redispatch so we get to the
34
+ // Batched key.
35
+ //
36
+ // 2) sendToNextInterpreter(ophandle, stack)
37
+ // The VmapInterpreter, when it sees aten::mv, will process it into a call to
38
+ // aten::mm. It then needs to send the call to aten::mm to the next interpreter
39
+ // in the interpreter stack.
40
+ //
41
+ // The VmapInterpreter just does this via a call to ophandle.callBoxed(stack)
42
+ // and most Interpreters will implement it this way.
43
+
44
+ enum class RandomnessType {
45
+ Error, // always errors when calling a random function
46
+ Same, // randomness appears the same across batches
47
+ Different, // randomness appears different across batches
48
+ END
49
+ };
50
+
51
+ enum class TransformType {
52
+ Torch, // Unused
53
+ Vmap,
54
+ Grad, // reverse-mode AD, aka vjp
55
+ Jvp, // forward-mode AD
56
+ Functionalize,
57
+ };
58
+
59
+ std::ostream& operator<<(std::ostream& os, const TransformType& t);
60
+
61
+ // NOTE: [Interpreter "subclassing" design]
62
+ //
63
+ // How are various Interpreters for different transforms (vmap, grad, ...)
64
+ // implemented?
65
+ //
66
+ // Accessing interpreters is in the hot-path of functorch so we have a constraint
67
+ // that this code must be as fast as possible.
68
+ //
69
+ // As a result, we stay away from virtual methods and this causes our code
70
+ // to look a little funny.
71
+ //
72
+ // `Interpreter` is the struct for Interpreters. It holds ALL of the
73
+ // relevant information (what type of interpreter it is and the metadata).
74
+ // Metadata for each interpreter is represented as a Union (std::variant)
75
+ // of all possible metadata (VmapInterpreterMeta, GradInterpreterMeta, ...).
76
+ //
77
+ // Given an Interpreter, how do I get a "VmapInterpreter"? You may wish to do this
78
+ // if you want to access the metadata fields (like batchSize and randomness).
79
+ //
80
+ // Each type of interpreter (e.g. Vmap) has a convenience struct
81
+ // (e.g. VmapInterpreterPtr) associated with it.
82
+ //
83
+ // Construct the convenience struct with VmapInterpreterPtr(Interpreter*),
84
+ // and then one can access methods on VmapInterpreterPtr like so:
85
+ // >>> VmapInterpreterPtr(&interpreter).batchSize()
86
+ //
87
+ // Finally, Interpreter::process switches on the type of the interpreter
88
+ // and calls one of {Transform}Intepreter::processImpl under the hood.
89
+ // Same for Interpreter::sendToNextInterpreter :)
90
+
91
+ struct VmapInterpreterMeta {
92
+ explicit VmapInterpreterMeta(c10::SymInt batchSize, RandomnessType randomness) :
93
+ batchSize_(std::move(batchSize)), randomness_(randomness) {}
94
+ c10::SymInt batchSize_;
95
+ RandomnessType randomness_;
96
+ };
97
+
98
+ struct GradInterpreterMeta {
99
+ explicit GradInterpreterMeta(bool prevGradMode): prevGradMode_(prevGradMode) {}
100
+ bool prevGradMode_;
101
+ };
102
+
103
+ struct JvpInterpreterMeta {
104
+ explicit JvpInterpreterMeta(bool prevFwdGradMode) : prevFwdGradMode_(prevFwdGradMode) {}
105
+ bool prevFwdGradMode_;
106
+ };
107
+
108
+ struct FunctionalizeInterpreterMeta {
109
+ explicit FunctionalizeInterpreterMeta(bool functionalizeAddBackViews) :
110
+ functionalizeAddBackViews_(functionalizeAddBackViews) {}
111
+ bool functionalizeAddBackViews_;
112
+ };
113
+
114
+ typedef std::variant<
115
+ int64_t,
116
+ GradInterpreterMeta,
117
+ JvpInterpreterMeta,
118
+ VmapInterpreterMeta,
119
+ FunctionalizeInterpreterMeta
120
+ > InterpreterMeta;
121
+
122
+
123
+ struct Interpreter {
124
+ // factory functions
125
+ static Interpreter Vmap(int64_t level, c10::SymInt batchSize, RandomnessType randomness) {
126
+ return Interpreter(TransformType::Vmap, level, VmapInterpreterMeta(std::move(batchSize), randomness));
127
+ }
128
+ static Interpreter Grad(int64_t level, bool prevGradMode) {
129
+ return Interpreter(TransformType::Grad, level, GradInterpreterMeta(prevGradMode));
130
+ }
131
+ static Interpreter Jvp(int64_t level, bool prevFwdGradMode) {
132
+ return Interpreter(TransformType::Jvp, level, JvpInterpreterMeta(prevFwdGradMode));
133
+ }
134
+ static Interpreter Functionalize(int64_t level, bool functionalizeAddBackViews) {
135
+ return Interpreter(TransformType::Functionalize, level, FunctionalizeInterpreterMeta(functionalizeAddBackViews));
136
+ }
137
+
138
+ // methods
139
+ TransformType key() const { return type_; }
140
+ int64_t level() const { return level_; }
141
+ const InterpreterMeta& meta() const { return meta_; }
142
+
143
+ void process(const c10::OperatorHandle& op, torch::jit::Stack* stack);
144
+ void sendToNextInterpreter(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
145
+
146
+ void saveLocalDispatchKeySet(c10::impl::LocalDispatchKeySet keyset) {
147
+ TORCH_INTERNAL_ASSERT(!savedLocalDispatchKeySet_.has_value());
148
+ savedLocalDispatchKeySet_ = keyset;
149
+ }
150
+ void clearSavedLocalDispatchKeySet() {
151
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
152
+ savedLocalDispatchKeySet_ = std::nullopt;
153
+ }
154
+ c10::impl::LocalDispatchKeySet getSavedLocalDispatchKeySet() const {
155
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
156
+ return *savedLocalDispatchKeySet_;
157
+ }
158
+
159
+ // An Interpreter is alive if we are currently inside the ongoing transform
160
+ // for the interpreter. For example, vmap(f)(x); inside of f, the vmap's
161
+ // corresponding Interpreter is alive, even when it is not on the DynamicLayerStack.
162
+ bool is_alive() const {
163
+ return *is_alive_;
164
+ }
165
+ const std::shared_ptr<bool>& is_alive_ptr() const {
166
+ return is_alive_;
167
+ }
168
+ void set_is_alive(bool alive) {
169
+ *is_alive_ = alive;
170
+ }
171
+
172
+ // Please don't use this
173
+ explicit Interpreter() = default;
174
+
175
+ private:
176
+ explicit Interpreter(TransformType type, int64_t level, InterpreterMeta meta):
177
+ type_(type), level_(level), is_alive_(std::make_shared<bool>(false)), meta_(std::move(meta)) {}
178
+
179
+ // fields
180
+ TransformType type_{};
181
+ int64_t level_{};
182
+ std::optional<c10::impl::LocalDispatchKeySet> savedLocalDispatchKeySet_;
183
+ std::shared_ptr<bool> is_alive_;
184
+ InterpreterMeta meta_;
185
+ };
186
+
187
+ // Applies the following for-loop:
188
+ // for i in range(begin, end):
189
+ // args[i] = func(args[i])
190
+ void foreachTensorInplace(std::vector<IValue>& args, int64_t begin, int64_t end,
191
+ std::function<Tensor(const Tensor&)> func);
192
+
193
+ // Applies the following for-loop:
194
+ // for i in range(begin, end):
195
+ // if use_flag_relative[i] == 1: <-- treats use_flag_relative as a bitset
196
+ // args[i] = func(args[i], i - begin, true)
197
+ // args[i] = func(args[i], i - begin)
198
+ void foreachTensorInplaceWithFlag(std::vector<IValue>& args, int64_t begin, int64_t end,
199
+ const std::bitset<64> use_flag_relative, const std::function<Tensor(const Tensor&, bool)>& func);
200
+
201
+ std::vector<int64_t> findUnwrappedInputs(std::vector<IValue>& args, int64_t begin, int64_t end);
202
+
203
+ DispatchKeySet keysToExcludeWhenEnteringDynamicLayer(TransformType key);
204
+
205
+ void setup_dispatch_key_tls(TransformType key, DispatchKeySet include);
206
+
207
+ void sanityCheckStack(const c10::OperatorHandle& op, torch::jit::Stack* stack);
208
+
209
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <ATen/functorch/Macros.h>
10
+ #include <ATen/functorch/BatchedTensorImpl.h>
11
+
12
+ namespace at::functorch {
13
+
14
+ // This files contains the legacy (now-deprecated) batching rule API.
15
+ // Please try to use the new-style batching rule API (see writing_batch_rules.md)
16
+
17
+ // This file contains abstractions used for transforming *logical* vmap arguments
18
+ // into *physical* arguments. (Keep reading for definitions of these terms).
19
+
20
+ // NOTE: [Logical vs physical args]
21
+ // Consider the following vmap.
22
+ // vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4))
23
+ // This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4],
24
+ // with batch dims 0 and 2:
25
+ // BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)])
26
+ //
27
+ // We say the *logical* view of the tensor has size [3] -- tensors inside
28
+ // `func` appear to have size [3].
29
+ // However, the *physical* underlying tensor (the one passed to vmap) has size
30
+ // [2, 3, 4].
31
+ //
32
+ // This notion of logical vs physical also extends to non-tensor arguments.
33
+ // Consider the previous tensor; let's assume the user called
34
+ // `torch.sum(tensor, dim=0)` inside of `func`. Then the logical
35
+ // dimension they are reducing over is dim 0 but the physical dim is dim 1
36
+ // (the first non-batch dimension)
37
+
38
+ // Forward declared; see NOTE: [What is a VmapPhysicalView?]
39
+ struct VmapPhysicalView;
40
+
41
+ // Most PyTorch operators take 4 or fewer inputs.
42
+ constexpr int64_t kVmapTransformStaticInputSize = 4;
43
+ using VmapPhysicalViewVec = SmallVector<VmapPhysicalView, kVmapTransformStaticInputSize>;
44
+
45
+ // Pytorch generally advertises good performance for <= 5 dims.
46
+ // (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap
47
+ // dimensions to get 8. Adjust this number as necessary
48
+ constexpr int64_t kVmapStaticDimVecSize = 8;
49
+ using VmapDimVector = SmallVector<int64_t, kVmapStaticDimVecSize>;
50
+ using VmapSymDimVector = SmallVector<c10::SymInt, kVmapStaticDimVecSize>;
51
+
52
+ // NOTE: [What is an VmapTransform?]
53
+ // An *VmapTransform* converts logical views of tensors to physical views.
54
+ //
55
+ // Batching rules use VmapTransforms to convert logical arguments to
56
+ // physical arguments, then call one or more at:: operator that handles the
57
+ // physical arguments, and then converts the physical result back to a logical
58
+ // argument.
59
+
60
+ // VmapTransform for operators that take tensors with multiple batch dims.
61
+ // Given one or more logical views on Tensors, `logicalToPhysical`
62
+ // permutes all of the batch dims to the front of the tensor, aligns
63
+ // and expands the batch dims to match each other (according to their `level`),
64
+ // and returns a VmapPhysicalView on the tensor(s).
65
+ struct TORCH_API MultiBatchVmapTransform {
66
+ static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor);
67
+ static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors);
68
+ };
69
+
70
+ // VmapTransform for operators that broadcast all inputs.
71
+ // Given some logical views on Tensors, `logicalToPhysical`:
72
+ // - permutes all of the batch dims to the front of the tensors
73
+ // - aligns all the batch dims to the collective levels of all of the tensors.
74
+ // If a tensor does not have a batch dim for a vmap level, then it receives
75
+ // a size-one dimension for said level.
76
+ // - aligns the non-batch dims to have the same dimensionality, adding extra
77
+ // size-1 dimensions in between the batch dimensions and the non-batch dimensions
78
+ // so that the batch dimensions are lined up from the right.
79
+ //
80
+ // For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch
81
+ // dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap tensors
82
+ // of size (B, 1, 2) and (B, 3, 2).
83
+ //
84
+ // Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns
85
+ // VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't
86
+ // actually *need* to return a tensor of size (1, 2) for the second tensor
87
+ // because the broadcasting operation takes care of that for us, but we do
88
+ // it anyways to keep things simple.
89
+ struct TORCH_API BroadcastingVmapTransform {
90
+ static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors);
91
+ };
92
+
93
+ // Forward declared, if you're reading this file head to toe, don't worry about
94
+ // it yet.
95
+ struct VmapPhysicalToLogicalMap;
96
+
97
+ // NOTE: [What is a VmapPhysicalView?]
98
+ // VmapPhysicalView represents a physical view on a Tensor.
99
+ //
100
+ // One can use it to further convert logical dimension indices, logical shapes,
101
+ // and more to their physical variants, or convert a new (physical) tensor into
102
+ // a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented).
103
+ //
104
+ // VmapPhysicalView stores a physical tensor with all of its batch dimensions at
105
+ // the front and some levels that correspond to said batch dimensions.
106
+ //
107
+ // The levels bitset specifies which vmap levels correspond to the batch
108
+ // dimensions at the front of the tensor. In particular, the number of set bits
109
+ // corresponds to the number of batch dimensions on `tensor` and the rightmost
110
+ // bit of `levels` specifies the maximum number of nested vmaps we are in at
111
+ // this point in time.
112
+ // For example, given:
113
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3})
114
+ //
115
+ // Rightmost bit of `levels` is 3 indicating the number of nested vmaps less
116
+ // than or equal to 3.
117
+ // bitset: 010100
118
+ // ^
119
+ // |
120
+ // levels: 012345
121
+ struct TORCH_API VmapPhysicalView {
122
+ VmapPhysicalView(Tensor&& tensor, std::bitset<kVmapNumLevels> levels)
123
+ : levels_(levels), tensor_(std::move(tensor)) {
124
+ // TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor));
125
+ }
126
+
127
+ Tensor& tensor() { return tensor_; }
128
+ const Tensor& tensor() const { return tensor_; }
129
+
130
+ // Maps logical dim indices to physical dim indices. Also does dim wrapping.
131
+ //
132
+ // For example, given:
133
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3})
134
+ //
135
+ // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}.
136
+ // This is because the size of levels tell us that the first two dimensions
137
+ // of `tensor_` are batch dimensions, so a logical dim of `n` is actually
138
+ // a physical dim of `n + 2`.
139
+ VmapDimVector getPhysicalDims(IntArrayRef logical_dims) const;
140
+ int64_t getPhysicalDim(int64_t logical_dim) const;
141
+
142
+ // Returns a VmapPhysicalToLogicalMap object. This can be used for
143
+ // mapping a physical tensor to a new logical tensor (BatchedTensor)
144
+ VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const;
145
+
146
+ // Maps a logical shape to a physical shape by pre-pending the batch
147
+ // sizes to the logical shape.
148
+ VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const;
149
+ SymDimVector getPhysicalShape(c10::SymIntArrayRef logical_shape) const;
150
+
151
+ int64_t numBatchDims() const;
152
+
153
+ private:
154
+ int64_t numLogicalDims() const;
155
+
156
+ std::bitset<kVmapNumLevels> levels_;
157
+ Tensor tensor_;
158
+ };
159
+
160
+ // Convenience struct used for mapping a physical tensor (a non-BatchedTensor)
161
+ // to a logical one (BatchedTensor). It holds some levels that are used to do the
162
+ // mapping and assumes that the batch dimensions in the physical tensor all
163
+ // occur at the front of the tensor.
164
+ struct TORCH_API VmapPhysicalToLogicalMap {
165
+ VmapPhysicalToLogicalMap(std::bitset<kVmapNumLevels> levels): levels_(levels) {}
166
+
167
+ // Maps a physical tensor to a new logical tensor (BatchedTensor).
168
+ // Assumes that all of the "batch dimensions" are at the front
169
+ // of the physical tensor. For example, given:
170
+ // - x = rank-4 Tensor with size 2, 3, 5, 7
171
+ // - levels = (2, 4)
172
+ // Returns:
173
+ // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)])
174
+ Tensor apply(const Tensor& physical_tensor) const;
175
+
176
+ // Given a vector of physical tensors,
177
+ // 1. maps each tensor to a new logical tensor. Assumes that all of the
178
+ // "batch dimensions" are at the front of the physical tensors.
179
+ // 2. stores the new logical tensors back into the passed-in vector. This is
180
+ // to avoid additional dynamic allocations.
181
+ void applyInplace(std::vector<Tensor>& physical_tensors) const;
182
+
183
+ std::bitset<kVmapNumLevels> levels_;
184
+ };
185
+
186
+
187
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/Macros.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+
3
+ #define SINGLE_ARG(...) __VA_ARGS__
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/PlumbingHelper.h ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #pragma once
7
+ #include <ATen/Tensor.h>
8
+ #include <ATen/functorch/BatchedTensorImpl.h>
9
+ #include <ATen/functorch/DynamicLayer.h>
10
+
11
+ // NOTE: [vmap plumbing]
12
+ //
13
+ // Here's how "batching rules" work.
14
+ // - we register kernels to the Batched key
15
+ // - these kernels have the same signatures as the original operators.
16
+ // For example, at::sin(Tensor self) accepts a Tensor, and the batched kernel
17
+ // must also accept a Tensor
18
+ // - However, it is more natural for users to write a batching rule like the
19
+ // following: sin_batch_rule(Tensor self, std::optional<int> self_bdim)
20
+ // - There is some codegenerated layer (the "plumbing") that wraps the user
21
+ // defined batching rule (e.g. sin_batch_rule) in a kernel that can be
22
+ // registered to the Batched key.
23
+ //
24
+ // The plumbing is responsible for wrapping a batching rule into a form that may
25
+ // be registered as the kernel for the batched key.
26
+
27
+ namespace at::functorch {
28
+
29
+ void vmap_check_escaped(const std::optional<DynamicLayer> &layer, const char* what);
30
+
31
+ // Create a BatchedTensor given a tensor, bdim, and level
32
+ TORCH_API Tensor makeBatched(Tensor tensor, std::optional<int64_t> bdim, int64_t level);
33
+
34
+ // Given a Tensor that may or may not be a BatchedTensor, unwrap it.
35
+ // If `tensor` is not a BatchedTensor, or is a BatchedTensor but the level
36
+ // doesn't match, then this returns (tensor, std::nullopt).
37
+ // Otherwise, it returns (unwrap(tensor), bdim).
38
+ TORCH_API std::tuple<Tensor, std::optional<int64_t>> unwrapTensorAtLevel(const Tensor& tensor, int64_t level);
39
+
40
+ // Creates a vector of BatchedTensor
41
+ TORCH_API std::vector<Tensor> makeBatchedVector(std::vector<Tensor> tensors, std::optional<int64_t> bdim, int64_t level);
42
+
43
+ // Returns True if ANY tensor in tensors is batched at level
44
+ TORCH_API bool isBatchedAtLevel(ITensorListRef tensors, int64_t level);
45
+ TORCH_API bool isBatchedAtLevel(const c10::List<std::optional<Tensor>>& maybe_tensors, int64_t level);
46
+ TORCH_API bool isBatchedAtLevel(const Tensor& tensor, int64_t level);
47
+ TORCH_API bool isBatchedAtLevel(const std::optional<Tensor>& maybe_tensor, int64_t level);
48
+
49
+ // Convenience helper. Returns true if any tensor is batched at level
50
+ TORCH_API bool areAnyBatchedAtLevel(ArrayRef<std::optional<Tensor>> maybe_tensors, int64_t level);
51
+
52
+ inline bool ivalueParticipatesInCurrentLevel(const IValue& ivalue) {
53
+ if (ivalue.isTensor()) {
54
+ auto maybe_level = maybeCurrentDynamicLayer();
55
+ TORCH_INTERNAL_ASSERT(maybe_level.has_value());
56
+ auto current_level = maybe_level->layerId();
57
+ return isBatchedAtLevel(ivalue.toTensor(), current_level);
58
+ }
59
+ // TODO: should really check this
60
+ return false;
61
+ }
62
+
63
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/TensorWrapper.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <ATen/functorch/Macros.h>
10
+ #include <ATen/Tensor.h>
11
+ #include <ATen/functorch/Interpreter.h>
12
+
13
+ namespace at::functorch {
14
+
15
+ // NOTE: [functorch's TensorWrapper]
16
+ //
17
+ // Taking better suggestions for a name. TensorWrapper is the wrapper Tensor
18
+ // Subclass for functorch's grad-based transforms (grad, vjp, jvp). It is
19
+ // analogous to how vmap uses BatchedTensor as the wrapper Tensor subclass.
20
+ //
21
+ // If you're familiar with the Tensor-Variable merge, TensorWrapper is effectively
22
+ // another Variable.
23
+ //
24
+ // Consider grad(grad(torch.sin))(x). This wraps `x` as TensorWrapper(TensorWrapper(x)).
25
+ // The reason why is so that each TensorWrapper can hold its own AutogradMeta and
26
+ // participate in a **separate** autograd graph.
27
+ //
28
+ // There are alternative designs we could have chosen (e.g. each grad transform
29
+ // stores a weak map of Tensor -> AutogradMeta); the benefit of the TensorWrapper
30
+ // design is that we can re-use existing VariableType kernels (i.e. Autograd kernels)
31
+ // without much modification. Since a TensorWrapper looks like a regular Tensor,
32
+ // the VariableType kernel can pull out the AutogradMeta struct from where it
33
+ // expects and extend the autograd graph
34
+
35
+ struct TORCH_API TensorWrapper : public c10::TensorImpl {
36
+ explicit TensorWrapper(
37
+ c10::DispatchKeySet key_set,
38
+ Tensor value,
39
+ int64_t level,
40
+ std::shared_ptr<bool> is_alive,
41
+ bool is_immutable = false, // if true, this came from an operation that aliases an immutable tensor
42
+ bool use_value_sizes_strides = true);
43
+
44
+ void refreshMetadata();
45
+
46
+ const Tensor& value() const {
47
+ return value_;
48
+ }
49
+ std::optional<int64_t> level() const {
50
+ if (is_alive()) {
51
+ return level_;
52
+ }
53
+ return {};
54
+ }
55
+ bool is_immutable() const {
56
+ return is_immutable_;
57
+ }
58
+ bool is_alive() const;
59
+
60
+ // Overrides necessary for autograd
61
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
62
+ const c10::VariableVersion& version_counter,
63
+ bool allow_tensor_metadata_change) const override;
64
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
65
+ c10::VariableVersion&& version_counter,
66
+ bool allow_tensor_metadata_change) const override;
67
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
68
+
69
+ private:
70
+ const char* tensorimpl_type_name() const override;
71
+ Tensor value_;
72
+ int64_t level_;
73
+ bool is_immutable_;
74
+
75
+ // TensorWrapper receives a boolean flag on whether or not the Grad Interpreter
76
+ // that created it is still alive or not.
77
+ // If the Grad Interpreter is no longer alive then it attempts to behave like
78
+ // a regular Tensor.
79
+ //
80
+ // When we exit the level, this wrapper may be marked as "not alive".
81
+ // Wrappers that are not alive:
82
+ // 1) May still have autograd metadata on them
83
+ // 2) Forward dispatches to the underlying value()
84
+ std::shared_ptr<bool> is_alive_;
85
+ };
86
+
87
+ // There are two variants of makeTensorWrapper: one that accepts a level
88
+ // and one that accepts an Interpreter.
89
+ //
90
+ // The one that accepts a level tries to automatically get the life handle from the
91
+ // interpreter on the DynamicLayerStack.
92
+ // It needs to be used with caution: if the interpreter is not on the
93
+ // DynamicLayerStack, then we won't be able to find the life handle.
94
+ //
95
+ // In practice this isn't a problem: when we're constructing TensorWrapper in
96
+ // Python, the corresponding interpreter is on the stack.
97
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, int64_t level, bool is_immutable=false);
98
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, const Interpreter& interpreter, bool is_immutable=false);
99
+ TORCH_API TensorWrapper* maybeGetTensorWrapper(const Tensor& tensor);
100
+ TORCH_API void dumpTensor(std::ostream & ss, const Tensor& tensor);
101
+ TORCH_API void dumpTensorCout(const Tensor& tensor);
102
+
103
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/functorch/VmapInterpreter.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/functorch/Interpreter.h>
3
+
4
+ namespace at::functorch {
5
+
6
+ // This is the interpreter that handles the functionalize() transform.
7
+ // See NOTE: [functorch interpreter stack] for more details.
8
+
9
+ struct VmapInterpreterPtr {
10
+ explicit VmapInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Vmap); }
11
+ TransformType key() const { return base_->key(); }
12
+ int64_t level() const { return base_->level(); }
13
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
14
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
15
+ c10::SymInt batchSize() const {
16
+ return std::get<VmapInterpreterMeta>(base_->meta()).batchSize_;
17
+ }
18
+ RandomnessType randomness() const {
19
+ return std::get<VmapInterpreterMeta>(base_->meta()).randomness_;
20
+ }
21
+ private:
22
+ const Interpreter* base_;
23
+ };
24
+
25
+ } // namespace at::functorch
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Descriptors.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/Exceptions.h>
4
+
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/TensorUtils.h>
8
+
9
+ namespace at { namespace native {
10
+
11
+ inline int dataSize(miopenDataType_t dataType)
12
+ {
13
+ switch (dataType) {
14
+ case miopenHalf: return 2;
15
+ case miopenFloat: return 4;
16
+ case miopenBFloat16: return 2;
17
+ default: return 8;
18
+ }
19
+ }
20
+
21
+ template <typename T, miopenStatus_t (*dtor)(T*)>
22
+ struct DescriptorDeleter {
23
+ void operator()(T* x) {
24
+ if (x != nullptr) {
25
+ MIOPEN_CHECK(dtor(x));
26
+ }
27
+ }
28
+ };
29
+
30
+ // A generic class for wrapping MIOpen descriptor types. All you need
31
+ // is to give the underlying type the Descriptor_t points to (usually,
32
+ // if it's miopenTensorDescriptor_t it points to miopenTensorStruct),
33
+ // the constructor and the destructor. Subclasses are responsible
34
+ // for defining a set() function to actually set the descriptor.
35
+ //
36
+ // Descriptors default construct to a nullptr, and have a descriptor
37
+ // initialized the first time you call set() or any other initializing
38
+ // function.
39
+ template <typename T, miopenStatus_t (*ctor)(T**), miopenStatus_t (*dtor)(T*)>
40
+ class Descriptor
41
+ {
42
+ public:
43
+ // Use desc() to access the underlying descriptor pointer in
44
+ // a read-only fashion. Most client code should use this.
45
+ // If the descriptor was never initialized, this will return
46
+ // nullptr.
47
+ T* desc() const { return desc_.get(); }
48
+ T* desc() { return desc_.get(); }
49
+
50
+ // Use mut_desc() to access the underlying descriptor pointer
51
+ // if you intend to modify what it points to (e.g., using
52
+ // miopenSetFooDescriptor). This will ensure that the descriptor
53
+ // is initialized. Code in this file will use this function.
54
+ T* mut_desc() { init(); return desc_.get(); }
55
+ protected:
56
+ void init() {
57
+ if (desc_ == nullptr) {
58
+ T* raw_desc;
59
+ MIOPEN_CHECK(ctor(&raw_desc));
60
+ desc_.reset(raw_desc);
61
+ }
62
+ }
63
+ private:
64
+ std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_;
65
+ };
66
+
67
+ class TensorDescriptor
68
+ : public Descriptor<miopenTensorDescriptor,
69
+ &miopenCreateTensorDescriptor,
70
+ &miopenDestroyTensorDescriptor>
71
+ {
72
+ public:
73
+ TensorDescriptor() {}
74
+ explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) {
75
+ set(t, pad);
76
+ }
77
+
78
+ void set(const at::Tensor &t, size_t pad = 0);
79
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0);
80
+
81
+ void print();
82
+
83
+ private:
84
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride) {
85
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, stride));
86
+ }
87
+ };
88
+
89
+ std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d);
90
+
91
+ class FilterDescriptor
92
+ : public Descriptor<miopenTensorDescriptor,
93
+ &miopenCreateTensorDescriptor,
94
+ &miopenDestroyTensorDescriptor>
95
+ {
96
+ public:
97
+ void set(const at::Tensor &t, int64_t pad = 0) {
98
+ set(t, at::MemoryFormat::Contiguous, pad);
99
+ }
100
+
101
+ void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0);
102
+
103
+ private:
104
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride) {
105
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, stride));
106
+ }
107
+ };
108
+
109
+ struct ConvolutionDescriptor
110
+ : public Descriptor<miopenConvolutionDescriptor,
111
+ &miopenCreateConvolutionDescriptor,
112
+ &miopenDestroyConvolutionDescriptor>
113
+ {
114
+ void set(miopenDataType_t dataType, miopenConvolutionMode_t c_mode, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool benchmark, bool deterministic) {
115
+ MIOPEN_CHECK(miopenInitConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, c_mode));
116
+ MIOPEN_CHECK(miopenSetConvolutionGroupCount(mut_desc(), groups));
117
+ MIOPEN_CHECK(miopenSetConvolutionAttribute(mut_desc(), MIOPEN_CONVOLUTION_ATTRIB_DETERMINISTIC, deterministic ? 1 : 0));
118
+ if (benchmark) {
119
+ MIOPEN_CHECK(miopenSetConvolutionFindMode(mut_desc(), miopenConvolutionFindModeNormal));
120
+ }
121
+ }
122
+ };
123
+
124
+
125
+ struct RNNDescriptor
126
+ : public Descriptor<miopenRNNDescriptor,
127
+ &miopenCreateRNNDescriptor,
128
+ &miopenDestroyRNNDescriptor>
129
+ {
130
+ void set(int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, miopenRNNMode_t rnn_mode,
131
+ miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
132
+ MIOPEN_CHECK(miopenSetRNNDescriptor(mut_desc(), hidden_size, num_layers, input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
133
+ }
134
+ };
135
+
136
+ union Constant
137
+ {
138
+ float f;
139
+ double d;
140
+ Constant(miopenDataType_t dataType, double value) {
141
+ if (dataType == miopenHalf || dataType == miopenFloat || dataType == miopenBFloat16) {
142
+ f = static_cast<float>(value);
143
+ } else {
144
+ d = value;
145
+ }
146
+ }
147
+ };
148
+
149
+ }} // namespace
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Exceptions.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+ #include <string>
5
+ #include <stdexcept>
6
+ #include <sstream>
7
+
8
+ namespace at { namespace native {
9
+
10
+ class miopen_exception : public std::runtime_error {
11
+ public:
12
+ miopenStatus_t status;
13
+ miopen_exception(miopenStatus_t status, const char* msg)
14
+ : std::runtime_error(msg)
15
+ , status(status) {}
16
+ miopen_exception(miopenStatus_t status, const std::string& msg)
17
+ : std::runtime_error(msg)
18
+ , status(status) {}
19
+ };
20
+
21
+ inline void MIOPEN_CHECK(miopenStatus_t status)
22
+ {
23
+ if (status != miopenStatusSuccess) {
24
+ if (status == miopenStatusNotImplemented) {
25
+ throw miopen_exception(status, std::string(miopenGetErrorString(status)) +
26
+ ". This error may appear if you passed in a non-contiguous input.");
27
+ }
28
+ throw miopen_exception(status, miopenGetErrorString(status));
29
+ }
30
+ }
31
+
32
+ inline void HIP_CHECK(hipError_t error)
33
+ {
34
+ if (error != hipSuccess) {
35
+ std::string msg("HIP error: ");
36
+ msg += hipGetErrorString(error);
37
+ throw std::runtime_error(msg);
38
+ }
39
+ }
40
+
41
+ }} // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Handle.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+
5
+ namespace at { namespace native {
6
+
7
+ miopenHandle_t getMiopenHandle();
8
+
9
+ }} // namespace
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Types.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+ #include <ATen/Tensor.h>
5
+
6
+ namespace at { namespace native {
7
+
8
+ miopenDataType_t getMiopenDataType(const at::Tensor& tensor);
9
+
10
+ int64_t miopen_version();
11
+
12
+ }} // namespace at::miopen
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/Utils.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <ATen/miopen/Handle.h>
6
+
7
+ namespace at { namespace native {
8
+
9
+ // This function makes tensors which have zero stride contiguous, by
10
+ // setting the strides to 1.
11
+ inline Tensor contiguousIfZeroInStrides(const Tensor& t) {
12
+ for (auto s : t.strides()) {
13
+ if (s == 0) return t.contiguous();
14
+ }
15
+ return t;
16
+ }
17
+
18
+ }}
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/miopen/miopen-wrapper.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <miopen/miopen.h>
4
+ #include <miopen/version.h>
5
+
6
+ #if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4)
7
+ // miopen 3.4 moved find mode from private header to public header
8
+ #else
9
+ // from miopen_internal.h
10
+ extern "C" {
11
+
12
+ typedef enum
13
+ {
14
+ miopenConvolutionFindModeNormal = 1, /*!< Normal mode */
15
+ } miopenConvolutionFindMode_t;
16
+
17
+ miopenStatus_t miopenSetConvolutionFindMode(
18
+ miopenConvolutionDescriptor_t convDesc,
19
+ miopenConvolutionFindMode_t findMode);
20
+ }
21
+ #endif
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/EmptyTensor.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+ #include <ATen/core/TensorBase.h>
5
+
6
+ namespace at::detail {
7
+
8
+ C10_EXPORT TensorBase empty_mps(
9
+ IntArrayRef size,
10
+ std::optional<ScalarType> dtype_opt,
11
+ std::optional<Layout> layout_opt,
12
+ std::optional<Device> device_opt,
13
+ std::optional<bool> pin_memory_opt,
14
+ std::optional<c10::MemoryFormat> memory_format_opt);
15
+ C10_EXPORT TensorBase empty_mps(IntArrayRef size, const TensorOptions& options);
16
+
17
+ C10_EXPORT TensorBase empty_strided_mps(
18
+ IntArrayRef size,
19
+ IntArrayRef stride,
20
+ ScalarType dtype,
21
+ std::optional<Device> device_opt);
22
+
23
+ C10_EXPORT TensorBase empty_strided_mps(
24
+ IntArrayRef size,
25
+ IntArrayRef stride,
26
+ const TensorOptions& options);
27
+
28
+ } // namespace at::detail
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/IndexKernels.h ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ namespace at::mps {
4
+
5
+ static const char* SCATTER_OPS_TEMPLATE = R"METAL_SCATTER(
6
+ template<typename Y, typename X>
7
+ Y cast(const X x);
8
+
9
+ template<>
10
+ {1} cast<{1}, {0}>(const {0} x) {{
11
+ return {2};
12
+ }}
13
+
14
+ kernel void scatter_kernel_n(uint linear_index [[thread_position_in_grid]],
15
+ constant void * src_ [[buffer(0)]],
16
+ device void * dst_ [[buffer(1)]],
17
+ constant uint32_t * size [[buffer(2)]],
18
+ constant uint32_t * stride [[buffer(3)]],
19
+ constant uint32_t & numel [[buffer(4)]],
20
+ constant int32_t & ndim [[buffer(5)]]) {{
21
+ if (linear_index >= numel) return;
22
+
23
+ constant {0} * src = (constant {0} *)src_;
24
+ device {1} * dst = (device {1} *)dst_;
25
+
26
+ uint64_t dst_offs = 0;
27
+ auto dst_idx = linear_index;
28
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
29
+ dst_offs += stride[dim] * (dst_idx % size[dim]);
30
+ dst_idx /= size[dim];
31
+ }}
32
+
33
+ dst[dst_offs] = cast<{1}>(src[linear_index]);
34
+ }}
35
+
36
+ kernel void scatter_kernel_4(uint linear_index [[thread_position_in_grid]],
37
+ constant void * src_ [[buffer(0)]],
38
+ device void * dst_ [[buffer(1)]],
39
+ constant packed_uint4 & size [[buffer(2)]],
40
+ constant packed_uint4 & stride [[buffer(3)]],
41
+ constant uint32_t & numel [[buffer(4)]]) {{
42
+ if (linear_index >= numel) return;
43
+
44
+ constant {0} * src = (constant {0} *)src_;
45
+ device {1} * dst = (device {1} *)dst_;
46
+
47
+ packed_uint4 local_index;
48
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
49
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
50
+ local_index.z = linear_index / size[3] % size[2];
51
+ local_index.w = linear_index % size[3];
52
+
53
+ const packed_uint4 strided_index = local_index * stride;
54
+ dst[strided_index.x + strided_index.y + strided_index.z + strided_index.w] = cast<{1}>(src[linear_index]);
55
+ }}
56
+
57
+ kernel void scatter_kernel_3(uint linear_index [[thread_position_in_grid]],
58
+ constant void * src_ [[buffer(0)]],
59
+ device void * dst_ [[buffer(1)]],
60
+ constant packed_uint3 & size [[buffer(2)]],
61
+ constant packed_uint3 & stride [[buffer(3)]],
62
+ constant uint32_t & numel [[buffer(4)]]) {{
63
+ if (linear_index >= numel) return;
64
+
65
+ constant {0} * src = (constant {0} *)src_;
66
+ device {1} * dst = (device {1} *)dst_;
67
+
68
+ packed_uint3 local_index;
69
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
70
+ local_index.y = linear_index / size[2] % size[1];
71
+ local_index.z = linear_index % size[2];
72
+
73
+ const packed_uint3 strided_index = local_index * stride;
74
+ dst[strided_index.x + strided_index.y + strided_index.z] = cast<{1}>(src[linear_index]);
75
+ }}
76
+
77
+ kernel void scatter_kernel_2(uint linear_index [[thread_position_in_grid]],
78
+ constant void * src_ [[buffer(0)]],
79
+ device void * dst_ [[buffer(1)]],
80
+ constant packed_uint2 & size [[buffer(2)]],
81
+ constant packed_uint2 & stride [[buffer(3)]],
82
+ constant uint32_t & numel [[buffer(4)]]) {{
83
+ if (linear_index >= numel) return;
84
+
85
+ constant {0} * src = (constant {0} *)src_;
86
+ device {1} * dst = (device {1} *)dst_;
87
+
88
+ packed_uint2 local_index;
89
+ local_index.x = linear_index / size[1] % size[0];
90
+ local_index.y = linear_index % size[1];
91
+
92
+ const packed_uint2 strided_index = local_index * stride;
93
+ dst[strided_index.x + strided_index.y] = cast<{1}>(src[linear_index]);
94
+ }}
95
+
96
+ kernel void scatter_kernel_1(uint linear_index [[thread_position_in_grid]],
97
+ constant void * src_ [[buffer(0)]],
98
+ device void * dst_ [[buffer(1)]],
99
+ constant int & size [[buffer(2)]],
100
+ constant int & stride [[buffer(3)]],
101
+ constant uint32_t & numel [[buffer(4)]]) {{
102
+ if (linear_index >= numel) return;
103
+
104
+ constant {0} * src = (constant {0} *)src_;
105
+ device {1} * dst = (device {1} *)dst_;
106
+
107
+ const int local_index = linear_index % size;
108
+ const int strided_index = local_index * stride;
109
+ dst[strided_index] = cast<{1}>(src[linear_index]);
110
+ }}
111
+ )METAL_SCATTER";
112
+
113
+ static const char* GATHER_OPS_TEMPLATE = R"METAL_GATHER(
114
+ template<typename Y, typename X>
115
+ Y cast(const X x);
116
+
117
+ template<>
118
+ {1} cast<{1}, {0}>(const {0} x) {{
119
+ return {2};
120
+ }}
121
+
122
+ kernel void gather_kernel_n(uint linear_index [[thread_position_in_grid]],
123
+ constant void * src_ [[buffer(0)]],
124
+ device void * dst_ [[buffer(1)]],
125
+ constant uint32_t * size [[buffer(2)]],
126
+ constant uint32_t * stride [[buffer(3)]],
127
+ constant uint32_t & numel [[buffer(4)]],
128
+ constant int32_t & ndim [[buffer(5)]]) {{
129
+ if (linear_index >= numel) return;
130
+
131
+ constant {0} * src = (constant {0} *)src_;
132
+ device {1} * dst = (device {1} *)dst_;
133
+
134
+ uint64_t src_offs = 0;
135
+ auto src_idx = linear_index;
136
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
137
+ src_offs += stride[dim] * (src_idx % size[dim]);
138
+ src_idx /= size[dim];
139
+ }}
140
+
141
+ dst[linear_index] = cast<{1}>(src[src_offs]);
142
+ }}
143
+
144
+ kernel void gather_kernel_4(uint linear_index [[thread_position_in_grid]],
145
+ constant void * src_ [[buffer(0)]],
146
+ device void * dst_ [[buffer(1)]],
147
+ constant packed_uint4 & size [[buffer(2)]],
148
+ constant packed_uint4 & stride [[buffer(3)]],
149
+ constant uint32_t & numel [[buffer(4)]]) {{
150
+ if (linear_index >= numel) return;
151
+
152
+ constant {0} * src = (constant {0} *)src_;
153
+ device {1} * dst = (device {1} *)dst_;
154
+
155
+ packed_uint4 local_index;
156
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
157
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
158
+ local_index.z = linear_index / size[3] % size[2];
159
+ local_index.w = linear_index % size[3];
160
+
161
+ const packed_uint4 strided_index = local_index * stride;
162
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z + strided_index.w]);
163
+ }}
164
+
165
+ kernel void gather_kernel_3(uint linear_index [[thread_position_in_grid]],
166
+ constant void * src_ [[buffer(0)]],
167
+ device void * dst_ [[buffer(1)]],
168
+ constant packed_uint3 & size [[buffer(2)]],
169
+ constant packed_uint3 & stride [[buffer(3)]],
170
+ constant uint32_t & numel [[buffer(4)]]) {{
171
+ if (linear_index >= numel) return;
172
+
173
+ constant {0} * src = (constant {0} *)src_;
174
+ device {1} * dst = (device {1} *)dst_;
175
+
176
+ packed_uint3 local_index;
177
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
178
+ local_index.y = linear_index / size[2] % size[1];
179
+ local_index.z = linear_index % size[2];
180
+
181
+ const packed_uint3 strided_index = local_index * stride;
182
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z]);
183
+ }}
184
+
185
+ kernel void gather_kernel_2(uint linear_index [[thread_position_in_grid]],
186
+ constant void * src_ [[buffer(0)]],
187
+ device void * dst_ [[buffer(1)]],
188
+ constant packed_uint2 & size [[buffer(2)]],
189
+ constant packed_uint2 & stride [[buffer(3)]],
190
+ constant uint32_t & numel [[buffer(4)]]) {{
191
+ if (linear_index >= numel) return;
192
+
193
+ constant {0} * src = (constant {0} *)src_;
194
+ device {1} * dst = (device {1} *)dst_;
195
+
196
+ packed_uint2 local_index;
197
+ local_index.x = linear_index / size[1] % size[0];
198
+ local_index.y = linear_index % size[1];
199
+
200
+ const packed_uint2 strided_index = local_index * stride;
201
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y]);
202
+ }}
203
+
204
+ kernel void gather_kernel_1(uint linear_index [[thread_position_in_grid]],
205
+ constant void * src_ [[buffer(0)]],
206
+ device void * dst_ [[buffer(1)]],
207
+ constant int & size [[buffer(2)]],
208
+ constant int & stride [[buffer(3)]],
209
+ constant uint32_t & numel [[buffer(4)]]) {{
210
+ if (linear_index >= numel) return;
211
+
212
+ constant {0} * src = (constant {0} *)src_;
213
+ device {1} * dst = (device {1} *)dst_;
214
+
215
+ const int local_index = linear_index % size;
216
+ const int strided_index = local_index * stride;
217
+ dst[linear_index] = cast<{1}>(src[strided_index]);
218
+ }}
219
+ )METAL_GATHER";
220
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSAllocator.h ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/mps/MPSAllocatorInterface.h>
6
+ #include <ATen/mps/MPSEvent.h>
7
+ #include <ATen/mps/MPSStream.h>
8
+
9
+ #include <c10/util/flat_hash_map.h>
10
+ #include <mach/vm_page_size.h>
11
+ #include <cstdio>
12
+ #include <mutex>
13
+ #include <set>
14
+ #include <unordered_set>
15
+
16
+ // this implementation is based on CUDACachingAllocator.
17
+ // It utilizes Metal Heaps to improve the performance with buffer allocation.
18
+ // Do not include this header. Use MPSAllocatorInterface.h instead.
19
+ // TODO: Unify the logic with CUDACachingAllocator and remove redundant code.
20
+ namespace at::mps::HeapAllocator {
21
+
22
+ static const size_t kMaxSmallAlloc = MB(1); // largest "small" allocation is 1 MiB
23
+ static const size_t kMinLargeAlloc = MB(10); // allocations between 1 and 10 MiB may use kLargeHeap
24
+ static const size_t kRoundLarge = MB(2); // round up large allocations to 2 MiB
25
+ static const size_t kSmallHeap = MB(8); // "small" allocations are packed in 8 MiB heaps
26
+ static const size_t kLargeHeap = MB(32); // "large" allocations may be packed in 32 MiB heaps
27
+ static const size_t kXLargeHeapD =
28
+ MB(128); // "extra large" allocations on Discrete devices may be packed in 128 MiB heaps
29
+ static const size_t kXLargeHeapU =
30
+ MB(1024); // "extra large" allocations on Unified devices may be packed in 1 GiB heaps
31
+ static const size_t kMaxScalarAlloc = (sizeof(int64_t)); // largest "scalar" allocation
32
+
33
+ // buffer pools could be customized with a combination of usage flags
34
+ enum UsageFlags : uint32_t {
35
+ PRIVATE = 0,
36
+ SMALL = (1 << 0), // small heaps have sizes of kSmallHeap, and large ones kLargeHeap
37
+ SHARED = (1 << 1), // shared pools allocated on devices with unified memory; otherwise, private between host/device
38
+ MANAGED = (1 << 2), // managed storage mode
39
+ HAZARD = (1 << 3), // enables Automatic Hazard Tracking for the resources allocated on the pool
40
+ SCALAR = (1 << 4), // used to import CPU scalar values to GPU and use them in MPS Stream
41
+ };
42
+ // debug verbosity flags
43
+ enum DebugVerbosity : uint32_t {
44
+ SILENT = 0,
45
+ PROFILING = (1 << 0), // print generic profiling data for total system memory usage
46
+ ALLOCATIONS = (1 << 1), // print buffer allocations
47
+ RECYCLES = (1 << 2), // print buffer recycling
48
+ RELEASES = (1 << 3), // print buffer releases
49
+ LARGE_ONLY = (1 << 4), // only log large buffer pool transactions
50
+ };
51
+
52
+ struct HeapBlock;
53
+
54
+ struct BufferBlock {
55
+ id<MTLBuffer> buffer;
56
+ void* cpu_ptr = nullptr; // stores the pointer to CPU mapping of a Shared MTLBuffer
57
+ size_t size; // size after alignment
58
+ size_t requested_size; // requested size (before alignment)
59
+ // buffer shape is used for retrieving base of views in cached graphs
60
+ std::vector<int64_t> shape;
61
+ bool in_use = false;
62
+ HeapBlock* heap;
63
+ id_t buf_id;
64
+ // counter to candidate least recently used buffers for garbage collection
65
+ uint32_t gc_count = 0;
66
+ uint32_t use_count = 0;
67
+ // counter to assign unique ids to buffer blocks
68
+ static uint64_t buffer_counter;
69
+ // Metal events used to sync GPU/CPU operations on the shared-storage buffers
70
+ MPSEventPtr event;
71
+
72
+ BufferBlock(size_t Size, size_t RequestedSize = 0, const id<MTLBuffer> Buffer = nullptr, HeapBlock* Heap = nullptr)
73
+ : buffer(Buffer), size(Size), requested_size(RequestedSize), heap(Heap), buf_id(Buffer ? ++buffer_counter : 0) {}
74
+
75
+ static bool Comparator(const BufferBlock* a, const BufferBlock* b) {
76
+ return (a->size != b->size) ? a->size < b->size : (uintptr_t)a->buffer < (uintptr_t)b->buffer;
77
+ }
78
+ static size_t alignUp(size_t Size, size_t Alignment) {
79
+ assert(((Alignment - 1) & Alignment) == 0);
80
+ return ((Size + Alignment - 1) & ~(Alignment - 1));
81
+ }
82
+ uint32_t retainCount() const {
83
+ return [buffer retainCount];
84
+ }
85
+ };
86
+ typedef bool (*BufferComparison)(const BufferBlock*, const BufferBlock*);
87
+
88
+ struct BufferPool;
89
+ struct AllocParams {
90
+ AllocParams(size_t Alloc_Size, size_t Requested_Size, BufferPool* Pool)
91
+ : search_key(Alloc_Size), pool(Pool), requested_size(Requested_Size) {}
92
+ size_t size() const {
93
+ return search_key.size;
94
+ }
95
+
96
+ BufferBlock search_key;
97
+ BufferPool* pool;
98
+ BufferBlock* buffer_block = nullptr;
99
+ size_t requested_size;
100
+ // true if we exceed the low watermark limit. In this case
101
+ // we apply strategies to relieve the pressure before allocation.
102
+ bool has_memory_pressure = false;
103
+ // true if we're allocating on a unified memory device
104
+ bool has_unified_memory = true;
105
+ };
106
+
107
+ struct HeapBlock {
108
+ id<MTLHeap> heap;
109
+ struct {
110
+ size_t total, available;
111
+ } size;
112
+ BufferPool* pool;
113
+ unsigned int n_buffers = 0;
114
+ id_t heap_id;
115
+ // indicates if we split this heap to sub-allocate 'several' buffers (otherwise single buffer)
116
+ bool is_split;
117
+ // counter to assign unique ids to heap blocks
118
+ static uint64_t heap_counter;
119
+
120
+ HeapBlock(size_t Size, const id<MTLHeap> Heap = nullptr, BufferPool* Pool = nullptr)
121
+ : heap(Heap),
122
+ size({.total = Size, .available = Size}),
123
+ pool(Pool),
124
+ heap_id(Heap ? ++heap_counter : 0),
125
+ is_split(true) {}
126
+
127
+ static MTLResourceOptions getOptions(uint32_t usage) {
128
+ // TODO: check the caching performance of write-combined mode
129
+ MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache;
130
+
131
+ if (usage & UsageFlags::MANAGED)
132
+ options |= MTLResourceStorageModeManaged;
133
+ else if (usage & UsageFlags::SHARED)
134
+ options |= MTLResourceStorageModeShared;
135
+ else
136
+ options |= MTLResourceStorageModePrivate;
137
+
138
+ options |=
139
+ (usage & UsageFlags::HAZARD) ? MTLResourceHazardTrackingModeTracked : MTLResourceHazardTrackingModeUntracked;
140
+
141
+ return options;
142
+ }
143
+
144
+ static HeapBlock* createHeapBlock(AllocParams& params, id<MTLDevice> device, uint32_t usage) {
145
+ HeapBlock* heapBlock = nullptr;
146
+ bool is_split = true;
147
+ const size_t size = params.size();
148
+ MTLHeapDescriptor* d = [MTLHeapDescriptor new];
149
+ if (d) {
150
+ const size_t kXLargeHeap = params.has_unified_memory ? kXLargeHeapU : kXLargeHeapD;
151
+ if (size <= kMaxSmallAlloc) {
152
+ d.size = kSmallHeap;
153
+ } else if (size < kMinLargeAlloc) {
154
+ d.size = kLargeHeap;
155
+ } else if (size < kXLargeHeap / 2 && !params.has_memory_pressure) {
156
+ d.size = kXLargeHeap;
157
+ } else {
158
+ d.size = kRoundLarge * ((size + kRoundLarge - 1) / kRoundLarge);
159
+ is_split = false;
160
+ }
161
+ d.storageMode = (usage & UsageFlags::SHARED) ? MTLStorageModeShared : MTLStorageModePrivate;
162
+ d.cpuCacheMode = MTLCPUCacheModeDefaultCache;
163
+ // this automatically handles Metal buffer access synchronizations at the
164
+ // cost of slightly lower performance.
165
+ d.hazardTrackingMode =
166
+ (usage & UsageFlags::HAZARD) ? MTLHazardTrackingModeTracked : MTLHazardTrackingModeUntracked;
167
+ d.resourceOptions = getOptions(usage);
168
+ d.type = MTLHeapTypeAutomatic;
169
+ id<MTLHeap> heap = [device newHeapWithDescriptor:d];
170
+ if (heap) {
171
+ [heap setPurgeableState:MTLPurgeableStateNonVolatile];
172
+ const size_t heap_size = heapAvailableSize(heap);
173
+ heapBlock = new HeapBlock(heap_size, heap, params.pool);
174
+ if (heapBlock) {
175
+ heapBlock->is_split = is_split;
176
+ }
177
+ }
178
+ [d release];
179
+ }
180
+ return heapBlock;
181
+ }
182
+ static bool Comparator(const HeapBlock* a, const HeapBlock* b) {
183
+ return (a->size.available != b->size.available) ? a->size.available < b->size.available
184
+ : (uintptr_t)a->heap < (uintptr_t)b->heap;
185
+ }
186
+ static NSUInteger heapAvailableSize(id<MTLHeap> heap, size_t Alignment = vm_page_size) {
187
+ return [heap maxAvailableSizeWithAlignment:Alignment];
188
+ }
189
+ NSUInteger Size() {
190
+ return [heap size];
191
+ }
192
+ id<MTLBuffer> newMTLBuffer(size_t length, uint32_t usage) {
193
+ id<MTLBuffer> buf = [heap newBufferWithLength:length options:getOptions(usage)];
194
+ if (buf) {
195
+ updateAvailableSize();
196
+ n_buffers++;
197
+ }
198
+ return buf;
199
+ }
200
+ // returns the retainCount before releasing the buffer
201
+ uint32_t releaseMTLBuffer(id<MTLBuffer>& buffer) {
202
+ const uint32_t retainCount = [buffer retainCount];
203
+ [buffer release];
204
+ buffer = nil;
205
+ updateAvailableSize();
206
+ n_buffers--;
207
+ return retainCount;
208
+ }
209
+ // returns the retainCount before releasing the heap
210
+ uint32_t releaseMTLHeap() {
211
+ const uint32_t retainCount = [heap retainCount];
212
+ TORCH_INTERNAL_ASSERT(!n_buffers); // assert if heap isn't empty
213
+ [heap setPurgeableState:MTLPurgeableStateEmpty];
214
+ [heap release];
215
+ heap = nil;
216
+ size.available = 0;
217
+ return retainCount;
218
+ }
219
+ uint32_t retainCount() const {
220
+ return [heap retainCount];
221
+ }
222
+ void updateAvailableSize() {
223
+ size.available = heapAvailableSize(heap);
224
+ }
225
+ };
226
+ typedef bool (*HeapComparison)(const HeapBlock*, const HeapBlock*);
227
+
228
+ struct BufferPool {
229
+ enum class Kind {
230
+ PRIVATE_SMALL,
231
+ PRIVATE_LARGE,
232
+ SHARED_SMALL,
233
+ SHARED_LARGE,
234
+ SCALAR,
235
+ };
236
+
237
+ BufferPool(const id<MTLDevice> Device, uint32_t Usage)
238
+ : device(Device), usage(Usage), heaps(HeapBlock::Comparator), available_buffers(BufferBlock::Comparator) {}
239
+
240
+ const id<MTLDevice> device;
241
+ // usage flags to customize the pool for various purposes (see UsageFlags enum)
242
+ const uint32_t usage;
243
+ // total number of buffers in the pool
244
+ uint32_t n_buffers = 0;
245
+ // total allocations size on this pool
246
+ size_t allocated_size = 0;
247
+ // total memory available in the pool
248
+ size_t available_size = 0;
249
+ // list of heaps ordered by their "available" (not total) memory size
250
+ std::set<HeapBlock*, HeapComparison> heaps;
251
+ // list of only "available" buffers in the pool (i.e., buffers not in-use)
252
+ std::set<BufferBlock*, BufferComparison> available_buffers;
253
+ // list of buffers that are in a state of "limbo" where they've already been freed
254
+ // from PyTorch-side, but were not returned to pool due to still being
255
+ // in-use by command buffers with retainCount > 1. In this state, the buffer is
256
+ // neither ready to be recycled, nor could be returned to pool as available.
257
+ // These buffers will be returned to pool once the command buffer's
258
+ // completionHandler callbacks are called.
259
+ std::unordered_set<BufferBlock*> buffers_pending_free;
260
+ // list of heaps pending size update
261
+ std::unordered_set<HeapBlock*> heaps_pending_update;
262
+ };
263
+
264
+ class MPSHeapAllocatorImpl {
265
+ public:
266
+ explicit MPSHeapAllocatorImpl()
267
+ : m_device(at::mps::MPSDevice::getInstance()->device()),
268
+ m_max_buffer_size([m_device maxBufferLength]),
269
+ m_stream(getDefaultMPSStream()),
270
+ m_event_pool(getMPSEventPool()) {
271
+ init_allocator();
272
+ }
273
+ ~MPSHeapAllocatorImpl() {
274
+ emptyCache();
275
+ }
276
+ // interface exposed to at::Allocator
277
+ id<MTLBuffer> malloc(size_t size, uint32_t usage);
278
+ // frees a buffer and returns it into buffer pool
279
+ void free(void* ptr);
280
+ // releases all the cached buffers and their associated heaps
281
+ void emptyCache();
282
+ // free inactive buffers that are pending to be freed
283
+ void freeInactiveBuffers();
284
+ // returns true if buffer was allocated from the shared pool
285
+ bool isSharedBuffer(const void* ptr);
286
+ // get the requested unaligned size of an MTLBuffer
287
+ ssize_t getUnalignedBufferSize(const void* ptr);
288
+ // set the shape of a base tensor from a view tensor
289
+ void setBufferShape(const void* ptr, const IntArrayRef& shape);
290
+ // retrieve the shape of a base tensor from a view tensor
291
+ IntArrayRef getBufferShape(const void* ptr);
292
+ // get the unique ID of the buffer
293
+ id_t getBufferId(const void* ptr);
294
+ // allocate a buffer from a specialized pool to import CPU scalars into GPU
295
+ id<MTLBuffer> allocScalarBufferWithValue(void* value, size_t size);
296
+ // returns a CPU-mapping of the input buffer and its retainCount,
297
+ // if only it has Shared storage-mode and allocated on MPSAllocator
298
+ std::pair<const void*, uint32_t> getSharedBufferPtr(const void* buffer);
299
+ // records events for a list of MTLBuffers (list is used to lock the mutex once)
300
+ // returns true if records any event (given if passed buffers exist and are shared-storage)
301
+ bool recordEvents(c10::ArrayRef<const void*> buffers);
302
+ // waits for the event to signal the completion of GPU execution
303
+ // on the passed shared buffers (list is used to lock the mutex once)
304
+ // returns true if actually waited on any event
305
+ bool waitForEvents(c10::ArrayRef<const void*> buffers);
306
+ // this indicates how far (in Megabytes) the current total allocations are from the
307
+ // low watermark limit which is used to detect if we're under memory pressure
308
+ // This returns zero if we've reached the low watermark limit
309
+ ssize_t getLowWatermarkValue();
310
+ // (see m_low_watermark_ratio for description)
311
+ void setLowWatermarkRatio(double ratio);
312
+ // (see m_high_watermark_ratio for description)
313
+ void setHighWatermarkRatio(double ratio);
314
+ // (see m_low_watermark_limit for description)
315
+ size_t getLowWatermarkLimit() const {
316
+ return m_low_watermark_limit;
317
+ }
318
+ // (see m_max_total_allowed_size for description)
319
+ size_t getHighWatermarkLimit() const {
320
+ return m_max_total_allowed_size;
321
+ }
322
+ // (see m_total_allocated_memory for description)
323
+ size_t getTotalAllocatedMemory() const {
324
+ return m_total_allocated_memory;
325
+ }
326
+ // (see m_current_allocated_memory for description)
327
+ size_t getCurrentAllocatedMemory() const {
328
+ return m_current_allocated_memory;
329
+ }
330
+ // total GPU memory allocated in the process by Metal driver; including
331
+ // implicit allocations from MPS/MPSGraph frameworks and MPSHeapAllocatorImpl.
332
+ size_t getDriverAllocatedMemory() const {
333
+ return current_allocated_size();
334
+ }
335
+ // recommended Max memory for Metal
336
+ size_t getRecommendedMaxMemory() const {
337
+ return max_device_size();
338
+ }
339
+ // (see enum DebugVerbosity for description)
340
+ uint32_t getDebugVerbosity() const {
341
+ return m_debug_verbosity;
342
+ }
343
+ // returns the device that we allocate from
344
+ inline id<MTLDevice> Device() const {
345
+ return m_device;
346
+ }
347
+
348
+ // TODO: make a common function to do size unit conversions in PyTorch.
349
+ inline std::string format_size(uint64_t size) const;
350
+
351
+ private:
352
+ // (see m_high_watermark_ratio for description)
353
+ constexpr static double default_high_watermark_ratio = 1.7;
354
+ // we set the allowed upper bound to twice the size of recommendedMaxWorkingSetSize.
355
+ constexpr static double default_high_watermark_upper_bound = 2.0;
356
+ // (see m_low_watermark_ratio for description)
357
+ // on unified memory, we could allocate beyond the recommendedMaxWorkingSetSize
358
+ constexpr static double default_low_watermark_ratio_unified = 1.4;
359
+ constexpr static double default_low_watermark_ratio_discrete = 1.0;
360
+
361
+ const id<MTLDevice> m_device;
362
+ std::recursive_mutex m_mutex;
363
+ // allocated buffers by device pointer
364
+ ska::flat_hash_map<const void*, BufferBlock*> m_allocated_buffers;
365
+ // using a container for pools to simplify iterating them
366
+ ska::flat_hash_map<BufferPool::Kind, std::unique_ptr<BufferPool>> m_pools;
367
+ // total memory allocated by HeapAllocator (including blocks in pools)
368
+ size_t m_total_allocated_memory = 0;
369
+ // currently active memory allocations in use (i.e., blocks not in pools)
370
+ size_t m_current_allocated_memory = 0;
371
+ // max buffer size allowed by Metal
372
+ size_t m_max_buffer_size = 0;
373
+ // maximum total size allowed to be allocated
374
+ size_t m_max_total_allowed_size = 0;
375
+ // high watermark ratio is a hard limit for the total allowed allocations
376
+ // 0. : disables high watermark limit (may cause system failure if system-wide OOM occurs)
377
+ // 1. : recommended maximum allocation size (i.e., device.recommendedMaxWorkingSetSize)
378
+ // >1.: allows limits beyond the device.recommendedMaxWorkingSetSize
379
+ // e.g., value 0.95 means we allocate up to 95% of recommended maximum
380
+ // allocation size; beyond that, the allocations would fail with OOM error.
381
+ double m_high_watermark_ratio;
382
+ // low watermark ratio is a soft limit to attempt limiting memory allocations up to the lower watermark
383
+ // level by garbage collection or committing command buffers more frequently (a.k.a, adaptive commit).
384
+ // Value between 0 to m_high_watermark_ratio (setting 0.0 disables adaptive commit and garbage collection)
385
+ // e.g., value 0.9 means we 'attempt' to limit allocations up to 90% of recommended maximum
386
+ // allocation size.
387
+ double m_low_watermark_ratio;
388
+ // low watermark size limit (in Bytes) at the time we initialize the allocator
389
+ size_t m_low_watermark_limit;
390
+ // use "PYTORCH_DEBUG_MPS_ALLOCATOR" env-var to set debug verbosity
391
+ uint32_t m_debug_verbosity;
392
+ // default MPS stream
393
+ MPSStream* m_stream;
394
+ // we hold a reference to MPSEventPool so it could get destroyed after MPSAllocator
395
+ std::shared_ptr<MPSEventPool> m_event_pool;
396
+
397
+ void init_allocator();
398
+ void init_buffer_pools();
399
+ HeapBlock* get_free_heap(AllocParams& params);
400
+ bool get_free_buffer(AllocParams& params);
401
+ BufferBlock* get_allocated_buffer_block(const void* ptr);
402
+ BufferBlock* alloc_buffer_block(size_t size, uint32_t usage);
403
+ bool alloc_buffer(AllocParams& params);
404
+ void free_buffer(BufferBlock* buffer_block);
405
+ // returns true if the container heap is also released
406
+ bool release_buffer(BufferBlock* buffer_block, bool remove_empty_heap = true);
407
+ void release_buffers(BufferPool& pool);
408
+ bool release_available_cached_buffers(AllocParams& params);
409
+ bool release_cached_buffers();
410
+ // free unused cached blocks to reclaim GPU memory if memory pressure is high
411
+ void garbage_collect_cached_buffers(AllocParams& params);
412
+ // returns the suitable buffer pool type for the usage or
413
+ // requested/allocated sizes
414
+ BufferPool& get_pool(size_t requested_size, size_t aligned_size, uint32_t usage);
415
+ // returns the aligned allocation size that is optimized
416
+ // for the buffers to get reused frequently
417
+ size_t get_allocation_size(size_t size, uint32_t usage) const;
418
+ // maximum size of device memory available for allocation in current process
419
+ // Note: the recommendedMaxWorkingSetSize is typically 75% of the total system memory.
420
+ size_t max_device_size() const {
421
+ return [m_device recommendedMaxWorkingSetSize];
422
+ }
423
+ // there are implicit allocations from MPS backend, so we need to query the 'device' for
424
+ // total allocated size instead of manually tracking in MPSAllocator
425
+ size_t current_allocated_size() const {
426
+ return [m_device currentAllocatedSize];
427
+ }
428
+
429
+ bool trigger_memory_callbacks(BufferBlock* buffer_block, IMpsAllocatorCallback::EventType event) const {
430
+ for (const auto& name : MPSAllocatorCallbacksRegistry()->Keys()) {
431
+ MPSAllocatorCallbacksRegistry()->Create(name)->executeMPSAllocatorCallback(
432
+ buffer_block ? buffer_block->buffer : nullptr, event);
433
+ }
434
+ return true;
435
+ }
436
+ };
437
+
438
+ } // namespace at::mps::HeapAllocator
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/core/ATen_fwd.h>
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/util/Registry.h>
8
+
9
+ #define MB(x) (x * 1048576UL)
10
+
11
+ namespace at::mps {
12
+
13
+ // this is a public interface to access MPSAllocator.
14
+ // Do not declare methods that would depend on MPS or Metal frameworks.
15
+ class IMPSAllocator : public c10::Allocator {
16
+ public:
17
+ // see the comments in MPSAllocator.h for the description of these methods.
18
+ virtual void emptyCache() const = 0;
19
+ virtual void freeInactiveBuffers() const = 0;
20
+ virtual ssize_t getUnalignedBufferSize(const void* ptr) const = 0;
21
+ virtual IntArrayRef getBufferShape(const void* ptr) const = 0;
22
+ virtual id_t getBufferId(const void* ptr) const = 0;
23
+ virtual void setBufferShape(const void* ptr, const IntArrayRef& shape)
24
+ const = 0;
25
+ virtual bool isSharedBuffer(const void* ptr) const = 0;
26
+ virtual bool isSharedStorageSupported() const = 0;
27
+ virtual c10::DataPtr allocScalarBufferWithValue(void* value, size_t size)
28
+ const = 0;
29
+ virtual std::string formatSize(size_t size) const = 0;
30
+ virtual void setLowWatermarkRatio(double ratio) const = 0;
31
+ virtual void setHighWatermarkRatio(double ratio) const = 0;
32
+ virtual ssize_t getLowWatermarkValue() const = 0;
33
+ virtual size_t getLowWatermarkLimit() const = 0;
34
+ virtual size_t getHighWatermarkLimit() const = 0;
35
+ virtual size_t getTotalAllocatedMemory() const = 0;
36
+ virtual size_t getCurrentAllocatedMemory() const = 0;
37
+ virtual size_t getDriverAllocatedMemory() const = 0;
38
+ virtual size_t getRecommendedMaxMemory() const = 0;
39
+ virtual std::pair<const void*, uint32_t> getSharedBufferPtr(
40
+ const void* ptr) const = 0;
41
+ virtual bool recordEvents(c10::ArrayRef<const void*> buffers) const = 0;
42
+ virtual bool waitForEvents(c10::ArrayRef<const void*> buffers) const = 0;
43
+ };
44
+
45
+ class IMpsAllocatorCallback {
46
+ public:
47
+ enum class EventType {
48
+ ALLOCATED, // buffer got allocated to be used immediately
49
+ RECYCLED, // buffer pulled from free list to be reused
50
+ FREED, // buffer put to free list for future recycling
51
+ RELEASED, // buffer memory released
52
+ ALLOCATION_FAILED // buffer allocation failed
53
+ };
54
+ virtual ~IMpsAllocatorCallback() = default;
55
+ virtual void executeMPSAllocatorCallback(void* ptr, EventType event) = 0;
56
+ };
57
+
58
+ // MPS allocator will execute every registered callback when a block of memory
59
+ // is freed.
60
+ TORCH_DECLARE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback);
61
+ #define REGISTER_MPS_ALLOCATOR_CALLBACK(name, ...) \
62
+ C10_REGISTER_CLASS(MPSAllocatorCallbacksRegistry, name, __VA_ARGS__)
63
+
64
+ IMPSAllocator* getIMPSAllocator(bool sharedAllocator = false);
65
+
66
+ bool isMPSPinnedPtr(const void* data);
67
+
68
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSDevice.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+ #include <c10/core/Allocator.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ #ifdef __OBJC__
9
+ #include <Foundation/Foundation.h>
10
+ #include <Metal/Metal.h>
11
+ typedef id<MTLDevice> MTLDevice_t;
12
+ #else
13
+ typedef void* MTLDevice_t;
14
+ #endif
15
+
16
+ namespace at::mps {
17
+
18
+ // Helper enum to check if a MPSGraph op is supported in a given macOS version
19
+ enum class MacOSVersion : uint32_t {
20
+ MACOS_VER_13_1_PLUS = 0,
21
+ MACOS_VER_13_2_PLUS,
22
+ MACOS_VER_13_3_PLUS,
23
+ MACOS_VER_14_0_PLUS,
24
+ MACOS_VER_14_4_PLUS,
25
+ MACOS_VER_15_0_PLUS,
26
+ MACOS_VER_15_1_PLUS,
27
+ MACOS_VER_15_2_PLUS,
28
+ };
29
+
30
+ //-----------------------------------------------------------------
31
+ // MPSDevice
32
+ //
33
+ // MPSDevice is a singleton class that returns the default device
34
+ //-----------------------------------------------------------------
35
+
36
+ class TORCH_API MPSDevice {
37
+ public:
38
+ /**
39
+ * MPSDevice should not be cloneable.
40
+ */
41
+ MPSDevice(MPSDevice& other) = delete;
42
+ /**
43
+ * MPSDevice should not be assignable.
44
+ */
45
+ void operator=(const MPSDevice&) = delete;
46
+ /**
47
+ * Gets single instance of the Device.
48
+ */
49
+ static MPSDevice* getInstance();
50
+ /**
51
+ * Returns the single device.
52
+ */
53
+ MTLDevice_t device() {
54
+ return _mtl_device;
55
+ }
56
+ /**
57
+ * Returns whether running on Ventura or newer
58
+ */
59
+ bool isMacOS13Plus(MacOSVersion version) const;
60
+
61
+ ~MPSDevice();
62
+
63
+ private:
64
+ static MPSDevice* _device;
65
+ MTLDevice_t _mtl_device;
66
+ MPSDevice();
67
+ };
68
+
69
+ TORCH_API bool is_available();
70
+ TORCH_API bool is_macos_13_or_newer(MacOSVersion version);
71
+ TORCH_API at::Allocator* GetMPSAllocator(bool useSharedAllocator = false);
72
+
73
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSEvent.h ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2023 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/mps/MPSStream.h>
6
+ #include <ctime>
7
+ #include <stack>
8
+
9
+ namespace at::mps {
10
+
11
+ // NOTE: don't create instances of this class directly.
12
+ // Use MPSEventPool to acquire instances of MPSEvent.
13
+ class MPSEvent {
14
+ public:
15
+ explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing);
16
+ ~MPSEvent();
17
+
18
+ // records an event on the stream
19
+ void record(bool needsLock, bool syncEvent = false);
20
+ // makes all future work submitted to the stream wait for this event.
21
+ bool wait(bool needsLock, bool syncEvent = false);
22
+ // schedules a notifyListener callback for the event.
23
+ bool notify(bool needsLock, MTLSharedEventNotificationBlock block);
24
+ // checks if events are already signaled.
25
+ bool query() const;
26
+ // blocks the CPU thread until all the GPU work that were scheduled
27
+ // prior to recording this event are completed.
28
+ bool synchronize();
29
+ // resets this event with new parameters in case it gets reused from the event
30
+ // pool
31
+ void reset(MPSStream* stream, bool enable_timing);
32
+ // returns the unique ID of the event instance
33
+ id_t getID() const {
34
+ return m_id;
35
+ }
36
+ // returns the completion timestamp of the event
37
+ uint64_t getCompletionTime() const {
38
+ return m_completion_time;
39
+ }
40
+ // if already recorded, waits for cpu_sync_cv to be signaled
41
+ void waitForCpuSync();
42
+
43
+ private:
44
+ id_t m_id;
45
+ // enables measuring the completion time of the notifyListener of this event
46
+ bool m_enable_timing;
47
+ uint64_t m_signalCounter = 0;
48
+ MPSStream* m_stream = nullptr;
49
+ MTLSharedEvent_t m_event = nullptr;
50
+ MTLSharedEventListener* m_listener = nullptr;
51
+ // used to sync the events created on this Stream with CPU
52
+ std::mutex m_cpu_sync_mutex{};
53
+ std::condition_variable m_cpu_sync_cv{};
54
+ // CondVar predicate to sync the events created on this Stream with CPU
55
+ bool m_cpu_sync_completed = false;
56
+ // used to compute elapsed time
57
+ uint64_t m_completion_time = 0;
58
+
59
+ void recordLocked(bool syncEvent);
60
+ bool waitLocked(bool syncEvent);
61
+ bool notifyLocked(MTLSharedEventNotificationBlock block);
62
+ void notifyCpuSync();
63
+ static uint64_t getTime() {
64
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
65
+ }
66
+ };
67
+
68
+ typedef std::unique_ptr<MPSEvent, std::function<void(MPSEvent*)>> MPSEventPtr;
69
+
70
+ class MPSEventPool {
71
+ public:
72
+ explicit MPSEventPool(MPSStream* default_stream);
73
+ ~MPSEventPool();
74
+
75
+ MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream);
76
+ void emptyCache();
77
+
78
+ // these are mainly used for MPSHooks and torch.mps.Event() bindings
79
+ id_t acquireEvent(bool enable_timing);
80
+ void releaseEvent(id_t event_id);
81
+ void recordEvent(id_t event_id, bool syncEvent);
82
+ void waitForEvent(id_t event_id, bool syncEvent);
83
+ void synchronizeEvent(id_t event_id);
84
+ bool queryEvent(id_t event_id);
85
+ // returns elapsed time between two recorded events in milliseconds
86
+ double elapsedTime(id_t start_event_id, id_t end_event_id);
87
+
88
+ private:
89
+ MPSStream* m_default_stream = nullptr;
90
+ std::recursive_mutex m_mutex;
91
+ std::stack<std::unique_ptr<MPSEvent>> m_pool{};
92
+ // dictionary to associate event IDs with event objects
93
+ // used to retain in-use events out of the pool
94
+ // for torch.mps.Event() bindings.
95
+ std::unordered_map<id_t, MPSEventPtr> m_in_use_events{};
96
+ uint64_t m_event_counter = 0;
97
+ std::function<void(MPSEvent*)> m_default_deleter;
98
+
99
+ MPSEvent* getInUseEvent(id_t event_id, bool locked = true);
100
+ };
101
+
102
+ // shared_ptr is used to get MPSEventPool destroyed after dependent instances
103
+ std::shared_ptr<MPSEventPool> getMPSEventPool();
104
+
105
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/core/Generator.h>
6
+ #include <ATen/core/PhiloxRNGEngine.h>
7
+ #include <c10/core/GeneratorImpl.h>
8
+ #include <optional>
9
+
10
+ namespace at {
11
+ namespace mps::detail {
12
+
13
+ constexpr uint32_t PHILOX_STATE_N = 7;
14
+ struct rng_data_pod {
15
+ std::array<uint32_t, PHILOX_STATE_N> state{1};
16
+ uint64_t seed = default_rng_seed_val;
17
+ };
18
+
19
+ TORCH_API const Generator& getDefaultMPSGenerator();
20
+ TORCH_API Generator
21
+ createMPSGenerator(uint64_t seed_val = default_rng_seed_val);
22
+
23
+ } // namespace mps::detail
24
+
25
+ struct TORCH_API MPSGeneratorImpl : public c10::GeneratorImpl {
26
+ // Constructors
27
+ MPSGeneratorImpl(uint64_t seed_in = default_rng_seed_val);
28
+ ~MPSGeneratorImpl() override = default;
29
+
30
+ // MPSGeneratorImpl methods
31
+ std::shared_ptr<MPSGeneratorImpl> clone() const;
32
+ void set_current_seed(uint64_t seed) override;
33
+ void set_offset(uint64_t offset) override;
34
+ uint64_t get_offset() const override;
35
+ uint64_t current_seed() const override;
36
+ uint64_t seed() override;
37
+ void set_state(const c10::TensorImpl& new_state) override;
38
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
39
+ void update_philox_counters();
40
+
41
+ void set_engine(at::Philox4_32 engine) {
42
+ engine_ = engine;
43
+ }
44
+ at::Philox4_32 engine() {
45
+ return engine_;
46
+ }
47
+ uint32_t* state_data() {
48
+ return data_.state.data();
49
+ }
50
+ static DeviceType device_type() {
51
+ return DeviceType::MPS;
52
+ }
53
+
54
+ private:
55
+ mps::detail::rng_data_pod data_;
56
+ at::Philox4_32 engine_;
57
+
58
+ MPSGeneratorImpl* clone_impl() const override;
59
+ };
60
+
61
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSGuardImpl.h ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+ #include <ATen/Context.h>
5
+ #include <ATen/mps/MPSEvent.h>
6
+ #include <ATen/mps/MPSStream.h>
7
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
8
+ #include <c10/macros/Macros.h>
9
+ #include <c10/util/Exception.h>
10
+
11
+ #ifdef __OBJC__
12
+ #include <Foundation/Foundation.h>
13
+ #include <Metal/Metal.h>
14
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
15
+ #endif
16
+
17
+ #include <ATen/Tensor.h>
18
+ #include <c10/core/MemoryFormat.h>
19
+ #include <c10/core/Storage.h>
20
+ #include <c10/core/TensorImpl.h>
21
+ #include <c10/core/UndefinedTensorImpl.h>
22
+ #include <c10/util/intrusive_ptr.h>
23
+ #include <sys/_types/_size_t.h>
24
+ #include <memory>
25
+
26
+ namespace at::mps {
27
+
28
+ typedef MPSEvent* mpsEvent_t;
29
+
30
+ // TODO: Move the MPSGuardImpl to inherit from NoOpDeviceGuardImpl
31
+ // https://github.com/pytorch/pytorch/issues/77170
32
+ struct TORCH_API MPSGuardImpl final
33
+ : public c10::impl::DeviceGuardImplInterface {
34
+ static constexpr c10::DeviceType static_type = c10::DeviceType::MPS;
35
+
36
+ // constructor
37
+ MPSGuardImpl() {}
38
+ explicit MPSGuardImpl(c10::DeviceType t) {
39
+ TORCH_INTERNAL_ASSERT(t == c10::DeviceType::MPS);
40
+ }
41
+
42
+ // returns the type
43
+ c10::DeviceType type() const override {
44
+ return c10::DeviceType::MPS;
45
+ }
46
+
47
+ Device exchangeDevice(Device d) const override {
48
+ return Device(c10::DeviceType::MPS, 0);
49
+ }
50
+
51
+ Device getDevice() const override {
52
+ return Device(c10::DeviceType::MPS, 0);
53
+ }
54
+
55
+ std::optional<Device> uncheckedGetDevice() const noexcept {
56
+ return Device(c10::DeviceType::MPS, 0);
57
+ }
58
+
59
+ void setDevice(Device d) const override {
60
+ TORCH_INTERNAL_ASSERT(d.is_mps());
61
+ }
62
+
63
+ void uncheckedSetDevice(Device d) const noexcept override {
64
+ // TODO: Currently setting only device 0
65
+ }
66
+
67
+ Stream getStream(Device d) const override {
68
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
69
+ }
70
+
71
+ Stream getNewStream(Device, int priority = 0) const override {
72
+ (void)priority;
73
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
74
+ }
75
+
76
+ Stream getDefaultStream(Device d) const override {
77
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
78
+ }
79
+
80
+ // NB: These do NOT set the current device
81
+ Stream exchangeStream(Stream s) const override {
82
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
83
+ }
84
+ DeviceIndex deviceCount() const noexcept override {
85
+ if (at::hasMPS()) {
86
+ // TODO: extend it for multi-device case
87
+ return 1;
88
+ } else {
89
+ return 0;
90
+ }
91
+ }
92
+
93
+ // Event-related functions
94
+ void createEvent(mpsEvent_t* event, const EventFlag flag) const;
95
+
96
+ void destroyEvent(void* event, const DeviceIndex device_index)
97
+ const noexcept override;
98
+
99
+ void record(
100
+ void** event,
101
+ const Stream& stream,
102
+ const DeviceIndex device_index,
103
+ const EventFlag flag) const override;
104
+
105
+ void block(void* event, const Stream& stream) const override;
106
+
107
+ bool queryEvent(void* event) const override;
108
+
109
+ void synchronizeEvent(void* event) const override;
110
+
111
+ double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
112
+ const override;
113
+
114
+ void synchronizeDevice(const DeviceIndex device_index) const override;
115
+ };
116
+
117
+ /// A variant of OptionalDeviceGuard that is specialized for MPS.
118
+ struct OptionalMPSGuard {
119
+ explicit OptionalMPSGuard() : guard_() {}
120
+
121
+ explicit OptionalMPSGuard(std::optional<Device> device_opt)
122
+ : guard_(device_opt) {}
123
+
124
+ /// Set the current MPS device to the passed device index, if it is not
125
+ /// nullopt
126
+ explicit OptionalMPSGuard(std::optional<DeviceIndex> device_index_opt)
127
+ : guard_(device_index_opt) {}
128
+
129
+ // Copy is not allowed
130
+ OptionalMPSGuard(const OptionalMPSGuard&) = delete;
131
+ OptionalMPSGuard& operator=(const OptionalMPSGuard&) = delete;
132
+ OptionalMPSGuard(OptionalMPSGuard&& other) = delete;
133
+ OptionalMPSGuard& operator=(OptionalMPSGuard&& other) = delete;
134
+
135
+ /// Sets the MPS device to the given device, initializing the guard if it
136
+ /// is not already initialized. Errors if the given device is not a MPS
137
+ /// device.
138
+ void set_device(Device device) {
139
+ guard_.set_device(device);
140
+ }
141
+
142
+ /// Sets the MPS device to the given device, initializing the guard if it is
143
+ /// not already initialized. Errors if the given device is not a MPS device.
144
+ void reset_device(Device device) {
145
+ guard_.reset_device(device);
146
+ }
147
+
148
+ /// Sets the MPS device to the given device index, initializing the guard if
149
+ /// it is not already initialized.
150
+ void set_index(DeviceIndex device_index) {
151
+ guard_.set_index(device_index);
152
+ }
153
+
154
+ /// Returns the device that was set immediately prior to initialization of the
155
+ /// guard, or nullopt if the guard is uninitialized.
156
+ std::optional<Device> original_device() const {
157
+ return guard_.original_device();
158
+ }
159
+
160
+ /// Returns the most recent device that was set using this device guard,
161
+ /// either from construction, or via set_device, if the guard is initialized,
162
+ /// or nullopt if the guard is uninitialized.
163
+ std::optional<Device> current_device() const {
164
+ return guard_.current_device();
165
+ }
166
+
167
+ /// Restore the original MPS device, resetting this guard to uninitialized
168
+ /// state.
169
+ void reset() {
170
+ guard_.reset();
171
+ }
172
+
173
+ private:
174
+ c10::impl::InlineOptionalDeviceGuard<MPSGuardImpl> guard_;
175
+ };
176
+
177
+ C10_REGISTER_GUARD_IMPL(MPS, MPSGuardImpl)
178
+
179
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSHooks.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/Generator.h>
6
+ #include <ATen/detail/MPSHooksInterface.h>
7
+ #include <ATen/mps/MPSEvent.h>
8
+ #include <optional>
9
+
10
+ namespace at::mps {
11
+
12
+ // The real implementation of MPSHooksInterface
13
+ struct MPSHooks : public at::MPSHooksInterface {
14
+ MPSHooks(at::MPSHooksArgs) {}
15
+ void init() const override;
16
+
17
+ // MPSDevice interface
18
+ bool hasMPS() const override;
19
+ bool isOnMacOSorNewer(unsigned major, unsigned minor) const override;
20
+
21
+ // MPSGeneratorImpl interface
22
+ const Generator& getDefaultGenerator(
23
+ DeviceIndex device_index = -1) const override;
24
+ Generator getNewGenerator(DeviceIndex device_index = -1) const override;
25
+
26
+ // MPSStream interface
27
+ void deviceSynchronize() const override;
28
+ void commitStream() const override;
29
+ void* getCommandBuffer() const override;
30
+ void* getDispatchQueue() const override;
31
+
32
+ // MPSAllocator interface
33
+ Allocator* getMPSDeviceAllocator() const override;
34
+ void emptyCache() const override;
35
+ size_t getCurrentAllocatedMemory() const override;
36
+ size_t getDriverAllocatedMemory() const override;
37
+ size_t getRecommendedMaxMemory() const override;
38
+ void setMemoryFraction(double ratio) const override;
39
+ bool isPinnedPtr(const void* data) const override;
40
+ Allocator* getPinnedMemoryAllocator() const override;
41
+
42
+ // MPSProfiler interface
43
+ void profilerStartTrace(const std::string& mode, bool waitUntilCompleted)
44
+ const override;
45
+ void profilerStopTrace() const override;
46
+
47
+ // MPSEvent interface
48
+ uint32_t acquireEvent(bool enable_timing) const override;
49
+ void releaseEvent(uint32_t event_id) const override;
50
+ void recordEvent(uint32_t event_id) const override;
51
+ void waitForEvent(uint32_t event_id) const override;
52
+ void synchronizeEvent(uint32_t event_id) const override;
53
+ bool queryEvent(uint32_t event_id) const override;
54
+ double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id)
55
+ const override;
56
+
57
+ bool isBuilt() const override {
58
+ return true;
59
+ }
60
+ bool isAvailable() const override {
61
+ return hasMPS();
62
+ }
63
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
64
+ // When MPS is available, it is always in use for the one device.
65
+ return true;
66
+ }
67
+ };
68
+
69
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSProfiler.h ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <ATen/Tensor.h>
6
+ #include <ATen/mps/MPSAllocatorInterface.h>
7
+ #include <ATen/mps/MPSStream.h>
8
+
9
+ #include <os/log.h>
10
+ #include <os/signpost.h>
11
+
12
+ #include <atomic>
13
+ #include <ctime>
14
+ #include <sstream>
15
+ #include <string>
16
+ #include <unordered_map>
17
+ #include <utility>
18
+
19
+ #ifndef __OBJC__
20
+ typedef void* MTLCaptureManager;
21
+ #endif
22
+
23
+ namespace at::mps {
24
+
25
+ namespace Profiler {
26
+
27
+ struct BaseInfo {
28
+ // profiling info types
29
+ enum class Type {
30
+ GRAPH,
31
+ KERNEL,
32
+ COPY,
33
+ CPU_FALLBACK,
34
+ };
35
+
36
+ BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle)
37
+ : type(infoType), profileId(Id), handle(Handle) {}
38
+ virtual ~BaseInfo() = default;
39
+
40
+ // type of profiling info
41
+ Type type;
42
+ // unique profile ID for execution instances of operations or copies
43
+ uint64_t profileId;
44
+ // ID generated by os_signpost
45
+ // since it's possible to use event and interval-based signposts at the
46
+ // same time, we need separate IDs for each.
47
+ os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0;
48
+ // accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime -
49
+ // GPUStartTime")
50
+ std::atomic<double> totalGpuTime{0.0};
51
+ // accumulated Scheduling time in ms (obtained from CompletionHandler's
52
+ // "KernelEndTime - KernelStartTime")
53
+ std::atomic<double> totalSchedulingTime{0.0};
54
+ // indicates if the operation or copy execution has completed
55
+ std::atomic_bool completed{false};
56
+ // handle used to identify the profile info's instance (usually the pointer)
57
+ const uintptr_t handle;
58
+
59
+ virtual const std::string toString(
60
+ double gpuTime = 0,
61
+ double schedulingTime = 0) const;
62
+ // builds a string for a tensor (format: Device:ScalarType[tensor.sizes()])
63
+ static std::string buildTensorString(
64
+ const Tensor& tensor,
65
+ bool includeBufferId = false);
66
+ static uint64_t getTime() {
67
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
68
+ }
69
+ };
70
+
71
+ struct OperationInfo : BaseInfo {
72
+ OperationInfo(
73
+ const void* Handle,
74
+ bool IsGraph,
75
+ uint64_t Id,
76
+ const std::string& StrKey)
77
+ : BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)),
78
+ strKey(StrKey) {}
79
+
80
+ uint64_t runCount = 0;
81
+ std::string strKey;
82
+
83
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
84
+ const override;
85
+
86
+ // builds a string for a kernel
87
+ static std::string buildKernelString(
88
+ const std::string& kernelName,
89
+ const TensorList& tensors,
90
+ bool includeBufferId = false) {
91
+ std::stringstream kernelStr;
92
+ kernelStr << kernelName;
93
+ for (const Tensor& tensor : tensors) {
94
+ kernelStr << ":" << BaseInfo::buildTensorString(tensor, includeBufferId);
95
+ }
96
+ return kernelStr.str();
97
+ }
98
+ };
99
+
100
+ struct CpuFbInfo : BaseInfo {
101
+ CpuFbInfo(uint64_t Id, const std::string& OpName)
102
+ : BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {}
103
+
104
+ uint64_t runCount = 0;
105
+ // the current and total overhead of copies in bytes required to convert the
106
+ // Op's input tensors from MPS to CPU and then output from CPU back to MPS
107
+ size_t currentCopyOverhead = 0;
108
+ size_t totalCopyOverhead = 0;
109
+ std::string opName;
110
+ std::string strKey;
111
+ uint64_t startTime = 0;
112
+
113
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
114
+ const override;
115
+
116
+ void updateCopyOverhead(const TensorList& tensors) {
117
+ currentCopyOverhead = 0;
118
+ for (const Tensor& tensor : tensors) {
119
+ if (tensor.defined()) {
120
+ currentCopyOverhead += tensor.nbytes();
121
+ }
122
+ }
123
+ totalCopyOverhead += currentCopyOverhead;
124
+ }
125
+ };
126
+
127
+ struct CopyInfo : BaseInfo {
128
+ enum class Kind {
129
+ MPS_TO_MPS,
130
+ MPS_TO_CPU,
131
+ CPU_TO_MPS,
132
+ };
133
+
134
+ CopyInfo(
135
+ const void* Handle,
136
+ size_t Length,
137
+ uint64_t Id,
138
+ bool IsNonBlocking,
139
+ bool UsesBlitter)
140
+ : BaseInfo(Type::COPY, Id, uintptr_t(Handle)),
141
+ kind(Kind::MPS_TO_MPS),
142
+ length(Length),
143
+ isNonBlocking(IsNonBlocking),
144
+ usesBlitter(UsesBlitter) {}
145
+
146
+ Kind kind;
147
+ size_t length;
148
+ bool isNonBlocking;
149
+ bool usesBlitter;
150
+ std::string srcStrKey;
151
+ std::string dstStrKey;
152
+ // for copies that don't use blitters, we measure CPU time
153
+ uint64_t startTime = 0;
154
+
155
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
156
+ const override;
157
+
158
+ static std::string buildTensorString(
159
+ const void* buffer,
160
+ const OptionalTensorRef tensor,
161
+ bool includeBufferId = false);
162
+
163
+ static bool isStorageOnMPS(
164
+ const void* buffer,
165
+ const OptionalTensorRef tensor) {
166
+ if (tensor.has_value()) {
167
+ return tensor->device().type() == at::kMPS;
168
+ }
169
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer);
170
+ // getUnalignedBufferSize() returns -1 if input buffer is not on MPS device
171
+ return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0;
172
+ }
173
+
174
+ static Kind getCopyKind(
175
+ const void* srcBuffer,
176
+ const void* dstBuffer,
177
+ const OptionalTensorRef srcTensor,
178
+ const OptionalTensorRef dstTensor) {
179
+ const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor);
180
+ const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor);
181
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS);
182
+ if (isSrcOnMPS && !isDstOnMPS) {
183
+ return Kind::MPS_TO_CPU;
184
+ } else if (!isSrcOnMPS && isDstOnMPS) {
185
+ return Kind::CPU_TO_MPS;
186
+ }
187
+ return Kind::MPS_TO_MPS;
188
+ }
189
+ };
190
+
191
+ struct CopyStat : CopyInfo {
192
+ explicit CopyStat(std::string CopyKindStr)
193
+ : CopyInfo(nullptr, 0, 0, false, false),
194
+ kindStr(std::move(CopyKindStr)) {}
195
+ // total number of copies
196
+ size_t totalCount = 0;
197
+ // number of Scalar copies (i.e., less than sizeof(int64))
198
+ size_t scalarsCount = 0;
199
+ // number of blocking copies (i.e., require syncing to GPU)
200
+ size_t blockingCount = 0;
201
+ // number of copies that used memcpy(), instead of Metal Blit Encoder
202
+ size_t memcpyCount = 0;
203
+ // accumulated GPU time in ms for the scalar copies
204
+ std::atomic<double> scalarsGpuTime{0.0};
205
+ // copy kind in string type
206
+ std::string kindStr;
207
+ };
208
+
209
+ class MPSProfiler {
210
+ public:
211
+ // lower 16 bits used for profiler options
212
+ enum ProfileOptions : uint32_t {
213
+ OPTIONS_NONE = 0,
214
+ // ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK,
215
+ // etc.) (used for convenience to not compute bit flags by OR-ing manually)
216
+ // trace all signpost types using events
217
+ ALL_SIGNPOST_EVENTS = (1 << 0),
218
+ // trace all signpost types using intervals
219
+ ALL_SIGNPOST_INTERVALS = (1 << 1),
220
+ // always wait for command buffer to finish executing after each commit
221
+ WAIT_UNTIL_COMPLETED = (1 << 2),
222
+ // for interval-based signposts, include the scheduling portion of
223
+ // Graph/Kernel/Copy executions as well.
224
+ // if flag is disable, only "GPU run time" is included in interval,
225
+ // and not schedule time.
226
+ INCLUDE_SCHEDULE_INTERVAL = (1 << 3),
227
+
228
+ // use these if you need to trace signposts types individually (rarely
229
+ // required) trace signpost using intervals
230
+ USE_INTERVALS = (1 << 4),
231
+ // trace signpost by emitting events
232
+ USE_EVENTS = (1 << 5),
233
+ // used for sanity check (Change this when new option added)
234
+ OPTIONS_COUNT = (USE_EVENTS << 1) - 1,
235
+ };
236
+
237
+ // when adding new types, #define the type string in MPSProfiler.mm as well.
238
+ // upper 16 bits used for event types
239
+ enum SignpostTypes : uint32_t {
240
+ SIGNPOST_NONE = 0,
241
+ // trace signposts for PyTorch operation executions
242
+ RUN_OPERATION = (1 << 16),
243
+ // trace signposts for blitter copies
244
+ BLIT_COPY = (1 << 17),
245
+ // trace signposts for ops that fall back on CPU
246
+ CPU_FALLBACK = (1 << 18),
247
+ // used for sanity check (Change this when new type added)
248
+ SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1,
249
+ };
250
+
251
+ enum LogOptions : uint32_t {
252
+ LOG_NONE = 0,
253
+
254
+ // Info logging options during execution
255
+ // -------------------------------------
256
+ // prints operation info (id/key/run_count) during execution
257
+ OPERATION_INFO = (1 << 0),
258
+ // prints copy info (src/dst tensors/buffers, size, etc.) during execution
259
+ COPY_INFO = (1 << 1),
260
+ // prints CPU Fallback info (id/runCount/opName/copyOverhead) during
261
+ // execution
262
+ CPU_FALLBACK_INFO = (1 << 2),
263
+
264
+ // Profiling Statistics logging options when process terminates
265
+ // ------------------------------------------------------------
266
+ // prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before
267
+ // process terminates this is convenient to not combine following stats bit
268
+ // flags manually
269
+ ALL_STATS = (1 << 3),
270
+ // prints operation stats (GPU times, run count, etc.) before process
271
+ // terminates
272
+ OPERATION_STATS = (1 << 4),
273
+ // prints copies stats (GPU times, copy kinds, sizes, etc.) before process
274
+ // terminates
275
+ COPY_STATS = (1 << 5),
276
+ // prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies
277
+ // for tensors, etc.) before process terminates
278
+ CPU_FALLBACK_STATS = (1 << 6),
279
+
280
+ // Metadata format options when logging the info
281
+ // ---------------------------------------------
282
+ // if enabled, includes GPU run time in metadata (i.e.,
283
+ // GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324
284
+ // ms])
285
+ INCLUDE_GPU_TIME = (1 << 7),
286
+ // if enabled, includes GPU scheduling time in metadata separately
287
+ // (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers)
288
+ // e.g., [GPU=0.324 ms, KRNL=0.036 ms]
289
+ INCLUDE_KERNEL_TIME = (1 << 8),
290
+ // if enabled, includes the unique buffer ID in metadata for the storage
291
+ // of a tensor that was allocated on MPSAllocator. This is useful (along
292
+ // with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are
293
+ // involved with various operations.
294
+ INCLUDE_BUFFER_ID = (1 << 9),
295
+
296
+ // used for sanity check (Change this when new option added)
297
+ LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1,
298
+ };
299
+
300
+ explicit MPSProfiler();
301
+ ~MPSProfiler();
302
+
303
+ // the handle is either "MPSGraph*" or "id<MTLComputePipelineState>" for Metal
304
+ // Kernels the beginProfile*() functions return a profileId which is unique
305
+ // per graph/kernel/copy
306
+ uint64_t beginProfileKernel(
307
+ const void* handle,
308
+ const std::string& strKey,
309
+ bool isGraph);
310
+ uint64_t beginProfileKernel(
311
+ const void* handle,
312
+ const std::string& kernelName,
313
+ const TensorList& tensors);
314
+ uint64_t beginProfileCopy(
315
+ const void* srcBuffer,
316
+ const void* dstBuffer,
317
+ const OptionalTensorRef srcTensor,
318
+ const OptionalTensorRef dstTensor,
319
+ size_t length,
320
+ bool isNonBlocking,
321
+ bool usesBlitter = true);
322
+ uint64_t beginProfileCPUFallback(
323
+ const std::string& opName,
324
+ const TensorList& tensors);
325
+ void beginProfileGPUInterval(const void* handle);
326
+
327
+ void endProfileCopy(uint64_t profileId, SyncType syncType);
328
+ void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE);
329
+ void endProfileCPUFallback(const std::string& opName);
330
+
331
+ // these are used to hook into Python bindings for torch.mps.profiler module.
332
+ // this enables generating OS Signpost traces from MPSProfiler on-demand
333
+ // during runtime (instead of environment variables).
334
+ // The "mode" could be either "interval", "event", or both "interval,event"
335
+ // for interval-based and/or event-based signpost tracing.
336
+ void StartTrace(const std::string& mode, bool waitUntilCompleted);
337
+ void StopTrace();
338
+
339
+ // Abstractions for GPU trace capturing
340
+ bool isCaptureEnabled() const;
341
+ bool isCapturing() const;
342
+ void startCapture(const std::string& name, MPSStream* stream = nullptr);
343
+ void stopCapture(MPSStream* stream = nullptr);
344
+
345
+ // convenience functions to indicate whether signpost tracing or
346
+ // logging are enabled for the SignpostTypes
347
+ bool isOperationProfilingEnabled() const {
348
+ return (m_signpost_types & SignpostTypes::RUN_OPERATION) ||
349
+ (m_log_options &
350
+ (LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS));
351
+ }
352
+ bool isCopyProfilingEnabled() const {
353
+ return (m_signpost_types & SignpostTypes::BLIT_COPY) ||
354
+ (m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS));
355
+ }
356
+ bool isCPUFallbackProfilingEnabled() const {
357
+ return (m_signpost_types & SignpostTypes::CPU_FALLBACK) ||
358
+ (m_log_options &
359
+ (LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS));
360
+ }
361
+ bool isSignpostTracingEnabled() const {
362
+ return (m_signpost_types != SignpostTypes::SIGNPOST_NONE);
363
+ }
364
+
365
+ private:
366
+ // indicates what type of signpost types are enabled and traced by MPS
367
+ // profiler.
368
+ uint32_t m_signpost_types = 0;
369
+ uint32_t m_profile_options = 0;
370
+ uint32_t m_log_options = 0;
371
+ uint64_t m_kernel_counter = 0;
372
+ uint64_t m_graph_counter = 0;
373
+ uint64_t m_cpu_fb_counter = 0;
374
+ uint64_t m_copy_counter = 0;
375
+ // technically, it's possible to trace both events and intervals at the same
376
+ // time so we use separate os_log categories for them
377
+ os_log_t m_os_log_events;
378
+ os_log_t m_os_log_intervals;
379
+ // stats logging could run either from destructor or signal handler
380
+ // so this is used to check if logging has already started.
381
+ std::atomic_bool hasLoggedStats{false};
382
+ // indicates there are pending completionHandler callbacks that haven't been
383
+ // called yet.
384
+ std::atomic_bool hasPendingCompletionHandlers{false};
385
+ // used to capture sigint signal to log profiling stats
386
+ static struct sigaction currentSigint, previousSigint;
387
+
388
+ // We use the following lists for two reasons:
389
+ // 1- for interval-based signposts the "begin" point won't be in same function
390
+ // as the "end" point where we need to be able to retrieve signpost's info
391
+ // 2- if Operations info need to be logged when process ends using
392
+ // LogOptions::OPERATION_INFO.
393
+
394
+ // the pointer key for this map is either "MPSGraph*" or
395
+ // "id<MTLComputePipelineState>" for Metal Kernels this list is retained and
396
+ // could be logged along with aggregate profiling numbers when the process
397
+ // ends.
398
+ std::unordered_map<uintptr_t, std::unique_ptr<OperationInfo>>
399
+ m_op_info_list{};
400
+ // the string key for this map is the op name that we fall back to execute on
401
+ // CPU this list is retained and could be logged along with aggregate
402
+ // profiling numbers when the process ends.
403
+ std::unordered_map<std::string, std::unique_ptr<CpuFbInfo>>
404
+ m_cpu_fb_info_list{};
405
+ // this list contains the info for copies, and its key is the unique profileId
406
+ // which is generated from m_copy_counter
407
+ // The copyInfo list is not retained.
408
+ std::unordered_map<uint64_t, std::unique_ptr<CopyInfo>> m_copy_info_list{};
409
+ // a short list that contains copy stats
410
+ std::unordered_map<CopyInfo::Kind, std::unique_ptr<CopyStat>>
411
+ m_copy_stat_list{};
412
+
413
+ mutable MTLCaptureManager* captureManager = nil;
414
+ unsigned captureCount = 0;
415
+
416
+ void initialize();
417
+ void beginProfileExecution(BaseInfo& info, bool cpuExecution = false);
418
+ void endProfileExecution(
419
+ BaseInfo& info,
420
+ os_signpost_id_t event_signpost_id,
421
+ os_signpost_id_t interval_signpost_id,
422
+ double gpuTime,
423
+ double schedulingTime);
424
+ void addProfilerScheduledHandler(BaseInfo& info);
425
+ void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType);
426
+ void emitSignpostEvent(
427
+ SignpostTypes signpost_type,
428
+ os_signpost_id_t signpost_id,
429
+ const std::string& msg) const;
430
+ void beginSignpostInterval(
431
+ SignpostTypes signpost_type,
432
+ os_signpost_id_t signpost_id,
433
+ const std::string& msg) const;
434
+ void endSignpostInterval(
435
+ SignpostTypes signpost_type,
436
+ os_signpost_id_t signpost_id) const;
437
+
438
+ void updateCopyStats(
439
+ const CopyInfo& copyInfo,
440
+ double gpuTime,
441
+ double schedulingTime);
442
+ // returns true if logging the profiling info "during the execution" is
443
+ // enabled
444
+ bool isProfileInfoLoggingEnabled(
445
+ BaseInfo::Type infoType,
446
+ bool isExecutionEnded);
447
+ // logs all the profiling stats that are enabled
448
+ void logProfilingStats();
449
+ // logs kernel profiling stats when the process ends.
450
+ void logOperationsProfilingStats(std::FILE* f) const;
451
+ // logs CPU Fallback profiling stats when the process ends.
452
+ void logCPUFallbackProfilingStats(std::FILE* f) const;
453
+ // logs copy profiling stats when the process ends.
454
+ void logCopyProfilingStats(std::FILE* f) const;
455
+
456
+ os_signpost_id_t generateSignpostId(
457
+ os_signpost_type_t signpostType,
458
+ const void* ptr = nullptr);
459
+ static SignpostTypes getSignpostType(BaseInfo::Type infoType);
460
+ static void handleIntSignal(int signal);
461
+ };
462
+
463
+ } // namespace Profiler
464
+
465
+ Profiler::MPSProfiler& getMPSProfiler();
466
+
467
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/mps/MPSStream.h ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright © 2022 Apple Inc.
2
+
3
+ #pragma once
4
+
5
+ #include <cstdint>
6
+ #include <utility>
7
+
8
+ #include <ATen/mps/MPSDevice.h>
9
+ #include <c10/core/DeviceGuard.h>
10
+ #include <c10/core/Stream.h>
11
+ #include <c10/util/Exception.h>
12
+
13
+ #ifdef __OBJC__
14
+ #include <Foundation/Foundation.h>
15
+ #include <Metal/Metal.h>
16
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
17
+ #include <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
18
+ typedef MPSCommandBuffer* MPSCommandBuffer_t;
19
+ typedef id<MTLCommandQueue> MTLCommandQueue_t;
20
+ typedef id<MTLComputeCommandEncoder> MTLComputeCommandEncoder_t;
21
+ typedef id<MTLSharedEvent> MTLSharedEvent_t;
22
+ typedef id<MTLDevice> MTLDevice_t;
23
+ typedef id<MTLBuffer> MTLBuffer_t;
24
+ #else
25
+ #include <dispatch/dispatch.h>
26
+ typedef void* MPSCommandBuffer_t;
27
+ typedef void* MPSGraph;
28
+ typedef void* MPSGraphExecutionDescriptor;
29
+ typedef void* MPSGraphCompilationDescriptor;
30
+ typedef void* MTLCommandQueue_t;
31
+ typedef void* MTLComputeCommandEncoder_t;
32
+ typedef void* MTLSharedEvent_t;
33
+ typedef void* MTLDevice_t;
34
+ typedef void* MTLBuffer_t;
35
+ typedef void* MTLCommandBufferHandler;
36
+ typedef void* NSDictionary;
37
+ #define nil NULL
38
+ #endif
39
+
40
+ namespace at::mps {
41
+
42
+ //-----------------------------------------------------------------
43
+ // MPSStream
44
+ //-----------------------------------------------------------------
45
+
46
+ enum class SyncType {
47
+ NONE, // no commit to command buffer
48
+ COMMIT, // commit and flush the command buffer
49
+ COMMIT_AND_WAIT, // flush and wait for command buffer execution to finish
50
+ COMMIT_AND_CONTINUE, // commit and continue with a new underlying command buffer
51
+ COMMIT_ADAPTIVE, // commit adaptively based on available memory
52
+ };
53
+
54
+ class TORCH_API MPSStream {
55
+ public:
56
+ enum Unchecked { UNCHECKED };
57
+
58
+ /// Construct a MPSStream from a Stream. This construction is checked,
59
+ /// and will raise an error if the Stream is not, in fact, a MPS stream.
60
+ explicit MPSStream(Stream stream);
61
+
62
+ ~MPSStream();
63
+
64
+ MTLCommandQueue_t commandQueue() const {
65
+ return _commandQueue;
66
+ }
67
+
68
+ dispatch_queue_t queue() const {
69
+ return _serialQueue;
70
+ }
71
+
72
+ MPSCommandBuffer_t commandBuffer();
73
+ MTLComputeCommandEncoder_t commandEncoder();
74
+ void endKernelCoalescing();
75
+ void synchronize(SyncType syncType);
76
+ void fill(MTLBuffer_t buffer, uint8_t value, size_t length, size_t offset, SyncType syncType = SyncType::NONE);
77
+ void copy(MTLBuffer_t srcBuffer,
78
+ MTLBuffer_t dstBuffer,
79
+ size_t length,
80
+ size_t srcOffset,
81
+ size_t dstOffset,
82
+ uint64_t profileId,
83
+ SyncType syncType = SyncType::NONE);
84
+ void copy_and_sync(MTLBuffer_t srcBuffer,
85
+ MTLBuffer_t dstBuffer,
86
+ size_t length,
87
+ size_t srcOffset,
88
+ size_t dstOffset,
89
+ bool non_blocking,
90
+ uint64_t profileId);
91
+ void executeMPSGraph(MPSGraph* mpsGraph,
92
+ NSDictionary* feeds,
93
+ NSDictionary* results,
94
+ SyncType syncType = SyncType::NONE);
95
+ void addCompletedHandler(MTLCommandBufferHandler block);
96
+
97
+ /// Get the MPS device index that this stream is associated with.
98
+ c10::DeviceIndex device_index() const {
99
+ return _stream.device_index();
100
+ }
101
+
102
+ MTLCommandQueue_t stream() const {
103
+ return _commandQueue;
104
+ }
105
+
106
+ MTLDevice_t device() const;
107
+
108
+ /// Explicit conversion to Stream.
109
+ Stream unwrap() const {
110
+ return _stream;
111
+ }
112
+
113
+ private:
114
+ Stream _stream;
115
+ MTLCommandQueue_t _commandQueue = nil;
116
+ MPSCommandBuffer_t _commandBuffer = nil;
117
+ MPSCommandBuffer_t _prevCommandBuffer = nil;
118
+ MTLComputeCommandEncoder_t _commandEncoder = nil;
119
+ MPSGraphExecutionDescriptor* _executionDescriptor = nil;
120
+ MPSGraphCompilationDescriptor* _compilationDescriptor = nil;
121
+ dispatch_queue_t _serialQueue = nullptr;
122
+ // CommitAndContinue is enabled by default
123
+ bool _enableCommitAndContinue = true;
124
+
125
+ // use synchronize() to access any of these commit functions outside MPSStream
126
+ void commit();
127
+ void commitAndWait();
128
+ void commitAndContinue();
129
+ void flush();
130
+ };
131
+
132
+ /**
133
+ * Get the current MPS stream
134
+ */
135
+ TORCH_API MPSStream* getCurrentMPSStream();
136
+
137
+ /**
138
+ * Get the default MPS stream
139
+ */
140
+ TORCH_API MPSStream* getDefaultMPSStream();
141
+
142
+ //-----------------------------------------------------------------
143
+ // MPSStreamImpl
144
+ //-----------------------------------------------------------------
145
+
146
+ class TORCH_API MPSStreamImpl {
147
+ public:
148
+ /**
149
+ * Gets single instance of the MPSStream.
150
+ */
151
+ static MPSStream* getInstance();
152
+
153
+ private:
154
+ static MPSStream* _stream;
155
+ MPSStreamImpl();
156
+ };
157
+
158
+ } // namespace at::mps
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Activation.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/native/Gelu.h>
5
+ #include <c10/util/Exception.h>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ struct TensorIterator;
13
+ struct TensorIteratorBase;
14
+ class TensorBase;
15
+ }
16
+
17
+ namespace at::native {
18
+
19
+ using structured_activation_fn = void (*)(TensorIteratorBase&);
20
+ using structured_activation_backward_fn = void (*)(TensorIteratorBase&);
21
+
22
+ using activation_fn = void (*)(TensorIterator&);
23
+ using activation_backward_fn = void (*)(TensorIterator&);
24
+ using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
25
+ using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
26
+ using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
27
+ using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&);
28
+ using hardsigmoid_fn = void(*)(TensorIteratorBase&);
29
+ using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&);
30
+ using hardswish_fn = void(*)(TensorIterator&);
31
+ using hardswish_backward_fn = void(*)(TensorIterator&);
32
+ using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
33
+ using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
34
+ using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
35
+ using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&);
36
+ using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool);
37
+ using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
38
+ using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
39
+ using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&);
40
+ using gelu_fn = void (*)(TensorIteratorBase&, GeluType);
41
+ using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType);
42
+ using glu_jvp_fn = void (*)(TensorIteratorBase&);
43
+
44
+ DECLARE_DISPATCH(elu_fn, elu_stub)
45
+ DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub)
46
+ DECLARE_DISPATCH(softplus_fn, softplus_stub)
47
+ DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub)
48
+ DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub)
49
+ DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub)
50
+ DECLARE_DISPATCH(threshold_fn, threshold_stub)
51
+ DECLARE_DISPATCH(gelu_fn, GeluKernel)
52
+ DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel)
53
+ DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub)
54
+ DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub)
55
+ DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub)
56
+ DECLARE_DISPATCH(hardswish_fn, hardswish_stub)
57
+ DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub)
58
+ DECLARE_DISPATCH(shrink_fn, hardshrink_stub)
59
+ DECLARE_DISPATCH(softshrink_fn, softshrink_stub)
60
+ DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub)
61
+ DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub)
62
+ DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub)
63
+ DECLARE_DISPATCH(structured_activation_fn, glu_stub)
64
+ DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub)
65
+ DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub)
66
+ DECLARE_DISPATCH(structured_activation_fn, silu_stub)
67
+ DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub)
68
+ DECLARE_DISPATCH(structured_activation_fn, mish_stub)
69
+ DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub)
70
+ DECLARE_DISPATCH(activation_fn, prelu_stub)
71
+ DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub)
72
+
73
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/AdaptivePooling.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/util/ArrayRef.h>
6
+ #include <c10/util/irange.h>
7
+ #include <cmath>
8
+
9
+ namespace at::native {
10
+
11
+ using adaptive_avg_pooling2d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
12
+ using adaptive_avg_pooling2d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
13
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_fn, adaptive_avg_pool2d_kernel)
14
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_backward_fn, adaptive_avg_pool2d_backward_kernel)
15
+
16
+ using adaptive_max_pooling2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
17
+ using adaptive_max_pooling2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
18
+ DECLARE_DISPATCH(adaptive_max_pooling2d_fn, adaptive_max_pool2d_kernel)
19
+ DECLARE_DISPATCH(adaptive_max_pooling2d_backward_fn, adaptive_max_pool2d_backward_kernel)
20
+
21
+ using adaptive_avg_pooling3d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
22
+ using adaptive_avg_pooling3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
23
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_fn, adaptive_avg_pool3d_kernel)
24
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_backward_fn, adaptive_avg_pool3d_backward_kernel)
25
+
26
+ using adaptive_max_pooling3d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
27
+ using adaptive_max_pooling3d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
28
+ DECLARE_DISPATCH(adaptive_max_pooling3d_fn, adaptive_max_pool3d_kernel)
29
+ DECLARE_DISPATCH(adaptive_max_pooling3d_backward_fn, adaptive_max_pool3d_backward_kernel)
30
+
31
+ inline int64_t start_index(int64_t a, int64_t b, int64_t c) {
32
+ return (a / b) * c + ((a % b) * c) / b;
33
+ }
34
+
35
+ inline int64_t end_index(int64_t a, int64_t b, int64_t c) {
36
+ return 1 + ((a + 1) * c - 1) / b;
37
+ }
38
+
39
+ inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) {
40
+ int64_t ndim = gradOutput_.ndimension();
41
+ for (const auto i : c10::irange(1, ndim)) {
42
+ TORCH_CHECK(gradOutput_.size(i) > 0,
43
+ arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, "
44
+ "but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i,
45
+ " being empty");
46
+ }
47
+ }
48
+
49
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/AmpKernels.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <ATen/core/ATen_fwd.h>
5
+
6
+ namespace at {
7
+ class Tensor;
8
+
9
+ namespace native {
10
+
11
+ using _amp_foreach_non_finite_check_and_unscale_cpu__fn = void (*)(
12
+ TensorList,
13
+ Tensor&,
14
+ const Tensor&);
15
+
16
+ using _amp_update_scale_cpu__fn = Tensor& (*)(
17
+ Tensor&,
18
+ Tensor&,
19
+ const Tensor&,
20
+ double,
21
+ double,
22
+ int64_t);
23
+
24
+ DECLARE_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu__fn, _amp_foreach_non_finite_check_and_unscale_cpu_stub)
25
+ DECLARE_DISPATCH(_amp_update_scale_cpu__fn, _amp_update_scale_cpu_stub)
26
+
27
+ } // namespace native
28
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <optional>
4
+ #include <string_view>
5
+ #include <ATen/Config.h>
6
+ #include <ATen/native/DispatchStub.h>
7
+
8
+ // Forward declare TI
9
+ namespace at {
10
+ class Tensor;
11
+ struct TensorIterator;
12
+
13
+ namespace native {
14
+ enum class TransposeType;
15
+ }
16
+
17
+ }
18
+
19
+ namespace at::native {
20
+
21
+ enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
22
+
23
+ #if AT_BUILD_WITH_LAPACK()
24
+ // Define per-batch functions to be used in the implementation of batched
25
+ // linear algebra operations
26
+
27
+ template <class scalar_t>
28
+ void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
29
+
30
+ template <class scalar_t>
31
+ void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
32
+
33
+ template <class scalar_t, class value_t=scalar_t>
34
+ void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
35
+
36
+ template <class scalar_t>
37
+ void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
38
+
39
+ template <class scalar_t>
40
+ void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
41
+
42
+ template <class scalar_t>
43
+ void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
44
+
45
+ template <class scalar_t, class value_t = scalar_t>
46
+ void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
47
+
48
+ template <class scalar_t>
49
+ void lapackGels(char trans, int m, int n, int nrhs,
50
+ scalar_t *a, int lda, scalar_t *b, int ldb,
51
+ scalar_t *work, int lwork, int *info);
52
+
53
+ template <class scalar_t, class value_t = scalar_t>
54
+ void lapackGelsd(int m, int n, int nrhs,
55
+ scalar_t *a, int lda, scalar_t *b, int ldb,
56
+ value_t *s, value_t rcond, int *rank,
57
+ scalar_t* work, int lwork,
58
+ value_t *rwork, int* iwork, int *info);
59
+
60
+ template <class scalar_t, class value_t = scalar_t>
61
+ void lapackGelsy(int m, int n, int nrhs,
62
+ scalar_t *a, int lda, scalar_t *b, int ldb,
63
+ int *jpvt, value_t rcond, int *rank,
64
+ scalar_t *work, int lwork, value_t* rwork, int *info);
65
+
66
+ template <class scalar_t, class value_t = scalar_t>
67
+ void lapackGelss(int m, int n, int nrhs,
68
+ scalar_t *a, int lda, scalar_t *b, int ldb,
69
+ value_t *s, value_t rcond, int *rank,
70
+ scalar_t *work, int lwork,
71
+ value_t *rwork, int *info);
72
+
73
+ template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
74
+ struct lapackLstsq_impl;
75
+
76
+ template <class scalar_t, class value_t>
77
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
78
+ static void call(
79
+ char trans, int m, int n, int nrhs,
80
+ scalar_t *a, int lda, scalar_t *b, int ldb,
81
+ scalar_t *work, int lwork, int *info, // Gels flavor
82
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
83
+ value_t *s, // Gelss flavor
84
+ int *iwork // Gelsd flavor
85
+ ) {
86
+ lapackGels<scalar_t>(
87
+ trans, m, n, nrhs,
88
+ a, lda, b, ldb,
89
+ work, lwork, info);
90
+ }
91
+ };
92
+
93
+ template <class scalar_t, class value_t>
94
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
95
+ static void call(
96
+ char trans, int m, int n, int nrhs,
97
+ scalar_t *a, int lda, scalar_t *b, int ldb,
98
+ scalar_t *work, int lwork, int *info, // Gels flavor
99
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
100
+ value_t *s, // Gelss flavor
101
+ int *iwork // Gelsd flavor
102
+ ) {
103
+ lapackGelsy<scalar_t, value_t>(
104
+ m, n, nrhs,
105
+ a, lda, b, ldb,
106
+ jpvt, rcond, rank,
107
+ work, lwork, rwork, info);
108
+ }
109
+ };
110
+
111
+ template <class scalar_t, class value_t>
112
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
113
+ static void call(
114
+ char trans, int m, int n, int nrhs,
115
+ scalar_t *a, int lda, scalar_t *b, int ldb,
116
+ scalar_t *work, int lwork, int *info, // Gels flavor
117
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
118
+ value_t *s, // Gelss flavor
119
+ int *iwork // Gelsd flavor
120
+ ) {
121
+ lapackGelsd<scalar_t, value_t>(
122
+ m, n, nrhs,
123
+ a, lda, b, ldb,
124
+ s, rcond, rank,
125
+ work, lwork,
126
+ rwork, iwork, info);
127
+ }
128
+ };
129
+
130
+ template <class scalar_t, class value_t>
131
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
132
+ static void call(
133
+ char trans, int m, int n, int nrhs,
134
+ scalar_t *a, int lda, scalar_t *b, int ldb,
135
+ scalar_t *work, int lwork, int *info, // Gels flavor
136
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
137
+ value_t *s, // Gelss flavor
138
+ int *iwork // Gelsd flavor
139
+ ) {
140
+ lapackGelss<scalar_t, value_t>(
141
+ m, n, nrhs,
142
+ a, lda, b, ldb,
143
+ s, rcond, rank,
144
+ work, lwork,
145
+ rwork, info);
146
+ }
147
+ };
148
+
149
+ template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
150
+ void lapackLstsq(
151
+ char trans, int m, int n, int nrhs,
152
+ scalar_t *a, int lda, scalar_t *b, int ldb,
153
+ scalar_t *work, int lwork, int *info, // Gels flavor
154
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
155
+ value_t *s, // Gelss flavor
156
+ int *iwork // Gelsd flavor
157
+ ) {
158
+ lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
159
+ trans, m, n, nrhs,
160
+ a, lda, b, ldb,
161
+ work, lwork, info,
162
+ jpvt, rcond, rank, rwork,
163
+ s,
164
+ iwork);
165
+ }
166
+
167
+ template <class scalar_t>
168
+ void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
169
+
170
+ template <class scalar_t>
171
+ void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
172
+
173
+ template <class scalar_t>
174
+ void lapackLdlHermitian(
175
+ char uplo,
176
+ int n,
177
+ scalar_t* a,
178
+ int lda,
179
+ int* ipiv,
180
+ scalar_t* work,
181
+ int lwork,
182
+ int* info);
183
+
184
+ template <class scalar_t>
185
+ void lapackLdlSymmetric(
186
+ char uplo,
187
+ int n,
188
+ scalar_t* a,
189
+ int lda,
190
+ int* ipiv,
191
+ scalar_t* work,
192
+ int lwork,
193
+ int* info);
194
+
195
+ template <class scalar_t>
196
+ void lapackLdlSolveHermitian(
197
+ char uplo,
198
+ int n,
199
+ int nrhs,
200
+ scalar_t* a,
201
+ int lda,
202
+ int* ipiv,
203
+ scalar_t* b,
204
+ int ldb,
205
+ int* info);
206
+
207
+ template <class scalar_t>
208
+ void lapackLdlSolveSymmetric(
209
+ char uplo,
210
+ int n,
211
+ int nrhs,
212
+ scalar_t* a,
213
+ int lda,
214
+ int* ipiv,
215
+ scalar_t* b,
216
+ int ldb,
217
+ int* info);
218
+
219
+ template<class scalar_t, class value_t=scalar_t>
220
+ void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
221
+ #endif
222
+
223
+ #if AT_BUILD_WITH_BLAS()
224
+ template <class scalar_t>
225
+ void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
226
+ #endif
227
+
228
+ using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
229
+ DECLARE_DISPATCH(cholesky_fn, cholesky_stub)
230
+
231
+ using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
232
+
233
+ DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub)
234
+
235
+ using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
236
+
237
+ DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub)
238
+
239
+ using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
240
+ DECLARE_DISPATCH(geqrf_fn, geqrf_stub)
241
+
242
+ using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
243
+ DECLARE_DISPATCH(orgqr_fn, orgqr_stub)
244
+
245
+ using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
246
+ DECLARE_DISPATCH(ormqr_fn, ormqr_stub)
247
+
248
+ using linalg_eigh_fn = void (*)(
249
+ const Tensor& /*eigenvalues*/,
250
+ const Tensor& /*eigenvectors*/,
251
+ const Tensor& /*infos*/,
252
+ bool /*upper*/,
253
+ bool /*compute_eigenvectors*/);
254
+ DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub)
255
+
256
+ using lstsq_fn = void (*)(
257
+ const Tensor& /*a*/,
258
+ Tensor& /*b*/,
259
+ Tensor& /*rank*/,
260
+ Tensor& /*singular_values*/,
261
+ Tensor& /*infos*/,
262
+ double /*rcond*/,
263
+ std::string /*driver_name*/);
264
+ DECLARE_DISPATCH(lstsq_fn, lstsq_stub)
265
+
266
+ using triangular_solve_fn = void (*)(
267
+ const Tensor& /*A*/,
268
+ const Tensor& /*B*/,
269
+ bool /*left*/,
270
+ bool /*upper*/,
271
+ TransposeType /*transpose*/,
272
+ bool /*unitriangular*/);
273
+ DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub)
274
+
275
+ using lu_factor_fn = void (*)(
276
+ const Tensor& /*input*/,
277
+ const Tensor& /*pivots*/,
278
+ const Tensor& /*infos*/,
279
+ bool /*compute_pivots*/);
280
+ DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub)
281
+
282
+ using unpack_pivots_fn = void(*)(
283
+ TensorIterator& iter,
284
+ const int64_t dim_size,
285
+ const int64_t max_pivot);
286
+ DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub)
287
+
288
+ using lu_solve_fn = void (*)(
289
+ const Tensor& /*LU*/,
290
+ const Tensor& /*pivots*/,
291
+ const Tensor& /*B*/,
292
+ TransposeType /*trans*/);
293
+ DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub)
294
+
295
+ using ldl_factor_fn = void (*)(
296
+ const Tensor& /*LD*/,
297
+ const Tensor& /*pivots*/,
298
+ const Tensor& /*info*/,
299
+ bool /*upper*/,
300
+ bool /*hermitian*/);
301
+ DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub)
302
+
303
+ using svd_fn = void (*)(
304
+ const Tensor& /*A*/,
305
+ const bool /*full_matrices*/,
306
+ const bool /*compute_uv*/,
307
+ const std::optional<std::string_view>& /*driver*/,
308
+ const Tensor& /*U*/,
309
+ const Tensor& /*S*/,
310
+ const Tensor& /*Vh*/,
311
+ const Tensor& /*info*/);
312
+ DECLARE_DISPATCH(svd_fn, svd_stub)
313
+
314
+ using ldl_solve_fn = void (*)(
315
+ const Tensor& /*LD*/,
316
+ const Tensor& /*pivots*/,
317
+ const Tensor& /*result*/,
318
+ bool /*upper*/,
319
+ bool /*hermitian*/);
320
+ DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub)
321
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BinaryOps.h ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/util/TypeSafeSignMath.h>
7
+
8
+
9
+ namespace at {
10
+ struct TensorIterator;
11
+ struct TensorIteratorBase;
12
+ }
13
+
14
+ namespace at::native {
15
+
16
+ inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
17
+ TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
18
+ "Boolean alpha only supported for Boolean results.");
19
+ TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
20
+ || alpha.isIntegral(true),
21
+ "For integral input tensors, argument alpha must not be a floating point number.");
22
+ TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
23
+ "For non-complex input tensors, argument alpha must not be a complex number.")
24
+ }
25
+
26
+ // Basic checking for all sub functions.
27
+ inline void sub_check(const TensorBase& self, const TensorBase& other) {
28
+ TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
29
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
30
+ "Use the `^` or `logical_xor()` operator instead.")
31
+ TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
32
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
33
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
34
+ }
35
+
36
+ inline void sub_check(const TensorBase& self, const Scalar& scalar) {
37
+ TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
38
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
39
+ "Use the `^` or `logical_xor()` operator instead.")
40
+ TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
41
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
42
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
43
+ }
44
+
45
+ using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
46
+ using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
47
+ using structured_binary_fn = void(*)(TensorIteratorBase&);
48
+
49
+ using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
50
+ using binary_fn_double = void(*)(TensorIterator&, double);
51
+ using binary_fn = void(*)(TensorIterator&);
52
+ using binary_clamp_fn_alpha =
53
+ void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
54
+
55
+ // NB: codegenned
56
+ DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub)
57
+
58
+ DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub)
59
+ DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub)
60
+ DECLARE_DISPATCH(structured_binary_fn, mul_stub)
61
+ DECLARE_DISPATCH(structured_binary_fn, div_true_stub)
62
+ DECLARE_DISPATCH(structured_binary_fn, div_floor_stub)
63
+ DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub)
64
+ DECLARE_DISPATCH(structured_binary_fn, atan2_stub)
65
+ DECLARE_DISPATCH(structured_binary_fn, remainder_stub)
66
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub)
67
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub)
68
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub)
69
+ DECLARE_DISPATCH(structured_binary_fn, lshift_stub)
70
+ DECLARE_DISPATCH(structured_binary_fn, rshift_stub)
71
+ DECLARE_DISPATCH(binary_fn, logical_xor_stub)
72
+ DECLARE_DISPATCH(binary_fn, logical_and_stub)
73
+ DECLARE_DISPATCH(binary_fn, logical_or_stub)
74
+ DECLARE_DISPATCH(structured_binary_fn, lt_stub)
75
+ DECLARE_DISPATCH(structured_binary_fn, le_stub)
76
+ DECLARE_DISPATCH(structured_binary_fn, gt_stub)
77
+ DECLARE_DISPATCH(structured_binary_fn, ge_stub)
78
+ DECLARE_DISPATCH(structured_binary_fn, eq_stub)
79
+ DECLARE_DISPATCH(structured_binary_fn, ne_stub)
80
+ DECLARE_DISPATCH(binary_fn, max_elementwise_stub)
81
+ DECLARE_DISPATCH(binary_fn, min_elementwise_stub)
82
+ DECLARE_DISPATCH(structured_binary_fn, maximum_stub)
83
+ DECLARE_DISPATCH(structured_binary_fn, minimum_stub)
84
+ DECLARE_DISPATCH(structured_binary_fn, fmax_stub)
85
+ DECLARE_DISPATCH(structured_binary_fn, fmin_stub)
86
+ DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub)
87
+ DECLARE_DISPATCH(binary_fn_double, huber_stub)
88
+ DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub)
89
+ DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub)
90
+ DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub)
91
+ DECLARE_DISPATCH(structured_binary_fn, mse_stub)
92
+ DECLARE_DISPATCH(structured_binary_fn, fmod_stub)
93
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub)
94
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub)
95
+ DECLARE_DISPATCH(structured_binary_fn, gcd_stub)
96
+ DECLARE_DISPATCH(structured_binary_fn, lcm_stub)
97
+ DECLARE_DISPATCH(structured_binary_fn, hypot_stub)
98
+ DECLARE_DISPATCH(structured_binary_fn, igamma_stub)
99
+ DECLARE_DISPATCH(structured_binary_fn, igammac_stub)
100
+ DECLARE_DISPATCH(structured_binary_fn, nextafter_stub)
101
+ DECLARE_DISPATCH(structured_binary_fn, heaviside_stub)
102
+ DECLARE_DISPATCH(structured_binary_fn, copysign_stub)
103
+ DECLARE_DISPATCH(structured_binary_fn, xlogy_stub)
104
+ DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub)
105
+ DECLARE_DISPATCH(structured_binary_fn, zeta_stub)
106
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub)
107
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub)
108
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub)
109
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub)
110
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub)
111
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub)
112
+ DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub)
113
+ DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub)
114
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub)
115
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub)
116
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub)
117
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub)
118
+
119
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/BucketizationUtils.h ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/TypeProperties.h>
5
+ #include <ATen/ScalarOps.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/NativeFunctions.h>
9
+ #else
10
+ #include <ATen/ops/result_type.h>
11
+ #endif
12
+
13
+ namespace at::native {
14
+
15
+ // original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to
16
+ // the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not
17
+ // match, will change them to be a common super type so comparisons are done between the same types.
18
+ // For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the
19
+ // corresponding raw_* version should be used since it was already contiguous of the right type.
20
+ inline void searchsorted_maybe_trim_input_tensors(
21
+ Tensor& trimmed_input,
22
+ Tensor& trimmed_boundaries,
23
+ Tensor& trimmed_sorter,
24
+ const Tensor& raw_input,
25
+ const Tensor& raw_boundaries,
26
+ const Tensor& raw_sorter) {
27
+ bool in_is_contiguous = raw_input.is_contiguous();
28
+ bool bd_is_contiguous = raw_boundaries.is_contiguous();
29
+ bool sort_is_contiguous = raw_sorter.is_contiguous();
30
+
31
+ if (!in_is_contiguous) {
32
+ TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due "
33
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value "
34
+ "tensor if possible. This message will only appear once per program.");
35
+ trimmed_input = raw_input.contiguous();
36
+ }
37
+ if (!bd_is_contiguous) {
38
+ TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due "
39
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary "
40
+ "tensor if possible. This message will only appear once per program.");
41
+ trimmed_boundaries = raw_boundaries.contiguous();
42
+ }
43
+ if (!sort_is_contiguous) {
44
+ TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due "
45
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter "
46
+ "tensor if possible. This message will only appear once per program.");
47
+ trimmed_sorter = raw_sorter.contiguous();
48
+ }
49
+ if (raw_input.dtype() != raw_boundaries.dtype()) {
50
+ at::native::ResultTypeState state = {};
51
+ state = at::native::update_result_type_state(raw_boundaries, state);
52
+ state = at::native::update_result_type_state(raw_input, state);
53
+ ScalarType common_stype = at::native::result_type(state);
54
+
55
+ TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined);
56
+ if (common_stype != raw_input.scalar_type()) {
57
+ trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype);
58
+ }
59
+ if (common_stype != raw_boundaries.scalar_type()) {
60
+ trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype);
61
+ }
62
+ }
63
+ }
64
+
65
+ /* unused but needed for internal jagged tensor class */
66
+ inline void searchsorted_maybe_trim_input_tensors(
67
+ Tensor& trimmed_input,
68
+ Tensor& trimmed_boundaries,
69
+ const Tensor& raw_input,
70
+ const Tensor& raw_boundaries) {
71
+ Tensor trimmed_sorter;
72
+ Tensor raw_sorter;
73
+ return searchsorted_maybe_trim_input_tensors(
74
+ trimmed_input,
75
+ trimmed_boundaries,
76
+ trimmed_sorter,
77
+ raw_input,
78
+ raw_boundaries,
79
+ raw_sorter);
80
+ }
81
+
82
+ inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) {
83
+ if (boundaries.dim() != input.dim()) {
84
+ return false;
85
+ }
86
+ const auto& dims_bd = boundaries.sizes();
87
+ const auto& dims_in = input.sizes();
88
+ for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) {
89
+ if (dims_bd[dim] != dims_in[dim]) {
90
+ return false;
91
+ }
92
+ }
93
+ return true;
94
+ }
95
+
96
+ inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) {
97
+ auto tensor = c10::scalar_to_tensor(scalar, device);
98
+ // This is to adopt the scalar promotion rules defined in native/TypeProperties.h
99
+ // So we have the same type promotion rules as binary operations.
100
+ tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
101
+ return tensor;
102
+ }
103
+
104
+ inline void searchsorted_pre_check(
105
+ const Tensor& boundaries,
106
+ const Tensor& input,
107
+ const Tensor& output,
108
+ const bool out_int32,
109
+ const bool right,
110
+ const std::optional<std::string_view> side_opt,
111
+ const Tensor& sorter) {
112
+ if (side_opt) {
113
+ const std::string_view side = *side_opt;
114
+ TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ",
115
+ "got ", side);
116
+
117
+ // assume the user has not explicitly set (right=False, side="right")
118
+ TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side "
119
+ "of ", side, " while right was True");
120
+ }
121
+
122
+ TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ",
123
+ "should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ",
124
+ "tensor device type ", input.device());
125
+
126
+ if (sorter.defined()) {
127
+ TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ",
128
+ "have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ",
129
+ "device type ", boundaries.device());
130
+
131
+ TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same "
132
+ "size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes());
133
+
134
+ TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ",
135
+ "dtype but got dtype ", sorter.scalar_type());
136
+
137
+ if (sorter.numel() > 0) {
138
+ auto minmax = sorter.aminmax();
139
+ int64_t vmin = std::get<0>(minmax).item().toLong();
140
+ int64_t vmax = std::get<1>(minmax).item().toLong();
141
+ TORCH_CHECK(vmin >= 0 && vmax < sorter.sizes().back(), "torch.searchsorted(): sorter index out of range");
142
+ }
143
+ }
144
+
145
+ TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1),
146
+ "torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ",
147
+ "boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(",
148
+ input.numel(), ")");
149
+
150
+ TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ",
151
+ "got 0 dimension");
152
+
153
+ TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input),
154
+ "torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ",
155
+ "and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ",
156
+ input.sizes());
157
+
158
+ ScalarType output_dtype = output.scalar_type();
159
+ TORCH_CHECK(
160
+ (output_dtype == ScalarType::Long && !out_int32) ||
161
+ (output_dtype == ScalarType::Int && out_int32),
162
+ "torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ",
163
+ "whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype,
164
+ " and out_int32 flag is ", (out_int32 ? "True" : "False"));
165
+
166
+ if (out_int32) {
167
+ TORCH_CHECK(boundaries.sizes().back() < INT_MAX,
168
+ "torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ",
169
+ boundaries.sizes().back());
170
+ }
171
+ }
172
+
173
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CPUBlas.h ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/OpMathType.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/native/TransposeType.h>
6
+ #include <c10/util/complex.h>
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/core/Scalar.h>
9
+
10
+
11
+ namespace at::native::cpublas {
12
+
13
+ namespace internal {
14
+ void normalize_last_dims(
15
+ TransposeType transa, TransposeType transb,
16
+ int64_t m, int64_t n, int64_t k,
17
+ int64_t *lda, int64_t *ldb, int64_t *ldc);
18
+ } // namespace internal
19
+
20
+ using gemm_fn = void(*)(
21
+ at::ScalarType type,
22
+ TransposeType transa, TransposeType transb,
23
+ int64_t m, int64_t n, int64_t k,
24
+ const Scalar& alpha,
25
+ const void *a, int64_t lda,
26
+ const void *b, int64_t ldb,
27
+ const Scalar& beta,
28
+ void *c, int64_t ldc);
29
+
30
+ DECLARE_DISPATCH(gemm_fn, gemm_stub)
31
+
32
+ template <typename scalar_t>
33
+ void gemm(
34
+ TransposeType transa, TransposeType transb,
35
+ int64_t m, int64_t n, int64_t k,
36
+ at::opmath_type<scalar_t> alpha,
37
+ const scalar_t *a, int64_t lda,
38
+ const scalar_t *b, int64_t ldb,
39
+ at::opmath_type<scalar_t> beta,
40
+ scalar_t *c, int64_t ldc) {
41
+ internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc);
42
+ gemm_stub(
43
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
44
+ transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
45
+ }
46
+
47
+ void gemm(
48
+ TransposeType transa, TransposeType transb,
49
+ int64_t m, int64_t n, int64_t k,
50
+ double alpha,
51
+ const double *a, int64_t lda,
52
+ const double *b, int64_t ldb,
53
+ double beta,
54
+ double *c, int64_t ldc);
55
+
56
+ void gemm(
57
+ TransposeType transa, TransposeType transb,
58
+ int64_t m, int64_t n, int64_t k,
59
+ float alpha,
60
+ const float *a, int64_t lda,
61
+ const float *b, int64_t ldb,
62
+ float beta,
63
+ float *c, int64_t ldc);
64
+
65
+ void gemm(
66
+ TransposeType transa, TransposeType transb,
67
+ int64_t m, int64_t n, int64_t k,
68
+ float alpha,
69
+ const at::BFloat16 *a, int64_t lda,
70
+ const at::BFloat16 *b, int64_t ldb,
71
+ float beta,
72
+ at::BFloat16 *c, int64_t ldc);
73
+
74
+ void gemm(
75
+ TransposeType transa, TransposeType transb,
76
+ int64_t m, int64_t n, int64_t k,
77
+ const float alpha,
78
+ const at::BFloat16 *a, int64_t lda,
79
+ const at::BFloat16 *b, int64_t ldb,
80
+ const float beta,
81
+ float *c, int64_t ldc);
82
+
83
+ void gemm(
84
+ TransposeType transa, TransposeType transb,
85
+ int64_t m, int64_t n, int64_t k,
86
+ float alpha,
87
+ const at::Half *a, int64_t lda,
88
+ const at::Half *b, int64_t ldb,
89
+ float beta,
90
+ at::Half *c, int64_t ldc);
91
+
92
+ void gemm(
93
+ TransposeType transa, TransposeType transb,
94
+ int64_t m, int64_t n, int64_t k,
95
+ const float alpha,
96
+ const at::Half *a, int64_t lda,
97
+ const at::Half *b, int64_t ldb,
98
+ const float beta,
99
+ float *c, int64_t ldc);
100
+
101
+ void gemm(
102
+ TransposeType transa, TransposeType transb,
103
+ int64_t m, int64_t n, int64_t k,
104
+ c10::complex<double> alpha,
105
+ const c10::complex<double> *a, int64_t lda,
106
+ const c10::complex<double> *b, int64_t ldb,
107
+ c10::complex<double> beta,
108
+ c10::complex<double> *c, int64_t ldc);
109
+
110
+ void gemm(
111
+ TransposeType transa, TransposeType transb,
112
+ int64_t m, int64_t n, int64_t k,
113
+ c10::complex<float> alpha,
114
+ const c10::complex<float> *a, int64_t lda,
115
+ const c10::complex<float> *b, int64_t ldb,
116
+ c10::complex<float> beta,
117
+ c10::complex<float> *c, int64_t ldc);
118
+
119
+ void gemm(
120
+ TransposeType transa, TransposeType transb,
121
+ int64_t m, int64_t n, int64_t k,
122
+ int64_t alpha,
123
+ const int64_t *a, int64_t lda,
124
+ const int64_t *b, int64_t ldb,
125
+ int64_t beta,
126
+ int64_t *c, int64_t ldc);
127
+
128
+ template <typename scalar_t>
129
+ void gemm_batched(
130
+ TransposeType transa, TransposeType transb,
131
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
132
+ scalar_t alpha,
133
+ const scalar_t * const *a, int64_t lda,
134
+ const scalar_t * const *b, int64_t ldb,
135
+ const scalar_t beta,
136
+ scalar_t * const *c, int64_t ldc);
137
+
138
+ template <typename scalar_t>
139
+ void gemm_batched_with_stride(
140
+ TransposeType transa, TransposeType transb,
141
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
142
+ scalar_t alpha,
143
+ const scalar_t *a, int64_t lda, int64_t batch_stride_a,
144
+ const scalar_t *b, int64_t ldb, int64_t batch_stride_b,
145
+ scalar_t beta,
146
+ scalar_t *c, int64_t ldc, int64_t batch_stride_c);
147
+
148
+ using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy);
149
+
150
+ DECLARE_DISPATCH(axpy_fn, axpy_stub)
151
+
152
+ template<typename scalar_t>
153
+ void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){
154
+ if(n == 1)
155
+ {
156
+ incx = 1;
157
+ incy = 1;
158
+ }
159
+ axpy_stub(
160
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
161
+ n, a, x, incx, y, incy);
162
+ }
163
+
164
+ void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy);
165
+ void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy);
166
+ void axpy(int64_t n, c10::complex<double> a, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
167
+ void axpy(int64_t n, c10::complex<float> a, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
168
+
169
+ using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy);
170
+
171
+ DECLARE_DISPATCH(copy_fn, copy_stub)
172
+
173
+ template<typename scalar_t>
174
+ void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) {
175
+ if(n == 1)
176
+ {
177
+ incx = 1;
178
+ incy = 1;
179
+ }
180
+ copy_stub(
181
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
182
+ n, x, incx, y, incy);
183
+ }
184
+
185
+ void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy);
186
+ void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy);
187
+ void copy(int64_t n, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
188
+ void copy(int64_t n, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
189
+
190
+ // Batch-reduce GEMM
191
+ // Operates by the following formula:
192
+ // C = SUM(A[i] x B[i]) + C if add_C is true, i = 0 to batch size
193
+ // A Base pointer to a tensor A.
194
+ // B Base pointer to a tensor B.
195
+ // C Pointer to a tensor C (accumulation buffer).
196
+ // Note only batch size 1 is used currently
197
+ TORCH_API void brgemm(
198
+ int64_t M,
199
+ int64_t N,
200
+ int64_t K,
201
+ int64_t ld_a,
202
+ int64_t ld_b,
203
+ int64_t ld_c,
204
+ const bool add_C,
205
+ const at::Half* A,
206
+ const at::Half* B,
207
+ float* C,
208
+ bool is_vnni = true);
209
+
210
+ TORCH_API void brgemm(
211
+ int64_t M,
212
+ int64_t N,
213
+ int64_t K,
214
+ int64_t ld_a,
215
+ int64_t ld_b,
216
+ int64_t ld_c,
217
+ const bool add_C,
218
+ const at::BFloat16* A,
219
+ const at::BFloat16* B,
220
+ float* C,
221
+ bool is_vnni = true);
222
+
223
+ TORCH_API void brgemm(
224
+ int64_t M,
225
+ int64_t N,
226
+ int64_t K,
227
+ int64_t ld_a,
228
+ int64_t ld_b,
229
+ int64_t ld_c,
230
+ const bool add_C,
231
+ const float* A,
232
+ const float* B,
233
+ float* C,
234
+ bool is_vnni = false);
235
+
236
+ TORCH_API void brgemm(
237
+ int64_t M,
238
+ int64_t N,
239
+ int64_t K,
240
+ int64_t ld_a,
241
+ int64_t ld_b,
242
+ int64_t ld_c,
243
+ const bool add_C,
244
+ const unsigned char* A,
245
+ const unsigned char* B,
246
+ int32_t* C,
247
+ bool is_vnni = true);
248
+
249
+ TORCH_API void brgemm(
250
+ int64_t M,
251
+ int64_t N,
252
+ int64_t K,
253
+ int64_t ld_a,
254
+ int64_t ld_b,
255
+ int64_t ld_c,
256
+ const bool add_C,
257
+ const unsigned char* A,
258
+ const signed char* B,
259
+ int32_t* C,
260
+ bool is_vnni = true);
261
+
262
+ // Release brgemm hardware context
263
+ TORCH_API void brgemm_release(bool is_vnni = true);
264
+
265
+ // Pack B matrix to get better performance if needed
266
+ TORCH_API void pack(
267
+ int64_t K,
268
+ int64_t N,
269
+ int64_t ld_in,
270
+ int64_t ld_out,
271
+ ScalarType dt_in,
272
+ ScalarType dt_out,
273
+ const void* in,
274
+ void* out);
275
+
276
+ // Whether pack is supported in the platform.
277
+ TORCH_API bool could_pack(ScalarType dt_in);
278
+
279
+ } // namespace at::native::cpublas
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CPUFallback.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <ATen/core/stack.h>
5
+ #include <ATen/core/boxing/KernelFunction.h>
6
+ #include <ATen/core/dispatch/Dispatcher.h>
7
+ #include <c10/util/Metaprogramming.h>
8
+ #include <torch/library.h>
9
+
10
+ namespace at::native {
11
+
12
+ // This function implements a boxed fallback to CPU.
13
+ // External backends can add their own custom logging on top if it to customize their own CPU fallbacks.
14
+ TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool error_on_views = false,
15
+ c10::DispatchKey cpu_dispatch_key = c10::DispatchKey::CPU);
16
+
17
+ // This is a helper function that backends can use to directly call their boxed CPU fallback
18
+ // TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands.
19
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
20
+ struct _call_fallback_fn final {};
21
+
22
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
23
+ struct _call_fallback_fn<fallback_fn, Op, symint, ReturnType(ParameterTypes...)> final {
24
+ static ReturnType call(typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
25
+ auto op = c10::Dispatcher::singleton()
26
+ // TODO: figure out how to make compiler happy without dynamic casts
27
+ .findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name)
28
+ //.findSchemaOrThrow("a", "b")
29
+ .typed<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>();
30
+ return c10::impl::BoxedKernelWrapper<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>::call(
31
+ c10::BoxedKernel::makeFromFunction<fallback_fn>(),
32
+ op,
33
+ c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset.
34
+ // TODO: get std::forward<> to work
35
+ args...
36
+ );
37
+ }
38
+ };
39
+
40
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
41
+ using call_fallback_fn_symint = _call_fallback_fn<fallback_fn, Op, true, typename Op::schema>;
42
+
43
+ template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
44
+ using call_fallback_fn = _call_fallback_fn<fallback_fn, Op, false, typename Op::schema>;
45
+
46
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CanUse32BitIndexMath.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Export.h>
3
+ #include <limits>
4
+
5
+ namespace at {
6
+ class TensorBase;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ TORCH_API bool canUse32BitIndexMath(const at::TensorBase &t, int64_t max_elem=std::numeric_limits<int32_t>::max());
12
+
13
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ComplexHelper.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/NativeFunctions.h>
8
+ #else
9
+ #include <ATen/ops/view_as_real_native.h>
10
+ #include <ATen/ops/view_as_complex_native.h>
11
+
12
+ #include <utility>
13
+ #endif
14
+
15
+ // WARNING: this header contains non-inline functions and should be only
16
+ // included from ONE cpp file
17
+
18
+ namespace at::native {
19
+
20
+ // View tensor with new dtype, storage offset, sizes and strides
21
+ inline Tensor view_tensor(
22
+ const Tensor &tensor, ScalarType dtype,
23
+ c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) {
24
+ Storage storage = tensor.storage();
25
+ auto key_set = tensor.key_set().remove(DispatchKey::Conjugate);
26
+ auto new_tensor = detail::make_tensor<TensorImpl>(
27
+ c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype));
28
+ auto * impl = new_tensor.unsafeGetTensorImpl();
29
+ impl->set_sizes_and_strides(sizes, strides, offset);
30
+ return new_tensor;
31
+ }
32
+
33
+ inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) {
34
+ SymDimVector res(oldstride.size() + 1);
35
+ for (const auto i : c10::irange(oldstride.size())) {
36
+ res[i] = oldstride[i] * 2;
37
+ }
38
+ res.back() = 1;
39
+ return res;
40
+ }
41
+
42
+ inline Tensor _view_as_real_physical(const Tensor& self) {
43
+ TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors");
44
+ auto old_sizes = self.sym_sizes();
45
+ SymDimVector new_sizes(old_sizes.size() + 1);
46
+ std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
47
+ // last dimension will always have two elements containing the real and imag vals
48
+ new_sizes.back() = 2;
49
+ auto new_strides = computeStrideForViewAsReal(self.sym_strides());
50
+ auto new_storage_offset = self.sym_storage_offset() * 2;
51
+ const auto float_type = c10::toRealValueType(self.scalar_type());
52
+ auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides);
53
+ return real_tensor;
54
+ }
55
+
56
+ // expects as input a complex tensor and returns back a tensor
57
+ // with corresponding real dtype containing the complex values
58
+ // in the last two dimensions
59
+ Tensor view_as_real(const Tensor& self) {
60
+ TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original.");
61
+ return _view_as_real_physical(self);
62
+ }
63
+
64
+ inline SymDimVector computeStrideForViewAsComplex(SymIntArrayRef oldstride) {
65
+ const auto dim = oldstride.size();
66
+ TORCH_CHECK(dim > 0 && oldstride[dim - 1] == 1, "Tensor must have a last dimension with stride 1");
67
+
68
+ SymDimVector res(dim - 1);
69
+ for (const auto i : c10::irange(res.size())) {
70
+ TORCH_CHECK(oldstride[i] % 2 == 0, "Tensor must have a stride divisible by 2 for all but last dimension");
71
+ res[i] = oldstride[i] / 2;
72
+ }
73
+ return res;
74
+ }
75
+
76
+ // expects as input a float or double tensor with last dimension of size 2
77
+ // and returns back a tensor with corresponding complex dtype
78
+ Tensor view_as_complex(const Tensor& self) {
79
+ TORCH_CHECK(
80
+ self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf,
81
+ "view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type());
82
+
83
+ auto old_sizes = self.sym_sizes();
84
+ TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions");
85
+ TORCH_CHECK(old_sizes[old_sizes.size()-1] == 2, "Tensor must have a last dimension of size 2");
86
+ SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1);
87
+
88
+ const auto new_strides = computeStrideForViewAsComplex(self.sym_strides());
89
+ const auto complex_type = c10::toComplexType(self.scalar_type());
90
+
91
+ TORCH_CHECK(self.sym_storage_offset() % 2 == 0, "Tensor must have a storage_offset divisible by 2");
92
+ const auto new_storage_offset = self.sym_storage_offset() / 2;
93
+
94
+ return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides);
95
+ }
96
+
97
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/CompositeRandomAccessorCommon.h>
4
+
5
+ namespace at::native {
6
+
7
+ struct TupleInfoCPU {
8
+ template <typename ...Types>
9
+ using tuple = std::tuple<Types...>;
10
+
11
+ template <typename ...Types>
12
+ static constexpr auto tie(Types&... args) noexcept {
13
+ return std::tie(args...);
14
+ }
15
+ };
16
+
17
+ template <typename KeyAccessor, typename ValueAccessor>
18
+ using CompositeRandomAccessorCPU =
19
+ CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfoCPU>;
20
+
21
+ template <typename Values, typename References>
22
+ void swap(
23
+ references_holder<Values, References> rh1,
24
+ references_holder<Values, References> rh2
25
+ ) {
26
+ return std::swap(rh1.data(), rh2.data());
27
+ }
28
+
29
+ template <int N, typename Values, typename References>
30
+ auto get(references_holder<Values, References> rh) -> decltype(std::get<N>(rh.data())) {
31
+ return std::get<N>(rh.data());
32
+ }
33
+
34
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <utility>
2
+
3
+ #pragma once
4
+
5
+ namespace at::native {
6
+
7
+ namespace {
8
+
9
+ // operator_brackets_proxy is used in
10
+ // CompositeRandomAccessor in place of operator[].
11
+ // For some iterators, references returned by operator[]
12
+ // could become invalid, operator_brackets_proxy tries to
13
+ // resolve that by making accessor[n] to be equivalent to
14
+ // *(accessor + n).
15
+ template <typename Accessor>
16
+ class operator_brackets_proxy {
17
+ using reference = typename std::iterator_traits<Accessor>::reference;
18
+ using value_type = typename std::iterator_traits<Accessor>::value_type;
19
+
20
+ public:
21
+ C10_HOST_DEVICE
22
+ operator_brackets_proxy(Accessor const& accessor)
23
+ : accessor(accessor)
24
+ {}
25
+
26
+ C10_HOST_DEVICE
27
+ operator reference() {
28
+ return *accessor;
29
+ }
30
+
31
+ C10_HOST_DEVICE
32
+ reference operator*() {
33
+ return *accessor;
34
+ }
35
+
36
+ C10_HOST_DEVICE
37
+ operator_brackets_proxy& operator=(value_type const& val) {
38
+ *accessor = val;
39
+ return *this;
40
+ }
41
+
42
+ private:
43
+ Accessor accessor;
44
+ };
45
+
46
+ }
47
+
48
+ // references_holder is used as a surrogate for the
49
+ // references type from std::iterator_traits in CompositeRandomAccessor.
50
+ // It is assumed in CompositeRandomAccessor that
51
+ // References = tuple<Types&...>,
52
+ // Values = tuple<Types...> by default,
53
+ // but they could be anything as long as References could be
54
+ // cast to Values.
55
+ // If you plan to use it with STL, for example, you will need to
56
+ // define 'swap` and `get`(aka std::get) methods.
57
+ template <typename Values, typename References>
58
+ class references_holder {
59
+ public:
60
+ using values = Values;
61
+ using references = References;
62
+
63
+ C10_HOST_DEVICE
64
+ references_holder(references refs)
65
+ : refs{std::move(refs)}
66
+ {}
67
+
68
+ C10_HOST_DEVICE
69
+ operator references() {
70
+ return refs;
71
+ }
72
+
73
+ C10_HOST_DEVICE
74
+ operator values() {
75
+ return refs;
76
+ }
77
+
78
+ C10_HOST_DEVICE
79
+ references_holder& operator=(values vals) {
80
+ refs = vals;
81
+ return *this;
82
+ }
83
+
84
+ C10_HOST_DEVICE
85
+ references& data() {
86
+ return refs;
87
+ }
88
+
89
+ protected:
90
+ references refs;
91
+ };
92
+
93
+ // CompositeRandomAccessor is essentially a simplified version of
94
+ // a random access iterator over two random access iterators.
95
+ // TupleInfo should contain a variadic type `tuple`, and a method `tie`,
96
+ // which constructs a tuple of references from a variadic list of arguments.
97
+ template <typename KeyAccessor, typename ValueAccessor, typename TupleInfo>
98
+ class CompositeRandomAccessor {
99
+ using self_type = CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfo>;
100
+
101
+ using key_accessor_value_type =
102
+ typename std::iterator_traits<KeyAccessor>::value_type;
103
+ using value_accessor_value_type =
104
+ typename std::iterator_traits<ValueAccessor>::value_type;
105
+ using key_accessor_reference_type =
106
+ typename std::iterator_traits<KeyAccessor>::reference;
107
+ using value_accessor_reference_type =
108
+ typename std::iterator_traits<ValueAccessor>::reference;
109
+
110
+ using composite_value_type = typename TupleInfo::template tuple<
111
+ key_accessor_value_type,
112
+ value_accessor_value_type>;
113
+ using composite_reference = typename TupleInfo::template tuple<
114
+ key_accessor_reference_type,
115
+ value_accessor_reference_type>;
116
+
117
+ public:
118
+ using value_type = composite_value_type;
119
+ using reference = references_holder<composite_value_type, composite_reference>;
120
+ // Note that CompositeRandomAccessor does not hold key and values
121
+ // in a specific datastructure, which means that a pointer to a (key, value)
122
+ // is not defined. Hence we just use a pointer type of the KeyAccessor.
123
+ using pointer = typename std::iterator_traits<KeyAccessor>::pointer;
124
+ using difference_type = typename std::iterator_traits<KeyAccessor>::difference_type;
125
+ using iterator_category = std::random_access_iterator_tag;
126
+
127
+ C10_HOST_DEVICE
128
+ CompositeRandomAccessor() = default;
129
+
130
+ C10_HOST_DEVICE
131
+ CompositeRandomAccessor(KeyAccessor keys, ValueAccessor values)
132
+ : keys(keys), values(values)
133
+ {}
134
+
135
+ // Pointer-like operations {
136
+ C10_HOST_DEVICE
137
+ reference operator*() const {
138
+ return TupleInfo::tie(*keys, *values);
139
+ }
140
+
141
+ // operator->() is supposed to return a pointer type.
142
+ // Since CompositeRandomAccessor does not hold pointers to pairs,
143
+ // we just return a pointer to a key.
144
+ C10_HOST_DEVICE
145
+ auto* operator->() const {
146
+ return keys.operator->();
147
+ }
148
+
149
+ C10_HOST_DEVICE
150
+ reference operator[](difference_type idx) {
151
+ return operator_brackets_proxy<self_type>(
152
+ CompositeRandomAccessor(keys + idx, values + idx)
153
+ );
154
+ }
155
+ // }
156
+
157
+ // Prefix/postfix increment/decrement {
158
+ C10_HOST_DEVICE
159
+ CompositeRandomAccessor& operator++() {
160
+ ++keys;
161
+ ++values;
162
+ return *this;
163
+ }
164
+
165
+ C10_HOST_DEVICE
166
+ CompositeRandomAccessor operator++(int) {
167
+ CompositeRandomAccessor copy(*this);
168
+ ++*this;
169
+ return copy;
170
+ }
171
+
172
+ C10_HOST_DEVICE
173
+ CompositeRandomAccessor& operator--() {
174
+ --keys;
175
+ --values;
176
+ return *this;
177
+ }
178
+
179
+ C10_HOST_DEVICE
180
+ CompositeRandomAccessor operator--(int) {
181
+ CompositeRandomAccessor copy(*this);
182
+ --*this;
183
+ return copy;
184
+ }
185
+ // }
186
+
187
+ // Arithmetic operations {
188
+ C10_HOST_DEVICE
189
+ CompositeRandomAccessor& operator+=(difference_type offset) {
190
+ keys += offset;
191
+ values += offset;
192
+ return *this;
193
+ }
194
+
195
+ C10_HOST_DEVICE
196
+ CompositeRandomAccessor operator+(difference_type offset) const {
197
+ return CompositeRandomAccessor(keys + offset, values + offset);
198
+ }
199
+
200
+ C10_HOST_DEVICE
201
+ friend CompositeRandomAccessor operator+(
202
+ difference_type offset,
203
+ const CompositeRandomAccessor& accessor
204
+ ) {
205
+ return accessor + offset;
206
+ }
207
+
208
+ C10_HOST_DEVICE
209
+ CompositeRandomAccessor& operator-=(difference_type offset) {
210
+ keys -= offset;
211
+ values -= offset;
212
+ return *this;
213
+ }
214
+
215
+ C10_HOST_DEVICE
216
+ CompositeRandomAccessor operator-(difference_type offset) const {
217
+ return CompositeRandomAccessor(keys - offset, values - offset);
218
+ }
219
+
220
+ C10_HOST_DEVICE
221
+ difference_type operator-(const CompositeRandomAccessor& other) const {
222
+ return keys - other.keys;
223
+ }
224
+ // }
225
+
226
+ // Comparison operators {
227
+ C10_HOST_DEVICE
228
+ bool operator==(const CompositeRandomAccessor& other) const {
229
+ return keys == other.keys;
230
+ }
231
+
232
+ C10_HOST_DEVICE
233
+ bool operator!=(const CompositeRandomAccessor& other) const {
234
+ return keys != other.keys;
235
+ }
236
+
237
+ C10_HOST_DEVICE
238
+ bool operator<(const CompositeRandomAccessor& other) const {
239
+ return keys < other.keys;
240
+ }
241
+
242
+ C10_HOST_DEVICE
243
+ bool operator<=(const CompositeRandomAccessor& other) const {
244
+ return keys <= other.keys;
245
+ }
246
+
247
+ C10_HOST_DEVICE
248
+ bool operator>(const CompositeRandomAccessor& other) const {
249
+ return keys > other.keys;
250
+ }
251
+
252
+ C10_HOST_DEVICE
253
+ bool operator>=(const CompositeRandomAccessor& other) const {
254
+ return keys >= other.keys;
255
+ }
256
+ // }
257
+
258
+ protected:
259
+ KeyAccessor keys;
260
+ ValueAccessor values;
261
+ };
262
+
263
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ConvUtils.h ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/TensorUtils.h>
4
+ #include <ATen/detail/CUDAHooksInterface.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <c10/util/env.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ #include <utility>
10
+
11
+ namespace at::native {
12
+
13
+ using conv_depthwise2d_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
14
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
15
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 2>);
16
+ DECLARE_DISPATCH(conv_depthwise2d_backward_fn, conv_depthwise2d_backward_stub)
17
+ using conv_depthwise3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
18
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
19
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
20
+ DECLARE_DISPATCH(conv_depthwise3d_backward_fn, conv_depthwise3d_backward_stub)
21
+ using cudnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
22
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
23
+ at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
24
+ DECLARE_DISPATCH(cudnn_convolution_backward_fn, cudnn_convolution_backward_stub)
25
+ using mps_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
26
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
27
+ at::IntArrayRef, int64_t, std::array<bool,3>);
28
+ DECLARE_DISPATCH(mps_convolution_backward_fn, mps_convolution_backward_stub)
29
+ using cudnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
30
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
31
+ at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
32
+ DECLARE_DISPATCH(cudnn_convolution_transpose_backward_fn, cudnn_convolution_transpose_backward_stub)
33
+ using miopen_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
34
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
35
+ at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
36
+ DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_convolution_backward_stub)
37
+ using miopen_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
38
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
39
+ at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
40
+ DECLARE_DISPATCH(miopen_convolution_transpose_backward_fn, miopen_convolution_transpose_backward_stub)
41
+ using miopen_depthwise_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
42
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
43
+ at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
44
+ DECLARE_DISPATCH(miopen_depthwise_convolution_backward_fn, miopen_depthwise_convolution_backward_stub)
45
+ using mkldnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
46
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
47
+ at::IntArrayRef, int64_t, std::array<bool,3>);
48
+ DECLARE_DISPATCH(mkldnn_convolution_backward_fn, mkldnn_convolution_backward_stub)
49
+ using mkldnn_convolution_transpose_fn = Tensor(*)(const Tensor&, const Tensor&, const std::optional<Tensor>&,
50
+ IntArrayRef, IntArrayRef, IntArrayRef, IntArrayRef, int64_t);
51
+ DECLARE_DISPATCH(mkldnn_convolution_transpose_fn, mkldnn_convolution_transpose_stub)
52
+ using mkldnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
53
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
54
+ at::IntArrayRef, at::IntArrayRef, int64_t, std::array<bool,3>);
55
+ DECLARE_DISPATCH(mkldnn_convolution_transpose_backward_fn, mkldnn_convolution_transpose_backward_stub)
56
+ using slow_conv_dilated2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
57
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
58
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
59
+ DECLARE_DISPATCH(slow_conv_dilated2d_backward_fn, slow_conv_dilated2d_backward_stub)
60
+ using slow_conv_dilated3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
61
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
62
+ at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
63
+ DECLARE_DISPATCH(slow_conv_dilated3d_backward_fn, slow_conv_dilated3d_backward_stub)
64
+ using slow_conv_transpose2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
65
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
66
+ at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
67
+ DECLARE_DISPATCH(slow_conv_transpose2d_backward_fn, slow_conv_transpose2d_backward_stub)
68
+ using slow_conv_transpose3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
69
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
70
+ at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
71
+ DECLARE_DISPATCH(slow_conv_transpose3d_backward_fn, slow_conv_transpose3d_backward_stub)
72
+
73
+ namespace {
74
+ bool is_cudnnv8_heuristic_mode_b() {
75
+ static const bool is_cudnnv8_heuristic_mode_b = c10::utils::check_env("TORCH_CUDNN_USE_HEURISTIC_MODE_B") == true;
76
+ return is_cudnnv8_heuristic_mode_b;
77
+ }
78
+ }
79
+
80
+ inline bool cudnnv8_enabled_check_debug() {
81
+ static bool cudnnv8_flag = c10::utils::check_env("TORCH_CUDNN_V8_API_DISABLED") != true;
82
+ static bool cudnnv8_debug = c10::utils::check_env("TORCH_CUDNN_V8_API_DEBUG") == true;
83
+ static uint8_t cudnnv8_debugcount = 0;
84
+ if (cudnnv8_debug == 1 && cudnnv8_debugcount < 10) {
85
+ TORCH_WARN("TORCH_CUDNN_V8_DEBUG ON, V8 ON: ", cudnnv8_flag, " TORCH_CUDNN_USE_HEURISTIC_MODE B: ", is_cudnnv8_heuristic_mode_b());
86
+ cudnnv8_debugcount++;
87
+ }
88
+ return cudnnv8_flag == 1;
89
+ }
90
+
91
+ inline bool cudnnv8_use_heur_mode_b() {
92
+ return is_cudnnv8_heuristic_mode_b();
93
+ }
94
+
95
+ // Keep in sync with py::enum_ in Module.cpp
96
+ enum class ConvBackend {
97
+ CudaDepthwise2d,
98
+ CudaDepthwise3d,
99
+ Cudnn,
100
+ CudnnTranspose,
101
+ Empty,
102
+ Miopen,
103
+ MiopenDepthwise,
104
+ MiopenTranspose,
105
+ Mkldnn,
106
+ MkldnnTranspose,
107
+ MkldnnEmpty,
108
+ NnpackSpatial,
109
+ Overrideable,
110
+ Slow2d,
111
+ Slow3d,
112
+ SlowDilated2d,
113
+ SlowDilated3d,
114
+ SlowTranspose2d,
115
+ SlowTranspose3d,
116
+ Winograd3x3Depthwise,
117
+ Xnnpack2d,
118
+ Mps,
119
+ MpsTranspose,
120
+ };
121
+
122
+ // Overload for selecting the convolution backend from the full set of convolution inputs.
123
+ // This overload is exposed to python for testing, etc.
124
+ TORCH_API ConvBackend select_conv_backend(
125
+ const Tensor& input, const Tensor& weight, const std::optional<Tensor>& bias_opt,
126
+ SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation,
127
+ bool transposed, SymIntArrayRef output_padding, c10::SymInt groups, const at::OptionalSymIntArrayRef bias_sizes_opt);
128
+
129
+ TORCH_API at::MemoryFormat _determine_backend_memory_format(const Tensor& input,
130
+ const Tensor& weight,
131
+ const ConvBackend backend);
132
+
133
+ // ---------------------------------------------------------------------
134
+ //
135
+ // Math
136
+ //
137
+ // ---------------------------------------------------------------------
138
+
139
+ constexpr int input_batch_size_dim = 0; // also grad_input
140
+ constexpr int input_channels_dim = 1;
141
+ constexpr int output_batch_size_dim = 0; // also grad_output
142
+ constexpr int output_channels_dim = 1;
143
+ constexpr int weight_output_channels_dim = 0;
144
+ constexpr int weight_input_channels_dim = 1;
145
+
146
+ // Often written as 2 + max_dim (extra dims for batch size and channels)
147
+ constexpr int max_dim = 3;
148
+
149
+ // ---------------------------------------------------------------------
150
+ //
151
+ // Checking
152
+ //
153
+ // ---------------------------------------------------------------------
154
+
155
+ // Used on pad, stride and dilation
156
+ static void check_args(CheckedFrom c, IntArrayRef args, size_t expected_size, const char* arg_name)
157
+ {
158
+ TORCH_CHECK(args.size() <= expected_size,
159
+ "Too many ", arg_name, " values (", args.size(), ") supplied, expecting ",
160
+ expected_size, " (while checking arguments for ", c, ")");
161
+ TORCH_CHECK(args.size() >= expected_size,
162
+ "Not enough ", arg_name, " values (", args.size(), ") supplied, expecting ",
163
+ expected_size, " (while checking arguments for ", c, ")");
164
+
165
+ auto num_negative_values = std::count_if(args.begin(), args.end(), [](int x){return x < 0;});
166
+ if (num_negative_values > 0){
167
+ std::stringstream ss;
168
+ ss << arg_name << " should be greater than zero but got (";
169
+ std::copy(args.begin(), args.end() - 1, std::ostream_iterator<int>(ss,", "));
170
+ ss << args.back() << ")" << " (while checking arguments for " << c << ")";
171
+ TORCH_CHECK(false, ss.str());
172
+ }
173
+ }
174
+
175
+
176
+ // NOTE [ Convolution checks ]
177
+ //
178
+ // NB: For many call sites, it is not strictly necessary to check all of
179
+ // these relationships (for example, for forward convolution, we compute
180
+ // the size of output ourselves, so we don't actually need to check
181
+ // output. However, writing a single function that does everything
182
+ // means we get to reuse it for both forwards and all backwards
183
+ // variants, even when the set of "real" inputs varies. The magic of
184
+ // relational computing!
185
+ //
186
+ // (There is one downside, which is that it is slightly harder to write
187
+ // error messages which are able to distinguish between real inputs
188
+ // (which the user can change) and computed inputs (which the user can
189
+ // only indirectly affect). It would be an interesting exercise to
190
+ // come up with a general framework to handle such situations.)
191
+ inline void convolution_shape_check(
192
+ CheckedFrom c,
193
+ const TensorGeometryArg& input, const TensorGeometryArg& weight, const TensorGeometryArg& output,
194
+ IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups)
195
+ {
196
+ check_args(c, padding, input->dim() - 2, "padding");
197
+ check_args(c, stride, padding.size(), "stride");
198
+ check_args(c, dilation, padding.size(), "dilation");
199
+
200
+ // Input
201
+ checkDimRange(c, input, 3, 6 /* exclusive */);
202
+ checkSize_symint(c, input, input_channels_dim, weight->size(1) * groups);
203
+
204
+ // Weight
205
+ checkSameDim(c, input, weight);
206
+
207
+ // TODO: check that output->size() matches output_sizes
208
+ // TODO: check that weight matches output->sizes()
209
+ checkSameDim(c, input, output);
210
+ }
211
+
212
+ // NB: conv_output_size and conv_input_size are not bijections,
213
+ // as conv_output_size loses information; this is why conv_input_size
214
+ // takes an extra output_padding argument to resolve the ambiguity.
215
+
216
+ template <typename T>
217
+ inline std::vector<T> _conv_output_size(
218
+ ArrayRef<T> input_size, ArrayRef<T> weight_size,
219
+ ArrayRef<T> padding, ArrayRef<T> stride, ArrayRef<T> dilation = ArrayRef<T>()
220
+ ) {
221
+ // ASSERT(input_size.size() > 2)
222
+ // ASSERT(input_size.size() == weight_size.size())
223
+ bool has_dilation = !dilation.empty();
224
+ auto dim = input_size.size();
225
+ std::vector<T> output_size(dim);
226
+ output_size[0] = input_size[input_batch_size_dim];
227
+ output_size[1] = weight_size[weight_output_channels_dim];
228
+ for (const auto d : c10::irange(2, dim)) {
229
+ auto dilation_ = has_dilation ? dilation[d - 2] : 1;
230
+ auto kernel = dilation_ * (weight_size[d] - 1) + 1;
231
+ output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1;
232
+ }
233
+ return output_size;
234
+ }
235
+
236
+ inline std::vector<int64_t> conv_output_size(
237
+ IntArrayRef input_size, IntArrayRef weight_size,
238
+ IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
239
+ ) {
240
+ return _conv_output_size(input_size, weight_size, padding, stride, dilation);
241
+ }
242
+
243
+ inline std::vector<c10::SymInt> conv_output_size(
244
+ SymIntArrayRef input_size, SymIntArrayRef weight_size,
245
+ SymIntArrayRef padding, SymIntArrayRef stride, SymIntArrayRef dilation = SymIntArrayRef()
246
+ ) {
247
+ return _conv_output_size(input_size, weight_size, padding, stride, dilation);
248
+ }
249
+
250
+ template <typename T>
251
+ std::vector<T> _conv_input_size(
252
+ ArrayRef<T> output_size, ArrayRef<T> weight_size,
253
+ ArrayRef<T> padding, ArrayRef<T> output_padding, ArrayRef<T> stride, ArrayRef<T> dilation, T groups
254
+ ) {
255
+ // ASSERT(output_size.size() > 2)
256
+ // ASSERT(output_size.size() == weight_size.size())
257
+ auto dim = output_size.size();
258
+ std::vector<T> input_size(dim);
259
+ input_size[0] = output_size[output_batch_size_dim];
260
+ input_size[1] = weight_size[weight_input_channels_dim] * groups;
261
+ for (const auto d : c10::irange(2, dim)) {
262
+ auto kernel = (weight_size[d] - 1) * dilation[d - 2] + 1;
263
+ input_size[d] = (output_size[d] - 1) * stride[d - 2] - (padding[d - 2] * 2) +
264
+ kernel + output_padding[d - 2];
265
+ }
266
+ return input_size;
267
+ }
268
+
269
+ inline std::vector<c10::SymInt> conv_input_size(
270
+ SymIntArrayRef output_size, SymIntArrayRef weight_size,
271
+ SymIntArrayRef padding, SymIntArrayRef output_padding, SymIntArrayRef stride, SymIntArrayRef dilation, c10::SymInt groups
272
+ ) {
273
+ return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, std::move(groups));
274
+ }
275
+
276
+ inline std::vector<int64_t> conv_input_size(
277
+ IntArrayRef output_size, IntArrayRef weight_size,
278
+ IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
279
+ ) {
280
+ return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
281
+ }
282
+
283
+ template <typename T>
284
+ std::vector<T> _conv_weight_size(
285
+ ArrayRef<T> input_size, ArrayRef<T> output_size,
286
+ ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
287
+ ) {
288
+ auto dim = input_size.size();
289
+ std::vector<T> weight_size(dim);
290
+ weight_size[0] = output_size[1];
291
+ weight_size[1] = input_size[1] / groups;
292
+ for (const auto d : c10::irange(2, dim)) {
293
+ auto kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2]
294
+ + padding[d - 2] * 2 - output_padding[d - 2];
295
+ weight_size[d] = (kernel - 1) / dilation[d - 2] + 1;
296
+ }
297
+ return weight_size;
298
+ }
299
+
300
+ inline std::vector<c10::SymInt> conv_weight_size(
301
+ SymIntArrayRef input_size, SymIntArrayRef output_size,
302
+ SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
303
+ ) {
304
+ return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
305
+ }
306
+
307
+ inline std::vector<int64_t> conv_weight_size(
308
+ IntArrayRef input_size, IntArrayRef output_size,
309
+ IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
310
+ ) {
311
+ return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
312
+ }
313
+
314
+ inline Tensor reshape_bias(int64_t dim, const Tensor& bias) {
315
+ std::vector<int64_t> shape(dim, 1);
316
+ shape[1] = -1;
317
+ return bias.reshape(shape);
318
+ }
319
+
320
+ inline at::MemoryFormat cudnn_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) {
321
+ // disable NHWC for float64 input.
322
+ if (!at::detail::getCUDAHooks().compiledWithCuDNN() ||
323
+ input.scalar_type() == at::kDouble ||
324
+ weight.scalar_type() == at::kDouble) {
325
+ return at::MemoryFormat::Contiguous;
326
+ }
327
+ long cudnn_version = at::detail::getCUDAHooks().versionCuDNN();
328
+ auto input_memory_format = input.suggest_memory_format();
329
+ auto weight_memory_format = weight.suggest_memory_format();
330
+ auto weight_ndim = weight.ndimension();
331
+
332
+ bool can_use_cudnn_channels_last_2d = (cudnn_version >= 7603) && (weight_ndim == 4) && (
333
+ (input_memory_format == at::MemoryFormat::ChannelsLast) ||
334
+ (weight_memory_format == at::MemoryFormat::ChannelsLast)
335
+ );
336
+ if (can_use_cudnn_channels_last_2d) {
337
+ return at::MemoryFormat::ChannelsLast;
338
+ }
339
+
340
+ bool can_use_cudnn_channels_last_3d = (cudnn_version >= 8005) && (weight_ndim == 5) && (
341
+ (input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
342
+ (weight_memory_format == at::MemoryFormat::ChannelsLast3d)
343
+ );
344
+ if (can_use_cudnn_channels_last_3d) {
345
+ return at::MemoryFormat::ChannelsLast3d;
346
+ }
347
+
348
+ return at::MemoryFormat::Contiguous;
349
+ }
350
+
351
+ // controls whether emptyCache will be called following cudnn conv benchmarking
352
+ TORCH_API void _cudnn_set_conv_benchmark_empty_cache(bool enable);
353
+ TORCH_API bool _cudnn_get_conv_benchmark_empty_cache();
354
+
355
+
356
+ inline bool miopen_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
357
+
358
+ // disable NHWC for float64 input.
359
+ if (!at::detail::getCUDAHooks().compiledWithMIOpen() ||
360
+ input.scalar_type() == at::kDouble ||
361
+ weight.scalar_type() == at::kDouble) {
362
+ return false;
363
+ }
364
+
365
+ bool can_use_miopen_channels_last_2d = false;
366
+ // TODO: Remove PYTORCH_MIOPEN_SUGGEST_NHWC once ROCm officially supports NHWC in MIOpen
367
+ // See #64427
368
+ static std::optional<bool> PYTORCH_MIOPEN_SUGGEST_NHWC = c10::utils::check_env("PYTORCH_MIOPEN_SUGGEST_NHWC");
369
+
370
+ auto input_memory_format = input.suggest_memory_format();
371
+ auto weight_memory_format = weight.suggest_memory_format();
372
+
373
+ can_use_miopen_channels_last_2d = PYTORCH_MIOPEN_SUGGEST_NHWC && *PYTORCH_MIOPEN_SUGGEST_NHWC && (
374
+ ( (input_memory_format == at::MemoryFormat::ChannelsLast) ||
375
+ (weight_memory_format == at::MemoryFormat::ChannelsLast) )
376
+ );
377
+
378
+ bool can_use_miopen_channels_last_3d = false;
379
+
380
+ return can_use_miopen_channels_last_2d || can_use_miopen_channels_last_3d;
381
+ }
382
+
383
+ inline bool mkldnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
384
+
385
+ // disable NHWC for float64 input.
386
+ if (input.scalar_type() == at::kDouble ||
387
+ weight.scalar_type() == at::kDouble) {
388
+ return false;
389
+ }
390
+
391
+ // disable NHWC for MkldnnCPU tensor.
392
+ if (input.is_mkldnn() || weight.is_mkldnn()) {
393
+ return false;
394
+ }
395
+
396
+ auto input_memory_format = input.suggest_memory_format();
397
+ auto weight_memory_format = weight.suggest_memory_format();
398
+
399
+ bool can_use_mkldnn_channels_last_2d =
400
+ (input_memory_format == at::MemoryFormat::ChannelsLast) ||
401
+ (weight_memory_format == at::MemoryFormat::ChannelsLast);
402
+
403
+ bool can_use_mkldnn_channels_last_3d =
404
+ (input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
405
+ (weight_memory_format == at::MemoryFormat::ChannelsLast3d);
406
+
407
+ return can_use_mkldnn_channels_last_2d || can_use_mkldnn_channels_last_3d;
408
+ }
409
+
410
+ inline bool thnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
411
+
412
+ auto input_memory_format = input.suggest_memory_format();
413
+ auto weight_memory_format = weight.suggest_memory_format();
414
+
415
+ bool can_use_thnn_channels_last_2d = input.device().is_cpu() && (
416
+ (input_memory_format == at::MemoryFormat::ChannelsLast) || (
417
+ weight_memory_format == at::MemoryFormat::ChannelsLast));
418
+
419
+ return can_use_thnn_channels_last_2d;
420
+ }
421
+
422
+ inline bool xpu_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
423
+
424
+ // check layout only for xpu tensor.
425
+ if (!input.is_xpu() || !weight.is_xpu()) {
426
+ return false;
427
+ }
428
+ if (!input.defined() || input.is_sparse()) {
429
+ // suggest channels_first
430
+ return false;
431
+ }
432
+
433
+ auto is_channel_last = [](const at::Tensor& t) {
434
+ auto fmt = t.suggest_memory_format();
435
+ return fmt == at::MemoryFormat::ChannelsLast || fmt == at::MemoryFormat::ChannelsLast3d;
436
+ };
437
+ return is_channel_last(input) || is_channel_last(weight);
438
+ }
439
+
440
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/ConvolutionMM3d.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+
3
+ namespace at::native {
4
+
5
+ std::tuple<Tensor, Tensor, Tensor> slow_conv3d_backward_cpu(
6
+ const Tensor& grad_output,
7
+ const Tensor& self,
8
+ const Tensor& weight,
9
+ IntArrayRef kernel_size,
10
+ IntArrayRef stride,
11
+ IntArrayRef padding,
12
+ std::array<bool, 3> output_mask);
13
+
14
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Copy.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+
7
+ class Tensor;
8
+ struct TensorIterator;
9
+ class TensorBase;
10
+
11
+ namespace native {
12
+
13
+ using copy_fn = void (*)(TensorIterator&, bool non_blocking);
14
+
15
+ DECLARE_DISPATCH(copy_fn, copy_stub)
16
+
17
+ TORCH_API void copy_ignoring_overlaps(const TensorBase &dst, const TensorBase &src);
18
+
19
+ } // namespace native
20
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Cross.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d);
11
+
12
+ DECLARE_DISPATCH(cross_fn, cross_stub)
13
+
14
+ }} // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <vector>
5
+
6
+ #include <ATen/div_rtn.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <c10/util/irange.h>
9
+
10
+ #define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \
11
+ TORCH_CHECK( \
12
+ T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \
13
+ "Need " #T " of dimension ", \
14
+ DIM, \
15
+ " and " #T ".size[", \
16
+ DIM_SIZE, \
17
+ "] == ", \
18
+ SIZE, \
19
+ " but got input to be of shape ", \
20
+ T.sizes())
21
+
22
+ namespace at::native::internal {
23
+ namespace {
24
+ inline bool all_positive(IntArrayRef& arr) {
25
+ return std::all_of(
26
+ arr.begin(), arr.end(), [](int64_t item) { return item > 0; });
27
+ }
28
+
29
+ inline bool all_nonnegative(std::vector<int64_t>& arr) {
30
+ return std::all_of(
31
+ arr.begin(), arr.end(), [](int64_t item) { return item >= 0; });
32
+ }
33
+
34
+ } // namespace
35
+
36
+ // calculate the rear part of output tensor sizes
37
+ template <int64_t dim>
38
+ std::vector<int64_t> get_output_size(
39
+ const Tensor& input,
40
+ IntArrayRef kernel_size,
41
+ IntArrayRef stride_size,
42
+ IntArrayRef pad_size,
43
+ IntArrayRef dilation_size) {
44
+ std::vector<int64_t> sizes;
45
+ for (const auto index : c10::irange(dim)) {
46
+ sizes.push_back(
47
+ div_rtn<int64_t>(
48
+ input.size(index + input.dim() - dim) + 2 * pad_size[index] -
49
+ (dilation_size[index] * (kernel_size[index] - 1) + 1),
50
+ stride_size[index]) +
51
+ 1);
52
+ }
53
+ return sizes;
54
+ }
55
+
56
+ // calculate the sizes of output tensor
57
+ template <int64_t dim>
58
+ std::vector<int64_t> get_output_size(
59
+ const Tensor& input,
60
+ const Tensor& weight,
61
+ IntArrayRef kernel_size,
62
+ IntArrayRef stride_size,
63
+ IntArrayRef pad_size,
64
+ IntArrayRef dilation_size) {
65
+ auto output_size = get_output_size<dim>(
66
+ input, kernel_size, stride_size, pad_size, dilation_size);
67
+ output_size.insert(output_size.begin(), weight.size(0));
68
+ if (input.dim() == dim + 2) {
69
+ output_size.insert(output_size.begin(), input.size(0));
70
+ }
71
+ return output_size;
72
+ }
73
+ /*
74
+ slow_conv_dilated_shape_check - check user-input to dilated convolution
75
+ forward and backward functions.
76
+ */
77
+ template <int64_t dim>
78
+ void slow_conv_dilated_shape_check(
79
+ const Tensor& input,
80
+ const Tensor& weight,
81
+ const Tensor& bias,
82
+ const Tensor& grad_output,
83
+ IntArrayRef kernel_size,
84
+ IntArrayRef stride_size,
85
+ IntArrayRef pad_size,
86
+ IntArrayRef dilation_size) {
87
+ /*
88
+ When the following tensors are defined:
89
+
90
+ bias, grad_weight, grad_output
91
+
92
+ then these are assumed to be contiguous without checking
93
+ because of these tensors are made contiguous by calling
94
+ .contiguous() method or by resizing of zero-sized tensors in
95
+ forward/backward functions.
96
+
97
+ When grad_weight is defined then it is assumed without
98
+ checking to have the same shape as weight, see backward
99
+ functions.
100
+ */
101
+ // Check size arguments
102
+ TORCH_CHECK(
103
+ kernel_size.size() == dim,
104
+ "kernel sizes length should be ",
105
+ dim,
106
+ ", but got ",
107
+ kernel_size.size());
108
+ TORCH_CHECK(
109
+ stride_size.size() == dim,
110
+ "strides length should be ",
111
+ dim,
112
+ ", but got ",
113
+ stride_size.size());
114
+ TORCH_CHECK(
115
+ dilation_size.size() == dim,
116
+ "dilations length should be ",
117
+ dim,
118
+ ", but got ",
119
+ dilation_size.size());
120
+ TORCH_CHECK(
121
+ pad_size.size() == dim,
122
+ "pads length should be ",
123
+ dim,
124
+ ", but got ",
125
+ pad_size.size());
126
+
127
+ TORCH_CHECK(
128
+ all_positive(kernel_size),
129
+ "kernel size should be greater than zero, but got ",
130
+ kernel_size);
131
+ TORCH_CHECK(
132
+ all_positive(stride_size),
133
+ "stride should be greater than zero, but got ",
134
+ stride_size);
135
+ TORCH_CHECK(
136
+ all_positive(dilation_size),
137
+ "dilation should be greater than zero, but got ",
138
+ dilation_size);
139
+
140
+ // check input
141
+ TORCH_CHECK(input.defined(), "input must be defined");
142
+ bool is_batch = input.dim() == dim + 2;
143
+ int64_t n = (is_batch ? 2 : 1);
144
+ int64_t ndim = n + dim;
145
+ if (!is_batch) {
146
+ // input dim has to be dim + 1 if not batched
147
+ TORCH_CHECK(
148
+ input.dim() == dim + 1,
149
+ "input must be 4D or 5D tensor but got ",
150
+ input.dim(),
151
+ "D tensor");
152
+ }
153
+
154
+ // check output sizes
155
+ auto output_size = get_output_size<dim>(
156
+ input, kernel_size, stride_size, pad_size, dilation_size);
157
+
158
+ TORCH_CHECK(
159
+ all_nonnegative(output_size),
160
+ "calculated output size ",
161
+ output_size,
162
+ " is too small (all sizes must be non-negative)");
163
+
164
+ // check weight
165
+ TORCH_CHECK(weight.defined(), "weight must be defined");
166
+ TORCH_CHECK(
167
+ weight.dim() == dim + 2,
168
+ "weight must be ",
169
+ dim + 2,
170
+ "D tensor but got ",
171
+ weight.dim(),
172
+ "D tensor dim=",
173
+ dim);
174
+ TORCH_CHECK(
175
+ weight.sizes().slice(2) == kernel_size,
176
+ "weight[2:] shape ",
177
+ weight.sizes().slice(2),
178
+ " must be equal to kernel_size ",
179
+ kernel_size);
180
+
181
+ TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1));
182
+
183
+ // check bias when present
184
+ if (bias.defined()) {
185
+ TORCH_CHECK(
186
+ bias.dim() == 1,
187
+ "bias must be 1D tensor but got ",
188
+ bias.dim(),
189
+ "D tensor");
190
+ TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0));
191
+ }
192
+
193
+ // check grad_output when present
194
+ if (grad_output.defined()) {
195
+ TORCH_CHECK(
196
+ grad_output.dim() == ndim,
197
+ "grad_output must be ",
198
+ ndim,
199
+ "D tensor but got ",
200
+ grad_output.dim(),
201
+ "D tensor");
202
+ if (is_batch) {
203
+ TORCH_CHECK(
204
+ grad_output.size(0) == input.size(0),
205
+ "grad_output.size(0)=",
206
+ grad_output.size(0),
207
+ " must be input.size(0)=",
208
+ input.size(0));
209
+ }
210
+ TORCH_CHECK(
211
+ grad_output.size(n - 1) == weight.size(0),
212
+ "grad_output.size(",
213
+ n - 1,
214
+ ")=",
215
+ grad_output.size(n - 1),
216
+ " must be weight.size(0)=",
217
+ weight.size(0));
218
+ TORCH_CHECK(
219
+ grad_output.sizes().slice(n) == output_size,
220
+ "grad_output[",
221
+ n,
222
+ ":] shape",
223
+ grad_output.sizes().slice(n),
224
+ " must be equal to output size ",
225
+ output_size);
226
+ }
227
+ }
228
+
229
+ } // namespace at::native::internal
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DispatchStub.h ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/macros/Macros.h>
5
+
6
+ #include <atomic>
7
+ #include <utility>
8
+ #include <variant>
9
+
10
+ // Implements instruction set specific function dispatch.
11
+ //
12
+ // Kernels that may make use of specialized instruction sets (e.g. AVX2) are
13
+ // compiled multiple times with different compiler flags (e.g. -mavx2). A
14
+ // DispatchStub contains a table of function pointers for a kernel. At runtime,
15
+ // the fastest available kernel is chosen based on the features reported by
16
+ // cpuinfo.
17
+ //
18
+ // Example:
19
+ //
20
+ // In native/MyKernel.h:
21
+ // using fn_type = void(*)(const Tensor& x);
22
+ // DECLARE_DISPATCH(fn_type, stub)
23
+ //
24
+ // In native/MyKernel.cpp
25
+ // DEFINE_DISPATCH(stub);
26
+ //
27
+ // In native/cpu/MyKernel.cpp:
28
+ // namespace {
29
+ // // use anonymous namespace so that different cpu versions won't conflict
30
+ // void kernel(const Tensor& x) { ... }
31
+ // }
32
+ // REGISTER_DISPATCH(stub, &kernel);
33
+ //
34
+ // To call:
35
+ // stub(kCPU, tensor);
36
+ //
37
+ // TODO: CPU instruction set selection should be folded into whatever
38
+ // the main dispatch mechanism is.
39
+ //
40
+ // Supported device types for registration:
41
+ // - CPU: Central Processing Unit
42
+ // - CUDA: NVIDIA GPUs
43
+ // - HIP: AMD GPUs
44
+ // - MPS: Apple Silicon GPUs (Metal Performance Shaders)
45
+ // - MTIA: Meta Training and Inference Devices
46
+ // - XPU: Intel GPUs
47
+ // - PrivateUse1: Reserved for private/custom device types
48
+ //
49
+ // If you want to update the list of supported devices, add a new dispatch_ptr
50
+ // member in DispatchStubImpl.h and update the get_call_ptr switch.
51
+ // As well you will need to update the inlined list in 'is_device_supported`
52
+ //
53
+ //
54
+ // ignore warnings about DispatchStub::DEFAULT, AVX, AVX2 defined elsewhere
55
+ C10_CLANG_DIAGNOSTIC_PUSH()
56
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wundefined-var-template")
57
+
58
+ namespace at::native {
59
+
60
+ enum class CPUCapability {
61
+ DEFAULT = 0,
62
+ #if defined(HAVE_VSX_CPU_DEFINITION)
63
+ VSX = 1,
64
+ #elif defined(HAVE_ZVECTOR_CPU_DEFINITION)
65
+ ZVECTOR = 1,
66
+ #elif defined(HAVE_SVE_CPU_DEFINITION)
67
+ SVE256 = 1,
68
+ #else
69
+ AVX2 = 1,
70
+ AVX512 = 2,
71
+ #endif
72
+ NUM_OPTIONS
73
+ };
74
+
75
+ // Enum for error types
76
+ enum class ErrorType {
77
+ MissingDeviceKernel,
78
+ DeviceNotSupported
79
+ };
80
+
81
+ // Alias for the return type using std::variant
82
+ using DispatchResult = std::variant<void*, ErrorType>;
83
+
84
+ CPUCapability get_cpu_capability();
85
+
86
+ template <typename FnPtr, typename T>
87
+ struct DispatchStub;
88
+
89
+ /**
90
+ * The sole purpose of this class is to outline methods that don't need to be
91
+ * specialized or otherwise inlined and duplicated (by the compiler due to
92
+ * template expansion), since it causes size bloat if there are a significant
93
+ * number of specialization of the DispatchStub<> class.
94
+ */
95
+ struct TORCH_API DispatchStubImpl {
96
+
97
+ // The DispatchStubImpl::try_get_call_ptr() method is used to get the call
98
+ // pointer for a given device type. If the call pointer is not found,
99
+ // DispatchStubImpl::try_get_call_ptr() returns an ErrorType.
100
+ // The main difference between try_get_call_ptr() and get_call_ptr() is that
101
+ // try_get_call_ptr() will return the ErrorType and not raise an exception.
102
+ DispatchResult try_get_call_ptr(
103
+ c10::DeviceType device_type
104
+ , void *DEFAULT
105
+ #ifdef HAVE_AVX512_CPU_DEFINITION
106
+ , void *AVX512
107
+ #endif
108
+ #ifdef HAVE_AVX2_CPU_DEFINITION
109
+ , void *AVX2
110
+ #endif
111
+ #ifdef HAVE_VSX_CPU_DEFINITION
112
+ , void *VSX
113
+ #endif
114
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
115
+ , void *ZVECTOR
116
+ #endif
117
+ #ifdef HAVE_SVE256_CPU_DEFINITION
118
+ , void *SVE256
119
+ #endif
120
+ );
121
+
122
+ // Analogous to try_get_call_ptr(), but it will return the ErrorType and not
123
+ // raise an exception.
124
+ DispatchResult try_choose_cpu_impl(
125
+ void *DEFAULT
126
+ #ifdef HAVE_AVX512_CPU_DEFINITION
127
+ , void *AVX512
128
+ #endif
129
+ #ifdef HAVE_AVX2_CPU_DEFINITION
130
+ , void *AVX2
131
+ #endif
132
+ #ifdef HAVE_VSX_CPU_DEFINITION
133
+ , void *VSX
134
+ #endif
135
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
136
+ , void *ZVECTOR
137
+ #endif
138
+ #ifdef HAVE_SVE256_CPU_DEFINITION
139
+ , void *SVE256
140
+ #endif
141
+ );
142
+
143
+
144
+ void* get_call_ptr(
145
+ c10::DeviceType device_type
146
+ , void *DEFAULT
147
+ #ifdef HAVE_AVX512_CPU_DEFINITION
148
+ , void *AVX512
149
+ #endif
150
+ #ifdef HAVE_AVX2_CPU_DEFINITION
151
+ , void *AVX2
152
+ #endif
153
+ #ifdef HAVE_VSX_CPU_DEFINITION
154
+ , void *VSX
155
+ #endif
156
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
157
+ , void *ZVECTOR
158
+ #endif
159
+ #ifdef HAVE_SVE256_CPU_DEFINITION
160
+ , void *SVE256
161
+ #endif
162
+ );
163
+
164
+ /**
165
+ * The CPU Dispatch actual method is chosen in decreasing order of preference by
166
+ * DispatchStubImpl::choose_cpu_impl() in case none is found by
167
+ * DispatchStubImpl::get_call_ptr() in cpu_dispatch_ptr.
168
+ */
169
+ void* choose_cpu_impl(
170
+ void *DEFAULT
171
+ #ifdef HAVE_AVX512_CPU_DEFINITION
172
+ , void *AVX512
173
+ #endif
174
+ #ifdef HAVE_AVX2_CPU_DEFINITION
175
+ , void *AVX2
176
+ #endif
177
+ #ifdef HAVE_VSX_CPU_DEFINITION
178
+ , void *VSX
179
+ #endif
180
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
181
+ , void *ZVECTOR
182
+ #endif
183
+ #ifdef HAVE_SVE256_CPU_DEFINITION
184
+ , void *SVE256
185
+ #endif
186
+ );
187
+
188
+ // Fixing dispatch error in Windows debug builds.
189
+ // See https://github.com/pytorch/pytorch/issues/22681 for more details.
190
+ #if defined(_MSC_VER) && defined(_DEBUG)
191
+ std::atomic<void*> cpu_dispatch_ptr;
192
+ void* cuda_dispatch_ptr;
193
+ void* hip_dispatch_ptr;
194
+ void* mps_dispatch_ptr;
195
+ void* mtia_dispatch_ptr;
196
+ #if defined(USE_XPU)
197
+ void* xpu_dispatch_ptr;
198
+ #endif
199
+ void* privateuse1_dispatch_ptr;
200
+ #else
201
+ std::atomic<void*> cpu_dispatch_ptr{nullptr};
202
+ void* cuda_dispatch_ptr = nullptr;
203
+ void* hip_dispatch_ptr = nullptr;
204
+ void* mps_dispatch_ptr = nullptr;
205
+ void* mtia_dispatch_ptr = nullptr;
206
+ #if defined(USE_XPU)
207
+ void* xpu_dispatch_ptr = nullptr;
208
+ #endif
209
+ void* privateuse1_dispatch_ptr = nullptr;
210
+ #endif
211
+ };
212
+
213
+ template <typename rT, typename T, typename... Args>
214
+ struct DispatchStub<rT (*)(Args...), T> {
215
+ using FnPtr = rT (*) (Args...);
216
+
217
+ DispatchStub() = default;
218
+ DispatchStub(const DispatchStub&) = delete;
219
+ DispatchStub& operator=(const DispatchStub&) = delete;
220
+
221
+ private:
222
+ FnPtr get_call_ptr(const c10::DeviceType device_type) {
223
+ return reinterpret_cast<FnPtr>(
224
+ impl.get_call_ptr(device_type
225
+ , reinterpret_cast<void*>(DEFAULT)
226
+ #ifdef HAVE_AVX512_CPU_DEFINITION
227
+ , reinterpret_cast<void*>(AVX512)
228
+ #endif
229
+ #ifdef HAVE_AVX2_CPU_DEFINITION
230
+ , reinterpret_cast<void*>(AVX2)
231
+ #endif
232
+ #ifdef HAVE_VSX_CPU_DEFINITION
233
+ , reinterpret_cast<void*>(VSX)
234
+ #endif
235
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
236
+ , reinterpret_cast<void*>(ZVECTOR)
237
+ #endif
238
+ #ifdef HAVE_SVE256_CPU_DEFINITION
239
+ , reinterpret_cast<void*>(SVE256)
240
+ #endif
241
+ )
242
+ );
243
+ }
244
+
245
+ public:
246
+ template <typename... ArgTypes>
247
+ rT operator()(c10::DeviceType device_type, ArgTypes&&... args) {
248
+ FnPtr call_ptr = get_call_ptr(device_type);
249
+ return (*call_ptr)(std::forward<ArgTypes>(args)...);
250
+ }
251
+
252
+ void set_cuda_dispatch_ptr(FnPtr fn_ptr) {
253
+ impl.cuda_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
254
+ }
255
+
256
+ #if defined(USE_XPU)
257
+ void set_xpu_dispatch_ptr(FnPtr fn_ptr){
258
+ impl.xpu_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
259
+ }
260
+ #endif
261
+
262
+ void set_hip_dispatch_ptr(FnPtr fn_ptr) {
263
+ impl.hip_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
264
+ }
265
+
266
+ void set_mps_dispatch_ptr(FnPtr fn_ptr) {
267
+ impl.mps_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
268
+ }
269
+
270
+ void set_mtia_dispatch_ptr(FnPtr fn_ptr) {
271
+ impl.mtia_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
272
+ }
273
+
274
+ void set_privateuse1_dispatch_ptr(FnPtr fn_ptr) {
275
+ impl.privateuse1_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
276
+ }
277
+
278
+ // Returns true if the dispatcher has a kernel registered for this device
279
+ // type.
280
+ bool is_device_supported(const c10::DeviceType device_type) {
281
+ auto result = impl.try_get_call_ptr(device_type
282
+ , reinterpret_cast<void*>(DEFAULT)
283
+ #ifdef HAVE_AVX512_CPU_DEFINITION
284
+ , reinterpret_cast<void*>(AVX512)
285
+ #endif
286
+ #ifdef HAVE_AVX2_CPU_DEFINITION
287
+ , reinterpret_cast<void*>(AVX2)
288
+ #endif
289
+ #ifdef HAVE_VSX_CPU_DEFINITION
290
+ , reinterpret_cast<void*>(VSX)
291
+ #endif
292
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
293
+ , reinterpret_cast<void*>(ZVECTOR)
294
+ #endif
295
+ #ifdef HAVE_SVE256_CPU_DEFINITION
296
+ , reinterpret_cast<void*>(SVE256)
297
+ #endif
298
+ );
299
+ if (std::holds_alternative<ErrorType>(result)){
300
+ return false;
301
+ }
302
+ return true;
303
+ }
304
+
305
+ static TORCH_API FnPtr DEFAULT;
306
+ #ifdef HAVE_AVX512_CPU_DEFINITION
307
+ static TORCH_API FnPtr AVX512;
308
+ #endif
309
+ #ifdef HAVE_AVX2_CPU_DEFINITION
310
+ static TORCH_API FnPtr AVX2;
311
+ #endif
312
+ #ifdef HAVE_VSX_CPU_DEFINITION
313
+ static TORCH_API FnPtr VSX;
314
+ #endif
315
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
316
+ static TORCH_API FnPtr ZVECTOR;
317
+ #endif
318
+ #ifdef HAVE_SVE256_CPU_DEFINITION
319
+ static TORCH_API FnPtr SVE256;
320
+ #endif
321
+ private:
322
+ DispatchStubImpl impl;
323
+ };
324
+
325
+ namespace {
326
+ template <typename DispatchStub>
327
+ struct RegisterCUDADispatch {
328
+ RegisterCUDADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
329
+ stub.set_cuda_dispatch_ptr(value);
330
+ }
331
+ };
332
+
333
+ template <typename DispatchStub>
334
+ struct RegisterXPUDispatch {
335
+ RegisterXPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){
336
+ stub.set_xpu_dispatch_ptr(value);
337
+ }
338
+ };
339
+
340
+ template <typename DispatchStub>
341
+ struct RegisterMPSDispatch {
342
+ RegisterMPSDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
343
+ stub.set_mps_dispatch_ptr(value);
344
+ }
345
+ };
346
+
347
+ template <typename DispatchStub>
348
+ struct RegisterHIPDispatch {
349
+ RegisterHIPDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
350
+ // TODO: make this point at hip_dispatch_ptr
351
+ stub.set_cuda_dispatch_ptr(value);
352
+ }
353
+ };
354
+
355
+ template <typename DispatchStub>
356
+ struct RegisterMTIADispatch {
357
+ RegisterMTIADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
358
+ stub.set_mtia_dispatch_ptr(value);
359
+ }
360
+ };
361
+
362
+ template <typename DispatchStub>
363
+ struct RegisterPRIVATEUSE1Dispatch {
364
+ RegisterPRIVATEUSE1Dispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
365
+ stub.set_privateuse1_dispatch_ptr(value);
366
+ }
367
+ };
368
+
369
+ } // anonymous namespace
370
+ // Compiler will complain if you put things like std::tuple<Tensor, Tensor> in
371
+ // the `fn` argument of DECLARE_DISPATCH. Some possible workarounds, e.g.,
372
+ // adding parentheses and using helper struct to get rid of the parentheses, do
373
+ // not work with MSVC. So do a `using`-declaration if you need to pass in such
374
+ // `fn`, e.g., grid_sampler_2d_backward_cpu_kernel in GridSampleKernel.h.
375
+ #define DECLARE_DISPATCH(fn, name) \
376
+ struct name##_DECLARE_DISPATCH_type : DispatchStub<fn, name##_DECLARE_DISPATCH_type> { \
377
+ name##_DECLARE_DISPATCH_type() = default; \
378
+ name##_DECLARE_DISPATCH_type(const name##_DECLARE_DISPATCH_type&) = delete; \
379
+ name##_DECLARE_DISPATCH_type& operator=(const name##_DECLARE_DISPATCH_type&) = delete; \
380
+ name##_DECLARE_DISPATCH_type(name##_DECLARE_DISPATCH_type&&) = delete; \
381
+ name##_DECLARE_DISPATCH_type& operator=(name##_DECLARE_DISPATCH_type&&) = delete; \
382
+ ~name##_DECLARE_DISPATCH_type() = default; \
383
+ }; \
384
+ extern TORCH_API struct name##_DECLARE_DISPATCH_type name;
385
+
386
+ #define DEFINE_DISPATCH(name) struct name##_DECLARE_DISPATCH_type name
387
+
388
+ #define REGISTER_ARCH_DISPATCH(name, arch, fn) \
389
+ template <> name##_DECLARE_DISPATCH_type::FnPtr TORCH_API DispatchStub<name##_DECLARE_DISPATCH_type::FnPtr, struct name##_DECLARE_DISPATCH_type>::arch = fn;
390
+
391
+ #ifdef HAVE_AVX512_CPU_DEFINITION
392
+ #define REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX512, fn)
393
+ #else
394
+ #define REGISTER_AVX512_DISPATCH(name, fn)
395
+ #endif
396
+
397
+ #ifdef HAVE_AVX2_CPU_DEFINITION
398
+ #define REGISTER_AVX2_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX2, fn)
399
+ #else
400
+ #define REGISTER_AVX2_DISPATCH(name, fn)
401
+ #endif
402
+
403
+ #ifdef HAVE_VSX_CPU_DEFINITION
404
+ #define REGISTER_VSX_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, VSX, fn)
405
+ #else
406
+ #define REGISTER_VSX_DISPATCH(name, fn)
407
+ #endif
408
+
409
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
410
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, ZVECTOR, fn)
411
+ #else
412
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn)
413
+ #endif
414
+
415
+ #ifdef HAVE_SVE256_CPU_DEFINITION
416
+ #define REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, SVE256, fn)
417
+ #else
418
+ #define REGISTER_SVE256_DISPATCH(name, fn)
419
+ #endif
420
+
421
+ // Macro to register the same kernel for all CPU arch types. This is useful
422
+ // if a kernel does not benefit from being recompiled across different arch types.
423
+ #define REGISTER_ALL_CPU_DISPATCH(name, fn) \
424
+ REGISTER_ARCH_DISPATCH(name, DEFAULT, fn) \
425
+ REGISTER_AVX512_DISPATCH(name, fn) \
426
+ REGISTER_AVX2_DISPATCH(name, fn) \
427
+ REGISTER_VSX_DISPATCH(name, fn) \
428
+ REGISTER_ZVECTOR_DISPATCH(name, fn) \
429
+ REGISTER_SVE256_DISPATCH(name, fn)
430
+
431
+ #define REGISTER_NO_CPU_DISPATCH(name) \
432
+ REGISTER_ALL_CPU_DISPATCH(name, nullptr)
433
+
434
+ #define REGISTER_CUDA_DISPATCH(name, fn) \
435
+ static RegisterCUDADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
436
+
437
+ #define REGISTER_XPU_DISPATCH(name, fn) \
438
+ static RegisterXPUDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
439
+
440
+ #define REGISTER_HIP_DISPATCH(name, fn) \
441
+ static RegisterHIPDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
442
+
443
+ #define REGISTER_MPS_DISPATCH(name, fn) \
444
+ static RegisterMPSDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
445
+
446
+ #define REGISTER_MTIA_DISPATCH(name, fn) \
447
+ static RegisterMTIADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
448
+
449
+ #define REGISTER_PRIVATEUSE1_DISPATCH(name, fn) \
450
+ static RegisterPRIVATEUSE1Dispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
451
+
452
+ // NB: This macro must be used in an actual 'cu' file; if you try using
453
+ // it from a 'cpp' file it will not work!
454
+ #if defined(__CUDACC__)
455
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
456
+ #elif defined(__HIPCC__)
457
+ // TODO: cut this over to HIP dispatch once we stop pretending that CUDA
458
+ // is HIP in the PyTorch HIPify build.
459
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
460
+ // #define REGISTER_DISPATCH(name, fn) REGISTER_HIP_DISPATCH(name, fn)
461
+ #elif defined(__OBJC__) && defined(USE_MPS)
462
+ // NB: this macro must be used from a 'mm' file in order to dispatch a MPS kernel
463
+ #define REGISTER_DISPATCH(name, fn) REGISTER_MPS_DISPATCH(name, fn)
464
+ #elif defined(CPU_CAPABILITY)
465
+ // REGISTER_DISPATCH now dispatches an AVX512 kernel to nullptr but registers other dispatches.
466
+ // ALSO_REGISTER_AVX512_DISPATCH should be used for ensuring AVX512 dispatch, among others.
467
+ // ALSO_REGISTER_SVE256_DISPATCH should be used for ensuring SVE256 dispatch, among others.
468
+ #ifdef CPU_CAPABILITY_AVX512
469
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, ((void*)(fn) ? nullptr : nullptr))
470
+ #else
471
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
472
+ #endif
473
+ #define ALSO_REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
474
+ #define ALSO_REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
475
+ #endif
476
+ } // namespace at::native
477
+
478
+ C10_CLANG_DIAGNOSTIC_POP()
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Distance.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+
8
+ namespace native {
9
+
10
+ using pdist_forward_fn = void(*)(Tensor&, const Tensor&, const double p);
11
+ using pdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
12
+ using cdist_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p);
13
+ using cdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
14
+
15
+ DECLARE_DISPATCH(pdist_forward_fn, pdist_forward_stub)
16
+ DECLARE_DISPATCH(pdist_backward_fn, pdist_backward_stub)
17
+ DECLARE_DISPATCH(cdist_fn, cdist_stub)
18
+ DECLARE_DISPATCH(cdist_backward_fn, cdist_backward_stub)
19
+
20
+ }} // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/DistributionTemplates.h ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/Dispatch_v2.h>
6
+ #include <ATen/Generator.h>
7
+ #include <ATen/ExpandUtils.h>
8
+ #include <ATen/Tensor.h>
9
+ #include <ATen/MemoryOverlap.h>
10
+ #include <ATen/NamedTensorUtils.h>
11
+ #include <ATen/native/Resize.h>
12
+ #include <ATen/native/TensorIterator.h>
13
+ #include <cmath>
14
+ #include <limits>
15
+ #include <optional>
16
+
17
+ #ifndef AT_PER_OPERATOR_HEADERS
18
+ #include <ATen/Functions.h>
19
+ #else
20
+ #include <ATen/ops/empty_like.h>
21
+ #include <ATen/ops/empty.h>
22
+ #include <ATen/ops/full.h>
23
+ #include <ATen/ops/view_as_real.h>
24
+ #endif
25
+
26
+ namespace at::native::templates {
27
+
28
+ // ==================================================== Random ========================================================
29
+
30
+ // The purpose of `update_from` and `update_to` is to find the closest valid int64_t number that can be used as actual `from`.
31
+ // The current implementation of `random_` uses uint64_t arithmetics and casts the result to the target dtype(scalar_t).
32
+ // This casting can result in generating numbers that happen to be greater or equal to `to` value. For instance:
33
+ //
34
+ // auto actual = torch::empty({3, 3}, torch::half);
35
+ // actual.random_(0, 65504);
36
+ //
37
+ // If random's uint64_t arithmetics produces 65503 as a random value after casting to torch::half it becomes 65504
38
+ // and violates the requirement that random value must be less than `to`. To resolve this issue `update_from` and `update_to`
39
+ // moves `from` to the right and `to` to the left to the next closest value that won't go outside [from, to) after casting to
40
+ // the target dtype. For `to` = 65504 it moves left for (1 << (log2(to) - 11 + 1)) = 32 and becomes 65472, which is previous
41
+ // available number for torch::half dtype.
42
+ template<typename scalar_t>
43
+ int64_t update_from(int64_t from) {
44
+ static_assert(
45
+ std::is_floating_point_v<scalar_t> ||
46
+ std::is_same_v<scalar_t, at::Half> ||
47
+ std::is_same_v<scalar_t, at::BFloat16>, "scalar_t must be floating-point type");
48
+ const auto from_plus_1 = static_cast<int64_t>(static_cast<scalar_t>(from + 1));
49
+ if (from_plus_1 < from) {
50
+ int64_t from_ = std::abs(from + 1);
51
+ int n = 0;
52
+ while (from_ >>= 1) ++n;
53
+ // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
54
+ from = from_plus_1 + (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
55
+ }
56
+ return from;
57
+ }
58
+
59
+ template<typename scalar_t>
60
+ int64_t update_to(int64_t to) {
61
+ static_assert(
62
+ std::is_floating_point_v<scalar_t> ||
63
+ std::is_same_v<scalar_t, at::Half> ||
64
+ std::is_same_v<scalar_t, at::BFloat16>, "scalar_t must be floating-point type");
65
+ const auto to_minus_1 = static_cast<int64_t>(static_cast<scalar_t>(to - 1));
66
+ if (to_minus_1 >= to) {
67
+ int64_t to_ = std::abs(to - 1);
68
+ int n = 0;
69
+ while (to_ >>= 1) ++n;
70
+ // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
71
+ to = to_minus_1 - (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
72
+ }
73
+ return to;
74
+ }
75
+
76
+ // Return earlier for not invoking kernel.
77
+ // See https://github.com/pytorch/pytorch/issues/103418 for more details
78
+ #define CHECK_EMPTY_AND_RETURN(tensor) \
79
+ if (tensor.numel() == 0) { \
80
+ return tensor; \
81
+ }
82
+
83
+ template<template<typename> class random_kernel, typename RNG>
84
+ at::Tensor& random_impl(at::Tensor& self, std::optional<Generator> generator) {
85
+ CHECK_EMPTY_AND_RETURN(self);
86
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
87
+ random_kernel<RNG>()(iter, generator);
88
+ return self;
89
+ }
90
+
91
+ #define CHECK_OUT_OF_BOUNDS(var, name, min, max, dtype) \
92
+ TORCH_CHECK(var >= min && var <= max, name , " is out of bounds for ", dtype); \
93
+
94
+ #define WARN_OUT_OF_BOUNDS(var, name, digits, dtype) \
95
+ if (var < -(1LL << digits) || var > (1LL << digits)) { \
96
+ TORCH_WARN(name , " is out of bounds [-(2^", digits, "), 2^", digits, "]. ", \
97
+ "Due to precision limitations ", dtype, " can support discrete uniform distribution only within this range. ", \
98
+ "This warning will become an error in version 1.7 release, please fix the code in advance"); \
99
+ }
100
+
101
+ inline void check_from_to_in_range(int64_t from, int64_t to_inc, caffe2::TypeMeta dtype) {
102
+ const auto scalar_type = typeMetaToScalarType(dtype);
103
+ if (isFloatingType(scalar_type)) {
104
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, scalar_type, "check_random_fp_bounds", [&] {
105
+ const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
106
+ const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
107
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
108
+ CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
109
+
110
+ constexpr auto digits = std::numeric_limits<scalar_t>::digits;
111
+ WARN_OUT_OF_BOUNDS(from, "from", digits, dtype);
112
+ WARN_OUT_OF_BOUNDS(to_inc, "to - 1", digits, dtype);
113
+ });
114
+ } else if (scalar_type == kUInt64) {
115
+ // When you do a comparison between int64_t and uint64_t, the usual
116
+ // arithmetic conversions say that the int64_t value is promoted to
117
+ // unsigned. But this conversion wraps around: if I had -1 as my int64_t,
118
+ // then it will promote to 0xFFFFFFFFFFFFFFFF in uint64_t. This is never
119
+ // the right thing to do.
120
+ CHECK_OUT_OF_BOUNDS(from, "from", 0, INT64_MAX, dtype);
121
+ CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", 0, INT64_MAX, dtype);
122
+ } else if (isIntegralType(scalar_type, /*includeBool=*/true)) {
123
+ AT_DISPATCH_V2(scalar_type, "check_random_integral_bounds", AT_WRAP([&]() {
124
+ const auto min = static_cast<int64_t>(std::numeric_limits<scalar_t>::lowest());
125
+ const auto max = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
126
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
127
+ CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
128
+ }), AT_EXPAND(AT_INTEGRAL_TYPES), kUInt16, kUInt32, kBool);
129
+ } else {
130
+ TORCH_CHECK(false, "check_random_bounds handles only integral, floating-point and boolean types");
131
+ }
132
+ }
133
+
134
+ template<template<typename> class random_from_to_kernel, typename RNG>
135
+ at::Tensor& random_from_to_impl(at::Tensor& self, int64_t from, std::optional<int64_t> to_opt, std::optional<Generator> generator) {
136
+ uint64_t range = 0;
137
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
138
+ if (to_opt.has_value()) {
139
+ // [from, to)
140
+ int64_t to = *to_opt;
141
+ TORCH_CHECK(from < to, "random_ expects 'from' to be less than 'to', but got from=", from, " >= to=", to);
142
+ if (isFloatingType(iter.dtype())) {
143
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_update_from_to", [&] {
144
+ from = update_from<scalar_t>(from);
145
+ to = update_to<scalar_t>(to);
146
+ TORCH_CHECK(from < to, "random_ expects 'from' casted to dtype to be less than 'to' casted to dtype, but got from=", from, " >= to=", to);
147
+ });
148
+ }
149
+ check_from_to_in_range(from, to - 1, self.dtype());
150
+ CHECK_EMPTY_AND_RETURN(self);
151
+ range = static_cast<uint64_t>(to) - static_cast<uint64_t>(from);
152
+ random_from_to_kernel<RNG>()(iter, range, from, generator);
153
+ } else if (from != std::numeric_limits<int64_t>::lowest()) {
154
+ // [from, std::numeric_limits<int64_t>::max()]
155
+ int64_t to_inc = 0;
156
+ if (isFloatingType(iter.dtype())) {
157
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_from_to_range_calc", [&] {
158
+ constexpr int64_t scalar_t_max = static_cast<int64_t>(1) << std::numeric_limits<scalar_t>::digits;
159
+ to_inc = scalar_t_max > std::numeric_limits<int64_t>::max() ? std::numeric_limits<int64_t>::max() : static_cast<int64_t>(scalar_t_max);
160
+ from = update_from<scalar_t>(from);
161
+ TORCH_CHECK(from < to_inc, "random_ expects 'from' casted to dtype to be less than or equal to 'to_inc' casted to dtype, but got from=", from, " > to_inc=", to_inc);
162
+ });
163
+ } else if (isIntegralType(iter.dtype(), /*includeBool=*/true)) {
164
+ AT_DISPATCH_V2(self.scalar_type(), "random_from_to_range_calc", AT_WRAP([&] {
165
+ if constexpr (std::is_same_v<scalar_t, bool>) {
166
+ to_inc = static_cast<int64_t>(true);
167
+ } else {
168
+ to_inc = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
169
+ }
170
+ }), AT_EXPAND(AT_INTEGRAL_TYPES_V2), kBool);
171
+ } else {
172
+ TORCH_CHECK(false, "random_from_to_impl handles only integral, floating-point and boolean types");
173
+ }
174
+ check_from_to_in_range(from, to_inc, self.dtype());
175
+ CHECK_EMPTY_AND_RETURN(self);
176
+ range = static_cast<uint64_t>(to_inc) - static_cast<uint64_t>(from) + 1;
177
+ random_from_to_kernel<RNG>()(iter, range, from, generator);
178
+ } else {
179
+ // [std::numeric_limits<int64_t>::lowest(), std::numeric_limits<int64_t>::max()]
180
+ // range = 2^64
181
+ CHECK_EMPTY_AND_RETURN(self);
182
+ random_from_to_kernel<RNG>()(iter, generator);
183
+ }
184
+ return self;
185
+ }
186
+
187
+ // ==================================================== Normal ========================================================
188
+
189
+ #define CHECK_NORMAL_TENSOR_STD(std) \
190
+ do { \
191
+ TORCH_CHECK( \
192
+ !std.is_complex(), \
193
+ "normal expects standard deviation to be non-complex"); \
194
+ TORCH_CHECK( \
195
+ std.numel() == 0 || std.is_meta() || std.min().ge(0).item<bool>(), \
196
+ "normal expects all elements of std >= 0.0"); \
197
+ } while (0)
198
+
199
+ #define CHECK_NORMAL_STD(std) \
200
+ TORCH_CHECK(std >= 0.0, "normal expects std >= 0.0, but found std ", std);
201
+
202
+ template<template<typename> class normal_kernel, typename RNG>
203
+ Tensor& normal_impl_(Tensor& self, double mean, double std, std::optional<Generator> gen) {
204
+ CHECK_NORMAL_STD(std);
205
+ CHECK_EMPTY_AND_RETURN(self);
206
+
207
+ if (self.is_complex()) {
208
+ auto float_tensor = at::view_as_real(self);
209
+ // variance for normal distribution of the real and imaginary values
210
+ // is half of the input variance
211
+ normal_kernel<RNG>()(float_tensor, mean, std/(std::sqrt(2)), gen);
212
+ } else {
213
+ normal_kernel<RNG>()(self, mean, std, gen);
214
+ }
215
+ return self;
216
+ }
217
+
218
+ template<template<typename> class normal_kernel, typename RNG>
219
+ Tensor& normal_out_impl(Tensor& output, const Tensor& mean, double std, std::optional<Generator> gen) {
220
+ CHECK_NORMAL_STD(std);
221
+ auto std_tensor = at::empty_like(output, MemoryFormat::Contiguous);
222
+ auto shape = at::infer_size(mean.sizes(), std_tensor.sizes());
223
+ at::native::resize_output(output, shape);
224
+ normal_impl_<normal_kernel, RNG>(output, 0, std, gen);
225
+ output.add_(mean);
226
+ return output;
227
+ }
228
+
229
+ template<template<typename> class normal_kernel, typename RNG>
230
+ Tensor& normal_out_impl(Tensor& output, double mean, const Tensor& std, std::optional<Generator> gen) {
231
+ CHECK_NORMAL_TENSOR_STD(std);
232
+ auto mean_tensor = at::full({}, mean, output.options());
233
+ auto shape = at::infer_size(mean_tensor.sizes(), std.sizes());
234
+ at::native::resize_output(output, shape);
235
+ normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
236
+ // CUDA NB: addcmul_out copies the tensor to be added into the output.
237
+ // The previous function here was addcmul_out(output, mean_tensor, output, std, 1);
238
+ // The third argument is not a constant reference and hence the samples in output are overwritten.
239
+ // Consequently, the computation performed is mean_tensor + mean_tensor * std instead of mean_tensor + output * std
240
+ output.mul_(std).add_(mean_tensor);
241
+ return output;
242
+ }
243
+
244
+ template<template<typename> class normal_kernel, typename RNG>
245
+ Tensor& normal_out_impl(Tensor& output, const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
246
+ CHECK_NORMAL_TENSOR_STD(std);
247
+ auto shape = at::infer_size(mean.sizes(), std.sizes());
248
+ at::native::resize_output(output, shape);
249
+ normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
250
+ // CUDA NB: addcmul_out copies the tensor to be added into the output.
251
+ // The previous function here was addcmul_out(output, mean, output, std, 1);
252
+ // The third argument is not a constant reference and hence the samples in output are overwritten.
253
+ // Consequently, the computation performed is mean + mean * std instead of mean + output * std
254
+ output.mul_(std).add_(mean);
255
+ return output;
256
+ }
257
+
258
+ template<template<typename> class normal_kernel, typename RNG>
259
+ Tensor normal_impl(const Tensor& mean, double std, std::optional<Generator> gen) {
260
+ CHECK_NORMAL_STD(std);
261
+ Tensor ret = at::empty_like(mean, MemoryFormat::Contiguous);
262
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
263
+ return ret;
264
+ }
265
+
266
+ template<template<typename> class normal_kernel, typename RNG>
267
+ Tensor normal_impl(double mean, const Tensor& std, std::optional<Generator> gen) {
268
+ CHECK_NORMAL_TENSOR_STD(std);
269
+ Tensor ret = at::empty_like(std, MemoryFormat::Contiguous);
270
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
271
+ return ret;
272
+ }
273
+
274
+ template<template<typename> class normal_kernel, typename RNG>
275
+ Tensor normal_impl(const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
276
+ CHECK_NORMAL_TENSOR_STD(std);
277
+ auto shape = at::infer_size(mean.sizes(), std.sizes());
278
+ Tensor ret = at::empty(shape, mean.options(), MemoryFormat::Contiguous);
279
+ normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
280
+ return ret;
281
+ }
282
+
283
+ // ==================================================== Uniform =======================================================
284
+
285
+ template<template<typename> class uniform_kernel, typename RNG>
286
+ at::Tensor& uniform_impl_(at::Tensor& self, double from, double to, std::optional<Generator> generator) {
287
+ if (self.is_complex()) {
288
+ CHECK_EMPTY_AND_RETURN(self);
289
+ auto float_tensor = at::view_as_real(self);
290
+ uniform_impl_<uniform_kernel, RNG>(float_tensor, from, to, generator);
291
+ } else {
292
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "check_uniform_bounds", [&] {
293
+ [[maybe_unused]] const auto dtype = self.dtype();
294
+ const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
295
+ const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
296
+ CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
297
+ CHECK_OUT_OF_BOUNDS(to, "to", min, max, dtype);
298
+ TORCH_CHECK(from <= to, "uniform_ expects to return a [from, to) range, but found from=", from, " > to=", to);
299
+ TORCH_CHECK((to - from) <= std::numeric_limits<scalar_t>::max(),
300
+ "uniform_ expects to-from <= std::numeric_limits<", toString(self.scalar_type()),
301
+ ">::max(), but found to=", to, " and from=", from,
302
+ " which result in to-from to exceed the limit");
303
+ from = std::min(std::max(from, min), max);
304
+ to = std::max(std::min(to, max), min);
305
+ });
306
+ CHECK_EMPTY_AND_RETURN(self);
307
+ auto iter = at::TensorIterator::borrowing_nullary_op(self);
308
+ uniform_kernel<RNG>()(iter, from, to, generator);
309
+ }
310
+ return self;
311
+ }
312
+
313
+ // ================================================== LogNormal =======================================================
314
+
315
+ template<template<typename> class log_normal_kernel, typename RNG>
316
+ at::Tensor& log_normal_impl_(at::Tensor& self, double mean, double std, std::optional<Generator> gen) {
317
+ TORCH_CHECK(std > 0.0, "log_normal_ expects std > 0.0, but found std=", std);
318
+ CHECK_EMPTY_AND_RETURN(self);
319
+ auto iter = TensorIterator::borrowing_nullary_op(self);
320
+ log_normal_kernel<RNG>()(iter, mean, std, gen);
321
+ return self;
322
+ }
323
+
324
+ // =================================================== Geometric ======================================================
325
+
326
+ template<template<typename> class geometric_kernel, typename RNG>
327
+ Tensor& geometric_impl_(Tensor& self, double p, std::optional<Generator> gen) {
328
+ TORCH_CHECK(0 < p && p < 1, "geometric_ expects p to be in (0, 1), but got p=", p);
329
+ CHECK_EMPTY_AND_RETURN(self);
330
+ auto iter = TensorIterator::borrowing_nullary_op(self);
331
+ geometric_kernel<RNG>()(iter, p, gen);
332
+ return self;
333
+ }
334
+
335
+ // ================================================== Exponential =====================================================
336
+
337
+ template<template<typename> class exponential_kernel, typename RNG>
338
+ Tensor& exponential_impl_(Tensor& self, double lambda, std::optional<Generator> gen) {
339
+ TORCH_CHECK(lambda > 0.0, "exponential_ expects lambda > 0.0, but found lambda=", lambda);
340
+ CHECK_EMPTY_AND_RETURN(self);
341
+ auto iter = TensorIterator::borrowing_nullary_op(self);
342
+ exponential_kernel<RNG>()(iter, lambda, gen);
343
+ return self;
344
+ }
345
+
346
+ // ==================================================== Cauchy ========================================================
347
+
348
+ template<template<typename> class cauchy_kernel, typename RNG>
349
+ Tensor& cauchy_impl_(Tensor& self, double median, double sigma, std::optional<Generator> gen) {
350
+ // TODO: instead of variable name 'sigma', use 'gamma' or 'scale'
351
+ // the variance, squared sigma, is undefined for cauchy distribution
352
+ TORCH_CHECK(sigma > 0.0, "cauchy_ expects sigma > 0.0, but found sigma=", sigma);
353
+ TORCH_CHECK(at::isFloatingType(self.scalar_type()), "Cauchy distribution is a continuous probability distribution. dtype must be a floating point but you specified ", self.dtype());
354
+ CHECK_EMPTY_AND_RETURN(self);
355
+ auto iter = TensorIterator::borrowing_nullary_op(self);
356
+ cauchy_kernel<RNG>()(iter, median, sigma, gen);
357
+ return self;
358
+ }
359
+
360
+ // ==================================================== Bernoulli =====================================================
361
+
362
+ template<template<typename> class bernoulli_tensor_kernel, typename RNG>
363
+ Tensor& bernoulli_impl_(Tensor& self, const Tensor& p_, std::optional<Generator> gen) {
364
+ CHECK_EMPTY_AND_RETURN(self);
365
+ NoNamesGuard guard;
366
+ at::assert_no_internal_overlap(self);
367
+ bernoulli_tensor_kernel<RNG>()(self, p_, gen);
368
+ return self;
369
+ }
370
+
371
+ template<template<typename> class bernoulli_scalar_kernel, typename RNG>
372
+ Tensor& bernoulli_impl_(Tensor& self, double p, std::optional<Generator> gen) {
373
+ TORCH_CHECK(0 <= p && p <= 1, "bernoulli_ expects p to be in [0, 1], but got p=", p);
374
+ CHECK_EMPTY_AND_RETURN(self);
375
+ at::assert_no_internal_overlap(self);
376
+ bernoulli_scalar_kernel<RNG>()(self, p, gen);
377
+ return self;
378
+ }
379
+
380
+ template<template<typename> class bernoulli_tensor_kernel, typename RNG>
381
+ Tensor& bernoulli_out_impl(Tensor& result, const Tensor& self, std::optional<Generator> gen) {
382
+ // result.resize_as_(self) requires self to have same dtype as result, so we
383
+ // use resize_ instead.
384
+ // TODO: Fix resize_as_. See pytorch/pytorch#11665.
385
+ result.resize_(self.sizes());
386
+ bernoulli_impl_<bernoulli_tensor_kernel, RNG>(result, self, gen);
387
+ namedinference::propagate_names(result, self);
388
+ return result;
389
+ }
390
+
391
+ #undef CHECK_OUT_OF_BOUNDS
392
+ #undef WARN_OUT_OF_BOUNDS
393
+
394
+ } // namespace at::native::templates
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/Distributions.h ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/Math.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/MathConstants.h>
6
+
7
+ // ROCM hcc doesn't work well with using std:: in kernel functions
8
+ #if defined(__CUDA_ARCH__)
9
+ #include <c10/cuda/CUDAMathCompat.h>
10
+ #define compat_exp c10::cuda::compat::exp
11
+ #define compat_ceil c10::cuda::compat::ceil
12
+ #define compat_floor c10::cuda::compat::floor
13
+ #define compat_log c10::cuda::compat::log
14
+ #define compat_pow c10::cuda::compat::pow
15
+ #define compat_sqrt c10::cuda::compat::sqrt
16
+ #define compat_tan c10::cuda::compat::tan
17
+ #define compat_abs c10::cuda::compat::abs
18
+ #define compat_log1p c10::cuda::compat::log1p
19
+ #elif defined(__HIPCC__)
20
+ #include <c10/hip/HIPMathCompat.h>
21
+ #define compat_exp c10::hip::compat::exp
22
+ #define compat_ceil c10::hip::compat::ceil
23
+ #define compat_floor c10::hip::compat::floor
24
+ #define compat_log c10::hip::compat::log
25
+ #define compat_pow c10::hip::compat::pow
26
+ #define compat_sqrt c10::hip::compat::sqrt
27
+ #define compat_tan c10::hip::compat::tan
28
+ #define compat_abs c10::hip::compat::abs
29
+ #define compat_log1p c10::hip::compat::log1p
30
+ #else
31
+ #define compat_exp std::exp
32
+ #define compat_ceil std::ceil
33
+ #define compat_floor std::floor
34
+ #define compat_log std::log
35
+ #define compat_pow std::pow
36
+ #define compat_sqrt std::sqrt
37
+ #define compat_tan std::tan
38
+ #define compat_abs std::abs
39
+ #define compat_log1p std::log1p
40
+ #endif
41
+
42
+ namespace {
43
+
44
+ #if !defined(__CUDA_ARCH__) && !defined(__HIPCC__)
45
+ // we cannot use std::isnan directly due to some incompatibility of
46
+ // gcc constexpr'ing and nvcc
47
+ using std::isnan;
48
+ #endif
49
+
50
+ // Here sampler_t should be function type scalar_t(void). For gpu
51
+ // "sampler" is a device function, but since ROCM doesn't have
52
+ // equivalent to nvstd::function, we use a template type parameter to
53
+ // capture it.
54
+ template<typename scalar_t, typename sampler_t>
55
+ struct BaseSampler {
56
+ sampler_t sampler;
57
+ C10_DEVICE BaseSampler(const sampler_t& sampler): sampler(sampler) {}
58
+ C10_DEVICE scalar_t sample() {
59
+ return sampler();
60
+ }
61
+ };
62
+
63
+ // The function `sample_gamma` is
64
+ // is adapted from Numpy's distributions.c implementation.
65
+ // It is MIT licensed, so here is the copyright:
66
+
67
+ /* Copyright 2005 Robert Kern (robert.kern@gmail.com)
68
+ *
69
+ * Permission is hereby granted, free of charge, to any person obtaining a
70
+ * copy of this software and associated documentation files (the
71
+ * "Software"), to deal in the Software without restriction, including
72
+ * without limitation the rights to use, copy, modify, merge, publish,
73
+ * distribute, sublicense, and/or sell copies of the Software, and to
74
+ * permit persons to whom the Software is furnished to do so, subject to
75
+ * the following conditions:
76
+ *
77
+ * The above copyright notice and this permission notice shall be included
78
+ * in all copies or substantial portions of the Software.
79
+ *
80
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
81
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
82
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
83
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
84
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
85
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
86
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87
+ */
88
+
89
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t, typename normal_sampler_t>
90
+ C10_DEVICE scalar_t sample_gamma(scalar_t alpha, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform, BaseSampler<accscalar_t, normal_sampler_t>& standard_normal) {
91
+ accscalar_t scale = 1.0f;
92
+
93
+ // Boost alpha for higher acceptance probability.
94
+ if (alpha < 1.0f) {
95
+ if (alpha == 0.f) return 0.f;
96
+ scale *= compat_pow(1 - standard_uniform.sample(), 1.0f / alpha);
97
+ alpha += 1.0f;
98
+ }
99
+
100
+ // This implements the acceptance-rejection method of Marsaglia and Tsang (2000)
101
+ // doi:10.1145/358407.358414
102
+ const accscalar_t d = alpha - 1.0f / 3.0f;
103
+ const accscalar_t c = 1.0f / compat_sqrt(9.0f * d);
104
+ for (;;) {
105
+ accscalar_t x, y;
106
+ do {
107
+ x = standard_normal.sample();
108
+ y = 1.0f + c * x;
109
+ } while (y <= 0);
110
+ const accscalar_t v = y * y * y;
111
+ const accscalar_t u = 1 - standard_uniform.sample();
112
+ const accscalar_t xx = x * x;
113
+ if (u < 1.0f - 0.0331f * xx * xx)
114
+ return static_cast<scalar_t>(scale * d * v);
115
+ if (compat_log(u) < 0.5f * xx + d * (1.0f - v + compat_log(v)))
116
+ return static_cast<scalar_t>(scale * d * v);
117
+ }
118
+ }
119
+
120
+ /* the functions stirling_approx_tail, binomial_inversion, and btrs are adapted
121
+ * from TensorFlow's random_binomial_op.cc implementation. That code is under
122
+ * copyright: 2019 The TensorFlow Authors.
123
+ *
124
+ * It was released under the Apache License, Version 2.0 (the "License"), available at:
125
+ * http://www.apache.org/licenses/LICENSE-2.0
126
+ */
127
+
128
+ template<typename scalar_t>
129
+ C10_DEVICE scalar_t stirling_approx_tail(scalar_t k) {
130
+ const static scalar_t kTailValues[] = {
131
+ 0.0810614667953272,
132
+ 0.0413406959554092,
133
+ 0.0276779256849983,
134
+ 0.02079067210376509,
135
+ 0.0166446911898211,
136
+ 0.0138761288230707,
137
+ 0.0118967099458917,
138
+ 0.0104112652619720,
139
+ 0.00925546218271273,
140
+ 0.00833056343336287
141
+ };
142
+ if (k <= 9) {
143
+ return kTailValues[static_cast<size_t>(k)];
144
+ }
145
+ scalar_t kp1sq = (k + 1) * (k + 1);
146
+ return (1.0 / 12 - (1.0 / 360 - 1.0 / 1260 / kp1sq) / kp1sq) / (k + 1);
147
+ }
148
+
149
+
150
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
151
+ C10_DEVICE scalar_t binomial_inversion(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
152
+ accscalar_t U;
153
+ accscalar_t geom_sum = 0;
154
+ scalar_t num_geom = 0;
155
+
156
+ accscalar_t logprob = compat_log1p(-prob);
157
+
158
+ while (true) {
159
+ U = standard_uniform.sample();
160
+ accscalar_t geom = compat_ceil(compat_log(U) / logprob);
161
+ geom_sum += geom;
162
+ if (geom_sum > count) {
163
+ break;
164
+ }
165
+ num_geom = num_geom + 1;
166
+ }
167
+ return num_geom;
168
+ }
169
+
170
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
171
+ C10_DEVICE scalar_t btrs(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
172
+ scalar_t k;
173
+ accscalar_t U, V, us;
174
+
175
+ // This is spq in the paper.
176
+ const accscalar_t stddev = compat_sqrt(count * prob * (1 - prob));
177
+
178
+ // Other coefficients for Transformed Rejection sampling.
179
+ const accscalar_t b = 1.15 + 2.53 * stddev;
180
+ const accscalar_t a = -0.0873 + 0.0248 * b + 0.01 * prob;
181
+ const accscalar_t c = count * prob + 0.5;
182
+ const accscalar_t v_r = 0.92 - 4.2 / b;
183
+ const accscalar_t r = prob / (1 - prob);
184
+
185
+ const accscalar_t alpha = (2.83 + 5.1 / b) * stddev;
186
+ const accscalar_t m = compat_floor((count + 1) * prob);
187
+
188
+ while (true) {
189
+ U = standard_uniform.sample() - 0.5;
190
+ V = standard_uniform.sample();
191
+
192
+ us = 0.5 - compat_abs(U);
193
+ k = static_cast<scalar_t>(compat_floor((2 * a / us + b) * U + c));
194
+
195
+ // Reject non-sensical answers.
196
+ if (k < 0 || k > count) {
197
+ continue;
198
+ }
199
+ // Region for which the box is tight, and we can return our calculated value.
200
+ // This should happen 0.86 * v_r times. In the limit as n * p is large,
201
+ // the acceptance rate converges to ~79% (and in the lower regime it is ~24%).
202
+ if (us >= 0.07 && V <= v_r) {
203
+ return k;
204
+ }
205
+
206
+ // This deviates from Hormann's BTRS algorithm, as there is a log missing.
207
+ // For all (u, v) pairs outside of the bounding box, this calculates the
208
+ // transformed-reject ratio.
209
+ V = compat_log(V * alpha / (a / (us * us) + b));
210
+ accscalar_t upperbound =
211
+ ((m + 0.5) * compat_log((m + 1) / (r * (count - m + 1))) +
212
+ (count + 1) * compat_log((count - m + 1) / (count - k + 1)) +
213
+ (k + 0.5) * compat_log(r * (count - k + 1) / (k + 1)) +
214
+ stirling_approx_tail<accscalar_t>(m) + stirling_approx_tail<accscalar_t>(count - m) -
215
+ stirling_approx_tail<accscalar_t>(k) - stirling_approx_tail<accscalar_t>(count - k));
216
+
217
+ if (V <= upperbound) {
218
+ return k;
219
+ }
220
+ }
221
+ }
222
+
223
+ template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
224
+ C10_DEVICE scalar_t sample_binomial(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
225
+ if (count <= 0.0 || prob <= 0.0) {
226
+ return 0;
227
+ } else if (prob >= 1.0) {
228
+ return count;
229
+ } else if (prob <= 0.5) {
230
+ if (count * prob >= 10.0) {
231
+ // btrs
232
+ return btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
233
+ } else {
234
+ // binomial inversion
235
+ return binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
236
+ }
237
+ } else if (prob > 0.5) {
238
+ scalar_t qprob = 1.0 - prob;
239
+ if (count * qprob >= 10.0) {
240
+ // btrs
241
+ return count - btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
242
+ } else {
243
+ // count - binomial inversion
244
+ return count - binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
245
+ }
246
+ } else {
247
+ // prob is nan?
248
+ return static_cast<scalar_t>(NAN);
249
+ }
250
+ }
251
+
252
+ /*
253
+ * This function is derived from the implementation of the digamma function in the Cephes Math Library.
254
+ * See note [3-Clause BSD License for the Cephes Math Library] in ATen/native/Math.h.
255
+ */
256
+ template<typename scalar_t, typename accscalar_t>
257
+ C10_DEVICE inline scalar_t digamma_one(scalar_t x) {
258
+ constexpr accscalar_t PSI_10 = 2.25175258906672110764;
259
+ if (x == 0) {
260
+ return INFINITY;
261
+ }
262
+ accscalar_t additional_summand = 0;
263
+ int x_is_integer = x == compat_floor(x);
264
+ if (x < 0) {
265
+ if (x_is_integer) {
266
+ return INFINITY;
267
+ }
268
+ // it is more standard to write this as recursion, but
269
+ // nvcc does not like that
270
+ additional_summand = -c10::pi<scalar_t> /
271
+ compat_tan(c10::pi<scalar_t> * x);
272
+ x = 1 - x;
273
+ }
274
+
275
+ // Push x to be >= 10
276
+ accscalar_t result = 0;
277
+ while (x < 10) {
278
+ result -= 1 / x;
279
+ x += 1;
280
+ }
281
+ if (x == 10) {
282
+ return result + PSI_10 + additional_summand;
283
+ }
284
+
285
+ // Compute asymptotic digamma
286
+ static const accscalar_t A[] = {
287
+ 8.33333333333333333333E-2,
288
+ -2.10927960927960927961E-2,
289
+ 7.57575757575757575758E-3,
290
+ -4.16666666666666666667E-3,
291
+ 3.96825396825396825397E-3,
292
+ -8.33333333333333333333E-3,
293
+ 8.33333333333333333333E-2,
294
+ };
295
+
296
+ accscalar_t y = 0;
297
+ if (x < 1.0e17f) {
298
+ accscalar_t z = 1.0 / (x * x);
299
+ y = z * polevl<accscalar_t>(z, A, 6);
300
+ }
301
+ return static_cast<scalar_t>(
302
+ result + compat_log(x) - (0.5f / x) - y + additional_summand);
303
+ }
304
+
305
+ // Computes the reparameterized gradient -(d/dalpha cdf(x;alpha)) / pdf(x;alpha)
306
+ // for random number x drawn from a standard Gamma distribution Gamma(alpha).
307
+ template <typename scalar_t, typename accscalar_t>
308
+ C10_HOST_DEVICE scalar_t standard_gamma_grad_one(scalar_t alpha_, scalar_t x_) {
309
+ // Use a Taylor series expansion for small x.
310
+ accscalar_t x = static_cast<accscalar_t>(x_);
311
+ accscalar_t alpha = static_cast<accscalar_t>(alpha_);
312
+ if (x < 0.8f) {
313
+ accscalar_t numer = 1;
314
+ accscalar_t denom = alpha;
315
+ auto series1 = numer / denom;
316
+ auto series2 = numer / (denom * denom);
317
+ for (int i = 1; i <= 5; ++i) {
318
+ numer *= -x / static_cast<accscalar_t>(i);
319
+ denom += 1;
320
+ series1 += numer / denom;
321
+ series2 += numer / (denom * denom);
322
+ }
323
+ const auto pow_x_alpha = compat_pow(x, alpha);
324
+ const auto gamma_pdf = compat_pow(x, alpha - 1) * compat_exp(-x);
325
+ const auto gamma_cdf = pow_x_alpha * series1;
326
+ const auto gamma_cdf_alpha =
327
+ (compat_log(x) - digamma_one<accscalar_t, accscalar_t>(alpha)) *
328
+ gamma_cdf -
329
+ pow_x_alpha * series2;
330
+ const auto result = -gamma_cdf_alpha / gamma_pdf;
331
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : static_cast<scalar_t>(result);
332
+ }
333
+
334
+ // Use a Rice saddle point expansion for large alpha.
335
+ if (alpha > 8.0f) {
336
+ if (0.9f * alpha <= x && x <= 1.1f * alpha) {
337
+ const auto numer_1 = 1 + 24 * alpha * (1 + 12 * alpha);
338
+ const auto numer_2 = 1440 * (alpha * alpha) + 6 * x * (53 - 120 * x)
339
+ - 65 * x * x / alpha + alpha * (107 + 3600 * x);
340
+ const auto denom = 1244160 * (alpha * alpha) * (alpha * alpha);
341
+ return static_cast<scalar_t>(numer_1 * numer_2 / denom);
342
+ }
343
+ const auto denom = compat_sqrt(8 * alpha);
344
+ const auto term2 = denom / (alpha - x);
345
+ const auto term3 = compat_pow(
346
+ x - alpha - alpha * compat_log(x / alpha),
347
+ static_cast<accscalar_t>(-1.5));
348
+ const auto term23 = (x < alpha) ? term2 - term3 : term2 + term3;
349
+ const auto term1 = compat_log(x / alpha) * term23 -
350
+ compat_sqrt(2 / alpha) * (alpha + x) / ((alpha - x) * (alpha - x));
351
+ const auto stirling = 1 + 1 / (12 * alpha) * (1 + 1 / (24 * alpha));
352
+ const auto numer = x * term1;
353
+ return static_cast<scalar_t>(-stirling * numer / denom);
354
+ }
355
+
356
+ // Use a bivariate rational approximation to the reparameterized gradient.
357
+ const auto u = compat_log(x / alpha);
358
+ const auto v = compat_log(alpha);
359
+ static const accscalar_t coef_uv[3][8] = {
360
+ {0.16009398, -0.094634809, 0.025146376, -0.0030648343,
361
+ 1, 0.32668115, 0.10406089, 0.0014179084},
362
+ {0.53487893, 0.1298071, 0.065735949, -0.0015649758,
363
+ 0.16639465, 0.020070113, -0.0035938915, -0.00058392623},
364
+ {0.040121004, -0.0065914022, -0.0026286047, -0.0013441777,
365
+ 0.017050642, -0.0021309326, 0.00085092367, -1.5247877e-07},
366
+ };
367
+ accscalar_t coef_v[8];
368
+ for (int i = 0; i < 8; ++ i) {
369
+ coef_v[i] = coef_uv[0][i] + u * (coef_uv[1][i] + u * coef_uv[2][i]);
370
+ }
371
+ const auto p = coef_v[0] + v * (coef_v[1] + v * (coef_v[2] + v * coef_v[3]));
372
+ const auto q = coef_v[4] + v * (coef_v[5] + v * (coef_v[6] + v * coef_v[7]));
373
+ return static_cast<scalar_t>(compat_exp(p / q));
374
+ }
375
+
376
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
377
+ // Assumes x is close to zero and uses a Taylor expansion.
378
+ template <typename scalar_t, typename accscalar_t>
379
+ C10_DEVICE inline scalar_t _beta_grad_alpha_small(scalar_t x, scalar_t alpha, scalar_t beta) {
380
+ const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha)
381
+ - digamma_one<scalar_t, accscalar_t>(alpha + beta) - compat_log(x);
382
+ scalar_t numer = 1;
383
+ scalar_t series = numer / alpha * (factor + 1 / alpha);
384
+ for (int i = 1; i <= 10; ++i) {
385
+ scalar_t casted_i = static_cast<scalar_t>(i);
386
+ numer *= (casted_i - beta) * x / casted_i;
387
+ const scalar_t denom = alpha + casted_i;
388
+ series += numer / denom * (factor + 1 / denom);
389
+ }
390
+ const scalar_t result = x * compat_pow(1 - x, -beta) * series;
391
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
392
+ }
393
+
394
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt beta.
395
+ // Assumes x is close to zero and uses a Taylor expansion.
396
+ template <typename scalar_t, typename accscalar_t>
397
+ C10_DEVICE inline scalar_t _beta_grad_beta_small(scalar_t x, scalar_t alpha, scalar_t beta) {
398
+ const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha + beta) - digamma_one<scalar_t, accscalar_t>(beta);
399
+ scalar_t numer = 1, betas = 1, dbetas = 0, series = factor / alpha;
400
+ for (int i = 1; i <= 8; ++i) {
401
+ scalar_t casted_i = static_cast<scalar_t>(i);
402
+ numer *= -x / casted_i;
403
+ dbetas = dbetas * (beta - casted_i) + betas;
404
+ betas = betas * (beta - casted_i);
405
+ series += numer / (alpha + casted_i) * (dbetas + factor * betas);
406
+ }
407
+ const scalar_t result = -compat_pow(1 - x, 1 - beta) * series;
408
+ return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
409
+ }
410
+
411
+ // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
412
+ // Assumes alpha and beta are both large and uses a Rice saddle point expansion.
413
+ // To ensure numerical stability, this computation is performed at higher precision.
414
+ template<typename scalar_t, typename accscalar_t>
415
+ C10_DEVICE inline scalar_t _beta_grad_alpha_mid(accscalar_t x, accscalar_t alpha, accscalar_t beta) {
416
+ const accscalar_t total = alpha + beta;
417
+ const accscalar_t mean = alpha / total;
418
+ const accscalar_t std = compat_sqrt(alpha * beta / (total + 1)) / total;
419
+ if (mean - 0.1 * std <= x && x <= mean + 0.1 * std) {
420
+ // Avoid the singularity at x = mean.
421
+ const accscalar_t poly = 47 * x * (beta * beta) * (beta * beta) + alpha * (
422
+ (43 + 20 * (16 + 27 * beta) * x) * (beta * beta) * beta + alpha * (
423
+ 3 * (59 + 180 * beta - 90 * x) * (beta * beta) + alpha * (
424
+ (453 + 1620 * beta * (1 - x) - 455 * x) * beta + alpha * (
425
+ 8 * (1 - x) * (135 * beta - 11)))));
426
+ const accscalar_t prefactor_num = (1 + 12 * alpha) * (1 + 12 * beta) / (total * total);
427
+ const accscalar_t prefactor_den = 12960 * alpha * alpha * alpha * beta * beta * (1 + 12 * total);
428
+ return prefactor_num / (1 - x) * poly / prefactor_den;
429
+ }
430
+ const accscalar_t prefactor = -x / compat_sqrt(2 * alpha * beta / total);
431
+ const accscalar_t stirling = (1 + 1 / (12 * alpha) + 1 / (288 * alpha * alpha))
432
+ * (1 + 1 / (12 * beta) + 1 / (288 * beta * beta))
433
+ / (1 + 1 / (12 * total) + 1 / (288 * total * total));
434
+ const accscalar_t term1_num = 2 * (alpha * alpha) * (x - 1) + alpha * beta * (x - 1) - x * (beta * beta);
435
+ const accscalar_t axbx = alpha * (x - 1) + beta * x;
436
+ const accscalar_t term1_den = compat_sqrt(2 * alpha / beta) * compat_pow(total, static_cast<accscalar_t>(1.5f)) * axbx * axbx;
437
+ const accscalar_t term1 = term1_num / term1_den;
438
+ const accscalar_t term2 = 0.5f * compat_log(alpha / (total * x));
439
+ const accscalar_t term3_num = compat_sqrt(8 * alpha * beta / total);
440
+ const accscalar_t term3_den = beta * x + alpha * (x - 1);
441
+ const accscalar_t term3 = term3_num / term3_den;
442
+ const accscalar_t term4_base = beta * compat_log(beta / (total * (1 - x))) +
443
+ alpha * compat_log(alpha / (total * x));
444
+ const accscalar_t term4 = compat_pow(term4_base, static_cast<accscalar_t>(-1.5f));
445
+ const accscalar_t term1234 = term1 + term2 * (term3 + (x < mean ? term4 : -term4));
446
+ return static_cast<scalar_t>(stirling * prefactor * term1234);
447
+ }
448
+
449
+ // Computes a scaled reparameterized gradient
450
+ // -(d/dalpha cdf(x;alpha,beta)) / pdf(x;alpha,beta) / (1-x)
451
+ // for random number x drawn from a Beta distribution Beta(alpha,beta).
452
+ // This function inputs total=alpha+beta to make it easy to implement
453
+ // Dirichlet reparameterized gradients in terms of Betas.
454
+ template<typename scalar_t, typename accscalar_t>
455
+ C10_HOST_DEVICE inline scalar_t dirichlet_grad_one(scalar_t x, scalar_t alpha, scalar_t total) {
456
+ accscalar_t x_ = static_cast<accscalar_t>(x);
457
+ accscalar_t alpha_ = static_cast<accscalar_t>(alpha);
458
+ accscalar_t total_ = static_cast<accscalar_t>(total);
459
+
460
+ const scalar_t beta = total - alpha;
461
+ const accscalar_t beta_ = total_ - alpha_;
462
+ const scalar_t boundary = total * x * (1 - x);
463
+
464
+ // Use an asymptotic approximation for x close to 0.
465
+ if (x <= 0.5f && boundary < 2.5f) {
466
+ return _beta_grad_alpha_small<scalar_t, accscalar_t>(x, alpha, beta);
467
+ }
468
+
469
+ // Use an asymptotic approximation for x close to 1.
470
+ if (x >= 0.5f && boundary < 0.75f) {
471
+ return -_beta_grad_beta_small<scalar_t, accscalar_t>(1 - x, beta, alpha);
472
+ }
473
+
474
+ // Use an asymptotic approximation when alpha and (total - alpha) are both large.
475
+ if (alpha > 6 && beta > 6) {
476
+ return _beta_grad_alpha_mid<scalar_t, accscalar_t>(x_, alpha_, beta_);
477
+ }
478
+
479
+ // Use a rational correction to an analytic approximation.
480
+ static const accscalar_t c[2][3][3][4] = {
481
+ {{{1.003668233, -0.01061107488, -0.0657888334, 0.01201642863},
482
+ {0.6336835991, -0.3557432599, 0.05486251648, -0.001465281033},
483
+ {-0.03276231906, 0.004474107445, 0.002429354597, -0.0001557569013}},
484
+ {{0.221950385, -0.3187676331, 0.01799915743, 0.01074823814},
485
+ {-0.2951249643, 0.06219954479, 0.01535556598, 0.001550077057},
486
+ {0.02155310298, 0.004170831599, 0.001292462449, 6.976601077e-05}},
487
+ {{-0.05980841433, 0.008441916499, 0.01085618172, 0.002319392565},
488
+ {0.02911413504, 0.01400243777, -0.002721828457, 0.000751041181},
489
+ {0.005900514878, -0.001936558688, -9.495446725e-06, 5.385558597e-05}}},
490
+ {{{1, -0.02924021934, -0.04438342661, 0.007285809825},
491
+ {0.6357567472, -0.3473456711, 0.05454656494, -0.002407477521},
492
+ {-0.03301322327, 0.004845219414, 0.00231480583, -0.0002307248149}},
493
+ {{0.5925320577, -0.1757678135, 0.01505928619, 0.000564515273},
494
+ {0.1014815858, -0.06589186703, 0.01272886114, -0.0007316646956},
495
+ {-0.007258481865, 0.001096195486, 0.0003934994223, -4.12701925e-05}},
496
+ {{0.06469649321, -0.0236701437, 0.002902096474, -5.896963079e-05},
497
+ {0.001925008108, -0.002869809258, 0.0008000589141, -6.063713228e-05},
498
+ {-0.0003477407336, 6.959756487e-05, 1.097287507e-05, -1.650964693e-06}}},
499
+ };
500
+ const accscalar_t u = compat_log(x_);
501
+ const accscalar_t a = compat_log(alpha_) - u;
502
+ const accscalar_t b = compat_log(total_) - a;
503
+ const accscalar_t pow_u[3] = {1, u, u * u};
504
+ const accscalar_t pow_a[3] = {1, a, a * a};
505
+ accscalar_t p = 0.0;
506
+ accscalar_t q = 0.0;
507
+ for (int i = 0; i < 3; ++i) {
508
+ for (int j = 0; j < 3; ++j) {
509
+ const accscalar_t ua = pow_u[i] * pow_a[j];
510
+ p += ua * (c[0][i][j][0] + b * (c[0][i][j][1] + b * (c[0][i][j][2] + b * c[0][i][j][3])));
511
+ q += ua * (c[1][i][j][0] + b * (c[1][i][j][1] + b * (c[1][i][j][2] + b * c[1][i][j][3])));
512
+ }
513
+ }
514
+ const accscalar_t approx = x_ * (digamma_one<scalar_t, accscalar_t>(total_) - digamma_one<scalar_t, accscalar_t>(alpha_)) / beta_;
515
+ return static_cast<scalar_t>(p / q * approx);
516
+ }
517
+
518
+ } // namespace
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/native/EmbeddingBag.h ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+ #include <ATen/Config.h>
3
+ #include <cstdint>
4
+
5
+ #ifdef USE_FBGEMM
6
+ #include <fbgemm/FbgemmEmbedding.h>
7
+ #endif
8
+
9
+ namespace at::native {
10
+
11
+ enum class EmbeddingBagMode {
12
+ SUM = 0,
13
+ MEAN = 1,
14
+ MAX = 2,
15
+ };
16
+
17
+ [[maybe_unused]] static bool operator==(int64_t op1, EmbeddingBagMode op2) {
18
+ return op1 == static_cast<int64_t>(op2);
19
+ }
20
+
21
+ [[maybe_unused]] static bool operator!=(int64_t op1, EmbeddingBagMode op2) {
22
+ return !(op1 == op2);
23
+ }
24
+
25
+ void check_arguments(
26
+ const Tensor& weight,
27
+ const Tensor& indices,
28
+ const Tensor& offsets,
29
+ const int64_t mode,
30
+ const std::optional<Tensor>& per_sample_weights,
31
+ bool include_last_offset);
32
+
33
+ void make_bag_size_out(
34
+ Tensor& bag_size_out,
35
+ const Tensor& offsets,
36
+ const Tensor& indices,
37
+ const int64_t mode,
38
+ const bool include_last_offset,
39
+ const bool requires_grad);
40
+
41
+ void make_max_indices_out(
42
+ Tensor& max_indices_out,
43
+ const Tensor& weight,
44
+ const Tensor& indices,
45
+ const Tensor& offsets,
46
+ const Tensor& bag_size,
47
+ const int64_t mode,
48
+ bool include_last_offset);
49
+
50
+ void make_offset2bag_out(
51
+ Tensor& offset2bag,
52
+ Tensor& output,
53
+ const Tensor& weight,
54
+ const Tensor& indices,
55
+ const Tensor& offsets,
56
+ const int64_t mode,
57
+ const std::optional<Tensor>& per_sample_weights,
58
+ const int64_t padding_idx = -1);
59
+
60
+ #ifdef USE_FBGEMM
61
+
62
+ template<bool has_weight, typename TIndex, typename TData>
63
+ struct _CallbackAndBlockSize {
64
+ using TCallback = typename fbgemm::EmbeddingSpMDMKernelSignature<TData, TIndex, TIndex, TData>::Type;
65
+
66
+ int64_t blockSize = -1;
67
+ TCallback callback = nullptr;
68
+
69
+ static TCallback generateCallback(int64_t block_size) {
70
+ return fbgemm::GenerateEmbeddingSpMDM<TData, TIndex, TIndex, TData>(
71
+ block_size,
72
+ has_weight,
73
+ /* normalize_by_lengths */false,
74
+ /* prefetch */16,
75
+ /* is_weight_positional */false,
76
+ /* use_offsets */true);
77
+ }
78
+
79
+ _CallbackAndBlockSize() = default;
80
+
81
+ explicit _CallbackAndBlockSize(std::optional<int64_t> maybe_block_size)
82
+ : blockSize(maybe_block_size.value_or(-1))
83
+ , callback(maybe_block_size.has_value() ? generateCallback(maybe_block_size.value()) : nullptr)
84
+ {}
85
+ };
86
+
87
+ template<typename... StorageMixins>
88
+ struct _EmbeddingBagKernelCacheImpl : private StorageMixins... {
89
+
90
+ _EmbeddingBagKernelCacheImpl() = default;
91
+ // use each of the mixins to store corresponding kernel and block size
92
+ explicit _EmbeddingBagKernelCacheImpl(std::optional<int64_t> maybe_block_size)
93
+ : StorageMixins(maybe_block_size)...
94
+ {}
95
+
96
+ // this method is thread safe (call sites may call from different threads)
97
+ template<bool has_weight, typename TIndex, typename TData>
98
+ typename _CallbackAndBlockSize<has_weight, TIndex, TData>::TCallback
99
+ getCallback(int64_t block_size) const {
100
+ // if the cache doesn't store the kernel for the incoming block size
101
+ // (so it is different from the one stored in corresponding mixin)
102
+ // regenerate the kernel (not writing it into the cache so we avoid locks)
103
+ if (block_size != _CallbackAndBlockSize<has_weight, TIndex, TData>::blockSize) {
104
+ return _CallbackAndBlockSize<has_weight, TIndex, TData>::generateCallback(block_size);
105
+ }
106
+ // else retrieve the cached kernel from the corresponding mixin
107
+ return _CallbackAndBlockSize<has_weight, TIndex, TData>::callback;
108
+ }
109
+ };
110
+
111
+ // instantiate the cache with the list of storage mixins
112
+ // for each of the 8 _EmbeddingBagKernelCache* usages in the EmbeddingBag.cpp impl file
113
+ using _EmbeddingBagKernelCache = _EmbeddingBagKernelCacheImpl<
114
+ _CallbackAndBlockSize<true, int32_t, float>,
115
+ _CallbackAndBlockSize<false, int32_t, float>,
116
+ _CallbackAndBlockSize<true, int64_t, float>,
117
+ _CallbackAndBlockSize<false, int64_t, float>,
118
+ _CallbackAndBlockSize<true, int32_t, unsigned short>,
119
+ _CallbackAndBlockSize<false, int32_t, unsigned short>,
120
+ _CallbackAndBlockSize<true, int64_t, unsigned short>,
121
+ _CallbackAndBlockSize<false, int64_t, unsigned short>>;
122
+ #else
123
+ struct _EmbeddingBagKernelCache {
124
+ explicit _EmbeddingBagKernelCache(std::optional<int64_t> /* maybe_block_size */) {}
125
+ };
126
+ #endif
127
+
128
+ void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag,
129
+ Tensor& bag_size, Tensor* max_indices,
130
+ const Tensor &weight, const Tensor &indices,
131
+ const Tensor &offsets, const int64_t mode = 0,
132
+ const std::optional<Tensor>& per_sample_weights = std::nullopt,
133
+ bool include_last_offset = false,
134
+ int64_t padding_idx = -1,
135
+ _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
136
+
137
+ void _embedding_bag_cpu_out(
138
+ at::Tensor& output,
139
+ at::Tensor& offset2bag,
140
+ at::Tensor& bag_size,
141
+ at::Tensor* p_max_indices,
142
+ const at::Tensor& weight,
143
+ const at::Tensor& indices,
144
+ const at::Tensor& offsets,
145
+ const bool scale_grad_by_freq,
146
+ const int64_t mode,
147
+ const bool sparse,
148
+ const std::optional<at::Tensor>& per_sample_weights,
149
+ const bool include_last_offset,
150
+ const std::optional<int64_t>& padding_idx,
151
+ _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
152
+
153
+ } // namespace at::native