BryanW commited on
Commit
631b03a
·
verified ·
1 Parent(s): 204b9ca

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. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/__init__.cpython-312.pyc +0 -0
  2. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/code_template.cpython-312.pyc +0 -0
  3. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/context.cpython-312.pyc +0 -0
  4. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc +0 -0
  5. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc +0 -0
  6. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc +0 -0
  7. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc +0 -0
  8. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-312.pyc +0 -0
  9. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc +0 -0
  10. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/local.cpython-312.pyc +0 -0
  11. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/native_function_generation.cpython-312.pyc +0 -0
  12. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/utils.cpython-312.pyc +0 -0
  13. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/yaml_utils.cpython-312.pyc +0 -0
  14. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__init__.py +0 -0
  15. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/__init__.cpython-312.pyc +0 -0
  16. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc +0 -0
  17. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/fallback_ops.py +194 -0
  18. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/__init__.cpython-312.pyc +0 -0
  19. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/autograd.cpython-312.pyc +0 -0
  20. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/cpp.cpython-312.pyc +0 -0
  21. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/dispatcher.cpython-312.pyc +0 -0
  22. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/functionalization.cpython-312.pyc +0 -0
  23. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/lazy.cpython-312.pyc +0 -0
  24. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/meta.cpython-312.pyc +0 -0
  25. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/native.cpython-312.pyc +0 -0
  26. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/python.cpython-312.pyc +0 -0
  27. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/structured.cpython-312.pyc +0 -0
  28. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/translate.cpython-312.pyc +0 -0
  29. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/ufunc.cpython-312.pyc +0 -0
  30. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/unboxing.cpython-312.pyc +0 -0
  31. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/autograd.py +874 -0
  32. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/meta.py +13 -0
  33. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/python.py +1548 -0
  34. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__init__.py +5 -0
  35. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/__init__.cpython-312.pyc +0 -0
  36. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/signatures.cpython-312.pyc +0 -0
  37. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types.cpython-312.pyc +0 -0
  38. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types_base.cpython-312.pyc +0 -0
  39. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/signatures.py +356 -0
  40. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/types.py +183 -0
  41. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/types_base.py +238 -0
  42. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/__init__.cpython-312.pyc +0 -0
  43. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc +0 -0
  44. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc +0 -0
  45. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/native_functions.cpython-312.pyc +0 -0
  46. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc +0 -0
  47. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/ufunc.cpython-312.pyc +0 -0
  48. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc +0 -0
  49. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc +0 -0
  50. Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc +0 -0
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (575 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/code_template.cpython-312.pyc ADDED
Binary file (4.54 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/context.cpython-312.pyc ADDED
Binary file (5.78 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc ADDED
Binary file (28.3 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc ADDED
Binary file (22.1 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc ADDED
Binary file (50.7 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc ADDED
Binary file (18.6 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-312.pyc ADDED
Binary file (5.3 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc ADDED
Binary file (13.9 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/local.cpython-312.pyc ADDED
Binary file (2.12 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/native_function_generation.cpython-312.pyc ADDED
Binary file (24.3 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/utils.cpython-312.pyc ADDED
Binary file (22.2 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/__pycache__/yaml_utils.cpython-312.pyc ADDED
Binary file (1.43 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__init__.py ADDED
File without changes
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (219 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc ADDED
Binary file (8.75 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/aoti/fallback_ops.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Be extra careful when you edit this file, because it affects AOTInductor ABI compatibility. See
2
+ # https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436
3
+ # for details.
4
+ #
5
+ # The inductor_fallback_ops list is based on the fallback ops from torch/_inductor/lowering.py.
6
+ #
7
+ # Generally speaking, it is ok to add a new op to the list, but you need to run
8
+ # `python torchgen/gen.py --update-aoti-c-shim` in order to regenerate C shim header files.
9
+ # But it is NOT ok to remove an existing fallback op from the list, since that will break
10
+ # some existing AOTInductor-compiled models.
11
+ #
12
+ # A fallback op version defaults to 1. If you want to extend an existing fallback op by adding
13
+ # a new argument with a default value, while it is fine in the Python world, it will be BC-breaking
14
+ # when generating C shim. Thus you need to bump up the version number of that fallback op by
15
+ # updating the entry in the inductor_fallback_ops list, adding a new version number with a list
16
+ # of new arguments, and then run `python torchgen/gen.py --update-aoti-c-shim` to regenerate.
17
+
18
+ inductor_fallback_ops: dict[str, dict[str, list[str]]] = {
19
+ "aten._adaptive_avg_pool2d_backward.default": {},
20
+ "aten._adaptive_avg_pool2d.default": {},
21
+ "aten._adaptive_avg_pool3d_backward.default": {},
22
+ "aten._adaptive_avg_pool3d.default": {},
23
+ "aten._addmm_activation.default": {},
24
+ "aten._cdist_backward.default": {},
25
+ "aten._cdist_forward.default": {},
26
+ "aten._cudnn_rnn.default": {},
27
+ "aten._dyn_quant_matmul_4bit.default": {},
28
+ "aten._dyn_quant_pack_4bit_weight.default": {},
29
+ "aten._efficient_attention_backward.default": {},
30
+ "aten._efficient_attention_forward.default": {},
31
+ "aten._efficientzerotensor.default": {},
32
+ "aten._embedding_bag_dense_backward.default": {},
33
+ "aten._embedding_bag_forward_only.default": {},
34
+ "aten._embedding_bag_per_sample_weights_backward.default": {},
35
+ "aten._embedding_bag.default": {},
36
+ "aten._fft_c2c.default": {},
37
+ "aten._fft_r2c.default": {},
38
+ "aten._flash_attention_backward.default": {},
39
+ "aten._flash_attention_forward.default": {},
40
+ "aten._fused_moving_avg_obs_fq_helper_functional.default": {},
41
+ "aten._fused_moving_avg_obs_fq_helper.default": {},
42
+ "aten._fused_rms_norm.default": {},
43
+ "aten._histogramdd_from_bin_cts.default": {},
44
+ "aten._int_mm.out": {},
45
+ "aten._pdist_backward.default": {},
46
+ "aten._pdist_forward.default": {},
47
+ "aten._scaled_dot_product_attention_math_for_mps.default": {},
48
+ "aten._scaled_dot_product_cudnn_attention_backward.default": {},
49
+ "aten._scaled_dot_product_cudnn_attention.default": {},
50
+ "aten._scaled_dot_product_efficient_attention_backward.default": {},
51
+ "aten._scaled_dot_product_efficient_attention.default": {},
52
+ "aten._scaled_dot_product_flash_attention_backward.default": {},
53
+ "aten._scaled_dot_product_flash_attention_for_cpu_backward.default": {},
54
+ "aten._scaled_dot_product_flash_attention_for_cpu.default": {},
55
+ "aten._scaled_dot_product_flash_attention.default": {},
56
+ "aten._scaled_dot_product_fused_attention_overrideable_backward.default": {},
57
+ "aten._scaled_dot_product_fused_attention_overrideable.default": {},
58
+ "aten._scaled_mm.default": {},
59
+ "aten._scaled_grouped_mm.default": {},
60
+ "aten._scaled_mm.out": {},
61
+ "aten._segment_reduce_backward.default": {},
62
+ "aten._thnn_fused_lstm_cell.default": {},
63
+ "aten._to_sparse.default": {},
64
+ "aten._trilinear.default": {},
65
+ "aten._weight_int4pack_mm.default": {},
66
+ "aten._weight_int8pack_mm.default": {},
67
+ "aten.abs.default": {},
68
+ "aten.adaptive_max_pool2d_backward.default": {},
69
+ "aten.adaptive_max_pool2d.default": {},
70
+ "aten.adaptive_max_pool3d_backward.default": {},
71
+ "aten.adaptive_max_pool3d.default": {},
72
+ "aten.add.Scalar": {},
73
+ "aten.add.Tensor": {},
74
+ "aten.addbmm.default": {},
75
+ "aten.addmm.out": {},
76
+ "aten.addmv.default": {},
77
+ "aten.angle.default": {},
78
+ "aten.avg_pool2d_backward.default": {},
79
+ "aten.avg_pool2d.default": {},
80
+ "aten.avg_pool3d_backward.default": {},
81
+ "aten.avg_pool3d.default": {},
82
+ "aten.baddbmm.out": {},
83
+ "aten.bernoulli_.float": {},
84
+ "aten.bernoulli_.Tensor": {},
85
+ "aten.bmm.out": {},
86
+ "aten.bucketize.Tensor": {},
87
+ "aten.cat.default": {},
88
+ "aten.cholesky_inverse.default": {},
89
+ "aten.cholesky_solve.default": {},
90
+ "aten.convolution_backward.default": {},
91
+ "aten.convolution.default": {},
92
+ "aten.cummax.default": {},
93
+ "aten.cummin.default": {},
94
+ "aten.cumprod.default": {},
95
+ "aten.cumsum.default": {},
96
+ "aten.exponential.default": {},
97
+ "aten.fill_.Scalar": {},
98
+ "aten.fractional_max_pool2d_backward.default": {},
99
+ "aten.fractional_max_pool2d.default": {},
100
+ "aten.fractional_max_pool3d_backward.default": {},
101
+ "aten.fractional_max_pool3d.default": {},
102
+ "aten.gcd.default": {},
103
+ "aten.geqrf.default": {},
104
+ "aten.grid_sampler_2d_backward.default": {},
105
+ "aten.hann_window.default": {},
106
+ "aten.histc.default": {},
107
+ "aten.histogram.bin_ct": {},
108
+ "aten.index_put.default": {},
109
+ "aten.index_reduce.default": {},
110
+ "aten.index.Tensor": {},
111
+ "aten.kthvalue.default": {},
112
+ "aten.logcumsumexp.default": {},
113
+ "aten.lu_unpack.default": {},
114
+ "aten.masked_scatter_backward.default": {},
115
+ "aten.masked_scatter.default": {},
116
+ "aten.masked_select.default": {},
117
+ "aten.max_pool2d_with_indices_backward.default": {},
118
+ "aten.max_pool2d_with_indices.default": {},
119
+ "aten.max_pool3d_with_indices_backward.default": {},
120
+ "aten.max_pool3d_with_indices.default": {},
121
+ "aten.max_unpool2d.default": {},
122
+ "aten.max_unpool3d.default": {},
123
+ "aten.median.default": {},
124
+ "aten.mm.out": {},
125
+ "aten.mode.default": {},
126
+ "aten.mul.Scalar": {},
127
+ "aten.mul.Tensor": {},
128
+ "aten.nanmedian.default": {},
129
+ "aten.narrow.default": {},
130
+ "aten.native_dropout.default": {},
131
+ "aten.nonzero.default": {},
132
+ "aten.normal_functional.default": {},
133
+ "aten.ormqr.default": {},
134
+ "aten.pad.default": {},
135
+ "aten.permute.default": {},
136
+ "aten.polar.default": {},
137
+ "aten.pow.Scalar": {},
138
+ "aten.pow.Tensor_Scalar": {},
139
+ "aten.pow.Tensor_Tensor": {},
140
+ "aten.rand.default": {},
141
+ "aten.rand.generator": {},
142
+ "aten.randint.default": {},
143
+ "aten.randint.generator": {},
144
+ "aten.randint.low_out": {},
145
+ "aten.randint.low": {},
146
+ "aten.randn.default": {},
147
+ "aten.randn.generator": {},
148
+ "aten.randperm.default": {},
149
+ "aten.repeat_interleave.Tensor": {},
150
+ "aten.replication_pad1d_backward.default": {},
151
+ "aten.replication_pad2d_backward.default": {},
152
+ "aten.reshape.default": {},
153
+ "aten.resize_.default": {},
154
+ "aten.resize_as_.default": {},
155
+ "aten.scatter_reduce.two_out": {},
156
+ "aten.scatter.src_out": {},
157
+ "aten.scatter.value_out": {},
158
+ "aten.searchsorted.Scalar": {},
159
+ "aten.searchsorted.Tensor": {},
160
+ "aten.segment_reduce.default": {},
161
+ "aten.set_.source_Tensor": {},
162
+ "aten.slice.Tensor": {},
163
+ "aten.soft_margin_loss_backward.default": {},
164
+ "aten.sort.default": {},
165
+ "aten.sort.stable": {},
166
+ "aten.squeeze.dim": {},
167
+ "aten.to_sparse.default": {},
168
+ "aten.topk.default": {},
169
+ "aten.triangular_solve.default": {},
170
+ "aten.uniform.default": {},
171
+ "aten.upsample_bicubic2d_backward.default": {},
172
+ "aten.upsample_linear1d_backward.default": {},
173
+ "aten.upsample_trilinear3d_backward.default": {},
174
+ "aten.view_as_complex.default": {},
175
+ "aten.view_as_real.default": {},
176
+ "aten.view.dtype": {},
177
+ "aten._weight_int4pack_mm_with_scales_and_zeros.default": {},
178
+ }
179
+
180
+ # `python torchgen/gen.py --update-aoti-c-shim` will automatically generate
181
+ # c_shim_aten.{h/cpp} based on the list below.
182
+ # Operators in this list are intended to be used in torch/csrc/stable/ops.h
183
+ # Unlike other c_shims, operators in this file do not bypass the dispatcher.
184
+ # The same BC rules apply as inductor_fallback_ops.
185
+ aten_shimified_ops: dict[str, dict[str, list[str]]] = {
186
+ "aten.fill_.Scalar": {},
187
+ "aten.pad.default": {},
188
+ "aten.narrow.default": {},
189
+ "aten.amax.default": {},
190
+ "aten.new_empty.default": {},
191
+ "aten.new_zeros.default": {},
192
+ "aten.full.default": {},
193
+ "aten.subtract.Tensor": {},
194
+ }
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (218 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/autograd.cpython-312.pyc ADDED
Binary file (29.6 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/cpp.cpython-312.pyc ADDED
Binary file (17.2 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/dispatcher.cpython-312.pyc ADDED
Binary file (3.94 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/functionalization.cpython-312.pyc ADDED
Binary file (6.43 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/lazy.cpython-312.pyc ADDED
Binary file (17.9 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/meta.cpython-312.pyc ADDED
Binary file (608 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/native.cpython-312.pyc ADDED
Binary file (5.45 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/python.cpython-312.pyc ADDED
Binary file (49.5 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/structured.cpython-312.pyc ADDED
Binary file (6.93 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/translate.cpython-312.pyc ADDED
Binary file (15.6 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/ufunc.cpython-312.pyc ADDED
Binary file (7.3 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/unboxing.cpython-312.pyc ADDED
Binary file (7.04 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/autograd.py ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import cast, TYPE_CHECKING
6
+
7
+ from torchgen import local
8
+ from torchgen.api import cpp
9
+ from torchgen.api.types import BaseCType, Binding, NamedCType, tensorListT
10
+ from torchgen.model import (
11
+ BaseTy,
12
+ BaseType,
13
+ FunctionSchema,
14
+ ListType,
15
+ NativeFunction,
16
+ NativeFunctionsViewGroup,
17
+ SchemaKind,
18
+ Type,
19
+ )
20
+ from torchgen.utils import IDENT_REGEX
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Sequence
25
+
26
+
27
+ # Represents a saved attribute involved in backward calculation.
28
+ # Note that it can be a derived property of an input argument, e.g.:
29
+ # we could save `other.scalar_type()` instead of the entire `other` tensor.
30
+ @dataclass(frozen=True)
31
+ class SavedAttribute:
32
+ # The NamedCType holds the updated name and cpp type of the attribute
33
+ # for the name, Suffix is appended if it's derived property, e.g.: `other_scalar_type`
34
+ nctype: NamedCType
35
+
36
+ # The expression to read the derived property at save time, e.g.:
37
+ # `other.scalar_type()`.
38
+ expr: str
39
+
40
+
41
+ # Represents a backward formula that calculates derivatives for one
42
+ # or more tensors.
43
+ @dataclass(frozen=True)
44
+ class Derivative:
45
+ # The formula string (legit C++ expression).
46
+ # Note that expressions against input arguments have been replaced with the
47
+ # corresponding saved attributes.
48
+ # E.g.:
49
+ # raw formula: `mul_tensor_backward(grad, self, other.scalar_type())`
50
+ # here: `mul_tensor_backward(grad, self, other_scalar_type)`
51
+ formula: str
52
+
53
+ # The formula string before input argument replacement
54
+ original_formula: str
55
+
56
+ # Names of the arguments for which this formula calculates derivatives.
57
+ var_names: tuple[str, ...]
58
+
59
+ # Saved inputs that are referenced by the formula.
60
+ saved_inputs: tuple[SavedAttribute, ...]
61
+
62
+ # Saved outputs that are referenced by the formula.
63
+ saved_outputs: tuple[SavedAttribute, ...]
64
+
65
+ # Gradients that are referenced by name in the formula.
66
+ named_gradients: set[str]
67
+
68
+
69
+ # Represents a forward formula that calculates forward derivatives
70
+ # for one tensor.
71
+ @dataclass(frozen=True)
72
+ class ForwardDerivative:
73
+ # The formula string (legit C++ expression).
74
+ # Note that special keywords such as "linear" or "element_wise" have been
75
+ # replaced by the automatically generated formula.
76
+ formula: str
77
+
78
+ # Name of the output arguments for which this formula calculates forward
79
+ # derivatives
80
+ var_names: tuple[str, ...]
81
+
82
+ # Type of the output arguments for which this formula calculates forward
83
+ # derivatives
84
+ var_types: tuple[Type, ...]
85
+
86
+ # Inputs for which the forward derivatives are required for this formula
87
+ required_inputs_fw_grad: tuple[str, ...] | None
88
+
89
+ # Inputs for which the primal is required for this formula
90
+ required_inputs_primal: tuple[str, ...] | None
91
+
92
+ # Flag to specify if this formula requires the original value of self
93
+ # This is only used by inplace operations
94
+ required_original_self_value: bool
95
+
96
+ # If this formula is specified in derivatives.yaml or if we are reusing the
97
+ # out of place formula for inplace
98
+ is_reusing_outplace_formula: bool
99
+
100
+
101
+ # Represents differentiability info for a NativeFunction.
102
+ @dataclass(frozen=True)
103
+ class DifferentiabilityInfo:
104
+ # The base name read from derivatives.yaml.
105
+ name: str
106
+
107
+ # The matching native function.
108
+ #
109
+ # There can be multiple NativeFunction having the same base name:
110
+ # - different overloads with different types of input arguments;
111
+ # - in-place/out/functional variants of the same function;
112
+ #
113
+ # We first use the schema string (under the 'name' key) in derivatives.yaml
114
+ # to find the NativeFunction having the same schema string.
115
+ # Then we find the in-place/out/functional variants of the matching function.
116
+ # Among these variants, we choose the one having the same name as the
117
+ # derivatives.yaml entry. If there is no exact match, then we choose the
118
+ # in-place variant.
119
+ # TODO: maybe the logic to search for all variants is no longer necessary?
120
+ func: NativeFunction
121
+
122
+ # The name of the generated autograd function.
123
+ # It's set only if we will calculate a derivative, i.e.
124
+ # 'args_with_derivatives' is not empty.
125
+ op: str | None
126
+
127
+ # The derivatives formulae for this function.
128
+ # Note that the length of this sequence is the number of differentiable inputs
129
+ derivatives: Sequence[Derivative]
130
+
131
+ # The forward derivatives formulae for this function.
132
+ # Note that the length of this sequence is the number of differentiable outputs
133
+ forward_derivatives: Sequence[ForwardDerivative]
134
+
135
+ # The union of 'saved_inputs' of all 'derivatives'.
136
+ all_saved_inputs: Sequence[SavedAttribute]
137
+
138
+ # The union of 'saved_outputs' of all 'derivatives'.
139
+ all_saved_outputs: Sequence[SavedAttribute]
140
+
141
+ # All named gradients that are available for use, in the same
142
+ # order as in the grads vector.
143
+ available_named_gradients: Sequence[str]
144
+
145
+ # The named gradients that are used in any of the derivatives.
146
+ # Invariant: all(name in available_named_gradients for name in used_named_gradients)
147
+ used_named_gradients: set[str]
148
+
149
+ # The function's input arguments for which it calculates derivatives.
150
+ # It's the union of 'var_names' of all 'derivatives', sorted by the
151
+ # argument order in the function schema.
152
+ args_with_derivatives: Sequence[Binding]
153
+
154
+ # Names of arguments whose derivative formula is 'non_differentiable'.
155
+ non_differentiable_arg_names: Sequence[str]
156
+
157
+ # Raw data read from derivatives.yaml.
158
+ output_differentiability: list[bool] | None
159
+
160
+ # output_differentiability in derivatives.yaml can be a list of
161
+ # conditions that express if the output is differentiable. In this case,
162
+ # the number of conditions must match the number of outputs
163
+ # (NB: we only support one condition right now).
164
+ # output_differentiability gets populated with True for each condition,
165
+ # while output_differentiability_conditions gets populated with the conditions
166
+ output_differentiability_conditions: list[str] | None
167
+
168
+ @property
169
+ def has_derivatives(self) -> bool:
170
+ return len(self.args_with_derivatives) > 0
171
+
172
+ # Generates a new DifferentiabilityInfo using the exact same set of derivative information,
173
+ # but with a new operator name.
174
+ # This is used when generating "copy" variants of view ops,
175
+ # which are able to use the exact same derivative formula as the original view op
176
+ # See Note [Codegen'd {view}_copy Operators]
177
+ def create_view_copy_from_view_derivative(
178
+ self, g: NativeFunctionsViewGroup
179
+ ) -> DifferentiabilityInfo | None:
180
+ if g.view_copy is None:
181
+ return None
182
+ f = g.view_copy
183
+
184
+ name_split_by_period = self.name.split(".", maxsplit=2)
185
+ # Append a "_copy" to the base name of the operator (but keep the overload name the same)
186
+ view_copy_name = f"{name_split_by_period[0]}_copy." + ".".join(
187
+ name_split_by_period[1:]
188
+ )
189
+ view_copy_op_name = None if self.op is None else f"{self.op}_copy"
190
+
191
+ return DifferentiabilityInfo(
192
+ # Use the "_copy" version of name/func/op
193
+ name=view_copy_name,
194
+ func=f,
195
+ op=view_copy_op_name,
196
+ # But keep all derivative info the same
197
+ derivatives=self.derivatives,
198
+ forward_derivatives=self.forward_derivatives,
199
+ all_saved_inputs=self.all_saved_inputs,
200
+ all_saved_outputs=self.all_saved_outputs,
201
+ available_named_gradients=self.available_named_gradients,
202
+ used_named_gradients=self.used_named_gradients,
203
+ args_with_derivatives=self.args_with_derivatives,
204
+ non_differentiable_arg_names=self.non_differentiable_arg_names,
205
+ output_differentiability=self.output_differentiability,
206
+ output_differentiability_conditions=self.output_differentiability_conditions,
207
+ )
208
+
209
+
210
+ def uses_ident(info: DifferentiabilityInfo | None, ident: str) -> bool:
211
+ if info is None:
212
+ return False
213
+ for derivative in info.derivatives:
214
+ formula = derivative.formula
215
+ if re.search(IDENT_REGEX.format(ident), formula):
216
+ return True
217
+ return False
218
+
219
+
220
+ def uses_retain_variables(info: DifferentiabilityInfo | None) -> bool:
221
+ return uses_ident(info, "retain_variables")
222
+
223
+
224
+ def uses_single_grad(info: DifferentiabilityInfo | None) -> bool:
225
+ return uses_ident(info, "grad")
226
+
227
+
228
+ # Represents a differentiable `Argument`.
229
+ # How is it different from the `Argument` type?
230
+ # - It's processed Arguments which are differentiable and only used in the
231
+ # context of the autograd codegen;
232
+ # - It can represent SelfArgument or regular Argument but not TensorOptionsArgument;
233
+ @dataclass(frozen=True)
234
+ class DifferentiableInput:
235
+ name: str
236
+ type: Type
237
+
238
+ # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
239
+ cpp_type: str
240
+
241
+
242
+ # Represents a differentiable `Return`.
243
+ # How it it different from the `Return` type?
244
+ # - The name in `Return` is optional. Here it is always populated using the same
245
+ # `cpp.return_names()` method.
246
+ # TODO: some cpp naming logic (e.g. resolving name conflict) might be irrelevant?
247
+ # - It's processed Returns which are differentiable, in compliance with the
248
+ # `output_differentiability` field defined in derivatives.yaml (if specified),
249
+ # and are only used in the context of the autograd codegen;
250
+ @dataclass(frozen=True)
251
+ class DifferentiableOutput:
252
+ name: str
253
+ type: Type
254
+
255
+ # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
256
+ cpp_type: str
257
+
258
+
259
+ @dataclass(frozen=True)
260
+ class NativeFunctionWithDifferentiabilityInfo:
261
+ func: NativeFunction
262
+ info: dict[str, DifferentiabilityInfo] | None
263
+ fw_derivatives: dict[str, Sequence[ForwardDerivative]] | None
264
+
265
+
266
+ # TODO: Update comment below since it is out of date.
267
+ def dispatch_strategy(fn: NativeFunctionWithDifferentiabilityInfo) -> str:
268
+ """How are we going to call the underlying implementation of a
269
+ declaration? There are two strategies:
270
+ - use_derived: we want to call the implementation on CPUDoubleType
271
+ (or a similar, derived Type instance). Because these derived
272
+ instances deal in Tensors, not Variables (it's a completely different
273
+ object, so it doesn't dispatch back to VariableType), code on
274
+ this dispatch path needs to wrap/unwrap tensors. If the
275
+ derived implementation takes and returns tensors, the
276
+ implementation is usually differentiable (although we also use
277
+ the derived dispatch path for non-differentiable functions
278
+ that we still want to dispatch on the derived Type instance;
279
+ e.g., size())
280
+ - use_type: we want to call the implementation on Type, because
281
+ it is implemented concretely, and the functions it invokes will
282
+ get dispatched back to VariableType (which will ensure that they
283
+ are differentiable.)
284
+ """
285
+ # fn is derived as long as any of its per-key differentiability infos
286
+ # has_derivatives. dispatch_strategy() is used to guard generation of fns in VariableType
287
+ # and ADInplaceOrViewType. We want to generate these functions as long as a
288
+ # derivative is defined for ANY dispatch key.
289
+ if fn.func.is_abstract or (
290
+ fn.info is not None and any(info.has_derivatives for info in fn.info.values())
291
+ ):
292
+ # If the function is abstract (not implemented on at::Type), we must
293
+ # call the implementation on the derived type with unpacked tensors.
294
+
295
+ # If the function has a derivative specified and is concrete, we could
296
+ # call either implementation. We prefer the calling the derived
297
+ # type's implementation with unpacked tensors because it is more
298
+ # performant in some cases: any internal calls to other ATen functions
299
+ # won't have the history tracked.
300
+
301
+ # If the function has a type dispatched argument (i.e. is a factory),
302
+ # we prefer calling the derived type's implementation both because it is
303
+ # more performant and to ensure factory functions return tensors with _version
304
+ # of 0 (probably not strictly necessary, but nice to have to keeps versions simple
305
+ # to understand.
306
+
307
+ return "use_derived"
308
+ else:
309
+ # If the function is concrete (we don't have to override it) and we
310
+ # didn't declare it in derivatives.yaml, we'll assume that it is
311
+ # actually implemented out of differentiable functions. (This
312
+ # assumption might not hold, but then you'll see gradcheck fail.)
313
+ return "use_type"
314
+
315
+
316
+ def is_foreach_func(f: NativeFunction) -> bool:
317
+ return f.func.name.name.base.startswith("_foreach_")
318
+
319
+
320
+ # note(crcrpar): Most foreach functions can reference an out-place `torch` function whose schema kind
321
+ # is functional for their backward derivatives (and forward derivatives in the future), i.e.,
322
+ # they would find such one in `functional_info_by_signature`. There however are some exceptions:
323
+ _foreach_with_inplace_ref = {"_foreach_zero_"}
324
+ _foreach_with_tensor_overload = {
325
+ "_foreach_add.Tensor",
326
+ "_foreach_mul.Tensor",
327
+ "_foreach_div.Tensor",
328
+ }
329
+ # The following do not support the alpha kwarg, which the nonforeach versions support.
330
+ _skip_argument_len_check = {
331
+ "_foreach_add.Scalar",
332
+ "_foreach_add_.Scalar",
333
+ "_foreach_add.ScalarList",
334
+ "_foreach_add_.ScalarList",
335
+ "_foreach_sub.Scalar",
336
+ "_foreach_sub_.Scalar",
337
+ "_foreach_sub.ScalarList",
338
+ "_foreach_sub_.ScalarList",
339
+ }
340
+
341
+
342
+ # Checks if `function_schema` is a native, non-foreach function which `f`, a foreach function
343
+ # reference to generate derivatives.
344
+ def is_reference_for_foreach(
345
+ f: NativeFunction,
346
+ function_schema: FunctionSchema,
347
+ ) -> bool:
348
+ return (
349
+ f.func.name.name.base.split("_foreach_")[-1] == function_schema.name.name.base
350
+ and (
351
+ not function_schema.name.name.inplace
352
+ or str(f.func.name) in _foreach_with_inplace_ref
353
+ )
354
+ and (
355
+ str(f.func.name) in _skip_argument_len_check
356
+ or len(f.func.arguments.flat_non_out)
357
+ == len(function_schema.arguments.flat_non_out)
358
+ )
359
+ and all(
360
+ ref_arg.type in (arg.type, getattr(arg.type, "elem", None))
361
+ for arg, ref_arg in zip(
362
+ f.func.arguments.flat_non_out,
363
+ function_schema.arguments.flat_non_out,
364
+ )
365
+ )
366
+ )
367
+
368
+
369
+ # TODO(crcrpar): Avoid hard coding "Default" ideally.
370
+ def gen_foreach_derivativeinfo(
371
+ foreach_function: NativeFunction,
372
+ functional_info_by_signature: dict[
373
+ FunctionSchema, dict[str, DifferentiabilityInfo]
374
+ ],
375
+ non_functional_info_by_signature: dict[
376
+ FunctionSchema, dict[str, DifferentiabilityInfo]
377
+ ],
378
+ dispatch_key: str = "Default",
379
+ ) -> tuple[DifferentiabilityInfo | None, bool]:
380
+ """Generate DifferentiabilityInfo for out-place foreach function, return the existing one for in-place.
381
+
382
+ The second return value indicates whether the info is generated in this function.
383
+ """
384
+ ref_diff_info: DifferentiabilityInfo | None = None
385
+
386
+ for function_schema, diff_info in functional_info_by_signature.items():
387
+ if not is_reference_for_foreach(foreach_function, function_schema):
388
+ continue
389
+ ref_diff_info = diff_info[dispatch_key]
390
+ if ref_diff_info is not None:
391
+ break
392
+ # note(crcrpar): It seems like `zero`'s info isn't available in functional_info_by_signature
393
+ # while the info of `zero_` is in non_functional_info_by_signature
394
+ if (
395
+ ref_diff_info is None
396
+ and foreach_function.func.kind() == SchemaKind.inplace
397
+ and str(foreach_function.func.name) in _foreach_with_inplace_ref
398
+ ):
399
+ for function_schema, diff_info in non_functional_info_by_signature.items():
400
+ if not is_reference_for_foreach(foreach_function, function_schema):
401
+ continue
402
+ ref_diff_info = diff_info[dispatch_key]
403
+ if ref_diff_info is not None:
404
+ break
405
+ if ref_diff_info is None:
406
+ return None, False
407
+
408
+ # non out-place uses the existing Derivative.
409
+ if foreach_function.func.kind() == SchemaKind.inplace:
410
+ return ref_diff_info, False
411
+
412
+ map_refarg2foreacharg, map_name2arg = {}, {}
413
+ for i, (arg, ref_arg) in enumerate(
414
+ zip(
415
+ foreach_function.func.arguments.flat_non_out,
416
+ function_schema.arguments.flat_non_out,
417
+ )
418
+ ):
419
+ map_refarg2foreacharg[ref_arg.name] = arg.name
420
+ map_name2arg[arg.name] = arg
421
+
422
+ all_saved_inputs, all_saved_outputs, all_var_names = [], [], []
423
+ modified_derivative_formulas = []
424
+ for i, derivative in enumerate(ref_diff_info.derivatives):
425
+ modified_formula = derivative.formula.replace("grad", "grads[i]").replace(
426
+ "result", "result[i]"
427
+ )
428
+ saved_inputs, saved_outputs = [], []
429
+ # note(crcrpar): This context seems necessary to call `cpp.argument_type`
430
+ with local.parametrize(
431
+ use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
432
+ use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
433
+ ):
434
+ for ref_input in derivative.saved_inputs:
435
+ ref_input_jit_name = ref_input.expr.split(".")[0]
436
+ mapped_name = map_refarg2foreacharg[ref_input_jit_name]
437
+ if isinstance(map_name2arg[mapped_name].type, ListType):
438
+ mapped_expr = mapped_name + "[i]"
439
+ else:
440
+ mapped_expr = mapped_name
441
+ new_expr = ref_input.expr.replace(ref_input_jit_name, mapped_expr)
442
+ modified_formula = modified_formula.replace(
443
+ cast(str, ref_input.nctype.name), new_expr
444
+ )
445
+
446
+ nctype = cpp.argument_type(map_name2arg[mapped_name], binds=mapped_name)
447
+ canonical_nctype = NamedCType(
448
+ nctype.name, nctype.type.remove_const_ref()
449
+ )
450
+ saved_inputs.append(
451
+ SavedAttribute(nctype=canonical_nctype, expr=mapped_name)
452
+ )
453
+ for ref_output in derivative.saved_outputs:
454
+ if ref_output.nctype.name == "result":
455
+ saved_outputs.append(
456
+ SavedAttribute(
457
+ nctype=NamedCType(
458
+ name="result", type=BaseCType(tensorListT)
459
+ ),
460
+ expr="result",
461
+ )
462
+ )
463
+ else:
464
+ raise RuntimeError("")
465
+ var_names = [map_refarg2foreacharg[var] for var in derivative.var_names]
466
+ all_var_names.extend(var_names)
467
+ all_saved_inputs.extend(saved_inputs)
468
+ all_saved_outputs.extend(saved_outputs)
469
+ modified_derivative = Derivative(
470
+ formula=modified_formula,
471
+ original_formula=derivative.formula,
472
+ var_names=tuple(var_names),
473
+ saved_inputs=tuple(saved_inputs),
474
+ saved_outputs=tuple(saved_outputs),
475
+ named_gradients=set(),
476
+ )
477
+ modified_derivative_formulas.append(modified_derivative)
478
+
479
+ with local.parametrize(
480
+ use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
481
+ use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
482
+ ):
483
+ args_with_derivatives = [
484
+ Binding(
485
+ name=arg.name,
486
+ nctype=cpp.argument_type(arg, binds=arg.name),
487
+ argument=arg,
488
+ default=None,
489
+ )
490
+ for arg in foreach_function.func.arguments.flat_non_out
491
+ if arg.name in all_var_names
492
+ ]
493
+
494
+ forward_derivatives: list[ForwardDerivative] = []
495
+ fw_derivative: ForwardDerivative
496
+ for fw_derivative in ref_diff_info.forward_derivatives:
497
+ var_names: list[str] = list(fw_derivative.var_names) # type: ignore[no-redef]
498
+ var_types: list[Type] = list(fw_derivative.var_types)
499
+ required_inputs_fw_grad: list[str] = []
500
+ required_inputs_primal: list[str] = []
501
+ if fw_derivative.required_inputs_fw_grad is not None:
502
+ required_inputs_fw_grad = list(fw_derivative.required_inputs_fw_grad)
503
+ if fw_derivative.required_inputs_primal:
504
+ required_inputs_primal = list(fw_derivative.required_inputs_primal)
505
+ modified_formula = fw_derivative.formula
506
+
507
+ # Foreach's result is TensorList
508
+ if "result" in modified_formula:
509
+ modified_formula = fw_derivative.formula.replace("result", "result[i]")
510
+
511
+ for foreach_arg, ref_arg in zip(
512
+ foreach_function.func.arguments.flat_non_out,
513
+ ref_diff_info.func.func.arguments.flat_non_out,
514
+ ):
515
+ # Modify reference forward formula
516
+ if (
517
+ isinstance(foreach_arg.type, ListType)
518
+ and not foreach_arg.type.is_tensor_like()
519
+ ):
520
+ # Assuming ScalarList
521
+ modified_formula = modified_formula.replace(
522
+ ref_arg.name, foreach_arg.name + "[i]"
523
+ )
524
+ elif foreach_arg.type.is_tensor_like():
525
+ # Assuming TensorList / Tensor
526
+ # assert isinstance(foreach_arg.type, ListType), f"{foreach_function.func.name}, {foreach_arg.type}"
527
+ assert isinstance(foreach_arg.type, ListType) or (
528
+ foreach_arg.type == BaseType(BaseTy.Tensor)
529
+ and str(foreach_function.func.name) in _foreach_with_tensor_overload
530
+ ), f"{foreach_function.func.name}, {foreach_arg.type}"
531
+ for suffix in ("_p", "_t"):
532
+ curr_expr = ref_arg.name + suffix
533
+ if curr_expr in modified_formula:
534
+ new_expr = foreach_arg.name + suffix
535
+ modified_formula = modified_formula.replace(curr_expr, new_expr)
536
+ else:
537
+ # Assuming Scalar
538
+ if foreach_arg.name != ref_arg.name:
539
+ modified_formula = modified_formula.replace(
540
+ ref_arg.name, foreach_arg.name
541
+ )
542
+
543
+ # note(crcrpar): there should exist a cooler way...
544
+ for i, name in enumerate(var_names):
545
+ if name == ref_arg.name:
546
+ var_names[i] = foreach_arg.name
547
+ var_types[i] = foreach_arg.type
548
+ for i, name in enumerate(required_inputs_fw_grad):
549
+ if name == ref_arg.name:
550
+ required_inputs_fw_grad[i] = foreach_arg.name
551
+ for i, name in enumerate(required_inputs_primal):
552
+ if name == ref_arg.name:
553
+ required_inputs_primal[i] = foreach_arg.name
554
+ forward_derivatives.append(
555
+ ForwardDerivative(
556
+ formula=modified_formula,
557
+ var_names=tuple(var_names),
558
+ var_types=tuple(var_types),
559
+ required_inputs_fw_grad=tuple(required_inputs_fw_grad),
560
+ required_inputs_primal=tuple(required_inputs_primal),
561
+ required_original_self_value=fw_derivative.required_original_self_value,
562
+ is_reusing_outplace_formula=fw_derivative.is_reusing_outplace_formula,
563
+ )
564
+ )
565
+
566
+ return (
567
+ DifferentiabilityInfo(
568
+ name=foreach_function.func.name.name.base,
569
+ func=foreach_function,
570
+ op=f"Foreach{ref_diff_info.op}{foreach_function.func.name.overload_name}",
571
+ derivatives=modified_derivative_formulas,
572
+ forward_derivatives=forward_derivatives,
573
+ all_saved_inputs=tuple(set(all_saved_inputs)),
574
+ all_saved_outputs=tuple(set(all_saved_outputs)),
575
+ available_named_gradients=(),
576
+ used_named_gradients=set(),
577
+ args_with_derivatives=args_with_derivatives,
578
+ non_differentiable_arg_names=[],
579
+ output_differentiability=None,
580
+ output_differentiability_conditions=None,
581
+ ),
582
+ True,
583
+ )
584
+
585
+
586
+ def match_differentiability_info(
587
+ native_functions: list[NativeFunction],
588
+ differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
589
+ ) -> list[NativeFunctionWithDifferentiabilityInfo]:
590
+ """Sets the "derivative" key on declarations to matching autograd function
591
+ In-place functions will use the out-of-place derivative definition if there
592
+ is no in-place specific derivative.
593
+ """
594
+
595
+ functional_info_by_signature = {
596
+ schema.signature(strip_default=True): info_dict
597
+ for schema, info_dict in differentiability_infos.items()
598
+ if schema.kind() == SchemaKind.functional
599
+ }
600
+ non_functional_info_by_signature = {
601
+ schema.signature(strip_default=True): info_dict
602
+ for schema, info_dict in differentiability_infos.items()
603
+ if schema.kind() != SchemaKind.functional
604
+ }
605
+
606
+ def find_info(
607
+ f: NativeFunction,
608
+ ) -> tuple[dict[str, DifferentiabilityInfo] | None, bool]:
609
+ # Don't bother matching info to generated out= variants
610
+ if "generated" in f.tags and f.func.kind() == SchemaKind.out:
611
+ return None, False
612
+
613
+ # (1) Check for an exact match
614
+ if f.func in differentiability_infos:
615
+ return differentiability_infos[f.func], True
616
+
617
+ # (2) If no exact match, check if the out-of-place variant
618
+ # of this operator has a match.
619
+ # i.e mul() for mul_() or mul_out()
620
+ # note(crcrpar): Check foreach or not because in-place foreach functions use backward defined for the existing
621
+ # native functions instead of the out-place counterparts.
622
+ f_sig = f.func.signature(strip_default=True)
623
+ if f_sig in functional_info_by_signature and not is_foreach_func(f):
624
+ return functional_info_by_signature[f_sig], False
625
+
626
+ # (3) Some operators have a derivative explicitly defined for the mutable
627
+ # variant, but get a code-generated out-of-place variant which does *not*
628
+ # come with a derivative formula.
629
+ # For the generated out-of-place variant, use the mutable variant's formula
630
+ # if it exists.
631
+ if "generated" in f.tags and f_sig in non_functional_info_by_signature:
632
+ info_dict = non_functional_info_by_signature[f_sig]
633
+ # See https://github.com/pytorch/pytorch/pull/76320/files#r874816389
634
+ assert not any(
635
+ any("self" in str(input.nctype.name) for input in info.all_saved_inputs)
636
+ for info in info_dict.values()
637
+ ), f"""\
638
+ Attempted to convert a derivative formula for a mutable operator
639
+ to be used by automatically by its functional variant ("{str(f.func)}").
640
+ this is not currently supported (we'd need to fix up the formula in the codegen)."""
641
+ return info_dict, False
642
+
643
+ # (4) Generate derivative information of foreach functions if none is defined in `derivatives.yaml`
644
+ if is_foreach_func(f):
645
+ assert f.func not in differentiability_infos
646
+ diff_info, is_generated = gen_foreach_derivativeinfo(
647
+ f,
648
+ functional_info_by_signature,
649
+ non_functional_info_by_signature,
650
+ )
651
+ if diff_info is None:
652
+ return None, False
653
+ # TODO(crcrpar): Avoid hard coding "Default" ideally.
654
+ diff_info_dict = {"Default": diff_info}
655
+ if is_generated:
656
+ differentiability_infos[f.func] = diff_info_dict
657
+ functional_info_by_signature[f.func] = diff_info_dict
658
+ return diff_info_dict, is_generated
659
+
660
+ return None, False
661
+
662
+ result: list[NativeFunctionWithDifferentiabilityInfo] = []
663
+ for f in native_functions:
664
+ info_dict, is_exact_match = find_info(f)
665
+
666
+ # Currently, the '.strides()' to 'strides_or_error' replacement does not support
667
+ # 'self' derivatives of an inplace function, so we must check for this case.
668
+ if f.func.kind() == SchemaKind.inplace and (info_dict is not None):
669
+ for info in info_dict.values():
670
+ for derivative in info.derivatives:
671
+ if "self" in derivative.var_names:
672
+ for saved_input in derivative.saved_inputs:
673
+ assert "strides_or_error" not in saved_input.expr, (
674
+ "Calling '.strides()' in the 'self' derivative formula of an "
675
+ f"in-place function is not supported: {f.func}"
676
+ )
677
+
678
+ if not info_dict:
679
+ result.append(
680
+ NativeFunctionWithDifferentiabilityInfo(
681
+ func=f, info=None, fw_derivatives=None
682
+ )
683
+ )
684
+ continue
685
+
686
+ fw_derivative_dict: dict[str, Sequence[ForwardDerivative]] = {}
687
+ for key, info in info_dict.items():
688
+ if not info.forward_derivatives:
689
+ fw_derivative_dict[key] = []
690
+ continue
691
+
692
+ forward_derivatives = info.forward_derivatives
693
+
694
+ # For functions that have a single def for out-of-place and inplace (like abs())
695
+ if f.func.kind() == SchemaKind.inplace:
696
+ # For inplace functions there is a little bit of work to do:
697
+ # 1) Validate the formula and make sure the input that is modified in not used:
698
+ # - If there is a formula for the inplace variant of the function (is_exact_match == True) then
699
+ # we make sure that the original value of the input that is being modified inplace (self_p) is
700
+ # not used in the formula. Note that the formula can use "original_self_p" here and that would
701
+ # trigger a clone of the original input.
702
+ # - If we are reusing the out of place formula (is_exact_match == False) then we replace every
703
+ # occurrence of self_p and self_t by original_self_p and original_self_t. These will be
704
+ # populated by cloned version of the original input (either the clone done by the backward AD
705
+ # logic if self is also used in a backward formula or a special clone that we add).
706
+ # 2) At this point, there cannot be a self_p in the formula.
707
+ # 3) Change "result" into "self_p" as by design, in the inplace function codegen, the result is
708
+ # simply called self (as it is modified inplace).
709
+ # 4) Update the required primals data in case it used to contain "result" but should now contain
710
+ # "self"
711
+ # 5) If it is not an exact match, the user formula is not modifying the existing forward grad
712
+ # inplace as it should. So add some code that makes sure that we do so if the forward grad
713
+ # already exists.
714
+
715
+ assert (
716
+ len(info.forward_derivatives) == 1
717
+ ) # Only single output inplace should exist
718
+ fw_info = info.forward_derivatives[0]
719
+ formula = fw_info.formula
720
+
721
+ def replace_self_with_original_self(formula: str, postfix: str) -> str:
722
+ def repl(m: re.Match[str]) -> str:
723
+ return f"{m.group(1)}original_self{postfix}{m.group(2)}"
724
+
725
+ return re.sub(IDENT_REGEX.format(f"self{postfix}"), repl, formula)
726
+
727
+ if re.search(IDENT_REGEX.format("self_p"), formula):
728
+ if is_exact_match:
729
+ # For manually defined formulas, don't allow the original value to be used
730
+ raise RuntimeError(
731
+ f'The formula for "{f.func.name}" is using the original value of self '
732
+ "that is being modified inplace. This would lead to wrong forward gradients. "
733
+ 'Please use "result" in the formula only.'
734
+ )
735
+ else:
736
+ # When the original formula is out of place, we save a clone of the primal
737
+ # value to be able to access this value if needed
738
+ # replace "self_p"/"self_t" from the formula by "original_self_p"/"original_self_t"
739
+ formula = replace_self_with_original_self(formula, "_p")
740
+ formula = replace_self_with_original_self(formula, "_t")
741
+
742
+ # replace "result" from the formula by "self_p"
743
+ def repl(m: re.Match[str]) -> str:
744
+ return f"{m.group(1)}self_p{m.group(2)}"
745
+
746
+ formula = re.sub(IDENT_REGEX.format("result"), repl, formula)
747
+
748
+ required_primals = fw_info.required_inputs_primal
749
+ if re.search(IDENT_REGEX.format("self_p"), formula):
750
+ required_primals = (
751
+ required_primals + ("self",) if required_primals else ("self",)
752
+ )
753
+
754
+ if not is_exact_match:
755
+ # NOTE [In-place forward AD formula Optimization]
756
+ #
757
+ # This optimization transforms the formula to directly do inplace, i.e.
758
+ # instead of self_t.copy_(self_t.op()) we do self_t.op_() when the following are met:
759
+ #
760
+ # 1) the formula satisfies the pattern: "self_t.op(*args)"
761
+ # 2) "op" in (1) needs to be the same as the op the derivative is for
762
+ #
763
+ # (2) may seem too strict, but currently the only ops that satisfy (1) also satisfy (2)
764
+ # If there is a need, we can relax (2) to allow any op that has an in-place variant
765
+ is_single_method_on_self_t = False
766
+ directly_do_inplace = False
767
+ op_name: str | None = None
768
+ between_parens: str | None = None
769
+ match = re.fullmatch(r"self_t.([\w]*)\((.*)\)", formula)
770
+ if match:
771
+ op_name, between_parens = match.group(1), match.group(2)
772
+
773
+ # We want to...
774
+ # Match: self_t.op1(other_p.op2(arg))
775
+ # Avoid: self_t.op1(args) + self_t.op2(args)
776
+ # Avoid: self_t.op1(other_p.op2(arg)) + self_t.op2(args)
777
+ def check_parens_nest_level_gt_zero(s: str) -> bool:
778
+ level = 1
779
+ for ch in s:
780
+ if ch == ")":
781
+ level -= 1
782
+ if level == 0:
783
+ return False
784
+ if ch == "(":
785
+ level += 1
786
+ return True
787
+
788
+ is_single_method_on_self_t = check_parens_nest_level_gt_zero(
789
+ between_parens
790
+ )
791
+ directly_do_inplace = (
792
+ is_single_method_on_self_t and op_name == info.name
793
+ )
794
+
795
+ if directly_do_inplace:
796
+ assert op_name is not None
797
+ assert between_parens is not None
798
+ formula = f"self_t_raw.defined() ? self_t_raw.{op_name}_({between_parens}) : {formula}"
799
+ else:
800
+ # Make sure that the forward grad is modified inplace when the original formula
801
+ # is out of place
802
+ formula = f"self_t_raw.defined() ? self_t_raw.copy_({formula}) : {formula}"
803
+
804
+ required_original_self_value = bool(
805
+ re.search(IDENT_REGEX.format("original_self_p"), formula)
806
+ ) or bool(re.search(IDENT_REGEX.format("original_self_t"), formula))
807
+
808
+ forward_derivatives = [
809
+ ForwardDerivative(
810
+ formula=formula,
811
+ var_names=("self",),
812
+ var_types=fw_info.var_types,
813
+ required_inputs_fw_grad=fw_info.required_inputs_fw_grad,
814
+ required_inputs_primal=required_primals,
815
+ required_original_self_value=required_original_self_value,
816
+ is_reusing_outplace_formula=not is_exact_match,
817
+ ),
818
+ ]
819
+
820
+ fw_derivative_dict[key] = forward_derivatives
821
+
822
+ result.append(
823
+ NativeFunctionWithDifferentiabilityInfo(
824
+ func=f, info=info_dict, fw_derivatives=fw_derivative_dict
825
+ )
826
+ )
827
+
828
+ return result
829
+
830
+
831
+ def is_differentiable(
832
+ name: str, type: Type, info: DifferentiabilityInfo | None
833
+ ) -> bool:
834
+ return type.is_tensor_like() and (
835
+ info is None or name not in info.non_differentiable_arg_names
836
+ )
837
+
838
+
839
+ def gen_differentiable_outputs(
840
+ fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default"
841
+ ) -> list[DifferentiableOutput]:
842
+ f = fn.func
843
+ info = fn.info[key] if fn.info else None
844
+ outputs: list[DifferentiableOutput] = [
845
+ DifferentiableOutput(
846
+ name=name,
847
+ type=ret.type,
848
+ cpp_type=cpp.return_type(ret, symint=True).cpp_type(),
849
+ )
850
+ for name, ret in zip(cpp.return_names(f), f.func.returns)
851
+ ]
852
+ output_differentiability = info.output_differentiability if info else None
853
+ if output_differentiability is not None:
854
+ if len(output_differentiability) != len(outputs):
855
+ raise RuntimeError(
856
+ f"The length of output_differentiability ({len(output_differentiability)}), "
857
+ f"does not match the number of outputs ({len(outputs)})."
858
+ )
859
+ differentiable_outputs: list[DifferentiableOutput] = []
860
+ if False in output_differentiability and f.func.kind() == SchemaKind.inplace:
861
+ raise RuntimeError(
862
+ "output_differentiability=False for inplace operation (version_counter won't get updated)"
863
+ )
864
+ for differentiable, output in zip(output_differentiability, outputs):
865
+ if differentiable:
866
+ differentiable_outputs.append(output)
867
+ return differentiable_outputs
868
+ candidate_differentiable_outputs = list(
869
+ filter(lambda r: is_differentiable(r.name, r.type, info), outputs)
870
+ )
871
+ if uses_single_grad(info):
872
+ return candidate_differentiable_outputs[:1]
873
+ else:
874
+ return candidate_differentiable_outputs
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/meta.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torchgen.model import NativeFunctionsGroup
2
+
3
+
4
+ # Follows dispatcher calling convention, but:
5
+ # - Mutable arguments not allowed. Meta functions are always
6
+ # written in functional form. Look at FunctionSchema.signature()
7
+ # - No tensor returns; instead we return a TensorMeta describing
8
+ # the tensor in question
9
+
10
+
11
+ def name(g: NativeFunctionsGroup) -> str:
12
+ # use the overload name from the functional version
13
+ return str(g.functional.func.name).replace(".", "_")
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/python.py ADDED
@@ -0,0 +1,1548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING
5
+
6
+ from torchgen.api import cpp
7
+ from torchgen.api.types import Binding, CppSignature, CppSignatureGroup
8
+ from torchgen.gen import pythonify_default
9
+ from torchgen.model import (
10
+ Argument,
11
+ BaseTy,
12
+ BaseType,
13
+ FunctionSchema,
14
+ ListType,
15
+ NativeFunction,
16
+ OptionalType,
17
+ Return,
18
+ Type,
19
+ Variant,
20
+ )
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Iterable, Sequence
25
+
26
+
27
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
28
+ #
29
+ # Data Models
30
+ #
31
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
32
+ #
33
+ # [Notes] python binding codegen
34
+ #
35
+ # The Python binding codegen produces code that takes the input list of
36
+ # PyObjects, finds the matching ATen C++ function using PythonArgParser,
37
+ # converts the PyObjects into C++ types and calls the ATen C++ function:
38
+ #
39
+ # +--------+ parsing +------------------------+ binding +-----------------------+
40
+ # | PyObjs | ---------> | PythonArgParser Output | ---------> | Cpp Function Dispatch |
41
+ # +--------+ +------------------------+ +-----------------------+
42
+ #
43
+ # The following examples demonstrate the data models the Python binding
44
+ # codegen needs to deal with and the tasks it needs to accomplish. It
45
+ # helps understand the purpose of the new data types we introduced below.
46
+ #
47
+ # - Function Schema (source of truth)
48
+ #
49
+ # aten::empty.names(int[] size, *, Dimname[]? names,
50
+ # ScalarType? dtype=None, Layout? layout=None,
51
+ # Device? device=None, bool? pin_memory=None,
52
+ # MemoryFormat? memory_format=None) -> Tensor
53
+ #
54
+ # - Python Signature
55
+ #
56
+ # It's used to generate input schema string for PythonArgParser.
57
+ # Note: TensorOptions fields are reordered and the additional
58
+ # 'requires_grad' field is added:
59
+ #
60
+ # empty(IntArrayRef size, *, DimnameList? names,
61
+ # MemoryFormat? memory_format=None, ScalarType dtype=None,
62
+ # Layout layout=torch.strided, Device device=None,
63
+ # bool pin_memory=False, bool requires_grad=False)
64
+ #
65
+ # - C++ Signature
66
+ #
67
+ # It's used to generate C++ lambda formals & dispatch call.
68
+ # Note: the scattered TensorOptions fields are packed into 'options'.
69
+ #
70
+ # auto dispatch_empty =
71
+ # [](IntArrayRef size, std::optional<DimnameList> names,
72
+ # const TensorOptions & options,
73
+ # std::optional<MemoryFormat> memory_format) -> Tensor {
74
+ # pybind11::gil_scoped_release no_gil;
75
+ # return torch::empty(size, names, options, memory_format);
76
+ # };
77
+ #
78
+ # - Binding between Python Arguments and C++ Arguments
79
+ #
80
+ # Given a set of Python Arguments in scope, we need produce the
81
+ # binding expressions that translate the Python API into C++ API:
82
+ #
83
+ # Python Args Cpp Args Binding Exprs
84
+ # -----------------------------------------------------------------
85
+ # 0: size size '_r.intlist(0)'
86
+ # 1: names names 'names' [special init]
87
+ # 2: memory_format -------+
88
+ # 3: dtype -----+-|--> options 'options' [special packing]
89
+ # 4: layout / |
90
+ # 5: device / +--> memory_format '_r.memoryformatOptional(2)'
91
+ # 6: pin_memory /
92
+ # 7: requires_grad -+
93
+ #
94
+ # So the full dispatch expression would look like:
95
+ #
96
+ # dispatch_empty(_r.intlist(0), names, options,
97
+ # _r.memoryformatOptional(2))
98
+ #
99
+ # Where does 'names' come from? It involves special local init:
100
+ #
101
+ # auto __names = _r.toDimnameListOptional(1);
102
+ # std::optional<DimnameList> names =
103
+ # __names ? std::make_optional(DimnameList(__names.value()))
104
+ # : std::nullopt;
105
+ #
106
+ # Where does 'options' come from? It involves special local init
107
+ # for TensorOptions. Note that Python side has the additional
108
+ # 'requires_grad' field:
109
+ #
110
+ # const auto options = TensorOptions()
111
+ # .dtype(_r.scalartype(3))
112
+ # .device(_r.device(5))
113
+ # .layout(_r.layoutOptional(4))
114
+ # .requires_grad(_r.toBool(7))
115
+ # .pinned_memory(_r.toBool(6));
116
+ #
117
+ # In some other cases one Python Argument can map to multiple C++
118
+ # Arguments. For example:
119
+ #
120
+ # aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False)
121
+ # -> (Tensor values, Tensor indices)
122
+ #
123
+ # Python Args Cpp Args Binding Exprs
124
+ # ---------------------------------------------------------------------
125
+ # +----> max 'out[0]'
126
+ # /-----> max_values 'out[1]
127
+ # 0: input / self '_r.tensor(0)'
128
+ # 1: dim / dim '_r.dimname(1)'
129
+ # 2: keepdim / keepdim '_r.toBool(2)'
130
+ # 3: out -----+ [local init] out '_r.tensorlist_n<2>(3)'
131
+ #
132
+ # As demonstrated above, the binding can involve reordering,
133
+ # packing, unpacking and special local inits.
134
+ #
135
+ #
136
+ # Let's look at a concrete example:
137
+ #
138
+ # static PythonArgParser parser({
139
+ # "abs(Tensor input, *, Tensor out=None)",
140
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141
+ # ^
142
+ # +--- Python Schema, represented by PythonSignature and PythonArgument
143
+ #
144
+ # }, /*traceable=*/true);
145
+ #
146
+ # ParsedArgs<2> parsed_args;
147
+ # auto _r = parser.parse(nullptr, args, kwargs, parsed_args);
148
+ #
149
+ # ...
150
+ #
151
+ # if (_r.isNone(1)) {
152
+ # ~~~~~~~~~~~~ <--- Scattered PythonArgParser output (arg name = 'out')
153
+ # represented by PythonArgParserOutputExpr
154
+ #
155
+ # // aten::abs(Tensor self) -> Tensor
156
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157
+ # ^
158
+ # +--- NativeFunction schema, base version
159
+ #
160
+ # auto dispatch_abs = [](const Tensor & self) -> Tensor {
161
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162
+ # ^
163
+ # +--- dispatch_lambda_args / dispatch_lambda_return_str
164
+ # generated from NativeFunction / CppSignature
165
+ # (deprecated PythonSignature is special)
166
+ # arguments are represented by DispatchLambdaArgument
167
+ #
168
+ # pybind11::gil_scoped_release no_gil;
169
+ # return self.abs();
170
+ # ~~~~~~~~~~~ <--- cpp_dispatch_target / cpp_dispatch_exprs
171
+ # generated from NativeFunction / CppSignature
172
+ # };
173
+ # return wrap(dispatch_abs(_r.tensor(0)));
174
+ # ~~~~~~~~~~~~~
175
+ # ^
176
+ # +--- dispatch_lambda_exprs
177
+ # binding PythonArgParserOutputExpr (python args)
178
+ # and DispatchLambdaArgument (c++ args)
179
+ #
180
+ # } else {
181
+ # // aten::abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
182
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
183
+ # ^
184
+ # +--- NativeFunction schema, out-variant
185
+ #
186
+ # auto dispatch_abs_out = [](Tensor out, const Tensor & self) -> Tensor {
187
+ # pybind11::gil_scoped_release no_gil;
188
+ # return at::abs_out(out, self);
189
+ # };
190
+ # return wrap(dispatch_abs_out(_r.tensor(1), _r.tensor(0)));
191
+ # }
192
+ #
193
+ #
194
+ # [Notes] python interface codegen
195
+ # The python dataclasses below are used used to generate both python binding code
196
+ # and pyi type hint signatures.
197
+ # In theory these two should look very similar, but there are number of differences
198
+ # in how pyi signatures vs. python_arg_parser signatures are generated.
199
+ # These differences have been encapsulated in signature_str() vs. signature_str_pyi()
200
+ # to display the full signatures, and argument_str() vs argument_str_pyi() to display arguments.
201
+ # For examples, only pyi signatures include return types.
202
+
203
+
204
+ def format_function_signature(
205
+ name: str, arguments: Iterable[str] = (), return_type: str | None = None
206
+ ) -> str:
207
+ if not isinstance(arguments, (list, tuple)):
208
+ arguments = tuple(arguments)
209
+ return_type = f" -> {return_type}" if return_type is not None else ""
210
+
211
+ sig = f"def {name}({', '.join(arguments)}){return_type}: ..."
212
+ if len(sig) <= 80 or len(arguments) == 0 or tuple(arguments) == ("self",):
213
+ return sig
214
+
215
+ lines = [
216
+ f"def {name}(",
217
+ *(f" {arg}," for arg in arguments),
218
+ f"){return_type}: ...",
219
+ ]
220
+ sig = "\n".join(lines)
221
+ if all(len(line) <= 80 for line in lines):
222
+ return sig
223
+ # ruff format bug for compound statements: https://github.com/astral-sh/ruff/issues/18658
224
+ # use `skip` instead of `on` + `off`
225
+ return sig.removesuffix(" ...") + " # fmt: skip\n ..."
226
+
227
+
228
+ @dataclass(frozen=True)
229
+ class PythonReturns:
230
+ returns: tuple[Return, ...]
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class PythonArgument:
235
+ name: str
236
+ type: Type
237
+ default: str | None
238
+
239
+ # Used to generate the default init expr for some PythonArgParser outputs, e.g.:
240
+ #
241
+ # _r.layoutWithDefault(3, layout_from_backend(self.options().backend())))
242
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
243
+ # ^
244
+ # +--- default_init str
245
+ default_init: str | None
246
+
247
+ # Compute argument formal for python argument parsing.
248
+ # Needs to be consistent with torch/csrc/utils/python_arg_parser.h.
249
+ def argument_str(self, *, method: bool = False, symint: bool = True) -> str:
250
+ type_str = (
251
+ argument_type_str(self.type, symint=symint)
252
+ .replace("const ", "")
253
+ .replace(" &", "")
254
+ )
255
+
256
+ name = self.name
257
+ # s/self/input/ outside method bindings
258
+ # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
259
+ # for the parse string
260
+ if name == "self" and type_str in ["Tensor", "Number"] and not method:
261
+ name = "input"
262
+
263
+ # add default
264
+ if self.default is not None:
265
+ default = {
266
+ "nullptr": "None",
267
+ "::std::nullopt": "None",
268
+ "std::nullopt": "None",
269
+ "{}": "None",
270
+ }.get(self.default, self.default)
271
+ return f"{type_str} {name}={default}"
272
+ else:
273
+ return f"{type_str} {name}"
274
+
275
+ def argument_str_pyi(
276
+ self, *, method: bool = False, deprecated: bool = False
277
+ ) -> str:
278
+ type_str = argument_type_str_pyi(self.type)
279
+
280
+ name = self.name
281
+ # s/self/input/ outside method bindings
282
+ # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
283
+ # for the parse string
284
+ if name == "self" and type_str == "Tensor" and not method and not deprecated:
285
+ name = "input"
286
+
287
+ if name == "from": # from is a Python keyword...
288
+ name += "_"
289
+
290
+ # pyi merges the _out and functional variants into the same signature, with an optional out arg
291
+ if name == "out" and type_str == "Tensor" and not deprecated:
292
+ type_str = f"{type_str} | None".replace(" | None | None", " | None")
293
+
294
+ # pyi deprecated signatures don't get defaults for their out arg
295
+ treat_as_no_default = (
296
+ deprecated
297
+ and isinstance(self, PythonOutArgument)
298
+ and self.default == "None"
299
+ )
300
+
301
+ # add default
302
+ if self.default is not None and not treat_as_no_default:
303
+ if (
304
+ isinstance(self.type, ListType)
305
+ and self.type.elem == BaseType(BaseTy.int)
306
+ and self.default.startswith("{")
307
+ and self.default.endswith("}")
308
+ ):
309
+ default = (
310
+ "(" + ", ".join(map(str.strip, self.default[1:-1].split(","))) + ")"
311
+ )
312
+ else:
313
+ default = {
314
+ "nullptr": "None",
315
+ "::std::nullopt": "None",
316
+ "std::nullopt": "None",
317
+ "{}": "None",
318
+ "c10::MemoryFormat::Contiguous": "contiguous_format",
319
+ "QScheme::PER_TENSOR_AFFINE": "per_tensor_affine",
320
+ }.get(self.default, self.default)
321
+ return f"{name}: {type_str} = {default}"
322
+ else:
323
+ return f"{name}: {type_str}"
324
+
325
+
326
+ @dataclass(frozen=True)
327
+ class PythonOutArgument(PythonArgument):
328
+ # In Python signature multiple output fields are packed into one 'out' argument.
329
+ # When binding to C++, it's first binded to a local 'out' variable:
330
+ # 'auto out = _r.tensorlist_n<2>(2);',
331
+ # then binded to scattered C++ output arguments as 'out[0]', 'out[1]', and etc.
332
+ # TODO: maybe don't need keep scattered out fields for python signature?
333
+ outputs: tuple[PythonArgument, ...]
334
+
335
+ @staticmethod
336
+ def from_outputs(outputs: tuple[PythonArgument, ...]) -> PythonOutArgument | None:
337
+ if not outputs:
338
+ return None
339
+
340
+ size = len(outputs)
341
+ if size == 1:
342
+ return PythonOutArgument(
343
+ name=outputs[0].name,
344
+ type=outputs[0].type,
345
+ default="None",
346
+ default_init=None,
347
+ outputs=outputs,
348
+ )
349
+ elif size > 1:
350
+ if any(not a.type.is_tensor_like() for a in outputs):
351
+ raise RuntimeError(f"Unsupported output type: {outputs}")
352
+ return PythonOutArgument(
353
+ name="out",
354
+ # TODO: shouldn't this be OptionalType[ListType[...]], since it defaults to None?
355
+ type=ListType(BaseType(BaseTy.Tensor), size),
356
+ default="None",
357
+ default_init=None,
358
+ outputs=outputs,
359
+ )
360
+ raise AssertionError(r"Unexpected PythonOutArgument size")
361
+
362
+
363
+ @dataclass(frozen=True)
364
+ class PythonSignature:
365
+ # Base operator name, without inplace/outplace suffix.
366
+ name: str
367
+
368
+ # Positional arguments.
369
+ # TODO: create a dedicated SelfArgument type for 'self'?
370
+ input_args: tuple[PythonArgument, ...]
371
+
372
+ # Keyword arguments excluding the 'out' argument and scattered kwargs belonging
373
+ # to TensorOptions (dtype, layout, device, pin_memory, requires_grad, etc).
374
+ input_kwargs: tuple[PythonArgument, ...]
375
+
376
+ output_args: PythonOutArgument | None
377
+
378
+ # Return types, which are only used by pyi
379
+ returns: PythonReturns
380
+
381
+ # These are scattered kwargs arguments belonging to TensorOptions.
382
+ # When binding to C++, they are packed into a TensorOptions object 'options'.
383
+ # It's possible that the C++ signature doesn't take TensorOptions object (e.g.
384
+ # for out variant), in which case they will be used as scattered fields without
385
+ # being packed into 'options'.
386
+ # TODO: maybe create a PythonTensorOptionsArgument?
387
+ tensor_options_args: tuple[PythonArgument, ...]
388
+
389
+ # method or function signature?
390
+ method: bool
391
+
392
+ @property
393
+ def deprecated(self) -> bool:
394
+ return False
395
+
396
+ def arguments(
397
+ self, *, skip_outputs: bool = False, skip_tensor_options: bool = False
398
+ ) -> tuple[PythonArgument | PythonOutArgument, ...]:
399
+ result: list[PythonArgument | PythonOutArgument] = []
400
+ result.extend(self.input_args)
401
+ result.extend(self.input_kwargs)
402
+ if self.output_args is not None and not skip_outputs:
403
+ result.append(self.output_args)
404
+ if not skip_tensor_options:
405
+ result.extend(self.tensor_options_args)
406
+ return tuple(result)
407
+
408
+ def arguments_count(self) -> int:
409
+ return len(self.arguments())
410
+
411
+ def output_idx(self) -> int:
412
+ return len(self.input_args) + len(self.input_kwargs)
413
+
414
+ # [old codegen] Compute the Python function signature for argument parsing,
415
+ # as specified in torch/csrc/utils/python_arg_parser.h. WARNING:
416
+ # this is NOT the same type signature as specified by PEP 484
417
+ # as understood by mypy; our format was independently developed
418
+ # and has some quirks to make it more suitable specifically
419
+ # for error parsing.
420
+ #
421
+ # For a translation to mypy-valid type signatures, see
422
+ # signature_str_pyi().
423
+ def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
424
+ args = self.arguments(skip_outputs=skip_outputs)
425
+ schema_formals: list[str] = [
426
+ a.argument_str(method=self.method, symint=symint) for a in args
427
+ ]
428
+ positional_argc = len(self.input_args)
429
+ if len(schema_formals) > positional_argc:
430
+ schema_formals.insert(positional_argc, "*")
431
+
432
+ return f"{self.name}({', '.join(schema_formals)})"
433
+
434
+ def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
435
+ args = self.arguments(skip_outputs=skip_outputs)
436
+ schema_formals: list[str] = [
437
+ a.argument_str_pyi(method=self.method) for a in args
438
+ ]
439
+ positional_argc = len(self.input_args)
440
+ if len(schema_formals) > positional_argc:
441
+ schema_formals.insert(positional_argc, "*")
442
+
443
+ # only pyi signatures include returns
444
+ returns_str = returns_str_pyi(self)
445
+ # pyi also includes self (with no typing/defaults) for methods
446
+ if self.method:
447
+ schema_formals.insert(0, "self")
448
+ return format_function_signature(self.name, schema_formals, returns_str)
449
+
450
+ def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
451
+ # only pyi uses vararg signatures
452
+ args = self.arguments(skip_outputs=skip_outputs)
453
+ schema_formals: list[str] = [
454
+ a.argument_str_pyi(method=self.method) for a in args
455
+ ]
456
+ # vararg only applies to pyi signatures. vararg variants are not generated for all signatures
457
+ num_args = self.arguments_count()
458
+ if num_args == 0:
459
+ return None
460
+
461
+ num_positionalargs = len(self.input_args)
462
+
463
+ vararg_type = args[0].type
464
+ if not (
465
+ isinstance(vararg_type, ListType)
466
+ and str(vararg_type.elem) in ["int", "SymInt"]
467
+ and num_positionalargs == 1
468
+ ):
469
+ return None
470
+
471
+ # Below are the major changes in vararg vs. regular pyi signatures
472
+ # vararg signatures also omit the asterix
473
+ assert isinstance(vararg_type, ListType)
474
+ schema_formals[0] = (
475
+ "*" + args[0].name + ": " + argument_type_str_pyi(vararg_type.elem)
476
+ )
477
+
478
+ returns_str = returns_str_pyi(self)
479
+ # pyi also includes self (with no typing/defaults) for methods
480
+ if self.method:
481
+ schema_formals.insert(0, "self")
482
+ return format_function_signature(self.name, schema_formals, returns_str)
483
+
484
+
485
+ # The deprecated python signature involves some special logic, so create a
486
+ # dedicated data model to store these extra properties.
487
+ @dataclass(frozen=True)
488
+ class PythonSignatureDeprecated(PythonSignature):
489
+ # Schema for the deprecated function
490
+ deprecated_schema: FunctionSchema
491
+
492
+ # The deprecated signature might miss some arguments that the corresponding
493
+ # C++ signature expects. We need store the constant default values to pass in.
494
+ # For example:
495
+ # [deprecate signature]: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2)
496
+ # [func schema]: aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
497
+ # [func call]: self.addmm(mat1, mat2, beta, 1)
498
+ # We store ['self', 'mat1', 'mat2', 'beta', '1'] in this case.
499
+ deprecated_args_exprs: tuple[str, ...]
500
+
501
+ @property
502
+ def deprecated(self) -> bool:
503
+ return True
504
+
505
+ def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
506
+ return (
507
+ PythonSignature.signature_str(
508
+ self, skip_outputs=skip_outputs, symint=symint
509
+ )
510
+ + "|deprecated"
511
+ )
512
+
513
+ def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
514
+ args = self.arguments(skip_outputs=skip_outputs)
515
+ schema_formals: list[str] = [
516
+ a.argument_str_pyi(method=self.method, deprecated=True) for a in args
517
+ ]
518
+ positional_argc = len(self.input_args)
519
+ if len(schema_formals) > positional_argc:
520
+ schema_formals.insert(positional_argc, "*")
521
+
522
+ returns_str = returns_str_pyi(self)
523
+ return format_function_signature(self.name, schema_formals, returns_str)
524
+
525
+ def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
526
+ # the codegen doesn't include vararg variants for deprecated signatures
527
+ return None
528
+
529
+
530
+ # This struct is used to hold the PythonSignature and its corresponding
531
+ # NativeFunction BEFORE grouping base and out-variant functions.
532
+ # Why not store NativeFunction in PythonSignature or construct PythonSignature
533
+ # from NativeFunction? Because they are not 1-1 mapped.
534
+ # One native function could have both deprecated and non-deprecated python
535
+ # signatures - NativeFunction doesn't contain information to construct the
536
+ # deprecated python signature.
537
+ # One python signature is used to handle both the base and the out-variant
538
+ # function - see 'PythonSignatureGroup'.
539
+ @dataclass(frozen=True)
540
+ class PythonSignatureNativeFunctionPair:
541
+ signature: PythonSignature
542
+ function: NativeFunction
543
+
544
+
545
+ # We merge pairs of functions with signatures that are equivalent mod
546
+ # output arguments, and use a single entry in the python_arg_parser sig
547
+ # list for both (output arguments become optional).
548
+ @dataclass(frozen=True)
549
+ class PythonSignatureGroup:
550
+ # The signature used for Python argument parsing. The outplace signature
551
+ # is preferred if exists, because it can be used to parse inputs for both
552
+ # the out-place variant and the base version (with output omitted).
553
+ signature: PythonSignature
554
+
555
+ # The regular ATen declaration (e.g. conv2d)
556
+ base: NativeFunction
557
+
558
+ # The out variant (e.g. conv2d_out)
559
+ outplace: NativeFunction | None
560
+
561
+ @classmethod
562
+ def from_pairs(
563
+ cls,
564
+ functional: PythonSignatureNativeFunctionPair,
565
+ out: PythonSignatureNativeFunctionPair | None,
566
+ ) -> PythonSignatureGroup:
567
+ if out is None:
568
+ return PythonSignatureGroup(
569
+ signature=functional.signature,
570
+ base=functional.function,
571
+ outplace=None,
572
+ )
573
+
574
+ # prefer the signature with optional out=... arguments because it's the
575
+ # superset that can be used to parse input for both base and outplace.
576
+ signature_kwargs = out.signature.__dict__.copy()
577
+
578
+ # Out overloads in C++ don't have TensorOptions arguments,
579
+ # so take these from the functional variant
580
+ signature_kwargs["tensor_options_args"] = (
581
+ functional.signature.tensor_options_args
582
+ )
583
+
584
+ return PythonSignatureGroup(
585
+ signature=type(out.signature)(**signature_kwargs),
586
+ base=functional.function,
587
+ outplace=out.function,
588
+ )
589
+
590
+
591
+ # C++ function dispatch is wrapped in a lambda function. The lambda function
592
+ # has almost the same signature as the C++ function, only with some small
593
+ # variants - see details below.
594
+ # This data model is used to represent arguments of the lambda function
595
+ # signature.
596
+ @dataclass(frozen=True)
597
+ class DispatchLambdaArgument:
598
+ name: str
599
+ type_str: str
600
+ is_out_arg: bool
601
+
602
+
603
+ # To pass PyObjects arguments to C++ function (via the lambda wrapper),
604
+ # we need first convert PyObjects into simple C++ objects. This work
605
+ # is done by PythonArgParser.
606
+ # This data model is used to represent the output of PythonArgParser.
607
+ # It has 1-1 mapping with PythonArgument in PythonSignature.
608
+ @dataclass(frozen=True)
609
+ class PythonArgParserOutputExpr:
610
+ # argument name
611
+ name: str
612
+
613
+ # RHS expression to reference PythonArgParser output.
614
+ expr: str
615
+
616
+ # In some special cases we need create different expr, e.g.:
617
+ # '_r.isNone(1)' instead of '_r.tensor(1)'.
618
+ index: int
619
+
620
+ # The python argument it maps to.
621
+ argument: PythonArgument
622
+
623
+ @property
624
+ def is_none_expr(self) -> str:
625
+ return f"_r.isNone({self.index})"
626
+
627
+
628
+ # To pass PythonArgParser output to the lambda wrapper, we need bind
629
+ # PythonArgParserOutputExpr to DispatchLambdaArgument.
630
+ # They are not always 1-1 mapped, e.g. scattered TensorOptions fields
631
+ # need be packed into a TensorOptions object, which is the argument
632
+ # that the lambda function wrapper takes.
633
+ @dataclass(frozen=True)
634
+ class DispatchLambdaArgumentExprs:
635
+ # The exprs that provide the binding for lambda arguments, e.g.:
636
+ #
637
+ # 'self' -> '_r.tensor(0)'
638
+ # 'min' -> 'out[0]' / 'min_indices' -> 'out[1]'
639
+ # 'options' -> 'options'
640
+ #
641
+ # It has 1-1 mapping with DispatchLambdaArgument.
642
+ exprs: Sequence[str]
643
+
644
+ # Special local inits, which might introduce new variables that
645
+ # the 'exprs' above reference, e.g.:
646
+ #
647
+ # 'auto out = _r.tensorlist_n<2>(2);'
648
+ #
649
+ inits: Sequence[str]
650
+
651
+
652
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
653
+ #
654
+ # Helper Functions
655
+ #
656
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
657
+
658
+
659
+ def _cpp_signature(f: NativeFunction, *, method: bool = False) -> CppSignature:
660
+ return CppSignatureGroup.from_native_function(f, method=method).signature
661
+
662
+
663
+ def has_tensor_options(f: NativeFunction) -> bool:
664
+ return f.func.arguments.tensor_options is not None
665
+
666
+
667
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
668
+ #
669
+ # Python Signature
670
+ #
671
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
672
+
673
+
674
+ # 'simple_type' was introduced by the old codegen, which is slightly
675
+ # different from the python schema type, e.g.: doesn't have '?' suffix
676
+ # for optional Tensor/TensorList; doesn't have '[size]' suffix for list type.
677
+ def argument_type_str(
678
+ t: Type, *, simple_type: bool = False, symint: bool = True
679
+ ) -> str:
680
+ if isinstance(t, BaseType):
681
+ if t.name == BaseTy.int:
682
+ return "int64_t"
683
+ elif t.name == BaseTy.float:
684
+ return "double"
685
+ elif t.name == BaseTy.str:
686
+ return "c10::string_view"
687
+ elif t.name in [
688
+ BaseTy.Tensor,
689
+ BaseTy.bool,
690
+ BaseTy.QScheme,
691
+ BaseTy.Scalar,
692
+ BaseTy.ScalarType,
693
+ BaseTy.Generator,
694
+ BaseTy.Storage,
695
+ BaseTy.Layout,
696
+ BaseTy.Device,
697
+ BaseTy.DeviceIndex,
698
+ BaseTy.MemoryFormat,
699
+ BaseTy.Dimname,
700
+ BaseTy.Stream,
701
+ BaseTy.SymInt,
702
+ ]:
703
+ # These python schema type names line up with their function schema names
704
+ return t.name.name
705
+
706
+ elif isinstance(t, OptionalType):
707
+ elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
708
+ return f"{elem}?"
709
+ elif isinstance(t, ListType):
710
+ size = t.size if not simple_type else None
711
+ if str(t.elem) == "bool":
712
+ assert t.size is not None
713
+ return f"::std::array<bool,{t.size}>"
714
+ elif str(t.elem) == "int":
715
+ return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
716
+ elif str(t.elem) == "SymInt":
717
+ if symint:
718
+ return (
719
+ f"SymIntArrayRef[{size}]" if size is not None else "SymIntArrayRef"
720
+ )
721
+ else:
722
+ return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
723
+ elif str(t.elem) == "Tensor":
724
+ return f"TensorList[{size}]" if size is not None else "TensorList"
725
+ elif str(t.elem) == "Scalar":
726
+ return f"ScalarList[{size}]" if size is not None else "ScalarList"
727
+ elif str(t.elem) == "Tensor?":
728
+ if simple_type:
729
+ return "c10::List<::std::optional<Tensor>>"
730
+ else:
731
+ return "const c10::List<::std::optional<Tensor>> &"
732
+ elif str(t.elem) == "Dimname":
733
+ return f"DimnameList[{size}]" if size is not None else "DimnameList"
734
+ elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
735
+ return f"ArrayRef<{elem}>"
736
+
737
+ raise RuntimeError(f"unrecognized type {repr(t)}")
738
+
739
+
740
+ def argument_type_size(t: Type) -> int | None:
741
+ l = t.is_list_like()
742
+ if l is not None and str(l.elem) != "bool":
743
+ return l.size
744
+ else:
745
+ return None
746
+
747
+
748
+ def argument(a: Argument) -> PythonArgument:
749
+ return PythonArgument(
750
+ name=a.name,
751
+ type=a.type,
752
+ # TODO: directly translate a.default to python default
753
+ default=(
754
+ str(pythonify_default(cpp.default_expr(a.default, a.type, symint=False)))
755
+ if a.default is not None
756
+ else None
757
+ ),
758
+ default_init=None,
759
+ )
760
+
761
+
762
+ # Generates a PythonSignature that can be used for either .pyi or PythonArgParser codegen
763
+ def signature(
764
+ f: NativeFunction, *, method: bool = False, pyi: bool = False
765
+ ) -> PythonSignature:
766
+ return signature_from_schema(
767
+ f.func, category_override=f.category_override, method=method, pyi=pyi
768
+ )
769
+
770
+
771
+ def signature_from_schema(
772
+ func: FunctionSchema,
773
+ *,
774
+ category_override: str | None,
775
+ method: bool = False,
776
+ pyi: bool = False,
777
+ ) -> PythonSignature:
778
+ args: list[Argument] = []
779
+ args.extend(func.arguments.pre_self_positional)
780
+ # Skip SelfArgument if this is method.
781
+ if not method and func.arguments.self_arg is not None:
782
+ args.append(func.arguments.self_arg.argument)
783
+ args.extend(func.arguments.post_self_positional)
784
+ args.extend(func.arguments.pre_tensor_options_kwarg_only)
785
+ # Skip TensorOptionsArguments. Python side TensorOptions
786
+ # arguments are created based on different rules - see below.
787
+ args.extend(func.arguments.post_tensor_options_kwarg_only)
788
+ args.extend(func.arguments.out)
789
+
790
+ input_arg_set = {a.name for a in func.arguments.flat_positional}
791
+ kwarg_only_set = {a.name for a in func.arguments.flat_kwarg_only}
792
+ out_arg_set = {a.name for a in func.arguments.out}
793
+
794
+ input_args = tuple(map(argument, filter(lambda a: a.name in input_arg_set, args)))
795
+ input_kwargs = tuple(
796
+ map(argument, filter(lambda a: a.name in kwarg_only_set, args))
797
+ )
798
+ outputs = tuple(map(argument, filter(lambda a: a.name in out_arg_set, args)))
799
+
800
+ # Reintroduce the scattered fields of TensorOptions for Python.
801
+ # Compared to the cpp counterpart, the python arguments have new property
802
+ # (default_init) and a new argument 'requires_grad', which require some
803
+ # special handlings.
804
+ # [old codegen] TODO: because these aren't guaranteed to be 100% faithful
805
+ # to the original versions in the yaml, this recreation is a potential
806
+ # source of drift between eager and JIT. Pull this logic out to a shared place.
807
+
808
+ has_tensor_input_arg = any(
809
+ a.type.is_tensor_like() for a in func.arguments.flat_non_out
810
+ )
811
+ if any(a.name == "requires_grad" for a in func.schema_order_arguments()):
812
+ raise ValueError(
813
+ "argument named requires_grad is reserved, should not explicitly add it in the schema"
814
+ )
815
+
816
+ # [old codegen] this probably won't work if one of the returns is not a tensor,
817
+ # but it will produce a compile-time error that is obvious.
818
+ has_tensor_return = any(r.type.is_tensor_like() for r in func.returns)
819
+
820
+ name: str = cpp.name(func)
821
+ is_factory_function = category_override == "factory" or (
822
+ has_tensor_return and not has_tensor_input_arg
823
+ )
824
+ is_like_or_new_function = (
825
+ category_override in ("new", "like")
826
+ or name.startswith("new_")
827
+ or name.endswith("_like")
828
+ )
829
+ is_dummy_function = category_override == "dummy"
830
+
831
+ tensor_options_args: list[PythonArgument] = []
832
+ if (is_factory_function or is_like_or_new_function) and not is_dummy_function:
833
+
834
+ def topt_default_init(name: str) -> str | None:
835
+ topt_args = func.arguments.tensor_options
836
+ if topt_args is None:
837
+ return None
838
+ a = getattr(topt_args, name)
839
+ if a.default is None or a.default == "None":
840
+ return None
841
+ return cpp.default_expr(a.default, a.type, symint=False)
842
+
843
+ tensor_options_args.append(
844
+ PythonArgument(
845
+ name="dtype",
846
+ type=OptionalType(BaseType(BaseTy.ScalarType)),
847
+ default="None",
848
+ default_init=(
849
+ None if is_like_or_new_function else topt_default_init("dtype")
850
+ ),
851
+ )
852
+ )
853
+ tensor_options_args.append(
854
+ PythonArgument(
855
+ name="layout",
856
+ type=OptionalType(BaseType(BaseTy.Layout)),
857
+ default="None",
858
+ default_init=(
859
+ None if is_like_or_new_function else topt_default_init("layout")
860
+ ),
861
+ )
862
+ )
863
+ tensor_options_args.append(
864
+ PythonArgument(
865
+ name="device",
866
+ type=OptionalType(BaseType(BaseTy.Device)),
867
+ default="None",
868
+ default_init=(
869
+ None
870
+ if is_like_or_new_function
871
+ else (
872
+ topt_default_init("device")
873
+ or "torch::tensors::get_default_device()"
874
+ )
875
+ ),
876
+ )
877
+ )
878
+ tensor_options_args.append(
879
+ PythonArgument(
880
+ name="pin_memory",
881
+ type=OptionalType(BaseType(BaseTy.bool)),
882
+ default="False",
883
+ default_init=None,
884
+ )
885
+ )
886
+ tensor_options_args.append(
887
+ PythonArgument(
888
+ name="requires_grad",
889
+ type=OptionalType(BaseType(BaseTy.bool)),
890
+ default="False",
891
+ default_init=None,
892
+ )
893
+ )
894
+
895
+ returns = PythonReturns(returns=func.returns)
896
+
897
+ return PythonSignature(
898
+ name=str(func.name.name),
899
+ input_args=input_args,
900
+ input_kwargs=input_kwargs,
901
+ output_args=PythonOutArgument.from_outputs(outputs),
902
+ tensor_options_args=tuple(tensor_options_args),
903
+ returns=returns,
904
+ method=method,
905
+ )
906
+
907
+
908
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
909
+ #
910
+ # Python Interface
911
+ #
912
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
913
+
914
+
915
+ def structseq_fieldnames(returns: tuple[Return, ...]) -> list[str]:
916
+ if len(returns) <= 1 or all(r.name is None for r in returns):
917
+ return []
918
+ else:
919
+ if any(r.name is None for r in returns):
920
+ # When building on Windows, `PyStructSequence_UnnamedField` could not be
921
+ # resolved by the linker for some reason, which cause error in building:
922
+ #
923
+ # python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol
924
+ # PyStructSequence_UnnamedField
925
+ #
926
+ # Thus, at this point in time, we do not support unnamed
927
+ # fields in structseq; you must either name all fields,
928
+ # or none of them.
929
+ raise ValueError("Unnamed field is not supported by codegen")
930
+
931
+ return [str(r.name) for r in returns]
932
+
933
+
934
+ def argument_type_str_pyi(t: Type) -> str:
935
+ add_optional = False
936
+ if isinstance(t, OptionalType):
937
+ t = t.elem
938
+ add_optional = True
939
+
940
+ ret = ""
941
+ if isinstance(t, BaseType):
942
+ if t.name in [BaseTy.int, BaseTy.DeviceIndex]:
943
+ ret = "_int"
944
+ if t.name == BaseTy.SymInt:
945
+ ret = "_int | SymInt"
946
+ elif t.name == BaseTy.float:
947
+ ret = "_float"
948
+ elif t.name == BaseTy.str:
949
+ ret = "str"
950
+ elif t.name == BaseTy.Scalar:
951
+ ret = "Number | _complex"
952
+ elif t.name == BaseTy.ScalarType:
953
+ ret = "_dtype"
954
+ elif t.name == BaseTy.bool:
955
+ ret = "_bool"
956
+ elif t.name == BaseTy.QScheme:
957
+ ret = "_qscheme"
958
+ elif t.name == BaseTy.Layout:
959
+ ret = "_layout"
960
+ elif t.name == BaseTy.Device:
961
+ ret = "DeviceLikeType | None"
962
+ elif t.name == BaseTy.MemoryFormat:
963
+ ret = "memory_format"
964
+ elif t.name == BaseTy.Dimname:
965
+ ret = "str | EllipsisType | None"
966
+ elif t.name == BaseTy.Storage:
967
+ ret = "Storage | UntypedStorage"
968
+ elif t.name in [BaseTy.Tensor, BaseTy.Generator, BaseTy.Stream]:
969
+ # These python schema type names line up with their function schema names
970
+ ret = t.name.name
971
+
972
+ elif isinstance(t, ListType):
973
+ if str(t.elem) == "int":
974
+ ret = "_int | _size" if t.size is not None else "_size"
975
+ elif t.is_tensor_like():
976
+ # TODO: this doesn't seem right...
977
+ # Tensor?[] currently translates to tuple[Tensor, ...] | list[Tensor] | None
978
+ # It should probably translate to tuple[Tensor | None, ...] | list[Tensor | None]
979
+ add_optional = True
980
+ ret = (
981
+ "Tensor | tuple[Tensor, ...] | list[Tensor]"
982
+ if t.size is not None
983
+ else "tuple[Tensor, ...] | list[Tensor]"
984
+ )
985
+ elif str(t.elem) == "float":
986
+ ret = "Sequence[_float]"
987
+ elif str(t.elem) == "SymInt" and t.size is not None:
988
+ elem = argument_type_str_pyi(t.elem)
989
+ ret = f"{elem} | Sequence[{elem}]"
990
+ else:
991
+ elem = argument_type_str_pyi(t.elem)
992
+ ret = f"Sequence[{elem}]"
993
+
994
+ else:
995
+ raise RuntimeError(f"unrecognized type {repr(t)}")
996
+
997
+ if add_optional:
998
+ ret = f"{ret} | None".replace(" | None | None", " | None")
999
+
1000
+ return ret
1001
+
1002
+
1003
+ def return_type_str_pyi(t: Type) -> str:
1004
+ # Where arguments are open to accepting Union, return types should return
1005
+ # concrete types
1006
+
1007
+ if isinstance(t, OptionalType):
1008
+ inner = return_type_str_pyi(t.elem)
1009
+ return f"{inner} | None".replace(" | None | None", " | None")
1010
+
1011
+ if isinstance(t, BaseType):
1012
+ if t.name == BaseTy.Device:
1013
+ return "_device"
1014
+ elif t.name == BaseTy.Dimname:
1015
+ return "str | None"
1016
+ else:
1017
+ return argument_type_str_pyi(t)
1018
+
1019
+ if isinstance(t, ListType):
1020
+ inner = return_type_str_pyi(t.elem)
1021
+ return f"tuple[{inner}, ...]"
1022
+
1023
+ return argument_type_str_pyi(t)
1024
+
1025
+
1026
+ def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None:
1027
+ python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
1028
+ structseq_name = signature.name
1029
+ field_names = structseq_fieldnames(signature.returns.returns)
1030
+ if field_names:
1031
+ # These types are structseq objects which act like named NamedTuples, but
1032
+ # the constructor acts like the constructor of tuple. Using typing.NamedTuple
1033
+ # does not allow us to override __init__.
1034
+ seq_type = f"tuple[{', '.join(python_returns)}]"
1035
+ structseq_def_lines = [
1036
+ f"class {structseq_name}({seq_type}): # fmt: skip",
1037
+ ]
1038
+ for name, ret_type in zip(field_names, python_returns):
1039
+ structseq_def_lines.extend(
1040
+ [
1041
+ " @property",
1042
+ f" def {name}(self) -> {ret_type}: ...",
1043
+ ]
1044
+ )
1045
+ structseq_def_lines.extend(
1046
+ [
1047
+ " def __new__(",
1048
+ " cls,",
1049
+ f" sequence: {seq_type},",
1050
+ " ) -> Self: # fmt: skip",
1051
+ " ...",
1052
+ f" n_fields: Final[_int] = {len(field_names)}",
1053
+ f" n_sequence_fields: Final[_int] = {len(field_names)}",
1054
+ " n_unnamed_fields: Final[_int] = 0",
1055
+ " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing",
1056
+ "", # add an extra newline
1057
+ ]
1058
+ )
1059
+ structseq_def = "\n".join(structseq_def_lines)
1060
+ # Example:
1061
+ # structseq_def = (
1062
+ # "class max(tuple[Tensor, Tensor]): # fmt: skip\n"
1063
+ # " @property\n"
1064
+ # " def values(self) -> Tensor: ...\n"
1065
+ # " @property\n"
1066
+ # " def indices(self) -> Tensor: ...\n"
1067
+ # " def __new__(\n"
1068
+ # " cls,\n"
1069
+ # " sequence: tuple[Tensor, Tensor],\n"
1070
+ # " ) -> Self: # fmt: skip\n"
1071
+ # " ...\n"
1072
+ # " n_fields: Final[_int] = 2",
1073
+ # " n_sequence_fields: Final[_int] = 2",
1074
+ # " n_unnamed_fields: Final[_int] = 0",
1075
+ # " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing",
1076
+ # )
1077
+ return structseq_name, structseq_def
1078
+ return None
1079
+
1080
+
1081
+ def returns_str_pyi(signature: PythonSignature) -> str:
1082
+ field_names = structseq_fieldnames(signature.returns.returns)
1083
+ if field_names:
1084
+ return f"torch.return_types.{signature.name}"
1085
+
1086
+ python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
1087
+ if len(python_returns) > 1:
1088
+ return "tuple[" + ", ".join(python_returns) + "]"
1089
+ if len(python_returns) == 1:
1090
+ return python_returns[0]
1091
+ return "None"
1092
+
1093
+
1094
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1095
+ #
1096
+ # C++ Function Dispatch
1097
+ #
1098
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1099
+ # This section provides APIs to generate the code that does C++ function
1100
+ # dispatch. The C++ function call is wrapped by a lambda function.
1101
+ # For example:
1102
+ #
1103
+ # // aten::selu_(Tensor(a!) self) -> Tensor(a!)
1104
+ # auto dispatch_selu_ = [](Tensor self) -> Tensor {
1105
+ # pybind11::gil_scoped_release no_gil;
1106
+ # return at::selu_(self);
1107
+ # };
1108
+ #
1109
+ # The lambda function's signature follows the C++ signature in common
1110
+ # cases, e.g.:
1111
+ #
1112
+ # // aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
1113
+ # [](const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
1114
+ #
1115
+ # For out variant the 'out' argument's type is changed from 'Tensor &'
1116
+ # to 'Tensor'. It's because when calling the lambda it passes in the
1117
+ # PythonArgParser output '_r.tensor(3)', which is stack allocated object
1118
+ # and needs to pass by value. Also see comments in 'dispatch_lambda_return_str()'.
1119
+ #
1120
+ # // aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
1121
+ # [](Tensor out, const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
1122
+ #
1123
+ # For multi-output case it can keep using reference type because the
1124
+ # PythonArgParser output has been unpacked to local variables, e.g.:
1125
+ #
1126
+ # // aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *,
1127
+ # // Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
1128
+ # [](Tensor & max, Tensor & max_values, const Tensor & self, Dimname dim, bool keepdim) -> std::tuple<Tensor,Tensor>
1129
+ #
1130
+ # For deprecated python signature, it should follow deprecated python arg order.
1131
+ # TODO: This is to keep same byte-for-byte result as the old codegen - maybe unnecessary?
1132
+
1133
+
1134
+ def dispatch_lambda_args(
1135
+ ps: PythonSignature, f: NativeFunction, symint: bool = True
1136
+ ) -> tuple[DispatchLambdaArgument, ...]:
1137
+ if isinstance(ps, PythonSignatureDeprecated):
1138
+ schema = ps.deprecated_schema
1139
+ else:
1140
+ schema = f.func
1141
+
1142
+ # Start with cpp arguments - dispatch lambda signature always include 'self'
1143
+ cpp_args = cpp.arguments(
1144
+ arguments=schema.arguments,
1145
+ faithful=False,
1146
+ symint=symint,
1147
+ method=False,
1148
+ cpp_no_default_args=f.cpp_no_default_args,
1149
+ )
1150
+ out_args: set[str] = {a.name for a in schema.arguments.out}
1151
+
1152
+ # Convert from cpp argument to lambda argument
1153
+ def dispatch_lambda_arg(cpp_arg: Binding) -> DispatchLambdaArgument:
1154
+ type_str = cpp_arg.type
1155
+ is_out_arg = cpp_arg.name in out_args
1156
+ if ps.method and cpp_arg.name == "self":
1157
+ # For method's 'self', we can use 'const Tensor &' and simply ignore mutability!
1158
+ type_str = "const at::Tensor &"
1159
+ else:
1160
+ # For other cases we need prevent dangling refs to temps (unless it's
1161
+ # unpacked scattered output)
1162
+ # The reason is explained in the comments above and in 'dispatch_lambda_return_str()'.
1163
+ # TODO: avoid this special handling?
1164
+ ensure_temp_safe = len(out_args) <= 1 or not is_out_arg
1165
+ if ensure_temp_safe:
1166
+ type_str = {
1167
+ "at::Tensor &": "at::Tensor",
1168
+ }.get(type_str, type_str)
1169
+ return DispatchLambdaArgument(
1170
+ name=cpp_arg.name,
1171
+ type_str=type_str,
1172
+ is_out_arg=is_out_arg,
1173
+ )
1174
+
1175
+ return tuple(map(dispatch_lambda_arg, cpp_args))
1176
+
1177
+
1178
+ # [old codegen] XXX: if you got here because of an assertion failure, it doesn't mean
1179
+ # it's enough to just extend the list here. Before you do this, make sure
1180
+ # to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h.
1181
+ SUPPORTED_RETURN_TYPES = {
1182
+ "at::Tensor",
1183
+ "::std::tuple<at::Tensor,at::Tensor>",
1184
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor>",
1185
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor>",
1186
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor>",
1187
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor>",
1188
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,int64_t>",
1189
+ "::std::tuple<at::Tensor,at::Tensor,double,int64_t>",
1190
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,int64_t>",
1191
+ "::std::tuple<at::Tensor,at::Tensor,double,at::Tensor,int64_t>",
1192
+ "::std::tuple<double,int64_t>",
1193
+ "::std::tuple<at::Tensor,::std::vector<at::Tensor>>",
1194
+ "::std::vector<at::Tensor>",
1195
+ # Needed for flash attention forw/backward
1196
+ "::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,c10::SymInt,c10::SymInt,at::Tensor,at::Tensor,at::Tensor>",
1197
+ "at::Scalar",
1198
+ "bool",
1199
+ "int64_t",
1200
+ "void*",
1201
+ "void",
1202
+ "at::QScheme",
1203
+ "double",
1204
+ "at::IntArrayRef",
1205
+ "at::ScalarType",
1206
+ "at::Stream",
1207
+ }
1208
+
1209
+
1210
+ def dispatch_lambda_return_str(f: NativeFunction) -> str:
1211
+ # [old codegen] Remove type annotation (e.g. 'Tensor' rather than 'Tensor &')
1212
+ # because the dispatch lambdas take mutable arguments *by value*, not
1213
+ # by reference. If you then return a reference to such an argument, you
1214
+ # will now have a pointer to a dangling stack entry. Not good.
1215
+ #
1216
+ # You want:
1217
+ #
1218
+ # auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); };
1219
+ # ^^^^^^
1220
+ #
1221
+ # *not*
1222
+ #
1223
+ # auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); };
1224
+ # ^^^^^^^
1225
+ #
1226
+ # (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing
1227
+ # codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a
1228
+ # mutable reference to temporary. Maybe we could assign it to a
1229
+ # variable itself.)
1230
+ returns_without_annotation = tuple(
1231
+ Return(r.name, r.type, None) for r in f.func.returns
1232
+ )
1233
+ return_str = cpp.returns_type(returns_without_annotation, symint=True).cpp_type()
1234
+ if return_str not in SUPPORTED_RETURN_TYPES:
1235
+ raise RuntimeError(f"{f.func.name} returns unsupported type {return_str}")
1236
+ return return_str
1237
+
1238
+
1239
+ def cpp_dispatch_target(f: NativeFunction) -> str:
1240
+ symint = f.func.has_symint()
1241
+ name = cpp.name(f.func, symint_overload=symint)
1242
+ if Variant.method in f.variants:
1243
+ return f"self.{name}"
1244
+ if Variant.function in f.variants:
1245
+ if has_tensor_options(f) or f.func.name.name.base.endswith("_like"):
1246
+ namespace = "torch"
1247
+ else:
1248
+ namespace = "at"
1249
+ return f"{namespace}::{name}"
1250
+ raise RuntimeError(f"could not dispatch, neither function nor method: {f.func}")
1251
+
1252
+
1253
+ def cpp_dispatch_exprs(
1254
+ f: NativeFunction,
1255
+ *,
1256
+ python_signature: PythonSignature | None = None,
1257
+ ) -> tuple[str, ...]:
1258
+ cpp_args: Sequence[Binding] = _cpp_signature(f, method=False).arguments()
1259
+
1260
+ exprs: tuple[str, ...] = ()
1261
+ if not isinstance(python_signature, PythonSignatureDeprecated):
1262
+ # By default the exprs are consistent with the C++ signature.
1263
+ exprs = tuple(a.name for a in cpp_args)
1264
+ else:
1265
+ # For deprecated python signature we may need fill in some constants.
1266
+ exprs = tuple(
1267
+ filter(
1268
+ lambda n: n != "out" or f.func.is_out_fn(),
1269
+ python_signature.deprecated_args_exprs,
1270
+ )
1271
+ )
1272
+
1273
+ if Variant.method in f.variants:
1274
+ exprs = tuple(filter("self".__ne__, exprs))
1275
+
1276
+ return exprs
1277
+
1278
+
1279
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1280
+ #
1281
+ # Python / C++ Args Binding
1282
+ #
1283
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1284
+
1285
+
1286
+ # We explicitly enumerate the PythonArgParser unpacking methods for all
1287
+ # supported types. This might be more verbose than necessary, partially
1288
+ # because of the irregularity of unpacking method naming, partially
1289
+ # because we want to mimic the old codegen behavior - to reject
1290
+ # unexpected and/or unsupported cases which the old codegen rejects.
1291
+ # For certain cases it is intentionally more restrictive than necessary,
1292
+ # e.g.: it doesn't accepts doublelist with definite size.
1293
+ def arg_parser_unpack_method(
1294
+ t: Type, default: str | None, default_init: str | None, *, symint: bool = True
1295
+ ) -> str:
1296
+ has_default_init = default_init is not None
1297
+ if has_default_init and str(t) not in (
1298
+ "ScalarType?",
1299
+ "ScalarType",
1300
+ "Device",
1301
+ "Device?",
1302
+ "Layout",
1303
+ "Layout?",
1304
+ "bool",
1305
+ "bool?",
1306
+ ):
1307
+ raise RuntimeError(f"type '{t}' does not supported unpacking with default")
1308
+
1309
+ if isinstance(t, BaseType):
1310
+ if t.name in [
1311
+ BaseTy.Tensor,
1312
+ BaseTy.Stream,
1313
+ BaseTy.Storage,
1314
+ BaseTy.Scalar,
1315
+ BaseTy.Dimname,
1316
+ ]:
1317
+ # These unpack methods line up with their schema names
1318
+ return t.name.name.lower()
1319
+ elif t.name == BaseTy.ScalarType:
1320
+ return "scalartypeWithDefault" if has_default_init else "scalartype"
1321
+ elif t.name == BaseTy.Device:
1322
+ return "deviceWithDefault" if has_default_init else "device"
1323
+ elif t.name == BaseTy.DeviceIndex:
1324
+ return "toInt64"
1325
+ elif t.name == BaseTy.int:
1326
+ return "toInt64"
1327
+ elif t.name == BaseTy.SymInt:
1328
+ return "toSymInt" if symint else "toInt64"
1329
+ elif t.name == BaseTy.bool:
1330
+ return "toBoolWithDefault" if has_default_init else "toBool"
1331
+ elif t.name == BaseTy.float:
1332
+ return "toDouble"
1333
+ elif t.name == BaseTy.str:
1334
+ return "stringView"
1335
+ elif t.name == BaseTy.Layout:
1336
+ return "layoutWithDefault" if has_default_init else "layout"
1337
+ elif t.name == BaseTy.MemoryFormat:
1338
+ return "memoryformat"
1339
+
1340
+ elif isinstance(t, OptionalType):
1341
+ if str(t.elem) == "Tensor":
1342
+ return "optionalTensor"
1343
+ elif str(t.elem) == "Generator":
1344
+ return "generator"
1345
+ elif str(t.elem) == "Dimname[]":
1346
+ return "toDimnameListOptional"
1347
+ elif not has_default_init and default in (
1348
+ None,
1349
+ "None",
1350
+ "::std::nullopt",
1351
+ "std::nullopt",
1352
+ ):
1353
+ # If default is None: append 'Optional' to elem's unpacking method
1354
+ return (
1355
+ arg_parser_unpack_method(t.elem, None, None, symint=symint) + "Optional"
1356
+ )
1357
+ else:
1358
+ # Otherwise, load as underlying type with default
1359
+ return arg_parser_unpack_method(
1360
+ t.elem, default, default_init, symint=symint
1361
+ )
1362
+
1363
+ elif isinstance(t, ListType):
1364
+ if str(t.elem) == "Tensor":
1365
+ # accept and use definite size
1366
+ return f"tensorlist_n<{t.size}>" if t.size is not None else "tensorlist"
1367
+ elif str(t.elem) == "Tensor?":
1368
+ return "list_of_optional_tensors"
1369
+ elif str(t.elem) == "Dimname":
1370
+ # accept definite size
1371
+ return "dimnamelist"
1372
+ elif str(t.elem) == "int":
1373
+ # accept definite size
1374
+ return "intlist"
1375
+ elif str(t.elem) == "float":
1376
+ return "doublelist"
1377
+ elif str(t.elem) == "SymInt":
1378
+ # accept definite size
1379
+ return "symintlist" if symint else "intlist"
1380
+ elif str(t.elem) == "Scalar":
1381
+ return "scalarlist"
1382
+ raise RuntimeError(f"type '{t}' is not supported by PythonArgParser")
1383
+
1384
+
1385
+ # Return RHS expression for python argument using PythonArgParser output.
1386
+ # e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)'
1387
+ def arg_parser_output_expr(
1388
+ arg_index: int, a: PythonArgument, *, symint: bool = True
1389
+ ) -> PythonArgParserOutputExpr:
1390
+ has_default = a.default_init is not None
1391
+ unpack_method = arg_parser_unpack_method(
1392
+ t=a.type, default=a.default, default_init=a.default_init, symint=symint
1393
+ )
1394
+ default = f", {a.default_init}" if has_default else ""
1395
+ expr = f"_r.{unpack_method}({arg_index}{default})"
1396
+
1397
+ return PythonArgParserOutputExpr(
1398
+ name=a.name,
1399
+ expr=expr,
1400
+ index=arg_index,
1401
+ argument=a,
1402
+ )
1403
+
1404
+
1405
+ # Returns a map with key = arg_name and value = PythonArgParserOutputExpr.
1406
+ def arg_parser_output_exprs(
1407
+ ps: PythonSignature, f: NativeFunction, *, symint: bool = True
1408
+ ) -> dict[str, PythonArgParserOutputExpr]:
1409
+ return {
1410
+ e.name: e
1411
+ for i, a in enumerate(ps.arguments())
1412
+ for e in (arg_parser_output_expr(i, a, symint=symint),)
1413
+ }
1414
+
1415
+
1416
+ # argument name to type for scattered tensor options fields
1417
+ TENSOR_OPTIONS_FIELDS = {
1418
+ "dtype": "ScalarType?",
1419
+ "device": "Device?",
1420
+ "layout": "Layout?",
1421
+ "pin_memory": "bool?",
1422
+ "requires_grad": "bool?",
1423
+ }
1424
+
1425
+
1426
+ # bind arg parser outputs (python args) with dispatch lambda arguments (c++ args).
1427
+ def dispatch_lambda_exprs(
1428
+ ps: PythonSignature, f: NativeFunction, *, symint: bool = True
1429
+ ) -> DispatchLambdaArgumentExprs:
1430
+ # This method is to bind 'arg_parser_outputs' and 'lambda_args' by producing
1431
+ # 'inits' and 'lambda_args_exprs' for each lambda argument using arg parser
1432
+ # outputs.
1433
+ arg_parser_outputs = arg_parser_output_exprs(ps, f, symint=symint)
1434
+ lambda_args = dispatch_lambda_args(ps, f, symint=symint)
1435
+ inits: list[str] = []
1436
+ lambda_args_exprs: dict[str, str] = {}
1437
+
1438
+ has_toptions = has_tensor_options(f)
1439
+
1440
+ # 1. special inits/unpacking to provide binding exprs for lambda arguments.
1441
+ for a in ps.arguments(skip_tensor_options=True):
1442
+ name = a.name
1443
+ arg_parser_expr = arg_parser_outputs[a.name].expr
1444
+
1445
+ if has_toptions and name == "self":
1446
+ # TODO: why this needs to be special case?
1447
+ inits.extend(
1448
+ [
1449
+ f"auto self = {arg_parser_expr};",
1450
+ ]
1451
+ )
1452
+ lambda_args_exprs[name] = name
1453
+ elif (
1454
+ isinstance(a, PythonOutArgument)
1455
+ and len(a.outputs) > 1
1456
+ and f.func.is_out_fn()
1457
+ ):
1458
+ inits.extend(
1459
+ [
1460
+ f"auto out = {arg_parser_expr};",
1461
+ ]
1462
+ )
1463
+ for i, out_arg in enumerate(a.outputs):
1464
+ lambda_args_exprs[out_arg.name] = f"out[{i}]"
1465
+ elif str(a.type) == "Dimname[]?":
1466
+ # [old codegen]
1467
+ # TODO: make this part of something more general, or get rid of it.
1468
+ # optional<ArrayRef<T>> are special. The PythonArgParser returns an
1469
+ # optional<vector<T>>, which cannot be implicitly converted to
1470
+ # optional<ArrayRef<T>>. One needs to unwrap the optional and rewrap.
1471
+ inits.extend(
1472
+ [
1473
+ f"auto __{name} = {arg_parser_expr};",
1474
+ f"::std::optional<DimnameList> {name} = __{name} ? ::std::make_optional(DimnameList(__{name}.value())) : ::std::nullopt;", # noqa: B950
1475
+ ]
1476
+ )
1477
+ lambda_args_exprs[name] = name
1478
+ else:
1479
+ # default case - directly using PythonArgParser output expr
1480
+ lambda_args_exprs[name] = arg_parser_expr
1481
+
1482
+ # method's self is passed directly to python binding, rather than parsed
1483
+ if ps.method:
1484
+ lambda_args_exprs["self"] = "self"
1485
+
1486
+ # 2. special packing/checking for TensorOptions.
1487
+ tensor_options_args_names = [a.name for a in ps.tensor_options_args]
1488
+ if has_toptions:
1489
+ if f.func.is_out_fn():
1490
+ raise RuntimeError(f"{f.func}: tensor options with output arg")
1491
+ for a in ps.tensor_options_args:
1492
+ if a.name not in TENSOR_OPTIONS_FIELDS:
1493
+ raise RuntimeError(
1494
+ f"{f.func}: unrecognized tensor options field '{a.name}' in python binding arguments"
1495
+ )
1496
+ if str(a.type) != TENSOR_OPTIONS_FIELDS.get(a.name):
1497
+ raise RuntimeError(
1498
+ f"{f.func}: unrecognized type '{str(a.type)}' for tensor options field '{a.name}'"
1499
+ )
1500
+ if not all(a in tensor_options_args_names for a in TENSOR_OPTIONS_FIELDS):
1501
+ raise RuntimeError(
1502
+ f"{f.func}: incomplete tensor options args: {tensor_options_args_names}"
1503
+ )
1504
+
1505
+ inits.append(
1506
+ f"""\
1507
+ const auto options = TensorOptions()
1508
+ .dtype({arg_parser_outputs["dtype"].expr})
1509
+ .device({arg_parser_outputs["device"].expr})
1510
+ .layout({arg_parser_outputs["layout"].expr})
1511
+ .requires_grad({arg_parser_outputs["requires_grad"].expr})
1512
+ .pinned_memory({arg_parser_outputs["pin_memory"].expr});
1513
+ torch::utils::maybe_initialize_device(options);
1514
+ """
1515
+ )
1516
+ lambda_args_exprs["options"] = "options"
1517
+
1518
+ # 3. special case - access scattered TensorOptions fields without packing
1519
+ # TODO: maybe move to the generator side as it's not related to binding.
1520
+ if not has_toptions and tensor_options_args_names:
1521
+ if "dtype" in tensor_options_args_names:
1522
+ # we're an output-arg variant, check these args against output tensor
1523
+ if not f.func.is_out_fn():
1524
+ raise RuntimeError(
1525
+ f"{f.func}: dtype in tensor_options_args without output arg, {ps} {ps.arguments}"
1526
+ )
1527
+ if not all(a in tensor_options_args_names for a in ("layout", "device")):
1528
+ raise RuntimeError(
1529
+ f"{f.func}: incomplete tensor options for output check"
1530
+ )
1531
+
1532
+ inits.append(
1533
+ f"""\
1534
+ check_out_type_matches({arg_parser_outputs["out"].expr}, {arg_parser_outputs["dtype"].expr},
1535
+ {arg_parser_outputs["dtype"].is_none_expr}, {arg_parser_outputs["layout"].expr},
1536
+ {arg_parser_outputs["device"].expr}, {arg_parser_outputs["device"].is_none_expr});
1537
+ """
1538
+ )
1539
+ # we'll set requires_grad on outgoing tensor
1540
+ if "requires_grad" not in tensor_options_args_names:
1541
+ raise RuntimeError(
1542
+ f'{f.func}: expected "requires_grad" in tensor_options_args absent, but found [{tensor_options_args_names}]'
1543
+ )
1544
+
1545
+ return DispatchLambdaArgumentExprs(
1546
+ exprs=tuple(lambda_args_exprs[a.name] for a in lambda_args),
1547
+ inits=inits,
1548
+ )
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from torchgen.api.types.types import *
2
+ from torchgen.api.types.types_base import *
3
+
4
+
5
+ from torchgen.api.types.signatures import * # usort: skip
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (360 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/signatures.cpython-312.pyc ADDED
Binary file (19.5 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types.cpython-312.pyc ADDED
Binary file (8.59 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types_base.cpython-312.pyc ADDED
Binary file (10.8 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/signatures.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING
5
+
6
+ from torchgen.api.types.types_base import Binding, CType, Expr
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Iterator, Sequence
11
+
12
+ from torchgen.model import (
13
+ BackendIndex,
14
+ FunctionSchema,
15
+ NativeFunction,
16
+ NativeFunctionsGroup,
17
+ NativeFunctionsViewGroup,
18
+ )
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class CppSignature:
23
+ """
24
+ A CppSignature represents a single overload in the C++ API. For
25
+ any given function schema, there may be multiple CppSignatures
26
+ corresponding to it, based on how we desugar to C++. See also
27
+ CppSignatureGroup.
28
+ """
29
+
30
+ # The schema this signature is derived from
31
+ func: FunctionSchema
32
+
33
+ # Is this a C++ signature for a method, i.e. Tensor::my_op(...)?
34
+ method: bool
35
+
36
+ # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API
37
+ # (i.e. with a potential TensorOptions argument and out arguments in the front)
38
+ faithful: bool
39
+
40
+ # Is this a symint C++ signature. For BC reasons, functions that take
41
+ # SymInts still present as int64_t in C++, and the SymInt variant is
42
+ # offered at a different overload name
43
+ #
44
+ # NB: If a function RETURNS a SymInt, this is ALWAYS false
45
+ symint: bool
46
+
47
+ # The set of C++ arguments which should not have defaults applied to them
48
+ cpp_no_default_args: set[str]
49
+
50
+ # Is this a fallback C++ binding? Fallback bindings are enabled by
51
+ # manual_cpp_binding: True and are alternate, non-public API that
52
+ # lets manual C++ binding implementers access the binding that would
53
+ # have been automatically generated
54
+ fallback_binding: bool = False
55
+
56
+ # Return the unpacked argument structure of this signature,
57
+ # discarding information about which arguments are semantically
58
+ # related to each other.
59
+ def arguments(self) -> Sequence[Binding]:
60
+ return cpp.arguments(
61
+ self.func.arguments,
62
+ faithful=self.faithful,
63
+ symint=self.symint,
64
+ method=self.method,
65
+ cpp_no_default_args=self.cpp_no_default_args,
66
+ )
67
+
68
+ def name(self, *, suppress_symint_suffix: bool = False) -> str:
69
+ n = cpp.name(
70
+ self.func,
71
+ faithful_name_for_out_overloads=self.faithful,
72
+ symint_overload=False if suppress_symint_suffix else self.symint,
73
+ )
74
+ if self.fallback_binding:
75
+ n = f"__dispatch_{n}"
76
+ return n
77
+
78
+ # Render the C++ declaration for this signature
79
+ def decl(
80
+ self,
81
+ *,
82
+ name: str | None = None,
83
+ prefix: str = "",
84
+ is_redispatching_fn: bool = False,
85
+ suppress_symint_suffix: bool = False,
86
+ ) -> str:
87
+ returns_type = cpp.returns_type(
88
+ self.func.returns, symint=self.symint
89
+ ).cpp_type()
90
+ cpp_args = [a.decl() for a in self.arguments()]
91
+ if is_redispatching_fn:
92
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
93
+ cpp_args_str = ", ".join(cpp_args)
94
+ if name is None:
95
+ name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix)
96
+ return f"{returns_type} {name}({cpp_args_str})"
97
+
98
+ # Render the C++ definition for this signature, not including
99
+ # the body (with curly braces)
100
+ def defn(
101
+ self,
102
+ *,
103
+ name: str | None = None,
104
+ prefix: str = "",
105
+ is_redispatching_fn: bool = False,
106
+ ) -> str:
107
+ returns_type = cpp.returns_type(
108
+ self.func.returns, symint=self.symint
109
+ ).cpp_type()
110
+ cpp_args = [a.defn() for a in self.arguments()]
111
+ if is_redispatching_fn:
112
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
113
+ cpp_args_str = ", ".join(cpp_args)
114
+ if name is None:
115
+ name = prefix + self.name()
116
+ return f"{returns_type} {name}({cpp_args_str})"
117
+
118
+ def ptr_type(self) -> str:
119
+ args_types_str = ", ".join(a.type for a in self.arguments())
120
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})"
121
+
122
+ # Return the C++ function type, e.g., something like int(bool)
123
+ def type(self) -> str:
124
+ args_types_str = ", ".join(a.type for a in self.arguments())
125
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})"
126
+
127
+
128
+ # Represents group of all CppSignatures associated with a
129
+ # FunctionSchema. Right now, that's the regular, user-visible
130
+ # signature, as well as a "faithful" signature which doesn't
131
+ # have grouping.
132
+ @dataclass(frozen=True)
133
+ class CppSignatureGroup:
134
+ func: FunctionSchema
135
+ signature: CppSignature
136
+ faithful_signature: CppSignature | None
137
+ symint_signature: CppSignature | None
138
+ symint_faithful_signature: CppSignature | None
139
+
140
+ def most_faithful_signature(self) -> CppSignature:
141
+ if self.faithful_signature:
142
+ return self.faithful_signature
143
+ else:
144
+ return self.signature
145
+
146
+ def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]:
147
+ yield self.signature
148
+ if self.faithful_signature:
149
+ yield self.faithful_signature
150
+ if symint:
151
+ if self.symint_signature:
152
+ yield self.symint_signature
153
+ if self.symint_faithful_signature:
154
+ yield self.symint_faithful_signature
155
+
156
+ @staticmethod
157
+ def from_native_function(
158
+ f: NativeFunction, *, method: bool, fallback_binding: bool = False
159
+ ) -> CppSignatureGroup:
160
+ func = f.func
161
+
162
+ def make_sig(*, faithful: bool, symint: bool) -> CppSignature:
163
+ return CppSignature(
164
+ func=func,
165
+ faithful=faithful,
166
+ symint=symint,
167
+ method=method,
168
+ fallback_binding=fallback_binding,
169
+ cpp_no_default_args=f.cpp_no_default_args,
170
+ )
171
+
172
+ def make_sigs(*, symint: bool) -> tuple[CppSignature, CppSignature | None]:
173
+ faithful_signature: CppSignature | None = None
174
+ if func.arguments.tensor_options is not None or len(func.arguments.out) > 0:
175
+ faithful_signature = make_sig(faithful=True, symint=symint)
176
+ signature = make_sig(faithful=False, symint=symint)
177
+ return signature, faithful_signature
178
+
179
+ signature, faithful_signature = make_sigs(symint=False)
180
+ symint_signature: CppSignature | None = None
181
+ symint_faithful_signature: CppSignature | None = None
182
+ if func.has_symint():
183
+ symint_signature, symint_faithful_signature = make_sigs(symint=True)
184
+
185
+ return CppSignatureGroup(
186
+ func=func,
187
+ signature=signature,
188
+ faithful_signature=faithful_signature,
189
+ symint_signature=symint_signature,
190
+ symint_faithful_signature=symint_faithful_signature,
191
+ )
192
+
193
+
194
+ @dataclass(frozen=True)
195
+ class DispatcherSignature:
196
+ # The schema this signature is derived from
197
+ func: FunctionSchema
198
+
199
+ # Allows you to prepend an arbitrary prefix to the signature name.
200
+ # This is useful for parts of the codegen that generate wrappers around kernels,
201
+ # and need to avoid naming collisions.
202
+ prefix: str = ""
203
+
204
+ symint: bool = True
205
+
206
+ def arguments(self) -> list[Binding]:
207
+ return dispatcher.arguments(self.func, symint=self.symint)
208
+
209
+ def name(self) -> str:
210
+ return self.prefix + dispatcher.name(self.func)
211
+
212
+ def decl(self, name: str | None = None) -> str:
213
+ args_str = ", ".join(a.decl() for a in self.arguments())
214
+ if name is None:
215
+ name = self.name()
216
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
217
+
218
+ def defn(
219
+ self, name: str | None = None, *, is_redispatching_fn: bool = False
220
+ ) -> str:
221
+ args = [a.defn() for a in self.arguments()]
222
+ if is_redispatching_fn:
223
+ args = ["c10::DispatchKeySet dispatchKeySet"] + args
224
+ args_str = ", ".join(args)
225
+ if name is None:
226
+ name = self.name()
227
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
228
+
229
+ def exprs(self) -> list[Expr]:
230
+ return [Expr(a.name, a.nctype) for a in self.arguments()]
231
+
232
+ def returns_type(self) -> CType:
233
+ return dispatcher.returns_type(self.func.returns, symint=self.symint)
234
+
235
+ def ptr_type(self) -> str:
236
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
237
+ return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})"
238
+
239
+ # Return the C++ function type, e.g., something like int(bool)
240
+ def type(self) -> str:
241
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
242
+ return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})"
243
+
244
+ @staticmethod
245
+ def from_schema(
246
+ func: FunctionSchema, *, prefix: str = "", symint: bool = True
247
+ ) -> DispatcherSignature:
248
+ return DispatcherSignature(func, prefix, symint)
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class NativeSignature:
253
+ # The schema this signature is derived from
254
+ func: FunctionSchema
255
+
256
+ symint: bool
257
+
258
+ prefix: str = ""
259
+
260
+ def name(self) -> str:
261
+ return self.prefix + native.name(self.func)
262
+
263
+ def decl(self, name: str | None = None) -> str:
264
+ args_str = ", ".join(a.decl() for a in self.arguments())
265
+ if name is None:
266
+ name = self.name()
267
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
268
+
269
+ def defn(self, name: str | None = None) -> str:
270
+ args_str = ", ".join(a.defn() for a in self.arguments())
271
+ if name is None:
272
+ name = self.name()
273
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
274
+
275
+ def ptr_type(self) -> str:
276
+ # don't include defaults in type signature!
277
+ args_str = ", ".join(a.defn() for a in self.arguments())
278
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})"
279
+
280
+ def arguments(self) -> list[Binding]:
281
+ return native.arguments(self.func, symint=self.symint)
282
+
283
+ def returns_type(self) -> CType:
284
+ return native.returns_type(self.func.returns, symint=self.symint)
285
+
286
+ def dispatcher_exprs(self) -> list[Expr]:
287
+ return translate.translate(
288
+ self.arguments(), dispatcher.arguments(self.func), method=False
289
+ )
290
+
291
+
292
+ @dataclass(frozen=True)
293
+ class ViewInverseSignature:
294
+ g: NativeFunctionsViewGroup
295
+
296
+ def name(self) -> str:
297
+ return functionalization.reverse_name(self.g.view, include_namespace=False)
298
+
299
+ def decl(self) -> str:
300
+ return_type = functionalization.returns_type(self.g.view.func)
301
+ decls = [
302
+ a.decl()
303
+ for a in functionalization.op_arguments(self.g.view.func, is_reverse=True)
304
+ ]
305
+ return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});"
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class StructuredImplSignature:
310
+ g: NativeFunctionsGroup
311
+ name: str
312
+
313
+ def defn(self, name: str | None = None) -> str:
314
+ args_str = ", ".join(a.defn() for a in self.arguments())
315
+ return f"TORCH_IMPL_FUNC({self.name})({args_str})"
316
+
317
+ def arguments(self) -> list[Binding]:
318
+ return structured.impl_arguments(self.g)
319
+
320
+
321
+ # Helper functions
322
+
323
+
324
+ def kernel_signature(
325
+ f: NativeFunction, backend_index: BackendIndex, *, prefix: str = ""
326
+ ) -> NativeSignature | DispatcherSignature:
327
+ # Note [External Backends Follow Dispatcher API]
328
+ # Kernel signatures for in-tree backends follow the "native" API,
329
+ # while kernels for out-of-tree backends follow the dispatcher API.
330
+ # See the comments in `native.py` for details, but historically there have been
331
+ # some small differences in schema convention between them and the Dispatcher API.
332
+ # Any differences that require translating between the two will results in a runtime cost,
333
+ # so we'd like to keep the differences as small as possible.
334
+ # With external backends, we'd like to enforce that they write their kernels with schemas
335
+ # that match the Dispatcher API directly, if they can.
336
+ meta = backend_index.get_kernel(f)
337
+ symint = meta is not None and meta.supports_symint()
338
+ if symint:
339
+ assert f.func.has_symint(), (
340
+ f"attempted to define symint kernel for {backend_index.dispatch_key} without SymInt in schema"
341
+ )
342
+ if backend_index.external:
343
+ return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint)
344
+ else:
345
+ return NativeSignature(f.func, prefix=prefix, symint=symint)
346
+
347
+
348
+ # Functions only, no types
349
+ from torchgen.api import (
350
+ cpp,
351
+ dispatcher,
352
+ functionalization,
353
+ native,
354
+ structured,
355
+ translate,
356
+ )
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/types.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Where should I add a new type? `types_base.py` vs `types.py`
3
+
4
+ This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
5
+
6
+ `types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
7
+
8
+ The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
9
+ contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
10
+ if we want to generate code for another C++ library.
11
+
12
+ Add new types to `types.py` if these types are ATen/c10 related.
13
+ Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+
20
+ from torchgen.api.types.types_base import (
21
+ BaseCppType,
22
+ BaseCType,
23
+ boolT,
24
+ byteT,
25
+ charT,
26
+ CType,
27
+ doubleT,
28
+ floatT,
29
+ int32T,
30
+ longT,
31
+ shortT,
32
+ )
33
+ from torchgen.model import BaseTy, ScalarType
34
+
35
+
36
+ TENSOR_LIST_LIKE_CTYPES = [
37
+ "at::TensorList",
38
+ "const c10::List<::std::optional<at::Tensor>> &",
39
+ "const at::ITensorListRef &",
40
+ ]
41
+
42
+
43
+ halfT = BaseCppType("at", "Half")
44
+ complexHalfT = BaseCppType(
45
+ "c10", "complex<c10::Half>"
46
+ ) # stuffing template param here is an abuse
47
+ complexFloatT = BaseCppType("c10", "complex<float>")
48
+ complexDoubleT = BaseCppType("c10", "complex<double>")
49
+ bfloat16T = BaseCppType("at", "BFloat16")
50
+ float8_e5m2T = BaseCppType("at", "Float8_e5m2")
51
+ float8_e5m2fnuzT = BaseCppType("at", "Float8_e5m2fnuz")
52
+ float8_e4m3fnT = BaseCppType("at", "Float8_e4m3fn")
53
+ float8_e4m3fnuzT = BaseCppType("at", "Float8_e4m3fnuz")
54
+ float8_e8m0fnuT = BaseCppType("at", "Float8_e8m0fnu")
55
+ stringT = BaseCppType("c10", "string_view")
56
+ generatorT = BaseCppType("at", "Generator")
57
+ scalarTypeT = BaseCppType("at", "ScalarType")
58
+ tensorT = BaseCppType("at", "Tensor")
59
+ optionalTensorRefT = BaseCppType("at", "OptionalTensorRef")
60
+ tensorListT = BaseCppType("at", "TensorList")
61
+ iTensorListRefT = BaseCppType("at", "ITensorListRef")
62
+ iOptTensorListRefT = BaseCppType("at", "IOptTensorListRef")
63
+ dimnameT = BaseCppType("at", "Dimname")
64
+ dimnameListT = BaseCppType("at", "DimnameList")
65
+ dimVectorT = BaseCppType("at", "DimVector")
66
+ layoutT = BaseCppType("at", "Layout")
67
+ deviceT = BaseCppType("at", "Device")
68
+ deviceIndexT = BaseCppType("at", "DeviceIndex")
69
+ scalarT = BaseCppType("at", "Scalar")
70
+ optionalScalarRefT = BaseCppType("at", "OptionalScalarRef")
71
+ memoryFormatT = BaseCppType("at", "MemoryFormat")
72
+ qschemeT = BaseCppType("at", "QScheme")
73
+ storageT = BaseCppType("at", "Storage")
74
+ streamT = BaseCppType("at", "Stream")
75
+ intArrayRefT = BaseCppType("at", "IntArrayRef")
76
+ optionalIntArrayRefT = BaseCppType("at", "OptionalIntArrayRef")
77
+ optionalSymIntArrayRefT = BaseCppType("at", "OptionalSymIntArrayRef")
78
+ tensorOptionsT = BaseCppType("at", "TensorOptions")
79
+ typeAndSizeT = BaseCppType("torch::autograd::generated", "TypeAndSize")
80
+ tensorGeometryT = BaseCppType("at", "TensorGeometry")
81
+ SymIntT = BaseCppType("c10", "SymInt")
82
+ SymBoolT = BaseCppType("c10", "SymBool")
83
+ symIntArrayRefT = BaseCppType("c10", "SymIntArrayRef")
84
+
85
+ # Types representing template parameters. Technically, we probably shouldn't
86
+ # represent them this way in codegen, but it was pretty convenient.
87
+ scalar_t = BaseCppType("", "scalar_t")
88
+ opmath_t = BaseCppType("", "opmath_t")
89
+
90
+ ScalarTypeToCppMapping: dict[ScalarType, BaseCppType] = {
91
+ ScalarType.Byte: byteT,
92
+ ScalarType.Char: charT,
93
+ ScalarType.Short: shortT,
94
+ ScalarType.Int: int32T,
95
+ ScalarType.Long: longT,
96
+ ScalarType.Half: halfT,
97
+ ScalarType.Float: floatT,
98
+ ScalarType.Double: doubleT,
99
+ ScalarType.ComplexHalf: complexHalfT,
100
+ ScalarType.ComplexFloat: complexFloatT,
101
+ ScalarType.ComplexDouble: complexDoubleT,
102
+ ScalarType.Bool: boolT,
103
+ ScalarType.Float8_e5m2: float8_e5m2T,
104
+ ScalarType.Float8_e5m2fnuz: float8_e5m2fnuzT,
105
+ ScalarType.Float8_e4m3fn: float8_e4m3fnT,
106
+ ScalarType.Float8_e4m3fnuz: float8_e4m3fnuzT,
107
+ ScalarType.Float8_e8m0fnu: float8_e8m0fnuT,
108
+ }
109
+
110
+ BaseTypeToCppMapping: dict[BaseTy, BaseCppType] = {
111
+ BaseTy.int: longT,
112
+ BaseTy.float: doubleT,
113
+ BaseTy.bool: boolT,
114
+ BaseTy.str: stringT,
115
+ BaseTy.Generator: generatorT,
116
+ BaseTy.ScalarType: scalarTypeT,
117
+ BaseTy.Tensor: tensorT,
118
+ BaseTy.Dimname: dimnameT,
119
+ BaseTy.DimVector: dimVectorT,
120
+ BaseTy.Layout: layoutT,
121
+ BaseTy.Device: deviceT,
122
+ BaseTy.DeviceIndex: deviceIndexT,
123
+ BaseTy.Scalar: scalarT,
124
+ BaseTy.MemoryFormat: memoryFormatT,
125
+ BaseTy.QScheme: qschemeT,
126
+ BaseTy.Storage: storageT,
127
+ BaseTy.Stream: streamT,
128
+ BaseTy.SymInt: SymIntT,
129
+ BaseTy.SymBool: SymBoolT,
130
+ }
131
+
132
+ # CTypes encode C++ type structure as needed for translation.
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class OptionalCType(CType):
137
+ elem: CType
138
+
139
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
140
+ # Do not pass `strip_ref` recursively.
141
+ return f"::std::optional<{self.elem.cpp_type()}>"
142
+
143
+ def remove_const_ref(self) -> CType:
144
+ return OptionalCType(self.elem.remove_const_ref())
145
+
146
+
147
+ @dataclass(frozen=True)
148
+ class ListCType(CType):
149
+ elem: CType
150
+
151
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
152
+ # Do not pass `strip_ref` recursively.
153
+ return f"c10::List<{self.elem.cpp_type()}>"
154
+
155
+ def remove_const_ref(self) -> CType:
156
+ return ListCType(self.elem.remove_const_ref())
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class ArrayRefCType(CType):
161
+ elem: CType
162
+
163
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
164
+ # Do not pass `strip_ref` recursively.
165
+ return f"at::ArrayRef<{self.elem.cpp_type()}>"
166
+
167
+ def remove_const_ref(self) -> CType:
168
+ return ArrayRefCType(self.elem.remove_const_ref())
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class VectorizedCType(CType):
173
+ # This template is explicitly specialized, so the only valid
174
+ # elems are those we have specializations for (e.g., float, double, ...)
175
+ # scalar_t is also a common argument here (when we are codegen in
176
+ # a templated context)
177
+ elem: BaseCType
178
+
179
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
180
+ return f"at::vec::Vectorized<{self.elem.cpp_type()}>"
181
+
182
+ def remove_const_ref(self) -> CType:
183
+ return self
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/api/types/types_base.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Where should I add a new type? `types_base.py` vs `types.py`
3
+
4
+ This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
5
+
6
+ `types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
7
+
8
+ The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
9
+ contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
10
+ if we want to generate code for another C++ library.
11
+
12
+ Add new types to `types.py` if these types are ATen/c10 related.
13
+ Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from abc import ABC, abstractmethod
19
+ from dataclasses import dataclass
20
+ from enum import auto, Enum
21
+ from typing import TYPE_CHECKING, Union
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from torchgen.model import Argument, SelfArgument, TensorOptionsArguments
26
+
27
+
28
+ # An ArgName is just the str name of the argument in schema;
29
+ # but in some special circumstances, we may add a little extra
30
+ # context. The Enum SpecialArgName covers all of these cases;
31
+ # grep for their construction sites to see when they can occur.
32
+
33
+
34
+ class SpecialArgName(Enum):
35
+ possibly_redundant_memory_format = auto()
36
+
37
+
38
+ ArgName = Union[str, SpecialArgName]
39
+
40
+
41
+ # This class shouldn't be created directly; instead, use/create one of the singletons below.
42
+ @dataclass(frozen=True)
43
+ class BaseCppType:
44
+ ns: str | None
45
+ name: str
46
+
47
+ def __str__(self) -> str:
48
+ if self.ns is None or self.ns == "":
49
+ return self.name
50
+ return f"{self.ns}::{self.name}"
51
+
52
+
53
+ # The set of all non-templated, valid, fully-qualified names of C++ types that are used in the codegen.
54
+ # Templated types get their own dataclass, mainly to make namespace parsing easier.
55
+ byteT = BaseCppType("", "uint8_t")
56
+ charT = BaseCppType("", "int8_t")
57
+ shortT = BaseCppType("", "int16_t")
58
+ # It would be more symmetric for this to be called intT, but it easy to mix
59
+ # this up with JIT int (which is int64_t in C++), so we intentionally don't
60
+ # define intT to make it obvious when you've stuffed it up
61
+ int32T = BaseCppType("", "int32_t")
62
+ longT = BaseCppType("", "int64_t")
63
+ doubleT = BaseCppType("", "double")
64
+ floatT = BaseCppType("", "float")
65
+ boolT = BaseCppType("", "bool")
66
+ voidT = BaseCppType("", "void")
67
+
68
+
69
+ class CType(ABC):
70
+ @abstractmethod
71
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
72
+ raise NotImplementedError
73
+
74
+ @abstractmethod
75
+ def remove_const_ref(self) -> CType:
76
+ return self
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class BaseCType(CType):
81
+ type: BaseCppType
82
+
83
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
84
+ return str(self.type)
85
+
86
+ def remove_const_ref(self) -> CType:
87
+ return self
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class ConstRefCType(CType):
92
+ elem: CType
93
+
94
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
95
+ if strip_ref:
96
+ return self.elem.cpp_type(strip_ref=strip_ref)
97
+ return f"const {self.elem.cpp_type()} &"
98
+
99
+ def remove_const_ref(self) -> CType:
100
+ return self.elem.remove_const_ref()
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class VectorCType(CType):
105
+ elem: CType
106
+
107
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
108
+ # Do not pass `strip_ref` recursively.
109
+ return f"::std::vector<{self.elem.cpp_type()}>"
110
+
111
+ def remove_const_ref(self) -> CType:
112
+ return VectorCType(self.elem.remove_const_ref())
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class ArrayCType(CType):
117
+ elem: CType
118
+ size: int
119
+
120
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
121
+ # Do not pass `strip_ref` recursively.
122
+ return f"::std::array<{self.elem.cpp_type()},{self.size}>"
123
+
124
+ def remove_const_ref(self) -> CType:
125
+ return ArrayCType(self.elem.remove_const_ref(), self.size)
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class TupleCType(CType):
130
+ elems: list[CType]
131
+
132
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
133
+ # Do not pass `strip_ref` recursively.
134
+ return f"::std::tuple<{','.join([e.cpp_type() for e in self.elems])}>"
135
+
136
+ def remove_const_ref(self) -> CType:
137
+ return TupleCType([e.remove_const_ref() for e in self.elems])
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class MutRefCType(CType):
142
+ elem: CType
143
+
144
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
145
+ if strip_ref:
146
+ return self.elem.cpp_type(strip_ref=strip_ref)
147
+ return f"{self.elem.cpp_type()} &"
148
+
149
+ def remove_const_ref(self) -> CType:
150
+ return self.elem.remove_const_ref()
151
+
152
+
153
+ # A NamedCType is short for Named C++ semantic type. A NamedCType represents a C++ type, plus
154
+ # semantic information about what it represents. For example, consider the
155
+ # argument "bool pin_memory"; its normal C++ type is "bool", but its C++
156
+ # semantic type also keeps track that this represents a "pin_memory"; you can't
157
+ # just use a random other boolean in a context where you need a "pin_memory"!
158
+ #
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class NamedCType:
163
+ name: ArgName
164
+ type: CType
165
+
166
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
167
+ return self.type.cpp_type(strip_ref=strip_ref)
168
+
169
+ def remove_const_ref(self) -> NamedCType:
170
+ return NamedCType(self.name, self.type.remove_const_ref())
171
+
172
+ def with_name(self, name: str) -> NamedCType:
173
+ return NamedCType(name, self.type)
174
+
175
+
176
+ # A binding represents any C++ binding site for a formal parameter.
177
+ # We don't distinguish between binding sites for different APIs;
178
+ # instead, all of the important distinctions are encoded in CType,
179
+ # which you can use to figure out if a given Binding is appropriate
180
+ # for use in another context. (See torchgen.api.translate)
181
+
182
+
183
+ @dataclass(frozen=True)
184
+ class Binding:
185
+ name: str
186
+ nctype: NamedCType
187
+ argument: Argument | TensorOptionsArguments | SelfArgument
188
+ # TODO: maybe don't represent default here
189
+ default: str | None = None
190
+
191
+ def rename(self, name: str) -> Binding:
192
+ return Binding(
193
+ name=name,
194
+ nctype=self.nctype,
195
+ argument=self.argument,
196
+ default=self.default,
197
+ )
198
+
199
+ @property
200
+ def type(self) -> str:
201
+ return self.nctype.cpp_type()
202
+
203
+ def no_default(self) -> Binding:
204
+ return Binding(
205
+ name=self.name,
206
+ nctype=self.nctype,
207
+ default=None,
208
+ argument=self.argument,
209
+ )
210
+
211
+ def decl(self, *, func_ptr_cast: bool = False) -> str:
212
+ mb_default = ""
213
+ if self.default is not None:
214
+ mb_default = f"={self.default}"
215
+
216
+ # casting only needs to know the type
217
+ if func_ptr_cast:
218
+ return f"{self.type}"
219
+ else:
220
+ return f"{self.type} {self.name}{mb_default}"
221
+
222
+ def defn(self) -> str:
223
+ return f"{self.type} {self.name}"
224
+
225
+ def with_name(self, name: str) -> Binding:
226
+ return Binding(
227
+ name=name, nctype=self.nctype, argument=self.argument, default=self.default
228
+ )
229
+
230
+
231
+ # An Expr is a C++ expression. It has a C++ string representing its syntax,
232
+ # as well as a CType saying what it provides.
233
+
234
+
235
+ @dataclass(frozen=True)
236
+ class Expr:
237
+ expr: str
238
+ type: NamedCType
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (791 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc ADDED
Binary file (36.8 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc ADDED
Binary file (2.88 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/native_functions.cpython-312.pyc ADDED
Binary file (3.67 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc ADDED
Binary file (44.3 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/ufunc.cpython-312.pyc ADDED
Binary file (25.4 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (232 Bytes). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc ADDED
Binary file (14 kB). View file
 
Prism/LLaDA/LLaDA_Prism/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc ADDED
Binary file (499 Bytes). View file