FaustDerLegende commited on
Commit
3829c5f
·
verified ·
1 Parent(s): adae81d

Upload folder using huggingface_hub (part 21)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +23 -0
  2. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py +979 -0
  3. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py +623 -0
  4. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py +140 -0
  5. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py +784 -0
  6. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py +999 -0
  7. .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py +907 -0
  8. .venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py +1971 -0
  9. .venv/lib/python3.12/site-packages/torch/_functorch/apis.py +510 -0
  10. .venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py +935 -0
  11. .venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py +27 -0
  12. .venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py +245 -0
  13. .venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py +306 -0
  14. .venv/lib/python3.12/site-packages/torch/_functorch/compilers.py +505 -0
  15. .venv/lib/python3.12/site-packages/torch/_functorch/config.py +464 -0
  16. .venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py +188 -0
  17. .venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py +1960 -0
  18. .venv/lib/python3.12/site-packages/torch/_functorch/einops.py +74 -0
  19. .venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py +264 -0
  20. .venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py +562 -0
  21. .venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py +669 -0
  22. .venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py +0 -0
  23. .venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py +297 -0
  24. .venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py +338 -0
  25. .venv/lib/python3.12/site-packages/torch/_functorch/python_key.py +15 -0
  26. .venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py +23 -0
  27. .venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py +630 -0
  28. .venv/lib/python3.12/site-packages/torch/_functorch/utils.py +30 -0
  29. .venv/lib/python3.12/site-packages/torch/_functorch/vmap.py +567 -0
  30. .venv/lib/python3.12/site-packages/torch/_guards.py +1610 -0
  31. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py +91 -0
  32. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc +0 -0
  33. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc +0 -0
  34. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc +0 -0
  35. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc +0 -0
  36. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc +0 -0
  37. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc +0 -0
  38. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc +0 -0
  39. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc +0 -0
  40. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc +0 -0
  42. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc +0 -0
  45. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc +0 -0
  46. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc +0 -0
  47. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc +0 -0
  49. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc +0 -0
  50. .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -526,3 +526,26 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
526
  .venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
527
  .venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
528
  .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  .venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
527
  .venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
528
  .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
529
+ .venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
530
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
531
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
532
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
533
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
534
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
535
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
536
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
537
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
538
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
539
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
540
+ .venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
541
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
542
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
543
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
544
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
545
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
546
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
547
+ .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
548
+ .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
549
+ .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
550
+ .venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
551
+ .venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from collections.abc import Callable
3
+ from typing import Any, TYPE_CHECKING, TypeAlias
4
+
5
+ import torch.fx
6
+ import torch.fx.traceback
7
+ import torch.utils._pytree as pytree
8
+ from torch._dynamo.graph_utils import _get_flat_args
9
+ from torch._dynamo.variables.streams import get_current_stream, new_event
10
+ from torch.fx.node import map_arg
11
+ from torch.utils._ordered_set import OrderedSet
12
+ from torch.utils._runtime_estimation import (
13
+ _FLOAT_TYPES,
14
+ _IGNORE_OPS,
15
+ get_compute_time,
16
+ get_transfer_time,
17
+ )
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .schemas import ViewAndMutationMeta
22
+
23
+ from .indexed_dict import IndexedDict
24
+
25
+
26
+ aten = torch.ops.aten
27
+
28
+ Node: TypeAlias = torch.fx.Node
29
+ Graph: TypeAlias = torch.fx.Graph
30
+ Partition: TypeAlias = bool
31
+
32
+ FORWARD: Partition = False
33
+ BACKWARD: Partition = True
34
+ _EMPTY_LOCATIONS: frozenset[tuple[Partition, int]] = frozenset()
35
+
36
+ _SYNC_OPS = (
37
+ torch.ops.streams.record_event.default,
38
+ torch.ops.streams.wait_event.default,
39
+ torch.ops.streams.wait_stream.default,
40
+ torch.ops.streams.synchronize_event.default,
41
+ torch.ops.streams.synchronize_device.default,
42
+ torch.ops.streams.synchronize_stream.default,
43
+ )
44
+
45
+
46
+ def get_roofline_estimate(node: Node) -> float:
47
+ if node.op != "call_function":
48
+ raise AssertionError(f"non-func node in roofline estimate: {node.op}")
49
+
50
+ def map_value(x: Any) -> Any:
51
+ return x.meta.get("value", x) if isinstance(x, Node) else x
52
+
53
+ func = node.target
54
+ if func in _IGNORE_OPS:
55
+ return 0.0
56
+
57
+ mapped_args = torch.fx.map_arg(node.args, map_value)
58
+ mapped_kwargs = torch.fx.map_arg(node.kwargs, map_value)
59
+ flat_args_kwargs = [map_value(x) for x in _get_flat_args(node, {})]
60
+ flat_outs, _ = pytree.tree_flatten(node.meta.get("value", node))
61
+ out = node.meta.get("value", node)
62
+ out_dtypes = {
63
+ t.dtype
64
+ for t in flat_outs
65
+ if isinstance(t, torch.Tensor) and t.dtype in _FLOAT_TYPES
66
+ }
67
+
68
+ return (
69
+ max(
70
+ get_transfer_time(flat_args_kwargs, flat_outs),
71
+ get_compute_time(func, mapped_args, mapped_kwargs, out, out_dtypes),
72
+ )
73
+ / 1e6
74
+ )
75
+
76
+
77
+ def is_gradient_acc(node: Node) -> bool:
78
+ return node.meta.get("is_gradient_acc", False)
79
+
80
+
81
+ def is_bwd_node(node: Node) -> Partition:
82
+ tag = node.meta.get("partitioner_tag")
83
+ return tag == "is_backward" or tag == "must_be_in_backward"
84
+
85
+
86
+ def get_device(node: Node) -> torch.device:
87
+ return node.meta["val"].device
88
+
89
+
90
+ def get_stream(node: Node) -> int | None:
91
+ maybe_annotation = node.meta.get("custom", None)
92
+ if maybe_annotation is not None:
93
+ return node.meta["custom"].get("stream", None)
94
+ else:
95
+ return None
96
+
97
+
98
+ def get_stream_or_current_stream(node: Node) -> int:
99
+ ind = get_stream(node)
100
+ if ind is None:
101
+ ind = get_current_stream(get_device(node))
102
+ return ind
103
+
104
+
105
+ def set_stream(node: Node, ind: int) -> None:
106
+ if "custom" in node.meta:
107
+ node.meta["custom"].update({"stream": ind})
108
+ else:
109
+ node.meta["custom"] = {"stream": ind}
110
+
111
+
112
+ def insert_record_event_after_node(graph: Graph, node: Node, event_ind: int) -> Node:
113
+ with graph.inserting_after(node):
114
+ node = graph.call_function(
115
+ torch.ops.streams.record_event.default,
116
+ (
117
+ event_ind,
118
+ get_stream_or_current_stream(node),
119
+ ),
120
+ )
121
+ node.meta["partitioner_tag"] = "must_be_in_backward"
122
+
123
+ return node
124
+
125
+
126
+ def insert_wait_event_before_node(graph: Graph, node: Node, event_ind: int) -> Node:
127
+ with graph.inserting_before(node):
128
+ node = graph.call_function(
129
+ torch.ops.streams.wait_event.default,
130
+ (
131
+ event_ind,
132
+ get_stream_or_current_stream(node),
133
+ ),
134
+ )
135
+ node.meta["partitioner_tag"] = "must_be_in_backward"
136
+
137
+ return node
138
+
139
+
140
+ def populate_stream_timeline(
141
+ stream_to_timeline: dict[int | None, IndexedDict[Node, float]],
142
+ graph: Graph,
143
+ stream_index: int | None,
144
+ ) -> IndexedDict[Node, float]:
145
+ if stream_index not in stream_to_timeline:
146
+ stream_to_timeline[stream_index] = IndexedDict()
147
+ total_time = 0.0
148
+ for node in graph.nodes:
149
+ # mlazos: not sure if we should include forward here too but don't think it matters
150
+ if (
151
+ node.op == "call_function"
152
+ and is_bwd_node(node)
153
+ and get_stream(node) == stream_index
154
+ ):
155
+ total_time += get_roofline_estimate(node)
156
+ stream_to_timeline[stream_index][node] = (
157
+ total_time # NB: total time includes the node's runtime
158
+ )
159
+
160
+ return stream_to_timeline[stream_index]
161
+
162
+
163
+ # NB: we start all estimates at 0, estimating the total runtime of each stream with timestamps at each node
164
+ # we then try and use these timestamps to estimate when to deallocate tensors used in side streams
165
+ # See https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream
166
+ # for details on the problem being addressed. Rather than using the automatic memory management approach of record_stream
167
+ # we attempt to find the point which to deallocate based on the estimated timestamps.
168
+ def handle_synced_deallocation(
169
+ graph: Graph,
170
+ stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]],
171
+ node: Node,
172
+ last_usage: Node,
173
+ ) -> None:
174
+ if not is_bwd_node(node):
175
+ raise AssertionError(
176
+ "synced allocations should only be handled on backward nodes"
177
+ )
178
+ if not is_bwd_node(last_usage):
179
+ raise AssertionError(
180
+ "synced allocations should only be handled on backward nodes"
181
+ )
182
+ allocating_stream = get_stream(node)
183
+ side_stream = get_stream(last_usage)
184
+ if allocating_stream == side_stream:
185
+ raise AssertionError(
186
+ "allocating and side stream should be different for synced deallocations"
187
+ )
188
+ if not torch.accelerator.is_available():
189
+ # fallback to record_stream in this case
190
+ with graph.inserting_after(node):
191
+ rs = graph.call_function(
192
+ torch.ops.streams.record_stream.default,
193
+ (
194
+ node,
195
+ get_stream_or_current_stream(last_usage),
196
+ ),
197
+ {},
198
+ )
199
+ rs.meta["partitioner_tag"] = "must_be_in_backward"
200
+
201
+ allocating_stream_trace = populate_stream_timeline(
202
+ stream_to_exec_trace, graph, allocating_stream
203
+ )
204
+ side_stream_trace = populate_stream_timeline(
205
+ stream_to_exec_trace, graph, side_stream
206
+ )
207
+
208
+ alloc_ptr = node
209
+ target_side_stream_time = side_stream_trace[last_usage]
210
+ # linear search from first usage of tensor to a point in time after the side stream has finished
211
+ while alloc_ptr is not None:
212
+ alloc_time = allocating_stream_trace[alloc_ptr]
213
+
214
+ if alloc_time >= target_side_stream_time:
215
+ break
216
+ elif alloc_time < target_side_stream_time:
217
+ next_ptr = allocating_stream_trace.next_key(alloc_ptr)
218
+ if next_ptr is not None:
219
+ alloc_ptr = next_ptr
220
+ else:
221
+ break
222
+
223
+ wait_event = new_event()
224
+ record_node = insert_record_event_after_node(graph, last_usage, wait_event)
225
+ with graph.inserting_after(max(alloc_ptr, record_node)):
226
+ sd = graph.call_function(
227
+ torch.ops.streams.sync_dealloc.default,
228
+ (wait_event, get_stream_or_current_stream(alloc_ptr), node),
229
+ {},
230
+ )
231
+ sd.meta["partitioner_tag"] = "must_be_in_backward"
232
+
233
+
234
+ def insert_sync(
235
+ graph: Graph,
236
+ consumer: Node,
237
+ producer: Node,
238
+ node_to_wait_event_ind: dict[Node, int],
239
+ ) -> None:
240
+ if producer not in node_to_wait_event_ind:
241
+ node_to_wait_event_ind[producer] = new_event()
242
+
243
+ insert_record_event_after_node(
244
+ graph, producer, node_to_wait_event_ind[producer]
245
+ )
246
+ insert_wait_event_before_node(graph, consumer, node_to_wait_event_ind[producer])
247
+
248
+
249
+ def assign_backward_streams(gm: torch.fx.GraphModule) -> None:
250
+ """Assigns backward streams to gradient accumulation nodes"""
251
+
252
+ # NB: iterate in reverse order to more closely match eager
253
+ # the user node stream will be populated first
254
+ for node in reversed(list(gm.graph.nodes)):
255
+ if is_gradient_acc(node):
256
+ # Accumulation stream selection. Follow the rules from top to bottom to determine the accumulation stream:
257
+ # 1. Match first stream assignment of the first user with a stream
258
+ # 2. Match first stream assignment encountered in the args from left to right
259
+ # This differs from eager in some cases:
260
+ # Specifically the eager code uses the autograd node to determine the stream,
261
+ # crucially this does not necessarily correspond to the FX graph node. For example,
262
+ # in the backward for an add node with a constant we will passthrough and during backward tracing,
263
+ # no op will be added to the FX graph, so our stream assignment will differ in this case.
264
+ gradients = _get_flat_args(node, {})
265
+ users = list(node.users.keys())
266
+
267
+ # All gradients will be on same device, they will be coerced if they were not with a .to() node
268
+ for neighbor in users + gradients:
269
+ ind = get_stream(neighbor)
270
+ if ind is not None:
271
+ set_stream(node, ind)
272
+ break
273
+
274
+
275
+ def insert_backward_syncs(gm: torch.fx.GraphModule) -> None:
276
+ """Inserts stream syncs for backward nodes if consumer and producer are on different streams"""
277
+ node_to_wait_event_ind: dict[Node, int] = {}
278
+ for node in gm.graph.nodes:
279
+ if node.op == "call_function" and is_bwd_node(node):
280
+ flat_args = _get_flat_args(node, {})
281
+ cur_node_stream = get_stream(node)
282
+
283
+ for arg in flat_args:
284
+ if arg.op == "call_function" and is_bwd_node(arg):
285
+ arg_stream = get_stream(arg)
286
+ if arg_stream != cur_node_stream and get_device(arg).type != "cpu":
287
+ insert_sync(gm.graph, node, arg, node_to_wait_event_ind)
288
+
289
+
290
+ def sync_deallocations(gm: torch.fx.GraphModule) -> None:
291
+ """Handles https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream"""
292
+ # Note: this is only needed if the last usage of a tensor is on a stream other than
293
+ # the stream the tensor was allocated on
294
+
295
+ # an estimated timestamp from the beginning of graph execution (assuming 0 CPU overhead)
296
+ # I think this is fine because you should have large tensors if you're using streams
297
+ # although perhaps I could add a constant 10us per op ahead of the first stream op?
298
+ # a trace of all the nodes running in a given stream
299
+ stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]] = {}
300
+ for node in gm.graph.nodes:
301
+ if node.op == "call_function" and is_bwd_node(node):
302
+ allocating_stream = get_stream(node)
303
+ users = list(node.users.keys())
304
+ if not users:
305
+ continue
306
+ last_user = max(user for user in users)
307
+ if last_user.op == "output":
308
+ continue
309
+ side_stream = get_stream(last_user)
310
+ if allocating_stream != side_stream:
311
+ handle_synced_deallocation(
312
+ gm.graph, stream_to_exec_trace, node, last_user
313
+ )
314
+
315
+
316
+ def assign_epilogue_copy_streams(gm: torch.fx.GraphModule) -> None:
317
+ for epi_copy in gm.graph.find_nodes(op="call_function", target=aten.copy_.default):
318
+ arg_stream = get_stream(epi_copy.args[1])
319
+ copy_stream = get_stream(epi_copy)
320
+ if arg_stream != copy_stream:
321
+ set_stream(epi_copy, get_stream_or_current_stream(epi_copy.args[1]))
322
+
323
+
324
+ def populate_fw_metadata_with_stream_indices(
325
+ gm: torch.fx.GraphModule, fw_metadata: "ViewAndMutationMeta"
326
+ ) -> None:
327
+ """
328
+ Populates fw_metadata.mutated_inp_stream_indices with stream indices from the compiled graph.
329
+
330
+ The forward graph outputs are structured as:
331
+ (*mutated_inputs, *user_outputs, *intermediate_bases, *saved_tensors, *saved_symints)
332
+
333
+ We extract the stream index for each mutated input from the graph's output node.
334
+ """
335
+
336
+ num_mutated_inps = fw_metadata.num_mutated_inp_runtime_indices
337
+ if num_mutated_inps == 0:
338
+ fw_metadata.mutated_inp_stream_indices = []
339
+ return
340
+
341
+ # Find the output node in the graph
342
+ output_node = None
343
+ for node in gm.graph.find_nodes(op="output"):
344
+ output_node = node
345
+ break
346
+
347
+ if output_node is None:
348
+ raise AssertionError(
349
+ "No output node found in the graph when extracting stream indices"
350
+ )
351
+
352
+ # The output node's args[0] is a tuple/list of all outputs
353
+ output_args = output_node.args[0]
354
+
355
+ # Extract stream indices for the first num_mutated_inps outputs
356
+ stream_indices = []
357
+ for i in range(num_mutated_inps):
358
+ if i < len(output_args):
359
+ output_arg = output_args[i]
360
+ # Get the stream index from the node metadata
361
+ stream_idx = (
362
+ get_stream(output_arg)
363
+ if isinstance(output_arg, torch.fx.Node)
364
+ else None
365
+ )
366
+ stream_indices.append(stream_idx)
367
+ else:
368
+ stream_indices.append(None)
369
+
370
+ fw_metadata.mutated_inp_stream_indices = stream_indices
371
+
372
+
373
+ def _expand_dict_returning_deps(
374
+ deps: list[Node],
375
+ visited: set[Node],
376
+ graph: torch.fx.Graph,
377
+ sync_node: Node,
378
+ ) -> list[Node]:
379
+ """Expand triton_kernel_wrapper_functional dict deps into per-key getitems.
380
+
381
+ ``triton_kernel_wrapper_functional`` returns a flat ``dict[str, Tensor]``.
382
+ If such a node is threaded through ``control_deps`` as a pass-through
383
+ value, ``decompose_triton_kernel_wrapper_functional`` later replaces it
384
+ with a raw Python dict, corrupting every user that expected an FX Node.
385
+
386
+ To avoid this, we insert ``operator.getitem`` nodes *before* the sync for
387
+ each after-sync getitem user, so that only tensor-valued nodes are passed
388
+ through ``control_deps``. The dict node may still appear in
389
+ ``additional_deps`` (ordering-only) which is safe since that tuple is
390
+ never decomposed.
391
+ """
392
+ expanded: list[Node] = []
393
+ for dep in deps:
394
+ if not (
395
+ dep.op == "call_function"
396
+ and dep.target is torch.ops.higher_order.triton_kernel_wrapper_functional
397
+ ):
398
+ expanded.append(dep)
399
+ continue
400
+
401
+ after_sync_getitems = [
402
+ user
403
+ for user in dep.users
404
+ if user not in visited
405
+ and user.op == "call_function"
406
+ and user.target is operator.getitem
407
+ ]
408
+ if not after_sync_getitems:
409
+ expanded.append(dep)
410
+ continue
411
+
412
+ with graph.inserting_before(sync_node):
413
+ for old_gi in after_sync_getitems:
414
+ key = old_gi.args[1]
415
+ new_gi = graph.call_function(operator.getitem, args=(dep, key))
416
+ new_gi.meta.update(old_gi.meta)
417
+ if isinstance(new_gi.meta.get("val"), dict):
418
+ raise AssertionError(
419
+ f"nested dict in triton kernel output for key {key}"
420
+ )
421
+ visited.add(new_gi)
422
+ expanded.append(new_gi)
423
+ old_gi.replace_all_uses_with(new_gi)
424
+ graph.erase_node(old_gi)
425
+
426
+ return expanded
427
+
428
+
429
+ def _wrap_sync_node(
430
+ gm: torch.fx.GraphModule,
431
+ sync_node: Node,
432
+ deps_before_sync: list[Node],
433
+ visited: set[Node],
434
+ partition_scoped_deps: set[Node] | None = None,
435
+ ) -> tuple[Node, list[Node]]:
436
+ """
437
+ Core logic: wrap a single sync node in control_deps.
438
+
439
+ Returns (control_deps_node, passthrough_getitems) where passthrough_getitems
440
+ are the getitem nodes that thread dependencies through the control_deps node.
441
+ ``visited`` is the set of nodes at or before the sync node in graph order,
442
+ used to distinguish pre-sync vs post-sync users.
443
+ """
444
+ from torch._inductor.fx_passes.control_dependencies import (
445
+ _create_subgraph_for_node,
446
+ control_deps,
447
+ get_subgraph_name,
448
+ )
449
+
450
+ graph = gm.graph
451
+ if partition_scoped_deps is None:
452
+ partition_scoped_deps = set()
453
+
454
+ sync_is_bwd = is_bwd_node(sync_node)
455
+
456
+ def _user_rewrite_pred(dep: Node) -> Callable[[Node], bool]:
457
+ if dep in partition_scoped_deps:
458
+
459
+ def pred(user: Node) -> bool:
460
+ if user in visited:
461
+ return False
462
+ if user.op == "output":
463
+ return sync_is_bwd
464
+ return is_bwd_node(user) == sync_is_bwd
465
+
466
+ return pred
467
+
468
+ dep_is_bwd = is_bwd_node(dep)
469
+
470
+ def pred(user: Node) -> bool:
471
+ return user not in visited and (user.op != "output" or dep_is_bwd)
472
+
473
+ return pred
474
+
475
+ # Use dep.users to find deps with uses after the sync — avoids a forward walk.
476
+ deps_with_uses_after_sync = []
477
+ for dep in deps_before_sync:
478
+ pred = _user_rewrite_pred(dep)
479
+ if any(pred(user) for user in dep.users):
480
+ deps_with_uses_after_sync.append(dep)
481
+
482
+ # Expand dict-returning nodes (triton_kernel_wrapper_functional) into
483
+ # individual getitem outputs. Passing a dict-valued node through
484
+ # control_deps breaks post-grad passes: reinplace + decomposition replace
485
+ # the dict node with a Python dict, corrupting any user that expected an
486
+ # FX Node. Unwrapping here ensures only tensor-valued nodes flow through.
487
+ deps_with_uses_after_sync = _expand_dict_returning_deps(
488
+ deps_with_uses_after_sync, visited, graph, sync_node
489
+ )
490
+
491
+ # Create subgraph that executes sync and passes through only used dependencies
492
+ subgraph_module = _create_subgraph_for_node(
493
+ graph, sync_node, deps_with_uses_after_sync
494
+ )
495
+ subgraph_attr_name = get_subgraph_name(gm, sync_node.name)
496
+ setattr(gm, subgraph_attr_name, subgraph_module)
497
+
498
+ # Create control_deps call
499
+ # Note: sync nodes (record_event/wait_event) only take int args, no Node args.
500
+ with graph.inserting_before(sync_node):
501
+ get_subgraph = graph.get_attr(subgraph_attr_name)
502
+ control_deps_node = graph.call_function(
503
+ control_deps,
504
+ args=(
505
+ tuple(deps_before_sync), # additional_deps (all deps for ordering)
506
+ get_subgraph, # subgraph
507
+ *deps_with_uses_after_sync, # only pass through deps that are used
508
+ ),
509
+ kwargs={},
510
+ )
511
+
512
+ # Propagate partitioner_tag so the partitioner can distinguish
513
+ # forward vs backward sync control_deps during graph extraction.
514
+ if "partitioner_tag" in sync_node.meta:
515
+ control_deps_node.meta["partitioner_tag"] = sync_node.meta["partitioner_tag"]
516
+
517
+ # Mark newly created nodes as visited so subsequent syncs don't
518
+ # misclassify them as "after the sync" during replacement.
519
+ visited.add(get_subgraph)
520
+ visited.add(control_deps_node)
521
+
522
+ # The output is (sync_result, *deps_with_uses_after_sync)
523
+ # Reuse the val the subgraph output already carries: the min-cut
524
+ # partitioner's _size_of() raises on any node without `val`, and its escape
525
+ # hatch covers only get_attr and zero-return OpOverloads, not a schema-less
526
+ # HOP. The subgraph output is unwrapped when it has no pass-through deps.
527
+ sg_val = subgraph_module.graph.output_node().meta.get("val")
528
+ control_deps_node.meta["val"] = sg_val if isinstance(sg_val, tuple) else (sg_val,)
529
+
530
+ # Create getitem nodes only for dependencies that have uses after sync
531
+ replacements: dict[Node, Node] = {}
532
+ with graph.inserting_after(control_deps_node):
533
+ for i, dep in enumerate(deps_with_uses_after_sync):
534
+ getitem_node = graph.call_function(
535
+ operator.getitem,
536
+ args=(control_deps_node, i + 1), # +1 because index 0 is sync result
537
+ )
538
+ getitem_node.meta.update(dep.meta)
539
+ # The getitem is a passthrough projection of an existing value, not
540
+ # a node that *produces* an unbacked symbol - the original ``dep``
541
+ # (still inside the subgraph) is the binding site. Leaving the
542
+ # binding on the getitem trips Inductor's run_node assertion that
543
+ # ``new_unbacked_defs >= renamed_unbacked_bindings``.
544
+ getitem_node.meta.pop("unbacked_bindings", None)
545
+ replacements[dep] = getitem_node
546
+ visited.add(getitem_node)
547
+
548
+ # Replace uses of dependencies that come after sync_node.
549
+ # Use map_arg to handle nested structures (e.g. output node's list args).
550
+ for dep, getitem_node in replacements.items():
551
+ pred = _user_rewrite_pred(dep)
552
+ for user in list(dep.users.keys()):
553
+ if user is control_deps_node:
554
+ continue
555
+ if not pred(user):
556
+ continue
557
+
558
+ def _replace(n: Node) -> Node:
559
+ return getitem_node if n is dep else n
560
+
561
+ if (
562
+ user.op == "call_function"
563
+ and user.target is torch.ops.aten.copy_.default
564
+ and user.args[0] is dep
565
+ and dep in partition_scoped_deps
566
+ ):
567
+ # AOT functionalization leaves keep_input_mutations epilogue
568
+ # copy_ as the only writer of a partition-scoped placeholder.
569
+ # Preserve the destination identity used by mutation bookkeeping.
570
+ user.args = (dep, *map_arg(user.args[1:], _replace))
571
+ else:
572
+ user.args = map_arg(user.args, _replace)
573
+ user.kwargs = map_arg(user.kwargs, _replace)
574
+
575
+ # Remove original sync node
576
+ sync_node.replace_all_uses_with(control_deps_node)
577
+ graph.erase_node(sync_node)
578
+ return control_deps_node, list(replacements.values())
579
+
580
+
581
+ def _collect_sync_forward_deps(
582
+ graph: torch.fx.Graph,
583
+ ) -> tuple[dict[Node, OrderedSet[Node]], dict[Node, OrderedSet[Node]]]:
584
+ """Collect values that must cross sync boundaries.
585
+
586
+ ``live_inputs[partition][stream]`` tracks values whose passthrough can anchor
587
+ later work in that partition on that stream. Demand labels propagate through
588
+ producers while each producer also seeds its own execution stream. This is a
589
+ single reverse liveness traversal; the forward pass still handles sync/event
590
+ state introduced while rewriting the graph.
591
+ """
592
+ stream_sync_deps: dict[Node, OrderedSet[Node]] = {}
593
+ full_barrier_deps: dict[Node, OrderedSet[Node]] = {}
594
+ live_inputs: dict[Partition, dict[int, OrderedSet[Node]]] = {
595
+ FORWARD: {},
596
+ BACKWARD: {},
597
+ }
598
+ locations: dict[Node, OrderedSet[tuple[Partition, int]]] = {}
599
+ full_barriers = (
600
+ torch.ops.streams.synchronize_device.default,
601
+ torch.ops.streams.synchronize_event.default,
602
+ torch.ops.streams.synchronize_stream.default,
603
+ )
604
+
605
+ def _add_live(node: Node, partition: Partition, stream: int) -> None:
606
+ stream_inputs = live_inputs[partition].get(stream)
607
+ if stream_inputs is None:
608
+ stream_inputs = live_inputs[partition][stream] = OrderedSet()
609
+ stream_inputs.add(node)
610
+ node_locations = locations.get(node)
611
+ if node_locations is None:
612
+ node_locations = locations[node] = OrderedSet()
613
+ node_locations.add((partition, stream))
614
+
615
+ for node in reversed(graph.nodes):
616
+ if node.op == "call_function" and node.target in full_barriers:
617
+ deps = OrderedSet(
618
+ dep
619
+ for stream_inputs in live_inputs[is_bwd_node(node)].values()
620
+ for dep in stream_inputs
621
+ )
622
+ if deps:
623
+ full_barrier_deps[node] = deps
624
+ continue
625
+ if (
626
+ node.op == "call_function"
627
+ and node.target is torch.ops.streams.wait_stream.default
628
+ ):
629
+ waiting_stream: int = node.args[0] # type: ignore[assignment]
630
+ deps = live_inputs[is_bwd_node(node)].get(waiting_stream)
631
+ if deps:
632
+ stream_sync_deps[node] = deps.copy()
633
+ continue
634
+ if (
635
+ node.op == "call_function"
636
+ and node.target is torch.ops.streams.wait_event.default
637
+ ):
638
+ waiting_stream: int = node.args[1] # type: ignore[assignment]
639
+ deps = live_inputs[is_bwd_node(node)].get(waiting_stream, ())
640
+ graph_inputs = OrderedSet(dep for dep in deps if dep.op == "placeholder")
641
+ if graph_inputs:
642
+ stream_sync_deps[node] = graph_inputs
643
+ continue
644
+ if node.op != "call_function" or node.target in _SYNC_OPS:
645
+ continue
646
+
647
+ inherited_locations = locations.pop(node, _EMPTY_LOCATIONS)
648
+ for partition, stream in inherited_locations:
649
+ live_inputs[partition][stream].discard(node)
650
+ execution_stream = get_stream(node)
651
+ if execution_stream is None:
652
+ execution_stream = 0
653
+ target_locations = OrderedSet(
654
+ (*inherited_locations, (is_bwd_node(node), execution_stream))
655
+ )
656
+
657
+ def _collect(n: Node) -> Node:
658
+ if "val" in n.meta:
659
+ for partition, stream in target_locations:
660
+ _add_live(n, partition, stream)
661
+ return n
662
+
663
+ map_arg(node.args, _collect)
664
+ map_arg(node.kwargs, _collect)
665
+ return stream_sync_deps, full_barrier_deps
666
+
667
+
668
+ def _collect_full_barrier_deps(
669
+ stream_to_nodes: dict[int | None, list[Node]],
670
+ stream_sync_deps: dict[int | None, list[Node]],
671
+ bwd: bool = False,
672
+ ) -> list[Node]:
673
+ """Collect all still-live cross-stream deps for a full CPU barrier
674
+ (synchronize_stream/device/event).
675
+
676
+ These ops block the CPU, so a consumer is only ordered after them by an
677
+ explicit control_deps edge (nothing on the consumer's stream waits for a CPU
678
+ barrier). Includes live compute nodes (stream_to_nodes) plus the ctrl/
679
+ passthrough nodes accumulated by prior sync ops that already cleared
680
+ stream_to_nodes (stream_sync_deps), deduped by identity preserving order.
681
+
682
+ ``bwd`` marks a backward barrier: its accumulated sync deps are filtered to
683
+ backward nodes only, so it never depends on a forward control_deps node.
684
+ That edge would cross the fwd/bwd boundary onto a node that is neither
685
+ saveable nor recomputable, making the min-cut partitioner infeasible.
686
+ Forward compute deps (stream_to_nodes) are kept -- backward legitimately
687
+ depends on forward activations.
688
+ """
689
+ all_deps = [n for nodes in stream_to_nodes.values() for n in nodes]
690
+ seen = set(all_deps)
691
+ for deps in stream_sync_deps.values():
692
+ for dep in deps:
693
+ if dep in seen or (bwd and not is_bwd_node(dep)):
694
+ continue
695
+ all_deps.append(dep)
696
+ seen.add(dep)
697
+ return all_deps
698
+
699
+
700
+ def wrap_all_sync_nodes_with_control_deps(gm: torch.fx.GraphModule) -> None:
701
+ """
702
+ Single-pass wrap of all sync nodes in control_deps.
703
+
704
+ Iterates through the graph once, accumulating per-stream node lists.
705
+ When a sync node is encountered, it is wrapped using the accumulated deps
706
+ for that stream, then the deps are reset to the control_deps node
707
+ (maintaining the ordering chain for subsequent syncs on the same stream).
708
+ """
709
+ graph = gm.graph
710
+ if len(graph.nodes) == 0:
711
+ raise RuntimeError("Expected a non-empty graph")
712
+
713
+ stream_sync_forward_deps, full_barrier_forward_deps = _collect_sync_forward_deps(
714
+ graph
715
+ )
716
+
717
+ stream_to_nodes: dict[int | None, list[Node]] = {}
718
+ # Maps event_index to its latest ordering anchor: either the control_deps that
719
+ # wrapped record_event or a raw record_event with no dependencies.
720
+ event_to_anchor: dict[int, Node] = {}
721
+ # Maps event_index -> getitem nodes threaded through record_event's control_deps,
722
+ # so synchronize_event can thread them through to subsequent ops.
723
+ event_to_passthrough: dict[int, list[Node]] = {}
724
+ # Maps event_index -> stream that the event was recorded on,
725
+ # so synchronize_event can infer its stream.
726
+ event_to_stream: dict[int, int | None] = {}
727
+ # Tracks the most recent control_deps node and its passthrough
728
+ # getitems per stream. synchronize_stream/device consults this to
729
+ # depend on prior sync ops (ctrl_node for ordering) and thread
730
+ # cross-stream data through (passthrough for data edges), even
731
+ # after stream_to_nodes has been cleared by those sync ops.
732
+ stream_sync_deps: dict[int | None, list[Node]] = {}
733
+ visited: set[Node] = set()
734
+ found_sync = False
735
+
736
+ # Walk the node linked-list manually so we can mutate the graph
737
+ # (wrapping sync nodes inserts/erases nodes) without losing our place.
738
+ node = next(iter(graph.nodes))
739
+ while node.op != "root":
740
+ next_node = node.next
741
+ visited.add(node)
742
+
743
+ if node.op == "call_function":
744
+ if node.target in _SYNC_OPS:
745
+ # synchronize_device and synchronize_stream block the CPU,
746
+ # so all subsequent kernel launches are host-ordered after
747
+ # them. Treat both as full barriers across all streams.
748
+ if node.target in (
749
+ torch.ops.streams.synchronize_device.default,
750
+ torch.ops.streams.synchronize_stream.default,
751
+ ):
752
+ all_stream_deps = _collect_full_barrier_deps(
753
+ stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node)
754
+ )
755
+ existing_deps = set(all_stream_deps)
756
+ for dep in full_barrier_forward_deps.get(node, ()):
757
+ if dep not in existing_deps:
758
+ all_stream_deps.append(dep)
759
+ existing_deps.add(dep)
760
+ if all_stream_deps:
761
+ found_sync = True
762
+ ctrl_node_sync, passthrough_sync = _wrap_sync_node(
763
+ gm, node, all_stream_deps, visited
764
+ )
765
+ else:
766
+ ctrl_node_sync = None
767
+ passthrough_sync: list[Node] = []
768
+ stream_to_nodes.clear()
769
+ stream_sync_deps.clear()
770
+ sync_anchor = ctrl_node_sync if ctrl_node_sync is not None else node
771
+ stream_sync_deps[None] = [sync_anchor, *passthrough_sync]
772
+ while (
773
+ getattr(next_node, "_erased", False) and next_node.op != "root"
774
+ ):
775
+ next_node = next_node.next
776
+ node = next_node
777
+ continue
778
+
779
+ # wait_stream(waiting, waited_on) creates a dependency on
780
+ # the waited_on stream: all prior work there must complete
781
+ # before the waiting stream proceeds.
782
+ if node.target is torch.ops.streams.wait_stream.default:
783
+ waiting_stream: int = node.args[0] # type: ignore[assignment]
784
+ waited_on_stream: int = node.args[1] # type: ignore[assignment]
785
+ deps_before_sync = list(stream_to_nodes.get(waited_on_stream, ()))
786
+ if waiting_stream != waited_on_stream:
787
+ deps_before_sync.extend(stream_to_nodes.get(waiting_stream, ()))
788
+ if None in stream_to_nodes and waited_on_stream is not None:
789
+ deps_before_sync.extend(stream_to_nodes[None])
790
+ participating_streams = dict.fromkeys(
791
+ (waited_on_stream, waiting_stream, None)
792
+ )
793
+ prior_syncs = list(
794
+ dict.fromkeys(
795
+ dep
796
+ for stream in participating_streams
797
+ for dep in stream_sync_deps.get(stream, ())
798
+ )
799
+ )
800
+ if is_bwd_node(node):
801
+ prior_syncs = [n for n in prior_syncs if is_bwd_node(n)]
802
+ deps_before_sync.extend(prior_syncs)
803
+ # Also include inputs of subsequent waiting-stream nodes
804
+ # so they get threaded through control_deps, creating a
805
+ # forward ordering constraint (waiting-stream work must
806
+ # come after wait_stream).
807
+ existing_deps = set(deps_before_sync)
808
+ for dep in stream_sync_forward_deps.get(node, ()):
809
+ if dep not in existing_deps:
810
+ deps_before_sync.append(dep)
811
+ existing_deps.add(dep)
812
+ if deps_before_sync:
813
+ found_sync = True
814
+ ctrl_node_ws, passthrough_ws = _wrap_sync_node(
815
+ gm, node, deps_before_sync, visited
816
+ )
817
+ else:
818
+ ctrl_node_ws = None
819
+ passthrough_ws: list[Node] = []
820
+ wait_anchor = ctrl_node_ws if ctrl_node_ws is not None else node
821
+ # Key under both streams: the wait executes on waiting_stream
822
+ # and subsumes the waited-on work used to anchor it.
823
+ stream_sync_deps[waiting_stream] = [
824
+ wait_anchor,
825
+ *passthrough_ws,
826
+ ]
827
+ stream_sync_deps[waited_on_stream] = [
828
+ wait_anchor,
829
+ *passthrough_ws,
830
+ ]
831
+ stream_to_nodes[waited_on_stream] = []
832
+ if None in stream_to_nodes:
833
+ stream_to_nodes[None] = []
834
+ while (
835
+ getattr(next_node, "_erased", False) and next_node.op != "root"
836
+ ):
837
+ next_node = next_node.next
838
+ node = next_node
839
+ continue
840
+
841
+ event_index: int = node.args[0] # type: ignore[assignment]
842
+
843
+ # synchronize_event blocks the CPU thread, so it acts
844
+ # as a barrier across all streams. Collect deps from every
845
+ # stream and reset them all afterward. If the event was
846
+ # recorded externally, thread the graph inputs through so
847
+ # that any post-sync uses depend on the synchronize.
848
+ partition_scoped_deps: list[Node] = []
849
+ if node.target is torch.ops.streams.synchronize_event.default:
850
+ sync_stream: int | None = event_to_stream.get(event_index)
851
+ # Like synchronize_stream/device, this is a CPU-side barrier,
852
+ # so fold in still-live cross-stream data accumulated by prior
853
+ # sync ops (which cleared stream_to_nodes).
854
+ all_stream_deps = _collect_full_barrier_deps(
855
+ stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node)
856
+ )
857
+ deps_before_sync = [
858
+ *all_stream_deps,
859
+ *full_barrier_forward_deps.get(node, ()),
860
+ ]
861
+ else:
862
+ sync_stream = node.args[1] # type: ignore[assignment]
863
+ deps_before_sync = list(stream_to_nodes.get(sync_stream, ()))
864
+ partition_scoped_deps = (
865
+ list(stream_sync_forward_deps.get(node, ()))
866
+ if node.target is torch.ops.streams.wait_event.default
867
+ and event_index not in event_to_anchor
868
+ else []
869
+ )
870
+ deps_before_sync.extend(partition_scoped_deps)
871
+ # Nodes without explicit stream annotation (custom.stream=None)
872
+ # run on the current/default stream. Include them when the sync
873
+ # op references a stream, since the unannotated nodes are
874
+ # implicitly on that stream.
875
+ if None in stream_to_nodes and sync_stream is not None:
876
+ deps_before_sync.extend(stream_to_nodes[None])
877
+ # Order this sync op after the prior sync on its own stream
878
+ # (and after any full barrier, keyed under None). Without this,
879
+ # a record/wait whose stream_to_nodes was reset by an earlier
880
+ # sync would have no deps, stay unwrapped, and float as a bare
881
+ # side-effectful node -- capturing nothing, the same failure as
882
+ # an unanchored synchronize_stream.
883
+ prior_syncs = [
884
+ *stream_sync_deps.get(sync_stream, ()),
885
+ *stream_sync_deps.get(None, ()),
886
+ ]
887
+ # A backward sync must anchor only on backward sync nodes:
888
+ # depending on a forward control_deps node crosses the fwd/bwd
889
+ # boundary onto a node that is neither saveable nor
890
+ # recomputable, which makes the min-cut partitioner infeasible.
891
+ if is_bwd_node(node):
892
+ prior_syncs = [n for n in prior_syncs if is_bwd_node(n)]
893
+ deps_before_sync.extend(prior_syncs)
894
+
895
+ # For wait_event and synchronize_event, depend on the matching
896
+ # record_event's control_deps node (ordering) and thread its
897
+ # passthrough getitems through (data edge), so consumers of
898
+ # recorded values are rewired through the wait/synchronize
899
+ # and the scheduler sees the dependency.
900
+ if node.target in (
901
+ torch.ops.streams.wait_event.default,
902
+ torch.ops.streams.synchronize_event.default,
903
+ ):
904
+ if event_index in event_to_anchor:
905
+ deps_before_sync = [
906
+ event_to_anchor[event_index],
907
+ *deps_before_sync,
908
+ ]
909
+ if event_index in event_to_passthrough:
910
+ deps_before_sync = [
911
+ *deps_before_sync,
912
+ *event_to_passthrough[event_index],
913
+ ]
914
+ elif (
915
+ node.target is torch.ops.streams.record_event.default
916
+ and event_index in event_to_anchor
917
+ ):
918
+ # Re-recording replaces an event's state, but the host-side
919
+ # record operations must retain program order even when the
920
+ # new record is on an otherwise-empty stream.
921
+ deps_before_sync.insert(0, event_to_anchor[event_index])
922
+
923
+ # Deduplicate (preserving order): the folded stream_sync_deps and
924
+ # the event's own anchor/passthrough can overlap.
925
+ deps_before_sync = list(OrderedSet(deps_before_sync))
926
+
927
+ if deps_before_sync:
928
+ found_sync = True
929
+ ctrl_node, passthrough = _wrap_sync_node(
930
+ gm,
931
+ node,
932
+ deps_before_sync,
933
+ visited,
934
+ set(partition_scoped_deps)
935
+ if node.target is torch.ops.streams.wait_event.default
936
+ else None,
937
+ )
938
+ else:
939
+ ctrl_node = None
940
+ passthrough: list[torch.fx.Node] = []
941
+
942
+ if node.target is torch.ops.streams.record_event.default:
943
+ event_to_stream[event_index] = sync_stream
944
+ event_to_anchor[event_index] = (
945
+ ctrl_node if ctrl_node is not None else node
946
+ )
947
+ event_to_passthrough[event_index] = passthrough
948
+
949
+ sync_anchor = ctrl_node if ctrl_node is not None else node
950
+ stream_sync_deps[sync_stream] = [sync_anchor, *passthrough]
951
+
952
+ # Reset: ops between this sync and the next will accumulate
953
+ # fresh. Ordering with prior ops is already enforced because
954
+ # their uses were rewired through getitems from control_deps.
955
+ # synchronize_event is a full barrier, so its own passthrough
956
+ # subsumes all prior per-stream data: clear then re-seed. Key the
957
+ # reseed under None (like synchronize_stream/device) so a later
958
+ # record/wait on any stream chains after it.
959
+ if node.target is torch.ops.streams.synchronize_event.default:
960
+ stream_to_nodes.clear()
961
+ stream_sync_deps.clear()
962
+ stream_sync_deps[None] = [sync_anchor, *passthrough]
963
+ else:
964
+ stream_to_nodes[sync_stream] = []
965
+ if None in stream_to_nodes:
966
+ stream_to_nodes[None] = []
967
+ elif "val" in node.meta:
968
+ stream = get_stream(node)
969
+ stream_to_nodes.setdefault(stream, []).append(node)
970
+
971
+ # _wrap_sync_node may erase nodes after the sync (e.g.
972
+ # _expand_dict_returning_deps erases getitems). Skip erased nodes
973
+ # so we don't re-process a dead node into stream_to_nodes.
974
+ while getattr(next_node, "_erased", False) and next_node.op != "root":
975
+ next_node = next_node.next
976
+ node = next_node
977
+
978
+ if found_sync:
979
+ gm.recompile()
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Codegen for AOTDispatchSubclassWrapper.
3
+
4
+ Generates a Python function that replaces the data-driven
5
+ runtime_unwrap_tensor_subclasses / wrap_tensor_subclasses loop with
6
+ a straight-line function where all metadata (indices, attr names,
7
+ subclass types, symint positions) is baked in at compile time.
8
+ """
9
+
10
+ import functools
11
+ import keyword
12
+ from collections.abc import Callable, Iterable
13
+ from typing import cast, TYPE_CHECKING
14
+
15
+ from torch import SymInt
16
+
17
+ from .codegen import _compile_and_exec_source, PySourceBuilder
18
+ from .schemas import ActInputPaths, OpaqueMeta, PlainTensorMeta, SubclassCreationMeta
19
+ from .utils import import_async_collective_tensor_type
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
24
+
25
+
26
+ def _is_symint_placeholder(x: None | int | SymInt) -> bool:
27
+ """Check whether a size/stride entry is symbolic and needs a runtime value.
28
+
29
+ Works both before make_runtime_safe() (entries are SymInt) and after
30
+ (symbolic entries replaced with None, nested ints with -1).
31
+ """
32
+ if x is None:
33
+ return True
34
+ if isinstance(x, SymInt) and not x.node.is_nested_int():
35
+ return True
36
+ return False
37
+
38
+
39
+ def _compute_placeholders(outer: Iterable[None | int | SymInt]) -> list[bool]:
40
+ return [_is_symint_placeholder(s) for s in outer]
41
+
42
+
43
+ def _safe_attr_access(var: str, attr: str) -> str:
44
+ if attr.isidentifier() and not keyword.iskeyword(attr):
45
+ return f"{var}.{attr}"
46
+ return f"getattr({var}, {attr!r})"
47
+
48
+
49
+ class _OutputWrapState:
50
+ def __init__(
51
+ self,
52
+ *,
53
+ remaining_min_count: int,
54
+ remaining_max_count: int,
55
+ optional_symint_check: str,
56
+ ) -> None:
57
+ self.remaining_min_count = remaining_min_count
58
+ self.remaining_max_count = remaining_max_count
59
+ self.optional_symint_check = optional_symint_check
60
+
61
+ def mark_required(self) -> None:
62
+ self.remaining_min_count -= 1
63
+ self.remaining_max_count -= 1
64
+
65
+ def mark_optional(self) -> None:
66
+ self.remaining_max_count -= 1
67
+
68
+
69
+ def _maybe_wait_async_collective_tensor(
70
+ x: object,
71
+ AsyncCollectiveTensor: type["AsyncCollectiveTensor"],
72
+ ) -> object:
73
+ """Wait on ACT values and leave all other runtime inputs unchanged."""
74
+ if isinstance(x, AsyncCollectiveTensor):
75
+ return cast("AsyncCollectiveTensor", x).trigger_wait()
76
+ return x
77
+
78
+
79
+ def _codegen_unwrap_subclass(
80
+ state: PySourceBuilder,
81
+ meta: SubclassCreationMeta,
82
+ var: str,
83
+ indent: int = 1,
84
+ include_symints: bool = True,
85
+ act_input_paths: set[tuple[str, ...]] | None = None,
86
+ act_wait_fn: str | None = None,
87
+ ) -> None:
88
+ """Emit code to recursively unwrap a single subclass input."""
89
+ act_input_paths = act_input_paths or set()
90
+
91
+ def emit_plain_tensor_symints(var: str, meta: PlainTensorMeta) -> None:
92
+ if not include_symints:
93
+ return
94
+
95
+ if any(meta.size_symbol_placeholders):
96
+ size_var = state.fresh_name("_size")
97
+ state.emit(f"{size_var} = {var}.size()", indent=indent)
98
+ for i, is_sym in enumerate(meta.size_symbol_placeholders):
99
+ if is_sym:
100
+ state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent)
101
+
102
+ if any(meta.stride_symbol_placeholders):
103
+ stride_var = state.fresh_name("_stride")
104
+ state.emit(f"{stride_var} = {var}.stride()", indent=indent)
105
+ for i, is_sym in enumerate(meta.stride_symbol_placeholders):
106
+ if is_sym:
107
+ state.emit(
108
+ f"unwrapped_args.append({stride_var}[{i}])", indent=indent
109
+ )
110
+
111
+ for attr, attr_meta in meta.attrs.items():
112
+ attr_expr = _safe_attr_access(var, attr)
113
+ attr_act_input_paths = {
114
+ path[1:] for path in act_input_paths if path and path[0] == attr
115
+ }
116
+ match attr_meta:
117
+ case PlainTensorMeta():
118
+ if attr_act_input_paths:
119
+ if attr_act_input_paths != {()}:
120
+ raise AssertionError(
121
+ f"ACT path for {attr} continues past a leaf meta"
122
+ )
123
+ if act_wait_fn is None:
124
+ raise AssertionError("missing ACT wait function")
125
+ resolved_var = state.fresh_name("_resolved")
126
+ state.emit(
127
+ f"{resolved_var} = {act_wait_fn}({attr_expr})",
128
+ indent=indent,
129
+ )
130
+ attr_expr = resolved_var
131
+ state.emit(f"unwrapped_args.append({attr_expr})", indent=indent)
132
+ emit_plain_tensor_symints(attr_expr, attr_meta)
133
+ case OpaqueMeta():
134
+ if attr_act_input_paths:
135
+ if attr_act_input_paths != {()}:
136
+ raise AssertionError(
137
+ f"ACT path for {attr} continues past a leaf meta"
138
+ )
139
+ if act_wait_fn is None:
140
+ raise AssertionError("missing ACT wait function")
141
+ resolved_var = state.fresh_name("_resolved")
142
+ state.emit(
143
+ f"{resolved_var} = {act_wait_fn}({attr_expr})",
144
+ indent=indent,
145
+ )
146
+ state.emit(f"unwrapped_args.append({resolved_var})", indent=indent)
147
+ else:
148
+ state.emit(
149
+ f"unwrapped_args.append({attr_expr})",
150
+ indent=indent,
151
+ )
152
+ case SubclassCreationMeta():
153
+ if () in attr_act_input_paths:
154
+ raise AssertionError(f"ACT path for {attr} stops at subclass meta")
155
+ inner_var = state.fresh_name("_inner")
156
+ state.emit(f"{inner_var} = {attr_expr}", indent=indent)
157
+ _codegen_unwrap_subclass(
158
+ state,
159
+ attr_meta,
160
+ inner_var,
161
+ indent=indent,
162
+ include_symints=include_symints,
163
+ act_input_paths=attr_act_input_paths,
164
+ act_wait_fn=act_wait_fn,
165
+ )
166
+
167
+ if include_symints:
168
+ size_placeholders = _compute_placeholders(meta.outer_size)
169
+ stride_placeholders = _compute_placeholders(meta.outer_stride)
170
+ if any(size_placeholders) or any(stride_placeholders):
171
+ size_var = state.fresh_name("_size")
172
+ state.emit(f"{size_var} = {var}.size()", indent=indent)
173
+ for i, is_sym in enumerate(size_placeholders):
174
+ if is_sym:
175
+ state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent)
176
+
177
+ stride_var = state.fresh_name("_stride")
178
+ state.emit(f"{stride_var} = {var}.stride()", indent=indent)
179
+ for i, is_sym in enumerate(stride_placeholders):
180
+ if is_sym:
181
+ state.emit(
182
+ f"unwrapped_args.append({stride_var}[{i}])", indent=indent
183
+ )
184
+
185
+
186
+ def _concrete_value(val: None | int | SymInt) -> int:
187
+ """Get the concrete int value for a non-symbolic size/stride entry.
188
+
189
+ Used for entries that are NOT symbolic placeholders, meaning they are
190
+ concrete ints or nested ints (represented as -1 after make_runtime_safe).
191
+ """
192
+ if isinstance(val, int):
193
+ return val
194
+ # Before make_runtime_safe: nested ints are SymInts; use -1 as dummy.
195
+ # After make_runtime_safe: they're already -1.
196
+ if isinstance(val, SymInt) and val.node.is_nested_int():
197
+ return -1
198
+ raise AssertionError(f"Expected concrete int, got {type(val)}: {val}")
199
+
200
+
201
+ def _is_optional_symint_output(val: object) -> bool:
202
+ return isinstance(val, (int, SymInt))
203
+
204
+
205
+ def _codegen_wrap_subclass(
206
+ state: PySourceBuilder,
207
+ meta: SubclassCreationMeta,
208
+ output_state: _OutputWrapState,
209
+ ) -> str:
210
+ """Emit code to reconstruct one subclass output. Returns the variable name."""
211
+ inner_dict_var = state.fresh_name("_out_inner")
212
+ entries: list[str] = []
213
+ attr_exprs: dict[str, str] = {}
214
+
215
+ for attr, attr_meta in meta.attrs.items():
216
+ match attr_meta:
217
+ case PlainTensorMeta():
218
+ attr_expr = state.fresh_name("_out_attr")
219
+ state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]")
220
+ state.emit("_out_idx += 1")
221
+ output_state.mark_required()
222
+ _emit_optional_plain_tensor_symint_skips(state, output_state, attr_meta)
223
+ case OpaqueMeta():
224
+ attr_expr = state.fresh_name("_out_attr")
225
+ state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]")
226
+ state.emit("_out_idx += 1")
227
+ output_state.mark_required()
228
+ case SubclassCreationMeta():
229
+ attr_expr = _codegen_wrap_subclass(state, attr_meta, output_state)
230
+ attr_exprs[attr] = attr_expr
231
+ entries.append(f"{attr!r}: {attr_expr}")
232
+
233
+ state.emit(f"{inner_dict_var} = {{{', '.join(entries)}}}")
234
+
235
+ # Reconstruct outer_size and outer_stride
236
+ size_placeholders = _compute_placeholders(meta.outer_size)
237
+ stride_placeholders = _compute_placeholders(meta.outer_stride)
238
+
239
+ def _build_tuple(
240
+ outer: Iterable[None | int | SymInt], placeholders: list[bool]
241
+ ) -> str:
242
+ parts: list[str] = []
243
+ for val, is_sym in zip(outer, placeholders):
244
+ if is_sym:
245
+ sym_expr = state.fresh_name("_out_sym")
246
+ state.emit(f"{sym_expr} = unwrapped_outs[_out_idx]")
247
+ state.emit("_out_idx += 1")
248
+ output_state.mark_required()
249
+ parts.append(sym_expr)
250
+ else:
251
+ parts.append(repr(_concrete_value(val)))
252
+ if len(parts) == 1:
253
+ return f"({parts[0]},)"
254
+ return f"({', '.join(parts)})"
255
+
256
+ def _consume_optional_placeholders(placeholders: list[bool]) -> None:
257
+ for is_sym in placeholders:
258
+ if is_sym:
259
+ _emit_optional_symint_skip(state, output_state)
260
+
261
+ outer_size_from_attr = meta.outer_size_from_attr
262
+ outer_stride_from_attr = meta.outer_stride_from_attr
263
+ if outer_size_from_attr is not None:
264
+ size_expr = f"{attr_exprs[outer_size_from_attr]}.size()"
265
+ _consume_optional_placeholders(size_placeholders)
266
+ else:
267
+ size_expr = _build_tuple(meta.outer_size, size_placeholders)
268
+
269
+ if outer_stride_from_attr is not None:
270
+ stride_expr = f"{attr_exprs[outer_stride_from_attr]}.stride()"
271
+ _consume_optional_placeholders(stride_placeholders)
272
+ else:
273
+ stride_expr = _build_tuple(meta.outer_stride, stride_placeholders)
274
+
275
+ type_name = state.add_global(
276
+ state.fresh_name("_subclass_type"),
277
+ meta.original_subclass_type or type(meta.original_subclass),
278
+ )
279
+ meta_name = state.add_global(state.fresh_name("_meta"), meta.meta)
280
+
281
+ result_var = state.fresh_name("_out")
282
+ state.emit(
283
+ f"{result_var} = {type_name}.__tensor_unflatten__("
284
+ f"{inner_dict_var}, {meta_name}, {size_expr}, {stride_expr})"
285
+ )
286
+ return result_var
287
+
288
+
289
+ def _count_output_args(
290
+ meta: PlainTensorMeta | SubclassCreationMeta,
291
+ *,
292
+ include_subclass_symints: bool,
293
+ ) -> int:
294
+ if isinstance(meta, PlainTensorMeta):
295
+ return meta.arg_count if include_subclass_symints else 1
296
+
297
+ total = 0
298
+ for attr_meta in meta.attrs.values():
299
+ if isinstance(attr_meta, OpaqueMeta):
300
+ total += 1
301
+ else:
302
+ total += _count_output_args(
303
+ attr_meta, include_subclass_symints=include_subclass_symints
304
+ )
305
+
306
+ if include_subclass_symints:
307
+ total += sum(_compute_placeholders(meta.outer_size))
308
+ total += sum(_compute_placeholders(meta.outer_stride))
309
+ else:
310
+ if meta.outer_size_from_attr is None:
311
+ total += sum(_compute_placeholders(meta.outer_size))
312
+ if meta.outer_stride_from_attr is None:
313
+ total += sum(_compute_placeholders(meta.outer_stride))
314
+ return total
315
+
316
+
317
+ def _emit_optional_symint_skip(
318
+ state: PySourceBuilder,
319
+ output_state: _OutputWrapState,
320
+ ) -> None:
321
+ remaining_var = state.fresh_name("_remaining_outs")
322
+ include_var = state.fresh_name("_include_symints")
323
+ later_min_count = output_state.remaining_min_count
324
+ later_max_count = output_state.remaining_max_count - 1
325
+ max_fits = (
326
+ f"{remaining_var} - 1 >= {later_min_count} and "
327
+ f"{remaining_var} - 1 <= {later_max_count}"
328
+ )
329
+ min_fits = (
330
+ f"{remaining_var} >= {later_min_count} and {remaining_var} <= {later_max_count}"
331
+ )
332
+
333
+ state.emit(f"{remaining_var} = _num_wrapped_outs - _out_idx")
334
+ state.emit(
335
+ f"{include_var} = ({max_fits}) and "
336
+ f"{output_state.optional_symint_check}(unwrapped_outs[_out_idx])"
337
+ )
338
+ state.emit(
339
+ f"assert {include_var} or ({min_fits}), "
340
+ "'could not match output layout with optional SymInt outputs'"
341
+ )
342
+ state.emit(f"if {include_var}:")
343
+ state.emit("_out_idx += 1", indent=2)
344
+ output_state.mark_optional()
345
+
346
+
347
+ def _emit_optional_plain_tensor_symint_skips(
348
+ state: PySourceBuilder,
349
+ output_state: _OutputWrapState,
350
+ meta: PlainTensorMeta,
351
+ ) -> None:
352
+ for is_sym in meta.size_symbol_placeholders:
353
+ if is_sym:
354
+ _emit_optional_symint_skip(state, output_state)
355
+ for is_sym in meta.stride_symbol_placeholders:
356
+ if is_sym:
357
+ _emit_optional_symint_skip(state, output_state)
358
+
359
+
360
+ def _emit_output_wrapping(
361
+ state: PySourceBuilder,
362
+ out_metas: list[PlainTensorMeta | SubclassCreationMeta],
363
+ num_fw_outs_saved_for_bw: int | None,
364
+ ) -> tuple[list[str], int]:
365
+ """Emit wrapping code for output metas.
366
+
367
+ Returns (result_exprs, num_args_tallied) where result_exprs are Python
368
+ expression strings referencing each wrapped output.
369
+ """
370
+ result_exprs: list[str] = []
371
+ num_args_tallied = 0
372
+ saved_for_bw = num_fw_outs_saved_for_bw or 0
373
+ min_counts = [
374
+ _count_output_args(meta, include_subclass_symints=False) for meta in out_metas
375
+ ]
376
+ max_counts = [
377
+ _count_output_args(meta, include_subclass_symints=True) for meta in out_metas
378
+ ]
379
+ min_wrapped_outputs = sum(min_counts)
380
+ max_wrapped_outputs = sum(max_counts)
381
+
382
+ optional_symint_check = (
383
+ state.add_global(
384
+ state.fresh_name("_is_optional_symint_output"),
385
+ _is_optional_symint_output,
386
+ )
387
+ if min_wrapped_outputs != max_wrapped_outputs
388
+ else ""
389
+ )
390
+ state.emit("_out_idx = 0")
391
+ if saved_for_bw:
392
+ state.emit(f"_num_wrapped_outs = len(unwrapped_outs) - {saved_for_bw}")
393
+ else:
394
+ state.emit("_num_wrapped_outs = len(unwrapped_outs)")
395
+ if min_wrapped_outputs != max_wrapped_outputs:
396
+ state.emit(
397
+ "assert "
398
+ f"{min_wrapped_outputs} <= _num_wrapped_outs <= {max_wrapped_outputs}, "
399
+ f"f'expected between {min_wrapped_outputs} and {max_wrapped_outputs} "
400
+ "wrapped outputs, got {_num_wrapped_outs}'"
401
+ )
402
+ else:
403
+ state.emit(
404
+ f"assert _num_wrapped_outs == {max_wrapped_outputs}, "
405
+ f"f'expected {max_wrapped_outputs} wrapped outputs, "
406
+ "got {_num_wrapped_outs}'"
407
+ )
408
+
409
+ output_state = _OutputWrapState(
410
+ remaining_min_count=min_wrapped_outputs,
411
+ remaining_max_count=max_wrapped_outputs,
412
+ optional_symint_check=optional_symint_check,
413
+ )
414
+ for meta in out_metas:
415
+ if isinstance(meta, PlainTensorMeta):
416
+ out_expr = state.fresh_name("_out_plain")
417
+ state.emit(f"{out_expr} = unwrapped_outs[_out_idx]")
418
+ state.emit("_out_idx += 1")
419
+ output_state.mark_required()
420
+ _emit_optional_plain_tensor_symint_skips(state, output_state, meta)
421
+ result_exprs.append(out_expr)
422
+ num_args_tallied += meta.arg_count
423
+ else:
424
+ result_var = _codegen_wrap_subclass(state, meta, output_state)
425
+ result_exprs.append(result_var)
426
+ num_args_tallied += meta.arg_count
427
+
428
+ if output_state.remaining_min_count != 0 or output_state.remaining_max_count != 0:
429
+ raise AssertionError(
430
+ "output wrapping counts did not balance: "
431
+ f"{output_state.remaining_min_count}, "
432
+ f"{output_state.remaining_max_count}"
433
+ )
434
+ state.emit(
435
+ "assert _out_idx == _num_wrapped_outs, "
436
+ "f'wrapped {_out_idx} outputs, expected {_num_wrapped_outs}'"
437
+ )
438
+ return result_exprs, num_args_tallied
439
+
440
+
441
+ def _emit_input_unwrapping(
442
+ state: PySourceBuilder,
443
+ inp_metas: list[PlainTensorMeta | SubclassCreationMeta],
444
+ frozen_inp_indices: frozenset[int] = frozenset(),
445
+ include_symints: bool = True,
446
+ act_input_paths_by_input: dict[int, set[tuple[str, ...]]] | None = None,
447
+ act_wait_fn: str | None = None,
448
+ ) -> None:
449
+ """Emit unwrapping code for input metas into unwrapped_args.
450
+
451
+ Caller must have already emitted ``unwrapped_args = []``.
452
+ """
453
+ act_input_paths_by_input = act_input_paths_by_input or {}
454
+ for i, meta in enumerate(inp_metas):
455
+ input_act_paths = act_input_paths_by_input.get(i, set())
456
+ if isinstance(meta, PlainTensorMeta):
457
+ if input_act_paths:
458
+ if input_act_paths != {()}:
459
+ raise AssertionError(
460
+ f"ACT path for input {i} continues past a plain meta"
461
+ )
462
+ if act_wait_fn is None:
463
+ raise AssertionError("missing ACT wait function")
464
+ state.emit(f"unwrapped_args.append({act_wait_fn}(args[{i}]))")
465
+ else:
466
+ state.emit(f"unwrapped_args.append(args[{i}])")
467
+ elif i in frozen_inp_indices:
468
+ # Frozen by inductor freezing: constant already baked into graph.
469
+ state.emit("unwrapped_args.append(None)")
470
+ else:
471
+ if () in input_act_paths:
472
+ raise AssertionError(f"ACT path for input {i} stops at subclass meta")
473
+ inp_var = state.fresh_name("_inp")
474
+ type_name = state.add_global(
475
+ state.fresh_name("_expected_type"),
476
+ meta.original_subclass_type or type(meta.original_subclass),
477
+ )
478
+ state.emit(f"{inp_var} = args[{i}]")
479
+ state.emit(
480
+ f"assert type({inp_var}) is {type_name}, "
481
+ f"f'expected {{{type_name}}}, got {{type({inp_var})}}'",
482
+ )
483
+ _codegen_unwrap_subclass(
484
+ state,
485
+ meta,
486
+ inp_var,
487
+ indent=1,
488
+ include_symints=include_symints,
489
+ act_input_paths=input_act_paths,
490
+ act_wait_fn=act_wait_fn,
491
+ )
492
+
493
+
494
+ def _codegen_subclass_wrapper_source(
495
+ inp_metas: list[PlainTensorMeta | SubclassCreationMeta],
496
+ out_metas: list[PlainTensorMeta | SubclassCreationMeta],
497
+ num_fw_outs_saved_for_bw: int | None,
498
+ frozen_inp_indices: frozenset[int] = frozenset(),
499
+ act_input_paths: ActInputPaths | None = None,
500
+ ) -> tuple[str, dict[str, object]]:
501
+ """Generate source and globals for a subclass wrapper.
502
+
503
+ Returns (source, globals_dict). The globals_dict will NOT contain
504
+ ``compiled_fn`` — the caller is responsible for adding it before exec.
505
+ """
506
+ state = PySourceBuilder()
507
+
508
+ state.emit("def inner_fn(args):", indent=0)
509
+
510
+ act_input_paths_by_input: dict[int, set[tuple[str, ...]]] = {}
511
+ act_wait_fn = None
512
+ if act_input_paths:
513
+ AsyncCollectiveTensor = import_async_collective_tensor_type()
514
+ act_wait_fn = state.add_global(
515
+ state.fresh_name("_maybe_wait_act"),
516
+ functools.partial(
517
+ _maybe_wait_async_collective_tensor,
518
+ AsyncCollectiveTensor=AsyncCollectiveTensor,
519
+ ),
520
+ )
521
+ for i, attr_path in act_input_paths:
522
+ act_input_paths_by_input.setdefault(i, set()).add(attr_path)
523
+
524
+ # --- Input unwrapping ---
525
+ state.emit("unwrapped_args = []")
526
+ _emit_input_unwrapping(
527
+ state,
528
+ inp_metas,
529
+ frozen_inp_indices=frozen_inp_indices,
530
+ act_input_paths_by_input=act_input_paths_by_input,
531
+ act_wait_fn=act_wait_fn,
532
+ )
533
+
534
+ # Pass through any trailing args not covered by inp_metas
535
+ # (e.g. rng seed/offset added by FunctionalizedRngRuntimeWrapper).
536
+ num_inp_metas = len(inp_metas)
537
+ state.emit(f"unwrapped_args.extend(args[{num_inp_metas}:])")
538
+ state.emit("args.clear()")
539
+
540
+ # --- Call compiled function ---
541
+ state.emit("unwrapped_outs = compiled_fn(unwrapped_args)")
542
+
543
+ # --- Output wrapping ---
544
+ result_exprs, _ = _emit_output_wrapping(state, out_metas, num_fw_outs_saved_for_bw)
545
+ result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()"
546
+ if num_fw_outs_saved_for_bw is not None:
547
+ state.emit(
548
+ f"_activation_start = len(unwrapped_outs) - {num_fw_outs_saved_for_bw}"
549
+ )
550
+ state.emit(f"return {result_tuple} + tuple(unwrapped_outs[_activation_start:])")
551
+ else:
552
+ state.emit(f"return {result_tuple}")
553
+
554
+ source = state.getvalue()
555
+ return source, state.globals
556
+
557
+
558
+ def _codegen_subclass_wrap_source(
559
+ out_metas: list[PlainTensorMeta | SubclassCreationMeta],
560
+ ) -> tuple[str, dict[str, object]]:
561
+ """Generate source for wrapping flat outputs into subclasses.
562
+
563
+ Used for the backward epilogue. Shares output-wrapping logic with
564
+ _codegen_subclass_wrapper_source via _emit_output_wrapping.
565
+ """
566
+ state = PySourceBuilder()
567
+ state.emit("def wrap_fn(unwrapped_outs):", indent=0)
568
+ result_exprs, _ = _emit_output_wrapping(
569
+ state, out_metas, num_fw_outs_saved_for_bw=None
570
+ )
571
+ result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()"
572
+ state.emit(f"return {result_tuple}")
573
+ source = state.getvalue()
574
+ return source, state.globals
575
+
576
+
577
+ def codegen_backward_subclass_fns(
578
+ grad_input_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None,
579
+ ) -> tuple[Callable[..., object], Callable[..., object] | None]:
580
+ """Generate codegen'd unwrap and wrap functions for the backward pass.
581
+
582
+ Returns (unwrap_fn, wrap_fn). unwrap_fn is used by the backward prologue
583
+ to unwrap non-tangent subclass inputs (always an identity in AOT dispatch
584
+ since the compiled forward operates on unwrapped inner tensors). wrap_fn
585
+ is used by the backward epilogue to wrap flat grad inputs back into
586
+ subclasses; it is None when grad_input_metas is None.
587
+ """
588
+ source = "def unwrap_fn(args):\n return list(args)"
589
+ globals_dict: dict[str, object] = {}
590
+ unwrap_fn = _compile_and_exec_source(
591
+ source, globals_dict, "unwrap_fn", "backward_subclass_unwrap"
592
+ )
593
+
594
+ wrap_fn = None
595
+ if grad_input_metas is not None:
596
+ wrap_source, wrap_globals = _codegen_subclass_wrap_source(grad_input_metas)
597
+ wrap_fn = _compile_and_exec_source(
598
+ wrap_source, wrap_globals, "wrap_fn", "backward_subclass_wrapper"
599
+ )
600
+
601
+ return unwrap_fn, wrap_fn
602
+
603
+
604
+ def codegen_subclass_wrapper(
605
+ compiled_fn: Callable[..., object],
606
+ inp_metas: list[PlainTensorMeta | SubclassCreationMeta],
607
+ out_metas: list[PlainTensorMeta | SubclassCreationMeta],
608
+ num_fw_outs_saved_for_bw: int | None,
609
+ frozen_inp_indices: frozenset[int] = frozenset(),
610
+ act_input_paths: ActInputPaths | None = None,
611
+ ) -> Callable[..., object]:
612
+ """Generate a specialized wrapper function for subclass unwrap/wrap."""
613
+ source, globals_dict = _codegen_subclass_wrapper_source(
614
+ inp_metas,
615
+ out_metas,
616
+ num_fw_outs_saved_for_bw,
617
+ frozen_inp_indices,
618
+ act_input_paths=act_input_paths,
619
+ )
620
+ globals_dict["compiled_fn"] = compiled_fn
621
+ return _compile_and_exec_source(
622
+ source, globals_dict, "inner_fn", "subclass_wrapper", wrapped_fn=compiled_fn
623
+ )
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import itertools
5
+ from typing import Any, TYPE_CHECKING
6
+
7
+ import torch
8
+ from torch._custom_class_base import CustomClassBase
9
+ from torch._library.opaque_object import is_opaque_symbolic_type
10
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
11
+
12
+ from .schemas import OpaqueMeta
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Iterable
17
+
18
+
19
+ # This is technically very similar to SubclassCreatingMeta
20
+ # in aot_autograd, but we don't need all the stuff in there
21
+ # so just recreated a new dataclass.
22
+ @dataclasses.dataclass
23
+ class SubclassCreationMeta:
24
+ start_idx: int
25
+ num_tensors: int
26
+ class_type: Any
27
+ # None means the attr is a plain tensor (base case of recursion)
28
+ attrs: dict[str, SubclassCreationMeta | OpaqueMeta | None]
29
+ metadata: Any
30
+ outer_size: Iterable[None | int | torch.SymInt]
31
+ outer_stride: Iterable[None | int | torch.SymInt]
32
+
33
+
34
+ class UnwrapTensorSubclass(torch.nn.Module):
35
+ def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def]
36
+ todo: list[torch.Tensor | CustomClassBase] = list(tensors)
37
+
38
+ def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def]
39
+ if subclass_meta is None:
40
+ return tensors[offset], offset + 1
41
+ inner_tensors = {}
42
+ for attr, meta in subclass_meta.attrs.items():
43
+ if isinstance(meta, OpaqueMeta):
44
+ inner_tensors[attr] = tensors[offset]
45
+ offset += 1
46
+ else:
47
+ built_tensor, offset = _unwrap_tensor_subclasses(
48
+ meta, tensors, offset
49
+ )
50
+ inner_tensors[attr] = built_tensor
51
+ rebuilt = subclass_meta.class_type.__tensor_unflatten__(
52
+ inner_tensors,
53
+ subclass_meta.metadata,
54
+ subclass_meta.outer_size,
55
+ subclass_meta.outer_stride,
56
+ )
57
+ return rebuilt, offset
58
+
59
+ return _unwrap_tensor_subclasses(self.subclass_meta, todo, 0)[0]
60
+
61
+ def right_inverse(
62
+ self, tensor: torch.Tensor
63
+ ) -> list[torch.Tensor | CustomClassBase]:
64
+ if type(tensor) is torch.Tensor:
65
+ raise AssertionError("tensor must be a subclass, not torch.Tensor")
66
+ plain_tensors: list[torch.Tensor | CustomClassBase] = []
67
+
68
+ def _create_subclass_meta(tensor, idx, plain_tensor_container): # type: ignore[no-untyped-def]
69
+ if type(tensor) is torch.Tensor:
70
+ plain_tensor_container.append(tensor)
71
+ return None, idx + 1
72
+ inner_tensors_attrnames, metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined]
73
+ new_idx = idx
74
+ attr_to_meta: dict[str, SubclassCreationMeta | OpaqueMeta | None] = {}
75
+ for attr in inner_tensors_attrnames:
76
+ val = getattr(tensor, attr)
77
+ match val:
78
+ case CustomClassBase():
79
+ if not is_opaque_symbolic_type(type(val)):
80
+ raise ValueError(
81
+ f"{type(val).__name__!r} found in tensor attrs of "
82
+ f"{type(tensor).__name__}.__tensor_flatten__(). "
83
+ "Only tensors and reference-type opaques are allowed "
84
+ "in tensor attrs."
85
+ )
86
+ attr_to_meta[attr] = OpaqueMeta()
87
+ plain_tensor_container.append(val)
88
+ new_idx += 1
89
+ case torch.Tensor():
90
+ subclass_meta, new_idx = _create_subclass_meta(
91
+ val, new_idx, plain_tensor_container
92
+ )
93
+ attr_to_meta[attr] = subclass_meta
94
+ case _:
95
+ raise AssertionError(
96
+ f"expected Tensor or CustomClassBase, got {type(val)}"
97
+ )
98
+ return (
99
+ SubclassCreationMeta(
100
+ start_idx=idx,
101
+ num_tensors=new_idx - idx,
102
+ class_type=type(tensor),
103
+ attrs=attr_to_meta,
104
+ metadata=metadata,
105
+ outer_size=tensor.size(),
106
+ outer_stride=tensor.stride(),
107
+ ),
108
+ new_idx,
109
+ )
110
+
111
+ self.subclass_meta = _create_subclass_meta(tensor, 0, plain_tensors)[0]
112
+ return plain_tensors
113
+
114
+
115
+ def unwrap_tensor_subclass_parameters(module: torch.nn.Module) -> torch.nn.Module:
116
+ """
117
+ Model transformation that replaces all the parameters that are subclasses to plain tensors.
118
+ This reduces runtime overhead of flattening/unflattening the parameters.
119
+
120
+ This transformation adds parametrization with `torch.nn.utils.parametrize`.
121
+ The FQNs of the subclass parameters will be changed and state_dict will become incompatible with the original model.
122
+ E.g.
123
+ Original model state_dict: {"p1": torch.testing._internal.TwoTensor}
124
+ becomes: {"parametrizations.p2.original0": torch.Tensor, "parametrizations.p2.original1": torch.Tensor}
125
+
126
+ """
127
+ for name, tensor in itertools.chain(
128
+ list(module.named_parameters(recurse=False)),
129
+ # pyrefly: ignore [bad-argument-type, no-matching-overload]
130
+ list(module.named_buffers(recurse=False)),
131
+ ):
132
+ if is_traceable_wrapper_subclass(tensor):
133
+ torch.nn.utils.parametrize.register_parametrization(
134
+ module, name, UnwrapTensorSubclass()
135
+ )
136
+
137
+ for child in module.children():
138
+ unwrap_tensor_subclass_parameters(child)
139
+
140
+ return module
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file contains utilities for tracing through __torch_dispatch__ based tensor subclasses and modes.
3
+ AOTAutograd's responsibility is to trace through all pytorch capabilities that live in the pytorch dispatcher,
4
+ and this includes tensor subclasses that implement __torch_dispatch__.
5
+ """
6
+
7
+ import collections
8
+ from collections.abc import Callable, Iterable, Sequence
9
+ from typing import Any, TypeGuard, TypeVar
10
+
11
+ import torch
12
+ import torch.utils._pytree as pytree
13
+ from torch import SymInt, Tensor
14
+ from torch._custom_class_base import CustomClassBase
15
+ from torch._library.fake_class_registry import maybe_unwrap_fake_script_object
16
+ from torch._library.opaque_object import is_opaque_symbolic_type
17
+ from torch._subclasses.fake_tensor import get_plain_tensors
18
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq
19
+ from torch.types import IntLikeType
20
+ from torch.utils._python_dispatch import (
21
+ is_traceable_wrapper_subclass,
22
+ TraceableWrapperSubclass,
23
+ )
24
+
25
+ from .descriptors import (
26
+ AOTInput,
27
+ AOTOutput,
28
+ DummyAOTInput,
29
+ SubclassGetAttrAOTInput,
30
+ SubclassGetAttrAOTOutput,
31
+ SubclassSizeAOTInput,
32
+ SubclassSizeAOTOutput,
33
+ SubclassStrideAOTInput,
34
+ SubclassStrideAOTOutput,
35
+ )
36
+ from .schemas import (
37
+ FakifiedFlatArgs,
38
+ FxValue,
39
+ MutationType,
40
+ OpaqueMeta,
41
+ PlainTensorMeta,
42
+ SubclassCreationMeta,
43
+ ViewAndMutationMeta,
44
+ )
45
+ from .utils import strict_zip
46
+
47
+
48
+ zip = strict_zip
49
+
50
+ T = TypeVar("T", bound=torch.Tensor)
51
+
52
+
53
+ def requires_subclass_dispatch(
54
+ args: FakifiedFlatArgs, fw_metadata: ViewAndMutationMeta
55
+ ) -> bool:
56
+ args_flattened = pytree.arg_tree_leaves(*args)
57
+ any_subclass_args = any(
58
+ is_traceable_wrapper_subclass(x)
59
+ for x in args_flattened
60
+ if isinstance(x, Tensor)
61
+ )
62
+ from torch._functorch._aot_autograd.schemas import SubclassCreationMeta
63
+
64
+ any_subclass_outputs = any(
65
+ type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta
66
+ )
67
+ # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime.
68
+ return bool(any_subclass_args or any_subclass_outputs)
69
+
70
+
71
+ from .schemas import MemoryFormatMeta
72
+
73
+
74
+ def maybe_suggest_memory_format(
75
+ t: Tensor, with_memory_format: bool
76
+ ) -> MemoryFormatMeta | None:
77
+ if not with_memory_format:
78
+ return None
79
+
80
+ return MemoryFormatMeta.from_tensor(t)
81
+
82
+
83
+ def _safe_metadata_eq(
84
+ outer: Iterable[IntLikeType],
85
+ inner: Iterable[IntLikeType],
86
+ ) -> bool:
87
+ return guard_or_false(sym_eq(tuple(outer), tuple(inner)))
88
+
89
+
90
+ def _find_attr_matching_outer_metadata(
91
+ a: Tensor,
92
+ inner_keys: Sequence[str],
93
+ *,
94
+ metadata_fn: Callable[[Tensor], Iterable[IntLikeType]],
95
+ ) -> str | None:
96
+ tensor_attrs = [key for key in inner_keys if isinstance(getattr(a, key), Tensor)]
97
+ if not tensor_attrs:
98
+ return None
99
+
100
+ outer_metadata = tuple(metadata_fn(a))
101
+ # Only use an attr as the runtime source when every tensor attr agrees
102
+ # with the wrapper metadata; otherwise there is no single attr to trust.
103
+ if all(
104
+ _safe_metadata_eq(outer_metadata, metadata_fn(getattr(a, key)))
105
+ for key in tensor_attrs
106
+ ):
107
+ return tensor_attrs[0]
108
+ return None
109
+
110
+
111
+ def _symint_placeholders(lst: Iterable[IntLikeType]) -> tuple[bool, ...]:
112
+ return tuple(isinstance(s, SymInt) and not s.node.is_nested_int() for s in lst)
113
+
114
+
115
+ def get_subclass_typing_container(
116
+ tensor_subclass: torch.Tensor,
117
+ ) -> dict[type[torch.Tensor], list[type[torch.Tensor]]]:
118
+ """
119
+ Given a subclass, returns a recursive dictionary mapping each
120
+ inner tensors to its subclass types.
121
+ """
122
+
123
+ def _get_types_for_subclass(tensor_subclass: torch.Tensor) -> None:
124
+ if not is_traceable_wrapper_subclass(tensor_subclass):
125
+ return
126
+ tracker[type(tensor_subclass)].append(tensor_subclass)
127
+ inner_keys, _ = tensor_subclass.__tensor_flatten__()
128
+ for key in inner_keys:
129
+ match getattr(tensor_subclass, key):
130
+ case torch.Tensor() as inner_value:
131
+ _get_types_for_subclass(inner_value)
132
+ case CustomClassBase():
133
+ pass
134
+ case unexpected:
135
+ raise AssertionError(
136
+ f"expected Tensor or CustomClassBase, got {type(unexpected)}"
137
+ )
138
+
139
+ tracker: dict[Any, list[Any]] = collections.defaultdict(list)
140
+ _get_types_for_subclass(tensor_subclass)
141
+ return tracker
142
+
143
+
144
+ def create_subclass_metadata(
145
+ a: Any,
146
+ start_idx: int,
147
+ count_symints: bool,
148
+ with_memory_format: bool = False,
149
+ ) -> tuple[Any, int]:
150
+ if not is_traceable_wrapper_subclass(a):
151
+ size_symbol_placeholders = (
152
+ _symint_placeholders(a.size()) if count_symints else ()
153
+ )
154
+ stride_symbol_placeholders = (
155
+ _symint_placeholders(a.stride()) if count_symints else ()
156
+ )
157
+ meta = PlainTensorMeta(
158
+ start_idx + 1,
159
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
160
+ size_symbol_placeholders=size_symbol_placeholders,
161
+ stride_symbol_placeholders=stride_symbol_placeholders,
162
+ )
163
+ return (
164
+ meta,
165
+ start_idx + meta.arg_count,
166
+ )
167
+
168
+ inner_keys, metadata = a.__tensor_flatten__()
169
+ new_start_idx = start_idx
170
+ attrs: dict[str, SubclassCreationMeta | PlainTensorMeta | OpaqueMeta] = {}
171
+
172
+ for key in inner_keys:
173
+ inner_value = getattr(a, key)
174
+ match inner_value:
175
+ case CustomClassBase():
176
+ # During tracing, opaques are wrapped in FakeScriptObject;
177
+ # unwrap to check the real type.
178
+ real_type = type(maybe_unwrap_fake_script_object(inner_value))
179
+ if not is_opaque_symbolic_type(real_type):
180
+ raise RuntimeError(
181
+ f"{real_type.__name__!r} found in tensor attrs of "
182
+ f"{type(a).__name__}.__tensor_flatten__(). "
183
+ "Only tensors and reference-type opaques are allowed "
184
+ "in tensor attrs."
185
+ )
186
+ attrs[key] = OpaqueMeta()
187
+ new_start_idx += 1
188
+ case Tensor():
189
+ new_subclass_meta, new_start_idx = create_subclass_metadata(
190
+ inner_value,
191
+ new_start_idx,
192
+ count_symints=count_symints,
193
+ with_memory_format=with_memory_format,
194
+ )
195
+ attrs[key] = new_subclass_meta
196
+ case _:
197
+ raise AssertionError(
198
+ f"expected Tensor or CustomClassBase, got {type(inner_value)}"
199
+ )
200
+
201
+ # It *must* be because is_traceable_wrapper_subclass() - but mypy is not smart.
202
+ if not isinstance(a, Tensor):
203
+ raise AssertionError(f"expected Tensor, got {type(a)}")
204
+
205
+ new_start_idx = (
206
+ new_start_idx
207
+ + count_symints * len(enumerate_filter_symints(a.size()))
208
+ + count_symints * len(enumerate_filter_symints(a.stride()))
209
+ )
210
+
211
+ return (
212
+ SubclassCreationMeta(
213
+ flat_tensor_start_idx=start_idx,
214
+ arg_count=new_start_idx - start_idx,
215
+ included_subclass_symints=count_symints,
216
+ attrs=attrs,
217
+ meta=metadata,
218
+ outer_size=a.size(), # type: ignore[attr-defined, arg-type]
219
+ outer_stride=a.stride(), # type: ignore[arg-type]
220
+ original_subclass=a,
221
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
222
+ outer_size_from_attr=_find_attr_matching_outer_metadata(
223
+ a, inner_keys, metadata_fn=lambda t: t.size()
224
+ ),
225
+ outer_stride_from_attr=_find_attr_matching_outer_metadata(
226
+ a, inner_keys, metadata_fn=lambda t: t.stride()
227
+ ),
228
+ ),
229
+ new_start_idx,
230
+ )
231
+
232
+
233
+ # Given a flat list of arguments, some of which may be tensor subclasses,
234
+ # computes metadata about "how to reconstruct the current list of subclasses,
235
+ # if we were given their flattened dense tensors instead"
236
+ def create_subclass_meta(
237
+ curr_args: list[Any] | tuple[Any, ...],
238
+ *,
239
+ count_symints: bool = True,
240
+ with_memory_format: bool = False,
241
+ ) -> list[PlainTensorMeta | SubclassCreationMeta]:
242
+ idx = 0
243
+ infos: list[PlainTensorMeta | SubclassCreationMeta] = []
244
+ for a in curr_args:
245
+ if is_traceable_wrapper_subclass(a):
246
+ if not isinstance(a, Tensor):
247
+ raise AssertionError(
248
+ f"expected Tensor for traceable wrapper subclass, got {type(a)}"
249
+ )
250
+ start_idx = idx
251
+ subclass_meta, _ = create_subclass_metadata(
252
+ a,
253
+ start_idx,
254
+ count_symints=count_symints,
255
+ with_memory_format=with_memory_format,
256
+ )
257
+ infos.append(subclass_meta)
258
+ cnt = subclass_meta.arg_count
259
+ else:
260
+ infos.append(
261
+ PlainTensorMeta(
262
+ idx,
263
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
264
+ )
265
+ )
266
+ cnt = 1
267
+ idx += cnt
268
+ return infos
269
+
270
+
271
+ def enumerate_filter_symints(lst: Iterable[IntLikeType]) -> list[tuple[int, SymInt]]:
272
+ # Capture all SymInts from the iterable.
273
+ def symint_check(s: IntLikeType) -> TypeGuard[SymInt]:
274
+ return isinstance(s, SymInt) and not s.node.is_nested_int()
275
+
276
+ return [(i, s) for i, s in enumerate(lst) if symint_check(s)]
277
+
278
+
279
+ def compute_symint_placeholders(lst: Iterable[None | int | SymInt]) -> list[bool]:
280
+ # Non-nested symints are replaced with None in `make_runtime_safe()`
281
+ return [s is None for s in lst]
282
+
283
+
284
+ # Intended to make it easier to define function that is
285
+ # either (AOTInput -> AOTInput) or (AOTOutput -> AOTOutput)
286
+ # but not the other combos
287
+ AOTDescriptor = TypeVar("AOTDescriptor", AOTInput, AOTOutput)
288
+
289
+
290
+ # This function takes in a pytree of arguments and unwraps any tensor
291
+ # subclasses.
292
+ #
293
+ # NOTE: The reason for "append_symints":
294
+ #
295
+ # * At compile time: we append extra symint args when unwrapping primals
296
+ # (but not tangents, because they should always share symints with primals).
297
+ # We also append extra symints when unwrapping the subclass outputs of the
298
+ # traced function, so we can return them as extra outputs
299
+ #
300
+ # * At runtime: we similarly append subclass sizes when we unwrap subclass
301
+ # primals (but not tangents) on entry to the forward. See the runtime version of
302
+ # this function below.
303
+ def unwrap_tensor_subclasses(
304
+ wrapped_args: list[FxValue],
305
+ wrapped_args_descs: Sequence[AOTDescriptor],
306
+ *,
307
+ append_symints: bool,
308
+ ) -> tuple[list[FxValue], list[AOTDescriptor]]:
309
+ def _maybe_fakeify_opaque(v: Any) -> Any:
310
+ # Registered opaque types need to be wrapped as FakeScriptObject for
311
+ # compile-time FX tracing (proxy slot tracking, hashability, etc.).
312
+ if isinstance(v, CustomClassBase):
313
+ from torch._guards import detect_fake_mode
314
+ from torch._library.fake_class_registry import maybe_to_fake_obj
315
+ from torch._library.opaque_object import is_custom_class
316
+
317
+ fake_mode = detect_fake_mode()
318
+ if fake_mode is not None and is_custom_class(type(v)):
319
+ return maybe_to_fake_obj(fake_mode, v)
320
+ return v
321
+
322
+ def flatten_subclass(
323
+ t: FxValue,
324
+ desc: AOTDescriptor,
325
+ *,
326
+ out: tuple[list[FxValue], list[AOTDescriptor]],
327
+ ) -> None:
328
+ # unwrap a subclass into plain tensors and their size/stride if "append_symint"
329
+ # is True
330
+ if not is_traceable_wrapper_subclass(t):
331
+ out[0].append(_maybe_fakeify_opaque(t))
332
+ out[1].append(desc)
333
+ if (
334
+ append_symints
335
+ and isinstance(t, Tensor)
336
+ and isinstance(
337
+ desc, (SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput)
338
+ )
339
+ ):
340
+ sizes = enumerate_filter_symints(t.size())
341
+ strides = enumerate_filter_symints(t.stride())
342
+ out[0].extend(s for _, s in sizes)
343
+ out[0].extend(s for _, s in strides)
344
+ if isinstance(desc, AOTInput):
345
+ out[1].extend(SubclassSizeAOTInput(desc, i) for i, _ in sizes)
346
+ out[1].extend(SubclassStrideAOTInput(desc, i) for i, _ in strides)
347
+ else:
348
+ out[1].extend(SubclassSizeAOTOutput(desc, i) for i, _ in sizes)
349
+ out[1].extend(SubclassStrideAOTOutput(desc, i) for i, _ in strides)
350
+ return
351
+
352
+ attrs, _ = t.__tensor_flatten__()
353
+
354
+ SubclassGetAttr: Callable[[AOTInput | AOTOutput, str], AOTDescriptor]
355
+ SubclassSize: Callable[[AOTInput | AOTOutput, int], AOTDescriptor]
356
+ SubclassStride: Callable[[AOTInput | AOTOutput, int], AOTDescriptor]
357
+ if isinstance(desc, AOTInput):
358
+ SubclassGetAttr = SubclassGetAttrAOTInput # type: ignore[bad-assignment]
359
+ SubclassSize = SubclassSizeAOTInput # type: ignore[bad-assignment]
360
+ SubclassStride = SubclassStrideAOTInput # type: ignore[bad-assignment]
361
+ else:
362
+ SubclassGetAttr = SubclassGetAttrAOTOutput # type: ignore[bad-assignment]
363
+ SubclassSize = SubclassSizeAOTOutput # type: ignore[bad-assignment]
364
+ SubclassStride = SubclassStrideAOTOutput # type: ignore[bad-assignment]
365
+
366
+ for attr in attrs:
367
+ inner_value = getattr(t, attr)
368
+ n_desc: Any = SubclassGetAttr(desc, attr)
369
+ flatten_subclass(inner_value, n_desc, out=out)
370
+
371
+ if append_symints:
372
+ sizes = enumerate_filter_symints(t.size())
373
+ strides = enumerate_filter_symints(t.stride())
374
+ out[0].extend(s for _, s in sizes)
375
+ out[0].extend(s for _, s in strides)
376
+ out[1].extend(SubclassSize(desc, i) for i, _ in sizes)
377
+ out[1].extend(SubclassStride(desc, i) for i, _ in strides)
378
+
379
+ xs_inner: list[FxValue] = []
380
+ descs_inner: list[AOTDescriptor] = []
381
+
382
+ for x, desc in zip(wrapped_args, wrapped_args_descs):
383
+ flatten_subclass(x, desc, out=(xs_inner, descs_inner))
384
+
385
+ return xs_inner, descs_inner
386
+
387
+
388
+ # subclass_metas is needed at runtime to compute which indices are symints in
389
+ # the outer_size/outer_stride
390
+ def runtime_unwrap_tensor_subclasses(
391
+ wrapped_args: list[Tensor | int],
392
+ *,
393
+ append_symints: bool,
394
+ subclass_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None,
395
+ ) -> list[int | Tensor | SymInt | CustomClassBase]:
396
+ def flatten_subclass(
397
+ x: Tensor | TraceableWrapperSubclass,
398
+ subclass_meta: PlainTensorMeta | SubclassCreationMeta | OpaqueMeta | None,
399
+ *,
400
+ out: list[CustomClassBase | SymInt | Tensor | int],
401
+ ) -> list[CustomClassBase | SymInt | Tensor | int]:
402
+ def append_plain_tensor_symints(tensor: Tensor, meta: PlainTensorMeta) -> None:
403
+ size = tensor.size()
404
+ if len(size) != len(meta.size_symbol_placeholders):
405
+ raise AssertionError(
406
+ f"size length mismatch: {len(size)} != {len(meta.size_symbol_placeholders)}"
407
+ )
408
+ out.extend(
409
+ [
410
+ r
411
+ for (r, is_symint) in zip(size, meta.size_symbol_placeholders)
412
+ if is_symint
413
+ ]
414
+ )
415
+
416
+ stride = tensor.stride()
417
+ if len(stride) != len(meta.stride_symbol_placeholders):
418
+ raise AssertionError(
419
+ f"stride length mismatch: {len(stride)} != {len(meta.stride_symbol_placeholders)}"
420
+ )
421
+ out.extend(
422
+ [
423
+ r
424
+ for (r, is_symint) in zip(stride, meta.stride_symbol_placeholders)
425
+ if is_symint
426
+ ]
427
+ )
428
+
429
+ if not is_traceable_wrapper_subclass(x):
430
+ out.append(x)
431
+ if append_symints and isinstance(subclass_meta, PlainTensorMeta):
432
+ append_plain_tensor_symints(x, subclass_meta)
433
+ return out
434
+
435
+ if not isinstance(x, Tensor):
436
+ raise AssertionError(f"expected Tensor, got {type(x)}")
437
+ if not isinstance(subclass_meta, SubclassCreationMeta):
438
+ raise AssertionError("subclass_meta should be a SubclassCreationMeta")
439
+
440
+ attrs, _ = x.__tensor_flatten__()
441
+
442
+ for attr in attrs:
443
+ inner_value = getattr(x, attr)
444
+ match inner_value:
445
+ case CustomClassBase():
446
+ out.append(inner_value)
447
+ case Tensor():
448
+ inner_meta = subclass_meta.attrs.get(attr)
449
+ flatten_subclass(inner_value, inner_meta, out=out)
450
+ case _:
451
+ raise AssertionError(
452
+ f"expected Tensor or CustomClassBase, got {type(inner_value)}"
453
+ )
454
+
455
+ if append_symints:
456
+ # outer_size
457
+ size = x.size()
458
+ symint_placeholders = compute_symint_placeholders(subclass_meta.outer_size)
459
+ if len(size) != len(symint_placeholders):
460
+ raise AssertionError(
461
+ f"size length mismatch: {len(size)} != {len(symint_placeholders)}"
462
+ )
463
+ out.extend(
464
+ [r for (r, is_symint) in zip(size, symint_placeholders) if is_symint]
465
+ )
466
+
467
+ # outer_stride
468
+ stride = x.stride()
469
+ symint_placeholders = compute_symint_placeholders(
470
+ subclass_meta.outer_stride
471
+ )
472
+ if len(stride) != len(symint_placeholders):
473
+ raise AssertionError(
474
+ f"stride length mismatch: {len(stride)} != {len(symint_placeholders)}"
475
+ )
476
+ out.extend(
477
+ [r for (r, is_symint) in zip(stride, symint_placeholders) if is_symint]
478
+ )
479
+ return out
480
+
481
+ xs_inner: list[int | Tensor | SymInt | CustomClassBase] = []
482
+
483
+ if append_symints:
484
+ if subclass_metas is None:
485
+ raise AssertionError(
486
+ "subclass_metas must not be None when append_symints is True"
487
+ )
488
+
489
+ for idx, x in enumerate(wrapped_args):
490
+ if not is_traceable_wrapper_subclass(x):
491
+ xs_inner.append(x)
492
+ continue
493
+
494
+ if subclass_metas is None:
495
+ get_plain_tensors(x, out=xs_inner)
496
+ else:
497
+ subclass_meta = subclass_metas[idx]
498
+ if not isinstance(subclass_meta, SubclassCreationMeta):
499
+ raise AssertionError(
500
+ f"expected SubclassCreationMeta, got {type(subclass_meta)}"
501
+ )
502
+ flatten_subclass(x, subclass_meta, out=xs_inner)
503
+
504
+ return xs_inner
505
+
506
+
507
+ def unwrap_tensor_subclasses_with_indices_to_original(
508
+ wrapped_args: list[Any],
509
+ ) -> tuple[list[Any], list[int]]:
510
+ ret_unwrapped = []
511
+ ret_indices_to_original = []
512
+ for i, a in enumerate(wrapped_args):
513
+ a_unwrapped, _ = unwrap_tensor_subclasses(
514
+ [a], [DummyAOTInput(9999)], append_symints=False
515
+ )
516
+ ret_unwrapped.extend(a_unwrapped)
517
+ n = len(a_unwrapped)
518
+ ret_indices_to_original.extend([i] * n)
519
+
520
+ return ret_unwrapped, ret_indices_to_original
521
+
522
+
523
+ def remap_unwrapped_subclass_arg_indices(
524
+ wrapped_args: list[Any], static_input_indices: list[int]
525
+ ) -> list[int]:
526
+ def static_arg_slots(arg: Any, *, include_plain_tensor_symints: bool) -> list[bool]:
527
+ # Forwarded SymInts occupy flattened arg positions, but static input indices
528
+ # describe tensor/opaque slots whose value should not be copied.
529
+ if not is_traceable_wrapper_subclass(arg):
530
+ if include_plain_tensor_symints and isinstance(arg, Tensor):
531
+ num_symints = len(enumerate_filter_symints(arg.size())) + len(
532
+ enumerate_filter_symints(arg.stride())
533
+ )
534
+ return [True] + [False] * num_symints
535
+ return [True]
536
+
537
+ slots = []
538
+ attrs, _ = arg.__tensor_flatten__()
539
+ for attr in attrs:
540
+ inner_value = getattr(arg, attr)
541
+ match inner_value:
542
+ case CustomClassBase():
543
+ slots.append(True)
544
+ case Tensor():
545
+ slots.extend(
546
+ static_arg_slots(inner_value, include_plain_tensor_symints=True)
547
+ )
548
+ case _:
549
+ raise AssertionError(
550
+ f"expected Tensor or CustomClassBase, got {type(inner_value)}"
551
+ )
552
+
553
+ slots.extend(
554
+ [False]
555
+ * (
556
+ len(enumerate_filter_symints(arg.size()))
557
+ + len(enumerate_filter_symints(arg.stride()))
558
+ )
559
+ )
560
+ return slots
561
+
562
+ static_input_indices_set = set(static_input_indices)
563
+ new_ind = 0
564
+ remapped_static_indices = []
565
+ for i, arg in enumerate(wrapped_args):
566
+ slots = (
567
+ static_arg_slots(arg, include_plain_tensor_symints=False)
568
+ if is_traceable_wrapper_subclass(arg)
569
+ else [True]
570
+ )
571
+
572
+ for is_static_arg_slot in slots:
573
+ if i in static_input_indices_set and is_static_arg_slot:
574
+ remapped_static_indices.append(new_ind)
575
+
576
+ new_ind += 1
577
+
578
+ return remapped_static_indices
579
+
580
+
581
+ # Turns a flattened list of tensor arguments into (maybe) subclass tensors.
582
+ # This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in.
583
+ def wrap_tensor_subclasses(
584
+ unwrapped_args: Sequence[Any],
585
+ *,
586
+ subclass_metas: list[PlainTensorMeta | SubclassCreationMeta],
587
+ num_fw_outs_saved_for_bw: int | None = None,
588
+ included_subclass_symints: bool = False,
589
+ is_runtime: bool = False,
590
+ make_subclass_override: Callable[..., Any] | None = None,
591
+ ) -> tuple[Any, ...]:
592
+ # pyrefly: ignore [implicit-any]
593
+ wrapped_args = []
594
+ num_args_tallied = 0
595
+ for subclass_meta in subclass_metas:
596
+ if isinstance(subclass_meta, PlainTensorMeta):
597
+ wrapped_args.append(unwrapped_args[subclass_meta.unwrapped_idx])
598
+ num_args_tallied += subclass_meta.arg_count
599
+ else:
600
+ if not isinstance(subclass_meta, SubclassCreationMeta):
601
+ raise AssertionError(
602
+ f"expected SubclassCreationMeta, got {type(subclass_meta)}"
603
+ )
604
+ if subclass_meta.included_subclass_symints != included_subclass_symints:
605
+ raise AssertionError(
606
+ f"included_subclass_symints mismatch: {subclass_meta.included_subclass_symints} != {included_subclass_symints}"
607
+ )
608
+
609
+ if make_subclass_override:
610
+ wrapped_args.append(
611
+ make_subclass_override(subclass_meta, is_runtime, unwrapped_args)
612
+ )
613
+ else:
614
+ wrapped_args.append(
615
+ subclass_meta.creation_fn(
616
+ unwrapped_args,
617
+ is_runtime=is_runtime,
618
+ )
619
+ )
620
+ num_args_tallied += subclass_meta.arg_count
621
+
622
+ # Note: [Partitioner handling for Subclasses, Part 2]
623
+ # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw,
624
+ # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them.
625
+ #
626
+ # When this function is called at runtime in the forward,
627
+ # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs.
628
+ #
629
+ # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen?
630
+ # Answer: we do it **inside of our compiled autograd.Function**.
631
+ # This seems like morally the right place: autograd happens above subclass desugaring,
632
+ # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors.
633
+ #
634
+ # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph
635
+ # into a forward and backward graph, we end up with some activations that show up as extra outputs
636
+ # in the compiled forward graph, that are **not** user outputs.
637
+ # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses.
638
+ #
639
+ # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`),
640
+ # we computed subclass metadata on every forward output, but this did **not** include activations
641
+ # created by the partitioner.
642
+ # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations),
643
+ # but `subclass_metas` will only correspond to subclass metadata on `user_fw_outs`.
644
+ # We then need to make sure that we return (*wrapped_user_fw_outs, *activations).
645
+ if num_fw_outs_saved_for_bw is not None:
646
+ if len(unwrapped_args) != num_args_tallied + num_fw_outs_saved_for_bw:
647
+ raise AssertionError(
648
+ f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal "
649
+ f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of "
650
+ f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})"
651
+ )
652
+ activations = unwrapped_args[num_args_tallied:]
653
+ if isinstance(wrapped_args, tuple) and isinstance(activations, tuple):
654
+ return wrapped_args + activations
655
+ return tuple(list(wrapped_args) + list(activations))
656
+ else:
657
+ if len(unwrapped_args) != num_args_tallied:
658
+ raise AssertionError(
659
+ f"Expected {len(unwrapped_args)} == {num_args_tallied}"
660
+ )
661
+ return tuple(wrapped_args)
662
+
663
+
664
+ # Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses.
665
+ # This function carefully handles the inference vs. joint cases:
666
+ # - when is_joint_structure is True, args is (primals, tangents)
667
+ # - when is_joint_structure is False, args is [*primals]
668
+ def wrap_tensor_subclasses_maybe_joint(
669
+ unwrapped_args: Sequence[Any],
670
+ *,
671
+ is_joint_structure: bool,
672
+ meta: ViewAndMutationMeta,
673
+ ) -> tuple[Any, ...]:
674
+ # Since this function is reused for both inference and joint graphs,
675
+ if is_joint_structure:
676
+ if not (isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2):
677
+ unwrapped_len = (
678
+ len(unwrapped_args)
679
+ if isinstance(unwrapped_args, (tuple, list))
680
+ else "N/A"
681
+ )
682
+ raise AssertionError(
683
+ f"expected tuple of length 2 for joint structure, "
684
+ f"got {type(unwrapped_args)} with length {unwrapped_len}"
685
+ )
686
+ if not (
687
+ isinstance(unwrapped_args[0], (tuple, list))
688
+ and isinstance(unwrapped_args[1], (tuple, list))
689
+ ):
690
+ raise AssertionError(
691
+ f"expected primals and tangents to be tuple or list, got {type(unwrapped_args[0])} and {type(unwrapped_args[1])}"
692
+ )
693
+ primals, tangents = unwrapped_args[0], unwrapped_args[1]
694
+ wrapped_primals = wrap_tensor_subclasses(
695
+ primals,
696
+ subclass_metas=meta.subclass_inp_meta,
697
+ included_subclass_symints=True,
698
+ )
699
+ wrapped_tangents = wrap_tensor_subclasses(
700
+ tangents,
701
+ subclass_metas=meta.subclass_tangent_meta,
702
+ included_subclass_symints=False,
703
+ )
704
+ return (wrapped_primals, wrapped_tangents)
705
+ else:
706
+ wrapped_args = wrap_tensor_subclasses(
707
+ unwrapped_args,
708
+ subclass_metas=meta.subclass_inp_meta,
709
+ included_subclass_symints=True,
710
+ )
711
+ return wrapped_args
712
+
713
+
714
+ def compute_inner_mutated_inp_indices_from_subclass_meta(
715
+ fw_metadata: ViewAndMutationMeta,
716
+ inner_metadata: ViewAndMutationMeta,
717
+ ) -> list[int]:
718
+ # Note: [Recomputing subclass mutation handling]
719
+ #
720
+ # Generally, if a subclass requires grad, its components will not require grad.
721
+ # But for the purposes of tracking returned tensors, we should treat those component
722
+ # tensors as if they require grad.
723
+ #
724
+ # For example, if the subclass tensor requires grad and will be mutated in a way that
725
+ # requires us to handle the mutation outside of the graph, we need to return it
726
+ # from the forward graph. The inner_meta data won't consider the component tensors
727
+ # as if they need to be returned, because they don't require grad; but really, we
728
+ # should handle those tensors the same way we handle the subclass tensor itself; i.e.
729
+ # if we'd include the subclass tensor as part of the outputs, then we should also
730
+ # include the component tensors.
731
+ #
732
+ # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs
733
+ # from the outer subclass tensors and propagating
734
+
735
+ updated_input_info = []
736
+ inner_idx = 0
737
+ if not fw_metadata.subclass_inp_meta:
738
+ # Sometimes we don't have subclass info, e.g. synthetic_base codepaths
739
+ return inner_metadata.mutated_inp_runtime_indices
740
+ if len(fw_metadata.subclass_inp_meta) != len(fw_metadata.input_info):
741
+ raise AssertionError(
742
+ f"subclass_inp_meta length ({len(fw_metadata.subclass_inp_meta)}) != input_info length ({len(fw_metadata.input_info)})"
743
+ )
744
+ for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta):
745
+ if isinstance(inp_meta, PlainTensorMeta):
746
+ if outer_idx >= len(fw_metadata.input_info):
747
+ raise AssertionError(
748
+ f"outer_idx ({outer_idx}) >= len(fw_metadata.input_info) ({len(fw_metadata.input_info)})"
749
+ )
750
+ if inner_metadata is not None:
751
+ if inner_idx >= len(inner_metadata.input_info):
752
+ raise AssertionError(
753
+ f"inner_idx ({inner_idx}) >= len(inner_metadata.input_info) ({len(inner_metadata.input_info)})"
754
+ )
755
+ if (
756
+ inner_metadata.input_info[inner_idx]
757
+ != fw_metadata.input_info[outer_idx]
758
+ ):
759
+ raise AssertionError(
760
+ f"input_info mismatch at inner_idx={inner_idx}, outer_idx={outer_idx}: "
761
+ f"{inner_metadata.input_info[inner_idx]} != {fw_metadata.input_info[outer_idx]}"
762
+ )
763
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
764
+ inner_idx += 1
765
+ else:
766
+ if inp_meta.original_subclass is None:
767
+ raise AssertionError(
768
+ "inp_meta.original_subclass must not be None for SubclassCreationMeta"
769
+ )
770
+ for _ in range(inp_meta.arg_count):
771
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
772
+ inner_idx += 1
773
+ if inner_metadata is not None:
774
+ if len(inner_metadata.input_info) != len(updated_input_info):
775
+ raise AssertionError(
776
+ f"inner_metadata.input_info length ({len(inner_metadata.input_info)}) "
777
+ f"!= updated_input_info length ({len(updated_input_info)})"
778
+ )
779
+
780
+ return [
781
+ i
782
+ for i, inp in enumerate(updated_input_info)
783
+ if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH
784
+ ]
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lower a GraphModule to a self-contained Python module via AOTAutograd + Inductor.
2
+
3
+ This is the AOT half of the backend contract behind ``torch.compiler.precompile``:
4
+
5
+ python_code, cache = compile_to_python(gm, example_inputs)
6
+
7
+ ``inductor.compile_to_python`` produces only the inner Inductor ``call`` (kernels
8
+ for the post-AOTAutograd dense graph). This module wraps that with the prelude /
9
+ epilogue (input-mutation reflection, output-alias regen, subclass wrap/unwrap,
10
+ ...) by COMPOSING AOTAutograd's own codegen'd runtime-wrapper source -- captured
11
+ during compile -- rather than reimplementing it. Every wrapper is spliced verbatim as a
12
+ real top-level ``def``, with its closed-over globals hoisted to module-scope assignments,
13
+ so the module reads as ordinary code. These nest in the SAME order the runtime builds:
14
+ the INNER chain wrappers (subclass / functionalized-RNG) wrap the inner ``call`` and are
15
+ composed inside the orchestration, while the OUTER ``CompilerWrapper``s (dedup / synthetic
16
+ base) wrap the orchestration itself (via a single-arg adapter over it). Cross-wrapper references, the inner ``call`` chain,
17
+ public helpers, and baked metadata objects (reconstructed as source -- see
18
+ ``_emit_value``) are wired by name; a guard rejects the rare case where a wrapper def
19
+ name or hoisted global would collide with another top-level name (a sibling wrapper or
20
+ an inner-module binding) rather than silently rebinding one.
21
+ The result is a standalone module exposing ``call(flat_inputs) -> outputs`` that
22
+ runs on its own (JIT-compiling kernels); ``cache`` is an opaque acceleration (or
23
+ None).
24
+
25
+ Baked metadata is emitted as plain Python source (no pickle / base64 blobs), so the
26
+ generated module is fully auditable and exec'ing it never invokes ``pickle.loads``.
27
+ A leaf that cannot be expressed as source raises NotImplementedError rather than
28
+ falling back to an opaque embedding.
29
+
30
+ Contract note: the standalone ``call`` deliberately substitutes ``nullcontext`` / a
31
+ no-op for the runtime's first-invocation context and profiler prologue, dropping the
32
+ cold-start custom-op aliasing analysis and the profiler prologue -- both diagnostics
33
+ with no effect on numerics (see the generated-call emission site). One caveat: that
34
+ dropped first-invocation custom-op aliasing analysis can itself RAISE under
35
+ ``config.error_on_custom_op_aliasing`` (default on in CI), so a graph whose custom op
36
+ violates the aliasing contract runs SILENTLY in the standalone artifact where the
37
+ eager / compiled path would error -- an intentional trade-off, not a numerics bug.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import ast
43
+ import re
44
+ import threading
45
+ from typing import Any, TYPE_CHECKING
46
+
47
+ from .codegen import capture_generated_sources, GeneratedSource
48
+ from .source_emit import _REBUILD_HELPER, emit_value
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ from collections.abc import Callable, Iterator, Sequence
53
+
54
+ from torch.fx import GraphModule
55
+
56
+
57
+ # Serializes compile_to_python: the wrapper-source capture is thread-local, but the
58
+ # AOTAutograd capture pass and the inner inductor compile swap process-global cache state
59
+ # (see the THREADING note on compile_to_python), so concurrent compiles must not overlap.
60
+ # An RLock (not a
61
+ # plain Lock) because this entry point is re-entrant on a single thread: a custom
62
+ # backend or inductor pass invoked while the lock is held may call back into this
63
+ # lowering to compile a subgraph on the SAME thread, and a plain Lock would
64
+ # self-deadlock on that re-entry. On-thread re-entry is safe here: the capture sink and
65
+ # the cache-state swap (CacheArtifactManager.with_fresh_cache) are each self-contained
66
+ # per call, so a nested compile neither corrupts the outer capture nor the outer cache
67
+ # scope.
68
+ _COMPILE_LOCK = threading.RLock()
69
+
70
+
71
+ # ======================================================================
72
+ # WHAT IS GOING ON HERE: composing AOTAutograd's runtime wrappers as source
73
+ # ======================================================================
74
+ #
75
+ # AOTAutograd does not hand back a single flat function. The dense graph Inductor
76
+ # compiles (the inner ``call``) is only the arithmetic core; around it AOTAutograd
77
+ # wraps a prelude/epilogue that does what the core cannot express: reflecting input
78
+ # mutations back onto the caller's tensors, regenerating outputs that alias an input
79
+ # or each other, wrapping/unwrapping tensor subclasses, de-duplicating aliased
80
+ # inputs, and threading functionalized RNG state. At runtime AOTAutograd emits each
81
+ # wrapper as Python *source*, exec's it (the chokepoint is _compile_and_exec_source
82
+ # in codegen.py), and the resulting function runs while closing over a
83
+ # globals dict supplied in-process -- i.e. a wrapper is (source text) +
84
+ # ({local_name: live_object}).
85
+ #
86
+ # The objects a wrapper closes over come in a few kinds:
87
+ # - public runtime helpers the codegen'd source references (e.g. increment_version,
88
+ # gen_alias_from_base, _unwrap_tensoralias, mark_dynamo_propagated_dynamic_indices,
89
+ # the CUDARngStateHelper staticmethods) -- ordinary importable objects;
90
+ # - the inner Inductor ``call`` that the chain ultimately invokes;
91
+ # - sibling captured wrappers -- the next link of the runtime chain (an inner subclass /
92
+ # functionalized-RNG wrapper, or an outer dedup / synthetic-base wrapper, whose body
93
+ # calls the link it wraps -- the orchestration's outer closure for the innermost outer
94
+ # wrapper), plus the orchestration's output-alias and mutation epilogue helpers, which
95
+ # it closes over directly by reference;
96
+ # - per-graph metadata baked at compile time (e.g. a ViewMetaSequence for alias
97
+ # regen, tensor-subclass metadata) -- live objects with no import path.
98
+ #
99
+ # Concretely, the module emitted for ``x.view(-1)`` (an output aliasing its input) has
100
+ # one of each (heavily trimmed; the (1)-(4) tags match the kinds listed above):
101
+ #
102
+ # from ...standalone_runtime import gen_alias_from_base # (1) public helper
103
+ # <inner Inductor kernels + ``def call(args): ...``>
104
+ # _inner_call = call # (2) the inner call
105
+ # _vms_0 = ViewMetaSequence._from_parts(...) # (4) metadata as source
106
+ # def _alias_fn(orig_inputs, fw_outs): # (3) sibling wrapper
107
+ # return [gen_alias_from_base(orig_inputs[0], fw_outs[0], False, _vms_0, ...)]
108
+ # _replay_aliases_ = _alias_fn # (3) orchestration's ref
109
+ # def _runtime_wrapper(_compiled_fn_, _first_ctx_, _on_before_call_, args):
110
+ # all_outs = _compiled_fn_(args) # (2) inner call invoked
111
+ # return _replay_aliases_(orig_inputs, all_outs) # (3) sibling invoked
112
+ # def call(flat_inputs):
113
+ # return _runtime_wrapper(
114
+ # _inner_call, contextlib.nullcontext, lambda: None, list(flat_inputs))
115
+ #
116
+ # We do NOT reimplement any of this. We CAPTURE AOTAutograd's exact codegen'd wrapper
117
+ # source together with the (pre-exec) globals dict each wrapper closed over: a
118
+ # thread-local sink in codegen.py records one GeneratedSource per wrapper.
119
+ # To trigger the capture we run AOTAutograd ourselves (under no_grad, the inference path)
120
+ # with a capture-only inner compiler: it grabs the dense inner graph and returns a
121
+ # placeholder callable, so AOTAutograd still codegen's the runtime-wrapper chain AROUND
122
+ # that placeholder -- which is what the sink records. Inductor does not run in that pass;
123
+ # it runs once afterward on the captured dense graph (via inductor.compile_to_python), and
124
+ # the composer swaps the placeholder for the inner inductor ``call`` by object identity.
125
+ #
126
+ # THE COMPOSITION PROBLEM. To turn a captured wrapper into a real top-level ``def`` in
127
+ # the standalone module we splice its source verbatim. But that source refers to each
128
+ # global by the LOCAL ALIAS AOTAutograd happened to choose (e.g. ``compiled_fn`` for
129
+ # the inner call), not by any importable name. So for each ``{name: obj}`` in the
130
+ # captured globals dict we emit a top-level binding ``name = <source for obj>`` (see
131
+ # _emit_inline) -- except when the resolved expression already IS that module-scope
132
+ # name (an import, or ``torch``), which needs no binding. The hard part is the right-
133
+ # hand side: given only a live object, produce source that reproduces it. That requires
134
+ # RECOGNIZING what the object is, the job of _resolve_global and the id-keyed
135
+ # structures it consults, in order:
136
+ # - inner_call_id -> the inner ``call`` becomes ``_inner_call``
137
+ # - fn_id_to_name -> a sibling wrapper's fn becomes that wrapper's own name
138
+ # - _known_helper_table() -> an importable helper becomes (import, expr)
139
+ # - anything else: reconstruct field-by-field as source (_emit_value), or raise.
140
+ # Recognition is by id() (object identity), not value-equality: for "is this the EXACT
141
+ # object the wrapper closed over," == is the wrong tool (functions don't compare by
142
+ # value, and an equal-but-different object would mis-resolve). Value-equality IS used,
143
+ # but later and for a different job -- _emit_value round-trip-checks reconstructed
144
+ # metadata (rebuilt == obj) before trusting it. Every hoisted name is _reserve'd: a
145
+ # collision with a sibling wrapper's name or an inner-module binding fails loudly
146
+ # rather than silently rebinding.
147
+ #
148
+ # WHY THIS IS SAFE ACROSS PROCESSES AND MACHINES. Every id() above is consulted ONLY
149
+ # here, during composition, in the process that just ran the compile -- where all the
150
+ # candidate objects (helpers, the inner call, sibling wrappers) are simultaneously
151
+ # alive, held by the GeneratedSource records and the captured globals dicts, so no
152
+ # address can be freed and reused mid-pass. Nothing the composer emits carries an id()
153
+ # value, a live object, or any thread-local capture state: it emits only import lines,
154
+ # ``name = expr`` bindings, and verbatim def source (the inner Inductor source is
155
+ # likewise spliced as text). Grep the GENERATED module and there is no ``id(`` to
156
+ # find. By the time the user holds the Python, all the process/thread-local state the
157
+ # composer leaned on is gone; what ships is imports + name bindings + verbatim code.
158
+ # Load it on another machine with the same torch version and the imports resolve by
159
+ # name and the bindings reconstruct -- identity was a compile-time recognition device,
160
+ # never a serialized artifact (live tensors / pickle / base64 blobs are rejected
161
+ # outright rather than embedded).
162
+ #
163
+ # So the one genuine cross-machine contract is not id() but that the *names* the
164
+ # artifact imports still resolve on load. Helpers are emitted as either ``import
165
+ # torch`` (the torch module and stable public paths, e.g.
166
+ # torch.autograd.graph.increment_version) or an import from the single small surface
167
+ # standalone_runtime.py (for the AOTAutograd-area internals -- plus CUDARngStateHelper,
168
+ # re-exported there for import-ordering -- whose locations are not themselves a stable
169
+ # contract). That file's IDENTITY CONTRACT -- re-exports must preserve object id --
170
+ # exists purely so the COMPOSER's id-lookup keeps matching; it is a compile-time
171
+ # requirement, and the runtime artifact has no id dependency of its own.
172
+ # ======================================================================
173
+
174
+
175
+ # Global objects the codegen'd wrappers close over that are reproducible as an
176
+ # import in the standalone module (rather than reconstructed field-by-field). Maps
177
+ # object id -> (import_statement, expression). Built lazily to avoid import cycles.
178
+ def _known_helper_table() -> dict[int, tuple[str, str]]:
179
+ # Generated artifacts import runtime helpers from the single stable surface
180
+ # ``standalone_runtime`` (not scattered AOTAutograd internals).
181
+ import torch
182
+
183
+ from . import standalone_runtime as rt
184
+
185
+ _RT = "from torch._functorch._aot_autograd.standalone_runtime import"
186
+ table: dict[int, tuple[str, str]] = {
187
+ id(torch): ("import torch", "torch"),
188
+ id(rt.normalize_as_list): (f"{_RT} normalize_as_list", "normalize_as_list"),
189
+ id(rt.mark_dynamo_propagated_dynamic_indices): (
190
+ f"{_RT} mark_dynamo_propagated_dynamic_indices",
191
+ "mark_dynamo_propagated_dynamic_indices",
192
+ ),
193
+ id(torch.autograd.graph.increment_version): (
194
+ "import torch",
195
+ "torch.autograd.graph.increment_version",
196
+ ),
197
+ id(rt.gen_alias_from_base): (
198
+ f"{_RT} gen_alias_from_base",
199
+ "gen_alias_from_base",
200
+ ),
201
+ id(rt._unwrap_tensoralias): (
202
+ f"{_RT} _unwrap_tensoralias",
203
+ "_unwrap_tensoralias",
204
+ ),
205
+ id(rt.CUDARngStateHelper.get_torch_state_as_tuple): (
206
+ f"{_RT} CUDARngStateHelper",
207
+ "CUDARngStateHelper.get_torch_state_as_tuple",
208
+ ),
209
+ id(rt.CUDARngStateHelper.set_new_offset): (
210
+ f"{_RT} CUDARngStateHelper",
211
+ "CUDARngStateHelper.set_new_offset",
212
+ ),
213
+ }
214
+ return table
215
+
216
+
217
+ _MODULE_HEADER = """\
218
+ # Generated by torch._functorch.aot_autograd.compile_to_python -- do not edit.
219
+ #
220
+ # Self-contained, executable module exposing ``call(flat_inputs) -> outputs`` for
221
+ # the post-AOTAutograd graph. The Inductor kernels JIT-compile from the inlined
222
+ # source on first call (no cache needed). The prelude/epilogue is AOTAutograd's own
223
+ # codegen'd runtime wrappers, not reimplemented: each (the orchestration and any chain
224
+ # wrappers) is spliced as a real top-level ``def`` with its closed-over globals (inner
225
+ # ``call``, sibling wrappers, public helpers, baked metadata reconstructed as source)
226
+ # hoisted to module-scope assignments -- so results match eager. The companion opaque
227
+ # cache is only an acceleration; this module never reads it.
228
+ """
229
+
230
+
231
+ def _resolve_global(
232
+ obj: object,
233
+ helper_table: dict[int, tuple[str, str]],
234
+ inner_call_id: int | None,
235
+ fn_id_to_name: dict[int, str],
236
+ imports: set[str],
237
+ orch_closure_id: int | None = None,
238
+ orch_entry_name: str | None = None,
239
+ ) -> str:
240
+ """Return a Python expression (valid in the generated module) that reproduces
241
+ ``obj``, recording any needed import. Raises NotImplementedError if ``obj`` is
242
+ neither the inner call, a sibling wrapper, a known helper, nor source-
243
+ reconstructible (see ``_emit_value``)."""
244
+ if inner_call_id is not None and id(obj) == inner_call_id:
245
+ return "_inner_call"
246
+ # An OUTER wrapper (dedup / synthetic base) closes over the orchestration's outer
247
+ # closure as its inner. That closure is not a captured wrapper and has no import
248
+ # path, so wire it to the single-arg orchestration entry adapter the composer emits.
249
+ if orch_closure_id is not None and id(obj) == orch_closure_id:
250
+ if orch_entry_name is None:
251
+ raise AssertionError("expected orch_entry_name to be not None")
252
+ return orch_entry_name
253
+ if id(obj) in fn_id_to_name:
254
+ return fn_id_to_name[id(obj)]
255
+ if id(obj) in helper_table:
256
+ import_stmt, expr = helper_table[id(obj)]
257
+ if import_stmt:
258
+ imports.add(import_stmt)
259
+ return expr
260
+ # Not a wired reference (inner call / sibling wrapper / helper): emit ``obj`` as
261
+ # plain reconstruction source. Raises if it is not source-expressible.
262
+ return emit_value(obj, imports)
263
+
264
+
265
+ def _module_level_names(tree: ast.Module) -> set[str]:
266
+ """Names bound at module scope by a parsed module. Used to seed ``_reserve`` so an
267
+ inlined wrapper's def name or hoisted global (chain wrapper or orchestration) cannot
268
+ silently shadow a top-level name the inner Inductor module already binds."""
269
+ names: set[str] = set()
270
+ for n in tree.body:
271
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
272
+ names.add(n.name)
273
+ elif isinstance(n, ast.Assign):
274
+ # Walk each target so tuple/list/starred unpacking (``a, b = ...`` /
275
+ # ``first, *rest = ...``) is covered, not just bare-name targets.
276
+ for t in n.targets:
277
+ names.update(x.id for x in ast.walk(t) if isinstance(x, ast.Name))
278
+ elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
279
+ names.add(n.target.id)
280
+ elif isinstance(n, (ast.Import, ast.ImportFrom)):
281
+ names.update(a.asname or a.name.split(".")[0] for a in n.names)
282
+ elif isinstance(n, ast.Delete):
283
+ # Inductor's inner module does ``async_compile = AsyncCompile()`` then
284
+ # ``del async_compile`` at module scope; a del'd name does not survive, so it
285
+ # must not be reserved (else a hoisted wrapper global of the same name would
286
+ # trip a spurious collision). Body order is assign-then-del, so removing here
287
+ # leaves only names that actually persist.
288
+ for t in n.targets:
289
+ names.difference_update(
290
+ x.id for x in ast.walk(t) if isinstance(x, ast.Name)
291
+ )
292
+ return names
293
+
294
+
295
+ def _compose_standalone_module(
296
+ inner_python: str, captured: list[GeneratedSource], inner_call_obj: Any
297
+ ) -> str:
298
+ """Compose the inner Inductor ``call`` with AOTAutograd's captured runtime
299
+ wrappers into one standalone module exposing ``call(flat_inputs) -> outputs``.
300
+
301
+ Every wrapper (chain wrappers and the orchestration) is spliced as a real top-level
302
+ ``def`` with its closed-over globals hoisted to module-scope assignments (resolved
303
+ here). They are chained by name in the SAME nesting the runtime builds: the
304
+ orchestration is invoked with the INNER InductorWrapper chain head (subclass / RNG)
305
+ as its inner, and any OUTER ``CompilerWrapper`` (dedup / synthetic base, applied
306
+ AROUND the orchestration in ``graph_compile._aot_stage2c_make_inference_function``)
307
+ wraps a single-arg adapter over the orchestration.
308
+
309
+ ``inner_call_obj`` is the placeholder the capture pass returned for the inner call;
310
+ its identity is authoritative (see the note at the inner-call site below).
311
+ """
312
+ # The capture sink is duration-scoped over the inner inductor compile, with no
313
+ # originating-graph id at install time, so a re-entrant on-thread AOTAutograd /
314
+ # inductor lowering during that window that codegen's wrappers into THIS sink would
315
+ # append ITS wrappers here too. (A nested compile_to_python installs its OWN sink via
316
+ # capture_generated_sources, so its wrappers go there, not here -- it is not this
317
+ # case.) Each captured wrapper is tagged at append time with its TracingContext
318
+ # identity (origin_id), which separates such a foreign lowering when it ran under a
319
+ # DISTINCT TracingContext. A same-context re-entrant lowering reuses the ambient
320
+ # TracingContext via try_get() and so shares this origin_id; that case is instead
321
+ # caught by the orchestration count/wiring guards below (a second orchestration trips
322
+ # the len() != 1 check). Filter to the target graph's origin before composing. The
323
+ # target is the origin of the LAST captured orchestration wrapper: a foreign lowering
324
+ # appends its orchestration before the outer one finishes, so the final orchestration
325
+ # is always the outer/target one.
326
+ orchestrations = [
327
+ g for g in captured if g.artifact_name == "runtime_wrapper_orchestration"
328
+ ]
329
+ if orchestrations:
330
+ # target_origin is None only without an ambient TracingContext, which the real
331
+ # precompile path never hits (capture always runs under one); in that defensive
332
+ # case the filter keeps every None-origin wrapper and the count/wiring guards
333
+ # below remain the backstop.
334
+ target_origin = orchestrations[-1].origin_id
335
+ captured = [g for g in captured if g.origin_id == target_origin]
336
+
337
+ # Backward wrappers are out of scope for forward lowering; reject them up front.
338
+ # Every other wrapper that can appear in a composable (cacheable) forward graph is
339
+ # codegen'd as source and captured here. The one non-codegen'd wrapper,
340
+ # FakifiedOutWrapper, only activates under fakify_first_call, which makes the graph
341
+ # non-cacheable -- so such a graph is rejected before it ever reaches composition.
342
+ unsupported = [g.artifact_name for g in captured if "backward" in g.artifact_name]
343
+ if unsupported:
344
+ raise NotImplementedError(
345
+ "aot_autograd.compile_to_python cannot yet compose these runtime "
346
+ f"wrappers into standalone source: {sorted(set(unsupported))}."
347
+ )
348
+
349
+ orchestration = [
350
+ g for g in captured if g.artifact_name == "runtime_wrapper_orchestration"
351
+ ]
352
+ if len(orchestration) != 1:
353
+ raise NotImplementedError(
354
+ "aot_autograd.compile_to_python expected exactly one forward "
355
+ f"orchestration wrapper, captured {len(orchestration)}."
356
+ )
357
+ orch = orchestration[0]
358
+ non_orch = [g for g in captured if g is not orch]
359
+
360
+ # The generated ``call`` invokes the orchestration POSITIONALLY by its own name (see
361
+ # the bottom of this function): _runtime_wrapper(chain_head, contextlib.nullcontext,
362
+ # lambda: None, flat_inputs). That mapping is hardcoded to the codegen'd signature in
363
+ # runtime_wrappers.py (``def _runtime_wrapper(_compiled_fn_, _first_ctx_,
364
+ # _on_before_call_, args)``). Verify the captured signature still matches so a future
365
+ # rename/reorder fails loudly here instead of silently passing wrong arguments.
366
+ expected_orch_params = ["_compiled_fn_", "_first_ctx_", "_on_before_call_", "args"]
367
+ orch_def = next(
368
+ (
369
+ n
370
+ for n in ast.walk(ast.parse(orch.source))
371
+ if isinstance(n, ast.FunctionDef) and n.name == orch.fn_name
372
+ ),
373
+ None,
374
+ )
375
+ args_node = orch_def.args if orch_def is not None else None
376
+ if args_node is None:
377
+ orch_params = None
378
+ else:
379
+ # Compare the FULL signature, not just positional params: the standalone call is
380
+ # purely positional, so a keyword-only / *args / **kwargs param (e.g. an added
381
+ # kw-only-with-default) would be silently dropped. Surface any such param so it
382
+ # trips this guard rather than passing.
383
+ orch_params = [a.arg for a in (*args_node.posonlyargs, *args_node.args)]
384
+ orch_params += [a.arg for a in args_node.kwonlyargs]
385
+ if args_node.vararg is not None:
386
+ orch_params.append("*" + args_node.vararg.arg)
387
+ if args_node.kwarg is not None:
388
+ orch_params.append("**" + args_node.kwarg.arg)
389
+ if orch_params != expected_orch_params:
390
+ raise NotImplementedError(
391
+ "aot_autograd.compile_to_python: the orchestration wrapper signature "
392
+ f"changed (expected {expected_orch_params}, got {orch_params}); the "
393
+ "standalone module invokes it positionally and must be updated to match."
394
+ )
395
+
396
+ helper_table = _known_helper_table()
397
+ # Every wrapper is inlined (below) as a real def at module scope under its OWN codegen'd
398
+ # name, so references resolve to that name. Note these names are NOT distinct in general
399
+ # -- the subclass, dedup, and debug-assert chain wrappers all codegen ``inner_fn``; what
400
+ # holds today is that at most one chain wrapper appears per composable forward graph (see
401
+ # the test note on multi-link chains), so the names don't actually clash. ``_reserve``
402
+ # fails loudly if that ever stops holding (the old ``_wrapper_{i}`` scheme could carry
403
+ # multiple same-named wrappers in private exec namespaces; inlining deliberately cannot).
404
+ fn_id_to_name = {id(g.fn): g.fn_name for g in non_orch}
405
+
406
+ # A chain wrapper references the inner it wraps via one of these globals
407
+ # (subclass/dedup use ``compiled_fn``; the functionalized-RNG wrapper uses
408
+ # ``_compiled_fn_``). The orchestration takes its inner as a call-time arg, not a
409
+ # global, so it is never a chain wrapper. MAINTAINERS: if AOTAutograd adds a
410
+ # forward chain wrapper that names its inner via a new global, add that name here,
411
+ # otherwise inner-call/chain-head detection silently bypasses it.
412
+ _INNER_NAMES = ("compiled_fn", "_compiled_fn_")
413
+
414
+ def _inner_ref(g: GeneratedSource) -> Any:
415
+ for nm in _INNER_NAMES:
416
+ if nm in g.globals_dict:
417
+ return g.globals_dict[nm]
418
+ return None
419
+
420
+ # The inner Inductor call is AUTHORITATIVE: it is the placeholder object the capture
421
+ # pass returned (threaded in as ``inner_call_obj``), NOT inferred from capture order.
422
+ # This is what lets the composer tell the inner call apart from the orchestration's
423
+ # own outer closure -- both surface as some wrapper's inner-ref yet neither is a
424
+ # captured wrapper fn -- which is precisely how INNER wrappers (subclass / RNG,
425
+ # wrapping the inner call, composed INSIDE the orchestration) are distinguished from
426
+ # OUTER wrappers (dedup / synthetic base, ``CompilerWrapper``s applied AROUND the
427
+ # orchestration in graph_compile._aot_stage2c_make_inference_function).
428
+ inner_call_id: int = id(inner_call_obj)
429
+
430
+ # Name of the single-arg adapter emitted over the orchestration; the innermost outer
431
+ # wrapper closes over the orchestration's outer closure and is wired to this name.
432
+ _ORCH_ENTRY = "_orchestration_entry"
433
+
434
+ # The orchestration's outer closure is the object outer wrappers wrap. The composer
435
+ # never captures it directly (the captured orchestration ``fn`` is the inner
436
+ # ``_codegen_runtime_wrapper``), so recognize it structurally: an inner-ref that is
437
+ # neither the inner call nor any captured wrapper's fn can only be that closure.
438
+ orch_closure_ids = {
439
+ id(_inner_ref(g))
440
+ for g in non_orch
441
+ if _inner_ref(g) is not None
442
+ and id(_inner_ref(g)) != inner_call_id
443
+ and id(_inner_ref(g)) not in fn_id_to_name
444
+ }
445
+ if len(orch_closure_ids) > 1:
446
+ raise NotImplementedError(
447
+ "aot_autograd.compile_to_python: captured multiple wrappers whose inner "
448
+ "reference is neither the inner call nor a captured wrapper; cannot tell "
449
+ "which wraps the orchestration."
450
+ )
451
+ orch_closure_id: int | None = next(iter(orch_closure_ids), None)
452
+
453
+ # Walk the OUTER chain outward from the orchestration closure: the innermost outer
454
+ # wrapper wraps the closure, the next wraps that wrapper's fn, and so on. Everything
455
+ # else is inner-side -- the subclass / RNG chain wrappers plus the alias / mutation
456
+ # epilogue helpers the orchestration closes over (which reference no inner at all).
457
+ outer_wrappers: list[GeneratedSource] = []
458
+ if orch_closure_id is not None:
459
+ target_id: int | None = orch_closure_id
460
+ while target_id is not None:
461
+ nxt = next(
462
+ (
463
+ g
464
+ for g in non_orch
465
+ if g not in outer_wrappers
466
+ and _inner_ref(g) is not None
467
+ and id(_inner_ref(g)) == target_id
468
+ ),
469
+ None,
470
+ )
471
+ if nxt is None:
472
+ break
473
+ outer_wrappers.append(nxt)
474
+ target_id = id(nxt.fn)
475
+ outer_ids = {id(g) for g in outer_wrappers}
476
+ inner_side = [g for g in non_orch if id(g) not in outer_ids]
477
+
478
+ # Chain head passed to the orchestration: the outermost INNER InductorWrapper (last
479
+ # inner-side wrapper that wraps via an inner reference), else the inner call. Computed
480
+ # up front (a pure capture-order check) so the order-inversion guard below fires
481
+ # before the later name-uniqueness guard -- a mis-ordered chain is the more specific
482
+ # diagnosis.
483
+ chain_head = "_inner_call"
484
+ chain_head_g: GeneratedSource | None = None
485
+ for g in inner_side:
486
+ if _inner_ref(g) is not None:
487
+ chain_head = fn_id_to_name[id(g.fn)]
488
+ chain_head_g = g
489
+
490
+ # "Last with an inner-ref == outermost" holds only when INNER capture order is
491
+ # innermost-to-outermost (it is today: subclass before functionalized-RNG). Back that
492
+ # assumption with a guard: the true outermost inner wrapper is the one NO other inner
493
+ # wrapper wraps, i.e. whose fn is not referenced as another inner wrapper's inner. If
494
+ # the chosen head is itself wrapped, capture order inverted and the chain would be
495
+ # mis-ordered -- reject rather than silently emit a wrong chain (the wiring guard
496
+ # below would not catch this, since every wrapper is still referenced somewhere).
497
+ referenced_inner_ids = {
498
+ id(_inner_ref(g)) for g in inner_side if _inner_ref(g) is not None
499
+ }
500
+ if chain_head_g is not None and id(chain_head_g.fn) in referenced_inner_ids:
501
+ raise NotImplementedError(
502
+ "aot_autograd.compile_to_python: the selected chain head is itself wrapped "
503
+ "by another captured wrapper, so capture order is not innermost-to-outermost "
504
+ "as assumed; refusing to emit a mis-ordered runtime-wrapper chain."
505
+ )
506
+
507
+ imports: set[str] = set()
508
+
509
+ # Parse the inner module once: to verify it binds a module-level ``call`` (the
510
+ # inner-call contract, checked below) and to collect its top-level names so no inlined
511
+ # wrapper's def name or hoisted global can silently shadow one.
512
+ inner_tree = ast.parse(inner_python)
513
+ inner_module_names = _module_level_names(inner_tree)
514
+
515
+ # Every runtime wrapper is inlined: its def is spliced at module scope and its
516
+ # closed-over globals hoisted to top-level assignments (no exec / private namespace).
517
+ # So every emitted top-level name -- each wrapper's def name and each hoisted global --
518
+ # must be unique and must not shadow a name the inner Inductor module binds. This holds
519
+ # in practice because at most one chain wrapper appears per composable forward graph, so
520
+ # its def name (``inner_fn`` is shared across subclass/dedup/debug-assert wrappers) and
521
+ # the inner-ref global ``compiled_fn`` each occur once, and metadata globals are
522
+ # per-wrapper suffixed. ``_reserve`` guards it: a collision fails loudly (rename/namespace
523
+ # needed) rather than silently rebinding a name.
524
+ emitted_names = set(inner_module_names) | {
525
+ "call",
526
+ "_inner_call",
527
+ "_rebuild",
528
+ "contextlib",
529
+ _ORCH_ENTRY,
530
+ }
531
+
532
+ def _reserve(name: str) -> None:
533
+ if name in emitted_names:
534
+ raise NotImplementedError(
535
+ "aot_autograd.compile_to_python: generated top-level name "
536
+ f"{name!r} collides with another top-level name in the composed module; "
537
+ "inlining the runtime wrappers would shadow a binding."
538
+ )
539
+ emitted_names.add(name)
540
+
541
+ # Reserve every wrapper def name up front (before hoists) so a hoisted global cannot
542
+ # shadow a def and two wrappers cannot share a name.
543
+ for _g in (*non_orch, orch):
544
+ _reserve(_g.fn_name)
545
+
546
+ def _resolve_globals(globals_dict: dict[str, object]) -> list[tuple[str, str]]:
547
+ # Resolve each global a wrapper closes over to a standalone source expression.
548
+ # ``globals_dict`` is the pre-exec snapshot from codegen.py, so the
549
+ # interpreter ``__builtins__`` is absent; the skip is kept defensively in case a
550
+ # future caller hands us a post-exec live dict.
551
+ out: list[tuple[str, str]] = []
552
+ for gname, gobj in globals_dict.items():
553
+ if gname == "__builtins__":
554
+ continue
555
+ expr = _resolve_global(
556
+ gobj,
557
+ helper_table,
558
+ inner_call_id,
559
+ fn_id_to_name,
560
+ imports,
561
+ orch_closure_id,
562
+ _ORCH_ENTRY,
563
+ )
564
+ out.append((gname, expr))
565
+ return out
566
+
567
+ def _emit_inline(source: str, globals_dict: dict[str, object]) -> str:
568
+ # Splice the wrapper's def verbatim at module scope, hoisting each closed-over global
569
+ # to a top-level assignment (skipping a name already module-available -- an imported
570
+ # helper or ``torch`` -- detected as gname == its resolved expr). No exec / private
571
+ # namespace: the def reads as ordinary code and is referenced by its own name. Each
572
+ # hoisted name is ``_reserve``'d so a collision fails loudly rather than rebinding.
573
+ hoists: list[str] = []
574
+ for gname, expr in _resolve_globals(globals_dict):
575
+ if gname == expr:
576
+ continue # already at module scope (an import / ``torch``)
577
+ _reserve(gname)
578
+ hoists.append(f"{gname} = {expr}")
579
+ return "\n".join(hoists + [source, ""])
580
+
581
+ # Inner-side wrappers first (subclass / RNG chain wrappers innermost-to-outermost,
582
+ # plus the epilogue helpers), then the orchestration, then the outer wrappers -- all
583
+ # spliced as real defs. An inner wrapper's hoisted inner-ref (``compiled_fn``)
584
+ # references ``_inner_call`` / a sibling emitted earlier; an outer wrapper's inner-ref
585
+ # references the orchestration entry adapter / a sibling emitted earlier -- so order
586
+ # is satisfied.
587
+ inner_blocks = [_emit_inline(g.source, g.globals_dict) for g in inner_side]
588
+ orch_block = _emit_inline(orch.source, orch.globals_dict)
589
+ outer_blocks = [_emit_inline(g.source, g.globals_dict) for g in outer_wrappers]
590
+
591
+ # Imports (helper table + whatever emit_value added) are emitted BEFORE the inner
592
+ # module and the wrapper blocks, so a later top-level binding of the same name -- an
593
+ # inner-module binding or a hoisted wrapper global -- would shadow the import. And
594
+ # _emit_inline skips hoisting a global whose resolved expr already equals its own name
595
+ # (an imported helper referenced as ``gname == expr``), so such a wrapper would then
596
+ # silently bind to the shadowing object instead of the helper. ``from X import Y``
597
+ # names bind a specific (non-module) object and are the ones at risk; plain ``import
598
+ # mod`` names resolve to the same singleton module no matter who imports them, so a
599
+ # duplicate binding is benign and is left unchecked (else ``import torch`` -- which the
600
+ # inner module also emits -- would trip a spurious collision). ``_reserve`` fails loudly
601
+ # if an inner-module name or a hoisted global collides with one of these import names.
602
+ for stmt in sorted(imports):
603
+ node = ast.parse(stmt).body[0]
604
+ if isinstance(node, ast.ImportFrom):
605
+ for alias in node.names:
606
+ _reserve(alias.asname or alias.name)
607
+
608
+ # The final ``call`` invokes the outermost outer wrapper (else the orchestration
609
+ # directly). Build that line now so the wiring guard's corpus includes it -- the
610
+ # outermost outer wrapper is referenced ONLY there.
611
+ if outer_wrappers:
612
+ outermost_name = fn_id_to_name[id(outer_wrappers[-1].fn)]
613
+ final_invoke = f" return {outermost_name}(list(flat_inputs))"
614
+ else:
615
+ final_invoke = (
616
+ f" return {orch.fn_name}(\n"
617
+ f" {chain_head}, contextlib.nullcontext, lambda: None, "
618
+ "list(flat_inputs)\n )"
619
+ )
620
+
621
+ # The single-arg adapter over the orchestration (emitted only when outer wrappers
622
+ # wrap it). The outer wrappers call their inner as ``fn(args)``; this adapts the
623
+ # orchestration's positional (_compiled_fn_, _first_ctx_, _on_before_call_, args)
624
+ # signature to that. When there are no outer wrappers the orchestration is invoked
625
+ # directly in ``call`` (see final_invoke).
626
+ orch_invoke_comment = [
627
+ " # The 2nd/3rd positional args INTENTIONALLY substitute contextlib.nullcontext",
628
+ " # for the runtime's first-invocation context (_FirstInvocationContext) and a",
629
+ " # no-op for the profiler-prologue exit. This drops two cold-start diagnostics:",
630
+ " # the first-call custom-op aliasing analysis (_AnalyzeCustomOpInputOutputMode,",
631
+ " # active when check_custom_op_aliasing is set, which can even RAISE under",
632
+ " # error_on_custom_op_aliasing) and the profiler prologue. Neither affects",
633
+ " # numerics, so this is not a bug -- the standalone artifact deliberately omits",
634
+ " # them. (See the positional-mapping note in _compose_standalone_module.)",
635
+ ]
636
+ entry_block: list[str] = []
637
+ if outer_wrappers:
638
+ entry_block = [
639
+ f"def {_ORCH_ENTRY}(args):",
640
+ " # Single-arg adapter so the CompilerWrappers applied AROUND the",
641
+ " # orchestration (dedup / synthetic base) can invoke it as ``fn(args)``.",
642
+ *orch_invoke_comment,
643
+ f" return {orch.fn_name}(",
644
+ f" {chain_head}, contextlib.nullcontext, lambda: None, args",
645
+ " )",
646
+ "",
647
+ ]
648
+
649
+ # _INNER_NAMES detection is a hardcoded allowlist (see above). If AOTAutograd adds
650
+ # a forward wrapper that names its inner via an unrecognized global, that wrapper
651
+ # is captured but may never be wired into the module -- silently composing a
652
+ # structurally-wrong result. Enforce that every captured non-orch wrapper is
653
+ # actually referenced somewhere: as the inner chain head, in the final ``call``
654
+ # (the outermost outer wrapper), or by name in another block (another wrapper's
655
+ # globals, the orchestration's epilogue helpers -- e.g. ``_alias_fn`` /
656
+ # ``_apply_mutations`` -- or the entry adapter). A wrapper whose name appears in no
657
+ # other block went unwired, so reject rather than emit a wrong module.
658
+ block_of = {id(g): b for g, b in zip(inner_side, inner_blocks)}
659
+ block_of.update({id(g): b for g, b in zip(outer_wrappers, outer_blocks)})
660
+ other_text = "\n".join(
661
+ inner_blocks + [orch_block] + entry_block + outer_blocks + [final_invoke]
662
+ )
663
+ for g in non_orch:
664
+ name = fn_id_to_name[id(g.fn)]
665
+ own = block_of[id(g)]
666
+ elsewhere = other_text.replace(own, "", 1)
667
+ # Whole-token match: ``name`` is a wrapper def name (e.g. ``inner_fn``); a raw
668
+ # substring test would treat ``inner_fn`` as wired whenever a longer token like
669
+ # ``inner_fn2`` is referenced, silently defeating this guard.
670
+ wired = re.search(r"\b" + re.escape(name) + r"\b", elsewhere) is not None
671
+ if name != chain_head and not wired:
672
+ raise NotImplementedError(
673
+ "aot_autograd.compile_to_python could not wire captured runtime "
674
+ f"wrapper {g.fn_name!r} into the module (an inner-call global may be "
675
+ "unrecognized; see _INNER_NAMES)."
676
+ )
677
+
678
+ # The module splices ``_inner_call = call`` below, relying on inner_python binding a
679
+ # module-level ``call`` entry point. Inductor emits this in one of two forms: the
680
+ # flat path defines ``def call(args):`` (FunctionDef) while the graph_partition Runner
681
+ # path binds ``call = runner.call`` (Assign with a Name target). Verify one is present
682
+ # so a future inductor codegen drift fails loudly here -- like the orchestration /
683
+ # chain / wiring guards above -- instead of surfacing as a bare NameError at exec of
684
+ # the generated module. (``inner_tree`` was parsed once up front.)
685
+ binds_call = any(
686
+ (isinstance(n, ast.FunctionDef) and n.name == "call")
687
+ or (
688
+ isinstance(n, ast.Assign)
689
+ and any(isinstance(t, ast.Name) and t.id == "call" for t in n.targets)
690
+ )
691
+ for n in inner_tree.body
692
+ )
693
+ if not binds_call:
694
+ raise NotImplementedError(
695
+ "compile_to_python: inner Inductor module does not bind a module-level "
696
+ "'call' entry point (the inner-call contract); the standalone module "
697
+ "splices ``_inner_call = call`` and must be updated to match."
698
+ )
699
+
700
+ # Only emit the _rebuild helper if a baked value actually reconstructs through it.
701
+ needs_rebuild = any(
702
+ "_rebuild(" in b for b in (*inner_blocks, orch_block, *outer_blocks)
703
+ )
704
+
705
+ # ``call`` invokes the orchestration directly when nothing wraps it; when outer
706
+ # wrappers do, its body just calls the outermost of them (which drives the entry
707
+ # adapter, then the orchestration) -- so the orchestration-substitution comment lives
708
+ # on whichever site actually invokes the orchestration.
709
+ if outer_wrappers:
710
+ call_body = [
711
+ " # Invokes the outer CompilerWrapper chain (dedup / synthetic base), which",
712
+ f" # wraps {_ORCH_ENTRY} (the orchestration adapter).",
713
+ final_invoke,
714
+ ]
715
+ else:
716
+ call_body = [
717
+ " # AOTAutograd orchestration: disables grad, invokes the inner chain,",
718
+ " # bumps mutated-input versions, applies the output epilogue.",
719
+ " #",
720
+ *orch_invoke_comment,
721
+ final_invoke,
722
+ ]
723
+
724
+ parts = [
725
+ _MODULE_HEADER,
726
+ "import contextlib",
727
+ *sorted(imports),
728
+ "",
729
+ "",
730
+ *(_REBUILD_HELPER if needs_rebuild else []),
731
+ "# " + "=" * 70,
732
+ "# Inner Inductor output code (kernels + ``call``)",
733
+ "# " + "=" * 70,
734
+ inner_python,
735
+ "_inner_call = call",
736
+ "",
737
+ "# " + "=" * 70,
738
+ "# AOTAutograd runtime wrappers (codegen'd): each inlined as a real def with its",
739
+ "# closed-over globals hoisted to module scope -- inner chain wrappers first, then",
740
+ "# the orchestration, then any outer wrappers (dedup / synthetic base) that wrap it",
741
+ "# " + "=" * 70,
742
+ *inner_blocks,
743
+ orch_block,
744
+ *entry_block,
745
+ *outer_blocks,
746
+ "",
747
+ "def call(flat_inputs): # noqa: F811",
748
+ *call_body,
749
+ "",
750
+ ]
751
+ return "\n".join(parts)
752
+
753
+
754
+ def _find_effectful_op(gm: GraphModule, get_effect: Any) -> Any:
755
+ """Return the first effectful op target reachable from ``gm``, or None.
756
+
757
+ The target may be an ``OpOverload`` (e.g. ``aten::_print``) or a
758
+ ``HigherOrderOperator`` -- ``call_torchbind`` / ``hop_print`` /
759
+ ``invoke_leaf_function`` are registered ``_EffectType.ORDERED`` HOPs, not
760
+ OpOverloads -- so both are checked (``get_effect`` returns None for a
761
+ non-effectful HOP like ``cond``).
762
+
763
+ Walks the graph and descends into any child GraphModule a node references -- a
764
+ HOP (cond/while_loop/scan) holds its body as a get_attr'd submodule or passes it
765
+ directly as a node arg -- so an effect nested inside a HOP subgraph is caught, not
766
+ just effects at the top level."""
767
+ import torch
768
+ from torch.fx import GraphModule as _GraphModule
769
+
770
+ seen: set[int] = set()
771
+
772
+ def _scan(g: _GraphModule) -> Any:
773
+ if id(g) in seen:
774
+ return None
775
+ seen.add(id(g))
776
+ for node in g.graph.nodes:
777
+ if (
778
+ node.op == "call_function"
779
+ and isinstance(
780
+ node.target,
781
+ (torch._ops.OpOverload, torch._ops.HigherOrderOperator),
782
+ )
783
+ and get_effect(node.target) is not None
784
+ ):
785
+ return node.target
786
+ for sub in _iter_subgraphs(g, node):
787
+ found = _scan(sub)
788
+ if found is not None:
789
+ return found
790
+ return None
791
+
792
+ def _walk_values(value: Any) -> Iterator[_GraphModule]:
793
+ # A GraphModule can appear as a direct node arg OR nested one level (or more)
794
+ # inside a list/tuple/dict arg -- some HOPs pass their branch/body callables
795
+ # inside a container -- so descend into containers before the isinstance check,
796
+ # otherwise the recursive effect scan would never enter that nested subgraph.
797
+ if isinstance(value, _GraphModule):
798
+ yield value
799
+ elif isinstance(value, (list, tuple)):
800
+ for item in value:
801
+ yield from _walk_values(item)
802
+ elif isinstance(value, dict):
803
+ for item in value.values():
804
+ yield from _walk_values(item)
805
+
806
+ def _iter_subgraphs(g: _GraphModule, node: Any) -> Iterator[_GraphModule]:
807
+ # A child graph reaches a node either as an attribute fetched by get_attr or
808
+ # as a (possibly container-nested) argument (the form HOPs use for their
809
+ # branch/body callables). make_fx emits FLAT get_attr targets (e.g.
810
+ # true_graph_0) since _scan recurses per-GraphModule, so a plain getattr
811
+ # suffices (no dotted walk needed here).
812
+ if node.op == "get_attr":
813
+ attr = getattr(g, node.target, None)
814
+ if isinstance(attr, _GraphModule):
815
+ yield attr
816
+ for arg in (*node.args, *node.kwargs.values()):
817
+ yield from _walk_values(arg)
818
+
819
+ return _scan(gm)
820
+
821
+
822
+ def _graph_has_dynamic_shapes(gm: GraphModule) -> bool:
823
+ """True if any placeholder is itself a SymInt or carries symbolic (SymInt) size,
824
+ stride, or storage-offset metadata -- i.e. the graph was traced with dynamic dims.
825
+ Drives the shapes mode for the capture pass: dynamic graphs stay dynamic, static
826
+ graphs specialize so the composer can bake their (static) view metadata. Strides and
827
+ storage offset are checked too, not just sizes: a graph dynamic solely via symbolic
828
+ strides has static sizes, and treating it as static would silently specialize the
829
+ artifact to the example strides. (Unbacked symints appearing only in intermediates,
830
+ not on any placeholder, are still missed here, but such a graph fails loudly
831
+ downstream when emit_value rejects the still-symbolic metadata.)"""
832
+ import torch
833
+
834
+ def _is_symbolic(v: Any) -> bool:
835
+ return isinstance(v, torch.SymInt)
836
+
837
+ for node in gm.graph.nodes:
838
+ if node.op != "placeholder":
839
+ continue
840
+ val = node.meta.get("val")
841
+ if _is_symbolic(val):
842
+ return True
843
+ if isinstance(val, torch.Tensor) and (
844
+ any(_is_symbolic(s) for s in val.shape)
845
+ or any(_is_symbolic(s) for s in val.stride())
846
+ or _is_symbolic(val.storage_offset())
847
+ ):
848
+ return True
849
+ return False
850
+
851
+
852
+ def compile_to_python(
853
+ gm: GraphModule,
854
+ example_inputs: Sequence[Any],
855
+ *,
856
+ options: dict[str, Any] | None = None,
857
+ ) -> tuple[str, bytes | None]:
858
+ """Compile ``gm`` to ``(python_code, cache)``; see the module docstring.
859
+
860
+ THREADING: serialized by a process-global lock (``_COMPILE_LOCK``). The wrapper-source
861
+ capture is thread-local, but the AOTAutograd pass and the inner inductor compile both
862
+ swap process-global cache state (``CacheArtifactManager.with_fresh_cache()``); a
863
+ concurrent compile on another thread would corrupt the captured wrappers or cache
864
+ artifacts, so concurrent calls (including via ``torch.compiler.precompile``) are
865
+ serialized rather than run in parallel.
866
+ """
867
+ import copy
868
+
869
+ import torch
870
+ from torch._higher_order_ops.effects import _get_effect
871
+ from torch._inductor import compile_to_python as _inductor_compile_to_python
872
+ from torch._inductor.compile_fx import compile_fx
873
+ from torch._inductor.standalone_compile import (
874
+ _resolve_ignore_shape_env,
875
+ _standalone_context,
876
+ )
877
+ from torch.fx.graph_module import _share_torchbind_and_process_group_on_deepcopy
878
+
879
+ from .utils import make_boxed_func
880
+
881
+ # Validate up front: this layer dereferences ``gm.graph`` (the effectful-op scan
882
+ # below) before reaching inductor's own type-check, so a non-GraphModule would
883
+ # otherwise surface as an opaque AttributeError instead of this clear contract error.
884
+ if not isinstance(gm, torch.fx.GraphModule):
885
+ raise TypeError(
886
+ "aot_autograd.compile_to_python expects a post-AOTAutograd "
887
+ f"torch.fx.GraphModule, got {type(gm)}."
888
+ )
889
+
890
+ # Effectful ops thread effect tokens through a calling convention the standalone
891
+ # composition does not reproduce (and their with_effects HOP is non-cacheable);
892
+ # reject them up front with a concrete reason. Not supported yet. (Detected here
893
+ # too, not only in torch.compiler.precompile's capture-time guard, so direct callers of
894
+ # this lowering get the same clear failure rather than a silently-wrong artifact.)
895
+ # Scan recursively: a HOP (cond/while_loop/scan) carries its body as a child
896
+ # GraphModule referenced by a get_attr node (or passed directly as a node arg), so
897
+ # effects nested in such a subgraph would be missed by a top-level-only scan.
898
+ effectful = _find_effectful_op(gm, _get_effect)
899
+ if effectful is not None:
900
+ raise NotImplementedError(
901
+ "aot_autograd.compile_to_python cannot lower this graph to standalone "
902
+ f"source: it contains an effectful op ({effectful}), which is not "
903
+ "supported yet."
904
+ )
905
+
906
+ with _COMPILE_LOCK:
907
+ # Run AOTAutograd ONCE to do two things: (1) produce the dense, decomposed,
908
+ # functionalized inner graph, and (2) codegen its runtime-wrapper chain, which the
909
+ # thread-local ``capture_generated_sources`` sink records. A capture-only inner
910
+ # compiler grabs the dense graph and returns a placeholder boxed callable, so
911
+ # AOTAutograd still builds and codegen's the wrappers AROUND it -- that codegen is
912
+ # what we capture. Inductor is NOT run in this pass; it runs exactly once below, on
913
+ # the captured dense graph, via the ``_inductor_compile_to_python`` call (which
914
+ # drives inductor's ``compile_fx_inner`` directly, not a re-entry into AOTAutograd).
915
+ # The composer swaps the placeholder (the wrappers' inner reference) for the
916
+ # inner inductor ``call`` by object identity, so the placeholder is only a
917
+ # compile-time token and never runs.
918
+ captured: list[GeneratedSource] = []
919
+ dense: dict[str, Any] = {}
920
+
921
+ def _capture_inner_compile(dense_gm, dense_inputs, **kwargs):
922
+ if "gm" in dense:
923
+ raise NotImplementedError(
924
+ "aot_autograd.compile_to_python does not support a graph whose "
925
+ "AOTAutograd lowering emits more than one inner forward graph."
926
+ )
927
+ dense["gm"] = dense_gm
928
+ # Retain the placeholder's IDENTITY: it is the authoritative inner call the
929
+ # runtime-wrapper chain closes over. The composer needs it to tell the inner
930
+ # call apart from the orchestration's own outer closure (both surface as a
931
+ # wrapper's inner-ref yet neither is a captured wrapper fn), which is what
932
+ # separates INNER wrappers from the OUTER dedup / synthetic-base wrappers.
933
+ placeholder = make_boxed_func(dense_gm.forward)
934
+ dense["placeholder"] = placeholder
935
+ return placeholder
936
+
937
+ # Drive inductor's own ``compile_fx`` (i.e. its exact AOTAutograd invocation --
938
+ # decomposition table + aot config) but swap in the capture inner compiler so the
939
+ # dense graph is intercepted before codegen and no inductor compile happens. Using
940
+ # compile_fx (rather than calling aot_autograd directly) guarantees the dense graph
941
+ # matches what the step-2 inductor compile below expects. Pick the shapes mode from
942
+ # the graph (there is no dynamic_shapes knob): a symbolically-traced graph uses
943
+ # ``"from_graph"`` to stay dynamic, a static one ``"from_example_inputs"`` to
944
+ # specialize -- matching what the composer can bake (symbolic view metadata is
945
+ # rejected downstream). no_grad pins the inference path (one forward module).
946
+ # Deepcopy first so compile_fx cannot mutate the caller's gm (torchbind
947
+ # ProcessGroups smuggled through as shared references). Note: the raw-collective /
948
+ # torchbind rewrites are inductor-lowering prereqs and belong to the step-2 inductor
949
+ # compile, which applies them to the dense graph -- not duplicated here.
950
+ shapes_mode = (
951
+ "from_graph" if _graph_has_dynamic_shapes(gm) else "from_example_inputs"
952
+ )
953
+ with (
954
+ torch.no_grad(),
955
+ _standalone_context(gm, shapes_mode, aot=False),
956
+ capture_generated_sources(captured),
957
+ ):
958
+ with _share_torchbind_and_process_group_on_deepcopy():
959
+ gm_owned = copy.deepcopy(gm)
960
+ compile_fx(
961
+ gm_owned,
962
+ example_inputs,
963
+ # Placeholder returns a boxed callable, not a full OutputCode; AOTAutograd
964
+ # only wraps it (never inductor-post-compiles it), so this is fine at runtime.
965
+ inner_compile=_capture_inner_compile, # pyrefly: ignore[bad-argument-type]
966
+ ignore_shape_env=_resolve_ignore_shape_env(shapes_mode),
967
+ )
968
+ if "gm" not in dense:
969
+ raise RuntimeError(
970
+ "aot_autograd.compile_to_python: AOTAutograd never reached the inner "
971
+ "forward compiler, so no dense graph was captured."
972
+ )
973
+
974
+ inner_python, cache = _inductor_compile_to_python(
975
+ dense["gm"], example_inputs, options=options
976
+ )
977
+ source = _compose_standalone_module(
978
+ inner_python, captured, dense["placeholder"]
979
+ )
980
+ return source, cache
981
+
982
+
983
+ def load_from_python(
984
+ python_code: str, cache: bytes | None = None
985
+ ) -> Callable[..., Any]:
986
+ """Load the module emitted by ``compile_to_python`` into a runnable ``call`` -- the
987
+ inverse of ``compile_to_python``: (python_code, cache) in, runnable ``call`` out.
988
+
989
+ The composed module is self-contained -- the inductor kernels and the pure-Python
990
+ runtime wrappers are inlined -- so this delegates straight to the inductor loader:
991
+ ``python_code`` runs standalone (kernels JIT-compile on first use), and ``cache`` (the
992
+ inductor accelerator bundle this layer forwards) warms the kernel caches so exec loads
993
+ the precompiled binaries instead of recompiling. There is no separate aot-level load
994
+ step: exec'ing the module yields the aot-composed top-level ``call`` directly, and the
995
+ wrappers carry no kernels to load.
996
+ """
997
+ from torch._inductor import load_from_python as _inductor_load_from_python
998
+
999
+ return _inductor_load_from_python(python_code, cache)
.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py ADDED
@@ -0,0 +1,907 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains various utils for AOTAutograd, including those for handling collections.
3
+ """
4
+
5
+ import copy
6
+ import dataclasses
7
+ import logging
8
+ import operator
9
+ import sys
10
+ import warnings
11
+ from collections.abc import Callable, Sequence
12
+ from contextlib import nullcontext
13
+ from functools import partial, wraps
14
+ from typing import Any, overload, TYPE_CHECKING
15
+ from typing_extensions import ParamSpec, TypeVar, TypeVarTuple, Unpack
16
+
17
+ import torch
18
+ import torch.utils._pytree as pytree
19
+ from torch._library.fake_class_registry import FakeScriptObject
20
+ from torch._library.opaque_object import is_custom_class_obj
21
+ from torch._logging import getArtifactLogger
22
+ from torch._subclasses.fake_tensor import is_fake_tensor
23
+ from torch._subclasses.functional_tensor import FunctionalTensor
24
+ from torch.fx.experimental._backward_state import BackwardState
25
+ from torch.fx.experimental.proxy_tensor import py_sym_types
26
+
27
+
28
+ _T = TypeVar("_T")
29
+ if TYPE_CHECKING:
30
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
31
+
32
+ from .schemas import AOTConfig, ViewAndMutationMeta
33
+
34
+
35
+ KNOWN_TYPES = [
36
+ torch.Tensor,
37
+ BackwardState,
38
+ int,
39
+ str,
40
+ float,
41
+ bool,
42
+ type(None),
43
+ *py_sym_types,
44
+ FakeScriptObject,
45
+ torch.ScriptObject,
46
+ ]
47
+
48
+ aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects")
49
+ annotation_log = getArtifactLogger(__name__, "annotation")
50
+
51
+ strict_zip = partial(zip, strict=True)
52
+
53
+
54
+ def get_loaded_async_collective_tensor_type() -> type["AsyncCollectiveTensor"] | None:
55
+ """Return the ACT type if distributed collectives are already loaded."""
56
+ if "torch.distributed._functional_collectives" not in sys.modules:
57
+ return None
58
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
59
+
60
+ return AsyncCollectiveTensor
61
+
62
+
63
+ def import_async_collective_tensor_type() -> type["AsyncCollectiveTensor"]:
64
+ """Import and return the ACT type."""
65
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
66
+
67
+ return AsyncCollectiveTensor
68
+
69
+
70
+ def is_async_collective_tensor_type(pytype: type) -> bool:
71
+ """Whether pytype is the AsyncCollectiveTensor type (False if not loaded)."""
72
+ act = get_loaded_async_collective_tensor_type()
73
+ return act is not None and pytype is act
74
+
75
+
76
+ def partial_flatten_asdict(obj: object) -> Any:
77
+ if dataclasses.is_dataclass(obj):
78
+ return {
79
+ field.name: getattr(obj, field.name) for field in dataclasses.fields(obj)
80
+ }
81
+ elif isinstance(obj, (list, tuple)):
82
+ return obj.__class__([partial_flatten_asdict(item) for item in obj])
83
+ elif isinstance(obj, dict):
84
+ return {k: partial_flatten_asdict(v) for k, v in obj.items()}
85
+ else:
86
+ return obj
87
+
88
+
89
+ @overload
90
+ def normalize_as_list(x: _T) -> list[_T]: ...
91
+ @overload
92
+ def normalize_as_list(x: tuple[_T, ...]) -> list[_T]: ...
93
+ @overload
94
+ def normalize_as_list(x: list[_T]) -> list[_T]: ...
95
+
96
+
97
+ def normalize_as_list(x: object) -> list[object]:
98
+ if isinstance(x, tuple):
99
+ return list(x)
100
+ elif isinstance(x, list):
101
+ return x
102
+ return [x]
103
+
104
+
105
+ def _get_autocast_states() -> list[Any]:
106
+ return [
107
+ torch.is_autocast_enabled("cuda"),
108
+ torch.is_autocast_enabled("cpu"),
109
+ torch.get_autocast_dtype("cuda"),
110
+ torch.get_autocast_dtype("cpu"),
111
+ torch.is_autocast_cache_enabled(),
112
+ ]
113
+
114
+
115
+ def make_boxed_func(f: Callable[..., Any]) -> Callable[[list[Any]], Any]:
116
+ @simple_wraps(f)
117
+ def g(args: list[Any]) -> Any:
118
+ return f(*args)
119
+
120
+ # pyrefly: ignore[missing-attribute]
121
+ g._boxed_call = True
122
+ return g
123
+
124
+
125
+ def make_boxed_compiler(
126
+ compiler: Callable[..., Any],
127
+ ) -> Callable[..., Any]:
128
+ @wraps(compiler)
129
+ def f(fx_g: Any, inps: Any) -> Any:
130
+ out_f = compiler(fx_g, inps)
131
+ fx_g = make_boxed_func(out_f)
132
+ return fx_g
133
+
134
+ return f
135
+
136
+
137
+ def call_func_at_runtime_with_args(
138
+ f: Callable[..., Any],
139
+ args: Sequence[Any],
140
+ steal_args: bool = False,
141
+ disable_amp: bool = False,
142
+ ) -> list[Any]:
143
+ if not steal_args:
144
+ args = list(args)
145
+ if not isinstance(args, list):
146
+ raise AssertionError(f"args must be a list, got {type(args)}")
147
+
148
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
149
+ with context():
150
+ if getattr(f, "_boxed_call", False):
151
+ out = normalize_as_list(f(args))
152
+ else:
153
+ # TODO: Please remove soon
154
+ # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670
155
+ warnings.warn(
156
+ "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. "
157
+ "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. "
158
+ "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale.",
159
+ stacklevel=2,
160
+ )
161
+ out = normalize_as_list(f(*args))
162
+ return out
163
+
164
+
165
+ # Inspired by autodidax (thanks!)
166
+ class PytreeThunk:
167
+ spec: pytree.TreeSpec | None = None
168
+ # These are some kinda dumb microoptimizations that save about 3-4 us of overhead.
169
+ is_simple: bool | None = (
170
+ None # if the output spec is a tuple/list, we won't bother unflattening it.
171
+ )
172
+ is_really_simple: bool | None = None # if the output spec is a LeafSpec
173
+
174
+ def set(self, spec: pytree.TreeSpec) -> None:
175
+ if not (self.spec is None or self.spec == spec):
176
+ raise AssertionError(f"spec mismatch: existing={self.spec}, new={spec}")
177
+ if spec is None:
178
+ raise AssertionError("spec must not be None")
179
+ self.spec: pytree.TreeSpec = spec
180
+ if self.spec.type in {tuple, list} and all(
181
+ child.is_leaf() for child in spec.children()
182
+ ):
183
+ self.is_simple = True
184
+ if self.spec.is_leaf():
185
+ self.is_really_simple = True
186
+
187
+ def unflatten(self, x: Sequence[Any]) -> Any:
188
+ if self.is_really_simple:
189
+ return x[0]
190
+ if self.is_simple:
191
+ return x
192
+ if self.spec is None:
193
+ raise AssertionError("spec must be set before calling unflatten")
194
+ return pytree.tree_unflatten(x, self.spec)
195
+
196
+
197
+ # Creates a function that returns flattened inputs and outputs
198
+ # Also returns the output tree spec, which is needed to recover the "unflattened"
199
+ # output tree structure later.
200
+ def create_tree_flattened_fn(
201
+ fn: Callable[..., Any],
202
+ args: Sequence[Any],
203
+ kwargs: dict[str, Any] | None = None,
204
+ ) -> tuple[Callable[..., list[Any]], PytreeThunk]:
205
+ if kwargs is None:
206
+ kwargs = {}
207
+ # Save the args_spec for flat_tensor_args to unflatten while tracing
208
+ _, tensor_args_spec = pytree.tree_flatten((args, kwargs))
209
+ out_spec = PytreeThunk()
210
+
211
+ def flat_fn(*flat_args: Any) -> list[Any]:
212
+ # The input are flattened tensor args. Prepare the args in the
213
+ # order that original function expects. Add static args as well.
214
+ # They will appear as tensor constants in the traced graph.
215
+ nonlocal out_spec
216
+ args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec)
217
+ tree_out = fn(*args, **kwargs)
218
+ flat_out, spec = pytree.tree_flatten(tree_out)
219
+ for i in flat_out:
220
+ is_known_type = isinstance(i, tuple(KNOWN_TYPES)) or is_custom_class_obj(i)
221
+ if not is_known_type:
222
+ raise RuntimeError(
223
+ f"Found {type(i)} in output, which is not a known type. "
224
+ "If this type holds tensors, you need to register a pytree for it. "
225
+ "See https://github.com/pytorch/functorch/issues/475 for a brief "
226
+ "explanation why. If you don't need to register a pytree, please "
227
+ "leave a comment explaining your use case and we'll make this more "
228
+ "ergonomic to deal with"
229
+ )
230
+ out_spec.set(spec)
231
+ return flat_out
232
+
233
+ # Can't use functools.wraps here because the wrapper has different
234
+ # calling convention
235
+ if hasattr(fn, "_orig_mod"):
236
+ # pyrefly: ignore[missing-attribute]
237
+ flat_fn._orig_mod = fn._orig_mod
238
+
239
+ return flat_fn, out_spec
240
+
241
+
242
+ # This function takes in a tensor t, and returns one of t, t.view(), or t.clone().
243
+ # When tracing the joint forward + backward, for any inputs in the graph that are mutated,
244
+ # we need to clone them first (and similarly for metadata-only mutations, we need to view them first).
245
+ # The idea is that when we trace the backward, we need to pass in the *original* primals
246
+ # to autograd.grad(), before they were mutated.
247
+ # Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them.
248
+ # This means that "idx" here represents the index of the (potentially) synthetic base.
249
+ # What we need to do is:
250
+ # (1) map the current (post-synthetic-base calling convention) input argument index
251
+ # to int index pre-synthetic-base-calling-convention.
252
+ # (2) There could be multiple, if this index corresponds to a synthetic base
253
+ # that has multiple input aliases.
254
+ # (3) If any of those corresponding inputs get metadata mutations, then we clone the base.
255
+ def maybe_to_fresh_input(idx: int, t: Any, meta: "ViewAndMutationMeta") -> Any:
256
+ if not isinstance(t, torch.Tensor):
257
+ return t
258
+ if idx in meta.mutated_inp_runtime_indices:
259
+ # We only need to bother cloning mutated inputs that participate in autograd.
260
+ if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data:
261
+ # Make sure the primal we pass to autograd.grad()
262
+ # sees the tensor before the mutation
263
+ return t.clone()
264
+ if meta.input_info[idx] and meta.input_info[idx].mutates_metadata:
265
+ # Make sure the primal we pass to autograd.grad()
266
+ # sees the tensor before the metadata mutation
267
+ return t.view(t.shape)
268
+ return t
269
+
270
+
271
+ def is_with_effects(node: torch.fx.Node) -> bool:
272
+ if (
273
+ node.op == "call_function"
274
+ and node.target is torch.ops.higher_order.with_effects
275
+ ):
276
+ return True
277
+ elif (
278
+ node.op == "call_function"
279
+ and node.target is torch.ops.higher_order.invoke_subgraph
280
+ ):
281
+ # Check if subgraph has effects by looking in the cache
282
+ from torch._guards import InvokeSubgraphCache, TracingContext
283
+
284
+ tracing_ctx = TracingContext.try_get()
285
+ if tracing_ctx:
286
+ invoke_subgraph_cache = tracing_ctx.hop_dispatch_set_cache.get_cache(
287
+ torch.ops.higher_order.invoke_subgraph
288
+ )
289
+ if invoke_subgraph_cache:
290
+ if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache):
291
+ raise AssertionError(
292
+ f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}"
293
+ )
294
+ # pyrefly: ignore[bad-argument-type]
295
+ effects = invoke_subgraph_cache.get_effects(node.args[1])
296
+ return effects is not None
297
+ return False
298
+
299
+
300
+ def unlift_tokens(
301
+ fw_module: torch.fx.GraphModule,
302
+ fw_metadata: "ViewAndMutationMeta",
303
+ aot_config: "AOTConfig",
304
+ bw_module: torch.fx.GraphModule | None = None,
305
+ ) -> None:
306
+ # Remove the tokens from the inputs/outputs of the graph since inductor does
307
+ # not want these extra inputs/outputs, and replace them with
308
+ # _make_token() to create a token, and _sink_tokens() to collect the
309
+ # tokens. See Note [Side-Effectful Tokens in AOTAutograd]
310
+ # Logic:
311
+ # 1. In the case of with_effects:
312
+ # Before:
313
+ # ```
314
+ # def forward(self, token, arg1_1):
315
+ # with_effects = torch.ops.higher_order.with_effects(token, ...)
316
+ # getitem = with_effects[0]
317
+ # getitem_1 = with_effects[0]
318
+ # return (getitem, getitem_1)
319
+ # ```
320
+ #
321
+ # After:
322
+ # ```
323
+ # def forward(self, arg1_1):
324
+ # _make_token_default = torch.ops.prims._make_token.default()
325
+ # with_effects = torch.ops.higher_order.with_effects(_make_token_default, ...)
326
+ # getitem = with_effects[0]
327
+ # getitem_1 = with_effects[0]
328
+ # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem]);
329
+ # return (getitem_1,)
330
+ # ```
331
+ #
332
+ # 2. In the case of an invoke_subgraph node, we will use the
333
+ # InvokeSubgraphCache to determine if the subgraph has effects. Then we will
334
+ # turn it into a `with_effects` node. This is so that at the toplevel graph,
335
+ # the nodes will have the correct with_effects threading. We will apply this
336
+ # pass recursively to submodules so the tokens will be removed from the
337
+ # subgraph's inputs.
338
+ #
339
+ # Before:
340
+ # ```
341
+ # def forward(self, token, arg1_1):
342
+ # repeated_subgraph0 = self.repeated_subgraph0
343
+ # invoke_subgraph = torch.ops.higher_order.invoke_subgraph(
344
+ # repeated_subgraph0, 'subgraph_0', token, x, arg1_1)
345
+ # getitem = invoke_subgraph[0]
346
+ # getitem_1 = invoke_subgraph[1]
347
+ # return (getitem, getitem1)
348
+ # ```
349
+ #
350
+ # After:
351
+ # ```
352
+ # def forward(self, arg1_1):
353
+ # _make_token_default = torch.ops.prims._make_token.default()
354
+ # repeated_subgraph0 = self.repeated_subgraph0
355
+ # with_effects_1 = torch.ops.higher_order.with_effects(
356
+ # _make_token_default, torch.ops.higher_order.invoke_subgraph,
357
+ # repeated_subgraph0, 'subgraph_0', arg1_1)
358
+ # getitem = with_effects_1[0]
359
+ # getitem_1 = with_effects_1[1]; with_effects_1 = None
360
+ # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem])
361
+ # return (getitem_1,)
362
+ # ```
363
+ #
364
+ # 3. The toplevel module should have the following invariants:
365
+ # forward:
366
+ # expected_num_erased_inputs == len(fw_metadata.tokens)
367
+ # expected_num_erased_outputs == len(fw_metadata.tokens)
368
+ # backward:
369
+ # expected_num_erased_inputs == fw_metadata.num_backward_tokens
370
+ # expected_num_erased_outputs == fw_metadata.num_backward_tokens
371
+ num_forward_tokens = len(fw_metadata.tokens)
372
+ num_backward_tokens = fw_metadata.num_backward_tokens
373
+
374
+ def replace_input_token_with_make_token(
375
+ module: torch.fx.GraphModule, node: torch.fx.Node
376
+ ) -> None:
377
+ with module.graph.inserting_before(node):
378
+ new_token_node = module.graph.call_function(
379
+ torch.ops.prims._make_token.default, ()
380
+ )
381
+ new_token_node.meta["val"] = torch.tensor([])
382
+ new_token_node.meta["tensor_meta"] = torch.tensor([])
383
+ node.replace_all_uses_with(new_token_node)
384
+ module.graph.erase_node(node)
385
+
386
+ def get_output_tokens(node: torch.fx.Node) -> set[torch.fx.Node]:
387
+ output_tokens = set()
388
+ for user in list(node.users.keys()):
389
+ # Check if this is a getitem accessing index 0 (the token)
390
+ if (
391
+ user.op == "call_function"
392
+ and user.target is operator.getitem
393
+ and len(user.args) > 1
394
+ and user.args[1] == 0
395
+ ):
396
+ # Check if this getitem is used in an output
397
+ for user_user in list(user.users.keys()):
398
+ if user_user.op == "output":
399
+ output_tokens.add(user)
400
+ return output_tokens
401
+
402
+ def _unlift_tokens_from_module_helper(
403
+ module: torch.fx.GraphModule,
404
+ subgraph_str: str,
405
+ expected_num_erased: int | None,
406
+ ) -> None:
407
+ input_token_nodes = set()
408
+ output_token_nodes = set()
409
+
410
+ for node in module.graph.nodes:
411
+ if (
412
+ node.op == "call_function"
413
+ and node.target is torch.ops.higher_order.with_effects
414
+ ):
415
+ if node.args[0].op == "placeholder":
416
+ input_token_nodes.add(node.args[0])
417
+ replace_input_token_with_make_token(module, node.args[0])
418
+
419
+ tokens_from_with_effects = get_output_tokens(node)
420
+ output_token_nodes = output_token_nodes | tokens_from_with_effects
421
+
422
+ elif (
423
+ node.op == "call_function"
424
+ and node.target is torch.ops.higher_order.invoke_subgraph
425
+ ):
426
+ subgraph_node, identifier, *operands = node.args
427
+
428
+ # Check if subgraph has effects by looking in the cache
429
+ from torch._guards import InvokeSubgraphCache, TracingContext
430
+
431
+ effects = None
432
+ tracing_ctx = TracingContext.try_get()
433
+ if tracing_ctx:
434
+ invoke_subgraph_cache = (
435
+ tracing_ctx.hop_dispatch_set_cache.get_cache(
436
+ torch.ops.higher_order.invoke_subgraph
437
+ )
438
+ )
439
+ if invoke_subgraph_cache:
440
+ if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache):
441
+ raise AssertionError(
442
+ f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}"
443
+ )
444
+ effects = invoke_subgraph_cache.get_effects(identifier)
445
+
446
+ if effects is not None:
447
+ # Wrap invoke_subgraph with with_effects
448
+ # Before: invoke_subgraph(subgraph, id, token, *args) -> (token_out, result)
449
+ # After: with_effects(token, invoke_subgraph, subgraph, id, *args) -> (token_out, result)
450
+ #
451
+ # Note: The subgraph itself will be unlifted separately when we iterate
452
+ # through named_modules() below.
453
+
454
+ num_tokens = len(effects)
455
+ if num_tokens != 1:
456
+ raise AssertionError(
457
+ f"Multiple token subgraph NYI, got {num_tokens} tokens"
458
+ )
459
+ token_args = operands[:num_tokens]
460
+ non_token_args = operands[num_tokens:]
461
+
462
+ # Create with_effects wrapper around invoke_subgraph
463
+ # with_effects(token, op, *args) where op is invoke_subgraph
464
+ # Pass the subgraph and non-token args to invoke_subgraph
465
+ with module.graph.inserting_before(node):
466
+ new_node = module.graph.call_function(
467
+ torch.ops.higher_order.with_effects,
468
+ # pyrefly: ignore [bad-argument-type]
469
+ (
470
+ token_args[0], # pyrefly: ignore[bad-argument-type]
471
+ torch.ops.higher_order.invoke_subgraph,
472
+ subgraph_node,
473
+ identifier,
474
+ *tuple(non_token_args),
475
+ ),
476
+ )
477
+ node.replace_all_uses_with(new_node)
478
+ new_node.meta = node.meta
479
+ module.graph.erase_node(node)
480
+
481
+ for token in token_args:
482
+ if token.op == "placeholder":
483
+ input_token_nodes.add(token)
484
+ replace_input_token_with_make_token(module, token)
485
+
486
+ # Get output tokens from the new with_effects node
487
+ tokens_from_invoke_subgraph = get_output_tokens(new_node)
488
+ output_token_nodes = (
489
+ output_token_nodes | tokens_from_invoke_subgraph
490
+ )
491
+
492
+ if not output_token_nodes and not input_token_nodes:
493
+ return
494
+
495
+ output_node = next(reversed(module.graph.find_nodes(op="output")))
496
+ if output_node is None:
497
+ raise AssertionError("output node not found in graph")
498
+ with module.graph.inserting_before(output_node):
499
+ module.graph.call_function(
500
+ torch.ops.prims._sink_tokens.default,
501
+ (list(output_token_nodes),),
502
+ )
503
+ new_out_args = tuple(
504
+ [out for out in output_node.args[0] if out not in output_token_nodes]
505
+ )
506
+ output_node.args = (new_out_args,)
507
+
508
+ if expected_num_erased:
509
+ if len(input_token_nodes) != expected_num_erased:
510
+ raise AssertionError(
511
+ f"{subgraph_str} num_erased_inputs:{len(input_token_nodes)} "
512
+ f"{input_token_nodes} != expected {expected_num_erased} \n"
513
+ f"{fw_module.print_readable(print_output=False)}"
514
+ )
515
+ if len(output_token_nodes) != expected_num_erased:
516
+ raise AssertionError(
517
+ f"{subgraph_str} num_erased_outs:{len(output_token_nodes)} "
518
+ f"{output_token_nodes} != expected {expected_num_erased} \n"
519
+ f"{fw_module.print_readable(print_output=False)}"
520
+ )
521
+
522
+ module.recompile()
523
+
524
+ def unlift_tokens_from_module(
525
+ module: torch.fx.GraphModule, subgraph_str: str, expected_num_erased: int
526
+ ) -> None:
527
+ for name, m in module.named_modules():
528
+ if isinstance(m, torch.fx.GraphModule):
529
+ if name == "":
530
+ _unlift_tokens_from_module_helper(
531
+ m, subgraph_str, expected_num_erased
532
+ )
533
+ else:
534
+ # Subgraph -- we may or may not have effects applied
535
+ _unlift_tokens_from_module_helper(m, f"{subgraph_str}_{name}", None)
536
+
537
+ if num_forward_tokens > 0:
538
+ if aot_config.enable_log:
539
+ from torch._dynamo.utils import lazy_format_graph_code
540
+
541
+ aot_graphs_effects_log.debug(
542
+ "%s",
543
+ lazy_format_graph_code(
544
+ "Forward graph before unlifting tokens",
545
+ fw_module,
546
+ aot_config.aot_id,
547
+ include_stride=True,
548
+ include_device=True,
549
+ colored=True,
550
+ ),
551
+ )
552
+ unlift_tokens_from_module(
553
+ fw_module,
554
+ "forward",
555
+ num_forward_tokens,
556
+ )
557
+
558
+ if bw_module is not None and num_backward_tokens > 0:
559
+ if aot_config.enable_log:
560
+ from torch._dynamo.utils import lazy_format_graph_code
561
+
562
+ aot_graphs_effects_log.debug(
563
+ "%s",
564
+ lazy_format_graph_code(
565
+ "Backward graph before unlifting tokens",
566
+ bw_module,
567
+ aot_config.aot_id,
568
+ include_stride=True,
569
+ include_device=True,
570
+ colored=True,
571
+ ),
572
+ )
573
+ unlift_tokens_from_module(bw_module, "backward", num_backward_tokens)
574
+
575
+ # This is sad, but we need to update the metadata to get rid of
576
+ # the tokens.
577
+ fw_metadata.tokens = {}
578
+ fw_metadata.num_backward_tokens = 0
579
+
580
+
581
+ def root_module_when_exporting_non_strict(
582
+ flat_fn: Callable[..., Any],
583
+ ) -> torch.nn.Module | None:
584
+ # When exporting in non-strict mode, we wrap the root module in a specific pattern.
585
+ # See `_aot_export_non_strict` in torch.export._trace.py.
586
+ # We look for that wrapping pattern here.
587
+ if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"):
588
+ return flat_fn._orig_mod._export_root
589
+ else:
590
+ return None
591
+
592
+
593
+ def _is_forward_node_with_seq_nr(node: torch.fx.Node) -> bool:
594
+ # For now, assume that if nn_module_stack_metadata is populated, this
595
+ # node is from the forward. Ignore nodes without `seq_nr`.
596
+ # TODO(future): there is likely a less brittle way to do this by walking
597
+ # the descendants of graph inputs corresponding to fwd inputs, didn't
598
+ # seem obvious at first glance on how to partition graph inputs into
599
+ # fwd vs bwd without relying on string names.
600
+ return node.meta.get("partitioner_tag") != "is_backward" and "seq_nr" in node.meta
601
+
602
+
603
+ def _is_backward_node_with_seq_nr(node: torch.fx.Node) -> bool:
604
+ # For now, assume that if nn_module_stack_metadata is not populated,
605
+ # this node is from the backward. Ignore nodes without `seq_nr`.
606
+ # TODO(future): there is likely a less brittle way to do this, same
607
+ # as with the forward.
608
+ return node.meta.get("partitioner_tag") == "is_backward" and "seq_nr" in node.meta
609
+
610
+
611
+ def _collect_fwd_nodes_from_subgraph(
612
+ fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node]
613
+ ) -> None:
614
+ """Collect forward nodes from a single subgraph into the global mapping."""
615
+ for node in fx_g.graph.nodes:
616
+ if not _is_forward_node_with_seq_nr(node):
617
+ continue
618
+ seq_nr = node.meta["seq_nr"]
619
+ if seq_nr in fwd_seq_nr_to_node:
620
+ # If we already saw an op with the current `seq_nr`, that means
621
+ # that the current op did not create an autograd node, and there
622
+ # is no corresponding backward node, so we skip.
623
+ continue
624
+ fwd_seq_nr_to_node[seq_nr] = node
625
+
626
+
627
+ def _copy_metadata_to_bw_nodes_in_subgraph(
628
+ fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node]
629
+ ) -> None:
630
+ """Copy metadata from forward nodes to backward nodes in a single subgraph."""
631
+ for node in fx_g.graph.nodes:
632
+ annotation_log.debug("node: %s", node.name)
633
+ seq_nr = node.meta.get("seq_nr")
634
+ annotation_log.debug("seq_nr: %s", seq_nr)
635
+
636
+ if not _is_backward_node_with_seq_nr(node):
637
+ continue
638
+
639
+ # We exclude gradient accumulation nodes from copying tags
640
+ if node.meta.get("is_gradient_acc", False):
641
+ annotation_log.debug("is_gradient_acc")
642
+ continue
643
+
644
+ # fwd_node should always exist, but handle non-existence just in case
645
+ fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"])
646
+ if fwd_node is not None:
647
+ node.meta["fwd_nn_module_stack"] = fwd_node.meta.get("nn_module_stack")
648
+ node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack")
649
+ # TODO: better to change to a specific field of custom?
650
+ custom = fwd_node.meta.get("custom")
651
+ if custom is not None:
652
+ # Merge rather than overwrite so bw-only keys survive
653
+ # fw keys win on conflict.
654
+ node.meta["custom"] = {
655
+ **node.meta.get("custom", {}),
656
+ **copy.deepcopy(custom),
657
+ }
658
+
659
+
660
+ def copy_fwd_metadata_to_bw_nodes(fx_g: torch.fx.GraphModule) -> None:
661
+ """
662
+ Input: `fx_g` which contains the joint fwd+bwd FX graph created by
663
+ aot_autograd.
664
+
665
+ This function walks the graph and copies over metadata from forward nodes
666
+ to backward nodes, using the `seq_nr` field as a one-to-many mapping
667
+ from forward node to backward node. This metadata is useful for performance
668
+ profiling and debugging.
669
+
670
+ This function supports matching forward and backward nodes across different
671
+ subgraphs (e.g., in recursive submodules from HOPs), enabling backward nodes
672
+ in any submodule to match forward nodes in any submodule.
673
+ """
674
+
675
+ # Build a global mapping of seq_nr to forward nodes across all subgraphs
676
+ fwd_seq_nr_to_node: dict[str, torch.fx.Node] = {}
677
+
678
+ # First pass: collect all forward nodes from all subgraphs
679
+ for submod in fx_g.modules():
680
+ if isinstance(submod, torch.fx.GraphModule):
681
+ _collect_fwd_nodes_from_subgraph(submod, fwd_seq_nr_to_node)
682
+
683
+ if annotation_log.isEnabledFor(logging.DEBUG):
684
+ for k, v in fwd_seq_nr_to_node.items():
685
+ annotation_log.debug("forward:: key: %s, value: %s", k, v)
686
+
687
+ # Second pass: copy metadata to backward nodes in all subgraphs
688
+ # using the global forward mapping
689
+ for submod in fx_g.modules():
690
+ if isinstance(submod, torch.fx.GraphModule):
691
+ _copy_metadata_to_bw_nodes_in_subgraph(submod, fwd_seq_nr_to_node)
692
+
693
+
694
+ def register_buffer_assignment_hook(
695
+ mod: torch.nn.Module, assigned_buffers: dict[str, str]
696
+ ) -> Any:
697
+ """
698
+ Register a hook that intercepts buffer assignments.
699
+ This is used to detect when a buffer is assigned to, and then we can
700
+ map that buffer to the corresponding proxy node in the graph.
701
+ """
702
+
703
+ def _map_assigned_buffer_to_proxy(
704
+ _mod: torch.nn.Module, name: str, buffer: Any
705
+ ) -> Any:
706
+ # We intercept buffer assignments on the root module through this hook.
707
+ if _mod._buffers is mod._buffers:
708
+ # either buffer is a functional tensor, which wraps a fake tensor
709
+ if isinstance(buffer, FunctionalTensor):
710
+ buffer = buffer.from_functional()
711
+ # or buffer is a fake tensor
712
+ if not is_fake_tensor(buffer):
713
+ raise AssertionError(f"expected FakeTensor, got {type(buffer)}")
714
+ # The fake tensor in turn is associated with a proxy node.
715
+ proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode()
716
+ if proxy_mode is None:
717
+ raise AssertionError("proxy_mode must not be None")
718
+ proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot(
719
+ buffer, proxy_mode.tracer
720
+ ).proxy.node
721
+ # We map the assigned buffer to this proxy node.
722
+ assigned_buffers[name] = proxy.name
723
+ return buffer
724
+
725
+ return torch.nn.modules.module.register_module_buffer_registration_hook(
726
+ _map_assigned_buffer_to_proxy
727
+ )
728
+
729
+
730
+ def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool:
731
+ """
732
+ Checks if the module contains any metadata mutation ops.
733
+ """
734
+ for node in module.graph.nodes:
735
+ if (
736
+ node.op == "call_function"
737
+ and hasattr(node.target, "tags")
738
+ and torch.Tag.inplace_view in node.target.tags
739
+ ):
740
+ return True
741
+ return False
742
+
743
+
744
+ _GRAPHSAFE_RNG_DEVICE_TYPES: set[str] = {"cuda"}
745
+
746
+
747
+ def register_graphsafe_rng_device_type(device_type: str) -> None:
748
+ """Register a device type as supporting graphsafe RNG operations.
749
+
750
+ The device backend module (``torch.<device_type>``) must provide:
751
+ - ``_get_generator(device: torch.device) -> Generator``: return the default
752
+ generator for the given device. The generator must implement
753
+ ``graphsafe_get_state()``, ``graphsafe_set_state(state)``, and
754
+ ``clone_state()``.
755
+ - ``get_rng_state(device_index: int) -> Tensor``: return the current RNG
756
+ state tensor.
757
+
758
+ Args:
759
+ device_type: The device type string (e.g. "cuda", "xpu").
760
+ """
761
+ from torch._prims.rng_prims import register_graphsafe_rng_dispatch
762
+
763
+ key_name = torch._C._dispatch_key_for_device(device_type)
764
+ dispatch_key = getattr(torch._C.DispatchKey, key_name)
765
+ _GRAPHSAFE_RNG_DEVICE_TYPES.add(device_type)
766
+ register_graphsafe_rng_dispatch(dispatch_key)
767
+
768
+
769
+ def supports_graphsafe_rng(device: torch.device) -> bool:
770
+ """Check whether a device supports graphsafe RNG operations."""
771
+ return device.type in _GRAPHSAFE_RNG_DEVICE_TYPES
772
+
773
+
774
+ def get_default_generator(device: torch.device) -> Any:
775
+ """Get the default RNG generator for a device.
776
+
777
+ Calls ``torch.<device_type>._get_generator(device)``.
778
+ """
779
+ device_mod = getattr(torch, device.type, None)
780
+ if device_mod is None or not hasattr(device_mod, "_get_generator"):
781
+ raise AssertionError(
782
+ f"Device type '{device.type}' does not implement _get_generator. "
783
+ f"Registered graphsafe RNG types: {sorted(_GRAPHSAFE_RNG_DEVICE_TYPES)}."
784
+ )
785
+ return device_mod._get_generator(device)
786
+
787
+
788
+ def get_device_rng_state(device: torch.device) -> torch.Tensor:
789
+ """Get the RNG state tensor for a device."""
790
+ device_mod = getattr(torch, device.type, None)
791
+ if device_mod is not None and hasattr(device_mod, "get_rng_state"):
792
+ idx = device.index if device.index is not None else 0
793
+ return device_mod.get_rng_state(idx)
794
+ return torch.get_rng_state()
795
+
796
+
797
+ def top_saved_tensors_hooks() -> Any:
798
+ return torch._C._autograd._top_saved_tensors_default_hooks(True)
799
+
800
+
801
+ def saved_tensors_hooks_are_inlineable(hooks: Any) -> bool:
802
+ if not hooks:
803
+ return False
804
+ pack, unpack = hooks
805
+ return isinstance(pack, torch.fx.GraphModule) and isinstance(
806
+ unpack, torch.fx.GraphModule
807
+ )
808
+
809
+
810
+ _P = ParamSpec("_P")
811
+ _T = TypeVar("_T")
812
+ _S = TypeVar("_S")
813
+
814
+
815
+ def without_output_descs(f: Callable[_P, tuple[_T, _S]]) -> Callable[_P, _T]:
816
+ @wraps(f)
817
+ @simple_wraps(f)
818
+ def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:
819
+ return f(*args, **kwargs)[0]
820
+
821
+ return inner
822
+
823
+
824
+ _P2 = ParamSpec("_P2")
825
+ _R = TypeVar("_R")
826
+ _R2 = TypeVar("_R2")
827
+
828
+
829
+ def simple_wraps(
830
+ f: Callable[_P, _R],
831
+ ) -> Callable[[Callable[_P2, _R2]], Callable[_P2, _R2]]:
832
+ # NB: omit ('__module__', '__name__', '__qualname__') for ease of
833
+ # debugging
834
+ return wraps(f, assigned=("__doc__", "__annotations__", "__type_params__"))
835
+
836
+
837
+ _Ts = TypeVarTuple("_Ts")
838
+
839
+
840
+ def call_and_expect_output_descs(
841
+ fn: Callable[[*_Ts], tuple[Any, Any]], args: tuple[Unpack[_Ts]]
842
+ ) -> tuple[Any, Any]:
843
+ from .descriptors import AOTOutput
844
+
845
+ outs_pair = fn(*args)
846
+ if not (isinstance(outs_pair, tuple) and len(outs_pair) == 2):
847
+ raise AssertionError(
848
+ f"expected tuple of length 2, got {type(outs_pair)} with value {outs_pair}"
849
+ )
850
+ outs, outs_descs = outs_pair
851
+ # The Tensor tests protects against the test when there are no outputs
852
+ out_vals, out_spec = pytree.tree_flatten(outs)
853
+ out_desc_vals, out_desc_spec = pytree.tree_flatten(outs_descs)
854
+ if out_spec != out_desc_spec:
855
+ raise AssertionError(
856
+ f"output spec mismatch: {fn_wrappers(fn)}, outs={outs}, outs_descs={outs_descs}, "
857
+ f"out_spec={out_spec}, out_desc_spec={out_desc_spec}"
858
+ )
859
+ if any(isinstance(x, AOTOutput) for x in out_vals):
860
+ raise AssertionError(
861
+ f"unexpected AOTOutput in out_vals: {fn_wrappers(fn)}, outs={outs}, "
862
+ f"outs_descs={outs_descs}, out_vals={out_vals}"
863
+ )
864
+ if not all(
865
+ isinstance(d, AOTOutput)
866
+ for (x, d) in zip(out_vals, out_desc_vals)
867
+ if isinstance(x, (torch.Tensor, torch.SymInt)) or type(x) is int
868
+ ):
869
+ raise AssertionError(
870
+ f"expected all descriptors to be AOTOutput: {fn_wrappers(fn)}, outs={outs}, "
871
+ f"outs_descs={outs_descs}, out_vals={out_vals}, out_desc_vals={out_desc_vals}"
872
+ )
873
+ return outs_pair
874
+
875
+
876
+ def fn_wrappers(fn: Callable[..., Any]) -> list[Callable[..., Any]]:
877
+ fns = [fn]
878
+ f = fn
879
+ while hasattr(f, "__wrapped__"):
880
+ f = f.__wrapped__
881
+ fns.append(f)
882
+ return fns
883
+
884
+
885
+ def _is_primal(node: torch.fx.Node) -> bool:
886
+ return (
887
+ node.op == "placeholder"
888
+ and "tangents" not in str(node.target)
889
+ and not _is_bwd_seed_offset(node)
890
+ and not _is_fwd_seed_offset(node)
891
+ )
892
+
893
+
894
+ def _is_tangent(node: torch.fx.Node) -> bool:
895
+ return node.op == "placeholder" and "tangents" in str(node.target)
896
+
897
+
898
+ def _is_bwd_seed_offset(node: torch.fx.Node) -> bool:
899
+ return node.op == "placeholder" and (
900
+ "bwd_seed" in str(node.target) or "bwd_base_offset" in str(node.target)
901
+ )
902
+
903
+
904
+ def _is_fwd_seed_offset(node: torch.fx.Node) -> bool:
905
+ return node.op == "placeholder" and (
906
+ "fwd_seed" in str(node.target) or "fwd_base_offset" in str(node.target)
907
+ )
.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py ADDED
@@ -0,0 +1,1971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import itertools
6
+ import time
7
+ from contextlib import nullcontext
8
+ from functools import wraps
9
+ from typing import Any, cast, Literal, TYPE_CHECKING
10
+ from typing_extensions import ParamSpec, TypeVar
11
+ from unittest.mock import patch
12
+
13
+ import torch
14
+ import torch._dynamo.logging
15
+ import torch.nn as nn
16
+ import torch.utils._pytree as pytree
17
+ import torch.utils.dlpack
18
+ from torch import Tensor
19
+ from torch._decomp.decompositions_for_rng import PhiloxStateTracker, rng_decompositions
20
+ from torch._dispatch.python import enable_python_dispatcher
21
+ from torch._dynamo import compiled_autograd
22
+ from torch._dynamo.utils import (
23
+ CompileEventLogger,
24
+ dynamo_timed,
25
+ preserve_rng_state,
26
+ set_feature_use,
27
+ )
28
+ from torch._guards import detect_fake_mode
29
+ from torch._inductor.codecache import resolve_pre_grad_pass_timing
30
+
31
+ # Runtime annotation consumers still resolve BoxedBool from module globals.
32
+ from torch._subclasses import FakeTensorMode
33
+ from torch._subclasses.fake_tensor import maybe_get_fake_mode
34
+ from torch.export._tree_utils import reorder_kwargs
35
+ from torch.fx.experimental.proxy_tensor import make_fx
36
+
37
+ from . import config
38
+ from ._aot_autograd import autograd_cache
39
+ from ._aot_autograd.autograd_cache import (
40
+ AOTAutogradCache,
41
+ should_use_local_autograd_cache,
42
+ should_use_remote_autograd_cache,
43
+ )
44
+ from ._aot_autograd.collect_metadata_analysis import (
45
+ run_functionalized_fw_and_collect_metadata,
46
+ )
47
+ from ._aot_autograd.descriptors import (
48
+ AOTInput,
49
+ BufferAOTInput,
50
+ DifferentiableAOTInput,
51
+ ParamAOTInput,
52
+ PlainAOTInput,
53
+ )
54
+ from ._aot_autograd.frontend_utils import (
55
+ _detect_attribute_assignment,
56
+ _try_get_metadata_from_dynamo,
57
+ construct_fake_mode,
58
+ process_inputs,
59
+ )
60
+ from ._aot_autograd.functional_utils import ( # noqa: F401
61
+ _check_if_mutation_can_be_in_graph,
62
+ are_all_mutations_hidden_from_autograd,
63
+ are_all_mutations_under_no_grad_or_inference_mode,
64
+ assert_functional_graph,
65
+ from_fun,
66
+ gen_alias_from_base,
67
+ has_data_mutation,
68
+ has_metadata_mutation,
69
+ is_fun,
70
+ sync_functional_tensor,
71
+ to_fun,
72
+ )
73
+ from ._aot_autograd.graph_capture_wrappers import ( # noqa: F401
74
+ aot_dispatch_subclass,
75
+ create_functional_call,
76
+ create_functionalized_fn,
77
+ create_functionalized_rng_ops_wrapper,
78
+ create_joint,
79
+ fn_input_mutations_to_outputs,
80
+ fn_prepped_for_autograd,
81
+ )
82
+ from ._aot_autograd.graph_compile import (
83
+ aot_stage1_graph_capture,
84
+ aot_stage2_compile,
85
+ aot_stage2_export,
86
+ )
87
+ from ._aot_autograd.input_output_analysis import ( # noqa: F401
88
+ compute_overlapping_inputs,
89
+ create_graph_signature,
90
+ create_synthetic_base_metadata,
91
+ remove_dupe_metadata,
92
+ )
93
+ from ._aot_autograd.logging_utils import ( # noqa: F401
94
+ callback_set,
95
+ describe_input,
96
+ format_guard_bug_msg,
97
+ get_aot_compilation_context,
98
+ get_aot_graph_name,
99
+ get_graph_being_compiled,
100
+ graph_being_compiled,
101
+ model_name,
102
+ nth_graph,
103
+ set_model_name,
104
+ setup_stacktrace_preservation_hooks,
105
+ track_graph_compiling,
106
+ )
107
+ from ._aot_autograd.runtime_wrappers import ( # noqa: F401
108
+ AOTDedupeWrapper,
109
+ AOTSyntheticBaseWrapper,
110
+ SerializableCompiledFunction,
111
+ )
112
+ from ._aot_autograd.schemas import ( # noqa: F401
113
+ ActInputPath,
114
+ AOTConfig,
115
+ AOTDispatchCompiler,
116
+ AOTGraphCapture,
117
+ AOTState,
118
+ BackwardSignature,
119
+ FakifiedFlatArgs,
120
+ FQN,
121
+ GraphInputName,
122
+ GraphOutputName,
123
+ GraphSignature,
124
+ InputAliasInfo,
125
+ JointWithDescriptors,
126
+ MutationType,
127
+ OpaqueMeta,
128
+ OutputAliasInfo,
129
+ OutputType,
130
+ SerializableAOTDispatchCompiler,
131
+ SubclassCreationMeta,
132
+ SubclassMeta,
133
+ TensorAlias,
134
+ ViewAndMutationMeta,
135
+ )
136
+ from ._aot_autograd.subclass_utils import ( # noqa: F401
137
+ requires_subclass_dispatch,
138
+ unwrap_tensor_subclasses,
139
+ unwrap_tensor_subclasses_with_indices_to_original,
140
+ wrap_tensor_subclasses,
141
+ wrap_tensor_subclasses_maybe_joint,
142
+ )
143
+ from ._aot_autograd.to_standalone_python import ( # noqa: F401
144
+ compile_to_python,
145
+ load_from_python,
146
+ )
147
+ from ._aot_autograd.utils import ( # noqa: F401
148
+ _get_autocast_states,
149
+ call_func_at_runtime_with_args,
150
+ create_tree_flattened_fn,
151
+ KNOWN_TYPES,
152
+ make_boxed_compiler,
153
+ make_boxed_func,
154
+ maybe_to_fresh_input,
155
+ normalize_as_list,
156
+ partial_flatten_asdict,
157
+ PytreeThunk,
158
+ root_module_when_exporting_non_strict,
159
+ simple_wraps,
160
+ strict_zip,
161
+ )
162
+ from .partitioners import default_partition
163
+
164
+
165
+ if TYPE_CHECKING:
166
+ from collections.abc import Callable, Iterable, Sequence
167
+
168
+ from torch._inductor.compile_fx import CompilerConfigExtra
169
+ from torch._inductor.output_code import OutputCode
170
+ from torch._inductor.utils import InputType
171
+ from torch._ops import OpOverload
172
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
173
+
174
+ _P = ParamSpec("_P")
175
+ _R = TypeVar("_R")
176
+
177
+ zip = strict_zip
178
+
179
+ # This global counter increments every time we compile a graph with
180
+ # AOTAutograd. You can use this to correlate runtime error messages
181
+ # with compile time (e.g., if you get an error at runtime saying
182
+ # compiled graph 3 failed, you can set a breakpoint at compile time
183
+ # for this graph number to investigate further at compile time.)
184
+ #
185
+ # NB: this is different from get_aot_compilation_context, which tracks
186
+ # each underlying graph that is compiled. In contrast, AOT_COUNTER
187
+ # corresponds to top-level invocations of aot_module/aot_function;
188
+ # one counter is allocated per entire compiled block (but this block
189
+ # may involve compiling multiple subgraphs; e.g., for forwards/backwards)
190
+ AOT_COUNTER = itertools.count()
191
+
192
+
193
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
194
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195
+ #
196
+ # AOT Autograd contains a pretty non-trivial amount of logic to handle edge cases around aliasing and mutation
197
+ # that are external to the graph (they show up as side effects in some way when you run the graph).
198
+ #
199
+ # Take a look at `test_aotdispatch.py TestAOTAutograd.test_input_mutation*` tests for some examples functions
200
+ # and what they're compiled graphs looks like.
201
+ # Below is a very long comment detailing several edge cases, and showing how AOT Autograd handles them.
202
+ #
203
+ # Note [AOT Autograd: input data mutations]
204
+ #
205
+ # If we compile a function that mutates inputs, then those input mutations are real side effects
206
+ # that a user expects to see after running the compiled graph.
207
+ # However, the graph that we want to send to a backend needs to be *entirely* functional.
208
+ # The way we reconcile this difference is that we remove the mutations completely from the graph that we compile
209
+ # but we update the graph to return (updated_inputs, user_outputs).
210
+ # In the epilogue that runs after the compiled graph is executed, we copy the updated inputs back to the originals.
211
+ #
212
+ # Example: original user code:
213
+ # def f(x):
214
+ # x.mul_(2)
215
+ # out = x.mul(3)
216
+ # return out
217
+ #
218
+ # After AOT Autograd compiles, we end up with a:
219
+ # (a) compiled graph
220
+ # (b) autograd.Function.forward() method, that executes the compiled graph
221
+ # (c) wrapper function, that calls the autograd.Function.forward() and performs the epilogue
222
+ #
223
+ # The output of (a, b, c) are all written below.
224
+ #
225
+ # def compiled_forward_graph(x):
226
+ # x_updated = x.mul(2)
227
+ # out = x_updated.mul(3)
228
+ # return x_updated, out
229
+ #
230
+ # # x_updated gets a gradient in the compiled backward
231
+ # def compiled_backward_graph(grad_x_updated, grad_out):
232
+ # grad_x = ...
233
+ # return grad_x
234
+ #
235
+ # def autograd.Function.forward(x):
236
+ # x_updated, out = compiled_forward_graph(x)
237
+ # return x_updated, out
238
+ #
239
+ # def compiled_wrapper(x):
240
+ # x_updated, out = autograd.Function.apply(x)
241
+ # x.copy_(x_updated)
242
+ # return out
243
+ #
244
+ # Another important thing to note is that updated inputs (due to data mutations) *do* participate
245
+ # in the compiled backward graph! Since the compiled forward graph gets N extra outputs
246
+ # (due to updated inputs showing up as graph outputs),
247
+ # The compiled backward gets an additional N inputs.
248
+ # That way, during the x.copy_(x_updated) bit in the epilogue, gradients will flow from the updated input
249
+ # back to the original input.
250
+
251
+
252
+ # Note [AOT Autograd: input metadata mutations]
253
+ #
254
+ # For the same reason as input mutations, we also don't put input metadata mutations in the graph.
255
+ # Instead, we return the updated version of the input (a view), and mutate the input's metadata outside of the graph
256
+ #
257
+ # Example: original user code:
258
+ # def f(x):
259
+ # x.t_()
260
+ # out = x.mul(3)
261
+ # return out
262
+ #
263
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
264
+ # def compiled_forward_graph(x):
265
+ # x_updated = x.t()
266
+ # out = x_updated.mul(3)
267
+ # return x_updated, out
268
+ #
269
+ # # x_updated does *not* get a gradient in the compiled backward
270
+ # def compiled_backward_graph(grad_out):
271
+ # grad_x = ...
272
+ # return grad_x
273
+ #
274
+ # def autograd.Function.forward(x):
275
+ # x_updated, out = compiled_forward_graph(x)
276
+ # return x_updated, out
277
+ #
278
+ # def compiled_wrapper(x):
279
+ # x_updated, out = autograd.Function.apply(x)
280
+ # x.as_strided_(x_updated)
281
+ # return out
282
+
283
+
284
+ # Note [AOT Autograd: outputs aliasing inputs or intermediates!]
285
+ #
286
+ # AOT Autograd needs special handling for outputs that alias graph inputs or intermediates!
287
+ # Why?
288
+ # (1) autograd.Function.forward() has a limitation, where views that returned in the forward cannot later be mutated.
289
+ # (2) views don't need to be compiled in the graph anyway - it's cheap to generate them outside of the compiled graph,
290
+ # in an epilogue.
291
+ # For outputs that alias inputs, we do the following:
292
+ # (a) *still* return the aliased output as a graph output
293
+ # (b) In the AOT Autograd wrapper/epilogue, we don't return that aliased output. Instead, we use it to regenerate the output.
294
+ #
295
+ # For outputs that alias *intermediates*, we do the following:
296
+ # (a) Return the output in the compiled forward, **and** return it's ._base (a graph intermediates) as an output in the forward
297
+ # (b) Use (output, graph_intermediate) to regenerate the alias, and return that to the user (instead of the compiled fw output).
298
+ # You might wonder why we return the aliased output directly in the graph (and making the graph compute it),
299
+ # only to not return it and instead generate a fresh alias off of the intermediate,
300
+ # instead of (say) just storing metadata about the size/stride of the output somewhere to generate the alias. There are two reasons:
301
+ # (1) Getting the actual alias tensor allows us to use view-replay to generate the alias, instead of an as_strided() call
302
+ # (2) Inductor (and other backends) are free to change the memory format of graph outputs, if it results in better performance.
303
+ # This can result in problems if a user later tries to .view() that output expecting it to have one set of strides,
304
+ # when it has a different set of strides.
305
+ # By including the view op directly in the graph, inductor takes that into account when deciding what memory format
306
+ # the graph intermediate should be.
307
+ #
308
+ # Another important thing to note is how our traced backward() graph handles aliases.
309
+ # (this applies to outputs aliasing inputs, outputs aliasing intermediates,
310
+ # *and* updated inputs returned in the compiled forward due to metadata-only mutations).
311
+ # Any outputs that alias (either inputs or intermediates) do NOT participate in the compiled backward graph
312
+ # It would be wasteful to include them in the compiled backward(), because we regenerate them eagerly
313
+ # at the end of the forward.
314
+ #
315
+ # Example: original user code:
316
+ # def f(x):
317
+ # out1 = x.t()
318
+ # intermediate = x.mul(2)
319
+ # out2 = intermediate.view(-1)
320
+ # return out1, out2
321
+ #
322
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
323
+ # def compiled_forward_graph(x):
324
+ # out1 = x.t()
325
+ # intermediate = x.mul(2)
326
+ # out2 = intermediate.view(-1)
327
+ # # the compiled graph also returns the intermediate
328
+ # return out1, out2, intermediate
329
+ #
330
+ # # intermediate gets a gradient in the compiled backward.
331
+ # # both output aliases (out1 and out2) do not.
332
+ # def compiled_backward_graph(grad_intermediate):
333
+ # grad_x = ...
334
+ # return grad_x
335
+ #
336
+ # def autograd.Function.forward(x):
337
+ # out1, out2, intermediate = compiled_forward_graph(x)
338
+ # return out1, out2, intermediate
339
+ #
340
+ # def compiled_wrapper(x):
341
+ # out1, out2, intermediate = autograd.Function.apply(x)
342
+ # # regenerate out1 from the input
343
+ # out1_regenerated = out1._view_func(x)
344
+ # # regenerate out1 from the intermediate
345
+ # out2_regenerated = out2._view_func(intermediate)
346
+ # return out1_regenerated, out2_regenerated
347
+
348
+
349
+ # Note [AOT Autograd: mutations to inputs that alias other inputs]
350
+ #
351
+ # Another edge case that is (only partially) handled today is when an input is mutated, but itself aliases another input.
352
+ # AOT Autograd needs to **ensure** that functionalization knows that the two inputs are aliased to each other.
353
+ # That way, when the aliased input is accessed later in the graph, functionalization knows to "update" the alias
354
+ # given the mutation that occurred.
355
+ #
356
+ # This is handled by updating the calling convention: we create a "synthetic base" that becomes a new input
357
+ # in the compiled function, and we regenerate the original (aliased) inputs directly off of the base
358
+ # inside of the compiled function.
359
+ #
360
+ # This logic is fully encapsulated in aot_wrapper_synthetic_base()
361
+ #
362
+ # Example: original user code:
363
+ # def f(x, x_view):
364
+ # x.mul_(2)
365
+ # out = x * x_view
366
+ # return out
367
+ # f(x, x.view(-1))
368
+ #
369
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
370
+ # def compiled_forward_graph(base)
371
+ # x = generate_x(base)
372
+ # x_view = generate_x_view(base)
373
+ # x_updated = x.mul(2)
374
+ # x_view_updated = x_updated.view(-1)
375
+ # out = x_updated * x_view_updated
376
+ # return x_updated, out
377
+ #
378
+ # # The calling convention change from (aliases) -> (base) happens
379
+ # # *outside* of the autograd.Function.forward().
380
+ # # That means the forward() only has 1 input (base),
381
+ # # and the backward() only has 1 output (grad_base)
382
+ # def compiled_backward_graph(grad_out):
383
+ # grad_base = ...
384
+ # return grad_base
385
+ #
386
+ # def autograd.Function.forward(base):
387
+ # x_updated, out = compiled_forward_graph(base)
388
+ # return x_updated, out
389
+ #
390
+ # # The compiled wrapper is where we create synthetic bases.
391
+ # # The info on which inputs are mutated is also tracked *before* synthetic base creation.
392
+ # def compiled_wrapper(x, x_view):
393
+ # base = merge_view_inputs(x, x_view)
394
+ # x_updated, out = autograd.Function.apply(base)
395
+ # # x and x_view are aliased in eager mode, so this mutation to x will automatically affect x_view.
396
+ # x.copy_(x_updated)
397
+ # return out
398
+
399
+
400
+ # Note [AOT Autograd: Views to avoid tangents aliasing inputs]
401
+ #
402
+ # We view every forward output when creating out tangent tensors to handle the problematic
403
+ # case in which a subclass does extra aliasing between graph outputs/inputs in a way that
404
+ # is not visible above the subclass.
405
+ #
406
+ # Ordinarily, when constructing the joint function that we want to trace in AOTAutograd,
407
+ # we're guaranteed that the tangent tensors that we pass
408
+ # into the joint are distinct tensors from the primals. This is because when
409
+ # decide which forward outputs to create tangents for, we only create tangents
410
+ # for forward outputs that are not aliases of inputs (See Note
411
+ # [AOT Autograd: outputs aliasing inputs or intermediates!]).
412
+ #
413
+ # However, when wrapper tensor subclasses enter the picture, it is possible
414
+ # to have an output of the forward that is a subclass that is not an
415
+ # input / alias of an input, but one of its inner tensors is an alias!
416
+ # NestedTensor is an example: Performing an out-of-place pointwise op on a
417
+ # NestedTensor constructs a fresh NestedTensor that holds onto the input's
418
+ # offsets tensor directly.
419
+ #
420
+ # Having tangent tensors that are the same as the (primal) forward inputs,
421
+ # can cause problems during tracing as make_fx() will specialize on our
422
+ # duplicate inputs: If we passed in the same tensor for primals_1 and
423
+ # tangents_1 during tracing, make_fx() will happily sub out all usages of
424
+ # tangents_1 with primals_1 in the graph, which is not what we want.
425
+ #
426
+ # To work around this, we view every forward output when creating out tangent
427
+ # tensors so that tangents can never be the same as forward inputs even if
428
+ # forward inputs alias forward outputs.
429
+
430
+ # Note [Side-Effectful Tokens in AOTAutograd]
431
+ #
432
+ # We allow some side-effectful operators in
433
+ # the post-AOTAutograd (functional) graph, such as prints and torchbind operations.
434
+ # To ensure that these side-effects are compatible to future graph passes that
435
+ # assume that the graph is functional, we will thread "effect tokens" to show
436
+ # data dependence between these side-effectful operators. Practically speaking,
437
+ # effect tokens are just dummy values (torch.tensor([])). The graph would look
438
+ # like the following:
439
+ #
440
+ # def gm(self, token0, reader):
441
+ # token1, frame = with_token(ordered_effect_op, (reader,), token0)
442
+ # frame = frame * 2
443
+ # token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
444
+ # frame2 = frame2 * 2
445
+ # return token2, frame, frame2
446
+ #
447
+ # We will pass the token as an input to the graph, thread it through
448
+ # side-effectful operators using the `with_effects` high order operator, and then
449
+ # return the updated token as an output.
450
+ # So the signature of the graph input would look something like
451
+ # (*tokens, *params_buffers, *user_inputs), and the signature of the graph
452
+ # output would look something like (*tokens, *outputs).
453
+ #
454
+ # However, Inductor does not want the concept of tokens in the final generated
455
+ # code's input and output. Since changing the graph signature inside of inductor
456
+ # is difficult, after generating the forward graph, we will run a pass to
457
+ # remove the tokens from the input and generate the following graph for Inductor, where
458
+ # the tokens are created and sunk within the graph, rather than as inputs and
459
+ # outputs:
460
+ #
461
+ # def gm(self, reader):
462
+ # token0 = torch.ops.prims._make_token()
463
+ # token1, frame = with_token(ordered_effect_op, (reader,), token0)
464
+ # frame = frame * 2
465
+ # token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
466
+ # frame2 = frame2 * 2
467
+ # sink_token = torch.ops.prims._sink_tokens([token2])
468
+ # return frame, frame2
469
+
470
+ #
471
+ #
472
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
473
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474
+
475
+
476
+ aot_autograd_decompositions: dict[OpOverload, Callable[..., Any]] = {}
477
+
478
+
479
+ def create_aot_state(
480
+ stack: contextlib.ExitStack,
481
+ flat_fn: Callable[_P, _R],
482
+ fake_flat_args: FakifiedFlatArgs,
483
+ flat_args_descs: list[AOTInput],
484
+ aot_config: AOTConfig,
485
+ fake_mode: FakeTensorMode,
486
+ shape_env: ShapeEnv | None,
487
+ ) -> AOTState:
488
+ """
489
+ Traces the forward and backward graphs of the attr:`flat_fn` to generate a
490
+ joint graph. The joint graph is an Fx graph with Aten ops. Please refer to
491
+ the tracing mechanism to understand the graph capturing details.
492
+
493
+ The joint graph is then passed through attr:`partition_fn` to isolate the
494
+ forward and backward portions, which are then respectively compiled via the
495
+ provided attr:`fw_compiler` and attr:`bw_compiler`.
496
+
497
+ The resulting compiled forward and backward graphs are then wrapped up in a
498
+ ``torch.autograd.Function`` object.
499
+
500
+ The calling convention here is that the first aot_config.num_params_buffers
501
+ inputs in flat_args are parameters and buffers, and the rest are inputs.
502
+
503
+ We use this to assume that parameters/buffer's shapes don't change.
504
+ """
505
+
506
+ # Old name for now to avoid messing with stats. Also, note this is pushed
507
+ # on the stack, so it extends BEYOND this function
508
+ stack.enter_context(
509
+ dynamo_timed("create_aot_dispatcher_function", log_pt2_compile_event=True)
510
+ )
511
+
512
+ # This is the main entry point.
513
+ # TODO: Chillee argues that dynamo itself should pass in fake tensors to
514
+ # the list of arguments when compiling; at the moment we do not do this
515
+
516
+ decompositions = aot_config.decompositions or {}
517
+ decompositions = {
518
+ **aot_autograd_decompositions,
519
+ **decompositions,
520
+ }
521
+
522
+ if config.functionalize_rng_ops:
523
+ # Update the decompositions with functionalized random decompositions
524
+ decompositions = {
525
+ **rng_decompositions,
526
+ **decompositions,
527
+ }
528
+
529
+ aot_config = dataclasses.replace(
530
+ aot_config,
531
+ decompositions=cast("dict[OpOverload, Callable[..., Any]]", decompositions),
532
+ )
533
+
534
+ # Check flat_args to see if they're already fake. If so, use that fake
535
+ # mode instead.
536
+
537
+ python_dispatcher_mode = (
538
+ enable_python_dispatcher() if shape_env is not None else nullcontext()
539
+ )
540
+
541
+ # See NOTE: [Deferring tensor pack/unpack hooks until runtime]
542
+ # If any saved tensor hooks are active, we **don't** want to trace them.
543
+ # Instead, we'll let them run at runtime, around the custom autograd.Function
544
+ # that we generate in torch.compile.
545
+ stack.enter_context(torch.autograd.set_multithreading_enabled(False))
546
+ stack.enter_context(preserve_rng_state())
547
+ stack.enter_context(fake_mode)
548
+ stack.enter_context(python_dispatcher_mode)
549
+ stack.enter_context(PhiloxStateTracker())
550
+ stack.enter_context(
551
+ torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing()
552
+ )
553
+
554
+ from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj
555
+ from torch._library.opaque_object import is_custom_class
556
+
557
+ # Tracing may mutate the states the fake script object,
558
+ # so we need to duplicate the fake script objects so that subsequent tracing
559
+ # won't be affected.
560
+ def _dup_fake_script_obj(fake_flat_args: FakifiedFlatArgs) -> list[Any]:
561
+ return [
562
+ maybe_to_fake_obj(detect_fake_mode(fake_flat_args), arg.real_obj)
563
+ if isinstance(arg, FakeScriptObject) or is_custom_class(type(arg))
564
+ else arg
565
+ for arg in fake_flat_args
566
+ ]
567
+
568
+ needs_autograd = any(
569
+ x.requires_grad for x in fake_flat_args if isinstance(x, Tensor)
570
+ )
571
+
572
+ with enable_python_dispatcher():
573
+ # Patch set_rng_state as set_rng_state with fake tensors is
574
+ # nonsensical. This does not affect the collection of metadata.
575
+ with patch("torch.cuda.set_rng_state", lambda *args: None):
576
+ mod = root_module_when_exporting_non_strict(flat_fn)
577
+ if mod is not None:
578
+ ctx = _detect_attribute_assignment(mod)
579
+ else:
580
+ ctx = nullcontext()
581
+
582
+ if torch._functorch.config.fake_tensor_propagate_real_tensors:
583
+ # Running dynamo_timed causes fake tensor issues when
584
+ # propagate real tensor is switched on.
585
+ dynamo_timed_ctx = nullcontext()
586
+ else:
587
+ dynamo_timed_ctx = dynamo_timed(
588
+ "aot_collect_metadata", log_pt2_compile_event=True
589
+ )
590
+
591
+ with (
592
+ dynamo_timed_ctx,
593
+ ctx,
594
+ torch._dynamo.eval_frame._use_eager_on_nested_compile(),
595
+ ):
596
+ fw_metadata = run_functionalized_fw_and_collect_metadata(
597
+ flat_fn,
598
+ flat_args_descs=flat_args_descs,
599
+ static_input_indices=aot_config.static_input_indices,
600
+ keep_input_mutations=aot_config.keep_inference_input_mutations,
601
+ pre_dispatch=aot_config.pre_dispatch,
602
+ )(*_dup_fake_script_obj(fake_flat_args))
603
+
604
+ req_subclass_dispatch = requires_subclass_dispatch(
605
+ fake_flat_args, fw_metadata
606
+ )
607
+ CompileEventLogger.try_add_pt2_compile(
608
+ "backend_compile", requires_subclass_dispatch=req_subclass_dispatch
609
+ )
610
+
611
+ output_and_mutation_safe = not any(
612
+ x.requires_grad
613
+ # view-type operations preserve requires_grad even in no_grad.
614
+ # Do not count aliases of inputs with requires_grad as reason to make a training graph,
615
+ # as AOTAutograd will perform view-replay to regenerate the view outputs at runtime,
616
+ # setting their grad_fn properly.
617
+ and not (
618
+ x.output_type in (OutputType.alias_of_input, OutputType.is_input)
619
+ and x.base_idx is not None
620
+ and fw_metadata.input_info[x.base_idx].requires_grad
621
+ )
622
+ for x in fw_metadata.output_info
623
+ ) and not any(
624
+ x.requires_grad
625
+ and x.mutates_data
626
+ and not x.mutations_under_no_grad_or_inference_mode
627
+ and not x.mutations_hidden_from_autograd
628
+ for x in fw_metadata.input_info
629
+ )
630
+
631
+ if needs_autograd and output_and_mutation_safe:
632
+ # We realized that none of the outputs require grad,
633
+ # and none of the inputs that require grad are mutated.
634
+ # so we actually have an inference graph.
635
+ needs_autograd = False
636
+
637
+ if fw_metadata.num_intermediate_bases > 0:
638
+ if req_subclass_dispatch:
639
+ raise AssertionError(f"""\
640
+ torch.compile is currently being used with tensor subclass inputs.
641
+ We are attempting to a compile a graph with two graph outputs
642
+ that alias one another, specifically output indices:
643
+
644
+ {[i for i, x in enumerate(fw_metadata.output_info) if x.output_type == OutputType.alias_of_intermediate]}
645
+
646
+ ANY output aliasing (even for regular tensors) is currently unsupported if
647
+ there are any subclass outputs. If you run into this, please file a github
648
+ issue""")
649
+
650
+ if aot_config.is_export:
651
+ # aot_export: ban input metadata mutations for now to keep shared code paths simpler.
652
+ # Keeping .resize_() in the graph will require some work
653
+ # Allowing it but keeping the graph functional will require some calling convention changes.
654
+ if len([x for x in fw_metadata.input_info if x.mutates_metadata]) != 0:
655
+ raise RuntimeError(
656
+ f"""\
657
+ Found an input that received a metadata mutation, through e.g. a call to `.resize_()` or `.transpose_()`.
658
+ This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
659
+
660
+ fw_metadata={str(fw_metadata)}"""
661
+ )
662
+ # In export, banning data mutations on inputs that require grad for now.
663
+ # This should be rare, and is tricky to get right. When we trace the backward,
664
+ # we currently trace with autograd.grad instead of .backward(), which makes it difficult
665
+ # to ensure that we run autograd all the way through the input **before** it saw the mutation.
666
+ if (
667
+ len(
668
+ [
669
+ x
670
+ for x in fw_metadata.input_info
671
+ if x.requires_grad and x.mutates_data
672
+ ]
673
+ )
674
+ != 0
675
+ and aot_config.export_trace_joint
676
+ ):
677
+ raise RuntimeError(
678
+ f"""\
679
+ Found a graph input that requires gradients, and received a mutation.
680
+ This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
681
+
682
+ fw_metadata={str(fw_metadata)}"""
683
+ )
684
+ if req_subclass_dispatch:
685
+ raise RuntimeError(
686
+ """\
687
+ aot_export is not currently supported with traceable tensor subclass.
688
+ If you need this feature, please comment on <CREATE_ISSUE_LINK>"""
689
+ )
690
+
691
+ # Need to decide on a strategy for functionalized RNG: toggling via global config seems bad,
692
+ # and turning it on will require a non-trivial calling convention change for any export runtime.
693
+ if config.functionalize_rng_ops:
694
+ raise RuntimeError(
695
+ """\
696
+ Functionalized RNG is not currently supported in the aot_export workflow. Please file a github issue,
697
+ or otherwise set torch._functorch.config.functionalize_rng_ops = False."""
698
+ )
699
+
700
+ return AOTState(
701
+ needs_autograd=needs_autograd,
702
+ flat_args=_dup_fake_script_obj(fake_flat_args),
703
+ flat_args_descs=flat_args_descs,
704
+ fw_metadata=fw_metadata,
705
+ # Packaging this just for later use
706
+ aot_config=aot_config,
707
+ stack=stack,
708
+ fake_mode=fake_mode,
709
+ )
710
+
711
+
712
+ def aot_function(
713
+ fn: Callable[_P, _R],
714
+ fw_compiler: AOTDispatchCompiler,
715
+ bw_compiler: AOTDispatchCompiler | None = None,
716
+ partition_fn: Callable[..., Any] = default_partition,
717
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
718
+ num_params_buffers: int = 0,
719
+ keep_inference_input_mutations: bool = False,
720
+ inference_compiler: AOTDispatchCompiler | None = None,
721
+ *,
722
+ # Whether or not to trace with dynamic shapes
723
+ dynamic: bool = False,
724
+ enable_log: bool = True,
725
+ disable_functionalization: bool = False,
726
+ _disable_torch_fn_metadata_mode: bool = False,
727
+ ) -> Callable[_P, Any]:
728
+ """
729
+ Traces the forward and backward graph of :attr:`fn` using torch dispatch
730
+ mechanism, and then compiles the generated forward and backward graphs
731
+ through :attr:`fw_compiler` and :attr:`bw_compiler`.
732
+
733
+ :func:`aot_function` traces the forward and backward graph ahead of time,
734
+ and generates a joint forward and backward graph. :attr:`partition_fn` is
735
+ then used to separate out forward and backward graphs. The partitioner
736
+ function can be used to perform optimizations such as recomputation. One can
737
+ set `decompositions` dictionary to decompose the operators into a sequence
738
+ of core or simpler operators supported by the backend compilers.
739
+
740
+ .. warning::
741
+ This API is experimental and likely to change.
742
+
743
+ Args:
744
+ fn (Callable): A Python function that takes one or more arguments. Must
745
+ return one or more Tensors.
746
+ fw_compiler (Callable): A Python function that accepts an Fx graph with
747
+ Aten ops and input args, and returns a Callable that semantically is
748
+ equivalent to the input Fx graph.
749
+ bw_compiler (Optional[Callable]): A Python function that accepts an
750
+ Fx graph with Aten ops and input args, and returns a Callable that
751
+ semantically is equivalent to the input Fx graph. Default: None
752
+ (when None, it defaults to the :attr:`fw_compiler`)
753
+ partition_fn (Callable): A Python function that takes a joint forward
754
+ and backward graph, and partitions it into separate forward and
755
+ backward graphs.
756
+ decompositions (Dict): A dictionary to define the decomposition of
757
+ larger Aten ops into simpler or core Aten ops.
758
+ inference_compiler (Optional[Callable]): A Python function that accepts an
759
+ Fx graph with Aten ops and input args, and returns a Callable that
760
+ semantically is equivalent to the input Fx graph. inference_compiler is invoked
761
+ if no autograd is needed. Default: None
762
+ (when None, it defaults to the :attr:`fw_compiler`)
763
+ Returns:
764
+ Returns a ``Callable`` that retains the eager behavior of the original
765
+ :attr:`fn`, but with forward and backward graph compiled via
766
+ :attr:`fw_compile` and :attr:`bw_compile`.
767
+
768
+ A simple example usage of :func:`aot_function` is as follows. This example
769
+ will print the forward and backward graphs of the function ``fn``
770
+
771
+ >>> fn = lambda x: x.sin().cos()
772
+ >>> def print_compile_fn(fx_module, args):
773
+ >>> print(fx_module)
774
+ >>> return fx_module
775
+ >>> aot_fn = aot_function(fn, print_compile_fn)
776
+ >>> x = torch.randn(4, 5, requires_grad=True)
777
+ >>> aot_fn(x)
778
+ """
779
+
780
+ aot_config = AOTConfig(
781
+ fw_compiler=None,
782
+ bw_compiler=None,
783
+ inference_compiler=None,
784
+ partition_fn=None,
785
+ decompositions=decompositions,
786
+ num_params_buffers=num_params_buffers,
787
+ aot_id=next(AOT_COUNTER),
788
+ keep_inference_input_mutations=keep_inference_input_mutations,
789
+ dynamic_shapes=dynamic,
790
+ aot_autograd_arg_pos_to_source=None,
791
+ is_export=False,
792
+ no_tangents=False,
793
+ enable_log=enable_log,
794
+ disable_functionalization=disable_functionalization,
795
+ _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
796
+ )
797
+ cached_res = None
798
+
799
+ @wraps(fn)
800
+ def returned_function(*args: _P.args, **kwargs: _P.kwargs) -> Any:
801
+ nonlocal cached_res
802
+ # Now flatten the tensor args
803
+ flat_args = pytree.arg_tree_leaves(*args, **kwargs)
804
+
805
+ # Compile the function and save it in the cache
806
+ if cached_res is None:
807
+ flat_fn, out_spec = create_tree_flattened_fn(fn, args, kwargs)
808
+ (fake_mode, shape_env) = construct_fake_mode(flat_args, aot_config)
809
+ fake_flat_args: FakifiedFlatArgs
810
+ fake_flat_args, act_input_paths = process_inputs(
811
+ flat_args, aot_config, fake_mode, shape_env
812
+ )
813
+ # TODO: We actually could use the pytree path to make better descs.
814
+ # Also, the descs here are bad if you do aot_module.
815
+ fake_flat_args_descs: list[AOTInput] = [
816
+ PlainAOTInput(i) for i in range(len(fake_flat_args))
817
+ ]
818
+ with contextlib.ExitStack() as stack:
819
+ aot_state = create_aot_state(
820
+ stack,
821
+ flat_fn,
822
+ fake_flat_args,
823
+ fake_flat_args_descs,
824
+ aot_config,
825
+ fake_mode,
826
+ shape_env,
827
+ )
828
+ aot_state.fw_metadata.act_input_paths = act_input_paths
829
+ aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn)
830
+ compiled_fn, _ = aot_stage2_compile(
831
+ aot_state,
832
+ aot_graph_capture,
833
+ partition_fn,
834
+ fw_compiler,
835
+ bw_compiler,
836
+ inference_compiler,
837
+ )
838
+ cached_res = (compiled_fn, out_spec)
839
+
840
+ cached_fn, out_spec = cached_res
841
+ out = cached_fn(flat_args)
842
+ return out_spec.unflatten(out)
843
+
844
+ return returned_function
845
+
846
+
847
+ def aot_module(mod: nn.Module, *args: Any, **kwargs: Any) -> nn.Module:
848
+ """
849
+ Traces the forward and backward graph of :attr:`mod` using torch dispatch
850
+ tracing mechanism. It is wrapper function, that underneath uses
851
+ :func:`aot_function` to perform tracing and compilation.
852
+
853
+ :func:`aot_module` lifts the parameters and buffers of ``nn.Module`` as inputs
854
+ to a new callable which is then compiled through :func:`aot_function`.
855
+
856
+ .. warning::
857
+ This API is experimental and likely to change.
858
+
859
+ Args:
860
+ mod (Callable): A ``nn.Module`` module.
861
+ args : args to be passed to :func:`aot_function`
862
+ kwargs : kwargs to be passed to :func:`aot_function`
863
+
864
+ Returns:
865
+ Returns a ``nn.Module`` that retains the eager behavior of the original
866
+ :attr:`mod`, but with forward and backward graph compiled.
867
+
868
+ """
869
+ # See Note: [Fake Modules and AOTAutograd]
870
+ torch._dynamo.utils.assert_no_fake_params_or_buffers(mod)
871
+
872
+ def functional_call(
873
+ named_params: dict[str, torch.nn.Parameter],
874
+ named_buffers: dict[str, torch.Tensor],
875
+ *args: Any,
876
+ **kwargs: Any,
877
+ ) -> Any:
878
+ params_and_buffers = {**named_params, **named_buffers}
879
+ return torch.func.functional_call(mod, params_and_buffers, args, kwargs)
880
+
881
+ named_params = dict(mod.named_parameters(remove_duplicate=False))
882
+ named_buffers = dict(mod.named_buffers(remove_duplicate=False))
883
+ num_params_buffers = len(named_params) + len(named_buffers)
884
+ compiled_f = aot_function(
885
+ functional_call,
886
+ *args,
887
+ # pyrefly: ignore[bad-keyword-argument]
888
+ num_params_buffers=num_params_buffers,
889
+ **kwargs,
890
+ )
891
+
892
+ class AOTModule(nn.Module):
893
+ def __init__(self) -> None:
894
+ super().__init__()
895
+ self.orig_module = mod
896
+
897
+ def forward(self, *args: Any, **kwargs: Any) -> Any:
898
+ return compiled_f(
899
+ named_params,
900
+ named_buffers,
901
+ *args,
902
+ **kwargs,
903
+ )
904
+
905
+ return AOTModule()
906
+
907
+
908
+ def autograd_cache_key(
909
+ graph,
910
+ example_inputs,
911
+ ignore_shape_env: bool,
912
+ decompositions,
913
+ compiler_config_extra: CompilerConfigExtra,
914
+ keep_inference_input_mutations: bool = False,
915
+ disable_functionalization: bool = False,
916
+ ):
917
+ (
918
+ _params_buffers_flat,
919
+ _params_spec,
920
+ _buffers_spec,
921
+ full_args,
922
+ _full_args_descs,
923
+ aot_config,
924
+ ) = prepare_aot_config(
925
+ graph,
926
+ example_inputs,
927
+ decompositions,
928
+ keep_inference_input_mutations,
929
+ ignore_shape_env,
930
+ force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering,
931
+ disable_functionalization=disable_functionalization,
932
+ )
933
+
934
+ fake_mode, shape_env = construct_fake_mode(full_args, aot_config)
935
+ fake_flat_args, act_input_paths = process_inputs(
936
+ full_args, aot_config, fake_mode, shape_env, ignore_shape_env
937
+ )
938
+
939
+ return autograd_cache.autograd_cache_key(
940
+ graph, fake_flat_args, aot_config, compiler_config_extra, act_input_paths
941
+ )
942
+
943
+
944
+ def prepare_aot_config(
945
+ mod: nn.Module,
946
+ args: Iterable[Any],
947
+ decompositions: dict[OpOverload, Callable[..., Any]] | None,
948
+ keep_inference_input_mutations: bool,
949
+ ignore_shape_env: bool,
950
+ *,
951
+ force_non_lazy_backward_lowering: bool = False,
952
+ disable_functionalization: bool = False,
953
+ _disable_torch_fn_metadata_mode: bool = False,
954
+ ) -> tuple[
955
+ list[torch.nn.Parameter | Tensor],
956
+ list[str],
957
+ list[str],
958
+ list[Any],
959
+ list[Any],
960
+ AOTConfig,
961
+ ]:
962
+ # TODO: There's something a bit suspicious here; typically simplified
963
+ # module shouldn't actually have any parameters...
964
+ params = dict(mod.named_parameters(remove_duplicate=False))
965
+ buffers = dict(dict(mod.named_buffers(remove_duplicate=False)))
966
+
967
+ params_flat, params_spec = list(params.values()), list(params.keys())
968
+ params_len = len(params_flat)
969
+
970
+ buffers_flat, buffers_spec = list(buffers.values()), list(buffers.keys())
971
+ buffers_len = len(buffers_flat)
972
+
973
+ params_buffers = {**params, **buffers}
974
+ params_buffers_flat = params_flat + buffers_flat
975
+
976
+ full_args = [*params_flat, *buffers_flat, *args]
977
+
978
+ # OK, set up the descs
979
+
980
+ full_args_descs: list[DifferentiableAOTInput] = []
981
+ full_args_descs.extend(ParamAOTInput(fqn) for fqn in params_spec)
982
+ full_args_descs.extend(BufferAOTInput(fqn) for fqn in buffers_spec)
983
+
984
+ # TODO: These tracing_context fields should become unnecessary once we
985
+ # always maintain sources on all arguments
986
+ if tracing_context := torch._guards.TracingContext.try_get():
987
+ # NB: TracingContext misnames this, the "params" here also contains
988
+ # buffers
989
+ tracing_context.params_flat = params_buffers_flat
990
+ (
991
+ tracing_context.params_flat_unwrap_subclasses,
992
+ tracing_context.params_unwrapped_to_flat_index,
993
+ ) = unwrap_tensor_subclasses_with_indices_to_original(params_buffers_flat)
994
+
995
+ # TODO: Might be nice to hold on to the Dynamo source here in full_args_descs!
996
+ (
997
+ aot_autograd_arg_pos_to_source,
998
+ static_input_indices,
999
+ ) = _try_get_metadata_from_dynamo(
1000
+ mod, params_buffers.keys(), len(full_args), full_args_descs
1001
+ )
1002
+
1003
+ dynamic_shapes = False
1004
+ for x in full_args:
1005
+ fake_mode = maybe_get_fake_mode(x)
1006
+ if fake_mode is not None:
1007
+ dynamic_shapes = fake_mode.shape_env is not None
1008
+ break
1009
+
1010
+ aot_config = AOTConfig(
1011
+ fw_compiler=None,
1012
+ bw_compiler=None,
1013
+ inference_compiler=None,
1014
+ partition_fn=None,
1015
+ decompositions=decompositions,
1016
+ num_params_buffers=params_len + buffers_len,
1017
+ aot_id=next(AOT_COUNTER),
1018
+ keep_inference_input_mutations=keep_inference_input_mutations,
1019
+ dynamic_shapes=dynamic_shapes,
1020
+ # pyrefly: ignore[bad-argument-type]
1021
+ aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source,
1022
+ static_input_indices=static_input_indices,
1023
+ is_export=False,
1024
+ no_tangents=False,
1025
+ cache_info=None,
1026
+ ignore_shape_env=ignore_shape_env,
1027
+ precompile_backend_id=getattr(mod, "_backend_id", None),
1028
+ force_non_lazy_backward_lowering=force_non_lazy_backward_lowering,
1029
+ disable_functionalization=disable_functionalization,
1030
+ _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
1031
+ )
1032
+
1033
+ return (
1034
+ params_buffers_flat,
1035
+ params_spec,
1036
+ buffers_spec,
1037
+ full_args,
1038
+ full_args_descs,
1039
+ aot_config,
1040
+ )
1041
+
1042
+
1043
+ def prepare_aot_module_simplified(
1044
+ mod: nn.Module,
1045
+ args: Iterable[Any],
1046
+ kwargs: dict[str, Any] | None,
1047
+ decompositions: dict[OpOverload, Callable[..., Any]] | None,
1048
+ keep_inference_input_mutations: bool,
1049
+ ignore_shape_env: bool,
1050
+ flatten: bool,
1051
+ *,
1052
+ force_non_lazy_backward_lowering: bool = False,
1053
+ disable_functionalization: bool = False,
1054
+ _record_nn_module_stack: bool = False,
1055
+ _disable_torch_fn_metadata_mode: bool = False,
1056
+ ) -> tuple[
1057
+ Any,
1058
+ list[torch.nn.Parameter | Tensor],
1059
+ list[str],
1060
+ list[str],
1061
+ FakifiedFlatArgs,
1062
+ list[Any],
1063
+ AOTConfig,
1064
+ FakeTensorMode,
1065
+ ShapeEnv | None,
1066
+ pytree.TreeSpec | None,
1067
+ PytreeThunk | None,
1068
+ list[ActInputPath],
1069
+ ]:
1070
+ if not flatten:
1071
+ if kwargs is not None:
1072
+ raise AssertionError("kwargs must be None when flatten=False")
1073
+ elif kwargs is None:
1074
+ kwargs = {}
1075
+
1076
+ (
1077
+ params_buffers_flat,
1078
+ params_spec,
1079
+ buffers_spec,
1080
+ full_args,
1081
+ full_args_descs,
1082
+ aot_config,
1083
+ ) = prepare_aot_config(
1084
+ mod,
1085
+ args,
1086
+ decompositions,
1087
+ keep_inference_input_mutations,
1088
+ ignore_shape_env,
1089
+ force_non_lazy_backward_lowering=force_non_lazy_backward_lowering,
1090
+ disable_functionalization=disable_functionalization,
1091
+ _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
1092
+ )
1093
+
1094
+ params_buffers_spec = params_spec + buffers_spec
1095
+
1096
+ # NB: This doesn't change the in/out convention, except adding the
1097
+ # parameters as explicit arguments
1098
+ functional_call = create_functional_call(
1099
+ mod,
1100
+ params_buffers_spec,
1101
+ aot_config.num_params_buffers,
1102
+ strict_out_tuple=not flatten,
1103
+ # We need this for export to run ModuleStackTracer
1104
+ # instead of PythonKeyTracer
1105
+ store_orig_mod=_record_nn_module_stack,
1106
+ )
1107
+
1108
+ in_spec, out_spec = None, None
1109
+ if flatten:
1110
+ functional_call, out_spec = create_tree_flattened_fn(
1111
+ functional_call, full_args, kwargs
1112
+ )
1113
+ full_args, in_spec = pytree.tree_flatten((full_args, kwargs))
1114
+
1115
+ # TODO: it would be better to put pytree information in here
1116
+ full_args_descs.extend(
1117
+ PlainAOTInput(i) for i in range(len(full_args) - len(full_args_descs))
1118
+ )
1119
+
1120
+ fake_mode, shape_env = construct_fake_mode(full_args, aot_config)
1121
+ # NB: full_args_descs not needed here, fake_flat_args is 1:1 with full_args
1122
+ fake_flat_args, act_input_paths = process_inputs(
1123
+ full_args, aot_config, fake_mode, shape_env, ignore_shape_env
1124
+ )
1125
+
1126
+ return (
1127
+ functional_call,
1128
+ params_buffers_flat,
1129
+ params_spec,
1130
+ buffers_spec,
1131
+ fake_flat_args,
1132
+ full_args_descs,
1133
+ aot_config,
1134
+ fake_mode,
1135
+ shape_env,
1136
+ in_spec,
1137
+ out_spec,
1138
+ act_input_paths,
1139
+ )
1140
+
1141
+
1142
+ def aot_module_simplified(
1143
+ mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper,
1144
+ args: Sequence[Any],
1145
+ fw_compiler: AOTDispatchCompiler,
1146
+ bw_compiler: AOTDispatchCompiler | None = None,
1147
+ partition_fn: Callable[..., Any] = default_partition,
1148
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
1149
+ keep_inference_input_mutations: bool = False,
1150
+ inference_compiler: AOTDispatchCompiler | None = None,
1151
+ # TODO: This doesn't seem to be used in any nontrivial way, check if it's
1152
+ # actually needed
1153
+ compiler_config_extra: CompilerConfigExtra | None = None,
1154
+ ignore_shape_env: bool = False,
1155
+ disable_functionalization: bool = False,
1156
+ # Optional callback to run passes on the module at the start of AOT autograd.
1157
+ pre_grad_passes: Callable[
1158
+ [torch.fx.GraphModule, Sequence[InputType]], torch.fx.GraphModule
1159
+ ]
1160
+ | None = None,
1161
+ compile_region_name: str | None = None,
1162
+ ) -> Callable[..., Any]:
1163
+ """
1164
+ This is the simplified or low overhead version of aot_module. For frontends
1165
+ like TorchDynamo, the input functions/modules to AOT are static and have
1166
+ unpacked inputs/outputs. This gives us an opportunity to remove the
1167
+ (1) pytree overhead to parse inputs/outputs,
1168
+ (2) AOT Autograd cache,
1169
+ (3) Reading of params/buffers in every forward call
1170
+
1171
+ :func:`aot_module_simplified` removes these overheads.
1172
+ """
1173
+
1174
+ pre_grad_pass_timing: Literal["early", "late"] = resolve_pre_grad_pass_timing()
1175
+
1176
+ if (
1177
+ pre_grad_pass_timing == "early"
1178
+ and pre_grad_passes
1179
+ and isinstance(mod, torch.fx.GraphModule)
1180
+ ):
1181
+ mod = pre_grad_passes(mod, args)
1182
+
1183
+ with contextlib.ExitStack() as stack:
1184
+ (
1185
+ functional_call,
1186
+ params_buffers_flat,
1187
+ _params_spec,
1188
+ _buffers_spec,
1189
+ fake_flat_args,
1190
+ full_args_descs,
1191
+ aot_config,
1192
+ fake_mode,
1193
+ shape_env,
1194
+ _in_spec,
1195
+ _out_spec,
1196
+ act_input_paths,
1197
+ ) = prepare_aot_module_simplified(
1198
+ mod,
1199
+ args,
1200
+ None,
1201
+ decompositions,
1202
+ keep_inference_input_mutations,
1203
+ ignore_shape_env,
1204
+ flatten=False,
1205
+ force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering,
1206
+ disable_functionalization=disable_functionalization,
1207
+ )
1208
+
1209
+ compiled_fn = None
1210
+
1211
+ if (
1212
+ isinstance(fw_compiler, SerializableAOTDispatchCompiler)
1213
+ or torch._functorch.config.force_autograd_cache
1214
+ ):
1215
+ local = should_use_local_autograd_cache()
1216
+ remote = should_use_remote_autograd_cache()
1217
+ if local or remote:
1218
+ set_feature_use("aot_autograd_remote_cache", remote)
1219
+ compiled_fn, aot_config = AOTAutogradCache.try_load(
1220
+ mod,
1221
+ fake_flat_args,
1222
+ aot_config,
1223
+ compiler_config_extra,
1224
+ local,
1225
+ remote,
1226
+ act_input_paths,
1227
+ compile_region_name=compile_region_name,
1228
+ )
1229
+
1230
+ if compiled_fn is None:
1231
+ if (
1232
+ pre_grad_pass_timing == "late"
1233
+ and pre_grad_passes
1234
+ and isinstance(mod, torch.fx.GraphModule)
1235
+ ):
1236
+ mod = pre_grad_passes(mod, args)
1237
+
1238
+ stack.enter_context(compiled_autograd._disable())
1239
+ aot_state = create_aot_state(
1240
+ stack,
1241
+ functional_call,
1242
+ fake_flat_args,
1243
+ full_args_descs,
1244
+ aot_config,
1245
+ fake_mode,
1246
+ shape_env,
1247
+ )
1248
+ aot_state.fw_metadata.act_input_paths = act_input_paths
1249
+ aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call)
1250
+ compiled_fn, _ = aot_stage2_compile(
1251
+ aot_state,
1252
+ aot_graph_capture,
1253
+ partition_fn,
1254
+ fw_compiler,
1255
+ bw_compiler,
1256
+ inference_compiler,
1257
+ )
1258
+ if compiled_fn is None:
1259
+ raise AssertionError("compiled_fn must not be None")
1260
+ if isinstance(mod, torch._dynamo.utils.GmWrapper):
1261
+ # This function is called by the flatten_graph_inputs wrapper, which boxes
1262
+ # the inputs so that they can be freed before the end of this scope.
1263
+ # For overhead reasons, this is not the default wrapper, see comment:
1264
+ # https://github.com/pytorch/pytorch/pull/122535/files#r1560096481
1265
+ @simple_wraps(compiled_fn)
1266
+ def forward(runtime_args: list[Any]) -> Any:
1267
+ flat_args = []
1268
+ flat_args.extend(params_buffers_flat)
1269
+ flat_args.extend(runtime_args)
1270
+ runtime_args.clear()
1271
+ if compiled_fn is None:
1272
+ raise AssertionError("compiled_fn must not be None")
1273
+ return compiled_fn(flat_args)
1274
+
1275
+ else:
1276
+ # TODO: There is something deeply wrong here; compiled_fn running with
1277
+ # the boxed calling convention, but aot_module_simplified somehow
1278
+ # historically returned a function that was not the boxed calling
1279
+ # convention. This should get fixed...
1280
+ # NB: GraphModule/nn.Module rely on the non-boxed calling convention here
1281
+ @simple_wraps(compiled_fn)
1282
+ def forward(*runtime_args: tuple[Any]) -> Any:
1283
+ full_args = []
1284
+ full_args.extend(params_buffers_flat)
1285
+ # pyrefly: ignore[bad-argument-type]
1286
+ full_args.extend(runtime_args)
1287
+ if compiled_fn is None:
1288
+ raise AssertionError("compiled_fn must not be None")
1289
+ return compiled_fn(full_args)
1290
+
1291
+ # Just for convenience
1292
+ forward.zero_grad = mod.zero_grad # type: ignore[attr-defined]
1293
+ forward.named_parameters = mod.named_parameters # type: ignore[attr-defined]
1294
+ forward.named_buffers = mod.named_buffers # type: ignore[attr-defined]
1295
+
1296
+ # Add a serialize function
1297
+ def grab_serialize_fn(fn: Any) -> Callable[..., Any] | None:
1298
+ if isinstance(fn, SerializableCompiledFunction):
1299
+ return fn.serialize_fn
1300
+ elif hasattr(fn, "__wrapped__"):
1301
+ return grab_serialize_fn(fn.__wrapped__)
1302
+ else:
1303
+ return None
1304
+
1305
+ forward.serialize = grab_serialize_fn(forward) # type: ignore[attr-defined]
1306
+ return forward
1307
+
1308
+
1309
+ def boxed_nop_preserve_node_meta(
1310
+ gm: torch.fx.GraphModule, example_inputs: Sequence[InputType]
1311
+ ) -> Any:
1312
+ def run(args: list[Any]) -> OutputCode:
1313
+ with torch.fx.traceback.preserve_node_meta():
1314
+ return torch.fx.Interpreter(gm).boxed_run(args)
1315
+
1316
+ run._boxed_call = True # type: ignore[attr-defined]
1317
+ return run
1318
+
1319
+
1320
+ def aot_export_joint_with_descriptors(
1321
+ stack: contextlib.ExitStack,
1322
+ mod: nn.Module,
1323
+ args: tuple[Any, ...],
1324
+ kwargs: dict[str, Any] | None = None,
1325
+ *,
1326
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
1327
+ keep_inference_input_mutations: bool = False,
1328
+ ignore_shape_env: bool = False,
1329
+ disable_functionalization: bool = False,
1330
+ _record_nn_module_stack: bool = False,
1331
+ _disable_torch_fn_metadata_mode: bool = False,
1332
+ ) -> JointWithDescriptors:
1333
+ """
1334
+ This API captures the joint graph for an nn.Module. However, unlike
1335
+ aot_export_joint_simple or aot_export_module(trace_joint=True), the
1336
+ calling convention of the produced joint graph follows no fixed positional
1337
+ schema; for example, you cannot rely on the second argument of the traced
1338
+ joint graph to correspond to the second argument of the module you traced.
1339
+ However, the inputs and outputs of the traced graph are schematized
1340
+ with **descriptors**, annotated on meta['desc'] on the placeholder and
1341
+ return FX nodes, which you can use to determine the meaning of arguments.
1342
+
1343
+ The major benefit of using this export rather than aot_export_joint_simple
1344
+ is that we have feature parity with all situations that torch.compile
1345
+ supports (via aot_module_simplified), including handling for more
1346
+ complicated cases such as multiple differentiable outputs, input mutations
1347
+ that must be handled outside of the graph, tensor subclasses, etc.
1348
+
1349
+ What can you do with one of these joint graphs with descriptors? The
1350
+ motivating use case (autoparallel) involves taking the joint graph, doing
1351
+ optimizations on it, and then turning it back into a callable so it can be
1352
+ torch.compile'd at a later point in time. This cannot be done as a
1353
+ traditional torch.compile joint graph pass for two reasons:
1354
+
1355
+ 1. The sharding of parameters must be decided before parameter
1356
+ initialization / checkpoint load, far before torch.compile would
1357
+ ordinarily run.
1358
+
1359
+ 2. We need to change the meaning of parameters (e.g., we might replace
1360
+ a replicated parameter with a sharded version of it, changing its
1361
+ input size). torch.compile is ordinarily semantics preserving, and
1362
+ not allowed to change the meaning of inputs.
1363
+
1364
+ Some descriptors can be quite exotic, so we recommend thinking carefully
1365
+ if there is a safe fallback you can apply to descriptors you don't understand.
1366
+ For example, you should have some way to handle not finding a particular
1367
+ input exactly as is in the final FX graph inputs.
1368
+
1369
+ Note: When using this API, you must create and enter an ExitStack context
1370
+ manager, which will be passed into this function. This context manager
1371
+ must remain active if you call the compile function to finish compilation.
1372
+ (TODO: We may relax this requirement by having AOTAutograd keep track of
1373
+ how to reconstruct all the context managers at a later point in time.)
1374
+
1375
+ NB: You're not obligated to do a /full/ compile in stage2; instead you can
1376
+ leave the forward/backward compilers unspecified in which case the
1377
+ partitioned FX graphs will directly run. The overall autograd Function
1378
+ can be allowed in graph so you can reprocess it in the context of a
1379
+ (potentially larger) compiled region later.
1380
+
1381
+ NB: These APIs do NOT hit cache, as we only ever cache the final compile results,
1382
+ not the intermediate export result.
1383
+
1384
+ NB: If the passed nn.Module has parameters and buffers on it, we will
1385
+ generate extra implicit parameter/buffer arguments and assign ParamAOTInput
1386
+ and BufferAOTInput descriptors to them. However, if you generate the input
1387
+ nn.Module from a mechanism like Dynamo, you will NOT get these descriptors
1388
+ (because Dynamo will already have taken care of lifting the parameters/buffers
1389
+ into arguments!) In that case, it would be necessary to analyze the Sources
1390
+ of the inputs to determine if inputs are parameters and their FQNs.
1391
+ """
1392
+
1393
+ (
1394
+ functional_call,
1395
+ _params_buffers_flat,
1396
+ params_spec,
1397
+ buffers_spec,
1398
+ fake_flat_args,
1399
+ full_args_descs,
1400
+ aot_config,
1401
+ fake_mode,
1402
+ shape_env,
1403
+ in_spec,
1404
+ out_spec,
1405
+ act_input_paths,
1406
+ ) = prepare_aot_module_simplified(
1407
+ mod,
1408
+ args,
1409
+ kwargs,
1410
+ # In contrast, decompositions are needed at this stage.
1411
+ decompositions,
1412
+ keep_inference_input_mutations,
1413
+ ignore_shape_env,
1414
+ flatten=True,
1415
+ # Without this, we will attempt to "compile" the backward lazily
1416
+ # at runtime, but this is pointless because it's just boxed_nop,
1417
+ # it's trivial. But this will get Inductor confused about scoping
1418
+ # Metric(s) {'is_forward'} have already been set in the current
1419
+ # context.
1420
+ force_non_lazy_backward_lowering=True,
1421
+ disable_functionalization=disable_functionalization,
1422
+ _record_nn_module_stack=_record_nn_module_stack,
1423
+ _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode,
1424
+ )
1425
+
1426
+ # TODO: Maybe this should be in create_aot_state? Not sure, that would
1427
+ # increase its scope
1428
+ stack.enter_context(compiled_autograd._disable())
1429
+
1430
+ aot_state = create_aot_state(
1431
+ stack,
1432
+ functional_call,
1433
+ fake_flat_args,
1434
+ full_args_descs,
1435
+ aot_config,
1436
+ fake_mode,
1437
+ shape_env,
1438
+ )
1439
+ aot_state.fw_metadata.act_input_paths = act_input_paths
1440
+
1441
+ # NB: no cache lookup!
1442
+ aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call)
1443
+
1444
+ if out_spec is None or out_spec.spec is None:
1445
+ raise AssertionError("out_spec and out_spec.spec must not be None")
1446
+ if in_spec is None:
1447
+ raise AssertionError("in_spec must not be None")
1448
+ return JointWithDescriptors(
1449
+ _aot_state=aot_state,
1450
+ _aot_graph_capture=aot_graph_capture,
1451
+ params_spec=params_spec,
1452
+ buffers_spec=buffers_spec,
1453
+ in_spec=in_spec,
1454
+ out_spec=out_spec.spec,
1455
+ )
1456
+
1457
+
1458
+ def aot_compile_joint_with_descriptors(
1459
+ jd: JointWithDescriptors,
1460
+ *,
1461
+ partition_fn: Callable[..., Any] = default_partition,
1462
+ fw_compiler: AOTDispatchCompiler = boxed_nop_preserve_node_meta,
1463
+ bw_compiler: AOTDispatchCompiler | None = boxed_nop_preserve_node_meta,
1464
+ serializable: bool = False,
1465
+ ) -> Callable[..., Any]:
1466
+ """
1467
+ Companion function for aot_export_joint_with_descriptors which compiles the joint
1468
+ graph into a callable function that follows a standard calling convention.
1469
+ params_flat all are arguments.
1470
+
1471
+ Note: We do NOT instantiate the module; this gives you the flexibility to subclass it and
1472
+ customize its behavior without having to worry about FQN rebinding.
1473
+
1474
+ Args:
1475
+ serializable: If True, configures the compilation to produce a serializable
1476
+ callable by leveraging AOTAutogradCache machinery. This sets up the
1477
+ necessary cache_info and patches config options required for serialization.
1478
+ When True, this function will always return a BundledAOTAutogradSerializableCallable.
1479
+ """
1480
+ # TODO: Consider if we should allow_in_graph the result by default.
1481
+ from torch._dynamo.aot_compile_types import (
1482
+ BundledAOTAutogradSerializableCallable,
1483
+ SerializableCallable,
1484
+ )
1485
+ from torch._functorch._aot_autograd.schemas import AOTAutogradCacheInfo
1486
+ from torch._guards import detect_fake_mode
1487
+ from torch._inductor.output_code import OutputCode
1488
+
1489
+ fw_compiler = SerializableAOTDispatchCompiler(OutputCode, fw_compiler)
1490
+
1491
+ cache_ctx = nullcontext()
1492
+ if serializable:
1493
+ jd._aot_state.aot_config = dataclasses.replace(
1494
+ jd._aot_state.aot_config,
1495
+ cache_info=AOTAutogradCacheInfo(
1496
+ jd.cache_hash(),
1497
+ time.time_ns(),
1498
+ forward_symints=[],
1499
+ ),
1500
+ )
1501
+ cache_ctx = torch._functorch.config.patch(
1502
+ {
1503
+ "strict_autograd_cache": True,
1504
+ "bundled_autograd_cache": True,
1505
+ "force_non_lazy_backward_lowering": True,
1506
+ "bypass_autograd_cache_key": True,
1507
+ }
1508
+ )
1509
+
1510
+ # Set up a TracingContext if one isn't already available.
1511
+ # This is needed for compilers (like regional_inductor) that call
1512
+ # standalone_compile with dynamic_shapes="from_tracing_context".
1513
+ tracing_context = torch._guards.TracingContext.try_get()
1514
+ if tracing_context is None:
1515
+ fake_mode = detect_fake_mode(jd._aot_state.flat_args)
1516
+ if fake_mode is not None:
1517
+ tracing_context = torch._guards.TracingContext(fake_mode)
1518
+ tracing_ctx = torch._guards.tracing(tracing_context)
1519
+ else:
1520
+ tracing_ctx = nullcontext()
1521
+ else:
1522
+ tracing_ctx = nullcontext()
1523
+
1524
+ with cache_ctx, tracing_ctx:
1525
+ compiled_fn, _ = aot_stage2_compile(
1526
+ jd._aot_state,
1527
+ jd._aot_graph_capture,
1528
+ partition_fn,
1529
+ fw_compiler,
1530
+ bw_compiler,
1531
+ )
1532
+
1533
+ if not isinstance(compiled_fn, SerializableCallable) and hasattr(
1534
+ compiled_fn, "serialize"
1535
+ ):
1536
+ compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn)
1537
+
1538
+ # Cribbed from torch/export/pt2_archive/_package.py
1539
+ @simple_wraps(compiled_fn)
1540
+ @torch._dynamo.nonstrict_trace # allow recursive compilation
1541
+ def unflattened_compiled_fn(*args: Any, **kwargs: Any) -> Any:
1542
+ flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, jd.in_spec)))[0]
1543
+ # TODO: do I need to filter? I hope not!
1544
+ flat_outputs = compiled_fn(flat_inputs)
1545
+ return pytree.tree_unflatten(flat_outputs, jd.out_spec)
1546
+
1547
+ return unflattened_compiled_fn
1548
+
1549
+
1550
+ def aot_export_module(
1551
+ mod: nn.Module,
1552
+ args: Iterable[Any],
1553
+ *,
1554
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
1555
+ # If true, we'll return a joint forward-backward graph,
1556
+ # As well as metadata on the loss + gradients in the backward.
1557
+ trace_joint: bool,
1558
+ # If trace_joint is True, we expect your module to return a scalar loss.
1559
+ # Your module can return multiple outputs, so you must specify which output the loss is.
1560
+ output_loss_index: int | None = None,
1561
+ pre_dispatch: bool = False,
1562
+ # If None, will be inferred from inputs and mod.graph.nodes if mod is a graph module, but the inferred result might be wrong.
1563
+ dynamic_shapes: bool | None = None,
1564
+ kwargs: dict[str, Any] | None = None,
1565
+ ) -> tuple[Callable[..., Any] | torch.fx.GraphModule, GraphSignature]:
1566
+ """
1567
+ This function takes in a module, and returns:
1568
+ (1) an FX graph that can be exported
1569
+ (2) some metadata about the graph
1570
+
1571
+ If `trace_joint=True` we will return a joint graph of the forward + backward.
1572
+
1573
+ The traced FX graph will have the following properties compared to the original module:
1574
+ (1) Inputs and outputs to the module will be pytree-flattened
1575
+ (2) Parameters and buffers on the module will be lifted into graph inputs,
1576
+ graph_inputs = (*parameters, *buffers, *user_inputs)
1577
+ (3) The graph will be fully functionalized
1578
+ (4) Any input mutations will be converted into additional outputs in the graph,
1579
+ meaning whoever calls this graph is responsible for applying the mutations
1580
+ back to the original inputs.
1581
+ (5) If is_joint is provided the graph will return parameter gradients in addition to user outputs.
1582
+ The graph output will look like:
1583
+ graph_outputs = (*updated_inputs, *user_outputs, *param_gradients)
1584
+
1585
+ There are also several restrictions on what modules can use this API. In particular:
1586
+ (1) If trace_joint is specified, we expect the loss function to be **fused**
1587
+ into the module forward. One of the outputs to the forward must be a scalar loss,
1588
+ which is specified with `output_loss_index`.
1589
+ All other outputs to the forward are presumed to not require gradients.
1590
+ (2) This API cannot capture optimizers (although in theory we could build an API for this).
1591
+ (3) Metadata mutations on params/buffers/inputs are banned.
1592
+ (4) Data mutations on anything that requires gradients are banned (parameters)
1593
+ (5) If an input is mutated, it is not allowed to alias any other inputs.
1594
+ (6) Parameters must not be duplicated.
1595
+ """
1596
+ if pre_dispatch and trace_joint:
1597
+ raise RuntimeError("pre_dispatch is not supported when trace_joint is True.")
1598
+ named_parameters = dict(mod.named_parameters(remove_duplicate=False))
1599
+ named_buffers = dict(mod.named_buffers(remove_duplicate=False))
1600
+
1601
+ params_and_buffers = {
1602
+ **dict(named_parameters),
1603
+ **dict(named_buffers),
1604
+ }
1605
+ params_and_buffers_flat, params_spec = pytree.tree_flatten(params_and_buffers)
1606
+ params_and_buffers_flat = tuple(params_and_buffers_flat)
1607
+ params_len = len(params_and_buffers_flat)
1608
+
1609
+ kwargs = kwargs or {}
1610
+
1611
+ functional_call = create_functional_call(
1612
+ mod, params_spec, params_len, store_orig_mod=True
1613
+ )
1614
+
1615
+ num_fw_outs = None
1616
+
1617
+ if trace_joint:
1618
+ # This helper effectively just adds some extra asserts about what the backward will look like:
1619
+ # Outputs must include a scalar loss, that we compute gradients w.r.t.
1620
+ # We don't compute gradients w.r.t. anything else: so just in case we detach()
1621
+ # and other output tensors.
1622
+ def fn_to_trace(*args: Any) -> Any:
1623
+ nonlocal num_fw_outs
1624
+ out = functional_call(*args)
1625
+ if output_loss_index is None:
1626
+ raise RuntimeError(
1627
+ """\
1628
+ If trace_joint=Trueit is required that one of your forward outputs must be a scalar loss.
1629
+ You must specify the which (index) output is the loss with output_loss_index."""
1630
+ )
1631
+ if isinstance(out, (torch.Tensor)):
1632
+ out = (out,)
1633
+ if not isinstance(out, (tuple, list)):
1634
+ raise RuntimeError(
1635
+ f"Expected forward output to be either a tensor or a list/tuple of tensors. found {type(out)}"
1636
+ )
1637
+
1638
+ for i, o in enumerate(out):
1639
+ # We only want to create a backward graph w.r.t. the loss that the user passed in.
1640
+ # This implies that every other output should not require gradients.
1641
+ # Instead of making this an error (and forcing the user to detach all other outputs
1642
+ # of their forward),
1643
+ # we'll automatically detach them here.
1644
+ if o.requires_grad and i != output_loss_index:
1645
+ raise RuntimeError(
1646
+ f"""\
1647
+ Found an output of the forward that requires gradients, that was not the scalar loss.
1648
+ We require all outputs to the forward that are not the scalar loss to not require gradient,
1649
+ because we will only compute a backward graph against the scalar loss.
1650
+ You can fix this by calling .detach() on each of your forward outputs that is not the loss.
1651
+ You specified that output index {output_loss_index} is the loss, but we found that
1652
+ the output at index {i} requires gradients."""
1653
+ )
1654
+ out_loss = out[output_loss_index]
1655
+ num_fw_outs = len(out)
1656
+ if not out_loss.requires_grad:
1657
+ raise RuntimeError(
1658
+ f"""\
1659
+ The output at index {output_loss_index} was marked as the loss, but it does not require gradients"""
1660
+ )
1661
+ if out_loss.numel() != 1:
1662
+ raise RuntimeError(
1663
+ f"""\
1664
+ We require the output marked as the loss (at index {output_loss_index}) to be a scalar, but it has shape {out_loss.shape}"""
1665
+ )
1666
+ return out
1667
+
1668
+ ctx = nullcontext
1669
+ else:
1670
+ # Run under no_grad, so our tracing machinery only traces an inference graph.
1671
+ # However if pre_dispatch=True, we want to correctly trace set_grad_enabled calls for training.
1672
+ ctx = nullcontext if pre_dispatch else torch.no_grad
1673
+ fn_to_trace = functional_call
1674
+
1675
+ full_args = []
1676
+ # First, the params
1677
+ # NB: It is REQUIRED that parameters come first, Inductor infers "fixed"
1678
+ # parameters by looking at the difference in parameter count outside
1679
+ # and inside AOTAutograd, and assumes the prefix of arguments are fixed
1680
+ # arguments
1681
+ full_args.extend(params_and_buffers_flat)
1682
+ # Next, the input args
1683
+ full_args.extend(args)
1684
+
1685
+ with ctx():
1686
+ fx_g, metadata, in_spec, out_spec = _aot_export_function(
1687
+ fn_to_trace,
1688
+ tuple(full_args),
1689
+ decompositions=decompositions,
1690
+ num_params_buffers=params_len,
1691
+ no_tangents=True,
1692
+ pre_dispatch=pre_dispatch,
1693
+ dynamic_shapes=dynamic_shapes,
1694
+ trace_joint=trace_joint,
1695
+ kwargs=kwargs,
1696
+ )
1697
+
1698
+ # TODO: subsume this path with the aot_stage2_graph_capture path
1699
+ if trace_joint:
1700
+
1701
+ @wraps(functional_call)
1702
+ def flattened_joint(*args: Any) -> Any:
1703
+ # The idea here is that the joint graph that AOTAutograd creates has some strict properties:
1704
+ # (1) It accepts two arguments (primals, tangents), and pytree_flattens them
1705
+ # (2) It returns a tuple of (fw_outs, gradients)
1706
+ # This is a very useful convention for anyone who wants to partition the joint graph
1707
+ # into a separate forward and backward graph.
1708
+ # However,
1709
+ # (1) for people exporting a single joint graph, it would be preferable not to have
1710
+ # any pytrees in the graph.
1711
+ # (2) We are guaranteed in the aot_export_module case that the forward outputs a loss,
1712
+ # and there are therefore no tangents that are needed to run the joint graph.
1713
+ # (3) AOTAutograd creates a grad_input for every input in the forward,
1714
+ # including None's for inputs that are not grad-requiring tensors.
1715
+ # we don't want these in our export graph.
1716
+ # and there are therefore no tangents that are needed to run the joint graph.
1717
+ # This function "fixes" both of the above by removing any tangent inputs,
1718
+ # and removing pytrees from the original FX graph.
1719
+ fake_tangents = [
1720
+ None
1721
+ for _ in range(
1722
+ metadata.num_outputs + metadata.num_mutated_inp_runtime_indices
1723
+ )
1724
+ ]
1725
+ fw_outs, gradients = fx_g(args, fake_tangents)
1726
+ if len(gradients) != len(args):
1727
+ raise AssertionError(
1728
+ f"len(gradients)={len(gradients)} != len(args)={len(args)}"
1729
+ )
1730
+ output_gradients = []
1731
+ for a, grad in zip(args, gradients):
1732
+ if isinstance(a, torch.Tensor) and a.requires_grad:
1733
+ if grad is None:
1734
+ raise AssertionError("""\
1735
+ Found a parameter that did not receive a gradient.
1736
+ "This is most likely a bug, but if this needs to be supported please comment on this Github issue:
1737
+ https://github.com/pytorch/pytorch/issues/101192
1738
+ """)
1739
+ output_gradients.append(grad)
1740
+ else:
1741
+ if grad is not None:
1742
+ raise AssertionError(
1743
+ f"expected grad to be None for non-tensor or non-requires_grad input, got {type(grad)}"
1744
+ )
1745
+ return *fw_outs, *output_gradients
1746
+
1747
+ fx_g = make_fx(flattened_joint, record_module_stack=True)(*full_args)
1748
+
1749
+ user_args_flat = pytree.arg_tree_leaves(*args, **kwargs)
1750
+ if out_spec is None:
1751
+ raise AssertionError("out_spec must not be None")
1752
+ return fx_g, create_graph_signature(
1753
+ # type: ignore[bad-argument-type]
1754
+ fx_g,
1755
+ metadata,
1756
+ in_spec,
1757
+ out_spec,
1758
+ user_args_flat=user_args_flat,
1759
+ params_and_buffers_flat=list(params_and_buffers_flat),
1760
+ param_names=list(named_parameters.keys()),
1761
+ buffer_names=list(named_buffers.keys()),
1762
+ trace_joint=trace_joint,
1763
+ num_user_fw_outs=num_fw_outs,
1764
+ loss_index=output_loss_index,
1765
+ )
1766
+
1767
+
1768
+ def aot_export_joint_simple(
1769
+ func: Callable[..., Any],
1770
+ args: tuple[Any, ...],
1771
+ *,
1772
+ trace_joint: bool,
1773
+ # It looks like the main consequence of this API is that for dynamic shapes,
1774
+ # it will assume that params/buffers are static.
1775
+ # With the new inferred dynamic shapes API, maybe this doesn't matter?
1776
+ num_params_buffers: int = 0,
1777
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
1778
+ ) -> Callable[..., Any]:
1779
+ """
1780
+ A simplified version of export. Used by higher order operators.
1781
+
1782
+ This function makes a high-level "no calling convention changes" guarantee:
1783
+ - If no inputs require grad (so we export an inference graph),
1784
+ there are *no* calling convention change between the exported graph, and "func".
1785
+ - If at least one input requires grad (so we trace out and export a joint fw-bw graph),
1786
+ Then if you were partition the graph into a separate forward and backward graph,
1787
+ The forward graph will have no calling convention changes compared to "func".
1788
+
1789
+ The above also relies on some strong restrictions around which functions this API accepts:
1790
+ (1) `args` cannot contain any pytrees (they must have been pytree_flattened already)
1791
+ (2) `func` cannot mutate any inputs
1792
+ (3) The outputs of `func` cannot alias any inputs.
1793
+
1794
+ Note: this function is only lightly tested today. It will probably be tested more heavily by higher order ops.
1795
+ """
1796
+ if trace_joint:
1797
+ ctx = nullcontext
1798
+ else:
1799
+ # Run under no_grad, so our tracing machinery only traces an inference graph.
1800
+ ctx = torch.no_grad
1801
+
1802
+ with ctx():
1803
+ fx_g, metadata, in_spec, out_spec = _aot_export_function(
1804
+ func,
1805
+ args,
1806
+ decompositions=decompositions,
1807
+ trace_joint=trace_joint,
1808
+ )
1809
+ in_spec, _kw_in_spec = in_spec.children()
1810
+ # At this point, we can just directly return the (joint or inference graph) that we traced.
1811
+ # First though: a bunch of assertions to make sure that our graph doesn't require
1812
+ # any calling convention changes compared to the original function.
1813
+ # These restrictions are *in addition to* the general restrictions on export.
1814
+
1815
+ # No input mutations
1816
+ if (
1817
+ len([x for x in metadata.input_info if x.mutates_data or x.mutates_metadata])
1818
+ != 0
1819
+ ):
1820
+ raise RuntimeError(
1821
+ f"aot_export_joint_simple does not support input mutations. {str(metadata)}"
1822
+ )
1823
+ # No output aliasing
1824
+ if (
1825
+ len([x for x in metadata.output_info if x.output_type != OutputType.non_alias])
1826
+ != 0
1827
+ ):
1828
+ raise RuntimeError(
1829
+ f"aot_export_joint_simple does not support outputs that alias inputs. {str(metadata)}"
1830
+ )
1831
+ # No pytrees
1832
+ if in_spec.is_leaf():
1833
+ raise RuntimeError(
1834
+ f"aot_export_joint_simple requires inputs to be a single list/tuple. in_spec={str(in_spec)}"
1835
+ )
1836
+ if not all(child.is_leaf() for child in in_spec.children()):
1837
+ raise RuntimeError(
1838
+ f"aot_export_joint_simple requires individual inputs not to be pytrees. in_spec={str(in_spec)}"
1839
+ )
1840
+
1841
+ if out_spec is None:
1842
+ raise AssertionError("out_spec must not be None")
1843
+ if out_spec.is_leaf():
1844
+ raise RuntimeError(
1845
+ f"aot_export_joint_simple requires outputs to be a single list/tuple. out_spec={str(out_spec)}"
1846
+ )
1847
+ if not all(child.is_leaf() for child in out_spec.children()):
1848
+ raise RuntimeError(
1849
+ f"aot_export_joint_simple requires individual outputs not to be pytrees. out_spec={str(out_spec)}"
1850
+ )
1851
+ # TODO: we might have to temporarily patch config.functionalize_rng
1852
+ # so that it doesn't run when we're exporting a higher order op.
1853
+
1854
+ if config.debug_assert:
1855
+ # Smoke test that after partitioning, we can run the forward without any calling convention changes.
1856
+ fw_module, _bw_module = default_partition(
1857
+ # type: ignore[bad-argument-type]
1858
+ fx_g,
1859
+ args,
1860
+ # type: ignore[unknown-name]
1861
+ num_fwd_outputs=len(fw_metadata.output_infos), # noqa: F821
1862
+ )
1863
+ # Attempt to run the fw_module with the original user inputs
1864
+ fake_mode = detect_fake_mode(args)
1865
+ if fake_mode is None:
1866
+ fake_mode = FakeTensorMode()
1867
+ with fake_mode:
1868
+ fw_module(*args)
1869
+ return fx_g
1870
+
1871
+
1872
+ # Private for now because we aren't providing a contract on what to return
1873
+ # for joint graphs (we could when there's a clearer use case)
1874
+ # In the future, we may need to add more export API's that provide their own strong guarantees.
1875
+ # This is meant as a general helper function for handling various export-y use cases.
1876
+ def _aot_export_function(
1877
+ func: Callable[..., Any],
1878
+ args: tuple[Any, ...],
1879
+ *,
1880
+ num_params_buffers: int = 0,
1881
+ decompositions: dict[OpOverload, Callable[..., Any]] | None = None,
1882
+ # If we're exporting a joint graph and we don't want any tangent inputs in the graph
1883
+ # (because we are backpropping through a scalar 1 loss),
1884
+ # we need to explicitly specify not to include tangents in the graph.
1885
+ # It's not enough just to check that our tangent is a scalar, since we also
1886
+ # need to know if it is a 1 (no need to make it a graph input), or something else
1887
+ # (requiring it to be a graph input).
1888
+ # We don't know this info at trace time though, so we need to make it an explicit config.
1889
+ no_tangents: bool = False,
1890
+ pre_dispatch: bool = False,
1891
+ # If None, `dynamic_shapes` will be inferred from inputs, but the inferred result might be wrong.
1892
+ dynamic_shapes: bool | None = None,
1893
+ keep_input_mutations: bool = False,
1894
+ # Under export, configures whether we are getting inference or training IR
1895
+ trace_joint: bool = False,
1896
+ kwargs: dict[str, Any] | None = None,
1897
+ ) -> tuple[
1898
+ Callable[..., Any], ViewAndMutationMeta, pytree.TreeSpec, pytree.TreeSpec | None
1899
+ ]:
1900
+ kwargs = kwargs or {}
1901
+
1902
+ flat_fn, out_spec = create_tree_flattened_fn(func, args, kwargs)
1903
+ flat_args, in_spec = pytree.tree_flatten((args, kwargs))
1904
+
1905
+ fake_mode = None
1906
+ if dynamic_shapes is None:
1907
+ # Try to infer `dynamic_shapes from inputs and graph nodes
1908
+ fake_mode = detect_fake_mode(flat_args)
1909
+ if (
1910
+ fake_mode is None
1911
+ and hasattr(func, "_orig_mod")
1912
+ and isinstance(func._orig_mod, torch.fx.GraphModule)
1913
+ ):
1914
+ vals = [
1915
+ node.meta["val"]
1916
+ for node in func._orig_mod.graph.nodes
1917
+ if "val" in node.meta
1918
+ ]
1919
+ fake_mode = detect_fake_mode(vals)
1920
+ dynamic_shapes = fake_mode is not None and fake_mode.shape_env is not None
1921
+
1922
+ # The export use case doesn't care about several bits of AOTConfig
1923
+ # (1) compilers (we just export the graph)
1924
+ # (2) partitioners (export is only full graph, user can partition themselves)
1925
+ aot_config = AOTConfig( # type: ignore[arg-type]
1926
+ fw_compiler=None,
1927
+ bw_compiler=None,
1928
+ inference_compiler=None,
1929
+ partition_fn=None,
1930
+ decompositions=decompositions,
1931
+ num_params_buffers=num_params_buffers,
1932
+ aot_id=next(AOT_COUNTER),
1933
+ keep_inference_input_mutations=keep_input_mutations,
1934
+ dynamic_shapes=dynamic_shapes,
1935
+ aot_autograd_arg_pos_to_source=None,
1936
+ is_export=True,
1937
+ no_tangents=no_tangents,
1938
+ pre_dispatch=pre_dispatch,
1939
+ export_trace_joint=trace_joint,
1940
+ )
1941
+ if fake_mode is None:
1942
+ fake_mode, shape_env = construct_fake_mode(flat_args, aot_config)
1943
+ else:
1944
+ shape_env = fake_mode.shape_env
1945
+ fake_flat_args, act_input_paths = process_inputs(
1946
+ flat_args, aot_config, fake_mode, shape_env
1947
+ )
1948
+ # TODO: Improve the descs here with pytree information
1949
+ fake_flat_args_descs: list[AOTInput] = [
1950
+ PlainAOTInput(i) for i in range(len(fake_flat_args))
1951
+ ]
1952
+
1953
+ with contextlib.ExitStack() as stack:
1954
+ aot_state = create_aot_state(
1955
+ stack,
1956
+ flat_fn,
1957
+ fake_flat_args,
1958
+ fake_flat_args_descs,
1959
+ aot_config,
1960
+ fake_mode,
1961
+ shape_env,
1962
+ )
1963
+ aot_state.fw_metadata.act_input_paths = act_input_paths
1964
+ aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn)
1965
+ fx_g, meta = aot_stage2_export(aot_state, aot_graph_capture)
1966
+
1967
+ return fx_g, meta, in_spec, out_spec.spec
1968
+
1969
+
1970
+ compiled_function = aot_function
1971
+ compiled_module = aot_module
.venv/lib/python3.12/site-packages/torch/_functorch/apis.py ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTE: We allow Dynamo to see this file (via torch/_dynamo/trace_rules.py) so that it can
2
+ # trace through functorch transforms.
3
+ # Currently, we can't allow Dynamo to see `eager_transforms.py`/`vmap.py` as that break a lot of thing
4
+ # and there isn't a mechanism to selectively expose only some functions (eg. grad) from a file
5
+ # to Dynamo.
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ from typing import Any, TYPE_CHECKING
11
+ from typing_extensions import ParamSpec, TypeVar
12
+
13
+ from torch._functorch.utils import argnums_t, exposed_in
14
+ from torch._functorch.vmap import (
15
+ _check_out_dims_is_int_or_int_pytree,
16
+ _check_randomness_arg,
17
+ _chunked_vmap,
18
+ _process_batched_inputs,
19
+ Callable,
20
+ in_dims_t,
21
+ out_dims_t,
22
+ vmap_impl,
23
+ )
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Iterable
28
+
29
+ import torch
30
+
31
+ _P = ParamSpec("_P")
32
+ _R = TypeVar("_R")
33
+
34
+ # functools.wraps copies __dict__, but these attrs describe the original
35
+ # compiled callable, not the transformed function wrapper.
36
+ _DYNAMO_WRAPPER_ATTRS = (
37
+ "_torchdynamo_inline",
38
+ "_torchdynamo_orig_callable",
39
+ "_torchdynamo_wrapper_id",
40
+ "_isolate_recompiles_id",
41
+ "get_compiler_config",
42
+ "aot_compile",
43
+ "_is_torch_compile",
44
+ )
45
+
46
+
47
+ def _wraps_without_dynamo_attrs(
48
+ func: Callable[..., Any],
49
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
50
+ def inner(wrapper: Callable[_P, _R]) -> Callable[_P, _R]:
51
+ wrapper = functools.wraps(func)(wrapper)
52
+ for attr in _DYNAMO_WRAPPER_ATTRS:
53
+ wrapper.__dict__.pop(attr, None)
54
+ return wrapper
55
+
56
+ return inner
57
+
58
+
59
+ # vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
60
+ # sends those into func, and then unwraps the output BatchedTensors. Operations
61
+ # on BatchedTensors perform the batched operations that the user is asking for.
62
+ #
63
+ # vmap's randomness behavior differs from JAX's, which would require a PRNG key
64
+ # to be passed everywhere.
65
+
66
+
67
+ @exposed_in("torch.func")
68
+ def vmap(
69
+ func: Callable[_P, _R],
70
+ in_dims: in_dims_t = 0,
71
+ out_dims: out_dims_t = 0,
72
+ randomness: str = "error",
73
+ *,
74
+ chunk_size: int | None = None,
75
+ ) -> Callable[_P, _R]:
76
+ """
77
+ vmap is the vectorizing map; ``vmap(func)`` returns a new function that
78
+ maps ``func`` over some dimension of the inputs. Semantically, vmap
79
+ pushes the map into PyTorch operations called by ``func``, effectively
80
+ vectorizing those operations.
81
+
82
+ vmap is useful for handling batch dimensions: one can write a function
83
+ ``func`` that runs on examples and then lift it to a function that can
84
+ take batches of examples with ``vmap(func)``. vmap can also be used to
85
+ compute batched gradients when composed with autograd.
86
+
87
+ .. note::
88
+ :func:`torch.vmap` is aliased to :func:`torch.func.vmap` for
89
+ convenience. Use whichever one you'd like.
90
+
91
+ Args:
92
+ func (function): A Python function that takes one or more arguments.
93
+ Must return one or more Tensors.
94
+ in_dims (int or nested structure): Specifies which dimension of the
95
+ inputs should be mapped over. ``in_dims`` should have a
96
+ structure like the inputs. If the ``in_dim`` for a particular
97
+ input is None, then that indicates there is no map dimension.
98
+ Default: 0.
99
+ out_dims (int or Tuple[int]): Specifies where the mapped dimension
100
+ should appear in the outputs. If ``out_dims`` is a Tuple, then
101
+ it should have one element per output. Default: 0.
102
+ randomness (str): Specifies whether the randomness in this
103
+ vmap should be the same or different across batches. If 'different',
104
+ the randomness for each batch will be different. If 'same', the
105
+ randomness will be the same across batches. If 'error', any calls to
106
+ random functions will error. Default: 'error'. WARNING: this flag
107
+ only applies to random PyTorch operations and does not apply to
108
+ Python's random module or numpy randomness.
109
+ chunk_size (None or int): If None (default), apply a single vmap over inputs.
110
+ If not None, then compute the vmap :attr:`chunk_size` samples at a time.
111
+ Note that :attr:`chunk_size=1` is equivalent to computing the vmap with a for-loop.
112
+ If you run into memory issues computing the vmap, please try a non-None chunk_size.
113
+
114
+ Returns:
115
+ Returns a new "batched" function. It takes the same inputs as
116
+ ``func``, except each input has an extra dimension at the index
117
+ specified by ``in_dims``. It takes returns the same outputs as
118
+ ``func``, except each output has an extra dimension at the index
119
+ specified by ``out_dims``.
120
+
121
+ .. warning:
122
+ :func:`vmap` works best with functional-style code. Please do not
123
+ perform any side-effects in ``func``, with the exception of
124
+ in-place PyTorch operations. Examples of side-effects include mutating
125
+ Python data structures and assigning values to variables not captured
126
+ in ``func``.
127
+
128
+ One example of using :func:`vmap` is to compute batched dot products. PyTorch
129
+ doesn't provide a batched ``torch.dot`` API; instead of unsuccessfully
130
+ rummaging through docs, use :func:`vmap` to construct a new function.
131
+
132
+ >>> torch.dot # [D], [D] -> []
133
+ >>> batched_dot = torch.func.vmap(torch.dot) # [N, D], [N, D] -> [N]
134
+ >>> x, y = torch.randn(2, 5), torch.randn(2, 5)
135
+ >>> batched_dot(x, y)
136
+
137
+ :func:`vmap` can be helpful in hiding batch dimensions, leading to a simpler
138
+ model authoring experience.
139
+
140
+ >>> batch_size, feature_size = 3, 5
141
+ >>> weights = torch.randn(feature_size, requires_grad=True)
142
+ >>>
143
+ >>> def model(feature_vec):
144
+ >>> # Very simple linear model with activation
145
+ >>> return feature_vec.dot(weights).relu()
146
+ >>>
147
+ >>> examples = torch.randn(batch_size, feature_size)
148
+ >>> result = torch.vmap(model)(examples)
149
+
150
+ :func:`vmap` can also help vectorize computations that were previously difficult
151
+ or impossible to batch. One example is higher-order gradient computation.
152
+ The PyTorch autograd engine computes vjps (vector-Jacobian products).
153
+ Computing a full Jacobian matrix for some function f: R^N -> R^N usually
154
+ requires N calls to ``autograd.grad``, one per Jacobian row. Using :func:`vmap`,
155
+ we can vectorize the whole computation, computing the Jacobian in a single
156
+ call to ``autograd.grad``.
157
+
158
+ >>> # Setup
159
+ >>> N = 5
160
+ >>> f = lambda x: x**2
161
+ >>> x = torch.randn(N, requires_grad=True)
162
+ >>> y = f(x)
163
+ >>> I_N = torch.eye(N)
164
+ >>>
165
+ >>> # Sequential approach
166
+ >>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
167
+ >>> for v in I_N.unbind()]
168
+ >>> jacobian = torch.stack(jacobian_rows)
169
+ >>>
170
+ >>> # vectorized gradient computation
171
+ >>> def get_vjp(v):
172
+ >>> return torch.autograd.grad(y, x, v)
173
+ >>> jacobian = torch.vmap(get_vjp)(I_N)
174
+
175
+ :func:`vmap` can also be nested, producing an output with multiple batched dimensions
176
+
177
+ >>> torch.dot # [D], [D] -> []
178
+ >>> batched_dot = torch.vmap(
179
+ ... torch.vmap(torch.dot)
180
+ ... ) # [N1, N0, D], [N1, N0, D] -> [N1, N0]
181
+ >>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5)
182
+ >>> batched_dot(x, y) # tensor of size [2, 3]
183
+
184
+ If the inputs are not batched along the first dimension, ``in_dims`` specifies
185
+ the dimension that each inputs are batched along as
186
+
187
+ >>> torch.dot # [N], [N] -> []
188
+ >>> batched_dot = torch.vmap(torch.dot, in_dims=1) # [N, D], [N, D] -> [D]
189
+ >>> x, y = torch.randn(2, 5), torch.randn(2, 5)
190
+ >>> batched_dot(
191
+ ... x, y
192
+ ... ) # output is [5] instead of [2] if batched along the 0th dimension
193
+
194
+ If there are multiple inputs each of which is batched along different dimensions,
195
+ ``in_dims`` must be a tuple with the batch dimension for each input as
196
+
197
+ >>> torch.dot # [D], [D] -> []
198
+ >>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None)) # [N, D], [D] -> [N]
199
+ >>> x, y = torch.randn(2, 5), torch.randn(5)
200
+ >>> batched_dot(
201
+ ... x, y
202
+ ... ) # second arg doesn't have a batch dim because in_dim[1] was None
203
+
204
+ If the input is a Python struct, ``in_dims`` must be a tuple containing a struct
205
+ matching the shape of the input:
206
+
207
+ >>> f = lambda dict: torch.dot(dict["x"], dict["y"])
208
+ >>> x, y = torch.randn(2, 5), torch.randn(5)
209
+ >>> input = {"x": x, "y": y}
210
+ >>> batched_dot = torch.vmap(f, in_dims=({"x": 0, "y": None},))
211
+ >>> batched_dot(input)
212
+
213
+ By default, the output is batched along the first dimension. However, it can be batched
214
+ along any dimension by using ``out_dims``
215
+
216
+ >>> f = lambda x: x**2
217
+ >>> x = torch.randn(2, 5)
218
+ >>> batched_pow = torch.vmap(f, out_dims=1)
219
+ >>> batched_pow(x) # [5, 2]
220
+
221
+ For any function that uses kwargs, the returned function will not batch the kwargs but will
222
+ accept kwargs
223
+
224
+ >>> x = torch.randn([2, 5])
225
+ >>> def fn(x, scale=4.):
226
+ >>> return x * scale
227
+ >>>
228
+ >>> batched_pow = torch.vmap(fn)
229
+ >>> assert torch.allclose(batched_pow(x), x * 4)
230
+ >>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5]
231
+
232
+ .. note::
233
+ vmap does not provide general autobatching or handle variable-length
234
+ sequences out of the box.
235
+ """
236
+ from torch.compiler import is_compiling
237
+
238
+ _check_randomness_arg(randomness)
239
+ if not (chunk_size is None or chunk_size > 0):
240
+ raise ValueError(
241
+ f"vmap: chunk_size should be None or greater than 0. (got {chunk_size})"
242
+ )
243
+
244
+ def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R:
245
+ # pyrefly: ignore[bad-argument-type]
246
+ return vmap_impl(
247
+ # pyrefly: ignore[bad-argument-type]
248
+ func,
249
+ in_dims,
250
+ out_dims,
251
+ randomness,
252
+ chunk_size,
253
+ *args,
254
+ **kwargs,
255
+ )
256
+
257
+ if not is_compiling():
258
+ wrapped = _wraps_without_dynamo_attrs(func)(wrapped)
259
+
260
+ return wrapped
261
+
262
+
263
+ def chunk_vmap(
264
+ func: Callable[_P, _R],
265
+ in_dims: in_dims_t = 0,
266
+ out_dims: out_dims_t = 0,
267
+ randomness: str = "error",
268
+ chunks: int = 2,
269
+ ) -> Callable[_P, _R]:
270
+ """
271
+ chunk_vmap is the vectorizing map (vmap) using chunks of input data. It is a mix of vmap (which vectorizes
272
+ everything) and map (which executes things sequentially). ``chunk_vmap`` vectorizes the input with number of
273
+ chunks at a time. For more details about vectorizing map, see :func:`vmap`.
274
+
275
+ .. note::
276
+ Please use :func:`vmap` with ``chunk_size`` argument instead of this API.
277
+
278
+ Args:
279
+ func (function): A Python function that takes one or more arguments.
280
+ Must return one or more Tensors.
281
+ in_dims (int or nested structure): Specifies which dimension of the
282
+ inputs should be mapped over. ``in_dims`` should have a
283
+ structure like the inputs. If the ``in_dim`` for a particular
284
+ input is None, then that indicates there is no map dimension.
285
+ Default: 0.
286
+ out_dims (int or Tuple[int]): Specifies where the mapped dimension
287
+ should appear in the outputs. If ``out_dims`` is a Tuple, then
288
+ it should have one element per output. Default: 0.
289
+ randomness (str): Specifies whether the randomness in this
290
+ vmap should be the same or different across batches. If 'different',
291
+ the randomness for each batch will be different. If 'same', the
292
+ randomness will be the same across batches. If 'error', any calls to
293
+ random functions will error. Default: 'error'. WARNING: this flag
294
+ only applies to random PyTorch operations and does not apply to
295
+ Python's random module or numpy randomness.
296
+ chunks (int): Number of chunks to use to split the input data. Default is 2.
297
+ If equals to 1 then :func:`vmap` is called.
298
+
299
+ Returns:
300
+ Returns a new "batched" function. It takes the same inputs as
301
+ ``func``, except each input has an extra dimension at the index
302
+ specified by ``in_dims``. It takes returns the same outputs as
303
+ ``func``, except each output has an extra dimension at the index
304
+ specified by ``out_dims``.
305
+ """
306
+ _check_randomness_arg(randomness)
307
+
308
+ if chunks == 1:
309
+ return vmap(func, in_dims=in_dims, out_dims=out_dims, randomness=randomness)
310
+
311
+ def _get_chunk_flat_args(
312
+ flat_args_: Iterable[Any],
313
+ flat_in_dims_: Iterable[int | None],
314
+ chunks_: int,
315
+ ) -> Iterable[Any]:
316
+ flat_args_chunks = tuple(
317
+ t.chunk(chunks_, dim=in_dim)
318
+ if in_dim is not None
319
+ else [
320
+ t,
321
+ ]
322
+ * chunks_
323
+ for t, in_dim in zip(flat_args_, flat_in_dims_)
324
+ )
325
+ # transpose chunk dim and flatten structure
326
+ # chunks_flat_args is a list of flatten args
327
+ chunks_flat_args = zip(*flat_args_chunks)
328
+ return chunks_flat_args
329
+
330
+ @_wraps_without_dynamo_attrs(func)
331
+ def wrapped_with_chunks(*args: _P.args, **kwargs: _P.kwargs) -> _R:
332
+ _check_out_dims_is_int_or_int_pytree(out_dims, func)
333
+ _, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
334
+ in_dims, args, func
335
+ )
336
+ # Chunk flat arguments
337
+ chunks_flat_args = _get_chunk_flat_args(flat_args, flat_in_dims, chunks)
338
+
339
+ # Apply vmap on chunks
340
+ return _chunked_vmap(
341
+ # pyrefly: ignore[bad-argument-type]
342
+ func,
343
+ flat_in_dims,
344
+ chunks_flat_args,
345
+ args_spec,
346
+ out_dims,
347
+ randomness,
348
+ **kwargs,
349
+ )
350
+
351
+ return wrapped_with_chunks
352
+
353
+
354
+ # TODO: Improve the return type of this function
355
+ @exposed_in("torch.func")
356
+ def grad(
357
+ func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False
358
+ ) -> Callable[_P, Any]:
359
+ """``grad`` operator helps computing gradients of ``func`` with respect to the
360
+ input(s) specified by ``argnums``. This operator can be nested to
361
+ compute higher-order gradients.
362
+
363
+ Args:
364
+ func (Callable): A Python function that takes one or more arguments.
365
+ Must return a single-element Tensor. If specified ``has_aux`` equals ``True``,
366
+ function can return a tuple of single-element Tensor and other auxiliary objects:
367
+ ``(output, aux)``.
368
+ argnums (int or Tuple[int]): Specifies arguments to compute gradients with respect to.
369
+ ``argnums`` can be single integer or tuple of integers. Default: 0.
370
+ has_aux (bool): Flag indicating that ``func`` returns a tensor and other
371
+ auxiliary objects: ``(output, aux)``. Default: False.
372
+
373
+ Returns:
374
+ Function to compute gradients with respect to its inputs. By default, the output of
375
+ the function is the gradient tensor(s) with respect to the first argument.
376
+ If specified ``has_aux`` equals ``True``, tuple of gradients and output auxiliary objects
377
+ is returned. If ``argnums`` is a tuple of integers, a tuple of output gradients with
378
+ respect to each ``argnums`` value is returned.
379
+
380
+ Example of using ``grad``:
381
+
382
+ >>> # xdoctest: +SKIP
383
+ >>> from torch.func import grad
384
+ >>> x = torch.randn([])
385
+ >>> cos_x = grad(lambda x: torch.sin(x))(x)
386
+ >>> assert torch.allclose(cos_x, x.cos())
387
+ >>>
388
+ >>> # Second-order gradients
389
+ >>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x)
390
+ >>> assert torch.allclose(neg_sin_x, -x.sin())
391
+
392
+ When composed with ``vmap``, ``grad`` can be used to compute per-sample-gradients:
393
+
394
+ >>> # xdoctest: +SKIP
395
+ >>> from torch.func import grad, vmap
396
+ >>> batch_size, feature_size = 3, 5
397
+ >>>
398
+ >>> def model(weights, feature_vec):
399
+ >>> # Very simple linear model with activation
400
+ >>> assert feature_vec.dim() == 1
401
+ >>> return feature_vec.dot(weights).relu()
402
+ >>>
403
+ >>> def compute_loss(weights, example, target):
404
+ >>> y = model(weights, example)
405
+ >>> return ((y - target) ** 2).mean() # MSELoss
406
+ >>>
407
+ >>> weights = torch.randn(feature_size, requires_grad=True)
408
+ >>> examples = torch.randn(batch_size, feature_size)
409
+ >>> targets = torch.randn(batch_size)
410
+ >>> inputs = (weights, examples, targets)
411
+ >>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))(
412
+ ... *inputs
413
+ ... )
414
+
415
+ Example of using ``grad`` with ``has_aux`` and ``argnums``:
416
+
417
+ >>> # xdoctest: +SKIP
418
+ >>> from torch.func import grad
419
+ >>> def my_loss_func(y, y_pred):
420
+ >>> loss_per_sample = (0.5 * y_pred - y) ** 2
421
+ >>> loss = loss_per_sample.mean()
422
+ >>> return loss, (y_pred, loss_per_sample)
423
+ >>>
424
+ >>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True)
425
+ >>> y_true = torch.rand(4)
426
+ >>> y_preds = torch.rand(4, requires_grad=True)
427
+ >>> out = fn(y_true, y_preds)
428
+ >>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample))
429
+
430
+ .. note::
431
+ Using PyTorch ``torch.no_grad`` together with ``grad``.
432
+
433
+ Case 1: Using ``torch.no_grad`` inside a function:
434
+
435
+ >>> # xdoctest: +SKIP
436
+ >>> def f(x):
437
+ >>> with torch.no_grad():
438
+ >>> c = x ** 2
439
+ >>> return x - c
440
+
441
+ In this case, ``grad(f)(x)`` will respect the inner ``torch.no_grad``.
442
+
443
+ Case 2: Using ``grad`` inside ``torch.no_grad`` context manager:
444
+
445
+ >>> # xdoctest: +SKIP
446
+ >>> with torch.no_grad():
447
+ >>> grad(f)(x)
448
+
449
+ In this case, ``grad`` will respect the inner ``torch.no_grad``, but not the
450
+ outer one. This is because ``grad`` is a "function transform": its result
451
+ should not depend on the result of a context manager outside of ``f``.
452
+
453
+ """
454
+ # To avoid cyclical dependency.
455
+ import torch._functorch.eager_transforms as eager_transforms
456
+ from torch.compiler import is_compiling
457
+
458
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]:
459
+ return eager_transforms.grad_impl(func, argnums, has_aux, args, kwargs)
460
+
461
+ if not is_compiling():
462
+ wrapper = _wraps_without_dynamo_attrs(func)(wrapper)
463
+
464
+ return wrapper
465
+
466
+
467
+ # TODO: Improve the return type of this function
468
+ @exposed_in("torch.func")
469
+ def grad_and_value(
470
+ func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False
471
+ ) -> Callable[_P, tuple[Any, Any]]:
472
+ """
473
+ Returns a function to compute a tuple of the gradient and primal, or
474
+ forward, computation.
475
+
476
+ Args:
477
+ func (Callable): A Python function that takes one or more arguments.
478
+ Must return a single-element Tensor. If specified ``has_aux``
479
+ equals ``True``, function can return a tuple of single-element
480
+ Tensor and other auxiliary objects: ``(output, aux)``.
481
+ argnums (int or Tuple[int]): Specifies arguments to compute gradients
482
+ with respect to. ``argnums`` can be single integer or tuple of
483
+ integers. Default: 0.
484
+ has_aux (bool): Flag indicating that ``func`` returns a tensor and
485
+ other auxiliary objects: ``(output, aux)``. Default: False.
486
+
487
+ Returns:
488
+ Function to compute a tuple of gradients with respect to its inputs
489
+ and the forward computation. By default, the output of the function is
490
+ a tuple of the gradient tensor(s) with respect to the first argument
491
+ and the primal computation. If specified ``has_aux`` equals
492
+ ``True``, tuple of gradients and tuple of the forward computation with
493
+ output auxiliary objects is returned. If ``argnums`` is a tuple of
494
+ integers, a tuple of a tuple of the output gradients with respect to
495
+ each ``argnums`` value and the forward computation is returned.
496
+
497
+ See :func:`grad` for examples
498
+ """
499
+ from torch._functorch import eager_transforms
500
+ from torch.compiler import is_compiling
501
+
502
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]:
503
+ return eager_transforms.grad_and_value_impl(
504
+ func, argnums, has_aux, args, kwargs
505
+ )
506
+
507
+ if not is_compiling():
508
+ wrapper = _wraps_without_dynamo_attrs(func)(wrapper)
509
+
510
+ return wrapper
.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py ADDED
@@ -0,0 +1,935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, NamedTuple, TYPE_CHECKING
4
+ from typing_extensions import ParamSpec, TypeVar
5
+
6
+ import torch
7
+ import torch.utils._pytree as pytree
8
+ from torch._C._functorch import (
9
+ _unwrap_for_grad,
10
+ _wrap_for_grad,
11
+ current_level,
12
+ TransformType,
13
+ )
14
+ from torch._functorch.apis import vmap
15
+ from torch._functorch.utils import enable_single_level_autograd_function
16
+ from torch._functorch.vmap import (
17
+ _add_batch_dim,
18
+ _broadcast_to_and_flatten,
19
+ restore_vmap,
20
+ unwrap_batched,
21
+ wrap_batched,
22
+ )
23
+ from torch._ops import HigherOrderOperator
24
+ from torch.autograd.forward_ad import _set_fwd_grad_enabled
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Callable, Iterable, Sequence
29
+
30
+ from torch._functorch.pyfunctorch import FuncTorchInterpreter, VmapInterpreter
31
+
32
+ _P = ParamSpec("_P")
33
+ _R = TypeVar("_R")
34
+
35
+
36
+ # autograd.Function technically runs before the regular PyTorch dispatcher.
37
+ # This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot)
38
+ # work with it. One day we might decide to change this, but until then,
39
+ # we need to give the illusion that autograd.Function runs before those things.
40
+ #
41
+ # We do this by using creating a custom HigherOrderOperator that only functorch
42
+ # dispatches specially.
43
+ class CustomFunctionHigherOrderOperator(HigherOrderOperator):
44
+ def __init__(self) -> None:
45
+ super().__init__("custom_function_call")
46
+
47
+ def __call__(
48
+ self,
49
+ autograd_function: type[torch.autograd.Function],
50
+ *args: _P.args,
51
+ **kwargs: _P.kwargs,
52
+ ) -> Any:
53
+ # When custom_function_call is done dispatching through functorch,
54
+ # it should just invoke the autograd.Function. This is consistent
55
+ # with the autograd.Function behavior of being invoked before the
56
+ # PyTorch dispatcher.
57
+ #
58
+ # This will lead us into trouble later down the line, but this is
59
+ # pre-existing. There is an invariant that a function traced by
60
+ # make_fx should have the same behavior when provided the same
61
+ # Tensor. However, make_fx sees autograd.Function as a composite
62
+ # (because autograd.Function happens before the Python dispatch key)
63
+ # and only traces the forward pass.
64
+ if torch._C._are_functorch_transforms_active():
65
+ # pyrefly: ignore [missing-attribute]
66
+ return super().__call__(autograd_function, *args, **kwargs)
67
+ return autograd_function.apply(*args, **kwargs)
68
+
69
+
70
+ # "custom_function_call"
71
+ # This is the mechanism for an autograd.Function that works with functorch transforms.
72
+ # It wraps an autograd.Function; interactions with functorch transforms are defined
73
+ # via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch
74
+ # dispatcher.
75
+ custom_function_call = CustomFunctionHigherOrderOperator()
76
+
77
+
78
+ # The grad rule for custom_function_call is to construct a new _SingleLevelFunction
79
+ # (autograd.Function that only works with a single layer (level) of functorch) that:
80
+ # - unwraps the inputs
81
+ # - redispatches to custom_function_call
82
+ # - wraps the outputs
83
+ # and whose backward pass calls the original autograd.Function's backward.
84
+ #
85
+ # Why do we need to redispatch to custom_function_call?
86
+ # -----------------------------------------------------
87
+ # This is consistent with how ATen operators work with functorch's grad transform:
88
+ # they always redispatch to the original operator.
89
+ # Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x)
90
+ #
91
+ # grad1 will:
92
+ # - set up the autograd graph
93
+ # - unwrap the inputs
94
+ # - redispatch to at::sin (*)
95
+ # - rewrap the outputs on the return
96
+ #
97
+ # On the redispatch in (*), grad0 will:
98
+ # - set up the autograd graph
99
+ # - unwrap the inputs
100
+ # - redispatch to at::sin
101
+ # - rewrap the outputs on the return
102
+ #
103
+ # To "set up the autograd graph", we generate a _SingleLevelFunction
104
+ # and apply it.
105
+ @custom_function_call.py_impl(TransformType.Grad)
106
+ @custom_function_call.py_impl(TransformType.Jvp)
107
+ def custom_function_call_grad(
108
+ interpreter: FuncTorchInterpreter,
109
+ autograd_function: type[torch.autograd.Function],
110
+ *operands: Any,
111
+ ) -> Any:
112
+ Generated = generate_single_level_function(interpreter, autograd_function)
113
+ with enable_single_level_autograd_function():
114
+ # pyrefly: ignore [missing-attribute]
115
+ flat_out = Generated.apply(*operands)
116
+ return flat_out
117
+
118
+
119
+ def generate_single_level_function(
120
+ interpreter: FuncTorchInterpreter,
121
+ autograd_function: type[torch.autograd.Function],
122
+ ) -> type[torch.autograd.function._SingleLevelFunction]:
123
+ level = interpreter.level()
124
+
125
+ def forward(*operands: Any) -> Any:
126
+ unwrapped_operands = pytree.tree_map_only(
127
+ torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands
128
+ )
129
+ # Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter
130
+ # the transform. _SingleLevelFunction will turn off both fwd and bwd
131
+ # gradient computation and we need to turn it back on here.
132
+ with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower():
133
+ unwrapped_output = custom_function_call(
134
+ autograd_function, *unwrapped_operands
135
+ )
136
+
137
+ # See NOTE [mark_dirty object identity check]
138
+ def wrap_fn(output: torch.Tensor) -> torch.Tensor:
139
+ return _wrap_for_grad(output, level)
140
+
141
+ return wrap_outputs_maintaining_identity(
142
+ unwrapped_output, unwrapped_operands, operands, wrap_fn
143
+ )
144
+
145
+ def setup_context(ctx: Any, inputs: Any, output: Any) -> Any:
146
+ return autograd_function.setup_context(ctx, inputs, output)
147
+
148
+ # backward is only used if the transform is TransformType.Grad
149
+ def backward(ctx: Any, *grads: Any) -> Any:
150
+ result = autograd_function.backward(ctx, *grads)
151
+ return result
152
+
153
+ # jvp is only used if the transform is TransformType.Jvp
154
+ def jvp(ctx: Any, *tangents: Any) -> Any:
155
+ result = autograd_function.jvp(ctx, *tangents)
156
+ return result
157
+
158
+ # This is the sequence of magic words to dynamically generate a Subclass with
159
+ # a given name. A Tensor's .grad_fn field has a class name that is the original
160
+ # autograd.Function's name + Backward, so we do this to generate some
161
+ # meaningful name.
162
+ name = f"{autograd_function.__name__}Generated"
163
+ Generated = type(
164
+ name,
165
+ (torch.autograd.function._SingleLevelFunction,),
166
+ {
167
+ "forward": staticmethod(forward),
168
+ "backward": staticmethod(backward),
169
+ "jvp": staticmethod(jvp),
170
+ "setup_context": staticmethod(setup_context),
171
+ },
172
+ )
173
+ return Generated
174
+
175
+
176
+ # wrap_outputs_maintaining_identity handles outputs from the vmap,
177
+ # backward (vjp), and jvp staticmethod. The way it distinguishes
178
+ # between the vmap case and the {backward, jvp} case is if the out_dims
179
+ # are specified or not.
180
+ #
181
+ # NB: we cannot use out_dims=None as the deciding factor. This because
182
+ # out_dims=None can still happen in the vmap staticmethod! What the
183
+ # user is saying in that case is that their output does not have a
184
+ # dimension that is being vmapped over, which is valid.
185
+ NO_OUT_DIMS = "not specified"
186
+
187
+
188
+ # NOTE [mark_dirty object identity check]
189
+ # autograd.Function's ctx.mark_dirty expect a returned input
190
+ # to have the same object identity as the input.
191
+ # Mode-only functorch will greatly simplify this logic.
192
+ def wrap_outputs_maintaining_identity(
193
+ outputs: Any,
194
+ unwrapped_inputs: Any,
195
+ orig_inputs: Any,
196
+ wrap_fn: Callable[..., Any],
197
+ out_dims: Any = NO_OUT_DIMS,
198
+ ) -> Any:
199
+ flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs)
200
+ flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs)
201
+
202
+ unwrapped_input_to_orig_input = {
203
+ id(unwrapped): orig
204
+ for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs)
205
+ }
206
+
207
+ flat_outputs, spec = pytree.tree_flatten(outputs)
208
+ result = []
209
+
210
+ out_dims_specified = out_dims != NO_OUT_DIMS
211
+
212
+ flat_out_dims = None
213
+ if out_dims_specified:
214
+ flat_out_dims = _broadcast_to_and_flatten(out_dims, spec)
215
+ # _broadcast_to_and_flatten returns None if it is unable to broadcast.
216
+ # TODO: update following link from master to stable once that's out
217
+ if flat_out_dims is None:
218
+ raise RuntimeError(
219
+ f"The autograd.Function's vmap staticmethod returned an "
220
+ f"incompatible (output, out_dims) tuple. "
221
+ f"Expected out_dims={out_dims} "
222
+ f"to be compatible with the structure of `output`. "
223
+ f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} "
224
+ f"but output has structure {spec}. "
225
+ f"For more details, please see "
226
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
227
+ )
228
+
229
+ for i, output in enumerate(flat_outputs):
230
+ if not isinstance(output, torch.Tensor):
231
+ result.append(output)
232
+ continue
233
+ if id(output) in unwrapped_input_to_orig_input:
234
+ result.append(unwrapped_input_to_orig_input[id(output)])
235
+ continue
236
+ if out_dims_specified:
237
+ if flat_out_dims is None:
238
+ raise AssertionError(
239
+ "flat_out_dims must not be None when out_dims is specified"
240
+ )
241
+ result.append(wrap_fn(output, flat_out_dims[i]))
242
+ else:
243
+ result.append(wrap_fn(output))
244
+
245
+ return pytree.tree_unflatten(result, spec)
246
+
247
+
248
+ # NOTE: [functorch vjp and autograd interaction]
249
+ # There's an edge case with the functorch vjp and autograd interaction
250
+ # that will eventually be fixed by mode-only functorch.
251
+ # The TL;DR is that there's no way to unwrap a dead GradTensorWrapper,
252
+ # so we (the framework) need to do it manually. Regular PyTorch operators
253
+ # automatically do so this is consistent.
254
+ #
255
+ # class MyExp(torch.autograd.Function):
256
+ # @staticmethod
257
+ # def forward(x):
258
+ # return x.exp()
259
+ #
260
+ # @staticmethod
261
+ # def setup_context(ctx, inputs, output):
262
+ # y = output
263
+ # ctx.save_for_backward(y)
264
+ #
265
+ # @staticmethod
266
+ # def backward(gy):
267
+ # y, = ctx.saved_tensors()
268
+ # return MyMul.apply(gy, y)
269
+ #
270
+ # x = torch.randn([], requires_grad=True)
271
+ # gy = torch.randn([], requires_grad=True)
272
+ # _, vjp_fn = vjp(MySin.apply, x)
273
+ # result = vjp_fn(gy)
274
+ #
275
+ # MyMul is an autograd.Function that is not shown here.
276
+ # It saves a `y` for backward (since gy requires grad).
277
+ #
278
+ # in vjp_fn(gy), we get:
279
+ # > MyMul.apply(gy, GradTensorWrapper(y, level=dead))
280
+ # Because the y that is saved for backward by MyExp is a GradTensorWrapper
281
+ # but is now dead since we are outside the vjp context.
282
+ #
283
+ # PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper,
284
+ # will automatically unwrap the GradTensorWrapper when applied.
285
+ # But since autograd.Function technically sits above the regular PyTorch
286
+ # dispatcher, it doesn't get this treatment. So we manually do
287
+ # the unwrapping to be consistent with regular PyTorch dispatcher operations.
288
+
289
+
290
+ class VmapInfo(NamedTuple):
291
+ batch_size: int
292
+ randomness: str
293
+
294
+
295
+ def has_overridden_vmap_rule(
296
+ autograd_function: type[torch.autograd.Function],
297
+ ) -> bool:
298
+ return autograd_function.vmap is not torch.autograd.Function.vmap
299
+
300
+
301
+ def validate_vmap_returns_tuple_of_two_elements(result: Any) -> None:
302
+ base_error_msg = (
303
+ "Expected the vmap staticmethod to have two returns, an output "
304
+ "and out_dims with pytree structure compatible with the output. "
305
+ )
306
+ if not isinstance(result, tuple):
307
+ raise RuntimeError(base_error_msg + f"Got a {type(result)} instead")
308
+ if not len(result) == 2:
309
+ raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead")
310
+
311
+
312
+ @custom_function_call.py_impl(TransformType.Vmap)
313
+ def custom_function_call_vmap(
314
+ interpreter: VmapInterpreter,
315
+ autograd_function: type[torch.autograd.Function],
316
+ *operands: Any,
317
+ **kwargs: Any,
318
+ ) -> Any:
319
+ if any(
320
+ isinstance(val, torch.Tensor)
321
+ for val in torch.utils._pytree.tree_flatten(kwargs)[0]
322
+ ):
323
+ raise NotImplementedError(
324
+ f"Run vmap on autograd.Function with kwarg-only Tensor args. "
325
+ f"Please do not pass kwarg-only Tensors to autograd.Function. "
326
+ f"Got: {kwargs}"
327
+ )
328
+
329
+ if autograd_function.generate_vmap_rule:
330
+ if has_overridden_vmap_rule(autograd_function):
331
+ # TODO: Update link to stable once that's out
332
+ # https://github.com/pytorch/pytorch/issues/92029
333
+ raise RuntimeError(
334
+ f"You tried to vmap over {autograd_function.__name__}, but "
335
+ f"it has both generate_vmap_rule=True and an overridden vmap "
336
+ f"staticmethod. Please set generate_vmap_rule=False or delete "
337
+ f"the overridden vmap staticmethod to avoid ambiguity. "
338
+ f"For more details, please see "
339
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
340
+ )
341
+ return custom_function_call_vmap_generate_rule(
342
+ interpreter, autograd_function, *operands
343
+ )
344
+
345
+ if not has_overridden_vmap_rule(autograd_function):
346
+ # TODO: Update link to stable once that's out
347
+ # https://github.com/pytorch/pytorch/issues/92029
348
+ raise RuntimeError(
349
+ f"You tried to vmap over {autograd_function.__name__}, but "
350
+ f"it does not have vmap support. Please override and implement the "
351
+ f"vmap staticmethod or set generate_vmap_rule=True. "
352
+ f"For more details, please see "
353
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
354
+ )
355
+
356
+ return custom_function_call_vmap_helper(
357
+ interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs
358
+ )
359
+
360
+
361
+ def custom_function_call_vmap_helper(
362
+ interpreter: VmapInterpreter,
363
+ vmap_function: Callable[..., Any],
364
+ op: Any,
365
+ *operands: Any,
366
+ **kwargs: Any,
367
+ ) -> Any:
368
+ current_level = interpreter.level()
369
+ info = VmapInfo(
370
+ batch_size=interpreter.batch_size(),
371
+ randomness=interpreter.randomness(),
372
+ )
373
+ # We're either in the autograd.Function case (vmap staticmethod)
374
+ # or the torch.library.register_vmap case.
375
+ autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta)
376
+
377
+ def lower_to_next() -> Any:
378
+ if autograd_function_case:
379
+ return interpreter.lower()
380
+ else:
381
+ return torch._C._ExcludeDispatchKeyGuard(
382
+ torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched)
383
+ )
384
+
385
+ unwrapped_operands, in_dims = unwrap_batched(operands, current_level)
386
+ # If none of the tensors are batched at the current level, then we skip the
387
+ # current level. This saves the user from needing to handle this case in
388
+ # their vmap staticmethod (and is consistent with our C++ batching rule API)
389
+ if pytree.tree_all(lambda dim: dim is None, in_dims):
390
+ with lower_to_next():
391
+ if autograd_function_case:
392
+ return custom_function_call(op, *operands)
393
+ else:
394
+ return op(*operands, **kwargs)
395
+
396
+ with lower_to_next():
397
+ result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs)
398
+ validate_vmap_returns_tuple_of_two_elements(result)
399
+ unwrapped_output, out_dims = result
400
+
401
+ # See NOTE [mark_dirty object identity check]
402
+ def wrap_fn(output: torch.Tensor, out_dim: int | None) -> torch.Tensor:
403
+ return (
404
+ output
405
+ if out_dim is None
406
+ else _add_batch_dim(output, out_dim, current_level)
407
+ )
408
+
409
+ return wrap_outputs_maintaining_identity(
410
+ unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims
411
+ )
412
+
413
+
414
+ def unpack_outputs(outputs: tuple[Any, ...]) -> tuple[Any, Any]:
415
+ out_dims = outputs[-1]
416
+ if isinstance(out_dims, tuple):
417
+ outputs = outputs[:-1]
418
+ else:
419
+ outputs = outputs[0]
420
+ return outputs, out_dims
421
+
422
+
423
+ def custom_function_call_vmap_generate_rule(
424
+ interpreter: VmapInterpreter,
425
+ autograd_function: type[torch.autograd.Function],
426
+ *operands: Any,
427
+ ) -> Any:
428
+ unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level())
429
+ vmapped_function = vmapify_autograd_function(
430
+ autograd_function,
431
+ in_dims,
432
+ interpreter.batch_size(),
433
+ interpreter.randomness(),
434
+ )
435
+ with interpreter.lower():
436
+ outputs = custom_function_call(vmapped_function, *unwrapped_operands)
437
+
438
+ if not isinstance(outputs, tuple):
439
+ raise AssertionError(f"expected outputs to be a tuple, got {type(outputs)}")
440
+ outputs, out_dims = unpack_outputs(outputs)
441
+ return wrap_batched(outputs, out_dims, interpreter.level())
442
+
443
+
444
+ @custom_function_call.py_impl(TransformType.Functionalize)
445
+ def custom_function_call_functionalize(
446
+ interpreter: FuncTorchInterpreter,
447
+ autograd_function: type[torch.autograd.Function],
448
+ generate_vmap_rule: bool,
449
+ *operands: Any,
450
+ ) -> Any:
451
+ raise RuntimeError("NYI: Functionalize rule for custom_function_call")
452
+
453
+
454
+ def vmapify_autograd_function(
455
+ autograd_function: type[torch.autograd.Function],
456
+ in_dims: Any,
457
+ batch_size: int,
458
+ randomness: str,
459
+ ) -> type[torch.autograd.Function]:
460
+ def forward(*operands: Any) -> Any:
461
+ outputs, out_dims = restore_vmap(
462
+ autograd_function.forward, in_dims, batch_size, randomness
463
+ )(*operands)
464
+ if isinstance(outputs, torch.Tensor):
465
+ return outputs, out_dims
466
+ else:
467
+ return *outputs, out_dims
468
+
469
+ def setup_context(ctx: Any, inputs: Any, outputs: Any) -> None:
470
+ outputs, out_dims = unpack_outputs(outputs)
471
+ key = id(Generated)
472
+
473
+ def inner(inputs: Any, outputs: Any) -> None:
474
+ # wrapped_ctx.save_for_backward will:
475
+ # - unwrap batchedtensors into (tensor, bdim)
476
+ # - save_for_backward(*unwrapped_tensors)
477
+ # - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims
478
+ wrapped_ctx = CtxCustomSave(ctx, current_level())
479
+ autograd_function.setup_context(wrapped_ctx, inputs, outputs)
480
+
481
+ # input_shapes are used for reductify later to reduce expanded gradients
482
+ # to the correct shape.
483
+ # See NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
484
+ # for more details
485
+ input_shapes = tuple(
486
+ inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs
487
+ )
488
+ if not hasattr(ctx, "_pt_input_shapes"):
489
+ # pyrefly: ignore [implicit-any]
490
+ ctx._pt_input_shapes = {}
491
+ ctx._pt_input_shapes.update({key: input_shapes})
492
+
493
+ if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"):
494
+ # pyrefly: ignore [implicit-any]
495
+ ctx._pt_saved_tensors_bdims_stack = {}
496
+ ctx._pt_saved_tensors_bdims_stack.update(
497
+ {key: (wrapped_ctx._pt_saved_tensors_bdims)}
498
+ )
499
+
500
+ # See NOTE: [Why do we need to run setup_context under a vmap?]
501
+ restore_vmap(
502
+ inner,
503
+ (in_dims, out_dims),
504
+ batch_size,
505
+ randomness,
506
+ )(inputs, outputs)
507
+
508
+ if not hasattr(ctx, "_pt_out_dims"):
509
+ # pyrefly: ignore [implicit-any]
510
+ ctx._pt_out_dims = {}
511
+ ctx._pt_out_dims.update({key: out_dims})
512
+
513
+ def jvp(ctx: Any, *tangents: Any) -> Any:
514
+ key = id(Generated)
515
+
516
+ def jvp_no_context(saved_tensors: Any, tangents: Any) -> Any:
517
+ wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
518
+ return autograd_function.jvp(wrapped_ctx, *tangents)
519
+
520
+ tangent_in_dims = get_tangents_in_dims(in_dims, tangents)
521
+ out_tangents, out_tangents_dims = restore_vmap(
522
+ jvp_no_context,
523
+ (ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims),
524
+ batch_size,
525
+ randomness,
526
+ )(ctx.saved_tensors, tangents)
527
+
528
+ result = reductify(
529
+ out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size
530
+ )
531
+ if isinstance(result, torch.Tensor):
532
+ return result, None
533
+ else:
534
+ return *result, None
535
+
536
+ def backward(ctx: Any, *grad_outputs: Any) -> Any:
537
+ key = id(Generated)
538
+ grad_outputs_ = grad_outputs[:-1]
539
+ grad_outputs_in_dims = ctx._pt_out_dims[key]
540
+
541
+ if not isinstance(grad_outputs_in_dims, tuple):
542
+ grad_outputs_in_dims = (grad_outputs_in_dims,)
543
+
544
+ grad_outputs_in_dims = tuple(
545
+ in_dim if grad_output is not None else None
546
+ for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims)
547
+ )
548
+
549
+ def backward_no_context(inputs: Any) -> Any:
550
+ saved_tensors, grad_outputs = inputs
551
+ wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
552
+ return autograd_function.backward(wrapped_ctx, *grad_outputs)
553
+
554
+ grad_ins, grad_ins_dims = restore_vmap(
555
+ backward_no_context,
556
+ ((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),),
557
+ batch_size,
558
+ randomness,
559
+ )((ctx.saved_tensors, grad_outputs_))
560
+ result = reductify(
561
+ grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key]
562
+ )
563
+ return result
564
+
565
+ name = f"Vmapped{autograd_function.__name__}"
566
+ Generated = type(
567
+ name,
568
+ (torch.autograd.Function,),
569
+ {
570
+ "forward": staticmethod(forward),
571
+ "backward": staticmethod(backward),
572
+ "jvp": staticmethod(jvp),
573
+ "setup_context": staticmethod(setup_context),
574
+ "generate_vmap_rule": True,
575
+ },
576
+ )
577
+
578
+ return Generated
579
+
580
+
581
+ # tangents might be None, so we need to replace
582
+ # the corresponding in_dims with None.
583
+ def get_tangents_in_dims(input_dims: Any, tangents: tuple[Any, ...]) -> Any:
584
+ flat_in_dims, spec = pytree.tree_flatten(input_dims)
585
+ flat_tangents = pytree.arg_tree_leaves(*tangents)
586
+ result = [
587
+ None if tangent is None else in_dim
588
+ for in_dim, tangent in zip(flat_in_dims, flat_tangents)
589
+ ]
590
+ return pytree.tree_unflatten(result, spec)
591
+
592
+
593
+ # NOTE: [Why do we need to run setup_context under a vmap?]
594
+ # Consider the following autograd.Function
595
+ #
596
+ # class Sum(torch.autograd.Function):
597
+ # @staticmethod
598
+ # def forward(x):
599
+ # return x.sum()
600
+ # @staticmethod
601
+ # def setup_context(ctx, inputs, outputs):
602
+ # ctx.x_shape = inputs[0]
603
+ # @staticmethod
604
+ # def backward(ctx, gy):
605
+ # return gy.expand(ctx.x_shape)
606
+ #
607
+ # x = torch.randn(B, 4)
608
+ # in_dims = 0
609
+ # vmap(Sum.apply, in_dims)(x)
610
+ #
611
+ # Let's assume for a moment that we didn't vmap setup_context in VmappedSum:
612
+ #
613
+ # class VmappedSum(torch.autograd.Function):
614
+ # @staticmethod
615
+ # def forward(x):
616
+ # return vmap(Sum.forward, in_dims)(x)
617
+ #
618
+ # @staticmethod
619
+ # def setup_context(ctx, inputs, outputs):
620
+ # Sum.setup_context(ctx, inputs, outputs)
621
+ #
622
+ # @staticmethod
623
+ # def backward(ctx, gy):
624
+ # def backward_no_context(gy):
625
+ # return gy.expand(ctx.x_shape)
626
+ #
627
+ # dims = (0,)
628
+ # gx = vmap(backward_no_context, dims)(gy)
629
+ # return gx
630
+ #
631
+ # We end up saving [B, 4] as x_shape. In the backward, gy has shape [B],
632
+ # and we're doing:
633
+ #
634
+ # def backward_no_context(gy):
635
+ # return gy.expand([B, 4])
636
+ #
637
+ # gx = vmap(backward_no_context, dims)(gy: "Tensor[B]")
638
+ #
639
+ # This gives us the wrong result (gx has shape [B, B, 4], but it should
640
+ # have shape [4]). Performing vmap over setup_context means the shape
641
+ # saved has shape [4] and leads to a correct result shape for gx.
642
+
643
+
644
+ # Wraps a ctx object. Forwards all attr accesses to the underlying object
645
+ # except for the attrs in _pt_attrs
646
+ class WrappedCtx:
647
+ _pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx")
648
+
649
+ def __init__(self, ctx: Any) -> None:
650
+ if not isinstance(ctx, WrappedCtx):
651
+ reserved_attrs = type(self)._pt_reserved_attrs
652
+ for name in reserved_attrs:
653
+ if not hasattr(ctx, name):
654
+ continue
655
+ raise RuntimeError(
656
+ f"PyTorch reserves the {reserved_attrs} field on ctx. "
657
+ "Please name your fields on ctx something else to avoid name "
658
+ "collision."
659
+ )
660
+ self._pt_inner_ctx = ctx
661
+
662
+ def __getattr__(self, name: str) -> Any:
663
+ return getattr(self._pt_inner_ctx, name)
664
+
665
+ def __setattr__(self, name: str, value: Any) -> None:
666
+ if name in type(self)._pt_reserved_attrs:
667
+ self.__dict__[name] = value
668
+ return
669
+ return setattr(self._pt_inner_ctx, name, value)
670
+
671
+
672
+ # Wraps ctx to create a new ctx object that overrides saved_tensors.
673
+ class CtxWithSavedTensors(WrappedCtx):
674
+ _pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs)
675
+
676
+ def __init__(self, ctx: Any, new_saved_tensors: Sequence[torch.Tensor]) -> None:
677
+ super().__init__(ctx)
678
+ self._pt_new_saved_tensors = new_saved_tensors
679
+
680
+ @property
681
+ def saved_tensors(self) -> Sequence[torch.Tensor]:
682
+ return self._pt_new_saved_tensors
683
+
684
+
685
+ class CtxCustomSave(WrappedCtx):
686
+ _pt_reserved_attrs = (
687
+ "_pt_saved_tensors_bdims",
688
+ "_pt_current_level",
689
+ *WrappedCtx._pt_reserved_attrs,
690
+ )
691
+
692
+ def __init__(self, ctx: Any, current_level: int) -> None:
693
+ super().__init__(ctx)
694
+ self._pt_saved_tensors_bdims: tuple[Any, ...] = ()
695
+ self._pt_current_level = current_level
696
+
697
+ def save_for_backward(self, *tensors: torch.Tensor) -> None:
698
+ unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
699
+ self._pt_inner_ctx.save_for_backward(*unwrapped_tensors)
700
+ self._pt_saved_tensors_bdims = bdims
701
+
702
+ def save_for_forward(self, *tensors: torch.Tensor) -> None:
703
+ unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
704
+ self._pt_inner_ctx.save_for_forward(*unwrapped_tensors)
705
+ self._pt_saved_tensors_bdims = bdims
706
+
707
+
708
+ def reductify(
709
+ grad_input: torch.Tensor | tuple[torch.Tensor, ...],
710
+ grad_input_bdim: int | tuple[int, ...],
711
+ input_bdim: int | tuple[int, ...],
712
+ batch_size: int,
713
+ target_shape_without_bdim_to_reduce_to: Any = None,
714
+ ) -> tuple[Any, ...]:
715
+ if not isinstance(grad_input, tuple):
716
+ grad_input = (grad_input,)
717
+ if not isinstance(grad_input_bdim, tuple):
718
+ grad_input_bdim = (grad_input_bdim,)
719
+ if not isinstance(input_bdim, tuple):
720
+ input_bdim = (input_bdim,)
721
+
722
+ if target_shape_without_bdim_to_reduce_to is None:
723
+ target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,)
724
+ result = tuple(
725
+ reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape)
726
+ for gi, gi_bdim, i_bdim, maybe_ishape in zip(
727
+ grad_input,
728
+ grad_input_bdim,
729
+ input_bdim,
730
+ target_shape_without_bdim_to_reduce_to,
731
+ )
732
+ )
733
+ return result
734
+
735
+
736
+ def reductify_leaf(
737
+ grad_input: torch.Tensor | None,
738
+ grad_input_bdim: int | None,
739
+ input_bdim: int | None,
740
+ batch_size: int,
741
+ target_shape_without_bdim_to_reduce_to: Any = None,
742
+ ) -> torch.Tensor | None:
743
+ if grad_input is None:
744
+ return None
745
+
746
+ if grad_input_bdim is None and input_bdim is None:
747
+ return grad_input
748
+
749
+ if grad_input_bdim is not None and input_bdim is None:
750
+ return grad_input.sum(grad_input_bdim)
751
+
752
+ # NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
753
+ # For reverse-mode AD,
754
+ # given a grad_input and input, it is valid for the user to return a
755
+ # grad_input that has a broadcasted shape when compared to the input.
756
+ # In this situation, autograd automatically reduces the grad_input to
757
+ # the shape of the input.
758
+ #
759
+ # However, when input_bdim is not None, we have problems.
760
+ #
761
+ # [example 1]
762
+ # grad_input: Tensor[3, 4], input: Tensor[B, 4]
763
+ # We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable
764
+ # from [B, 4].
765
+ #
766
+ # [example 2]
767
+ # grad_input: Tensor[3, B, 4], input: Tensor[B, 4]
768
+ # We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable
769
+ # from [B, 4].
770
+ #
771
+ # This means that we need to also reduce the grad_input to the shape of the
772
+ # input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag;
773
+ # if not-None then we do the reducing manually, otherwise, we do not do a reduction.
774
+ if input_bdim is None:
775
+ raise AssertionError("input_bdim must not be None")
776
+
777
+ if grad_input_bdim is None:
778
+ grad_input = grad_input.unsqueeze(input_bdim)
779
+ new_shape = list(grad_input.shape)
780
+ new_shape[input_bdim] = batch_size
781
+ grad_input = grad_input.expand(new_shape)
782
+ grad_input_bdim = input_bdim
783
+
784
+ if target_shape_without_bdim_to_reduce_to is not None:
785
+ return vmap(
786
+ torch.Tensor.sum_to_size,
787
+ in_dims=(grad_input_bdim, None),
788
+ out_dims=input_bdim,
789
+ )(grad_input, target_shape_without_bdim_to_reduce_to)
790
+
791
+ if input_bdim != grad_input_bdim:
792
+ grad_input = grad_input.movedim(grad_input_bdim, input_bdim)
793
+ return grad_input
794
+
795
+
796
+ def autograd_function_forward_rewritten(
797
+ original_forward: Callable[_P, _R],
798
+ original_setup_context: Callable[..., Any],
799
+ ) -> Callable[..., _R]:
800
+ def new_forward(ctx: Any, *args: _P.args, **kwargs: _P.kwargs) -> _R:
801
+ output = original_forward(*args, **kwargs)
802
+ original_setup_context(ctx, args, output)
803
+ return output
804
+
805
+ return new_forward
806
+
807
+
808
+ class AutogradFunctionApply(HigherOrderOperator):
809
+ def __init__(self) -> None:
810
+ super().__init__("autograd_function_apply")
811
+
812
+ def __call__(
813
+ self,
814
+ fwd: torch.fx.GraphModule,
815
+ bwd: torch.fx.GraphModule,
816
+ *fwd_args: Any,
817
+ **fwd_kwargs: Any,
818
+ ) -> Any:
819
+ saved_values: Iterable[Any] | None = None
820
+ dirty_idx = fwd_kwargs.get("dirty_idx", [])
821
+ dirty_idx_set = set(dirty_idx)
822
+ non_differentiable_idx = fwd_kwargs["non_differentiable_idx"]
823
+ saved_for_backward_idx = fwd_kwargs["saved_for_backward_idx"]
824
+
825
+ class ApplyTemplate(torch.autograd.Function):
826
+ @staticmethod
827
+ def forward(*args: Any, **kwargs: Any) -> Any:
828
+ nonlocal saved_values
829
+
830
+ # The Interpreter here is required to propagate metadata
831
+ # from the dynamo graph body to the local_map graph body.
832
+ # This is required for fx_traceback.annotate for work.
833
+ output, saved_values = torch.fx.Interpreter(fwd).run(*args)
834
+
835
+ # See Note [Activations with no version counter checks in eager]
836
+ # Mark tensors that came from ctx.save_for_backward with metadata.
837
+ # This allows AOT autograd to distinguish between tensors saved via
838
+ # save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x).
839
+ from torch.fx.experimental.proxy_tensor import _get_proxies
840
+
841
+ for idx, t in enumerate(saved_values):
842
+ if idx not in saved_for_backward_idx:
843
+ for proxy in _get_proxies(t):
844
+ proxy.node.meta["saved_tensor_with_no_vc_check"] = True
845
+
846
+ return output
847
+
848
+ @staticmethod
849
+ def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None:
850
+ def selected_outputs(idx: Iterable[int]) -> list[Any]:
851
+ idx_set = set(idx)
852
+ if isinstance(output, (tuple, list)):
853
+ return [x for i, x in enumerate(output) if i in idx_set]
854
+ return [output] if 0 in idx_set else []
855
+
856
+ # If users call ctx.mark_dirty() in the original fwd function.
857
+ if len(dirty_idx) > 0:
858
+ ctx.mark_dirty(*selected_outputs(dirty_idx_set))
859
+
860
+ # If users call ctx.mark_non_differentiable() in the original fwd function.
861
+ if len(non_differentiable_idx) > 0:
862
+ ctx.mark_non_differentiable(
863
+ *selected_outputs(non_differentiable_idx)
864
+ )
865
+
866
+ @staticmethod
867
+ def backward(ctx: Any, *grad: Any) -> Any:
868
+ # The Interpreter here is required to propagate metadata
869
+ # from the dynamo graph body to the local_map graph body.
870
+ # This is required for fx_traceback.annotate for work.
871
+
872
+ if saved_values is None:
873
+ raise AssertionError("saved_values must not be None")
874
+ return torch.fx.Interpreter(bwd).run(*grad, *saved_values)
875
+
876
+ return ApplyTemplate.apply(*fwd_args)
877
+
878
+
879
+ autograd_function_apply = AutogradFunctionApply()
880
+
881
+
882
+ class DynamoAutogradFunctionTraceHelper:
883
+ @staticmethod
884
+ def fwd_trace_helper(orig_fwd: Callable[_P, Any]) -> Callable[_P, Any]:
885
+ # autograd.Function forward does more than just running the forward method. Most
886
+ # of this logic is in C++. Here, we rewrite that functionality in python and let
887
+ # Dynamo trace it.
888
+ def inner(*args: _P.args, **kwargs: _P.kwargs) -> Any:
889
+ with torch.no_grad():
890
+ outs = orig_fwd(*args, **kwargs)
891
+
892
+ ctx = args[0]
893
+ dirty_tensors = getattr(ctx, "dirty_tensors", None)
894
+
895
+ def is_dirty_tensor(tensor: torch.Tensor) -> bool:
896
+ if dirty_tensors is None:
897
+ return False
898
+ return any(
899
+ tensor is dirty_tensor
900
+ for dirty_tensor in dirty_tensors
901
+ if isinstance(dirty_tensor, torch.Tensor)
902
+ )
903
+
904
+ def is_tensor_arg(tensor: torch.Tensor) -> bool:
905
+ return any(
906
+ arg is tensor for arg in args if isinstance(arg, torch.Tensor)
907
+ )
908
+
909
+ # Handle the case where if the input is passed on directly to the output, we call view_as
910
+ # Refer to https://github.com/pytorch/pytorch/blob/main/torch/csrc/autograd/custom_function.cpp#L254
911
+ if isinstance(outs, torch.Tensor):
912
+ if is_tensor_arg(outs) and not is_dirty_tensor(outs):
913
+ return outs.view_as(outs)
914
+ else:
915
+ return outs
916
+
917
+ new_outs = []
918
+ for out in outs:
919
+ if isinstance(out, torch.Tensor):
920
+ if is_tensor_arg(out) and not is_dirty_tensor(out):
921
+ new_outs.append(out.view_as(out))
922
+ else:
923
+ new_outs.append(out)
924
+ else:
925
+ new_outs.append(out)
926
+ return tuple(new_outs)
927
+
928
+ # TODO - there is missing functionality here, where
929
+ # autograd.Function overwrites the requires_grad_ of the output
930
+ # tensors depending on the `mark_non_differentiable`. Currently,
931
+ # this is handled hackily in Dynamo, where we just overwrite the
932
+ # variable trackers requires_grad. Refer to the function -
933
+ # overwrite_tensor_vt_requires_grad
934
+
935
+ return inner
.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from torch._functorch.utils import exposed_in
3
+
4
+
5
+ def batch_norm_without_running_stats(module: nn.Module) -> None:
6
+ if (
7
+ isinstance(module, nn.modules.batchnorm._BatchNorm)
8
+ and module.track_running_stats
9
+ ):
10
+ module.running_mean = None
11
+ module.running_var = None
12
+ module.num_batches_tracked = None
13
+ module.track_running_stats = False
14
+
15
+
16
+ @exposed_in("torch.func")
17
+ def replace_all_batch_norm_modules_(root: nn.Module) -> nn.Module:
18
+ """
19
+ In place updates :attr:`root` by setting the ``running_mean`` and ``running_var`` to be None and
20
+ setting track_running_stats to be False for any nn.BatchNorm module in :attr:`root`
21
+ """
22
+ # base case
23
+ batch_norm_without_running_stats(root)
24
+
25
+ for obj in root.modules():
26
+ batch_norm_without_running_stats(obj)
27
+ return root
.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import json
5
+ import operator
6
+ import os
7
+ import time
8
+ from contextlib import AbstractContextManager
9
+ from typing import Any, TYPE_CHECKING
10
+ from typing_extensions import TypeVar
11
+
12
+ import torch
13
+ from torch.profiler import profile, ProfilerActivity
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Callable, Sequence
18
+
19
+
20
+ _R = TypeVar("_R")
21
+
22
+
23
+ def synchronize() -> None:
24
+ pass
25
+
26
+
27
+ def dump_chrome_trace(
28
+ f: Callable[[tuple[Any, ...]], _R],
29
+ input_: tuple[Any, ...],
30
+ trace_filename: str,
31
+ optimize_ctx: AbstractContextManager[Any],
32
+ activities: Sequence[ProfilerActivity],
33
+ num_runs: int = 1,
34
+ devices: list[str] | None = None,
35
+ kwargs_for_f: dict[str, Any] | None = None,
36
+ kwargs_for_profiler: dict[str, Any] | None = None,
37
+ ) -> float:
38
+ """
39
+ Output the chrome trace of running f(input_, **kwargs_for_f) with [optimize_ctx]
40
+ [num_runs] times to [trace_filename].
41
+
42
+ [activities] are the activities that the profiler will record, e.g. ProfilerActivity.CUDA.
43
+ Return total runtime without the profiler
44
+
45
+ Outputs to trace_filename
46
+ """
47
+
48
+ if devices is None:
49
+ devices = ["cuda"]
50
+
51
+ global synchronize
52
+ if devices != ["cpu"] and torch.accelerator.is_available():
53
+ synchronize = torch.accelerator.synchronize
54
+
55
+ if kwargs_for_f is None:
56
+ kwargs_for_f = {}
57
+ if kwargs_for_profiler is None:
58
+ kwargs_for_profiler = {}
59
+
60
+ with optimize_ctx:
61
+ torch.manual_seed(1337)
62
+ for _ in range(5): # warmup runs
63
+ f(input_, **kwargs_for_f)
64
+ synchronize()
65
+ torch.manual_seed(1337)
66
+ t0 = time.perf_counter()
67
+ for _ in range(num_runs):
68
+ f(input_, **kwargs_for_f)
69
+ synchronize()
70
+ t1 = time.perf_counter()
71
+ timing = t1 - t0
72
+
73
+ with profile(activities=activities, **kwargs_for_profiler) as prof:
74
+ with optimize_ctx:
75
+ synchronize()
76
+ torch.manual_seed(1337)
77
+ for _ in range(num_runs):
78
+ f(input_, **kwargs_for_f)
79
+ synchronize()
80
+ prof.export_chrome_trace(trace_filename)
81
+
82
+ return timing
83
+
84
+
85
+ def get_chrome_trace_events(filename: str) -> list[dict[str, Any]]:
86
+ with open(filename) as f:
87
+ data = json.load(f)
88
+ events = data["traceEvents"]
89
+ return events
90
+
91
+
92
+ def is_gpu_compute_event(event: dict[str, Any]) -> bool:
93
+ global gpu_pids
94
+ return (
95
+ "pid" in event
96
+ and event["pid"] in gpu_pids
97
+ and "ph" in event
98
+ and event["ph"] == "X"
99
+ )
100
+
101
+
102
+ def get_sorted_gpu_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
103
+ sorted_gpu_events: list[dict[str, Any]] = []
104
+ for event in events:
105
+ if not is_gpu_compute_event(event):
106
+ continue
107
+ sorted_gpu_events.append(event)
108
+ return sorted(sorted_gpu_events, key=operator.itemgetter("ts"))
109
+
110
+
111
+ def get_duration(sorted_gpu_events: list[dict[str, Any]]) -> int:
112
+ if len(sorted_gpu_events) == 0:
113
+ return 0
114
+ event = sorted_gpu_events[0]
115
+ current_end_time = event["ts"] + event["dur"]
116
+ total_duration = event["dur"]
117
+ for event in sorted_gpu_events[1:]:
118
+ start_time = max(event["ts"], current_end_time)
119
+ end_time = event["ts"] + event["dur"]
120
+ total_duration = total_duration + max(end_time - start_time, 0)
121
+ current_end_time = max(current_end_time, end_time)
122
+ return total_duration
123
+
124
+
125
+ def get_sorted_gpu_mm_conv_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
126
+ def is_mm_conv_event(event: dict[str, Any]) -> bool:
127
+ return "name" in event and (
128
+ "gemm" in event["name"]
129
+ or "conv" in event["name"]
130
+ or "cutlass" in event["name"]
131
+ or "wgrad" in event["name"]
132
+ )
133
+
134
+ gpu_events = get_sorted_gpu_events(events)
135
+ sorted_events: list[dict[str, Any]] = []
136
+ for event in gpu_events:
137
+ if not is_mm_conv_event(event):
138
+ continue
139
+ sorted_events.append(event)
140
+ return sorted_events
141
+
142
+
143
+ gpu_pids: list[Any] = []
144
+
145
+
146
+ def compute_utilization(filename: str, total_length: float) -> tuple[float, float]:
147
+ """
148
+ Process the chrome traces outputs by the pytorch profiler to compute GPU Utilization
149
+ and percent of times spent on matmul and convolution
150
+
151
+ Args:
152
+ filename(str): Name of chrome traces file produced by pytorch profiler
153
+
154
+ total_length(float): total length of the process without profiler in second
155
+
156
+ Return:
157
+ tuple: (GPU Utilization, percent of time spent on matmul and convolution)
158
+ """
159
+ events = get_chrome_trace_events(filename)
160
+
161
+ # get pids of GPU events
162
+ global gpu_pids
163
+ gpu_pids = []
164
+ for event in events:
165
+ if "name" not in event:
166
+ continue
167
+ if event["name"] == "process_labels" and "GPU" in event["args"]["labels"]:
168
+ gpu_pids.append(event["pid"])
169
+
170
+ total_length = total_length * 1e6
171
+ sorted_gpu_events = get_sorted_gpu_events(events)
172
+ utilization = get_duration(sorted_gpu_events) / total_length
173
+
174
+ sorted_gpu_mm_conv_events = get_sorted_gpu_mm_conv_events(events)
175
+ mm_conv_utilization = get_duration(sorted_gpu_mm_conv_events) / total_length
176
+
177
+ return utilization, mm_conv_utilization
178
+
179
+
180
+ def benchmark_utilization(
181
+ f: Callable[[tuple[Any, ...]], _R],
182
+ input_: tuple[Any, ...],
183
+ trace_folder: str,
184
+ optimize_ctx: AbstractContextManager[Any] | None = None,
185
+ trace_file_name: str = "tmp_chrome_trace",
186
+ num_runs: int = 1,
187
+ ) -> tuple[float, float]:
188
+ """
189
+ Benchmark the GPU Utilization and percent of time spent on matmul and convolution operations of
190
+ running f(input_, **kwargs_for_f) with [optimize_ctx] [num_runs] times.
191
+ It will produce a chrome trace file in trace_folder/trace_file_name.json
192
+
193
+ Example:
194
+
195
+ ```
196
+ def f(a):
197
+ return a.sum()
198
+
199
+
200
+ a = torch.rand(2**20, device="cuda")
201
+ utilization, mm_conv_utilization = benchmark_utilization(
202
+ f, a, "tmp", trace_file_name="tmp_chrome_trace"
203
+ )
204
+ ```
205
+
206
+ Args:
207
+ f: function to benchmark
208
+
209
+ input_: input to :attr:`f`
210
+
211
+ trace_folder: name of the folder to store the chrome trace
212
+
213
+ optimize_ctx: the context in which f will run
214
+
215
+ trace_file_name: name of the dumped chrome trace file, default to "tmp_chrome_trace"
216
+
217
+ num_runs: number of times to run f, excluding the warm-up runs, default to 1.
218
+
219
+ Return:
220
+ tuple: (GPU Utilization, percent of time spent on matmul and convolution)
221
+
222
+ """
223
+ isExist = os.path.exists(trace_folder)
224
+ if not isExist:
225
+ os.makedirs(trace_folder)
226
+ print("create folder " + trace_folder)
227
+
228
+ if optimize_ctx is None:
229
+ optimize_ctx = contextlib.nullcontext()
230
+
231
+ chrome_trace_file_name = os.path.join(trace_folder, trace_file_name + ".json")
232
+ total_length = dump_chrome_trace(
233
+ f,
234
+ input_,
235
+ chrome_trace_file_name,
236
+ optimize_ctx,
237
+ [ProfilerActivity.CUDA],
238
+ num_runs=num_runs,
239
+ devices=["cuda"],
240
+ )
241
+ utilization, mm_conv_utilization = compute_utilization(
242
+ chrome_trace_file_name, total_length
243
+ )
244
+
245
+ return utilization, mm_conv_utilization
.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import operator
5
+ import struct
6
+ from typing import Any, TYPE_CHECKING
7
+
8
+ import sympy
9
+
10
+ import torch
11
+ import torch.fx as fx
12
+ from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
13
+ from torch.multiprocessing.reductions import StorageWeakRef
14
+ from torch.utils import _pytree as pytree
15
+ from torch.utils._pytree import tree_flatten
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable, Hashable
20
+
21
+ from torch._ops import OpOverloadPacket
22
+ from torch.utils._pytree import TreeSpec
23
+
24
+ aten = torch.ops.aten
25
+
26
+
27
+ @dataclasses.dataclass(frozen=True)
28
+ class _ScalarKey:
29
+ tag: str
30
+ bits: bytes
31
+
32
+
33
+ def _normalize_cse_arg(val: Any) -> Any:
34
+ # Python float hash/eq is not value-identity: nan != nan (hash(nan) is
35
+ # id-based) while -0.0 == 0.0 and hashes equal. Key by bit pattern instead.
36
+ if type(val) is float:
37
+ return _ScalarKey("float", struct.pack(">d", val))
38
+ if type(val) is complex:
39
+ return _ScalarKey("complex", struct.pack(">dd", val.real, val.imag))
40
+ return val
41
+
42
+
43
+ def get_aten_target(node: fx.Node) -> OpOverloadPacket | Callable[..., Any] | str:
44
+ if hasattr(node.target, "overloadpacket"):
45
+ return node.target.overloadpacket
46
+ return node.target
47
+
48
+
49
+ rand_ops = [
50
+ aten.dropout,
51
+ aten._fused_dropout,
52
+ aten._standard_gamma,
53
+ aten.bernoulli,
54
+ aten.multinomial,
55
+ aten.native_dropout,
56
+ aten.normal,
57
+ aten.poisson,
58
+ aten.binomial,
59
+ aten.rrelu,
60
+ aten.rand_like,
61
+ aten.rand,
62
+ aten.randint,
63
+ aten.randn,
64
+ aten.randperm,
65
+ ]
66
+
67
+
68
+ # return a new copy of torch.fx.graph.Graph with CSE applied to the input graph
69
+ def fx_graph_cse(
70
+ fx_g: torch.fx.graph.Graph,
71
+ extra_node_key: Callable[[fx.Node], Hashable] | None = None,
72
+ ) -> fx.Graph:
73
+ new_graph = fx.Graph()
74
+ env: dict[
75
+ fx.Node, fx.Node
76
+ ] = {} # map from node in the old graph to node in the new graph
77
+ hash_env: dict[
78
+ tuple[Any, Hashable | None, int], fx.Node
79
+ ] = {} # map from hash to a node in the new graph
80
+ token_map: dict[
81
+ tuple[Any, Hashable | None, int], dict[str, Any]
82
+ ] = {} # map from hash to token
83
+
84
+ from torch._inductor.pattern_matcher import (
85
+ compute_mutation_region_ids,
86
+ same_mutation_regions,
87
+ )
88
+
89
+ compute_mutation_region_ids(fx_g) # type: ignore[arg-type]
90
+
91
+ # Make a set of separate storages returned from the output, which will be preserved
92
+ # when pruning. This prevents us from deduplicating returned tensors which have
93
+ # experienced identical operations, but are separate data structures in eager mode.
94
+ output_node: fx.Node = list(fx_g.nodes)[-1]
95
+ if output_node.op != "output":
96
+ raise AssertionError(
97
+ f"expected output_node.op to be 'output', got '{output_node.op}'"
98
+ )
99
+
100
+ def checkable_node(node: fx.Node) -> bool:
101
+ """We can evaluate only nodes that represent tensors with defined storage."""
102
+ if "val" not in node.meta or not isinstance(node.meta["val"], torch.Tensor):
103
+ return False
104
+
105
+ try:
106
+ node.meta["val"].untyped_storage()
107
+ except NotImplementedError:
108
+ return False
109
+
110
+ return True
111
+
112
+ def custom_context_key(node: fx.Node) -> tuple[int, int | None, int | None]:
113
+ custom = node.meta.get("custom", {})
114
+ return (
115
+ custom.get("stream", 0),
116
+ custom.get("mempool"),
117
+ custom.get("mempool_device"),
118
+ )
119
+
120
+ output_storages = {
121
+ StorageWeakRef(n.meta["val"].untyped_storage())
122
+ for n in output_node.all_input_nodes
123
+ if checkable_node(n)
124
+ }
125
+ nodes_that_alias_outputs = {
126
+ n
127
+ for n in fx_g.nodes
128
+ if checkable_node(n)
129
+ and StorageWeakRef(n.meta["val"].untyped_storage()) in output_storages
130
+ }
131
+
132
+ # A node used as the mutable base of a functional-wrapper op is a distinct
133
+ # mutable buffer. Two identical factory ops feeding distinct bases (e.g. the
134
+ # forward and backward ``aten.full`` from a pair of ``ones_like`` calls) must
135
+ # not be CSE-merged, or the later mutation aliases a buffer that still has a
136
+ # live downstream view and reinplacing fails (mirrors the aten.empty
137
+ # exclusion below). See pytorch/pytorch#170160.
138
+ from torch._higher_order_ops.auto_functionalize import get_mutable_args
139
+ from torch._higher_order_ops.triton_kernel_wrap import (
140
+ triton_kernel_wrapper_functional,
141
+ )
142
+
143
+ def _add_base(node: Any, bases: set[fx.Node]) -> None:
144
+ for b in node if isinstance(node, (list, tuple)) else (node,):
145
+ if isinstance(b, fx.Node):
146
+ bases.add(b)
147
+
148
+ nodes_used_as_mutation_base: set[fx.Node] = set()
149
+ for n in fx_g.find_nodes(
150
+ op="call_function", target=torch.ops.higher_order.auto_functionalized_v2
151
+ ):
152
+ # v2 lists its mutable buffers explicitly in ``_all_bases``.
153
+ for base in n.kwargs.get("_all_bases", ()):
154
+ _add_base(base, nodes_used_as_mutation_base)
155
+ for n in fx_g.find_nodes(
156
+ op="call_function", target=torch.ops.higher_order.auto_functionalized
157
+ ):
158
+ # v1 has no ``_all_bases``; the mutated tensors are the args named by the
159
+ # wrapped op's schema (``_mutable_op`` is the first positional).
160
+ mutable_op = n.args[0]
161
+ mutable_args_names, _ = get_mutable_args(mutable_op)
162
+ for name in mutable_args_names:
163
+ _add_base(n.kwargs.get(name), nodes_used_as_mutation_base)
164
+ for n in fx_g.find_nodes(
165
+ op="call_function", target=triton_kernel_wrapper_functional
166
+ ):
167
+ inner_kwargs = n.kwargs.get("kwargs", {})
168
+ for name in n.kwargs.get("tensors_to_clone", ()):
169
+ _add_base(inner_kwargs.get(name), nodes_used_as_mutation_base)
170
+
171
+ for n in fx_g.nodes:
172
+ # The placeholder, output, and get_attr nodes are copied to the new graph without change
173
+ # do not CSE away random operations
174
+ if (
175
+ n.op == "placeholder"
176
+ or n.op == "output"
177
+ or n.op == "get_attr"
178
+ or n.is_impure()
179
+ or get_aten_target(n) in rand_ops
180
+ # aten.empty is non-deterministic, so don't CSE it.
181
+ # Also, aten.empty is almost always fusible into its consumer,
182
+ # so it's not worth CSEing.
183
+ or get_aten_target(n) is aten.empty
184
+ or n in nodes_that_alias_outputs
185
+ # Keep distinct functional-wrapper mutation bases independent.
186
+ or n in nodes_used_as_mutation_base
187
+ # This CSE pass currently doesn't handle re-propagation of unbacked
188
+ # meta where it'll sometimes eliminate a _local_scalar_dense but not
189
+ # replace the meta of downstream users. eg. one bug we've seen is:
190
+ #
191
+ # _local_scalar_dense_11: "Sym(u14)" = torch.ops.aten._local_scalar_dense.default(select_10);
192
+ # sym_sum_2: "Sym(u19 + u20 + u21)" = torch.sym_sum((_local_scalar_dense_11, _local_scalar_dense_12, _local_scalar_dense_13))
193
+ #
194
+ # Notice how _local_scalar_dense_11 is u14 but sym_sum_2's meta is incorrectly the old
195
+ # pre-cse value of u19.
196
+ or (
197
+ "val" in n.meta
198
+ and isinstance(n.meta["val"], sympy.Symbol)
199
+ and free_unbacked_symbols(n.meta["val"])
200
+ )
201
+ ):
202
+ new_node = new_graph.node_copy(n, lambda x: env[x])
203
+ env[n] = new_node
204
+ else: # n.op == 'call_function', should never see n.op == 'call_module' or 'call_method'
205
+ # substitute args and kwargs members to their mapping in env if exists
206
+ # specs can be used to reconstruct nested list/dictionaries
207
+ def substitute(
208
+ arg_list: list[Any] | tuple[Any, ...],
209
+ ) -> tuple[tuple[Any, ...], TreeSpec]:
210
+ arg_list, spec = tree_flatten(arg_list)
211
+ for i in range(len(arg_list)):
212
+ v = arg_list[i]
213
+ if isinstance(v, torch.fx.node.Node) and v in env:
214
+ arg_list[i] = env[v]
215
+ if isinstance(v, (torch.SymBool, torch.SymInt, torch.SymFloat)):
216
+ arg_list[i] = v.node
217
+ arg_list[i] = _normalize_cse_arg(arg_list[i])
218
+ return tuple(arg_list), spec
219
+
220
+ args, args_spec = substitute(n.args)
221
+ kwargs, kwargs_spec = substitute(n.kwargs)
222
+
223
+ # each token corresponds to a unique node
224
+ # nodes with the same token can be substituted
225
+ extra_key = extra_node_key(n) if extra_node_key is not None else None
226
+ token = {
227
+ "target": n.target,
228
+ "extra_key": extra_key,
229
+ "args": args,
230
+ "args_spec": args_spec,
231
+ "kwargs": kwargs,
232
+ "kwargs_spec": kwargs_spec,
233
+ "custom_context": custom_context_key(n),
234
+ }
235
+
236
+ # hash substituted args to a number, do not hash specs because specs are not hashable
237
+ # We need to add type into hash to avoid situations like:
238
+ # hash((primals_2, 1.0)) == hash((primals_2, 1))
239
+ hash_arg = hash(
240
+ (tuple((a, type(a)) for a in args), tuple((a, type(a)) for a in kwargs))
241
+ )
242
+ hash_val = (n.target, extra_key, hash_arg)
243
+
244
+ # check if a node has a substitute and can be eliminated
245
+ hash_val_in_hash_env = hash_val in hash_env
246
+ overwrite_due_to_mutation = False
247
+ if hash_val_in_hash_env and token_map[hash_val] == token:
248
+ duplicate_n_prev = hash_env[hash_val]
249
+ if same_mutation_regions(n, duplicate_n_prev):
250
+ env[n] = duplicate_n_prev
251
+ continue
252
+ else:
253
+ # any futures duplicates should replace with n, not duplicate_n_prev
254
+ overwrite_due_to_mutation = True
255
+
256
+ new_node = new_graph.node_copy(n, lambda x: env[x])
257
+ env[n] = new_node
258
+ if overwrite_due_to_mutation or not hash_val_in_hash_env:
259
+ hash_env[hash_val] = new_node
260
+ token_map[hash_val] = token
261
+
262
+ return new_graph
263
+
264
+
265
+ def raise_getitems(gm: fx.GraphModule) -> fx.GraphModule:
266
+ # Pre-create a list of nodes to iterate over, as modifying the node order
267
+ # during the loop can lead to infinite loops if not handled properly.
268
+ getitem_nodes = list(
269
+ gm.graph.find_nodes(op="call_function", target=operator.getitem)
270
+ )
271
+
272
+ # loop through getitem nodes in the graph and raise them to the parent node
273
+ # in reverse order to preserve their original relative order
274
+ for node in reversed(getitem_nodes):
275
+ if len(node.all_input_nodes) != 1:
276
+ raise AssertionError(
277
+ f"expected node {node.name} to have 1 input node, got {len(node.all_input_nodes)}"
278
+ )
279
+ parent = node.all_input_nodes[0]
280
+ parent.append(node)
281
+
282
+ gm.recompile()
283
+ return gm
284
+
285
+
286
+ def strip_overloads(gm: fx.GraphModule) -> None:
287
+ """
288
+ Modifies the target of graph nodes in :attr:`gm` to strip overloads.
289
+
290
+ Args:
291
+ gm(fx.GraphModule): The input Fx graph module to be modified
292
+ """
293
+ for node in gm.graph.nodes:
294
+ if isinstance(node.target, torch._ops.OpOverload):
295
+ node.target = node.target.overloadpacket
296
+ gm.recompile()
297
+
298
+
299
+ def get_placeholders(graph: fx.Graph) -> list[Any]:
300
+ return graph.find_nodes(op="placeholder")
301
+
302
+
303
+ def get_outputs(graph: fx.Graph) -> list[fx.Node]:
304
+ for node in graph.find_nodes(op="output"):
305
+ return pytree.tree_leaves(node.args[0])
306
+ raise AssertionError("No output node found")
.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import logging
5
+ import os
6
+ import pickle
7
+ import random
8
+ from contextlib import contextmanager
9
+ from functools import partial
10
+ from typing import Any, TYPE_CHECKING
11
+ from typing_extensions import ParamSpec, TypeVar
12
+
13
+ import sympy
14
+
15
+ import torch
16
+ import torch.fx as fx
17
+ import torch.nn as nn
18
+ import torch.utils._pytree as pytree
19
+ from torch import SymInt
20
+ from torch._decomp import get_decompositions
21
+ from torch.fx.experimental.symbolic_shapes import bind_symbols
22
+
23
+ from .aot_autograd import aot_function, aot_module, make_boxed_compiler
24
+ from .compile_utils import strip_overloads
25
+ from .partitioners import (
26
+ default_partition,
27
+ draw_graph,
28
+ min_cut_rematerialization_partition,
29
+ )
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import Callable, Generator, Sequence
34
+
35
+ from torch.fx.node import Node
36
+ from torch.types import IntLikeType
37
+
38
+
39
+ _P = ParamSpec("_P")
40
+ _R = TypeVar("_R")
41
+
42
+ log = logging.getLogger(__name__)
43
+
44
+
45
+ # These canonicalizations are needed here (and not decompositions), as the ops
46
+ # we're trying to canonicalize to CompositeImplicitAutograd.
47
+ def _canonicalize(fx_g: fx.GraphModule) -> fx.GraphModule:
48
+ for node in fx_g.graph.find_nodes(
49
+ op="call_function", target=torch.ops.aten._to_copy
50
+ ):
51
+ node.target = torch.ops.aten.to
52
+ fx_g.recompile()
53
+ return fx_g
54
+
55
+
56
+ @contextmanager
57
+ def _disable_jit_autocast() -> Generator[None, None, None]:
58
+ # pyrefly: ignore [missing-attribute]
59
+ old_jit_autocast_flag = torch._C._jit_set_autocast_mode(False)
60
+ try:
61
+ yield
62
+ finally:
63
+ # pyrefly: ignore [missing-attribute]
64
+ torch._C._jit_set_autocast_mode(old_jit_autocast_flag)
65
+
66
+
67
+ @make_boxed_compiler
68
+ def ts_compile(fx_g: fx.GraphModule, inps: Sequence[Any]) -> torch.jit.ScriptModule:
69
+ """
70
+ Compiles the :attr:`fx_g` with Torchscript compiler.
71
+
72
+ .. warning::
73
+ This API is experimental and likely to change.
74
+
75
+ Args:
76
+ fx_g(fx.GraphModule): The input Fx graph module to be compiled.
77
+
78
+ Returns:
79
+ Torch scripted model.
80
+ """
81
+
82
+ from torch.fx._lazy_graph_module import _unwrap_lazy_graph_module
83
+
84
+ fx_g = _unwrap_lazy_graph_module(fx_g)
85
+
86
+ with _disable_jit_autocast():
87
+ strip_overloads(fx_g)
88
+
89
+ for node in fx_g.graph.find_nodes(
90
+ op="call_function", target=torch.ops.aten._to_copy
91
+ ):
92
+ if len(node.args) == 1 and len(node.kwargs) == 1 and "dtype" in node.kwargs:
93
+ node.target = torch.ops.aten.to
94
+
95
+ for node in fx_g.graph.nodes:
96
+ new_kwargs = {}
97
+ for k, v in node.kwargs.items():
98
+ if isinstance(v, torch.device):
99
+ v = v.type
100
+ new_kwargs[k] = v
101
+ node.kwargs = new_kwargs
102
+
103
+ fx_g.graph.lint()
104
+
105
+ fx_g.recompile()
106
+
107
+ f = torch.jit.script(fx_g)
108
+
109
+ # pyrefly: ignore [missing-attribute]
110
+ torch._C._jit_pass_remove_mutation(f.graph)
111
+
112
+ f = torch.jit.freeze(f.eval())
113
+ f = torch.jit.optimize_for_inference(f)
114
+ if not any(torch._subclasses.fake_tensor.is_fake_tensor(t) for t in inps):
115
+ f(*inps)
116
+ return f
117
+
118
+
119
+ def _draw_graph_compile(
120
+ fx_g: fx.GraphModule, _: Any, name: str, clear_meta: bool = True
121
+ ) -> fx.GraphModule:
122
+ print(fx_g.code)
123
+ draw_graph(fx_g, name, clear_meta=clear_meta)
124
+ return fx_g
125
+
126
+
127
+ def draw_graph_compile(
128
+ name: str,
129
+ ) -> Callable[[fx.GraphModule, list[Any]], fx.GraphModule]:
130
+ return make_boxed_compiler(partial(_draw_graph_compile, name=name))
131
+
132
+
133
+ @make_boxed_compiler
134
+ def nop(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule:
135
+ """
136
+ Returns the :attr:`fx_g` Fx graph module as it is. This is a no-op compiler
137
+ and can be used to check accuracy.
138
+
139
+ .. warning::
140
+ This API is experimental and likely to change.
141
+
142
+ """
143
+ return fx_g
144
+
145
+
146
+ class DebugInterpreter(fx.Interpreter):
147
+ def run(
148
+ self,
149
+ *args: Any,
150
+ initial_env: dict[Node, Any] | None = None,
151
+ enable_io_processing: bool = True,
152
+ ) -> Any:
153
+ self.symbol_mapping = bind_symbols(
154
+ # pyrefly: ignore[bad-argument-type]
155
+ self.module,
156
+ *args,
157
+ )
158
+ return super().run(
159
+ *args, initial_env=initial_env, enable_io_processing=enable_io_processing
160
+ )
161
+
162
+ def run_node(self, n: Node) -> Any:
163
+ def subst_symint(ni: IntLikeType) -> int:
164
+ if not isinstance(ni, SymInt):
165
+ return ni
166
+ r = sympy.expand(ni.node.expr.xreplace(self.symbol_mapping))
167
+ if not r.is_number:
168
+ raise AssertionError(f"expected r to be a number, got {r}")
169
+ return int(r)
170
+
171
+ def subst_symint_tuple(nis: tuple[IntLikeType, ...]) -> tuple[int, ...]:
172
+ return tuple(subst_symint(ni) for ni in nis)
173
+
174
+ def check_significant_strides(a: torch.Tensor, b: torch.Tensor) -> bool:
175
+ if subst_symint(a.numel()) > 0:
176
+ for idx in range(a.ndim):
177
+ if (
178
+ subst_symint(a.stride(idx)) != b.stride(idx)
179
+ and subst_symint(a.size(idx)) > 1
180
+ ):
181
+ return False
182
+ return True
183
+
184
+ def check(nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str]) -> None:
185
+ if not callable(desc):
186
+ raise AssertionError(f"expected desc to be callable, got {type(desc)}")
187
+ if nv.dtype != rv.dtype:
188
+ raise AssertionError(f"{desc()}: {nv.dtype} != {rv.dtype}")
189
+ if subst_symint_tuple(nv.size()) != rv.size():
190
+ raise AssertionError(
191
+ f"{desc()}: {nv.size()} aka {subst_symint_tuple(nv.size())} != {rv.size()}"
192
+ )
193
+ same_strides = check_significant_strides(nv, rv)
194
+ if not same_strides:
195
+ raise AssertionError(
196
+ f"{desc()}: {nv.stride()} aka {subst_symint_tuple(nv.stride())} != {rv.stride()}"
197
+ )
198
+
199
+ r = super().run_node(n)
200
+ if "val" in n.meta:
201
+ n_vals, _n_spec = pytree.tree_flatten(n.meta["val"])
202
+ r_vals, _r_spec = pytree.tree_flatten(r)
203
+ # TODO: There is some sort of problem where we record that an
204
+ # operator returned a tuple/list, and then later it turns out the
205
+ # real version of the operator returned a list/tuple. Need to
206
+ # figure out what's actually going on here, the error itself is
207
+ # harmless enough as we only getitem out the outputs.
208
+ # assert n_spec == r_spec, f"{n_spec} != {r_spec}"
209
+ if len(n_vals) != len(r_vals):
210
+ raise AssertionError(f"{len(n_vals)} != {len(r_vals)}")
211
+ for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals):
212
+ if not isinstance(rv, torch.Tensor):
213
+ continue
214
+ check(nv, rv, lambda: f"output {i} where {self.symbol_mapping}")
215
+ return r
216
+
217
+
218
+ @make_boxed_compiler
219
+ def debug_nop(
220
+ fx_g: fx.GraphModule, _: Any
221
+ ) -> Callable[[DebugInterpreter, Any, dict[Node, Any] | None, bool], Any]:
222
+ """
223
+ Returns a (slow) interpreter over the FX graph module that also checks
224
+ various debugging properties (e.g., that tracing strides matched real
225
+ strides.)
226
+ """
227
+ return DebugInterpreter(fx_g).run
228
+
229
+
230
+ @make_boxed_compiler
231
+ def simple_ts_compile(fx_g: fx.GraphModule, _: Any) -> torch.jit.ScriptModule:
232
+ strip_overloads(fx_g)
233
+ f = torch.jit.script(fx_g)
234
+ f = torch.jit.freeze(f.eval())
235
+ return f
236
+
237
+
238
+ def nnc_jit(f: Callable[..., Any]) -> Callable[..., Any]:
239
+ return aot_function(f, simple_ts_compile)
240
+
241
+
242
+ aten = torch.ops.aten
243
+ default_decompositions = {
244
+ aten.detach,
245
+ aten.gelu_backward,
246
+ aten.leaky_relu_backward,
247
+ aten.sigmoid_backward,
248
+ aten.threshold_backward,
249
+ aten.hardtanh_backward,
250
+ aten.hardsigmoid_backward,
251
+ aten.hardswish_backward,
252
+ aten.tanh_backward,
253
+ aten.silu_backward,
254
+ aten.elu_backward,
255
+ aten.cudnn_batch_norm,
256
+ aten.cudnn_batch_norm_backward,
257
+ aten.masked_fill.Scalar,
258
+ aten.masked_fill.Tensor,
259
+ aten.elu,
260
+ aten.leaky_relu,
261
+ aten.hardtanh,
262
+ aten.hardswish,
263
+ aten.hardsigmoid,
264
+ aten.conj_physical,
265
+ aten.is_same_size,
266
+ }
267
+
268
+ # pyrefly: ignore[bad-argument-type]
269
+ default_decompositions = get_decompositions(default_decompositions)
270
+
271
+
272
+ @make_boxed_compiler
273
+ def print_compile(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule:
274
+ print(fx_g.code)
275
+ return fx_g
276
+
277
+
278
+ def memory_efficient_fusion(
279
+ fn: Callable[_P, _R] | nn.Module,
280
+ **kwargs: Any,
281
+ ) -> Callable[_P, _R] | nn.Module:
282
+ """
283
+ Wrapper function over :func:`aot_function` and :func:`aot_module` to perform
284
+ memory efficient fusion. It uses the
285
+ :func:`min_cut_rematerialization_partition` partitioner to perform efficient
286
+ recomputation. It uses NVFuser to compile the generated forward and backward
287
+ graphs.
288
+
289
+ .. warning::
290
+ This API is experimental and likely to change.
291
+
292
+ Args:
293
+ fn (Union[Callable, nn.Module]): A Python function or a ``nn.Module``
294
+ that takes one or more arguments. Must return one or more Tensors.
295
+ **kwargs: Any other overrides you want to make to the settings
296
+
297
+ Returns:
298
+ Returns a ``Callable`` or ``nn.Module`` that retains the eager behavior
299
+ of the original :attr:`fn`, but whose forward and backward graphs have
300
+ gone through recomputation optimizations, and the graphs have been
301
+ compiled with nvfuser.
302
+
303
+ """
304
+ config = {
305
+ "fw_compiler": ts_compile,
306
+ "bw_compiler": ts_compile,
307
+ "partition_fn": min_cut_rematerialization_partition,
308
+ "decompositions": default_decompositions,
309
+ }
310
+ config.update(kwargs)
311
+ if isinstance(fn, torch.nn.Module):
312
+ return aot_module(fn, **config) # pyrefly: ignore[bad-argument-type]
313
+ else:
314
+ return aot_function(fn, **config) # pyrefly: ignore[bad-argument-type]
315
+
316
+
317
+ def debug_compile(
318
+ fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]
319
+ ) -> torch.jit.ScriptModule:
320
+ fx_g.to_folder("foo")
321
+ print(
322
+ f"""
323
+ ##############################################################
324
+ # To minimize FX graph, copy and paste the below and run it #
325
+ ##############################################################
326
+
327
+ import torch
328
+ import torch.fx as fx
329
+ from functorch.compile import minifier, check_nvfuser_subprocess, check_nvfuser_correctness_subprocess
330
+
331
+ inps = {[(i.shape, i.dtype) for i in inps]}
332
+ inps = [torch.ones(shape, dtype=dtype, device='cuda') for (shape, dtype) in inps]
333
+ from foo import FxModule
334
+ mod = FxModule().cuda()
335
+
336
+ with torch.jit.fuser("fuser2"):
337
+ # check_nvfuser_subprocess can be replaced with check_nvfuser_correctness_subprocess
338
+ minifier(fx.symbolic_trace(mod), inps, check_nvfuser_subprocess)
339
+ """
340
+ )
341
+ # pyrefly: ignore[missing-import, missing-module-attribute]
342
+ from foo import FxModule
343
+
344
+ FxModule().cuda()(*inps)
345
+
346
+ return ts_compile(fx_g, inps)
347
+
348
+
349
+ graph_index: int = 0
350
+
351
+
352
+ def get_inputs(input_data_path: str) -> list[torch.Tensor]:
353
+ """
354
+ Return a random input for the given inputs meta generated from _save_fx_default.
355
+ """
356
+ inputs: list[torch.Tensor] = []
357
+ with open(input_data_path, "rb") as f:
358
+ inputs_meta = pickle.load(f)
359
+ inputs = []
360
+ for meta in inputs_meta:
361
+ if len(meta) == 1:
362
+ type = meta
363
+ input_ = type(random.random())
364
+ else:
365
+ type, shape, _stride, dtype, device = meta
366
+ if dtype in {
367
+ torch.int,
368
+ torch.int32,
369
+ torch.int64,
370
+ torch.bool,
371
+ torch.int,
372
+ torch.uint8,
373
+ int,
374
+ float,
375
+ }:
376
+ input_ = torch.randint(0, 1, shape, dtype=dtype, device=device)
377
+ else:
378
+ input_ = torch.rand(shape, dtype=dtype, device=device)
379
+ inputs.append(input_)
380
+ return inputs
381
+
382
+
383
+ def _save_fx_default(
384
+ current_name: str,
385
+ folder_name: str,
386
+ dump_example_input: bool,
387
+ gm: torch.fx.GraphModule,
388
+ example_inputs: list[torch.Tensor],
389
+ ) -> nn.Module:
390
+ """
391
+ The forward, backward, and joint computation graph will be stored in
392
+ {folder_name}/{current_name}/{current_name}_forward_{graph_index},
393
+ {folder_name}/{current_name}/{current_name}_backward_{graph_index}, and
394
+ {folder_name}/{current_name}/{current_name}_joint_{graph_index} respectively.
395
+ The input shape of the graphs will be stored in the .input files.
396
+ These files can be loaded with pickle,
397
+ and is a list of format (type, shape, stride, dtype, device).
398
+ In the case of type = int or float, it is just (type,).
399
+ For joint graph input, it is a nested list [[],[]]
400
+ where the two inner lists have the same format.
401
+ If dump_example_input is True, example_inputs will be stored in .pt file.
402
+ Since each function might produce multiple graphs,
403
+ the graph_index is used to distinguish different graphs
404
+ """
405
+ from functorch.compile import aot_module_simplified
406
+
407
+ def get_input_meta(args: Any) -> list[Any]:
408
+ input_meta = []
409
+ if len(args) > 0 and isinstance(args[0], tuple): # joint input
410
+ input_meta += get_input_meta(args[0])
411
+ input_meta += get_input_meta(args[1])
412
+ return input_meta
413
+ for arg in args:
414
+ if type(arg) is int or type(arg) is float:
415
+ input_meta.append((type(arg),))
416
+ else:
417
+ input_meta.append(
418
+ (type(arg), arg.shape, arg.stride(), arg.dtype, arg.device)
419
+ )
420
+ return input_meta
421
+
422
+ def graph_saver_helper(
423
+ gm_to_save: fx.GraphModule, args: Any, type_name: str
424
+ ) -> None:
425
+ global graph_index
426
+ if len(gm_to_save.graph.nodes) == 0:
427
+ log.log(
428
+ logging.WARNING,
429
+ "No nodes in graph {%s}_{%s}_{%s}.",
430
+ current_name,
431
+ type_name,
432
+ graph_index,
433
+ )
434
+ return
435
+
436
+ gm = copy.deepcopy(gm_to_save)
437
+ gm.graph.set_codegen(torch.fx.graph.CodeGen()) # remove codegen
438
+ gm.recompile()
439
+
440
+ input_meta = get_input_meta(args)
441
+
442
+ os.makedirs(f"{folder_name}/{current_name}", exist_ok=True)
443
+ gm.to_folder(
444
+ f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}"
445
+ )
446
+ with open(
447
+ f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.input",
448
+ "wb",
449
+ ) as f:
450
+ pickle.dump(input_meta, f)
451
+ if dump_example_input:
452
+ torch.save(
453
+ args,
454
+ f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.pt",
455
+ )
456
+
457
+ def graph_saver_forward(
458
+ gm: fx.GraphModule, example_inputs: list[torch.Tensor]
459
+ ) -> fx.GraphModule:
460
+ graph_saver_helper(gm, example_inputs, "forward")
461
+ return gm
462
+
463
+ def graph_saver_backward(
464
+ gm: fx.GraphModule, example_inputs: list[torch.Tensor]
465
+ ) -> fx.GraphModule:
466
+ graph_saver_helper(gm, example_inputs, "backward")
467
+ global graph_index
468
+ graph_index += 1
469
+ return gm
470
+
471
+ def graph_saver_joint(
472
+ gm: fx.GraphModule, joint_args: list[torch.Tensor]
473
+ ) -> tuple[fx.GraphModule, fx.GraphModule]:
474
+ graph_saver_helper(gm, joint_args, "joint")
475
+ return default_partition(gm, joint_args) # pyrefly: ignore[missing-argument]
476
+
477
+ # pyrefly: ignore[bad-return]
478
+ return aot_module_simplified(
479
+ gm,
480
+ example_inputs,
481
+ fw_compiler=graph_saver_forward, # pyrefly: ignore[bad-argument-type]
482
+ bw_compiler=graph_saver_backward, # pyrefly: ignore[bad-argument-type]
483
+ partition_fn=graph_saver_joint,
484
+ decompositions=default_decompositions, # pyrefly: ignore[bad-argument-type]
485
+ )
486
+
487
+
488
+ # WARNING: This isn't tested anywhere!!
489
+ def graph_dumper_aot(
490
+ current_name: str, folder_name: str, dump_example_input: bool = False
491
+ ) -> Callable[[bool, nn.Module], Any]:
492
+ """
493
+ Dump the forward, backward, and joint computation graph.
494
+ Example Usage:
495
+ save_fx_func = graph_dumper_aot(current_name, folder_name, dump_example_input = False)
496
+ optimize_ctx = torchdynamo.optimize(
497
+ save_fx_func
498
+ )
499
+ with torch.enable_grad():
500
+ with optimize_ctx:
501
+ result = forward_and_backward_pass(model, example_inputs)
502
+ """
503
+ global graph_index
504
+ graph_index = 0
505
+ return partial(_save_fx_default, current_name, folder_name, dump_example_input)
.venv/lib/python3.12/site-packages/torch/_functorch/config.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from collections.abc import Callable
8
+
9
+
10
+ """
11
+ Global flags for aot autograd
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ from typing import Literal, TYPE_CHECKING
17
+
18
+ from torch.utils._config_module import Config, install_config_module
19
+
20
+
21
+ # [@compile_ignored: debug]
22
+ _save_config_ignore = [
23
+ # callable not serializable
24
+ "joint_custom_pass",
25
+ # callable configs with uuid() for caching, or raw callables
26
+ "activation_memory_budget_runtime_estimator",
27
+ "activation_memory_budget_solver",
28
+ ]
29
+
30
+
31
+ # Converts torch rng ops to their functional philox rng equivalents. Note that
32
+ # we functionalize only CUDA rng ops today.
33
+ functionalize_rng_ops = False
34
+
35
+ # can be useful for debugging if we are incorrectly creating meta fake tensors
36
+ fake_tensor_allow_meta = os.environ.get("FAKE_ALLOW_META", "1") != "0"
37
+
38
+ # Enables optional asserts in hotpath code to check for errors. If
39
+ # you are seeing weird accuracy problems, try turning this on.
40
+ # This is currently off by default as it will harm tracing time,
41
+ # but it is on by default for aot_eager.
42
+ debug_assert = False
43
+
44
+ debug_partitioner = os.environ.get("AOT_PARTITIONER_DEBUG", "0") != "0"
45
+
46
+ # See # NOTE [Export custom triton op]
47
+ decompose_custom_triton_ops = True
48
+
49
+ static_weight_shapes = True
50
+
51
+ # See https://github.com/pytorch/pytorch/issues/141881
52
+ # Tells partitioner that parameters are free to save for backward.
53
+ treat_parameters_as_free_to_save = True
54
+
55
+ # Applies CSE to the graph before partitioning
56
+ cse = True
57
+
58
+ # When the partitioner's _size_of encounters a (Fake)ScriptObject in node
59
+ # metadata, it has no general way to know the object's true memory footprint:
60
+ # a ScriptObject may hold tensors internally. By default we raise rather than
61
+ # guess. Enabling this flag makes _size_of assume such objects are zero size,
62
+ # which unblocks dynamic-shapes compilation of models containing ScriptObject
63
+ # parameters (e.g. embedding-table configs from FBGEMM) at the cost of
64
+ # soundness. This is a temporary escape hatch until we have a principled way to
65
+ # probe the size of a (Fake)ScriptObject.
66
+ unsafe_treat_script_objects_as_zero_size = False
67
+
68
+ from torch._environment import is_fbcode
69
+
70
+
71
+ enable_autograd_cache: bool = Config(
72
+ justknob="pytorch/remote_cache:enable_local_autograd_cache",
73
+ env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE",
74
+ default=True,
75
+ )
76
+
77
+ autograd_cache_allow_custom_autograd_functions: bool = Config(
78
+ env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE_ALLOW_CUSTOM_AUTOGRAD", default=False
79
+ )
80
+
81
+ # For now, this is just for enabling unit testing in test_aot_autograd_cache.py
82
+ # We will either make this the default with AOTAutogradCache, or
83
+ # we'll just use it in the precompile flow. So there's no
84
+ # need to add env vars or make it configurable
85
+ bundled_autograd_cache: bool = False
86
+
87
+ bypass_autograd_cache_key: bool = False
88
+
89
+ # Whether or not to normalize placeholder names in graphs
90
+ # from dynamo in AOTAutogradCache
91
+ autograd_cache_normalize_inputs = not is_fbcode()
92
+
93
+ # Enable debug mode at first invocation to check if custom ops are valid.
94
+ # When enabled, this checks that custom operators don't violate aliasing constraints.
95
+ #
96
+ # check_custom_op_aliasing: Controls whether to run the custom op aliasing check at all.
97
+ # - When True: The check runs on first invocation of compiled functions.
98
+ # - When False: The check is skipped entirely.
99
+ #
100
+ # error_on_custom_op_aliasing: Controls behavior when a violation is detected.
101
+ # Only has effect when check_custom_op_aliasing is True.
102
+ # - When True: Raises RuntimeError on aliasing violations.
103
+ # - When False: Emits UserWarning on aliasing violations.
104
+ #
105
+ # Deprecated: Custom ops returning aliased outputs is deprecated and will
106
+ # become an error in a future version of PyTorch. Currently error_on_custom_op_aliasing
107
+ # is True in CI unless explicitly overridden.
108
+ check_custom_op_aliasing = True
109
+ error_on_custom_op_aliasing: bool = Config(
110
+ env_name_force="TORCHINDUCTOR_ERROR_ON_CUSTOM_OP_ALIASING",
111
+ default=bool(os.getenv("CI")),
112
+ )
113
+
114
+
115
+ def remote_autograd_cache_default() -> bool | None:
116
+ if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "1":
117
+ return True
118
+ if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "0":
119
+ return False
120
+ return None
121
+
122
+
123
+ enable_remote_autograd_cache = remote_autograd_cache_default()
124
+
125
+
126
+ # When AOTAutograd regenerates aliased graph outputs,
127
+ # attempt to use functionalization's view-replay logic
128
+ # before falling back to the autograd engine's view replay or as_strided.
129
+ # This can have some perf implications
130
+ # (although for many models this will not matter).
131
+ # (1) If you have many view ops chained together, replaying all of them
132
+ # at runtime can have more overhead compared to a single as_strided call
133
+ # (2) If you are doing training, AsStridedBackward is quite slow,
134
+ # and the individual view op backward formulas will likely be faster.
135
+ # (3) Some backends like XLA do not support as_strided
136
+
137
+ # Temporary hack: disable this flag for internal
138
+ # (needed to fix an internal issue while avoiding bumping XLA pin)
139
+ # eventually: either default this config to false completely
140
+ # once XLA pin update works,
141
+ # or default config to true and fix relevant bugs
142
+
143
+
144
+ # View replay is currently not compatible with AOTAutogradCache, since
145
+ # FunctionalTensors are not serializable. We'll need to make them
146
+ # serializable before enabling warm cache with this config turned on.
147
+ view_replay_for_aliased_outputs = not is_fbcode()
148
+
149
+ # Restricts the amount of computation AOTAutograd can do.
150
+ # NB: We have essentially disabled this heuristic now. However, this is kept
151
+ # here for now in case it's useful. Setting it low can artificially reduce the
152
+ # amount of recomputation AOTAutograd performs, although not in any kind of
153
+ # principled way.
154
+ max_dist_from_bw = 1000
155
+
156
+
157
+ # Bans recomputation of nodes that are reading from nodes that are far before
158
+ # the current node
159
+ ban_recompute_used_far_apart = True
160
+ # Breaks up long chain of fusible ops, as otherwise we can have an arbitrarily
161
+ # long chain of recomputation in the backwards pass.
162
+ ban_recompute_long_fusible_chains = True
163
+ # Bans recomputation of nodes that must be materialized in the backwards pass
164
+ # (used by a non-fusible node)
165
+ ban_recompute_materialized_backward = True
166
+ # Chooses to ban recomputation of nodes based off an allowlist. Setting it to
167
+ # False changes it to use a denylist. Main change is on operators like
168
+ # sort/pool/stuff that isn't cheap enough to be fusible for free but also isn't
169
+ # that expensive
170
+ ban_recompute_not_in_allowlist = True
171
+ # Chooses to ban recomputation of reductions. This is generally a good idea, as
172
+ # the result of reductions is generally very small but recomputing reductions in
173
+ # a fusion can be expensive.
174
+ ban_recompute_reductions = True
175
+ # Prevents the partitioner from ever saving views (i.e. always recompute them).
176
+ # Generally a good idea since views are free to recompute.
177
+ recompute_views = False
178
+ # Set this flag to enable considering non-built-in ops, including triton and custom
179
+ # ops, for recomputation during the knapsack optimization solver.
180
+ is_non_builtin_to_include = False
181
+
182
+ # Rematerialize AC nodes for graphs with forward+loss+backward in one graph.
183
+ # This optimization minimizes activation checkpoint node lifetimes by computing them
184
+ # just-in-time. For AC nodes only used in backward, they are deferred to backward region
185
+ # instead of being computed and saved in forward. This reduces peak memory usage.
186
+ # Note: This only applies to forward+loss+backward graphs where torch.autograd.grad is allowed
187
+ # in the graph. Joint graphs (standard AOTAutograd) use the partitioner instead.
188
+ remat_using_tags_for_fwd_loss_bwd_graph = True
189
+
190
+ # By default, the partitioner is purely trying to optimize for runtime (although
191
+ # it should always use less memory than eager)
192
+ # This knob controls the partitioner to make that tradeoff for you, choosing the
193
+ # fastest option that saves less activations than the memory budget.
194
+ # Specifically, 0.0 corresponds to the activation memory from applying
195
+ # activation checkpointing to the full compiled region, and 1.0 corresponds to
196
+ # the activation memory from the default runtime-optimized strategy. So, 0.4
197
+ # would result in a strategy that saves 40% of the activations compared to the
198
+ # default strategy.
199
+ # It solves a 0-1 knapsack to find the minimum recompute necessary to stay below
200
+ # the activation memory budget.
201
+ # NOTE: This *cannot* be treated as
202
+ activation_memory_budget = 1.0
203
+
204
+ # This controls how we estimate the runtime when deciding what the cheapest
205
+ # operators to recompute are. The 3 options are
206
+ # "flops": Bases it off of the flop count provided by torch.utils.flop_counter
207
+ # "profile": Benchmarks each operator to come up with a runtime
208
+ # "testing": Returns 1 for everything
209
+ activation_memory_budget_runtime_estimator = "flops"
210
+
211
+ # This controls the solver used for the 0-1 knapsack. By default we use a
212
+ # quantized DP solution ("dp"). The other approaches are a "greedy", an "ilp"
213
+ # (which has a scipy dependency) and "dp_knapsack_sliding_hirschberg", which
214
+ # used memory-efficient quantized DP solution
215
+ activation_memory_budget_solver = "dp"
216
+
217
+ # This dumps out an SVG visualization of the expected runtime vs. activation
218
+ # memory tradeoffs for all memory budget values from 0 to 1 in increments of
219
+ # 0.5. See an example here:
220
+ # https://github.com/pytorch/pytorch/pull/126320#discussion_r1625104015
221
+ visualize_memory_budget_pareto = (
222
+ os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO", "0") == "1"
223
+ )
224
+
225
+ # This controls the directory in which to dump the SVG plot with the pareto
226
+ # frontier of the activation checkpointing memory-vs-runtime tradeoffs.
227
+ memory_budget_pareto_dir = os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO_DIR")
228
+
229
+ # Sets all of the ban_recompute heuristics to False except ban_recompute_reductions
230
+ # Generally, this will probably result in some memory improvement, but at the
231
+ # cost of some performance
232
+ aggressive_recomputation = False
233
+
234
+ # activation offloading enablement (testing purpose)
235
+ enable_activation_offloading = False
236
+
237
+ # activation offloading with separate CUDA stream
238
+ activation_offload_separate_stream = False
239
+
240
+ # activation offloading wait sinking when using separate stream (fwd graph)
241
+ activation_offload_sink_wait = False
242
+
243
+ # activation reloading with prefetching when using separate streams (bwd graph)
244
+ activation_reload_prefetch = False
245
+
246
+ # CPU ↔ GPU bandwidth in GB/s, used to estimate transfer times for prefetch
247
+ # scheduling. This is hardware-specific and should be set by the user.
248
+ activation_offload_cpu_gpu_bw: float = 50.0
249
+
250
+ # If FakeTensor.data_ptr() should error.
251
+ # This option is independent of AOTAutograd and torch.compile, but our policy
252
+ # is to turn it off during torch.compile.
253
+ fake_tensor_allow_unsafe_data_ptr_access = True
254
+
255
+ # Unlifts effect tokens from the inputs/outputs in the traced graph and instead
256
+ # inserts make_token/sink_token calls in the graph to create tokens and then
257
+ # sink them at the end. Note that this means the graph is no longer functional
258
+ # which may lead to silent errors unless the backend knows how to handle the
259
+ # tokens.
260
+ unlift_effect_tokens = False
261
+
262
+ # NOTE: [The default layout constraint for custom operators.]
263
+ # This must be the name of one of the layout constraint tags
264
+ # (that is, one of {"needs_fixed_stride_order", "flexible_layout"}),
265
+ # If the custom op does not have a layout constraint tag already
266
+ # then we assume the following applies.
267
+ #
268
+ # This config is respected by Inductor and we recommend other backends also
269
+ # respect it.
270
+ # This config is in torch._functorch and not torch._inductor because it affects
271
+ # ProxyTensor tracing.
272
+ custom_op_default_layout_constraint: Literal[
273
+ "needs_exact_strides", "needs_fixed_stride_order", "flexible_layout"
274
+ ] = "needs_exact_strides"
275
+
276
+
277
+ # Run aot eager decomp partition with CrossRefFakeMode
278
+ # options = False, "all", "custom_ops"
279
+ fake_tensor_crossref = False
280
+
281
+ # This mode specifies that we should also keep track of the real
282
+ # tensor along with the fake tensor, and do real compute. While
283
+ # seemingly this eliminates the whole point of fake tensors, there are
284
+ # two obvious use cases for it:
285
+ #
286
+ # 1. When users call item()/other data dependent operations,
287
+ # if we propagate_real_tensors we are able to determine what
288
+ # the true value is and keep going.
289
+ #
290
+ # 2. It can be useful for testing, when you want to see if the fake
291
+ # and real tensors agree with each other. (Note that there are
292
+ # currently known inaccuracies in how we clone real tensors, that
293
+ # would have to be tightened up for this to be useful in this
294
+ # case.)
295
+ #
296
+ # Note that fake tensors are typically understood to be cheap to store
297
+ # indefinitely, so we tend to hold on to them longer than we would
298
+ # hold onto the real tensors. So we also support you explicitly
299
+ # deallocating the real tensor associated with a fake tensor, at which
300
+ # point we will stop propagating real tensors.
301
+ #
302
+ # One more thing: when you provide a real tensor to fakeify, we will
303
+ # clone it, so that we can safely perform mutations on it if necessary.
304
+ # This will increase live memory usage. This could potentially be
305
+ # optimized by using COW. We also currently do not faithfully
306
+ # maintain autograd metadata on the real tensor; this is fine because
307
+ # AOTAutograd will only use the fake tensor to determine leafness/etc
308
+ # of tensors in question.
309
+ fake_tensor_propagate_real_tensors = False
310
+
311
+ # AOTDispatcher traces out a backward graph at the time of the forward pass.
312
+ # This flag controls whether or not that backward graph gets autocast behavior
313
+ # applied to it.
314
+ #
315
+ # The options are either:
316
+ # - "same_as_forward". We assume that the backward of the torch.compile'ed region
317
+ # will be run under the same autocast context manager that the region was run
318
+ # under. This is equivalent to running the following code in eager:
319
+ #
320
+ # with torch.amp.autocast(...):
321
+ # y = region(x)
322
+ # ...
323
+ # z.backward()
324
+ #
325
+ # - "off". We assume that the backward of the torch.compile'd region will
326
+ # not be run under any autocast context managers.
327
+ # This is equivalent to running the following code in eager:
328
+ #
329
+ # with torch.amp.autocast(...):
330
+ # y = region(x)
331
+ # ...
332
+ # z.backward()
333
+ #
334
+ # - or a list of kwargs dicts that represent an autocast context manager to turn
335
+ # on during the backward pass.
336
+ #
337
+ # e.g. [{"device_type": "cuda"}] is equivalent to running the following code in eager:
338
+ #
339
+ # y = region(x)
340
+ # ...
341
+ # with torch.amp.autocast(device="cuda"):
342
+ # z.backward()
343
+ backward_pass_autocast = "same_as_forward"
344
+
345
+ # This controls whether we collect donated buffers. This flag must be set
346
+ # False if a user wants to retain_graph=True for backward.
347
+ donated_buffer = not is_fbcode()
348
+
349
+ # Controls the default graph output format used by draw_graph.
350
+ # Most supported formats are defined here https://graphviz.org/docs/outputs/.
351
+ # The "dot" and "raw" formats write raw DOT text without invoking Graphviz.
352
+ torch_compile_graph_format = os.environ.get("TORCH_COMPILE_GRAPH_FORMAT", "svg")
353
+
354
+ # Valid only if fake_tensor_propagate_real_tensors = True; if a fake-real
355
+ # kernel mismatch is detected, bypasses by making a fake kernel from the
356
+ # real tensor outputs.
357
+ generate_fake_kernels_from_real_mismatches = False
358
+
359
+ # When there are device mismatches in FakeTensor device propagation,
360
+ # prefer a specific device type over others. This is particularly useful
361
+ # in full compiled mode where intermediate tensors with device mismatches
362
+ # represent only logical differences during compilation - these intermediate
363
+ # tensors will never physically materialize in the binary execution, so the
364
+ # device mismatch is not a real runtime concern. Enabling this allows the
365
+ # compiler to proceed with compilation by choosing the preferred device type
366
+ # for consistency. For example, set to "mtia" to prefer MTIA devices over
367
+ # CPU, or "cuda" to prefer CUDA devices over CPU.
368
+ fake_tensor_prefer_device_type: str | None = None
369
+
370
+ # CUDAGraph safe run_with_rng functionalization.
371
+ graphsafe_rng_functionalization = True
372
+
373
+ # Whether or not to eagerly compile the backward
374
+ # used by AOT compile and other settings
375
+ # TODO: once AOT compile calls aot autograd directly instead of
376
+ # through compile_fx, we can remove this
377
+ force_non_lazy_backward_lowering = False
378
+
379
+ # only for testing, used to turn functionalization off in AOTDispatcher
380
+ _test_disable_functionalization = True
381
+
382
+ # Error on BypassAOTAutogradCache instead of just a warning
383
+ # Used for tests
384
+ strict_autograd_cache = False
385
+
386
+ # Note [Recomputing collectives in the partitioner]
387
+ # The purpose of this config is as follows:
388
+ # - We have many passes in the compiler (min-cut partitioning, DCE, etc)
389
+ # which can reorder or delete duplicate nodes in the graph
390
+ # - If any of these passes reorder/delete/duplicate a collective
391
+ # in a setting where the compiler is being run independently on multiple
392
+ # ranks, we run the risk that the compiler will make a different decision on
393
+ # different ranks, resulting in a NCCL hang when using torch.compile
394
+ # To handle this, we will (by default) ensure that collectives are not modified
395
+ # by the compiler.
396
+ #
397
+ # A few examples:
398
+ # - don't dead-code-eliminate collectives
399
+ # (in case they are dead on rank i but not rank j)
400
+ # - don't recompute collectives in partitioning
401
+ # (in case we recompute on rank i but not rank j)
402
+ #
403
+ # Today this flag **must** be set to false, but eventually
404
+ # we want the option to set it to true.
405
+ # In order to potentially optimize collectives, we'll need the compiler
406
+ # to broadcast information across ranks at compile time to ensure
407
+ # that any decisions on collectives are made consistently.
408
+ unsafe_allow_optimization_of_collectives = False
409
+
410
+ # See Note [AOTAutograd Tangent Subclassness for mutated inputs]
411
+ # TODO(ivankobzarev): Remove this config, being able to deduce it compile time.
412
+ disable_guess_zero_tangent_for_mutated_input_subclass = False
413
+
414
+ # See Note [Tangents memory format]
415
+ # By default tangents strideness is guessed to be contiguous,
416
+ # At runtime non contiguous tangents will be coerced to be contiguous.
417
+ # This config changes this guess for tangents strides to be the same as outputs.
418
+ # TODO(ivankobzarev): Remove this config once extra memory usage is investigated.
419
+ guess_tangent_strides_as_outputs = not is_fbcode()
420
+
421
+
422
+ # This is a temporary config to ensure all ranks take the same decision in the partitioner
423
+ # it will ultimately be removed once we share size_hints across ranks through compiler collectives
424
+ _sync_decision_cross_ranks = False
425
+
426
+ # By default apply inlined saved_tensors_hooks only for "donated" buffers.
427
+ # "donated" buffers are invisible to the user, they are intermediates of the forward graph.
428
+ # Applying saved tensors hooks for memory optimizations only for intermediates
429
+ # guarantees that original saved tensors could be deallocated.
430
+ # This config enables saved_tensors_hooks are applied for **all** saved tensors,
431
+ # that could include inputs, parameters, outputs.
432
+ # "donated" - applied only to saved intermediates of the graph
433
+ # "no_static" - applied to all saved but not "static"
434
+ # (this includes parameters and user marked as static)
435
+ # "all" - no filtering, everything saved for backward.
436
+ saved_tensors_hooks_filtering_mode = "donated"
437
+
438
+
439
+ # This callback is invoked on the joint graph before partitioning
440
+ joint_custom_pass: Callable = None # type: ignore[assignment]
441
+
442
+ force_autograd_cache = False
443
+
444
+ # Note [Selective Decomposition]
445
+ # This config allows selective decomposition of certain operators in the graph.
446
+ # When True, it does NOT decompose any nodes, except those nodes that users explicitly
447
+ # annotated with regional inductor compile. Please read torch.fx.passes.regional_inductor
448
+ # on to explicitly annotate. This is currently only used by inductor lite mode.
449
+ selective_decompose: bool = False
450
+
451
+ # Complex Support
452
+ # This config disallows decomposition of complex-valued Tensors using
453
+ # `torch._subclasses.complex_tensor.ComplexTensor` by decomposing everything into
454
+ # real-valued operations, passing through the regular pipeline as necessary,
455
+ # then converting back to a regular tensor.
456
+ enable_complex_wrapper: bool = False
457
+
458
+
459
+ if TYPE_CHECKING:
460
+ from torch.utils._config_typing import * # noqa: F403
461
+
462
+
463
+ # adds patch, save_config, invalid config checks, etc
464
+ install_config_module(sys.modules[__name__])
.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The APIs in this file are exposed as `functorch.*`. They are thin wrappers
3
+ around the torch.func.* APIs that have deprecation warnings -- we're trying
4
+ to move people to the torch.func.* equivalents.
5
+
6
+ NB: We don't use *args, **kwargs in the signatures because that changes the
7
+ documentation.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import textwrap
13
+ import warnings
14
+ from typing import Any, TYPE_CHECKING
15
+
16
+ import torch._functorch.apis as apis
17
+ import torch._functorch.eager_transforms as _impl
18
+ import torch._functorch.make_functional as _nn_impl
19
+ import torch.nn as nn
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable
24
+
25
+ from torch._functorch.eager_transforms import argnums_t
26
+ from torch._functorch.vmap import in_dims_t, out_dims_t
27
+
28
+
29
+ def get_warning(
30
+ api: str, new_api: str | None = None, replace_newlines: bool = False
31
+ ) -> str:
32
+ if new_api is None:
33
+ new_api = f"torch.func.{api}"
34
+ warning = (
35
+ f"We've integrated functorch into PyTorch. As the final step of the \n"
36
+ f"integration, `functorch.{api}` is deprecated as of PyTorch \n"
37
+ f"2.0 and will be deleted in a future version of PyTorch >= 2.3. \n"
38
+ f"Please use `{new_api}` instead; see the PyTorch 2.0 release notes \n"
39
+ f"and/or the `torch.func` migration guide for more details \n"
40
+ f"https://pytorch.org/docs/main/func.migrating.html"
41
+ )
42
+ if replace_newlines:
43
+ warning = warning.replace("\n", "")
44
+ return warning
45
+
46
+
47
+ def warn_deprecated(api: str, new_api: str | None = None) -> None:
48
+ warning = get_warning(api, new_api, replace_newlines=True)
49
+ warnings.warn(warning, FutureWarning, stacklevel=3)
50
+
51
+
52
+ def setup_docs(
53
+ functorch_api: Callable[..., Any],
54
+ torch_func_api: Callable[..., Any] | None = None,
55
+ new_api_name: str | None = None,
56
+ ) -> None:
57
+ api_name = functorch_api.__name__
58
+ if torch_func_api is None:
59
+ torch_func_api = getattr(_impl, api_name)
60
+ # See https://docs.python.org/3/using/cmdline.html#cmdoption-OO
61
+ if torch_func_api.__doc__ is None:
62
+ return
63
+
64
+ warning = get_warning(api_name, new_api_name)
65
+ warning_note = "\n.. warning::\n\n" + textwrap.indent(warning, " ")
66
+ warning_note = textwrap.indent(warning_note, " ")
67
+ functorch_api.__doc__ = torch_func_api.__doc__ + warning_note
68
+
69
+
70
+ def vmap(
71
+ func: Callable[..., Any],
72
+ in_dims: in_dims_t = 0,
73
+ out_dims: out_dims_t = 0,
74
+ randomness: str = "error",
75
+ *,
76
+ chunk_size: int | None = None,
77
+ ) -> Callable[..., Any]:
78
+ warn_deprecated("vmap", "torch.vmap")
79
+ return apis.vmap(func, in_dims, out_dims, randomness, chunk_size=chunk_size)
80
+
81
+
82
+ def grad(
83
+ func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False
84
+ ) -> Callable[..., Any]:
85
+ warn_deprecated("grad")
86
+ return apis.grad(func, argnums, has_aux)
87
+
88
+
89
+ def grad_and_value(
90
+ func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False
91
+ ) -> Callable[..., Any]:
92
+ warn_deprecated("grad_and_value")
93
+ return apis.grad_and_value(func, argnums, has_aux)
94
+
95
+
96
+ def vjp(func: Callable[..., Any], *primals: Any, has_aux: bool = False) -> Any:
97
+ warn_deprecated("vjp")
98
+ return _impl.vjp(func, *primals, has_aux=has_aux)
99
+
100
+
101
+ def jvp(
102
+ func: Callable[..., Any],
103
+ primals: Any,
104
+ tangents: Any,
105
+ *,
106
+ strict: bool = False,
107
+ has_aux: bool = False,
108
+ ) -> Any:
109
+ warn_deprecated("jvp")
110
+ return _impl.jvp(func, primals, tangents, strict=strict, has_aux=has_aux)
111
+
112
+
113
+ def jacrev(
114
+ func: Callable[..., Any],
115
+ argnums: int | tuple[int, ...] = 0,
116
+ *,
117
+ has_aux: bool = False,
118
+ chunk_size: int | None = None,
119
+ _preallocate_and_copy: bool = False,
120
+ ) -> Callable[..., Any]:
121
+ warn_deprecated("jacrev")
122
+ return _impl.jacrev(
123
+ func,
124
+ argnums,
125
+ has_aux=has_aux,
126
+ chunk_size=chunk_size,
127
+ _preallocate_and_copy=_preallocate_and_copy,
128
+ )
129
+
130
+
131
+ def jacfwd(
132
+ func: Callable[..., Any],
133
+ argnums: argnums_t = 0,
134
+ has_aux: bool = False,
135
+ *,
136
+ randomness: str = "error",
137
+ ) -> Callable[..., Any]:
138
+ warn_deprecated("jacfwd")
139
+ return _impl.jacfwd(func, argnums, has_aux, randomness=randomness)
140
+
141
+
142
+ def hessian(func: Callable[..., Any], argnums: int = 0) -> Callable[..., Any]:
143
+ warn_deprecated("hessian")
144
+ return _impl.hessian(func, argnums=argnums)
145
+
146
+
147
+ def functionalize(
148
+ func: Callable[..., Any], *, remove: str = "mutations"
149
+ ) -> Callable[..., Any]:
150
+ warn_deprecated("functionalize")
151
+ return _impl.functionalize(func, remove=remove)
152
+
153
+
154
+ def make_functional(model: nn.Module, disable_autograd_tracking: bool = False) -> Any:
155
+ warn_deprecated("make_functional", "torch.func.functional_call")
156
+ return _nn_impl.make_functional(model, disable_autograd_tracking)
157
+
158
+
159
+ def make_functional_with_buffers(
160
+ model: nn.Module, disable_autograd_tracking: bool = False
161
+ ) -> Any:
162
+ warn_deprecated("make_functional_with_buffers", "torch.func.functional_call")
163
+ return _nn_impl.make_functional_with_buffers(model, disable_autograd_tracking)
164
+
165
+
166
+ def combine_state_for_ensemble(models: list[nn.Module]) -> Any:
167
+ warn_deprecated("combine_state_for_ensemble", "torch.func.stack_module_state")
168
+ return _nn_impl.combine_state_for_ensemble(models)
169
+
170
+
171
+ setup_docs(vmap, apis.vmap, "torch.vmap")
172
+ setup_docs(grad, apis.grad)
173
+ setup_docs(grad_and_value, apis.grad_and_value)
174
+ setup_docs(vjp)
175
+ setup_docs(jvp)
176
+ setup_docs(jacrev)
177
+ setup_docs(jacfwd)
178
+ setup_docs(hessian)
179
+ setup_docs(functionalize)
180
+ setup_docs(make_functional, _nn_impl.make_functional, "torch.func.functional_call")
181
+ setup_docs(
182
+ make_functional_with_buffers, _nn_impl.make_functional, "torch.func.functional_call"
183
+ )
184
+ setup_docs(
185
+ combine_state_for_ensemble,
186
+ _nn_impl.combine_state_for_ensemble,
187
+ "torch.func.stack_module_state",
188
+ )
.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py ADDED
@@ -0,0 +1,1960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ from functools import partial
11
+ from typing import Any, overload, TYPE_CHECKING
12
+ from typing_extensions import ParamSpec, TypeVar
13
+
14
+ import torch
15
+ import torch.autograd.forward_ad as fwAD
16
+ from torch._C._functorch import (
17
+ _assert_wrapped_functional, # type: ignore[attr-defined]
18
+ _func_decrement_nesting, # type: ignore[attr-defined]
19
+ _func_increment_nesting, # type: ignore[attr-defined]
20
+ _grad_decrement_nesting,
21
+ _grad_increment_nesting,
22
+ _propagate_functional_input_mutation, # type: ignore[attr-defined]
23
+ _unwrap_functional_tensor,
24
+ _wrap_for_grad,
25
+ _wrap_functional_tensor,
26
+ get_inplace_requires_grad_allowed,
27
+ get_unwrapped,
28
+ is_functorch_wrapped_tensor,
29
+ set_inplace_requires_grad_allowed,
30
+ )
31
+ from torch._functorch.predispatch import (
32
+ _jvp_decrement_nesting,
33
+ _jvp_increment_nesting,
34
+ _unwrap_for_grad,
35
+ )
36
+ from torch._functorch.utils import argnums_t, exposed_in
37
+ from torch._subclasses.functional_tensor import FunctionalTensor
38
+ from torch.fx.experimental import const_fold
39
+ from torch.fx.experimental.proxy_tensor import make_fx
40
+ from torch.utils import _pytree as pytree
41
+ from torch.utils._pytree import (
42
+ tree_flatten,
43
+ tree_map,
44
+ tree_map_,
45
+ tree_map_only,
46
+ tree_unflatten,
47
+ treespec_pprint,
48
+ )
49
+
50
+ from .apis import _wraps_without_dynamo_attrs, vmap
51
+ from .vmap import doesnt_support_saved_tensors_hooks, get_chunk_sizes
52
+
53
+
54
+ if TYPE_CHECKING:
55
+ from collections.abc import Callable, Generator, Sequence
56
+
57
+
58
+ _P = ParamSpec("_P")
59
+ _R = TypeVar("_R")
60
+ _T = TypeVar("_T")
61
+
62
+
63
+ def lazy_dynamo_disallow(func: Callable[_P, _R]) -> Callable[_P, _R]:
64
+ import torch._dynamo
65
+
66
+ return torch._dynamo.disallow_in_graph(func)
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def enable_inplace_requires_grad(enabled: bool) -> Generator[None, None, None]:
71
+ prev_state = get_inplace_requires_grad_allowed()
72
+ set_inplace_requires_grad_allowed(enabled)
73
+ try:
74
+ yield
75
+ finally:
76
+ set_inplace_requires_grad_allowed(prev_state)
77
+
78
+
79
+ def _set_tensor_requires_grad(x: torch.Tensor) -> torch.Tensor:
80
+ # avoid graph-break on x.requires_grad_()
81
+ # https://github.com/pytorch/pytorch/pull/110053
82
+ return x.requires_grad_()
83
+
84
+
85
+ def _create_differentiable(inps: Any, level: int | None = None) -> Any:
86
+ def create_differentiable(x: torch.Tensor | Any) -> torch.Tensor:
87
+ if isinstance(x, torch.Tensor):
88
+ with enable_inplace_requires_grad(True):
89
+ return _set_tensor_requires_grad(x)
90
+ raise ValueError(f"Thing passed to transform API must be Tensor, got {type(x)}")
91
+
92
+ return tree_map(create_differentiable, inps)
93
+
94
+
95
+ _Tensors = torch.Tensor | tuple[torch.Tensor, ...]
96
+ _TensorsT = TypeVar("_TensorsT", bound=_Tensors)
97
+ _TensorsU = TypeVar("_TensorsU", bound=_Tensors)
98
+
99
+
100
+ def _undo_create_differentiable(inps: _TensorsT, level: int | None = None) -> _TensorsT:
101
+ def unwrap_tensors(x: _TensorsU) -> _TensorsU:
102
+ if isinstance(x, torch.Tensor):
103
+ if level is None:
104
+ raise AssertionError("level must not be None when unwrapping tensors")
105
+ # pyrefly: ignore[bad-return]
106
+ return _unwrap_for_grad(x, level)
107
+ # TODO: Remove the following hack for namedtuples
108
+ if isinstance(x, tuple):
109
+ return tree_map(unwrap_tensors, tuple(x))
110
+
111
+ raise RuntimeError(f"Expected tensors, got unsupported type {type(x)}")
112
+
113
+ return tree_map(unwrap_tensors, inps)
114
+
115
+
116
+ def _is_differentiable(maybe_tensor: object) -> bool:
117
+ if not isinstance(maybe_tensor, torch.Tensor):
118
+ return False
119
+ return maybe_tensor.requires_grad
120
+
121
+
122
+ def _any_differentiable(
123
+ tensor_or_tuple_of_tensors: _Tensors,
124
+ ) -> bool:
125
+ flat_args, _ = tree_flatten(tensor_or_tuple_of_tensors)
126
+ return any(tuple(map(_is_differentiable, flat_args)))
127
+
128
+
129
+ def _wrap_tensor_for_grad(maybe_tensor: _T, level: int) -> _T:
130
+ if not isinstance(maybe_tensor, torch.Tensor):
131
+ return maybe_tensor
132
+ # pyrefly: ignore[bad-return]
133
+ return _wrap_for_grad(maybe_tensor, level)
134
+
135
+
136
+ def _wrap_all_tensors(tensor_pytree: _T, level: int) -> _T:
137
+ return tree_map(partial(_wrap_tensor_for_grad, level=level), tensor_pytree)
138
+
139
+
140
+ # TODO: this is more accurate - enable in 3.11
141
+ # _Ts = TypeVarTuple("_Ts")
142
+ # @overload
143
+ # def _as_tuple(val: tuple[*_Ts]) -> tuple[*_Ts]: ...
144
+ @overload
145
+ def _as_tuple(val: tuple[_R, ...]) -> tuple[_R]: ...
146
+ @overload
147
+ def _as_tuple(val: _R) -> tuple[_R]: ...
148
+ def _as_tuple(val: object) -> object:
149
+ if isinstance(val, tuple):
150
+ return val
151
+ return (val,)
152
+
153
+
154
+ # Version of autograd.grad that handles outputs that don't depend on inputs
155
+
156
+
157
+ def _autograd_grad(
158
+ outputs: Sequence[torch.Tensor],
159
+ inputs: Sequence[torch.Tensor],
160
+ grad_outputs: Sequence[torch.Tensor] | None = None,
161
+ retain_graph: bool = False,
162
+ create_graph: bool = True,
163
+ ) -> tuple[torch.Tensor, ...]:
164
+ if grad_outputs is None:
165
+ diff_outputs = tuple(out for out in outputs if out.requires_grad)
166
+ else:
167
+ result = tuple(
168
+ (out, go) for out, go in zip(outputs, grad_outputs) if out.requires_grad
169
+ )
170
+ if len(result) == 0:
171
+ diff_outputs, grad_outputs = (), ()
172
+ else:
173
+ diff_outputs, grad_outputs = zip(*result)
174
+ if len(diff_outputs) == 0:
175
+ return tuple(torch.zeros_like(inp) for inp in inputs)
176
+ with torch._dynamo.compiled_autograd._disable():
177
+ grad_inputs = torch.autograd.grad(
178
+ diff_outputs,
179
+ inputs,
180
+ grad_outputs,
181
+ retain_graph=retain_graph,
182
+ create_graph=create_graph,
183
+ allow_unused=True,
184
+ )
185
+ grad_inputs = tuple(
186
+ torch.zeros_like(inp) if gi is None else gi
187
+ for gi, inp in zip(grad_inputs, inputs)
188
+ )
189
+ return grad_inputs
190
+
191
+
192
+ # NOTE [grad and vjp interaction with no_grad]
193
+ #
194
+ # def f(x):
195
+ # with torch.no_grad():
196
+ # c = x ** 2
197
+ # return x - c
198
+ #
199
+ # The thing to consider is if enable_grad is on/off before grad gets called.
200
+ #
201
+ # Case 1: enable_grad is on.
202
+ # grad(f)(x)
203
+ # In this case, `grad` should respect the inner torch.no_grad.
204
+ #
205
+ # Case 2: enable_grad is off
206
+ # with torch.no_grad():
207
+ # grad(f)(x)
208
+ # In this case, `grad` should respect the inner torch.no_grad, but not the
209
+ # outer one. This is because `grad` is a "function transform": its result
210
+ # should not depend on the result of a context manager outside of `f`.
211
+ #
212
+ # This gives us the following desired behavior:
213
+ # - (nested) grad transforms must obey torch.no_grad inside them
214
+ # - (nested) grad transforms should not obey torch.no_grad outside them
215
+ #
216
+ # To achieve this behavior, upon entering grad/vjp:
217
+ # - we save the current ("previous") is_grad_enabled (*)
218
+ # - we unconditionally enable grad.
219
+ #
220
+ # Inside DynamicLayerBackFallback, when we're temporarily popping `grad` layer
221
+ # off the stack:
222
+ # - if grad_mode is disabled, then we do nothing. (there is a torch.no_grad
223
+ # active, all subsequent grad transforms must obey it).
224
+ # - if grad_mode is enabled, and the previous is_grad_enabled (*) is False,
225
+ # then we temporarily restore the previous `is_grad_enabled`. This is
226
+ # because we're crossing the boundary from a `grad` outside the
227
+ # no_grad to a `grad` inside the no_grad.
228
+ #
229
+ # NB: vjp has some interesting behavior because the vjp's Callable[..., Any] can be called
230
+ # under a different grad_mode than the forward computation...
231
+ #
232
+ # NB: forward-mode AD: forward-mode AD doesn't respect torch.no_grad, but
233
+ # it respects c10::AutoFwGradMode. We've implemented the same logic for
234
+ # our jvp transform (it will have special handling if FwGradMode is disabled).
235
+
236
+
237
+ # How do we increment and decrement the nesting? I don't think we can.
238
+ @exposed_in("torch.func")
239
+ def vjp(
240
+ func: Callable[..., Any], *primals: Any, has_aux: bool = False
241
+ ) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]:
242
+ """
243
+ Standing for the vector-Jacobian product, returns a tuple containing the
244
+ results of ``func`` applied to ``primals`` and a function that, when
245
+ given ``cotangents``, computes the reverse-mode Jacobian of ``func`` with
246
+ respect to ``primals`` times ``cotangents``.
247
+
248
+ Args:
249
+ func (Callable[..., Any]): A Python function that takes one or more arguments. Must
250
+ return one or more Tensors.
251
+ primals (Tensors): Positional arguments to ``func`` that must all be
252
+ Tensors. The returned function will also be computing the
253
+ derivative with respect to these arguments
254
+ has_aux (bool): Flag indicating that ``func`` returns a
255
+ ``(output, aux)`` tuple where the first element is the output of
256
+ the function to be differentiated and the second element is
257
+ other auxiliary objects that will not be differentiated.
258
+ Default: False.
259
+
260
+ Returns:
261
+ Returns a ``(output, vjp_fn)`` tuple containing the output of ``func``
262
+ applied to ``primals`` and a function that computes the vjp of
263
+ ``func`` with respect to all ``primals`` using the cotangents passed
264
+ to the returned function. If ``has_aux is True``, then instead returns a
265
+ ``(output, vjp_fn, aux)`` tuple.
266
+ The returned ``vjp_fn`` function will return a tuple of each VJP.
267
+
268
+ When used in simple cases, :func:`vjp` behaves the same as :func:`grad`
269
+
270
+ >>> x = torch.randn([5])
271
+ >>> f = lambda x: x.sin().sum()
272
+ >>> (_, vjpfunc) = torch.func.vjp(f, x)
273
+ >>> grad = vjpfunc(torch.tensor(1.0))[0]
274
+ >>> assert torch.allclose(grad, torch.func.grad(f)(x))
275
+
276
+ However, :func:`vjp` can support functions with multiple outputs by
277
+ passing in the cotangents for each of the outputs
278
+
279
+ >>> x = torch.randn([5])
280
+ >>> f = lambda x: (x.sin(), x.cos())
281
+ >>> (_, vjpfunc) = torch.func.vjp(f, x)
282
+ >>> vjps = vjpfunc((torch.ones([5]), torch.ones([5])))
283
+ >>> assert torch.allclose(vjps[0], x.cos() + -x.sin())
284
+
285
+ :func:`vjp` can even support outputs being Python structs
286
+
287
+ >>> x = torch.randn([5])
288
+ >>> f = lambda x: {"first": x.sin(), "second": x.cos()}
289
+ >>> (_, vjpfunc) = torch.func.vjp(f, x)
290
+ >>> cotangents = {"first": torch.ones([5]), "second": torch.ones([5])}
291
+ >>> vjps = vjpfunc(cotangents)
292
+ >>> assert torch.allclose(vjps[0], x.cos() + -x.sin())
293
+
294
+ The function returned by :func:`vjp` will compute the partials with
295
+ respect to each of the ``primals``
296
+
297
+ >>> x, y = torch.randn([5, 4]), torch.randn([4, 5])
298
+ >>> (_, vjpfunc) = torch.func.vjp(torch.matmul, x, y)
299
+ >>> cotangents = torch.randn([5, 5])
300
+ >>> vjps = vjpfunc(cotangents)
301
+ >>> assert len(vjps) == 2
302
+ >>> assert torch.allclose(vjps[0], torch.matmul(cotangents, y.transpose(0, 1)))
303
+ >>> assert torch.allclose(vjps[1], torch.matmul(x.transpose(0, 1), cotangents))
304
+
305
+ ``primals`` are the positional arguments for ``f``. All kwargs use their
306
+ default value
307
+
308
+ >>> x = torch.randn([5])
309
+ >>> def f(x, scale=4.):
310
+ >>> return x * scale
311
+ >>>
312
+ >>> (_, vjpfunc) = torch.func.vjp(f, x)
313
+ >>> vjps = vjpfunc(torch.ones_like(x))
314
+ >>> assert torch.allclose(vjps[0], torch.full(x.shape, 4.0))
315
+
316
+ .. note::
317
+ Using PyTorch ``torch.no_grad`` together with ``vjp``.
318
+ Case 1: Using ``torch.no_grad`` inside a function:
319
+
320
+ >>> def f(x):
321
+ >>> with torch.no_grad():
322
+ >>> c = x ** 2
323
+ >>> return x - c
324
+
325
+ In this case, ``vjp(f)(x)`` will respect the inner ``torch.no_grad``.
326
+
327
+ Case 2: Using ``vjp`` inside ``torch.no_grad`` context manager:
328
+
329
+ >>> # xdoctest: +SKIP(failing)
330
+ >>> with torch.no_grad():
331
+ >>> vjp(f)(x)
332
+
333
+ In this case, ``vjp`` will respect the inner ``torch.no_grad``, but not the
334
+ outer one. This is because ``vjp`` is a "function transform": its result
335
+ should not depend on the result of a context manager outside of ``f``.
336
+ """
337
+ return _vjp_with_argnums(func, *primals, has_aux=has_aux)
338
+
339
+
340
+ @contextlib.contextmanager
341
+ def _disable_inference_mode() -> Generator[None, None, None]:
342
+ # Disable inference_mode without clobbering grad_mode / fw_grad_mode.
343
+ # torch.inference_mode(False) unconditionally sets grad_mode=True and
344
+ # fw_grad_mode=True; we save and restore those to avoid that.
345
+ # No-op when inference_mode is already off.
346
+ if not torch.is_inference_mode_enabled():
347
+ yield
348
+ return
349
+ prev_grad = torch.is_grad_enabled()
350
+ prev_fw_grad = torch._C._is_fwd_grad_enabled()
351
+ with torch.inference_mode(False):
352
+ torch._C._set_grad_enabled(prev_grad)
353
+ torch._C._set_fwd_grad_enabled(prev_fw_grad)
354
+ yield
355
+
356
+
357
+ @contextlib.contextmanager
358
+ def grad_increment_nesting() -> Generator[int, None, None]:
359
+ try:
360
+ grad_level = _grad_increment_nesting()
361
+ yield grad_level
362
+ finally:
363
+ _grad_decrement_nesting()
364
+
365
+
366
+ def enter_jvp_nesting() -> int:
367
+ global JVP_NESTING
368
+ jvp_level = _jvp_increment_nesting()
369
+ JVP_NESTING += 1
370
+ return jvp_level
371
+
372
+
373
+ def exit_jvp_nesting() -> None:
374
+ global JVP_NESTING
375
+ _jvp_decrement_nesting()
376
+ JVP_NESTING -= 1
377
+
378
+
379
+ @contextlib.contextmanager
380
+ def jvp_increment_nesting() -> Generator[int, None, None]:
381
+ try:
382
+ yield enter_jvp_nesting()
383
+ finally:
384
+ exit_jvp_nesting()
385
+
386
+
387
+ @doesnt_support_saved_tensors_hooks
388
+ def _vjp_with_argnums(
389
+ func: Callable[..., Any],
390
+ *primals: Any,
391
+ argnums: argnums_t | None = None,
392
+ has_aux: bool = False,
393
+ ) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]:
394
+ # This is the same function as vjp but also accepts an argnums argument
395
+ # All args are the same as vjp except for the added argument
396
+ # argnums (int or tuple[int,...] | None): Optional, specifies the argument(s) to compute gradients with respect to.
397
+ # If None, computes the gradients with respect to all inputs (used for vjp). Default: None
398
+ #
399
+ # WARN: Users should NOT call this function directly and should just be calling vjp.
400
+ # It is only separated so that inputs passed to jacrev but not differentiated get the correct wrappers.
401
+ #
402
+ # NOTE: All error messages are produced as if vjp was being called, even if this was called by jacrev
403
+ #
404
+ # Returns the same two elements as :func:`vjp` but the function returned, vjp_fn, returns a tuple of VJPs
405
+ # for only the primal elements given by argnums.
406
+ with grad_increment_nesting() as level:
407
+ # See NOTE [grad and vjp interaction with no_grad]
408
+ with torch.enable_grad():
409
+ primals = _wrap_all_tensors(primals, level)
410
+ if argnums is None:
411
+ diff_primals = _create_differentiable(primals, level)
412
+ else:
413
+ diff_primals = _slice_argnums(primals, argnums, as_tuple=False)
414
+ tree_map_(partial(_create_differentiable, level=level), diff_primals)
415
+ primals_out = func(*primals)
416
+
417
+ aux: Any = None
418
+ if has_aux:
419
+ if not (isinstance(primals_out, tuple) and len(primals_out) == 2):
420
+ raise RuntimeError(
421
+ "vjp(f, *primals): output of function f should be a tuple: (output, aux) "
422
+ "if has_aux is True"
423
+ )
424
+ primals_out, aux = primals_out
425
+ aux = _undo_create_differentiable(aux, level)
426
+
427
+ flat_primals_out, primals_out_spec = tree_flatten(primals_out)
428
+ assert_non_empty_tensor_output(flat_primals_out, "vjp(f, *primals)")
429
+ flat_diff_primals, primals_spec = tree_flatten(diff_primals)
430
+ results = _undo_create_differentiable(primals_out, level)
431
+
432
+ for primal_out in flat_primals_out:
433
+ if not isinstance(primal_out, torch.Tensor):
434
+ raise AssertionError(
435
+ f"expected primal_out to be a Tensor, got {type(primal_out)}"
436
+ )
437
+ if primal_out.is_floating_point() or primal_out.is_complex():
438
+ continue
439
+ raise RuntimeError(
440
+ "vjp(f, ...): All outputs of f must be "
441
+ "floating-point or complex Tensors, got Tensor "
442
+ f"with dtype {primal_out.dtype}"
443
+ )
444
+
445
+ def wrapper(
446
+ cotangents: Any,
447
+ retain_graph: bool = True,
448
+ create_graph: bool | None = None,
449
+ ) -> Any:
450
+ if create_graph is None:
451
+ create_graph = torch.is_grad_enabled()
452
+ flat_cotangents, cotangents_spec = tree_flatten(cotangents)
453
+ if primals_out_spec != cotangents_spec:
454
+ raise RuntimeError(
455
+ f"Expected pytree structure of cotangents to be the same "
456
+ f"as pytree structure of outputs to the function. "
457
+ f"cotangents: {treespec_pprint(cotangents_spec)}, "
458
+ f"primal output: {treespec_pprint(primals_out_spec)}"
459
+ )
460
+ # This closure runs after grad_increment_nesting exits, so
461
+ # inference_mode may have been restored. Disable it for autograd.
462
+ # Skip under Dynamo — tracing through the generator CM emits
463
+ # spurious _enter_inference_mode nodes.
464
+ ctx = (
465
+ contextlib.nullcontext()
466
+ if torch.compiler.is_compiling()
467
+ else _disable_inference_mode()
468
+ )
469
+ with ctx:
470
+ result = _autograd_grad(
471
+ flat_primals_out,
472
+ flat_diff_primals,
473
+ flat_cotangents,
474
+ retain_graph=retain_graph,
475
+ create_graph=create_graph,
476
+ )
477
+ return tree_unflatten(result, primals_spec)
478
+
479
+ if has_aux:
480
+ return results, wrapper, aux # type: ignore[possibly-unbound]
481
+ else:
482
+ return results, wrapper
483
+
484
+
485
+ def _safe_zero_index(x: tuple[_R, ...]) -> _R:
486
+ if len(x) != 1:
487
+ raise AssertionError(f"expected tuple of length 1, got length {len(x)}")
488
+ return x[0]
489
+
490
+
491
+ # jacrev and jacfwd don't support complex functions
492
+ # Helper function to throw appropriate error.
493
+ def error_if_complex(func_name: str, args: Any, is_input: bool) -> None:
494
+ flat_args = pytree.tree_leaves(args)
495
+ for idx, arg in enumerate(flat_args):
496
+ if isinstance(arg, torch.Tensor) and arg.dtype.is_complex:
497
+ input_or_output = "inputs" if is_input else "outputs"
498
+ err_msg = (
499
+ f"{func_name}: Expected all {input_or_output} "
500
+ f"to be real but received complex tensor at flattened input idx: {idx}"
501
+ )
502
+ raise RuntimeError(err_msg)
503
+
504
+
505
+ @exposed_in("torch.func")
506
+ def jacrev(
507
+ func: Callable[..., Any],
508
+ argnums: int | tuple[int, ...] = 0,
509
+ *,
510
+ has_aux: bool = False,
511
+ chunk_size: int | None = None,
512
+ _preallocate_and_copy: bool = False,
513
+ ) -> Callable[..., Any]:
514
+ """
515
+ Computes the Jacobian of ``func`` with respect to the arg(s) at index
516
+ ``argnum`` using reverse mode autodiff
517
+
518
+ .. note::
519
+ Using :attr:`chunk_size=1` is equivalent to computing the jacobian
520
+ row-by-row with a for-loop i.e. the constraints of :func:`vmap` are
521
+ not applicable.
522
+
523
+ Args:
524
+ func (function): A Python function that takes one or more arguments,
525
+ one of which must be a Tensor, and returns one or more Tensors
526
+ argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
527
+ saying which arguments to get the Jacobian with respect to.
528
+ Default: 0.
529
+ has_aux (bool): Flag indicating that ``func`` returns a
530
+ ``(output, aux)`` tuple where the first element is the output of
531
+ the function to be differentiated and the second element is
532
+ auxiliary objects that will not be differentiated.
533
+ Default: False.
534
+ chunk_size (None or int): If None (default), use the maximum chunk size
535
+ (equivalent to doing a single vmap over vjp to compute the jacobian).
536
+ If 1, then compute the jacobian row-by-row with a for-loop.
537
+ If not None, then compute the jacobian :attr:`chunk_size` rows at a time
538
+ (equivalent to doing multiple vmap over vjp). If you run into memory issues computing
539
+ the jacobian, please try to specify a non-None chunk_size.
540
+
541
+ Returns:
542
+ Returns a function that takes in the same inputs as ``func`` and
543
+ returns the Jacobian of ``func`` with respect to the arg(s) at
544
+ ``argnums``. If ``has_aux is True``, then the returned function
545
+ instead returns a ``(jacobian, aux)`` tuple where ``jacobian``
546
+ is the Jacobian and ``aux`` is auxiliary objects returned by ``func``.
547
+
548
+ A basic usage with a pointwise, unary operation will give a diagonal array
549
+ as the Jacobian
550
+
551
+ >>> from torch.func import jacrev
552
+ >>> x = torch.randn(5)
553
+ >>> jacobian = jacrev(torch.sin)(x)
554
+ >>> expected = torch.diag(torch.cos(x))
555
+ >>> assert torch.allclose(jacobian, expected)
556
+
557
+ If you would like to compute the output of the function as well as the
558
+ jacobian of the function, use the ``has_aux`` flag to return the output
559
+ as an auxiliary object:
560
+
561
+ >>> from torch.func import jacrev
562
+ >>> x = torch.randn(5)
563
+ >>>
564
+ >>> def f(x):
565
+ >>> return x.sin()
566
+ >>>
567
+ >>> def g(x):
568
+ >>> result = f(x)
569
+ >>> return result, result
570
+ >>>
571
+ >>> jacobian_f, f_x = jacrev(g, has_aux=True)(x)
572
+ >>> assert torch.allclose(f_x, f(x))
573
+
574
+ :func:`jacrev` can be composed with vmap to produce batched
575
+ Jacobians:
576
+
577
+ >>> from torch.func import jacrev, vmap
578
+ >>> x = torch.randn(64, 5)
579
+ >>> jacobian = vmap(jacrev(torch.sin))(x)
580
+ >>> assert jacobian.shape == (64, 5, 5)
581
+
582
+ Additionally, :func:`jacrev` can be composed with itself to produce
583
+ Hessians
584
+
585
+ >>> from torch.func import jacrev
586
+ >>> def f(x):
587
+ >>> return x.sin().sum()
588
+ >>>
589
+ >>> x = torch.randn(5)
590
+ >>> hessian = jacrev(jacrev(f))(x)
591
+ >>> assert torch.allclose(hessian, torch.diag(-x.sin()))
592
+
593
+ By default, :func:`jacrev` computes the Jacobian with respect to the first
594
+ input. However, it can compute the Jacobian with respect to a different
595
+ argument by using ``argnums``:
596
+
597
+ >>> from torch.func import jacrev
598
+ >>> def f(x, y):
599
+ >>> return x + y ** 2
600
+ >>>
601
+ >>> x, y = torch.randn(5), torch.randn(5)
602
+ >>> jacobian = jacrev(f, argnums=1)(x, y)
603
+ >>> expected = torch.diag(2 * y)
604
+ >>> assert torch.allclose(jacobian, expected)
605
+
606
+ Additionally, passing a tuple to ``argnums`` will compute the Jacobian
607
+ with respect to multiple arguments
608
+
609
+ >>> from torch.func import jacrev
610
+ >>> def f(x, y):
611
+ >>> return x + y ** 2
612
+ >>>
613
+ >>> x, y = torch.randn(5), torch.randn(5)
614
+ >>> jacobian = jacrev(f, argnums=(0, 1))(x, y)
615
+ >>> expectedX = torch.diag(torch.ones_like(x))
616
+ >>> expectedY = torch.diag(2 * y)
617
+ >>> assert torch.allclose(jacobian[0], expectedX)
618
+ >>> assert torch.allclose(jacobian[1], expectedY)
619
+
620
+ .. note::
621
+ Using PyTorch ``torch.no_grad`` together with ``jacrev``.
622
+ Case 1: Using ``torch.no_grad`` inside a function:
623
+
624
+ >>> def f(x):
625
+ >>> with torch.no_grad():
626
+ >>> c = x ** 2
627
+ >>> return x - c
628
+
629
+ In this case, ``jacrev(f)(x)`` will respect the inner ``torch.no_grad``.
630
+
631
+ Case 2: Using ``jacrev`` inside ``torch.no_grad`` context manager:
632
+
633
+ >>> with torch.no_grad():
634
+ >>> jacrev(f)(x)
635
+
636
+ In this case, ``jacrev`` will respect the inner ``torch.no_grad``, but not the
637
+ outer one. This is because ``jacrev`` is a "function transform": its result
638
+ should not depend on the result of a context manager outside of ``f``.
639
+ """
640
+ if not (chunk_size is None or chunk_size > 0):
641
+ raise ValueError("jacrev: `chunk_size` should be greater than 0.")
642
+
643
+ @_wraps_without_dynamo_attrs(func)
644
+ def wrapper_fn(*args: Any) -> Any:
645
+ error_if_complex("jacrev", args, is_input=True)
646
+ vjp_out = _vjp_with_argnums(func, *args, argnums=argnums, has_aux=has_aux)
647
+ aux: Any = None
648
+ if has_aux:
649
+ # pyrefly: ignore[bad-unpacking]
650
+ output, vjp_fn, aux = vjp_out
651
+ else:
652
+ # pyrefly: ignore[bad-unpacking]
653
+ output, vjp_fn = vjp_out
654
+
655
+ # See NOTE: [Computing jacobian with vmap and vjp for multiple outputs]
656
+ flat_output, output_spec = tree_flatten(output)
657
+
658
+ error_if_complex("jacrev", flat_output, is_input=False)
659
+
660
+ # NB: vjp already checks that all outputs are tensors
661
+ # Step 1: Construct grad_outputs by splitting the standard basis
662
+ flat_output_numels = tuple(out.numel() for out in flat_output)
663
+
664
+ primals = _slice_argnums(args, argnums)
665
+ flat_primals, primals_spec = tree_flatten(primals)
666
+
667
+ def compute_jacobian_stacked() -> list[Any]:
668
+ # Helper function to compute chunked Jacobian
669
+ # The intermediate chunked calculation are only
670
+ # scoped at this function level.
671
+ chunked_results: list[list[Any]] = []
672
+ for flat_basis_chunk in _chunked_standard_basis_for_(
673
+ flat_output, flat_output_numels, chunk_size=chunk_size
674
+ ):
675
+ if chunk_size == 1:
676
+ # sanity check.
677
+ for t in flat_basis_chunk:
678
+ if t.size(0) != 1:
679
+ raise AssertionError(
680
+ f"expected t.size(0) to be 1, got {t.size(0)}"
681
+ )
682
+
683
+ flat_basis_chunk = tree_map(
684
+ lambda t: torch.squeeze(t, 0), flat_basis_chunk
685
+ )
686
+
687
+ basis = tree_unflatten(flat_basis_chunk, output_spec)
688
+
689
+ if chunk_size == 1:
690
+ # Behaviour with `chunk_size=1` is same as `for-loop`
691
+ # i.e. user shouldn't deal with the limitations of vmap.
692
+ chunked_result = vjp_fn(basis)
693
+ else: # chunk_size is None or chunk_size != 1
694
+ chunked_result = vmap(vjp_fn)(basis)
695
+
696
+ flat_results = pytree.tree_leaves(chunked_result)
697
+
698
+ if chunk_size == 1:
699
+ flat_results = tree_map(
700
+ lambda t: torch.unsqueeze(t, 0), flat_results
701
+ )
702
+
703
+ chunked_results.append(flat_results)
704
+
705
+ if len(chunked_results) == 1:
706
+ # Short-circuit if we used a single chunk
707
+ return chunked_results[0]
708
+
709
+ # Concatenate chunks.
710
+ flat_results = []
711
+ # Iterate and concat the jacobians of different
712
+ # inputs.
713
+ for idx in range(len(flat_primals)):
714
+ r = tuple(r_[idx] for r_ in chunked_results)
715
+ flat_results.append(torch.cat(r, 0))
716
+
717
+ return flat_results
718
+
719
+ def compute_jacobian_preallocate_and_copy() -> list[Any]:
720
+ # Helper function to compute chunked Jacobian
721
+ # The intermediate chunked calculation are only
722
+ # scoped at this function level.
723
+ out_vec_size = sum(flat_output_numels)
724
+
725
+ # Don't pre-allocate if we have a single chunk.
726
+ stacked_results: list[torch.Tensor] = []
727
+ if not (chunk_size is None or chunk_size >= out_vec_size):
728
+ stacked_results = [
729
+ primal.new_zeros(out_vec_size, *primal.shape)
730
+ for primal in flat_primals
731
+ ]
732
+
733
+ for idx, flat_basis_chunk in enumerate(
734
+ _chunked_standard_basis_for_(
735
+ flat_output, flat_output_numels, chunk_size=chunk_size
736
+ )
737
+ ):
738
+ if chunk_size == 1:
739
+ # sanity check.
740
+ for t in flat_basis_chunk:
741
+ if t.size(0) != 1:
742
+ raise AssertionError(
743
+ f"expected t.size(0) to be 1, got {t.size(0)}"
744
+ )
745
+
746
+ flat_basis_chunk = [torch.squeeze(t, 0) for t in flat_basis_chunk]
747
+
748
+ basis = tree_unflatten(flat_basis_chunk, output_spec)
749
+
750
+ if chunk_size == 1:
751
+ # Behaviour with `chunk_size=1` is same as `for-loop`
752
+ # i.e. user shouldn't deal with the limitations of vmap.
753
+ chunked_result = vjp_fn(basis)
754
+ else: # chunk_size is None or chunk_size != 1
755
+ chunked_result = vmap(vjp_fn)(basis)
756
+
757
+ flat_results = pytree.tree_leaves(chunked_result)
758
+
759
+ # Short-circuit if we have a single chunk.
760
+ if chunk_size is None or chunk_size >= out_vec_size:
761
+ if chunk_size == 1: # and out_vec_size == 1
762
+ # Since we squeezed the output dim
763
+ flat_results = tree_map(
764
+ lambda t: torch.unsqueeze(t, 0), flat_results
765
+ )
766
+ return flat_results
767
+
768
+ for r, sr in zip(flat_results, stacked_results): # type: ignore[possibly-unbound]
769
+ sr[idx * chunk_size : (idx + 1) * chunk_size].copy_(r)
770
+
771
+ return stacked_results # type: ignore[possibly-unbound]
772
+
773
+ if _preallocate_and_copy:
774
+ flat_jacobians_per_input = compute_jacobian_preallocate_and_copy()
775
+ else:
776
+ flat_jacobians_per_input = compute_jacobian_stacked()
777
+
778
+ # Step 2: The returned jacobian is one big tensor per input. In this step,
779
+ # we split each Tensor by output.
780
+ flat_jacobians_per_input = [
781
+ torch.split(result, list(flat_output_numels), dim=0)
782
+ for result in flat_jacobians_per_input
783
+ ]
784
+ flat_input_flat_output = [
785
+ tuple(
786
+ split.view(out.shape + primal.shape)
787
+ for split, out in zip(splits, flat_output)
788
+ )
789
+ for splits, primal in zip(flat_jacobians_per_input, flat_primals)
790
+ ]
791
+
792
+ # Step 3: Right now, `jacobian` is a List[List[Tensor]].
793
+ # The outer List corresponds to the number of primals,
794
+ # the inner List corresponds to the number of outputs.
795
+ # We need to:
796
+ # a. Exchange the order of the outer List and inner List
797
+ # b. tree_unflatten the inner Lists (which correspond to the primals)
798
+ # c. handle the argnums=int case
799
+ # d. tree_unflatten the outer List (which corresponds to the outputs)
800
+ flat_output_flat_input = tuple(zip(*flat_input_flat_output))
801
+
802
+ flat_output_input = tuple(
803
+ tree_unflatten(flat_input, primals_spec)
804
+ for flat_input in flat_output_flat_input
805
+ )
806
+
807
+ if isinstance(argnums, int):
808
+ flat_output_input = tuple(
809
+ _safe_zero_index(flat_input) for flat_input in flat_output_input
810
+ )
811
+ output_input = tree_unflatten(flat_output_input, output_spec)
812
+ if has_aux:
813
+ return output_input, aux # type: ignore[possibly-unbound]
814
+ return output_input
815
+
816
+ return wrapper_fn
817
+
818
+
819
+ # NOTE: [Computing jacobian with vmap and vjp for multiple outputs]
820
+ #
821
+ # Let's consider f(x) = (x**2, x.sum()) and let x = torch.randn(3).
822
+ # It turns out we can compute the jacobian of this function with a single
823
+ # call to autograd.grad by using vmap over the correct grad_outputs.
824
+ #
825
+ # Firstly, one way to compute the jacobian is to stack x**2 and x.sum()
826
+ # into a 4D vector. E.g., use g(x) = torch.stack([x**2, x.sum()])
827
+ #
828
+ # To get the first row of the jacobian, we call
829
+ # >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([1, 0, 0, 0]))
830
+ # To get the 2nd row of the jacobian, we call
831
+ # >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([0, 1, 0, 0]))
832
+ # and so on.
833
+ #
834
+ # Using vmap, we can vectorize all 4 of these computations into one by
835
+ # passing the standard basis for R^4 as the grad_output.
836
+ # vmap(partial(autograd.grad, g(x), x))(torch.eye(4)).
837
+ #
838
+ # Now, how do we compute the jacobian *without stacking the output*?
839
+ # We can just split the standard basis across the outputs. So to
840
+ # compute the jacobian of f(x), we'd use
841
+ # >>> autograd.grad(f(x), x, grad_outputs=_construct_standard_basis_for(...))
842
+ # The grad_outputs looks like the following:
843
+ # ( torch.tensor([[1, 0, 0],
844
+ # [0, 1, 0],
845
+ # [0, 0, 1],
846
+ # [0, 0, 0]]),
847
+ # torch.tensor([[0],
848
+ # [0],
849
+ # [0],
850
+ # [1]]) )
851
+ #
852
+ # But we're not done yet!
853
+ # >>> vmap(partial(autograd.grad(f(x), x, grad_outputs=...)))
854
+ # returns a Tensor of shape [4, 3]. We have to remember to split the
855
+ # jacobian of shape [4, 3] into two:
856
+ # - one of shape [3, 3] for the first output
857
+ # - one of shape [ 3] for the second output
858
+
859
+
860
+ def _chunked_standard_basis_for_(
861
+ tensors: Sequence[torch.Tensor],
862
+ tensor_numels: Sequence[int],
863
+ chunk_size: int | None = None,
864
+ ) -> Generator[tuple[torch.Tensor, ...], None, None]:
865
+ # This function:
866
+ # - constructs a N=sum(tensor_numels) standard basis. i.e. an NxN identity matrix.
867
+ # - Splits the identity matrix into chunks with each chunk size determined by `tensor_numels`.
868
+ # - Each chunk corresponds to one tensor. The chunk has the same dtype and
869
+ # device as the tensor
870
+ #
871
+ # For example, with tensor_numels = [1, 2, 1], this function returns:
872
+ # ( tensor([[1], tensor([[0, 0], tensor([[0],
873
+ # [0], [1, 0], [0],
874
+ # [0], [0, 1], [0],
875
+ # [0]]) , [0, 0]]) , [1]]) )
876
+ #
877
+ # Precondition: tensor_numels == tuple(tensor.numel() for tensor in tensors)
878
+ # Precondition: tensors always has at least one element.
879
+ #
880
+ # See NOTE: [Computing jacobian with vmap and grad for multiple tensors]
881
+ # for context behind this function.
882
+ # NOTE: Argument `chunk_size` is used to generate chunked basis instead of
883
+ # one huge basis matrix. `chunk_size` dictates the maximum size of the
884
+ # basis matrix along dim=0.
885
+ if len(tensors) != len(tensor_numels):
886
+ raise AssertionError(
887
+ f"len(tensors)={len(tensors)} != len(tensor_numels)={len(tensor_numels)}"
888
+ )
889
+ if len(tensors) == 0:
890
+ raise AssertionError("tensors must have at least one element")
891
+ if chunk_size is not None and chunk_size <= 0:
892
+ raise AssertionError(f"chunk_size must be > 0 or None, got {chunk_size}")
893
+ total_numel = sum(tensor_numels)
894
+ if chunk_size and chunk_size < total_numel:
895
+ chunk_numels = get_chunk_sizes(total_numel, chunk_size)
896
+ else: # chunk_size is None or chunk_size >= total_numel
897
+ chunk_size = total_numel
898
+ chunk_numels = [total_numel]
899
+
900
+ diag_start_indices = []
901
+ diag_start_idx = 0
902
+ for tensor_numel in tensor_numels:
903
+ diag_start_indices.append(diag_start_idx)
904
+ diag_start_idx -= tensor_numel
905
+
906
+ for chunk_idx, total_numel in enumerate(chunk_numels):
907
+ chunks = tuple(
908
+ tensor.new_zeros(total_numel, tensor_numel)
909
+ for tensor, tensor_numel in zip(tensors, tensor_numels)
910
+ )
911
+
912
+ for chunk, diag_start_idx in zip(chunks, diag_start_indices):
913
+ offset = int(diag_start_idx) + chunk_idx * chunk_size
914
+ chunk.diagonal(offset).fill_(1)
915
+ chunks = tuple(
916
+ chunk.view(total_numel, *tensor.shape)
917
+ for chunk, tensor in zip(chunks, tensors)
918
+ )
919
+ yield chunks
920
+
921
+
922
+ def _construct_standard_basis_for(
923
+ tensors: Sequence[torch.Tensor], tensor_numels: Sequence[int]
924
+ ) -> tuple[torch.Tensor, ...] | None:
925
+ for basis in _chunked_standard_basis_for_(tensors, tensor_numels, chunk_size=None):
926
+ return basis
927
+ return None
928
+
929
+
930
+ def _validate_and_wrap_argnum(argnum: int, num_args: int) -> int:
931
+ if not isinstance(argnum, int):
932
+ raise RuntimeError(f"argnum must be int, got: {type(argnum)}")
933
+ if argnum >= 0 and argnum < num_args:
934
+ return argnum
935
+ if argnum < 0 and argnum >= -num_args:
936
+ return argnum + num_args
937
+ raise RuntimeError(f"Got argnum={argnum}, but only {num_args} positional inputs")
938
+
939
+
940
+ def _check_unique_non_empty(argnums: argnums_t) -> None:
941
+ if isinstance(argnums, tuple):
942
+ if len(argnums) == 0:
943
+ raise RuntimeError("argnums must be non-empty")
944
+ if len(set(argnums)) != len(argnums):
945
+ raise RuntimeError(f"argnums elements must be unique, got {argnums}")
946
+
947
+
948
+ def _replace_args(
949
+ old_args: tuple[Any, ...], new_args: tuple[Any, ...], argnums: argnums_t
950
+ ) -> tuple[Any, ...]:
951
+ if isinstance(argnums, int):
952
+ if len(new_args) != 1:
953
+ raise RuntimeError(
954
+ f"new_args should be of size 1, was of size {len(new_args)}"
955
+ )
956
+ return tuple(
957
+ new_args[0] if i == argnums else old_args[i] for i in range(len(old_args))
958
+ )
959
+ if isinstance(argnums, tuple):
960
+ if len(new_args) != len(argnums):
961
+ raise RuntimeError(
962
+ "new_args should have the same size as argnums. "
963
+ f"Argnums size {len(argnums)}, new_args size {len(new_args)}"
964
+ )
965
+
966
+ argnums_tuple = argnums
967
+
968
+ def get_right_elem(i: int) -> Any:
969
+ return (
970
+ new_args[argnums_tuple.index(i)] if i in argnums_tuple else old_args[i]
971
+ )
972
+
973
+ return tuple(get_right_elem(i) for i in range(len(old_args)))
974
+ raise RuntimeError(f"argnums must be int or Tuple[int, ...], got: {type(argnums)}")
975
+
976
+
977
+ def _validate_and_wrap_argnums(argnums: argnums_t, num_args: int) -> argnums_t:
978
+ if isinstance(argnums, int):
979
+ return _validate_and_wrap_argnum(argnums, num_args)
980
+ if isinstance(argnums, tuple):
981
+ return tuple(_validate_and_wrap_argnum(argnum, num_args) for argnum in argnums)
982
+ raise AssertionError("Should never get here")
983
+
984
+
985
+ def _slice_argnums(
986
+ args: tuple[Any, ...], argnums: argnums_t, as_tuple: bool = True
987
+ ) -> Any:
988
+ if not isinstance(argnums, int) and not isinstance(argnums, tuple):
989
+ raise RuntimeError(
990
+ f"argnums must be int or Tuple[int, ...], got: {type(argnums)}"
991
+ )
992
+ argnums = _validate_and_wrap_argnums(argnums, len(args))
993
+ _check_unique_non_empty(argnums)
994
+ if isinstance(argnums, int):
995
+ if as_tuple:
996
+ return (args[argnums],)
997
+ else:
998
+ return args[argnums]
999
+ return tuple(args[i] for i in argnums)
1000
+
1001
+
1002
+ JVP_NESTING = 0
1003
+
1004
+
1005
+ def assert_flat_tuple_of_tensors(elts: Any, api: str, argname: str) -> None:
1006
+ if not isinstance(elts, tuple):
1007
+ raise RuntimeError(
1008
+ f"{api}: Expected {argname} to be a tuple of Tensors, got {type(elts)}"
1009
+ )
1010
+ for elt in elts:
1011
+ if isinstance(elt, torch.Tensor):
1012
+ continue
1013
+ raise RuntimeError(
1014
+ f"{api}: Expected {argname} to be a tuple of Tensors, got "
1015
+ f"a tuple with an element of type {type(elt)}"
1016
+ )
1017
+ if len(elts) == 0:
1018
+ raise RuntimeError(
1019
+ f"{api}: Expected {argname} to be a non-empty tuple of Tensors."
1020
+ )
1021
+
1022
+
1023
+ def assert_non_empty_tensor_output(output: list[Any], api: str) -> None:
1024
+ if (len(output) == 1 and output[0] is None) or len(output) < 1:
1025
+ raise RuntimeError(
1026
+ f"{api}: Expected f to be a function that has non-empty output (got output = {output})"
1027
+ )
1028
+ for o in output:
1029
+ if not isinstance(o, torch.Tensor):
1030
+ raise RuntimeError(
1031
+ f"{api}: expected f(*primals) to return only tensors"
1032
+ f", got unsupported type {type(o)}"
1033
+ )
1034
+
1035
+
1036
+ def assert_output_is_tensor_or_tensors(output: Any, api: str) -> None:
1037
+ if isinstance(output, torch.Tensor):
1038
+ return
1039
+ if not isinstance(output, tuple):
1040
+ raise RuntimeError(
1041
+ f"{api}: Expected output of f to be a Tensor or Tensors, got {type(output)}"
1042
+ )
1043
+ if len(output) == 0:
1044
+ raise RuntimeError(
1045
+ f"{api}: Expected output of f to be a non-empty tuple of Tensors."
1046
+ )
1047
+ for out in output:
1048
+ if isinstance(out, torch.Tensor):
1049
+ continue
1050
+ raise RuntimeError(
1051
+ f"{api}: Expected output of f to be a Tensor or Tensors, got "
1052
+ f"{type(out)} as an output"
1053
+ )
1054
+
1055
+
1056
+ def assert_non_empty_list_of_tensors(
1057
+ output: list[torch.Tensor], api: str, argname: str
1058
+ ) -> None:
1059
+ if len(output) == 0:
1060
+ raise RuntimeError(f"{api}: Expected {argname} to contain at least one Tensor.")
1061
+ for out in output:
1062
+ if isinstance(out, torch.Tensor):
1063
+ continue
1064
+ raise RuntimeError(
1065
+ f"{api}: Expected {argname} to only contain Tensors, got {type(out)}"
1066
+ )
1067
+
1068
+
1069
+ jvp_str = "jvp(f, primals, tangents)"
1070
+
1071
+
1072
+ def safe_unpack_dual(
1073
+ dual: torch.Tensor, strict: bool
1074
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1075
+ if not isinstance(dual, torch.Tensor):
1076
+ raise RuntimeError(
1077
+ f"{jvp_str}: expected f(*args) to return only tensors"
1078
+ f", got unsupported type {type(dual)}"
1079
+ )
1080
+
1081
+ primal, tangent = fwAD.unpack_dual(dual)
1082
+ if tangent is None:
1083
+ if strict:
1084
+ raise RuntimeError(
1085
+ "jvp(f, primals, tangents, strict=True): "
1086
+ "The output of f is independent of "
1087
+ "the inputs. This is not allowed with strict=True."
1088
+ )
1089
+ tangent = torch.zeros_like(primal)
1090
+ return primal, tangent
1091
+
1092
+
1093
+ @exposed_in("torch.func")
1094
+ def jvp(
1095
+ func: Callable[..., Any],
1096
+ primals: Any,
1097
+ tangents: Any,
1098
+ *,
1099
+ strict: bool = False,
1100
+ has_aux: bool = False,
1101
+ ) -> tuple[Any, Any] | tuple[Any, Any, Any]:
1102
+ """
1103
+ Standing for the Jacobian-vector product, returns a tuple containing
1104
+ the output of `func(*primals)` and the "Jacobian of ``func`` evaluated at
1105
+ ``primals``" times ``tangents``. This is also known as forward-mode autodiff.
1106
+
1107
+ Args:
1108
+ func (function): A Python function that takes one or more arguments,
1109
+ one of which must be a Tensor, and returns one or more Tensors
1110
+ primals (Tensors): Positional arguments to ``func`` that must all be
1111
+ Tensors. The returned function will also be computing the
1112
+ derivative with respect to these arguments
1113
+ tangents (Tensors): The "vector" for which Jacobian-vector-product is
1114
+ computed. Must be the same structure and sizes as the inputs to
1115
+ ``func``.
1116
+ has_aux (bool): Flag indicating that ``func`` returns a
1117
+ ``(output, aux)`` tuple where the first element is the output of
1118
+ the function to be differentiated and the second element is
1119
+ other auxiliary objects that will not be differentiated.
1120
+ Default: False.
1121
+
1122
+ Returns:
1123
+ Returns a ``(output, jvp_out)`` tuple containing the output of ``func``
1124
+ evaluated at ``primals`` and the Jacobian-vector product.
1125
+ If ``has_aux is True``, then instead returns a ``(output, jvp_out, aux)`` tuple.
1126
+
1127
+ .. note::
1128
+ You may see this API error out with "forward-mode AD not implemented
1129
+ for operator X". If so, please file a bug report and we will prioritize it.
1130
+
1131
+ jvp is useful when you wish to compute gradients of a function R^1 -> R^N
1132
+
1133
+ >>> from torch.func import jvp
1134
+ >>> x = torch.randn([])
1135
+ >>> f = lambda x: x * torch.tensor([1.0, 2.0, 3])
1136
+ >>> warnings.filterwarnings(
1137
+ ... "ignore", message=".*torch.jit.script"
1138
+ ... ) # docs: hide
1139
+ >>> value, grad = jvp(f, (x,), (torch.tensor(1.0),))
1140
+ >>> assert torch.allclose(value, f(x))
1141
+ >>> assert torch.allclose(grad, torch.tensor([1.0, 2, 3]))
1142
+
1143
+ :func:`jvp` can support functions with multiple inputs by passing in the
1144
+ tangents for each of the inputs
1145
+
1146
+ >>> from torch.func import jvp
1147
+ >>> x = torch.randn(5)
1148
+ >>> y = torch.randn(5)
1149
+ >>> f = lambda x, y: (x * y)
1150
+ >>> _, output = jvp(f, (x, y), (torch.ones(5), torch.ones(5)))
1151
+ >>> assert torch.allclose(output, x + y)
1152
+
1153
+ """
1154
+
1155
+ return _jvp_with_argnums(
1156
+ func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux
1157
+ )
1158
+
1159
+
1160
+ def _jvp_with_argnums(
1161
+ func: Callable[..., Any],
1162
+ primals: Any,
1163
+ tangents: Any,
1164
+ argnums: argnums_t | None,
1165
+ *,
1166
+ strict: bool = False,
1167
+ has_aux: bool,
1168
+ ) -> tuple[Any, Any] | tuple[Any, Any, Any]:
1169
+ # This is the same function as jvp but also accepts an argnums argument
1170
+ # Most args are the same as jvp except for the added argument
1171
+ # argnums (int or tuple[int, ...]): Optional, specifies the argument(s) to compute gradients with respect to.
1172
+ # If None, computes the gradients with respect to all inputs (used for jvp). Default: None
1173
+ # Because of this, tangents must be of length argnums and matches up to the corresponding primal whose index is
1174
+ # given by argnums
1175
+ #
1176
+ # WARN: Users should NOT call this function directly and should just be calling jvp.
1177
+ # It is only separated so that inputs passed to jacfwd but not differentiated get the correct wrappers.
1178
+ #
1179
+ # NOTE: All error messages are produced as if jvp was being called, even if this was called by jacfwd
1180
+ #
1181
+ # Returns the same two elements as :func:`jvp` but the returned tuple, ``jvp_out``, only has JVPs with respect to
1182
+ # the primals given by argnums
1183
+ if not isinstance(primals, tuple):
1184
+ raise RuntimeError(
1185
+ f"{jvp_str}: Expected primals to be a tuple. "
1186
+ f"E.g. it should be valid to call f(*primals)."
1187
+ )
1188
+ diff_args = primals if argnums is None else _slice_argnums(primals, argnums)
1189
+ flat_primals, primals_spec = tree_flatten(diff_args)
1190
+ flat_tangents, tangents_spec = tree_flatten(tangents)
1191
+ if primals_spec != tangents_spec:
1192
+ raise RuntimeError(
1193
+ f"{jvp_str}: Expected primals and tangents to have the same python "
1194
+ f"structure. For example, if primals is a tuple of 3 tensors, "
1195
+ f"tangents also must be. Got primals with structure {primals_spec} "
1196
+ f"and tangents with structure {tangents_spec}"
1197
+ )
1198
+ assert_non_empty_list_of_tensors(flat_primals, jvp_str, "primals")
1199
+ assert_non_empty_list_of_tensors(flat_tangents, jvp_str, "tangents")
1200
+
1201
+ global JVP_NESTING
1202
+
1203
+ with jvp_increment_nesting() as level:
1204
+ with fwAD._set_fwd_grad_enabled(True):
1205
+ ctx = fwAD.dual_level if JVP_NESTING == 1 else contextlib.nullcontext
1206
+ with ctx():
1207
+ flat_duals = tuple(
1208
+ fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents)
1209
+ )
1210
+ duals = tree_unflatten(flat_duals, primals_spec)
1211
+ if argnums is not None:
1212
+ primals = _wrap_all_tensors(primals, level)
1213
+ duals = _replace_args(primals, duals, argnums)
1214
+ result_duals = func(*duals)
1215
+ aux: Any = None
1216
+ if has_aux:
1217
+ if not (isinstance(result_duals, tuple) and len(result_duals) == 2):
1218
+ raise RuntimeError(
1219
+ f"{jvp_str}: output of function f should be a tuple: (output, aux) "
1220
+ "if has_aux is True"
1221
+ )
1222
+ result_duals, aux = result_duals
1223
+ aux = _undo_create_differentiable(aux, level)
1224
+
1225
+ result_duals, spec = tree_flatten(result_duals)
1226
+ assert_non_empty_tensor_output(result_duals, jvp_str)
1227
+
1228
+ primals_out, tangents_out = zip(
1229
+ *[safe_unpack_dual(dual, strict) for dual in result_duals]
1230
+ )
1231
+ primals_out = tree_map(
1232
+ partial(_undo_create_differentiable, level=level), primals_out
1233
+ )
1234
+ tangents_out = tree_map(
1235
+ partial(_undo_create_differentiable, level=level), tangents_out
1236
+ )
1237
+
1238
+ primals_out_unflatten = tree_unflatten(primals_out, spec)
1239
+ tangents_out_unflatten = tree_unflatten(tangents_out, spec)
1240
+ if has_aux:
1241
+ return primals_out_unflatten, tangents_out_unflatten, aux # type: ignore[possibly-unbound]
1242
+
1243
+ return primals_out_unflatten, tangents_out_unflatten
1244
+
1245
+
1246
+ def safe_unflatten(tensor: torch.Tensor, dim: int, shape: torch.Size) -> torch.Tensor:
1247
+ if len(shape) == 0:
1248
+ if tensor.shape[dim] != 1:
1249
+ raise AssertionError(
1250
+ f"expected tensor.shape[{dim}] to be 1, got {tensor.shape[dim]}"
1251
+ )
1252
+ return tensor.squeeze(dim)
1253
+ return tensor.unflatten(dim, shape)
1254
+
1255
+
1256
+ @exposed_in("torch.func")
1257
+ def jacfwd(
1258
+ func: Callable[..., Any],
1259
+ argnums: argnums_t = 0,
1260
+ has_aux: bool = False,
1261
+ *,
1262
+ randomness: str = "error",
1263
+ ) -> Callable[..., Any]:
1264
+ """
1265
+ Computes the Jacobian of ``func`` with respect to the arg(s) at index
1266
+ ``argnum`` using forward-mode autodiff
1267
+
1268
+ Args:
1269
+ func (function): A Python function that takes one or more arguments,
1270
+ one of which must be a Tensor, and returns one or more Tensors
1271
+ argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
1272
+ saying which arguments to get the Jacobian with respect to.
1273
+ Default: 0.
1274
+ has_aux (bool): Flag indicating that ``func`` returns a
1275
+ ``(output, aux)`` tuple where the first element is the output of
1276
+ the function to be differentiated and the second element is
1277
+ auxiliary objects that will not be differentiated.
1278
+ Default: False.
1279
+ randomness(str): Flag indicating what type of randomness to use.
1280
+ See :func:`vmap` for more detail. Allowed: "different", "same", "error".
1281
+ Default: "error"
1282
+
1283
+ Returns:
1284
+ Returns a function that takes in the same inputs as ``func`` and
1285
+ returns the Jacobian of ``func`` with respect to the arg(s) at
1286
+ ``argnums``. If ``has_aux is True``, then the returned function
1287
+ instead returns a ``(jacobian, aux)`` tuple where ``jacobian``
1288
+ is the Jacobian and ``aux`` is auxiliary objects returned by ``func``.
1289
+
1290
+ .. note::
1291
+ You may see this API error out with "forward-mode AD not implemented
1292
+ for operator X". If so, please file a bug report and we will prioritize it.
1293
+ An alternative is to use :func:`jacrev`, which has better operator coverage.
1294
+
1295
+ A basic usage with a pointwise, unary operation will give a diagonal array
1296
+ as the Jacobian
1297
+
1298
+ >>> from torch.func import jacfwd
1299
+ >>> x = torch.randn(5)
1300
+ >>> jacobian = jacfwd(torch.sin)(x)
1301
+ >>> expected = torch.diag(torch.cos(x))
1302
+ >>> assert torch.allclose(jacobian, expected)
1303
+
1304
+ :func:`jacfwd` can be composed with vmap to produce batched
1305
+ Jacobians:
1306
+
1307
+ >>> from torch.func import jacfwd, vmap
1308
+ >>> x = torch.randn(64, 5)
1309
+ >>> jacobian = vmap(jacfwd(torch.sin))(x)
1310
+ >>> assert jacobian.shape == (64, 5, 5)
1311
+
1312
+ If you would like to compute the output of the function as well as the
1313
+ jacobian of the function, use the ``has_aux`` flag to return the output
1314
+ as an auxiliary object:
1315
+
1316
+ >>> from torch.func import jacfwd
1317
+ >>> x = torch.randn(5)
1318
+ >>>
1319
+ >>> def f(x):
1320
+ >>> return x.sin()
1321
+ >>>
1322
+ >>> def g(x):
1323
+ >>> result = f(x)
1324
+ >>> return result, result
1325
+ >>>
1326
+ >>> jacobian_f, f_x = jacfwd(g, has_aux=True)(x)
1327
+ >>> assert torch.allclose(f_x, f(x))
1328
+
1329
+ Additionally, :func:`jacrev` can be composed with itself or :func:`jacrev`
1330
+ to produce Hessians
1331
+
1332
+ >>> from torch.func import jacfwd, jacrev
1333
+ >>> def f(x):
1334
+ >>> return x.sin().sum()
1335
+ >>>
1336
+ >>> x = torch.randn(5)
1337
+ >>> hessian = jacfwd(jacrev(f))(x)
1338
+ >>> assert torch.allclose(hessian, torch.diag(-x.sin()))
1339
+
1340
+ By default, :func:`jacfwd` computes the Jacobian with respect to the first
1341
+ input. However, it can compute the Jacobian with respect to a different
1342
+ argument by using ``argnums``:
1343
+
1344
+ >>> from torch.func import jacfwd
1345
+ >>> def f(x, y):
1346
+ >>> return x + y ** 2
1347
+ >>>
1348
+ >>> x, y = torch.randn(5), torch.randn(5)
1349
+ >>> jacobian = jacfwd(f, argnums=1)(x, y)
1350
+ >>> expected = torch.diag(2 * y)
1351
+ >>> assert torch.allclose(jacobian, expected)
1352
+
1353
+ Additionally, passing a tuple to ``argnums`` will compute the Jacobian
1354
+ with respect to multiple arguments
1355
+
1356
+ >>> from torch.func import jacfwd
1357
+ >>> def f(x, y):
1358
+ >>> return x + y ** 2
1359
+ >>>
1360
+ >>> x, y = torch.randn(5), torch.randn(5)
1361
+ >>> jacobian = jacfwd(f, argnums=(0, 1))(x, y)
1362
+ >>> expectedX = torch.diag(torch.ones_like(x))
1363
+ >>> expectedY = torch.diag(2 * y)
1364
+ >>> assert torch.allclose(jacobian[0], expectedX)
1365
+ >>> assert torch.allclose(jacobian[1], expectedY)
1366
+
1367
+ """
1368
+
1369
+ @_wraps_without_dynamo_attrs(func)
1370
+ def wrapper_fn(*args: Any) -> Any:
1371
+ error_if_complex("jacfwd", args, is_input=True)
1372
+ primals = args if argnums is None else _slice_argnums(args, argnums)
1373
+ flat_primals, primals_spec = tree_flatten(primals)
1374
+ flat_primals_numels = tuple(p.numel() for p in flat_primals)
1375
+ flat_basis = _construct_standard_basis_for(flat_primals, flat_primals_numels)
1376
+ if flat_basis is None:
1377
+ raise AssertionError("flat_basis must not be None")
1378
+ basis = tree_unflatten(flat_basis, primals_spec)
1379
+
1380
+ def push_jvp(basis: Any) -> Any:
1381
+ output = _jvp_with_argnums(
1382
+ func, args, basis, argnums=argnums, has_aux=has_aux
1383
+ )
1384
+ # output[0] is the output of `func(*args)`
1385
+ error_if_complex("jacfwd", output[0], is_input=False)
1386
+ if has_aux:
1387
+ _, jvp_out, aux = output # pyrefly: ignore[bad-unpacking]
1388
+ return jvp_out, aux
1389
+ _, jvp_out = output # pyrefly: ignore[bad-unpacking]
1390
+ return jvp_out
1391
+
1392
+ results = vmap(push_jvp, randomness=randomness)(basis)
1393
+ aux: Any = None
1394
+ if has_aux:
1395
+ results, aux = results
1396
+ # aux is in the standard basis format, e.g. NxN matrix
1397
+ # We need to fetch the first element as original `func` output
1398
+ flat_aux, aux_spec = tree_flatten(aux)
1399
+ flat_aux = [value[0] for value in flat_aux]
1400
+ aux = tree_unflatten(flat_aux, aux_spec)
1401
+
1402
+ jac_outs, spec = tree_flatten(results)
1403
+ # Most probably below output check can never raise an error
1404
+ # as jvp should test the output before
1405
+ # assert_non_empty_output(jac_outs, 'jacfwd(f, ...)(*args)')
1406
+
1407
+ jac_outs_ins = tuple(
1408
+ tuple(
1409
+ safe_unflatten(jac_out_in, -1, primal.shape)
1410
+ for primal, jac_out_in in zip(
1411
+ flat_primals,
1412
+ torch.split(
1413
+ jac_out.movedim(0, -1), list(flat_primals_numels), dim=-1
1414
+ ),
1415
+ )
1416
+ )
1417
+ for jac_out in jac_outs
1418
+ )
1419
+ jac_outs_ins = tuple(
1420
+ tree_unflatten(jac_ins, primals_spec) for jac_ins in jac_outs_ins
1421
+ )
1422
+
1423
+ if isinstance(argnums, int):
1424
+ jac_outs_ins = tuple(jac_ins[0] for jac_ins in jac_outs_ins)
1425
+ if has_aux:
1426
+ return tree_unflatten(jac_outs_ins, spec), aux # type: ignore[possibly-unbound]
1427
+ return tree_unflatten(jac_outs_ins, spec)
1428
+
1429
+ return wrapper_fn
1430
+
1431
+
1432
+ @exposed_in("torch.func")
1433
+ def hessian(func: Callable[..., Any], argnums: argnums_t = 0) -> Callable[..., Any]:
1434
+ """
1435
+ Computes the Hessian of ``func`` with respect to the arg(s) at index
1436
+ ``argnum`` via a forward-over-reverse strategy.
1437
+
1438
+ The forward-over-reverse strategy (composing ``jacfwd(jacrev(func))``) is
1439
+ a good default for good performance. It is possible to compute Hessians
1440
+ through other compositions of :func:`jacfwd` and :func:`jacrev` like
1441
+ ``jacfwd(jacfwd(func))`` or ``jacrev(jacrev(func))``.
1442
+
1443
+ Args:
1444
+ func (function): A Python function that takes one or more arguments,
1445
+ one of which must be a Tensor, and returns one or more Tensors
1446
+ argnums (int or tuple[int, ...]): Optional, integer or tuple of integers,
1447
+ saying which arguments to get the Hessian with respect to.
1448
+ Default: 0.
1449
+
1450
+ Returns:
1451
+ Returns a function that takes in the same inputs as ``func`` and
1452
+ returns the Hessian of ``func`` with respect to the arg(s) at
1453
+ ``argnums``.
1454
+
1455
+ .. note::
1456
+ You may see this API error out with "forward-mode AD not implemented
1457
+ for operator X". If so, please file a bug report and we will prioritize it.
1458
+ An alternative is to use ``jacrev(jacrev(func))``, which has better
1459
+ operator coverage.
1460
+
1461
+ A basic usage with a R^N -> R^1 function gives a N x N Hessian:
1462
+
1463
+ >>> from torch.func import hessian
1464
+ >>> def f(x):
1465
+ >>> return x.sin().sum()
1466
+ >>>
1467
+ >>> x = torch.randn(5)
1468
+ >>> hess = hessian(f)(x) # equivalent to jacfwd(jacrev(f))(x)
1469
+ >>> assert torch.allclose(hess, torch.diag(-x.sin()))
1470
+
1471
+ """
1472
+ return jacfwd(jacrev(func, argnums), argnums)
1473
+
1474
+
1475
+ @doesnt_support_saved_tensors_hooks
1476
+ def grad_and_value_impl(
1477
+ func: Callable[..., Any],
1478
+ argnums: argnums_t,
1479
+ has_aux: bool,
1480
+ args: tuple[Any, ...],
1481
+ kwargs: dict[str, Any],
1482
+ ) -> tuple[Any, Any]:
1483
+ with grad_increment_nesting() as level:
1484
+ output, aux, grad_input = None, None, None
1485
+ # See NOTE [grad and vjp interaction with no_grad]
1486
+ with torch.enable_grad():
1487
+ args = _wrap_all_tensors(args, level)
1488
+ kwargs = _wrap_all_tensors(kwargs, level)
1489
+ diff_args = _slice_argnums(args, argnums, as_tuple=False)
1490
+ tree_map_(partial(_create_differentiable, level=level), diff_args)
1491
+
1492
+ output = func(*args, **kwargs)
1493
+ if has_aux:
1494
+ if not (isinstance(output, tuple) and len(output) == 2):
1495
+ raise RuntimeError(
1496
+ "grad_and_value(f)(*args): output of function f should be a tuple: (output, aux) "
1497
+ "if has_aux is True"
1498
+ )
1499
+ output, aux = output
1500
+
1501
+ if not isinstance(output, torch.Tensor):
1502
+ raise RuntimeError(
1503
+ "grad_and_value(f)(*args): Expected f(*args) "
1504
+ f"to return a Tensor, got {type(output)}"
1505
+ )
1506
+ if output.dim() != 0:
1507
+ raise RuntimeError(
1508
+ "grad_and_value(f)(*args): Expected f(*args) "
1509
+ "to return a scalar Tensor, got tensor with "
1510
+ f"{output.dim()} dims. Maybe you wanted to "
1511
+ "use the vjp or jacrev APIs instead?"
1512
+ )
1513
+
1514
+ flat_diff_args, spec = tree_flatten(diff_args)
1515
+
1516
+ # NB: need create_graph so that backward pass isn't run in no_grad mode
1517
+ flat_outputs = _as_tuple(output)
1518
+ flat_grad_input = _autograd_grad(
1519
+ flat_outputs, flat_diff_args, create_graph=True
1520
+ )
1521
+ grad_input = tree_unflatten(flat_grad_input, spec)
1522
+
1523
+ grad_input = _undo_create_differentiable(grad_input, level)
1524
+ output = _undo_create_differentiable(output, level)
1525
+ if has_aux:
1526
+ # pyrefly: ignore[bad-specialization]
1527
+ aux = _undo_create_differentiable(aux, level)
1528
+
1529
+ if has_aux:
1530
+ return grad_input, (output, aux)
1531
+ return grad_input, output
1532
+
1533
+
1534
+ def grad_impl(
1535
+ func: Callable[..., Any],
1536
+ argnums: argnums_t,
1537
+ has_aux: bool,
1538
+ args: tuple[Any, ...],
1539
+ kwargs: dict[str, Any],
1540
+ ) -> Any:
1541
+ results = grad_and_value_impl(func, argnums, has_aux, args, kwargs)
1542
+ if has_aux:
1543
+ grad, (_, aux) = results
1544
+ return grad, aux
1545
+ grad, _ = results
1546
+ return grad
1547
+
1548
+
1549
+ def _maybe_wrap_functional_tensor(
1550
+ maybe_tensor: Any, level: int, *, _python_functionalize: bool = False
1551
+ ) -> Any:
1552
+ if not isinstance(maybe_tensor, torch.Tensor):
1553
+ return maybe_tensor
1554
+ wrapped = _wrap_functional_tensor(maybe_tensor, level)
1555
+ _assert_wrapped_functional(maybe_tensor, wrapped)
1556
+ if _python_functionalize:
1557
+ # pyrefly: ignore[missing-argument]
1558
+ out = FunctionalTensor(wrapped)
1559
+ # pyrefly: ignore[missing-attribute]
1560
+ torch._mirror_autograd_meta_to(maybe_tensor, out)
1561
+ return out
1562
+ return wrapped
1563
+
1564
+
1565
+ def _wrap_all_tensors_to_functional(
1566
+ tensor_pytree: Any, level: int, *, _python_functionalize: bool = False
1567
+ ) -> Any:
1568
+ return tree_map(
1569
+ partial(
1570
+ lambda x: _maybe_wrap_functional_tensor(
1571
+ x, level, _python_functionalize=_python_functionalize
1572
+ )
1573
+ ),
1574
+ tensor_pytree,
1575
+ )
1576
+
1577
+
1578
+ def _maybe_unwrap_functional_tensor(maybe_tensor: Any, *, reapply_views: bool) -> Any:
1579
+ if not isinstance(maybe_tensor, torch.Tensor):
1580
+ return maybe_tensor
1581
+ if isinstance(maybe_tensor, FunctionalTensor):
1582
+ maybe_tensor = maybe_tensor.elem
1583
+
1584
+ if not torch._is_functional_tensor(maybe_tensor):
1585
+ # If it's not a functional tensor, just return it.
1586
+ # This can happen if we functionalize a fn that returns a global,
1587
+ # which was never wrapped properly.
1588
+ return maybe_tensor
1589
+ # Sync any pending updates on the output tensor
1590
+ torch._sync(maybe_tensor)
1591
+ return _unwrap_functional_tensor(maybe_tensor, reapply_views)
1592
+
1593
+
1594
+ def _unwrap_all_tensors_from_functional(
1595
+ tensor_pytree: Any, *, reapply_views: bool
1596
+ ) -> Any:
1597
+ return tree_map(
1598
+ lambda t: _maybe_unwrap_functional_tensor(t, reapply_views=reapply_views),
1599
+ tensor_pytree,
1600
+ )
1601
+
1602
+
1603
+ @exposed_in("torch.func")
1604
+ def functionalize(
1605
+ func: Callable[..., Any], *, remove: str = "mutations"
1606
+ ) -> Callable[..., Any]:
1607
+ """
1608
+ functionalize is a transform that can be used to remove (intermediate)
1609
+ mutations and aliasing from a function, while preserving the function's
1610
+ semantics.
1611
+
1612
+ ``functionalize(func)`` returns a new function with the same semantics
1613
+ as ``func``, but with all intermediate mutations removed.
1614
+ Every inplace operation performed on an intermediate tensor:
1615
+ ``intermediate.foo_()``
1616
+ gets replaced by its out-of-place equivalent:
1617
+ ``intermediate_updated = intermediate.foo()``.
1618
+
1619
+ functionalize is useful for shipping a pytorch program off to
1620
+ backends or compilers that aren't able to easily represent
1621
+ mutations or aliasing operators.
1622
+
1623
+ Args:
1624
+ func (Callable[..., Any]): A Python function that takes one or more arguments.
1625
+ remove (str): An optional string argument, that takes on either
1626
+ the value 'mutations' or 'mutations_and_views'.
1627
+ If 'mutations' is passed in then all mutating operators
1628
+ will be replaced with their non-mutating equivalents.
1629
+ If 'mutations_and_views' is passed in, then additionally, all aliasing
1630
+ operators will be replaced with their non-aliasing equivalents.
1631
+ Default: 'mutations'.
1632
+
1633
+ Returns:
1634
+ Returns a new "functionalized" function. It takes the same inputs as
1635
+ ``func``, and has the same behavior, but any mutations
1636
+ (and optionally aliasing) performed on intermediate tensors
1637
+ in the function will be removed.
1638
+
1639
+ functionalize will also remove mutations (and views) that were performed on function inputs.
1640
+ However to preserve semantics, functionalize will "fix up" the mutations after
1641
+ the transform has finished running, by detecting if any tensor inputs "should have"
1642
+ been mutated, and copying the new data back to the inputs if necessary.
1643
+
1644
+
1645
+ Example::
1646
+
1647
+ >>> # xdoctest: +SKIP
1648
+ >>> import torch
1649
+ >>> from torch.fx.experimental.proxy_tensor import make_fx
1650
+ >>> from torch.func import functionalize
1651
+ >>>
1652
+ >>> # A function that uses mutations and views, but only on intermediate tensors.
1653
+ >>> def f(a):
1654
+ ... b = a + 1
1655
+ ... c = b.view(-1)
1656
+ ... c.add_(1)
1657
+ ... return b
1658
+ ...
1659
+ >>> inpt = torch.randn(2)
1660
+ >>>
1661
+ >>> out1 = f(inpt)
1662
+ >>> out2 = functionalize(f)(inpt)
1663
+ >>>
1664
+ >>> # semantics are the same (outputs are equivalent)
1665
+ >>> print(torch.allclose(out1, out2))
1666
+ True
1667
+ >>>
1668
+ >>> f_traced = make_fx(f)(inpt)
1669
+ >>> f_no_mutations_traced = make_fx(functionalize(f))(inpt)
1670
+ >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt)
1671
+ >>>
1672
+ >>> print(f_traced.code)
1673
+
1674
+
1675
+
1676
+ def forward(self, a_1):
1677
+ add = torch.ops.aten.add(a_1, 1); a_1 = None
1678
+ view = torch.ops.aten.view(add, [-1])
1679
+ add_ = torch.ops.aten.add_(view, 1); view = None
1680
+ return add
1681
+
1682
+ >>> print(f_no_mutations_traced.code)
1683
+
1684
+
1685
+
1686
+ def forward(self, a_1):
1687
+ add = torch.ops.aten.add(a_1, 1); a_1 = None
1688
+ view = torch.ops.aten.view(add, [-1]); add = None
1689
+ add_1 = torch.ops.aten.add(view, 1); view = None
1690
+ view_1 = torch.ops.aten.view(add_1, [2]); add_1 = None
1691
+ return view_1
1692
+
1693
+ >>> print(f_no_mutations_and_views_traced.code)
1694
+
1695
+
1696
+
1697
+ def forward(self, a_1):
1698
+ add = torch.ops.aten.add(a_1, 1); a_1 = None
1699
+ view_copy = torch.ops.aten.view_copy(add, [-1]); add = None
1700
+ add_1 = torch.ops.aten.add(view_copy, 1); view_copy = None
1701
+ view_copy_1 = torch.ops.aten.view_copy(add_1, [2]); add_1 = None
1702
+ return view_copy_1
1703
+
1704
+
1705
+ >>> # A function that mutates its input tensor
1706
+ >>> def f(a):
1707
+ ... b = a.view(-1)
1708
+ ... b.add_(1)
1709
+ ... return a
1710
+ ...
1711
+ >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt)
1712
+ >>> #
1713
+ >>> # All mutations and views have been removed,
1714
+ >>> # but there is an extra copy_ in the graph to correctly apply the mutation to the input
1715
+ >>> # after the function has completed.
1716
+ >>> print(f_no_mutations_and_views_traced.code)
1717
+
1718
+
1719
+
1720
+ def forward(self, a_1):
1721
+ view_copy = torch.ops.aten.view_copy(a_1, [-1])
1722
+ add = torch.ops.aten.add(view_copy, 1); view_copy = None
1723
+ view_copy_1 = torch.ops.aten.view_copy(add, [2]); add = None
1724
+ copy_ = torch.ops.aten.copy_(a_1, view_copy_1); a_1 = None
1725
+ return view_copy_1
1726
+
1727
+
1728
+ There are a few "failure modes" for functionalize that are worth calling out:
1729
+ (1) Like other torch.func transforms, `functionalize()` doesn't work with functions
1730
+ that directly use `.backward()`. The same is true for torch.autograd.grad.
1731
+ If you want to use autograd, you can compute gradients directly
1732
+ with `functionalize(grad(f))`.
1733
+ (2) Like other torch.func transforms, `functionalize()` doesn't work with global state.
1734
+ If you call `functionalize(f)` on a function that takes views / mutations of
1735
+ non-local state, functionalization will simply no-op and pass the view/mutation
1736
+ calls directly to the backend.
1737
+ One way to work around this is to ensure that any non-local state creation
1738
+ is wrapped into a larger function, which you then call functionalize on.
1739
+ (3) `resize_()` has some limitations: functionalize will only work on programs
1740
+ that use resize_()` as long as the tensor being resized is not a view.
1741
+ (4) `as_strided()` has some limitations: functionalize will not work on
1742
+ `as_strided()` calls that result in tensors with overlapping memory.
1743
+
1744
+
1745
+ Finally, a helpful mental model for understanding functionalization is that
1746
+ most user pytorch programs are writing with the public torch API.
1747
+ When executed, torch operators are generally decomposed into
1748
+ our internal C++ "ATen" API.
1749
+ The logic for functionalization happens entirely at the level of ATen.
1750
+ Functionalization knows how to take every aliasing operator in ATen,
1751
+ and map it to its non-aliasing equivalent
1752
+ (e.g. ``tensor.view({-1})`` -> ``at::view_copy(tensor, {-1})``),
1753
+ and how to take every mutating operator in ATen,
1754
+ and map it to its non-mutating equivalent
1755
+ (e.g. ``tensor.add_(1)`` -> ``at::add(tensor, -1)``),
1756
+ while tracking aliases and mutations out-of-line to know when to fix things up.
1757
+ Information about which ATen operators are aliasing or mutating all comes from
1758
+ https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml.
1759
+ """
1760
+ if remove == "mutations":
1761
+ reapply_views = True
1762
+ elif remove == "mutations_and_views":
1763
+ reapply_views = False
1764
+ else:
1765
+ raise RuntimeError(
1766
+ f"functionalize(f, remove='mutations'): received invalid argument for remove={remove}."
1767
+ " Valid options are:\n"
1768
+ " remove='mutations': all inplace and out= operators will be removed from the program, and replaced"
1769
+ " with their out-of-place equivalents.\n"
1770
+ " remove='mutations_and_views': In addition to the above, all aliasing operators {view} will be"
1771
+ " replaced with their non-aliasing counterparts, {view}_copy.\n"
1772
+ )
1773
+
1774
+ @_wraps_without_dynamo_attrs(func)
1775
+ def wrapped(*args: Any, **kwargs: Any) -> Any:
1776
+ try:
1777
+ func_level = _func_increment_nesting(reapply_views)
1778
+ func_args = _wrap_all_tensors_to_functional(args, func_level)
1779
+ func_kwargs = _wrap_all_tensors_to_functional(kwargs, func_level)
1780
+
1781
+ flattened_unwrapped_args = pytree.arg_tree_leaves(*args)
1782
+ flattened_wrapped_args = pytree.arg_tree_leaves(*func_args)
1783
+ flattened_unwrapped_kwargs = pytree.arg_tree_leaves(**kwargs)
1784
+ flattened_wrapped_kwargs = pytree.arg_tree_leaves(**func_kwargs)
1785
+
1786
+ func_outputs = func(*func_args, **func_kwargs)
1787
+ outputs = _unwrap_all_tensors_from_functional(
1788
+ func_outputs, reapply_views=reapply_views
1789
+ )
1790
+
1791
+ for a in flattened_wrapped_args + flattened_wrapped_kwargs:
1792
+ if isinstance(a, torch.Tensor):
1793
+ # Call sync_() on the inputs, to ensure that any pending mutations have been applied.
1794
+ torch._sync(a)
1795
+
1796
+ # And if any mutations were applied to the inputs, we need to propagate them back to the user.
1797
+ for unwrapped, wrapped in zip(
1798
+ flattened_unwrapped_args, flattened_wrapped_args
1799
+ ):
1800
+ if isinstance(unwrapped, torch.Tensor) and isinstance(
1801
+ wrapped, torch.Tensor
1802
+ ):
1803
+ _propagate_functional_input_mutation(unwrapped, wrapped)
1804
+ for unwrapped, wrapped in zip(
1805
+ flattened_unwrapped_kwargs, flattened_wrapped_kwargs
1806
+ ):
1807
+ if isinstance(unwrapped, torch.Tensor) and isinstance(
1808
+ wrapped, torch.Tensor
1809
+ ):
1810
+ _propagate_functional_input_mutation(unwrapped, wrapped)
1811
+
1812
+ return outputs
1813
+ finally:
1814
+ _func_decrement_nesting()
1815
+
1816
+ return wrapped
1817
+
1818
+
1819
+ @exposed_in("torch.func")
1820
+ def linearize(
1821
+ func: Callable[..., Any], *primals: Any
1822
+ ) -> tuple[Any, Callable[..., Any]]:
1823
+ """
1824
+ Returns the value of ``func`` at ``primals`` and linear approximation
1825
+ at ``primals``.
1826
+
1827
+ Args:
1828
+ func (Callable[..., Any]): A Python function that takes one or more arguments.
1829
+ primals (Tensors): Positional arguments to ``func`` that must all be
1830
+ Tensors. These are the values at which the function is linearly approximated.
1831
+
1832
+ Returns:
1833
+ Returns a ``(output, jvp_fn)`` tuple containing the output of ``func``
1834
+ applied to ``primals`` and a function that computes the jvp of
1835
+ ``func`` evaluated at ``primals``.
1836
+
1837
+ linearize is useful if jvp is to be computed multiple times at ``primals``. However,
1838
+ to achieve this, linearize saves intermediate computation and has higher memory requirements
1839
+ than directly applying `jvp`. So, if all the ``tangents`` are known, it maybe more efficient
1840
+ to compute vmap(jvp) instead of using linearize.
1841
+
1842
+ .. note::
1843
+ linearize evaluates ``func`` twice. Please file an issue for an implementation
1844
+ with a single evaluation.
1845
+
1846
+ Example::
1847
+
1848
+ >>> import torch
1849
+ >>> from torch.func import linearize
1850
+ >>> def fn(x):
1851
+ ... return x.sin()
1852
+ ...
1853
+ >>> warnings.filterwarnings("ignore", message=".*Attempted to insert a get_attr Node with no underlying reference") # docs: hide
1854
+ >>> output, jvp_fn = linearize(fn, torch.zeros(3, 3))
1855
+ >>> jvp_fn(torch.ones(3, 3))
1856
+ tensor([[1., 1., 1.],
1857
+ [1., 1., 1.],
1858
+ [1., 1., 1.]])
1859
+ >>>
1860
+
1861
+ """
1862
+ # Note: We evaluate `fn` twice.
1863
+ # Once for returning the output and other while
1864
+ # tracing the graph.
1865
+ # If this becomes a bottle-neck, we should update
1866
+ # make_fx such that it also returns the output.
1867
+
1868
+ output = func(*primals)
1869
+ _, output_spec = tree_flatten(output)
1870
+
1871
+ flat_primals, primals_argspec = tree_flatten(primals)
1872
+
1873
+ # tangents for tracing
1874
+ flat_tangents = tuple(p.new_empty(()).expand_as(p) for p in flat_primals)
1875
+
1876
+ # function to trace
1877
+ def trace_fn(flat_tangents: tuple[torch.Tensor, ...]) -> Any:
1878
+ with fwAD.dual_level():
1879
+ flat_duals = tuple(
1880
+ fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents)
1881
+ )
1882
+ duals = tree_unflatten(flat_duals, primals_argspec)
1883
+ output = func(*duals)
1884
+ tangents = tree_map_only(
1885
+ torch.Tensor, lambda dual: safe_unpack_dual(dual, False)[1], output
1886
+ )
1887
+
1888
+ return tangents
1889
+
1890
+ jvp_graph = lazy_dynamo_disallow(make_fx)(trace_fn)(flat_tangents)
1891
+ const_folded_jvp_graph = lazy_dynamo_disallow(const_fold.split_const_subgraphs)(
1892
+ jvp_graph
1893
+ )
1894
+
1895
+ # Hold only the meta-data regarding the primals.
1896
+ flat_primals_shape = tuple(p.shape for p in flat_primals)
1897
+ flat_primals_device = tuple(p.device for p in flat_primals)
1898
+ flat_primals_dtype = tuple(p.dtype for p in flat_primals)
1899
+
1900
+ def forward_ad_checks(flat_tangents: Sequence[torch.Tensor]) -> None:
1901
+ for idx, t in enumerate(flat_tangents):
1902
+ if t.shape != flat_primals_shape[idx]:
1903
+ msg = (
1904
+ f"tangent:{idx} with shape {t.shape} in flattened "
1905
+ f"pytree doesn't match the shape {flat_primals_shape[idx]} "
1906
+ "of the corresponding primal."
1907
+ )
1908
+ raise RuntimeError(msg)
1909
+
1910
+ if t.device != flat_primals_device[idx]:
1911
+ msg = (
1912
+ f"tangent:{idx} with device {t.device} in flattened "
1913
+ f"pytree doesn't match the device {flat_primals_device[idx]} "
1914
+ "of the corresponding primal."
1915
+ )
1916
+ raise RuntimeError(msg)
1917
+
1918
+ if t.dtype != flat_primals_dtype[idx]:
1919
+ msg = (
1920
+ f"tangent:{idx} with dtype {t.dtype} in flattened "
1921
+ f"pytree doesn't match the dtype {flat_primals_dtype[idx]} "
1922
+ "of the corresponding primal."
1923
+ )
1924
+ raise RuntimeError(msg)
1925
+
1926
+ # jvp_fn : Callable[..., Any] to return
1927
+ # It takes care of checking the argspec of tangents,
1928
+ # calling the folded fx graph and unflattening fx graph output
1929
+ def jvp_fn(*tangents: Any) -> Any:
1930
+ flat_tangents, tangent_argspec = tree_flatten(tangents)
1931
+ if tangent_argspec != primals_argspec:
1932
+ raise RuntimeError(
1933
+ f"Expected the tangents {tangent_argspec} to have "
1934
+ f"the same argspec as the primals {primals_argspec}"
1935
+ )
1936
+
1937
+ forward_ad_checks(flat_tangents) # type: ignore[arg-type]
1938
+
1939
+ flat_output = const_folded_jvp_graph(*flat_tangents)
1940
+ # const folded graph can return flat output,
1941
+ # so transform output.
1942
+ return tree_unflatten(flat_output, output_spec)
1943
+
1944
+ return output, jvp_fn
1945
+
1946
+
1947
+ @exposed_in("torch.func")
1948
+ def debug_unwrap(tensor: torch.Tensor, *, recurse: bool = True) -> torch.Tensor:
1949
+ """Unwraps a functorch tensor (e.g. BatchedTensor, GradTrackingTensor) to its underlying tensor.
1950
+
1951
+ This function should only be used in a debug setting (e.g. trying to print the
1952
+ value of a Tensor in a debugger). Otherwise, using the result of function
1953
+ inside of a function being transformed will lead to undefined behavior.
1954
+ """
1955
+ if not is_functorch_wrapped_tensor(tensor):
1956
+ return tensor
1957
+ result = get_unwrapped(tensor)
1958
+ if recurse:
1959
+ return debug_unwrap(result)
1960
+ return result
.venv/lib/python3.12/site-packages/torch/_functorch/einops.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ from torch._functorch.utils import exposed_in
5
+
6
+
7
+ __all__ = ["rearrange"]
8
+
9
+
10
+ @exposed_in("torch.func")
11
+ def rearrange(
12
+ tensor: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...],
13
+ pattern: str,
14
+ **axes_lengths: int,
15
+ ) -> torch.Tensor:
16
+ r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional
17
+ tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze,
18
+ stack, concatenate and other operations.
19
+
20
+ See: https://einops.rocks/api/rearrange/
21
+
22
+ Args:
23
+ tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange
24
+ pattern (str): the rearrangement pattern
25
+ axes_lengths (int): any additional length specifications for dimensions
26
+
27
+ Returns:
28
+ Tensor: the rearranged tensor
29
+
30
+ Examples:
31
+ >>> from torch.func import rearrange
32
+ >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel)
33
+ >>> images = torch.randn((32, 30, 40, 3))
34
+
35
+ >>> # stack along first (batch) axis, output is a single array
36
+ >>> rearrange(images, "b h w c -> b h w c").shape
37
+ torch.Size([32, 30, 40, 3])
38
+
39
+ >>> # concatenate images along height (vertical axis), 960 = 32 * 30
40
+ >>> rearrange(images, "b h w c -> (b h) w c").shape
41
+ torch.Size([960, 40, 3])
42
+
43
+ >>> # concatenated images along horizontal axis, 1280 = 32 * 40
44
+ >>> rearrange(images, "b h w c -> h (b w) c").shape
45
+ torch.Size([30, 1280, 3])
46
+
47
+ >>> # reordered axes to "b c h w" format for deep learning
48
+ >>> rearrange(images, "b h w c -> b c h w").shape
49
+ torch.Size([32, 3, 30, 40])
50
+
51
+ >>> # flattened each image into a vector, 3600 = 30 * 40 * 3
52
+ >>> rearrange(images, "b h w c -> b (c h w)").shape
53
+ torch.Size([32, 3600])
54
+
55
+ >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
56
+ >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape
57
+ torch.Size([128, 15, 20, 3])
58
+
59
+ >>> # space-to-depth operation
60
+ >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape
61
+ torch.Size([32, 15, 20, 12])
62
+ """
63
+ if not isinstance(tensor, torch.Tensor):
64
+ tensor = torch.stack(tensor)
65
+
66
+ # Lazy import to avoid circular import:
67
+ # torch._functorch.einops -> functorch.einops (package __init__) -> torch._functorch.einops
68
+ from functorch.einops.rearrange import _create_rearrange_callable
69
+
70
+ rearrange_callable = _create_rearrange_callable(
71
+ tensor.ndim, pattern, **axes_lengths
72
+ )
73
+
74
+ return rearrange_callable(tensor)
.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch import Tensor
9
+ from torch._functorch.utils import exposed_in
10
+
11
+
12
+ @exposed_in("torch.func")
13
+ def functional_call(
14
+ module: torch.nn.Module,
15
+ parameter_and_buffer_dicts: dict[str, Tensor] | Sequence[dict[str, Tensor]],
16
+ args: Any = None,
17
+ kwargs: dict[str, Any] | None = None,
18
+ *,
19
+ tie_weights: bool = True,
20
+ strict: bool = False,
21
+ ) -> Any:
22
+ r"""Performs a functional call on the module by replacing the module parameters
23
+ and buffers with the provided ones.
24
+
25
+ .. note:: If the module has active parametrizations, passing a value in the
26
+ :attr:`parameter_and_buffer_dicts` argument with the name set to the regular parameter
27
+ name will completely disable the parametrization.
28
+ If you want to apply the parametrization function to the value passed
29
+ please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``.
30
+
31
+ .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected
32
+ in the ``parameter_and_buffer_dicts`` input.
33
+
34
+
35
+ Example::
36
+
37
+ >>> a = {'foo': torch.zeros(())}
38
+ >>> # xdoctest: +SKIP
39
+ >>> mod = Foo() # does self.foo = self.foo + 1
40
+ >>> print(mod.foo) # tensor(0.)
41
+ >>> functional_call(mod, a, torch.ones(()))
42
+ >>> print(mod.foo) # tensor(0.)
43
+ >>> print(a['foo']) # tensor(1.)
44
+
45
+ .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the
46
+ tie_weights flag.
47
+
48
+ Example::
49
+
50
+ >>> a = {'foo': torch.zeros(())}
51
+ >>> # xdoctest: +SKIP
52
+ >>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied
53
+ >>> print(mod.foo) # tensor(1.)
54
+ >>> mod(torch.zeros(())) # tensor(2.)
55
+ >>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too
56
+ >>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated
57
+ >>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())}
58
+ >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.)
59
+
60
+ An example of passing multiple dictionaries
61
+
62
+ .. code-block:: python
63
+
64
+ a = (
65
+ {"weight": torch.ones(1, 1)},
66
+ {"buffer": torch.zeros(1)},
67
+ ) # two separate dictionaries
68
+ mod = nn.Bar(1, 1) # return self.weight @ x + self.buffer
69
+ print(mod.weight) # tensor(...)
70
+ print(mod.buffer) # tensor(...)
71
+ x = torch.randn((1, 1))
72
+ print(x)
73
+ functional_call(mod, a, x) # same as x
74
+ print(mod.weight) # same as before functional_call
75
+
76
+
77
+ And here is an example of applying the grad transform over the parameters
78
+ of a model.
79
+
80
+ .. code-block:: python
81
+
82
+ import torch
83
+ import torch.nn as nn
84
+ from torch.func import functional_call, grad
85
+
86
+ x = torch.randn(4, 3)
87
+ t = torch.randn(4, 3)
88
+ model = nn.Linear(3, 3)
89
+
90
+
91
+ def compute_loss(params, x, t):
92
+ y = functional_call(model, params, x)
93
+ return nn.functional.mse_loss(y, t)
94
+
95
+
96
+ grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t)
97
+
98
+ .. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the
99
+ parameters for better performance and memory usage
100
+
101
+ Example::
102
+
103
+ >>> detached_params = {k: v.detach() for k, v in model.named_parameters()}
104
+ >>> grad_weights = grad(compute_loss)(detached_params, x, t)
105
+ >>> grad_weights.grad_fn # None--it's not tracking gradients outside of grad
106
+
107
+ This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking
108
+ outside of the transforms, this will result in less memory usage and faster speeds.
109
+
110
+ Args:
111
+ module (torch.nn.Module): the module to call
112
+ parameters_and_buffer_dicts (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in
113
+ the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can
114
+ be used together
115
+ args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument.
116
+ kwargs (dict): keyword arguments to be passed to the module call
117
+ tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as
118
+ tied in the reparameterized version. Therefore, if True and different values are passed for the tied
119
+ parameters and buffers, it will error. If False, it will not respect the originally tied parameters and
120
+ buffers unless the values passed for both weights are the same. Default: True.
121
+ strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and
122
+ buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will
123
+ error. Default: False.
124
+
125
+ Returns:
126
+ Any: the result of calling ``module``.
127
+ """
128
+ if isinstance(parameter_and_buffer_dicts, dict):
129
+ parameters_and_buffers = parameter_and_buffer_dicts
130
+ elif isinstance(parameter_and_buffer_dicts, Sequence):
131
+ if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts):
132
+ raise ValueError(
133
+ "Expected all elements of parameter_and_buffer_dicts to be dictionaries"
134
+ )
135
+ all_keys = [k for d in parameter_and_buffer_dicts for k in d]
136
+ all_keys_counter: dict[str, int] = {}
137
+ for k in all_keys:
138
+ v = all_keys_counter.get(k, 0)
139
+ all_keys_counter[k] = v + 1
140
+ repeated_keys = [key for key, n in all_keys_counter.items() if n > 1]
141
+ if len(repeated_keys) > 0:
142
+ raise ValueError(
143
+ f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous"
144
+ )
145
+ parameters_and_buffers = {
146
+ k: v for d in parameter_and_buffer_dicts for k, v in d.items()
147
+ }
148
+ else:
149
+ raise ValueError(
150
+ f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, "
151
+ f"but got {type(parameter_and_buffer_dicts)}"
152
+ )
153
+
154
+ return nn.utils.stateless._functional_call(
155
+ module,
156
+ parameters_and_buffers,
157
+ args,
158
+ kwargs,
159
+ tie_weights=tie_weights,
160
+ strict=strict,
161
+ )
162
+
163
+
164
+ @exposed_in("torch.func")
165
+ def stack_module_state(
166
+ models: Sequence[nn.Module] | nn.ModuleList,
167
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
168
+ """stack_module_state(models) -> params, buffers
169
+
170
+ Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
171
+
172
+ Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries
173
+ that stack all of their parameters and buffers together, indexed by name.
174
+ The stacked parameters are optimizable (i.e. they are new leaf nodes in the
175
+ autograd history that are unrelated to the original parameters and can be
176
+ passed directly to an optimizer).
177
+
178
+ Here's an example of how to ensemble over a very simple model:
179
+
180
+ .. code-block:: python
181
+
182
+ num_models = 5
183
+ batch_size = 64
184
+ in_features, out_features = 3, 3
185
+ models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
186
+ data = torch.randn(batch_size, 3)
187
+
188
+
189
+ def wrapper(params, buffers, data):
190
+ return torch.func.functional_call(models[0], (params, buffers), data)
191
+
192
+
193
+ params, buffers = stack_module_state(models)
194
+ output = vmap(wrapper, (0, 0, None))(params, buffers, data)
195
+
196
+ assert output.shape == (num_models, batch_size, out_features)
197
+
198
+ When there's submodules, this follows state dict naming conventions
199
+
200
+ .. code-block:: python
201
+
202
+ import torch.nn as nn
203
+
204
+
205
+ class Foo(nn.Module):
206
+ def __init__(self, in_features, out_features):
207
+ super().__init__()
208
+ hidden = 4
209
+ self.l1 = nn.Linear(in_features, hidden)
210
+ self.l2 = nn.Linear(hidden, out_features)
211
+
212
+ def forward(self, x):
213
+ return self.l2(self.l1(x))
214
+
215
+
216
+ num_models = 5
217
+ in_features, out_features = 3, 3
218
+ models = [Foo(in_features, out_features) for i in range(num_models)]
219
+ params, buffers = stack_module_state(models)
220
+ print(list(params.keys())) # "l1.weight", "l1.bias", "l2.weight", "l2.bias"
221
+
222
+ .. warning::
223
+ All of the modules being stacked together must be the same (except for
224
+ the values of their parameters/buffers). For example, they should be in the
225
+ same mode (training vs eval).
226
+ """
227
+ if len(models) == 0:
228
+ raise RuntimeError("stack_module_state: Expected at least one model, got 0.")
229
+ if not (all(m.training for m in models) or all(not m.training for m in models)):
230
+ raise RuntimeError(
231
+ "stack_module_state: Expected all models to have the same training/eval mode."
232
+ )
233
+ model0_typ = type(models[0])
234
+ if not all(type(m) is model0_typ for m in models):
235
+ raise RuntimeError(
236
+ "stack_module_state: Expected all models to be of the same class."
237
+ )
238
+ all_params = [dict(model.named_parameters()) for model in models]
239
+ params = {
240
+ k: construct_stacked_leaf(tuple(params[k] for params in all_params), k)
241
+ for k in all_params[0]
242
+ }
243
+ all_buffers = [dict(model.named_buffers()) for model in models]
244
+ buffers = {
245
+ k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k)
246
+ for k in all_buffers[0]
247
+ }
248
+
249
+ return params, buffers
250
+
251
+
252
+ def construct_stacked_leaf(
253
+ tensors: tuple[Tensor, ...] | list[Tensor], name: str
254
+ ) -> Tensor:
255
+ all_requires_grad = all(t.requires_grad for t in tensors)
256
+ none_requires_grad = all(not t.requires_grad for t in tensors)
257
+ if not all_requires_grad and not none_requires_grad:
258
+ raise RuntimeError(
259
+ f"Expected {name} from each model to have the same .requires_grad"
260
+ )
261
+ result = torch.stack(tensors)
262
+ if all_requires_grad:
263
+ result = result.detach().requires_grad_()
264
+ return result
.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import math
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from functools import partial, wraps
9
+ from typing import Any, TYPE_CHECKING
10
+
11
+ import torch
12
+ import torch.fx as fx
13
+ from torch.hub import tqdm
14
+ from torch.multiprocessing.reductions import StorageWeakRef
15
+ from torch.utils._content_store import ContentStoreWriter
16
+
17
+ from .compile_utils import get_outputs, get_placeholders
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import Callable, Sequence
22
+
23
+
24
+ is_tuple = object()
25
+
26
+
27
+ @dataclass
28
+ class LoadTensorMeta:
29
+ size: tuple[int, ...]
30
+ stride: tuple[int, ...]
31
+ dtype: torch.dtype
32
+ device: torch.device
33
+
34
+
35
+ class ConcreteProp(torch.fx.Interpreter):
36
+ def __init__(
37
+ self,
38
+ mod: fx.GraphModule,
39
+ *,
40
+ writer: ContentStoreWriter | None = None,
41
+ skip_offload: bool = False,
42
+ ) -> None:
43
+ super().__init__(mod)
44
+ self.writer = writer
45
+ self.skip_offload = skip_offload
46
+ self.seen_storages: set[StorageWeakRef] = set()
47
+ self.pbar: Any = None
48
+
49
+ def run_node(self, n: fx.Node) -> Any:
50
+ self.pbar.update(1)
51
+ r = super().run_node(n)
52
+ name = n.name
53
+
54
+ if isinstance(r, torch.Tensor):
55
+ if self.writer is None:
56
+ n.meta["concrete_value"] = r
57
+ else:
58
+ if StorageWeakRef(r.untyped_storage()) in self.seen_storages:
59
+ # Refuse to offload tensors which alias other live
60
+ # tensors, because this will violate operator contracts
61
+ n.meta["concrete_value"] = None
62
+ else:
63
+ if not self.skip_offload:
64
+ self.writer.write_tensor(os.path.join("eager", name), r)
65
+ n.meta["concrete_value"] = LoadTensorMeta(
66
+ r.size(), r.stride(), r.dtype, r.device
67
+ )
68
+ self.seen_storages.add(StorageWeakRef(r.untyped_storage()))
69
+ else:
70
+ n.meta["concrete_value"] = is_tuple
71
+
72
+ return r
73
+
74
+ def propagate(self, *args: Any) -> Any:
75
+ mod = self.module
76
+ if not isinstance(mod, fx.GraphModule):
77
+ raise AssertionError(f"expected fx.GraphModule, got {type(mod)}")
78
+ with tqdm(
79
+ desc="Saving intermediates for delta debugging",
80
+ total=len(mod.graph.nodes),
81
+ disable=self.writer is None,
82
+ ) as pbar:
83
+ self.pbar = pbar
84
+ r = super().run(*args)
85
+ if not self.skip_offload:
86
+ pbar.set_description(
87
+ "Saved! To skip next time, run with --skip-saving-eager-intermediates"
88
+ )
89
+ return r
90
+
91
+
92
+ def is_load_tensor_node(node: fx.Node) -> bool:
93
+ return (
94
+ node.op == "call_function"
95
+ and node.target is torch.ops.debugprims.load_tensor.default
96
+ )
97
+
98
+
99
+ # inplace modifies node/inps
100
+ def _convert_node_to_placeholder(
101
+ graph: fx.Graph, node: fx.Node, inps: list[torch.Tensor]
102
+ ) -> bool:
103
+ if node.op == "output" or node.op == "placeholder":
104
+ return False
105
+
106
+ if is_load_tensor_node(node):
107
+ return False
108
+
109
+ concrete_val = node.meta.get("concrete_value", None)
110
+
111
+ if isinstance(concrete_val, torch.Tensor):
112
+ node.op = "placeholder"
113
+ node.target = node.name
114
+ node.args = ()
115
+ node.kwargs = {}
116
+
117
+ inps.append(concrete_val)
118
+ return True
119
+
120
+ elif concrete_val is None:
121
+ return False
122
+
123
+ elif concrete_val is is_tuple:
124
+ r = False
125
+ for tuple_user in list(node.users):
126
+ r = _convert_node_to_placeholder(graph, tuple_user, inps) or r
127
+ # NB: We must not erase the node at this point, because
128
+ # we are iterating over the nodes and this would change
129
+ # the iteration order
130
+ # graph.erase_node(node)
131
+ return r
132
+
133
+ elif isinstance(concrete_val, LoadTensorMeta):
134
+ node.op = "call_function"
135
+ node.target = torch.ops.debugprims.load_tensor.default
136
+ node.args = (
137
+ os.path.join("eager", node.name),
138
+ concrete_val.size,
139
+ concrete_val.stride,
140
+ )
141
+ node.kwargs = {
142
+ "device": concrete_val.device,
143
+ "dtype": concrete_val.dtype,
144
+ }
145
+ return True
146
+
147
+ return False
148
+
149
+
150
+ def create_minified_hlo_graph(
151
+ minified_fx_graph: fx.GraphModule, inputs: Sequence[torch.Tensor]
152
+ ) -> None:
153
+ """
154
+ Takes minified FX graph as primary input, and ports it to HLO via StableHLO
155
+ Provides minified HLO graph as output, and archive them to local directory
156
+ """
157
+ hlo_dir = f"{os.getcwd()}/hlo_files"
158
+ os.makedirs(hlo_dir, exist_ok=True)
159
+
160
+ from torch_xla.stablehlo import save_torch_model_as_stablehlo
161
+
162
+ save_torch_model_as_stablehlo(minified_fx_graph, inputs, hlo_dir)
163
+
164
+
165
+ def dump_state(fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]) -> None:
166
+ print(
167
+ f"""
168
+ # Working Repro with {len(fx_g.graph.nodes)} nodes
169
+ inps = {[(i.shape, i.dtype, str(i.device)) for i in inps]}
170
+ inps = [torch.zeros(())] + [torch.ones(shape, dtype=dtype, device=device) for (shape, dtype, device) in inps]
171
+ {fx_g.code}
172
+ """
173
+ )
174
+
175
+
176
+ def is_power_of_two(n: int) -> bool:
177
+ if n == 0:
178
+ return False
179
+ return (n & (n - 1)) == 0
180
+
181
+
182
+ @dataclass
183
+ class ReproState:
184
+ graph: fx.Graph
185
+ inps: Sequence[torch.Tensor]
186
+
187
+ def __post_init__(self) -> None:
188
+ ph_nodes = get_placeholders(self.graph)
189
+ if len(ph_nodes) != len(self.inps):
190
+ raise AssertionError(
191
+ f"len(ph_nodes)={len(ph_nodes)} != len(self.inps)={len(self.inps)}"
192
+ )
193
+
194
+
195
+ def minifier(
196
+ fail_f: fx.GraphModule,
197
+ inps: Sequence[torch.Tensor],
198
+ module_fails: Callable[[fx.GraphModule, Sequence[torch.Tensor]], bool],
199
+ dump_state: Callable[[fx.GraphModule, Sequence[torch.Tensor]], None] = dump_state,
200
+ *,
201
+ save_dir: str | None = None,
202
+ offload_to_disk: bool = False,
203
+ skip_offload: bool = False,
204
+ skip_sanity: bool = False,
205
+ max_granularity: int | None = None,
206
+ ) -> tuple[fx.GraphModule, Sequence[torch.Tensor]]:
207
+ """
208
+ Minimizes a FX graph with given inputs, such that the resulting FX graph still returns True for module_fails.
209
+
210
+ Does 2 main strategies:
211
+ 1. Truncates suffix: Removes some suffix from the graph and sets a new output.
212
+ 2. Delta Debugging: Tries replacing half of the graph with inputs. If fails,
213
+ tries replacing quarter of the graph, etc.
214
+
215
+ >>> # xdoctest: +SKIP(failing)
216
+ >>> failing_function = fx.symbolic_trace(f)
217
+ >>> minimize(failing_function, [torch.randn(5)], lambda fx_g, inps: fx_g(*inps))
218
+
219
+ note: module_fails returns True if it fails.
220
+ """
221
+
222
+ failing_graph = fail_f.graph
223
+ cur_size = len(failing_graph.nodes)
224
+
225
+ if max_granularity is not None and not is_power_of_two(max_granularity):
226
+ raise RuntimeError(f"max_granularity {max_granularity} not power of two")
227
+
228
+ num_queries = 0
229
+
230
+ def deepcopy_fx_graph(fx_graph: fx.Graph) -> fx.Graph:
231
+ return fx.GraphModule(fail_f, copy.deepcopy(fx_graph)).graph
232
+
233
+ def graph_fails(graph: fx.Graph, inps: Sequence[torch.Tensor]) -> bool:
234
+ nonlocal num_queries
235
+ graph = copy.deepcopy(graph)
236
+ num_queries += 1
237
+ mod = fx.GraphModule(fail_f, graph)
238
+ mod.graph.lint()
239
+ return module_fails(mod, inps)
240
+
241
+ writer = None
242
+ if offload_to_disk:
243
+ if save_dir is None:
244
+ raise AssertionError("save_dir must not be None when offload_to_disk=True")
245
+ writer = ContentStoreWriter(save_dir)
246
+
247
+ ConcreteProp(fail_f, writer=writer, skip_offload=skip_offload).propagate(*inps)
248
+ if not skip_sanity and not graph_fails(failing_graph, inps):
249
+ raise RuntimeError("Input graph did not fail the tester")
250
+ print(f"Started off with {cur_size} nodes", file=sys.stderr)
251
+
252
+ def _register_strategy(
253
+ strategy: Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None],
254
+ name: str,
255
+ ) -> Callable[[ReproState, int], ReproState | None]:
256
+ @wraps(strategy)
257
+ def new_func(old_state: ReproState, granularity: int = 1) -> ReproState | None:
258
+ print(file=sys.stderr)
259
+ print(
260
+ f"Strategy: {name} (G: {granularity}) "
261
+ f"({len(old_state.graph.nodes)} nodes, {len(old_state.inps)} inputs)",
262
+ file=sys.stderr,
263
+ )
264
+ new_state = strategy(
265
+ deepcopy_fx_graph(old_state.graph), list(old_state.inps), granularity
266
+ )
267
+ if new_state is not None:
268
+ new_nodes = len(new_state.graph.nodes)
269
+ old_nodes = len(old_state.graph.nodes)
270
+ new_inps = len(new_state.inps)
271
+ old_inps = len(old_state.inps)
272
+ new_outs = len(get_outputs(new_state.graph))
273
+ old_outs = len(get_outputs(old_state.graph))
274
+ progress_made = False
275
+ if new_nodes < old_nodes:
276
+ progress_made = True
277
+ print(
278
+ f"SUCCESS: Went from {old_nodes} to {new_nodes} nodes",
279
+ file=sys.stderr,
280
+ )
281
+ if new_inps > old_inps:
282
+ progress_made = True
283
+ print(
284
+ f"SUCCESS: Went from {old_inps} to {new_inps} inputs",
285
+ file=sys.stderr,
286
+ )
287
+ if new_outs < old_outs:
288
+ progress_made = True
289
+ print(
290
+ f"SUCCESS: Went from {old_outs} to {new_outs} outputs",
291
+ file=sys.stderr,
292
+ )
293
+
294
+ if not progress_made:
295
+ raise RuntimeError("Success raised but no progress made?")
296
+
297
+ if not graph_fails(new_state.graph, new_state.inps):
298
+ print(
299
+ "WARNING: Something went wrong, not applying this minification",
300
+ file=sys.stderr,
301
+ )
302
+ return None
303
+ return new_state
304
+ else:
305
+ print(f"FAIL: {name}", file=sys.stderr)
306
+ return None
307
+
308
+ return new_func
309
+
310
+ def register_strategy(
311
+ name: str,
312
+ ) -> Callable[
313
+ [Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None]],
314
+ Callable[[ReproState, int], ReproState | None],
315
+ ]:
316
+ return partial(_register_strategy, name=name)
317
+
318
+ @register_strategy("Truncate suffix")
319
+ def remove_suffix(
320
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
321
+ ) -> ReproState | None:
322
+ tested: set[int] = set()
323
+ new_graph = fx.Graph()
324
+ env: dict[fx.Node, fx.Node] = {}
325
+ for idx, node in enumerate(cur_graph.nodes):
326
+ new_node = new_graph.node_copy(node, lambda x: env[x])
327
+ if node.op not in ["placeholder", "output"]:
328
+ # If idx is divisible by (granularity * 2), it would have been checked already.
329
+ if (
330
+ idx % granularity == 0
331
+ and (idx % (granularity * 2) != 0)
332
+ and idx not in tested
333
+ ):
334
+ output_node = new_graph.output((new_node,))
335
+ if len(new_graph.nodes) < len(cur_graph.nodes) and graph_fails(
336
+ new_graph, cur_inps
337
+ ):
338
+ return ReproState(new_graph, cur_inps)
339
+ else:
340
+ tested.add(idx)
341
+ new_graph.erase_node(output_node)
342
+ env[node] = new_node
343
+ return None
344
+
345
+ @register_strategy("Remove outputs")
346
+ def remove_outputs(
347
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
348
+ ) -> ReproState | None:
349
+ granularity = max(1, granularity // 2)
350
+ output: fx.Node | None = None
351
+ for idx, node in enumerate(cur_graph.nodes):
352
+ node.idx = idx # type: ignore[attr-defined]
353
+ if node.op == "output":
354
+ output = node
355
+ break
356
+
357
+ if output is None:
358
+ return None
359
+
360
+ if isinstance(output.args[0], fx.Node):
361
+ return None
362
+
363
+ # output.args[0] is a tuple/list of nodes when returning multiple outputs
364
+ output_args_raw = output.args[0]
365
+ if not isinstance(output_args_raw, (list, tuple)):
366
+ raise AssertionError(
367
+ f"expected output_args_raw to be list or tuple, got {type(output_args_raw)}"
368
+ )
369
+ output_args = sorted(
370
+ output_args_raw,
371
+ key=lambda x: x.idx if isinstance(x, fx.Node) else int(1e9), # type: ignore[attr-defined]
372
+ )
373
+ if len(output_args) == 1:
374
+ return None
375
+
376
+ for idx in range(0, len(output_args), granularity):
377
+ output.args = (output_args[:idx] + output_args[idx + granularity :],)
378
+ if graph_fails(cur_graph, cur_inps):
379
+ return ReproState(cur_graph, cur_inps)
380
+ return None
381
+
382
+ def remove_unused_inputs_unchecked(cur_state: ReproState) -> ReproState | None:
383
+ cur_graph = cur_state.graph
384
+ cur_inps = cur_state.inps
385
+ ph_nodes = list(get_placeholders(cur_graph))
386
+ if len(ph_nodes) != len(cur_inps):
387
+ raise AssertionError(
388
+ f"len(ph_nodes)={len(ph_nodes)} != len(cur_inps)={len(cur_inps)}"
389
+ )
390
+
391
+ new_inps: list[torch.Tensor] = []
392
+ for idx in range(len(ph_nodes)):
393
+ if len(ph_nodes[idx].users) == 0:
394
+ cur_graph.erase_node(ph_nodes[idx])
395
+ else:
396
+ new_inps.append(cur_inps[idx])
397
+ if len(new_inps) < len(cur_inps):
398
+ return ReproState(cur_graph, new_inps)
399
+ return None
400
+
401
+ def remove_unused_inputs_checked(cur_state: ReproState) -> ReproState | None:
402
+ new_state = remove_unused_inputs_unchecked(cur_state)
403
+ if new_state is not None and graph_fails(new_state.graph, new_state.inps):
404
+ return new_state
405
+ return None
406
+
407
+ def _remove_unused_wrapper(
408
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
409
+ ) -> ReproState | None:
410
+ return remove_unused_inputs_checked(ReproState(cur_graph, cur_inps))
411
+
412
+ remove_unused_inputs = register_strategy("Remove unused inputs")(
413
+ _remove_unused_wrapper
414
+ )
415
+
416
+ @register_strategy("Eliminate dead code")
417
+ def eliminate_dead_code(
418
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
419
+ ) -> ReproState | None:
420
+ if cur_graph.eliminate_dead_code() and graph_fails(cur_graph, cur_inps):
421
+ return ReproState(cur_graph, cur_inps)
422
+ return None
423
+
424
+ def _consolidate_placeholders(
425
+ cur_graph: fx.Graph, inps: list[torch.Tensor]
426
+ ) -> fx.Graph:
427
+ new_graph = fx.Graph()
428
+ env = {}
429
+ seen_non_placeholder = False
430
+
431
+ # Move all placeholders to the front; also, if any load_tensor
432
+ # is at the front, convert it into an input (because it can be live
433
+ # all the time)
434
+ for node in cur_graph.nodes:
435
+ if node.op == "placeholder":
436
+ new_node = new_graph.node_copy(node, lambda x: env[x])
437
+ env[node] = new_node
438
+ elif not seen_non_placeholder and is_load_tensor_node(node):
439
+ new_node = new_graph.placeholder(node.name)
440
+ env[node] = new_node
441
+ inps.append(
442
+ torch.ops.debugprims.load_tensor.default(*node.args, **node.kwargs)
443
+ )
444
+ else:
445
+ seen_non_placeholder = True
446
+
447
+ # Move everyone else
448
+ for node in cur_graph.nodes:
449
+ if node not in env:
450
+ new_node = new_graph.node_copy(node, lambda x: env[x])
451
+ env[node] = new_node
452
+ return new_graph
453
+
454
+ @register_strategy("Delta Debugging")
455
+ def delta_debugging(
456
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
457
+ ) -> ReproState | None:
458
+ num_nodes = len(cur_graph.nodes)
459
+ for start_range in range(0, num_nodes, granularity):
460
+ is_removing = False
461
+ new_graph = deepcopy_fx_graph(cur_graph)
462
+ new_inps = list(cur_inps[:])
463
+ end_range = min(num_nodes, start_range + granularity)
464
+ for idx in range(start_range, end_range):
465
+ new_node = list(new_graph.nodes)[idx]
466
+ if _convert_node_to_placeholder(new_graph, new_node, new_inps):
467
+ is_removing = True
468
+ if not is_removing:
469
+ continue
470
+ new_graph.eliminate_dead_code()
471
+ new_graph = _consolidate_placeholders(new_graph, new_inps)
472
+ new_state = remove_unused_inputs_unchecked(ReproState(new_graph, new_inps))
473
+ if new_state is None:
474
+ new_state = ReproState(new_graph, new_inps)
475
+ if graph_fails(new_state.graph, new_state.inps):
476
+ return ReproState(new_state.graph, new_state.inps)
477
+
478
+ return None
479
+
480
+ @register_strategy("Consolidate Inputs")
481
+ def consolidate_inputs(
482
+ cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int
483
+ ) -> ReproState | None:
484
+ old_len = len(cur_inps)
485
+ new_inps = list(cur_inps[:])
486
+ cur_graph = _consolidate_placeholders(cur_graph, new_inps)
487
+ if len(cur_inps) > old_len and graph_fails(cur_graph, new_inps):
488
+ return ReproState(cur_graph, new_inps)
489
+ return None
490
+
491
+ failing_state = ReproState(failing_graph, inps)
492
+
493
+ def try_granularity(
494
+ failing_state: ReproState, granularity: int, use_non_granular: bool
495
+ ) -> ReproState | None:
496
+ print(f"Trying granularity {granularity}", file=sys.stderr)
497
+
498
+ strategies = []
499
+ num_nodes = len(failing_state.graph.nodes)
500
+ num_outputs = len(get_outputs(failing_state.graph))
501
+ if num_outputs > num_nodes // 2:
502
+ strategies += [remove_outputs]
503
+
504
+ if use_non_granular:
505
+ strategies += [
506
+ eliminate_dead_code,
507
+ remove_unused_inputs,
508
+ consolidate_inputs,
509
+ ]
510
+
511
+ strategies += [remove_suffix, delta_debugging]
512
+
513
+ for strategy in strategies:
514
+ new_state = strategy(failing_state, granularity)
515
+ if new_state is not None:
516
+ return new_state
517
+ return None
518
+
519
+ while True:
520
+ dump_state(fx.GraphModule(fail_f, failing_state.graph), failing_state.inps)
521
+ granularity = int(2 ** (math.floor(math.log2(len(failing_state.graph.nodes)))))
522
+ if max_granularity is not None:
523
+ granularity = min(max_granularity, granularity)
524
+ new_state = try_granularity(failing_state, granularity, use_non_granular=True)
525
+ if new_state is not None:
526
+ failing_state = new_state
527
+ continue
528
+
529
+ granularity //= 2
530
+ has_progress = False
531
+ while granularity >= 1:
532
+ new_state = try_granularity(
533
+ failing_state, granularity, use_non_granular=False
534
+ )
535
+ if new_state is not None:
536
+ failing_state = new_state
537
+ has_progress = True
538
+ break
539
+ granularity //= 2
540
+ if has_progress:
541
+ continue
542
+
543
+ new_state = remove_outputs(failing_state, 1)
544
+ if new_state is not None:
545
+ failing_state = new_state
546
+ continue
547
+
548
+ break
549
+
550
+ if not graph_fails(failing_state.graph, failing_state.inps):
551
+ raise RuntimeError("Uh oh, something went wrong :( Final graph is not failing")
552
+
553
+ print(f"Made {num_queries} queries", file=sys.stderr)
554
+ failing_fx = fx.GraphModule(fail_f, failing_state.graph)
555
+
556
+ # If XLA debugging environment is enabled, create minified HLO graph as well
557
+ if "XLA_HLO_DEBUG" in os.environ:
558
+ create_minified_hlo_graph(failing_fx, failing_state.inps)
559
+
560
+ dump_state(failing_fx, failing_state.inps)
561
+ print("Wrote minimal repro out to repro.py", file=sys.stderr)
562
+ return failing_fx, failing_state.inps
.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ from typing import Any, NoReturn, TYPE_CHECKING
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from torch import Tensor
15
+ from torch.nn.utils._named_member_accessor import NamedMemberAccessor
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable, Iterable, Sequence
20
+
21
+ # Utilities to make nn.Module "functional"
22
+ # In particular the goal is to be able to provide a function that takes as input
23
+ # the parameters and evaluate the nn.Module using fixed inputs.
24
+
25
+
26
+ def raise_parameter_tying_error() -> NoReturn:
27
+ raise RuntimeError(
28
+ "make_functional(module): we don't yet support models that "
29
+ "do parameter tying (also sometimes known as weight sharing). "
30
+ "Please try to rewrite your model by replacing all instances of the "
31
+ "tied parameter with another and/or comment your support in "
32
+ "https://github.com/pytorch/functorch/issues/446"
33
+ )
34
+
35
+
36
+ def create_names_map(
37
+ named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]],
38
+ tied_named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]],
39
+ ) -> dict[str, list[str]]:
40
+ """
41
+ named_params is a dictionary of tensors: {'A': A, 'B': B}
42
+ tied_named_params is another dictionary of tensors {'A': A, 'B': B, 'B_tied': B}
43
+ with potentially tied (or 'duplicated') tensors
44
+
45
+ This function creates a mapping from the names in named_params to the
46
+ names in tied_named_params: {'A': ['A'], 'B': ['B', 'B_tied']}.
47
+ """
48
+ named_params_dict = dict(named_params)
49
+ tied_named_params_dict = dict(tied_named_params)
50
+
51
+ tensors_dict_keys = set(named_params_dict.keys())
52
+ tied_tensors_dict_keys = set(tied_named_params_dict.keys())
53
+ if not tensors_dict_keys.issubset(tied_tensors_dict_keys):
54
+ raise AssertionError(
55
+ f"tensors_dict_keys {tensors_dict_keys} is not a subset of "
56
+ f"tied_tensors_dict_keys {tied_tensors_dict_keys}"
57
+ )
58
+
59
+ tensor_to_mapping: dict[Tensor, tuple[str, list[str]]] = {}
60
+ for key, tensor in named_params_dict.items():
61
+ tensor_to_mapping[tensor] = (key, [])
62
+ for key, tensor in tied_named_params_dict.items():
63
+ if tensor not in tensor_to_mapping:
64
+ raise AssertionError(
65
+ f"tensor for key '{key}' not found in tensor_to_mapping"
66
+ )
67
+ tensor_to_mapping[tensor][1].append(key)
68
+ return dict(tensor_to_mapping.values())
69
+
70
+
71
+ def _extract_members(
72
+ mod: nn.Module,
73
+ named_members: Callable[..., Iterable[tuple[str, Tensor]]],
74
+ subclass: Callable[[Tensor], Tensor],
75
+ ) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
76
+ all_named_members = tuple(named_members(remove_duplicate=False))
77
+ unique_named_members = tuple(named_members(remove_duplicate=True))
78
+ names_map = create_names_map(unique_named_members, all_named_members)
79
+
80
+ # Remove all the members in the model
81
+ # pyrefly: ignore [implicit-any]
82
+ memo = {}
83
+ accessor = NamedMemberAccessor(mod)
84
+ for name, p in all_named_members:
85
+ if p not in memo:
86
+ memo[p] = subclass(torch.empty_like(p, device="meta"))
87
+ replacement = memo[p]
88
+ accessor.set_tensor(name, replacement)
89
+
90
+ if len(unique_named_members) == 0:
91
+ names, params = (), ()
92
+ else:
93
+ names, params = zip(*unique_named_members) # type: ignore[assignment]
94
+ return params, names, names_map
95
+
96
+
97
+ def extract_weights(
98
+ mod: nn.Module,
99
+ ) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
100
+ """
101
+ This function removes all the Parameters from the model and
102
+ return them as a tuple as well as their original attribute names.
103
+ The weights must be re-loaded with `load_weights` before the model
104
+ can be used again.
105
+ Note that this function modifies the model in place and after this
106
+ call, mod.parameters() will be empty.
107
+ """
108
+ return _extract_members(mod, mod.named_parameters, nn.Parameter)
109
+
110
+
111
+ def extract_buffers(
112
+ mod: nn.Module,
113
+ ) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]:
114
+ return _extract_members(mod, mod.named_buffers, lambda x: x)
115
+
116
+
117
+ def load_weights(
118
+ mod: nn.Module,
119
+ names: Sequence[str],
120
+ params: Sequence[Tensor],
121
+ as_params: bool = False,
122
+ ) -> None:
123
+ """
124
+ Reload a set of weights so that `mod` can be used again to perform a forward pass.
125
+ Note that the `params` are regular Tensors (that can have history) and so are left
126
+ as Tensors. This means that mod.parameters() will still be empty after this call.
127
+ """
128
+ accessor = NamedMemberAccessor(mod)
129
+ if as_params:
130
+ params = [nn.Parameter(p) for p in params]
131
+ accessor.set_tensors(names, params)
132
+
133
+
134
+ def _swap_state(
135
+ mod: nn.Module, names_map: dict[str, list[str]], elems: Iterable[Tensor]
136
+ ) -> list[Tensor]:
137
+ result: list[Tensor] = []
138
+ accessor = NamedMemberAccessor(mod)
139
+ for (_, attr_names), elem in zip(names_map.items(), elems):
140
+ for i, attr_name in enumerate(attr_names):
141
+ if i == 0:
142
+ result.append(accessor.swap_tensor(attr_name, elem))
143
+ else:
144
+ accessor.set_tensor(attr_name, elem)
145
+ return result
146
+
147
+
148
+ def load_buffers(
149
+ mod: nn.Module,
150
+ names: Sequence[str],
151
+ buffers: Sequence[Tensor],
152
+ as_params: bool = False,
153
+ ) -> None:
154
+ accessor = NamedMemberAccessor(mod)
155
+ accessor.set_tensors(names, buffers)
156
+
157
+
158
+ def load_state(
159
+ model: nn.Module,
160
+ weights: Sequence[Tensor],
161
+ weight_names: Sequence[str],
162
+ buffers: Sequence[Tensor] = (),
163
+ buffer_names: Sequence[str] = (),
164
+ ) -> nn.Module:
165
+ """load_state(model, weights, weight_names, buffers=(), buffer_names=()) -> model
166
+
167
+ load_state takes `weights` and `buffers` and assigns them to the model.
168
+ This is the inverse operation of `make_functional_deprecated_v1`.
169
+ """
170
+ if len(weight_names) != len(weights):
171
+ raise AssertionError(
172
+ f"len(weight_names)={len(weight_names)} != len(weights)={len(weights)}"
173
+ )
174
+ load_weights(model, weight_names, weights)
175
+ if len(buffers) > 0:
176
+ if len(buffer_names) != len(buffers):
177
+ raise AssertionError(
178
+ f"len(buffer_names)={len(buffer_names)} != len(buffers)={len(buffers)}"
179
+ )
180
+ load_buffers(model, buffer_names, buffers)
181
+ return model
182
+
183
+
184
+ def make_functional_deprecated_v1(
185
+ model: nn.Module,
186
+ ) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]:
187
+ """make_functional_deprecated_v1(model) -> weights, func, weight_names
188
+
189
+ Given an nn.Module, make_functional_deprecated_v1 extracts the state (weights)
190
+ and returns a functional version of the model, `func`. This makes
191
+ it so that it is possible use transforms over the parameters of
192
+ `model`.
193
+
194
+ `func` can be invoked as follows:
195
+ ```
196
+ x = torch.randn(4, 3)
197
+ model = nn.Linear(3, 3)
198
+ weights, func, _ = make_functional_deprecated_v1(model)
199
+ func(weights, (x,))
200
+ ```
201
+
202
+ And here is an example of applying the grad transform:
203
+ ```
204
+ x = torch.randn(4, 3)
205
+ model = nn.Linear(3, 3)
206
+ weights, _, func = make_functional_deprecated_v1(model)
207
+ grad_weights = grad(func)(weights, (x,))
208
+ ```
209
+
210
+ To put the state back into a model, use `load_state`.
211
+ """
212
+ buffers = list(model.buffers())
213
+ if len(buffers) > 0:
214
+ raise RuntimeError(
215
+ "make_functional_deprecated_v1(model): `model` has buffers. Please use "
216
+ "make_functional_with_buffers_deprecated_v1(model) instead."
217
+ )
218
+ weights, descriptors, _ = extract_weights(model)
219
+
220
+ def fun(weights: tuple[Tensor, ...], data: tuple[Any, ...]) -> Any:
221
+ mutable_model = copy.deepcopy(model)
222
+ load_weights(mutable_model, descriptors, weights)
223
+ return mutable_model(*data)
224
+
225
+ return weights, fun, descriptors
226
+
227
+
228
+ def make_functional_with_buffers_deprecated_v1(
229
+ model: nn.Module,
230
+ ) -> tuple[
231
+ tuple[Tensor, ...],
232
+ tuple[Tensor, ...],
233
+ Callable[..., Any],
234
+ tuple[str, ...],
235
+ tuple[str, ...],
236
+ ]:
237
+ """make_functional_with_buffers_deprecated_v1(model) -> weights, buffers, func, weight_names, buffer_names
238
+
239
+ Given an nn.Module, make_functional_with_buffers_deprecated_v1 extracts the state (weights and buffers)
240
+ and returns a functional version of the model, `func`.
241
+
242
+ `func` can be invoked as follows:
243
+ ```
244
+ x = torch.randn(4, 3)
245
+ model = nn.Linear(3, 3)
246
+ weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
247
+ func(weights, buffers, (x,))
248
+ ```
249
+
250
+ And here is an example of applying the grad transform:
251
+ ```
252
+ x = torch.randn(4, 3)
253
+ model = nn.Linear(3, 3)
254
+ weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
255
+ func(weights, buffers, (x,))
256
+ grad_weights = grad(func)(weights, buffers, (x,))
257
+ ```
258
+
259
+ To put the state back into a model, use `load_state`.
260
+ """
261
+ weights, weight_descriptors, _ = extract_weights(model)
262
+ buffers, buf_descriptors, _ = extract_buffers(model)
263
+
264
+ def fun(
265
+ weights: tuple[Tensor, ...],
266
+ buffers: tuple[Tensor, ...],
267
+ data: tuple[Any, ...],
268
+ ) -> Any:
269
+ mutable_model = copy.deepcopy(model)
270
+ load_weights(mutable_model, weight_descriptors, weights)
271
+ load_buffers(mutable_model, buf_descriptors, buffers)
272
+ return mutable_model(*data)
273
+
274
+ return weights, buffers, fun, weight_descriptors, buf_descriptors
275
+
276
+
277
+ class FunctionalModuleWithBuffers(nn.Module):
278
+ """
279
+ This is the callable object returned by :func:`make_functional_with_buffers`.
280
+ """
281
+
282
+ def __init__(
283
+ self,
284
+ stateless_model: nn.Module,
285
+ param_names: tuple[str, ...],
286
+ buffer_names: tuple[str, ...],
287
+ param_names_map: dict[str, list[str]],
288
+ buffer_names_map: dict[str, list[str]],
289
+ ) -> None:
290
+ super().__init__()
291
+ self.stateless_model = stateless_model
292
+ self.param_names = param_names
293
+ self.buffer_names = buffer_names
294
+
295
+ self.all_names_map = dict(param_names_map)
296
+ self.all_names_map.update(buffer_names_map)
297
+
298
+ @staticmethod
299
+ def _create_from(
300
+ model: nn.Module, disable_autograd_tracking: bool = False
301
+ ) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
302
+ # TODO: We don't need to copy the model to create a stateless copy
303
+ model_copy = copy.deepcopy(model)
304
+ params, param_names, param_names_map = extract_weights(model_copy)
305
+ buffers, buffer_names, buffer_names_map = extract_buffers(model_copy)
306
+ if disable_autograd_tracking:
307
+ for param in params:
308
+ param.requires_grad_(False)
309
+ return (
310
+ FunctionalModuleWithBuffers(
311
+ model_copy, param_names, buffer_names, param_names_map, buffer_names_map
312
+ ),
313
+ params,
314
+ buffers,
315
+ )
316
+
317
+ def forward(
318
+ self,
319
+ params: Iterable[Tensor],
320
+ buffers: Iterable[Tensor],
321
+ *args: Any,
322
+ **kwargs: Any,
323
+ ) -> Any:
324
+ # Temporarily load the state back onto self.stateless_model
325
+ old_state = _swap_state(
326
+ self.stateless_model,
327
+ self.all_names_map,
328
+ tuple(params) + tuple(buffers),
329
+ )
330
+ try:
331
+ return self.stateless_model(*args, **kwargs)
332
+ finally:
333
+ # Remove the loaded state on self.stateless_model
334
+ _swap_state(self.stateless_model, self.all_names_map, old_state)
335
+
336
+
337
+ class FunctionalModule(nn.Module):
338
+ """
339
+ This is the callable object returned by :func:`make_functional`.
340
+ """
341
+
342
+ def __init__(
343
+ self,
344
+ stateless_model: nn.Module,
345
+ param_names: tuple[str, ...],
346
+ names_map: dict[str, list[str]],
347
+ ) -> None:
348
+ super().__init__()
349
+ self.stateless_model = stateless_model
350
+ self.param_names = param_names
351
+ self.names_map = names_map
352
+
353
+ @staticmethod
354
+ def _create_from(
355
+ model: nn.Module, disable_autograd_tracking: bool = False
356
+ ) -> tuple[FunctionalModule, tuple[Tensor, ...]]:
357
+ # TODO: We don't need to copy the model to create a stateless copy
358
+ model_copy = copy.deepcopy(model)
359
+ params, param_names, names_map = extract_weights(model_copy)
360
+ if disable_autograd_tracking:
361
+ for param in params:
362
+ param.requires_grad_(False)
363
+ return FunctionalModule(model_copy, param_names, names_map), params
364
+
365
+ def forward(self, params: Iterable[Tensor], *args: Any, **kwargs: Any) -> Any:
366
+ # Temporarily load the state back onto self.stateless_model
367
+ old_state = _swap_state(self.stateless_model, self.names_map, params)
368
+ try:
369
+ return self.stateless_model(*args, **kwargs)
370
+ finally:
371
+ # Remove the loaded state on self.stateless_model
372
+ _swap_state(self.stateless_model, self.names_map, old_state)
373
+
374
+
375
+ def make_functional(
376
+ model: nn.Module, disable_autograd_tracking: bool = False
377
+ ) -> tuple[FunctionalModule, tuple[Tensor, ...]]:
378
+ """make_functional(model, disable_autograd_tracking=False) -> func, params
379
+
380
+ Given a ``torch.nn.Module``, :func:`make_functional` extracts the state
381
+ (params) and returns a functional version of the model, ``func``. This
382
+ makes it so that it is possible use transforms over the parameters of
383
+ ``model``.
384
+
385
+ ``func`` can be invoked as follows:
386
+
387
+ .. code-block:: python
388
+
389
+ import torch
390
+ import torch.nn as nn
391
+ from functorch import make_functional
392
+
393
+ x = torch.randn(4, 3)
394
+ model = nn.Linear(3, 3)
395
+ func, params = make_functional(model)
396
+ func(params, x)
397
+
398
+ And here is an example of applying the grad transform over the parameters
399
+ of a model.
400
+
401
+ .. code-block:: python
402
+
403
+ import torch
404
+ import torch.nn as nn
405
+ from functorch import make_functional, grad
406
+
407
+ x = torch.randn(4, 3)
408
+ t = torch.randn(4, 3)
409
+ model = nn.Linear(3, 3)
410
+ func, params = make_functional(model)
411
+
412
+
413
+ def compute_loss(params, x, t):
414
+ y = func(params, x)
415
+ return nn.functional.mse_loss(y, t)
416
+
417
+
418
+ grad_weights = grad(compute_loss)(params, x, t)
419
+
420
+ If the model has any buffers, please use :func:`make_functional_with_buffers` instead.
421
+
422
+ Args:
423
+ model (torch.nn.Module): Input model.
424
+ disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
425
+ The returned params are unrelated to the set of params from the original model. If False (default),
426
+ the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
427
+ PyTorch autograd), matching the requires_grad-ness of the params from the original model.
428
+ Otherwise, the returned params will have ``requires_grad=False``. Default, False.
429
+ If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
430
+ ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
431
+ Otherwise, if you're only planning on using functorch's gradient transforms,
432
+ then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
433
+ history with PyTorch autograd.
434
+
435
+ """
436
+ buffers = list(model.buffers())
437
+ if len(buffers) > 0:
438
+ raise RuntimeError(
439
+ "make_functional(model): `model` has buffers. Please use "
440
+ "make_functional_with_buffers(model) instead."
441
+ )
442
+ return FunctionalModule._create_from(
443
+ model, disable_autograd_tracking=disable_autograd_tracking
444
+ )
445
+
446
+
447
+ def make_functional_with_buffers(
448
+ model: nn.Module, disable_autograd_tracking: bool = False
449
+ ) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
450
+ """make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers
451
+
452
+ Given a ``torch.nn.Module``, make_functional_with_buffers extracts the
453
+ state (params and buffers) and returns a functional version of the model
454
+ ``func`` that can be invoked like a function.
455
+
456
+ ``func`` can be invoked as follows:
457
+
458
+ .. code-block:: python
459
+
460
+ import torch
461
+ import torch.nn as nn
462
+ from functorch import make_functional_with_buffers
463
+
464
+ x = torch.randn(4, 3)
465
+ model = nn.Linear(3, 3)
466
+ func, params, buffers = make_functional_with_buffers(model)
467
+ func(params, buffers, x)
468
+
469
+ And here is an example of applying the grad transform over the parameters
470
+ of a model:
471
+
472
+ .. code-block:: python
473
+
474
+ import torch
475
+ import torch.nn as nn
476
+ from functorch import make_functional_with_buffers, grad
477
+
478
+ x = torch.randn(4, 3)
479
+ t = torch.randn(4, 3)
480
+ model = nn.Linear(3, 3)
481
+ func, params, buffers = make_functional_with_buffers(model)
482
+
483
+
484
+ def compute_loss(params, buffers, x, t):
485
+ y = func(params, buffers, x)
486
+ return nn.functional.mse_loss(y, t)
487
+
488
+
489
+ grad_weights = grad(compute_loss)(params, buffers, x, t)
490
+
491
+ Args:
492
+ model (torch.nn.Module): Input model.
493
+ disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
494
+ The returned params are unrelated to the set of params from the original model. If False (default),
495
+ the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
496
+ PyTorch autograd), matching the requires_grad-ness of the params from the original model.
497
+ Otherwise, the returned params will have ``requires_grad=False``. Default, False.
498
+ If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
499
+ ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
500
+ Otherwise, if you're only planning on using functorch's gradient transforms,
501
+ then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
502
+ history with PyTorch autograd.
503
+
504
+ """
505
+ return FunctionalModuleWithBuffers._create_from(
506
+ model, disable_autograd_tracking=disable_autograd_tracking
507
+ )
508
+
509
+
510
+ def transpose_stack(
511
+ tuple_of_tuple_of_tensors: tuple[tuple[Tensor, ...], ...],
512
+ ) -> tuple[Tensor, ...]:
513
+ tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors))
514
+ results = tuple(
515
+ torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors
516
+ )
517
+ return results
518
+
519
+
520
+ def combine_state_for_ensemble(
521
+ models: Sequence[nn.Module],
522
+ ) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
523
+ """combine_state_for_ensemble(models) -> func, params, buffers
524
+
525
+ Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
526
+
527
+ Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their
528
+ parameters and buffers together to make ``params`` and ``buffers``.
529
+ Each parameter and buffer in the result will have an additional dimension
530
+ of size ``M``.
531
+
532
+ :func:`combine_state_for_ensemble` also returns ``func``, a functional
533
+ version of one of the models in :attr:`models`. One cannot directly run
534
+ ``func(params, buffers, *args, **kwargs)`` directly, you probably want to
535
+ use ``vmap(func, ...)(params, buffers, *args, **kwargs)``
536
+
537
+ Here's an example of how to ensemble over a very simple model:
538
+
539
+ .. code-block:: python
540
+
541
+ num_models = 5
542
+ batch_size = 64
543
+ in_features, out_features = 3, 3
544
+ models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
545
+ data = torch.randn(batch_size, 3)
546
+
547
+ fmodel, params, buffers = combine_state_for_ensemble(models)
548
+ output = vmap(fmodel, (0, 0, None))(params, buffers, data)
549
+
550
+ assert output.shape == (num_models, batch_size, out_features)
551
+
552
+ .. warning::
553
+ All of the modules being stacked together must be the same (except for
554
+ the values of their parameters/buffers). For example, they should be in the
555
+ same mode (training vs eval).
556
+
557
+ This API is subject to change -- we're investigating better ways to
558
+ create ensembles and would love your feedback how to improve this.
559
+ """
560
+ if len(models) == 0:
561
+ raise RuntimeError(
562
+ "combine_state_for_ensemble: Expected at least one model, got 0."
563
+ )
564
+ if not (all(m.training for m in models) or all(not m.training for m in models)):
565
+ raise RuntimeError(
566
+ "combine_state_for_ensemble: Expected all models to "
567
+ "have the same training/eval mode."
568
+ )
569
+ model0_typ = type(models[0])
570
+ if not all(type(m) is model0_typ for m in models):
571
+ raise RuntimeError(
572
+ "combine_state_for_ensemble: Expected all models to be of the same class."
573
+ )
574
+ funcs, params, buffers = zip(
575
+ *[make_functional_with_buffers(model) for model in models]
576
+ )
577
+ params = transpose_stack(params)
578
+ buffers = transpose_stack(buffers)
579
+ return funcs[0], params, buffers
580
+
581
+
582
+ def functional_init(
583
+ model_class: type[nn.Module],
584
+ ensemble_shape: tuple[()] | tuple[int, ...] = (),
585
+ device: torch.types.Device = "cpu",
586
+ ) -> Callable[..., tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]]:
587
+ def wrapped(
588
+ *args: Any, **kwargs: Any
589
+ ) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]:
590
+ if len(ensemble_shape) >= 2:
591
+ raise ValueError("NYI: ensemble_shape with more than 1 element")
592
+ if len(ensemble_shape) == 0:
593
+ model = model_class(*args, **kwargs).to(device)
594
+ return make_functional_deprecated_v1(model)
595
+ num_models = ensemble_shape[0] # type: ignore[misc]
596
+ if num_models <= 0:
597
+ raise ValueError(f"num_models {num_models} should be > 0")
598
+ # NB: Not very efficient, more of a POC
599
+ models = tuple(
600
+ model_class(*args, **kwargs).to(device) for _ in range(num_models)
601
+ )
602
+ _, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs))
603
+ weights = tuple(make_functional_deprecated_v1(model)[0] for model in models)
604
+ weights = tuple(zip(*weights))
605
+ weights = tuple(torch.stack(shards).detach() for shards in weights)
606
+ return weights, fn, names
607
+
608
+ return wrapped
609
+
610
+
611
+ def functional_init_with_buffers(
612
+ model_class: type[nn.Module],
613
+ ensemble_shape: tuple[()] | tuple[int, ...] = (),
614
+ device: torch.types.Device = "cpu",
615
+ ) -> Callable[
616
+ ...,
617
+ tuple[
618
+ tuple[Tensor, ...],
619
+ tuple[Tensor, ...],
620
+ Callable[..., Any],
621
+ tuple[str, ...],
622
+ tuple[str, ...],
623
+ ]
624
+ | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]],
625
+ ]:
626
+ def wrapped(
627
+ *args: Any, **kwargs: Any
628
+ ) -> (
629
+ tuple[
630
+ tuple[Tensor, ...],
631
+ tuple[Tensor, ...],
632
+ Callable[..., Any],
633
+ tuple[str, ...],
634
+ tuple[str, ...],
635
+ ]
636
+ | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]
637
+ ):
638
+ if len(ensemble_shape) >= 2:
639
+ raise ValueError("NYI: ensemble_shape with more than 1 element")
640
+ if len(ensemble_shape) == 0:
641
+ model = model_class(*args, **kwargs).to(device)
642
+ return make_functional_deprecated_v1(model)
643
+ num_models = ensemble_shape[0] # type: ignore[misc]
644
+ if num_models <= 0:
645
+ raise ValueError(f"num_models {num_models} should be > 0")
646
+ # NB: Not very efficient, more of a POC
647
+ models = tuple(
648
+ model_class(*args, **kwargs).to(device) for _ in range(num_models)
649
+ )
650
+ (
651
+ _,
652
+ _,
653
+ fn,
654
+ weight_names,
655
+ buffer_names,
656
+ ) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs))
657
+ weights, buffers = zip(
658
+ *tuple(
659
+ make_functional_with_buffers_deprecated_v1(model)[:2]
660
+ for model in models
661
+ )
662
+ )
663
+ weights = tuple(zip(*weights))
664
+ weights = tuple(torch.stack(shards).detach() for shards in weights)
665
+ buffers = tuple(zip(*buffers))
666
+ buffers = tuple(torch.stack(shards).detach() for shards in buffers)
667
+ return weights, buffers, fn, weight_names, buffer_names
668
+
669
+ return wrapped
.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ This module contains pre-dispatch wrappers for functorch operations
9
+ that enable proper tracing in PT2 non-strict export/compile fx graph.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING
15
+
16
+ import torch
17
+ from torch._C import (
18
+ _enter_dual_level as _enter_dual_level_impl,
19
+ _exit_dual_level as _exit_dual_level_impl,
20
+ )
21
+ from torch._C._functorch import (
22
+ _add_batch_dim as _add_batch_dim_impl,
23
+ _jvp_decrement_nesting as _jvp_decrement_nesting_impl,
24
+ _jvp_increment_nesting as _jvp_increment_nesting_impl,
25
+ _remove_batch_dim as _remove_batch_dim_impl,
26
+ _unwrap_for_grad as _unwrap_for_grad_impl,
27
+ _vmap_decrement_nesting as _vmap_decrement_nesting_impl,
28
+ _vmap_increment_nesting as _vmap_increment_nesting_impl,
29
+ )
30
+ from torch._VF import ( # type: ignore[attr-defined]
31
+ _make_dual as _make_dual_impl,
32
+ _unpack_dual as _unpack_dual_impl,
33
+ )
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ import threading
38
+
39
+
40
+ def _add_batch_dim(self: torch.Tensor, batch_dim: int, level: int) -> torch.Tensor:
41
+ """
42
+ Thin wrapper around torch._C._add_batch_dim that is used to proxy in
43
+ PT2 export/compile fx graph
44
+ """
45
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
46
+
47
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
48
+ batch_dim = self.ndim + batch_dim if batch_dim < 0 else batch_dim
49
+
50
+ if mode:
51
+ return torch.overrides.handle_torch_function(
52
+ _add_batch_dim, (self,), self, batch_dim, level
53
+ )
54
+
55
+ res = _add_batch_dim_impl(self, batch_dim, level)
56
+ return res
57
+
58
+
59
+ def _remove_batch_dim(
60
+ self: torch.Tensor, level: int, batch_size: int, out_dim: int
61
+ ) -> torch.Tensor:
62
+ """
63
+ Thin wrapper around torch._C._remove_batch_dim that is used to proxy in
64
+ PT2 export/compile fx graph
65
+ """
66
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
67
+
68
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
69
+
70
+ if mode:
71
+ return torch.overrides.handle_torch_function(
72
+ _remove_batch_dim, (self,), self, level, batch_size, out_dim
73
+ )
74
+
75
+ res = _remove_batch_dim_impl(self, level, batch_size, out_dim)
76
+ return res
77
+
78
+
79
+ def _vmap_increment_nesting(batch_size: int, randomness: str) -> int:
80
+ """
81
+ Thin wrapper around torch._C._vmap_increment_nesting that is used
82
+ to proxy in export/compile graph
83
+ """
84
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
85
+
86
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
87
+
88
+ if mode:
89
+ return torch.overrides.handle_torch_function(
90
+ _vmap_increment_nesting, (batch_size,), batch_size, randomness
91
+ )
92
+ res = _vmap_increment_nesting_impl(batch_size, randomness)
93
+ return res
94
+
95
+
96
+ def _vmap_decrement_nesting() -> int:
97
+ """
98
+ Thin wrapper around torch._C._vmap_increment_nesting that is used
99
+ to proxy in export/compile graph
100
+ """
101
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
102
+
103
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
104
+
105
+ if mode:
106
+ return torch.overrides.handle_torch_function(
107
+ _vmap_decrement_nesting,
108
+ (),
109
+ )
110
+ return _vmap_decrement_nesting_impl()
111
+
112
+
113
+ # Global variables for lazy_load_decompositions
114
+ DECOMPOSITIONS_LOADED: bool = False
115
+ DECOMPOSITIONS_LOCK: threading.Lock | None = None
116
+ VMAP_DECOMPOSITIONS_LIB: torch.library.Library | None = None
117
+
118
+
119
+ def lazy_load_decompositions() -> None:
120
+ """
121
+ Lazy loading of vmap decompositions with pre-dispatch support.
122
+ """
123
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
124
+
125
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
126
+
127
+ if mode:
128
+ return torch.overrides.handle_torch_function(lazy_load_decompositions, ())
129
+
130
+ global DECOMPOSITIONS_LOADED, DECOMPOSITIONS_LOCK, VMAP_DECOMPOSITIONS_LIB
131
+
132
+ if DECOMPOSITIONS_LOADED:
133
+ return
134
+
135
+ # Initialize lock if needed
136
+ if DECOMPOSITIONS_LOCK is None:
137
+ import threading
138
+
139
+ DECOMPOSITIONS_LOCK = threading.Lock()
140
+
141
+ with DECOMPOSITIONS_LOCK:
142
+ if DECOMPOSITIONS_LOADED:
143
+ return
144
+
145
+ import os
146
+
147
+ if not (os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__):
148
+ DECOMPOSITIONS_LOADED = True
149
+ return
150
+
151
+ # use an alternate way to register an operator into the decomposition table
152
+ # _register_jit_decomposition doesn't work for some operators, e.g. addr,
153
+ # because the Tensor types generated cannot be unioned by torchscript
154
+ # decomp should be type OpOverload
155
+ VMAP_DECOMPOSITIONS_LIB = torch.library.Library(
156
+ "aten", "IMPL", "FuncTorchBatched"
157
+ )
158
+
159
+ from torch._decomp import decomposition_table
160
+
161
+ def _register_python_decomposition_vmap(decomp: torch._ops.OpOverload) -> None:
162
+ if VMAP_DECOMPOSITIONS_LIB is None:
163
+ raise AssertionError("VMAP_DECOMPOSITIONS_LIB must not be None")
164
+ if decomp in decomposition_table:
165
+ VMAP_DECOMPOSITIONS_LIB.impl(decomp, decomposition_table[decomp])
166
+ else:
167
+ raise RuntimeError(f"could not find decomposition for {decomp}")
168
+
169
+ _register_python_decomposition_vmap(torch.ops.aten.mse_loss_backward.default)
170
+ _register_python_decomposition_vmap(
171
+ torch.ops.aten.smooth_l1_loss_backward.default
172
+ )
173
+ _register_python_decomposition_vmap(torch.ops.aten.huber_loss_backward.default)
174
+ _register_python_decomposition_vmap(torch.ops.aten.nll_loss_forward.default)
175
+ _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_forward.default)
176
+ _register_python_decomposition_vmap(torch.ops.aten.nll_loss_backward.default)
177
+ _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_backward.default)
178
+ _register_python_decomposition_vmap(torch.ops.aten.addr.default)
179
+
180
+ DECOMPOSITIONS_LOADED = True
181
+
182
+
183
+ def _make_dual(
184
+ tensor: torch.Tensor, tangent: torch.Tensor, *, level: int = 0
185
+ ) -> torch.Tensor:
186
+ """
187
+ Thin wrapper around torch._VF._make_dual that is used to proxy in
188
+ PT2 export/compile fx graph for forward-mode AD.
189
+ """
190
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
191
+
192
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
193
+
194
+ if mode:
195
+ return torch.overrides.handle_torch_function(
196
+ _make_dual, (tensor, tangent), tensor, tangent, level=level
197
+ )
198
+
199
+ return _make_dual_impl(tensor, tangent, level=level)
200
+
201
+
202
+ def _unpack_dual(
203
+ tensor: torch.Tensor, *, level: int = 0
204
+ ) -> tuple[torch.Tensor, torch.Tensor]:
205
+ """
206
+ Thin wrapper around torch._VF._unpack_dual that is used to proxy in
207
+ PT2 export/compile fx graph for forward-mode AD.
208
+ """
209
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
210
+
211
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
212
+
213
+ if mode:
214
+ return torch.overrides.handle_torch_function(
215
+ _unpack_dual, (tensor,), tensor, level=level
216
+ )
217
+
218
+ return _unpack_dual_impl(tensor, level=level)
219
+
220
+
221
+ def _jvp_increment_nesting() -> int:
222
+ """
223
+ Thin wrapper around torch._C._functorch._jvp_increment_nesting that is
224
+ used to proxy in export/compile graph for forward-mode AD.
225
+ """
226
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
227
+
228
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
229
+
230
+ if mode:
231
+ return torch.overrides.handle_torch_function(
232
+ _jvp_increment_nesting,
233
+ (),
234
+ )
235
+ return _jvp_increment_nesting_impl()
236
+
237
+
238
+ def _jvp_decrement_nesting() -> int:
239
+ """
240
+ Thin wrapper around torch._C._functorch._jvp_decrement_nesting that is
241
+ used to proxy in export/compile graph for forward-mode AD.
242
+ """
243
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
244
+
245
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
246
+
247
+ if mode:
248
+ return torch.overrides.handle_torch_function(
249
+ _jvp_decrement_nesting,
250
+ (),
251
+ )
252
+ return _jvp_decrement_nesting_impl()
253
+
254
+
255
+ def _unwrap_for_grad(tensor: torch.Tensor, level: int) -> torch.Tensor:
256
+ """
257
+ Thin wrapper around torch._C._functorch._unwrap_for_grad that is used
258
+ to proxy in PT2 export/compile fx graph for functorch transforms (grad, vjp, jvp).
259
+ """
260
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
261
+
262
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
263
+
264
+ if mode:
265
+ return torch.overrides.handle_torch_function(
266
+ _unwrap_for_grad, (tensor,), tensor, level
267
+ )
268
+
269
+ return _unwrap_for_grad_impl(tensor, level)
270
+
271
+
272
+ def _enter_dual_level() -> int:
273
+ """
274
+ Thin wrapper around torch._C._enter_dual_level that is used to proxy in
275
+ PT2 export/compile fx graph for forward-mode AD.
276
+ """
277
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
278
+
279
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
280
+
281
+ if mode:
282
+ return torch.overrides.handle_torch_function(_enter_dual_level, ())
283
+ return _enter_dual_level_impl()
284
+
285
+
286
+ def _exit_dual_level(*, level: int) -> None:
287
+ """
288
+ Thin wrapper around torch._C._exit_dual_level that is used to proxy in
289
+ PT2 export/compile fx graph for forward-mode AD.
290
+ """
291
+ from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
292
+
293
+ mode = _maybe_find_pre_dispatch_tf_mode_for_export()
294
+
295
+ if mode:
296
+ return torch.overrides.handle_torch_function(_exit_dual_level, (), level=level)
297
+ return _exit_dual_level_impl(level=level)
.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ from abc import ABC, abstractmethod
5
+ from functools import cached_property
6
+ from typing import Any, TYPE_CHECKING
7
+
8
+ import torch
9
+ import torch.utils._pytree as pytree
10
+ from torch._C._functorch import (
11
+ CFunctionalizeInterpreterPtr,
12
+ CGradInterpreterPtr,
13
+ CInterpreter,
14
+ CJvpInterpreterPtr,
15
+ CVmapInterpreterPtr,
16
+ pop_dynamic_layer_stack,
17
+ push_dynamic_layer_stack,
18
+ RandomnessType,
19
+ TransformType,
20
+ )
21
+ from torch.autograd.forward_ad import _set_fwd_grad_enabled
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Generator
26
+
27
+
28
+ """
29
+ This file contains the functorch integration with PyDispatcher.
30
+
31
+ PyDispatcher does not understand functorch's DynamicLayerStack dispatching
32
+ logic because it is entirely implemented in C++ in the fallbacks for two
33
+ dispatch keys, FuncTorchDynamicLayer{Front, Back}Mode (PyDispatcher is unable
34
+ to directly reuse C++ boxed fallbacks).
35
+
36
+ Instead of trying to hammer PyDispatcher into understanding those fallbacks,
37
+ we re-implement the logic of peeking the top of the stack for an interpreter,
38
+ selecting the interpreter to dispatch on, etc, in Python. This leads to a
39
+ simpler design.
40
+
41
+ The main difference between C++ functorch and PyDispatcher's functorch logic
42
+ is that:
43
+ - C++ functorch needs to manually tweak dispatch keys to ping-pong between
44
+ DynamicLayerFrontMode and DynamicLayerBackMode.
45
+ - PyDispatcher's functorch logic pops an Interpreter from the top of the stack
46
+ and asks it to execute the rule associated with the Interpreter.
47
+
48
+ In C++ we do the ping-pong because e.g. vmap rules are associated with the
49
+ batched DispatchKey, but in PyDispatcher we are able to avoid this by asking
50
+ the user to register a batching rule directly to a transform that an
51
+ interpreter then invokes.
52
+ """
53
+
54
+
55
+ # FuncTorchInterpreter is the Python version of Interpreter (recall that
56
+ # the DynamicLayerStack is a stack of interpreters).
57
+ # It is a wrapper around the actual C++ Interpreter object.
58
+ #
59
+ # Keep the methods in sync with aten/src/ATen/functorch/Interpreter.h
60
+ class FuncTorchInterpreter(ABC):
61
+ def __init__(self, cptr: Any) -> None:
62
+ self._cptr = cptr
63
+
64
+ # Process an operation. eg for vmap, this is invoking a batching rule.
65
+ # Conceptually this is analogous to Interpreter::process in C++
66
+ @abstractmethod
67
+ def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
68
+ pass
69
+
70
+ # lower an operation from this Interpreter to the next Interpreter on the stack.
71
+ # Concretely, this involves temporarily popping the current Interpreter.
72
+ # Conceptually this is analogous to Interpreter::sendToNextInterpreter in C++
73
+ def lower(self) -> contextlib.AbstractContextManager[Any]:
74
+ return temporarily_pop_interpreter_stack()
75
+
76
+ def level(self) -> int:
77
+ return self._cptr.level()
78
+
79
+ def key(self) -> TransformType:
80
+ return self._cptr.key()
81
+
82
+ def get_state(self) -> tuple[Any, ...]:
83
+ raise NotImplementedError
84
+
85
+ def check_state(self, state: tuple[Any, ...]) -> bool:
86
+ return state == self.get_state()
87
+
88
+ def __getstate__(self) -> dict[str, Any]:
89
+ state = self.__dict__.copy()
90
+ state.pop("_cptr", None)
91
+ return state
92
+
93
+
94
+ @contextlib.contextmanager
95
+ def temporarily_pop_interpreter_stack() -> Generator[None, None, None]:
96
+ try:
97
+ saved = pop_dynamic_layer_stack()
98
+ yield
99
+ finally:
100
+ push_dynamic_layer_stack(saved)
101
+
102
+
103
+ @contextlib.contextmanager
104
+ def temporarily_clear_interpreter_stack() -> Generator[list[Any], None, None]:
105
+ stack: list[Any] = []
106
+ try:
107
+ while torch._C._functorch.peek_interpreter_stack() is not None:
108
+ stack.append(pop_dynamic_layer_stack())
109
+ yield list(stack)
110
+ finally:
111
+ while stack:
112
+ push_dynamic_layer_stack(stack.pop())
113
+
114
+
115
+ @contextlib.contextmanager
116
+ def temporarily_restore_interpreter_stack(
117
+ stack: list[Any] | None,
118
+ ) -> Generator[None, None, None]:
119
+ pushed: list[Any] = []
120
+ if stack is None:
121
+ return
122
+ try:
123
+ for s in reversed(stack):
124
+ push_dynamic_layer_stack(s)
125
+ pushed.append(s)
126
+ yield
127
+ finally:
128
+ for _ in reversed(pushed):
129
+ # TODO: would be nice to assert that the layers are the same, but
130
+ # Python object identity is not preserved
131
+ pop_dynamic_layer_stack()
132
+
133
+
134
+ class VmapInterpreter(FuncTorchInterpreter):
135
+ def __init__(self, cdata: CInterpreter) -> None:
136
+ if cdata.key() != TransformType.Vmap:
137
+ raise AssertionError(f"expected TransformType.Vmap, got {cdata.key()}")
138
+ # NOTE: [Interpreter cdata vs cptr]
139
+ # cdata is a generic CInterpreter. We wrap it in a CVmapInterpreterPtr
140
+ # so that we can access methods specific to the vmap interpreter
141
+ self._cdata = cdata
142
+
143
+ @cached_property
144
+ # pyrefly: ignore [bad-override]
145
+ def _cptr(self) -> CVmapInterpreterPtr:
146
+ return CVmapInterpreterPtr(self._cdata)
147
+
148
+ def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
149
+ kernel = op.functorch_table[TransformType.Vmap]
150
+ return kernel(self, *args, **kwargs)
151
+
152
+ def batch_size(self) -> int:
153
+ return self._cptr.batchSize()
154
+
155
+ def randomness(self) -> str:
156
+ typ = self._cptr.randomness()
157
+ if typ == RandomnessType.Error:
158
+ return "error"
159
+ elif typ == RandomnessType.Same:
160
+ return "same"
161
+ elif typ == RandomnessType.Different:
162
+ return "different"
163
+ raise RuntimeError(f"Unknown RandomnessType: {typ}")
164
+
165
+ def get_state(self) -> tuple[Any, ...]:
166
+ return (self.key().name, self.level(), self.randomness())
167
+
168
+
169
+ @contextlib.contextmanager
170
+ def nested(
171
+ *contexts: contextlib.AbstractContextManager[Any],
172
+ ) -> Generator[tuple[contextlib.AbstractContextManager[Any], ...], None, None]:
173
+ with contextlib.ExitStack() as stack:
174
+ for ctx in contexts:
175
+ stack.enter_context(ctx)
176
+ yield contexts
177
+
178
+
179
+ class GradInterpreter(FuncTorchInterpreter):
180
+ def __init__(self, cdata: CInterpreter) -> None:
181
+ if cdata.key() != TransformType.Grad:
182
+ raise AssertionError(f"expected TransformType.Grad, got {cdata.key()}")
183
+ # See NOTE: [Interpreter cdata vs cptr]
184
+ self._cdata = cdata
185
+
186
+ @cached_property
187
+ # pyrefly: ignore [bad-override]
188
+ def _cptr(self) -> CGradInterpreterPtr:
189
+ return CGradInterpreterPtr(self._cdata)
190
+
191
+ def lift(
192
+ self, args: tuple[Any, ...], kwargs: dict[str, Any]
193
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
194
+ args, kwargs = pytree.tree_map_only(
195
+ torch.Tensor, self._cptr.lift, [args, kwargs]
196
+ )
197
+ return args, kwargs
198
+
199
+ def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
200
+ kernel = op.functorch_table[TransformType.Grad]
201
+ args, kwargs = self.lift(args, kwargs)
202
+ return kernel(self, *args, **kwargs)
203
+
204
+ # GradInterpreter has custom lower because of the no_grad interaction
205
+ # See NOTE [grad and vjp interaction with no_grad]
206
+ # This logic is mirrored from C++ GradInterpreterPtr::sendToNextInterpreter
207
+ def lower(self) -> contextlib.AbstractContextManager[Any]:
208
+ prev_grad_mode = self.prev_grad_mode()
209
+ if not prev_grad_mode:
210
+ return nested(torch.no_grad(), super().lower())
211
+ return super().lower()
212
+
213
+ def prev_grad_mode(self) -> bool:
214
+ return self._cptr.prevGradMode()
215
+
216
+ def get_state(self) -> tuple[Any, ...]:
217
+ return (self.key().name, self.level(), self.prev_grad_mode())
218
+
219
+
220
+ class JvpInterpreter(FuncTorchInterpreter):
221
+ def __init__(self, cdata: CInterpreter) -> None:
222
+ if cdata.key() != TransformType.Jvp:
223
+ raise AssertionError(f"expected TransformType.Jvp, got {cdata.key()}")
224
+ # See NOTE: [Interpreter cdata vs cptr]
225
+ self._cdata = cdata
226
+
227
+ @cached_property
228
+ # pyrefly: ignore [bad-override]
229
+ def _cptr(self) -> CJvpInterpreterPtr:
230
+ return CJvpInterpreterPtr(self._cdata)
231
+
232
+ def lift(
233
+ self, args: tuple[Any, ...], kwargs: dict[str, Any]
234
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
235
+ args, kwargs = pytree.tree_map_only(
236
+ torch.Tensor, self._cptr.lift, [args, kwargs]
237
+ )
238
+ return args, kwargs
239
+
240
+ def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
241
+ kernel = op.functorch_table[TransformType.Jvp]
242
+ args, kwargs = self.lift(args, kwargs)
243
+ return kernel(self, *args, **kwargs)
244
+
245
+ # Jvp has custom lower because of the no_fwd_grad interaction
246
+ # See NOTE [grad and vjp interaction with no_grad] for related info.
247
+ # This logic is mirrored from C++ JvpInterpreterPtr::sendToNextInterpreter
248
+ def lower(self) -> contextlib.AbstractContextManager[Any]:
249
+ prev_fwd_grad_mode = self.prev_fwd_grad_mode()
250
+ if not prev_fwd_grad_mode:
251
+ return nested(_set_fwd_grad_enabled(False), super().lower())
252
+ return super().lower()
253
+
254
+ def prev_fwd_grad_mode(self) -> bool:
255
+ return self._cptr.prevFwdGradMode()
256
+
257
+ def get_state(self) -> tuple[Any, ...]:
258
+ return (self.key().name, self.level(), self.prev_fwd_grad_mode())
259
+
260
+
261
+ class FunctionalizeInterpreter(FuncTorchInterpreter):
262
+ def __init__(self, cdata: CInterpreter) -> None:
263
+ if cdata.key() != TransformType.Functionalize:
264
+ raise AssertionError(
265
+ f"expected TransformType.Functionalize, got {cdata.key()}"
266
+ )
267
+ self._cdata = cdata
268
+
269
+ @cached_property
270
+ # pyrefly: ignore [bad-override]
271
+ def _cptr(self) -> CFunctionalizeInterpreterPtr:
272
+ return CFunctionalizeInterpreterPtr(self._cdata)
273
+
274
+ def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
275
+ kernel = op.functorch_table[TransformType.Functionalize]
276
+ return kernel(self, *args, **kwargs)
277
+
278
+ def functionalize_add_back_views(self) -> bool:
279
+ return self._cptr.functionalizeAddBackViews()
280
+
281
+ def get_state(self) -> tuple[Any, ...]:
282
+ return (self.key().name, self.level())
283
+
284
+
285
+ def coerce_cinterpreter(cinterpreter: CInterpreter) -> FuncTorchInterpreter:
286
+ key = cinterpreter.key()
287
+ if key == TransformType.Grad:
288
+ return GradInterpreter(cinterpreter)
289
+ if key == TransformType.Vmap:
290
+ return VmapInterpreter(cinterpreter)
291
+ if key == TransformType.Jvp:
292
+ return JvpInterpreter(cinterpreter)
293
+ if key == TransformType.Functionalize:
294
+ return FunctionalizeInterpreter(cinterpreter)
295
+ raise RuntimeError(f"NYI: PyDispatcher has not implemented support for {key}")
296
+
297
+
298
+ def retrieve_current_functorch_interpreter() -> FuncTorchInterpreter:
299
+ interpreter = torch._C._functorch.peek_interpreter_stack()
300
+ if interpreter is None:
301
+ raise AssertionError("interpreter must not be None")
302
+ return coerce_cinterpreter(interpreter)
303
+
304
+
305
+ def retrieve_all_functorch_interpreters() -> list[FuncTorchInterpreter]:
306
+ cis = torch._C._functorch.get_interpreter_stack()
307
+ if cis is None:
308
+ return []
309
+ return [coerce_cinterpreter(ci) for ci in cis]
310
+
311
+
312
+ def compare_functorch_state(states: list[tuple[Any, ...]]) -> bool:
313
+ # There are four possible cases covered here:
314
+ # 1. Current stack empty AND stack when generated not empty -> Invalidate
315
+ # 2. Current stack not empty AND stack when generated empty -> Invalidate
316
+ # 3. Current stack and generated stack empty -> Valid FX graph
317
+ # 4. Current stack and generated stack not empty -> Valid if both states match
318
+ peek = torch._C._functorch.peek_interpreter_stack()
319
+ if (peek is None and len(states) != 0) or (peek is not None and len(states) == 0):
320
+ return False
321
+
322
+ cis = retrieve_all_functorch_interpreters()
323
+ return len(cis) == len(states) and all(
324
+ ci.check_state(state) for ci, state in zip(cis, states)
325
+ )
326
+
327
+
328
+ def dispatch_functorch(op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
329
+ interpreter = retrieve_current_functorch_interpreter()
330
+ # In traditional PyTorch operators, DispatchKey::FuncTorchTensorWrapper's
331
+ # unwrap_dead_tensors fallback handles unwrapping dead tensor wrappers.
332
+ # PyDispatcher sidesteps the PyTorch dispatcher when dealing with functorch
333
+ # transforms, so we manually unwrap the dead tensors here.
334
+ # This logic won't need to exist when we have mode-only functorch.
335
+ args, kwargs = pytree.tree_map_only(
336
+ torch.Tensor, torch._C._functorch.unwrap_if_dead, (args, kwargs)
337
+ )
338
+ return interpreter.process(op, args, kwargs)
.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ __all__ = ["make_fx", "dispatch_trace", "PythonKeyTracer", "pythonkey_decompose"]
7
+ from torch.fx.experimental.proxy_tensor import (
8
+ decompose,
9
+ dispatch_trace,
10
+ make_fx,
11
+ PythonKeyTracer,
12
+ )
13
+
14
+
15
+ pythonkey_decompose = decompose
.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+
9
+ # TODO: remove this file when the migration of the pytree utility is done
10
+ from torch.utils._pytree import tree_map_, treespec_pprint
11
+
12
+
13
+ __all__ = ["tree_map_", "treespec_pprint"]
14
+
15
+
16
+ with warnings.catch_warnings():
17
+ warnings.simplefilter("always")
18
+ warnings.warn(
19
+ "`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. "
20
+ "Please `use torch.utils._pytree` instead.",
21
+ DeprecationWarning,
22
+ stacklevel=2,
23
+ )
.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ """
5
+ From https://docs.google.com/spreadsheets/d/12R3nCOLskxPYjjiNkdqy4OdQ65eQp_htebXGODsjSeA/edit#gid=0
6
+ Try to keep this list in sync with that.
7
+ """
8
+
9
+ import operator
10
+
11
+
12
+ top_torch: list[tuple[str, int]] = [
13
+ ("t", 6837449),
14
+ ("tensor", 585786),
15
+ ("mode", 462182),
16
+ ("cat", 394818),
17
+ ("max", 368038),
18
+ ("zeros", 329495),
19
+ ("load", 327756),
20
+ ("no_grad", 294694),
21
+ ("save", 265130),
22
+ ("from_numpy", 243063),
23
+ ("manual_seed", 165044),
24
+ ("ones", 153696),
25
+ ("randn", 150796),
26
+ ("stack", 133358),
27
+ ("sum", 130772),
28
+ ("arange", 98087),
29
+ ("rand", 94715),
30
+ ("mean", 88546),
31
+ ("exp", 73883),
32
+ ("zeros_like", 72831),
33
+ ("min", 72248),
34
+ ("sigmoid", 66798),
35
+ ("log", 62135),
36
+ ("matmul", 47811),
37
+ ("clamp", 45304),
38
+ ("sqrt", 44911),
39
+ ("abs", 43535),
40
+ ("tanh", 42793),
41
+ ("empty", 40311),
42
+ ("argmax", 38435),
43
+ ("bmm", 33984),
44
+ ("pow", 33571),
45
+ ("norm", 31125),
46
+ ("mm", 30995),
47
+ ("is_tensor", 29546),
48
+ ("ones_like", 29512),
49
+ ("nonzero", 28681),
50
+ ("full", 28373),
51
+ ("unsqueeze", 27911),
52
+ ("where", 26585),
53
+ ("randperm", 26450),
54
+ ("eye", 24342),
55
+ ("mul", 23236),
56
+ ("topk", 22537),
57
+ ("as_tensor", 21967),
58
+ ("sort", 21412),
59
+ ("squeeze", 20863),
60
+ ("randint", 20771),
61
+ ("linspace", 20041),
62
+ ("add", 19201),
63
+ ("transpose", 18663),
64
+ ("split", 18325),
65
+ ("gather", 17904),
66
+ ("set_grad_enabled", 16013),
67
+ ("sin", 15669),
68
+ ("cos", 15562),
69
+ ("div", 15513),
70
+ ("index_select", 14866),
71
+ ("multinomial", 14331),
72
+ ("flatten", 14267),
73
+ ("isnan", 14170),
74
+ ("randn_like", 13096),
75
+ ("eq", 12680),
76
+ ("einsum", 12480),
77
+ ("round", 12367),
78
+ ("floor", 11628),
79
+ ("allclose", 11000),
80
+ ("reshape", 10605),
81
+ ("diag", 10167),
82
+ ("chunk", 9581),
83
+ ("std", 9379),
84
+ ("set_default_tensor_type", 9281),
85
+ ("triu", 8559),
86
+ ("meshgrid", 8292),
87
+ ("set_num_threads", 8126),
88
+ ("unique", 7964),
89
+ ("full_like", 7780),
90
+ ("tril", 7538),
91
+ ("dot", 7275),
92
+ ("sign", 6943),
93
+ ("equal", 6916),
94
+ ("normal", 6750),
95
+ ("cumsum", 6556),
96
+ ("dist", 6058),
97
+ ("isfinite", 6030),
98
+ ("gt", 5935),
99
+ ("set_printoptions", 5888),
100
+ ("range", 5491),
101
+ ("empty_like", 5351),
102
+ ("flip", 5342),
103
+ ("masked_select", 5341),
104
+ ("bernoulli", 5262),
105
+ ("atan", 5253),
106
+ ("var", 5247),
107
+ ("prod", 5200),
108
+ ("erf", 5088),
109
+ ("inverse", 5072),
110
+ ("addmm", 4854),
111
+ ("logsumexp", 4582),
112
+ ("fft", 4436),
113
+ ("lt", 4421),
114
+ ("log2", 4316),
115
+ ("enable_grad", 4238),
116
+ ("rand_like", 4187),
117
+ ("argsort", 3972),
118
+ ("seed", 3932),
119
+ ("mv", 3547),
120
+ ("ger", 3309),
121
+ ("ge", 3248),
122
+ ("atan2", 3210),
123
+ ("ceil", 3202),
124
+ ("ne", 3075),
125
+ ("bincount", 3063),
126
+ ("acos", 3055),
127
+ ("rsqrt", 3031),
128
+ ("svd", 3029),
129
+ ("numel", 3003),
130
+ ("log1p", 2840),
131
+ ("unbind", 2808),
132
+ ("le", 2714),
133
+ ("isinf", 2707),
134
+ ("cross", 2646),
135
+ ("set_default_dtype", 2536),
136
+ ("argmin", 2535),
137
+ ("sparse_coo_tensor", 2489),
138
+ ("log10", 2304),
139
+ ("kthvalue", 2192),
140
+ ("set_rng_state", 2158),
141
+ ("get_rng_state", 1996),
142
+ ("get_default_dtype", 1879),
143
+ ("det", 1868),
144
+ ("qr", 1864),
145
+ ("histc", 1852),
146
+ ("symeig", 1832),
147
+ ("trace", 1801),
148
+ ("median", 1795),
149
+ ("addcmul", 1751),
150
+ ("remainder", 1717),
151
+ ("baddbmm", 1693),
152
+ ("lgamma", 1665),
153
+ ("repeat_interleave", 1598),
154
+ ("fmod", 1576),
155
+ ("reciprocal", 1575),
156
+ ("tan", 1560),
157
+ ("initial_seed", 1532),
158
+ ("take", 1529),
159
+ ("stft", 1487),
160
+ ("get_num_threads", 1477),
161
+ ("real", 1459),
162
+ ("quantize_per_tensor", 1392),
163
+ ("diag_embed", 1364),
164
+ ("lerp", 1363),
165
+ ("asin", 1345),
166
+ ("eig", 1333),
167
+ ("trunc", 1290),
168
+ ("diagonal", 1287),
169
+ ("cosh", 1279),
170
+ ("rfft", 1269),
171
+ ("cumprod", 1260),
172
+ ("addr", 1211),
173
+ ("roll", 1198),
174
+ ("narrow", 1188),
175
+ ("digamma", 1172),
176
+ ("square", 1163),
177
+ ("sinh", 1131),
178
+ ("logspace", 1084),
179
+ ("broadcast_tensors", 1070),
180
+ ("irfft", 1013),
181
+ ("frac", 997),
182
+ ("hann_window", 994),
183
+ ("solve", 989),
184
+ ("logdet", 977),
185
+ ("expm1", 968),
186
+ ("cdist", 946),
187
+ ("addmv", 903),
188
+ ("randint_like", 888),
189
+ ("tensordot", 888),
190
+ ("ifft", 877),
191
+ ("true_divide", 854),
192
+ ("erfinv", 830),
193
+ ("addcdiv", 819),
194
+ ("addbmm", 813),
195
+ ("renorm", 781),
196
+ ("pinverse", 753),
197
+ ("isclose", 740),
198
+ ("erfc", 729),
199
+ ("is_storage", 725),
200
+ ("triangular_solve", 723),
201
+ ("rot90", 709),
202
+ ("logical_not", 686),
203
+ ("geqrf", 681),
204
+ ("slogdet", 677),
205
+ ("lu", 665),
206
+ ("hamming_window", 659),
207
+ ("orgqr", 651),
208
+ ("ormqr", 622),
209
+ ("is_floating_point", 602),
210
+ ("diagflat", 562),
211
+ ("cholesky_solve", 559),
212
+ ("tril_indices", 552),
213
+ ("chain_matmul", 551),
214
+ ("triu_indices", 548),
215
+ ("angle", 522),
216
+ ("poisson", 505),
217
+ ("matrix_power", 485),
218
+ ("unique_consecutive", 471),
219
+ ("quantize_per_channel", 465),
220
+ ("std_mean", 458),
221
+ ("bartlett_window", 447),
222
+ ("var_mean", 428),
223
+ ("lstsq", 421),
224
+ ("logical_and", 419),
225
+ ("mvlgamma", 411),
226
+ ("blackman_window", 400),
227
+ ("bitwise_not", 395),
228
+ ("cholesky_inverse", 388),
229
+ ("as_strided", 384),
230
+ ("floor_divide", 353),
231
+ ("cartesian_prod", 321),
232
+ ("lu_solve", 317),
233
+ ("set_flush_denormal", 310),
234
+ ("empty_strided", 283),
235
+ ("logical_xor", 282),
236
+ ("polygamma", 282),
237
+ ("logical_or", 280),
238
+ ("set_num_interop_threads", 278),
239
+ ("combinations", 274),
240
+ ("trapz", 270),
241
+ ("matrix_rank", 260),
242
+ ("lu_unpack", 255),
243
+ ("result_type", 244),
244
+ ("conj", 231),
245
+ ("cummax", 230),
246
+ ("lobpcg", 229),
247
+ ("bitwise_xor", 217),
248
+ ("promote_types", 213),
249
+ ("get_num_interop_threads", 211),
250
+ ("cummin", 205),
251
+ ("bitwise_and", 198),
252
+ ("dequantize", 192),
253
+ ("bitwise_or", 191),
254
+ ("imag", 191),
255
+ ("can_cast", 184),
256
+ ("istft", 180),
257
+ ("compiled_with_cxx11_abi", 159),
258
+ ("is_complex", 151),
259
+ ("block_diag", 136),
260
+ ("pca_lowrank", 124),
261
+ ("absolute", 122),
262
+ ("svd_lowrank", 108),
263
+ ("neg", 2),
264
+ ]
265
+
266
+ top_nn_functional: list[tuple[str, int]] = [
267
+ ("nn.functional.softmax", 10522),
268
+ ("nn.functional.relu", 8572),
269
+ ("nn.functional.interpolate", 7277),
270
+ ("nn.functional.pad", 5207),
271
+ ("nn.functional.log_softmax", 4699),
272
+ ("nn.functional.normalize", 2338),
273
+ ("nn.functional.cross_entropy", 2083),
274
+ ("nn.functional.grid_sample", 1970),
275
+ ("nn.functional.one_hot", 1967),
276
+ ("nn.functional.mse_loss", 1920),
277
+ ("nn.functional.conv2d", 1593),
278
+ ("nn.functional.dropout", 1516),
279
+ ("nn.functional.softplus", 1385),
280
+ ("nn.functional.sigmoid", 1128),
281
+ ("nn.functional.linear", 1036),
282
+ ("nn.functional.gelu", 930),
283
+ ("nn.functional.avg_pool2d", 899),
284
+ ("nn.functional.max_pool2d", 876),
285
+ ("nn.functional.nll_loss", 863),
286
+ ("nn.functional.embedding", 737),
287
+ ("nn.functional.tanh", 664),
288
+ ("nn.functional.leaky_relu", 640),
289
+ ("nn.functional.adaptive_avg_pool2d", 633),
290
+ ("nn.functional.cosine_similarity", 627),
291
+ ("nn.functional.unfold", 609),
292
+ ("nn.functional.conv1d", 596),
293
+ ("nn.functional.binary_cross_entropy_with_logits", 591),
294
+ ("nn.functional.l1_loss", 571),
295
+ ("nn.functional.binary_cross_entropy", 492),
296
+ ("nn.functional.elu", 416),
297
+ ("nn.functional.batch_norm", 413),
298
+ ("nn.functional.upsample", 413),
299
+ ("nn.functional.fold", 305),
300
+ ("nn.functional.affine_grid", 298),
301
+ ("nn.functional.max_pool1d", 297),
302
+ ("nn.functional.torch", 294),
303
+ ("nn.functional.threshold", 263),
304
+ ("nn.functional.smooth_l1_loss", 262),
305
+ ("nn.functional.pairwise_distance", 253),
306
+ ("nn.functional.logsigmoid", 243),
307
+ ("nn.functional.adaptive_max_pool2d", 235),
308
+ ("nn.functional.relu6", 213),
309
+ ("nn.functional.pixel_shuffle", 209),
310
+ ("nn.functional.avg_pool3d", 203),
311
+ ("nn.functional.bilinear", 203),
312
+ ("nn.functional.conv_transpose2d", 201),
313
+ ("nn.functional.gumbel_softmax", 197),
314
+ ("nn.functional.max_unpool2d", 196),
315
+ ("nn.functional.kl_div", 191),
316
+ ("nn.functional.hardtanh", 189),
317
+ ("nn.functional.ctc_loss", 185),
318
+ ("nn.functional.layer_norm", 178),
319
+ ("nn.functional.conv3d", 172),
320
+ ("nn.functional.max_unpool3d", 167),
321
+ ("nn.functional.hardshrink", 165),
322
+ ("nn.functional.hardswish", 156),
323
+ ("nn.functional.selu", 156),
324
+ ("nn.functional.glu", 155),
325
+ ("nn.functional.assert_int_or_pair", 150),
326
+ ("nn.functional.hardsigmoid", 146),
327
+ ("nn.functional.upsample_bilinear", 146),
328
+ ("nn.functional.max_pool3d", 140),
329
+ ("nn.functional.adaptive_avg_pool3d", 139),
330
+ ("nn.functional.instance_norm", 124),
331
+ ("nn.functional.embedding_bag", 122),
332
+ ("nn.functional.upsample_nearest", 110),
333
+ ("nn.functional.avg_pool1d", 105),
334
+ ("nn.functional.prelu", 102),
335
+ ("nn.functional.celu", 92),
336
+ ("nn.functional.dropout2d", 86),
337
+ ("nn.functional.hinge_embedding_loss", 82),
338
+ ("nn.functional.softsign", 81),
339
+ ("nn.functional.max_unpool1d", 74),
340
+ ("nn.functional.silu", 74),
341
+ ("nn.functional.softshrink", 70),
342
+ ("nn.functional.leaky_relu_", 68),
343
+ ("nn.functional.softmin", 67),
344
+ ("nn.functional.channel_shuffle", 66),
345
+ ("nn.functional.multilabel_margin_loss", 66),
346
+ ("nn.functional.dropout3d", 65),
347
+ ("nn.functional.multi_margin_loss", 65),
348
+ ("nn.functional.lp_pool2d", 64),
349
+ ("nn.functional.conv_transpose1d", 62),
350
+ ("nn.functional.triplet_margin_loss", 62),
351
+ ("nn.functional.tanhshrink", 61),
352
+ ("nn.functional.adaptive_max_pool1d", 59),
353
+ ("nn.functional.cosine_embedding_loss", 58),
354
+ ("nn.functional.multi_head_attention_forward", 58),
355
+ ("nn.functional.max_pool1d_with_indices", 53),
356
+ ("nn.functional.poisson_nll_loss", 53),
357
+ ("nn.functional.margin_ranking_loss", 52),
358
+ ("nn.functional.soft_margin_loss", 52),
359
+ ("nn.functional.adaptive_max_pool3d", 51),
360
+ ("nn.functional.group_norm", 51),
361
+ ("nn.functional.local_response_norm", 51),
362
+ ("nn.functional.multilabel_soft_margin_loss", 51),
363
+ ("nn.functional.relu_", 50),
364
+ ("nn.functional.alpha_dropout", 49),
365
+ ("nn.functional.feature_alpha_dropout", 49),
366
+ ("nn.functional.lp_pool1d", 49),
367
+ ("nn.functional.adaptive_max_pool1d_with_indices", 48),
368
+ ("nn.functional.adaptive_max_pool2d_with_indices", 48),
369
+ ("nn.functional.adaptive_max_pool3d_with_indices", 48),
370
+ ("nn.functional.fractional_max_pool2d", 48),
371
+ ("nn.functional.fractional_max_pool2d_with_indices", 48),
372
+ ("nn.functional.fractional_max_pool3d", 48),
373
+ ("nn.functional.fractional_max_pool3d_with_indices", 48),
374
+ ("nn.functional.max_pool2d_with_indices", 48),
375
+ ("nn.functional.max_pool3d_with_indices", 48),
376
+ ("nn.functional.handle_torch_function", 47),
377
+ ("nn.functional.has_torch_function", 47),
378
+ ("nn.functional.adaptive_avg_pool1d", 43),
379
+ ("nn.functional.pdist", 43),
380
+ ("nn.functional.rrelu_", 37),
381
+ ("nn.functional.elu_", 34),
382
+ ("nn.functional.boolean_dispatch", 33),
383
+ ("nn.functional.hardtanh_", 26),
384
+ ("nn.functional.triplet_margin_with_distance_loss", 23),
385
+ ("nn.functional.selu_", 20),
386
+ ("nn.functional.pixel_unshuffle", 19),
387
+ ("nn.functional.conv_transpose3d", 18),
388
+ ("nn.functional.gaussian_nll_loss", 15),
389
+ ("nn.functional.has_torch_function_unary", 15),
390
+ ("nn.functional.has_torch_function_variadic", 15),
391
+ ("nn.functional.celu_", 13),
392
+ ("nn.functional.huber_loss", 7),
393
+ ("nn.functional.mish", 4),
394
+ ("nn.functional.threshold_", 3),
395
+ ("nn.functional.grad", 2),
396
+ ("nn.functional.conv_tbc", 1),
397
+ ("nn.functional.math", 1),
398
+ ]
399
+
400
+ top_nn_module: list[tuple[str, int, str | None]] = [
401
+ ("nn.Module", 927129, None),
402
+ ("nn.Linear", 530688, "nn.functional.linear"),
403
+ ("nn.Sequential", 384968, None),
404
+ ("nn.Conv2d", 383320, "nn.functional.conv2d"),
405
+ ("nn.ReLU", 318877, "nn.functional.relu"),
406
+ ("nn.BatchNorm2d", 233265, "nn.functional.batch_norm"),
407
+ ("nn.Dropout", 179268, "nn.functional.dropout"),
408
+ ("nn.ModuleList", 171225, None),
409
+ ("nn.Parameter", 153291, None),
410
+ ("nn.CrossEntropyLoss", 152696, "nn.functional.cross_entropy"),
411
+ ("nn.MaxPool2d", 138619, "nn.functional.max_pool2d"),
412
+ ("nn.Embedding", 111844, "nn.functional.embedding"),
413
+ ("nn.DataParallel", 104238, None),
414
+ ("nn.MSELoss", 82954, "nn.functional.mse_loss"),
415
+ ("nn.Sigmoid", 75810, "nn.functional.sigmoid"),
416
+ ("nn.LeakyReLU", 65632, "nn.functional.leaky_relu"),
417
+ ("nn.BatchNorm1d", 65374, "nn.functional.batch_norm"),
418
+ ("nn.Softmax", 65114, "nn.functional.softmax"),
419
+ ("nn.Tanh", 59445, "nn.functional.tanh"),
420
+ ("nn.AdaptiveAvgPool2d", 59071, "nn.functional.adaptive_avg_pool2d"),
421
+ ("nn.AvgPool2d", 58377, "nn.functional.avg_pool2d"),
422
+ ("nn.ConvTranspose2d", 57524, "nn.functional.conv_transpose2d"),
423
+ ("nn.LSTM", 57411, None),
424
+ ("nn.Conv1d", 41108, "nn.functional.conv1d"),
425
+ ("nn.LayerNorm", 36089, "nn.functional.layer_norm"),
426
+ ("nn.BCELoss", 34005, "nn.functional.binary_cross_entropy"),
427
+ ("nn.Upsample", 32527, "nn.functional.interpolate"),
428
+ ("nn.BCEWithLogitsLoss", 29944, "nn.functional.binary_cross_entropy_with_logits"),
429
+ ("nn.GRU", 25421, None),
430
+ ("nn.Dropout2d", 23512, "nn.functional.dropout2d"),
431
+ ("nn.LogSoftmax", 22897, "nn.functional.log_softmax"),
432
+ ("nn.L1Loss", 22778, "nn.functional.l1_loss"),
433
+ ("nn.GroupNorm", 22183, "nn.functional.group_norm"),
434
+ ("nn.NLLLoss", 21751, "nn.functional.nll_loss"),
435
+ ("nn.Conv3d", 20874, "nn.functional.conv3d"),
436
+ ("nn.Identity", 17911, None),
437
+ ("nn.InstanceNorm2d", 16426, "nn.functional.instance_norm"),
438
+ ("nn.BatchNorm3d", 16378, "nn.functional.batch_norm"),
439
+ ("nn.PReLU", 13472, "nn.functional.prelu"),
440
+ ("nn.ReLU6", 12622, "nn.functional.relu6"),
441
+ ("nn.ELU", 12508, "nn.functional.elu"),
442
+ ("nn.LSTMCell", 10885, None),
443
+ ("nn.Flatten", 10384, "torch.flatten"),
444
+ ("nn.ModuleDict", 10255, None),
445
+ ("nn.ReflectionPad2d", 9954, "nn.functional.pad"),
446
+ ("nn.MaxPool3d", 9526, "nn.functional.max_pool3d"),
447
+ ("nn.MaxPool1d", 9154, "nn.functional.max_pool1d"),
448
+ ("nn.RNN", 9154, None),
449
+ ("nn.ZeroPad2d", 8847, "nn.functional.pad"),
450
+ ("nn.ParameterList", 7702, None),
451
+ ("nn.SyncBatchNorm", 6814, None),
452
+ ("nn.PixelShuffle", 6571, "nn.functional.pixel_shuffle"),
453
+ ("nn.SmoothL1Loss", 6517, "nn.functional.smooth_l1_loss"),
454
+ ("nn.Hardswish", 6458, "nn.functional.hardswish"),
455
+ ("nn.AdaptiveMaxPool2d", 6071, "nn.functional.adaptive_max_pool2d"),
456
+ ("nn.SELU", 6043, "nn.functional.selu"),
457
+ ("nn.ConvTranspose3d", 6039, "nn.functional.conv_transpose3d"),
458
+ ("nn.GRUCell", 5840, None),
459
+ ("nn.ReplicationPad2d", 5600, "nn.functional.pad"),
460
+ ("nn.KLDivLoss", 5541, "nn.functional.kl_div"),
461
+ ("nn.ConvTranspose1d", 5183, "nn.functional.conv_transpose1d"),
462
+ ("nn.Softplus", 5120, "nn.functional.softplus"),
463
+ ("nn.SiLU", 4895, "nn.functional.silu"),
464
+ ("nn.AvgPool3d", 4523, "nn.functional.avg_pool3d"),
465
+ ("nn.CosineSimilarity", 4058, "nn.functional.cosine_similarity"),
466
+ ("nn.GELU", 3932, "nn.functional.gelu"),
467
+ ("nn.UpsamplingBilinear2d", 3673, "nn.functional.interpolate"),
468
+ ("nn.InstanceNorm1d", 3658, "nn.functional.instance_norm"),
469
+ ("nn.Transformer", 3604, None),
470
+ ("nn.MultiheadAttention", 3435, "nn.functional.multi_head_attention_forward"),
471
+ ("nn.AvgPool1d", 3195, "nn.functional.avg_pool1d"),
472
+ ("nn.Dropout3d", 2964, "nn.functional.dropout3d"),
473
+ ("nn.AdaptiveAvgPool3d", 2915, "nn.functional.adaptive_avg_pool3d"),
474
+ ("nn.InstanceNorm3d", 2893, "nn.functional.instance_norm"),
475
+ ("nn.Hardtanh", 2613, "nn.functional.hardtanh"),
476
+ ("nn.MarginRankingLoss", 2568, "nn.functional.margin_ranking_loss"),
477
+ ("nn.GLU", 2526, "nn.functional.glu"),
478
+ ("nn.AdaptiveAvgPool1d", 2481, "nn.functional.adaptive_avg_pool1d"),
479
+ ("nn.EmbeddingBag", 2344, "nn.functional.embedding_bag"),
480
+ ("nn.TransformerEncoderLayer", 2292, None),
481
+ ("nn.TransformerEncoder", 2091, None),
482
+ ("nn.MaxUnpool2d", 2031, "nn.functional.max_unpool2d"),
483
+ ("nn.UpsamplingNearest2d", 2004, "nn.functional.interpolate"),
484
+ ("nn.ConstantPad1d", 1904, "nn.functional.pad"),
485
+ ("nn.ConstantPad2d", 1791, "nn.functional.pad"),
486
+ ("nn.CTCLoss", 1789, "nn.functional.ctc_loss"),
487
+ ("nn.AdaptiveMaxPool1d", 1713, "nn.functional.adaptive_max_pool1d"),
488
+ ("nn.AdaptiveLogSoftmaxWithLoss", 1665, None),
489
+ ("nn.Bilinear", 1664, "nn.functional.bilinear"),
490
+ ("nn.RNNCell", 1653, None),
491
+ ("nn.MultiLabelSoftMarginLoss", 1624, "nn.functional.multilabel_soft_margin_loss"),
492
+ ("nn.Unfold", 1452, "nn.functional.unfold"),
493
+ ("nn.RReLU", 1431, "nn.functional.rrelu"),
494
+ ("nn.CosineEmbeddingLoss", 1357, "nn.functional.cosine_embedding_loss"),
495
+ ("nn.LocalResponseNorm", 1331, "nn.functional.local_response_norm"),
496
+ ("nn.Softmax2d", 1300, "nn.functional.softmax"),
497
+ ("nn.PairwiseDistance", 1241, "nn.functional.pairwise_distance"),
498
+ ("nn.LogSigmoid", 1235, "nn.functional.logsigmoid"),
499
+ ("nn.TripletMarginLoss", 1230, "nn.functional.triplet_margin_loss"),
500
+ ("nn.RNNBase", 1133, None),
501
+ ("nn.Threshold", 1043, "nn.functional.threshold"),
502
+ ("nn.AdaptiveMaxPool3d", 1025, "nn.functional.adaptive_max_pool3d"),
503
+ ("nn.CELU", 1018, "nn.functional.celu"),
504
+ ("nn.NLLLoss2d", 966, "nn.functional.nll_loss"),
505
+ ("nn.Softsign", 877, "nn.functional.softsign"),
506
+ ("nn.ReplicationPad1d", 862, "nn.functional.pad"),
507
+ ("nn.SoftMarginLoss", 856, "nn.functional.soft_margin_loss"),
508
+ ("nn.ParameterDict", 742, None),
509
+ ("nn.ReflectionPad1d", 731, "nn.functional.pad"),
510
+ ("nn.Softshrink", 713, "nn.functional.softshrink"),
511
+ ("nn.AlphaDropout", 710, "nn.functional.alpha_dropout"),
512
+ ("nn.Tanhshrink", 681, "nn.functional.tanhshrink"),
513
+ ("nn.PoissonNLLLoss", 676, "nn.functional.poisson_nll_loss"),
514
+ ("nn.MaxUnpool3d", 660, "nn.functional.max_unpool3d"),
515
+ ("nn.Fold", 630, "nn.functional.fold"),
516
+ ("nn.MultiMarginLoss", 622, "nn.functional.multi_margin_loss"),
517
+ ("nn.TransformerDecoderLayer", 614, None),
518
+ ("nn.TransformerDecoder", 607, None),
519
+ ("nn.Hardshrink", 592, "nn.functional.hardshrink"),
520
+ ("nn.ConstantPad3d", 582, "nn.functional.pad"),
521
+ ("nn.MultiLabelMarginLoss", 580, "nn.functional.multilabel_margin_loss"),
522
+ ("nn.LPPool2d", 550, "nn.functional.lp_pool2d"),
523
+ ("nn.Softmin", 537, "nn.functional.softmin"),
524
+ ("nn.MaxUnpool1d", 518, "nn.functional.max_unpool1d"),
525
+ ("nn.FractionalMaxPool2d", 484, "nn.functional.fractional_max_pool2d"),
526
+ ("nn.Hardsigmoid", 477, "nn.functional.hardsigmoid"),
527
+ ("nn.ReplicationPad3d", 470, "nn.functional.pad"),
528
+ ("nn.HingeEmbeddingLoss", 442, "nn.functional.hinge_embedding_loss"),
529
+ ("nn.LPPool1d", 386, "nn.functional.lp_pool1d"),
530
+ ("nn.FractionalMaxPool3d", 252, "nn.functional.fractional_max_pool3d"),
531
+ ("nn.Container", 217, None),
532
+ ("nn.Unflatten", 206, "nn.functional.unflatten"),
533
+ ("nn.FeatureAlphaDropout", 136, "nn.functional.feature_alpha_dropout"),
534
+ (
535
+ "nn.TripletMarginWithDistanceLoss",
536
+ 107,
537
+ "nn.functional.triplet_margin_with_distance_loss",
538
+ ),
539
+ ("nn.ChannelShuffle", 90, "nn.functional.channel_shuffle"),
540
+ ("nn.RNNCellBase", 88, None),
541
+ ("nn.LazyLinear", 81, "nn.functional.linear"),
542
+ ("nn.UninitializedParameter", 60, None),
543
+ ("nn.CrossMapLRN2d", 59, None),
544
+ ("nn.GaussianNLLLoss", 55, "nn.functional.gaussian_nll_loss"),
545
+ ("nn.PixelUnshuffle", 45, "nn.functional.pixel_unshuffle"),
546
+ ("nn.Mish", 31, "nn.functional.mish"),
547
+ ("nn.ReflectionPad3d", 22, "nn.functional.pad"),
548
+ ("nn.HuberLoss", 18, "nn.functional.huber_loss"),
549
+ ("nn.LazyConv2d", 15, None),
550
+ ("nn.LazyConv1d", 9, None),
551
+ ("nn.LazyConv3d", 8, None),
552
+ ("nn.LazyConvTranspose1d", 8, None),
553
+ ("nn.LazyConvTranspose2d", 8, None),
554
+ ("nn.LazyConvTranspose3d", 8, None),
555
+ ("nn.LazyBatchNorm1d", 3, None),
556
+ ("nn.LazyBatchNorm2d", 3, None),
557
+ ("nn.LazyBatchNorm3d", 3, None),
558
+ ("nn.UninitializedBuffer", 3, None),
559
+ ]
560
+
561
+ # No rankings because these are a little hard to get rankings for
562
+ method_only_ops: list[str] = [
563
+ "bfloat16",
564
+ "bool",
565
+ "byte",
566
+ "char",
567
+ "contiguous",
568
+ "cpu",
569
+ "cuda",
570
+ "detach",
571
+ "double",
572
+ "expand",
573
+ "expand_as",
574
+ "float",
575
+ "get_device",
576
+ "half",
577
+ "hardshrink",
578
+ "index_add",
579
+ "index_copy",
580
+ "index_fill",
581
+ "index_put",
582
+ "int",
583
+ "is_contiguous",
584
+ "is_pinned",
585
+ "is_set_to",
586
+ "is_shared",
587
+ "is_signed",
588
+ "item",
589
+ "long",
590
+ "masked_scatter",
591
+ "masked_fill",
592
+ "narrow_copy",
593
+ "numpy",
594
+ "pin_memory",
595
+ "repeat",
596
+ "reshape_as",
597
+ "select",
598
+ "short",
599
+ "storage_offset",
600
+ "sum_to_size",
601
+ "to",
602
+ "to_mkldnn",
603
+ "tolist",
604
+ "type",
605
+ "type_as",
606
+ "unfold",
607
+ "view",
608
+ "view_as",
609
+ ]
610
+
611
+
612
+ def get_nn_functional_top_list() -> list[tuple[str, int]]:
613
+ top_nn_functional_: dict[str, int] = dict(top_nn_functional)
614
+ for _, count, functional_name in top_nn_module:
615
+ if functional_name is None:
616
+ continue
617
+ if functional_name == "torch.flatten":
618
+ continue
619
+ if functional_name not in top_nn_functional_:
620
+ top_nn_functional_[functional_name] = count
621
+ else:
622
+ top_nn_functional_[functional_name] += count
623
+
624
+ top_nn_functional_list = list(top_nn_functional_.items())
625
+ top_nn_functional_list.sort(key=operator.itemgetter(1), reverse=True)
626
+ return top_nn_functional_list
627
+
628
+
629
+ usage_count: dict[str, int] = dict(get_nn_functional_top_list())
630
+ usage_count.update(top_torch)
.venv/lib/python3.12/site-packages/torch/_functorch/utils.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ from collections.abc import Generator
3
+
4
+ from torch._C._functorch import (
5
+ get_single_level_autograd_function_allowed,
6
+ set_single_level_autograd_function_allowed,
7
+ unwrap_dead_wrappers,
8
+ )
9
+ from torch.utils._exposed_in import exposed_in
10
+
11
+
12
+ __all__ = [
13
+ "exposed_in",
14
+ "argnums_t",
15
+ "enable_single_level_autograd_function",
16
+ "unwrap_dead_wrappers",
17
+ ]
18
+
19
+
20
+ @contextlib.contextmanager
21
+ def enable_single_level_autograd_function() -> Generator[None, None, None]:
22
+ try:
23
+ prev_state = get_single_level_autograd_function_allowed()
24
+ set_single_level_autograd_function_allowed(True)
25
+ yield
26
+ finally:
27
+ set_single_level_autograd_function_allowed(prev_state)
28
+
29
+
30
+ argnums_t = int | tuple[int, ...]
.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import functools
11
+ import itertools
12
+ from collections.abc import Callable # noqa: TC003
13
+ from functools import partial
14
+ from typing import Any, cast, NoReturn, TYPE_CHECKING
15
+ from typing_extensions import ParamSpec, TypeVar
16
+
17
+ import torch
18
+ from torch import Tensor
19
+ from torch._C._functorch import is_batchedtensor
20
+ from torch._functorch.predispatch import (
21
+ _add_batch_dim,
22
+ _remove_batch_dim,
23
+ _vmap_decrement_nesting,
24
+ _vmap_increment_nesting,
25
+ lazy_load_decompositions,
26
+ )
27
+ from torch.utils._pytree import (
28
+ _broadcast_to_and_flatten,
29
+ tree_flatten,
30
+ tree_map_,
31
+ tree_unflatten,
32
+ TreeSpec,
33
+ )
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ from collections.abc import Generator, Iterable
38
+
39
+
40
+ _P = ParamSpec("_P")
41
+ _R = TypeVar("_R")
42
+
43
+ in_dims_t = int | tuple[Any, ...]
44
+ out_dims_t = int | tuple[int, ...] | None
45
+
46
+
47
+ def doesnt_support_saved_tensors_hooks(f: Callable[_P, _R]) -> Callable[_P, _R]:
48
+ message = (
49
+ "torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. "
50
+ "Please open an issue with your use case."
51
+ )
52
+
53
+ @functools.wraps(f)
54
+ def fn(*args: _P.args, **kwargs: _P.kwargs) -> _R:
55
+ with torch.autograd.graph.disable_saved_tensors_hooks(message):
56
+ return f(*args, **kwargs)
57
+
58
+ return fn
59
+
60
+
61
+ # Checks that all args-to-be-batched have the same batch dim size
62
+ def _validate_and_get_batch_size(
63
+ flat_in_dims: list[int | None], flat_args: list[Any]
64
+ ) -> int:
65
+ batch_sizes = [
66
+ arg.size(in_dim)
67
+ for in_dim, arg in zip(flat_in_dims, flat_args)
68
+ if in_dim is not None
69
+ ]
70
+ if len(batch_sizes) == 0:
71
+ raise ValueError("vmap: Expected at least one Tensor to vmap over")
72
+ if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes):
73
+ raise ValueError(
74
+ f"vmap: Expected all tensors to have the same size in the mapped "
75
+ f"dimension, got sizes {batch_sizes} for the mapped dimension"
76
+ )
77
+ return batch_sizes[0]
78
+
79
+
80
+ def _num_outputs(batched_outputs: Tensor | tuple[Tensor, ...]) -> int:
81
+ if isinstance(batched_outputs, tuple):
82
+ return len(batched_outputs)
83
+ return 1
84
+
85
+
86
+ # If value is a tuple, check it has length `num_elements`.
87
+ # If value is not a tuple, make a tuple with `value` repeated `num_elements` times
88
+
89
+
90
+ def _as_tuple(
91
+ value: tuple[_R, ...] | _R,
92
+ num_elements: int,
93
+ error_message_lambda: Callable[[], str],
94
+ ) -> tuple[_R, ...]:
95
+ if not isinstance(value, tuple):
96
+ return (value,) * num_elements
97
+ if len(value) != num_elements:
98
+ raise ValueError(error_message_lambda())
99
+ return value
100
+
101
+
102
+ def _process_batched_inputs(
103
+ in_dims: in_dims_t, args: tuple[Any, ...], func: Callable[..., Any]
104
+ ) -> tuple[int, list[int | None], list[Any], TreeSpec]:
105
+ if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
106
+ raise ValueError(
107
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
108
+ f"expected `in_dims` to be int or a (potentially nested) tuple "
109
+ f"matching the structure of inputs, got: {type(in_dims)}."
110
+ )
111
+ if len(args) == 0:
112
+ raise ValueError(
113
+ f"vmap({_get_name(func)})(<inputs>): got no inputs. Maybe you forgot to add "
114
+ f"inputs, or you are trying to vmap over a function with no inputs. "
115
+ f"The latter is unsupported."
116
+ )
117
+
118
+ flat_args, args_spec = tree_flatten(args)
119
+ flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
120
+ if flat_in_dims is None:
121
+ raise ValueError(
122
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
123
+ f"in_dims is not compatible with the structure of `inputs`. "
124
+ f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs "
125
+ f"has structure {args_spec}."
126
+ )
127
+
128
+ for i, (arg, in_dim) in enumerate(zip(flat_args, flat_in_dims)):
129
+ if not isinstance(in_dim, int) and in_dim is not None:
130
+ raise ValueError(
131
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
132
+ f"Got in_dim={in_dim} for an input but in_dim must be either "
133
+ f"an integer dimension or None."
134
+ )
135
+ if isinstance(in_dim, int) and not isinstance(arg, Tensor):
136
+ raise ValueError(
137
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
138
+ f"Got in_dim={in_dim} for an input but the input is of type "
139
+ f"{type(arg)}. We cannot vmap over non-Tensor arguments, "
140
+ f"please use None as the respective in_dim"
141
+ )
142
+ if in_dim is not None and (in_dim < -arg.dim() or in_dim >= arg.dim()):
143
+ raise ValueError(
144
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
145
+ f"Got in_dim={in_dim} for some input, but that input is a Tensor "
146
+ f"of dimensionality {arg.dim()} so expected in_dim to satisfy "
147
+ f"-{arg.dim()} <= in_dim < {arg.dim()}."
148
+ )
149
+ if in_dim is not None and in_dim < 0:
150
+ flat_in_dims[i] = in_dim % arg.dim()
151
+
152
+ return (
153
+ _validate_and_get_batch_size(flat_in_dims, flat_args),
154
+ flat_in_dims,
155
+ flat_args,
156
+ args_spec,
157
+ )
158
+
159
+
160
+ # Creates BatchedTensors for every Tensor in arg that should be batched.
161
+ # Returns the (potentially) batched arguments and the batch_size.
162
+
163
+
164
+ # TODO: See if we can explain how flat works to the type checker
165
+ def _create_batched_inputs(
166
+ flat_in_dims: list[int | None],
167
+ flat_args: list[Any],
168
+ vmap_level: int,
169
+ args_spec: TreeSpec,
170
+ ) -> tuple[Any, ...]:
171
+ # See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
172
+ batched_inputs = [
173
+ arg if in_dim is None else _add_batch_dim(arg, in_dim, vmap_level)
174
+ for in_dim, arg in zip(flat_in_dims, flat_args)
175
+ ]
176
+ return tree_unflatten(batched_inputs, args_spec)
177
+
178
+
179
+ def _maybe_remove_batch_dim(
180
+ name: str,
181
+ batched_output: Any,
182
+ vmap_level: int,
183
+ batch_size: int,
184
+ out_dim: int | None,
185
+ ) -> torch.Tensor:
186
+ if out_dim is None:
187
+ if isinstance(batched_output, torch.Tensor) and is_batchedtensor(
188
+ batched_output
189
+ ):
190
+ raise ValueError(
191
+ f"vmap({name}, ...): `{name}` can not return a "
192
+ f"BatchedTensor when out_dim is None"
193
+ )
194
+ return batched_output
195
+
196
+ # out_dim is non None
197
+ if not isinstance(batched_output, torch.Tensor):
198
+ raise ValueError(
199
+ f"vmap({name}, ...): `{name}` must only return "
200
+ f"Tensors, got type {type(batched_output)}. "
201
+ "Did you mean to set out_dims= to None for output?"
202
+ )
203
+
204
+ return _remove_batch_dim(batched_output, vmap_level, batch_size, out_dim)
205
+
206
+
207
+ # Undoes the batching (and any batch dimensions) associated with the `vmap_level`.
208
+ def _unwrap_batched(
209
+ batched_outputs: Tensor | tuple[Tensor, ...],
210
+ out_dims: out_dims_t,
211
+ vmap_level: int,
212
+ batch_size: int,
213
+ func: Callable[..., Any],
214
+ ) -> tuple[Any, ...]:
215
+ flat_batched_outputs, output_spec = tree_flatten(batched_outputs)
216
+
217
+ def incompatible_error() -> NoReturn:
218
+ raise ValueError(
219
+ f"vmap({_get_name(func)}, ..., out_dims={out_dims})(<inputs>): "
220
+ f"out_dims is not compatible with the structure of `outputs`. "
221
+ f"out_dims has structure {tree_flatten(out_dims)[1]} but outputs "
222
+ f"has structure {output_spec}."
223
+ )
224
+
225
+ flat_out_dims: list[int | None] = []
226
+ if isinstance(batched_outputs, torch.Tensor):
227
+ # Some weird edge case requires us to spell out the following
228
+ # see test_out_dims_edge_case
229
+ if isinstance(out_dims, int):
230
+ flat_out_dims = [out_dims]
231
+ elif isinstance(out_dims, tuple) and len(out_dims) == 1:
232
+ flat_out_dims = list(out_dims)
233
+ elif out_dims is None:
234
+ flat_out_dims = [out_dims]
235
+ else:
236
+ incompatible_error()
237
+ else:
238
+ broadcast_result = _broadcast_to_and_flatten(out_dims, output_spec)
239
+ if broadcast_result is None:
240
+ incompatible_error()
241
+ else:
242
+ flat_out_dims = broadcast_result
243
+
244
+ flat_outputs = [
245
+ _maybe_remove_batch_dim(
246
+ _get_name(func), batched_output, vmap_level, batch_size, out_dim
247
+ )
248
+ for batched_output, out_dim in zip(flat_batched_outputs, flat_out_dims)
249
+ ]
250
+ return tree_unflatten(flat_outputs, output_spec)
251
+
252
+
253
+ def _check_int_or_none(x: Any, func: Callable[..., Any], out_dims: out_dims_t) -> None:
254
+ if isinstance(x, int):
255
+ return
256
+ if x is None:
257
+ return
258
+ raise ValueError(
259
+ f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be "
260
+ f"an int, None or a python collection of ints representing where in the outputs the "
261
+ f"vmapped dimension should appear."
262
+ )
263
+
264
+
265
+ def _check_out_dims_is_int_or_int_pytree(
266
+ out_dims: out_dims_t, func: Callable[..., Any]
267
+ ) -> None:
268
+ if isinstance(out_dims, int):
269
+ return
270
+ tree_map_(partial(_check_int_or_none, func=func, out_dims=out_dims), out_dims)
271
+
272
+
273
+ def _get_name(func: Callable[..., Any]) -> str:
274
+ if hasattr(func, "__name__"):
275
+ return func.__name__
276
+
277
+ if isinstance(func, functools.partial):
278
+ return f"functools.partial({_get_name(func.func)}, ...)"
279
+
280
+ # Not all callables have __name__, in fact, only static functions/methods
281
+ # do. A callable created via nn.Module, to name one example, doesn't have a
282
+ # __name__.
283
+ return repr(func)
284
+
285
+
286
+ def vmap_impl(
287
+ func: Callable[_P, Tensor | tuple[Tensor, ...]],
288
+ in_dims: in_dims_t,
289
+ out_dims: out_dims_t,
290
+ randomness: str,
291
+ chunk_size: int | None,
292
+ *args: _P.args,
293
+ **kwargs: _P.kwargs,
294
+ ) -> Any:
295
+ lazy_load_decompositions()
296
+ _check_out_dims_is_int_or_int_pytree(out_dims, func)
297
+ batch_size, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
298
+ in_dims, args, func
299
+ )
300
+
301
+ if chunk_size is not None:
302
+ chunks_flat_args = _get_chunked_inputs(
303
+ flat_args, flat_in_dims, batch_size, chunk_size
304
+ )
305
+ return _chunked_vmap(
306
+ func,
307
+ flat_in_dims,
308
+ chunks_flat_args,
309
+ args_spec,
310
+ out_dims,
311
+ randomness,
312
+ **kwargs,
313
+ )
314
+
315
+ # If chunk_size is not specified.
316
+ return _flat_vmap(
317
+ func,
318
+ batch_size,
319
+ flat_in_dims,
320
+ flat_args,
321
+ args_spec,
322
+ out_dims,
323
+ randomness,
324
+ **kwargs,
325
+ )
326
+
327
+
328
+ def get_chunk_sizes(total_elems: int, chunk_size: int) -> list[int]:
329
+ n_chunks = total_elems // chunk_size
330
+ chunk_sizes = [chunk_size] * n_chunks
331
+ # remainder chunk
332
+ remainder = total_elems % chunk_size
333
+ if remainder != 0:
334
+ chunk_sizes.append(remainder)
335
+ return chunk_sizes
336
+
337
+
338
+ def _get_chunked_inputs(
339
+ flat_args: list[Any],
340
+ flat_in_dims: list[int | None],
341
+ batch_size: int,
342
+ chunk_size: int | None,
343
+ ) -> Iterable[tuple[Any, ...]]:
344
+ split_idxs = (batch_size,)
345
+ if chunk_size is not None:
346
+ chunk_sizes = get_chunk_sizes(batch_size, chunk_size)
347
+ split_idxs = tuple(itertools.accumulate(chunk_sizes))
348
+
349
+ flat_args_chunks = tuple(
350
+ (
351
+ t.tensor_split(split_idxs, dim=in_dim)
352
+ if in_dim is not None
353
+ else [
354
+ t,
355
+ ]
356
+ * len(split_idxs)
357
+ )
358
+ for t, in_dim in zip(flat_args, flat_in_dims)
359
+ )
360
+
361
+ # transpose chunk dim and flatten structure
362
+ # chunks_flat_args is a list of flatten args
363
+ chunks_flat_args = zip(*flat_args_chunks)
364
+ return chunks_flat_args
365
+
366
+
367
+ def _flatten_chunks_output(
368
+ chunks_output_: list[Any],
369
+ ) -> tuple[list[tuple[Any, ...]], TreeSpec]:
370
+ # chunks_output is a list of chunked outputs
371
+ # flatten chunked outputs:
372
+ flat_chunks_output: list[list[Any]] = []
373
+ arg_spec: TreeSpec | None = None
374
+ for output in chunks_output_:
375
+ flat_output, arg_specs = tree_flatten(output)
376
+ flat_chunks_output.append(flat_output)
377
+ if arg_spec is None:
378
+ arg_spec = arg_specs
379
+
380
+ # transpose chunk dim and flatten structure
381
+ # flat_output_chunks is flat list of chunks
382
+ flat_output_chunks = list(zip(*flat_chunks_output))
383
+ if arg_spec is None:
384
+ raise AssertionError("arg_spec must not be None")
385
+ return flat_output_chunks, arg_spec
386
+
387
+
388
+ def _concat_chunked_outputs(
389
+ out_dims: out_dims_t,
390
+ arg_spec: TreeSpec,
391
+ flat_output_chunks: list[tuple[Any, ...] | None],
392
+ ) -> list[Tensor]:
393
+ # concat chunks on out_dim
394
+ flat_out_dims = _broadcast_to_and_flatten(out_dims, arg_spec)
395
+ if flat_out_dims is None:
396
+ raise AssertionError("flat_out_dims must not be None")
397
+ if len(flat_out_dims) != len(flat_output_chunks):
398
+ raise AssertionError(
399
+ f"len(flat_out_dims)={len(flat_out_dims)} != len(flat_output_chunks)={len(flat_output_chunks)}"
400
+ )
401
+ flat_output: list[Tensor] = []
402
+ for idx, out_dim in enumerate(flat_out_dims):
403
+ chunk = flat_output_chunks[idx]
404
+ if chunk is None:
405
+ raise AssertionError(f"chunk at index {idx} must not be None")
406
+ flat_output.append(torch.cat(chunk, dim=out_dim))
407
+ # release tensors
408
+ flat_output_chunks[idx] = None
409
+
410
+ return flat_output
411
+
412
+
413
+ # Applies vmap on chunked_input and returns concatenated output over the chunks.
414
+ def _chunked_vmap(
415
+ func: Callable[_P, Tensor | tuple[Tensor, ...]],
416
+ flat_in_dims: list[int | None],
417
+ chunks_flat_args: Iterable[tuple[Any, ...]],
418
+ args_spec: TreeSpec,
419
+ out_dims: out_dims_t,
420
+ randomness: str,
421
+ **kwargs: Any,
422
+ ) -> Any:
423
+ chunks_output: list[Any] = []
424
+ rs = torch.get_rng_state() if randomness == "same" else None
425
+ for flat_args_tuple in chunks_flat_args:
426
+ flat_args = list(flat_args_tuple)
427
+ batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
428
+
429
+ # The way we compute split the input in `_get_chunked_inputs`,
430
+ # we may get a tensor with `0` batch-size. We skip any computation
431
+ # in that case.
432
+ # Eg.
433
+ # >>> chunk_size = 1
434
+ # >>> batch_size = 6
435
+ # >>> t = torch.zeros(batch_size, 1)
436
+ # >>> t.tensor_split([1, 2, 3, 4, 5, 6])
437
+ # (tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), tensor([[0.]]),
438
+ # tensor([[0.]]), tensor([[0.]]), tensor([], size=(0, 1)))
439
+ if batch_size == 0:
440
+ continue
441
+
442
+ if rs is not None:
443
+ torch.set_rng_state(rs)
444
+ chunks_output.append(
445
+ _flat_vmap(
446
+ func,
447
+ batch_size,
448
+ flat_in_dims,
449
+ flat_args,
450
+ args_spec,
451
+ out_dims,
452
+ randomness,
453
+ **kwargs,
454
+ )
455
+ )
456
+
457
+ flat_output_chunks, arg_spec = _flatten_chunks_output(chunks_output)
458
+
459
+ # chunked output tensors are held by both `flat_output_chunks` and `chunks_output`.
460
+ # eagerly remove the reference from `chunks_output`.
461
+ del chunks_output
462
+
463
+ # concat chunks on out_dim
464
+ # Note: We use cast since flat_output_chunks is modified in _concat_chunked_outputs
465
+ # to set elements to None after processing
466
+ flat_output = _concat_chunked_outputs(
467
+ out_dims, arg_spec, cast(list[tuple[Any, ...] | None], flat_output_chunks)
468
+ )
469
+
470
+ # finally unflatten the output
471
+ return tree_unflatten(flat_output, arg_spec)
472
+
473
+
474
+ # Vmap refactored helper functions:
475
+ def _check_randomness_arg(randomness: str) -> None:
476
+ if randomness not in ["error", "different", "same"]:
477
+ raise RuntimeError(
478
+ f"Only allowed values for randomness are 'error', 'different', or 'same'. Got {randomness}"
479
+ )
480
+
481
+
482
+ @contextlib.contextmanager
483
+ def vmap_increment_nesting(
484
+ batch_size: int, randomness: str
485
+ ) -> Generator[int, None, None]:
486
+ try:
487
+ vmap_level = _vmap_increment_nesting(batch_size, randomness)
488
+ yield vmap_level
489
+ finally:
490
+ _vmap_decrement_nesting()
491
+
492
+
493
+ def _flat_vmap(
494
+ func: Callable[..., Tensor | tuple[Tensor, ...]],
495
+ batch_size: int,
496
+ flat_in_dims: list[int | None],
497
+ flat_args: list[Any],
498
+ args_spec: TreeSpec,
499
+ out_dims: out_dims_t,
500
+ randomness: str,
501
+ **kwargs: Any,
502
+ ) -> Any:
503
+ with vmap_increment_nesting(batch_size, randomness) as vmap_level:
504
+ batched_inputs = _create_batched_inputs(
505
+ flat_in_dims, flat_args, vmap_level, args_spec
506
+ )
507
+ batched_outputs = func(*batched_inputs, **kwargs)
508
+ return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func)
509
+
510
+
511
+ # `restore_vmap` is a private helper function. It is vmap but has the following
512
+ # differences:
513
+ # - instead of returning outputs, it returns an (outputs, out_dims) tuple.
514
+ # out_dims is a pytree of same shape as outputs and contains Optional[int]
515
+ # specifying where the vmapped dimension, if it exists, is in the corresponding output.
516
+ # - does no validation on in_dims or inputs (vmap expects at least one Tensor to be vmapped).
517
+ # restore_vmap allows for no inputs to have the vmap dimension
518
+ # - does no validation on outputs (vmap expects only Tensor outputs)
519
+ # restore_vmap allows for return of arbitrary outputs (not just Tensors)
520
+ #
521
+ # The TL;DR is that restore_vmap is more general than vmap and has a slightly
522
+ # different API. The relaxations are so that we can "pause" vmap in the middle
523
+ # of its execution and then "restore" it later (this is what we do in
524
+ # the generate_vmap_rule=True implementation of autograd.Function).
525
+ #
526
+ # restore_vmap can be technically used in the implementation of vmap, but doing
527
+ # that refactor is a bit technically challenging because:
528
+ # - vmap couples the tensor-wrapping code with error checking
529
+ # - vmap's tensor unwrapping code is in C++; we would need to rewrite part of it
530
+ # in python because it overlaps with unwrap_batched
531
+ def restore_vmap(
532
+ func: Callable[..., _R], in_dims: in_dims_t, batch_size: int, randomness: str
533
+ ) -> Callable[..., tuple[Any, Any]]:
534
+ def inner(*args: Any, **kwargs: Any) -> tuple[Any, Any]:
535
+ with vmap_increment_nesting(batch_size, randomness) as vmap_level:
536
+ batched_inputs = wrap_batched(args, in_dims, vmap_level)
537
+ batched_outputs = func(*batched_inputs, **kwargs)
538
+ return unwrap_batched(batched_outputs, vmap_level)
539
+
540
+ return inner
541
+
542
+
543
+ def wrap_batched(
544
+ args: tuple[Any, ...], bdims: in_dims_t, level: int
545
+ ) -> tuple[Any, ...]:
546
+ flat_args, spec = tree_flatten(args)
547
+ flat_bdims = _broadcast_to_and_flatten(bdims, spec)
548
+ if flat_bdims is None:
549
+ raise AssertionError("flat_bdims must not be None")
550
+ result = _create_batched_inputs(flat_bdims, flat_args, level, spec)
551
+ return result
552
+
553
+
554
+ def unwrap_batched(args: Any, level: int) -> tuple[Any, Any]:
555
+ flat_args, spec = tree_flatten(args)
556
+ if len(flat_args) == 0:
557
+ return args, ()
558
+ result = [
559
+ (
560
+ torch._C._functorch._unwrap_batched(arg, level)
561
+ if isinstance(arg, torch.Tensor)
562
+ else (arg, None)
563
+ )
564
+ for arg in flat_args
565
+ ]
566
+ output, bdims = zip(*result)
567
+ return tree_unflatten(output, spec), tree_unflatten(bdims, spec)
.venv/lib/python3.12/site-packages/torch/_guards.py ADDED
@@ -0,0 +1,1610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import enum
6
+ import functools
7
+ import logging
8
+ import re
9
+ import sys
10
+ import threading
11
+ import traceback
12
+ import unittest.mock
13
+ import weakref
14
+ from abc import abstractmethod
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+ from dataclasses import dataclass
18
+ from typing import Any, Generic, NamedTuple, overload, TYPE_CHECKING, TypeVar
19
+ from typing_extensions import dataclass_transform
20
+
21
+ import torch
22
+ from torch.utils import _pytree as pytree
23
+ from torch.utils._ordered_set import OrderedSet
24
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
25
+ from torch.utils._traceback import CapturedTraceback, format_frame
26
+ from torch.utils.weak import WeakTensorKeyDictionary
27
+
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ import dis
34
+ from collections.abc import Callable, Generator, Iterator
35
+ from types import CodeType
36
+
37
+ import sympy
38
+
39
+ from torch._dynamo.backends.distributed import DDPOptimizerContext
40
+ from torch._dynamo.codegen import PyCodegen
41
+ from torch._dynamo.guards import GuardCheckSpec
42
+ from torch._dynamo.output_graph import CodeOptions
43
+ from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta
44
+ from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions
45
+ from torch._subclasses.fake_tensor import FakeTensorMode
46
+
47
+
48
+ """
49
+ torch._guards is the definitional source of truth for general purpose guard structures.
50
+
51
+ An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions,
52
+ and no guard installation notions here.
53
+ """
54
+
55
+ COMPILE_ID_PATTERN = re.compile(r"^(?P<frame_id>\d+)/(?P<frame_compile_id>\d+)$")
56
+ CA_COMPILE_ID_PATTERN = re.compile(
57
+ r"^!(?P<compiled_autograd_id>\d+)(?:/(?P<frame_id>\d+)/(?P<frame_compile_id>\d+))?$"
58
+ )
59
+
60
+ # [Note: Updating CompiledId]
61
+ #
62
+ # CompiledId represents a unique program-level identifier, and we want to keep that
63
+ # property as the codebase evolves. This property is relied on even outside of the pytorch
64
+ # repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed,
65
+ # as those dependencies only consume the string serialization.
66
+ #
67
+ # The string form should be:
68
+ # 1. Program-level uid: CompileId can uniquely identify a compiled graph.
69
+ # 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible.
70
+ # 3. Compact: The string form is directly displayed by some tools. Special symbols are okay.
71
+
72
+
73
+ @dataclass(frozen=True, kw_only=True, slots=True)
74
+ class CompileId:
75
+ frame_id: int | None
76
+ # This id is per-frame, and counts how many times we've compiled this
77
+ # frame. This could have been a global id but having this be per-frame
78
+ # gives you a better intuitive sense for how many recompiles have occurred
79
+ # so far.
80
+ frame_compile_id: int | None
81
+
82
+ # torch.compiling a compiled autograd graph
83
+ compiled_autograd_id: int | None = None
84
+
85
+ # TODO: consider also tracking the recompilation count
86
+ # See Note: Updating CompileId
87
+
88
+ def __str__(self) -> str:
89
+ # NOTE: Keep this in sync with both from_string and the tlparse repo
90
+ if self.compiled_autograd_id is not None:
91
+ if (self.frame_id is None) != (self.frame_compile_id is None):
92
+ raise AssertionError(
93
+ f"frame_id and frame_compile_id must both be None or both be set, "
94
+ f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
95
+ )
96
+ frame_str = ""
97
+ if self.frame_id is not None:
98
+ frame_str = f"/{self.frame_id}/{self.frame_compile_id}"
99
+
100
+ return f"!{self.compiled_autograd_id}{frame_str}"
101
+ else:
102
+ if self.frame_id is None or self.frame_compile_id is None:
103
+ raise AssertionError(
104
+ f"frame_id and frame_compile_id must not be None, "
105
+ f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
106
+ )
107
+ return f"{self.frame_id}/{self.frame_compile_id}"
108
+
109
+ @classmethod
110
+ def from_string(cls, compile_id: str | None) -> CompileId | None:
111
+ """
112
+ Factory method that creates a CompileId from its string representation.
113
+ Keep this in sync with the __str__ method.
114
+ """
115
+ if compile_id is None:
116
+ return None
117
+ try:
118
+ for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN):
119
+ if match := pattern.match(compile_id):
120
+ groups = match.groupdict()
121
+ for k, v in groups.items():
122
+ if v is not None:
123
+ groups[k] = int(v)
124
+ return cls(**groups) # type: ignore[arg-type]
125
+ else:
126
+ raise ValueError
127
+
128
+ except Exception as e:
129
+ raise ValueError(f"Invalid compile_id '{compile_id}'") from e
130
+
131
+
132
+ class TraceId(NamedTuple):
133
+ compile_id: CompileId
134
+ # This starts off as 0, and every time we restart analysis it goes
135
+ # up by one
136
+ attempt: int
137
+
138
+ def __str__(self) -> str:
139
+ # Keep this in sync with tlparse repo
140
+ if self.attempt == 0:
141
+ return str(self.compile_id)
142
+ else:
143
+ return f"{self.compile_id}_{self.attempt}"
144
+
145
+
146
+ class GuardSource(enum.Enum):
147
+ LOCAL = 0
148
+ GLOBAL = 1
149
+ LOCAL_SPECIALIZED_NN_MODULE = 2
150
+ GLOBAL_SPECIALIZED_NN_MODULE = 3
151
+ CONSTANT = 4
152
+ RANDOM_VALUE = 5
153
+ SHAPE_ENV = 6
154
+ LOCAL_FSDP_MODULE = 7
155
+ GLOBAL_FSDP_MODULE = 8
156
+ BACKWARD_STATE = 9
157
+ EPHEMERAL = 10
158
+ SYNTHETIC_LOCAL = 11
159
+ LOCAL_UNSPECIALIZED_NN_MODULE = 12
160
+ GLOBAL_UNSPECIALIZED_NN_MODULE = 13
161
+ LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14
162
+ GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15
163
+ TEMP_LOCAL = 16
164
+
165
+ def is_fsdp_module(self) -> bool:
166
+ return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE)
167
+
168
+ def is_specialized_nn_module(self) -> bool:
169
+ import torch._dynamo.config as config
170
+
171
+ if config._unsafe_skip_fsdp_module_guards:
172
+ return (
173
+ self
174
+ in (
175
+ GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
176
+ GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
177
+ )
178
+ or self.is_fsdp_module()
179
+ )
180
+ return self in (
181
+ GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
182
+ GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
183
+ )
184
+
185
+ def is_unspecialized_nn_module(self) -> bool:
186
+ return self in (
187
+ GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
188
+ GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
189
+ GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
190
+ GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
191
+ )
192
+
193
+ def is_unspecialized_builtin_nn_module(self) -> bool:
194
+ return self in (
195
+ GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
196
+ GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
197
+ )
198
+
199
+ def is_local(self) -> bool:
200
+ return self in (
201
+ GuardSource.LOCAL,
202
+ GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
203
+ GuardSource.LOCAL_FSDP_MODULE,
204
+ GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
205
+ GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
206
+ )
207
+
208
+
209
+ """
210
+ Base class for a "GuardBuilder" role.
211
+
212
+ The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little
213
+ confusing, as it's not a builder, but for the sake of avoiding a lot of renames and keeping the original reference
214
+ to torchdynamo's GuardBuilder.
215
+
216
+ Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based
217
+ on GuardSource's select function.
218
+
219
+ There is value in keeping this GuardBuilderBase empty to keep layering clean.
220
+ """
221
+
222
+
223
+ class GuardBuilderBase:
224
+ pass
225
+
226
+
227
+ @dataclasses.dataclass(frozen=True)
228
+ class SLoc:
229
+ framework_loc: traceback.FrameSummary | str | None
230
+ maybe_user_loc: str | None
231
+
232
+ def __str__(self) -> str:
233
+ floc = (
234
+ self.framework_loc
235
+ if isinstance(self.framework_loc, str)
236
+ else ""
237
+ if self.framework_loc is None
238
+ else format_frame(self.framework_loc)
239
+ )
240
+ if self.maybe_user_loc is not None:
241
+ return f"{self.maybe_user_loc} ({floc})"
242
+ else:
243
+ return f"({floc})"
244
+
245
+
246
+ class ShapeGuard(NamedTuple):
247
+ expr: sympy.logic.boolalg.Boolean
248
+ sloc: SLoc
249
+ size_oblivious: bool
250
+
251
+
252
+ @dataclasses.dataclass(slots=True)
253
+ class Guard:
254
+ # originating_source is the source that called the make_guard method to
255
+ # construct this guard object. The property name specifies what exactly it
256
+ # is the guard is guarding on. The meaning of the name is dependent on the
257
+ # create_fn; you must look at the use-site inside create_fn to know what
258
+ # name means.
259
+ #
260
+ # That being said, although you might think this is just a "name", name is
261
+ # usually an arbitrary Python expression that will be evaluated with all
262
+ # globals (and locals, if you create a LOCAL guard) to extract the Python
263
+ # object that we want to perform guard tests on. This evaluation
264
+ # typically happens in GuardBuilder.eval. In these cases, name is
265
+ # typically produced by originating_source.name (not to be confused with
266
+ # GuardSource - the property source).
267
+ #
268
+ # Occasionally, name is not a valid Python expression; sometimes
269
+ # it is meaningless. Example create_fns that are like this include
270
+ # GRAD_MODE and SHAPE_ENV.
271
+ originating_source: Source
272
+ create_fn: Callable[[GuardBuilderBase, Guard], None]
273
+
274
+ # Export only. These values are written to at time of guard check_fn creation.
275
+ guard_types: list[str] | None = None
276
+ code_list: list[str] | None = None
277
+ obj_weakref: object | None = None
278
+ guarded_class_weakref: weakref.ReferenceType[Any] | None = None
279
+
280
+ stack: CapturedTraceback | None = None
281
+ user_stack: traceback.StackSummary | None = None
282
+ _hash: int | None = None
283
+ _unserializable: bool = False
284
+ _force_dict_keys_match: bool = False
285
+
286
+ def __hash__(self) -> int:
287
+ if self._hash is None:
288
+ self._hash = hash((self.name, self.source, id(self.create_fn)))
289
+ return self._hash
290
+
291
+ def sort_key(self) -> tuple[bool, int, int, str, int]:
292
+ # Put the duplicate input guards at the end. The duplicate guards have
293
+ # two sources while guard.name only considers one source.
294
+
295
+ is_duplicate_input = (
296
+ isinstance(self.create_fn, functools.partial)
297
+ and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT
298
+ )
299
+ return (
300
+ is_duplicate_input,
301
+ self.source.value if self.source else -1,
302
+ len(self.name),
303
+ self.name,
304
+ self.inner_create_fn().__code__.co_firstlineno,
305
+ )
306
+
307
+ def __lt__(self, other: Guard) -> bool:
308
+ return self.sort_key() < other.sort_key()
309
+
310
+ def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]:
311
+ if isinstance(self.create_fn, functools.partial):
312
+ return self.create_fn.func
313
+ else:
314
+ return self.create_fn
315
+
316
+ @property
317
+ def name(self) -> str:
318
+ return self.originating_source.name
319
+
320
+ @property
321
+ def source(self) -> GuardSource:
322
+ return self.originating_source.guard_source
323
+
324
+ @staticmethod
325
+ def weakref_to_str(obj_weakref: object) -> str:
326
+ """
327
+ This is a workaround of a Python weakref bug.
328
+
329
+ `obj_weakref` is instance returned by `weakref.ref`,
330
+ `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g:
331
+
332
+ class MyConfig(dict):
333
+ def __getattr__(self, x):
334
+ return self[x]
335
+
336
+ obj = MyConfig(offset=5)
337
+ obj_weakref = weakref.ref(obj)
338
+ str(obj_weakref) # raise error: KeyError: '__name__'
339
+ """
340
+ if isinstance(obj_weakref, weakref.ReferenceType):
341
+ obj = obj_weakref()
342
+ if obj is not None:
343
+ return f"<weakref at {hex(id(obj_weakref))}; to '{obj.__class__.__name__}' at {hex(id(obj))}>"
344
+ else:
345
+ return f"<weakref at {hex(id(obj_weakref))}; dead>"
346
+ else:
347
+ return str(obj_weakref)
348
+
349
+ def __repr__(self) -> str:
350
+ s = f"""
351
+ {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__}
352
+ {{
353
+ 'guard_types': {self.guard_types},
354
+ 'code': {self.code_list},
355
+ 'obj_weakref': {self.weakref_to_str(self.obj_weakref)}
356
+ 'guarded_class': {self.guarded_class_weakref}
357
+ }}
358
+ """
359
+ return s
360
+
361
+ def __str__(self) -> str:
362
+ output = f"Name: {repr(self.name)}\n"
363
+ source = self.source.name.lower() if self.source else ""
364
+ output += f" Source: {source}\n"
365
+ output += f" Create Function: {self.inner_create_fn().__name__}\n"
366
+ output += f" Guard Types: {self.guard_types}\n"
367
+ output += f" Code List: {self.code_list}\n"
368
+ output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n"
369
+ output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n"
370
+ return output
371
+
372
+ def create(self, builder: GuardBuilderBase) -> Any:
373
+ try:
374
+ return self.create_fn(builder, self)
375
+ except Exception:
376
+ log.exception("Error while creating guard:\n%s", str(self).rstrip())
377
+ if self.stack:
378
+ log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip())
379
+ raise
380
+
381
+ def is_specialized_nn_module(self) -> bool:
382
+ return self.source.is_specialized_nn_module()
383
+
384
+ def is_fsdp_module(self) -> bool:
385
+ return self.source.is_fsdp_module()
386
+
387
+ def is_local(self) -> bool:
388
+ return self.source.is_local()
389
+
390
+ def create_fn_name(self) -> str:
391
+ if isinstance(self.create_fn, functools.partial):
392
+ create_fn = self.create_fn.func # type: ignore[attr-defined]
393
+ else:
394
+ create_fn = self.create_fn
395
+ return create_fn.__name__
396
+
397
+ def set_export_info(
398
+ self,
399
+ guard_type: str,
400
+ guarded_class: weakref.ReferenceType[Any] | None,
401
+ code_list: list[str],
402
+ obj_weakref: object,
403
+ ) -> None:
404
+ if not self.guard_types:
405
+ self.guard_types = []
406
+
407
+ self.guard_types.append(guard_type)
408
+
409
+ if self.guarded_class_weakref not in (guarded_class, None):
410
+ raise AssertionError(
411
+ f"Guarded class id must be identical, or None, "
412
+ f"got {self.guarded_class_weakref} vs {guarded_class}"
413
+ )
414
+ self.guarded_class_weakref = guarded_class
415
+
416
+ if not self.code_list:
417
+ self.code_list = code_list
418
+ else:
419
+ self.code_list.extend(code_list)
420
+
421
+ # Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have
422
+ # multiple guards on the same object, the weakref can die between the
423
+ # invocation of set_export_info calls. So a dead weakref is also
424
+ # acceptable.
425
+ is_valid = (
426
+ self.obj_weakref in (obj_weakref, None)
427
+ or callable(self.obj_weakref)
428
+ and self.obj_weakref() is None
429
+ )
430
+ if not is_valid:
431
+ raise AssertionError(
432
+ f"Guarded object must be identical, None or ephemeral (dead weakref), "
433
+ f"got {self.obj_weakref} vs {obj_weakref}"
434
+ )
435
+ self.obj_weakref = obj_weakref
436
+
437
+
438
+ T = TypeVar("T")
439
+
440
+ """
441
+ Parent structure for guard env expressions.
442
+ A GuardEnvExpr can have any subtype.
443
+ Note: All subtypes must be handled exhaustively in
444
+ torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError.
445
+ """
446
+
447
+
448
+ @dataclasses.dataclass(frozen=True)
449
+ class GuardEnvExpr:
450
+ pass
451
+
452
+
453
+ """
454
+ A class representing a pair of duplicate inputs.
455
+ input_pos_a and input_pos_b are input positions we have deduped.
456
+ """
457
+
458
+
459
+ @dataclasses.dataclass(frozen=True)
460
+ class DuplicateInputs(GuardEnvExpr):
461
+ input_source_a: Source
462
+ input_source_b: Source
463
+
464
+ def __post_init__(self) -> None:
465
+ if self.input_source_a == self.input_source_b:
466
+ raise AssertionError(
467
+ f"input_source_a and input_source_b must be different, "
468
+ f"got {self.input_source_a}"
469
+ )
470
+
471
+
472
+ """
473
+ A class representing storage overlap relations among inputs that aliases the same storage.
474
+
475
+ Given that a set of tensors alias the same storage, this guard checks whether they actually
476
+ have overlapping storages.
477
+
478
+ While non_overlapping_sources represent input tensors that definitely don't have any storage
479
+ overlapping with any other input, overlapping_sources represent tensors that either:
480
+
481
+ 1. Do overlap some other input tensor
482
+ 2. Might not overlap some other input tensor, but we are not sure
483
+ """
484
+
485
+
486
+ @dataclasses.dataclass(frozen=True)
487
+ class StorageOverlap(GuardEnvExpr):
488
+ overlapping_sources: list[Source]
489
+ non_overlapping_sources: list[Source]
490
+
491
+
492
+ """
493
+ Checkpointable is an interface for driving state snapshotting, left purposely vague for now.
494
+
495
+ copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that
496
+ can also be taken in at restore_graphstate(T) calls.
497
+
498
+ When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable
499
+ does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet.
500
+
501
+ In the future, it will have a closer coupling to a generic Checkpoint management system.
502
+ """
503
+
504
+
505
+ class Checkpointable(Generic[T]):
506
+ @abstractmethod
507
+ def copy_graphstate(self) -> T: ...
508
+
509
+ @abstractmethod
510
+ def restore_graphstate(self, state: T) -> None: ...
511
+
512
+
513
+ class GuardsCheckpointState:
514
+ """
515
+ The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
516
+ """
517
+
518
+ dynamo_guards: OrderedSet[Guard]
519
+
520
+ def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None:
521
+ self.dynamo_guards = dynamo_guards
522
+
523
+ def diff(self, other: GuardsCheckpointState) -> OrderedSet[Guard] | None:
524
+ """
525
+ Produces a delta against another GuardsCheckpointState.
526
+
527
+ Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched
528
+ Guard type objects.
529
+ """
530
+ r = self.dynamo_guards.difference(other.dynamo_guards)
531
+ if len(r) == 0:
532
+ return None
533
+ return r
534
+
535
+ def __eq__(self, other: object) -> bool:
536
+ if not isinstance(other, GuardsCheckpointState):
537
+ return False
538
+ return self.diff(other) is None
539
+
540
+
541
+ class ModuleContextCheckpointState:
542
+ nn_modules: dict[str, torch.nn.Module] = {}
543
+
544
+ def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None:
545
+ self.nn_modules = nn_modules
546
+
547
+ def diff(self, other: ModuleContextCheckpointState) -> set[str] | None:
548
+ """
549
+ Produces a delta against another ModuleContextCheckpointState.
550
+
551
+ Returns None if no delta is found, otherwise, return a set() of mismatched
552
+ module key names.
553
+ """
554
+ r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys()))
555
+ if len(r) == 0:
556
+ return None
557
+ return r
558
+
559
+ def __eq__(self, other: object) -> bool:
560
+ if not isinstance(other, ModuleContextCheckpointState):
561
+ return False
562
+ return self.diff(other) is None
563
+
564
+
565
+ class ModuleContext(Checkpointable[ModuleContextCheckpointState]):
566
+ def __init__(self) -> None:
567
+ self.nn_modules: dict[str, Any] = {}
568
+
569
+ def copy_graphstate(self) -> ModuleContextCheckpointState:
570
+ return ModuleContextCheckpointState(dict(self.nn_modules))
571
+
572
+ def restore_graphstate(self, state: ModuleContextCheckpointState) -> None:
573
+ if not isinstance(state, ModuleContextCheckpointState):
574
+ raise AssertionError(
575
+ f"expected ModuleContextCheckpointState, got {type(state)}"
576
+ )
577
+ self.nn_modules = state.nn_modules
578
+
579
+
580
+ class GlobalContextCheckpointState:
581
+ global_state: dict[str, tuple[Callable, Any]] = {}
582
+
583
+ def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None:
584
+ self.global_state = global_states
585
+
586
+ def diff(self, other: GlobalContextCheckpointState) -> set[str] | None:
587
+ """
588
+ Produces a delta against another GlobalContextCheckpointState.
589
+
590
+ Returns None if no delta is found, otherwise, return a set() of mismatched
591
+ global key names.
592
+ """
593
+ r = set(self.global_state.keys()).difference(set(other.global_state.keys()))
594
+ if len(r) == 0:
595
+ return None
596
+ return r
597
+
598
+ def __eq__(self, other: object) -> bool:
599
+ if not isinstance(other, GlobalContextCheckpointState):
600
+ return False
601
+ return self.diff(other) is None
602
+
603
+
604
+ class GlobalContext(Checkpointable[GlobalContextCheckpointState]):
605
+ """
606
+ This keeps track of the global torch state during tracing of a function.
607
+ For example, torch.is_grad_enabled.
608
+ """
609
+
610
+ _supported_global_states = {
611
+ "grad_enabled",
612
+ "autocast_enabled",
613
+ "autocast_cpu_enabled",
614
+ "autocast_gpu_dtype",
615
+ "autocast_cpu_dtype",
616
+ "autocast_cache_enabled",
617
+ }
618
+
619
+ def __init__(self) -> None:
620
+ self.global_state: dict[str, tuple[Callable, Any]] = {}
621
+
622
+ def copy_graphstate(self) -> GlobalContextCheckpointState:
623
+ return GlobalContextCheckpointState(self.global_state)
624
+
625
+ def restore_graphstate(self, state: GlobalContextCheckpointState) -> None:
626
+ if not isinstance(state, GlobalContextCheckpointState):
627
+ raise AssertionError(
628
+ f"expected GlobalContextCheckpointState, got {type(state)}"
629
+ )
630
+ self.global_state = state.global_state
631
+ if not (
632
+ len(self.global_state) == len(self._supported_global_states)
633
+ and set(self.global_state.keys()) == self._supported_global_states
634
+ ):
635
+ raise AssertionError(
636
+ f"Global state mismatch: got keys {set(self.global_state.keys())}, "
637
+ f"expected {self._supported_global_states}"
638
+ )
639
+ for func, args in self.global_state.values():
640
+ func(args)
641
+
642
+
643
+ # Like a Set[Guard] but will record the user stack on all guards at the
644
+ # time they were installed at their destination
645
+ class GuardsSet:
646
+ def __init__(self, inner: OrderedSet[Guard] | None = None) -> None:
647
+ if inner is None:
648
+ self.inner: OrderedSet[Guard] = OrderedSet()
649
+ else:
650
+ self.inner = inner
651
+ # Map from source to list of guards with that source. Incrementally
652
+ # built in `add` method.
653
+ self.source_to_guards: defaultdict[Source, list[Guard]] = defaultdict(list)
654
+ for guard in self.inner:
655
+ self.track_guard_by_source(guard)
656
+
657
+ def track_guard_by_source(self, guard: Guard) -> None:
658
+ source = guard.originating_source
659
+ self.source_to_guards[source].append(guard)
660
+
661
+ def __iter__(self) -> Iterator[Guard]:
662
+ return iter(self.inner)
663
+
664
+ def __len__(self) -> int:
665
+ return len(self.inner)
666
+
667
+ # Subtraction along with bool is typically used to determine the delta of
668
+ # added guards between checkpoints for higher order ops
669
+ def __sub__(self, other: GuardsSet) -> GuardsSet:
670
+ return GuardsSet(self.inner - other.inner)
671
+
672
+ def __bool__(self) -> bool:
673
+ return bool(self.inner)
674
+
675
+ def clear(self) -> None:
676
+ self.inner = OrderedSet()
677
+ self.source_to_guards = defaultdict(list)
678
+
679
+ def add(
680
+ self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0
681
+ ) -> None:
682
+ if guard in self.inner:
683
+ return
684
+ if collect_debug_stack:
685
+ if guard.stack is None:
686
+ guard.stack = CapturedTraceback.extract(skip=1 + skip)
687
+ if guard.user_stack is None:
688
+ guard.user_stack = TracingContext.extract_stack()
689
+ self.inner.add(guard)
690
+ self.track_guard_by_source(guard)
691
+
692
+ def update(self, *others: set[Guard]) -> None:
693
+ for o in others:
694
+ for g in o:
695
+ self.add(g, skip=1)
696
+
697
+ def get_guards_for_source(self, source: Source) -> list[Guard]:
698
+ """Return all guards with the given originating_source."""
699
+ return list(self.source_to_guards[source])
700
+
701
+ def remove_guards_with_source(self, source: Source) -> None:
702
+ """Delete all guards that contains a given source"""
703
+ from ._dynamo.source import is_from_source
704
+
705
+ self.inner = OrderedSet(
706
+ g for g in self.inner if not is_from_source(g.originating_source, source)
707
+ )
708
+ # Rebuild the index since is_from_source walks the chain, so
709
+ # multiple source keys may need removal.
710
+ self.source_to_guards = defaultdict(list)
711
+ for guard in self.inner:
712
+ self.track_guard_by_source(guard)
713
+
714
+
715
+ """
716
+ A GuardsContext is a checkpointable representation of all the guards in the current tracing
717
+ context. Its lifecycle is bound 1:1 to the tracing context, and it should never be instantiated
718
+ directly outside of it. For passing around internal state representations of this object,
719
+ prefer to extract them with copy_graphstate to produce a GuardsCheckpointState.
720
+ """
721
+
722
+
723
+ class GuardsContext(Checkpointable[GuardsCheckpointState]):
724
+ def __init__(self) -> None:
725
+ self.dynamo_guards: GuardsSet = GuardsSet()
726
+ self.aotautograd_guards: list[GuardEnvExpr] = []
727
+ self.skip_install: bool = False
728
+
729
+ @contextlib.contextmanager
730
+ def skip_guard_install(self) -> Generator[None, None, None]:
731
+ old = self.skip_install
732
+ self.skip_install = True
733
+ try:
734
+ yield
735
+ finally:
736
+ self.skip_install = old
737
+
738
+ def copy_graphstate(self) -> GuardsCheckpointState:
739
+ return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner))
740
+
741
+ def restore_graphstate(self, state: GuardsCheckpointState) -> None:
742
+ # NB: "steals" the passed in state
743
+ if not isinstance(state, GuardsCheckpointState):
744
+ raise AssertionError(f"expected GuardsCheckpointState, got {type(state)}")
745
+ self.dynamo_guards = GuardsSet(state.dynamo_guards)
746
+
747
+
748
+ class HopSubgraphCache:
749
+ @abstractmethod
750
+ def add_dynamo_installed_submodule(
751
+ self, fn_code: CodeType, identifier: str
752
+ ) -> None: ...
753
+
754
+ @abstractmethod
755
+ def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: ...
756
+
757
+ @abstractmethod
758
+ def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ...
759
+
760
+ @abstractmethod
761
+ def get_autograd_key_entry(self, identifier: str) -> Callable | None: ...
762
+
763
+ @abstractmethod
764
+ def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ...
765
+
766
+ @abstractmethod
767
+ def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ...
768
+
769
+ @abstractmethod
770
+ def add_functionalize_schema_entry(
771
+ self, key: object, schema: torch._C.FunctionSchema
772
+ ) -> None: ...
773
+
774
+ @abstractmethod
775
+ def get_functionalize_schema_entry(
776
+ self, key: object
777
+ ) -> torch._C.FunctionSchema | None: ...
778
+
779
+ @abstractmethod
780
+ def add_lazy_bwd_entry(
781
+ self,
782
+ identifier: str,
783
+ tangent_metadata: tuple[object],
784
+ gmod: torch.fx.GraphModule,
785
+ ) -> int: ...
786
+
787
+ @abstractmethod
788
+ def get_lazy_bwd_entry(
789
+ self, identifier: str, tangent_metadata: tuple[object]
790
+ ) -> tuple[torch.fx.GraphModule | None, int | None]: ...
791
+
792
+
793
+ @dataclass
794
+ class InvokeSubgraphReuseEntry:
795
+ body_name: str
796
+ body_gmod: torch.fx.GraphModule
797
+ config: NestedCompileRegionOptions | None
798
+ subgraph_input_mapping: list[
799
+ Any
800
+ ] # list[LiftedArgOrigin] - defined in invoke_subgraph.py
801
+ single_tensor_output: bool
802
+ # Per-output tensor metadata (shape, stride, dtype, device, requires_grad)
803
+ # cached from the first trace so we can construct fresh FakeTensors on
804
+ # cache hit without re-running body_gmod.
805
+ output_metadata: list[
806
+ tuple[torch.Size, tuple[int, ...], torch.dtype, torch.device, bool]
807
+ ]
808
+ # 1-1 mapping to flat_vts: source for each flattened arg/kwarg, or None if
809
+ # the VT has no source. On cache hit, we build a source replacement mapping
810
+ # (old arg sources → new arg sources) to rewrite captured variable sources
811
+ # for the current invocation.
812
+ arg_sources: list[Source | None]
813
+ # Number of user-visible outputs (from the function return value).
814
+ # The graph may have additional outputs from side-effect intermediates;
815
+ # stamp_out_subgraph uses this to return only the user-visible slice.
816
+ num_user_outputs: int = 0
817
+
818
+
819
+ @dataclass
820
+ class InvokeSubgraphReuseCondition:
821
+ # Per flattened input VT: (InputTag, metadata).
822
+ # (InputTag.TENSOR, TensorMetadata)
823
+ # (InputTag.SYMNODE, sym_num — same object implies same symbol)
824
+ # (InputTag.CONSTANT, value)
825
+ # (InputTag.OBJECT, None)
826
+ # Tensor metadata is checked here because TENSOR_MATCH guards for
827
+ # subgraph inputs may already exist before tracing and thus won't
828
+ # appear in the guard delta.
829
+ input_checks: list[tuple[Any, object]] # list[tuple[InputTag, object]]
830
+
831
+ # Guards captured during the trace (delta + source-mapped).
832
+ # Each entry: (source, handler, expected_value, guard)
833
+ # handler is a pre-resolved GuardCheckSpec from GUARD_VALUE_DISPATCH.
834
+ guards: list[tuple[Source, GuardCheckSpec, object, Guard]]
835
+
836
+ # TreeSpec from pytree.tree_flatten of the (args, kwargs) structure.
837
+ # On cache hit, we verify the new call has the same treespec.
838
+ treespec: pytree.TreeSpec | None = None
839
+
840
+ # All sources accessed via VariableBuilder during the subgraph trace.
841
+ # On cache hit, we check if any modified VT's source is a base of one
842
+ # of these to detect mutations on captured variables.
843
+ traced_sources: OrderedSet[Source] = dataclasses.field(default_factory=OrderedSet)
844
+
845
+
846
+ class InvokeSubgraphCache(HopSubgraphCache):
847
+ def __init__(self) -> None:
848
+ self.autograd_cache: dict[str, Callable] = {}
849
+ self.proxy_dispatch_cache: dict[str, Callable] = {}
850
+ self.functionalize_schema_cache: dict[object, torch._C.FunctionSchema] = {}
851
+ self.dynamo_installed_submodules: dict[CodeType, list[str]] = defaultdict(list)
852
+ self.lazy_bwd_cache: dict[
853
+ str, dict[tuple[object], tuple[torch.fx.GraphModule, int]]
854
+ ] = defaultdict(dict)
855
+ self.effects_cache: dict[
856
+ str, set
857
+ ] = {} # Maps identifier -> set of effect types
858
+ # fn.__code__ → list of (condition, cache_entry) pairs. Walked linearly
859
+ # on lookup; first matching condition wins.
860
+ self.subgraph_reuse_cache: dict[
861
+ CodeType,
862
+ list[tuple[InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry]],
863
+ ] = defaultdict(list)
864
+ # fn_code → {hash_key → cache_entry}. Used by user-provided
865
+ # reuse_hash_fn for O(1) subgraph reuse lookup.
866
+ self.subgraph_reuse_key_cache: dict[
867
+ CodeType, dict[int, InvokeSubgraphReuseEntry]
868
+ ] = defaultdict(dict)
869
+
870
+ def add_dynamo_installed_submodule(
871
+ self, fn_code: CodeType, identifier: str
872
+ ) -> None:
873
+ self.dynamo_installed_submodules[fn_code].append(identifier)
874
+
875
+ def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]:
876
+ return self.dynamo_installed_submodules.get(fn_code, [])
877
+
878
+ def add_autograd_key_entry(self, identifier: str, key: Callable) -> None:
879
+ self.autograd_cache[identifier] = key
880
+
881
+ def get_autograd_key_entry(self, identifier: str) -> Callable | None:
882
+ return self.autograd_cache.get(identifier, None)
883
+
884
+ def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None:
885
+ self.proxy_dispatch_cache[identifier] = key
886
+
887
+ def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None:
888
+ return self.proxy_dispatch_cache.get(identifier, None)
889
+
890
+ def add_functionalize_schema_entry(
891
+ self, key: object, schema: torch._C.FunctionSchema
892
+ ) -> None:
893
+ self.functionalize_schema_cache[key] = schema
894
+
895
+ def get_functionalize_schema_entry(
896
+ self, key: object
897
+ ) -> torch._C.FunctionSchema | None:
898
+ return self.functionalize_schema_cache.get(key, None)
899
+
900
+ def add_lazy_bwd_entry(
901
+ self,
902
+ identifier: str,
903
+ tangent_metadata: tuple[object],
904
+ gmod: torch.fx.GraphModule,
905
+ ) -> int:
906
+ # Save the number of existing graph modules in the dictionary to get the suffix
907
+ num_gmods = len(self.lazy_bwd_cache[identifier])
908
+ self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods)
909
+ return num_gmods
910
+
911
+ def get_lazy_bwd_entry(
912
+ self, identifier: str, tangent_metadata: tuple[object]
913
+ ) -> tuple[torch.fx.GraphModule | None, int | None]:
914
+ if identifier not in self.lazy_bwd_cache:
915
+ return (None, None)
916
+
917
+ return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None))
918
+
919
+ def add_effects(self, identifier: str, effects: set) -> None:
920
+ """Store the effect types for a given invoke_subgraph identifier."""
921
+ if prev_effects := self.effects_cache.get(identifier, None):
922
+ if effects != prev_effects:
923
+ raise AssertionError(
924
+ "Different number of effects were found for invoke_subgraph "
925
+ f"call with identifier {identifier}. \n"
926
+ f"Previously we had the following effects: {prev_effects}.\n"
927
+ f"But now we have: {effects}."
928
+ )
929
+ self.effects_cache[identifier] = effects
930
+
931
+ def get_effects(self, identifier: str) -> set | None:
932
+ """Retrieve the effect types for a given invoke_subgraph identifier."""
933
+ return self.effects_cache.get(identifier, None)
934
+
935
+ def add_reuse_entry(
936
+ self,
937
+ fn_code: CodeType,
938
+ condition: InvokeSubgraphReuseCondition,
939
+ entry: InvokeSubgraphReuseEntry,
940
+ max_reuse_entries: int = 8,
941
+ ) -> None:
942
+ entries = self.subgraph_reuse_cache[fn_code]
943
+ if len(entries) >= max_reuse_entries:
944
+ raise RuntimeError(
945
+ f"invoke_subgraph: exceeded maximum reuse entries "
946
+ f"({max_reuse_entries}) for function code {fn_code}. "
947
+ f"This most likely means a guard keeps failing on every "
948
+ f"invocation, preventing subgraph reuse. "
949
+ f"Set TORCH_LOGS='+hierarchical_compile' to identify which "
950
+ f"guard is failing. If reuse is genuinely not possible and "
951
+ f"you need more cache entries, increase the limit via the "
952
+ f"max_reuse_entries argument to nested_compile_region()."
953
+ )
954
+ entries.append((condition, entry))
955
+
956
+ def find_reuse_entry(
957
+ self,
958
+ fn_code: CodeType,
959
+ evaluator: Callable[
960
+ [InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry], bool
961
+ ],
962
+ ) -> InvokeSubgraphReuseEntry | None:
963
+ entries = self.subgraph_reuse_cache.get(fn_code, [])
964
+ for i, (condition, entry) in enumerate(entries):
965
+ if evaluator(condition, entry):
966
+ # MRU: move the hit entry to the front for faster future lookups
967
+ if i > 0:
968
+ entries.insert(0, entries.pop(i))
969
+ return entry
970
+ return None
971
+
972
+ def find_reuse_entry_by_key(
973
+ self, fn_code: CodeType, hash_key: int
974
+ ) -> InvokeSubgraphReuseEntry | None:
975
+ return self.subgraph_reuse_key_cache.get(fn_code, {}).get(hash_key)
976
+
977
+ def add_reuse_entry_by_key(
978
+ self,
979
+ fn_code: CodeType,
980
+ hash_key: int,
981
+ entry: InvokeSubgraphReuseEntry,
982
+ max_reuse_entries: int = 8,
983
+ ) -> None:
984
+ key_cache = self.subgraph_reuse_key_cache[fn_code]
985
+ if len(key_cache) >= max_reuse_entries and hash_key not in key_cache:
986
+ raise RuntimeError(
987
+ f"invoke_subgraph: exceeded maximum reuse entries "
988
+ f"({max_reuse_entries}) for function code {fn_code} (hash-key path). "
989
+ f"Increase the limit via the max_reuse_entries argument to "
990
+ f"nested_compile_region()."
991
+ )
992
+ key_cache[hash_key] = entry
993
+
994
+
995
+ class HopDispatchSetCache:
996
+ def __init__(self) -> None:
997
+ # Delayed import to avoid circular dependency
998
+ from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
999
+
1000
+ self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()}
1001
+
1002
+ def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None:
1003
+ if op not in self.hop_cache_map:
1004
+ return None
1005
+ return self.hop_cache_map[op] # type: ignore[index]
1006
+
1007
+
1008
+ class _TLSStorage(threading.local):
1009
+ # Default the hot-path attributes to None per thread so that
1010
+ # TracingContext.try_get() / CompileContext.try_get() -- called on every
1011
+ # torch.compile'd call -- hit a present attribute instead of paying for an
1012
+ # AttributeError raise+catch inside getattr(). Without this, a thread that
1013
+ # never ran compilation itself (e.g. a worker thread executing compiled code
1014
+ # compiled on another thread) takes the slow getattr-miss path on every call.
1015
+ def __init__(self) -> None:
1016
+ self.tracing_context: TracingContext | None = None
1017
+ self.compile_context: CompileContext | None = None
1018
+
1019
+
1020
+ _TLS = _TLSStorage()
1021
+
1022
+ """
1023
+ TracingContext is the source of truth for all currently accumulated information
1024
+ needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems
1025
+ are open to managing their own TracingContext with that in mind.
1026
+
1027
+ The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid
1028
+ having to plumb complex subsystems across multiple verticals.
1029
+
1030
+ Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor.
1031
+ Accessing the current tracing context via
1032
+ TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how
1033
+ to plumb objects back up to where frame interpretation happened.
1034
+
1035
+ Note that you can end up with multiple TracingContext for a single compilation
1036
+ of a frame, as we reset the TracingContext whenever we restart analysis.
1037
+ CompileContext is a more overarching context that encompasses multiple restarts.
1038
+ """
1039
+
1040
+
1041
+ class CompileContext:
1042
+ @staticmethod
1043
+ def get() -> CompileContext:
1044
+ if _TLS.compile_context is None:
1045
+ raise AssertionError("compile_context is not set")
1046
+ return _TLS.compile_context
1047
+
1048
+ @staticmethod
1049
+ def try_get() -> CompileContext | None:
1050
+ return getattr(_TLS, "compile_context", None)
1051
+
1052
+ def __init__(self, compile_id: CompileId | None) -> None:
1053
+ if compile_id is not None and not isinstance(compile_id, CompileId):
1054
+ raise AssertionError(
1055
+ f"compile_id must be None or CompileId, got {type(compile_id)}"
1056
+ )
1057
+ self.compile_id: CompileId | None = compile_id
1058
+ self.attempt = 0
1059
+ # Verbose ShapeEnv guards produced.
1060
+ self.shape_env_guards: list[str] = []
1061
+
1062
+ @staticmethod
1063
+ def current_compile_id() -> CompileId | None:
1064
+ self = CompileContext.try_get()
1065
+ if self is None:
1066
+ return None
1067
+ return self.compile_id
1068
+
1069
+ @staticmethod
1070
+ def current_trace_id() -> TraceId | None:
1071
+ self = CompileContext.try_get()
1072
+ if self is None:
1073
+ return None
1074
+ if self.compile_id is None:
1075
+ return None
1076
+ return TraceId(self.compile_id, self.attempt)
1077
+
1078
+
1079
+ @dataclass
1080
+ class InlinedCodeCache:
1081
+ """Cache for code-object-derived data used during inlining."""
1082
+
1083
+ instructions: list[Any]
1084
+ indexof: dict[Any, int]
1085
+ code_options: CodeOptions
1086
+
1087
+
1088
+ class TracingContext:
1089
+ """
1090
+ Provides the currently installed TracingContext, or None.
1091
+
1092
+ Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but
1093
+ will return None.
1094
+ """
1095
+
1096
+ @staticmethod
1097
+ def try_get() -> TracingContext | None:
1098
+ return getattr(_TLS, "tracing_context", None)
1099
+
1100
+ @staticmethod
1101
+ def get() -> TracingContext:
1102
+ if ctx := TracingContext.try_get():
1103
+ return ctx
1104
+ raise RuntimeError(
1105
+ "TracingContext.get() must be called within an ongoing trace."
1106
+ )
1107
+
1108
+ def __init__(self, fake_mode: FakeTensorMode | None) -> None:
1109
+ self.guards_context = GuardsContext()
1110
+ self.module_context = ModuleContext()
1111
+ self.global_context = GlobalContext()
1112
+ self.previously_inlined_functions: dict[Any, Any] = dict()
1113
+ self.previously_cleaned_instructions: dict[Any, Any] = dict()
1114
+ # Combined cache for inlined code data (instructions, indexof, code_options)
1115
+ self.inlined_code_cache: dict[Any, InlinedCodeCache] = dict()
1116
+ self.fake_mode: FakeTensorMode | None = fake_mode
1117
+ self.frame_summary_stack: list[traceback.FrameSummary] = []
1118
+ # This is morally part of frame_summary_stack, but it is kept separate
1119
+ # for clarity. As we process a frame, this variable gets updated
1120
+ # to keep track of what line we are in the function. We make a
1121
+ # function call, this gets cleared and the frame location is pushed
1122
+ # to frame_summary_stack (prepping this variable for the inner frame's
1123
+ # progress)
1124
+ self.loc_in_frame: tuple[str, int, str] | None = None
1125
+ self.loc_in_frame_positions: dis.Positions | None = None
1126
+ # this is only set after aot_autograd
1127
+ self.fw_metadata: ViewAndMutationMeta | None = None
1128
+ # this is only set when the DDPOptimizer is used
1129
+ self.ddp_optimizer_ctx: DDPOptimizerContext | None = None
1130
+ # this is only set after aot_autograd
1131
+ self.aot_graph_name: list[str] | None = None
1132
+ self.params_flat: list[Any] | None = None
1133
+ self.params_flat_unwrap_subclasses: list[Any] | None = None
1134
+ self.params_unwrapped_to_flat_index: list[Any] | None = None
1135
+ # this is for extended return calling convention from backend
1136
+ # compiler to aot_autograd
1137
+ # Per output, what the compiler specified stride of the output is,
1138
+ # or None if no stride is known. This is always the HINT, it
1139
+ # is never a SymInt (it would be better if it was a SymInt, but
1140
+ # I can't conveniently get this from Inductor atm. Also, be
1141
+ # careful not to accidentally induce guards on the SymInt if
1142
+ # you ever do change this in aot_autograd.py; you should check
1143
+ # on permutations preferentially.)
1144
+ self.output_strides: list[tuple[int, ...] | None] | None = None
1145
+ # When this is True, whenever we encounter an int in Dynamo tracing,
1146
+ # we will (1) force unspec it and (2) force it as a size-like unbacked
1147
+ # integer. This is currently used when processing certain lists of
1148
+ # ints that are known to be size-like and may have 0/1 entries that we
1149
+ # must not specialize on.
1150
+ self.force_unspec_int_unbacked_size_like = False
1151
+ # See note [Tensor Fakification and Symbol Caching]
1152
+ self.tensor_to_context = WeakTensorKeyDictionary()
1153
+
1154
+ # If this true, Aot Autograd will return output Fake Tensors with appropriate
1155
+ # meta on the first invocation
1156
+ # see note: [Returning Fake Tensors on First AOT Autograd Call]
1157
+ self.fakify_first_call = False
1158
+ self.hop_dispatch_set_cache = HopDispatchSetCache()
1159
+ # list of code objects for inlined functions
1160
+ self.traced_code: list[CodeType] = []
1161
+ self.cudagraph_annotation: Any = None
1162
+
1163
+ def clear(self) -> None:
1164
+ # Look at the note in output_graph.py in function `save_global_state`
1165
+ # for the context on clearing global context.
1166
+ self.global_context.global_state = {}
1167
+ self.previously_inlined_functions.clear()
1168
+ self.previously_cleaned_instructions.clear()
1169
+ self.inlined_code_cache.clear()
1170
+
1171
+ @staticmethod
1172
+ @contextmanager
1173
+ def patch(**kwargs: Any) -> Generator[None, None, None]:
1174
+ prior = {}
1175
+ ctx = TracingContext.get()
1176
+
1177
+ for key in kwargs:
1178
+ # KeyError on invalid entry
1179
+ prior[key] = getattr(ctx, key)
1180
+ for key, val in kwargs.items():
1181
+ setattr(ctx, key, val)
1182
+ try:
1183
+ yield
1184
+ finally:
1185
+ for key, val in prior.items():
1186
+ setattr(ctx, key, val)
1187
+
1188
+ @staticmethod
1189
+ def extract_stack() -> traceback.StackSummary:
1190
+ self = TracingContext.try_get()
1191
+ if self is None:
1192
+ return traceback.StackSummary()
1193
+ stack = self.frame_summary_stack
1194
+ if self.loc_in_frame is not None:
1195
+ stack = stack + [self._populate_loc_in_frame_summary()]
1196
+ return traceback.StackSummary.from_list(stack)
1197
+
1198
+ def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary:
1199
+ if self.loc_in_frame is None:
1200
+ raise AssertionError("loc_in_frame must not be None")
1201
+ filename, lineno, frame_name = self.loc_in_frame
1202
+ # colno/end_colno kwargs were added to FrameSummary in 3.11
1203
+ kwargs: dict[str, Any] = {}
1204
+ if sys.version_info >= (3, 11) and self.loc_in_frame_positions is not None:
1205
+ kwargs["colno"] = self.loc_in_frame_positions.col_offset
1206
+ kwargs["end_colno"] = self.loc_in_frame_positions.end_col_offset
1207
+ return traceback.FrameSummary(
1208
+ filename,
1209
+ lineno,
1210
+ frame_name,
1211
+ lookup_line=False,
1212
+ **kwargs,
1213
+ )
1214
+
1215
+ # Call this when you want to call into some code that isn't necessarily
1216
+ # associated with the current frame state
1217
+ @staticmethod
1218
+ @contextlib.contextmanager
1219
+ def clear_frame() -> Generator[None, None, None]:
1220
+ tc = TracingContext.get()
1221
+ with (
1222
+ unittest.mock.patch.object(tc, "frame_summary_stack", []),
1223
+ unittest.mock.patch.object(tc, "loc_in_frame", None),
1224
+ unittest.mock.patch.object(tc, "loc_in_frame_positions", None),
1225
+ ):
1226
+ try:
1227
+ yield
1228
+ except Exception as e:
1229
+ # Prevent real_stack from getting attached
1230
+ #
1231
+ # The invariant is that if an Exception as real_stack, we've
1232
+ # appropriately attached a user stack and we no longer need to
1233
+ # attach anything. Because we cannot conveniently interpose
1234
+ # when an exception is thrown, we instead interpose everywhere
1235
+ # we set what the user stack is set (using the context
1236
+ # manager). However, our compiler stack does "tail calls"
1237
+ # (when it calls into user compiler), at which point the
1238
+ # parent exception frames would incorrectly attach an
1239
+ # incorrect frame.
1240
+ #
1241
+ # However, if, somehow, someone raised an exception with this
1242
+ # scope that had a stack (for example, because they are
1243
+ # restoring the user stack state appropriately as they process
1244
+ # node by node), we should respect it. Thus, we cannot
1245
+ # unconditionally set None.
1246
+ if not hasattr(e, "real_stack"):
1247
+ e.real_stack = None # type: ignore[attr-defined]
1248
+ raise
1249
+
1250
+ @staticmethod
1251
+ @contextlib.contextmanager
1252
+ def current_frame(
1253
+ frame_summary: traceback.FrameSummary | None,
1254
+ ) -> Generator[None, None, None]:
1255
+ # frame_summary can be None to solely take advantage of real_stack
1256
+ # attachment to thrown exceptions
1257
+ tc = TracingContext.get()
1258
+ if frame_summary is not None:
1259
+ tc.frame_summary_stack.append(frame_summary)
1260
+ old = tc.loc_in_frame
1261
+ old_positions = tc.loc_in_frame_positions
1262
+ tc.loc_in_frame = None
1263
+ tc.loc_in_frame_positions = None
1264
+ try:
1265
+ yield
1266
+ except Exception as e:
1267
+ if not hasattr(e, "real_stack"):
1268
+ e.real_stack = tc.extract_stack() # type: ignore[attr-defined]
1269
+ raise
1270
+ finally:
1271
+ if frame_summary is not None:
1272
+ tc.frame_summary_stack.pop()
1273
+ tc.loc_in_frame = old
1274
+ tc.loc_in_frame_positions = old_positions
1275
+
1276
+ @staticmethod
1277
+ @contextlib.contextmanager
1278
+ def report_output_strides() -> Generator[
1279
+ list[tuple[int, ...] | None] | None, None, None
1280
+ ]:
1281
+ tc = TracingContext.try_get()
1282
+ if tc is None:
1283
+ yield None
1284
+ return
1285
+ old_output_strides = tc.output_strides
1286
+ tc.output_strides = []
1287
+ try:
1288
+ yield tc.output_strides
1289
+ finally:
1290
+ tc.output_strides = old_output_strides
1291
+
1292
+ @staticmethod
1293
+ def set_current_loc(
1294
+ filename: str,
1295
+ lineno: int,
1296
+ frame_name: str,
1297
+ positions: dis.Positions | None = None,
1298
+ ) -> None:
1299
+ # Save the current location in the frame. Lazily generate the
1300
+ # framesummary.
1301
+ tc = TracingContext.get()
1302
+ tc.loc_in_frame = (filename, lineno, frame_name)
1303
+ tc.loc_in_frame_positions = positions
1304
+
1305
+ @staticmethod
1306
+ def get_traced_code() -> list[CodeType] | None:
1307
+ tc = TracingContext.try_get()
1308
+ if tc is None:
1309
+ return None
1310
+ return tc.traced_code
1311
+
1312
+
1313
+ @contextmanager
1314
+ def compile_context(
1315
+ context: CompileContext | None,
1316
+ ) -> Generator[CompileContext | None, None, None]:
1317
+ old_context = getattr(_TLS, "compile_context", None)
1318
+ _TLS.compile_context = context
1319
+ try:
1320
+ yield context
1321
+ finally:
1322
+ _TLS.compile_context = old_context
1323
+
1324
+
1325
+ @contextmanager
1326
+ def tracing(
1327
+ context: TracingContext | None,
1328
+ ) -> Generator[TracingContext | None, None, None]:
1329
+ """
1330
+ This function installs the passed in tracing context as a dynamic scoped
1331
+ global variable.
1332
+
1333
+ Calls to TracingContext.get() while not under a `with tracing()` context
1334
+ will return None.
1335
+ """
1336
+ old_context = getattr(_TLS, "tracing_context", None)
1337
+ _TLS.tracing_context = context
1338
+ try:
1339
+ yield context
1340
+ except Exception as e:
1341
+ if not hasattr(e, "real_stack") and context is not None:
1342
+ e.real_stack = context.extract_stack() # type: ignore[attr-defined]
1343
+ raise
1344
+ finally:
1345
+ if (
1346
+ context is not None
1347
+ and context.fake_mode is not None
1348
+ and context.fake_mode.shape_env is not None
1349
+ ):
1350
+ context.fake_mode.shape_env.cleanup()
1351
+ _TLS.tracing_context = old_context
1352
+
1353
+
1354
+ @overload
1355
+ def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ...
1356
+
1357
+
1358
+ @overload
1359
+ def dataclass_with_cached_hash(
1360
+ cls: None = None, **kwargs: Any
1361
+ ) -> Callable[[type[T]], type[T]]: ...
1362
+
1363
+
1364
+ @dataclass_transform()
1365
+ def dataclass_with_cached_hash(
1366
+ cls: type[T] | None = None, **kwargs: Any
1367
+ ) -> type[T] | Callable[[type[T]], type[T]]:
1368
+ def wrap(cls_inner: type[T]) -> type[T]:
1369
+ new_cls = dataclasses.dataclass(cls_inner, **kwargs)
1370
+ old_hash = cls_inner.__hash__
1371
+
1372
+ def __hash__(self) -> int:
1373
+ if not hasattr(self, "_hash"):
1374
+ object.__setattr__(self, "_hash", old_hash(self))
1375
+ return self._hash
1376
+
1377
+ def __reduce__(self):
1378
+ # Exclude _hash from pickling to ensure deterministic cache keys.
1379
+ # The _hash is a cached value that can be nondeterministically computed
1380
+ # (e.g., based on id() of objects), so it should not affect pickling.
1381
+ fields = dataclasses.fields(self)
1382
+ field_values = tuple(getattr(self, f.name) for f in fields if f.init)
1383
+ return (self.__class__, field_values)
1384
+
1385
+ new_cls.__hash__ = __hash__
1386
+ new_cls.__reduce__ = __reduce__
1387
+ return new_cls # type: ignore[return-value]
1388
+
1389
+ if cls is None:
1390
+ return wrap
1391
+
1392
+ return wrap(cls)
1393
+
1394
+
1395
+ # Subclasses can be found in torch/_dynamo/source.py
1396
+ # TODO(voz): Consider a toplevel torch/_source.py
1397
+ @dataclass_with_cached_hash(frozen=True)
1398
+ class Source:
1399
+ def is_dict_key(self) -> bool:
1400
+ return False
1401
+
1402
+ def is_ephemeral(self) -> bool:
1403
+ return False
1404
+
1405
+ def reconstruct(self, codegen: PyCodegen) -> None:
1406
+ raise NotImplementedError
1407
+
1408
+ def reconstruct_pycode(self, codegen: PyCodegen) -> str:
1409
+ """
1410
+ Reconstructs the source into a string of Python code. This method should
1411
+ be eventually implemented for all subclasses of Source to achieve full
1412
+ coverage of python wrapper code generation.
1413
+ """
1414
+ raise NotImplementedError
1415
+
1416
+ @functools.cached_property
1417
+ def guard_source(self) -> GuardSource:
1418
+ raise NotImplementedError
1419
+
1420
+ @property
1421
+ def _name_template(self) -> str:
1422
+ """
1423
+ A template for the name of the source. Used to prevent code duplication between
1424
+ `name` and `get_value`.
1425
+
1426
+ For non-ChainedSources, `name` and `get_value` use the returned string directly.
1427
+
1428
+ For ChainedSources, `name` and `get_value` expect the return to be a format string
1429
+ with `{0}` present - `name` and `get_value` will apply different values to this function's
1430
+ returned format string.
1431
+ """
1432
+ raise NotImplementedError
1433
+
1434
+ @functools.cached_property
1435
+ def name(self) -> str:
1436
+ return self._name_template
1437
+
1438
+ def get_value(
1439
+ self,
1440
+ globals: dict[str, Any],
1441
+ locals: dict[str, Any],
1442
+ cache: dict[Source, Any],
1443
+ ) -> Any:
1444
+ if self in cache:
1445
+ return cache[self]
1446
+ value = eval(self._name_template, globals, locals)
1447
+ cache[self] = value
1448
+ return value
1449
+
1450
+ def make_guard(self, fn: Callable[..., Any]) -> Guard:
1451
+ if self.guard_source is GuardSource.CONSTANT:
1452
+ raise NotImplementedError
1453
+ return Guard(self, fn)
1454
+
1455
+ def is_specialized_nn_module(self) -> bool:
1456
+ return self.guard_source.is_specialized_nn_module()
1457
+
1458
+ def subguards_allowed(self) -> bool:
1459
+ """True if you can guard on attributes of this"""
1460
+ return self.guard_source != GuardSource.SYNTHETIC_LOCAL
1461
+
1462
+ def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source:
1463
+ # Frozen dataclass, so returning self is effectively a clone.
1464
+ # Subclasses with mutable state should override.
1465
+ if transform_fn is not None:
1466
+ return transform_fn(self)
1467
+ return self
1468
+
1469
+
1470
+ # Subclasses can be found in torch/_dynamo/source.py
1471
+ @dataclass_with_cached_hash(frozen=True)
1472
+ class ChainedSource(Source):
1473
+ base: Source
1474
+
1475
+ def is_dict_key(self) -> bool:
1476
+ # Recurse until you either hit a ConstDictKey or a Source
1477
+ return self.base.is_dict_key()
1478
+
1479
+ def is_ephemeral(self) -> bool:
1480
+ return self.base.is_ephemeral()
1481
+
1482
+ @functools.cached_property
1483
+ def guard_source(self) -> GuardSource:
1484
+ return self.base.guard_source
1485
+
1486
+ def get_base(self) -> Source:
1487
+ current: Source = self
1488
+ while isinstance(current, ChainedSource):
1489
+ current = current.base
1490
+ return current
1491
+
1492
+ @functools.cached_property
1493
+ def name(self) -> str:
1494
+ return self._name_template.format(self.base.name)
1495
+
1496
+ def get_value(
1497
+ self,
1498
+ globals: dict[str, Any],
1499
+ locals: dict[str, Any],
1500
+ cache: dict[Source, Any],
1501
+ ) -> Any:
1502
+ if self in cache:
1503
+ return cache[self]
1504
+ tmpvar = "tmp"
1505
+ counter = 0
1506
+ while tmpvar in locals:
1507
+ tmpvar = f"tmp{counter}"
1508
+ counter += 1
1509
+ locals[tmpvar] = self.base.get_value(globals, locals, cache)
1510
+ value = eval(self._name_template.format(tmpvar), globals, locals)
1511
+ del locals[tmpvar]
1512
+ cache[self] = value
1513
+ return value
1514
+
1515
+ def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source:
1516
+ cloned_fields: dict[str, Any] = {"base": self.base.clone(transform_fn)}
1517
+ for f in dataclasses.fields(self):
1518
+ if f.name == "base":
1519
+ continue
1520
+ val = getattr(self, f.name)
1521
+ if isinstance(val, Source):
1522
+ cloned_fields[f.name] = val.clone(transform_fn)
1523
+ result = dataclasses.replace(self, **cloned_fields)
1524
+ if transform_fn is not None:
1525
+ result = transform_fn(result)
1526
+ return result
1527
+
1528
+
1529
+ def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None:
1530
+ """
1531
+ Attempts to "detect" what the current fake mode is. If there is one ambiently
1532
+ available from TracingContext, we preferentially use that. Otherwise, we
1533
+ heuristically detect the fake mode via the following sources, in order of
1534
+ priority:
1535
+
1536
+ - Currently active fake mode on stack
1537
+ - Fake mode associated with passed in tensors (inputs does not
1538
+ have to be flattened)
1539
+ """
1540
+ from torch._subclasses.fake_tensor import (
1541
+ FakeTensor,
1542
+ FakeTensorMode,
1543
+ get_plain_tensors,
1544
+ is_fake_tensor,
1545
+ maybe_get_fake_mode,
1546
+ )
1547
+
1548
+ # If TracingContext has a fake_mode, use it authoritatively.
1549
+ # This is the case when Dynamo is driving compilation - any fake tensors
1550
+ # from other modes in the inputs will be refakified by the caller.
1551
+ if context := TracingContext.try_get():
1552
+ fake_mode = context.fake_mode
1553
+ if fake_mode is not None:
1554
+ return fake_mode
1555
+
1556
+ fake_modes = []
1557
+
1558
+ from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
1559
+
1560
+ for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
1561
+ if isinstance(m, FakeTensorMode):
1562
+ fake_modes.append((m, "active fake mode", i))
1563
+
1564
+ flat_inputs = pytree.tree_leaves(inputs)
1565
+ for i, flat_input in enumerate(flat_inputs):
1566
+ if is_fake_tensor(flat_input):
1567
+ fake_modes.append((maybe_get_fake_mode(flat_input), "fake tensor input", i))
1568
+ if is_traceable_wrapper_subclass(flat_input):
1569
+ out: list[torch.Tensor | int | torch.SymInt] = []
1570
+ get_plain_tensors(flat_input, out=out) # type: ignore[arg-type]
1571
+ fake_tensors: list[FakeTensor] = [
1572
+ x
1573
+ for x in out
1574
+ if isinstance(x, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR
1575
+ ]
1576
+ fake_modes.extend(
1577
+ [
1578
+ (maybe_get_fake_mode(tensor), f"subclass input {i}", ix)
1579
+ for ix, tensor in enumerate(fake_tensors)
1580
+ ]
1581
+ )
1582
+
1583
+ if fake_modes:
1584
+ fake_mode, desc1, i1 = fake_modes[0]
1585
+ for m, desc2, i2 in fake_modes[1:]:
1586
+ if fake_mode is not m:
1587
+ raise AssertionError(
1588
+ f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n"
1589
+ f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n"
1590
+ f"fake mode from {desc2} {i2} allocated at:\n{m.stack}"
1591
+ )
1592
+
1593
+ return fake_mode
1594
+ else:
1595
+ return None
1596
+
1597
+
1598
+ def active_fake_mode() -> FakeTensorMode | None:
1599
+ """
1600
+ Inspects the dispatch mode stack for an active fake mode and returns it.
1601
+ Returns None if no fake mode is active.
1602
+ """
1603
+ from torch._subclasses.fake_tensor import FakeTensorMode
1604
+ from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
1605
+
1606
+ for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
1607
+ if isinstance(m, FakeTensorMode):
1608
+ return m
1609
+
1610
+ return None
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.flex_gemm import flex_gemm
22
+ from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map
23
+ from torch._higher_order_ops.hints_wrap import hints_wrapper
24
+ from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise
25
+ from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function
26
+ from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
27
+ from torch._higher_order_ops.local_map import local_map_hop
28
+ from torch._higher_order_ops.map import map
29
+ from torch._higher_order_ops.out_dtype import out_dtype
30
+ from torch._higher_order_ops.print import print
31
+ from torch._higher_order_ops.run_const_graph import run_const_graph
32
+ from torch._higher_order_ops.scan import scan
33
+ from torch._higher_order_ops.strict_mode import strict_mode
34
+ from torch._higher_order_ops.switch import switch
35
+ from torch._higher_order_ops.torchbind import call_torchbind
36
+ from torch._higher_order_ops.while_loop import (
37
+ while_loop,
38
+ while_loop_stack_output_op as while_loop_stack_output,
39
+ )
40
+ from torch._higher_order_ops.wrap import (
41
+ dynamo_bypassing_wrapper,
42
+ inductor_compiled_code,
43
+ tag_activation_checkpoint,
44
+ wrap_activation_checkpoint,
45
+ wrap_with_autocast,
46
+ wrap_with_set_grad_enabled,
47
+ )
48
+
49
+
50
+ __all__ = [
51
+ "cond",
52
+ "switch",
53
+ "while_loop",
54
+ "invoke_subgraph",
55
+ "scan",
56
+ "map",
57
+ "flex_attention",
58
+ "flex_attention_backward",
59
+ "hints_wrapper",
60
+ "BaseHOP",
61
+ "flat_apply",
62
+ "foreach_map",
63
+ "_foreach_map",
64
+ "flex_gemm",
65
+ "with_effects",
66
+ "tag_activation_checkpoint",
67
+ "auto_functionalized",
68
+ "auto_functionalized_v2",
69
+ "associative_scan",
70
+ "out_dtype",
71
+ "executorch_call_delegate",
72
+ "call_torchbind",
73
+ "run_const_graph",
74
+ "InvokeQuant",
75
+ "invoke_leaf_function",
76
+ "invoke_quant",
77
+ "invoke_quant_packed",
78
+ "wrap_with_set_grad_enabled",
79
+ "wrap_with_autocast",
80
+ "wrap_activation_checkpoint",
81
+ "dynamo_bypassing_wrapper",
82
+ "strict_mode",
83
+ "aoti_call_delegate",
84
+ "map",
85
+ "while_loop_stack_output",
86
+ "local_map_hop",
87
+ "print",
88
+ "inductor_compiled_code",
89
+ "inline_asm_elementwise",
90
+ "register_hook",
91
+ ]
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.83 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc ADDED
Binary file (2.89 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc ADDED
Binary file (8.17 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc ADDED
Binary file (41.5 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc ADDED
Binary file (50 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc ADDED
Binary file (11.5 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc ADDED
Binary file (32.7 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc ADDED
Binary file (11.3 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc ADDED
Binary file (15.2 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc ADDED
Binary file (9.09 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc ADDED
Binary file (8.98 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc ADDED
Binary file (59.4 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc ADDED
Binary file (17.7 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc ADDED
Binary file (1.42 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc ADDED
Binary file (6.66 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc ADDED
Binary file (12.8 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc ADDED
Binary file (42 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc ADDED
Binary file (52.5 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc ADDED
Binary file (28.5 kB). View file