jonghanko commited on
Commit
f43c152
·
verified ·
1 Parent(s): 8622a4b

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. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py +0 -0
  2. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/__init__.cpython-310.pyc +0 -0
  3. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/autograd.cpython-310.pyc +0 -0
  4. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/impl.cpython-310.pyc +0 -0
  5. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py +275 -0
  6. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/impl.py +670 -0
  7. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__init__.py +545 -0
  8. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/__init__.cpython-310.pyc +0 -0
  9. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-310.pyc +0 -0
  10. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py +0 -0
  11. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py +335 -0
  12. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py +266 -0
  13. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py +67 -0
  14. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-310.pyc +0 -0
  15. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-310.pyc +0 -0
  16. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-310.pyc +0 -0
  17. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-310.pyc +0 -0
  18. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-310.pyc +0 -0
  19. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-310.pyc +0 -0
  20. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-310.pyc +0 -0
  21. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-310.pyc +0 -0
  22. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-310.pyc +0 -0
  23. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-310.pyc +0 -0
  24. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-310.pyc +0 -0
  25. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-310.pyc +0 -0
  26. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-310.pyc +0 -0
  27. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-310.pyc +0 -0
  28. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-310.pyc +0 -0
  29. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-310.pyc +0 -0
  30. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-310.pyc +0 -0
  31. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-310.pyc +0 -0
  32. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-310.pyc +0 -0
  33. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-310.pyc +0 -0
  34. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-310.pyc +0 -0
  35. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-310.pyc +0 -0
  36. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-310.pyc +0 -0
  37. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-310.pyc +0 -0
  38. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/_invoke_quant.py +65 -0
  39. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/aoti_call_delegate.py +109 -0
  40. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/associative_scan.py +461 -0
  41. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/auto_functionalize.py +825 -0
  42. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/base_hop.py +182 -0
  43. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/cond.py +703 -0
  44. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/effects.py +288 -0
  45. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/executorch_call_delegate.py +175 -0
  46. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flat_apply.py +125 -0
  47. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flex_attention.py +1196 -0
  48. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/foreach_map.py +23 -0
  49. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/hints_wrap.py +151 -0
  50. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_subgraph.py +307 -0
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py ADDED
File without changes
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (227 Bytes). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/autograd.cpython-310.pyc ADDED
Binary file (8.93 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/impl.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.utils._pytree as pytree
4
+ from collections import namedtuple
5
+ import functools
6
+
7
+
8
+ # NOTE [CustomOp autograd kernel indirection]
9
+ # We register `inner` as the autograd kernel for this custom_op.
10
+ # `inner` either calls the autograd formula registered by the user,
11
+ # or goes into an `autograd_not_implemented` kernel.
12
+ #
13
+ # The reason why this indirection exists is
14
+ # so that we can swap out the autograd kernel (the PyTorch dispatcher
15
+ # doesn't actually allow us to do this). By default, we want
16
+ # the `autograd_not_implemented` behavior, but then the user may come
17
+ # and register something that is actually a backward formula
18
+ def autograd_kernel_indirection(custom_op):
19
+ autograd_fallback = autograd_not_implemented(custom_op)
20
+
21
+ def inner(*args, **kwargs):
22
+ if custom_op._has_impl('autograd'):
23
+ kernel = custom_op._get_impl('autograd').func
24
+ return kernel(*args, **kwargs)
25
+ # As explained in NOTE ["backward", "save_for_backward", and "autograd"],
26
+ # after the user gives us "backward" and "save_for_backward", we generate
27
+ # the "autograd" impl. If the user only provided one, then we tell
28
+ # the user they've done something wrong.
29
+ if custom_op._has_impl('save_for_backward') or custom_op._has_impl('backward'):
30
+ missing = (
31
+ 'save_for_backward' if custom_op._has_impl('backward')
32
+ else 'backward'
33
+ )
34
+ found = 'save_for_backward' if missing == 'backward' else 'backward'
35
+ loc = custom_op._get_impl(found).location
36
+ raise RuntimeError(
37
+ f"We found a '{found}' registration for {custom_op} at "
38
+ f"{loc} but were unable to find a '{missing}' registration. "
39
+ f"To use the CustomOp API to register a backward formula, "
40
+ f"please provide us both a backward function and a "
41
+ f"'save for backward' function via `impl_backward` and "
42
+ f"`impl_save_for_backward` respectively.")
43
+ return autograd_fallback(*args, **kwargs)
44
+ return inner
45
+
46
+
47
+ # TODO(#101191): Use the actual C++ autograd not implemented fallback,
48
+ # or change the default autograd fallback to the autograd not implemented fallback.
49
+ def autograd_not_implemented(custom_op):
50
+ def kernel(*args, **kwargs):
51
+ if torch.is_grad_enabled() and pytree.tree_any(
52
+ lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs)
53
+ ):
54
+ raise RuntimeError("Autograd has not been implemented for operator")
55
+ with torch._C._AutoDispatchBelowAutograd():
56
+ return custom_op(*args, **kwargs)
57
+ return kernel
58
+
59
+
60
+ def mark_non_differentiable(ctx, output, output_differentiability):
61
+ # Output types are restricted to be:
62
+ # - Tensor
63
+ # - Tensor[]
64
+ # - int, bool, Scalar, float
65
+ # See _check_can_register_backward
66
+ if output_differentiability is not None:
67
+ if not isinstance(output, tuple):
68
+ tuple_output = (output,)
69
+ else:
70
+ tuple_output = output # type: ignore[assignment]
71
+ assert len(output_differentiability) == len(tuple_output)
72
+ non_differentiable_tensors = []
73
+ for idx, (differentiable, out) in enumerate(zip(output_differentiability, tuple_output)):
74
+ if isinstance(out, torch.Tensor):
75
+ if not differentiable:
76
+ non_differentiable_tensors.append(out)
77
+ continue
78
+ if isinstance(out, list):
79
+ if not differentiable:
80
+ non_differentiable_tensors.extend(out)
81
+ continue
82
+ if differentiable:
83
+ raise RuntimeError(
84
+ f"With output_differentiability={output_differentiability}. "
85
+ f"At idx {idx}, we received an object of type {type(out)} that "
86
+ f"is not a Tensor, so it cannot have be marked as differentiable in "
87
+ f"output_differentiability.")
88
+ if non_differentiable_tensors:
89
+ ctx.mark_non_differentiable(*non_differentiable_tensors)
90
+
91
+
92
+ def construct_autograd_kernel(
93
+ schema,
94
+ output_differentiability,
95
+ custom_op,
96
+ op_overload,
97
+ save_for_backward_fn,
98
+ backward_fn):
99
+
100
+ def apply(*args):
101
+ flat_args, spec = pytree.tree_flatten(args)
102
+ out_spec = None
103
+
104
+ def forward(ctx, *flat_args):
105
+ ctx.set_materialize_grads(True)
106
+ args = pytree.tree_unflatten(list(flat_args), spec)
107
+ with torch._C._AutoDispatchBelowAutograd():
108
+ output = op_overload(*args)
109
+
110
+ # We use the info about args to give better error messages in backward
111
+ args_info = namedtuple_args(
112
+ schema, pytree.tree_map(type, args))
113
+
114
+ save_for_backward_fn_inputs = namedtuple_args(schema, args)
115
+ to_save = save_for_backward_fn(save_for_backward_fn_inputs, output)
116
+
117
+ save_pytree_for_backward(ctx, (to_save, args_info))
118
+ mark_non_differentiable(ctx, output, output_differentiability)
119
+
120
+ nonlocal out_spec
121
+ flat_output, out_spec = pytree.tree_flatten(output)
122
+ return tuple(flat_output)
123
+
124
+ def backward(ctx, *flat_grad_output):
125
+ assert out_spec is not None
126
+ grads = pytree.tree_unflatten(list(flat_grad_output), out_spec)
127
+ saved, args_info = unpack_saved(ctx)
128
+ # There is nothing on the ctx object for now, it is just there so
129
+ # that we can add additional things in the future.
130
+ inner_ctx = object()
131
+ if not isinstance(grads, tuple):
132
+ grads = (grads,)
133
+ grad_inputs_dict = backward_fn(inner_ctx, saved, *grads)
134
+
135
+ # Massage the grad_inputs_dict to a form acceptable by
136
+ # autograd.Function.
137
+ validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info)
138
+ return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info)
139
+
140
+ generated_cls = gen_autograd_function(
141
+ custom_op._opname + '_customop', forward, backward)
142
+
143
+ flat_output = generated_cls.apply(*flat_args)
144
+ assert out_spec is not None
145
+ return pytree.tree_unflatten(list(flat_output), out_spec)
146
+ return apply
147
+
148
+
149
+ def gen_autograd_function(name, forward, backward):
150
+ generated_cls = type(
151
+ name,
152
+ (torch.autograd.Function,),
153
+ {
154
+ 'forward': staticmethod(forward),
155
+ 'backward': staticmethod(backward),
156
+ }
157
+ )
158
+ return generated_cls
159
+
160
+
161
+ @functools.lru_cache
162
+ def namedtuple_args_cls(schema):
163
+ attribs = [arg.name for arg in schema.arguments.flat_all]
164
+ name = str(schema.name) + "_args"
165
+ # mypy doesn't support dynamic namedtuple name
166
+ tuple_cls = namedtuple(name, attribs) # type: ignore[misc]
167
+ return tuple_cls
168
+
169
+
170
+ def namedtuple_args(schema, args):
171
+ assert isinstance(args, tuple)
172
+ tuple_cls = namedtuple_args_cls(schema)
173
+ return tuple_cls(*args)
174
+
175
+
176
+ def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info):
177
+ def error(what):
178
+ backward = forward_op._get_impl('backward')
179
+ raise RuntimeError(
180
+ f"In the backward function defined for {forward_op} at "
181
+ f"{backward.location} using the CustomOp API, {what}")
182
+
183
+ if not isinstance(grad_inputs_dict, dict):
184
+ error(f"expected the output of the backward function to be a dict but "
185
+ f"got {type(grad_inputs_dict)}")
186
+
187
+ expected_keys = {arg.name for arg in forward_op._schema.arguments.flat_all
188
+ if arg.type.is_tensor_like()}
189
+ actual_keys = grad_inputs_dict.keys()
190
+ if expected_keys != actual_keys:
191
+ error(f"expected the returned grad_input dict to have keys "
192
+ f"{expected_keys} but got {actual_keys}. The backward "
193
+ f"function must return a gradient (can be None) for each arg "
194
+ f"to the CustomOp that may be a Tensor or Sequence[Tensor]. "
195
+ f"Args declared to be non-Tensor-like types should not appear "
196
+ f"in the grad_input dict")
197
+
198
+ for name, grad in grad_inputs_dict.items():
199
+ arg_info = getattr(args_info, name)
200
+
201
+ if isinstance(arg_info, list):
202
+ if not isinstance(grad, (tuple, list)):
203
+ error(f"for input '{name}' expected the grad_input dict to "
204
+ f"hold a list of gradients but got object of type "
205
+ f"{type(grad)}.")
206
+ if not len(grad) == len(arg_info):
207
+ error(f"for input '{name}' expected the grad_input dict to "
208
+ f"hold a list of {len(arg_info)} gradients but got "
209
+ f"{len(grad)}")
210
+ for idx, (g, info) in enumerate(zip(grad, arg_info)):
211
+ if g is None:
212
+ continue
213
+ if not isinstance(g, torch.Tensor):
214
+ error(f"for input '{name}' expected the grad_input dict to "
215
+ f"hold a list of None or Tensor gradients but got "
216
+ f"object of {type(g)} at index {idx}")
217
+ if not issubclass(info, torch.Tensor):
218
+ error(f"for input '{name}', got a Tensor as the gradient "
219
+ f"for the {idx}-th value but expected None because "
220
+ f"the {idx}-th value was not a Tensor (it was "
221
+ f"type {arg_info}")
222
+ continue
223
+
224
+ if grad is None:
225
+ continue
226
+ if not isinstance(grad, torch.Tensor):
227
+ error(f"got object of type {type(grad)} as the gradient for input "
228
+ f"'{name}', "
229
+ f"but expected the gradient to be either None or a Tensor")
230
+ if not issubclass(arg_info, torch.Tensor):
231
+ error(f"got a Tensor as the gradient for input '{name}' but "
232
+ f"expected None as the gradient because input '{name}' "
233
+ f"was not a Tensor (it was type {arg_info}).")
234
+
235
+
236
+ def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info):
237
+ result = []
238
+ for name, arg_info in args_info._asdict().items():
239
+ if name not in grad_inputs_dict:
240
+ result.append(pytree.tree_map(lambda x: None, arg_info))
241
+ continue
242
+ result.append(grad_inputs_dict[name])
243
+ return tuple(pytree.tree_leaves(result))
244
+
245
+ # Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it.
246
+ # autograd.Function prefers that users use ctx.save_for_backward to
247
+ # save Tensors (to avoid reference cycles) and for non-Tensors to go onto the
248
+ # ctx object.
249
+ def save_pytree_for_backward(ctx, stuff):
250
+ flat_stuff, spec = pytree.tree_flatten(stuff)
251
+ num_elts = len(flat_stuff)
252
+ tensor_idxs = [idx for idx, thing in enumerate(flat_stuff)
253
+ if isinstance(thing, torch.Tensor)]
254
+ non_tensor_idxs = [idx for idx, thing in enumerate(flat_stuff)
255
+ if not isinstance(thing, torch.Tensor)]
256
+ tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)]
257
+ non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)]
258
+
259
+ ctx.spec = spec
260
+ ctx.num_elts = num_elts
261
+ ctx.save_for_backward(*tensors)
262
+ ctx.tensor_idxs = tensor_idxs
263
+ ctx.saved_non_tensors = non_tensors
264
+ ctx.non_tensor_idxs = non_tensor_idxs
265
+
266
+
267
+ # Inverse operation to save_pytree_for_backward
268
+ def unpack_saved(ctx):
269
+ flat_stuff = [None] * ctx.num_elts
270
+ for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs):
271
+ flat_stuff[idx] = tensor
272
+ for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs):
273
+ flat_stuff[idx] = non_tensor
274
+ stuff = pytree.tree_unflatten(flat_stuff, ctx.spec)
275
+ return stuff
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/impl.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ import functools
4
+ import inspect
5
+ import sys
6
+ import typing
7
+ import weakref
8
+ import warnings
9
+
10
+ from torchgen.model import FunctionSchema, OperatorName, SchemaKind, BaseType, ListType, BaseTy
11
+
12
+ import torch
13
+ import torch._C as _C
14
+ import torch.library as library
15
+ from torch.library import get_ctx
16
+
17
+ from .autograd import autograd_kernel_indirection, construct_autograd_kernel
18
+ import torch._library.infer_schema
19
+ from torch._library.infer_schema import infer_schema
20
+
21
+ """
22
+ torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library.
23
+ Please use those APIs instead.
24
+ """
25
+
26
+ __all__ = ["custom_op", "CustomOp", "get_ctx"]
27
+
28
+
29
+ SUPPORTED_DEVICE_TYPE_TO_KEY = {
30
+ "cpu": "CPU",
31
+ "cuda": "CUDA",
32
+ }
33
+
34
+ # We will not let users register CustomOps with anything that could look like
35
+ # PyTorch internals to avoid confusion.
36
+ RESERVED_NS = {
37
+ "prim",
38
+ "prims",
39
+ "aten",
40
+ "at",
41
+ "torch",
42
+ "pytorch",
43
+ }
44
+
45
+ def warn_deprecated():
46
+ warnings.warn(
47
+ "torch._custom_op is deprecated and will be removed in PyTorch 2.6, please "
48
+ "use the equivalent torch.library API instead.", DeprecationWarning)
49
+
50
+
51
+ def custom_op(
52
+ qualname: str, manual_schema: typing.Optional[str] = None
53
+ ) -> typing.Callable:
54
+ r"""
55
+ This API is deprecated, please use torch.library.custom_op instead
56
+ """
57
+ warn_deprecated()
58
+
59
+ def inner(func):
60
+ if not inspect.isfunction(func):
61
+ raise ValueError(
62
+ f"custom_op(...)(func): Expected `func` to be a Python "
63
+ f"function, got: {type(func)}"
64
+ )
65
+
66
+ ns, name = parse_qualname(qualname)
67
+ validate_namespace(ns)
68
+ if func.__name__ != name:
69
+ raise ValueError(
70
+ f"custom_op(qualname='{qualname}', ...)(func): expected `func` "
71
+ f"to have name '{name}' but got '{func.__name__}'. "
72
+ f"Please either change the name of `func` or the qualname that "
73
+ f"is passed to `custom_op`"
74
+ )
75
+
76
+ schema = infer_schema(func, mutates_args=()) if manual_schema is None else manual_schema
77
+ schema_str = f"{name}{schema}"
78
+ function_schema = FunctionSchema.parse(schema_str)
79
+ validate_schema(function_schema)
80
+ if manual_schema is not None:
81
+ validate_function_matches_schema(function_schema, func)
82
+
83
+ lib = library.Library(ns, "FRAGMENT")
84
+ lib.define(schema_str)
85
+ ophandle = find_ophandle_or_throw(ns, function_schema.name)
86
+ result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True)
87
+
88
+ result.__name__ = func.__name__
89
+ result.__module__ = func.__module__
90
+ result.__doc__ = func.__doc__
91
+
92
+ library.impl(lib, result._opname, "Autograd")(
93
+ autograd_kernel_indirection(weakref.proxy(result))
94
+ )
95
+
96
+ torch._C._dispatch_set_report_error_callback(
97
+ ophandle, functools.partial(report_error_callback, weakref.proxy(result))
98
+ )
99
+
100
+ return result
101
+
102
+ return inner
103
+
104
+
105
+ # Global dictionary holding references to all CustomOp objects
106
+ # Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime])
107
+ # Used to query the CustomOp associated with a specific C++ dispatcher operator.
108
+ # An example usage is FakeTensor: FakeTensor checks if a specific operator
109
+ # has an implementation registered via the CustomOp API.
110
+ # Indexed by qualname (e.g. aten::foo)
111
+ global_registry: dict[str, "CustomOp"] = {}
112
+
113
+
114
+ class CustomOp:
115
+ r"""
116
+ This API is deprecated, please use torch.library.custom_op instead
117
+ """
118
+
119
+ def __init__(self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False):
120
+ super().__init__()
121
+ warn_deprecated()
122
+ if not _private_access:
123
+ raise RuntimeError(
124
+ "The CustomOp constructor is private and we do not guarantee "
125
+ "BC for it. Please use custom_op(...) to create a CustomOp object"
126
+ )
127
+ name = f"{cpp_ns}::{operator_name}"
128
+ self._schema = schema
129
+ self._cpp_ns = cpp_ns
130
+ self._lib: library.Library = lib
131
+ self._ophandle: _C._DispatchOperatorHandle = ophandle
132
+ # Has the name of the op, e.g. "foo". We cache here for convenience.
133
+ self._opname: str = operator_name
134
+ # this is _opname but with namespace. e.g. "custom::foo"
135
+ self._qualname: str = name
136
+ self.__name__ = None # mypy requires this
137
+ # NB: Some of these impls are registered as kernels to DispatchKeys.
138
+ # Modifying the _impls dict directly won't do anything in that case.
139
+ self._impls: dict[str, typing.Optional[FuncAndLocation]] = {}
140
+ # See NOTE [CustomOp autograd kernel indirection]
141
+ self._registered_autograd_kernel_indirection = False
142
+
143
+ global_registry[self._qualname] = self
144
+
145
+ def _register_autograd_kernel_indirection(self):
146
+ assert not self._registered_autograd_kernel_indirection
147
+ self._lib.impl(self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd")
148
+ self._registered_autograd_kernel_indirection = True
149
+
150
+ # Records the impl and the source location in self._impls
151
+ # Note that this doesn't cause torch.library to use the impl, that
152
+ # needs to be done in a separate self._lib.impl call.
153
+ def _register_impl(self, kind, func, stacklevel=2):
154
+ if self._has_impl(kind):
155
+ func_and_location = self._impls[kind]
156
+ assert func_and_location is not None # Pacify mypy
157
+ location = func_and_location.location
158
+ raise RuntimeError(
159
+ f"Attempting to register a {kind} impl for operator {self._qualname} "
160
+ f"that already has a {kind} impl registered from Python at "
161
+ f"{location}. This is not supported."
162
+ )
163
+ frame = inspect.getframeinfo(sys._getframe(stacklevel))
164
+ location = f"{frame.filename}:{frame.lineno}"
165
+ self._impls[kind] = FuncAndLocation(func, location)
166
+
167
+ def _get_impl(self, kind):
168
+ return self._impls[kind]
169
+
170
+ def _has_impl(self, kind):
171
+ return kind in self._impls
172
+
173
+ def _destroy(self):
174
+ # NOTE: [CustomOp lifetime]
175
+ # A CustomOp, once created, lives forever. The mechanism is that the
176
+ # global registry holds a reference to it. However, to make testing
177
+ # easier, we want to be able to destroy CustomOp objects.
178
+ # CustomOp._destroy does the job, though it leaves the CustomOp
179
+ # in a garbage state.
180
+ del self._lib
181
+
182
+ opnamespace = getattr(torch.ops, self._cpp_ns)
183
+ if hasattr(opnamespace, self._opname):
184
+ delattr(opnamespace, self._opname)
185
+
186
+ del global_registry[self._qualname]
187
+
188
+ def __repr__(self):
189
+ return f'<CustomOp(op="{self._qualname}")>'
190
+
191
+ def __call__(self, *args, **kwargs):
192
+ # Bypass torch.ops.* and directly do OperatorHandle::callBoxed.
193
+ # Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime
194
+ # issues from caching operators that make testing CustomOp difficult).
195
+ result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs)
196
+ return result
197
+
198
+ def impl(
199
+ self, device_types: typing.Union[str, typing.Iterable[str]], _stacklevel=2,
200
+ ) -> typing.Callable:
201
+ r"""
202
+ This API is deprecated, please use torch.library.custom_op instead
203
+ """
204
+ if isinstance(device_types, str):
205
+ device_types = [device_types]
206
+ for device_type in device_types:
207
+ validate_device_type(device_type)
208
+
209
+ def inner(f):
210
+ for device_type in set(device_types):
211
+ self._check_doesnt_have_library_impl(device_type)
212
+ self._register_impl(device_type, f, stacklevel=_stacklevel)
213
+ dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
214
+ library.impl(self._lib, self._opname, dispatch_key)(f)
215
+ return f
216
+
217
+ return inner
218
+
219
+ def _check_doesnt_have_library_impl(self, device_type):
220
+ if self._has_impl(device_type):
221
+ return
222
+ key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
223
+ if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key):
224
+ raise RuntimeError(
225
+ f"impl(..., device_types={device_type}): the operator {self._qualname} "
226
+ f"already has an implementation for this device type via a "
227
+ f"pre-existing torch.library or TORCH_LIBRARY registration.")
228
+
229
+ def impl_factory(self) -> typing.Callable:
230
+ r"""Register an implementation for a factory function."""
231
+
232
+ def inner(f):
233
+ self._register_impl("factory", f)
234
+ library.impl(self._lib, self._opname, "BackendSelect")(f)
235
+ return f
236
+
237
+ return inner
238
+
239
+ def impl_abstract(self, _stacklevel=2) -> typing.Callable:
240
+ r"""
241
+ This API is deprecated, please use torch.library.custom_op instead
242
+ """
243
+
244
+ def inner(f):
245
+ self._check_doesnt_have_library_meta_impl()
246
+ self._register_impl("abstract", f, stacklevel=_stacklevel)
247
+ location = self._get_impl("abstract").location
248
+
249
+ qualname = self._qualname
250
+
251
+ # Handle DispatchKey.Meta registration
252
+ @functools.wraps(f)
253
+ def f_with_ctx(*args, **kwargs):
254
+ def error_on_ctx():
255
+ raise RuntimeError(
256
+ f"Attempted to call get_ctx() for the meta implementation "
257
+ f"for {qualname}."
258
+ f"You have presumably called get_ctx() because the operator "
259
+ f"has a data-dependent output shape; if so, there is no "
260
+ f"such meta implementation and this error is the correct "
261
+ f"behavior. Otherwise, please remove the call to get_ctx() "
262
+ f"in the implementation registered with impl_abstract "
263
+ f"at {location}"
264
+ )
265
+
266
+ with torch._library.fake_impl.set_ctx_getter(error_on_ctx):
267
+ return f(*args, **kwargs)
268
+
269
+ self._lib.impl(self._opname, f_with_ctx, "Meta")
270
+ return f
271
+
272
+ return inner
273
+
274
+ def _check_can_register_backward(self):
275
+ def error(detail):
276
+ raise RuntimeError(
277
+ f"Cannot use torch._custom_ops APIs to register backward "
278
+ f"formula for {detail}. Got operator "
279
+ f"{self._qualname} with schema: {schema}"
280
+ )
281
+
282
+ schema = self._schema
283
+ if schema.kind() != SchemaKind.functional:
284
+ error("non-functional operator")
285
+
286
+ rets = schema.returns
287
+ if not schema.returns:
288
+ error("operator with no returns")
289
+
290
+ assert len(rets) > 0
291
+ is_non_mutating_view = any(
292
+ r.annotation is not None and not r.annotation.is_write for r in rets
293
+ )
294
+ if is_non_mutating_view:
295
+ error("operator that returns views")
296
+
297
+ # We make assumptions about the schema's return types.
298
+ allowed_return_types = {
299
+ BaseType(BaseTy.int): "int",
300
+ BaseType(BaseTy.SymInt): "SymInt",
301
+ BaseType(BaseTy.bool): "bool",
302
+ BaseType(BaseTy.float): "float",
303
+ BaseType(BaseTy.Tensor): "Tensor",
304
+ ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]",
305
+ }
306
+ for ret in schema.returns:
307
+ if ret.type in allowed_return_types:
308
+ continue
309
+ error(f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})")
310
+
311
+ def _check_doesnt_have_library_autograd_impl(self):
312
+ if self._registered_autograd_kernel_indirection:
313
+ return
314
+
315
+ if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "CompositeImplicitAutograd"):
316
+ raise RuntimeError(
317
+ f"impl_backward/impl_save_for_backward: the operator {self._qualname} "
318
+ f"already has an implementation for this device type via a "
319
+ f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
320
+ f"CompositeImplicitAutograd operators do not need an autograd formula; "
321
+ f"instead, the operator will decompose into its constituents and those "
322
+ f"can have autograd formulas defined on them.")
323
+
324
+ # We can improve this by adding "all Autograd<BACKEND> keys", but
325
+ # realistically people will just be using this API for CPU/CUDA for now.
326
+ for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]:
327
+ if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key):
328
+ raise RuntimeError(
329
+ f"impl_backward/impl_save_for_backward: "
330
+ f"the operator {self._qualname} already has an Autograd kernel "
331
+ f"registered to DispatchKey::{key} vi a pre-existing "
332
+ f"torch.library or TORCH_LIBRARY registration. Please either "
333
+ f"remove those registrations or don't use the torch._custom_ops APIs")
334
+
335
+ def _check_doesnt_have_library_meta_impl(self):
336
+ if self._has_impl("abstract"):
337
+ return
338
+
339
+ # If the user's operator is CompositeExplicitAutograd,
340
+ # allow them to impl_abstract. This is being pragmatic
341
+ # (existing custom ops may have CompositeExplicitAutograd
342
+ # registration that don't work with Meta kernels, so this
343
+ # gives them an escape hatch).
344
+ if (
345
+ _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "CompositeExplicitAutograd")
346
+ and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta")
347
+ ):
348
+ return
349
+
350
+ # Otherwise, if the user's already has a Meta kernel or their
351
+ # op is CompositeImplicitAutograd or some other alias dispatch key,
352
+ # raise.
353
+
354
+ # Special case for CompositeImplicitAutograd
355
+ if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "CompositeImplicitAutograd"):
356
+ raise RuntimeError(
357
+ f"impl_abstract(...): the operator {self._qualname} "
358
+ f"already has an implementation for this device type via a "
359
+ f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
360
+ f"CompositeImplicitAutograd operators do not need an abstract impl; "
361
+ f"instead, the operator will decompose into its constituents and those "
362
+ f"can have abstract impls defined on them.")
363
+
364
+ if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"):
365
+ raise RuntimeError(
366
+ f"impl_abstract(...): the operator {self._qualname} "
367
+ f"already has an DispatchKey::Meta implementation via a "
368
+ f"pre-existing torch.library or TORCH_LIBRARY registration. "
369
+ f"Please either remove that registration or don't call impl_abstract.")
370
+
371
+ # NOTE ["backward", "save_for_backward", and "autograd"]
372
+ # As a part of the explicit autograd API, a user must provide us
373
+ # a "save_for_backward" function and a "backward" function.
374
+ # When both of these have been provided, then we automatically
375
+ # construct the "autograd" kernel.
376
+ def _register_autograd_kernel(self):
377
+ assert self._has_impl("backward")
378
+ assert self._has_impl("save_for_backward")
379
+ kernel = construct_autograd_kernel(
380
+ self._schema,
381
+ self._output_differentiability,
382
+ self,
383
+ get_op(self._qualname),
384
+ self._get_impl("save_for_backward").func,
385
+ self._get_impl("backward").func)
386
+ self._register_impl("autograd", kernel)
387
+
388
+ def impl_save_for_backward(self, _stacklevel=2):
389
+ r"""Register a function that tells us what to save for backward.
390
+
391
+ Please see impl_backward for more details.
392
+ """
393
+ def inner(f):
394
+ self._check_can_register_backward()
395
+ self._check_doesnt_have_library_autograd_impl()
396
+ if not self._registered_autograd_kernel_indirection:
397
+ self._register_autograd_kernel_indirection()
398
+ self._register_impl("save_for_backward", f, stacklevel=_stacklevel)
399
+ if self._has_impl("backward"):
400
+ self._register_autograd_kernel()
401
+ return inner
402
+
403
+ def impl_backward(self, output_differentiability=None, _stacklevel=2):
404
+ r"""
405
+ This API is deprecated, please use torch.library.custom_op instead
406
+ """
407
+ if output_differentiability is not None:
408
+ def yell():
409
+ raise RuntimeError(
410
+ f"impl_backward(output_differentiability): expected "
411
+ f"output_differentiability to be a list of bools with "
412
+ f"length equal to the number of outputs of this CustomOp "
413
+ f"got: {output_differentiability}")
414
+
415
+ if not isinstance(output_differentiability, list):
416
+ yell()
417
+ for diff in output_differentiability:
418
+ if not isinstance(diff, bool):
419
+ yell()
420
+ if len(self._schema.returns) != len(output_differentiability):
421
+ yell()
422
+
423
+ def inner(f):
424
+ self._check_can_register_backward()
425
+ self._check_doesnt_have_library_autograd_impl()
426
+ if not self._registered_autograd_kernel_indirection:
427
+ self._register_autograd_kernel_indirection()
428
+ self._register_impl("backward", f, stacklevel=_stacklevel)
429
+ self._output_differentiability = output_differentiability
430
+ if self._has_impl("save_for_backward"):
431
+ self._register_autograd_kernel()
432
+ return inner
433
+
434
+
435
+ @dataclasses.dataclass
436
+ class FuncAndLocation:
437
+ func: typing.Callable
438
+ location: str
439
+
440
+
441
+ def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName):
442
+ overload_name = (
443
+ "" if operator_name.overload_name is None else operator_name.overload_name
444
+ )
445
+ return _C._dispatch_find_schema_or_throw(
446
+ f"{cpp_ns}::{str(operator_name.name)}", overload_name
447
+ )
448
+
449
+
450
+ def validate_namespace(ns: str) -> None:
451
+ if "." in ns:
452
+ raise ValueError(
453
+ f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a '
454
+ f"valid variable name)"
455
+ )
456
+ if ns in RESERVED_NS:
457
+ raise ValueError(
458
+ f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, "
459
+ f"please choose something else. "
460
+ )
461
+
462
+ def validate_schema(schema: FunctionSchema) -> None:
463
+ if not torch._library.utils.is_functional_schema(schema):
464
+ raise ValueError(
465
+ f"custom_op only supports functional operators "
466
+ f"(ops that do not mutate any inputs, do not return "
467
+ f"views of the inputs, and has at least one return). "
468
+ f"Got the following non-functional schema: {schema}"
469
+ )
470
+
471
+ # For simplicity: don't allow self arguments
472
+ if schema.arguments.self_arg is not None:
473
+ raise ValueError(
474
+ f"custom_op does not support arguments named 'self'. Please "
475
+ f"rename your argument. Got: {schema}"
476
+ )
477
+
478
+
479
+ def parse_qualname(qualname: str) -> tuple[str, str]:
480
+ names = qualname.split("::", 1)
481
+ if len(names) != 2:
482
+ raise ValueError(f"Expected there to be a namespace in {qualname}, i.e. The "
483
+ f"operator name should look something like ns::foo")
484
+ if '.' in names[1]:
485
+ raise ValueError(f"The torch.custom_ops APIs do not handle overloads, "
486
+ f"i.e. operator names with '.' in them. "
487
+ f"Please name your operator something like ns::foo. "
488
+ f"Got: {qualname}")
489
+ return names[0], names[1]
490
+
491
+
492
+ def validate_device_type(device_type: str) -> None:
493
+ if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY:
494
+ raise ValueError(
495
+ f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type "
496
+ f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}."
497
+ )
498
+
499
+
500
+ def supported_param(param: inspect.Parameter) -> bool:
501
+ return param.kind in (
502
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
503
+ inspect.Parameter.KEYWORD_ONLY,
504
+ )
505
+
506
+
507
+ def validate_function_matches_schema(
508
+ schema: FunctionSchema, func: typing.Callable
509
+ ) -> None:
510
+ sig = inspect.signature(func)
511
+
512
+ if not all(supported_param(p) for _, p in sig.parameters.items()):
513
+ raise ValueError(
514
+ f"custom_op(..., manual_schema)(func): positional-only args, "
515
+ f"varargs, and kwargs are not supported. Please rewrite `func` "
516
+ f"to not have them. Got `func` with signature: {sig}"
517
+ )
518
+
519
+ if (
520
+ any(
521
+ p.annotation is not inspect.Parameter.empty
522
+ for _, p in sig.parameters.items()
523
+ )
524
+ or sig.return_annotation is not inspect.Signature.empty
525
+ ):
526
+ raise ValueError(
527
+ f"custom_op(..., manual_schema)(func): When passing in a manual "
528
+ f"schema, we expect `func` to have no type annotations to avoid "
529
+ f"ambiguity. Got `func` with signature: {sig}"
530
+ )
531
+
532
+ positional = [
533
+ (name, param)
534
+ for name, param in sig.parameters.items()
535
+ if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
536
+ ]
537
+ kwargonly = [
538
+ (name, param)
539
+ for name, param in sig.parameters.items()
540
+ if param.kind == inspect.Parameter.KEYWORD_ONLY
541
+ ]
542
+
543
+ def error():
544
+ raise ValueError(
545
+ f"custom_op(..., manual_schema)(func): When passing in a manual "
546
+ f"schema, we expect `func`'s signature to match `manual_schema` "
547
+ f"(aside from type annotations). "
548
+ f"func's signature: {sig}, manual_schema: {schema}"
549
+ )
550
+
551
+ def error_default_args():
552
+ raise ValueError(
553
+ f"custom_op(..., manual_schema)(func): "
554
+ f"neither func nor manual_schema should have default "
555
+ f"arguments. Got "
556
+ f"func's signature: {sig}, manual_schema: {schema}"
557
+ )
558
+
559
+ def compare(sig_args, schema_args):
560
+ if len(sig_args) != len(schema_args):
561
+ error()
562
+ for (name, param), arg in zip(sig_args, schema_args):
563
+ if name != arg.name:
564
+ error()
565
+ if param.default is not inspect.Parameter.empty or arg.default is not None:
566
+ error_default_args()
567
+
568
+ compare(positional, schema.arguments.flat_positional)
569
+ compare(kwargonly, schema.arguments.flat_kwarg_only)
570
+
571
+
572
+ def report_error_callback(custom_op: typing.Any, key: str) -> None:
573
+ if key == "Undefined":
574
+ raise NotImplementedError(
575
+ f"{custom_op}: There were no Tensor inputs to this operator "
576
+ f"(e.g. you passed an empty list of Tensors). If your operator is a "
577
+ f"factory function (that is, it takes no Tensors and constructs "
578
+ f"a new one), then please use CustomOp.impl_factory to register "
579
+ f"an implementation for it"
580
+ )
581
+ if key == "Meta":
582
+ raise NotImplementedError(
583
+ f"{custom_op}: when running with device='Meta' tensors: there is no "
584
+ f"abstract impl registered for this CustomOp. Please register one via "
585
+ f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors"
586
+ )
587
+ if key in ("CPU", "CUDA"):
588
+ device = key.lower()
589
+ raise NotImplementedError(
590
+ f"{custom_op}: when running with device='{device}' tensors: there is no "
591
+ f"{device} impl registered for this CustomOp. Please register one via "
592
+ f"CustomOp.impl(device_type='{device}')"
593
+ )
594
+ raise NotImplementedError(
595
+ f"{custom_op}: No implementation for dispatch key {key}. It is likely "
596
+ f"that we have not added this functionality yet, please either open an "
597
+ f"issue or if you're feeling adventurous, use the low-level "
598
+ f"torch.library API"
599
+ )
600
+
601
+
602
+ def custom_op_from_existing(op):
603
+ ns = op.namespace
604
+ lib = torch.library.Library(ns, "FRAGMENT")
605
+ name = op.name().split("::")[-1]
606
+ schema_str = str(op._schema)
607
+ # CustomOp expects the schema string without the namespace
608
+ schema_str = schema_str.split("::")[-1]
609
+ schema = FunctionSchema.parse(schema_str)
610
+ return CustomOp(lib, ns, schema, name, op, _private_access=True)
611
+
612
+
613
+ def get_op(qualname):
614
+ def error_not_found():
615
+ raise ValueError(
616
+ f"Could not find the operator {qualname}. Please make sure you have "
617
+ f"already registered the operator and (if registered from C++) "
618
+ f"loaded it via torch.ops.load_library.")
619
+
620
+ ns, name = parse_qualname(qualname)
621
+ if not hasattr(torch.ops, ns):
622
+ error_not_found()
623
+ opnamespace = getattr(torch.ops, ns)
624
+ if not hasattr(opnamespace, name):
625
+ error_not_found()
626
+ packet = getattr(opnamespace, name)
627
+ if not hasattr(packet, 'default'):
628
+ error_not_found()
629
+ return packet.default
630
+
631
+
632
+ def _find_custom_op(qualname, also_check_torch_library=False):
633
+ if qualname in global_registry:
634
+ return global_registry[qualname]
635
+ if not also_check_torch_library:
636
+ raise RuntimeError(
637
+ f'Could not find custom op "{qualname}". Did you register it via '
638
+ f"the torch._custom_ops API?")
639
+ overload = get_op(qualname)
640
+ result = custom_op_from_existing(overload)
641
+ return result
642
+
643
+
644
+ def get_abstract_impl(qualname):
645
+ if qualname not in torch._custom_op.impl.global_registry:
646
+ return None
647
+ custom_op = torch._custom_op.impl.global_registry[qualname]
648
+ if custom_op is None:
649
+ return None
650
+ if not custom_op._has_impl("abstract"):
651
+ return None
652
+ return custom_op._get_impl("abstract").func
653
+
654
+
655
+ def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True):
656
+ ns, name = qualname.split("::")
657
+ schema_str = f"{name}{schema}"
658
+ function_schema = FunctionSchema.parse(schema_str)
659
+ validate_schema(function_schema)
660
+ tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else []
661
+ lib = library.Library(ns, "FRAGMENT")
662
+ lib.define(schema_str, tags=tags)
663
+ ophandle = find_ophandle_or_throw(ns, function_schema.name)
664
+ result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True)
665
+ result._register_autograd_kernel_indirection()
666
+
667
+ torch._C._dispatch_set_report_error_callback(
668
+ ophandle, functools.partial(report_error_callback, weakref.proxy(result))
669
+ )
670
+ return get_op(qualname)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__init__.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ from collections import defaultdict
4
+ from collections.abc import Sequence
5
+ from functools import lru_cache, partial, wraps
6
+ from itertools import chain
7
+ from typing import Callable, Optional, TYPE_CHECKING, TypeVar, Union
8
+ from typing_extensions import ParamSpec
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from torch.export.decomp_utils import CustomDecompTable
13
+
14
+ import torch
15
+ import torch.library
16
+ from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket
17
+ from torch._prims_common import CustomOutParamAnnotation
18
+ from torch._subclasses.functional_tensor import FunctionalTensor
19
+ from torch.utils import _pytree as pytree
20
+
21
+
22
+ __all__ = [
23
+ "decomposition_table",
24
+ "pre_autograd_decomposition_table",
25
+ "meta_table",
26
+ "register_decomposition",
27
+ "get_decompositions",
28
+ "core_aten_decompositions",
29
+ "_should_decompose_because_unsafe_op",
30
+ ]
31
+
32
+ _T = TypeVar("_T")
33
+ _P = ParamSpec("_P")
34
+
35
+ # TODO: relax key type here; torch registrations should be possible to; but
36
+ # right now this type is accurate
37
+ global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = (
38
+ defaultdict(dict)
39
+ )
40
+
41
+ decomposition_table = global_decomposition_table["post_autograd"]
42
+ pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"]
43
+ meta_table = global_decomposition_table["meta"]
44
+
45
+
46
+ def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool:
47
+ """
48
+ Returns True if the op must always decompose in export/compile tracing system
49
+
50
+ In export, we always decompose certain CIA ops that are tagged with
51
+ maybe_aliasing_or_mutating because we statically need to know if the op is
52
+ mutating or not. But these CIA ops could have different behaviour in runtime.
53
+
54
+ native_batch_norm is a prim op which has a wrong schema and it needs to be replaced
55
+ with correct schema. But until then, we will force decompose it via this tag.
56
+ """
57
+ if not isinstance(op, torch._ops.OpOverload):
58
+ return False
59
+ if torch.Tag.maybe_aliasing_or_mutating in op.tags:
60
+ return True
61
+ return op == torch.ops.aten.native_batch_norm.default
62
+
63
+
64
+ def _add_op_to_registry(registry, op, fn):
65
+ """
66
+ This is an internal API for adding an op to the decomposition table.
67
+
68
+ If op is OpOverload, it will be added to the registry directly.
69
+ If op is OpOverloadPacket, all the valid op_overloads in the packet will be added to the registry.
70
+ """
71
+ overloads: list[Union[torch._ops.OperatorBase]] = []
72
+ if isinstance(op, HigherOrderOperator):
73
+ # There's no concept of overloads for HigherOrderOperator
74
+ registry[op] = fn
75
+ return
76
+ elif isinstance(op, OpOverload):
77
+ overloads.append(op)
78
+ else:
79
+ assert isinstance(op, OpOverloadPacket)
80
+ for ol in op.overloads():
81
+ overloads.append(getattr(op, ol))
82
+
83
+ for op_overload in overloads:
84
+ if op_overload in registry:
85
+ raise RuntimeError(f"duplicate registrations for {op_overload}")
86
+ # TorchScript dumps a bunch of extra nonsense overloads
87
+ # which don't have corresponding dispatcher entries, we need
88
+ # to filter those out, e.g aten.add.float_int
89
+ if torch._C._dispatch_has_kernel(op_overload.name()):
90
+ registry[op_overload] = fn
91
+
92
+
93
+ def _convert_out_params(f):
94
+ out_annotation = f.__annotations__.get("out")
95
+
96
+ # If there are no out params, do not wrap the function.
97
+ if not out_annotation:
98
+ return f
99
+
100
+ # Hack to detect when out is a Tuple. There seems to be no pretty way of doing this
101
+ if getattr(out_annotation, "__origin__", None) is tuple:
102
+ sig = inspect.signature(f)
103
+ out_names = sig.return_annotation._fields
104
+ # If out is a tuple, we need to register a function that unpacks all the out
105
+ # elements as this is what native_functions.yaml expects
106
+
107
+ @wraps(f)
108
+ def _fn(*args, **kwargs):
109
+ out_kwargs = tuple(kwargs.pop(o, None) for o in out_names)
110
+ # Either all of the out kwargs are set or none of them
111
+ is_none = out_kwargs[0] is None
112
+ assert all((o is None) == is_none for o in out_kwargs)
113
+ return f(*args, **kwargs, out=None if is_none else out_kwargs)
114
+
115
+ out_params = [
116
+ inspect.Parameter(
117
+ o,
118
+ kind=inspect.Parameter.KEYWORD_ONLY,
119
+ default=None,
120
+ annotation=t,
121
+ )
122
+ for o, t in zip(out_names, out_annotation.__args__)
123
+ ]
124
+ # Drop the out parameter and concatenate the new kwargs in the signature
125
+ params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params)
126
+ _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
127
+ parameters=params, # type: ignore[arg-type]
128
+ return_annotation=sig.return_annotation,
129
+ )
130
+ # Drop the out parameter and concatenate the new kwargs in the annotations
131
+ _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
132
+ for o in out_params:
133
+ _fn.__annotations__[o.name] = o.annotation
134
+
135
+ # Propagate that this function is wrapped by `out_wrapper`
136
+ _fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined]
137
+
138
+ return _fn
139
+
140
+ # Alternatively, there may be a single tensor out parameter with a name
141
+ # other than "out". This will need special treatment and is indicated by an
142
+ # annotation, which we will remove here so it is not exposed after wrapping.
143
+ custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None)
144
+ if custom_out_param_name:
145
+
146
+ @wraps(f)
147
+ def _fn(*args, **kwargs):
148
+ out_kwarg = kwargs.pop(custom_out_param_name, None)
149
+ return f(*args, **kwargs, out=out_kwarg)
150
+
151
+ out_param = inspect.Parameter(
152
+ custom_out_param_name,
153
+ kind=inspect.Parameter.KEYWORD_ONLY,
154
+ default=None,
155
+ annotation=out_annotation,
156
+ )
157
+
158
+ # Drop the out parameter and concatenate the new kwarg in the signature
159
+ sig = inspect.signature(f)
160
+ params = chain(
161
+ (v for k, v in sig.parameters.items() if k != "out"), (out_param,)
162
+ )
163
+ _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
164
+ parameters=params, # type: ignore[arg-type]
165
+ return_annotation=sig.return_annotation,
166
+ )
167
+
168
+ # Drop the out parameter and concatenate the new kwargs in the annotations
169
+ _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
170
+ _fn.__annotations__[out_param.name] = out_param.annotation
171
+
172
+ return _fn
173
+
174
+ return f
175
+
176
+
177
+ def register_decomposition(
178
+ aten_op, registry=None, *, type="post_autograd", unsafe=False
179
+ ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
180
+ """
181
+ A decorator to register a function as a decomposition to the Python
182
+ decomposition table. Use it like this::
183
+
184
+ @register_decomposition(torch.ops.aten.clamp_min)
185
+ def clamp_min(x):
186
+ return torch.clamp(self, min=min)
187
+
188
+ If you are writing a new decomposition, consider contributing it
189
+ directly to PyTorch in torch._decomp.decompositions.
190
+
191
+ This API is experimental; we are almost certainly going to extend
192
+ the API when we make decompositions eligible for use in transforms (e.g.,
193
+ autograd) and not just backend tracing, where we then need to know if a
194
+ decomposition can be used to simulate a transform.
195
+
196
+ By default, we also will register it to the Meta key of dispatcher,
197
+ and replace the c++ Meta implementation if there is already one.
198
+
199
+ unsafe kwarg is for reuse of this function for registering non-function
200
+ things
201
+ """
202
+
203
+ assert type in {"post_autograd", "pre_autograd", "meta"}
204
+
205
+ def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]:
206
+ orig_fn = fn
207
+ if not unsafe:
208
+ fn = _convert_out_params(fn)
209
+
210
+ nonlocal registry
211
+ if registry is None:
212
+ registry = global_decomposition_table[type]
213
+
214
+ def register(op):
215
+ _add_op_to_registry(registry, op, fn)
216
+
217
+ # To handle allowing multiple aten_ops at once
218
+ pytree.tree_map_(register, aten_op)
219
+ return orig_fn
220
+
221
+ return decomposition_decorator
222
+
223
+
224
+ def get_decompositions(
225
+ aten_ops: Sequence[Union[torch._ops.OperatorBase, OpOverloadPacket]],
226
+ type: str = "post_autograd",
227
+ ) -> dict[torch._ops.OperatorBase, Callable]:
228
+ """
229
+ Retrieve a dictionary of decompositions corresponding to the list of
230
+ operator overloads and overload packets passed as input. Overload
231
+ packets will include all decomposed overloads in the packet. If there is
232
+ no decomposition for a requested operator, it is silently ignored.
233
+
234
+ This API is experimental; we are almost certainly going to give an alternate,
235
+ more recommended formulation, where a user provides the set of operators
236
+ they know how to implement, and we provide decompositions for everything
237
+ not in this set.
238
+ """
239
+ assert type in {"post_autograd", "pre_autograd", "meta"}
240
+
241
+ registry = global_decomposition_table[type]
242
+ packets_to_overloads = defaultdict(list)
243
+ for opo in registry:
244
+ if isinstance(opo, (OpOverload, OpOverloadPacket)):
245
+ packets_to_overloads[opo.overloadpacket].append(opo)
246
+ decompositions: dict[torch._ops.OperatorBase, Callable] = {}
247
+ for op in aten_ops:
248
+ if isinstance(op, OpOverloadPacket) and op in packets_to_overloads:
249
+ for op_overload in packets_to_overloads[op]:
250
+ decompositions[op_overload] = registry[op_overload]
251
+ elif isinstance(op, (torch._ops.OperatorBase)) and op in registry:
252
+ decompositions[op] = registry[op]
253
+ return decompositions
254
+
255
+
256
+ def remove_decompositions(
257
+ decompositions: dict[torch._ops.OperatorBase, Callable],
258
+ aten_ops: Sequence[Union[OpOverload, OpOverloadPacket]],
259
+ ) -> None:
260
+ """
261
+ Given a dictionary of decompositions obtained from get_decompositions(), removes
262
+ operators associated with a list of operator overloads and overload packets passed
263
+ as input. If the decomposition dictionary does not contain a decomposition that is
264
+ specified to be removed, it is silently ignored.
265
+ """
266
+ for op in aten_ops:
267
+ if isinstance(op, OpOverloadPacket):
268
+ for overload_name in op.overloads():
269
+ opo = getattr(op, overload_name)
270
+ decompositions.pop(opo, None)
271
+ elif isinstance(op, OpOverload):
272
+ decompositions.pop(op, None)
273
+
274
+
275
+ # populate the table
276
+ import torch._decomp.decompositions
277
+ import torch._refs
278
+
279
+
280
+ def core_aten_decompositions() -> "CustomDecompTable":
281
+ from torch.export.exported_program import default_decompositions
282
+
283
+ return default_decompositions()
284
+
285
+
286
+ # See NOTE [Core ATen Ops]
287
+ #
288
+ # list was copied from torch/_inductor/decomposition.py
289
+ # excluding decompositions that results in prim ops
290
+ # Resulting opset of decomposition is core aten ops
291
+ def _core_aten_decompositions_post_autograd() -> dict[
292
+ torch._ops.OperatorBase, Callable
293
+ ]:
294
+ aten = torch.ops.aten
295
+ return get_decompositions(
296
+ [
297
+ aten.addcdiv,
298
+ aten.addcdiv_,
299
+ aten.addcmul,
300
+ aten.addcmul_,
301
+ aten.addr,
302
+ aten.affine_grid_generator,
303
+ aten.alias_copy,
304
+ aten.all,
305
+ aten.aminmax,
306
+ aten.arange.default,
307
+ aten.arange.start,
308
+ aten.avg_pool2d_backward,
309
+ aten.baddbmm,
310
+ aten.binary_cross_entropy,
311
+ aten.binary_cross_entropy_backward,
312
+ aten.binary_cross_entropy_with_logits,
313
+ aten.block_diag,
314
+ aten.bernoulli.p,
315
+ aten.bernoulli.default,
316
+ aten.celu,
317
+ aten.celu_,
318
+ aten.channel_shuffle,
319
+ aten.clamp_max,
320
+ aten.clamp_min,
321
+ aten.col2im,
322
+ aten.count_nonzero,
323
+ aten.linalg_cross,
324
+ aten.cudnn_batch_norm,
325
+ aten.cudnn_batch_norm_backward,
326
+ aten.miopen_batch_norm_backward,
327
+ aten.deg2rad,
328
+ aten.deg2rad_,
329
+ aten.detach,
330
+ aten.diag_embed,
331
+ aten.diagonal_backward,
332
+ aten.diagonal_copy,
333
+ aten.dot,
334
+ aten.vdot,
335
+ aten.elu,
336
+ aten.elu_,
337
+ aten.elu_backward,
338
+ aten._embedding_bag,
339
+ aten.embedding_dense_backward,
340
+ aten.empty_like,
341
+ aten._euclidean_dist.default,
342
+ aten.expand_as,
343
+ aten.expand_copy,
344
+ aten.eye,
345
+ aten.fill,
346
+ aten.fill_,
347
+ aten.floor_divide,
348
+ aten.frac,
349
+ aten.frac_,
350
+ aten._fused_moving_avg_obs_fq_helper,
351
+ aten.gelu_,
352
+ aten.gelu_backward,
353
+ aten.glu,
354
+ aten.glu_backward,
355
+ aten.hardshrink,
356
+ aten.hardsigmoid,
357
+ aten.hardsigmoid_,
358
+ aten.hardsigmoid_backward,
359
+ aten.hardswish,
360
+ aten.hardswish_,
361
+ aten.hardswish_backward,
362
+ aten.hardtanh_,
363
+ aten.hardtanh_backward,
364
+ aten.heaviside,
365
+ aten.heaviside_,
366
+ aten.huber_loss,
367
+ aten.huber_loss_backward,
368
+ aten.im2col,
369
+ aten.index_add.out,
370
+ aten.index_add.default,
371
+ aten.index_add_,
372
+ aten.index_copy.out,
373
+ aten.index_copy.default,
374
+ aten.index_copy_,
375
+ aten.index_fill.int_Scalar,
376
+ aten.index_fill.int_Tensor,
377
+ aten.index_fill.int_Scalar_out,
378
+ aten.index_fill.int_Tensor_out,
379
+ aten.index_fill_,
380
+ aten.isin,
381
+ aten.isneginf,
382
+ aten.isposinf,
383
+ aten.l1_loss,
384
+ aten._lazy_clone,
385
+ aten._test_parallel_materialize,
386
+ aten.leaky_relu_,
387
+ aten.leaky_relu_backward,
388
+ aten.lerp,
389
+ aten.lerp_,
390
+ aten.linspace,
391
+ aten.logaddexp,
392
+ aten.logaddexp2,
393
+ aten.logit,
394
+ aten.logit_,
395
+ aten.logit_backward,
396
+ aten.log_sigmoid_backward,
397
+ aten.log_sigmoid_forward,
398
+ aten._log_softmax_backward_data,
399
+ aten.logspace,
400
+ aten.logsumexp.default,
401
+ aten.masked_fill,
402
+ aten.masked_fill_,
403
+ aten.max_unpool2d,
404
+ aten.max_unpool3d,
405
+ aten.mish,
406
+ aten.mish_,
407
+ aten.mse_loss,
408
+ aten.mse_loss_backward,
409
+ aten.multi_margin_loss,
410
+ aten.multilabel_margin_loss_forward,
411
+ aten.mv,
412
+ aten.mvlgamma,
413
+ aten.mvlgamma_,
414
+ aten.nansum,
415
+ aten.nan_to_num,
416
+ aten.nan_to_num_,
417
+ aten.narrow,
418
+ aten.native_batch_norm_backward,
419
+ aten.native_dropout_backward,
420
+ aten.native_group_norm_backward,
421
+ aten.native_layer_norm_backward,
422
+ aten.new_empty,
423
+ aten.new_full,
424
+ aten.new_ones,
425
+ aten.new_zeros,
426
+ aten.nll_loss2d_forward,
427
+ aten.nll_loss2d_backward,
428
+ aten.nll_loss_backward,
429
+ aten.nll_loss_forward,
430
+ aten.norm.ScalarOpt_dtype,
431
+ aten.norm.Scalar,
432
+ aten.norm.ScalarOpt_dim_dtype,
433
+ aten.norm.ScalarOpt_dim,
434
+ aten.norm.dtype_out,
435
+ aten.norm.out,
436
+ aten.norm.names_dtype_out,
437
+ aten.norm.names_out,
438
+ aten.norm.ScalarOpt_dtype_out,
439
+ aten.norm.Scalar_out,
440
+ aten.ones,
441
+ aten.ones_like,
442
+ aten.pixel_shuffle,
443
+ aten.pixel_unshuffle,
444
+ aten._prelu_kernel,
445
+ aten._prelu_kernel_backward,
446
+ aten._reshape_alias,
447
+ aten.rad2deg,
448
+ aten.rad2deg_,
449
+ aten.reflection_pad1d,
450
+ aten.reflection_pad1d_backward,
451
+ aten.reflection_pad2d,
452
+ aten.reflection_pad2d_backward,
453
+ aten.reflection_pad3d,
454
+ aten.reflection_pad3d_backward,
455
+ aten.replication_pad1d,
456
+ aten.replication_pad2d,
457
+ aten.replication_pad3d,
458
+ aten.renorm,
459
+ aten.renorm_,
460
+ aten.replication_pad2d,
461
+ aten.resize_as,
462
+ aten.roll,
463
+ aten.rot90,
464
+ aten.rrelu_with_noise,
465
+ aten.rrelu_with_noise_,
466
+ aten.rsub,
467
+ aten._safe_softmax,
468
+ aten._scaled_dot_product_flash_attention_for_cpu.default,
469
+ aten.select_backward,
470
+ aten.select_scatter,
471
+ aten.sgn,
472
+ aten.sgn_,
473
+ aten.sigmoid_backward,
474
+ aten.silu,
475
+ aten.silu_,
476
+ aten.silu_backward.grad_input,
477
+ aten.sinc,
478
+ aten.sinc_,
479
+ aten.slice_backward,
480
+ aten.smooth_l1_loss,
481
+ aten.smooth_l1_loss_backward,
482
+ aten.soft_margin_loss,
483
+ aten.soft_margin_loss_backward,
484
+ aten._softmax_backward_data,
485
+ aten.softplus,
486
+ aten.softplus_backward,
487
+ aten.softshrink,
488
+ aten.special_entr,
489
+ aten.special_log_ndtr,
490
+ aten.special_xlog1py,
491
+ aten.split.Tensor,
492
+ aten.split_with_sizes_copy,
493
+ aten.squeeze_copy,
494
+ aten.squeeze.default,
495
+ aten.squeeze.dim,
496
+ aten.std.correction,
497
+ aten.std.out,
498
+ aten.std.correction_out,
499
+ aten.std.names_out,
500
+ aten.std.correction_names_out,
501
+ aten.std_mean.correction,
502
+ aten.std_mean.correction_out,
503
+ aten.stack,
504
+ aten.sum.default,
505
+ aten.sum.out,
506
+ aten.t,
507
+ aten.t_copy,
508
+ aten.take,
509
+ aten.tanh_backward,
510
+ aten.threshold,
511
+ aten.threshold_,
512
+ aten.threshold_backward,
513
+ aten.trace,
514
+ aten.transpose.int,
515
+ aten.transpose_copy,
516
+ aten.tril,
517
+ aten.tril_,
518
+ aten.triu,
519
+ aten.triu_,
520
+ aten.unbind,
521
+ aten.unfold_backward,
522
+ aten.unfold_copy,
523
+ aten._unsafe_index,
524
+ aten._unsafe_index_put,
525
+ aten._unsafe_masked_index,
526
+ aten._unsafe_masked_index_put_accumulate,
527
+ aten.unsafe_split.Tensor,
528
+ aten.unsafe_split_with_sizes,
529
+ aten.unsqueeze_copy,
530
+ aten._unsafe_view,
531
+ aten.upsample_linear1d,
532
+ aten.upsample_bilinear2d.out,
533
+ aten.upsample_trilinear3d.out,
534
+ aten.upsample_nearest2d_backward,
535
+ aten.view_as_complex,
536
+ aten.xlogy,
537
+ aten.xlogy_,
538
+ aten.zero,
539
+ aten.zero_,
540
+ aten.zeros,
541
+ aten.zeros_like,
542
+ aten._chunk_cat,
543
+ aten._weight_norm_interface,
544
+ ]
545
+ )
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-310.pyc ADDED
Binary file (8.07 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import inspect
4
+ from typing import Callable, Optional
5
+
6
+ import torch
7
+ import torch._decomp
8
+ from torch import Tensor
9
+ from torch._prims_common.wrappers import _maybe_remove_out_wrapper
10
+
11
+
12
+ decomposition_table = torch._decomp.decomposition_table
13
+ decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {}
14
+ register_decomposition = torch._decomp.register_decomposition
15
+ aten = torch.ops.aten
16
+
17
+ # NOTE: [forward-mode AD decompositions mechanism]
18
+ #
19
+ # The mechanism is in VariableType,
20
+ # IF any inputs have forward grad
21
+ # AND there is no forward AD formula implemented
22
+ # AND the functions are actually differentiable
23
+ # run the decomposition
24
+ # See run_jit_decomposition_with_args_for_jvp
25
+ # We currently use python decompositions that we torchscript.
26
+ #
27
+ # Note that we would be building the backward graph at the decomposed level
28
+ # too, but that is OK, because we would've errored out otherwise anyway.
29
+ #
30
+ # TODO: The mechanism we are using to register decompositions doesn't
31
+ # seem to be exclusively used for jvp. So open question here is whether
32
+ # torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things.
33
+ # If that is the case, we may go down the decomposition path unexpectedly
34
+ # (and possibly produce an unintelligible error) vs erroring out earlier and
35
+ # printing that the forward AD formula is not implemented.
36
+ #
37
+ # The solution to this may be to have an explicitly white list control when
38
+ # to enable the decomposition.
39
+
40
+
41
+ def maybe_register_decomposition(op):
42
+ def decorator(f):
43
+ try:
44
+ return register_decomposition(op)(f)
45
+ except Exception:
46
+ return f
47
+
48
+ return decorator
49
+
50
+
51
+ # Functions where we need a special decomposition for jvp but there's another version that
52
+ # should be used more generally (ex. for jvp we need to recompute the mean and variance for
53
+ # the backwards of a normalization function. Without jvp, it should use the saved value)
54
+ decomposition_table_for_jvp = {}
55
+
56
+
57
+ def register_decomposition_for_jvp(fn):
58
+ return register_decomposition(fn, registry=decomposition_table_for_jvp)
59
+
60
+
61
+ def _register_jit_decomposition_for_jvp(decomp, use_python=False):
62
+ if decomp in decomposition_table_for_jvp:
63
+ decomposition_table_used = decomposition_table_for_jvp
64
+ elif decomp in decomposition_table:
65
+ decomposition_table_used = decomposition_table
66
+ else:
67
+ raise RuntimeError(f"could not find decomposition for {decomp}")
68
+ decomp_fn = decomposition_table_used[decomp]
69
+
70
+ # `out_wrapper` extends a decompositions signature with
71
+ # an `out` parameter. However jit will use the unwrapped function's
72
+ # signature instead so we need to unwrap here to prevent an error
73
+ decomp_fn = _maybe_remove_out_wrapper(decomp_fn)
74
+
75
+ if use_python:
76
+ decomp_fn = torch.jit.ignore(decomp_fn)
77
+ sig = inspect.signature(decomp_fn)
78
+
79
+ # Create a string wrapping the function from the signature
80
+ # example output:
81
+ # def wrapped_decomp(x: torch.Tensor, y: int, z: int):
82
+ # return decomp_fn(x, y, z)
83
+ # Thanks copilot!
84
+ def get_function_def(sig):
85
+ param_def = [f"{param_str}" for param_str in sig.parameters.values()]
86
+ param_use = [f"{param_str}" for param_str in sig.parameters.keys()]
87
+
88
+ return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n"
89
+
90
+ f_str = get_function_def(sig)
91
+ graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph
92
+ else:
93
+ graph = torch.jit.script(decomp_fn).graph
94
+ torch.jit._register_decomposition(decomp, graph)
95
+
96
+
97
+ # The only decompositions here are temporary or hacks for the purposes of jvp
98
+
99
+
100
+ # TODO: do these also belong here?
101
+ @maybe_register_decomposition(aten.trace.default)
102
+ def trace(self: Tensor) -> Tensor:
103
+ return torch.sum(torch.diag(self))
104
+
105
+
106
+ @maybe_register_decomposition(aten.log_sigmoid_forward.default)
107
+ def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]:
108
+ min = torch.minimum(self.new_zeros(()), self)
109
+ z = torch.exp(-torch.abs(self))
110
+ if self.is_cuda or self.is_xpu:
111
+ buffer = self.new_zeros((0,))
112
+ else:
113
+ buffer = z
114
+ return min - torch.log1p(z), buffer
115
+
116
+
117
+ def recompute_mean_var(
118
+ input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool
119
+ ):
120
+ # for most norm decompositions, it will be the same as the core version except for here.
121
+ # We recompute the mean and variance so that they track gradients through input
122
+
123
+ mean = torch.mean(input, dim=inner_dim_indices, keepdim=keepdim)
124
+ var = torch.var(input, dim=inner_dim_indices, unbiased=False, keepdim=keepdim)
125
+ eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside
126
+ eps = eps.detach()
127
+ rstd = 1 / torch.sqrt(var + eps)
128
+ return mean, rstd
129
+
130
+
131
+ @register_decomposition_for_jvp(aten.native_layer_norm_backward)
132
+ def native_layer_norm_backward(
133
+ grad_out: Tensor,
134
+ input: Tensor,
135
+ normalized_shape: list[int],
136
+ mean: Tensor,
137
+ rstd: Tensor,
138
+ weight: Optional[Tensor],
139
+ bias: Optional[Tensor],
140
+ output_mask: list[bool],
141
+ ) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
142
+ input_shape = input.shape
143
+ input_ndim = input.dim()
144
+
145
+ axis = input_ndim - len(normalized_shape)
146
+ inner_dims = input_shape[axis:]
147
+ outer_dims = input_shape[:axis]
148
+ inner_dim_indices = list(range(axis, input_ndim))
149
+ outer_dim_indices = list(range(0, axis))
150
+
151
+ N = 1
152
+ for i in inner_dims:
153
+ N *= i
154
+ M = 1
155
+ for i in outer_dims:
156
+ M *= i
157
+ if M <= 0 or N <= 0:
158
+ return (
159
+ input.new_zeros(input_shape),
160
+ input.new_zeros(input_shape[axis:]),
161
+ input.new_zeros(input_shape[axis:]),
162
+ )
163
+
164
+ mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True)
165
+
166
+ x_hat = (input - mean_) * rstd_
167
+ if weight is not None:
168
+ grad_x_hat = grad_out * weight
169
+ else:
170
+ grad_x_hat = grad_out
171
+ a = grad_x_hat * N
172
+ b = torch.sum(grad_x_hat, inner_dim_indices, True)
173
+ c1 = torch.mul(grad_x_hat, x_hat)
174
+ c2 = torch.sum(c1, inner_dim_indices, True)
175
+ c3 = torch.mul(x_hat, c2)
176
+ inner = a - b - c3
177
+
178
+ if output_mask[0]:
179
+ d_input: Optional[Tensor] = (rstd_ / N) * inner
180
+ else:
181
+ d_input = torch.zeros_like(input) # should be None but doesn't work with vjp
182
+
183
+ if output_mask[1] and weight is not None:
184
+ if len(outer_dim_indices) > 0:
185
+ d_weight: Optional[Tensor] = torch.sum(
186
+ grad_out * x_hat, outer_dim_indices, False
187
+ )
188
+ else:
189
+ d_weight = grad_out * x_hat
190
+ elif weight is not None:
191
+ d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp
192
+ else:
193
+ d_weight = torch.zeros(()) # should be None but doesn't work with vjp
194
+
195
+ if output_mask[2] and bias is not None:
196
+ if len(outer_dim_indices) > 0:
197
+ d_bias: Optional[Tensor] = torch.sum(grad_out, outer_dim_indices, False)
198
+ else:
199
+ d_bias = grad_out.clone()
200
+ elif bias is not None:
201
+ d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp
202
+ else:
203
+ d_bias = torch.zeros(()) # should be None but doesn't work with vjp
204
+
205
+ return (d_input, d_weight, d_bias)
206
+
207
+
208
+ def prod(x: list[int]):
209
+ r = 1
210
+ for i in x:
211
+ r *= i
212
+ return r
213
+
214
+
215
+ @register_decomposition_for_jvp(aten.native_batch_norm_backward)
216
+ def native_batch_norm_backward(
217
+ grad_out: Tensor,
218
+ input: Tensor,
219
+ weight: Optional[Tensor],
220
+ running_mean: Optional[Tensor],
221
+ running_var: Optional[Tensor],
222
+ save_mean: Optional[Tensor],
223
+ save_invstd: Optional[Tensor],
224
+ train: bool,
225
+ eps: float,
226
+ output_mask: list[bool],
227
+ ) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
228
+ input_shape = input.shape
229
+ input_rank = input.dim()
230
+ assert input_rank >= 2, "rank of the input must be at least 2"
231
+
232
+ axis = 1
233
+ num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type]
234
+ mean = save_mean
235
+ invstd = save_invstd
236
+ if train:
237
+ assert save_mean is not None and save_invstd is not None, (
238
+ "when train=True, save_mean and save_invstd are required"
239
+ )
240
+
241
+ reduciton_dims = [0] + list(range(2, input.dim()))
242
+ assert invstd is not None # for typing
243
+ mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False)
244
+ else:
245
+ assert running_mean is not None and running_var is not None
246
+ mean = running_mean
247
+ invstd = torch.rsqrt(running_var + eps)
248
+
249
+ assert invstd is not None and mean is not None
250
+
251
+ broadcast_mask = [1] * input_rank
252
+ broadcast_mask[axis] = input_shape[axis]
253
+
254
+ reduction_axes: list[int] = []
255
+ for i in range(input_rank):
256
+ if i != axis:
257
+ reduction_axes.append(i)
258
+
259
+ mean = torch.reshape(mean, broadcast_mask)
260
+ norm = 1.0 / num_features
261
+ grad_output_sum = torch.sum(grad_out, reduction_axes)
262
+ dot_p = torch.sum(grad_out * (input - mean), reduction_axes)
263
+
264
+ grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask)
265
+ proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask)
266
+
267
+ if weight is None:
268
+ grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0
269
+ else:
270
+ grad_scale = torch.reshape(invstd * weight, broadcast_mask)
271
+
272
+ if train:
273
+ proj = (input - mean) * proj_scale
274
+ grad_input = ((grad_out - proj) - grad_mean) * grad_scale
275
+ else:
276
+ grad_input = grad_out * grad_scale
277
+
278
+ if output_mask[1]:
279
+ grad_weight = dot_p * invstd
280
+ elif weight is not None:
281
+ grad_weight = torch.zeros_like(
282
+ weight
283
+ ) # should be None but doesn't work with vjp
284
+ else:
285
+ grad_weight = torch.zeros(()) # should be None but doesn't work with vjp
286
+
287
+ if output_mask[2]:
288
+ grad_bias = grad_output_sum
289
+ else:
290
+ grad_bias = torch.zeros_like(
291
+ grad_output_sum
292
+ ) # should be None but doesn't work with vjp
293
+
294
+ return (grad_input, grad_weight, grad_bias)
295
+
296
+
297
+ @register_decomposition_for_jvp(aten.batch_norm_backward)
298
+ def batch_norm_backward(
299
+ grad_out: Tensor,
300
+ input: Tensor,
301
+ weight: Tensor,
302
+ running_mean: Optional[Tensor],
303
+ running_var: Optional[Tensor],
304
+ save_mean: Optional[Tensor],
305
+ save_var: Optional[Tensor],
306
+ update: bool,
307
+ eps: float,
308
+ output_mask: list[bool],
309
+ reserve: Tensor,
310
+ ) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
311
+ return native_batch_norm_backward(
312
+ grad_out,
313
+ input,
314
+ weight,
315
+ running_mean,
316
+ running_var,
317
+ save_mean,
318
+ save_var,
319
+ update,
320
+ eps,
321
+ output_mask,
322
+ )
323
+
324
+
325
+ _register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True)
326
+ _register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default)
327
+ _register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default)
328
+ _register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default)
329
+ _register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default)
330
+ _register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default)
331
+ _register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default)
332
+ _register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default)
333
+ _register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default)
334
+ _register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default)
335
+ _register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import functools
4
+ from collections import defaultdict
5
+ from typing import Callable
6
+
7
+ import torch
8
+ import torch._decomp as decomp
9
+ from torch._decomp import get_decompositions
10
+ from torch._ops import OpOverload
11
+
12
+
13
+ aten = torch.ops.aten
14
+
15
+ rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict)
16
+
17
+
18
+ def register_rng_decomposition(aten_op):
19
+ return decomp.register_decomposition(aten_op, rng_decompositions)
20
+
21
+
22
+ def throw_on_non_cuda(device):
23
+ raise RuntimeError(
24
+ f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not "
25
+ f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is "
26
+ "not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU."
27
+ )
28
+
29
+
30
+ # TODO - We have to register many more distributions here, and also higher level
31
+ # ops like dropout which have fused implementation and can hide the rand inside.
32
+ @register_rng_decomposition(aten.rand)
33
+ def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False):
34
+ if device and device.type != "cuda":
35
+ throw_on_non_cuda(device)
36
+ seed, offset = PhiloxStateTracker.get_state_as_tuple()
37
+ dtype = dtype or torch.float32
38
+ out, offset_jump = torch.ops.rngprims.philox_rand(
39
+ shape, seed, offset, None, device, dtype
40
+ )
41
+ PhiloxStateTracker.advance_offset(offset_jump)
42
+ return out
43
+
44
+
45
+ @register_rng_decomposition(aten.rand_like)
46
+ def rand_like(
47
+ x: torch.Tensor,
48
+ dtype=None,
49
+ layout=None,
50
+ device=None,
51
+ pin_memory=False,
52
+ memory_format=torch.preserve_format,
53
+ ):
54
+ device = device or x.device
55
+ if device.type != "cuda":
56
+ throw_on_non_cuda(device)
57
+ dtype = dtype or x.dtype
58
+ seed, offset = PhiloxStateTracker.get_state_as_tuple()
59
+ out, offset_jump = torch.ops.rngprims.philox_rand(
60
+ x.shape, seed, offset, None, device, dtype
61
+ )
62
+ PhiloxStateTracker.advance_offset(offset_jump)
63
+ return out
64
+
65
+
66
+ class PhiloxState:
67
+ """
68
+ Represents a PhiloxRngState - (seed, offset) where offset = base_offset +
69
+ relative_offset. seed and base_offset basically point to the rng state just
70
+ before tracing starts. relative offset tracks the totally consumed offset at
71
+ trace time.
72
+ """
73
+
74
+ def __init__(self) -> None:
75
+ self.reset()
76
+
77
+ def reset(self):
78
+ self.seed = torch.tensor(())
79
+ self.base_offset = torch.tensor(())
80
+ self.relative_offset = 0
81
+ self.offset_advanced_alteast_once = False
82
+
83
+ def validate_state(self):
84
+ assert self.seed.numel() != 0 and self.base_offset.numel() != 0
85
+
86
+ def advance_offset(self, consumed_offset):
87
+ self.offset_advanced_alteast_once = True
88
+ self.relative_offset = self.relative_offset + consumed_offset
89
+
90
+ def set_state(self, seed, base_offset, relative_offset=0):
91
+ self.seed = seed
92
+ self.base_offset = base_offset
93
+ self.relative_offset = relative_offset
94
+
95
+ def get_state_as_tuple(self):
96
+ self.validate_state()
97
+ return (self.seed, self.base_offset + self.relative_offset)
98
+
99
+ def get_state_as_tensor(self):
100
+ # Only needed because we override get_rng_state.
101
+ self.validate_state()
102
+ return torch.stack([self.seed, self.base_offset + self.relative_offset])
103
+
104
+ def set_state_from_tensor(self, state):
105
+ # Only needed because we override set_rng_state.
106
+ self.seed, self.base_offset = torch.unbind(state)
107
+ self.relative_offset = 0
108
+
109
+
110
+ class PhiloxStateTracker:
111
+ """
112
+ Singleton class to track the philox rng state during AOT Autograd tracing.
113
+ For each aot tracing instance, AOT Autograd resets this tracker and keeps
114
+ track of both forward and backward offsets. At runtime, we only care about
115
+ the total consumed forward and backward offsets. For dynamic shapes, these
116
+ offsets are a function of input shapes. Therefore, the AOT generated graphs
117
+ have additional outputs that compute total consumed forward and backward
118
+ offsets.
119
+ """
120
+
121
+ running_state: PhiloxState
122
+ fwd_state: PhiloxState
123
+ bwd_state: PhiloxState
124
+
125
+ def __enter__(self):
126
+ PhiloxStateTracker.reset()
127
+ return self
128
+
129
+ def __exit__(self, exc_type, exc_cal, exc_tb):
130
+ PhiloxStateTracker.reset()
131
+
132
+ @classmethod
133
+ def reset(cls):
134
+ cls.running_state = PhiloxState()
135
+ cls.fwd_state = PhiloxState()
136
+ cls.bwd_state = PhiloxState()
137
+
138
+ @classmethod
139
+ def mark_beginning_of_forward(cls):
140
+ # Tells the tracker to use fwd_state as the running state
141
+ cls.running_state = cls.fwd_state
142
+
143
+ @classmethod
144
+ def mark_beginning_of_backward(cls):
145
+ # Tells the tracker to use bwd_state as the running state
146
+ cls.running_state = cls.bwd_state
147
+
148
+ @classmethod
149
+ def record_state(cls, seed, offset, mode):
150
+ # Records the seed and offset tensors. These tensors are used to invoke
151
+ # the philox_rand functional primitives.
152
+ if mode == "forward":
153
+ cls.fwd_state.set_state(seed, offset)
154
+ cls.mark_beginning_of_forward()
155
+ else:
156
+ assert mode == "backward"
157
+ cls.bwd_state.set_state(seed, offset)
158
+
159
+ @classmethod
160
+ def get_state_as_tensor(cls):
161
+ # The only reason this exists is because we override get_rng_state and
162
+ # set_rng_state during tracing. get_rng_state expects a tensor output,
163
+ # so return (seed, offset) tuple upset other parts of the program like
164
+ # ctx.saved_tensors.
165
+
166
+ # A bad consequence is that if user saves and restores rng state, we
167
+ # have little bit of ugliness in the generated code, where we first
168
+ # concat the (seed, offset) to create a tensor for get_rng_state, and
169
+ # then split it back to get (seed, offset) tuple in set_rng_state.
170
+
171
+ # TODO: Investigate if there is be a better way to wrap the tuple in a
172
+ # false Tensor object, and then desugar it later on.
173
+ return cls.running_state.get_state_as_tensor()
174
+
175
+ @classmethod
176
+ def get_state_as_tuple(cls):
177
+ return cls.running_state.get_state_as_tuple()
178
+
179
+ @classmethod
180
+ def set_state_from_tensor(cls, x):
181
+ # This is only needed because we override set_rng_state. Look at the
182
+ # comment in get_state_from_tensor method.
183
+ cls.running_state.set_state_from_tensor(x)
184
+
185
+ @classmethod
186
+ def advance_offset(cls, consumed_offset):
187
+ cls.running_state.advance_offset(consumed_offset)
188
+
189
+ @classmethod
190
+ def get_current_relative_offset(cls):
191
+ return cls.running_state.relative_offset
192
+
193
+ @staticmethod
194
+ def multiple_of_4(offset):
195
+ # torch cuda rng state offset must be a multiple of 4. For inductor, as
196
+ # we sum up all the numel, the result might not be a multiple of 4. This
197
+ # method achieves that.
198
+ return (offset + 3) // 4 * 4
199
+
200
+ @classmethod
201
+ def get_updated_fwd_offset(cls):
202
+ # Short circuit if no rand ops were observed
203
+ if not cls.fwd_state.offset_advanced_alteast_once:
204
+ return cls.fwd_state.base_offset
205
+ return cls.multiple_of_4(
206
+ cls.fwd_state.base_offset + cls.fwd_state.relative_offset
207
+ )
208
+
209
+ @classmethod
210
+ def get_updated_bwd_offset(cls):
211
+ # Short circuit if no rand ops were observed
212
+ if not cls.bwd_state.offset_advanced_alteast_once:
213
+ return cls.bwd_state.base_offset
214
+ return cls.multiple_of_4(
215
+ cls.bwd_state.base_offset + cls.bwd_state.relative_offset
216
+ )
217
+
218
+
219
+ # Adding more decompositions which eventually use rand_like inside decomps.
220
+ # Adding these in rng_decompositions ensures the functionalization of rand_like
221
+ # ops used in these decomps. The list is copied from inductor codebase, which
222
+ # uses it for similar purpose.
223
+ #
224
+ # Caution - These decomps do not have same accuracy as that of eager. However,
225
+ # we can't just disable them with a config flag like fallback_random, because
226
+ # for functionalization of rng ops, we have to decompose these ops.
227
+ extra_random_decomps = get_decompositions(
228
+ [
229
+ aten.cauchy,
230
+ aten.cauchy_,
231
+ aten.exponential,
232
+ aten.exponential_,
233
+ aten.geometric,
234
+ aten.geometric_,
235
+ aten.native_dropout,
236
+ aten.normal,
237
+ aten.normal_,
238
+ aten.normal_functional,
239
+ aten.log_normal,
240
+ aten.log_normal_,
241
+ aten.rrelu_with_noise,
242
+ aten.rrelu_with_noise_,
243
+ aten.uniform_,
244
+ ]
245
+ )
246
+ register_extra_random_decomp = functools.partial(
247
+ decomp.register_decomposition, registry=extra_random_decomps
248
+ )
249
+
250
+
251
+ @register_extra_random_decomp([aten.bernoulli_])
252
+ def bernoulli_(self, p=0.5):
253
+ if self.device == torch.device("cpu"):
254
+ return NotImplemented
255
+ return self.copy_(torch.rand_like(self, dtype=torch.float32) < p)
256
+
257
+
258
+ @register_extra_random_decomp([aten.bernoulli.p])
259
+ def bernoulli_p(self, p=0.5, *, generator=None):
260
+ if self.device == torch.device("cpu"):
261
+ return NotImplemented
262
+ assert generator is None
263
+ return torch.rand_like(self, dtype=torch.float32) < p
264
+
265
+
266
+ rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type]
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._higher_order_ops._invoke_quant import (
2
+ invoke_quant,
3
+ invoke_quant_packed,
4
+ InvokeQuant,
5
+ )
6
+ from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate
7
+ from torch._higher_order_ops.associative_scan import associative_scan
8
+ from torch._higher_order_ops.auto_functionalize import (
9
+ auto_functionalized,
10
+ auto_functionalized_v2,
11
+ )
12
+ from torch._higher_order_ops.base_hop import BaseHOP
13
+ from torch._higher_order_ops.cond import cond
14
+ from torch._higher_order_ops.effects import with_effects
15
+ from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate
16
+ from torch._higher_order_ops.flat_apply import flat_apply
17
+ from torch._higher_order_ops.flex_attention import (
18
+ flex_attention,
19
+ flex_attention_backward,
20
+ )
21
+ from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map
22
+ from torch._higher_order_ops.hints_wrap import hints_wrapper
23
+ from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
24
+ from torch._higher_order_ops.out_dtype import out_dtype
25
+ from torch._higher_order_ops.run_const_graph import run_const_graph
26
+ from torch._higher_order_ops.scan import scan
27
+ from torch._higher_order_ops.strict_mode import strict_mode
28
+ from torch._higher_order_ops.torchbind import call_torchbind
29
+ from torch._higher_order_ops.while_loop import while_loop
30
+ from torch._higher_order_ops.wrap import (
31
+ tag_activation_checkpoint,
32
+ wrap_activation_checkpoint,
33
+ wrap_with_autocast,
34
+ wrap_with_set_grad_enabled,
35
+ )
36
+
37
+
38
+ __all__ = [
39
+ "cond",
40
+ "while_loop",
41
+ "invoke_subgraph",
42
+ "scan",
43
+ "flex_attention",
44
+ "flex_attention_backward",
45
+ "hints_wrapper",
46
+ "BaseHOP",
47
+ "flat_apply",
48
+ "foreach_map",
49
+ "_foreach_map",
50
+ "with_effects",
51
+ "tag_activation_checkpoint",
52
+ "auto_functionalized",
53
+ "auto_functionalized_v2",
54
+ "associative_scan",
55
+ "out_dtype",
56
+ "executorch_call_delegate",
57
+ "call_torchbind",
58
+ "run_const_graph",
59
+ "InvokeQuant",
60
+ "invoke_quant",
61
+ "invoke_quant_packed",
62
+ "wrap_with_set_grad_enabled",
63
+ "wrap_with_autocast",
64
+ "wrap_activation_checkpoint",
65
+ "strict_mode",
66
+ "aoti_call_delegate",
67
+ ]
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-310.pyc ADDED
Binary file (2.63 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-310.pyc ADDED
Binary file (4.12 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-310.pyc ADDED
Binary file (20.6 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-310.pyc ADDED
Binary file (6.61 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-310.pyc ADDED
Binary file (19.6 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-310.pyc ADDED
Binary file (7.94 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-310.pyc ADDED
Binary file (5.8 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-310.pyc ADDED
Binary file (4.45 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-310.pyc ADDED
Binary file (26.2 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-310.pyc ADDED
Binary file (9.15 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-310.pyc ADDED
Binary file (9.09 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-310.pyc ADDED
Binary file (5.58 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-310.pyc ADDED
Binary file (4.09 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-310.pyc ADDED
Binary file (41 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-310.pyc ADDED
Binary file (19.6 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-310.pyc ADDED
Binary file (8.77 kB). View file
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/_invoke_quant.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # need to fix prim_hop_base type annotations first
3
+
4
+ import dataclasses
5
+ from typing import Optional
6
+
7
+ import torch
8
+ from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
9
+
10
+
11
+ class InvokeQuantTracer(BaseHOP):
12
+ def __init__(self) -> None:
13
+ super().__init__("invoke_quant_packed")
14
+
15
+ def __call__(self, subgraph, *operands, scheme=None, quant_options=None):
16
+ subgraph = FunctionWithNoFreeVars(subgraph)
17
+ return super().__call__(
18
+ subgraph, *operands, scheme=scheme, quant_options=quant_options
19
+ )
20
+
21
+
22
+ invoke_quant_packed = InvokeQuantTracer()
23
+
24
+
25
+ class InvokeQuantUnpacked(BaseHOP):
26
+ def __init__(self) -> None:
27
+ super().__init__("invoke_quant")
28
+
29
+ def __call__(self, subgraph, *operands, scheme=None):
30
+ return super().__call__(subgraph, *operands, scheme=scheme)
31
+
32
+
33
+ invoke_quant = InvokeQuantUnpacked()
34
+
35
+
36
+ @dataclasses.dataclass(frozen=True, repr=True)
37
+ class InvokeQuant:
38
+ """
39
+ Invoke a quantization function that will be preserved as a single operator. Preservation
40
+ as a single operator aids in pattern matching and custom lowerings.
41
+
42
+ The operation appears as:
43
+ torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme)
44
+
45
+ Args:
46
+ codegen_low_precision: Use observed subgraph dtypes for codegen instead of
47
+ upcasting to fp32. Can improve performance for prologue fusion but
48
+ requires careful testing of numerics.
49
+ """
50
+
51
+ codegen_low_precision: bool = True
52
+
53
+ def __call__(
54
+ self,
55
+ *args,
56
+ scheme: Optional[str] = None,
57
+ **kwargs,
58
+ ):
59
+ if not torch.compiler.is_compiling():
60
+ return args[0](*args[1:], **kwargs)
61
+
62
+ if scheme is not None:
63
+ kwargs["scheme"] = scheme
64
+
65
+ return invoke_quant_packed(*args, **kwargs, quant_options=self) # type: ignore[call-arg]
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/aoti_call_delegate.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-strict
8
+
9
+ from __future__ import annotations
10
+
11
+ import torch
12
+ import torch.utils._pytree as pytree
13
+ from torch._ops import HigherOrderOperator
14
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
15
+
16
+
17
+ AOTI_LOWERED_MODULE = "AOTInductorEPModule"
18
+
19
+
20
+ class AOTICallDelegate(HigherOrderOperator):
21
+ """aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram.
22
+
23
+ It has the following signature:
24
+ aoti_call_delegate(
25
+ lowered_module: AOTInductorEPModule,
26
+ original_gm:fx.GraphModule,
27
+ weight_args: List[Tensor],
28
+ input_args: List[Tensor],
29
+ ) -> outputs: List[Tensor]
30
+
31
+ where,
32
+ - lowered_module is the AOTInductor lowered submodule, backed by compiled .so file, supporting real tensor inputs
33
+ - original_gm is the original GraphModule before lowering, allowing FakeTensor propagation
34
+ - weight_args is the list of weights in original GraphModule, including parameters and buffers
35
+ - input_args is the list of flatten inputs
36
+
37
+ NOTE: aoti_call_delegate doesn't support retracing yet, as original_gm is currently stateful with weight as get_attr nodes.
38
+ This will fail functionalization during retrace. When we move AOTI to accept stateless GraphModule, we can enable retracing.
39
+
40
+ When serialization, we have special hanlding for aoti_call_delegate, as AOTInductorEPModule is not serializable
41
+ and stateful original_gm is failing the verifier.
42
+ """
43
+
44
+ def __init__(self) -> None:
45
+ super().__init__("aoti_call_delegate")
46
+
47
+ def __call__(
48
+ self,
49
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
50
+ original_gm: torch.fx.GraphModule,
51
+ weight_args: list[torch.Tensor],
52
+ input_args: list[torch.Tensor],
53
+ ) -> list[torch.Tensor]:
54
+ return super().__call__(lowered_module, original_gm, weight_args, input_args)
55
+
56
+
57
+ aoti_call_delegate = AOTICallDelegate()
58
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
59
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
60
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
61
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
62
+
63
+
64
+ @aoti_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
65
+ # pyre-ignore
66
+ def call_delegate_cpu(
67
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
68
+ original_gm: torch.fx.GraphModule,
69
+ weight_args: list[torch.Tensor],
70
+ input_args: list[torch.Tensor],
71
+ ) -> list[torch.Tensor]:
72
+ # FX creates this immutable_dict/list concept. Get rid of this.
73
+ map_types: dict[type, type] = {
74
+ torch.fx.immutable_collections.immutable_dict: dict,
75
+ torch.fx.immutable_collections.immutable_list: list,
76
+ }
77
+ new_args = pytree.tree_map_only(
78
+ tuple(map_types.keys()),
79
+ lambda a: map_types[type(a)](a),
80
+ input_args,
81
+ lambda a: isinstance(a, tuple(map_types.keys())),
82
+ )
83
+
84
+ has_fake_input_args = any(isinstance(arg, FakeTensor) for arg in new_args)
85
+ has_fake_params = any(
86
+ isinstance(param, FakeTensor) for param in original_gm.parameters()
87
+ )
88
+ has_fake_buffers = any(
89
+ isinstance(buffer, FakeTensor) for buffer in original_gm.buffers()
90
+ )
91
+
92
+ if has_fake_input_args or has_fake_params or has_fake_buffers:
93
+ # aoti lowered module doesn't support fake tensor
94
+ return original_gm(*new_args)
95
+ else:
96
+ return lowered_module(new_args) # type: ignore[misc]
97
+
98
+
99
+ @aoti_call_delegate.py_impl(FakeTensorMode)
100
+ # pyre-ignore
101
+ def call_delegate_fake_tensor_mode(
102
+ mode: FakeTensorMode,
103
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
104
+ original_gm: torch.fx.GraphModule,
105
+ weight_args: list[torch.Tensor],
106
+ input_args: list[torch.Tensor],
107
+ ) -> list[torch.Tensor]:
108
+ with mode:
109
+ return call_delegate_cpu(lowered_module, original_gm, weight_args, input_args)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/associative_scan.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import itertools
4
+ from typing import Any, Callable
5
+
6
+ import torch
7
+ import torch._prims_common as utils
8
+ import torch._subclasses.functional_tensor
9
+ import torch.utils._pytree as pytree
10
+ from torch._C import DispatchKey
11
+ from torch._higher_order_ops.utils import (
12
+ _maybe_run_with_interpreter,
13
+ _set_compilation_env,
14
+ autograd_not_implemented,
15
+ first_slice_copy,
16
+ reenter_make_fx,
17
+ unique_graph_id,
18
+ validate_subgraph_args_types,
19
+ )
20
+ from torch._ops import HigherOrderOperator
21
+ from torch._subclasses.fake_tensor import FakeTensorMode
22
+ from torch.fx.experimental.proxy_tensor import (
23
+ disable_proxy_modes_tracing,
24
+ ProxyTorchDispatchMode,
25
+ track_tensor_tree,
26
+ )
27
+
28
+
29
+ aten = torch._ops.ops.aten
30
+
31
+
32
+ def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves):
33
+ assert len(args) == 2 * num_leaves
34
+ lhs = pytree.tree_unflatten(args[:num_leaves], spec)
35
+ rhs = pytree.tree_unflatten(args[num_leaves:], spec)
36
+ combined = combine_fn(lhs, rhs)
37
+ combined_leaves = pytree.tree_leaves(combined)
38
+ assert num_leaves == len(combined_leaves)
39
+ return combined_leaves
40
+
41
+
42
+ def _interleave(a, b, dim=0):
43
+ # https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors
44
+ if b_trunc := (a.shape[dim] == b.shape[dim] + 1):
45
+ pad = (
46
+ [0] * ((b.ndim - dim - 1) * 2 + 1)
47
+ + [1]
48
+ + [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2))
49
+ )
50
+ b = torch.nn.functional.pad(b, pad)
51
+
52
+ stacked = torch.stack([a, b], dim=dim + 1)
53
+ interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1)
54
+ if b_trunc:
55
+ # TODO: find torch alternative for slice_along dim for torch.jit.script to work
56
+ interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1)
57
+ return interleaved
58
+
59
+
60
+ def safe_map(f, *args):
61
+ args = list(map(list, args))
62
+ n = len(args[0])
63
+ for arg in args[1:]:
64
+ if len(arg) != n:
65
+ raise ValueError("length mismatch: {list(map(len, args))}")
66
+
67
+ def nf(a):
68
+ return f(*a)
69
+
70
+ return list(map(nf, zip(*args)))
71
+
72
+
73
+ class AssociativeScanOp(HigherOrderOperator):
74
+ def __init__(self):
75
+ super().__init__("associative_scan")
76
+
77
+ def __call__(self, combine_fn, xs, additional_inputs):
78
+ # There is currently an issue that the ScanOp is sometimes called with
79
+ # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785
80
+ # Once this issue is resolved, the assertion should only allow tuples
81
+ # and the tuple cast should be removed
82
+ assert isinstance(
83
+ additional_inputs, (tuple, list)
84
+ ), "additional_inputs must be a tuple."
85
+ validate_subgraph_args_types(additional_inputs)
86
+ return super().__call__(combine_fn, xs, additional_inputs)
87
+
88
+
89
+ associative_scan_op = AssociativeScanOp()
90
+
91
+
92
+ def associative_scan(
93
+ combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree],
94
+ xs: pytree.PyTree,
95
+ dim: int,
96
+ reverse: bool = False,
97
+ combine_mode: str = "pointwise",
98
+ ) -> torch.Tensor:
99
+ r"""
100
+ Performs an inclusive scan with an associative combine function.
101
+
102
+ .. warning::
103
+ `torch.associative_scan` is a prototype feature in PyTorch. It currently
104
+ does not support autograd and you may run into miscompiles.
105
+ Read more about feature classification at:
106
+ https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
107
+
108
+ This operator requires runtime code generation and so requires support for
109
+ ``torch.compile``. Further, only CUDA device codegen is supported at the moment.
110
+
111
+ Args:
112
+ combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
113
+ or if input is a pytree ``(pytree, pytree) -> pytree``.
114
+ This function must be pure, i.e., no lifted arguments are supported at the moment,
115
+ satisfy the associative property and have no side-effects.
116
+ xs (torch.Tensor): The input tensor, or nested pytree of tensors.
117
+ All inputs are expected to have the same shape.
118
+ dim (int): the dimension to scan over
119
+ reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``.
120
+ combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``.
121
+ If ``combine_mode=pointwise``, ``combine_fn`` must be pure, may only contain pointwise operations
122
+ and ``xs`` must be CUDA tensors.
123
+ In all other cases ``combine_mode=generic`` should be used.
124
+ Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``.
125
+
126
+
127
+ Example::
128
+
129
+ def add(x: torch.Tensor, y: torch.Tensor):
130
+ return x + y
131
+
132
+ cumsum = associative_scan(add, x, dim)
133
+
134
+ """
135
+ if not callable(combine_fn):
136
+ raise ValueError("Combine_fn must be a callable, but got {combine_fn}")
137
+ if not isinstance(dim, int):
138
+ raise ValueError("Dim must be an int, but got " + str(type(dim)))
139
+ if combine_mode not in ["pointwise", "generic"]:
140
+ raise ValueError(
141
+ "Combine_mode must either 'pointwise' or 'generic', but got {combine_mode}"
142
+ )
143
+
144
+ if not torch.compiler.is_compiling():
145
+ with _set_compilation_env(), torch._dynamo.utils.disable_cache_limit():
146
+ return torch.compile(associative_scan, fullgraph=True, backend="eager")(
147
+ combine_fn, xs, dim, reverse=reverse, combine_mode=combine_mode
148
+ )
149
+
150
+ leaves, spec = pytree.tree_flatten(xs)
151
+
152
+ if combine_mode == "pointwise" and not all(l.device.type == "cuda" for l in leaves):
153
+ raise ValueError(
154
+ "For combine_mode='pointwise', all input tensors need to be on CUDA"
155
+ )
156
+
157
+ if len(leaves) == 0:
158
+ raise ValueError("Expected at least 1 xs leaf")
159
+ if any(not isinstance(x, torch.Tensor) for x in leaves):
160
+ raise ValueError("xs leaves must be a Tensor")
161
+ if any(x.is_sparse for x in leaves):
162
+ raise ValueError("xs leaves must dense Tensors, consider using `to_dense()`")
163
+ if any(x.ndim <= dim for x in leaves):
164
+ raise ValueError(
165
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
166
+ )
167
+ if any(x.shape[dim] == 0 for x in leaves):
168
+ raise ValueError(
169
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
170
+ )
171
+
172
+ if reverse:
173
+ leaves = [torch.flip(elem, [dim]) for elem in leaves]
174
+
175
+ ndim = leaves[0].ndim
176
+ orig_scan_dim = utils.canonicalize_dim(ndim, dim)
177
+ leaves = [torch.movedim(elem, dim, 0) for elem in leaves]
178
+
179
+ # Call the combine_fn with only a slice along the scan dim
180
+ # and check whether the output leaves have the same slice dimensions
181
+ sliced_leaves = [first_slice_copy(leaf) for leaf in leaves]
182
+
183
+ out = combine_fn(
184
+ pytree.tree_unflatten(sliced_leaves, spec),
185
+ pytree.tree_unflatten(sliced_leaves, spec),
186
+ )
187
+ out_leaves = pytree.tree_leaves(out)
188
+ if len(leaves) != len(out_leaves):
189
+ raise RuntimeError(
190
+ "The number of leaves of the pytree of the output of the operator needs to match the length of the pytree of the input"
191
+ )
192
+ if any(
193
+ x.shape != x_sliced.shape
194
+ or x.dtype != x_sliced.dtype
195
+ or x.device != x_sliced.device
196
+ or x.stride() != x_sliced.stride()
197
+ for x, x_sliced in zip(out_leaves, sliced_leaves)
198
+ ):
199
+ raise RuntimeError(
200
+ f"The metadata of the output of the operator needs to match the meta data of the xs pytree"
201
+ f"\n xs metadata : {[(x.shape, x.dtype, x.device, x.stride()) for x in sliced_leaves]}"
202
+ f"\n operator output metadata: {[(x.shape, x.dtype, x.device, x.stride()) for x in out_leaves]}"
203
+ )
204
+
205
+ if combine_mode == "generic":
206
+ # The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension
207
+ # For example, consider:
208
+ # def add(x: torch.Tensor, y: torch.Tensor):
209
+ # return x + y
210
+ # leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0]
211
+ # [0.0, 1.0, 2.0, 3.0]])
212
+ # which has shape 2 x 4;
213
+ # dim = 1;
214
+ # In the first iteration of `_scan` the combine_fn gets invoked with
215
+ # combine_fn([torch.tensor([[0.0, 2.0],
216
+ # [0.0, 2.0]])],
217
+ # [torch.tensor([[1.0, 3.0],
218
+ # [1.0, 3.0]])])
219
+ # The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension.
220
+ combine_fn = functools.partial(
221
+ wrap_combine_fn_flat,
222
+ combine_fn=torch.vmap(
223
+ combine_fn,
224
+ in_dims=(
225
+ pytree.tree_unflatten([0] * len(leaves), spec),
226
+ pytree.tree_unflatten([0] * len(leaves), spec),
227
+ ),
228
+ out_dims=0,
229
+ ),
230
+ spec=spec,
231
+ num_leaves=len(leaves),
232
+ )
233
+ result_flat = generic_associative_scan(combine_fn, leaves, additional_inputs=())
234
+ else:
235
+ combine_fn = functools.partial(
236
+ wrap_combine_fn_flat,
237
+ combine_fn=combine_fn,
238
+ spec=spec,
239
+ num_leaves=len(leaves),
240
+ )
241
+ result_flat = associative_scan_op(combine_fn, leaves, additional_inputs=())
242
+
243
+ if reverse:
244
+ result_flat = [torch.flip(elem, [0]) for elem in result_flat]
245
+
246
+ result_flat = [torch.movedim(elem, 0, orig_scan_dim) for elem in result_flat]
247
+
248
+ return pytree.tree_unflatten(result_flat, spec)
249
+
250
+
251
+ def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()):
252
+ r"""
253
+ This function performs the associative_scan operation.
254
+ The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently
255
+ applying the ``operator`` on all pairs in parallel along ``dim``.
256
+ The results of the recursive calls are later combined.
257
+
258
+ Args:
259
+ operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
260
+ or if input is a pytree ``(pytree, pytree) -> pytree``.
261
+ This function must be pure, pointwise, and satisfy the associative property.
262
+ leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of
263
+ ``xs`` provided to ``associative_scan``.
264
+ All inputs are expected to have the same shape.
265
+ dim (int): the dimension to scan over
266
+ additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope.
267
+ This parameter will be populated internally.
268
+
269
+ Example::
270
+
271
+ def add(x: torch.Tensor, y: torch.Tensor):
272
+ return x + y
273
+
274
+ leaves = torch.tensor([0.0, 1.0, 2.0, 3.0])
275
+
276
+ First iteration of _scan ->
277
+ # odd_elems -> apply operator on all neighbours
278
+ # odd_elems = operator([torch.tensor([0.0, 2.0])],
279
+ # [torch.tensor([1.0, 3.0])])
280
+ odd_elems = torch.tensor([1.0, 5.0])
281
+ Second iteration of _scan ->
282
+ # odd_elems = operator([torch.tensor([1.0])],
283
+ # [torch.tensor([5.0])])
284
+ odd_elems = torch.tensor([6.0])
285
+ # even_elems -> apply operator on all odd_elems and
286
+ # every second element of ``elems``, starting from the second element.
287
+ # even_elems is expanded with the first element of ``elems``
288
+ even_elems = [1.0]
289
+ # Merges odd_elems and even_elems
290
+ res = torch.tensor([1.0, 6.0])
291
+ # even_elems -> apply operator on all odd_elems and
292
+ # every second element of ``elems``, starting from the second element.
293
+ # even_elems is expanded with the first element of ``elems``
294
+ even_elems = [0.0, 3.0]
295
+ # Merges odd_elems and even_elems
296
+ res = torch.tensor([0.0, 1.0, 3.0, 6.0])
297
+
298
+ """
299
+
300
+ def _scan(elems):
301
+ """Perform the actual recursive scan on ``elems``."""
302
+ num_elems = elems[0].shape[dim]
303
+
304
+ if num_elems < 2:
305
+ return elems
306
+
307
+ reduced_elems = operator(
308
+ *[aten.slice(elem, dim, 0, -1, 2) for elem in elems],
309
+ *[aten.slice(elem, dim, 1, None, 2) for elem in elems],
310
+ *additional_inputs,
311
+ )
312
+
313
+ # Recursively compute scan for partially reduced tensors.
314
+ odd_elems = _scan(reduced_elems)
315
+
316
+ if num_elems % 2 == 0:
317
+ even_elems = operator(
318
+ *[aten.slice(e, dim, 0, -1) for e in odd_elems],
319
+ *[aten.slice(e, dim, 2, None, 2) for e in elems],
320
+ *additional_inputs,
321
+ )
322
+ else:
323
+ even_elems = operator(
324
+ *odd_elems,
325
+ *[aten.slice(e, dim, 2, None, 2) for e in elems],
326
+ *additional_inputs,
327
+ )
328
+
329
+ # The first element of a scan is the same as the first element
330
+ # of the original `elems`.
331
+ even_elems = [
332
+ torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim)
333
+ if result.shape.numel() > 0 and elem.shape[dim] > 0
334
+ else result
335
+ if result.shape.numel() > 0
336
+ else aten.slice(
337
+ elem, dim, 0, 1
338
+ ) # Jax allows/ignores concat with 0-dim, Pytorch does not
339
+ for (elem, result) in zip(elems, even_elems)
340
+ ]
341
+
342
+ return list(
343
+ safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems)
344
+ )
345
+
346
+ scans = _scan(leaves)
347
+
348
+ return scans
349
+
350
+
351
+ def trace_associative_scan(
352
+ proxy_mode,
353
+ func_overload,
354
+ combine_fn: Callable,
355
+ xs: list[torch.Tensor],
356
+ additional_inputs: tuple[torch.Tensor],
357
+ ):
358
+ with disable_proxy_modes_tracing():
359
+ sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)]
360
+ combine_graph = reenter_make_fx(combine_fn)(*sample_xs, *additional_inputs)
361
+
362
+ outputs = None
363
+ for node in combine_graph.graph.nodes:
364
+ if node.op == "output":
365
+ assert outputs is None
366
+ assert len(node.args) == 1
367
+ outputs = node.args[0]
368
+
369
+ assert outputs is not None
370
+ assert len(outputs) == len(
371
+ xs
372
+ ), f"expected combine_fn to return {len(xs)} results but got {len(outputs)}"
373
+
374
+ for i, o in zip(xs, outputs):
375
+ o_meta = o.meta["tensor_meta"]
376
+ assert o_meta.dtype == i.dtype, (
377
+ f"combine_fn output type mismatch, expected {i.dtype} "
378
+ + f"but got {o_meta.dtype}"
379
+ )
380
+
381
+ _, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph")
382
+
383
+ proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph)
384
+
385
+ args = (combine_graph, xs, additional_inputs)
386
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
387
+ out_proxy = proxy_mode.tracer.create_proxy(
388
+ "call_function", func_overload, proxy_args, {}, name="associative_scan"
389
+ )
390
+
391
+ with disable_proxy_modes_tracing():
392
+ out = tuple(aten.clone(x) for x in xs)
393
+
394
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
395
+
396
+
397
+ @associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd)
398
+ def associative_scan_op_dense(combine_fn, xs, additional_inputs):
399
+ return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs)
400
+
401
+
402
+ associative_scan_op.py_impl(DispatchKey.Autograd)(
403
+ autograd_not_implemented(associative_scan_op, deferred_error=True)
404
+ )
405
+
406
+
407
+ @associative_scan_op.py_impl(ProxyTorchDispatchMode)
408
+ def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs):
409
+ return trace_associative_scan(
410
+ mode, associative_scan_op, combine_fn, xs, additional_inputs
411
+ )
412
+
413
+
414
+ @associative_scan_op.py_impl(FakeTensorMode)
415
+ def assoiciative_scan_fake_tensor_mode(mode, combine_fn, xs, additional_inputs):
416
+ with mode:
417
+ return tuple(x.clone() for x in xs)
418
+
419
+
420
+ @associative_scan_op.py_functionalize_impl
421
+ def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs):
422
+ unwrapped_xs = ctx.unwrap_tensors(xs)
423
+ unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
424
+ with ctx.redispatch_to_next():
425
+ functional_combine_fn = ctx.functionalize(
426
+ _maybe_run_with_interpreter(combine_fn)
427
+ )
428
+ ret = associative_scan_op(
429
+ functional_combine_fn,
430
+ unwrapped_xs,
431
+ unwrapped_additional_inputs,
432
+ )
433
+ return ctx.wrap_tensors(ret)
434
+
435
+
436
+ def _fake_associative_scan(combine_fn, xs, dim, reverse=False):
437
+ inp_leaves, spec = pytree.tree_flatten(xs)
438
+ result_flat: list[Any] = []
439
+ num_leaves = len(inp_leaves)
440
+ op = reversed if reverse else lambda x: x
441
+
442
+ for ind in op(range(inp_leaves[0].size(dim))):
443
+ r = [
444
+ inp_leaves[leave_ind][(slice(None),) * dim + (ind,)]
445
+ for leave_ind in range(num_leaves)
446
+ ]
447
+ if (ind > 0 and not reverse) or (
448
+ ind < (inp_leaves[0].size(dim) - 1) and reverse
449
+ ):
450
+ r = combine_fn(
451
+ pytree.tree_unflatten(result_flat[-1], spec),
452
+ pytree.tree_unflatten(r, spec),
453
+ )
454
+ r_flat, _ = pytree.tree_flatten(r)
455
+ result_flat.append(r_flat)
456
+
457
+ results = [
458
+ torch.stack([e[leave_ind] for e in op(result_flat)], dim)
459
+ for leave_ind in range(num_leaves)
460
+ ]
461
+ return pytree.tree_unflatten(results, spec)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/auto_functionalize.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Any, Optional, Union
7
+
8
+ import torch
9
+ import torch._library.utils as library_utils
10
+ import torch.utils._pytree as pytree
11
+ from torch import Tensor
12
+ from torch._C import DispatchKey
13
+ from torch._ops import HigherOrderOperator, OperatorBase, OpOverload
14
+ from torch._prims_common import clone_preserve_strides
15
+ from torch._subclasses.fake_tensor import FakeTensorMode
16
+ from torch.fx.experimental.proxy_tensor import (
17
+ disable_proxy_modes_tracing,
18
+ ProxyTorchDispatchMode,
19
+ track_tensor_tree,
20
+ )
21
+
22
+
23
+ def get_base(tensor):
24
+ if torch.is_inference_mode_enabled():
25
+ return tensor._inference_mode_base
26
+ else:
27
+ return tensor._base
28
+
29
+
30
+ class ViewInfo(ABC):
31
+ base_index: int
32
+
33
+ def __init__(self, base_index):
34
+ self.base_index = base_index
35
+
36
+ @abstractmethod
37
+ def regenerate_view(self, bases_list: list[Tensor]):
38
+ pass
39
+
40
+
41
+ @dataclass
42
+ class AsStridedViewInfo(ViewInfo):
43
+ size: Sequence[Union[int, torch.SymInt]]
44
+ stride: Sequence[Union[int, torch.SymInt]]
45
+ storage_offset: int
46
+
47
+ def __init__(self, base_index, size, stride, storage_offset):
48
+ super().__init__(base_index)
49
+ self.size = size
50
+ self.stride = stride
51
+ self.storage_offset = storage_offset
52
+
53
+ def regenerate_view(self, bases_list: list[Tensor]):
54
+ return torch.as_strided(
55
+ bases_list[self.base_index],
56
+ self.size,
57
+ self.stride,
58
+ self.storage_offset,
59
+ )
60
+
61
+
62
+ @dataclass
63
+ class SliceViewInfo(ViewInfo):
64
+ dim: Union[int, torch.SymInt]
65
+ start: Union[int, torch.SymInt]
66
+ end: Union[int, torch.SymInt]
67
+
68
+ def __init__(self, base_index, dim, start, end):
69
+ super().__init__(base_index)
70
+ self.dim = dim
71
+ self.start = start
72
+ self.end = end
73
+
74
+ def regenerate_view(self, bases_list: list[Tensor]):
75
+ return torch.ops.aten.slice.Tensor(
76
+ bases_list[self.base_index], self.dim, self.start, self.end
77
+ )
78
+
79
+
80
+ @dataclass
81
+ class AliasViewInfo(ViewInfo):
82
+ def __init__(self, base_index):
83
+ super().__init__(base_index)
84
+
85
+ def regenerate_view(self, bases_list: list[Tensor]):
86
+ return torch.ops.aten.alias.default(bases_list[self.base_index])
87
+
88
+
89
+ @dataclass
90
+ class NotView(ViewInfo):
91
+ def __init__(self, base_index):
92
+ super().__init__(base_index)
93
+
94
+ def regenerate_view(self, bases_list: list[Tensor]):
95
+ return bases_list[self.base_index]
96
+
97
+
98
+ def is_alias(base, tensor):
99
+ from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
100
+
101
+ return all(
102
+ statically_known_true(a)
103
+ for a in [
104
+ sym_eq(base.storage_offset(), tensor.storage_offset()),
105
+ sym_eq(base.stride(), tensor.stride()),
106
+ sym_eq(base.size(), tensor.size()),
107
+ ]
108
+ )
109
+
110
+
111
+ # return None or (dim, start, end)
112
+ def try_use_slice(base, tensor):
113
+ from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
114
+
115
+ # This condition should never be triggered.
116
+ if is_alias(base, tensor):
117
+ return (0, 0, base.size()[0])
118
+
119
+ # TODO is there cases can we use slice even if stride or len(sizes) are not equal?
120
+ if not statically_known_true(sym_eq(tensor.stride(), base.stride())):
121
+ return None
122
+ if not statically_known_true(sym_eq(len(tensor.size()), len(base.size()))):
123
+ return None
124
+
125
+ dim = None
126
+ count = 0
127
+ for i in range(len(tensor.size())):
128
+ if base.size()[i] != tensor.size()[i]:
129
+ dim = i
130
+ count = count + 1
131
+ if count != 1:
132
+ return None
133
+
134
+ if tensor.storage_offset() % tensor.stride()[dim] != 0:
135
+ return None
136
+ start = tensor.storage_offset() // tensor.stride()[dim]
137
+ end = start + tensor.size()[dim]
138
+ return (dim, start, end)
139
+
140
+
141
+ def write_view_information_to_args(
142
+ mutable_arg_names: list[str],
143
+ mutable_arg_types: list[torch.Type],
144
+ kwargs: dict[str, Any],
145
+ arg_to_base_index: dict[str, Any],
146
+ ):
147
+ """
148
+ This function writes the view information into kwargs. It reads mutable_args from kwargs.
149
+ and uses arg_to_base_index and tensor information to write ViewInfo into kwargs.
150
+ mutable_arg_names: mutable custom operator arg names.
151
+ mutable_arg_types: mutable custom operator arg types.
152
+ kwargs: the original custom operator args.
153
+ arg_to_base_index: maps mutable_arg_name to int | [int] that refers to the base tensor that
154
+ corresponds to the input tensor
155
+ """
156
+
157
+ def write_single_view(prefix: str, tensor: Tensor, base_index: int):
158
+ assert f"{prefix}_base_index" not in kwargs
159
+ assert f"{prefix}_size" not in kwargs
160
+ assert f"{prefix}_stride" not in kwargs
161
+ assert f"{prefix}_storage_offset" not in kwargs
162
+
163
+ assert f"{prefix}_slice_dim" not in kwargs
164
+ assert f"{prefix}_slice_start" not in kwargs
165
+ assert f"{prefix}_slice_end" not in kwargs
166
+
167
+ def use_as_strided(tensor):
168
+ kwargs[f"{prefix}_size"] = tensor.size()
169
+ kwargs[f"{prefix}_stride"] = tensor.stride()
170
+ kwargs[f"{prefix}_storage_offset"] = tensor.storage_offset()
171
+
172
+ def use_slice(dim, start, end):
173
+ kwargs[f"{prefix}_slice_dim"] = dim
174
+ kwargs[f"{prefix}_slice_start"] = start
175
+ kwargs[f"{prefix}_slice_end"] = end
176
+
177
+ def use_alias():
178
+ kwargs[f"{prefix}_alias"] = True
179
+
180
+ # The start if the function
181
+ if tensor is None:
182
+ kwargs[f"{prefix}_base_index"] = None
183
+ else:
184
+ base = get_base(tensor)
185
+ kwargs[f"{prefix}_base_index"] = base_index
186
+ if base is None:
187
+ # no need to add anything else other than _base_index
188
+ return
189
+ elif is_alias(base, tensor):
190
+ use_alias()
191
+ elif (slice_info := try_use_slice(base, tensor)) is not None:
192
+ use_slice(*slice_info)
193
+ else:
194
+ use_as_strided(tensor)
195
+
196
+ for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
197
+ arg = kwargs[arg_name]
198
+ if library_utils.is_tensorlist_like_type(arg_type):
199
+ if arg is None:
200
+ kwargs[f"_{arg_name}_length"] = None
201
+ else:
202
+ kwargs[f"_{arg_name}_length"] = len(arg)
203
+ for i, elem in enumerate(arg):
204
+ write_single_view(
205
+ f"_{arg_name}_{i}", elem, arg_to_base_index[arg_name][i]
206
+ )
207
+
208
+ elif library_utils.is_tensor_like_type(arg_type):
209
+ write_single_view(
210
+ f"_{arg_name}",
211
+ kwargs[arg_name],
212
+ arg_to_base_index.get(arg_name, None),
213
+ )
214
+ else:
215
+ raise RuntimeError(f"Unsupported type {arg_type}")
216
+
217
+
218
+ # Returns a dict of arg_name -> ViewInfo | [ViewInfo]
219
+ def read_view_information_from_args(
220
+ mutable_arg_names: list[str],
221
+ mutable_arg_types: list[torch.Type],
222
+ kwargs: dict[str, Any],
223
+ all_bases: list[Tensor],
224
+ ):
225
+ """
226
+ This reads the view information added by `write_view_information_to_args` from kwargs, pop them,
227
+ and returns a dict arg_name -> ViewInfo | [ViewInfo](if the input is list). that maps each mutable arg
228
+ to its view information.
229
+ mutable_arg_names: mutable custom operator arg names.
230
+ mutable_arg_types: mutable custom operator arg types.
231
+ kwargs : args of auto_functionalize(custom_op, kwargs)
232
+ """
233
+
234
+ def get_arg(name):
235
+ return kwargs.pop(name)
236
+
237
+ def read_single_view(prefix):
238
+ base_index = get_arg(f"{prefix}_base_index")
239
+ if base_index is None:
240
+ return None
241
+ elif f"{prefix}_alias" in kwargs:
242
+ get_arg(f"{prefix}_alias")
243
+ return AliasViewInfo(base_index)
244
+ elif f"{prefix}_storage_offset" in kwargs:
245
+ # The view is regenerated using as_strided.
246
+ size = get_arg(f"{prefix}_size")
247
+ stride = get_arg(f"{prefix}_stride")
248
+ storage_offset = get_arg(f"{prefix}_storage_offset")
249
+ return AsStridedViewInfo(base_index, size, stride, storage_offset)
250
+ elif f"{prefix}_slice_dim" in kwargs:
251
+ dim = get_arg(f"{prefix}_slice_dim")
252
+ start = get_arg(f"{prefix}_slice_start")
253
+ end = get_arg(f"{prefix}_slice_end")
254
+ return SliceViewInfo(base_index, dim, start, end)
255
+ else:
256
+ # This means that the argument is the base tensor
257
+ return NotView(base_index)
258
+
259
+ args_view_info: dict[str, Any] = {}
260
+ for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
261
+ if library_utils.is_tensorlist_like_type(arg_type):
262
+ length = get_arg(f"_{arg_name}_length")
263
+ if length is None:
264
+ # The whole list is None.
265
+ args_view_info[arg_name] = None
266
+ else:
267
+ args_view_info[arg_name] = [
268
+ read_single_view(f"_{arg_name}_{i}") for i in range(length)
269
+ ]
270
+
271
+ elif library_utils.is_tensor_like_type(arg_type):
272
+ args_view_info[arg_name] = read_single_view(f"_{arg_name}")
273
+ else:
274
+ raise RuntimeError(f"Unsupported type {arg_type}")
275
+ return args_view_info
276
+
277
+
278
+ # NOTE: [auto-functionalizing custom ops]
279
+ # Users may wish to torch.compile custom ops that mutate their inputs.
280
+ # torch.compile will automatically support this op without anyone needing
281
+ # to provide a functionalization kernel for it. Here's how.
282
+ #
283
+ # Let's say we have a hypothetical mylib::sin_(Tensor(a!) x) -> ()
284
+ # op. First, when FakeTensor sees this op:
285
+ # - If the schema says it returns nothing, we can generate a trivial
286
+ # FakeTensor rule for it (that returns nothing).
287
+ # - Otherwise, the user needs to provide a FakeTensor impl (fake impl)
288
+ #
289
+ # Next, when Python FunctionalTensor sees the op, it will functionalize
290
+ # it by emitting a call to an auto_functionalize(op, ["x"], {"x": ...})
291
+ # HOP and replacing the mutated inputs with corresponding outputs of this HOP.
292
+ # This HOP effectively runs the functional version of the op when
293
+ # called: it clones inputs that will be mutated, runs the op, and
294
+ # then returns (output, Tensors with the new values)
295
+ #
296
+ # auto_functionalize_v2 is an improved version of auto_functionalize that better handle
297
+ # re-inplacing views.
298
+
299
+
300
+ class AutoFunctionalized(HigherOrderOperator):
301
+ """auto_functionalized(_mutable_op, **kwargs)
302
+
303
+ This HOP runs a "functional" version of _mutable_op.
304
+
305
+ Concretely, it looks at all the arguments that are mutable through
306
+ _mutable_op's operator schema, clones those kwargs, runs
307
+ `out = _mutable_op(**kwargs)` with the cloned values, and then returns the
308
+ operator output concatenated with the cloned values that were mutated.
309
+
310
+ We have some restrictions on `_mutable_op`.
311
+ See `can_auto_functionalize` for the restrictions. We can likely lift
312
+ many of these if users request it.
313
+
314
+ The reason why _mutable_op is prefixed with an
315
+ underscore is to prevent collisions with kwarg names in **kwargs.
316
+ """
317
+
318
+ def __init__(self) -> None:
319
+ super().__init__("auto_functionalized", cacheable=True)
320
+
321
+ def __call__(
322
+ self,
323
+ /,
324
+ _mutable_op: OpOverload,
325
+ **kwargs: Any,
326
+ ) -> tuple[Any, tuple[Tensor, ...]]:
327
+ assert can_auto_functionalize(_mutable_op)
328
+ assert isinstance(kwargs, dict)
329
+ return super().__call__(_mutable_op, **kwargs)
330
+
331
+
332
+ auto_functionalized = AutoFunctionalized()
333
+ auto_functionalized.__module__ = "torch.ops.higher_order"
334
+
335
+ auto_functionalized.fallthrough(DispatchKey.AutogradCPU)
336
+ auto_functionalized.fallthrough(DispatchKey.AutogradCUDA)
337
+
338
+
339
+ class AutoFunctionalizedV2(HigherOrderOperator):
340
+ """auto_functionalized_v2(_mutable_op, **kwargs)
341
+
342
+ This HOP runs a "functional" version of _mutable_op.
343
+ Unlike AutoFunctionalized, this version is improved to better handle
344
+ view tensors. This version is only used in non export mode.
345
+ """
346
+
347
+ def __init__(self) -> None:
348
+ super().__init__("auto_functionalized_v2", cacheable=True)
349
+
350
+ def __call__(
351
+ self,
352
+ /,
353
+ _mutable_op: OpOverload,
354
+ **kwargs: Any,
355
+ ) -> tuple[Any, tuple[Tensor, ...]]:
356
+ assert can_auto_functionalize(_mutable_op)
357
+ assert isinstance(kwargs, dict)
358
+ return super().__call__(_mutable_op, **kwargs)
359
+
360
+
361
+ auto_functionalized_v2 = AutoFunctionalizedV2()
362
+ auto_functionalized_v2.__module__ = "torch.ops.higher_order"
363
+
364
+ auto_functionalized_v2.fallthrough(DispatchKey.AutogradCPU)
365
+ auto_functionalized_v2.fallthrough(DispatchKey.AutogradCUDA)
366
+
367
+
368
+ def can_auto_functionalize(op: OperatorBase) -> bool:
369
+ if not isinstance(op, OpOverload):
370
+ return False
371
+
372
+ if torch._library.utils.is_builtin(op):
373
+ # We control the built-ins. These may (in rare cases)
374
+ # do input metadata mutation (which we have banned on custom ops)
375
+ return False
376
+ schema = op._schema
377
+ if not schema.is_mutable:
378
+ return False
379
+ schema = op._schema
380
+
381
+ for arg in schema.arguments:
382
+ if arg.alias_info is None:
383
+ continue
384
+ if not arg.alias_info.is_write:
385
+ continue
386
+ if torch._library.utils.is_tensor_like_type(arg.type):
387
+ continue
388
+ if torch._library.utils.is_tensorlist_like_type(arg.type):
389
+ continue
390
+ return False
391
+
392
+ if len(schema.returns) == 1 and isinstance(schema.returns[0].type, torch.NoneType):
393
+ # Skip schema returns -> None
394
+ return True
395
+ # The returns must not alias anything
396
+ for ret in schema.returns:
397
+ if ret.alias_info is None and type(ret.type) is torch.TensorType:
398
+ continue
399
+ # Not yet supported: List[Tensor] return.
400
+ return False
401
+ if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Functionalize"):
402
+ return False
403
+ return True
404
+
405
+
406
+ def get_mutable_args(op: OpOverload) -> tuple[list[str], list[torch.Type]]:
407
+ """
408
+ Returns the list of argument names that get mutated according to the
409
+ schema and their types.
410
+ """
411
+ mutable_args_names = [
412
+ arg.name
413
+ for arg in op._schema.arguments
414
+ if arg.alias_info is not None and arg.alias_info.is_write
415
+ ]
416
+
417
+ mutable_args_types = [
418
+ arg.type
419
+ for arg in op._schema.arguments
420
+ if arg.alias_info is not None and arg.alias_info.is_write
421
+ ]
422
+ return mutable_args_names, mutable_args_types
423
+
424
+
425
+ def do_auto_functionalize(
426
+ mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
427
+ op: OpOverload,
428
+ args: tuple[Any, ...],
429
+ kwargs: dict[str, Any],
430
+ ) -> Any:
431
+ """Functionalizes a call to op(*args, **kwargs) by emitting a call to
432
+ `outs = auto_functionalized(op, normalized_kwargs)`
433
+ and replacing the mutated (args, kwargs) with the corresponding outputs.
434
+
435
+ The normalized_kwargs are just the (args, kwargs), but all in kwarg form.
436
+ This makes handling easier for the auto_functionalized HOP.
437
+ """
438
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
439
+
440
+ ctx = PythonFunctionalizeAPI(mode=mode)
441
+
442
+ # All of the (args, kwargs), but all as kwargs. The names for the
443
+ # args come from the schema. This makes it easier for us to work with them.
444
+ normalized_kwargs = {}
445
+ schema = op._schema
446
+ for idx, arg in enumerate(schema.arguments):
447
+ # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
448
+ if arg.name in kwargs:
449
+ normalized_kwargs[arg.name] = kwargs[arg.name]
450
+ elif idx < len(args):
451
+ # if its out of bounds we don't need to do anything
452
+ # as it means the the optional arg was passed with its default
453
+ # value
454
+ normalized_kwargs[arg.name] = args[idx]
455
+ else:
456
+ normalized_kwargs[arg.name] = arg.default_value
457
+
458
+ unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
459
+ if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
460
+ warnings.warn(
461
+ "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
462
+ "Please consider using a different name for this argument to avoid potential issues."
463
+ )
464
+ with ctx.redispatch_to_next():
465
+ unwrapped_outs = auto_functionalized(
466
+ op, **unwrapped_kwargs # type: ignore[arg-type]
467
+ )
468
+
469
+ # List of the name of args that get mutated (according to the schema)
470
+ mutable_args_names, _ = get_mutable_args(op)
471
+
472
+ unwrapped_actual_out: Union[Any, tuple[Any]] = unwrapped_outs[
473
+ : -len(mutable_args_names)
474
+ ]
475
+ unwrapped_mutable_out = unwrapped_outs[-len(mutable_args_names) :]
476
+
477
+ if len(op._schema.returns) == 0:
478
+ assert unwrapped_actual_out[0] is None
479
+ unwrapped_actual_out = None
480
+ elif len(op._schema.returns) == 1:
481
+ assert len(unwrapped_actual_out) == 1
482
+ unwrapped_actual_out = unwrapped_actual_out[0]
483
+ else:
484
+ assert len(unwrapped_actual_out) == len(op._schema.returns)
485
+
486
+ for name, unwrapped_out in zip(mutable_args_names, unwrapped_mutable_out):
487
+ # Can be None if input was `Tensor(a!)?`
488
+ if unwrapped_out is None:
489
+ continue
490
+
491
+ # We only handle Tensor or List[Tensor] here for now.
492
+ def sync_update(o, orig_arg):
493
+ ctx.replace(orig_arg, o)
494
+ ctx.commit_update(orig_arg)
495
+ ctx.sync(orig_arg)
496
+
497
+ orig_arg = normalized_kwargs[name]
498
+
499
+ if isinstance(unwrapped_out, torch.Tensor):
500
+ sync_update(unwrapped_out, orig_arg)
501
+ elif isinstance(unwrapped_out, list) and all(
502
+ isinstance(o, torch.Tensor) for o in unwrapped_out
503
+ ):
504
+ assert len(orig_arg) == len(unwrapped_out)
505
+ for orig_a, o in zip(orig_arg, unwrapped_out):
506
+ sync_update(o, orig_a)
507
+ else:
508
+ raise RuntimeError(
509
+ f"unsupported type for auto-functionalization: {unwrapped_out}"
510
+ )
511
+
512
+ return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
513
+
514
+
515
+ def do_auto_functionalize_v2(
516
+ mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
517
+ op: OpOverload,
518
+ args: tuple[Any, ...],
519
+ kwargs: dict[str, Any],
520
+ ) -> Any:
521
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
522
+
523
+ ctx = PythonFunctionalizeAPI(mode=mode)
524
+
525
+ # All of the (args, kwargs), but all as kwargs. The names for the
526
+ # args come from the schema. This makes it easier for us to work with them.
527
+ normalized_kwargs = {}
528
+
529
+ schema = op._schema
530
+ for idx, arg in enumerate(schema.arguments):
531
+ # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
532
+ if arg.name in kwargs:
533
+ normalized_kwargs[arg.name] = kwargs[arg.name]
534
+ elif idx < len(args):
535
+ # if its out of bounds we don't need to do anything
536
+ # as it means the the optional arg was passed with its default
537
+ # value
538
+ normalized_kwargs[arg.name] = args[idx]
539
+ else:
540
+ normalized_kwargs[arg.name] = arg.default_value
541
+
542
+ # List of the name of args that get mutated (according to the schema)
543
+ mutable_args_names, mutable_args_types = get_mutable_args(op)
544
+
545
+ # A list of all bases of mutable args without duplication
546
+ all_bases = []
547
+ all_bases_addresses: list[int] = []
548
+
549
+ # Map arg_name to the index of its base in all_bases.
550
+ arg_to_base_index: dict[str, Any] = {}
551
+
552
+ def update_dict(tensor, arg_name, index=None):
553
+ base = tensor if get_base(tensor) is None else get_base(tensor)
554
+
555
+ def set_result(base_index):
556
+ if index is None:
557
+ arg_to_base_index[arg_name] = base_index
558
+ else:
559
+ arg_to_base_index[arg_name][index] = base_index
560
+
561
+ if not all_bases_addresses.__contains__(base._cdata):
562
+ all_bases_addresses.append(base._cdata)
563
+ all_bases.append(base)
564
+ set_result(len(all_bases) - 1)
565
+ else:
566
+ set_result(all_bases_addresses.index(base._cdata))
567
+
568
+ for arg_name in mutable_args_names:
569
+ arg = normalized_kwargs[arg_name]
570
+ if arg is None:
571
+ continue
572
+
573
+ if isinstance(arg, list):
574
+ arg_to_base_index[arg_name] = {}
575
+ for i, tensor in enumerate(arg):
576
+ if tensor is None:
577
+ arg_to_base_index[arg_name].append(None)
578
+ continue
579
+
580
+ update_dict(tensor, arg_name, i)
581
+
582
+ else:
583
+ update_dict(arg, arg_name)
584
+
585
+ # add view_meta for each args into unwrapped_kwargs.
586
+ write_view_information_to_args(
587
+ mutable_args_names,
588
+ mutable_args_types,
589
+ normalized_kwargs,
590
+ arg_to_base_index,
591
+ )
592
+
593
+ # remove mutated args from the kwargs (its a function of _all_bases now)
594
+ for arg_name in mutable_args_names:
595
+ del normalized_kwargs[arg_name] # type: ignore[arg-type]
596
+
597
+ unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
598
+ if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
599
+ warnings.warn(
600
+ "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
601
+ "Please consider using a different name for this argument to avoid potential issues."
602
+ )
603
+ all_basis_unwrapped = ctx.unwrap_tensors(all_bases)
604
+
605
+ with ctx.redispatch_to_next():
606
+ unwrapped_outs = auto_functionalized_v2(
607
+ op, **dict(unwrapped_kwargs, _all_bases=all_basis_unwrapped) # type: ignore[arg-type]
608
+ )
609
+
610
+ unwrapped_actual_out: Union[Any, tuple[Any]] = (
611
+ unwrapped_outs if len(all_bases) == 0 else unwrapped_outs[: -len(all_bases)]
612
+ )
613
+
614
+ unwrapped_mutable_out = (
615
+ [] if len(all_bases) == 0 else unwrapped_outs[-len(all_bases) :]
616
+ )
617
+
618
+ if len(op._schema.returns) == 0:
619
+ assert unwrapped_actual_out[0] is None
620
+ unwrapped_actual_out = None
621
+ elif len(op._schema.returns) == 1:
622
+ assert len(unwrapped_actual_out) == 1
623
+ unwrapped_actual_out = unwrapped_actual_out[0]
624
+ else:
625
+ assert len(unwrapped_actual_out) == len(op._schema.returns)
626
+
627
+ for orig_arg, unwrapped_out in zip(all_bases, unwrapped_mutable_out):
628
+ # Can be None if input was `Tensor(a!)?`
629
+ if unwrapped_out is None:
630
+ continue
631
+
632
+ # We only handle Tensor or List[Tensor] here for now.
633
+ def sync_update(o, orig_arg):
634
+ ctx.replace(orig_arg, o)
635
+ ctx.commit_update(orig_arg)
636
+ ctx.sync(orig_arg)
637
+
638
+ if isinstance(unwrapped_out, torch.Tensor):
639
+ sync_update(unwrapped_out, orig_arg)
640
+ elif isinstance(unwrapped_out, list) and all(
641
+ isinstance(o, torch.Tensor) for o in unwrapped_out
642
+ ):
643
+ assert len(orig_arg) == len(unwrapped_out)
644
+ for orig_a, o in zip(orig_arg, unwrapped_out):
645
+ sync_update(o, orig_a)
646
+ else:
647
+ raise RuntimeError(
648
+ f"unsupported type for auto-functionalization: {unwrapped_out}"
649
+ )
650
+
651
+ return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
652
+
653
+
654
+ # auto_functionalize functions
655
+ @auto_functionalized.py_impl(DispatchKey.CompositeExplicitAutograd)
656
+ def auto_functionalized_dense(
657
+ _mutable_op: OpOverload,
658
+ _only_clone_these_tensors: Optional[tuple[str, ...]] = None,
659
+ **kwargs: Any,
660
+ ) -> tuple[Any, tuple[Tensor, ...]]:
661
+ new_kwargs = dict(**kwargs)
662
+ result = []
663
+
664
+ _mutable_args_names, _ = get_mutable_args(_mutable_op)
665
+ for name in _mutable_args_names:
666
+ if (
667
+ _only_clone_these_tensors is not None
668
+ and name not in _only_clone_these_tensors
669
+ ):
670
+ new_kwargs[name] = kwargs[name]
671
+ else:
672
+ new_kwargs[name] = (
673
+ [clone_preserve_strides(x) for x in kwargs[name]]
674
+ if kwargs[name] is not None and isinstance(kwargs[name], list)
675
+ else (
676
+ clone_preserve_strides(kwargs[name])
677
+ if kwargs[name] is not None
678
+ else None
679
+ )
680
+ )
681
+ result.append(new_kwargs[name])
682
+ out = _mutable_op(**new_kwargs)
683
+
684
+ if isinstance(out, tuple):
685
+ return (*out, *result) # type: ignore[return-value]
686
+ else:
687
+ return (out, *result) # type: ignore[return-value]
688
+
689
+
690
+ @auto_functionalized.py_impl(FakeTensorMode)
691
+ def auto_functionalized_fake(
692
+ mode,
693
+ _mutable_op: OpOverload,
694
+ **kwargs: Any,
695
+ ) -> tuple[Any, tuple[Tensor, ...]]:
696
+ with mode:
697
+ result = auto_functionalized_dense(
698
+ _mutable_op, _only_clone_these_tensors=None, **kwargs
699
+ )
700
+ return result
701
+
702
+
703
+ @auto_functionalized.py_impl(ProxyTorchDispatchMode)
704
+ def auto_functionalized_proxy(
705
+ mode,
706
+ _mutable_op: OpOverload,
707
+ **kwargs: Any,
708
+ ) -> tuple[Any, tuple[Tensor, ...]]:
709
+ with disable_proxy_modes_tracing():
710
+ out = auto_functionalized(_mutable_op, **kwargs)
711
+
712
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
713
+ out_proxy = mode.tracer.create_proxy(
714
+ "call_function",
715
+ auto_functionalized,
716
+ (_mutable_op,),
717
+ proxy_kwargs,
718
+ )
719
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
720
+ return result
721
+
722
+
723
+ @auto_functionalized.py_functionalize_impl
724
+ def auto_functionalized_func(ctx, _mutable_op, **kwargs):
725
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
726
+ with ctx.redispatch_to_next():
727
+ result = auto_functionalized(_mutable_op, **unwrapped_kwargs)
728
+ return ctx.wrap_tensors(result)
729
+
730
+
731
+ # auto_functionalized_v2 functions
732
+ @auto_functionalized_v2.py_impl(DispatchKey.CompositeExplicitAutograd)
733
+ def auto_functionalized_v2_dense(
734
+ _mutable_op: OpOverload,
735
+ _only_clone_these_bases: Optional[tuple[int, ...]] = None,
736
+ **kwargs: Any,
737
+ ) -> tuple[Any, tuple[Tensor, ...]]:
738
+ all_bases: list[Tensor] = kwargs.pop("_all_bases", [])
739
+ mutable_args_names, mutable_args_types = get_mutable_args(_mutable_op)
740
+ args_view_info = read_view_information_from_args(
741
+ mutable_args_names, mutable_args_types, kwargs, all_bases
742
+ )
743
+
744
+ if _only_clone_these_bases is None:
745
+ _only_clone_these_bases = tuple(range(len(all_bases)))
746
+
747
+ def maybe_copy(i, t):
748
+ if t is None:
749
+ return None
750
+ if i in _only_clone_these_bases:
751
+ return clone_preserve_strides(t)
752
+ else:
753
+ return t
754
+
755
+ all_bases_new = [maybe_copy(i, t) for i, t in enumerate(all_bases)]
756
+
757
+ # create new args
758
+ new_kwargs = dict(**kwargs)
759
+
760
+ # re-generate all inputs from all_bases_new using args_view_info and add them to new_kwargs.
761
+ for arg_name in mutable_args_names:
762
+ if args_view_info[arg_name] is None:
763
+ new_kwargs[arg_name] = None
764
+ elif isinstance(args_view_info[arg_name], list):
765
+ new_kwargs[arg_name] = []
766
+ for i, elem in enumerate(args_view_info[arg_name]):
767
+ if elem is None:
768
+ new_kwargs[arg_name].append(None)
769
+ else:
770
+ view_info = args_view_info[arg_name][i]
771
+ new_kwargs[arg_name].append(
772
+ view_info.regenerate_view(all_bases_new)
773
+ )
774
+ else:
775
+ new_kwargs[arg_name] = args_view_info[arg_name].regenerate_view(
776
+ all_bases_new
777
+ )
778
+
779
+ out = _mutable_op(**new_kwargs)
780
+
781
+ if isinstance(out, tuple):
782
+ return (*out, *all_bases_new) # type: ignore[return-value]
783
+ else:
784
+ return (out, *all_bases_new) # type: ignore[return-value]
785
+
786
+
787
+ @auto_functionalized_v2.py_impl(FakeTensorMode)
788
+ def auto_functionalized_v2_fake(
789
+ mode,
790
+ _mutable_op: OpOverload,
791
+ **kwargs: dict[str, Any],
792
+ ) -> tuple[Any, tuple[Tensor, ...]]:
793
+ with mode:
794
+ result = auto_functionalized_v2_dense(
795
+ _mutable_op, _only_clone_these_bases=None, **kwargs
796
+ )
797
+ return result
798
+
799
+
800
+ @auto_functionalized_v2.py_impl(ProxyTorchDispatchMode)
801
+ def auto_functionalized_v2_proxy(
802
+ mode,
803
+ _mutable_op: OpOverload,
804
+ **kwargs: dict[str, Any],
805
+ ) -> tuple[Any, tuple[Tensor, ...]]:
806
+ with disable_proxy_modes_tracing():
807
+ out = auto_functionalized_v2(_mutable_op, **kwargs)
808
+
809
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
810
+ out_proxy = mode.tracer.create_proxy(
811
+ "call_function",
812
+ auto_functionalized_v2,
813
+ (_mutable_op,),
814
+ proxy_kwargs,
815
+ )
816
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
817
+ return result
818
+
819
+
820
+ @auto_functionalized_v2.py_functionalize_impl
821
+ def auto_functionalized_v2_func(ctx, _mutable_op, **kwargs):
822
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
823
+ with ctx.redispatch_to_next():
824
+ result = auto_functionalized_v2(_mutable_op, **unwrapped_kwargs)
825
+ return ctx.wrap_tensors(result)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/base_hop.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import abc
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+ from torch._C import DispatchKey
8
+ from torch._dispatch.python import suspend_functionalization
9
+ from torch._higher_order_ops.utils import reenter_make_fx
10
+ from torch._ops import HigherOrderOperator
11
+ from torch._subclasses import FakeTensorMode
12
+ from torch._subclasses.functional_tensor import disable_functional_mode
13
+ from torch.fx.experimental.proxy_tensor import (
14
+ disable_proxy_modes_tracing,
15
+ ProxyTorchDispatchMode,
16
+ track_tensor_tree,
17
+ )
18
+
19
+
20
+ class BaseHOP(HigherOrderOperator, abc.ABC):
21
+ """
22
+ This is the "Base" HOP implementation for a HOP that looks like:
23
+
24
+ call_subgraph_hop(subgraph, *operands, **kwargs)
25
+
26
+ That is:
27
+ 1) the HOP stays alive until Inductor
28
+ 2) the HOP's semantics are subgraph(*operands)
29
+ 3) kwargs may be some config options but aren't passed directly to the subgraph.
30
+
31
+ To use this, please subclass this class and override methods as necessary:
32
+ ```
33
+ class InvokeQuant(BaseHOP):
34
+ def __init__(self):
35
+ return super().__init__("invoke_quant")
36
+
37
+ invoke_quant = InvokeQuant()
38
+
39
+ def g(x):
40
+ return x.sin().cos()
41
+
42
+ @torch.compile(backend="aot_eager")
43
+ def f(x):
44
+ return invoke_quant(g, x, scheme="nf4")
45
+ ```
46
+
47
+ NOTE: don't subclass BaseHOP out of tree! That is not allowed. All
48
+ usages must be in tree.
49
+ """
50
+
51
+ def __init__(self, hop_name) -> None:
52
+ super().__init__(hop_name)
53
+
54
+ # Set up the registrations
55
+ # If you want to override any of these, override them in your subclass.
56
+ self.py_impl(DispatchKey.Autograd)(self._call_Autograd)
57
+ self.py_functionalize_impl(self._call_Functionalize)
58
+ self.py_impl(ProxyTorchDispatchMode)(self._call_ProxyTorchDispatchMode)
59
+ self.py_impl(FakeTensorMode)(self._call_FakeTensorMode)
60
+ self.py_impl(DispatchKey.CompositeExplicitAutograd)(
61
+ self._call_CompositeExplicitAutograd
62
+ )
63
+
64
+ def __call__(self, subgraph, *operands, **kwargs):
65
+ if not isinstance(subgraph, (torch.fx.GraphModule, FunctionWithNoFreeVars)):
66
+ raise RuntimeError(
67
+ f"{self._name}: when calling this API without torch.compile, "
68
+ f"we require that the subgraph be a torch.fx.GraphModule (or "
69
+ f"a function we know doesn't have free variables)."
70
+ )
71
+ return super().__call__(subgraph, *operands, **kwargs)
72
+
73
+ def _call_Autograd(self, subgraph, *operands, **kwargs):
74
+ if isinstance(subgraph, torch.fx.GraphModule):
75
+ pass
76
+ if not torch.is_grad_enabled() or pytree.tree_all_only(
77
+ torch.Tensor,
78
+ lambda t: not t.requires_grad, # type: ignore[union-attr]
79
+ operands,
80
+ ):
81
+ with torch._C._AutoDispatchBelowAutograd():
82
+ return self(subgraph, *operands, **kwargs)
83
+
84
+ # We assume the subgraph doesn't mutate inputs and there is no aliasing.
85
+ # In the PT2 stack, this is Dynamo's responsibility to figure out.
86
+ return BaseHOPFunction.apply(self, subgraph, kwargs, *operands)
87
+
88
+ def _call_CompositeExplicitAutograd(self, subgraph, *operands, **kwargs):
89
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
90
+
91
+ mode = _get_current_dispatch_mode()
92
+ assert mode is None, "Mode should never be enabled for CPU/CUDA key"
93
+ return subgraph(*operands)
94
+
95
+ def _call_ProxyTorchDispatchMode(self, proxy_mode, subgraph, *operands, **kwargs):
96
+ traced_graph = reenter_make_fx(subgraph)(*operands)
97
+ assert isinstance(proxy_mode.tracer, torch.fx.Tracer)
98
+ qualname = proxy_mode.tracer.get_fresh_qualname("subgraph")
99
+ proxy_mode.tracer.root.register_module(qualname, traced_graph)
100
+
101
+ node_args = (traced_graph, *operands)
102
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[attr-defined]
103
+ proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[attr-defined]
104
+ out_proxy = proxy_mode.tracer.create_proxy(
105
+ "call_function", self, proxy_args, proxy_kwargs
106
+ )
107
+
108
+ out = self(subgraph, *operands, **kwargs)
109
+ return track_tensor_tree(
110
+ out, out_proxy, constant=None, tracer=proxy_mode.tracer # type: ignore[arg-type]
111
+ )
112
+
113
+ def _call_FakeTensorMode(self, mode, subgraph, *operands, **kwargs):
114
+ # TODO: this should probably route through FakeTensorMode to reuse caching
115
+ with mode:
116
+ return subgraph(*operands)
117
+
118
+ def _call_Functionalize(self, ctx, subgraph, *operands, **kwargs):
119
+ unwrapped_operands = ctx.unwrap_tensors(operands)
120
+ with ctx.redispatch_to_next():
121
+ # We assume the subgraph doesn't mutate inputs and there is no aliasing.
122
+ # In the PT2 stack, this is Dynamo's responsibility to figure out.
123
+ functionalized_subgraph = FunctionWithNoFreeVars(
124
+ ctx.functionalize(subgraph)
125
+ )
126
+ out = self(functionalized_subgraph, *unwrapped_operands, **kwargs)
127
+ return ctx.wrap_tensors(out)
128
+
129
+
130
+ class BaseHOPFunction(torch.autograd.Function):
131
+ @staticmethod
132
+ def forward(ctx, hop, subgraph, kwargs, *operands):
133
+ ctx.hop = hop
134
+ ctx.operands = operands
135
+ ctx.subgraph = subgraph
136
+ ctx.kwargs = kwargs
137
+
138
+ with torch._C._AutoDispatchBelowAutograd():
139
+ return hop(subgraph, *operands, **kwargs)
140
+
141
+ @staticmethod
142
+ def backward(ctx, *grad_outputs):
143
+ subgraph = ctx.subgraph
144
+ operands = ctx.operands
145
+ kwargs = ctx.kwargs
146
+
147
+ # TODO: Something special needs to happen with min cut partitioner
148
+ with suspend_functionalization(), disable_functional_mode(), torch.enable_grad():
149
+ with disable_proxy_modes_tracing():
150
+ from .invoke_subgraph import create_fw_bw_graph
151
+ from .utils import _from_fun
152
+
153
+ fw_inputs = pytree.tree_map(_from_fun, operands)
154
+ _, joint_graph, _ = create_fw_bw_graph(
155
+ subgraph, fw_inputs, grad_outputs
156
+ )
157
+
158
+ # The joint graph returns (*grad_inputs, *fwd_outputs).
159
+ # We only need the grad_inputs.
160
+ def bwd_fn(*args):
161
+ operands = args[: -len(grad_outputs)]
162
+ grad_outs = args[-len(grad_outputs) :]
163
+ result = joint_graph(*operands, *grad_outs)
164
+ grad_inputs = result[: -len(grad_outputs)]
165
+ return grad_inputs
166
+
167
+ return (
168
+ None,
169
+ None,
170
+ None,
171
+ *ctx.hop(
172
+ FunctionWithNoFreeVars(bwd_fn), *operands, *grad_outputs, **kwargs
173
+ ),
174
+ )
175
+
176
+
177
+ class FunctionWithNoFreeVars:
178
+ def __init__(self, fn):
179
+ self.fn = fn
180
+
181
+ def __call__(self, *args, **kwargs):
182
+ return self.fn(*args, **kwargs)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/cond.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import contextlib
4
+ import logging
5
+ import warnings
6
+ from typing import Any, Callable, Optional, Union
7
+
8
+ import torch
9
+ import torch._subclasses.functional_tensor
10
+ import torch.utils._pytree as pytree
11
+ from torch._C import DispatchKey
12
+ from torch._C._functorch import (
13
+ _add_batch_dim,
14
+ get_unwrapped,
15
+ is_batchedtensor,
16
+ maybe_get_bdim,
17
+ )
18
+ from torch._dispatch.python import suspend_functionalization
19
+ from torch._functorch.utils import exposed_in
20
+ from torch._higher_order_ops.utils import (
21
+ _has_potential_branch_input_alias,
22
+ _has_potential_branch_input_mutation,
23
+ _maybe_run_with_interpreter,
24
+ _set_compilation_env,
25
+ reenter_make_fx,
26
+ save_tensors_and_symints_for_backward,
27
+ saved_tensors_and_symints,
28
+ unique_graph_id,
29
+ UnsupportedAliasMutationException,
30
+ validate_subgraph_args_types,
31
+ )
32
+ from torch._ops import HigherOrderOperator
33
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
34
+ from torch._subclasses.functional_tensor import disable_functional_mode
35
+ from torch.fx.experimental.proxy_tensor import (
36
+ _temp_remove_metadata_torch_function_mode,
37
+ _temp_remove_pre_dispatch_torch_function_mode,
38
+ disable_proxy_modes_tracing,
39
+ ProxyTorchDispatchMode,
40
+ track_tensor_tree,
41
+ )
42
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
43
+
44
+ from .utils import _from_fun, _maybe_fake_prop_ignore_unbacked, create_fw_bw_graph
45
+
46
+
47
+ log = logging.getLogger(__name__)
48
+
49
+ """
50
+ We're going to define a `cond_op` operation.
51
+ In order to do this, we need implementations for each of the dispatch keys.
52
+ """
53
+
54
+
55
+ class CondOp(HigherOrderOperator):
56
+ def __init__(self):
57
+ super().__init__("cond")
58
+
59
+ def __call__(self, pred, true_fn, false_fn, operands):
60
+ validate_subgraph_args_types(operands)
61
+ return super().__call__(pred, true_fn, false_fn, operands)
62
+
63
+
64
+ cond_op = CondOp()
65
+
66
+
67
+ @exposed_in("torch")
68
+ def cond(
69
+ pred: Union[bool, int, float, torch.Tensor],
70
+ true_fn: Callable,
71
+ false_fn: Callable,
72
+ operands: Union[tuple, list] = (),
73
+ ) -> Any:
74
+ r"""
75
+ Conditionally applies `true_fn` or `false_fn`.
76
+
77
+ .. warning::
78
+ `torch.cond` is a prototype feature in PyTorch. It has limited support for input and output types and
79
+ doesn't support training currently. Please look forward to a more stable implementation in a future version of PyTorch.
80
+ Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
81
+
82
+ `cond` is structured control flow operator. That is, it is like a Python if-statement,
83
+ but has restrictions on `true_fn`, `false_fn`, and `operands` that enable it to be
84
+ capturable using torch.compile and torch.export.
85
+
86
+ Assuming the constraints on `cond`'s arguments are met, `cond` is equivalent to the following::
87
+
88
+ def cond(pred, true_branch, false_branch, operands):
89
+ if pred:
90
+ return true_branch(*operands)
91
+ else:
92
+ return false_branch(*operands)
93
+
94
+ Args:
95
+ pred (Union[bool, torch.Tensor]): A boolean expression or a tensor with one element,
96
+ indicating which branch function to apply.
97
+
98
+ true_fn (Callable): A callable function (a -> b) that is within the
99
+ scope that is being traced.
100
+
101
+ false_fn (Callable): A callable function (a -> b) that is within the
102
+ scope that is being traced. The true branch and false branch must
103
+ have consistent input and outputs, meaning the inputs have to be
104
+ the same, and the outputs have to be the same type and shape.
105
+
106
+ operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): A tuple of inputs to the
107
+ true/false functions. It can be empty if true_fn/false_fn doesn't require input. Defaults to ().
108
+
109
+ Example::
110
+
111
+ def true_fn(x: torch.Tensor):
112
+ return x.cos()
113
+ def false_fn(x: torch.Tensor):
114
+ return x.sin()
115
+ return cond(x.shape[0] > 4, true_fn, false_fn, (x,))
116
+
117
+ Restrictions:
118
+ - The conditional statement (aka `pred`) must meet one of the following constraints:
119
+
120
+ - It's a `torch.Tensor` with only one element, and torch.bool dtype
121
+
122
+ - It's a boolean expression, e.g. `x.shape[0] > 10` or `x.dim() > 1 and x.shape[1] > 10`
123
+
124
+ - The branch function (aka `true_fn`/`false_fn`) must meet all of the following constraints:
125
+
126
+ - The function signature must match with operands.
127
+
128
+ - The function must return a tensor with the same metadata, e.g. shape,
129
+ dtype, etc.
130
+
131
+ - The function cannot have in-place mutations on inputs or global variables.
132
+ (Note: in-place tensor operations such as `add_` for intermediate results
133
+ are allowed in a branch)
134
+
135
+ """
136
+ if torch.compiler.is_dynamo_compiling():
137
+ return cond_op(pred, true_fn, false_fn, operands)
138
+
139
+ from torch._dynamo.backends.debugging import (
140
+ make_eager_backend_with_torch_function_mode,
141
+ )
142
+
143
+ if isinstance(pred, (bool, int, float)):
144
+ # This is the non-strict export case. Strict export and torch.compile are
145
+ # handled above in dynamo.
146
+ if torch.compiler.is_compiling():
147
+ warnings.warn(
148
+ "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches."
149
+ " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.",
150
+ UserWarning,
151
+ )
152
+ # This is the eager case. We can just run the true or false branch.
153
+ if pred:
154
+ return true_fn(*operands)
155
+ else:
156
+ return false_fn(*operands)
157
+
158
+ def _validate_input(pred, true_fn, false_fn, operands):
159
+ if not isinstance(pred, (bool, torch.Tensor, torch.SymBool)):
160
+ raise RuntimeError(f"Expected pred to be bool or tensor, but got {pred}.")
161
+
162
+ if isinstance(pred, torch.Tensor) and pred.numel() != 1:
163
+ raise RuntimeError(
164
+ f"Expected pred to be bool or single-element tensor, but got {pred}."
165
+ )
166
+
167
+ if not callable(true_fn) or not callable(false_fn):
168
+ raise RuntimeError("Expect both branches to be callable.")
169
+
170
+ if not isinstance(operands, (tuple, list)) or pytree.tree_any(
171
+ lambda t: not isinstance(t, torch.Tensor), operands
172
+ ):
173
+ raise RuntimeError(
174
+ "Expect operands to be a tuple of possibly nested dict/list/tuple that only "
175
+ f"consists of tensor leaves, but got {operands}."
176
+ )
177
+
178
+ _validate_input(pred, true_fn, false_fn, operands)
179
+
180
+ if not torch._dynamo.is_dynamo_supported():
181
+ raise RuntimeError("torch.cond requires dynamo support.")
182
+
183
+ # Dynamo is expecting a callable with "__code__" attribute.
184
+ # We cannot directly pass cond_op to it. So we wrap it in a dummy function.
185
+ def _cond_op_wrapper(*args, **kwargs):
186
+ return cond_op(*args, **kwargs)
187
+
188
+ with _set_compilation_env(), torch._dynamo.utils.disable_cache_limit(), _temp_remove_pre_dispatch_torch_function_mode():
189
+ with _temp_remove_metadata_torch_function_mode() as metadata_mode:
190
+ if metadata_mode:
191
+ backend = make_eager_backend_with_torch_function_mode(metadata_mode)
192
+ else:
193
+ backend = "eager"
194
+ return torch.compile(_cond_op_wrapper, backend=backend, fullgraph=True)(
195
+ pred, true_fn, false_fn, operands
196
+ )
197
+
198
+
199
+ def create_fw_bw_graph_branches(true_fn, false_fn, *operands):
200
+ # See Note [HOP create fw_bw graph] in create_fw_bw_graph in utils.py
201
+
202
+ with suspend_functionalization(), disable_functional_mode():
203
+ with disable_proxy_modes_tracing():
204
+ fw_inputs = pytree.tree_map(_from_fun, operands)
205
+
206
+ fw_outputs_true = pytree.tree_map(
207
+ _from_fun, _maybe_fake_prop_ignore_unbacked(true_fn, fw_inputs)
208
+ )
209
+ if any(
210
+ not isinstance(out, torch.Tensor)
211
+ for out in fw_outputs_true
212
+ if out is not None
213
+ ):
214
+ raise RuntimeError(
215
+ "Expect outputs of true_fn to only contains tensors or None. "
216
+ f"Got types {[type(out) for out in fw_outputs_true]}."
217
+ )
218
+ fw_outputs_false = pytree.tree_map(
219
+ _from_fun, _maybe_fake_prop_ignore_unbacked(false_fn, fw_inputs)
220
+ )
221
+ if any(
222
+ not isinstance(out, torch.Tensor)
223
+ for out in fw_outputs_false
224
+ if out is not None
225
+ ):
226
+ raise RuntimeError(
227
+ "Expect outputs of false_fn to only contains tensors or None. "
228
+ f"Got types {[type(out) for out in fw_outputs_false]}."
229
+ )
230
+
231
+ # TODO: There is a major issue that the create_fw_bw in the higher_order_op is invoked twice:
232
+ # Once in the forward path (as it should) and once in the backward path, where it shouldn't be called
233
+ # If we can get rid of the second invokation, it would simplify this function
234
+ fw_true_graph, joint_true_graph = create_fw_bw_graph(
235
+ true_fn, False, fw_inputs, fw_outputs_true
236
+ )
237
+ fw_false_graph, joint_false_graph = create_fw_bw_graph(
238
+ false_fn, False, fw_inputs, fw_outputs_false
239
+ )
240
+
241
+ return fw_true_graph, fw_false_graph, joint_true_graph, joint_false_graph
242
+
243
+
244
+ def trace_cond(proxy_mode, func_overload, pred, true_fn, false_fn, operands):
245
+ assert isinstance(
246
+ operands, (list, tuple)
247
+ ), f"Cond operands must be a list or tuple of tensors and SymInts {operands}"
248
+
249
+ true_graph = reenter_make_fx(true_fn)(*operands)
250
+ false_graph = reenter_make_fx(false_fn)(*operands)
251
+
252
+ true_outs = []
253
+ false_outs = []
254
+ for node in true_graph.graph.nodes:
255
+ if node.op == "output":
256
+ true_outs.extend(node.args)
257
+
258
+ for node in false_graph.graph.nodes:
259
+ if node.op == "output":
260
+ false_outs.extend(node.args)
261
+
262
+ flat_true_outs = pytree.arg_tree_leaves(*true_outs)
263
+ flat_false_outs = pytree.arg_tree_leaves(*false_outs)
264
+ if len(flat_true_outs) != len(flat_false_outs):
265
+ raise torch._dynamo.exc.CondOpArgsMismatchError(
266
+ f"Expected to return same number of outputs but got:"
267
+ f"\n true branch returns {len(flat_true_outs)} item(s)"
268
+ f"\n false branch returns {len(flat_false_outs)} item(s)"
269
+ )
270
+
271
+ i, true_name = unique_graph_id(proxy_mode, prefix="true_graph")
272
+
273
+ false_name = f"false_graph_{i}"
274
+ assert not hasattr(proxy_mode.tracer.root, false_name)
275
+
276
+ proxy_mode.tracer.root.register_module(true_name, true_graph)
277
+ proxy_mode.tracer.root.register_module(false_name, false_graph)
278
+
279
+ args = (pred, true_graph, false_graph, operands)
280
+
281
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
282
+
283
+ out_proxy = proxy_mode.tracer.create_proxy(
284
+ "call_function", func_overload, proxy_args, {}
285
+ )
286
+
287
+ out = func_overload(pred, true_graph, false_graph, operands)
288
+
289
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
290
+
291
+
292
+ @cond_op.py_impl(DispatchKey.CompositeExplicitAutograd)
293
+ def cond_op_dense(pred, true_fn, false_fn, operands):
294
+ assert all(
295
+ isinstance(o, (torch.Tensor, int)) for o in operands
296
+ ), f"Dense implementation operands must be a list of tensors and ints {operands}"
297
+ mode = _get_current_dispatch_mode()
298
+ assert mode is None, "Mode should never be enabled for CPU/CUDA key"
299
+ if pred:
300
+ return true_fn(*operands)
301
+ else:
302
+ return false_fn(*operands)
303
+
304
+
305
+ class CondAutogradOp(torch.autograd.Function):
306
+ @staticmethod
307
+ def forward(
308
+ ctx,
309
+ pred,
310
+ fw_true_graph,
311
+ fw_false_graph,
312
+ joint_true_graph,
313
+ joint_false_graph,
314
+ *operands,
315
+ ):
316
+ ctx._pred = pred
317
+ ctx._joint_true_graph = joint_true_graph
318
+ ctx._joint_false_graph = joint_false_graph
319
+ save_tensors_and_symints_for_backward(ctx, operands)
320
+
321
+ with torch._C._AutoDispatchBelowAutograd():
322
+ return cond_op(pred, fw_true_graph, fw_false_graph, operands)
323
+
324
+ @staticmethod
325
+ def backward(ctx, *flat_grads):
326
+ operands = saved_tensors_and_symints(ctx)
327
+
328
+ grads = cond_op(
329
+ ctx._pred,
330
+ ctx._joint_true_graph,
331
+ ctx._joint_false_graph,
332
+ flat_grads + operands,
333
+ )
334
+ return None, None, None, None, None, *grads
335
+
336
+
337
+ @cond_op.py_impl(DispatchKey.Autograd)
338
+ def cond_autograd(pred, true_fn, false_fn, operands):
339
+ # A shortcut for the case where all inputs don't require gradient,
340
+ # we skip tracing the forward and backward graph.
341
+ if pytree.tree_all_only(
342
+ torch.Tensor,
343
+ lambda t: not t.requires_grad, # type: ignore[union-attr]
344
+ (pred, operands),
345
+ ):
346
+ with torch._C._AutoDispatchBelowAutograd():
347
+ return cond_op(pred, true_fn, false_fn, operands)
348
+
349
+ (
350
+ fw_true_graph,
351
+ fw_false_graph,
352
+ joint_true_graph,
353
+ joint_false_graph,
354
+ ) = create_fw_bw_graph_branches(true_fn, false_fn, *operands)
355
+ flat_out = CondAutogradOp.apply(
356
+ pred,
357
+ fw_true_graph,
358
+ fw_false_graph,
359
+ joint_true_graph,
360
+ joint_false_graph,
361
+ *operands,
362
+ )
363
+ return flat_out
364
+
365
+
366
+ @cond_op.py_impl(ProxyTorchDispatchMode)
367
+ def inner(mode, pred, true_fn, false_fn, operands):
368
+ return trace_cond(mode, cond_op, pred, true_fn, false_fn, operands)
369
+
370
+
371
+ @cond_op.py_impl(FakeTensorMode)
372
+ def cond_fake_tensor_mode(mode, pred, true_fn, false_fn, operands):
373
+ # Ignore here, because if you've gotten here but you're not manually
374
+ # tracing the inner graphs, that means that you intend to reuse the graph
375
+ # directly. Which means the old unbacked symbol bindings are appropriate.
376
+ # This strategy will not work if unbacked symbols can escape.
377
+ ignore_fresh_unbacked = contextlib.nullcontext()
378
+ if mode.shape_env:
379
+ ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols()
380
+
381
+ with mode, ignore_fresh_unbacked:
382
+ flat_true_outs, true_out_spec = pytree.tree_flatten(true_fn(*operands))
383
+ flat_false_outs, false_out_spec = pytree.tree_flatten(false_fn(*operands))
384
+ if true_out_spec != false_out_spec:
385
+ raise RuntimeError(
386
+ "Unmatched output spec from torch.cond branches: "
387
+ f"true branch tree_spec {true_out_spec} vs false branch tree_spec {false_out_spec}."
388
+ )
389
+
390
+ merged_outs = []
391
+ for true_out, false_out in zip(flat_true_outs, flat_false_outs):
392
+ merged_outs.append(_merge_tensors(true_out, false_out, mode))
393
+ return pytree.tree_unflatten(merged_outs, true_out_spec)
394
+
395
+
396
+ def check_tensor_meta_match(
397
+ t1: torch.Tensor, t2: torch.Tensor, attr_names: tuple[str, ...], msg_prefix: str
398
+ ) -> None:
399
+ def _get_attr_maybe_call(t: torch.Tensor, attr_name: str) -> Any:
400
+ attr = getattr(t, attr_name)
401
+ if callable(attr):
402
+ return attr()
403
+ return attr
404
+
405
+ for attr_name in attr_names:
406
+ lattr = _get_attr_maybe_call(t1, attr_name)
407
+ rattr = _get_attr_maybe_call(t2, attr_name)
408
+ torch._check(
409
+ lattr == rattr,
410
+ lambda: f"{msg_prefix} expected same {attr_name} but got {lattr} and {rattr}.",
411
+ )
412
+
413
+
414
+ def _merge_tensors(
415
+ a: Optional[torch.Tensor], b: Optional[torch.Tensor], mode: FakeTensorMode
416
+ ):
417
+ from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr
418
+
419
+ if a is None or b is None:
420
+ assert a is None and b is None, (a, b)
421
+ return None
422
+
423
+ assert type(a) is FakeTensor and type(b) is FakeTensor, (a, type(a), b, type(b))
424
+
425
+ # Note: we don't check size, stride because
426
+ # they'll be merged with unbacked symints if they differ.
427
+ _meta_to_check = {
428
+ "dtype",
429
+ "device",
430
+ "layout",
431
+ "dim",
432
+ "is_quantized",
433
+ "is_conj",
434
+ "is_sparse",
435
+ "storage_offset",
436
+ }
437
+ check_tensor_meta_match(
438
+ a,
439
+ b,
440
+ tuple(_meta_to_check),
441
+ msg_prefix="When merging two branches' output in torch.cond, ",
442
+ )
443
+ # NYI
444
+ assert not a.is_quantized and not b.is_quantized
445
+ assert not a.is_sparse and not b.is_sparse
446
+ assert not a.is_conj() and not b.is_conj()
447
+
448
+ """
449
+ Step 1: create unbacked symints for sizes that are different
450
+ along the same axis. For example:
451
+ a.size is [s0, 4, s0, 5, 4, 5]
452
+ b.size is [s1, 4, s2, 8, 4, 7]
453
+ merged_size will be [u0, 4, u1, u2, 4, u3], where
454
+ u0 has range [min(s0, s1), max(s0, s1)]
455
+ u1 has range [min(s0, s2), max(s0, s2)]
456
+ u2 has range [5, 8]
457
+ u3 has range [5, 7]
458
+ """
459
+ merged_size: list[Union[int, torch.SymInt]] = []
460
+ for s0, s1 in zip(a.size(), b.size()):
461
+ if SymIntEqByExpr(s0) == SymIntEqByExpr(s1):
462
+ merged_size.append(s0)
463
+ else:
464
+
465
+ def min_max(s0, s1):
466
+ def _bound(s0, lower_bound: bool):
467
+ if isinstance(s0, int):
468
+ return s0
469
+ r = mode.shape_env.var_to_range.get( # type: ignore[union-attr]
470
+ s0.node.expr,
471
+ torch.utils._sympy.value_ranges.ValueRanges.unknown(),
472
+ )
473
+ return r.lower if lower_bound else r.upper
474
+
475
+ return min(_bound(s0, True), _bound(s1, True)), max(
476
+ _bound(s0, False), _bound(s1, False)
477
+ )
478
+
479
+ assert mode.shape_env is not None
480
+ new_size = mode.shape_env.create_unbacked_symint()
481
+ mode.shape_env.constrain_symbol_range(new_size.node.expr, *min_max(s0, s1))
482
+ merged_size.append(new_size)
483
+
484
+ """
485
+ This follows the logic in symbolic_shapes._compute_symbolic_stride
486
+ Step 2: Since tensor stride is an accumulative muliplication of the sizes, which is a permutated
487
+ (due to view ops) non-decending sequence.
488
+
489
+ Case 1: No size is 1. In this case, strides have unique values.
490
+ For example, suppose we have a tenosr with:
491
+ size [3, 4, 3, 5, 4, 5],
492
+ stride (1200, 300, 1, 12, 3, 60),
493
+ merged_size [u0, u1, u2, u3, u4, u5].
494
+
495
+ We visit the strides in ascending order: 1, 3, 12, 60, 300, 1200. In each step, we check whether
496
+ the current stride is bounded or not and bound next stride by setting.
497
+ stride_expr[next_stride] = current_stride_expr * current_size_expr
498
+ 1st round:
499
+ current_stride is 1, current_size is 3, so next_stride is 1 * 3 = 3,
500
+ current_stride_expr is set to 1, current_size_expr is u2, so stride_expr[3] is therefore 1 * u2 = u2
501
+ 2nd round:
502
+ current_stride is 3, current_size is 4, so next_stride is 3 * 4 = 12,
503
+ current_stride_expr is stride_expr[3] i.e. u2, current_size_expr is u4, so stride_expr[12] = u2 * u4
504
+ ...
505
+
506
+ Case 2: At least one dimension has size 1, which can produce duplicates in strides.
507
+ In this case, theorectically, we cannot uniquely determine the expr of strides because
508
+ the accessing stride_expr with same key in different order causes the final stride expression
509
+ to be different.
510
+
511
+ Suppose we have:
512
+ size: (3, 1)
513
+ stride: (1, 1)
514
+ merged_size: (u0, u1)
515
+
516
+ The stride expr could either be (u1, 1) or (1, u0) depending on whether we start with u1 or u0.
517
+ For this reason, we try to break tie by sorting via decending index so we always get (u1, 1).
518
+
519
+ Note that backend might optimize the strides anyway so this is usually not a problem as long
520
+ as two branches matches. See relevant discussions in https://github.com/pytorch/pytorch/issues/142024.
521
+
522
+ Case 3: Dim has 0 stride. 0 stride doesn't participate in the accumulative multiplication of
523
+ sizes. So they're always treated as constant even if their corresponding size is turned into unbacked symint.
524
+
525
+ Suppose we have:
526
+ size: (3, 3)
527
+ stride: (0, 1)
528
+ merged_size: (u0, u1)
529
+
530
+ The merged stride would be (0, 1)
531
+ """
532
+
533
+ def _bound_stride(
534
+ a_ex_size: torch.Size,
535
+ b_ex_size: torch.Size,
536
+ a_ex_stride: tuple[int, ...],
537
+ b_ex_stride: tuple[int, ...],
538
+ merged_size: list[Union[int, torch.SymInt]],
539
+ ) -> list[Union[int, torch.SymInt]]:
540
+ from torch._inductor.ir import get_stride_order
541
+
542
+ a_sorted_stride_idx = get_stride_order(a_ex_stride, mode.shape_env)
543
+ b_sorted_stride_idx = get_stride_order(b_ex_stride, mode.shape_env)
544
+
545
+ a_stride_li: list[Optional[tuple[Union[int, torch.SymInt], int]]] = [
546
+ None
547
+ ] * len(a_ex_stride)
548
+ b_stride_li: list[Optional[tuple[Union[int, torch.SymInt], int]]] = [
549
+ None
550
+ ] * len(b_ex_stride)
551
+ for i, idx in enumerate(a_sorted_stride_idx):
552
+ a_stride_li[idx] = (a_ex_stride[i], -i)
553
+ for i, idx in enumerate(b_sorted_stride_idx):
554
+ b_stride_li[idx] = (b_ex_stride[i], -i)
555
+
556
+ for a_pair, b_pair in zip(a_stride_li, b_stride_li):
557
+ assert a_pair is not None and b_pair is not None
558
+ _, a_idx = a_pair
559
+ _, b_idx = b_pair
560
+
561
+ if a_idx != b_idx:
562
+ raise RuntimeError(
563
+ f"The sorted order of strides of the two branches' output doesn't match."
564
+ f"this indicates the contiguousness of the two branches are different. "
565
+ f"True branch has stride {a_ex_stride} but false branch has stride {b_ex_stride}."
566
+ f"Consider using contiguous() to make the two branches have the same contiguousness."
567
+ )
568
+
569
+ def _maybe_expr(s: Union[int, torch.SymInt]):
570
+ if isinstance(s, int):
571
+ return s
572
+ return s.node.expr
573
+
574
+ a_stride_expr: dict[Any, Union[int, torch.SymInt]] = {}
575
+ b_stride_expr: dict[Any, Union[int, torch.SymInt]] = {}
576
+ merged_strides: list[Union[int, torch.SymInt]] = [None] * len(a_ex_stride) # type: ignore[list-item]
577
+ for a_pair, b_pair in zip(a_stride_li, b_stride_li):
578
+ assert a_pair is not None and b_pair is not None
579
+ a_val, neg_i = a_pair
580
+ b_val, _ = b_pair
581
+
582
+ i = -neg_i
583
+ if a_val == 0:
584
+ assert b_val == 0, (a_val, b_val)
585
+ merged_strides[i] = 0
586
+ continue
587
+
588
+ if _maybe_expr(a_val) in a_stride_expr:
589
+ a_expr = a_stride_expr[_maybe_expr(a_val)]
590
+ assert (
591
+ b_stride_expr[_maybe_expr(b_val)] == a_expr
592
+ ), f"a_stride_expr:{a_stride_expr}, b_stride_expr:{b_stride_expr}"
593
+ merged_strides[i] = a_expr
594
+ else:
595
+ if a_val == 1:
596
+ assert b_val == 1
597
+ a_stride_expr[_maybe_expr(a_val)] = 1
598
+ b_stride_expr[_maybe_expr(b_val)] = 1
599
+ merged_strides[i] = 1
600
+ else:
601
+ # If we cannot find the expr of a_val in a_stride_expr, it means
602
+ # the strides is not a simple accumulative multiplication of sizes.
603
+ # In this case, we cannot determine the expr of strides from the new
604
+ # shapes so we error out and hint users to call contiguous().
605
+ raise RuntimeError(
606
+ f"It seems one of cond's output stride is not a simple accumulative multiplication of sizes. "
607
+ f"This could be because cond returns a slice of a tensor, which is not dense in memory. "
608
+ f"True branch has size {a_ex_size}, stride {a_ex_stride} and false branch has size {b_ex_size} "
609
+ f"stride {b_ex_stride}. Hint: can call t.contiguous(). "
610
+ )
611
+ nxt_merged_stride_expr = merged_strides[i] * merged_size[i]
612
+ a_stride_expr[_maybe_expr(a_val * a_ex_size[i])] = nxt_merged_stride_expr
613
+ b_stride_expr[_maybe_expr(b_val * b_ex_size[i])] = nxt_merged_stride_expr
614
+ return merged_strides
615
+
616
+ merged_stride: list[Union[int, torch.SymInt]] = _bound_stride(
617
+ a.size(), b.size(), a.stride(), b.stride(), merged_size
618
+ )
619
+
620
+ with mode:
621
+ return torch.empty_strided(
622
+ merged_size, merged_stride, dtype=a.dtype, device=a.device
623
+ )
624
+
625
+
626
+ @cond_op.py_functionalize_impl
627
+ def cond_func(ctx, pred, true_fn, false_fn, inputs):
628
+ unwrapped_inputs = ctx.unwrap_tensors(inputs)
629
+ unwrapped_pred = ctx.unwrap_tensors(pred)
630
+ with ctx.redispatch_to_next():
631
+ functional_true = ctx.functionalize(_maybe_run_with_interpreter(true_fn))
632
+ functional_false = ctx.functionalize(_maybe_run_with_interpreter(false_fn))
633
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
634
+ for branch in [true_fn, false_fn]:
635
+ if _has_potential_branch_input_mutation(
636
+ branch, unwrapped_inputs, pre_dispatch=pre_dispatch
637
+ ):
638
+ raise UnsupportedAliasMutationException(
639
+ "One of torch.cond branch might be modifying the input! "
640
+ "Consider cloning the input before modifying it. "
641
+ )
642
+ for branch in [true_fn, false_fn]:
643
+ if _has_potential_branch_input_alias(
644
+ branch, unwrapped_inputs, pre_dispatch=pre_dispatch
645
+ ):
646
+ raise UnsupportedAliasMutationException(
647
+ "One of torch.cond branch might be aliasing the input! "
648
+ "If you are returning a view of the input, please make sure "
649
+ "to clone it. "
650
+ )
651
+
652
+ cond_return = cond_op(
653
+ unwrapped_pred, functional_true, functional_false, unwrapped_inputs
654
+ )
655
+ return ctx.wrap_tensors(cond_return)
656
+
657
+
658
+ @cond_op.py_impl(torch._C._functorch.TransformType.Vmap)
659
+ def cond_batch_rule(interpreter, pred, true_fn, false_fn, inputs):
660
+ assert isinstance(
661
+ inputs, (list, tuple)
662
+ ), "Cond inputs must be a list or tuple of tensors"
663
+ assert all(
664
+ isinstance(i, torch.Tensor) for i in inputs
665
+ ), "Cond inputs must be a list of tensors"
666
+
667
+ pred_is_batched = isinstance(pred, torch.Tensor) and is_batchedtensor(pred)
668
+ pred_ = get_unwrapped(pred) if pred_is_batched else pred
669
+
670
+ # unbatched tensors are not vmapped
671
+ tensors, in_dims = zip(
672
+ *[
673
+ (get_unwrapped(t), maybe_get_bdim(t)) if is_batchedtensor(t) else (t, None)
674
+ for t in inputs
675
+ ]
676
+ )
677
+
678
+ if pred_is_batched:
679
+ # prepend "pred" and vmap everything
680
+ tensors = (pred_,) + tensors
681
+ in_dims = (0,) + in_dims
682
+
683
+ def fn(p, *args):
684
+ t = true_fn(*args)
685
+ f = false_fn(*args)
686
+ return torch.where(p, t[0], f[0])
687
+
688
+ with interpreter.lower():
689
+ result = torch.vmap(fn, in_dims=in_dims)(*tensors)
690
+
691
+ else:
692
+ # predicate is known at this stage and it is a boolean expression or a
693
+ # tensor with one element.
694
+ true_fn = torch.vmap(true_fn, in_dims=in_dims)
695
+ false_fn = torch.vmap(false_fn, in_dims=in_dims)
696
+
697
+ with interpreter.lower():
698
+ result = cond_op(pred, true_fn, false_fn, tensors)
699
+
700
+ if not isinstance(result, tuple):
701
+ result = (result,)
702
+ lvl = interpreter.level()
703
+ return tuple([_add_batch_dim(r, 0, lvl) for r in result])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/effects.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from enum import Enum
3
+ from typing import Any, Optional, Union
4
+ from weakref import WeakKeyDictionary
5
+
6
+ import torch
7
+ import torch.utils._pytree as pytree
8
+ from torch._C import DispatchKey
9
+ from torch._higher_order_ops.torchbind import call_torchbind
10
+ from torch._library.fake_class_registry import FakeScriptObject
11
+ from torch._ops import HigherOrderOperator
12
+ from torch._subclasses.fake_tensor import FakeTensorMode
13
+ from torch.fx.experimental.proxy_tensor import (
14
+ disable_proxy_modes_tracing,
15
+ ProxyTorchDispatchMode,
16
+ track_tensor_tree,
17
+ )
18
+
19
+
20
+ class _EffectType(Enum):
21
+ ORDERED = "Ordered"
22
+
23
+
24
+ OpType = Union[torch._ops.HigherOrderOperator, torch._ops.OpOverload]
25
+
26
+
27
+ SIDE_EFFECTS: "WeakKeyDictionary[OpType, _EffectType]" = WeakKeyDictionary(
28
+ {
29
+ torch.ops.aten._print.default: _EffectType.ORDERED,
30
+ call_torchbind: _EffectType.ORDERED,
31
+ }
32
+ )
33
+
34
+
35
+ def _register_effectful_op(op: OpType, effect: _EffectType):
36
+ assert isinstance(
37
+ op, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)
38
+ ) and not has_aliasing(op)
39
+ if op in SIDE_EFFECTS and SIDE_EFFECTS[op] != effect:
40
+ raise RuntimeError(
41
+ f"Already registered effect type {SIDE_EFFECTS[op]} to op {op}, "
42
+ f"trying to register a different effect type {effect}."
43
+ )
44
+ SIDE_EFFECTS[op] = effect
45
+
46
+
47
+ def _deregister_effectful_op(op: OpType):
48
+ if op not in SIDE_EFFECTS:
49
+ raise RuntimeError(f"Op {op} is not registered as effectful")
50
+
51
+ del SIDE_EFFECTS[op]
52
+
53
+
54
+ class WithEffects(HigherOrderOperator):
55
+ """
56
+ with_effects(token, op, args, kwargs) -> (new_token, op_results)
57
+
58
+ This HOP helps ensure ordering between side effectful ops like prints or ops
59
+ using torchbind objects. This is needed to ensure a traced graph from
60
+ AOTAutograd is functional so that future optimization passes do not reorder
61
+ these operators. This is done through threading "effect tokens" through the
62
+ graph to enforce data dependence between side effectful ops.
63
+
64
+ The tokens are basically dummy values (torch.tensor([])). We create a token
65
+ per "effect type", which are enumerated in the _EffectType enum.
66
+ """
67
+
68
+ def __init__(self) -> None:
69
+ super().__init__("with_effects")
70
+
71
+ def __call__(
72
+ self,
73
+ token,
74
+ op: OpType,
75
+ *args: tuple[Any, ...],
76
+ **kwargs: dict[str, Any],
77
+ ) -> tuple[Any, ...]:
78
+ assert isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload))
79
+ assert not has_aliasing(op), "Ops with aliasing is not supported"
80
+ assert has_effects(op, args, kwargs)
81
+ assert isinstance(kwargs, dict)
82
+ return super().__call__(token, op, *args, **kwargs)
83
+
84
+
85
+ with_effects = WithEffects()
86
+
87
+
88
+ def has_aliasing(op: OpType):
89
+ # NOT FOR PUBLIC USE
90
+ if isinstance(op, torch._ops.HigherOrderOperator):
91
+ return op not in SIDE_EFFECTS
92
+
93
+ for arg in op._schema.arguments:
94
+ if arg.alias_info is not None:
95
+ return True
96
+ for arg in op._schema.returns:
97
+ if arg.alias_info is not None:
98
+ return True
99
+ return False
100
+
101
+
102
+ def has_effects(op, args, kwargs) -> bool:
103
+ # Skip over the profiler's RecordFunction as they should not show up in the graph
104
+ _skip_ops = {torch.ops.profiler._record_function_exit._RecordFunction}
105
+ if op in _skip_ops:
106
+ return False
107
+
108
+ return (
109
+ isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload))
110
+ and not has_aliasing(op)
111
+ and get_effect_key(op, args, kwargs) is not None
112
+ )
113
+
114
+
115
+ def get_effect_key(op, args, kwargs) -> Optional[_EffectType]:
116
+ if op in SIDE_EFFECTS:
117
+ return SIDE_EFFECTS[op]
118
+
119
+ for arg in args:
120
+ if isinstance(arg, (torch.ScriptObject, FakeScriptObject)):
121
+ # Add it to the table so that next time we see the same op we don't
122
+ # have to parse through the args again
123
+ SIDE_EFFECTS[op] = _EffectType.ORDERED
124
+ return _EffectType.ORDERED
125
+
126
+ return None
127
+
128
+
129
+ def new_token_tensor() -> torch.Tensor:
130
+ return torch.tensor([])
131
+
132
+
133
+ @with_effects.py_impl(DispatchKey.CompositeExplicitAutograd)
134
+ def with_effects_dense(
135
+ token: torch.Tensor,
136
+ op: torch._ops.OpOverload,
137
+ *args: tuple[Any, ...],
138
+ **kwargs: dict[str, Any],
139
+ ) -> tuple[torch.Tensor, ...]:
140
+ out = op(*args, **kwargs)
141
+ new_token = new_token_tensor()
142
+ if isinstance(out, tuple):
143
+ return (new_token, *out)
144
+ return (new_token, out)
145
+
146
+
147
+ @with_effects.py_impl(FakeTensorMode)
148
+ def with_effects_fake(
149
+ mode,
150
+ token: torch.Tensor,
151
+ op: torch._ops.OpOverload,
152
+ *args: tuple[Any, ...],
153
+ **kwargs: dict[str, Any],
154
+ ) -> tuple[torch.Tensor, ...]:
155
+ with mode:
156
+ result = with_effects_dense(token, op, *args, **kwargs)
157
+ return result
158
+
159
+
160
+ @with_effects.py_impl(ProxyTorchDispatchMode)
161
+ def with_effects_proxy(
162
+ mode,
163
+ token: torch.Tensor,
164
+ op: torch._ops.OpOverload,
165
+ *args: tuple[Any, ...],
166
+ **kwargs: dict[str, Any],
167
+ ) -> tuple[torch.Tensor, ...]:
168
+ with disable_proxy_modes_tracing():
169
+ out = with_effects(token, op, *args, **kwargs)
170
+
171
+ proxy_token = mode.tracer.unwrap_proxy(token)
172
+ proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args)
173
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
174
+
175
+ from torch.fx.node import has_side_effect
176
+
177
+ # To avoid the being DCEed by graph.eliminate_dead_code if they.
178
+ # don't have output or their outputs are not used.
179
+ has_side_effect(op)
180
+
181
+ out_proxy = mode.tracer.create_proxy(
182
+ "call_function",
183
+ with_effects,
184
+ (proxy_token, op, *proxy_args),
185
+ proxy_kwargs,
186
+ )
187
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
188
+ return result
189
+
190
+
191
+ with_effects.fallthrough(DispatchKey.AutogradCPU)
192
+ with_effects.fallthrough(DispatchKey.AutogradCUDA)
193
+
194
+
195
+ def _get_schema(op, args) -> torch.FunctionSchema:
196
+ if isinstance(op, torch._ops.OpOverload):
197
+ return op._schema
198
+ elif op == call_torchbind:
199
+ return getattr(args[0], args[1]).schema
200
+ else:
201
+ raise RuntimeError(f"Unable to get schema for op {op}")
202
+
203
+
204
+ def handle_effects(
205
+ allow_token_discovery: bool,
206
+ tokens: dict[_EffectType, torch.Tensor],
207
+ op: OpType,
208
+ args: tuple[Any, ...],
209
+ kwargs: dict[str, Any],
210
+ ) -> Any:
211
+ """
212
+ Args:
213
+ allow_token_discovery: Whether or not we are discovering tokens. If this
214
+ is true, we will create a token for every side effect type seen that
215
+ does not have a token assigned yet. If this is false, the tokens
216
+ should've all been created ahead of time, so we will error if there is
217
+ no token mapping to every effect type.
218
+
219
+ tokens: Map of effect type to tokens. This is to chain operators of the
220
+ same effects together so that they do not get reordered in later
221
+ optimization passes.
222
+ """
223
+
224
+ # Get a token. We can't do `tokens.get(op, torch.tensor([]))` because
225
+ # this will create an empty tensor during proxy mode tracing if the token
226
+ # doesn't exist. But the tokens should always exist during proxy mode tracing.
227
+ key = get_effect_key(op, args, kwargs)
228
+ assert key is not None
229
+ if key not in tokens:
230
+ assert (
231
+ allow_token_discovery
232
+ ), f"Could not find a token for effect {key} which came from the function {op}"
233
+ proxy_tensor_mode = torch._C._get_dispatch_mode(
234
+ torch._C._TorchDispatchModeKey.PROXY
235
+ )
236
+ if proxy_tensor_mode is not None:
237
+ # If we discovered a new token during tracing, we are in backward.
238
+ # Then we patch the graph, adding additional tangents_token as input to the joint graph.
239
+ tracer = proxy_tensor_mode.tracer
240
+
241
+ from torch.fx.experimental.proxy_tensor import (
242
+ disable_proxy_modes_tracing,
243
+ track_tensor_tree,
244
+ )
245
+
246
+ with disable_proxy_modes_tracing():
247
+ token_tensor = new_token_tensor()
248
+
249
+ token_proxy = proxy_tensor_mode.tracer.create_proxy(
250
+ "placeholder", "tangents_token", (), {}, name="tangents_token"
251
+ )
252
+ track_tensor_tree(token_tensor, token_proxy, constant=None, tracer=tracer)
253
+
254
+ tokens[key] = token_tensor
255
+ else:
256
+ tokens[key] = new_token_tensor()
257
+
258
+ token = tokens[key]
259
+
260
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
261
+
262
+ ctx = PythonFunctionalizeAPI()
263
+
264
+ unwrapped_token = ctx.unwrap_tensors([token])[0]
265
+ unwrapped_args = ctx.unwrap_tensors(args)
266
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type]
267
+ with ctx.redispatch_to_next():
268
+ (new_token, *unwrapped_outs) = with_effects(
269
+ unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs
270
+ )
271
+
272
+ schema = _get_schema(op, unwrapped_args)
273
+ if len(schema.returns) == 0:
274
+ assert unwrapped_outs[0] is None
275
+ unwrapped_outs = None # type: ignore[assignment]
276
+ elif len(schema.returns) == 1:
277
+ assert len(unwrapped_outs) == 1
278
+ unwrapped_outs = unwrapped_outs[0]
279
+ else:
280
+ assert len(unwrapped_outs) == len(schema.returns)
281
+
282
+ # Add the newly created token into the tokens map for a following call to
283
+ # use this token.
284
+ wrapped_token = ctx.wrap_tensors(new_token)
285
+ assert isinstance(wrapped_token, torch.Tensor)
286
+ tokens[key] = wrapped_token
287
+
288
+ return ctx.wrap_tensors(unwrapped_outs)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/executorch_call_delegate.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ # pyre-strict
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, cast
14
+
15
+ import torch
16
+ import torch.utils._pytree as pytree
17
+ from torch._ops import HigherOrderOperator
18
+ from torch._subclasses.fake_tensor import FakeTensorMode
19
+ from torch.fx.experimental.proxy_tensor import (
20
+ disable_proxy_modes_tracing,
21
+ get_proxy_slot,
22
+ ProxyTorchDispatchMode,
23
+ track_tensor_tree,
24
+ )
25
+ from torch.utils._pytree import tree_flatten
26
+
27
+
28
+ class ExecutorchCallDelegate(HigherOrderOperator):
29
+ def __init__(self):
30
+ super().__init__("executorch_call_delegate")
31
+
32
+ def __call__(self, lowered_module, *args):
33
+ return super().__call__(lowered_module, *args)
34
+
35
+
36
+ executorch_call_delegate = ExecutorchCallDelegate()
37
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
38
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
39
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
40
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
41
+
42
+ LOWERED_BACKEND_MODULE_TYPE = "LoweredBackendModule"
43
+
44
+
45
+ # pyre-ignore
46
+ def trace_call_delegate(proxy_mode, func_overload, lowered_module, *args):
47
+ # pyre-ignore
48
+ def _unwrap_proxy(e):
49
+ if not isinstance(e, (torch.Tensor, torch.SymInt, torch.SymFloat)):
50
+ return e
51
+ return get_proxy_slot(
52
+ cast(torch.Tensor, e), proxy_mode.tracer, e, lambda e: e.proxy # type: ignore[attr-defined]
53
+ )
54
+
55
+ if not is_lowered_module(lowered_module):
56
+ raise ValueError(
57
+ "executorch_call_delegate()'s first argument must be a LoweredBackendModule"
58
+ )
59
+
60
+ with disable_proxy_modes_tracing():
61
+ out = call_delegate_cpu(lowered_module, *args)
62
+
63
+ get_lowered_module_name(proxy_mode.tracer.root, lowered_module)
64
+
65
+ node_args = (lowered_module, *args)
66
+ proxy_args = pytree.tree_map(_unwrap_proxy, node_args)
67
+ out_proxy = proxy_mode.tracer.create_proxy(
68
+ "call_function", func_overload, proxy_args, {}, name="executorch_call_delegate"
69
+ )
70
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
71
+
72
+
73
+ @executorch_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
74
+ # pyre-ignore
75
+ def call_delegate_cpu(lowered_module, *args):
76
+ # FX creates this immutable_dict/list concept. Get rid of this.
77
+ map_types: dict[type, type] = {
78
+ torch.fx.immutable_collections.immutable_dict: dict,
79
+ torch.fx.immutable_collections.immutable_list: list,
80
+ }
81
+ new_args = pytree.tree_map_only(
82
+ tuple(map_types.keys()),
83
+ lambda a: map_types[type(a)](a),
84
+ args,
85
+ lambda a: isinstance(a, tuple(map_types.keys())),
86
+ )
87
+ return lowered_module.original_module.module()(*new_args)
88
+
89
+
90
+ @executorch_call_delegate.py_impl(torch._C.DispatchKey.Autograd)
91
+ # pyre-ignore
92
+ def call_delegate_autograd(lowered_module, *args):
93
+ # TODO: support autograd
94
+ flat_operands, _ = tree_flatten([lowered_module, *args])
95
+ requires_grad = any(
96
+ f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor)
97
+ )
98
+
99
+ with torch._C._ExcludeDispatchKeyGuard(
100
+ torch._C.DispatchKeySet(torch._C.DispatchKey.AutogradCPU)
101
+ ):
102
+ res = executorch_call_delegate(lowered_module, *args)
103
+
104
+ if requires_grad:
105
+ # Create aliases of the output that has requires_grad=True. We need
106
+ # at least one of the inputs to err_fn to require grad so that the
107
+ # output will have a grad_fn.
108
+
109
+ # pyre-ignore
110
+ def fake_requires_grad(var):
111
+ if var is not None:
112
+ var = var.detach()
113
+ if torch.is_floating_point(var) or torch.is_complex(var):
114
+ var.requires_grad = True
115
+ return var
116
+
117
+ return pytree.tree_map_only(torch.Tensor, fake_requires_grad, res)
118
+
119
+ return res
120
+
121
+
122
+ @executorch_call_delegate.py_impl(ProxyTorchDispatchMode)
123
+ # pyre-ignore
124
+ def call_delegate_proxy_torch_dispatch_mode(mode, lowered_module, *args):
125
+ res = trace_call_delegate(mode, executorch_call_delegate, lowered_module, *args)
126
+ return res
127
+
128
+
129
+ @executorch_call_delegate.py_impl(FakeTensorMode)
130
+ # pyre-ignore
131
+ def call_delegate_fake_tensor_mode(mode, lowered_module, *args):
132
+ with mode:
133
+ return call_delegate_cpu(lowered_module, *args)
134
+
135
+
136
+ @executorch_call_delegate.py_functionalize_impl
137
+ # pyre-ignore
138
+ def call_delegate_functionalize(ctx, lowered_module, *args):
139
+ unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
140
+ with ctx.redispatch_to_next():
141
+ res = executorch_call_delegate(lowered_module, *unwrapped_args)
142
+ return ctx.wrap_tensors(res)
143
+
144
+
145
+ # pyre-ignore: Missing parameter annotation [2]: Parameter `obj` must have a type other than `Any`.Pyre
146
+ def is_lowered_module(obj: Any) -> bool:
147
+ """
148
+ This function is added to avoid using isinstance(obj,
149
+ LoweredBackendModule) as it will import LoweredBackendModule, which may
150
+ cause a circular import.
151
+ """
152
+ return type(obj).__name__ == LOWERED_BACKEND_MODULE_TYPE
153
+
154
+
155
+ def get_lowered_module_name(
156
+ root: torch.nn.Module,
157
+ # pyre-ignore: Undefined or invalid type [11]: Annotation `LoweredBackendModule` is not defined as a type.
158
+ lowered_module: LOWERED_BACKEND_MODULE_TYPE, # type: ignore[valid-type]
159
+ ) -> str:
160
+ """
161
+ Adds the given lowered_module into the given root module and returns the
162
+ name of the module added.
163
+ """
164
+ # Find a qualifying name for the lowered submodule
165
+ qualname = None
166
+ i = 0
167
+ while True:
168
+ qualname = f"lowered_module_{i}"
169
+ if not hasattr(root, qualname):
170
+ break
171
+ i += 1
172
+ assert qualname is not None
173
+
174
+ root.add_module(qualname, lowered_module)
175
+ return qualname
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flat_apply.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass
3
+ from typing import Callable
4
+
5
+ import torch
6
+ import torch.fx.node
7
+ import torch.utils._pytree as pytree
8
+ from torch._ops import HigherOrderOperator
9
+
10
+
11
+ def is_graphable(val) -> bool:
12
+ """Definition: a graphable type is a type that that is an acceptable input/output type to a FX node."""
13
+ return isinstance(val, torch.fx.node.base_types)
14
+
15
+
16
+ def is_graphable_type(typ) -> bool:
17
+ """Return whether the given type is graphable"""
18
+ return issubclass(typ, torch.fx.node.base_types)
19
+
20
+
21
+ def to_graphable(stuff):
22
+ """Flattens stuff into a flat list of graphable types."""
23
+ # We can consider preserving things like List[int] to improve
24
+ # perf and readability (right now that is all flattened out)
25
+ flat_args, spec = pytree.tree_flatten(stuff)
26
+ for arg in flat_args:
27
+ if not is_graphable(arg):
28
+ raise RuntimeError(
29
+ f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found "
30
+ f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as "
31
+ f"via pytree.register_constant; otherwise, register it as a pytree."
32
+ )
33
+ return flat_args, spec
34
+
35
+
36
+ def from_graphable(flat_args, spec):
37
+ """The inverse of to_graphable."""
38
+ stuff = pytree.tree_unflatten(flat_args, spec)
39
+ return stuff
40
+
41
+
42
+ def func_to_graphable(func):
43
+ """
44
+ Pack and flatten a function type into graphable types.
45
+ This is useful for legalizing the function argument of `flat_apply`.
46
+ """
47
+ return pytree.tree_flatten(_ConstantFunction(func))
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class _ConstantFunction:
52
+ func: Callable
53
+
54
+ def __call__(self, *args, **kwargs):
55
+ return self.func(*args, **kwargs)
56
+
57
+
58
+ pytree.register_constant(_ConstantFunction)
59
+
60
+ _op_types = (
61
+ torch._ops.OpOverload,
62
+ torch._ops.OpOverloadPacket,
63
+ torch._ops.HigherOrderOperator,
64
+ )
65
+
66
+
67
+ class FlatApply(HigherOrderOperator):
68
+ def __init__(self) -> None:
69
+ super().__init__("flat_apply")
70
+
71
+ def __call__(self, func, in_spec, *flat_args, **_unused):
72
+ """
73
+ Functions that take in non-graphable types cannot directly be put into FX graph.
74
+
75
+ Given func(*args, **kwargs), if all of the non-graphable types are pytrees,
76
+ then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph.
77
+
78
+ The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to:
79
+
80
+ >>> def flat_apply_impl(func, in_spec, *flat_args):
81
+ >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec)
82
+ >>> output = func(*args, **kwargs)
83
+ >>> return output
84
+
85
+ flat_apply supports the following two cases:
86
+ - an input type is a container type (e.g. of tensors) registered as a pytree.
87
+ We'll tree_flatten the input type and store the spec.
88
+ - an input type is a constant type (i.e. torch.compile will specialize on it)
89
+ registered with pytree.register_constant. The constant type goes directly
90
+ into the spec.
91
+
92
+ """
93
+ assert isinstance(func, _op_types) or pytree._is_constant_holder(func)
94
+ assert len(_unused) == 0
95
+ return impl(func, in_spec, *flat_args)
96
+
97
+
98
+ def impl(func, in_spec, *flat_args):
99
+ if not isinstance(func, _op_types):
100
+ # assume _ConstantFunction
101
+ func = pytree._retrieve_constant(func)
102
+ assert isinstance(func, _ConstantFunction)
103
+
104
+ args, kwargs = from_graphable(flat_args, in_spec)
105
+ out = func(*args, **kwargs)
106
+
107
+ # Right now, all outputs must either be graphable or lists/tuples of graphables.
108
+ #
109
+ # TODO: The following can be updated to support non-graphable outputs and pytrees.
110
+ # For non-graphable constant outputs: the assumption would be that they are constant
111
+ # (everytime the function runs those MUST be the same)
112
+ # For pytree outputs:
113
+ # I'm not sure if we need to return (flat_output, spec) or just (flat_output,):
114
+ # in the latter case the tracers need to carry out the output specs
115
+ # (they need to know how to reconstruct the object from just the flat_output).
116
+ def is_valid_output(x):
117
+ if isinstance(x, (tuple, list)):
118
+ return all(map(is_valid_output, x))
119
+ return is_graphable(x)
120
+
121
+ assert is_valid_output(out)
122
+ return out
123
+
124
+
125
+ flat_apply = FlatApply()
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flex_attention.py ADDED
@@ -0,0 +1,1196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections.abc import Sequence
3
+ from typing import Any, Callable, Optional, Union
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+ from torch import Tensor
8
+ from torch._C import DispatchKey
9
+ from torch._higher_order_ops.utils import (
10
+ _has_potential_branch_input_mutation,
11
+ _maybe_reenter_make_fx,
12
+ autograd_not_implemented,
13
+ reenter_make_fx,
14
+ save_tensors_and_symints_for_backward,
15
+ saved_tensors_and_symints,
16
+ UnsupportedAliasMutationException,
17
+ validate_subgraph_args_types,
18
+ )
19
+ from torch._ops import HigherOrderOperator
20
+ from torch._subclasses import FakeTensorMode
21
+ from torch.fx.experimental.proxy_tensor import (
22
+ make_fx,
23
+ ProxyTorchDispatchMode,
24
+ track_tensor_tree,
25
+ )
26
+ from torch.fx.graph_module import GraphModule
27
+
28
+
29
+ # Duplicate of _inductor/kernel/flex_attention.py to avoid circular import
30
+ def _construct_strides(
31
+ sizes: Sequence[int],
32
+ fill_order: Sequence[int],
33
+ ) -> Sequence[int]:
34
+ """From a list of sizes and a fill order, construct the strides of the permuted tensor."""
35
+ # Initialize strides
36
+ assert len(sizes) == len(
37
+ fill_order
38
+ ), "Length of sizes must match the length of the fill order"
39
+ strides = [0] * len(sizes)
40
+
41
+ # Start with stride 1 for the innermost dimension
42
+ current_stride = 1
43
+
44
+ # Iterate through the fill order populating strides
45
+ for dim in fill_order:
46
+ strides[dim] = current_stride
47
+ current_stride *= sizes[dim]
48
+
49
+ return strides
50
+
51
+
52
+ def _permute_strides(out: torch.Tensor, query_strides: tuple[int, ...]) -> torch.Tensor:
53
+ """
54
+ Create a new tensor with the same data and shape as the input,
55
+ but with strides permuted based on the input tensor's stride order.
56
+
57
+ Args:
58
+ out (torch.Tensor): The output tensor of attention.
59
+ query_strides (List[int]): The stride order of the input query tensor
60
+
61
+ Returns:
62
+ torch.Tensor: A new tensor with same shape and data as the input,
63
+ but with strides permuted based on the query tensor's stride order.
64
+ """
65
+ from torch._inductor.ir import get_fill_order
66
+
67
+ fill_order = get_fill_order(query_strides)
68
+ assert out.storage_offset() == 0, "Only support storage_offset == 0"
69
+ out_strides = _construct_strides(out.shape, fill_order)
70
+ new_out = out.new_empty(out.shape).as_strided(out.shape, out_strides)
71
+ new_out.copy_(out)
72
+ return new_out
73
+
74
+
75
+ class FlexAttentionHOP(HigherOrderOperator):
76
+ def __init__(self) -> None:
77
+ super().__init__("flex_attention", cacheable=True)
78
+
79
+ def __call__(
80
+ self,
81
+ query: torch.Tensor,
82
+ key: torch.Tensor,
83
+ value: torch.Tensor,
84
+ score_mod: Callable,
85
+ block_mask: tuple,
86
+ scale: float,
87
+ kernel_options: dict[str, Any],
88
+ score_mod_other_buffers: tuple = (),
89
+ mask_mod_other_buffers: tuple = (),
90
+ ) -> tuple[torch.Tensor, torch.Tensor]:
91
+ validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
92
+ return super().__call__(
93
+ query,
94
+ key,
95
+ value,
96
+ score_mod,
97
+ block_mask,
98
+ scale,
99
+ kernel_options,
100
+ score_mod_other_buffers,
101
+ mask_mod_other_buffers,
102
+ )
103
+
104
+
105
+ flex_attention = FlexAttentionHOP()
106
+
107
+
108
+ class FlexAttentionBackwardHOP(HigherOrderOperator):
109
+ def __init__(self) -> None:
110
+ super().__init__("flex_attention_backward")
111
+
112
+ def __call__(
113
+ self,
114
+ query: torch.Tensor,
115
+ key: torch.Tensor,
116
+ value: torch.Tensor,
117
+ out: torch.Tensor,
118
+ logsumexp: torch.Tensor,
119
+ grad_out: torch.Tensor,
120
+ grad_logsumexp: torch.Tensor,
121
+ fw_graph: Union[Callable, GraphModule],
122
+ joint_graph: GraphModule,
123
+ block_mask: tuple,
124
+ scale: float,
125
+ kernel_options: dict[str, Any],
126
+ score_mod_other_buffers: tuple = (),
127
+ mask_mod_other_buffers: tuple = (),
128
+ ) -> tuple[
129
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
130
+ ]:
131
+ validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
132
+ return super().__call__(
133
+ query,
134
+ key,
135
+ value,
136
+ out,
137
+ logsumexp,
138
+ grad_out,
139
+ grad_logsumexp,
140
+ fw_graph,
141
+ joint_graph,
142
+ block_mask,
143
+ scale,
144
+ kernel_options,
145
+ score_mod_other_buffers,
146
+ mask_mod_other_buffers,
147
+ )
148
+
149
+
150
+ flex_attention_backward = FlexAttentionBackwardHOP()
151
+
152
+
153
+ def _math_attention_inner(
154
+ query: torch.Tensor,
155
+ key: torch.Tensor,
156
+ value: torch.Tensor,
157
+ score_mod: Callable,
158
+ block_mask: tuple,
159
+ scale: float,
160
+ kernel_options: dict[str, Any],
161
+ score_mod_other_buffers: tuple = (),
162
+ mask_mod_other_buffers: tuple = (),
163
+ ) -> tuple[torch.Tensor, torch.Tensor]:
164
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
165
+
166
+ working_precision = torch.float64 if query.dtype == torch.float64 else torch.float32
167
+
168
+ scores = (query @ key.transpose(-2, -1)).to(dtype=working_precision)
169
+
170
+ b = torch.arange(0, scores.size(0), device=scores.device)
171
+ h = torch.arange(0, scores.size(1), device=scores.device)
172
+ m = torch.arange(0, scores.size(2), device=scores.device)
173
+ n = torch.arange(0, scores.size(3), device=scores.device)
174
+
175
+ captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
176
+ from torch.nn.attention.flex_attention import _vmap_for_bhqkv
177
+
178
+ # first input is score
179
+ score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,), suffix=captured_buffers_in_dim)
180
+
181
+ mask_mod = block_mask[-1]
182
+ mask_mod_in_dim_buffers = (None,) * len(mask_mod_other_buffers)
183
+ mask_mod = _vmap_for_bhqkv(mask_mod, prefix=(), suffix=mask_mod_in_dim_buffers)
184
+
185
+ with TransformGetItemToIndex():
186
+ scores = (scores * scale).to(working_precision)
187
+ post_mod_scores = torch.where(
188
+ mask_mod(b, h, m, n, *mask_mod_other_buffers),
189
+ score_mod(scores, b, h, m, n, *score_mod_other_buffers),
190
+ torch.tensor(-float("inf"), dtype=working_precision, device=scores.device),
191
+ )
192
+
193
+ return scores, post_mod_scores
194
+
195
+
196
+ def math_attention(
197
+ query: torch.Tensor,
198
+ key: torch.Tensor,
199
+ value: torch.Tensor,
200
+ score_mod: Callable,
201
+ block_mask: tuple,
202
+ scale: float,
203
+ kernel_options: dict[str, Any],
204
+ score_mod_other_buffers: tuple = (),
205
+ mask_mod_other_buffers: tuple = (),
206
+ ) -> tuple[torch.Tensor, torch.Tensor]:
207
+ """Eager implementation
208
+
209
+ This implementation uses vmap to vectorize the score_mod function over the batch, head, m, and n dimensions.
210
+ We then apply the vectorized score_mod function to the scores matrix. Each wrap of vmap applies one of the
211
+ batch, head, m, or n dimensions. We need to apply vmap 4 times to vectorized over all 4 dimensions.
212
+
213
+ Args:
214
+ query: The query tensor
215
+ key: The key tensor
216
+ value: The value tensor
217
+ score_mod: The score_mod function
218
+ other_buffers: Other buffers that are passed to the score_mod function
219
+ """
220
+ # broadcast query & key along head dim for GQA
221
+ G = query.size(1) // key.size(1)
222
+ value = torch.repeat_interleave(value, G, dim=1)
223
+ key = torch.repeat_interleave(key, G, dim=1)
224
+
225
+ Bq, Bkv = query.size(0), key.size(0)
226
+ if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
227
+ raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
228
+
229
+ key = key.expand((Bq, *key.size()[1:]))
230
+ value = value.expand((Bq, *value.size()[1:]))
231
+
232
+ _, post_mod_scores = _math_attention_inner(
233
+ query,
234
+ key,
235
+ value,
236
+ score_mod,
237
+ block_mask,
238
+ scale,
239
+ kernel_options,
240
+ score_mod_other_buffers,
241
+ mask_mod_other_buffers,
242
+ )
243
+
244
+ # Set fully masked rows' sumexp to 0.0
245
+ logsumexp = post_mod_scores.logsumexp(dim=-1)
246
+ masked_rows = torch.all(post_mod_scores == -float("inf"), dim=-1)
247
+ logsumexp = torch.where(masked_rows, -float("inf"), logsumexp)
248
+
249
+ post_mod_scores = torch._safe_softmax(post_mod_scores, dim=-1)
250
+
251
+ return post_mod_scores.to(query.dtype) @ value, logsumexp / math.log(2)
252
+
253
+
254
+ @flex_attention.py_impl(DispatchKey.CompositeExplicitAutograd)
255
+ def sdpa_dense(
256
+ query: torch.Tensor,
257
+ key: torch.Tensor,
258
+ value: torch.Tensor,
259
+ score_mod: Callable,
260
+ block_mask: tuple,
261
+ scale: float,
262
+ kernel_options: dict[str, Any],
263
+ score_mod_other_buffers: tuple = (),
264
+ mask_mod_other_buffers: tuple = (),
265
+ ) -> tuple[torch.Tensor, torch.Tensor]:
266
+ out, lse = math_attention(
267
+ query,
268
+ key,
269
+ value,
270
+ score_mod,
271
+ block_mask,
272
+ scale,
273
+ kernel_options,
274
+ score_mod_other_buffers,
275
+ mask_mod_other_buffers,
276
+ )
277
+ out = _permute_strides(out, query.stride())
278
+ return out, lse
279
+
280
+
281
+ def trace_flex_attention(
282
+ proxy_mode: ProxyTorchDispatchMode,
283
+ query: torch.Tensor,
284
+ key: torch.Tensor,
285
+ value: torch.Tensor,
286
+ score_mod: Callable,
287
+ block_mask: tuple,
288
+ scale: float,
289
+ kernel_options: dict[str, Any],
290
+ score_mod_other_buffers: tuple = (),
291
+ mask_mod_other_buffers: tuple = (),
292
+ ) -> tuple[torch.Tensor, torch.Tensor]:
293
+ """Traces the flex_attention operator with the given score_mod function and other_buffers.
294
+
295
+ Trace SDPA will call make_fx with "fake" example vals and then trace the score_mod function
296
+ This will produce a GraphModule that will be stored on the root tracer as "sdpa_score". We
297
+ access this graph module in inductor to inline the score_mod function to the triton template.
298
+ """
299
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
300
+
301
+ example_out = flex_attention(
302
+ query,
303
+ key,
304
+ value,
305
+ score_mod,
306
+ block_mask,
307
+ scale,
308
+ kernel_options,
309
+ score_mod_other_buffers,
310
+ mask_mod_other_buffers,
311
+ )
312
+ example_vals = [query.new_zeros((), requires_grad=query.requires_grad)] + [
313
+ query.new_zeros((), dtype=torch.int) for _ in range(4)
314
+ ]
315
+ mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
316
+ mask_mod = block_mask[-1]
317
+ with TransformGetItemToIndex():
318
+ score_graph = reenter_make_fx(score_mod)(
319
+ *example_vals, *score_mod_other_buffers
320
+ )
321
+ mask_graph = reenter_make_fx(mask_mod)(
322
+ *mask_example_vals, *mask_mod_other_buffers
323
+ )
324
+ assert isinstance(proxy_mode.tracer, torch.fx.Tracer)
325
+ block_mask = block_mask[:-1] + (mask_graph,)
326
+ qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_score")
327
+ proxy_mode.tracer.root.register_module(qualname, score_graph)
328
+ mask_qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_mask")
329
+ proxy_mode.tracer.root.register_module(mask_qualname, mask_graph)
330
+ node_args = (
331
+ query,
332
+ key,
333
+ value,
334
+ score_graph,
335
+ block_mask,
336
+ scale,
337
+ kernel_options,
338
+ score_mod_other_buffers,
339
+ mask_mod_other_buffers,
340
+ )
341
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
342
+ out_proxy = proxy_mode.tracer.create_proxy(
343
+ "call_function", flex_attention, proxy_args, {}
344
+ )
345
+ return track_tensor_tree(
346
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
347
+ )
348
+
349
+
350
+ @flex_attention.py_impl(ProxyTorchDispatchMode)
351
+ def flex_attention_proxy_torch_dispatch_mode(
352
+ mode: ProxyTorchDispatchMode,
353
+ query: torch.Tensor,
354
+ key: torch.Tensor,
355
+ value: torch.Tensor,
356
+ score_mod: Callable,
357
+ block_mask: tuple,
358
+ scale: float,
359
+ kernel_options: dict[str, Any],
360
+ score_mod_other_buffers: tuple = (),
361
+ mask_mod_other_buffers: tuple = (),
362
+ ) -> tuple[torch.Tensor, torch.Tensor]:
363
+ assert mode is not None, "Mode should always be enabled for python fallback key"
364
+ return trace_flex_attention(
365
+ mode,
366
+ query,
367
+ key,
368
+ value,
369
+ score_mod,
370
+ block_mask,
371
+ scale,
372
+ kernel_options,
373
+ score_mod_other_buffers,
374
+ mask_mod_other_buffers,
375
+ )
376
+
377
+
378
+ @flex_attention.py_functionalize_impl
379
+ def flex_attention_functionalize(
380
+ ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
381
+ query: torch.Tensor,
382
+ key: torch.Tensor,
383
+ value: torch.Tensor,
384
+ score_mod: Callable,
385
+ block_mask: tuple,
386
+ scale: float,
387
+ kernel_options: dict[str, Any],
388
+ score_mod_other_buffers: tuple = (),
389
+ mask_mod_other_buffers: tuple = (),
390
+ ) -> tuple[torch.Tensor, torch.Tensor]:
391
+ """Defines the functionalization rules for the flex_attention operator.
392
+
393
+ Write now we are unwrapping each tensor and then redispatching to the next, however we want to
394
+ guard against any mutations in the score_mod function, to the other_buffers since those
395
+ are free variables.
396
+ """
397
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
398
+
399
+ query_unwrapped = ctx.unwrap_tensors(query)
400
+ key_unwrapped = ctx.unwrap_tensors(key)
401
+ value_unwrapped = ctx.unwrap_tensors(value)
402
+ block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
403
+ score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
404
+ mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
405
+
406
+ # Appease the mypy overlords
407
+ assert isinstance(query_unwrapped, torch.Tensor)
408
+ assert isinstance(key_unwrapped, torch.Tensor)
409
+ assert isinstance(value_unwrapped, torch.Tensor)
410
+ assert isinstance(block_mask_unwrapped, tuple)
411
+ assert isinstance(score_mod_other_buffers_unwrapped, tuple)
412
+ assert isinstance(mask_mod_other_buffers_unwrapped, tuple)
413
+
414
+ example_vals = (
415
+ [query_unwrapped.new_zeros(())]
416
+ + [query_unwrapped.new_zeros((), dtype=torch.int) for _ in range(4)]
417
+ + list(score_mod_other_buffers_unwrapped)
418
+ )
419
+ with ctx.redispatch_to_next():
420
+ functional_score_mod = ctx.functionalize(score_mod)
421
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
422
+ with TransformGetItemToIndex():
423
+ mutates = _has_potential_branch_input_mutation(
424
+ score_mod, example_vals, pre_dispatch
425
+ )
426
+ # The only care about mutations of existing buffers since we can't replay these.
427
+ # However, we can just error if anything is detected
428
+ if mutates:
429
+ raise UnsupportedAliasMutationException("Mutations detected in score_mod")
430
+
431
+ out = flex_attention(
432
+ query_unwrapped,
433
+ key_unwrapped,
434
+ value_unwrapped,
435
+ functional_score_mod,
436
+ block_mask_unwrapped,
437
+ scale,
438
+ kernel_options,
439
+ score_mod_other_buffers_unwrapped,
440
+ mask_mod_other_buffers_unwrapped,
441
+ )
442
+ return ctx.wrap_tensors(out) # type: ignore[return-value, arg-type]
443
+
444
+
445
+ def flex_attention_fake_impl(
446
+ query: torch.Tensor, value: torch.Tensor
447
+ ) -> tuple[torch.Tensor, torch.Tensor]:
448
+ # TODO: Figure out a better way to handle this for NJT than using sum()
449
+ if query.is_nested:
450
+ out = torch.empty_like(query, memory_format=torch.contiguous_format)
451
+ logsumexp = query.sum(dim=-1)
452
+ return out, logsumexp
453
+
454
+ v_head_dim = value.size(-1)
455
+ batch_size, num_heads, seq_len_q, _q_head_dim = query.shape
456
+ logsumexp = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32)
457
+ out_shape = (batch_size, num_heads, seq_len_q, v_head_dim)
458
+ out = query.new_empty(out_shape)
459
+ out = _permute_strides(out, query.stride())
460
+ return out, logsumexp
461
+
462
+
463
+ @flex_attention.py_impl(FakeTensorMode)
464
+ def flex_attention_fake_tensor_mode(
465
+ mode: FakeTensorMode,
466
+ query: torch.Tensor,
467
+ key: torch.Tensor,
468
+ value: torch.Tensor,
469
+ score_mod: Callable,
470
+ block_mask: tuple,
471
+ scale: float,
472
+ kernel_options: dict[str, Any],
473
+ score_mod_other_buffers: tuple = (),
474
+ mask_mod_other_buffers: tuple = (),
475
+ ) -> tuple[torch.Tensor, torch.Tensor]:
476
+ with mode:
477
+ out, logsumexp = flex_attention_fake_impl(query, value)
478
+ return out, logsumexp
479
+
480
+
481
+ # ---------------------------- Autograd Implementation ----------------------------
482
+ def create_fw_bw_graph(
483
+ score_mod: Callable,
484
+ index_values: tuple[Tensor, Tensor, Tensor, Tensor, Tensor],
485
+ other_buffers: tuple[Tensor, ...],
486
+ ) -> tuple[Callable, Callable]:
487
+ # See Note:[HOP create fw_bw graph]
488
+
489
+ # All of these imports need to be here in order to avoid circular dependencies
490
+ from torch._dispatch.python import suspend_functionalization
491
+ from torch._functorch.aot_autograd import AOTConfig, create_joint
492
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
493
+ from torch._subclasses.functional_tensor import disable_functional_mode
494
+ from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
495
+
496
+ dummy_aot_config = AOTConfig(
497
+ fw_compiler=None, # type: ignore[arg-type]
498
+ bw_compiler=None, # type: ignore[arg-type]
499
+ partition_fn=None, # type: ignore[arg-type]
500
+ decompositions={},
501
+ num_params_buffers=0,
502
+ aot_id=0,
503
+ keep_inference_input_mutations=False,
504
+ )
505
+
506
+ with suspend_functionalization(), disable_functional_mode():
507
+ with disable_proxy_modes_tracing():
508
+
509
+ def _from_fun(
510
+ t: Union[Tensor, torch.SymInt, int]
511
+ ) -> Union[Tensor, torch.SymInt, int]:
512
+ if isinstance(t, torch.Tensor):
513
+ return torch.empty_strided(
514
+ t.size(),
515
+ t.stride(),
516
+ device=t.device,
517
+ dtype=t.dtype,
518
+ requires_grad=t.requires_grad,
519
+ )
520
+ return t
521
+
522
+ # If someone runs this hop under the default compiler backend ("eager")
523
+ # Then this path will be run with the actual user inputs. We convert them
524
+ # to fake tensors in order to not perform any actual compute.
525
+ from torch._guards import detect_fake_mode
526
+
527
+ fake_mode = detect_fake_mode(index_values)
528
+ if fake_mode is None:
529
+ fake_mode = FakeTensorMode(allow_non_fake_inputs=True)
530
+
531
+ with fake_mode:
532
+ unwrapped_score_mod_indexes = pytree.tree_map(_from_fun, index_values)
533
+ unwrapped_other_buffers = pytree.tree_map(_from_fun, other_buffers)
534
+
535
+ assert all(
536
+ isinstance(t, (FakeTensor, int, torch.SymInt))
537
+ for t in unwrapped_score_mod_indexes + unwrapped_other_buffers
538
+ )
539
+
540
+ example_flat_out = pytree.tree_map(
541
+ _from_fun,
542
+ score_mod(*unwrapped_score_mod_indexes, *unwrapped_other_buffers),
543
+ )
544
+ if not isinstance(example_flat_out, torch.Tensor):
545
+ raise RuntimeError(
546
+ "Expected output of score_mod to be a tensor."
547
+ f"Got type {type(example_flat_out)}."
548
+ )
549
+ example_grad = _from_fun(example_flat_out)
550
+
551
+ def joint_f(
552
+ score: Tensor,
553
+ b: Tensor,
554
+ h: Tensor,
555
+ m: Tensor,
556
+ n: Tensor,
557
+ example_grad: Tensor,
558
+ *other_buffers: tuple[Tensor, ...],
559
+ ) -> tuple[Tensor, ...]:
560
+ def fw_with_masks(
561
+ *args: tuple[Tensor, ...]
562
+ ) -> tuple[tuple[Tensor], tuple[bool]]:
563
+ fw_out = score_mod(*args)
564
+ out_requires_grad = fw_out.requires_grad
565
+ return ((fw_out,), (out_requires_grad,))
566
+
567
+ joint = create_joint(fw_with_masks, aot_config=dummy_aot_config)
568
+ args = [score, b, h, m, n] + list(other_buffers)
569
+ optional_grad = [example_grad] if example_grad.requires_grad else []
570
+ _, grads = joint(args, optional_grad)
571
+
572
+ return grads
573
+
574
+ joint_graph = make_fx(joint_f)(
575
+ *unwrapped_score_mod_indexes, example_grad, *unwrapped_other_buffers
576
+ )
577
+ return score_mod, joint_graph
578
+
579
+
580
+ class FlexAttentionAutogradOp(torch.autograd.Function):
581
+ @staticmethod
582
+ def forward(
583
+ ctx: Any,
584
+ query: Tensor,
585
+ key: Tensor,
586
+ value: Tensor,
587
+ fw_graph: Callable,
588
+ joint_graph: Callable,
589
+ block_mask: tuple[Any, ...],
590
+ scale: float,
591
+ kernel_options: dict[str, Any],
592
+ mask_mod_other_buffers: tuple[Any, ...],
593
+ *score_mod_other_buffers: tuple[Any, ...],
594
+ ) -> tuple[torch.Tensor, torch.Tensor]:
595
+ any_buffer_requires_grad = any(
596
+ buffer.requires_grad
597
+ for buffer in mask_mod_other_buffers
598
+ if isinstance(buffer, torch.Tensor)
599
+ )
600
+ assert (
601
+ not any_buffer_requires_grad
602
+ ), "Captured buffers from mask mod that require grad are not supported."
603
+ ctx._fw_graph = fw_graph
604
+ ctx._joint_graph = joint_graph
605
+ ctx._mask_graph = block_mask[-1]
606
+ ctx.scale = scale
607
+ ctx.kernel_options = kernel_options
608
+ ctx._score_mod_other_buffers_len = len(score_mod_other_buffers)
609
+ with torch._C._AutoDispatchBelowAutograd():
610
+ out, logsumexp = flex_attention(
611
+ query,
612
+ key,
613
+ value,
614
+ fw_graph,
615
+ block_mask,
616
+ scale,
617
+ kernel_options,
618
+ score_mod_other_buffers,
619
+ mask_mod_other_buffers,
620
+ )
621
+
622
+ save_tensors_and_symints_for_backward(
623
+ ctx,
624
+ (
625
+ query,
626
+ key,
627
+ value,
628
+ out,
629
+ logsumexp,
630
+ *block_mask[:-1],
631
+ *score_mod_other_buffers,
632
+ *mask_mod_other_buffers,
633
+ ),
634
+ )
635
+ return out, logsumexp
636
+
637
+ @staticmethod
638
+ def backward(ctx: Any, grad_out: Tensor, grad_logsumexp: Tensor) -> tuple[Optional[Tensor], ...]: # type: ignore[override]
639
+ fw_args = saved_tensors_and_symints(ctx)
640
+ (
641
+ query,
642
+ key,
643
+ value,
644
+ out,
645
+ logsumexp,
646
+ query_lengths,
647
+ kv_lengths,
648
+ kv_num_blocks,
649
+ kv_indices,
650
+ full_kv_num_blocks,
651
+ full_kv_indices,
652
+ q_num_blocks,
653
+ q_indices,
654
+ full_q_num_blocks,
655
+ full_q_indices,
656
+ Q_BLOCK_SIZE,
657
+ KV_BLOCK_SIZE,
658
+ *other_buffers,
659
+ ) = fw_args
660
+ fw_graph = ctx._fw_graph
661
+ joint_graph = ctx._joint_graph
662
+ mask_graph = ctx._mask_graph
663
+ scale = ctx.scale
664
+ kernel_options = ctx.kernel_options
665
+ score_mod_other_buffers = tuple(
666
+ other_buffers[: ctx._score_mod_other_buffers_len]
667
+ )
668
+ mask_mod_other_buffers = tuple(
669
+ other_buffers[ctx._score_mod_other_buffers_len :]
670
+ )
671
+ # We have asserted that mask_mod_other_buffers do not require grad,
672
+ # but score_mod_other_buffers can require grad.
673
+ none_grads = [None] * 6
674
+ (
675
+ grad_query,
676
+ grad_key,
677
+ grad_value,
678
+ grad_score_mod_captured,
679
+ ) = flex_attention_backward(
680
+ query,
681
+ key,
682
+ value,
683
+ out,
684
+ logsumexp,
685
+ grad_out,
686
+ grad_logsumexp,
687
+ fw_graph,
688
+ joint_graph,
689
+ (
690
+ query_lengths,
691
+ kv_lengths,
692
+ kv_num_blocks,
693
+ kv_indices,
694
+ full_kv_num_blocks,
695
+ full_kv_indices,
696
+ q_num_blocks,
697
+ q_indices,
698
+ full_q_num_blocks,
699
+ full_q_indices,
700
+ Q_BLOCK_SIZE,
701
+ KV_BLOCK_SIZE,
702
+ mask_graph,
703
+ ),
704
+ scale,
705
+ kernel_options,
706
+ score_mod_other_buffers,
707
+ mask_mod_other_buffers,
708
+ )
709
+ return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured
710
+
711
+
712
+ @flex_attention.py_impl(DispatchKey.Autograd)
713
+ def flex_attention_autograd(
714
+ query: torch.Tensor,
715
+ key: torch.Tensor,
716
+ value: torch.Tensor,
717
+ score_mod: Callable,
718
+ block_mask: tuple,
719
+ scale: float,
720
+ kernel_options: dict[str, Any],
721
+ score_mod_other_buffers: tuple[Tensor, ...] = (),
722
+ mask_mod_other_buffers: tuple[Tensor, ...] = (),
723
+ ) -> tuple[torch.Tensor, torch.Tensor]:
724
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
725
+
726
+ with TransformGetItemToIndex():
727
+ input_requires_grad = any(
728
+ isinstance(t, torch.Tensor) and t.requires_grad
729
+ for t in (query, key, value, *score_mod_other_buffers)
730
+ )
731
+ if torch.is_grad_enabled() and input_requires_grad:
732
+ example_vals = (
733
+ query.new_zeros((), requires_grad=input_requires_grad),
734
+ query.new_zeros((), dtype=torch.int),
735
+ query.new_zeros((), dtype=torch.int),
736
+ query.new_zeros((), dtype=torch.int),
737
+ query.new_zeros((), dtype=torch.int),
738
+ )
739
+ fw_graph, bw_graph = create_fw_bw_graph(
740
+ score_mod, example_vals, score_mod_other_buffers
741
+ )
742
+ else:
743
+ fw_graph, bw_graph = score_mod, None
744
+ out, logsumexp = FlexAttentionAutogradOp.apply(
745
+ query,
746
+ key,
747
+ value,
748
+ fw_graph,
749
+ bw_graph,
750
+ block_mask,
751
+ scale,
752
+ kernel_options,
753
+ mask_mod_other_buffers,
754
+ *score_mod_other_buffers,
755
+ )
756
+ return out, logsumexp
757
+
758
+
759
+ # ---------------------------- Backward HOP Implementation ----------------------------
760
+
761
+
762
+ @flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd)
763
+ def sdpa_dense_backward(
764
+ query: torch.Tensor,
765
+ key: torch.Tensor,
766
+ value: torch.Tensor,
767
+ out: torch.Tensor,
768
+ logsumexp: torch.Tensor,
769
+ grad_out: torch.Tensor,
770
+ grad_logsumexp: torch.Tensor,
771
+ fw_graph: Callable, # GraphModule type hint?
772
+ joint_graph: Callable,
773
+ block_mask: tuple,
774
+ scale: float,
775
+ kernel_options: dict[str, Any],
776
+ score_mod_other_buffers: tuple,
777
+ mask_mod_other_buffers: tuple,
778
+ ) -> tuple[
779
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
780
+ ]:
781
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
782
+
783
+ Bq, Hq, seq_len_q, qk_head_dim = query.shape
784
+ Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
785
+
786
+ # Get outputs before calling repeat interleave and permute to input stride orders
787
+ actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim))
788
+ actual_grad_query = _permute_strides(actual_grad_query, query.stride())
789
+
790
+ actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
791
+ actual_grad_key = _permute_strides(actual_grad_key, key.stride())
792
+
793
+ actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
794
+ actual_grad_value = _permute_strides(actual_grad_value, value.stride())
795
+
796
+ def _maybe_new_buffer(
797
+ buffer: Union[torch.Tensor, torch.SymInt, int]
798
+ ) -> Optional[Union[torch.Tensor, torch.SymInt, int]]:
799
+ if isinstance(buffer, torch.Tensor):
800
+ return (
801
+ torch.empty_like(buffer, memory_format=torch.contiguous_format)
802
+ if buffer.requires_grad
803
+ else None
804
+ )
805
+ return buffer
806
+
807
+ actual_grad_score_mod_captured = [
808
+ _maybe_new_buffer(buffer) for buffer in score_mod_other_buffers
809
+ ]
810
+
811
+ Bq, Bkv = query.size(0), key.size(0)
812
+ if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
813
+ raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
814
+
815
+ key = key.expand((Bq, *key.size()[1:]))
816
+ value = value.expand((Bq, *value.size()[1:]))
817
+
818
+ G = query.size(1) // key.size(1)
819
+ key = torch.repeat_interleave(key, G, dim=1)
820
+ value = torch.repeat_interleave(value, G, dim=1)
821
+
822
+ # We're undoing the log -> log2 change of base in the forwards
823
+ logsumexp = logsumexp * math.log(2)
824
+ # The backwards formula for the log -> log2 change of base in the forwards
825
+ grad_logsumexp = grad_logsumexp / math.log(2)
826
+ scores, post_mod_scores = _math_attention_inner(
827
+ query,
828
+ key,
829
+ value,
830
+ fw_graph,
831
+ block_mask,
832
+ scale,
833
+ kernel_options,
834
+ score_mod_other_buffers,
835
+ mask_mod_other_buffers,
836
+ )
837
+ masked_out_rows = logsumexp == -float("inf")
838
+ softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1))
839
+ softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores)
840
+
841
+ grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out
842
+
843
+ grad_softmax_scores = grad_out @ value.transpose(-2, -1)
844
+
845
+ sum_scores = torch.sum(out * grad_out, -1, keepdim=True)
846
+ grad_score_mod = softmax_scores * (
847
+ grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1)
848
+ )
849
+
850
+ b = torch.arange(0, scores.size(0), device=scores.device)
851
+ h = torch.arange(0, scores.size(1), device=scores.device)
852
+ m = torch.arange(0, scores.size(2), device=scores.device)
853
+ n = torch.arange(0, scores.size(3), device=scores.device)
854
+
855
+ mask_graph = block_mask[-1]
856
+ # Gradient of the inline score_mod function, with respect to the scores
857
+ captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
858
+ out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers)
859
+ from torch.nn.attention.flex_attention import _vmap_for_bhqkv
860
+
861
+ # inputs are [score, b, h, q_idx, kv_idx, gradOut, ...]
862
+ # score and gradOut are "fully" batched
863
+ joint_score_mod = _vmap_for_bhqkv(
864
+ joint_graph,
865
+ prefix=(0,),
866
+ suffix=(0,) + captured_buffers_in_dim,
867
+ out_dims=out_dims,
868
+ )
869
+ with TransformGetItemToIndex():
870
+ grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod(
871
+ scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers
872
+ )
873
+ grad_scores = grad_scores * scale
874
+ grad_scores = grad_scores.to(query.dtype)
875
+
876
+ mask_mod = _vmap_for_bhqkv(
877
+ mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers)
878
+ )
879
+ with TransformGetItemToIndex():
880
+ mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers)
881
+ grad_scores = torch.where(
882
+ mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype)
883
+ )
884
+
885
+ grad_query = grad_scores @ key
886
+ grad_key = grad_scores.transpose(-2, -1) @ query
887
+
888
+ # Reduce DK, DV along broadcasted heads.
889
+ grad_key = grad_key.view(
890
+ grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1)
891
+ )
892
+ grad_value = grad_value.view(
893
+ grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1)
894
+ )
895
+
896
+ grad_key = torch.sum(grad_key, 2, keepdim=False)
897
+ grad_value = torch.sum(grad_value, 2, keepdim=False)
898
+
899
+ # Fill to correctly strided outputs
900
+ actual_grad_query.copy_(grad_query)
901
+ actual_grad_key.copy_(grad_key)
902
+ actual_grad_value.copy_(grad_value)
903
+
904
+ if Bq != Bkv:
905
+ assert (
906
+ Bq > 1 and Bkv == 1
907
+ ), f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}"
908
+
909
+ actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True)
910
+ actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True)
911
+
912
+ score_mod_other_buffer_grads = [
913
+ actual_grad.copy_(grad) if isinstance(actual_grad, torch.Tensor) else None
914
+ for actual_grad, grad in zip(
915
+ actual_grad_score_mod_captured, grad_score_mod_captured
916
+ )
917
+ ]
918
+
919
+ return (
920
+ actual_grad_query,
921
+ actual_grad_key,
922
+ actual_grad_value,
923
+ tuple(score_mod_other_buffer_grads),
924
+ )
925
+
926
+
927
+ def trace_flex_attention_backward(
928
+ proxy_mode: ProxyTorchDispatchMode,
929
+ query: torch.Tensor,
930
+ key: torch.Tensor,
931
+ value: torch.Tensor,
932
+ out: torch.Tensor,
933
+ logsumexp: torch.Tensor,
934
+ grad_out: torch.Tensor,
935
+ grad_logsumexp: torch.Tensor,
936
+ fw_graph: Union[Callable, GraphModule],
937
+ joint_graph: GraphModule,
938
+ block_mask: tuple,
939
+ scale: float,
940
+ kernel_options: dict[str, Any],
941
+ score_mod_other_buffers: tuple = (),
942
+ mask_mod_other_buffers: tuple = (),
943
+ ) -> tuple[
944
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
945
+ ]:
946
+ """We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs"""
947
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
948
+
949
+ example_out = flex_attention_backward(
950
+ query,
951
+ key,
952
+ value,
953
+ out,
954
+ logsumexp,
955
+ grad_out,
956
+ grad_logsumexp,
957
+ fw_graph,
958
+ joint_graph,
959
+ block_mask,
960
+ scale,
961
+ kernel_options,
962
+ score_mod_other_buffers,
963
+ mask_mod_other_buffers,
964
+ )
965
+
966
+ requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key)))
967
+ fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [
968
+ query.new_zeros((), dtype=torch.int) for _ in range(4)
969
+ ]
970
+ bw_example_vals = fw_example_vals + [query.new_zeros(())]
971
+ mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
972
+ mask_graph = block_mask[-1]
973
+ with TransformGetItemToIndex():
974
+ # There's no active make_fx during the compiled autograd graph's initial capture
975
+ fw_graph = _maybe_reenter_make_fx(fw_graph)(
976
+ *fw_example_vals, *score_mod_other_buffers
977
+ )
978
+ joint_graph = _maybe_reenter_make_fx(joint_graph)(
979
+ *bw_example_vals, *score_mod_other_buffers
980
+ )
981
+ mask_graph = _maybe_reenter_make_fx(mask_graph)(
982
+ *mask_example_vals, *mask_mod_other_buffers
983
+ )
984
+ assert isinstance(proxy_mode.tracer, torch.fx.Tracer)
985
+ block_mask = block_mask[:-1] + (mask_graph,)
986
+
987
+ qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph")
988
+ proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type]
989
+ qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph")
990
+ proxy_mode.tracer.root.register_module(qualname, joint_graph)
991
+ qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph")
992
+ proxy_mode.tracer.root.register_module(qualname, mask_graph)
993
+
994
+ node_args = (
995
+ query,
996
+ key,
997
+ value,
998
+ out,
999
+ logsumexp,
1000
+ grad_out,
1001
+ grad_logsumexp,
1002
+ fw_graph,
1003
+ joint_graph,
1004
+ block_mask,
1005
+ scale,
1006
+ kernel_options,
1007
+ score_mod_other_buffers,
1008
+ mask_mod_other_buffers,
1009
+ )
1010
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
1011
+ out_proxy = proxy_mode.tracer.create_proxy(
1012
+ "call_function",
1013
+ flex_attention_backward,
1014
+ proxy_args,
1015
+ {},
1016
+ name="flex_attention_backward",
1017
+ )
1018
+ return track_tensor_tree(
1019
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
1020
+ )
1021
+
1022
+
1023
+ @flex_attention_backward.py_impl(ProxyTorchDispatchMode)
1024
+ def flex_attention_backward_proxy_torch_dispatch_mode(
1025
+ mode: ProxyTorchDispatchMode,
1026
+ query: torch.Tensor,
1027
+ key: torch.Tensor,
1028
+ value: torch.Tensor,
1029
+ out: torch.Tensor,
1030
+ logsumexp: torch.Tensor,
1031
+ grad_out: torch.Tensor,
1032
+ grad_logsumexp: torch.Tensor,
1033
+ fw_graph: Union[Callable, GraphModule],
1034
+ joint_graph: GraphModule,
1035
+ block_mask: tuple,
1036
+ scale: float,
1037
+ kernel_options: dict[str, Any],
1038
+ score_mod_other_buffers: tuple = (),
1039
+ mask_mod_other_buffers: tuple = (),
1040
+ ) -> tuple[
1041
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1042
+ ]:
1043
+ assert mode is not None, "Mode should always be enabled for python fallback key"
1044
+ return trace_flex_attention_backward(
1045
+ mode,
1046
+ query,
1047
+ key,
1048
+ value,
1049
+ out,
1050
+ logsumexp,
1051
+ grad_out,
1052
+ grad_logsumexp,
1053
+ fw_graph,
1054
+ joint_graph,
1055
+ block_mask,
1056
+ scale,
1057
+ kernel_options,
1058
+ score_mod_other_buffers,
1059
+ mask_mod_other_buffers,
1060
+ )
1061
+
1062
+
1063
+ @flex_attention_backward.py_functionalize_impl
1064
+ def flex_attention_backward_functionalize(
1065
+ ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
1066
+ query: torch.Tensor,
1067
+ key: torch.Tensor,
1068
+ value: torch.Tensor,
1069
+ out: torch.Tensor,
1070
+ logsumexp: torch.Tensor,
1071
+ grad_out: torch.Tensor,
1072
+ grad_logsumexp: torch.Tensor,
1073
+ fw_graph: Union[Callable, GraphModule],
1074
+ joint_graph: GraphModule,
1075
+ block_mask: tuple,
1076
+ scale: float,
1077
+ kernel_options: dict[str, Any],
1078
+ score_mod_other_buffers: tuple = (),
1079
+ mask_mod_other_buffers: tuple = (),
1080
+ ) -> tuple[
1081
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1082
+ ]:
1083
+ """Defines the functionalization rules for the flex_attention operator.
1084
+
1085
+ Write now we are unwrapping each tensor and then redispatching to the next,
1086
+ since we know that the forward score mod function is assured to be free of mutations
1087
+ to the other_buffers, we skip that mutate check and go straight to redispatching.
1088
+ """
1089
+ query_unwrapped = ctx.unwrap_tensors(query)
1090
+ key_unwrapped = ctx.unwrap_tensors(key)
1091
+ value_unwrapped = ctx.unwrap_tensors(value)
1092
+ out_unwrapped = ctx.unwrap_tensors(out)
1093
+ logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp)
1094
+ grad_out_unwrapped = ctx.unwrap_tensors(grad_out)
1095
+ grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp)
1096
+ block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
1097
+ score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
1098
+ mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
1099
+
1100
+ # Appease the mypy overlords
1101
+ assert isinstance(query_unwrapped, torch.Tensor)
1102
+ assert isinstance(key_unwrapped, torch.Tensor)
1103
+ assert isinstance(value_unwrapped, torch.Tensor)
1104
+ assert isinstance(out_unwrapped, torch.Tensor)
1105
+ assert isinstance(logsumexp_unwrapped, torch.Tensor)
1106
+ assert isinstance(grad_out_unwrapped, torch.Tensor)
1107
+ assert isinstance(grad_logsumexp_unwrapped, torch.Tensor)
1108
+ assert isinstance(block_mask_unwrapped, tuple)
1109
+ assert isinstance(score_mod_other_buffers_unwrapped, tuple)
1110
+ assert isinstance(mask_mod_other_buffers_unwrapped, tuple)
1111
+
1112
+ with ctx.redispatch_to_next():
1113
+ functional_fw_graph = ctx.functionalize(fw_graph)
1114
+ functional_joint_graph = ctx.functionalize(joint_graph)
1115
+
1116
+ (
1117
+ grad_query,
1118
+ grad_key,
1119
+ grad_value,
1120
+ grad_score_mod_captured,
1121
+ ) = flex_attention_backward(
1122
+ query_unwrapped,
1123
+ key_unwrapped,
1124
+ value_unwrapped,
1125
+ out_unwrapped,
1126
+ logsumexp_unwrapped,
1127
+ grad_out_unwrapped,
1128
+ grad_logsumexp_unwrapped,
1129
+ functional_fw_graph, # type: ignore[arg-type]
1130
+ functional_joint_graph, # type: ignore[arg-type]
1131
+ block_mask_unwrapped,
1132
+ scale,
1133
+ kernel_options,
1134
+ score_mod_other_buffers_unwrapped,
1135
+ mask_mod_other_buffers_unwrapped,
1136
+ )
1137
+
1138
+ return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type]
1139
+
1140
+
1141
+ @flex_attention_backward.py_impl(FakeTensorMode)
1142
+ def flex_attention_backward_fake_tensor_mode(
1143
+ mode: FakeTensorMode,
1144
+ query: torch.Tensor,
1145
+ key: torch.Tensor,
1146
+ value: torch.Tensor,
1147
+ out: torch.Tensor,
1148
+ logsumexp: torch.Tensor,
1149
+ grad_out: torch.Tensor,
1150
+ grad_logsumexp: torch.Tensor,
1151
+ fw_graph: Union[Callable, GraphModule],
1152
+ joint_graph: GraphModule,
1153
+ block_mask: tuple,
1154
+ scale: float,
1155
+ kernel_options: dict[str, Any],
1156
+ score_mod_other_buffers: tuple = (),
1157
+ mask_mod_other_buffers: tuple = (),
1158
+ ) -> tuple[
1159
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1160
+ ]:
1161
+ with mode:
1162
+ Bq, _, _, qk_head_dim = query.shape
1163
+ Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
1164
+
1165
+ grad_query = torch.empty_like(query)
1166
+ # zeros_and_scatter creates a contiguous zeros tensor -> contiguous_format
1167
+ grad_score_mod_captured = tuple(
1168
+ [
1169
+ torch.empty_like(buffer, memory_format=torch.contiguous_format)
1170
+ if isinstance(buffer, torch.Tensor) and buffer.requires_grad
1171
+ else None
1172
+ for buffer in score_mod_other_buffers
1173
+ ]
1174
+ )
1175
+
1176
+ broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
1177
+ broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride())
1178
+
1179
+ broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
1180
+ broadcasted_grad_value = _permute_strides(
1181
+ broadcasted_grad_value, value.stride()
1182
+ )
1183
+
1184
+ if Bq > 1 and Bkv == 1:
1185
+ grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True)
1186
+ grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True)
1187
+ else:
1188
+ grad_key = broadcasted_grad_key
1189
+ grad_value = broadcasted_grad_value
1190
+
1191
+ return grad_query, grad_key, grad_value, grad_score_mod_captured
1192
+
1193
+
1194
+ flex_attention_backward.py_impl(DispatchKey.Autograd)(
1195
+ autograd_not_implemented(flex_attention_backward, deferred_error=True)
1196
+ )
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/foreach_map.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ from typing import Any, Callable
4
+
5
+ from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
6
+
7
+
8
+ class ForeachMap(BaseHOP):
9
+ def __init__(self):
10
+ super().__init__("foreach_map")
11
+
12
+ def __call__(self, fn, *operands, **kwargs): # type: ignore[override]
13
+ fn = FunctionWithNoFreeVars(fn)
14
+ return super().__call__(fn, *operands, **kwargs)
15
+
16
+
17
+ _foreach_map = ForeachMap()
18
+
19
+
20
+ def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]):
21
+ from torch._dynamo.polyfills import foreach_map_fn
22
+
23
+ return _foreach_map(foreach_map_fn, op, *operands, **kwargs)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/hints_wrap.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.utils._pytree as pytree
4
+ from torch._C import DispatchKey
5
+ from torch._higher_order_ops.utils import (
6
+ _has_potential_branch_input_alias,
7
+ _has_potential_branch_input_mutation,
8
+ autograd_not_implemented,
9
+ reenter_make_fx,
10
+ unique_graph_id,
11
+ UnsupportedAliasMutationException,
12
+ )
13
+ from torch._ops import HigherOrderOperator
14
+ from torch._subclasses.fake_tensor import FakeTensorMode
15
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
16
+
17
+
18
+ # used for wrapping a function/op with context hints
19
+ class HintsWrapper(HigherOrderOperator):
20
+ def __init__(self):
21
+ super().__init__("hints_wrapper")
22
+
23
+ def __call__(self, body_fn, args, kwargs, hints):
24
+ r"""
25
+ Call implementation of hints_wrapper
26
+
27
+ Args:
28
+ body_fn (Callable): A callable function that is within the scope
29
+ that is being traced.
30
+
31
+ args (Tuple of torch.Tensor/int/float/bool): A tuple of inputs to
32
+ body_fn.
33
+
34
+ kwargs (dict): Keyword argument to the body_fn.
35
+
36
+ hints (dict): A dict of context hints which could be passed to
37
+ backend compiler.
38
+ """
39
+ if not isinstance(args, tuple):
40
+ raise RuntimeError(f"args must be a tuple, got {type(args)}")
41
+
42
+ if not all(isinstance(t, (torch.Tensor, int, float, bool)) for t in args):
43
+ raise RuntimeError(
44
+ "args must be a tuple of tensors, ints, floats, or bools, got "
45
+ f"{args}"
46
+ )
47
+
48
+ if not isinstance(kwargs, dict):
49
+ raise RuntimeError(f"kwargs must be a dict, got {type(kwargs)}")
50
+
51
+ if len(kwargs) > 0:
52
+ raise RuntimeError(
53
+ f"kwargs except for hints are not supported, got {kwargs}"
54
+ )
55
+
56
+ if not isinstance(hints, dict):
57
+ raise RuntimeError(f"hints must be a dict, got {type(hints)}")
58
+
59
+ for k, v in hints.items():
60
+ if not isinstance(k, str):
61
+ raise RuntimeError(f"hints key must be a str, got {k}.")
62
+
63
+ if not isinstance(v, (int, float, bool, str)):
64
+ raise RuntimeError(
65
+ "hints must be a dict containing int, float, bool or str "
66
+ f"value, got value {v} for key {k}."
67
+ )
68
+
69
+ return super().__call__(body_fn, args, kwargs, hints)
70
+
71
+
72
+ hints_wrapper = HintsWrapper()
73
+
74
+
75
+ @hints_wrapper.py_impl(DispatchKey.CompositeExplicitAutograd)
76
+ def hints_wrapper_dense(body_fn, args, kwargs, hints):
77
+ return body_fn(*args, **kwargs)
78
+
79
+
80
+ hints_wrapper.py_impl(DispatchKey.Autograd)(
81
+ autograd_not_implemented(hints_wrapper, deferred_error=True)
82
+ )
83
+
84
+
85
+ @hints_wrapper.py_impl(FakeTensorMode)
86
+ def hints_wrapper_fake_tensor_mode(mode, body_func, args, kwargs, hints):
87
+ flat_args = pytree.tree_leaves(args)
88
+ with mode:
89
+ return body_func(*flat_args, **kwargs)
90
+
91
+
92
+ @hints_wrapper.py_functionalize_impl
93
+ def hints_wrapper_functionalize(ctx, body_fn, args, kwargs, hints):
94
+ unwrapped_args = ctx.unwrap_tensors(args)
95
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
96
+ unwrapped_hints = ctx.unwrap_tensors(hints)
97
+ with ctx.redispatch_to_next():
98
+ functional_body_fn = ctx.functionalize(body_fn)
99
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
100
+ if _has_potential_branch_input_mutation(
101
+ body_fn, unwrapped_args, pre_dispatch=pre_dispatch
102
+ ):
103
+ raise UnsupportedAliasMutationException(
104
+ "body_fn of hints_wrapper might be modifying the input!"
105
+ )
106
+ if _has_potential_branch_input_alias(
107
+ body_fn, unwrapped_args, pre_dispatch=pre_dispatch
108
+ ):
109
+ raise UnsupportedAliasMutationException(
110
+ "body_fn of hints_wrapper might be aliasing the input!"
111
+ )
112
+ outputs = hints_wrapper(
113
+ functional_body_fn,
114
+ unwrapped_args,
115
+ unwrapped_kwargs,
116
+ unwrapped_hints,
117
+ )
118
+ return ctx.wrap_tensors(outputs)
119
+
120
+
121
+ def trace_hints_wrapper(proxy_mode, hints_wrapper, body_fn, args, kwargs, hints):
122
+ flat_args = tuple(pytree.tree_leaves(args))
123
+ body_graph = reenter_make_fx(body_fn)(*flat_args, **kwargs)
124
+
125
+ _, body_graph_name = unique_graph_id(proxy_mode, prefix="hints_wrapper_body_graph")
126
+ proxy_mode.tracer.root.register_module(body_graph_name, body_graph)
127
+
128
+ new_args: tuple = (body_graph, flat_args, {})
129
+ # merge hints into kwargs
130
+ new_kwargs = {}
131
+ new_kwargs["hints"] = hints
132
+
133
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_args)
134
+ proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_kwargs)
135
+
136
+ out_proxy = proxy_mode.tracer.create_proxy(
137
+ "call_function", hints_wrapper, proxy_args, proxy_kwargs, name="hints_wrapper"
138
+ )
139
+
140
+ out = body_fn(*flat_args, **kwargs)
141
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
142
+
143
+
144
+ @hints_wrapper.py_impl(ProxyTorchDispatchMode)
145
+ def inner(proxy_mode, body_fn, args, kwargs, hints):
146
+ if proxy_mode.enable_tracing:
147
+ return trace_hints_wrapper(
148
+ proxy_mode, hints_wrapper, body_fn, args, kwargs, hints
149
+ )
150
+ else:
151
+ return hints_wrapper(body_fn, args, kwargs, hints)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_subgraph.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+
4
+ from typing import Optional, Union
5
+
6
+ import torch
7
+ import torch.utils._pytree as pytree
8
+ from torch._C import DispatchKey
9
+ from torch._dispatch.python import suspend_functionalization
10
+ from torch._higher_order_ops.utils import (
11
+ _from_fun,
12
+ _maybe_reenter_make_fx,
13
+ clone_outputs_aliasing_inputs,
14
+ get_dummy_aot_autograd_config,
15
+ prepare_fw_with_masks,
16
+ reenter_make_fx,
17
+ save_tensors_and_symints_for_backward,
18
+ saved_tensors_and_symints,
19
+ )
20
+ from torch._ops import HigherOrderOperator
21
+ from torch._subclasses import FakeTensorMode
22
+ from torch._subclasses.functional_tensor import disable_functional_mode
23
+ from torch.fx.experimental.proxy_tensor import (
24
+ disable_proxy_modes_tracing,
25
+ ProxyTorchDispatchMode,
26
+ track_tensor_tree,
27
+ )
28
+ from torch.fx.graph_module import GraphModule
29
+
30
+
31
+ invoke_subgraph_counter = 0
32
+
33
+
34
+ class InvokeSubgraphHOP(HigherOrderOperator):
35
+ def __init__(self) -> None:
36
+ super().__init__("invoke_subgraph")
37
+
38
+ # identifier is setup by upper part of the stack. This helps us in
39
+ # identifying two invoke_subgraph calls have same subgraph.
40
+ def __call__(
41
+ self,
42
+ subgraph: GraphModule,
43
+ identifier: Optional[str],
44
+ operands: Union[
45
+ list[Union[torch.Tensor, int, torch.SymInt]],
46
+ tuple[Union[torch.Tensor, int, torch.SymInt]],
47
+ ],
48
+ ):
49
+ assert identifier is None or isinstance(
50
+ identifier, str
51
+ ), "identifier must be a None or a string"
52
+
53
+ assert isinstance(
54
+ operands, (list, tuple)
55
+ ), f"invoke_subgraph operands must be a list or tuple of tensors/ints/SymInts {operands}"
56
+ assert all(
57
+ isinstance(o, (torch.Tensor, int, torch.SymInt)) for o in operands
58
+ ), f"invoke_subgraph operands must be a list of tensors/ints/SymInts {operands}"
59
+
60
+ return super().__call__(subgraph, identifier, operands)
61
+
62
+
63
+ invoke_subgraph = InvokeSubgraphHOP()
64
+
65
+
66
+ def invoke_subgraph_placeholder(subgraph, *args, **kwargs):
67
+ # Just a placeholder for Dynamo to replace with invoke_subgraph
68
+ return subgraph(*args, **kwargs)
69
+
70
+
71
+ def mark_compile_region(fn=None):
72
+ """
73
+ This wrapper instructs torch.compile to compile the wrapped region once and
74
+ reuse the compiled artifact, instead of the usual way of aggressively
75
+ inlining the function.
76
+
77
+ Under the hood, it tells TorchDynamo to use InvokeSubgraph HOP for the
78
+ region. For PyTorch eager, this is a no-op.
79
+ """
80
+
81
+ def wrap(func):
82
+ def inner(*args, **kwargs):
83
+ return invoke_subgraph_placeholder(func, *args, **kwargs)
84
+
85
+ return inner
86
+
87
+ if fn:
88
+ return wrap(fn)
89
+ else:
90
+ return wrap
91
+
92
+
93
+ def get_invoke_subgraph_cache():
94
+ cache = None
95
+ if tracing_ctx := torch._guards.TracingContext.try_get():
96
+ cache = tracing_ctx.hop_dispatch_set_cache.get_cache(invoke_subgraph)
97
+ return cache
98
+
99
+
100
+ def trace_joint_graph(fn, fw_inputs, fw_outputs):
101
+ """
102
+ Naively trace out a joint graph. This simplifies the reconstruction of joint
103
+ graph in the min-cut partitioner later on.
104
+ """
105
+ from torch._functorch.aot_autograd import create_joint
106
+
107
+ dummy_aot_config = get_dummy_aot_autograd_config()
108
+
109
+ # This joint_fn is inserted as the backward graph as is. This simplifies the
110
+ # min-cut partitioner work later on.
111
+ # Input signature - (*primals, *tangents)
112
+ # Output signature - (*grads, *fw_outs)
113
+ # The output signature is deliberately kept grads first and fw_outs second.
114
+ # Having grads first makes the min-cut partitioner HOP graph stitching
115
+ # easier.
116
+ def joint_fn(*primals_and_tangents):
117
+ primals = primals_and_tangents[: len(fw_inputs)]
118
+ tangents = primals_and_tangents[len(fw_inputs) :]
119
+
120
+ fw_outs, grads = create_joint(
121
+ prepare_fw_with_masks(fn), aot_config=dummy_aot_config
122
+ )(primals, tangents)
123
+
124
+ maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
125
+
126
+ # return signature is deliberately kept (*grads, *fw_outs). This
127
+ # simplifies partitioning work later on.
128
+ return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs)))
129
+
130
+ primals = list(fw_inputs)
131
+ # This assumes that the tangent strides match fw_outputs strides. Check the
132
+ # InvokeSubgraphAutogradOp backward op for the contiguous call.
133
+ tangents = [_from_fun(out) for out in fw_outputs]
134
+
135
+ joint_operands = primals + tangents
136
+
137
+ return _maybe_reenter_make_fx(joint_fn)(*joint_operands)
138
+
139
+
140
+ def create_fw_bw_graph(subgraph, operands, grad_outputs=None):
141
+ with suspend_functionalization(), disable_functional_mode():
142
+ with disable_proxy_modes_tracing():
143
+ # args are functional tensors, generate some example tensors
144
+ fw_inputs = pytree.tree_map(_from_fun, operands)
145
+
146
+ if grad_outputs is None:
147
+ # Infer grad_outputs to be the same properties as the fw_outputs
148
+ # if they're not passed in.
149
+ grad_outputs = pytree.tree_map(_from_fun, subgraph(*fw_inputs))
150
+ if any(
151
+ not isinstance(out, torch.Tensor)
152
+ for out in grad_outputs
153
+ if out is not None
154
+ ):
155
+ raise RuntimeError(
156
+ "Expect outputs of invoke_subgraph to only contains tensors or None. "
157
+ f"Got types {[type(out) for out in grad_outputs]}."
158
+ )
159
+
160
+ # Trace the forward subgraph
161
+ fw_graph = _maybe_reenter_make_fx(subgraph)(*fw_inputs)
162
+
163
+ # Trace the joint graph and assign it to the bwd graph
164
+ bw_graph = trace_joint_graph(
165
+ subgraph,
166
+ fw_inputs,
167
+ grad_outputs,
168
+ )
169
+ return fw_graph, bw_graph, len(grad_outputs)
170
+
171
+
172
+ class InvokeSubgraphAutogradOp(torch.autograd.Function):
173
+ """
174
+ This autograd function op is to stash the backward graph in the ctx while
175
+ running forward.
176
+ """
177
+
178
+ @staticmethod
179
+ def forward(ctx, fw_graph, bw_graph, identifier, num_fw_outs, *operands):
180
+ ctx._fw_graph = fw_graph
181
+ ctx._bw_graph = bw_graph
182
+ ctx._identifier = identifier
183
+ ctx._num_fw_outs = num_fw_outs
184
+
185
+ with torch._C._AutoDispatchBelowAutograd():
186
+ out = invoke_subgraph(
187
+ fw_graph,
188
+ f"___forward_{identifier}",
189
+ operands,
190
+ )
191
+
192
+ save_tensors_and_symints_for_backward(ctx, operands)
193
+ return out
194
+
195
+ @staticmethod
196
+ def backward(ctx, *grad_outs):
197
+ bw_graph = ctx._bw_graph
198
+ identifier = ctx._identifier
199
+ primals = saved_tensors_and_symints(ctx)
200
+ num_fw_outs = ctx._num_fw_outs
201
+
202
+ # While tracing we made the assumption that tangents are contiguous. So,
203
+ # force the grad_outs to be contiguous.
204
+ contiguous_grad_outs = tuple([o.contiguous() for o in grad_outs])
205
+
206
+ # bw_graph is a joint graph with signature (*primals_and_tangents) and
207
+ # returns (*grads_and_fw_outs). To get the grads, we use the num_fw_outs
208
+ # to extract the grads.
209
+ primals_and_tangents = primals + contiguous_grad_outs
210
+ grads = invoke_subgraph(
211
+ bw_graph, f"___backward_{identifier}", primals_and_tangents
212
+ )[:-num_fw_outs]
213
+ return None, None, None, None, *grads
214
+
215
+
216
+ @invoke_subgraph.py_impl(DispatchKey.CompositeExplicitAutograd)
217
+ def _(subgraph, identifier, operands):
218
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
219
+
220
+ mode = _get_current_dispatch_mode()
221
+ assert mode is None, "Mode should never be enabled for CPU/CUDA key"
222
+ return subgraph(*operands)
223
+
224
+
225
+ @invoke_subgraph.py_impl(DispatchKey.Autograd)
226
+ def _(subgraph, identifier, operands):
227
+ if not torch.is_grad_enabled():
228
+ with torch._C._AutoDispatchBelowAutograd():
229
+ return invoke_subgraph(subgraph, identifier, operands)
230
+
231
+ # A shortcut for the case where all inputs don't require gradient,
232
+ # we skip tracing the forward and backward graph.
233
+ if pytree.tree_all_only(
234
+ torch.Tensor,
235
+ lambda t: not t.requires_grad, # type: ignore[union-attr]
236
+ operands,
237
+ ):
238
+ with torch._C._AutoDispatchBelowAutograd():
239
+ return invoke_subgraph(subgraph, identifier, operands)
240
+
241
+ # Check if we have already traced the subgraph.
242
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
243
+ if invoke_subgraph_cache:
244
+ if saved_autograd_fn := invoke_subgraph_cache.get_autograd_key_entry(
245
+ identifier
246
+ ):
247
+ return saved_autograd_fn(*operands)
248
+
249
+ fw_graph, bw_graph, num_fw_outs = create_fw_bw_graph(subgraph, operands)
250
+
251
+ def autograd_fn_callable(*args):
252
+ return InvokeSubgraphAutogradOp.apply(
253
+ fw_graph, bw_graph, identifier, num_fw_outs, *args
254
+ )
255
+
256
+ # Save the autograd_fn_callable in the dispatch set cache.
257
+ if invoke_subgraph_cache:
258
+ invoke_subgraph_cache.add_autograd_key_entry(identifier, autograd_fn_callable)
259
+
260
+ return autograd_fn_callable(*operands)
261
+
262
+
263
+ @invoke_subgraph.py_functionalize_impl
264
+ def _(ctx, subgraph, identifier, operands):
265
+ unwrapped_operands = ctx.unwrap_tensors(operands)
266
+ with ctx.redispatch_to_next():
267
+ # NB: There is an assumption that subgraph does not mutate inputs and
268
+ # there is no aliasing. Its Dynamo responsibility to prevent formation
269
+ # of invoke_subgraph ops if input aliasing/mutation is detected.
270
+ functionalized_subgraph = ctx.functionalize(subgraph)
271
+ out = invoke_subgraph(functionalized_subgraph, identifier, unwrapped_operands)
272
+ return ctx.wrap_tensors(out)
273
+
274
+
275
+ @invoke_subgraph.py_impl(FakeTensorMode)
276
+ def _(mode, subgraph, identifier, operands):
277
+ # TODO(anijain2305) - Implement fake tensor caching.
278
+ with mode:
279
+ return subgraph(*operands)
280
+
281
+
282
+ @invoke_subgraph.py_impl(ProxyTorchDispatchMode)
283
+ def _(proxy_mode: ProxyTorchDispatchMode, subgraph, identifier, operands):
284
+ # Check if we have already traced the subgraph.
285
+ graph = None
286
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
287
+ if invoke_subgraph_cache:
288
+ graph = invoke_subgraph_cache.get_proxy_dispatch_entry(identifier)
289
+
290
+ if graph is None:
291
+ graph = reenter_make_fx(subgraph)(*operands)
292
+ assert isinstance(proxy_mode.tracer, torch.fx.Tracer)
293
+ qualname = proxy_mode.tracer.get_fresh_qualname("repeated_subgraph")
294
+ proxy_mode.tracer.root.register_module(qualname, graph)
295
+ if invoke_subgraph_cache:
296
+ invoke_subgraph_cache.add_proxy_dispatch_entry(identifier, graph)
297
+
298
+ node_args = (graph, identifier, operands)
299
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[union-attr]
300
+ out_proxy = proxy_mode.tracer.create_proxy(
301
+ "call_function", invoke_subgraph, proxy_args, {}
302
+ )
303
+
304
+ example_out = invoke_subgraph(graph, identifier, operands)
305
+ return track_tensor_tree(
306
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
307
+ )