ADAPT-Chase commited on
Commit
01a4f5c
·
verified ·
1 Parent(s): fd34729

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/SDPBackend.h +16 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SavedTensorHooks.h +66 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Scalar.h +3 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ScalarOps.h +53 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ScalarType.h +4 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SequenceNumber.h +13 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SmallVector.h +2 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseCsrTensorImpl.h +206 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseCsrTensorUtils.h +454 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseTensorImpl.h +421 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Storage.h +2 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/StorageUtils.h +49 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Tensor.h +3 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorAccessor.h +2 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorGeometry.h +154 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIndexing.h +742 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIterator.h +1034 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIteratorInternal.h +72 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorMeta.h +137 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorNames.h +75 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorOperators.h +51 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorOptions.h +2 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorSubclassLikeUtils.h +88 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorUtils.h +190 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ThreadLocalPythonObjects.h +21 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ThreadLocalState.h +124 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TracerMode.h +132 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TypeDefault.h +26 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Utils.h +138 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Version.h +18 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/VmapGeneratedPlumbing.h +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/WrapDimUtils.h +156 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/WrapDimUtilsMulti.h +44 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/autocast_mode.h +945 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ceil_div.h +24 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/code_template.h +245 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpp_custom_type_hack.h +110 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/div_rtn.h +11 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/dlpack.h +236 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/jit_macros.h +7 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/jiterator_macros.h +38 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/record_function.h +802 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/include/THC/THCAtomics.cuh +3 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/include/THC/THCDeviceUtils.cuh +3 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/AbstractConfig.h +123 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityProfilerInterface.h +108 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityTraceInterface.h +28 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityType.h +65 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ClientInterface.h +22 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/Config.h +516 -0
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SDPBackend.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstdint>
3
+
4
+ namespace at {
5
+
6
+ constexpr int32_t num_sdp_backends = 5;
7
+ enum class SDPBackend {
8
+ error = -1,
9
+ math = 0,
10
+ flash_attention = 1,
11
+ efficient_attention = 2,
12
+ cudnn_attention = 3,
13
+ overrideable = 4
14
+ };
15
+
16
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SavedTensorHooks.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SafePyObject.h>
4
+ #include <c10/macros/Export.h>
5
+ #include <c10/util/python_stub.h>
6
+ #include <optional>
7
+ #include <stack>
8
+ #include <string>
9
+
10
+ #include <utility>
11
+
12
+ namespace at {
13
+
14
+ namespace impl {
15
+
16
+ struct TORCH_API SavedTensorDefaultHooksTLS {
17
+ // PyObject is defined in c10/util/python_stub.h
18
+ std::stack<std::pair<c10::SafePyObject, c10::SafePyObject>> stack;
19
+
20
+ // See NOTE: [Disabling SavedTensorDefaultHooks] for context
21
+ // NOTE: [disabled_error_message invariant]
22
+ // disabled_error_message is nullopt IFF Saved Tensor hooks is enabled
23
+ // We did this for efficiency (so we didn't have to keep a separate bool
24
+ // around)
25
+ std::optional<std::string> disabled_error_message;
26
+
27
+ // See NOTE: [Deferring tensor pack/unpack hooks until runtime]
28
+ bool is_tracing = false;
29
+ };
30
+
31
+ } // namespace impl
32
+
33
+ struct TORCH_API SavedTensorDefaultHooks {
34
+ static void push_hooks(
35
+ c10::SafePyObject pack_hook,
36
+ c10::SafePyObject unpack_hook);
37
+ static std::pair<c10::SafePyObject, c10::SafePyObject> pop_hooks();
38
+ static std::optional<std::pair<c10::SafePyObject, c10::SafePyObject>>
39
+ get_hooks();
40
+ static void lazy_initialize();
41
+
42
+ static const impl::SavedTensorDefaultHooksTLS& get_tls_state();
43
+ static void set_tls_state(const impl::SavedTensorDefaultHooksTLS& tls);
44
+
45
+ // NOTE: [Disabling SavedTensorDefaultHooks]
46
+ // A developer of a PyTorch feature may choose to disable SavedTensorDefault
47
+ // hooks, especially if their feature does not work with it. If they are
48
+ // disabled, then the following will raise an error:
49
+ // - Attempting to push_hooks
50
+ // - calling disable(message) with a non-zero stack (hooks) size
51
+ static void disable(const std::string& error_message);
52
+ static void enable();
53
+ static bool is_enabled();
54
+ static const std::optional<std::string>& get_disabled_error_message();
55
+
56
+ // NOTE: [Deferring tensor pack/unpack hooks until runtime]
57
+ // To preserve eager semantics of pack/unpack hooks firing only once per saved
58
+ // variable, Dynamo/AOTAutograd need to defer hook firing until runtime. Using
59
+ // disable() would loud error at trace time, and pushing a no-op hook would
60
+ // fail when the traced code is wrapped in a disable_saved_tensors_hooks ctx.
61
+ // To do so, we disable these hooks during tracing. See
62
+ // https://github.com/pytorch/pytorch/issues/113263.
63
+ static bool set_tracing(bool is_tracing);
64
+ };
65
+
66
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Scalar.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Scalar.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ScalarOps.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/core/Scalar.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/Functions.h>
8
+ #else
9
+ #include <ATen/ops/scalar_tensor.h>
10
+ #endif
11
+
12
+ namespace at::detail {
13
+ // When filling a number to 1-element CPU tensor, we want to skip
14
+ // everything but manipulate data ptr directly.
15
+ // Ideally this fast pass should be implemented in TensorIterator,
16
+ // but we also want to skip compute_types which in not avoidable
17
+ // in TensorIterator for now.
18
+ Tensor& scalar_fill(Tensor& self, const Scalar& value);
19
+ TORCH_API Tensor scalar_tensor_static(
20
+ const Scalar& s,
21
+ std::optional<ScalarType> dtype_opt,
22
+ std::optional<Device> device_opt);
23
+ } // namespace at::detail
24
+
25
+ // This is in the c10 namespace because we use ADL to find the functions in it.
26
+ namespace c10 {
27
+
28
+ // FIXME: this should be (and was) Scalar::toTensor, but there is currently no
29
+ // way to implement this without going through Derived Types (which are not part
30
+ // of core).
31
+ inline at::Tensor scalar_to_tensor(
32
+ const Scalar& s,
33
+ const Device device = at::kCPU) {
34
+ // This is the fast track we have for CPU scalar tensors.
35
+ if (device == at::kCPU) {
36
+ return at::detail::scalar_tensor_static(s, s.type(), at::kCPU);
37
+ }
38
+ return at::scalar_tensor(s, at::device(device).dtype(s.type()));
39
+ }
40
+
41
+ } // namespace c10
42
+
43
+ namespace at::native {
44
+
45
+ inline Tensor wrapped_scalar_tensor(
46
+ const Scalar& scalar,
47
+ const Device device = at::kCPU) {
48
+ auto tensor = scalar_to_tensor(scalar, device);
49
+ tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
50
+ return tensor;
51
+ }
52
+
53
+ } // namespace at::native
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ScalarType.h ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/ATenGeneral.h> // for BC reasons
3
+ #include <c10/core/Backend.h>
4
+ #include <c10/core/ScalarType.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SequenceNumber.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Export.h>
4
+ #include <cstdint>
5
+
6
+ // A simple thread local enumeration, used to link forward and backward pass
7
+ // ops and is used by autograd and observers framework
8
+ namespace at::sequence_number {
9
+
10
+ TORCH_API uint64_t peek();
11
+ TORCH_API uint64_t get_and_increment();
12
+
13
+ } // namespace at::sequence_number
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SmallVector.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <c10/util/SmallVector.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseCsrTensorImpl.h ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/core/TensorImpl.h>
5
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
6
+ #include <c10/util/Exception.h>
7
+ namespace at {
8
+
9
+ // Struct implementing a sparse CSR tensor. It uses three 1-D tensors for
10
+ // denoting the data: `crow_indices_`, `col_indices_` and `values_`.
11
+ // The `crow_indices_` tensor is a integer tensor of shape `(size(0) + 1)`
12
+ // that represents the compressed row indices of the CSR tensor. The
13
+ // `col_indices_` tensor is an integer tensor of shape `(nnz())`
14
+ // that explicitly stores the column indices of each value of the sparse
15
+ // tensor. The `values_` tensor can be of any pytorch-supported data type
16
+ // and has shape `(nnz())`.
17
+ //
18
+ // Since the main advantage of the CSR format over the COO format is speed of
19
+ // computation, care must be taken to facilitate smooth interfacing of
20
+ // these data structures with optimized libraries such as MKL and MAGMA.
21
+ // Since the MKL interface for pytorch currently uses indexing with int32
22
+ // type, it is important to make sure that the `crow_indices` and `col_indices`
23
+ // are of type int32 when calling MKL routines such as SPMM or SPMV.
24
+ //
25
+ // If not calling MKL, it should be alright to use 64 bit integer tensors
26
+ // for indexing.
27
+ struct TORCH_API SparseCsrTensorImpl : public TensorImpl {
28
+ Tensor crow_indices_;
29
+ Tensor col_indices_;
30
+ Tensor values_;
31
+ Layout layout_;
32
+
33
+ public:
34
+ explicit SparseCsrTensorImpl(
35
+ at::DispatchKeySet,
36
+ at::Device device,
37
+ Layout layout,
38
+ const caffe2::TypeMeta);
39
+
40
+ void resize_(int64_t nnz, IntArrayRef size);
41
+ void resize_and_clear_(
42
+ int64_t sparse_dim,
43
+ int64_t dense_dim,
44
+ IntArrayRef size);
45
+ void resize_as_sparse_compressed_tensor_(const Tensor& src);
46
+ void set_member_tensors(
47
+ const Tensor& crow_indices,
48
+ const Tensor& col_indices,
49
+ const Tensor& values,
50
+ c10::SymIntArrayRef size);
51
+ void set_member_tensors(
52
+ const Tensor& crow_indices,
53
+ const Tensor& col_indices,
54
+ const Tensor& values,
55
+ IntArrayRef size);
56
+ const Tensor& compressed_indices() const {
57
+ return crow_indices_;
58
+ }
59
+ const Tensor& plain_indices() const {
60
+ return col_indices_;
61
+ }
62
+ const Tensor& values() const {
63
+ return values_;
64
+ }
65
+ int64_t nnz() {
66
+ return col_indices_.size(-1);
67
+ }
68
+
69
+ inline int64_t batch_dim() const noexcept {
70
+ return crow_indices_.dim() - 1;
71
+ }
72
+
73
+ inline int64_t sparse_dim() const noexcept {
74
+ return 2;
75
+ }
76
+
77
+ inline int64_t dense_dim() const noexcept {
78
+ return values_.dim() - batch_dim() - block_dim() - 1;
79
+ }
80
+
81
+ private:
82
+ inline int64_t block_dim() const noexcept {
83
+ return (layout_ == kSparseBsr || layout_ == kSparseBsc ? 2 : 0);
84
+ }
85
+
86
+ protected:
87
+ IntArrayRef strides_custom() const override;
88
+ SymIntArrayRef sym_strides_custom() const override;
89
+ bool is_contiguous_custom(MemoryFormat) const override;
90
+
91
+ public:
92
+ void set_size(int64_t dim, int64_t new_size) override;
93
+ void set_stride(int64_t dim, int64_t new_stride) override;
94
+ void set_storage_offset(int64_t storage_offset) override;
95
+ Layout layout_impl() const override {
96
+ return layout_;
97
+ }
98
+ void set_layout(Layout layout) {
99
+ switch (layout) {
100
+ case kSparseCsr:
101
+ case kSparseCsc:
102
+ case kSparseBsr:
103
+ case kSparseBsc:
104
+ layout_ = layout;
105
+ break;
106
+ default:
107
+ TORCH_CHECK(false, "unsupported layout ", layout);
108
+ }
109
+ }
110
+
111
+ template <typename VariableVersion>
112
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach_core(
113
+ VariableVersion&& version_counter,
114
+ bool allow_tensor_metadata_change) const {
115
+ const auto mode_stack_len = c10::impl::TorchDispatchModeTLS::stack_len();
116
+ c10::impl::PyInterpreter&& interpreter = nullptr;
117
+ if (mode_stack_len > 0 &&
118
+ !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) {
119
+ const auto& cur_torch_dispatch_mode_state =
120
+ c10::impl::TorchDispatchModeTLS::get_stack_at(mode_stack_len - 1);
121
+ interpreter = cur_torch_dispatch_mode_state->pyinterpreter();
122
+ } else if (
123
+ key_set_.has(DispatchKey::Python) &&
124
+ !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) {
125
+ interpreter = pyobj_slot_.load_pyobj_interpreter();
126
+ } else {
127
+ // otherwise just copy the SparseTensorImpl and not the PyObject.
128
+ auto impl = c10::make_intrusive<SparseCsrTensorImpl>(
129
+ key_set(), device(), layout_impl(), dtype());
130
+ copy_tensor_metadata(
131
+ /*src_sparse_impl=*/this,
132
+ /*dest_sparse_impl=*/impl.get(),
133
+ /*version_counter=*/version_counter,
134
+ /*allow_tensor_metadata_change=*/allow_tensor_metadata_change);
135
+ impl->refresh_numel();
136
+ return impl;
137
+ }
138
+ auto r = interpreter->detach(this);
139
+ r->set_version_counter(std::forward<VariableVersion>(version_counter));
140
+ r->set_allow_tensor_metadata_change(allow_tensor_metadata_change);
141
+ return r;
142
+ }
143
+
144
+ /**
145
+ * Return a TensorImpl that is a shallow-copy of this TensorImpl.
146
+ *
147
+ * For usage of `version_counter` and `allow_tensor_metadata_change`,
148
+ * see NOTE [ TensorImpl Shallow-Copying ].
149
+ */
150
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
151
+ const c10::VariableVersion& version_counter,
152
+ bool allow_tensor_metadata_change) const override {
153
+ return shallow_copy_and_detach_core(
154
+ version_counter, allow_tensor_metadata_change);
155
+ }
156
+
157
+ /**
158
+ * Return a TensorImpl that is a shallow-copy of this TensorImpl.
159
+ *
160
+ * For usage of `version_counter` and `allow_tensor_metadata_change`,
161
+ * see NOTE [ TensorImpl Shallow-Copying ].
162
+ */
163
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
164
+ c10::VariableVersion&& version_counter,
165
+ bool allow_tensor_metadata_change) const override {
166
+ return shallow_copy_and_detach_core(
167
+ std::move(version_counter), allow_tensor_metadata_change);
168
+ }
169
+
170
+ private:
171
+ explicit SparseCsrTensorImpl(
172
+ at::DispatchKeySet key_set,
173
+ const caffe2::TypeMeta data_type,
174
+ at::Tensor crow_indices,
175
+ at::Tensor col_indices,
176
+ at::Tensor values,
177
+ at::Layout layout);
178
+
179
+ const char* tensorimpl_type_name() const override;
180
+
181
+ /**
182
+ * Copy the tensor metadata fields (e.g. sizes / strides / storage pointer /
183
+ * storage_offset) from one TensorImpl to another TensorImpl.
184
+ *
185
+ * For usage of `version_counter` and `allow_tensor_metadata_change`, see NOTE
186
+ * [ TensorImpl Shallow-Copying ].
187
+ */
188
+ static void copy_tensor_metadata(
189
+ const SparseCsrTensorImpl* src_sparse_impl,
190
+ SparseCsrTensorImpl* dest_sparse_impl,
191
+ c10::VariableVersion version_counter,
192
+ bool allow_tensor_metadata_change) {
193
+ TensorImpl::copy_tensor_metadata(
194
+ src_sparse_impl,
195
+ dest_sparse_impl,
196
+ std::move(version_counter),
197
+ allow_tensor_metadata_change);
198
+
199
+ // Sparse-specific fields
200
+ dest_sparse_impl->crow_indices_ = src_sparse_impl->compressed_indices();
201
+ dest_sparse_impl->col_indices_ = src_sparse_impl->plain_indices();
202
+ dest_sparse_impl->values_ = src_sparse_impl->values();
203
+ dest_sparse_impl->layout_ = src_sparse_impl->layout_impl();
204
+ }
205
+ };
206
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseCsrTensorUtils.h ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/SparseCsrTensorImpl.h>
4
+ #include <ATen/SparseTensorImpl.h>
5
+ #include <ATen/core/Tensor.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/Functions.h>
9
+ #include <ATen/NativeFunctions.h>
10
+ #include <ATen/Operators.h>
11
+ #else
12
+ #include <ATen/ops/_sparse_compressed_tensor_unsafe.h>
13
+ #include <ATen/ops/resize_as_sparse_native.h>
14
+ #endif
15
+
16
+ #define AT_DISPATCH_ALL_SPARSE_COMPRESSED_LAYOUTS(LAYOUT, NAME, ...) \
17
+ [&] { \
18
+ const auto& the_layout = LAYOUT; \
19
+ switch (the_layout) { \
20
+ case kSparseCsr: \
21
+ case kSparseCsc: \
22
+ case kSparseBsr: \
23
+ case kSparseBsc: \
24
+ return __VA_ARGS__(); \
25
+ default: \
26
+ TORCH_CHECK( \
27
+ false, \
28
+ NAME, \
29
+ " expected sparse compressed tensor layout but got ", \
30
+ the_layout); \
31
+ } \
32
+ }()
33
+
34
+ #define AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS( \
35
+ LAYOUT, NAME, ROW_DIM_ACTION, COLUMN_DIM_ACTION) \
36
+ [&]() { \
37
+ const auto& the_layout = LAYOUT; \
38
+ switch (the_layout) { \
39
+ case kSparseCsr: \
40
+ case kSparseBsr: \
41
+ return (ROW_DIM_ACTION)(); \
42
+ case kSparseCsc: \
43
+ case kSparseBsc: \
44
+ return (COLUMN_DIM_ACTION)(); \
45
+ default: \
46
+ TORCH_CHECK( \
47
+ false, \
48
+ NAME, \
49
+ " expected sparse compressed tensor layout but got ", \
50
+ the_layout); \
51
+ } \
52
+ }()
53
+
54
+ #define AT_DISPATCH_PLAIN_SPARSE_COMPRESSED_LAYOUTS( \
55
+ LAYOUT, NAME, NO_BLOCK_ACTION, BLOCK_ACTION) \
56
+ [&]() { \
57
+ const auto& the_layout = LAYOUT; \
58
+ switch (the_layout) { \
59
+ case kSparseCsr: \
60
+ case kSparseCsc: \
61
+ return (NO_BLOCK_ACTION)(); \
62
+ case kSparseBsr: \
63
+ case kSparseBsc: \
64
+ return (BLOCK_ACTION)(); \
65
+ default: \
66
+ TORCH_CHECK( \
67
+ false, \
68
+ NAME, \
69
+ " expected sparse compressed tensor layout but got ", \
70
+ the_layout); \
71
+ } \
72
+ }()
73
+
74
+ #define AT_DISPATCH_SPARSE_ROW_COMPRESSED_LAYOUTS( \
75
+ LAYOUT, NAME, ROW_DIM_ACTION) \
76
+ [&]() { \
77
+ const auto& the_layout = LAYOUT; \
78
+ switch (the_layout) { \
79
+ case kSparseCsr: \
80
+ case kSparseBsr: \
81
+ return (ROW_DIM_ACTION)(); \
82
+ default: \
83
+ TORCH_CHECK( \
84
+ false, \
85
+ NAME, \
86
+ " expected sparse row compressed tensor layout but got ", \
87
+ the_layout); \
88
+ } \
89
+ }()
90
+
91
+ #define AT_DISPATCH_SPARSE_COL_COMPRESSED_LAYOUTS( \
92
+ LAYOUT, NAME, COL_DIM_ACTION) \
93
+ [&]() { \
94
+ const auto& the_layout = LAYOUT; \
95
+ switch (the_layout) { \
96
+ case kSparseCsc: \
97
+ case kSparseBsc: \
98
+ return (COL_DIM_ACTION)(); \
99
+ default: \
100
+ TORCH_CHECK( \
101
+ false, \
102
+ NAME, \
103
+ " expected sparse column compressed tensor layout but got ", \
104
+ the_layout); \
105
+ } \
106
+ }()
107
+
108
+ #define AT_DISPATCH_SPARSE_COMPRESSED_NONBLOCK_LAYOUTS(LAYOUT, NAME, ACTION) \
109
+ [&]() { \
110
+ const auto& the_layout = LAYOUT; \
111
+ switch (the_layout) { \
112
+ case kSparseCsr: \
113
+ case kSparseCsc: \
114
+ return (ACTION)(); \
115
+ default: \
116
+ TORCH_CHECK( \
117
+ false, \
118
+ NAME, \
119
+ " expected sparse compressed (non-block) tensor layout but got ", \
120
+ the_layout); \
121
+ } \
122
+ }()
123
+
124
+ #define AT_DISPATCH_SPARSE_COMPRESSED_BLOCK_LAYOUTS(LAYOUT, NAME, ACTION) \
125
+ [&]() { \
126
+ const auto& the_layout = LAYOUT; \
127
+ switch (the_layout) { \
128
+ case kSparseBsr: \
129
+ case kSparseBsc: \
130
+ return (ACTION)(); \
131
+ default: \
132
+ TORCH_CHECK( \
133
+ false, \
134
+ NAME, \
135
+ " expected sparse compressed block tensor layout but got ", \
136
+ the_layout); \
137
+ } \
138
+ }()
139
+
140
+ #define AT_DISPATCH_SPARSE_VALUE_TYPES(TYPE, NAME, ...) \
141
+ AT_DISPATCH_SWITCH( \
142
+ TYPE, \
143
+ NAME, \
144
+ AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND4( \
145
+ kComplexHalf, kHalf, kBool, kBFloat16, __VA_ARGS__))
146
+
147
+ namespace at::sparse_csr {
148
+
149
+ // Implements RAII object to manage checking sparse tensor invariants:
150
+ class CheckSparseTensorInvariants {
151
+ bool old_state;
152
+
153
+ public:
154
+ CheckSparseTensorInvariants(bool state)
155
+ : old_state(at::globalContext().checkSparseTensorInvariants()) {
156
+ at::globalContext().setCheckSparseTensorInvariants(state);
157
+ }
158
+ CheckSparseTensorInvariants(CheckSparseTensorInvariants&& other) = delete;
159
+ CheckSparseTensorInvariants(const CheckSparseTensorInvariants&) = delete;
160
+ CheckSparseTensorInvariants& operator=(const CheckSparseTensorInvariants&) =
161
+ delete;
162
+ CheckSparseTensorInvariants& operator=(CheckSparseTensorInvariants&&) =
163
+ delete;
164
+
165
+ ~CheckSparseTensorInvariants() {
166
+ at::globalContext().setCheckSparseTensorInvariants(old_state);
167
+ }
168
+ };
169
+
170
+ using SparseCsrTensor = Tensor;
171
+
172
+ inline bool is_sparse_compressed(const Layout& layout) {
173
+ switch (layout) {
174
+ case kSparseCsr:
175
+ case kSparseCsc:
176
+ case kSparseBsr:
177
+ case kSparseBsc:
178
+ return true;
179
+ default:;
180
+ }
181
+ return false;
182
+ }
183
+
184
+ inline bool is_sparse_compressed(const Tensor& self) {
185
+ return is_sparse_compressed(self.layout());
186
+ }
187
+
188
+ inline SparseCsrTensorImpl* get_sparse_csr_impl(const SparseCsrTensor& self) {
189
+ AT_DISPATCH_ALL_SPARSE_COMPRESSED_LAYOUTS(
190
+ self.layout(), "get_sparse_csr_impl", [&] {});
191
+ return static_cast<SparseCsrTensorImpl*>(self.unsafeGetTensorImpl());
192
+ }
193
+
194
+ inline std::string layoutToString(
195
+ Layout layout,
196
+ bool upper = false,
197
+ bool lower = false) {
198
+ switch (layout) {
199
+ case kSparseCsr:
200
+ return (upper ? "CSR" : (lower ? "csr" : "Csr"));
201
+ case kSparseCsc:
202
+ return (upper ? "CSC" : (lower ? "csc" : "Csc"));
203
+ case kSparseBsr:
204
+ return (upper ? "BSR" : (lower ? "bsr" : "Bsr"));
205
+ case kSparseBsc:
206
+ return (upper ? "BSC" : (lower ? "bsc" : "Bsc"));
207
+ default:
208
+ TORCH_CHECK(false, "Not a sparse compressed layout:", layout);
209
+ return "";
210
+ }
211
+ }
212
+
213
+ inline bool isCompressedRow(Layout layout) {
214
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
215
+ layout, "isCompressedRow", [&] { return true; }, [&] { return false; });
216
+ }
217
+
218
+ inline bool isCompressedColumn(Layout layout) {
219
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
220
+ layout,
221
+ "isCompressedColumn",
222
+ [&] { return false; },
223
+ [&] { return true; });
224
+ }
225
+
226
+ inline std::string compressedIndicesName(Layout layout) {
227
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
228
+ layout,
229
+ "compressedIndicesName",
230
+ [&] { return "crow_indices"; },
231
+ [&] { return "ccol_indices"; });
232
+ }
233
+
234
+ inline std::string plainIndicesName(Layout layout) {
235
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
236
+ layout,
237
+ "plainIndicesName",
238
+ [&] { return "col_indices"; },
239
+ [&] { return "row_indices"; });
240
+ }
241
+
242
+ inline std::string compressedDimName(Layout layout) {
243
+ switch (layout) {
244
+ case kSparseCsr:
245
+ return "row";
246
+ case kSparseCsc:
247
+ return "column";
248
+ case kSparseBsr:
249
+ return "row block";
250
+ case kSparseBsc:
251
+ return "column block";
252
+ default:
253
+ TORCH_CHECK(false, "Not a sparse compressed layout:", layout);
254
+ return "";
255
+ }
256
+ }
257
+
258
+ inline std::string plainDimName(Layout layout) {
259
+ switch (layout) {
260
+ case kSparseCsr:
261
+ return "column";
262
+ case kSparseCsc:
263
+ return "row";
264
+ case kSparseBsr:
265
+ return "column block";
266
+ case kSparseBsc:
267
+ return "row block";
268
+ default:
269
+ TORCH_CHECK(false, "Not a sparse compressed layout:", layout);
270
+ return "";
271
+ }
272
+ }
273
+
274
+ inline size_t rowDimension(Layout layout, IntArrayRef size) {
275
+ return size.size() - (isCompressedRow(layout) ? 2 : 1);
276
+ }
277
+
278
+ inline size_t columnDimension(Layout layout, IntArrayRef size) {
279
+ return size.size() - (isCompressedColumn(layout) ? 2 : 1);
280
+ }
281
+
282
+ inline size_t compressedDimension(
283
+ Layout layout,
284
+ IntArrayRef size,
285
+ size_t dense_ndim = 0) {
286
+ return size.size() - dense_ndim - (isCompressedRow(layout) ? 2 : 1);
287
+ }
288
+
289
+ inline size_t plainDimension(
290
+ Layout layout,
291
+ IntArrayRef size,
292
+ size_t dense_ndim = 0) {
293
+ return size.size() - dense_ndim - (isCompressedRow(layout) ? 1 : 2);
294
+ }
295
+
296
+ inline int64_t numBatchDimensions(Tensor const& self) {
297
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
298
+ self.layout(),
299
+ "numBatchDimensions",
300
+ [&self] { return self.crow_indices().dim() - 1; },
301
+ [&self] { return self.ccol_indices().dim() - 1; });
302
+ }
303
+
304
+ inline std::pair<Tensor, Tensor> getCompressedPlainIndices(Tensor const& self) {
305
+ return AT_DISPATCH_ROW_SPARSE_COMPRESSED_LAYOUTS(
306
+ self.layout(),
307
+ "getCompressedPlainIndices",
308
+ [&self] {
309
+ return std::make_pair(self.crow_indices(), self.col_indices());
310
+ },
311
+ [&self] {
312
+ return std::make_pair(self.ccol_indices(), self.row_indices());
313
+ });
314
+ }
315
+
316
+ inline ScalarType getIndexDtype(Tensor const& self) {
317
+ switch (self.layout()) {
318
+ case kSparseCsr:
319
+ case kSparseBsr:
320
+ return self.crow_indices().scalar_type();
321
+ case kSparseCsc:
322
+ case kSparseBsc:
323
+ return self.ccol_indices().scalar_type();
324
+ case kSparse:
325
+ return self._indices().scalar_type();
326
+ default:
327
+ return ScalarType::Long;
328
+ }
329
+ }
330
+
331
+ inline Layout flip_compressed_layout(Layout layout) {
332
+ switch (layout) {
333
+ case kSparseCsr:
334
+ return kSparseCsc;
335
+ case kSparseCsc:
336
+ return kSparseCsr;
337
+ case kSparseBsr:
338
+ return kSparseBsc;
339
+ case kSparseBsc:
340
+ return kSparseBsr;
341
+ default:
342
+ TORCH_CHECK(false, "Not a sparse compressed layout:", layout);
343
+ return kSparseCsr;
344
+ }
345
+ }
346
+
347
+ inline DimVector getBlockSize(Tensor const& self) {
348
+ int64_t n_batch = numBatchDimensions(self);
349
+ return at::DimVector(self.values().sizes().slice(n_batch + 1, 2));
350
+ }
351
+
352
+ inline at::OptionalArray<at::SymInt> getSymIntBlockSize(Tensor const& self) {
353
+ if (self.layout() == at::kSparseBsr || self.layout() == at::kSparseBsc) {
354
+ int64_t n_batch = numBatchDimensions(self);
355
+ return self.values().sym_sizes().slice(n_batch + 1, 2).vec();
356
+ } else {
357
+ return {};
358
+ }
359
+ }
360
+
361
+ template <typename binary_op_t, typename binary_op_out_t>
362
+ inline bool only_sparse_compressed_binary_op_trivial_cases(
363
+ const Tensor& self,
364
+ const Tensor& other,
365
+ const Scalar& alpha,
366
+ Tensor& out,
367
+ const binary_op_t& binary_op,
368
+ const binary_op_out_t& binary_op_out) {
369
+ // Only sparse compressed! Just like the name says :)
370
+ TORCH_INTERNAL_ASSERT(at::sparse_csr::is_sparse_compressed(self));
371
+ TORCH_INTERNAL_ASSERT(at::sparse_csr::is_sparse_compressed(other));
372
+ TORCH_INTERNAL_ASSERT(at::sparse_csr::is_sparse_compressed(out));
373
+
374
+ // Bypass BLAS if there are matches in (self, other, out)
375
+ if (self.is_same(out) && self.is_same(other)) {
376
+ binary_op_out(self.values(), other.values(), alpha);
377
+ return true;
378
+ }
379
+ if (self.is_same(other)) {
380
+ auto [compressed_indices, plain_indices] =
381
+ at::sparse_csr::getCompressedPlainIndices(self);
382
+ static_cast<SparseCsrTensorImpl*>(out.unsafeGetTensorImpl())
383
+ ->set_member_tensors(
384
+ compressed_indices,
385
+ plain_indices,
386
+ binary_op(self.values(), other.values(), alpha),
387
+ self.sizes());
388
+ return true;
389
+ }
390
+ return false;
391
+ }
392
+
393
+ inline bool only_sparse_compressed_add_trivial_cases(
394
+ const Tensor& self,
395
+ const Tensor& other,
396
+ const Scalar& alpha,
397
+ Tensor& out) {
398
+ return only_sparse_compressed_binary_op_trivial_cases(
399
+ self,
400
+ other,
401
+ alpha,
402
+ out,
403
+ [](const Tensor& v1, const Tensor& v2, const Scalar& alpha) {
404
+ return v1.add(v2, alpha);
405
+ },
406
+ [](const Tensor& v1, const Tensor& v2, const Scalar& alpha) {
407
+ return v1.add_(v2, alpha);
408
+ });
409
+ }
410
+
411
+ inline Tensor to_type(const Tensor& input, ScalarType dtype) {
412
+ auto [compressed_indices, plain_indices] =
413
+ at::sparse_csr::getCompressedPlainIndices(input);
414
+ return at::_sparse_compressed_tensor_unsafe(
415
+ compressed_indices,
416
+ plain_indices,
417
+ std::move(input.values()).to(dtype),
418
+ input.sizes(),
419
+ dtype,
420
+ input.layout(),
421
+ input.device(),
422
+ input.options().pinned_memory_opt());
423
+ }
424
+
425
+ template <typename acc_t, typename scalar_t>
426
+ inline std::tuple<Tensor, Tensor> create_acc_buffer(
427
+ TensorOptions option,
428
+ ScalarType type,
429
+ int64_t nnz = -1) {
430
+ Tensor new_values, new_values_acc;
431
+ constexpr bool need_acc = !std::is_same_v<scalar_t, acc_t>;
432
+ bool is_integral = at::isIntegralType(type, /*includeBool=*/true);
433
+ if constexpr (need_acc) {
434
+ auto acc_dtype = CppTypeToScalarType<acc_t>::value;
435
+ new_values_acc = at::empty({}, option.dtype(acc_dtype));
436
+ new_values = is_integral ? new_values_acc : at::empty({}, option);
437
+ } else {
438
+ new_values = new_values_acc = at::empty({}, option);
439
+ }
440
+ if (nnz != -1) {
441
+ return std::make_tuple(
442
+ new_values.resize_(nnz), new_values_acc.resize_(nnz));
443
+ } else {
444
+ return std::make_tuple(new_values, new_values_acc);
445
+ }
446
+ }
447
+
448
+ inline void copy_from_acc_buffer(Tensor& new_values, Tensor& new_values_acc) {
449
+ if (!new_values_acc.is_same(new_values)) {
450
+ new_values.copy_(new_values_acc);
451
+ }
452
+ }
453
+
454
+ } // namespace at::sparse_csr
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/SparseTensorImpl.h ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/core/TensorImpl.h>
5
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
6
+ #include <c10/util/Exception.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ #ifndef AT_PER_OPERATOR_HEADERS
10
+ #include <ATen/Functions.h>
11
+ #else
12
+ #include <ATen/ops/empty.h>
13
+ #include <ATen/ops/resize.h>
14
+ #endif
15
+
16
+ namespace at {
17
+ struct TORCH_API SparseTensorImpl : public TensorImpl {
18
+ // Stored in COO format, indices + values.
19
+
20
+ // INVARIANTS:
21
+ // sparse_dim: range [0, len(shape)]; sparse_dim + dense_dim = len(shape)
22
+ // dense_dim : range [0, len(shape)]; sparse_dim + dense_dim = len(shape)
23
+ // _indices.shape: dimensionality: 2, shape: (sparse_dim, nnz)
24
+ // _values.shape: dimensionality: 1 + dense_dim. shape: (nnz,
25
+ // shape[sparse_dim:])
26
+
27
+ int64_t sparse_dim_ = 0; // number of sparse dimensions
28
+ int64_t dense_dim_ = 0; // number of dense dimensions
29
+
30
+ Tensor indices_; // always a LongTensor
31
+ Tensor values_;
32
+
33
+ // A sparse tensor is 'coalesced' if every index occurs at most once in
34
+ // the indices tensor, and the indices are in sorted order. (This means
35
+ // that it is very easy to convert a coalesced tensor to CSR format: you
36
+ // need only compute CSR format indices.)
37
+ //
38
+ // Most math operations can only be performed on coalesced sparse tensors,
39
+ // because many algorithms proceed by merging two sorted lists (of indices).
40
+ bool coalesced_ = false;
41
+
42
+ // compute_numel with integer multiplication overflow check, see gh-57542
43
+ void refresh_numel() {
44
+ TensorImpl::safe_refresh_numel();
45
+ }
46
+
47
+ public:
48
+ // Public for now...
49
+ explicit SparseTensorImpl(at::DispatchKeySet, const caffe2::TypeMeta);
50
+
51
+ void release_resources() override;
52
+
53
+ int64_t nnz() const {
54
+ return values_.size(0);
55
+ }
56
+
57
+ c10::SymInt sym_nnz() const {
58
+ return values_.sym_size(0);
59
+ }
60
+ int64_t sparse_dim() const {
61
+ return sparse_dim_;
62
+ }
63
+ int64_t dense_dim() const {
64
+ return dense_dim_;
65
+ }
66
+ bool coalesced() const {
67
+ return coalesced_;
68
+ }
69
+ Tensor indices() const {
70
+ return indices_;
71
+ }
72
+ Tensor values() const {
73
+ return values_;
74
+ }
75
+
76
+ void set_size(int64_t dim, int64_t new_size) override;
77
+ void set_stride(int64_t dim, int64_t new_stride) override;
78
+ void set_storage_offset(int64_t storage_offset) override;
79
+
80
+ #ifdef DEBUG
81
+ bool has_storage() const override;
82
+ #endif
83
+
84
+ // WARNING: This function does NOT preserve invariants of sparse_dim/dense_dim
85
+ // with respect to indices and values
86
+ void raw_resize_(int64_t sparse_dim, int64_t dense_dim, IntArrayRef size) {
87
+ TORCH_CHECK(
88
+ allow_tensor_metadata_change(),
89
+ "raw_resize_ ",
90
+ err_msg_tensor_metadata_change_not_allowed);
91
+ TORCH_CHECK(
92
+ !has_symbolic_sizes_strides_,
93
+ "raw_resize_ called on tensor with symbolic shape")
94
+ set_sizes_and_strides(size, std::vector<int64_t>(size.size()));
95
+ sparse_dim_ = sparse_dim;
96
+ dense_dim_ = dense_dim;
97
+ refresh_numel();
98
+ }
99
+
100
+ // NOTE: This function preserves invariants of sparse_dim/dense_dim with
101
+ // respect to indices and values.
102
+ //
103
+ // NOTE: This function supports the following cases:
104
+ // 1. When we keep the number of dense dimensions unchanged, and NOT shrinking
105
+ // the size of any of the dense dimensions.
106
+ // 2. When we keep the number of sparse dimensions unchanged, and NOT
107
+ // shrinking the size of any of the sparse dimensions.
108
+ // 3. When the sparse tensor has zero nnz, in which case we are free to change
109
+ // the shapes of both its sparse and dense dimensions.
110
+ //
111
+ // This function DOESN'T support (and will throw an error) the following
112
+ // cases:
113
+ // 1. When we attempt to change the number of sparse dimensions on a non-empty
114
+ // sparse tensor (such an operation will invalidate the indices stored).
115
+ // 2. When we attempt to change the number of dense dimensions on a non-empty
116
+ // sparse tensor (such an operation will behave differently from an equivalent
117
+ // dense tensor's resize method, and for API consistency we don't support it).
118
+ // 3. When we attempt to shrink the size of any of the dense dimensions on a
119
+ // non-empty sparse tensor (such an operation will behave differently from an
120
+ // equivalent dense tensor's resize method, and for API consistency we don't
121
+ // support it).
122
+ // 4. When we attempt to shrink the size of any of the sparse dimensions on a
123
+ // non-empty sparse tensor (this could make some of the stored indices
124
+ // out-of-bound and thus unsafe).
125
+ template <typename T>
126
+ void _resize_(int64_t sparse_dim, int64_t dense_dim, ArrayRef<T> size) {
127
+ TORCH_CHECK(
128
+ allow_tensor_metadata_change(),
129
+ "resize_ ",
130
+ err_msg_tensor_metadata_change_not_allowed);
131
+ TORCH_CHECK(
132
+ !has_symbolic_sizes_strides_,
133
+ "resize_ called on tensor with symbolic shape")
134
+ TORCH_CHECK(
135
+ sparse_dim + dense_dim == static_cast<int64_t>(size.size()),
136
+ "number of dimensions must be sparse_dim (",
137
+ sparse_dim,
138
+ ") + dense_dim (",
139
+ dense_dim,
140
+ "), but got ",
141
+ size.size());
142
+ if (nnz() > 0) {
143
+ [[maybe_unused]] auto constexpr alt_options_msg =
144
+ "You could try the following options:\n\
145
+ 1. If you need an empty sparse tensor of this size, call `x = torch.sparse_coo_tensor(size)`.\n\
146
+ 2. If you need to resize this tensor, you have the following options:\n\
147
+ 1. For both sparse and dense dimensions, keep the number of them constant and the size of them non-shrinking, and then try the same call again.\n\
148
+ 2. Or, create a new sparse tensor with the correct indices and values from this sparse tensor.";
149
+
150
+ TORCH_CHECK(
151
+ sparse_dim == sparse_dim_,
152
+ "changing the number of sparse dimensions (from ",
153
+ sparse_dim_,
154
+ " to ",
155
+ sparse_dim,
156
+ ") on a non-empty sparse tensor is not supported.\n",
157
+ alt_options_msg);
158
+
159
+ TORCH_CHECK(
160
+ dense_dim == dense_dim_,
161
+ "changing the number of dense dimensions (from ",
162
+ dense_dim_,
163
+ " to ",
164
+ dense_dim,
165
+ ") on a non-empty sparse tensor is not supported.\n",
166
+ alt_options_msg);
167
+
168
+ bool shrinking_sparse_dims = false;
169
+ bool shrinking_dense_dim = false;
170
+ auto sparse_size_original = generic_sizes<T>().slice(0, sparse_dim);
171
+ auto sparse_size_new = size.slice(0, sparse_dim);
172
+ for (const auto i : c10::irange(sparse_dim)) {
173
+ if (sparse_size_new[i] < sparse_size_original[i]) {
174
+ shrinking_sparse_dims = true;
175
+ break;
176
+ }
177
+ }
178
+ auto dense_size_original = generic_sizes<T>().slice(sparse_dim);
179
+ auto dense_size_new = size.slice(sparse_dim);
180
+ for (const auto i : c10::irange(dense_dim)) {
181
+ if (dense_size_new[i] < dense_size_original[i]) {
182
+ shrinking_dense_dim = true;
183
+ break;
184
+ }
185
+ }
186
+
187
+ TORCH_CHECK(
188
+ !shrinking_sparse_dims,
189
+ "shrinking the size of sparse dimensions (from ",
190
+ sparse_size_original,
191
+ " to ",
192
+ sparse_size_new,
193
+ ") on a non-empty sparse tensor is not supported.\n",
194
+ alt_options_msg);
195
+
196
+ TORCH_CHECK(
197
+ !shrinking_dense_dim,
198
+ "shrinking the size of dense dimensions (from ",
199
+ dense_size_original,
200
+ " to ",
201
+ dense_size_new,
202
+ ") on a non-empty sparse tensor is not supported.\n",
203
+ alt_options_msg);
204
+ }
205
+
206
+ auto sizes_and_strides = generic_sizes<T>();
207
+ const bool size_equals_sizes = std::equal(
208
+ size.begin(),
209
+ size.end(),
210
+ sizes_and_strides.begin(),
211
+ sizes_and_strides.end());
212
+ if ((!size_equals_sizes) || (sparse_dim != sparse_dim_) ||
213
+ (dense_dim != dense_dim_)) {
214
+ auto nnz = at::symint::sizes<T>(values())[0];
215
+ std::vector<T> values_size = {nnz};
216
+ auto dense_size = size.slice(sparse_dim);
217
+ values_size.insert(
218
+ values_size.end(), dense_size.begin(), dense_size.end());
219
+ at::symint::resize_<T>(values_, values_size);
220
+ at::symint::resize_<T>(indices_, {T(sparse_dim), nnz});
221
+ }
222
+
223
+ if (!size_equals_sizes) {
224
+ set_sizes_and_strides(size, std::vector<T>(size.size()));
225
+ }
226
+ sparse_dim_ = sparse_dim;
227
+ dense_dim_ = dense_dim;
228
+ refresh_numel();
229
+ }
230
+
231
+ void resize_(int64_t sparse_dim, int64_t dense_dim, ArrayRef<int64_t> size) {
232
+ return _resize_(sparse_dim, dense_dim, size);
233
+ }
234
+
235
+ void resize_(
236
+ int64_t sparse_dim,
237
+ int64_t dense_dim,
238
+ ArrayRef<c10::SymInt> size) {
239
+ return _resize_(sparse_dim, dense_dim, size);
240
+ }
241
+
242
+ // NOTE: this function will resize the sparse tensor and also set `indices`
243
+ // and `values` to empty.
244
+ void resize_and_clear_(
245
+ int64_t sparse_dim,
246
+ int64_t dense_dim,
247
+ IntArrayRef size) {
248
+ TORCH_CHECK(
249
+ allow_tensor_metadata_change(),
250
+ "resize_and_clear_ ",
251
+ err_msg_tensor_metadata_change_not_allowed);
252
+ TORCH_CHECK(
253
+ !has_symbolic_sizes_strides_,
254
+ "resize_and_clear_ called on tensor with symbolic shape")
255
+ TORCH_CHECK(
256
+ sparse_dim + dense_dim == static_cast<int64_t>(size.size()),
257
+ "number of dimensions must be sparse_dim (",
258
+ sparse_dim,
259
+ ") + dense_dim (",
260
+ dense_dim,
261
+ "), but got ",
262
+ size.size());
263
+
264
+ set_sizes_and_strides(size, std::vector<int64_t>(size.size()));
265
+ sparse_dim_ = sparse_dim;
266
+ dense_dim_ = dense_dim;
267
+
268
+ auto empty_indices = at::empty({sparse_dim, 0}, indices().options());
269
+ std::vector<int64_t> values_size = {0};
270
+ auto dense_size = sizes().slice(sparse_dim);
271
+ values_size.insert(values_size.end(), dense_size.begin(), dense_size.end());
272
+ auto empty_values = at::empty(values_size, values().options());
273
+ set_indices_and_values_unsafe(empty_indices, empty_values);
274
+ refresh_numel();
275
+ }
276
+
277
+ void set_coalesced(bool coalesced) {
278
+ TORCH_CHECK(
279
+ allow_tensor_metadata_change(),
280
+ "set_coalesced ",
281
+ err_msg_tensor_metadata_change_not_allowed);
282
+ coalesced_ = coalesced;
283
+ }
284
+
285
+ // NOTE: this function is only used internally and not exposed to Python
286
+ // frontend
287
+ void set_nnz_and_narrow(int64_t new_nnz) {
288
+ TORCH_CHECK(
289
+ allow_tensor_metadata_change(),
290
+ "set_nnz_and_narrow ",
291
+ err_msg_tensor_metadata_change_not_allowed);
292
+ AT_ASSERT(new_nnz <= nnz());
293
+ indices_ = indices_.narrow(1, 0, new_nnz);
294
+ values_ = values_.narrow(0, 0, new_nnz);
295
+ if (new_nnz < 2) {
296
+ coalesced_ = true;
297
+ }
298
+ }
299
+
300
+ // Takes indices and values and directly puts them into the sparse tensor, no
301
+ // copy. NOTE: this function is unsafe because it doesn't check whether any
302
+ // indices are out of boundaries of `sizes`, so it should ONLY be used where
303
+ // we know that the indices are guaranteed to be within bounds. This used to
304
+ // be called THSTensor_(_move) NB: This used to be able to avoid a refcount
305
+ // bump, but I was too lazy to make it happen
306
+ void set_indices_and_values_unsafe(
307
+ const Tensor& indices,
308
+ const Tensor& values);
309
+
310
+ template <typename VariableVersion>
311
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach_core(
312
+ VariableVersion&& version_counter,
313
+ bool allow_tensor_metadata_change) const {
314
+ const auto mode_stack_len = c10::impl::TorchDispatchModeTLS::stack_len();
315
+ c10::impl::PyInterpreter&& interpreter = nullptr;
316
+ if (mode_stack_len > 0 &&
317
+ !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) {
318
+ const auto& cur_torch_dispatch_mode_state =
319
+ c10::impl::TorchDispatchModeTLS::get_stack_at(mode_stack_len - 1);
320
+ interpreter = cur_torch_dispatch_mode_state->pyinterpreter();
321
+ } else if (
322
+ key_set_.has(DispatchKey::Python) &&
323
+ !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) {
324
+ interpreter = pyobj_slot_.load_pyobj_interpreter();
325
+ } else {
326
+ // otherwise just copy the SparseTensorImpl and not the PyObject.
327
+ auto impl = c10::make_intrusive<SparseTensorImpl>(key_set(), dtype());
328
+ copy_tensor_metadata(
329
+ /*src_sparse_impl=*/this,
330
+ /*dest_sparse_impl=*/impl.get(),
331
+ /*version_counter=*/version_counter,
332
+ /*allow_tensor_metadata_change=*/allow_tensor_metadata_change);
333
+ impl->refresh_numel();
334
+ return impl;
335
+ }
336
+ auto r = interpreter->detach(this);
337
+ r->set_version_counter(std::forward<VariableVersion>(version_counter));
338
+ r->set_allow_tensor_metadata_change(allow_tensor_metadata_change);
339
+ return r;
340
+ }
341
+
342
+ /**
343
+ * Return a TensorImpl that is a shallow-copy of this TensorImpl.
344
+ *
345
+ * For usage of `version_counter` and `allow_tensor_metadata_change`,
346
+ * see NOTE [ TensorImpl Shallow-Copying ].
347
+ */
348
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
349
+ const c10::VariableVersion& version_counter,
350
+ bool allow_tensor_metadata_change) const override {
351
+ return shallow_copy_and_detach_core(
352
+ version_counter, allow_tensor_metadata_change);
353
+ }
354
+
355
+ /**
356
+ * Return a TensorImpl that is a shallow-copy of this TensorImpl.
357
+ *
358
+ * For usage of `version_counter` and `allow_tensor_metadata_change`,
359
+ * see NOTE [ TensorImpl Shallow-Copying ].
360
+ */
361
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
362
+ c10::VariableVersion&& version_counter,
363
+ bool allow_tensor_metadata_change) const override {
364
+ return shallow_copy_and_detach_core(
365
+ std::move(version_counter), allow_tensor_metadata_change);
366
+ }
367
+
368
+ /**
369
+ * Shallow-copies data from another TensorImpl into this TensorImpl.
370
+ *
371
+ * For why this function doesn't check this TensorImpl's
372
+ * `allow_tensor_metadata_change_`, see NOTE [ TensorImpl Shallow-Copying ].
373
+ */
374
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override {
375
+ AT_ASSERT(has_compatible_shallow_copy_type(impl->key_set()));
376
+ auto sparse_impl = static_cast<const SparseTensorImpl*>(impl.get());
377
+ copy_tensor_metadata(
378
+ /*src_sparse_impl=*/sparse_impl,
379
+ /*dest_sparse_impl=*/this,
380
+ /*version_counter=*/version_counter(),
381
+ /*allow_tensor_metadata_change=*/allow_tensor_metadata_change());
382
+ refresh_numel();
383
+ }
384
+
385
+ private:
386
+ explicit SparseTensorImpl(
387
+ at::DispatchKeySet,
388
+ const caffe2::TypeMeta,
389
+ at::Tensor indices,
390
+ at::Tensor values);
391
+
392
+ /**
393
+ * Copy the tensor metadata fields (e.g. sizes / strides / storage pointer /
394
+ * storage_offset) from one TensorImpl to another TensorImpl.
395
+ *
396
+ * For usage of `version_counter` and `allow_tensor_metadata_change`, see NOTE
397
+ * [ TensorImpl Shallow-Copying ].
398
+ */
399
+ static void copy_tensor_metadata(
400
+ const SparseTensorImpl* src_sparse_impl,
401
+ SparseTensorImpl* dest_sparse_impl,
402
+ c10::VariableVersion version_counter,
403
+ bool allow_tensor_metadata_change) {
404
+ TensorImpl::copy_tensor_metadata(
405
+ src_sparse_impl,
406
+ dest_sparse_impl,
407
+ std::move(version_counter),
408
+ allow_tensor_metadata_change);
409
+
410
+ // Sparse-specific fields
411
+ dest_sparse_impl->sparse_dim_ = src_sparse_impl->sparse_dim();
412
+ dest_sparse_impl->dense_dim_ = src_sparse_impl->dense_dim();
413
+ dest_sparse_impl->indices_ = src_sparse_impl->indices();
414
+ dest_sparse_impl->values_ = src_sparse_impl->values();
415
+ dest_sparse_impl->coalesced_ = src_sparse_impl->coalesced();
416
+ }
417
+
418
+ const char* tensorimpl_type_name() const override;
419
+ };
420
+
421
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Storage.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <c10/core/Storage.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/StorageUtils.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Storage.h>
4
+ #include <c10/core/StorageImpl.h>
5
+ #include <c10/util/intrusive_ptr.h>
6
+
7
+ namespace at {
8
+
9
+ class TensorBase;
10
+
11
+ // Here we define a series of utils to create/manipulate ATen backed
12
+ // c10 storage implementations.
13
+
14
+ /**
15
+ * Create a new shared memory storage impl managed by file descriptor
16
+ *
17
+ * @param size size in bytes
18
+ */
19
+ C10_EXPORT c10::intrusive_ptr<c10::StorageImpl> new_shm_fd_storage(size_t size);
20
+
21
+ /**
22
+ * Copy src to dst
23
+ * Caller must guarantee the validness of the storage objects
24
+ * during the entire copy process, esp. when it's async.
25
+ *
26
+ * This can probably live in c10 namespace later if needed,
27
+ * but for now keep it in at to keep implementation simple.
28
+ *
29
+ * @param dst dst tensor
30
+ * @param src src tensor
31
+ * @param non_blocking (default false) whether this operation blocks caller
32
+ */
33
+ C10_EXPORT void storage_copy(
34
+ c10::Storage& dst,
35
+ const c10::Storage& src,
36
+ bool non_blocking = false);
37
+
38
+ /**
39
+ * In place change the storage to shm based.
40
+ *
41
+ * This is only applicable to CPU tensors not already shared.
42
+ * Otherwise, it's a no op to mirror the THP tensor behavior:
43
+ * https://pytorch.org/docs/stable/generated/torch.Tensor.share_memory_.html
44
+ *
45
+ * @param t a tensor
46
+ */
47
+ C10_EXPORT void share_memory_(TensorBase& t);
48
+
49
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Tensor.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorAccessor.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/TensorAccessor.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorGeometry.h ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <c10/core/WrapDimMinimal.h>
5
+
6
+ namespace at {
7
+
8
+ // Return if the tensor geometry represented by `sizes` and `strides` is
9
+ // contiguous Although we cache is_contiguous in tensor now, this is till useful
10
+ // because it allows checking if a particular geometry is contiguous without
11
+ // explicitly constructing a tensor, e.g., when you want to choose a kernel
12
+ // strategy based on whether a subgeometry is contiguous.
13
+ TORCH_API bool geometry_is_contiguous(IntArrayRef sizes, IntArrayRef strides);
14
+
15
+ struct TORCH_API TensorGeometry {
16
+ TensorGeometry() = default;
17
+
18
+ explicit TensorGeometry(c10::SymIntArrayRef sizes)
19
+ : sizes_(sizes.vec()),
20
+ strides_(sizes.size()),
21
+ has_symbolic_sizes_strides_(
22
+ !c10::asIntArrayRefSlowOpt(sizes).has_value()) {
23
+ int64_t dim = static_cast<int64_t>(sizes.size());
24
+ c10::SymInt expected_stride = 1;
25
+ for (int64_t i = dim - 1; i >= 0; i--) {
26
+ strides_[i] = expected_stride;
27
+ expected_stride *= sizes_[i];
28
+ }
29
+ numel_ = expected_stride;
30
+ }
31
+
32
+ explicit TensorGeometry(const TensorBase& t)
33
+ : sizes_(t.sym_sizes().vec()),
34
+ strides_(t.sym_strides().vec()),
35
+ storage_offset_(t.sym_storage_offset()),
36
+ numel_(t.sym_numel()),
37
+ has_symbolic_sizes_strides_(
38
+ t.unsafeGetTensorImpl()->has_symbolic_sizes_strides()) {}
39
+
40
+ explicit TensorGeometry(
41
+ std::vector<at::SymInt> sizes,
42
+ std::vector<at::SymInt> strides,
43
+ at::SymInt storage_offset)
44
+ : sizes_(std::move(sizes)),
45
+ strides_(std::move(strides)),
46
+ storage_offset_(std::move(storage_offset)) {
47
+ recompute();
48
+ }
49
+
50
+ // true if the tensor is contiguous
51
+ bool is_contiguous() const;
52
+
53
+ int64_t dim() const {
54
+ return static_cast<int64_t>(sizes_.size());
55
+ }
56
+
57
+ int64_t size(int64_t dim) const {
58
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
59
+ dim = c10::maybe_wrap_dim(dim, this->dim());
60
+ return sizes_.at(static_cast<size_t>(dim)).as_int_unchecked();
61
+ }
62
+ c10::IntArrayRef sizes() const {
63
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
64
+ return c10::asIntArrayRefUnchecked(sizes_);
65
+ }
66
+ int64_t stride(int64_t dim) const {
67
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
68
+ dim = c10::maybe_wrap_dim(dim, this->dim());
69
+ return strides_.at(static_cast<size_t>(dim)).as_int_unchecked();
70
+ }
71
+ c10::IntArrayRef strides() const {
72
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
73
+ return c10::asIntArrayRefUnchecked(strides_);
74
+ }
75
+ int64_t storage_offset() const {
76
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
77
+ return storage_offset_.as_int_unchecked();
78
+ }
79
+ int64_t numel() const {
80
+ TORCH_INTERNAL_ASSERT(!has_symbolic_sizes_strides_);
81
+ return numel_.as_int_unchecked();
82
+ }
83
+
84
+ c10::SymInt sym_size(int64_t dim) const {
85
+ dim = c10::maybe_wrap_dim(dim, this->dim());
86
+ return sizes_.at(static_cast<size_t>(dim));
87
+ }
88
+ c10::SymIntArrayRef sym_sizes() const {
89
+ return sizes_;
90
+ }
91
+ c10::SymInt sym_stride(int64_t dim) const {
92
+ dim = c10::maybe_wrap_dim(dim, this->dim());
93
+ return strides_.at(static_cast<size_t>(dim));
94
+ }
95
+ c10::SymIntArrayRef sym_strides() const {
96
+ return strides_;
97
+ }
98
+ c10::SymInt sym_storage_offset() const {
99
+ return storage_offset_;
100
+ }
101
+ c10::SymInt sym_numel() const {
102
+ return numel_;
103
+ }
104
+
105
+ TensorGeometry transpose(int64_t dim0, int64_t dim1) {
106
+ TensorGeometry r = *this; // copy
107
+ TORCH_CHECK(
108
+ dim0 < dim(),
109
+ "transpose: dim0=",
110
+ dim0,
111
+ " out of range (dim=",
112
+ dim(),
113
+ ")")
114
+ TORCH_CHECK(
115
+ dim1 < dim(),
116
+ "transpose: dim1=",
117
+ dim1,
118
+ " out of range (dim=",
119
+ dim(),
120
+ ")")
121
+ std::swap(r.sizes_[dim0], r.sizes_[dim1]);
122
+ std::swap(r.strides_[dim0], r.strides_[dim1]);
123
+ return r;
124
+ }
125
+
126
+ std::vector<c10::SymInt>& mutable_sizes() {
127
+ return sizes_;
128
+ }
129
+ std::vector<c10::SymInt>& mutable_strides() {
130
+ return strides_;
131
+ }
132
+ c10::SymInt& mutable_storage_offset() {
133
+ return storage_offset_;
134
+ }
135
+ void recompute() {
136
+ // recalculate numel after a change
137
+ c10::SymInt numel = 1;
138
+ for (const auto& i : sizes_) {
139
+ numel = numel * i;
140
+ }
141
+ numel_ = std::move(numel);
142
+ has_symbolic_sizes_strides_ =
143
+ !c10::asIntArrayRefSlowOpt(sizes_).has_value();
144
+ }
145
+
146
+ private:
147
+ std::vector<c10::SymInt> sizes_;
148
+ std::vector<c10::SymInt> strides_;
149
+ c10::SymInt storage_offset_;
150
+ c10::SymInt numel_;
151
+ bool has_symbolic_sizes_strides_{false};
152
+ };
153
+
154
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIndexing.h ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ExpandUtils.h>
4
+ #include <ATen/ScalarOps.h>
5
+ #include <ATen/core/Tensor.h>
6
+ #include <ATen/core/TensorBody.h>
7
+ #include <c10/core/SymInt.h>
8
+ #include <c10/util/irange.h>
9
+ #include <optional>
10
+
11
+ #ifndef AT_PER_OPERATOR_HEADERS
12
+ #include <ATen/Functions.h>
13
+ #include <ATen/NativeFunctions.h>
14
+ #else
15
+ #include <ATen/ops/alias.h>
16
+ #include <ATen/ops/empty.h>
17
+ #include <ATen/ops/scalar_tensor.h>
18
+ #include <ATen/ops/zeros.h>
19
+ #endif
20
+
21
+ #include <ATen/core/List.h>
22
+
23
+ #include <utility>
24
+
25
+ namespace at::indexing {
26
+
27
+ constexpr int64_t INDEX_MIN = c10::SymInt::min_representable_int();
28
+ constexpr int64_t INDEX_MAX = -(INDEX_MIN + 1);
29
+
30
+ enum class TensorIndexType { None, Ellipsis, SymInt, Boolean, Slice, Tensor };
31
+
32
+ constexpr std::nullopt_t None = std::nullopt;
33
+
34
+ struct TORCH_API EllipsisIndexType final {
35
+ EllipsisIndexType() = default;
36
+ };
37
+ TORCH_API extern const EllipsisIndexType Ellipsis;
38
+
39
+ struct TORCH_API Slice final {
40
+ public:
41
+ Slice(
42
+ std::optional<c10::SymInt> start_index = std::nullopt,
43
+ std::optional<c10::SymInt> stop_index = std::nullopt,
44
+ std::optional<c10::SymInt> step_index = std::nullopt) {
45
+ if (!step_index.has_value()) {
46
+ step_ = c10::SymInt(1);
47
+ } else {
48
+ step_ = std::move(step_index).value();
49
+ }
50
+
51
+ TORCH_CHECK_VALUE(
52
+ step_.sym_ne(0).expect_true(__FILE__, __LINE__),
53
+ "slice step cannot be zero");
54
+
55
+ if (!start_index.has_value()) {
56
+ start_ = c10::SymInt(step_ < 0 ? INDEX_MAX : 0);
57
+ } else {
58
+ start_ = std::move(start_index).value();
59
+ }
60
+
61
+ if (!stop_index.has_value()) {
62
+ stop_ = c10::SymInt(step_ < 0 ? INDEX_MIN : INDEX_MAX);
63
+ } else {
64
+ stop_ = std::move(stop_index).value();
65
+ }
66
+ }
67
+
68
+ inline c10::SymInt start() const {
69
+ return start_;
70
+ }
71
+
72
+ inline c10::SymInt stop() const {
73
+ return stop_;
74
+ }
75
+
76
+ inline c10::SymInt step() const {
77
+ return step_;
78
+ }
79
+
80
+ private:
81
+ c10::SymInt start_;
82
+ c10::SymInt stop_;
83
+ c10::SymInt step_;
84
+ };
85
+
86
+ TORCH_API std::ostream& operator<<(std::ostream& stream, const Slice& slice);
87
+
88
+ // `at::indexing::TensorIndex` is used for converting C++ tensor indices such as
89
+ // `{None, "...", Ellipsis, 0, true, Slice(1, None, 2), torch::tensor({1, 2})}`
90
+ // into its equivalent `std::vector<TensorIndex>`, so that further tensor
91
+ // indexing operations can be performed using the supplied indices.
92
+ //
93
+ // There is one-to-one correspondence between Python and C++ tensor index types:
94
+ // Python | C++
95
+ // -----------------------------------------------------
96
+ // `None` | `at::indexing::None`
97
+ // `Ellipsis` | `at::indexing::Ellipsis`
98
+ // `...` | `"..."`
99
+ // `123` | `123`
100
+ // `True` / `False` | `true` / `false`
101
+ // `:` | `Slice()` / `Slice(None, None)`
102
+ // `::` | `Slice()` / `Slice(None, None, None)`
103
+ // `1:` | `Slice(1, None)`
104
+ // `1::` | `Slice(1, None, None)`
105
+ // `:3` | `Slice(None, 3)`
106
+ // `:3:` | `Slice(None, 3, None)`
107
+ // `::2` | `Slice(None, None, 2)`
108
+ // `1:3` | `Slice(1, 3)`
109
+ // `1::2` | `Slice(1, None, 2)`
110
+ // `:3:2` | `Slice(None, 3, 2)`
111
+ // `1:3:2` | `Slice(1, 3, 2)`
112
+ // `torch.tensor([1, 2])`) | `torch::tensor({1, 2})`
113
+ struct TORCH_API TensorIndex final {
114
+ // Case 1: `at::indexing::None`
115
+ TensorIndex(std::nullopt_t) : type_(TensorIndexType::None) {}
116
+
117
+ // Case 2: "..." / `at::indexing::Ellipsis`
118
+ TensorIndex(at::indexing::EllipsisIndexType)
119
+ : type_(TensorIndexType::Ellipsis) {}
120
+ TensorIndex(const char* str) : TensorIndex(at::indexing::Ellipsis) {
121
+ TORCH_CHECK_VALUE(
122
+ strcmp(str, "...") == 0,
123
+ "Expected \"...\" to represent an ellipsis index, but got \"",
124
+ str,
125
+ "\"");
126
+ }
127
+
128
+ // Case 3: (Sym) Integer value
129
+ TensorIndex(SymInt integer)
130
+ : integer_(std::move(integer)), type_(TensorIndexType::SymInt) {}
131
+ TensorIndex(int64_t integer) : TensorIndex(SymInt(integer)) {}
132
+ TensorIndex(int integer) : TensorIndex(SymInt(integer)) {}
133
+
134
+ // Case 4: Boolean value
135
+ template <class T, class = std::enable_if_t<std::is_same_v<bool, T>>>
136
+ TensorIndex(T boolean) : boolean_(boolean), type_(TensorIndexType::Boolean) {}
137
+
138
+ // Case 5: Slice represented in `at::indexing::Slice` form
139
+ TensorIndex(Slice slice)
140
+ : slice_(std::move(slice)), type_(TensorIndexType::Slice) {}
141
+
142
+ // Case 6: Tensor value
143
+ TensorIndex(Tensor tensor)
144
+ : tensor_(std::move(tensor)), type_(TensorIndexType::Tensor) {}
145
+
146
+ inline bool is_none() const {
147
+ return type_ == TensorIndexType::None;
148
+ }
149
+
150
+ inline bool is_ellipsis() const {
151
+ return type_ == TensorIndexType::Ellipsis;
152
+ }
153
+
154
+ inline bool is_integer() const {
155
+ return type_ == TensorIndexType::SymInt;
156
+ }
157
+
158
+ inline SymInt integer() const {
159
+ return integer_;
160
+ }
161
+
162
+ inline bool is_boolean() const {
163
+ return type_ == TensorIndexType::Boolean;
164
+ }
165
+
166
+ inline bool boolean() const {
167
+ return boolean_;
168
+ }
169
+
170
+ inline bool is_slice() const {
171
+ return type_ == TensorIndexType::Slice;
172
+ }
173
+
174
+ inline const Slice& slice() const {
175
+ return slice_;
176
+ }
177
+
178
+ inline bool is_tensor() const {
179
+ return type_ == TensorIndexType::Tensor;
180
+ }
181
+
182
+ inline const Tensor& tensor() const {
183
+ return tensor_;
184
+ }
185
+
186
+ private:
187
+ SymInt integer_ = 0;
188
+ bool boolean_ = false;
189
+ Slice slice_;
190
+ Tensor tensor_;
191
+ TensorIndexType type_;
192
+ };
193
+
194
+ TORCH_API std::ostream& operator<<(
195
+ std::ostream& stream,
196
+ const TensorIndex& tensor_index);
197
+ TORCH_API std::ostream& operator<<(
198
+ std::ostream& stream,
199
+ const std::vector<TensorIndex>& tensor_indices);
200
+
201
+ namespace impl {
202
+ inline Tensor applySlice(
203
+ const Tensor& self,
204
+ int64_t dim,
205
+ c10::SymInt start,
206
+ c10::SymInt stop,
207
+ c10::SymInt step,
208
+ bool disable_slice_optimization,
209
+ const at::Device& self_device,
210
+ const std::optional<SymIntArrayRef>& self_sizes) {
211
+ // TODO: implement negative step
212
+ TORCH_CHECK_VALUE(
213
+ step.sym_gt(0).expect_true(__FILE__, __LINE__),
214
+ "step must be greater than zero");
215
+
216
+ // See NOTE [nested tensor size for indexing]
217
+ if (self_sizes.has_value()) {
218
+ // Skip this optimization if we are tracing, as the trace may be polymorphic
219
+ // over the shape of the `self` tensor, and we still want to record
220
+ // the slice.
221
+ SymInt length = (self_device == at::kCPU || self_device == at::kCUDA)
222
+ ? (*self_sizes)[dim]
223
+ : self.sym_size(dim);
224
+ if (!disable_slice_optimization &&
225
+ TORCH_GUARD_SIZE_OBLIVIOUS(start.sym_eq(0)) &&
226
+ TORCH_GUARD_SIZE_OBLIVIOUS(length.sym_eq(stop)) && step == 1) {
227
+ return self;
228
+ }
229
+ }
230
+ return self.slice_symint(
231
+ dim, std::move(start), std::move(stop), std::move(step));
232
+ }
233
+
234
+ inline Tensor applySelect(
235
+ const Tensor& self,
236
+ int64_t dim,
237
+ SymInt index,
238
+ int64_t real_dim,
239
+ const at::Device& /*self_device*/,
240
+ const std::optional<SymIntArrayRef>& self_sizes) {
241
+ // See NOTE [nested tensor size for indexing]
242
+ if (self_sizes.has_value()) {
243
+ auto maybe_index = index.maybe_as_int();
244
+ if (maybe_index.has_value()) {
245
+ TORCH_CHECK_INDEX(
246
+ !(maybe_index.value() == 0 && dim == 0 && self_sizes->empty()),
247
+ "invalid index of a 0-dim tensor. ",
248
+ "Use `tensor.item()` in Python or `tensor.item<T>()` in C++ to convert a 0-dim tensor to a number");
249
+ }
250
+
251
+ auto size = (*self_sizes)[dim];
252
+ // Note: `size >= -index` is not equivalent to `size > -1 - index` if index
253
+ // is INT64_MIN For std::numeric_limits<int64_t>::min() result of unary
254
+ // minus is undefined by the standard but in practice is equal to self. On
255
+ // the other hand, indexing wraping is valid for all negative int64_t
256
+ // values, as x[INT64_MIN] is the same as x[INT64_MAX]
257
+ TORCH_CHECK_INDEX(
258
+ size.sym_gt(-1 - index)
259
+ .sym_and(size.sym_gt(index))
260
+ .expect_true(__FILE__, __LINE__),
261
+ "index ",
262
+ index,
263
+ " is out of bounds for dimension ",
264
+ real_dim,
265
+ " with size ",
266
+ size);
267
+ }
268
+
269
+ // if the index is negative, do not normalize it because that would fix the
270
+ // index on the current tensor size in the tracer. aten::select also works on
271
+ // negative indices
272
+ return self.select_symint(dim, std::move(index));
273
+ }
274
+
275
+ inline Tensor boolToIndexingTensorCPUOrCUDA(const Tensor& self, bool value) {
276
+ // booleans add a dimension of size 1. true indexes this dimension as if 0:,
277
+ // false as empty.
278
+ if (value) {
279
+ return at::empty({1}, self.options().dtype(kLong)).fill_(0.);
280
+ } else {
281
+ return at::empty({0}, self.options().dtype(kLong));
282
+ }
283
+ }
284
+
285
+ inline Tensor boolToIndexingTensorNonNativeDeviceType(
286
+ const Tensor& self,
287
+ bool value) {
288
+ // booleans add a dimension of size 1. true indexes this dimension as if 0:,
289
+ // false as empty.
290
+ if (value) {
291
+ return at::zeros({1}, self.options().dtype(kLong));
292
+ } else {
293
+ return at::empty({0}, self.options().dtype(kLong));
294
+ }
295
+ }
296
+
297
+ inline Tensor boolToIndexingTensor(
298
+ const Tensor& self,
299
+ bool value,
300
+ const at::Device& self_device) {
301
+ if (self_device == at::kCPU || self_device == at::kCUDA) {
302
+ return boolToIndexingTensorCPUOrCUDA(self, value);
303
+ } else {
304
+ return boolToIndexingTensorNonNativeDeviceType(self, value);
305
+ }
306
+ }
307
+
308
+ inline Tensor scalarToTensorNonNativeDeviceType(
309
+ const Scalar& v,
310
+ const TensorOptions& options) {
311
+ return at::scalar_tensor(v, options);
312
+ }
313
+
314
+ inline void recordTensorIndex(
315
+ const Tensor& tensor,
316
+ std::vector<Tensor>& outIndices,
317
+ int64_t* dim_ptr) {
318
+ // TODO: check scalarType
319
+ outIndices.resize(*dim_ptr + 1);
320
+ outIndices[*dim_ptr] = tensor;
321
+ (*dim_ptr)++;
322
+ }
323
+
324
+ inline c10::List<::std::optional<Tensor>> typeConvertIndices(
325
+ const Tensor& /*self*/,
326
+ std::vector<Tensor>&& indices) {
327
+ c10::List<::std::optional<Tensor>> converted_inds;
328
+ converted_inds.reserve(indices.size());
329
+ for (auto&& i : std::move(indices)) {
330
+ converted_inds.push_back(std::move(i));
331
+ }
332
+ return converted_inds;
333
+ }
334
+
335
+ // NOTE: Why do we mirror instead of replace the `count_specified_dimensions`
336
+ // function in torch/csrc/autograd/python_variable_indexing.cpp? It's because
337
+ // `count_specified_dimensions` is on the hot path of Python tensor multi-dim
338
+ // indexing (i.e. it's called by `applySlicing` which is called by
339
+ // `THPVariable_getitem` / `THPVariable_setitem` when handling indexing of more
340
+ // than one dimension). If we were to merge the Python/C++
341
+ // `count_specified_dimensions` function, on the Python side we would have to
342
+ // construct a `std::vector` container to be consumed by the C++
343
+ // `count_specified_dimensions` function, which adds 100s of nanoseconds
344
+ // overhead and is undesirable.
345
+ inline int64_t count_specified_dimensions(
346
+ const ArrayRef<TensorIndex>& indices) {
347
+ // Count the number of indexed dimensions (everything but ellipsis and None)
348
+ int64_t count = 0;
349
+ for (auto& obj : indices) {
350
+ if (obj.is_tensor()) {
351
+ auto& tensor = obj.tensor();
352
+ if (tensor.scalar_type() == kByte || tensor.scalar_type() == kBool) {
353
+ count += tensor.dim();
354
+ } else {
355
+ count++;
356
+ }
357
+ } else if (!obj.is_none() && !obj.is_ellipsis() && !obj.is_boolean()) {
358
+ count++;
359
+ }
360
+ }
361
+ return count;
362
+ }
363
+ } // namespace impl
364
+
365
+ // NOTE: Many functions below are only for consumption from Python indexing
366
+ // implementation, they include:
367
+ //
368
+ // - `Tensor scalarToTensor(...)`
369
+ // - `IntArrayRef slicePrefix1sSize(...)`
370
+ // - `void copy_to(...)`
371
+ // - `Tensor handleDimInMultiDimIndexing(...)`
372
+ // - `Tensor dispatch_index(...)`
373
+ // - `Tensor dispatch_index_put_(...)`
374
+ // - `Tensor get_item(...)`
375
+ // - `void set_item(...)`
376
+ //
377
+ // The rest of the functions are in `at::indexing::impl` namespace, signifying
378
+ // that they shouldn't be used from Python indexing implementation.
379
+ inline Tensor scalarToTensor(
380
+ const Scalar& v,
381
+ const TensorOptions& options,
382
+ const at::Device& self_device) {
383
+ if (self_device == at::kCPU && !v.isSymbolic()) {
384
+ return at::detail::scalar_tensor_static(
385
+ v,
386
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
387
+ options.dtype_opt()->toScalarType(),
388
+ self_device);
389
+ } else {
390
+ return impl::scalarToTensorNonNativeDeviceType(v, options);
391
+ }
392
+ }
393
+
394
+ // To match numpy semantics:
395
+ // As a special case for backwards compatibility,
396
+ // strip away unit dimensions from the left of 'src'
397
+ inline SymIntArrayRef slicePrefix1sSize(const SymIntArrayRef& sizes) {
398
+ size_t first_non1_src = sizes.size();
399
+ for (const auto i : c10::irange(sizes.size())) {
400
+ // Unbacked SymInt has different behavior, but this is sound because
401
+ // failing to slice will only ever cause an error, not divergent
402
+ // behavior
403
+ if (!sizes[i].has_hint() || sizes[i] != 1) {
404
+ first_non1_src = i;
405
+ break;
406
+ }
407
+ }
408
+
409
+ return sizes.slice(first_non1_src);
410
+ }
411
+
412
+ inline void copy_to(const Tensor& dst, const Tensor& src) {
413
+ if (dst.sym_sizes().equals(src.sym_sizes())) {
414
+ // A shortcut to avoid generating hard-coded constant sizes during tracing.
415
+ // This is not a perfect solution: when src & dst have different shapes,
416
+ // constants will still appear. Users can workaround that case by
417
+ // dst[index..] = src.reshape(..)
418
+ dst.copy_(src);
419
+ return;
420
+ } else if (src.dim() == 0 && src.device().type() == at::kCPU) {
421
+ dst.fill_(src);
422
+ return;
423
+ }
424
+ auto src_view = src.view_symint(slicePrefix1sSize(src.sym_sizes()));
425
+ c10::MaybeOwned<Tensor> b_src = expand_inplace(dst, src_view, "setitem");
426
+ dst.copy_(*b_src);
427
+ }
428
+
429
+ // See NOTE [ Setting `disable_slice_optimization` when calling C++ tensor
430
+ // indexing functions from Python ]
431
+ inline Tensor handleDimInMultiDimIndexing(
432
+ const Tensor& prev_dim_result,
433
+ const Tensor& original_tensor,
434
+ const TensorIndex& index,
435
+ int64_t* dim_ptr,
436
+ int64_t* specified_dims_ptr,
437
+ int64_t real_dim,
438
+ std::vector<Tensor>& outIndices,
439
+ bool disable_slice_optimization,
440
+ const at::Device& original_tensor_device,
441
+ const std::optional<SymIntArrayRef>& prev_dim_result_sizes) {
442
+ if (index.is_integer()) {
443
+ return impl::applySelect(
444
+ prev_dim_result,
445
+ *dim_ptr,
446
+ index.integer(),
447
+ real_dim,
448
+ original_tensor_device,
449
+ prev_dim_result_sizes);
450
+ } else if (index.is_slice()) {
451
+ Tensor result = impl::applySlice(
452
+ prev_dim_result,
453
+ *dim_ptr,
454
+ index.slice().start(),
455
+ index.slice().stop(),
456
+ index.slice().step(),
457
+ /*disable_slice_optimization=*/disable_slice_optimization,
458
+ original_tensor_device,
459
+ prev_dim_result_sizes);
460
+ (*dim_ptr)++;
461
+ return result;
462
+ } else if (index.is_ellipsis()) {
463
+ (*dim_ptr) += original_tensor.dim() - (*specified_dims_ptr);
464
+ return prev_dim_result;
465
+ } else if (index.is_none()) {
466
+ Tensor result = prev_dim_result.unsqueeze(*dim_ptr);
467
+ (*dim_ptr)++;
468
+ return result;
469
+ } else if (index.is_boolean()) {
470
+ Tensor result = prev_dim_result.unsqueeze(*dim_ptr);
471
+ impl::recordTensorIndex(
472
+ impl::boolToIndexingTensor(
473
+ result, index.boolean(), original_tensor_device),
474
+ outIndices,
475
+ dim_ptr);
476
+ return result;
477
+ } else if (index.is_tensor()) {
478
+ Tensor result = prev_dim_result;
479
+ const Tensor& tensor = index.tensor();
480
+ auto scalar_type = tensor.scalar_type();
481
+ if (tensor.dim() == 0 &&
482
+ at::isIntegralType(scalar_type, /*includeBool=*/true)) {
483
+ if (scalar_type != at::kByte && scalar_type != at::kBool) {
484
+ result = impl::applySelect(
485
+ result,
486
+ *dim_ptr,
487
+ tensor.item<int64_t>(),
488
+ real_dim,
489
+ original_tensor_device,
490
+ prev_dim_result_sizes);
491
+ } else {
492
+ result = result.unsqueeze(*dim_ptr);
493
+ if (scalar_type == at::kBool) {
494
+ impl::recordTensorIndex(
495
+ impl::boolToIndexingTensor(
496
+ result, tensor.item<bool>() != 0, original_tensor_device),
497
+ outIndices,
498
+ dim_ptr);
499
+ } else {
500
+ impl::recordTensorIndex(
501
+ impl::boolToIndexingTensor(
502
+ result, tensor.item<uint8_t>() != 0, original_tensor_device),
503
+ outIndices,
504
+ dim_ptr);
505
+ }
506
+ }
507
+ } else {
508
+ impl::recordTensorIndex(tensor, outIndices, dim_ptr);
509
+ }
510
+ return result;
511
+ } else {
512
+ TORCH_INTERNAL_ASSERT(false, "Invalid TensorIndex type");
513
+ }
514
+ }
515
+
516
+ namespace impl {
517
+ // This mirrors `applySlicing` in
518
+ // torch/csrc/autograd/python_variable_indexing.cpp
519
+ inline Tensor applySlicing(
520
+ const Tensor& self,
521
+ const ArrayRef<TensorIndex>& indices,
522
+ std::vector<Tensor>& outIndices,
523
+ bool disable_slice_optimization,
524
+ const at::Device& self_device,
525
+ const std::optional<SymIntArrayRef>& self_sizes) {
526
+ int64_t dim = 0;
527
+ int64_t specified_dims = impl::count_specified_dimensions(indices);
528
+
529
+ // See NOTE [nested tensor size for indexing]
530
+ if (self_sizes.has_value()) {
531
+ TORCH_CHECK_INDEX(
532
+ specified_dims <= (int64_t)self_sizes->size(),
533
+ "too many indices for tensor of dimension ",
534
+ (int)self_sizes->size());
535
+ }
536
+
537
+ Tensor result = self;
538
+ for (const auto i : c10::irange(indices.size())) {
539
+ auto& obj = indices[i];
540
+ // See NOTE [nested tensor size for indexing]
541
+ std::optional<SymIntArrayRef> result_sizes = result.is_nested()
542
+ ? std::optional<SymIntArrayRef>(std::nullopt)
543
+ : std::optional<SymIntArrayRef>(result.sym_sizes());
544
+ result = handleDimInMultiDimIndexing(
545
+ /*prev_dim_result=*/result,
546
+ /*original_tensor=*/self,
547
+ /*index=*/obj,
548
+ /*dim_ptr=*/&dim,
549
+ /*specified_dims_ptr=*/&specified_dims,
550
+ /*real_dim=*/static_cast<int64_t>(i),
551
+ /*outIndices=*/outIndices,
552
+ /*disable_slice_optimization=*/disable_slice_optimization,
553
+ /*original_tensor_device=*/self_device,
554
+ /*prev_dim_result_sizes=*/result_sizes);
555
+ }
556
+ return result;
557
+ }
558
+ } // namespace impl
559
+
560
+ inline Tensor dispatch_index(
561
+ const Tensor& self,
562
+ std::vector<Tensor>&& indices) {
563
+ return self.index(impl::typeConvertIndices(self, std::move(indices)));
564
+ }
565
+
566
+ inline Tensor dispatch_index_put_(
567
+ Tensor& self,
568
+ std::vector<Tensor>&& indices,
569
+ const Tensor& value) {
570
+ return self.index_put_(
571
+ impl::typeConvertIndices(self, std::move(indices)), value);
572
+ }
573
+
574
+ // NOTE [ Setting `disable_slice_optimization` when calling C++ tensor indexing
575
+ // functions from Python ]
576
+ //
577
+ // Question: When should we set `disable_slice_optimization` to `true` when
578
+ // calling C++ tensor indexing functions from Python indexing code?
579
+ //
580
+ // Answer: What "slice optimization" means: when we have a slicing expression
581
+ // like `x[0:5, 0]`, where the sliced tensor was of size 5 in dimension 0, we
582
+ // would skip dispatching the actual slice call as an optimization. However,
583
+ // here are the cases where we DON'T want this optimization:
584
+ //
585
+ // 1. When we are doing 1-D slicing (e.g. `tensor[:]`).
586
+ // Reason: we always return a shallow copy for expressions such as
587
+ // `tensor[:]` / `tensor[...]` / `tensor[:, :]`. (Note that for `tensor[:,
588
+ // :]`, we return an alias of `tensor` by doing the following:
589
+ // ```
590
+ // Tensor sliced = impl::applySlicing(self, indices, tensorIndices,
591
+ // disable_slice_optimization, self_device, self_sizes); if
592
+ // (tensorIndices.empty()) {
593
+ // if (sliced.is_same(self)) {
594
+ // // ensure we return a shallow copy for things like x[...]
595
+ // sliced = at::alias(sliced);
596
+ // }
597
+ // return sliced;
598
+ // }
599
+ // ```)
600
+ // 2. When we are doing JIT tracing.
601
+ // Reason: JIT tracing needs the `self.slice(...)` call to properly trace the
602
+ // slice operation.
603
+
604
+ // This mirrors `THPVariable_getitem` in
605
+ // torch/csrc/autograd/python_variable_indexing.cpp See NOTE [ Setting
606
+ // `disable_slice_optimization` when calling C++ tensor indexing functions from
607
+ // Python ]
608
+ inline Tensor get_item(
609
+ const Tensor& self,
610
+ const ArrayRef<TensorIndex>& indices,
611
+ bool disable_slice_optimization = false) {
612
+ at::Device self_device = self.device();
613
+ // NOTE [nested tensor size for indexing]
614
+ // nested tensor does not have a size (yet) so for now we represent its size
615
+ // as null may need to be changed after we reach a better solution for nested
616
+ // tensor size
617
+ std::optional<SymIntArrayRef> self_sizes = self.is_nested()
618
+ ? std::optional<SymIntArrayRef>(std::nullopt)
619
+ : std::optional<SymIntArrayRef>(self.sym_sizes());
620
+
621
+ // handle simple types: integers, slices, none, ellipsis, bool
622
+ if (indices.size() == 1) {
623
+ const TensorIndex& index = indices[0];
624
+ if (index.is_integer()) {
625
+ return impl::applySelect(
626
+ self, 0, index.integer(), 0, self_device, self_sizes);
627
+ } else if (index.is_slice()) {
628
+ return impl::applySlice(
629
+ self,
630
+ 0,
631
+ index.slice().start(),
632
+ index.slice().stop(),
633
+ index.slice().step(),
634
+ /*disable_slice_optimization=*/true,
635
+ self_device,
636
+ self_sizes);
637
+ } else if (index.is_none()) {
638
+ return self.unsqueeze(0);
639
+ } else if (index.is_ellipsis()) {
640
+ return at::alias(self);
641
+ } else if (index.is_boolean()) {
642
+ Tensor result = self.unsqueeze(0);
643
+ return dispatch_index(
644
+ result,
645
+ std::vector<Tensor>{impl::boolToIndexingTensor(
646
+ result, index.boolean(), self_device)});
647
+ }
648
+ }
649
+
650
+ std::vector<Tensor> tensorIndices;
651
+ Tensor sliced = impl::applySlicing(
652
+ self,
653
+ indices,
654
+ tensorIndices,
655
+ disable_slice_optimization,
656
+ self_device,
657
+ self_sizes);
658
+ if (tensorIndices.empty()) {
659
+ if (sliced.is_same(self)) {
660
+ // ensure we return a shallow copy for things like x[...]
661
+ sliced = at::alias(sliced);
662
+ }
663
+ return sliced;
664
+ }
665
+
666
+ // indexing by tensors ("advanced" indexing)
667
+ return dispatch_index(sliced, std::move(tensorIndices));
668
+ }
669
+
670
+ // This mirrors `THPVariable_setitem` in
671
+ // torch/csrc/autograd/python_variable_indexing.cpp for "the assigned value is a
672
+ // Tensor" case See NOTE [ Setting `disable_slice_optimization` when calling C++
673
+ // tensor indexing functions from Python ]
674
+ inline void set_item(
675
+ const Tensor& self,
676
+ const ArrayRef<TensorIndex>& indices,
677
+ const Tensor& value,
678
+ bool disable_slice_optimization = false) {
679
+ at::Device self_device = self.device();
680
+ SymIntArrayRef self_sizes = self.sym_sizes();
681
+
682
+ // handle simple types: integers, slices, ellipsis, bool
683
+ if (indices.size() == 1) {
684
+ const TensorIndex& index = indices[0];
685
+ if (index.is_boolean() && !index.boolean()) {
686
+ // do nothing for false (technically we should check the size, but we
687
+ // don't have real 0-sized shapes.
688
+ return;
689
+ } else if (index.is_ellipsis()) {
690
+ copy_to(self, value);
691
+ return;
692
+ } else if (index.is_none() || (index.is_boolean() && index.boolean())) {
693
+ copy_to(self.unsqueeze(0), value);
694
+ return;
695
+ } else if (index.is_integer()) {
696
+ copy_to(
697
+ impl::applySelect(
698
+ self, 0, index.integer(), 0, self_device, self_sizes),
699
+ value);
700
+ return;
701
+ } else if (index.is_slice()) {
702
+ copy_to(
703
+ impl::applySlice(
704
+ self,
705
+ 0,
706
+ index.slice().start(),
707
+ index.slice().stop(),
708
+ index.slice().step(),
709
+ /*disable_slice_optimization=*/disable_slice_optimization,
710
+ self_device,
711
+ self_sizes),
712
+ value);
713
+ return;
714
+ }
715
+ }
716
+
717
+ std::vector<Tensor> tensorIndices;
718
+ Tensor sliced = impl::applySlicing(
719
+ self,
720
+ indices,
721
+ tensorIndices,
722
+ disable_slice_optimization,
723
+ self_device,
724
+ self_sizes);
725
+ if (tensorIndices.empty()) {
726
+ copy_to(sliced, value);
727
+ return;
728
+ }
729
+
730
+ SymIntArrayRef valueSizes = value.sym_sizes();
731
+ SymIntArrayRef slicedValueSizes = slicePrefix1sSize(valueSizes);
732
+ Tensor valuesSliced;
733
+ if (!valueSizes.equals(slicedValueSizes)) {
734
+ valuesSliced = value.view_symint(slicedValueSizes);
735
+ } else {
736
+ valuesSliced = value;
737
+ }
738
+ dispatch_index_put_(sliced, std::move(tensorIndices), valuesSliced);
739
+ return;
740
+ }
741
+
742
+ } // namespace at::indexing
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIterator.h ADDED
@@ -0,0 +1,1034 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/TensorMeta.h>
4
+ #include <ATen/core/Dimname.h>
5
+ #include <ATen/core/Range.h>
6
+ #include <ATen/core/TensorBase.h>
7
+ #include <c10/core/DynamicCast.h>
8
+ #include <c10/util/FunctionRef.h>
9
+ #include <c10/util/MaybeOwned.h>
10
+ #include <c10/util/SmallVector.h>
11
+ #include <c10/util/TypeCast.h>
12
+ #include <c10/util/irange.h>
13
+
14
+ #include <array>
15
+ #include <bitset>
16
+
17
+ namespace at {
18
+ class Tensor;
19
+ class OptionalTensorRef;
20
+ using NameVector = SmallVector<Dimname, kDimVectorStaticSize>;
21
+ } // namespace at
22
+
23
+ // TensorIterator is a helper class for element-wise operations, such as
24
+ // arithmetic, comparisons, and trigonometric functions. It handles
25
+ // broadcasting and type conversions of operands.
26
+ //
27
+ // This is inspired by NumPy's Array Iterator API (NpyIter).
28
+ //
29
+ // The files Loops.h and Loops.cuh provide functions to build kernels that
30
+ // use TensorIterator.
31
+ //
32
+ // Example:
33
+ //
34
+ // auto iter = TensorIteratorConfig()
35
+ // .add_output(output)
36
+ // .add_input(input)
37
+ // .build()
38
+ //
39
+ // [MyKernel.cpp / MyKernel.cu]
40
+ // cpu_kernel(iter, [](float a, float b) {
41
+ // return a + b;
42
+ // });
43
+ //
44
+ // gpu_kernel(iter, []GPU_LAMBDA(float a, float b) -> float {
45
+ // return a + b;
46
+ // });
47
+ //
48
+ // Note [Order of Construction]
49
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
+ // When setting up the tensor iterator configuration, the output Tensors
51
+ // have to be added first via
52
+ // TensorIteratorConfig::add_owned_output(at::Tensor). After adding all outputs,
53
+ // the inputs can be added via
54
+ // TensorIteratorConfig::add_owned_input(at::Tensor).
55
+ // Adding another output after inputs have been added will rise an exception.
56
+ //
57
+ // Note [Common Dtype Computation]
58
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
59
+ // Some operations have a natural notion of a "common dtype" or
60
+ // "computation dtype" where all inputs are cast to one dtype, the
61
+ // operation is performed, and then the results are cast to all outputs.
62
+ //
63
+ // TensorIterator infers a common dtype if all inputs have the same dtype,
64
+ // and it computes one using type promotion rules on its inputs if
65
+ // promote_inputs_to_common_dtype_ is true. Attempting to query
66
+ // a common dtype otherwise will throw an exception.
67
+ //
68
+ // Note that the outputs are not considered when computing a common dtype.
69
+
70
+ namespace at {
71
+
72
+ namespace internal {
73
+ // This parameter is heuristically chosen to determine the minimum number of
74
+ // work that warrants parallelism. For example, when summing an array, it is
75
+ // deemed inefficient to parallelise over arrays shorter than 32768. Further,
76
+ // no parallel algorithm (such as parallel_reduce) should split work into
77
+ // smaller than GRAIN_SIZE chunks.
78
+ constexpr int64_t GRAIN_SIZE = 32768;
79
+
80
+ // Storage for a non-owning Tensor, without needing to include Tensor.h
81
+ class TORCH_API OpaqueOptionalTensorRef {
82
+ alignas(alignof(TensorBase)) std::array<char, sizeof(TensorBase)> data_{};
83
+
84
+ public:
85
+ OpaqueOptionalTensorRef();
86
+ OpaqueOptionalTensorRef(const OpaqueOptionalTensorRef&) = default;
87
+ OpaqueOptionalTensorRef& operator=(const OpaqueOptionalTensorRef&) = default;
88
+ OpaqueOptionalTensorRef(OpaqueOptionalTensorRef&&) noexcept = default;
89
+ OpaqueOptionalTensorRef& operator=(OpaqueOptionalTensorRef&&) noexcept =
90
+ default;
91
+ ~OpaqueOptionalTensorRef();
92
+
93
+ OptionalTensorRef* get() {
94
+ return reinterpret_cast<OptionalTensorRef*>(data_.data());
95
+ }
96
+ const OptionalTensorRef* get() const {
97
+ return reinterpret_cast<const OptionalTensorRef*>(data_.data());
98
+ }
99
+
100
+ OptionalTensorRef& operator*() {
101
+ return *get();
102
+ }
103
+ const OptionalTensorRef& operator*() const {
104
+ return *get();
105
+ }
106
+ OptionalTensorRef* operator->() {
107
+ return get();
108
+ }
109
+ const OptionalTensorRef* operator->() const {
110
+ return get();
111
+ }
112
+
113
+ const Tensor& getTensor() const;
114
+ };
115
+ } // namespace internal
116
+
117
+ struct TORCH_API OperandInfo {
118
+ using StrideVector = SmallVector<int64_t, 6>;
119
+ OperandInfo() = default;
120
+ C10_ALWAYS_INLINE explicit OperandInfo(c10::MaybeOwned<TensorBase>&& t) {
121
+ if (t->defined()) {
122
+ device = t->device();
123
+ target_dtype = t->scalar_type();
124
+ current_dtype = target_dtype;
125
+ }
126
+ tensor(std::move(t));
127
+ validate();
128
+ }
129
+
130
+ C10_ALWAYS_INLINE OperandInfo(const OperandInfo&) = default;
131
+ C10_ALWAYS_INLINE OperandInfo& operator=(const OperandInfo&) = default;
132
+ C10_ALWAYS_INLINE OperandInfo(OperandInfo&&) noexcept = default;
133
+ C10_ALWAYS_INLINE OperandInfo& operator=(OperandInfo&&) noexcept = default;
134
+ C10_ALWAYS_INLINE ~OperandInfo() = default;
135
+
136
+ /// The data pointer. This may be different from tensor->data_ptr() if the
137
+ /// iterator is split.
138
+ void* data = nullptr;
139
+
140
+ /// Stride after broadcasting. The stride is in bytes, not number of elements.
141
+ StrideVector stride_bytes;
142
+
143
+ /// The desired device and type for the operand. For inputs, this specifies
144
+ /// that the input should be converted to this type if necessary. For outputs,
145
+ /// this specifies which type to allocate. target_dtype and device are
146
+ /// initialized with the dtype and device of the tensor but during type
147
+ /// promotion target_dtype value can become different from tensor's dtype
148
+ /// also, during type promotion target_dtype and device can be set for an
149
+ /// undefined tensor so that tensor can be properly constructed later.
150
+ std::optional<Device> device = std::nullopt;
151
+ ScalarType target_dtype = ScalarType::Undefined;
152
+ // Caches dtype of the tensor, because scalar_type is an expensive operation
153
+ // If dtype of the tensor is changed (e.g. as a result of type promotion or in
154
+ // allocate_outputs), this
155
+ // value should be changed too.
156
+ ScalarType current_dtype = ScalarType::Undefined;
157
+
158
+ bool is_device_defined() const {
159
+ return device.has_value();
160
+ }
161
+ bool is_type_defined() const {
162
+ return target_dtype != ScalarType::Undefined;
163
+ }
164
+ TensorOptions options() const {
165
+ return TensorOptions(target_dtype).device(device);
166
+ }
167
+
168
+ bool is_output = false;
169
+
170
+ // will_resize is only for output tensor.
171
+ // 1) Functional call(like torch.add(self, other)): output tensor is
172
+ // undefined, and pytorch creates a new tensor by using common shape
173
+ // and computed stride in TensorIterator;
174
+ // 2) Inplace call(like torch.add_(self, other)): output tensor is same
175
+ // with input tensor, and can't to modify tensor's size and stride;
176
+ // 3) Op call with output(like torch.add(self, other, out = output)):
177
+ // output tensor is defined, but tensor shape maybe different with common
178
+ // shape. If tensor shape is not same with common shape, this output
179
+ // tensor will be resized by using common shape and computed stride in
180
+ // TensorIterator. Otherwise can't modify tensor's size and stride.
181
+ bool will_resize = false;
182
+
183
+ bool is_read_write = false;
184
+
185
+ bool is_const = false;
186
+
187
+ void validate() {
188
+ TORCH_CHECK(
189
+ !tensor_base_->defined() || tensor_base_->layout() == kStrided,
190
+ "unsupported tensor layout: ",
191
+ tensor_base_->layout());
192
+ }
193
+
194
+ /// The tensor operand. Note that the strides, data pointer, and
195
+ /// other attributes may differ due to dimension reordering and
196
+ /// coalescing.
197
+ const Tensor& tensor() const {
198
+ return tensor_storage_.getTensor();
199
+ }
200
+ const TensorBase& tensor_base() const {
201
+ return *tensor_base_;
202
+ }
203
+ void tensor(c10::MaybeOwned<TensorBase>&& tensor);
204
+
205
+ // Save the original tensor operand in cases when an output is modified
206
+ // (e.g. if dtype is changed)
207
+ const Tensor& original_tensor() const {
208
+ return original_tensor_storage_.getTensor();
209
+ }
210
+ const TensorBase& original_tensor_base() const {
211
+ return *original_tensor_base_;
212
+ }
213
+
214
+ // Set tensor to a new value, and store the old tensor value in
215
+ // original_tensor Should only ever be called once for the lifetime of an
216
+ // operand
217
+ void exchange_tensor(c10::MaybeOwned<TensorBase>&& new_tensor);
218
+
219
+ // Move original_tensor back into tensor, exchange_tensor must have been
220
+ // called before
221
+ void restore_original_tensor();
222
+
223
+ private:
224
+ c10::MaybeOwned<TensorBase> tensor_base_;
225
+ c10::MaybeOwned<TensorBase> original_tensor_base_ =
226
+ c10::MaybeOwned<TensorBase>::owned(std::in_place);
227
+
228
+ // We store TensorBase visibly in the header to allow inline access.
229
+ // However, we sometimes need a genuine `const Tensor &` for the
230
+ // TensorIterator API. So, we also store a non-owning `Tensor`
231
+ // object in these `_storage_` variables.
232
+ internal::OpaqueOptionalTensorRef tensor_storage_;
233
+ internal::OpaqueOptionalTensorRef original_tensor_storage_;
234
+ };
235
+
236
+ struct SplitUntil32Bit;
237
+
238
+ enum class FastSetupType : uint8_t {
239
+ NONE,
240
+ CONTIGUOUS,
241
+ CHANNELS_LAST,
242
+ NON_OVERLAPPING_DENSE
243
+ };
244
+
245
+ class TensorIteratorConfig;
246
+ struct TensorIterator;
247
+
248
+ struct TORCH_API TensorIteratorBase : public impl::MetaBase {
249
+ using DimMask = std::bitset<64>;
250
+ using PtrVector = SmallVector<char*, 4>;
251
+ using StrideVector = SmallVector<int64_t, 6>;
252
+
253
+ void build(TensorIteratorConfig&);
254
+
255
+ // The inner-loop function operates on the fastest moving dimension. It
256
+ // implements element-wise operations in terms of 1-d strided tensors.
257
+ //
258
+ // Arguments:
259
+ // data: data pointers for each operand (length `ntensors`)
260
+ // strides: stride for each operand (length `ntensors`)
261
+ // size: size of inner loop
262
+ //
263
+ // The `size` often matches shape[0], but may be smaller due to
264
+ // parallelization of the inner loop.
265
+ using loop2d_t = c10::function_ref<
266
+ void(char** data, const int64_t* strides, int64_t size0, int64_t size1)>;
267
+
268
+ using loop_subiter_t = c10::function_ref<void(TensorIteratorBase& subiter)>;
269
+
270
+ void foreach_reduced_elt(loop_subiter_t loop, bool parallelize = true);
271
+
272
+ int ndim() const {
273
+ return static_cast<int>(shape_.size());
274
+ }
275
+ IntArrayRef shape() const {
276
+ return shape_;
277
+ }
278
+ int64_t numel() const;
279
+ int ntensors() const {
280
+ return static_cast<int>(operands_.size());
281
+ }
282
+ int noutputs() const {
283
+ return num_outputs_;
284
+ }
285
+ int ninputs() const {
286
+ return ntensors() - noutputs();
287
+ }
288
+ IntArrayRef view_offsets() const {
289
+ return view_offsets_;
290
+ }
291
+
292
+ /// number of elements in the output operand. this is the same as numel() for
293
+ /// operations that are not reductions.
294
+ int64_t num_output_elements() const;
295
+
296
+ /// number of reduced dimensions in a reduction operation
297
+ int num_reduce_dims() const;
298
+
299
+ /// 1-dimensional iteration and no buffering or type conversion
300
+ bool is_trivial_1d() const;
301
+ /// Reducible to 1-dimensional and all operands are contiguous
302
+ bool is_contiguous() const;
303
+ bool is_dim_reduced(int dim) const;
304
+
305
+ /// Accessors for each operand
306
+ IntArrayRef strides(int64_t arg) const {
307
+ return operands_[arg].stride_bytes;
308
+ }
309
+ void* data_ptr(int64_t arg) const;
310
+ ScalarType dtype(int64_t arg = 0) const {
311
+ return operands_[arg].current_dtype;
312
+ }
313
+ ScalarType common_dtype() const {
314
+ TORCH_INTERNAL_ASSERT(
315
+ common_dtype_ != ScalarType::Undefined,
316
+ "Queried for invalid common dtype!");
317
+ return common_dtype_;
318
+ }
319
+ ScalarType input_dtype(int64_t arg = 0) const {
320
+ return operands_[num_outputs_ + arg].current_dtype;
321
+ }
322
+ Device device(int64_t arg = 0) const {
323
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
324
+ return operands_[arg].device.value();
325
+ }
326
+ c10::DeviceType device_type(int64_t arg = 0) const {
327
+ return device(arg).type();
328
+ }
329
+ int64_t element_size(int64_t arg) const {
330
+ return static_cast<int64_t>(elementSize(dtype(arg)));
331
+ }
332
+ bool is_scalar(int64_t arg) const;
333
+ bool is_cpu_scalar(int64_t arg) const;
334
+
335
+ const TensorBase& tensor_base(int64_t arg) const {
336
+ return operands_[arg].tensor_base();
337
+ }
338
+ const Tensor& tensor(int64_t arg) const {
339
+ return operands_[arg].tensor();
340
+ }
341
+
342
+ const TensorBase& output_base(int64_t arg = 0) const {
343
+ AT_ASSERT(arg < num_outputs_);
344
+ return tensor_base(arg);
345
+ }
346
+
347
+ const Tensor& output(int64_t arg = 0) const {
348
+ AT_ASSERT(arg < num_outputs_);
349
+ return tensor(arg);
350
+ }
351
+
352
+ const TensorBase& input_base(int64_t arg = 0) const {
353
+ AT_ASSERT(arg >= 0 && arg < ntensors() - num_outputs_);
354
+ return tensor_base(num_outputs_ + arg);
355
+ }
356
+ const Tensor& input(int64_t arg = 0) const {
357
+ AT_ASSERT(arg >= 0 && arg < ntensors() - num_outputs_);
358
+ return tensor(num_outputs_ + arg);
359
+ }
360
+
361
+ // Copies from temporary outputs back to the original outputs
362
+ // NOTE: only used on CPU
363
+ void cast_outputs();
364
+
365
+ /// Removes an operand from this iterator
366
+ void remove_operand(int64_t arg);
367
+ /// Shrinks an iterated dimension
368
+ void narrow(int dim, int64_t start, int64_t size);
369
+ /// Narrows every dim after and including `start_dim` to size one.
370
+ void select_all_keeping_dim(int start_dim, IntArrayRef starts);
371
+ /// Replaces the data pointer for the operand at index `arg`.
372
+ /// The new pointer should have the same sizes, strides and dtype as the
373
+ /// original
374
+ void unsafe_replace_operand(int64_t arg, void* data);
375
+
376
+ /// Splits this TensorIterator into two iterators. Together they iterate over
377
+ /// the entire operation. Used by `with_32bit_indexing()`.
378
+ std::unique_ptr<TensorIterator> split(int dim);
379
+
380
+ /// Returns the dimension with the largest extent: (size[dim]-1) * stride[dim]
381
+ int get_dim_to_split() const;
382
+
383
+ template <typename T>
384
+ T scalar_value(int64_t arg) {
385
+ auto& op = operands_[arg];
386
+ return c10::fetch_and_cast<T>(op.tensor_base().scalar_type(), op.data);
387
+ }
388
+
389
+ /// Return scalar value from original_tensor_base if it is defined. When
390
+ /// common_dtype is Half, casting scalar input to common_dtype might overflow.
391
+ /// If the scalar is aleady given in the type of Half, then return scalar
392
+ /// value from tensor_base.
393
+ template <typename T>
394
+ T original_scalar_value(int64_t arg) {
395
+ auto& original_tensor_base = operands_[arg].original_tensor_base();
396
+ if (original_tensor_base.defined()) {
397
+ TORCH_INTERNAL_ASSERT(
398
+ original_tensor_base.scalar_type() != common_dtype());
399
+ return c10::fetch_and_cast<T>(
400
+ original_tensor_base.scalar_type(),
401
+ original_tensor_base.const_data_ptr());
402
+ } else {
403
+ return scalar_value<T>(arg);
404
+ }
405
+ }
406
+
407
+ private:
408
+ template <typename loop1d_t>
409
+ auto loop_2d_from_1d(const loop1d_t& loop) {
410
+ return
411
+ [loop, ntensor = ntensors()](
412
+ char** base, const int64_t* strides, int64_t size0, int64_t size1) {
413
+ PtrVector data(base, base + ntensor);
414
+ const int64_t* outer_strides = &strides[ntensor];
415
+ for (const auto i : c10::irange(size1)) {
416
+ if (i > 0) {
417
+ for (const auto arg : c10::irange(ntensor)) {
418
+ data[arg] += outer_strides[arg];
419
+ }
420
+ }
421
+ loop(data.data(), strides, size0);
422
+ }
423
+ };
424
+ }
425
+
426
+ public:
427
+ template <
428
+ typename loop1d_t,
429
+ std::enable_if_t<
430
+ std::is_convertible_v<
431
+ loop1d_t,
432
+ c10::function_ref<
433
+ void(char**, const int64_t* strides, int64_t size)>>,
434
+ int> = 0>
435
+ void for_each(loop1d_t loop, int64_t grain_size = at::internal::GRAIN_SIZE) {
436
+ for_each(loop_2d_from_1d(loop), grain_size);
437
+ }
438
+
439
+ void for_each(loop2d_t loop, int64_t grain_size = at::internal::GRAIN_SIZE);
440
+
441
+ void parallel_reduce(loop2d_t loop);
442
+
443
+ template <
444
+ typename loop1d_t,
445
+ std::enable_if_t<
446
+ std::is_convertible_v<
447
+ loop1d_t,
448
+ c10::function_ref<
449
+ void(char**, const int64_t* strides, int64_t size)>>,
450
+ int> = 0>
451
+ void serial_for_each(loop1d_t loop, Range range) {
452
+ serial_for_each(loop_2d_from_1d(loop), range);
453
+ }
454
+
455
+ void serial_for_each(loop2d_t loop, Range range) const;
456
+
457
+ /// Create a strides array for a Tensor with shape of this iterator. The
458
+ /// parameter `element_size` specifies the size of Tensor's data type in
459
+ /// bytes (e.g. `4` for `float`)
460
+ StrideVector compatible_stride(int64_t element_size) const;
461
+
462
+ /// Inverts the re-ordering done by reorder_dimensions. This can only be
463
+ /// called *before* coalesce_dimensions() is called.
464
+ DimVector invert_perm(IntArrayRef input) const;
465
+
466
+ /// Reapply same re-ordering as it is done by reorder_dimensions. This can
467
+ /// only be called *before* coalesce_dimensions() is called.
468
+ DimVector apply_perm_and_mul(IntArrayRef input, int mul) const;
469
+
470
+ /// Helper functions for CPU iteration
471
+ StrideVector get_dim_strides(int dim) const;
472
+ StrideVector get_strides() const;
473
+ StrideVector get_inner_strides() const {
474
+ return get_dim_strides(0);
475
+ }
476
+ PtrVector get_base_ptrs() const;
477
+
478
+ // Helper functions for advanced stride manipulations (e.g. torch.flip)
479
+ void _unsafe_set_arg_strides(const int64_t arg, IntArrayRef strides) {
480
+ operands_[arg].stride_bytes = strides;
481
+ }
482
+ void _unsafe_set_arg_data(const int64_t arg, void* data) {
483
+ operands_[arg].data = data;
484
+ }
485
+
486
+ // Helper functions for custom device, custom device can get OperandInfo and
487
+ // NameVector in their side.
488
+ const OperandInfo& operand(int arg = 0) const {
489
+ return operands_[arg];
490
+ }
491
+ OperandInfo& operand(int arg = 0) {
492
+ return operands_[arg];
493
+ }
494
+ NameVector& get_dim_names() {
495
+ return names_;
496
+ }
497
+ const NameVector& get_dim_names() const {
498
+ return names_;
499
+ }
500
+
501
+ /// true if the stride computation can use 32-bit arithmetic. Used by GPU
502
+ /// kernels
503
+ bool can_use_32bit_indexing() const;
504
+
505
+ /// An "iteratable" object that recursively splits this iterator into
506
+ /// sub-iterators that can use 32-bit indexing.
507
+ SplitUntil32Bit with_32bit_indexing() const;
508
+
509
+ /// If the kernel should accumulate into the output. Only relevant for CUDA
510
+ /// reductions.
511
+ bool should_accumulate() const {
512
+ return accumulate_;
513
+ }
514
+
515
+ /// Whether this iterator produces the actual output,
516
+ /// as opposed to something that will be accumulated further. Only relevant
517
+ /// for CUDA reductions.
518
+ bool is_final_output() const {
519
+ return final_output_;
520
+ }
521
+
522
+ bool has_contiguous_first_dim() const {
523
+ if (ndim() == 0) {
524
+ return true;
525
+ }
526
+
527
+ int num_tensors = ntensors();
528
+ for (const auto i : c10::irange(num_tensors)) {
529
+ if (strides(i)[0] != element_size(i)) {
530
+ return false;
531
+ }
532
+ }
533
+ return true;
534
+ }
535
+
536
+ void set_output_raw_strided(
537
+ int64_t output_idx,
538
+ IntArrayRef sizes,
539
+ IntArrayRef strides,
540
+ TensorOptions options,
541
+ DimnameList names) override;
542
+
543
+ #define TORCH_DISALLOW_TEMPORARIES_IMPL(methodname, maybestatic) \
544
+ maybestatic void methodname( \
545
+ TensorBase&& out, const TensorBase& a, const TensorBase& b) = delete; \
546
+ maybestatic void methodname( \
547
+ const TensorBase& out, TensorBase&& a, const TensorBase& b) = delete; \
548
+ maybestatic void methodname( \
549
+ const TensorBase& out, const TensorBase& a, TensorBase&& b) = delete; \
550
+ maybestatic void methodname( \
551
+ TensorBase&& out, TensorBase&& a, const TensorBase& b) = delete; \
552
+ maybestatic void methodname( \
553
+ TensorBase&& out, const TensorBase& a, TensorBase&& b) = delete; \
554
+ maybestatic void methodname( \
555
+ const TensorBase& out, TensorBase&& a, TensorBase&& b) = delete; \
556
+ maybestatic void methodname( \
557
+ TensorBase&& out, TensorBase&& a, TensorBase&& b) = delete;
558
+
559
+ #define TORCH_DISALLOW_TEMPORARIES(methodname) \
560
+ TORCH_DISALLOW_TEMPORARIES_IMPL(methodname, )
561
+
562
+ void build_binary_float_op(
563
+ const TensorBase& out,
564
+ const TensorBase& a,
565
+ const TensorBase& b);
566
+ void build_borrowing_binary_float_op(
567
+ const TensorBase& out,
568
+ const TensorBase& a,
569
+ const TensorBase& b);
570
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_binary_float_op)
571
+ void build_binary_op(
572
+ const TensorBase& out,
573
+ const TensorBase& a,
574
+ const TensorBase& b);
575
+ void build_borrowing_binary_op(
576
+ const TensorBase& out,
577
+ const TensorBase& a,
578
+ const TensorBase& b);
579
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_binary_op)
580
+ void build_unary_float_op(const TensorBase& out, const TensorBase& a);
581
+ void build_borrowing_unary_float_op(
582
+ const TensorBase& out,
583
+ const TensorBase& a);
584
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_unary_float_op)
585
+ void build_unary_op(const TensorBase& out, const TensorBase& a);
586
+ // Odd special case needed for pow. Has to borrow the output because
587
+ // it's a structured kernel, but the argument is potentially a copy.
588
+ void build_output_borrowing_argument_owning_unary_op(
589
+ const TensorBase& out,
590
+ const TensorBase& a);
591
+ void build_borrowing_unary_op(const TensorBase& out, const TensorBase& a);
592
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_unary_op)
593
+ void build_borrowing_unary_force_boolean_op(
594
+ const TensorBase& out,
595
+ const TensorBase& a);
596
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_unary_force_boolean_op)
597
+ void build_comparison_op(
598
+ const TensorBase& out,
599
+ const TensorBase& a,
600
+ const TensorBase& b);
601
+ void build_borrowing_comparison_op(
602
+ const TensorBase& out,
603
+ const TensorBase& a,
604
+ const TensorBase& b);
605
+ TORCH_DISALLOW_TEMPORARIES(build_borrowing_comparison_op)
606
+ // Another special case: we need to own the second argument for comparison
607
+ // ops.
608
+ void build_borrowing_except_last_argument_comparison_op(
609
+ const TensorBase& out,
610
+ const TensorBase& a,
611
+ const TensorBase& b);
612
+ void build_ternary_op(
613
+ const TensorBase& out,
614
+ const TensorBase& a,
615
+ const TensorBase& b,
616
+ const TensorBase& c);
617
+
618
+ #undef TORCH_DISALLOW_TEMPORARIES
619
+ protected:
620
+ // Mutable reference as it moves tensors out of TensorIteratorConfig
621
+ void populate_operands(TensorIteratorConfig&);
622
+ void mark_outputs();
623
+ void mark_resize_outputs(const TensorIteratorConfig&);
624
+ void compute_mem_overlaps(const TensorIteratorConfig&);
625
+ void compute_shape(const TensorIteratorConfig&);
626
+ void compute_strides(const TensorIteratorConfig&);
627
+ void reorder_dimensions();
628
+ void permute_dimensions(IntArrayRef perm);
629
+ void compute_types(const TensorIteratorConfig&);
630
+ ScalarType compute_common_dtype();
631
+ void allocate_or_resize_outputs();
632
+ bool fast_set_up(const TensorIteratorConfig&);
633
+ FastSetupType compute_fast_setup_type(const TensorIteratorConfig&);
634
+ void compute_names(const TensorIteratorConfig&);
635
+ void propagate_names_to_outputs();
636
+ void coalesce_dimensions();
637
+
638
+ protected:
639
+ /// Records the "computation" shape of the output tensor. The computation
640
+ /// shape is different from the regular shape in a few ways:
641
+ ///
642
+ /// - The shape may be permuted (via permute_dimensions) so that we
643
+ /// process the dimensions in the most computationally efficient order
644
+ /// (rather than the logical order given to us by the users.)
645
+ /// - The shape may have adjacent dimensions collapsed (via
646
+ /// coalesce_dimensions) so that we minimize the number of
647
+ /// dimensions we have to explicitly iterate over. For example,
648
+ /// a pointwise operation on a contiguous tensor "computationally"
649
+ /// consists of only a single dimension.
650
+ ///
651
+ /// In other words, the computation shape is the output shape as it
652
+ /// actually matters for implementing the kernel, but not necessarily the
653
+ /// output shape that the user will see in the end.
654
+ ///
655
+ /// The lifecycle of mutations to shape_ in TensorIterator:
656
+ /// - declare_static_shape() sets an initial shape explicitly
657
+ /// provided by user, otherwise
658
+ /// - compute_shape() computes the true (non-computational) shape
659
+ /// specified by the user.
660
+ /// - reorder_dimensions() reorders dimensions to improve coalescing.
661
+ /// - coalesce_dimensions() then coalesces adjacent dimensions when
662
+ /// possible.
663
+ ///
664
+ /// The shape may also be further modified if we create sub-TensorIterators,
665
+ /// e.g., via narrow or select_all_keeping_dim.
666
+ DimVector shape_;
667
+
668
+ /// Temporarily records the permutation computed by reorder_dimensions.
669
+ /// This permutation maps the computation output dimension (dim) to
670
+ /// the original true output dimension (perm_[dim]). It is used by
671
+ /// invert_perm to undo the permutation. After coalesce_dimensions is
672
+ /// called, the permutation is no longer valid (as, in general, there
673
+ /// is no permutation that will make computation dimensions to
674
+ /// output dimensions); methods that manipulate perm_ are obligated
675
+ /// to test that !has_coalesced_dimensions
676
+ DimVector perm_;
677
+
678
+ /// Has coalesce_dimensions() (or any moral equivalent, e.g., fast_build())
679
+ /// been called? This is SOLELY used to check validity of perm_.
680
+ bool has_coalesced_dimensions_ = false;
681
+
682
+ /// Whether iteration must be fixed. This disables dimension permuting and
683
+ /// also changes how for_each divides work among threads.
684
+ bool enforce_linear_iteration_ = false;
685
+
686
+ /// The index offsets into the original tensors for each dimension.
687
+ /// This is only non-zero when you narrow() a TensorIterator (e.g.,
688
+ /// when you make sub-TensorIterators).
689
+ DimVector view_offsets_;
690
+
691
+ /// The computed names of the output tensor. Computed by compute_names()
692
+ NameVector names_;
693
+
694
+ /// The operands of the TensorIterator: both the inputs and outputs. The
695
+ /// outputs MUST come first in the operands_ list. There is always an
696
+ /// operand for each output of the TensorIterator, even if TensorIterator
697
+ /// will ultimately be responsible for allocating the output; in those
698
+ /// cases, tensor is simply undefined (and will be populated later
699
+ /// during build()).
700
+ ///
701
+ /// This list is initially populated prior to build(), but build() mutates
702
+ /// OperandInfo to populate more information.
703
+ SmallVector<OperandInfo, 4> operands_;
704
+
705
+ /// Number of outputs in operands_ (the length of the outputs prefix
706
+ /// in operands_).
707
+ int num_outputs_ = 0;
708
+
709
+ /// Whether or not all operands have the same shape and are 1d+. Having all
710
+ /// the same shape affects whether or not the iterator is eligible for fast
711
+ /// setup.
712
+ bool all_ops_same_shape_ = false;
713
+ /// Whether or not all operands are 0d, this affects type promotion
714
+ bool all_ops_are_scalars_ = false;
715
+
716
+ /// The "computation" dtype of TensorIterator, specifying what the dtype
717
+ /// we will do the internal computation in TensorIterator. Typically,
718
+ /// this matches the dtype of the output tensors, but not always!
719
+ ScalarType common_dtype_ = ScalarType::Undefined;
720
+
721
+ /// This is currently defined as kCPU, or the device of the first non-CPU
722
+ /// tensor argument. See TensorIteratorBase::compute_types for details.
723
+ Device common_device_ = kCPU;
724
+
725
+ /// Set by split(), see should_accumulate() and is_final_output()
726
+ bool accumulate_ = false;
727
+ bool final_output_ = true;
728
+
729
+ // From TensorIteratorConfig
730
+ bool is_reduction_ = false;
731
+
732
+ /// Set by populate_operands(), says if we're handling meta tensors
733
+ bool is_meta_ = false;
734
+ };
735
+
736
+ struct TORCH_API TensorIterator final : public TensorIteratorBase {
737
+ TensorIterator() : TensorIteratorBase() {}
738
+ // Slicing is OK, TensorIterator guaranteed NOT to have any fields
739
+ TensorIterator(const TensorIteratorBase& iter) : TensorIteratorBase(iter) {}
740
+
741
+ #define TORCH_DISALLOW_TEMPORARIES(methodname) \
742
+ TORCH_DISALLOW_TEMPORARIES_IMPL(methodname, static)
743
+
744
+ static TensorIterator binary_float_op(
745
+ TensorBase& out,
746
+ const TensorBase& a,
747
+ const TensorBase& b);
748
+ static TensorIterator binary_op(
749
+ TensorBase& out,
750
+ const TensorBase& a,
751
+ const TensorBase& b);
752
+ static TensorIterator borrowing_binary_op(
753
+ const TensorBase& out,
754
+ const TensorBase& a,
755
+ const TensorBase& b);
756
+ TORCH_DISALLOW_TEMPORARIES(borrowing_binary_op)
757
+ static TensorIterator comparison_op(
758
+ TensorBase& out,
759
+ const TensorBase& a,
760
+ const TensorBase& b);
761
+ static TensorIterator unary_op(TensorBase& out, const TensorBase& a);
762
+ static TensorIterator unary_float_op(TensorBase& out, const TensorBase& a);
763
+ static TensorIterator nullary_op(TensorBase& out);
764
+ static TensorIterator borrowing_nullary_op(const TensorBase& out);
765
+ static TensorIterator borrowing_nullary_op(TensorBase&& out) = delete;
766
+ static TensorIterator reduce_op(TensorBase& out, const TensorBase& a);
767
+ static TensorIterator reduce_op(
768
+ TensorBase& out1,
769
+ TensorBase& out2,
770
+ const TensorBase& a);
771
+ #undef TORCH_DISALLOW_TEMPORARIES
772
+ #undef TORCH_DISALLOW_TEMPORARIES_IMPL
773
+
774
+ const Tensor& maybe_get_output(int64_t output_idx) override;
775
+ void set_output_raw_strided(
776
+ int64_t output_idx,
777
+ IntArrayRef sizes,
778
+ IntArrayRef strides,
779
+ TensorOptions options,
780
+ DimnameList names) override;
781
+ };
782
+
783
+ class TORCH_API TensorIteratorConfig final {
784
+ public:
785
+ friend struct TensorIteratorBase;
786
+ friend struct TensorIterator;
787
+
788
+ TensorIteratorConfig() = default;
789
+
790
+ C10_DISABLE_COPY_AND_ASSIGN(TensorIteratorConfig);
791
+ TensorIteratorConfig(TensorIteratorConfig&&) = default;
792
+ TensorIteratorConfig& operator=(TensorIteratorConfig&&) = default;
793
+ ~TensorIteratorConfig() = default;
794
+
795
+ /// Construction
796
+ // Stores input/output Tensors without incrementing the reference count.
797
+ // Important: the outputs have to be added before the inputs.
798
+ TensorIteratorConfig& add_output(const TensorBase& output) {
799
+ return add_borrowed_output(output);
800
+ }
801
+ TensorIteratorConfig& add_input(const TensorBase& input) {
802
+ return add_borrowed_input(input);
803
+ }
804
+ TensorIteratorConfig& add_const_input(const TensorBase& input) {
805
+ return add_borrowed_const_input(input);
806
+ }
807
+
808
+ // Borrowing from temporaries is unlikely to go well.
809
+ TensorIteratorConfig& add_output(TensorBase&& output) = delete;
810
+ TensorIteratorConfig& add_input(TensorBase&& input) = delete;
811
+ TensorIteratorConfig& add_const_input(TensorBase&& input) = delete;
812
+
813
+ // Stores input/output Tensors while incrementing the reference count.
814
+ // Note that add_{in,out}put are nearly always what you
815
+ // want, and the exception (adding an unnamed temporary) won't
816
+ // compile.
817
+ TensorIteratorConfig& add_owned_output(const TensorBase& output);
818
+ TensorIteratorConfig& add_owned_input(const TensorBase& input);
819
+ TensorIteratorConfig& add_owned_const_input(const TensorBase& input);
820
+
821
+ // Advanced API: stores input/output Tensors without incrementing
822
+ // the reference count. The caller must ensure that these Tensors
823
+ // live at least as long as this TensorIteratorConfig and any
824
+ // TensorIteratorBase built from this TensorIteratorConfig.
825
+ // Important: the outputs have to be added before the inputs.
826
+ TensorIteratorConfig& add_borrowed_output(const TensorBase& output);
827
+ TensorIteratorConfig& add_borrowed_input(const TensorBase& input);
828
+ TensorIteratorConfig& add_borrowed_const_input(const TensorBase& input);
829
+
830
+ // Borrowing from temporaries is unlikely to go well.
831
+ TensorIteratorConfig& add_borrowed_output(TensorBase&& output) = delete;
832
+ TensorIteratorConfig& add_borrowed_input(TensorBase&& input) = delete;
833
+ TensorIteratorConfig& add_borrowed_const_input(TensorBase&& input) = delete;
834
+
835
+ // Sets the check_mem_overlap_ flag, which is true by default.
836
+ // If true, inputs are checked for partial overlap with the outputs and
837
+ // outputs are checked for internal overlap (e.g. broadcasted views). An error
838
+ // is raised if unacceptable overlap is detected.
839
+ // If you're migrating an existing operator to using TensorIterator, please
840
+ // consider if the previous implementation checked memory overlap. If it did
841
+ // not, and if the operator is idempotent (for example, Tensor.fill_(0)), then
842
+ // checking memory overlap is BC-breaking. Please don't check memory overlap
843
+ // in that case.
844
+ TensorIteratorConfig& set_check_mem_overlap(bool check_mem_overlap) {
845
+ check_mem_overlap_ = check_mem_overlap;
846
+ return *this;
847
+ }
848
+
849
+ // Sets the check_all_same_dtype_ flag, which is true by default
850
+ // If true, checks that all inputs and defined outputs have the same dtype
851
+ // Setting either of promote_inputs_to_common_dtype_
852
+ // or cast_common_dtype_to_outputs_ to true will set
853
+ // check_all_same_dtype_ to false.
854
+ TensorIteratorConfig& check_all_same_dtype(const bool _check_all_same_dtype) {
855
+ check_all_same_dtype_ = _check_all_same_dtype;
856
+ return *this;
857
+ }
858
+
859
+ // Sets the check_all_same_device_ flag, which is true by default
860
+ // If true, all operands must be on the same device, with the possible
861
+ // exception of CPU scalars, which can be passed to some CUDA kernels
862
+ // as kernel arguments.
863
+ TensorIteratorConfig& check_all_same_device(
864
+ const bool _check_all_same_device) {
865
+ check_all_same_device_ = _check_all_same_device;
866
+ return *this;
867
+ }
868
+
869
+ // Sets the enforce_safe_casting_to_output_ flag, which is false by default
870
+ // If true, the iterator's "common dtype" must be computable
871
+ // (see the [Common Dtype Computation] note) and
872
+ // canCast(common dtype, output dtype) must be true for all outputs.
873
+ TensorIteratorConfig& enforce_safe_casting_to_output(
874
+ const bool _enforce_safe_casting_to_output) {
875
+ enforce_safe_casting_to_output_ = _enforce_safe_casting_to_output;
876
+ return *this;
877
+ }
878
+
879
+ // Sets the enforce_linear_iteration_ flag, which is false by default.
880
+ // If true, iteration goes in the same order as a C-contiguous tensor
881
+ // is layed out in memory. i.e. last dimension iterates fastest.
882
+ //
883
+ // This iteration order can be less efficient and may even prevent
884
+ // vectorization. So only use if the correctness of your kernel depends on it.
885
+ TensorIteratorConfig& enforce_linear_iteration(
886
+ const bool _enforce_linear_iteration = true) {
887
+ enforce_linear_iteration_ = _enforce_linear_iteration;
888
+ return *this;
889
+ }
890
+
891
+ // Sets the promote_inputs_to_common_dtype_ flag, which is false by default
892
+ // If true, the iterator's "common dtype" is always computed (see the
893
+ // [Common Dtype Computation] note) and, on the CPU, temporary copies of
894
+ // the inputs in the common dtype are passed as the actual inputs to
895
+ // the operation.
896
+ // Setting this flag to true sets check_all_same_dtype_ to false.
897
+ TensorIteratorConfig& promote_inputs_to_common_dtype(
898
+ const bool _promote_inputs_to_common_dtype) {
899
+ promote_inputs_to_common_dtype_ = _promote_inputs_to_common_dtype;
900
+ if (_promote_inputs_to_common_dtype) {
901
+ check_all_same_dtype_ = false;
902
+ }
903
+ return *this;
904
+ }
905
+
906
+ // Sets the promote_integer_inputs_to_float_ flag, which is false by default
907
+ // NOTE: If set to true, the promote_inputs_to_common_dtype_ must also be
908
+ // true. If true, if the iterator's "common dtype" is an integral type
909
+ // (including bool)
910
+ // then it is changed to the default float scalar type.
911
+ TensorIteratorConfig& promote_integer_inputs_to_float(
912
+ const bool _promote_integer_inputs_to_float) {
913
+ promote_integer_inputs_to_float_ = _promote_integer_inputs_to_float;
914
+ TORCH_INTERNAL_ASSERT(
915
+ !promote_integer_inputs_to_float_ || promote_inputs_to_common_dtype_);
916
+ return *this;
917
+ }
918
+
919
+ TensorIteratorConfig& is_reduction(const bool _is_reduction) {
920
+ is_reduction_ = _is_reduction;
921
+ return *this;
922
+ }
923
+
924
+ TensorIteratorConfig& allow_cpu_scalars(const bool _allow_cpu_scalars) {
925
+ allow_cpu_scalars_ = _allow_cpu_scalars;
926
+ return *this;
927
+ }
928
+
929
+ // Sets the cast_common_dtype_to_outputs_ flag, which is false by default
930
+ // If true, the iterator's "common dtype" must be computatable
931
+ // (see the [Common Dtype Computation] note) and, on the CPU, temporary
932
+ // copies of the outputs are passed as the actual output to the operation.
933
+ // These temporaries are then copied to the original outputs after
934
+ // the operation is performed (see cast_outputs()).
935
+ // Setting this flag to true sets check_all_same_dtype_ to false.
936
+ TensorIteratorConfig& cast_common_dtype_to_outputs(
937
+ const bool _cast_common_dtype_to_outputs) {
938
+ cast_common_dtype_to_outputs_ = _cast_common_dtype_to_outputs;
939
+ if (_cast_common_dtype_to_outputs) {
940
+ check_all_same_dtype_ = false;
941
+ }
942
+ return *this;
943
+ }
944
+
945
+ TensorIteratorConfig& resize_outputs(bool resize_outputs) {
946
+ resize_outputs_ = resize_outputs;
947
+ return *this;
948
+ }
949
+
950
+ // Bypass output dtype/device computation and fix the dtype/device as
951
+ // specified here.
952
+ TensorIteratorConfig& declare_static_dtype_and_device(
953
+ ScalarType dtype,
954
+ Device device);
955
+ TensorIteratorConfig& declare_static_dtype(ScalarType dtype);
956
+ TensorIteratorConfig& declare_static_device(Device device);
957
+ TensorIteratorConfig& declare_static_shape(IntArrayRef shape);
958
+ TensorIteratorConfig& declare_static_shape(
959
+ IntArrayRef shape,
960
+ IntArrayRef squash_dims);
961
+
962
+ // It would be better if this was && qualified, but this would be at the cost
963
+ // of a lot of boilerplate above
964
+ TensorIterator build() {
965
+ TensorIterator iter;
966
+ iter.build(*this);
967
+ return iter;
968
+ }
969
+
970
+ private:
971
+ bool is_tensor_const(size_t idx);
972
+
973
+ SmallVector<c10::MaybeOwned<TensorBase>, 4> tensors_;
974
+ int num_outputs_ = 0;
975
+ int num_inputs_ = 0;
976
+
977
+ std::optional<DimVector> static_shape_ = std::nullopt;
978
+ std::optional<ScalarType> static_dtype_ = std::nullopt;
979
+ std::optional<Device> static_device_ = std::nullopt;
980
+ bool check_mem_overlap_ = true;
981
+ bool allow_cpu_scalars_ = false;
982
+ bool is_reduction_ = false;
983
+ bool resize_outputs_ = true;
984
+ bool check_all_same_dtype_ = true;
985
+ bool check_all_same_device_ = true;
986
+ bool enforce_safe_casting_to_output_ = false;
987
+ bool enforce_linear_iteration_ = false;
988
+ bool promote_inputs_to_common_dtype_ = false;
989
+ bool promote_integer_inputs_to_float_ = false;
990
+ bool cast_common_dtype_to_outputs_ = false;
991
+
992
+ SmallVector<size_t, 4> const_tensor_indices_;
993
+ };
994
+
995
+ /// A container-like struct that acts as if it contains splits of a
996
+ /// TensorIterator that can use 32-bit indexing. Taken together the splits cover
997
+ /// the original TensorIterator.
998
+ struct TORCH_API SplitUntil32Bit {
999
+ // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
1000
+ struct TORCH_API iterator {
1001
+ iterator() = default;
1002
+ iterator(const TensorIteratorBase& iter);
1003
+ iterator(iterator&&) = default;
1004
+ iterator& operator=(iterator&&) = default;
1005
+ ~iterator() = default;
1006
+
1007
+ // Guaranteed to be a TensorIterator proper!
1008
+ TensorIterator& operator*() const;
1009
+ iterator& operator++();
1010
+ bool operator==(const iterator& other) const {
1011
+ // two iterators are equal if they are the same object or they're both
1012
+ // empty
1013
+ return this == &other || (vec.empty() && other.vec.empty());
1014
+ }
1015
+ // needed for C++11 range-based for loop
1016
+ bool operator!=(const iterator& other) const {
1017
+ return !(*this == other);
1018
+ }
1019
+
1020
+ /// stack of TensorIterators to be split
1021
+ std::vector<std::unique_ptr<TensorIterator>> vec;
1022
+ };
1023
+
1024
+ SplitUntil32Bit(const TensorIteratorBase& iter) : iter(iter) {}
1025
+
1026
+ iterator begin() const;
1027
+ iterator end() const;
1028
+
1029
+ private:
1030
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1031
+ const TensorIteratorBase& iter;
1032
+ };
1033
+
1034
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorIteratorInternal.h ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/TensorIterator.h>
3
+ #include <c10/util/SmallBuffer.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ namespace at {
7
+
8
+ struct DimCounter {
9
+ DimCounter(IntArrayRef shape, Range range);
10
+
11
+ void increment(const std::array<int64_t, 2>& step);
12
+ bool is_done() const;
13
+ std::array<int64_t, 2> max_2d_step() const;
14
+
15
+ IntArrayRef shape;
16
+ Range range;
17
+ c10::SmallBuffer<int64_t, 4> values;
18
+ int64_t offset;
19
+ };
20
+
21
+ namespace internal {
22
+
23
+ inline void get_data_ptrs(
24
+ char** ptrs,
25
+ ArrayRef<char*> base,
26
+ IntArrayRef strides,
27
+ IntArrayRef counter) {
28
+ const auto ntensors = base.size();
29
+ const auto ndim = counter.size();
30
+ std::copy(base.begin(), base.end(), ptrs);
31
+ for (const auto dim : c10::irange(ndim)) {
32
+ int64_t value = counter[dim];
33
+ for (const auto arg : c10::irange(ntensors)) {
34
+ ptrs[arg] += value * strides[dim * ntensors + arg];
35
+ }
36
+ }
37
+ }
38
+
39
+ inline void serial_for_each(
40
+ IntArrayRef shape,
41
+ IntArrayRef strides,
42
+ char** base_ptrs,
43
+ size_t ntensors,
44
+ typename TensorIteratorBase::loop2d_t loop,
45
+ Range range) {
46
+ const auto ndim = shape.size();
47
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
48
+ strides.size() == ntensors * std::max(size_t{2}, ndim));
49
+
50
+ if (ndim <= 1) {
51
+ if (range.begin == 0) {
52
+ loop(base_ptrs, strides.data(), range.size(), 1);
53
+ } else {
54
+ c10::SmallBuffer<char*, 4> ptrs(ntensors);
55
+ get_data_ptrs(ptrs.data(), {base_ptrs, ntensors}, strides, {range.begin});
56
+ loop(ptrs.data(), strides.data(), range.size(), 1);
57
+ }
58
+ } else {
59
+ c10::SmallBuffer<char*, 4> ptrs(ntensors);
60
+ auto counter = DimCounter(shape, range);
61
+ while (!counter.is_done()) {
62
+ get_data_ptrs(
63
+ ptrs.data(), {base_ptrs, ntensors}, strides, counter.values);
64
+ auto step = counter.max_2d_step();
65
+ loop(ptrs.data(), strides.data(), step[0], step[1]);
66
+ counter.increment(step);
67
+ }
68
+ }
69
+ }
70
+
71
+ } // namespace internal
72
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorMeta.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/DimVector.h>
4
+ #include <ATen/core/Dimname.h>
5
+ #include <c10/core/TensorOptions.h>
6
+ #include <c10/util/strides.h>
7
+
8
+ namespace at {
9
+
10
+ class Tensor;
11
+
12
+ namespace impl {
13
+
14
+ // Use this to define the prototype for a meta function. There are two
15
+ // versions; one that takes one argument (just the operator name), or FUNC2
16
+ // variant that takes two arguments (operator name and overload name).
17
+ //
18
+ // Example usage:
19
+ //
20
+ // TORCH_META_FUNC2(add, Tensor) (
21
+ // const Tensor& self, const Tensor& other
22
+ // ) {
23
+ // ... compute sizes and options ...
24
+ // set_output(sizes, options);
25
+ // }
26
+ //
27
+ #define TORCH_META_FUNC(name) void structured_##name::meta
28
+ #define TORCH_META_FUNC2(name, overload) \
29
+ void structured_##name##_##overload::meta
30
+
31
+ // These are versions of TORCH_META_FUNC(2) that include a precompute_out struct
32
+ // as a return value. They should be used when the kernel in question has
33
+ // precomputed values declared in native_functions.yaml and the corresponding
34
+ // implementation should return an instance of the aforementioned struct.
35
+ #define TORCH_PRECOMPUTE_META_FUNC(name) \
36
+ structured_##name::meta_return_ty structured_##name::meta
37
+ #define TORCH_PRECOMPUTE_META_FUNC2(name, overload) \
38
+ structured_##name##_##overload::meta_return_ty \
39
+ structured_##name##_##overload::meta
40
+
41
+ // Use this to create a precompute struct in a meta function.
42
+ #define TORCH_PRECOMPUTE_STRUCT(name) structured_##name::precompute_out<>
43
+ #define TORCH_PRECOMPUTE_STRUCT2(name, overload) \
44
+ structured_##name##_##overload::precompute_out<>
45
+
46
+ // Use this to define the prototype for an implementation. This takes only
47
+ // one argument, which is the name of the dispatch key entry you're
48
+ // implementing.
49
+ //
50
+ // Example usage:
51
+ //
52
+ // TORCH_IMPL_FUNC(add_cpu) (
53
+ // Tensor& result, const Tensor& self, const Tensor& other
54
+ // ) {
55
+ // ... do the actual implementation ...
56
+ // }
57
+ //
58
+ #define TORCH_IMPL_FUNC(name) void structured_##name::impl
59
+
60
+ // Base class for all structured kernel classes. The set_output virtual
61
+ // method is varied depending whether or not the operator is
62
+ // functional/out/inplace, and could also be specialized for CPU/CUDA/etc
63
+ // (although presently it isn't).
64
+ //
65
+ // A notable subclass of this interface is TensorIteratorBase.
66
+ struct TORCH_API MetaBase {
67
+ MetaBase() = default;
68
+ MetaBase(const MetaBase&) = default;
69
+ MetaBase& operator=(const MetaBase&) = default;
70
+ MetaBase(MetaBase&&) noexcept = default;
71
+ MetaBase& operator=(MetaBase&&) noexcept = default;
72
+ virtual const Tensor& maybe_get_output(int64_t output_idx) = 0;
73
+
74
+ // Note: [set_output_*]
75
+ // See: https://github.com/pytorch/pytorch/issues/69813
76
+ // Whenever defining the output properties in the META function of a
77
+ // structured kernel (what was usually done with `set_output`), use one of
78
+ // these 3 variants, instead. In order to decide which variant to use, check
79
+ // the following decision tree:
80
+ //
81
+ // - Can the kernel you are going to implement support output tensors
82
+ // with arbitrary strides?
83
+ // |
84
+ // -- YES: `set_output_raw_strided`
85
+ // |
86
+ // -- NO: Should the output tensor strides be contiguous?
87
+ // |
88
+ // -- YES: `set_output_contiguous`
89
+ // |
90
+ // -- NO: `set_output_strided`
91
+ //
92
+ // Use this function whenever the kernel requires specific strides for the
93
+ // output. If `strides` does not match the given output strides, proxy outputs
94
+ // will be created and passed to the IMPL function.
95
+ virtual void set_output_strided(
96
+ int64_t output_idx [[maybe_unused]],
97
+ IntArrayRef sizes [[maybe_unused]],
98
+ IntArrayRef strides [[maybe_unused]],
99
+ TensorOptions options [[maybe_unused]],
100
+ DimnameList names [[maybe_unused]] = {}) {
101
+ TORCH_INTERNAL_ASSERT(false, "set_output_strided not implemented.");
102
+ }
103
+
104
+ // Use this function whenever the kernel knows how to handle arbitrary strided
105
+ // outputs. This function has the same behavior as the old `set_output`: it
106
+ // will only re-stride if the given output was resized.
107
+ virtual void set_output_raw_strided(
108
+ int64_t output_idx [[maybe_unused]],
109
+ IntArrayRef sizes [[maybe_unused]],
110
+ IntArrayRef strides_hint [[maybe_unused]],
111
+ TensorOptions options [[maybe_unused]],
112
+ DimnameList names [[maybe_unused]] = {}) {
113
+ TORCH_INTERNAL_ASSERT(false, "set_output_strided not implemented.");
114
+ }
115
+
116
+ // Use this function if the kernel requires contiguous strides.
117
+ // Alias for `set_output_strided`, but with contiguous strides.
118
+ void set_output_contiguous(
119
+ int64_t output_idx,
120
+ IntArrayRef sizes,
121
+ TensorOptions options,
122
+ DimnameList names = {}) {
123
+ auto strides = c10::contiguous_strides(sizes);
124
+ set_output_strided(output_idx, sizes, strides, options, names);
125
+ }
126
+
127
+ // Returns a reference to an undefined tensor if there is no presupplied
128
+ // output
129
+ const Tensor& maybe_get_output() {
130
+ return maybe_get_output(0);
131
+ }
132
+ virtual ~MetaBase() = default;
133
+ };
134
+
135
+ } // namespace impl
136
+
137
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorNames.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/WrapDimUtils.h>
4
+
5
+ namespace at::namedinference {
6
+
7
+ // TensorName and TensorNames are wrappers around Dimname and DimnameList
8
+ // that contain helper functions to make writing name inference rules easier.
9
+ //
10
+ // A TensorName represents a Dimname associated with some DimnameList (from a
11
+ // Tensor). This encapsulates all the information that is needed to check if
12
+ // names *match* and to *unify* names.
13
+ //
14
+ // Definition: Two names in two tensors *match* if they are equal, or if at
15
+ // least one of them is a wildcard that can be *refined* to the other name.
16
+ //
17
+ // Definition: unify(name, other) fails if the names do not match. Otherwise,
18
+ // it returns the most refined of name and other.
19
+ //
20
+ // Here is an example of checking if two names match.
21
+ // tensor: Tensor[A, None]
22
+ // other: Tensor[A]
23
+ //
24
+ // Let's say we wish to check if tensor.names[-1] matches other.names[-1].
25
+ // None (in tensor) cannot match A (in other) because if the None were refined
26
+ // to A, `tensor` would have duplicate names [A, A]. Therefore we need to check
27
+ // tensor.names [A, None] for the existence of A.
28
+ struct TORCH_API TensorName {
29
+ explicit TensorName(ArrayRef<Dimname> origin, int origin_idx)
30
+ : origin_(origin),
31
+ name_(origin[maybe_wrap_dim(
32
+ origin_idx,
33
+ static_cast<int64_t>(origin.size()))]),
34
+ origin_idx_(origin_idx) {}
35
+
36
+ // op_name is only used for error reporting.
37
+ const TensorName& unify(const TensorName& other, const char* op_name) const;
38
+ Dimname toDimname() const;
39
+
40
+ private:
41
+ ArrayRef<Dimname> origin_;
42
+ Dimname name_;
43
+ int origin_idx_; // A named tensor can have at most 64 dims.
44
+
45
+ TORCH_API friend std::ostream& operator<<(
46
+ std::ostream& out,
47
+ const TensorName& tensorname);
48
+ };
49
+
50
+ using TensorNameVec = SmallVector<TensorName, 10>;
51
+
52
+ struct TORCH_API TensorNames {
53
+ explicit TensorNames(ArrayRef<Dimname> names);
54
+
55
+ // Create TensorNames from names[start:end]. Each individual TensorName stores
56
+ // `names`, NOT names[start:end], because the original tensor's names are
57
+ // `names`.
58
+ explicit TensorNames(ArrayRef<Dimname> names, int64_t start, int64_t end);
59
+
60
+ // op_name is only used for error reporting.
61
+ TensorNames& unifyFromRightInplace(
62
+ const TensorNames& other,
63
+ const char* op_name = "unify");
64
+ void checkUnique(const char* op_name) const;
65
+
66
+ void append(TensorName name);
67
+ std::vector<Dimname> toDimnameVec() const;
68
+
69
+ private:
70
+ explicit TensorNames(TensorNameVec&& names) : names_(std::move(names)) {}
71
+
72
+ TensorNameVec names_;
73
+ };
74
+
75
+ } // namespace at::namedinference
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorOperators.h ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/core/Scalar.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/Functions.h>
8
+ #else
9
+ #include <ATen/ops/empty_like.h>
10
+ #endif
11
+
12
+ namespace at {
13
+
14
+ #define AT_FORALL_BINARY_OPS(_) \
15
+ _(+, x.add(y), y.add(x)) \
16
+ _(*, x.mul(y), y.mul(x)) \
17
+ _(-, \
18
+ x.sub(y), \
19
+ ::at::empty_like(y, at::MemoryFormat::Preserve).fill_(x).sub_(y)) \
20
+ _(/, \
21
+ x.div(y), \
22
+ ::at::empty_like(y, at::MemoryFormat::Preserve).fill_(x).div_(y)) \
23
+ _(%, \
24
+ x.remainder(y), \
25
+ ::at::empty_like(y, at::MemoryFormat::Preserve).fill_(x).remainder_(y)) \
26
+ _(&, x.bitwise_and(y), y.bitwise_and(x)) \
27
+ _(|, x.bitwise_or(y), y.bitwise_or(x)) \
28
+ _(^, x.bitwise_xor(y), y.bitwise_xor(x)) \
29
+ _(<, x.lt(y), y.gt(x)) \
30
+ _(<=, x.le(y), y.ge(x)) \
31
+ _(>, x.gt(y), y.lt(x)) \
32
+ _(>=, x.ge(y), y.le(x)) \
33
+ _(==, x.eq(y), y.eq(x)) \
34
+ _(!=, x.ne(y), y.ne(x))
35
+
36
+ #define DEFINE_OPERATOR(op, body, reverse_scalar_body) \
37
+ inline Tensor operator op(const Tensor& x, const Tensor& y) { \
38
+ return body; \
39
+ } \
40
+ inline Tensor operator op(const Tensor& x, const Scalar& y) { \
41
+ return body; \
42
+ } \
43
+ inline Tensor operator op(const Scalar& x, const Tensor& y) { \
44
+ return reverse_scalar_body; \
45
+ }
46
+
47
+ AT_FORALL_BINARY_OPS(DEFINE_OPERATOR)
48
+ #undef DEFINE_OPERATOR
49
+ #undef AT_FORALL_BINARY_OPS
50
+
51
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorOptions.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #pragma once
2
+ #include <c10/core/TensorOptions.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorSubclassLikeUtils.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/List.h>
3
+ #include <ATen/core/Tensor.h>
4
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
5
+
6
+ #ifndef AT_PER_OPERATOR_HEADERS
7
+ #include <ATen/Functions.h>
8
+ #else
9
+ #include <ATen/ops/equal.h>
10
+ #endif
11
+
12
+ namespace at {
13
+
14
+ // Note [Tensor-subclass-like Tensors]
15
+ // Tensor-subclass-like is defined as:
16
+ // - a Tensor subclass (via __torch_dispatch__ in Python or extending
17
+ // TensorImpl in C++)
18
+ // - anything else that shares the same perils as Tensor subclasses.
19
+ // For example, many Tensor subclasses do not have storage and meta Tensors
20
+ // do not have storage either, so meta Tensors belong here.
21
+ //
22
+ // We should ensure that PyTorch internals supports Tensor-subclass-like
23
+ // objects. In particular, Tensor-subclass-like objects struggle with two
24
+ // classes of operations that are problematic for Tensor subclasses:
25
+ // 1. Because some Tensor subclasses do not have storage, .item() or
26
+ // .data_ptr() calls are not good.
27
+ // 2. Certain in-place operations can eliminate the typing of the Tensor
28
+ // subclass. For example:
29
+ // >>> torch.zeros(input.sizes(), grad.options()).diag().copy_(input)
30
+ // If input is a Tensor subclass, then the above ends up either erroring out
31
+ // or returning a regular non-Tensor-subclass Tensor!
32
+
33
+ constexpr auto kFunctorchWrappedTensors = DispatchKeySet(
34
+ {DispatchKey::FuncTorchGradWrapper,
35
+ DispatchKey::FuncTorchBatched,
36
+ DispatchKey::Functionalize});
37
+
38
+ constexpr auto kTensorSubclassLike =
39
+ kFunctorchWrappedTensors |
40
+ DispatchKeySet(
41
+ {// WARNING: DO NOT put combined backend component + functionality keys
42
+ // here, you will incorrectly always match on the functionality key
43
+ // no matter the backend component
44
+ DispatchKey::Batched,
45
+ DispatchKey::Sparse,
46
+ DispatchKey::SparseCsr,
47
+ DispatchKey::Python}) |
48
+ DispatchKeySet(BackendComponent::MetaBit);
49
+
50
+ inline bool isTensorSubclassLike(const Tensor& tensor) {
51
+ if (c10::impl::dispatch_mode_enabled())
52
+ return true;
53
+ auto key_set = tensor.unsafeGetTensorImpl()->key_set();
54
+ return !(key_set & kTensorSubclassLike).empty();
55
+ }
56
+
57
+ inline bool areAnyTensorSubclassLike(TensorList tensors) {
58
+ if (c10::impl::dispatch_mode_enabled())
59
+ return true;
60
+ return std::any_of(tensors.begin(), tensors.end(), isTensorSubclassLike);
61
+ }
62
+
63
+ inline bool areAnyOptionalTensorSubclassLike(
64
+ const c10::List<std::optional<Tensor>>& tensors) {
65
+ if (c10::impl::dispatch_mode_enabled())
66
+ return true;
67
+ return std::any_of(
68
+ tensors.begin(),
69
+ tensors.end(),
70
+ [](const std::optional<Tensor>& opt_tensor) {
71
+ return (
72
+ opt_tensor.has_value() && isTensorSubclassLike(opt_tensor.value()));
73
+ });
74
+ }
75
+
76
+ // Helper function to deal testing truthfulness of a scalar tensor
77
+ // in a Composite Compliant manner.
78
+ // NOTE: This function expects a scalar tensor of boolean dtype.
79
+ // Eg.
80
+ // Non-Composite Compliant Pattern : (t == 0).all().item<bool>()
81
+ // Composite Compliant Patter : is_salar_tensor_true((t == 0).all())
82
+ inline bool is_scalar_tensor_true(const Tensor& t) {
83
+ TORCH_INTERNAL_ASSERT(t.dim() == 0)
84
+ TORCH_INTERNAL_ASSERT(t.scalar_type() == kBool)
85
+ return at::equal(t, t.new_ones({}, t.options()));
86
+ }
87
+
88
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TensorUtils.h ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/DimVector.h>
4
+ #include <ATen/EmptyTensor.h>
5
+ #include <ATen/Tensor.h>
6
+ #include <ATen/TensorGeometry.h>
7
+ #include <ATen/Utils.h>
8
+
9
+ #include <utility>
10
+
11
+ // These functions are NOT in Utils.h, because this file has a dep on Tensor.h
12
+
13
+ #define TORCH_CHECK_TENSOR_ALL(cond, ...) \
14
+ TORCH_CHECK((cond)._is_all_true().item<bool>(), __VA_ARGS__);
15
+
16
+ namespace at {
17
+
18
+ // The following are utility functions for checking that arguments
19
+ // make sense. These are particularly useful for native functions,
20
+ // which do NO argument checking by default.
21
+
22
+ struct TORCH_API TensorArg {
23
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
24
+ const Tensor& tensor;
25
+ const char* name;
26
+ int pos; // 1-indexed
27
+ TensorArg(const Tensor& tensor, const char* name, int pos)
28
+ : tensor(tensor), name(name), pos(pos) {}
29
+ // Try to mitigate any possibility of dangling reference to temporaries.
30
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
31
+ TensorArg(Tensor&& tensor, const char* name, int pos) = delete;
32
+ const Tensor* operator->() const {
33
+ return &tensor;
34
+ }
35
+ const Tensor& operator*() const {
36
+ return tensor;
37
+ }
38
+ };
39
+
40
+ struct TORCH_API TensorGeometryArg {
41
+ TensorGeometry tensor;
42
+ const char* name;
43
+ int pos; // 1-indexed
44
+ /* implicit */ TensorGeometryArg(TensorArg arg)
45
+ : tensor(TensorGeometry{arg.tensor}), name(arg.name), pos(arg.pos) {}
46
+ TensorGeometryArg(TensorGeometry tensor, const char* name, int pos)
47
+ : tensor(std::move(tensor)), name(name), pos(pos) {}
48
+ const TensorGeometry* operator->() const {
49
+ return &tensor;
50
+ }
51
+ const TensorGeometry& operator*() const {
52
+ return tensor;
53
+ }
54
+ };
55
+
56
+ // A string describing which function did checks on its input
57
+ // arguments.
58
+ // TODO: Consider generalizing this into a call stack.
59
+ using CheckedFrom = const char*;
60
+
61
+ // The undefined convention: singular operators assume their arguments
62
+ // are defined, but functions which take multiple tensors will
63
+ // implicitly filter out undefined tensors (to make it easier to perform
64
+ // tests which should apply if the tensor is defined, and should not
65
+ // otherwise.)
66
+ //
67
+ // NB: This means that the n-ary operators take lists of TensorArg,
68
+ // not TensorGeometryArg, because the Tensor to TensorGeometry
69
+ // conversion will blow up if you have undefined tensors.
70
+
71
+ TORCH_API std::ostream& operator<<(
72
+ std::ostream& out,
73
+ const TensorGeometryArg& t);
74
+ TORCH_API void checkDim(
75
+ CheckedFrom c,
76
+ const Tensor& tensor,
77
+ const char* name,
78
+ int pos, // 1-indexed
79
+ int64_t dim);
80
+ TORCH_API void checkDim(CheckedFrom c, const TensorGeometryArg& t, int64_t dim);
81
+ // NB: this is an inclusive-exclusive range
82
+ TORCH_API void checkDimRange(
83
+ CheckedFrom c,
84
+ const TensorGeometryArg& t,
85
+ int64_t dim_start,
86
+ int64_t dim_end);
87
+ TORCH_API void checkSameDim(
88
+ CheckedFrom c,
89
+ const TensorGeometryArg& t1,
90
+ const TensorGeometryArg& t2);
91
+ TORCH_API void checkContiguous(CheckedFrom c, const TensorGeometryArg& t);
92
+ TORCH_API void checkAllContiguous(CheckedFrom c, at::ArrayRef<TensorArg> ts);
93
+ TORCH_API void checkSize(
94
+ CheckedFrom c,
95
+ const TensorGeometryArg& t,
96
+ IntArrayRef sizes);
97
+ TORCH_API void checkSize_symint(
98
+ CheckedFrom c,
99
+ const TensorGeometryArg& t,
100
+ c10::SymIntArrayRef sizes);
101
+ TORCH_API void checkSize(
102
+ CheckedFrom c,
103
+ const TensorGeometryArg& t,
104
+ int64_t dim,
105
+ int64_t size);
106
+ TORCH_API void checkSize_symint(
107
+ CheckedFrom c,
108
+ const TensorGeometryArg& t,
109
+ int64_t dim,
110
+ const c10::SymInt& size);
111
+ TORCH_API void checkNumel(
112
+ CheckedFrom c,
113
+ const TensorGeometryArg& t,
114
+ int64_t numel);
115
+ TORCH_API void checkSameNumel(
116
+ CheckedFrom c,
117
+ const TensorArg& t1,
118
+ const TensorArg& t2);
119
+ TORCH_API void checkAllSameNumel(CheckedFrom c, ArrayRef<TensorArg> tensors);
120
+ TORCH_API void checkScalarType(CheckedFrom c, const TensorArg& t, ScalarType s);
121
+ TORCH_API void checkScalarTypes(
122
+ CheckedFrom c,
123
+ const TensorArg& t,
124
+ at::ArrayRef<ScalarType> l);
125
+ TORCH_API void checkSameGPU(
126
+ CheckedFrom c,
127
+ const TensorArg& t1,
128
+ const TensorArg& t2);
129
+ TORCH_API void checkAllSameGPU(CheckedFrom c, ArrayRef<TensorArg> tensors);
130
+ TORCH_API void checkSameType(
131
+ CheckedFrom c,
132
+ const TensorArg& t1,
133
+ const TensorArg& t2);
134
+ TORCH_API void checkAllSameType(CheckedFrom c, ArrayRef<TensorArg> tensors);
135
+ TORCH_API void checkSameSize(
136
+ CheckedFrom c,
137
+ const TensorArg& t1,
138
+ const TensorArg& t2);
139
+ TORCH_API void checkAllSameSize(CheckedFrom c, ArrayRef<TensorArg> tensors);
140
+ TORCH_API void checkDefined(CheckedFrom c, const TensorArg& t);
141
+ TORCH_API void checkAllDefined(CheckedFrom c, at::ArrayRef<TensorArg> t);
142
+
143
+ // FixMe: does TensorArg slow things down?
144
+ TORCH_API void checkBackend(
145
+ CheckedFrom c,
146
+ at::ArrayRef<Tensor> t,
147
+ at::Backend backend);
148
+
149
+ TORCH_API void checkDeviceType(
150
+ CheckedFrom c,
151
+ at::ArrayRef<Tensor> tensors,
152
+ at::DeviceType device_type);
153
+
154
+ TORCH_API void checkLayout(CheckedFrom c, const Tensor& t, Layout layout);
155
+
156
+ TORCH_API void checkLayout(
157
+ CheckedFrom c,
158
+ at::ArrayRef<Tensor> tensors,
159
+ at::Layout layout);
160
+
161
+ // Methods for getting data_ptr if tensor is defined
162
+ TORCH_API void* maybe_data_ptr(const Tensor& tensor);
163
+ TORCH_API void* maybe_data_ptr(const TensorArg& tensor);
164
+
165
+ TORCH_API void check_dim_size(
166
+ const Tensor& tensor,
167
+ int64_t dim,
168
+ int64_t dim_size,
169
+ int64_t size);
170
+
171
+ namespace detail {
172
+ TORCH_API std::vector<int64_t> defaultStrides(IntArrayRef sizes);
173
+
174
+ TORCH_API std::optional<std::vector<int64_t>> computeStride(
175
+ IntArrayRef oldshape,
176
+ IntArrayRef oldstride,
177
+ IntArrayRef newshape);
178
+
179
+ TORCH_API std::optional<SymDimVector> computeStride(
180
+ c10::SymIntArrayRef oldshape,
181
+ c10::SymIntArrayRef oldstride,
182
+ c10::SymIntArrayRef newshape);
183
+
184
+ TORCH_API std::optional<DimVector> computeStride(
185
+ IntArrayRef oldshape,
186
+ IntArrayRef oldstride,
187
+ const DimVector& newshape);
188
+
189
+ } // namespace detail
190
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ThreadLocalPythonObjects.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SafePyObject.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <unordered_map>
6
+
7
+ namespace at::impl {
8
+
9
+ struct TORCH_API ThreadLocalPythonObjects {
10
+ static void set(const std::string& key, std::shared_ptr<SafePyObject> value);
11
+ static const std::shared_ptr<SafePyObject>& get(const std::string& key);
12
+ static bool contains(const std::string& key);
13
+
14
+ static const ThreadLocalPythonObjects& get_state();
15
+ static void set_state(ThreadLocalPythonObjects state);
16
+
17
+ private:
18
+ std::unordered_map<std::string, std::shared_ptr<c10::SafePyObject>> obj_dict_;
19
+ };
20
+
21
+ } // namespace at::impl
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ThreadLocalState.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/InferenceMode.h>
4
+ #include <c10/core/impl/LocalDispatchKeySet.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/ThreadLocalDebugInfo.h>
7
+
8
+ #include <ATen/FuncTorchTLS.h>
9
+ #include <ATen/PythonTorchFunctionTLS.h>
10
+ #include <ATen/SavedTensorHooks.h>
11
+ #include <ATen/ThreadLocalPythonObjects.h>
12
+ #include <ATen/record_function.h>
13
+ #include <c10/core/impl/PythonDispatcherTLS.h>
14
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
15
+
16
+ namespace at {
17
+
18
+ // Thread local state contains values that are preserved across
19
+ // thread boundaries (e.g. at::launch/JIT fork, autograd).
20
+ // Note at::parallel_for doesn't preserve TLS across thread boundaries.
21
+ class TORCH_API ThreadLocalState {
22
+ public:
23
+ // Saves the thread local variables' values and
24
+ // returns them as a ThreadLocalState
25
+ ThreadLocalState();
26
+
27
+ // set_grad_mode - force the value of the grad mode TLS in
28
+ // the current state object. This is used for example in the
29
+ // autograd engine.
30
+ void set_grad_mode(bool enabled);
31
+
32
+ // set_multithreading_enabled - force the value of the multithreadinmaximum
33
+ // threads TLS in
34
+ // the current state object. This is used for example in the
35
+ // autograd engine.
36
+ void set_multithreading_enabled(bool enabled);
37
+
38
+ // Sets thread local variables in the current thread,
39
+ // according to the thread boundary specified
40
+ static void setThreadLocalState(const ThreadLocalState& state);
41
+
42
+ private:
43
+ c10::impl::LocalDispatchKeySet dispatch_key_;
44
+
45
+ // ThreadLocalDebugInfo does not change after being created
46
+ // with DebugInfoGuard
47
+ std::shared_ptr<c10::ThreadLocalDebugInfo> debug_info_;
48
+
49
+ // RecordFunction TLS
50
+ RecordFunctionTLS rf_tls_;
51
+
52
+ // TLS for out-of-tree functorch
53
+ // See NOTE [functorch TLS in pytorch/pytorch] for why this needs to be a
54
+ // pointer (spoiler alert: it's due to the indirection)
55
+ // This needs to be a shared_ptr instead of a unique_ptr because
56
+ // ThreadLocalState is copy-able and does indeed get copied. Maybe we can
57
+ // consider adding an explicit copy constructor for ThreadLocalState in the
58
+ // future but I didn't want to add one just for this.
59
+ std::shared_ptr<const functorch::FuncTorchTLSBase> functorch_tls_;
60
+
61
+ // TLS for AutogradModes
62
+ AutogradState autograd_tls_;
63
+
64
+ // TLS for enable_torch_dispatch_mode
65
+ c10::impl::TorchDispatchModeTLS torch_dispatch_mode_state_;
66
+
67
+ // TLS for enable_python_dispatcher
68
+ c10::impl::PyInterpreter* python_dispatcher_state_;
69
+
70
+ // TLS for __torch_function__ (mode and disable_torch_function)
71
+ at::impl::PythonTorchFunctionTLS python_torch_function_state_;
72
+
73
+ // TLS for saved tensors default hooks
74
+ at::impl::SavedTensorDefaultHooksTLS saved_tensors_default_hooks_state_;
75
+
76
+ bool functionalization_reapply_views_state_;
77
+
78
+ // TLS for arbitrary python objects that is registered via hooks
79
+ at::impl::ThreadLocalPythonObjects saved_objects_;
80
+
81
+ #if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE) && \
82
+ !defined(BUILD_LITE_INTERPRETER)
83
+ // TLS for autocast dtypes
84
+ std::array<at::ScalarType, at::COMPILE_TIME_MAX_DEVICE_TYPES>
85
+ autocast_dtypes_{};
86
+ #endif
87
+
88
+ friend class ThreadLocalStateGuard;
89
+ };
90
+
91
+ // Guard to set and reset the thread local state
92
+ class TORCH_API ThreadLocalStateGuard {
93
+ public:
94
+ explicit ThreadLocalStateGuard(const ThreadLocalState& state)
95
+ : prev_state_(ThreadLocalState()) {
96
+ // set the given state across the thread boundary
97
+ ThreadLocalState::setThreadLocalState(state);
98
+ }
99
+ ThreadLocalStateGuard(ThreadLocalStateGuard&& other) = delete;
100
+ ThreadLocalStateGuard(const ThreadLocalStateGuard&) = delete;
101
+ ThreadLocalStateGuard& operator=(const ThreadLocalStateGuard&) = delete;
102
+ ThreadLocalStateGuard& operator=(ThreadLocalStateGuard&&) = delete;
103
+
104
+ ~ThreadLocalStateGuard() {
105
+ // restore previously set variables
106
+ ThreadLocalState::setThreadLocalState(prev_state_);
107
+ }
108
+
109
+ private:
110
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
111
+ const ThreadLocalState prev_state_;
112
+ };
113
+
114
+ template <typename T>
115
+ auto wrapPropagateTLSState(T callback) {
116
+ return [tls_state = ThreadLocalState(),
117
+ callback = std::move(callback)](auto&&... args) {
118
+ ThreadLocalStateGuard g(tls_state);
119
+ // Propagate value returned by callback().
120
+ return callback(std::forward<decltype(args)>(args)...);
121
+ };
122
+ }
123
+
124
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TracerMode.h ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/impl/LocalDispatchKeySet.h>
4
+ #include <c10/macros/Export.h>
5
+ #include <c10/macros/Macros.h>
6
+
7
+ // NOTE [Tracing Mode Switches]
8
+ //
9
+ // Historically, tracing function was controlled by two switches:
10
+ //
11
+ // - `AutoDispatchBelowADInplaceOrView` guard
12
+ //
13
+ // Tracing function used to be script-generated inside `VariableType_*.cpp`
14
+ // kernels, sharing the same `Autograd` dispatch key with autograd function.
15
+ // Therefore, before tracing function was moved out of VariableType,
16
+ // `AutoDispatchBelowADInplaceOrView` guard can also disable tracing as a
17
+ // side effect of disabling `Autograd` dispatching.
18
+ //
19
+ // - `setTracingState()` API in `torch/csrc/jit/frontend/tracer.h`
20
+ //
21
+ // It stores tracing data in a `TracingState` object in TLS. If the
22
+ // `TracingState` object in TLS is `null`, then tracing is paused.
23
+ //
24
+ // The `TracingState` object is created in `tracer::trace()` - the main
25
+ // entrance of tracing function. It's temporarily set to `null` inside
26
+ // generated VariableType (now TraceType) to bypass tracing for intermediate
27
+ // ops (ops being called by other ops). After the intermediate op call
28
+ // finishes it's set back to the original `TracingState` object.
29
+ //
30
+ // The `TracingState` obect in TLS can also be read/written via its Python
31
+ // binding in `python_tracer.cpp`, and `get/setTracingState()` C++ APIs,
32
+ // which are also exposed as `TORCH_API`.
33
+ //
34
+ // Two new switches were introduced since tracing function was moved out of
35
+ // VariableType:
36
+ //
37
+ // - `tracer::impl::set_dispatch_enabled()` API
38
+ //
39
+ // Unlike the special `Autograd` dispatch key which is included in dispatch
40
+ // key set by default, `Tracer` dispatch key is off by default. The
41
+ // dispatching switch can be toggled via this new API.
42
+ //
43
+ // - `tracer::impl::NoTracerDispatchMode` guard
44
+ //
45
+ // It's used to cover the old semantics of `AutoDispatchBelowADInplaceOrView`
46
+ // after tracing was moved out of VariableType.
47
+ //
48
+ // Before tracing function was moved out of VariableType, tracing was enabled
49
+ // when the following conditions are satisfied:
50
+ //
51
+ // 1) `TracingState` object in TLS != null;
52
+ // - Either inside the execution scope of `tracer::trace()`, or
53
+ // - Eagerly called `setTracingState()` with non-null object.
54
+ // 2) Not inside `AutoDispatchBelowADInplaceOrView` scope;
55
+ //
56
+ // After:
57
+ //
58
+ // 1) `TracingState` object in TLS != null;
59
+ // 2) Has called `tracer::impl::set_dispatch_enabled(true)`;
60
+ // 3) Not inside `tracer::impl::NonDispatchGuard` scope;
61
+ //
62
+ // [TODOs]
63
+ //
64
+ // - `setTracingState()` v.s. `tracer::impl::set_dispatch_enabled()`
65
+ //
66
+ // Currently `set_dispatch_enabled()` is set/unset inside `setTracingState()`
67
+ // to keep the semantics exactly the same as before - it's confusing to keep
68
+ // both switches, though. We should consider simplifying/limiting the exposed
69
+ // `setTracingState()` Python/C++ APIs (and other APIs calling it) so that
70
+ // these two can be unified.
71
+ //
72
+ // - `AutoDispatchBelowADInplaceOrView` v.s.
73
+ // `tracer::impl::NoTracerDispatchMode`
74
+ //
75
+ // We don't need to always set both guards together to keep semantics
76
+ // unchanged. For the follow use cases of `AutoDispatchBelowADInplaceOrView`
77
+ // we don't need set the new tracer guard:
78
+ //
79
+ // * Script-generated VariableType kernels. The guard is not necessary as
80
+ // tracing is already disabled explicitly by `setTracingState(null)` in
81
+ // generated TraceType kernels - we could keep it as is or use the new guard
82
+ // instead.
83
+ //
84
+ // * Custom ops. Will be handled by fallback kernel for `Tracer`.
85
+ //
86
+ // * Functions that are not likely to be called in tracing context (no python
87
+ // binding / not an operator), e.g.: all mobile forward() wrappers, test
88
+ // binaries, and etc.
89
+ //
90
+ // * Where new threads are spawned, e.g.: ATen/native/ConvolutionMM2d.cpp.
91
+ // It's not necessary as tracing is off by default.
92
+ //
93
+ // For the rest of cases we might need have both:
94
+ //
95
+ // * Functions that might be reachable from eager mode python (especially
96
+ // factory methods), e.g.:
97
+ // `internal_new_from_data()` in `torch/csrc/utils/tensor_new.cpp`.
98
+ // Without the new guard it will add `aten::empty` to the traced graph.
99
+ //
100
+ // * Some manually maintained functions, e.g.:
101
+ // `torch/csrc/autograd/VariableTypeManual.cpp`.
102
+ // Set the new guard if it's not obvious whether `setTracingState(null)`
103
+ // has been called before it reaches the `AutoDispatchBelowADInplaceOrView`
104
+ // guard.
105
+ //
106
+ // We might need tweak the usage of the new guard to optimize/fix things.
107
+ // It should only affect the correctness of tracing function, because the
108
+ // guard is essentially no-op when the master `setTracingState()` switch is
109
+ // off.
110
+
111
+ // TODO: move this from `at::` to `jit::torch::` after
112
+ // `aten/src/ATen/cpp_custom_type_hack.h` is removed.
113
+
114
+ namespace at::tracer::impl {
115
+
116
+ inline bool is_dispatch_enabled() {
117
+ return c10::impl::tls_is_dispatch_key_included(at::DispatchKey::Tracer) &&
118
+ !c10::impl::tls_is_dispatch_key_excluded(at::DispatchKey::Tracer);
119
+ }
120
+
121
+ inline void set_dispatch_enabled(bool enabled) {
122
+ TORCH_INTERNAL_ASSERT(
123
+ !c10::impl::tls_is_dispatch_key_excluded(at::DispatchKey::Tracer),
124
+ "Cannot enable tracing within the scope of NoTracerDispatchMode!");
125
+ c10::impl::tls_set_dispatch_key_included(at::DispatchKey::Tracer, enabled);
126
+ }
127
+
128
+ struct NoTracerDispatchMode {
129
+ c10::impl::ExcludeDispatchKeyGuard guard_{at::DispatchKey::Tracer};
130
+ };
131
+
132
+ } // namespace at::tracer::impl
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/TypeDefault.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Dimname.h>
4
+ #include <c10/core/MemoryFormat.h>
5
+ #include <c10/core/QScheme.h>
6
+ #include <c10/core/Scalar.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/macros/Export.h>
9
+ #include <c10/util/ArrayRef.h>
10
+ #include <c10/util/intrusive_ptr.h>
11
+
12
+ namespace c10 {
13
+ struct Storage;
14
+ }
15
+
16
+ namespace at {
17
+
18
+ class Tensor;
19
+ using TensorList = ArrayRef<Tensor>;
20
+
21
+ class Context;
22
+ struct Generator;
23
+
24
+ struct Quantizer;
25
+
26
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Utils.h ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/EmptyTensor.h>
4
+ #include <ATen/Formatting.h>
5
+ #include <ATen/core/ATenGeneral.h>
6
+ #include <ATen/core/Generator.h>
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/core/StorageImpl.h>
9
+ #include <c10/core/UndefinedTensorImpl.h>
10
+ #include <c10/util/ArrayRef.h>
11
+ #include <c10/util/Exception.h>
12
+ #include <c10/util/accumulate.h>
13
+ #include <c10/util/irange.h>
14
+
15
+ #include <algorithm>
16
+
17
+ #define AT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
18
+ TypeName(const TypeName&) = delete; \
19
+ void operator=(const TypeName&) = delete
20
+
21
+ namespace at {
22
+
23
+ TORCH_API int _crash_if_asan(int);
24
+
25
+ // Converts a TensorList (i.e. ArrayRef<Tensor> to vector of TensorImpl*)
26
+ // NB: This is ONLY used by legacy TH bindings, and ONLY used by cat.
27
+ // Once cat is ported entirely to ATen this can be deleted!
28
+ inline std::vector<TensorImpl*> checked_dense_tensor_list_unwrap(
29
+ ArrayRef<Tensor> tensors,
30
+ const char* name,
31
+ int pos,
32
+ c10::DeviceType device_type,
33
+ ScalarType scalar_type) {
34
+ std::vector<TensorImpl*> unwrapped;
35
+ unwrapped.reserve(tensors.size());
36
+ for (const auto i : c10::irange(tensors.size())) {
37
+ const auto& expr = tensors[i];
38
+ if (expr.layout() != Layout::Strided) {
39
+ TORCH_CHECK(
40
+ false,
41
+ "Expected dense tensor but got ",
42
+ expr.layout(),
43
+ " for sequence element ",
44
+ i,
45
+ " in sequence argument at position #",
46
+ pos,
47
+ " '",
48
+ name,
49
+ "'");
50
+ }
51
+ if (expr.device().type() != device_type) {
52
+ TORCH_CHECK(
53
+ false,
54
+ "Expected object of device type ",
55
+ device_type,
56
+ " but got device type ",
57
+ expr.device().type(),
58
+ " for sequence element ",
59
+ i,
60
+ " in sequence argument at position #",
61
+ pos,
62
+ " '",
63
+ name,
64
+ "'");
65
+ }
66
+ if (expr.scalar_type() != scalar_type) {
67
+ TORCH_CHECK(
68
+ false,
69
+ "Expected object of scalar type ",
70
+ scalar_type,
71
+ " but got scalar type ",
72
+ expr.scalar_type(),
73
+ " for sequence element ",
74
+ i,
75
+ " in sequence argument at position #",
76
+ pos,
77
+ " '",
78
+ name,
79
+ "'");
80
+ }
81
+ unwrapped.emplace_back(expr.unsafeGetTensorImpl());
82
+ }
83
+ return unwrapped;
84
+ }
85
+
86
+ template <size_t N>
87
+ std::array<int64_t, N> check_intlist(
88
+ ArrayRef<int64_t> list,
89
+ const char* name,
90
+ int pos) {
91
+ if (list.empty()) {
92
+ // TODO: is this necessary? We used to treat nullptr-vs-not in IntList
93
+ // differently with strides as a way of faking optional.
94
+ list = {};
95
+ }
96
+ auto res = std::array<int64_t, N>();
97
+ if (list.size() == 1 && N > 1) {
98
+ res.fill(list[0]);
99
+ return res;
100
+ }
101
+ if (list.size() != N) {
102
+ TORCH_CHECK(
103
+ false,
104
+ "Expected a list of ",
105
+ N,
106
+ " ints but got ",
107
+ list.size(),
108
+ " for argument #",
109
+ pos,
110
+ " '",
111
+ name,
112
+ "'");
113
+ }
114
+ std::copy_n(list.begin(), N, res.begin());
115
+ return res;
116
+ }
117
+
118
+ using at::detail::check_size_nonnegative;
119
+
120
+ namespace detail {
121
+
122
+ template <typename T>
123
+ TORCH_API Tensor tensor_cpu(ArrayRef<T> values, const TensorOptions& options);
124
+
125
+ template <typename T>
126
+ TORCH_API Tensor
127
+ tensor_backend(ArrayRef<T> values, const TensorOptions& options);
128
+
129
+ template <typename T>
130
+ TORCH_API Tensor
131
+ tensor_complex_cpu(ArrayRef<T> values, const TensorOptions& options);
132
+
133
+ template <typename T>
134
+ TORCH_API Tensor
135
+ tensor_complex_backend(ArrayRef<T> values, const TensorOptions& options);
136
+ } // namespace detail
137
+
138
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/Version.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/Context.h>
2
+
3
+ namespace at {
4
+
5
+ /// Returns a detailed string describing the configuration PyTorch.
6
+ TORCH_API std::string show_config();
7
+
8
+ TORCH_API std::string get_mkl_version();
9
+
10
+ TORCH_API std::string get_mkldnn_version();
11
+
12
+ TORCH_API std::string get_openmp_version();
13
+
14
+ TORCH_API std::string get_cxx_flags();
15
+
16
+ TORCH_API std::string get_cpu_capability();
17
+
18
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/VmapGeneratedPlumbing.h ADDED
The diff for this file is too large to render. See raw diff
 
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/WrapDimUtils.h ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/IListRef.h>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <c10/core/TensorImpl.h>
6
+ #include <c10/core/WrapDimMinimal.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ namespace at {
10
+
11
+ // if dim_post_expr is 0 and wrap_scalar is true, then dim must be in the
12
+ // range [-1, 0]. This is a special case for scalar tensors and manifests in
13
+ // e.g. torch.sum(scalar_tensor, 0) Otherwise, dim should be in the range
14
+ // [-dim_post_expr, dim_post_expr-1].
15
+ using c10::maybe_wrap_dim;
16
+
17
+ inline int64_t maybe_wrap_dim(int64_t dim, TensorImpl* tensor) {
18
+ return maybe_wrap_dim(dim, tensor->dim());
19
+ }
20
+
21
+ inline int64_t maybe_wrap_dim(int64_t dim, TensorList tensors) {
22
+ if (tensors.empty()) {
23
+ // can't wrap empty TensorList; rely on underlying implementation to throw
24
+ // error if necessary.
25
+ return dim;
26
+ }
27
+ return maybe_wrap_dim(dim, tensors[0].dim());
28
+ }
29
+
30
+ inline int64_t maybe_wrap_dim(
31
+ int64_t dim,
32
+ const std::vector<std::vector<int64_t>>& tensor_sizes) {
33
+ if (tensor_sizes.empty()) {
34
+ // can't wrap empty list; rely on underlying implementation to throw error
35
+ // if necessary
36
+ return dim;
37
+ }
38
+ return maybe_wrap_dim(dim, static_cast<int64_t>(tensor_sizes[0].size()));
39
+ }
40
+
41
+ // Given an array of dimensions `dims` of length `ndims`, this function "Wraps"
42
+ // each dim in-place for a tensor of rank `dim_post_expr`, allowing dims to be
43
+ // specified using negative indices.
44
+ //
45
+ // Additionally, if `wrap_scalar` is true then scalar tensors with rank 0, will
46
+ // allow dimensions in the range [-1, 0]. Otherwise, an IndexError is raised for
47
+ // dimensions not in the range [-dim_post_expr, dim_post_expr).
48
+ inline void maybe_wrap_dims_n(
49
+ int64_t* dims,
50
+ int64_t ndims,
51
+ int64_t dim_post_expr,
52
+ bool wrap_scalars = true) {
53
+ if (dim_post_expr <= 0) {
54
+ if (wrap_scalars) {
55
+ dim_post_expr = 1; // this will make range [-1, 0]
56
+ } else {
57
+ TORCH_CHECK_INDEX(
58
+ ndims == 0,
59
+ "Dimension specified as ",
60
+ dims[0],
61
+ " but tensor has no dimensions");
62
+ return;
63
+ }
64
+ }
65
+ int64_t min = -dim_post_expr;
66
+ int64_t max = dim_post_expr - 1;
67
+ for (const auto i : c10::irange(ndims)) {
68
+ auto& dim = dims[i];
69
+ if (dim < min || dim > max) {
70
+ TORCH_CHECK_INDEX(
71
+ false,
72
+ "Dimension out of range (expected to be in range of [",
73
+ min,
74
+ ", ",
75
+ max,
76
+ "], but got ",
77
+ dim,
78
+ ")");
79
+ }
80
+ if (dim < 0)
81
+ dim += dim_post_expr;
82
+ }
83
+ }
84
+
85
+ // Given a contiguous container of dimensions `dims`, this function "Wraps"
86
+ // each dim in-place for a tensor of rank `dim_post_expr`, allowing dims to be
87
+ // specified using negative indices.
88
+ //
89
+ // Additionally, if `wrap_scalar` is true then scalar tensors with rank 0, will
90
+ // allow dimensions in the range [-1, 0]. Otherwise, an IndexError is raised for
91
+ // dimensions not in the range [-dim_post_expr, dim_post_expr).
92
+ template <typename Container>
93
+ inline void maybe_wrap_dims(
94
+ Container& dims,
95
+ int64_t dim_post_expr,
96
+ bool wrap_scalars = true) {
97
+ return maybe_wrap_dims_n(
98
+ dims.data(), dims.size(), dim_post_expr, wrap_scalars);
99
+ }
100
+
101
+ // previously, size [0] tensors were the only possible empty tensors; thus, it
102
+ // wasn't possible to cat empty tensors unless all the other tensors were
103
+ // 1-dimensional, so we allowed these tensors to be "skipped" (both for wrap
104
+ // dimension behavior and dimension size checking). We maintain this behavior
105
+ // for backwards compatibility, but only for this specific size (i.e. other
106
+ // empty sizes are not skipped).
107
+ inline int64_t legacy_cat_wrap_dim(
108
+ int64_t dim,
109
+ const std::vector<std::vector<int64_t>>& tensor_sizes) {
110
+ for (auto& sizes : tensor_sizes) {
111
+ if (sizes.size() == 1 && sizes[0] == 0) {
112
+ continue;
113
+ }
114
+ return maybe_wrap_dim(dim, static_cast<int64_t>(sizes.size()));
115
+ }
116
+ return dim;
117
+ }
118
+
119
+ inline int64_t legacy_cat_wrap_dim_symint(
120
+ int64_t dim,
121
+ const std::vector<std::vector<c10::SymInt>>& tensor_sizes) {
122
+ for (auto& sizes : tensor_sizes) {
123
+ if (sizes.size() == 1) {
124
+ if (TORCH_GUARD_SIZE_OBLIVIOUS(sizes[0].sym_eq(0))) {
125
+ continue;
126
+ }
127
+ }
128
+ return maybe_wrap_dim(dim, static_cast<int64_t>(sizes.size()));
129
+ }
130
+ return dim;
131
+ }
132
+
133
+ inline int64_t legacy_cat_wrap_dim(
134
+ int64_t dim,
135
+ const MaterializedITensorListRef& tensors) {
136
+ for (const Tensor& tensor : tensors) {
137
+ if (tensor.dim() == 1) {
138
+ if (TORCH_GUARD_SIZE_OBLIVIOUS(tensor.sym_sizes()[0].sym_eq(0))) {
139
+ continue;
140
+ }
141
+ }
142
+ return maybe_wrap_dim(dim, tensor.dim());
143
+ }
144
+ return dim;
145
+ }
146
+
147
+ // wrap negative dims in a vector
148
+ inline void wrap_all_dims(
149
+ std::vector<int64_t>& dims_to_wrap,
150
+ int64_t tensor_total_dims) {
151
+ for (const auto i : c10::irange(dims_to_wrap.size())) {
152
+ dims_to_wrap[i] = maybe_wrap_dim(dims_to_wrap[i], tensor_total_dims);
153
+ }
154
+ }
155
+
156
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/WrapDimUtilsMulti.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/WrapDimUtils.h>
4
+ #include <c10/core/TensorImpl.h>
5
+ #include <c10/util/irange.h>
6
+ #include <bitset>
7
+ #include <sstream>
8
+
9
+ namespace at {
10
+
11
+ // This is in an extra file to work around strange interaction of
12
+ // bitset on Windows with operator overloading
13
+
14
+ constexpr size_t dim_bitset_size = 64;
15
+
16
+ inline std::bitset<dim_bitset_size> dim_list_to_bitset(
17
+ OptionalIntArrayRef opt_dims,
18
+ size_t ndims) {
19
+ TORCH_CHECK(
20
+ ndims <= dim_bitset_size,
21
+ "only tensors with up to ",
22
+ dim_bitset_size,
23
+ " dims are supported");
24
+ std::bitset<dim_bitset_size> seen;
25
+ if (opt_dims.has_value()) {
26
+ auto dims = opt_dims.value();
27
+ for (const auto i : c10::irange(dims.size())) {
28
+ size_t dim = maybe_wrap_dim(dims[i], static_cast<int64_t>(ndims));
29
+ TORCH_CHECK(
30
+ !seen[dim],
31
+ "dim ",
32
+ dim,
33
+ " appears multiple times in the list of dims");
34
+ seen[dim] = true;
35
+ }
36
+ } else {
37
+ for (size_t dim = 0; dim < ndims; dim++) {
38
+ seen[dim] = true;
39
+ }
40
+ }
41
+ return seen;
42
+ }
43
+
44
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/autocast_mode.h ADDED
@@ -0,0 +1,945 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <ATen/NativeFunctions.h>
5
+ #include <ATen/Operators.h>
6
+ #include <torch/library.h>
7
+
8
+ #include <c10/core/impl/LocalDispatchKeySet.h>
9
+ #include <c10/util/intrusive_ptr.h>
10
+
11
+ namespace at::autocast {
12
+
13
+ TORCH_API bool is_autocast_enabled(at::DeviceType device_type);
14
+ TORCH_API void set_autocast_enabled(at::DeviceType device_type, bool enabled);
15
+ TORCH_API at::ScalarType get_autocast_dtype(at::DeviceType device_type);
16
+ TORCH_API void set_autocast_dtype(
17
+ at::DeviceType device_type,
18
+ at::ScalarType dtype);
19
+ TORCH_API void clear_cache();
20
+ TORCH_API int increment_nesting();
21
+ TORCH_API int decrement_nesting();
22
+ TORCH_API bool is_autocast_cache_enabled();
23
+ TORCH_API void set_autocast_cache_enabled(bool enabled);
24
+
25
+ // deprecated CUDA-specific autocast APIs
26
+ C10_DEPRECATED_MESSAGE(
27
+ "at::autocast::is_enabled() is deprecated. Please use at::autocast::is_autocast_enabled(at::kCUDA) instead.")
28
+ TORCH_API inline bool is_enabled() {
29
+ TORCH_WARN_DEPRECATION(
30
+ "at::autocast::",
31
+ __func__,
32
+ "() is deprecated. Please use at::autocast::is_autocast_enabled(at::kCUDA) instead.")
33
+ return is_autocast_enabled(at::kCUDA);
34
+ }
35
+ C10_DEPRECATED_MESSAGE(
36
+ "at::autocast::set_enabled(enabled) is deprecated. Please use at::autocast::set_autocast_enabled(at::kCUDA, enabled) instead.")
37
+ TORCH_API inline void set_enabled(bool enabled) {
38
+ TORCH_WARN_DEPRECATION(
39
+ "at::autocast::",
40
+ __func__,
41
+ "(enabled) is deprecated. Please use at::autocast::set_autocast_enabled(at::kCUDA, enabled) instead.")
42
+ set_autocast_enabled(at::kCUDA, enabled);
43
+ }
44
+ C10_DEPRECATED_MESSAGE(
45
+ "at::autocast::get_autocast_gpu_dtype() is deprecated. Please use at::autocast::get_autocast_dtype(at::kCUDA) instead.")
46
+ TORCH_API inline at::ScalarType get_autocast_gpu_dtype() {
47
+ TORCH_WARN_DEPRECATION(
48
+ "at::autocast::",
49
+ __func__,
50
+ "() is deprecated. Please use at::autocast::get_autocast_dtype(at::kCUDA) instead.")
51
+ return get_autocast_dtype(at::kCUDA);
52
+ }
53
+ C10_DEPRECATED_MESSAGE(
54
+ "at::autocast::set_autocast_gpu_dtype(dtype) is deprecated. Please use at::autocast::set_autocast_dtype(at::kCUDA, dtype) instead.")
55
+ TORCH_API inline void set_autocast_gpu_dtype(at::ScalarType dtype) {
56
+ TORCH_WARN_DEPRECATION(
57
+ "at::autocast::",
58
+ __func__,
59
+ "(dtype) is deprecated. Please use at::autocast::set_autocast_dtype(at::kCUDA, dtype) instead.")
60
+ set_autocast_dtype(at::kCUDA, dtype);
61
+ }
62
+
63
+ #define DECLARE_DEPRECATED_AUTOCAST_APIS(name, device_type) \
64
+ C10_DEPRECATED_MESSAGE( \
65
+ "at::autocast::is_" #name \
66
+ "_enabled() is deprecated. Please use at::autocast::is_autocast_enabled(" #device_type \
67
+ ") instead.") \
68
+ TORCH_API inline bool is_##name##_enabled() { \
69
+ TORCH_WARN_DEPRECATION( \
70
+ "at::autocast::", \
71
+ __func__, \
72
+ "() is deprecated. Please use at::autocast::is_autocast_enabled(" #device_type \
73
+ ") instead.") \
74
+ return is_autocast_enabled(device_type); \
75
+ } \
76
+ \
77
+ C10_DEPRECATED_MESSAGE( \
78
+ "at::autocast::set_" #name \
79
+ "_enabled(enabled) is deprecated. Please use at::autocast::set_autocast_enabled(" #device_type \
80
+ ", enabled) instead.") \
81
+ TORCH_API inline void set_##name##_enabled(bool enabled) { \
82
+ TORCH_WARN_DEPRECATION( \
83
+ "at::autocast::", \
84
+ __func__, \
85
+ "(enabled) is deprecated. Please use at::autocast::set_autocast_enabled(" #device_type \
86
+ ", enabled) instead.") \
87
+ set_autocast_enabled(device_type, enabled); \
88
+ } \
89
+ \
90
+ C10_DEPRECATED_MESSAGE( \
91
+ "at::autocast::get_autocast_" #name \
92
+ "_dtype() is deprecated. Please use at::autocast::get_autocast_dtype(" #device_type \
93
+ ") instead.") \
94
+ TORCH_API inline at::ScalarType get_autocast_##name##_dtype() { \
95
+ TORCH_WARN_DEPRECATION( \
96
+ "at::autocast::", \
97
+ __func__, \
98
+ "() is deprecated. Please at::autocast::get_autocast_dtype(" #device_type \
99
+ ") instead.") \
100
+ return get_autocast_dtype(device_type); \
101
+ } \
102
+ \
103
+ C10_DEPRECATED_MESSAGE( \
104
+ "at::autocast::set_autocast_" #name \
105
+ "_dtype(dtype) is deprecated. Please use at::autocast::set_autocast_dtype(" #device_type \
106
+ ", dtype) instead.") \
107
+ TORCH_API inline void set_autocast_##name##_dtype(at::ScalarType dtype) { \
108
+ TORCH_WARN_DEPRECATION( \
109
+ "at::autocast::", \
110
+ __func__, \
111
+ "(dtype) is deprecated. Please use at::autocast::set_autocast_dtype(" #device_type \
112
+ ", dtype) instead.") \
113
+ set_autocast_dtype(device_type, dtype); \
114
+ }
115
+
116
+ #define AT_FORALL_DEPRECATED_AUTOCAST_BACKENDS(_) \
117
+ _(cpu, at::kCPU) \
118
+ _(mtia, at::kMTIA) \
119
+ _(xpu, at::kXPU) \
120
+ _(xla, at::kXLA) \
121
+ _(hpu, at::kHPU) \
122
+ _(ipu, at::kIPU) \
123
+ _(privateuseone, at::kPrivateUse1)
124
+
125
+ // deprecated other backend specific autocast APIs
126
+ AT_FORALL_DEPRECATED_AUTOCAST_BACKENDS(DECLARE_DEPRECATED_AUTOCAST_APIS)
127
+
128
+ const std::array<at::DeviceType, 9> _AUTOCAST_SUPPORTED_DEVICES{
129
+ at::kCPU,
130
+ at::kCUDA,
131
+ at::kMTIA,
132
+ at::kXPU,
133
+ at::kIPU,
134
+ at::kHPU,
135
+ at::kXLA,
136
+ at::kPrivateUse1,
137
+ at::kMPS};
138
+
139
+ namespace {
140
+ inline bool is_autocast_eligible(
141
+ const Tensor& tensor,
142
+ c10::DeviceType device_type) {
143
+ switch (device_type) {
144
+ case c10::DeviceType::CUDA:
145
+ return (tensor.is_cuda() || tensor.is_xla()) &&
146
+ tensor.is_floating_point();
147
+ case c10::DeviceType::CPU:
148
+ return (tensor.is_cpu() || tensor.is_mkldnn()) &&
149
+ tensor.is_floating_point();
150
+ case c10::DeviceType::MTIA:
151
+ return tensor.is_mtia() && tensor.is_floating_point();
152
+ case c10::DeviceType::XPU:
153
+ return tensor.is_xpu() && tensor.is_floating_point();
154
+ case c10::DeviceType::IPU:
155
+ return tensor.is_ipu() && tensor.is_floating_point();
156
+ case c10::DeviceType::HPU:
157
+ return tensor.is_hpu() && tensor.is_floating_point();
158
+ case c10::DeviceType::XLA:
159
+ return tensor.is_xla() && tensor.is_floating_point();
160
+ case c10::DeviceType::PrivateUse1:
161
+ return tensor.is_privateuseone() && tensor.is_floating_point();
162
+ case c10::DeviceType::MPS:
163
+ return tensor.is_mps() && tensor.is_floating_point();
164
+ default:
165
+ return false;
166
+ }
167
+ }
168
+ } // namespace
169
+
170
+ inline DispatchKey get_autocast_dispatch_key_from_device_type(
171
+ c10::DeviceType device_type) {
172
+ switch (device_type) {
173
+ case c10::DeviceType::CUDA:
174
+ return DispatchKey::Autocast;
175
+ case c10::DeviceType::CPU:
176
+ return DispatchKey::AutocastCPU;
177
+ case c10::DeviceType::MTIA:
178
+ return DispatchKey::AutocastMTIA;
179
+ case c10::DeviceType::XPU:
180
+ return DispatchKey::AutocastXPU;
181
+ case c10::DeviceType::IPU:
182
+ return DispatchKey::AutocastIPU;
183
+ case c10::DeviceType::HPU:
184
+ return DispatchKey::AutocastHPU;
185
+ case c10::DeviceType::XLA:
186
+ return DispatchKey::AutocastXLA;
187
+ case c10::DeviceType::PrivateUse1:
188
+ return DispatchKey::AutocastPrivateUse1;
189
+ case c10::DeviceType::MPS:
190
+ return DispatchKey::AutocastMPS;
191
+ default:
192
+ throw std::runtime_error(
193
+ "unknown device type for autocast in get_autocast_dispatch_key_from_device_type");
194
+ }
195
+ }
196
+
197
+ inline bool is_autocast_available(c10::DeviceType device_type) {
198
+ if (std::find(
199
+ _AUTOCAST_SUPPORTED_DEVICES.begin(),
200
+ _AUTOCAST_SUPPORTED_DEVICES.end(),
201
+ device_type) != _AUTOCAST_SUPPORTED_DEVICES.end()) {
202
+ return true;
203
+ } else {
204
+ return false;
205
+ }
206
+ }
207
+
208
+ inline at::ScalarType get_lower_precision_fp_from_device_type(
209
+ c10::DeviceType device_type) {
210
+ if (is_autocast_available(device_type)) {
211
+ return get_autocast_dtype(device_type);
212
+ } else {
213
+ throw std::runtime_error(
214
+ "unknown device type for autocast in get_lower_precision_fp_from_device_type");
215
+ }
216
+ }
217
+
218
+ /********************************************************************
219
+ Logic to extract the promote type from any Tensor or TensorList args.
220
+ ********************************************************************/
221
+
222
+ // Overload to catch Tensor args.
223
+ // If nextArg is floating-point, compare its scalar_type with our
224
+ // current best guess for the promote type, and update if necessary.
225
+ inline at::ScalarType prioritize(
226
+ at::ScalarType current,
227
+ const Tensor& nextArg,
228
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
229
+ if (current == at::kDouble) {
230
+ TORCH_CHECK(false, "promote type is double in at::autocast::prioritize");
231
+ return current;
232
+ }
233
+ at::ScalarType lower_precision_fp =
234
+ get_lower_precision_fp_from_device_type(device_type);
235
+ if (is_autocast_eligible(nextArg, device_type)) {
236
+ auto next = nextArg.scalar_type();
237
+ if (next == at::kDouble) {
238
+ return current; // ignores double tensors
239
+ } else if (current == at::kFloat || next == at::kFloat) {
240
+ return at::kFloat; // prioritizes float over lower_precision_fp
241
+ } else if (current == lower_precision_fp && next == lower_precision_fp) {
242
+ return lower_precision_fp;
243
+ } else {
244
+ TORCH_CHECK(
245
+ false, "Unexpected floating ScalarType in at::autocast::prioritize");
246
+ return current;
247
+ }
248
+ } else {
249
+ return current;
250
+ }
251
+ }
252
+
253
+ // Overload to catch TensorList args (for e.g. cat, stack).
254
+ // Reuses the overload above to process each Tensor in the list.
255
+ inline at::ScalarType prioritize(
256
+ at::ScalarType current,
257
+ const TensorList& list,
258
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
259
+ for (const auto& tensor : list) {
260
+ current = prioritize(current, tensor, device_type);
261
+ }
262
+ return current;
263
+ }
264
+
265
+ inline at::ScalarType prioritize(
266
+ at::ScalarType current,
267
+ const ITensorListRef& list,
268
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
269
+ for (const auto& tensor : list) {
270
+ current = prioritize(current, tensor, device_type);
271
+ }
272
+ return current;
273
+ }
274
+
275
+ // Template to catch non-Tensor args (no-op that returns current best guess)
276
+ template <typename T>
277
+ inline at::ScalarType prioritize(
278
+ at::ScalarType current,
279
+ T nextArg,
280
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
281
+ return current;
282
+ }
283
+
284
+ // Overload for the tail case.
285
+ inline at::ScalarType promote_type(
286
+ at::ScalarType current,
287
+ c10::DeviceType device_type) {
288
+ return current;
289
+ }
290
+
291
+ // Unpack args and determine if incoming lower_precision_fp tensors need to be
292
+ // promoted to float32. Non-Tensor arguments are ignored.
293
+ template <typename Arg0, typename... Args>
294
+ inline at::ScalarType promote_type(
295
+ at::ScalarType current,
296
+ c10::DeviceType device_type,
297
+ Arg0 arg0,
298
+ Args... args) {
299
+ auto new_current = prioritize(current, arg0, device_type);
300
+ return promote_type(new_current, device_type, args...);
301
+ }
302
+
303
+ /****************************************************
304
+ Logic to apply cached casting to any Tensor argument.
305
+ ****************************************************/
306
+ inline bool is_eligible(
307
+ const Tensor& arg,
308
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
309
+ return (
310
+ arg.defined() && is_autocast_eligible(arg, device_type) &&
311
+ (arg.scalar_type() != at::kDouble));
312
+ }
313
+
314
+ // Overload to catch Tensor args
315
+ TORCH_API Tensor cached_cast(
316
+ at::ScalarType to_type,
317
+ const Tensor& arg,
318
+ c10::DeviceType device_type = c10::DeviceType::CUDA);
319
+
320
+ // Overload to process std::optional<Tensor>
321
+ inline std::optional<Tensor> cached_cast(
322
+ at::ScalarType to_type,
323
+ const std::optional<Tensor>& arg,
324
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
325
+ if (arg.has_value()) {
326
+ return cached_cast(to_type, *arg, device_type);
327
+ } else {
328
+ return std::nullopt;
329
+ }
330
+ }
331
+
332
+ // Overload to process TensorLists
333
+ inline std::vector<Tensor> cached_cast(
334
+ at::ScalarType to_type,
335
+ const TensorList& arg,
336
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
337
+ std::vector<Tensor> vec;
338
+ vec.reserve(arg.size());
339
+ for (const auto& t : arg) {
340
+ vec.emplace_back(cached_cast(to_type, t, device_type));
341
+ }
342
+ return vec;
343
+ }
344
+
345
+ inline std::vector<Tensor> cached_cast(
346
+ at::ScalarType to_type,
347
+ const ITensorListRef& arg,
348
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
349
+ std::vector<Tensor> vec;
350
+ vec.reserve(arg.size());
351
+ for (const auto& t : arg) {
352
+ vec.emplace_back(cached_cast(to_type, t, device_type));
353
+ }
354
+ return vec;
355
+ }
356
+
357
+ // Template to catch non-Tensor args.
358
+ template <typename T>
359
+ inline T cached_cast(
360
+ at::ScalarType to_type,
361
+ T arg,
362
+ c10::DeviceType device_type = c10::DeviceType::CUDA) {
363
+ return arg;
364
+ }
365
+
366
+ /*******************************************************
367
+ Logic to flip an output dtype flag.
368
+ Keep it simple for now by assuming only one such flag is
369
+ present in the argument list. If I ever need a function
370
+ with more than flag I'll figure out something else.
371
+ The policy is:
372
+ If the user has explicity specified a dtype, respect it.
373
+ Otherwise, set it to the autocast type.
374
+ ********************************************************/
375
+
376
+ // Overload to catch dtype flags
377
+ std::optional<ScalarType> inline set_opt_dtype(
378
+ at::ScalarType to_type,
379
+ const std::optional<ScalarType>& dtype) {
380
+ return dtype.has_value() ? dtype : to_type;
381
+ }
382
+
383
+ // Template to catch other args
384
+ template <typename T>
385
+ inline T set_opt_dtype(at::ScalarType to_type, T arg) {
386
+ return arg;
387
+ }
388
+
389
+ template <typename... Args>
390
+ inline bool firstarg_is_eligible(
391
+ c10::DeviceType device_type,
392
+ const Tensor& arg,
393
+ Args... args) {
394
+ return is_eligible(arg, device_type);
395
+ }
396
+
397
+ template <typename... Args>
398
+ inline at::ScalarType type_from_firstarg(
399
+ c10::DeviceType device_type,
400
+ at::ScalarType to_type,
401
+ const Tensor& arg,
402
+ Args... args) {
403
+ return (is_eligible(arg, device_type) ? to_type : arg.scalar_type());
404
+ }
405
+
406
+ // Policies correspond to op categories that need code-divergent handling.
407
+ // Wrapper templates below are specialized based on a policy template parameter.
408
+ enum class CastPolicy : uint8_t {
409
+ lower_precision_fp = 0, // Cast all inputs to lower_precision_fp before
410
+ // running the op. Currently, lower_precision_fp is
411
+ // fp16 for AutocastCUDA, and is defined by user
412
+ // (default bf16) for AutocastCPU or other device.
413
+ fp32, // Cast all inputs to at::kFloat before running the op.
414
+ fp32_set_opt_dtype, // Treats functions (like softmax) that
415
+ // 1. we'd like to run in fp32 and
416
+ // 2. have a std::optional<ScalarType> arg that controls
417
+ // the output type.
418
+ // fp32_set_opt_dtype wrappers' policy is: if the output
419
+ // type is already set, don't touch it, otherwise, set
420
+ // it to at::kFloat.
421
+ fp32_append_dtype, // Treats functions (like norm) that
422
+ // 1. we'd like to run in fp32 and
423
+ // 2. have some overloads that accept an output type and
424
+ // other overloads that don't.
425
+ // fp32_append_dtype wrappers wrap the overloads that don't
426
+ // have an output dtype.
427
+ // The wrapper policy is: append at::kFloat to the args,
428
+ // and redispatch to the type-aware overload.
429
+ promote, // Run in the widest dtype among several args.
430
+ };
431
+
432
+ /********************************************************************************************************
433
+ Templates to provide wrapper functions
434
+
435
+ I'm copying the pattern used in core/boxing/impl/WrapFunctionIntoFunctor.h to
436
+ extract args and return type. (see also
437
+ https://stackoverflow.com/questions/46533698/how-to-deduce-argument-list-from-function-pointer)
438
+
439
+ This strategy uses an exterior "WrapFunction" that extracts arguments on behalf
440
+ of (in my case several specializations of) an interior "WrapFunction_".
441
+ Interior WrapFunction_ specializations are defined for each CastPolicy.
442
+ ********************************************************************************************************/
443
+
444
+ // Base template for WrapFunction_, which is specialized to contain a "call"
445
+ // method each CastPolicy
446
+ template <
447
+ CastPolicy policy,
448
+ c10::DeviceType device_type,
449
+ class Redispatch,
450
+ Redispatch* F,
451
+ class Ret,
452
+ class ArgList>
453
+ struct WrapFunction_ {};
454
+
455
+ // CastPolicy::lower_precision_fp General_DeviceType
456
+ template <
457
+ c10::DeviceType device_type,
458
+ class Redispatch,
459
+ Redispatch* F,
460
+ class Ret,
461
+ class... Args>
462
+ struct WrapFunction_<
463
+ CastPolicy::lower_precision_fp,
464
+ device_type,
465
+ Redispatch,
466
+ F,
467
+ Ret,
468
+ guts::typelist::typelist<Args...>> {
469
+ static Ret call(Args... args) {
470
+ c10::impl::ExcludeDispatchKeyGuard no_autocast(
471
+ get_autocast_dispatch_key_from_device_type(device_type));
472
+ return (*F)(cached_cast(
473
+ get_lower_precision_fp_from_device_type(device_type),
474
+ args,
475
+ device_type)...);
476
+ }
477
+ };
478
+
479
+ // CastPolicy::fp32 General_DeviceType
480
+ template <
481
+ c10::DeviceType device_type,
482
+ class Redispatch,
483
+ Redispatch* F,
484
+ class Ret,
485
+ class... Args>
486
+ struct WrapFunction_<
487
+ CastPolicy::fp32,
488
+ device_type,
489
+ Redispatch,
490
+ F,
491
+ Ret,
492
+ guts::typelist::typelist<Args...>> {
493
+ static Ret call(Args... args) {
494
+ c10::impl::ExcludeDispatchKeyGuard no_autocast(
495
+ get_autocast_dispatch_key_from_device_type(device_type));
496
+ return (*F)(cached_cast(at::kFloat, args, device_type)...);
497
+ }
498
+ };
499
+
500
+ // CastPolicy::fp32_set_opt_dtype General_DeviceType
501
+ template <
502
+ c10::DeviceType device_type,
503
+ class Redispatch,
504
+ Redispatch* F,
505
+ class Ret,
506
+ class... Args>
507
+ struct WrapFunction_<
508
+ CastPolicy::fp32_set_opt_dtype,
509
+ device_type,
510
+ Redispatch,
511
+ F,
512
+ Ret,
513
+ guts::typelist::typelist<Args...>> {
514
+ static Ret call(Args... args) {
515
+ c10::impl::ExcludeDispatchKeyGuard no_autocast(
516
+ get_autocast_dispatch_key_from_device_type(device_type));
517
+ if (firstarg_is_eligible(device_type, args...)) {
518
+ return (*F)(set_opt_dtype(at::kFloat, args)...);
519
+ } else {
520
+ // If ineligible, calls F with unaltered args. Does not set opt dtype,
521
+ // because setting opt dtype explicitly may interfere with internal
522
+ // implicit promotion decisions.
523
+ return (*F)(args...);
524
+ }
525
+ }
526
+ };
527
+
528
+ // CastPolicy::fp32_append_dtype General_DeviceType
529
+ template <
530
+ c10::DeviceType device_type,
531
+ class Redispatch,
532
+ Redispatch* F,
533
+ class Ret,
534
+ class... Args>
535
+ struct WrapFunction_<
536
+ CastPolicy::fp32_append_dtype,
537
+ device_type,
538
+ Redispatch,
539
+ F,
540
+ Ret,
541
+ guts::typelist::typelist<Args...>> {
542
+ static Ret call(Args... args) {
543
+ c10::impl::ExcludeDispatchKeyGuard no_autocast(
544
+ get_autocast_dispatch_key_from_device_type(device_type));
545
+ at::ScalarType out_type =
546
+ type_from_firstarg(device_type, at::kFloat, args...);
547
+ return (*F)(args..., out_type);
548
+ }
549
+ };
550
+
551
+ // CastPolicy::promote General_DeviceType
552
+ template <
553
+ c10::DeviceType device_type,
554
+ class Redispatch,
555
+ Redispatch* F,
556
+ class Ret,
557
+ class... Args>
558
+ struct WrapFunction_<
559
+ CastPolicy::promote,
560
+ device_type,
561
+ Redispatch,
562
+ F,
563
+ Ret,
564
+ guts::typelist::typelist<Args...>> {
565
+ static Ret call(Args... args) {
566
+ c10::impl::ExcludeDispatchKeyGuard no_autocast(
567
+ get_autocast_dispatch_key_from_device_type(device_type));
568
+ auto to_type = promote_type(
569
+ get_lower_precision_fp_from_device_type(device_type),
570
+ device_type,
571
+ args...);
572
+ return (*F)(cached_cast(to_type, args, device_type)...);
573
+ }
574
+ };
575
+
576
+ // Wrapper to infer return_type and parameter_types for WrapFunction_ (imitating
577
+ // core/boxing/impl/WrapFunctionIntoFunctor.h)
578
+ template <
579
+ CastPolicy policy,
580
+ c10::DeviceType device_type,
581
+ class Registered, // The signature for which we're registering. The
582
+ // dispatcher's calling code invokes our registered
583
+ // functions with arguments matching Registered, so we
584
+ // register WrapFunction_::call methods with a matching
585
+ // signature to properly field those arguments.
586
+ // guts::function_traits below extracts return_type and
587
+ // parameter_types from Registered, which WrapFunction_
588
+ // templates above use to declare their call methods.
589
+ class Redispatch, // The signature for the function we're redispatching to.
590
+ // In most cases this is the same as Registered, but for
591
+ // some ops (for example, ops where we append a dtype)
592
+ // it's useful to redispatch to a function with a
593
+ // different signature.
594
+ Redispatch* F> // The actual function we're redispatching to.
595
+ struct WrapFunction final {
596
+ using type = WrapFunction_<
597
+ policy,
598
+ device_type,
599
+ Redispatch,
600
+ F,
601
+ typename guts::function_traits<Registered>::return_type,
602
+ typename guts::function_traits<Registered>::parameter_types>;
603
+ };
604
+
605
+ /*****************************************************************************************************************
606
+ This section performs load-time registration for autocast wrappers.
607
+
608
+ It's debatable at what level operations should be patched. We'd like casts to
609
+ be autograd-exposed and precede autograd history recording, so that for
610
+ lower_precision_fp ops, input tensors are saved for backward in
611
+ lower_precision_fp rather than fp32. Saving inputs in lower_precision_fp
612
+ can significantly reduce a model's memory footprint.
613
+
614
+ Option 1 (strawman): Patch only at the level of explicit calls into
615
+ cudnn/cublas (cudnn_convolution, etc), because those are the code paths that are
616
+ guaranteed to use Tensor Cores, therefore they're the ones that will benefit
617
+ most from lower_precision_fp. Potential pitfall: convolutions (and other ops)
618
+ are wrapped in several layers of at::* calls. If one of those happens to record
619
+ autograd history, then we've lost the opportunity to save inputs in
620
+ lower_precision_fp.
621
+
622
+ Option 2: Patch the Python-exposed surface of calls, to make 100% sure autograd
623
+ history recording can't sneak in ahead of autocast. This mirrors Apex most
624
+ closely.
625
+
626
+ I think Option 2 is the right answer for all ops, not just convolutions. Option
627
+ 2 is what I implement here.
628
+ *****************************************************************************************************************/
629
+
630
+ /********************************************************************************************************************
631
+ Explicit registration for out-of-place ops
632
+
633
+ The stuff below could be codegenned. Ed said
634
+ > you are going to have to write the function definition at some point, I
635
+ wouldn't try to get clever about it Therefore, for the moment, this is all
636
+ copy pasted in from VariableTypeEverything.cpp with appropriate substitutions.
637
+ ********************************************************************************************************************/
638
+
639
+ } // namespace at::autocast
640
+
641
+ #define ADD_NS(RAW_OP) at::RAW_OP
642
+
643
+ #define _KERNEL_OVERLOAD_NARG_IMPL(_0, _1, _2, N, ...) N
644
+ #define _KERNEL_OVERLOAD_NARG(...) \
645
+ C10_EXPAND_MSVC_WORKAROUND(_KERNEL_OVERLOAD_NARG_IMPL(__VA_ARGS__, 2, 1))
646
+
647
+ // Common cases where registration signature matches redispatch signature
648
+ // (that's why SIGNATURE is repeated in the WrapFunction instantiation)
649
+ #define KERNEL1(DISPATCHKEY, OP, POLICY) \
650
+ m.impl( \
651
+ TORCH_SELECTIVE_NAME("aten::" #OP), \
652
+ &::at::autocast::WrapFunction< \
653
+ ::at::autocast::CastPolicy::POLICY, \
654
+ DISPATCHKEY, \
655
+ decltype(ATEN_FN(OP)), \
656
+ decltype(ATEN_FN(OP)), \
657
+ &ATEN_FN(OP)>::type::call);
658
+
659
+ #define KERNEL2(DISPATCHKEY, OP, OVERLOAD, POLICY) \
660
+ m.impl( \
661
+ TORCH_SELECTIVE_NAME("aten::" #OP "." #OVERLOAD), \
662
+ &::at::autocast::WrapFunction< \
663
+ ::at::autocast::CastPolicy::POLICY, \
664
+ DISPATCHKEY, \
665
+ decltype(ATEN_FN2(OP, OVERLOAD)), \
666
+ decltype(ATEN_FN2(OP, OVERLOAD)), \
667
+ &ATEN_FN2(OP, OVERLOAD)>::type::call);
668
+
669
+ #define _KERNEL_DISPATCH(DISPATCHKEY, NARG, ...) \
670
+ C10_CONCATENATE(KERNEL, NARG)(DISPATCHKEY, __VA_ARGS__)
671
+
672
+ #define _KERNEL_IMPL(DISPATCHKEY, ...) \
673
+ _KERNEL_DISPATCH(DISPATCHKEY, _KERNEL_OVERLOAD_NARG(__VA_ARGS__), __VA_ARGS__)
674
+
675
+ // It will dispatch to KERNEL1 or KERNEL2 based on its inputs.
676
+ #define KERNEL(DISPATCHKEY, ...) _KERNEL_IMPL(DISPATCHKEY, __VA_ARGS__)
677
+
678
+ // Less-common but still useful case: redispatching to a function
679
+ // with a new signature (e.g. appending a dtype)
680
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
681
+ DISPATCHKEY, \
682
+ REDISPATCH_FUNC, \
683
+ REGISTER_NAME, \
684
+ REGISTER_SIGNATURE, \
685
+ REDISPATCH_SIGNATURE, \
686
+ POLICY) \
687
+ m.impl( \
688
+ TORCH_SELECTIVE_NAME("aten::" REGISTER_NAME), \
689
+ &::at::autocast::WrapFunction< \
690
+ ::at::autocast::CastPolicy::POLICY, \
691
+ DISPATCHKEY, \
692
+ REGISTER_SIGNATURE, \
693
+ REDISPATCH_SIGNATURE, \
694
+ &REDISPATCH_FUNC>::type::call);
695
+
696
+ // KERNEL_CPU/KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_CPU
697
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastCPU
698
+ #define KERNEL_CPU(...) KERNEL(c10::DeviceType::CPU, __VA_ARGS__)
699
+
700
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_CPU( \
701
+ REDISPATCH_FUNC, \
702
+ REGISTER_NAME, \
703
+ REGISTER_SIGNATURE, \
704
+ REDISPATCH_SIGNATURE, \
705
+ POLICY) \
706
+ KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
707
+ c10::DeviceType::CPU, \
708
+ REDISPATCH_FUNC, \
709
+ REGISTER_NAME, \
710
+ REGISTER_SIGNATURE, \
711
+ REDISPATCH_SIGNATURE, \
712
+ POLICY)
713
+
714
+ // KERNEL_CUDA/KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_CUDA
715
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastCUDA
716
+ #define KERNEL_CUDA(...) KERNEL(c10::DeviceType::CUDA, __VA_ARGS__)
717
+
718
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_CUDA( \
719
+ REDISPATCH_FUNC, \
720
+ REGISTER_NAME, \
721
+ REGISTER_SIGNATURE, \
722
+ REDISPATCH_SIGNATURE, \
723
+ POLICY) \
724
+ KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
725
+ c10::DeviceType::CUDA, \
726
+ REDISPATCH_FUNC, \
727
+ REGISTER_NAME, \
728
+ REGISTER_SIGNATURE, \
729
+ REDISPATCH_SIGNATURE, \
730
+ POLICY)
731
+
732
+ // KERNEL_MTIA/KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_MTIA
733
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastMTIA
734
+ #define KERNEL_MTIA(...) KERNEL(c10::DeviceType::MTIA, __VA_ARGS__)
735
+
736
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_MTIA( \
737
+ REDISPATCH_FUNC, \
738
+ REGISTER_NAME, \
739
+ REGISTER_SIGNATURE, \
740
+ REDISPATCH_SIGNATURE, \
741
+ POLICY) \
742
+ KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
743
+ c10::DeviceType::MTIA, \
744
+ REDISPATCH_FUNC, \
745
+ REGISTER_NAME, \
746
+ REGISTER_SIGNATURE, \
747
+ REDISPATCH_SIGNATURE, \
748
+ POLICY)
749
+
750
+ // KERNEL_XPU/KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_XPU
751
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastXPU
752
+ #define KERNEL_XPU(...) KERNEL(c10::DeviceType::XPU, __VA_ARGS__)
753
+
754
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_XPU( \
755
+ REDISPATCH_FUNC, \
756
+ REGISTER_NAME, \
757
+ REGISTER_SIGNATURE, \
758
+ REDISPATCH_SIGNATURE, \
759
+ POLICY) \
760
+ KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
761
+ c10::DeviceType::XPU, \
762
+ REDISPATCH_FUNC, \
763
+ REGISTER_NAME, \
764
+ REGISTER_SIGNATURE, \
765
+ REDISPATCH_SIGNATURE, \
766
+ POLICY)
767
+
768
+ // KERNEL_PRIVATEUSEONE/KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_PRIVATEUSEONE
769
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastPrivateUse1
770
+ #define KERNEL_PRIVATEUSEONE(...) \
771
+ KERNEL(c10::DeviceType::PrivateUse1, __VA_ARGS__)
772
+
773
+ #define KERNEL_DIFFERENT_REDISPATCH_SIGNATURE_PRIVATEUSEONE( \
774
+ REDISPATCH_FUNC, \
775
+ REGISTER_NAME, \
776
+ REGISTER_SIGNATURE, \
777
+ REDISPATCH_SIGNATURE, \
778
+ POLICY) \
779
+ KERNEL_DIFFERENT_REDISPATCH_SIGNATURE( \
780
+ c10::DeviceType::PrivateUse1, \
781
+ REDISPATCH_FUNC, \
782
+ REGISTER_NAME, \
783
+ REGISTER_SIGNATURE, \
784
+ REDISPATCH_SIGNATURE, \
785
+ POLICY)
786
+
787
+ // KERNEL_MPS
788
+ // registration (OP, POLICY) or (OP, OVERLOAD, POLICY) for AutocastMPS
789
+ #define KERNEL_MPS(...) KERNEL(c10::DeviceType::MPS, __VA_ARGS__)
790
+
791
+ // Op lists for different policies.
792
+ // To make sure other backends can reuse the policy op list.
793
+ #define AT_FORALL_LOWER_PRECISION_FP(_) \
794
+ _(_convolution, deprecated) \
795
+ _(_convolution) \
796
+ _(conv1d) \
797
+ _(conv2d) \
798
+ _(conv3d) \
799
+ _(conv_tbc) \
800
+ _(conv_transpose1d) \
801
+ _(conv_transpose2d, input) \
802
+ _(conv_transpose3d, input) \
803
+ _(convolution) \
804
+ _(prelu) \
805
+ _(addmm) \
806
+ _(addmv) \
807
+ _(addr) \
808
+ _(matmul) \
809
+ _(einsum) \
810
+ _(mm) \
811
+ _(mv) \
812
+ _(linalg_vecdot) \
813
+ _(linear) \
814
+ _(addbmm) \
815
+ _(baddbmm) \
816
+ _(bmm) \
817
+ _(chain_matmul) \
818
+ _(linalg_multi_dot) \
819
+ _(_thnn_fused_lstm_cell) \
820
+ _(_thnn_fused_gru_cell) \
821
+ _(lstm_cell) \
822
+ _(gru_cell) \
823
+ _(rnn_tanh_cell) \
824
+ _(rnn_relu_cell) \
825
+ _(_scaled_dot_product_flash_attention) \
826
+ _(scaled_dot_product_attention)
827
+
828
+ #define AT_FORALL_FP32(_) \
829
+ _(acos) \
830
+ _(asin) \
831
+ _(cosh) \
832
+ _(erfinv) \
833
+ _(exp) \
834
+ _(expm1) \
835
+ _(log) \
836
+ _(log10) \
837
+ _(log2) \
838
+ _(log1p) \
839
+ _(reciprocal) \
840
+ _(rsqrt) \
841
+ _(sinh) \
842
+ _(tan) \
843
+ _(pow, Tensor_Scalar) \
844
+ _(pow, Tensor_Tensor) \
845
+ _(pow, Scalar) \
846
+ _(softplus) \
847
+ _(layer_norm) \
848
+ _(native_layer_norm) \
849
+ _(group_norm) \
850
+ _(frobenius_norm, dim) \
851
+ _(nuclear_norm) \
852
+ _(nuclear_norm, dim) \
853
+ _(cosine_similarity) \
854
+ _(poisson_nll_loss) \
855
+ _(cosine_embedding_loss) \
856
+ _(nll_loss) \
857
+ _(nll_loss2d) \
858
+ _(hinge_embedding_loss) \
859
+ _(kl_div) \
860
+ _(l1_loss) \
861
+ _(smooth_l1_loss) \
862
+ _(huber_loss) \
863
+ _(mse_loss) \
864
+ _(margin_ranking_loss) \
865
+ _(multilabel_margin_loss) \
866
+ _(soft_margin_loss) \
867
+ _(triplet_margin_loss) \
868
+ _(multi_margin_loss) \
869
+ _(binary_cross_entropy_with_logits) \
870
+ _(dist) \
871
+ _(pdist) \
872
+ _(cdist) \
873
+ _(renorm) \
874
+ _(logsumexp) \
875
+ _(upsample_nearest1d) \
876
+ _(_upsample_nearest_exact1d) \
877
+ _(upsample_nearest2d) \
878
+ _(_upsample_nearest_exact2d) \
879
+ _(upsample_nearest3d) \
880
+ _(_upsample_nearest_exact3d) \
881
+ _(upsample_linear1d) \
882
+ _(upsample_bilinear2d) \
883
+ _(_upsample_bilinear2d_aa) \
884
+ _(upsample_trilinear3d) \
885
+ _(upsample_bicubic2d) \
886
+ _(_upsample_bicubic2d_aa)
887
+
888
+ #define AT_FORALL_FP32_SET_OPT_DTYPE(_) \
889
+ _(prod) \
890
+ _(prod, dim_int) \
891
+ _(prod, dim_Dimname) \
892
+ _(softmax, int) \
893
+ _(softmax, Dimname) \
894
+ _(log_softmax, int) \
895
+ _(log_softmax, Dimname) \
896
+ _(cumprod) \
897
+ _(cumprod, dimname) \
898
+ _(cumsum) \
899
+ _(cumsum, dimname) \
900
+ _(linalg_vector_norm) \
901
+ _(linalg_matrix_norm) \
902
+ _(linalg_matrix_norm, str_ord) \
903
+ _(sum) \
904
+ _(sum, dim_IntList) \
905
+ _(sum, dim_DimnameList)
906
+
907
+ #define AT_FORALL_DIFFERENT_REDISPATCH_SIGNATURE(_) \
908
+ _(ADD_NS(norm), \
909
+ "norm.Scalar", \
910
+ Tensor(const Tensor&, const Scalar&), \
911
+ Tensor(const Tensor&, const std::optional<Scalar>&, ScalarType), \
912
+ fp32_append_dtype) \
913
+ _(ADD_NS(norm), \
914
+ "norm.ScalarOpt_dim", \
915
+ Tensor(const Tensor&, const std::optional<Scalar>&, IntArrayRef, bool), \
916
+ Tensor( \
917
+ const Tensor&, \
918
+ const std::optional<Scalar>&, \
919
+ IntArrayRef, \
920
+ bool, \
921
+ ScalarType), \
922
+ fp32_append_dtype) \
923
+ _(ADD_NS(norm), \
924
+ "norm.names_ScalarOpt_dim", \
925
+ Tensor(const Tensor&, const std::optional<Scalar>&, DimnameList, bool), \
926
+ Tensor( \
927
+ const Tensor&, \
928
+ const std::optional<Scalar>&, \
929
+ DimnameList, \
930
+ bool, \
931
+ ScalarType), \
932
+ fp32_append_dtype)
933
+
934
+ #define AT_FORALL_PROMOTE(_) \
935
+ _(addcdiv) \
936
+ _(addcmul) \
937
+ _(atan2) \
938
+ _(bilinear) \
939
+ _(cross) \
940
+ _(dot) \
941
+ _(vdot) \
942
+ _(grid_sampler) \
943
+ _(index_put) \
944
+ _(tensordot) \
945
+ _(scatter_add)
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/ceil_div.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Macros.h>
3
+ #include <type_traits>
4
+
5
+ namespace at {
6
+
7
+ /**
8
+ Computes ceil(a / b)
9
+ */
10
+ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
11
+ C10_ALWAYS_INLINE C10_HOST_DEVICE T ceil_div(T a, T b) {
12
+ return (a + b - 1) / b;
13
+ }
14
+
15
+ /**
16
+ Computes ceil(a / b) * b; i.e., rounds up `a` to the next highest
17
+ multiple of b
18
+ */
19
+ template <typename T>
20
+ C10_ALWAYS_INLINE C10_HOST_DEVICE T round_up(T a, T b) {
21
+ return ceil_div(a, b) * b;
22
+ }
23
+
24
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/code_template.h ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/irange.h>
4
+
5
+ #include <sstream>
6
+ #include <string>
7
+ #include <unordered_map>
8
+ #include <vector>
9
+
10
+ namespace at::jit {
11
+
12
+ // A template environment is a mapping from template variable names, e.g.,
13
+ // identifier (corresponding to $identifier) to their expansions.
14
+ //
15
+ // This template environment supports storing strings, numbers and lists
16
+ // of strings, and can be chained together (so that lookup proceeds in
17
+ // in the top level environment, and then recurses into a parent
18
+ // environment if the key is not found.)
19
+ struct TemplateEnv {
20
+ TemplateEnv() = default;
21
+ TemplateEnv(TemplateEnv& parent) : parent(&parent) {}
22
+ TemplateEnv(TemplateEnv&&) = delete;
23
+ TemplateEnv& operator=(const TemplateEnv& parent) = delete;
24
+ TemplateEnv& operator=(TemplateEnv&& parent) = delete;
25
+ ~TemplateEnv() = default;
26
+
27
+ using string_list = std::vector<std::string>;
28
+
29
+ // Add a string 'v' to the map at key 'k'.
30
+ void s(const std::string& k, const std::string& v) {
31
+ strings_[k] = v;
32
+ lists_.erase(k);
33
+ }
34
+
35
+ // Add a number 'v' to the map at key 'k'
36
+ template <typename T>
37
+ void d(const std::string& k, const T& v) {
38
+ strings_[k] = std::to_string(v);
39
+ lists_.erase(k);
40
+ }
41
+
42
+ // Retrieve the string representation of the value stored at 'k' from the map.
43
+ // Raises an exception if the key is not found.
44
+ const std::string& s(const std::string& k) const {
45
+ if (strings_.count(k) == 0) {
46
+ if (parent) {
47
+ return parent->s(k);
48
+ }
49
+ notFound(k);
50
+ }
51
+ return strings_.at(k);
52
+ }
53
+
54
+ // Store a list of strings 'v' in the map at 'k'.
55
+ void v(const std::string& k, const string_list& v) {
56
+ lists_[k] = v;
57
+ strings_.erase(k);
58
+ }
59
+
60
+ // Retrieve a list of strings stored at 'k' from the map.
61
+ // Raises an exception if the key is not found.
62
+ const string_list& v(const std::string& k) const {
63
+ if (lists_.count(k) == 0) {
64
+ if (parent) {
65
+ return parent->v(k);
66
+ }
67
+ notFound(k);
68
+ }
69
+ return lists_.at(k);
70
+ }
71
+
72
+ // Test if a string 'k' is a string (as opposed to a list.)
73
+ bool keyIsString(const std::string& k) const {
74
+ if (strings_.count(k) > 0)
75
+ return true;
76
+ if (lists_.count(k) > 0)
77
+ return false;
78
+ if (parent)
79
+ return parent->keyIsString(k);
80
+ notFound(k);
81
+ }
82
+
83
+ private:
84
+ [[noreturn]] void notFound(const std::string& k) const {
85
+ std::stringstream ss;
86
+ ss << "key not found: " << k;
87
+ throw std::logic_error(ss.str());
88
+ }
89
+
90
+ std::unordered_map<std::string, std::string> strings_;
91
+ std::unordered_map<std::string, string_list> lists_;
92
+ TemplateEnv* parent{nullptr};
93
+ };
94
+
95
+ /*
96
+ # Match $identifier or ${identifier} and replace with the value in env.
97
+ # If this identifier is at the beginning of whitespace on a line
98
+ # and its value is a list then it is treated as
99
+ # block substitution by indenting all lines of all elements.
100
+ # If the identifier is on a line starting with non-whitespace and a list
101
+ # then it is comma separated. ${,foo} will insert a comma before the list
102
+ # if this list is not empty and ${foo,} will insert one after.
103
+ */
104
+ struct CodeTemplate {
105
+ /* implicit */ CodeTemplate(std::string t) : template_text(std::move(t)) {}
106
+
107
+ std::string format(const TemplateEnv& env) const {
108
+ std::stringstream out;
109
+ size_t pos = 0;
110
+ size_t indent = 0;
111
+ bool all_whitespace = true;
112
+ while (pos < template_text.size()) {
113
+ char c = template_text[pos];
114
+ if (c == '$') {
115
+ std::stringstream kss;
116
+ bool comma_before = false;
117
+ bool comma_after = false;
118
+ size_t new_pos = parseKey(pos, kss, comma_before, comma_after);
119
+ std::string k = kss.str();
120
+ bool is_string = env.keyIsString(k);
121
+ if (all_whitespace) {
122
+ if (is_string)
123
+ emitStringWithIndents(out, indent, env.s(k));
124
+ else
125
+ emitLinesIndented(out, indent, env.v(k));
126
+ } else {
127
+ if (is_string)
128
+ out << env.s(k);
129
+ else
130
+ emitCommaSeparatedList(out, env.v(k), comma_before, comma_after);
131
+ }
132
+ all_whitespace = false;
133
+ pos = new_pos;
134
+ } else {
135
+ out << c;
136
+ if (!isspace(c))
137
+ all_whitespace = false;
138
+ indent++;
139
+ if (c == '\n') {
140
+ indent = 0;
141
+ all_whitespace = true;
142
+ }
143
+ pos++;
144
+ }
145
+ }
146
+ return out.str();
147
+ }
148
+
149
+ private:
150
+ using string_list = std::vector<std::string>;
151
+ char charAt(size_t p) const {
152
+ if (p >= template_text.size())
153
+ throw std::logic_error("EOS found in key");
154
+ return template_text[p];
155
+ }
156
+ size_t parseKey(
157
+ size_t pos,
158
+ std::ostream& k,
159
+ bool& comma_before,
160
+ bool& comma_after) const {
161
+ comma_before = false;
162
+ comma_after = false;
163
+ pos++;
164
+ if (charAt(pos) == '{') {
165
+ pos++;
166
+ if (charAt(pos) == ',') {
167
+ comma_before = true;
168
+ pos++;
169
+ }
170
+ pos = parseIdent(pos, k);
171
+ if (charAt(pos) == ',') {
172
+ comma_after = true;
173
+ pos++;
174
+ }
175
+ if (charAt(pos) != '}')
176
+ throw std::logic_error("missing terminating '}'");
177
+ pos++;
178
+ return pos;
179
+ } else {
180
+ return parseIdent(pos, k);
181
+ }
182
+ }
183
+ size_t parseIdent(size_t pos, std::ostream& k) const {
184
+ while (pos < template_text.size() &&
185
+ (isalnum(template_text[pos]) || template_text[pos] == '_')) {
186
+ k << template_text[pos];
187
+ pos++;
188
+ }
189
+ return pos;
190
+ }
191
+ void emitCommaSeparatedList(
192
+ std::ostream& out,
193
+ const string_list& strings,
194
+ bool comma_before,
195
+ bool comma_after) const {
196
+ if (comma_before && !strings.empty())
197
+ out << ", ";
198
+ for (const auto i : c10::irange(strings.size())) {
199
+ if (i > 0)
200
+ out << ", ";
201
+ out << strings[i];
202
+ }
203
+ if (comma_after && !strings.empty())
204
+ out << ", ";
205
+ }
206
+ // These indentation functions follow the convention that they never emit
207
+ // leading or trailing newlines when the input string does not have leading
208
+ // or trailing newlines. It's the responsibility of the calling function
209
+ // to indent correctly in the context.
210
+ void emitIndent(std::ostream& out, size_t indent) const {
211
+ for ([[maybe_unused]] const auto i : c10::irange(indent)) {
212
+ out << " ";
213
+ }
214
+ }
215
+ void emitStringWithIndents(
216
+ std::ostream& out,
217
+ size_t indent,
218
+ const std::string& str) const {
219
+ for (auto c : str) {
220
+ out << c;
221
+ if (c == '\n') {
222
+ emitIndent(out, indent);
223
+ }
224
+ }
225
+ }
226
+ void emitLinesIndented(
227
+ std::stringstream& out,
228
+ size_t indent,
229
+ const string_list& strings) const {
230
+ for (const auto i : c10::irange(strings.size())) {
231
+ if (i > 0)
232
+ emitIndent(out, indent);
233
+ emitStringWithIndents(out, indent, strings[i]);
234
+ if (i + 1 != strings.size())
235
+ out << "\n";
236
+ }
237
+ }
238
+ std::string template_text;
239
+ };
240
+
241
+ static inline std::string format(const std::string& fmt, TemplateEnv& env) {
242
+ return CodeTemplate(fmt).format(env);
243
+ }
244
+
245
+ } // namespace at::jit
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpp_custom_type_hack.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
2
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
3
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
4
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
5
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
6
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
7
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
8
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
9
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
10
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
11
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
12
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
13
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
14
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
15
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
16
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
17
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
18
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
19
+
20
+ // YOU ARE IN THE WRONG PLACE! TURN BACK NOW!
21
+
22
+ // This code was a temporary hack to enable embedding arbitrary C++ structures
23
+ // into Tensors. THIS IS UNSAFE AND IS NOT SUPPORTED. IF YOU USE THIS CODE,
24
+ // IT __WILL__ BREAK.
25
+
26
+ // This code has been superseded by custom classes:
27
+ // https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html
28
+
29
+ // Please use custom classes and **DO NOT ADD MORE CALLSITES TO THINGS DEFINED
30
+ // IN THIS FILE**.
31
+
32
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
33
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
34
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
35
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
36
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
37
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
38
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
39
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
40
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
41
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
42
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
43
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
44
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
45
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
46
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
47
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
48
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
49
+ // STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP STOP
50
+
51
+ #include <ATen/TracerMode.h>
52
+ #include <ATen/core/Tensor.h>
53
+
54
+ #ifndef AT_PER_OPERATOR_HEADERS
55
+ #include <ATen/Functions.h>
56
+ #else
57
+ #include <ATen/ops/empty.h>
58
+ #endif
59
+
60
+ namespace at::cpp_custom_type_hack {
61
+
62
+ template <typename T>
63
+ [[deprecated(
64
+ "Use custom classes instead: "
65
+ "https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html")]] bool
66
+ isa(const Tensor& packed) {
67
+ return (packed.scalar_type() == kByte) &&
68
+ (packed.storage().data_ptr().get_deleter() ==
69
+ caffe2::TypeMeta::Make<T>().deleteFn());
70
+ }
71
+
72
+ template <typename T>
73
+ [[deprecated(
74
+ "Use custom classes instead: "
75
+ "https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html")]] T&
76
+ cast(const Tensor& packed) {
77
+ TORCH_CHECK(
78
+ packed.scalar_type() == kByte, "Expected temporary cpp type wrapper");
79
+ TORCH_CHECK(
80
+ packed.storage().data_ptr().get_deleter() ==
81
+ caffe2::TypeMeta::Make<T>().deleteFn(),
82
+ "Expected temporary cpp type wrapper of type ",
83
+ caffe2::TypeMeta::TypeName<T>());
84
+ return *reinterpret_cast<T*>(packed.storage().data_ptr().get());
85
+ }
86
+
87
+ template <typename T>
88
+ [[deprecated(
89
+ "Use custom classes instead: "
90
+ "https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html")]] Tensor
91
+ create(std::unique_ptr<T> ptr, TensorOptions options) {
92
+ // None of this should trace, so turn off Tracer dispatching
93
+ at::AutoDispatchBelowADInplaceOrView guard; // TODO: remove
94
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
95
+
96
+ // We store this instance away in a Tensor and register a deleter function
97
+ // so that we do not leak memory. On the other side, we pull out the storage's
98
+ // data_ptr and get the right typed pointer.
99
+ void* raw_ptr = ptr.release();
100
+ at::DataPtr at_ptr(
101
+ raw_ptr, raw_ptr, caffe2::TypeMeta::Make<T>().deleteFn(), at::kCPU);
102
+
103
+ // size doesn't really matter, but we can align it to the actual size
104
+ // returning variables because one likely want to use this hack from python
105
+ auto retval = at::empty({sizeof(T)}, options.device(kCPU).dtype(at::kByte));
106
+ retval.storage().set_data_ptr_noswap(std::move(at_ptr));
107
+ return retval;
108
+ }
109
+
110
+ } // namespace at::cpp_custom_type_hack
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/div_rtn.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Integer division rounding to -Infinity
4
+ template <typename T>
5
+ static inline T div_rtn(T x, T y) {
6
+ int q = x / y;
7
+ int r = x % y;
8
+ if ((r != 0) && ((r < 0) != (y < 0)))
9
+ --q;
10
+ return q;
11
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/dlpack.h ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ * Copyright (c) 2017 by Contributors
3
+ * \file dlpack.h
4
+ * \brief The common header of DLPack.
5
+ */
6
+ #ifndef DLPACK_DLPACK_H_
7
+ #define DLPACK_DLPACK_H_
8
+
9
+ /**
10
+ * \brief Compatibility with C++
11
+ */
12
+ #ifdef __cplusplus
13
+ #define DLPACK_EXTERN_C extern "C"
14
+ #else
15
+ #define DLPACK_EXTERN_C
16
+ #endif
17
+
18
+ /*! \brief The current version of dlpack */
19
+ #define DLPACK_VERSION 80
20
+
21
+ /*! \brief The current ABI version of dlpack */
22
+ #define DLPACK_ABI_VERSION 1
23
+
24
+ /*! \brief DLPACK_DLL prefix for windows */
25
+ #ifdef _WIN32
26
+ #ifdef DLPACK_EXPORTS
27
+ #define DLPACK_DLL __declspec(dllexport)
28
+ #else
29
+ #define DLPACK_DLL __declspec(dllimport)
30
+ #endif
31
+ #else
32
+ #define DLPACK_DLL
33
+ #endif
34
+
35
+ // NOLINTNEXTLINE(modernize-deprecated-headers)
36
+ #include <stdint.h>
37
+ // NOLINTNEXTLINE(modernize-deprecated-headers)
38
+ #include <stddef.h>
39
+
40
+ #ifdef __cplusplus
41
+ extern "C" {
42
+ #endif
43
+ /*!
44
+ * \brief The device type in DLDevice.
45
+ */
46
+ #ifdef __cplusplus
47
+ typedef enum : int32_t {
48
+ #else
49
+ typedef enum {
50
+ #endif
51
+ /*! \brief CPU device */
52
+ kDLCPU = 1,
53
+ /*! \brief CUDA GPU device */
54
+ kDLCUDA = 2,
55
+ /*!
56
+ * \brief Pinned CUDA CPU memory by cudaMallocHost
57
+ */
58
+ kDLCUDAHost = 3,
59
+ /*! \brief OpenCL devices. */
60
+ kDLOpenCL = 4,
61
+ /*! \brief Vulkan buffer for next generation graphics. */
62
+ kDLVulkan = 7,
63
+ /*! \brief Metal for Apple GPU. */
64
+ kDLMetal = 8,
65
+ /*! \brief Verilog simulator buffer */
66
+ kDLVPI = 9,
67
+ /*! \brief ROCm GPUs for AMD GPUs */
68
+ kDLROCM = 10,
69
+ /*!
70
+ * \brief Pinned ROCm CPU memory allocated by hipMallocHost
71
+ */
72
+ kDLROCMHost = 11,
73
+ /*!
74
+ * \brief Reserved extension device type,
75
+ * used for quickly test extension device
76
+ * The semantics can differ depending on the implementation.
77
+ */
78
+ kDLExtDev = 12,
79
+ /*!
80
+ * \brief CUDA managed/unified memory allocated by cudaMallocManaged
81
+ */
82
+ kDLCUDAManaged = 13,
83
+ /*!
84
+ * \brief Unified shared memory allocated on a oneAPI non-partititioned
85
+ * device. Call to oneAPI runtime is required to determine the device
86
+ * type, the USM allocation type and the sycl context it is bound to.
87
+ *
88
+ */
89
+ kDLOneAPI = 14,
90
+ /*! \brief GPU support for next generation WebGPU standard. */
91
+ kDLWebGPU = 15,
92
+ /*! \brief Qualcomm Hexagon DSP */
93
+ kDLHexagon = 16,
94
+ /*! \brief Microsoft AI Accelerator */
95
+ kDLMAIA = 17,
96
+ } DLDeviceType;
97
+
98
+ /*!
99
+ * \brief A Device for Tensor and operator.
100
+ */
101
+ typedef struct {
102
+ /*! \brief The device type used in the device. */
103
+ DLDeviceType device_type;
104
+ /*!
105
+ * \brief The device index.
106
+ * For vanilla CPU memory, pinned memory, or managed memory, this is set to 0.
107
+ */
108
+ int32_t device_id;
109
+ } DLDevice;
110
+
111
+ /*!
112
+ * \brief The type code options DLDataType.
113
+ */
114
+ typedef enum {
115
+ /*! \brief signed integer */
116
+ kDLInt = 0U,
117
+ /*! \brief unsigned integer */
118
+ kDLUInt = 1U,
119
+ /*! \brief IEEE floating point */
120
+ kDLFloat = 2U,
121
+ /*!
122
+ * \brief Opaque handle type, reserved for testing purposes.
123
+ * Frameworks need to agree on the handle data type for the exchange to be well-defined.
124
+ */
125
+ kDLOpaqueHandle = 3U,
126
+ /*! \brief bfloat16 */
127
+ kDLBfloat = 4U,
128
+ /*!
129
+ * \brief complex number
130
+ * (C/C++/Python layout: compact struct per complex number)
131
+ */
132
+ kDLComplex = 5U,
133
+ /*! \brief boolean */
134
+ kDLBool = 6U,
135
+ } DLDataTypeCode;
136
+
137
+ /*!
138
+ * \brief The data type the tensor can hold. The data type is assumed to follow the
139
+ * native endian-ness. An explicit error message should be raised when attempting to
140
+ * export an array with non-native endianness
141
+ *
142
+ * Examples
143
+ * - float: type_code = 2, bits = 32, lanes = 1
144
+ * - float4(vectorized 4 float): type_code = 2, bits = 32, lanes = 4
145
+ * - int8: type_code = 0, bits = 8, lanes = 1
146
+ * - std::complex<float>: type_code = 5, bits = 64, lanes = 1
147
+ * - bool: type_code = 6, bits = 8, lanes = 1 (as per common array library convention, the underlying storage size of bool is 8 bits)
148
+ */
149
+ typedef struct {
150
+ /*!
151
+ * \brief Type code of base types.
152
+ * We keep it uint8_t instead of DLDataTypeCode for minimal memory
153
+ * footprint, but the value should be one of DLDataTypeCode enum values.
154
+ * */
155
+ uint8_t code;
156
+ /*!
157
+ * \brief Number of bits, common choices are 8, 16, 32.
158
+ */
159
+ uint8_t bits;
160
+ /*! \brief Number of lanes in the type, used for vector types. */
161
+ uint16_t lanes;
162
+ } DLDataType;
163
+
164
+ /*!
165
+ * \brief Plain C Tensor object, does not manage memory.
166
+ */
167
+ typedef struct {
168
+ /*!
169
+ * \brief The data pointer points to the allocated data. This will be CUDA
170
+ * device pointer or cl_mem handle in OpenCL. It may be opaque on some device
171
+ * types. This pointer is always aligned to 256 bytes as in CUDA. The
172
+ * `byte_offset` field should be used to point to the beginning of the data.
173
+ *
174
+ * Note that as of Nov 2021, multiply libraries (CuPy, PyTorch, TensorFlow,
175
+ * TVM, perhaps others) do not adhere to this 256 byte aligment requirement
176
+ * on CPU/CUDA/ROCm, and always use `byte_offset=0`. This must be fixed
177
+ * (after which this note will be updated); at the moment it is recommended
178
+ * to not rely on the data pointer being correctly aligned.
179
+ *
180
+ * For given DLTensor, the size of memory required to store the contents of
181
+ * data is calculated as follows:
182
+ *
183
+ * \code{.c}
184
+ * static inline size_t GetDataSize(const DLTensor* t) {
185
+ * size_t size = 1;
186
+ * for (tvm_index_t i = 0; i < t->ndim; ++i) {
187
+ * size *= t->shape[i];
188
+ * }
189
+ * size *= (t->dtype.bits * t->dtype.lanes + 7) / 8;
190
+ * return size;
191
+ * }
192
+ * \endcode
193
+ */
194
+ void* data;
195
+ /*! \brief The device of the tensor */
196
+ DLDevice device;
197
+ /*! \brief Number of dimensions */
198
+ int32_t ndim;
199
+ /*! \brief The data type of the pointer*/
200
+ DLDataType dtype;
201
+ /*! \brief The shape of the tensor */
202
+ const int64_t* shape;
203
+ /*!
204
+ * \brief strides of the tensor (in number of elements, not bytes)
205
+ * can be NULL, indicating tensor is compact and row-majored.
206
+ */
207
+ const int64_t* strides;
208
+ /*! \brief The offset in bytes to the beginning pointer to data */
209
+ uint64_t byte_offset;
210
+ } DLTensor;
211
+
212
+ /*!
213
+ * \brief C Tensor object, manage memory of DLTensor. This data structure is
214
+ * intended to facilitate the borrowing of DLTensor by another framework. It is
215
+ * not meant to transfer the tensor. When the borrowing framework doesn't need
216
+ * the tensor, it should call the deleter to notify the host that the resource
217
+ * is no longer needed.
218
+ */
219
+ typedef struct DLManagedTensor {
220
+ /*! \brief DLTensor which is being memory managed */
221
+ DLTensor dl_tensor;
222
+ /*! \brief the context of the original host framework of DLManagedTensor in
223
+ * which DLManagedTensor is used in the framework. It can also be NULL.
224
+ */
225
+ void * manager_ctx;
226
+ /*! \brief Destructor signature void (*)(void*) - this should be called
227
+ * to destruct manager_ctx which holds the DLManagedTensor. It can be NULL
228
+ * if there is no way for the caller to provide a reasonable destructor.
229
+ * The destructors deletes the argument self as well.
230
+ */
231
+ void (*deleter)(struct DLManagedTensor * self);
232
+ } DLManagedTensor;
233
+ #ifdef __cplusplus
234
+ } // DLPACK_EXTERN_C
235
+ #endif
236
+ #endif // DLPACK_DLPACK_H_
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/jit_macros.h ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/cuda/CUDAConfig.h>
3
+ #include <string>
4
+
5
+ // AT_USE_JITERATOR(), controls whether we jit some elementwise kernels
6
+ #define AT_USE_JITERATOR() true
7
+ #define jiterator_stringify(...) std::string(#__VA_ARGS__);
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/jiterator_macros.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Macros.h>
3
+ #include <string>
4
+
5
+ #define JITERATOR_HOST_DEVICE C10_HOST_DEVICE
6
+ #if defined(_MSC_VER) && defined(__CUDACC__)
7
+ // NVRTC on Windows errors if __host__ __device__ attribute is
8
+ // present on kernel.
9
+ // error: attribute "__host__" does not apply here
10
+ // error: attribute "__device__" does not apply here
11
+ #define JITERATOR_HOST_DEVICE
12
+ #endif
13
+
14
+ // jiterator_also_stringify_as macro is used to define code (for CPU/ROCm)
15
+ // and generate code string for `jiterator` (only when compiling for CUDA).
16
+ // Usage :
17
+ // jiterator_also_stringify_as(
18
+ // jiterator_code(template <typename T> T identity(T x) { return x; }),
19
+ // identity_string);
20
+ // This will define the template `identity` as present in code and
21
+ // also define `std::string identity_string` with the code as the string
22
+ // if this is being compiled for CUDA.
23
+
24
+ // `jiterator_code` macro is to deal with `,` in the kernel code.
25
+ // These `,`s confuse the preprocessor into thinking we are passing
26
+ // multiple arguments to the macro.
27
+ #define jiterator_code(...) __VA_ARGS__
28
+ #if defined(__CUDACC__) || defined(__HIPCC__)
29
+ // CPU and CUDA and ROCm case
30
+ #define stringify_code(...) #__VA_ARGS__
31
+ #define jiterator_also_stringify_as(code, str_name) \
32
+ code /* define the function */ \
33
+ const std::string str_name = std::string(stringify_code(code));
34
+ #else
35
+ // CPU only or CPU and ROCm case
36
+ // Only needs the function
37
+ #define jiterator_also_stringify_as(code, str_name) code
38
+ #endif
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/record_function.h ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <ATen/core/operator_name.h>
5
+ #include <c10/macros/Export.h>
6
+ #include <c10/util/SmallVector.h>
7
+ #include <optional>
8
+
9
+ #include <array>
10
+ #include <functional>
11
+ #include <memory>
12
+ #include <variant>
13
+
14
+ namespace c10 {
15
+ class TORCH_API OperatorHandle;
16
+ }
17
+
18
+ namespace at {
19
+
20
+ // Function name to record NCCL metadata
21
+ extern TORCH_API const std::string kParamCommsCallName;
22
+
23
+ // Kind of record function scope;
24
+ enum class C10_API_ENUM RecordScope : uint8_t {
25
+ // c10/ATen ops, autograd nodes
26
+ FUNCTION = 0,
27
+ // Functions/nodes called from the autograd
28
+ BACKWARD_FUNCTION,
29
+ // TorchScript functions, methods
30
+ TORCHSCRIPT_FUNCTION,
31
+ // Kernel Function dtype Tag
32
+ KERNEL_FUNCTION_DTYPE,
33
+ // Torchbind custom class,
34
+ CUSTOM_CLASS,
35
+ // Generic Build Feature
36
+ BUILD_FEATURE,
37
+ // Kernel Function dtype Tag
38
+ LITE_INTERPRETER,
39
+ // User defined scope (e.g. with record_function())
40
+ USER_SCOPE,
41
+ // Scopes for static runtime, a specialized TorchScript interpreter
42
+ STATIC_RUNTIME_OP,
43
+ STATIC_RUNTIME_MODEL,
44
+ NUM_SCOPES, // must be the last in the list
45
+ };
46
+
47
+ } // namespace at
48
+
49
+ namespace std {
50
+ template <>
51
+ struct hash<at::RecordScope> {
52
+ size_t operator()(const at::RecordScope& sc) const {
53
+ return static_cast<std::size_t>(sc);
54
+ }
55
+ };
56
+ } // namespace std
57
+
58
+ namespace at {
59
+
60
+ struct TORCH_API StringView {
61
+ StringView() : StringView(nullptr) {}
62
+ explicit StringView(const char* str_ptr)
63
+ : owned_str_ptr_(nullptr), str_ptr_(str_ptr) {}
64
+ explicit StringView(std::string str)
65
+ : owned_str_ptr_(std::make_shared<std::string>(std::move(str))),
66
+ str_ptr_(owned_str_ptr_->c_str()) {}
67
+
68
+ const char* str() const {
69
+ return str_ptr_;
70
+ }
71
+
72
+ friend std::ostream& operator<<(std::ostream& os, const StringView& dt) {
73
+ os << dt.str();
74
+ return os;
75
+ }
76
+
77
+ friend bool operator==(const StringView& lhs, const StringView& rhs) {
78
+ return strcmp(lhs.str(), rhs.str()) == 0;
79
+ }
80
+
81
+ friend bool operator!=(const StringView& lhs, const StringView& rhs) {
82
+ return !(lhs == rhs);
83
+ }
84
+
85
+ private:
86
+ std::shared_ptr<std::string> owned_str_ptr_;
87
+ const char* str_ptr_;
88
+ };
89
+
90
+ // Soft limit on the number of callbacks to use;
91
+ constexpr std::size_t kSoftLimitCallbacks = 4;
92
+
93
+ // An abstract base class for various observer contexts that can be attached to
94
+ // the RecordFunction.
95
+ struct ObserverContext {
96
+ virtual ~ObserverContext() = default;
97
+
98
+ protected:
99
+ ObserverContext() = default;
100
+ };
101
+
102
+ typedef c10::SmallVector<uint64_t, kSoftLimitCallbacks> CallbackHandles;
103
+ typedef c10::SmallVector<std::unique_ptr<ObserverContext>, kSoftLimitCallbacks>
104
+ ObserverContextList;
105
+ typedef uint64_t RecordFunctionHandle;
106
+ struct RecordFunction;
107
+
108
+ //
109
+ // PyTorch callbacks/observers API:
110
+ //
111
+
112
+ /**
113
+ * RecordFunctionCallback represents a pair of callbacks to be used with
114
+ * RecordFunction, members:
115
+ * start, end - the callbacks to run when entering and exiting the scope;
116
+ * optionally, the start callback may return an ObserverContext which will
117
+ * be passed to the end callback, use appropriate constructor accordingly.
118
+ * needs_inputs - whether the callbacks need the inputs passed from the
119
+ * observed function/range; NOTE: passing the inputs incurs an additional
120
+ * overhead; sampling_probability - if not 1.0, then the callback is
121
+ * probabilistically sampled to run; NOTE: start and end callbacks always run as
122
+ * a pair and are sampled together; scopes - types of scopes to execute the
123
+ * callbacks on (see RecordScope); passing empty set means the callbacks will be
124
+ * executed for all possible scope types should_run - optional function that
125
+ * returns whether this callback should run; overwrites the effect of setting
126
+ * sampling_probability
127
+ */
128
+ class TORCH_API RecordFunctionCallback {
129
+ public:
130
+ using StartCallback =
131
+ std::unique_ptr<ObserverContext> (*)(const RecordFunction&);
132
+ using EndCallback = void (*)(const RecordFunction&, ObserverContext*);
133
+
134
+ // This interface supports observers that require passing an ObserverContext
135
+ // between start and end callbacks.
136
+ explicit RecordFunctionCallback(
137
+ StartCallback start,
138
+ EndCallback end = nullptr)
139
+ : start_(start), end_(end) {
140
+ scopes_.fill(true);
141
+ }
142
+
143
+ RecordFunctionCallback& needsInputs(bool needs_inputs) {
144
+ needs_inputs_ = needs_inputs;
145
+ return *this;
146
+ }
147
+
148
+ RecordFunctionCallback& needsOutputs(bool needs_outputs) {
149
+ needs_outputs_ = needs_outputs;
150
+ return *this;
151
+ }
152
+
153
+ RecordFunctionCallback& needsIds(bool needs_ids) {
154
+ needs_ids_ = needs_ids;
155
+ return *this;
156
+ }
157
+
158
+ RecordFunctionCallback& samplingProb(double sampling_prob) {
159
+ TORCH_CHECK(
160
+ sampling_prob >= 0.0 && sampling_prob <= 1.0,
161
+ "Invalid sampling probability");
162
+ sampling_prob_ = sampling_prob;
163
+ return *this;
164
+ }
165
+
166
+ RecordFunctionCallback& scopes(
167
+ const std::unordered_set<RecordScope, std::hash<RecordScope>>& scopes) {
168
+ if (!scopes.empty()) {
169
+ scopes_.fill(false);
170
+ for (auto sc : scopes) {
171
+ scopes_[static_cast<size_t>(sc)] = true;
172
+ }
173
+ } else {
174
+ scopes_.fill(true);
175
+ }
176
+ return *this;
177
+ }
178
+
179
+ bool needsInputs() const {
180
+ return needs_inputs_;
181
+ }
182
+
183
+ bool needsOutputs() const {
184
+ return needs_outputs_;
185
+ }
186
+
187
+ bool needsIds() const {
188
+ return needs_ids_;
189
+ }
190
+
191
+ double samplingProb() const {
192
+ return sampling_prob_;
193
+ }
194
+
195
+ bool checkScope(RecordScope sc) const {
196
+ return scopes_[(size_t)sc];
197
+ }
198
+
199
+ StartCallback start() const {
200
+ return start_;
201
+ }
202
+
203
+ EndCallback end() const {
204
+ return end_;
205
+ }
206
+
207
+ private:
208
+ StartCallback start_;
209
+ EndCallback end_;
210
+ double sampling_prob_ = 1.0;
211
+ std::array<bool, static_cast<size_t>(RecordScope::NUM_SCOPES)> scopes_ = {};
212
+ bool needs_inputs_ = false;
213
+ bool needs_outputs_ = false;
214
+ bool needs_ids_ = false;
215
+ };
216
+
217
+ // Notes:
218
+ // - two types of callbacks are provided: thread local and global
219
+ // - thread local callbacks are added/removed only for the given thread
220
+ // and are stored locally for each thread and separately from the list
221
+ // of the global callbacks
222
+ // - global callbacks are stored in a single per process list and are
223
+ // invoked by every RecordFunction, in addition to the thread local
224
+ // callbacks specific to the given thread
225
+ // - we allow the added callbacks to be sampled, by specifying a sampling
226
+ // probability for each callback pair, if the start callback is
227
+ // not picked to run, the corresponding end callback won't be called
228
+ // - a typical use case for the global callbacks is passive monitoring
229
+ // in the background (e.g. fleet-wide monitoring), without focusing on
230
+ // the specific piece of code
231
+ // - in contrast, thread local callbacks are enabled locally, on demand,
232
+ // for the specific piece of code (range) and are not sampled
233
+ // - a typical use case for thread local callbacks is profiler and code
234
+ // execution tracer
235
+ // - note, thread local callbacks are automatically propagated with
236
+ // ThreadLocalState across JIT continuations and async tasks (at::launch)
237
+
238
+ typedef uint64_t CallbackHandle;
239
+
240
+ constexpr CallbackHandle INVALID_CALLBACK_HANDLE{0};
241
+
242
+ // It is unnecessary to use atomic operations for enabling
243
+ // thread-local function callbacks. Moreover, it prevents saving to
244
+ // ThreadLocalState because std::atomic is non-copyable.
245
+ struct RecordFunctionCallbacksEntry {
246
+ RecordFunctionCallbacksEntry(RecordFunctionCallback cb, CallbackHandle h)
247
+ : callback_(cb), handle_(h) {}
248
+
249
+ RecordFunctionCallback callback_;
250
+ bool enabled_{true};
251
+ CallbackHandle handle_;
252
+ };
253
+
254
+ // Holds pairs (callbacks, unique_id)
255
+ using RecordFunctionCallbacks = std::vector<RecordFunctionCallbacksEntry>;
256
+
257
+ // Generated by the callback managers to determine which functions to run.
258
+ struct StepCallbacks {
259
+ StepCallbacks() = default;
260
+ StepCallbacks(uint64_t thread_id, RecordScope scope)
261
+ : thread_id_{thread_id}, scope_{scope} {}
262
+
263
+ bool empty() const {
264
+ return callbacks_.empty();
265
+ }
266
+
267
+ struct StartEndPair {
268
+ RecordFunctionCallback::StartCallback start_;
269
+ RecordFunctionCallback::EndCallback end_;
270
+ };
271
+
272
+ using StartEndPairs = c10::SmallVector<StartEndPair, kSoftLimitCallbacks>;
273
+
274
+ StartEndPairs callbacks_;
275
+ uint64_t thread_id_{0};
276
+ RecordScope scope_{RecordScope::FUNCTION};
277
+ bool needs_inputs_{false};
278
+ bool needs_outputs_{false};
279
+ bool needs_ids_{false};
280
+ };
281
+
282
+ struct TORCH_API RecordFunction {
283
+ // Default constructor is used with before function called afterwards:
284
+ // scope - record scope that this function tracks
285
+ // pre_sampled - whether this RecordFunction was already pre-sampled with
286
+ // kLowProb probability
287
+ explicit RecordFunction(RecordScope scope = RecordScope::FUNCTION);
288
+ explicit RecordFunction(StepCallbacks&& step_callbacks);
289
+
290
+ template <typename F>
291
+ void before(
292
+ F fn,
293
+ c10::ArrayRef<const c10::IValue> args,
294
+ int64_t current_sequence_nr = -1) {
295
+ if (!isActive()) {
296
+ return;
297
+ }
298
+ inputs_ = args;
299
+ before(fn, current_sequence_nr);
300
+ }
301
+
302
+ template <typename F>
303
+ void before(
304
+ F fn,
305
+ c10::ArrayRef<const c10::IValue> args,
306
+ const std::unordered_map<std::string, IValue>* kwargs,
307
+ int64_t current_sequence_nr = -1) {
308
+ if (!isActive()) {
309
+ return;
310
+ }
311
+ kwinputs_ = *kwargs;
312
+ before(std::move(fn), args, current_sequence_nr);
313
+ }
314
+
315
+ template <typename F>
316
+ void before(
317
+ F fn,
318
+ const std::unordered_map<std::string, IValue>* kwargs,
319
+ int64_t current_sequence_nr = -1) {
320
+ if (!isActive()) {
321
+ return;
322
+ }
323
+ kwinputs_ = *kwargs;
324
+ before(fn, current_sequence_nr);
325
+ }
326
+
327
+ template <typename F>
328
+ void before(
329
+ F fn,
330
+ const std::vector<IValue>* args,
331
+ int64_t current_sequence_nr = -1) {
332
+ before(
333
+ std::move(fn),
334
+ c10::ArrayRef<const c10::IValue>(args->data(), args->size()),
335
+ current_sequence_nr);
336
+ }
337
+
338
+ template <typename F>
339
+ void before(
340
+ F fn,
341
+ const std::vector<IValue>* args,
342
+ const std::unordered_map<std::string, IValue>* kwargs,
343
+ int64_t current_sequence_nr = -1) {
344
+ if (!isActive()) {
345
+ return;
346
+ }
347
+ kwinputs_ = *kwargs;
348
+ before(std::move(fn), args, current_sequence_nr);
349
+ }
350
+
351
+ // Destructor calls end callbacks
352
+ virtual ~RecordFunction();
353
+
354
+ RecordFunction(const RecordFunction&) = delete;
355
+ RecordFunction& operator=(const RecordFunction&) = delete;
356
+ RecordFunction(RecordFunction&&) = delete;
357
+ RecordFunction& operator=(RecordFunction&&) = delete;
358
+
359
+ const char* name() const;
360
+ const char* overload_name() const;
361
+
362
+ int64_t seqNr() const {
363
+ return sequence_nr_;
364
+ }
365
+
366
+ c10::ArrayRef<const IValue> inputs() const {
367
+ #ifndef NDEBUG
368
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
369
+ inputs_valid_, "Called inputs() outside RecordFunction start callback");
370
+ #endif
371
+ return inputs_;
372
+ }
373
+
374
+ std::unordered_map<std::string, IValue> kwinputs() const {
375
+ #ifndef NDEBUG
376
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
377
+ inputs_valid_,
378
+ "Called kwinputs() outside RecordFunction start callback");
379
+ #endif
380
+ return kwinputs_;
381
+ }
382
+
383
+ const std::vector<c10::IValue>& outputs() const {
384
+ return outputs_;
385
+ }
386
+
387
+ void setOutputs(std::vector<c10::IValue>&& outputs) {
388
+ outputs_ = std::move(outputs);
389
+ }
390
+
391
+ void setOutputs(c10::ArrayRef<c10::IValue> outputs) {
392
+ outputs_ = outputs.vec();
393
+ }
394
+
395
+ size_t num_inputs() const;
396
+ size_t num_outputs() const;
397
+
398
+ // Retrieves the thread_id that this RecordFunction ran start callbacks with.
399
+ // Useful for writing thread safe end callbacks that may be potentially
400
+ // executed in a different thread (async ops)
401
+ uint64_t threadId() const {
402
+ return step_callbacks_.thread_id_;
403
+ }
404
+
405
+ // For backward functions - thread id of the corresponding forward function,
406
+ // or zero otherwise;
407
+ // used alongside with sequence number to correlate backward functions with
408
+ // the forward ones
409
+ uint64_t forwardThreadId() const {
410
+ return fwd_thread_id_;
411
+ }
412
+
413
+ void setForwardThreadId(uint64_t thread_id) {
414
+ fwd_thread_id_ = thread_id;
415
+ }
416
+
417
+ RecordScope scope() const {
418
+ return step_callbacks_.scope_;
419
+ }
420
+
421
+ // Returns logical thread_id for the current thread
422
+ static uint64_t currentThreadId();
423
+
424
+ // Internal functions, do not use directly;
425
+ // used in python's context manager
426
+
427
+ // before functions initialize RecordFunction members and call
428
+ // start callbacks
429
+ using schema_ref_t = std::reference_wrapper<const c10::FunctionSchema>;
430
+ void before(const char* name, int64_t sequence_nr = -1);
431
+ void before(std::string name, int64_t sequence_nr = -1);
432
+ void before(schema_ref_t schema, int64_t sequence_nr = -1);
433
+
434
+ // Sets node ID for distributed profiling
435
+ static void setDefaultNodeId(int64_t defaultNodeId);
436
+ // Gets node ID for distributed profiling
437
+ static int64_t getDefaultNodeId();
438
+
439
+ // Calls end callbacks. After end(), accessors will no longer provide useful
440
+ // results.
441
+ void end();
442
+
443
+ // Internal-only, used only force async event for distributed events
444
+ // profiling.
445
+ void _setAsync();
446
+
447
+ // Returns whether this RecordFunction corresponds to an async event or not.
448
+ bool isAsync() const;
449
+
450
+ // Returns whether this RecordFunction corresponds to NCCL metadata collection
451
+ // or not.
452
+ bool isNcclMeta() const {
453
+ return is_nccl_meta_;
454
+ }
455
+
456
+ // Internal-only, used to denote out variant used for Static Runtime execution
457
+ void _setStaticRuntimeOutVariant();
458
+ bool isStaticRuntimeOutVariant() const;
459
+
460
+ RecordFunctionHandle handle() const {
461
+ return handle_;
462
+ }
463
+
464
+ std::optional<OperatorName> operator_name() const;
465
+
466
+ // This method returns a copy of the FunctionSchema and can be expensive.
467
+ std::optional<FunctionSchema> operator_schema() const;
468
+
469
+ void setHandle(RecordFunctionHandle handle) {
470
+ handle_ = handle;
471
+ }
472
+
473
+ // Whether this RecordFunction runs any callbacks.
474
+ bool isActive() const {
475
+ return !step_callbacks_.empty();
476
+ }
477
+
478
+ bool needsInputs() const {
479
+ return step_callbacks_.needs_inputs_;
480
+ }
481
+
482
+ bool needsOutputs() const {
483
+ return step_callbacks_.needs_outputs_;
484
+ }
485
+
486
+ int64_t debugHandle() const {
487
+ return debug_handle_;
488
+ }
489
+
490
+ void setDebugHandle(int64_t debug_handle) {
491
+ debug_handle_ = debug_handle;
492
+ }
493
+
494
+ void invalidateInputs() {
495
+ #ifndef NDEBUG
496
+ inputs_valid_ = false;
497
+ #endif
498
+ }
499
+
500
+ private:
501
+ void runStartCallbacks();
502
+
503
+ StepCallbacks step_callbacks_;
504
+
505
+ // In cases when RecordFunction might be active but we chose not to
506
+ // use the observers (e.g. operator is not observed), this boolean
507
+ // flag is used to check whether the start callbacks were called
508
+ bool called_start_callbacks_ = false;
509
+
510
+ #ifndef NDEBUG
511
+ bool inputs_valid_ = false;
512
+ #endif
513
+
514
+ // Stores various ObserverContext objects with event metadata for callbacks.
515
+ ObserverContextList ctx_;
516
+
517
+ std::variant<std::string, schema_ref_t> fn_;
518
+
519
+ int64_t sequence_nr_ = -1;
520
+ c10::ArrayRef<const IValue> inputs_;
521
+ std::unordered_map<std::string, IValue> kwinputs_;
522
+ std::vector<c10::IValue> outputs_;
523
+
524
+ // For backward functions - thread id of the forward function
525
+ uint64_t fwd_thread_id_ = 0;
526
+
527
+ // Unique id for this RecordFunction, used in callbacks to track start
528
+ // and end of ranges
529
+ RecordFunctionHandle handle_{0};
530
+
531
+ // Whether this record_function corresponds to an async event or not. Async
532
+ // events can complete in different threads or follow a future-like pattern
533
+ // of use.
534
+ bool is_async_{false};
535
+
536
+ // Debug handles are used for lazy annotation of module hierarchy
537
+ // and callstack.
538
+ // This is specifically is useful for mobile runtime, where generated
539
+ // debug handles can be lazily symbolicated using debug information
540
+ int64_t debug_handle_{-1};
541
+
542
+ // Whether this RecordFunction is used for an out variant run with
543
+ // Static Runtime
544
+ bool is_static_runtime_out_variant_{false};
545
+
546
+ // Whether this RecordFunction is used for NCCL metadata collection
547
+ bool is_nccl_meta_{false};
548
+ };
549
+
550
+ TORCH_API StepCallbacks getStepCallbacks(RecordScope scope);
551
+
552
+ TORCH_API std::optional<StepCallbacks> getStepCallbacksUnlessEmpty(
553
+ RecordScope scope);
554
+
555
+ namespace detail {
556
+ template <typename Inputs, typename F, typename... Args>
557
+ void record_function_with_scope(
558
+ RecordFunction& guard,
559
+ F fn,
560
+ const Inputs& inputs,
561
+ Args&&... args) {
562
+ if (guard.needsInputs()) {
563
+ guard.before(
564
+ fn,
565
+ c10::ArrayRef<const c10::IValue>(inputs.data(), inputs.size()),
566
+ std::forward<Args>(args)...);
567
+ } else {
568
+ guard.before(fn, std::forward<Args>(args)...);
569
+ }
570
+ }
571
+
572
+ template <typename Inputs, typename F, typename... Args>
573
+ void record_function_with_scope_and_debug_handle(
574
+ RecordFunction& guard,
575
+ F fn,
576
+ int64_t debug_handle,
577
+ const Inputs& inputs,
578
+ Args&&... args) {
579
+ guard.setDebugHandle(debug_handle);
580
+ if (guard.needsInputs()) {
581
+ guard.before(
582
+ fn,
583
+ c10::ArrayRef<const c10::IValue>(inputs.data(), inputs.size()),
584
+ std::forward<Args>(args)...);
585
+ } else {
586
+ guard.before(fn, std::forward<Args>(args)...);
587
+ }
588
+ }
589
+
590
+ template <typename F, typename... Args>
591
+ void record_function_with_scope(
592
+ RecordFunction& guard,
593
+ F fn,
594
+ c10::ArrayRef<const c10::IValue> inputs,
595
+ Args&&... args) {
596
+ return record_function_with_scope<
597
+ c10::ArrayRef<const c10::IValue>,
598
+ F,
599
+ Args...>(guard, std::move(fn), inputs, std::forward<Args>(args)...);
600
+ }
601
+
602
+ template <typename F, typename... Args>
603
+ void record_function_with_scope_and_debug_handle(
604
+ RecordFunction& guard,
605
+ F fn,
606
+ int64_t debug_handle,
607
+ c10::ArrayRef<const c10::IValue> inputs,
608
+ Args&&... args) {
609
+ return record_function_with_scope_and_debug_handle<
610
+ c10::ArrayRef<const c10::IValue>,
611
+ F,
612
+ Args...>(
613
+ guard, std::move(fn), debug_handle, inputs, std::forward<Args>(args)...);
614
+ }
615
+
616
+ } // namespace detail
617
+
618
+ // optional argument - function's seq_no
619
+ #define RECORD_FUNCTION_WITH_SCOPE(scope, fn, inputs, ...) \
620
+ at::RecordFunction guard(scope); \
621
+ if (guard.isActive()) { \
622
+ ::at::detail::record_function_with_scope( \
623
+ guard, fn, inputs, ##__VA_ARGS__); \
624
+ }
625
+
626
+ #define RECORD_FUNCTION_WITH_SCOPE_INPUTS_OUTPUTS( \
627
+ scope, fn, inputs, outputs, ...) \
628
+ at::RecordFunction guard(scope); \
629
+ if (guard.isActive()) { \
630
+ if (guard.needsInputs()) { \
631
+ guard.before(fn, inputs, ##__VA_ARGS__); \
632
+ } else { \
633
+ guard.before(fn, ##__VA_ARGS__); \
634
+ } \
635
+ if (guard.needsOutputs()) { \
636
+ guard.setOutputs(outputs); \
637
+ } \
638
+ }
639
+
640
+ #define RECORD_FUNCTION(fn, inputs, ...) \
641
+ RECORD_FUNCTION_WITH_SCOPE( \
642
+ at::RecordScope::FUNCTION, fn, inputs, ##__VA_ARGS__)
643
+
644
+ #define RECORD_TORCHSCRIPT_FUNCTION(mn, inputs) \
645
+ RECORD_FUNCTION_WITH_SCOPE(at::RecordScope::TORCHSCRIPT_FUNCTION, mn, inputs)
646
+
647
+ #define RECORD_FUNCTION_WITH_INPUTS_OUTPUTS(fn, inputs, outputs, ...) \
648
+ RECORD_FUNCTION_WITH_SCOPE_INPUTS_OUTPUTS( \
649
+ at::RecordScope::FUNCTION, fn, inputs, outputs, ##__VA_ARGS__)
650
+
651
+ // Custom user scopes in C++; similar to Python's 'with record_function("..."):'
652
+ #define RECORD_USER_SCOPE(fn) \
653
+ RECORD_FUNCTION_WITH_SCOPE( \
654
+ at::RecordScope::USER_SCOPE, fn, c10::ArrayRef<const c10::IValue>{})
655
+
656
+ // RECORD_USER_SCOPE with inputs
657
+ #define RECORD_USER_SCOPE_WITH_INPUTS(fn, inputs) \
658
+ RECORD_FUNCTION_WITH_SCOPE(at::RecordScope::USER_SCOPE, fn, inputs)
659
+
660
+ #define RECORD_USER_SCOPE_WITH_KWARGS_ONLY(fn, kwargs) \
661
+ RECORD_FUNCTION_WITH_SCOPE( \
662
+ at::RecordScope::USER_SCOPE, \
663
+ fn, \
664
+ c10::ArrayRef<const c10::IValue>{}, \
665
+ kwargs)
666
+
667
+ // Helper macro to pass in debug handle that is used to
668
+ // post process events
669
+ #define RECORD_WITH_SCOPE_DEBUG_HANDLE_AND_INPUTS( \
670
+ scope, fn, debug_handle, inputs, ...) \
671
+ at::RecordFunction guard(scope); \
672
+ if (guard.isActive()) { \
673
+ ::at::detail::record_function_with_scope_and_debug_handle( \
674
+ guard, fn, debug_handle, inputs, ##__VA_ARGS__); \
675
+ }
676
+
677
+ // Helper macros to record LITE INTERPETER scope events with debug handles
678
+ #define RECORD_EDGE_SCOPE_WITH_DEBUG_HANDLE_AND_INPUTS( \
679
+ fn, debug_handle, inputs) \
680
+ RECORD_WITH_SCOPE_DEBUG_HANDLE_AND_INPUTS( \
681
+ at::RecordScope::LITE_INTERPRETER, fn, debug_handle, inputs)
682
+
683
+ // Bookend to the RECORD_FUNCTION macros. Use this after the kernel
684
+ // launch to let the profiler bind the outputs to the op that produced
685
+ // them. Note that guard is declared by RECORD_FUNCTION so this macro
686
+ // needs to be called from the same scope as RECORD_FUNCTION
687
+ #define RECORD_OUTPUTS(outputs) \
688
+ if (guard.needsOutputs()) { \
689
+ guard.setOutputs( \
690
+ std::vector<c10::IValue>(outputs.begin(), outputs.end())); \
691
+ }
692
+
693
+ /**
694
+ * addThreadLocalCallback adds a thread local callback to run with
695
+ * RecordFunction, returns handle to use with removeThreadLocalCallback
696
+ */
697
+ TORCH_API CallbackHandle addThreadLocalCallback(RecordFunctionCallback cb);
698
+
699
+ /**
700
+ * hasThreadLocalCallbacks returns whether there're callbacks registered
701
+ * with addThreadLocalCallback
702
+ */
703
+ TORCH_API bool hasThreadLocalCallbacks();
704
+
705
+ /**
706
+ * clearThreadLocalCallbacks removes all thread local callbacks
707
+ */
708
+ TORCH_API void clearThreadLocalCallbacks();
709
+
710
+ /**
711
+ * addGlobalCallback adds a global callback to run with RecordFunction:
712
+ *
713
+ * only during the program initialization
714
+ */
715
+ TORCH_API CallbackHandle addGlobalCallback(RecordFunctionCallback cb);
716
+
717
+ /**
718
+ * removeCallback removes a callback given the handle returned by
719
+ * addThreadLocalCallback or addGlobalCallback;
720
+ *
721
+ * no other code can run simultaneously
722
+ */
723
+ TORCH_API void removeCallback(CallbackHandle handle);
724
+
725
+ /**
726
+ * Prevent the given callback from executing. If handle is invalid,
727
+ * does nothing.
728
+ */
729
+ TORCH_API void disableCallback(CallbackHandle handle);
730
+
731
+ /**
732
+ * Allow the given callback, previously disabled with disableCallback, to
733
+ * execute again. If handle is invalid, does nothing.
734
+ */
735
+ TORCH_API void reenableCallback(CallbackHandle handle);
736
+
737
+ /**
738
+ * hasGlobalCallbacks returns whether there're global callbacks
739
+ * registered with pushGlobalCallback
740
+ */
741
+ TORCH_API bool hasGlobalCallbacks();
742
+
743
+ /**
744
+ * clearGlobalCallbacks removes all global callbacks
745
+ */
746
+ TORCH_API void clearGlobalCallbacks();
747
+
748
+ // for both thread local and global callbacks
749
+ TORCH_API bool hasCallbacks();
750
+ TORCH_API void clearCallbacks();
751
+
752
+ /**
753
+ * enableRecordFunction enables RecordFunction thread locally
754
+ */
755
+ TORCH_API void enableRecordFunction(bool enable = true);
756
+
757
+ /**
758
+ * isRecordFunctionEnabled returns whether RecordFunction
759
+ * is enabled thread locally
760
+ */
761
+ TORCH_API bool isRecordFunctionEnabled();
762
+
763
+ class TORCH_API RecordFunctionGuard {
764
+ public:
765
+ explicit RecordFunctionGuard(bool is_enabled = true)
766
+ : prev_value_(isRecordFunctionEnabled()) {
767
+ enableRecordFunction(is_enabled);
768
+ }
769
+
770
+ RecordFunctionGuard(RecordFunctionGuard&& other) = delete;
771
+ RecordFunctionGuard(const RecordFunctionGuard&) = delete;
772
+ RecordFunctionGuard& operator=(const RecordFunctionGuard&) = delete;
773
+ RecordFunctionGuard& operator=(RecordFunctionGuard&&) = delete;
774
+ virtual ~RecordFunctionGuard() {
775
+ enableRecordFunction(prev_value_);
776
+ }
777
+
778
+ private:
779
+ bool prev_value_ = false;
780
+ };
781
+
782
+ class TORCH_API DisableRecordFunctionGuard : public RecordFunctionGuard {
783
+ public:
784
+ DisableRecordFunctionGuard() : RecordFunctionGuard(false) {}
785
+ ~DisableRecordFunctionGuard() override = default;
786
+ };
787
+
788
+ struct TORCH_API RecordFunctionTLS {
789
+ // Thread local vector of callbacks, holds pairs (callbacks, unique_id);
790
+ // must be sorted in increasing handles order
791
+ RecordFunctionCallbacks sorted_tls_callbacks_;
792
+
793
+ bool tls_record_function_enabled_ = true;
794
+ };
795
+
796
+ TORCH_API const RecordFunctionTLS& get_record_function_tls_();
797
+
798
+ TORCH_API void set_record_function_tls_(const RecordFunctionTLS& tls);
799
+
800
+ TORCH_API void set_record_function_seed_for_testing(uint32_t seed);
801
+
802
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/THC/THCAtomics.cuh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+ // TODO: Remove once torchvision has been updated to use the ATen header
3
+ #include <ATen/cuda/Atomic.cuh>
tool_server/.venv/lib/python3.12/site-packages/torch/include/THC/THCDeviceUtils.cuh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+ // TODO: Remove this header
3
+ #include <ATen/cuda/DeviceUtils.cuh>
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/AbstractConfig.h ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include <chrono>
12
+ #include <map>
13
+ #include <memory>
14
+ #include <string>
15
+ #include <vector>
16
+
17
+ namespace libkineto {
18
+
19
+ class AbstractConfig {
20
+ public:
21
+ AbstractConfig& operator=(const AbstractConfig&) = delete;
22
+ AbstractConfig(AbstractConfig&&) = delete;
23
+ AbstractConfig& operator=(AbstractConfig&&) = delete;
24
+
25
+ virtual ~AbstractConfig() {
26
+ for (const auto& p : featureConfigs_) {
27
+ delete p.second;
28
+ }
29
+ }
30
+
31
+ // Return a copy of the full derived class
32
+ virtual AbstractConfig* cloneDerived(AbstractConfig& parent) const = 0;
33
+
34
+ // Returns true if successfully parsed the config string
35
+ bool parse(const std::string& conf);
36
+
37
+ // Default setup for signal-triggered profiling
38
+ virtual void setSignalDefaults() {
39
+ for (auto& p : featureConfigs_) {
40
+ p.second->setSignalDefaults();
41
+ }
42
+ }
43
+
44
+ // Default setup for client-triggered profiling
45
+ virtual void setClientDefaults() {
46
+ for (auto& p : featureConfigs_) {
47
+ p.second->setClientDefaults();
48
+ }
49
+ }
50
+
51
+ // Time config was created / updated
52
+ std::chrono::time_point<std::chrono::system_clock> timestamp() const {
53
+ return timestamp_;
54
+ }
55
+
56
+ // Source config string that this was parsed from
57
+ const std::string& source() const {
58
+ return source_;
59
+ }
60
+
61
+ AbstractConfig& feature(std::string name) const {
62
+ const auto& pos = featureConfigs_.find(name);
63
+ return *pos->second;
64
+ }
65
+
66
+ // Transfers ownership of cfg arg
67
+ void addFeature(const std::string& name, AbstractConfig* cfg) {
68
+ featureConfigs_[name] = cfg;
69
+ }
70
+
71
+ protected:
72
+ AbstractConfig() {}
73
+ AbstractConfig(const AbstractConfig& other) = default;
74
+
75
+ // Return true if the option was recognized and successfully parsed.
76
+ // Throw std::invalid_argument if val is invalid.
77
+ virtual bool handleOption(const std::string& name, std::string& val);
78
+
79
+ // Perform post-validation checks, typically conditons involving
80
+ // multiple options.
81
+ // Throw std::invalid_argument if automatic correction can not be made.
82
+ //
83
+ // @param fallbackProfileStartTime Specify a fallback profile start timestamp
84
+ // in case it was never specified by the client
85
+ virtual void validate(
86
+ const std::chrono::time_point<std::chrono::system_clock>&
87
+ fallbackProfileStartTime) = 0;
88
+
89
+ // TODO: Separate out each profiler type into features?
90
+ virtual void printActivityProfilerConfig(std::ostream& s) const;
91
+ virtual void setActivityDependentConfig();
92
+
93
+ // Helpers for use in handleOption
94
+ // Split a string by delimiter and remove external white space
95
+ std::vector<std::string> splitAndTrim(const std::string& s, char delim) const;
96
+ // Lowercase for case-insensitive comparisons
97
+ std::string toLower(std::string& s) const;
98
+ // Does string end with suffix
99
+ bool endsWith(const std::string& s, const std::string& suffix) const;
100
+ // Conversions
101
+ int64_t toIntRange(const std::string& val, int64_t min, int64_t max) const;
102
+ int32_t toInt32(const std::string& val) const;
103
+ int64_t toInt64(const std::string& val) const;
104
+ bool toBool(std::string& val) const;
105
+
106
+ void cloneFeaturesInto(AbstractConfig& cfg) const {
107
+ for (const auto& feature : featureConfigs_) {
108
+ cfg.featureConfigs_[feature.first] = feature.second->cloneDerived(cfg);
109
+ }
110
+ }
111
+
112
+ private:
113
+ // Time config was created / updated
114
+ std::chrono::time_point<std::chrono::system_clock> timestamp_{};
115
+
116
+ // Original configuration string, used for comparison
117
+ std::string source_{""};
118
+
119
+ // Configuration objects for optional features
120
+ std::map<std::string, AbstractConfig*> featureConfigs_{};
121
+ };
122
+
123
+ } // namespace libkineto
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityProfilerInterface.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include <memory>
12
+ #include <set>
13
+ #include <thread>
14
+ #include <vector>
15
+
16
+ #include "ActivityTraceInterface.h"
17
+ #include "ActivityType.h"
18
+ #include "IActivityProfiler.h"
19
+
20
+ namespace libkineto {
21
+
22
+ class ActivityProfilerController;
23
+ struct CpuTraceBuffer;
24
+ class Config;
25
+
26
+ class ActivityProfilerInterface {
27
+ public:
28
+ virtual ~ActivityProfilerInterface() {}
29
+
30
+ virtual void init() {}
31
+ virtual bool isInitialized() {
32
+ return false;
33
+ }
34
+ virtual bool isActive() {
35
+ return false;
36
+ }
37
+
38
+ // *** Asynchronous API ***
39
+ // Instead of starting and stopping the trace manually, provide a start time
40
+ // and duration and / or iteration stop criterion.
41
+ // Tracing terminates when either condition is met.
42
+ virtual void scheduleTrace(const std::string& configStr) {}
43
+
44
+ // *** Synchronous API ***
45
+ // These must be called in order:
46
+ // prepareTrace -> startTrace -> stopTrace.
47
+
48
+ // Many tracing structures are lazily initialized during trace collection,
49
+ // with potentially high overhead.
50
+ // Call prepareTrace to enable tracing, then run the region to trace
51
+ // at least once (and ideally run the same code that is to be traced) to
52
+ // allow tracing structures to be initialized.
53
+ virtual void prepareTrace(
54
+ const std::set<ActivityType>& activityTypes,
55
+ const std::string& configStr = "") {}
56
+
57
+ // Toggle GPU tracing as a trace is running to omit certain parts of a graph
58
+ virtual void toggleCollectionDynamic(const bool enable) {}
59
+
60
+ // Start recording, potentially reusing any buffers allocated since
61
+ // prepareTrace was called.
62
+ virtual void startTrace() {}
63
+
64
+ // Stop and process trace, producing an in-memory list of trace records.
65
+ // The processing will be done synchronously (using the calling thread.)
66
+ virtual std::unique_ptr<ActivityTraceInterface> stopTrace() {
67
+ return nullptr;
68
+ }
69
+
70
+ // Re-evaluate internal state to allow for triggering operations based
71
+ // on number of iteration. each implicitly increments the iteration count
72
+ virtual void step() {}
73
+
74
+ // *** TraceActivity API ***
75
+ // FIXME: Pass activityProfiler interface into clientInterface?
76
+ virtual void pushCorrelationId(uint64_t id) {}
77
+ virtual void popCorrelationId() {}
78
+ virtual void transferCpuTrace(std::unique_ptr<CpuTraceBuffer> traceBuffer) {}
79
+
80
+ // Correlation ids for user defined spans
81
+ virtual void pushUserCorrelationId(uint64_t) {}
82
+ virtual void popUserCorrelationId() {}
83
+
84
+ // Saves information for the current thread to be used in profiler output
85
+ // Client must record any new kernel thread where the activity has occured.
86
+ virtual void recordThreadInfo() {}
87
+
88
+ // Record trace metadata, currently supporting only string key and values,
89
+ // values with the same key are overwritten
90
+ virtual void addMetadata(
91
+ const std::string& key,
92
+ const std::string& value) = 0;
93
+
94
+ // Add a child activity profiler, this enables frameworks in the application
95
+ // to enable custom framework events.
96
+ virtual void addChildActivityProfiler(
97
+ std::unique_ptr<IActivityProfiler> profiler) {}
98
+
99
+ // Log Invariant Violation to factories enabled. This helps record
100
+ // instances when the profiler behaves unexpectedly.
101
+ virtual void logInvariantViolation(
102
+ const std::string&,
103
+ const std::string&,
104
+ const std::string&,
105
+ const std::string& = "") {}
106
+ };
107
+
108
+ } // namespace libkineto
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityTraceInterface.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include <memory>
12
+ #include <string>
13
+ #include <vector>
14
+
15
+ namespace libkineto {
16
+
17
+ struct ITraceActivity;
18
+
19
+ class ActivityTraceInterface {
20
+ public:
21
+ virtual ~ActivityTraceInterface() {}
22
+ virtual const std::vector<const ITraceActivity*>* activities() {
23
+ return nullptr;
24
+ }
25
+ virtual void save(const std::string& path) {}
26
+ };
27
+
28
+ } // namespace libkineto
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ActivityType.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include <array>
12
+ #include <set>
13
+ #include <string>
14
+
15
+ namespace libkineto {
16
+
17
+ // Note : All activity types are not enabled by default. Please add them
18
+ // at correct position in the enum
19
+ enum class ActivityType {
20
+ // Activity types enabled by default
21
+ CPU_OP = 0, // cpu side ops
22
+ USER_ANNOTATION,
23
+ GPU_USER_ANNOTATION,
24
+ GPU_MEMCPY,
25
+ GPU_MEMSET,
26
+ CONCURRENT_KERNEL, // on-device kernels
27
+ EXTERNAL_CORRELATION,
28
+ CUDA_RUNTIME, // host side cuda runtime events
29
+ CUDA_DRIVER, // host side cuda driver events
30
+ CPU_INSTANT_EVENT, // host side point-like events
31
+ PYTHON_FUNCTION,
32
+ OVERHEAD, // CUPTI induced overhead events sampled from its overhead API.
33
+ MTIA_RUNTIME, // host side MTIA runtime events
34
+ MTIA_CCP_EVENTS, // MTIA ondevice CCP events
35
+ CUDA_SYNC, // synchronization events between runtime and kernels
36
+
37
+ // Optional Activity types
38
+ GLOW_RUNTIME, // host side glow runtime events
39
+ CUDA_PROFILER_RANGE, // CUPTI Profiler range for performance metrics
40
+ HPU_OP, // HPU host side runtime event
41
+ XPU_RUNTIME, // host side xpu runtime events
42
+ COLLECTIVE_COMM, // collective communication
43
+ MTIA_WORKLOADD, // MTIA workloadd events
44
+
45
+ // PRIVATEUSE1 Activity types are used for custom backends.
46
+ // The corresponding device type is `DeviceType::PrivateUse1` in PyTorch.
47
+ PRIVATEUSE1_RUNTIME, // host side privateUse1 runtime events
48
+ PRIVATEUSE1_DRIVER, // host side privateUse1 driver events
49
+
50
+ ENUM_COUNT, // This is to add buffer and not used for any profiling logic. Add
51
+ // your new type before it.
52
+ OPTIONAL_ACTIVITY_TYPE_START = GLOW_RUNTIME,
53
+ };
54
+
55
+ const char* toString(ActivityType t);
56
+ ActivityType toActivityType(const std::string& str);
57
+
58
+ // Return an array of all activity types except COUNT
59
+ constexpr int activityTypeCount = (int)ActivityType::ENUM_COUNT;
60
+ constexpr int defaultActivityTypeCount =
61
+ (int)ActivityType::OPTIONAL_ACTIVITY_TYPE_START;
62
+ const std::array<ActivityType, activityTypeCount> activityTypes();
63
+ const std::array<ActivityType, defaultActivityTypeCount> defaultActivityTypes();
64
+
65
+ } // namespace libkineto
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/ClientInterface.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ namespace libkineto {
12
+
13
+ class ClientInterface {
14
+ public:
15
+ virtual ~ClientInterface() {}
16
+ virtual void init() = 0;
17
+ virtual void prepare(bool, bool, bool, bool, bool) = 0;
18
+ virtual void start() = 0;
19
+ virtual void stop() = 0;
20
+ };
21
+
22
+ } // namespace libkineto
tool_server/.venv/lib/python3.12/site-packages/torch/include/kineto/Config.h ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include "AbstractConfig.h"
12
+ #include "ActivityType.h"
13
+
14
+ #include <assert.h>
15
+ #include <chrono>
16
+ #include <functional>
17
+ #include <set>
18
+ #include <string>
19
+ #include <vector>
20
+
21
+ namespace libkineto {
22
+
23
+ class Config : public AbstractConfig {
24
+ public:
25
+ Config();
26
+ Config& operator=(const Config&) = delete;
27
+ Config(Config&&) = delete;
28
+ Config& operator=(Config&&) = delete;
29
+
30
+ // Return a full copy including feature config object
31
+ std::unique_ptr<Config> clone() const {
32
+ auto cfg = std::unique_ptr<Config>(new Config(*this));
33
+ cloneFeaturesInto(*cfg);
34
+ return cfg;
35
+ }
36
+
37
+ bool handleOption(const std::string& name, std::string& val) override;
38
+
39
+ void setClientDefaults() override;
40
+
41
+ // Log events to this file
42
+ const std::string& eventLogFile() const {
43
+ return eventLogFile_;
44
+ }
45
+
46
+ bool activityProfilerEnabled() const {
47
+ return activityProfilerEnabled_ ||
48
+ activitiesOnDemandTimestamp_.time_since_epoch().count() > 0;
49
+ }
50
+
51
+ // Log activitiy trace to this file
52
+ const std::string& activitiesLogFile() const {
53
+ return activitiesLogFile_;
54
+ }
55
+
56
+ // Log activitiy trace to this url
57
+ const std::string& activitiesLogUrl() const {
58
+ return activitiesLogUrl_;
59
+ }
60
+
61
+ void setActivitiesLogUrl(const std::string& url) {
62
+ activitiesLogUrl_ = url;
63
+ }
64
+
65
+ bool activitiesLogToMemory() const {
66
+ return activitiesLogToMemory_;
67
+ }
68
+
69
+ bool eventProfilerEnabled() const {
70
+ return !eventNames_.empty() || !metricNames_.empty();
71
+ }
72
+
73
+ // Is profiling enabled for the given device?
74
+ bool eventProfilerEnabledForDevice(uint32_t dev) const {
75
+ return 0 != (eventProfilerDeviceMask_ & (1 << dev));
76
+ }
77
+
78
+ // Take a sample (read hardware counters) at this frequency.
79
+ // This controls how often counters are read - if all counters cannot
80
+ // be collected simultaneously then multiple samples are needed to
81
+ // collect all requested counters - see multiplex period.
82
+ std::chrono::milliseconds samplePeriod() const {
83
+ return samplePeriod_;
84
+ }
85
+
86
+ void setSamplePeriod(std::chrono::milliseconds period) {
87
+ samplePeriod_ = period;
88
+ }
89
+
90
+ // When all requested counters cannot be collected simultaneously,
91
+ // counters will be multiplexed at this frequency.
92
+ // Multiplexing can have a large performance impact if done frequently.
93
+ // To avoid a perf impact, keep this at 1s or above.
94
+ std::chrono::milliseconds multiplexPeriod() const {
95
+ return multiplexPeriod_;
96
+ }
97
+
98
+ void setMultiplexPeriod(std::chrono::milliseconds period) {
99
+ multiplexPeriod_ = period;
100
+ }
101
+
102
+ // Report counters at this frequency. Note that several samples can
103
+ // be reported each time, see samplesPerReport.
104
+ std::chrono::milliseconds reportPeriod() const {
105
+ return reportPeriod_;
106
+ }
107
+
108
+ void setReportPeriod(std::chrono::milliseconds msecs);
109
+
110
+ // Number of samples dispatched each report period.
111
+ // Must be in the range [1, report period / sample period].
112
+ // In other words, aggregation is supported but not interpolation.
113
+ int samplesPerReport() const {
114
+ return samplesPerReport_;
115
+ }
116
+
117
+ void setSamplesPerReport(int count) {
118
+ samplesPerReport_ = count;
119
+ }
120
+
121
+ // The names of events to collect
122
+ const std::set<std::string>& eventNames() const {
123
+ return eventNames_;
124
+ }
125
+
126
+ // Add additional events to be profiled
127
+ void addEvents(const std::set<std::string>& names) {
128
+ eventNames_.insert(names.begin(), names.end());
129
+ }
130
+
131
+ // The names of metrics to collect
132
+ const std::set<std::string>& metricNames() const {
133
+ return metricNames_;
134
+ }
135
+
136
+ // Add additional metrics to be profiled
137
+ void addMetrics(const std::set<std::string>& names) {
138
+ metricNames_.insert(names.begin(), names.end());
139
+ }
140
+
141
+ const std::vector<int>& percentiles() const {
142
+ return eventReportPercentiles_;
143
+ }
144
+
145
+ // Profile for this long, then revert to base config
146
+ std::chrono::seconds eventProfilerOnDemandDuration() const {
147
+ return eventProfilerOnDemandDuration_;
148
+ }
149
+
150
+ void setEventProfilerOnDemandDuration(std::chrono::seconds duration) {
151
+ eventProfilerOnDemandDuration_ = duration;
152
+ }
153
+
154
+ // Too many event profilers on a single system can overload the driver.
155
+ // At some point, latencies shoot through the roof and collection of samples
156
+ // becomes impossible. To avoid this situation we have a limit of profilers
157
+ // per GPU.
158
+ // NOTE: Communication with a daemon is needed for this feature.
159
+ // Library must be built with an active DaemonConfigLoader.
160
+ int maxEventProfilersPerGpu() const {
161
+ return eventProfilerMaxInstancesPerGpu_;
162
+ }
163
+
164
+ // On Cuda11 we've seen occasional hangs when reprogramming counters
165
+ // Monitor profiling threads and report when a thread is not responding
166
+ // for a given number of seconds.
167
+ // A period of 0 means disable.
168
+ std::chrono::seconds eventProfilerHeartbeatMonitorPeriod() const {
169
+ return eventProfilerHeartbeatMonitorPeriod_;
170
+ }
171
+
172
+ // The types of activities selected in the configuration file
173
+ const std::set<ActivityType>& selectedActivityTypes() const {
174
+ return selectedActivityTypes_;
175
+ }
176
+
177
+ // Set the types of activities to be traced
178
+ bool perThreadBufferEnabled() const {
179
+ return perThreadBufferEnabled_;
180
+ }
181
+
182
+ void setSelectedActivityTypes(const std::set<ActivityType>& types) {
183
+ selectedActivityTypes_ = types;
184
+ }
185
+
186
+ bool isReportInputShapesEnabled() const {
187
+ return enableReportInputShapes_;
188
+ }
189
+
190
+ bool isProfileMemoryEnabled() const {
191
+ return enableProfileMemory_;
192
+ }
193
+
194
+ bool isWithStackEnabled() const {
195
+ return enableWithStack_;
196
+ }
197
+
198
+ bool isWithFlopsEnabled() const {
199
+ return enableWithFlops_;
200
+ }
201
+
202
+ bool isWithModulesEnabled() const {
203
+ return enableWithModules_;
204
+ }
205
+
206
+ // Trace for this long
207
+ std::chrono::milliseconds activitiesDuration() const {
208
+ return activitiesDuration_;
209
+ }
210
+
211
+ // Trace for this many iterations, determined by external API
212
+ int activitiesRunIterations() const {
213
+ return activitiesRunIterations_;
214
+ }
215
+
216
+ int activitiesMaxGpuBufferSize() const {
217
+ return activitiesMaxGpuBufferSize_;
218
+ }
219
+
220
+ std::chrono::seconds activitiesWarmupDuration() const {
221
+ return activitiesWarmupDuration_;
222
+ }
223
+
224
+ int activitiesWarmupIterations() const {
225
+ return activitiesWarmupIterations_;
226
+ }
227
+
228
+ // Show CUDA Synchronization Stream Wait Events
229
+ bool activitiesCudaSyncWaitEvents() const {
230
+ return activitiesCudaSyncWaitEvents_;
231
+ }
232
+
233
+ void setActivitiesCudaSyncWaitEvents(bool enable) {
234
+ activitiesCudaSyncWaitEvents_ = enable;
235
+ }
236
+
237
+ // Timestamp at which the profiling to start, requested by the user.
238
+ const std::chrono::time_point<std::chrono::system_clock> requestTimestamp()
239
+ const {
240
+ if (profileStartTime_.time_since_epoch().count()) {
241
+ return profileStartTime_;
242
+ }
243
+ // If no one requested timestamp, return 0.
244
+ if (requestTimestamp_.time_since_epoch().count() == 0) {
245
+ return requestTimestamp_;
246
+ }
247
+
248
+ // TODO(T94634890): Deprecate requestTimestamp
249
+ return requestTimestamp_ + maxRequestAge() + activitiesWarmupDuration();
250
+ }
251
+
252
+ bool hasProfileStartTime() const {
253
+ return requestTimestamp_.time_since_epoch().count() > 0 ||
254
+ profileStartTime_.time_since_epoch().count() > 0;
255
+ }
256
+
257
+ int profileStartIteration() const {
258
+ return profileStartIteration_;
259
+ }
260
+
261
+ bool hasProfileStartIteration() const {
262
+ return profileStartIteration_ >= 0 && activitiesRunIterations_ > 0;
263
+ }
264
+
265
+ void setProfileStartIteration(int iter) {
266
+ profileStartIteration_ = iter;
267
+ }
268
+
269
+ int profileStartIterationRoundUp() const {
270
+ return profileStartIterationRoundUp_;
271
+ }
272
+
273
+ // calculate the start iteration accounting for warmup
274
+ int startIterationIncludingWarmup() const {
275
+ if (!hasProfileStartIteration()) {
276
+ return -1;
277
+ }
278
+ return profileStartIteration_ - activitiesWarmupIterations_;
279
+ }
280
+
281
+ const std::chrono::seconds maxRequestAge() const;
282
+
283
+ // All VLOG* macros will log if the verbose log level is >=
284
+ // the verbosity specified for the verbose log message.
285
+ // Default value is -1, so messages with log level 0 will log by default.
286
+ int verboseLogLevel() const {
287
+ return verboseLogLevel_;
288
+ }
289
+
290
+ // Modules for which verbose logging is enabled.
291
+ // If empty, logging is enabled for all modules.
292
+ const std::vector<std::string>& verboseLogModules() const {
293
+ return verboseLogModules_;
294
+ }
295
+
296
+ bool sigUsr2Enabled() const {
297
+ return enableSigUsr2_;
298
+ }
299
+
300
+ bool ipcFabricEnabled() const {
301
+ return enableIpcFabric_;
302
+ }
303
+
304
+ std::chrono::seconds onDemandConfigUpdateIntervalSecs() const {
305
+ return onDemandConfigUpdateIntervalSecs_;
306
+ }
307
+
308
+ static std::chrono::milliseconds alignUp(
309
+ std::chrono::milliseconds duration,
310
+ std::chrono::milliseconds alignment) {
311
+ duration += alignment;
312
+ return duration - (duration % alignment);
313
+ }
314
+
315
+ std::chrono::time_point<std::chrono::system_clock>
316
+ eventProfilerOnDemandStartTime() const {
317
+ return eventProfilerOnDemandTimestamp_;
318
+ }
319
+
320
+ std::chrono::time_point<std::chrono::system_clock>
321
+ eventProfilerOnDemandEndTime() const {
322
+ return eventProfilerOnDemandTimestamp_ + eventProfilerOnDemandDuration_;
323
+ }
324
+
325
+ std::chrono::time_point<std::chrono::system_clock>
326
+ activityProfilerRequestReceivedTime() const {
327
+ return activitiesOnDemandTimestamp_;
328
+ }
329
+
330
+ static constexpr std::chrono::milliseconds kControllerIntervalMsecs{1000};
331
+
332
+ // Users may request and set trace id and group trace id.
333
+ const std::string& requestTraceID() const {
334
+ return requestTraceID_;
335
+ }
336
+
337
+ void setRequestTraceID(const std::string& tid) {
338
+ requestTraceID_ = tid;
339
+ }
340
+
341
+ const std::string& requestGroupTraceID() const {
342
+ return requestGroupTraceID_;
343
+ }
344
+
345
+ void setRequestGroupTraceID(const std::string& gtid) {
346
+ requestGroupTraceID_ = gtid;
347
+ }
348
+
349
+ size_t cuptiDeviceBufferSize() const {
350
+ return cuptiDeviceBufferSize_;
351
+ }
352
+
353
+ size_t cuptiDeviceBufferPoolLimit() const {
354
+ return cuptiDeviceBufferPoolLimit_;
355
+ }
356
+
357
+ void updateActivityProfilerRequestReceivedTime();
358
+
359
+ void printActivityProfilerConfig(std::ostream& s) const override;
360
+ void setActivityDependentConfig() override;
361
+
362
+ void validate(const std::chrono::time_point<std::chrono::system_clock>&
363
+ fallbackProfileStartTime) override;
364
+
365
+ static void addConfigFactory(
366
+ std::string name,
367
+ std::function<AbstractConfig*(Config&)> factory);
368
+
369
+ void print(std::ostream& s) const;
370
+
371
+ // Config relies on some state with global static lifetime. If other
372
+ // threads are using the config, it's possible that the global state
373
+ // is destroyed before the threads stop. By hanging onto this handle,
374
+ // correct destruction order can be ensured.
375
+ static std::shared_ptr<void> getStaticObjectsLifetimeHandle();
376
+
377
+ bool getTSCTimestampFlag() const {
378
+ return useTSCTimestamp_;
379
+ }
380
+
381
+ void setTSCTimestampFlag(bool flag) {
382
+ useTSCTimestamp_ = flag;
383
+ }
384
+
385
+ private:
386
+ explicit Config(const Config& other) = default;
387
+
388
+ AbstractConfig* cloneDerived(AbstractConfig& parent) const override {
389
+ // Clone from AbstractConfig not supported
390
+ assert(false);
391
+ return nullptr;
392
+ }
393
+
394
+ uint8_t createDeviceMask(const std::string& val);
395
+
396
+ // Adds valid activity types from the user defined string list in the
397
+ // configuration file
398
+ void setActivityTypes(const std::vector<std::string>& selected_activities);
399
+
400
+ // Sets the default activity types to be traced
401
+ void selectDefaultActivityTypes() {
402
+ // If the user has not specified an activity list, add all types
403
+ for (ActivityType t : defaultActivityTypes()) {
404
+ selectedActivityTypes_.insert(t);
405
+ }
406
+ }
407
+
408
+ int verboseLogLevel_;
409
+ std::vector<std::string> verboseLogModules_;
410
+
411
+ // Event profiler
412
+ // These settings are also supported in on-demand mode
413
+ std::chrono::milliseconds samplePeriod_;
414
+ std::chrono::milliseconds reportPeriod_;
415
+ int samplesPerReport_;
416
+ std::set<std::string> eventNames_;
417
+ std::set<std::string> metricNames_;
418
+
419
+ // On-demand duration
420
+ std::chrono::seconds eventProfilerOnDemandDuration_;
421
+ // Last on-demand request
422
+ std::chrono::time_point<std::chrono::system_clock>
423
+ eventProfilerOnDemandTimestamp_;
424
+
425
+ int eventProfilerMaxInstancesPerGpu_;
426
+
427
+ // Monitor whether event profiler threads are stuck
428
+ // at this frequency
429
+ std::chrono::seconds eventProfilerHeartbeatMonitorPeriod_;
430
+
431
+ // These settings can not be changed on-demand
432
+ std::string eventLogFile_;
433
+ std::vector<int> eventReportPercentiles_ = {5, 25, 50, 75, 95};
434
+ uint8_t eventProfilerDeviceMask_ = ~0;
435
+ std::chrono::milliseconds multiplexPeriod_;
436
+
437
+ // Activity profiler
438
+ bool activityProfilerEnabled_;
439
+
440
+ // Enable per-thread buffer
441
+ bool perThreadBufferEnabled_;
442
+ std::set<ActivityType> selectedActivityTypes_;
443
+
444
+ // The activity profiler settings are all on-demand
445
+ std::string activitiesLogFile_;
446
+
447
+ std::string activitiesLogUrl_;
448
+
449
+ // Log activities to memory buffer
450
+ bool activitiesLogToMemory_{false};
451
+
452
+ int activitiesMaxGpuBufferSize_;
453
+ std::chrono::seconds activitiesWarmupDuration_;
454
+ int activitiesWarmupIterations_;
455
+ bool activitiesCudaSyncWaitEvents_;
456
+
457
+ // Enable Profiler Config Options
458
+ // Temporarily disable shape collection until we re-roll out the feature for
459
+ // on-demand cases
460
+ bool enableReportInputShapes_{false};
461
+ bool enableProfileMemory_{false};
462
+ bool enableWithStack_{false};
463
+ bool enableWithFlops_{false};
464
+ bool enableWithModules_{false};
465
+
466
+ // Profile for specified iterations and duration
467
+ std::chrono::milliseconds activitiesDuration_;
468
+ int activitiesRunIterations_;
469
+
470
+ // Below are not used
471
+ // Use this net name for iteration count
472
+ std::string activitiesExternalAPIIterationsTarget_;
473
+ // Only profile nets that includes this in the name
474
+ std::vector<std::string> activitiesExternalAPIFilter_;
475
+ // Only profile nets with at least this many operators
476
+ int activitiesExternalAPINetSizeThreshold_;
477
+ // Only profile nets with at least this many GPU operators
478
+ int activitiesExternalAPIGpuOpCountThreshold_;
479
+ // Last activity profiler request
480
+ std::chrono::time_point<std::chrono::system_clock>
481
+ activitiesOnDemandTimestamp_;
482
+
483
+ // ActivityProfilers are triggered by either:
484
+ // Synchronized start timestamps
485
+ std::chrono::time_point<std::chrono::system_clock> profileStartTime_;
486
+ // Or start iterations.
487
+ int profileStartIteration_;
488
+ int profileStartIterationRoundUp_;
489
+
490
+ // DEPRECATED
491
+ std::chrono::time_point<std::chrono::system_clock> requestTimestamp_;
492
+
493
+ // Enable profiling via SIGUSR2
494
+ bool enableSigUsr2_;
495
+
496
+ // Enable IPC Fabric instead of thrift communication
497
+ bool enableIpcFabric_;
498
+ std::chrono::seconds onDemandConfigUpdateIntervalSecs_;
499
+
500
+ // Logger Metadata
501
+ std::string requestTraceID_;
502
+ std::string requestGroupTraceID_;
503
+
504
+ // CUPTI Device Buffer
505
+ size_t cuptiDeviceBufferSize_;
506
+ size_t cuptiDeviceBufferPoolLimit_;
507
+
508
+ // CUPTI Timestamp Format
509
+ bool useTSCTimestamp_{true};
510
+ };
511
+
512
+ constexpr char kUseDaemonEnvVar[] = "KINETO_USE_DAEMON";
513
+
514
+ bool isDaemonEnvVarSet();
515
+
516
+ } // namespace libkineto