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

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/core/interned_strings.h +355 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/interned_strings_class.h +32 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue.h +1589 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue_inl.h +2569 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue_to.h +36 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/jit_type.h +2437 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/jit_type_base.h +721 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/operator_name.h +98 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/qualified_name.h +161 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/rref_interface.h +41 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/stack.h +204 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/symbol.h +147 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/type_factory.h +108 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/type_ptr.h +54 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/typeid.h +1 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/FlushDenormal.h +14 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/Utils.h +33 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/vml.h +170 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ATenCUDAGeneral.h +9 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ApplyGridUtils.cuh +47 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/AsmUtils.cuh +149 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Atomic.cuh +514 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAApplyUtils.cuh +537 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDABlas.h +360 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAConfig.h +19 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAContext.h +9 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAContextLight.h +99 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDADataType.h +98 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDADevice.h +23 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAEvent.h +211 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h +180 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGraph.h +86 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh +53 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparse.h +75 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparseBlas.h +320 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h +288 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh +15 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAUtils.h +20 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CachingHostAllocator.h +42 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh +121 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/EmptyTensor.h +44 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Exceptions.h +234 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/NumericLimits.cuh +121 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PeerToPeerAccess.h +12 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PhiloxCudaState.h +5 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PhiloxUtils.cuh +4 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PinnedMemoryAllocator.h +11 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ScanUtils.cuh +78 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Sleep.h +13 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ThrustAllocator.h +23 -0
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/interned_strings.h ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ #include <ATen/core/aten_interned_strings.h>
6
+ #include <ATen/core/symbol.h>
7
+
8
+ namespace c10 {
9
+
10
+ #define FORALL_NS_SYMBOLS(_) \
11
+ _(namespaces, prim) \
12
+ _(namespaces, prims) \
13
+ _(namespaces, nvprims) \
14
+ _(namespaces, aten) \
15
+ _(namespaces, cuda) \
16
+ _(namespaces, onnx) \
17
+ _(namespaces, attr) \
18
+ _(namespaces, scope) \
19
+ _(namespaces, user) \
20
+ _(namespaces, _caffe2) \
21
+ _(namespaces, dimname) \
22
+ _(namespaces, namespaces) \
23
+ _(prim, Assign) \
24
+ _(prim, BroadcastingChunk) \
25
+ _(prim, BroadcastSizes) \
26
+ _(prim, ReductionSizes) \
27
+ _(prim, Constant) \
28
+ _(prim, ChunkSizes) \
29
+ _(prim, ConstantMKLDNNTensor) \
30
+ _(prim, BroadcastMKLDNNTensors) \
31
+ _(prim, MKLDNNGroup) \
32
+ _(prim, MKLDNNHardSwish) \
33
+ _(prim, MKLDNNHardSigmoid) \
34
+ _(prim, MKLDNNHardTanh) \
35
+ _(prim, MKLDNNClamp) \
36
+ _(prim, StaticRuntimeCopyOuts) \
37
+ _(prim, Drop) \
38
+ _(prim, Eval) \
39
+ _(prim, Expand) /* onnx */ \
40
+ _(prim, FusionGroup) \
41
+ _(prim, CudaFusionGroup) \
42
+ _(prim, CudaFusionGuard) \
43
+ _(prim, oneDNNFusionGroup) \
44
+ _(prim, oneDNNFusionGuard) \
45
+ _(prim, FunctionalGraph) \
46
+ _(prim, add_optional) \
47
+ _(prim, view_copy) \
48
+ _(prim, permute_copy) \
49
+ _(prim, reshape_copy) \
50
+ _(prim, squeeze_copy) \
51
+ _(prim, t_copy) \
52
+ _(prim, transpose_copy) \
53
+ _(prim, unsqueeze_copy) \
54
+ _(prim, flatten_copy) \
55
+ _(prim, expand_copy) \
56
+ _(prim, expand_as_copy) \
57
+ _(prim, DifferentiableGraph) \
58
+ _(prim, TensorExprGroup) \
59
+ _(prim, TensorExprDynamicGroup) \
60
+ _(prim, StaticSubgraph) \
61
+ _(prim, If) \
62
+ _(prim, Jump) /* debug */ \
63
+ _(prim, JumpNZ) /* debug */ \
64
+ _(prim, JumpZ) /* debug */ \
65
+ _(prim, Load) \
66
+ _(prim, Loop) \
67
+ _(prim, Param) \
68
+ _(prim, PackPadded) /* onnx */ \
69
+ _(prim, PadPacked) /* onnx */ \
70
+ _(prim, Placeholder) /* debug */ \
71
+ _(prim, Print) \
72
+ _(prim, EmptyListLiteral) \
73
+ _(prim, LegacyTypedConstructor) \
74
+ _(prim, PythonOp) \
75
+ _(prim, IgnoredPythonOp) \
76
+ _(prim, Reverse) \
77
+ _(prim, Return) \
78
+ _(prim, ReturnStmt) \
79
+ _(prim, BreakStmt) \
80
+ _(prim, ContinueStmt) \
81
+ _(prim, ComprehensionScope) \
82
+ _(prim, Store) \
83
+ _(prim, AutogradZero) \
84
+ _(prim, AutogradAnyNonZero) \
85
+ _(prim, AutogradAllNonZero) \
86
+ _(prim, AutogradAllZero) \
87
+ _(prim, Starred) \
88
+ _(prim, TupleConstruct) \
89
+ _(prim, TupleUnpack) \
90
+ _(prim, TupleIndex) \
91
+ _(prim, TupleSlice) \
92
+ _(prim, ListConstruct) \
93
+ _(prim, ListUnpack) \
94
+ _(prim, DictConstruct) \
95
+ _(prim, ModuleContainerIndex) \
96
+ _(prim, EnumName) \
97
+ _(prim, EnumValue) \
98
+ _(prim, StringIndex) \
99
+ _(prim, NumToTensor) \
100
+ _(prim, Uninitialized) \
101
+ _(prim, VarConcat) \
102
+ _(prim, VarStack) \
103
+ _(prim, With) \
104
+ _(prim, Enter) \
105
+ _(prim, Exit) \
106
+ _(prim, IfThenElse) \
107
+ _(aten, Bool) \
108
+ _(aten, Int) \
109
+ _(aten, FloatImplicit) \
110
+ _(aten, ComplexImplicit) \
111
+ _(aten, IntImplicit) \
112
+ _(aten, ScalarImplicit) \
113
+ _(aten, Float) \
114
+ _(aten, Complex) \
115
+ _(aten, str) \
116
+ _(aten, Delete) \
117
+ _(prim, device) \
118
+ _(prim, dtype) \
119
+ _(prim, layout) \
120
+ _(prim, id) \
121
+ _(prim, requires_grad) \
122
+ _(prim, MakeTestTensor) /* test */ \
123
+ _(prim, AutogradAdd) \
124
+ _(prim, GradOf) \
125
+ _(aten, grad) \
126
+ _(aten, backward) \
127
+ _(prim, Guard) \
128
+ _(prim, BailOut) \
129
+ _(prim, TypeCheck) \
130
+ _(prim, RequiresGradCheck) \
131
+ _(prim, FallbackGraph) \
132
+ _(prim, FusedConcat) \
133
+ _(prim, ConstantChunk) \
134
+ _(prim, MMTreeReduce) \
135
+ _(prim, MMBatchSide) \
136
+ _(prim, list) \
137
+ _(prim, dict) \
138
+ _(prim, min) \
139
+ _(prim, max) \
140
+ _(prim, abs) \
141
+ _(aten, divmod) \
142
+ _(prim, zip) \
143
+ _(prim, enumerate) \
144
+ _(prim, range) \
145
+ _(prim, rangelist) \
146
+ _(prim, isinstance) \
147
+ _(prim, tolist) \
148
+ _(prim, unchecked_cast) \
149
+ _(aten, _grad_sum_to_size) \
150
+ _(aten, _size_if_not_equal) \
151
+ _(aten, _ncf_unsqueeze) \
152
+ _(aten, warn) \
153
+ _(aten, sorted) \
154
+ _(aten, floordiv) \
155
+ _(aten, __range_length) \
156
+ _(aten, __derive_index) \
157
+ _(aten, __round_to_zero_floordiv) \
158
+ _(aten, is_scripting) \
159
+ _(aten, _unwrap_optional) \
160
+ _(prim, fork) \
161
+ _(prim, awaitable) \
162
+ _(prim, forkClosure) \
163
+ _(prim, awaitableClosure) \
164
+ _(prim, awaitable_nowait) \
165
+ _(prim, awaitable_wait) \
166
+ _(prim, RaiseException) \
167
+ _(prim, Closure) \
168
+ _(prim, CreateObject) \
169
+ _(prim, SetAttr) \
170
+ _(prim, GetAttr) \
171
+ _(prim, HasAttr) \
172
+ _(prim, profile) \
173
+ _(prim, profile_ivalue) \
174
+ _(prim, AddStatValue) \
175
+ _(prim, TimePoint) \
176
+ _(prim, CallFunction) \
177
+ _(prim, CallMethod) \
178
+ _(prim, LoopContinuation) \
179
+ _(prim, annotate) \
180
+ _(prim, TracedModuleForward) \
181
+ _(prim, TracedFork) \
182
+ _(prim, TracedAttr) \
183
+ _(prim, rpc_async) \
184
+ _(prim, rpc_sync) \
185
+ _(prim, rpc_remote) \
186
+ _(prim, is_cuda) \
187
+ _(aten, append) \
188
+ _(aten, as_tensor) \
189
+ _(aten, adaptive_avg_pool2d_backward) \
190
+ _(aten, dim) \
191
+ _(aten, format) \
192
+ _(aten, percentFormat) \
193
+ _(aten, __not__) \
194
+ _(aten, __is__) \
195
+ _(aten, __isnot__) \
196
+ _(aten, _ger) \
197
+ _(aten, __getitem__) \
198
+ _(aten, _set_item) \
199
+ _(aten, manual_seed) \
200
+ _(aten, device) \
201
+ _(aten, hash) \
202
+ _(aten, len) \
203
+ _(aten, list) \
204
+ _(aten, dict) \
205
+ _(aten, wait) \
206
+ _(aten, save) \
207
+ _(aten, keys) \
208
+ _(aten, ord) \
209
+ _(aten, chr) \
210
+ _(aten, hex) \
211
+ _(aten, oct) \
212
+ _(aten, clear) \
213
+ _(aten, setdefault) \
214
+ _(aten, bin) \
215
+ _(aten, pop) \
216
+ _(aten, insert) \
217
+ _(aten, tensor) \
218
+ _(prim, unchecked_unwrap_optional) \
219
+ _(aten, __contains__) \
220
+ _(prim, BailoutTemplate) \
221
+ _(prim, grad) \
222
+ _(cuda, _set_device) \
223
+ _(cuda, set_stream) \
224
+ _(cuda, _current_device) \
225
+ _(cuda, synchronize) \
226
+ _(aten, has_torch_function) \
227
+ _(aten, is_autocast_enabled) \
228
+ _(aten, is_autocast_cpu_enabled) \
229
+ _(aten, is_autocast_xla_enabled) \
230
+ _(aten, get_autocast_dtype) \
231
+ _(aten, is_autocast_mps_enabled) \
232
+ FORALL_ATEN_BASE_SYMBOLS(_) \
233
+ _(onnx, Add) \
234
+ _(onnx, Concat) \
235
+ _(onnx, Constant) \
236
+ _(onnx, ConstantFill) \
237
+ _(onnx, Div) \
238
+ _(onnx, GRU) \
239
+ _(onnx, Gather) \
240
+ _(onnx, Gemm) \
241
+ _(onnx, LSTM) \
242
+ _(onnx, MatMul) \
243
+ _(onnx, Min) \
244
+ _(onnx, Max) \
245
+ _(onnx, Mul) \
246
+ _(onnx, Pow) \
247
+ _(onnx, RNN) \
248
+ _(onnx, Shape) \
249
+ _(onnx, Size) \
250
+ _(onnx, Slice) \
251
+ _(onnx, Softmax) \
252
+ _(onnx, Squeeze) \
253
+ _(onnx, Sub) \
254
+ _(onnx, Transpose) \
255
+ _(onnx, Unsqueeze) \
256
+ _(onnx, Loop) \
257
+ _(onnx, If) \
258
+ _(onnx, Reshape) \
259
+ _(onnx, Expand) \
260
+ _(onnx, Equal) \
261
+ _(onnx, Greater) \
262
+ _(onnx, GreaterOrEqual) \
263
+ _(onnx, Less) \
264
+ _(onnx, LessOrEqual) \
265
+ _(onnx, Not) \
266
+ _(aten, ATen) \
267
+ _(onnx, Split) \
268
+ _(onnx, ConstantOfShape) \
269
+ _(onnx, Cast) \
270
+ _(onnx, Mod) \
271
+ _(onnx, Sqrt) \
272
+ _(onnx, SplitToSequence) \
273
+ _(onnx, SequenceAt) \
274
+ _(onnx, SequenceConstruct) \
275
+ _(onnx, SequenceEmpty) \
276
+ _(onnx, SequenceInsert) \
277
+ _(onnx, SequenceErase) \
278
+ _(onnx, ConcatFromSequence) \
279
+ _(onnx, Identity) \
280
+ _(onnx, SoftmaxCrossEntropyLoss) \
281
+ _(onnx, NegativeLogLikelihoodLoss) \
282
+ _(onnx, LogSoftmax) \
283
+ _(onnx, ReduceL1) \
284
+ _(onnx, ReduceL2) \
285
+ _(onnx, Conv) \
286
+ _(onnx, BatchNormalization) \
287
+ _(onnx, ReduceMean) \
288
+ _(onnx, ReduceProd) \
289
+ _(onnx, Relu) \
290
+ _(onnx, Neg) \
291
+ _(onnx, NonZero) \
292
+ _(onnx, Range) \
293
+ _(onnx, Tile) \
294
+ _(onnx, Where) \
295
+ _(onnx, Optional) \
296
+ _(onnx, OptionalGetElement) \
297
+ _(onnx, OptionalHasElement) \
298
+ FORALL_ATTR_BASE_SYMBOLS(_) \
299
+ _(attr, Subgraph) \
300
+ _(attr, ReverseSubgraph) \
301
+ _(attr, f_real_outputs) \
302
+ _(attr, df_input_vjps) \
303
+ _(attr, df_input_captured_inputs) \
304
+ _(attr, df_input_captured_outputs) \
305
+ _(attr, df_output_vjps) \
306
+ _(attr, axes) \
307
+ _(attr, symbolic_shape_inputs) \
308
+ _(attr, allow_stack_outputs) \
309
+ _(attr, striding_inputs_desc) \
310
+ _(attr, striding_outputs_desc) \
311
+ _(attr, broadcast) \
312
+ _(attr, direction) \
313
+ _(attr, ends) \
314
+ _(attr, inplace) \
315
+ _(attr, input_as_shape) \
316
+ _(attr, is_zero) \
317
+ _(attr, num_none) \
318
+ _(attr, num_present) \
319
+ _(attr, perm) \
320
+ _(attr, starts) \
321
+ _(attr, profiled_type) \
322
+ _(attr, transA) \
323
+ _(attr, transB) \
324
+ _(attr, name) \
325
+ _(attr, module) \
326
+ _(attr, beg) \
327
+ _(attr, idx) \
328
+ _(attr, split) \
329
+ _(attr, slot) \
330
+ _(attr, kinds) \
331
+ _(attr, types) \
332
+ _(attr, scope) \
333
+ _(attr, keepdims) \
334
+ _(attr, cache_id) \
335
+ _(attr, new_axis) \
336
+ _(attr, warn_id) \
337
+ _(attr, output_layouts) \
338
+ _(attr, allowzero) \
339
+ _(attr, seen_none) \
340
+ _(attr, overload_name) \
341
+ _(attr, node_stack_idx)
342
+
343
+ enum class _keys : unique_t {
344
+ #define DEFINE_KEY(ns, s) ns##_##s,
345
+ FORALL_NS_SYMBOLS(DEFINE_KEY)
346
+ #undef DEFINE_KEY
347
+ num_symbols
348
+ };
349
+
350
+ #define DEFINE_SYMBOL(ns, s) \
351
+ namespace ns { constexpr Symbol s(static_cast<unique_t>(_keys::ns##_##s)); }
352
+ FORALL_NS_SYMBOLS(DEFINE_SYMBOL)
353
+ #undef DEFINE_SYMBOL
354
+
355
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/interned_strings_class.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <mutex>
2
+ #include <string>
3
+ #include <unordered_map>
4
+ #include <vector>
5
+ #include <ATen/core/symbol.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ namespace c10 {
9
+
10
+ struct TORCH_API InternedStrings {
11
+ InternedStrings();
12
+ Symbol symbol(const std::string& s);
13
+ std::pair<const char*, const char*> string(Symbol sym);
14
+ Symbol ns(Symbol sym);
15
+
16
+ private:
17
+ // prereq - holding mutex_
18
+ Symbol _symbol(const std::string& s);
19
+ std::pair<const char*, const char*> customString(Symbol sym);
20
+ std::unordered_map<std::string, Symbol> string_to_sym_;
21
+
22
+ struct SymbolInfo {
23
+ Symbol ns;
24
+ std::string qual_name;
25
+ std::string unqual_name;
26
+ };
27
+ std::vector<SymbolInfo> sym_to_info_;
28
+
29
+ std::mutex mutex_;
30
+ };
31
+
32
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue.h ADDED
@@ -0,0 +1,1589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/DimVector.h>
4
+ #include <ATen/core/TensorBody.h>
5
+ #include <ATen/core/blob.h>
6
+ #include <ATen/core/custom_class.h>
7
+ #include <ATen/core/ivalue_to.h>
8
+ #include <ATen/core/jit_type_base.h>
9
+ #include <ATen/core/type_factory.h>
10
+ #include <c10/core/SymBool.h>
11
+ #include <c10/core/SymFloat.h>
12
+ #include <c10/macros/Export.h>
13
+ #include <c10/util/MaybeOwned.h>
14
+ #include <c10/util/intrusive_ptr.h>
15
+ #include <type_traits>
16
+ #include <unordered_map>
17
+ #include <unordered_set>
18
+ #include <utility>
19
+
20
+ namespace torch {
21
+ class TORCH_API CustomClassHolder : public c10::intrusive_ptr_target {};
22
+ namespace jit {
23
+ using ::torch::CustomClassHolder;
24
+ struct Function;
25
+ struct CompilationUnit;
26
+ struct Module;
27
+ } // namespace jit
28
+ } // namespace torch
29
+ namespace c10 {
30
+ template <class Key, class Value>
31
+ class Dict;
32
+ template <class T>
33
+ class List;
34
+ template <class T>
35
+ class IListRef;
36
+ struct IValue;
37
+ struct ClassType;
38
+ struct Type;
39
+ class RRefInterface;
40
+
41
+ struct ClassType;
42
+ using ClassTypePtr = std::shared_ptr<ClassType>;
43
+
44
+ TORCH_API bool _fastEqualsForContainer(const IValue& lhs, const IValue& rhs);
45
+
46
+ TORCH_API torch::jit::Function* checkObjectSortSchema(
47
+ const c10::ClassTypePtr& t,
48
+ std::stringstream& why_not);
49
+
50
+ // A comparator that checks ordering of two IValues of same type.
51
+ typedef std::function<bool(const IValue& a, const IValue& b)> IValueComparator;
52
+
53
+ TORCH_API IValueComparator getLessThanComparator(const IValue& v);
54
+ TORCH_API IValueComparator getGreaterThanComparator(const IValue& v);
55
+
56
+ namespace ivalue {
57
+ struct Tuple;
58
+ struct Future;
59
+ struct Await;
60
+ struct ConstantString;
61
+ struct GenericDict;
62
+ struct Object;
63
+ struct PyObjectHolder;
64
+ struct EnumHolder;
65
+ // We need a ComplexHolder because currently the payloads in the Union
66
+ // only take 64 bits. Since ComplexDouble takes up 128 bits, and is too big
67
+ // to fit in the IValue directly, we indirect complex numbers through an
68
+ // intrusive pointer to ComplexHolder (which contains a c10::complex).
69
+ struct ComplexHolder : c10::intrusive_ptr_target {
70
+ public:
71
+ template <typename T>
72
+ ComplexHolder(c10::complex<T> c) {
73
+ val = convert<decltype(val), c10::complex<T>>(c);
74
+ }
75
+ ComplexHolder() = default;
76
+ c10::complex<double> val;
77
+ };
78
+
79
+ // Similar to ComplexHolder, for StreamData3
80
+ struct StreamData3Holder : c10::intrusive_ptr_target {
81
+ public:
82
+ StreamData3Holder(struct c10::StreamData3 d) : val(d) {}
83
+ StreamData3Holder() = delete;
84
+ struct c10::StreamData3 val;
85
+ };
86
+
87
+ } // namespace ivalue
88
+
89
+ // This is an owning wrapper for a std::optional<std::vector<T>>
90
+ // that can be implicitly converted to a (non-owning) std::optional<ArrayRef<T>>.
91
+ // Its purpose is to be used in generated code to keep the vector alive
92
+ // either until the end of a statement (as a temporary), or as a saved arg
93
+ // in autograd.
94
+ template <typename T>
95
+ struct OptionalArray {
96
+ std::optional<std::vector<T>> list;
97
+
98
+ OptionalArray() = default;
99
+ OptionalArray(std::vector<T> val) : list(std::move(val)) {}
100
+
101
+ // Used when saving an argument for the backwards pass.
102
+ OptionalArray& operator=(std::optional<ArrayRef<T>> ref) {
103
+ if (ref) {
104
+ list = std::vector<T>(ref->begin(), ref->end());
105
+ } else {
106
+ list = std::nullopt;
107
+ }
108
+ return *this;
109
+ }
110
+
111
+ // Used when saving an argument for the backwards pass.
112
+ OptionalArray& operator=(c10::OptionalArrayRef<T> ref) {
113
+ if (ref) {
114
+ list = std::vector<T>(ref->begin(), ref->end());
115
+ } else {
116
+ list = std::nullopt;
117
+ }
118
+ return *this;
119
+ }
120
+
121
+ operator std::optional<c10::ArrayRef<T>>() {
122
+ if (!list) {
123
+ return std::nullopt;
124
+ }
125
+ return *list;
126
+ }
127
+
128
+ operator c10::OptionalArrayRef<T>() {
129
+ if (!list) {
130
+ return std::nullopt;
131
+ }
132
+ return *list;
133
+ }
134
+ };
135
+
136
+ // Capsule is an internal implementation detail of custom C++ classes. We
137
+ // define it as an owning wrapper for
138
+ // c10::intrusive_ptr<torch::CustomClassHolder> This wrapper is here to serve as
139
+ // an abstraction of the type erased custom class object pointer. It also allow
140
+ // pybind11 to treat this as a standalone class to register as a separate type
141
+ // caster, instead of a custom pointer holder which the pointer holder type
142
+ // caster try to "unwrap" it automatically.
143
+ struct Capsule {
144
+ c10::intrusive_ptr<torch::CustomClassHolder> obj_ptr;
145
+ explicit Capsule(c10::intrusive_ptr<torch::CustomClassHolder> ptr)
146
+ : obj_ptr(std::move(ptr)) {}
147
+ };
148
+
149
+ // IValue is the generic tagged union used by the interpreter to hold
150
+ // all value types.
151
+ // It is a 16-byte object with an 8-byte payload and an 8-byte tag.
152
+ // The tag is currently 4 bytes to determine the type, and 1 byte
153
+ // to mark whether that type is a subtype of c10::intrusive_ptr_target and needs
154
+ // retain/release calls.
155
+
156
+ #define TORCH_FORALL_TAGS(_) \
157
+ _(None) \
158
+ _(Tensor) \
159
+ _(Storage) \
160
+ _(Double) \
161
+ _(ComplexDouble) \
162
+ _(Int) \
163
+ _(SymInt) \
164
+ _(SymFloat) \
165
+ _(SymBool) \
166
+ _(Bool) \
167
+ _(Tuple) \
168
+ _(String) \
169
+ _(Blob) \
170
+ _(GenericList) \
171
+ _(GenericDict) \
172
+ _(Future) \
173
+ _(Await) \
174
+ _(Device) \
175
+ _(Stream) \
176
+ _(Object) \
177
+ _(PyObject) \
178
+ _(Uninitialized) \
179
+ _(Capsule) \
180
+ _(RRef) \
181
+ _(Quantizer) \
182
+ _(Generator) \
183
+ _(Enum)
184
+
185
+ // [doxygen private]
186
+ // These methods are not actually private but we don't want to document them, so
187
+ // they are marked `@private`, which hides them on the doxygen documentation for
188
+ // this page.
189
+
190
+ /// IValue (Interpreter Value) is a tagged union over the types
191
+ /// supported by the TorchScript interpreter. IValues contain their
192
+ /// values as an `IValue::Payload`, which holds primitive types
193
+ /// (`int64_t`, `bool`, `double`, `Device`) and `Tensor` as values,
194
+ /// and all other types as a `c10::intrusive_ptr`. In order to
195
+ /// optimize performance of the destructor and related operations by
196
+ /// making the `Tensor` and `c10::intrusive_ptr` paths generate the
197
+ /// same code, we represent a null `c10::intrusive_ptr` as
198
+ /// `UndefinedTensorImpl::singleton()`, *not* `nullptr`.
199
+ ///
200
+ /// IValues are used as inputs to and outputs from the TorchScript interpreter.
201
+ /// To retrieve the value contained within an IValue, use the `.toX()` methods,
202
+ /// where `X` is the type you are trying to get. Note that neither the `.toX()`
203
+ /// methods nor the templated `.to<T>` functions do any kind of casting, they
204
+ /// only unwrap the contained value. For example:
205
+ ///
206
+ /// \rst
207
+ /// .. code-block:: cpp
208
+ ///
209
+ /// // Make the IValue
210
+ /// torch::IValue my_ivalue(26);
211
+ /// std::cout << my_ivalue << "\n";
212
+ ///
213
+ /// // Unwrap the IValue
214
+ /// int64_t my_int = my_ivalue.toInt();
215
+ /// std::cout << my_int << "\n";
216
+ ///
217
+ /// // This will throw an error!
218
+ /// // `my_ivalue` is tagged as an int and cannot be used as another type
219
+ /// torch::Tensor my_tensor = my_ivalue.toTensor();
220
+ /// \endrst
221
+ struct TORCH_API IValue final {
222
+ IValue(const IValue& rhs) : IValue(rhs.payload, rhs.tag) {
223
+ if (isIntrusivePtr() &&
224
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()) {
225
+ c10::raw::intrusive_ptr::incref(payload.u.as_intrusive_ptr);
226
+ }
227
+ }
228
+
229
+ IValue(IValue&& rhs) noexcept : tag(rhs.tag) {
230
+ moveFrom(std::move(rhs));
231
+ }
232
+
233
+ /// @private [doxygen private]
234
+ ~IValue() {
235
+ destroy();
236
+ }
237
+
238
+ C10_ALWAYS_INLINE IValue& operator=(IValue&& rhs) & noexcept {
239
+ if (&rhs == this) {
240
+ return *this;
241
+ }
242
+
243
+ destroy();
244
+ moveFrom(std::move(rhs));
245
+ return *this;
246
+ }
247
+
248
+ IValue& operator=(IValue const& rhs) & {
249
+ *this = IValue(rhs);
250
+ return *this;
251
+ }
252
+
253
+ void dump() const;
254
+
255
+ /**
256
+ * Equality comparison. The semantics are the same as Python's `==`:
257
+ * 1. Numerical types are compared by value.
258
+ * 2. Tensors compute element-wise equality, returning a BoolTensor (see:
259
+ * `torch.eq()`)
260
+ * 3. Strings are compared by value.
261
+ * 4. Sequence types (list, tuple) are compared lexicographically by
262
+ * comparing their elements. Different sequence types never compare equal.
263
+ * 5. Mappings (dict) must have equal (key, value) pairs.
264
+ * 6. If not listed above, the default behavior for is to test identity
265
+ * equality (e.g. pointer equality).
266
+ *
267
+ * Why does this return an IValue instead of a bool? Because in PyTorch,
268
+ * `tensor1 == tensor2` returns a `BoolTensor`, not a bool.
269
+ *
270
+ * NOTE: we (like Python) assume that identity equality implies value equality
271
+ * for efficiency.
272
+ * TODO: need to support customizing equality
273
+ */
274
+ IValue equals(const IValue& rhs) const;
275
+ /**
276
+ * This implements the same semantics as `bool(lhs == rhs)` in Python. which
277
+ * is the same as `equals()` except for Tensor types.
278
+ */
279
+ TORCH_API friend bool operator==(const IValue& lhs, const IValue& rhs);
280
+ TORCH_API friend bool operator!=(const IValue& lhs, const IValue& rhs);
281
+
282
+ /**
283
+ * Identity comparison. Checks if `this` is the same object as `rhs`. The
284
+ * semantics are the same as Python's `is` operator.
285
+ *
286
+ * NOTE: Like in Python, this operation is poorly defined for primitive types
287
+ * like numbers and strings. Prefer to use `==` unless you really want to
288
+ * check identity equality.
289
+ */
290
+ bool is(const IValue& rhs) const;
291
+
292
+ /**
293
+ * Hashing for IValues. Returns an IValue-boxed int.
294
+ *
295
+ * Some notes:
296
+ * - Like eager, Tensors are hashed by looking at the pointer. This is not
297
+ * strictly correct because two value-equal tensors with different tensor
298
+ * pointers will hash differently, but we choose to reproduce the eager
299
+ * semantics.
300
+ * - Hashing is not defined on all built-in IValue types (e.g. list and
301
+ * dict), following Python. Calling `hash()` on these types will throw.
302
+ */
303
+ IValue hash() const {
304
+ return (int64_t)IValue::hash(*this);
305
+ }
306
+ // This is defined because `c10::hash` dispatches to a function of this
307
+ // signature. See the member function `hash()`.
308
+ static size_t hash(const IValue& iv);
309
+
310
+ /**
311
+ * @private [doxygen private]
312
+ * [container equality]
313
+ * This is an equality implementation that assumes objects with the same
314
+ * identity equal themselves, for efficiency reasons. We primarily have this
315
+ * for consistency, because Python does the same thing. This actually
316
+ * provokes user-visible changes in behavior due to quirks in torch:
317
+ * [tensor1] == [tensor1] -> True (because container equality will first
318
+ * compare identity) [tensor1] == [tensor1_copy] -> RuntimeError:
319
+ * Boolean value of Tensor with more than one value is ambiguous
320
+ */
321
+ TORCH_API friend bool _fastEqualsForContainer(
322
+ const IValue& lhs,
323
+ const IValue& rhs);
324
+
325
+ private:
326
+ static bool isAliasOf(const at::Tensor& a, const at::Tensor& b) {
327
+ if (a.is_sparse()) {
328
+ return isAliasOf(a._values(), b) || isAliasOf(a._indices(), b);
329
+ }
330
+ if (b.is_sparse()) {
331
+ return isAliasOf(a, b._values()) || isAliasOf(a, b._indices());
332
+ }
333
+ if (a.is_sparse_csr()) {
334
+ return isAliasOf(a.values(), b) || isAliasOf(a.crow_indices(), b) ||
335
+ isAliasOf(a.col_indices(), b);
336
+ }
337
+ if (b.is_sparse_csr()) {
338
+ return isAliasOf(a, b.values()) || isAliasOf(a, b.crow_indices()) ||
339
+ isAliasOf(a, b.col_indices());
340
+ }
341
+
342
+ // Opaque tensors such as the ones constructed by the MKL-DNN backend
343
+ // don't have storage so we just compare their TensorImpls.
344
+ // TODO: Find way to expose alias info for opaque tensors.
345
+ if (!a.has_storage() || !b.has_storage()) {
346
+ return a.unsafeGetTensorImpl() == b.unsafeGetTensorImpl();
347
+ }
348
+
349
+ return a.is_alias_of(b);
350
+ }
351
+
352
+ template <typename T>
353
+ bool isListOf() const;
354
+
355
+ public:
356
+ /// @private [doxygen private]
357
+ bool isAliasOf(const IValue& rhs) const {
358
+ if (this->tag != rhs.tag) {
359
+ // Trivially don't alias if the type is different
360
+ return false;
361
+ }
362
+
363
+ // Tensors should be compared based on internal storage
364
+ if (this->isTensor()) {
365
+ return isAliasOf(this->toTensor(), rhs.toTensor());
366
+ }
367
+
368
+ if (!isIntrusivePtr()) {
369
+ // Primitive types don't alias anything
370
+ return false;
371
+ }
372
+
373
+ AT_ASSERT(rhs.isIntrusivePtr());
374
+
375
+ // Other types can be compared by their ptr value
376
+ return this->payload.u.as_intrusive_ptr == rhs.payload.u.as_intrusive_ptr;
377
+ }
378
+
379
+ /// @private [doxygen private]
380
+ size_t use_count() const noexcept {
381
+ if (isTensor()) {
382
+ return payload.as_tensor.use_count();
383
+ }
384
+
385
+ if (!isIntrusivePtrLegacyBehavior()) {
386
+ return 1;
387
+ }
388
+
389
+ if (payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()) {
390
+ return 0;
391
+ }
392
+ return c10::raw::intrusive_ptr::use_count(payload.u.as_intrusive_ptr);
393
+ }
394
+
395
+ /// @private [doxygen private]
396
+ void swap(IValue& rhs) noexcept {
397
+ if (isTensor() && rhs.isTensor()) {
398
+ std::swap(payload.as_tensor, rhs.payload.as_tensor);
399
+ } else if (isTensor()) {
400
+ at::Tensor t = std::move(payload.as_tensor);
401
+ // As far as I can tell, omitting the usual explicit destructor call
402
+ // is not UB in and of itself, and it's a slight perf win. The
403
+ // destructor is a no-op, because the moved-from Tensor is
404
+ // effectively an intrusive_ptr in the null state, so we don't need
405
+ // the behavior for correctness reasons either. Leaving this
406
+ // explanatory comment, including commented-out destructor call, to
407
+ // make this abundantly clear.
408
+ //
409
+ // payload.as_tensor.~Tensor();
410
+ payload.u = rhs.payload.u;
411
+ new (&rhs.payload.as_tensor) at::Tensor(std::move(t));
412
+ } else if (rhs.isTensor()) {
413
+ rhs.swap(*this);
414
+ return;
415
+ } else {
416
+ std::swap(payload.u, rhs.payload.u);
417
+ }
418
+ std::swap(tag, rhs.tag);
419
+ }
420
+
421
+ // Accessors for subtypes are arranged together below
422
+ // While some of these accessors could be generated through templates,
423
+ // we prefer to write them manually for clarity
424
+
425
+ IValue(at::TensorBase t) : tag(Tag::Tensor) {
426
+ new (&payload.as_tensor) at::Tensor(std::move(t));
427
+ }
428
+ bool isTensor() const {
429
+ return Tag::Tensor == tag;
430
+ }
431
+
432
+ private:
433
+ // Outlined error path so that toTensor() can be inlined.
434
+ [[noreturn]] void reportToTensorTypeError() const;
435
+
436
+ public:
437
+ at::Tensor toTensor() &&;
438
+ at::Tensor& toTensor() &;
439
+ const at::Tensor& toTensor() const&;
440
+ at::TensorImpl* unsafeToTensorImpl() const {
441
+ TORCH_INTERNAL_ASSERT(isTensor());
442
+ return payload.as_tensor.unsafeGetTensorImpl();
443
+ }
444
+
445
+ IValue(at::Storage s) : tag(Tag::Storage) {
446
+ payload.u.as_intrusive_ptr =
447
+ null_to_undefined_tensor(s.unsafeReleaseStorageImpl());
448
+ }
449
+ bool isStorage() const {
450
+ return Tag::Storage == tag;
451
+ }
452
+ c10::Storage toStorage() &&;
453
+ c10::Storage toStorage() const&;
454
+
455
+ const IValue& toIValue() const {
456
+ return *this;
457
+ }
458
+ IValue& toIValue() {
459
+ return *this;
460
+ }
461
+
462
+ /// @private [doxygen private]
463
+ IValue(intrusive_ptr<caffe2::Blob> blob) : tag(Tag::Blob) {
464
+ // TODO (after Tensor merge) If we pass in a Blob holding a Tensor, extract
465
+ // and store it as a Tensor instead.
466
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(blob.release());
467
+ }
468
+
469
+ /// @private [doxygen private]
470
+ bool isBlob() const {
471
+ return Tag::Blob == tag;
472
+ }
473
+
474
+ /// @private [doxygen private]
475
+ c10::intrusive_ptr<caffe2::Blob> toBlob() &&;
476
+
477
+ /// @private [doxygen private]
478
+ c10::intrusive_ptr<caffe2::Blob> toBlob() const&;
479
+
480
+ // Capsule. No new callsites of these APIs should
481
+ // be introduced.
482
+ static inline IValue make_capsule(
483
+ intrusive_ptr<torch::CustomClassHolder> blob);
484
+ bool isCapsule() const {
485
+ return Tag::Capsule == tag;
486
+ }
487
+ c10::intrusive_ptr<torch::CustomClassHolder> toCapsule() &&;
488
+ c10::intrusive_ptr<torch::CustomClassHolder> toCapsule() const&;
489
+
490
+ // Custom C++ classes
491
+ template <
492
+ typename T,
493
+ std::enable_if_t<std::is_base_of_v<torch::CustomClassHolder, T>, int> = 0>
494
+ IValue(intrusive_ptr<T> custom_class);
495
+ bool isCustomClass() const;
496
+ template <typename T>
497
+ c10::intrusive_ptr<T> toCustomClass() &&;
498
+ template <typename T>
499
+ c10::intrusive_ptr<T> toCustomClass() const&;
500
+
501
+ // Tuple
502
+ IValue(c10::intrusive_ptr<ivalue::Tuple> v);
503
+
504
+ template <
505
+ typename... Args,
506
+ std::enable_if_t<
507
+ !std::disjunction_v<
508
+ std::is_lvalue_reference<Args>...,
509
+ std::negation<std::is_constructible<IValue, Args>>...>,
510
+ std::nullptr_t> = nullptr>
511
+ IValue(const std::tuple<Args...>& t);
512
+ template <
513
+ typename... Args,
514
+ std::enable_if_t<
515
+ !std::disjunction_v<
516
+ std::is_lvalue_reference<Args>...,
517
+ std::negation<std::is_constructible<IValue, Args>>...>,
518
+ std::nullptr_t> = nullptr>
519
+ IValue(std::tuple<Args...>&& t);
520
+ bool isTuple() const {
521
+ return Tag::Tuple == tag;
522
+ }
523
+ c10::intrusive_ptr<ivalue::Tuple> toTuple() &&;
524
+ c10::intrusive_ptr<ivalue::Tuple> toTuple() const&;
525
+ [[nodiscard]] ivalue::Tuple& toTupleRef() const;
526
+
527
+ // Double
528
+ IValue(double d) : tag(Tag::Double) {
529
+ payload.u.as_double = d;
530
+ }
531
+ bool isDouble() const {
532
+ return Tag::Double == tag;
533
+ }
534
+ double toDouble() const {
535
+ if (isDouble()) {
536
+ return payload.u.as_double;
537
+ } else if (isSymFloat()) {
538
+ return toSymFloat().guard_float(__FILE__, __LINE__);
539
+ } else {
540
+ TORCH_INTERNAL_ASSERT(0, "expected double");
541
+ }
542
+ }
543
+
544
+ // ComplexDouble
545
+ template <typename T>
546
+ IValue(c10::complex<T> c);
547
+ bool isComplexDouble() const {
548
+ return Tag::ComplexDouble == tag;
549
+ }
550
+ c10::complex<double> toComplexDouble() const;
551
+
552
+ // Future
553
+ IValue(c10::intrusive_ptr<ivalue::Future> v);
554
+ bool isFuture() const {
555
+ return Tag::Future == tag;
556
+ }
557
+ c10::intrusive_ptr<ivalue::Future> toFuture() &&;
558
+ c10::intrusive_ptr<ivalue::Future> toFuture() const&;
559
+
560
+ IValue(c10::intrusive_ptr<ivalue::Await> v);
561
+ bool isAwait() const {
562
+ return Tag::Await == tag;
563
+ }
564
+ c10::intrusive_ptr<ivalue::Await> toAwait() &&;
565
+ c10::intrusive_ptr<ivalue::Await> toAwait() const&;
566
+
567
+ // RRef
568
+ IValue(c10::intrusive_ptr<c10::RRefInterface> v);
569
+ bool isRRef() const {
570
+ return Tag::RRef == tag;
571
+ }
572
+ c10::intrusive_ptr<c10::RRefInterface> toRRef() &&;
573
+ c10::intrusive_ptr<c10::RRefInterface> toRRef() const&;
574
+
575
+ // Quantizer
576
+ IValue(c10::intrusive_ptr<at::Quantizer> v);
577
+ bool isQuantizer() const {
578
+ return Tag::Quantizer == tag;
579
+ }
580
+ c10::intrusive_ptr<at::Quantizer> toQuantizer() &&;
581
+ c10::intrusive_ptr<at::Quantizer> toQuantizer() const&;
582
+
583
+ // Int
584
+ IValue(int64_t i) : tag(Tag::Int) {
585
+ payload.u.as_int = i;
586
+ }
587
+
588
+ IValue(const c10::SymInt& i) {
589
+ if (auto mi = i.maybe_as_int()) {
590
+ tag = Tag::Int;
591
+ payload.u.as_int = *mi;
592
+ } else {
593
+ tag = Tag::SymInt;
594
+ payload.u.as_intrusive_ptr = i.toSymNode().release();
595
+ }
596
+ }
597
+
598
+ bool isSymInt() const {
599
+ return Tag::SymInt == tag;
600
+ }
601
+
602
+ c10::SymInt toSymInt() &&;
603
+ c10::SymInt toSymInt() const&;
604
+
605
+ IValue(const c10::SymFloat& i) {
606
+ if (i.is_symbolic()) {
607
+ tag = Tag::SymFloat;
608
+ payload.u.as_intrusive_ptr = i.toSymNodeImpl().release();
609
+ } else {
610
+ tag = Tag::Double;
611
+ payload.u.as_double = i.as_float_unchecked();
612
+ }
613
+ }
614
+
615
+ bool isSymFloat() const {
616
+ return Tag::SymFloat == tag;
617
+ }
618
+
619
+ c10::SymFloat toSymFloat() &&;
620
+ c10::SymFloat toSymFloat() const&;
621
+
622
+ IValue(const c10::SymBool& i) {
623
+ if (auto mi = i.maybe_as_bool()) {
624
+ tag = Tag::Bool;
625
+ payload.u.as_int = *mi;
626
+ } else {
627
+ tag = Tag::SymBool;
628
+ payload.u.as_intrusive_ptr = i.toSymNodeImpl().release();
629
+ }
630
+ }
631
+
632
+ bool isSymBool() const {
633
+ return Tag::SymBool == tag;
634
+ }
635
+
636
+ c10::SymBool toSymBool() &&;
637
+ c10::SymBool toSymBool() const&;
638
+
639
+ // allow you to pass literals (3, 4) without ambiguity
640
+ IValue(int32_t i) : IValue(static_cast<int64_t>(i)) {}
641
+
642
+ bool isInt() const {
643
+ return Tag::Int == tag;
644
+ }
645
+
646
+ int64_t toInt() const {
647
+ if (isInt()) {
648
+ return payload.u.as_int;
649
+ } else if (isSymInt()) {
650
+ return toSymInt().guard_int(__FILE__, __LINE__);
651
+ } else {
652
+ TORCH_INTERNAL_ASSERT(0, "expected int");
653
+ }
654
+ }
655
+
656
+ // Bool
657
+ IValue(bool b) : tag(Tag::Bool) {
658
+ #if defined(__clang__) && defined(__x86_64__)
659
+ // Initializing entire payload stops valgrind's from reporting
660
+ // "jump or move depends on uninitialised value" in IValue copy constructor
661
+ // See https://github.com/pytorch/pytorch/issues/37117
662
+ payload.u.as_int = b;
663
+ #else
664
+ payload.u.as_bool = b;
665
+ #endif
666
+ }
667
+ bool isBool() const {
668
+ return Tag::Bool == tag;
669
+ }
670
+ bool toBool() const {
671
+ if (isBool()) {
672
+ return payload.u.as_bool;
673
+ } else if (isSymBool()) {
674
+ return toSymBool().guard_bool(__FILE__, __LINE__);
675
+ } else {
676
+ TORCH_INTERNAL_ASSERT(0, "expected bool");
677
+ }
678
+ }
679
+
680
+ // IntList
681
+ bool isIntList() const;
682
+ bool isSymIntList() const;
683
+ c10::List<int64_t> toIntList() &&;
684
+ c10::List<int64_t> toIntList() const&;
685
+ std::vector<int64_t> toIntVector() const;
686
+ c10::List<c10::SymInt> toSymIntList() &&;
687
+ c10::List<c10::SymInt> toSymIntList() const&;
688
+ std::vector<c10::SymInt> toSymIntVector() const;
689
+ at::DimVector toDimVector() const;
690
+
691
+ // ConstantString
692
+ IValue(c10::intrusive_ptr<ivalue::ConstantString> v);
693
+ IValue(std::string v);
694
+ IValue(const char* v) : IValue(std::string(v)) {}
695
+ IValue(std::string_view v) : IValue(std::string(v)){}
696
+ bool isString() const {
697
+ return Tag::String == tag;
698
+ }
699
+ c10::intrusive_ptr<ivalue::ConstantString> toString() &&;
700
+ c10::intrusive_ptr<ivalue::ConstantString> toString() const&;
701
+ const std::string& toStringRef() const;
702
+ std::optional<std::reference_wrapper<const std::string>> toOptionalStringRef()
703
+ const;
704
+ std::string_view toStringView() const;
705
+
706
+ // DoubleList
707
+ bool isDoubleList() const;
708
+ c10::List<double> toDoubleList() &&;
709
+ c10::List<double> toDoubleList() const&;
710
+ std::vector<double> toDoubleVector() const;
711
+
712
+ // ComplexDoubleList
713
+ bool isComplexDoubleList() const;
714
+ c10::List<c10::complex<double>> toComplexDoubleList() &&;
715
+ c10::List<c10::complex<double>> toComplexDoubleList() const&;
716
+ std::vector<c10::complex<double>> toComplexDoubleVector() const;
717
+
718
+ // BoolList
719
+ bool isBoolList() const;
720
+ c10::List<bool> toBoolList() &&;
721
+ c10::List<bool> toBoolList() const&;
722
+
723
+ // TensorList
724
+ bool isTensorList() const;
725
+ c10::List<at::Tensor> toTensorList() &&;
726
+ c10::List<at::Tensor> toTensorList() const&;
727
+ std::vector<at::Tensor> toTensorVector() const;
728
+
729
+ // OptionalTensorList
730
+ bool isOptionalTensorList() const;
731
+ c10::List<std::optional<at::Tensor>> toOptionalTensorList() &&;
732
+ c10::List<std::optional<at::Tensor>> toOptionalTensorList() const&;
733
+ std::vector<std::optional<at::Tensor>> toOptionalTensorVector() const;
734
+
735
+ // GenericList
736
+ IValue(c10::List<IValue> v);
737
+ bool isList() const {
738
+ return Tag::GenericList == tag;
739
+ }
740
+ c10::List<IValue> toList() &&;
741
+ c10::List<IValue> toList() const&;
742
+ c10::ArrayRef<IValue> toListRef() const;
743
+
744
+ // Some template constructors of IValue calls another constructor recursively.
745
+ // This SFINAEs the called constructor exists.
746
+ template <class T>
747
+ using enable_if_ivalue_constructible =
748
+ std::enable_if_t<std::is_constructible_v<IValue, T>, std::nullptr_t>;
749
+
750
+ // The rule for lists is more complicated; the generic constructor is only
751
+ // acceptable if your element isn't SymInt. If you do have a SymInt element,
752
+ // then you must also, at construction time, check if you can decay the list
753
+ // into an int list (this is MANDATORY, as at a use site we may expect
754
+ // toIntList to work even if at the call site you had a SymIntArrayRef
755
+ // argument). In practice, only SymIntArrayRef is used this way, so we
756
+ // didn't bother making it work for the other constructors, we just make sure
757
+ // they're not selectable.
758
+ template <class T>
759
+ using enable_if_list_is_ivalue_constructible = std::enable_if_t<
760
+ std::is_constructible_v<IValue, T> && !std::is_same_v<T, c10::SymInt>,
761
+ std::nullptr_t>;
762
+
763
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
764
+ IValue(c10::List<T>&& v);
765
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
766
+ IValue(const c10::List<T>& v);
767
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
768
+ IValue(at::ArrayRef<T> v);
769
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
770
+ IValue(const std::vector<T>& v);
771
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
772
+ IValue(std::vector<T>&& v);
773
+ template <class T, size_t N>
774
+ IValue(std::array<T, N> v);
775
+
776
+ // Manual constructors for lists of symints, which decay to int list if
777
+ // possible. To avoid ambiguous overload situations, we template them
778
+ // to prevent implicit conversions
779
+ template <class T>
780
+ using enable_if_symint =
781
+ std::enable_if_t<std::is_same_v<T, c10::SymInt>, std::nullptr_t>;
782
+
783
+ template <class T, enable_if_symint<T> = nullptr>
784
+ IValue(at::ArrayRef<T> v);
785
+ template <class T, enable_if_symint<T> = nullptr>
786
+ IValue(at::OptionalArrayRef<T> v);
787
+ template <class T, enable_if_symint<T> = nullptr>
788
+ IValue(const std::vector<T>& v);
789
+ template <class T, enable_if_symint<T> = nullptr>
790
+ IValue(std::vector<T>&& v);
791
+
792
+ template <class T>
793
+ using enable_if_ilist_is_ivalue_constructible = std::enable_if_t<
794
+ std::is_constructible_v<IValue, T> &&
795
+ std::is_constructible_v<IValue, typename IListRef<T>::boxed_type> &&
796
+ !std::is_same_v<T, c10::SymInt>,
797
+ std::nullptr_t>;
798
+
799
+ template <class T, enable_if_ilist_is_ivalue_constructible<T> = nullptr>
800
+ IValue(c10::IListRef<T> v);
801
+
802
+ // GenericDict
803
+ IValue(c10::Dict<IValue, IValue> v);
804
+ bool isGenericDict() const {
805
+ return Tag::GenericDict == tag;
806
+ }
807
+ c10::Dict<IValue, IValue> toGenericDict() &&;
808
+ c10::Dict<IValue, IValue> toGenericDict() const&;
809
+
810
+ template <class Key, class Value>
811
+ IValue(c10::Dict<Key, Value> v);
812
+
813
+ template <class Key, class Value>
814
+ /// \cond
815
+ /// DOXYGEN_CANNOT_HANDLE_CONSTRUCTORS_WITH_MACROS_SO_EXCLUDE_THIS_LINE_FROM_DOXYGEN
816
+ C10_DEPRECATED_MESSAGE(
817
+ "IValues based on std::unordered_map<K, V> are slow and deprecated. Please use c10::Dict<K, V> instead.")
818
+ /// \endcond
819
+ IValue(std::unordered_map<Key, Value> v);
820
+
821
+ template <class T, enable_if_ivalue_constructible<T> = nullptr>
822
+ IValue(std::optional<T> v);
823
+ template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
824
+ IValue(c10::OptionalArrayRef<T> v);
825
+ IValue(std::nullopt_t);
826
+
827
+ // ClassType
828
+ IValue(c10::intrusive_ptr<ivalue::Object> v);
829
+ bool isObject() const {
830
+ return tag == Tag::Object;
831
+ }
832
+ c10::intrusive_ptr<ivalue::Object> toObject() &&;
833
+ c10::intrusive_ptr<ivalue::Object> toObject() const&;
834
+ ivalue::Object& toObjectRef() const;
835
+
836
+ torch::jit::Module toModule() const;
837
+ bool isModule() const;
838
+
839
+ // PyObject
840
+ IValue(c10::intrusive_ptr<ivalue::PyObjectHolder> v);
841
+ bool isPyObject() const {
842
+ return tag == Tag::PyObject;
843
+ }
844
+ c10::intrusive_ptr<ivalue::PyObjectHolder> toPyObjectHolder() &&;
845
+ c10::intrusive_ptr<ivalue::PyObjectHolder> toPyObjectHolder() const&;
846
+ PyObject* toPyObject() const;
847
+
848
+ // Enum
849
+ explicit IValue(c10::intrusive_ptr<ivalue::EnumHolder> v);
850
+ bool isEnum() const {
851
+ return tag == Tag::Enum;
852
+ }
853
+ c10::intrusive_ptr<ivalue::EnumHolder> toEnumHolder() &&;
854
+ c10::intrusive_ptr<ivalue::EnumHolder> toEnumHolder() const&;
855
+
856
+ // None
857
+ IValue() = default;
858
+ bool isNone() const {
859
+ return Tag::None == tag;
860
+ }
861
+ std::string toNone() const {
862
+ AT_ASSERT(isNone());
863
+ return "None";
864
+ }
865
+
866
+ static IValue uninitialized() {
867
+ auto i = IValue();
868
+ i.tag = Tag::Uninitialized;
869
+ return i;
870
+ }
871
+
872
+ // Scalar, which gets encoded as either an Int, a Double or a ComplexDouble
873
+ IValue(const at::Scalar& s) : IValue() {
874
+ // NB: do the symbolic versions first, as isFloatingPoint is true
875
+ // for both SymFloat and double
876
+ if (s.isSymInt()) {
877
+ tag = Tag::SymInt;
878
+ payload.u.as_intrusive_ptr = s.toSymInt().toSymNode().release();
879
+ } else if (s.isSymFloat()) {
880
+ tag = Tag::SymFloat;
881
+ payload.u.as_intrusive_ptr = s.toSymFloat().toSymNodeImpl().release();
882
+ } else if (s.isSymBool()) {
883
+ tag = Tag::SymBool;
884
+ payload.u.as_intrusive_ptr = s.toSymBool().toSymNodeImpl().release();
885
+ } else if (s.isFloatingPoint()) {
886
+ tag = Tag::Double;
887
+ payload.u.as_double = s.toDouble();
888
+ } else if (s.isComplex()) {
889
+ *this = s.toComplexDouble();
890
+ } else if (s.isBoolean()) {
891
+ tag = Tag::Bool;
892
+ payload.u.as_bool = s.toBool();
893
+ } else {
894
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
895
+ s.isIntegral(false), "Unknown type in Scalar");
896
+ tag = Tag::Int;
897
+ payload.u.as_int = s.toLong();
898
+ }
899
+ }
900
+
901
+ bool isScalar() const {
902
+ return isDouble() || isInt() || isComplexDouble() || isBool() ||
903
+ isSymInt() || isSymFloat() || isSymBool();
904
+ }
905
+
906
+ at::Scalar toScalar() const {
907
+ if (isDouble())
908
+ return toDouble();
909
+ else if (isInt())
910
+ return toInt();
911
+ else if (isComplexDouble())
912
+ return toComplexDouble();
913
+ else if (isBool())
914
+ return toBool();
915
+ else if (isSymInt())
916
+ return toSymInt();
917
+ else if (isSymFloat())
918
+ return toSymFloat();
919
+ else if (isSymBool())
920
+ return toSymBool();
921
+ TORCH_CHECK(false, "IValue is not a Scalar");
922
+ }
923
+
924
+ // Device
925
+ IValue(c10::Device d) : tag(Tag::Device) {
926
+ payload.u.as_device.type = d.type();
927
+ payload.u.as_device.index = d.index();
928
+ }
929
+ bool isDevice() const {
930
+ return Tag::Device == tag;
931
+ }
932
+ c10::Device toDevice() const {
933
+ AT_ASSERT(isDevice());
934
+ return c10::Device(payload.u.as_device.type, payload.u.as_device.index);
935
+ }
936
+
937
+ // Stream
938
+ IValue(c10::Stream s) : tag(Tag::Stream) {
939
+ auto v = c10::make_intrusive<ivalue::StreamData3Holder>(s.pack3());
940
+ payload.u.as_intrusive_ptr = v.release();
941
+ }
942
+ c10::Stream toStream() &&;
943
+ c10::Stream toStream() const&;
944
+ bool isStream() const {
945
+ return Tag::Stream == tag;
946
+ }
947
+
948
+ // ScalarType
949
+ IValue(ScalarType t)
950
+ : IValue(static_cast<std::underlying_type_t<ScalarType>>(t)) {}
951
+ at::ScalarType toScalarType() const {
952
+ return static_cast<at::ScalarType>(toInt());
953
+ }
954
+
955
+ // Layout
956
+ IValue(Layout l) : IValue(static_cast<std::underlying_type_t<Layout>>(l)) {}
957
+ at::Layout toLayout() const {
958
+ return static_cast<at::Layout>(toInt());
959
+ }
960
+
961
+ // MemoryFormat
962
+ IValue(MemoryFormat m)
963
+ : IValue(static_cast<std::underlying_type_t<MemoryFormat>>(m)) {}
964
+ at::MemoryFormat toMemoryFormat() const {
965
+ return static_cast<at::MemoryFormat>(toInt());
966
+ }
967
+
968
+ // QScheme
969
+ IValue(at::QScheme qscheme) : tag(Tag::Int) {
970
+ payload.u.as_int = static_cast<int64_t>(qscheme);
971
+ }
972
+
973
+ at::QScheme toQScheme() const {
974
+ return static_cast<at::QScheme>(toInt());
975
+ }
976
+
977
+ // Dimname
978
+ IValue(at::Dimname dimname) : IValue(dimname.symbol().toQualString()) {}
979
+
980
+ at::Dimname toDimname() const {
981
+ return at::Dimname::fromSymbol(Symbol::fromQualString(toStringRef()));
982
+ }
983
+
984
+ // Generator
985
+ IValue(at::Generator g) : tag(Tag::Generator) {
986
+ payload.u.as_intrusive_ptr =
987
+ null_to_undefined_tensor(g.unsafeReleaseGeneratorImpl());
988
+ }
989
+ bool isGenerator() const {
990
+ return Tag::Generator == tag;
991
+ }
992
+ at::Generator toGenerator() &&;
993
+ at::Generator toGenerator() const&;
994
+
995
+ // for debugging
996
+ std::string tagKind() const {
997
+ switch (tag) {
998
+ #define DEFINE_CASE(x) \
999
+ case Tag::x: \
1000
+ return #x;
1001
+ TORCH_FORALL_TAGS(DEFINE_CASE)
1002
+ #undef DEFINE_CASE
1003
+ }
1004
+ return "InvalidTag(" + std::to_string(static_cast<int>(tag)) + ")";
1005
+ }
1006
+
1007
+ // generic v.to<at::Tensor>() implementations
1008
+ // that can be used in special functions like pop/push
1009
+ // that use template meta-programming.
1010
+ // prefer the directly named methods when you can,
1011
+ // since they are simpler to understand
1012
+
1013
+ // Note: if you get linker errors saying one of these is missing,
1014
+ // change it to ... && = delete; and you will see better error messages for
1015
+ // why However, we cannot commit this because some compiler versions barf on
1016
+ // it.
1017
+ template <typename T>
1018
+ T to() &&;
1019
+ template <typename T>
1020
+ typename c10::detail::ivalue_to_const_ref_overload_return<T>::type to()
1021
+ const&;
1022
+
1023
+ // ToOptional: convert a IValue to the Optional obj that accepts both T and
1024
+ // None
1025
+ template <typename T>
1026
+ std::optional<T> toOptional();
1027
+ template <typename T>
1028
+ std::optional<T> toOptional() const;
1029
+
1030
+ /// @private [doxygen private]
1031
+ /// this is a shallow comparison of two IValues to test the object identity
1032
+ bool isSameIdentity(const IValue& rhs) const;
1033
+
1034
+ // Computes the "official" string representation of an IValue. This produces a
1035
+ // TorchScript expression that can be used to recreate an IValue with the same
1036
+ // value (e.g. when we are printing constants in the serializer).
1037
+ //
1038
+ // Callers can use `customFormatter` to override how `repr()` prints out an
1039
+ // IValue. This is useful if you have some other environment where you can
1040
+ // look up values, and you want to print a reference to that environment (like
1041
+ // the serializer's constant table).
1042
+ //
1043
+ // repr() is not necessarily defined on all objects!
1044
+ std::ostream& repr(
1045
+ std::ostream& stream,
1046
+ std::function<bool(std::ostream&, const IValue& v)> customFormatter)
1047
+ const;
1048
+
1049
+ // Computes an "informal" string representation of an IValue. This should be
1050
+ // used for debugging, or servicing `print()`-like functions.
1051
+ // This is different from `repr()` in that there is no expectation that we can
1052
+ // exactly reconstruct an IValue from the output; feel free to use a
1053
+ // concise/pretty form
1054
+ TORCH_API friend std::ostream& operator<<(std::ostream& out, const IValue& v);
1055
+
1056
+ bool isPtrType() const {
1057
+ if (isTensor()) {
1058
+ return payload.as_tensor.defined();
1059
+ }
1060
+ return isIntrusivePtrLegacyBehavior();
1061
+ }
1062
+
1063
+ /// @private [doxygen private]
1064
+ const void* internalToPointer() const {
1065
+ TORCH_INTERNAL_ASSERT(
1066
+ isPtrType(), "Can only call internalToPointer() for pointer types");
1067
+ if (isTensor()) {
1068
+ return payload.as_tensor.unsafeGetTensorImpl();
1069
+ } else {
1070
+ return payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()
1071
+ ? payload.u.as_intrusive_ptr
1072
+ : nullptr;
1073
+ }
1074
+ }
1075
+
1076
+ template <typename T = c10::PlatformType>
1077
+ TypePtr type() const;
1078
+
1079
+ // Detect aliased tensors.
1080
+ struct HashAliasedIValue {
1081
+ size_t hashTensor(const at::Tensor& ten) const {
1082
+ if (ten.is_sparse()) {
1083
+ // COO sparse tensors have a "values" tensor and an "indices" tensor
1084
+ // so this will detect overlap of sparse tensors that share a values
1085
+ // tensor, but not sparse tensors that share an indices tensor.
1086
+ return hashTensor(ten._values());
1087
+ } else if (ten.is_sparse_csr()) {
1088
+ // COO sparse tensors have a "values" tensor and an "indices" tensor
1089
+ // so this will detect overlap of sparse tensors that share a values
1090
+ // tensor, but not sparse tensors that share an indices tensor.
1091
+ return hashTensor(ten.values());
1092
+ } else if (!ten.has_storage()) {
1093
+ // Opaque tensors such as the ones constructed by the MKL-DNN backend
1094
+ // don't have storage so we just use their TensorImpls.
1095
+ // TODO: Find way to expose alias info for opaque tensors.
1096
+ return reinterpret_cast<size_t>(ten.unsafeGetTensorImpl());
1097
+ } else {
1098
+ return reinterpret_cast<size_t>(ten.storage().unsafeGetStorageImpl());
1099
+ }
1100
+ }
1101
+ size_t operator()(const IValue& val) const {
1102
+ if (val.isTensor()) {
1103
+ return hashTensor(val.toTensor());
1104
+ }
1105
+ // If it is not a Tensor, then two mutable IValues alias each other only
1106
+ // if they are the same pointer.
1107
+ return val.payload.u.as_int;
1108
+ }
1109
+ };
1110
+
1111
+ struct CompAliasedIValues {
1112
+ bool operator()(const IValue& lhs, const IValue& rhs) const {
1113
+ return lhs.isAliasOf(rhs);
1114
+ }
1115
+ };
1116
+
1117
+ using HashAliasedIValues =
1118
+ std::unordered_set<IValue, HashAliasedIValue, CompAliasedIValues>;
1119
+ using HashAliasedIValueMap =
1120
+ std::unordered_map<IValue, IValue, HashAliasedIValue, CompAliasedIValues>;
1121
+
1122
+ struct HashIdentityIValue {
1123
+ size_t operator()(const IValue& val) const {
1124
+ return val.payload.u.as_int;
1125
+ }
1126
+ };
1127
+
1128
+ struct CompIdentityIValues {
1129
+ bool operator()(const IValue& lhs, const IValue& rhs) const {
1130
+ return lhs.is(rhs);
1131
+ }
1132
+ };
1133
+
1134
+ using HashIdentityIValues =
1135
+ std::unordered_set<IValue, HashIdentityIValue, CompIdentityIValues>;
1136
+ using HashIdentityIValueMap =
1137
+ std::unordered_map<IValue, IValue, HashIdentityIValue, CompIdentityIValues>;
1138
+
1139
+ // Chechs if this and rhs has a subvalues in common.
1140
+ // [t1,t2] and [t2, t3] returns true.
1141
+ bool overlaps(const IValue& rhs) const;
1142
+
1143
+ // Inserts all subvalues of this in subValues.
1144
+ void getSubValues(HashAliasedIValues& subValues) const;
1145
+
1146
+ // Apply visitor to every subvalue.
1147
+ // TODO: There are several places that recurse over IValue. This is fragile.
1148
+ // This visitor should be used to recurse over ivalues.
1149
+ void visit(const std::function<bool(const IValue&)>& visitor) const;
1150
+ IValue deepcopy(std::optional<at::Device> device = std::nullopt) const;
1151
+ IValue deepcopy(
1152
+ HashIdentityIValueMap& memo,
1153
+ std::optional<at::Device> device = std::nullopt) const;
1154
+
1155
+ private:
1156
+ static c10::intrusive_ptr_target* null_to_undefined_tensor(
1157
+ c10::intrusive_ptr_target* p) {
1158
+ return p ? p
1159
+ : static_cast<c10::intrusive_ptr_target*>(
1160
+ c10::UndefinedTensorImpl::singleton());
1161
+ }
1162
+
1163
+ static bool ptrEqual(const IValue& lhs, const IValue& rhs);
1164
+ // NOTE: IValue tags are intentionally private. In the future we may encode
1165
+ // this value different (e.g. using NaN boxing), and this would make it more
1166
+ // costly to determine the tag for all types vs just determining if something
1167
+ // is a particular type. Instead we want clients to use the `isX` methods when
1168
+ // possible. If for performance reasons you really, absolutely, must have a jump
1169
+ // table, then we can revisit this.
1170
+ enum class Tag : uint32_t {
1171
+ #define DEFINE_TAG(x) x,
1172
+ TORCH_FORALL_TAGS(DEFINE_TAG)
1173
+ #undef DEFINE_TAG
1174
+ };
1175
+
1176
+ #define COUNT_TAG(x) 1 +
1177
+ static constexpr auto kNumTags = TORCH_FORALL_TAGS(COUNT_TAG) 0;
1178
+ #undef COUNT_TAG
1179
+
1180
+ template <
1181
+ class T,
1182
+ class NullType = c10::detail::intrusive_target_default_null_type<T>>
1183
+ c10::intrusive_ptr<T, NullType> moveToIntrusivePtr();
1184
+ template <
1185
+ typename T,
1186
+ class NullType = c10::detail::intrusive_target_default_null_type<T>>
1187
+ c10::intrusive_ptr<T, NullType> toIntrusivePtr() const;
1188
+
1189
+ void destroy() {
1190
+ // We carefully construct this call to both 1) avoid UB by using
1191
+ // the "wrong" one of as_tensor and as_intrusive_ptr and 2) enable
1192
+ // the compiler to generate the same code for each case. It is
1193
+ // surprisingly difficult to get this right.
1194
+ if (isTensor() || isIntrusivePtr()) {
1195
+ c10::intrusive_ptr_target* p = isTensor()
1196
+ ? payload.as_tensor.unsafeGetTensorImpl()
1197
+ : payload.u.as_intrusive_ptr;
1198
+ c10::intrusive_ptr<intrusive_ptr_target, c10::UndefinedTensorImpl>::
1199
+ reclaim(p);
1200
+ // No need to make this destructor call!
1201
+ // payload.as_tensor.~Tensor();
1202
+ }
1203
+ }
1204
+
1205
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
1206
+ C10_ALWAYS_INLINE void moveFrom(IValue&& rhs) noexcept {
1207
+ if (rhs.isTensor()) {
1208
+ new (&payload.as_tensor) at::Tensor(std::move(rhs.payload.as_tensor));
1209
+ // As far as I can tell, omitting the usual explicit destructor call
1210
+ // is not UB in and of itself, and it's a slight perf win. The
1211
+ // destructor is a no-op, because the moved-from Tensor is
1212
+ // effectively an intrusive_ptr in the null state, so we don't need
1213
+ // the behavior for correctness reasons either. Leaving this
1214
+ // explanatory comment, including commented-out destructor call, to
1215
+ // make this abundantly clear.
1216
+ //
1217
+ // rhs.payload.as_tensor.~Tensor();
1218
+ } else {
1219
+ payload.u = rhs.payload.u;
1220
+ }
1221
+ tag = rhs.tag;
1222
+ rhs.clearToNone();
1223
+ }
1224
+
1225
+ void clearToNone() noexcept {
1226
+ payload.u.as_int = 0;
1227
+ tag = Tag::None;
1228
+ }
1229
+
1230
+ private:
1231
+ // This is the source of truth for isIntrusivePtr; edit results here
1232
+ // as needed and isIntrusivePtr will pick them up.
1233
+ // NOLINTBEGIN(bugprone-branch-clone)
1234
+ static constexpr bool isIntrusivePtrConstexpr(Tag tag) {
1235
+ switch (tag) {
1236
+ case Tag::None:
1237
+ return false;
1238
+ case Tag::Tensor:
1239
+ return false;
1240
+ case Tag::Storage:
1241
+ return true;
1242
+ case Tag::Generator:
1243
+ return true;
1244
+ case Tag::Double:
1245
+ return false;
1246
+ case Tag::ComplexDouble:
1247
+ return true;
1248
+ case Tag::Int:
1249
+ return false;
1250
+ case Tag::SymInt:
1251
+ return true;
1252
+ case Tag::SymFloat:
1253
+ return true;
1254
+ case Tag::SymBool:
1255
+ return true;
1256
+ case Tag::Bool:
1257
+ return false;
1258
+ case Tag::Tuple:
1259
+ return true;
1260
+ case Tag::String:
1261
+ return true;
1262
+ case Tag::Blob:
1263
+ return true;
1264
+ case Tag::GenericList:
1265
+ return true;
1266
+ case Tag::GenericDict:
1267
+ return true;
1268
+ case Tag::Future:
1269
+ return true;
1270
+ case Tag::Await:
1271
+ return true;
1272
+ case Tag::Device:
1273
+ return false;
1274
+ case Tag::Stream:
1275
+ return true;
1276
+ case Tag::Object:
1277
+ return true;
1278
+ case Tag::PyObject:
1279
+ return true;
1280
+ case Tag::Uninitialized:
1281
+ return false;
1282
+ case Tag::Capsule:
1283
+ return true;
1284
+ case Tag::RRef:
1285
+ return true;
1286
+ case Tag::Quantizer:
1287
+ return true;
1288
+ case Tag::Enum:
1289
+ return true;
1290
+ }
1291
+ return false;
1292
+ }
1293
+ // NOLINTEND(bugprone-branch-clone)
1294
+
1295
+ public:
1296
+ // Don't edit this just to add results for new tags; edit
1297
+ // isIntrusivePtrConstexpr above.
1298
+ bool isIntrusivePtr() const {
1299
+ // Implementation NOTE: the switch in isIntrusivePtrConstexpr
1300
+ // above is the previous production implementation of this
1301
+ // function. We observed that, at least on x86_64, the generated
1302
+ // instruction sequence was a similar bit vector test to what we
1303
+ // have manually implemented below, except that there was an extra
1304
+ // "bounds check" branch confirming, essentially, that `tag <
1305
+ // kNumTags` and providing a consistent result in that case. We
1306
+ // don't care about the result if tag is out of bounds, so we'd
1307
+ // like to eliminate that comparison and branch; manually
1308
+ // implementing this function as a bit test is the simplest way I
1309
+ // could find to accomplish that elimination.
1310
+ static constexpr uint32_t kTruthTableBitVector =
1311
+ #define TRUTH_TABLE_ENTRY(tag) \
1312
+ (uint32_t(isIntrusivePtrConstexpr(Tag::tag)) << uint32_t(Tag::tag)) |
1313
+ TORCH_FORALL_TAGS(TRUTH_TABLE_ENTRY)
1314
+ #undef TRUTH_TABLE_ENTRY
1315
+ 0;
1316
+
1317
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
1318
+ static_cast<uint32_t>(tag) < kNumTags,
1319
+ "unexpected tag ",
1320
+ static_cast<int>(tag));
1321
+ return kTruthTableBitVector & (1 << (uint32_t(tag) % 32));
1322
+ }
1323
+
1324
+ // Storage and Generator were treated specially when
1325
+ // is_intrusive_ptr was stored as explicit state. This getter
1326
+ // preserves the old behavior for use with WeakIValue for now.
1327
+ bool isIntrusivePtrLegacyBehavior() const {
1328
+ if (tag == Tag::Storage || tag == Tag::Generator) {
1329
+ return payload.u.as_intrusive_ptr !=
1330
+ c10::UndefinedTensorImpl::singleton();
1331
+ } else {
1332
+ return isIntrusivePtr();
1333
+ }
1334
+ }
1335
+
1336
+ union Payload {
1337
+ // [TriviallyCopyablePayload]
1338
+ // We use a nested union here so that we can make the copy easy
1339
+ // and efficient in the non-tensor (i.e., trivially copyable)
1340
+ // case. Specifically, we do not have to do a switch-on-tag to
1341
+ // figure out which union member to assign; we can just use
1342
+ // TriviallyCopyablePayload::operator=.
1343
+ union TriviallyCopyablePayload {
1344
+ TriviallyCopyablePayload() : as_int(0) {}
1345
+ int64_t as_int;
1346
+ double as_double;
1347
+ bool as_bool;
1348
+ // Invariant: never nullptr; null state is represented as
1349
+ // c10::UndefinedTensorImpl::singleton() for consistency of
1350
+ // representation with Tensor.
1351
+ c10::intrusive_ptr_target* as_intrusive_ptr;
1352
+ struct {
1353
+ c10::DeviceType type;
1354
+ DeviceIndex index;
1355
+ } as_device;
1356
+ } u;
1357
+ static_assert(std::is_trivially_copyable_v<TriviallyCopyablePayload>);
1358
+ at::Tensor as_tensor;
1359
+ Payload() : u() {}
1360
+ Payload(const Payload&) = delete;
1361
+ Payload(Payload&&) = delete;
1362
+ Payload& operator=(const Payload&) = delete;
1363
+ Payload& operator=(Payload&&) = delete;
1364
+ // NOLINTNEXTLINE(modernize-use-equals-default)
1365
+ ~Payload() {}
1366
+ };
1367
+
1368
+ IValue(const Payload& p, Tag t) : tag(t) {
1369
+ if (isTensor()) {
1370
+ new (&payload.as_tensor) at::Tensor(p.as_tensor);
1371
+ } else {
1372
+ payload.u = p.u;
1373
+ }
1374
+ }
1375
+
1376
+ template <typename T>
1377
+ struct TagType {};
1378
+
1379
+ friend MaybeOwnedTraits<IValue>;
1380
+
1381
+ Payload payload;
1382
+ Tag tag{IValue::Tag::None};
1383
+ friend struct WeakIValue;
1384
+ };
1385
+
1386
+ struct TORCH_API WeakIValue final {
1387
+ WeakIValue() = default;
1388
+
1389
+ WeakIValue(const WeakIValue& rhs)
1390
+ : payload(rhs.payload),
1391
+ tag(rhs.tag),
1392
+ is_intrusive_ptr(rhs.is_intrusive_ptr) {
1393
+ if (is_intrusive_ptr &&
1394
+ payload.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()) {
1395
+ c10::raw::weak_intrusive_ptr::incref(payload.as_intrusive_ptr);
1396
+ }
1397
+ }
1398
+ WeakIValue(const IValue& rhs)
1399
+ : tag(rhs.tag), is_intrusive_ptr(rhs.isIntrusivePtrLegacyBehavior()) {
1400
+ if (rhs.isTensor()) {
1401
+ payload.as_intrusive_ptr = rhs.unsafeToTensorImpl();
1402
+ is_intrusive_ptr = true;
1403
+ } else {
1404
+ payload = rhs.payload.u;
1405
+ }
1406
+ if (is_intrusive_ptr) {
1407
+ if (payload.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()) {
1408
+ c10::raw::weak_intrusive_ptr::incref(payload.as_intrusive_ptr);
1409
+ }
1410
+ }
1411
+ }
1412
+ WeakIValue(WeakIValue&& rhs) noexcept : WeakIValue() {
1413
+ swap(rhs);
1414
+ }
1415
+ ~WeakIValue() {
1416
+ if (is_intrusive_ptr &&
1417
+ payload.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()) {
1418
+ c10::raw::weak_intrusive_ptr::decref(payload.as_intrusive_ptr);
1419
+ }
1420
+ }
1421
+ WeakIValue& operator=(WeakIValue&& rhs) & noexcept {
1422
+ WeakIValue(std::move(rhs)).swap(*this); // this also sets rhs to None
1423
+ return *this;
1424
+ }
1425
+ WeakIValue& operator=(WeakIValue const& rhs) & {
1426
+ WeakIValue(rhs).swap(*this);
1427
+ return *this;
1428
+ }
1429
+ void swap(WeakIValue& rhs) noexcept {
1430
+ std::swap(payload, rhs.payload);
1431
+ std::swap(is_intrusive_ptr, rhs.is_intrusive_ptr);
1432
+ std::swap(tag, rhs.tag);
1433
+ }
1434
+
1435
+ bool isSameIdentity(const WeakIValue& rhs) const {
1436
+ return payload.as_int == rhs.payload.as_int && tag == rhs.tag &&
1437
+ is_intrusive_ptr == rhs.is_intrusive_ptr;
1438
+ }
1439
+
1440
+ IValue lock() const {
1441
+ if (!is_intrusive_ptr) {
1442
+ IValue::Payload newPayload;
1443
+ newPayload.u = payload;
1444
+ return IValue(newPayload, tag);
1445
+ }
1446
+ if (IValue::Tag::Tensor == tag) {
1447
+ auto temp =
1448
+ c10::weak_intrusive_ptr<at::TensorImpl, c10::UndefinedTensorImpl>::
1449
+ reclaim(static_cast<at::TensorImpl*>(payload.as_intrusive_ptr));
1450
+ c10::intrusive_ptr<at::TensorImpl, c10::UndefinedTensorImpl> ip(
1451
+ temp.lock());
1452
+ temp.release();
1453
+ if (!ip) {
1454
+ return IValue();
1455
+ } else {
1456
+ return IValue(at::Tensor(std::move(ip)));
1457
+ }
1458
+ } else {
1459
+ auto temp = c10::weak_intrusive_ptr<c10::intrusive_ptr_target>::reclaim(
1460
+ payload.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()
1461
+ ? nullptr
1462
+ : payload.as_intrusive_ptr);
1463
+ IValue::Payload pl;
1464
+ pl.u.as_intrusive_ptr = temp.lock().release();
1465
+ temp.release();
1466
+ if (!pl.u.as_intrusive_ptr) {
1467
+ return IValue();
1468
+ } else {
1469
+ return IValue(pl, tag);
1470
+ }
1471
+ }
1472
+ }
1473
+
1474
+ size_t use_count() const noexcept {
1475
+ if (!is_intrusive_ptr) {
1476
+ return 1;
1477
+ }
1478
+ auto temp = c10::weak_intrusive_ptr<
1479
+ c10::intrusive_ptr_target,
1480
+ c10::UndefinedTensorImpl>::reclaim(payload.as_intrusive_ptr);
1481
+ size_t result = temp.use_count();
1482
+ temp.release();
1483
+ return result;
1484
+ }
1485
+
1486
+ size_t weak_use_count() const noexcept {
1487
+ if (!is_intrusive_ptr) {
1488
+ return 1;
1489
+ }
1490
+ auto temp = c10::weak_intrusive_ptr<
1491
+ c10::intrusive_ptr_target,
1492
+ c10::UndefinedTensorImpl>::reclaim(payload.as_intrusive_ptr);
1493
+ size_t result = temp.weak_use_count();
1494
+ temp.release();
1495
+ return result;
1496
+ }
1497
+ size_t hash() const {
1498
+ return payload.as_int;
1499
+ }
1500
+
1501
+ private:
1502
+ using Payload = IValue::Payload::TriviallyCopyablePayload;
1503
+ Payload payload;
1504
+ IValue::Tag tag{IValue::Tag::None};
1505
+ bool is_intrusive_ptr{false};
1506
+ };
1507
+
1508
+ // An owning pointer to a type. When the type is class type, it requires a pair
1509
+ // of shared_ptrs to the class type and its owning CU, so that the class type is
1510
+ // guaranteed to stay alive as long as we hold this object.
1511
+ struct TORCH_API StrongTypePtr {
1512
+ StrongTypePtr(std::shared_ptr<torch::jit::CompilationUnit> cu, TypePtr type);
1513
+
1514
+ std::shared_ptr<torch::jit::CompilationUnit> cu_;
1515
+ TypePtr type_;
1516
+ };
1517
+
1518
+ // [Constant Object Weak CompilationUnit Reference]
1519
+ // A non owning pointer to a type. When a class get inserted as a constant
1520
+ // into a graph, if we used a strong pointer we would have a circular reference
1521
+ // from Object -> CompilationUnit and CompilationUnit -> Graph (which owns the
1522
+ // Constant Object)
1523
+ struct TORCH_API WeakTypePtr {
1524
+ WeakTypePtr(std::weak_ptr<torch::jit::CompilationUnit> cu, TypePtr type);
1525
+
1526
+ std::weak_ptr<torch::jit::CompilationUnit> cu_;
1527
+ TypePtr type_;
1528
+ };
1529
+
1530
+ // internal build errors with std::variant :/
1531
+ struct WeakOrStrongCompilationUnit {
1532
+ explicit WeakOrStrongCompilationUnit(
1533
+ std::shared_ptr<torch::jit::CompilationUnit> shared_cu)
1534
+ : strong_ptr_(std::move(shared_cu)), weak_ptr_(std::nullopt) {}
1535
+
1536
+ explicit WeakOrStrongCompilationUnit(
1537
+ std::weak_ptr<torch::jit::CompilationUnit> weak_cu)
1538
+ : strong_ptr_(std::nullopt), weak_ptr_(std::move(weak_cu)) {}
1539
+
1540
+ std::shared_ptr<torch::jit::CompilationUnit> getStrongRefOrThrow() const {
1541
+ TORCH_INTERNAL_ASSERT(strong_ptr_.has_value());
1542
+ return *strong_ptr_;
1543
+ }
1544
+
1545
+ std::weak_ptr<torch::jit::CompilationUnit> getWeakRefOrThrow() const {
1546
+ TORCH_INTERNAL_ASSERT(weak_ptr_.has_value());
1547
+ return *weak_ptr_;
1548
+ }
1549
+
1550
+ bool holdingStrongRef() const {
1551
+ return strong_ptr_.has_value();
1552
+ }
1553
+
1554
+ bool holdingEmptyStrongRef() const {
1555
+ return strong_ptr_ == nullptr;
1556
+ }
1557
+
1558
+ std::optional<std::shared_ptr<torch::jit::CompilationUnit>> strong_ptr_;
1559
+ std::optional<std::weak_ptr<torch::jit::CompilationUnit>> weak_ptr_;
1560
+ };
1561
+
1562
+ // An Object will hold a non-owning Compilation Unit reference if it is a
1563
+ // Constant in the graph and a Owning reference otherwise
1564
+ struct TORCH_API WeakOrStrongTypePtr {
1565
+ explicit WeakOrStrongTypePtr(WeakTypePtr weak)
1566
+ : cu_(WeakOrStrongCompilationUnit(std::move(weak.cu_))),
1567
+ type_(std::move(weak.type_)) {}
1568
+ explicit WeakOrStrongTypePtr(StrongTypePtr strong)
1569
+ : cu_(WeakOrStrongCompilationUnit(std::move(strong.cu_))),
1570
+ type_(std::move(strong.type_)) {}
1571
+ explicit WeakOrStrongTypePtr(WeakOrStrongCompilationUnit cu, TypePtr type)
1572
+ : cu_(std::move(cu)), type_(std::move(type)) {}
1573
+ WeakTypePtr asWeakTypePtr() const;
1574
+
1575
+ WeakOrStrongCompilationUnit cu_;
1576
+ TypePtr type_;
1577
+
1578
+ bool holds_strong_ref() const {
1579
+ return cu_.holdingStrongRef();
1580
+ }
1581
+
1582
+ bool holds_empty_strong_ref() const {
1583
+ return cu_.holdingEmptyStrongRef();
1584
+ }
1585
+ };
1586
+
1587
+ } // namespace c10
1588
+
1589
+ #include <ATen/core/ivalue_inl.h> // IWYU pragma: keep
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue_inl.h ADDED
@@ -0,0 +1,2569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <condition_variable>
4
+ #include <memory>
5
+ #include <optional>
6
+ #include <tuple>
7
+ #include <type_traits>
8
+ #include <utility>
9
+
10
+ #include <ATen/core/Dict.h>
11
+ #include <ATen/core/List.h>
12
+ #include <ATen/core/IListRef.h>
13
+ #include <ATen/core/functional.h>
14
+ #include <ATen/core/jit_type.h>
15
+ #include <ATen/core/qualified_name.h>
16
+ #include <ATen/core/rref_interface.h>
17
+ #include <ATen/core/symbol.h>
18
+ #include <c10/core/DeviceGuard.h>
19
+ #include <c10/core/Event.h>
20
+ #include <c10/core/Scalar.h>
21
+ #include <c10/core/Stream.h>
22
+ #include <c10/core/StreamGuard.h>
23
+ #include <c10/core/TensorImpl.h>
24
+ #include <c10/core/UndefinedTensorImpl.h>
25
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
26
+ #include <c10/util/FunctionRef.h>
27
+ #include <c10/util/Logging.h>
28
+ #include <c10/util/hash.h>
29
+ #include <c10/util/intrusive_ptr.h>
30
+ #include <c10/util/irange.h>
31
+
32
+ namespace torch {
33
+ namespace jit {
34
+ struct Function;
35
+ struct CompilationUnit;
36
+ } // namespace jit
37
+ TORCH_API bool isCustomClass(const c10::IValue& v);
38
+ } // namespace torch
39
+ namespace c10 {
40
+ struct IValue;
41
+ struct ClassType;
42
+ struct TupleType;
43
+ struct EnumType;
44
+ struct InferredType;
45
+
46
+ // For custom class __init__ registration, we need to pass in a function
47
+ // that looks like this: [](IValue x, args...)
48
+
49
+ // However, make_boxed_from_unboxed_functor.h automatically sets the input types
50
+ // of the function by introspecting the types of the functor (which is IValue in
51
+ // this case). However, we need the type it binds to be Foo.
52
+
53
+ // Instead, we pass in a lambda [](ivalue_holder<CurClass> x, args...) from
54
+ // which getTypePtr can recover the original class pointer.
55
+
56
+ template <typename TaggedCapsuleType>
57
+ struct tagged_capsule {
58
+ IValue ivalue;
59
+ };
60
+
61
+ template <class T, class NullType>
62
+ c10::intrusive_ptr<T, NullType> IValue::moveToIntrusivePtr() {
63
+ auto t = c10::intrusive_ptr<T, NullType>::reclaim(
64
+ payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()
65
+ ? NullType::singleton()
66
+ : static_cast<T*>(payload.u.as_intrusive_ptr));
67
+ clearToNone();
68
+ return t;
69
+ }
70
+ template <typename T, class NullType>
71
+ c10::intrusive_ptr<T, NullType> IValue::toIntrusivePtr() const {
72
+ if (payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()) {
73
+ return c10::intrusive_ptr<T, NullType>();
74
+ }
75
+ c10::raw::intrusive_ptr::incref(payload.u.as_intrusive_ptr);
76
+ return c10::intrusive_ptr<T, NullType>::reclaim(
77
+ static_cast<T*>(payload.u.as_intrusive_ptr));
78
+ }
79
+
80
+ template <class T, class U>
81
+ intrusive_ptr<T> static_intrusive_pointer_cast(intrusive_ptr<U> r) {
82
+ return intrusive_ptr<T>::reclaim(static_cast<T*>(r.release()));
83
+ }
84
+
85
+ template <class T, class U>
86
+ intrusive_ptr<T> dynamic_intrusive_pointer_cast(intrusive_ptr<U> r) {
87
+ return intrusive_ptr<T>::reclaim(dynamic_cast<T*>(r.release()));
88
+ }
89
+
90
+ inline c10::intrusive_ptr<ivalue::Future> IValue::toFuture() && {
91
+ AT_ASSERT(isFuture(), "Expected Future but got ", tagKind());
92
+ return moveToIntrusivePtr<ivalue::Future>();
93
+ }
94
+ inline c10::intrusive_ptr<ivalue::Future> IValue::toFuture() const& {
95
+ AT_ASSERT(isFuture(), "Expected Future but got ", tagKind());
96
+ return toIntrusivePtr<ivalue::Future>();
97
+ }
98
+ inline c10::intrusive_ptr<ivalue::Await> IValue::toAwait() && {
99
+ AT_ASSERT(isAwait(), "Expected Await but got ", tagKind());
100
+ return moveToIntrusivePtr<ivalue::Await>();
101
+ }
102
+ inline c10::intrusive_ptr<ivalue::Await> IValue::toAwait() const& {
103
+ AT_ASSERT(isAwait(), "Expected Await but got ", tagKind());
104
+ return toIntrusivePtr<ivalue::Await>();
105
+ }
106
+ inline c10::intrusive_ptr<c10::RRefInterface> IValue::toRRef() && {
107
+ AT_ASSERT(isRRef(), "Expected RRef but got ", tagKind());
108
+ return moveToIntrusivePtr<c10::RRefInterface>();
109
+ }
110
+ inline c10::intrusive_ptr<c10::RRefInterface> IValue::toRRef() const& {
111
+ AT_ASSERT(isRRef(), "Expected RRef but got ", tagKind());
112
+ return toIntrusivePtr<c10::RRefInterface>();
113
+ }
114
+ inline c10::intrusive_ptr<at::Quantizer> IValue::toQuantizer() && {
115
+ AT_ASSERT(isQuantizer(), "Expected Quantizer but got ", tagKind());
116
+ return moveToIntrusivePtr<at::Quantizer>();
117
+ }
118
+ inline c10::intrusive_ptr<at::Quantizer> IValue::toQuantizer() const& {
119
+ AT_ASSERT(isQuantizer(), "Expected Quantizer but got ", tagKind());
120
+ return toIntrusivePtr<at::Quantizer>();
121
+ }
122
+ inline c10::intrusive_ptr<ivalue::ConstantString> IValue::toString() && {
123
+ AT_ASSERT(isString(), "Expected String but got ", tagKind());
124
+ return moveToIntrusivePtr<ivalue::ConstantString>();
125
+ }
126
+ inline c10::intrusive_ptr<ivalue::ConstantString> IValue::toString() const& {
127
+ AT_ASSERT(isString(), "Expected String but got ", tagKind());
128
+ return toIntrusivePtr<ivalue::ConstantString>();
129
+ }
130
+ inline c10::intrusive_ptr<ivalue::Object> IValue::toObject() && {
131
+ AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
132
+ return moveToIntrusivePtr<ivalue::Object>();
133
+ }
134
+ inline c10::intrusive_ptr<ivalue::Object> IValue::toObject() const& {
135
+ AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
136
+ return toIntrusivePtr<ivalue::Object>();
137
+ }
138
+ inline c10::intrusive_ptr<ivalue::PyObjectHolder> IValue::
139
+ toPyObjectHolder() && {
140
+ TORCH_INTERNAL_ASSERT(isPyObject(), "Expected PyObject but got ", tagKind());
141
+ return moveToIntrusivePtr<ivalue::PyObjectHolder>();
142
+ }
143
+ inline c10::intrusive_ptr<ivalue::PyObjectHolder> IValue::toPyObjectHolder()
144
+ const& {
145
+ TORCH_INTERNAL_ASSERT(isPyObject(), "Expected PyObject but got ", tagKind());
146
+ return toIntrusivePtr<ivalue::PyObjectHolder>();
147
+ }
148
+ inline c10::intrusive_ptr<ivalue::EnumHolder> IValue::toEnumHolder() && {
149
+ TORCH_INTERNAL_ASSERT(isEnum(), "Expected Enum but got ", tagKind());
150
+ return moveToIntrusivePtr<ivalue::EnumHolder>();
151
+ }
152
+ inline c10::intrusive_ptr<ivalue::EnumHolder> IValue::toEnumHolder() const& {
153
+ TORCH_INTERNAL_ASSERT(isEnum(), "Expected Enum but got ", tagKind());
154
+ return toIntrusivePtr<ivalue::EnumHolder>();
155
+ }
156
+ inline c10::complex<double> IValue::toComplexDouble() const {
157
+ TORCH_INTERNAL_ASSERT(isComplexDouble(), "Expected ComplexDouble but got ", tagKind());
158
+ auto ptr = toIntrusivePtr<ivalue::ComplexHolder>();
159
+ return (*ptr).val;
160
+ }
161
+ inline at::Tensor IValue::toTensor() && {
162
+ if (C10_UNLIKELY(!isTensor())) {
163
+ reportToTensorTypeError();
164
+ }
165
+ auto result = std::move(payload.as_tensor);
166
+ // As far as I can tell, omitting the usual explicit destructor call
167
+ // is not UB in and of itself, and it's a slight perf win. The
168
+ // destructor is a no-op, because the moved-from Tensor is
169
+ // effectively an intrusive_ptr in the null state, so we don't need
170
+ // the behavior for correctness reasons either. Leaving this
171
+ // explanatory comment, including commented-out destructor call, to
172
+ // make this abundantly clear.
173
+ //
174
+ // payload.as_tensor.~Tensor();
175
+ clearToNone();
176
+ return result;
177
+ }
178
+ inline at::Tensor& IValue::toTensor() & {
179
+ if (C10_UNLIKELY(!isTensor())) {
180
+ reportToTensorTypeError();
181
+ }
182
+ return payload.as_tensor;
183
+ }
184
+ inline const at::Tensor& IValue::toTensor() const& {
185
+ if (C10_UNLIKELY(!isTensor())) {
186
+ reportToTensorTypeError();
187
+ }
188
+ return payload.as_tensor;
189
+ }
190
+ inline c10::Storage IValue::toStorage() && {
191
+ AT_ASSERT(isStorage(), "Expected Storage but got ", tagKind());
192
+ return c10::Storage(
193
+ moveToIntrusivePtr<at::StorageImpl>());
194
+ }
195
+ inline c10::Storage IValue::toStorage() const& {
196
+ AT_ASSERT(isStorage(), "Expected Storage but got ", tagKind());
197
+ return c10::Storage(toIntrusivePtr<at::StorageImpl>());
198
+ }
199
+ inline c10::Stream IValue::toStream() && {
200
+ AT_ASSERT(isStream(), "Expected Stream but got ", tagKind());
201
+ auto ptr = toIntrusivePtr<ivalue::StreamData3Holder>();
202
+ return c10::Stream::unpack3((*ptr).val.stream_id,
203
+ (*ptr).val.device_index,
204
+ (*ptr).val.device_type);
205
+ }
206
+ inline c10::Stream IValue::toStream() const& {
207
+ AT_ASSERT(isStream(), "Expected Stream but got ", tagKind());
208
+ auto ptr = toIntrusivePtr<ivalue::StreamData3Holder>();
209
+ return c10::Stream::unpack3((*ptr).val.stream_id,
210
+ (*ptr).val.device_index,
211
+ (*ptr).val.device_type);
212
+ }
213
+ inline c10::intrusive_ptr<caffe2::Blob> IValue::toBlob() && {
214
+ AT_ASSERT(isBlob(), "Expected Blob but got ", tagKind());
215
+ return moveToIntrusivePtr<caffe2::Blob>();
216
+ }
217
+ inline c10::intrusive_ptr<caffe2::Blob> IValue::toBlob() const& {
218
+ AT_ASSERT(isBlob(), "Expected Blob but got ", tagKind());
219
+ return toIntrusivePtr<caffe2::Blob>();
220
+ ;
221
+ }
222
+ inline c10::intrusive_ptr<torch::CustomClassHolder> IValue::toCapsule() && {
223
+ TORCH_INTERNAL_ASSERT(isCapsule());
224
+ return moveToIntrusivePtr<torch::CustomClassHolder>();
225
+ }
226
+ inline c10::intrusive_ptr<torch::CustomClassHolder> IValue::toCapsule() const& {
227
+ TORCH_INTERNAL_ASSERT(isCapsule());
228
+ return toIntrusivePtr<torch::CustomClassHolder>();
229
+ }
230
+ inline at::Generator IValue::toGenerator() && {
231
+ AT_ASSERT(isGenerator(), "Expected Generator but got ", tagKind());
232
+ return at::Generator(moveToIntrusivePtr<at::GeneratorImpl>());
233
+ }
234
+ inline at::Generator IValue::toGenerator() const& {
235
+ AT_ASSERT(isGenerator(), "Expected Generator but got ", tagKind());
236
+ return at::Generator(toIntrusivePtr<at::GeneratorImpl>());
237
+ }
238
+ inline c10::SymInt IValue::toSymInt() && {
239
+ AT_ASSERT(isSymInt() || isInt(), "Expected SymInt or int but got ", tagKind());
240
+ if (isSymInt()) {
241
+ return c10::SymInt(moveToIntrusivePtr<c10::SymNodeImpl>());
242
+ } else {
243
+ return c10::SymInt(payload.u.as_int);
244
+ }
245
+ }
246
+ inline c10::SymInt IValue::toSymInt() const& {
247
+ AT_ASSERT(isSymInt() || isInt(), "Expected SymInt or int but got ", tagKind());
248
+ if (isSymInt()) {
249
+ return c10::SymInt(toIntrusivePtr<c10::SymNodeImpl>());
250
+ } else {
251
+ return c10::SymInt(payload.u.as_int);
252
+ }
253
+ }
254
+ inline c10::SymFloat IValue::toSymFloat() && {
255
+ AT_ASSERT(isSymFloat() || isDouble(), "Expected SymFloat or double but got ", tagKind());
256
+ if (isSymFloat()) {
257
+ return c10::SymFloat(moveToIntrusivePtr<c10::SymNodeImpl>());
258
+ } else {
259
+ return c10::SymFloat(payload.u.as_double);
260
+ }
261
+ }
262
+ inline c10::SymFloat IValue::toSymFloat() const& {
263
+ AT_ASSERT(isSymFloat() || isDouble(), "Expected SymFloat or double but got ", tagKind());
264
+ if (isSymFloat()) {
265
+ return c10::SymFloat(toIntrusivePtr<c10::SymNodeImpl>());
266
+ } else {
267
+ return c10::SymFloat(payload.u.as_double);
268
+ }
269
+ }
270
+ inline c10::SymBool IValue::toSymBool() && {
271
+ AT_ASSERT(isSymBool() || isBool(), "Expected SymBool or boolean but got ", tagKind());
272
+ if (isSymBool()) {
273
+ return c10::SymBool(moveToIntrusivePtr<c10::SymNodeImpl>());
274
+ } else {
275
+ return c10::SymBool(payload.u.as_bool);
276
+ }
277
+ }
278
+
279
+ inline c10::SymBool IValue::toSymBool() const& {
280
+ AT_ASSERT(isSymBool() || isBool(), "Expected SymBool or boolean but got ", tagKind());
281
+ if (isSymBool()) {
282
+ return c10::SymBool(toIntrusivePtr<c10::SymNodeImpl>());
283
+ } else {
284
+ return c10::SymBool(payload.u.as_bool);
285
+ }
286
+ }
287
+
288
+ namespace ivalue {
289
+
290
+ void TORCH_API
291
+ checkCustomClassType(const ClassType* expected_type, const Type* actual_type);
292
+
293
+ template <typename T>
294
+ using Shared = c10::intrusive_ptr<T>;
295
+
296
+ // string
297
+ struct TORCH_API ConstantString final : c10::intrusive_ptr_target {
298
+ private:
299
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
300
+ const std::string str_;
301
+
302
+ public:
303
+ ConstantString(std::string str) : str_(std::move(str)) {}
304
+ ConstantString(std::string_view str) : str_(std::string(str)) {}
305
+ static c10::intrusive_ptr<ConstantString> create(std::string str_);
306
+ static c10::intrusive_ptr<ConstantString> create(std::string_view str_);
307
+ static c10::intrusive_ptr<ConstantString> create(const char* str_);
308
+
309
+ const std::string& string() const {
310
+ return str_;
311
+ }
312
+ std::string_view string_view() const {
313
+ return str_;
314
+ }
315
+
316
+ operator const std::string&() const {
317
+ return string();
318
+ }
319
+ TORCH_API friend std::ostream& operator<<(
320
+ std::ostream& out,
321
+ const ConstantString& v);
322
+ };
323
+
324
+ struct Future;
325
+
326
+ struct TORCH_API TupleElements {
327
+ private:
328
+ size_t inlineSize_;
329
+ // We represent TupleElements this way to save doing a heap
330
+ // allocation in the common (at least for unpickling) case where we
331
+ // have only 3 elements. We have our own union instead of
332
+ // c10::SmallVector<IValue> because c10::SmallVector<IValue> always
333
+ // stores the begin/end/capacity pointers, which would be a waste of
334
+ // space in our use case.
335
+ union {
336
+ std::vector<IValue> elementsVector_;
337
+ // Don't want to declare a std::array because the convenient
338
+ // iteration and size members are a footgun in this case -- the
339
+ // actual size of the array may be smaller than 3!
340
+ // NOLINTNEXTLINE(*c-arrays*)
341
+ IValue elementsInline_[3];
342
+ };
343
+
344
+ void destroyInline() {
345
+ for (const auto ii : c10::irange(inlineSize_)) {
346
+ elementsInline_[ii].~IValue();
347
+ }
348
+ }
349
+ public:
350
+
351
+ using iterator = IValue*;
352
+ using const_iterator = const IValue*;
353
+
354
+ TupleElements() : inlineSize_(0) {
355
+ new (&elementsVector_) std::vector<IValue>();
356
+ }
357
+
358
+ explicit TupleElements(std::vector<IValue> elements)
359
+ : inlineSize_(0), elementsVector_(std::move(elements)) {}
360
+
361
+ explicit TupleElements(c10::ArrayRef<IValue> elements)
362
+ : inlineSize_(elements.size() <= 3 ? elements.size() : 0) {
363
+ switch (inlineSize_) {
364
+ case 3:
365
+ new (&elementsInline_[2]) IValue(elements[2]);
366
+ [[fallthrough]];
367
+ case 2:
368
+ new (&elementsInline_[1]) IValue(elements[1]);
369
+ [[fallthrough]];
370
+ case 1:
371
+ new (&elementsInline_[0]) IValue(elements[0]);
372
+ break;
373
+ case 0:
374
+ new (&elementsVector_) std::vector<IValue>(elements.begin(), elements.end());
375
+ break;
376
+ }
377
+ }
378
+
379
+ explicit TupleElements(IValue&& e1)
380
+ : inlineSize_(1) {
381
+ new (&elementsInline_[0]) IValue(std::move(e1));
382
+ }
383
+
384
+ explicit TupleElements(IValue&& e1, IValue&& e2)
385
+ : inlineSize_(2) {
386
+ new (&elementsInline_[0]) IValue(std::move(e1));
387
+ new (&elementsInline_[1]) IValue(std::move(e2));
388
+ }
389
+
390
+ explicit TupleElements(IValue&& e1, IValue&& e2, IValue&& e3)
391
+ : inlineSize_(3) {
392
+ new (&elementsInline_[0]) IValue(std::move(e1));
393
+ new (&elementsInline_[1]) IValue(std::move(e2));
394
+ new (&elementsInline_[2]) IValue(std::move(e3));
395
+ }
396
+
397
+ ~TupleElements() {
398
+ if (inlineSize_) {
399
+ destroyInline();
400
+ } else {
401
+ elementsVector_.~vector();
402
+ }
403
+ }
404
+
405
+ // It would be nice to make this noncopyable to prevent people from
406
+ // writing code like `auto output =
407
+ // forward(...).toTupleRef().elements()` (which does refcount bumps on
408
+ // each element, unlike the more efficient but verbose
409
+ // ```
410
+ // auto outputIntrusivePtr = forward(...).toTuple();
411
+ // const auto& output = outputIntrusivePtr->elements();
412
+ // ```
413
+ // ), but there is simply an overwhelming amount of code that does
414
+ // it the inefficient way.
415
+ // See also operator std::vector below.
416
+ TupleElements(const TupleElements& rhs)
417
+ : inlineSize_(rhs.inlineSize_) {
418
+ if (rhs.inlineSize_) {
419
+ for (const auto ii : c10::irange(inlineSize_)) {
420
+ new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
421
+ }
422
+ } else {
423
+ new (&elementsVector_) std::vector<IValue>(rhs.elementsVector_);
424
+ }
425
+ }
426
+
427
+ TupleElements& operator=(const TupleElements& rhs) {
428
+ if (inlineSize_) {
429
+ if (rhs.inlineSize_) {
430
+ for (const auto ii : c10::irange(std::min(inlineSize_, rhs.inlineSize_))) {
431
+ elementsInline_[ii] = rhs.elementsInline_[ii];
432
+ }
433
+ if (rhs.inlineSize_ > inlineSize_) {
434
+ for (const auto ii : c10::irange(inlineSize_, rhs.inlineSize_)) {
435
+ new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
436
+ }
437
+ } else {
438
+ for (const auto ii : c10::irange(rhs.inlineSize_, inlineSize_)) {
439
+ elementsInline_[ii].~IValue();
440
+ }
441
+ }
442
+ } else {
443
+ destroyInline();
444
+ new (&elementsVector_) std::vector<IValue>(rhs.elementsVector_);
445
+ }
446
+ } else {
447
+ if (rhs.inlineSize_) {
448
+ elementsVector_.~vector();
449
+ for (const auto ii : c10::irange(rhs.inlineSize_)) {
450
+ new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
451
+ }
452
+ } else {
453
+ elementsVector_ = rhs.elementsVector_;
454
+ }
455
+ }
456
+ inlineSize_ = rhs.inlineSize_;
457
+ return *this;
458
+ }
459
+
460
+ TupleElements(TupleElements&& rhs) noexcept
461
+ : inlineSize_(rhs.inlineSize_) {
462
+ if (inlineSize_) {
463
+ for (const auto ii : c10::irange(inlineSize_)) {
464
+ new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
465
+ }
466
+ } else {
467
+ new (&elementsVector_) std::vector<IValue>(std::move(rhs.elementsVector_));
468
+ }
469
+ }
470
+
471
+ TupleElements& operator=(TupleElements&& rhs) noexcept {
472
+ if (inlineSize_) {
473
+ if (rhs.inlineSize_) {
474
+ for (const auto ii : c10::irange(std::min(inlineSize_, rhs.inlineSize_))) {
475
+ elementsInline_[ii] = std::move(rhs.elementsInline_[ii]);
476
+ }
477
+ if (rhs.inlineSize_ > inlineSize_) {
478
+ for (const auto ii : c10::irange(inlineSize_, rhs.inlineSize_)) {
479
+ new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
480
+ }
481
+ } else {
482
+ for (const auto ii : c10::irange(rhs.inlineSize_, inlineSize_)) {
483
+ elementsInline_[ii].~IValue();
484
+ }
485
+ }
486
+ } else {
487
+ destroyInline();
488
+ new (&elementsVector_) std::vector<IValue>(std::move(rhs.elementsVector_));
489
+ }
490
+ } else {
491
+ if (rhs.inlineSize_) {
492
+ elementsVector_.~vector();
493
+ for (const auto ii : c10::irange(rhs.inlineSize_)) {
494
+ new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
495
+ }
496
+ } else {
497
+ elementsVector_ = std::move(rhs.elementsVector_);
498
+ }
499
+ }
500
+ inlineSize_ = rhs.inlineSize_;
501
+ return *this;
502
+ }
503
+
504
+ [[nodiscard]] c10::ArrayRef<IValue> asArrayRef() const {
505
+ if (inlineSize_) {
506
+ return c10::ArrayRef<IValue>(elementsInline_, inlineSize_);
507
+ } else {
508
+ return elementsVector_;
509
+ }
510
+ }
511
+
512
+ // Mimic implicit conversion from std::vector to ArrayRef.
513
+ operator c10::ArrayRef<IValue>() const {
514
+ return asArrayRef();
515
+ }
516
+
517
+ static size_t hash(const TupleElements& v) {
518
+ return c10::hash<c10::ArrayRef<IValue>>()(v.asArrayRef());
519
+ }
520
+
521
+ void setContents(std::vector<IValue>&& contents) {
522
+ if (inlineSize_) {
523
+ destroyInline();
524
+ new (&elementsVector_) std::vector<IValue>(std::move(contents));
525
+ inlineSize_ = 0;
526
+ } else {
527
+ elementsVector_ = std::move(contents);
528
+ }
529
+ }
530
+
531
+ [[nodiscard]] bool empty() const {
532
+ return inlineSize_ ? false : elementsVector_.empty();
533
+ }
534
+
535
+ [[nodiscard]] size_t size() const {
536
+ return inlineSize_ ? inlineSize_ : elementsVector_.size();
537
+ }
538
+
539
+ [[nodiscard]] IValue& operator[](size_t idx) {
540
+ if (inlineSize_) {
541
+ return elementsInline_[idx];
542
+ } else {
543
+ return elementsVector_[idx];
544
+ }
545
+ }
546
+
547
+ [[nodiscard]] const IValue& operator[](size_t idx) const {
548
+ if (inlineSize_) {
549
+ return elementsInline_[idx];
550
+ } else {
551
+ return elementsVector_[idx];
552
+ }
553
+ }
554
+
555
+ [[nodiscard]] IValue& at(size_t idx) {
556
+ if (inlineSize_) {
557
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(inlineSize_ <= 3);
558
+ TORCH_CHECK(idx < inlineSize_, "TupleElements: invalid index Index = ", idx, "; Length = ", inlineSize_);
559
+ return elementsInline_[idx];
560
+ } else {
561
+ return elementsVector_.at(idx);
562
+ }
563
+ }
564
+
565
+ [[nodiscard]] const IValue& at(size_t idx) const {
566
+ if (inlineSize_) {
567
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(inlineSize_ <= 3);
568
+ TORCH_CHECK(idx < inlineSize_, "TupleElements: invalid index Index = ", idx, "; Length = ", inlineSize_);
569
+ return elementsInline_[idx];
570
+ } else {
571
+ TORCH_CHECK(idx < elementsVector_.size(), "TupleElements: invalid index Index = ", idx, "; Length = ", elementsVector_.size());
572
+ return elementsVector_.at(idx);
573
+ }
574
+ }
575
+
576
+ [[nodiscard]] iterator begin() {
577
+ if (inlineSize_) {
578
+ return elementsInline_;
579
+ } else {
580
+ return elementsVector_.data();
581
+ }
582
+ }
583
+
584
+ [[nodiscard]] iterator end() {
585
+ if (inlineSize_) {
586
+ return elementsInline_ + inlineSize_;
587
+ } else {
588
+ return elementsVector_.data() + elementsVector_.size();
589
+ }
590
+ }
591
+
592
+ [[nodiscard]] const_iterator begin() const {
593
+ if (inlineSize_) {
594
+ return elementsInline_;
595
+ } else {
596
+ return elementsVector_.data();
597
+ }
598
+ }
599
+
600
+ [[nodiscard]] const_iterator end() const {
601
+ if (inlineSize_) {
602
+ return elementsInline_ + inlineSize_;
603
+ } else {
604
+ return elementsVector_.data() + elementsVector_.size();
605
+ }
606
+ }
607
+
608
+ [[nodiscard]] const_iterator cbegin() const {
609
+ return begin();
610
+ }
611
+
612
+ [[nodiscard]] const_iterator cend() const {
613
+ return end();
614
+ }
615
+
616
+ [[nodiscard]] std::vector<IValue> vec() const& {
617
+ return asArrayRef().vec();
618
+ }
619
+
620
+ [[nodiscard]] IValue& back() {
621
+ return *(end() - 1);
622
+ }
623
+
624
+ [[nodiscard]] const IValue& back() const {
625
+ return *(end() - 1);
626
+ }
627
+
628
+ [[nodiscard]] std::vector<IValue> vec() && {
629
+ std::vector<IValue> result;
630
+ result.reserve(size());
631
+ for (auto&& iv : *this) {
632
+ result.push_back(std::move(iv));
633
+ }
634
+ return result;
635
+ }
636
+
637
+ // More compatibility shims for the overwhelming amount of code that
638
+ // likes to copy tuple elements into a vector; see comment above the
639
+ // copy constructor.
640
+ operator std::vector<IValue>() const & {
641
+ return vec();
642
+ }
643
+
644
+ operator std::vector<IValue>() && {
645
+ return vec();
646
+ }
647
+ };
648
+
649
+ template <typename T>
650
+ struct TupleTypeFactory {};
651
+
652
+ template <>
653
+ struct TORCH_API TupleTypeFactory<TupleType> {
654
+ static TupleTypePtr create(std::vector<TypePtr> types) {
655
+ return TupleType::create(std::move(types));
656
+ }
657
+ static TupleTypePtr fallback(const Type& type);
658
+ };
659
+
660
+ template <>
661
+ struct TORCH_API TupleTypeFactory<c10::DynamicType> {
662
+ static DynamicTypePtr create(const std::vector<TypePtr>& elemTypes);
663
+ static DynamicTypePtr fallback(const Type&);
664
+ };
665
+
666
+ struct TORCH_API Tuple : c10::intrusive_ptr_target {
667
+ private:
668
+ TupleElements elements_;
669
+ mutable c10::TypePtr type_; // lazily computed for unnamed tuples
670
+
671
+ public:
672
+ // named tuples have additional type information, so we
673
+ // directly create them tagged
674
+ static c10::intrusive_ptr<Tuple> createNamed(
675
+ std::vector<IValue> elements_,
676
+ c10::TypePtr type_) {
677
+ return c10::make_intrusive<Tuple>(std::move(elements_), std::move(type_));
678
+ }
679
+
680
+ static c10::intrusive_ptr<Tuple> createNamed(
681
+ TupleElements elements_,
682
+ std::shared_ptr<TupleType> type_) {
683
+ return c10::make_intrusive<Tuple>(std::move(elements_), std::move(type_));
684
+ }
685
+
686
+ static c10::intrusive_ptr<Tuple> createNamed(
687
+ std::initializer_list<IValue> elements_,
688
+ std::shared_ptr<TupleType> type_) {
689
+ return createNamed(TupleElements(c10::ArrayRef<IValue>(elements_)), std::move(type_));
690
+ }
691
+
692
+ // MSVC apparently can't disambiguate the other two overloads of
693
+ // create when passed an initializer_list without this.
694
+ static c10::intrusive_ptr<Tuple> create(std::initializer_list<IValue> elements_) {
695
+ return create(c10::ArrayRef<IValue>(elements_));
696
+ }
697
+
698
+ static c10::intrusive_ptr<Tuple> create(std::vector<IValue> elements_) {
699
+ return c10::make_intrusive<Tuple>(std::move(elements_));
700
+ }
701
+
702
+ static c10::intrusive_ptr<Tuple> create(TupleElements elements_) {
703
+ return c10::make_intrusive<Tuple>(std::move(elements_));
704
+ }
705
+
706
+ static c10::intrusive_ptr<Tuple> create(c10::ArrayRef<IValue> elements_) {
707
+ return create(TupleElements(elements_));
708
+ }
709
+
710
+ static c10::intrusive_ptr<Tuple> create(IValue e1) {
711
+ return c10::make_intrusive<Tuple>(std::move(e1));
712
+ }
713
+
714
+ static c10::intrusive_ptr<Tuple> create(IValue e1, IValue e2) {
715
+ return c10::make_intrusive<Tuple>(std::move(e1), std::move(e2));
716
+ }
717
+
718
+ static c10::intrusive_ptr<Tuple> create(IValue e1, IValue e2, IValue e3) {
719
+ return c10::make_intrusive<Tuple>(std::move(e1), std::move(e2), std::move(e3));
720
+ }
721
+
722
+ private:
723
+ // Workaround inability to use `>` operator in template argument list.
724
+ template <typename... Args>
725
+ static constexpr bool hasMoreThanThreeArgs() {
726
+ return sizeof...(Args) > 3;
727
+ }
728
+
729
+ public:
730
+ template <typename... Args>
731
+ static c10::intrusive_ptr<Tuple> create(Args&&... elements_) {
732
+ switch (sizeof...(Args)) {
733
+ case 1:
734
+ case 2:
735
+ case 3:
736
+ return create(IValue(std::forward<Args>(elements_))...);
737
+ default:
738
+ return create(
739
+ std::vector<IValue>{IValue(std::forward<Args>(elements_))...});
740
+ }
741
+ }
742
+
743
+ // Again, it would be nice to make this noncopyable, but there's a
744
+ // lot of extant code that copies Tuples.
745
+ // Tuple(const Tuple& rhs) = delete;
746
+
747
+ const TupleElements& elements() const& {
748
+ return elements_;
749
+ }
750
+
751
+ TupleElements elements() && {
752
+ return std::move(elements_);
753
+ }
754
+
755
+ void setElements(std::vector<IValue>&& elements) {
756
+ elements_.setContents(std::move(elements));
757
+ }
758
+
759
+ void setElements(TupleElements&& elements) {
760
+ elements_ = std::move(elements);
761
+ }
762
+
763
+ void unsafeSetElement(size_t idx, const IValue& element) {
764
+ elements_[idx] = element;
765
+ }
766
+
767
+ void unsafeSetElement(size_t idx, IValue&& element) {
768
+ elements_[idx] = std::move(element);
769
+ }
770
+
771
+ size_t size() const {
772
+ return elements_.size();
773
+ }
774
+
775
+ template <typename T = c10::TupleType>
776
+ std::shared_ptr<T> type() const {
777
+ if (!type_) {
778
+ type_ = TupleTypeFactory<T>::create(fmap(elements(), [&](const IValue& v) {
779
+ return v.type<typename T::ElementType>();
780
+ }));
781
+ }
782
+ if (auto t = type_->cast<T>()) {
783
+ return t;
784
+ }
785
+ return TupleTypeFactory<T>::fallback(*type_);
786
+ }
787
+
788
+ static size_t hash(const Tuple& t) {
789
+ return c10::get_hash(t.elements());
790
+ }
791
+
792
+ TORCH_API friend bool operator==(
793
+ const ivalue::Tuple& lhs,
794
+ const ivalue::Tuple& rhs);
795
+
796
+ private:
797
+ // NOTE: If we try to avoid the overloads without
798
+ // `std::shared_ptr<TupleType> type` by defaulting it to nullptr, we
799
+ // end up having to call (part of) the shared_ptr destructor for
800
+ // `type` even though we should know statically it won't do
801
+ // anything.
802
+ explicit Tuple(std::vector<IValue> elements)
803
+ : elements_(std::move(elements)){}
804
+
805
+ explicit Tuple(std::vector<IValue> elements, c10::TypePtr type)
806
+ : elements_(std::move(elements)), type_(std::move(type)) {}
807
+
808
+ explicit Tuple(TupleElements&& elements)
809
+ : elements_(std::move(elements)) {}
810
+
811
+ explicit Tuple(TupleElements&& elements, std::shared_ptr<TupleType> type)
812
+ : elements_(std::move(elements)), type_(std::move(type)) {}
813
+
814
+ explicit Tuple(IValue&& e1)
815
+ : elements_(std::move(e1)) {}
816
+
817
+ explicit Tuple(IValue&& e1, std::shared_ptr<TupleType> type)
818
+ : elements_(std::move(e1)), type_(std::move(type)) {}
819
+
820
+ explicit Tuple(IValue&& e1, IValue&& e2)
821
+ : elements_(std::move(e1), std::move(e2)) {}
822
+
823
+ explicit Tuple(IValue&& e1, IValue&& e2, std::shared_ptr<TupleType> type)
824
+ : elements_(std::move(e1), std::move(e2)), type_(std::move(type)) {}
825
+
826
+ explicit Tuple(IValue&& e1, IValue&& e2, IValue&& e3)
827
+ : elements_(std::move(e1), std::move(e2), std::move(e3)) {}
828
+
829
+ explicit Tuple(IValue&& e1, IValue&& e2, IValue&& e3, std::shared_ptr<TupleType> type)
830
+ : elements_(std::move(e1), std::move(e2), std::move(e3)), type_(std::move(type)) {}
831
+
832
+ friend class c10::intrusive_ptr<Tuple>;
833
+ };
834
+
835
+ struct Object;
836
+ struct PyObjectHolder;
837
+ struct EnumHolder;
838
+ } // namespace ivalue
839
+
840
+ // Future
841
+ struct C10_EXPORT ivalue::Future final : c10::intrusive_ptr_target {
842
+ private:
843
+ // Keep this private in order to force users to go through make_intrusive and
844
+ // thus prevent creating a Future that's not held by an intrusive_ptr.
845
+ explicit Future(TypePtr type, std::vector<c10::Device> devices={})
846
+ : type_(std::move(type)),
847
+ impl_(getTypeOfDevices(devices)),
848
+ devices_(sortAndDeduplicateDevices(impl_, std::move(devices))) {}
849
+
850
+ friend c10::intrusive_ptr<Future>;
851
+
852
+ struct FutureCallback {
853
+ std::function<void(Future&)> callback;
854
+ bool uses_future; // whether the Future& passed in is actually used
855
+
856
+ template <typename T>
857
+ FutureCallback(T callback, bool uses_future)
858
+ : callback(std::move(callback)), uses_future(uses_future) {}
859
+ };
860
+
861
+ public:
862
+ Future(const Future&) = delete;
863
+ Future(Future&&) = delete;
864
+ Future& operator=(const Future&) = delete;
865
+ Future& operator=(Future&&) = delete;
866
+
867
+ // Destructor
868
+ // Explicitly destroy events under device guard, otherwise it can lead to
869
+ // extra context being created on device 0. Reason: python garbage collector
870
+ // calls this destructor, but python GC does not have a device context, so a
871
+ // "default" one (usually on device 0) could be created when we go down the
872
+ // line of event destroy.
873
+ ~Future() override {
874
+ while (!events_.empty()) {
875
+ c10::OptionalDeviceGuard deviceGuard(events_.back().device());
876
+ events_.pop_back();
877
+ }
878
+ }
879
+
880
+ struct TORCH_API FutureError final : public std::exception {
881
+ explicit FutureError(std::string&& error_msg_)
882
+ : error_msg(std::move(error_msg_)) {}
883
+
884
+ FutureError() = default;
885
+
886
+ const char* what() const noexcept override {
887
+ return error_msg.c_str();
888
+ }
889
+
890
+ std::string error_msg;
891
+ };
892
+
893
+ /**
894
+ * Wait on the future until it completes.
895
+ */
896
+ void wait() {
897
+ std::unique_lock<std::mutex> lock(mutex_);
898
+ finished_cv_.wait(lock, [&]() -> bool { return completed_; });
899
+ synchronizeWithCurrentStreams();
900
+ }
901
+
902
+ /**
903
+ * Wait on the future until it completes and throw an
904
+ * exception if an error exists.
905
+ */
906
+ void waitAndThrow() {
907
+ wait();
908
+
909
+ if (eptr_) {
910
+ std::rethrow_exception(eptr_);
911
+ }
912
+ }
913
+
914
+ /**
915
+ * Explicitly mark the future as completed with the output value. Optionally,
916
+ * the storages for all tensors in IValue can be passed as well. The DataPtrs
917
+ * of these storages are used to synchronize CUDA streams. If storages isn't
918
+ * given we will attempt to extract it from the value, if we need to (this
919
+ * happens if a non-empty set of devices was given to the constructor). Thus
920
+ * one only needs to provide storages when 1) they cannot be extracted through
921
+ * IValue::getSubValues() or through pickling in case of Python object; or
922
+ * when 2) customized storage extraction is more efficient.
923
+ */
924
+ using WeakStorage = c10::weak_intrusive_ptr<c10::StorageImpl>;
925
+ void markCompleted(
926
+ IValue value,
927
+ std::optional<std::vector<WeakStorage>> storages = std::nullopt) {
928
+ // Start by performing all steps that can throw, before setting any field.
929
+ // Do this before even acquiring the mutex, because extractStorages might
930
+ // acquire the GIL, which could lead to a lock inversion with our mutex.
931
+ // See https://github.com/pytorch/pytorch/issues/58239.
932
+ std::vector<WeakStorage> actualStorages;
933
+ std::vector<c10::Device> usedDevices;
934
+ try {
935
+ // FIXME We should always extract DataPtrs, in order to catch the case of
936
+ // users using CUDA values but forgetting to set devices, which currently
937
+ // leads to a silent synchronization/correctness issue. However, as this
938
+ // might worsen perf in CPU-only cases, we should only do so after careful
939
+ // benchmarks.
940
+ if (impl_.type() != c10::kCPU) {
941
+ actualStorages =
942
+ storages.has_value() ? std::move(*storages) : extractStorages(value);
943
+ usedDevices = getDevicesOfStorages(impl_, actualStorages);
944
+ ensureIsSubsetOfDevices(usedDevices, devices_);
945
+ }
946
+ } catch (const std::exception&) {
947
+ setError(std::current_exception());
948
+ return;
949
+ }
950
+
951
+ std::unique_lock<std::mutex> lock(mutex_);
952
+ TORCH_CHECK(
953
+ !completed(),
954
+ "Attempting to mark a completed Future as complete again. Note that "
955
+ "a Future can only be marked completed once.");
956
+
957
+ // Only set value_ and completed_ flag once all checks and preparation steps
958
+ // have returned successfully to allow for proper error propagation.
959
+ value_ = std::move(value);
960
+ completed_ = true;
961
+
962
+ currentDevice_ = impl_.getDevice();
963
+ storages_ = std::move(actualStorages);
964
+ for (const c10::Device& device : usedDevices) {
965
+ c10::Event event(impl_.type());
966
+ event.record(impl_.getStream(device));
967
+ events_.push_back(std::move(event));
968
+ }
969
+
970
+ std::vector<FutureCallback> cbs;
971
+ cbs.swap(callbacks_);
972
+ lock.unlock();
973
+
974
+ finished_cv_.notify_all();
975
+ for (const auto& callback : cbs) {
976
+ invokeCallback(callback.callback, callback.uses_future);
977
+ }
978
+ }
979
+
980
+ void markCompleted() {
981
+ markCompleted(IValue{});
982
+ }
983
+
984
+ void setError(std::exception_ptr eptr) {
985
+ std::unique_lock<std::mutex> lock(mutex_);
986
+ setErrorInternal(std::move(eptr), lock);
987
+ }
988
+
989
+ void setErrorIfNeeded(std::exception_ptr eptr) {
990
+ std::unique_lock<std::mutex> lock(mutex_);
991
+ if (completed_) {
992
+ // This should be rare and shouldn't cause log spew. Its important to
993
+ // log errors and thats why we have this log here.
994
+ std::string msg = c10::str(
995
+ "Skipping setting following error on the Future since "
996
+ "it is already marked completed (this is not necessarily "
997
+ "an error):\n",
998
+ tryRetrieveErrorMessageInternal(std::move(eptr)));
999
+ if (eptr_) {
1000
+ msg += c10::str(
1001
+ ", \nOriginal exception:\n",
1002
+ tryRetrieveErrorMessageInternal(eptr_));
1003
+ }
1004
+ LOG(INFO) << msg;
1005
+ return;
1006
+ } else {
1007
+ setErrorInternal(std::move(eptr), lock);
1008
+ }
1009
+ }
1010
+
1011
+ // Get the result of the current future.
1012
+ IValue value() {
1013
+ std::unique_lock<std::mutex> lock(mutex_);
1014
+ AT_ASSERT(completed());
1015
+ if (eptr_) {
1016
+ std::rethrow_exception(eptr_);
1017
+ }
1018
+ return value_;
1019
+ }
1020
+
1021
+ // This accessor should only be used if we know that the future is
1022
+ // completed() with no error.
1023
+ const IValue& constValue() const {
1024
+ std::unique_lock<std::mutex> lock(mutex_);
1025
+ AT_ASSERT(completed());
1026
+ TORCH_INTERNAL_ASSERT(
1027
+ !eptr_,
1028
+ "value() accessor should only be used when future is not completed with ",
1029
+ "an error, but future had the following error: ",
1030
+ tryRetrieveErrorMessageInternal(eptr_)
1031
+ );
1032
+ return value_;
1033
+ }
1034
+
1035
+ // This accessor should only be used if we know that the future is
1036
+ // completed() with no error.
1037
+ const std::vector<WeakStorage>& storages() const {
1038
+ std::unique_lock<std::mutex> lock(mutex_);
1039
+ AT_ASSERT(completed());
1040
+ AT_ASSERT(!eptr_);
1041
+ return storages_;
1042
+ }
1043
+
1044
+ /**
1045
+ * Add a callback to the future.
1046
+ * The callbacks will be executed once the future completes.
1047
+ * If the future has already completed,
1048
+ * this function will execute the callback immediately.
1049
+ */
1050
+ template <typename T>
1051
+ void addCallback(T callback, bool uses_future = true) {
1052
+ static_assert(
1053
+ std::is_invocable_r_v<void, T, Future&>,
1054
+ "The callback must have signature void(Future&)");
1055
+
1056
+ std::unique_lock<std::mutex> lock(mutex_);
1057
+ if (completed()) {
1058
+ lock.unlock();
1059
+ invokeCallback(callback, uses_future);
1060
+ return;
1061
+ }
1062
+ callbacks_.emplace_back(std::move(callback), uses_future);
1063
+ }
1064
+
1065
+ /**
1066
+ * Add a callback to the future, and return another Future to hold the return
1067
+ * value of the callback. This is necessary when the callback provider needs
1068
+ * to know for sure when the callback has finished.
1069
+ */
1070
+ template <typename T>
1071
+ c10::intrusive_ptr<Future> then(T callback, TypePtr type) {
1072
+ using IValueWithStorages = std::tuple<IValue, std::vector<WeakStorage>>;
1073
+ static_assert(
1074
+ std::disjunction_v<
1075
+ std::is_invocable_r<IValue, T, Future&>,
1076
+ std::is_invocable_r<IValueWithStorages, T, Future&>>,
1077
+ "The callback must have signature IValue(Future&) or "
1078
+ "std::tuple<IValue, std::vector<Storage>>(Future&)");
1079
+
1080
+ auto childFut = createInstance(::std::move(type));
1081
+ addCallback([childFut,
1082
+ cb = std::move(callback)](Future& parentFut) {
1083
+ try {
1084
+ if constexpr (::std::is_convertible_v<typename std::invoke_result_t<T &&, Future&>, IValueWithStorages>) {
1085
+ auto [ivalue, storages] = cb(parentFut);
1086
+ childFut->markCompleted(::std::move(ivalue), ::std::move(storages));
1087
+ } else {
1088
+ childFut->markCompleted(cb(parentFut));
1089
+ }
1090
+ } catch (std::exception&) {
1091
+ childFut->setError(std::current_exception());
1092
+ }
1093
+ });
1094
+ return childFut;
1095
+ }
1096
+
1097
+ template <typename T>
1098
+ c10::intrusive_ptr<Future> thenAsync(T callback, TypePtr type) {
1099
+ static_assert(
1100
+ std::is_invocable_r_v<c10::intrusive_ptr<Future>, T, Future&>,
1101
+ "The callback must have signature c10::intrusive_ptr<Future>(Future&)");
1102
+
1103
+ auto childFut = createInstance(std::move(type));
1104
+ addCallback(
1105
+ [childFut, cb = std::move(callback)](Future& parentFut) mutable {
1106
+ c10::intrusive_ptr<Future> intermediateFut;
1107
+ try {
1108
+ intermediateFut = cb(parentFut);
1109
+ } catch (std::exception&) {
1110
+ childFut->setError(std::current_exception());
1111
+ return;
1112
+ }
1113
+ intermediateFut->addCallback(
1114
+ [childFut = std::move(childFut)](Future& intermediateFut) {
1115
+ if (intermediateFut.hasError()) {
1116
+ childFut->setError(intermediateFut.exception_ptr());
1117
+ } else {
1118
+ childFut->markCompleted(
1119
+ intermediateFut.value(), intermediateFut.storages());
1120
+ }
1121
+ });
1122
+ });
1123
+ return childFut;
1124
+ }
1125
+
1126
+ // Tries to retrieve the error message from std::exception_ptr.
1127
+ std::string tryRetrieveErrorMessage() const {
1128
+ TORCH_CHECK(hasError(), "No error present on the future.");
1129
+ std::unique_lock<std::mutex> lock(mutex_);
1130
+ return tryRetrieveErrorMessageInternal(eptr_);
1131
+ }
1132
+
1133
+ // Check if the current future has completed
1134
+ bool completed() const {
1135
+ return completed_;
1136
+ }
1137
+
1138
+ bool hasValue() const {
1139
+ std::unique_lock<std::mutex> lock(mutex_);
1140
+ return completed_ && !eptr_;
1141
+ }
1142
+
1143
+ bool hasError() const {
1144
+ std::unique_lock<std::mutex> lock(mutex_);
1145
+ return eptr_ ? true : false;
1146
+ }
1147
+
1148
+ std::exception_ptr exception_ptr() const {
1149
+ std::unique_lock<std::mutex> lock(mutex_);
1150
+ return eptr_;
1151
+ }
1152
+
1153
+ TORCH_API friend std::ostream& operator<<(
1154
+ std::ostream& out,
1155
+ const Future& v);
1156
+
1157
+ const TypePtr& elementType() const {
1158
+ return type_;
1159
+ }
1160
+
1161
+ const std::vector<c10::Device>& devices() const {
1162
+ return devices_;
1163
+ }
1164
+
1165
+ // This method should be used when one intends to manually create a child
1166
+ // future, for example when implementing a customized version of then().
1167
+ c10::intrusive_ptr<Future> createInstance(at::TypePtr type) {
1168
+ return c10::make_intrusive<Future>(std::move(type), devices_);
1169
+ }
1170
+
1171
+ private:
1172
+
1173
+ // This method should always be used when invoking a callback (regardless of
1174
+ // how/when that happens) as it will ensure that the proper "environment" is
1175
+ // set up before running the callback, as in, it will set up the CUDA streams,
1176
+ // synchronize them with the value, and so on (if needed).
1177
+ template<typename T>
1178
+ void invokeCallback(T& callback, bool uses_future) {
1179
+ static_assert(
1180
+ std::is_invocable_r_v<void, T, Future&>,
1181
+ "The callback must have signature void(Future&)");
1182
+
1183
+ // The synchronization performed below shouldn't be needed when the future
1184
+ // is not used by the callback.
1185
+ if (uses_future) {
1186
+ c10::OptionalDeviceGuard deviceGuard(currentDevice_);
1187
+
1188
+ std::vector<c10::Stream> streams;
1189
+ streams.reserve(devices_.size());
1190
+ for (const c10::Device& device : devices_) {
1191
+ streams.push_back(impl_.getStreamFromGlobalPool(device));
1192
+ }
1193
+ c10::MultiStreamGuard streamGuard(streams);
1194
+ synchronizeWithCurrentStreams();
1195
+ callback(*this);
1196
+ } else {
1197
+ callback(*this);
1198
+ }
1199
+ }
1200
+
1201
+ // This method should be called before this future's value is used, as it
1202
+ // ensures that the CUDA streams that are "current" at the callsite properly
1203
+ // synchronize with the value.
1204
+ void synchronizeWithCurrentStreams() {
1205
+ for (c10::Event& event : events_) {
1206
+ event.block(impl_.getStream(event.device()));
1207
+ }
1208
+
1209
+ for (const WeakStorage& weak_storage : storages_) {
1210
+ c10::intrusive_ptr<c10::StorageImpl> storage = weak_storage.lock();
1211
+ if (!storage) {
1212
+ continue;
1213
+ }
1214
+ if (!storage->device().is_cpu()) {
1215
+ impl_.recordDataPtrOnStream(
1216
+ storage->data_ptr(), impl_.getStream(storage->device()));
1217
+ }
1218
+ }
1219
+ }
1220
+
1221
+ void setErrorInternal(
1222
+ std::exception_ptr eptr,
1223
+ std::unique_lock<std::mutex>& lock) {
1224
+ TORCH_CHECK(
1225
+ !eptr_,
1226
+ "Error already set on this Future: ",
1227
+ tryRetrieveErrorMessageInternal(eptr_),
1228
+ ", trying to set error: ",
1229
+ tryRetrieveErrorMessageInternal(eptr));
1230
+ TORCH_INTERNAL_ASSERT(!completed(), "Future is already marked completed");
1231
+ completed_ = true;
1232
+ eptr_ = std::move(eptr);
1233
+
1234
+ std::vector<FutureCallback> cbs;
1235
+ cbs.swap(callbacks_);
1236
+ lock.unlock();
1237
+
1238
+ finished_cv_.notify_all();
1239
+ for (const auto& callback : cbs) {
1240
+ invokeCallback(callback.callback, callback.uses_future);
1241
+ }
1242
+ }
1243
+
1244
+ // Tries to retrieve the error message from std::exception_ptr.
1245
+ std::string tryRetrieveErrorMessageInternal(std::exception_ptr eptr) const {
1246
+ try {
1247
+ std::rethrow_exception(std::move(eptr));
1248
+ } catch (const std::exception& e) {
1249
+ return e.what();
1250
+ } catch (...) {
1251
+ return "Unknown Exception Type";
1252
+ }
1253
+ }
1254
+
1255
+ // Defined in ivalue.cpp.
1256
+ static std::vector<WeakStorage> extractStorages(
1257
+ const at::IValue& value);
1258
+
1259
+ static std::vector<c10::Device> getDevicesOfStorages(
1260
+ const c10::impl::VirtualGuardImpl& impl,
1261
+ const std::vector<WeakStorage>& storages) {
1262
+ c10::DeviceIndex deviceCount = impl.deviceCount();
1263
+ std::vector<bool> isDeviceUsed(deviceCount, false);
1264
+ for (const WeakStorage& weak_storage : storages) {
1265
+ c10::intrusive_ptr<c10::StorageImpl> storage = weak_storage.lock();
1266
+ if (!storage) {
1267
+ continue;
1268
+ }
1269
+ c10::Device device = storage->device();
1270
+ if (!device.is_cpu()) {
1271
+ TORCH_CHECK_VALUE(
1272
+ device.type() == impl.type(),
1273
+ "Expected all data ptrs to be on a device of type ",
1274
+ impl.type(),
1275
+ ", got one on device ",
1276
+ device);
1277
+ isDeviceUsed[device.index()] = true;
1278
+ }
1279
+ }
1280
+ std::vector<c10::Device> devices;
1281
+ for (c10::DeviceIndex idx = 0; idx < deviceCount; idx++) {
1282
+ if (isDeviceUsed[idx]) {
1283
+ devices.emplace_back(impl.type(), idx);
1284
+ }
1285
+ }
1286
+ return devices;
1287
+ }
1288
+
1289
+ static std::string formatSetOfDevices(
1290
+ const std::vector<c10::Device>& devices) {
1291
+ if (devices.empty()) {
1292
+ return "(none)";
1293
+ }
1294
+ std::ostringstream oss;
1295
+ oss << devices[0];
1296
+ for (const auto idx : c10::irange(1, devices.size())) {
1297
+ if (idx == devices.size() - 1) {
1298
+ oss << " and ";
1299
+ } else {
1300
+ oss << ", ";
1301
+ }
1302
+ oss << devices[idx];
1303
+ }
1304
+ return oss.str();
1305
+ }
1306
+
1307
+ static c10::DeviceType getTypeOfDevices(
1308
+ const std::vector<c10::Device>& devices) {
1309
+ if (devices.empty()) {
1310
+ return c10::kCPU;
1311
+ }
1312
+ c10::DeviceType deviceType = devices[0].type();
1313
+ for (const auto idx : c10::irange(1, devices.size())) {
1314
+ TORCH_CHECK_VALUE(
1315
+ devices[idx].type() == deviceType,
1316
+ "Expected all devices to be of the same type, but got a mismatch between ",
1317
+ devices[0],
1318
+ " and ",
1319
+ devices[idx]);
1320
+ }
1321
+ return deviceType;
1322
+ }
1323
+
1324
+ // We need devices to be sorted in order to use ensureIsSubsetOfDevices.
1325
+ static std::vector<c10::Device> sortAndDeduplicateDevices(
1326
+ const c10::impl::VirtualGuardImpl& /*impl*/,
1327
+ std::vector<c10::Device> devices) {
1328
+ std::sort(
1329
+ devices.begin(), devices.end(),
1330
+ [](const c10::Device& a, const c10::Device& b) { return a.index() < b.index(); });
1331
+ // Deduplicate by compacting.
1332
+ size_t targetIdx = 0;
1333
+ for (const auto sourceIdx : c10::irange(devices.size())) {
1334
+ TORCH_CHECK_VALUE(
1335
+ devices[sourceIdx].has_index(),
1336
+ "Expected devices to have indices, got ", devices[sourceIdx]);
1337
+ if (targetIdx > 0 && devices[targetIdx - 1].index() == devices[sourceIdx].index()) {
1338
+ // It's a duplicate, skip it.
1339
+ continue;
1340
+ }
1341
+ if (sourceIdx != targetIdx) {
1342
+ devices[targetIdx] = devices[sourceIdx];
1343
+ }
1344
+ targetIdx++;
1345
+ }
1346
+ // If there were duplicates there's now a gap at the end: trim it. Resizing
1347
+ // requires the item type to be default-constructible (which c10::Device is
1348
+ // not) because in principle it could be required to create new items. Since
1349
+ // we know we'll shrink the vector, we provide a custom dummy value instead.
1350
+ devices.resize(targetIdx, c10::Device(c10::kCPU));
1351
+ return devices;
1352
+ }
1353
+
1354
+ static void ensureIsSubsetOfDevices(
1355
+ const std::vector<c10::Device>& subset,
1356
+ const std::vector<c10::Device>& superset) {
1357
+ // We assume the devices in both vectors have the same consistent type, and
1358
+ // their indices are unique and sorted.
1359
+ std::vector<c10::Device> excessDevices;
1360
+ std::set_difference(
1361
+ subset.begin(),
1362
+ subset.end(),
1363
+ superset.begin(),
1364
+ superset.end(),
1365
+ std::back_inserter(excessDevices),
1366
+ [](const c10::Device& a, const c10::Device& b) { return a.index() < b.index(); });
1367
+ TORCH_CHECK_VALUE(
1368
+ excessDevices.empty(),
1369
+ "The result contained tensors residing on device(s) ",
1370
+ formatSetOfDevices(excessDevices),
1371
+ " which are not among the expected device(s) ",
1372
+ formatSetOfDevices(superset));
1373
+ }
1374
+
1375
+ mutable std::mutex mutex_;
1376
+ std::atomic_bool completed_ = {false}; // is this future complete
1377
+ std::condition_variable finished_cv_;
1378
+
1379
+ IValue value_; // when finished the value
1380
+ TypePtr type_;
1381
+ std::vector<FutureCallback> callbacks_;
1382
+ std::exception_ptr eptr_;
1383
+
1384
+ // An upcast pointer to a virtual class which allows us to manipulate events,
1385
+ // streams, ... in a generic way, without an explicit dependency on CUDA.
1386
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1387
+ const c10::impl::VirtualGuardImpl impl_;
1388
+
1389
+ // The device that was current when markCompleted was called, which we'll
1390
+ // restore when invoking callbacks. It's optional because we'll only store it
1391
+ // if the future completes successfully.
1392
+ std::optional<c10::Device> currentDevice_;
1393
+
1394
+ // The events that correspond to the completion of the async I/O kernels. They
1395
+ // are recorded on the appropriate streams when the future is marked completed
1396
+ // and can then be queried/waited/blocked on. There is one event for each
1397
+ // distinct device on which the value's tensors reside.
1398
+ std::vector<c10::Event> events_;
1399
+
1400
+ // A cached version of the storages extracted from the value when the future
1401
+ // is first marked completed.
1402
+ std::vector<WeakStorage> storages_;
1403
+
1404
+ // The bounding set of devices that this future, and any of its children, is
1405
+ // allowed to use. This is a superset of the set of devices used by the events
1406
+ // above. We need this to know what streams (for which devices) to set as
1407
+ // current when invoking a callback, thus allowing the callback to use devices
1408
+ // that the parent future didn't use. This field is set to the value provided
1409
+ // in the constructor and will be "inherited" by all child futures.
1410
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1411
+ const std::vector<c10::Device> devices_;
1412
+ };
1413
+
1414
+ struct C10_EXPORT ivalue::Await final : c10::intrusive_ptr_target {
1415
+ private:
1416
+ explicit Await(TypePtr elType, std::function<IValue()> fn)
1417
+ : elType_(std::move(elType)), type_(AwaitType::create(elType_)), fn_(std::move(fn)) {}
1418
+
1419
+ explicit Await(TypePtr elType) : elType_(std::move(elType)), type_(AwaitType::create(elType_)) { }
1420
+
1421
+ friend c10::intrusive_ptr<Await>;
1422
+
1423
+ public:
1424
+ Await(const Await&) = delete;
1425
+ Await(Await&&) = delete;
1426
+ Await& operator=(const Await&) = delete;
1427
+ Await& operator=(Await&&) = delete;
1428
+ ~Await() override = default;
1429
+
1430
+ IValue wait() {
1431
+ if (!completed_) {
1432
+ TORCH_CHECK(fn_, "Incompleted Await: fn can't be None");
1433
+ value_ = fn_();
1434
+ completed_ = true;
1435
+ args_ = {};
1436
+ }
1437
+ return value_;
1438
+ }
1439
+
1440
+ IValue value() {
1441
+ TORCH_CHECK(completed_, "Await must be completed");
1442
+ return value_;
1443
+ }
1444
+
1445
+ void setFn(std::function<IValue()> fn) {
1446
+ fn_ = std::move(fn);
1447
+ }
1448
+
1449
+ bool completed() {
1450
+ return completed_;
1451
+ }
1452
+
1453
+ void markCompleted(IValue value) {
1454
+ value_ = std::move(value);
1455
+ completed_ = true;
1456
+ }
1457
+
1458
+ TORCH_API friend std::ostream& operator<<(
1459
+ std::ostream& out,
1460
+ const Await& v);
1461
+
1462
+ const TypePtr& elementType() const {
1463
+ return elType_;
1464
+ }
1465
+
1466
+ const TypePtr& type() const {
1467
+ return type_;
1468
+ }
1469
+
1470
+ void setArgs(std::vector<IValue> args) {
1471
+ args_ = std::move(args);
1472
+ }
1473
+
1474
+ std::vector<IValue>& args() {
1475
+ return args_;
1476
+ }
1477
+
1478
+ private:
1479
+ TypePtr elType_;
1480
+ TypePtr type_;
1481
+ std::vector<IValue> args_;
1482
+ std::function<IValue()> fn_;
1483
+ IValue value_;
1484
+ bool completed_{};
1485
+ };
1486
+
1487
+ // Input is a list of Futures with the same target type.
1488
+ // Output is a Future to the List of completed Futures.
1489
+ TORCH_API intrusive_ptr<ivalue::Future> collectAll(
1490
+ const c10::List<c10::intrusive_ptr<ivalue::Future>>& srcs);
1491
+ // Input is a List of Futures with the same target type.
1492
+ // Output is a Future that will be updated with a seen value.
1493
+ TORCH_API intrusive_ptr<ivalue::Future> collectAny(
1494
+ const c10::List<c10::intrusive_ptr<ivalue::Future>>& srcs);
1495
+
1496
+ // User-defined object.
1497
+ struct C10_EXPORT ivalue::Object final : c10::intrusive_ptr_target {
1498
+ public:
1499
+ // In general, class types hold a shared_ptr to its owning CompilationUnit,
1500
+ // so that its type and methods do not get deallocated while the class exists.
1501
+ // However, the CompilationUnit holds ownership of the type's graphs, so
1502
+ // inserting a constant object into a Graph would create a reference cycle if
1503
+ // that constant object held a shared_ptr to its CU. For these objects we
1504
+ // instatiate them with non-owning references to its CU
1505
+ Object(WeakOrStrongTypePtr type, size_t numSlots) : type_(std::move(type)) {
1506
+ slots_.resize(numSlots);
1507
+ }
1508
+
1509
+ Object(StrongTypePtr type, size_t numSlots)
1510
+ : type_(WeakOrStrongTypePtr(std::move(type))) {
1511
+ slots_.resize(numSlots);
1512
+ }
1513
+
1514
+ static c10::intrusive_ptr<Object> create(
1515
+ WeakOrStrongTypePtr type,
1516
+ size_t numSlots) {
1517
+ return c10::make_intrusive<Object>(std::move(type), numSlots);
1518
+ }
1519
+
1520
+ static c10::intrusive_ptr<Object> create(
1521
+ StrongTypePtr type,
1522
+ size_t numSlots) {
1523
+ return c10::make_intrusive<Object>(std::move(type), numSlots);
1524
+ }
1525
+
1526
+ static c10::intrusive_ptr<Object> create(ClassTypePtr classType, size_t numSlots);
1527
+
1528
+ /**
1529
+ * Slot API.
1530
+ *
1531
+ * Attributes are stored as a simple vector so that lookups are fast at
1532
+ * runtime. A "slot" is just an index into that vector, which can be computed
1533
+ * statically if you have access to the class type. Use this API if you are
1534
+ * writing compiler stuff.
1535
+ */
1536
+ void setSlot(size_t slot, IValue v) {
1537
+ if (slot >= slots_.size()) {
1538
+ // for module types, it is possible that the members of the class have
1539
+ // expanded after the object was created. In this case, we expand
1540
+ // the slots to the right size
1541
+ resizeObject(slot);
1542
+ }
1543
+ slots_[slot] = std::move(v);
1544
+ }
1545
+
1546
+ const IValue& getSlot(size_t slot) const {
1547
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(slot < slots_.size());
1548
+ // NOTE: This lookup is fairly hot, so we use unchecked access to the
1549
+ // vector. Errors should still be detectable with ASan.
1550
+ return slots_[slot];
1551
+ }
1552
+
1553
+ void unsafeRemoveSlot(size_t slot) {
1554
+ TORCH_CHECK(slot < slots_.size());
1555
+ slots_.erase(slots_.begin() + static_cast<std::ptrdiff_t>(slot));
1556
+ }
1557
+
1558
+ /**
1559
+ * Attribute API.
1560
+ *
1561
+ * Wrappers around the slot stuff so that users can access attributes
1562
+ * directly. Use this API if you are a user.
1563
+ *
1564
+ * Note: Unlike in Python, TorchScript must make a distinction between
1565
+ * attributes (which are IValues) and methods (which are Methods). If you
1566
+ * want a method, use `obj.type()->getMethod()`
1567
+ */
1568
+ IValue getAttr(const std::string& name) const;
1569
+ void setAttr(const std::string& name, IValue v);
1570
+ // Remove attribute by name, caller is responsible for
1571
+ // the safety of this operation
1572
+ // We didn't remove the attribute in the type because the type
1573
+ // might be shared by multiple objects.
1574
+ // Therefore after removing attribute, the object is in an inconsistent
1575
+ // state where it has more attribute types in its Type than
1576
+ // the attribute slots it has, user needs to make sure the object
1577
+ // has consistent by removing the attribute in type as well
1578
+ void unsafeRemoveAttr(const std::string& name);
1579
+
1580
+ std::string name() const;
1581
+
1582
+ const std::vector<IValue>& slots() const {
1583
+ return slots_;
1584
+ }
1585
+ std::shared_ptr<ClassType> type() const;
1586
+
1587
+ std::shared_ptr<torch::jit::CompilationUnit> compilation_unit() {
1588
+ if (type_.holds_strong_ref()) {
1589
+ return type_.cu_.getStrongRefOrThrow();
1590
+ } else {
1591
+ auto weak_ptr = type_.cu_.getWeakRefOrThrow();
1592
+ return std::shared_ptr<torch::jit::CompilationUnit>(weak_ptr);
1593
+ }
1594
+ }
1595
+
1596
+ c10::intrusive_ptr<Object> copy_to_weak_compilation_ref() const;
1597
+
1598
+ void unsafe_make_weak_compilation_ref() {
1599
+ type_ = WeakOrStrongTypePtr(type_.asWeakTypePtr());
1600
+ }
1601
+
1602
+ c10::intrusive_ptr<Object> copy() const;
1603
+
1604
+ c10::intrusive_ptr<Object> deepcopy(
1605
+ std::optional<at::Device> device = std::nullopt) const;
1606
+
1607
+ c10::intrusive_ptr<Object> deepcopy(
1608
+ IValue::HashIdentityIValueMap& memo,
1609
+ std::optional<at::Device> device = std::nullopt) const;
1610
+
1611
+ bool is_weak_compilation_ref() const {
1612
+ return !type_.holds_strong_ref();
1613
+ }
1614
+
1615
+ bool is_empty_strong_compilation_ref() const {
1616
+ return type_.holds_empty_strong_ref();
1617
+ }
1618
+
1619
+ private:
1620
+ void resizeObject(size_t slot);
1621
+ WeakOrStrongTypePtr type_;
1622
+ std::vector<IValue> slots_;
1623
+ };
1624
+
1625
+ // virtual ivalue PyObjectHolder that hold a py::object, we make this virtual
1626
+ // because the py::object and refcounting logic should happen in libtorch_python
1627
+ // see concrete implementation in python_ivalue.h
1628
+ struct ivalue::PyObjectHolder : c10::intrusive_ptr_target {
1629
+ public:
1630
+ virtual PyObject* getPyObject() = 0;
1631
+ virtual c10::InferredType tryToInferType() = 0;
1632
+ virtual IValue toIValue(const TypePtr& type, std::optional<int32_t> N = std::nullopt) = 0;
1633
+ virtual std::string toStr() = 0;
1634
+ virtual std::vector<at::Tensor> extractTensors() = 0;
1635
+
1636
+ ~PyObjectHolder() override = default;
1637
+ };
1638
+
1639
+ struct ivalue::EnumHolder : c10::intrusive_ptr_target {
1640
+ public:
1641
+ EnumHolder(std::shared_ptr<EnumType> type, std::string name, IValue value)
1642
+ : type_(std::move(type)),
1643
+ name_(std::move(name)),
1644
+ value_(std::move(value)) {}
1645
+
1646
+ bool is(const ivalue::EnumHolder& rhs) {
1647
+ return *this == rhs;
1648
+ }
1649
+
1650
+ friend bool operator==(
1651
+ const ivalue::EnumHolder& lhs,
1652
+ const ivalue::EnumHolder& rhs);
1653
+
1654
+ TORCH_API friend std::ostream& operator<<(
1655
+ std::ostream& out,
1656
+ const ivalue::EnumHolder& v);
1657
+
1658
+ TORCH_API const std::string& qualifiedClassName() const;
1659
+
1660
+ const std::string& unqualifiedClassName() const;
1661
+
1662
+ const std::string& name() const {
1663
+ return name_;
1664
+ }
1665
+
1666
+ const IValue& value() const {
1667
+ return value_;
1668
+ }
1669
+
1670
+ std::shared_ptr<EnumType> type() const {
1671
+ return type_;
1672
+ }
1673
+
1674
+ private:
1675
+ std::shared_ptr<EnumType> type_;
1676
+ std::string name_;
1677
+ IValue value_;
1678
+ };
1679
+
1680
+ #undef TORCH_FORALL_TAGS
1681
+
1682
+ namespace detail {
1683
+
1684
+ struct _guarded_unsigned_long_unique_dummy final {
1685
+ _guarded_unsigned_long_unique_dummy(int64_t){}
1686
+ };
1687
+ using _guarded_unsigned_long = std::conditional_t<
1688
+ std::is_same_v<unsigned long, uint32_t> ||
1689
+ std::is_same_v<unsigned long, uint64_t>,
1690
+ _guarded_unsigned_long_unique_dummy,
1691
+ unsigned long>;
1692
+
1693
+ } // namespace detail
1694
+
1695
+ inline ivalue::Object& IValue::toObjectRef() const {
1696
+ AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
1697
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(), "Attempted to create null reference");
1698
+ return *static_cast<c10::ivalue::Object*>(payload.u.as_intrusive_ptr);
1699
+ }
1700
+
1701
+ // note: when adding a DEFINE_TO case here you should also add a
1702
+ // toX method to IValue. These named methods are much more discoverable
1703
+ // than the to templated function.
1704
+
1705
+ #define DEFINE_TO(T, method_name) \
1706
+ template <> \
1707
+ inline T IValue::to<T>()&& { \
1708
+ return static_cast<T>(std::move(*this).method_name()); \
1709
+ } \
1710
+ template <> \
1711
+ inline c10::detail::ivalue_to_const_ref_overload_return<T>::type IValue::to<T>() const& { \
1712
+ typedef c10::detail::ivalue_to_const_ref_overload_return<T>::type return_type; \
1713
+ return static_cast<return_type>(this->method_name()); \
1714
+ }
1715
+
1716
+ DEFINE_TO(at::Tensor, toTensor)
1717
+ DEFINE_TO(at::Storage, toStorage)
1718
+ DEFINE_TO(c10::Stream, toStream)
1719
+ DEFINE_TO(float, toDouble)
1720
+ DEFINE_TO(double, toDouble)
1721
+ DEFINE_TO(c10::complex<double>, toComplexDouble)
1722
+ DEFINE_TO(unsigned char, toInt)
1723
+ DEFINE_TO(signed char, toInt)
1724
+ DEFINE_TO(unsigned short, toInt)
1725
+ DEFINE_TO(short, toInt)
1726
+ DEFINE_TO(int, toInt)
1727
+ DEFINE_TO(uint32_t, toInt)
1728
+ DEFINE_TO(uint64_t, toInt)
1729
+ DEFINE_TO(detail::_guarded_unsigned_long, toInt)
1730
+ DEFINE_TO(int64_t, toInt)
1731
+ DEFINE_TO(bool, toBool)
1732
+ DEFINE_TO(c10::intrusive_ptr<caffe2::Blob>, toBlob)
1733
+ DEFINE_TO(c10::intrusive_ptr<ivalue::ConstantString>, toString)
1734
+ DEFINE_TO(c10::intrusive_ptr<ivalue::Object>, toObject)
1735
+ DEFINE_TO(at::Scalar, toScalar)
1736
+ DEFINE_TO(c10::List<int64_t>, toIntList)
1737
+ DEFINE_TO(c10::List<c10::SymInt>, toSymIntList)
1738
+ DEFINE_TO(c10::List<double>, toDoubleList)
1739
+ DEFINE_TO(c10::List<c10::complex<double>>, toComplexDoubleList)
1740
+ DEFINE_TO(c10::List<bool>, toBoolList)
1741
+ DEFINE_TO(c10::List<at::Tensor>, toTensorList)
1742
+ DEFINE_TO(c10::impl::GenericList, toList)
1743
+ DEFINE_TO(c10::impl::GenericDict, toGenericDict)
1744
+ DEFINE_TO(c10::intrusive_ptr<ivalue::Tuple>, toTuple)
1745
+ DEFINE_TO(std::string, toStringRef)
1746
+ DEFINE_TO(std::string_view, toStringView)
1747
+ DEFINE_TO(c10::intrusive_ptr<ivalue::Future>, toFuture)
1748
+ DEFINE_TO(c10::intrusive_ptr<ivalue::Await>, toAwait)
1749
+ DEFINE_TO(c10::intrusive_ptr<c10::RRefInterface>, toRRef)
1750
+ DEFINE_TO(c10::intrusive_ptr<at::Quantizer>, toQuantizer)
1751
+ DEFINE_TO(IValue, toIValue)
1752
+ DEFINE_TO(c10::Device, toDevice)
1753
+ DEFINE_TO(at::ScalarType, toScalarType)
1754
+ DEFINE_TO(at::Layout, toLayout)
1755
+ DEFINE_TO(at::MemoryFormat, toMemoryFormat)
1756
+ DEFINE_TO(at::QScheme, toQScheme)
1757
+ DEFINE_TO(at::Dimname, toDimname)
1758
+ DEFINE_TO(at::Generator, toGenerator)
1759
+ DEFINE_TO(c10::SymInt, toSymInt)
1760
+ DEFINE_TO(c10::SymFloat, toSymFloat)
1761
+ DEFINE_TO(c10::SymBool, toSymBool)
1762
+
1763
+ template <class T>
1764
+ struct _fake_type {};
1765
+
1766
+ // generic_to<T> converts an IValue from a generic list or generic dict
1767
+ // to a concrete list/dict type likelike List<T>, Dict<...> or std::optional<T>.
1768
+ // Note that in the case of lists, this only works for IValue-based lists,
1769
+ // i.e. not for int64_t, double, ...
1770
+ // generic_to<T> is an implementation detail of IValue::to<T> and not
1771
+ // supposed to be called directly.
1772
+ // The _fake_type<T> parameter allows us to overload
1773
+ // based on the return type.
1774
+ template <class Elem>
1775
+ // TODO this is deprecated but we don't throw a warning because a lot of ops in
1776
+ // native_functions.yaml still return std::vector.
1777
+ // C10_DEPRECATED_MESSAGE("IValues based on std::vector<T> are potentially slow
1778
+ // and deprecated. Please use torch::List<T> instead.")
1779
+ std::vector<Elem> generic_to(IValue ivalue, _fake_type<std::vector<Elem>>) {
1780
+ // We need to do a deep copy of the vector because there might be other
1781
+ // references to this same IValue that also use the list. We can't just
1782
+ // move the elements out.
1783
+ auto list = std::move(ivalue).template to<List<Elem>>();
1784
+ std::vector<Elem> result;
1785
+ result.reserve(list.size());
1786
+ for (Elem v : list) {
1787
+ result.push_back(std::move(v));
1788
+ }
1789
+ return result;
1790
+ }
1791
+
1792
+ template <typename T>
1793
+ c10::intrusive_ptr<T> IValue::toCustomClass() && {
1794
+ static_assert(
1795
+ std::is_base_of_v<torch::CustomClassHolder, T> == true,
1796
+ "toCustomClass requires that template parameter T must inherit "
1797
+ "from torch::CustomClassHolder");
1798
+ auto obj = toObject();
1799
+ TORCH_CHECK(
1800
+ obj->slots().size() == 1,
1801
+ "Tried to cast IValue to custom class but it did "
1802
+ "not contain a custom class!");
1803
+ const auto* expected_type = c10::getCustomClassType<c10::intrusive_ptr<T>>().get();
1804
+ ivalue::checkCustomClassType(expected_type, type().get());
1805
+ auto userObj =
1806
+ c10::static_intrusive_pointer_cast<T>(obj->getSlot(0).toCapsule());
1807
+ return userObj;
1808
+ }
1809
+
1810
+ template <typename T>
1811
+ c10::intrusive_ptr<T> IValue::toCustomClass() const& {
1812
+ static_assert(
1813
+ std::is_base_of_v<torch::CustomClassHolder, T> == true,
1814
+ "toCustomClass requires that template parameter T must inherit "
1815
+ "from torch::CustomClassHolder");
1816
+ auto obj = toObject();
1817
+ TORCH_CHECK(
1818
+ obj->slots().size() == 1,
1819
+ "Tried to cast IValue to custom class but it did "
1820
+ "not contain a custom class!");
1821
+ const auto* expected_type = c10::getCustomClassType<c10::intrusive_ptr<T>>().get();
1822
+ ivalue::checkCustomClassType(expected_type, type().get());
1823
+ auto userObj =
1824
+ c10::static_intrusive_pointer_cast<T>(obj->getSlot(0).toCapsule());
1825
+ return userObj;
1826
+ }
1827
+
1828
+ template <typename T>
1829
+ T generic_to(IValue ivalue, _fake_type<T>) {
1830
+ using ElemType = typename std::remove_pointer<T>::type::element_type;
1831
+ return std::move(ivalue).template toCustomClass<ElemType>();
1832
+ }
1833
+
1834
+ template <typename T>
1835
+ tagged_capsule<T> generic_to(IValue ivalue, _fake_type<tagged_capsule<T>>) {
1836
+ return tagged_capsule<T>{std::move(ivalue)};
1837
+ }
1838
+
1839
+ template <typename Elem>
1840
+ c10::List<Elem> generic_to(IValue ivalue, _fake_type<c10::List<Elem>>) {
1841
+ return impl::toTypedList<Elem>(std::move(ivalue).toList());
1842
+ }
1843
+
1844
+ template <typename T>
1845
+ static T createVectorLikeFromList(const c10::detail::ListImpl* impl) {
1846
+ T result;
1847
+ result.reserve(impl->list.size());
1848
+ for (const auto & i : impl->list) {
1849
+ result.push_back(i.to<typename T::value_type>());
1850
+ }
1851
+ return result;
1852
+ }
1853
+
1854
+ template <typename T>
1855
+ static std::vector<T> createVectorFromList(const c10::detail::ListImpl* impl) {
1856
+ return createVectorLikeFromList<std::vector<T>>(impl);
1857
+ }
1858
+
1859
+ template <typename T>
1860
+ std::vector<T> createVectorFromList(const c10::List<T>& impl) {
1861
+ std::vector<T> result;
1862
+ result.reserve(impl.size());
1863
+ for (size_t i = 0, N = impl.size(); i < N; ++i) {
1864
+ result.push_back(impl[i]);
1865
+ }
1866
+ return result;
1867
+ }
1868
+
1869
+ template <typename T>
1870
+ OptionalArray<T> generic_to(IValue ivalue, _fake_type<OptionalArray<T>>) {
1871
+ if (ivalue.isNone()) {
1872
+ return {};
1873
+ }
1874
+ return createVectorFromList<T>(
1875
+ std::move(ivalue).template to<c10::List<T>>()
1876
+ );
1877
+ }
1878
+
1879
+ namespace detail {
1880
+ template <typename Elem, size_t... I>
1881
+ std::array<Elem, sizeof...(I)> generic_to_array(
1882
+ IValue ivalue,
1883
+ _fake_type<std::array<Elem, sizeof...(I)>>,
1884
+ std::index_sequence<I...>) {
1885
+ // We need to do a deep copy of the array because there might be other
1886
+ // references to this same IValue that also use the list. We can't just
1887
+ // move the elements out.
1888
+ auto list = std::move(ivalue).template to<List<Elem>>();
1889
+ TORCH_CHECK(
1890
+ list.size() == sizeof...(I),
1891
+ "Tried to convert a List with ",
1892
+ list.size(),
1893
+ " elements to a fixed-size array of size ",
1894
+ sizeof...(I));
1895
+ return {list[I]...};
1896
+ }
1897
+ } // namespace detail
1898
+
1899
+ template <typename Elem, size_t N>
1900
+ std::array<Elem, N> generic_to(
1901
+ IValue ivalue,
1902
+ _fake_type<std::array<Elem, N>> ft) {
1903
+ return detail::generic_to_array(ivalue, ft, std::make_index_sequence<N>());
1904
+ }
1905
+
1906
+ template <typename Key, typename Value>
1907
+ c10::Dict<Key, Value> generic_to(
1908
+ IValue ivalue,
1909
+ _fake_type<c10::Dict<Key, Value>>) {
1910
+ return impl::toTypedDict<Key, Value>(std::move(ivalue).toGenericDict());
1911
+ }
1912
+
1913
+ template <typename K, typename V>
1914
+ C10_DEPRECATED_MESSAGE(
1915
+ "IValues based on std::unordered_map are slow and deprecated. Please use c10::Dict<K, V> instead.")
1916
+ std::unordered_map<K, V> generic_to(
1917
+ IValue ivalue,
1918
+ _fake_type<std::unordered_map<K, V>>) {
1919
+ std::unordered_map<K, V> specialized_dict;
1920
+
1921
+ for (const auto& item : std::move(ivalue).toGenericDict()) {
1922
+ specialized_dict[item.key().template to<K>()] = item.value().template to<V>();
1923
+ }
1924
+
1925
+ return specialized_dict;
1926
+ }
1927
+
1928
+ template <typename T>
1929
+ std::optional<T> generic_to(IValue ivalue, _fake_type<std::optional<T>>) {
1930
+ if (ivalue.isNone()) {
1931
+ return std::nullopt;
1932
+ }
1933
+ return std::move(ivalue).template to<T>();
1934
+ }
1935
+
1936
+ namespace detail {
1937
+ template <typename Tuple, std::size_t... INDEX>
1938
+ Tuple generic_to_tuple_impl(
1939
+ const ivalue::TupleElements& t,
1940
+ std::index_sequence<INDEX...>) {
1941
+ return std::make_tuple(
1942
+ t[INDEX].to<typename std::tuple_element<INDEX, Tuple>::type>()...);
1943
+ }
1944
+ } // namespace detail
1945
+
1946
+ template <
1947
+ typename... Args,
1948
+ typename Indices = std::make_index_sequence<sizeof...(Args)>,
1949
+ std::enable_if_t<
1950
+ !std::disjunction_v<
1951
+ std::is_lvalue_reference<Args>...,
1952
+ std::negation<std::is_constructible<IValue, Args>>...>,
1953
+ std::nullptr_t> = nullptr>
1954
+ std::tuple<Args...> generic_to(const IValue& ivalue, _fake_type<std::tuple<Args...>>) {
1955
+ const auto& vals = ivalue.toTupleRef().elements();
1956
+ TORCH_CHECK(vals.size() == sizeof...(Args));
1957
+ return detail::generic_to_tuple_impl<std::tuple<Args...>>(vals, Indices{});
1958
+ }
1959
+
1960
+ template <typename T>
1961
+ inline T IValue::to() && {
1962
+ return generic_to(std::move(*this), _fake_type<T>{});
1963
+ }
1964
+
1965
+ template <>
1966
+ inline std::optional<std::string_view> IValue::to() && {
1967
+ // In the default implementation, the IValue is destroyed with std::move.
1968
+ // But if the unboxed type is std::optional<string_view> we cannot destroy
1969
+ // the IValue.
1970
+ return generic_to(*this, _fake_type<std::optional<std::string_view>>{});
1971
+ }
1972
+
1973
+ template <typename T>
1974
+ inline typename c10::detail::ivalue_to_const_ref_overload_return<T>::type IValue::to() const& {
1975
+ return generic_to(*this, _fake_type<T>{});
1976
+ }
1977
+
1978
+ inline c10::List<int64_t> IValue::toIntList() && {
1979
+ AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
1980
+ return c10::List<int64_t>(moveToIntrusivePtr<c10::detail::ListImpl>());
1981
+ }
1982
+ inline c10::List<int64_t> IValue::toIntList() const& {
1983
+ AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
1984
+ return c10::List<int64_t>(toIntrusivePtr<c10::detail::ListImpl>());
1985
+ }
1986
+ inline std::vector<int64_t> IValue::toIntVector() const {
1987
+ AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
1988
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
1989
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
1990
+ "called toIntVector on null intrusive_ptr IValue");
1991
+ return createVectorFromList<int64_t>(
1992
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
1993
+ }
1994
+ inline c10::List<c10::SymInt> IValue::toSymIntList() && {
1995
+ AT_ASSERT(
1996
+ isSymIntList() || isIntList(),
1997
+ "Expected SymIntList or IntList but got ",
1998
+ tagKind());
1999
+ return c10::List<c10::SymInt>(moveToIntrusivePtr<c10::detail::ListImpl>());
2000
+ }
2001
+ inline c10::List<c10::SymInt> IValue::toSymIntList() const& {
2002
+ AT_ASSERT(
2003
+ isSymIntList() || isIntList(),
2004
+ "Expected SymIntList or IntList but got ",
2005
+ tagKind());
2006
+ return c10::List<c10::SymInt>(toIntrusivePtr<c10::detail::ListImpl>());
2007
+ }
2008
+ inline std::vector<c10::SymInt> IValue::toSymIntVector() const {
2009
+ AT_ASSERT(isSymIntList() || isIntList(), "Expected SymIntList or IntList but got ", tagKind());
2010
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2011
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2012
+ "called toSymIntVector on null intrusive_ptr IValue");
2013
+ return createVectorFromList<c10::SymInt>(
2014
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2015
+ }
2016
+ inline at::DimVector IValue::toDimVector() const {
2017
+ AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
2018
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2019
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2020
+ "called toDimVector on null intrusive_ptr IValue");
2021
+ return createVectorLikeFromList<at::DimVector>(
2022
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2023
+ }
2024
+ inline c10::List<double> IValue::toDoubleList() && {
2025
+ AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
2026
+ return c10::List<double>(moveToIntrusivePtr<c10::detail::ListImpl>());
2027
+ }
2028
+ inline c10::List<double> IValue::toDoubleList() const& {
2029
+ AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
2030
+ return c10::List<double>(toIntrusivePtr<c10::detail::ListImpl>());
2031
+ }
2032
+ inline std::vector<double> IValue::toDoubleVector() const {
2033
+ AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
2034
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2035
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2036
+ "called toDoubleVector on null intrusive_ptr IValue");
2037
+ return createVectorFromList<double>(
2038
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2039
+ }
2040
+ inline c10::List<c10::complex<double>> IValue::toComplexDoubleList() && {
2041
+ AT_ASSERT(isComplexDoubleList(), "Expected ComplexDoubleList but got ", tagKind());
2042
+ return c10::List<c10::complex<double>>(moveToIntrusivePtr<c10::detail::ListImpl>());
2043
+ }
2044
+ inline c10::List<c10::complex<double>> IValue::toComplexDoubleList() const& {
2045
+ AT_ASSERT(isComplexDoubleList(), "Expected ComplexDoubleList but got ", tagKind());
2046
+ return c10::List<c10::complex<double>>(toIntrusivePtr<c10::detail::ListImpl>());
2047
+ }
2048
+ inline std::vector<c10::complex<double>> IValue::toComplexDoubleVector() const {
2049
+ AT_ASSERT(isComplexDoubleList(), "Expected ComplexDoubleList but got ", tagKind());
2050
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2051
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2052
+ "called toComplexDoubleVector on null intrusive_ptr IValue");
2053
+ return createVectorFromList<c10::complex<double>>(
2054
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2055
+ }
2056
+ inline c10::List<bool> IValue::toBoolList() && {
2057
+ AT_ASSERT(isBoolList(), "Expected BoolList but got ", tagKind());
2058
+ return c10::List<bool>(moveToIntrusivePtr<c10::detail::ListImpl>());
2059
+ }
2060
+ inline c10::List<bool> IValue::toBoolList() const& {
2061
+ AT_ASSERT(isBoolList(), "Expected BoolList but got ", tagKind());
2062
+ return c10::List<bool>(toIntrusivePtr<c10::detail::ListImpl>());
2063
+ }
2064
+ inline c10::List<at::Tensor> IValue::toTensorList() && {
2065
+ AT_ASSERT(isTensorList(), "Expected TensorList but got ", tagKind());
2066
+ return c10::List<at::Tensor>(moveToIntrusivePtr<c10::detail::ListImpl>());
2067
+ }
2068
+ inline c10::List<at::Tensor> IValue::toTensorList() const& {
2069
+ AT_ASSERT(isTensorList(), "Expected TensorList but got ", tagKind());
2070
+ return c10::List<at::Tensor>(toIntrusivePtr<c10::detail::ListImpl>());
2071
+ }
2072
+ inline std::vector<at::Tensor> IValue::toTensorVector() const {
2073
+ AT_ASSERT(isTensorList(), "Expected TensorList but got ", tagKind());
2074
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2075
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2076
+ "called toTensorVector on null intrusive_ptr IValue");
2077
+ return createVectorFromList<at::Tensor>(
2078
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2079
+ }
2080
+ inline c10::List<std::optional<at::Tensor>> IValue::toOptionalTensorList() && {
2081
+ AT_ASSERT(isOptionalTensorList(), "Expected OptionalTensorList but got ", tagKind());
2082
+ return c10::List<std::optional<at::Tensor>>(moveToIntrusivePtr<c10::detail::ListImpl>());
2083
+ }
2084
+ inline c10::List<std::optional<at::Tensor>> IValue::toOptionalTensorList() const& {
2085
+ AT_ASSERT(isOptionalTensorList(), "Expected OptionalTensorList but got ", tagKind());
2086
+ return c10::List<std::optional<at::Tensor>>(toIntrusivePtr<c10::detail::ListImpl>());
2087
+ }
2088
+ inline std::vector<std::optional<at::Tensor>> IValue::toOptionalTensorVector() const {
2089
+ AT_ASSERT(isOptionalTensorList(), "Expected OptionalTensorList but got ", tagKind());
2090
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2091
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2092
+ "called toOptionalTensorVector on null intrusive_ptr IValue");
2093
+ return createVectorFromList<std::optional<at::Tensor>>(
2094
+ static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr));
2095
+ }
2096
+ inline c10::List<IValue> IValue::toList() && {
2097
+ AT_ASSERT(isList(), "Expected GenericList but got ", tagKind());
2098
+ return c10::List<IValue>(moveToIntrusivePtr<c10::detail::ListImpl>());
2099
+ }
2100
+ inline c10::List<IValue> IValue::toList() const& {
2101
+ AT_ASSERT(isList(), "Expected GenericList but got ", tagKind());
2102
+ return c10::List<IValue>(toIntrusivePtr<c10::detail::ListImpl>());
2103
+ }
2104
+ inline c10::ArrayRef<IValue> IValue::toListRef() const {
2105
+ AT_ASSERT(isList(), "Expected GenericList but got ", tagKind());
2106
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2107
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2108
+ "called toListRef on null intrusive_ptr IValue");
2109
+ return static_cast<const c10::detail::ListImpl*>(payload.u.as_intrusive_ptr)
2110
+ ->list;
2111
+ }
2112
+ inline c10::Dict<IValue, IValue> IValue::toGenericDict() && {
2113
+ AT_ASSERT(isGenericDict(), "Expected GenericDict but got ", tagKind());
2114
+ return c10::Dict<IValue, IValue>(moveToIntrusivePtr<c10::detail::DictImpl>());
2115
+ }
2116
+ inline c10::Dict<IValue, IValue> IValue::toGenericDict() const& {
2117
+ AT_ASSERT(isGenericDict(), "Expected GenericDict but got ", tagKind());
2118
+ return c10::Dict<IValue, IValue>(toIntrusivePtr<c10::detail::DictImpl>());
2119
+ }
2120
+ inline c10::intrusive_ptr<ivalue::Tuple> IValue::toTuple() && {
2121
+ AT_ASSERT(isTuple(), "Expected Tuple but got ", tagKind());
2122
+ return moveToIntrusivePtr<ivalue::Tuple>();
2123
+ }
2124
+ inline c10::intrusive_ptr<ivalue::Tuple> IValue::toTuple() const& {
2125
+ AT_ASSERT(isTuple(), "Expected Tuple but got ", tagKind());
2126
+ return toIntrusivePtr<ivalue::Tuple>();
2127
+ }
2128
+ inline ivalue::Tuple& IValue::toTupleRef() const {
2129
+ AT_ASSERT(isTuple(), "Expected Tuple but got ", tagKind());
2130
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2131
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2132
+ "called toTupleRef on null intrusive_ptr IValue");
2133
+ return *static_cast<c10::ivalue::Tuple*>(
2134
+ payload.u.as_intrusive_ptr);
2135
+ }
2136
+
2137
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::Tuple> v)
2138
+ : tag(Tag::Tuple) {
2139
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2140
+ }
2141
+ template <
2142
+ typename... Args,
2143
+ std::enable_if_t<
2144
+ !std::disjunction_v<
2145
+ std::is_lvalue_reference<Args>...,
2146
+ std::negation<std::is_constructible<IValue, Args>>...>,
2147
+ std::nullptr_t>>
2148
+ inline IValue::IValue(const std::tuple<Args...>& t)
2149
+ : IValue(std::apply(c10::ivalue::Tuple::create<const Args&...>, t)) {
2150
+ }
2151
+
2152
+ template <
2153
+ typename... Args,
2154
+ std::enable_if_t<
2155
+ !std::disjunction_v<
2156
+ std::is_lvalue_reference<Args>...,
2157
+ std::negation<std::is_constructible<IValue, Args>>...>,
2158
+ std::nullptr_t>>
2159
+ inline IValue::IValue(std::tuple<Args...>&& t)
2160
+ : IValue(std::apply(c10::ivalue::Tuple::create<Args&&...>, std::move(t))) {
2161
+ }
2162
+
2163
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::ConstantString> v)
2164
+ : tag(Tag::String) {
2165
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2166
+ }
2167
+ inline IValue::IValue(std::string v)
2168
+ : IValue(ivalue::ConstantString::create(std::move(v))) {}
2169
+
2170
+ inline IValue::IValue(c10::impl::GenericList v)
2171
+ : tag(Tag::GenericList) {
2172
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.impl_.release());
2173
+ }
2174
+
2175
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2176
+ inline IValue::IValue(c10::List<T>&& v) : IValue(impl::toList<T>(std::move(v))) {}
2177
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2178
+ inline IValue::IValue(const c10::List<T>& v) : IValue(impl::toList<T>(v)) {}
2179
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2180
+ inline IValue::IValue(at::ArrayRef<T> v) : IValue(c10::List<T>()) {
2181
+ auto list = to<c10::List<T>>();
2182
+ list.reserve(v.size());
2183
+ for (const auto& e : v) {
2184
+ list.push_back(e);
2185
+ }
2186
+ }
2187
+ template <class T, IValue::enable_if_symint<T>>
2188
+ inline IValue::IValue(at::ArrayRef<T> v) : IValue() {
2189
+ auto vi = c10::asIntArrayRefSlowOpt(v);
2190
+ if (vi.has_value()) {
2191
+ // This list is entirely integers; ensure it is typed as
2192
+ // an IntList so toIntList works
2193
+ *this = IValue(*vi);
2194
+ } else {
2195
+ // This list has SymInts; type it as a SymInt
2196
+ *this = IValue(impl::toList<c10::SymInt>(c10::List<c10::SymInt>()));
2197
+ auto list = to<c10::List<c10::SymInt>>();
2198
+ list.reserve(v.size());
2199
+ for (const auto& e : v) {
2200
+ list.push_back(e);
2201
+ }
2202
+ }
2203
+ }
2204
+ template <class T, IValue::enable_if_symint<T>>
2205
+ inline IValue::IValue(at::OptionalArrayRef<T> mb_v) : IValue() {
2206
+ if (!mb_v.has_value()) return;
2207
+ *this = IValue(*mb_v);
2208
+ }
2209
+ template <class T, IValue::enable_if_symint<T>>
2210
+ inline IValue::IValue(const std::vector<T>& v) : IValue() {
2211
+ *this = IValue(at::ArrayRef<T>(v));
2212
+ }
2213
+ template <class T, IValue::enable_if_symint<T>>
2214
+ inline IValue::IValue(std::vector<T>&& v) : IValue() {
2215
+ auto vi = c10::asIntArrayRefSlowOpt(v);
2216
+ if (vi.has_value()) {
2217
+ // This list is entirely integers; ensure it is typed as
2218
+ // an IntList so toIntList works
2219
+ *this = IValue(*vi);
2220
+ } else {
2221
+ // This list has SymInts; type it as a SymInt
2222
+ *this = IValue(impl::toList<c10::SymInt>(c10::List<c10::SymInt>()));
2223
+ auto list = to<c10::List<c10::SymInt>>();
2224
+ list.reserve(v.size());
2225
+ for (auto&& e : std::move(v)) {
2226
+ list.push_back(std::move(e));
2227
+ }
2228
+ }
2229
+ }
2230
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2231
+ inline IValue::IValue(const std::vector<T>& v) : IValue(c10::List<T>()) {
2232
+ auto list = to<c10::List<T>>();
2233
+ list.reserve(v.size());
2234
+ for (const auto& e : v) {
2235
+ list.push_back(e);
2236
+ }
2237
+ }
2238
+
2239
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2240
+ inline IValue::IValue(std::vector<T>&& v) : IValue(c10::List<T>()) {
2241
+ auto list = to<c10::List<T>>();
2242
+ list.reserve(v.size());
2243
+ if constexpr (std::is_same_v<T, bool>) {
2244
+ for (auto e : v) {
2245
+ list.push_back(e);
2246
+ }
2247
+ } else {
2248
+ for (auto&& e : std::move(v)) {
2249
+ list.push_back(std::move(e));
2250
+ }
2251
+ }
2252
+ }
2253
+
2254
+ template <class T, IValue::enable_if_list_is_ivalue_constructible<T>>
2255
+ inline IValue::IValue(c10::OptionalArrayRef<T> v) : IValue() {
2256
+ if (v.has_value()) {
2257
+ *this = IValue(std::move(*v));
2258
+ }
2259
+ }
2260
+
2261
+ template <class T, size_t N>
2262
+ inline IValue::IValue(std::array<T, N> v) : IValue(c10::List<T>()) {
2263
+ auto list = to<c10::List<T>>();
2264
+ list.reserve(v.size());
2265
+ for (auto& e : v) {
2266
+ list.push_back(std::move(e));
2267
+ }
2268
+ }
2269
+
2270
+ template <class T, IValue::enable_if_ilist_is_ivalue_constructible<T>>
2271
+ inline IValue::IValue(c10::IListRef<T> v) : IValue() {
2272
+ constexpr bool boxed_type_constructs_ivalue =
2273
+ std::is_constructible_v<IValue, typename c10::IListRef<T>::boxed_type>;
2274
+ // First, we try to use the boxed value.
2275
+ // If we fail (either it's not in the boxed state, or its boxed type
2276
+ // can not construct an IValue), we fallback to copying the list.
2277
+ if (boxed_type_constructs_ivalue && v.isBoxed()) {
2278
+ *this = IValue(impl::toList(v.toBoxed()));
2279
+ } else {
2280
+ c10::List<T> list;
2281
+ list.reserve(v.size());
2282
+ for (const auto& t : v) {
2283
+ list.push_back(t);
2284
+ }
2285
+ *this = IValue(impl::toList(std::move(list)));
2286
+ }
2287
+ }
2288
+
2289
+ inline IValue::IValue(c10::impl::GenericDict v)
2290
+ : tag(Tag::GenericDict) {
2291
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.impl_.release());
2292
+ }
2293
+ template <class Key, class Value>
2294
+ inline IValue::IValue(c10::Dict<Key, Value> v)
2295
+ : IValue(impl::toGenericDict(std::move(v))) {}
2296
+
2297
+ template <class Key, class Value>
2298
+ inline IValue::IValue(std::unordered_map<Key, Value> v)
2299
+ : IValue(Dict<Key, Value>()) {
2300
+ auto dict = to<c10::Dict<Key, Value>>();
2301
+ dict.reserve(v.size());
2302
+ for (auto& e : v) {
2303
+ dict.insert(std::move(e.first), std::move(e.second));
2304
+ }
2305
+ }
2306
+
2307
+ template <class T, IValue::enable_if_ivalue_constructible<T>>
2308
+ inline IValue::IValue(std::optional<T> v) : IValue() {
2309
+ if (v.has_value()) {
2310
+ *this = IValue(std::move(*v));
2311
+ }
2312
+ }
2313
+
2314
+ inline IValue::IValue(std::nullopt_t) : IValue() {}
2315
+
2316
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::Object> v)
2317
+ : tag(Tag::Object) {
2318
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2319
+ }
2320
+
2321
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::PyObjectHolder> v)
2322
+ : tag(Tag::PyObject) {
2323
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2324
+ }
2325
+
2326
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::EnumHolder> v)
2327
+ : tag(Tag::Enum) {
2328
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2329
+ }
2330
+
2331
+ inline IValue IValue::make_capsule(
2332
+ intrusive_ptr<torch::CustomClassHolder> blob) {
2333
+ IValue iv;
2334
+ iv.tag = Tag::Capsule;
2335
+ iv.payload.u.as_intrusive_ptr = null_to_undefined_tensor(blob.release());
2336
+ return iv;
2337
+ }
2338
+
2339
+ template <
2340
+ typename T,
2341
+ std::enable_if_t<std::is_base_of_v<torch::CustomClassHolder, T>, int>>
2342
+ IValue::IValue(c10::intrusive_ptr<T> custom_class) : tag(Tag::Object) {
2343
+ auto classType = []() {
2344
+ try {
2345
+ return c10::getCustomClassType<c10::intrusive_ptr<T>>();
2346
+ } catch (const c10::Error&) {
2347
+ throw c10::Error(
2348
+ "Trying to instantiate a class that isn't a registered custom class: " +
2349
+ std::string(c10::util::get_fully_qualified_type_name<T>()));
2350
+ }
2351
+ }();
2352
+ auto ivalue_obj = c10::ivalue::Object::create(std::move(classType), /* numSlots */1);
2353
+ ivalue_obj->setSlot(0, IValue::make_capsule(std::move(custom_class)));
2354
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(ivalue_obj.release());
2355
+
2356
+ }
2357
+
2358
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::Future> v)
2359
+ : tag(Tag::Future) {
2360
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2361
+ }
2362
+
2363
+ inline IValue::IValue(c10::intrusive_ptr<ivalue::Await> v)
2364
+ : tag(Tag::Await) {
2365
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2366
+ }
2367
+
2368
+ inline IValue::IValue(c10::intrusive_ptr<c10::RRefInterface> v)
2369
+ : tag(Tag::RRef) {
2370
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2371
+ }
2372
+
2373
+ inline IValue::IValue(c10::intrusive_ptr<at::Quantizer> v)
2374
+ : tag(Tag::Quantizer) {
2375
+ payload.u.as_intrusive_ptr = null_to_undefined_tensor(v.release());
2376
+ }
2377
+
2378
+ template <typename T>
2379
+ inline IValue::IValue(c10::complex<T> c)
2380
+ : tag(Tag::ComplexDouble) {
2381
+ auto v = c10::make_intrusive<ivalue::ComplexHolder>(c);
2382
+ payload.u.as_intrusive_ptr = v.release();
2383
+ }
2384
+
2385
+ inline const std::string& IValue::toStringRef() const {
2386
+ AT_ASSERT(isString(), "Expected String but got ", tagKind());
2387
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2388
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2389
+ "called toStringRef on null intrusive_ptr IValue");
2390
+ return static_cast<const c10::ivalue::ConstantString*>(
2391
+ payload.u.as_intrusive_ptr)
2392
+ ->string();
2393
+ }
2394
+ inline std::optional<std::reference_wrapper<const std::string>> IValue::
2395
+ toOptionalStringRef() const {
2396
+ if (isNone()) {
2397
+ return std::nullopt;
2398
+ }
2399
+ AT_ASSERT(isString(), "Expected std::optional<string> but got ", tagKind());
2400
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2401
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2402
+ "called toOptionalStringRef on null intrusive_ptr IValue");
2403
+ return std::reference_wrapper<const std::string>(
2404
+ static_cast<const c10::ivalue::ConstantString*>(payload.u.as_intrusive_ptr)
2405
+ ->string());
2406
+ }
2407
+
2408
+ inline std::string_view IValue::toStringView() const {
2409
+ AT_ASSERT(isString(), "Expected String but got ", tagKind());
2410
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
2411
+ payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton(),
2412
+ "called toStringView on null intrusive_ptr IValue");
2413
+ return static_cast<const c10::ivalue::ConstantString*>(
2414
+ payload.u.as_intrusive_ptr)
2415
+ ->string_view();
2416
+ }
2417
+
2418
+ inline PyObject* IValue::toPyObject() const {
2419
+ return toPyObjectHolder()->getPyObject();
2420
+ }
2421
+
2422
+ template <typename T>
2423
+ inline std::optional<T> IValue::toOptional() {
2424
+ if (this->isNone()) {
2425
+ return std::nullopt;
2426
+ }
2427
+ return this->to<T>();
2428
+ }
2429
+
2430
+ template <typename T>
2431
+ inline std::optional<T> IValue::toOptional() const {
2432
+ if (this->isNone()) {
2433
+ return std::nullopt;
2434
+ }
2435
+ return this->to<T>();
2436
+ }
2437
+
2438
+ inline bool IValue::isCustomClass() const {
2439
+ return torch::isCustomClass(*this);
2440
+ }
2441
+
2442
+ inline bool IValue::isSameIdentity(const IValue& rhs) const {
2443
+ // We choose to not use memcmp for payload check due to potential random
2444
+ // padding characters on union type
2445
+
2446
+ // Semantics:
2447
+ // 1. Immutable primitive values of the same type (Int, Double, None, Bool,
2448
+ // Str) return value equality
2449
+ // 2. If it is a tensor type, we need to take undefined tensor into account
2450
+ // 3. Undefined_tensor is None and vice versa should be true
2451
+ // 4. If it is a reference type (i.e. isIntrusivePtr()), then is True when
2452
+ // the pointed-to object is the same.
2453
+ // 5. False for all other comparisons.
2454
+ if (this->isNone() && rhs.isNone()) {
2455
+ return true;
2456
+ } else if (this->isBool() && rhs.isBool()) {
2457
+ // for bool type, do equality check
2458
+ return this->toBool() == rhs.toBool();
2459
+ } else if (this->isTensor() && rhs.isTensor()) {
2460
+ return this->payload.as_tensor.is_same(rhs.payload.as_tensor);
2461
+ } else if (this->isTensor() && rhs.isNone()) {
2462
+ // special case: undefined tensor and None are the same identity
2463
+ return !this->payload.as_tensor.defined();
2464
+ } else if (this->isNone() && rhs.isTensor()) {
2465
+ // special case: undefined tensor and None are the same identity
2466
+ return !rhs.payload.as_tensor.defined();
2467
+ } else if (this->isInt() && rhs.isInt()) {
2468
+ return this->toInt() == rhs.toInt();
2469
+ } else if (this->isDouble() && rhs.isDouble()) {
2470
+ return this->toDouble() == rhs.toDouble();
2471
+ } else if (this->isString() && rhs.isString()) {
2472
+ return this->toStringRef() == rhs.toStringRef();
2473
+ } else {
2474
+ // for objects holding in IValue, do shallow compare on pointer address to
2475
+ // testify the identity
2476
+ return this->isIntrusivePtr() && rhs.isIntrusivePtr() &&
2477
+ this->payload.u.as_intrusive_ptr == rhs.payload.u.as_intrusive_ptr;
2478
+ }
2479
+ }
2480
+
2481
+ namespace ivalue {
2482
+ namespace detail {
2483
+
2484
+ template <typename T>
2485
+ IValue from_(T&& x, std::true_type) {
2486
+ return IValue(std::forward<T>(x));
2487
+ }
2488
+ template <typename T>
2489
+ IValue from_(c10::intrusive_ptr<T> x, std::false_type) {
2490
+ return IValue(std::move(x));
2491
+ }
2492
+ template <typename T>
2493
+ IValue from_(T&& /*x*/, std::false_type) {
2494
+ static_assert(
2495
+ guts::false_t<T>::value,
2496
+ "You are calling from with a type that it doesn't support, and isn't a potential custom class (ie: is an intrusive_ptr)");
2497
+ return IValue();
2498
+ }
2499
+ } // namespace detail
2500
+
2501
+ template <typename T>
2502
+ IValue from(T&& x) {
2503
+ return detail::from_(
2504
+ std::forward<T>(x), typename std::is_constructible<IValue, T>::type{});
2505
+ }
2506
+
2507
+ } // namespace ivalue
2508
+
2509
+
2510
+ template <>
2511
+ struct MaybeOwnedTraits<IValue> {
2512
+ using owned_type = IValue;
2513
+ using borrow_type = IValue;
2514
+
2515
+ static borrow_type createBorrow(const owned_type& from) {
2516
+ if (!from.isPtrType()) {
2517
+ return from;
2518
+ }
2519
+ if (from.isTensor()) {
2520
+ return IValue(MaybeOwnedTraits<at::Tensor>::createBorrow(from.toTensor()));
2521
+ } else {
2522
+ return IValue(from.payload, from.tag);
2523
+ }
2524
+ }
2525
+
2526
+ static void assignBorrow(borrow_type& lhs, const borrow_type& rhs) {
2527
+ lhs.clearToNone();
2528
+ if (!rhs.isPtrType()) {
2529
+ lhs = rhs;
2530
+ } else if (rhs.isTensor()) {
2531
+ lhs = IValue(MaybeOwnedTraits<at::Tensor>::createBorrow(rhs.toTensor()));
2532
+ } else {
2533
+ lhs = IValue(rhs.payload, rhs.tag);
2534
+ }
2535
+ }
2536
+
2537
+ static void destroyBorrow(borrow_type& toDestroy) {
2538
+ toDestroy.clearToNone();
2539
+ }
2540
+
2541
+ static const owned_type& referenceFromBorrow(const borrow_type& borrow) {
2542
+ return borrow;
2543
+ }
2544
+
2545
+ static const owned_type* pointerFromBorrow(const borrow_type& borrow) {
2546
+ return &borrow;
2547
+ }
2548
+
2549
+ static bool debugBorrowIsValid(const borrow_type&) {
2550
+ return true;
2551
+ }
2552
+ };
2553
+
2554
+ template <>
2555
+ struct IValue::TagType<c10::Type> {
2556
+ static TORCH_API c10::TypePtr get(const IValue&);
2557
+ };
2558
+
2559
+ template <>
2560
+ struct IValue::TagType<c10::DynamicType> {
2561
+ static TORCH_API c10::TypePtr get(const IValue&);
2562
+ };
2563
+
2564
+ template <typename T>
2565
+ TypePtr IValue::type() const {
2566
+ return IValue::TagType<T>::get(*this);
2567
+ }
2568
+
2569
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/ivalue_to.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+ } // namespace at
8
+
9
+ namespace c10 {
10
+ struct IValue;
11
+ namespace detail {
12
+ // Determine the return type of `IValue::to() const &`. It's a const
13
+ // reference when possible and a copy otherwise. It is in this
14
+ // separate header so that List can use it as well.
15
+ template<typename T>
16
+ struct ivalue_to_const_ref_overload_return {
17
+ using type = T;
18
+ };
19
+
20
+ template<>
21
+ struct ivalue_to_const_ref_overload_return<at::Tensor> {
22
+ using type = const at::Tensor&;
23
+ };
24
+
25
+ template<>
26
+ struct ivalue_to_const_ref_overload_return<std::string> {
27
+ using type = const std::string&;
28
+ };
29
+
30
+ template<>
31
+ struct ivalue_to_const_ref_overload_return<IValue> {
32
+ using type = const IValue&;
33
+ };
34
+
35
+ } // namespace detail
36
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/jit_type.h ADDED
@@ -0,0 +1,2437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/custom_class.h>
4
+ #include <ATen/core/jit_type_base.h>
5
+ #include <ATen/core/TensorBody.h>
6
+ #include <ATen/core/functional.h>
7
+ #include <ATen/core/symbol.h>
8
+ #include <ATen/core/type_factory.h>
9
+ #include <ATen/core/qualified_name.h>
10
+ #include <c10/util/TypeList.h>
11
+ #include <optional>
12
+ #include <c10/core/SymFloat.h>
13
+ #include <c10/core/SymBool.h>
14
+ #include <c10/core/Device.h>
15
+
16
+ #include <array>
17
+ #include <memory>
18
+ #include <ostream>
19
+ #include <sstream>
20
+ #include <utility>
21
+
22
+
23
+ namespace torch::jit {
24
+ struct Function;
25
+ } // namespace torch::jit
26
+
27
+
28
+ namespace c10 {
29
+
30
+ template<class Key, class Value>
31
+ class Dict;
32
+ struct IValue;
33
+ struct FunctionSchema;
34
+ struct NamedType;
35
+ using OptNameList = std::optional<std::vector<std::string>>;
36
+
37
+ void standardizeVectorForUnion(std::vector<TypePtr>& reference, std::vector<TypePtr>* to_fill);
38
+ void standardizeVectorForUnion(std::vector<TypePtr>* to_flatten);
39
+
40
+ inline bool is_contiguous_strides(
41
+ const IntArrayRef sizes,
42
+ const IntArrayRef strides) {
43
+ int n_dim = static_cast<int>(sizes.size());
44
+ if (n_dim == 0) {
45
+ return true;
46
+ }
47
+
48
+ if (strides[n_dim - 1] != 1) {
49
+ return false;
50
+ }
51
+
52
+ for (int i = n_dim - 2; i >= 0; i--) {
53
+ if (strides[i] != strides[i + 1] * sizes[i + 1]) {
54
+ return false;
55
+ }
56
+ }
57
+ return true;
58
+ }
59
+
60
+ struct AnyType;
61
+ using AnyTypePtr = SingletonTypePtr<AnyType>;
62
+ // Any is the top of the type hierarchy, all other types are subtypes
63
+ // T <: Any, forall T
64
+ struct TORCH_API AnyType : public Type {
65
+ bool equals(const Type& rhs) const override {
66
+ return rhs.kind() == kind();
67
+ }
68
+ std::string str() const override {
69
+ return "Any";
70
+ }
71
+ static const TypeKind Kind = TypeKind::AnyType;
72
+ // global singleton
73
+ static AnyTypePtr get();
74
+
75
+ private:
76
+ AnyType() : Type(TypeKind::AnyType) {}
77
+ };
78
+
79
+ inline std::string toString(const Type& type) {
80
+ return type.str();
81
+ }
82
+
83
+ // Shim for compatibility with code that uses TypePtr.
84
+ inline std::string toString(const TypePtr& typePtr) {
85
+ return toString(*typePtr);
86
+ }
87
+
88
+ inline bool operator!=(const Type& lhs, const Type& rhs) {
89
+ return !(lhs == rhs);
90
+ }
91
+
92
+ // common base for all types that have a single sub element
93
+ // e.g. Future[T], Optional[T], List[T]
94
+ template <TypeKind K, typename T>
95
+ struct SingleElementType : public SharedType {
96
+ static const TypeKind Kind = K;
97
+
98
+ const TypePtr& getElementType() const {
99
+ return elem;
100
+ }
101
+
102
+ bool hasFreeVariables() const override {
103
+ return getElementType()->hasFreeVariables();
104
+ }
105
+
106
+ at::ArrayRef<TypePtr> containedTypes() const override {
107
+ return elem;
108
+ }
109
+
110
+ bool equals(const Type& rhs) const override {
111
+ if (auto rhs_ = rhs.cast<T>()) {
112
+ return *getElementType() == *rhs_->getElementType();
113
+ }
114
+ return false;
115
+ }
116
+
117
+ protected:
118
+ SingleElementType(TypePtr elem) : SharedType(Kind), elem(std::move(elem)) {
119
+ if (!this->elem) {
120
+ throw std::runtime_error(c10::str(
121
+ "Can not create ", typeKindToString(Kind), " with None type"));
122
+ }
123
+ }
124
+
125
+ private:
126
+ TypePtr elem;
127
+ };
128
+
129
+ struct UnionType;
130
+ using UnionTypePtr = std::shared_ptr<UnionType>;
131
+ struct TORCH_API UnionType : public SharedType {
132
+ friend struct Type;
133
+
134
+ static const TypeKind Kind = TypeKind::UnionType;
135
+
136
+ bool isSubtypeOfExt(const Type& rhs_, std::ostream* why_not) const override;
137
+
138
+ std::string str() const override;
139
+
140
+ static UnionTypePtr create(std::vector<TypePtr> reference);
141
+
142
+ bool equals(const Type& rhs) const override;
143
+
144
+ bool isUnionType() const override {
145
+ return true;
146
+ }
147
+
148
+ at::ArrayRef<TypePtr> containedTypes() const override {
149
+ return types_;
150
+ }
151
+
152
+ // For testing purposes only
153
+ at::ArrayRef<TypePtr> getTypes() const {
154
+ return types_;
155
+ }
156
+
157
+ TypePtr createWithContained(std::vector<TypePtr> contained_types) const override {
158
+ return create(std::move(contained_types));
159
+ }
160
+
161
+ bool canHoldType(const Type& type) const;
162
+
163
+ bool hasFreeVariables() const override {
164
+ return has_free_variables_;
165
+ }
166
+
167
+ std::optional<TypePtr> toOptional() const;
168
+
169
+ std::optional<TypePtr> subtractTypeSet(std::vector<TypePtr>& to_subtract) const;
170
+
171
+ protected:
172
+ explicit UnionType(std::vector<TypePtr> types, TypeKind kind=TypeKind::UnionType);
173
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override;
174
+ std::string unionStr(
175
+ const TypePrinter& printer = nullptr,
176
+ bool is_annotation_str = false) const;
177
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
178
+ bool has_free_variables_;
179
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
180
+ std::vector<TypePtr> types_;
181
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
182
+ bool can_hold_none_;
183
+
184
+ };
185
+
186
+ struct OptionalType;
187
+ using OptionalTypePtr = std::shared_ptr<OptionalType>;
188
+ // This type represents an optional type. There is one `Optional` for
189
+ // each element type. `Optional[T]` can accept both `T` and
190
+ // `None`(`std::nullopt` in C++)
191
+ // Subtype hierarchy for Optional:
192
+ // - Optional[T] <: Optional[R] iff T <: R
193
+ // - T <: Optional[R] if T <: R
194
+ // - None <: Optional[T] for all T
195
+ // - Optional[T] == Union[T, None] for all T
196
+ struct TORCH_API OptionalType : public UnionType {
197
+ static OptionalTypePtr create(const TypePtr& contained);
198
+
199
+ static const TypeKind Kind = TypeKind::OptionalType;
200
+
201
+ friend struct Type;
202
+
203
+ bool equals(const Type& rhs) const override;
204
+
205
+ const TypePtr& getElementType() const {
206
+ return contained_;
207
+ }
208
+
209
+ at::ArrayRef<TypePtr> containedTypes() const override {
210
+ return contained_;
211
+ }
212
+
213
+ std::string str() const override {
214
+ std::stringstream ss;
215
+ ss << getElementType()->str() << "?";
216
+ return ss.str();
217
+ }
218
+
219
+ TypePtr createWithContained(
220
+ std::vector<TypePtr> contained_types) const override {
221
+ AT_ASSERT(contained_types.size() == 1);
222
+ return create(contained_types[0]);
223
+ }
224
+
225
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override;
226
+
227
+ bool isUnionType() const override {
228
+ return true;
229
+ }
230
+
231
+ // common cast Optional[Tensor] for undefined tensor type
232
+ static TypePtr ofTensor();
233
+ //
234
+ // global singleton
235
+ static TypePtr get(TypePtr inner);
236
+
237
+ private:
238
+ explicit OptionalType(const TypePtr& contained);
239
+
240
+ TypePtr contained_;
241
+
242
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override {
243
+ std::stringstream ss;
244
+ ss << "Optional[" << getElementType()->annotation_str(printer) << "]";
245
+ return ss.str();
246
+ }
247
+ };
248
+
249
+ template <typename T>
250
+ inline std::optional<T> merge_primitive(
251
+ const std::optional<T>& a,
252
+ const std::optional<T>& b) {
253
+ if (a.has_value() && b.has_value() && a.value() == b.value()) {
254
+ return a;
255
+ }
256
+ return std::optional<T>{};
257
+ }
258
+
259
+ // If we see `a + b + c` and know that a, b, and c are the same size and have
260
+ // two dimensions (WxH), then we can generate a fused kernel for them. That
261
+ // fused kernel would likely have indexing math to handling both the W and H
262
+ // dimensions. However, if we knew the WxH dimensions were contiguous, we can
263
+ // pretend like we only have a single dimension, simplifying the indexing logic.
264
+ // This can be performed even if the dimensions are transposed,
265
+ // as long as a, b, and c are transposed in the same way.
266
+ // We'd like to have the compiler be able to do this dimensionality reduction,
267
+ // but simply knowing sizes is not enough.
268
+ // We can extend profiling to also record stride information.
269
+ // Rather than recording specific strides,
270
+ // we can simply order the strides from smallest to largest with
271
+ // `stride_indices` A contiguity marker on the smallest stride (c0) indicates
272
+ // the stride is precisely 1, otherwise a contiguity marker means that $stride_n
273
+ // = size_{n-1}*stride_{n-1}$
274
+ struct TORCH_API Stride {
275
+ Stride() = default;
276
+ Stride(
277
+ const std::optional<size_t>& stride_index,
278
+ std::optional<bool> contiguous,
279
+ const std::optional<size_t>& stride)
280
+ : stride_index_(stride_index), contiguous_(contiguous), stride_(stride) {}
281
+
282
+ bool operator==(const Stride& b) const {
283
+ return stride_index_ == b.stride_index_ && contiguous_ == b.contiguous_ &&
284
+ stride_ == b.stride_;
285
+ }
286
+
287
+ bool isComplete() const {
288
+ return stride_index_ && contiguous_ && stride_;
289
+ }
290
+
291
+ std::optional<size_t> stride_index_;
292
+ std::optional<bool> contiguous_;
293
+ std::optional<size_t> stride_;
294
+ };
295
+
296
+ template <>
297
+ inline std::optional<Stride> merge_primitive(
298
+ const std::optional<Stride>& a,
299
+ const std::optional<Stride>& b) {
300
+ std::optional<Stride> left = a;
301
+ std::optional<Stride> right = b;
302
+ if (!left.has_value()) {
303
+ left = {Stride()};
304
+ }
305
+ if (!right.has_value()) {
306
+ right = {Stride()};
307
+ }
308
+
309
+ auto merged_index =
310
+ merge_primitive(left->stride_index_, right->stride_index_);
311
+ auto merged_cont = merge_primitive(left->contiguous_, right->contiguous_);
312
+ auto merged_stride = merge_primitive(left->stride_, right->stride_);
313
+ auto r = Stride(merged_index, merged_cont, merged_stride);
314
+ // normalize
315
+ if (!r.stride_index_.has_value() && !r.contiguous_.has_value() &&
316
+ !r.stride_.has_value()) {
317
+ return std::optional<Stride>{};
318
+ }
319
+
320
+ return r;
321
+ }
322
+
323
+ struct TORCH_API ShapeSymbol {
324
+ // needed for use in `std::map`
325
+ ShapeSymbol() : value_(-1) {}
326
+ // is this symbol a fixed/static dimension
327
+ bool is_static() const {
328
+ return value_ >= 0;
329
+ }
330
+ bool operator==(const ShapeSymbol& b) const {
331
+ return value_ == b.value_;
332
+ }
333
+ bool operator<(const ShapeSymbol& b) const {
334
+ return value_ < b.value_;
335
+ }
336
+
337
+ static ShapeSymbol fromStaticSize(int64_t val) {
338
+ return ShapeSymbol(val);
339
+ }
340
+ int64_t static_size() const {
341
+ TORCH_CHECK(is_static());
342
+ return value_;
343
+ }
344
+
345
+ int64_t value() const {
346
+ return value_;
347
+ }
348
+
349
+ static ShapeSymbol newSymbol() {
350
+ return fromStaticSize(-static_cast<int64_t>(++num_symbols));
351
+ }
352
+ friend TORCH_API std::ostream& operator<<(
353
+ std::ostream& os,
354
+ const ShapeSymbol& s);
355
+
356
+ private:
357
+ ShapeSymbol(int64_t val) : value_(val) {}
358
+ int64_t value_;
359
+ static std::atomic<size_t> num_symbols;
360
+ };
361
+
362
+ inline ShapeSymbol merge_primitive(
363
+ const ShapeSymbol& a,
364
+ const ShapeSymbol& b) {
365
+ if (a.is_static() && b.is_static() && a == b) {
366
+ return a;
367
+ }
368
+ return ShapeSymbol::newSymbol();
369
+ }
370
+
371
+ // Shape of a Tensor represented with ShapeSymbol's. Unranked, ranked unknown
372
+ // dims, partially known and fully known shapes are all supported.
373
+ struct TORCH_API SymbolicShape {
374
+ // Unranked shape constructor.
375
+ SymbolicShape() : dims_(std::nullopt) {}
376
+
377
+ // Known rank but unknown dimentions.
378
+ SymbolicShape(std::optional<size_t> rank) : dims_(std::nullopt) {
379
+ if(!rank) {
380
+ return;
381
+ }
382
+
383
+ std::vector<ShapeSymbol> shape_symbols;
384
+ shape_symbols.reserve(*rank);
385
+ for(size_t i = 0; i < *rank; ++i) {
386
+ shape_symbols.push_back(ShapeSymbol::newSymbol());
387
+ }
388
+ dims_ = shape_symbols;
389
+ }
390
+
391
+ // Mix of known and unknown ranks
392
+ SymbolicShape(const std::vector<std::optional<int64_t>>& dims) {
393
+ std::vector<ShapeSymbol> shape_symbols;
394
+ shape_symbols.reserve(dims.size());
395
+ for(std::optional<int64_t> dim: dims) {
396
+ if(!dim) {
397
+ shape_symbols.push_back(ShapeSymbol::newSymbol());
398
+ } else {
399
+ shape_symbols.push_back(ShapeSymbol::fromStaticSize(*dim));
400
+ }
401
+ }
402
+ dims_ = shape_symbols;
403
+ }
404
+
405
+ void dump() const;
406
+
407
+ SymbolicShape(std::vector<ShapeSymbol> dims) : dims_(std::move(dims)) {}
408
+
409
+ SymbolicShape(c10::IntArrayRef dims) {
410
+ std::vector<ShapeSymbol> shape_symbols;
411
+ shape_symbols.reserve(dims.size());
412
+ for(int64_t dim : dims) {
413
+ shape_symbols.push_back(ShapeSymbol::fromStaticSize(dim));
414
+ }
415
+ dims_ = shape_symbols;
416
+ }
417
+
418
+ ShapeSymbol operator[](size_t i) const {
419
+ if (!dims_) {
420
+ throw std::runtime_error("Rank isn't fixed");
421
+ }
422
+ return (*dims_).at(i);
423
+ }
424
+
425
+ ShapeSymbol at(size_t i) const {
426
+ if (!dims_) {
427
+ throw std::runtime_error("Rank isn't fixed");
428
+ }
429
+ return (*dims_).at(i);
430
+ }
431
+
432
+ // Returns rank or nullopt in case of unranked shape.
433
+ std::optional<size_t> rank() const {
434
+ if(!dims_) {
435
+ return std::nullopt;
436
+ }
437
+ return dims_->size();
438
+ }
439
+
440
+ std::optional<std::vector<ShapeSymbol>> sizes() const {
441
+ return dims_;
442
+ }
443
+
444
+ std::optional<std::vector<bool>> symbolicDims() const {
445
+ if (!dims_) {
446
+ return std::nullopt;
447
+ }
448
+ auto symbolic_dims = std::vector<bool>();
449
+ for (const ShapeSymbol& s : *dims_) {
450
+ symbolic_dims.push_back(!s.is_static());
451
+ }
452
+ return symbolic_dims;
453
+ }
454
+
455
+ // Checks whether the shape is fully defined/complete, ie. rank and sizes
456
+ // of every dimension are known.
457
+ bool isComplete() const {
458
+ if(!dims_) {
459
+ return false;
460
+ }
461
+ for(auto d : *dims_) {
462
+ if(!d.is_static()) {
463
+ return false;
464
+ }
465
+ }
466
+ return true;
467
+ }
468
+
469
+ // Create new SymbolicShape that is result of merging self and another
470
+ // SymbolicShape. Only dimensions that are static and equal will be
471
+ // preserved.
472
+ // If either of two shapes are of unknown rank or they have unmatching rank,
473
+ // result will be unranked.
474
+ SymbolicShape merge(const SymbolicShape& other) const;
475
+
476
+ friend bool operator==(const SymbolicShape& lhs, const SymbolicShape& rhs) {
477
+ return lhs.dims_ == rhs.dims_;
478
+ }
479
+
480
+ friend bool operator!=(const SymbolicShape& lhs, const SymbolicShape& rhs) {
481
+ return !(lhs == rhs);
482
+ }
483
+
484
+ private:
485
+ std::optional<std::vector<ShapeSymbol>> dims_;
486
+ };
487
+
488
+ namespace detail {
489
+ inline bool isComplete(const Stride& s) {
490
+ return s.isComplete();
491
+ }
492
+
493
+ template<typename T>
494
+ inline bool isComplete(const T& /*t*/) {
495
+ return true;
496
+ }
497
+ }
498
+
499
+ template <typename T>
500
+ struct VaryingShape {
501
+ using ListOfOptionalElements = std::vector<std::optional<T>>;
502
+ VaryingShape(const std::vector<T>& vec)
503
+ : VaryingShape(ListOfOptionalElements(vec.begin(), vec.end())) {}
504
+
505
+ VaryingShape(c10::ArrayRef<T> vec)
506
+ : VaryingShape(ListOfOptionalElements(vec.begin(), vec.end())) {}
507
+
508
+ VaryingShape(std::optional<size_t> size = std::nullopt) : dims_(std::nullopt) {
509
+ if (size) {
510
+ dims_ = ListOfOptionalElements(*size);
511
+ }
512
+ }
513
+
514
+ VaryingShape(ListOfOptionalElements dims) : dims_(std::move(dims)) {}
515
+
516
+ VaryingShape(size_t size) : VaryingShape(std::optional<size_t>(size)) {}
517
+
518
+ bool operator==(const VaryingShape& other) const {
519
+ return dims_ == other.dims_;
520
+ }
521
+
522
+ const std::optional<T> &operator[](size_t i) const {
523
+ if (!dims_) {
524
+ throw std::runtime_error("Rank isn't fixed");
525
+ }
526
+ return (*dims_).at(i);
527
+ }
528
+
529
+ std::optional<size_t> size() const {
530
+ if (!dims_) {
531
+ return std::nullopt;
532
+ }
533
+ const auto& dims = dims_.value();
534
+ return dims.size();
535
+ }
536
+
537
+ const std::optional<ListOfOptionalElements>& sizes() const {
538
+ return dims_;
539
+ }
540
+
541
+ TORCH_API VaryingShape merge(const VaryingShape& other) const;
542
+
543
+ std::optional<std::vector<T>> concrete_sizes() const {
544
+ if (!dims_) {
545
+ return std::nullopt;
546
+ }
547
+ std::vector<T> sizes;
548
+ sizes.reserve(dims_.value().size());
549
+ for (auto d : *dims_) {
550
+ if (!d) {
551
+ return std::nullopt;
552
+ }
553
+ sizes.push_back(d.value());
554
+ }
555
+ return sizes;
556
+ }
557
+
558
+ bool isComplete() const {
559
+ if (!dims_) {
560
+ return false;
561
+ }
562
+ for (auto d : *dims_) {
563
+ if (!d || !detail::isComplete(*d)) {
564
+ return false;
565
+ }
566
+ }
567
+ return true;
568
+ }
569
+
570
+ private:
571
+ std::optional<ListOfOptionalElements> dims_;
572
+ };
573
+
574
+ struct TensorType;
575
+ // TODO: investigate making this SingletonOrSharedTypePtr<TensorType>
576
+ using TensorTypePtr = std::shared_ptr<TensorType>;
577
+ // This type represents a single Tensor with a specific size
578
+ struct TORCH_API TensorType : public SharedType {
579
+ static TensorTypePtr create(const at::Tensor& t);
580
+
581
+ // used by TensorType::create(size_t dim) which in turn used by
582
+ // shape_analysis.cpp
583
+ static TensorTypePtr create(
584
+ std::optional<at::ScalarType> scalar_type,
585
+ std::optional<Device> device,
586
+ const VaryingShape<int64_t>& sizes,
587
+ const VaryingShape<int64_t>& strides,
588
+ std::optional<bool> requires_grad,
589
+ std::optional<bool> undefined = false,
590
+ bool tensor_contiguity = false);
591
+
592
+ static TensorTypePtr create(
593
+ std::optional<at::ScalarType> scalar_type,
594
+ std::optional<Device> device,
595
+ SymbolicShape sizes,
596
+ VaryingShape<Stride> stride_,
597
+ std::optional<bool> requires_grad,
598
+ std::optional<bool> undefined = false);
599
+
600
+ static TensorTypePtr create(
601
+ std::optional<at::ScalarType> scalar_type,
602
+ std::optional<Device> device,
603
+ std::optional<size_t> dim,
604
+ std::optional<bool> requires_grad);
605
+
606
+ // overloaded create variadic template argument as it could not distinguish
607
+ // initializer list
608
+ static TensorTypePtr createContiguous(
609
+ at::ScalarType scalar_type,
610
+ at::Device device,
611
+ at::IntArrayRef sizes);
612
+
613
+ static TypePtr fromNumberType(const Type& typ);
614
+ static TypePtr fromBoolType();
615
+
616
+ std::optional<size_t> dim() const {
617
+ return sizes().size();
618
+ }
619
+
620
+ VaryingShape<int64_t> sizes() const;
621
+
622
+ VaryingShape<int64_t> strides() const;
623
+
624
+ const VaryingShape<Stride>& stride_properties() const {
625
+ return strides_;
626
+ }
627
+
628
+ const std::optional<at::Device>& device() const {
629
+ return device_;
630
+ }
631
+ const std::optional<at::ScalarType>& scalarType() const {
632
+ return scalar_type_;
633
+ }
634
+ const std::optional<bool>& requiresGrad() const {
635
+ return requires_grad_;
636
+ }
637
+ bool requires_grad() const override {
638
+ return requires_grad_ ? *requires_grad_ : true;
639
+ }
640
+
641
+ bool equals(const Type& rhs) const override;
642
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override;
643
+
644
+ std::string str() const override;
645
+
646
+ std::string repr_str() const override {
647
+ if (isInferredType()) {
648
+ return str() + " (inferred)";
649
+ } else {
650
+ return str();
651
+ }
652
+ }
653
+
654
+ std::optional<size_t> numel() const {
655
+ size_t prod = 1;
656
+ const auto& shape = sizes();
657
+
658
+ for (size_t i = 0; i < shape.size(); i++) {
659
+ auto const &s = shape[i];
660
+ if (!s.has_value()) {
661
+ return std::optional<size_t>{};
662
+ }
663
+ prod *= s.value();
664
+ }
665
+ return prod;
666
+ }
667
+
668
+ TensorTypePtr withRequiresGrad(std::optional<bool> s) {
669
+ auto copy = clone();
670
+ copy->requires_grad_ = s;
671
+ return copy;
672
+ }
673
+
674
+ TensorTypePtr withScalarType(std::optional<ScalarType> st) {
675
+ auto copy = clone();
676
+ copy->scalar_type_ = st;
677
+ return copy;
678
+ }
679
+
680
+ TensorTypePtr withDim(std::optional<size_t> d) {
681
+ auto copy = clone();
682
+ // withDim is only used by the legacy executor
683
+ // that only cares about the rank, so create dummy symbols)) :
684
+ copy->sizes_ = SymbolicShape(d);
685
+ copy->strides_ = VaryingShape<Stride>(d);
686
+ return copy;
687
+ }
688
+
689
+ TensorTypePtr withStrides(VaryingShape<Stride> sstrides) const {
690
+ auto cloned = clone();
691
+ cloned->strides_ = std::move(sstrides);
692
+ return cloned;
693
+ }
694
+
695
+ TensorTypePtr withSizesStrides(
696
+ at::IntArrayRef sizes,
697
+ at::IntArrayRef strides) const {
698
+ auto cloned = clone();
699
+ auto ssizes = SymbolicShape(sizes);
700
+ cloned->sizes_ = ssizes;
701
+ cloned->strides_ = computeStrideProps(sizes, strides);
702
+ return cloned;
703
+ }
704
+
705
+ TensorTypePtr withSymbolicShapes(SymbolicShape ssizes) const {
706
+ auto cloned = clone();
707
+ cloned->sizes_ = std::move(ssizes);
708
+ return cloned;
709
+ }
710
+
711
+ TensorTypePtr withSizes(at::IntArrayRef sizes) const {
712
+ return withSizesStrides(
713
+ sizes, contiguousStridesOf(sizes));
714
+ }
715
+
716
+ TensorTypePtr withDevice(const std::optional<at::Device> device) const {
717
+ auto copy = clone();
718
+ copy->device_ = device;
719
+ return copy;
720
+ }
721
+
722
+ TensorTypePtr dimensionedOnly() const {
723
+ auto copy = clone();
724
+ copy->sizes_ = SymbolicShape(sizes().size());
725
+ copy->strides_ = VaryingShape<Stride>(sizes().size());
726
+ return copy;
727
+ }
728
+
729
+ TensorTypePtr contiguous() const {
730
+ auto cloned = clone();
731
+ auto concrete_sizes = sizes().concrete_sizes();
732
+ TORCH_INTERNAL_ASSERT(concrete_sizes.has_value());
733
+ auto strides = computeStrideProps(
734
+ *concrete_sizes,
735
+ contiguousStridesOf(*concrete_sizes));
736
+ cloned->strides_ = strides;
737
+ return cloned;
738
+ }
739
+
740
+ const SymbolicShape& symbolic_sizes() const;
741
+
742
+ TensorTypePtr merge(const TensorType& other, bool merge_sizes = true) const;
743
+
744
+ bool matchTensor(const at::Tensor& t);
745
+
746
+ // is all information about the type specified except for autograd?
747
+ // This replaces the notion of a 'CompleteTensorType' that used to exist
748
+ // in the type-hierarchy. Excluding require_grad and undefined allows
749
+ // this to match the old behavior.
750
+ bool isComplete() const {
751
+ return scalar_type_ && device_ && sizes_.isComplete() && strides_.isComplete();
752
+ }
753
+
754
+ bool isInferredType() const {
755
+ return is_inferred_;
756
+ }
757
+
758
+ static TensorTypePtr getInferred() {
759
+ static auto valueInferred = TensorType::create(
760
+ /*scalar_type=*/{},
761
+ /*device=*/{},
762
+ /*sizes=*/SymbolicShape(),
763
+ /*stride=*/VaryingShape<Stride>{},
764
+ /*requires_grad=*/{},
765
+ /*undefined=*/false);
766
+ valueInferred->is_inferred_ = true;
767
+ return valueInferred;
768
+ }
769
+
770
+ // this property is used by GuardElimination
771
+ // please see `checkInputs` for more details
772
+ bool isSummarized() const {
773
+ return !(isComplete() && requiresGrad().has_value() &&
774
+ undefined().has_value());
775
+ }
776
+
777
+ TensorTypePtr withUndefined() {
778
+ auto r = clone();
779
+ r->undefined_ = true;
780
+ return r;
781
+ }
782
+
783
+ TensorTypePtr withPossiblyUndefined() {
784
+ auto r = clone();
785
+ r->undefined_ = std::nullopt;
786
+ return r;
787
+ }
788
+
789
+ std::optional<bool> undefined() const { return undefined_; }
790
+
791
+ static const TensorTypePtr& get();
792
+
793
+ static const TypeKind Kind = TypeKind::TensorType;
794
+
795
+ static std::vector<int64_t> contiguousStridesOf(
796
+ at::IntArrayRef in_sizes,
797
+ at::MemoryFormat memory_format = MemoryFormat::Contiguous) {
798
+ auto contiguous_fn = [](const at::IntArrayRef& sizes,
799
+ const std::vector<int64_t>& dim_order) {
800
+ std::vector<int64_t> strides(sizes.size());
801
+ if (sizes.empty()) // zero-dim case
802
+ return strides;
803
+
804
+ strides[dim_order[0]] = 1;
805
+ for (size_t i = 1; i < dim_order.size(); i++) {
806
+ auto cur_dim = dim_order[i];
807
+ auto pre_dim = dim_order[i - 1];
808
+ strides[cur_dim] = strides[pre_dim] * sizes[pre_dim];
809
+ }
810
+ return strides;
811
+ };
812
+
813
+ std::vector<int64_t> dim_order(in_sizes.size());
814
+ if (memory_format == MemoryFormat::ChannelsLast) {
815
+ dim_order = {1, 3, 2, 0};
816
+ } else if (memory_format == MemoryFormat::ChannelsLast3d) {
817
+ dim_order = {1, 4, 3, 2, 0};
818
+ } else {
819
+ auto ndims = in_sizes.size();
820
+ for (size_t i = 0; i < ndims; i++) {
821
+ dim_order[i] = static_cast<int64_t>(ndims - i - 1); // Reverse
822
+ }
823
+ }
824
+ return contiguous_fn(in_sizes, dim_order);
825
+ }
826
+
827
+ private:
828
+ TensorType(
829
+ std::optional<at::ScalarType> scalar_type,
830
+ std::optional<Device> device,
831
+ SymbolicShape sizes,
832
+ VaryingShape<Stride> strides,
833
+ std::optional<bool> requires_grad,
834
+ std::optional<bool> undefined = false);
835
+
836
+ TensorTypePtr clone() const {
837
+ return TensorTypePtr(new TensorType(
838
+ scalar_type_, device_, sizes_, strides_, requires_grad_, undefined_));
839
+ }
840
+
841
+ static VaryingShape<Stride> computeStrideProps(
842
+ at::IntArrayRef sizes,
843
+ at::IntArrayRef strides,
844
+ bool tensor_contiguity = false);
845
+
846
+ std::optional<at::ScalarType> scalar_type_;
847
+ std::optional<at::Device> device_;
848
+ SymbolicShape sizes_;
849
+ VaryingShape<Stride> strides_;
850
+ std::optional<bool> requires_grad_;
851
+ // we exploit the fact certain tensors must be zero in the autograd to
852
+ // optimize gradient computation. Such zero tensors are currently implemented
853
+ // with `UndefinedTensorImpl.` They can be handled only by special operators
854
+ // (e.g. `AutogradAdd`) and their `Tensor::defined()` property returns false.
855
+ // Normally, `undefined_` is set to false, unless a type was created
856
+ // with `withUndefined`
857
+ // This will also mean that `undefined` tensors will fail
858
+ // `subtypeOf(TensorType::get())` check
859
+ // undefined_ may become `std::nullopt` if the tensor was observed to be both
860
+ // defined and undefined. However, no tensor type starts out with
861
+ // `undefined_` set to `std::nullopt`
862
+ std::optional<bool> undefined_;
863
+ // Represents whether or not this type was inferred.
864
+ bool is_inferred_ = false;
865
+ };
866
+
867
+ struct ListType;
868
+ using ListTypePtr = std::shared_ptr<ListType>;
869
+ struct TORCH_API ListType
870
+ : public SingleElementType<TypeKind::ListType, ListType> {
871
+ // It's not exactly a singleton, but there should be exactly one instance of
872
+ // List[T] for every T
873
+ friend struct Type;
874
+ template <typename... T>
875
+ static ListTypePtr create(T&&... all) {
876
+ return ListTypePtr(
877
+ new ListType(std::forward<T>(all)...)); // NOLINT(modernize-make-shared)
878
+ }
879
+
880
+ std::string str() const override {
881
+ std::stringstream ss;
882
+ ss << getElementType()->str() << "[]";
883
+ return ss.str();
884
+ }
885
+ TypePtr createWithContained(
886
+ std::vector<TypePtr> contained_types) const override {
887
+ return create(std::move(contained_types.at(0)));
888
+ }
889
+
890
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override;
891
+
892
+ // global singleton
893
+ // Given an inner type T and an identifier,
894
+ // this function wil return the global singleton type pointer
895
+ // the type List<T>.
896
+ // The extra "identifier" argument is needed beccause we have multiple container types
897
+ // that all re-use this function (List<T>, array<T, N>, etc.)
898
+ static TypePtr get(const std::string& identifier, TypePtr inner);
899
+
900
+ // common cast List[Tensor]
901
+ static ListTypePtr ofTensors();
902
+ static ListTypePtr ofOptionalTensors();
903
+ static ListTypePtr ofInts();
904
+ static ListTypePtr ofSymInts();
905
+ static ListTypePtr ofFloats();
906
+ static ListTypePtr ofComplexDoubles();
907
+ static ListTypePtr ofBools();
908
+ static ListTypePtr ofStrings();
909
+ static ListTypePtr ofNumbers();
910
+
911
+ private:
912
+ ListType(TypePtr elem) : SingleElementType(std::move(elem)) {}
913
+
914
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override {
915
+ std::stringstream ss;
916
+ ss << "List[" << getElementType()->annotation_str(printer) << "]";
917
+ return ss.str();
918
+ }
919
+ };
920
+
921
+ struct DictType;
922
+ using DictTypePtr = std::shared_ptr<DictType>;
923
+ struct TORCH_API DictType : public SharedType {
924
+ friend struct Type;
925
+ static const TypeKind Kind = TypeKind::DictType;
926
+
927
+ static DictTypePtr create(TypePtr key, TypePtr value) {
928
+ auto kind = key->kind();
929
+ if (auto dyn = key->castRaw<DynamicType>()) {
930
+ kind = dyn->dynamicKind();
931
+ }
932
+ switch (kind) {
933
+ case TypeKind::AnyType:
934
+ case TypeKind::IntType:
935
+ case TypeKind::BoolType:
936
+ case TypeKind::FloatType:
937
+ case TypeKind::ComplexType:
938
+ case TypeKind::StringType:
939
+ case TypeKind::TensorType:
940
+ case TypeKind::DeviceObjType:
941
+ return DictTypePtr(new DictType(std::move(key), std::move(value)));
942
+ default:
943
+ TORCH_CHECK(false,
944
+ "Cannot create dict for key type '",
945
+ key->str(),
946
+ "', only int, float, complex, Tensor, device and string keys are supported");
947
+ }
948
+ }
949
+
950
+ // aligned with the format in FunctionSchema
951
+ std::string str() const override {
952
+ std::stringstream ss;
953
+ ss << "Dict(" << getKeyType()->str() << ", " << getValueType()->str()
954
+ << ")";
955
+ return ss.str();
956
+ }
957
+
958
+ TypePtr createWithContained(
959
+ std::vector<TypePtr> contained_types) const override {
960
+ if (contained_types.size() != 2) {
961
+ throw std::runtime_error("Expected 2 contained types");
962
+ }
963
+ return create(std::move(contained_types.at(0)), std::move(contained_types.at(1)));
964
+ }
965
+
966
+ const TypePtr& getKeyType() const {
967
+ return types.at(0);
968
+ }
969
+
970
+ const TypePtr& getValueType() const {
971
+ return types.at(1);
972
+ }
973
+
974
+ bool hasFreeVariables() const override {
975
+ return has_free_variables;
976
+ }
977
+
978
+ at::ArrayRef<TypePtr> containedTypes() const override {
979
+ return types;
980
+ }
981
+
982
+ bool equals(const Type& rhs) const override {
983
+ if (auto* dict_rhs = rhs.castRaw<DictType>()) {
984
+ return *getKeyType() == *(dict_rhs->getKeyType()) &&
985
+ *getValueType() == *(dict_rhs->getValueType());
986
+ }
987
+ return false;
988
+ }
989
+
990
+ // global singleton
991
+ // Given an inner type T and an identifier,
992
+ // this function will return the global singleton type pointer
993
+ // the type List<T>.
994
+ // The extra "identifier" argument is needed because we have multiple container types
995
+ // that all re-use this function (Dict<K, V> and unordered_map<K, V>)
996
+ static TypePtr get(const std::string& identifier, TypePtr key, TypePtr val);
997
+
998
+ private:
999
+ DictType(TypePtr key, TypePtr value)
1000
+ : SharedType(TypeKind::DictType),
1001
+ has_free_variables(
1002
+ key->hasFreeVariables() || value->hasFreeVariables()) {
1003
+ types.reserve(2);
1004
+ types.push_back(std::move(key));
1005
+ types.push_back(std::move(value));
1006
+ }
1007
+
1008
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override;
1009
+
1010
+ std::vector<TypePtr> types;
1011
+ bool has_free_variables;
1012
+ };
1013
+
1014
+ struct FutureType;
1015
+ using FutureTypePtr = std::shared_ptr<FutureType>;
1016
+
1017
+ struct TORCH_API FutureType
1018
+ : public SingleElementType<TypeKind::FutureType, FutureType> {
1019
+ friend struct Type;
1020
+ template <typename... T>
1021
+ static FutureTypePtr create(TypePtr elem) {
1022
+ return FutureTypePtr(
1023
+ new FutureType(std::move(elem))); // NOLINT(modernize-make-shared)
1024
+ }
1025
+
1026
+ std::string str() const override {
1027
+ std::stringstream ss;
1028
+ ss << "Future(" << getElementType()->str() << ")";
1029
+ return ss.str();
1030
+ }
1031
+ TypePtr createWithContained(
1032
+ std::vector<TypePtr> contained_types) const override {
1033
+ return create(std::move(contained_types.at(0)));
1034
+ }
1035
+
1036
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override {
1037
+ if (Type::isSubtypeOfExt(rhs, why_not)) {
1038
+ return true;
1039
+ }
1040
+ if (auto rhs_ = rhs.castRaw<FutureType>()) {
1041
+ return getElementType()->isSubtypeOfExt(*rhs_->getElementType(), why_not);
1042
+ }
1043
+ return false;
1044
+ }
1045
+
1046
+ private:
1047
+ FutureType(TypePtr elem) : SingleElementType(std::move(elem)) {}
1048
+
1049
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override {
1050
+ std::stringstream ss;
1051
+ ss << "Future[" << getElementType()->annotation_str(printer) << "]";
1052
+ return ss.str();
1053
+ }
1054
+ };
1055
+
1056
+ struct AwaitType;
1057
+ using AwaitTypePtr = std::shared_ptr<AwaitType>;
1058
+
1059
+ struct TORCH_API AwaitType
1060
+ : public SingleElementType<TypeKind::AwaitType, AwaitType> {
1061
+ friend struct Type;
1062
+ template <typename... T>
1063
+ static AwaitTypePtr create(TypePtr elem) {
1064
+ return AwaitTypePtr(
1065
+ new AwaitType(std::move(elem))); // NOLINT(modernize-make-shared)
1066
+ }
1067
+
1068
+ std::string str() const override {
1069
+ std::stringstream ss;
1070
+ ss << "Await(" << getElementType()->str() << ")";
1071
+ return ss.str();
1072
+ }
1073
+ TypePtr createWithContained(
1074
+ std::vector<TypePtr> contained_types) const override {
1075
+ return create(std::move(contained_types.at(0)));
1076
+ }
1077
+
1078
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override {
1079
+ if (Type::isSubtypeOfExt(rhs, why_not)) {
1080
+ return true;
1081
+ }
1082
+ if (auto rhs_ = rhs.castRaw<AwaitType>()) {
1083
+ return getElementType()->isSubtypeOfExt(*rhs_->getElementType(), why_not);
1084
+ }
1085
+ return false;
1086
+ }
1087
+
1088
+ private:
1089
+ AwaitType(TypePtr elem) : SingleElementType(std::move(elem)) {}
1090
+
1091
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override {
1092
+ std::stringstream ss;
1093
+ ss << "Await[" << getElementType()->annotation_str(printer) << "]";
1094
+ return ss.str();
1095
+ }
1096
+ };
1097
+
1098
+ struct RRefType;
1099
+ using RRefTypePtr = std::shared_ptr<RRefType>;
1100
+
1101
+ struct TORCH_API RRefType
1102
+ : public SingleElementType<TypeKind::RRefType, RRefType> {
1103
+ friend struct Type;
1104
+ template <typename... T>
1105
+ static RRefTypePtr create(TypePtr elem) {
1106
+ return RRefTypePtr(
1107
+ new RRefType(std::move(elem))); // NOLINT(modernize-make-shared)
1108
+ }
1109
+
1110
+ std::string str() const override {
1111
+ std::stringstream ss;
1112
+ ss << "RRef(" << getElementType()->str() << ")";
1113
+ return ss.str();
1114
+ }
1115
+ TypePtr createWithContained(
1116
+ std::vector<TypePtr> contained_types) const override {
1117
+ return create(std::move(contained_types.at(0)));
1118
+ }
1119
+
1120
+ private:
1121
+ RRefType(TypePtr elem) : SingleElementType(std::move(elem)) {}
1122
+
1123
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override {
1124
+ std::stringstream ss;
1125
+ ss << "RRef[" << getElementType()->annotation_str(printer) << "]";
1126
+ return ss.str();
1127
+ }
1128
+ };
1129
+
1130
+ // Any should never appear in a named type like a class, namedtuple or
1131
+ // interface. If it does, then dynamic type information will be lost in the
1132
+ // Pickler, leading to hard-to-track-down bugs that will only occur
1133
+ // after saving or loading a model. This is because we rely on the
1134
+ // static types in named types to reconstruct type tags of loaded
1135
+ // values. Lifting this restriction requires solving the serialization
1136
+ // problem first.
1137
+ TORCH_API void checkNoAny(
1138
+ const Type& base,
1139
+ const char* what,
1140
+ const std::string& attrname,
1141
+ const TypePtr& attrtype);
1142
+
1143
+ struct TupleType;
1144
+ using TupleTypePtr = std::shared_ptr<TupleType>;
1145
+ using NameList = std::vector<std::string>;
1146
+ // This type represents a Tuple
1147
+ struct TORCH_API TupleType : public NamedType {
1148
+
1149
+ static TupleTypePtr createNamed(const std::optional<c10::QualifiedName>& name,
1150
+ const std::vector<std::string>& field_names,
1151
+ const std::vector<TypePtr>& field_types,
1152
+ std::vector<IValue>& field_defaults);
1153
+
1154
+ static TupleTypePtr createNamed(const std::optional<c10::QualifiedName>& name,
1155
+ const std::vector<std::string>& field_names,
1156
+ const std::vector<TypePtr>& field_types);
1157
+
1158
+ static TupleTypePtr createNamed(const std::optional<c10::QualifiedName>& name,
1159
+ const std::vector<std::string_view>& field_names,
1160
+ const std::vector<TypePtr>& field_types);
1161
+
1162
+ static TupleTypePtr create(
1163
+ std::vector<TypePtr> types) {
1164
+ return TupleTypePtr(new TupleType(
1165
+ std::move(types),
1166
+ std::nullopt,
1167
+ nullptr)); // NOLINT(modernize-make-shared)
1168
+ }
1169
+ static TupleTypePtr create() {
1170
+ return create({});
1171
+ }
1172
+
1173
+ at::ArrayRef<TypePtr> elements() const {
1174
+ return elements_;
1175
+ }
1176
+
1177
+ bool equals(const Type& rhs) const override;
1178
+ bool isSubtypeOfExt(const Type& rhs_, std::ostream* why_not) const override;
1179
+
1180
+ std::string str() const override;
1181
+ bool hasFreeVariables() const override {
1182
+ return has_free_variables_;
1183
+ }
1184
+ at::ArrayRef<TypePtr> containedTypes() const override {
1185
+ return elements_;
1186
+ }
1187
+ TypePtr createWithContained(
1188
+ std::vector<TypePtr> contained_types) const override {
1189
+ return std::shared_ptr<TupleType>(
1190
+ new TupleType(std::move(contained_types), name(), schema()));
1191
+ }
1192
+ const std::shared_ptr<FunctionSchema>& schema() const {
1193
+ return schema_;
1194
+ }
1195
+ std::optional<std::vector<std::string_view>> names() const;
1196
+
1197
+ static const TypeKind Kind = TypeKind::TupleType;
1198
+
1199
+ private:
1200
+ template <typename S>
1201
+ static TupleTypePtr createWithSpec(
1202
+ const std::optional<c10::QualifiedName>& name,
1203
+ const std::vector<S>& field_names,
1204
+ const std::vector<TypePtr>& field_types,
1205
+ std::vector<IValue>& field_defaults);
1206
+
1207
+ TupleType(
1208
+ std::vector<TypePtr> elements_,
1209
+ std::optional<c10::QualifiedName> name,
1210
+ std::shared_ptr<FunctionSchema> schema);
1211
+
1212
+ bool compare(
1213
+ const Type& rhs,
1214
+ const std::function<bool(const Type&, const Type&)>& fn) const {
1215
+ if (rhs.kind() != kind()) {
1216
+ return false;
1217
+ }
1218
+
1219
+ const auto& l_elements = elements();
1220
+ const auto& r_elements = rhs.castRaw<TupleType>()->elements();
1221
+ if (l_elements.size() != r_elements.size())
1222
+ return false;
1223
+ for (size_t i = 0; i < l_elements.size(); ++i) {
1224
+ if (!fn(*l_elements[i], *r_elements[i]))
1225
+ return false;
1226
+ }
1227
+ return true;
1228
+ }
1229
+
1230
+ std::string annotation_str_impl(const TypePrinter& printer = nullptr) const override;
1231
+
1232
+ std::vector<TypePtr> elements_;
1233
+ bool has_free_variables_;
1234
+ std::shared_ptr<FunctionSchema> schema_;
1235
+ };
1236
+
1237
+ // the common supertype of all Enums, only used in operator registraion.
1238
+ // EnumType <: AnyEnumType for all Enums
1239
+ struct AnyEnumType;
1240
+ using AnyEnumTypePtr = SingletonTypePtr<AnyEnumType>;
1241
+ struct TORCH_API AnyEnumType final : public Type {
1242
+ bool equals(const Type& rhs) const override {
1243
+ return rhs.kind() == kind();
1244
+ }
1245
+ std::string str() const override {
1246
+ return "AnyEnumType";
1247
+ }
1248
+ static const TypeKind Kind = TypeKind::AnyEnumType;
1249
+ // global singleton
1250
+ static AnyEnumTypePtr get();
1251
+ private:
1252
+ AnyEnumType()
1253
+ : Type(TypeKind::AnyEnumType) {}
1254
+ };
1255
+
1256
+ struct NumberType;
1257
+ using NumberTypePtr = SingletonTypePtr<NumberType>;
1258
+ // This type represents a Python number
1259
+ // Subtype hierarchy for Number Types (NumberType as the base type):
1260
+ // IntType <: NumberType
1261
+ // FloatType <: NumberType
1262
+ // ComplexType <:NumberType
1263
+ //
1264
+ // WARNING: if you add a new subtype of NumberType that is not
1265
+ // represented by a global singleton, you need to change NumberTypePtr
1266
+ // to a SingletonOrSharedTypePtr and deal with NumberType needing to
1267
+ // both inherit and not inherit from SharedType!
1268
+ struct TORCH_API NumberType : public Type {
1269
+ bool equals(const Type& rhs) const override;
1270
+
1271
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override;
1272
+
1273
+ std::string str() const override {
1274
+ return "Scalar"; // match what PythonArgParser says for clarity
1275
+ }
1276
+ static const TypeKind Kind = TypeKind::NumberType;
1277
+ // global singleton
1278
+ static NumberTypePtr get();
1279
+
1280
+ protected:
1281
+ NumberType(TypeKind kind = TypeKind::NumberType) : Type(kind) {}
1282
+
1283
+ std::string annotation_str_impl(
1284
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1285
+ return "number"; // technically not a valid python type, but
1286
+ // we need to use it when parsing back in annotations
1287
+ // for implicit conversions
1288
+ }
1289
+ };
1290
+
1291
+ struct FloatType;
1292
+ using FloatTypePtr = SingletonTypePtr<FloatType>;
1293
+ // This type represents a Python float number
1294
+ struct TORCH_API FloatType : public NumberType {
1295
+ bool equals(const Type& rhs) const override {
1296
+ return rhs.kind() == kind();
1297
+ }
1298
+ std::string str() const override {
1299
+ return "float";
1300
+ }
1301
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override {
1302
+ // NOLINTNEXTLINE(bugprone-parent-virtual-call)
1303
+ return rhs.kind() == TypeKind::NumberType || Type::isSubtypeOfExt(rhs, why_not);
1304
+ }
1305
+ static const TypeKind Kind = TypeKind::FloatType;
1306
+ // global singleton
1307
+ static FloatTypePtr get();
1308
+
1309
+ private:
1310
+ FloatType() : NumberType(TypeKind::FloatType) {}
1311
+ std::string annotation_str_impl(
1312
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1313
+ return "float";
1314
+ }
1315
+ };
1316
+
1317
+ struct ComplexType;
1318
+ using ComplexTypePtr = SingletonTypePtr<ComplexType>;
1319
+ // This type represents a Python float number
1320
+ struct TORCH_API ComplexType : public NumberType {
1321
+ bool equals(const Type& rhs) const override {
1322
+ return rhs.kind() == kind();
1323
+ }
1324
+ std::string str() const override {
1325
+ return "complex";
1326
+ }
1327
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override {
1328
+ // NOLINTNEXTLINE(bugprone-parent-virtual-call)
1329
+ return rhs.kind() == TypeKind::NumberType || Type::isSubtypeOfExt(rhs, why_not);
1330
+ }
1331
+ static const TypeKind Kind = TypeKind::ComplexType;
1332
+ // global singleton
1333
+ static ComplexTypePtr get();
1334
+
1335
+ private:
1336
+ ComplexType() : NumberType(TypeKind::ComplexType) {}
1337
+ std::string annotation_str_impl(
1338
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1339
+ return "complex";
1340
+ }
1341
+ };
1342
+
1343
+ // We need to introduce `SymIntType` to represent the `SymInt` type
1344
+ // used in function schemas e.g. `aten::narrow_copy(... SymInt length)
1345
+ // `SymInt` will be used to enable tracing arithmetic operations on
1346
+ // dimension values. Please see [SymInt.h] for more information
1347
+ struct SymIntType;
1348
+ using SymIntTypePtr = SingletonTypePtr<SymIntType>;
1349
+ struct TORCH_API SymIntType : public Type {
1350
+ bool equals(const Type& rhs) const override {
1351
+ return rhs.kind() == kind();
1352
+ }
1353
+ std::string str() const override {
1354
+ return "SymInt";
1355
+ }
1356
+ std::string annotation_str_impl(const TypePrinter& printer [[maybe_unused]] = nullptr) const override {
1357
+ return "int";
1358
+ }
1359
+ static const TypeKind Kind = TypeKind::SymIntType;
1360
+ // global singleton
1361
+ static SymIntTypePtr get();
1362
+
1363
+ private:
1364
+ SymIntType() : Type(TypeKind::SymIntType) {}
1365
+ };
1366
+
1367
+ struct SymFloatType;
1368
+ using SymFloatTypePtr = SingletonTypePtr<SymFloatType>;
1369
+ struct TORCH_API SymFloatType : public Type {
1370
+ bool equals(const Type& rhs) const override {
1371
+ return rhs.kind() == kind();
1372
+ }
1373
+ std::string str() const override {
1374
+ return "SymFloat";
1375
+ }
1376
+ std::string annotation_str_impl(const TypePrinter& printer [[maybe_unused]] = nullptr) const override {
1377
+ return "float";
1378
+ }
1379
+ static const TypeKind Kind = TypeKind::SymFloatType;
1380
+ // global singleton
1381
+ static SymFloatTypePtr get();
1382
+
1383
+ private:
1384
+ SymFloatType() : Type(TypeKind::SymFloatType) {}
1385
+ };
1386
+
1387
+ struct SymBoolType;
1388
+ using SymBoolTypePtr = SingletonTypePtr<SymBoolType>;
1389
+ struct TORCH_API SymBoolType : public Type {
1390
+ bool equals(const Type& rhs) const override {
1391
+ return rhs.kind() == kind();
1392
+ }
1393
+ std::string str() const override {
1394
+ return "SymBool";
1395
+ }
1396
+ std::string annotation_str_impl(const TypePrinter& printer [[maybe_unused]] = nullptr) const override {
1397
+ return "bool";
1398
+ }
1399
+ static const TypeKind Kind = TypeKind::SymBoolType;
1400
+ // global singleton
1401
+ static SymBoolTypePtr get();
1402
+
1403
+ private:
1404
+ SymBoolType() : Type(TypeKind::SymBoolType) {}
1405
+ };
1406
+
1407
+ struct IntType;
1408
+ using IntTypePtr = SingletonTypePtr<IntType>;
1409
+ // This type represents a Python int number
1410
+ struct TORCH_API IntType : public NumberType {
1411
+ bool equals(const Type& rhs) const override {
1412
+ return rhs.kind() == kind();
1413
+ }
1414
+ std::string str() const override {
1415
+ return "int";
1416
+ }
1417
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override {
1418
+ // NOLINTNEXTLINE(bugprone-parent-virtual-call)
1419
+ return rhs.kind() == TypeKind::NumberType || Type::isSubtypeOfExt(rhs, why_not);
1420
+ }
1421
+ static const TypeKind Kind = TypeKind::IntType;
1422
+ // global singleton
1423
+ static IntTypePtr get();
1424
+
1425
+ private:
1426
+ IntType() : NumberType(TypeKind::IntType) {}
1427
+ std::string annotation_str_impl(
1428
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1429
+ return "int";
1430
+ }
1431
+ };
1432
+
1433
+ struct BoolType;
1434
+ using BoolTypePtr = SingletonTypePtr<BoolType>;
1435
+ // This node represents a Python bool value
1436
+ struct TORCH_API BoolType : public Type {
1437
+ bool equals(const Type& rhs) const override {
1438
+ return rhs.kind() == kind();
1439
+ }
1440
+ std::string str() const override {
1441
+ return "bool";
1442
+ }
1443
+ static const TypeKind Kind = TypeKind::BoolType;
1444
+ // global singleton
1445
+ static BoolTypePtr get();
1446
+
1447
+ private:
1448
+ BoolType() : Type(TypeKind::BoolType) {}
1449
+ };
1450
+
1451
+ struct StringType;
1452
+ using StringTypePtr = SingletonTypePtr<StringType>;
1453
+ // This type represents a Python string
1454
+ struct TORCH_API StringType : public Type {
1455
+ bool equals(const Type& rhs) const override {
1456
+ return rhs.kind() == kind();
1457
+ }
1458
+ std::string str() const override {
1459
+ // we only use "str" (not "string") in both FunctionSchema and script
1460
+ return annotation_str();
1461
+ }
1462
+ std::string annotation_str_impl(
1463
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1464
+ return "str";
1465
+ }
1466
+ static const TypeKind Kind = TypeKind::StringType;
1467
+ // global singleton
1468
+ static StringTypePtr get();
1469
+
1470
+ private:
1471
+ StringType() : Type(TypeKind::StringType) {}
1472
+ };
1473
+
1474
+ struct StorageType;
1475
+ using StorageTypePtr = SingletonTypePtr<StorageType>;
1476
+ struct TORCH_API StorageType : public Type {
1477
+ bool equals(const Type& rhs) const override {
1478
+ return rhs.kind() == kind();
1479
+ }
1480
+ std::string str() const override {
1481
+ return annotation_str();
1482
+ }
1483
+ std::string annotation_str_impl(
1484
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1485
+ return "Storage";
1486
+ }
1487
+ static const TypeKind Kind = TypeKind::StorageType;
1488
+ // global singleton
1489
+ static StorageTypePtr get();
1490
+
1491
+ private:
1492
+ StorageType() : Type(TypeKind::StorageType) {}
1493
+ };
1494
+
1495
+ struct FunctionType;
1496
+ using FunctionTypePtr = std::shared_ptr<FunctionType>;
1497
+ struct TORCH_API FunctionType : public NamedType {
1498
+ static FunctionTypePtr create(torch::jit::Function* function) {
1499
+ return FunctionTypePtr(
1500
+ new FunctionType(function)); // NOLINT(modernize-make-shared)
1501
+ }
1502
+ bool equals(const Type& rhs) const override {
1503
+ if (auto func_type = rhs.cast<FunctionType>()) {
1504
+ return func_type->function_ == function_;
1505
+ }
1506
+
1507
+ return false;
1508
+ }
1509
+ std::string str() const override {
1510
+ return "Function";
1511
+ }
1512
+ torch::jit::Function* function() const {
1513
+ return function_;
1514
+ }
1515
+ static const TypeKind Kind = TypeKind::FunctionType;
1516
+
1517
+ private:
1518
+ FunctionType(torch::jit::Function* function);
1519
+ std::string annotation_str_impl(
1520
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
1521
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1522
+ return name()->qualifiedName();
1523
+ }
1524
+ torch::jit::Function* function_;
1525
+ };
1526
+
1527
+ struct NoneType;
1528
+ using NoneTypePtr = SingletonTypePtr<NoneType>;
1529
+ // This type represents a Python None
1530
+ struct TORCH_API NoneType : public Type {
1531
+ bool equals(const Type& rhs) const override {
1532
+ return rhs.kind() == kind();
1533
+ }
1534
+ std::string str() const override {
1535
+ return "NoneType";
1536
+ }
1537
+ bool isSubtypeOfExt(const Type& rhs, std::ostream *why_not) const override;
1538
+
1539
+ static const TypeKind Kind = TypeKind::NoneType;
1540
+ // global singleton
1541
+ static NoneTypePtr get();
1542
+
1543
+ private:
1544
+ NoneType() : Type(TypeKind::NoneType) {}
1545
+ };
1546
+
1547
+ struct GeneratorType;
1548
+ using GeneratorTypePtr = SingletonTypePtr<GeneratorType>;
1549
+ // This type represents a Generator
1550
+ struct TORCH_API GeneratorType : public Type {
1551
+ bool equals(const Type& rhs) const override {
1552
+ return rhs.kind() == kind();
1553
+ }
1554
+ std::string str() const override {
1555
+ return "Generator";
1556
+ }
1557
+ static const TypeKind Kind = TypeKind::GeneratorType;
1558
+ // global singleton
1559
+ static GeneratorTypePtr get();
1560
+
1561
+ private:
1562
+ GeneratorType() : Type(TypeKind::GeneratorType) {}
1563
+ };
1564
+
1565
+ struct QuantizerType;
1566
+ using QuantizerTypePtr = SingletonTypePtr<QuantizerType>;
1567
+ // This type represents a Quantizer
1568
+ struct TORCH_API QuantizerType : public Type {
1569
+ bool equals(const Type& rhs) const override {
1570
+ return rhs.kind() == kind();
1571
+ }
1572
+ std::string str() const override {
1573
+ return "Quantizer";
1574
+ }
1575
+ static const TypeKind Kind = TypeKind::QuantizerType;
1576
+ // global singleton
1577
+ static QuantizerTypePtr get();
1578
+
1579
+ private:
1580
+ QuantizerType() : Type(TypeKind::QuantizerType) {}
1581
+ };
1582
+
1583
+ struct QSchemeType;
1584
+ using QSchemeTypePtr = SingletonTypePtr<QSchemeType>;
1585
+ // This type represents a QScheme
1586
+ struct TORCH_API QSchemeType : public Type {
1587
+ bool equals(const Type& rhs) const override {
1588
+ return rhs.kind() == kind();
1589
+ }
1590
+ std::string str() const override {
1591
+ return "QScheme";
1592
+ }
1593
+ static const TypeKind Kind = TypeKind::QSchemeType;
1594
+ // global singleton
1595
+ static QSchemeTypePtr get();
1596
+
1597
+ private:
1598
+ QSchemeType() : Type(TypeKind::QSchemeType) {}
1599
+ };
1600
+
1601
+ struct DeviceObjType;
1602
+ using DeviceObjTypePtr = SingletonTypePtr<DeviceObjType>;
1603
+ // This type represents a Device
1604
+ struct TORCH_API DeviceObjType : public Type {
1605
+ bool equals(const Type& rhs) const override {
1606
+ return rhs.kind() == kind();
1607
+ }
1608
+ std::string str() const override {
1609
+ return "Device";
1610
+ }
1611
+ static const TypeKind Kind = TypeKind::DeviceObjType;
1612
+ // global singleton
1613
+ static DeviceObjTypePtr get();
1614
+
1615
+ private:
1616
+ DeviceObjType() : Type(TypeKind::DeviceObjType) {}
1617
+ };
1618
+
1619
+ struct StreamObjType;
1620
+ using StreamObjTypePtr = SingletonTypePtr<StreamObjType>;
1621
+ // This type represents a Generator
1622
+ struct TORCH_API StreamObjType : public Type {
1623
+ bool equals(const Type& rhs) const override {
1624
+ return rhs.kind() == kind();
1625
+ }
1626
+ std::string str() const override {
1627
+ return "Stream";
1628
+ }
1629
+ static const TypeKind Kind = TypeKind::StreamObjType;
1630
+ // global singleton
1631
+ static StreamObjTypePtr get();
1632
+
1633
+ private:
1634
+ StreamObjType() : Type(TypeKind::StreamObjType) {}
1635
+ };
1636
+
1637
+ struct VarType;
1638
+ using VarTypePtr = std::shared_ptr<VarType>;
1639
+ // This type represents a type variable, used in FunctionSchema
1640
+ struct VarType : public SharedType {
1641
+ static VarTypePtr create(std::string name_) {
1642
+ return VarTypePtr(new VarType(std::move(name_)));
1643
+ }
1644
+ bool equals(const Type& rhs) const override {
1645
+ return rhs.kind() == kind();
1646
+ }
1647
+ std::string str() const override {
1648
+ return name();
1649
+ }
1650
+ const std::string& name() const {
1651
+ return name_;
1652
+ }
1653
+ bool hasFreeVariables() const override {
1654
+ return true;
1655
+ }
1656
+ static const TypeKind Kind = TypeKind::VarType;
1657
+
1658
+ private:
1659
+ VarType(std::string name_)
1660
+ : SharedType(TypeKind::VarType), name_(std::move(name_)) {}
1661
+ std::string name_;
1662
+ };
1663
+
1664
+ struct CapsuleType;
1665
+ using CapsuleTypePtr = SingletonTypePtr<CapsuleType>;
1666
+ // This type represents a Python Capsule.
1667
+ // It does not appear in the IR and is only used during runtime
1668
+ struct TORCH_API CapsuleType : public Type {
1669
+ bool equals(const Type& rhs) const override {
1670
+ return rhs.kind() == kind();
1671
+ }
1672
+ std::string str() const override {
1673
+ return "Capsule";
1674
+ }
1675
+ static const TypeKind Kind = TypeKind::CapsuleType;
1676
+ // global singleton
1677
+ static CapsuleTypePtr get();
1678
+ private:
1679
+ CapsuleType()
1680
+ : Type(TypeKind::CapsuleType) {}
1681
+ };
1682
+
1683
+ struct PyObjectType;
1684
+ using PyObjectTypePtr = SingletonTypePtr<PyObjectType>;
1685
+ // This type represents a PyObject Type
1686
+ struct TORCH_API PyObjectType : public Type {
1687
+ bool equals(const Type& rhs) const override {
1688
+ return rhs.kind() == kind();
1689
+ }
1690
+ std::string str() const override {
1691
+ return "PyObject";
1692
+ }
1693
+ static const TypeKind Kind = TypeKind::PyObjectType;
1694
+ // global singleton
1695
+ static PyObjectTypePtr get();
1696
+ private:
1697
+ PyObjectType()
1698
+ : Type(TypeKind::PyObjectType) {}
1699
+ };
1700
+
1701
+ enum class TypeVerbosity {
1702
+ None,
1703
+ Type,
1704
+ TypeAndStride,
1705
+ Full,
1706
+ Symbolic,
1707
+ Default = Full,
1708
+ };
1709
+
1710
+ TORCH_API TypeVerbosity type_verbosity();
1711
+
1712
+ TORCH_API std::ostream& operator<<(std::ostream& out, const Type& t);
1713
+ template <typename T>
1714
+ TORCH_API std::ostream& operator<<(
1715
+ std::ostream& out,
1716
+ const VaryingShape<T>& t);
1717
+ TORCH_API std::ostream& operator<<(std::ostream& os, const SymbolicShape& s);
1718
+ TORCH_API std::ostream& operator<<(std::ostream& os, const ShapeSymbol& s);
1719
+ TORCH_API std::ostream& operator<<(std::ostream& os, const Stride& s);
1720
+ // what is the type, ignoring extra size/shape information?
1721
+ // e.g. Tensor(2x3) -> Dynamic, and Tuple(Tensor(2x3),...) -> Tuple(Dynamic,...)
1722
+
1723
+ // `unshapedType` is used to remove Tensor subtypes. We treat all Tensor
1724
+ // subtypes as simply "Tensor"; we also create a new version of any
1725
+ // container types in which internal Tensors have undergone the same
1726
+ // operation. This is used for type comparisons between two Tensor types
1727
+ // (`unshapedType` means that we don't falsely return `false` for e.g.
1728
+ // Tensors of different dimensions). It's also used in the alias
1729
+ // analysis pass.
1730
+ // Be careful with calls because this can be very slow. If calling this
1731
+ // on a graph, use `EraseShapeInformation` in shape_analysis.h
1732
+ inline TypePtr unshapedType(const TypePtr& type) {
1733
+ if (type->isSubtypeOf(*TensorType::get())) {
1734
+ return TensorType::get();
1735
+ }
1736
+ at::ArrayRef<TypePtr> contained = type->containedTypes();
1737
+ if (contained.empty()) {
1738
+ return type;
1739
+ }
1740
+ return type->withContained(fmap(type->containedTypes(), unshapedType));
1741
+ }
1742
+
1743
+ inline TypePtr TensorType::fromNumberType(const Type& typ) {
1744
+ if (typ.isSubtypeOf(*IntType::get())) {
1745
+ return TensorType::createContiguous(at::kLong, at::kCPU, {});
1746
+ } else if (typ.isSubtypeOf(*FloatType::get())) {
1747
+ return TensorType::createContiguous(at::kDouble, at::kCPU, {});
1748
+ } else if (typ.isSubtypeOf(*BoolType::get())) {
1749
+ return TensorType::createContiguous(at::kBool, at::kCPU, {});
1750
+ } else if (typ.kind() == NumberType::Kind) {
1751
+ return TensorType::create(std::nullopt, at::kCPU, {}, std::nullopt);
1752
+ }
1753
+ TORCH_CHECK(false, "Unknown number type: ", typ.str());
1754
+ }
1755
+ inline TypePtr TensorType::fromBoolType() {
1756
+ return TensorType::createContiguous(at::kBool, at::kCPU, {});
1757
+ }
1758
+
1759
+ inline std::optional<c10::ScalarType> tryScalarTypeFromJitType(const Type& type) {
1760
+ if (type == *FloatType::get()) {
1761
+ return at::typeMetaToScalarType(c10::get_default_dtype());
1762
+ } else if (type == *IntType::get()) {
1763
+ return at::ScalarType::Long;
1764
+ } else if (type == *BoolType::get()) {
1765
+ return at::ScalarType::Bool;
1766
+ }
1767
+ return std::nullopt;
1768
+ }
1769
+
1770
+ inline at::ScalarType scalarTypeFromJitType(const Type& type) {
1771
+ auto result = tryScalarTypeFromJitType(type);
1772
+ TORCH_CHECK(
1773
+ result,
1774
+ "Add new condition, expected Float, Complex, Int, or Bool but got",
1775
+ type.str());
1776
+ return *result;
1777
+ }
1778
+
1779
+ // Attempt to find the correct supertype of the two types `t1` and `t2`.
1780
+ // If no supertype is found, then nullopt will be returned if
1781
+ // `default_to_union` is false, and `Union[t1, t2]` will be returned
1782
+ // if it is true. If `t1 == t2`, or `t1` is a type refinement of `t2`,
1783
+ // then `t2` will be returned (and vice versa).
1784
+ //
1785
+ // Two different tensortypes will return dynamic.
1786
+ //
1787
+ // Currently we chose not to support returning a NumberType for
1788
+ // two types from the set of {FloatType, IntType, ComplexType}, because
1789
+ // there is a lack of operator support for NumberType.
1790
+ //
1791
+ // If `type_hint` is an `InterfaceType`, then we can use that as a
1792
+ // potential supertype for `ClassType`s in the list. Otherwise, we have
1793
+ // no way to find and use some common interface type
1794
+ TORCH_API std::optional<TypePtr> unifyTypes(
1795
+ const TypePtr& t1,
1796
+ const TypePtr& t2,
1797
+ bool default_to_union = false,
1798
+ const TypePtr& type_hint = nullptr);
1799
+
1800
+ TORCH_API std::optional<TypePtr> unifyTypeList(
1801
+ at::ArrayRef<TypePtr> elements,
1802
+ std::ostream& why_not,
1803
+ bool default_to_union = false,
1804
+ const TypePtr& type_hint = nullptr);
1805
+
1806
+ namespace detail {
1807
+ template <typename T>
1808
+ struct getTypePtr_ final {
1809
+ static decltype(auto) call() {
1810
+ return ([]() {
1811
+ try {
1812
+ return getCustomClassType<T>();
1813
+ } catch(const c10::Error&) {
1814
+ TORCH_CHECK(
1815
+ false,
1816
+ "Type ",
1817
+ c10::util::get_fully_qualified_type_name<T>(),
1818
+ " could not be converted to any of the known types."
1819
+ );
1820
+ }
1821
+ }());
1822
+ }
1823
+ };
1824
+
1825
+ template <typename T, bool fake>
1826
+ struct getMaybeFakeTypePtr_ final {
1827
+ static decltype(auto) call() {
1828
+ return getTypePtr_<T>::call();
1829
+ }
1830
+ };
1831
+
1832
+ template <>
1833
+ struct getTypePtr_<at::IValue> final {
1834
+ static decltype(auto) call() {
1835
+ return AnyType::get();
1836
+ }
1837
+ };
1838
+
1839
+ template <>
1840
+ struct getTypePtr_<at::Tensor> final {
1841
+ static decltype(auto) call() {
1842
+ return TensorType::get();
1843
+ }
1844
+ };
1845
+ template <>
1846
+ struct getTypePtr_<c10::Storage> final {
1847
+ static decltype(auto) call() {
1848
+ return StorageType::get();
1849
+ }
1850
+ };
1851
+ template <>
1852
+ struct getTypePtr_<c10::Stream> final {
1853
+ static decltype(auto) call() {
1854
+ return StreamObjType::get();
1855
+ }
1856
+ };
1857
+ template <>
1858
+ struct getTypePtr_<double> final {
1859
+ static decltype(auto) call() {
1860
+ return FloatType::get();
1861
+ }
1862
+ };
1863
+ template <>
1864
+ struct getTypePtr_<c10::complex<double>> final {
1865
+ static decltype(auto) call() {
1866
+ return ComplexType::get();
1867
+ }
1868
+ };
1869
+ template <>
1870
+ struct getTypePtr_<int64_t> final {
1871
+ static decltype(auto) call() {
1872
+ return IntType::get();
1873
+ }
1874
+ };
1875
+
1876
+ template <>
1877
+ struct getTypePtr_<DeviceIndex> final {
1878
+ static decltype(auto) call() {
1879
+ return IntType::get();
1880
+ }
1881
+ };
1882
+
1883
+ template <>
1884
+ struct getMaybeFakeTypePtr_<SymInt, false> final {
1885
+ static decltype(auto) call() {
1886
+ return SymIntType::get();
1887
+ }
1888
+ };
1889
+ template <>
1890
+ struct getMaybeFakeTypePtr_<SymInt, true> final {
1891
+ static decltype(auto) call() {
1892
+ return IntType::get();
1893
+ }
1894
+ };
1895
+
1896
+ template <>
1897
+ struct getMaybeFakeTypePtr_<SymFloat, false> final {
1898
+ static decltype(auto) call() {
1899
+ return SymFloatType::get();
1900
+ }
1901
+ };
1902
+ template <>
1903
+ struct getMaybeFakeTypePtr_<SymFloat, true> final {
1904
+ static decltype(auto) call() {
1905
+ return FloatType::get();
1906
+ }
1907
+ };
1908
+
1909
+ template <>
1910
+ struct getMaybeFakeTypePtr_<SymBool, false> final {
1911
+ static decltype(auto) call() {
1912
+ return SymBoolType::get();
1913
+ }
1914
+ };
1915
+ template <>
1916
+ struct getMaybeFakeTypePtr_<SymBool, true> final {
1917
+ static decltype(auto) call() {
1918
+ return BoolType::get();
1919
+ }
1920
+ };
1921
+
1922
+ template <>
1923
+ struct getTypePtr_<c10::Device> final {
1924
+ static decltype(auto) call() {
1925
+ return DeviceObjType::get();
1926
+ }
1927
+ };
1928
+ template <>
1929
+ struct getTypePtr_<bool> final {
1930
+ static decltype(auto) call() {
1931
+ return BoolType::get();
1932
+ }
1933
+ };
1934
+ template <>
1935
+ struct getTypePtr_<at::Scalar> final {
1936
+ static decltype(auto) call() {
1937
+ return NumberType::get();
1938
+ }
1939
+ };
1940
+ template <>
1941
+ struct getTypePtr_<c10::QScheme> final {
1942
+ static decltype(auto) call() {
1943
+ return QSchemeType::get();
1944
+ }
1945
+ };
1946
+ template <>
1947
+ struct getTypePtr_<at::Generator> final {
1948
+ static decltype(auto) call() {
1949
+ return TypeFactory::create<OptionalType>(
1950
+ TypeFactory::get<GeneratorType>());
1951
+ }
1952
+ };
1953
+ template <>
1954
+ struct getTypePtr_<std::string> final {
1955
+ static decltype(auto) call() {
1956
+ return StringType::get();
1957
+ }
1958
+ };
1959
+ template <>
1960
+ struct getTypePtr_<std::string_view> final {
1961
+ static decltype(auto) call() {
1962
+ return StringType::get();
1963
+ }
1964
+ };
1965
+ template <>
1966
+ struct getTypePtr_<at::Dimname> final {
1967
+ static decltype(auto) call() {
1968
+ return StringType::get();
1969
+ }
1970
+ };
1971
+ template <class T, bool fake>
1972
+ struct getMaybeFakeTypePtr_<std::vector<T>, fake> final {
1973
+ static const auto& call() {
1974
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
1975
+ // The "per vector<T>" static singleton needs to live in a .cpp file,
1976
+ // otherwise we'll end up with one singleton instance per shared library.
1977
+ static auto type = ListType::get("vector", inner_type);
1978
+ return type;
1979
+ }
1980
+ };
1981
+ template <class T, bool fake>
1982
+ struct getMaybeFakeTypePtr_<c10::ArrayRef<T>, fake> final {
1983
+ static const auto& call() {
1984
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
1985
+ // The "per ArrayRef<T>" static singleton needs to live in a .cpp file,
1986
+ // otherwise we'll end up with one singleton instance per shared library.
1987
+ static auto type = ListType::get("ArrayRef", inner_type);
1988
+ return type;
1989
+ }
1990
+ };
1991
+ template <bool fake>
1992
+ struct getMaybeFakeTypePtr_<c10::SymIntArrayRef, fake> final {
1993
+ static const auto& call() {
1994
+ static auto type = ListType::create(getMaybeFakeTypePtr_<c10::SymInt, fake>::call());
1995
+ return type;
1996
+ }
1997
+ };
1998
+ template <class T, bool fake>
1999
+ struct getMaybeFakeTypePtr_<c10::List<T>, fake> final {
2000
+ static const auto& call() {
2001
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
2002
+ // The "per List<T>" static singleton needs to live in a .cpp file,
2003
+ // otherwise we'll end up with one singleton instance per shared library.
2004
+ static auto type = ListType::get("List", inner_type);
2005
+ return type;
2006
+ }
2007
+ };
2008
+ template <class T, bool fake>
2009
+ struct getMaybeFakeTypePtr_<c10::IListRef<T>, fake> final {
2010
+ static const auto& call() {
2011
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
2012
+ static auto type = ListType::get("List", inner_type);
2013
+ return type;
2014
+ }
2015
+ };
2016
+ template <class T, size_t N, bool fake>
2017
+ struct getMaybeFakeTypePtr_<std::array<T, N>, fake> final {
2018
+ static const auto& call() {
2019
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
2020
+ // The "per array<T, N>" static singleton needs to live in a .cpp file,
2021
+ // otherwise we'll end up with one singleton instance per shared library.
2022
+ // (Concatenating the length onto the end of the string because we want a unique
2023
+ // type_ptr created for every std::array<T, N> type).
2024
+ static auto type = ListType::get(std::string("array") + std::to_string(N), inner_type);
2025
+ return type;
2026
+ }
2027
+ };
2028
+ template <class K, class V, bool fake>
2029
+ struct getMaybeFakeTypePtr_<std::unordered_map<K, V>, fake> final {
2030
+ static const auto& call() {
2031
+ static auto inner_key_type = getMaybeFakeTypePtr_<K, fake>::call();
2032
+ static auto inner_val_type = getMaybeFakeTypePtr_<V, fake>::call();
2033
+ // The "per unordered_map<K, V>" static singleton needs to live in a .cpp file,
2034
+ // otherwise we'll end up with one singleton instance per shared library.
2035
+ static auto type = DictType::get("unordered_map", inner_key_type, inner_val_type);
2036
+ return type;
2037
+ }
2038
+ };
2039
+ template <class K, class V, bool fake>
2040
+ struct getMaybeFakeTypePtr_<c10::Dict<K, V>, fake> final {
2041
+ static const auto& call() {
2042
+ static auto inner_key_type = getMaybeFakeTypePtr_<K, fake>::call();
2043
+ static auto inner_val_type = getMaybeFakeTypePtr_<V, fake>::call();
2044
+ // The "per Dict<K, V>" static singleton needs to live in a .cpp file,
2045
+ // otherwise we'll end up with one singleton instance per shared library.
2046
+ static auto type = DictType::get("Dict", inner_key_type, inner_val_type);
2047
+ return type;
2048
+ }
2049
+ };
2050
+
2051
+ template <class T, bool fake>
2052
+ struct getMaybeFakeTypePtr_<std::optional<T>, fake> final {
2053
+ static const auto& call() {
2054
+ static auto inner_type = getMaybeFakeTypePtr_<T, fake>::call();
2055
+ // The "per std::optional<T>" static singleton needs to live in a .cpp file,
2056
+ // otherwise we'll end up with one singleton instance per shared library.
2057
+ static auto type = OptionalType::get(inner_type);
2058
+ return type;
2059
+ }
2060
+ };
2061
+
2062
+
2063
+ template<>
2064
+ struct getTypePtr_<at::OptionalIntArrayRef> final {
2065
+ static const auto& call() {
2066
+ static auto inner_type = getMaybeFakeTypePtr_<IntArrayRef, false>::call();
2067
+ // The "per std::optional<T>" static singleton needs to live in a .cpp file,
2068
+ // otherwise we'll end up with one singleton instance per shared library.
2069
+ static auto type = OptionalType::get(inner_type);
2070
+ return type;
2071
+ }
2072
+ };
2073
+
2074
+ template <bool fake>
2075
+ struct getMaybeFakeTypePtr_<at::OptionalSymIntArrayRef, fake> final {
2076
+ static const auto& call() {
2077
+ // The "per std::optional<T>" static singleton needs to live in a .cpp file,
2078
+ // otherwise we'll end up with one singleton instance per shared library.
2079
+ static auto inner_type = getMaybeFakeTypePtr_<SymIntArrayRef, fake>::call();
2080
+ static auto type = OptionalType::get(inner_type);
2081
+ return type;
2082
+ }
2083
+ };
2084
+
2085
+ template <class... Contained, bool fake>
2086
+ struct getMaybeFakeTypePtr_<std::tuple<Contained...>, fake> final {
2087
+ static const auto& call() {
2088
+ static auto type = ([]() {
2089
+ std::vector<TypePtr> contained_types = {
2090
+ (getMaybeFakeTypePtr_<Contained, fake>::call())...
2091
+ };
2092
+ return TupleType::create(std::move(contained_types));
2093
+ })();
2094
+ return type;
2095
+ }
2096
+ };
2097
+ template <>
2098
+ struct getTypePtr_<void> final {
2099
+ static decltype(auto) call() {
2100
+ return NoneType::get();
2101
+ }
2102
+ };
2103
+ } // namespace detail
2104
+ template <class T>
2105
+ inline decltype(auto) getTypePtr() {
2106
+ // TODO: static_assert that a templated function exists, and throw a friendly
2107
+ // error message if not
2108
+ return detail::getMaybeFakeTypePtr_<T, false>::call();
2109
+ }
2110
+
2111
+ template <class T>
2112
+ inline TypePtr getTypePtrCopy() {
2113
+ // TODO: static_assert that a templated function exists, and throw a friendly
2114
+ // error message if not
2115
+ return getTypePtr<T>();
2116
+ }
2117
+
2118
+ template <class T>
2119
+ inline decltype(auto) getFakeTypePtr() {
2120
+ return detail::getMaybeFakeTypePtr_<T, true>::call();
2121
+ }
2122
+
2123
+ template <class T>
2124
+ inline TypePtr getFakeTypePtrCopy() {
2125
+ return getFakeTypePtr<T>();
2126
+ }
2127
+
2128
+ using TypeEnv = std::unordered_map<std::string, TypePtr>;
2129
+ struct MatchTypeReturn {
2130
+ MatchTypeReturn(std::string reason) : reason_(std::move(reason)) {}
2131
+ static MatchTypeReturn Success() {
2132
+ return MatchTypeReturn();
2133
+ }
2134
+ bool success() const {
2135
+ return !reason_.has_value();
2136
+ }
2137
+ const std::string& reason() const {
2138
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
2139
+ return reason_.value();
2140
+ }
2141
+
2142
+ private:
2143
+ MatchTypeReturn()
2144
+ : reason_(std::nullopt) {}
2145
+ std::optional<std::string> reason_; // is there is no match, this contains the reason
2146
+ };
2147
+
2148
+ // attempt to match the type variables in formal to actual, adding them to type_env.
2149
+ // If no match is possible this returns a MatchTypeReturn with r.success() == false
2150
+ // and a r.reason() that describes why it could not match.
2151
+ // note: It is possible to successfully match a formal, but for type variables
2152
+ // in the formal to still not be defined. In particular, None matches Optional[T]
2153
+ // but does not define the value of T.
2154
+ TORCH_API MatchTypeReturn
2155
+ matchTypeVariables(const TypePtr& formal, const TypePtr& actual, TypeEnv& type_env);
2156
+
2157
+ // replace type variables appearing in `type` with the values in
2158
+ // `type_env`. Returns nullptr if a variable used in `type`
2159
+ // does not appear in `type_env`
2160
+ TORCH_API TypePtr tryEvalTypeVariables(const TypePtr& type, TypeEnv& type_env);
2161
+
2162
+ TORCH_API bool elementTypeCanBeInferredFromMembers(const TypePtr& elem_type);
2163
+
2164
+ struct InterfaceType;
2165
+ using InterfaceTypePtr = std::shared_ptr<InterfaceType>;
2166
+
2167
+ // Interfaces are a list of abstract methods that a class might meet.
2168
+ // If a class provides those methods, it implicitly meets the interface.
2169
+
2170
+ // Subtype relations for Interface with ClassType:
2171
+ // lhs (ClassType or InterfaceType) is a subtype of rhs if:
2172
+ // 1. lhs methods are a superset of rhs methods
2173
+ // 2. if rhs is module interface, the lhs must be module interface or module itself
2174
+ struct TORCH_API InterfaceType : public NamedType {
2175
+ static InterfaceTypePtr create(
2176
+ QualifiedName qualifiedName, bool is_module=false);
2177
+
2178
+ bool equals(const Type& rhs) const override {
2179
+ if (auto user_rhs = rhs.castRaw<InterfaceType>()) {
2180
+ return isSubTypeImpl(*this, *user_rhs, nullptr) &&
2181
+ isSubTypeImpl(*user_rhs, *this, nullptr);
2182
+ }
2183
+ return false;
2184
+ }
2185
+
2186
+ std::string str() const override {
2187
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
2188
+ return std::string("InterfaceType<") + name()->name() + ">";
2189
+ }
2190
+
2191
+ bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override;
2192
+
2193
+ // try to find a method of this interface,
2194
+ // returns nullptr if not found.
2195
+ const FunctionSchema* getMethod(const std::string& name) const;
2196
+ void addMethod(FunctionSchema schema);
2197
+ const std::vector<FunctionSchema>& methods() const {
2198
+ return *methods_;
2199
+ }
2200
+
2201
+ bool is_module() const override{
2202
+ return is_module_;
2203
+ }
2204
+ static const TypeKind Kind = TypeKind::InterfaceType;
2205
+ ~InterfaceType() override = default;
2206
+ private:
2207
+ InterfaceType(QualifiedName name, bool is_module);
2208
+ static bool isSubTypeImpl(
2209
+ const InterfaceType& lhs,
2210
+ const InterfaceType& rhs,
2211
+ std::ostream* why_not);
2212
+
2213
+ std::string annotation_str_impl(
2214
+ [[maybe_unused]] const TypePrinter& printer = nullptr) const override {
2215
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
2216
+ return name()->qualifiedName();
2217
+ }
2218
+
2219
+ // shared_ptr so that this header does not have to depend on
2220
+ // FunctionSchema.h
2221
+ std::shared_ptr<std::vector<FunctionSchema>> methods_;
2222
+ // flag to distinguish if it's an interface type from a module or not
2223
+ bool is_module_;
2224
+ };
2225
+
2226
+ template <TypeKind K>
2227
+ struct EnumerationType : public Type {
2228
+ static const TypeKind Kind = K;
2229
+
2230
+ bool equals(const Type& rhs) const override {
2231
+ return rhs.kind() == kind();
2232
+ }
2233
+
2234
+ protected:
2235
+ EnumerationType() : Type(Kind) {}
2236
+ };
2237
+
2238
+ // WARNING: These enumeration types below DO NOT actually get parsed out
2239
+ // from the logical schema strings, instead they are mapped as ints. To
2240
+ // observe these types, use real_type() instead of type() on Argument
2241
+
2242
+ struct ScalarTypeType;
2243
+ using ScalarTypeTypePtr = SingletonTypePtr<ScalarTypeType>;
2244
+ struct TORCH_API ScalarTypeType : public EnumerationType<TypeKind::ScalarTypeType> {
2245
+ std::string str() const override {
2246
+ return "ScalarType";
2247
+ }
2248
+ static const TypeKind Kind = TypeKind::ScalarTypeType;
2249
+ // global singleton
2250
+ static ScalarTypeTypePtr get();
2251
+
2252
+ private:
2253
+ ScalarTypeType() {}
2254
+ };
2255
+
2256
+ struct MemoryFormatType;
2257
+ using MemoryFormatTypePtr = SingletonTypePtr<MemoryFormatType>;
2258
+ struct TORCH_API MemoryFormatType : public EnumerationType<TypeKind::MemoryFormatType> {
2259
+ std::string str() const override {
2260
+ return "MemoryFormat";
2261
+ }
2262
+ static const TypeKind Kind = TypeKind::MemoryFormatType;
2263
+ // global singleton
2264
+ static MemoryFormatTypePtr get();
2265
+
2266
+ private:
2267
+ MemoryFormatType() {}
2268
+ };
2269
+
2270
+ struct LayoutType;
2271
+ using LayoutTypePtr = SingletonTypePtr<LayoutType>;
2272
+ struct TORCH_API LayoutType : public EnumerationType<TypeKind::LayoutType> {
2273
+ std::string str() const override {
2274
+ return "Layout";
2275
+ }
2276
+ static const TypeKind Kind = TypeKind::LayoutType;
2277
+ // global singleton
2278
+ static LayoutTypePtr get();
2279
+
2280
+ private:
2281
+ LayoutType() {}
2282
+ };
2283
+
2284
+ namespace detail {
2285
+ template <>
2286
+ struct getMaybeFakeTypePtr_<c10::ScalarType, false> final {
2287
+ static decltype(auto) call() {
2288
+ return ScalarTypeType::get();
2289
+ }
2290
+ };
2291
+ template <>
2292
+ struct getMaybeFakeTypePtr_<c10::Layout, false> final {
2293
+ static decltype(auto) call() {
2294
+ return LayoutType::get();
2295
+ }
2296
+ };
2297
+ template <>
2298
+ struct getMaybeFakeTypePtr_<c10::MemoryFormat, false> final {
2299
+ static decltype(auto) call() {
2300
+ return MemoryFormatType::get();
2301
+ }
2302
+ };
2303
+ template <>
2304
+ struct getMaybeFakeTypePtr_<c10::ScalarType, true> final {
2305
+ static decltype(auto) call() {
2306
+ return IntType::get();
2307
+ }
2308
+ };
2309
+ template <>
2310
+ struct getMaybeFakeTypePtr_<c10::Layout, true> final {
2311
+ static decltype(auto) call() {
2312
+ return IntType::get();
2313
+ }
2314
+ };
2315
+ template <>
2316
+ struct getMaybeFakeTypePtr_<c10::MemoryFormat, true> final {
2317
+ static decltype(auto) call() {
2318
+ return IntType::get();
2319
+ }
2320
+ };
2321
+ } // namespace detail
2322
+
2323
+ // the common supertype of all lists,
2324
+ // List[T] <: AnyList for all T
2325
+ struct AnyListType;
2326
+ using AnyListTypePtr = SingletonTypePtr<AnyListType>;
2327
+ struct TORCH_API AnyListType : public Type {
2328
+ bool equals(const Type& rhs) const override {
2329
+ return rhs.kind() == kind();
2330
+ }
2331
+ std::string str() const override {
2332
+ return "list";
2333
+ }
2334
+ static const TypeKind Kind = TypeKind::AnyListType;
2335
+ // global singleton
2336
+ static AnyListTypePtr get();
2337
+ private:
2338
+ AnyListType()
2339
+ : Type(TypeKind::AnyListType) {}
2340
+ };
2341
+
2342
+ // the common supertype of all tuples,
2343
+ // Tuple[T...] <: AnyTuple for all T
2344
+ struct AnyTupleType;
2345
+ using AnyTupleTypePtr = SingletonTypePtr<AnyTupleType>;
2346
+ struct TORCH_API AnyTupleType : public Type {
2347
+ bool equals(const Type& rhs) const override {
2348
+ return rhs.kind() == kind();
2349
+ }
2350
+
2351
+ std::string str() const override {
2352
+ return "tuple";
2353
+ }
2354
+ static const TypeKind Kind = TypeKind::AnyTupleType;
2355
+
2356
+ // global singleton
2357
+ static AnyTupleTypePtr get();
2358
+ private:
2359
+ AnyTupleType()
2360
+ : Type(TypeKind::AnyTupleType) {}
2361
+ };
2362
+
2363
+ // the common supertype of all classes,
2364
+ // ClassType <: AnyClassType for all classes
2365
+ struct AnyClassType;
2366
+ using AnyClassTypePtr = SingletonTypePtr<AnyClassType>;
2367
+ struct TORCH_API AnyClassType : public Type {
2368
+ bool equals(const Type& rhs) const override {
2369
+ return rhs.kind() == kind();
2370
+ }
2371
+ std::string str() const override {
2372
+ return "AnyClassType";
2373
+ }
2374
+ static const TypeKind Kind = TypeKind::AnyClassType;
2375
+ // global singleton
2376
+ static AnyClassTypePtr get();
2377
+ private:
2378
+ AnyClassType()
2379
+ : Type(TypeKind::AnyClassType) {}
2380
+ };
2381
+
2382
+ template<>
2383
+ inline typename detail::CastReturnType<NamedType>::type Type::cast<NamedType>() {
2384
+ if (kind() == TypeKind::TupleType || kind() == TypeKind::FunctionType ||
2385
+ kind() == TypeKind::ClassType || kind() == TypeKind::InterfaceType) {
2386
+ return std::static_pointer_cast<NamedType>(static_cast<NamedType *>(this)->shared_from_this());
2387
+ }
2388
+ return nullptr;
2389
+ }
2390
+
2391
+ template<>
2392
+ inline typename detail::CastConstReturnType<NamedType>::type Type::cast<NamedType>() const {
2393
+ if (kind() == TypeKind::TupleType || kind() == TypeKind::FunctionType ||
2394
+ kind() == TypeKind::ClassType || kind() == TypeKind::InterfaceType) {
2395
+ return std::static_pointer_cast<const NamedType>(static_cast<const NamedType *>(this)->shared_from_this());
2396
+ }
2397
+ return nullptr;
2398
+ }
2399
+
2400
+ template<>
2401
+ inline const NamedType* Type::castRaw<NamedType>() const {
2402
+ if (kind() == TypeKind::TupleType || kind() == TypeKind::FunctionType ||
2403
+ kind() == TypeKind::ClassType || kind() == TypeKind::InterfaceType) {
2404
+ return static_cast<const NamedType*>(this);
2405
+ }
2406
+ return nullptr;
2407
+ }
2408
+
2409
+ // Used as a return type when inferring the IValue type of a Python object.
2410
+ struct InferredType {
2411
+ /* implicit */ InferredType(TypePtr type) : type_(std::move(type)) {}
2412
+ /* implicit */ InferredType(std::string reason)
2413
+ : type_(nullptr), reason_(std::move(reason)) {}
2414
+ TypePtr type() const {
2415
+ TORCH_INTERNAL_ASSERT(
2416
+ type_,
2417
+ "Tried to get the type from an InferredType but the type is null. ",
2418
+ "Reason: ",
2419
+ reason_);
2420
+ return type_;
2421
+ }
2422
+ bool success() const {
2423
+ return type_ != nullptr;
2424
+ }
2425
+ const std::string& reason() const {
2426
+ TORCH_INTERNAL_ASSERT(!type_);
2427
+ return reason_;
2428
+ }
2429
+
2430
+ private:
2431
+ TypePtr type_;
2432
+ std::string reason_;
2433
+ };
2434
+
2435
+ TORCH_API bool containsAnyType(const TypePtr& type);
2436
+
2437
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/jit_type_base.h ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <functional>
4
+ #include <memory>
5
+ #include <string>
6
+ #include <utility>
7
+
8
+ #include <ATen/core/qualified_name.h>
9
+ #include <ATen/core/type_ptr.h>
10
+ #include <c10/core/SymInt.h>
11
+ #include <c10/core/SymFloat.h>
12
+ #include <c10/core/SymBool.h>
13
+ #include <c10/core/SymIntArrayRef.h>
14
+ #include <c10/macros/Macros.h>
15
+ #include <c10/util/ArrayRef.h>
16
+ #include <c10/util/Exception.h>
17
+ #include <optional>
18
+
19
+ namespace c10 {
20
+
21
+ #define C10_FORALL_TYPES(_) \
22
+ _(AnyType) \
23
+ _(EnumType) \
24
+ _(AnyEnumType) \
25
+ _(TensorType) \
26
+ _(StorageType) \
27
+ _(TupleType) \
28
+ _(ListType) \
29
+ _(DictType) \
30
+ _(NumberType) \
31
+ _(FloatType) \
32
+ _(ComplexType) \
33
+ _(FutureType) \
34
+ _(AwaitType) \
35
+ _(RRefType) \
36
+ _(IntType) \
37
+ _(NoneType) \
38
+ _(StringType) \
39
+ _(GeneratorType) \
40
+ _(QuantizerType) \
41
+ _(BoolType) \
42
+ _(OptionalType) \
43
+ _(VarType) \
44
+ _(DeviceObjType) \
45
+ _(StreamObjType) \
46
+ _(FunctionType) \
47
+ _(ClassType) \
48
+ _(PyObjectType) \
49
+ _(CapsuleType) \
50
+ _(InterfaceType) \
51
+ _(QSchemeType) \
52
+ _(ScalarTypeType) \
53
+ _(LayoutType) \
54
+ _(MemoryFormatType) \
55
+ _(AnyListType) \
56
+ _(AnyTupleType) \
57
+ _(AnyClassType) \
58
+ _(SymIntType) \
59
+ _(SymFloatType) \
60
+ _(SymBoolType) \
61
+ _(UnionType) \
62
+ _(DynamicType)
63
+
64
+ enum class TypeKind {
65
+ #define DEFINE_TYPE(T) T,
66
+ C10_FORALL_TYPES(DEFINE_TYPE)
67
+ #undef DEFINE_TYPE
68
+ };
69
+
70
+ TORCH_API const char* typeKindToString(TypeKind kind);
71
+
72
+ struct Type;
73
+ struct SharedType;
74
+
75
+ // Use this to customize how a Type is printed using `annotation_str()`. If
76
+ // std::nullopt is returned, `annotation_str()` falls through to its default
77
+ // implementation.
78
+ using TypePrinter = std::function<std::optional<std::string>(const Type&)>;
79
+
80
+ namespace detail {
81
+ template <typename T>
82
+ struct IsSingletonType : public std::integral_constant<bool, false> {};
83
+ } // namespace detail
84
+ #define TORCH_DECLARE_SINGLETON(Type) \
85
+ struct Type; \
86
+ namespace detail { \
87
+ template <> struct IsSingletonType<Type> : public std::integral_constant<bool, true> {}; \
88
+ }
89
+
90
+ TORCH_DECLARE_SINGLETON(AnyType)
91
+ TORCH_DECLARE_SINGLETON(AnyEnumType)
92
+ TORCH_DECLARE_SINGLETON(NumberType)
93
+ TORCH_DECLARE_SINGLETON(FloatType)
94
+ TORCH_DECLARE_SINGLETON(ComplexType)
95
+ TORCH_DECLARE_SINGLETON(IntType)
96
+ TORCH_DECLARE_SINGLETON(BoolType)
97
+ TORCH_DECLARE_SINGLETON(StringType)
98
+ TORCH_DECLARE_SINGLETON(StorageType)
99
+ TORCH_DECLARE_SINGLETON(NoneType)
100
+ TORCH_DECLARE_SINGLETON(GeneratorType)
101
+ TORCH_DECLARE_SINGLETON(QuantizerType)
102
+ TORCH_DECLARE_SINGLETON(QSchemeType)
103
+ TORCH_DECLARE_SINGLETON(DeviceObjType)
104
+ TORCH_DECLARE_SINGLETON(StreamObjType)
105
+ TORCH_DECLARE_SINGLETON(CapsuleType)
106
+ TORCH_DECLARE_SINGLETON(PyObjectType)
107
+ TORCH_DECLARE_SINGLETON(ScalarTypeType)
108
+ TORCH_DECLARE_SINGLETON(LayoutType)
109
+ TORCH_DECLARE_SINGLETON(MemoryFormatType)
110
+ TORCH_DECLARE_SINGLETON(AnyListType)
111
+ TORCH_DECLARE_SINGLETON(AnyTupleType)
112
+ TORCH_DECLARE_SINGLETON(AnyClassType)
113
+
114
+ namespace detail {
115
+ template <typename T, typename Enable = void>
116
+ struct CastReturnType {
117
+ using type = std::shared_ptr<T>;
118
+ };
119
+
120
+ template <typename T>
121
+ struct CastReturnType<T, std::enable_if_t<IsSingletonType<T>::value>> {
122
+ using type = SingletonTypePtr<T>;
123
+ };
124
+
125
+ template <typename T, typename Enable = void>
126
+ struct CastConstReturnType {
127
+ using type = std::shared_ptr<const T>;
128
+ };
129
+
130
+ template <typename T>
131
+ struct CastConstReturnType<T, std::enable_if_t<IsSingletonType<T>::value>> {
132
+ using type = SingletonTypePtr<const T>;
133
+ };
134
+
135
+ template <typename T>
136
+ struct as_shared_type {
137
+ using type = SharedType*;
138
+ };
139
+
140
+ template <typename T>
141
+ struct as_shared_type<const T*> {
142
+ using type = const SharedType *;
143
+ };
144
+ } // namespace detail
145
+
146
+ struct TORCH_API Type {
147
+ friend TORCH_API bool operator==(const Type& lhs, const Type& rhs);
148
+ private:
149
+ TypeKind kind_;
150
+
151
+ protected:
152
+ Type(TypeKind kind) : kind_(kind) {}
153
+
154
+ Type(const Type&) = default;
155
+ Type& operator=(const Type&) = default;
156
+ Type(Type&&) noexcept = default;
157
+ Type& operator=(Type&&) noexcept = default;
158
+
159
+ virtual std::string annotation_str_impl(const TypePrinter& /*printer*/) const {
160
+ return str();
161
+ }
162
+ // a == b
163
+ virtual bool equals(const Type& rhs) const = 0;
164
+ // a == b <=> b == a
165
+ virtual bool symmetric() const {
166
+ return true;
167
+ }
168
+
169
+ public:
170
+ template <typename T>
171
+ class SingletonOrSharedTypePtr {
172
+ public:
173
+ using element_type = typename std::shared_ptr<T>::element_type;
174
+
175
+ SingletonOrSharedTypePtr() = default;
176
+
177
+ /* implicit */ SingletonOrSharedTypePtr(std::shared_ptr<T> x)
178
+ : repr_(std::move(x)) {}
179
+
180
+ template <typename U, std::enable_if_t<std::is_convertible_v<U*, T*>, bool> = true>
181
+ /* implicit */ SingletonOrSharedTypePtr(std::shared_ptr<U> x)
182
+ : repr_(std::move(x)) {}
183
+
184
+ /* implicit */ SingletonOrSharedTypePtr(std::nullptr_t)
185
+ : repr_(nullptr) {}
186
+
187
+ /* implicit */ SingletonOrSharedTypePtr(SingletonTypePtr<T> p)
188
+ : repr_(p) {}
189
+
190
+ template <typename U, std::enable_if_t<std::is_convertible_v<U*, T*>, bool> = true>
191
+ /* implicit */ SingletonOrSharedTypePtr(SingletonTypePtr<U> p)
192
+ : repr_(SingletonTypePtr<T>(p.get())) {}
193
+
194
+
195
+ // We need to support construction from T* for pybind. The problem
196
+ // is that it's not clear if we are supposed to be taking shared
197
+ // ownership or not.
198
+ //
199
+ // Case 1: if T is known statically to derive from SharedType, we should use
200
+ // shared_from_this() and take shared_ownership.
201
+ //
202
+ // Case 2: if T is exactly Type, we need to do a dynamic_cast to
203
+ // check if it's a SharedType and do the right thing.
204
+ //
205
+ // Case 3: Otherwise, T is not a SharedType. (debug-check this
206
+ // assumption!) Use a singleton pointer.
207
+
208
+ template <typename U = T, std::enable_if_t<std::is_base_of_v<SharedType, U>, bool> = true>
209
+ /* implicit */ SingletonOrSharedTypePtr(T* p) : SingletonOrSharedTypePtr(static_cast<typename detail::as_shared_type<U>::type>(p)->shared_from_this()) {}
210
+
211
+ template <typename U = T, std::enable_if_t<std::is_same_v<Type, U>, bool> = true>
212
+ /* implicit */ SingletonOrSharedTypePtr(T* p) {
213
+ if (auto* shared_p = dynamic_cast<typename detail::as_shared_type<U>::type>(p)) {
214
+ repr_ = Repr(shared_p->shared_from_this());
215
+ } else {
216
+ repr_ = Repr(p);
217
+ }
218
+ }
219
+
220
+ template <typename U = T, std::enable_if_t<!std::is_same_v<Type, U> && !std::is_base_of_v<SharedType, U>, bool> = true>
221
+ /* implicit */ SingletonOrSharedTypePtr(T* p)
222
+ : repr_(p) {
223
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dynamic_cast<typename detail::as_shared_type<U>::type>(p) == nullptr);
224
+ }
225
+
226
+ SingletonOrSharedTypePtr(const SingletonOrSharedTypePtr&) = default;
227
+ SingletonOrSharedTypePtr(SingletonOrSharedTypePtr&&) noexcept = default;
228
+ SingletonOrSharedTypePtr& operator=(const SingletonOrSharedTypePtr&) = default;
229
+ SingletonOrSharedTypePtr& operator=(SingletonOrSharedTypePtr&&) noexcept = default;
230
+ ~SingletonOrSharedTypePtr() = default;
231
+
232
+ T* get() const {
233
+ return repr_.isSharedAndNonNull() ? repr_.shared_.repr_.get() : static_cast<T*>(repr_.rawRepr().first);
234
+ }
235
+
236
+ operator bool() const {
237
+ return repr_.isNonNull();
238
+ }
239
+
240
+ bool operator==(std::nullptr_t) const {
241
+ return !repr_.isNonNull();
242
+ }
243
+
244
+ bool operator!=(std::nullptr_t) const {
245
+ return repr_.isNonNull();
246
+ }
247
+
248
+ template <typename U = T, std::enable_if_t<!std::is_same_v<std::remove_const_t<U>, void>, bool> = true>
249
+ U& operator*() const {
250
+ return *get();
251
+ }
252
+
253
+ T* operator->() const {
254
+ return get();
255
+ }
256
+
257
+ private:
258
+ // NOTE: SharedPtrWrapper exists to work around a baffling bug in
259
+ // nvcc; see comment in destroy() below.
260
+ struct SharedPtrWrapper {
261
+ SharedPtrWrapper(std::shared_ptr<T> &&x)
262
+ : repr_(std::move(x)) {}
263
+ std::shared_ptr<T> repr_;
264
+ };
265
+ union Repr {
266
+ Repr() : Repr(nullptr) {}
267
+
268
+ explicit Repr(std::shared_ptr<T> x)
269
+ : shared_(std::move(x)) {}
270
+
271
+ explicit Repr(std::nullptr_t)
272
+ : singletonRepr_(nullptr) {}
273
+
274
+ explicit Repr(SingletonTypePtr<T> p)
275
+ : singletonRepr_(p.get()) {}
276
+
277
+ ~Repr() {
278
+ destroy();
279
+ }
280
+
281
+ // NOTE: the only non-UB way to access our null state is through
282
+ // rawRepr(), because our copy operation doesn't preserve which
283
+ // union member is active for null pointers.
284
+ Repr(const Repr& rhs) {
285
+ if (rhs.isSharedAndNonNull()) {
286
+ new (&shared_) SharedPtrWrapper(rhs.shared_);
287
+ } else {
288
+ singletonRepr_.singleton_ = static_cast<T*>(rhs.rawRepr().first);
289
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.singletonRepr_.unused_ == nullptr);
290
+ singletonRepr_.unused_ = nullptr;
291
+ }
292
+ }
293
+
294
+ Repr(Repr&& rhs) noexcept {
295
+ if (rhs.isSharedAndNonNull()) {
296
+ new (&shared_) SharedPtrWrapper(std::move(rhs.shared_));
297
+ } else {
298
+ singletonRepr_.singleton_ = static_cast<T*>(rhs.rawRepr().first);
299
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.singletonRepr_.unused_ == nullptr);
300
+ singletonRepr_.unused_ = nullptr;
301
+ }
302
+ }
303
+
304
+ Repr& operator=(const Repr& rhs) {
305
+ if (&rhs == this) {
306
+ return *this;
307
+ }
308
+ if (rhs.isSharedAndNonNull()) {
309
+ if (isSharedAndNonNull()) {
310
+ shared_ = rhs.shared_;
311
+ } else {
312
+ new (&shared_) SharedPtrWrapper(rhs.shared_);
313
+ }
314
+ } else {
315
+ if (isSharedAndNonNull()) {
316
+ destroy();
317
+ }
318
+ singletonRepr_.singleton_ = static_cast<T*>(rhs.rawRepr().first);
319
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.rawRepr().nullIfSingleton_ == nullptr);
320
+ singletonRepr_.unused_ = nullptr;
321
+ }
322
+ return *this;
323
+ }
324
+
325
+ Repr& operator=(Repr&& rhs) noexcept {
326
+ if (&rhs == this) {
327
+ return *this;
328
+ }
329
+ if (rhs.isSharedAndNonNull()) {
330
+ if (isSharedAndNonNull()) {
331
+ shared_ = std::move(rhs.shared_);
332
+ } else {
333
+ new (&shared_) SharedPtrWrapper(std::move(rhs.shared_));
334
+ }
335
+ } else {
336
+ if (isSharedAndNonNull()) {
337
+ destroy();
338
+ }
339
+ singletonRepr_.singleton_ = static_cast<T*>(rhs.rawRepr().first);
340
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.rawRepr().nullIfSingleton_ == nullptr);
341
+ singletonRepr_.unused_ = nullptr;
342
+ }
343
+ return *this;
344
+ }
345
+
346
+ SharedPtrWrapper shared_;
347
+
348
+ struct SingletonRepr {
349
+ explicit SingletonRepr(T* s) : singleton_(s) {}
350
+ T* singleton_;
351
+ void* unused_ = nullptr;
352
+ } singletonRepr_;
353
+ struct RawRepr {
354
+ void* first;
355
+ void* nullIfSingleton_;
356
+ };
357
+
358
+ // It is UB to read the singleton part of Repr if it was
359
+ // constructed as a shared_ptr and vice versa, but memcpying out
360
+ // the representation is always OK, so here's an accessor to obey
361
+ // the letter of the law.
362
+ RawRepr rawRepr() const {
363
+ RawRepr repr{};
364
+ memcpy(&repr, reinterpret_cast<const char *>(this), sizeof(RawRepr));
365
+ return repr;
366
+ }
367
+
368
+ bool isNonNull() const {
369
+ auto repr = rawRepr();
370
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(repr.nullIfSingleton_ == nullptr || repr.first != nullptr);
371
+ return repr.first != nullptr;
372
+ }
373
+
374
+ bool isSharedAndNonNull() const {
375
+ return rawRepr().nullIfSingleton_ != nullptr;
376
+ }
377
+
378
+ private:
379
+ void destroy() {
380
+ if (isSharedAndNonNull()) {
381
+ // Without SharedPtrWrapper, this line would read
382
+ // `shared_.~shared_ptr()` and nvcc would complain with
383
+ // "error: expected primary-expression before '>' token"
384
+ // referring to the "t" in "shared_ptr". SharedPtrWrapper
385
+ // exists to work around this compiler bug.
386
+ shared_.~SharedPtrWrapper();
387
+ }
388
+ }
389
+ } repr_;
390
+ };
391
+
392
+ using TypePtr = SingletonOrSharedTypePtr<Type>;
393
+ using Ptr = TypePtr;
394
+ using ElementType = Type;
395
+
396
+ // subtyping relation. By default, we return true for the case
397
+ // when the type is exactly equal or if this <: T where rhs = Optional[T]
398
+
399
+ // if this returns false and the why_not stream is non-null, it contains
400
+ // additional details that describe why this is not a subtype of 'rhs'.
401
+ // This additional information should only contain details that are not
402
+ // obvious from the annotation_str() that describes the type. For instance it
403
+ // is clear that `int <: str` is false but not clear why `Foo <: InterfaceBar`
404
+ // might be false.
405
+ virtual bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const;
406
+ virtual bool is_module() const;
407
+ bool isSubtypeOf(const Type& rhs) const {
408
+ return isSubtypeOfExt(rhs, nullptr);
409
+ }
410
+ // Compatibility shims to accommodate existing code that passes shared_ptrs
411
+ // around. Ideally, we would just delete this, but it should be harmless.
412
+ template <typename T>
413
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
414
+ isSubtypeOf(const std::shared_ptr<T>& rhs) const {
415
+ return isSubtypeOf(*rhs);
416
+ }
417
+
418
+ template <typename T>
419
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
420
+ isSubtypeOf(const SingletonOrSharedTypePtr<T>& rhs) const {
421
+ return isSubtypeOf(*rhs);
422
+ }
423
+
424
+ template <typename T>
425
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
426
+ isSubtypeOf(SingletonTypePtr<T> rhs) const {
427
+ return isSubtypeOf(*rhs);
428
+ }
429
+
430
+ template <typename T>
431
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
432
+ isSubtypeOfExt(const SingletonOrSharedTypePtr<T>& rhs, std::ostream* why_not) const {
433
+ return isSubtypeOfExt(*rhs, why_not);
434
+ }
435
+
436
+ template <typename T>
437
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
438
+ isSubtypeOfExt(const std::shared_ptr<T>& rhs, std::ostream* why_not) const {
439
+ return isSubtypeOfExt(*rhs, why_not);
440
+ }
441
+
442
+ template <typename T>
443
+ std::enable_if_t<std::is_base_of_v<Type, T>, bool>
444
+ isSubtypeOfExt(SingletonTypePtr<T> rhs, std::ostream* why_not) const {
445
+ return isSubtypeOfExt(*rhs, why_not);
446
+ }
447
+
448
+ // How this type will appear in FunctionSchema declarations
449
+ virtual std::string str() const = 0;
450
+
451
+ // How this type will appear as if it were a type annotation in Python
452
+ // which is sometimes different than how it appears in declarations (e.g.
453
+ // int[] vs List[int])
454
+ //
455
+ // Takes a custom printer that users can pass in to customize the output of
456
+ // this method.
457
+ std::string annotation_str(const TypePrinter& printer) const {
458
+ if (printer) {
459
+ // the printer can return std::nullopt to fall through to the default impl
460
+ if (auto renamed = printer(*this)) {
461
+ return *renamed;
462
+ }
463
+ }
464
+ return annotation_str_impl(printer);
465
+ }
466
+ std::string annotation_str() const {
467
+ // Overload instead of define a default value for `printer` to help
468
+ // debuggers out.
469
+ return annotation_str(nullptr);
470
+ }
471
+
472
+ // Returns a human readable string that includes additional information like
473
+ // "type is inferred rather than explicitly defined" to help construct more
474
+ // user-friendly messages.
475
+ virtual std::string repr_str() const {
476
+ return annotation_str();
477
+ }
478
+
479
+ TypeKind kind() const {
480
+ return kind_;
481
+ }
482
+
483
+ virtual bool isUnionType() const {
484
+ return false;
485
+ }
486
+
487
+ virtual bool requires_grad() const {
488
+ for (const auto& ct : containedTypes()) {
489
+ if (ct->requires_grad()) {
490
+ return true;
491
+ }
492
+ }
493
+ return false;
494
+ }
495
+
496
+ // Dynamically cast this object to the subclass indicated by the
497
+ // template variable, returning nullptr if the cast is invalid.
498
+ template <typename T, std::enable_if_t<!detail::IsSingletonType<T>::value, bool> = true>
499
+ typename detail::CastReturnType<T>::type cast() {
500
+ if (T::Kind == kind()) {
501
+ return std::static_pointer_cast<T>(static_cast<T*>(this)->shared_from_this());
502
+ }
503
+ return nullptr;
504
+ }
505
+ template <typename T, std::enable_if_t<detail::IsSingletonType<T>::value, bool> = true>
506
+ typename detail::CastReturnType<T>::type cast() {
507
+ if (T::Kind == kind()) {
508
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(this == T::get().get());
509
+ return typename detail::CastReturnType<T>::type(static_cast<T*>(this));
510
+ }
511
+ return nullptr;
512
+ }
513
+ template <typename T, std::enable_if_t<!detail::IsSingletonType<T>::value, bool> = true>
514
+ typename detail::CastConstReturnType<T>::type cast() const {
515
+ if (T::Kind == kind()) {
516
+ return std::static_pointer_cast<const T>(static_cast<const T*>(this)->shared_from_this());
517
+ }
518
+ return nullptr;
519
+ }
520
+ template <typename T, std::enable_if_t<detail::IsSingletonType<T>::value, bool> = true>
521
+ typename detail::CastConstReturnType<T>::type cast() const {
522
+ if (T::Kind == kind()) {
523
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(this == T::get().get());
524
+ return typename detail::CastConstReturnType<T>::type(static_cast<const T*>(this));
525
+ }
526
+ return nullptr;
527
+ }
528
+ template <typename T>
529
+ T* castRaw() {
530
+ if (T::Kind == kind()) {
531
+ return static_cast<T*>(this);
532
+ }
533
+ return nullptr;
534
+ }
535
+ template <typename T>
536
+ const T* castRaw() const {
537
+ if (T::Kind == kind()) {
538
+ return static_cast<const T*>(this);
539
+ }
540
+ return nullptr;
541
+ }
542
+ template <typename T>
543
+ auto expect() {
544
+ auto r = cast<T>();
545
+ AT_ASSERT(r);
546
+ return r;
547
+ }
548
+ template <typename T>
549
+ auto expect() const {
550
+ auto r = cast<const T>();
551
+ AT_ASSERT(r);
552
+ return r;
553
+ }
554
+ template <typename T>
555
+ T& expectRef() {
556
+ auto* r = castRaw<T>();
557
+ AT_ASSERT(r);
558
+ return *r;
559
+ }
560
+ template <typename T>
561
+ const T& expectRef() const {
562
+ auto* r = castRaw<const T>();
563
+ AT_ASSERT(r);
564
+ return *r;
565
+ }
566
+ virtual ~Type() = default;
567
+ virtual bool hasFreeVariables() const {
568
+ return false;
569
+ }
570
+ // list of types this type contains, e.g. for a List then element type of a
571
+ // list for a tuple, the types of the tuple elements
572
+ virtual at::ArrayRef<TypePtr> containedTypes() const {
573
+ return {};
574
+ }
575
+ virtual TypePtr containedType(size_t i) const {
576
+ return containedTypes().at(i);
577
+ }
578
+ virtual size_t containedTypeSize() const {
579
+ return containedTypes().size();
580
+ }
581
+ // create a new version of this type, replacing its contained types with
582
+ // contained_types
583
+ TypePtr withContained(std::vector<TypePtr> contained_types);
584
+ // per-type constructor, you only need to override this if the
585
+ // containedTypes() is not empty
586
+ virtual TypePtr createWithContained(
587
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
588
+ std::vector<TypePtr> /*contained_types*/) const {
589
+ TORCH_CHECK(false,
590
+ "type with contained types did not overload createWithContained: ",
591
+ str());
592
+ }
593
+
594
+ };
595
+
596
+ template <typename T>
597
+ using SingletonOrSharedTypePtr = Type::SingletonOrSharedTypePtr<T>;
598
+
599
+
600
+ template <typename T, typename U>
601
+ bool operator==(const SingletonOrSharedTypePtr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
602
+ return (void*)x.get() == (void*)y.get();
603
+ }
604
+
605
+ template <typename T, typename U>
606
+ bool operator==(const SingletonOrSharedTypePtr<T>& x, const std::shared_ptr<U>& y) {
607
+ return (void*)x.get() == (void*)y.get();
608
+ }
609
+
610
+ template <typename T, typename U>
611
+ bool operator==(const std::shared_ptr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
612
+ return (void*)x.get() == (void*)y.get();
613
+ }
614
+
615
+ template <typename T, typename U>
616
+ bool operator==(const SingletonOrSharedTypePtr<T>& x, const SingletonTypePtr<U>& y) {
617
+ return (void*)x.get() == (void*)y.get();
618
+ }
619
+
620
+ template <typename T, typename U>
621
+ bool operator==(const SingletonTypePtr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
622
+ return (void*)x.get() == (void*)y.get();
623
+ }
624
+
625
+ template <typename T, typename U>
626
+ bool operator!=(const SingletonOrSharedTypePtr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
627
+ return !(x == y);
628
+ }
629
+
630
+ template <typename T, typename U>
631
+ bool operator!=(const SingletonOrSharedTypePtr<T>& x, const std::shared_ptr<U>& y) {
632
+ return !(x == y);
633
+ }
634
+
635
+ template <typename T, typename U>
636
+ bool operator!=(const std::shared_ptr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
637
+ return !(x == y);
638
+ }
639
+
640
+ template <typename T, typename U>
641
+ bool operator!=(const SingletonOrSharedTypePtr<T>& x, const SingletonTypePtr<U>& y) {
642
+ return !(x == y);
643
+ }
644
+
645
+ template <typename T, typename U>
646
+ bool operator!=(const SingletonTypePtr<T>& x, const SingletonOrSharedTypePtr<U>& y) {
647
+ return !(x == y);
648
+ }
649
+
650
+ using TypePtr = SingletonOrSharedTypePtr<Type>;
651
+ using ConstTypePtr = SingletonOrSharedTypePtr<const Type>;
652
+
653
+ // Explicitly enable MaybeOwned<shared_ptr<T>>, rather than allowing
654
+ // MaybeOwned to be used for any type right away.
655
+ template <typename T>
656
+ struct MaybeOwnedTraits<SingletonOrSharedTypePtr<T>>
657
+ : public MaybeOwnedTraitsGenericImpl<SingletonOrSharedTypePtr<T>> {};
658
+
659
+ // Base class for Types that are guaranteed to be owned by std::shared_ptr.
660
+ struct TORCH_API SharedType : public Type, public std::enable_shared_from_this<SharedType> {
661
+ using Type::Type;
662
+ };
663
+
664
+ inline TypePtr Type::withContained(std::vector<TypePtr> contained_types) {
665
+ auto current_contained = containedTypes();
666
+ // Types with no contained_types don't need this call. Check before calling!
667
+ //
668
+ // (We can't support this efficiently because types without
669
+ // contained types may be singletons, in which case
670
+ // shared_from_this will crash; we would have to provide a virtual
671
+ // typeptr_from_this or isSingleton.)
672
+ TORCH_INTERNAL_ASSERT(!current_contained.empty() && current_contained.size() == contained_types.size());
673
+ if (current_contained.equals(contained_types)) {
674
+ return std::static_pointer_cast<Type>(static_cast<SharedType *>(this)->shared_from_this());
675
+ }
676
+ return createWithContained(std::move(contained_types));
677
+ }
678
+
679
+
680
+ TORCH_API inline bool operator==(const Type& lhs, const Type& rhs) {
681
+ if (C10_UNLIKELY(!rhs.symmetric())) {
682
+ return rhs.equals(lhs);
683
+ }
684
+ return lhs.equals(rhs);
685
+ }
686
+
687
+ struct NamedType;
688
+ using NamedTypePtr = std::shared_ptr<NamedType>;
689
+ using ConstNamedTypePtr = std::shared_ptr<const NamedType>;
690
+
691
+ struct TORCH_API NamedType : public SharedType {
692
+ NamedType(TypeKind tk, std::optional<QualifiedName> name)
693
+ : SharedType(tk), name_(std::move(name)) {
694
+ TORCH_INTERNAL_ASSERT(
695
+ tk == TypeKind::TupleType || tk == TypeKind::FunctionType ||
696
+ tk == TypeKind::ClassType || tk == TypeKind::InterfaceType ||
697
+ tk == TypeKind::EnumType,
698
+ "If you add a new kind of NamedType, ",
699
+ "please update the cast<NamedType> specialization and this assert");
700
+ }
701
+
702
+ // Fully qualified name of type
703
+ // Looks like: "foo.bar.Baz".
704
+ const std::optional<QualifiedName>& name() const {
705
+ return name_;
706
+ }
707
+
708
+ private:
709
+ std::optional<QualifiedName> name_;
710
+ };
711
+
712
+ } // namespace c10
713
+
714
+ namespace std {
715
+ template <typename T>
716
+ struct hash<c10::SingletonOrSharedTypePtr<T>> {
717
+ size_t operator()(const c10::SingletonOrSharedTypePtr<T>& x) const {
718
+ return std::hash<T*>()(x.get());
719
+ }
720
+ };
721
+ } // namespace std
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/operator_name.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/Exception.h>
5
+
6
+ #include <cstring>
7
+ #include <optional>
8
+ #include <ostream>
9
+ #include <string>
10
+ #include <string_view>
11
+ #include <utility>
12
+
13
+ namespace c10 {
14
+
15
+ // TODO: consider storing namespace separately too
16
+ struct OperatorName final {
17
+ std::string name;
18
+ std::string overload_name;
19
+ OperatorName(std::string name, std::string overload_name)
20
+ : name(std::move(name)), overload_name(std::move(overload_name)) {}
21
+
22
+ // TODO: These two functions below are slow! Fix internal data structures so
23
+ // I don't have to manually reconstruct the namespaces!
24
+
25
+ // Return the namespace of this OperatorName, if it exists. The
26
+ // returned string_view is only live as long as the OperatorName
27
+ // exists and name is not mutated
28
+ std::optional<std::string_view> getNamespace() const {
29
+ auto pos = name.find("::");
30
+ if (pos == std::string::npos) {
31
+ return std::nullopt;
32
+ } else {
33
+ return std::string_view(name.data(), pos);
34
+ }
35
+ }
36
+
37
+ // Returns true if we successfully set the namespace
38
+ bool setNamespaceIfNotSet(const char* ns) {
39
+ if (!getNamespace().has_value()) {
40
+ const auto ns_len = strlen(ns);
41
+ const auto old_name_size = name.size();
42
+ name.resize(ns_len + 2 + old_name_size);
43
+ // Shift current value of name to the end of the new space.
44
+ name.replace(
45
+ name.size() - old_name_size, old_name_size, name, 0, old_name_size);
46
+ name.replace(0, ns_len, ns, ns_len);
47
+ name[ns_len] = ':';
48
+ name[ns_len + 1] = ':';
49
+ return true;
50
+ } else {
51
+ return false;
52
+ }
53
+ }
54
+ };
55
+
56
+ // Non-owning view of an OperatorName. Unlike OperatorName, most of
57
+ // its functions are constexpr, so it can be used for compile time
58
+ // computations
59
+ struct OperatorNameView final {
60
+ std::string_view name;
61
+ std::string_view overload_name;
62
+ constexpr OperatorNameView(
63
+ std::string_view name,
64
+ std::string_view overload_name)
65
+ : name(name), overload_name(overload_name) {}
66
+ // Parses strings like "foo.overload" and also "foo"
67
+ constexpr static OperatorNameView parse(std::string_view full_name) {
68
+ auto i = full_name.find('.');
69
+ if (i == std::string_view::npos) {
70
+ return OperatorNameView(full_name, std::string_view());
71
+ } else {
72
+ return OperatorNameView(full_name.substr(0, i), full_name.substr(i + 1));
73
+ }
74
+ }
75
+ };
76
+
77
+ inline bool operator==(const OperatorName& lhs, const OperatorName& rhs) {
78
+ return lhs.name == rhs.name && lhs.overload_name == rhs.overload_name;
79
+ }
80
+
81
+ inline bool operator!=(const OperatorName& lhs, const OperatorName& rhs) {
82
+ return !operator==(lhs, rhs);
83
+ }
84
+
85
+ TORCH_API std::string toString(const OperatorName& opName);
86
+ TORCH_API std::ostream& operator<<(std::ostream&, const OperatorName&);
87
+
88
+ } // namespace c10
89
+
90
+ namespace std {
91
+ template <>
92
+ struct hash<::c10::OperatorName> {
93
+ size_t operator()(const ::c10::OperatorName& x) const {
94
+ return std::hash<std::string>()(x.name) ^
95
+ (~std::hash<std::string>()(x.overload_name));
96
+ }
97
+ };
98
+ } // namespace std
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/qualified_name.h ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/ArrayRef.h>
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/StringUtil.h>
6
+ #include <c10/util/irange.h>
7
+ #include <string>
8
+
9
+ namespace c10 {
10
+
11
+ // Represents a name of the form "foo.bar.baz"
12
+ struct QualifiedName {
13
+ QualifiedName() = default;
14
+
15
+ // `name` can be a dotted string, like "foo.bar.baz", or just a bare name.
16
+ /* implicit */ QualifiedName(const std::string& name) {
17
+ TORCH_CHECK(!name.empty());
18
+ // split the string into its atoms.
19
+ size_t startSearchFrom = 0;
20
+ size_t pos = name.find(delimiter_, startSearchFrom);
21
+
22
+ while (pos != std::string::npos) {
23
+ auto atom = name.substr(startSearchFrom, pos - startSearchFrom);
24
+ TORCH_INTERNAL_ASSERT(
25
+ !atom.empty(), "Invalid name for qualified name: '", name, "'");
26
+ atoms_.push_back(std::move(atom));
27
+ startSearchFrom = pos + 1;
28
+ pos = name.find(delimiter_, startSearchFrom);
29
+ }
30
+
31
+ auto finalAtom = name.substr(startSearchFrom);
32
+ TORCH_INTERNAL_ASSERT(
33
+ !finalAtom.empty(), "Invalid name for qualified name: '", name, "'");
34
+ atoms_.emplace_back(std::move(finalAtom));
35
+
36
+ cacheAccessors();
37
+ }
38
+
39
+ explicit QualifiedName(std::vector<std::string> atoms) : atoms_(std::move(atoms)) {
40
+ for (const auto& atom : atoms_) {
41
+ TORCH_CHECK(!atom.empty(), "Atom cannot be empty");
42
+ TORCH_CHECK(
43
+ atom.find(delimiter_) == std::string::npos,
44
+ "Delimiter not allowed in atom");
45
+ }
46
+
47
+ cacheAccessors();
48
+ }
49
+ // Unnecessary copy. Ideally we'd use something like std::string_view.
50
+ /* implicit */ QualifiedName(const char* name)
51
+ : QualifiedName(std::string(name)) {}
52
+
53
+ // `name` must be a bare name (no dots!)
54
+ explicit QualifiedName(const QualifiedName& prefix, std::string name) {
55
+ TORCH_INTERNAL_ASSERT(!name.empty());
56
+ TORCH_INTERNAL_ASSERT(name.find(delimiter_) == std::string::npos);
57
+ atoms_.insert(atoms_.begin(), prefix.atoms_.begin(), prefix.atoms_.end());
58
+ atoms_.push_back(std::move(name));
59
+
60
+ cacheAccessors();
61
+ }
62
+
63
+ // Is `this` a prefix of `other`?
64
+ // For example, "foo.bar" is a prefix of "foo.bar.baz"
65
+ bool isPrefixOf(const QualifiedName& other) const {
66
+ const auto& thisAtoms = atoms_;
67
+ const auto& otherAtoms = other.atoms_;
68
+
69
+ if (thisAtoms.size() > otherAtoms.size()) {
70
+ // Can't be a prefix if it's bigger
71
+ return false;
72
+ }
73
+ for (const auto i : c10::irange(thisAtoms.size())) {
74
+ if (thisAtoms[i] != otherAtoms[i]) {
75
+ return false;
76
+ }
77
+ }
78
+ return true;
79
+ }
80
+
81
+ // The fully qualified name, like "foo.bar.baz"
82
+ const std::string& qualifiedName() const {
83
+ return qualifiedName_;
84
+ }
85
+
86
+ // The leading qualifier, like "foo.bar"
87
+ const std::string& prefix() const {
88
+ return prefix_;
89
+ }
90
+
91
+ // The base name, like "baz"
92
+ const std::string& name() const {
93
+ return name_;
94
+ }
95
+
96
+ const std::vector<std::string>& atoms() const {
97
+ return atoms_;
98
+ }
99
+
100
+ bool operator==(const QualifiedName& other) const {
101
+ return this->qualifiedName_ == other.qualifiedName_;
102
+ }
103
+
104
+ bool operator!=(const QualifiedName& other) const {
105
+ return !(*this == other);
106
+ }
107
+
108
+ private:
109
+ static constexpr char delimiter_ = '.';
110
+
111
+ // Helper for cacheAccessors() below.
112
+ template<typename T>
113
+ std::string join(char delimiter, const T& v) {
114
+ std::string out;
115
+ size_t reserve = 0;
116
+ for (const auto& e : v) {
117
+ reserve += e.size() + 1;
118
+ }
119
+ out.reserve(reserve);
120
+ for (const auto i : c10::irange(v.size())) {
121
+ if (i != 0) {
122
+ out.push_back(delimiter);
123
+ }
124
+ out.append(v[i]);
125
+ }
126
+ return out;
127
+ }
128
+
129
+ void cacheAccessors() {
130
+ qualifiedName_ = join(delimiter_, atoms_);
131
+ if (atoms_.size() > 1) {
132
+ ArrayRef<std::string> view(atoms_);
133
+ const auto prefixView = view.slice(0, view.size() - 1);
134
+ prefix_ = join(delimiter_, prefixView);
135
+ }
136
+
137
+ if (!atoms_.empty()) {
138
+ name_ = atoms_.back();
139
+ }
140
+ }
141
+
142
+ // The actual list of names, like "{foo, bar, baz}"
143
+ std::vector<std::string> atoms_;
144
+
145
+ /*
146
+ * Cached accessors, derived from `atoms_`.
147
+ */
148
+ std::string qualifiedName_;
149
+ std::string prefix_;
150
+ std::string name_;
151
+ };
152
+ } // namespace c10
153
+
154
+ namespace std {
155
+ template <>
156
+ struct hash<c10::QualifiedName> {
157
+ size_t operator()(const c10::QualifiedName& n) const noexcept {
158
+ return std::hash<std::string>()(n.qualifiedName());
159
+ }
160
+ };
161
+ } // namespace std
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/rref_interface.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/intrusive_ptr.h>
4
+ #include <ATen/core/jit_type_base.h>
5
+
6
+ namespace c10 {
7
+
8
+ struct Type;
9
+ using worker_id_t = int16_t;
10
+
11
+ // This abstract class contains only user-facing APIs, and will be shared
12
+ // between jit and distributed to implement TorchScript support.
13
+ class C10_EXPORT RRefInterface : public c10::intrusive_ptr_target {
14
+ public:
15
+ RRefInterface() = default;
16
+ // RRef is made NOT copyable NOT movable to prevent messing up reference
17
+ // counting.
18
+ RRefInterface(const RRefInterface& other) = delete;
19
+ RRefInterface(RRefInterface&& other) = delete;
20
+ RRefInterface& operator=(const RRefInterface& other) = delete;
21
+ RRefInterface& operator=(RRefInterface&& other) = delete;
22
+
23
+ ~RRefInterface() override = default;
24
+
25
+ // returns the worker id of the owner
26
+ virtual worker_id_t owner() const = 0;
27
+
28
+ // returns the worker name of the owner
29
+ virtual std::string ownerName() const = 0;
30
+
31
+ // Returns true if this is the ``OwnerRRef``
32
+ virtual bool isOwner() const = 0;
33
+
34
+ // Returns true if this is an ``OwnerRRef`` or if this ``UserRRef`` has been
35
+ // confirmed by its owner.
36
+ virtual bool confirmedByOwner() const = 0;
37
+
38
+ virtual const TypePtr type() const = 0;
39
+ };
40
+
41
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/stack.h ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <type_traits>
4
+
5
+ #include <ATen/core/ivalue.h>
6
+ #include <c10/util/Deprecated.h>
7
+ #include <c10/util/irange.h>
8
+
9
+ // TODO move this to c10 namespace
10
+
11
+
12
+ namespace torch::jit {
13
+
14
+ using c10::IValue;
15
+ using Stack = std::vector<IValue>;
16
+
17
+ class Operation {
18
+ template <typename F, typename Arg>
19
+ using accepts = std::is_constructible<std::function<void(Arg)>, F&&>;
20
+
21
+ public:
22
+ template <typename F,
23
+ std::enable_if_t<accepts<F, Stack*>::value, int> = 0>
24
+ C10_DEPRECATED_MESSAGE("Please use void(Stack&) to register operator instead.")
25
+ Operation(F&& raw): op_([raw = std::forward<F>(raw)](Stack& stack) {
26
+ raw(&stack);
27
+ }) {}
28
+
29
+ template <typename F,
30
+ std::enable_if_t<accepts<F, Stack&>::value &&
31
+ !std::is_same_v<std::decay_t<F>, Operation>, int> = 0>
32
+ Operation(F&& op): op_(std::forward<F>(op)) {}
33
+
34
+ Operation(std::nullptr_t) noexcept {}
35
+
36
+ explicit operator bool() const noexcept {
37
+ return op_ ? true : false;
38
+ }
39
+
40
+ void operator()(Stack& stack) {
41
+ op_(stack);
42
+ }
43
+
44
+ template <typename T>
45
+ T* target() noexcept {
46
+ return op_.target<T>();
47
+ }
48
+
49
+ private:
50
+ std::function<void(Stack&)> op_;
51
+ };
52
+
53
+ // An operation with N inputs and M outputs pops the last N inputs off
54
+ // the stack and pushes its M inputs onto the stack
55
+ // before: <other stack items> I0, I1, ... IN <- stack.back()
56
+ // after: <other stack items> O0, O1, ... OM
57
+ // operations are defined this way so that ownership of inputs can be
58
+ // transferred to the operation and it can incrementally drop ownership of
59
+ // tensors when they become unneeded. For large operations, like 'run an entire
60
+ // subgraph', this functionality is very important for minimizing gpu memory
61
+ // usage return value is the relative 'offset' to jump to for the next
62
+ // operation:
63
+ // pc += 1 + offset
64
+ // so a return value of 0 goes to the next instruction
65
+
66
+ // treat the last N elements of the stack as a list, looking up
67
+ // element i
68
+ inline IValue& peek(Stack& stack, size_t i, size_t N) {
69
+ // NOLINTNEXTLINE(*-narrowing-conversions)
70
+ return *(stack.end() - N + i);
71
+ }
72
+ inline IValue& peek(Stack* stack, size_t i, size_t N) {
73
+ return peek(*stack, i, N);
74
+ }
75
+ inline const IValue& peek(const Stack& stack, size_t i, size_t N) {
76
+ // NOLINTNEXTLINE(*-narrowing-conversions)
77
+ return *(stack.end() - N + i);
78
+ }
79
+ inline const IValue& peek(const Stack* stack, size_t i, size_t N) {
80
+ return peek(*stack, i, N);
81
+ }
82
+ // treat the last N elements of the stack as a list, looking up the
83
+ // slice starting at index i and having length len
84
+ inline at::ArrayRef<IValue> peekSlice(
85
+ const Stack& stack,
86
+ size_t i,
87
+ size_t len,
88
+ size_t N) {
89
+ return at::ArrayRef<IValue>(stack).slice(stack.size() - N + i, len);
90
+ }
91
+ inline at::ArrayRef<IValue> last(const Stack& stack, size_t N) {
92
+ return peekSlice(stack, 0, N, N);
93
+ }
94
+ inline at::ArrayRef<IValue> last(const Stack* stack, size_t N) {
95
+ return last(*stack, N);
96
+ }
97
+ inline void drop(Stack& stack, size_t n) {
98
+ // NOLINTNEXTLINE(*-narrowing-conversions)
99
+ stack.erase(stack.end() - n, stack.end());
100
+ }
101
+ inline void drop(Stack* stack, size_t n) {
102
+ drop(*stack, n);
103
+ }
104
+ inline IValue pop(Stack& stack) {
105
+ TORCH_CHECK(!stack.empty(), "pop() called on empty stack");
106
+ auto r = std::move(stack.back());
107
+ stack.pop_back();
108
+ return r;
109
+ }
110
+ inline IValue pop(Stack* stack) {
111
+ return pop(*stack);
112
+ }
113
+ inline std::vector<IValue> pop(Stack& stack, size_t n) {
114
+ std::vector<IValue> result;
115
+ result.reserve(n);
116
+ for (const auto i : c10::irange(n)) {
117
+ result.push_back(std::move(peek(stack, i, n)));
118
+ }
119
+ drop(stack, n);
120
+ return result;
121
+ }
122
+
123
+ // variadic pop:
124
+ // int64_t a; at::Tensor b;
125
+ // pop(stack, a, b);
126
+ // equivalent to:
127
+ // b = pop(stack).toTensor();
128
+ // a = pop(stack).toInt();
129
+ template <typename... Types>
130
+ inline void pop(Stack& stack, Types&... args) {
131
+ size_t i = 0;
132
+ constexpr size_t N = sizeof...(args);
133
+ (void)std::initializer_list<int>{
134
+ (args = std::move(peek(stack, i++, N)).template to<Types>(), 0)...};
135
+ drop(stack, N);
136
+ }
137
+ template <typename... Types>
138
+ inline void pop(Stack* stack, Types&... args) {
139
+ pop(*stack, args...);
140
+ }
141
+ template <typename Type>
142
+ inline void push_one(Stack& stack, Type&& arg) {
143
+ stack.emplace_back(std::forward<Type>(arg));
144
+ }
145
+
146
+ inline void push_one(Stack& stack, c10::TensorOptions options) {
147
+ stack.emplace_back(c10::typeMetaToScalarType(options.dtype()));
148
+ stack.emplace_back(options.layout());
149
+ stack.emplace_back(options.device());
150
+ stack.emplace_back(options.pinned_memory());
151
+ }
152
+
153
+ template <typename... Types>
154
+ inline void push(Stack& stack, Types&&... args) {
155
+ (void)std::initializer_list<int>{(push_one(stack, std::forward<Types>(args)), 0)...};
156
+ }
157
+ template <typename... Types>
158
+ inline void push(Stack* stack, Types&&... args) {
159
+ return push(*stack, std::forward<Types>(args)...);
160
+ }
161
+ template <class T>
162
+ inline void push_list_elements(Stack& stack, const c10::List<T>& elements) {
163
+ for (T elem : elements) {
164
+ stack.push_back(std::move(elem));
165
+ }
166
+ }
167
+
168
+ // The packer here is carefully written not to make any unnecessary
169
+ // copies.
170
+
171
+ // pack takes the return values of aten functions pushes them onto the stack
172
+ template <typename T>
173
+ inline void pack(Stack& stack, T&& v) {
174
+ stack.emplace_back(std::forward<T>(v));
175
+ }
176
+ template <typename T>
177
+ inline void pack(Stack* stack, T&& v) {
178
+ pack(*stack, std::forward<T>(v));
179
+ }
180
+
181
+ template <std::size_t remaining, typename... Args>
182
+ struct TuplePacker {
183
+ // NB: *Not* a universal reference.
184
+ static void execute(Stack& stack, std::tuple<Args...>&& t) {
185
+ // NB: The move here does not "destroy" the entire tuple, that is
186
+ // not what std::move does; only the particular tuple index
187
+ // processed here gets stolen.
188
+ pack(stack, std::get<sizeof...(Args) - remaining>(std::move(t)));
189
+ TuplePacker<remaining - 1, Args...>::execute(stack, std::move(t));
190
+ }
191
+ };
192
+
193
+ template <typename... Args>
194
+ struct TuplePacker<0, Args...> {
195
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
196
+ static void execute(Stack& /*stack*/, std::tuple<Args...>&& /*t*/){}
197
+ };
198
+
199
+ template <typename... Args>
200
+ inline void pack(Stack& stack, std::tuple<Args...>&& t) {
201
+ TuplePacker<sizeof...(Args), Args...>::execute(stack, std::move(t));
202
+ }
203
+
204
+ } // namespace torch::jit
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/symbol.h ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Export.h>
3
+ #include <cstdint>
4
+ #include <functional> // For std::hash
5
+ #include <string>
6
+
7
+
8
+ namespace c10 {
9
+
10
+ // 'prim' symbols are synthetic operators that occur only in the IR
11
+ // and don't have corresponding implementations in ATen.
12
+
13
+ // 'onnx' symbols correspond to ONNX operators. Their semantics
14
+ // are defined in https://github.com/onnx/onnx/blob/master/docs/Operators.md
15
+ // The particular version we are targeting is specified by '_onnx_opset_version'
16
+ // in torch.onnx.symbolic_helper
17
+ //
18
+ // In general, most ONNX operators won't get an entry here, because they
19
+ // are handled from the Python end. However, you may occasionally need
20
+ // to intern an ONNX symbol here so that you can conveniently write an
21
+ // optimization on ONNX operations.
22
+
23
+ // 'attr' symbols are attribute keys. They are shared between both ONNX and ATen
24
+ // operators (you disambiguate their meaning by looking at the operator itself).
25
+ // In general, you only need to define attribute keys that are used by
26
+ // onnx or prim; ATen attributes are automatically generated in FORALL_ATTR_BASE_SYMBOLS.
27
+
28
+ // Note [Symbol allocation]
29
+ // ~~~~~~~~~~~~~~~~~~~~~~~~
30
+ //
31
+ // 1. Symbol namespace is split up into namespaces.
32
+ //
33
+ // 2. The intended access pattern for built-in symbols is onnx::MatMul
34
+ // in the c10 namespace (this is a Symbol).
35
+ //
36
+
37
+ // Built-in constant definition strategy:
38
+ // - Enum is the most convenient way to generate a contiguous sequence
39
+ // of numbers for an identifier.
40
+ // - However, an enum gives you a fresh type. We want onnx::MatMul to
41
+ // be type Symbol, not some random enum type!
42
+ // - Therefore, after using enums to generate the sequence of integers,
43
+ // we then declare constexpr Symbols to get everything the actual Symbol
44
+ // type we want. Symbols must be constexpr to be valid to be "case"ed on.
45
+
46
+ using unique_t = uint32_t;
47
+
48
+ const std::string& domain_prefix();
49
+
50
+ // A Symbol is like an interned string, but with a little extra
51
+ // structure; it is namespaced via SymbolNamespace and the resulting
52
+ // intern pointers support efficient namespace testing.
53
+ struct TORCH_API Symbol {
54
+ explicit constexpr Symbol() : value(0) {}
55
+ explicit constexpr Symbol(unique_t uniq)
56
+ : value(uniq) {}
57
+
58
+ // Get a Symbol for a qualified string like "attr::bar"
59
+ static Symbol fromQualString(const std::string & s);
60
+
61
+ // Get a Symbol from a domain and an unqualified string like "org.pytorch.attr" and "bar"
62
+ static Symbol fromDomainAndUnqualString(const std::string & d, const std::string & s);
63
+
64
+ // Constructors for our various namespaced strings. This will construct
65
+ // the appropriate namespaced string, e.g., "attr::foo" for the
66
+ // argument "foo", and then attempt to intern it. DO NOT USE THIS
67
+ // with a string literal; attr::foo should be available in that case
68
+ // (and if it's not, you should add it to the built-ins list above.)
69
+ static Symbol attr(const std::string & s);
70
+ static Symbol aten(const std::string & s);
71
+ static Symbol cuda(const std::string & s);
72
+ static Symbol onnx(const std::string & s);
73
+ static Symbol prim(const std::string & s);
74
+ static Symbol user(const std::string & s);
75
+ static Symbol caffe2(const std::string & s);
76
+ static Symbol dimname(const std::string & s);
77
+ // TODO: eliminate me
78
+ static Symbol scope(const std::string & s);
79
+
80
+ bool is_attr() const;
81
+ bool is_aten() const;
82
+ bool is_cuda() const;
83
+ bool is_prim() const;
84
+ bool is_prims() const;
85
+ bool is_nvprims() const;
86
+ bool is_onnx() const;
87
+ bool is_user() const;
88
+ bool is_caffe2() const;
89
+ bool is_dimname() const;
90
+
91
+ // So we can switch on this
92
+ constexpr operator unique_t() const {
93
+ return value;
94
+ }
95
+
96
+ Symbol ns() const;
97
+
98
+ // Give a string corresponding to the unqualified version of this name, e.g.,
99
+ // "mm". Use this in a context where the intended namespace of the string is
100
+ // obvious; this is a *lossy* conversion.
101
+ const char * toUnqualString() const;
102
+
103
+ // Give a string corresponding to the qualified version of this name,
104
+ // e.g., "aten::mm". This string format is made available to Python bindings
105
+ // (so we know how to parse it.)
106
+ const char * toQualString() const;
107
+
108
+ // This describes a symbol in a case where humans read it. At the moment it's
109
+ // the same as toQualString. This has to be a const char* returned because
110
+ // a lot of printf style macros use it.
111
+ const char * toDisplayString() const;
112
+
113
+ // Give a string corresponding to the domain name for the symbol,
114
+ // e.g., "org.pytorch.aten".
115
+ std::string domainString() const;
116
+
117
+ private:
118
+
119
+ explicit Symbol(Symbol ns, const std::string & s);
120
+ unique_t value;
121
+ };
122
+
123
+ static inline bool operator==(Symbol lhs, Symbol rhs) {
124
+ return static_cast<unique_t>(lhs) == static_cast<unique_t>(rhs);
125
+ }
126
+
127
+ inline Symbol Symbol::attr(const std::string & s) { return Symbol::fromQualString("attr::" + s); }
128
+ inline Symbol Symbol::aten(const std::string & s) { return Symbol::fromQualString("aten::" + s); }
129
+ inline Symbol Symbol::cuda(const std::string & s) { return Symbol::fromQualString("cuda::" + s); }
130
+ inline Symbol Symbol::onnx(const std::string & s) { return Symbol::fromQualString("onnx::" + s); }
131
+ inline Symbol Symbol::prim(const std::string & s) { return Symbol::fromQualString("prim::" + s); }
132
+ inline Symbol Symbol::scope(const std::string & s) { return Symbol::fromQualString("scope::" + s); }
133
+ inline Symbol Symbol::user(const std::string & s) { return Symbol::fromQualString("user::" + s); }
134
+ inline Symbol Symbol::caffe2(const std::string & s) { return Symbol::fromQualString("_caffe2::" + s); }
135
+ inline Symbol Symbol::dimname(const std::string & s) { return Symbol::fromQualString("dimname::" + s); }
136
+
137
+ } // namespace c10
138
+
139
+ // make symbol behave like an integer in hash tables
140
+ namespace std {
141
+ template <>
142
+ struct hash<c10::Symbol> {
143
+ size_t operator()(c10::Symbol s) const {
144
+ return std::hash<uint32_t>()(static_cast<uint32_t>(s));
145
+ }
146
+ };
147
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/type_factory.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <type_traits>
4
+ #include <unordered_map>
5
+
6
+ #include <ATen/core/dynamic_type.h>
7
+ #include <ATen/core/jit_type_base.h>
8
+ #include <c10/macros/Macros.h>
9
+
10
+ namespace c10 {
11
+
12
+ template <typename T>
13
+ struct TORCH_API TypeFactoryBase {};
14
+
15
+ template <>
16
+ struct TORCH_API TypeFactoryBase<c10::DynamicType> {
17
+ template <typename T, typename... Args>
18
+ static c10::DynamicTypePtr create(TypePtr ty, Args&&... args) {
19
+ return std::make_shared<c10::DynamicType>(
20
+ c10::DynamicTypeTrait<T>::tagValue(),
21
+ c10::DynamicType::Arguments(c10::ArrayRef<c10::TypePtr>(
22
+ {std::move(ty), std::forward<Args>(args)...})));
23
+ }
24
+ template <typename T>
25
+ static c10::DynamicTypePtr create(const std::vector<c10::TypePtr>& types) {
26
+ return std::make_shared<c10::DynamicType>(
27
+ c10::DynamicTypeTrait<T>::tagValue(),
28
+ c10::DynamicType::Arguments(types));
29
+ }
30
+ static c10::DynamicTypePtr createNamedTuple(
31
+ const std::string& name,
32
+ const std::vector<std::string_view>& fields,
33
+ const std::vector<c10::TypePtr>& types) {
34
+ return std::make_shared<c10::DynamicType>(
35
+ c10::DynamicType::Tag::Tuple,
36
+ name,
37
+ c10::DynamicType::Arguments(fields, types));
38
+ }
39
+ template <typename T>
40
+ C10_ERASE static c10::DynamicTypePtr createNamed(const std::string& name) {
41
+ return std::make_shared<c10::DynamicType>(
42
+ c10::DynamicTypeTrait<T>::tagValue(),
43
+ name,
44
+ c10::DynamicType::Arguments{});
45
+ }
46
+ template <typename T>
47
+ C10_ERASE static c10::DynamicTypePtr get() {
48
+ return DynamicTypeTrait<T>::getBaseType();
49
+ }
50
+ static const std::unordered_map<std::string, c10::TypePtr>& basePythonTypes();
51
+ };
52
+
53
+ using DynamicTypeFactory = TypeFactoryBase<c10::DynamicType>;
54
+
55
+ // Helper functions for constructing DynamicTypes inline.
56
+ template <
57
+ typename T,
58
+ std::enable_if_t<DynamicTypeTrait<T>::isBaseType, int> = 0>
59
+ C10_ERASE DynamicTypePtr dynT() {
60
+ return DynamicTypeFactory::get<T>();
61
+ }
62
+
63
+ template <
64
+ typename T,
65
+ typename... Args,
66
+ std::enable_if_t<!DynamicTypeTrait<T>::isBaseType, int> = 0>
67
+ C10_ERASE DynamicTypePtr dynT(Args&&... args) {
68
+ return DynamicTypeFactory::create<T>(std::forward<Args>(args)...);
69
+ }
70
+
71
+ template <>
72
+ struct TORCH_API TypeFactoryBase<c10::Type> {
73
+ template <typename T, typename... Args>
74
+ static c10::TypePtr create(TypePtr ty, Args&&... args) {
75
+ return T::create(std::move(ty), std::forward<Args>(args)...);
76
+ }
77
+ template <typename T>
78
+ static c10::TypePtr create(std::vector<c10::TypePtr> types) {
79
+ return T::create(std::move(types));
80
+ }
81
+ static c10::TypePtr createNamedTuple(
82
+ const std::string& name,
83
+ const std::vector<std::string_view>& fields,
84
+ const std::vector<c10::TypePtr>& types);
85
+ template <typename T>
86
+ C10_ERASE static c10::TypePtr createNamed(const std::string& name) {
87
+ return T::create(name);
88
+ }
89
+ static const std::unordered_map<std::string, c10::TypePtr>& basePythonTypes();
90
+ template <typename T>
91
+ C10_ERASE static c10::TypePtr get() {
92
+ return T::get();
93
+ }
94
+ };
95
+
96
+ using DefaultTypeFactory = TypeFactoryBase<c10::Type>;
97
+
98
+ using PlatformType =
99
+ #ifdef C10_MOBILE
100
+ c10::DynamicType
101
+ #else
102
+ c10::Type
103
+ #endif
104
+ ;
105
+
106
+ using TypeFactory = TypeFactoryBase<PlatformType>;
107
+
108
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/type_ptr.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <memory>
4
+ #include <type_traits>
5
+
6
+ #include <c10/util/Exception.h>
7
+ #include <c10/util/MaybeOwned.h>
8
+
9
+ namespace c10 {
10
+
11
+ // Compatibility wrapper around a raw pointer so that existing code
12
+ // written to deal with a shared_ptr can keep working.
13
+ template <typename T>
14
+ class SingletonTypePtr {
15
+ public:
16
+ /* implicit */ SingletonTypePtr(T* p) : repr_(p) {}
17
+
18
+ // We need this to satisfy Pybind11, but it shouldn't be hit.
19
+ explicit SingletonTypePtr(std::shared_ptr<T>) { TORCH_CHECK(false); }
20
+
21
+ using element_type = typename std::shared_ptr<T>::element_type;
22
+
23
+ template <typename U = T, std::enable_if_t<!std::is_same_v<std::remove_const_t<U>, void>, bool> = true>
24
+ T& operator*() const {
25
+ return *repr_;
26
+ }
27
+
28
+ T* get() const {
29
+ return repr_;
30
+ }
31
+
32
+ T* operator->() const {
33
+ return repr_;
34
+ }
35
+
36
+ operator bool() const {
37
+ return repr_ != nullptr;
38
+ }
39
+
40
+ private:
41
+ T* repr_{nullptr};
42
+ };
43
+
44
+ template <typename T, typename U>
45
+ bool operator==(SingletonTypePtr<T> lhs, SingletonTypePtr<U> rhs) {
46
+ return (void*)lhs.get() == (void*)rhs.get();
47
+ }
48
+
49
+ template <typename T, typename U>
50
+ bool operator!=(SingletonTypePtr<T> lhs, SingletonTypePtr<U> rhs) {
51
+ return !(lhs == rhs);
52
+ }
53
+
54
+ } // namespace c10
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/core/typeid.h ADDED
@@ -0,0 +1 @@
 
 
1
+ #include <c10/util/typeid.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/FlushDenormal.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// Flush-To-Zero and Denormals-Are-Zero mode
2
+ ///
3
+ /// Flush-To-Zero (FTZ) and Denormals-Are-Zero (DAZ) are modes that bypass
4
+ /// IEEE 754 methods of dealing with denormal floating-point numbers on x86-64
5
+ /// and some x86 CPUs. They result in reduced precision for values near zero,
6
+ /// but increased performance.
7
+ ///
8
+ /// See https://software.intel.com/en-us/articles/x87-and-sse-floating-point-assists-in-ia-32-flush-to-zero-ftz-and-denormals-are-zero-daz
9
+
10
+ namespace at::cpu {
11
+
12
+ bool set_flush_denormal(bool on);
13
+
14
+ } // namespace at::cpu
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/Utils.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+
5
+ #include <c10/macros/Export.h>
6
+
7
+ namespace at::cpu {
8
+
9
+ TORCH_API bool is_avx2_supported();
10
+ TORCH_API bool is_avx512_supported();
11
+
12
+ // Detect if CPU support Vector Neural Network Instruction.
13
+ TORCH_API bool is_avx512_vnni_supported();
14
+
15
+ // Detect if CPU supports AVX512_BF16 ISA
16
+ TORCH_API bool is_avx512_bf16_supported();
17
+
18
+ // Detect if CPU support Advanced Matrix Extension.
19
+ TORCH_API bool is_amx_tile_supported();
20
+
21
+ // Detect if CPU support Advanced Matrix Extension for fp16.
22
+ TORCH_API bool is_amx_fp16_supported();
23
+
24
+ // Enable the system to use AMX instructions.
25
+ TORCH_API bool init_amx();
26
+
27
+ // Get the L1 cache size per core in Byte
28
+ TORCH_API uint32_t L1d_cache_size();
29
+
30
+ // Get the L2 cache size per core in Byte
31
+ TORCH_API uint32_t L2_cache_size();
32
+
33
+ } // namespace at::cpu
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cpu/vml.h ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Config.h>
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/OpMathType.h>
6
+ #include <ATen/cpu/vec/functional.h>
7
+ #include <ATen/cpu/vec/vec.h>
8
+ #include <c10/util/complex.h>
9
+
10
+ // This header implements various unary operations using a MKL VML style
11
+ // interface.
12
+
13
+ // It implements various functions with a simple interface
14
+ // For example it enables the user to call vsin(float* out, const float* in,
15
+ // size) This functions takes a pointer to a continuous output array of floats and
16
+ // a constant input array. It will then apply sin to each value in the input
17
+ // array and write the result into the output array. out and in may point to the
18
+ // same memory, i.e. this fully supports in-place operations. These functions
19
+ // also implement their own parallelization, so take precautions when calling
20
+ // these from threaded functions.
21
+
22
+ // When MKL is available it will call into MKL's VML library similar to NumPy
23
+ // If MKL is not available it will use SLEEF.
24
+
25
+ // This file might be compiled under AVX or AVX2 when called from e.g.
26
+ // UnaryOpsKernel.cpp
27
+
28
+ #include <algorithm>
29
+ #include <cstddef>
30
+ #include <cstdint>
31
+ #include <cstring>
32
+ #include <type_traits>
33
+
34
+ #if AT_MKL_ENABLED() && !defined(__APPLE__)
35
+ #include <mkl.h>
36
+ #endif
37
+
38
+
39
+ namespace at::vml {
40
+ inline namespace CPU_CAPABILITY {
41
+
42
+ using namespace vec;
43
+
44
+ template <typename scalar_t>
45
+ inline void vrsqrt(scalar_t* out, scalar_t* in, int64_t size) {
46
+ parallel_for(0, size, 2048, [out, in](int64_t begin, int64_t end) {
47
+ map(
48
+ [](const Vectorized<scalar_t>& x) {
49
+ return Vectorized<scalar_t>((scalar_t)(1)) / x.sqrt();
50
+ },
51
+ out + begin,
52
+ in + begin,
53
+ end - begin);
54
+ });
55
+ }
56
+
57
+ // NB: We ignore numerical errors by convention and leave them to the user
58
+
59
+ #define IMPLEMENT_VML(op) \
60
+ template <typename scalar_t> \
61
+ inline void v##op(scalar_t* out, const scalar_t* in, int64_t size) { \
62
+ using vec_t = Vectorized<vec_scalar_t<scalar_t>>; \
63
+ vec::map([](vec_t x) { return x.op(); }, out, in, size); \
64
+ } \
65
+
66
+ IMPLEMENT_VML(abs)
67
+ IMPLEMENT_VML(acos)
68
+ IMPLEMENT_VML(asin)
69
+ IMPLEMENT_VML(atan)
70
+ IMPLEMENT_VML(atanh)
71
+ IMPLEMENT_VML(ceil)
72
+ IMPLEMENT_VML(cos)
73
+ // IMPLEMENT_VML(cosh)
74
+ IMPLEMENT_VML(erf)
75
+ IMPLEMENT_VML(erfc)
76
+ IMPLEMENT_VML(erfinv)
77
+ IMPLEMENT_VML(exp)
78
+ IMPLEMENT_VML(expm1)
79
+ IMPLEMENT_VML(floor)
80
+ IMPLEMENT_VML(i0)
81
+ IMPLEMENT_VML(i0e)
82
+ IMPLEMENT_VML(digamma)
83
+ IMPLEMENT_VML(reciprocal)
84
+ IMPLEMENT_VML(log)
85
+ IMPLEMENT_VML(log10)
86
+ IMPLEMENT_VML(log1p)
87
+ IMPLEMENT_VML(log2)
88
+ IMPLEMENT_VML(neg)
89
+ IMPLEMENT_VML(sin)
90
+ // IMPLEMENT_VML(sinh)
91
+ IMPLEMENT_VML(sqrt)
92
+ IMPLEMENT_VML(round)
93
+ IMPLEMENT_VML(rsqrt)
94
+ IMPLEMENT_VML(tan)
95
+ IMPLEMENT_VML(tanh)
96
+ IMPLEMENT_VML(trunc)
97
+ IMPLEMENT_VML(lgamma)
98
+
99
+
100
+ #if AT_MKL_ENABLED() && !defined(__APPLE__)
101
+
102
+ // NB: LP64 MKL is the most commonly used and thus we assume it here. That means
103
+ // we need to expect MKL_INT to be of type int, which implies int32_t or int64_t in most
104
+ // cases.
105
+ static_assert(
106
+ std::is_same_v<MKL_INT, int32_t> || std::is_same_v<MKL_INT, int64_t>,
107
+ "MKL_INT is assumed to be int32_t or int64_t");
108
+ #define IMPLEMENT_VML_MKL_STUB(op, mklop, type, mkltype) \
109
+ template <> \
110
+ inline void v##op(type * out, const type * in, int64_t size) { \
111
+ auto constexpr max_mkl_ind = std::numeric_limits<MKL_INT>::max(); \
112
+ if (size <= static_cast<int64_t>(max_mkl_ind)) { \
113
+ vm##mkltype##mklop( \
114
+ size, in, out, VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \
115
+ } else { \
116
+ int64_t ind = 0; \
117
+ int64_t chunks = size / max_mkl_ind; \
118
+ int64_t rest = size % max_mkl_ind; \
119
+ for (; ind < chunks; ind++) { \
120
+ vm##mkltype##mklop( \
121
+ max_mkl_ind, \
122
+ in + ind * max_mkl_ind, \
123
+ out + ind * max_mkl_ind, \
124
+ VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \
125
+ } \
126
+ vm##mkltype##mklop( \
127
+ rest, \
128
+ in + ind * max_mkl_ind, \
129
+ out + ind * max_mkl_ind, \
130
+ VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \
131
+ } \
132
+ }
133
+
134
+ #define IMPLEMENT_VML_MKL(op, mklop) \
135
+ IMPLEMENT_VML_MKL_STUB(op, mklop, float, s) \
136
+ IMPLEMENT_VML_MKL_STUB(op, mklop, double, d)
137
+
138
+ // NB: abs, cosh and sinh were temporarily disabled due to issues with Apple
139
+ // NB: expm1 is disabled because on some configs it produces expm1(nan)=-1
140
+ IMPLEMENT_VML_MKL(acos, Acos)
141
+ IMPLEMENT_VML_MKL(asin, Asin)
142
+ IMPLEMENT_VML_MKL(atan, Atan)
143
+ IMPLEMENT_VML_MKL(cos, Cos)
144
+ // IMPLEMENT_VML_MKL(cosh, Cosh)
145
+ IMPLEMENT_VML_MKL(erf, Erf)
146
+ IMPLEMENT_VML_MKL(erfc, Erfc)
147
+ IMPLEMENT_VML_MKL(erfinv, ErfInv)
148
+ IMPLEMENT_VML_MKL(exp, Exp)
149
+ // IMPLEMENT_VML_MKL(expm1, Expm1)
150
+ IMPLEMENT_VML_MKL(log, Ln)
151
+ IMPLEMENT_VML_MKL(log10, Log10)
152
+ IMPLEMENT_VML_MKL(sin, Sin)
153
+ // IMPLEMENT_VML_MKL(sinh, Sinh)
154
+ IMPLEMENT_VML_MKL(sqrt, Sqrt)
155
+ IMPLEMENT_VML_MKL(tan, Tan)
156
+ IMPLEMENT_VML_MKL(tanh, Tanh)
157
+ IMPLEMENT_VML_MKL(trunc, Trunc)
158
+
159
+ // Not vectorized in MKL version tested
160
+ // IMPLEMENT_VML_MKL(abs, Abs)
161
+ // IMPLEMENT_VML_MKL(log1p, Log1p)
162
+
163
+ #if INTEL_MKL_VERSION >= 20180406
164
+ IMPLEMENT_VML_MKL(log2, Log2)
165
+ #endif
166
+
167
+ #endif
168
+
169
+ } // namespace
170
+ } // namespace at::vml
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ATenCUDAGeneral.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <cuda_runtime.h>
5
+ #include <cuda_fp16.h>
6
+
7
+ #include <c10/macros/Export.h>
8
+
9
+ // Use TORCH_CUDA_CPP_API or TORCH_CUDA_CU_API for exports from this folder
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ApplyGridUtils.cuh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/cuda/CUDAContext.h>
2
+
3
+ #include <cuda_runtime.h>
4
+
5
+ namespace at::cuda {
6
+
7
+ /**
8
+ Computes ceil(a / b)
9
+ */
10
+ template <typename T>
11
+ __host__ __device__ __forceinline__ T ATenCeilDiv(T a, T b) {
12
+ return (a + b - 1) / b;
13
+ }
14
+
15
+ namespace {
16
+
17
+ // Threads per block for our apply kernel
18
+ // FIXME: use occupancy calculator instead
19
+ constexpr uint32_t AT_APPLY_THREADS_PER_BLOCK = 512;
20
+ constexpr uint32_t AT_APPLY_BLOCKS_PER_SM = 4;
21
+
22
+ template <int step = 1>
23
+ inline bool getApplyGrid(uint64_t totalElements, dim3& grid, c10::DeviceIndex curDevice, int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK) {
24
+ if (curDevice == -1) return false;
25
+ uint64_t numel_per_thread = static_cast<uint64_t>(max_threads_per_block) * static_cast<uint64_t>(step);
26
+ uint64_t numBlocks = ATenCeilDiv(totalElements, numel_per_thread);
27
+ uint64_t maxGridX = at::cuda::getDeviceProperties(curDevice)->maxGridSize[0];
28
+ if (numBlocks > maxGridX)
29
+ numBlocks = maxGridX;
30
+ grid = dim3(numBlocks);
31
+ return true;
32
+ }
33
+
34
+ constexpr int getApplyBlocksPerSM() {
35
+ return AT_APPLY_BLOCKS_PER_SM;
36
+ }
37
+
38
+ constexpr int getApplyBlockSize() {
39
+ return AT_APPLY_THREADS_PER_BLOCK;
40
+ }
41
+
42
+ inline dim3 getApplyBlock(int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK) {
43
+ return dim3(max_threads_per_block);
44
+ }
45
+
46
+ } // anonymous namespace
47
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/AsmUtils.cuh ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstdint>
3
+
4
+ // Collection of direct PTX functions
5
+
6
+ namespace at::cuda {
7
+
8
+ template <typename T>
9
+ struct Bitfield {};
10
+
11
+ template <>
12
+ struct Bitfield<unsigned int> {
13
+ static __device__ __host__ __forceinline__
14
+ unsigned int getBitfield(unsigned int val, int pos, int len) {
15
+ #if !defined(__CUDA_ARCH__)
16
+ pos &= 0xff;
17
+ len &= 0xff;
18
+
19
+ unsigned int m = (1u << len) - 1u;
20
+ return (val >> pos) & m;
21
+ #else
22
+ unsigned int ret;
23
+ asm("bfe.u32 %0, %1, %2, %3;" : "=r"(ret) : "r"(val), "r"(pos), "r"(len));
24
+ return ret;
25
+ #endif
26
+ }
27
+
28
+ static __device__ __host__ __forceinline__
29
+ unsigned int setBitfield(unsigned int val, unsigned int toInsert, int pos, int len) {
30
+ #if !defined(__CUDA_ARCH__)
31
+ pos &= 0xff;
32
+ len &= 0xff;
33
+
34
+ unsigned int m = (1u << len) - 1u;
35
+ toInsert &= m;
36
+ toInsert <<= pos;
37
+ m <<= pos;
38
+
39
+ return (val & ~m) | toInsert;
40
+ #else
41
+ unsigned int ret;
42
+ asm("bfi.b32 %0, %1, %2, %3, %4;" :
43
+ "=r"(ret) : "r"(toInsert), "r"(val), "r"(pos), "r"(len));
44
+ return ret;
45
+ #endif
46
+ }
47
+ };
48
+
49
+ template <>
50
+ struct Bitfield<uint64_t> {
51
+ static __device__ __host__ __forceinline__
52
+ uint64_t getBitfield(uint64_t val, int pos, int len) {
53
+ #if !defined(__CUDA_ARCH__)
54
+ pos &= 0xff;
55
+ len &= 0xff;
56
+
57
+ uint64_t m = (1u << len) - 1u;
58
+ return (val >> pos) & m;
59
+ #else
60
+ uint64_t ret;
61
+ asm("bfe.u64 %0, %1, %2, %3;" : "=l"(ret) : "l"(val), "r"(pos), "r"(len));
62
+ return ret;
63
+ #endif
64
+ }
65
+
66
+ static __device__ __host__ __forceinline__
67
+ uint64_t setBitfield(uint64_t val, uint64_t toInsert, int pos, int len) {
68
+ #if !defined(__CUDA_ARCH__)
69
+ pos &= 0xff;
70
+ len &= 0xff;
71
+
72
+ uint64_t m = (1u << len) - 1u;
73
+ toInsert &= m;
74
+ toInsert <<= pos;
75
+ m <<= pos;
76
+
77
+ return (val & ~m) | toInsert;
78
+ #else
79
+ uint64_t ret;
80
+ asm("bfi.b64 %0, %1, %2, %3, %4;" :
81
+ "=l"(ret) : "l"(toInsert), "l"(val), "r"(pos), "r"(len));
82
+ return ret;
83
+ #endif
84
+ }
85
+ };
86
+
87
+ __device__ __forceinline__ int getLaneId() {
88
+ #if defined(USE_ROCM)
89
+ return __lane_id();
90
+ #else
91
+ int laneId;
92
+ asm("mov.s32 %0, %%laneid;" : "=r"(laneId) );
93
+ return laneId;
94
+ #endif
95
+ }
96
+
97
+ #if defined(USE_ROCM)
98
+ __device__ __forceinline__ unsigned long long int getLaneMaskLt() {
99
+ const std::uint64_t m = (1ull << getLaneId()) - 1ull;
100
+ return m;
101
+ }
102
+ #else
103
+ __device__ __forceinline__ unsigned getLaneMaskLt() {
104
+ unsigned mask;
105
+ asm("mov.u32 %0, %%lanemask_lt;" : "=r"(mask));
106
+ return mask;
107
+ }
108
+ #endif
109
+
110
+ #if defined (USE_ROCM)
111
+ __device__ __forceinline__ unsigned long long int getLaneMaskLe() {
112
+ std::uint64_t m = UINT64_MAX >> (sizeof(std::uint64_t) * CHAR_BIT - (getLaneId() + 1));
113
+ return m;
114
+ }
115
+ #else
116
+ __device__ __forceinline__ unsigned getLaneMaskLe() {
117
+ unsigned mask;
118
+ asm("mov.u32 %0, %%lanemask_le;" : "=r"(mask));
119
+ return mask;
120
+ }
121
+ #endif
122
+
123
+ #if defined(USE_ROCM)
124
+ __device__ __forceinline__ unsigned long long int getLaneMaskGt() {
125
+ const std::uint64_t m = getLaneMaskLe();
126
+ return m ? ~m : m;
127
+ }
128
+ #else
129
+ __device__ __forceinline__ unsigned getLaneMaskGt() {
130
+ unsigned mask;
131
+ asm("mov.u32 %0, %%lanemask_gt;" : "=r"(mask));
132
+ return mask;
133
+ }
134
+ #endif
135
+
136
+ #if defined(USE_ROCM)
137
+ __device__ __forceinline__ unsigned long long int getLaneMaskGe() {
138
+ const std::uint64_t m = getLaneMaskLt();
139
+ return ~m;
140
+ }
141
+ #else
142
+ __device__ __forceinline__ unsigned getLaneMaskGe() {
143
+ unsigned mask;
144
+ asm("mov.u32 %0, %%lanemask_ge;" : "=r"(mask));
145
+ return mask;
146
+ }
147
+ #endif
148
+
149
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Atomic.cuh ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <c10/util/Half.h>
5
+ #include <c10/util/BFloat16.h>
6
+
7
+ #include <ATen/NumericUtils.h>
8
+
9
+ #if !(defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))))
10
+ #include <cuda_bf16.h>
11
+ #endif
12
+
13
+ template <typename T>
14
+ struct AtomicFPOp;
15
+
16
+ template <>
17
+ struct AtomicFPOp<at::Half> {
18
+ template <typename func_t>
19
+ inline __device__ at::Half operator() (at::Half *address, at::Half val, const func_t& func) {
20
+ unsigned int * address_as_ui =
21
+ (unsigned int *) ((char *)address - ((size_t)address & 2));
22
+ unsigned int old = *address_as_ui;
23
+ unsigned int assumed;
24
+
25
+ at::Half hsum;
26
+ do {
27
+ assumed = old;
28
+ hsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff);
29
+ hsum = func(hsum, val);
30
+ old = (size_t)address & 2 ? (old & 0xffff) | (hsum.x << 16) : (old & 0xffff0000) | hsum.x;
31
+ old = atomicCAS(address_as_ui, assumed, old);
32
+ } while (assumed != old);
33
+ hsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff);
34
+ return hsum;
35
+ }
36
+ };
37
+
38
+ template <>
39
+ struct AtomicFPOp<at::BFloat16> {
40
+ template <typename func_t>
41
+ inline __device__ at::BFloat16 operator() (at::BFloat16 *address, at::BFloat16 val, const func_t& func) {
42
+ unsigned int * address_as_ui =
43
+ (unsigned int *) ((char *)address - ((size_t)address & 2));
44
+ unsigned int old = *address_as_ui;
45
+ unsigned int assumed;
46
+
47
+ at::BFloat16 bsum;
48
+ do {
49
+ assumed = old;
50
+ bsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff);
51
+ bsum = func(bsum, val);
52
+ old = (size_t)address & 2 ? (old & 0xffff) | (bsum.x << 16) : (old & 0xffff0000) | bsum.x;
53
+ old = atomicCAS(address_as_ui, assumed, old);
54
+ } while (assumed != old);
55
+ bsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff);
56
+ return bsum.x;
57
+ }
58
+ };
59
+
60
+ template <>
61
+ struct AtomicFPOp<double> {
62
+ template <typename func_t>
63
+ inline __device__ double operator() (double * address, double val, const func_t& func) {
64
+ unsigned long long int* address_as_ull = (unsigned long long int*)address;
65
+ unsigned long long int old = *address_as_ull;
66
+ unsigned long long int assumed;
67
+
68
+ do {
69
+ assumed = old;
70
+ old = atomicCAS(address_as_ull, assumed, func(val, assumed));
71
+ // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
72
+ } while (assumed != old);
73
+
74
+ return __longlong_as_double(old);
75
+ }
76
+ };
77
+
78
+ #define ATOMIC_INTEGER_IMPL(NAME) \
79
+ template <typename T, size_t n> \
80
+ struct Atomic##NAME##IntegerImpl; \
81
+ \
82
+ template<typename T> \
83
+ struct Atomic##NAME##IntegerImpl<T, 1> { \
84
+ template <typename func_t> \
85
+ inline __device__ void operator()(T *address, T val, const func_t& func) { \
86
+ size_t offset = (size_t)address & 3; \
87
+ uint32_t * address_as_ui = (uint32_t *)((char *)address - offset); \
88
+ uint32_t old = *address_as_ui; \
89
+ uint32_t shift = offset * 8; \
90
+ uint32_t old_byte; \
91
+ uint32_t newval; \
92
+ uint32_t assumed; \
93
+ \
94
+ do { \
95
+ assumed = old; \
96
+ old_byte = (old >> shift) & 0xff; \
97
+ newval = static_cast<uint8_t>(func(val, static_cast<T>(old_byte))); \
98
+ newval = (old & ~(0x000000ff << shift)) | (newval << shift); \
99
+ old = atomicCAS(address_as_ui, assumed, newval); \
100
+ } while (assumed != old); \
101
+ } \
102
+ }; \
103
+ \
104
+ template<typename T> \
105
+ struct Atomic##NAME##IntegerImpl<T, 2> { \
106
+ template <typename func_t> \
107
+ inline __device__ void operator()(T *address, T val, const func_t& func) { \
108
+ size_t offset = (size_t)address & 2; \
109
+ uint32_t * address_as_ui = (uint32_t *)((char *)address - offset); \
110
+ bool is_32_align = offset; \
111
+ uint32_t old = *address_as_ui; \
112
+ uint32_t old_bytes; \
113
+ uint32_t newval; \
114
+ uint32_t assumed; \
115
+ \
116
+ do { \
117
+ assumed = old; \
118
+ old_bytes = is_32_align ? old >> 16 : old & 0xffff; \
119
+ newval = static_cast<uint16_t>(func(val, static_cast<T>(old_bytes))); \
120
+ newval = is_32_align ? (old & 0xffff) | (newval << 16) : (old & 0xffff0000) | newval; \
121
+ old = atomicCAS(address_as_ui, assumed, newval); \
122
+ } while (assumed != old); \
123
+ } \
124
+ }; \
125
+ \
126
+ template<typename T> \
127
+ struct Atomic##NAME##IntegerImpl<T, 4> { \
128
+ template <typename func_t> \
129
+ inline __device__ void operator()(T *address, T val, const func_t& func) { \
130
+ uint32_t * address_as_ui = (uint32_t *) (address); \
131
+ uint32_t old = *address_as_ui; \
132
+ uint32_t newval; \
133
+ uint32_t assumed; \
134
+ \
135
+ do { \
136
+ assumed = old; \
137
+ newval = static_cast<uint32_t>(func(val, static_cast<T>(old))); \
138
+ old = atomicCAS(address_as_ui, assumed, newval); \
139
+ } while (assumed != old); \
140
+ } \
141
+ }; \
142
+ \
143
+ template<typename T> \
144
+ struct Atomic##NAME##IntegerImpl<T, 8> { \
145
+ template <typename func_t> \
146
+ inline __device__ void operator()(T *address, T val, const func_t& func) { \
147
+ unsigned long long * address_as_ui = (unsigned long long *) (address); \
148
+ unsigned long long old = *address_as_ui; \
149
+ unsigned long long newval; \
150
+ unsigned long long assumed; \
151
+ \
152
+ do { \
153
+ assumed = old; \
154
+ newval = static_cast<uint64_t>(func(val, static_cast<T>(old))); \
155
+ old = atomicCAS(address_as_ui, assumed, newval); \
156
+ } while (assumed != old); \
157
+ } \
158
+ };
159
+
160
+
161
+ # define GPU_ATOMIC_INTEGER(NAME, OP, DTYPE) \
162
+ inline __device__ void gpuAtomic##NAME(DTYPE *address, DTYPE val) { \
163
+ Atomic##NAME##IntegerImpl<DTYPE, sizeof(DTYPE)>()(address, \
164
+ val, \
165
+ [](DTYPE a, DTYPE b) { \
166
+ return OP; \
167
+ }); \
168
+ } \
169
+
170
+ ATOMIC_INTEGER_IMPL(Add)
171
+ GPU_ATOMIC_INTEGER(Add, a || b, bool)
172
+
173
+ // Don't instantiate gpuAtomicAdd with the macro as it seems non-standard (see int32, int64)
174
+ inline __device__ void gpuAtomicAdd(uint8_t *address, uint8_t val) {
175
+ AtomicAddIntegerImpl<uint8_t, sizeof(uint8_t)>()(address,
176
+ val,
177
+ [](uint8_t a, uint8_t b) {
178
+ return a + b;
179
+ });
180
+ }
181
+
182
+ inline __device__ void gpuAtomicAdd(int8_t *address, int8_t val) {
183
+ AtomicAddIntegerImpl<int8_t, sizeof(int8_t)>()(address,
184
+ val,
185
+ [](int8_t a, int8_t b) {
186
+ return a + b;
187
+ });
188
+ }
189
+
190
+ inline __device__ void gpuAtomicAdd(int16_t *address, int16_t val) {
191
+ AtomicAddIntegerImpl<int16_t, sizeof(int16_t)>()(address,
192
+ val,
193
+ [](int16_t a, int16_t b) {
194
+ return a + b;
195
+ });
196
+ }
197
+
198
+ inline __device__ int32_t gpuAtomicAdd(int32_t *address, int32_t val) {
199
+ return atomicAdd(address, val);
200
+ }
201
+
202
+ inline __device__ void gpuAtomicAdd(int64_t *address, int64_t val) {
203
+ #if defined(USE_ROCM)
204
+ __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
205
+ #else
206
+ static_assert(sizeof(unsigned long long int) == sizeof(int64_t), "bitwidth change is not allowed");
207
+ atomicAdd(reinterpret_cast<unsigned long long int *>(address), static_cast<unsigned long long int>(val));
208
+ #endif
209
+ }
210
+
211
+ inline __device__ at::Half gpuAtomicAdd(at::Half *address, at::Half val) {
212
+ #if defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)))
213
+ return AtomicFPOp<at::Half>()(address, val,
214
+ [](at::Half hsum, at::Half val) {
215
+ return hsum + val;
216
+ });
217
+ #else
218
+ return atomicAdd(reinterpret_cast<__half*>(address), val);
219
+ #endif
220
+ }
221
+
222
+ inline __device__ at::BFloat16 gpuAtomicAdd(at::BFloat16 *address, at::BFloat16 val) {
223
+ #if defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800)))
224
+ return AtomicFPOp<at::BFloat16>()(address, val,
225
+ [](at::BFloat16 bsum, at::BFloat16 val) {
226
+ return bsum + val;
227
+ });
228
+ #else
229
+ __nv_bfloat16 r = atomicAdd(reinterpret_cast<__nv_bfloat16*>(address), *reinterpret_cast<__nv_bfloat16*>(&val));
230
+ return *reinterpret_cast<c10::BFloat16*>(&r);
231
+ #endif
232
+ }
233
+
234
+ #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 600)
235
+ // from CUDA C Programmic Guide
236
+ inline __device__ double atomicAdd(double* address, double val)
237
+ #if defined(__clang__) && defined(__CUDA__)
238
+ #pragma GCC diagnostic push
239
+ #pragma GCC diagnostic ignored "-Wgcc-compat"
240
+ __attribute__((enable_if(true, "")))
241
+ #pragma GCC diagnostic pop
242
+ #endif
243
+ {
244
+
245
+ return AtomicFPOp<double>()(address, val,
246
+ [](double val, unsigned long long int assumed) {
247
+ return __double_as_longlong(val + __longlong_as_double(assumed));
248
+ });
249
+ }
250
+ #elif defined(USE_ROCM) || !(defined(__CUDA_ARCH__))
251
+
252
+ /* Note [hip-clang differences to hcc]
253
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
254
+ * The upcoming hip-clang compiler for ROCm differs from hcc in a few details.
255
+ * It exports the __HIP__ macro, we can hence differentiate between hcc and
256
+ * hip-clang. In the below, hcc only received support for atomicAdd with double
257
+ * typing after work week 18312. hip-clang had support from the first version.
258
+ * In general, the code-visible differences between hip-clang and hcc will be
259
+ * minimal.
260
+ */
261
+
262
+ #if defined(USE_ROCM) && __hcc_workweek__ < 18312 && !__HIP__
263
+ // This needs to be defined for the host side pass
264
+ inline __device__ double atomicAdd(double *address, double val) { }
265
+ #endif
266
+ #endif
267
+
268
+ inline __device__ double gpuAtomicAdd(double *address, double val) {
269
+ return atomicAdd(address, val);
270
+ }
271
+
272
+ inline __device__ float gpuAtomicAdd(float *address, float val) {
273
+ return atomicAdd(address, val);
274
+ }
275
+
276
+ template<typename T>
277
+ inline __device__ void gpuAtomicAdd(c10::complex<T> *address, c10::complex<T> val) {
278
+ gpuAtomicAdd(&address->real_, val.real_);
279
+ gpuAtomicAdd(&address->imag_, val.imag_);
280
+ }
281
+
282
+ /* Note [gpuAtomicAdd vs atomicAdd]
283
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284
+ * Some extensions such as torchvision call atomicAdd()
285
+ * directly and require non-library provided data type support. Only for these, we
286
+ * continue to provide atomicAdd overloads.
287
+ */
288
+ inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) {
289
+ return gpuAtomicAdd(address, val);
290
+ }
291
+
292
+ inline __device__ at::BFloat16 atomicAdd(at::BFloat16 *address, at::BFloat16 val) {
293
+ return gpuAtomicAdd(address, val);
294
+ }
295
+
296
+ inline __device__ void atomicAdd(uint8_t *address, uint8_t val) {
297
+ gpuAtomicAdd(address, val);
298
+ }
299
+
300
+ inline __device__ void atomicAdd(int8_t *address, int8_t val) {
301
+ gpuAtomicAdd(address, val);
302
+ }
303
+
304
+ inline __device__ void atomicAdd(int16_t *address, int16_t val) {
305
+ gpuAtomicAdd(address, val);
306
+ }
307
+
308
+ inline __device__ void atomicAdd(int64_t *address, int64_t val) {
309
+ gpuAtomicAdd(address, val);
310
+ }
311
+
312
+ inline __device__ void atomicAdd(bool *address, bool val) {
313
+ gpuAtomicAdd(address, val);
314
+ }
315
+
316
+ /* Note [explicitly non-returning atomics]
317
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318
+ * AMD's MI100 (gfx908) provides an optimized fp32 atomicAdd, exposed via atomicAddNoRet().
319
+ * Due to compiler limitations, callers must opt-in to guarantee the optimized instruction.
320
+ * This non-returning atomicAddNoRet cannot be used to implement the returning atomicAdd,
321
+ * therefore we need a new API 'gpuAtomicAddNoReturn'.
322
+ */
323
+ template<typename T>
324
+ inline __device__ void gpuAtomicAddNoReturn(c10::complex<T> *address, c10::complex<T> val) { gpuAtomicAdd(address, val); }
325
+ inline __device__ void gpuAtomicAddNoReturn(uint8_t *address, uint8_t val) { gpuAtomicAdd(address, val); }
326
+ inline __device__ void gpuAtomicAddNoReturn(int8_t *address, int8_t val) { gpuAtomicAdd(address, val); }
327
+ inline __device__ void gpuAtomicAddNoReturn(int16_t *address, int16_t val) { gpuAtomicAdd(address, val); }
328
+ inline __device__ void gpuAtomicAddNoReturn(int32_t *address, int32_t val) { gpuAtomicAdd(address, val); }
329
+ inline __device__ void gpuAtomicAddNoReturn(int64_t *address, int64_t val) { gpuAtomicAdd(address, val); }
330
+ inline __device__ void gpuAtomicAddNoReturn(bool *address, bool val) { gpuAtomicAdd(address, val); }
331
+ inline __device__ void gpuAtomicAddNoReturn(at::Half *address, at::Half val) { gpuAtomicAdd(address, val); }
332
+ inline __device__ void gpuAtomicAddNoReturn(at::BFloat16 *address, at::BFloat16 val) { gpuAtomicAdd(address, val); }
333
+ inline __device__ void gpuAtomicAddNoReturn(double *address, double val) { gpuAtomicAdd(address, val); }
334
+
335
+ /* Special case fp32 atomic. */
336
+ #if defined(USE_ROCM)
337
+ inline __device__ void gpuAtomicAddNoReturn(float *address, float val) {
338
+ #if defined(__gfx908__)
339
+ atomicAddNoRet(address, val);
340
+ #else
341
+ (void)unsafeAtomicAdd(address, val);
342
+ #endif
343
+ }
344
+ #else
345
+ inline __device__ void gpuAtomicAddNoReturn(float *address, float val) { gpuAtomicAdd(address, val); }
346
+ #endif
347
+
348
+ // Atomic multiplication implementation.
349
+
350
+ ATOMIC_INTEGER_IMPL(Mul)
351
+ GPU_ATOMIC_INTEGER(Mul, a * b, uint8_t)
352
+ GPU_ATOMIC_INTEGER(Mul, a * b, int8_t)
353
+ GPU_ATOMIC_INTEGER(Mul, a * b, int16_t)
354
+ GPU_ATOMIC_INTEGER(Mul, a * b, int32_t)
355
+ GPU_ATOMIC_INTEGER(Mul, a * b, int64_t)
356
+
357
+ inline __device__ at::Half gpuAtomicMul(at::Half * address, at::Half val) {
358
+ return AtomicFPOp<at::Half>()(address, val,
359
+ [](at::Half bsum, at::Half val) {
360
+ return bsum * val;
361
+ });
362
+ }
363
+
364
+ inline __device__ at::BFloat16 gpuAtomicMul(at::BFloat16 * address, at::BFloat16 val) {
365
+ return AtomicFPOp<at::BFloat16>()(address, val,
366
+ [](at::BFloat16 bsum, at::BFloat16 val) {
367
+ return bsum * val;
368
+ });
369
+ }
370
+
371
+ inline __device__ double gpuAtomicMul(double * address, double val) {
372
+ return AtomicFPOp<double>()(address, val,
373
+ [](double val, unsigned long long int assumed) {
374
+ return __double_as_longlong(val * __longlong_as_double(assumed));
375
+ });
376
+ }
377
+
378
+ // Dont use a templated function for this since the addition function defaults to the CUDA built-in.
379
+ inline __device__ float gpuAtomicMul (float * address, float val) {
380
+ unsigned int* address_as_ull = (unsigned int*)address;
381
+ unsigned int old = *address_as_ull;
382
+ unsigned int assumed;
383
+
384
+ do {
385
+ assumed = old;
386
+ old = atomicCAS(address_as_ull, assumed,
387
+ __float_as_int(val *
388
+ __int_as_float(assumed)));
389
+
390
+ // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
391
+ } while (assumed != old);
392
+
393
+ return __int_as_float(old);
394
+ }
395
+
396
+ // Atomic maximum implementation.
397
+
398
+ template <typename T>
399
+ __host__ __device__ T safe_max(T a, T b) {
400
+ #if defined(__HIPCC__)
401
+ // TODO: remove this special case for HIP when issue is fixed:
402
+ // https://github.com/ROCm-Developer-Tools/HIP/issues/2209
403
+ T max = at::_isnan(a) ? a : (at::_isnan(b) ? b : std::max<T>(a, b));
404
+ #else
405
+ T max = at::_isnan(b) ? b : std::max<T>(a, b);
406
+ #endif
407
+
408
+ return max;
409
+ }
410
+
411
+ ATOMIC_INTEGER_IMPL(Max)
412
+ GPU_ATOMIC_INTEGER(Max, safe_max(a, b), uint8_t)
413
+ GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int8_t)
414
+ GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int16_t)
415
+ GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int32_t)
416
+ GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int64_t)
417
+
418
+ inline __device__ at::Half gpuAtomicMax(at::Half * address, at::Half val) {
419
+ return AtomicFPOp<at::Half>()(address, val,
420
+ [](at::Half bsum, at::Half val) {
421
+ return safe_max(bsum, val);
422
+ });
423
+ }
424
+
425
+ inline __device__ at::BFloat16 gpuAtomicMax(at::BFloat16 * address, at::BFloat16 val) {
426
+ return AtomicFPOp<at::BFloat16>()(address, val,
427
+ [](at::BFloat16 bsum, at::BFloat16 val) {
428
+ return safe_max(bsum, val);
429
+ });
430
+ }
431
+
432
+ inline __device__ double gpuAtomicMax(double * address, double val) {
433
+ return AtomicFPOp<double>()(address, val,
434
+ [](double val, unsigned long long int assumed) {
435
+ return __double_as_longlong(safe_max(val, __longlong_as_double(assumed)));
436
+ });
437
+ }
438
+
439
+ // Dont use a templated function for this since the addition function defaults to the CUDA built-in.
440
+ inline __device__ float gpuAtomicMax(float * address, float val) {
441
+ unsigned int* address_as_ull = (unsigned int*)address;
442
+ unsigned int old = *address_as_ull;
443
+ unsigned int assumed;
444
+
445
+ do {
446
+ assumed = old;
447
+ old = atomicCAS(address_as_ull, assumed,
448
+ __float_as_int(safe_max(val, __int_as_float(assumed))));
449
+
450
+ // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
451
+ } while (assumed != old);
452
+
453
+ return __int_as_float(old);
454
+ }
455
+
456
+ // Atomic minimum implementation.
457
+
458
+ template <typename T>
459
+ __host__ __device__ T safe_min(T a, T b) {
460
+ #if defined(__HIPCC__)
461
+ // TODO: remove this special case for HIP when issue is fixed:
462
+ // https://github.com/ROCm-Developer-Tools/HIP/issues/2209
463
+ T min = at::_isnan(a) ? a : (at::_isnan(b) ? b : std::min<T>(a, b));
464
+ #else
465
+ T min = at::_isnan(b) ? b : std::min<T>(a, b);
466
+ #endif
467
+
468
+ return min;
469
+ }
470
+
471
+ ATOMIC_INTEGER_IMPL(Min)
472
+ GPU_ATOMIC_INTEGER(Min, safe_min(a, b), uint8_t)
473
+ GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int8_t)
474
+ GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int16_t)
475
+ GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int32_t)
476
+ GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int64_t)
477
+
478
+ inline __device__ at::Half gpuAtomicMin(at::Half * address, at::Half val) {
479
+ return AtomicFPOp<at::Half>()(address, val,
480
+ [](at::Half bsum, at::Half val) {
481
+ return safe_min(bsum, val);
482
+ });
483
+ }
484
+
485
+ inline __device__ at::BFloat16 gpuAtomicMin(at::BFloat16 * address, at::BFloat16 val) {
486
+ return AtomicFPOp<at::BFloat16>()(address, val,
487
+ [](at::BFloat16 bsum, at::BFloat16 val) {
488
+ return safe_min(bsum, val);
489
+ });
490
+ }
491
+
492
+ inline __device__ double gpuAtomicMin(double * address, double val) {
493
+ return AtomicFPOp<double>()(address, val,
494
+ [](double val, unsigned long long int assumed) {
495
+ return __double_as_longlong(safe_min(val, __longlong_as_double(assumed)));
496
+ });
497
+ }
498
+
499
+ // Dont use a templated function for this since the addition function defaults to the CUDA built-in.
500
+ inline __device__ float gpuAtomicMin(float * address, float val) {
501
+ unsigned int* address_as_ull = (unsigned int*)address;
502
+ unsigned int old = *address_as_ull;
503
+ unsigned int assumed;
504
+
505
+ do {
506
+ assumed = old;
507
+ old = atomicCAS(address_as_ull, assumed,
508
+ __float_as_int(safe_min(val, __int_as_float(assumed))));
509
+
510
+ // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
511
+ } while (assumed != old);
512
+
513
+ return __int_as_float(old);
514
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAApplyUtils.cuh ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/ApplyGridUtils.cuh>
4
+ #include <ATen/cuda/detail/IndexUtils.cuh>
5
+ #include <ATen/core/TensorBase.h>
6
+ #include <ATen/ceil_div.h>
7
+ #include <ATen/cuda/Atomic.cuh>
8
+ #include <ATen/cuda/CUDAContext.h>
9
+ #include <c10/macros/Macros.h>
10
+ #include <ATen/native/Copy.h>
11
+
12
+ #include <math.h>
13
+
14
+ //
15
+ // This file contains pointwise operation functions and kernels that
16
+ // work on both contiguous and non-contiguous tensor arguments of
17
+ // arbitrary (up to MAX_CUTORCH_DIMS) dimensioned arguments without
18
+ // copying or temporary storage.
19
+ //
20
+
21
+ /*
22
+ NOTE [ CUDA_tensor_applyN helpers ]
23
+
24
+ The following CUDA_tensor_applyN (where N currently can be 1, 2, 3, or 4)
25
+ functions apply a pointwise operator to N tensor(s).
26
+
27
+ The calling convention is
28
+
29
+ 1. The template arguments should be, sequentially,
30
+ - First N typename args specify the scalar types of each of the N tensors.
31
+ - (Optional) `int step` arg specifies the number of elements processed
32
+ together at the same time.
33
+ Default is 1.
34
+ - A usually omitted (i.e., inferred) typename arg specifies the type of the
35
+ function/functor applied on `N * step` values in each iteration of each
36
+ CUDA thread.
37
+ 2. The arguments should be, sequentially,
38
+ - N tensors
39
+ - op: a function/functor that processes `N * step` values at the same time.
40
+ - If `step == 1`, it must have signature
41
+ `void(*)(scalar1_t&, scalar2_t&, ..., scalarN_t&)`, where
42
+ `scalar*_t`s are the first N typename template args, and the inputs
43
+ are the `N` values from the `N` tensors retrieved at a common index.
44
+ - Otherwise, it must must have signature
45
+ void(*)(int n, scalar1_t&, scalar1_t&, ..., scalar1_t&, // repeat `step` times
46
+ scalar2_t&, scalar2_t&, ..., scalar2_t&, // repeat `step` times
47
+ ...,
48
+ scalarN_t&, scalarN_t&, ..., scalarN_t&) // repeat `step` times
49
+ Different from `step == 1` case, it processes `N * step` values taken
50
+ from `step` common indices. Moreover, the first input `n` represents the
51
+ number of valid indices (it will always have `0 < n <= step`). It will
52
+ almost always be `step`, but at the boundary we may not have full `step`
53
+ elements and `n` can be a lesser value.
54
+
55
+ E.g., if `step == 4` and `N == 2`, `op` could be
56
+
57
+ [](int n, scalar1_t &u1, scalar1_t &u2, scalar1_t &u3, scalar1_t &u4,
58
+ scalar2_t &v1, scalar2_t &v2, scalar2_t &v3, scalar2_t &v4) {
59
+ // Only process u1, ..., un and v1, ..., vn.
60
+ // So if `n == 3`, `u4` and `v4` need not to be considered.
61
+ }
62
+
63
+ In both cases, the references can actually be const, but at least one of
64
+ them should be non-const in order to write the output.
65
+ - (Optional, but recommended) N TensorArgType args that specify for each
66
+ tensor whether `op` reads AND writes ] (i.e., TensorArgType::ReadWrite),
67
+ or only reads (i.e., TensorArgType::ReadOnly).
68
+ Default is TensorArgType::ReadWrite for first Tensor, and
69
+ TensorArgType::ReadOnly for the rest.
70
+
71
+ E.g.,
72
+
73
+ to compute a = b^2 for a and b of same dtype, we can call
74
+
75
+ CUDA_tensor_apply2<scalar, scalar>(
76
+ a, b,
77
+ [] __device__ (scalar &a_val, const scalar &b_val) { a_val = b_val * b_val; }
78
+ );
79
+
80
+ to work on 2 values at the same time, we can call
81
+
82
+ CUDA_tensor_apply2<scalar1, scalar2, 2>(
83
+ a, b,
84
+ [] __device__ (int n, scalar1 &a_val1, scalar1 &a_val2,
85
+ const scalar2 &b_val1, const scalar2 &b_val2) {
86
+ // call special vectorized op here, or just do elementwise and enjoy unrolling...
87
+ // if n == 1, only process a_val1 and b_val1
88
+ }
89
+ );
90
+ */
91
+
92
+ namespace at::cuda {
93
+
94
+ // TODO: combine with TensorArg? So far that's been for debugging, and this is functional...
95
+ enum class TensorArgType { ReadWrite, ReadOnly };
96
+
97
+ namespace {
98
+
99
+ // Rearrange dimensions for pointwise operations so that strides are in
100
+ // decreasing order as much as possible, so that kernels have better memory
101
+ // access patterns.
102
+ //
103
+ // For example, consider a binary operation on two "transposed" 2-dim tensors:
104
+ // sizes: 256 512
105
+ // aInfo->strides: 1 256
106
+ // bInfo->strides: 1 256
107
+ //
108
+ // Given this, each concurrent memory access inside kernelPointwiseApply2() is
109
+ // exactly 256 elements apart, resulting in poor performance.
110
+ //
111
+ // This function exchanges dimensions so that memory access is contiguous:
112
+ // sizes: 512 256
113
+ // aInfo->strides: 256 1
114
+ // bInfo->strides: 256 1
115
+ //
116
+ // (Actually, it becomes even better because now collapseDims() can turn each
117
+ // input into one contiguous array.)
118
+ //
119
+ // In general, given M (<=4) TensorInfo's with N dimensions, we can view each
120
+ // strides[i] (0 <= i < N) as an M-tuple. Given each pair i < j, we exchange
121
+ // strides[i] and [j] if
122
+ // (1) strides[i][k] < strides[j][k] for some k (0 <= k < M)
123
+ // (exchanging them will benefit input #k), and
124
+ // (2) strides[i][k] <= strieds[j][k] for all k
125
+ // (exchanging them will not make any input worse).
126
+ template <typename T1, typename IndexType,
127
+ typename T2 = void, typename T3 = void, typename T4 = void>
128
+ inline void rearrangeDims(detail::TensorInfo<T1, IndexType>* aInfo,
129
+ detail::TensorInfo<T2, IndexType>* bInfo = nullptr,
130
+ detail::TensorInfo<T3, IndexType>* cInfo = nullptr,
131
+ detail::TensorInfo<T4, IndexType>* dInfo = nullptr) {
132
+ int numInfos = 1;
133
+ int dims = aInfo->dims;
134
+ IndexType *sizes[4] = { aInfo->sizes, };
135
+ IndexType *strides[4] = { aInfo->strides, };
136
+
137
+ if (bInfo != nullptr) {
138
+ ++numInfos;
139
+ if (bInfo->dims != dims) return;
140
+ sizes[1] = bInfo->sizes;
141
+ strides[1] = bInfo->strides;
142
+ }
143
+
144
+ if (cInfo != nullptr) {
145
+ ++numInfos;
146
+ if (cInfo->dims != dims) return;
147
+ sizes[2] = cInfo->sizes;
148
+ strides[2] = cInfo->strides;
149
+ }
150
+
151
+ if (dInfo != nullptr) {
152
+ ++numInfos;
153
+ if (dInfo->dims != dims) return;
154
+ sizes[3] = dInfo->sizes;
155
+ strides[3] = dInfo->strides;
156
+ }
157
+
158
+ // Bail out if sizes do not match: we are using "deprecated pointwise
159
+ // behavior" among tensors of different shapes but same number of elements.
160
+ for (int i = 1; i < numInfos; ++i) {
161
+ for (int j = 0; j < dims; ++j) {
162
+ if (sizes[i][j] != sizes[0][j]) return;
163
+ }
164
+ }
165
+
166
+ for (int i = 0; i < dims - 1; ++i) {
167
+ // No need to consider dimensions of size 1.
168
+ if (sizes[0][i] == 1) continue;
169
+
170
+ for (int j = i + 1; j < dims; ++j) {
171
+ if (sizes[0][j] == 1) continue;
172
+
173
+ // Compare the relative sizes of strides between dim #i and dim #j.
174
+ bool hasIncreasingStrides = false;
175
+ bool hasDecreasingStrides = false;
176
+
177
+ for (int k = 0; k < numInfos; k++) {
178
+ IndexType stride_i = strides[k][i];
179
+ IndexType stride_j = strides[k][j];
180
+ if (stride_i < stride_j) {
181
+ hasIncreasingStrides = true;
182
+ } else if (stride_i > stride_j) {
183
+ hasDecreasingStrides = true;
184
+ }
185
+ }
186
+
187
+ if (hasIncreasingStrides && !hasDecreasingStrides) {
188
+ for (int k = 0; k < numInfos; k++) {
189
+ IndexType size = sizes[k][i];
190
+ sizes[k][i] = sizes[k][j];
191
+ sizes[k][j] = size;
192
+
193
+ IndexType stride = strides[k][i];
194
+ strides[k][i] = strides[k][j];
195
+ strides[k][j] = stride;
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+
202
+ // The `remaining_steps` argument is used to support Op that operates on
203
+ // multiple elements at the same time. Generally, the strategy of ApplyOpN is to
204
+ // 1. Initialize `remaining_steps = step`, where `step` is the template arg of
205
+ // CUDA_tensor_applyN helpers. The input arg `n` to `apply()` represents the
206
+ // number of elements in bound for this call. It will almost always equal to
207
+ // `step` except at boundaries.
208
+ // 2. If `remaining_steps > 0` convert the current linearIndex to offset (if in
209
+ // bound), and recursively call `ApplyOpN` with `remaining_steps - 1`.
210
+ // 3. At `remaining_steps = 0`,
211
+ // if `step = 1`, call `op(tensor1_val, tensor2_val, ...)`;
212
+ // if `step > 1`, call `op(n, tensor1_val1, tensor1_val2, ..., tesor1_valstep,
213
+ // tensor2_val1, tensor2_val2, ..., tesor2_valstep,
214
+ // ...
215
+ // tensorN_val1, tensorN_val2, ..., tesorN_valstep);`
216
+ //
217
+ // See NOTE [ CUDA_tensor_applyN helpers ] above for how Op may look like.
218
+
219
+ template <typename Op,
220
+ typename scalar,
221
+ typename IndexType,
222
+ int ADims,
223
+ int remaining_steps,
224
+ typename... Offsets>
225
+ struct ApplyOp1 {
226
+ __device__ __forceinline__
227
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
228
+ IndexType linearIndex, Offsets... aOffsets) {
229
+ // Convert `linearIndex` into an offset of `a`
230
+ const IndexType aOffset = sizeof...(Offsets) < n ?
231
+ detail::IndexToOffset<scalar, IndexType, ADims>::get(linearIndex, a) : 0;
232
+
233
+ ApplyOp1<Op, scalar, IndexType, ADims, remaining_steps - 1, const IndexType, Offsets...>::apply(
234
+ a, op, n, linearIndex + 1, aOffsets..., aOffset
235
+ );
236
+ }
237
+ };
238
+
239
+ // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
240
+ // We don't need to pass in how many elements need to processed in this case.
241
+ template <typename Op,
242
+ typename scalar,
243
+ typename IndexType,
244
+ int ADims,
245
+ typename Offset>
246
+ struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offset> {
247
+ __device__ __forceinline__
248
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op,
249
+ int n, IndexType linearIndex, Offset offset) {
250
+ op(a.data[offset]);
251
+ }
252
+ };
253
+
254
+ template <typename Op,
255
+ typename scalar,
256
+ typename IndexType,
257
+ int ADims,
258
+ typename... Offsets>
259
+ struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offsets...> {
260
+ __device__ __forceinline__
261
+ static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
262
+ IndexType linearIndex, Offsets... offsets) {
263
+ op(n, a.data[offsets]...);
264
+ }
265
+ };
266
+
267
+ template <typename Op,
268
+ typename scalar,
269
+ typename IndexType,
270
+ int ADims,
271
+ int step>
272
+ #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
273
+ C10_LAUNCH_BOUNDS_2(AT_APPLY_THREADS_PER_BLOCK, AT_APPLY_BLOCKS_PER_SM)
274
+ #endif
275
+ __global__ void kernelPointwiseApply1(detail::TensorInfo<scalar, IndexType> a,
276
+ IndexType totalElements, const Op op) {
277
+ for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
278
+ linearIndex < totalElements;
279
+ linearIndex += gridDim.x * blockDim.x * step) {
280
+ ApplyOp1<Op, scalar, IndexType, ADims, step>::apply(
281
+ a, op, ::min(step, static_cast<int>(totalElements - linearIndex)), linearIndex);
282
+ }
283
+ }
284
+
285
+
286
+ template <typename Op,
287
+ typename scalar1,
288
+ typename scalar2,
289
+ typename IndexType,
290
+ int ADims,
291
+ int BDims,
292
+ int remaining_steps,
293
+ typename... Offsets>
294
+ struct ApplyOp2 {
295
+ __device__ __forceinline__
296
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
297
+ detail::TensorInfo<scalar2, IndexType> &b,
298
+ const Op &op, int64_t n, IndexType linearIndex,
299
+ Offsets... aOffsets, Offsets... bOffsets) {
300
+ // Convert `linearIndex` into an offset of `a`
301
+ const IndexType aOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
302
+ detail::IndexToOffset<scalar1, IndexType, ADims>::get(linearIndex, a) : 0;
303
+
304
+ // Convert `linearIndex` into an offset of `b`
305
+ const IndexType bOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
306
+ detail::IndexToOffset<scalar2, IndexType, BDims>::get(linearIndex, b) : 0;
307
+
308
+ ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, remaining_steps - 1, const IndexType, Offsets...>::apply(
309
+ a, b, op, n, linearIndex + 1, aOffsets..., aOffset, bOffsets..., bOffset
310
+ );
311
+ }
312
+ };
313
+
314
+ // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
315
+ // We don't need to pass in how many elements need to processed in this case.
316
+ template <typename Op,
317
+ typename scalar1,
318
+ typename scalar2,
319
+ typename IndexType,
320
+ int ADims,
321
+ int BDims,
322
+ typename Offset>
323
+ struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offset> {
324
+ __device__ __forceinline__
325
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
326
+ detail::TensorInfo<scalar2, IndexType> &b,
327
+ const Op &op, int /*n*/, IndexType /*linearIndex*/,
328
+ Offset aOffset, Offset bOffset) {
329
+ op(a.data[aOffset], b.data[bOffset]);
330
+ }
331
+ };
332
+
333
+ template <typename Op,
334
+ typename scalar1,
335
+ typename scalar2,
336
+ typename IndexType,
337
+ int ADims,
338
+ int BDims,
339
+ typename... Offsets>
340
+ struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offsets...> {
341
+ __device__ __forceinline__
342
+ static void apply(detail::TensorInfo<scalar1, IndexType> &a,
343
+ detail::TensorInfo<scalar2, IndexType> &b,
344
+ const Op &op, int n, IndexType linearIndex,
345
+ Offsets... aOffsets, Offsets... bOffsets) {
346
+ op(n, a.data[aOffsets]..., b.data[bOffsets]...);
347
+ }
348
+ };
349
+
350
+ template <typename Op,
351
+ typename scalar1,
352
+ typename scalar2,
353
+ typename IndexType,
354
+ int ADims, int BDims,
355
+ int step,
356
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
357
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
358
+ #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
359
+ C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm)
360
+ #endif
361
+ __global__ void
362
+ kernelPointwiseApply2(detail::TensorInfo<scalar1, IndexType> a,
363
+ detail::TensorInfo<scalar2, IndexType> b,
364
+ IndexType totalElements,
365
+ const Op op) {
366
+ for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
367
+ linearIndex < totalElements;
368
+ linearIndex += gridDim.x * blockDim.x * step) {
369
+ ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, step>::apply(
370
+ a, b, op, ::min(step, static_cast<int>(totalElements - linearIndex)),
371
+ linearIndex);
372
+ }
373
+ }
374
+
375
+ } // anonymous namespace
376
+
377
+ template <typename scalar1, typename scalar2, int step, typename Op,
378
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
379
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
380
+ inline bool CUDA_tensor_apply2(at::TensorBase a,
381
+ at::TensorBase b,
382
+ const Op op,
383
+ TensorArgType aType = TensorArgType::ReadWrite,
384
+ TensorArgType bType = TensorArgType::ReadOnly) {
385
+ TORCH_CHECK(a.device().is_cuda() && b.device().is_cuda(),
386
+ "CUDA_tensor_apply2: Expected tensors to have CUDA DeviceType, but got "
387
+ "tensors with type ", a.device().type(), " and ", b.device().type());
388
+ int64_t totalElements = a.numel();
389
+
390
+ if (totalElements != b.numel()) {
391
+ return false;
392
+ }
393
+
394
+ if (a.dim() > MAX_TENSORINFO_DIMS ||
395
+ b.dim() > MAX_TENSORINFO_DIMS) {
396
+ return false;
397
+ }
398
+
399
+ if (a.numel() == 0) {
400
+ // Empty tensor; do nothing
401
+ return true;
402
+ }
403
+ const dim3 block = getApplyBlock(max_threads_per_block);
404
+
405
+ dim3 grid;
406
+ auto curDevice = current_device();
407
+ if (curDevice == -1) return false;
408
+ if (!getApplyGrid<step>(totalElements, grid, curDevice, max_threads_per_block)) {
409
+ return false;
410
+ }
411
+
412
+ /*
413
+ Expands readable/writable tensors whose indices may be "overlapped."
414
+ This ensures that each element of the tensor is operated on once and only
415
+ once.
416
+ */
417
+ TensorBase oldA;
418
+ TensorBase oldB;
419
+
420
+ if (aType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(a)) {
421
+ // Must perform in contiguous space
422
+ oldA = std::exchange(a, a.contiguous());
423
+ }
424
+ if (bType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(b)) {
425
+ // Must perform in contiguous space
426
+ oldB = std::exchange(b, b.contiguous());
427
+ }
428
+
429
+ // It is possible that the tensor dimensions are able to be collapsed,
430
+ // and thus we can reduce the actual code complexity of the copy by
431
+ // exploiting this knowledge statically, since the div/mod is the
432
+ // most expensive part of the operation, more so than memory accesses.
433
+ // For instance, when copying a non-contiguous to a contiguous tensor
434
+ // (or vice versa), the contiguous tensor can be collapsed to one
435
+ // dimension, and the loop to translate the linear index to the array
436
+ // index can be similarly collapsed. That is what this unrolling is for.
437
+
438
+ #define HANDLE_CASE(TYPE, A, B) \
439
+ kernelPointwiseApply2<Op, \
440
+ scalar1, \
441
+ scalar2, \
442
+ TYPE, A, B, step, \
443
+ max_threads_per_block, \
444
+ min_blocks_per_sm> \
445
+ <<<grid, block, 0, at::cuda::getCurrentCUDAStream(curDevice)>>>( \
446
+ aInfo, bInfo, static_cast<TYPE>(totalElements), op); \
447
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
448
+
449
+ #define HANDLE_B_CASE(TYPE, A, B) { \
450
+ switch (B) { \
451
+ case 1: \
452
+ HANDLE_CASE(TYPE, A, 1); \
453
+ break; \
454
+ case 2: \
455
+ HANDLE_CASE(TYPE, A, 2); \
456
+ break; \
457
+ default: \
458
+ HANDLE_CASE(TYPE, A, -1); \
459
+ break; \
460
+ } \
461
+ }
462
+
463
+ #define HANDLE_A_CASE(TYPE, A, B) { \
464
+ switch (A) { \
465
+ case 1: \
466
+ HANDLE_B_CASE(TYPE, 1, B); \
467
+ break; \
468
+ case 2: \
469
+ HANDLE_B_CASE(TYPE, 2, B); \
470
+ break; \
471
+ default: \
472
+ HANDLE_B_CASE(TYPE, -1, B); \
473
+ break; \
474
+ } \
475
+ }
476
+
477
+ if (detail::canUse32BitIndexMath(a) &&
478
+ detail::canUse32BitIndexMath(b)) {
479
+ detail::TensorInfo<scalar1, unsigned int> aInfo =
480
+ detail::getTensorInfo<scalar1, unsigned int>(a);
481
+
482
+ detail::TensorInfo<scalar2, unsigned int> bInfo =
483
+ detail::getTensorInfo<scalar2, unsigned int>(b);
484
+ rearrangeDims(&aInfo, &bInfo);
485
+ aInfo.collapseDims();
486
+ bInfo.collapseDims();
487
+
488
+ HANDLE_A_CASE(unsigned int, aInfo.dims, bInfo.dims);
489
+ } else {
490
+ detail::TensorInfo<scalar1, uint64_t> aInfo =
491
+ detail::getTensorInfo<scalar1, uint64_t>(a);
492
+
493
+ detail::TensorInfo<scalar2, uint64_t> bInfo =
494
+ detail::getTensorInfo<scalar2, uint64_t>(b);
495
+ rearrangeDims(&aInfo, &bInfo);
496
+ aInfo.collapseDims();
497
+ bInfo.collapseDims();
498
+
499
+ /*
500
+ Only instantiates the all 1D special case and the fallback all nD case for
501
+ large (64-bit indexed) tensors to reduce compilation time.
502
+ */
503
+ if (aInfo.dims == 1 && bInfo.dims == 1) {
504
+ HANDLE_CASE(uint64_t, 1, 1);
505
+ } else {
506
+ HANDLE_CASE(uint64_t, -1, -1);
507
+ }
508
+ }
509
+ #undef HANDLE_CASE
510
+ #undef HANDLE_B_CASE
511
+ #undef HANDLE_A_CASE
512
+
513
+ if (oldA.defined()) {
514
+ at::native::copy_ignoring_overlaps(oldA, a);
515
+ }
516
+
517
+ if (oldB.defined()) {
518
+ at::native::copy_ignoring_overlaps(oldB, b);
519
+ }
520
+
521
+ return true;
522
+ }
523
+
524
+ /* Provides default step = 1 to CUDA_tensor_apply2. */
525
+ template <typename scalar1, typename scalar2, typename Op,
526
+ int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
527
+ int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
528
+ inline bool CUDA_tensor_apply2(const at::TensorBase &a,
529
+ const at::TensorBase &b,
530
+ const Op op,
531
+ TensorArgType aType = TensorArgType::ReadWrite,
532
+ TensorArgType bType = TensorArgType::ReadOnly) {
533
+ return CUDA_tensor_apply2<scalar1, scalar2, 1, Op,
534
+ max_threads_per_block, min_blocks_per_sm>(a, b, op, aType, bType);
535
+ }
536
+
537
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDABlas.h ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ /*
3
+ Provides a subset of CUDA BLAS functions as templates:
4
+
5
+ gemm<Dtype>(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c,
6
+ ldc)
7
+
8
+ gemv<Dtype>(transa, m, n, alpha, a, lda, x, incx, beta, y, incy)
9
+
10
+ dot<Dtype>(n, x, incx, y, incy, result)
11
+
12
+ where Dtype is double, float, at::Half or at::BFloat16 (ROCm, NOT for dot).
13
+ The functions are available in at::cuda::blas namespace.
14
+ */
15
+
16
+ #include <ATen/cuda/CUDAContext.h>
17
+ #include <ATen/OpMathType.h>
18
+
19
+ namespace at::cuda::blas {
20
+
21
+ // RAII guard that sets the CuBLAS pointer mode and restores it to
22
+ // its previous value when the guard is destroyed
23
+ class PointerModeGuard {
24
+ public:
25
+ PointerModeGuard(cublasHandle_t handle, cublasPointerMode_t mode) :
26
+ handle(handle) {
27
+ TORCH_CUDABLAS_CHECK(cublasGetPointerMode(handle, &previous_mode));
28
+ TORCH_CUDABLAS_CHECK(cublasSetPointerMode(handle, mode));
29
+ }
30
+
31
+ ~PointerModeGuard() {
32
+ cublasSetPointerMode(handle, previous_mode);
33
+ }
34
+
35
+ private:
36
+ cublasHandle_t handle;
37
+ cublasPointerMode_t previous_mode{};
38
+ };
39
+
40
+ /* LEVEL 3 BLAS FUNCTIONS */
41
+
42
+ #define CUDABLAS_GEMM_ARGTYPES(Dtype) \
43
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
44
+ const Dtype *a, int64_t lda, const Dtype *b, int64_t ldb, at::opmath_type<Dtype> beta,\
45
+ Dtype *c, int64_t ldc
46
+
47
+ #define CUDABLAS_GEMM_ARGS(Dtype) transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc
48
+
49
+ template <typename Dtype>
50
+ inline void gemm(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
51
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm: not implemented");
52
+ }
53
+
54
+ template <>
55
+ void gemm<double>(CUDABLAS_GEMM_ARGTYPES(double));
56
+ template <>
57
+ void gemm<float>(CUDABLAS_GEMM_ARGTYPES(float));
58
+ template <>
59
+ void gemm<c10::complex<double>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<double>));
60
+ template <>
61
+ void gemm<c10::complex<float>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<float>));
62
+ template <>
63
+ void gemm<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
64
+ template <>
65
+ void gemm<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
66
+
67
+ template <typename Dtype>
68
+ inline void gemm_internal(CUDABLAS_GEMM_ARGTYPES(Dtype)) {
69
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm_internal: not implemented");
70
+ }
71
+
72
+ template <>
73
+ void gemm_internal<double>(CUDABLAS_GEMM_ARGTYPES(double));
74
+ template <>
75
+ void gemm_internal<float>(CUDABLAS_GEMM_ARGTYPES(float));
76
+ template <>
77
+ void gemm_internal<c10::complex<double>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<double>));
78
+ template <>
79
+ void gemm_internal<c10::complex<float>>(CUDABLAS_GEMM_ARGTYPES(c10::complex<float>));
80
+ template <>
81
+ void gemm_internal<at::Half>(CUDABLAS_GEMM_ARGTYPES(at::Half));
82
+ template <>
83
+ void gemm_internal<at::BFloat16>(CUDABLAS_GEMM_ARGTYPES(at::BFloat16));
84
+
85
+ enum GEMMAndBiasActivationEpilogue {
86
+ None,
87
+ RELU,
88
+ GELU,
89
+ };
90
+
91
+ // NOTE: GELU activation is not supported prior to CUDA 11.4 and will
92
+ // do nothing if passed in that case.
93
+ template <typename Dtype>
94
+ void gemm_and_bias(
95
+ bool transpose_mat1,
96
+ bool transpose_mat2,
97
+ int64_t m,
98
+ int64_t n,
99
+ int64_t k,
100
+ at::opmath_type<Dtype> alpha_val,
101
+ const Dtype* mat1_ptr,
102
+ int64_t mat1_ld,
103
+ const Dtype* mat2_ptr,
104
+ int64_t mat2_ld,
105
+ const Dtype* bias,
106
+ Dtype* result_ptr,
107
+ int64_t result_ld,
108
+ GEMMAndBiasActivationEpilogue activation = GEMMAndBiasActivationEpilogue::None);
109
+
110
+ void int8_gemm(
111
+ bool transpose_mat1,
112
+ bool transpose_mat2,
113
+ int64_t m,
114
+ int64_t n,
115
+ int64_t k,
116
+ const int8_t* mat1_ptr,
117
+ int64_t mat1_ld,
118
+ const int8_t* mat2_ptr,
119
+ int64_t mat2_ld,
120
+ int32_t* result_ptr,
121
+ int64_t result_ld);
122
+
123
+ void scaled_gemm(
124
+ char transa,
125
+ char transb,
126
+ int64_t m,
127
+ int64_t n,
128
+ int64_t k,
129
+ const void* mat1_ptr,
130
+ const void* mat1_scale_ptr,
131
+ int64_t mat1_ld,
132
+ ScalarType mat1_dtype,
133
+ ScalarType mat1_scale_dtype,
134
+ const void* mat2_ptr,
135
+ const void* mat2_scale_ptr,
136
+ int64_t mat2_ld,
137
+ ScalarType mat2_dtype,
138
+ ScalarType mat2_scale_dtype,
139
+ const void* bias_ptr,
140
+ ScalarType bias_dtype,
141
+ void* result_ptr,
142
+ const void* result_scale_ptr,
143
+ int64_t result_ld,
144
+ ScalarType result_dtype,
145
+ bool use_fast_accum,
146
+ bool use_rowwise);
147
+
148
+ #define CUDABLAS_BGEMM_ARGTYPES(Dtype) \
149
+ char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type<Dtype> alpha, \
150
+ const Dtype *a, int64_t lda, int64_t stridea, \
151
+ const Dtype *b, int64_t ldb, int64_t strideb, \
152
+ at::opmath_type<Dtype> beta, Dtype *c, int64_t ldc, int64_t stridec, int64_t num_batches
153
+
154
+ #define CUDABLAS_BGEMM_ARGS(Dtype) \
155
+ transa, transb, m, n, k, alpha, a, lda, stridea, b, ldb, strideb, beta, c, ldc, stridec, num_batches
156
+
157
+ template <typename Dtype>
158
+ inline void bgemm(CUDABLAS_BGEMM_ARGTYPES(Dtype)) {
159
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm: not implemented");
160
+ }
161
+
162
+ template <>
163
+ void bgemm<double>(CUDABLAS_BGEMM_ARGTYPES(double));
164
+ template <>
165
+ void bgemm<float>(CUDABLAS_BGEMM_ARGTYPES(float));
166
+ template <>
167
+ void bgemm<c10::complex<double>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<double>));
168
+ template <>
169
+ void bgemm<c10::complex<float>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<float>));
170
+ template <>
171
+ void bgemm<at::Half>(CUDABLAS_BGEMM_ARGTYPES(at::Half));
172
+ template <>
173
+ void bgemm<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
174
+
175
+ template <typename Dtype>
176
+ inline void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(Dtype)) {
177
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm_internal: not implemented");
178
+ }
179
+
180
+ template <>
181
+ void bgemm_internal<double>(CUDABLAS_BGEMM_ARGTYPES(double));
182
+ template <>
183
+ void bgemm_internal<float>(CUDABLAS_BGEMM_ARGTYPES(float));
184
+ template <>
185
+ void bgemm_internal<c10::complex<double>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<double>));
186
+ template <>
187
+ void bgemm_internal<c10::complex<float>>(CUDABLAS_BGEMM_ARGTYPES(c10::complex<float>));
188
+ template <>
189
+ void bgemm_internal<at::Half>(CUDABLAS_BGEMM_ARGTYPES(at::Half));
190
+ template <>
191
+ void bgemm_internal<at::BFloat16>(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16));
192
+
193
+ #define CUDABLAS_TRSM_ARGTYPES(Dtype) \
194
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
195
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
196
+ const Dtype *alpha, const Dtype *A, int lda, Dtype *B, int ldb
197
+
198
+ template <typename Dtype>
199
+ inline void trsm(CUDABLAS_TRSM_ARGTYPES(Dtype)) {
200
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsm: not implemented");
201
+ }
202
+
203
+ template <>
204
+ TORCH_CUDA_CU_API void trsm<float>(CUDABLAS_TRSM_ARGTYPES(float));
205
+ template <>
206
+ TORCH_CUDA_CU_API void trsm<double>(CUDABLAS_TRSM_ARGTYPES(double));
207
+ template <>
208
+ TORCH_CUDA_CU_API void trsm<c10::complex<float>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<float>));
209
+ template <>
210
+ TORCH_CUDA_CU_API void trsm<c10::complex<double>>(CUDABLAS_TRSM_ARGTYPES(c10::complex<double>));
211
+
212
+ #define CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype) \
213
+ cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \
214
+ cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \
215
+ const Dtype *alpha, Dtype *A[], int lda, Dtype *B[], int ldb, \
216
+ int batchCount
217
+
218
+ template <typename Dtype>
219
+ inline void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype)) {
220
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsmBatched: not implemented");
221
+ }
222
+
223
+ template <>
224
+ TORCH_CUDA_CU_API void trsmBatched<float>(CUDABLAS_TRSM_BATCHED_ARGTYPES(float));
225
+ template <>
226
+ TORCH_CUDA_CU_API void trsmBatched<double>(CUDABLAS_TRSM_BATCHED_ARGTYPES(double));
227
+ template <>
228
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<float>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<float>));
229
+ template <>
230
+ TORCH_CUDA_CU_API void trsmBatched<c10::complex<double>>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex<double>));
231
+
232
+ /* LEVEL 2 BLAS FUNCTIONS */
233
+
234
+ #define CUDABLAS_GEMV_ARGTYPES(Dtype) \
235
+ char trans, int64_t m, int64_t n, Dtype alpha, const Dtype *a, int64_t lda, \
236
+ const Dtype *x, int64_t incx, Dtype beta, Dtype *y, int64_t incy
237
+
238
+ template <typename Dtype>
239
+ inline void gemv(CUDABLAS_GEMV_ARGTYPES(Dtype)) {
240
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::gemv: not implemented");
241
+ }
242
+
243
+ template <>
244
+ void gemv<double>(CUDABLAS_GEMV_ARGTYPES(double));
245
+ template <>
246
+ void gemv<float>(CUDABLAS_GEMV_ARGTYPES(float));
247
+ template <>
248
+ void gemv<c10::complex<double>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<double>));
249
+ template <>
250
+ void gemv<c10::complex<float>>(CUDABLAS_GEMV_ARGTYPES(c10::complex<float>));
251
+ template <>
252
+ void gemv<at::Half>(CUDABLAS_GEMV_ARGTYPES(at::Half));
253
+ template <>
254
+ void gemv<at::BFloat16>(CUDABLAS_GEMV_ARGTYPES(at::BFloat16));
255
+
256
+ /* LEVEL 1 BLAS FUNCTIONS */
257
+
258
+ #define CUDABLAS_DOT_ARGTYPES(Dtype) \
259
+ cublasHandle_t handle, int n, const Dtype *x, int incx, const Dtype *y, \
260
+ int incy, Dtype *result
261
+
262
+ template <typename Dtype>
263
+ inline void dot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
264
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::dot: not implemented");
265
+ }
266
+
267
+ template <>
268
+ void dot<double>(CUDABLAS_DOT_ARGTYPES(double));
269
+ template <>
270
+ void dot<float>(CUDABLAS_DOT_ARGTYPES(float));
271
+ template <>
272
+ void dot<at::Half>(CUDABLAS_DOT_ARGTYPES(at::Half));
273
+ template <>
274
+ void dot<at::BFloat16>(CUDABLAS_DOT_ARGTYPES(at::BFloat16));
275
+ template <>
276
+ void dot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
277
+ template <>
278
+ void dot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
279
+
280
+ template <typename Dtype>
281
+ inline void vdot(CUDABLAS_DOT_ARGTYPES(Dtype)) {
282
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::vdot: not implemented");
283
+ }
284
+
285
+ template <>
286
+ void vdot<c10::complex<float>>(CUDABLAS_DOT_ARGTYPES(c10::complex<float>));
287
+ template <>
288
+ void vdot<c10::complex<double>>(CUDABLAS_DOT_ARGTYPES(c10::complex<double>));
289
+
290
+ #define CUDABLAS_GETRS_ARGTYPES(Dtype) \
291
+ cublasHandle_t handle, cublasOperation_t trans, \
292
+ int n, int nrhs, Dtype** dA_array, int lda, int* ipiv_array, \
293
+ Dtype** dB_array, int ldb, int* info_array, int batchsize
294
+
295
+ template<class Dtype>
296
+ void getrsBatched(CUDABLAS_GETRS_ARGTYPES(Dtype)) {
297
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::getrsBatched: not implemented");
298
+ }
299
+ template<>
300
+ TORCH_CUDA_CU_API void getrsBatched<float>(CUDABLAS_GETRS_ARGTYPES(float));
301
+ template<>
302
+ TORCH_CUDA_CU_API void getrsBatched<double>(CUDABLAS_GETRS_ARGTYPES(double));
303
+ template<>
304
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<float>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<float>));
305
+ template<>
306
+ TORCH_CUDA_CU_API void getrsBatched<c10::complex<double>>(CUDABLAS_GETRS_ARGTYPES(c10::complex<double>));
307
+
308
+ #define CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype) \
309
+ cublasHandle_t handle, int m, int n, Dtype **A_array, int lda, \
310
+ Dtype **tau_array, int *info, int batchsize
311
+
312
+ template <class Dtype>
313
+ void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype)) {
314
+ static_assert(false&&sizeof(Dtype), "at::cuda::blas::geqrfBatched: not implemented");
315
+ }
316
+ template <>
317
+ TORCH_CUDA_CU_API void geqrfBatched<float>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(float));
318
+ template <>
319
+ TORCH_CUDA_CU_API void geqrfBatched<double>(CUDABLAS_GEQRF_BATCHED_ARGTYPES(double));
320
+ template <>
321
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<double>>(
322
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<double>));
323
+ template <>
324
+ TORCH_CUDA_CU_API void geqrfBatched<c10::complex<float>>(
325
+ CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex<float>));
326
+
327
+ #define CUDABLAS_GETRF_ARGTYPES(Dtype) \
328
+ int n, Dtype** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize
329
+
330
+ template<class Dtype>
331
+ void getrfBatched(CUDABLAS_GETRF_ARGTYPES(Dtype)) {
332
+ TORCH_CHECK(false, "at::cuda::blas::getrfBatched: not implemented");
333
+ }
334
+ template<>
335
+ TORCH_CUDA_CU_API void getrfBatched<float>(CUDABLAS_GETRF_ARGTYPES(float));
336
+ template<>
337
+ TORCH_CUDA_CU_API void getrfBatched<double>(CUDABLAS_GETRF_ARGTYPES(double));
338
+ template<>
339
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<double>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<double>));
340
+ template<>
341
+ TORCH_CUDA_CU_API void getrfBatched<c10::complex<float>>(CUDABLAS_GETRF_ARGTYPES(c10::complex<float>));
342
+
343
+ #define CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype) \
344
+ cublasHandle_t handle, cublasOperation_t trans, int m, int n, int nrhs, Dtype** dA_array, int ldda, Dtype** dC_array, int lddc, int* info, int *devInfoArray, int batchSize
345
+
346
+ template <class Dtype>
347
+ void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype)) {
348
+ static_assert(false&&sizeof(Dtype),"at::cuda::blas::gelsBatched: not implemented");
349
+ }
350
+
351
+ template<>
352
+ TORCH_CUDA_CU_API void gelsBatched<double>(CUDABLAS_GELS_BATCHED_ARGTYPES(double));
353
+ template<>
354
+ TORCH_CUDA_CU_API void gelsBatched<float>(CUDABLAS_GELS_BATCHED_ARGTYPES(float));
355
+ template<>
356
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<double>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<double>));
357
+ template<>
358
+ TORCH_CUDA_CU_API void gelsBatched<c10::complex<float>>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex<float>));
359
+
360
+ } // namespace at::cuda::blas
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAConfig.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Test these using #if AT_CUDNN_ENABLED(), not #ifdef, so that it's
4
+ // obvious if you forgot to include Config.h
5
+ // c.f. https://stackoverflow.com/questions/33759787/generating-an-error-if-checked-boolean-macro-is-not-defined
6
+ //
7
+ // NB: This header MUST NOT be included from other headers; it should
8
+ // only be included from C++ files.
9
+ #define AT_CUDNN_ENABLED() 1
10
+ #define AT_CUSPARSELT_ENABLED() 1
11
+ #define AT_ROCM_ENABLED() 0
12
+ #define AT_MAGMA_ENABLED() 1
13
+
14
+ // Needed for hipMAGMA to correctly identify implementation
15
+ #if (AT_ROCM_ENABLED() && AT_MAGMA_ENABLED())
16
+ #define HAVE_HIP 1
17
+ #endif
18
+
19
+ #define NVCC_FLAGS_EXTRA "-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90"
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAContext.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAContextLight.h>
4
+
5
+ // Preserved for BC, as many files depend on these includes
6
+ #include <ATen/Context.h>
7
+ #include <c10/cuda/CUDAStream.h>
8
+ #include <c10/util/Logging.h>
9
+ #include <ATen/cuda/Exceptions.h>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAContextLight.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // Light-weight version of CUDAContext.h with fewer transitive includes
3
+
4
+ #include <cstdint>
5
+
6
+ #include <cuda_runtime_api.h>
7
+ #include <cusparse.h>
8
+ #include <cublas_v2.h>
9
+
10
+ // cublasLT was introduced in CUDA 10.1 but we enable only for 11.1 that also
11
+ // added bf16 support
12
+ #include <cublasLt.h>
13
+
14
+ #ifdef CUDART_VERSION
15
+ #include <cusolverDn.h>
16
+ #endif
17
+
18
+ #if defined(USE_CUDSS)
19
+ #include <cudss.h>
20
+ #endif
21
+
22
+ #if defined(USE_ROCM)
23
+ #include <hipsolver/hipsolver.h>
24
+ #endif
25
+
26
+ #include <c10/core/Allocator.h>
27
+ #include <c10/cuda/CUDAFunctions.h>
28
+
29
+ namespace c10 {
30
+ struct Allocator;
31
+ }
32
+
33
+ namespace at::cuda {
34
+
35
+ /*
36
+ A common CUDA interface for ATen.
37
+
38
+ This interface is distinct from CUDAHooks, which defines an interface that links
39
+ to both CPU-only and CUDA builds. That interface is intended for runtime
40
+ dispatch and should be used from files that are included in both CPU-only and
41
+ CUDA builds.
42
+
43
+ CUDAContext, on the other hand, should be preferred by files only included in
44
+ CUDA builds. It is intended to expose CUDA functionality in a consistent
45
+ manner.
46
+
47
+ This means there is some overlap between the CUDAContext and CUDAHooks, but
48
+ the choice of which to use is simple: use CUDAContext when in a CUDA-only file,
49
+ use CUDAHooks otherwise.
50
+
51
+ Note that CUDAContext simply defines an interface with no associated class.
52
+ It is expected that the modules whose functions compose this interface will
53
+ manage their own state. There is only a single CUDA context/state.
54
+ */
55
+
56
+ /**
57
+ * DEPRECATED: use device_count() instead
58
+ */
59
+ inline int64_t getNumGPUs() {
60
+ return c10::cuda::device_count();
61
+ }
62
+
63
+ /**
64
+ * CUDA is available if we compiled with CUDA, and there are one or more
65
+ * devices. If we compiled with CUDA but there is a driver problem, etc.,
66
+ * this function will report CUDA is not available (rather than raise an error.)
67
+ */
68
+ inline bool is_available() {
69
+ return c10::cuda::device_count() > 0;
70
+ }
71
+
72
+ TORCH_CUDA_CPP_API cudaDeviceProp* getCurrentDeviceProperties();
73
+
74
+ TORCH_CUDA_CPP_API int warp_size();
75
+
76
+ TORCH_CUDA_CPP_API cudaDeviceProp* getDeviceProperties(c10::DeviceIndex device);
77
+
78
+ TORCH_CUDA_CPP_API bool canDeviceAccessPeer(
79
+ c10::DeviceIndex device,
80
+ c10::DeviceIndex peer_device);
81
+
82
+ TORCH_CUDA_CPP_API c10::Allocator* getCUDADeviceAllocator();
83
+
84
+ /* Handles */
85
+ TORCH_CUDA_CPP_API cusparseHandle_t getCurrentCUDASparseHandle();
86
+ TORCH_CUDA_CPP_API cublasHandle_t getCurrentCUDABlasHandle();
87
+ TORCH_CUDA_CPP_API cublasLtHandle_t getCurrentCUDABlasLtHandle();
88
+
89
+ TORCH_CUDA_CPP_API void clearCublasWorkspaces();
90
+
91
+ #if defined(CUDART_VERSION) || defined(USE_ROCM)
92
+ TORCH_CUDA_CPP_API cusolverDnHandle_t getCurrentCUDASolverDnHandle();
93
+ #endif
94
+
95
+ #if defined(USE_CUDSS)
96
+ TORCH_CUDA_CPP_API cudssHandle_t getCurrentCudssHandle();
97
+ #endif
98
+
99
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDADataType.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/ScalarType.h>
4
+
5
+ #include <cuda.h>
6
+ #include <library_types.h>
7
+
8
+ namespace at::cuda {
9
+
10
+ template <typename scalar_t>
11
+ cudaDataType getCudaDataType() {
12
+ static_assert(false && sizeof(scalar_t), "Cannot convert type to cudaDataType.");
13
+ return {};
14
+ }
15
+
16
+ template<> inline cudaDataType getCudaDataType<at::Half>() {
17
+ return CUDA_R_16F;
18
+ }
19
+ template<> inline cudaDataType getCudaDataType<float>() {
20
+ return CUDA_R_32F;
21
+ }
22
+ template<> inline cudaDataType getCudaDataType<double>() {
23
+ return CUDA_R_64F;
24
+ }
25
+ template<> inline cudaDataType getCudaDataType<c10::complex<c10::Half>>() {
26
+ return CUDA_C_16F;
27
+ }
28
+ template<> inline cudaDataType getCudaDataType<c10::complex<float>>() {
29
+ return CUDA_C_32F;
30
+ }
31
+ template<> inline cudaDataType getCudaDataType<c10::complex<double>>() {
32
+ return CUDA_C_64F;
33
+ }
34
+
35
+ template<> inline cudaDataType getCudaDataType<uint8_t>() {
36
+ return CUDA_R_8U;
37
+ }
38
+ template<> inline cudaDataType getCudaDataType<int8_t>() {
39
+ return CUDA_R_8I;
40
+ }
41
+ template<> inline cudaDataType getCudaDataType<int>() {
42
+ return CUDA_R_32I;
43
+ }
44
+
45
+ template<> inline cudaDataType getCudaDataType<int16_t>() {
46
+ return CUDA_R_16I;
47
+ }
48
+ template<> inline cudaDataType getCudaDataType<int64_t>() {
49
+ return CUDA_R_64I;
50
+ }
51
+ template<> inline cudaDataType getCudaDataType<at::BFloat16>() {
52
+ return CUDA_R_16BF;
53
+ }
54
+
55
+ inline cudaDataType ScalarTypeToCudaDataType(const c10::ScalarType& scalar_type) {
56
+ switch (scalar_type) {
57
+ case c10::ScalarType::Byte:
58
+ return CUDA_R_8U;
59
+ case c10::ScalarType::Char:
60
+ return CUDA_R_8I;
61
+ case c10::ScalarType::Int:
62
+ return CUDA_R_32I;
63
+ case c10::ScalarType::Half:
64
+ return CUDA_R_16F;
65
+ case c10::ScalarType::Float:
66
+ return CUDA_R_32F;
67
+ case c10::ScalarType::Double:
68
+ return CUDA_R_64F;
69
+ case c10::ScalarType::ComplexHalf:
70
+ return CUDA_C_16F;
71
+ case c10::ScalarType::ComplexFloat:
72
+ return CUDA_C_32F;
73
+ case c10::ScalarType::ComplexDouble:
74
+ return CUDA_C_64F;
75
+ case c10::ScalarType::Short:
76
+ return CUDA_R_16I;
77
+ case c10::ScalarType::Long:
78
+ return CUDA_R_64I;
79
+ case c10::ScalarType::BFloat16:
80
+ return CUDA_R_16BF;
81
+ #if (defined(CUDA_VERSION) && CUDA_VERSION >= 11080) || (defined(USE_ROCM) && ROCM_VERSION >= 60300)
82
+ case c10::ScalarType::Float8_e4m3fn:
83
+ return CUDA_R_8F_E4M3;
84
+ case c10::ScalarType::Float8_e5m2:
85
+ return CUDA_R_8F_E5M2;
86
+ #endif
87
+ #if defined(USE_ROCM)
88
+ case c10::ScalarType::Float8_e4m3fnuz:
89
+ return HIP_R_8F_E4M3_FNUZ;
90
+ case c10::ScalarType::Float8_e5m2fnuz:
91
+ return HIP_R_8F_E5M2_FNUZ;
92
+ #endif
93
+ default:
94
+ TORCH_INTERNAL_ASSERT(false, "Cannot convert ScalarType ", scalar_type, " to cudaDataType.")
95
+ }
96
+ }
97
+
98
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDADevice.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/Exceptions.h>
4
+
5
+ #include <cuda.h>
6
+ #include <cuda_runtime.h>
7
+
8
+ namespace at::cuda {
9
+
10
+ inline Device getDeviceFromPtr(void* ptr) {
11
+ cudaPointerAttributes attr{};
12
+
13
+ AT_CUDA_CHECK(cudaPointerGetAttributes(&attr, ptr));
14
+
15
+ #if !defined(USE_ROCM)
16
+ TORCH_CHECK(attr.type != cudaMemoryTypeUnregistered,
17
+ "The specified pointer resides on host memory and is not registered with any CUDA device.");
18
+ #endif
19
+
20
+ return {c10::DeviceType::CUDA, static_cast<DeviceIndex>(attr.device)};
21
+ }
22
+
23
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAEvent.h ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/ATenCUDAGeneral.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <c10/core/impl/GPUTrace.h>
6
+ #include <c10/cuda/CUDAStream.h>
7
+ #include <c10/cuda/CUDAGuard.h>
8
+ #include <ATen/cuda/Exceptions.h>
9
+ #include <c10/util/Exception.h>
10
+
11
+ #include <cuda_runtime_api.h>
12
+
13
+ #include <cstdint>
14
+ #include <utility>
15
+
16
+ namespace at::cuda {
17
+
18
+ /*
19
+ * CUDAEvents are movable not copyable wrappers around CUDA's events.
20
+ *
21
+ * CUDAEvents are constructed lazily when first recorded unless it is
22
+ * reconstructed from a cudaIpcEventHandle_t. The event has a device, and this
23
+ * device is acquired from the first recording stream. However, if reconstructed
24
+ * from a handle, the device should be explicitly specified; or if ipc_handle() is
25
+ * called before the event is ever recorded, it will use the current device.
26
+ * Later streams that record the event must match this device.
27
+ */
28
+ struct TORCH_CUDA_CPP_API CUDAEvent {
29
+ // Constructors
30
+ // Default value for `flags` is specified below - it's cudaEventDisableTiming
31
+ CUDAEvent() noexcept = default;
32
+ CUDAEvent(unsigned int flags) noexcept : flags_{flags} {}
33
+
34
+ CUDAEvent(
35
+ DeviceIndex device_index, const cudaIpcEventHandle_t* handle) : device_index_(device_index) {
36
+ CUDAGuard guard(device_index_);
37
+
38
+ AT_CUDA_CHECK(cudaIpcOpenEventHandle(&event_, *handle));
39
+ is_created_ = true;
40
+ }
41
+
42
+ // Note: event destruction done on creating device to avoid creating a
43
+ // CUDA context on other devices.
44
+ ~CUDAEvent() {
45
+ try {
46
+ if (is_created_) {
47
+ CUDAGuard guard(device_index_);
48
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
49
+ if (C10_UNLIKELY(interp)) {
50
+ (*interp)->trace_gpu_event_deletion(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
51
+ }
52
+ AT_CUDA_CHECK(cudaEventDestroy(event_));
53
+ }
54
+ } catch (...) { /* No throw */ }
55
+ }
56
+
57
+ CUDAEvent(const CUDAEvent&) = delete;
58
+ CUDAEvent& operator=(const CUDAEvent&) = delete;
59
+
60
+ CUDAEvent(CUDAEvent&& other) noexcept { moveHelper(std::move(other)); }
61
+ CUDAEvent& operator=(CUDAEvent&& other) noexcept {
62
+ if (this != &other) {
63
+ moveHelper(std::move(other));
64
+ }
65
+ return *this;
66
+ }
67
+
68
+ operator cudaEvent_t() const { return event(); }
69
+
70
+ // Less than operator (to allow use in sets)
71
+ friend bool operator<(const CUDAEvent& left, const CUDAEvent& right) {
72
+ return left.event_ < right.event_;
73
+ }
74
+
75
+ std::optional<at::Device> device() const {
76
+ if (is_created_) {
77
+ return at::Device(at::kCUDA, device_index_);
78
+ } else {
79
+ return {};
80
+ }
81
+ }
82
+
83
+ bool isCreated() const { return is_created_; }
84
+ DeviceIndex device_index() const {return device_index_;}
85
+ cudaEvent_t event() const { return event_; }
86
+
87
+ // Note: cudaEventQuery can be safely called from any device
88
+ bool query() const {
89
+ if (!is_created_) {
90
+ return true;
91
+ }
92
+
93
+ cudaError_t err = cudaEventQuery(event_);
94
+ if (err == cudaSuccess) {
95
+ return true;
96
+ } else if (err != cudaErrorNotReady) {
97
+ C10_CUDA_CHECK(err);
98
+ } else {
99
+ // ignore and clear the error if not ready
100
+ (void)cudaGetLastError();
101
+ }
102
+
103
+ return false;
104
+ }
105
+
106
+ void record() { record(getCurrentCUDAStream()); }
107
+
108
+ void recordOnce(const CUDAStream& stream) {
109
+ if (!was_recorded_) record(stream);
110
+ }
111
+
112
+ // Note: cudaEventRecord must be called on the same device as the event.
113
+ void record(const CUDAStream& stream) {
114
+ if (!is_created_) {
115
+ createEvent(stream.device_index());
116
+ }
117
+
118
+ TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_,
119
+ " does not match recording stream's device ", stream.device_index(), ".");
120
+ CUDAGuard guard(device_index_);
121
+ AT_CUDA_CHECK(cudaEventRecord(event_, stream));
122
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
123
+ if (C10_UNLIKELY(interp)) {
124
+ (*interp)->trace_gpu_event_record(at::kCUDA,
125
+ reinterpret_cast<uintptr_t>(event_),
126
+ reinterpret_cast<uintptr_t>(stream.stream())
127
+ );
128
+ }
129
+ was_recorded_ = true;
130
+ }
131
+
132
+ // Note: cudaStreamWaitEvent must be called on the same device as the stream.
133
+ // The event has no actual GPU resources associated with it.
134
+ void block(const CUDAStream& stream) {
135
+ if (is_created_) {
136
+ CUDAGuard guard(stream.device_index());
137
+ AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_, 0));
138
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
139
+ if (C10_UNLIKELY(interp)) {
140
+ (*interp)->trace_gpu_event_wait(at::kCUDA,
141
+ reinterpret_cast<uintptr_t>(event_),
142
+ reinterpret_cast<uintptr_t>(stream.stream())
143
+ );
144
+ }
145
+ }
146
+ }
147
+
148
+ // Note: cudaEventElapsedTime can be safely called from any device
149
+ float elapsed_time(const CUDAEvent& other) const {
150
+ TORCH_CHECK(is_created_ && other.isCreated(),
151
+ "Both events must be recorded before calculating elapsed time.");
152
+ float time_ms = 0;
153
+ // We do not strictly have to set the device index to the same as our event,
154
+ // but if we don't and the current device is not initialized, it will
155
+ // create a new cuda context, which will consume a lot of memory.
156
+ CUDAGuard guard(device_index_);
157
+ // raise cudaErrorNotReady if either event is recorded but not yet completed
158
+ AT_CUDA_CHECK(cudaEventElapsedTime(&time_ms, event_, other.event_));
159
+ return time_ms;
160
+ }
161
+
162
+ // Note: cudaEventSynchronize can be safely called from any device
163
+ void synchronize() const {
164
+ if (is_created_) {
165
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
166
+ if (C10_UNLIKELY(interp)) {
167
+ (*interp)->trace_gpu_event_synchronization(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
168
+ }
169
+ AT_CUDA_CHECK(cudaEventSynchronize(event_));
170
+ }
171
+ }
172
+
173
+ // Note: cudaIpcGetEventHandle must be called on the same device as the event
174
+ void ipc_handle(cudaIpcEventHandle_t * handle) {
175
+ if (!is_created_) {
176
+ // this CUDAEvent object was initially constructed from flags but event_
177
+ // is not created yet.
178
+ createEvent(getCurrentCUDAStream().device_index());
179
+ }
180
+ CUDAGuard guard(device_index_);
181
+ AT_CUDA_CHECK(cudaIpcGetEventHandle(handle, event_));
182
+ }
183
+
184
+ private:
185
+ unsigned int flags_ = cudaEventDisableTiming;
186
+ bool is_created_ = false;
187
+ bool was_recorded_ = false;
188
+ DeviceIndex device_index_ = -1;
189
+ cudaEvent_t event_{};
190
+
191
+ void createEvent(DeviceIndex device_index) {
192
+ device_index_ = device_index;
193
+ CUDAGuard guard(device_index_);
194
+ AT_CUDA_CHECK(cudaEventCreateWithFlags(&event_, flags_));
195
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
196
+ if (C10_UNLIKELY(interp)) {
197
+ (*interp)->trace_gpu_event_creation(at::kCUDA, reinterpret_cast<uintptr_t>(event_));
198
+ }
199
+ is_created_ = true;
200
+ }
201
+
202
+ void moveHelper(CUDAEvent&& other) {
203
+ std::swap(flags_, other.flags_);
204
+ std::swap(is_created_, other.is_created_);
205
+ std::swap(was_recorded_, other.was_recorded_);
206
+ std::swap(device_index_, other.device_index_);
207
+ std::swap(event_, other.event_);
208
+ }
209
+ };
210
+
211
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGeneratorImpl.h ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Context.h>
4
+ #include <ATen/core/Generator.h>
5
+ #include <ATen/core/TensorBase.h>
6
+ #include <ATen/cuda/PhiloxCudaState.h>
7
+ #include <atomic>
8
+ #include <memory>
9
+ #include <unordered_set>
10
+ namespace at {
11
+
12
+ namespace cuda {
13
+ struct CUDAGraph;
14
+ }
15
+
16
+ /**
17
+ * Note [CUDA Graph-safe RNG states]
18
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
19
+ *
20
+ * Strategy:
21
+ * ~~~~~~~~~
22
+ * (It helps to look at
23
+ * cuda/detail/PhiloxCudaStateRaw.cuh and
24
+ * cuda/detail/UnpackRaw.cuh
25
+ * while you read this.)
26
+ *
27
+ * A CUDA graph containing multiple RNG ops behaves like a
28
+ * single giant kernel from the perspective of ops external
29
+ * to the graph. During graph capture, logic in CUDAGeneratorImpl
30
+ * records the total of all offset increments that occur in the
31
+ * graphed region, and records the final total as the offset for
32
+ * the entire graph.
33
+ *
34
+ * When the graph reruns, the logic that reruns it
35
+ * increments this device's CUDA generator's offset
36
+ * by that total.
37
+ *
38
+ * Meanwhile, within the graph, at capture time, instead of
39
+ * populating PhiloxCudaStates with the uint64_t offset pulled
40
+ * directly from the global state, PhiloxCudaState uses a pointer
41
+ * to a one-element stream-local int64_t device tensor
42
+ * holding an initial offset value, and a uint64_t holding an
43
+ * intra-graph offset. (The intra-graph offset starts from zero
44
+ * when capture begins.) In each consumer kernel,
45
+ * at::cuda::philox::unpack computes the offset to use for this kernel
46
+ * as intra-graph offset + *initial offset.
47
+ *
48
+ * When the graph reruns, the logic that reruns it first
49
+ * fill_s the initial offset tensor with this device's
50
+ * CUDA generator's current offset.
51
+ *
52
+ * The control flow above ensures graphed execution is bitwise
53
+ * identical to eager execution as long as RNG ops are enqueued
54
+ * from a single thread, even if RNG ops and graphs containing
55
+ * RNG ops are enqueued and run simultaneously on multiple streams.
56
+ *
57
+ * Usage:
58
+ * ~~~~~~
59
+ * PhiloxCudaState in this file, and unpack() in
60
+ * cuda/CUDAGraphsUtils.cuh allow non-divergent use of
61
+ * CUDAGeneratorImpl whether graph capture is underway or not.
62
+ *
63
+ * Each PhiloxCudaState instance should be used for one and only one
64
+ * consumer kernel.
65
+ *
66
+ * Example (see e.g. native/cuda/Dropout.cu):
67
+ *
68
+ * #include <ATen/cuda/CUDAGeneratorImpl.h>
69
+ * #include <ATen/cuda/CUDAGraphsUtils.cuh>
70
+ *
71
+ * __global__ void kernel(..., PhiloxCudaState philox_args) {
72
+ * auto seeds = at::cuda::philox::unpack(philox_args);
73
+ * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x;
74
+ * curandStatePhilox4_32_10_t state;
75
+ * curand_init(std::get<0>(seeds), // seed
76
+ * idx, // per-thread subsequence
77
+ * std::get<1>(seeds), // offset in subsequence
78
+ * &state);
79
+ * ...
80
+ * }
81
+ *
82
+ * host_caller(...) {
83
+ * PhiloxCudaState rng_engine_inputs;
84
+ * {
85
+ * // See Note [Acquire lock when using random generators]
86
+ * std::lock_guard<std::mutex> lock(gen->mutex_);
87
+ *
88
+ * // gen could be HostState or DevState here! No divergent code needed!
89
+ * rng_engine_inputs = gen->philox_cuda_state(offset_increment);
90
+ * }
91
+ * kernel<<<...>>>(..., rng_engine_inputs);
92
+ * }
93
+ *
94
+ */
95
+
96
+ struct CUDAGeneratorState : public c10::intrusive_ptr_target {
97
+ uint64_t seed_;
98
+ uint64_t philox_offset_per_thread_;
99
+ uint32_t offset_intragraph_;
100
+ bool capturing_{};
101
+ std::unordered_set<cuda::CUDAGraph*> registered_graphs_;
102
+ at::TensorBase seed_extragraph_{};
103
+ at::TensorBase offset_extragraph_{};
104
+
105
+ CUDAGeneratorState(
106
+ uint64_t seed = default_rng_seed_val,
107
+ uint64_t philox_offset_per_thread = 0,
108
+ uint32_t offset_intragraph = 0)
109
+ : seed_(seed),
110
+ philox_offset_per_thread_(philox_offset_per_thread),
111
+ offset_intragraph_(offset_intragraph) {}
112
+
113
+ void increase(uint64_t increment);
114
+
115
+ void register_graph(cuda::CUDAGraph* graph);
116
+ void unregister_graph(cuda::CUDAGraph* graph);
117
+
118
+ void capture_prologue();
119
+ // capture_epilogue returns the wholegraph_increment
120
+ uint64_t capture_epilogue();
121
+ void replay_prologue(uint64_t wholegraph_increment);
122
+ c10::intrusive_ptr<CUDAGeneratorState> clone();
123
+ };
124
+
125
+ struct TORCH_CUDA_CPP_API CUDAGeneratorImpl : public c10::GeneratorImpl {
126
+ // Constructors
127
+ CUDAGeneratorImpl(DeviceIndex device_index = -1);
128
+ CUDAGeneratorImpl(
129
+ DeviceIndex device_index,
130
+ c10::intrusive_ptr<CUDAGeneratorState> state_);
131
+ ~CUDAGeneratorImpl() override = default;
132
+
133
+ // CUDAGeneratorImpl methods
134
+ std::shared_ptr<CUDAGeneratorImpl> clone() const;
135
+ void set_current_seed(uint64_t seed) override;
136
+ void set_offset(uint64_t offset) override;
137
+ uint64_t get_offset() const override;
138
+ uint64_t current_seed() const override;
139
+ uint64_t seed() override;
140
+ void set_state(const c10::TensorImpl& new_state) override;
141
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
142
+ void graphsafe_set_state(
143
+ const c10::intrusive_ptr<GeneratorImpl>& state) override;
144
+ c10::intrusive_ptr<c10::GeneratorImpl> graphsafe_get_state() const override;
145
+
146
+ void set_philox_offset_per_thread(uint64_t offset);
147
+ uint64_t philox_offset_per_thread() const;
148
+
149
+ void register_graph(cuda::CUDAGraph* graph);
150
+ void unregister_graph(cuda::CUDAGraph* graph);
151
+
152
+ // Generates a PhiloxCudaState with a specified increment, and increment
153
+ // current state
154
+ PhiloxCudaState philox_cuda_state(uint64_t increment);
155
+
156
+ bool reset_rnn_state() {
157
+ return !no_reset_rnn_state_.test_and_set();
158
+ }
159
+
160
+ // Temporarily accommodates call sites that use philox_engine_inputs.
161
+ // Allows incremental refactor of call sites to use philox_cuda_state.
162
+ std::pair<uint64_t, uint64_t> philox_engine_inputs(uint64_t increment);
163
+
164
+ static c10::DeviceType device_type();
165
+
166
+ private:
167
+ CUDAGeneratorImpl* clone_impl() const override;
168
+
169
+ c10::intrusive_ptr<CUDAGeneratorState> state_;
170
+ std::atomic_flag no_reset_rnn_state_{};
171
+ };
172
+
173
+ namespace cuda::detail {
174
+
175
+ TORCH_CUDA_CPP_API const Generator& getDefaultCUDAGenerator(
176
+ DeviceIndex device_index = -1);
177
+ TORCH_CUDA_CPP_API Generator createCUDAGenerator(DeviceIndex device_index = -1);
178
+
179
+ } // namespace cuda::detail
180
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGraph.h ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/core/Device.h>
5
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
6
+ #include <c10/cuda/CUDAStream.h>
7
+ #include <c10/util/flat_hash_map.h>
8
+
9
+ namespace at {
10
+
11
+ struct Generator;
12
+ struct CUDAGeneratorImpl;
13
+ struct CUDAGeneratorState;
14
+
15
+ namespace cuda {
16
+
17
+ // Standalone way to get a unique mempool id usable as a pool=... argument
18
+ // to CUDAGraph::capture_begin
19
+ TORCH_CUDA_CPP_API MempoolId_t graph_pool_handle();
20
+
21
+ struct TORCH_CUDA_CPP_API CUDAGraph {
22
+ CUDAGraph();
23
+ ~CUDAGraph();
24
+
25
+ // See Note [Explicit Registration of Generators to the CUDA Graph]
26
+ void register_generator_state(c10::intrusive_ptr<at::CUDAGeneratorState> state);
27
+ void register_generator_state(const at::Generator& generator);
28
+ void capture_begin(
29
+ MempoolId_t pool = {0, 0},
30
+ cudaStreamCaptureMode capture_mode = cudaStreamCaptureModeGlobal);
31
+ void capture_end();
32
+ void replay();
33
+ void reset();
34
+ MempoolId_t pool();
35
+ void enable_debug_mode();
36
+ void debug_dump(const std::string& debug_path);
37
+
38
+ protected:
39
+ cudaGraph_t graph_ = nullptr;
40
+ cudaGraphExec_t graph_exec_ = nullptr;
41
+
42
+ // internal states so reset() can do its best cleaning up
43
+ // Set to true in capture_end if cudaStreamEndCapture succeeded
44
+ // Set back to false soon after, when graph_ is consumed by cudaGraphInstantiate
45
+ // to create graph_exec_, then graph_ is deleted
46
+ bool has_graph_ = false;
47
+ // Set to true in capture_end if cudaGraphInstantiate succeeded
48
+ bool has_graph_exec_ = false;
49
+
50
+ // the ID assigned by cuda during graph capture,
51
+ // used to identify when a stream is participating in capture
52
+ CaptureId_t capture_id_ = -1;
53
+
54
+ // uuid used to request a particular private mempool from CUDACachingAllocator.
55
+ // By default, this will be set to {id_, 0}.
56
+ //
57
+ // If capture_begin is called with "pool=other_graph.pool()", this graph's mempool_id_
58
+ // will be set to the other graph's mempool_id_, and therefore share a mempool with the
59
+ // other graph.
60
+ //
61
+ // If capture_begin is called with "pool=handle" where "handle" came from graph_pool_handle(),
62
+ // it will share a mempool with any other captures that used "pool=handle".
63
+ //
64
+ // Sharing a mempool across graphs saves memory, and it's safe if you
65
+ // know you'll replay those graphs in the same order you captured them.
66
+ MempoolId_t mempool_id_;
67
+
68
+ // Stream on which capture began
69
+ at::cuda::CUDAStream capture_stream_;
70
+
71
+ // multiple generator states and their wholegraph_increments in this graph
72
+ // that are managed by the CUDA Graph
73
+ ska::flat_hash_map<c10::intrusive_ptr<at::CUDAGeneratorState>, uint64_t>
74
+ captured_generator_states_;
75
+
76
+ // Device where capture occurred. Right now, for simplicity, we require all ops
77
+ // in a capture to run on the same device, but this is a limitation of CUDAGraph,
78
+ // not CUDA itself. We can straightforwardly modify CUDAGraph to support multi-device
79
+ // captures if needed.
80
+ // init capture_dev_ as UNDEFINED_DEVICE to check that it stores the real device id in the destructor
81
+ static constexpr c10::DeviceIndex UNDEFINED_DEVICE = -1;
82
+ c10::DeviceIndex capture_dev_{UNDEFINED_DEVICE};
83
+ };
84
+
85
+ } // namespace cuda
86
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAGraphsUtils.cuh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAGeneratorImpl.h>
4
+ #include <ATen/cuda/CUDAEvent.h>
5
+ #include <ATen/cuda/PhiloxUtils.cuh>
6
+ #include <ATen/cuda/detail/CUDAHooks.h>
7
+ #include <ATen/detail/CUDAHooksInterface.h>
8
+ #include <c10/core/StreamGuard.h>
9
+ #include <c10/cuda/CUDAGraphsC10Utils.h>
10
+ #include <c10/cuda/CUDAGuard.h>
11
+
12
+ // c10/cuda/CUDAGraphsC10Utils.h has utils used by both c10 and aten.
13
+ // This file adds utils used by aten only.
14
+
15
+ namespace at::cuda {
16
+
17
+ using CaptureId_t = c10::cuda::CaptureId_t;
18
+ using CaptureStatus = c10::cuda::CaptureStatus;
19
+
20
+ // Use this version where you don't want to create a CUDA context if none exists.
21
+ inline CaptureStatus currentStreamCaptureStatus() {
22
+ // don't create a context if we don't have to
23
+ if (c10::cuda::hasPrimaryContext(c10::cuda::current_device())) {
24
+ return c10::cuda::currentStreamCaptureStatusMayInitCtx();
25
+ } else {
26
+ return CaptureStatus::None;
27
+ }
28
+ }
29
+
30
+ inline void assertNotCapturing(const std::string& attempt) {
31
+ auto status = currentStreamCaptureStatus();
32
+ TORCH_CHECK(status == CaptureStatus::None,
33
+ attempt,
34
+ " during CUDA graph capture. If you need this call to be captured, "
35
+ "please file an issue. "
36
+ "Current cudaStreamCaptureStatus: ",
37
+ status);
38
+ }
39
+
40
+ inline void errorIfCapturingCudnnBenchmark(const std::string& version_specific) {
41
+ auto status = currentStreamCaptureStatus();
42
+ TORCH_CHECK(status == CaptureStatus::None,
43
+ "Current cudaStreamCaptureStatus: ",
44
+ status,
45
+ "\nCapturing ",
46
+ version_specific,
47
+ "is prohibited. Possible causes of this error:\n"
48
+ "1. No warmup iterations occurred before capture.\n"
49
+ "2. The convolutions you're trying to capture use dynamic shapes, "
50
+ "in which case capturing them is generally prohibited.");
51
+ }
52
+
53
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparse.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAContext.h>
4
+ #if defined(USE_ROCM)
5
+ #include <hipsparse/hipsparse-version.h>
6
+ #define HIPSPARSE_VERSION ((hipsparseVersionMajor*100000) + (hipsparseVersionMinor*100) + hipsparseVersionPatch)
7
+ #endif
8
+
9
+ // cuSparse Generic API added in CUDA 10.1
10
+ // Windows support added in CUDA 11.0
11
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && ((CUSPARSE_VERSION >= 10300) || (CUSPARSE_VERSION >= 11000 && defined(_WIN32)))
12
+ #define AT_USE_CUSPARSE_GENERIC_API() 1
13
+ #else
14
+ #define AT_USE_CUSPARSE_GENERIC_API() 0
15
+ #endif
16
+
17
+ // cuSparse Generic API descriptor pointers were changed to const in CUDA 12.0
18
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && \
19
+ (CUSPARSE_VERSION < 12000)
20
+ #define AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() 1
21
+ #else
22
+ #define AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() 0
23
+ #endif
24
+
25
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && \
26
+ (CUSPARSE_VERSION >= 12000)
27
+ #define AT_USE_CUSPARSE_CONST_DESCRIPTORS() 1
28
+ #else
29
+ #define AT_USE_CUSPARSE_CONST_DESCRIPTORS() 0
30
+ #endif
31
+
32
+ #if defined(USE_ROCM)
33
+ // hipSparse const API added in v2.4.0
34
+ #if HIPSPARSE_VERSION >= 200400
35
+ #define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 1
36
+ #define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 0
37
+ #define AT_USE_HIPSPARSE_GENERIC_API() 1
38
+ #else
39
+ #define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 0
40
+ #define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 1
41
+ #define AT_USE_HIPSPARSE_GENERIC_API() 1
42
+ #endif
43
+ #else // USE_ROCM
44
+ #define AT_USE_HIPSPARSE_CONST_DESCRIPTORS() 0
45
+ #define AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS() 0
46
+ #define AT_USE_HIPSPARSE_GENERIC_API() 0
47
+ #endif // USE_ROCM
48
+
49
+ // cuSparse Generic API spsv function was added in CUDA 11.3.0
50
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11500)
51
+ #define AT_USE_CUSPARSE_GENERIC_SPSV() 1
52
+ #else
53
+ #define AT_USE_CUSPARSE_GENERIC_SPSV() 0
54
+ #endif
55
+
56
+ // cuSparse Generic API spsm function was added in CUDA 11.3.1
57
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11600)
58
+ #define AT_USE_CUSPARSE_GENERIC_SPSM() 1
59
+ #else
60
+ #define AT_USE_CUSPARSE_GENERIC_SPSM() 0
61
+ #endif
62
+
63
+ // cuSparse Generic API sddmm function was added in CUDA 11.2.1 (cuSparse version 11400)
64
+ #if defined(CUDART_VERSION) && defined(CUSPARSE_VERSION) && (CUSPARSE_VERSION >= 11400)
65
+ #define AT_USE_CUSPARSE_GENERIC_SDDMM() 1
66
+ #else
67
+ #define AT_USE_CUSPARSE_GENERIC_SDDMM() 0
68
+ #endif
69
+
70
+ // BSR triangular solve functions were added in hipSPARSE 1.11.2 (ROCm 4.5.0)
71
+ #if defined(CUDART_VERSION) || defined(USE_ROCM)
72
+ #define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 1
73
+ #else
74
+ #define AT_USE_HIPSPARSE_TRIANGULAR_SOLVE() 0
75
+ #endif
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparseBlas.h ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /*
4
+ Provides a subset of cuSPARSE functions as templates:
5
+
6
+ csrgeam2<scalar_t>(...)
7
+
8
+ where scalar_t is double, float, c10::complex<double> or c10::complex<float>.
9
+ The functions are available in at::cuda::sparse namespace.
10
+ */
11
+
12
+ #include <ATen/cuda/CUDAContext.h>
13
+ #include <ATen/cuda/CUDASparse.h>
14
+
15
+ // NOLINTBEGIN(misc-misplaced-const)
16
+ namespace at::cuda::sparse {
17
+
18
+ #define CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t) \
19
+ cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \
20
+ const cusparseMatDescr_t descrA, int nnzA, \
21
+ const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \
22
+ const int *csrSortedColIndA, const scalar_t *beta, \
23
+ const cusparseMatDescr_t descrB, int nnzB, \
24
+ const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \
25
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
26
+ const scalar_t *csrSortedValC, const int *csrSortedRowPtrC, \
27
+ const int *csrSortedColIndC, size_t *pBufferSizeInBytes
28
+
29
+ template <typename scalar_t>
30
+ inline void csrgeam2_bufferSizeExt(
31
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t)) {
32
+ TORCH_INTERNAL_ASSERT(
33
+ false,
34
+ "at::cuda::sparse::csrgeam2_bufferSizeExt: not implemented for ",
35
+ typeid(scalar_t).name());
36
+ }
37
+
38
+ template <>
39
+ void csrgeam2_bufferSizeExt<float>(
40
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(float));
41
+ template <>
42
+ void csrgeam2_bufferSizeExt<double>(
43
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(double));
44
+ template <>
45
+ void csrgeam2_bufferSizeExt<c10::complex<float>>(
46
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex<float>));
47
+ template <>
48
+ void csrgeam2_bufferSizeExt<c10::complex<double>>(
49
+ CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex<double>));
50
+
51
+ #define CUSPARSE_CSRGEAM2_NNZ_ARGTYPES() \
52
+ cusparseHandle_t handle, int m, int n, const cusparseMatDescr_t descrA, \
53
+ int nnzA, const int *csrSortedRowPtrA, const int *csrSortedColIndA, \
54
+ const cusparseMatDescr_t descrB, int nnzB, const int *csrSortedRowPtrB, \
55
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
56
+ int *csrSortedRowPtrC, int *nnzTotalDevHostPtr, void *workspace
57
+
58
+ template <typename scalar_t>
59
+ inline void csrgeam2Nnz(CUSPARSE_CSRGEAM2_NNZ_ARGTYPES()) {
60
+ TORCH_CUDASPARSE_CHECK(cusparseXcsrgeam2Nnz(
61
+ handle,
62
+ m,
63
+ n,
64
+ descrA,
65
+ nnzA,
66
+ csrSortedRowPtrA,
67
+ csrSortedColIndA,
68
+ descrB,
69
+ nnzB,
70
+ csrSortedRowPtrB,
71
+ csrSortedColIndB,
72
+ descrC,
73
+ csrSortedRowPtrC,
74
+ nnzTotalDevHostPtr,
75
+ workspace));
76
+ }
77
+
78
+ #define CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t) \
79
+ cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \
80
+ const cusparseMatDescr_t descrA, int nnzA, \
81
+ const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \
82
+ const int *csrSortedColIndA, const scalar_t *beta, \
83
+ const cusparseMatDescr_t descrB, int nnzB, \
84
+ const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \
85
+ const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \
86
+ scalar_t *csrSortedValC, int *csrSortedRowPtrC, int *csrSortedColIndC, \
87
+ void *pBuffer
88
+
89
+ template <typename scalar_t>
90
+ inline void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t)) {
91
+ TORCH_INTERNAL_ASSERT(
92
+ false,
93
+ "at::cuda::sparse::csrgeam2: not implemented for ",
94
+ typeid(scalar_t).name());
95
+ }
96
+
97
+ template <>
98
+ void csrgeam2<float>(CUSPARSE_CSRGEAM2_ARGTYPES(float));
99
+ template <>
100
+ void csrgeam2<double>(CUSPARSE_CSRGEAM2_ARGTYPES(double));
101
+ template <>
102
+ void csrgeam2<c10::complex<float>>(
103
+ CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex<float>));
104
+ template <>
105
+ void csrgeam2<c10::complex<double>>(
106
+ CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex<double>));
107
+
108
+ #define CUSPARSE_BSRMM_ARGTYPES(scalar_t) \
109
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
110
+ cusparseOperation_t transA, cusparseOperation_t transB, int mb, int n, \
111
+ int kb, int nnzb, const scalar_t *alpha, \
112
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
113
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
114
+ const scalar_t *B, int ldb, const scalar_t *beta, scalar_t *C, int ldc
115
+
116
+ template <typename scalar_t>
117
+ inline void bsrmm(CUSPARSE_BSRMM_ARGTYPES(scalar_t)) {
118
+ TORCH_INTERNAL_ASSERT(
119
+ false,
120
+ "at::cuda::sparse::bsrmm: not implemented for ",
121
+ typeid(scalar_t).name());
122
+ }
123
+
124
+ template <>
125
+ void bsrmm<float>(CUSPARSE_BSRMM_ARGTYPES(float));
126
+ template <>
127
+ void bsrmm<double>(CUSPARSE_BSRMM_ARGTYPES(double));
128
+ template <>
129
+ void bsrmm<c10::complex<float>>(CUSPARSE_BSRMM_ARGTYPES(c10::complex<float>));
130
+ template <>
131
+ void bsrmm<c10::complex<double>>(CUSPARSE_BSRMM_ARGTYPES(c10::complex<double>));
132
+
133
+ #define CUSPARSE_BSRMV_ARGTYPES(scalar_t) \
134
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
135
+ cusparseOperation_t transA, int mb, int nb, int nnzb, \
136
+ const scalar_t *alpha, const cusparseMatDescr_t descrA, \
137
+ const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \
138
+ int blockDim, const scalar_t *x, const scalar_t *beta, scalar_t *y
139
+
140
+ template <typename scalar_t>
141
+ inline void bsrmv(CUSPARSE_BSRMV_ARGTYPES(scalar_t)) {
142
+ TORCH_INTERNAL_ASSERT(
143
+ false,
144
+ "at::cuda::sparse::bsrmv: not implemented for ",
145
+ typeid(scalar_t).name());
146
+ }
147
+
148
+ template <>
149
+ void bsrmv<float>(CUSPARSE_BSRMV_ARGTYPES(float));
150
+ template <>
151
+ void bsrmv<double>(CUSPARSE_BSRMV_ARGTYPES(double));
152
+ template <>
153
+ void bsrmv<c10::complex<float>>(CUSPARSE_BSRMV_ARGTYPES(c10::complex<float>));
154
+ template <>
155
+ void bsrmv<c10::complex<double>>(CUSPARSE_BSRMV_ARGTYPES(c10::complex<double>));
156
+
157
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
158
+
159
+ #define CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t) \
160
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
161
+ cusparseOperation_t transA, int mb, int nnzb, \
162
+ const cusparseMatDescr_t descrA, scalar_t *bsrValA, \
163
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
164
+ bsrsv2Info_t info, int *pBufferSizeInBytes
165
+
166
+ template <typename scalar_t>
167
+ inline void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t)) {
168
+ TORCH_INTERNAL_ASSERT(
169
+ false,
170
+ "at::cuda::sparse::bsrsv2_bufferSize: not implemented for ",
171
+ typeid(scalar_t).name());
172
+ }
173
+
174
+ template <>
175
+ void bsrsv2_bufferSize<float>(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(float));
176
+ template <>
177
+ void bsrsv2_bufferSize<double>(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(double));
178
+ template <>
179
+ void bsrsv2_bufferSize<c10::complex<float>>(
180
+ CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex<float>));
181
+ template <>
182
+ void bsrsv2_bufferSize<c10::complex<double>>(
183
+ CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex<double>));
184
+
185
+ #define CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t) \
186
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
187
+ cusparseOperation_t transA, int mb, int nnzb, \
188
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
189
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
190
+ bsrsv2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer
191
+
192
+ template <typename scalar_t>
193
+ inline void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t)) {
194
+ TORCH_INTERNAL_ASSERT(
195
+ false,
196
+ "at::cuda::sparse::bsrsv2_analysis: not implemented for ",
197
+ typeid(scalar_t).name());
198
+ }
199
+
200
+ template <>
201
+ void bsrsv2_analysis<float>(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(float));
202
+ template <>
203
+ void bsrsv2_analysis<double>(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(double));
204
+ template <>
205
+ void bsrsv2_analysis<c10::complex<float>>(
206
+ CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex<float>));
207
+ template <>
208
+ void bsrsv2_analysis<c10::complex<double>>(
209
+ CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex<double>));
210
+
211
+ #define CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t) \
212
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
213
+ cusparseOperation_t transA, int mb, int nnzb, const scalar_t *alpha, \
214
+ const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
215
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
216
+ bsrsv2Info_t info, const scalar_t *x, scalar_t *y, \
217
+ cusparseSolvePolicy_t policy, void *pBuffer
218
+
219
+ template <typename scalar_t>
220
+ inline void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t)) {
221
+ TORCH_INTERNAL_ASSERT(
222
+ false,
223
+ "at::cuda::sparse::bsrsv2_solve: not implemented for ",
224
+ typeid(scalar_t).name());
225
+ }
226
+
227
+ template <>
228
+ void bsrsv2_solve<float>(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(float));
229
+ template <>
230
+ void bsrsv2_solve<double>(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(double));
231
+ template <>
232
+ void bsrsv2_solve<c10::complex<float>>(
233
+ CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex<float>));
234
+ template <>
235
+ void bsrsv2_solve<c10::complex<double>>(
236
+ CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex<double>));
237
+
238
+ #define CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t) \
239
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
240
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
241
+ int nnzb, const cusparseMatDescr_t descrA, scalar_t *bsrValA, \
242
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
243
+ bsrsm2Info_t info, int *pBufferSizeInBytes
244
+
245
+ template <typename scalar_t>
246
+ inline void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t)) {
247
+ TORCH_INTERNAL_ASSERT(
248
+ false,
249
+ "at::cuda::sparse::bsrsm2_bufferSize: not implemented for ",
250
+ typeid(scalar_t).name());
251
+ }
252
+
253
+ template <>
254
+ void bsrsm2_bufferSize<float>(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(float));
255
+ template <>
256
+ void bsrsm2_bufferSize<double>(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(double));
257
+ template <>
258
+ void bsrsm2_bufferSize<c10::complex<float>>(
259
+ CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex<float>));
260
+ template <>
261
+ void bsrsm2_bufferSize<c10::complex<double>>(
262
+ CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex<double>));
263
+
264
+ #define CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t) \
265
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
266
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
267
+ int nnzb, const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \
268
+ const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \
269
+ bsrsm2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer
270
+
271
+ template <typename scalar_t>
272
+ inline void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t)) {
273
+ TORCH_INTERNAL_ASSERT(
274
+ false,
275
+ "at::cuda::sparse::bsrsm2_analysis: not implemented for ",
276
+ typeid(scalar_t).name());
277
+ }
278
+
279
+ template <>
280
+ void bsrsm2_analysis<float>(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(float));
281
+ template <>
282
+ void bsrsm2_analysis<double>(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(double));
283
+ template <>
284
+ void bsrsm2_analysis<c10::complex<float>>(
285
+ CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex<float>));
286
+ template <>
287
+ void bsrsm2_analysis<c10::complex<double>>(
288
+ CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex<double>));
289
+
290
+ #define CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t) \
291
+ cusparseHandle_t handle, cusparseDirection_t dirA, \
292
+ cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \
293
+ int nnzb, const scalar_t *alpha, const cusparseMatDescr_t descrA, \
294
+ const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \
295
+ int blockDim, bsrsm2Info_t info, const scalar_t *B, int ldb, \
296
+ scalar_t *X, int ldx, cusparseSolvePolicy_t policy, void *pBuffer
297
+
298
+ template <typename scalar_t>
299
+ inline void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t)) {
300
+ TORCH_INTERNAL_ASSERT(
301
+ false,
302
+ "at::cuda::sparse::bsrsm2_solve: not implemented for ",
303
+ typeid(scalar_t).name());
304
+ }
305
+
306
+ template <>
307
+ void bsrsm2_solve<float>(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(float));
308
+ template <>
309
+ void bsrsm2_solve<double>(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(double));
310
+ template <>
311
+ void bsrsm2_solve<c10::complex<float>>(
312
+ CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex<float>));
313
+ template <>
314
+ void bsrsm2_solve<c10::complex<double>>(
315
+ CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex<double>));
316
+
317
+ #endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE
318
+
319
+ } // namespace at::cuda::sparse
320
+ // NOLINTEND(misc-misplaced-const)
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDASparseDescriptors.h ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <ATen/cuda/CUDASparse.h>
6
+
7
+ #include <c10/core/ScalarType.h>
8
+
9
+ #if defined(USE_ROCM)
10
+ #include <type_traits>
11
+ #endif
12
+
13
+ namespace at::cuda::sparse {
14
+
15
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
16
+ struct CuSparseDescriptorDeleter {
17
+ void operator()(T* x) {
18
+ if (x != nullptr) {
19
+ TORCH_CUDASPARSE_CHECK(destructor(x));
20
+ }
21
+ }
22
+ };
23
+
24
+ template <typename T, cusparseStatus_t (*destructor)(T*)>
25
+ class CuSparseDescriptor {
26
+ public:
27
+ T* descriptor() const {
28
+ return descriptor_.get();
29
+ }
30
+ T* descriptor() {
31
+ return descriptor_.get();
32
+ }
33
+
34
+ protected:
35
+ std::unique_ptr<T, CuSparseDescriptorDeleter<T, destructor>> descriptor_;
36
+ };
37
+
38
+ #if AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS()
39
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
40
+ struct ConstCuSparseDescriptorDeleter {
41
+ void operator()(T* x) {
42
+ if (x != nullptr) {
43
+ TORCH_CUDASPARSE_CHECK(destructor(x));
44
+ }
45
+ }
46
+ };
47
+
48
+ template <typename T, cusparseStatus_t (*destructor)(const T*)>
49
+ class ConstCuSparseDescriptor {
50
+ public:
51
+ T* descriptor() const {
52
+ return descriptor_.get();
53
+ }
54
+ T* descriptor() {
55
+ return descriptor_.get();
56
+ }
57
+
58
+ protected:
59
+ std::unique_ptr<T, ConstCuSparseDescriptorDeleter<T, destructor>> descriptor_;
60
+ };
61
+ #endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS || AT_USE_HIPSPARSE_CONST_DESCRIPTORS
62
+
63
+ #if defined(USE_ROCM)
64
+ using cusparseMatDescr = std::remove_pointer_t<hipsparseMatDescr_t>;
65
+ using cusparseDnMatDescr = std::remove_pointer_t<hipsparseDnMatDescr_t>;
66
+ using cusparseDnVecDescr = std::remove_pointer_t<hipsparseDnVecDescr_t>;
67
+ using cusparseSpMatDescr = std::remove_pointer_t<hipsparseSpMatDescr_t>;
68
+ using cusparseSpMatDescr = std::remove_pointer_t<hipsparseSpMatDescr_t>;
69
+ using cusparseSpGEMMDescr = std::remove_pointer_t<hipsparseSpGEMMDescr_t>;
70
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
71
+ using bsrsv2Info = std::remove_pointer_t<bsrsv2Info_t>;
72
+ using bsrsm2Info = std::remove_pointer_t<bsrsm2Info_t>;
73
+ #endif
74
+ #endif
75
+
76
+ // NOTE: This is only needed for CUDA 11 and earlier, since CUDA 12 introduced
77
+ // API for const descriptors
78
+ cusparseStatus_t destroyConstDnMat(const cusparseDnMatDescr* dnMatDescr);
79
+
80
+ class TORCH_CUDA_CPP_API CuSparseMatDescriptor
81
+ : public CuSparseDescriptor<cusparseMatDescr, &cusparseDestroyMatDescr> {
82
+ public:
83
+ CuSparseMatDescriptor() {
84
+ cusparseMatDescr_t raw_descriptor = nullptr;
85
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
86
+ descriptor_.reset(raw_descriptor);
87
+ }
88
+
89
+ CuSparseMatDescriptor(bool upper, bool unit) {
90
+ cusparseFillMode_t fill_mode =
91
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
92
+ cusparseDiagType_t diag_type =
93
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
94
+ cusparseMatDescr_t raw_descriptor = nullptr;
95
+ TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor));
96
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatFillMode(raw_descriptor, fill_mode));
97
+ TORCH_CUDASPARSE_CHECK(cusparseSetMatDiagType(raw_descriptor, diag_type));
98
+ descriptor_.reset(raw_descriptor);
99
+ }
100
+ };
101
+
102
+ #if AT_USE_HIPSPARSE_TRIANGULAR_SOLVE()
103
+
104
+ class TORCH_CUDA_CPP_API CuSparseBsrsv2Info
105
+ : public CuSparseDescriptor<bsrsv2Info, &cusparseDestroyBsrsv2Info> {
106
+ public:
107
+ CuSparseBsrsv2Info() {
108
+ bsrsv2Info_t raw_descriptor = nullptr;
109
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsv2Info(&raw_descriptor));
110
+ descriptor_.reset(raw_descriptor);
111
+ }
112
+ };
113
+
114
+ class TORCH_CUDA_CPP_API CuSparseBsrsm2Info
115
+ : public CuSparseDescriptor<bsrsm2Info, &cusparseDestroyBsrsm2Info> {
116
+ public:
117
+ CuSparseBsrsm2Info() {
118
+ bsrsm2Info_t raw_descriptor = nullptr;
119
+ TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsm2Info(&raw_descriptor));
120
+ descriptor_.reset(raw_descriptor);
121
+ }
122
+ };
123
+
124
+ #endif // AT_USE_HIPSPARSE_TRIANGULAR_SOLVE
125
+
126
+ #if AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API()
127
+
128
+ cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type);
129
+
130
+ #if AT_USE_CUSPARSE_NON_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_NON_CONST_DESCRIPTORS()
131
+ class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor
132
+ : public CuSparseDescriptor<cusparseDnMatDescr, &cusparseDestroyDnMat> {
133
+ public:
134
+ explicit CuSparseDnMatDescriptor(const Tensor& input, int64_t batch_offset = -1);
135
+ };
136
+
137
+ class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor
138
+ : public CuSparseDescriptor<const cusparseDnMatDescr, &destroyConstDnMat> {
139
+ public:
140
+ explicit CuSparseConstDnMatDescriptor(const Tensor& input, int64_t batch_offset = -1);
141
+ cusparseDnMatDescr* unsafe_mutable_descriptor() const {
142
+ return const_cast<cusparseDnMatDescr*>(descriptor());
143
+ }
144
+ cusparseDnMatDescr* unsafe_mutable_descriptor() {
145
+ return const_cast<cusparseDnMatDescr*>(descriptor());
146
+ }
147
+ };
148
+
149
+ class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor
150
+ : public CuSparseDescriptor<cusparseDnVecDescr, &cusparseDestroyDnVec> {
151
+ public:
152
+ explicit CuSparseDnVecDescriptor(const Tensor& input);
153
+ };
154
+
155
+ class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor
156
+ : public CuSparseDescriptor<cusparseSpMatDescr, &cusparseDestroySpMat> {};
157
+
158
+ #elif AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS()
159
+ class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor
160
+ : public ConstCuSparseDescriptor<
161
+ cusparseDnMatDescr,
162
+ &cusparseDestroyDnMat> {
163
+ public:
164
+ explicit CuSparseDnMatDescriptor(
165
+ const Tensor& input,
166
+ int64_t batch_offset = -1);
167
+ };
168
+
169
+ class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor
170
+ : public ConstCuSparseDescriptor<
171
+ const cusparseDnMatDescr,
172
+ &destroyConstDnMat> {
173
+ public:
174
+ explicit CuSparseConstDnMatDescriptor(
175
+ const Tensor& input,
176
+ int64_t batch_offset = -1);
177
+ cusparseDnMatDescr* unsafe_mutable_descriptor() const {
178
+ return const_cast<cusparseDnMatDescr*>(descriptor());
179
+ }
180
+ cusparseDnMatDescr* unsafe_mutable_descriptor() {
181
+ return const_cast<cusparseDnMatDescr*>(descriptor());
182
+ }
183
+ };
184
+
185
+ class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor
186
+ : public ConstCuSparseDescriptor<
187
+ cusparseDnVecDescr,
188
+ &cusparseDestroyDnVec> {
189
+ public:
190
+ explicit CuSparseDnVecDescriptor(const Tensor& input);
191
+ };
192
+
193
+ class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor
194
+ : public ConstCuSparseDescriptor<
195
+ cusparseSpMatDescr,
196
+ &cusparseDestroySpMat> {};
197
+ #endif // AT_USE_CUSPARSE_CONST_DESCRIPTORS() || AT_USE_HIPSPARSE_CONST_DESCRIPTORS()
198
+
199
+ class TORCH_CUDA_CPP_API CuSparseSpMatCsrDescriptor
200
+ : public CuSparseSpMatDescriptor {
201
+ public:
202
+ explicit CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset = -1);
203
+
204
+ std::tuple<int64_t, int64_t, int64_t> get_size() {
205
+ int64_t rows = 0, cols = 0, nnz = 0;
206
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatGetSize(
207
+ this->descriptor(),
208
+ &rows,
209
+ &cols,
210
+ &nnz));
211
+ return std::make_tuple(rows, cols, nnz);
212
+ }
213
+
214
+ void set_tensor(const Tensor& input) {
215
+ auto crow_indices = input.crow_indices();
216
+ auto col_indices = input.col_indices();
217
+ auto values = input.values();
218
+
219
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous());
220
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous());
221
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous());
222
+ TORCH_CUDASPARSE_CHECK(cusparseCsrSetPointers(
223
+ this->descriptor(),
224
+ crow_indices.data_ptr(),
225
+ col_indices.data_ptr(),
226
+ values.data_ptr()));
227
+ }
228
+
229
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
230
+ void set_mat_fill_mode(bool upper) {
231
+ cusparseFillMode_t fill_mode =
232
+ upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER;
233
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
234
+ this->descriptor(),
235
+ CUSPARSE_SPMAT_FILL_MODE,
236
+ &fill_mode,
237
+ sizeof(fill_mode)));
238
+ }
239
+
240
+ void set_mat_diag_type(bool unit) {
241
+ cusparseDiagType_t diag_type =
242
+ unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT;
243
+ TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute(
244
+ this->descriptor(),
245
+ CUSPARSE_SPMAT_DIAG_TYPE,
246
+ &diag_type,
247
+ sizeof(diag_type)));
248
+ }
249
+ #endif
250
+ };
251
+
252
+ #if AT_USE_CUSPARSE_GENERIC_SPSV()
253
+ class TORCH_CUDA_CPP_API CuSparseSpSVDescriptor
254
+ : public CuSparseDescriptor<cusparseSpSVDescr, &cusparseSpSV_destroyDescr> {
255
+ public:
256
+ CuSparseSpSVDescriptor() {
257
+ cusparseSpSVDescr_t raw_descriptor = nullptr;
258
+ TORCH_CUDASPARSE_CHECK(cusparseSpSV_createDescr(&raw_descriptor));
259
+ descriptor_.reset(raw_descriptor);
260
+ }
261
+ };
262
+ #endif
263
+
264
+ #if AT_USE_CUSPARSE_GENERIC_SPSM()
265
+ class TORCH_CUDA_CPP_API CuSparseSpSMDescriptor
266
+ : public CuSparseDescriptor<cusparseSpSMDescr, &cusparseSpSM_destroyDescr> {
267
+ public:
268
+ CuSparseSpSMDescriptor() {
269
+ cusparseSpSMDescr_t raw_descriptor = nullptr;
270
+ TORCH_CUDASPARSE_CHECK(cusparseSpSM_createDescr(&raw_descriptor));
271
+ descriptor_.reset(raw_descriptor);
272
+ }
273
+ };
274
+ #endif
275
+
276
+ class TORCH_CUDA_CPP_API CuSparseSpGEMMDescriptor
277
+ : public CuSparseDescriptor<cusparseSpGEMMDescr, &cusparseSpGEMM_destroyDescr> {
278
+ public:
279
+ CuSparseSpGEMMDescriptor() {
280
+ cusparseSpGEMMDescr_t raw_descriptor = nullptr;
281
+ TORCH_CUDASPARSE_CHECK(cusparseSpGEMM_createDescr(&raw_descriptor));
282
+ descriptor_.reset(raw_descriptor);
283
+ }
284
+ };
285
+
286
+ #endif // AT_USE_CUSPARSE_GENERIC_API() || AT_USE_HIPSPARSE_GENERIC_API()
287
+
288
+ } // namespace at::cuda::sparse
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDATensorMethods.cuh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Tensor.h>
4
+ #include <c10/util/Half.h>
5
+
6
+ #include <cuda.h>
7
+ #include <cuda_runtime.h>
8
+ #include <cuda_fp16.h>
9
+
10
+ namespace at {
11
+ template <>
12
+ inline __half* Tensor::data() const {
13
+ return reinterpret_cast<__half*>(data<Half>());
14
+ }
15
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CUDAUtils.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/CUDAContext.h>
4
+
5
+ namespace at::cuda {
6
+
7
+ // Check if every tensor in a list of tensors matches the current
8
+ // device.
9
+ inline bool check_device(ArrayRef<Tensor> ts) {
10
+ if (ts.empty()) {
11
+ return true;
12
+ }
13
+ Device curDevice = Device(kCUDA, current_device());
14
+ for (const Tensor& t : ts) {
15
+ if (t.device() != curDevice) return false;
16
+ }
17
+ return true;
18
+ }
19
+
20
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/CachingHostAllocator.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/CachingHostAllocator.h>
4
+ #include <c10/core/Allocator.h>
5
+ #include <c10/cuda/CUDAStream.h>
6
+
7
+ namespace at::cuda {
8
+
9
+ //
10
+ // A caching allocator for CUDA host allocations (pinned memory).
11
+ //
12
+ // This provides a drop-in replacement for THCudaHostAllocator, which re-uses
13
+ // freed pinned (page-locked) memory allocations. This avoids device
14
+ // synchronizations due to cudaFreeHost calls.
15
+ //
16
+ // To ensure correct behavior, THCCachingHostAllocator_recordEvent must be
17
+ // called anytime a pointer from this allocator is used in a cudaMemcpyAsync
18
+ // call between host and device, and passed the corresponding context from the
19
+ // allocation. This is currently invoked by at::native::copy_kernel_cuda.
20
+ //
21
+ TORCH_CUDA_CPP_API c10::Allocator* getCachingHostAllocator();
22
+
23
+ // Records an event in the specified stream. The allocation corresponding to the
24
+ // input `ptr`/`ctx` will not be re-used until the event has occurred.
25
+ TORCH_CUDA_CPP_API bool CachingHostAllocator_recordEvent(
26
+ void* ptr,
27
+ void* ctx,
28
+ c10::cuda::CUDAStream stream);
29
+
30
+ // Releases cached pinned memory allocations via cudaHostFree
31
+ TORCH_CUDA_CPP_API void CachingHostAllocator_emptyCache();
32
+
33
+ inline TORCH_CUDA_CPP_API at::DataPtr HostAlloc(size_t size) {
34
+ return getCachingHostAllocator()->allocate(size);
35
+ }
36
+
37
+ TORCH_CUDA_CPP_API at::HostStats CachingHostAllocator_getStats();
38
+
39
+ TORCH_CUDA_CPP_API void CachingHostAllocator_resetAccumulatedStats();
40
+ TORCH_CUDA_CPP_API void CachingHostAllocator_resetPeakStats();
41
+
42
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/DeviceUtils.cuh ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <c10/util/complex.h>
5
+ #include <c10/util/Half.h>
6
+
7
+ __device__ __forceinline__ unsigned int ACTIVE_MASK()
8
+ {
9
+ #if !defined(USE_ROCM)
10
+ return __activemask();
11
+ #else
12
+ // will be ignored anyway
13
+ return 0xffffffff;
14
+ #endif
15
+ }
16
+
17
+ __device__ __forceinline__ void WARP_SYNC(unsigned mask = 0xffffffff) {
18
+ #if !defined(USE_ROCM)
19
+ return __syncwarp(mask);
20
+ #endif
21
+ }
22
+
23
+ #if defined(USE_ROCM)
24
+ __device__ __forceinline__ unsigned long long int WARP_BALLOT(int predicate)
25
+ {
26
+ return __ballot(predicate);
27
+ }
28
+ #else
29
+ __device__ __forceinline__ unsigned int WARP_BALLOT(int predicate, unsigned int mask = 0xffffffff)
30
+ {
31
+ #if !defined(USE_ROCM)
32
+ return __ballot_sync(mask, predicate);
33
+ #else
34
+ return __ballot(predicate);
35
+ #endif
36
+ }
37
+ #endif
38
+
39
+ template <typename T>
40
+ __device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff)
41
+ {
42
+ #if !defined(USE_ROCM)
43
+ return __shfl_xor_sync(mask, value, laneMask, width);
44
+ #else
45
+ return __shfl_xor(value, laneMask, width);
46
+ #endif
47
+ }
48
+
49
+ template <typename T>
50
+ __device__ __forceinline__ T WARP_SHFL(T value, int srcLane, int width = warpSize, unsigned int mask = 0xffffffff)
51
+ {
52
+ #if !defined(USE_ROCM)
53
+ return __shfl_sync(mask, value, srcLane, width);
54
+ #else
55
+ return __shfl(value, srcLane, width);
56
+ #endif
57
+ }
58
+
59
+ template <typename T>
60
+ __device__ __forceinline__ T WARP_SHFL_UP(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
61
+ {
62
+ #if !defined(USE_ROCM)
63
+ return __shfl_up_sync(mask, value, delta, width);
64
+ #else
65
+ return __shfl_up(value, delta, width);
66
+ #endif
67
+ }
68
+
69
+ template <typename T>
70
+ __device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
71
+ {
72
+ #if !defined(USE_ROCM)
73
+ return __shfl_down_sync(mask, value, delta, width);
74
+ #else
75
+ return __shfl_down(value, delta, width);
76
+ #endif
77
+ }
78
+
79
+ #if defined(USE_ROCM)
80
+ template<>
81
+ __device__ __forceinline__ int64_t WARP_SHFL_DOWN<int64_t>(int64_t value, unsigned int delta, int width , unsigned int mask)
82
+ {
83
+ //(HIP doesn't support int64_t). Trick from https://devblogs.nvidia.com/faster-parallel-reductions-kepler/
84
+ int2 a = *reinterpret_cast<int2*>(&value);
85
+ a.x = __shfl_down(a.x, delta);
86
+ a.y = __shfl_down(a.y, delta);
87
+ return *reinterpret_cast<int64_t*>(&a);
88
+ }
89
+ #endif
90
+
91
+ template<>
92
+ __device__ __forceinline__ c10::Half WARP_SHFL_DOWN<c10::Half>(c10::Half value, unsigned int delta, int width, unsigned int mask)
93
+ {
94
+ return c10::Half(WARP_SHFL_DOWN<unsigned short>(value.x, delta, width, mask), c10::Half::from_bits_t{});
95
+ }
96
+
97
+ template <typename T>
98
+ __device__ __forceinline__ c10::complex<T> WARP_SHFL_DOWN(c10::complex<T> value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff)
99
+ {
100
+ #if !defined(USE_ROCM)
101
+ return c10::complex<T>(
102
+ __shfl_down_sync(mask, value.real_, delta, width),
103
+ __shfl_down_sync(mask, value.imag_, delta, width));
104
+ #else
105
+ return c10::complex<T>(
106
+ __shfl_down(value.real_, delta, width),
107
+ __shfl_down(value.imag_, delta, width));
108
+ #endif
109
+ }
110
+
111
+ /**
112
+ * For CC 3.5+, perform a load using __ldg
113
+ */
114
+ template <typename T>
115
+ __device__ __forceinline__ T doLdg(const T* p) {
116
+ #if __CUDA_ARCH__ >= 350 && !defined(USE_ROCM)
117
+ return __ldg(p);
118
+ #else
119
+ return *p;
120
+ #endif
121
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/EmptyTensor.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/TensorBase.h>
3
+
4
+ namespace at::detail {
5
+
6
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
7
+ IntArrayRef size,
8
+ ScalarType dtype,
9
+ std::optional<Device> device_opt,
10
+ std::optional<c10::MemoryFormat> memory_format_opt);
11
+
12
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
13
+ IntArrayRef size,
14
+ std::optional<ScalarType> dtype_opt,
15
+ std::optional<Layout> layout_opt,
16
+ std::optional<Device> device_opt,
17
+ std::optional<bool> pin_memory_opt,
18
+ std::optional<c10::MemoryFormat> memory_format_opt);
19
+
20
+ TORCH_CUDA_CPP_API TensorBase empty_cuda(
21
+ IntArrayRef size,
22
+ const TensorOptions &options);
23
+
24
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
25
+ IntArrayRef size,
26
+ IntArrayRef stride,
27
+ ScalarType dtype,
28
+ std::optional<Device> device_opt);
29
+
30
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
31
+ IntArrayRef size,
32
+ IntArrayRef stride,
33
+ std::optional<ScalarType> dtype_opt,
34
+ std::optional<Layout> layout_opt,
35
+ std::optional<Device> device_opt,
36
+ std::optional<bool> pin_memory_opt);
37
+
38
+ TORCH_CUDA_CPP_API TensorBase empty_strided_cuda(
39
+ IntArrayRef size,
40
+ IntArrayRef stride,
41
+ const TensorOptions &options);
42
+
43
+
44
+ } // namespace at::detail
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Exceptions.h ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cublas_v2.h>
4
+ #include <cusparse.h>
5
+ #include <c10/macros/Export.h>
6
+
7
+ #if !defined(USE_ROCM)
8
+ #include <cusolver_common.h>
9
+ #else
10
+ #include <hipsolver/hipsolver.h>
11
+ #endif
12
+
13
+ #if defined(USE_CUDSS)
14
+ #include <cudss.h>
15
+ #endif
16
+
17
+ #include <ATen/Context.h>
18
+ #include <c10/util/Exception.h>
19
+ #include <c10/cuda/CUDAException.h>
20
+
21
+
22
+ namespace c10 {
23
+
24
+ class CuDNNError : public c10::Error {
25
+ using Error::Error;
26
+ };
27
+
28
+ } // namespace c10
29
+
30
+ #define AT_CUDNN_FRONTEND_CHECK(EXPR, ...) \
31
+ do { \
32
+ auto error_object = EXPR; \
33
+ if (!error_object.is_good()) { \
34
+ TORCH_CHECK_WITH(CuDNNError, false, \
35
+ "cuDNN Frontend error: ", error_object.get_message()); \
36
+ } \
37
+ } while (0) \
38
+
39
+ #define AT_CUDNN_CHECK_WITH_SHAPES(EXPR, ...) AT_CUDNN_CHECK(EXPR, "\n", ##__VA_ARGS__)
40
+
41
+ // See Note [CHECK macro]
42
+ #define AT_CUDNN_CHECK(EXPR, ...) \
43
+ do { \
44
+ cudnnStatus_t status = EXPR; \
45
+ if (status != CUDNN_STATUS_SUCCESS) { \
46
+ if (status == CUDNN_STATUS_NOT_SUPPORTED) { \
47
+ TORCH_CHECK_WITH(CuDNNError, false, \
48
+ "cuDNN error: ", \
49
+ cudnnGetErrorString(status), \
50
+ ". This error may appear if you passed in a non-contiguous input.", ##__VA_ARGS__); \
51
+ } else { \
52
+ TORCH_CHECK_WITH(CuDNNError, false, \
53
+ "cuDNN error: ", cudnnGetErrorString(status), ##__VA_ARGS__); \
54
+ } \
55
+ } \
56
+ } while (0)
57
+
58
+ namespace at::cuda::blas {
59
+ C10_EXPORT const char* _cublasGetErrorEnum(cublasStatus_t error);
60
+ } // namespace at::cuda::blas
61
+
62
+ #define TORCH_CUDABLAS_CHECK(EXPR) \
63
+ do { \
64
+ cublasStatus_t __err = EXPR; \
65
+ TORCH_CHECK(__err == CUBLAS_STATUS_SUCCESS, \
66
+ "CUDA error: ", \
67
+ at::cuda::blas::_cublasGetErrorEnum(__err), \
68
+ " when calling `" #EXPR "`"); \
69
+ } while (0)
70
+
71
+ const char *cusparseGetErrorString(cusparseStatus_t status);
72
+
73
+ #define TORCH_CUDASPARSE_CHECK(EXPR) \
74
+ do { \
75
+ cusparseStatus_t __err = EXPR; \
76
+ TORCH_CHECK(__err == CUSPARSE_STATUS_SUCCESS, \
77
+ "CUDA error: ", \
78
+ cusparseGetErrorString(__err), \
79
+ " when calling `" #EXPR "`"); \
80
+ } while (0)
81
+
82
+ #if defined(USE_CUDSS)
83
+ namespace at::cuda::cudss {
84
+ C10_EXPORT const char* cudssGetErrorMessage(cudssStatus_t error);
85
+ } // namespace at::cuda::solver
86
+
87
+ #define TORCH_CUDSS_CHECK(EXPR) \
88
+ do { \
89
+ cudssStatus_t __err = EXPR; \
90
+ if (__err == CUDSS_STATUS_EXECUTION_FAILED) { \
91
+ TORCH_CHECK_LINALG( \
92
+ false, \
93
+ "cudss error: ", \
94
+ at::cuda::cudss::cudssGetErrorMessage(__err), \
95
+ ", when calling `" #EXPR "`", \
96
+ ". This error may appear if the input matrix contains NaN. ");\
97
+ } else { \
98
+ TORCH_CHECK( \
99
+ __err == CUDSS_STATUS_SUCCESS, \
100
+ "cudss error: ", \
101
+ at::cuda::cudss::cudssGetErrorMessage(__err), \
102
+ ", when calling `" #EXPR "`. "); \
103
+ } \
104
+ } while (0)
105
+ #else
106
+ #define TORCH_CUDSS_CHECK(EXPR) EXPR
107
+ #endif
108
+
109
+ namespace at::cuda::solver {
110
+ #if !defined(USE_ROCM)
111
+
112
+ C10_EXPORT const char* cusolverGetErrorMessage(cusolverStatus_t status);
113
+
114
+ constexpr const char* _cusolver_backend_suggestion = \
115
+ "If you keep seeing this error, you may use " \
116
+ "`torch.backends.cuda.preferred_linalg_library()` to try " \
117
+ "linear algebra operators with other supported backends. " \
118
+ "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library";
119
+
120
+ // When cuda < 11.5, cusolver raises CUSOLVER_STATUS_EXECUTION_FAILED when input contains nan.
121
+ // When cuda >= 11.5, cusolver normally finishes execution and sets info array indicating convergence issue.
122
+ #define TORCH_CUSOLVER_CHECK(EXPR) \
123
+ do { \
124
+ cusolverStatus_t __err = EXPR; \
125
+ if ((CUDA_VERSION < 11500 && \
126
+ __err == CUSOLVER_STATUS_EXECUTION_FAILED) || \
127
+ (CUDA_VERSION >= 11500 && \
128
+ __err == CUSOLVER_STATUS_INVALID_VALUE)) { \
129
+ TORCH_CHECK_LINALG( \
130
+ false, \
131
+ "cusolver error: ", \
132
+ at::cuda::solver::cusolverGetErrorMessage(__err), \
133
+ ", when calling `" #EXPR "`", \
134
+ ". This error may appear if the input matrix contains NaN. ", \
135
+ at::cuda::solver::_cusolver_backend_suggestion); \
136
+ } else { \
137
+ TORCH_CHECK( \
138
+ __err == CUSOLVER_STATUS_SUCCESS, \
139
+ "cusolver error: ", \
140
+ at::cuda::solver::cusolverGetErrorMessage(__err), \
141
+ ", when calling `" #EXPR "`. ", \
142
+ at::cuda::solver::_cusolver_backend_suggestion); \
143
+ } \
144
+ } while (0)
145
+
146
+ #else // defined(USE_ROCM)
147
+
148
+ C10_EXPORT const char* hipsolverGetErrorMessage(hipsolverStatus_t status);
149
+
150
+ constexpr const char* _hipsolver_backend_suggestion = \
151
+ "If you keep seeing this error, you may use " \
152
+ "`torch.backends.cuda.preferred_linalg_library()` to try " \
153
+ "linear algebra operators with other supported backends. " \
154
+ "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library";
155
+
156
+ #define TORCH_CUSOLVER_CHECK(EXPR) \
157
+ do { \
158
+ hipsolverStatus_t __err = EXPR; \
159
+ if (__err == HIPSOLVER_STATUS_INVALID_VALUE) { \
160
+ TORCH_CHECK_LINALG( \
161
+ false, \
162
+ "hipsolver error: ", \
163
+ at::cuda::solver::hipsolverGetErrorMessage(__err), \
164
+ ", when calling `" #EXPR "`", \
165
+ ". This error may appear if the input matrix contains NaN. ", \
166
+ at::cuda::solver::_hipsolver_backend_suggestion); \
167
+ } else { \
168
+ TORCH_CHECK( \
169
+ __err == HIPSOLVER_STATUS_SUCCESS, \
170
+ "hipsolver error: ", \
171
+ at::cuda::solver::hipsolverGetErrorMessage(__err), \
172
+ ", when calling `" #EXPR "`. ", \
173
+ at::cuda::solver::_hipsolver_backend_suggestion); \
174
+ } \
175
+ } while (0)
176
+ #endif
177
+ } // namespace at::cuda::solver
178
+
179
+ #define AT_CUDA_CHECK(EXPR) C10_CUDA_CHECK(EXPR)
180
+
181
+ // For CUDA Driver API
182
+ //
183
+ // This is here instead of in c10 because NVRTC is loaded dynamically via a stub
184
+ // in ATen, and we need to use its nvrtcGetErrorString.
185
+ // See NOTE [ USE OF NVRTC AND DRIVER API ].
186
+ #if !defined(USE_ROCM)
187
+
188
+ #define AT_CUDA_DRIVER_CHECK(EXPR) \
189
+ do { \
190
+ CUresult __err = EXPR; \
191
+ if (__err != CUDA_SUCCESS) { \
192
+ const char* err_str; \
193
+ [[maybe_unused]] CUresult get_error_str_err = \
194
+ at::globalContext().getNVRTC().cuGetErrorString(__err, &err_str); \
195
+ if (get_error_str_err != CUDA_SUCCESS) { \
196
+ TORCH_CHECK(false, "CUDA driver error: unknown error"); \
197
+ } else { \
198
+ TORCH_CHECK(false, "CUDA driver error: ", err_str); \
199
+ } \
200
+ } \
201
+ } while (0)
202
+
203
+ #else
204
+
205
+ #define AT_CUDA_DRIVER_CHECK(EXPR) \
206
+ do { \
207
+ CUresult __err = EXPR; \
208
+ if (__err != CUDA_SUCCESS) { \
209
+ TORCH_CHECK(false, "CUDA driver error: ", static_cast<int>(__err)); \
210
+ } \
211
+ } while (0)
212
+
213
+ #endif
214
+
215
+ // For CUDA NVRTC
216
+ //
217
+ // Note: As of CUDA 10, nvrtc error code 7, NVRTC_ERROR_BUILTIN_OPERATION_FAILURE,
218
+ // incorrectly produces the error string "NVRTC unknown error."
219
+ // The following maps it correctly.
220
+ //
221
+ // This is here instead of in c10 because NVRTC is loaded dynamically via a stub
222
+ // in ATen, and we need to use its nvrtcGetErrorString.
223
+ // See NOTE [ USE OF NVRTC AND DRIVER API ].
224
+ #define AT_CUDA_NVRTC_CHECK(EXPR) \
225
+ do { \
226
+ nvrtcResult __err = EXPR; \
227
+ if (__err != NVRTC_SUCCESS) { \
228
+ if (static_cast<int>(__err) != 7) { \
229
+ TORCH_CHECK(false, "CUDA NVRTC error: ", at::globalContext().getNVRTC().nvrtcGetErrorString(__err)); \
230
+ } else { \
231
+ TORCH_CHECK(false, "CUDA NVRTC error: NVRTC_ERROR_BUILTIN_OPERATION_FAILURE"); \
232
+ } \
233
+ } \
234
+ } while (0)
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/NumericLimits.cuh ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cuda.h>
4
+ #include <limits.h>
5
+ #include <math.h>
6
+ #include <float.h>
7
+
8
+ // NumericLimits.cuh is a holder for numeric limits definitions of commonly used
9
+ // types. This header is very specific to ROCm HIP and may be removed in the future.
10
+ // This header is derived from the legacy THCNumerics.cuh.
11
+
12
+ // The lower_bound and upper_bound constants are same as lowest and max for
13
+ // integral types, but are -inf and +inf for floating point types. They are
14
+ // useful in implementing min, max, etc.
15
+
16
+ namespace at {
17
+
18
+ template <typename T>
19
+ struct numeric_limits {
20
+ };
21
+
22
+ // WARNING: the following at::numeric_limits definitions are there only to support
23
+ // HIP compilation for the moment. Use std::numeric_limits if you are not
24
+ // compiling for ROCm.
25
+ // from @colesbury: "The functions on numeric_limits aren't marked with
26
+ // __device__ which is why they don't work with ROCm. CUDA allows them
27
+ // because they're constexpr."
28
+
29
+ namespace {
30
+ // ROCm doesn't like INFINITY too.
31
+ constexpr double inf = INFINITY;
32
+ }
33
+
34
+ template <>
35
+ struct numeric_limits<bool> {
36
+ static inline __host__ __device__ bool lowest() { return false; }
37
+ static inline __host__ __device__ bool max() { return true; }
38
+ static inline __host__ __device__ bool lower_bound() { return false; }
39
+ static inline __host__ __device__ bool upper_bound() { return true; }
40
+ };
41
+
42
+ template <>
43
+ struct numeric_limits<uint8_t> {
44
+ static inline __host__ __device__ uint8_t lowest() { return 0; }
45
+ static inline __host__ __device__ uint8_t max() { return UINT8_MAX; }
46
+ static inline __host__ __device__ uint8_t lower_bound() { return 0; }
47
+ static inline __host__ __device__ uint8_t upper_bound() { return UINT8_MAX; }
48
+ };
49
+
50
+ template <>
51
+ struct numeric_limits<int8_t> {
52
+ static inline __host__ __device__ int8_t lowest() { return INT8_MIN; }
53
+ static inline __host__ __device__ int8_t max() { return INT8_MAX; }
54
+ static inline __host__ __device__ int8_t lower_bound() { return INT8_MIN; }
55
+ static inline __host__ __device__ int8_t upper_bound() { return INT8_MAX; }
56
+ };
57
+
58
+ template <>
59
+ struct numeric_limits<int16_t> {
60
+ static inline __host__ __device__ int16_t lowest() { return INT16_MIN; }
61
+ static inline __host__ __device__ int16_t max() { return INT16_MAX; }
62
+ static inline __host__ __device__ int16_t lower_bound() { return INT16_MIN; }
63
+ static inline __host__ __device__ int16_t upper_bound() { return INT16_MAX; }
64
+ };
65
+
66
+ template <>
67
+ struct numeric_limits<int32_t> {
68
+ static inline __host__ __device__ int32_t lowest() { return INT32_MIN; }
69
+ static inline __host__ __device__ int32_t max() { return INT32_MAX; }
70
+ static inline __host__ __device__ int32_t lower_bound() { return INT32_MIN; }
71
+ static inline __host__ __device__ int32_t upper_bound() { return INT32_MAX; }
72
+ };
73
+
74
+ template <>
75
+ struct numeric_limits<int64_t> {
76
+ #ifdef _MSC_VER
77
+ static inline __host__ __device__ int64_t lowest() { return _I64_MIN; }
78
+ static inline __host__ __device__ int64_t max() { return _I64_MAX; }
79
+ static inline __host__ __device__ int64_t lower_bound() { return _I64_MIN; }
80
+ static inline __host__ __device__ int64_t upper_bound() { return _I64_MAX; }
81
+ #else
82
+ static inline __host__ __device__ int64_t lowest() { return INT64_MIN; }
83
+ static inline __host__ __device__ int64_t max() { return INT64_MAX; }
84
+ static inline __host__ __device__ int64_t lower_bound() { return INT64_MIN; }
85
+ static inline __host__ __device__ int64_t upper_bound() { return INT64_MAX; }
86
+ #endif
87
+ };
88
+
89
+ template <>
90
+ struct numeric_limits<at::Half> {
91
+ static inline __host__ __device__ at::Half lowest() { return at::Half(0xFBFF, at::Half::from_bits()); }
92
+ static inline __host__ __device__ at::Half max() { return at::Half(0x7BFF, at::Half::from_bits()); }
93
+ static inline __host__ __device__ at::Half lower_bound() { return at::Half(0xFC00, at::Half::from_bits()); }
94
+ static inline __host__ __device__ at::Half upper_bound() { return at::Half(0x7C00, at::Half::from_bits()); }
95
+ };
96
+
97
+ template <>
98
+ struct numeric_limits<at::BFloat16> {
99
+ static inline __host__ __device__ at::BFloat16 lowest() { return at::BFloat16(0xFF7F, at::BFloat16::from_bits()); }
100
+ static inline __host__ __device__ at::BFloat16 max() { return at::BFloat16(0x7F7F, at::BFloat16::from_bits()); }
101
+ static inline __host__ __device__ at::BFloat16 lower_bound() { return at::BFloat16(0xFF80, at::BFloat16::from_bits()); }
102
+ static inline __host__ __device__ at::BFloat16 upper_bound() { return at::BFloat16(0x7F80, at::BFloat16::from_bits()); }
103
+ };
104
+
105
+ template <>
106
+ struct numeric_limits<float> {
107
+ static inline __host__ __device__ float lowest() { return -FLT_MAX; }
108
+ static inline __host__ __device__ float max() { return FLT_MAX; }
109
+ static inline __host__ __device__ float lower_bound() { return -static_cast<float>(inf); }
110
+ static inline __host__ __device__ float upper_bound() { return static_cast<float>(inf); }
111
+ };
112
+
113
+ template <>
114
+ struct numeric_limits<double> {
115
+ static inline __host__ __device__ double lowest() { return -DBL_MAX; }
116
+ static inline __host__ __device__ double max() { return DBL_MAX; }
117
+ static inline __host__ __device__ double lower_bound() { return -inf; }
118
+ static inline __host__ __device__ double upper_bound() { return inf; }
119
+ };
120
+
121
+ } // namespace at
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PeerToPeerAccess.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <c10/macros/Macros.h>
2
+ #include <c10/core/Device.h>
3
+ #include <cstdint>
4
+
5
+ namespace at::cuda {
6
+ namespace detail {
7
+ void init_p2p_access_cache(int64_t num_devices);
8
+ }
9
+
10
+ TORCH_CUDA_CPP_API bool get_p2p_access(c10::DeviceIndex source_dev, c10::DeviceIndex dest_dev);
11
+
12
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PhiloxCudaState.h ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+
5
+ #include <ATen/cuda/detail/PhiloxCudaStateRaw.cuh>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PhiloxUtils.cuh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/PhiloxCudaState.h>
4
+ #include <ATen/cuda/detail/UnpackRaw.cuh>
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/PinnedMemoryAllocator.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <ATen/cuda/CachingHostAllocator.h>
5
+
6
+ namespace at::cuda {
7
+
8
+ inline TORCH_CUDA_CPP_API at::Allocator* getPinnedMemoryAllocator() {
9
+ return getCachingHostAllocator();
10
+ }
11
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ScanUtils.cuh ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ceil_div.h>
4
+ #include <ATen/cuda/DeviceUtils.cuh>
5
+ #include <ATen/cuda/AsmUtils.cuh>
6
+ #include <c10/macros/Macros.h>
7
+
8
+ // Collection of in-kernel scan / prefix sum utilities
9
+
10
+ namespace at::cuda {
11
+
12
+ // Inclusive prefix sum for binary vars using intra-warp voting +
13
+ // shared memory
14
+ template <typename T, bool KillWARDependency, class BinaryFunction>
15
+ __device__ void inclusiveBinaryPrefixScan(T* smem, bool in, T* out, BinaryFunction binop) {
16
+ // Within-warp, we use warp voting.
17
+ #if defined (USE_ROCM)
18
+ unsigned long long int vote = WARP_BALLOT(in);
19
+ T index = __popcll(getLaneMaskLe() & vote);
20
+ T carry = __popcll(vote);
21
+ #else
22
+ T vote = WARP_BALLOT(in);
23
+ T index = __popc(getLaneMaskLe() & vote);
24
+ T carry = __popc(vote);
25
+ #endif
26
+
27
+ int warp = threadIdx.x / C10_WARP_SIZE;
28
+
29
+ // Per each warp, write out a value
30
+ if (getLaneId() == 0) {
31
+ smem[warp] = carry;
32
+ }
33
+
34
+ __syncthreads();
35
+
36
+ // Sum across warps in one thread. This appears to be faster than a
37
+ // warp shuffle scan for CC 3.0+
38
+ if (threadIdx.x == 0) {
39
+ int current = 0;
40
+ for (int i = 0; i < blockDim.x / C10_WARP_SIZE; ++i) {
41
+ T v = smem[i];
42
+ smem[i] = binop(smem[i], current);
43
+ current = binop(current, v);
44
+ }
45
+ }
46
+
47
+ __syncthreads();
48
+
49
+ // load the carry from the preceding warp
50
+ if (warp >= 1) {
51
+ index = binop(index, smem[warp - 1]);
52
+ }
53
+
54
+ *out = index;
55
+
56
+ if (KillWARDependency) {
57
+ __syncthreads();
58
+ }
59
+ }
60
+
61
+ // Exclusive prefix sum for binary vars using intra-warp voting +
62
+ // shared memory
63
+ template <typename T, bool KillWARDependency, class BinaryFunction>
64
+ __device__ void exclusiveBinaryPrefixScan(T* smem, bool in, T* out, T* carry, BinaryFunction binop) {
65
+ inclusiveBinaryPrefixScan<T, false, BinaryFunction>(smem, in, out, binop);
66
+
67
+ // Inclusive to exclusive
68
+ *out -= (T) in;
69
+
70
+ // The outgoing carry for all threads is the last warp's sum
71
+ *carry = smem[at::ceil_div<int>(blockDim.x, C10_WARP_SIZE) - 1];
72
+
73
+ if (KillWARDependency) {
74
+ __syncthreads();
75
+ }
76
+ }
77
+
78
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/Sleep.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Export.h>
3
+ #include <cstdint>
4
+
5
+ namespace at::cuda {
6
+
7
+ // enqueues a kernel that spins for the specified number of cycles
8
+ TORCH_CUDA_CU_API void sleep(int64_t cycles);
9
+
10
+ // flushes instruction cache for ROCm; no-op for CUDA
11
+ TORCH_CUDA_CU_API void flush_icache();
12
+
13
+ } // namespace at::cuda
tool_server/.venv/lib/python3.12/site-packages/torch/include/ATen/cuda/ThrustAllocator.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <c10/cuda/CUDACachingAllocator.h>
5
+
6
+ namespace at::cuda {
7
+
8
+ /// Allocator for Thrust to re-route its internal device allocations
9
+ /// to the THC allocator
10
+ class ThrustAllocator {
11
+ public:
12
+ typedef char value_type;
13
+
14
+ char* allocate(std::ptrdiff_t size) {
15
+ return static_cast<char*>(c10::cuda::CUDACachingAllocator::raw_alloc(size));
16
+ }
17
+
18
+ void deallocate(char* p, size_t size) {
19
+ c10::cuda::CUDACachingAllocator::raw_delete(p);
20
+ }
21
+ };
22
+
23
+ } // namespace at::cuda