jasonfan commited on
Commit
c7926df
·
verified ·
1 Parent(s): 556ca7c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/db/examples/user_input_mutation.py +17 -0
  2. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/__init__.py +0 -0
  3. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py +32 -0
  4. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py +45 -0
  5. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/__init__.py +1 -0
  6. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/_node_metadata_hook.py +81 -0
  7. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py +250 -0
  8. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/collect_tracepoints_pass.py +146 -0
  9. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/constant_folding.py +303 -0
  10. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py +99 -0
  11. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/insert_custom_op_guards.py +78 -0
  12. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/lift_constants_pass.py +414 -0
  13. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/remove_runtime_assertions.py +36 -0
  14. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py +189 -0
  15. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py +673 -0
  16. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py +121 -0
  17. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py +65 -0
  18. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_with_hop_pass_util.py +187 -0
  19. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/__init__.py +0 -0
  20. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/dynamic_shapes.py +322 -0
  21. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/export_schema.thrift +362 -0
  22. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema.py +505 -0
  23. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema.yaml +536 -0
  24. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema_check.py +738 -0
  25. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/serialize.py +0 -0
  26. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/union.py +71 -0
  27. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/__init__.py +5 -0
  28. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__init__.py +5 -0
  29. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py +145 -0
  30. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py +321 -0
  31. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py +121 -0
  32. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py +273 -0
  33. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/__init__.py +5 -0
  34. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py +1442 -0
  35. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py +813 -0
  36. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/dispatch_and_compile_graph.py +338 -0
  37. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/functional_utils.py +523 -0
  38. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py +438 -0
  39. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/jit_compile_runtime_wrappers.py +1845 -0
  40. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/logging_utils.py +146 -0
  41. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py +0 -0
  42. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/schemas.py +968 -0
  43. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py +103 -0
  44. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py +476 -0
  45. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/traced_function_transforms.py +924 -0
  46. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/utils.py +515 -0
  47. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/aot_autograd.py +1737 -0
  48. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/apis.py +448 -0
  49. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/autograd_function.py +777 -0
  50. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/batch_norm_replacement.py +27 -0
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/db/examples/user_input_mutation.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+
4
+
5
+ class UserInputMutation(torch.nn.Module):
6
+ """
7
+ Directly mutate user input in forward
8
+ """
9
+
10
+ def forward(self, x):
11
+ x.mul_(2)
12
+ return x.cos()
13
+
14
+
15
+ example_args = (torch.randn(3, 2),)
16
+ tags = {"torch.mutation"}
17
+ model = UserInputMutation()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+
4
+ NodeMetadataValue = Any
5
+
6
+
7
+ PROTECTED_KEYS: set[str] = {
8
+ "val",
9
+ "stack_trace",
10
+ "nn_module_stack",
11
+ "debug_handle",
12
+ "tensor_meta",
13
+ }
14
+
15
+
16
+ class NodeMetadata:
17
+ def __init__(self, data: dict[str, Any]) -> None:
18
+ self.data: dict[str, Any] = data.copy()
19
+
20
+ def __getitem__(self, key: str) -> NodeMetadataValue:
21
+ return self.data[key]
22
+
23
+ def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue:
24
+ if key in PROTECTED_KEYS:
25
+ raise RuntimeError(f"Could not override node key: {key}")
26
+ self.data[key] = value
27
+
28
+ def __contains__(self, key: str) -> bool:
29
+ return key in self.data
30
+
31
+ def copy(self) -> "NodeMetadata":
32
+ return NodeMetadata(self.data.copy())
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyre-strict
2
+ from collections.abc import Iterable, Iterator
3
+ from typing import Generic, TypeVar, Union
4
+
5
+ import torch
6
+
7
+
8
+ _T = TypeVar("_T")
9
+
10
+
11
+ class ProxyValue(Generic[_T]):
12
+ # pyre-ignore
13
+ def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]):
14
+ # pyre-ignore
15
+ self.data = data
16
+ self.proxy_or_node = proxy
17
+
18
+ @property
19
+ def node(self) -> torch.fx.Node:
20
+ if isinstance(self.proxy_or_node, torch.fx.Node):
21
+ return self.proxy_or_node
22
+ assert isinstance(self.proxy_or_node, torch.fx.Proxy)
23
+ return self.proxy_or_node.node
24
+
25
+ @property
26
+ def proxy(self) -> torch.fx.Proxy:
27
+ if not isinstance(self.proxy_or_node, torch.fx.Proxy):
28
+ raise RuntimeError(
29
+ f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}"
30
+ )
31
+ return self.proxy_or_node
32
+
33
+ def to_tensor(self) -> torch.Tensor:
34
+ assert isinstance(self.data, torch.Tensor)
35
+ return self.data
36
+
37
+ def is_tensor(self) -> bool:
38
+ return isinstance(self.data, torch.Tensor)
39
+
40
+ # pyre-ignore
41
+ def __iter__(self) -> Iterator[_T]:
42
+ yield from self.data
43
+
44
+ def __bool__(self) -> bool:
45
+ return bool(self.data)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/_node_metadata_hook.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch.fx.graph_module import GraphModule
7
+
8
+
9
+ _EMPTY_NN_MODULE_STACK_KEY = "_empty_nn_module_stack_from_metadata_hook"
10
+
11
+
12
+ def _node_metadata_hook(node: torch.fx.Node, stack_trace: Optional[str] = None) -> None:
13
+ """
14
+ Hook for adding the appropriate metadata to nodes that are created during a
15
+ pass using graph.create_node. An example of how to use it:
16
+
17
+ ```
18
+ with _set_node_metadata_hook(gm,
19
+ functools.partial(_node_metadata_hook, stack_trace="file")
20
+ ):
21
+ pass(gm)
22
+ ```
23
+
24
+ This hook should not work for all generic cases -- specifically it assumes
25
+ that nodes being added are only call_function nodes, and copies over the
26
+ first argument node's nn_module_stack.
27
+ """
28
+ assert node.op == "call_function" and callable(node.target)
29
+
30
+ arg_meta = [arg.meta for arg in node.args if isinstance(arg, torch.fx.Node)]
31
+ assert len(arg_meta) >= 1
32
+ arg_meta = arg_meta[0]
33
+
34
+ if (
35
+ isinstance(node.target, torch._ops.OpOverload)
36
+ and len(node.target._schema.returns) == 0
37
+ ):
38
+ node.meta["val"] = None
39
+ else:
40
+ fake_args = [
41
+ arg.meta["val"] if isinstance(arg, torch.fx.Node) else arg
42
+ for arg in node.args
43
+ ]
44
+ fake_res = node.target(*fake_args)
45
+ node.meta["val"] = fake_res
46
+
47
+ node.meta["stack_trace"] = stack_trace
48
+ node.meta["nn_module_stack"] = arg_meta.get(
49
+ "nn_module_stack",
50
+ {
51
+ _EMPTY_NN_MODULE_STACK_KEY: (
52
+ _EMPTY_NN_MODULE_STACK_KEY,
53
+ _EMPTY_NN_MODULE_STACK_KEY,
54
+ )
55
+ },
56
+ )
57
+ node.meta["torch_fn"] = (
58
+ f"{node.target.__name__}_0",
59
+ f"{node.target.__class__.__name__}.{node.target.__name__}",
60
+ )
61
+
62
+
63
+ @contextlib.contextmanager
64
+ def _set_node_metadata_hook(gm: torch.fx.GraphModule, f):
65
+ """
66
+ Takes a callable which will be called after we create a new node. The
67
+ callable takes the newly created node as input and returns None.
68
+ """
69
+ assert callable(f), "node_metadata_hook must be a callable."
70
+
71
+ # Add the hook to all submodules
72
+ for m in gm.modules():
73
+ if isinstance(m, GraphModule):
74
+ m._register_create_node_hook(f)
75
+ try:
76
+ yield
77
+ finally:
78
+ # Restore hook for all submodules
79
+ for m in gm.modules():
80
+ if isinstance(m, GraphModule):
81
+ m._unregister_create_node_hook(f)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ import operator
4
+ import traceback
5
+ from functools import partial
6
+ from typing import Callable, NamedTuple
7
+
8
+ import sympy
9
+
10
+ import torch
11
+ import torch.fx
12
+ from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
13
+ from torch.fx.passes.infra.pass_base import PassBase, PassResult
14
+ from torch.utils._sympy.numbers import int_oo
15
+ from torch.utils._sympy.value_ranges import ValueRanges
16
+
17
+
18
+ __all__ = ["InputDim"]
19
+
20
+
21
+ class InputDim(NamedTuple):
22
+ input_name: str
23
+ dim: int
24
+
25
+
26
+ def _convert_to_int(val):
27
+ # Convert simple sympy Integers into concrete int
28
+ if val in (sympy.oo, int_oo):
29
+ return math.inf
30
+ if val in (-sympy.oo, -int_oo):
31
+ return -math.inf
32
+ if isinstance(val, sympy.Integer):
33
+ return int(val)
34
+ raise RuntimeError("Export constraints cannot be non-integer expressions")
35
+
36
+
37
+ def _convert_range_to_int(range: ValueRanges):
38
+ assert isinstance(range, ValueRanges)
39
+ min_val = _convert_to_int(range.lower)
40
+ max_val = _convert_to_int(range.upper)
41
+ return min_val, max_val
42
+
43
+
44
+ class _AddRuntimeAssertionsForInlineConstraintsPass(PassBase):
45
+ def __init__(
46
+ self,
47
+ range_constraints: dict[sympy.Symbol, ValueRanges],
48
+ ):
49
+ super().__init__()
50
+ self.range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints
51
+ self._asserts_generated_unbacked_symbols: set[sympy.Symbol] = set()
52
+ self.counter = 0
53
+
54
+ def _assert_range_constraint(self, node, lower, upper, assert_msg):
55
+ last_node = node
56
+ if lower > -math.inf:
57
+ last_node = self._insert_assert_async(
58
+ last_node, operator.ge, node, lower, assert_msg
59
+ )
60
+
61
+ if upper < math.inf:
62
+ last_node = self._insert_assert_async(
63
+ last_node, operator.le, node, upper, assert_msg
64
+ )
65
+
66
+ def _insert_assert_async(self, last_node, op, lower, upper, assert_msg):
67
+ """
68
+ Inserts assert_async call_function nodes in the graph. This function is
69
+ called **during** the interpreter-based pass.
70
+ """
71
+ self.counter += 1
72
+ graph = last_node.graph
73
+ with graph.inserting_after(last_node):
74
+ cmp = graph.call_function(op, (lower, upper), {})
75
+ with graph.inserting_after(cmp):
76
+ cmp_tensor = graph.call_function(
77
+ torch.ops.aten.scalar_tensor.default, (cmp,), {}
78
+ )
79
+ with graph.inserting_after(cmp_tensor):
80
+ assert_async = graph.call_function(
81
+ torch.ops.aten._assert_async.msg,
82
+ (cmp_tensor, assert_msg),
83
+ {},
84
+ )
85
+ return assert_async
86
+
87
+ def call(self, graph_module) -> PassResult:
88
+ self.existing_inline_assertions = _get_existing_inline_assertions(
89
+ graph_module, self.range_constraints
90
+ )
91
+
92
+ for module in graph_module.modules():
93
+ if not isinstance(module, torch.fx.GraphModule):
94
+ continue
95
+ for node in module.graph.nodes:
96
+ if node.op != "call_function":
97
+ continue
98
+ if "val" not in node.meta:
99
+ continue
100
+
101
+ val = node.meta["val"]
102
+ # In general, we may have to deal the case such as: ret[1].shape[0].
103
+ # We need first find out what symbols require assertion, then we need to follow the path
104
+ # from ret to the symbol, construct the proxies along the way and construct the messages
105
+ # piece-wise at the same time.
106
+ #
107
+ # We use post-order traversal to collect all the proxies callbacks needed, construct
108
+ # the error message callbacks, and at the top-level traversal tree we execute all the callbacks.
109
+ # We need the callbacks because, in order to call the function to create a proxy for shape[0], we
110
+ # need the proxy for shape, which further requires the proxy for ret[1], etc.
111
+
112
+ def add_assertions(val):
113
+ call_backs: list[Callable] = []
114
+ messages: list[str] = []
115
+ if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)):
116
+ symbol = val.node.expr
117
+ if symbol in self.existing_inline_assertions:
118
+ return call_backs, messages
119
+ if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols(
120
+ symbol
121
+ ):
122
+ if symbol in self._asserts_generated_unbacked_symbols:
123
+ return call_backs, messages
124
+ # We only care about unbacked symints for these inline
125
+ # constraints, which are prefixed with 'u'
126
+ constraint = self.range_constraints[symbol]
127
+ min_val, max_val = _convert_range_to_int(constraint)
128
+ assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]."
129
+ call_backs.append(
130
+ partial(
131
+ self._assert_range_constraint,
132
+ lower=min_val,
133
+ upper=max_val,
134
+ )
135
+ )
136
+ messages.append(assert_msg)
137
+ self._asserts_generated_unbacked_symbols.add(symbol)
138
+
139
+ elif isinstance(val, torch.Tensor):
140
+ for i, sym in enumerate(val.shape):
141
+ cbs, msgs = add_assertions(sym)
142
+ for cb, msg in zip(cbs, msgs):
143
+
144
+ def sym_size_cb(node, assert_msg, dim):
145
+ with node.graph.inserting_after(node):
146
+ dim_node = module.graph.call_function(
147
+ torch.ops.aten.sym_size.int,
148
+ (node, dim),
149
+ {},
150
+ )
151
+ cb(node=dim_node, assert_msg=assert_msg)
152
+
153
+ call_backs.append(partial(sym_size_cb, dim=i))
154
+ messages.append(f".shape[{i}]" + msg)
155
+ return call_backs, messages
156
+
157
+ callbacks, messages = add_assertions(val)
158
+ for cb, msg in zip(callbacks, messages):
159
+ cb(node=node, assert_msg=f"{node}" + msg)
160
+
161
+ module.recompile()
162
+
163
+ # Sometimes this pass would return a wrong graph where we have mismatched
164
+ # node names in signature. Before we fix it, let's just skip it.
165
+ if (
166
+ self.counter == 0
167
+ and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass
168
+ ):
169
+ return PassResult(graph_module, False)
170
+
171
+ # Populate the stack trace with dummy vals to respect IR
172
+ for node in graph_module.graph.nodes:
173
+ if not node.meta.get("stack_trace", None) and node.op not in [
174
+ "placeholder",
175
+ "output",
176
+ ]:
177
+ node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1))
178
+ return PassResult(graph_module, True)
179
+
180
+
181
+ def _get_existing_inline_assertions(
182
+ graph_module: torch.fx.GraphModule,
183
+ range_constraints: dict[sympy.Symbol, ValueRanges],
184
+ ) -> dict[sympy.Symbol, ValueRanges]:
185
+ existing_inline_assertions: dict[sympy.Symbol, ValueRanges] = {}
186
+
187
+ for module in graph_module.modules():
188
+ if not isinstance(module, torch.fx.GraphModule):
189
+ continue
190
+
191
+ # Find all the existing inline assertions. They will look something like:
192
+ # %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {})
193
+ # %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {})
194
+ # %_assert_scalar = call_function[target=torch.ops.aten._assert_scalar.default](args = (%scalar_tensor, "..."), kwargs = {})
195
+ for node in module.graph.nodes:
196
+ if node.target != torch.ops.aten._assert_scalar.default:
197
+ continue
198
+
199
+ compare_arg = node.args[0]
200
+ if not (
201
+ isinstance(compare_arg, torch.fx.Node)
202
+ and compare_arg.op == "call_function"
203
+ and compare_arg.target in (operator.le, operator.ge)
204
+ and len(compare_arg.args) == 2
205
+ ):
206
+ continue
207
+
208
+ compare_op = compare_arg.target
209
+ lhs, rhs = compare_arg.args
210
+
211
+ def maybe_get_symint(x):
212
+ if (
213
+ isinstance(x, torch.fx.Node)
214
+ and "val" in x.meta
215
+ and isinstance(x.meta["val"], torch.SymInt)
216
+ ):
217
+ return x.meta["val"].node.expr
218
+ return x
219
+
220
+ lhs = maybe_get_symint(lhs)
221
+ rhs = maybe_get_symint(rhs)
222
+
223
+ if compare_op == operator.ge:
224
+ lhs, rhs = rhs, lhs
225
+
226
+ if isinstance(lhs, sympy.Symbol) and isinstance(rhs, int):
227
+ symint = lhs
228
+ scalar = rhs
229
+ elif isinstance(rhs, sympy.Symbol) and isinstance(lhs, int):
230
+ symint = rhs
231
+ scalar = lhs
232
+ else:
233
+ continue
234
+
235
+ if symint not in range_constraints:
236
+ raise RuntimeError(
237
+ f"Unable to find symint {symint} in {range_constraints}"
238
+ )
239
+
240
+ previous_range = existing_inline_assertions.get(
241
+ symint, ValueRanges(-math.inf, math.inf)
242
+ )
243
+
244
+ if symint is lhs:
245
+ bounds = ValueRanges(-math.inf, scalar)
246
+ else:
247
+ bounds = ValueRanges(scalar, math.inf)
248
+ existing_inline_assertions[symint] = previous_range & bounds
249
+
250
+ return existing_inline_assertions
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/collect_tracepoints_pass.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import operator
5
+ from typing import Optional, TYPE_CHECKING, Union
6
+
7
+ import torch
8
+ from torch.export.exported_program import ConstantArgument, TensorArgument
9
+ from torch.fx.passes.infra.pass_base import PassBase, PassResult
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from torch.export.exported_program import ModuleCallSignature
14
+ from torch.export.graph_signature import ExportGraphSignature
15
+
16
+
17
+ __all__ = ["CollectTracepointsPass"]
18
+
19
+
20
+ class CollectTracepointsPass(PassBase):
21
+ """
22
+ Performs constant folding and constant propagation.
23
+ """
24
+
25
+ def __init__(
26
+ self, specs: dict[str, ModuleCallSignature], sig: ExportGraphSignature
27
+ ) -> None:
28
+ super().__init__()
29
+ self.specs = specs
30
+ self.sig = sig
31
+
32
+ def call(self, gm: torch.fx.GraphModule) -> Optional[PassResult]:
33
+ def get_arg_spec(arg) -> Union[TensorArgument, ConstantArgument]:
34
+ if isinstance(arg, torch.fx.Node):
35
+ if isinstance(arg.meta.get("val"), torch.Tensor):
36
+ return TensorArgument(name=arg.name)
37
+ else:
38
+ raise AssertionError(
39
+ "Symint input is not implemented yet for submodule call signature."
40
+ )
41
+ else:
42
+ return ConstantArgument(name="", value=arg)
43
+
44
+ for module in gm.modules():
45
+ if not isinstance(module, torch.fx.GraphModule):
46
+ continue
47
+ nn_module_stack = None
48
+ for node in module.graph.nodes:
49
+ if node.op != "call_function":
50
+ continue
51
+ if node.target == torch.ops.higher_order._export_tracepoint:
52
+ kind = node.kwargs["kind"]
53
+ if kind == "module_call_outputs":
54
+ nn_module_stack = node.meta["nn_module_stack"]
55
+ elif kind == "module_call_inputs":
56
+ nn_module_stack = None
57
+ else:
58
+ raise AssertionError(f"Unknown tracepoint kind: {kind}")
59
+ elif node.meta["nn_module_stack"] == nn_module_stack:
60
+ node.meta["nn_module_stack"].popitem()
61
+ else:
62
+ nn_module_stack = None
63
+ nn_module_stack = None
64
+ for node in reversed(module.graph.nodes):
65
+ if node.op != "call_function":
66
+ continue
67
+ if node.target == torch.ops.higher_order._export_tracepoint:
68
+ kind = node.kwargs["kind"]
69
+ if kind == "module_call_inputs":
70
+ nn_module_stack = node.meta["nn_module_stack"]
71
+ elif kind == "module_call_outputs":
72
+ nn_module_stack = None
73
+ else:
74
+ raise AssertionError(f"Unknown tracepoint kind: {kind}")
75
+ elif node.meta["nn_module_stack"] == nn_module_stack:
76
+ node.meta["nn_module_stack"].popitem()
77
+ else:
78
+ nn_module_stack = None
79
+
80
+ def copy_sig(sig) -> ModuleCallSignature:
81
+ from torch.export.exported_program import ModuleCallSignature
82
+
83
+ return ModuleCallSignature(
84
+ inputs=[],
85
+ outputs=[],
86
+ in_spec=sig.in_spec,
87
+ out_spec=sig.out_spec,
88
+ forward_arg_names=None,
89
+ )
90
+
91
+ for module in gm.modules():
92
+ if not isinstance(module, torch.fx.GraphModule):
93
+ continue
94
+ for node in module.graph.nodes:
95
+ if node.op != "call_function":
96
+ continue
97
+ if node.target == torch.ops.higher_order._export_tracepoint:
98
+ # There's some subtlety worth noting. Here fqn corresponds to
99
+ # the call name, whereas path corresponds to the module name.
100
+ # They are not necessarily the same! When a submodule is shared
101
+ # through different aliases, there are as many _export_tracepoint
102
+ # markers as there are aliases, since the shared submodule is
103
+ # wrapped once for each alias.
104
+ path = node.kwargs["path"]
105
+ fqn, _ = next(reversed(node.meta["nn_module_stack"].values()))
106
+
107
+ module_key = next(reversed(node.meta["nn_module_stack"]))
108
+ if "@" in module_key:
109
+ suffix = module_key.split("@")[-1]
110
+ path = f"{path}@{suffix}"
111
+
112
+ call_fqn = f"{fqn}@{suffix}"
113
+ if call_fqn not in self.specs:
114
+ self.specs[call_fqn] = copy_sig(self.specs[fqn])
115
+ fqn = call_fqn
116
+
117
+ kind = node.kwargs["kind"]
118
+ for i, arg in enumerate(node.args):
119
+ # We only update the signature of the alias used to call
120
+ # the submodule. Otherwise the signatures of all aliases
121
+ # would get conflated; the inputs/outputs of every call
122
+ # would be recorded in every other call as well.
123
+ if fqn == path:
124
+ if kind == "module_call_inputs":
125
+ self.specs[path].inputs.append(get_arg_spec(arg))
126
+ elif kind == "module_call_outputs":
127
+ self.specs[path].outputs.append(get_arg_spec(arg))
128
+ else:
129
+ raise AssertionError(f"Unknown tracepoint kind: {kind}")
130
+ if isinstance(arg, torch.fx.Node):
131
+ for user in node.users:
132
+ assert user.op == "call_function"
133
+ assert user.target == operator.getitem
134
+ assert isinstance(user.args[1], int)
135
+ if user.args[1] == i:
136
+ user.replace_all_uses_with(arg)
137
+ self.sig.replace_all_uses(user.name, arg.name)
138
+ break
139
+ users = list(node.users)
140
+ for user in users:
141
+ assert len(user.users) == 0
142
+ gm.graph.erase_node(user)
143
+ gm.graph.erase_node(node)
144
+ return PassResult(gm, True)
145
+
146
+ return None
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/constant_folding.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ from collections import defaultdict
4
+ from typing import Any, Callable, Optional
5
+
6
+ import torch
7
+ import torch.utils._pytree as pytree
8
+
9
+
10
+ aten = torch.ops.aten
11
+
12
+ # We would like to split modules into two subgraphs for runtime weight updates to work correctly.
13
+ # The use case and more information could be found at:
14
+ # https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing
15
+ META_TAG = "MODULE_TYPE"
16
+ MODULE_TAG = "_MAIN_MODULE"
17
+ CONST_MODULE_TAG = "_CONST_MODULE"
18
+
19
+
20
+ def replace_node_with_constant(gm, node, constant, name=None):
21
+ g = gm.graph
22
+
23
+ if name:
24
+ qualname = name
25
+ else:
26
+ if not hasattr(gm, "_frozen_param_count"):
27
+ gm._frozen_param_count = 0
28
+ i = gm._frozen_param_count
29
+
30
+ while True:
31
+ qualname = f"_frozen_param{i}"
32
+ if not hasattr(gm, qualname):
33
+ break
34
+ i += 1
35
+
36
+ gm._frozen_param_count = i + 1
37
+
38
+ with g.inserting_before(node):
39
+ new_input_node = g.create_node("get_attr", qualname, (), {})
40
+ node.replace_all_uses_with(new_input_node)
41
+ new_input_node.meta.update(node.meta)
42
+ g.erase_node(node)
43
+
44
+ # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning
45
+ gm.register_buffer(qualname, constant)
46
+ setattr(gm, qualname, constant)
47
+
48
+
49
+ class ConstantFolder(torch.fx.Interpreter):
50
+ def __init__(
51
+ self,
52
+ gm: torch.fx.GraphModule,
53
+ skip_constructors: bool = False,
54
+ ):
55
+ super().__init__(gm)
56
+ self.node_replacements: dict[torch.fx.Node, Any] = {}
57
+ self.replaced_uses: dict[torch.fx.Node, int] = collections.Counter()
58
+ self.unknown_value = object()
59
+ self.skip_constructors: bool = skip_constructors
60
+
61
+ # overwrite this to deallocate env values if their only remaining use
62
+ # is the output
63
+ self.user_to_last_uses = self.node_to_last_non_output_use()
64
+
65
+ def is_impure(self, node: torch.fx.Node) -> bool:
66
+ if (
67
+ node.target == torch.ops.prims.convert_element_type.default
68
+ and node.args[0].op == "get_attr" # type: ignore[union-attr]
69
+ and node.args[0].meta["val"].dtype == torch.int8 # type: ignore[union-attr]
70
+ and node.args[1] == torch.bfloat16
71
+ ):
72
+ # For int8_weight -> dq -> bf16_weight
73
+ return True
74
+ if node.target in [
75
+ torch.ops.quantized_decomposed.dequantize_per_channel.default,
76
+ torch.ops.quantized_decomposed.dequantize_per_tensor.default,
77
+ torch.ops.quantized_decomposed.dequantize_per_tensor.tensor,
78
+ torch.ops.pt2e_quant.dequantize_affine,
79
+ ]:
80
+ # For the pattern fp32_weight -> q -> dq
81
+ # We only folding fp32_weight -> q
82
+ # int8_weight and leave dq in graph to be fused
83
+ return True
84
+ return False
85
+
86
+ def node_to_last_non_output_use(self):
87
+ last_non_output_use = collections.defaultdict(list)
88
+ seen_uses = set()
89
+ output_node = next(iter(reversed(self.module.graph.nodes))) # type: ignore[arg-type, union-attr]
90
+
91
+ for node in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr]
92
+ if node.target == "output":
93
+ continue
94
+
95
+ def add_use(inp):
96
+ if inp in seen_uses:
97
+ return
98
+
99
+ seen_uses.add(inp)
100
+ last_non_output_use[node].append(inp)
101
+
102
+ # In-place is fine since we don't mutate
103
+ pytree.tree_map_only_(torch.fx.Node, add_use, (node.args, node.kwargs))
104
+
105
+ # if this node is only used in output, we want to gc it right away
106
+ if len(node.users) == 1 and output_node in node.users:
107
+ last_non_output_use[node].append(node)
108
+
109
+ return last_non_output_use
110
+
111
+ def run_node(self, node):
112
+ if node.target == "output":
113
+ # because we remove nodes from env on last non output use,
114
+ # re-define them now or we'll get error in interpreter
115
+ def set_env(arg):
116
+ self.env[arg] = self.unknown_value
117
+
118
+ # In-place is fine since we don't mutate
119
+ pytree.tree_map_only_(torch.fx.Node, set_env, node.args)
120
+ return super().run_node(node)
121
+
122
+ args, kwargs = self.fetch_args_kwargs_from_env(node)
123
+ flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs)
124
+
125
+ # We need to do this weird thing because in cases where flattened_inputs
126
+ # contains a ScriptObject, equality checking results in a type error if
127
+ # the types are different.
128
+ if any(
129
+ type(self.unknown_value) == type(input_) and self.unknown_value == input_
130
+ for input_ in flattened_inputs
131
+ ):
132
+ return self.unknown_value
133
+
134
+ # TODO - fix errors with this
135
+ if (
136
+ node.op == "call_function"
137
+ and node.target == aten._efficientzerotensor.default
138
+ ):
139
+ return self.unknown_value
140
+
141
+ # TODO - constant folding triton kernel returns the inputs -- fix this
142
+ if (
143
+ node.op == "call_function"
144
+ and node.name == "triton_kernel_wrapper_functional_proxy"
145
+ ):
146
+ return self.unknown_value
147
+
148
+ # skip constructors, since inductor generates optimal code for them already
149
+ # and turning into tensor would result in an additional global memory read
150
+ # TODO - more complicated strategy
151
+ if (
152
+ self.skip_constructors
153
+ and node.op != "get_attr"
154
+ and not any(isinstance(e, torch.Tensor) for e in flattened_inputs)
155
+ ):
156
+ return self.unknown_value
157
+
158
+ # All mutations should either be removed or on inputs which we did not make constant
159
+ if (
160
+ isinstance(node.target, torch._ops.OpOverload)
161
+ and torch.Tag.nondeterministic_seeded in node.target.tags
162
+ ):
163
+ return self.unknown_value
164
+
165
+ out = super().run_node(node)
166
+
167
+ if node.op != "get_attr" and isinstance(out, torch.Tensor):
168
+ if out.device.type == "meta":
169
+ return out
170
+
171
+ if not self.insertable_tensor_check(out):
172
+ return out
173
+
174
+ if self.is_impure(node):
175
+ return self.unknown_value
176
+
177
+ self.add_node_replacement(node, out)
178
+
179
+ flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs)
180
+
181
+ for n in flattened_node_inps:
182
+ if not isinstance(n, torch.fx.Node):
183
+ continue
184
+
185
+ self.replaced_uses[n] += 1
186
+
187
+ for to_delete in self.user_to_last_uses.get(node, []):
188
+ if self.replaced_uses[to_delete] == len(to_delete.users):
189
+ self.node_replacements.pop(to_delete, None)
190
+
191
+ return out
192
+
193
+ def insertable_tensor_check(self, tensor: torch.Tensor) -> bool:
194
+ return True
195
+
196
+ def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None:
197
+ self.node_replacements[node] = tensor
198
+
199
+ def run(self): # type: ignore[override]
200
+ env = {}
201
+ for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr]
202
+ env[n] = self.unknown_value
203
+ return super().run(initial_env=env)
204
+
205
+
206
+ def constant_fold(
207
+ gm: torch.fx.GraphModule,
208
+ constraint_fn: Optional[Callable[[torch.fx.Node], bool]] = None,
209
+ ):
210
+ with torch.utils._python_dispatch._disable_current_modes():
211
+ cf = ConstantFolder(gm, skip_constructors=True)
212
+ cf.run()
213
+
214
+ for node, constant in cf.node_replacements.items():
215
+ if constraint_fn is not None and not constraint_fn(node):
216
+ continue
217
+ replace_node_with_constant(gm, node, constant)
218
+
219
+ erased_params = []
220
+ # Get all attr users by looking up the graph instead from node.users, because in this case
221
+ # _tensor_constant0 and _tensor_constant0_1 are actually refereing to the same tensor.
222
+
223
+ # opcode name target args kwargs
224
+ # ------------- ------------------- ---------------- --------------------------- --------
225
+ # placeholder arg0_1 arg0 () {}
226
+ # get_attr _tensor_constant0 state () {}
227
+ # call_function add aten.add.Tensor (arg0_1, _tensor_constant0) {}
228
+ # get_attr _tensor_constant0_1 state () {}
229
+ # call_function add_ aten.add_.Tensor (_tensor_constant0_1, 1) {}
230
+ # output output output ([add],) {}
231
+
232
+ get_attr_node_users = defaultdict(list)
233
+ for node in gm.graph.nodes:
234
+ if node.op == "get_attr":
235
+ get_attr_node_users[node.target].extend(node.users.keys())
236
+ for node in gm.graph.find_nodes(op="get_attr"):
237
+ if node.op == "get_attr" and len(get_attr_node_users[node.target]) == 0:
238
+ if hasattr(gm, node.target):
239
+ delattr(gm, node.target)
240
+ erased_params.append(node)
241
+ for node in erased_params:
242
+ gm.graph.erase_node(node)
243
+
244
+ gm.graph.eliminate_dead_code()
245
+ gm.graph.lint()
246
+ gm.recompile()
247
+
248
+
249
+ def constant_graph_tag(gm: torch.fx.GraphModule) -> None:
250
+ with torch.utils._python_dispatch._disable_current_modes():
251
+ cf = ConstantFolder(gm, skip_constructors=True)
252
+ cf.run()
253
+
254
+ for node in gm.graph.nodes:
255
+ if (
256
+ node.op == "get_attr"
257
+ or node in cf.node_replacements
258
+ or node in cf.replaced_uses
259
+ ):
260
+ node.meta[META_TAG] = CONST_MODULE_TAG
261
+ else:
262
+ node.meta[META_TAG] = MODULE_TAG
263
+
264
+
265
+ def run_and_get_constant_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
266
+ """
267
+ Construct a GraphModule which corresponds to the part which could be
268
+ constant folded in provided gm.
269
+ """
270
+
271
+ constant_graph_tag(gm)
272
+ # We rewrite the tags, if it's a constant being directly consumed, without
273
+ # any folding opportunity, we keep it in main gm.
274
+ for node in gm.graph.find_nodes(op="get_attr"):
275
+ used_to_fold = False
276
+ for u in node.users:
277
+ if u.meta[META_TAG] == CONST_MODULE_TAG:
278
+ used_to_fold = True
279
+ break
280
+ if not used_to_fold:
281
+ node.meta[META_TAG] = MODULE_TAG
282
+
283
+ new_graph = torch.fx.Graph()
284
+
285
+ node_remapping: dict[torch.fx.Node, torch.fx.Node] = {}
286
+ output_nodes = []
287
+ for node in gm.graph.nodes:
288
+ if node.meta[META_TAG] == MODULE_TAG:
289
+ continue
290
+
291
+ new_node = new_graph.node_copy(node, lambda x: node_remapping[x])
292
+ node_remapping[node] = new_node
293
+
294
+ for user in node.users:
295
+ if user.meta[META_TAG] == MODULE_TAG:
296
+ output_nodes.append(new_node)
297
+ break
298
+
299
+ new_graph.output(tuple(output_nodes))
300
+ new_graph.lint()
301
+ new_gm = torch.fx.GraphModule(gm, new_graph)
302
+
303
+ return new_gm
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from torch._export.pass_base import (
6
+ _ExportPassBaseDeprecatedDoNotUse,
7
+ Argument,
8
+ PassResult,
9
+ )
10
+ from torch._export.pass_infra.node_metadata import NodeMetadata
11
+ from torch._export.pass_infra.proxy_value import ProxyValue
12
+ from torch._ops import OpOverload
13
+
14
+
15
+ aten = torch.ops.aten
16
+
17
+ _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: dict[OpOverload, OpOverload] = {
18
+ aten.sym_constrain_range.default: aten._functional_sym_constrain_range.default,
19
+ aten._assert_async.msg: aten._functional_assert_async.msg,
20
+ }
21
+
22
+
23
+ class _FunctionalizeSideEffectfulOpsPass(_ExportPassBaseDeprecatedDoNotUse):
24
+ """
25
+ Functionalize ops with side effect in graph module by replacing the op with
26
+ functional version of it. A new dependency token (`dep_token`) will be
27
+ created and propagated through functional ops to output.
28
+ For example:
29
+ ```
30
+ def f(x):
31
+ sym_constrain_range(x.shape[0], min=1, max=3)
32
+ return x.add(3)
33
+ ```
34
+ Will be transformed to:
35
+ ```
36
+ def f(x):
37
+ dep_token0 = _make_dep_token()
38
+ dep_token1 = _functional_sym_constrain_range(
39
+ x.shape[0], min=1, max=3, dep_token=dep_token0
40
+ )
41
+
42
+ return x.add(3), dep_token1
43
+ ```
44
+ """
45
+
46
+ def __init__(self) -> None:
47
+ super().__init__()
48
+ self._dep_token: Optional[ProxyValue] = None
49
+ self._next_dep_token_index: Optional[int] = None
50
+
51
+ def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
52
+ # Early return if no non-functional assertions.
53
+ if not any(
54
+ n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS
55
+ for n in graph_module.graph.nodes
56
+ ):
57
+ return PassResult(graph_module=graph_module, modified=False)
58
+
59
+ gm = copy.deepcopy(graph_module)
60
+ self._dep_token = None
61
+ self._next_dep_token_index = None
62
+ return super().call(gm)
63
+
64
+ def call_operator(
65
+ self,
66
+ op: OpOverload,
67
+ args: tuple[Argument, ...],
68
+ kwargs: dict[str, Argument],
69
+ meta: NodeMetadata,
70
+ ) -> ProxyValue:
71
+ if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS:
72
+ return super().call_operator(op, args, kwargs, meta)
73
+
74
+ if self._dep_token is None:
75
+ self._dep_token = super().call_operator(
76
+ aten._make_dep_token,
77
+ args=(),
78
+ kwargs={},
79
+ meta=self._create_dummy_node_metadata(),
80
+ )
81
+ self._dep_token.node.name = "dep_token0"
82
+ self._next_dep_token_index = 1
83
+
84
+ self._dep_token = super().call_operator(
85
+ _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op],
86
+ args=args,
87
+ kwargs={**kwargs, "dep_token": self._dep_token},
88
+ meta=meta,
89
+ )
90
+ assert self._next_dep_token_index is not None
91
+ self._dep_token.node.name = f"dep_token{self._next_dep_token_index}"
92
+ self._next_dep_token_index += 1
93
+
94
+ return self._dep_token
95
+
96
+ def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue:
97
+ assert self._dep_token is not None
98
+
99
+ return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/insert_custom_op_guards.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from collections import defaultdict
3
+
4
+ import torch
5
+ from torch._export.passes._node_metadata_hook import (
6
+ _node_metadata_hook,
7
+ _set_node_metadata_hook,
8
+ )
9
+ from torch._library.fake_profile import OpProfile, TensorMetadata
10
+
11
+
12
+ def insert_custom_op_guards(gm: torch.fx.GraphModule, ops_to_guard: set[str]) -> None:
13
+ """
14
+ This is used by draft_export to insert guards in front of calls to custom
15
+ operators which have a generated fake kernel.
16
+ """
17
+ for node in gm.graph.nodes:
18
+ if node.op == "call_function" and str(node.target) in ops_to_guard:
19
+ with _set_node_metadata_hook(
20
+ gm,
21
+ functools.partial(
22
+ _node_metadata_hook, stack_trace=node.meta.get("stack_trace")
23
+ ),
24
+ ), gm.graph.inserting_before(node):
25
+ for arg in (*node.args, *node.kwargs.values()):
26
+ if isinstance(arg, torch.fx.Node) and isinstance(
27
+ arg.meta.get("val"), torch.Tensor
28
+ ):
29
+ val = arg.meta["val"]
30
+ gm.graph.call_function(
31
+ torch.ops.aten._assert_tensor_metadata.default,
32
+ args=(arg,),
33
+ kwargs={
34
+ "dtype": val.dtype,
35
+ "device": val.device,
36
+ "layout": val.layout,
37
+ },
38
+ )
39
+
40
+ gm.recompile()
41
+
42
+
43
+ def get_op_profiles(
44
+ gm: torch.fx.GraphModule, ops_to_guard: set[str]
45
+ ) -> dict[str, set[OpProfile]]:
46
+ """
47
+ This is used by draft_export to get a list of custom operator profiles so
48
+ that we can generate fake kernels.
49
+ """
50
+
51
+ def _get_op_profile(node: torch.fx.Node) -> OpProfile:
52
+ args_profile = tuple(
53
+ [
54
+ TensorMetadata.maybe_from_tensor(arg.meta.get("val"))
55
+ if isinstance(arg, torch.fx.Node)
56
+ else None
57
+ for arg in (*node.args, *node.kwargs.values())
58
+ ]
59
+ )
60
+
61
+ out_profile = None
62
+ meta = node.meta.get("val")
63
+ assert meta is not None
64
+ if isinstance(meta, torch.Tensor):
65
+ out_profile = TensorMetadata.maybe_from_tensor(meta)
66
+ elif isinstance(meta, (list, tuple)):
67
+ out_profile = tuple([TensorMetadata.maybe_from_tensor(m) for m in meta]) # type: ignore[assignment]
68
+ assert out_profile is not None
69
+
70
+ return OpProfile(args_profile, out_profile) # type: ignore[arg-type]
71
+
72
+ op_profiles: dict[str, set[OpProfile]] = defaultdict(set)
73
+
74
+ for node in gm.graph.nodes:
75
+ if node.op == "call_function" and str(node.target) in ops_to_guard:
76
+ op_profiles[str(node.target)].add(_get_op_profile(node))
77
+
78
+ return op_profiles
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/lift_constants_pass.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import logging
4
+ from typing import Any, Optional, Union
5
+
6
+ import torch
7
+ from torch._export.verifier import SpecViolationError
8
+ from torch._guards import detect_fake_mode
9
+ from torch._library.fake_class_registry import FakeScriptObject
10
+ from torch._subclasses.fake_tensor import unset_fake_temporarily
11
+ from torch.export.exported_program import (
12
+ ArgumentSpec,
13
+ CustomObjArgument,
14
+ ExportGraphSignature,
15
+ InputKind,
16
+ InputSpec,
17
+ TensorArgument,
18
+ )
19
+ from torch.fx._symbolic_trace import _ConstantAttributeType
20
+ from torch.fx.graph_module import _get_attr
21
+
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+
26
+ class ConstantAttrMap(collections.abc.MutableMapping):
27
+ """A mapping class that understands how to use module constants (tensors,
28
+ ScriptObjects, FakeScriptObjects) as keys. We store tensors and FakeScriptObjects normally,
29
+ but ScriptObjects are stored by hash, because different torch.ScriptObjects can point to
30
+ the same underlying value (but we guarantee that they will `hash()` to the same value
31
+ if that's the case).
32
+ """
33
+
34
+ def __init__(self) -> None:
35
+ # Underlying dict that we use to implement this mapping.
36
+ self._constant_attrs: dict[
37
+ Union[int, torch.Tensor, FakeScriptObject, torch.utils._pytree.TreeSpec],
38
+ list[Any],
39
+ ] = {}
40
+ # Map from the hash(ScriptObject) to the ScriptObject itself. Used for
41
+ # APIs like `__iter__` that should look like they're returning the
42
+ # original ScriptObjects.
43
+ self._script_object_map: dict[int, torch.ScriptObject] = {}
44
+
45
+ def __getitem__(self, key: _ConstantAttributeType) -> Any:
46
+ real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
47
+ assert isinstance(real_key, (int, torch.Tensor, FakeScriptObject))
48
+ return self._constant_attrs[real_key]
49
+
50
+ def __setitem__(self, key: _ConstantAttributeType, value):
51
+ # we shouldn't actually call this, should go to add() instead to handle aliasing
52
+ raise NotImplementedError(
53
+ """Directly setting values for ConstantAttrMap is not supported, please use add(key, value) instead.
54
+ The same key can be mapped to multiple values, for handling constant aliasing."""
55
+ )
56
+
57
+ def add(self, key: _ConstantAttributeType, value: Any) -> None:
58
+ if isinstance(key, torch.ScriptObject):
59
+ if hash(key) not in self._constant_attrs:
60
+ self._constant_attrs[hash(key)] = []
61
+ self._constant_attrs[hash(key)].append(value)
62
+ self._script_object_map[hash(key)] = key
63
+ elif isinstance(key, (torch.Tensor, FakeScriptObject)):
64
+ if key not in self._constant_attrs:
65
+ self._constant_attrs[key] = []
66
+ self._constant_attrs[key].append(value)
67
+ else:
68
+ raise TypeError(
69
+ f"Expected key to be a tensor or ScriptObject, got {type(key)}"
70
+ )
71
+
72
+ def __delitem__(self, key: _ConstantAttributeType):
73
+ real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
74
+
75
+ del self._constant_attrs[real_key]
76
+
77
+ def __iter__(self):
78
+ for key in self._constant_attrs:
79
+ if isinstance(key, int):
80
+ yield self._script_object_map[key]
81
+ else:
82
+ yield key
83
+
84
+ def __len__(self):
85
+ return len(self._constant_attrs)
86
+
87
+ def __contains__(self, key: object) -> bool:
88
+ real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
89
+ return real_key in self._constant_attrs
90
+
91
+
92
+ def get_constant_fqn(node: torch.fx.Node, constant_name: str) -> str:
93
+ # The FQN of the constant tensor in the state dict should
94
+ # correspond to the module where the constant tensor was
95
+ # originally used.
96
+ if len(node.meta["nn_module_stack"]) == 0:
97
+ return constant_name
98
+ parent_fqn = list(node.meta["nn_module_stack"].values())[-1][0]
99
+ if len(parent_fqn) > 0:
100
+ return f"{parent_fqn}.{constant_name}"
101
+ else:
102
+ return constant_name
103
+
104
+
105
+ def _get_first_fqn(
106
+ const_attrs: ConstantAttrMap,
107
+ key: _ConstantAttributeType,
108
+ ) -> Any:
109
+ fqns = const_attrs.get(key)
110
+ return fqns[0] if fqns else None
111
+
112
+
113
+ def _unused_constant(node: torch.fx.Node) -> Optional[list[torch.fx.Node]]:
114
+ """
115
+ If there is a tensor constant created while tracing, here is how the graph
116
+ looks like:
117
+
118
+ %_tensor_constant0 : [num_users=1] = get_attr[target=_tensor_constant0]
119
+ %lift_fresh_copy : [num_users=1] = call_function[target=torch.ops.aten.lift_fresh_copy.default](args = (%_tensor_constant0,))
120
+ %detach_ : [num_users=?] = call_function[target=torch.ops.aten.detach_.default](args = (%lift_fresh_copy,))
121
+
122
+ To check to see if the tensor constant is being used, we want to traverse to
123
+ the detach node to see if it's actually being used.
124
+
125
+ This function returns None if this constant is being used, otherwise it returns the
126
+ lift_fresh and detach node to be removed later.
127
+ """ # noqa: B950
128
+ if len(node.users) > 1:
129
+ return None
130
+
131
+ lift_fresh_node = next(iter(node.users.keys()))
132
+ if not (
133
+ lift_fresh_node.op == "call_function"
134
+ and lift_fresh_node.target
135
+ in (
136
+ torch.ops.aten.lift_fresh.default,
137
+ torch.ops.aten.lift_fresh_copy.default,
138
+ )
139
+ ):
140
+ return None
141
+
142
+ if len(lift_fresh_node.users) > 1:
143
+ return None
144
+
145
+ detach_node = next(iter(lift_fresh_node.users.keys()))
146
+ if not (
147
+ detach_node.op == "call_function"
148
+ and detach_node.target
149
+ in (
150
+ torch.ops.aten.detach_.default,
151
+ torch.ops.aten.detach.default,
152
+ )
153
+ ):
154
+ return None
155
+
156
+ if len(detach_node.users) > 0:
157
+ return None
158
+ else:
159
+ return [detach_node, lift_fresh_node, node]
160
+
161
+
162
+ def lift_constants_pass(
163
+ gm: torch.fx.GraphModule,
164
+ graph_signature: ExportGraphSignature,
165
+ constant_attrs: ConstantAttrMap,
166
+ ) -> dict[str, _ConstantAttributeType]:
167
+ """
168
+ Takes a graph module, graph signature, and modifies them implace to lift any
169
+ constants (tensors or custom classes) as inputs to the graph. Returns a
170
+ dictionary of names to constants.
171
+
172
+ Arguments:
173
+ gm (torch.fx.GraphModule): The graph module containing the graph and constants to lift.
174
+ graph_signature (ExportGraphSignature): This graph signature will be
175
+ mutated to add additional CONSTANT_TENSOR and CUSTOM_OBJ inputs.
176
+ constant_attrs (ConstantAttr): A mapping from a constant value to its
177
+ fully-qualified path in `gm`. This is used to maintain consistent
178
+ location of constants between the original module and the exported
179
+ version.
180
+
181
+ Returns:
182
+ A dictionary of fqn => constant value.
183
+ """
184
+ all_constants: dict[str, _ConstantAttributeType] = {}
185
+
186
+ inputs = graph_signature.input_specs
187
+ num_custom_obj = sum(
188
+ input_specs.kind == InputKind.CUSTOM_OBJ for input_specs in inputs
189
+ )
190
+ num_tensor_constants = sum(
191
+ input_specs.kind == InputKind.CONSTANT_TENSOR for input_specs in inputs
192
+ )
193
+
194
+ fake_mode = detect_fake_mode(
195
+ tuple(node.meta["val"] for node in gm.graph.nodes if node.op == "placeholder")
196
+ )
197
+
198
+ first_user_input_loc, first_user_input = 0, next(iter(gm.graph.nodes))
199
+ used_target_names = set()
200
+ for node in gm.graph.nodes:
201
+ if node.op == "placeholder":
202
+ if node.name in graph_signature.user_inputs:
203
+ first_user_input = node
204
+ break
205
+ used_target_names.add(inputs[first_user_input_loc].target)
206
+ first_user_input_loc += 1
207
+ # If we ever hit here, it means that
208
+ # there was no user input so the constants
209
+ # should be inserted right before the first
210
+ # non-placeholder node.
211
+ if node.op != "placeholder":
212
+ first_user_input = node
213
+ break
214
+
215
+ lifted_objs = ConstantAttrMap()
216
+ renamed_targets = {}
217
+ for node in list(gm.graph.nodes):
218
+ if node.op == "get_attr":
219
+ if nodes_to_remove := _unused_constant(node):
220
+ # Remove the node if it's not being used
221
+ for node_rm in nodes_to_remove:
222
+ gm.graph.erase_node(node_rm)
223
+ continue
224
+
225
+ constant_val = _get_attr(gm, node.target)
226
+ # These are not hashable and not gonna be lifted
227
+ # so we can skip them earlier
228
+ if isinstance(constant_val, torch.fx.GraphModule):
229
+ continue
230
+ if "LoweredBackendModule" in type(constant_val).__name__:
231
+ continue
232
+ if "AOTInductorRunnerWrapper" in type(constant_val).__name__:
233
+ continue
234
+ if isinstance(constant_val, torch.utils._pytree.TreeSpec):
235
+ continue
236
+
237
+ if constant_val in lifted_objs:
238
+ # We already lifted this constant elsewhere. Just rewrite uses
239
+ # of this get_attr to point to the already-existing placeholder
240
+ # node.
241
+ const_placeholder_node = _get_first_fqn(lifted_objs, constant_val)
242
+ node.replace_all_uses_with(const_placeholder_node)
243
+ gm.graph.erase_node(node)
244
+ renamed_targets[node.name] = const_placeholder_node.name
245
+ continue
246
+
247
+ # For ScriptObject, Tensor and FakeScriptObject constants:
248
+ # First check if the constant was an attribute on some module by
249
+ # consulting `constant_attrs` map. If it is, use the fqn that keeps
250
+ # its location consistent with the eager module.
251
+ #
252
+ # If it's not in the `constant_attrs` map, that means it's an inline
253
+ # constant (e.g. x + torch.tensor(0)), and thus did not have a
254
+ # specific location in the eager module. In that case, just generate
255
+ # some name and attach it to the module in which it was used.
256
+ if isinstance(constant_val, (torch.ScriptObject, FakeScriptObject)):
257
+ constant_kind = InputKind.CUSTOM_OBJ
258
+ constant_fqn = _get_first_fqn(constant_attrs, constant_val)
259
+ if constant_fqn is not None:
260
+ constant_name = constant_fqn.replace(".", "_")
261
+ else:
262
+ constant_name = f"lifted_custom_{num_custom_obj}"
263
+ constant_fqn = get_constant_fqn(node, constant_name)
264
+ while constant_fqn in used_target_names:
265
+ num_custom_obj += 1
266
+ constant_name = f"lifted_custom_{num_custom_obj}"
267
+ constant_fqn = get_constant_fqn(node, constant_name)
268
+ num_custom_obj += 1
269
+ elif isinstance(constant_val, torch.Tensor):
270
+ # Remove the parameterness of constant_val
271
+ if isinstance(constant_val, torch.nn.Parameter):
272
+ log.debug(
273
+ "%s created when tracing %s is a parameter. But "
274
+ "it's not registered with register_parameter(). export will treat it as a constant tensor",
275
+ str(node.target),
276
+ str(node.meta.get("stack_trace", "<unknown stack>")),
277
+ )
278
+ # We get the real data out of the parameter by disabling the surrounding fake mode.
279
+ with unset_fake_temporarily():
280
+ constant_val = constant_val.data
281
+ constant_kind = InputKind.CONSTANT_TENSOR
282
+ constant_fqn = _get_first_fqn(constant_attrs, constant_val)
283
+ if constant_fqn is not None:
284
+ constant_name = constant_fqn.replace(".", "_")
285
+ else:
286
+ constant_name = f"lifted_tensor_{num_tensor_constants}"
287
+ constant_fqn = get_constant_fqn(node, constant_name)
288
+ while constant_fqn in used_target_names:
289
+ num_tensor_constants += 1
290
+ constant_name = f"lifted_tensor_{num_tensor_constants}"
291
+ constant_fqn = get_constant_fqn(node, constant_name)
292
+ num_tensor_constants += 1
293
+ else:
294
+ raise SpecViolationError(
295
+ f"getattr node {node} referencing unsupported type {type(constant_val)}"
296
+ )
297
+
298
+ with gm.graph.inserting_before(first_user_input):
299
+ # Insert the constant node before the first user input
300
+ const_placeholder_node = gm.graph.placeholder(constant_name)
301
+ # match target name with its node name in case there is name collision
302
+ # and suffix is added to node name in fx
303
+ const_placeholder_node.target = const_placeholder_node.name
304
+
305
+ for k, v in node.meta.items():
306
+ const_placeholder_node.meta[k] = v
307
+
308
+ # Once the FQN has been used, remove nn_module_stack, stack_trace
309
+ const_placeholder_node.meta.pop("nn_module_stack")
310
+ const_placeholder_node.meta.pop("stack_trace", None)
311
+
312
+ input_spec_arg: ArgumentSpec
313
+ if isinstance(constant_val, torch.Tensor):
314
+ if fake_mode is not None:
315
+ const_placeholder_node.meta["val"] = fake_mode.from_tensor(
316
+ constant_val, static_shapes=True
317
+ )
318
+ const_placeholder_node.meta["val"].constant = constant_val
319
+ else:
320
+ const_placeholder_node.meta["val"] = constant_val
321
+ input_spec_arg = TensorArgument(name=const_placeholder_node.name)
322
+ elif isinstance(constant_val, torch._C.ScriptObject):
323
+ class_fqn = constant_val._type().qualified_name() # type: ignore[attr-defined]
324
+ const_placeholder_node.meta["val"] = CustomObjArgument(
325
+ constant_fqn, class_fqn
326
+ )
327
+ input_spec_arg = CustomObjArgument(
328
+ name=const_placeholder_node.name, class_fqn=class_fqn
329
+ )
330
+ elif isinstance(constant_val, FakeScriptObject):
331
+ class_fqn = constant_val.script_class_name
332
+ const_placeholder_node.meta["val"] = CustomObjArgument(
333
+ constant_fqn, class_fqn, constant_val
334
+ )
335
+ input_spec_arg = CustomObjArgument(
336
+ name=const_placeholder_node.name,
337
+ class_fqn=class_fqn,
338
+ fake_val=constant_val,
339
+ )
340
+ else:
341
+ raise SpecViolationError(
342
+ f"tried to lift unsupported type {type(constant_val)} from node {node.format_node()}"
343
+ )
344
+
345
+ lifted_objs.add(constant_val, const_placeholder_node)
346
+ node.replace_all_uses_with(const_placeholder_node)
347
+ gm.graph.erase_node(node)
348
+
349
+ renamed_targets[node.name] = const_placeholder_node.name
350
+
351
+ # Add the constant as a buffer to the graph signature
352
+ graph_signature.input_specs.insert(
353
+ first_user_input_loc,
354
+ InputSpec(
355
+ kind=constant_kind,
356
+ arg=input_spec_arg,
357
+ target=constant_fqn,
358
+ ),
359
+ )
360
+ if constant_val in constant_attrs:
361
+ for fqn in constant_attrs[constant_val]:
362
+ all_constants[fqn] = constant_val
363
+ else:
364
+ all_constants[constant_fqn] = constant_val
365
+ first_user_input_loc += 1
366
+
367
+ for spec in graph_signature.output_specs:
368
+ if spec.arg.name in renamed_targets:
369
+ spec.arg.name = renamed_targets[spec.arg.name]
370
+
371
+ return all_constants
372
+
373
+
374
+ def rewrite_script_object_meta(
375
+ gm: torch.fx.GraphModule,
376
+ ) -> dict[str, _ConstantAttributeType,]:
377
+ """When tracing, we produce a graph with FakeScriptObject in the
378
+ meta["val"].
379
+
380
+ For now, we rewrie meta["val"] to be a placeholder CustomObjArgument
381
+ """
382
+ constants: dict[
383
+ str,
384
+ _ConstantAttributeType,
385
+ ] = {}
386
+ for node in gm.graph.nodes:
387
+ if "val" not in node.meta:
388
+ continue
389
+
390
+ old_meta = node.meta["val"]
391
+
392
+ if isinstance(old_meta, torch.ScriptObject):
393
+ class_fqn = old_meta._type().qualified_name() # type: ignore[attr-defined]
394
+ new_meta = CustomObjArgument(node.name, class_fqn)
395
+ constants[node.name] = old_meta
396
+ node.meta["val"] = new_meta
397
+
398
+ elif isinstance(old_meta, FakeScriptObject):
399
+ class_fqn = old_meta.script_class_name # type: ignore[attr-defined]
400
+ new_meta = CustomObjArgument(node.name, class_fqn, old_meta)
401
+ constants[node.name] = old_meta
402
+ node.meta["val"] = new_meta
403
+
404
+ return constants
405
+
406
+
407
+ def _materialize_and_lift_constants(
408
+ gm: torch.fx.GraphModule,
409
+ export_graph_signature: ExportGraphSignature,
410
+ constant_attrs: ConstantAttrMap,
411
+ ) -> dict[str, _ConstantAttributeType]:
412
+ constants = rewrite_script_object_meta(gm)
413
+ constants.update(lift_constants_pass(gm, export_graph_signature, constant_attrs))
414
+ return constants
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/remove_runtime_assertions.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.fx.passes.infra.pass_base import PassBase, PassResult
3
+
4
+
5
+ class _RemoveRuntimeAssertionsPass(PassBase):
6
+ """
7
+ Remove runtime assertions inserted by the
8
+ _AddRuntimeAssertionsForInlineConstraintsPass.
9
+ """
10
+
11
+ def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
12
+ modified = False
13
+ for module in graph_module.modules():
14
+ if not isinstance(module, torch.fx.GraphModule):
15
+ continue
16
+ for node in module.graph.nodes:
17
+ if node.target in [
18
+ torch.ops.aten._assert_async.msg,
19
+ torch.ops.aten._assert_scalar.default,
20
+ torch.ops.aten.sym_constrain_range_for_size.default,
21
+ torch.ops.aten.sym_constrain_range.default,
22
+ torch.ops.aten._assert_tensor_metadata.default,
23
+ ]:
24
+ assert_async_node = node
25
+ if len(assert_async_node.users) > 0:
26
+ continue
27
+ module.graph.erase_node(assert_async_node)
28
+ # the upstream scalar_tensor <- {le, ge} <- sym_size
29
+ # linear chain of nodes of nodes is removed by the
30
+ # downstream dead code elimination
31
+ modified = True
32
+
33
+ # We don't necessarily want to run DCE here because it could affect
34
+ # nodes that are in the module_call_graph attribute of the exported
35
+ # program. We will leave it to the pass caller to call DCE.
36
+ return PassResult(graph_module, modified)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional, TYPE_CHECKING, Union
5
+
6
+ import torch
7
+ from torch._higher_order_ops.wrap import wrap_with_autocast
8
+
9
+ from ..utils import node_inline_, nodes_filter, nodes_first, sequential_split
10
+ from .replace_with_hop_pass_util import (
11
+ _replace_with_hop_helper,
12
+ _replace_with_hop_pass_helper,
13
+ _sequential_split_and_maybe_inline_subgraphs_helper,
14
+ )
15
+
16
+
17
+ if TYPE_CHECKING:
18
+ from torch.export.graph_signature import ExportGraphSignature
19
+
20
+
21
+ def _is_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
22
+ return (
23
+ node
24
+ and node.op == "call_function"
25
+ and node.target
26
+ in [
27
+ torch.amp.autocast_mode._enter_autocast,
28
+ torch.amp.autocast_mode._exit_autocast,
29
+ ]
30
+ )
31
+
32
+
33
+ def _is_enter_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
34
+ return (
35
+ node
36
+ and node.op == "call_function"
37
+ and node.target == torch.amp.autocast_mode._enter_autocast
38
+ )
39
+
40
+
41
+ def _is_exit_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
42
+ return (
43
+ node
44
+ and node.op == "call_function"
45
+ and node.target == torch.amp.autocast_mode._exit_autocast
46
+ )
47
+
48
+
49
+ def _is_autocast_sub_mod(node: torch.fx.Node) -> bool:
50
+ """
51
+ Check if the first non-placeholder node is `torch.amp.autocast_mode._enter_autocast`.
52
+ """
53
+ if node.op == "call_module":
54
+ assert isinstance(node.target, str)
55
+ subgm = getattr(node.graph.owning_module, node.target)
56
+ first_non_ph = nodes_first(
57
+ subgm.graph.nodes, lambda node: node.op != "placeholder"
58
+ )
59
+ if (
60
+ first_non_ph
61
+ and first_non_ph.op == "call_function"
62
+ and first_non_ph.target == torch.amp.autocast_mode._enter_autocast
63
+ ):
64
+ # TODO: check if current auto-cast type is the same as the args of
65
+ # _enter_autocast. If so, return False, i.e. do not create a submodule.
66
+ return True
67
+ return False
68
+
69
+
70
+ def _check_valid_autocast_block(
71
+ enter_autocast_node: torch.fx.Node, exit_autocast_node: torch.fx.Node
72
+ ) -> None:
73
+ assert _is_enter_autocast_node(enter_autocast_node)
74
+ assert _is_exit_autocast_node(exit_autocast_node)
75
+ assert exit_autocast_node.args[0] == enter_autocast_node
76
+
77
+
78
+ def _replace_with_hop(node: torch.fx.Node) -> None:
79
+ assert node.op == "call_module"
80
+ graph: torch.fx.Graph = node.graph
81
+ assert graph.owning_module is not None
82
+ gm: torch.fx.GraphModule = graph.owning_module
83
+ assert isinstance(node.target, str)
84
+ sub_gm = getattr(gm, node.target)
85
+ sub_graph = sub_gm.graph
86
+ autocast_nodes = nodes_filter(sub_graph.nodes, _is_autocast_node)
87
+ if len(autocast_nodes) > 0:
88
+ assert len(autocast_nodes) > 1 # need at least an enter node and an exist node
89
+ enter_autocast_node = autocast_nodes[0]
90
+ exit_autocast_node = autocast_nodes[-1]
91
+ _check_valid_autocast_block(enter_autocast_node, exit_autocast_node)
92
+
93
+ _replace_with_hop_helper(node, enter_autocast_node, wrap_with_autocast)
94
+ sub_graph.erase_node(exit_autocast_node)
95
+ sub_graph.erase_node(enter_autocast_node)
96
+
97
+
98
+ def _split_autocast(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
99
+ """
100
+ split_autocast creates a new graph module that splits the input graph module into multiple submodules
101
+ based on the `_enter_autocast` and `_exit_autocast` nodes. It doesn't mutate the input graph module.
102
+
103
+ Nodes between the **outer-most** `_enter_autocast` and `_exit_autocast(_enter_autocast)` are splitted
104
+ into a submodule. Nested autocast regions are not splitted.
105
+ `_enter_autocast` and `_exit_autocast(_enter_autocast)` nodes are in the submodule as well.
106
+
107
+ Below is an example of splitting. A, B, C, D, E are blocks of non-autocast nodes in the original graph
108
+ module. Nodes marked with the same number are grouped into the same submodule.
109
+ A # 0
110
+ enter_autocast # 1
111
+ B # 1
112
+ exit_autocast # 1
113
+ C # 2
114
+ enter_autocast # 3
115
+ D # 3
116
+ exit_autocast # 3
117
+ E # 4
118
+ """
119
+ enter_autocast_node_stack: list[torch.fx.Node] = []
120
+ first_node_after_outer_most_exit: bool = False
121
+
122
+ def node_call_back(node: torch.fx.Node) -> bool:
123
+ nonlocal enter_autocast_node_stack, first_node_after_outer_most_exit
124
+ increment_id = False
125
+ if first_node_after_outer_most_exit or (
126
+ len(enter_autocast_node_stack) == 0 and _is_enter_autocast_node(node)
127
+ ):
128
+ assert len(enter_autocast_node_stack) == 0
129
+ first_node_after_outer_most_exit = False
130
+ increment_id = True
131
+ if _is_enter_autocast_node(node):
132
+ enter_autocast_node_stack.append(node)
133
+ elif _is_exit_autocast_node(node):
134
+ assert len(enter_autocast_node_stack) > 0
135
+ last_enter_autocast_node = enter_autocast_node_stack.pop()
136
+ assert node.args[0] == last_enter_autocast_node
137
+ if len(enter_autocast_node_stack) == 0:
138
+ # next node should be in the next submodule since
139
+ # autocast block ends
140
+ first_node_after_outer_most_exit = True
141
+ return increment_id
142
+
143
+ return sequential_split(gm, node_call_back)
144
+
145
+
146
+ def _sequential_split_and_maybe_inline_subgraphs(
147
+ gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
148
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
149
+ """
150
+ Helper function for replace_autocast_with_hop_pass().
151
+ Split the graph module into multiple subgraphs based on the autocast nodes.
152
+ For each subgraph, decides whether to construct a HOO subgraph, or inline the calls
153
+ back into the parent graph module.
154
+ Nodes between `_enter_autocast` and `_exit_autocast(_enter_autocast)` are considered
155
+ as a subgraph.
156
+ """
157
+ need_replacing = any(_is_autocast_node(node) for node in gm.graph.nodes)
158
+ if not need_replacing:
159
+ return gm, graph_signature
160
+
161
+ # split_autocast returns a new graph module that could have different output
162
+ # args names. We need to fix the graph signature in `_sequential_split_and_maybe_inline_subgraphs_helper`.
163
+ new_gm = _split_autocast(gm)
164
+
165
+ def _maybe_inline_or_replace_with_hop(node: torch.fx.Node) -> None:
166
+ if _is_autocast_sub_mod(node):
167
+ _replace_with_hop(node)
168
+ else:
169
+ assert node.op == "call_module"
170
+ assert isinstance(node.target, str)
171
+ node_inline_(node)
172
+
173
+ return _sequential_split_and_maybe_inline_subgraphs_helper(
174
+ new_gm, graph_signature, _maybe_inline_or_replace_with_hop
175
+ )
176
+
177
+
178
+ def replace_autocast_with_hop_pass(
179
+ gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
180
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
181
+ """
182
+ Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
183
+ then recursively call itself on each of the submodules.
184
+ """
185
+ return _replace_with_hop_pass_helper(
186
+ gm,
187
+ graph_signature,
188
+ _sequential_split_and_maybe_inline_subgraphs,
189
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import operator
4
+ from typing import Optional, Union
5
+
6
+ import torch
7
+ import torch.export._trace
8
+ from torch._ops import OpOverload
9
+ from torch.ao.quantization.fx._decomposed import (
10
+ dequantize_per_channel,
11
+ dequantize_per_tensor,
12
+ quantize_per_tensor,
13
+ )
14
+ from torch.ao.quantization.utils import calculate_qmin_qmax
15
+ from torch.fx.graph_module import _assign_attr
16
+
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ # Those values will need to be carried over multiple operators.
21
+ _INPUT_Q_DTYPE: Optional[Union[torch.dtype, torch.fx.Node]] = None
22
+ _SCALE: Optional[Union[float, torch.fx.Node]] = None
23
+ _ZERO_POINT: Optional[Union[float, torch.fx.Node]] = None
24
+
25
+
26
+ def int_to_valid_dtype(val: int) -> torch.dtype:
27
+ from torch._export.converter import _TORCH_ENUM_TO_DTYPE # No circular import.
28
+
29
+ if isinstance(val, torch.dtype):
30
+ return val
31
+ dtype = _TORCH_ENUM_TO_DTYPE[val]
32
+ if dtype == torch.quint8:
33
+ return torch.uint8
34
+ elif dtype == torch.qint8:
35
+ return torch.int8
36
+ return dtype
37
+
38
+
39
+ def fx_enum_to_dtype(gm: torch.fx.GraphModule, val: int) -> torch.fx.Node:
40
+ return gm.graph.call_function(int_to_valid_dtype, (val,))
41
+
42
+
43
+ def insert_quantized_node(
44
+ gm: torch.fx.GraphModule,
45
+ val_node: torch.fx.Node,
46
+ scale_node: Union[float, torch.fx.Node],
47
+ zero_point_node: Union[float, torch.fx.Node],
48
+ qmin_node: Union[float, int, torch.fx.Node],
49
+ qmax_node: Union[float, int, torch.fx.Node],
50
+ dtype_node: Union[torch.dtype, torch.fx.Node],
51
+ qscheme: Optional[torch.qscheme],
52
+ ) -> torch.fx.Node:
53
+ return gm.graph.call_function(
54
+ quantize_per_tensor,
55
+ (
56
+ val_node,
57
+ scale_node,
58
+ zero_point_node,
59
+ qmin_node,
60
+ qmax_node,
61
+ dtype_node,
62
+ ),
63
+ )
64
+
65
+
66
+ def get_dequantized(
67
+ val: torch.Tensor,
68
+ scale: Union[float, torch.Tensor],
69
+ zero_point: Union[float, torch.Tensor],
70
+ qmin: Union[float, int],
71
+ qmax: Union[float, int],
72
+ dtype: torch.dtype,
73
+ axis: Optional[int],
74
+ qscheme: Optional[torch.qscheme],
75
+ ) -> torch.Tensor:
76
+ if qscheme is torch.per_tensor_affine:
77
+ return dequantize_per_tensor(
78
+ val,
79
+ scale, # type: ignore[arg-type]
80
+ zero_point, # type: ignore[arg-type]
81
+ qmin, # type: ignore[arg-type]
82
+ qmax, # type: ignore[arg-type]
83
+ dtype,
84
+ )
85
+ elif qscheme is torch.per_channel_affine:
86
+ return dequantize_per_channel(
87
+ val,
88
+ scale, # type: ignore[arg-type]
89
+ zero_point, # type: ignore[arg-type]
90
+ axis, # type: ignore[arg-type]
91
+ qmin, # type: ignore[arg-type]
92
+ qmax, # type: ignore[arg-type]
93
+ dtype,
94
+ )
95
+ else:
96
+ raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}")
97
+
98
+
99
+ def insert_dequantized_node(
100
+ gm: torch.fx.GraphModule,
101
+ val_node: torch.fx.Node,
102
+ scale_node: Union[float, torch.fx.Node],
103
+ zero_point_node: Union[float, torch.fx.Node],
104
+ qmin_node: Union[float, int, torch.fx.Node],
105
+ qmax_node: Union[float, int, torch.fx.Node],
106
+ dtype_node: Union[torch.dtype, torch.fx.Node],
107
+ axis_node: Optional[Union[int, torch.fx.Node]],
108
+ qscheme: Optional[torch.qscheme],
109
+ ) -> torch.fx.Node:
110
+ if qscheme is torch.per_tensor_affine:
111
+ return gm.graph.call_function(
112
+ dequantize_per_tensor,
113
+ (
114
+ val_node,
115
+ scale_node,
116
+ zero_point_node,
117
+ qmin_node,
118
+ qmax_node,
119
+ dtype_node,
120
+ ),
121
+ )
122
+ elif qscheme is torch.per_channel_affine:
123
+ return gm.graph.call_function(
124
+ dequantize_per_channel,
125
+ (
126
+ val_node,
127
+ scale_node,
128
+ zero_point_node,
129
+ axis_node,
130
+ qmin_node,
131
+ qmax_node,
132
+ dtype_node,
133
+ ),
134
+ )
135
+ else:
136
+ raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}")
137
+
138
+
139
+ def get_qmin_qmax(dtype: torch.dtype) -> tuple[Union[int, float], Union[int, float]]:
140
+ return calculate_qmin_qmax(None, None, False, dtype, False) # type: ignore[arg-type]
141
+
142
+
143
+ def insert_qmin_qmax_node(
144
+ gm: torch.fx.GraphModule, dtype_node: Union[torch.dtype, torch.fx.Node]
145
+ ) -> tuple[torch.fx.Node, torch.fx.Node]:
146
+ q_min_max_node = gm.graph.call_function(
147
+ calculate_qmin_qmax, (None, None, False, dtype_node, False)
148
+ )
149
+ qmin_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 0))
150
+ qmax_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 1))
151
+ return qmin_node, qmax_node
152
+
153
+
154
+ def get_script_object(
155
+ gm: torch.nn.Module, node: torch.fx.Node
156
+ ) -> torch._C.ScriptObject:
157
+ assert isinstance(node, torch.fx.Node)
158
+ assert node.op == "get_attr"
159
+ attr_name = node.target
160
+ assert isinstance(attr_name, str)
161
+
162
+ mod = gm
163
+ for attr in attr_name.split("."):
164
+ mod = getattr(mod, attr)
165
+ assert isinstance(mod, torch._C.ScriptObject)
166
+ return mod
167
+
168
+
169
+ def insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
170
+ gm: torch.fx.GraphModule,
171
+ param_node: torch.fx.Node,
172
+ ) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
173
+ """Directly inline tensor from a get_attr fx node."""
174
+ mod = get_script_object(gm, param_node)
175
+ w_qtensor, b_qtensor = mod.unpack() # type: ignore[attr-defined]
176
+ w_attr_name, b_attr_name = (
177
+ f"dequantized_{param_node.target}_w",
178
+ f"dequantized_{param_node.target}_b",
179
+ )
180
+ return insert_weight_and_bias_get_attr_node(
181
+ gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name
182
+ )
183
+
184
+
185
+ def insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
186
+ gm: torch.fx.GraphModule,
187
+ get_attr_to_weight_node: torch.fx.Node,
188
+ get_attr_to_bias_node: Optional[torch.fx.Node],
189
+ ) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
190
+ assert isinstance(get_attr_to_weight_node.target, str)
191
+ w_qtensor = getattr(gm, get_attr_to_weight_node.target)
192
+ w_attr_name = f"dequantized_{get_attr_to_weight_node.target}_w"
193
+
194
+ if get_attr_to_bias_node is not None:
195
+ assert isinstance(get_attr_to_bias_node.target, str)
196
+ b_qtensor = getattr(gm, get_attr_to_bias_node.target)
197
+ b_attr_name = f"dequantized_{get_attr_to_bias_node.target}_b"
198
+ else:
199
+ b_qtensor, b_attr_name = None, ""
200
+
201
+ return insert_weight_and_bias_get_attr_node(
202
+ gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name
203
+ )
204
+
205
+
206
+ def insert_weight_and_bias_get_attr_node(
207
+ gm: torch.fx.GraphModule,
208
+ w_qtensor: torch.Tensor,
209
+ b_qtensor: Optional[torch.Tensor],
210
+ w_attr_name: str,
211
+ b_attr_name: str,
212
+ ) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
213
+ w_tensor = get_tensor_from_qtensor(w_qtensor)
214
+ _assign_attr(w_tensor, gm, w_attr_name)
215
+ w_tensor_attr = gm.graph.get_attr(w_attr_name)
216
+
217
+ if b_qtensor is not None:
218
+ b_tensor = get_tensor_from_qtensor(b_qtensor, dequant=False)
219
+ _assign_attr(b_tensor, gm, b_attr_name)
220
+ b_tensor_attr = gm.graph.get_attr(b_attr_name)
221
+ else:
222
+ b_tensor_attr = None
223
+
224
+ return w_tensor_attr, b_tensor_attr
225
+
226
+
227
+ def get_tensor_from_qtensor(
228
+ qtensor: torch.Tensor, dequant: bool = True
229
+ ) -> torch.Tensor:
230
+ # Manual conversion because qint8 is not used anymore.
231
+ if qtensor.dtype in [torch.qint8, torch.quint8]:
232
+ tensor = qtensor.int_repr()
233
+ else:
234
+ tensor = qtensor
235
+
236
+ # Weights need dequantization with scaling and zero_point adjustment, but
237
+ # bias does not need that.
238
+ if dequant:
239
+ qscheme = qtensor.qscheme()
240
+ if qscheme == torch.per_channel_affine:
241
+ scale, zero_point, axis = (
242
+ qtensor.q_per_channel_scales(),
243
+ qtensor.q_per_channel_zero_points(),
244
+ qtensor.q_per_channel_axis(),
245
+ )
246
+ else:
247
+ scale, zero_point, axis = (
248
+ qtensor.q_scale(), # type: ignore[assignment]
249
+ qtensor.q_zero_point(), # type: ignore[assignment]
250
+ None,
251
+ )
252
+ dtype = tensor.dtype
253
+ qmin, qmax = get_qmin_qmax(dtype)
254
+ return get_dequantized(
255
+ tensor, scale, zero_point, qmin, qmax, dtype, axis, qscheme
256
+ )
257
+ return tensor
258
+
259
+
260
+ def insert_fused_activation_node(
261
+ gm: torch.fx.GraphModule, opname: str, fx_node: torch.fx.Node
262
+ ) -> torch.fx.Node:
263
+ if opname in ["conv1d_relu", "conv2d_relu", "linear_relu", "add_relu", "mul_relu"]:
264
+ fx_node = gm.graph.call_function(torch.ops.aten.relu, (fx_node,))
265
+ return fx_node
266
+
267
+
268
+ def _conv1d_op_with_squeeze(
269
+ inp: torch.Tensor,
270
+ weight: torch.Tensor,
271
+ bias: Optional[torch.Tensor],
272
+ stride: list[int],
273
+ padding: list[int],
274
+ dilation: list[int],
275
+ groups: int,
276
+ ) -> torch.Tensor:
277
+ # In quantized version, conv1d is emulated using conv2d with squeeze and unsqueeze
278
+ # operations before and after the conv2d operation to match the dimension of weights.
279
+ # Reference: https://github.com/pytorch/pytorch/blob/eca0cb0fbe84bb0a34fa94afe261bceecd52c436/aten/src/ATen/native/quantized/cpu/qconv.cpp#L1827 # noqa: B950
280
+ s_inp = torch.ops.aten.unsqueeze(inp, 2)
281
+ conv1d_res = torch.ops.aten.conv2d(
282
+ s_inp,
283
+ weight,
284
+ bias,
285
+ stride,
286
+ padding,
287
+ dilation,
288
+ groups,
289
+ )
290
+ uns_conv1d_res = torch.ops.aten.squeeze(conv1d_res, 2)
291
+ return uns_conv1d_res
292
+
293
+
294
+ def _transform_conv_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node):
295
+ """Conv specfic transformation function."""
296
+ assert isinstance(node.target, torch._ops.OpOverload)
297
+ opname = node.target._opname
298
+ scale_node, zero_point_node = node.args[2], node.args[3]
299
+
300
+ op_f = (
301
+ torch.ops.aten.conv2d
302
+ if opname in ["conv2d", "conv2d_relu"]
303
+ else _conv1d_op_with_squeeze
304
+ )
305
+
306
+ inp_node, param_node = node.args[0], node.args[1]
307
+ assert isinstance(inp_node, torch.fx.Node)
308
+ assert isinstance(param_node, torch.fx.Node)
309
+
310
+ if param_node.op == "call_function":
311
+ # Using Conv2dPrepackParam from conv_prepack.
312
+ # We directly skip the packing call and inline weights and bias.
313
+ w_node, b_node = param_node.args[0], param_node.args[1]
314
+ assert isinstance(w_node, torch.fx.Node)
315
+ assert b_node is None or isinstance(b_node, torch.fx.Node)
316
+ (
317
+ param_0,
318
+ param_1,
319
+ ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
320
+ gm, w_node, b_node
321
+ )
322
+ op_res_node = gm.graph.call_function(
323
+ op_f, (inp_node, param_0, param_1, *param_node.args[2:])
324
+ )
325
+ else:
326
+ # Using ConvPrepackedParam.
327
+ param = get_script_object(gm, param_node)
328
+ (
329
+ param_0,
330
+ param_1,
331
+ ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
332
+ gm, param_node
333
+ ) # type: ignore[assignment]
334
+ op_res_node = gm.graph.call_function(
335
+ op_f,
336
+ (
337
+ inp_node,
338
+ param_0,
339
+ param_1,
340
+ param.stride(), # type: ignore[attr-defined]
341
+ param.padding(), # type: ignore[attr-defined]
342
+ param.dilation(), # type: ignore[attr-defined]
343
+ param.groups(), # type: ignore[attr-defined]
344
+ ),
345
+ )
346
+ return op_res_node, scale_node, zero_point_node
347
+
348
+
349
+ def _transform_linear_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node):
350
+ """Linear specfic transformation function."""
351
+ scale_node, zero_point_node = node.args[2], node.args[3]
352
+
353
+ inp_node, param_node = node.args[0], node.args[1]
354
+ assert isinstance(inp_node, torch.fx.Node)
355
+ assert isinstance(param_node, torch.fx.Node)
356
+
357
+ if param_node.op == "call_function":
358
+ # Using LinearPrepackParam from linear_prepack.
359
+ # We directly skip the packing call and inline weights and bias.
360
+ w_node, b_node = param_node.args[0], param_node.args[1]
361
+ assert isinstance(w_node, torch.fx.Node)
362
+ assert b_node is None or isinstance(b_node, torch.fx.Node)
363
+ (
364
+ param_0,
365
+ param_1,
366
+ ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
367
+ gm, w_node, b_node
368
+ )
369
+ op_res_node = gm.graph.call_function(
370
+ torch.ops.aten.linear, (inp_node, param_0, param_1, *param_node.args[2:])
371
+ )
372
+ else:
373
+ # Using LinearPackedParams.
374
+ (
375
+ param_0,
376
+ param_1,
377
+ ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
378
+ gm, param_node
379
+ ) # type: ignore[assignment]
380
+ op_res_node = gm.graph.call_function(
381
+ torch.ops.aten.linear, (inp_node, param_0, param_1)
382
+ )
383
+ return op_res_node, scale_node, zero_point_node
384
+
385
+
386
+ def _transform_op_where_last_two_arguments_are_scale_and_zero_point(
387
+ gm: torch.fx.GraphModule, node: torch.fx.Node
388
+ ):
389
+ """
390
+ This transformation function can be used for function where the last two
391
+ parameters are scale and zero point. Additionally, the function's parameters
392
+ do not need any unpacking.
393
+ """
394
+ to_standard_op = {
395
+ "mul": torch.ops.aten.mul,
396
+ "mul_relu": torch.ops.aten.mul,
397
+ "add": torch.ops.aten.add,
398
+ "add_relu": torch.ops.aten.add,
399
+ "softmax": torch.ops.aten.softmax,
400
+ "cat": torch.ops.aten.cat,
401
+ "hardswish": torch.ops.aten.hardswish,
402
+ }
403
+
404
+ assert isinstance(node.target, torch._ops.OpOverload)
405
+ opname, args = node.target._opname, node.args
406
+ scale_node, zero_point_node = args[-2], args[-1]
407
+ op_res_node = gm.graph.call_function(to_standard_op[opname], tuple(args[:-2]))
408
+ return op_res_node, scale_node, zero_point_node
409
+
410
+
411
+ def _transform_scalar_arithmetic(gm: torch.fx.GraphModule, node: torch.fx.Node):
412
+ """Transform scalar overload for basic arithmetic."""
413
+ to_standard_op = {
414
+ "mul": torch.ops.aten.mul.Scalar,
415
+ "add": torch.ops.aten.add.Scalar,
416
+ }
417
+ assert isinstance(node.target, torch._ops.OpOverload)
418
+ opname, args = node.target._opname, node.args
419
+ op_res_node = gm.graph.call_function(to_standard_op[opname], args)
420
+ return op_res_node, _SCALE, _ZERO_POINT
421
+
422
+
423
+ def _transform_prepacked_op(gm: torch.fx.GraphModule, node: torch.fx.Node):
424
+ """
425
+ Transformation for functions under prepacked namespace, where they share
426
+ the same handling logic that [...]OpContext contains all parameters.
427
+ """
428
+ assert isinstance(node.target, torch._ops.OpOverload)
429
+ opname, args = node.target._opname, node.args
430
+ op_f = None
431
+ if opname == "conv2d_clamp_run":
432
+ op_f = torch.ops.aten.conv2d
433
+ elif opname == "linear_clamp_run":
434
+ op_f = torch.ops.aten.linear
435
+ else:
436
+ raise RuntimeError(f"Invalid operator {opname}")
437
+
438
+ assert isinstance(args[1], torch.fx.Node)
439
+ so = get_script_object(gm, args[1])
440
+
441
+ func_args = []
442
+ func_args += [args[0]]
443
+ func_args += so.unpack()[:2] # type: ignore[attr-defined]
444
+ if opname == "conv2d_clamp_run":
445
+ func_args += torch.ops.prepacked.unpack_prepacked_sizes_conv2d(so)[2:]
446
+
447
+ op_res_node = gm.graph.call_function(op_f, tuple(func_args))
448
+ return op_res_node
449
+
450
+
451
+ def _transform_batch_norm(gm: torch.fx.GraphModule, node: torch.fx.Node):
452
+ args = node.args
453
+ scale_node, zero_point_node = args[-2], args[-1]
454
+ op_res_node = gm.graph.call_function(
455
+ torch.ops.aten.native_batch_norm, (*args[:-3], False, 0.1, args[-3])
456
+ )
457
+ op_res_node = gm.graph.call_function(operator.getitem, (op_res_node, 0))
458
+ return op_res_node, scale_node, zero_point_node
459
+
460
+
461
+ def fx_transform_quantized_op_to_standard_op(
462
+ gm: torch.fx.GraphModule, node: torch.fx.Node
463
+ ) -> torch.fx.Node:
464
+ global _SCALE, _ZERO_POINT, _INPUT_Q_DTYPE
465
+
466
+ assert isinstance(node.target, torch._ops.OpOverload)
467
+ opname, overload = node.target._opname, node.target._overloadname
468
+
469
+ key = f"{opname}.{overload}"
470
+ opname_to_transform_f = {
471
+ "conv1d.new": _transform_conv_with_packedparam,
472
+ "conv1d_relu.new": _transform_conv_with_packedparam,
473
+ "conv1d.default": _transform_conv_with_packedparam,
474
+ "conv1d_relu.default": _transform_conv_with_packedparam,
475
+ "conv2d.new": _transform_conv_with_packedparam,
476
+ "conv2d_relu.new": _transform_conv_with_packedparam,
477
+ "conv2d.default": _transform_conv_with_packedparam,
478
+ "conv2d_relu.default": _transform_conv_with_packedparam,
479
+ "linear.default": _transform_linear_with_packedparam,
480
+ "linear_relu.default": _transform_linear_with_packedparam,
481
+ "add.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
482
+ "add_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
483
+ "mul.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
484
+ "mul_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
485
+ "softmax.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
486
+ "cat.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
487
+ "hardswish.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
488
+ "batch_norm2d.default": _transform_batch_norm,
489
+ "mul.Scalar": _transform_scalar_arithmetic,
490
+ "add.Scalar": _transform_scalar_arithmetic,
491
+ }
492
+
493
+ if f"{key}" not in opname_to_transform_f:
494
+ raise RuntimeError(f"Unsupported quantized op during transformation: {key}")
495
+
496
+ op_res_node, scale_node, zero_point_node = opname_to_transform_f[f"{key}"](gm, node)
497
+
498
+ # Add fused activation layer.
499
+ op_res_node = insert_fused_activation_node(gm, opname, op_res_node)
500
+ _SCALE, _ZERO_POINT = scale_node, zero_point_node
501
+
502
+ assert _INPUT_Q_DTYPE is not None
503
+ qmin_node, qmax_node = insert_qmin_qmax_node(gm, _INPUT_Q_DTYPE)
504
+ q_fx_node = insert_quantized_node(
505
+ gm,
506
+ op_res_node,
507
+ scale_node,
508
+ zero_point_node,
509
+ qmin_node,
510
+ qmax_node,
511
+ _INPUT_Q_DTYPE,
512
+ torch.per_tensor_affine,
513
+ )
514
+ dq_fx_node = insert_dequantized_node(
515
+ gm,
516
+ q_fx_node,
517
+ scale_node,
518
+ zero_point_node,
519
+ qmin_node,
520
+ qmax_node,
521
+ _INPUT_Q_DTYPE,
522
+ None,
523
+ torch.per_tensor_affine,
524
+ )
525
+ return dq_fx_node
526
+
527
+
528
+ def replace_quantized_ops_with_standard_ops(gm: torch.fx.GraphModule):
529
+ """
530
+ Replace legacy quantized ops (aten.quantize_per_tensor, quantized.conv) with
531
+ PT2 ops (quantize_decomposed.quantize_per_tensor, aten.conv).
532
+
533
+ Before: x || -> aten.q || -> quantized.conv2d || -> quantized.linear || -> aten.dq || -> y
534
+
535
+ After: x || -> qd.q -> qd.dq || -> aten.conv2d -> qd.q -> qd.dq || aten.linear -> qd.q -> qd.dq || -> y
536
+
537
+ (qd == quantized_decomposed library, q = quantize, dq = dequantize)
538
+ ^
539
+ |
540
+ getattr(w), getattr(b) from Conv2dParamPrepack
541
+
542
+ During each iteration, the transformation spits out the transformed operator, its quantized output,
543
+ and its dequantized value together. We did this because dequantization need to use the
544
+ scale and zero point parameters from the quantization to recover the approximate original value. After each
545
+ iteration, the new dequantization node will be used as the input to the next node (e.g., dq2 -> linear).
546
+
547
+ For operators like conv2d and linear, their weights and bias are packed in a quantized format in the ScriptObject.
548
+ During the transformation, we unpack those objects, get their dequantized tensor, populate those
549
+ as attributes to the module, and use getattr to access them.
550
+
551
+ One exception in the transformation is conv_prepack and linear_prepack. Those calls pack
552
+ weight and bias constant tensors into ScriptObject, which are then used by subsequent conv2d or linear calls.
553
+ During transformation, we directly skip transforming conv_prepack or linear_prepack. We check whether ScriptObject to the
554
+ quantized::conv2d or linear is from conv_prepack or linear_prepack. If it is, we then inline those parameters
555
+ to the operator by converting them to a getattr fx.node.
556
+
557
+ For prepacked::conv2d_clamp_run and prepacked::linear_clamp_run, we directly convert them to aten.conv2d and aten.linear
558
+ without the need of doing de/quantization.
559
+
560
+ Three global variables defined are _INPUT_Q_DTYPE, _SCALE, _ZERO_POINT. _INPUT_Q_DTYPE determines the de/quantization
561
+ data type, which is the same across the entire program, but it only shows up in the very first quantization
562
+ call. _SCALE and _ZERO_POINT are used only when operators do not have those specified. E.g., mul.Scalar.
563
+ """
564
+
565
+ global _INPUT_Q_DTYPE
566
+
567
+ quantized = False
568
+
569
+ last_quantized_node = None
570
+ for node in gm.graph.nodes:
571
+ if isinstance(node.target, OpOverload):
572
+ with gm.graph.inserting_before(node):
573
+ namespace, opname = node.target.namespace, node.target._opname
574
+ if namespace == "quantized" and opname not in [
575
+ "conv_prepack",
576
+ "linear_prepack",
577
+ ]:
578
+ quantized = True
579
+ fx_node = fx_transform_quantized_op_to_standard_op(gm, node)
580
+ node.replace_all_uses_with(fx_node)
581
+ last_quantized_node = fx_node
582
+ elif namespace == "prepacked":
583
+ quantized = True
584
+ fx_node = _transform_prepacked_op(gm, node)
585
+ node.replace_all_uses_with(fx_node)
586
+ last_quantized_node = fx_node
587
+ elif namespace == "aten" and opname == "quantize_per_tensor":
588
+ inp_node, scale_node, zero_point_node, dtype_node = node.args
589
+ dtype_node = fx_enum_to_dtype(gm, dtype_node)
590
+ _INPUT_Q_DTYPE = dtype_node
591
+ qmin_node, qmax_node = insert_qmin_qmax_node(gm, dtype_node)
592
+ q_fx_node = insert_quantized_node(
593
+ gm,
594
+ inp_node,
595
+ scale_node,
596
+ zero_point_node,
597
+ qmin_node,
598
+ qmax_node,
599
+ dtype_node,
600
+ torch.per_tensor_affine,
601
+ )
602
+ dq_fx_node = insert_dequantized_node(
603
+ gm,
604
+ q_fx_node,
605
+ scale_node,
606
+ zero_point_node,
607
+ qmin_node,
608
+ qmax_node,
609
+ dtype_node,
610
+ None,
611
+ torch.per_tensor_affine,
612
+ )
613
+ node.replace_all_uses_with(dq_fx_node)
614
+ last_quantized_node = dq_fx_node
615
+ elif namespace == "aten" and opname == "dequantize":
616
+ assert last_quantized_node is not None
617
+ node.replace_all_uses_with(last_quantized_node)
618
+ else:
619
+ last_quantized_node = node
620
+
621
+ # Post-processing again to remove legacy ScriptObjects and quantizated tensors
622
+ # stored as attributes or in the buffer. This is used to clean up the GraphModule
623
+ # to not trigger tracing errors like missing __obj_flatten__ functions.
624
+ def _clean_attr(mod: torch.nn.Module):
625
+ for submod in mod.modules():
626
+ attr_names_to_clean = set()
627
+ for k, v in submod.__dict__.items():
628
+ if isinstance(v, torch.ScriptObject):
629
+ attr_names_to_clean.add(k)
630
+ if k == "_buffers":
631
+ buffer_name_to_clean = set()
632
+ for b_name, b_value in v.items():
633
+ if isinstance(b_value, torch.Tensor) and b_value.dtype in [
634
+ torch.qint8,
635
+ torch.quint8,
636
+ ]:
637
+ buffer_name_to_clean.add(b_name)
638
+ for b_name in buffer_name_to_clean:
639
+ v.pop(b_name, None)
640
+ for attr_name in attr_names_to_clean:
641
+ delattr(submod, attr_name)
642
+
643
+ if quantized:
644
+ """
645
+ TODO: SetAttr + quantized ops will result incorrect program. This flag is used to temporarily
646
+ bypass test cases.
647
+
648
+ The deadcode elimination pass is needed to remove legacy quantized ops. Otherwise, retracing
649
+ will throw errors. However, the current way of SetAttr does inplace update to attributes, so
650
+ this pass regard them as dead code and remove them. Below is an example of GraphModule before
651
+ and after the dead code elimination pass.
652
+
653
+ class GraphModule(torch.nn.Module):
654
+ def forward(self, x_1):
655
+ # No stacktrace found for following nodes
656
+ data = self.data; data = None
657
+ data_1 = self.data
658
+ add_tensor = torch.ops.aten.add.Tensor(data_1, x_1, alpha = 1); data_1 = None
659
+ data_2 = self.data
660
+ copy_ = torch_Tensor_copy_(data_2, add_tensor); data_2 = add_tensor = copy_ = None
661
+ data_3 = self.data
662
+ add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None
663
+ return add_tensor_1
664
+
665
+ class GraphModule(torch.nn.Module):
666
+ def forward(self, x_1):
667
+ # No stacktrace found for following nodes
668
+ data_3 = self.data
669
+ add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None
670
+ return add_tensor_1
671
+ """
672
+ gm.graph.eliminate_dead_code()
673
+ _clean_attr(gm)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional, TYPE_CHECKING, Union
5
+
6
+ import torch
7
+ from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled
8
+
9
+ from ..utils import node_inline_, nodes_filter, nodes_first, nodes_map, sequential_split
10
+ from .replace_with_hop_pass_util import (
11
+ _replace_with_hop_helper,
12
+ _replace_with_hop_pass_helper,
13
+ _sequential_split_and_maybe_inline_subgraphs_helper,
14
+ )
15
+
16
+
17
+ if TYPE_CHECKING:
18
+ from torch.export.graph_signature import ExportGraphSignature
19
+
20
+
21
+ def _is_set_grad_enabled_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
22
+ return (
23
+ node
24
+ and node.op == "call_function"
25
+ and node.target == torch._C._set_grad_enabled
26
+ )
27
+
28
+
29
+ def _is_set_grad_enabled_sub_mod(
30
+ node: torch.fx.Node, omit_if_same_with_ambient: bool = False
31
+ ) -> Union[bool, torch.Tensor]:
32
+ if node.op == "call_module":
33
+ assert isinstance(node.target, str)
34
+ subgm = getattr(node.graph.owning_module, node.target)
35
+ first_non_ph = nodes_first(
36
+ subgm.graph.nodes, lambda node: node.op != "placeholder"
37
+ )
38
+ if (
39
+ first_non_ph
40
+ and first_non_ph.op == "call_function"
41
+ and first_non_ph.target == torch._C._set_grad_enabled
42
+ ):
43
+ return (
44
+ first_non_ph.args[0] != torch.is_grad_enabled()
45
+ if omit_if_same_with_ambient
46
+ else True
47
+ )
48
+ return False
49
+
50
+
51
+ def _replace_with_hop(node: torch.fx.Node) -> None:
52
+ assert node.op == "call_module"
53
+ graph: torch.fx.Graph = node.graph
54
+ assert graph.owning_module is not None
55
+ gm: torch.fx.GraphModule = graph.owning_module
56
+ assert isinstance(node.target, str)
57
+ sub_gm = getattr(gm, node.target)
58
+ sub_graph = sub_gm.graph
59
+ set_grad_nodes = nodes_filter(sub_graph.nodes, _is_set_grad_enabled_node)
60
+ if len(set_grad_nodes) > 0:
61
+ assert len(set_grad_nodes) == 1
62
+ set_grad_node = set_grad_nodes[0]
63
+ _replace_with_hop_helper(node, set_grad_node, wrap_with_set_grad_enabled)
64
+ sub_graph.erase_node(set_grad_node)
65
+
66
+
67
+ def _remove_set_grad_and_inline(node: torch.fx.Node) -> None:
68
+ assert node.op == "call_module"
69
+ graph: torch.fx.Graph = node.graph
70
+ assert graph.owning_module is not None
71
+ gm: torch.fx.GraphModule = graph.owning_module
72
+ assert isinstance(node.target, str)
73
+ sub_gm = getattr(gm, node.target)
74
+ sub_graph = sub_gm.graph
75
+ nodes_map(
76
+ sub_graph.nodes,
77
+ lambda n: sub_graph.erase_node(n) if _is_set_grad_enabled_node(n) else n,
78
+ )
79
+ node_inline_(node)
80
+
81
+
82
+ def _sequential_split_and_maybe_inline_subgraphs(
83
+ gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
84
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
85
+ """
86
+ Helper function for replace_set_grad_with_hop_pass().
87
+ Split the graph module into multiple subgraphs based on the set_grad_enabled nodes.
88
+ For each subgraph, decides whether to construct a HOO subgraph, or inline the calls
89
+ back into the parent graph module.
90
+ """
91
+ need_replacing = any(_is_set_grad_enabled_node(node) for node in gm.graph.nodes)
92
+ if not need_replacing:
93
+ return gm, graph_signature
94
+
95
+ # sequential_split returns a new graph module that could have different output
96
+ # args names. We need to fix the graph signature.
97
+ new_gm = sequential_split(gm, _is_set_grad_enabled_node)
98
+
99
+ def _maybe_inline_or_replace_with_hop(node: torch.fx.Node):
100
+ if _is_set_grad_enabled_sub_mod(node, omit_if_same_with_ambient=True):
101
+ _replace_with_hop(node)
102
+ else:
103
+ _remove_set_grad_and_inline(node)
104
+
105
+ return _sequential_split_and_maybe_inline_subgraphs_helper(
106
+ new_gm, graph_signature, _maybe_inline_or_replace_with_hop
107
+ )
108
+
109
+
110
+ def replace_set_grad_with_hop_pass(
111
+ gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
112
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
113
+ """
114
+ Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
115
+ then recursively call itself on each of the submodules.
116
+ """
117
+ return _replace_with_hop_pass_helper(
118
+ gm,
119
+ graph_signature,
120
+ _sequential_split_and_maybe_inline_subgraphs,
121
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from torch._export.error import InternalError
6
+ from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse
7
+ from torch._ops import HigherOrderOperator, OpOverload
8
+
9
+
10
+ __all__ = ["ReplaceViewOpsWithViewCopyOpsPass"]
11
+
12
+
13
+ _NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: dict[OpOverload, OpOverload] = {
14
+ torch.ops.aten._unsafe_view.default: torch.ops.aten.view_copy.default,
15
+ }
16
+
17
+
18
+ def is_view_op(schema: torch._C.FunctionSchema) -> bool:
19
+ if len(schema.arguments) == 0:
20
+ return False
21
+ alias_info = schema.arguments[0].alias_info
22
+ return (alias_info is not None) and (not alias_info.is_write)
23
+
24
+
25
+ def get_view_copy_of_view_op(schema: torch._C.FunctionSchema) -> Optional[OpOverload]:
26
+ if is_view_op(schema) and schema.name.startswith("aten::"):
27
+ view_op_name = schema.name.split("::")[1]
28
+ view_op_overload = (
29
+ schema.overload_name if schema.overload_name != "" else "default"
30
+ )
31
+ view_copy_op_name = view_op_name + "_copy"
32
+ if not hasattr(torch.ops.aten, view_copy_op_name):
33
+ raise InternalError(f"{schema.name} is missing a view_copy variant")
34
+
35
+ view_copy_op_overload_packet = getattr(torch.ops.aten, view_copy_op_name)
36
+
37
+ if not hasattr(view_copy_op_overload_packet, view_op_overload):
38
+ raise InternalError(f"{schema.name} is missing a view_copy variant")
39
+
40
+ return getattr(view_copy_op_overload_packet, view_op_overload)
41
+
42
+ return None
43
+
44
+
45
+ class ReplaceViewOpsWithViewCopyOpsPass(_ExportPassBaseDeprecatedDoNotUse):
46
+ """
47
+ Our backend expects pure functional operators. For efficiency
48
+ purposes, we keep view ops around while functionalizing the exported
49
+ program. This pass replaces view ops with view copy ops for backends that
50
+ need AOT memory planning.
51
+ """
52
+
53
+ def call_operator(self, op, args, kwargs, meta):
54
+ if op in _NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS:
55
+ return super().call_operator(
56
+ (_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS[op]), args, kwargs, meta
57
+ )
58
+
59
+ if isinstance(op, HigherOrderOperator):
60
+ return super().call_operator(op, args, kwargs, meta)
61
+
62
+ if view_copy_op := get_view_copy_of_view_op(op._schema):
63
+ return super().call_operator(view_copy_op, args, kwargs, meta)
64
+
65
+ return super().call_operator(op, args, kwargs, meta)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/passes/replace_with_hop_pass_util.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import copy
6
+ import operator
7
+ from typing import Callable, Optional, TYPE_CHECKING
8
+
9
+ import torch
10
+
11
+ from ..utils import node_replace_, nodes_map
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from torch._ops import HigherOrderOperator
16
+ from torch.export.graph_signature import ExportGraphSignature
17
+
18
+
19
+ def _replace_with_hop_helper(
20
+ node: torch.fx.Node,
21
+ enter_block_node: torch.fx.Node,
22
+ wrap_hoo: HigherOrderOperator,
23
+ ) -> None:
24
+ graph: torch.fx.Graph = node.graph
25
+ assert graph.owning_module is not None
26
+ gm: torch.fx.GraphModule = graph.owning_module
27
+ assert isinstance(node.target, str)
28
+ sub_gm = getattr(gm, node.target)
29
+
30
+ def set_hoo_node_meta(call_func_node):
31
+ call_func_node.meta["nn_module_stack"] = copy.copy(
32
+ enter_block_node.meta.get("nn_module_stack", {})
33
+ )
34
+ call_func_node.meta["torch_fn"] = (
35
+ f"{wrap_hoo.__name__}",
36
+ f"{wrap_hoo.__class__.__name__}.{wrap_hoo.__name__}",
37
+ )
38
+ if isinstance(output_args, (tuple, list)):
39
+ call_func_node.meta["val"] = tuple(arg.meta["val"] for arg in output_args)
40
+ elif isinstance(output_args, torch.fx.Node):
41
+ call_func_node.meta["val"] = (output_args.meta["val"],)
42
+
43
+ with graph.inserting_before(node):
44
+ get_attr_node = graph.get_attr(node.target)
45
+ get_attr_node.meta["nn_module_stack"] = copy.copy(
46
+ enter_block_node.meta.get("nn_module_stack", {})
47
+ )
48
+ output_node = next(iter(reversed(sub_gm.graph.nodes)), None)
49
+ # Split_module pass intentially doesn't add output node
50
+ # if the graph doesn't return anything.
51
+ # TODO (tmanlaibaatar) Figure out if this is right behaviour
52
+ # for split_module
53
+ if isinstance(output_node, torch.fx.Node) and output_node.op != "output":
54
+ output_node = None
55
+ if output_node is not None:
56
+ assert len(output_node.args) == 1
57
+ output_args = output_node.args[0]
58
+ enter_block_node_args = enter_block_node.args
59
+ if isinstance(output_args, (tuple, list)):
60
+ call_func_node = graph.call_function(
61
+ wrap_hoo,
62
+ (*enter_block_node_args, get_attr_node, *node.args),
63
+ {},
64
+ )
65
+ # Create the metadata
66
+ set_hoo_node_meta(call_func_node)
67
+ node_replace_(node, call_func_node)
68
+
69
+ # Rename the name of getitem nodes to the actual name of its contents
70
+ # for passing verifier and better readability, also propagate metadata
71
+ for get_item_node in call_func_node.users.keys():
72
+ idx: int = get_item_node.args[1] # type: ignore[assignment]
73
+ output_node = output_args[idx]
74
+ get_item_node._rename(output_node.name)
75
+ get_item_node.meta = output_node.meta
76
+
77
+ elif isinstance(output_args, torch.fx.Node):
78
+ call_func_node = graph.create_node(
79
+ "call_function",
80
+ wrap_hoo,
81
+ (*enter_block_node_args, get_attr_node, *node.args),
82
+ {},
83
+ output_args.name,
84
+ )
85
+ # Modify the subgraph to output a singleton list.
86
+ output_node.args = ((output_args,),)
87
+ # Add in an extra `getitem(wrap_hoo, 0)` node to the toplevel graph.
88
+ get_item_node = graph.create_node(
89
+ "call_function",
90
+ operator.getitem,
91
+ (call_func_node, 0),
92
+ {},
93
+ )
94
+ # Create the metadata
95
+ get_item_node.meta = output_args.meta
96
+ set_hoo_node_meta(call_func_node)
97
+ node_replace_(node, get_item_node)
98
+ else:
99
+ raise NotImplementedError(
100
+ f"repalce_with_hop_pass doesnt' support output type {type(output_args)}"
101
+ )
102
+ else:
103
+ # TODO (shangdiy): remove this line, since the export graph can be non-functional
104
+ node.graph.erase_node(node)
105
+
106
+
107
+ def _sequential_split_and_maybe_inline_subgraphs_helper(
108
+ new_gm: torch.fx.GraphModule,
109
+ graph_signature: Optional[ExportGraphSignature],
110
+ maybe_inline_or_replace_with_hop: Callable[[torch.fx.Node], None],
111
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
112
+ """
113
+ Helper function for replacing graph nodse with higher order nodes.
114
+ For each subgraph in `new_gm`, decides whether to construct a HOO subgraph, or inline the calls
115
+ back into the parent graph module, depending on `maybe_inline_or_replace_with_hop`.
116
+ """
117
+ # new_gm is a new graph module that could have different output args names.
118
+ # We need to fix the graph signature.
119
+ replace_ctx = contextlib.nullcontext()
120
+ new_signature = None
121
+ if graph_signature is not None:
122
+ # Cannot deep copy a real ScriptObject, which is referenced
123
+ # in the FakeScriptObject. Copy should be good enough to guard
124
+ # against accidental mutation to original graph_signature.
125
+ new_signature = copy.copy(graph_signature)
126
+ new_gm_out_node = next(reversed(new_gm.graph.find_nodes(op="output")))
127
+ assert new_gm_out_node.op == "output" and len(new_gm_out_node.args[0]) == len(
128
+ new_signature.output_specs
129
+ )
130
+ for arg_node, out_spec in zip(
131
+ new_gm_out_node.args[0], new_signature.output_specs
132
+ ):
133
+ if arg_node is None:
134
+ assert out_spec.arg.value is None # type: ignore[union-attr]
135
+ elif (
136
+ isinstance(arg_node, torch.fx.Node)
137
+ and out_spec.arg.name != arg_node.name
138
+ ):
139
+ out_spec.arg.name = arg_node.name
140
+
141
+ replace_ctx = new_gm._set_replace_hook(new_signature.get_replace_hook()) # type: ignore[assignment]
142
+
143
+ with replace_ctx:
144
+ nodes_map(
145
+ list(new_gm.graph.nodes),
146
+ lambda node: (
147
+ maybe_inline_or_replace_with_hop(node)
148
+ if node.op == "call_module"
149
+ else node
150
+ ),
151
+ )
152
+ new_gm.recompile()
153
+ new_gm.graph.lint()
154
+ return new_gm, new_signature
155
+
156
+
157
+ def _replace_with_hop_pass_helper(
158
+ gm: torch.fx.GraphModule,
159
+ graph_signature: Optional[ExportGraphSignature],
160
+ sequential_split_and_maybe_inline_subgraphs: Callable[
161
+ [torch.fx.GraphModule, Optional[ExportGraphSignature]],
162
+ tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]],
163
+ ],
164
+ ) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
165
+ """
166
+ Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
167
+ then recursively call itself on each of the submodules.
168
+ """
169
+ new_gm, new_signature = sequential_split_and_maybe_inline_subgraphs(
170
+ gm, graph_signature
171
+ )
172
+ # recursively call
173
+ for node in new_gm.graph.nodes:
174
+ if node.op == "get_attr":
175
+ subgm = getattr(new_gm, node.target)
176
+ if not isinstance(subgm, torch.fx.GraphModule):
177
+ continue
178
+ new_subgm, _ = _replace_with_hop_pass_helper(
179
+ subgm,
180
+ None,
181
+ sequential_split_and_maybe_inline_subgraphs,
182
+ )
183
+ setattr(new_gm, node.target, new_subgm)
184
+
185
+ new_gm.recompile()
186
+ new_gm.graph.lint()
187
+ return new_gm, new_signature
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/__init__.py ADDED
File without changes
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/dynamic_shapes.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from typing import Any, Optional, Union
3
+
4
+ import torch
5
+ from torch._dynamo.exc import UserError, UserErrorType
6
+ from torch.export.dynamic_shapes import (
7
+ _check_dynamic_shapes,
8
+ _DerivedDim,
9
+ _DimHint,
10
+ _tree_map_with_path,
11
+ Dim,
12
+ )
13
+ from torch.utils._pytree import tree_map
14
+
15
+ from .serialize import _dataclass_to_dict
16
+
17
+
18
+ @dataclasses.dataclass
19
+ class RootDim:
20
+ """
21
+ This represents a Dim object.
22
+ """
23
+
24
+ min: int
25
+ max: Union[int, None]
26
+ derived: list[str]
27
+
28
+
29
+ @dataclasses.dataclass
30
+ class DynamicShapesSpec:
31
+ """
32
+ This stores a dynamic_shapes spec for de/serialization.
33
+ """
34
+
35
+ dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None]
36
+ dims: dict[str, RootDim]
37
+
38
+
39
+ def _postprocess_serialized_shapes(
40
+ dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
41
+ dims: dict[str, dict[str, Union[int, list[str], None]]],
42
+ to_dict: Optional[bool] = False,
43
+ ) -> Union[DynamicShapesSpec, dict[str, Any]]:
44
+ """
45
+ Sorts dims and dumps to dictionary format.
46
+ """
47
+ from torch.utils._sympy.numbers import int_oo
48
+
49
+ dims = {
50
+ k: RootDim(
51
+ min=v["min"], # type: ignore[arg-type]
52
+ max=None if v["max"] is int_oo else v["max"], # type: ignore[arg-type]
53
+ derived=sorted(v["derived"]), # type: ignore[arg-type]
54
+ )
55
+ for k, v in sorted(dims.items())
56
+ }
57
+ spec = DynamicShapesSpec(dynamic_shapes=dynamic_shapes, dims=dims)
58
+ if to_dict:
59
+ return _dataclass_to_dict(spec)
60
+ else:
61
+ return spec
62
+
63
+
64
+ def _dump_dynamic_shapes(
65
+ dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
66
+ args: tuple[Any],
67
+ kwargs: Optional[dict[str, Any]] = None,
68
+ to_dict: Optional[bool] = False,
69
+ ) -> Union[DynamicShapesSpec, dict[str, Any]]:
70
+ """
71
+ Utility function for dynamic shapes serialization, serializing a dynamic_shapes spec.
72
+ Returns a DynamicShapesSpec dataclass containing 2 fields, "dynamic_shapes" and "dims".
73
+ Uses args & kwargs to distinguish between tensor-level and dim-level specs (only for Nones).
74
+
75
+ dynamic_shapes: A pytree structure mirroring the dynamic_shapes input to export():
76
+ - Each tensor input is represented with a list of values, non-tensor inputs with None.
77
+ - dynamic dimensions (i.e. symbols) in tensors and Dim enums are represented with strings.
78
+ - static dimensions are represented with ints.
79
+
80
+ dims: A dictionary mapping each symbol name to the min/max range and derived dim names.
81
+
82
+ For example:
83
+ ```
84
+ dx = Dim("dx", min=4, max=16)
85
+ dy = dx + 1
86
+
87
+ inputs = (
88
+ [
89
+ torch.randn(4, 4),
90
+ torch.randn(5, 4),
91
+ ],
92
+ torch.randn(4),
93
+ torch.randn(4, 4),
94
+ "hello",
95
+ )
96
+ dynamic_shapes = {
97
+ "a": [
98
+ (dx, 4),
99
+ (dy, 4),
100
+ ],
101
+ "b": (Dim.STATIC,),
102
+ "c": None,
103
+ "d": None,
104
+ }
105
+ out = _dump_dynamic_shapes(dynamic_shapes, inputs, to_dict=True)
106
+ ```
107
+ would generate the following output:
108
+ ```
109
+ {
110
+ 'dynamic_shapes': (
111
+ [
112
+ ['dx', 4],
113
+ ['dx + 1', 4],
114
+ ],
115
+ ['_DimHint.STATIC'],
116
+ ['_DimHint.STATIC', '_DimHint.STATIC'],
117
+ None,
118
+ ),
119
+ 'dims': {
120
+ 'dx': {
121
+ 'min': 4,
122
+ 'max': 16,
123
+ 'derived': ['dx + 1'],
124
+ },
125
+ },
126
+ }
127
+ ```
128
+ """
129
+ dims: dict[str, dict[str, Any]] = {}
130
+
131
+ def _standardize_shapes(path, tensor, shape): # type: ignore[no-untyped-def]
132
+ """
133
+ Helps standardize the dynamic_shapes tree structure we serialize,
134
+ returning lists for each tensor shape, handling tensor-level Nones.
135
+ """
136
+ if not isinstance(tensor, torch.Tensor):
137
+ return None
138
+ if shape is None:
139
+ return [Dim.STATIC] * len(tensor.shape)
140
+
141
+ out = []
142
+ if isinstance(shape, dict):
143
+ for i, s in enumerate(tensor.shape):
144
+ out.append(s if shape.get(i) is None else shape.get(i))
145
+ else:
146
+ assert isinstance(shape, (tuple, list))
147
+ for i, s in enumerate(tensor.shape):
148
+ out.append(s if shape[i] is None else shape[i])
149
+ return out
150
+
151
+ def _track_dim_from_dims(
152
+ val: Union[None, int, _DimHint, Dim]
153
+ ) -> Union[None, int, str]:
154
+ """
155
+ Tracks dims, ranges, derived dims from the standardized dynamic_shapes spec.
156
+ """
157
+ if val is None or isinstance(val, int): # non-tensor input or static
158
+ return val
159
+ if isinstance(val, _DimHint): # store enum as string
160
+ return val.__class__.__name__ + "." + val.type.name
161
+
162
+ assert isinstance(val, Dim)
163
+
164
+ # track root dim
165
+ root = val.root if isinstance(val, _DerivedDim) else val # type: ignore[attr-defined]
166
+ if root.__name__ not in dims:
167
+ dims[root.__name__] = {
168
+ "min": root.min, # type: ignore[attr-defined,union-attr]
169
+ "max": root.max, # type: ignore[attr-defined,union-attr]
170
+ "derived": set(),
171
+ }
172
+
173
+ # track derived dims
174
+ if isinstance(val, _DerivedDim):
175
+ dims[root.__name__]["derived"].add(val.__name__)
176
+
177
+ return val.__name__
178
+
179
+ if dynamic_shapes is None:
180
+ return {"dynamic_shapes": None, "dims": {}}
181
+
182
+ # convert to tuple of specs, for each arg/kwarg
183
+ kwargs = kwargs or {}
184
+ if isinstance(dynamic_shapes, dict):
185
+ dynamic_shapes = dynamic_shapes.values() # type: ignore[assignment]
186
+ dynamic_shapes = tuple(dynamic_shapes)
187
+ combined_args = tuple(args) + tuple(kwargs.values())
188
+
189
+ # run same check when we're processing shapes for export - is this too lazy?
190
+ _check_dynamic_shapes(dict(enumerate(combined_args)), dynamic_shapes) # type: ignore[arg-type]
191
+
192
+ tree_shapes = _tree_map_with_path(
193
+ _standardize_shapes, combined_args, dynamic_shapes, tree_name="inputs"
194
+ )
195
+ serialized_shapes = tree_map(_track_dim_from_dims, tree_shapes)
196
+ return _postprocess_serialized_shapes(serialized_shapes, dims, to_dict=to_dict)
197
+
198
+
199
+ def _load_dynamic_shapes(
200
+ spec: Union[DynamicShapesSpec, dict[str, Any]],
201
+ from_dict: Optional[bool] = False,
202
+ ) -> Union[dict[str, Any], tuple[Any], list[Any], None]:
203
+ """
204
+ Utility function for dynamic shapes serialization.
205
+ Deserializes a DynamicShapesSpec or corresponding dictionary into a dynamic_shapes input to export().
206
+ """
207
+ import sympy
208
+
209
+ from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence
210
+
211
+ if from_dict:
212
+ if not isinstance(spec, dict):
213
+ raise UserError(
214
+ UserErrorType.INVALID_INPUT,
215
+ f"With from_dict=True, expected `spec` to be a dict, got {type(spec)}",
216
+ )
217
+ if sorted(spec.keys()) != ["dims", "dynamic_shapes"]:
218
+ raise UserError(
219
+ UserErrorType.INVALID_INPUT,
220
+ "With from_dict=True, expected `spec` to have keys `dims` and `dynamic_shapes`, "
221
+ f"instead found {spec.keys()}",
222
+ )
223
+ dims = {}
224
+ for k, v in spec["dims"].items():
225
+ if not isinstance(k, str):
226
+ raise UserError(
227
+ UserErrorType.INVALID_INPUT,
228
+ f"Expected `spec['dims']` keys to be strings for symbols, got key {type(k)}",
229
+ )
230
+ if sorted(v.keys()) != ["derived", "max", "min"]:
231
+ raise UserError(
232
+ UserErrorType.INVALID_INPUT,
233
+ f"Expected `spec['dims']` values to have keys `derived`, `max`, and `min`, "
234
+ f"instead found {v.keys()}",
235
+ )
236
+ if not isinstance(v["min"], int):
237
+ raise UserError(
238
+ UserErrorType.INVALID_INPUT,
239
+ f"Expected dims in `spec['dims']` to map `min` to an int, got {k}: {v['min']}",
240
+ )
241
+ if not isinstance(v["max"], int) or v["max"] is None:
242
+ raise UserError(
243
+ UserErrorType.INVALID_INPUT,
244
+ f"Expected dims in `spec['dims']` to map `max` to an int or None, got {k}: {v['max']}",
245
+ )
246
+ if not isinstance(v["derived"], list) or any(
247
+ not isinstance(d, str) for d in v["derived"]
248
+ ):
249
+ raise UserError(
250
+ UserErrorType.INVALID_INPUT,
251
+ "Expected dims in `spec['dims']` to map `derived` to a list of derived expressions, "
252
+ f"got {k}: {v['derived']}",
253
+ )
254
+ dims[k] = RootDim(**v)
255
+ dynamic_shapes = spec["dynamic_shapes"]
256
+ else:
257
+ if not isinstance(spec, DynamicShapesSpec):
258
+ raise UserError(
259
+ UserErrorType.INVALID_INPUT,
260
+ f"Expected `spec` to be a DynamicShapesSpec, got {type(spec)}",
261
+ )
262
+ dims = spec.dims
263
+ dynamic_shapes = spec.dynamic_shapes
264
+
265
+ if dynamic_shapes is None:
266
+ return None
267
+
268
+ dim_cache = {}
269
+ for name, info in dims.items():
270
+ symbol = sympy.sympify(name)
271
+ if not isinstance(symbol, sympy.Symbol):
272
+ raise UserError(
273
+ UserErrorType.INVALID_INPUT,
274
+ f"Expected `spec['dims']` keys to be symbols, got {name}",
275
+ )
276
+ dim_cache[name] = Dim(name, min=info.min, max=info.max) # cache root dim
277
+ for _expr in info.derived:
278
+ expr = sympy.sympify(_expr)
279
+ if len(expr.free_symbols) != 1 or symbol not in expr.free_symbols:
280
+ raise UserError(
281
+ UserErrorType.INVALID_INPUT,
282
+ f"Expected derived expressions in to have {name} as the only free symbol, got {expr}",
283
+ )
284
+ if not _is_supported_equivalence(expr):
285
+ raise UserError(
286
+ UserErrorType.INVALID_INPUT,
287
+ f"Expected derived expressions to be linear expressions, got {expr}",
288
+ )
289
+ modulus, remainder = sympy.polys.polytools.div(expr, symbol)
290
+ ddim = dim_cache[name]
291
+ if modulus != 1:
292
+ ddim = int(modulus) * ddim # type: ignore[assignment, operator]
293
+ if remainder != 0:
294
+ ddim = ddim + int(remainder) # type: ignore[assignment, operator]
295
+ dim_cache[_expr] = ddim # cache derived dims
296
+
297
+ def deserialize_shape(
298
+ val: Union[None, int, str]
299
+ ) -> Union[None, int, Dim, _DimHint]:
300
+ if val is None or isinstance(val, int):
301
+ return val
302
+ elif val == "_DimHint.AUTO":
303
+ return _DimHint.AUTO()
304
+ elif val == "_DimHint.DYNAMIC":
305
+ return _DimHint.DYNAMIC()
306
+ elif val == "_DimHint.STATIC":
307
+ return _DimHint.STATIC()
308
+ if not isinstance(val, str):
309
+ raise UserError(
310
+ UserErrorType.INVALID_INPUT,
311
+ "Expected leaves in `spec['dynamic_shapes']` to be ints, None, Dim.AUTO/STATIC, symbols, "
312
+ f" or derived expressions, got {val}",
313
+ )
314
+ if val not in dim_cache:
315
+ raise UserError(
316
+ UserErrorType.INVALID_INPUT,
317
+ "Expected dims in `spec['dynamic_shapes']` to be tracked in `spec['dims']`, "
318
+ f"got {val} which is not in {dims.keys()}",
319
+ )
320
+ return dim_cache[val] # type: ignore[return-value]
321
+
322
+ return tree_map(deserialize_shape, dynamic_shapes)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/export_schema.thrift ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @generated by update_schema.py
2
+ // checksum<<fd7996be362400fc786560be9e3d5680d1d7ec37b21d7a89d74146b669f72da6>>
3
+
4
+ namespace py3 torch._export
5
+ namespace cpp2 torch._export.schema
6
+
7
+ enum ArgumentKind {
8
+ UNKNOWN = 0,
9
+ POSITIONAL = 1,
10
+ KEYWORD = 2,
11
+ }
12
+
13
+
14
+ enum Layout {
15
+ Unknown = 0,
16
+ SparseCoo = 1,
17
+ SparseCsr = 2,
18
+ SparseCsc = 3,
19
+ SparseBsr = 4,
20
+ SparseBsc = 5,
21
+ _mkldnn = 6,
22
+ Strided = 7,
23
+ }
24
+
25
+
26
+ enum MemoryFormat {
27
+ Unknown = 0,
28
+ ContiguousFormat = 1,
29
+ ChannelsLast = 2,
30
+ ChannelsLast3d = 3,
31
+ PreserveFormat = 4,
32
+ }
33
+
34
+
35
+ enum ScalarType {
36
+ UNKNOWN = 0,
37
+ BYTE = 1,
38
+ CHAR = 2,
39
+ SHORT = 3,
40
+ INT = 4,
41
+ LONG = 5,
42
+ HALF = 6,
43
+ FLOAT = 7,
44
+ DOUBLE = 8,
45
+ COMPLEXHALF = 9,
46
+ COMPLEXFLOAT = 10,
47
+ COMPLEXDOUBLE = 11,
48
+ BOOL = 12,
49
+ BFLOAT16 = 13,
50
+ UINT16 = 28,
51
+ FLOAT8E4M3FN = 29,
52
+ FLOAT8E5M2 = 30,
53
+ }
54
+
55
+
56
+ struct Device {
57
+ 10: string type;
58
+ 20: optional i64 index;
59
+ }
60
+
61
+ union SymExprHint {
62
+ 10: i64 as_int;
63
+ 20: bool as_bool;
64
+ 30: double as_float;
65
+ }
66
+
67
+ struct SymExpr {
68
+ 10: string expr_str;
69
+ 20: optional SymExprHint hint;
70
+ }
71
+
72
+ union SymInt {
73
+ 10: SymExpr as_expr;
74
+ 20: i64 as_int;
75
+ }
76
+
77
+ union SymFloat {
78
+ 10: SymExpr as_expr;
79
+ 20: double as_float;
80
+ }
81
+
82
+ union SymBool {
83
+ 10: SymExpr as_expr;
84
+ 20: bool as_bool;
85
+ }
86
+
87
+ struct TensorMeta {
88
+ 10: ScalarType dtype;
89
+ 20: list<SymInt> sizes;
90
+ 30: bool requires_grad;
91
+ 40: Device device;
92
+ 50: list<SymInt> strides;
93
+ 60: SymInt storage_offset;
94
+ 70: Layout layout;
95
+ }
96
+
97
+ union SymIntArgument {
98
+ 10: string as_name;
99
+ 20: i64 as_int;
100
+ }
101
+
102
+ union SymFloatArgument {
103
+ 10: string as_name;
104
+ 20: double as_float;
105
+ }
106
+
107
+ union SymBoolArgument {
108
+ 10: string as_name;
109
+ 20: bool as_bool;
110
+ }
111
+
112
+ struct TensorArgument {
113
+ 10: string name;
114
+ }
115
+
116
+ struct TokenArgument {
117
+ 10: string name;
118
+ }
119
+
120
+ union OptionalTensorArgument {
121
+ 20: TensorArgument as_tensor;
122
+ 10: bool as_none;
123
+ }
124
+
125
+ struct GraphArgument {
126
+ 10: string name;
127
+ 20: Graph graph;
128
+ }
129
+
130
+ struct CustomObjArgument {
131
+ 10: string name;
132
+ 20: string class_fqn;
133
+ }
134
+
135
+ union Argument {
136
+ 10: bool as_none;
137
+ 20: TensorArgument as_tensor;
138
+ 30: list<TensorArgument> as_tensors;
139
+ 50: i64 as_int;
140
+ 70: list<i64> as_ints;
141
+ 80: double as_float;
142
+ 90: list<double> as_floats;
143
+ 100: string as_string;
144
+ 101: list<string> as_strings;
145
+ 110: SymIntArgument as_sym_int;
146
+ 120: list<SymIntArgument> as_sym_ints;
147
+ 130: ScalarType as_scalar_type;
148
+ 140: MemoryFormat as_memory_format;
149
+ 150: Layout as_layout;
150
+ 160: Device as_device;
151
+ 170: bool as_bool;
152
+ 180: list<bool> as_bools;
153
+ 182: SymBoolArgument as_sym_bool;
154
+ 184: list<SymBoolArgument> as_sym_bools;
155
+ 200: GraphArgument as_graph;
156
+ 190: list<OptionalTensorArgument> as_optional_tensors;
157
+ 210: CustomObjArgument as_custom_obj;
158
+ 220: string as_operator;
159
+ 230: SymFloatArgument as_sym_float;
160
+ 240: list<SymFloatArgument> as_sym_floats;
161
+ 250: OptionalTensorArgument as_optional_tensor;
162
+ }
163
+
164
+ struct NamedArgument {
165
+ 10: string name;
166
+ 20: Argument arg;
167
+ 30: optional ArgumentKind kind;
168
+ }
169
+
170
+ struct Node {
171
+ 10: string target;
172
+ 20: list<NamedArgument> inputs;
173
+ 30: list<Argument> outputs;
174
+ 40: map<string, string> metadata;
175
+ 50: optional bool is_hop_single_tensor_return;
176
+ }
177
+
178
+ struct Graph {
179
+ 10: list<Argument> inputs;
180
+ 20: list<Argument> outputs;
181
+ 30: list<Node> nodes;
182
+ 40: map<string, TensorMeta> tensor_values;
183
+ 50: map<string, SymInt> sym_int_values;
184
+ 60: map<string, SymBool> sym_bool_values;
185
+ 70: bool is_single_tensor_return;
186
+ 80: map<string, CustomObjArgument> custom_obj_values;
187
+ 90: map<string, SymFloat> sym_float_values;
188
+ }
189
+
190
+ struct UserInputSpec {
191
+ 10: Argument arg;
192
+ }
193
+
194
+ union ConstantValue {
195
+ 10: bool as_none;
196
+ 20: i64 as_int;
197
+ 30: double as_float;
198
+ 40: string as_string;
199
+ 50: bool as_bool;
200
+ }
201
+
202
+ struct InputToConstantInputSpec {
203
+ 10: string name;
204
+ 20: ConstantValue value;
205
+ }
206
+
207
+ struct InputToParameterSpec {
208
+ 10: TensorArgument arg;
209
+ 20: string parameter_name;
210
+ }
211
+
212
+ struct InputToBufferSpec {
213
+ 10: TensorArgument arg;
214
+ 20: string buffer_name;
215
+ 30: bool persistent;
216
+ }
217
+
218
+ struct InputToTensorConstantSpec {
219
+ 10: TensorArgument arg;
220
+ 20: string tensor_constant_name;
221
+ }
222
+
223
+ struct InputToCustomObjSpec {
224
+ 10: CustomObjArgument arg;
225
+ 20: string custom_obj_name;
226
+ }
227
+
228
+ struct InputTokenSpec {
229
+ 10: TokenArgument arg;
230
+ }
231
+
232
+ union InputSpec {
233
+ 10: UserInputSpec user_input;
234
+ 20: InputToParameterSpec parameter;
235
+ 30: InputToBufferSpec buffer;
236
+ 40: InputToTensorConstantSpec tensor_constant;
237
+ 50: InputToCustomObjSpec custom_obj;
238
+ 70: InputTokenSpec token;
239
+ 60: InputToConstantInputSpec constant_input;
240
+ }
241
+
242
+ struct UserOutputSpec {
243
+ 10: Argument arg;
244
+ }
245
+
246
+ struct LossOutputSpec {
247
+ 10: TensorArgument arg;
248
+ }
249
+
250
+ struct BufferMutationSpec {
251
+ 10: TensorArgument arg;
252
+ 20: string buffer_name;
253
+ }
254
+
255
+ struct GradientToParameterSpec {
256
+ 10: TensorArgument arg;
257
+ 20: string parameter_name;
258
+ }
259
+
260
+ struct GradientToUserInputSpec {
261
+ 10: TensorArgument arg;
262
+ 20: string user_input_name;
263
+ }
264
+
265
+ struct UserInputMutationSpec {
266
+ 10: TensorArgument arg;
267
+ 20: string user_input_name;
268
+ }
269
+
270
+ struct OutputTokenSpec {
271
+ 10: TokenArgument arg;
272
+ }
273
+
274
+ union OutputSpec {
275
+ 10: UserOutputSpec user_output;
276
+ 20: LossOutputSpec loss_output;
277
+ 30: BufferMutationSpec buffer_mutation;
278
+ 40: GradientToParameterSpec gradient_to_parameter;
279
+ 50: GradientToUserInputSpec gradient_to_user_input;
280
+ 60: UserInputMutationSpec user_input_mutation;
281
+ 70: OutputTokenSpec token;
282
+ }
283
+
284
+ struct GraphSignature {
285
+ 10: list<InputSpec> input_specs;
286
+ 20: list<OutputSpec> output_specs;
287
+ }
288
+
289
+ struct RangeConstraint {
290
+ 10: optional i64 min_val;
291
+ 20: optional i64 max_val;
292
+ }
293
+
294
+ struct ModuleCallSignature {
295
+ 10: list<Argument> inputs;
296
+ 20: list<Argument> outputs;
297
+ 30: string in_spec;
298
+ 40: string out_spec;
299
+ 50: optional list<string> forward_arg_names;
300
+ }
301
+
302
+ struct ModuleCallEntry {
303
+ 10: string fqn;
304
+ 30: optional ModuleCallSignature signature;
305
+ }
306
+
307
+ struct NamedTupleDef {
308
+ 10: list<string> field_names;
309
+ }
310
+
311
+ struct GraphModule {
312
+ 10: Graph graph;
313
+ 50: GraphSignature signature;
314
+ 60: list<ModuleCallEntry> module_call_graph;
315
+ 40: map<string, string> metadata;
316
+ 70: map<string, NamedTupleDef> treespec_namedtuple_fields;
317
+ }
318
+
319
+ struct SchemaVersion {
320
+ 10: i64 major;
321
+ 20: i64 minor;
322
+ }
323
+
324
+ struct ExportedProgram {
325
+ 10: GraphModule graph_module;
326
+ 20: map<string, i64> opset_version;
327
+ 30: map<string, RangeConstraint> range_constraints;
328
+ 60: SchemaVersion schema_version;
329
+ 70: list<string> verifiers;
330
+ 80: string torch_version;
331
+ }
332
+
333
+ struct Program {
334
+ 200: map<string, ExportedProgram> methods;
335
+ }
336
+
337
+ struct Model {
338
+ 10: string name;
339
+ 20: map<string, string> tensorPaths;
340
+ 40: Program program;
341
+ 50: map<string, Program> delegates;
342
+ 60: map<string, string> deviceAllocationMap;
343
+ 70: map<string, string> constantPaths;
344
+ }
345
+
346
+ struct AOTInductorModelPickleData {
347
+ 1: string library_basename;
348
+ 2: list<string> input_names;
349
+ 3: list<string> output_names;
350
+ 4: optional i64 floating_point_input_dtype;
351
+ 5: optional i64 floating_point_output_dtype;
352
+ 6: optional bool aot_inductor_model_is_cpu;
353
+ }
354
+
355
+ struct ExternKernelNode {
356
+ 10: string name;
357
+ 20: Node node;
358
+ }
359
+
360
+ struct ExternKernelNodes {
361
+ 10: list<ExternKernelNode> nodes;
362
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTE: This is a placeholder for iterating on export serialization schema design.
2
+ # Anything is subject to change and no guarantee is provided at this point.
3
+
4
+ from dataclasses import dataclass, field
5
+ from enum import IntEnum
6
+ from typing import Annotated, Optional
7
+
8
+ from torch._export.serde.union import _Union
9
+
10
+
11
+ # NOTE: Please update this value if any modifications are made to the schema
12
+ SCHEMA_VERSION = (8, 8)
13
+ TREESPEC_VERSION = 1
14
+
15
+
16
+ # NOTE: If you updated the schema, please run `scripts/export/update_schema.py`
17
+ # to update the auto generated files.
18
+ class ScalarType(IntEnum):
19
+ UNKNOWN = 0
20
+ BYTE = 1
21
+ CHAR = 2
22
+ SHORT = 3
23
+ INT = 4
24
+ LONG = 5
25
+ HALF = 6
26
+ FLOAT = 7
27
+ DOUBLE = 8
28
+ COMPLEXHALF = 9
29
+ COMPLEXFLOAT = 10
30
+ COMPLEXDOUBLE = 11
31
+ BOOL = 12
32
+ BFLOAT16 = 13
33
+ UINT16 = 28
34
+ FLOAT8E4M3FN = 29
35
+ FLOAT8E5M2 = 30
36
+
37
+
38
+ class Layout(IntEnum):
39
+ Unknown = 0
40
+ SparseCoo = 1
41
+ SparseCsr = 2
42
+ SparseCsc = 3
43
+ SparseBsr = 4
44
+ SparseBsc = 5
45
+ _mkldnn = 6
46
+ Strided = 7
47
+
48
+
49
+ class MemoryFormat(IntEnum):
50
+ Unknown = 0
51
+ ContiguousFormat = 1
52
+ ChannelsLast = 2
53
+ ChannelsLast3d = 3
54
+ PreserveFormat = 4
55
+
56
+
57
+ @dataclass
58
+ class Device:
59
+ type: Annotated[str, 10]
60
+ index: Annotated[Optional[int], 20] = None
61
+
62
+
63
+ @dataclass(repr=False)
64
+ class SymExprHint(_Union):
65
+ as_int: Annotated[int, 10]
66
+ as_bool: Annotated[bool, 20]
67
+ as_float: Annotated[float, 30]
68
+
69
+
70
+ # This is for storing the symbolic expressions behind symints/symfloats/symbools
71
+ # For example, we can get something like
72
+ # SymExpr(expr_str="s0 + s1", hint=SymExprHint(as_int=4)
73
+ # if we also have the hint that s0 and s1 are both 2.
74
+ @dataclass
75
+ class SymExpr:
76
+ expr_str: Annotated[str, 10]
77
+ hint: Annotated[Optional[SymExprHint], 20] = None
78
+
79
+
80
+ @dataclass(repr=False)
81
+ class SymInt(_Union):
82
+ as_expr: Annotated[SymExpr, 10]
83
+ as_int: Annotated[int, 20]
84
+
85
+
86
+ @dataclass(repr=False)
87
+ class SymFloat(_Union):
88
+ as_expr: Annotated[SymExpr, 10]
89
+ as_float: Annotated[float, 20]
90
+
91
+
92
+ @dataclass(repr=False)
93
+ class SymBool(_Union):
94
+ as_expr: Annotated[SymExpr, 10]
95
+ as_bool: Annotated[bool, 20]
96
+
97
+
98
+ @dataclass
99
+ class TensorMeta:
100
+ dtype: Annotated[ScalarType, 10]
101
+ sizes: Annotated[list[SymInt], 20]
102
+ requires_grad: Annotated[bool, 30]
103
+ device: Annotated[Device, 40]
104
+ strides: Annotated[list[SymInt], 50]
105
+ storage_offset: Annotated[SymInt, 60]
106
+ layout: Annotated[Layout, 70]
107
+
108
+
109
+ # In most cases we will use the "as_name" field to store arguments which are
110
+ # SymInts.
111
+ # The "as_int" field is used in the case where we have a list containing a mix
112
+ # of SymInt and ints (ex. [1, s0, ...]). We will serialize this type of list to
113
+ # be List[SymIntArgument] and map the SymInts to the "as_name" field, and ints
114
+ # to the "as_int" field.
115
+ @dataclass(repr=False)
116
+ class SymIntArgument(_Union):
117
+ as_name: Annotated[str, 10]
118
+ as_int: Annotated[int, 20]
119
+
120
+
121
+ # In most cases we will use the "as_name" field to store arguments which are
122
+ # SymFloats.
123
+ # The "as_float" field is used in the case where we have a list containing a mix
124
+ # of SymFloat and float (ex. [1.0, s0, ...]). We will serialize this type of list to
125
+ # be List[SymFloatArgument] and map the SymFloats to the "as_name" field, and ints
126
+ # to the "as_float" field.
127
+ @dataclass(repr=False)
128
+ class SymFloatArgument(_Union):
129
+ as_name: Annotated[str, 10]
130
+ as_float: Annotated[float, 20]
131
+
132
+
133
+ # In most cases we will use the "as_name" field to store arguments which are
134
+ # SymBools.
135
+ # The "as_bool" field is used in the case where we have a list containing a mix
136
+ # of SymBool and bools (ex. [True, i0, ...]). We will serialize this type of list to
137
+ # be List[SymboolArgument] and map the SymBools to the "as_name" field, and bools
138
+ # to the "as_bool" field.
139
+ @dataclass(repr=False)
140
+ class SymBoolArgument(_Union):
141
+ as_name: Annotated[str, 10]
142
+ as_bool: Annotated[bool, 20]
143
+
144
+
145
+ @dataclass
146
+ class TensorArgument:
147
+ name: Annotated[str, 10]
148
+
149
+
150
+ @dataclass
151
+ class TokenArgument:
152
+ name: Annotated[str, 10]
153
+
154
+
155
+ # This is use for storing the contents of a list which contain optional tensors
156
+ # (Tensor?[], ex. [Tensor, None, ...]), where the list will be serialized to the
157
+ # type List[OptionalTensorArgument], with tensor values seiralized to the
158
+ # "as_tensor" field, and None values serialized to the "as_none" field.
159
+ @dataclass(repr=False)
160
+ class OptionalTensorArgument(_Union):
161
+ as_tensor: Annotated[TensorArgument, 20]
162
+ as_none: Annotated[bool, 10]
163
+
164
+
165
+ @dataclass
166
+ class GraphArgument:
167
+ name: Annotated[str, 10]
168
+ graph: Annotated["Graph", 20]
169
+
170
+
171
+ @dataclass
172
+ class CustomObjArgument:
173
+ name: Annotated[str, 10]
174
+ class_fqn: Annotated[str, 20]
175
+
176
+
177
+ # This is actually a union type
178
+ @dataclass(repr=False)
179
+ class Argument(_Union):
180
+ as_none: Annotated[bool, 10]
181
+ as_tensor: Annotated[TensorArgument, 20]
182
+ as_tensors: Annotated[list[TensorArgument], 30]
183
+ as_int: Annotated[int, 50]
184
+ as_ints: Annotated[list[int], 70]
185
+ as_float: Annotated[float, 80]
186
+ as_floats: Annotated[list[float], 90]
187
+ as_string: Annotated[str, 100]
188
+ as_strings: Annotated[list[str], 101]
189
+ as_sym_int: Annotated[SymIntArgument, 110]
190
+ as_sym_ints: Annotated[list[SymIntArgument], 120]
191
+ as_scalar_type: Annotated[ScalarType, 130]
192
+ as_memory_format: Annotated[MemoryFormat, 140]
193
+ as_layout: Annotated[Layout, 150]
194
+ as_device: Annotated[Device, 160]
195
+ as_bool: Annotated[bool, 170]
196
+ as_bools: Annotated[list[bool], 180]
197
+ as_sym_bool: Annotated[SymBoolArgument, 182]
198
+ as_sym_bools: Annotated[list[SymBoolArgument], 184]
199
+ as_graph: Annotated[GraphArgument, 200]
200
+ as_optional_tensors: Annotated[list[OptionalTensorArgument], 190]
201
+ as_custom_obj: Annotated[CustomObjArgument, 210]
202
+ as_operator: Annotated[str, 220]
203
+ as_sym_float: Annotated[SymFloatArgument, 230]
204
+ as_sym_floats: Annotated[list[SymFloatArgument], 240]
205
+ as_optional_tensor: Annotated[OptionalTensorArgument, 250]
206
+
207
+
208
+ class ArgumentKind(IntEnum):
209
+ UNKNOWN = 0
210
+ POSITIONAL = 1
211
+ KEYWORD = 2
212
+
213
+
214
+ @dataclass
215
+ class NamedArgument:
216
+ # Argument name from the operator schema
217
+ name: Annotated[str, 10]
218
+ arg: Annotated[Argument, 20]
219
+ kind: Annotated[Optional[ArgumentKind], 30] = None
220
+
221
+
222
+ @dataclass
223
+ class Node:
224
+ target: Annotated[str, 10]
225
+ inputs: Annotated[list[NamedArgument], 20]
226
+ outputs: Annotated[list[Argument], 30]
227
+ metadata: Annotated[dict[str, str], 40]
228
+ is_hop_single_tensor_return: Annotated[Optional[bool], 50] = None
229
+
230
+
231
+ @dataclass
232
+ class Graph:
233
+ inputs: Annotated[list[Argument], 10]
234
+ outputs: Annotated[list[Argument], 20]
235
+ nodes: Annotated[list[Node], 30]
236
+ tensor_values: Annotated[dict[str, TensorMeta], 40]
237
+ sym_int_values: Annotated[dict[str, SymInt], 50]
238
+ sym_bool_values: Annotated[dict[str, SymBool], 60]
239
+ # This is for deserializing the submodule graphs from higher order ops
240
+ # (ex. cond, map) where single tensor returns will just return a single
241
+ # tensor, rather than following export schema and returning a singleton
242
+ # list.
243
+ is_single_tensor_return: Annotated[bool, 70] = False
244
+ custom_obj_values: Annotated[dict[str, CustomObjArgument], 80] = field(
245
+ default_factory=dict
246
+ )
247
+ sym_float_values: Annotated[dict[str, SymFloat], 90] = field(default_factory=dict)
248
+
249
+
250
+ @dataclass
251
+ class UserInputSpec:
252
+ # Actually, only tensors and SymInts are allowed here
253
+ arg: Annotated[Argument, 10]
254
+
255
+
256
+ @dataclass(repr=False)
257
+ class ConstantValue(_Union):
258
+ as_none: Annotated[bool, 10]
259
+ as_int: Annotated[int, 20]
260
+ as_float: Annotated[float, 30]
261
+ as_string: Annotated[str, 40]
262
+ as_bool: Annotated[bool, 50]
263
+
264
+
265
+ @dataclass
266
+ class InputToConstantInputSpec:
267
+ name: Annotated[str, 10]
268
+ value: Annotated[ConstantValue, 20]
269
+
270
+
271
+ @dataclass
272
+ class InputToParameterSpec:
273
+ arg: Annotated[TensorArgument, 10]
274
+ parameter_name: Annotated[str, 20]
275
+
276
+
277
+ @dataclass
278
+ class InputToBufferSpec:
279
+ arg: Annotated[TensorArgument, 10]
280
+ buffer_name: Annotated[str, 20]
281
+ persistent: Annotated[bool, 30]
282
+
283
+
284
+ @dataclass
285
+ class InputToTensorConstantSpec:
286
+ arg: Annotated[TensorArgument, 10]
287
+ tensor_constant_name: Annotated[str, 20]
288
+
289
+
290
+ @dataclass
291
+ class InputToCustomObjSpec:
292
+ arg: Annotated[CustomObjArgument, 10]
293
+ custom_obj_name: Annotated[str, 20]
294
+
295
+
296
+ @dataclass
297
+ class InputTokenSpec:
298
+ arg: Annotated[TokenArgument, 10]
299
+
300
+
301
+ @dataclass(repr=False)
302
+ class InputSpec(_Union):
303
+ user_input: Annotated[UserInputSpec, 10]
304
+ parameter: Annotated[InputToParameterSpec, 20]
305
+ buffer: Annotated[InputToBufferSpec, 30]
306
+ tensor_constant: Annotated[InputToTensorConstantSpec, 40]
307
+ custom_obj: Annotated[InputToCustomObjSpec, 50]
308
+ token: Annotated[InputTokenSpec, 70]
309
+ constant_input: Annotated[InputToConstantInputSpec, 60]
310
+
311
+
312
+ @dataclass
313
+ class UserOutputSpec:
314
+ arg: Annotated[Argument, 10]
315
+
316
+
317
+ @dataclass
318
+ class LossOutputSpec:
319
+ arg: Annotated[TensorArgument, 10]
320
+
321
+
322
+ @dataclass
323
+ class BufferMutationSpec:
324
+ arg: Annotated[TensorArgument, 10]
325
+ buffer_name: Annotated[str, 20]
326
+
327
+
328
+ @dataclass
329
+ class GradientToParameterSpec:
330
+ arg: Annotated[TensorArgument, 10]
331
+ parameter_name: Annotated[str, 20]
332
+
333
+
334
+ @dataclass
335
+ class GradientToUserInputSpec:
336
+ arg: Annotated[TensorArgument, 10]
337
+ user_input_name: Annotated[str, 20]
338
+
339
+
340
+ @dataclass
341
+ class UserInputMutationSpec:
342
+ arg: Annotated[TensorArgument, 10]
343
+ user_input_name: Annotated[str, 20]
344
+
345
+
346
+ @dataclass
347
+ class OutputTokenSpec:
348
+ arg: Annotated[TokenArgument, 10]
349
+
350
+
351
+ @dataclass(repr=False)
352
+ class OutputSpec(_Union):
353
+ user_output: Annotated[UserOutputSpec, 10]
354
+ loss_output: Annotated[LossOutputSpec, 20]
355
+ buffer_mutation: Annotated[BufferMutationSpec, 30]
356
+ gradient_to_parameter: Annotated[GradientToParameterSpec, 40]
357
+ gradient_to_user_input: Annotated[GradientToUserInputSpec, 50]
358
+ user_input_mutation: Annotated[UserInputMutationSpec, 60]
359
+ token: Annotated[OutputTokenSpec, 70]
360
+
361
+
362
+ @dataclass
363
+ class GraphSignature:
364
+ input_specs: Annotated[list[InputSpec], 10]
365
+ output_specs: Annotated[list[OutputSpec], 20]
366
+
367
+
368
+ @dataclass
369
+ class RangeConstraint:
370
+ min_val: Annotated[Optional[int], 10]
371
+ max_val: Annotated[Optional[int], 20]
372
+
373
+
374
+ @dataclass
375
+ class ModuleCallSignature:
376
+ inputs: Annotated[list[Argument], 10]
377
+ outputs: Annotated[list[Argument], 20]
378
+
379
+ # These are serialized by calling pytree.treespec_loads
380
+ # And deserialized by calling pytree.treespec_dumps
381
+ in_spec: Annotated[str, 30]
382
+ out_spec: Annotated[str, 40]
383
+
384
+ # This field is used to prettify the graph placeholders
385
+ # after we ser/der and retrace
386
+ forward_arg_names: Annotated[Optional[list[str]], 50] = None
387
+
388
+
389
+ @dataclass
390
+ class ModuleCallEntry:
391
+ fqn: Annotated[str, 10]
392
+ signature: Annotated[Optional[ModuleCallSignature], 30] = None
393
+
394
+
395
+ @dataclass
396
+ class NamedTupleDef:
397
+ field_names: Annotated[list[str], 10]
398
+
399
+
400
+ @dataclass
401
+ class GraphModule:
402
+ graph: Annotated[Graph, 10]
403
+ signature: Annotated[GraphSignature, 50]
404
+ # This is used for unflattening, by tracking the calling structure of all of
405
+ # the modules in order to unflatten the modules back to the eager calling
406
+ # conventions.
407
+ module_call_graph: Annotated[list[ModuleCallEntry], 60]
408
+ metadata: Annotated[dict[str, str], 40] = field(default_factory=dict)
409
+ # Mapping of namedtuple types to namedtuple field names, used for BC
410
+ treespec_namedtuple_fields: Annotated[dict[str, NamedTupleDef], 70] = field(
411
+ default_factory=dict
412
+ )
413
+
414
+
415
+ # Invariant: Every time a change is made to the schema, one of the versions
416
+ # should be upadted.
417
+ @dataclass
418
+ class SchemaVersion:
419
+ major: Annotated[
420
+ int, 10
421
+ ] # Major version number is bumped every time a breaking change is made.
422
+ minor: Annotated[
423
+ int, 20
424
+ ] # Minor version number is bumped when a compatible change is made.
425
+
426
+
427
+ @dataclass
428
+ class ExportedProgram:
429
+ graph_module: Annotated[GraphModule, 10]
430
+ # Key is the opset namespace (ex. aten), and value is the version number
431
+ opset_version: Annotated[dict[str, int], 20]
432
+ range_constraints: Annotated[dict[str, RangeConstraint], 30]
433
+ schema_version: Annotated[SchemaVersion, 60]
434
+ verifiers: Annotated[list[str], 70] = field(default_factory=list)
435
+ torch_version: Annotated[str, 80] = "<=2.4"
436
+
437
+
438
+ #########################################################################
439
+ # Container types for inference tasks, not being used directly for export.
440
+ #########################################################################
441
+
442
+
443
+ @dataclass
444
+ class Program:
445
+ methods: Annotated[dict[str, ExportedProgram], 200]
446
+
447
+
448
+ # This is the top-level model definition that be will serialized into the package
449
+ @dataclass
450
+ class Model:
451
+ # unique identifier of the model in the package, e.g. local, remote, merge
452
+ name: Annotated[str, 10]
453
+ # key is the FQN of tensor in exported program
454
+ # value is the archive path of tensor payloads
455
+ # e.g. "L__self__linear.weight" : "/data/tensor/L__self__linear.weight"
456
+ tensorPaths: Annotated[dict[str, str], 20]
457
+ # program exported from torch.export()
458
+ program: Annotated[Program, 40]
459
+ # Backend-specialized Lowered GraphModule
460
+ # e.g. "aotinductor-a100" : ExportedProgram_with_AOTInductor_delegate
461
+ delegates: Annotated[dict[str, Program], 50]
462
+ deviceAllocationMap: Annotated[dict[str, str], 60]
463
+ # key is the FQN of constant in exported program (constant tensor or torchbind objs)
464
+ # value is the archive path of serialized constants
465
+ constantPaths: Annotated[dict[str, str], 70]
466
+
467
+
468
+ #
469
+ # The structure is used to serialize instances of AOTInductorModel to pass
470
+ # them from the publishing pipeline to the predictor.
471
+ #
472
+ # All new fields should be marked as optional.
473
+ #
474
+ @dataclass
475
+ class AOTInductorModelPickleData:
476
+ # Base name of an associated .so AOTInductor library. Typically looks like:
477
+ # "abc.so".
478
+ library_basename: Annotated[str, 1]
479
+
480
+ # AOTInductor engine input names.
481
+ input_names: Annotated[list[str], 2]
482
+
483
+ # AOTInductor engine output names.
484
+ output_names: Annotated[list[str], 3]
485
+
486
+ # These fields tell whether floating point inputs/outputs should be converted to
487
+ # a certain type. If None, the dtypes that the AOTInductor engine inferred from the sample
488
+ # inputs are used.
489
+ floating_point_input_dtype: Annotated[Optional[int], 4] = None
490
+ floating_point_output_dtype: Annotated[Optional[int], 5] = None
491
+
492
+ # Whether AOTInductor runtime is for CPU.
493
+ aot_inductor_model_is_cpu: Annotated[Optional[bool], 6] = None
494
+
495
+
496
+ @dataclass
497
+ class ExternKernelNode:
498
+ # name is not the unique identifier of the node
499
+ name: Annotated[str, 10]
500
+ node: Annotated[Node, 20]
501
+
502
+
503
+ @dataclass
504
+ class ExternKernelNodes:
505
+ nodes: Annotated[list[ExternKernelNode], 10]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema.yaml ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @generated by update_schema.py
2
+ # checksum<<110c364974d3b0f7dcbdf6862781212bdcc7178925c43c894c336fc2b6ca6628>>
3
+ AOTInductorModelPickleData:
4
+ kind: struct
5
+ fields:
6
+ library_basename:
7
+ type: str
8
+ input_names:
9
+ type: List[str]
10
+ output_names:
11
+ type: List[str]
12
+ floating_point_input_dtype:
13
+ type: Optional[int]
14
+ default: None
15
+ floating_point_output_dtype:
16
+ type: Optional[int]
17
+ default: None
18
+ aot_inductor_model_is_cpu:
19
+ type: Optional[bool]
20
+ default: None
21
+ Argument:
22
+ kind: union
23
+ fields:
24
+ as_none:
25
+ type: bool
26
+ as_tensor:
27
+ type: TensorArgument
28
+ as_tensors:
29
+ type: List[TensorArgument]
30
+ as_int:
31
+ type: int
32
+ as_ints:
33
+ type: List[int]
34
+ as_float:
35
+ type: float
36
+ as_floats:
37
+ type: List[float]
38
+ as_string:
39
+ type: str
40
+ as_strings:
41
+ type: List[str]
42
+ as_sym_int:
43
+ type: SymIntArgument
44
+ as_sym_ints:
45
+ type: List[SymIntArgument]
46
+ as_scalar_type:
47
+ type: ScalarType
48
+ as_memory_format:
49
+ type: MemoryFormat
50
+ as_layout:
51
+ type: Layout
52
+ as_device:
53
+ type: Device
54
+ as_bool:
55
+ type: bool
56
+ as_bools:
57
+ type: List[bool]
58
+ as_sym_bool:
59
+ type: SymBoolArgument
60
+ as_sym_bools:
61
+ type: List[SymBoolArgument]
62
+ as_graph:
63
+ type: GraphArgument
64
+ as_optional_tensors:
65
+ type: List[OptionalTensorArgument]
66
+ as_custom_obj:
67
+ type: CustomObjArgument
68
+ as_operator:
69
+ type: str
70
+ as_sym_float:
71
+ type: SymFloatArgument
72
+ as_sym_floats:
73
+ type: List[SymFloatArgument]
74
+ as_optional_tensor:
75
+ type: OptionalTensorArgument
76
+ ArgumentKind:
77
+ kind: enum
78
+ fields:
79
+ UNKNOWN: 0
80
+ POSITIONAL: 1
81
+ KEYWORD: 2
82
+ BufferMutationSpec:
83
+ kind: struct
84
+ fields:
85
+ arg:
86
+ type: TensorArgument
87
+ buffer_name:
88
+ type: str
89
+ ConstantValue:
90
+ kind: union
91
+ fields:
92
+ as_none:
93
+ type: bool
94
+ as_int:
95
+ type: int
96
+ as_float:
97
+ type: float
98
+ as_string:
99
+ type: str
100
+ as_bool:
101
+ type: bool
102
+ CustomObjArgument:
103
+ kind: struct
104
+ fields:
105
+ name:
106
+ type: str
107
+ class_fqn:
108
+ type: str
109
+ Device:
110
+ kind: struct
111
+ fields:
112
+ type:
113
+ type: str
114
+ index:
115
+ type: Optional[int]
116
+ default: None
117
+ ExportedProgram:
118
+ kind: struct
119
+ fields:
120
+ graph_module:
121
+ type: GraphModule
122
+ opset_version:
123
+ type: Dict[str, int]
124
+ range_constraints:
125
+ type: Dict[str, RangeConstraint]
126
+ schema_version:
127
+ type: SchemaVersion
128
+ verifiers:
129
+ type: List[str]
130
+ default: '[]'
131
+ torch_version:
132
+ type: str
133
+ default: <=2.4
134
+ ExternKernelNode:
135
+ kind: struct
136
+ fields:
137
+ name:
138
+ type: str
139
+ node:
140
+ type: Node
141
+ ExternKernelNodes:
142
+ kind: struct
143
+ fields:
144
+ nodes:
145
+ type: List[ExternKernelNode]
146
+ GradientToParameterSpec:
147
+ kind: struct
148
+ fields:
149
+ arg:
150
+ type: TensorArgument
151
+ parameter_name:
152
+ type: str
153
+ GradientToUserInputSpec:
154
+ kind: struct
155
+ fields:
156
+ arg:
157
+ type: TensorArgument
158
+ user_input_name:
159
+ type: str
160
+ Graph:
161
+ kind: struct
162
+ fields:
163
+ inputs:
164
+ type: List[Argument]
165
+ outputs:
166
+ type: List[Argument]
167
+ nodes:
168
+ type: List[Node]
169
+ tensor_values:
170
+ type: Dict[str, TensorMeta]
171
+ sym_int_values:
172
+ type: Dict[str, SymInt]
173
+ sym_bool_values:
174
+ type: Dict[str, SymBool]
175
+ is_single_tensor_return:
176
+ type: bool
177
+ default: 'False'
178
+ custom_obj_values:
179
+ type: Dict[str, CustomObjArgument]
180
+ default: '{}'
181
+ sym_float_values:
182
+ type: Dict[str, SymFloat]
183
+ default: '{}'
184
+ GraphArgument:
185
+ kind: struct
186
+ fields:
187
+ name:
188
+ type: str
189
+ graph:
190
+ type: Graph
191
+ GraphModule:
192
+ kind: struct
193
+ fields:
194
+ graph:
195
+ type: Graph
196
+ signature:
197
+ type: GraphSignature
198
+ module_call_graph:
199
+ type: List[ModuleCallEntry]
200
+ metadata:
201
+ type: Dict[str, str]
202
+ default: '{}'
203
+ treespec_namedtuple_fields:
204
+ type: Dict[str, NamedTupleDef]
205
+ default: '{}'
206
+ GraphSignature:
207
+ kind: struct
208
+ fields:
209
+ input_specs:
210
+ type: List[InputSpec]
211
+ output_specs:
212
+ type: List[OutputSpec]
213
+ InputSpec:
214
+ kind: union
215
+ fields:
216
+ user_input:
217
+ type: UserInputSpec
218
+ parameter:
219
+ type: InputToParameterSpec
220
+ buffer:
221
+ type: InputToBufferSpec
222
+ tensor_constant:
223
+ type: InputToTensorConstantSpec
224
+ custom_obj:
225
+ type: InputToCustomObjSpec
226
+ token:
227
+ type: InputTokenSpec
228
+ constant_input:
229
+ type: InputToConstantInputSpec
230
+ InputToBufferSpec:
231
+ kind: struct
232
+ fields:
233
+ arg:
234
+ type: TensorArgument
235
+ buffer_name:
236
+ type: str
237
+ persistent:
238
+ type: bool
239
+ InputToConstantInputSpec:
240
+ kind: struct
241
+ fields:
242
+ name:
243
+ type: str
244
+ value:
245
+ type: ConstantValue
246
+ InputToCustomObjSpec:
247
+ kind: struct
248
+ fields:
249
+ arg:
250
+ type: CustomObjArgument
251
+ custom_obj_name:
252
+ type: str
253
+ InputToParameterSpec:
254
+ kind: struct
255
+ fields:
256
+ arg:
257
+ type: TensorArgument
258
+ parameter_name:
259
+ type: str
260
+ InputToTensorConstantSpec:
261
+ kind: struct
262
+ fields:
263
+ arg:
264
+ type: TensorArgument
265
+ tensor_constant_name:
266
+ type: str
267
+ InputTokenSpec:
268
+ kind: struct
269
+ fields:
270
+ arg:
271
+ type: TokenArgument
272
+ Layout:
273
+ kind: enum
274
+ fields:
275
+ Unknown: 0
276
+ SparseCoo: 1
277
+ SparseCsr: 2
278
+ SparseCsc: 3
279
+ SparseBsr: 4
280
+ SparseBsc: 5
281
+ _mkldnn: 6
282
+ Strided: 7
283
+ LossOutputSpec:
284
+ kind: struct
285
+ fields:
286
+ arg:
287
+ type: TensorArgument
288
+ MemoryFormat:
289
+ kind: enum
290
+ fields:
291
+ Unknown: 0
292
+ ContiguousFormat: 1
293
+ ChannelsLast: 2
294
+ ChannelsLast3d: 3
295
+ PreserveFormat: 4
296
+ Model:
297
+ kind: struct
298
+ fields:
299
+ name:
300
+ type: str
301
+ tensorPaths:
302
+ type: Dict[str, str]
303
+ program:
304
+ type: Program
305
+ delegates:
306
+ type: Dict[str, Program]
307
+ deviceAllocationMap:
308
+ type: Dict[str, str]
309
+ constantPaths:
310
+ type: Dict[str, str]
311
+ ModuleCallEntry:
312
+ kind: struct
313
+ fields:
314
+ fqn:
315
+ type: str
316
+ signature:
317
+ type: Optional[ModuleCallSignature]
318
+ default: None
319
+ ModuleCallSignature:
320
+ kind: struct
321
+ fields:
322
+ inputs:
323
+ type: List[Argument]
324
+ outputs:
325
+ type: List[Argument]
326
+ in_spec:
327
+ type: str
328
+ out_spec:
329
+ type: str
330
+ forward_arg_names:
331
+ type: Optional[List[str]]
332
+ default: None
333
+ NamedArgument:
334
+ kind: struct
335
+ fields:
336
+ name:
337
+ type: str
338
+ arg:
339
+ type: Argument
340
+ kind:
341
+ type: Optional[ArgumentKind]
342
+ default: None
343
+ NamedTupleDef:
344
+ kind: struct
345
+ fields:
346
+ field_names:
347
+ type: List[str]
348
+ Node:
349
+ kind: struct
350
+ fields:
351
+ target:
352
+ type: str
353
+ inputs:
354
+ type: List[NamedArgument]
355
+ outputs:
356
+ type: List[Argument]
357
+ metadata:
358
+ type: Dict[str, str]
359
+ is_hop_single_tensor_return:
360
+ type: Optional[bool]
361
+ default: None
362
+ OptionalTensorArgument:
363
+ kind: union
364
+ fields:
365
+ as_tensor:
366
+ type: TensorArgument
367
+ as_none:
368
+ type: bool
369
+ OutputSpec:
370
+ kind: union
371
+ fields:
372
+ user_output:
373
+ type: UserOutputSpec
374
+ loss_output:
375
+ type: LossOutputSpec
376
+ buffer_mutation:
377
+ type: BufferMutationSpec
378
+ gradient_to_parameter:
379
+ type: GradientToParameterSpec
380
+ gradient_to_user_input:
381
+ type: GradientToUserInputSpec
382
+ user_input_mutation:
383
+ type: UserInputMutationSpec
384
+ token:
385
+ type: OutputTokenSpec
386
+ OutputTokenSpec:
387
+ kind: struct
388
+ fields:
389
+ arg:
390
+ type: TokenArgument
391
+ Program:
392
+ kind: struct
393
+ fields:
394
+ methods:
395
+ type: Dict[str, ExportedProgram]
396
+ RangeConstraint:
397
+ kind: struct
398
+ fields:
399
+ min_val:
400
+ type: Optional[int]
401
+ max_val:
402
+ type: Optional[int]
403
+ ScalarType:
404
+ kind: enum
405
+ fields:
406
+ UNKNOWN: 0
407
+ BYTE: 1
408
+ CHAR: 2
409
+ SHORT: 3
410
+ INT: 4
411
+ LONG: 5
412
+ HALF: 6
413
+ FLOAT: 7
414
+ DOUBLE: 8
415
+ COMPLEXHALF: 9
416
+ COMPLEXFLOAT: 10
417
+ COMPLEXDOUBLE: 11
418
+ BOOL: 12
419
+ BFLOAT16: 13
420
+ UINT16: 28
421
+ FLOAT8E4M3FN: 29
422
+ FLOAT8E5M2: 30
423
+ SchemaVersion:
424
+ kind: struct
425
+ fields:
426
+ major:
427
+ type: int
428
+ minor:
429
+ type: int
430
+ SymBool:
431
+ kind: union
432
+ fields:
433
+ as_expr:
434
+ type: SymExpr
435
+ as_bool:
436
+ type: bool
437
+ SymBoolArgument:
438
+ kind: union
439
+ fields:
440
+ as_name:
441
+ type: str
442
+ as_bool:
443
+ type: bool
444
+ SymExpr:
445
+ kind: struct
446
+ fields:
447
+ expr_str:
448
+ type: str
449
+ hint:
450
+ type: Optional[SymExprHint]
451
+ default: None
452
+ SymExprHint:
453
+ kind: union
454
+ fields:
455
+ as_int:
456
+ type: int
457
+ as_bool:
458
+ type: bool
459
+ as_float:
460
+ type: float
461
+ SymFloat:
462
+ kind: union
463
+ fields:
464
+ as_expr:
465
+ type: SymExpr
466
+ as_float:
467
+ type: float
468
+ SymFloatArgument:
469
+ kind: union
470
+ fields:
471
+ as_name:
472
+ type: str
473
+ as_float:
474
+ type: float
475
+ SymInt:
476
+ kind: union
477
+ fields:
478
+ as_expr:
479
+ type: SymExpr
480
+ as_int:
481
+ type: int
482
+ SymIntArgument:
483
+ kind: union
484
+ fields:
485
+ as_name:
486
+ type: str
487
+ as_int:
488
+ type: int
489
+ TensorArgument:
490
+ kind: struct
491
+ fields:
492
+ name:
493
+ type: str
494
+ TensorMeta:
495
+ kind: struct
496
+ fields:
497
+ dtype:
498
+ type: ScalarType
499
+ sizes:
500
+ type: List[SymInt]
501
+ requires_grad:
502
+ type: bool
503
+ device:
504
+ type: Device
505
+ strides:
506
+ type: List[SymInt]
507
+ storage_offset:
508
+ type: SymInt
509
+ layout:
510
+ type: Layout
511
+ TokenArgument:
512
+ kind: struct
513
+ fields:
514
+ name:
515
+ type: str
516
+ UserInputMutationSpec:
517
+ kind: struct
518
+ fields:
519
+ arg:
520
+ type: TensorArgument
521
+ user_input_name:
522
+ type: str
523
+ UserInputSpec:
524
+ kind: struct
525
+ fields:
526
+ arg:
527
+ type: Argument
528
+ UserOutputSpec:
529
+ kind: struct
530
+ fields:
531
+ arg:
532
+ type: Argument
533
+ SCHEMA_VERSION:
534
+ - 8
535
+ - 8
536
+ TREESPEC_VERSION: 1
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/schema_check.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ import hashlib
4
+ import inspect
5
+ import re
6
+ import typing
7
+ from enum import IntEnum
8
+ from typing import Annotated, Any, ForwardRef, Optional, Union
9
+
10
+ from torch._export.serde import schema
11
+ from torch._export.serde.union import _Union
12
+
13
+
14
+ class SchemaUpdateError(Exception):
15
+ pass
16
+
17
+
18
+ def _check(x, msg):
19
+ if not x:
20
+ raise SchemaUpdateError(msg)
21
+
22
+
23
+ _CPP_TYPE_MAP = {
24
+ str: "std::string",
25
+ int: "int64_t",
26
+ float: "F64",
27
+ bool: "bool",
28
+ }
29
+
30
+ _THRIFT_TYPE_MAP = {
31
+ str: "string",
32
+ int: "i64",
33
+ float: "double",
34
+ bool: "bool",
35
+ }
36
+
37
+
38
+ def _staged_schema():
39
+ yaml_ret: dict[str, Any] = {}
40
+ defs = {}
41
+ cpp_enum_defs: dict[str, str] = {}
42
+ cpp_class_defs: dict[str, str] = {}
43
+ cpp_type_decls: list[str] = []
44
+ cpp_json_defs: list[str] = []
45
+ thrift_enum_defs: list[str] = []
46
+ thrift_type_defs: dict[str, str] = {}
47
+
48
+ def _handle_aggregate(ty) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
49
+ def dump_type(t, level: int) -> tuple[str, str, str]:
50
+ if getattr(t, "__name__", None) in cpp_enum_defs:
51
+ return t.__name__, "int64_t", t.__name__
52
+ elif t in _CPP_TYPE_MAP:
53
+ return (t.__name__, _CPP_TYPE_MAP[t], _THRIFT_TYPE_MAP[t])
54
+ elif isinstance(t, str):
55
+ assert t in defs
56
+ assert t not in cpp_enum_defs
57
+ assert "[" not in t
58
+ return t, f"ForwardRef<{t}>", t
59
+ elif isinstance(t, ForwardRef):
60
+ return (
61
+ t.__forward_arg__,
62
+ f"ForwardRef<{t.__forward_arg__}>",
63
+ t.__forward_arg__,
64
+ )
65
+ elif o := typing.get_origin(t):
66
+ # Lemme know if there's a better way to do this.
67
+ if o == list:
68
+ yaml_head, cpp_head, thrift_head, thrift_tail = (
69
+ "List",
70
+ "std::vector",
71
+ "list<",
72
+ ">",
73
+ )
74
+ elif o == dict:
75
+ yaml_head, cpp_head, thrift_head, thrift_tail = (
76
+ "Dict",
77
+ "std::unordered_map",
78
+ "map<",
79
+ ">",
80
+ )
81
+ elif o == Union:
82
+ assert level == 0, "Optional is only supported at the top level."
83
+ args = typing.get_args(t)
84
+ assert len(args) == 2 and args[1] == type(None)
85
+ yaml_type, cpp_type, thrift_type = dump_type(args[0], level + 1)
86
+ return (
87
+ f"Optional[{yaml_type}]",
88
+ f"std::optional<{cpp_type}>",
89
+ f"optional {thrift_type}",
90
+ )
91
+ elif o == Annotated:
92
+ return dump_type(t.__origin__, level)
93
+ else:
94
+ raise AssertionError(f"Type {t} is not supported in export schema.")
95
+ yaml_arg_types, cpp_arg_types, thrift_arg_types = zip(
96
+ *[dump_type(x, level + 1) for x in typing.get_args(t)]
97
+ )
98
+ return (
99
+ (f"{yaml_head}[{', '.join(yaml_arg_types)}]"),
100
+ (f"{cpp_head}<{', '.join(cpp_arg_types)}>"),
101
+ f"{thrift_head}{', '.join(thrift_arg_types)}{thrift_tail}",
102
+ )
103
+ elif isinstance(t, type):
104
+ return (t.__name__, t.__name__, t.__name__)
105
+ else:
106
+ raise AssertionError(f"Type {t} is not supported in export schema.")
107
+
108
+ def dump_cpp_value(v) -> str:
109
+ if v is None:
110
+ return "std::nullopt"
111
+ elif v is True:
112
+ return "true"
113
+ elif v is False:
114
+ return "false"
115
+ elif v == {}:
116
+ return "{}"
117
+ elif v == []:
118
+ return "{}"
119
+ elif v == ():
120
+ return "{}"
121
+ elif isinstance(v, str):
122
+ return f'"{v}"'
123
+ else:
124
+ raise AssertionError(
125
+ f"Default value {v} is not supported yet in export schema."
126
+ )
127
+
128
+ def dump_field(f) -> tuple[dict[str, Any], str, Optional[str], str, int]:
129
+ t, cpp_type, thrift_type = dump_type(f.type, 0)
130
+ ret = {"type": t}
131
+ cpp_default: Optional[str] = None
132
+ assert (
133
+ typing.get_origin(f.type) == Annotated
134
+ ), f"Field {f.name} must be annotated with an integer id."
135
+ thrift_id = f.type.__metadata__[0]
136
+ assert (
137
+ type(thrift_id) is int
138
+ ), f"Field {f.name} must be annotated with an integer id."
139
+
140
+ value = dataclasses.MISSING
141
+ if f.default is not dataclasses.MISSING:
142
+ value = f.default
143
+ elif f.default_factory is not dataclasses.MISSING:
144
+ value = f.default_factory()
145
+
146
+ if value is not dataclasses.MISSING:
147
+ default = str(value)
148
+ ret["default"] = default
149
+ cpp_default = dump_cpp_value(value)
150
+
151
+ if t.startswith("Optional[") and value is not None:
152
+ raise AssertionError(
153
+ f"Optional field {ty.__name__}.{f.name} must have default value to be None."
154
+ )
155
+
156
+ return ret, cpp_type, cpp_default, thrift_type, thrift_id
157
+
158
+ yaml_ret = {}
159
+ cpp_ret = {}
160
+ thrift_ret = {}
161
+ thrift_ids = set()
162
+ for f in dataclasses.fields(ty):
163
+ yaml_res, cpp_type, cpp_default, thrift_type, thrift_id = dump_field(f)
164
+ yaml_ret[f.name] = yaml_res
165
+ cpp_ret[f.name] = {"cpp_type": cpp_type, "cpp_default": cpp_default}
166
+ thrift_ret[f.name] = {"thrift_type": thrift_type, "thrift_id": thrift_id}
167
+ if thrift_id in thrift_ids:
168
+ raise AssertionError(
169
+ f"Duplicate thrift id {thrift_id} for field {f.name} in {ty.__name__}."
170
+ )
171
+ thrift_ids.add(thrift_id)
172
+ return yaml_ret, cpp_ret, thrift_ret
173
+
174
+ def _handle_int_enum(name, ty):
175
+ yaml_ret[name] = {"kind": "enum", "fields": {x.name: x.value for x in ty}}
176
+ cpp_enum_defs[
177
+ name
178
+ ] = f"""
179
+ enum class {name} {{
180
+ {chr(10).join([f" {x.name} = {x.value}," for x in ty])}
181
+ }};
182
+
183
+ inline std::string_view printEnum(const {name}& e) {{
184
+ switch (e) {{
185
+ {chr(10).join([f" case {name}::{x.name}: return {chr(34)}{x.name}{chr(34)};" for x in ty])}
186
+ default:
187
+ throw std::runtime_error("Unknown enum value");
188
+ }}
189
+ }}
190
+
191
+ inline void parseEnum(std::string_view s, {name}& t) {{
192
+ {chr(10).join([f" if (s == {chr(34)}{x.name}{chr(34)}) {{ t = {name}::{x.name}; return; }}" for x in ty])}
193
+ throw std::runtime_error("Unknown enum value: " + std::string{{s}});
194
+ }}
195
+ """
196
+ thrift_enum_defs.append(
197
+ f"""
198
+ enum {name} {{
199
+ {chr(10).join([f" {x.name} = {x.value}," for x in ty])}
200
+ }}
201
+ """
202
+ )
203
+
204
+ def _handle_struct(name, ty):
205
+ fields, cpp_fields, thrift_fields = _handle_aggregate(ty)
206
+ yaml_ret[name] = {"kind": "struct", "fields": fields}
207
+ field_decls = "\n".join(
208
+ f" {f['cpp_type']} {name}{' = ' + f['cpp_default'] if f['cpp_default'] is not None else ''};"
209
+ for name, f in cpp_fields.items()
210
+ )
211
+
212
+ def accessor(name, ty):
213
+ type_name = fields[name]["type"]
214
+ if type_name in cpp_enum_defs:
215
+ return f"""
216
+ {type_name} get_{name}() const {{
217
+ return static_cast<{type_name}>({name});
218
+ }}
219
+
220
+ void set_{name}({type_name} def) {{
221
+ {name} = static_cast<int64_t>(def);
222
+ }}
223
+ """
224
+ return f"""
225
+ const {ty}& get_{name}() const {{
226
+ return {name};
227
+ }}
228
+
229
+ void set_{name}({ty} def) {{
230
+ {name} = std::move(def);
231
+ }}
232
+ """
233
+
234
+ to_json_decl = f"void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t)"
235
+ to_json_def = f"""{{
236
+ {chr(10).join([f' nlohmann_json_j["{name}"] = nlohmann_json_t.{name};' for name, f in cpp_fields.items()])}
237
+ }}
238
+ """
239
+ from_json_decl = f"void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t)"
240
+
241
+ from_json_def = f"""{{
242
+ {name} nlohmann_json_default_obj;
243
+ {chr(10).join(
244
+ [f' nlohmann_json_t.{name} = nlohmann_json_j.value("{name}", nlohmann_json_default_obj.{name});'
245
+ for name, f in cpp_fields.items()])}
246
+ }}
247
+ """
248
+ cpp_class_defs[
249
+ name
250
+ ] = f"""
251
+ class {name} {{
252
+ private:
253
+ {field_decls}
254
+
255
+ public:
256
+ {"".join([accessor(name, f["cpp_type"]) for name, f in cpp_fields.items()])}
257
+ friend {to_json_decl};
258
+ friend {from_json_decl};
259
+ }};
260
+ """
261
+ cpp_json_defs.append(f"inline {to_json_decl} {to_json_def}")
262
+ cpp_json_defs.append(f"inline {from_json_decl} {from_json_def}")
263
+ cpp_type_decls.append(f"class {name};")
264
+
265
+ thrift_type_defs[
266
+ name
267
+ ] = f"""
268
+ struct {name} {{
269
+ {chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())}
270
+ }}"""
271
+
272
+ def _handle_union(name, ty):
273
+ fields, cpp_fields, thrift_fields = _handle_aggregate(ty)
274
+ yaml_ret[name] = {"kind": "union", "fields": fields}
275
+
276
+ def accessor(name, ty, idx):
277
+ return f"""
278
+ const {ty}& get_{name}() const {{
279
+ return std::get<{idx + 1}>(variant_);
280
+ }}
281
+
282
+ void set_{name}({ty} def) {{
283
+ variant_.emplace<{idx + 1}>(std::move(def));
284
+ tag_ = Tag::{name.upper()};
285
+ }}
286
+ """
287
+
288
+ to_json_branches = "".join(
289
+ [
290
+ f"""
291
+ if (nlohmann_json_t.tag_ == Tag::{name.upper()}) {{
292
+ nlohmann_json_j["{name}"] = nlohmann_json_t.get_{name}();
293
+ return;
294
+ }}"""
295
+ for idx, (name, f) in enumerate(cpp_fields.items())
296
+ ]
297
+ )
298
+ from_json_branches = "".join(
299
+ [
300
+ f"""
301
+ if (nlohmann_json_j.contains("{name}")) {{
302
+ nlohmann_json_t.variant_.emplace<{idx + 1}>(nlohmann_json_j.at("{name}").template get<{f["cpp_type"]}>());
303
+ nlohmann_json_t.tag_ = Tag::{name.upper()};
304
+ return;
305
+ }}"""
306
+ for idx, (name, f) in enumerate(cpp_fields.items())
307
+ ]
308
+ )
309
+
310
+ cpp_class_defs[
311
+ name
312
+ ] = f"""
313
+ class {name} {{
314
+ struct Void {{}};
315
+
316
+ public:
317
+ enum class Tag {{
318
+ {", ".join([name.upper() for name in cpp_fields])}
319
+ }};
320
+
321
+ private:
322
+ std::variant<Void, {", ".join(f["cpp_type"] for f in cpp_fields.values())}> variant_;
323
+ Tag tag_;
324
+
325
+ public:
326
+ Tag tag() const {{
327
+ return tag_;
328
+ }}
329
+ {"".join([accessor(name, f["cpp_type"], idx) for idx, (name, f) in enumerate(cpp_fields.items())])}
330
+ friend void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t) {{
331
+ {to_json_branches}
332
+ }}
333
+
334
+ friend void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t) {{
335
+ {from_json_branches}
336
+ }}
337
+ }};
338
+
339
+ inline std::string_view printEnum(const {name}::Tag& e) {{
340
+ switch (e) {{
341
+ {chr(10).join([f" case {name}::Tag::{x.upper()}: return {chr(34)}{x.upper()}{chr(34)};" for x in cpp_fields])}
342
+ default:
343
+ throw std::runtime_error("Unknown enum value");
344
+ }}
345
+ }}
346
+
347
+ inline void parseEnum(std::string_view s, {name}::Tag& t) {{
348
+ {chr(10).join([f" if (s == {chr(34)}{x.upper()}{chr(34)}) {{ t = {name}::Tag::{x.upper()}; return; }}" for x in cpp_fields])}
349
+ throw std::runtime_error("Unknown enum value: " + std::string{{s}});
350
+ }}
351
+
352
+ """
353
+ cpp_type_decls.append(f"class {name};")
354
+
355
+ thrift_type_defs[
356
+ name
357
+ ] = f"""
358
+ union {name} {{
359
+ {chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())}
360
+ }}"""
361
+
362
+ for name in dir(schema):
363
+ if name.startswith("_"):
364
+ continue
365
+
366
+ value = getattr(schema, name)
367
+
368
+ if hasattr(value, "__module__") and value.__module__ != schema.__name__:
369
+ continue
370
+
371
+ defs[name] = value
372
+
373
+ class_ordering = {}
374
+ for name, value in defs.items():
375
+ if isinstance(value, type):
376
+ if issubclass(value, IntEnum):
377
+ _handle_int_enum(name, value)
378
+ elif dataclasses.is_dataclass(value):
379
+ class_ordering[name] = inspect.findsource(value)[1]
380
+ if issubclass(value, _Union):
381
+ _handle_union(name, value)
382
+ else:
383
+ _handle_struct(name, value)
384
+ else:
385
+ raise AssertionError(f"Unknown schema type {name}: {value}")
386
+ elif isinstance(value, (int, tuple)):
387
+ assert name in ("SCHEMA_VERSION", "TREESPEC_VERSION")
388
+ else:
389
+ raise AssertionError(f"Unknown variable {name}: {value}")
390
+
391
+ yaml_ret["SCHEMA_VERSION"] = list(defs["SCHEMA_VERSION"])
392
+ assert all(x > 0 for x in yaml_ret["SCHEMA_VERSION"])
393
+ yaml_ret["TREESPEC_VERSION"] = defs["TREESPEC_VERSION"]
394
+ assert yaml_ret["TREESPEC_VERSION"] > 0
395
+
396
+ cpp_header = f"""
397
+ #pragma once
398
+
399
+ #include <optional>
400
+ #include <stdexcept>
401
+ #include <string>
402
+ #include <unordered_map>
403
+ #include <variant>
404
+ #include <vector>
405
+
406
+ #include <nlohmann/json.hpp>
407
+
408
+ #ifndef NLOHMANN_JSON_NAMESPACE_BEGIN
409
+ #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {{
410
+ #endif
411
+
412
+ #ifndef NLOHMANN_JSON_NAMESPACE_END
413
+ #define NLOHMANN_JSON_NAMESPACE_END }}
414
+ #endif
415
+
416
+ // https://github.com/nlohmann/json/pull/2117
417
+ NLOHMANN_JSON_NAMESPACE_BEGIN
418
+ template <typename T>
419
+ struct adl_serializer<std::optional<T>> {{
420
+ static void to_json(json& j, const std::optional<T>& opt) {{
421
+ if (opt == std::nullopt) {{
422
+ j = nullptr;
423
+ }} else {{
424
+ j = *opt; // this will call adl_serializer<T>::to_json which will
425
+ // find the free function to_json in T's namespace!
426
+ }}
427
+ }}
428
+
429
+ static void from_json(const json& j, std::optional<T>& opt) {{
430
+ if (j.is_null()) {{
431
+ opt = std::nullopt;
432
+ }} else {{
433
+ opt = j.template get<T>(); // same as above, but with
434
+ // adl_serializer<T>::from_json
435
+ }}
436
+ }}
437
+ }};
438
+ NLOHMANN_JSON_NAMESPACE_END
439
+
440
+ namespace torch {{
441
+ namespace _export {{
442
+
443
+ template <typename T>
444
+ class ForwardRef {{
445
+ static_assert(!std::is_reference_v<T>, "ForwardRef cannot be a reference type");
446
+
447
+ public:
448
+ ForwardRef(): ptr_(std::make_unique<T>()) {{}}
449
+ ForwardRef(ForwardRef<T>&&);
450
+ ForwardRef(const ForwardRef<T>& other): ptr_(std::make_unique<T>(*other.ptr_)) {{}}
451
+ ForwardRef<T>& operator=(ForwardRef<T>&&);
452
+ ForwardRef<T>& operator=(const ForwardRef<T>& other) {{
453
+ ptr_ = std::make_unique<T>(*other.ptr_);
454
+ return *this;
455
+ }}
456
+ const T& operator*() const {{
457
+ return *ptr_;
458
+ }}
459
+
460
+ const T* operator->() const {{
461
+ return ptr_.get();
462
+ }}
463
+
464
+ void emplace(T&& t) {{
465
+ ptr_ = std::make_unique<T>(std::move(t));
466
+ }}
467
+
468
+ private:
469
+ std::unique_ptr<T> ptr_;
470
+ }};
471
+
472
+ template <typename T>
473
+ void to_json(nlohmann::json& j, const ForwardRef<T>& p) {{
474
+ j = *p;
475
+ }}
476
+
477
+ template <typename T>
478
+ void from_json(const nlohmann::json& j, ForwardRef<T>& p) {{
479
+ p.emplace(j.template get<T>());
480
+ }}
481
+
482
+ class F64 {{
483
+ public:
484
+ double get() const {{
485
+ return value_;
486
+ }}
487
+
488
+ void set(double value) {{
489
+ value_ = value;
490
+ }}
491
+
492
+ private:
493
+ double value_;
494
+ }};
495
+
496
+ inline void to_json(nlohmann::json& j, const F64& f) {{
497
+ if (std::isinf(f.get())) {{
498
+ j = "Infinity";
499
+ }} else if (std::isinf(-f.get())) {{
500
+ j = "-Infinity";
501
+ }} else if (std::isnan(f.get())) {{
502
+ j = "NaN";
503
+ }} else {{
504
+ j = f.get();
505
+ }}
506
+ }}
507
+
508
+ inline void from_json(const nlohmann::json& j, F64& f) {{
509
+ if (j == "Infinity") {{
510
+ f.set(std::numeric_limits<double>::infinity());
511
+ }} else if (j == "-Infinity") {{
512
+ f.set(-std::numeric_limits<double>::infinity());
513
+ }} else if (j == "NaN") {{
514
+ f.set(std::numeric_limits<double>::quiet_NaN());
515
+ }} else {{
516
+ f.set(j.get<double>());
517
+ }}
518
+ }}
519
+
520
+ {chr(10).join(cpp_type_decls)}
521
+ {"".join(cpp_enum_defs.values())}
522
+ {"".join(dict(sorted(cpp_class_defs.items(), key=lambda x: class_ordering[x[0]])).values())}
523
+ {chr(10).join(cpp_json_defs)}
524
+
525
+ template <typename T> ForwardRef<T>::ForwardRef(ForwardRef<T>&&) = default;
526
+ template <typename T> ForwardRef<T>& ForwardRef<T>::operator=(ForwardRef<T>&&) = default;
527
+ }} // namespace _export
528
+ }} // namespace torch
529
+ """
530
+ thrift_schema = f"""
531
+ namespace py3 torch._export
532
+ namespace cpp2 torch._export.schema
533
+ {chr(10).join(thrift_enum_defs)}
534
+ {chr(10).join(dict(sorted(thrift_type_defs.items(), key=lambda x: class_ordering[x[0]])).values())}
535
+ """
536
+ return yaml_ret, cpp_header, thrift_schema
537
+
538
+
539
+ def _diff_schema(dst, src):
540
+ additions = {key: src[key] for key in src.keys() - dst.keys()}
541
+ subtractions = {key: dst[key] for key in dst.keys() - src.keys()}
542
+
543
+ common_keys = src.keys() & dst.keys()
544
+
545
+ versions = {"SCHEMA_VERSION", "TREESPEC_VERSION"}
546
+ common_keys -= versions
547
+
548
+ for key in common_keys:
549
+ src_kind = src[key]["kind"]
550
+ src_fields = src[key]["fields"]
551
+ dst_kind = dst[key]["kind"]
552
+ dst_fields = dst[key]["fields"]
553
+ _check(
554
+ src_kind == dst_kind,
555
+ f"Type {key} changed kind from {dst_kind} to {src_kind}",
556
+ )
557
+ assert isinstance(src_fields, dict) and isinstance(dst_fields, dict)
558
+ added_fields = {
559
+ key: src_fields[key] for key in src_fields.keys() - dst_fields.keys()
560
+ }
561
+ subtracted_fields = {
562
+ key: dst_fields[key] for key in dst_fields.keys() - src_fields.keys()
563
+ }
564
+ common_fields = src_fields.keys() & dst_fields.keys()
565
+
566
+ for field in common_fields:
567
+ src_field = src_fields[field]
568
+ dst_field = dst_fields[field]
569
+ if src_kind == "struct":
570
+ _check(
571
+ src_field["type"] == dst_field["type"],
572
+ f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}",
573
+ )
574
+ if "default" in src_field and "default" not in dst_field:
575
+ added_fields[field] = {}
576
+ added_fields[field]["default"] = src_field["default"]
577
+ if "default" not in src_field and "default" in dst_field:
578
+ subtracted_fields[field] = {}
579
+ subtracted_fields[field]["default"] = dst_field["default"]
580
+ elif src_kind == "enum":
581
+ _check(
582
+ src_field == dst_field,
583
+ f"Value of the enum field {key}.{field} changed from {dst_field} to {src_field}",
584
+ )
585
+ elif src_kind == "union":
586
+ _check(
587
+ src_field["type"] == dst_field["type"],
588
+ f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}",
589
+ )
590
+ else:
591
+ raise AssertionError(f"Unknown kind {src_kind}: {key}")
592
+ if len(added_fields) > 0:
593
+ assert key not in additions
594
+ additions[key] = {}
595
+ additions[key]["fields"] = added_fields
596
+ if len(subtracted_fields) > 0:
597
+ assert key not in subtractions
598
+ subtractions[key] = {}
599
+ subtractions[key]["fields"] = subtracted_fields
600
+
601
+ return additions, subtractions
602
+
603
+
604
+ def _hash_content(s: str):
605
+ return hashlib.sha256(s.strip().encode("utf-8")).hexdigest()
606
+
607
+
608
+ @dataclasses.dataclass
609
+ class _Commit:
610
+ result: dict[str, Any]
611
+ checksum_next: str
612
+ yaml_path: str
613
+ additions: dict[str, Any]
614
+ subtractions: dict[str, Any]
615
+ base: dict[str, Any]
616
+ checksum_head: Optional[str]
617
+ cpp_header: str
618
+ cpp_header_path: str
619
+ thrift_checksum_head: Optional[str]
620
+ thrift_checksum_real: Optional[str]
621
+ thrift_checksum_next: str
622
+ thrift_schema: str
623
+ thrift_schema_path: str
624
+
625
+
626
+ def update_schema():
627
+ import importlib.resources
628
+
629
+ if importlib.resources.is_resource(__package__, "schema.yaml"):
630
+ content = importlib.resources.read_text(__package__, "schema.yaml")
631
+ match = re.search("checksum<<([A-Fa-f0-9]{64})>>", content)
632
+ _check(match is not None, "checksum not found in schema.yaml")
633
+ assert match is not None
634
+ checksum_head = match.group(1)
635
+
636
+ thrift_content = importlib.resources.read_text(
637
+ __package__, "export_schema.thrift"
638
+ )
639
+ match = re.search("checksum<<([A-Fa-f0-9]{64})>>", thrift_content)
640
+ _check(match is not None, "checksum not found in export_schema.thrift")
641
+ assert match is not None
642
+ thrift_checksum_head = match.group(1)
643
+ thrift_content = thrift_content.splitlines()
644
+ assert thrift_content[0].startswith("// @" + "generated")
645
+ assert thrift_content[1].startswith("// checksum<<")
646
+ thrift_checksum_real = _hash_content("\n".join(thrift_content[2:]))
647
+
648
+ from yaml import load, Loader
649
+
650
+ dst = load(content, Loader=Loader)
651
+ assert isinstance(dst, dict)
652
+ else:
653
+ checksum_head = None
654
+ thrift_checksum_head = None
655
+ thrift_checksum_real = None
656
+ dst = {"SCHEMA_VERSION": None, "TREESPEC_VERSION": None}
657
+
658
+ src, cpp_header, thrift_schema = _staged_schema()
659
+ additions, subtractions = _diff_schema(dst, src)
660
+ yaml_path = __package__.replace(".", "/") + "/schema.yaml"
661
+ thrift_schema_path = __package__.replace(".", "/") + "/export_schema.thrift"
662
+ torch_prefix = "torch/"
663
+ assert yaml_path.startswith(torch_prefix) # sanity check
664
+ assert thrift_schema_path.startswith(torch_prefix) # sanity check
665
+
666
+ return _Commit(
667
+ result=src,
668
+ checksum_next=_hash_content(repr(src)),
669
+ yaml_path=yaml_path,
670
+ additions=additions,
671
+ subtractions=subtractions,
672
+ base=dst,
673
+ checksum_head=checksum_head,
674
+ cpp_header=cpp_header,
675
+ cpp_header_path=torch_prefix + "csrc/utils/generated_serialization_types.h",
676
+ thrift_checksum_head=thrift_checksum_head,
677
+ thrift_checksum_real=thrift_checksum_real,
678
+ thrift_checksum_next=_hash_content(thrift_schema),
679
+ thrift_schema=thrift_schema,
680
+ thrift_schema_path=thrift_schema_path,
681
+ )
682
+
683
+
684
+ def check(commit: _Commit, force_unsafe: bool = False):
685
+ next_version = None
686
+ reason = ""
687
+ # Step 1: Detect major schema updates.
688
+ if len(commit.additions) > 0:
689
+ for k, v in commit.additions.items():
690
+ if k not in commit.base:
691
+ continue
692
+ kind = commit.result[k]["kind"]
693
+ fields = v["fields"]
694
+ for f, d in fields.items():
695
+ if kind == "struct" and "default" not in d:
696
+ reason += (
697
+ f"Field {k}.{f} is added to schema.py without a default value as an incomparible change "
698
+ + "which requires major version bump.\n"
699
+ )
700
+ next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1]
701
+
702
+ if len(commit.subtractions) > 0:
703
+ for k, v in commit.subtractions.items():
704
+ if k not in commit.result:
705
+ continue
706
+ for f in v["fields"]:
707
+ reason = f"Field {k}.{f} is removed from schema.py as an incompatible change which requires major version bump.\n"
708
+ next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1]
709
+
710
+ if force_unsafe:
711
+ reason += "--force-unsafe is used."
712
+ next_version = commit.result["SCHEMA_VERSION"]
713
+ else:
714
+ # Step 2: Detect minor schema updates.
715
+ if next_version is None and len(commit.additions) > 0:
716
+ for k, v in commit.additions.items():
717
+ for f in v["fields"]:
718
+ reason += (
719
+ f"Field {k}.{f} is added to schema.py as an compatible change "
720
+ + "which still requires minor version bump.\n"
721
+ )
722
+ next_version = [
723
+ commit.base["SCHEMA_VERSION"][0],
724
+ commit.base["SCHEMA_VERSION"][1] + 1,
725
+ ]
726
+ if next_version is None and len(commit.subtractions) > 0:
727
+ for k, v in commit.subtractions.items():
728
+ for f in v["fields"]:
729
+ reason += (
730
+ f"Field {k}.{f} is removed from schema.py as an compatible change "
731
+ + "which still requires minor version bump.\n"
732
+ )
733
+ next_version = [
734
+ commit.base["SCHEMA_VERSION"][0],
735
+ commit.base["SCHEMA_VERSION"][1] + 1,
736
+ ]
737
+
738
+ return next_version, reason
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/serialize.py ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_export/serde/union.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections.abc import Hashable
4
+ from dataclasses import fields
5
+
6
+
7
+ class _UnionTag(str):
8
+ __slots__ = ("_cls",)
9
+ _cls: Hashable
10
+
11
+ @staticmethod
12
+ def create(t, cls):
13
+ tag = _UnionTag(t)
14
+ assert not hasattr(tag, "_cls")
15
+ tag._cls = cls
16
+ return tag
17
+
18
+ def __eq__(self, cmp) -> bool:
19
+ assert isinstance(cmp, str)
20
+ other = str(cmp)
21
+ assert other in _get_field_names(
22
+ self._cls
23
+ ), f"{other} is not a valid tag for {self._cls}. Available tags: {_get_field_names(self._cls)}"
24
+ return str(self) == other
25
+
26
+ def __hash__(self):
27
+ return hash(str(self))
28
+
29
+
30
+ @functools.cache
31
+ def _get_field_names(cls) -> set[str]:
32
+ return {f.name for f in fields(cls)}
33
+
34
+
35
+ class _Union:
36
+ _type: _UnionTag
37
+
38
+ @classmethod
39
+ def create(cls, **kwargs):
40
+ assert len(kwargs) == 1
41
+ obj = cls(**{**{f.name: None for f in fields(cls)}, **kwargs}) # type: ignore[arg-type]
42
+ obj._type = _UnionTag.create(next(iter(kwargs.keys())), cls)
43
+ return obj
44
+
45
+ def __post_init__(self):
46
+ assert not any(f.name in ("type", "_type", "create", "value") for f in fields(self)) # type: ignore[arg-type, misc]
47
+
48
+ @property
49
+ def type(self) -> str:
50
+ try:
51
+ return self._type
52
+ except AttributeError as e:
53
+ raise RuntimeError(
54
+ f"Please use {type(self).__name__}.create to instantiate the union type."
55
+ ) from e
56
+
57
+ @property
58
+ def value(self):
59
+ return getattr(self, self.type)
60
+
61
+ def __getattribute__(self, name):
62
+ attr = super().__getattribute__(name)
63
+ if attr is None and name in _get_field_names(type(self)) and name != self.type: # type: ignore[arg-type]
64
+ raise AttributeError(f"Field {name} is not set.")
65
+ return attr
66
+
67
+ def __str__(self):
68
+ return self.__repr__()
69
+
70
+ def __repr__(self):
71
+ return f"{type(self).__name__}({self.type}={getattr(self, self.type)})"
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Any
4
+
5
+ from torch._logging import trace_structured
6
+ from torch.fx import Graph, Node
7
+
8
+
9
+ log: logging.Logger = logging.getLogger(__name__)
10
+
11
+
12
+ def create_joint_graph_node_information(
13
+ joint_graph: Graph,
14
+ recomputable_node_info: dict[str, int],
15
+ ) -> dict[str, Any]:
16
+ joint_graph_node_information: dict[str, Any] = {}
17
+
18
+ for i, joint_graph_node in enumerate(joint_graph.nodes):
19
+ is_recomputable_candidate: bool = (
20
+ joint_graph_node.name in recomputable_node_info
21
+ )
22
+ tensor_meta = joint_graph_node.meta.get("tensor_meta")
23
+ shape = getattr(tensor_meta, "shape", []) if tensor_meta else []
24
+
25
+ node_info: dict[str, Any] = {
26
+ "index": i,
27
+ "name": joint_graph_node.name,
28
+ "is_recomputable_candidate": is_recomputable_candidate,
29
+ "target": str(joint_graph_node.target),
30
+ "shape": str(shape),
31
+ "input_arguments": [inp.name for inp in joint_graph_node.all_input_nodes],
32
+ "stack_trace": joint_graph_node.meta.get("stack_trace", ""),
33
+ }
34
+
35
+ if is_recomputable_candidate:
36
+ idx: int = recomputable_node_info[joint_graph_node.name]
37
+ node_info["recomputable_candidate_info"] = {
38
+ "recomputable_node_idx": idx,
39
+ }
40
+
41
+ joint_graph_node_information[joint_graph_node.name] = node_info
42
+
43
+ return joint_graph_node_information
44
+
45
+
46
+ def create_joint_graph_edges(joint_graph: Graph) -> list[tuple[str, str]]:
47
+ joint_graph_edges: list[tuple[str, str]] = [
48
+ (inp.name, node.name)
49
+ for node in joint_graph.nodes
50
+ for inp in node.all_input_nodes
51
+ ]
52
+ return joint_graph_edges
53
+
54
+
55
+ def create_activation_checkpointing_logging_structure_payload(
56
+ joint_graph: Graph,
57
+ joint_graph_node_information: dict[str, Any],
58
+ joint_graph_edges: list[tuple[str, str]],
59
+ all_recomputable_banned_nodes: list[Node],
60
+ expected_runtime: float,
61
+ saved_node_idxs: list[int],
62
+ recomputable_node_idxs: list[int],
63
+ memories_banned_nodes: list[float],
64
+ runtimes_banned_nodes: list[float],
65
+ min_cut_saved_values: list[Node],
66
+ ) -> dict[str, Any]:
67
+ activation_checkpointing_logging_structure_payload: dict[str, Any] = {
68
+ "Joint Graph Size": len(joint_graph.nodes),
69
+ "Joint Graph Edges": {
70
+ "Total": len(joint_graph_edges),
71
+ "Edges": joint_graph_edges,
72
+ },
73
+ "Joint Graph Node Information": joint_graph_node_information,
74
+ "Recomputable Banned Nodes Order": [
75
+ node.name for node in all_recomputable_banned_nodes
76
+ ],
77
+ "Expected Runtime": expected_runtime,
78
+ "Knapsack Saved Nodes": saved_node_idxs,
79
+ "Knapsack Recomputed Nodes": recomputable_node_idxs,
80
+ "Knapsack Input Memories": memories_banned_nodes,
81
+ "Knapsack Input Runtimes": runtimes_banned_nodes,
82
+ "Min Cut Solution Saved Values": [node.name for node in min_cut_saved_values],
83
+ }
84
+ return activation_checkpointing_logging_structure_payload
85
+
86
+
87
+ def create_structured_trace_for_min_cut_info(
88
+ joint_graph: Graph,
89
+ all_recomputable_banned_nodes: list[Node],
90
+ saved_node_idxs: list[int],
91
+ recomputable_node_idxs: list[int],
92
+ expected_runtime: float,
93
+ memories_banned_nodes: list[float],
94
+ runtimes_banned_nodes: list[float],
95
+ min_cut_saved_values: list[Node],
96
+ ) -> None:
97
+ recomputable_node_info: dict[str, int] = {
98
+ node.name: idx for idx, node in enumerate(all_recomputable_banned_nodes)
99
+ }
100
+ joint_graph_node_information = create_joint_graph_node_information(
101
+ joint_graph, recomputable_node_info
102
+ )
103
+
104
+ for node_name, node_info in joint_graph_node_information.items():
105
+ if node_info["is_recomputable_candidate"]:
106
+ idx = recomputable_node_info[node_name]
107
+ node_info["recomputable_candidate_info"]["memory"] = memories_banned_nodes[
108
+ idx
109
+ ]
110
+ node_info["recomputable_candidate_info"]["runtime"] = runtimes_banned_nodes[
111
+ idx
112
+ ]
113
+ node_info["recomputable_candidate_info"]["is_saved"] = (
114
+ idx in saved_node_idxs
115
+ )
116
+ node_info["recomputable_candidate_info"]["is_recomputed"] = (
117
+ idx in recomputable_node_idxs
118
+ )
119
+
120
+ joint_graph_edges = create_joint_graph_edges(joint_graph)
121
+ activation_checkpointing_logging_structure_payload = (
122
+ create_activation_checkpointing_logging_structure_payload(
123
+ joint_graph,
124
+ joint_graph_node_information,
125
+ joint_graph_edges,
126
+ all_recomputable_banned_nodes,
127
+ expected_runtime,
128
+ saved_node_idxs,
129
+ recomputable_node_idxs,
130
+ memories_banned_nodes,
131
+ runtimes_banned_nodes,
132
+ min_cut_saved_values,
133
+ )
134
+ )
135
+
136
+ trace_structured(
137
+ "artifact",
138
+ metadata_fn=lambda: {
139
+ "name": "min_cut_information",
140
+ "encoding": "json",
141
+ },
142
+ payload_fn=lambda: json.dumps(
143
+ activation_checkpointing_logging_structure_payload
144
+ ),
145
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+ import networkx as nx
4
+
5
+ from torch.fx import Graph, Node
6
+
7
+
8
+ class GraphInfoProvider:
9
+ """
10
+ This class provides information about the graph, such as the nodes, edges, and their runtime and memory requirements.
11
+ It also provides methods to create graphs from the information provided.
12
+ """
13
+
14
+ __RECOMPUTABLE_NODE_ONLY_GRAPH = "recomputable_node_only_graph"
15
+ __RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT = (
16
+ "recomputable_node_only_graph_with_larger_graph_context"
17
+ )
18
+ __FULL_NX_JOINT_GRAPH = "full_nx_joint_graph"
19
+ __SIMPLIFIED_FX_JOINT_GRAPH = "fx_joint_graph"
20
+
21
+ def __init__(
22
+ self,
23
+ graph_nodes_in_order: list[str],
24
+ graph_edges: list[tuple[str, str]],
25
+ all_recomputable_banned_nodes: list[str],
26
+ all_node_runtimes: Optional[dict[str, float]] = None,
27
+ all_node_memories: Optional[dict[str, float]] = None,
28
+ recorded_knapsack_input_memories: Optional[list[float]] = None,
29
+ recorded_knapsack_input_runtimes: Optional[list[float]] = None,
30
+ joint_graph: Optional[Graph] = None,
31
+ ):
32
+ self.graph_nodes_in_order = graph_nodes_in_order
33
+ self.graph_edges = graph_edges
34
+ self.all_node_runtimes: dict[str, float] = dict()
35
+ if all_node_runtimes is None:
36
+ if recorded_knapsack_input_runtimes is None:
37
+ raise ValueError(
38
+ "Either all_node_runtimes or recorded_knapsack_input_runtimes must be provided."
39
+ )
40
+ self.all_node_runtimes = {
41
+ node: recorded_knapsack_input_runtimes[i]
42
+ for i, node in enumerate(all_recomputable_banned_nodes)
43
+ }
44
+ else:
45
+ self.all_node_runtimes.update(all_node_runtimes)
46
+ self.all_node_memories: dict[str, float] = dict()
47
+ if all_node_memories is None:
48
+ if recorded_knapsack_input_memories is None:
49
+ raise ValueError(
50
+ "Either all_node_memories or recorded_knapsack_input_memories must be provided."
51
+ )
52
+ self.all_node_memories = {
53
+ node: recorded_knapsack_input_memories[i]
54
+ for i, node in enumerate(all_recomputable_banned_nodes)
55
+ }
56
+ else:
57
+ self.all_node_memories.update(all_node_memories)
58
+ self.all_recomputable_banned_nodes = all_recomputable_banned_nodes
59
+ self.all_recomputable_banned_nodes_set = set(all_recomputable_banned_nodes)
60
+ self.recorded_knapsack_input_memories = recorded_knapsack_input_memories
61
+ self.recorded_knapsack_input_runtimes = recorded_knapsack_input_runtimes
62
+ self._lazily_initialized_graphs: dict[str, Any] = {
63
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH: None,
64
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT: None,
65
+ self.__FULL_NX_JOINT_GRAPH: None,
66
+ self.__SIMPLIFIED_FX_JOINT_GRAPH: None,
67
+ }
68
+
69
+ @classmethod
70
+ def inialize_from_graph(
71
+ cls,
72
+ joint_graph: Graph,
73
+ all_recomputable_banned_nodes: list[Node],
74
+ recorded_knapsack_input_memories: list[float],
75
+ recorded_knapsack_input_runtimes: list[float],
76
+ ) -> "GraphInfoProvider":
77
+ """
78
+ Enables initialization from a joint graph.
79
+ """
80
+ graph_nodes_in_order = [node.name for node in joint_graph.nodes]
81
+ graph_edges = [
82
+ (node.name, user.name) for node in joint_graph.nodes for user in node.users
83
+ ]
84
+ all_recomputable_banned_node_names = [
85
+ node.name for node in all_recomputable_banned_nodes
86
+ ]
87
+ return cls(
88
+ graph_nodes_in_order=graph_nodes_in_order,
89
+ graph_edges=graph_edges,
90
+ all_recomputable_banned_nodes=all_recomputable_banned_node_names,
91
+ recorded_knapsack_input_memories=recorded_knapsack_input_memories,
92
+ recorded_knapsack_input_runtimes=recorded_knapsack_input_runtimes,
93
+ joint_graph=joint_graph,
94
+ )
95
+
96
+ @property
97
+ def recomputable_node_only_graph(self) -> nx.DiGraph:
98
+ if self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] is None:
99
+ self._lazily_initialized_graphs[
100
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH
101
+ ] = self._create_recomputable_node_only_graph()
102
+ return self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH]
103
+
104
+ @property
105
+ def recomputable_node_only_graph_with_larger_graph_context(self) -> nx.DiGraph:
106
+ if (
107
+ self._lazily_initialized_graphs[
108
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT
109
+ ]
110
+ is None
111
+ ):
112
+ self._lazily_initialized_graphs[
113
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT
114
+ ] = self._create_recomputable_node_only_graph_with_larger_graph_context()
115
+ return self._lazily_initialized_graphs[
116
+ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT
117
+ ]
118
+
119
+ @property
120
+ def full_joint_nx_graph(self) -> nx.DiGraph:
121
+ if self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] is None:
122
+ self._lazily_initialized_graphs[
123
+ self.__FULL_NX_JOINT_GRAPH
124
+ ] = self._create_full_joint_graph()
125
+ return self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH]
126
+
127
+ @property
128
+ def simplified_fx_joint_graph(self) -> Graph:
129
+ if self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] is None:
130
+ self._lazily_initialized_graphs[
131
+ self.__SIMPLIFIED_FX_JOINT_GRAPH
132
+ ] = self._recreate_psuedo_joint_graph()
133
+ return self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH]
134
+
135
+ def get_non_ac_peak_memory(self) -> float:
136
+ return sum(
137
+ self.all_node_memories[node_name]
138
+ for node_name in self.all_recomputable_banned_nodes_set
139
+ )
140
+
141
+ def get_theoretical_max_runtime(self) -> float:
142
+ return sum(
143
+ self.all_node_runtimes[node_name]
144
+ for node_name in self.all_recomputable_banned_nodes_set
145
+ )
146
+
147
+ def get_knapsack_memory_input(self) -> list[float]:
148
+ return (
149
+ self.recorded_knapsack_input_memories
150
+ if self.recorded_knapsack_input_memories
151
+ else [
152
+ self.all_node_memories[node_name]
153
+ for node_name in self.all_recomputable_banned_nodes
154
+ ]
155
+ )
156
+
157
+ def get_knapsack_runtime_input(self) -> list[float]:
158
+ return (
159
+ self.recorded_knapsack_input_runtimes
160
+ if self.recorded_knapsack_input_runtimes
161
+ else [
162
+ self.all_node_runtimes[node_name]
163
+ for node_name in self.all_recomputable_banned_nodes
164
+ ]
165
+ )
166
+
167
+ def _create_recomputable_node_only_graph(self) -> nx.DiGraph:
168
+ graph = nx.DiGraph()
169
+ for recomputable_node in self.all_recomputable_banned_nodes:
170
+ graph.add_node(recomputable_node)
171
+
172
+ for a, b in self.graph_edges:
173
+ if (
174
+ a in self.all_recomputable_banned_nodes_set
175
+ and b in self.all_recomputable_banned_nodes_set
176
+ ):
177
+ graph.add_edge(a, b)
178
+ return graph
179
+
180
+ def _create_recomputable_node_only_graph_with_larger_graph_context(
181
+ self,
182
+ ) -> nx.DiGraph:
183
+ # Create a dictionary to store the reachable nodes for each node
184
+ all_recomputable_banned_nodes_set = set(self.all_recomputable_banned_nodes)
185
+
186
+ reachable_nodes = {}
187
+ for node in all_recomputable_banned_nodes_set:
188
+ # Use BFS to find all reachable nodes
189
+ predecessors = dict(nx.bfs_predecessors(self.full_joint_nx_graph, node))
190
+ reachable_recomputable_nodes = set(predecessors.keys()).intersection(
191
+ all_recomputable_banned_nodes_set
192
+ )
193
+ reachable_nodes[node] = reachable_recomputable_nodes
194
+ # Create the candidate graph
195
+ candidate_graph = nx.DiGraph()
196
+ candidate_graph.add_nodes_from(all_recomputable_banned_nodes_set)
197
+ for node1 in all_recomputable_banned_nodes_set:
198
+ for node2 in reachable_nodes[node1]:
199
+ # Check if there is an overlapping path
200
+ overlapping_path = False
201
+ for intermediate_node in reachable_nodes[node1]:
202
+ if (
203
+ intermediate_node != node2
204
+ and node2 in reachable_nodes[intermediate_node]
205
+ ):
206
+ overlapping_path = True
207
+ break
208
+ if not overlapping_path:
209
+ candidate_graph.add_edge(node1, node2)
210
+ return candidate_graph
211
+
212
+ def _create_full_joint_graph(self) -> nx.DiGraph:
213
+ graph = nx.DiGraph()
214
+ for node in self.graph_nodes_in_order:
215
+ if node == "output":
216
+ continue
217
+ graph.add_node(node)
218
+
219
+ for a, b in self.graph_edges:
220
+ if a == "output" or b == "output":
221
+ continue
222
+ graph.add_edge(a, b)
223
+ return graph
224
+
225
+ def _recreate_psuedo_joint_graph(self) -> Graph:
226
+ # Create a dictionary to store the dependencies of each node
227
+ node_dependencies: dict[str, list[str]] = {
228
+ node: [] for node in self.graph_nodes_in_order
229
+ }
230
+ for a, b in self.graph_edges:
231
+ if a not in node_dependencies or b not in node_dependencies:
232
+ raise ValueError(f"Edge ({a}, {b}) references a non-existent node.")
233
+ node_dependencies[b].append(a)
234
+
235
+ joint_graph = Graph()
236
+ # Create nodes in the graph
237
+ nodes: dict[str, Node] = {}
238
+ for node_name in self.graph_nodes_in_order:
239
+ input_nodes = [nodes[dep] for dep in node_dependencies[node_name]]
240
+ if input_nodes:
241
+ node = joint_graph.call_function(lambda *x: x, tuple(input_nodes))
242
+ node.name = node_name
243
+ else:
244
+ node = joint_graph.placeholder(node_name)
245
+ nodes[node_name] = node
246
+ return joint_graph
247
+
248
+ def _visualize_recomputable_candidate_graph_with_larger_context(
249
+ self,
250
+ layout_k: float = 0.5,
251
+ layout_iterations: int = 30,
252
+ ) -> None:
253
+ """
254
+ Visualize the recomputable candidate graph with larger context.
255
+ """
256
+ from matplotlib import cm, colors as mcolors, pyplot as plt
257
+
258
+ pos = nx.spring_layout(
259
+ self.recomputable_node_only_graph_with_larger_graph_context,
260
+ k=layout_k,
261
+ iterations=layout_iterations,
262
+ )
263
+ # pos = nx.spectral_layout(graph_with_indirect_edges)
264
+ plt.figure(figsize=(20, 15))
265
+
266
+ # Create a dictionary for node labels using the index
267
+ labels = {
268
+ node: self.recomputable_node_only_graph_with_larger_graph_context.nodes[
269
+ node
270
+ ].get("index", node)
271
+ for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes
272
+ }
273
+
274
+ # Extract memory values and normalize them
275
+ norm = mcolors.Normalize(
276
+ vmin=min(self.get_knapsack_memory_input()),
277
+ vmax=max(self.get_knapsack_memory_input()),
278
+ )
279
+ cmap = cm.viridis # type: ignore[attr-defined]
280
+
281
+ # Assign colors based on memory
282
+ node_colors = [
283
+ cmap(
284
+ norm(
285
+ float(
286
+ self.recomputable_node_only_graph_with_larger_graph_context.nodes[
287
+ node
288
+ ][
289
+ "memory"
290
+ ]
291
+ )
292
+ )
293
+ )
294
+ for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes
295
+ ]
296
+
297
+ # Draw the graph with parsed nodes only
298
+ nx.draw_networkx_nodes(
299
+ self.recomputable_node_only_graph_with_larger_graph_context,
300
+ pos,
301
+ node_color=node_colors,
302
+ node_size=300,
303
+ label="Parsed Nodes",
304
+ )
305
+ nx.draw_networkx_edges(
306
+ self.recomputable_node_only_graph_with_larger_graph_context,
307
+ pos,
308
+ arrows=True,
309
+ arrowsize=10,
310
+ )
311
+ nx.draw_networkx_labels(
312
+ self.recomputable_node_only_graph_with_larger_graph_context,
313
+ pos,
314
+ labels=labels,
315
+ font_size=8,
316
+ font_weight="bold",
317
+ )
318
+
319
+ plt.title("Memory Colour Coded Dependency Graph for Recomputable Nodes")
320
+ plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), label="Memory")
321
+ plt.show()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def greedy_knapsack(
5
+ memory: list[float], runtimes: list[float], max_memory: float
6
+ ) -> tuple[float, list[int], list[int]]:
7
+ n = len(runtimes)
8
+ items = list(range(n))
9
+
10
+ # Sort items based on the ratio of runtime to memory in descending order
11
+ items = sorted(items, key=lambda i: runtimes[i] / memory[i], reverse=True)
12
+
13
+ total_memory = 0.0
14
+ total_runtime = 0.0
15
+ items_to_save = []
16
+ items_to_allow_recomputing = []
17
+
18
+ for i in items:
19
+ if total_memory + memory[i] <= max_memory:
20
+ total_memory += memory[i]
21
+ total_runtime += runtimes[i]
22
+ items_to_save.append(i)
23
+ else:
24
+ items_to_allow_recomputing.append(i)
25
+ return total_runtime, items_to_save, items_to_allow_recomputing
26
+
27
+
28
+ def ilp_knapsack(
29
+ memory: list[float], runtimes: list[float], max_memory: float
30
+ ) -> tuple[float, list[int], list[int]]:
31
+ import numpy as np
32
+
33
+ try:
34
+ from scipy.optimize import Bounds, LinearConstraint, milp
35
+ except ImportError:
36
+ raise RuntimeError(
37
+ "To use the ILP for memory budget checkpointing you need to install scipy"
38
+ ) from None
39
+
40
+ np_memory = np.array(memory)
41
+ np_runtimes = np.array(runtimes)
42
+ c = -np_runtimes # type: ignore[operator]
43
+
44
+ memory_constraint = LinearConstraint(A=np_memory, ub=np.array(max_memory))
45
+ constraints = [memory_constraint]
46
+
47
+ integrality = np.ones_like(c)
48
+ res = milp(
49
+ c=c, constraints=constraints, integrality=integrality, bounds=Bounds(0, 1)
50
+ )
51
+ if not res.success:
52
+ raise RuntimeError("Somehow scipy solving failed")
53
+
54
+ items_to_save = []
55
+ items_to_allow_recomputing = []
56
+ for idx, i in enumerate(res.x):
57
+ if i == 1:
58
+ items_to_save.append(idx)
59
+ else:
60
+ items_to_allow_recomputing.append(idx)
61
+ return -res.fun, items_to_save, items_to_allow_recomputing
62
+
63
+
64
+ def dp_knapsack(
65
+ memory: list[float], runtime: list[float], max_memory: float
66
+ ) -> tuple[float, list[int], list[int]]:
67
+ # Scaling factor to convert floating point weights to integers
68
+ S = 10000
69
+
70
+ # Quantize the memory weights
71
+ quantized_memory = torch.tensor(
72
+ [int(round(m * S)) for m in memory], dtype=torch.long, device="cpu"
73
+ )
74
+ runtimes = torch.tensor(runtime, dtype=torch.float32, device="cpu")
75
+
76
+ # Quantized pseudopolynomial DP for 0-1 Knapsack
77
+ quantized_max_memory = int(round(max_memory * S))
78
+
79
+ n = len(memory)
80
+
81
+ # Initialize the DP table
82
+ # TODO(chilli): I think if needed, this memory can be optimized with sliding
83
+ # window trick + Hirschberg trick:
84
+ # https://codeforces.com/blog/entry/47247?#comment-316200
85
+ dp = torch.zeros(
86
+ (n + 1, quantized_max_memory + 1), dtype=torch.float32, device="cpu"
87
+ )
88
+
89
+ for i in range(1, n + 1):
90
+ current_memory = quantized_memory[i - 1]
91
+ current_runtime = runtimes[i - 1]
92
+
93
+ # Copy the previous row
94
+ dp[i, :] = dp[i - 1, :]
95
+
96
+ # Update dp[i, j] for all j >= current_memory
97
+ if current_memory == 0:
98
+ dp[i, :] = dp[i - 1, :] + current_runtime
99
+ else:
100
+ dp[i, current_memory:] = torch.maximum(
101
+ dp[i - 1, current_memory:],
102
+ dp[i - 1, :-current_memory] + current_runtime,
103
+ )
104
+
105
+ # Backtrack to find the items included in the knapsack
106
+ saved_items = []
107
+ recomputable_items = []
108
+ j: int = quantized_max_memory
109
+ for i in range(n, 0, -1):
110
+ if dp[i][j] != dp[i - 1][j]:
111
+ saved_items.append(i - 1) # Include this item (indexing from 0)
112
+ j -= int(quantized_memory[i - 1].item())
113
+ else:
114
+ recomputable_items.append(i - 1)
115
+
116
+ saved_items.reverse() # To get items in the order they were added
117
+
118
+ # The maximum runtime that can be achieved within the max_memory constraint
119
+ max_runtime = dp[n][quantized_max_memory].item()
120
+
121
+ return max_runtime, saved_items, recomputable_items
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from collections import deque
3
+ from typing import Callable
4
+
5
+ import networkx as nx
6
+
7
+ from torch._functorch._activation_checkpointing.graph_info_provider import (
8
+ GraphInfoProvider,
9
+ )
10
+
11
+
12
+ class KnapsackEvaluator:
13
+ """
14
+ This class evaluates the theoretical runtime and peak memory usage of a given checkpointing strategy.
15
+ It takes in a graph and a list of nodes that are saved and recomputed, and then simulates the
16
+ backward pass to calculate the peak memory usage.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ graph_info_provider: GraphInfoProvider,
22
+ ) -> None:
23
+ self._graph_info_provider = graph_info_provider
24
+
25
+ def _get_backward_memory_from_topologically_sorted_graph(
26
+ self,
27
+ node_graph: nx.DiGraph,
28
+ node_memories: dict[str, float],
29
+ saved_nodes_set: set[str],
30
+ peak_memory_after_forward_pass: float,
31
+ ) -> list[tuple[float, str]]:
32
+ """
33
+ Simulates the backward pass and keeps track of the peak memory usage.
34
+
35
+ High Level Steps:
36
+ 1. Set Initial Peak/Current Memory
37
+ Allows you to set the peak memory after the forward pass, but typically this is
38
+ the sum of the estimated memory of the saved nodes.
39
+ 2. Perform a reverse topological sort of the node_graph.
40
+ If full graph is defined then will sort the full graph and only process the subset
41
+ of nodes in the node_graph.
42
+ 3. Iterate through the sorted graph nodes.
43
+ If the node is saved then just drop it's memory from current memory.
44
+ If the node is not saved then add it's memory to current memory and then traverse it's
45
+ predecessors to simulate recomuptation chain. Will check if new peak memory after all
46
+ predecessors are processed.
47
+
48
+ Args:
49
+ node_graph (nx.DiGraph): A directed graph representing the recomputable forward nodes.
50
+ saved_nodes_set (Set[str]): A set of node names that are saved.
51
+ peak_memory_after_forward_pass (float): The peak memory usage after the forward pass.
52
+ """
53
+ current_memory = [
54
+ (peak_memory_after_forward_pass, "Initial Peak/Current Memory")
55
+ ]
56
+ already_computed = set()
57
+ sorted_nodes = list(reversed(list(nx.topological_sort(node_graph))))
58
+ dependencies_computed = set()
59
+
60
+ for node in sorted_nodes:
61
+ if node in saved_nodes_set or node in already_computed:
62
+ current_memory.append(
63
+ (
64
+ current_memory[-1][0] - node_memories[node],
65
+ f"Dropping Node(already saved): {node}",
66
+ )
67
+ )
68
+ continue
69
+
70
+ already_computed.add(node)
71
+ current_memory.append(
72
+ (
73
+ current_memory[-1][0] + node_memories[node],
74
+ f"Recomputing Node: {node}",
75
+ )
76
+ )
77
+ # Create a queue of dependencies required for recomputation
78
+ predecessor_queue = deque(
79
+ [
80
+ dependency
81
+ for dependency, v in node_graph.in_edges(node)
82
+ if dependency not in already_computed
83
+ ]
84
+ )
85
+ while predecessor_queue:
86
+ dep = predecessor_queue.popleft()
87
+ already_computed.add(dep)
88
+ dependencies_computed.add(dep)
89
+ current_memory.append(
90
+ (
91
+ current_memory[-1][0] + node_memories[dep],
92
+ f"Recomputing Predecessor of {node}: {dep}",
93
+ )
94
+ )
95
+ # Add predecessors of the predecessor to the queue if they haven't been recomputed yet
96
+ for dependency_of_dependency, _ in node_graph.in_edges(dep):
97
+ if (
98
+ dependency_of_dependency in already_computed
99
+ or dependency_of_dependency in saved_nodes_set
100
+ or dependency_of_dependency in predecessor_queue
101
+ ):
102
+ continue
103
+ predecessor_queue.append(dependency_of_dependency)
104
+ dependencies_computed.clear()
105
+ current_memory.append(
106
+ (current_memory[-1][0] - node_memories[node], f"Dropping Node: {node}")
107
+ )
108
+ return current_memory
109
+
110
+ def _validate_all_indexes_accounted_for_in_provided_output(
111
+ self, saved_nodes_idxs: list[int], recomputable_node_idxs: list[int]
112
+ ) -> None:
113
+ """
114
+ Validate that all indexes are accounted for in the provided output.
115
+ This function checks that the union of saved nodes and recomputable nodes
116
+ covers all candidate nodes without any overlaps.
117
+ """
118
+ recomputable_node_idxs_set = set(recomputable_node_idxs)
119
+ saved_nodes_idxs_set = set(saved_nodes_idxs)
120
+ all_candidate_nodes_idxs = set(
121
+ range(len(self._graph_info_provider.all_recomputable_banned_nodes))
122
+ )
123
+ # Check that there are no overlaps between saved nodes and recomputable nodes
124
+ assert (
125
+ len(recomputable_node_idxs_set.intersection(saved_nodes_idxs_set)) == 0
126
+ ), "Saved nodes and recomputable nodes cannot have any overlaps"
127
+ # Check that all candidate nodes are accounted for
128
+ assert (
129
+ recomputable_node_idxs_set.union(saved_nodes_idxs_set)
130
+ == all_candidate_nodes_idxs
131
+ ), "All candidate nodes must be accounted for in the provided output"
132
+
133
+ def evaluate_knapsack_output(
134
+ self,
135
+ saved_nodes_idxs: list[int],
136
+ recomputable_node_idxs: list[int],
137
+ account_for_backward_pass: bool = False,
138
+ ) -> dict[str, float]:
139
+ """
140
+ Evaluate the theoretical runtime and peak memory usage of a given checkpointing strategy.
141
+ Args:
142
+ - saved_nodes_idxs (List[int]): The indices of nodes that are saved.
143
+ - recomputable_node_idxs (List[int]): The indices of nodes that need to be recomputed.
144
+ """
145
+ self._validate_all_indexes_accounted_for_in_provided_output(
146
+ saved_nodes_idxs, recomputable_node_idxs
147
+ )
148
+ recomputation_runtime = sum(
149
+ self._graph_info_provider.all_node_runtimes[
150
+ self._graph_info_provider.all_recomputable_banned_nodes[node]
151
+ ]
152
+ for node in recomputable_node_idxs
153
+ )
154
+ if account_for_backward_pass:
155
+ memory_list = self._get_backward_memory_from_topologically_sorted_graph(
156
+ node_graph=self._graph_info_provider.recomputable_node_only_graph_with_larger_graph_context,
157
+ saved_nodes_set={
158
+ self._graph_info_provider.all_recomputable_banned_nodes[i]
159
+ for i in saved_nodes_idxs
160
+ },
161
+ node_memories=self._graph_info_provider.all_node_memories,
162
+ peak_memory_after_forward_pass=sum(
163
+ self._graph_info_provider.all_node_memories[
164
+ self._graph_info_provider.all_recomputable_banned_nodes[i]
165
+ ]
166
+ for i in saved_nodes_idxs
167
+ ),
168
+ )
169
+ peak_memory = max(memory_list, key=operator.itemgetter(0))[0]
170
+ else:
171
+ peak_memory = sum(
172
+ self._graph_info_provider.all_node_memories[
173
+ self._graph_info_provider.all_recomputable_banned_nodes[node]
174
+ ]
175
+ for node in saved_nodes_idxs
176
+ )
177
+ return {
178
+ "peak_memory": peak_memory,
179
+ "recomputation_runtime": recomputation_runtime,
180
+ "non_ac_peak_memory": self._graph_info_provider.get_non_ac_peak_memory(),
181
+ "theoretical_max_runtime": self._graph_info_provider.get_theoretical_max_runtime(),
182
+ "percentage_of_theoretical_peak_memory": peak_memory
183
+ / self._graph_info_provider.get_non_ac_peak_memory(),
184
+ "percentage_of_theoretical_peak_runtime": recomputation_runtime
185
+ / self._graph_info_provider.get_theoretical_max_runtime(),
186
+ }
187
+
188
+ def evaluate_distribution_of_results_for_knapsack_algo(
189
+ self,
190
+ knapsack_algo: Callable[
191
+ [list[float], list[float], float], tuple[float, list[int], list[int]]
192
+ ],
193
+ memory_budget_values: list[float],
194
+ ) -> list[dict[str, float]]:
195
+ """
196
+ Evaluates the distribution of results for a given knapsack algorithm.
197
+ Args:
198
+ knapsack_algo (Callable): The knapsack algorithm to use for evaluation.
199
+ memory_budget_values (List[float]): A list of memory budgets to evaluate.
200
+ """
201
+ results = list()
202
+ for memory_budget in memory_budget_values:
203
+ _, saved_nodes, recomputed_nodes = knapsack_algo(
204
+ self._graph_info_provider.get_knapsack_memory_input(),
205
+ self._graph_info_provider.get_knapsack_runtime_input(),
206
+ memory_budget,
207
+ )
208
+ result = self.evaluate_knapsack_output(
209
+ saved_nodes_idxs=saved_nodes,
210
+ recomputable_node_idxs=recomputed_nodes,
211
+ )
212
+ result["memory_budget"] = memory_budget
213
+ results.append(result)
214
+ return results
215
+
216
+ def get_knee_point_memory_budget(
217
+ self,
218
+ knapsack_algo: Callable[
219
+ [list[float], list[float], float], tuple[float, list[int], list[int]]
220
+ ],
221
+ max_mem_budget: float = 0.1,
222
+ min_mem_budget: float = 0.001,
223
+ iterations: int = 100,
224
+ ) -> float:
225
+ """
226
+ Finds the memory budget at the knee point in the Pareto frontier.
227
+
228
+ The knee point is defined as the point where the trade-off between
229
+ runtime and memory usage is optimal.
230
+
231
+ Args:
232
+ knapsack_algo (callable): Knapsack algorithm to use for evaluation.
233
+ max_mem_budget (float, optional): Maximum memory budget. Defaults to 0.1.
234
+ min_mem_budget (float, optional): Minimum memory budget. Defaults to 0.001.
235
+ iterations (int, optional): Number of memory budgets to evaluate. Defaults to 100.
236
+
237
+ Returns:
238
+ float: Memory budget at the knee point.
239
+ """
240
+ results = self.evaluate_distribution_of_results_for_knapsack_algo(
241
+ knapsack_algo=knapsack_algo,
242
+ memory_budget_values=[
243
+ min_mem_budget
244
+ + i * (max_mem_budget - min_mem_budget) / (iterations - 1)
245
+ for i in range(iterations)
246
+ ],
247
+ )
248
+ runtime_values = [
249
+ result["percentage_of_theoretical_peak_runtime"] for result in results
250
+ ]
251
+ memory_values = [
252
+ result["percentage_of_theoretical_peak_memory"] for result in results
253
+ ]
254
+ runtime_range = max(runtime_values) - min(runtime_values)
255
+ memory_range = max(memory_values) - min(memory_values)
256
+ if runtime_range == 0 or memory_range == 0:
257
+ return max_mem_budget
258
+
259
+ # Normalize values
260
+ runtime_min = min(runtime_values)
261
+ memory_min = min(memory_values)
262
+ runtime_norm = [
263
+ (value - runtime_min) / runtime_range for value in runtime_values
264
+ ]
265
+ memory_norm = [(value - memory_min) / memory_range for value in memory_values]
266
+ # Calculate Euclidean distance
267
+ distances = [
268
+ (runtime_norm[i] ** 2 + memory_norm[i] ** 2) ** 0.5
269
+ for i in range(len(runtime_norm))
270
+ ]
271
+ # Find the knee point(shortest distance from the origin)
272
+ knee_index = distances.index(min(distances))
273
+ return results[knee_index]["memory_budget"]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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.
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py ADDED
@@ -0,0 +1,1442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Utils for caching the outputs of AOTAutograd
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import contextlib
9
+ import functools
10
+ import json
11
+ import logging
12
+ import os
13
+ import pickle
14
+ import shutil
15
+ import time
16
+ import traceback
17
+ from abc import ABC, abstractmethod
18
+ from copy import copy
19
+ from dataclasses import dataclass
20
+ from typing import Any, Callable, Generic, Optional, TYPE_CHECKING, TypeVar, Union
21
+ from typing_extensions import override
22
+
23
+ import torch
24
+ from torch._dynamo.precompile_context import PrecompileCacheArtifact, PrecompileContext
25
+ from torch._dynamo.trace_rules import torch_non_c_binding_in_graph_functions
26
+ from torch._dynamo.utils import (
27
+ chromium_event_log_active,
28
+ CompileEventLogger,
29
+ counters,
30
+ dynamo_timed,
31
+ )
32
+ from torch._functorch import config
33
+ from torch._inductor.codecache import (
34
+ _ident,
35
+ add_ephemeral_timeout_increase_for_distributed,
36
+ BypassFxGraphCache,
37
+ create_cache,
38
+ extract_tensor_metadata_for_cache_key,
39
+ FxGraphCache,
40
+ FxGraphCachePickler,
41
+ FxGraphHashDetails,
42
+ GuardedCache,
43
+ sha256_hash,
44
+ write_atomic,
45
+ )
46
+ from torch._inductor.output_code import (
47
+ CompiledFxGraph,
48
+ CompiledFxGraphConstants,
49
+ OutputCode,
50
+ )
51
+ from torch._inductor.runtime.runtime_utils import cache_dir
52
+ from torch._inductor.utils import should_use_remote_fx_graph_cache
53
+ from torch._logging import LazyString
54
+ from torch._utils_internal import log_cache_bypass
55
+ from torch.compiler._cache import (
56
+ CacheArtifact,
57
+ CacheArtifactFactory,
58
+ CacheArtifactManager,
59
+ )
60
+ from torch.fx.experimental.symbolic_shapes import hint_int
61
+ from torch.utils._triton import has_triton_package
62
+ from torchgen.utils import dataclass_repr
63
+
64
+ from .runtime_wrappers import (
65
+ AOTDispatchAutograd,
66
+ AOTDispatchSubclassWrapper,
67
+ CachedAutogradLazyBackwardCompileInfo,
68
+ CompilerWrapper,
69
+ FunctionalizedRngRuntimeWrapper,
70
+ post_compile,
71
+ RuntimeWrapper,
72
+ SubclassMeta,
73
+ )
74
+ from .schemas import AOTAutogradCacheInfo, AOTConfig, ViewAndMutationMeta # noqa: F401
75
+
76
+
77
+ if TYPE_CHECKING:
78
+ from torch._inductor.compile_fx import _CompileFxKwargs
79
+ from torch._inductor.cudagraph_utils import BoxedDeviceIndex
80
+ from torch._inductor.remote_cache import JsonDataTy, RemoteCache
81
+ from torch._inductor.utils import BoxedBool
82
+ from torch.fx.node import Node
83
+
84
+ log = logging.getLogger(__name__)
85
+
86
+
87
+ class BypassAOTAutogradCache(Exception):
88
+ pass
89
+
90
+
91
+ # Used to signify when FXGraphCache missed when AOTAutogradCache uses it
92
+ class FXGraphCacheMiss(BypassAOTAutogradCache):
93
+ pass
94
+
95
+
96
+ def should_use_remote_autograd_cache():
97
+ if torch._inductor.config.force_disable_caches:
98
+ return False
99
+ if config.enable_remote_autograd_cache is not None:
100
+ return config.enable_remote_autograd_cache
101
+ if not config.is_fbcode():
102
+ return False
103
+
104
+ if torch._utils_internal.is_fb_unit_test():
105
+ return False
106
+
107
+ try:
108
+ from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
109
+ except ModuleNotFoundError:
110
+ return False
111
+
112
+ jk_name = "pytorch/remote_cache:aot_autograd_cache_version"
113
+
114
+ return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(jk_name)
115
+
116
+
117
+ def should_use_local_autograd_cache():
118
+ if torch._inductor.config.force_disable_caches:
119
+ return False
120
+ return config.enable_autograd_cache
121
+
122
+
123
+ def check_node_safe(node: Node):
124
+ """
125
+ Checks that the node only uses supported operators. We are starting with very
126
+ conservative cacheability constraints, and incrementally adding more support as we expand.
127
+
128
+ [Note: AOTAutograd Cacheability checks]
129
+ - Our cache key is computed from the FX graph produced by Dynamo and the input example values
130
+ - A node is "safe" if the same cache key results in a compiled artifact that has the same behavior
131
+ (i.e, the set of inputs that go into our cache key is sufficient to distinguish its behavior)
132
+
133
+ To accomplish this safety check, we consider the following functions to be safe:
134
+ - Public functions under modules torch, torch.functional, and torch.nn.functional: these are
135
+ allowed in the graph by dynamo, so we can assume they are safe to cache.
136
+ - method calls on base tensor types
137
+ - Any call_module that dynamo deemed safe to allow AOTAutograd to trace
138
+ - Non callable nodes, such as placeholder, output, get_attr
139
+
140
+ The test suite test_aot_autograd_cache.py::AOTAutogradCachePicklerTests tries its best to fully cover/specify this behavior.
141
+ """
142
+ SAFE_TORCH_MODULES = ("torch.functional", "torch.nn.functional")
143
+ SAFE_TORCH_FUNCTIONS = (
144
+ "torch.Size",
145
+ "torch.Tensor",
146
+ "torch.sym_int",
147
+ "torch._sym_sqrt",
148
+ "torch.sym_float",
149
+ "torch.sym_sum",
150
+ )
151
+ SAFE_NON_TORCH_FUNCTIONS = (
152
+ "einops.einops.rearrange",
153
+ "einops.einops.repeat",
154
+ )
155
+
156
+ def is_public_torch_api(target):
157
+ # Don't blindly allow private functions in the torch namespace
158
+ is_private = target.__name__.startswith("_")
159
+
160
+ return (
161
+ getattr(target, "__module__", None) in SAFE_TORCH_MODULES and not is_private
162
+ )
163
+
164
+ def is_safe_torch_function(target):
165
+ """Allowlisted torch functions"""
166
+ function_name = f"{target.__module__}.{target.__name__}"
167
+ # Allow torch.autograd.function.FunctionCtx if custom autograd functions are allowed
168
+ if function_name == "torch.autograd.function.FunctionCtx":
169
+ return (
170
+ torch._functorch.config.autograd_cache_allow_custom_autograd_functions
171
+ )
172
+
173
+ # Functions in torch_non_c_binding_in_graph_functions
174
+ # are guaranteed to be cache safe.
175
+ # See NOTE: [Cacheability of in-graph torch functions]
176
+ return (
177
+ function_name in torch_non_c_binding_in_graph_functions
178
+ or function_name in SAFE_TORCH_FUNCTIONS
179
+ or function_name in torch._inductor.config.unsafe_marked_cacheable_functions
180
+ )
181
+
182
+ def is_cacheable_function(target):
183
+ if isinstance(target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)):
184
+ return True
185
+ if is_public_torch_api(target):
186
+ return True
187
+ # Technically, FXGraphCache._check_for_hop already checks this,
188
+ # but better to error earlier anyway
189
+ if isinstance(target, torch._ops.HigherOrderOperator):
190
+ return target.cacheable()
191
+ is_builtin_fun_or_type = type(target).__name__ == "builtin_function_or_method"
192
+ if is_builtin_fun_or_type:
193
+ return True
194
+ if is_safe_torch_function(target):
195
+ return True
196
+ function_name = f"{target.__module__}.{target.__name__}"
197
+ if function_name in SAFE_NON_TORCH_FUNCTIONS:
198
+ return True
199
+ return False
200
+
201
+ def is_tensor(target):
202
+ # Tensors always have example values in meta field
203
+ return "example_value" in target.meta
204
+
205
+ # I'd love to use a match statement here, but it wasn't introduced until py3.10
206
+ if node.op == "call_function":
207
+ if node.meta and node.meta.get("is_wrapped", False):
208
+ # This is fx.wrap function
209
+ # By default we BypassAOTAutogradCache for unknown functions,
210
+ # But if user explicitly specified cache hash - allow to cache it.
211
+ if node.meta.get("user_cache_hash", None):
212
+ return
213
+
214
+ if not is_cacheable_function(node.target):
215
+ module = getattr(node.target, "__module__", None)
216
+ name = getattr(node.target, "__name__", None)
217
+ raise BypassAOTAutogradCache(
218
+ f"Unsupported call_function target {node.target}. \n Function module: {module}, \nFunction name: {name}"
219
+ )
220
+ elif node.op == "call_method":
221
+ method_name = node.target
222
+ method_target = node.args[0]
223
+ # Only support method calls on base tensors
224
+ if not is_tensor(method_target):
225
+ module = getattr(method_target, "__module__", None)
226
+ name = getattr(method_target, "__name__", None)
227
+ raise BypassAOTAutogradCache(
228
+ f"Unsupported call_method target {method_target}. \nMethod module: {module}, \nMethod name: {name}"
229
+ )
230
+ if (
231
+ type(method_name) != str
232
+ and type(method_name).__name__ != "method_descriptor"
233
+ ):
234
+ raise BypassAOTAutogradCache(
235
+ f"Unsupported call_method method {node.target}: {method_name}"
236
+ )
237
+ # Cache safe
238
+ elif node.op in ("placeholder", "get_attr", "call_module", "output"):
239
+ # Assumption today for call_module being a safe op:
240
+ # (1) today the only call_module ops that can show up in a graph come from "built-in-nn-modules"
241
+ # that dynamo assumes are safe to trace. If dynamo assumes they are safely to blindly trace, then
242
+ # they should be safe to cache as well.
243
+ # (2) in the steady-state (some time in H2?) we shouldn't see these anymore, once inline builtin nn modules by default
244
+ # (3) We do not allow user made nn modules in the graph today, only function calls.
245
+ pass
246
+ else:
247
+ raise BypassAOTAutogradCache(f"Unsupported node op {node.op}")
248
+
249
+
250
+ def check_cacheable(gm: torch.fx.GraphModule):
251
+ """
252
+ Checks that the graph module only uses supported operators
253
+ """
254
+ nodes = gm.graph.nodes
255
+ if torch._inductor.config.freezing:
256
+ raise BypassAOTAutogradCache("Cannot cache a graph with freezing enabled")
257
+
258
+ if not (
259
+ torch._inductor.config.fx_graph_cache or should_use_remote_fx_graph_cache()
260
+ ):
261
+ raise BypassAOTAutogradCache("FX graph cache is not enabled")
262
+
263
+ tracing_context = torch._guards.TracingContext.try_get()
264
+ if tracing_context and tracing_context.fakify_first_call:
265
+ raise BypassAOTAutogradCache(
266
+ "Won't cache a graph with fakify_first_call enabled"
267
+ )
268
+ for node in nodes:
269
+ check_node_safe(node)
270
+
271
+ # Saved tensors hooks are globally set subgraphs,
272
+ # that are not used explicitly in the main graph.
273
+ # They are inlined in aot_autograd graphs.
274
+ # Subgraphs are only used for caching logic.
275
+ if hasattr(gm, "saved_tensors_hooks_pack_0"):
276
+ check_cacheable(gm.saved_tensors_hooks_pack_0) # type: ignore[arg-type]
277
+ # We have guarantee of unpack sugraph existance if pack subgraph exists
278
+ check_cacheable(gm.saved_tensors_hooks_unpack_0) # type: ignore[arg-type]
279
+
280
+
281
+ def check_metadata_cacheable(metadata: ViewAndMutationMeta):
282
+ """
283
+ When view replay is turned on, we bypass autograd cache if
284
+ the output is aliased.
285
+ """
286
+ if config.view_replay_for_aliased_outputs:
287
+ for info in metadata.output_info:
288
+ if info.functional_tensor is not None:
289
+ raise BypassAOTAutogradCache(
290
+ "Cannot cache a graph with functional tensor"
291
+ )
292
+
293
+
294
+ class AOTAutogradCacheDetails(FxGraphHashDetails):
295
+ """
296
+ Object to capture all the details for a dynamo graph module relevant to computing
297
+ a safe and stable cache key for AOTAutograd.
298
+ """
299
+
300
+ def __init__(
301
+ self,
302
+ gm: torch.fx.GraphModule,
303
+ example_inputs,
304
+ aot_config: AOTConfig,
305
+ fx_config: _CompileFxKwargs,
306
+ ):
307
+ # FxGraphHashDetails contains all the keys related to inductor. Also includes some system info
308
+ self.aot_config = aot_config
309
+ self.grad_enabled = torch.is_grad_enabled()
310
+ self.disable_amp = torch._C._is_any_autocast_enabled()
311
+ self.deterministic_algorithms = torch.are_deterministic_algorithms_enabled()
312
+ self.autograd_config = config.save_config()
313
+ self.saved_tensors_hooks_fx_wrap_cache_hashes: tuple[list[str], list[str]] = (
314
+ [],
315
+ [],
316
+ )
317
+
318
+ if hasattr(gm, "saved_tensors_hooks_pack_0"):
319
+
320
+ def _add_wrapped_user_cache_hashes(_gm, _l):
321
+ for node in _gm.graph.nodes:
322
+ if node.meta and node.meta.get("is_wrapped", False):
323
+ _l.append(node.meta["user_cache_hash"])
324
+
325
+ _add_wrapped_user_cache_hashes(
326
+ gm.saved_tensors_hooks_pack_0,
327
+ self.saved_tensors_hooks_fx_wrap_cache_hashes[0],
328
+ )
329
+ _add_wrapped_user_cache_hashes(
330
+ gm.saved_tensors_hooks_unpack_0,
331
+ self.saved_tensors_hooks_fx_wrap_cache_hashes[1],
332
+ )
333
+
334
+ try:
335
+ # FXGraphCache has constraints on what can be pickled in its inductor
336
+ # config. Check that the gm is cacheable by inductor first,
337
+ # and if it raises an exception, also bypass on our end.
338
+ FxGraphCache._check_can_cache(gm)
339
+ super().__init__(gm, example_inputs, fx_config, [])
340
+ except BypassFxGraphCache as e:
341
+ # Sometimes inductor configs are unpickleable and can fail
342
+ raise BypassAOTAutogradCache(str(e)) from e
343
+
344
+
345
+ class AOTAutogradCachePickler(FxGraphCachePickler):
346
+ def __init__(self, gm: torch.fx.GraphModule):
347
+ super().__init__(gm)
348
+ self.dispatch_table: dict
349
+ self.dispatch_table.update(
350
+ {
351
+ AOTConfig: functools.partial(self._reduce_aot_config),
352
+ torch.Tensor: functools.partial(self._reduce_tensor),
353
+ }
354
+ )
355
+
356
+ def _reduce_aot_config(self, aot_config: AOTConfig):
357
+ """
358
+ Reduce the config to a stable key for caching.
359
+ """
360
+ return (
361
+ _ident,
362
+ (
363
+ aot_config.num_params_buffers,
364
+ aot_config.keep_inference_input_mutations,
365
+ aot_config.is_export,
366
+ aot_config.no_tangents,
367
+ aot_config.dynamic_shapes,
368
+ aot_config.aot_autograd_arg_pos_to_source,
369
+ aot_config.enable_log,
370
+ aot_config.pre_dispatch,
371
+ ),
372
+ )
373
+
374
+ def _reduce_tensor(self, tensor):
375
+ """
376
+ Reduce the tensor to a stable key for caching.
377
+ """
378
+ metadata = extract_tensor_metadata_for_cache_key(tensor)
379
+ return (_ident, (metadata,))
380
+
381
+
382
+ def autograd_cache_key(
383
+ gm: torch.fx.GraphModule,
384
+ example_inputs,
385
+ config: AOTConfig,
386
+ fx_config: _CompileFxKwargs,
387
+ # TODO: add args and parameters
388
+ ) -> tuple[str, list[str]]:
389
+ """
390
+ Generate a unique hash of the FX graph for caching.
391
+ """
392
+ check_cacheable(gm)
393
+ if has_triton_package():
394
+ # Due to https://github.com/triton-lang/triton/issues/3729,
395
+ # if triton is < 3.2.0, AOTAutogradCache may cause us to
396
+ # attempt to load a cache entry without initializing
397
+ # the CUDA context on the autograd thread.
398
+
399
+ # Without caching, we naturally do this initialization when
400
+ # tracing through the graph with the autograd engine.
401
+ import triton
402
+
403
+ if triton.__version__ < "3.2.0":
404
+ raise BypassAOTAutogradCache("AOTAutogradCache requires triton 3.2.0")
405
+
406
+ details = AOTAutogradCacheDetails(gm, example_inputs, config, fx_config)
407
+ pickler = AOTAutogradCachePickler(gm)
408
+ # The prefix distinguishes among the other kinds of objects we cache
409
+ key = "a" + pickler.get_hash(details)
410
+ debug_lines = pickler.debug_lines(details)
411
+ log.debug(
412
+ "Autograd graph cache hash details for key %s:\n%s",
413
+ key,
414
+ LazyString(lambda: "\n".join(debug_lines)),
415
+ )
416
+ return key, debug_lines
417
+
418
+
419
+ TOut = TypeVar("TOut", bound=OutputCode)
420
+
421
+
422
+ class InductorOutput(Generic[TOut], ABC):
423
+ """
424
+ Class representing a single inductor output
425
+ """
426
+
427
+ @abstractmethod
428
+ def pre_save(self) -> None:
429
+ ...
430
+
431
+ @abstractmethod
432
+ def load(self, example_inputs) -> TOut:
433
+ ...
434
+
435
+ @abstractmethod
436
+ def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut:
437
+ ...
438
+
439
+
440
+ @dataclass
441
+ class CompiledFxGraphLoadable(InductorOutput[CompiledFxGraph]):
442
+ """
443
+ A full compiled fx graph that doesn't need to lookup the FxGraphCache
444
+ to run
445
+ """
446
+
447
+ result: CompiledFxGraph
448
+
449
+ def pre_save(self) -> None:
450
+ disk_compiled_graph = copy(self.result)
451
+ disk_compiled_graph.prepare_for_serialization()
452
+ self.result = disk_compiled_graph
453
+ return
454
+
455
+ def load(self, example_inputs) -> CompiledFxGraph:
456
+ self.example_inputs = example_inputs
457
+
458
+ return self.result
459
+
460
+ def post_compile(
461
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
462
+ ) -> CompiledFxGraph:
463
+ constants = CompiledFxGraphConstants()
464
+ # Cache hit specific post compile
465
+ graph, cache_info = FxGraphCache.cache_hit_post_compile(result, {}, constants)
466
+ if graph is None:
467
+ raise BypassAOTAutogradCache("Failed to reload cache entry from disk")
468
+ torch._logging.trace_structured(
469
+ "artifact",
470
+ metadata_fn=lambda: {
471
+ "name": "fx_graph_bundled_cache_hit", # always a hit
472
+ "encoding": "json",
473
+ },
474
+ payload_fn=lambda: json.dumps(cache_info),
475
+ )
476
+ counters["inductor"]["fxgraph_cache_hit"] += 1
477
+ # Run normal post compile
478
+ graph.post_compile(self.example_inputs, constants, fx_config)
479
+ return graph
480
+
481
+
482
+ @dataclass
483
+ class FxGraphCacheLoadable(InductorOutput[CompiledFxGraph]):
484
+ fx_graph_cache_info: tuple[str, list[str]]
485
+ fx_graph_guard_expr: Optional[str]
486
+
487
+ def pre_save(self):
488
+ return
489
+
490
+ def _is_backward(self) -> bool:
491
+ return False
492
+
493
+ def load(self, example_inputs) -> CompiledFxGraph:
494
+ # [Note: AOTAutogradCache and FXGraphCache Guard interactions]
495
+ # As mentioned, AOTAutograd takes in the symint inputs from dynamo's list of arguments.
496
+ # FXGraphCache serializes guards that are needed in the shape_env based on these symint inputs to the graph.
497
+ # The invariant that AOTAutograd uses here is that the sources for symints given to it by dynamo are exactly
498
+ # the same as the ones it passes to inductor, for both the forward and backward passes.
499
+ # (This does not mean that the tensor values passed in are the same: only that their symints are).
500
+ # That is, AOTAutograd and Inductor never create new guards based on symints with different sources
501
+ # than those passed to it by inductor.
502
+
503
+ # We pass the post compile function, which sets various fx_config boxed values,
504
+ # so we can call it only after we're sure both forward and backward have
505
+
506
+ # Clear CompiledTritonKernels before loading from FXGraphCache
507
+ torch._inductor.async_compile.CompiledTritonKernels.cache_clear()
508
+ remote_cache = None
509
+ constants = CompiledFxGraphConstants()
510
+ if should_use_remote_fx_graph_cache():
511
+ remote_cache = FxGraphCache.get_remote_cache()
512
+ (cache_key, debug_lines) = self.fx_graph_cache_info
513
+
514
+ def check_exact_guard_match(guard_expr, _hints):
515
+ """
516
+ AOTAutogradCache tracks its own guards, so we just need to treat these guard expressions as a second
517
+ cache key of sorts: we just check for equality, i.e. the FXGraphCache entry with
518
+ the exact same guards as we originally saved into the cache.
519
+ """
520
+ return guard_expr == self.fx_graph_guard_expr
521
+
522
+ result, cache_info = FxGraphCache.load_with_key(
523
+ cache_key,
524
+ debug_lines,
525
+ example_inputs,
526
+ local=True,
527
+ remote_cache=remote_cache,
528
+ is_backward=self._is_backward(),
529
+ constants=constants,
530
+ evaluate_guards=check_exact_guard_match,
531
+ )
532
+ if result is None:
533
+ log.info("FXGraphCache cache miss for key %s", self.fx_graph_cache_info)
534
+ torch._logging.trace_structured(
535
+ "artifact",
536
+ metadata_fn=lambda: {
537
+ "name": "fx_graph_cache_miss", # always a hit
538
+ "encoding": "json",
539
+ },
540
+ payload_fn=lambda: json.dumps(cache_info),
541
+ )
542
+
543
+ raise FXGraphCacheMiss
544
+
545
+ # No need to log chromium event because AOTAutograd will log that immediately for us
546
+ torch._logging.trace_structured(
547
+ "artifact",
548
+ metadata_fn=lambda: {
549
+ "name": "fx_graph_cache_hit", # always a hit
550
+ "encoding": "json",
551
+ },
552
+ payload_fn=lambda: json.dumps(cache_info),
553
+ )
554
+ self.example_inputs = example_inputs
555
+ self.constants = constants
556
+ return result
557
+
558
+ def post_compile(
559
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
560
+ ) -> CompiledFxGraph:
561
+ """
562
+ Called after FXGraphCacheLoadable.load, mutates fx_config
563
+ """
564
+ result.post_compile(self.example_inputs, self.constants, fx_config)
565
+ return result
566
+
567
+
568
+ @dataclass
569
+ class CompiledForward(FxGraphCacheLoadable):
570
+ """
571
+ Cacheable entry for a forward function
572
+ """
573
+
574
+ def _is_backward(self) -> bool:
575
+ return False
576
+
577
+
578
+ @dataclass
579
+ class GenericCompiledBackward(InductorOutput[TOut]):
580
+ # Used by AOTDispatchAutograd.post_compile
581
+ backward_state_indices: list[int]
582
+ num_symints_saved_for_bw_: int
583
+
584
+
585
+ @dataclass
586
+ class CompiledBackward(GenericCompiledBackward[CompiledFxGraph], FxGraphCacheLoadable):
587
+ """
588
+ Cacheable entry for a forward function
589
+ """
590
+
591
+ def _is_backward(self) -> bool:
592
+ return True
593
+
594
+ def post_compile(
595
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
596
+ ) -> CompiledFxGraph:
597
+ compiled_bw = super().post_compile(result, fx_config)
598
+ # See note [Wrapping bw_compiler in disable]
599
+ # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py
600
+ # But since on cache hit we do not call the bw_compiler, we need to reapply the disable
601
+ return torch._dynamo.disable(compiled_bw, reason="do not trace generated backwards pass") # type: ignore[return-value]
602
+
603
+
604
+ # Forward types don't have any extra parameters, so this is just a TypeAlias, in essence
605
+ class BundledCompiledForward(CompiledFxGraphLoadable):
606
+ pass
607
+
608
+
609
+ @dataclass
610
+ class BundledCompiledBackward(
611
+ GenericCompiledBackward[CompiledFxGraph], CompiledFxGraphLoadable
612
+ ):
613
+ def post_compile(
614
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
615
+ ) -> CompiledFxGraph:
616
+ compiled_bw = super().post_compile(result, fx_config)
617
+ # See note [Wrapping bw_compiler in disable]
618
+ # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py
619
+ # But since on cache hit we do not call the bw_compiler, we need to reapply the disable
620
+ return torch._dynamo.disable(compiled_bw, reason="do not trace generated backwards pass") # type: ignore[return-value]
621
+
622
+
623
+ @dataclass
624
+ class SerializedGraphModule:
625
+ fn: Callable[[dict[Any, Any], str], torch.nn.Module]
626
+ args: tuple[Any, ...]
627
+
628
+ def __init__(self, gm: torch.fx.GraphModule):
629
+ self.fn, self.args = gm.__reduce__()
630
+
631
+ def deserialize(self) -> torch.fx.GraphModule:
632
+ gm = self.fn(*self.args)
633
+ assert isinstance(gm, torch.fx.GraphModule)
634
+ return gm
635
+
636
+
637
+ def serialize_graph_module(gm: torch.fx.GraphModule) -> SerializedGraphModule:
638
+ # NOTE: mutates the graph module
639
+ gm.meta = {}
640
+ for node in gm.graph.nodes:
641
+ node.meta = {}
642
+ return SerializedGraphModule(gm)
643
+
644
+
645
+ TForward = TypeVar("TForward", bound=InductorOutput)
646
+ TBackward = TypeVar("TBackward", bound=GenericCompiledBackward)
647
+
648
+
649
+ @dataclass
650
+ class GenericAOTAutogradCacheEntry(Generic[TForward, TBackward]):
651
+ """A single entry into the cache, genericized by Forward and Backward types.
652
+
653
+ A TForward is always an InductorOutput of some sort, which represents the
654
+ forward graph of the compile.
655
+ A TBackward is an InductorOutput + metadata about the backward, useful for specific
656
+ backward-only wrappers. This type is encapsulated by GenericCompiledBackward.
657
+
658
+ Each AOTAutogradCacheEntry is essentially parameterized by 1. the method of loading
659
+ from the cache (either Bundled or UnBundled), and 2. The type of the output. For now,
660
+ the only type of output we support is Python Wrapper output, i.e. OutputCode.CompiledFxGraph,
661
+ but the same technique works for C++ wrapper code; we'd just add an extra InductorOutput type.
662
+ """
663
+
664
+ # Forward and Backward info
665
+ compiled_fw: TForward
666
+ compiled_bw: Optional[TBackward]
667
+
668
+ # Code of the joint graph using print_readable()
669
+ # Used for logging purposes
670
+ aot_joint_graph_str: Optional[str]
671
+ aot_forward_graph_str: Optional[str]
672
+ aot_backward_graph_str: Optional[str]
673
+
674
+ # Runtime_metadata saved right before compilation
675
+ runtime_metadata: ViewAndMutationMeta
676
+
677
+ # Wrappers that run after each aot_dispatch_* function
678
+ dispatch_wrappers: list[CompilerWrapper]
679
+
680
+ # Used by AOTSubclassWrapper
681
+ maybe_subclass_meta: Optional[SubclassMeta]
682
+ num_fw_outs_saved_for_bw: Optional[int]
683
+
684
+ # Used by RuntimeWrapepr
685
+ indices_of_inps_to_detach: list[int]
686
+
687
+ # Time taken to trace/compile the forward
688
+ # forward_time_taken includes AOTAutograd tracing time + inductor compilation time
689
+ # backward_time_taken is essentially just the time inductor took to compile
690
+ forward_time_taken_ns: int
691
+ backward_time_taken_ns: int
692
+
693
+ # Used by standalone_compile
694
+ sanitized_aot_config: AOTConfig
695
+
696
+ guards_expr: Optional[str]
697
+
698
+ # Used by Compiled Autograd
699
+ serialized_bw_module: Optional[SerializedGraphModule]
700
+
701
+ def pre_save(self):
702
+ """
703
+ Perform any preparations to make the cache entry ready for serialization.
704
+ """
705
+ check_metadata_cacheable(self.runtime_metadata)
706
+ self.compiled_fw.pre_save()
707
+ if self.compiled_bw is not None:
708
+ self.compiled_bw.pre_save()
709
+
710
+ # Turn cache entry into the original callable
711
+ def wrap_post_compile(
712
+ self,
713
+ args: list[torch.Tensor],
714
+ aot_config: AOTConfig,
715
+ fx_config: _CompileFxKwargs,
716
+ ) -> Callable:
717
+ """
718
+ This function takes a cache entry and carefully reconstructs the original callable
719
+ that AOTAutograd returned the first time it was run. It does this by running the various
720
+ post compile steps that AOTAutograd runs on its compiled artifact after running the fw/bw compilers.
721
+
722
+ In the inference path, this consists of the Subclass, FunctionalzedRngRuntime, and RuntimeWrappers.
723
+ In the autograd path, this consists of AOTAutogradDispatch.post_compile.
724
+
725
+ The steps here should match exactly the steps that are run in aot_dispatch_base and aot_dispatch_autograd.
726
+
727
+ Notably absent from the cached path are:
728
+ - DebugAssertWrapper
729
+ - FakifiedOutWrapper
730
+
731
+ Which we'll handle separately later on, if necessary.
732
+ """
733
+ # Log the output of AOTAutogradCache
734
+ if aot_config.enable_log:
735
+ # TODO: maybe also log to aot_graphs_log
736
+ # Unfortunately aot_graphs_log uses
737
+ # slightly different formatting though
738
+ if self.aot_joint_graph_str is not None:
739
+ torch._logging.trace_structured(
740
+ "aot_joint_graph", payload_fn=lambda: self.aot_joint_graph_str
741
+ )
742
+
743
+ if self.aot_forward_graph_str is not None:
744
+ torch._logging.trace_structured(
745
+ "artifact",
746
+ metadata_fn=lambda: {
747
+ "name": "aot_forward_graph_fw_metadata",
748
+ "encoding": "string",
749
+ },
750
+ payload_fn=lambda: dataclass_repr(self.runtime_metadata),
751
+ )
752
+ if self.maybe_subclass_meta is not None:
753
+ torch._logging.trace_structured(
754
+ "artifact",
755
+ metadata_fn=lambda: {
756
+ "name": "aot_forward_graph_fw_subclass_metadata",
757
+ "encoding": "string",
758
+ },
759
+ payload_fn=lambda: dataclass_repr(self.maybe_subclass_meta),
760
+ )
761
+
762
+ # It's called an inference graph if not running with autograd
763
+ name = (
764
+ "aot_forward_graph"
765
+ if self.aot_backward_graph_str is not None
766
+ else "aot_inference_graph"
767
+ )
768
+ torch._logging.trace_structured(
769
+ name, payload_fn=lambda: self.aot_forward_graph_str
770
+ )
771
+
772
+ if self.aot_backward_graph_str is not None:
773
+ torch._logging.trace_structured(
774
+ "aot_backward_graph", payload_fn=lambda: self.aot_backward_graph_str
775
+ )
776
+ with dynamo_timed("AOTAutogradCache.inductor_load"):
777
+ compiled_fw_func = self.compiled_fw.load(args)
778
+ compiled_bw_func = None
779
+ if self.compiled_bw is not None:
780
+ compiled_bw_func = self.compiled_bw.load(args)
781
+ needs_autograd = True
782
+ CompileEventLogger.try_add_pt2_compile(
783
+ "backend_compile", dispatch_mode="autograd"
784
+ )
785
+ # Now that we've loaded forward and backward, call post compile on both
786
+ # This avoids setting things like BoxedBools in fx_config until
787
+ # after both forward and backward cache hit
788
+ fw_fx_config: _CompileFxKwargs = {
789
+ **fx_config,
790
+ "is_backward": False,
791
+ }
792
+ bw_fx_config: _CompileFxKwargs = {
793
+ **fx_config,
794
+ "is_backward": True,
795
+ }
796
+ compiled_fw_func = self.compiled_fw.post_compile(
797
+ compiled_fw_func, fw_fx_config
798
+ )
799
+ compiled_bw_func = self.compiled_bw.post_compile(
800
+ compiled_bw_func, bw_fx_config
801
+ )
802
+ else:
803
+ inference_fx_config: _CompileFxKwargs = {
804
+ **fx_config,
805
+ "is_backward": False,
806
+ }
807
+
808
+ needs_autograd = False
809
+ CompileEventLogger.try_add_pt2_compile(
810
+ "backend_compile", dispatch_mode="inference"
811
+ )
812
+ compiled_fw_func = self.compiled_fw.post_compile(
813
+ compiled_fw_func, inference_fx_config
814
+ )
815
+
816
+ # Wrap the forward function in post compile wrappers
817
+ compiled_fw_func = AOTDispatchSubclassWrapper(
818
+ trace_joint=needs_autograd,
819
+ fw_only=None,
820
+ maybe_subclass_meta=self.maybe_subclass_meta,
821
+ num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw,
822
+ ).post_compile(
823
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
824
+ )
825
+
826
+ req_subclass_dispatch = self.maybe_subclass_meta is not None
827
+ CompileEventLogger.try_add_pt2_compile(
828
+ "backend_compile", requires_subclass_dispatch=req_subclass_dispatch
829
+ )
830
+
831
+ # In autograd case, functionalizedRngWrapper should not modify outs
832
+ return_new_outs = not needs_autograd
833
+ compiled_fw_func = FunctionalizedRngRuntimeWrapper(
834
+ return_new_outs=return_new_outs
835
+ ).post_compile(
836
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
837
+ )
838
+ disable_amp = torch._C._is_any_autocast_enabled()
839
+
840
+ if needs_autograd:
841
+ assert self.compiled_bw is not None
842
+
843
+ cached_lazy_backward = None
844
+ if self.serialized_bw_module is not None:
845
+ cached_lazy_backward = CachedAutogradLazyBackwardCompileInfo(
846
+ self.serialized_bw_module.deserialize
847
+ )
848
+ # This function is run on both cache miss and cache hit, either here
849
+ # or in aot_dispatch_autograd. On a cache hit,
850
+ # 1. the bw is already compiled
851
+ # 2. we don't need to save to the cache again
852
+ # so those corresponding arguments are set to None.
853
+ compiled_function = AOTDispatchAutograd.post_compile(
854
+ compiled_fw_func,
855
+ compiled_bw_func,
856
+ self.maybe_subclass_meta,
857
+ self.compiled_bw.num_symints_saved_for_bw_,
858
+ self.compiled_bw.backward_state_indices,
859
+ disable_amp,
860
+ self.indices_of_inps_to_detach,
861
+ cached_lazy_backward,
862
+ aot_config,
863
+ fw_metadata=self.runtime_metadata,
864
+ try_save_cache_entry=None,
865
+ )
866
+ else:
867
+ compiled_function = RuntimeWrapper(
868
+ indices_of_inps_to_detach=self.indices_of_inps_to_detach,
869
+ trace_joint=False,
870
+ disable_amp=disable_amp,
871
+ ).post_compile(
872
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
873
+ )
874
+
875
+ compiled_function, _ = post_compile(
876
+ self.dispatch_wrappers,
877
+ compiled_function,
878
+ aot_config,
879
+ runtime_metadata=self.runtime_metadata,
880
+ )
881
+
882
+ # Now that we're pretty sure it's a successful load, add guards
883
+ # to the existing shape environment from the cache
884
+ if self.guards_expr:
885
+ symints = AOTAutogradCache._filter_backed_symints(args)
886
+ check = bool(AOTAutogradCache.evaluate_guards(self.guards_expr, symints))
887
+ assert check is True
888
+
889
+ return compiled_function
890
+
891
+
892
+ class AOTAutogradCacheEntry(
893
+ GenericAOTAutogradCacheEntry[CompiledForward, CompiledBackward]
894
+ ):
895
+ """
896
+ Regular AOTAutogradCacheEntry: saves the forward/backward FxGraphCache keys
897
+ and looks them up in FxGraphCache on load
898
+ """
899
+
900
+
901
+ class BundledAOTAutogradCacheEntry(
902
+ GenericAOTAutogradCacheEntry[BundledCompiledForward, BundledCompiledBackward]
903
+ ):
904
+ """
905
+ AOTAutogradCacheEntry where we save the entire CompiledFxGraph instead
906
+ of relying on cache keys from FxGraphCache
907
+ """
908
+
909
+
910
+ @contextlib.contextmanager
911
+ def sanitize_gm_for_cache(gm: torch.fx.GraphModule):
912
+ """
913
+ Clears a few fields in a dynamo supplied Graph Module that are not stable between graph inputs, but don't
914
+ affect inductor or aotdispatch correctness.
915
+
916
+ These fields **can** be used by code calling into aotdispatch (namely, dynamo), so we can't null them out completely.
917
+
918
+ To ensure that these fields are not accessed by inductor or aotdispatch, we clear them during AOTAutogradCache.load,
919
+ and then put them back before returning. This way, we generate a cache key based off of a canonical graph
920
+ without these fields, and also guarantee they aren't used to affect the cache's output.
921
+ """
922
+ IGNORED_FIELDS = (
923
+ "meta", # metadata used by export
924
+ "compile_subgraph_reason", # Used by dynamo only for logging, no change in inductor/autograd behavior
925
+ "_param_name_to_source", # Encapsulated by aot_config.aot_autograd_arg_pos_to_source
926
+ "_backend_id",
927
+ )
928
+ saved_fields = {}
929
+ for field in IGNORED_FIELDS:
930
+ saved_fields[field] = getattr(gm, field, None)
931
+ # Clear the field
932
+ setattr(gm, field, None)
933
+ try:
934
+ yield
935
+ finally:
936
+ # Put the fields back after dispatch_and_compile is complete
937
+ for field, value in saved_fields.items():
938
+ setattr(gm, field, value)
939
+
940
+
941
+ @CacheArtifactFactory.register
942
+ class AOTAutogradCacheArtifact(CacheArtifact):
943
+ @override
944
+ def populate_cache(self):
945
+ AOTAutogradCache._write_to_local_cache(self.key, self.content)
946
+
947
+ @override
948
+ @staticmethod
949
+ def type():
950
+ return "aot_autograd"
951
+
952
+
953
+ @CacheArtifactFactory.register
954
+ class BundledAOTAutogradCacheArtifact(PrecompileCacheArtifact[Callable]):
955
+ @override
956
+ @staticmethod
957
+ def type():
958
+ return "precompile_aot_autograd"
959
+
960
+ @override
961
+ def after_deserialization(self) -> Callable:
962
+ entry = pickle.loads(self.content)
963
+ # In the precompile use case, guards are already serialized
964
+ # by dynamo, so we don't need to add them to the environment
965
+ entry.guards_expr = None
966
+ # TODO: this isn't exactly right, because cudagraphs needs to be a shared config
967
+ # which is set by compile_fx. But in precompile, we never actually call compile_fx
968
+ # so we don't have a place to track cudagraphs here.
969
+ cudagraphs = torch._inductor.config.triton.cudagraphs
970
+ compiled_fn = entry.wrap_post_compile(
971
+ [], entry.sanitized_aot_config, {"cudagraphs": cudagraphs}
972
+ )
973
+
974
+ # TODO: this ignores flat_params, which can exist
975
+ # if inline_builtin_nn_modules=False
976
+ def forward(*runtime_args: tuple[Any]):
977
+ return compiled_fn(list(runtime_args))
978
+
979
+ return forward
980
+
981
+
982
+ class AOTAutogradCache(GuardedCache[GenericAOTAutogradCacheEntry]):
983
+ """
984
+ Caches the results of running AOTAutograd. This class mostly handles the save and load logic, whereas
985
+ AOTAutogradCacheEntry handles the wrapping/unwrapping logic.
986
+
987
+ Cache Inputs (AOTAutogradCacheDetails)
988
+ - AOTAutogradCache takes in the following inputs, which are analogous to inputs given
989
+ to AOTAutograd by dynamo:
990
+ - A fx graph module generated by dynamo
991
+ - A list of args, which consists of:
992
+ - Symint inputs to the graph, generated by dynamo
993
+ - The **real tensor** inputs, which inductor uses for cudagraphs
994
+ - Notably, the real tensor inputs don't have symints in their metadata.
995
+ AOTAutograd then retraces those real tensor arguments into FakeTensors later during execution.
996
+ - A set of global configurations that affect AOTAutograd or Inductor behavior.
997
+
998
+ It then generates a cache key given these values. Notably, this means AOTAutogradCache currently
999
+ specializes on the sizes and strides of the real tensor inputs when dynamic shapes are turned on.
1000
+ In a later PR, we'll likely generate the cache key based on the FakeTensors AOTAutograd generates
1001
+ based on the real tensor inputs, which can contain symints.
1002
+
1003
+ # Cache Outputs (AOTAutogradCacheEntry)
1004
+ - AOTAutogradCache caches the following values:
1005
+ - The compiled forward and backward functions from inductor, via keys to the FXGraphCache
1006
+ - Metadata to reconstruct the AOTModule from the compiled inductor artifacts
1007
+ - See AOTAutogradCacheEntry for more info
1008
+
1009
+ [Note: Caching guards generated by AOTAutograd and Inductor]
1010
+ AOTAutograd and inductor both can introduce new guards to the shape environment. FXGraphCache saves guards with each
1011
+ compiled graph inductor generates. On a cache hit, AOTAutograd reloads the compiled forward and backward functions
1012
+ from FXGraphCache, giving it new symint arguments from the input args.
1013
+ FXGraphCache uses those symints and its saved guards to repopulate the ShapeEnv with guards.
1014
+ **No new guards are generated into the shape env after inductor finishes compiling**, so the guards
1015
+ saved by inductor are sufficient for correctness for both AOTAutograd and Inductor's caches.
1016
+ """
1017
+
1018
+ @staticmethod
1019
+ def clear():
1020
+ """Clear the cache"""
1021
+ try:
1022
+ shutil.rmtree(AOTAutogradCache._get_tmp_dir())
1023
+ except FileNotFoundError:
1024
+ pass
1025
+
1026
+ @staticmethod
1027
+ def load(
1028
+ dispatch_and_compile: Callable,
1029
+ mod: Union[torch.fx.GraphModule, torch._dynamo.utils.GmWrapper],
1030
+ args,
1031
+ aot_config: AOTConfig,
1032
+ cudagraphs: BoxedBool,
1033
+ boxed_forward_device_index: Optional[BoxedDeviceIndex],
1034
+ local: bool,
1035
+ remote: bool,
1036
+ ) -> Callable:
1037
+ """
1038
+ Load a result from the cache, and reconstruct a runtime wrapper around the object
1039
+ """
1040
+ gm = mod.gm if isinstance(mod, torch._dynamo.utils.GmWrapper) else mod
1041
+ with sanitize_gm_for_cache(gm):
1042
+ compiled_fn = None
1043
+ cache_info: dict[str, Any] = {}
1044
+ cache_key = None
1045
+ debug_lines: list[str] = []
1046
+ cache_event_time = time.time_ns()
1047
+ cache_state = None
1048
+ fx_config: _CompileFxKwargs = {
1049
+ "cudagraphs": cudagraphs,
1050
+ "boxed_forward_device_index": boxed_forward_device_index,
1051
+ }
1052
+ try:
1053
+ cache_key, debug_lines = autograd_cache_key(
1054
+ gm, args, aot_config, fx_config
1055
+ )
1056
+ entry: Optional[
1057
+ GenericAOTAutogradCacheEntry
1058
+ ] = AOTAutogradCache._lookup(
1059
+ cache_key, local, remote, args, cache_info, aot_config
1060
+ )
1061
+ if entry is not None:
1062
+ compiled_fn = entry.wrap_post_compile(args, aot_config, fx_config)
1063
+ log.info("AOTAutograd cache hit for key %s", cache_key)
1064
+
1065
+ counters["aot_autograd"]["autograd_cache_hit"] += 1
1066
+ cache_state = "hit"
1067
+ cache_event_time = time.time_ns()
1068
+ forward_time_saved = entry.forward_time_taken_ns // 1e6
1069
+ backward_time_saved = entry.backward_time_taken_ns // 1e6
1070
+ cache_info.update(
1071
+ {
1072
+ "forward_time_saved_ms": forward_time_saved,
1073
+ "backward_time_saved_ms": backward_time_saved,
1074
+ "time_saved_ms": forward_time_saved + backward_time_saved,
1075
+ }
1076
+ )
1077
+ time_saved_ns = (
1078
+ entry.forward_time_taken_ns + entry.backward_time_taken_ns
1079
+ )
1080
+ # TODO: should we use the same field for remote cache time saved for both
1081
+ # FXGraphCache and AOTAutogradCache?
1082
+ # get_metrics_context().increment(...)
1083
+ if (
1084
+ ephemeral_increase := add_ephemeral_timeout_increase_for_distributed(
1085
+ time_saved_ns
1086
+ )
1087
+ ) != 0:
1088
+ cache_info["ephemeral_timeout_increase"] = ephemeral_increase
1089
+
1090
+ if compiled_fn is None:
1091
+ log.info("AOTAutograd cache miss for key %s", cache_key)
1092
+ counters["aot_autograd"]["autograd_cache_miss"] += 1
1093
+ cache_state = "miss"
1094
+ cache_event_time = time.time_ns()
1095
+ # Count missing the FXGraphCache as a miss not a bypass
1096
+ except FXGraphCacheMiss as e:
1097
+ counters["aot_autograd"]["autograd_cache_miss"] += 1
1098
+ cache_state = "miss"
1099
+ if config.strict_autograd_cache:
1100
+ raise e
1101
+ # Most often this is BypassAOTAutogradCache, but
1102
+ # if there's ever different reason we can't cache,
1103
+ # we still never want to hard throw an exception, since
1104
+ # we can always fallback to a cache bypass.
1105
+ # As an example, if the user calls autograd via
1106
+ # standalone inductor, we will sometimes get a GraphModule
1107
+ # that doesn't actually have a `.graph` on it. Instead
1108
+ # of checking every single case, we safely catch the exception
1109
+ # in those cases.
1110
+ except Exception as e:
1111
+ cache_key = None
1112
+ counters["aot_autograd"]["autograd_cache_bypass"] += 1
1113
+ log.info("Bypassing autograd cache due to: %s", e)
1114
+ cache_state = "bypass"
1115
+ cache_event_time = time.time_ns()
1116
+ cache_info["cache_bypass_reason"] = str(e)
1117
+ cache_info["cache_bypass_exception_type"] = type(e).__name__
1118
+ cache_info["cache_bypass_traceback"] = traceback.format_exc().split(
1119
+ "\n"
1120
+ )
1121
+ # TODO: this gets logged implicitly by cache_bypass_reason,
1122
+ # and here we explicitly log it into tlparse.
1123
+ # We may want to log this as an extra column in Scuba, though.
1124
+ cache_info["cache_bypass_hard_exception"] = not isinstance(
1125
+ e, BypassAOTAutogradCache
1126
+ )
1127
+ if remote:
1128
+ log_cache_bypass("bypass_aot_autograd", str(e))
1129
+ if config.strict_autograd_cache:
1130
+ raise e
1131
+ if compiled_fn is None:
1132
+ # Set the cache key so we can save a cache result later
1133
+ symints = AOTAutogradCache._filter_backed_symints(args)
1134
+ if cache_key is not None:
1135
+ aot_config.cache_info = AOTAutogradCacheInfo(
1136
+ cache_key,
1137
+ time.time_ns(),
1138
+ forward_symints=symints,
1139
+ )
1140
+ compiled_fn = dispatch_and_compile()
1141
+
1142
+ cache_info.update(
1143
+ {
1144
+ "key": cache_key,
1145
+ "cache_state": cache_state,
1146
+ "components": debug_lines,
1147
+ }
1148
+ )
1149
+ if chromium_event_log_active():
1150
+ CompileEventLogger.instant(
1151
+ f"autograd_cache_{cache_state}",
1152
+ metadata=cache_info,
1153
+ time_ns=cache_event_time,
1154
+ )
1155
+ CompileEventLogger.try_add_pt2_compile(
1156
+ "backend_compile",
1157
+ cache_state=cache_state,
1158
+ cache_event_time=cache_event_time,
1159
+ key=cache_info.get("key"),
1160
+ components=cache_info.get("components"),
1161
+ cache_bypass_reason=cache_info.get("cache_bypass_reason"),
1162
+ remote_cache_enabled=remote,
1163
+ local_cache_enabled=local,
1164
+ )
1165
+
1166
+ torch._logging.trace_structured(
1167
+ "artifact",
1168
+ metadata_fn=lambda: {
1169
+ "name": f"aotautograd_cache_{cache_state}",
1170
+ "encoding": "json",
1171
+ },
1172
+ payload_fn=lambda: json.dumps(cache_info),
1173
+ )
1174
+ return compiled_fn
1175
+
1176
+ @classmethod
1177
+ def generate_guards_expression(
1178
+ cls: type[AOTAutogradCache], cache_info: AOTAutogradCacheInfo
1179
+ ) -> Optional[str]:
1180
+ shape_env = cls._get_shape_env()
1181
+ assert shape_env is not None
1182
+ symints = cache_info.forward_symints
1183
+ guards = shape_env.get_pruned_guards(symints)
1184
+ return shape_env.produce_guards_expression(placeholders=symints, guards=guards)
1185
+
1186
+ @classmethod
1187
+ def _get_tmp_dir(cls: type[AOTAutogradCache]) -> str:
1188
+ """
1189
+ Get the toplevel temporary directory for storing compiled graphs.
1190
+ """
1191
+ return os.path.join(cache_dir(), "aotautograd")
1192
+
1193
+ @classmethod
1194
+ def _get_tmp_dir_for_key(cls: type[AOTAutogradCache], key) -> str:
1195
+ """
1196
+ Get the toplevel temporary directory for storing compiled graphs.
1197
+ """
1198
+ return os.path.join(cls._get_tmp_dir(), key)
1199
+
1200
+ @staticmethod
1201
+ def evaluate_guards(guard_expr: str, hints: Union[list[int], list[torch.SymInt]]):
1202
+ if torch._inductor.config.unsafe_skip_cache_dynamic_shape_guards:
1203
+ return True
1204
+ shape_env = AOTAutogradCache._get_shape_env()
1205
+ assert shape_env is not None
1206
+ result = shape_env.evaluate_guards_expression(guard_expr, hints)
1207
+ return result
1208
+
1209
+ @staticmethod
1210
+ def _lookup(
1211
+ key: str,
1212
+ local: bool,
1213
+ remote: bool,
1214
+ args: list[Any],
1215
+ cache_info: dict[str, Any],
1216
+ aot_config: Optional[AOTConfig],
1217
+ ) -> Optional[GenericAOTAutogradCacheEntry]:
1218
+ """Given a key generated by AOTAutogradCachePickler, look up its location in the cache."""
1219
+ remote_cache: Optional[RemoteCache[JsonDataTy]] = None
1220
+ if remote:
1221
+ remote_cache = AOTAutogradCache.get_remote_cache()
1222
+
1223
+ symints = AOTAutogradCache._filter_backed_symints(args)
1224
+ hints = [hint_int(s) for s in symints]
1225
+ entry = None
1226
+ try:
1227
+ (
1228
+ entry,
1229
+ pickled_content,
1230
+ guard_info,
1231
+ ) = AOTAutogradCache.find_guarded_entry(
1232
+ key, local, remote_cache, AOTAutogradCache.evaluate_guards, hints
1233
+ )
1234
+
1235
+ if entry is None and guard_info["cache_status_detailed"] == "guard_miss":
1236
+ counters["aot_autograd"]["autograd_cache_guard_miss"] += 1
1237
+ cache_info.update(guard_info)
1238
+ if pickled_content is not None:
1239
+ CacheArtifactManager.record_artifact(
1240
+ AOTAutogradCacheArtifact.type(), key, pickled_content
1241
+ )
1242
+ if (
1243
+ config.bundled_autograd_cache
1244
+ and aot_config is not None
1245
+ and aot_config.precompile_backend_id is not None
1246
+ ):
1247
+ # NB: We don't want to use the cached aot_config.precompile_backend_id
1248
+ # 1. because we set it to None on save 2. even if we didn't, this new run
1249
+ # that cache hit has a *new* backend id associated with it.
1250
+ PrecompileContext.record_artifact(
1251
+ BundledAOTAutogradCacheArtifact.type(),
1252
+ aot_config.precompile_backend_id,
1253
+ pickled_content,
1254
+ )
1255
+ except Exception as e:
1256
+ log.info("AOTAutograd cache unable to load compiled graph: %s", e)
1257
+ if config.strict_autograd_cache:
1258
+ raise e
1259
+ return entry
1260
+
1261
+ @staticmethod
1262
+ def _write_to_local_cache(key: str, content: bytes):
1263
+ """Write an entry to the local cache."""
1264
+ subdir = AOTAutogradCache._get_tmp_dir_for_key(key)
1265
+ if not os.path.exists(subdir):
1266
+ os.makedirs(subdir, exist_ok=True)
1267
+
1268
+ # Use a hash of the serialized entry to get a unique file
1269
+ # name. The specific name doesn't matter since a lookup involves
1270
+ # iterating over all entries in the parent subdir.
1271
+ path = os.path.join(subdir, sha256_hash(content))
1272
+ log.info("Writing AOTAutograd cache entry to %s", path)
1273
+ write_atomic(path, content)
1274
+
1275
+ @staticmethod
1276
+ def save(key: str, entry: GenericAOTAutogradCacheEntry, remote: bool):
1277
+ """Save a single entry into the cache."""
1278
+ try:
1279
+ entry.pre_save()
1280
+ content = pickle.dumps(entry)
1281
+ CacheArtifactManager.record_artifact(
1282
+ AOTAutogradCacheArtifact.type(), key, content
1283
+ )
1284
+ if (
1285
+ config.bundled_autograd_cache
1286
+ and entry.sanitized_aot_config.precompile_backend_id is not None
1287
+ ):
1288
+ precompile_key = entry.sanitized_aot_config.precompile_backend_id
1289
+ # Now that we're saving it, the precompile_backend_id field is no longer
1290
+ # useful, remove it from the entry.
1291
+ entry.sanitized_aot_config.precompile_backend_id = None
1292
+ PrecompileContext.record_artifact(
1293
+ BundledAOTAutogradCacheArtifact.type(), precompile_key, content
1294
+ )
1295
+ AOTAutogradCache._write_to_local_cache(key, content)
1296
+ counters["aot_autograd"]["autograd_cache_saved"] += 1
1297
+ except BypassAOTAutogradCache as e:
1298
+ counters["aot_autograd"]["autograd_cache_bypass"] += 1
1299
+ log.info("Bypassing autograd cache due to: %s", e)
1300
+ if remote:
1301
+ log_cache_bypass("bypass_aot_autograd", str(e))
1302
+ return None
1303
+ except Exception as e:
1304
+ log.info("AOTAutograd cache unable to serialize compiled graph: %s", e)
1305
+ if remote:
1306
+ log_cache_bypass(
1307
+ "bypass_aot_autograd", "Unable to serialize: " + str(e)
1308
+ )
1309
+ if config.strict_autograd_cache:
1310
+ raise e
1311
+ return None
1312
+
1313
+ if remote:
1314
+ remote_cache: Optional[
1315
+ RemoteCache[JsonDataTy]
1316
+ ] = AOTAutogradCache.get_remote_cache()
1317
+ if remote_cache is not None:
1318
+ time_taken_ms = int(
1319
+ (entry.forward_time_taken_ns + entry.backward_time_taken_ns) // 1e6
1320
+ )
1321
+ cache_data: JsonDataTy = {
1322
+ "data": base64.b64encode(content).decode("ascii"),
1323
+ "time_taken_ms": time_taken_ms,
1324
+ }
1325
+ remote_cache.put(key, cache_data)
1326
+
1327
+ @staticmethod
1328
+ @functools.cache
1329
+ def get_remote_cache() -> Optional[RemoteCache[JsonDataTy]]:
1330
+ """
1331
+ Attempts to load the remote cache, returns None on error.
1332
+ """
1333
+ cache_id = "autograd-experimental"
1334
+ return create_cache(
1335
+ cache_id,
1336
+ config.is_fbcode(),
1337
+ "FbRemoteAOTAutogradCache",
1338
+ "RemoteAOTAutogradCache",
1339
+ )
1340
+
1341
+ @staticmethod
1342
+ def make_entry(
1343
+ compiled_fw_func: CompiledFxGraph,
1344
+ compiled_bw_func: Optional[CompiledFxGraph],
1345
+ aot_joint_graph_str: Optional[str],
1346
+ aot_forward_graph_str: Optional[str],
1347
+ aot_backward_graph_str: Optional[str],
1348
+ runtime_metadata: ViewAndMutationMeta,
1349
+ dispatch_wrappers: list[CompilerWrapper],
1350
+ maybe_subclass_meta: Optional[SubclassMeta],
1351
+ num_fw_outs_saved_for_bw: Optional[int],
1352
+ indices_of_inps_to_detach: list[int],
1353
+ forward_time_taken_ns: int,
1354
+ backward_time_taken_ns: int,
1355
+ sanitized_aot_config: AOTConfig,
1356
+ guards_expr: Optional[str],
1357
+ backward_state_indices: Optional[list[int]],
1358
+ num_symints_saved_for_bw: Optional[int],
1359
+ serialized_bw_module: Optional[SerializedGraphModule],
1360
+ ) -> GenericAOTAutogradCacheEntry:
1361
+ if config.bundled_autograd_cache:
1362
+ # Helper function to unwrap all the wrappers we added during aotdispatch
1363
+ # They get reapplied on cache load
1364
+ def unwrap_compiled_fx_graph(obj):
1365
+ while hasattr(obj, "__wrapped__"):
1366
+ obj = obj.__wrapped__
1367
+ assert isinstance(obj, CompiledFxGraph)
1368
+ return obj
1369
+
1370
+ compiled_fw_graph = unwrap_compiled_fx_graph(compiled_fw_func)
1371
+ bundled_compiled_forward = BundledCompiledForward(compiled_fw_graph)
1372
+ bundled_compiled_backward = None
1373
+ if compiled_bw_func is not None:
1374
+ assert backward_state_indices is not None
1375
+ assert num_symints_saved_for_bw is not None
1376
+ compiled_bw_graph = unwrap_compiled_fx_graph(compiled_bw_func)
1377
+ bundled_compiled_backward = BundledCompiledBackward(
1378
+ compiled_bw_graph, backward_state_indices, num_symints_saved_for_bw
1379
+ )
1380
+
1381
+ return BundledAOTAutogradCacheEntry(
1382
+ compiled_fw=bundled_compiled_forward,
1383
+ compiled_bw=bundled_compiled_backward,
1384
+ aot_joint_graph_str=aot_joint_graph_str,
1385
+ aot_forward_graph_str=aot_forward_graph_str,
1386
+ aot_backward_graph_str=aot_backward_graph_str,
1387
+ runtime_metadata=runtime_metadata,
1388
+ dispatch_wrappers=dispatch_wrappers,
1389
+ maybe_subclass_meta=maybe_subclass_meta,
1390
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1391
+ indices_of_inps_to_detach=indices_of_inps_to_detach,
1392
+ forward_time_taken_ns=forward_time_taken_ns,
1393
+ backward_time_taken_ns=backward_time_taken_ns,
1394
+ sanitized_aot_config=sanitized_aot_config,
1395
+ guards_expr=guards_expr,
1396
+ serialized_bw_module=serialized_bw_module,
1397
+ )
1398
+
1399
+ else:
1400
+ fw_key = getattr(compiled_fw_func, "_fx_graph_cache_key", None)
1401
+ fw_debug_lines = getattr(
1402
+ compiled_fw_func, "_fx_graph_cache_debug_lines", []
1403
+ )
1404
+
1405
+ assert fw_key is not None
1406
+ compiled_forward = CompiledForward(
1407
+ fx_graph_cache_info=(fw_key, fw_debug_lines),
1408
+ fx_graph_guard_expr=getattr(compiled_fw_func, "guards_expr", None),
1409
+ )
1410
+ compiled_backward = None
1411
+ if compiled_bw_func is not None:
1412
+ bw_key = getattr(compiled_bw_func, "_fx_graph_cache_key", None)
1413
+ bw_debug_lines = getattr(
1414
+ compiled_bw_func, "_fx_graph_cache_debug_lines", []
1415
+ )
1416
+ assert bw_key is not None
1417
+ assert backward_state_indices is not None
1418
+ assert num_symints_saved_for_bw is not None
1419
+ compiled_backward = CompiledBackward(
1420
+ fx_graph_cache_info=(bw_key, bw_debug_lines),
1421
+ fx_graph_guard_expr=getattr(compiled_bw_func, "guards_expr", None),
1422
+ backward_state_indices=backward_state_indices,
1423
+ num_symints_saved_for_bw_=num_symints_saved_for_bw,
1424
+ )
1425
+
1426
+ return AOTAutogradCacheEntry(
1427
+ compiled_fw=compiled_forward,
1428
+ compiled_bw=compiled_backward,
1429
+ aot_joint_graph_str=aot_joint_graph_str,
1430
+ aot_forward_graph_str=aot_forward_graph_str,
1431
+ aot_backward_graph_str=aot_backward_graph_str,
1432
+ runtime_metadata=runtime_metadata,
1433
+ dispatch_wrappers=dispatch_wrappers,
1434
+ maybe_subclass_meta=maybe_subclass_meta,
1435
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1436
+ indices_of_inps_to_detach=indices_of_inps_to_detach,
1437
+ forward_time_taken_ns=forward_time_taken_ns,
1438
+ backward_time_taken_ns=backward_time_taken_ns,
1439
+ sanitized_aot_config=sanitized_aot_config,
1440
+ guards_expr=guards_expr,
1441
+ serialized_bw_module=serialized_bw_module,
1442
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This module is one of the analysis modules - it takes as input a function or graph
4
+ and some preexisting properties, and returns some data that is useful for deciding
5
+ how to further proceed with compilation or construct runtime wrappers.
6
+
7
+ In particular, the analysis here constructs view and mutation metadata from running
8
+ a functionalized version of the graph under compilation.
9
+ """
10
+
11
+ import collections
12
+ import contextlib
13
+ import logging
14
+ from functools import wraps
15
+ from typing import Callable, Optional
16
+
17
+ import torch
18
+ import torch.utils._pytree as pytree
19
+ from torch import Tensor
20
+ from torch._guards import detect_fake_mode
21
+ from torch._logging import getArtifactLogger
22
+ from torch._subclasses.functional_tensor import FunctionalTensor, FunctionalTensorMode
23
+ from torch._subclasses.meta_utils import safe_is_leaf
24
+ from torch.fx.experimental.symbolic_shapes import is_concrete_int
25
+ from torch.multiprocessing.reductions import StorageWeakRef
26
+ from torch.utils._python_dispatch import (
27
+ is_traceable_wrapper_subclass,
28
+ transform_subclass,
29
+ )
30
+
31
+ from .functional_utils import (
32
+ are_all_mutations_hidden_from_autograd,
33
+ are_all_mutations_under_no_grad_or_inference_mode,
34
+ from_fun,
35
+ has_data_mutation,
36
+ has_metadata_mutation,
37
+ MetadataKey,
38
+ to_fun,
39
+ was_inductor_storage_resized,
40
+ )
41
+ from .schemas import (
42
+ FunctionalTensorMetadataEq,
43
+ InputAliasInfo,
44
+ MemoryFormatMeta,
45
+ MutationType,
46
+ OutputAliasInfo,
47
+ OutputType,
48
+ ViewAndMutationMeta,
49
+ )
50
+ from .subclass_utils import create_subclass_meta
51
+ from .utils import _get_autocast_states, KNOWN_TYPES, strict_zip
52
+
53
+
54
+ zip = strict_zip
55
+
56
+ log = logging.getLogger(__name__)
57
+ static_input_logger = getArtifactLogger("torch._dynamo", "cudagraph_static_inputs")
58
+
59
+
60
+ # Note [Tangents memory format]
61
+ # We assume tangents memory format to be similar to corresponding output's memory_format.
62
+ # The idea is that we are technically making a guess about the strides of our tangents,
63
+ # while we trace out the joint.
64
+ # If runtime specfied tangents will not have the same memory format as predicted traced tangents,
65
+ # we coerce them at runtime to traced tangents memory format.
66
+
67
+
68
+ # Coercing and collecting traced tangents memory format in one recursive traversal
69
+ # mypy: ignore-errors
70
+ def coerce_tangent_and_suggest_memory_format(x: Tensor):
71
+ updated = False
72
+ if not isinstance(x, Tensor):
73
+ return x, None, updated
74
+
75
+ out = x.detach()
76
+
77
+ is_subclass = is_traceable_wrapper_subclass(out)
78
+
79
+ memory_format = MemoryFormatMeta.from_tensor(out)
80
+
81
+ if memory_format.memory_format is not None:
82
+ was = out
83
+ out = out.contiguous(memory_format=memory_format.memory_format)
84
+ updated = was is not out
85
+
86
+ # For subclass we keep memory format of outer strides at the beggining of the list
87
+ out_memory_format = [memory_format] if is_subclass else memory_format
88
+
89
+ # Note [Tangents memory format, Part 2]
90
+ # In the same way that "what strides do we assigns to our tangents" is a question
91
+ # that we can not answer (and therefore have to guess) as we trace the backward ahead-of-time,
92
+ # The same applies to any tensor subclass metadata, when we have tangents that are subclasses.
93
+ # To handle this situation, we have two new methods that a tensor subclass can implement:
94
+ # (1) __coerce_tangent_metadata__(self)
95
+ # Given a subclass with "non-standard" metadata, turn it into a new subclass with "normal" metadata.
96
+ # The main example here is a DTensor with the "_Partial" placement.
97
+ # If we have a forward output with a _Partial placement, and corresponding tangent
98
+ # with a Replicate/Shard placement, we have no way to convert the tangent "back" to a _Partial placement.
99
+ # This method lets us avoid the problem entirely by allowing subclasses to ensure that we can never
100
+ # have a tangent with "problematic" metadata, that we cannot convert to.
101
+ # (1) __coerce_same_metadata_as_tangent__(self, metadata)
102
+ # Given a subclass, and a target differing metadata,
103
+ # convert self to have the same metadata as the target.
104
+ # With DTensor being the main example, we can use this to convert a DTensor with a Replicate()
105
+ # placement into one with a Shard() placement, in the case that we "guessed wrong",
106
+ # and traced tangents with a Shard() placement at compile time.
107
+ #
108
+ if is_subclass and hasattr(out, "__coerce_tangent_metadata__"):
109
+ out = out.__coerce_tangent_metadata__() # type: ignore[attr-defined]
110
+
111
+ if is_subclass:
112
+ attrs = out.__tensor_flatten__()[0]
113
+
114
+ for attr in attrs:
115
+ elem = getattr(out, attr)
116
+ (
117
+ new_elem,
118
+ new_elem_memory_format,
119
+ elem_updated,
120
+ ) = coerce_tangent_and_suggest_memory_format(elem)
121
+ out_memory_format.append(new_elem_memory_format)
122
+ if elem_updated:
123
+ setattr(out, attr, new_elem)
124
+
125
+ return out, out_memory_format, updated
126
+
127
+
128
+ # This is a version of functionalization that is specifically designed
129
+ # for the AOTAutograd use case.
130
+ #
131
+ # Unlike functorch's variant, this doesn't use the functorch level system,
132
+ # instead it directly uses PyTorch's conventional dispatcher to hit the
133
+ # functionalization key. In particular, this means that FunctionalTensorWrapper
134
+ # can have autograd data stored directly on it.
135
+ #
136
+ # In typical AOTAutograd usage, the dispatch key order will look like:
137
+ #
138
+ # Autograd - Functionalization ~~~~> Proxy Mode - Fake Tensor
139
+ # outer tensor inner tensor
140
+ #
141
+ # Returns:
142
+ # - ViewAndMutationMeta, telling us metadata about the inputs and outputs, and
143
+ # The list of outputs from the forward, but **only** the outputs that we need
144
+ # to pass in as tangents into the backward.
145
+ # Specifically, aliased outputs from the forward get regenerated, and don't participate
146
+ # in the compiled backward function.
147
+ def run_functionalized_fw_and_collect_metadata(
148
+ f,
149
+ *,
150
+ keep_input_mutations: bool,
151
+ # TODO: refactor to kill this flag
152
+ is_train: bool = False,
153
+ # Note: this is guaranteed to be set when running under dynamo
154
+ static_input_indices: Optional[list[int]] = None,
155
+ pre_dispatch: bool = False,
156
+ # is_export is technically only needed to avoid using functionalization V2
157
+ # during analysis
158
+ is_export: bool = False,
159
+ ) -> Callable[..., ViewAndMutationMeta]:
160
+ memo: dict[Tensor, Tensor] = {}
161
+
162
+ def _to_fun(t):
163
+ if isinstance(t, Tensor):
164
+ if t in memo:
165
+ return memo[t]
166
+ r = to_fun(t)
167
+ memo[t] = r
168
+ return r
169
+ else:
170
+ return t
171
+
172
+ @wraps(f)
173
+ def inner(*flat_args):
174
+ # This function is meant to be run with the forward, which expects a flat list of tensor/symint/other args.
175
+ assert all(isinstance(a, tuple(KNOWN_TYPES)) for a in flat_args)
176
+
177
+ input_info: list[InputAliasInfo] = []
178
+ output_info: list[OutputAliasInfo] = []
179
+
180
+ prior_grad_enabled = torch.is_grad_enabled()
181
+ prior_autocast_states = _get_autocast_states()
182
+
183
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
184
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
185
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
186
+ )
187
+
188
+ # It doesn't matter if we run this under predispatch or not because it is
189
+ # only for figuring out metadata
190
+ mode = FunctionalTensorMode(_allow_token_discovery=True, export=is_export)
191
+ suppress_pending = contextlib.nullcontext()
192
+ fake_mode = detect_fake_mode()
193
+ if fake_mode and (shape_env := fake_mode.shape_env):
194
+ suppress_pending = shape_env.ignore_fresh_unbacked_symbols()
195
+ with disable_above, mode, suppress_pending:
196
+ # precondition: The passed in function already handles unflattening inputs + flattening outputs
197
+ flat_f_args = pytree.tree_map(_to_fun, flat_args)
198
+ flat_f_outs = f(*flat_f_args)
199
+ # We didn't do any tracing, so we don't need to process the
200
+ # unbacked symbols, they will just disappear into the ether.
201
+ # Also, prevent memoization from applying.
202
+ if fake_mode:
203
+ fake_mode.epoch += 1
204
+ fake_mode.reset_nt_tensor_id_counter()
205
+
206
+ if prior_autocast_states != _get_autocast_states():
207
+ raise RuntimeError(
208
+ "AOTAutograd does not support tracing graphs that mutate the autocast state. "
209
+ "Dynamo will only insert autocast context managers (e.g. with torch.autocast(..)) into the graph, "
210
+ "which will unwind all of their mutations to autocast state before the graph exits. "
211
+ "If you encounter this error while using torch.compile, please file a bug."
212
+ )
213
+
214
+ # Inspect the state of the input tensor functional wrapper to detect input mutation info
215
+ # If inp[i] has a metadata-only mutation, then maybe_inputs_with_mutated_metadata[i] contains the updated version
216
+ for i, (arg, f_arg) in enumerate(zip(flat_args, flat_f_args)):
217
+ # NB: Mutation of non-contiguous tensor subclass input can result in a mismatch in
218
+ # strides between the functionalized arg inner tensors and non-functionalized arg inner
219
+ # tensors. This is a problem as the inner tensor stride change may not be reflected
220
+ # correctly in the outer tensor, so disallow this for now.
221
+ mutates_data = has_data_mutation(f_arg)
222
+ mutates_metadata = has_metadata_mutation(
223
+ f_arg, arg, check_only_storage_mutation=False
224
+ )
225
+ if mutates_metadata and is_traceable_wrapper_subclass(arg):
226
+ raise RuntimeError(
227
+ "Metadata mutations are currently not allowed on tensor subclasses"
228
+ )
229
+ mutates_storage_metadata = has_metadata_mutation(
230
+ f_arg, arg, check_only_storage_mutation=True
231
+ )
232
+ mutations_hidden_from_autograd = are_all_mutations_hidden_from_autograd(
233
+ f_arg
234
+ )
235
+ mutations_under_no_grad_or_inference_mode = (
236
+ mutates_data
237
+ and are_all_mutations_under_no_grad_or_inference_mode(f_arg)
238
+ )
239
+ mutation_inductor_storage_resize = was_inductor_storage_resized(f_arg)
240
+
241
+ if mutates_storage_metadata:
242
+ mutates_data = False
243
+
244
+ requires_grad = isinstance(f_arg, torch.Tensor) and f_arg.requires_grad
245
+
246
+ input_info.append(
247
+ InputAliasInfo(
248
+ is_leaf=isinstance(arg, Tensor) and safe_is_leaf(arg),
249
+ mutates_data=mutates_data,
250
+ mutates_metadata=mutates_metadata,
251
+ mutations_hidden_from_autograd=mutations_hidden_from_autograd,
252
+ mutates_storage_metadata=mutates_storage_metadata,
253
+ mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode,
254
+ mutation_inductor_storage_resize=mutation_inductor_storage_resize,
255
+ requires_grad=requires_grad,
256
+ keep_input_mutations=keep_input_mutations,
257
+ )
258
+ )
259
+
260
+ # If a function involves creating a tensor, and returning a view of it, such that its _base is the intermediate,
261
+ # We need to make sure our graph returns the _base as a graph output, and we manually recreate the view
262
+ # to return to the user. Why? The backend compiler is free to (incorrectly) not set requires_grad
263
+ # on the base tensor, but we are obligated to properly set requires-gradness on the real output.
264
+
265
+ inp_storage_refs = {
266
+ StorageWeakRef(inpt.untyped_storage()): idx
267
+ for idx, inpt in enumerate(flat_f_args)
268
+ if isinstance(inpt, Tensor)
269
+ }
270
+
271
+ # We need inp tensor id's to be able to tell if an outputs **are** inputs.
272
+ inp_tensor_ids = {id(inpt) for inpt in flat_f_args if isinstance(inpt, Tensor)}
273
+ # We need output tensor id's to tell if any output._base` attributes **are** other outputs.
274
+ # (This is also a dict because we need to know that output's index, so we can regenerate
275
+ # the alias from it).
276
+ out_tensor_ids = {id(o): i for i, o in enumerate(flat_f_outs)}
277
+
278
+ # Keep track of which outputs alias other outputs
279
+ out_tensor_alias_counts: collections.defaultdict = collections.defaultdict(int)
280
+ # This tells us, for a given group of outputs that alias each other,
281
+ # whether they e.g. all came from an unbind call
282
+ num_aliased_tensors_that_are_multi_output_views: collections.defaultdict = (
283
+ collections.defaultdict(int)
284
+ )
285
+
286
+ out_storage_to_metadata_key_to_tensors: collections.defaultdict[
287
+ Optional[StorageWeakRef],
288
+ collections.defaultdict[MetadataKey, set[torch.Tensor]],
289
+ ] = collections.defaultdict(lambda: collections.defaultdict(set))
290
+
291
+ curr_storage = None
292
+ for o in flat_f_outs:
293
+ if isinstance(o, torch.Tensor):
294
+ curr_storage = StorageWeakRef(o.untyped_storage())
295
+ out_tensor_alias_counts[curr_storage] += 1
296
+ # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
297
+ # This is an optimization on top of the "alias of intermediates" logic,
298
+ # which you can read more about under Note [AOT Autograd: outputs aliasing inputs or intermediates!]
299
+ #
300
+ # Before describing the optimization: this is important for AOTAutograd to have good
301
+ # perf around, multi-output views. HOWEVER:
302
+ # - There is a more generic change to AOTAutograd that we'd like to make, that subsumes this case,
303
+ # around using pre-dispatch tracing to partition out a graph so we can faithfully replay all
304
+ # views without having to regenerate them at runtime.
305
+ # - It's loosely described in this doc (more details will be added soon):
306
+ # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit
307
+ # - Once that change lands, we should just rip out this "optimization", since:
308
+ # (1) It will be fully unnecessary
309
+ # (2) Although it is only a few lines of code, it is a bit difficult to reason about
310
+ # its correctness with the autograd engine in all cases.
311
+ #
312
+ #
313
+ # What is this optimization? Consider the below case:
314
+ # def f(x):
315
+ # intermediate = x.mul(2)
316
+ # # x and intermediate here require grad
317
+ # o1, o2, ... o10 = intermediate.unbind(-1)
318
+ # return intermediate, o1, o2, ... o10
319
+ # Now, the "intermediate base" handling in AOTAutograd implies that we must do the following:
320
+ # (1) return "intermediate as an extra output of the compiled graph
321
+ # (2) regenerate each aliased output off of "intermediate", **outside** of the autograd.Function.
322
+ # The reason AOTAutograd ordinarily does this is for safety: the autograd engine needs to know
323
+ # that o1 through o10 are all aliased, and if we blindly return o1 through o10 from the autograd.Function,
324
+ # this information will be hidden.
325
+ # In particular, mutating one alias might require autograd to update autograd metadata on the other aliases
326
+ # (like their grad_fn, for example, when the autograd engine needs to do view-replay).
327
+ #
328
+ # However, intermediate_base logic can be bad for backward performance (we sometimes generate
329
+ # as_strided calls during the intermediate base logic, which can have a slow backward formula).
330
+ # Is it possible to find a set of conditions where it is **safe** to hide the output aliasing from autograd?
331
+ #
332
+ # For a set of outputs of the graph that alias each other, o_1...o_k, consider:
333
+ # (1) They came from the same multi-output view op, e.g. o_1, ..., o_k = intermediate.unbind(0)
334
+ # (2) If there are any other aliases of o_1 through o_k (in the example above, intermediate),
335
+ # **at most** 1 can escape from the graph (e.g. there is not some other graph input/output
336
+ # o_other, that aliases these outputs)
337
+ # (3) o_1...o_k all require_grad, they all share the same ._base, and their ._base requires grad.
338
+ # This condition is important because it's what causes slowness in the intermediate_base
339
+ # codepath of aot_autograd. Ordinarily, o_1...o_k would all get a grad_fn, and
340
+ # aot_autograd's view-replay might give each output an AsStridedBackward as its grad_fn.
341
+ # "K" AsStridedBackward calls will be *much* slower than a single UnbindBackward.
342
+ # In this setup, is it possible to mutate one of the outputs o_i in a way that would affect the autograd meta
343
+ # of the other aliases?
344
+ #
345
+ # Claim: No! Consider a few example (which I'm pretty sure cover all cases of mutation w.r.t. autograd):
346
+ # (a) What happens if we mutate any of o_1 through o_k directly?
347
+ # Autograd raises an error:
348
+ # "RuntimeError: Output 0 of UnbindBackward0 is a view and is being modified inplace. This view is
349
+ # the output of a function that returns multiple views. Such functions do not allow the output
350
+ # views to be modified inplace. You should replace the inplace operation by an out-of-place one."
351
+ # (b) What if we take a view of o_k and mutate it, o_k.view(o_k.shape).mul_(2)?
352
+ # Autograd raises the same error- the "multi-output-view"ness of an alias propagates to future views.
353
+ # (c) What if we mutate o_k under no_grad?
354
+ # Autograd raises the same error
355
+ # (d) What if we detach and mutate, e.g. o_k.detach().mul_(2)?
356
+ # Autograd allows this, *but* autograd updates all alias's grad_fn's to be error functions when accessed.
357
+ # Autograd raises the same error
358
+ # (e) What if we try to mutate another alias of o_1...o_k, that was **not** created from a multi-output view?
359
+ # We promised that there is at most **one** such alias, e.g. intermediate in the example above.
360
+ # You can mutate intermediate, but in eager mode this will change the grad_fn of o_1...o_k
361
+ # to be error fn's.
362
+ # Since intermediate was the *only* non-multi-output-alias, there are no other aliases
363
+ # of `intermediate` around that were produced by the compiled fn and have a valid grad_fn.
364
+ #
365
+ # Coming back to this optimization:
366
+ # Given that it is not possible for mutating one of these aliases to affect the autograd metadata of another alias
367
+ # without causing an error in eager mode, we will simple hide the aliasing from autograd during torch.compile
368
+ # if all of the above conditions are met.
369
+ # This has the slight downside that it's possible to write some "bad" code that autograd will raise an error on
370
+ # in eager but fail to during torch.compile, but it has the benefit that this code has much better performance.
371
+ # NOTE: if and when we eventually update AOTAutograd to do the "view graph slicing" defined here:
372
+ # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit,
373
+ # then this optimization will probably matter less and might be ok to remove.
374
+ is_cur_tensor_multi_out_view = isinstance(
375
+ o, FunctionalTensor
376
+ ) and torch._functionalize_is_multi_output_view( # type: ignore[attr-defined]
377
+ o.elem
378
+ )
379
+ if is_cur_tensor_multi_out_view:
380
+ num_aliased_tensors_that_are_multi_output_views[curr_storage] += 1
381
+ if o.requires_grad:
382
+ out_storage_to_metadata_key_to_tensors[curr_storage][
383
+ MetadataKey.make(o)
384
+ ].add(o)
385
+
386
+ # maps the id of an intermediate base to its index in the output of the compiled forward
387
+ intermediate_base_tensor_id_to_output_idx: dict[int, int] = {}
388
+ intermediate_bases: list[torch.Tensor] = []
389
+ # Why Do We Care If Storage Changed?
390
+ # It's important to understand the implications of storage changes in complex scenarios. Take this example:
391
+ #
392
+ # def f(x):
393
+ # x_storage = x.untyped_storage()
394
+ # non_leaf_tensor = torch.ones(4, requires_grad=True).clone()
395
+ #
396
+ # # Using no_grad() and _unsafe_preserve_version_counter to simulate the .data = operation
397
+ # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x):
398
+ # x.set_(non_leaf_tensor.untyped_storage())
399
+ #
400
+ # out = x.view(-1)
401
+ #
402
+ # # Restoring x to its original storage, again simulating .data = operation
403
+ # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x):
404
+ # x.set_(x_storage)
405
+ #
406
+ # return out
407
+ #
408
+ # In this scenario, 'x' and 'out' have different shapes and are stored at different memory addresses, aka no aliasing.
409
+ # However, due to how set_() and more specificlaly, set is functionalized, is defined to preserve eager semantics,
410
+ # the autograd engine mistakenly assumes that 'x' and 'out' are aliased, treating 'x' as 'out._base'.
411
+ # This misinterpretation leads to an 'alias_of_input' flag, causing an unnecessary as_strided() call to be generated,
412
+ # which could lead to issues later in the code.
413
+ for o in flat_f_outs:
414
+ functional_tensor_storage_changed = isinstance(
415
+ o, FunctionalTensor
416
+ ) and torch._functionalize_was_storage_changed( # type: ignore[attr-defined]
417
+ o.elem
418
+ )
419
+ curr_storage = (
420
+ None
421
+ if not isinstance(o, torch.Tensor)
422
+ else StorageWeakRef(o.untyped_storage())
423
+ )
424
+ outs_with_identical_metadata_that_require_grad = (
425
+ []
426
+ if not isinstance(o, Tensor)
427
+ else [
428
+ curr
429
+ for curr in out_storage_to_metadata_key_to_tensors[curr_storage][
430
+ MetadataKey.make(o)
431
+ ]
432
+ if o is not curr
433
+ ]
434
+ )
435
+
436
+ # See Note [Accessing .grad_fn on FunctionalTensor]
437
+ # In-place operations on views will trigger a lazy rebase of the autograd graph;
438
+ # this runs during access to the .grad_fn. The rebase logic will invoke view ops
439
+ # on FunctionalTensors, so we must enable a FunctionalTensorMode here to ensure
440
+ # these op calls succeed.
441
+ grad_fn = None
442
+ if isinstance(o, Tensor):
443
+ with FunctionalTensorMode():
444
+ grad_fn = o.grad_fn
445
+
446
+ is_result_of_custom_autograd_fn = False
447
+ # Need to check for both custom cpp (CppFunction) and python (BackwardCFunction)
448
+ # autograd fns
449
+ if type(grad_fn).__name__ == "CppFunction":
450
+ is_result_of_custom_autograd_fn = True
451
+ if isinstance(grad_fn, torch.autograd.function.BackwardCFunction):
452
+ is_result_of_custom_autograd_fn = True
453
+
454
+ if not isinstance(o, Tensor):
455
+ output_type = OutputType.non_alias
456
+ base_idx = None
457
+ elif (
458
+ curr_storage in inp_storage_refs
459
+ and grad_fn is not None
460
+ and is_result_of_custom_autograd_fn
461
+ ):
462
+ output_type = OutputType.custom_function_view
463
+ base_idx = None
464
+ elif (
465
+ curr_storage in inp_storage_refs
466
+ and not functional_tensor_storage_changed
467
+ ):
468
+ base_idx = inp_storage_refs[curr_storage]
469
+ is_input_tensor = id(o) in inp_tensor_ids
470
+ num_aliased_outs = out_tensor_alias_counts[curr_storage]
471
+ num_multi_output_view_outs = (
472
+ num_aliased_tensors_that_are_multi_output_views[curr_storage]
473
+ )
474
+ num_aliased_outs_that_are_not_multi_output_views = (
475
+ num_aliased_outs - num_multi_output_view_outs
476
+ )
477
+ if (
478
+ grad_fn is not None
479
+ and num_aliased_outs_that_are_not_multi_output_views == 0
480
+ ):
481
+ # See Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
482
+ # In particular, given:
483
+ # def f(x):
484
+ # return list(x.unbind(0))
485
+ # The main reason we ordinarily try to regenerate these output aliases outside of the
486
+ # compiled autograd.Function is because if any of the outputs are later mutated,
487
+ # autograd needs to perform view-replay to regenerate them.
488
+ # However, autograd does not allow users to mutate multi-output views
489
+ # in any way that can change the autograd metadata of other aliases.
490
+ # So we hide this aliasing from autograd here.
491
+ log.debug(
492
+ "Encountered AOTAutograd case: differentiable outputs that \
493
+ alias each other from a multi-output view call"
494
+ )
495
+ output_type = OutputType.non_alias
496
+ elif is_input_tensor:
497
+ output_type = OutputType.is_input
498
+ else:
499
+ output_type = OutputType.alias_of_input
500
+ elif functional_tensor_storage_changed and id(o) in inp_tensor_ids:
501
+ # When there is a set_() on an input, we cannot rely on checking storages
502
+ # to detect if we are returning an input (since the inputs storage is different)
503
+ assert curr_storage is not None
504
+ base_idx = inp_storage_refs[curr_storage]
505
+ output_type = OutputType.is_input
506
+
507
+ # We only need to handle the intermediate base case when both
508
+ # the intermediate base and the output require gradients.
509
+ # See Note [AOT Autograd: outputs aliasing inputs or intermediates!]
510
+ elif o._base is not None and o.requires_grad and o._base.requires_grad:
511
+ num_aliased_outs = out_tensor_alias_counts[curr_storage]
512
+ num_multi_output_view_outs = (
513
+ num_aliased_tensors_that_are_multi_output_views[curr_storage]
514
+ )
515
+ num_aliased_outs_that_are_not_multi_output_views = (
516
+ num_aliased_outs - num_multi_output_view_outs
517
+ )
518
+ # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
519
+ if (
520
+ out_tensor_alias_counts[curr_storage] == 1
521
+ or num_aliased_outs_that_are_not_multi_output_views <= 1
522
+ ):
523
+ # Note [Intermediate Bases Optimization]
524
+ # Normally if we have an output that aliases an intermediate,
525
+ # we need to add the extra "intermediate base" logic further down
526
+ # to prevent autograd from yelling at us if the user later tries to
527
+ # mutate that output.
528
+ # However, the common case here is if we have an output that aliases an intermediate,
529
+ # but doesn't alias any other outputs.
530
+ # In that case, autograd shouldn't have to worry about the aliasing at all
531
+ # (if that output is mutated, there are no other live aliases for autograd to worry about).
532
+ # The "intermediate bases" can hurt inductor perf by forcing more variables to become outputs.
533
+ # So as an optimization, we won't do intermediate base handling in this case.
534
+ # Instead, we'll hide the aliasing from autograd using aten._unsafe_view().
535
+ if (
536
+ out_tensor_alias_counts[curr_storage] != 1
537
+ and num_aliased_outs_that_are_not_multi_output_views <= 1
538
+ ):
539
+ log.debug(
540
+ "Encountered AOTAutograd case: differentiable outputs that alias each other \
541
+ from a multi-output view call"
542
+ )
543
+ output_type = OutputType.unsafe_view_alias
544
+ base_idx = None
545
+ else:
546
+ # First, check if o's ._base is an existing output
547
+ maybe_existing_out_idx = out_tensor_ids.get(id(o._base), None)
548
+ if maybe_existing_out_idx is not None:
549
+ # Special case where the output is an alias of a graph intermediate, but that intermediate
550
+ # is itself also a user output.
551
+ output_type = (
552
+ OutputType.alias_of_intermediate_base_is_user_output
553
+ )
554
+ base_idx = maybe_existing_out_idx
555
+ else:
556
+ # Next, check if o's ._base is an intermediate base that we already returned
557
+ maybe_existing_base_output_idx = (
558
+ intermediate_base_tensor_id_to_output_idx.get(
559
+ id(o._base), None
560
+ )
561
+ )
562
+ if maybe_existing_base_output_idx is not None:
563
+ output_type = OutputType.alias_of_intermediate
564
+ base_idx = maybe_existing_base_output_idx
565
+ else:
566
+ # Otherwise, take o._base and explicitly return it as an output in the compiled graph
567
+ new_out_idx = len(intermediate_bases)
568
+ base_idx = new_out_idx
569
+ # Indicate to the logic later on (when we trace the joint)
570
+ # that this particular output should get it's ._base appended to the forward graph outputs
571
+ output_type = (
572
+ OutputType.alias_of_intermediate_save_as_output
573
+ )
574
+ intermediate_base_tensor_id_to_output_idx[
575
+ id(o._base)
576
+ ] = new_out_idx
577
+ intermediate_bases.append(o._base)
578
+ elif (
579
+ # See https://github.com/pytorch/pytorch/issues/100348 for this case.
580
+ # This protects against the specific case where a user fn returns (output, output.detach())
581
+ out_tensor_alias_counts[curr_storage] > 1
582
+ and len(outs_with_identical_metadata_that_require_grad) > 0
583
+ and not o.requires_grad
584
+ ):
585
+ # In theory we could use any of these tensors to regenerate the aliased outputs from,
586
+ # since they all alias each other and have identical metatadata
587
+ out_alias = outs_with_identical_metadata_that_require_grad[0]
588
+ existing_out_idx = out_tensor_ids[id(out_alias)]
589
+ output_type = OutputType.alias_of_intermediate_base_is_user_output
590
+ base_idx = existing_out_idx
591
+ else:
592
+ output_type = OutputType.non_alias
593
+ base_idx = None
594
+
595
+ if isinstance(o, torch.Tensor):
596
+ dynamic_dims = {
597
+ i for i, s in enumerate(o.shape) if not is_concrete_int(s)
598
+ }
599
+ else:
600
+ dynamic_dims = None
601
+
602
+ # Save the current FunctionalTensor output.
603
+ #
604
+ # This will be used at runtime for reconstructing output views from
605
+ # their respective base tensors.
606
+ #
607
+ # The FunctionalTensor will be saved if one of the 2 conditions below
608
+ # is true:
609
+ functional_tensor = None
610
+ if (
611
+ # 1. If the output_type is either of:
612
+ # (i) alias_of_intermediate;
613
+ # (ii) alias_of_intermediate_save_as_output; or
614
+ # (iii) alias_of_intermediate_base_is_user_output.
615
+ #
616
+ # No need to worry about in-place view operations here, since
617
+ # this functionalization step elimitates mutations.
618
+ #
619
+ # i.e. we have access to the actual base tensor, before the
620
+ # in-place operation was applied.
621
+ output_type
622
+ in (
623
+ OutputType.alias_of_intermediate,
624
+ OutputType.alias_of_intermediate_save_as_output,
625
+ OutputType.alias_of_intermediate_base_is_user_output,
626
+ )
627
+ ) or (
628
+ # 2. If the output_type is alias_of_input, and no in-place view
629
+ # operationthe was run on the input (base tensor).
630
+ #
631
+ # In this case, we need to check for metadata mutation because
632
+ # the runtime explicitly reconstructs the inputs, before actually
633
+ # reconstructing the outputs. Due to in-place view operations, the
634
+ # fully reconstructed input may not be this output base tensor
635
+ # anymore.
636
+ output_type == OutputType.alias_of_input
637
+ and base_idx is not None
638
+ and not input_info[base_idx].mutates_metadata
639
+ ):
640
+ if isinstance(o, FunctionalTensor):
641
+ functional_tensor = FunctionalTensorMetadataEq(o.elem)
642
+
643
+ out_info = OutputAliasInfo(
644
+ output_type=output_type,
645
+ raw_type=type(o),
646
+ base_idx=base_idx,
647
+ dynamic_dims=dynamic_dims,
648
+ requires_grad=isinstance(o, torch.Tensor) and o.requires_grad,
649
+ functional_tensor=functional_tensor,
650
+ )
651
+ output_info.append(out_info)
652
+
653
+ # See Note [AOT Autograd: Views to avoid tangents aliasing inputs]
654
+ def view_avoid_dupes_with_primals(t):
655
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
656
+ return transform_subclass(
657
+ t, lambda _, inner_t: view_avoid_dupes_with_primals(inner_t)
658
+ )
659
+ if isinstance(t, Tensor):
660
+ return t.view(t.shape)
661
+ return t
662
+
663
+ # This analysis function returns *only* the outputs that are meant to be tangents to the backwards.
664
+ # Anything that aliases (inputs returned in the fw due to metadata mutations, or outputs that alias inputs/intermediates)
665
+ # are *regenerated* later, and not used directly in the autograd graph
666
+ def _plain_fake_tensor_like_subclass(x):
667
+ with detect_fake_mode():
668
+ return torch.empty(
669
+ x.shape, dtype=x.dtype, device=x.device, layout=x.layout
670
+ )
671
+
672
+ def _is_subclass_mutated_input_tangent_always_subclass(inp):
673
+ return (
674
+ isinstance(inp, torch.nested._internal.nested_tensor.NestedTensor)
675
+ or torch._functorch.config.disable_guess_zero_tangent_for_mutated_input_subclass
676
+ )
677
+
678
+ f_input_tangents = [
679
+ # Note: [AOTAutograd Tangent Subclassness for mutated inputs]
680
+ # Generally when creating tangents to trace with, we assume that tangents will have
681
+ # the same subclass-ness as their forward outs
682
+ # however: for tangents that correspond to input mutations, in practice it is more likely
683
+ # that these tangents will be plain tensors of zeros at runtime, so we tweak our guess
684
+ # to assume that these tangents should always be plaint tensors.
685
+ # Example:
686
+ # def f(x):
687
+ # x.mul_(2)
688
+ # return x + 1
689
+ # out = f(x)
690
+ # out.sum().backward()
691
+ # In the above code, we will have a tangent "x_updated_tangent",
692
+ # which will be a plain tensor of zeros, *unless* x is used in some compute after executing f
693
+ #
694
+ # However, there are exceptions to this logic. If a view is created from mutated input and is used in backward,
695
+ # The tangent for this subclass input will be a subclass tensor.
696
+ # Example:
697
+ # def f(a, b):
698
+ # a.mul_(2)
699
+ # b.mul_(3)
700
+ # return b.view(b.shape), a + b
701
+ # a_out, b_out = f(..., Subclass)
702
+ # (a * b).sum().backward()
703
+ #
704
+ # We can not deduce it easily now, so introducing a debug config to be able to turn off this for specific cases.
705
+ # NJT gurantees to have its tangent as NJT, because it has dedicated integration in Autograd
706
+ # See torch/csrc/autograd/python_function.cpp, use_zeros_like.
707
+ (
708
+ _plain_fake_tensor_like_subclass(inp)
709
+ if is_traceable_wrapper_subclass(inp)
710
+ and not _is_subclass_mutated_input_tangent_always_subclass(inp)
711
+ else inp
712
+ )
713
+ for inp, info in zip(flat_f_args, input_info)
714
+ if info.mutation_type == MutationType.MUTATED_OUT_GRAPH
715
+ and info.mutates_data
716
+ and info.requires_grad
717
+ ]
718
+ f_output_tangents = [
719
+ o
720
+ for o, info in zip(flat_f_outs, output_info)
721
+ if info.output_type
722
+ in [
723
+ OutputType.non_alias,
724
+ OutputType.unsafe_view_alias,
725
+ OutputType.custom_function_view,
726
+ ]
727
+ and issubclass(info.raw_type, torch.Tensor)
728
+ and info.requires_grad
729
+ ]
730
+ # intermediate bases are also included in the backward graph
731
+ f_tangents = f_input_tangents + f_output_tangents + intermediate_bases
732
+ traced_tangents = pytree.tree_map(from_fun, f_tangents)
733
+ traced_tangents = pytree.tree_map(
734
+ view_avoid_dupes_with_primals, traced_tangents
735
+ )
736
+
737
+ traced_tangents = [
738
+ coerce_tangent_and_suggest_memory_format(tt)[0]
739
+ for i, tt in enumerate(traced_tangents)
740
+ ]
741
+ nonlocal static_input_indices
742
+ static_input_indices = static_input_indices or []
743
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
744
+ passed_indices = set(static_input_indices)
745
+ static_input_indices = [
746
+ i
747
+ for i, arg in enumerate(flat_args)
748
+ if (isinstance(arg, torch.nn.Parameter) or i in passed_indices)
749
+ ]
750
+
751
+ static_input_logger.debug(
752
+ "static input indices metadata analysis: %s", static_input_indices
753
+ )
754
+
755
+ f_mutated_inputs = [
756
+ inp
757
+ for inp, info in zip(flat_f_args, input_info)
758
+ if info.mutation_type == MutationType.MUTATED_OUT_GRAPH
759
+ ]
760
+ f_metadata_mutated_inputs = [
761
+ inp for inp, info in zip(flat_f_args, input_info) if info.mutates_metadata
762
+ ]
763
+ # This logic (annoyingly) re-figures out exactly what the outputs to the compiled fw graph will be.
764
+ # When handling subclasses, we need info about **all** outputs of compiled forward graph,
765
+ # so we know precisely which graph outputs to wrap back into tensor subclasses
766
+ # Ideally we would refactor this so not have an is_train flag, and have the separate
767
+ # inference and training paths decide which inputs/output to ask for subclass info on.
768
+ # However, we currently stash indexing information on each SubclassMeta about its order
769
+ # in the graph outputs list.
770
+ f_fw_graph_outs = list(flat_f_outs)
771
+ if is_train or not keep_input_mutations:
772
+ f_fw_graph_outs = f_mutated_inputs + f_fw_graph_outs
773
+ else:
774
+ # even when "keep_input_mutations" is True,
775
+ # we never keep metadata-only mutations in the fw graph
776
+ f_fw_graph_outs = f_metadata_mutated_inputs + f_fw_graph_outs
777
+ if is_train:
778
+ f_fw_graph_outs = f_fw_graph_outs + intermediate_bases
779
+ fw_graph_outs = pytree.tree_map(from_fun, f_fw_graph_outs)
780
+
781
+ grad_enabled_mutation = None
782
+ if torch.is_grad_enabled() != prior_grad_enabled:
783
+ grad_enabled_mutation = torch.is_grad_enabled()
784
+ torch.set_grad_enabled(
785
+ prior_grad_enabled
786
+ ) # Restore the prior state after tracing it
787
+ log.debug(
788
+ (
789
+ "grad_mode mutation encountered in graph. "
790
+ "Will emit mutation epilogue, to set grad_mode=%s"
791
+ ),
792
+ grad_enabled_mutation,
793
+ )
794
+
795
+ metadata = ViewAndMutationMeta(
796
+ input_info=input_info,
797
+ output_info=output_info,
798
+ num_intermediate_bases=len(intermediate_bases),
799
+ keep_input_mutations=keep_input_mutations,
800
+ traced_tangents=traced_tangents,
801
+ subclass_inp_meta=create_subclass_meta(flat_args),
802
+ subclass_fw_graph_out_meta=create_subclass_meta(fw_graph_outs),
803
+ subclass_tangent_meta=create_subclass_meta(
804
+ traced_tangents, count_symints=False, with_memory_format=True
805
+ ),
806
+ is_train=is_train,
807
+ grad_enabled_mutation=grad_enabled_mutation,
808
+ static_input_indices=static_input_indices,
809
+ tokens=mode._tokens,
810
+ )
811
+ return metadata
812
+
813
+ return inner
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/dispatch_and_compile_graph.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This module dispatches the graphs to either the forward-only or joint compilation
4
+ pathways, taking into account the AOTConfig and the collected ViewAndMutationMetadata.
5
+ """
6
+
7
+ import dataclasses
8
+ from typing import Any, Optional
9
+
10
+ import torch
11
+ import torch.utils._pytree as pytree
12
+ import torch.utils.dlpack
13
+ from torch import Tensor
14
+ from torch._dispatch.python import enable_python_dispatcher
15
+ from torch._dynamo.utils import detect_fake_mode, lazy_format_graph_code
16
+ from torch._logging import getArtifactLogger, trace_structured
17
+ from torch._subclasses.functional_tensor import FunctionalTensorMode
18
+ from torch.fx.experimental.proxy_tensor import make_fx
19
+ from torchgen.utils import dataclass_repr
20
+
21
+ from .. import config
22
+ from .functional_utils import (
23
+ assert_functional_graph,
24
+ propagate_input_mutation_stacktraces,
25
+ )
26
+ from .schemas import AOTConfig, SubclassMeta, ViewAndMutationMeta
27
+ from .traced_function_transforms import (
28
+ aot_dispatch_subclass,
29
+ create_functionalized_fn,
30
+ create_joint,
31
+ fn_input_mutations_to_outputs,
32
+ fn_prepped_for_autograd,
33
+ handle_effect_tokens_fn,
34
+ )
35
+ from .utils import (
36
+ copy_fwd_metadata_to_bw_nodes,
37
+ register_buffer_assignment_hook,
38
+ root_module_when_exporting_non_strict,
39
+ unlift_tokens,
40
+ )
41
+
42
+
43
+ aot_graphs_log = getArtifactLogger(__name__, "aot_graphs")
44
+
45
+
46
+ def _create_graph(f, args, *, aot_config: AOTConfig) -> torch.fx.GraphModule:
47
+ # FunctionalTensorMode must be enabled here.
48
+ # See Note [Accessing .grad_fn on FunctionalTensor]
49
+ with enable_python_dispatcher(), FunctionalTensorMode(
50
+ pre_dispatch=aot_config.pre_dispatch,
51
+ export=aot_config.is_export,
52
+ # Allow token discovery for joint fn tracing as tokens can be used in backward.
53
+ _allow_token_discovery=True,
54
+ ):
55
+ fx_g = make_fx(
56
+ f,
57
+ decomposition_table=aot_config.decompositions,
58
+ record_module_stack=True,
59
+ pre_dispatch=aot_config.pre_dispatch,
60
+ )(*args)
61
+
62
+ return fx_g
63
+
64
+
65
+ # TODO: Refactor the following code so detach() persists item_memo
66
+ def _detach_and_copy_item_memo(t):
67
+ detached_t = t.detach()
68
+ if hasattr(t, "item_memo"):
69
+ detached_t.item_memo = t.item_memo
70
+ return detached_t
71
+
72
+
73
+ def aot_dispatch_base_graph(
74
+ flat_fn,
75
+ flat_args: list[Tensor],
76
+ aot_config: AOTConfig,
77
+ *,
78
+ fw_metadata: ViewAndMutationMeta,
79
+ ) -> tuple[torch.fx.GraphModule, list[Any], Optional[SubclassMeta]]:
80
+ # aot_dispatch_base requires functionalization, but doesn't need to handle as many cases as the autograd case.
81
+ # The cases that aot_dispatch_base doesn't need to handle include:
82
+ # - outputs that are aliases of graph intermediates
83
+ # - outputs that are aliases of graph inputs
84
+ # While cases that it does need to handle include:
85
+ # - input mutations (including when inputs are aliases of each other)
86
+ # - input metadata mutations
87
+ fn_to_trace = fn_input_mutations_to_outputs(
88
+ flat_fn,
89
+ fw_metadata,
90
+ keep_data_input_mutations=aot_config.keep_inference_input_mutations,
91
+ )
92
+
93
+ fn_to_trace, updated_flat_args = create_functionalized_fn(
94
+ fn_to_trace,
95
+ flat_args,
96
+ meta=fw_metadata,
97
+ aot_config=aot_config,
98
+ trace_joint=False,
99
+ )
100
+
101
+ # TODO: replace with AOTDispatchSubclassWrapper once we refactor
102
+ # fn_input_mutations_to_outputs and create_functionalized_fn
103
+ # into CompilerWrappers.
104
+ (
105
+ fn_to_trace,
106
+ updated_flat_args_subclasses_desugared,
107
+ maybe_subclass_meta,
108
+ ) = aot_dispatch_subclass(
109
+ fn_to_trace,
110
+ updated_flat_args,
111
+ is_joint_structure=False,
112
+ meta=fw_metadata,
113
+ fw_only=flat_fn,
114
+ )
115
+
116
+ (fn_to_trace, updated_flat_args_subclasses_desugared) = handle_effect_tokens_fn(
117
+ fn_to_trace,
118
+ updated_flat_args_subclasses_desugared,
119
+ meta=fw_metadata,
120
+ trace_joint=False,
121
+ )
122
+
123
+ aot_graphs_log.debug(
124
+ "aot_config id: %s, fw_metadata=%s,subclass_metadata=%s",
125
+ str(aot_config.aot_id),
126
+ str(fw_metadata),
127
+ str(maybe_subclass_meta),
128
+ )
129
+
130
+ # We track buffer assignments when exporting in non-strict mode.
131
+ # (In contrast, strict mode errors on any attribute assignment.)
132
+ mod_when_exporting_non_strict = root_module_when_exporting_non_strict(flat_fn)
133
+ if aot_config.is_export and mod_when_exporting_non_strict is not None:
134
+ # For any buffer that is assigned, we want to associate it to the final proxy node
135
+ # that it is assigned to. This node can then be added as a buffer mutation output.
136
+ assigned_buffers: dict[str, str] = {}
137
+ hook = register_buffer_assignment_hook(
138
+ mod_when_exporting_non_strict, assigned_buffers
139
+ )
140
+
141
+ fake_mode = detect_fake_mode()
142
+ if fake_mode:
143
+ saved_updated_flat_args_subclasses_desugared = pytree.tree_map_only(
144
+ torch.Tensor,
145
+ _detach_and_copy_item_memo,
146
+ updated_flat_args_subclasses_desugared,
147
+ )
148
+ else:
149
+ saved_updated_flat_args_subclasses_desugared = pytree.tree_map_only(
150
+ torch.Tensor, lambda t: t.detach(), updated_flat_args_subclasses_desugared
151
+ )
152
+
153
+ fw_module = _create_graph(
154
+ fn_to_trace,
155
+ updated_flat_args_subclasses_desugared,
156
+ aot_config=aot_config,
157
+ )
158
+
159
+ if aot_config.is_export and mod_when_exporting_non_strict is not None:
160
+ # We update metadata to consider any assigned buffers as buffer mutations.
161
+ i = len(dict(mod_when_exporting_non_strict.named_parameters()))
162
+ for name, _ in mod_when_exporting_non_strict.named_buffers():
163
+ if name in assigned_buffers and not fw_metadata.input_info[i].mutates_data: # type: ignore[possibly-undefined]
164
+ fw_metadata.input_info[i] = dataclasses.replace(
165
+ fw_metadata.input_info[i], mutates_data=True
166
+ )
167
+ fw_metadata.num_mutated_inp_runtime_indices += 1
168
+ i += 1
169
+
170
+ # We add nodes corresponding to buffer assignments as output nodes in the graph.
171
+ add_nodes = []
172
+ output_node = list(fw_module.graph.nodes)[-1]
173
+ for name in assigned_buffers.values(): # type: ignore[possibly-undefined]
174
+ for node in fw_module.graph.nodes:
175
+ if node.name == name:
176
+ add_nodes.append(node)
177
+ node.users[output_node] = None
178
+ output_node.args = ((*add_nodes, *output_node.args[0]),)
179
+
180
+ hook.remove() # type: ignore[possibly-undefined]
181
+
182
+ # As long as we opted to remove input mutations, then
183
+ # there should be *NO* mutating ops in the graph at this point.
184
+ copy_count = assert_functional_graph(fw_module.graph)
185
+ fw_module.graph.eliminate_dead_code()
186
+ fw_module.recompile()
187
+
188
+ copy_count2 = assert_functional_graph(fw_module.graph)
189
+ propagate_input_mutation_stacktraces(fw_module.graph)
190
+
191
+ # See Note [Side-Effectful Tokens in AOTAutograd]
192
+ num_tokens = len(fw_metadata.tokens)
193
+ if num_tokens != 0 and config.unlift_effect_tokens:
194
+ unlift_tokens(fw_module, fw_metadata, aot_config)
195
+ saved_updated_flat_args_subclasses_desugared = (
196
+ saved_updated_flat_args_subclasses_desugared[num_tokens:]
197
+ )
198
+
199
+ assert copy_count == copy_count2
200
+
201
+ if aot_config.enable_log:
202
+ aot_graphs_log.info(
203
+ "%s",
204
+ lazy_format_graph_code(
205
+ "Forward graph",
206
+ fw_module,
207
+ aot_config.aot_id,
208
+ include_stride=True,
209
+ include_device=True,
210
+ colored=True,
211
+ ),
212
+ )
213
+
214
+ trace_structured(
215
+ "artifact",
216
+ metadata_fn=lambda: {
217
+ "name": "aot_forward_graph_fw_metadata",
218
+ "encoding": "string",
219
+ },
220
+ payload_fn=lambda: dataclass_repr(fw_metadata),
221
+ )
222
+ if maybe_subclass_meta is not None:
223
+ trace_structured(
224
+ "artifact",
225
+ metadata_fn=lambda: {
226
+ "name": "aot_forward_graph_fw_subclass_metadata",
227
+ "encoding": "string",
228
+ },
229
+ payload_fn=lambda: dataclass_repr(maybe_subclass_meta),
230
+ )
231
+
232
+ trace_structured(
233
+ "aot_inference_graph",
234
+ payload_fn=lambda: fw_module.print_readable(
235
+ print_output=False, include_stride=True, include_device=True
236
+ ),
237
+ )
238
+
239
+ # TODO: should factor this into a separate function for export that always only returns just the graph.
240
+ if aot_config.is_export:
241
+ assert (
242
+ maybe_subclass_meta is None
243
+ ), "aot_export_module does not support tensor subclass inputs for now."
244
+ return fw_module, saved_updated_flat_args_subclasses_desugared, maybe_subclass_meta
245
+
246
+
247
+ # Has the precondition that there
248
+ # are no duplicate arguments in flat_args (e.g., the same Tensor
249
+ # object never shows up twice. However, two tensor inputs MAY alias
250
+ # the same storage, so long as they have separate TensorImpls.)
251
+ def aot_dispatch_autograd_graph(
252
+ flat_fn,
253
+ flat_args: list[Any],
254
+ aot_config: AOTConfig,
255
+ *,
256
+ fw_metadata: ViewAndMutationMeta,
257
+ ) -> tuple[torch.fx.GraphModule, tuple[list[Any], list[Any]], Optional[SubclassMeta]]:
258
+ # traced_tangents corresponds to the set of outputs in the traced forward that should get grad_outputs in the traced backward.
259
+ # It includes outputs of the original forward, *and* any updated inputs due to input mutations.
260
+ # However, it does *not* include any outputs that are aliases of inputs or intermediates, or any metadata-only input mutations.
261
+ joint_inputs = (flat_args, fw_metadata.traced_tangents)
262
+
263
+ fn_prepared_for_autograd = fn_prepped_for_autograd(
264
+ flat_fn,
265
+ fw_metadata,
266
+ )
267
+ joint_fn_to_trace = create_joint(fn_prepared_for_autograd, aot_config=aot_config)
268
+
269
+ joint_fn_to_trace, updated_joint_inputs = create_functionalized_fn(
270
+ joint_fn_to_trace,
271
+ joint_inputs,
272
+ meta=fw_metadata,
273
+ aot_config=aot_config,
274
+ trace_joint=True,
275
+ )
276
+
277
+ # TODO: replace with AOTDispatchSubclassWrapper once we refactor
278
+ # fn_input_mutations_to_outputs and create_functionalized_fn
279
+ # into CompilerWrappers.
280
+ subclass_tracing_info = aot_dispatch_subclass(
281
+ joint_fn_to_trace,
282
+ updated_joint_inputs,
283
+ is_joint_structure=True,
284
+ meta=fw_metadata,
285
+ fw_only=flat_fn,
286
+ )
287
+
288
+ joint_fn_to_trace = subclass_tracing_info.plain_tensor_trace_fn
289
+ updated_joint_inputs = subclass_tracing_info.plain_tensor_args
290
+
291
+ (joint_fn_to_trace, updated_joint_inputs) = handle_effect_tokens_fn(
292
+ joint_fn_to_trace,
293
+ updated_joint_inputs,
294
+ meta=fw_metadata,
295
+ trace_joint=True,
296
+ )
297
+
298
+ # When we call _create_graph, this may mutate the metadata of joint
299
+ # inputs. But callers are expecting to get the original joint inputs. So
300
+ # we make aliases of all the inputs to make sure we have a copy that
301
+ # doesn't get modified.
302
+ #
303
+ # This destroys requires_grad/grad_fn information. However, backends
304
+ # beneath AOTAutograd are indifferent to this information, so it doesn't
305
+ # matter.
306
+
307
+ fake_mode = detect_fake_mode()
308
+ if fake_mode:
309
+ saved_updated_joint_inputs = pytree.tree_map_only(
310
+ torch.Tensor, _detach_and_copy_item_memo, updated_joint_inputs
311
+ )
312
+ else:
313
+ saved_updated_joint_inputs = pytree.tree_map_only(
314
+ torch.Tensor, lambda t: t.detach(), updated_joint_inputs
315
+ )
316
+ maybe_subclass_meta = subclass_tracing_info.maybe_subclass_meta
317
+
318
+ fx_g = _create_graph(joint_fn_to_trace, updated_joint_inputs, aot_config=aot_config)
319
+
320
+ # There should be *NO* mutating ops in the graph at this point.
321
+ assert_functional_graph(fx_g.graph)
322
+
323
+ # Redundant with the check above, but worth having in case tracing introduced
324
+ # a fake tensor. Unlikely.
325
+ # See Note: [Fake Modules and AOTAutograd]
326
+ torch._dynamo.utils.assert_no_fake_params_or_buffers(fx_g)
327
+ fx_g.graph.eliminate_dead_code()
328
+ copy_fwd_metadata_to_bw_nodes(fx_g)
329
+ fx_g.recompile()
330
+
331
+ # TODO: in AOTAutograd, we create metadata like _indices_of_inps_to_detach to detect
332
+ # when we need to manually detach() some inputs in the forward.
333
+ # Higher order ops might eventually need to do the same.
334
+ if aot_config.is_export:
335
+ assert (
336
+ maybe_subclass_meta is None
337
+ ), "aot_export_module does not support tensor subclass inputs for now."
338
+ return fx_g, saved_updated_joint_inputs, maybe_subclass_meta
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/functional_utils.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This file contains utilities related to functionalization in AOTAutograd:
4
+ 1. converting to/from functional tensors
5
+ 2. detecting Tensor mutations - both metadata and Tensor value
6
+ 3. regenerating/replaying views from their base
7
+ 4. checking if a graph is functional i.e. whether it contains any mutation ops
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Optional
13
+
14
+ import torch
15
+ from torch import Tensor
16
+ from torch._logging import getArtifactLogger
17
+ from torch._subclasses.fake_tensor import FakeTensor
18
+ from torch._subclasses.functional_tensor import FunctionalTensor
19
+ from torch._subclasses.meta_utils import is_sparse_any
20
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq, SymIntEqByExpr
21
+ from torch.multiprocessing.reductions import StorageWeakRef
22
+ from torch.utils._python_dispatch import (
23
+ is_traceable_wrapper_subclass,
24
+ transform_subclass,
25
+ )
26
+
27
+
28
+ aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph")
29
+
30
+
31
+ def to_fun(t):
32
+ if isinstance(t, Tensor):
33
+ if is_traceable_wrapper_subclass(t):
34
+ # See Note [Functionalization always runs last]
35
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
36
+ # goes at the bottom.
37
+ # recurse here, so we can support nested wrapper subclasses
38
+ out = transform_subclass(t, lambda _, inner_t: to_fun(inner_t))
39
+ torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined]
40
+ return out
41
+ else:
42
+ return FunctionalTensor.to_functional(t)
43
+ else:
44
+ return t
45
+
46
+
47
+ def sync_functional_tensor(t):
48
+ if is_traceable_wrapper_subclass(t):
49
+ attrs, _ctx = t.__tensor_flatten__() # type: ignore[attr-defined]
50
+ for attr in attrs:
51
+ sync_functional_tensor(getattr(t, attr))
52
+ else:
53
+ torch._sync(t)
54
+
55
+
56
+ # When subclasses are involved, t here will usually look something like:
57
+ # SubclassA(SubclassB(FunctionalTensor(_to_fun_tensor(FakeTensor))))
58
+ def from_fun(t):
59
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
60
+ # See Note [Functionalization always runs last]
61
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
62
+ # goes at the bottom.
63
+ # recurse here, so we can support nested wrapper subclasses
64
+ out = transform_subclass(t, lambda _, inner_t: from_fun(inner_t))
65
+ torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined]
66
+ return out
67
+
68
+ if not isinstance(t, FunctionalTensor):
69
+ # quick sanity assert
70
+ if isinstance(t, torch.Tensor):
71
+ assert not torch._is_functional_tensor(t) # type: ignore[attr-defined]
72
+ return t
73
+ sync_functional_tensor(t)
74
+ return torch._from_functional_tensor(t.elem)
75
+
76
+
77
+ def is_fun(t):
78
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
79
+ # See Note [Functionalization always runs last]
80
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
81
+ # goes at the bottom.
82
+ # recurse here, so we can support nested wrapper subclasses
83
+ t_attrs, _ = t.__tensor_flatten__() # type: ignore[attr-defined]
84
+ t_inners = [getattr(t, attr) for attr in t_attrs]
85
+ any_fun = any(is_fun(x) for x in t_inners)
86
+ all_fun = all(is_fun(x) for x in t_inners)
87
+ assert any_fun == all_fun
88
+ return any_fun
89
+
90
+ return isinstance(t, FunctionalTensor)
91
+
92
+
93
+ # t here is either
94
+ # (1) A FunctionalTensor(_to_functional_tensor(FakeTensor))
95
+ # (2) A traceable tensor subclass that holds a FunctionalTensor
96
+ # (3) Not a tensor
97
+ def has_data_mutation(t):
98
+ if is_traceable_wrapper_subclass(t):
99
+ attrs, _ = t.__tensor_flatten__()
100
+ # A tensor subclass was updated if any of its inner elements were updated
101
+ return any(has_data_mutation(getattr(t, attr)) for attr in attrs)
102
+ else:
103
+ if isinstance(t, torch.Tensor):
104
+ assert isinstance(t, FunctionalTensor)
105
+ return torch._functionalize_has_data_mutation(t.elem) # type: ignore[attr-defined]
106
+ return False
107
+
108
+
109
+ def are_all_mutations_hidden_from_autograd(t):
110
+ if is_traceable_wrapper_subclass(t):
111
+ attrs, _ = t.__tensor_flatten__()
112
+ # If all inner elements are mutations hidden from autograd, then it is a mutation hidden from autograd.
113
+ return all(
114
+ are_all_mutations_hidden_from_autograd(getattr(t, attr)) for attr in attrs
115
+ )
116
+ elif isinstance(t, torch.Tensor):
117
+ assert isinstance(t, FunctionalTensor)
118
+ return torch._functionalize_are_all_mutations_hidden_from_autograd(t.elem)
119
+ else:
120
+ return False
121
+
122
+
123
+ def are_all_mutations_under_no_grad_or_inference_mode(t):
124
+ if is_traceable_wrapper_subclass(t):
125
+ attrs, _ = t.__tensor_flatten__()
126
+ return all(
127
+ are_all_mutations_under_no_grad_or_inference_mode(getattr(t, attr))
128
+ for attr in attrs
129
+ )
130
+ else:
131
+ assert isinstance(t, FunctionalTensor)
132
+ return torch._functionalize_are_all_mutations_under_no_grad_or_inference_mode(
133
+ t.elem
134
+ )
135
+
136
+
137
+ def was_inductor_storage_resized(t):
138
+ if is_traceable_wrapper_subclass(t):
139
+ attrs, _ = t.__tensor_flatten__()
140
+ if any(was_inductor_storage_resized(getattr(t, attr)) for attr in attrs):
141
+ raise RuntimeError(
142
+ f"storage resizing is not supported on tensor subclass: {type(t)}"
143
+ )
144
+ elif not isinstance(t, torch.Tensor):
145
+ return False
146
+ else:
147
+ assert isinstance(t, FunctionalTensor)
148
+ return torch._functionalize_was_inductor_storage_resized(t.elem)
149
+
150
+
151
+ # f_arg here is either
152
+ # (1) A FunctionalTensor(_to_functional_tensor(FakeTensor))
153
+ # (2) A traceable tensor subclass that holds a FunctionalTensor
154
+ # (3) Not a tensor
155
+ # Assumption: arg promises to be the "original" tensor wrapped by f_arg
156
+ # Note: "storage mutations" coming from set_() are a type of metadata mutation. So:
157
+ # - check_only_storage_mutation=True: only return true if there was a storage mutation
158
+ # - check_only_storage_mutation=Flse: return true if there was any metadata mutation (including a storage mutation)
159
+ def has_metadata_mutation(f_arg, arg, *, check_only_storage_mutation: bool):
160
+ if is_traceable_wrapper_subclass(f_arg):
161
+ attrs, _ = f_arg.__tensor_flatten__()
162
+ # A tensor subclass was updated if any of its inner elements were updated
163
+ f_inner_ts = [getattr(f_arg, attr) for attr in attrs]
164
+ inner_ts = [getattr(arg, attr) for attr in attrs]
165
+ return any(
166
+ has_metadata_mutation(
167
+ f_inner_t,
168
+ inner_t,
169
+ check_only_storage_mutation=check_only_storage_mutation,
170
+ )
171
+ for f_inner_t, inner_t in zip(f_inner_ts, inner_ts)
172
+ )
173
+ else:
174
+ if not isinstance(f_arg, torch.Tensor):
175
+ assert not isinstance(arg, torch.Tensor)
176
+ return False
177
+ assert isinstance(f_arg, FunctionalTensor)
178
+ assert isinstance(arg, FakeTensor)
179
+
180
+ arg_after = torch._from_functional_tensor(f_arg.elem)
181
+ # This is true if the current tensor experienced at least one set_() call
182
+ maybe_storage_changed = torch._functionalize_was_storage_changed(f_arg.elem) # type: ignore[attr-defined]
183
+ # However, multiple set_() calls can cancel out. So we also check whether the
184
+ # storage of the tensor has changed.
185
+ # Note: if an input experienced two set_() calls that cancel out, **and**
186
+ # it experiences an data mutation, we pessimistically think that the set_()
187
+ # call is necessary here. We could in theory fix this, but this will
188
+ # hopefully never happen in user code, and is not needed for fsdp.
189
+ if is_sparse_any(arg):
190
+ # TODO:add sparse tensors support to functionalization
191
+ same_storages = False
192
+ else:
193
+ same_storages = StorageWeakRef(arg.untyped_storage()) == StorageWeakRef(
194
+ arg_after.untyped_storage()
195
+ )
196
+ has_storage_metadata_mutation = maybe_storage_changed and not same_storages
197
+ if check_only_storage_mutation:
198
+ return has_storage_metadata_mutation
199
+
200
+ # storage metadata mutation is a type of metadata mutation, so return true if we saw one
201
+ if has_storage_metadata_mutation:
202
+ return True
203
+
204
+ maybe_metadata_mutated = torch._functionalize_has_metadata_mutation(f_arg.elem) # type: ignore[attr-defined]
205
+ # This is true if the current tensor experienced at least one metadata mutation.
206
+ # So if false, we know there was no metadata mutation
207
+ if not maybe_metadata_mutated:
208
+ return False
209
+
210
+ # However, multi metadata mutations can cancel out.
211
+ # So we also check if the concrete sizes/strides on the tensor have changed.
212
+ same_sizes = arg.shape == arg_after.shape
213
+ same_strides = arg.stride() == arg_after.stride()
214
+ same_offsets = arg.storage_offset() == arg_after.storage_offset()
215
+ has_metadata_mutation_ = maybe_metadata_mutated and not (
216
+ same_sizes and same_strides and same_offsets
217
+ )
218
+ # We consider a tensor to have been metadata mutated if its storage was mutated through a set_() call.
219
+ return has_metadata_mutation_
220
+
221
+
222
+ def gen_alias_from_base(
223
+ aliased_base_tensor,
224
+ target_meta_tensor,
225
+ target_requires_grad,
226
+ target_functional_tensor: Optional[FunctionalTensorMetadataEq] = None,
227
+ *,
228
+ replay_views,
229
+ ):
230
+ # Patch the correct requires_grad field of the output tensor, depending on whether:
231
+ # (i) the reconstructed output (out) was came from a tensor that requires grad or not;
232
+ # and (ii) the concrete returned output does require grad or not.
233
+ def patch_requires_grad(out):
234
+ if aliased_base_tensor.requires_grad and not target_requires_grad:
235
+ out = out.detach()
236
+ elif not aliased_base_tensor.requires_grad and target_requires_grad:
237
+ out.requires_grad_(True)
238
+ return out
239
+
240
+ # If provided, use the target functional tensor for replaying the views.
241
+ #
242
+ # In summary, we use the fact that FunctionalTensorWrapper saves the view
243
+ # functions applied to itself (collected during functionalization) so as
244
+ # to replay them (view functions) on the aliased_base_tensor.
245
+ if (
246
+ replay_views
247
+ and target_functional_tensor is not None
248
+ and not torch._functionalize_is_symbolic(target_functional_tensor.tensor)
249
+ ):
250
+ functional_tensor = target_functional_tensor.tensor
251
+
252
+ out = torch._functionalize_apply_view_metas(
253
+ functional_tensor, aliased_base_tensor
254
+ )
255
+ # If re-applying the ViewMeta sequence succeeded, there should be no more
256
+ # problems going forward. We just check we got to the target shape and
257
+ # patch requires_grad flag.
258
+ assert out.shape == target_meta_tensor.shape, (
259
+ "incorrect out shape after application of ViewMeta sequence: "
260
+ f"{tuple(out.shape)} (actual) vs {tuple(target_meta_tensor.shape)} (expected)"
261
+ )
262
+ return patch_requires_grad(out)
263
+
264
+ # Try to do view-replay if possible.
265
+ # fall back to .as_strided() if we can't.
266
+ if target_meta_tensor._base is not None:
267
+ # The base that we want to replay our view off of might have a different shape than the view's original base.
268
+ b = target_meta_tensor._base
269
+ abt = aliased_base_tensor
270
+ # Don't unnecessarily call as_strided if nothing changed; as_strided's
271
+ # backward is poorly implemented and slow
272
+ if abt is not b and (
273
+ abt.size() != b.size()
274
+ or abt.stride() != b.stride()
275
+ or abt.storage_offset() != b.storage_offset()
276
+ ):
277
+ reshaped_base_tensor = aliased_base_tensor.as_strided(
278
+ b.size(), b.stride(), b.storage_offset()
279
+ )
280
+ else:
281
+ reshaped_base_tensor = aliased_base_tensor
282
+ out = target_meta_tensor._view_func(reshaped_base_tensor)
283
+ # This shape mismatch can happen due to a bug in inplace/view handling in autograd.
284
+ # Try putting a breakpoint here and running
285
+ # `test/functorch/test_aotdispatch TestAOTAutograd.test_output_all_alias_types`
286
+ # Also, https://github.com/pytorch/pytorch/issues/49825
287
+ #
288
+ # As a stopgap, we'll fall back to as_strided.
289
+ if out is not None and out.shape == target_meta_tensor.shape:
290
+ return patch_requires_grad(out)
291
+
292
+ size = target_meta_tensor.size()
293
+ stride = target_meta_tensor.stride()
294
+ storage_offset = target_meta_tensor.storage_offset()
295
+ if aliased_base_tensor.is_complex() and not target_meta_tensor.is_complex():
296
+ aliased_out = torch.view_as_real(aliased_base_tensor).as_strided(
297
+ size, stride, storage_offset
298
+ )
299
+ elif not aliased_base_tensor.is_complex() and target_meta_tensor.is_complex():
300
+ aliased_out = torch.view_as_complex(aliased_base_tensor).as_strided(
301
+ size, stride, storage_offset
302
+ )
303
+ else:
304
+ aliased_out = aliased_base_tensor.as_strided(size, stride, storage_offset)
305
+ # For outputs aliasing inputs, we need to check if the requires-gradness has changed.
306
+ aliased_out = patch_requires_grad(aliased_out)
307
+ # For outputs aliasing inputs, we need to check if the dtype has changed.
308
+ # as_strided() is the "most generic" view, but it does not cover cross-dtype views
309
+ if aliased_out.dtype != target_meta_tensor.dtype:
310
+ aliased_out = aliased_out.view(target_meta_tensor.dtype)
311
+ return aliased_out
312
+
313
+
314
+ def has_same_metadata(t1, t2):
315
+ return (
316
+ guard_or_false(sym_eq(t1.size(), t2.size()))
317
+ and guard_or_false(t1.layout == t2.layout)
318
+ and (
319
+ is_sparse_any(t1)
320
+ or (
321
+ guard_or_false(sym_eq(t1.stride(), t2.stride()))
322
+ and guard_or_false(t1.storage_offset() == t2.storage_offset())
323
+ )
324
+ )
325
+ and t1.is_conj() == t2.is_conj()
326
+ and t1.is_neg() == t2.is_neg()
327
+ )
328
+
329
+
330
+ @dataclass(frozen=True)
331
+ class MetadataKey:
332
+ """
333
+ This should be equal whenever has_same_metadata would return True
334
+ """
335
+
336
+ size: tuple[SymIntEqByExpr, ...]
337
+ layout: torch.layout
338
+ is_sparse: bool
339
+ # these are empty when is_sparse
340
+ stride: Optional[tuple[SymIntEqByExpr, ...]]
341
+ storage_offset: Optional[SymIntEqByExpr]
342
+ is_conj: bool
343
+ is_neg: bool
344
+
345
+ @staticmethod
346
+ def make(t):
347
+ is_sparse = is_sparse_any(t)
348
+ return MetadataKey(
349
+ size=tuple(SymIntEqByExpr(s) for s in t.size()),
350
+ layout=t.layout,
351
+ is_sparse=is_sparse,
352
+ stride=None if is_sparse else tuple(SymIntEqByExpr(s) for s in t.stride()),
353
+ storage_offset=None if is_sparse else SymIntEqByExpr(t.storage_offset()),
354
+ is_conj=t.is_conj(),
355
+ is_neg=t.is_neg(),
356
+ )
357
+
358
+
359
+ # Wrapper around a FunctionalTensorWrapper for comparing only the resulting metadata
360
+ # after applying all the ViewMeta operations.
361
+ class FunctionalTensorMetadataEq:
362
+ def __init__(self, tensor: torch.Tensor) -> None:
363
+ assert torch._is_functional_tensor(tensor)
364
+ self.tensor = tensor
365
+
366
+ def __eq__(self, other: object) -> bool:
367
+ # If other is None, then it probably means that we weren't able to recreate
368
+ # the FunctionalTensorMetadataEq. One of this cases is when we update the
369
+ # view metadata by calling: create_synthetic_base_metadata.
370
+ if other is None:
371
+ return True
372
+
373
+ # Comparison agains any other type is not implemented.
374
+ if not isinstance(other, FunctionalTensorMetadataEq):
375
+ return NotImplemented
376
+
377
+ return has_same_metadata(self.tensor, other.tensor)
378
+
379
+
380
+ # new_arg and arg here are either:
381
+ # (1) both a FakeTensor
382
+ # (2) both a traceable tensor subclass that holds a FakeTensor
383
+ # Pre-condition: the two args are the "old" and "new" inputs from running functionalization.
384
+ # When we run functionalization and wrap our inputs into FunctionalTensors,
385
+ # we can detect whether or not an input was mutated by checking to see if the inner tensor has changed
386
+ #
387
+ # Normally it would be enough just to check if arg is new_arg, which is normally enough for functionalization
388
+ # to confirm that inputs were not mutated when running the user's model with functionalization on.
389
+ # But when we have subclass inputs, we can't rely on that:
390
+ # `from_fun(to_fun(x)) is x` will return False, because the call to `from_fun` constructs
391
+ # a brand new subclass instance: we are calling __tensor_unflatten__, and going
392
+ # from Subclass(FakeTensor) to Subclass(FunctionalTensor(FakeTensor))
393
+ def was_tensor_updated(arg, new_arg):
394
+ if is_traceable_wrapper_subclass(arg):
395
+ assert is_traceable_wrapper_subclass(new_arg)
396
+ attrs, _ = arg.__tensor_flatten__()
397
+ new_attrs, _ = new_arg.__tensor_flatten__()
398
+ assert attrs == new_attrs
399
+ # A tensor subclass was updated if any of its inner elements were updated
400
+ return any(
401
+ was_tensor_updated(getattr(arg, attr), getattr(new_arg, attr))
402
+ for attr in attrs
403
+ )
404
+ else:
405
+ return arg is not new_arg
406
+
407
+
408
+ # new_arg and arg here are either:
409
+ # (1) both a FakeTensor
410
+ # (2) both a traceable tensor subclass that holds a FakeTensor
411
+ # Pre-condition: the two args are the "old" and "new" inputs from running functionalization.
412
+ # When we run functionalization and wrap our inputs into FunctionalTensors,
413
+ # we can detect whether or not an input was mutated by checking to see if the inner tensor has changed,
414
+ # but shares storage with the old input
415
+ def was_tensor_metadata_updated(arg, new_arg):
416
+ if is_traceable_wrapper_subclass(arg):
417
+ assert is_traceable_wrapper_subclass(new_arg)
418
+ attrs, _ = arg.__tensor_flatten__()
419
+ new_attrs, _ = new_arg.__tensor_flatten__()
420
+ assert attrs == new_attrs
421
+ # A tensor subclass was updated if any of its inner elements were updated
422
+ return any(
423
+ was_tensor_metadata_updated(getattr(arg, attr), getattr(new_arg, attr))
424
+ for attr in attrs
425
+ )
426
+ else:
427
+ return arg is not new_arg and StorageWeakRef(
428
+ arg.untyped_storage()
429
+ ) == StorageWeakRef(new_arg.untyped_storage())
430
+
431
+
432
+ # Returns the number of detected copy_
433
+ def assert_functional_graph(fx_g: torch.fx.Graph) -> int:
434
+ allowed_mutation_ops = [
435
+ torch.ops.aten.copy_.default,
436
+ torch.ops.aten.set_.source_Tensor,
437
+ ]
438
+ if hasattr(torch.ops.fsdp, "copy_"):
439
+ allowed_mutation_ops.append(torch.ops.fsdp.copy_.default)
440
+
441
+ placeholders = set()
442
+ mutation_count = 0
443
+ # NB: It would also be nice to verify that the mutations all happen at the
444
+ # end, but we also do some administrative views after mutations so this
445
+ # isn't actually true. (TODO: Could this cause problems for Inductor?)
446
+ for n in fx_g.nodes:
447
+ if n.op == "placeholder":
448
+ placeholders.add(n)
449
+ if isinstance(n.target, torch._ops.OpOverload):
450
+ if n.target in allowed_mutation_ops:
451
+ # Can only copy_/set_ into an input
452
+ # this is mostly a hack to avoid failing XLA tests.
453
+ # See https://github.com/pytorch/pytorch/pull/122434#issuecomment-2101012113
454
+ if "set_buffer_donor_" not in str(n.args[0]):
455
+ assert (
456
+ n.args[0] in placeholders
457
+ ), f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}"
458
+ mutation_count += 1
459
+ else:
460
+ assert (
461
+ not n.target._schema.is_mutable
462
+ ), f"aot_autograd expected to have an entirely functional graph, but found {n.format_node()}"
463
+ return mutation_count
464
+
465
+
466
+ def propagate_input_mutation_stacktraces(fx_g: torch.fx.Graph) -> None:
467
+ placeholders = set()
468
+ for n in fx_g.nodes:
469
+ if n.op == "placeholder":
470
+ placeholders.add(n)
471
+ if isinstance(n.target, torch._ops.OpOverload):
472
+ if n.target is torch.ops.aten.copy_.default:
473
+ # Can only copy_ into an input, and can only do so once
474
+ if "set_buffer_donor_" not in str(n.args[0]):
475
+ assert (
476
+ n.args[0] in placeholders
477
+ ), f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}"
478
+ placeholders.remove(n.args[0])
479
+ copy_from_node = n.args[1]
480
+ # Pre-condition: every node has a "stack_trace" field in its meta,
481
+ # but copy_() nodes do not (since we manually added them during functionalization).
482
+ # Instead, we manually propagate here.
483
+ if "stack_trace" in copy_from_node.meta:
484
+ n.meta["stack_trace"] = copy_from_node.meta["stack_trace"]
485
+
486
+
487
+ def _check_if_mutation_can_be_in_graph(
488
+ keep_input_mutations: bool,
489
+ mutates_data,
490
+ mutates_metadata,
491
+ mutations_hidden_from_autograd,
492
+ mutations_under_no_grad_or_inference_mode,
493
+ mutates_storage_metadata,
494
+ mutation_inductor_storage_resize,
495
+ requires_grad,
496
+ ):
497
+ if keep_input_mutations:
498
+ in_graph = (
499
+ mutates_data or mutates_storage_metadata or mutation_inductor_storage_resize
500
+ ) and (
501
+ (not mutates_metadata and not requires_grad)
502
+ or mutations_hidden_from_autograd
503
+ or mutations_under_no_grad_or_inference_mode
504
+ )
505
+ else:
506
+ in_graph = False
507
+ # See Note [set_() Input Mutations in AOTAutograd]
508
+ # If there was a `set_()`, we require that all mutations were under no_grad,
509
+ # so we can (safely) emit the set_() in the graph at runtime
510
+ # resize_() gets the same treatment
511
+ if mutation_inductor_storage_resize or mutates_storage_metadata:
512
+ op_name = "resize_" if mutation_inductor_storage_resize else "set_"
513
+ assert in_graph, f"""\
514
+ Encountered a {op_name} on a graph input, but the input has other mutations that we cannot
515
+ keep in the graph. This is not supported today. Current state:
516
+ keep_input_mutations={keep_input_mutations}
517
+ mutates_data={mutates_data}
518
+ mutates_metadata={mutates_metadata}
519
+ mutations_hidden_from_autograd={mutations_hidden_from_autograd}
520
+ mutations_under_no_grad_or_inference_mode={mutations_under_no_grad_or_inference_mode}
521
+ mutation_inductor_storage_resize={mutation_inductor_storage_resize}
522
+ requires_grad={requires_grad}"""
523
+ return in_graph
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This module is one of the analysis modules - it takes as input a function or graph
4
+ and some preexisting properties, and returns some data that is useful for deciding
5
+ how to further proceed with compilation or construct runtime wrappers.
6
+
7
+ In particular, the following analyses are provided:
8
+ 1. Refine the view and mutation metadata collected previously - removing duplicate
9
+ inputs or mapping views to their bases.
10
+ 2. We also analyze the function signature for export graphs.
11
+ """
12
+
13
+ import contextlib
14
+ import itertools
15
+ from typing import Any, Optional, Union
16
+
17
+ import torch
18
+ import torch.utils._pytree as pytree
19
+ from torch import Tensor
20
+ from torch._C._dynamo.guards import compute_overlapping_tensors
21
+ from torch._functorch._aot_autograd.schemas import PlainTensorMeta
22
+ from torch._guards import StorageOverlap
23
+ from torch._subclasses.functional_tensor import FunctionalTensor
24
+ from torch.fx.experimental.symbolic_shapes import is_concrete_int
25
+
26
+ from .collect_metadata_analysis import coerce_tangent_and_suggest_memory_format
27
+ from .schemas import (
28
+ BackwardSignature,
29
+ GraphSignature,
30
+ InputAliasInfo,
31
+ MemoryFormatMeta,
32
+ OutputAliasInfo,
33
+ OutputType,
34
+ ViewAndMutationMeta,
35
+ )
36
+ from .utils import strict_zip
37
+
38
+
39
+ zip = strict_zip
40
+
41
+
42
+ def remove_dupe_metadata(
43
+ m: ViewAndMutationMeta,
44
+ keep_arg_mask: list[bool],
45
+ add_dupe_map: list[int],
46
+ ) -> ViewAndMutationMeta:
47
+ assert len(m.input_info) == len(keep_arg_mask)
48
+ # Easy invariant: the first argument should never be a dupe (it will be kept)
49
+ assert len(keep_arg_mask) > 0 and keep_arg_mask[0]
50
+
51
+ # Filter dupe'd mutated inputs out of traced_tangents
52
+ num_data_mutations = len([x for x in m.input_info if x.mutates_data])
53
+ other_traced_tangents = m.traced_tangents[num_data_mutations:]
54
+ inp_traced_tangents = m.traced_tangents[:num_data_mutations]
55
+ filtered_inp_traced_tangents = [
56
+ # See Note [Tangents memory format]
57
+ x
58
+ for i, x in enumerate(inp_traced_tangents)
59
+ if keep_arg_mask[m.mutated_inp_runtime_indices[i]]
60
+ ]
61
+ traced_tangents = filtered_inp_traced_tangents + other_traced_tangents
62
+
63
+ assert m.subclass_tangent_meta is not None
64
+ subclass_tangent_meta = [
65
+ PlainTensorMeta(
66
+ 0, memory_format=MemoryFormatMeta(memory_format=torch.contiguous_format)
67
+ )
68
+ ] * len(filtered_inp_traced_tangents) + m.subclass_tangent_meta[num_data_mutations:]
69
+
70
+ return ViewAndMutationMeta(
71
+ input_info=[x for i, x in enumerate(m.input_info) if keep_arg_mask[i]],
72
+ # For outputs that are views of inputs, we store the index of the input that the output
73
+ # was generated from. Need to update that index to account for removed dupes.
74
+ output_info=[
75
+ OutputAliasInfo(
76
+ output_type=o.output_type,
77
+ raw_type=o.raw_type,
78
+ dynamic_dims=o.dynamic_dims,
79
+ base_idx=None if o.base_idx is None else add_dupe_map[o.base_idx],
80
+ requires_grad=o.requires_grad,
81
+ functional_tensor=o.functional_tensor,
82
+ )
83
+ for o in m.output_info
84
+ ],
85
+ num_intermediate_bases=m.num_intermediate_bases,
86
+ keep_input_mutations=m.keep_input_mutations,
87
+ traced_tangents=traced_tangents,
88
+ # We are guaranteed not to get here, since dupes are not supported today with subclass inputs.
89
+ subclass_inp_meta=[],
90
+ subclass_fw_graph_out_meta=[],
91
+ subclass_tangent_meta=subclass_tangent_meta,
92
+ is_train=m.is_train,
93
+ )
94
+
95
+
96
+ # Given our ViewAndMutation metadata, this fn constructs a new set of metadata,
97
+ # after adding synthetic base arguments to the function.
98
+ # Most of the work in this fn is slogging through all of the metadata corresponding to inputs,
99
+ # and updating it with our synthetic base calling convention.
100
+ #
101
+ # When config.debug_assert is set, we automatically regenerate the metadata
102
+ # and compare it to this output for sanity.
103
+ #
104
+ # In addition to the updated metadata, also return the list of input indices
105
+ # that will need to be updated in the synthetic base epilogue
106
+ def create_synthetic_base_metadata(
107
+ m: ViewAndMutationMeta,
108
+ # Maps each outer argument idx to its inner idx (or, if this outer arg is generated from a
109
+ # synthetic base, you get a tuple of (i, TensorMeta), telling you the base tensor idx, and view metadata)
110
+ synthetic_base_info: list[Union[int, tuple[int, torch.Tensor]]],
111
+ outer_args: list[Any],
112
+ inner_args: list[Any],
113
+ ) -> tuple[ViewAndMutationMeta, list[int]]:
114
+ # maps inner arg indices to outer arg indices
115
+ synthetic_base_to_indices: dict[int, list[int]] = {}
116
+ for inner_idx in range(len(inner_args)):
117
+ outer_aliased_indices_of_current_base_arg = [
118
+ outer_idx
119
+ for outer_idx, inner_idx_or_tuple in enumerate(synthetic_base_info)
120
+ if (isinstance(inner_idx_or_tuple, int) and inner_idx_or_tuple == inner_idx)
121
+ or (
122
+ isinstance(inner_idx_or_tuple, tuple)
123
+ and inner_idx_or_tuple[0] == inner_idx
124
+ )
125
+ ]
126
+ synthetic_base_to_indices[inner_idx] = outer_aliased_indices_of_current_base_arg
127
+
128
+ # given the requires_grad info on mutated inputs,
129
+ # generate the requires_grad info on those same mutated inputs, but after constructing synthetic bases.
130
+ input_infos = []
131
+ for outer_indices in synthetic_base_to_indices.values():
132
+ # leaf-ness should be all-or-nothing for aliased tensor.
133
+ # (aka if "a" and "b" are views, then a.is_leaf == b.is_leaf)
134
+ any_leaf = any(m.input_info[x].is_leaf for x in outer_indices)
135
+ all_leaf = all(m.input_info[x].is_leaf for x in outer_indices)
136
+ assert any_leaf == all_leaf
137
+
138
+ mutates_data = (
139
+ True
140
+ if len(outer_indices) > 1
141
+ else m.input_info[outer_indices[0]].mutates_data
142
+ )
143
+ mutates_metadata = (
144
+ False
145
+ if len(outer_indices) > 1
146
+ else m.input_info[outer_indices[0]].mutates_metadata
147
+ )
148
+ requires_grad = any(m.input_info[x].requires_grad for x in outer_indices)
149
+ mutations_under_no_grad_or_inference_mode = all(
150
+ m.input_info[x].mutations_under_no_grad_or_inference_mode
151
+ for x in outer_indices
152
+ )
153
+
154
+ mutation_inductor_storage_resize = all(
155
+ m.input_info[x].mutation_inductor_storage_resize for x in outer_indices
156
+ )
157
+
158
+ inpt_info = InputAliasInfo(
159
+ # If len(outer_indices) > 1, then this input is a synthetic base.
160
+ # The invariant is that to the rest of aot autograd, synthetic bases only show up if
161
+ # one of their aliases gets a data mutation. And if any of their aliases get metadata
162
+ # mutations, they will be hidden from the rest of aot autograd.
163
+ mutates_data=mutates_data,
164
+ mutates_metadata=mutates_metadata,
165
+ mutations_hidden_from_autograd=all(
166
+ m.input_info[x].mutations_hidden_from_autograd for x in outer_indices
167
+ ),
168
+ mutates_storage_metadata=(
169
+ False
170
+ if len(outer_indices) > 1
171
+ else m.input_info[outer_indices[0]].mutates_storage_metadata
172
+ ),
173
+ mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode,
174
+ mutation_inductor_storage_resize=mutation_inductor_storage_resize,
175
+ is_leaf=any_leaf,
176
+ requires_grad=requires_grad,
177
+ keep_input_mutations=m.keep_input_mutations,
178
+ )
179
+ input_infos.append(inpt_info)
180
+
181
+ # Find any inputs that fulfill the following criteria:
182
+ # (1) They are part of a synthetic base (because they alias another input,
183
+ # and at least one input experiences a data mutation)
184
+ # (2) They experience a metadata mutation
185
+ outer_aliased_arg_idx_with_metadata_mutations = [
186
+ outer_idx
187
+ for outer_idx, inpt_info in enumerate(m.input_info)
188
+ if inpt_info.mutates_metadata
189
+ and not isinstance(synthetic_base_info[outer_idx], int)
190
+ ]
191
+
192
+ # grab the original requires grad info on the outputs, except the ones from the mutated inputs
193
+ input_metadata_output_info = [
194
+ OutputAliasInfo(
195
+ output_type=OutputType.alias_of_input,
196
+ raw_type=FunctionalTensor,
197
+ dynamic_dims={
198
+ i
199
+ for i, s in enumerate(outer_args[outer_idx].shape)
200
+ if not is_concrete_int(s)
201
+ },
202
+ base_idx=synthetic_base_info[outer_idx][0], # type: ignore[index]
203
+ requires_grad=outer_args[outer_idx].requires_grad,
204
+ )
205
+ for outer_idx in outer_aliased_arg_idx_with_metadata_mutations
206
+ ]
207
+ existing_output_infos = []
208
+ for o in m.output_info:
209
+ new_base_idx = (
210
+ None
211
+ if o.base_idx is None
212
+ else (
213
+ synthetic_base_info[o.base_idx]
214
+ if isinstance(synthetic_base_info[o.base_idx], int)
215
+ else synthetic_base_info[o.base_idx][0] # type: ignore[index]
216
+ )
217
+ )
218
+ # If base_idx is changed for OutputType.is_input, we need to update the output type to reflect the change
219
+ new_output_type = (
220
+ OutputType.alias_of_input
221
+ if o.output_type == OutputType.is_input and o.base_idx != new_base_idx
222
+ else o.output_type
223
+ )
224
+ existing_output_infos.append(
225
+ OutputAliasInfo(
226
+ output_type=new_output_type,
227
+ raw_type=o.raw_type,
228
+ dynamic_dims=o.dynamic_dims,
229
+ # Map the input idx pre-synthetic-bases to the new idx post-synthetic-bases
230
+ base_idx=new_base_idx, # type: ignore[arg-type]
231
+ requires_grad=o.requires_grad,
232
+ functional_tensor=o.functional_tensor,
233
+ )
234
+ )
235
+
236
+ inner_mutated_tangents_and_memory_formats = [
237
+ # See Note [Tangents memory format]
238
+ coerce_tangent_and_suggest_memory_format(x)
239
+ for inner_idx, x in enumerate(inner_args)
240
+ if input_infos[inner_idx].mutates_data and input_infos[inner_idx].requires_grad
241
+ ]
242
+ inner_mutated_tangents = [x[0] for x in inner_mutated_tangents_and_memory_formats]
243
+ inner_mutated_tangents_memory_formats = [
244
+ x[1] for x in inner_mutated_tangents_and_memory_formats
245
+ ]
246
+
247
+ output_info = existing_output_infos + input_metadata_output_info
248
+ # Regenerate traced tangents to include mutated inputs including synthetic bases
249
+ traced_tangents = (
250
+ inner_mutated_tangents + m.traced_tangents[len(inner_mutated_tangents) :]
251
+ )
252
+ assert m.subclass_tangent_meta is not None
253
+ subclass_tangent_meta = [
254
+ PlainTensorMeta(0, memory_format=x)
255
+ for x in inner_mutated_tangents_memory_formats
256
+ ] + m.subclass_tangent_meta[len(inner_mutated_tangents) :]
257
+
258
+ return (
259
+ ViewAndMutationMeta(
260
+ input_info=input_infos,
261
+ output_info=output_info,
262
+ num_intermediate_bases=m.num_intermediate_bases,
263
+ keep_input_mutations=m.keep_input_mutations,
264
+ traced_tangents=traced_tangents,
265
+ # We are guaranteed not to get here, since synthetic_base codepaths are not supported today with subclass inputs.
266
+ subclass_inp_meta=[],
267
+ subclass_fw_graph_out_meta=[],
268
+ subclass_tangent_meta=subclass_tangent_meta,
269
+ is_train=m.is_train,
270
+ ),
271
+ outer_aliased_arg_idx_with_metadata_mutations,
272
+ )
273
+
274
+
275
+ def compute_overlapping_inputs(aot_config, fwd_inputs, aliased_input_indices):
276
+ num_aliases = len(aliased_input_indices)
277
+
278
+ shape_env = None
279
+ maybe_suppress_guards = contextlib.nullcontext
280
+ tracing_context = torch._guards.TracingContext.try_get()
281
+
282
+ if tracing_context is not None:
283
+ shape_env = tracing_context.fake_mode.shape_env
284
+
285
+ # Check whether we can actually get the dynamo sources from within AOTAutograd.
286
+ if aot_config.aot_autograd_arg_pos_to_source and shape_env is not None:
287
+ maybe_suppress_guards = shape_env.suppress_guards
288
+
289
+ # Check whether there are any symbolic values being used.
290
+ # We do this for 2 reasons:
291
+ # 1. StorageOverlap guard is only issued whenever dynamic shapes is turned on
292
+ # 2. Triggers the fast-path for computing storage overlapping
293
+ symbolic = any(
294
+ isinstance(x, torch.SymInt)
295
+ for i in aliased_input_indices
296
+ for x in [
297
+ *fwd_inputs[i].shape,
298
+ *fwd_inputs[i].stride(),
299
+ fwd_inputs[i].storage_offset(),
300
+ ]
301
+ )
302
+
303
+ if torch._inductor.config.is_fbcode():
304
+ if symbolic and num_aliases > 400:
305
+ from torch._subclasses.fake_tensor import (
306
+ UnsupportedMutationAliasingException,
307
+ )
308
+ from torch._utils_internal import justknobs_check
309
+
310
+ msg = f"Encountered {num_aliases} dynamic, aliased/mutated inputs, consider setting dynamic=False"
311
+
312
+ if justknobs_check(
313
+ "pytorch/compiler:aliased_inputs_with_mutation_and_dyn_shapes_killswitch",
314
+ False,
315
+ ):
316
+ raise UnsupportedMutationAliasingException(msg)
317
+
318
+ with maybe_suppress_guards():
319
+ aliased_fwd_inputs = [fwd_inputs[i] for i in aliased_input_indices]
320
+ actual_aliased_indices = {
321
+ aliased_input_indices[i]
322
+ for i in compute_overlapping_tensors(aliased_fwd_inputs, symbolic=symbolic)
323
+ }
324
+
325
+ # Add the StorageOverlap AOTAutograd guard only if we are actually keeping track of
326
+ # dynamo sources inside AOTAutograd.
327
+ if (
328
+ tracing_context is not None
329
+ # Make sure dynamic shapes is currently being used.
330
+ and symbolic
331
+ # We check that we have more than 1 aliased tensor, which should be true at
332
+ # this point, anyway.
333
+ and num_aliases > 1
334
+ and aot_config.aot_autograd_arg_pos_to_source
335
+ ):
336
+ no_overlap_indices = list(set(aliased_input_indices) - actual_aliased_indices)
337
+
338
+ overlapping_sources = [
339
+ aot_config.aot_autograd_arg_pos_to_source[i] for i in actual_aliased_indices
340
+ ]
341
+ non_overlapping_sources = [
342
+ aot_config.aot_autograd_arg_pos_to_source[i] for i in no_overlap_indices
343
+ ]
344
+
345
+ tracing_context.guards_context.aotautograd_guards.append(
346
+ StorageOverlap(overlapping_sources, non_overlapping_sources)
347
+ )
348
+
349
+ return actual_aliased_indices
350
+
351
+
352
+ def _graph_input_names(gm):
353
+ return [node.name for node in gm.graph.find_nodes(op="placeholder")]
354
+
355
+
356
+ def _graph_output_names(gm):
357
+ output_node = next(iter(reversed(gm.graph.nodes)))
358
+ assert output_node.op == "output" and len(output_node.args) == 1
359
+ return_args = output_node.args[0]
360
+ return [getattr(return_arg, "name", None) for return_arg in return_args]
361
+
362
+
363
+ def create_graph_signature(
364
+ fx_g: torch.fx.GraphModule,
365
+ fw_metadata: ViewAndMutationMeta,
366
+ in_spec: pytree.TreeSpec,
367
+ out_spec: pytree.TreeSpec,
368
+ *,
369
+ user_args_flat: list[Tensor],
370
+ params_and_buffers_flat: list[Tensor],
371
+ param_names: list[str],
372
+ buffer_names: list[str],
373
+ trace_joint: bool,
374
+ num_user_fw_outs: Optional[int],
375
+ loss_index: Optional[int],
376
+ ) -> GraphSignature:
377
+ # Retrieve graph input names
378
+ graph_input_names = _graph_input_names(fx_g)
379
+ # Retrieve graph output names
380
+ graph_output_names = _graph_output_names(fx_g)
381
+
382
+ num_params_buffers = len(param_names) + len(buffer_names)
383
+ num_tokens = len(fw_metadata.tokens)
384
+ # We have enough restrictions on the graph (no de-duping, synthetic bases, etc),
385
+ # Such that # graph inps = # user inps + # params + # buffers
386
+ num_user_args = len(graph_input_names) - num_params_buffers - num_tokens
387
+
388
+ if trace_joint:
389
+ assert num_user_fw_outs is not None
390
+ num_fw_outs = num_user_fw_outs + fw_metadata.num_mutated_inp_runtime_indices
391
+ backward_output_names = graph_output_names[num_fw_outs:]
392
+
393
+ grad_index = itertools.count(0)
394
+ gradients_to_parameters = {
395
+ backward_output_names[next(grad_index)]: param_names[i]
396
+ for i, param in enumerate(params_and_buffers_flat)
397
+ if param.requires_grad
398
+ }
399
+
400
+ gradients_to_user_inputs = {
401
+ backward_output_names[next(grad_index)]: graph_input_names[
402
+ i + len(params_and_buffers_flat)
403
+ ]
404
+ for i, user_input in enumerate(user_args_flat)
405
+ if user_input.requires_grad
406
+ }
407
+
408
+ assert len(gradients_to_parameters) + len(gradients_to_user_inputs) == len(
409
+ backward_output_names
410
+ )
411
+
412
+ # Check that we have fully accounted for all graph outputs
413
+ backward_signature = BackwardSignature(
414
+ gradients_to_parameters,
415
+ gradients_to_user_inputs,
416
+ graph_output_names[loss_index],
417
+ )
418
+ else:
419
+ backward_signature = None
420
+ num_user_fw_outs = (
421
+ len(graph_output_names)
422
+ - fw_metadata.num_mutated_inp_runtime_indices
423
+ - num_tokens
424
+ )
425
+
426
+ return GraphSignature.from_tracing_metadata(
427
+ in_spec=in_spec,
428
+ out_spec=out_spec,
429
+ graph_input_names=graph_input_names,
430
+ graph_output_names=graph_output_names,
431
+ view_mutation_metadata=fw_metadata,
432
+ named_parameters=param_names,
433
+ named_buffers=buffer_names,
434
+ num_user_inputs=num_user_args,
435
+ num_user_outputs=num_user_fw_outs,
436
+ loss_index=loss_index,
437
+ backward_signature=backward_signature,
438
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/jit_compile_runtime_wrappers.py ADDED
@@ -0,0 +1,1845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Functions in this module do most of the "work" of AOTAutograd.
4
+ An aot_dispatch_* function:
5
+ - Takes in the input flat_fn, flat_args, and some metadata
6
+ - Runs a set of pre compile wrappers (e.g. argument deduping)
7
+ - Runs the actual compiler
8
+ - Wraps the returned callable in a set of post compile wrappers
9
+ - Returns the wrapped callable and metadata.
10
+ """
11
+
12
+ import copy
13
+ import dataclasses
14
+ import itertools
15
+ import logging
16
+ import operator
17
+ import time
18
+ import traceback
19
+ from collections import defaultdict
20
+ from contextlib import nullcontext
21
+ from typing import Any, Callable, Optional, TYPE_CHECKING
22
+
23
+ import torch
24
+ import torch.utils._pytree as pytree
25
+ import torch.utils.dlpack
26
+ from torch import Tensor
27
+ from torch._dynamo.utils import detect_fake_mode, dynamo_timed, lazy_format_graph_code
28
+ from torch._guards import CompileContext, TracingContext
29
+ from torch._logging import getArtifactLogger, trace_structured
30
+ from torch._subclasses import FakeTensor
31
+ from torch._subclasses.meta_utils import is_sparse_any
32
+ from torch.fx.experimental._backward_state import BackwardState
33
+ from torch.fx.experimental.proxy_tensor import is_sym_node
34
+ from torch.fx.experimental.symbolic_shapes import fx_placeholder_vals
35
+ from torch.fx.graph_module import GraphModule
36
+ from torch.fx.passes._tensorify_python_scalars import tensorify_python_scalars
37
+ from torch.multiprocessing.reductions import StorageWeakRef
38
+ from torch.types import py_sym_types
39
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
40
+ from torchgen.utils import dataclass_repr
41
+
42
+ from .. import config
43
+ from .autograd_cache import (
44
+ AOTAutogradCache,
45
+ serialize_graph_module,
46
+ should_use_remote_autograd_cache,
47
+ )
48
+ from .dispatch_and_compile_graph import (
49
+ aot_dispatch_autograd_graph,
50
+ aot_dispatch_base_graph,
51
+ )
52
+ from .logging_utils import track_graph_compiling
53
+ from .runtime_wrappers import (
54
+ AOTDedupeWrapper,
55
+ AOTDispatchAutograd,
56
+ AOTDispatchSubclassWrapper,
57
+ AOTSyntheticBaseWrapper,
58
+ AutogradLazyBackwardCompileInfo,
59
+ CompilerWrapper,
60
+ DebugAssertWrapper,
61
+ EffectTokensWrapper,
62
+ FakifiedOutWrapper,
63
+ FunctionalizedRngRuntimeWrapper,
64
+ make_runtime_safe,
65
+ post_compile,
66
+ pre_compile,
67
+ RuntimeWrapper,
68
+ )
69
+ from .schemas import AOTConfig, MutationType, ViewAndMutationMeta
70
+ from .subclass_utils import compute_inner_mutated_inp_indices_from_subclass_meta
71
+ from .utils import (
72
+ _get_symint_hints,
73
+ contain_metadata_mutation_ops,
74
+ get_cuda_generator_meta_val,
75
+ make_boxed_func,
76
+ strict_zip,
77
+ unlift_tokens,
78
+ )
79
+
80
+
81
+ if TYPE_CHECKING:
82
+ from collections.abc import Sequence
83
+
84
+ zip = strict_zip
85
+
86
+ log = logging.getLogger(__name__)
87
+ aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph")
88
+ aot_graphs_log = getArtifactLogger(__name__, "aot_graphs")
89
+
90
+ aten = torch.ops.aten
91
+
92
+ # Returns a Callable and a ViewAndMutationMeta.
93
+ # Currently, only export needs the ViewAndMutationMeta after this function.
94
+ DispatchReturn = tuple[Callable, ViewAndMutationMeta]
95
+
96
+
97
+ def _create_wrappers_for_dispatch(needs_autograd: bool) -> list[CompilerWrapper]:
98
+ """
99
+ Wrappers that run on every dispatch function
100
+ """
101
+ return [AOTDedupeWrapper(), AOTSyntheticBaseWrapper(trace_joint=needs_autograd)]
102
+
103
+
104
+ # Export's dispatching logic is unique in a few ways: it only needs the "graph"
105
+ # bits of aot_autograd, and doesn't need to do any specific wrapping.
106
+ def aot_dispatch_export(
107
+ flat_fn: Callable,
108
+ flat_args: list[Any],
109
+ aot_config: AOTConfig,
110
+ *,
111
+ fw_metadata: ViewAndMutationMeta,
112
+ needs_autograd: bool,
113
+ ) -> DispatchReturn:
114
+ wrappers = _create_wrappers_for_dispatch(needs_autograd)
115
+ flat_fn, flat_args, fw_metadata = pre_compile(
116
+ wrappers,
117
+ flat_fn,
118
+ flat_args,
119
+ aot_config,
120
+ fw_metadata=fw_metadata,
121
+ )
122
+ if needs_autograd and not aot_config.pre_dispatch:
123
+ graph, _, _ = aot_dispatch_autograd_graph(
124
+ flat_fn, flat_args, aot_config, fw_metadata=fw_metadata
125
+ )
126
+ else:
127
+ graph, _, _ = aot_dispatch_base_graph(
128
+ flat_fn, flat_args, aot_config, fw_metadata=fw_metadata
129
+ )
130
+
131
+ # NB: the wrappers that run in pre_compile for export are
132
+ # either a no-op, because they're not needed, or will raise a runtime error,
133
+ # since they don't support export.
134
+ # We still run these wrappers to make sure that they're not needed pre compile,
135
+ # but we technically don't need to run them post compile at all here.
136
+ compiled_fn, fw_metadata = post_compile(
137
+ wrappers, graph, aot_config, runtime_metadata=fw_metadata
138
+ )
139
+
140
+ # Therefore, since no wrapperes run, we don't get back a callable - we get back the raw fx graph
141
+ # (either a joint or an inference-only graph)
142
+ assert isinstance(compiled_fn, torch.fx.GraphModule)
143
+ return compiled_fn, fw_metadata
144
+
145
+
146
+ def sanitize_aot_config(input: AOTConfig) -> AOTConfig:
147
+ return AOTConfig(
148
+ fw_compiler=None, # type: ignore[arg-type]
149
+ bw_compiler=None, # type: ignore[arg-type]
150
+ partition_fn=None, # type: ignore[arg-type]
151
+ decompositions={},
152
+ inference_compiler=None,
153
+ num_params_buffers=input.num_params_buffers,
154
+ aot_id=input.aot_id,
155
+ keep_inference_input_mutations=input.keep_inference_input_mutations,
156
+ is_export=input.is_export,
157
+ no_tangents=input.no_tangents,
158
+ aot_autograd_arg_pos_to_source=input.aot_autograd_arg_pos_to_source,
159
+ dynamic_shapes=input.dynamic_shapes,
160
+ enable_log=input.enable_log,
161
+ static_input_indices=input.static_input_indices,
162
+ pre_dispatch=input.pre_dispatch,
163
+ cache_info=None,
164
+ precompile_backend_id=input.precompile_backend_id,
165
+ )
166
+
167
+
168
+ def aot_dispatch_base(
169
+ flat_fn,
170
+ flat_args: list[Any],
171
+ aot_config: AOTConfig,
172
+ *,
173
+ fw_metadata: ViewAndMutationMeta,
174
+ ) -> DispatchReturn:
175
+ """
176
+ Handles functions that don't need autograd. Runs wrappers and compiles with fw_compiler.
177
+ """
178
+ wrappers = _create_wrappers_for_dispatch(needs_autograd=False)
179
+ flat_fn, flat_args, fw_metadata = pre_compile(
180
+ wrappers, flat_fn, flat_args, aot_config, fw_metadata=fw_metadata
181
+ )
182
+ fw_module, updated_flat_args, maybe_subclass_meta = aot_dispatch_base_graph( # type: ignore[misc]
183
+ flat_fn, flat_args, aot_config, fw_metadata=fw_metadata
184
+ )
185
+ # Save the forward_graph_str right after aot_dispatch_base_graph,
186
+ # to save in the cache
187
+ aot_forward_graph_str = None
188
+ if aot_config.cache_info is not None:
189
+ aot_forward_graph_str = fw_module.print_readable(
190
+ print_output=False,
191
+ include_stride=True,
192
+ include_device=True,
193
+ fast_sympy_print=True,
194
+ )
195
+
196
+ fakified_out_wrapper = FakifiedOutWrapper()
197
+ (
198
+ fw_module,
199
+ updated_flat_args,
200
+ fw_metadata,
201
+ ) = fakified_out_wrapper.pre_compile(
202
+ fw_module, updated_flat_args, aot_config, fw_metadata=fw_metadata
203
+ )
204
+ functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper()
205
+ (
206
+ fw_module,
207
+ updated_flat_args,
208
+ fw_metadata,
209
+ ) = functionalized_rng_wrapper.pre_compile(
210
+ fw_module, updated_flat_args, aot_config, fw_metadata=fw_metadata
211
+ )
212
+ assert isinstance(fw_module, GraphModule)
213
+
214
+ if aot_config.enable_log:
215
+ trace_structured(
216
+ "artifact",
217
+ metadata_fn=lambda: {
218
+ "name": "torch._functorch.config",
219
+ "encoding": "string",
220
+ },
221
+ payload_fn=lambda: torch._functorch.config.get_config_copy(),
222
+ )
223
+
224
+ disable_amp = torch._C._is_any_autocast_enabled()
225
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
226
+
227
+ with context(), track_graph_compiling(aot_config, "inference"):
228
+ compiler = (
229
+ aot_config.inference_compiler
230
+ if aot_config.inference_compiler is not None
231
+ else aot_config.fw_compiler
232
+ )
233
+
234
+ if tracing_context := torch._guards.TracingContext.try_get():
235
+ tracing_context.fw_metadata = (
236
+ fw_metadata
237
+ if maybe_subclass_meta is None
238
+ else maybe_subclass_meta.fw_metadata
239
+ )
240
+
241
+ with TracingContext.report_output_strides() as fwd_output_strides:
242
+ fake_mode = detect_fake_mode()
243
+ if fake_mode is not None and fake_mode.shape_env is not None:
244
+ tensorify_python_scalars(fw_module, fake_mode.shape_env, fake_mode)
245
+ compiled_fw = compiler(fw_module, updated_flat_args)
246
+
247
+ if fakified_out_wrapper.needs_post_compile:
248
+ fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides)
249
+
250
+ make_runtime_safe(fw_metadata, maybe_subclass_meta)
251
+
252
+ # However, RuntimeWrapper does not expect the rng offsets in the
253
+ # output. So, we have to create another wrapper and take out the offset. As
254
+ # a result, we have to account for not boxed_call compilers as well.
255
+ if not getattr(compiled_fw, "_boxed_call", False):
256
+ compiled_fw = make_boxed_func(compiled_fw)
257
+
258
+ # Create a wrapper to set up the rng functionalize and fakified out bits
259
+ compiled_fw = functionalized_rng_wrapper.post_compile(
260
+ compiled_fw, aot_config, runtime_metadata=fw_metadata
261
+ )
262
+ cache_info = aot_config.cache_info
263
+ if cache_info is not None:
264
+ if hasattr(compiled_fw, "_fx_graph_cache_key"):
265
+ time_taken_ns = time.time_ns() - cache_info.start_time_ns
266
+ guards_expr = AOTAutogradCache.generate_guards_expression(cache_info)
267
+ entry = AOTAutogradCache.make_entry(
268
+ compiled_fw_func=compiled_fw, # type: ignore[arg-type]
269
+ compiled_bw_func=None,
270
+ aot_joint_graph_str=None,
271
+ aot_forward_graph_str=aot_forward_graph_str,
272
+ aot_backward_graph_str=None,
273
+ runtime_metadata=fw_metadata,
274
+ dispatch_wrappers=wrappers,
275
+ maybe_subclass_meta=maybe_subclass_meta,
276
+ num_fw_outs_saved_for_bw=None,
277
+ indices_of_inps_to_detach=[],
278
+ forward_time_taken_ns=time_taken_ns,
279
+ backward_time_taken_ns=0,
280
+ sanitized_aot_config=sanitize_aot_config(aot_config),
281
+ guards_expr=guards_expr,
282
+ backward_state_indices=None,
283
+ num_symints_saved_for_bw=None,
284
+ serialized_bw_module=None,
285
+ )
286
+ AOTAutogradCache.save(
287
+ cache_info.cache_key, entry, remote=should_use_remote_autograd_cache()
288
+ )
289
+
290
+ compiled_fw = fakified_out_wrapper.post_compile(
291
+ compiled_fw,
292
+ aot_config,
293
+ runtime_metadata=fw_metadata,
294
+ )
295
+
296
+ compiled_fw = EffectTokensWrapper().post_compile(
297
+ compiled_fw,
298
+ aot_config,
299
+ runtime_metadata=fw_metadata,
300
+ )
301
+
302
+ # Why do we need to pass in num_fw_outs_saved_for_bw?
303
+ # See Note: [Partitioner handling for Subclasses, Part 2]
304
+ compiled_fw = AOTDispatchSubclassWrapper(
305
+ trace_joint=False,
306
+ # TODO: once we use pre_compile this will be flat_fn at the top of this function
307
+ fw_only=None,
308
+ maybe_subclass_meta=maybe_subclass_meta,
309
+ num_fw_outs_saved_for_bw=None,
310
+ ).post_compile(
311
+ compiled_fw,
312
+ aot_config, # not used
313
+ runtime_metadata=fw_metadata,
314
+ )
315
+
316
+ if not getattr(compiled_fw, "_boxed_call", False):
317
+ compiled_fw = make_boxed_func(compiled_fw)
318
+
319
+ compiled_fn = RuntimeWrapper(
320
+ indices_of_inps_to_detach=[],
321
+ trace_joint=False,
322
+ disable_amp=disable_amp,
323
+ ).post_compile(
324
+ compiled_fw,
325
+ aot_config,
326
+ runtime_metadata=fw_metadata,
327
+ )
328
+
329
+ compiled_fn = post_compile(
330
+ wrappers, compiled_fn, aot_config, runtime_metadata=fw_metadata
331
+ )
332
+ return compiled_fn
333
+
334
+
335
+ def collect_fw_donated_buffer_idxs(
336
+ fw_ins: list[Optional[FakeTensor]],
337
+ user_fw_outs: list[Optional[FakeTensor]],
338
+ bw_outs: list[Optional[FakeTensor]],
339
+ saved_tensors: list[FakeTensor],
340
+ ) -> list[int]:
341
+ """
342
+ Checks if the saved tensors are donated buffers, which means a saved tensor is not
343
+ an alias of any tensors in fw_ins, user_fw_outs, and bw_outs.
344
+ """
345
+
346
+ storage_refs = set()
347
+ for t in itertools.chain(fw_ins, user_fw_outs, bw_outs):
348
+ # Only access storage if a tensor has storage (not sparse)
349
+ if t is not None and isinstance(t, FakeTensor) and not is_sparse_any(t):
350
+ storage_refs.add(StorageWeakRef(t.untyped_storage()))
351
+
352
+ num_saved_tensor = len(saved_tensors)
353
+ donated_buffer_idxs = []
354
+ for i in range(num_saved_tensor):
355
+ t = saved_tensors[i]
356
+ if (
357
+ t is not None
358
+ and not is_sparse_any(t)
359
+ and StorageWeakRef(t.untyped_storage()) not in storage_refs
360
+ ):
361
+ donated_buffer_idxs.append(i)
362
+
363
+ return donated_buffer_idxs
364
+
365
+
366
+ def collect_bw_donated_buffer_idxs(
367
+ fw_module: torch.fx.GraphModule,
368
+ bw_module: torch.fx.GraphModule,
369
+ fw_metadata: ViewAndMutationMeta,
370
+ ) -> list[int]:
371
+ """
372
+ Collects backward donated buffer indexes from fw_module and bw_module.
373
+ """
374
+
375
+ # [Note: Metadata mutation in proxy tracing]
376
+ # node.meta["val"] is a snapshot of the tensor value when tracing a graph,
377
+ # instead of the final state after the graph has run. node.meta["val"] is
378
+ # not updated even if later there is a metadata mutation op.
379
+ # See: https://github.com/pytorch/pytorch/pull/141308#issuecomment-2495798947
380
+ #
381
+ # Currently, metadata mutation op happens only for sacrificial parameter
382
+ # specifically the `set_` op. This motivates banning metadata mutation from
383
+ # proxy tracing.
384
+ #
385
+ # Since node.meta["val"] is used to detect donated buffer, we return an empty
386
+ # list if there exists metadata mutation op.
387
+ if contain_metadata_mutation_ops(fw_module) or contain_metadata_mutation_ops(
388
+ bw_module
389
+ ):
390
+ return []
391
+
392
+ fw_ins = fw_module.graph.find_nodes(op="placeholder")
393
+ bw_outs = next(reversed(bw_module.graph.find_nodes(op="output"))).args[0]
394
+ fw_outs = next(reversed(fw_module.graph.find_nodes(op="output"))).args[0]
395
+
396
+ fw_ins = [
397
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
398
+ for n in fw_ins
399
+ ]
400
+ fw_outs = [
401
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
402
+ for n in fw_outs
403
+ ]
404
+ bw_outs = [
405
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
406
+ for n in bw_outs
407
+ ]
408
+
409
+ user_fw_outs = fw_outs[: fw_metadata.num_forward]
410
+ saved_tensors = fw_outs[fw_metadata.tensors_saved_for_backwards_slice]
411
+
412
+ fw_donated_buffer = collect_fw_donated_buffer_idxs(
413
+ fw_ins,
414
+ user_fw_outs,
415
+ bw_outs,
416
+ saved_tensors,
417
+ )
418
+
419
+ assert fw_metadata.num_symints_saved_for_bw is not None
420
+ return [fw_metadata.num_symints_saved_for_bw + i for i in fw_donated_buffer]
421
+
422
+
423
+ @dataclasses.dataclass
424
+ class InvokeSubgraphHopGraphs:
425
+ """
426
+ A data structure to hold all the information needed to partition the
427
+ `joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and
428
+ `new_bw_hop_gm` into the bigger `joint_gm`.
429
+ """
430
+
431
+ # To avoid re-partitioning subgraphs
432
+ partitioning_done: bool = False
433
+ old_num_fw_outputs: Optional[int] = None
434
+ old_num_fw_inputs: Optional[int] = None
435
+
436
+ new_fw_hop_gm: Optional[torch.fx.GraphModule] = None
437
+ new_bw_hop_gm: Optional[torch.fx.GraphModule] = None
438
+ new_num_sym_nodes: Optional[int] = None
439
+ new_num_saved_nodes: Optional[int] = None
440
+
441
+
442
+ def run_joint_graph_passes_on_hops(
443
+ joint_gm: torch.fx.GraphModule,
444
+ joint_inputs: Any,
445
+ aot_config: AOTConfig,
446
+ ) -> torch.fx.GraphModule:
447
+ """
448
+ This pass runs the joint graph passes on the HOP graph. In torch.compile, we
449
+ typically have many passes which work on the joint graph and then end with a
450
+ partitioner.
451
+
452
+
453
+ The partitioner part is quite mechanical to handle. HOP have their own
454
+ forward and backward graph. The process can be broken into following steps
455
+
456
+ 1) Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm`
457
+ 2) Run joint graph passes on the `joint_hop_gm` to get `new_fw_hop_gm` and `new_bw_hop_gm`
458
+ 3) Stitch the `new_fw_hop_gm` and `new_bw_hop_gm` back into the `joint_gm`.
459
+
460
+ The terminology used in the code is
461
+ `joint_graph/joint_gm` : Refers to the main graph. This may contain many HOPs which have their own `hop_graph`
462
+ `fw_hop_graph/fw_hop_gm` : Refers to the forward graph associated with a HOP.
463
+ `bw_hop_graph/bw_hop_gm` : Refers to the backward graph associated with a HOP.
464
+ `joint_hop_graph/joint_hop_gm` : Refers to the subgraph associated with the HOP like invoke_subgraph.
465
+ `new_fw_hop_graph/new_fw_hop_gm` : Refers to the forward graph after partitioning is applied to `joint_hop_gm`.
466
+ `new_bw_hop_graph/new_bw_hop_gm` : Refers to the backward graph after partitioning is applied to `joint_hop_gm`.
467
+
468
+ NB: This pass works for invoke_subgraph today because we took extra care in
469
+ the Autograd.Dispatch key of invoke_subgraph to vastly simplify Step 1.
470
+ """
471
+ from torch._higher_order_ops import invoke_subgraph
472
+
473
+ def num_outputs(mod):
474
+ return len(mod.graph.find_nodes(op="output")[0].args[0])
475
+
476
+ def num_inputs(mod):
477
+ return len(mod.graph.find_nodes(op="placeholder"))
478
+
479
+ def prepare_for_partitioner(mod, num_primals, num_fw_outputs):
480
+ # min-cut partitioner requires the placeholders to have primals and
481
+ # tangents string in the node.name. The signature of the joint graph is
482
+ # (*primals, *tangents)
483
+
484
+ # We also have to update the output signature which is right now
485
+ # (*grads, *fw_outs) and we have to change to (*fw_outs, *grads) for the
486
+ # partitioner to work.
487
+ new_graph = torch.fx.Graph()
488
+ env = {}
489
+
490
+ primals_counter = itertools.count(0)
491
+ tangents_counter = itertools.count(0)
492
+
493
+ for idx, node in enumerate(mod.graph.nodes):
494
+ if node.op == "placeholder":
495
+ if idx < num_primals:
496
+ env[node] = new_graph.placeholder(
497
+ f"primals_{next(primals_counter)}"
498
+ )
499
+ else:
500
+ env[node] = new_graph.placeholder(
501
+ f"tangents_{next(tangents_counter)}"
502
+ )
503
+ env[node].meta = copy.copy(node.meta)
504
+ elif node.op == "output":
505
+ # Reverse the (*grads, *fw_outs) to (*fw_outs, *grads)
506
+ # The reason for having the reversed signature in the first
507
+ # place is to simplify step 3.
508
+ old_outputs = node.args[0]
509
+ new_outputs = (
510
+ *old_outputs[-num_fw_outputs:],
511
+ *old_outputs[:-num_fw_outputs],
512
+ )
513
+ new_outputs = [env[n] if n else None for n in new_outputs]
514
+ new_graph.output(tuple(new_outputs))
515
+ else:
516
+ env[node] = new_graph.node_copy(node, lambda n: env[n])
517
+ env[node].meta = copy.copy(node.meta)
518
+
519
+ new_graph.lint()
520
+
521
+ out = torch.fx.GraphModule(mod, new_graph)
522
+ return out
523
+
524
+ new_hop_graphs: dict[str, InvokeSubgraphHopGraphs] = defaultdict(
525
+ lambda: InvokeSubgraphHopGraphs()
526
+ )
527
+
528
+ # Step 1 - Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` This is
529
+ # easy to do for `invoke_subgraph` HOP. During the Autograd dispatch key
530
+ # tracing, we have put the joint_hop_graph in the backward hop graph itself.
531
+ # So to recover the joint_hop_gm, we just have to look at the backward
532
+ # HOP graphs.
533
+ # So we will merge step 1 and step 2 in this next section
534
+
535
+ # Save the fw and bwd hop nodes. We will later in-place modify the graph
536
+ # using these nodes.
537
+ fw_hop_nodes = []
538
+ bw_hop_nodes = []
539
+ for node in joint_gm.graph.nodes:
540
+ if (
541
+ node.op == "call_function"
542
+ and node.target is invoke_subgraph
543
+ and isinstance(node.args[1], str)
544
+ ):
545
+ if node.args[1].startswith("fw"):
546
+ fw_hop_nodes.append(node)
547
+ elif node.args[1].startswith("bw"):
548
+ bw_hop_nodes.append(node)
549
+
550
+ if not bw_hop_nodes:
551
+ return joint_gm
552
+
553
+ assert len(fw_hop_nodes) == len(bw_hop_nodes)
554
+
555
+ # Create a bw to hop node mapping. This helps us in identifying the bw and
556
+ # fw subgraph pairs without relying on the identifier. This is important
557
+ # because we can have different subgraphs for bwd for same subgraph in the
558
+ # fwd because of differing strides in the backward.
559
+ bw_to_fw_hop_node = dict(zip(list(reversed(bw_hop_nodes)), fw_hop_nodes))
560
+
561
+ for node in bw_hop_nodes:
562
+ identifier = node.args[1].removeprefix("bw")
563
+
564
+ # If partitioning already done for this identifier, skip. This saves
565
+ # redundant joint graph passes for same subgraphs.
566
+ if new_hop_graphs[identifier].partitioning_done:
567
+ continue
568
+
569
+ # Collect some information from the forward hop graph
570
+ fw_hop_node = bw_to_fw_hop_node[node]
571
+ fw_hop_gm = getattr(joint_gm, fw_hop_node.args[0].target)
572
+ assert isinstance(fw_hop_gm, torch.fx.GraphModule)
573
+ num_fw_inputs = num_inputs(fw_hop_gm)
574
+ num_fw_outputs = num_outputs(fw_hop_gm)
575
+ new_hop_graphs[identifier].old_num_fw_inputs = num_fw_inputs
576
+ new_hop_graphs[identifier].old_num_fw_outputs = num_fw_outputs
577
+
578
+ # Step 1) - Get the `joint_hop_gm`. As mentioned earlier, the
579
+ # backward graph is the joint graph.
580
+ joint_hop_gm = getattr(joint_gm, node.args[0].target)
581
+ assert isinstance(joint_hop_gm, torch.fx.GraphModule)
582
+
583
+ # Prepare the graph for the partitioner
584
+ joint_hop_gm = prepare_for_partitioner(
585
+ joint_hop_gm, num_fw_inputs, num_fw_outputs
586
+ )
587
+
588
+ # TODO: invoke_subgraph should track which of its inputs static indices
589
+ # so it can propagate them to the partitioner (and use in cudagraphs)
590
+ static_lifetime_input_indices: list[int] = []
591
+ # Step 2) and 3) - Run joint graph passes and partitioner
592
+ new_fw_hop_gm, new_bw_hop_gm = aot_config.partition_fn(
593
+ joint_hop_gm,
594
+ [],
595
+ num_fwd_outputs=num_fw_outputs,
596
+ static_lifetime_input_indices=static_lifetime_input_indices,
597
+ )
598
+
599
+ # Save the new forward and backward graph modules
600
+ new_hop_graphs[identifier].new_fw_hop_gm = new_fw_hop_gm
601
+ new_hop_graphs[identifier].new_bw_hop_gm = new_bw_hop_gm
602
+
603
+ # Save the number of symints and saved tensors
604
+ new_fw_out_nodes = new_fw_hop_gm.graph.find_nodes(op="output")[0].args[0]
605
+ extra_outputs = new_fw_out_nodes[num_fw_outputs:]
606
+ symint_outputs = [n for n in extra_outputs if is_sym_node(n)]
607
+
608
+ new_hop_graphs[identifier].new_num_sym_nodes = len(symint_outputs)
609
+ new_hop_graphs[identifier].new_num_saved_nodes = len(extra_outputs) - len(
610
+ symint_outputs
611
+ )
612
+
613
+ new_hop_graphs[identifier].partitioning_done = True
614
+
615
+ # Step 3) Restitch the new fw and bw graphs back into the main graph.
616
+ #
617
+ # This is a very mechanical process. There are a quite a few pieces that we
618
+ # need to connect together to make it work. Lets try to understand the
619
+ # problem statement first.
620
+ #
621
+ # For the forward graph, the signature of the old_fw_hop_gm is
622
+ # inputs - (*primals)
623
+ # outputs - (*fw_outs)
624
+ # Now the signature of the new_fw_hop_gm is
625
+ # inputs - (*primals) -- This is same
626
+ # outputs - (*fw_outs, *saved_tensors) - This is different
627
+ # At a high level, this is an easy transformation, in the new graph we just
628
+ # have to replace the old_fw_hop_gm with the new_fw_hop_gm. Everything else
629
+ # falls into place, because the input signature (i.e. args) is same. And
630
+ # even though output signature is different, fw_outs are still at the same
631
+ # indexes as before. So the forward of the `joint_gm` works nicely.
632
+ #
633
+ # Now, lets look at the backward hop graph. Old signature
634
+ # inputs - (*primals, *tangents)
635
+ # outputs - (*grad_outs, *fw_outs)
636
+ # New signature
637
+ # inputs - (*saved_tensors, *tangents) -- Different
638
+ # outputs - (*grad_outs) -- Different
639
+ # Here both input and output signature change. The output signature handling
640
+ # is quite easy because the grads_out are sitting at the right place, so we
641
+ # dont have to do anything.
642
+ #
643
+ # For the input signature, we have to collect the saved tensors from the
644
+ # corresponding forward graph output. We collect all saved_tensors when we
645
+ # see the forward graph, and save it into a map and then later use it during
646
+ # the backward.
647
+
648
+ # The stack of fw_nodes for invoke_subgraph HOP. There is an implicit
649
+ # assumption about the graph structure, i.e., if we have hop1, hop2, hop3,
650
+ # ... in the forward part of the joint graph, we will have .., hop3, hop2,
651
+ # hop1 order for the backward. This structure allows us to just use a stack
652
+ # to collect all the information that we need to pass from the forward hop
653
+ # node to the corresponding backward node.
654
+
655
+ already_added_new_hop_mods = set()
656
+
657
+ def add_new_hop_gm(new_subgraph_mod, name):
658
+ new_subgraph_attr_name = f"partitioned_{name}"
659
+ if new_subgraph_attr_name in already_added_new_hop_mods:
660
+ return new_subgraph_attr_name
661
+
662
+ joint_gm.register_module(new_subgraph_attr_name, new_subgraph_mod)
663
+ already_added_new_hop_mods.add(new_subgraph_attr_name)
664
+ return new_subgraph_attr_name
665
+
666
+ def propagate_meta_info(new_hop_gm, new_call_function_node, old_call_function_node):
667
+ # Copy all the fields from the old call_function node. And then override
668
+ # the `val` meta field with the outputs of new_hop_gm.
669
+ new_call_function_node.meta = copy.copy(old_call_function_node.meta)
670
+
671
+ output = new_hop_gm.graph.find_nodes(op="output")[0]
672
+ out_example_vals = [n.meta["val"] if n else None for n in output.args[0]]
673
+ new_call_function_node.meta["val"] = tuple(out_example_vals)
674
+
675
+ for bw_node in reversed(bw_hop_nodes):
676
+ identifier = bw_node.args[1].removeprefix("bw")
677
+
678
+ # Make changes to the corresponding fw and bw node pair simultaneously.
679
+ # The removes the need of any bookkeeping.
680
+
681
+ # Fw node changes
682
+ # Insert the new_fw_hop_gm. This is straightforward. Get the
683
+ # new_fw_hop_gm, insert the hop_gm as a get_attr fw_node, and then
684
+ # add a call_function fw_node. Additionally, also use getitem
685
+ # call_functions to collect the saved_tensor nodes
686
+
687
+ fw_node = bw_to_fw_hop_node[bw_node]
688
+ new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm
689
+ assert new_fw_hop_gm is not None
690
+
691
+ old_num_fw_outputs = new_hop_graphs[identifier].old_num_fw_outputs
692
+ new_num_sym_nodes = new_hop_graphs[identifier].new_num_sym_nodes
693
+ new_num_saved_nodes = new_hop_graphs[identifier].new_num_saved_nodes
694
+ assert old_num_fw_outputs is not None
695
+ assert new_num_sym_nodes is not None
696
+ assert new_num_saved_nodes is not None
697
+ total_outputs = old_num_fw_outputs + new_num_saved_nodes + new_num_sym_nodes
698
+
699
+ extra_fw_outputs = []
700
+
701
+ # Insert the new_fw_hop_gm into the joint_gm
702
+ with joint_gm.graph.inserting_after(fw_node):
703
+ new_fw_mod_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}")
704
+ new_fw_mod_attr = joint_gm.graph.get_attr(new_fw_mod_attr_name)
705
+
706
+ # new_hop_fw_gm output signature is (*fw_outs, *saved_tensors)
707
+ with joint_gm.graph.inserting_after(new_fw_mod_attr):
708
+ new_fw_node = joint_gm.graph.call_function(
709
+ the_function=invoke_subgraph,
710
+ args=(
711
+ new_fw_mod_attr,
712
+ new_fw_mod_attr_name,
713
+ *fw_node.args[2:],
714
+ ),
715
+ )
716
+ propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node)
717
+
718
+ # old_num_fw_outputs = (*fw_outs)
719
+ # new_num_fw_outputs = (*fw_outs, *saved_tensors, *sym_nodes)
720
+ with joint_gm.graph.inserting_after(new_fw_node):
721
+ for fw_out_idx in range(old_num_fw_outputs, total_outputs):
722
+ saved_tensor_node = joint_gm.graph.call_function(
723
+ the_function=operator.getitem, args=(new_fw_node, fw_out_idx)
724
+ )
725
+ saved_tensor_node.meta = copy.copy(new_fw_node.meta)
726
+ saved_tensor_node.meta["val"] = new_fw_node.meta["val"][fw_out_idx]
727
+ extra_fw_outputs.append(saved_tensor_node)
728
+
729
+ fw_node.replace_all_uses_with(new_fw_node)
730
+ joint_gm.graph.erase_node(fw_node)
731
+
732
+ # Bw node changes
733
+ # Prepare the operands for the bwd graph
734
+ # Old bw graph signature : (*primals, *tangents)
735
+ # New signature will be : (*sym_nodes, *saved_tensors, *tangents)
736
+ # We have already collected the saved_tensors in the forward hop processing.
737
+
738
+ # extra_fw_outputs are in the order (*saved_nodes, *sym_nodes).
739
+ # Partitioner has this quirk where the backward wants sym_nodes
740
+ # first. So extract the sym and saved nodes.
741
+
742
+ new_bw_hop_gm = new_hop_graphs[identifier].new_bw_hop_gm
743
+ assert new_bw_hop_gm is not None
744
+
745
+ saved_tensor_nodes = extra_fw_outputs[:new_num_saved_nodes]
746
+ sym_nodes = extra_fw_outputs[new_num_saved_nodes:]
747
+
748
+ num_primals = new_hop_graphs[identifier].old_num_fw_inputs
749
+ assert num_primals is not None
750
+ tangents = list(bw_node.args[2 + num_primals :])
751
+ operands = sym_nodes + saved_tensor_nodes + tangents
752
+
753
+ # Insert the new_bw_hop_gm into the joint_gm
754
+ with joint_gm.graph.inserting_after(bw_node):
755
+ new_bw_mod_attr_name = add_new_hop_gm(new_bw_hop_gm, bw_node.args[1])
756
+ new_bw_mod_attr = joint_gm.graph.get_attr(new_bw_mod_attr_name)
757
+
758
+ with joint_gm.graph.inserting_after(new_bw_mod_attr):
759
+ new_bw_node = joint_gm.graph.call_function(
760
+ the_function=invoke_subgraph,
761
+ args=(
762
+ new_bw_mod_attr,
763
+ new_bw_mod_attr_name,
764
+ *operands,
765
+ ),
766
+ )
767
+ propagate_meta_info(new_bw_hop_gm, new_bw_node, bw_node)
768
+ # Since the partitioner is run after the graph passes, we have lost
769
+ # the eager information and cannot faithfully extract the eager
770
+ # inputs for the new partitioned backward graph. For the forward
771
+ # graph, it was fine because the input signature remains same.
772
+ new_bw_node.meta.pop("eager_input_vals", None)
773
+
774
+ bw_node.replace_all_uses_with(new_bw_node)
775
+ joint_gm.graph.erase_node(bw_node)
776
+
777
+ joint_gm.graph.eliminate_dead_code()
778
+ joint_gm.graph.lint()
779
+ joint_gm.recompile()
780
+ return joint_gm
781
+
782
+
783
+ def maybe_log_graph(
784
+ gm,
785
+ graph_name,
786
+ aot_config,
787
+ structured_log_prefix_fn,
788
+ out_structured_logs: Optional[list[str]] = None,
789
+ ):
790
+ if not aot_config.enable_log:
791
+ return
792
+ aot_graphs_log.debug(
793
+ "%s",
794
+ lazy_format_graph_code(
795
+ f"{graph_name}",
796
+ gm,
797
+ aot_config.aot_id,
798
+ include_stride=True,
799
+ include_device=True,
800
+ colored=True,
801
+ ),
802
+ )
803
+
804
+ def gm_str_fn() -> str:
805
+ return gm.print_readable(
806
+ print_output=False, include_stride=True, include_device=True
807
+ )
808
+
809
+ if out_structured_logs is not None:
810
+ out_structured_logs.append(f"{structured_log_prefix_fn()}:{gm_str_fn()}")
811
+ else:
812
+ trace_structured(
813
+ f"{structured_log_prefix_fn()}",
814
+ payload_fn=lambda: gm_str_fn(),
815
+ )
816
+
817
+
818
+ def create_wrap_fn(fn, args):
819
+ from functools import wraps
820
+
821
+ from torch.fx.experimental.proxy_tensor import maybe_enable_thunkify
822
+
823
+ from .functional_utils import from_fun, has_data_mutation, to_fun
824
+
825
+ def assert_no_mutation(t):
826
+ assert not has_data_mutation(
827
+ t
828
+ ), "Saved tensors hooks with inputs mutations are not allowed"
829
+
830
+ @wraps(fn)
831
+ def _wrapper(*args):
832
+ with maybe_enable_thunkify():
833
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
834
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
835
+ )
836
+
837
+ with disable_above:
838
+ f_args = pytree.tree_map(to_fun, args)
839
+ f_outs = fn(*f_args)
840
+ pytree.tree_map(assert_no_mutation, f_args)
841
+ return pytree.tree_map(from_fun, f_outs)
842
+
843
+ return _wrapper, args
844
+
845
+
846
+ def prepare_hook_gm(aot_config, fn, args):
847
+ from torch._functorch._aot_autograd.dispatch_and_compile_graph import _create_graph
848
+
849
+ fn, args = create_wrap_fn(fn, args)
850
+ gm = _create_graph(fn, args, aot_config=aot_config)
851
+ return gm
852
+
853
+
854
+ # Inline Autograd saved_tensors_hooks into epilogue of forward graph
855
+ # and prologue of backward graph.
856
+ # This changes forward graph outputs and inputs.
857
+ # Pack hook can return tensors, sym scalars, constants.
858
+ # All tensors to save for backward will be grouped together at front.
859
+ # Sym scalars grouped on another end. Constants are inlined in the graph.
860
+ def maybe_inline_graph_saved_tensors_hooks(
861
+ fw_module,
862
+ bw_module,
863
+ num_inner_fwd_outputs,
864
+ inner_meta,
865
+ aot_config,
866
+ static_input_indices,
867
+ ):
868
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
869
+ return
870
+
871
+ get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks
872
+ are_inline_hooks = (
873
+ torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable
874
+ )
875
+
876
+ hooks = get_hooks()
877
+ if not are_inline_hooks(hooks):
878
+ return
879
+
880
+ pack_hook_gm, unpack_hook_gm = hooks
881
+
882
+ structured_logs: list[str] = []
883
+ maybe_log_graph(
884
+ fw_module,
885
+ "Forward graph pre saved_tensors_hooks inlining",
886
+ aot_config,
887
+ lambda: "aot_forward_graph_pre_saved_tensors_hooks",
888
+ structured_logs,
889
+ )
890
+ maybe_log_graph(
891
+ bw_module,
892
+ "Backward graph pre saved_tensors_hooks inlining",
893
+ aot_config,
894
+ lambda: "aot_backward_graph_pre_saved_tensors_hooks",
895
+ structured_logs,
896
+ )
897
+ fw_g = fw_module.graph
898
+ bw_g = bw_module.graph
899
+
900
+ fw_g_names = {node.name for node in fw_g.nodes}
901
+ bw_g_names = {node.name for node in bw_g.nodes}
902
+
903
+ def _gen_unused_name(candidate: str):
904
+ c = candidate
905
+ i = 0
906
+ while c in fw_g_names or c in bw_g_names:
907
+ c = f"{candidate}_{i}"
908
+ i = i + 1
909
+ return c
910
+
911
+ bw_g_inputs = bw_g.find_nodes(op="placeholder")
912
+
913
+ fw_out_n = fw_g.output_node()
914
+ fw_outs = fw_out_n.args[0] # type: ignore[var-annotated]
915
+ fw_outs_inner_set = set(fw_outs[:num_inner_fwd_outputs])
916
+ fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
917
+ fw_outs_packed_tensors = [] # type: ignore[var-annotated]
918
+ fw_outs_packed_syms = [] # type: ignore[var-annotated]
919
+
920
+ # The main use case for saved_tensors_hooks is activation quantization,
921
+ # for memory usage optimization.
922
+ # Desired behavior is to quantize saved activations to free the original saved tensor.
923
+ # Saved nodes may include forward inputs, outputs, parameters.
924
+ # They may be held by something else and will not be deallocated after quantization.
925
+ # Donated buffers are intermediates in the graph invisible for the user,
926
+ # this guarantees that they can be deallocated.
927
+ # Using this as a default behavior to select saved nodes to apply hooks.
928
+ # There is also a config to apply hooks for all saved nodes without any filtering.
929
+ # The plan is to propagate meta about the source of the saved node to the user hook function.
930
+ mode = torch._functorch.config.saved_tensors_hooks_filtering_mode
931
+ allow_set = None
932
+ exclude_set = None
933
+
934
+ if mode == "donated":
935
+ # collect_bw_donated_buffer_idxs requires inner_meta to have num_symints_saved_for_bw
936
+ inner_meta.num_symints_saved_for_bw = len(
937
+ [n for n in fw_outs_saved_for_bw if is_sym_node(n)]
938
+ )
939
+ bw_donated_idxs = collect_bw_donated_buffer_idxs(
940
+ fw_module,
941
+ bw_module,
942
+ inner_meta,
943
+ )
944
+ fw_donated_idxs = [
945
+ i - inner_meta.num_symints_saved_for_bw for i in bw_donated_idxs
946
+ ]
947
+ allow_set = {fw_outs_saved_for_bw[i].name for i in fw_donated_idxs}
948
+ elif mode == "no_static":
949
+ fw_g_inputs = fw_g.find_nodes(op="placeholder")
950
+ exclude_set = {fw_g_inputs[i].name for i in static_input_indices}
951
+
952
+ if (allow_set is not None) and (not allow_set):
953
+ # This means we have empty whitelist,
954
+ # No donated (intermediate) saved.
955
+ # Do not do anything in this case
956
+ return
957
+
958
+ if aot_config.enable_log:
959
+ structured_logs.append(f"fw_outs_saved_for_bw:{fw_outs_saved_for_bw}")
960
+ structured_logs.append(f"mode:{mode}")
961
+ structured_logs.append(f"allow_set:{allow_set}")
962
+ structured_logs.append(f"exclude_set:{exclude_set}")
963
+
964
+ for saved in fw_outs_saved_for_bw:
965
+ if ((allow_set is not None) and (saved.name not in allow_set)) or (
966
+ (exclude_set is not None) and (saved.name in exclude_set)
967
+ ):
968
+ if isinstance(saved.meta["val"], torch.Tensor):
969
+ fw_outs_packed_tensors.append(saved)
970
+ continue
971
+
972
+ val = saved.meta["val"]
973
+ if not isinstance(val, torch.Tensor):
974
+ continue
975
+
976
+ pack_out_val = pack_hook_gm(val)
977
+
978
+ requires_sc_handling = any(
979
+ is_traceable_wrapper_subclass(x) for x in pytree.tree_leaves(pack_out_val)
980
+ )
981
+ if requires_sc_handling:
982
+ raise NotImplementedError(
983
+ "Tensor subclasses in GraphModule saved tensors hooks are not supported"
984
+ "You can workaround it by manually returning subclass's inner tensors"
985
+ " in the pack hook, and reconstructing the subclass in the unpack hook"
986
+ )
987
+
988
+ pack_gm = prepare_hook_gm(aot_config, pack_hook_gm, (val,))
989
+ pack_g = pack_gm.graph
990
+ maybe_log_graph(
991
+ pack_gm,
992
+ f"saved_tensors_pack_hook {saved.name}",
993
+ aot_config,
994
+ lambda: f"aot_saved_tensors_hooks_pack {saved.name}",
995
+ structured_logs,
996
+ )
997
+ pack_out_val = pack_gm(val)
998
+
999
+ # Install pack hook graph as eiplogue of fw_module.
1000
+ # Saved tensor output becomes input of pack hook graph.
1001
+ # Replace saved tensor output with pack hook graph output.
1002
+ # Outputs symbolic scalars, tensors are accumulated separately.
1003
+ # Then in forward outputs and backward inputs installed in order
1004
+ # sym_scalars, packed_saved_tensors.
1005
+ # Keeping all tensors together allows to preserve
1006
+ # the same identification at runtime,
1007
+ # updating only number of saved sym_scalars and tensors.
1008
+ pack_g_inputs = pack_g.find_nodes(op="placeholder")
1009
+ assert len(pack_g_inputs) == 1
1010
+ env = {pack_g_inputs[0]: saved}
1011
+ fw_pack_out_args = None
1012
+ with fw_g.inserting_before(fw_out_n):
1013
+ for node in pack_g.nodes:
1014
+ if node.op == "placeholder":
1015
+ continue
1016
+ new_n = fw_g.node_copy(node, lambda n: env[n])
1017
+ fw_g_names.add(new_n.name)
1018
+ env[node] = new_n
1019
+ # Output node is temporarily copied to have remapped arguments.
1020
+ # Removed in the end.
1021
+ if node.op == "output":
1022
+ fw_pack_out_args = new_n.args[0]
1023
+ fw_g.erase_node(new_n)
1024
+
1025
+ env.clear()
1026
+ assert fw_pack_out_args
1027
+ fw_outs_bw_ins_node_names = []
1028
+ for out_idx, _n in enumerate(pytree.tree_leaves(fw_pack_out_args)):
1029
+ if not isinstance(_n, torch.fx.Node):
1030
+ fw_outs_bw_ins_node_names.append("")
1031
+ continue
1032
+
1033
+ # This happens when hook is noop and it is either user input or user output.
1034
+ # Do not do anything with this node.
1035
+ if _n.op == "placeholder" or _n in fw_outs_inner_set:
1036
+ # This means the hook returned input primals unchanged
1037
+ # Do not rename in this case.
1038
+ n = _n
1039
+ new_node_name = _n.name
1040
+ fw_outs_bw_ins_node_names.append(new_node_name)
1041
+ else:
1042
+ # We can not specify desired name in node_copy.
1043
+ # Copying node manually to set specifc name,
1044
+ # to have matching fw_outs, bw_inputs names.
1045
+ new_node_name = _gen_unused_name(f"{saved.name}_hook_{out_idx}")
1046
+ with fw_g.inserting_before(_n):
1047
+ n = fw_g.create_node(
1048
+ _n.op,
1049
+ _n.target,
1050
+ _n.args,
1051
+ _n.kwargs,
1052
+ name=new_node_name,
1053
+ )
1054
+ assert n.name == new_node_name
1055
+ fw_outs_bw_ins_node_names.append(new_node_name)
1056
+ n.meta = copy.copy(_n.meta)
1057
+ _n.replace_all_uses_with(n)
1058
+ fw_g.erase_node(_n)
1059
+ if isinstance(n.meta["val"], torch.Tensor):
1060
+ fw_outs_packed_tensors.append(n)
1061
+ elif is_sym_node(n):
1062
+ fw_outs_packed_syms.append(n)
1063
+
1064
+ # Install unpack hook graph as a prologue of backward graph
1065
+ # Saved tensors inputs are replaced with packed tensors and packed sym scalars.
1066
+ # The saved tensors inputs usages in the graph are replaced with unpack hook graph outputs.
1067
+ unpack_gm = prepare_hook_gm(aot_config, unpack_hook_gm, (pack_out_val,))
1068
+ unpack_g = unpack_gm.graph
1069
+ maybe_log_graph(
1070
+ unpack_gm,
1071
+ f"saved_tensors_unpack_hook {saved.name}",
1072
+ aot_config,
1073
+ lambda: f"aot_saved_tensors_hooks_unpack {saved.name}",
1074
+ structured_logs,
1075
+ )
1076
+
1077
+ def find_saved_in_bw_inputs(bw_inputs):
1078
+ for n in bw_inputs:
1079
+ if n.name == saved.name:
1080
+ return n
1081
+
1082
+ bw_g_input = find_saved_in_bw_inputs(bw_g_inputs)
1083
+ assert bw_g_input
1084
+ original_bw_g_input_users = list(bw_g_input.users.keys())
1085
+ bw_g_input_used_directly = False
1086
+
1087
+ # Replace backward graph saved tensor input with copy of pack graph outputs
1088
+ # All non-Tensor, non-symscalars outputs are constanted.
1089
+
1090
+ unpack_g_inputs = unpack_g.find_nodes(op="placeholder")
1091
+ env = {}
1092
+ for out_idx, (unp_in_n, out_n, val) in enumerate(
1093
+ zip(
1094
+ unpack_g_inputs,
1095
+ pytree.tree_leaves(fw_pack_out_args),
1096
+ pytree.tree_leaves(pack_out_val),
1097
+ )
1098
+ ):
1099
+ is_sym = isinstance(val, py_sym_types)
1100
+ if isinstance(val, torch.Tensor) or is_sym:
1101
+ # We want forward_outputs names to match backward_inputs,
1102
+ # Potentially backward may already have "{saved.name}_hook_{idx}",
1103
+ # In this case fx.Graph will add suffix.
1104
+ new_node_name = fw_outs_bw_ins_node_names[out_idx]
1105
+ if bw_g_input.name == new_node_name:
1106
+ env[unp_in_n] = bw_g_input
1107
+ bw_g_input_used_directly = True
1108
+ else:
1109
+ # Backward calling convention: ctx_symints,ctx_saved_tensors
1110
+ # Inserting packed sym scalars before first saved tensor input.
1111
+ # Inserting packed tensors before last saved tensor input.
1112
+ # Saved tensor inputs between them will be removed.
1113
+ with bw_g.inserting_before(
1114
+ bw_g_inputs[0]
1115
+ ) if is_sym else bw_g.inserting_before(bw_g_input):
1116
+ new_n = bw_g.placeholder(new_node_name)
1117
+ assert new_n.name == new_node_name
1118
+ new_n.meta = copy.copy(out_n.meta)
1119
+ env[unp_in_n] = new_n
1120
+ else:
1121
+ # Inline values of non-Tensor, non-SymScalars
1122
+ env[unp_in_n] = val
1123
+
1124
+ # Inserting unpack hook after placeholders.
1125
+ bw_unpack_out_n = None
1126
+ with bw_g.inserting_before(bw_g_inputs[-1].next):
1127
+ for node in unpack_g.nodes:
1128
+ if node.op == "placeholder":
1129
+ continue
1130
+ new_n = bw_g.node_copy(node, lambda n: env[n])
1131
+ bw_g_names.add(new_n.name)
1132
+ env[node] = new_n
1133
+ # Temporary insert output, to have remapped by node_copy args.
1134
+ # Removed in the end.
1135
+ if node.op == "output":
1136
+ bw_unpack_out_n = new_n
1137
+
1138
+ assert bw_unpack_out_n
1139
+ _leaves = pytree.tree_leaves(bw_unpack_out_n.args)
1140
+ assert len(_leaves) == 1
1141
+ unpack_saved_tensor_n = _leaves[0]
1142
+
1143
+ if not bw_g_input_used_directly:
1144
+ bw_g_input.replace_all_uses_with(unpack_saved_tensor_n)
1145
+ bw_g.erase_node(bw_g_input)
1146
+ else:
1147
+ # Keep usages of bw_g_input in inserted unpacked hook graph.
1148
+ # Replace other usages of bw_g_input with unpack_saved_tensor_n.
1149
+ from torch._C import _fx_map_arg
1150
+
1151
+ def maybe_replace_node(n):
1152
+ return unpack_saved_tensor_n if n == bw_g_input else n
1153
+
1154
+ for use_node in original_bw_g_input_users:
1155
+ new_args = _fx_map_arg(use_node.args, maybe_replace_node)
1156
+ new_kwargs = _fx_map_arg(use_node.kwargs, maybe_replace_node)
1157
+ assert isinstance(new_args, tuple)
1158
+ assert isinstance(new_kwargs, dict)
1159
+ use_node._update_args_kwargs(new_args, new_kwargs)
1160
+ bw_g.erase_node(bw_unpack_out_n)
1161
+
1162
+ # Changing forward graph outputs,
1163
+ # Inserting packed_tensors and packed_syms on the place of saved tensors.
1164
+ # Packed sym_scalars are together with saved symints
1165
+ symint_outs_saved_for_bw = [n for n in fw_outs_saved_for_bw if is_sym_node(n)]
1166
+ fw_new_outs = pytree.tree_leaves(
1167
+ (
1168
+ fw_outs[:num_inner_fwd_outputs],
1169
+ fw_outs_packed_tensors,
1170
+ fw_outs_packed_syms,
1171
+ symint_outs_saved_for_bw,
1172
+ )
1173
+ )
1174
+ fw_out_n.args = (tuple(fw_new_outs),)
1175
+
1176
+ # Assert that saved tensors and symints in forward outputs are aligned with backward inputs
1177
+ _fw_n = num_inner_fwd_outputs
1178
+ _fw_num_t = len(fw_outs_packed_tensors)
1179
+ _fw_num_s = len(fw_outs_packed_syms) + len(symint_outs_saved_for_bw)
1180
+ fw_outs_saved_tensors = fw_new_outs[_fw_n : _fw_n + _fw_num_t]
1181
+ fw_outs_saved_syms = fw_new_outs[_fw_n + _fw_num_t :]
1182
+ bw_new_ins = list(bw_g.find_nodes(op="placeholder"))
1183
+ bw_ins_saved_syms = bw_new_ins[:_fw_num_s]
1184
+ bw_ins_saved_tensors = bw_new_ins[_fw_num_s : _fw_num_s + _fw_num_t]
1185
+
1186
+ fw_t_names = [n.name for n in fw_outs_saved_tensors]
1187
+ bw_t_names = [n.name for n in bw_ins_saved_tensors]
1188
+ fw_s_names = [n.name for n in fw_outs_saved_syms]
1189
+ bw_s_names = [n.name for n in bw_ins_saved_syms]
1190
+
1191
+ def _log_structured_logs():
1192
+ if not aot_config.enable_log:
1193
+ return
1194
+
1195
+ trace_structured(
1196
+ "artifact",
1197
+ metadata_fn=lambda: {
1198
+ "name": "aot_saved_tensors_hooks_graphs",
1199
+ "encoding": "string",
1200
+ },
1201
+ payload_fn=lambda: "\n".join(structured_logs),
1202
+ )
1203
+
1204
+ if aot_config.enable_log:
1205
+ structured_logs.append(
1206
+ f"fw_outs[:num_inner_fwd_outputs]:{fw_outs[:num_inner_fwd_outputs]}"
1207
+ )
1208
+ structured_logs.append(f"fw_outs_packed_tensors:{fw_outs_packed_tensors}")
1209
+ structured_logs.append(f"fw_t_names:{fw_t_names}")
1210
+ structured_logs.append(f"bw_t_names:{bw_t_names}")
1211
+ structured_logs.append(f"fw_s_names:{fw_s_names}")
1212
+ structured_logs.append(f"bw_s_names:{bw_s_names}")
1213
+ structured_logs.append(f"\nfw_g_pre_assert:{fw_g}")
1214
+ structured_logs.append(f"\nbw_g_pre_assert:{bw_g}")
1215
+ maybe_log_graph(
1216
+ fw_module,
1217
+ "Forward graph after transform pre-assert",
1218
+ aot_config,
1219
+ lambda: "aot_forward_graph_pre_assert_saved_tensors_hooks",
1220
+ structured_logs,
1221
+ )
1222
+ maybe_log_graph(
1223
+ bw_module,
1224
+ "Backward graph after transform pre-assert",
1225
+ aot_config,
1226
+ lambda: "aot_backward_graph_pre_assert_saved_tensors_hooks",
1227
+ structured_logs,
1228
+ )
1229
+ _log_structured_logs()
1230
+
1231
+ assert fw_t_names == bw_t_names
1232
+ assert fw_s_names == bw_s_names
1233
+
1234
+ fw_g.lint()
1235
+ bw_g.lint()
1236
+ fw_module.recompile()
1237
+ bw_module.recompile()
1238
+
1239
+
1240
+ def aot_dispatch_autograd(
1241
+ flat_fn,
1242
+ flat_args: list[Any],
1243
+ aot_config: AOTConfig,
1244
+ *,
1245
+ fw_metadata: ViewAndMutationMeta,
1246
+ ) -> DispatchReturn:
1247
+ """
1248
+ Autograd logic. Generates a joint graph, partitions it, manipulates the input with various wrappers,
1249
+ and returns a wrapped torch.autograd.Function with a forward and backward.
1250
+ """
1251
+ wrappers = _create_wrappers_for_dispatch(needs_autograd=True)
1252
+ flat_fn, flat_args, fw_metadata = pre_compile(
1253
+ wrappers,
1254
+ flat_fn,
1255
+ flat_args,
1256
+ aot_config,
1257
+ fw_metadata=fw_metadata,
1258
+ )
1259
+
1260
+ fw_metadata.deterministic = torch.are_deterministic_algorithms_enabled()
1261
+ with dynamo_timed("aot_trace_joint_graph", log_pt2_compile_event=True):
1262
+ fx_g, joint_inputs, maybe_subclass_meta = aot_dispatch_autograd_graph(
1263
+ flat_fn, flat_args, aot_config, fw_metadata=fw_metadata
1264
+ )
1265
+
1266
+ # Copied from aot_dispatch_autograd_graph.
1267
+ disable_amp = torch._C._is_any_autocast_enabled()
1268
+ joint_graph_str = None
1269
+ if aot_config.enable_log:
1270
+ aot_joint_log.info(
1271
+ "%s",
1272
+ lazy_format_graph_code(
1273
+ "Joint graph",
1274
+ fx_g,
1275
+ aot_config.aot_id,
1276
+ include_stride=True,
1277
+ include_device=True,
1278
+ colored=True,
1279
+ ),
1280
+ )
1281
+ joint_graph_str = fx_g.print_readable(
1282
+ print_output=False, include_stride=True, include_device=True
1283
+ )
1284
+ trace_structured(
1285
+ "aot_joint_graph",
1286
+ payload_fn=lambda: joint_graph_str,
1287
+ )
1288
+
1289
+ with torch.no_grad():
1290
+ inner_meta = (
1291
+ fw_metadata
1292
+ if maybe_subclass_meta is None
1293
+ else maybe_subclass_meta.fw_metadata
1294
+ )
1295
+ with track_graph_compiling(aot_config, "joint"):
1296
+ # See Note: [Partitioner handling for Subclasses, Part 1]
1297
+ # See Note: [Recomputing subclass mutation handling]
1298
+ mutated_inp_runtime_indices = (
1299
+ compute_inner_mutated_inp_indices_from_subclass_meta(
1300
+ fw_metadata, inner_meta
1301
+ )
1302
+ )
1303
+ num_tokens = len(fw_metadata.tokens)
1304
+ num_mutated_inp_runtime_indices = len(mutated_inp_runtime_indices)
1305
+ num_inner_fwd_outputs = (
1306
+ num_mutated_inp_runtime_indices
1307
+ + inner_meta.num_outputs
1308
+ + inner_meta.num_intermediate_bases
1309
+ + inner_meta.num_outputs_rng_offset
1310
+ + num_tokens # See Note [Side-Effectful Tokens in AOTAutograd]
1311
+ )
1312
+ fake_mode = detect_fake_mode()
1313
+ fx_g = run_joint_graph_passes_on_hops(fx_g, joint_inputs, aot_config)
1314
+
1315
+ # TODO(anijain2305) - Add tensorify_python_scalars to the HOP graph passes.
1316
+ if fake_mode is not None and fake_mode.shape_env is not None:
1317
+ tensorify_python_scalars(fx_g, fake_mode.shape_env, fake_mode)
1318
+
1319
+ static_lifetime_input_indices = fw_metadata.static_input_indices
1320
+ fw_module, bw_module = aot_config.partition_fn(
1321
+ fx_g,
1322
+ joint_inputs,
1323
+ num_fwd_outputs=num_inner_fwd_outputs,
1324
+ static_lifetime_input_indices=static_lifetime_input_indices,
1325
+ )
1326
+ rng_states = [
1327
+ n
1328
+ for n in fw_module.graph.find_nodes(op="placeholder")
1329
+ if "fwd_rng_state" in n.name
1330
+ ]
1331
+ fw_metadata.num_graphsafe_rng_states = len(rng_states)
1332
+ if rng_states:
1333
+ fw_metadata.graphsafe_rng_state_index = (
1334
+ rng_states[0].meta["val"].device.index
1335
+ )
1336
+
1337
+ # See Note [Side-Effectful Tokens in AOTAutograd]
1338
+ if config.unlift_effect_tokens and (
1339
+ num_tokens > 0 or fw_metadata.num_backward_tokens > 0
1340
+ ):
1341
+ unlift_tokens(fw_module, fw_metadata, aot_config, bw_module)
1342
+
1343
+ num_inner_fwd_outputs -= num_tokens
1344
+ joint_inputs = (
1345
+ joint_inputs[0][num_tokens:],
1346
+ joint_inputs[1],
1347
+ )
1348
+
1349
+ maybe_inline_graph_saved_tensors_hooks(
1350
+ fw_module,
1351
+ bw_module,
1352
+ num_inner_fwd_outputs,
1353
+ inner_meta,
1354
+ aot_config,
1355
+ fw_metadata.static_input_indices,
1356
+ )
1357
+ static_lifetime_input_indices = fw_metadata.static_input_indices
1358
+
1359
+ fw_outs = next(iter(fw_module.graph.find_nodes(op="output"))).args[0]
1360
+ # we only need to bookkeep the symints that are saved for bw, not any symints
1361
+ # the user forward might have returned in its own output
1362
+ fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
1363
+ num_fw_outs_saved_for_bw = len(fw_outs_saved_for_bw)
1364
+ symint_outs_saved_for_bw = []
1365
+ for idx, node in enumerate(fw_outs_saved_for_bw):
1366
+ if is_sym_node(node):
1367
+ symint_outs_saved_for_bw.append(node)
1368
+ elif (
1369
+ isinstance(node, torch.fx.Node)
1370
+ and "val" in getattr(node, "meta", {})
1371
+ and isinstance(node.meta["val"], FakeTensor)
1372
+ ):
1373
+ # record dynamic tensor activations
1374
+ dynamic_dims: set[int] = {
1375
+ dim
1376
+ for dim, size in enumerate(node.meta["val"].shape)
1377
+ if not isinstance(size, int)
1378
+ }
1379
+ if dynamic_dims:
1380
+ fw_metadata.dynamic_saved_tensors_idxs[idx] = dynamic_dims
1381
+
1382
+ fw_metadata.num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1383
+ inner_meta.num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1384
+ num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1385
+ if torch._functorch.config.donated_buffer:
1386
+ fw_metadata.bw_donated_idxs = collect_bw_donated_buffer_idxs(
1387
+ fw_module,
1388
+ bw_module,
1389
+ inner_meta,
1390
+ )
1391
+ inner_meta.bw_donated_idxs = fw_metadata.bw_donated_idxs
1392
+
1393
+ if aot_config.enable_log:
1394
+ trace_structured(
1395
+ "artifact",
1396
+ metadata_fn=lambda: {
1397
+ "name": "torch._functorch.config",
1398
+ "encoding": "string",
1399
+ },
1400
+ payload_fn=lambda: torch._functorch.config.get_config_copy(),
1401
+ )
1402
+ aot_graphs_log.info(
1403
+ "aot_config id: %s, fw_metadata=%s, inner_meta=%s",
1404
+ str(aot_config.aot_id),
1405
+ str(fw_metadata),
1406
+ str(inner_meta),
1407
+ )
1408
+
1409
+ # Note [Detaching inputs that never need gradients]
1410
+ # See https://github.com/pytorch/pytorch/issues/97745
1411
+ # Suppose we have a function like this that we want to compile:
1412
+ #
1413
+ # def f(x, y):
1414
+ # return torch.mul(x, y.detach())
1415
+ #
1416
+ # What gradients should we compute for x and y?
1417
+ # By default, AOTAutograd will compute a gradient for **every** input that requires gradients,
1418
+ # and so we'll compute:
1419
+ # x_grad_input = y
1420
+ # y_grad_input = None
1421
+ # Does this preserve the semantics of eager mode?
1422
+ # Unfortunately, no.
1423
+ # Doing the above will cause autograd to **continue** to backprop the autograd tape
1424
+ # that was generated from constructing y.
1425
+ #
1426
+ # This is **different** from what would have happened in eager mode.
1427
+ # In eager mode, if we backprop through the output of this function, autograd will only traverse
1428
+ # the bit of the autograd tape corresponding to "x".
1429
+ # In particular, if a user had previously backpropped through y's autograd tape,
1430
+ # And then they try to backprop through the output of the above function,
1431
+ # then we'll hit the dreaded "Trying to backward through the graph a second time" error.
1432
+ #
1433
+ # You might think: If autograd sees that a gradient is None, shouldn't it stop early,
1434
+ # instead of continuing the backprop through the ancestors of that node in the graph?
1435
+ #
1436
+ # Autograd has two passes:
1437
+ # (1) a first pass that traverses the autograd graph and figures out which nodes need to be executed
1438
+ # (2) a second pass that actually goes ahead and executes each node when it becomes ready,
1439
+ # propagating gradients
1440
+ # By the time we're executing a node and we see that it produces a None, the set of nodes to execute
1441
+ # is already locked-in.
1442
+ #
1443
+ # The fix: instead, we can recognize statically that the graph we're compiling will never contribute
1444
+ # gradients to y, and prevent autograd from trying to traverse y's autograd tape at all.
1445
+ # We can do this by manually detach'ing y before sending it through the `CompiledFunction`.
1446
+ #
1447
+ # Note that this solution is not bulletproof.
1448
+ # It's possible to construct a case where eager may or may not have have tried to autograd through y,
1449
+ # depending on the actual grad_outputs that were passed in during the backward.
1450
+ # There is no easy fix for this: the simplest fix would be to run with `retain_graph=True`,
1451
+ # allowing autograd to re-use the graph.
1452
+ #
1453
+ # An example of this case is:
1454
+ # def f(x):
1455
+ # return x.detach() * 2, x * 3
1456
+ # If we were to only backprop through outs[0], in eager, we would stop
1457
+ # If we backward only on the first output, we shouldn't send a grad through x.
1458
+ # But the custom autograd function doesn't know that: it will materialize zero grads for x * 3
1459
+ # and we will end up with a zero grad at x.
1460
+ # If we later backprop through the second output, this will also require backprop'ing through x.
1461
+ # Meaning we'll need to use `retain_graph=True` to be able to backprop through x the second time.
1462
+ _indices_of_inps_to_detach: list[int] = []
1463
+
1464
+ # reversed() since we expect output at end of graph
1465
+ bw_output = next(reversed(bw_module.graph.find_nodes(op="output")))
1466
+ bw_outs: Sequence[torch.fx.Node] = bw_output.args[0] # type: ignore[assignment]
1467
+
1468
+ # TODO: we should apply the below "detach inputs if their gradients are statically known to be None"
1469
+ # optimization even if we have subclass inputs/outputs (we do not handle this today).
1470
+ # Computing which our our inputs get None gradients is a bit more complicated,
1471
+ # if any of our inputs are subclasses. Why?
1472
+ # (a) we need to make sure that we call .detach() on the input subclasses, since autograd sees subclasses.
1473
+ # (b) The grad_outputs that we AOT computed in our backward graph are the desugared tensor tensors,
1474
+ # so we need to figure out which subclass fw inputs they map to.
1475
+ if maybe_subclass_meta is None:
1476
+ num_backward_tokens: int = inner_meta.num_backward_tokens
1477
+ assert (
1478
+ len(bw_outs)
1479
+ == len(fw_metadata.input_info)
1480
+ + inner_meta.num_outputs_rng_offset
1481
+ + num_backward_tokens
1482
+ )
1483
+ bw_outs_no_rng_no_tokens = bw_outs
1484
+ if (inner_meta.num_outputs_rng_offset + num_backward_tokens) > 0:
1485
+ bw_outs_no_rng_no_tokens = bw_outs[
1486
+ : -(inner_meta.num_outputs_rng_offset + num_backward_tokens)
1487
+ ]
1488
+ assert len(bw_outs_no_rng_no_tokens) == len(fw_metadata.input_info)
1489
+
1490
+ for i, (bw_out) in enumerate(bw_outs_no_rng_no_tokens):
1491
+ # If our input experiences a metadata mutation inside the graph (e.g. set_()),
1492
+ # we *must* not detach, otherwise it will be the detach'd input that gets the metadata mutation
1493
+ metadata_mutation_in_graph = (
1494
+ fw_metadata.input_info[i].mutation_type
1495
+ == MutationType.MUTATED_IN_GRAPH
1496
+ and fw_metadata.input_info[i].mutates_storage_metadata
1497
+ )
1498
+ is_non_leaf = (
1499
+ fw_metadata.input_info[i].requires_grad
1500
+ and not fw_metadata.input_info[i].is_leaf
1501
+ )
1502
+ if bw_out is None and not metadata_mutation_in_graph and is_non_leaf:
1503
+ _indices_of_inps_to_detach.append(i)
1504
+
1505
+ fw_module_str = None
1506
+ bw_module_str = None
1507
+ if aot_config.enable_log:
1508
+ aot_graphs_log.info(
1509
+ "%s",
1510
+ lazy_format_graph_code(
1511
+ "Forward graph",
1512
+ fw_module,
1513
+ aot_config.aot_id,
1514
+ include_stride=True,
1515
+ include_device=True,
1516
+ colored=True,
1517
+ ),
1518
+ )
1519
+ aot_graphs_log.info(
1520
+ "%s",
1521
+ lazy_format_graph_code(
1522
+ "Backward graph",
1523
+ bw_module,
1524
+ aot_config.aot_id,
1525
+ include_stride=True,
1526
+ include_device=True,
1527
+ colored=True,
1528
+ ),
1529
+ )
1530
+ fw_module_str = fw_module.print_readable(
1531
+ print_output=False, include_stride=True, include_device=True
1532
+ )
1533
+ bw_module_str = bw_module.print_readable(
1534
+ print_output=False, include_stride=True, include_device=True
1535
+ )
1536
+
1537
+ trace_structured(
1538
+ "artifact",
1539
+ metadata_fn=lambda: {
1540
+ "name": "aot_forward_graph_fw_metadata",
1541
+ "encoding": "string",
1542
+ },
1543
+ payload_fn=lambda: dataclass_repr(fw_metadata),
1544
+ )
1545
+ if maybe_subclass_meta is not None:
1546
+ trace_structured(
1547
+ "artifact",
1548
+ metadata_fn=lambda: {
1549
+ "name": "aot_forward_graph_fw_subclass_metadata",
1550
+ "encoding": "string",
1551
+ },
1552
+ payload_fn=lambda: dataclass_repr(maybe_subclass_meta),
1553
+ )
1554
+
1555
+ trace_structured(
1556
+ "aot_forward_graph",
1557
+ payload_fn=lambda: fw_module_str,
1558
+ )
1559
+ trace_structured(
1560
+ "aot_backward_graph",
1561
+ payload_fn=lambda: bw_module_str,
1562
+ )
1563
+
1564
+ # AMP is already traced out in joint graph. we do not wish to reapply it accidentally
1565
+ # in the compiler.
1566
+ with track_graph_compiling(aot_config, "forward"), torch._C._DisableAutocast():
1567
+ # flat_args at this point might still be subclasses-
1568
+ # make sure to pass the unwrapped fake tensors into the compiler!
1569
+ adjusted_flat_args = joint_inputs[0]
1570
+
1571
+ fakified_out_wrapper = FakifiedOutWrapper()
1572
+ (
1573
+ fw_module,
1574
+ adjusted_flat_args,
1575
+ fw_metadata,
1576
+ ) = fakified_out_wrapper.pre_compile(
1577
+ fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
1578
+ )
1579
+
1580
+ functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper(
1581
+ return_new_outs=False
1582
+ )
1583
+
1584
+ if rng_states:
1585
+ index = fw_metadata.graphsafe_rng_state_index
1586
+ assert index is not None
1587
+ rng_states = [
1588
+ get_cuda_generator_meta_val(index)
1589
+ for _ in range(fw_metadata.num_graphsafe_rng_states)
1590
+ ]
1591
+ adjusted_flat_args.extend(rng_states) # type: ignore[arg-type]
1592
+
1593
+ (
1594
+ fw_module,
1595
+ adjusted_flat_args,
1596
+ fw_metadata,
1597
+ ) = functionalized_rng_wrapper.pre_compile(
1598
+ fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
1599
+ )
1600
+ if tracing_context := torch._guards.TracingContext.try_get():
1601
+ tracing_context.fw_metadata = inner_meta
1602
+
1603
+ with TracingContext.report_output_strides() as fwd_output_strides:
1604
+ compiled_fw_func = aot_config.fw_compiler(fw_module, adjusted_flat_args)
1605
+
1606
+ if not getattr(compiled_fw_func, "_boxed_call", False):
1607
+ compiled_fw_func = make_boxed_func(compiled_fw_func)
1608
+
1609
+ if fakified_out_wrapper.needs_post_compile:
1610
+ fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides)
1611
+
1612
+ compiled_fw_func = EffectTokensWrapper().post_compile(
1613
+ compiled_fw_func,
1614
+ aot_config,
1615
+ runtime_metadata=fw_metadata,
1616
+ )
1617
+
1618
+ compiled_fw_func = AOTDispatchSubclassWrapper(
1619
+ fw_only=None,
1620
+ trace_joint=False,
1621
+ maybe_subclass_meta=maybe_subclass_meta,
1622
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1623
+ ).post_compile(
1624
+ compiled_fw_func,
1625
+ aot_config, # not used
1626
+ runtime_metadata=fw_metadata,
1627
+ )
1628
+
1629
+ compiled_fw_func = functionalized_rng_wrapper.post_compile(
1630
+ compiled_fw_func, aot_config, runtime_metadata=fw_metadata
1631
+ )
1632
+ compiled_fw_func = fakified_out_wrapper.post_compile(
1633
+ compiled_fw_func,
1634
+ aot_config,
1635
+ runtime_metadata=fw_metadata,
1636
+ )
1637
+
1638
+ # NB: It's important to compile backwards ahead of time, as this may
1639
+ # add extra guards which we need to apply to the Dynamo cache at
1640
+ # forwards
1641
+ with track_graph_compiling(aot_config, "backward"), torch._C._DisableAutocast():
1642
+ placeholder_list = fx_placeholder_vals(bw_module)
1643
+
1644
+ forward_saved_for_backwards_strides = None
1645
+ if fwd_output_strides is not None:
1646
+ forward_saved_for_backwards_strides = fwd_output_strides[
1647
+ inner_meta.tensors_saved_for_backwards_slice
1648
+ ]
1649
+
1650
+ # saved activations can have different stride to eager if
1651
+ # the compiler does layout optimization. We should restride the
1652
+ # tensor passed in for compiling the backward graph using the
1653
+ # saved tensor's stride.
1654
+ for i in range(len(placeholder_list)):
1655
+ ph_arg = placeholder_list[i]
1656
+ if not isinstance(ph_arg, torch.Tensor):
1657
+ continue
1658
+
1659
+ if forward_saved_for_backwards_strides is None:
1660
+ continue
1661
+
1662
+ real_stride = None
1663
+ # Per all_args calling convention
1664
+ j = i - num_symints_saved_for_bw
1665
+ if 0 <= j < len(forward_saved_for_backwards_strides):
1666
+ real_stride = forward_saved_for_backwards_strides[j]
1667
+ if real_stride is None:
1668
+ continue
1669
+
1670
+ # Comparing ph_arg.stride() with real_stride directly may
1671
+ # cause dynamic dimensions in ph_arg being specialized to static
1672
+ # value. Using the hints to avoid that.
1673
+ if _get_symint_hints(ph_arg.stride()) != real_stride:
1674
+ # Note that here we use the stride of the real tensor to
1675
+ # restride a FakeTensor. This does not cause trouble
1676
+ # for dynamic shape since this code path only get
1677
+ # executed if layout optimization is enabled. And we
1678
+ # disable layout optimization for dynamic shape right
1679
+ # now.
1680
+ #
1681
+ # A solution that decide stride order based on real
1682
+ # tensor's stride and then apply that stride order to
1683
+ # the FakeTensor does not work smoothly since some
1684
+ # tensor's layout is not 'dense'. E.g. mixnet_l has a
1685
+ # tensor with size [8, 64, 112, 112] and strides
1686
+ # (2408448, 1, 21504, 192). The solution mentioned will
1687
+ # decide a stride of (802816, 1, 7168, 64) for this
1688
+ # tensor which is wrong.
1689
+ placeholder_list[i] = ph_arg.as_strided(ph_arg.size(), real_stride)
1690
+
1691
+ compiled_bw_func = None
1692
+ if num_symints_saved_for_bw > 0:
1693
+ try:
1694
+ # See Note: [Backward graph lazy lowering]
1695
+ with torch._subclasses.fake_tensor.unset_fake_temporarily():
1696
+ # If bw_module contains lifted constants, they will be real tensors stored as
1697
+ # GraphModule. Deepcopying tensors under fake mode is not supported and will
1698
+ # raise when attempting to set storage.
1699
+ bw_module_copy = copy.deepcopy(bw_module)
1700
+ compiled_bw_func = aot_config.bw_compiler(
1701
+ bw_module_copy, placeholder_list
1702
+ )
1703
+ del bw_module_copy
1704
+ except Exception as e:
1705
+ exc = e
1706
+ trace_structured(
1707
+ "artifact",
1708
+ metadata_fn=lambda: {
1709
+ "name": "eager_compile_backwards_failure",
1710
+ "encoding": "string",
1711
+ },
1712
+ payload_fn=lambda: "\n".join(
1713
+ traceback.format_exception(
1714
+ type(exc), exc, exc.__traceback__
1715
+ )
1716
+ ),
1717
+ )
1718
+ log.warning(
1719
+ "failed to eagerly compile backwards for dynamic, suppressing in case backwards not needed",
1720
+ exc_info=True,
1721
+ )
1722
+ # Compiled autograd will run the bw_module in the backward pass,
1723
+ # so recompilation need happen anyway if the backward pass is ever
1724
+ # called.
1725
+ #
1726
+ # The reason we do the GraphModule recompilation here is because
1727
+ # the lazy recompilation will cause issue in the backward pass
1728
+ # with compiled autograd.
1729
+ #
1730
+ # Do the _LazyGraphModule.force_recompile here rather than when
1731
+ # bw_module is first generated by the partitioner because the bw_module.recompile
1732
+ # may be called in some code path later and cause the _LazyGraphModule.forward
1733
+ # becomes the lazy version again. One example is when dynamic shape is enabled
1734
+ # upfront, the bw_compiler will be called above which can cause extra
1735
+ # graph module recompilation on bw_module.
1736
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
1737
+ from torch.fx._lazy_graph_module import _LazyGraphModule
1738
+
1739
+ _LazyGraphModule.force_recompile(bw_module)
1740
+
1741
+ saved_context = TracingContext.try_get()
1742
+ saved_compile_context = CompileContext.try_get()
1743
+
1744
+ backward_state_indices = [
1745
+ idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState)
1746
+ ]
1747
+ assert len(backward_state_indices) <= 1
1748
+
1749
+ lazy_backward_info = AutogradLazyBackwardCompileInfo(
1750
+ bw_module,
1751
+ placeholder_list,
1752
+ saved_context,
1753
+ saved_compile_context,
1754
+ )
1755
+
1756
+ make_runtime_safe(fw_metadata, maybe_subclass_meta)
1757
+
1758
+ try_save_cache_entry: Optional[Callable] = None
1759
+
1760
+ if aot_config.cache_info is not None:
1761
+ forward_time_taken_ns = time.time_ns() - aot_config.cache_info.start_time_ns
1762
+
1763
+ # NB: aot_config here is technically not needed as an argument: we could just
1764
+ # close over aot_config.cache_info, since aot_config never changes.
1765
+ # But closing over random variables is confusing IMO, so I'm leaving it.
1766
+ def try_save_cache_entry( # noqa: F811
1767
+ compiled_bw_func: Callable,
1768
+ bw_module: torch.fx.GraphModule,
1769
+ _fw_metadata: ViewAndMutationMeta,
1770
+ aot_config: AOTConfig,
1771
+ ):
1772
+ fw_key = getattr(compiled_fw_func, "_fx_graph_cache_key", None)
1773
+ bw_key = getattr(compiled_bw_func, "_fx_graph_cache_key", None)
1774
+ cache_info = aot_config.cache_info
1775
+ if cache_info is not None and fw_key and bw_key:
1776
+ assert forward_time_taken_ns is not None
1777
+ # TODO: technically, AOTAutograd does a *little* bit of post processing work
1778
+ # in the backward that isn't measured here. But it's small enough that it's not worth
1779
+ # the complexity of threading a bunch of times through the code, so we
1780
+ # use the compiled_bw_func's inductor compile time instead.
1781
+ # It's possible this changes in the future, in which case we should
1782
+ # update backward_time_taken_ns to be more inclusive
1783
+ backward_time_taken_ns = getattr(compiled_bw_func, "_time_taken_ns", 0)
1784
+
1785
+ aot_forward_graph_str: Optional[str] = fw_module_str
1786
+ aot_backward_graph_str: Optional[str] = bw_module_str
1787
+ aot_joint_graph_str: Optional[str] = joint_graph_str
1788
+ guards_expr = AOTAutogradCache.generate_guards_expression(cache_info)
1789
+
1790
+ entry = AOTAutogradCache.make_entry(
1791
+ compiled_fw_func, # type: ignore[arg-type]
1792
+ compiled_bw_func, # type: ignore[arg-type]
1793
+ aot_joint_graph_str,
1794
+ aot_forward_graph_str,
1795
+ aot_backward_graph_str,
1796
+ _fw_metadata,
1797
+ wrappers,
1798
+ maybe_subclass_meta,
1799
+ num_fw_outs_saved_for_bw,
1800
+ _indices_of_inps_to_detach,
1801
+ forward_time_taken_ns,
1802
+ backward_time_taken_ns,
1803
+ sanitized_aot_config=sanitize_aot_config(aot_config),
1804
+ guards_expr=guards_expr,
1805
+ backward_state_indices=backward_state_indices,
1806
+ num_symints_saved_for_bw=num_symints_saved_for_bw,
1807
+ serialized_bw_module=serialize_graph_module(bw_module),
1808
+ )
1809
+ remote = should_use_remote_autograd_cache()
1810
+ AOTAutogradCache.save(cache_info.cache_key, entry, remote)
1811
+
1812
+ if compiled_bw_func is not None:
1813
+ # If we already compiled the backward, we save its cache entry now
1814
+ try_save_cache_entry(compiled_bw_func, bw_module, fw_metadata, aot_config)
1815
+ try_save_cache_entry = None
1816
+
1817
+ compiled_fn = AOTDispatchAutograd.post_compile(
1818
+ compiled_fw_func,
1819
+ compiled_bw_func,
1820
+ maybe_subclass_meta,
1821
+ num_symints_saved_for_bw,
1822
+ backward_state_indices,
1823
+ disable_amp,
1824
+ _indices_of_inps_to_detach,
1825
+ lazy_backward_info,
1826
+ aot_config,
1827
+ fw_metadata=fw_metadata,
1828
+ try_save_cache_entry=try_save_cache_entry,
1829
+ )
1830
+
1831
+ if config.debug_assert:
1832
+ flat_requires_grad: list[Optional[bool]] = [
1833
+ a.requires_grad if isinstance(a, Tensor) else None for a in flat_args
1834
+ ]
1835
+ compiled_fn = DebugAssertWrapper(
1836
+ flat_requires_grad=flat_requires_grad
1837
+ ).post_compile(compiled_fn, aot_config, runtime_metadata=fw_metadata)
1838
+
1839
+ compiled_fn = post_compile(
1840
+ wrappers,
1841
+ compiled_fn,
1842
+ aot_config,
1843
+ runtime_metadata=fw_metadata,
1844
+ )
1845
+ return compiled_fn
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/logging_utils.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Contains utils for logging in AOTAutograd, including managing the names of the graphs under
4
+ compilation, capturing user-friendly tracebacks, and debug messages.
5
+ """
6
+
7
+ import collections
8
+ from contextlib import contextmanager
9
+
10
+ import torch
11
+ import torch.fx.traceback as fx_traceback
12
+
13
+
14
+ # This is a list since looking forward, we can have this arbitrarily nested.
15
+ graph_being_compiled: list[str] = []
16
+ # TODO: It would be nice to reset the numbering every time aot_id goes
17
+ # up, but this is annoying to do right now (because we don't know if
18
+ # an aot_id will come back from the dead), so right now this also happens
19
+ # to be a globally unique number too (at the cost of wobbling if you change
20
+ # how the graphs compile)
21
+ nth_graph: int = 0
22
+ model_name: str = "model"
23
+
24
+
25
+ def set_model_name(name):
26
+ global model_name
27
+ model_name = name
28
+
29
+
30
+ def get_aot_compilation_context() -> tuple[list[str], str, int]:
31
+ return list(graph_being_compiled), model_name, nth_graph
32
+
33
+
34
+ def get_aot_graph_name() -> str:
35
+ """
36
+ Returns the name of the graph being compiled.
37
+ """
38
+ global model_name, graph_being_compiled, nth_graph
39
+ return f"{model_name}__{'_'.join(graph_being_compiled)}_{nth_graph}"
40
+
41
+
42
+ get_graph_being_compiled = get_aot_graph_name
43
+
44
+
45
+ @contextmanager
46
+ def track_graph_compiling(aot_config, graph_name):
47
+ global graph_being_compiled
48
+ # TODO: Don't shove the aot_id in here; set it in the context
49
+ graph_being_compiled = [f"{aot_config.aot_id}_{graph_name}"]
50
+ old_name = None
51
+ if tracing_context := torch._guards.TracingContext.try_get():
52
+ old_name = tracing_context.aot_graph_name
53
+ tracing_context.aot_graph_name = graph_being_compiled
54
+ has_tracing_context = True
55
+ else:
56
+ has_tracing_context = False
57
+ try:
58
+ yield
59
+ finally:
60
+ global nth_graph
61
+ nth_graph += 1
62
+ graph_being_compiled = []
63
+ if has_tracing_context:
64
+ if tracing_context := torch._guards.TracingContext.try_get():
65
+ tracing_context.aot_graph_name = old_name
66
+
67
+
68
+ # Set up hooks so that during backward the fx's stack_trace is properly set
69
+ callback_set = False
70
+
71
+
72
+ def setup_stacktrace_preservation_hooks(roots: list):
73
+ def iter_graph(roots):
74
+ if not roots:
75
+ return
76
+ seen = set()
77
+ q = collections.deque() # type: ignore[var-annotated]
78
+ for node in roots:
79
+ if node is not None and node not in seen:
80
+ seen.add(node)
81
+ q.append(node)
82
+
83
+ while q:
84
+ node = q.popleft()
85
+ for fn, _idx in node.next_functions:
86
+ if fn in seen or fn is None:
87
+ continue
88
+ seen.add(fn)
89
+ q.append(fn)
90
+
91
+ yield node
92
+
93
+ def get_callback(saved_stack_):
94
+ def callback():
95
+ global callback_set
96
+ fx_traceback.set_stack_trace(saved_stack_)
97
+ callback_set = False
98
+
99
+ return callback
100
+
101
+ def get_prehook(stack_, seq_nr):
102
+ def prehook(grad_output):
103
+ global callback_set
104
+
105
+ if not callback_set:
106
+ torch.autograd.variable.Variable._execution_engine.queue_callback( # type: ignore[attr-defined]
107
+ get_callback(fx_traceback.format_stack())
108
+ )
109
+ callback_set = True
110
+
111
+ fx_traceback.set_stack_trace(stack_)
112
+ fx_traceback.set_grad_fn_seq_nr(seq_nr)
113
+
114
+ return prehook
115
+
116
+ def get_posthook(special_stack_, seq_nr):
117
+ def posthook(grad_input, grad_output):
118
+ fx_traceback.set_stack_trace(special_stack_)
119
+ fx_traceback.reset_grad_fn_seq_nr()
120
+
121
+ return posthook
122
+
123
+ for node in iter_graph(roots):
124
+ forward_node_stack = node.metadata.get("traceback_", [])
125
+ node.register_prehook(get_prehook(forward_node_stack, node._sequence_nr()))
126
+
127
+ special_stack = forward_node_stack.copy()
128
+ special_stack.append(
129
+ "Gradient addition node due to multiple use of tensor around:"
130
+ )
131
+ node.register_hook(get_posthook(special_stack, node._sequence_nr()))
132
+
133
+
134
+ def describe_input(i, aot_config):
135
+ if i < aot_config.num_params_buffers:
136
+ return f"parameter/buffer {i}"
137
+ else:
138
+ return f"input {i - aot_config.num_params_buffers}"
139
+
140
+
141
+ def format_guard_bug_msg(aot_config, expected):
142
+ return (
143
+ f"At compilation time, graph {aot_config.aot_id} was compiled under the "
144
+ f"assumption that {expected}, but at runtime this was not the case. "
145
+ "This indicates a guard bug in AOTAutograd or Dynamo, please file a bug to PyTorch."
146
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py ADDED
The diff for this file is too large to render. See raw diff
 
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/schemas.py ADDED
@@ -0,0 +1,968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ The various dataclasses, Enums, namedtuples etc used in AOTAutograd. This includes
4
+ input/output types, metadata, config, function signatures etc.
5
+ """
6
+
7
+ import collections
8
+ import dataclasses
9
+ import functools
10
+ import itertools
11
+ from collections.abc import Iterable, Sequence
12
+ from dataclasses import dataclass, field
13
+ from enum import Enum
14
+ from typing import Any, Callable, NewType, Optional, Union
15
+
16
+ import torch
17
+ import torch.utils._pytree as pytree
18
+ from torch._guards import Source
19
+ from torch._ops import OpOverload
20
+ from torch._subclasses import FakeTensor
21
+ from torch._subclasses.fake_tensor import is_fake
22
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
23
+
24
+ from .. import config
25
+ from .functional_utils import (
26
+ _check_if_mutation_can_be_in_graph,
27
+ FunctionalTensorMetadataEq,
28
+ )
29
+ from .utils import strict_zip
30
+
31
+
32
+ zip = strict_zip
33
+
34
+
35
+ OutputType = Enum(
36
+ "OutputType",
37
+ (
38
+ # output is not an alias
39
+ "non_alias",
40
+ # output aliases an input
41
+ "alias_of_input",
42
+ # output **is** an input tensor
43
+ "is_input",
44
+ # output has a ._base tensor, which is a graph intermediate.
45
+ # We need to return its ._base as a graph output,
46
+ # so its requires_grad info is populated correctly.
47
+ # Instructs the runtime code to regenerate the current output
48
+ # from a base tensor, graph_intermediates[base_idx]
49
+ "alias_of_intermediate_save_as_output",
50
+ # Same as above; but we don't need to explicitly add its ._base
51
+ # as a graph output, because it already **is** a graph output.
52
+ "alias_of_intermediate",
53
+ # Same as above; but the output's ._base is **already** a user output.
54
+ # Instructs the runtime code to regenerate the current output from
55
+ # a base tensor, user_outputs[base_idx]
56
+ "alias_of_intermediate_base_is_user_output",
57
+ # See Note [Intermediate Bases Optimization]
58
+ "unsafe_view_alias",
59
+ # output is an alias, but has a custom autograd.Function backward.
60
+ # In this case, we don't want to do view-replay, since we won't be able to replay the custom function.
61
+ # Instead, we'll treat this output "normally", and trace its backward into the graph.
62
+ "custom_function_view",
63
+ ),
64
+ )
65
+
66
+
67
+ # This class stores info about every user output.
68
+ @dataclass(frozen=True)
69
+ class OutputAliasInfo:
70
+ # Tells us if this output is:
71
+ # (1) a regular (non-aliased) output
72
+ # (2) an alias of a forward input
73
+ # (3) **is** a forward input (special case of "alias_of_input")
74
+ # (4) an alias of an intermediate (aka an alias of an output of the inner traced forward)
75
+ # (5) an alias of an intermediate, that explicitly requires returning the intermediate
76
+ # as a graph output
77
+ # (6) an alias of an intermediate, where that intermediate is also a user output
78
+ output_type: OutputType
79
+ # The raw type of the output (torch.Tensor, SymInt, etc)
80
+ raw_type: type
81
+ # If (1) above, then
82
+ # - base_idx is None
83
+ # If (2) or (3) above, then
84
+ # - Tells us that the base of this alias is user_fwd_input[base_idx]
85
+ # (This is an index into the inputs *before* we make synthetic bases)
86
+ # If (4) or (5) above, then
87
+ # - Tells us that the base of this alias is output_graph_intermediates[base_idx]
88
+ # here, this refers to the index of the *direct* traced
89
+ # If (6) above, then:
90
+ # - Tells us that the base of this alias is output_user_fwds[base_idx]
91
+ # here, this refers to the index of the *direct* traced
92
+ base_idx: Optional[int]
93
+ # If it is a Tensor, what the dynamic dims are (otherwise is None)
94
+ dynamic_dims: Optional[set[int]]
95
+ # requires_grad
96
+ requires_grad: bool
97
+ # FunctionalTensorWrapper that represents this output.
98
+ #
99
+ # Provides us the means to replay views from it.
100
+ #
101
+ # We need to wrap the actual FunctionalTensorWrapper with this class so that
102
+ # we only compare the tensor's metadata. That's because with the transformations
103
+ # of the model throughout AOTAutograd, the sequence of ViewMeta and the base
104
+ # tensor might change.
105
+ functional_tensor: Optional[FunctionalTensorMetadataEq] = None
106
+
107
+
108
+ class MutationType(Enum):
109
+ NOT_MUTATED = 1
110
+ MUTATED_IN_GRAPH = 2
111
+ MUTATED_OUT_GRAPH = 3
112
+
113
+
114
+ # This class tells us info about user inputs.
115
+ @dataclass(frozen=True)
116
+ class InputAliasInfo:
117
+ is_leaf: bool
118
+ mutates_data: bool
119
+ mutates_metadata: bool
120
+ mutations_hidden_from_autograd: bool
121
+ mutations_under_no_grad_or_inference_mode: bool
122
+ mutation_inductor_storage_resize: bool
123
+ mutates_storage_metadata: bool
124
+ requires_grad: bool
125
+ keep_input_mutations: bool
126
+
127
+ def __post_init__(self):
128
+ if self.mutates_storage_metadata:
129
+ # For convenience, we guarantee that this is always true.
130
+ # In practice, If we call .set_(), then at runtime there is no need
131
+ # to additionally fix up the tensor metadata, since our runtime
132
+ # call to inp.set_(updated_inp) will already have the right metadata
133
+ assert self.mutates_metadata
134
+
135
+ @functools.cached_property
136
+ def mutation_type(self) -> MutationType:
137
+ if (
138
+ (not self.mutates_data)
139
+ and (not self.mutates_metadata)
140
+ and not (self.mutation_inductor_storage_resize)
141
+ ):
142
+ return MutationType.NOT_MUTATED
143
+
144
+ if _check_if_mutation_can_be_in_graph(
145
+ self.keep_input_mutations,
146
+ self.mutates_data,
147
+ self.mutates_metadata,
148
+ self.mutations_hidden_from_autograd,
149
+ self.mutations_under_no_grad_or_inference_mode,
150
+ self.mutates_storage_metadata,
151
+ self.mutation_inductor_storage_resize,
152
+ self.requires_grad,
153
+ ):
154
+ return MutationType.MUTATED_IN_GRAPH
155
+
156
+ return MutationType.MUTATED_OUT_GRAPH
157
+
158
+
159
+ @dataclass
160
+ class MemoryFormatMeta:
161
+ # For static shapes we assume tangents have the same strideness as outputs
162
+ size: Optional[Sequence[int]] = None
163
+ stride: Optional[Sequence[int]] = None
164
+
165
+ # For dynamic shapes we assume the same memory format: contiguous, channels_last etc.
166
+ memory_format: Optional[torch.memory_format] = None
167
+
168
+ @staticmethod
169
+ def from_tensor(t: torch.Tensor) -> Optional["MemoryFormatMeta"]:
170
+ # We only memorize expected memory format for
171
+ # 1. Traceable wrapper subclasses
172
+ # We can not create restrided subclass tensor, as torch.empty_strided works only with dense tensors.
173
+ # 2. Dynamic shape tensors
174
+ # Support for symbolic shapes is not implemented yet.
175
+ use_memory_format: bool = (
176
+ not torch._functorch.config.guess_tangent_strides_as_outputs
177
+ or is_traceable_wrapper_subclass(t)
178
+ )
179
+ if not use_memory_format:
180
+ is_static_shape = True
181
+ for s in itertools.chain(t.shape, t.stride()):
182
+ if not isinstance(s, int):
183
+ is_static_shape = False
184
+ break
185
+
186
+ use_memory_format = not is_static_shape
187
+
188
+ if use_memory_format:
189
+ return MemoryFormatMeta(
190
+ memory_format=torch._prims_common.suggest_memory_format(t),
191
+ )
192
+
193
+ return MemoryFormatMeta(
194
+ size=t.size(),
195
+ stride=t.stride(),
196
+ )
197
+
198
+
199
+ @dataclass
200
+ class PlainTensorMeta:
201
+ unwrapped_idx: int
202
+ memory_format: Optional[MemoryFormatMeta] = None
203
+
204
+
205
+ @dataclass
206
+ class SubclassCreationMeta:
207
+ """
208
+ Used for AOTDispatch.
209
+ This dataclass gives us the information we need to reconstruct a tensor subclass
210
+ from our flat inputs.
211
+ Why is this important? The graph that we'd like to trace out contains flat tensor inputs,
212
+ But the user's original model may have subclass inputs and outputs.
213
+ So we need to wrap/unwrap subclasses as necessary to translate between the user's
214
+ view (subclass inps/outs), and the backend compiler's view (graph with no subclass args).
215
+
216
+ Complications arise mostly from the fact that a subclass can hold more than one inner tensor;
217
+ So for a given subclass input/output, we need to carefully track which indices map
218
+ to the subclass tensor in the corresponding "dense-tensor-only" graph.
219
+ """
220
+
221
+ # In the inner graph that only takes in dense tensor inputs,
222
+ # this maps to the first index of "tensors that should go in this subclass wrapper"
223
+ flat_tensor_start_idx: int
224
+ # arg_count is inclusive of the arg_counts of any
225
+ # inner tensor subclasses: If I have a TwoTensor and
226
+ # both of its inner elements are TwoTensors, then the
227
+ # arg_count of the outer-most sublass will be 4
228
+ arg_count: int
229
+ # Mark where or not symints were included. This flag is only used in one assertion
230
+ # in "wrap_tensor_subclasses"
231
+ included_subclass_symints: bool
232
+ # meta and attrs are produced by the subclass's __tensor_flatten__.
233
+ # We need to keep them around along with outer_size / outer_stride to plumb them
234
+ # into __tensor_unflatten__
235
+ attrs: dict[str, Union["SubclassCreationMeta", PlainTensorMeta]]
236
+ outer_size: Iterable[Union[None, int, torch.SymInt]]
237
+ outer_stride: Iterable[Union[None, int, torch.SymInt]]
238
+ meta: Any
239
+ # Stores the original subclass itself.
240
+ # This is needed because we need the autograd metadata on the original subclass
241
+ # (this is guaranteed to be a wrapper subclass that holds a fake tensor,
242
+ # so holding onto this at runtime shouldn't leak memory)
243
+ # This field is nulled out after calling make_runtime_safe()
244
+ original_subclass: Optional[torch.Tensor]
245
+
246
+ # Used at runtime to determine the subclass type, so we don't need to save the original subclass
247
+ original_subclass_type: Optional[type] = None
248
+ memory_format: Optional[MemoryFormatMeta] = None
249
+
250
+ def compute_outer_size_and_stride(
251
+ self,
252
+ all_args,
253
+ *,
254
+ curr_start_idx: int,
255
+ ):
256
+ from .subclass_utils import compute_symint_placeholders
257
+
258
+ def compute(outer, start_idx):
259
+ placeholders = compute_symint_placeholders(outer)
260
+ has_symbolic = any(placeholders)
261
+
262
+ if has_symbolic:
263
+ start = curr_start_idx
264
+ end = start_idx + sum(placeholders)
265
+ it_args = iter(all_args[start:end])
266
+ it_placeholders = iter(placeholders)
267
+ return pytree.tree_map_only(
268
+ lambda _: next(it_placeholders), lambda _: next(it_args), outer
269
+ ), start + len(placeholders)
270
+ else:
271
+ return outer, start_idx
272
+
273
+ outer_size, next_idx = compute(self.outer_size, curr_start_idx)
274
+ outer_stride, _ = compute(self.outer_stride, next_idx)
275
+ return outer_size, outer_stride
276
+
277
+ def creation_fn(
278
+ self,
279
+ all_args,
280
+ *,
281
+ is_runtime: bool,
282
+ ):
283
+ inner_tensors = {}
284
+
285
+ curr_start_idx = self.flat_tensor_start_idx
286
+ for attr, creation_meta in self.attrs.items():
287
+ if isinstance(creation_meta, PlainTensorMeta):
288
+ subclass = all_args[curr_start_idx]
289
+ curr_start_idx += 1
290
+ else:
291
+ subclass = creation_meta.creation_fn(
292
+ all_args,
293
+ is_runtime=is_runtime,
294
+ )
295
+ curr_start_idx += creation_meta.arg_count
296
+ inner_tensors[attr] = subclass
297
+
298
+ if is_runtime:
299
+ assert self.original_subclass_type is not None
300
+ original_subclass_type = self.original_subclass_type
301
+ else:
302
+ original_subclass_type = type(self.original_subclass)
303
+
304
+ if is_runtime:
305
+ outer_size, outer_stride = self.compute_outer_size_and_stride(
306
+ all_args,
307
+ curr_start_idx=curr_start_idx,
308
+ )
309
+ else:
310
+ outer_size, outer_stride = self.outer_size, self.outer_stride
311
+
312
+ rebuilt = original_subclass_type.__tensor_unflatten__( # type: ignore[attr-defined]
313
+ inner_tensors, self.meta, outer_size, outer_stride
314
+ )
315
+
316
+ if not is_runtime:
317
+ # After wrapping up the inner dense tensors into a subclass, we need to make sure that our new wrapper
318
+ # has correct autograd metadata, since we'll be tracing through the autograd engine with the subclass.
319
+ # We don't trace through the autograd engine at runtime though, so no need
320
+ # to compute this extra metadata then!
321
+ torch._mirror_autograd_meta_to(self.original_subclass, rebuilt) # type: ignore[attr-defined]
322
+
323
+ return rebuilt
324
+
325
+ def make_runtime_safe(self):
326
+ def _make_size_runtime_safe(x: Union[None, int, torch.SymInt]) -> Optional[int]:
327
+ dummy = -1
328
+ if isinstance(x, torch.SymInt):
329
+ # Replace nested ints by a dummy value (-1) as NJT ignores
330
+ # the outer_size/outer_stride at runtime.
331
+ return dummy if x.node.is_nested_int() else None
332
+ return x
333
+
334
+ assert self.original_subclass is not None
335
+ self.original_subclass_type = type(self.original_subclass)
336
+ self.original_subclass = None
337
+
338
+ # Note: NJT outer_size in AOTDispatcher
339
+ # `_make_size_runtime_safe` replaces any nested int with a dummy value (-1)
340
+ # to prevent serializing a SymInt at runtime. Internally, nested tensor __tensor_unflatten__
341
+ # is designed to safely ignore this dummy value.
342
+ # For more details, see: https://github.com/pytorch/pytorch/blob/5141ade8e30c64e873e14dcc8de233da45d15025/torch/nested/_internal/nested_tensor.py#L266-L299 # noqa: B950
343
+ self.outer_size = tuple(map(_make_size_runtime_safe, self.outer_size))
344
+ self.outer_stride = tuple(map(_make_size_runtime_safe, self.outer_stride))
345
+
346
+ # Recurse on nested subclass info
347
+ for creation_meta in self.attrs.values():
348
+ if isinstance(creation_meta, SubclassCreationMeta):
349
+ creation_meta.make_runtime_safe()
350
+
351
+ def __post_init__(self):
352
+ # sanity assert to make sure we don't leak memory
353
+ assert is_fake(self.original_subclass)
354
+
355
+
356
+ # This class encapsulates all aliasing + mutation info we need about the forward graph
357
+ # See a more detailed overview of the edge case handling at
358
+ # https://docs.google.com/document/d/19UoIh_SVrMy_b2Sx5ZaeOJttm6P0Qmyss2rdBuyfoic/edit
359
+ # NOTE: This class is saved in AOTAutogradCache, If you are adding elements, make sure
360
+ # they are covered by warm cache tests.
361
+ @dataclass(eq=False)
362
+ class ViewAndMutationMeta:
363
+ # length = # user inputs
364
+ # This gives us info about every input, and what sort of mutation happened to it (if any)
365
+ input_info: list[InputAliasInfo]
366
+
367
+ # length = # user outputs
368
+ # This gives us info about every output (mostly around whether it aliases other tensors)
369
+ output_info: list[OutputAliasInfo]
370
+
371
+ # length = the number of intermediate bases appended as outputs to the end of the forward graph.
372
+ # Note: this is not necessarily the same thing as:
373
+ # len([x for x in output_info if x.output_type == OutputType.alias_of_intermediate])
374
+ # Because outputs might share a ._base, or an output's ._base might itself be
375
+ # another user output (in both cases, we won't redundantly append bases to the end of the graph)
376
+ num_intermediate_bases: int
377
+
378
+ # For inference only: instructs us to keep data-only input mutations directly in the graph
379
+ keep_input_mutations: bool
380
+
381
+ # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors)
382
+ # + (# intermediate bases)
383
+ # These are the FakeTensor (or potential SymInt) outputs that we traced from our
384
+ # metadata pass of the user's forward function.
385
+ # Their only use today is to pass them as a best-guess for tangents when tracing the joint.
386
+ # Stashing them as part of our "metadata" makes it simpler if we want to run our analysis
387
+ # pass once, and re-use the output throughout AOTAutograd
388
+ traced_tangents: list[Any]
389
+
390
+ # Each of these is a list telling us about subclasses for the inputs/outputs/grad_outs
391
+ # They are used throughout AOTDispatch to tell us how to generate a list of subclass tensors,
392
+ # Given a (potentially larger) list of plain torch tensors.
393
+
394
+ # Taking subclass_inp_meta as an example:
395
+ # subclass_inp_meta[i] = j (an int) tells us:
396
+ # "The i'th user input is not a subclass, and corresponds to inputs[j] of the plain-tensor graph."
397
+ # subclass_inp_meta[i] = SubclassCreationMeta(flat_tensor_start_idx=3, arg_count=2)
398
+ # "The i'th user input is subclass holding two inner tensors, which are
399
+ # inputs[3] and inputs[4] of the plain-tensor graph".
400
+
401
+ # length = # user inputs
402
+ subclass_inp_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
403
+ # So, the full set of outputs to the forward graph looks something like:
404
+ # (*mutated_inps, *user_outs, *intermediate_bases, *saved_for_bw_tensors)
405
+ # where the first 3 of those 4 can be subclasses
406
+ # (but not saved_for_bw tensors, since these are internal to the compiler
407
+ # and not user visible, so there's no point in wrapping/unwrapping them at runtime).
408
+ # This list contains subclass information on all of the fw graph outputs
409
+ # except for saved_for_bw_tensors.
410
+ subclass_fw_graph_out_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
411
+ # length = # backward graph inputs
412
+ subclass_tangent_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
413
+ # TODO: we should kill this
414
+ # (need to default it to not break internal)
415
+ is_train: bool = False
416
+
417
+ # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors)
418
+ # + (# intermediate bases)
419
+ # At runtime, we don't keep the traced_tangents around since they're not serializable.
420
+ # Instead, we keep any necessary subclass metadata necessary about each traced_tangent.
421
+ # This list is generated after calling make_runtime_safe().
422
+ traced_tangent_metas: Optional[list[Any]] = None
423
+
424
+ num_symints_saved_for_bw: Optional[int] = None
425
+
426
+ # The grad_enabled mutation that will be emitted in the runtime_wrapper epilogue
427
+ # NOTE: AOTAutograd will assume that the ambient `is_grad_enabled` is the grad mode
428
+ # that is intended to be in effect prior to running the graph, in keeping with
429
+ # equivalence to eager mode. It is the responsibility of upstream graph acquisition
430
+ # to reset the grad mode to its pre-graph value prior to calling aot_autograd.
431
+ grad_enabled_mutation: Optional[bool] = None
432
+
433
+ # Keeps track of whether `torch.use_deterministic_algorithms` was turned on
434
+ # when the forward was run. If deterministic mode was turned off during the
435
+ # forward, but is turned on during the backward call, then an error is
436
+ # raised
437
+ deterministic: Optional[bool] = None
438
+
439
+ # Keeps track of which input indices store parameters (which we will treat as static)
440
+ static_input_indices: list[int] = field(default_factory=list)
441
+
442
+ # Map of effect type (ex. _EffectType.ORDERED) to token. If there are
443
+ # side-effectful operators, FunctionalTensorMode will populate this
444
+ # dictionary telling us how many tokens we will need during tracing.
445
+ tokens: dict[Any, torch.Tensor] = field(default_factory=dict)
446
+
447
+ # Only filled in if/when we trace the joint function
448
+ # If an input requires grad and is mutated in the backward, it is only safe to keep the mutation
449
+ # in the graph if gradients are disabled while the backward runs
450
+ # (grad mode is disabled by default when users run the backward, but can be turned on with create_graph=True)
451
+ # At runtime during the backward, we use this list of indices to error properly if we find out
452
+ # that it was not safe to include a backward mutation in the graph.
453
+ indices_of_inputs_that_requires_grad_with_mutations_in_bw: list[int] = field(
454
+ default_factory=list
455
+ )
456
+
457
+ # Indexes of saved tensors which are donated buffer.
458
+ # Donated buffer means the tensor is not alias of any forward user input, forward user output,
459
+ # and backward output.
460
+ bw_donated_idxs: Optional[list[int]] = None
461
+
462
+ # Number of tokens used in backward, appended at the end of backward outputs.
463
+ # Filled after tracing joint function.
464
+ num_backward_tokens: int = 0
465
+
466
+ # Number of rng states that will get thread into the forward and backward for
467
+ # cudagraph compatible run_and_save_rng
468
+ num_graphsafe_rng_states: int = 0
469
+
470
+ graphsafe_rng_state_index: Optional[int] = None
471
+
472
+ def __post_init__(self):
473
+ # pre-compute the indices of the inputs that are mutated.
474
+ # When keep_input_mutations is set, we don't need to worry about our epilogue
475
+ # handling data-only mutations, because we keep them directly in the graph.
476
+ mutated_inp_runtime_indices = [
477
+ i
478
+ for i, m in enumerate(self.input_info)
479
+ if (m.mutation_type == MutationType.MUTATED_OUT_GRAPH)
480
+ ]
481
+
482
+ mutated_graph_handled_indices = [
483
+ i
484
+ for i, m in enumerate(self.input_info)
485
+ if m.mutation_type == MutationType.MUTATED_IN_GRAPH
486
+ ]
487
+ self.mutated_graph_handled_indices = mutated_graph_handled_indices
488
+ self.num_mutated_graph_handled_indices = len(self.mutated_graph_handled_indices)
489
+
490
+ mutated_graph_handled_indices_seen_by_autograd = [
491
+ i
492
+ for i in mutated_graph_handled_indices
493
+ if not self.input_info[i].mutations_hidden_from_autograd
494
+ ]
495
+
496
+ self.mutated_graph_handled_indices_seen_by_autograd = (
497
+ mutated_graph_handled_indices_seen_by_autograd
498
+ )
499
+ self.num_mutated_graph_handled_indices_seen_by_autograd = len(
500
+ self.mutated_graph_handled_indices_seen_by_autograd
501
+ )
502
+
503
+ aliased_out_indices = [
504
+ i
505
+ for i, m in enumerate(self.output_info)
506
+ if m.output_type
507
+ not in [
508
+ OutputType.non_alias,
509
+ OutputType.unsafe_view_alias,
510
+ OutputType.custom_function_view,
511
+ ]
512
+ ]
513
+ unsafe_view_out_indices = [
514
+ i
515
+ for i, m in enumerate(self.output_info)
516
+ if m.output_type is OutputType.unsafe_view_alias
517
+ ]
518
+
519
+ # This is pre-computed in post_init for perf.
520
+ # It contains the index of every element
521
+ # of input_info that corresponds to a mutation (data or metadata or both)
522
+ self.mutated_inp_runtime_indices = mutated_inp_runtime_indices
523
+ self.num_mutated_inp_runtime_indices = len(self.mutated_inp_runtime_indices)
524
+
525
+ # This is pre-computed for perf.
526
+ # It contains the index of every element
527
+ # of output_info that corresponds to an alias (either of an input or intermediate)
528
+ self.aliased_out_indices = aliased_out_indices
529
+ self.unsafe_view_out_indices = unsafe_view_out_indices
530
+ self.num_outputs = len(self.output_info)
531
+ self.num_outputs_non_aliased = len(
532
+ [
533
+ x
534
+ for x in self.output_info
535
+ if x.output_type
536
+ in [
537
+ OutputType.non_alias,
538
+ OutputType.unsafe_view_alias,
539
+ OutputType.custom_function_view,
540
+ ]
541
+ ]
542
+ )
543
+ self.num_outputs_aliased_to_inputs = len(
544
+ [
545
+ x
546
+ for x in self.output_info
547
+ if x.output_type
548
+ in [
549
+ OutputType.alias_of_input,
550
+ OutputType.is_input,
551
+ ]
552
+ ]
553
+ )
554
+ self.num_unsafe_view_outputs = len(self.unsafe_view_out_indices)
555
+ self.num_outputs_aliased_to_intermediates = len(
556
+ [
557
+ x
558
+ for x in self.output_info
559
+ if x.output_type
560
+ in [
561
+ OutputType.alias_of_intermediate,
562
+ OutputType.alias_of_intermediate_save_as_output,
563
+ OutputType.alias_of_intermediate_base_is_user_output,
564
+ ]
565
+ ]
566
+ )
567
+ self.num_outputs_aliased = (
568
+ self.num_outputs_aliased_to_inputs
569
+ + self.num_outputs_aliased_to_intermediates
570
+ )
571
+
572
+ # Record dynamic outputs of the Dynamo traced forward graph
573
+ # Mark them as dynamic at the end of the runtime wrapper
574
+ self.dynamic_outputs = any(o.dynamic_dims for o in self.output_info)
575
+
576
+ # Record the indices of dynamic outputs in the partitioned forward graph
577
+ # Mark them as dynamic in the runtime wrapper
578
+ # activation index -> dynamic dims indices
579
+ self.dynamic_saved_tensors_idxs: dict[int, set[int]] = {}
580
+
581
+ # See Note: [AOTAutograd Backward Guards]
582
+ # This is pre-computed for fast asserts on the types of our grad_outputs in the backward.
583
+ # Eventually, we should kill this and replace with real backward guards.
584
+ # (we want to precompute the "runtime" types, so replace FakeTensor with torch.Tensor)
585
+ self.output_types = [
586
+ torch.Tensor if isinstance(x, FakeTensor) else type(x)
587
+ for x in self.traced_tangents
588
+ ]
589
+
590
+ self.is_rng_op_functionalized = config.functionalize_rng_ops
591
+ # All of the above metadata is collected by tracing the fw function.
592
+ # However, extra outputs for rng offsets behave differently. Both fwd
593
+ # and bwd graphs have their own outputs for the total consumed offsets.
594
+ # Unlike mutated inputs, we don't have to worry about sending the right
595
+ # set of tensors between fwd and bwd. Fwd and bwd offsets are
596
+ # independent and simpler to handle. Therefore, we track them
597
+ # separately.
598
+ self.num_outputs_rng_offset = 1 if self.is_rng_op_functionalized else 0
599
+
600
+ # Our forward() returns both (tokens, mutated_inputs, outputs, output_intermediate_bases, saved_tensors, saved_symints)
601
+ # Tokens will be split out before mutations/view handling and we do not count them here.
602
+ self.num_forward_returns = (
603
+ self.num_mutated_inp_runtime_indices
604
+ + self.num_outputs
605
+ + self.num_intermediate_bases
606
+ )
607
+ # In case of functionalization of rng ops, the fw_module returns one
608
+ # additional output for rng offset. This rng offset is used right
609
+ # away to advance the rng state, and is not passed on to the raw
610
+ # outputs. However, we need to know the exact boundary to identify
611
+ # which tensors to be saved for the bwd graph. num_forward captures
612
+ # this information.
613
+ self.num_forward = self.num_forward_returns + self.num_outputs_rng_offset
614
+
615
+ def make_runtime_safe(self):
616
+ """
617
+ There are various fields in ViewAndMutationMeta that aren't serializable. This function is called after all tracing
618
+ is completed to simplify certain fields in the metadata so that they can be safely cached.
619
+
620
+ Doing so may lose information (in the case of traced_tangents), but none of the information is needed at runtime.
621
+ """
622
+ # TODO: This function is only a best effort: there are other fields that may not be cache safe
623
+ # (i.e., there's no guarantee that tensor_flatten() returns a serializable result), or that
624
+ # SubclassCreationMeta is cache safe.
625
+ assert self.traced_tangent_metas is None
626
+
627
+ def extract_metadata(t):
628
+ if isinstance(t, torch.Tensor) and is_traceable_wrapper_subclass(t):
629
+ (inner_tensors, flatten_spec) = t.__tensor_flatten__() # type: ignore[attr-defined]
630
+ # Technically, we only need the flatten_spec, not the inner tensors.
631
+ # However, some Tensor subclasses (like TwoTensor) may have flatten_spec = None.
632
+ # And we want to be able to assert that this metadata is non-None,
633
+ # to distinguish between "this was a tensor subclass with no metadata" vs.
634
+ # "this wasn't a tensor subclass at all".
635
+ return (inner_tensors, flatten_spec)
636
+ else:
637
+ return None
638
+
639
+ self.traced_tangent_metas = [extract_metadata(t) for t in self.traced_tangents]
640
+ # Clear traced tangents at runtime
641
+ self.traced_tangents = []
642
+ new_output_info = []
643
+ for out in self.output_info:
644
+ if config.view_replay_for_aliased_outputs:
645
+ new_out = out
646
+ else:
647
+ # If we're not using view_replay, remove the functional tensor.
648
+ # Functional tensors are unfortunately not serializable,
649
+ # so doing this is required for AOTAutograd caching.
650
+ new_out = dataclasses.replace(out, functional_tensor=None)
651
+ new_output_info.append(new_out)
652
+ self.output_info = new_output_info
653
+ for inp_meta in self.subclass_inp_meta:
654
+ if isinstance(inp_meta, SubclassCreationMeta):
655
+ inp_meta.make_runtime_safe()
656
+ for inp_meta in self.subclass_fw_graph_out_meta:
657
+ if isinstance(inp_meta, SubclassCreationMeta):
658
+ inp_meta.make_runtime_safe()
659
+ for inp_meta in self.subclass_tangent_meta:
660
+ if isinstance(inp_meta, SubclassCreationMeta):
661
+ inp_meta.make_runtime_safe()
662
+
663
+ @property
664
+ def tensors_saved_for_backwards_slice(self):
665
+ assert self.num_symints_saved_for_bw is not None
666
+ if self.num_symints_saved_for_bw > 0:
667
+ return slice(self.num_forward, -self.num_symints_saved_for_bw)
668
+ else:
669
+ return slice(self.num_forward, None)
670
+
671
+ @property
672
+ def symints_saved_for_backwards_slice(self):
673
+ assert self.num_symints_saved_for_bw is not None
674
+ if self.num_symints_saved_for_bw > 0:
675
+ return slice(-self.num_symints_saved_for_bw, None)
676
+ else:
677
+ return slice(0, 0) # empty slice
678
+
679
+ def __eq__(self, other):
680
+ if not isinstance(other, ViewAndMutationMeta):
681
+ return NotImplemented
682
+ return (
683
+ self.input_info == other.input_info
684
+ and self.output_info == other.output_info
685
+ and self.num_intermediate_bases == other.num_intermediate_bases
686
+ and self.keep_input_mutations == other.keep_input_mutations
687
+ and self.is_rng_op_functionalized == other.is_rng_op_functionalized
688
+ and self.num_outputs_rng_offset == other.num_outputs_rng_offset
689
+ and len(self.traced_tangents) == len(other.traced_tangents)
690
+ and all(
691
+ x.shape == y.shape and x.dtype == y.dtype
692
+ for x, y, in zip(self.traced_tangents, other.traced_tangents)
693
+ )
694
+ and self.num_backward_tokens == other.num_backward_tokens
695
+ )
696
+
697
+
698
+ @dataclass(eq=False)
699
+ class SubclassMeta:
700
+ # A copy of all forward metadata, but computed on the *dense* tensor forward (after desugaring subclasses)
701
+ # So for example, if the user had a model containing two `TwoTensor` inputs,
702
+ # Then `SubclassMeta.fw_metadata.input_infos` would have length 4 here.
703
+ fw_metadata: ViewAndMutationMeta
704
+
705
+ # Note: [Computing Subclass Metadata about grad_inputs]
706
+ # Given a list of flattened, plain tensor grad_inputs, this tells us how to reconstruct the grad_input subclasses
707
+ #
708
+ # You might think: why not just assume that all grad_inputs will have the same subclass-ness as the original inputs?
709
+ # (AOTAutograd generally assumes other properties, e.g. that grad_outputs are contiguous)
710
+ #
711
+ # This doesn't really work though. take this example:
712
+ #
713
+ # def f(DoubleTensor, DenseTensor):
714
+ # return DoubleTensor * DenseTensor
715
+ #
716
+ # In the above example, the .grad field of *both* DoubleTensor and DenseTensor will be a DoubleTensor.
717
+ # When we trace out a joint fw-bw graph, we'll end up returning two subclasses for the two grad_inputs.
718
+ # This means that our backward graph will return 4 outputs (two dense tensors for each DoubleTensor grad_input)
719
+ # and we need to properly store the metadata that tells us how to turn these 4 outputs back into DoubleTensors.
720
+ #
721
+ # Note that this info **cannot** easily be figured out from ViewAndMutationMeta.
722
+ # We can only compute this info by tracing the entire joint and examining the grad_inputs that we computed.
723
+ #
724
+ # See Note: [AOTAutograd Backward Guards]
725
+ # This will also eventually require us to install backward guards,
726
+ # in case we made incorrect assumptions about the subclass-ness of our grad_outputs
727
+ #
728
+ # Optional field because we don't compute for inference graphs
729
+ grad_input_metas: Optional[
730
+ list[Union[PlainTensorMeta, SubclassCreationMeta]]
731
+ ] = None
732
+
733
+ def __init__(self) -> None:
734
+ # The fields in this class get set after its construction.
735
+ pass
736
+
737
+
738
+ # This class exists because:
739
+ # - the autograd.Function.forward() in aot autograd returns outputs that might alias inputs
740
+ # - we only care about the metadata on those aliases, so we can regenerate them.
741
+ # We do not want them to participate in the autograd.Function.
742
+ # We do that by wrapping them in an opaque class, so the autograd.Function
743
+ # does not know to treat them as tensors.
744
+ @dataclass(frozen=True)
745
+ class TensorAlias:
746
+ alias: torch.Tensor
747
+
748
+
749
+ @dataclass
750
+ class BackwardSignature:
751
+ """
752
+ Provides information about the backward section of an exported
753
+ joint forward-backward graph.
754
+ For a particular fx GraphModule, this class contains information on:
755
+ (1) A mapping from each gradient (backwards output) to the parameter
756
+ it corresponds to (forward input)
757
+ (2) A mapping from each gradient (backwards output) to the user input
758
+ it corresponds to (forward input)
759
+ (3) Which of the forward outputs corresponds to the loss, that we backprop on.
760
+
761
+ Each string name is the `node.name` of the corresponding node in the fx graph.
762
+ """
763
+
764
+ gradients_to_parameters: dict[str, str]
765
+ gradients_to_user_inputs: dict[str, str]
766
+ loss_output: str
767
+
768
+
769
+ GraphOutputName = NewType("GraphOutputName", str)
770
+ GraphInputName = NewType("GraphInputName", str)
771
+ FQN = NewType("FQN", str)
772
+
773
+
774
+ @dataclass
775
+ class GraphSignature:
776
+ """
777
+ Provides information about an exported module.
778
+ For a particular fx GraphModule, this class contains information on:
779
+ (1) Which graph inputs are parameters, buffers, or user inputs
780
+ (2) (for params/buffers) a mapping from the name of each graph argument
781
+ to its parameter/buffer FQN in the original nn.Module.
782
+ (3) If there are input mutations, these are represented as extra outputs
783
+ in the fx GraphModule. We provide a mapping from these
784
+ extra output names to the names of the actual inputs.
785
+ (4) The pytree metadata on how to flatten/unflatten inputs and outputs.
786
+ The corresponding FX GraphModule only accepts and returns
787
+ pytree-flattened inputs/outputs.
788
+ (5) (Optionally) if the FX is a joint forward-backward graph, we provide
789
+ a signature on the backward section of the joint graph.
790
+ """
791
+
792
+ parameters: list[FQN]
793
+ buffers: list[FQN]
794
+
795
+ user_inputs: list[GraphInputName]
796
+ user_outputs: list[GraphOutputName]
797
+ inputs_to_parameters: dict[GraphInputName, FQN]
798
+ inputs_to_buffers: dict[GraphInputName, FQN]
799
+
800
+ # If the user's module mutates a buffer,
801
+ # it's represented in the graph as an extra graph output.
802
+ # This dict is a mapping from
803
+ # "graph outputs that correspond to updated buffers"
804
+ # to the FQN names of those mutated buffers.
805
+ buffers_to_mutate: dict[GraphOutputName, FQN]
806
+ user_inputs_to_mutate: dict[GraphOutputName, GraphInputName]
807
+
808
+ in_spec: pytree.TreeSpec
809
+ out_spec: pytree.TreeSpec
810
+
811
+ backward_signature: Optional[BackwardSignature]
812
+
813
+ input_tokens: list[GraphInputName]
814
+ output_tokens: list[GraphOutputName]
815
+
816
+ @classmethod
817
+ def from_tracing_metadata(
818
+ cls,
819
+ *,
820
+ in_spec: pytree.TreeSpec,
821
+ out_spec: pytree.TreeSpec,
822
+ graph_input_names: list[str],
823
+ graph_output_names: list[str],
824
+ view_mutation_metadata: ViewAndMutationMeta,
825
+ named_parameters: list[str],
826
+ named_buffers: list[str],
827
+ num_user_inputs: int,
828
+ num_user_outputs: int,
829
+ loss_index: Optional[int],
830
+ backward_signature: Optional[BackwardSignature],
831
+ ) -> "GraphSignature":
832
+ graph_inputs = graph_input_names
833
+ graph_outputs = graph_output_names
834
+ parameters = list(named_parameters)
835
+ buffers = list(named_buffers)
836
+ num_tokens = len(view_mutation_metadata.tokens)
837
+
838
+ # Calling convention assumptions:
839
+ # (1) graph inputs = (input_tokens, params, buffers, user_inputs)
840
+ # (2) graph outputs = (output_tokens, mutated_inputs, user_outs, param_gradients)
841
+ # (If we are capturing an inference graph, this convention is identical
842
+ # except that param_gradients is empty)
843
+ # See Note [Side-Effectful Tokens in AOTAutograd] for information on tokens
844
+
845
+ # Address input calling conventions:
846
+ start, stop = 0, num_tokens
847
+ input_tokens = graph_inputs[start:stop]
848
+
849
+ start, stop = stop, stop + len(parameters)
850
+ inputs_to_parameters = dict(zip(graph_inputs[start:stop], parameters))
851
+
852
+ start, stop = stop, stop + len(buffers)
853
+ inputs_to_buffers = dict(
854
+ zip(
855
+ graph_inputs[start:stop],
856
+ buffers,
857
+ )
858
+ )
859
+
860
+ start, stop = stop, stop + num_user_inputs
861
+ user_inputs = graph_inputs[start:stop]
862
+
863
+ # We should've gone through all the inputs now
864
+ assert len(graph_inputs) - stop == 0
865
+
866
+ # Address output calling conventions:
867
+ start, stop = 0, num_tokens
868
+ output_tokens = graph_outputs[start:stop]
869
+
870
+ names = [*input_tokens, *parameters, *buffers, *user_inputs]
871
+ mutations = []
872
+ for idx, input_info in enumerate(view_mutation_metadata.input_info):
873
+ if input_info.mutates_data:
874
+ # Only buffers can be mutated, not parameters
875
+ assert idx >= len(parameters)
876
+ mutations.append(names[idx + num_tokens])
877
+
878
+ assert len(mutations) == view_mutation_metadata.num_mutated_inp_runtime_indices
879
+
880
+ start, stop = (
881
+ stop,
882
+ stop + view_mutation_metadata.num_mutated_inp_runtime_indices,
883
+ )
884
+ outputs_to_mutations = dict(zip(graph_outputs[start:stop], mutations))
885
+
886
+ user_inputs_to_mutate = {}
887
+ buffers_to_mutate = {}
888
+ for output_name, mutation_name in outputs_to_mutations.items():
889
+ if mutation_name in user_inputs:
890
+ user_inputs_to_mutate[output_name] = mutation_name
891
+ else:
892
+ assert mutation_name in buffers
893
+ buffers_to_mutate[output_name] = mutation_name
894
+
895
+ start, stop = stop, stop + num_user_outputs
896
+ user_outputs = graph_outputs[start:stop]
897
+
898
+ unused_outputs = len(graph_outputs) - stop
899
+ if backward_signature is not None:
900
+ unused_outputs -= len(backward_signature.gradients_to_parameters) + len(
901
+ backward_signature.gradients_to_user_inputs
902
+ )
903
+ assert unused_outputs == 0
904
+
905
+ return GraphSignature(
906
+ parameters=parameters, # type: ignore[arg-type]
907
+ buffers=buffers, # type: ignore[arg-type]
908
+ user_inputs=user_inputs, # type: ignore[arg-type]
909
+ user_outputs=user_outputs, # type: ignore[arg-type]
910
+ inputs_to_buffers=inputs_to_buffers, # type: ignore[arg-type]
911
+ inputs_to_parameters=inputs_to_parameters, # type: ignore[arg-type]
912
+ user_inputs_to_mutate=user_inputs_to_mutate,
913
+ buffers_to_mutate=buffers_to_mutate, # type: ignore[arg-type]
914
+ in_spec=in_spec,
915
+ out_spec=out_spec,
916
+ backward_signature=backward_signature,
917
+ input_tokens=input_tokens, # type: ignore[arg-type]
918
+ output_tokens=output_tokens, # type: ignore[arg-type]
919
+ )
920
+
921
+
922
+ @dataclass
923
+ class AOTAutogradCacheInfo:
924
+ cache_key: str
925
+ start_time_ns: int
926
+ forward_symints: list[torch.SymInt]
927
+
928
+
929
+ @dataclass
930
+ class AOTConfig:
931
+ """
932
+ Configuration for AOTDispatcher
933
+ """
934
+
935
+ fw_compiler: Callable
936
+ bw_compiler: Callable
937
+ partition_fn: Callable
938
+ decompositions: dict[OpOverload, Callable]
939
+ num_params_buffers: int
940
+ aot_id: int
941
+ keep_inference_input_mutations: bool
942
+ is_export: bool = False
943
+ no_tangents: bool = False
944
+ dynamic_shapes: bool = False
945
+ aot_autograd_arg_pos_to_source: Optional[list[Source]] = None
946
+ static_input_indices: Optional[list[int]] = None
947
+ inference_compiler: Optional[Callable] = None
948
+ enable_log: bool = True
949
+ # this is always false outside of export.
950
+ pre_dispatch: bool = False
951
+ # Key to use for AOTAutogradCache
952
+ cache_info: Optional[AOTAutogradCacheInfo] = None
953
+ # If we should ignore the shape_env in the ambient tracing_context.
954
+ # The net effect is that if dynamic shapes are on, we end up
955
+ # specializing on example_inputs.
956
+ # Used only by standalone_compile.
957
+ ignore_shape_env: bool = False
958
+ precompile_backend_id: Optional[str] = None
959
+
960
+ def __post_init__(self):
961
+ if self.pre_dispatch:
962
+ assert self.is_export, "Can only have pre_dispatch IR for export."
963
+
964
+
965
+ SubclassTracingInfo = collections.namedtuple(
966
+ "SubclassTracingInfo",
967
+ ["plain_tensor_trace_fn", "plain_tensor_args", "maybe_subclass_meta"],
968
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import itertools
3
+ from collections.abc import Iterable
4
+ from typing import Any, Union
5
+
6
+ import torch
7
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
8
+
9
+
10
+ # This is technically very similar to SubclassCreatingMeta
11
+ # in aot_autograd, but we don't need all the stuff in there
12
+ # so just recreated a new dataclass.
13
+ @dataclasses.dataclass
14
+ class SubclassCreationMeta:
15
+ start_idx: int
16
+ num_tensors: int
17
+ class_type: Any
18
+ attrs: dict[str, "SubclassCreationMeta"]
19
+ metadata: Any
20
+ outer_size: Iterable[Union[None, int, torch.SymInt]]
21
+ outer_stride: Iterable[Union[None, int, torch.SymInt]]
22
+
23
+
24
+ class UnwrapTensorSubclass(torch.nn.Module):
25
+ def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def]
26
+ todo: list[torch.Tensor] = list(tensors)
27
+
28
+ def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def]
29
+ if subclass_meta is None:
30
+ return tensors[offset], offset + 1
31
+ inner_tensors = {}
32
+ for attr, meta in subclass_meta.attrs.items():
33
+ built_tensor, offset = _unwrap_tensor_subclasses(meta, tensors, offset)
34
+ inner_tensors[attr] = built_tensor
35
+ rebuilt = subclass_meta.class_type.__tensor_unflatten__(
36
+ inner_tensors,
37
+ subclass_meta.metadata,
38
+ subclass_meta.outer_size,
39
+ subclass_meta.outer_stride,
40
+ )
41
+ return rebuilt, offset
42
+
43
+ return _unwrap_tensor_subclasses(self.subclass_meta, todo, 0)[0]
44
+
45
+ def right_inverse(self, tensor: torch.Tensor) -> list[torch.Tensor]:
46
+ assert type(tensor) is not torch.Tensor
47
+ plain_tensors: list[torch.Tensor] = []
48
+
49
+ def _create_subclass_meta(tensor, idx, plain_tensor_container): # type: ignore[no-untyped-def]
50
+ if type(tensor) is torch.Tensor:
51
+ plain_tensor_container.append(tensor)
52
+ return None, idx + 1
53
+ inner_tensors_attrnames, metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined]
54
+ new_idx = idx
55
+ attr_to_meta = {}
56
+ for attr in inner_tensors_attrnames:
57
+ val = getattr(tensor, attr)
58
+ subclass_meta, new_idx = _create_subclass_meta(
59
+ val, new_idx, plain_tensor_container
60
+ )
61
+ attr_to_meta[attr] = subclass_meta
62
+ return (
63
+ SubclassCreationMeta(
64
+ start_idx=idx,
65
+ num_tensors=new_idx - idx,
66
+ class_type=type(tensor),
67
+ attrs=attr_to_meta,
68
+ metadata=metadata,
69
+ outer_size=tensor.size(),
70
+ outer_stride=tensor.stride(),
71
+ ),
72
+ new_idx,
73
+ )
74
+
75
+ self.subclass_meta = _create_subclass_meta(tensor, 0, plain_tensors)[0]
76
+ return plain_tensors
77
+
78
+
79
+ def unwrap_tensor_subclass_parameters(module: torch.nn.Module) -> torch.nn.Module:
80
+ """
81
+ Model transformation that replaces all the parameters that are subclasses to plain tensors.
82
+ This reduces runtime overhead of flattening/unflattening the parameters.
83
+
84
+ This transformation adds parametrization with `torch.nn.utils.parametrize`.
85
+ The FQNs of the subclass parameters will be changed and state_dict will become incompatible with the original model.
86
+ E.g.
87
+ Original model state_dict: {"p1": torch.testing._internal.TwoTensor}
88
+ becomes: {"parametrizations.p2.original0": torch.Tensor, "parametrizations.p2.original1": torch.Tensor}
89
+
90
+ """
91
+ for name, tensor in itertools.chain(
92
+ list(module.named_parameters(recurse=False)),
93
+ list(module.named_buffers(recurse=False)),
94
+ ):
95
+ if is_traceable_wrapper_subclass(tensor):
96
+ torch.nn.utils.parametrize.register_parametrization(
97
+ module, name, UnwrapTensorSubclass()
98
+ )
99
+
100
+ for name, child in module.named_children():
101
+ unwrap_tensor_subclass_parameters(child)
102
+
103
+ return module
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This file contains utilities for tracing through __torch_dispatch__ based tensor subclasses and modes.
4
+ AOTAutograd's responsibility is to trace through all pytorch capabilities that live in the pytorch dispatcher,
5
+ and this includes tensor subclasses that implement __torch_dispatch__.
6
+ """
7
+
8
+ import collections
9
+ import typing
10
+ from collections.abc import Iterable
11
+ from typing import Any, Callable, Optional, TypeVar, Union
12
+
13
+ import torch
14
+ import torch.utils._pytree as pytree
15
+ from torch import SymInt, Tensor
16
+ from torch._subclasses.fake_tensor import get_plain_tensors
17
+ from torch.types import IntLikeType
18
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
19
+
20
+ from .schemas import (
21
+ MutationType,
22
+ PlainTensorMeta,
23
+ SubclassCreationMeta,
24
+ ViewAndMutationMeta,
25
+ )
26
+ from .utils import strict_zip
27
+
28
+
29
+ zip = strict_zip
30
+
31
+ T = TypeVar("T", bound=torch.Tensor)
32
+
33
+
34
+ def requires_subclass_dispatch(args, fw_metadata: ViewAndMutationMeta) -> bool:
35
+ args_flattened = pytree.arg_tree_leaves(*args)
36
+ any_subclass_args = any(
37
+ is_traceable_wrapper_subclass(x)
38
+ for x in args_flattened
39
+ if isinstance(x, Tensor)
40
+ )
41
+ from torch._functorch._aot_autograd.schemas import SubclassCreationMeta
42
+
43
+ any_subclass_outputs = any(
44
+ type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta
45
+ )
46
+ # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime.
47
+ return any_subclass_args or any_subclass_outputs
48
+
49
+
50
+ from .schemas import MemoryFormatMeta
51
+
52
+
53
+ def maybe_suggest_memory_format(
54
+ t, with_memory_format: bool
55
+ ) -> Optional[MemoryFormatMeta]:
56
+ if not with_memory_format:
57
+ return None
58
+
59
+ return MemoryFormatMeta.from_tensor(t)
60
+
61
+
62
+ def get_subclass_typing_container(
63
+ tensor_subclass: torch.Tensor,
64
+ ) -> dict[type[torch.Tensor], list[type[torch.Tensor]]]:
65
+ """
66
+ Given a subclass, returns a recursive dictionary mapping each
67
+ inner tensors to its' subclass types.
68
+ """
69
+
70
+ def _get_types_for_subclass(tensor_subclass: torch.Tensor) -> None:
71
+ if not is_traceable_wrapper_subclass(tensor_subclass):
72
+ return
73
+ tracker[type(tensor_subclass)].append(tensor_subclass)
74
+ inner_keys, _ = tensor_subclass.__tensor_flatten__()
75
+ for key in inner_keys:
76
+ inner_tensor = getattr(tensor_subclass, key)
77
+ _get_types_for_subclass(inner_tensor)
78
+
79
+ tracker: dict[Any, list[Any]] = collections.defaultdict(list)
80
+ _get_types_for_subclass(tensor_subclass)
81
+ return tracker
82
+
83
+
84
+ def create_subclass_metadata(
85
+ a: Any, start_idx: int, count_symints: bool, with_memory_format: bool = False
86
+ ):
87
+ if not is_traceable_wrapper_subclass(a):
88
+ idx = start_idx + 1
89
+ return (
90
+ PlainTensorMeta(
91
+ idx,
92
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
93
+ ),
94
+ idx,
95
+ )
96
+
97
+ inner_keys, metadata = a.__tensor_flatten__()
98
+ new_start_idx = start_idx
99
+ attrs = {}
100
+
101
+ for key in inner_keys:
102
+ new_subclass_meta, new_start_idx = create_subclass_metadata(
103
+ getattr(a, key),
104
+ new_start_idx,
105
+ count_symints=count_symints,
106
+ with_memory_format=with_memory_format,
107
+ )
108
+ attrs[key] = new_subclass_meta
109
+
110
+ # It *must* be because is_traceable_wrapper_subclass() - but mypy is not smart.
111
+ assert isinstance(a, Tensor)
112
+
113
+ new_start_idx = (
114
+ new_start_idx
115
+ + count_symints * len(filter_symints(a.size()))
116
+ + count_symints * len(filter_symints(a.stride()))
117
+ )
118
+
119
+ return (
120
+ SubclassCreationMeta(
121
+ flat_tensor_start_idx=start_idx,
122
+ arg_count=new_start_idx - start_idx,
123
+ included_subclass_symints=count_symints,
124
+ attrs=attrs,
125
+ meta=metadata,
126
+ outer_size=a.size(), # type: ignore[attr-defined, arg-type]
127
+ outer_stride=a.stride(), # type: ignore[arg-type]
128
+ original_subclass=a,
129
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
130
+ ),
131
+ new_start_idx,
132
+ )
133
+
134
+
135
+ # Given a flat list of arguments, some of which may be tensor subclasses,
136
+ # computes metadata about "how to reconstruct the current list of subclasses,
137
+ # if we were given their flattened dense tensors instead"
138
+ def create_subclass_meta(
139
+ curr_args: Union[list[Any], tuple[Any, ...]],
140
+ *,
141
+ count_symints: bool = True,
142
+ with_memory_format: bool = False,
143
+ ) -> list[Union[PlainTensorMeta, SubclassCreationMeta]]:
144
+ idx = 0
145
+ infos: list[Union[PlainTensorMeta, SubclassCreationMeta]] = []
146
+ for a in curr_args:
147
+ if is_traceable_wrapper_subclass(a):
148
+ assert isinstance(a, Tensor)
149
+ start_idx = idx
150
+ subclass_meta, _ = create_subclass_metadata(
151
+ a,
152
+ start_idx,
153
+ count_symints=count_symints,
154
+ with_memory_format=with_memory_format,
155
+ )
156
+ infos.append(subclass_meta)
157
+ cnt = subclass_meta.arg_count
158
+ else:
159
+ infos.append(
160
+ PlainTensorMeta(
161
+ idx,
162
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
163
+ )
164
+ )
165
+ cnt = 1
166
+ idx += cnt
167
+ return infos
168
+
169
+
170
+ def filter_symints(lst: Iterable[IntLikeType]):
171
+ # Capture all SymInts from the iterable.
172
+ def symint_check(s: IntLikeType) -> bool:
173
+ return isinstance(s, SymInt) and not s.node.is_nested_int()
174
+
175
+ return [s for s in lst if symint_check(s)]
176
+
177
+
178
+ def compute_symint_placeholders(lst: Iterable[Union[None, int, SymInt]]) -> list[bool]:
179
+ # Non-nested symints are replaced with None in `make_runtime_safe()`
180
+ return [s is None for s in lst]
181
+
182
+
183
+ # This function takes in a pytree of arguments and unwraps any tensor
184
+ # subclasses.
185
+ #
186
+ # NOTE: The reason for "append_symints":
187
+ #
188
+ # * At compile time: we append extra symint args when unwrapping primals
189
+ # (but not tangents, because they should always share symints with primals).
190
+ # We also append extra symints when unwrapping the subclass outputs of the
191
+ # traced function, so we can return them as extra outputs
192
+ #
193
+ # * At runtime: we similarly append subclass sizes when we unwrap subclass
194
+ # primals (but not tangents) on entry to the forward. See the runtime version of
195
+ # this function below.
196
+ def unwrap_tensor_subclasses(
197
+ wrapped_args: list[Union[Tensor, int]],
198
+ *,
199
+ append_symints: bool,
200
+ ):
201
+ def flatten_subclass(t: Union[Tensor, int], *, out=None):
202
+ # unwrap a subclass into plain tensors and their size/stride if "append_symint"
203
+ # is True
204
+ if not is_traceable_wrapper_subclass(t):
205
+ out.append(t)
206
+ return
207
+
208
+ attrs, _ = t.__tensor_flatten__()
209
+
210
+ for attr in attrs:
211
+ inner_tensor = getattr(t, attr)
212
+ flatten_subclass(inner_tensor, out=out)
213
+
214
+ if append_symints:
215
+ out.extend(filter_symints(t.size()))
216
+ out.extend(filter_symints(t.stride()))
217
+
218
+ xs_inner: list[Union[int, Tensor, SymInt]] = []
219
+
220
+ for x in wrapped_args:
221
+ flatten_subclass(typing.cast(Tensor, x), out=xs_inner)
222
+
223
+ return xs_inner
224
+
225
+
226
+ # subclass_metas is needed at runtime to compute which indices are symints in
227
+ # the outer_size/outer_stride
228
+ def runtime_unwrap_tensor_subclasses(
229
+ wrapped_args: list[Union[Tensor, int]],
230
+ *,
231
+ append_symints: bool,
232
+ subclass_metas: Optional[list[Union[PlainTensorMeta, SubclassCreationMeta]]] = None,
233
+ ):
234
+ def flatten_subclass(x: Tensor, meta: Optional[SubclassCreationMeta], *, out):
235
+ if not is_traceable_wrapper_subclass(x):
236
+ out.append(x)
237
+ return out
238
+
239
+ assert isinstance(x, Tensor)
240
+
241
+ attrs, _ = x.__tensor_flatten__()
242
+
243
+ for attr in attrs:
244
+ inner_tensor = getattr(x, attr)
245
+ inner_meta = meta.attrs.get(attr)
246
+ flatten_subclass(inner_tensor, inner_meta, out=out)
247
+
248
+ if append_symints:
249
+ assert isinstance(meta, SubclassCreationMeta)
250
+ # outer_size
251
+ size = x.size()
252
+ symint_placeholders = compute_symint_placeholders(meta.outer_size)
253
+ assert len(size) == len(symint_placeholders)
254
+ out.extend(
255
+ [r for (r, is_symint) in zip(size, symint_placeholders) if is_symint]
256
+ )
257
+
258
+ # outer_stride
259
+ stride = x.stride()
260
+ symint_placeholders = compute_symint_placeholders(meta.outer_stride)
261
+ assert len(stride) == len(symint_placeholders)
262
+ out.extend(
263
+ [r for (r, is_symint) in zip(stride, symint_placeholders) if is_symint]
264
+ )
265
+ return out
266
+
267
+ xs_inner: list[Union[int, Tensor, SymInt]] = []
268
+
269
+ if append_symints:
270
+ assert subclass_metas is not None
271
+
272
+ for idx, x in enumerate(wrapped_args):
273
+ if not is_traceable_wrapper_subclass(x):
274
+ xs_inner.append(x)
275
+ continue
276
+
277
+ if subclass_metas is None:
278
+ get_plain_tensors(typing.cast(Tensor, x), out=xs_inner)
279
+ else:
280
+ meta = subclass_metas[idx]
281
+ assert isinstance(meta, SubclassCreationMeta)
282
+ flatten_subclass(typing.cast(Tensor, x), meta, out=xs_inner)
283
+
284
+ return xs_inner
285
+
286
+
287
+ def unwrap_tensor_subclasses_with_indices_to_original(wrapped_args):
288
+ ret_unwrapped = []
289
+ ret_indices_to_original = []
290
+ for i, a in enumerate(wrapped_args):
291
+ a_unwrapped = unwrap_tensor_subclasses([a], append_symints=False)
292
+ ret_unwrapped.extend(a_unwrapped)
293
+ n = len(a_unwrapped)
294
+ ret_indices_to_original.extend([i] * n)
295
+
296
+ return ret_unwrapped, ret_indices_to_original
297
+
298
+
299
+ def remap_unwrapped_subclass_arg_indices(wrapped_args, static_input_indices):
300
+ static_input_indices = set(static_input_indices)
301
+ new_ind = 0
302
+ remapped_static_indices = []
303
+ for i, arg in enumerate(wrapped_args):
304
+ num_indices = 1
305
+ if is_traceable_wrapper_subclass(arg):
306
+ num_indices = (
307
+ len(get_plain_tensors(typing.cast(Tensor, arg), out=[]))
308
+ + len(filter_symints(arg.size()))
309
+ + len(filter_symints(arg.stride()))
310
+ )
311
+
312
+ for _ in range(num_indices):
313
+ if i in static_input_indices:
314
+ remapped_static_indices.append(new_ind)
315
+
316
+ new_ind += 1
317
+
318
+ return remapped_static_indices
319
+
320
+
321
+ # Turns a flattened list of tensor arguments into (maybe) subclass tensors.
322
+ # This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in.
323
+ def wrap_tensor_subclasses(
324
+ unwrapped_args: Union[tuple[Any, ...], list[Any]],
325
+ *,
326
+ subclass_metas: list[Union[PlainTensorMeta, SubclassCreationMeta]],
327
+ num_fw_outs_saved_for_bw: Optional[int] = None,
328
+ included_subclass_symints: bool = False,
329
+ is_runtime: bool = False,
330
+ make_subclass_override: Optional[Callable] = None,
331
+ ) -> tuple[Any, ...]:
332
+ wrapped_args = []
333
+ num_args_tallied = 0
334
+ for subclass_meta in subclass_metas:
335
+ if isinstance(subclass_meta, PlainTensorMeta):
336
+ wrapped_args.append(unwrapped_args[subclass_meta.unwrapped_idx])
337
+ num_args_tallied += 1
338
+ else:
339
+ assert isinstance(subclass_meta, SubclassCreationMeta)
340
+ assert subclass_meta.included_subclass_symints == included_subclass_symints
341
+
342
+ if make_subclass_override:
343
+ wrapped_args.append(
344
+ make_subclass_override(subclass_meta, is_runtime, unwrapped_args)
345
+ )
346
+ else:
347
+ wrapped_args.append(
348
+ subclass_meta.creation_fn(unwrapped_args, is_runtime=is_runtime)
349
+ )
350
+ num_args_tallied += subclass_meta.arg_count
351
+
352
+ # Note: [Partitioner handling for Subclasses, Part 2]
353
+ # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw,
354
+ # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them.
355
+ #
356
+ # When this function is called at runtime in the forward,
357
+ # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs.
358
+ #
359
+ # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen?
360
+ # Answer: we do it **inside of our compiled autograd.Function**.
361
+ # This seems like morally the right place: autograd happens above subclass desugaring,
362
+ # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors.
363
+ #
364
+ # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph
365
+ # into a forward and backward graph, we end up with some activations that show up as extra outputs
366
+ # in the compiled forward graph, that are **not** user outputs.
367
+ # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses.
368
+ #
369
+ # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`),
370
+ # we computed subclass metadata on every forward output, but this did **not** include activations
371
+ # created by the partitioner.
372
+ # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations),
373
+ # but `subclass_metas` will only correspond to subclass metatadata on `user_fw_outs`.
374
+ # We then need to make sure that we return (*wrapped_user_fw_outs, *activations).
375
+ if num_fw_outs_saved_for_bw is not None:
376
+ assert len(unwrapped_args) == num_args_tallied + num_fw_outs_saved_for_bw, (
377
+ f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal "
378
+ f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of "
379
+ f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})"
380
+ )
381
+ activations = unwrapped_args[num_args_tallied:]
382
+ if isinstance(wrapped_args, tuple) and isinstance(activations, tuple):
383
+ return wrapped_args + activations
384
+ return tuple(list(wrapped_args) + list(activations))
385
+ else:
386
+ assert (
387
+ len(unwrapped_args) == num_args_tallied
388
+ ), f"Expected {len(unwrapped_args)} == {num_args_tallied}"
389
+ return tuple(wrapped_args)
390
+
391
+
392
+ # Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses.
393
+ # This function carefully handles the inference vs. joint cases:
394
+ # - when is_joint_structure is True, args is (primals, tangents)
395
+ # - when is_joint_structure is False, args is [*primals]
396
+ def wrap_tensor_subclasses_maybe_joint(
397
+ unwrapped_args, *, is_joint_structure: bool, meta: ViewAndMutationMeta
398
+ ) -> Union[tuple[Any, ...], list[Any]]:
399
+ # Since this function is re-used for both inference and joint graphs,
400
+ if is_joint_structure:
401
+ assert isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2
402
+ assert isinstance(unwrapped_args[0], (tuple, list)) and isinstance(
403
+ unwrapped_args[1], (tuple, list)
404
+ )
405
+ primals, tangents = unwrapped_args[0], unwrapped_args[1]
406
+ wrapped_primals = wrap_tensor_subclasses(
407
+ primals,
408
+ subclass_metas=meta.subclass_inp_meta,
409
+ included_subclass_symints=True,
410
+ )
411
+ wrapped_tangents = wrap_tensor_subclasses(
412
+ tangents,
413
+ subclass_metas=meta.subclass_tangent_meta,
414
+ included_subclass_symints=False,
415
+ )
416
+ return (wrapped_primals, wrapped_tangents)
417
+ else:
418
+ wrapped_args = wrap_tensor_subclasses(
419
+ unwrapped_args,
420
+ subclass_metas=meta.subclass_inp_meta,
421
+ included_subclass_symints=True,
422
+ )
423
+ return wrapped_args
424
+
425
+
426
+ def compute_inner_mutated_inp_indices_from_subclass_meta(
427
+ fw_metadata: ViewAndMutationMeta,
428
+ inner_metadata: ViewAndMutationMeta,
429
+ ) -> list[int]:
430
+ # Note: [Recomputing subclass mutation handling]
431
+ #
432
+ # Generally, if a subclass requires grad, its components will not require grad.
433
+ # But for the purposes of tracking returned tensors, we should treat those component
434
+ # tensors as if they require grad.
435
+ #
436
+ # For example, if the subclass tensor requires grad and will be mutated in a way that
437
+ # requires us to handle the mutation outside of the graph, we need to return it
438
+ # from the forward graph. The inner_meta data won't consider the component tensors
439
+ # as if they need to be returned, because they don't require grad; but really, we
440
+ # should handle those tensors the same way we handle the subclass tensor itself; i.e.
441
+ # if we'd include the subclass tensor as part of the outputs, then we should also
442
+ # include the component tensors.
443
+ #
444
+ # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs
445
+ # from the outer subclass tensors and propagating
446
+
447
+ updated_input_info = []
448
+ inner_idx = 0
449
+ if not fw_metadata.subclass_inp_meta:
450
+ # Sometimes we don't have subclass info, e.g. synthetic_base codepaths
451
+ return inner_metadata.mutated_inp_runtime_indices
452
+ assert len(fw_metadata.subclass_inp_meta) == len(fw_metadata.input_info)
453
+ for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta):
454
+ if isinstance(inp_meta, PlainTensorMeta):
455
+ assert outer_idx < len(fw_metadata.input_info)
456
+ if inner_metadata is not None:
457
+ assert inner_idx < len(inner_metadata.input_info)
458
+ assert (
459
+ inner_metadata.input_info[inner_idx]
460
+ == fw_metadata.input_info[outer_idx]
461
+ )
462
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
463
+ inner_idx += 1
464
+ else:
465
+ assert inp_meta.original_subclass is not None
466
+ for _ in range(inp_meta.arg_count):
467
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
468
+ inner_idx += 1
469
+ if inner_metadata is not None:
470
+ assert len(inner_metadata.input_info) == len(updated_input_info)
471
+
472
+ return [
473
+ i
474
+ for i, inp in enumerate(updated_input_info)
475
+ if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH
476
+ ]
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/traced_function_transforms.py ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This module is responsible for transforming functions to be traced into a form
4
+ that is easier for the downstream infra (e.g. Autograd, FX, AOTAutograd analysis)
5
+ to handle.
6
+
7
+ It does so by:
8
+ 1. functionalization (including RNG functionalzation)
9
+ 2. creating a joint graph when required
10
+ 3. transforming mutations into extra outputs
11
+ 4. dispatching subclasses
12
+ """
13
+
14
+ import warnings
15
+ from contextlib import contextmanager, nullcontext
16
+ from functools import wraps
17
+ from typing import Any, Callable, Union
18
+ from unittest.mock import patch
19
+
20
+ import torch
21
+ import torch.fx.traceback as fx_traceback
22
+ import torch.utils._pytree as pytree
23
+ from torch import Tensor
24
+ from torch._decomp.decompositions_for_rng import PhiloxStateTracker
25
+ from torch._guards import detect_fake_mode
26
+ from torch._prims_common import CUDARngStateHelper
27
+ from torch.fx.experimental.proxy_tensor import (
28
+ maybe_disable_thunkify,
29
+ maybe_enable_thunkify,
30
+ )
31
+ from torch.fx.experimental.symbolic_shapes import (
32
+ guard_or_true,
33
+ PropagateUnbackedSymInts,
34
+ sym_eq,
35
+ )
36
+ from torch.nn.utils import stateless
37
+
38
+ from .. import config
39
+ from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata
40
+ from .functional_utils import (
41
+ _check_if_mutation_can_be_in_graph,
42
+ are_all_mutations_hidden_from_autograd,
43
+ are_all_mutations_under_no_grad_or_inference_mode,
44
+ from_fun,
45
+ has_data_mutation,
46
+ has_metadata_mutation,
47
+ is_fun,
48
+ sync_functional_tensor,
49
+ to_fun,
50
+ was_inductor_storage_resized,
51
+ )
52
+ from .logging_utils import setup_stacktrace_preservation_hooks
53
+ from .schemas import (
54
+ AOTConfig,
55
+ MutationType,
56
+ OutputType,
57
+ SubclassMeta,
58
+ SubclassTracingInfo,
59
+ ViewAndMutationMeta,
60
+ )
61
+ from .subclass_utils import (
62
+ create_subclass_meta,
63
+ remap_unwrapped_subclass_arg_indices,
64
+ requires_subclass_dispatch,
65
+ unwrap_tensor_subclasses,
66
+ wrap_tensor_subclasses_maybe_joint,
67
+ )
68
+ from .utils import maybe_to_fresh_input
69
+
70
+
71
+ # This function returns a new function that returns mutated inputs as outputs.
72
+ # if keep_data_input_mutations is set, then we assume that data-only mutations
73
+ # will be left in the graph, and we only return metadata-mutated inputs as outputs.
74
+ def fn_input_mutations_to_outputs(
75
+ fn: Callable,
76
+ meta: ViewAndMutationMeta,
77
+ keep_data_input_mutations: bool,
78
+ ) -> Any:
79
+ @wraps(fn)
80
+ def inner_fn(*args):
81
+ outs = fn(*args)
82
+ assert len(meta.output_info) == len(outs)
83
+ # The compiled fw will return mutated input tensors, *including* metadata-only mutation.
84
+ # However, if keep_data_input_mutations is set, the compiled fw only needs to return metadata-mutated inputs.
85
+ # (because data-only input mutations are handled directly in the compiled graph)
86
+ mutated_inputs_to_return = [
87
+ x for (i, x) in enumerate(args) if i in meta.mutated_inp_runtime_indices
88
+ ]
89
+ return *mutated_inputs_to_return, *outs
90
+
91
+ return inner_fn
92
+
93
+
94
+ # This function takes in a fn with external aliasing and mutation,
95
+ # and returns a new fn with no external aliasing and mutation,
96
+ # as needed for autograd.
97
+ # The main transformations are:
98
+ # - Return mutated inputs as extra outputs
99
+ # - Clone mutated inputs that require gradients,
100
+ # because autograd will require us to pass the pre-mutated inputs into autograd.grad
101
+ # - Return intermediate bases of outputs as additional outputs,
102
+ # needed to appease autograd.Function
103
+ # The new function returns:
104
+ # (1) The updated outputs
105
+ # (2) A boolean mask of len(new_fn_outputs),
106
+ # that can be used to tell autograd.grad which outputs should get tangents
107
+ # if we trace the backward.
108
+ def fn_prepped_for_autograd(
109
+ fn: Callable,
110
+ meta: ViewAndMutationMeta,
111
+ ) -> Any:
112
+ @wraps(fn)
113
+ def inner_fn(*args):
114
+ args_maybe_cloned = [
115
+ maybe_to_fresh_input(i, t, meta) for i, t in enumerate(args)
116
+ ]
117
+
118
+ outs = fn(*args_maybe_cloned)
119
+ assert isinstance(outs, (tuple, list))
120
+ outs = list(outs)
121
+ assert len(meta.output_info) == len(outs)
122
+
123
+ mutated_inputs_to_return = [
124
+ x
125
+ for (i, x) in enumerate(args_maybe_cloned)
126
+ if i in meta.mutated_inp_runtime_indices
127
+ ]
128
+
129
+ intermediate_bases = []
130
+ for i, (o, info) in enumerate(zip(outs, meta.output_info)):
131
+ if info.output_type == OutputType.alias_of_intermediate_save_as_output:
132
+ intermediate_bases.append(o._base)
133
+
134
+ assert meta.num_intermediate_bases == len(intermediate_bases)
135
+
136
+ # the compiled forward should return (mutated_inputs, user_outs, intermediate_bases)
137
+ fw_outs_to_return = *mutated_inputs_to_return, *outs, *intermediate_bases
138
+
139
+ # Also return a boolean mask specifying which outputs to this function will be used as tangents
140
+ mutated_inputs_grad_mask = [
141
+ meta.input_info[meta.mutated_inp_runtime_indices[i]].mutates_data
142
+ and meta.input_info[meta.mutated_inp_runtime_indices[i]].requires_grad
143
+ for (i, x) in enumerate(mutated_inputs_to_return)
144
+ ]
145
+
146
+ # Pass any (non-aliased) outputs in as tangents, since they'll be returned as outputs in the fw
147
+ # For outputs that are aliases of intermediates, we will have returned the output's _base as an output in the graph instead,
148
+ # which we *should* send to grad()
149
+ output_grad_mask = [
150
+ meta.output_info[i].output_type
151
+ in [
152
+ OutputType.non_alias,
153
+ OutputType.unsafe_view_alias,
154
+ OutputType.custom_function_view,
155
+ ]
156
+ # Also, only tensor outputs should participate in the backward
157
+ # (in particular, Symint outputs in the forward graph shouldn't get tangents)
158
+ and issubclass(meta.output_info[i].raw_type, Tensor)
159
+ and meta.output_info[i].requires_grad
160
+ for (i, x) in enumerate(outs)
161
+ ]
162
+
163
+ intermediate_base_grad_mask = [True for _ in range(len(intermediate_bases))]
164
+
165
+ out_grad_mask = (
166
+ mutated_inputs_grad_mask + output_grad_mask + intermediate_base_grad_mask
167
+ )
168
+ assert len(out_grad_mask) == len(fw_outs_to_return)
169
+
170
+ # Take care to grab and sync the updated inputs from primals_after_cloning (the inputs we actually mutate!)
171
+ # and not primals (the preserved inputs, pre-mutation, that we pass to grad())
172
+ # This is annoying: our joint function needs to be aware of functionalization
173
+ # (syncing mutated inputs before calling autograd.grad())
174
+ # In theory, we could make the autograd engine do this automatically, although that probably isn't any cleaner.
175
+ for arg in args_maybe_cloned:
176
+ if not isinstance(arg, Tensor):
177
+ continue
178
+ sync_functional_tensor(arg)
179
+
180
+ return fw_outs_to_return, out_grad_mask
181
+
182
+ return inner_fn
183
+
184
+
185
+ # Given a fn, computes the joint.
186
+ # NOTE: fn is expects the following behavior:
187
+ # (1) fn() needs to return a tuple of (outs, mask),
188
+ # where `mask` tells us which outputs are meant to have tangents.
189
+ # we don't know this info automatically, because we don't actually want to blindly
190
+ # compute tangents for every output that requires grad.
191
+ # Specifically, outputs that alias inputs won't participate in the backward and get tangents.
192
+ # (2) fn() cannot mutate any inputs that require gradient.
193
+ # otherwise, when we compute autograd.grad(), we will not take those input mutations into account
194
+ # (the way this is handled is that we ensure any inputs that normally get mutated are cloned first)
195
+ def create_joint(fn: Callable, *, aot_config: AOTConfig) -> Any:
196
+ def inner_fn(primals: list[Any], tangents: list[Any]):
197
+ outs, tangent_mask = fn(*primals)
198
+
199
+ assert len(tangent_mask) == len(outs)
200
+ outs_to_grad = [
201
+ o for needs_tangent, o in zip(tangent_mask, outs) if needs_tangent
202
+ ]
203
+ assert len(outs_to_grad) == len(tangents)
204
+
205
+ # Get the inputs that need gradients
206
+ grad_primals = []
207
+ inputs_needs_grads = []
208
+ # Note that we're not using primals here,
209
+ # being carefully not to pass any mutated inputs into autograd.grad()
210
+ for p in primals:
211
+ is_grad_tensor = isinstance(p, Tensor) and p.requires_grad
212
+ inputs_needs_grads.append(is_grad_tensor)
213
+ if is_grad_tensor:
214
+ grad_primals.append(p)
215
+
216
+ # Get the outputs that need gradients
217
+ needed_outs = []
218
+ needed_tangents = []
219
+ for out, tangent in zip(outs_to_grad, tangents):
220
+ if isinstance(out, Tensor) and out.requires_grad:
221
+ # A bit sketchy, but fixes e.g. test_aot_autograd_exhaustive_matmul_cpu_float32
222
+ # The issue is that we are sensitive to decomps that don't accurately maintain
223
+ # their output's _base.shape compared to eager mode, and this helps mitigate a bit.
224
+ # The guard_or_true also sketchy; if unbacked
225
+ # symints are involved, we're just going to assume that the
226
+ # decomps setup the base shape correctly
227
+
228
+ # Return out if the result of out.shape==tangent.shape is unknown or known to be true.
229
+ # otherwise if its a known false return out.view(tangent.shape).
230
+ needed_outs.append(
231
+ out
232
+ if guard_or_true(sym_eq(out.shape, tangent.shape))
233
+ else out.view(tangent.shape)
234
+ )
235
+ needed_tangents.append(tangent)
236
+
237
+ setup_stacktrace_preservation_hooks([out.grad_fn for out in needed_outs])
238
+
239
+ if config.functionalize_rng_ops:
240
+ PhiloxStateTracker.mark_beginning_of_backward()
241
+ backward_out: tuple[Tensor, ...] = ()
242
+ # Call the backwards pass
243
+ if grad_primals:
244
+ functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode(
245
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
246
+ )
247
+ if functional_tensor_mode is not None:
248
+ # Side-Effect Tokens:
249
+ # We want to have independent chains of tokens for forward and backward.
250
+ # functional_tensor_mode._tokens is used by both.
251
+ # We memoize the result tokens of forward in functional_tensor_mode._tokens_forward_output,
252
+ # to return them as joint graph outputs.
253
+ # We clean functional_tensor_mode._tokens before backward, to prevent reuse of forward tokens in backward.
254
+ # Joint graph tracing allows tokens discovery,
255
+ # So all the tokens in backward will be created and added as a graph inputs during tracing.
256
+ functional_tensor_mode._tokens_forward_output = (
257
+ functional_tensor_mode._tokens
258
+ )
259
+ functional_tensor_mode._tokens = {}
260
+
261
+ with set_partitioner_tag_is_backward(), fx_traceback.preserve_node_meta():
262
+ # for full graph export, we always export a joint graph where we assume no tangents are needed.
263
+ if aot_config.no_tangents:
264
+ assert len(needed_tangents) == 1 and needed_tangents[0].numel() == 1
265
+ backward_out = torch.autograd.grad(
266
+ needed_outs,
267
+ grad_primals,
268
+ allow_unused=True,
269
+ )
270
+ else:
271
+ backward_out = torch.autograd.grad(
272
+ needed_outs,
273
+ grad_primals,
274
+ grad_outputs=needed_tangents,
275
+ allow_unused=True,
276
+ )
277
+ backward_out_iter = iter(backward_out)
278
+ return outs, [
279
+ next(backward_out_iter) if i else None for i in inputs_needs_grads
280
+ ]
281
+
282
+ def inner_fn_with_anomaly(*args):
283
+ with fx_traceback.preserve_node_meta(), warnings.catch_warnings():
284
+ warnings.filterwarnings("ignore", "Anomaly Detection has been enabled.")
285
+ with torch.autograd.detect_anomaly(check_nan=False):
286
+ return inner_fn(*args)
287
+
288
+ return inner_fn_with_anomaly
289
+
290
+
291
+ def create_functionalized_rng_ops_wrapper(func, args, trace_joint=True) -> Any:
292
+ # Functionalization of rng ops changes the calling convention of the joint graph.
293
+ # It goes from (primals, tangents) to (seed, offset, primals, tangents)
294
+ # At runtime, we pass on the current seed and offset. This is hidden from
295
+ # the user.
296
+ fake_mode = detect_fake_mode()
297
+ if fake_mode is None:
298
+ fake_mode = nullcontext()
299
+
300
+ def override_get_rng_state(device: Union[int, str, torch.device] = "cuda"):
301
+ out = PhiloxStateTracker.get_state_as_tensor()
302
+ return out
303
+
304
+ def override_set_rng_state(x, device: Union[int, str, torch.device] = "cuda"):
305
+ PhiloxStateTracker.set_state_from_tensor(x)
306
+
307
+ def append_rng_offsets(args):
308
+ if trace_joint:
309
+ # args signature before: Tuple(fwd_outputs), Tuple(bwd_outputs)
310
+ # args signature after: Tuple(fwd_outputs, new_fwd_rng_offset), Tuple(bwd_offset, new_bwd_rng_offset)
311
+ return (
312
+ (*args[0], PhiloxStateTracker.get_updated_fwd_offset()),
313
+ (*args[1], PhiloxStateTracker.get_updated_bwd_offset()),
314
+ )
315
+ else:
316
+ # args signature before: Tuple(fwd_outputs)
317
+ # args signature after: Tuple(fwd_outputs, new_fwd_rng_offset)
318
+ return (*args, PhiloxStateTracker.get_updated_fwd_offset())
319
+
320
+ def traced_joint(
321
+ primals, tangents, fwd_seed, fwd_base_offset, bwd_seed, bwd_base_offset
322
+ ):
323
+ with patch("torch.cuda.get_rng_state", override_get_rng_state), patch(
324
+ "torch.cuda.set_rng_state", override_set_rng_state
325
+ ):
326
+ return append_rng_offsets(func(primals, tangents))
327
+
328
+ def traced_forward(*primals_fwd_seed_fwd_base_offset):
329
+ # The signature is (*primals, seed, offset)
330
+ with patch("torch.cuda.get_rng_state", override_get_rng_state), patch(
331
+ "torch.cuda.set_rng_state", override_set_rng_state
332
+ ):
333
+ return append_rng_offsets(func(*primals_fwd_seed_fwd_base_offset[:-2]))
334
+
335
+ if trace_joint:
336
+ # Get the current seed and offset to setup tracing.
337
+ fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
338
+ fake_mode
339
+ )
340
+ bwd_seed, bwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
341
+ fake_mode
342
+ )
343
+ PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward")
344
+ PhiloxStateTracker.record_state(bwd_seed, bwd_base_offset, "backward")
345
+ return traced_joint, (
346
+ *args,
347
+ fwd_seed,
348
+ fwd_base_offset,
349
+ bwd_seed,
350
+ bwd_base_offset,
351
+ )
352
+ else:
353
+ # Get the current seed and offset to setup tracing.
354
+ fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
355
+ fake_mode
356
+ )
357
+ PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward")
358
+ return traced_forward, (*args, fwd_seed, fwd_base_offset)
359
+
360
+
361
+ @contextmanager
362
+ def set_partitioner_tag(tag: str):
363
+ meta_key = "partitioner_tag"
364
+ assert fx_traceback.has_preserved_node_meta()
365
+
366
+ original_val = fx_traceback.current_meta.get(meta_key, None)
367
+ fx_traceback.current_meta[meta_key] = tag
368
+ try:
369
+ yield
370
+ finally:
371
+ fx_traceback.current_meta[meta_key] = original_val
372
+
373
+
374
+ def set_partitioner_tag_is_backward():
375
+ return set_partitioner_tag("is_backward")
376
+
377
+
378
+ def set_partitioner_tag_must_be_in_backward():
379
+ return set_partitioner_tag("must_be_in_backward")
380
+
381
+
382
+ # This creates the final function that we want to trace using make_fx(),
383
+ # in both aot_dispatch_autograd and aot_dispatch_base.
384
+ # Preconditions:
385
+ # - fn corresponds to the user's fw function
386
+ # - fn arguments have been flattened, duplicate arguments have been handled
387
+ # - In the returned function, the "primals" arguments *includes* synthetic bases.
388
+ # This function does the work of functionalizing the input function,
389
+ # and performing copy_() calls at the end of the function if `keep_input_mutations` is set.
390
+ # The function returned has signature that is either:
391
+ # (1) "traced_fn(primals: List[Any])" if trace_joint is False
392
+ # (2) "traced_fn(primals: List[Any], tangents: List[Any])" if trace_joint is True
393
+ # Returns a new (functionalized) function, and updated arguments to call it with.
394
+ def create_functionalized_fn(
395
+ fn,
396
+ args,
397
+ *,
398
+ meta: ViewAndMutationMeta,
399
+ aot_config: AOTConfig,
400
+ trace_joint: bool,
401
+ ) -> Any:
402
+ @wraps(fn)
403
+ def _functionalized_f_helper(*args):
404
+ with maybe_enable_thunkify():
405
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
406
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
407
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
408
+ )
409
+
410
+ with disable_above:
411
+ # The functionalization code here can potentially trigger traces
412
+ # into the graph, but we'd prefer to NOT do this, because if we
413
+ # trace them now, we will end up with FX nodes that don't have
414
+ # module stack annotations, which makes unflattener unhappy.
415
+ # Wrap inputs into functional wrappers
416
+ f_args = pytree.tree_map(to_fun, args)
417
+
418
+ # Run the joint
419
+ f_outs = fn(*f_args)
420
+
421
+ if trace_joint:
422
+ # We support a limited amount of mutation of graph inputs during the backward pass.
423
+ # (This is used e.g. by Float8, which needs to update buffers during the backward pass)
424
+ # Here, we perform extra checks for primals that were mutated in the **backward**
425
+ # We're doing the checks here instead of doing them with the rest of the input mutation handling because:
426
+ # - We need to detect inputs that were mutated in the backward **separately** from mutations that happened
427
+ # during the forward, because the handling is different: some input mutations from the the forward
428
+ # can be only handled in a fw-only runtime epilogue, and in theory if we wanted to handle those same
429
+ # types of mutations in the backward we would need a bw-only runtime epilogue.
430
+ # - We could in theory have our analysis pass differentiate mutations in the fw from mutations in
431
+ # the bw by running our analysis first on the fw-only graph, and then on the joint graph. This would
432
+ # require an extra round of tracing though, so it's more efficient to do in-line here.
433
+ assert (
434
+ isinstance(args, tuple)
435
+ and len(args) == 2
436
+ and isinstance(args[0], (list, tuple))
437
+ )
438
+ # Only look at mutations that happened to forward inputs (e.g. fw buffers that were saved for bw)
439
+ primals_before = args[0]
440
+ primals_after = pytree.tree_map(from_fun, f_args[0])
441
+ for idx, (f_inpt, before, after, inpt_info) in enumerate(
442
+ zip(f_args[0], primals_before, primals_after, meta.input_info)
443
+ ):
444
+ # Store information about mutations in joint(for backward analysis)
445
+ joint_mutates_data = has_data_mutation(f_inpt)
446
+
447
+ joint_mutates_metadata = has_metadata_mutation(
448
+ f_inpt, before, check_only_storage_mutation=False
449
+ )
450
+
451
+ # Ban metadata mutations on fw inputs during the bw
452
+ if not inpt_info.mutates_metadata:
453
+ assert (
454
+ not joint_mutates_metadata
455
+ ), "Found a graph input that had its metadata mutated in the backward. This is not supported"
456
+
457
+ # Ban storage resizing on fw inputs during the bw
458
+ if not inpt_info.mutation_inductor_storage_resize:
459
+ assert not was_inductor_storage_resized(
460
+ f_inpt
461
+ ), "Found a graph input that had storage resizing in the backward. This is not supported"
462
+
463
+ # Allow data mutations on fw inputs during the bw, but only if they do not require grad
464
+ # So we can guarantee that we can keep the mutations in the graph
465
+ if (
466
+ joint_mutates_data
467
+ and not inpt_info.mutates_data
468
+ and not inpt_info.mutates_storage_metadata
469
+ ):
470
+ # Not banning here mutations on inpt_info.requires_grad -
471
+ # we'll check at runtime and fail only when backward is under torch.is_grad_enabled (create_graph)
472
+ # Add node meta for copy_ for partitioner that this node should be in backward graph.
473
+ with torch.fx.traceback.preserve_node_meta(), set_partitioner_tag_must_be_in_backward():
474
+ before.copy_(after)
475
+ meta.indices_of_inputs_that_requires_grad_with_mutations_in_bw.append(
476
+ idx
477
+ )
478
+ # Now that we covered mutations to *forward* inputs during the backward,
479
+ # we also need to cover mutations to *backward-only* inputs during the backward (e.g. mutation to a grad_out).
480
+ # Today, we will just error in all cases of this happening unless someone needs us to support it.
481
+ tangents_before = args[1]
482
+ tangents_after = pytree.tree_map(from_fun, f_args[1])
483
+ for f_inpt, before, after in zip(
484
+ f_args[1], tangents_before, tangents_after
485
+ ):
486
+ assert not has_metadata_mutation(
487
+ f_inpt, before, check_only_storage_mutation=False
488
+ ), "Found an input to the backward that had metadata mutated during the backward pass. This is not supported"
489
+ if has_data_mutation(f_inpt):
490
+ can_be_in_graph = _check_if_mutation_can_be_in_graph(
491
+ keep_input_mutations=True,
492
+ mutates_data=True,
493
+ mutates_metadata=False,
494
+ mutations_hidden_from_autograd=are_all_mutations_hidden_from_autograd(
495
+ f_inpt
496
+ ),
497
+ mutations_under_no_grad_or_inference_mode=are_all_mutations_under_no_grad_or_inference_mode(
498
+ f_inpt
499
+ ),
500
+ mutates_storage_metadata=False,
501
+ mutation_inductor_storage_resize=was_inductor_storage_resized(
502
+ f_inpt
503
+ ),
504
+ requires_grad=f_inpt.requires_grad,
505
+ )
506
+ assert (
507
+ can_be_in_graph
508
+ ), "a backward input that had data mutated in an autograd-aware way. This is not supported"
509
+ # Perform the input mutation
510
+ with torch.fx.traceback.preserve_node_meta():
511
+ before.copy_(after)
512
+
513
+ if aot_config.keep_inference_input_mutations:
514
+ # Note: This is a bit annoying. There's a layering issue here, where:
515
+ # (1) functionalization needs to operate on **synthetic base** inputs, before unpacking them into the "real" inputs.
516
+ # (2) For keep_input_mutations, we support tracing a call to copy_() directly on mutated inputs.
517
+ # However, we **only** want to support this for inputs that have data-only (and no metadata) mutations,
518
+ # because inductor (and backends in generally) would prefer not to see these (e.g. as_strided_(), resize_()).
519
+ # This makes it pretty difficult for this logic to operate on synthetic bases.
520
+ # (3) In addition, there are cases where it's significantly cheaper to perform the copy on the individual
521
+ # (unpacked) input aliases, instead of the synthetic base.
522
+ # Example case where (3) could be important:
523
+ #
524
+ # def f(x, y):
525
+ # x.mul_(2)
526
+ # y.mul_(3)
527
+ # return x, y
528
+ # a = torch.ones(1'000'000)
529
+ # x, y = out(a[0:9], a[1:10])
530
+ #
531
+ # It would be much better to add copy_() calls into the graph for the two tiny slices, instead of materializing
532
+ # a giant "updated synthetic base" and copying into a's entire storage.
533
+ #
534
+ # For now, we are pessimistically not performing the optimization from (3);
535
+ # we will materialize an "updated" synthetic base, and copy it back to the synthetic input base.
536
+ # This allows us to factor aot autograd much more nicely, since only one area of the code needs to worry
537
+ # about synthetic bases.
538
+ for i, (inpt_old, inpt_f) in enumerate(
539
+ zip(args, f_args) if not trace_joint else zip(args[0], f_args[0])
540
+ ):
541
+ if not isinstance(inpt_f, torch.Tensor):
542
+ continue
543
+ assert is_fun(inpt_f)
544
+ inpt_new = from_fun(inpt_f)
545
+ if (
546
+ meta.input_info[i].mutation_type
547
+ == MutationType.MUTATED_IN_GRAPH
548
+ ):
549
+ # See Note [set_() Input Mutations in AOTAutograd]
550
+ # all mutations on the input must be under no_grad, so it is safe to put in the graph
551
+ # Here, we're saying that if an input experienced a set call, inp.set_(other),
552
+ # then we can effectively not have to worry about whether its data was mutated.
553
+ # There are 3 cases:
554
+ # (1) We mutate inp *after* the set_() call. other is a graph intermediate.
555
+ # In this case, we're not really mutating the input storage of "inp";
556
+ # we're mutating the storage of an intermdiate value (other),
557
+ # and slamming that storage into the input tensor. So no data mutation is necessary.
558
+ # (2) We mutate inp *after* the set_() call. other is a graph *input*.
559
+ # In this case, the data mutation will be properly handled in the runtime
560
+ # epilogue during the processing of "other"
561
+ # (3) We mutate inp *before* the set_() call.
562
+ # This case is *not* currently handled.
563
+ if meta.input_info[i].mutates_storage_metadata:
564
+ with torch.no_grad():
565
+ inpt_old.set_(inpt_new)
566
+
567
+ # Note [Ordering of resize_() and set_()]
568
+ # Importantly: the common usage in FSDP is that we have a dummy parameter
569
+ # that sees a set_() and **Then** a resize_().
570
+ # We must put those mutations into the graph in the same order,
571
+ # Since running them in the opposite order will have different behavior.
572
+ # We fully ban resize_() followed by set_() for now, although in principal
573
+ # we could support this
574
+ if meta.input_info[i].mutation_inductor_storage_resize:
575
+ # resizing is not supported on subclasses (we error earlier if this happens)
576
+ from torch._subclasses.functional_tensor import (
577
+ FunctionalTensor,
578
+ )
579
+
580
+ assert isinstance(inpt_f, FunctionalTensor)
581
+ old_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined]
582
+ inpt_f.elem, before=True
583
+ )
584
+ new_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined]
585
+ inpt_f.elem, before=False
586
+ )
587
+ if old_storage_size != new_storage_size:
588
+ assert (
589
+ old_storage_size == 0 or new_storage_size == 0
590
+ ), f"""\
591
+ Encountered a storage resize during tracing on input {i}. Old nbytes={old_storage_size}, new nbytes={new_storage_size}
592
+ We only support storage resizing on graph inputs as long as the input either starts or ends with a storage size of 0
593
+ (the case for FSDP)"""
594
+ torch.ops.inductor.resize_storage_bytes_(
595
+ inpt_old, new_storage_size
596
+ )
597
+ if new_storage_size == 0:
598
+ # Even if we marked the input as having a data mutation (thus needing a copy_()),
599
+ # We should **ignore** it if our input has no storage
600
+ # (this can happen if, e.g. we temporarily resize our input, copy data into it,
601
+ # and resize it back down to zero)
602
+ continue
603
+ # Optimization: if the copy_() is a no-op then don't include it in the graph.
604
+ # In theory inductor could optimize this away, however in fsdp, we end up with
605
+ # param.copy_(param), where param is a zero-storage-size tensor,
606
+ # and running this op in eager mode (using the aot_eager backend) will result in a segfault.
607
+ # So we may as well optimize it away here.
608
+ if inpt_old is inpt_new:
609
+ # (This check needs to be done after putting resize_() in the graph,
610
+ # since a resize_(0) doesn't actually change the FunctionalTensor's inner tensor)
611
+ continue
612
+ # We found an input that had a (data-only) mutation.
613
+ # Since keep_input_mutations is set, we need to faithfully apply a copy_()
614
+ # so the compiler will see the input mutation in the graph.
615
+ if (
616
+ meta.input_info[i].mutates_data
617
+ and meta.input_info[i].mutations_hidden_from_autograd
618
+ ):
619
+ # Hidden from autograd = run under no_grad, **and** don't bump VC
620
+ # (although if the tensor was created in inference mode, it has no VC)
621
+ if inpt_old.is_inference():
622
+ maybe_preserve_vc = nullcontext()
623
+ else:
624
+ maybe_preserve_vc = torch.autograd._unsafe_preserve_version_counter(
625
+ inpt_old # type: ignore[assignment]
626
+ )
627
+ with torch.no_grad(), maybe_preserve_vc:
628
+ inpt_old.copy_(inpt_new)
629
+ elif (
630
+ meta.input_info[i].mutates_data
631
+ and meta.input_info[
632
+ i
633
+ ].mutations_under_no_grad_or_inference_mode
634
+ ):
635
+ # Under no_grad = run under no_grad (we still bump the VC though)
636
+ # (inference_mode will also bump the VC, as long as the tensor in question
637
+ # was created outside of inference_mode)
638
+ with torch.no_grad():
639
+ inpt_old.copy_(inpt_new)
640
+ elif meta.input_info[i].mutates_data:
641
+ inpt_old.copy_(inpt_new)
642
+
643
+ # When an output tensor is a functionalized mutated input, and we
644
+ # were able to move the mutation in to the graph then we can return
645
+ # the mutated input directly. This prevents duplicating the
646
+ # tensors contents.
647
+ flat_outs, outs_spec = pytree.tree_flatten(f_outs)
648
+ flat_outs = [from_fun(o) for o in flat_outs]
649
+ num_outs = len(meta.output_info)
650
+
651
+ for i in range(num_outs):
652
+ info = meta.output_info[i]
653
+ if info.output_type != OutputType.is_input:
654
+ continue
655
+
656
+ assert info.base_idx is not None
657
+ if (
658
+ meta.input_info[info.base_idx].mutation_type
659
+ == MutationType.MUTATED_IN_GRAPH
660
+ ):
661
+ fw_args = args[0] if trace_joint else args
662
+ flat_outs[i] = fw_args[info.base_idx]
663
+ return pytree.tree_unflatten(flat_outs, outs_spec)
664
+
665
+ return pytree.tree_map(from_fun, f_outs)
666
+
667
+ # Kinda annoying, but needed to make sure that the fx graph we trace out has "primals"
668
+ # and "tangents" as its input names (which are special-cased by the partitioner)
669
+ # TODO (tmanlaibaatar) revisit this if we ever need to turn on non-strict joint graph export
670
+ def joint_helper(primals, tangents):
671
+ return _functionalized_f_helper(primals, tangents)
672
+
673
+ helper = joint_helper if trace_joint else _functionalized_f_helper
674
+ if config.functionalize_rng_ops:
675
+ # Setup the wrapper for functionalization of rng ops
676
+ helper, args = create_functionalized_rng_ops_wrapper(helper, args, trace_joint)
677
+
678
+ return helper, args
679
+
680
+
681
+ def handle_effect_tokens_fn(
682
+ fn,
683
+ args,
684
+ *,
685
+ meta: ViewAndMutationMeta,
686
+ trace_joint: bool,
687
+ ) -> Any:
688
+ num_tokens = len(meta.tokens)
689
+
690
+ @wraps(fn)
691
+ def inner_fn(*args):
692
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
693
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
694
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
695
+ )
696
+
697
+ with disable_above:
698
+ # See Note [Side-Effectful Tokens in AOTAutograd]
699
+ if trace_joint:
700
+ assert isinstance(args, tuple) and isinstance(args[0], (list, tuple))
701
+ tokens = args[0][:num_tokens]
702
+ assert all(token.numel() == 0 for token in tokens)
703
+ args = (args[0][num_tokens:], *args[1:])
704
+ else:
705
+ tokens = args[:num_tokens]
706
+ assert all(token.numel() == 0 for token in tokens)
707
+ args = args[num_tokens:]
708
+
709
+ # Populate the current FunctionalTensorMode with the tokens per
710
+ # operator. See Note [FunctionalTensorMode is Stateful]
711
+ functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode(
712
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
713
+ )
714
+ assert functional_tensor_mode is not None
715
+ f_tokens = pytree.tree_map(to_fun, tokens)
716
+ for i, k in enumerate(meta.tokens.keys()):
717
+ functional_tensor_mode._tokens[k] = f_tokens[i]
718
+
719
+ # Run the joint
720
+ outs = fn(*args)
721
+
722
+ # Return both the tokens and the outputs
723
+ # See Note [Side-Effectful Tokens in AOTAutograd]
724
+ if trace_joint:
725
+ assert len(outs) == 2
726
+ assert len(functional_tensor_mode._tokens_forward_output) == num_tokens
727
+ fwd_out_tokens = functional_tensor_mode._tokens_forward_output.values()
728
+
729
+ bwd_out_tokens = functional_tensor_mode._tokens.values()
730
+
731
+ f_fwd_out_tokens = [from_fun(t) for t in fwd_out_tokens]
732
+ f_bwd_out_tokens = [from_fun(t) for t in bwd_out_tokens]
733
+
734
+ meta.num_backward_tokens = len(bwd_out_tokens)
735
+ return ((*f_fwd_out_tokens, *outs[0]), (*outs[1], *f_bwd_out_tokens))
736
+
737
+ out_tokens = [from_fun(t) for t in functional_tensor_mode._tokens.values()]
738
+ return (*out_tokens, *outs)
739
+
740
+ # Additionally pass in tokens as inputs
741
+ # See Note [Side-Effectful Tokens in AOTAutograd]
742
+ additional_fwd_token_inputs = [torch.tensor([])] * num_tokens
743
+
744
+ if trace_joint:
745
+ args = ([*additional_fwd_token_inputs, *args[0]], *args[1:])
746
+ else:
747
+ args = [*additional_fwd_token_inputs, *args]
748
+ return inner_fn, args
749
+
750
+
751
+ # Given a function operating on Subclass -> Subclass, returns an function that operates on Tensor -> Tensor
752
+ # Also returns:
753
+ # - the new set of arguments to pass into this function (now that tensor subclasses have been eliminated)
754
+ # - the updated ViewAndMutationMeta for this dense -> dense function.
755
+ # The other important arguments are:
756
+ # - flat_fn_maybe_joint: when is_joint_structure=True, this is the joint fw-bw function.
757
+ # when is_joint_structure=False, this is just the forward function.
758
+ # - fw_only: this is *always* the forward-only function.
759
+ # Why do we need this? We need to collect updated ViewAndMutationMeta on our new dense -> dense functions.
760
+ # In particular, we need this to tell the partitioner how many dense forward outputs there are.
761
+ def aot_dispatch_subclass(
762
+ flat_fn_maybe_joint,
763
+ args: list[Any],
764
+ *,
765
+ is_joint_structure: bool,
766
+ meta: ViewAndMutationMeta,
767
+ fw_only: Callable,
768
+ ) -> SubclassTracingInfo:
769
+ # Skip logic if we don't need to trace through any subclasses
770
+ req_subclass_dispatch = requires_subclass_dispatch(args, meta)
771
+ if not req_subclass_dispatch:
772
+ return SubclassTracingInfo(
773
+ plain_tensor_trace_fn=flat_fn_maybe_joint,
774
+ plain_tensor_args=args,
775
+ maybe_subclass_meta=None,
776
+ )
777
+
778
+ # TODO: add subclass guards (later PR).
779
+
780
+ # What's going on here? We need to compute subclass metadata about the outputs of the joint (grad_inputs).
781
+ # Annoying: we don't know the grad input metas until we're in the middle of tracing the joint,
782
+ # so we set it later, while we're tracing the joint (see inner_fn() below).
783
+ # Another option would be to run our run_functionalized_fw_and_collect_metadata() function
784
+ # directly on the joint, but this would hurt compile time (adding yet another pass through the joint).
785
+ subclass_meta = SubclassMeta()
786
+
787
+ def inner_fn(fn, args, *, use_trace_joint: bool):
788
+ # Step 1: wrap tensor inputs into subclasses if necessary
789
+ all_args = wrap_tensor_subclasses_maybe_joint(
790
+ args, is_joint_structure=use_trace_joint, meta=meta
791
+ )
792
+
793
+ # Step 2: call the inner function, with our (maybe subclass) inputs
794
+ wrapped_outs = fn(*all_args)
795
+
796
+ if use_trace_joint:
797
+ # See Note: [Computing Subclass Metadata about grad_inputs]
798
+ # We also stash subclass info on our grad_inputs, if we're tracing the joint.
799
+ nonlocal subclass_meta
800
+ assert isinstance(wrapped_outs, tuple) and len(wrapped_outs) == 2
801
+ # Don't need fw outs since we already have subclass metadata on them
802
+ grad_inputs = wrapped_outs[1]
803
+ subclass_meta.grad_input_metas = create_subclass_meta(grad_inputs)
804
+
805
+ # Add extra symints as outputs to the forward/backward graphs
806
+ # ignore nested ints here
807
+ forward_outs = unwrap_tensor_subclasses(
808
+ wrapped_outs[0], append_symints=True
809
+ )
810
+ # ignore nested ints here
811
+ backward_outs = unwrap_tensor_subclasses(
812
+ wrapped_outs[1], append_symints=True
813
+ )
814
+ return (forward_outs, backward_outs)
815
+
816
+ # Step 3: Unwrap any subclass outputs back into dense tensors
817
+ unwrapped_outs = unwrap_tensor_subclasses(wrapped_outs, append_symints=True)
818
+ return unwrapped_outs
819
+
820
+ def joint_fn(primals, tangents):
821
+ with maybe_enable_thunkify():
822
+ return inner_fn(
823
+ flat_fn_maybe_joint, (primals, tangents), use_trace_joint=True
824
+ )
825
+
826
+ def fw_fn(*primals):
827
+ with maybe_enable_thunkify():
828
+ return inner_fn(flat_fn_maybe_joint, primals, use_trace_joint=False)
829
+
830
+ def metadata_fn(*primals):
831
+ return inner_fn(fw_only, primals, use_trace_joint=False)
832
+
833
+ if is_joint_structure:
834
+ args_unwrapped = (
835
+ # Add extra symints (size/strides) as input to the forward graph
836
+ unwrap_tensor_subclasses(args[0], append_symints=True),
837
+ # We pass append_symints=False here because the partitioner will
838
+ # capture and add any extra argument
839
+ unwrap_tensor_subclasses(args[1], append_symints=False),
840
+ )
841
+ else:
842
+ args_unwrapped = unwrap_tensor_subclasses(args, append_symints=True)
843
+ remapped_static_indices = remap_unwrapped_subclass_arg_indices(
844
+ args, meta.static_input_indices
845
+ )
846
+
847
+ if is_joint_structure:
848
+ primals_unwrapped = args_unwrapped[0]
849
+ fn_to_trace = joint_fn
850
+ else:
851
+ primals_unwrapped = args_unwrapped
852
+ fn_to_trace = fw_fn
853
+
854
+ # Note: [Partitioner handling for Subclasses, Part 1]
855
+ # The way the partitioner works is that:
856
+ # (1) we pass is a single graph containing the joint fw/bw,
857
+ # where the # of graph outputs corresponds to # fw_outputs + # grad_inputs
858
+ # (2) The partitioner accepts an arguments, num_fwd_outputs,
859
+ # and assumes that the first "num_fwd_outputs" graph outputs correspond
860
+ # to outputs of the forward graph.
861
+ # How do tensor subclasses enter the picture?
862
+ # the num_fwd_outputs in the final graph is actually non-trivial to compute,
863
+ # because it can be influenced by input mutations and intermediate bases.
864
+ # So we compute it by inspecting the current ViewAndMutationMeta object.
865
+ # However, the original ViewAndMutationMeta that we computed was created
866
+ # on the subclass -> subclass graph,
867
+ # which can have a different number of outputs than the dense -> dense graph.
868
+ # That's why we created a fresh metadata object on the dense -> dense function here,
869
+ # and plumb it back up to the partitioner.
870
+ # See Note: [Partitioner handling for Subclasses, Part 2] for more info.
871
+ meta_updated = run_functionalized_fw_and_collect_metadata(
872
+ metadata_fn,
873
+ static_input_indices=remapped_static_indices,
874
+ keep_input_mutations=meta.keep_input_mutations,
875
+ is_train=meta.is_train,
876
+ )(*primals_unwrapped)
877
+
878
+ subclass_meta.fw_metadata = meta_updated
879
+
880
+ return SubclassTracingInfo(
881
+ plain_tensor_trace_fn=fn_to_trace,
882
+ plain_tensor_args=args_unwrapped,
883
+ maybe_subclass_meta=subclass_meta,
884
+ )
885
+
886
+
887
+ def create_functional_call(mod, params_spec, params_len, store_orig_mod=False):
888
+ # Redundant with dynamo, but worth having in case this gets invoked elsewhere.
889
+ # https://github.com/pytorch/pytorch/issues/103569
890
+
891
+ def functional_call(*args, **kwargs):
892
+ with stateless._reparametrize_module(
893
+ mod, pytree.tree_unflatten(args[:params_len], params_spec)
894
+ ), maybe_disable_thunkify():
895
+ if isinstance(mod, torch.fx.GraphModule):
896
+ with fx_traceback.preserve_node_meta(), warnings.catch_warnings():
897
+ warnings.filterwarnings(
898
+ "ignore", "Anomaly Detection has been enabled."
899
+ )
900
+ with torch.autograd.detect_anomaly(check_nan=False):
901
+ detect_fake_mode().epoch += 1
902
+ out = PropagateUnbackedSymInts(mod).run(
903
+ *args[params_len:], **kwargs
904
+ )
905
+ else:
906
+ out = mod(*args[params_len:], **kwargs)
907
+
908
+ if not isinstance(out, (tuple, list)):
909
+ raise RuntimeError(
910
+ "Graph output must be a (). This is so that we can avoid "
911
+ "pytree processing of the outputs. Please change the module to "
912
+ "have tuple outputs or use aot_module instead."
913
+ )
914
+ return out
915
+
916
+ # Note [Preserving the nn module stack metadata during export non-strict mode]
917
+ # This path is currently only used by the non-strict export flow,
918
+ # where we cannot rely on dynamo to preserve nn stack metadata in our captured graph.
919
+ # Instead, we stash the original user nn module here, and rely on `make_fx` to grab
920
+ # this stashed module and use it to track nn module stack metadata
921
+ if store_orig_mod and not hasattr(functional_call, "_orig_mod"):
922
+ functional_call._orig_mod = mod # type: ignore[attr-defined]
923
+
924
+ return functional_call
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/_aot_autograd/utils.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Contains various utils for AOTAutograd, including those for handling collections.
4
+ """
5
+
6
+ import dataclasses
7
+ import operator
8
+ import warnings
9
+ from contextlib import nullcontext
10
+ from functools import wraps
11
+ from typing import Any, Callable, Optional, Union
12
+
13
+ import torch
14
+ import torch.utils._pytree as pytree
15
+ from torch._library.fake_class_registry import FakeScriptObject
16
+ from torch._logging import getArtifactLogger
17
+ from torch._subclasses.fake_tensor import FakeTensor
18
+ from torch._subclasses.functional_tensor import FunctionalTensor
19
+ from torch.fx.experimental._backward_state import BackwardState
20
+ from torch.fx.experimental.proxy_tensor import py_sym_types
21
+
22
+
23
+ KNOWN_TYPES = [
24
+ torch.Tensor,
25
+ BackwardState,
26
+ int,
27
+ str,
28
+ float,
29
+ bool,
30
+ type(None),
31
+ *py_sym_types,
32
+ FakeScriptObject,
33
+ torch.ScriptObject,
34
+ ]
35
+
36
+ original_zip = zip
37
+
38
+ aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects")
39
+
40
+
41
+ def strict_zip(*iterables, strict=True, **kwargs):
42
+ if not strict:
43
+ return original_zip(*iterables, **kwargs)
44
+
45
+ length = len(iterables[0])
46
+ for iterable in iterables[1:]:
47
+ if len(iterable) != length:
48
+ raise ValueError(
49
+ "The iterables have different lengths and strict mode is enabled."
50
+ )
51
+
52
+ return original_zip(*iterables, **kwargs)
53
+
54
+
55
+ def _get_symint_hints(exprs):
56
+ """
57
+ Get the hints of a list/tuple of int/SymInt.
58
+ """
59
+ if isinstance(exprs, (list, tuple)):
60
+ return type(exprs)(_get_symint_hints(e) for e in exprs)
61
+ elif isinstance(exprs, torch.SymInt):
62
+ return exprs.node.shape_env.size_hint(exprs.node.expr)
63
+ else:
64
+ return exprs
65
+
66
+
67
+ def partial_flatten_asdict(obj: Any) -> Any:
68
+ if dataclasses.is_dataclass(obj):
69
+ return {
70
+ field.name: getattr(obj, field.name) for field in dataclasses.fields(obj)
71
+ }
72
+ elif isinstance(obj, (list, tuple)):
73
+ return obj.__class__([partial_flatten_asdict(item) for item in obj])
74
+ elif isinstance(obj, dict):
75
+ return {k: partial_flatten_asdict(v) for k, v in obj.items()}
76
+ else:
77
+ return obj
78
+
79
+
80
+ def normalize_as_list(x):
81
+ if isinstance(x, tuple):
82
+ return list(x)
83
+ elif isinstance(x, list):
84
+ return x
85
+ return [x]
86
+
87
+
88
+ def _get_autocast_states():
89
+ return [
90
+ torch.is_autocast_enabled("cuda"),
91
+ torch.is_autocast_enabled("cpu"),
92
+ torch.get_autocast_dtype("cuda"),
93
+ torch.get_autocast_dtype("cpu"),
94
+ torch.is_autocast_cache_enabled(),
95
+ ]
96
+
97
+
98
+ def make_boxed_func(f):
99
+ def g(args):
100
+ return f(*args)
101
+
102
+ g._boxed_call = True # type: ignore[attr-defined]
103
+ return g
104
+
105
+
106
+ def make_boxed_compiler(compiler):
107
+ @wraps(compiler)
108
+ def f(fx_g, inps):
109
+ out_f = compiler(fx_g, inps)
110
+ fx_g = make_boxed_func(out_f)
111
+ return fx_g
112
+
113
+ return f
114
+
115
+
116
+ def call_func_at_runtime_with_args(
117
+ f, args: Union[tuple[Any], list[Any]], steal_args=False, disable_amp=False
118
+ ):
119
+ if not steal_args:
120
+ args = list(args)
121
+ assert isinstance(args, list)
122
+
123
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
124
+ with context():
125
+ if getattr(f, "_boxed_call", False):
126
+ out = normalize_as_list(f(args))
127
+ else:
128
+ # TODO: Please remove soon
129
+ # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670
130
+ warnings.warn(
131
+ "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. "
132
+ "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. "
133
+ "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale."
134
+ )
135
+ out = normalize_as_list(f(*args))
136
+ return out
137
+
138
+
139
+ # Inspired by autodidax (thanks!)
140
+ class PytreeThunk:
141
+ spec: Optional[pytree.TreeSpec] = None
142
+ # These are some kinda dumb microoptimizations that save about 3-4 us of overhead.
143
+ is_simple: Optional[
144
+ bool
145
+ ] = None # if the output spec is a tuple/list, we won't bother unflattening it.
146
+ is_really_simple: Optional[bool] = None # if the output spec is a LeafSpec
147
+
148
+ def set(self, spec: pytree.TreeSpec) -> None:
149
+ assert self.spec is None or self.spec == spec
150
+ assert spec is not None
151
+ self.spec: pytree.TreeSpec = spec
152
+ if self.spec.type in {tuple, list} and all(
153
+ child.is_leaf() for child in spec.children_specs
154
+ ):
155
+ self.is_simple = True
156
+ if self.spec.is_leaf():
157
+ self.is_really_simple = True
158
+
159
+ def unflatten(self, x: list[Any]) -> Any:
160
+ if self.is_really_simple:
161
+ return x[0]
162
+ if self.is_simple:
163
+ return x
164
+ assert self.spec is not None
165
+ return pytree.tree_unflatten(x, self.spec)
166
+
167
+
168
+ # Creates a function that returns flattened inputs and outputs
169
+ # Also returns the output tree spec, which is needed to recover the "unflattened"
170
+ # output tree structure later.
171
+ def create_tree_flattened_fn(fn, args, kwargs=None) -> tuple[Callable, PytreeThunk]:
172
+ if kwargs is None:
173
+ kwargs = {}
174
+ # Save the args_spec for flat_tensor_args to unflatten while tracing
175
+ _, tensor_args_spec = pytree.tree_flatten((args, kwargs))
176
+ out_spec = PytreeThunk()
177
+
178
+ def flat_fn(*flat_args):
179
+ # The input are flattened tensor args. Prepare the args in the
180
+ # order that original function expects. Add static args as well.
181
+ # They will appear as tensor constants in the traced graph.
182
+ nonlocal out_spec
183
+ args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec)
184
+ tree_out = fn(*args, **kwargs)
185
+ flat_out, spec = pytree.tree_flatten(tree_out)
186
+ for i in flat_out:
187
+ is_known_type = False
188
+ for j in KNOWN_TYPES:
189
+ if isinstance(i, j):
190
+ is_known_type = True
191
+ break
192
+ if not is_known_type:
193
+ raise RuntimeError(
194
+ f"Found {type(i)} in output, which is not a known type. "
195
+ "If this type holds tensors, you need to register a pytree for it. "
196
+ "See https://github.com/pytorch/functorch/issues/475 for a brief "
197
+ "explanation why. If you don't need to register a pytree, please "
198
+ "leave a comment explaining your use case and we'll make this more "
199
+ "ergonomic to deal with"
200
+ )
201
+ out_spec.set(spec)
202
+ return flat_out
203
+
204
+ # Can't use functools.wraps here because the wrapper has different
205
+ # calling convention
206
+ if hasattr(fn, "_orig_mod"):
207
+ flat_fn._orig_mod = fn._orig_mod # type: ignore[attr-defined]
208
+
209
+ return flat_fn, out_spec
210
+
211
+
212
+ # This function takes in a tensor t, and returns one of t, t.view(), or t.clone().
213
+ # When tracing the joint forward + backward, for any inputs in the graph that are mutated,
214
+ # we need to clone them first (and similarly for metadata-only mutations, we need to view them first).
215
+ # The idea is that when we trace the backward, we need to pass in the *original* primals
216
+ # to autograd.grad(), before they were mutated.
217
+ # Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them.
218
+ # This means that "idx" here represents the index of the (potentially) synthetic base.
219
+ # What we need to do is:
220
+ # (1) map the current (post-synthetic-base calling convention) input argument index
221
+ # to int index pre-synthetic-base-calling-convention.
222
+ # (2) There could be multiple, if this index corresponds to a synthetic base
223
+ # that has multiple input aliases.
224
+ # (3) If any of those corresponding inputs get metadata mutations, then we clone the base.
225
+ def maybe_to_fresh_input(idx, t, meta):
226
+ if not isinstance(t, torch.Tensor):
227
+ return t
228
+ if idx in meta.mutated_inp_runtime_indices:
229
+ # We only need to bother cloning mutated inputs that participate in autograd.
230
+ if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data:
231
+ # Make sure the primal we pass to autograd.grad()
232
+ # sees the tensor before the mutation
233
+ return t.clone()
234
+ if meta.input_info[idx] and meta.input_info[idx].mutates_metadata:
235
+ # Make sure the primal we pass to autograd.grad()
236
+ # sees the tensor before the metadata mutation
237
+ return t.view(t.shape)
238
+ return t
239
+
240
+
241
+ def is_with_effects(node):
242
+ return (
243
+ node.op == "call_function"
244
+ and node.target == torch.ops.higher_order.with_effects
245
+ )
246
+
247
+
248
+ def is_with_effects_op(node, op):
249
+ return is_with_effects(node) and node.args[1] == op
250
+
251
+
252
+ def unlift_tokens(fw_module, fw_metadata, aot_config, bw_module=None):
253
+ # Remove the tokens from the inputs/outputs of the graph since inductor does
254
+ # not want these extra inputs/outputs, and replace them with
255
+ # _make_token() to create a token, and _sink_tokens() to collect the
256
+ # tokens. See Note [Side-Effectful Tokens in AOTAutograd]
257
+ # Logic:
258
+ # 1. Inputs identified as input tokens:
259
+ # - If used as a first argument in with_effects
260
+ #
261
+ # 2. Outputs identified as output tokens:
262
+ # - If Produced by getitem(with_effects, 0)
263
+ #
264
+ # 3. Checks invariants of number input output tokens:
265
+ # forward:
266
+ # expected_num_erased_inputs == len(fw_metadata.tokens)
267
+ # expected_num_erased_outputs == len(fw_metadata.tokens)
268
+ # backward:
269
+ # expected_num_erased_inputs == fw_metadata.num_backward_tokens
270
+ # expected_num_erased_outputs == fw_metadata.num_backward_tokens
271
+ num_forward_tokens = len(fw_metadata.tokens)
272
+ num_backward_tokens = fw_metadata.num_backward_tokens
273
+
274
+ def rewrite_with_effects_input_token(module, node):
275
+ with module.graph.inserting_before(node):
276
+ new_token_node = module.graph.call_function(
277
+ torch.ops.prims._make_token.default, ()
278
+ )
279
+ new_token_node.meta["val"] = torch.tensor([])
280
+ new_token_node.meta["tensor_meta"] = torch.tensor([])
281
+
282
+ args = list(node.args)
283
+ args[0] = new_token_node
284
+ node.args = tuple(args)
285
+
286
+ def rewrite_output(module, node, output_token_nodes, other_output_args):
287
+ for output_token_node in output_token_nodes:
288
+ assert (
289
+ output_token_node.op == "call_function"
290
+ and output_token_node.target == operator.getitem
291
+ and output_token_node.args[1] == 0
292
+ )
293
+ with module.graph.inserting_before(node):
294
+ module.graph.call_function(
295
+ torch.ops.prims._sink_tokens.default,
296
+ (output_token_nodes,),
297
+ )
298
+ node.args = (other_output_args,)
299
+
300
+ def do(module, subgraph, expected_num_erased):
301
+ num_erased_inputs = 0
302
+ num_erased_outs = 0
303
+ input_nodes = []
304
+ input_token_nodes = set()
305
+ with_effect_nodes = []
306
+ output_token_nodes = []
307
+ other_output_nodes = []
308
+ for node in module.graph.nodes:
309
+ if node.op == "placeholder":
310
+ input_nodes.append(node)
311
+ elif is_with_effects(node):
312
+ with_effect_nodes.append(node)
313
+ if node.args[0] in input_nodes:
314
+ input_token_nodes.add(node.args[0])
315
+ rewrite_with_effects_input_token(module, node)
316
+ elif node.op == "output":
317
+ outs = node.args[0]
318
+ for out in outs:
319
+ if (
320
+ isinstance(out, torch.fx.node.Node)
321
+ and out.op == "call_function"
322
+ and out.target == operator.getitem
323
+ and out.args[1] == 0
324
+ and out.args[0] in with_effect_nodes
325
+ ):
326
+ output_token_nodes.append(out)
327
+ else:
328
+ other_output_nodes.append(out)
329
+
330
+ rewrite_output(module, node, output_token_nodes, other_output_nodes)
331
+ num_erased_outs = len(output_token_nodes)
332
+
333
+ for input_token_node in input_token_nodes:
334
+ module.graph.erase_node(input_token_node)
335
+
336
+ num_erased_inputs = len(input_token_nodes)
337
+
338
+ assert (
339
+ num_erased_inputs == expected_num_erased
340
+ ), f"{subgraph} num_erased_inputs:{num_erased_inputs} {input_token_nodes}!=expected {expected_num_erased}"
341
+ assert (
342
+ num_erased_outs == expected_num_erased
343
+ ), f"{subgraph} num_erased_outs:{num_erased_outs} {output_token_nodes}!=expected {expected_num_erased}"
344
+
345
+ module.recompile()
346
+
347
+ if num_forward_tokens > 0:
348
+ if aot_config.enable_log:
349
+ from torch._dynamo.utils import lazy_format_graph_code
350
+
351
+ aot_graphs_effects_log.debug(
352
+ "%s",
353
+ lazy_format_graph_code(
354
+ "Forward graph before unlifting tokens",
355
+ fw_module,
356
+ aot_config.aot_id,
357
+ include_stride=True,
358
+ include_device=True,
359
+ colored=True,
360
+ ),
361
+ )
362
+ do(
363
+ fw_module,
364
+ "forward",
365
+ num_forward_tokens,
366
+ )
367
+
368
+ if bw_module is not None and num_backward_tokens > 0:
369
+ if aot_config.enable_log:
370
+ from torch._dynamo.utils import lazy_format_graph_code
371
+
372
+ aot_graphs_effects_log.debug(
373
+ "%s",
374
+ lazy_format_graph_code(
375
+ "Backward graph before unlifting tokens",
376
+ bw_module,
377
+ aot_config.aot_id,
378
+ include_stride=True,
379
+ include_device=True,
380
+ colored=True,
381
+ ),
382
+ )
383
+ do(bw_module, "backward", num_backward_tokens)
384
+
385
+ # This is sad, but we need to update the metadata to get rid of
386
+ # the tokens.
387
+ fw_metadata.tokens = {}
388
+ fw_metadata.num_backward_tokens = 0
389
+
390
+
391
+ def root_module_when_exporting_non_strict(flat_fn):
392
+ # When exporting in non-strict mode, we wrap the root module in a specific pattern.
393
+ # See `_aot_export_non_strict` in torch.export._trace.py.
394
+ # We look for that wrapping pattern here.
395
+ if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"):
396
+ return flat_fn._orig_mod._export_root
397
+ else:
398
+ return None
399
+
400
+
401
+ def copy_fwd_metadata_to_bw_nodes(fx_g):
402
+ """
403
+ Input: `fx_g` which contains the joint fwd+bwd FX graph created by
404
+ aot_autograd.
405
+
406
+ This function walks the graph and copies over metadata from forward nodes
407
+ to backward nodes, using the `seq_nr` field as a one-to-many mapping
408
+ from forward node to backward node. This metadata is useful for performance
409
+ profiling and debugging.
410
+ """
411
+
412
+ def _is_forward_node_with_seq_nr(node):
413
+ # For now, assume that if nn_module_stack_metadata is populated, this
414
+ # node is from the forward. Ignore nodes without `seq_nr`.
415
+ # TODO(future): there is likely a less brittle way to do this by walking
416
+ # the descendants of graph inputs corresponding to fwd inputs, didn't
417
+ # seem obvious at first glance on how to partition graph inputs into
418
+ # fwd vs bwd without relying on string names.
419
+ return "nn_module_stack" in node.meta and "seq_nr" in node.meta
420
+
421
+ def _is_backward_node_with_seq_nr(node):
422
+ # For now, assume that if nn_module_stack_metadata is not populated,
423
+ # this node is from the backward. Ignore nodes without `seq_nr`.
424
+ # TODO(future): there is likely a less brittle way to do this, same
425
+ # as with the forward.
426
+ return ("nn_module_stack" not in node.meta) and "seq_nr" in node.meta
427
+
428
+ fwd_seq_nr_to_node = {}
429
+ for node in fx_g.graph.nodes:
430
+ if not _is_forward_node_with_seq_nr(node):
431
+ continue
432
+ seq_nr = node.meta["seq_nr"]
433
+ if seq_nr in fwd_seq_nr_to_node:
434
+ # If we already saw an op with the current `seq_nr`, that means
435
+ # that the current op did not create an autograd node, and there
436
+ # is no corresponding backward node, so we skip.
437
+ continue
438
+ fwd_seq_nr_to_node[node.meta["seq_nr"]] = node
439
+
440
+ for node in fx_g.graph.nodes:
441
+ if not _is_backward_node_with_seq_nr(node):
442
+ continue
443
+ # fwd_node should always exist, but handle non-existence just in case
444
+ fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"])
445
+ if fwd_node is not None:
446
+ node.meta["fwd_nn_module_stack"] = fwd_node.meta["nn_module_stack"]
447
+ node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack")
448
+
449
+
450
+ def register_buffer_assignment_hook(mod, assigned_buffers):
451
+ """
452
+ Register a hook that intercepts buffer assignments.
453
+ This is used to detect when a buffer is assigned to, and then we can
454
+ map that buffer to the corresponding proxy node in the graph.
455
+ """
456
+
457
+ def _map_assigned_buffer_to_proxy(_mod, name, buffer):
458
+ # We intercept buffer assignments on the root module through this hook.
459
+ if _mod._buffers is mod._buffers:
460
+ # either buffer is a functional tensor, which wraps a fake tensor
461
+ if isinstance(buffer, FunctionalTensor):
462
+ buffer = buffer.from_functional()
463
+ # or buffer is a fake tensor
464
+ assert isinstance(buffer, FakeTensor)
465
+ # The fake tensor in turn is associated with a proxy node.
466
+ proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode()
467
+ assert proxy_mode is not None
468
+ proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot(
469
+ buffer, proxy_mode.tracer
470
+ ).proxy.node
471
+ # We map the assigned buffer to this proxy node.
472
+ assigned_buffers[name] = proxy.name
473
+ return buffer
474
+
475
+ return torch.nn.modules.module.register_module_buffer_registration_hook(
476
+ _map_assigned_buffer_to_proxy
477
+ )
478
+
479
+
480
+ def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool:
481
+ """
482
+ Checks if the module contains any metadata mutation ops.
483
+ """
484
+ for node in module.graph.nodes:
485
+ if (
486
+ node.op == "call_function"
487
+ and hasattr(node.target, "tags")
488
+ and torch.Tag.inplace_view in node.target.tags
489
+ ):
490
+ return True
491
+ return False
492
+
493
+
494
+ def get_cuda_generator_meta_val(device_idx: int):
495
+ """
496
+ Get a generator value to use as a meta val
497
+
498
+ newly cloned generator will not contain tensors. it is only Generators that are
499
+ registered to a CUDAGraph that contain tensors. since this does not contain Tensor
500
+ it is fine to use in the meta.
501
+ """
502
+ return torch.cuda.default_generators[device_idx].clone_state()
503
+
504
+
505
+ def top_saved_tensors_hooks():
506
+ return torch._C._autograd._top_saved_tensors_default_hooks(True)
507
+
508
+
509
+ def saved_tensors_hooks_are_inlineable(hooks) -> bool:
510
+ if not hooks:
511
+ return False
512
+ pack, unpack = hooks
513
+ return isinstance(pack, torch.fx.GraphModule) and isinstance(
514
+ unpack, torch.fx.GraphModule
515
+ )
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/aot_autograd.py ADDED
@@ -0,0 +1,1737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import itertools
4
+ from collections.abc import KeysView, Sequence
5
+ from contextlib import contextmanager, nullcontext
6
+ from functools import partial, wraps
7
+ from typing import Any, Callable, NewType, Optional, Protocol, TypeVar
8
+ from unittest.mock import patch
9
+
10
+ import torch
11
+ import torch._dynamo.logging
12
+ import torch.nn as nn
13
+ import torch.utils._pytree as pytree
14
+ import torch.utils.dlpack
15
+ from torch import Tensor
16
+ from torch._decomp.decompositions_for_rng import PhiloxStateTracker, rng_decompositions
17
+ from torch._dispatch.python import enable_python_dispatcher
18
+ from torch._dynamo import compiled_autograd
19
+ from torch._dynamo.utils import (
20
+ CompileEventLogger,
21
+ dynamo_timed,
22
+ preserve_rng_state,
23
+ set_feature_use,
24
+ )
25
+ from torch._guards import detect_fake_mode
26
+ from torch._inductor.cudagraph_utils import BoxedDeviceIndex
27
+ from torch._inductor.output_code import OutputCode
28
+ from torch._inductor.utils import BoxedBool, InputType
29
+ from torch._subclasses import FakeTensor, FakeTensorMode
30
+ from torch.fx.experimental.proxy_tensor import (
31
+ _pytree_subclasses_that_lose_info,
32
+ make_fx,
33
+ )
34
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
35
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
36
+
37
+
38
+ static_inputs_log = torch._logging.getArtifactLogger(
39
+ __name__, "cudagraph_static_inputs"
40
+ )
41
+ from . import config
42
+ from ._aot_autograd.autograd_cache import ( # noqa: F401
43
+ AOTAutogradCache,
44
+ autograd_cache_key,
45
+ should_use_local_autograd_cache,
46
+ should_use_remote_autograd_cache,
47
+ )
48
+ from ._aot_autograd.collect_metadata_analysis import ( # noqa: F401
49
+ run_functionalized_fw_and_collect_metadata,
50
+ )
51
+ from ._aot_autograd.functional_utils import ( # noqa: F401
52
+ _check_if_mutation_can_be_in_graph,
53
+ are_all_mutations_hidden_from_autograd,
54
+ are_all_mutations_under_no_grad_or_inference_mode,
55
+ assert_functional_graph,
56
+ from_fun,
57
+ gen_alias_from_base,
58
+ has_data_mutation,
59
+ has_metadata_mutation,
60
+ is_fun,
61
+ sync_functional_tensor,
62
+ to_fun,
63
+ )
64
+ from ._aot_autograd.input_output_analysis import ( # noqa: F401
65
+ compute_overlapping_inputs,
66
+ create_graph_signature,
67
+ create_synthetic_base_metadata,
68
+ remove_dupe_metadata,
69
+ )
70
+ from ._aot_autograd.jit_compile_runtime_wrappers import ( # noqa: F401
71
+ aot_dispatch_autograd,
72
+ aot_dispatch_base,
73
+ aot_dispatch_export,
74
+ )
75
+ from ._aot_autograd.logging_utils import ( # noqa: F401
76
+ callback_set,
77
+ describe_input,
78
+ format_guard_bug_msg,
79
+ get_aot_compilation_context,
80
+ get_aot_graph_name,
81
+ get_graph_being_compiled,
82
+ graph_being_compiled,
83
+ model_name,
84
+ nth_graph,
85
+ set_model_name,
86
+ setup_stacktrace_preservation_hooks,
87
+ track_graph_compiling,
88
+ )
89
+ from ._aot_autograd.runtime_wrappers import ( # noqa: F401
90
+ AOTDedupeWrapper,
91
+ AOTSyntheticBaseWrapper,
92
+ )
93
+ from ._aot_autograd.schemas import ( # noqa: F401
94
+ AOTConfig,
95
+ BackwardSignature,
96
+ FQN,
97
+ GraphInputName,
98
+ GraphOutputName,
99
+ GraphSignature,
100
+ InputAliasInfo,
101
+ MutationType,
102
+ OutputAliasInfo,
103
+ OutputType,
104
+ SubclassCreationMeta,
105
+ SubclassMeta,
106
+ TensorAlias,
107
+ ViewAndMutationMeta,
108
+ )
109
+ from ._aot_autograd.subclass_utils import ( # noqa: F401
110
+ requires_subclass_dispatch,
111
+ unwrap_tensor_subclasses,
112
+ unwrap_tensor_subclasses_with_indices_to_original,
113
+ wrap_tensor_subclasses,
114
+ wrap_tensor_subclasses_maybe_joint,
115
+ )
116
+ from ._aot_autograd.traced_function_transforms import ( # noqa: F401
117
+ aot_dispatch_subclass,
118
+ create_functional_call,
119
+ create_functionalized_fn,
120
+ create_functionalized_rng_ops_wrapper,
121
+ create_joint,
122
+ fn_input_mutations_to_outputs,
123
+ fn_prepped_for_autograd,
124
+ )
125
+ from ._aot_autograd.utils import ( # noqa: F401
126
+ _get_autocast_states,
127
+ _get_symint_hints,
128
+ call_func_at_runtime_with_args,
129
+ create_tree_flattened_fn,
130
+ KNOWN_TYPES,
131
+ make_boxed_compiler,
132
+ make_boxed_func,
133
+ maybe_to_fresh_input,
134
+ normalize_as_list,
135
+ partial_flatten_asdict,
136
+ root_module_when_exporting_non_strict,
137
+ strict_zip,
138
+ )
139
+ from .partitioners import default_partition
140
+
141
+
142
+ zip = strict_zip
143
+
144
+ # This global counter increments every time we compile a graph with
145
+ # AOTAutograd. You can use this to correlate runtime error messages
146
+ # with compile time (e.g., if you get an error at runtime saying
147
+ # compiled graph 3 failed, you can set a breakpoint at compile time
148
+ # for this graph number to investigate further at compile time.)
149
+ #
150
+ # NB: this is different from get_aot_compilation_context, which tracks
151
+ # each underlying graph that is compiled. In contrast, AOT_COUNTER
152
+ # corresponds to top-level invocations of aot_module/aot_function;
153
+ # one counter is allocated per entire compiled block (but this block
154
+ # may involve compiling multiple subgraphs; e.g., for forwards/backwards)
155
+ AOT_COUNTER = itertools.count()
156
+
157
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159
+ #
160
+ # AOT Autograd contains a pretty non-trivial amount of logic to handle edge cases around aliasing and mutation
161
+ # that are external to the graph (they show up as side effects in some way when you run the graph).
162
+ #
163
+ # Take a look at `test_aotdispatch.py TestAOTAutograd.test_input_mutation*` tests for some examples functions
164
+ # and what they're compiled graphs looks like.
165
+ # Below is a very long comment detailing several edge cases, and showing how AOT Autograd handles them.
166
+ #
167
+ # Note [AOT Autograd: input data mutations]
168
+ #
169
+ # If we compile a function that mutates inputs, then those input mutations are real side effects
170
+ # that a user expects to see after running the compiled graph.
171
+ # However, the graph that we want to send to a backend needs to be *entirely* functional.
172
+ # The way we reconcile this difference is that we remove the mutations completely from the graph that we compile
173
+ # but we update the graph to return (updated_inputs, user_outputs).
174
+ # In the epilogue that runs after the compiled graph is executed, we copy the updated inputs back to the originals.
175
+ #
176
+ # Example: original user code:
177
+ # def f(x):
178
+ # x.mul_(2)
179
+ # out = x.mul(3)
180
+ # return out
181
+ #
182
+ # After AOT Autograd compiles, we end up with a:
183
+ # (a) compiled graph
184
+ # (b) autograd.Function.forward() method, that executes the compiled graph
185
+ # (c) wrapper function, that calls the autograd.Function.forward() and performs the epilogue
186
+ #
187
+ # The output of (a, b, c) are all written below.
188
+ #
189
+ # def compiled_forward_graph(x):
190
+ # x_updated = x.mul(2)
191
+ # out = x_updated.mul(3)
192
+ # return x_updated, out
193
+ #
194
+ # # x_updated gets a gradient in the compiled backward
195
+ # def compiled_backward_graph(grad_x_updated, grad_out):
196
+ # grad_x = ...
197
+ # return grad_x
198
+ #
199
+ # def autograd.Function.forward(x):
200
+ # x_updated, out = compiled_forward_graph(x)
201
+ # return x_updated, out
202
+ #
203
+ # def compiled_wrapper(x):
204
+ # x_updated, out = autograd.Function.apply(x)
205
+ # x.copy_(x_updated)
206
+ # return out
207
+ #
208
+ # Another important thing to note is that updated inputs (due to data mutations) *do* participate
209
+ # in the compiled backward graph! Since the compiled forward graph gets N extra outputs
210
+ # (due to updated inputs showing up as graph outputs),
211
+ # The compiled backward gets an additional N inputs.
212
+ # That way, during the x.copy_(x_updated) bit in the epilogue, gradients will flow from the updated input
213
+ # back to the original input.
214
+
215
+
216
+ # Note [AOT Autograd: input metadata mutations]
217
+ #
218
+ # For the same reason as input mutations, we also don't put input metadata mutations in the graph.
219
+ # Instead, we return the updated version of the input (a view), and mutate the input's metadata outside of the graph
220
+ #
221
+ # Example: original user code:
222
+ # def f(x):
223
+ # x.t_()
224
+ # out = x.mul(3)
225
+ # return out
226
+ #
227
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
228
+ # def compiled_forward_graph(x):
229
+ # x_updated = x.t()
230
+ # out = x_updated.mul(3)
231
+ # return x_updated, out
232
+ #
233
+ # # x_updated does *not* get a gradient in the compiled backward
234
+ # def compiled_backward_graph(grad_out):
235
+ # grad_x = ...
236
+ # return grad_x
237
+ #
238
+ # def autograd.Function.forward(x):
239
+ # x_updated, out = compiled_forward_graph(x)
240
+ # return x_updated, out
241
+ #
242
+ # def compiled_wrapper(x):
243
+ # x_updated, out = autograd.Function.apply(x)
244
+ # x.as_strided_(x_updated)
245
+ # return out
246
+
247
+
248
+ # Note [AOT Autograd: outputs aliasing inputs or intermediates!]
249
+ #
250
+ # AOT Autograd needs special handling for outputs that alias graph inputs or intermediates!
251
+ # Why?
252
+ # (1) autograd.Function.forward() has a limitation, where views that returned in the forward cannot later be mutated.
253
+ # (2) views don't need to be compiled in the graph anyway - it's cheap to generate them outside of the compiled graph,
254
+ # in an epilogue.
255
+ # For outputs that alias inputs, we do the following:
256
+ # (a) *still* return the aliased output as a graph output
257
+ # (b) In the AOT Autograd wrapper/epilogue, we don't return that aliased output. Instead, we use it to regenerate the output.
258
+ #
259
+ # For outputs that alias *intermediates*, we do the following:
260
+ # (a) Return the output in the compiled forward, **and** return it's ._base (a graph intermediates) as an output in the forward
261
+ # (b) Use (output, graph_intermediate) to regenerate the alias, and return that to the user (instead of the compiled fw output).
262
+ # You might wonder why we return the aliased output directly in the graph (and making the graph compute it),
263
+ # only to not return it and instead generate a fresh alias off of the intermediate,
264
+ # instead of (say) just storing metadata about the size/stride of the output somewhere to generate the alias. There are two reasons:
265
+ # (1) Getting the actual alias tensor allows us to use view-replay to generate the alias, instead of an as_strided() call
266
+ # (2) Inductor (and other backends) are free to change the memory format of graph outputs, if it results in better performance.
267
+ # This can result in problems if a user later tries to .view() that output expecting it to have one set of strides,
268
+ # when it has a different set of strides.
269
+ # By including the view op directly in the graph, inductor takes that into account when deciding what memory format
270
+ # the graph intermediate should be.
271
+ #
272
+ # Another important thing to note is how our traced backward() graph handles aliases.
273
+ # (this applies to outputs aliasing inputs, outputs aliasing intermediates,
274
+ # *and* updated inputs returned in the compiled forward due to metadata-only mutations).
275
+ # Any outputs that alias (either inputs or intermediates) do NOT participate in the compiled backward graph
276
+ # It would be wasteful to include them in the compiled backward(), because we regenerate them eagerly
277
+ # at the end of the forward.
278
+ #
279
+ # Example: original user code:
280
+ # def f(x):
281
+ # out1 = x.t()
282
+ # intermediate = x.mul(2)
283
+ # out2 = intermediate.view(-1)
284
+ # return out1, out2
285
+ #
286
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
287
+ # def compiled_forward_graph(x):
288
+ # out1 = x.t()
289
+ # intermediate = x.mul(2)
290
+ # out2 = intermediate.view(-1)
291
+ # # the compiled graph also returns the intermediate
292
+ # return out1, out2, intermediate
293
+ #
294
+ # # intermediate gets a gradient in the compiled backward.
295
+ # # both output aliases (out1 and out2) do not.
296
+ # def compiled_backward_graph(grad_intermediate):
297
+ # grad_x = ...
298
+ # return grad_x
299
+ #
300
+ # def autograd.Function.forward(x):
301
+ # out1, out2, intermediate = compiled_forward_graph(x)
302
+ # return out1, out2, intermediate
303
+ #
304
+ # def compiled_wrapper(x):
305
+ # out1, out2, intermediate = autograd.Function.apply(x)
306
+ # # regenerate out1 from the input
307
+ # out1_regenerated = out1._view_func(x)
308
+ # # regenerate out1 from the intermediate
309
+ # out2_regenerated = out2._view_func(intermediate)
310
+ # return out1_regenerated, out2_regenerated
311
+
312
+
313
+ # Note [AOT Autograd: mutations to inputs that alias other inputs]
314
+ #
315
+ # Another edge case that is (only partially) handled today is when an input is mutated, but itself aliases another input.
316
+ # AOT Autograd needs to **ensure** that functionalization knows that the two inputs are aliased to each other.
317
+ # That way, when the aliased input is accessed later in the graph, functionalization knows to "update" the alias
318
+ # given the mutation that occurred.
319
+ #
320
+ # This is handled by updating the calling convention: we create a "synthetic base" that becomes a new input
321
+ # in the compiled function, and we regenerate the original (aliased) inputs directly off of the base
322
+ # inside of the compiled function.
323
+ #
324
+ # This logic is fully encapsulated in aot_wrapper_synthetic_base()
325
+ #
326
+ # Example: original user code:
327
+ # def f(x, x_view):
328
+ # x.mul_(2)
329
+ # out = x * x_view
330
+ # return out
331
+ # f(x, x.view(-1))
332
+ #
333
+ # AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function):
334
+ # def compiled_forward_graph(base)
335
+ # x = generate_x(base)
336
+ # x_view = generate_x_view(base)
337
+ # x_updated = x.mul(2)
338
+ # x_view_updated = x_updated.view(-1)
339
+ # out = x_updated * x_view_updated
340
+ # return x_updated, out
341
+ #
342
+ # # The calling convention change from (aliases) -> (base) happens
343
+ # # *outside* of the autograd.Function.forward().
344
+ # # That means the forward() only has 1 input (base),
345
+ # # and the backward() only has 1 output (grad_base)
346
+ # def compiled_backward_graph(grad_out):
347
+ # grad_base = ...
348
+ # return grad_base
349
+ #
350
+ # def autograd.Function.forward(base):
351
+ # x_updated, out = compiled_forward_graph(base)
352
+ # return x_updated, out
353
+ #
354
+ # # The compiled wrapper is where we create synthetic bases.
355
+ # # The info on which inputs are mutated is also tracked *before* synthetic base creation.
356
+ # def compiled_wrapper(x, x_view):
357
+ # base = merge_view_inputs(x, x_view)
358
+ # x_updated, out = autograd.Function.apply(base)
359
+ # # x and x_view are aliased in eager mode, so this mutation to x will automatically affect x_view.
360
+ # x.copy_(x_updated)
361
+ # return out
362
+
363
+
364
+ # Note [AOT Autograd: Views to avoid tangents aliasing inputs]
365
+ #
366
+ # We view every forward output when creating out tangent tensors to handle the problematic
367
+ # case in which a subclass does extra aliasing between graph outputs/inputs in a way that
368
+ # is not visible above the sublass.
369
+ #
370
+ # Ordinarily, when constructing the joint function that we want to trace in AOTAutograd,
371
+ # we're guaranteed that the tangent tensors that we pass
372
+ # into the joint are distinct tensors from the primals. This is because when
373
+ # decide which forward outputs to create tangents for, we only create tangents
374
+ # for forward outputs that are not aliases of inputs (See Note
375
+ # [AOT Autograd: outputs aliasing inputs or intermediates!]).
376
+ #
377
+ # However, when wrapper tensor subclasses enter the picture, it is possible
378
+ # to have an output of the forward that is a subclass that is not an
379
+ # input / alias of an input, but one of its inner tensors is an alias!
380
+ # NestedTensor is an example: Performing an out-of-place pointwise op on a
381
+ # NestedTensor constructs a fresh NestedTensor that holds onto the input's
382
+ # offsets tensor directly.
383
+ #
384
+ # Having tangent tensors that are the same as the (primal) forward inputs,
385
+ # can cause problems during tracing as make_fx() will specialize on our
386
+ # duplicate inputs: If we passed in the same tensor for primals_1 and
387
+ # tangents_1 during tracing, make_fx() will happily sub out all usages of
388
+ # tangents_1 with primals_1 in the graph, which is not what we want.
389
+ #
390
+ # To work around this, we view every forward output when creating out tangent
391
+ # tensors so that tangents can never be the same as forward inputs even if
392
+ # forward inputs alias forward outputs.
393
+
394
+ # Note [Side-Effectful Tokens in AOTAutograd]
395
+ #
396
+ # We allow some some side-effectful operators in
397
+ # the post-AOTAutograd (functional) graph, such as prints and torchbind operations.
398
+ # To ensure that these side-effects are compatible to future graph passes that
399
+ # assume that the graph is functional, we will thread "effect tokens" to show
400
+ # data dependence between these side-effectful operators. Practically speaking,
401
+ # effect tokens are just dummy values (torch.tensor([])). The graph would look
402
+ # like the following:
403
+ #
404
+ # def gm(self, token0, reader):
405
+ # token1, frame = with_token(ordered_effect_op, (reader,), token0)
406
+ # frame = frame * 2
407
+ # token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
408
+ # frame2 = frame2 * 2
409
+ # return token2, frame, frame2
410
+ #
411
+ # We will pass the token as an input to the graph, thread it through
412
+ # side-effectful operators using the `with_effects` high order operator, and then
413
+ # return the updated token as an output.
414
+ # So the signature of the graph input would look something like
415
+ # (*tokens, *params_buffers, *user_inputs), and the signature of the graph
416
+ # output would look something like (*tokens, *outputs).
417
+ #
418
+ # However, Inductor does not want the concept of tokens in the final generated
419
+ # code's input and output. Since changing the graph signature inside of inductor
420
+ # is difficult, after generating the forward graph, we will run a pass to
421
+ # remove the tokens from the inputgenerate the following graph for Inductor, where
422
+ # the tokens are created and sunk within the graph, rather than as inputs and
423
+ # outputs:
424
+ #
425
+ # def gm(self, reader):
426
+ # token0 = torch.ops.prims._make_token()
427
+ # token1, frame = with_token(ordered_effect_op, (reader,), token0)
428
+ # frame = frame * 2
429
+ # token2, frame2 = with_token(ordered_effect_op, (reader,), token1)
430
+ # frame2 = frame2 * 2
431
+ # sink_token = torch.ops.prims._sink_tokens([token2])
432
+ # return frame, frame2
433
+
434
+ #
435
+ #
436
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
437
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
438
+
439
+
440
+ aot_autograd_decompositions = {}
441
+
442
+ FakifiedFlatArgs = NewType("FakifiedFlatArgs", list[Any])
443
+
444
+
445
+ TOutputCode = TypeVar("TOutputCode", bound=OutputCode)
446
+
447
+
448
+ class AOTDispatchCompiler(Protocol):
449
+ """
450
+ Represents a fw or bw_compiler passed to AOTAutograd.
451
+ """
452
+
453
+ def __call__(
454
+ self,
455
+ gm: torch.fx.GraphModule,
456
+ example_inputs: Sequence[InputType],
457
+ ) -> Any:
458
+ ...
459
+
460
+
461
+ # TODO: bikeshed on this name
462
+ class SerializableAOTDispatchCompiler(AOTDispatchCompiler):
463
+ """
464
+ Represents an AOTDispatchCompiler that returns an OutputCode, and is
465
+ therefore cacheable. SerializableAOTDispatchCompiler always return an OutputCode.
466
+ A _CompileFxCallable usually gets converted into an AOTDispatchCompiler after binding all of
467
+ the kwargs in _CompileFxKwargs.
468
+ """
469
+
470
+ def __init__(
471
+ self,
472
+ output_code_ty: type[TOutputCode],
473
+ compiler_fn: Callable[[torch.fx.GraphModule, Sequence[InputType]], TOutputCode],
474
+ ):
475
+ self.output_code_ty = output_code_ty
476
+ self.compiler_fn = compiler_fn
477
+
478
+ def __call__(
479
+ self,
480
+ gm: torch.fx.GraphModule,
481
+ example_inputs: Sequence[InputType],
482
+ ) -> OutputCode:
483
+ return self.compiler_fn(gm, example_inputs)
484
+
485
+
486
+ def process_inputs(
487
+ flat_args: list[Any],
488
+ aot_config: AOTConfig,
489
+ fake_mode: FakeTensorMode,
490
+ shape_env: Optional[ShapeEnv],
491
+ ignore_shape_env: bool = False,
492
+ ) -> FakifiedFlatArgs:
493
+ with fake_mode:
494
+
495
+ def convert(idx, x):
496
+ if shape_env is not None and not ignore_shape_env:
497
+ from torch._dynamo.source import ConstantSource
498
+
499
+ if isinstance(x, int):
500
+ # We always specialize on scalar values in export.
501
+ if aot_config.is_export:
502
+ return x
503
+ source = ConstantSource(f"sym_{idx}")
504
+ return shape_env.create_symintnode(
505
+ shape_env.create_symbol(x, source), hint=x, source=source
506
+ )
507
+ if isinstance(x, torch.ScriptObject):
508
+ return torch._library.fake_class_registry.maybe_to_fake_obj(
509
+ fake_mode, x
510
+ )
511
+ if not isinstance(x, torch.Tensor):
512
+ return x
513
+ if isinstance(x, FakeTensor):
514
+ assert x.fake_mode is fake_mode
515
+ return x
516
+ if is_traceable_wrapper_subclass(x):
517
+ attrs, _ = x.__tensor_flatten__()
518
+ if all(isinstance(getattr(x, attr), FakeTensor) for attr in attrs):
519
+ assert all(
520
+ getattr(x, attr).fake_mode is fake_mode for attr in attrs
521
+ )
522
+ return x
523
+
524
+ # see note [Tensor Fakification and Symbol Caching]
525
+ symbolic_context = None
526
+ source = None
527
+ trace = True
528
+ if tracing_context := torch._guards.TracingContext.try_get():
529
+ if x in tracing_context.tensor_to_context:
530
+ symbolic_context = tracing_context.tensor_to_context[x]
531
+ source = symbolic_context.tensor_source
532
+ # We already fakeified this tensor in Dynamo, don't
533
+ # dump the trace for it again
534
+ trace = False
535
+ if (
536
+ idx < aot_config.num_params_buffers
537
+ and config.static_weight_shapes
538
+ and not symbolic_context
539
+ ):
540
+ # TODO: Ensure that this codepath is never exercised from
541
+ # Dynamo
542
+ return fake_mode.from_tensor(x, static_shapes=True)
543
+
544
+ result = fake_mode.from_tensor(
545
+ x,
546
+ static_shapes=ignore_shape_env,
547
+ symbolic_context=symbolic_context,
548
+ source=source,
549
+ trace=trace,
550
+ )
551
+ return result
552
+
553
+ return FakifiedFlatArgs([convert(idx, x) for idx, x in enumerate(flat_args)])
554
+
555
+
556
+ def construct_fake_mode(
557
+ flat_args: list[Any], aot_config: AOTConfig
558
+ ) -> tuple[FakeTensorMode, Optional[ShapeEnv]]:
559
+ fake_mode = detect_fake_mode(flat_args)
560
+ if fake_mode is None:
561
+ shape_env = ShapeEnv() if aot_config.dynamic_shapes else None
562
+ fake_mode = FakeTensorMode(shape_env=shape_env)
563
+ else:
564
+ shape_env = fake_mode.shape_env
565
+ return (fake_mode, shape_env)
566
+
567
+
568
+ def create_aot_dispatcher_function(
569
+ flat_fn,
570
+ fake_flat_args: FakifiedFlatArgs,
571
+ aot_config: AOTConfig,
572
+ fake_mode: FakeTensorMode,
573
+ shape_env: Optional[ShapeEnv],
574
+ ) -> tuple[Callable, ViewAndMutationMeta]:
575
+ with dynamo_timed("create_aot_dispatcher_function", log_pt2_compile_event=True):
576
+ return _create_aot_dispatcher_function(
577
+ flat_fn, fake_flat_args, aot_config, fake_mode, shape_env
578
+ )
579
+
580
+
581
+ def _create_aot_dispatcher_function(
582
+ flat_fn,
583
+ fake_flat_args: FakifiedFlatArgs,
584
+ aot_config: AOTConfig,
585
+ fake_mode: FakeTensorMode,
586
+ shape_env: Optional[ShapeEnv],
587
+ ) -> tuple[Callable, ViewAndMutationMeta]:
588
+ """
589
+ Traces the forward and backward graphs of the attr:`flat_fn` to generate a
590
+ joint graph. The joint graph is an Fx graph with Aten ops. Please refer to
591
+ the tracing mechanism to understand the graph capturing details.
592
+
593
+ The joint graph is then passed through attr:`partition_fn` to isolate the
594
+ forward and backward portions, which are then respectively compiled via the
595
+ provided attr:`fw_compiler` and attr:`bw_compiler`.
596
+
597
+ The resulting compiled forward and backward graphs are then wrapped up in a
598
+ ``torch.autograd.Function`` object.
599
+
600
+ The calling convention here is that the first aot_config.num_params_buffers
601
+ inputs in flat_args are parameters and buffers, and the rest are inputs.
602
+
603
+ We use this to assume that parameters/buffer's shapes don't change.
604
+
605
+ Note: this function is used both by aot_function and aot_export (controlled by aot_config.is_export)
606
+ When aot_config.is_export is True, we return an FX graph + metadata
607
+ When aot_config.is_export is False, we return an ordinary runtime function
608
+ """
609
+
610
+ # This is the main entry point.
611
+ # TODO: Chillee argues that dynamo itself should pass in fake tensors to
612
+ # the list of arguments when compiling; at the moment we do not do this
613
+
614
+ if aot_config.decompositions is None:
615
+ aot_config.decompositions = {}
616
+
617
+ aot_config.decompositions = {
618
+ **aot_autograd_decompositions,
619
+ **aot_config.decompositions,
620
+ }
621
+
622
+ if config.functionalize_rng_ops:
623
+ # Update the decompositions with functionalized random decompositions
624
+ aot_config.decompositions = {
625
+ **rng_decompositions,
626
+ **aot_config.decompositions,
627
+ }
628
+
629
+ # Check flat_args to see if they're already fake. If so, use that fake
630
+ # mode instead.
631
+
632
+ python_dispatcher_mode = (
633
+ enable_python_dispatcher() if shape_env is not None else nullcontext()
634
+ )
635
+
636
+ # See NOTE: [Deferring tensor pack/unpack hooks until runtime]
637
+ # If any saved tensor hooks are active, we **don't** want to trace them.
638
+ # Instead, we'll let them run at runtime, around the custom autograd.Function
639
+ # that we generate in torch.compile.
640
+ with torch.autograd.set_multithreading_enabled(
641
+ False
642
+ ), preserve_rng_state(), (
643
+ fake_mode
644
+ ), (
645
+ python_dispatcher_mode
646
+ ), PhiloxStateTracker(), torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing():
647
+ from torch._library.fake_class_registry import (
648
+ FakeScriptObject,
649
+ maybe_to_fake_obj,
650
+ )
651
+
652
+ # Tracing may mutate the states the fake script object,
653
+ # so we need to duplicate the fake script objects so that subsequent tracing
654
+ # won't be affected.
655
+ def _dup_fake_script_obj(fake_flat_args):
656
+ return [
657
+ maybe_to_fake_obj(detect_fake_mode(fake_flat_args), arg.real_obj)
658
+ if isinstance(arg, FakeScriptObject)
659
+ else arg
660
+ for arg in fake_flat_args
661
+ ]
662
+
663
+ needs_autograd = any(
664
+ x.requires_grad for x in fake_flat_args if isinstance(x, Tensor)
665
+ )
666
+
667
+ with enable_python_dispatcher():
668
+ # Patch set_rng_state as set_rng_state with fake tensors is
669
+ # nonsensical. This does not affect the collection of metadata.
670
+ with patch("torch.cuda.set_rng_state", lambda *args: None):
671
+ mod = root_module_when_exporting_non_strict(flat_fn)
672
+ if mod is not None:
673
+ ctx = _detect_attribute_assignment(mod)
674
+ else:
675
+ ctx = nullcontext()
676
+
677
+ if torch._functorch.config.fake_tensor_propagate_real_tensors:
678
+ # Running dynamo_timed causes fake tensor issues when
679
+ # propagate real tensor is switched on.
680
+ dynamo_timed_ctx = nullcontext()
681
+ else:
682
+ dynamo_timed_ctx = dynamo_timed(
683
+ "aot_collect_metadata", log_pt2_compile_event=True
684
+ )
685
+
686
+ with dynamo_timed_ctx, ctx:
687
+ fw_metadata = run_functionalized_fw_and_collect_metadata(
688
+ flat_fn,
689
+ static_input_indices=aot_config.static_input_indices,
690
+ keep_input_mutations=aot_config.keep_inference_input_mutations,
691
+ is_train=needs_autograd,
692
+ pre_dispatch=aot_config.pre_dispatch,
693
+ is_export=aot_config.is_export,
694
+ )(*_dup_fake_script_obj(fake_flat_args))
695
+
696
+ req_subclass_dispatch = requires_subclass_dispatch(
697
+ fake_flat_args, fw_metadata
698
+ )
699
+ CompileEventLogger.try_add_pt2_compile(
700
+ "backend_compile", requires_subclass_dispatch=req_subclass_dispatch
701
+ )
702
+
703
+ output_and_mutation_safe = not any(
704
+ x.requires_grad
705
+ # view-type operations preserve requires_grad even in no_grad.
706
+ # Do not count aliases of inputs with requires_grad as reason to make a training graph,
707
+ # as AOTAutograd will perform view-replay to regenerate the view outputs at runtime,
708
+ # setting their grad_fn properly.
709
+ and not (
710
+ x.output_type
711
+ in (OutputType.alias_of_input, OutputType.is_input)
712
+ and fw_metadata.input_info[x.base_idx].requires_grad
713
+ )
714
+ for x in fw_metadata.output_info
715
+ ) and not any(
716
+ x.requires_grad
717
+ and x.mutates_data
718
+ and not x.mutations_under_no_grad_or_inference_mode
719
+ and not x.mutations_hidden_from_autograd
720
+ for x in fw_metadata.input_info
721
+ )
722
+
723
+ if needs_autograd and output_and_mutation_safe:
724
+ # We realized that none of the outputs require grad,
725
+ # and none of the inputs that require grad are mutated.
726
+ # so we actually have an inference graph.
727
+ needs_autograd = False
728
+ # A bit silly: right now in the subclass codepath, our ViewAndMutationMeta
729
+ # changes depending on whether we pass in is_train / keep_input_mutations,
730
+ # so we're forced to recompute the metadata.
731
+ # TODO: refactor the subclass path of run_functionalized_fw_and_collect_metadata
732
+ # so that this is unnecessary.
733
+ if req_subclass_dispatch:
734
+ fw_metadata = run_functionalized_fw_and_collect_metadata(
735
+ flat_fn,
736
+ keep_input_mutations=aot_config.keep_inference_input_mutations,
737
+ is_train=False,
738
+ pre_dispatch=aot_config.pre_dispatch,
739
+ static_input_indices=aot_config.static_input_indices,
740
+ )(*fake_flat_args)
741
+ else:
742
+ fw_metadata = ViewAndMutationMeta(
743
+ input_info=fw_metadata.input_info,
744
+ output_info=fw_metadata.output_info,
745
+ num_intermediate_bases=fw_metadata.num_intermediate_bases,
746
+ keep_input_mutations=aot_config.keep_inference_input_mutations,
747
+ traced_tangents=fw_metadata.traced_tangents,
748
+ subclass_inp_meta=fw_metadata.subclass_inp_meta,
749
+ subclass_fw_graph_out_meta=fw_metadata.subclass_fw_graph_out_meta,
750
+ subclass_tangent_meta=fw_metadata.subclass_tangent_meta,
751
+ is_train=False,
752
+ tokens=fw_metadata.tokens,
753
+ static_input_indices=fw_metadata.static_input_indices,
754
+ )
755
+
756
+ if fw_metadata.num_intermediate_bases > 0:
757
+ assert not req_subclass_dispatch, f"""\
758
+ torch.compile is currently being used with tensor subclass inputs:
759
+ {','.join([str(type(x)) for x in fake_flat_args])}. We are attempting to a compile a graph with two graph outputs
760
+ that alias one another, which is currently unsupported in the subclass use case. If you run into this,
761
+ please file a github issue"""
762
+
763
+ if aot_config.is_export:
764
+ # aot_export: ban input metadata mutations for now to keep shared code paths simpler.
765
+ # Keeping .resize_() in the graph will require some work
766
+ # Allowing it but keeping the graph functional will require some calling convention changes.
767
+ if len([x for x in fw_metadata.input_info if x.mutates_metadata]) != 0:
768
+ raise RuntimeError(
769
+ f"""\
770
+ Found an input that received a metadata mutation, through e.g. a call to `.resize_()` or `.transpose_()`.
771
+ This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
772
+
773
+ fw_metadata={str(fw_metadata)}"""
774
+ )
775
+ # In export, banning data mutations on inputs that require grad for now.
776
+ # This should be rare, and is tricky to get right. When we trace the backward,
777
+ # we currently trace with autograd.grad instead of .backward(), which makes it difficult
778
+ # to ensure that we run autograd all the way through the input **before** it saw the mutation.
779
+ if (
780
+ len(
781
+ [
782
+ x
783
+ for x in fw_metadata.input_info
784
+ if x.requires_grad and x.mutates_data
785
+ ]
786
+ )
787
+ != 0
788
+ ):
789
+ raise RuntimeError(
790
+ f"""\
791
+ Found a graph input that requires gradients, and received a mutation.
792
+ This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue.
793
+
794
+ fw_metadata={str(fw_metadata)}"""
795
+ )
796
+ if req_subclass_dispatch:
797
+ raise RuntimeError(
798
+ """\
799
+ aot_export is not currently supported with traceable tensor subclass.
800
+ If you need this feature, please comment on <CREATE_ISSUE_LINK>"""
801
+ )
802
+
803
+ # Need to decide on a strategy for functionalized RNG: toggling via global config seems bad,
804
+ # and turning it on will require a non-trivial calling convention change for any export runtime.
805
+ if config.functionalize_rng_ops:
806
+ raise RuntimeError(
807
+ """\
808
+ Functionalized RNG is not currently supported in the aot_export workflow. Please file a github issue,
809
+ or otherwise set torch._functorch.config.functionalize_rng_ops = False."""
810
+ )
811
+
812
+ def choose_dispatcher(needs_autograd, aot_config):
813
+ """
814
+ Pick a dispatcher based on the config rules.
815
+ """
816
+ if aot_config.is_export:
817
+ # export uses just the "graph bits", whereas the other
818
+ # two dispatchers include some extra work around handling a runtime epilogue
819
+ CompileEventLogger.try_add_pt2_compile(
820
+ "backend_compile", dispatch_mode="export"
821
+ )
822
+ return partial(aot_dispatch_export, needs_autograd=needs_autograd)
823
+ elif needs_autograd and not aot_config.pre_dispatch:
824
+ CompileEventLogger.try_add_pt2_compile(
825
+ "backend_compile", dispatch_mode="autograd"
826
+ )
827
+ return aot_dispatch_autograd
828
+ else:
829
+ CompileEventLogger.try_add_pt2_compile(
830
+ "backend_compile", dispatch_mode="inference"
831
+ )
832
+ return aot_dispatch_base
833
+
834
+ compiler_fn = choose_dispatcher(needs_autograd, aot_config)
835
+
836
+ compiled_fn, fw_metadata = compiler_fn(
837
+ flat_fn,
838
+ _dup_fake_script_obj(fake_flat_args),
839
+ aot_config,
840
+ fw_metadata=fw_metadata,
841
+ )
842
+ return compiled_fn, fw_metadata
843
+
844
+
845
+ def aot_function(
846
+ fn: Callable,
847
+ fw_compiler: Callable,
848
+ bw_compiler: Optional[Callable] = None,
849
+ partition_fn: Callable = default_partition,
850
+ decompositions: Optional[dict] = None,
851
+ num_params_buffers: int = 0,
852
+ keep_inference_input_mutations: bool = False,
853
+ inference_compiler: Optional[Callable] = None,
854
+ *,
855
+ # Whether or not to trace with dynamic shapes
856
+ dynamic=False,
857
+ enable_log=True,
858
+ ) -> Callable:
859
+ """
860
+ Traces the forward and backward graph of :attr:`fn` using torch dispatch
861
+ mechanism, and then compiles the generated forward and backward graphs
862
+ through :attr:`fw_compiler` and :attr:`bw_compiler`.
863
+
864
+ :func:`aot_function` traces the forward and backward graph ahead of time,
865
+ and generates a joint forward and backward graph. :attr:`partition_fn` is
866
+ then used to separate out forward and backward graphs. The partitioner
867
+ function can be used to perform optimizations such as recomputation. One can
868
+ set `decompositions` dictionary to decompose the operators into a sequence
869
+ of core or simpler operators supported by the backend compilers.
870
+
871
+ .. warning::
872
+ This API is experimental and likely to change.
873
+
874
+ Args:
875
+ fn (Callable): A Python function that takes one ore more arguments. Must
876
+ return one or more Tensors.
877
+ fw_compiler (Callable): A Python function that accepts an Fx graph with
878
+ Aten ops and input args, and returns a Callable that semantically is
879
+ equivalent to the input Fx graph.
880
+ bw_compiler (Optional[Callable]): A Python function that accepts an
881
+ Fx graph with Aten ops and input args, and returns a Callable that
882
+ semantically is equivalent to the input Fx graph. Default: None
883
+ (when None, it defaults to the :attr:`fw_compiler`)
884
+ partition_fn (Callable): A Python function that takes a joint forward
885
+ and backward graph, and partitions it into separate forward and
886
+ backward graphs.
887
+ decompositions (Dict): A dictionary to define the decomposition of
888
+ larger Aten ops into simpler or core Aten ops.
889
+ inference_compiler (Optional[Callable]): A Python function that accepts an
890
+ Fx graph with Aten ops and input args, and returns a Callable that
891
+ semantically is equivalent to the input Fx graph. inference_compiler is invoked
892
+ if no autograd is needed. Default: None
893
+ (when None, it defaults to the :attr:`fw_compiler`)
894
+ Returns:
895
+ Returns a ``Callable`` that retains the eager behavior of the original
896
+ :attr:`fn`, but with forward and backward graph compiled via
897
+ :attr:`fw_compile` and :attr:`bw_compile`.
898
+
899
+ A simple example usage of :func:`aot_function` is as follows. This example
900
+ will print the forward and backward graphs of the function ``fn``
901
+
902
+ >>> fn = lambda x : x.sin().cos()
903
+ >>> def print_compile_fn(fx_module, args):
904
+ >>> print(fx_module)
905
+ >>> return fx_module
906
+ >>> aot_fn = aot_function(fn, print_compile_fn)
907
+ >>> x = torch.randn(4, 5, requires_grad=True)
908
+ >>> aot_fn(x)
909
+ """
910
+
911
+ if bw_compiler is None:
912
+ bw_compiler = fw_compiler
913
+ if inference_compiler is None:
914
+ inference_compiler = fw_compiler
915
+ aot_config = AOTConfig(
916
+ fw_compiler=fw_compiler,
917
+ bw_compiler=bw_compiler,
918
+ inference_compiler=inference_compiler,
919
+ partition_fn=partition_fn,
920
+ decompositions=decompositions,
921
+ num_params_buffers=num_params_buffers,
922
+ aot_id=next(AOT_COUNTER),
923
+ keep_inference_input_mutations=keep_inference_input_mutations,
924
+ dynamic_shapes=dynamic,
925
+ aot_autograd_arg_pos_to_source=None,
926
+ is_export=False,
927
+ no_tangents=False,
928
+ enable_log=enable_log,
929
+ )
930
+ cached_res = None
931
+
932
+ @wraps(fn)
933
+ def returned_function(*args, **kwargs):
934
+ nonlocal cached_res
935
+ # Now flatten the tensor args
936
+ flat_args = pytree.arg_tree_leaves(*args, **kwargs)
937
+
938
+ # Compile the function and save it in the cache
939
+ if cached_res is None:
940
+ flat_fn, out_spec = create_tree_flattened_fn(fn, args, kwargs)
941
+ (fake_mode, shape_env) = construct_fake_mode(flat_args, aot_config)
942
+ fake_flat_args: FakifiedFlatArgs = process_inputs(
943
+ flat_args, aot_config, fake_mode, shape_env
944
+ )
945
+ compiled_fn, _ = create_aot_dispatcher_function(
946
+ flat_fn,
947
+ fake_flat_args,
948
+ aot_config,
949
+ fake_mode,
950
+ shape_env,
951
+ )
952
+ cached_res = (compiled_fn, out_spec)
953
+
954
+ cached_fn, out_spec = cached_res
955
+ out = cached_fn(flat_args)
956
+ return out_spec.unflatten(out)
957
+
958
+ return returned_function
959
+
960
+
961
+ def aot_module(mod: nn.Module, *args, **kwargs) -> nn.Module:
962
+ """
963
+ Traces the forward and backward graph of :attr:`mod` using torch dispatch
964
+ tracing mechanism. It is wrapper function, that underneath uses
965
+ :func:`aot_function` to perform tracing and compilation.
966
+
967
+ :func:`aot_module` lifts the parameters and buffers of ``nn.Module`` as inputs
968
+ to a new callable which is then compiled through :func:`aot_function`.
969
+
970
+ .. warning::
971
+ This API is experimental and likely to change.
972
+
973
+ Args:
974
+ mod (Callable): A ``nn.Module`` module.
975
+ args : args to be passed to :func:`aot_function`
976
+ kwargs : kwargs to be passed to :func:`aot_function`
977
+
978
+ Returns:
979
+ Returns a ``nn.Module`` that retains the eager behavior of the original
980
+ :attr:`mod`, but with forward and backward graph compiled.
981
+
982
+ """
983
+ # See Note: [Fake Modules and AOTAutograd]
984
+ torch._dynamo.utils.assert_no_fake_params_or_buffers(mod)
985
+
986
+ def functional_call(named_params, named_buffers, *args, **kwargs):
987
+ params_and_buffers = {**named_params, **named_buffers}
988
+ return torch.func.functional_call(mod, params_and_buffers, args, kwargs)
989
+
990
+ named_params = dict(mod.named_parameters(remove_duplicate=False))
991
+ named_buffers = dict(mod.named_buffers(remove_duplicate=False))
992
+ num_params_buffers = len(named_params) + len(named_buffers)
993
+ compiled_f = aot_function(
994
+ functional_call, *args, num_params_buffers=num_params_buffers, **kwargs
995
+ )
996
+
997
+ class AOTModule(nn.Module):
998
+ def __init__(self) -> None:
999
+ super().__init__()
1000
+ self.orig_module = mod
1001
+
1002
+ def forward(self, *args, **kwargs):
1003
+ return compiled_f(
1004
+ named_params,
1005
+ named_buffers,
1006
+ *args,
1007
+ **kwargs,
1008
+ )
1009
+
1010
+ return AOTModule()
1011
+
1012
+
1013
+ def _try_get_metadata_from_dynamo(
1014
+ mod: torch.nn.Module, param_keys: KeysView[str], full_args_num: int
1015
+ ) -> tuple[Optional[list[torch._guards.Source]], list[int]]:
1016
+ """
1017
+ Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModule.
1018
+ We first verify that `mod` does come from Dynamo, then we handle cases where
1019
+ metadata might be missing.
1020
+
1021
+ Returns:
1022
+ aot_autograd_arg_pos_to_source: used to dedup params and their guards
1023
+ static_input_indices: used to identify static inputs for cudagraphs
1024
+ """
1025
+ # Note [Assumption on Dynamo Metadata]
1026
+ # This function assumes a graph module from dynamo provides `dynamo_compiled_id`,
1027
+ # _param_name_to_source, and every placeholder node has `_dynamo_source` attributes.
1028
+ # When gm is modified (e.g., DDPOptimizer via split_module), metadata needs to
1029
+ # be propagated in order to be recognized as a dynamo graph
1030
+
1031
+ if not (isinstance(mod, torch.fx.GraphModule) and "dynamo_compile_id" in mod.meta):
1032
+ # graph was not captured by dynamo
1033
+ return None, []
1034
+
1035
+ if not hasattr(mod, "_param_name_to_source"):
1036
+ # is from export
1037
+ return None, []
1038
+
1039
+ # We now know this came from dynamo, and (1) we care about guards,
1040
+ # so setting up aot_autograd_arg_pos_to_source for downstream dedup guards
1041
+ # can now be done safely. (2) Dynamo logic protects the 1:1 sizing below.
1042
+ # Additionally, we mark static indices for cudagraphs.
1043
+ param_name_to_source = mod._param_name_to_source
1044
+ seen_sources = set()
1045
+
1046
+ aot_autograd_arg_pos_to_source = []
1047
+ static_input_indices = []
1048
+ # Collect the new inputs lifted by aotdispatch
1049
+ for i, name in enumerate(param_keys):
1050
+ assert name in param_name_to_source, f"{name} not found."
1051
+ source = param_name_to_source[name]
1052
+ assert source not in seen_sources, source
1053
+ seen_sources.add(source)
1054
+ aot_autograd_arg_pos_to_source.append(source)
1055
+
1056
+ static_input_indices.append(i)
1057
+
1058
+ # Collect the dynamo graph inputs
1059
+ # TODO(mlazos): Revisit if this is still needed. With Dynamo install ID
1060
+ # matched tensors back into the Fx graph, this might not be necessary.
1061
+ for pos, node in enumerate(mod.graph.find_nodes(op="placeholder")):
1062
+ assert hasattr(node, "_dynamo_source")
1063
+ source = node._dynamo_source
1064
+ # `source`` specifies the source from user code. ddp optimizer may have
1065
+ # intermediate values becoming submodule placeholders which does not
1066
+ # have a source
1067
+ assert source is None or source not in seen_sources, source
1068
+ seen_sources.add(source)
1069
+ aot_autograd_arg_pos_to_source.append(source)
1070
+ source_name = source.name() if source else str(source)
1071
+
1072
+ # input[i] in dynamo is now:
1073
+ # input[i + len(extra_params)] in AOT,
1074
+ # where extra_params are the params/buffers that dynamo baked into the
1075
+ # OutputGraph
1076
+ actual_pos = pos + len(param_keys)
1077
+
1078
+ if "tensor_dict" in node.meta and node.meta["tensor_dict"].get(
1079
+ "_dynamo_static_input_type", None
1080
+ ):
1081
+ static_inputs_log.debug(
1082
+ "Adding static input pos %s for source %s", actual_pos, source_name
1083
+ )
1084
+ static_input_indices.append(actual_pos)
1085
+ else:
1086
+ static_inputs_log.debug(
1087
+ "Non-static input pos %s for source %s", actual_pos, source_name
1088
+ )
1089
+
1090
+ assert full_args_num == len(aot_autograd_arg_pos_to_source)
1091
+ return aot_autograd_arg_pos_to_source, static_input_indices
1092
+
1093
+
1094
+ def aot_module_simplified(
1095
+ mod: nn.Module,
1096
+ args,
1097
+ fw_compiler: AOTDispatchCompiler,
1098
+ bw_compiler: Optional[AOTDispatchCompiler] = None,
1099
+ partition_fn: Callable = default_partition,
1100
+ decompositions: Optional[dict] = None,
1101
+ keep_inference_input_mutations=False,
1102
+ inference_compiler: Optional[AOTDispatchCompiler] = None,
1103
+ cudagraphs: Optional[BoxedBool] = None,
1104
+ boxed_forward_device_index: Optional[BoxedDeviceIndex] = None,
1105
+ ignore_shape_env: bool = False,
1106
+ ) -> nn.Module:
1107
+ """
1108
+ This is the simplified or low overhead version of aot_module. For frontends
1109
+ like TorchDynamo, the input functions/modules to AOT are static and have
1110
+ unpacked inputs/outputs. This gives us an opportunity to remove the
1111
+ (1) pytree overhead to parse inputs/outputs,
1112
+ (2) AOT Autograd cache,
1113
+ (3) Reading of params/buffers in every forward call
1114
+
1115
+ :func:`aot_module_simplified` removes these overheads.
1116
+ """
1117
+ params = {
1118
+ **dict(mod.named_parameters(remove_duplicate=False)),
1119
+ **dict(mod.named_buffers(remove_duplicate=False)),
1120
+ }
1121
+ params_flat, params_spec = pytree.tree_flatten(params)
1122
+ params_flat = list(params_flat)
1123
+ params_len = len(params_flat)
1124
+
1125
+ if cudagraphs is None:
1126
+ cudagraphs = BoxedBool(torch._inductor.config.triton.cudagraphs)
1127
+
1128
+ if bw_compiler is None:
1129
+ bw_compiler = fw_compiler
1130
+ if inference_compiler is None:
1131
+ inference_compiler = fw_compiler
1132
+
1133
+ full_args = []
1134
+ # First, the params
1135
+ full_args.extend(params_flat)
1136
+
1137
+ if tracing_context := torch._guards.TracingContext.try_get():
1138
+ tracing_context.params_flat = params_flat
1139
+ (
1140
+ tracing_context.params_flat_unwrap_subclasses,
1141
+ tracing_context.params_unwrapped_to_flat_index,
1142
+ ) = unwrap_tensor_subclasses_with_indices_to_original(params_flat)
1143
+
1144
+ # Next, the input args
1145
+ full_args.extend(args)
1146
+
1147
+ (
1148
+ aot_autograd_arg_pos_to_source,
1149
+ static_input_indices,
1150
+ ) = _try_get_metadata_from_dynamo(mod, params.keys(), len(full_args))
1151
+
1152
+ dynamic_shapes = False
1153
+ for x in full_args:
1154
+ if isinstance(x, FakeTensor):
1155
+ dynamic_shapes = x.fake_mode.shape_env is not None
1156
+ break
1157
+
1158
+ aot_config = AOTConfig(
1159
+ fw_compiler=fw_compiler,
1160
+ bw_compiler=bw_compiler,
1161
+ inference_compiler=inference_compiler,
1162
+ partition_fn=partition_fn,
1163
+ decompositions=decompositions,
1164
+ num_params_buffers=params_len,
1165
+ aot_id=next(AOT_COUNTER),
1166
+ keep_inference_input_mutations=keep_inference_input_mutations,
1167
+ dynamic_shapes=dynamic_shapes,
1168
+ aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source,
1169
+ static_input_indices=static_input_indices,
1170
+ is_export=False,
1171
+ no_tangents=False,
1172
+ cache_info=None,
1173
+ ignore_shape_env=ignore_shape_env,
1174
+ precompile_backend_id=getattr(mod, "_backend_id", None),
1175
+ )
1176
+ fake_mode, shape_env = construct_fake_mode(full_args, aot_config)
1177
+ fake_flat_args = process_inputs(
1178
+ full_args, aot_config, fake_mode, shape_env, ignore_shape_env
1179
+ )
1180
+
1181
+ def dispatch_and_compile():
1182
+ functional_call = create_functional_call(mod, params_spec, params_len)
1183
+ with compiled_autograd._disable():
1184
+ compiled_fn, _ = create_aot_dispatcher_function(
1185
+ functional_call,
1186
+ fake_flat_args,
1187
+ aot_config,
1188
+ fake_mode,
1189
+ shape_env,
1190
+ )
1191
+ return compiled_fn
1192
+
1193
+ # We only care if the forward will return an OutputCode.
1194
+ if isinstance(fw_compiler, SerializableAOTDispatchCompiler):
1195
+ local = should_use_local_autograd_cache()
1196
+ remote = should_use_remote_autograd_cache()
1197
+ if local or remote:
1198
+ set_feature_use("aot_autograd_remote_cache", remote)
1199
+ compiled_fn = AOTAutogradCache.load(
1200
+ dispatch_and_compile,
1201
+ mod,
1202
+ fake_flat_args,
1203
+ aot_config,
1204
+ cudagraphs,
1205
+ boxed_forward_device_index,
1206
+ local,
1207
+ remote,
1208
+ )
1209
+ else:
1210
+ compiled_fn = dispatch_and_compile()
1211
+ else:
1212
+ compiled_fn = dispatch_and_compile()
1213
+
1214
+ if isinstance(mod, torch._dynamo.utils.GmWrapper):
1215
+ # This function is called by the flatten_graph_inputs wrapper, which boxes
1216
+ # the inputs so that they can be freed before the end of this scope.
1217
+ # For overhead reasons, this is not the default wrapper, see comment:
1218
+ # https://github.com/pytorch/pytorch/pull/122535/files#r1560096481
1219
+ def boxed_forward(runtime_args: list[Any]):
1220
+ flat_args = []
1221
+ flat_args.extend(params_flat)
1222
+ flat_args.extend(runtime_args)
1223
+ runtime_args.clear()
1224
+ return compiled_fn(flat_args)
1225
+
1226
+ # Just for convenience
1227
+ boxed_forward.zero_grad = mod.zero_grad
1228
+ boxed_forward.named_parameters = mod.named_parameters
1229
+ boxed_forward.named_buffers = mod.named_buffers
1230
+ return boxed_forward
1231
+
1232
+ # TODO: There is something deeply wrong here; compiled_fn running with
1233
+ # the boxed calling convention, but aot_module_simplified somehow
1234
+ # historically returned a function that was not the boxed calling
1235
+ # convention. This should get fixed...
1236
+ # NB: GraphModule/nn.Module rely on the non-boxed calling convention here
1237
+ def forward(*runtime_args: tuple[Any]):
1238
+ full_args = []
1239
+ full_args.extend(params_flat)
1240
+ full_args.extend(runtime_args)
1241
+ return compiled_fn(full_args)
1242
+
1243
+ # Just for convenience
1244
+ forward.zero_grad = mod.zero_grad
1245
+ forward.named_parameters = mod.named_parameters
1246
+ forward.named_buffers = mod.named_buffers
1247
+
1248
+ return forward
1249
+
1250
+
1251
+ def aot_export_module(
1252
+ mod: nn.Module,
1253
+ args,
1254
+ *,
1255
+ decompositions: Optional[dict] = None,
1256
+ # If true, we'll return a joint forward-backward graph,
1257
+ # As well as metadata on the loss + gradients in the backward.
1258
+ trace_joint: bool,
1259
+ # If trace_joint is True, we expect your module to return a scalar loss.
1260
+ # Your module can return multiple outputs, so you must specify which output the loss is.
1261
+ output_loss_index: Optional[int] = None,
1262
+ pre_dispatch: bool = False,
1263
+ # If None, will be infered from inputs and mod.graph.nodes if mod is a graph module, but the inferred result might be wrong.
1264
+ dynamic_shapes: Optional[bool] = None,
1265
+ kwargs=None,
1266
+ ) -> tuple[torch.fx.GraphModule, GraphSignature]:
1267
+ """
1268
+ This function takes in a module, and returns:
1269
+ (1) an FX graph that can be exported
1270
+ (2) some metadata about the graph
1271
+
1272
+ If `trace_joint=True` we will return a joint graph of the forward + backward.
1273
+
1274
+ The traced FX graph will have the following properties compared to the original module:
1275
+ (1) Inputs and outputs to the module will be pytree-flattened
1276
+ (2) Parameters and buffers on the module will be lifted into graph inputs,
1277
+ graph_inputs = (*parameters, *buffers, *user_inputs)
1278
+ (3) The graph will be fully functionalized
1279
+ (4) Any input mutations will be converted into additional outputs in the graph,
1280
+ meaning whoever calls this graph is responsible for applying the mutations
1281
+ back to the original inputs.
1282
+ (5) If is_joint is provided the graph will return parameter gradients in addition to user outputs.
1283
+ The graph output will look like:
1284
+ graph_outputs = (*updated_inputs, *user_outputs, *param_gradients)
1285
+
1286
+ There are also several restrictions on what modules can use this API. In particular:
1287
+ (1) If trace_joint is specified, we expect the loss function to be **fused**
1288
+ into the module forward. One of the outputs to the forward must be a scalar loss,
1289
+ which is specified with `output_loss_index`.
1290
+ All other outputs to the forward are presumed to not require gradients.
1291
+ (2) This API cannot capture optimizers (although in theory we could build an API for this).
1292
+ (3) Metadata mutations on params/buffers/inputs are banned.
1293
+ (4) Data mutations on anything that requires gradients are banned (parameters)
1294
+ (5) If an input is mutated, it is not allowed to alias any other inputs.
1295
+ (6) Parameters must not be duplicated.
1296
+ """
1297
+ if pre_dispatch and trace_joint:
1298
+ raise RuntimeError("pre_dispatch is not supported when trace_joint is True.")
1299
+ named_parameters = dict(mod.named_parameters(remove_duplicate=False))
1300
+ named_buffers = dict(mod.named_buffers(remove_duplicate=False))
1301
+
1302
+ params_and_buffers = {
1303
+ **dict(named_parameters),
1304
+ **dict(named_buffers),
1305
+ }
1306
+ params_and_buffers_flat, params_spec = pytree.tree_flatten(params_and_buffers)
1307
+ params_and_buffers_flat = tuple(params_and_buffers_flat)
1308
+ params_len = len(params_and_buffers_flat)
1309
+
1310
+ kwargs = kwargs or {}
1311
+
1312
+ functional_call = create_functional_call(
1313
+ mod, params_spec, params_len, store_orig_mod=True
1314
+ )
1315
+
1316
+ num_fw_outs = None
1317
+
1318
+ if trace_joint:
1319
+ # This helper effectively just adds some extra asserts about what the backward will look like:
1320
+ # Outputs must include a scalar loss, that we compute gradients w.r.t.
1321
+ # We don't compute gradients w.r.t. anything else: so just in case we detach()
1322
+ # and other output tensors.
1323
+ def fn_to_trace(*args):
1324
+ nonlocal num_fw_outs
1325
+ out = functional_call(*args)
1326
+ if output_loss_index is None:
1327
+ raise RuntimeError(
1328
+ """\
1329
+ If trace_joint=Trueit is required that one of your forward outputs must be a scalar loss.
1330
+ You must specify the which (index) output is the loss with output_loss_index."""
1331
+ )
1332
+ if isinstance(out, (torch.Tensor)):
1333
+ out = (out,)
1334
+ if not isinstance(out, (tuple, list)):
1335
+ raise RuntimeError(
1336
+ f"Expected forward output to be either a tensor or a list/tuple of tensors. found {type(out)}"
1337
+ )
1338
+
1339
+ for i, o in enumerate(out):
1340
+ # We only want to create a backward graph w.r.t. the loss that the user passed in.
1341
+ # This implies that every other output should not require gradients.
1342
+ # Instead of making this an error (and forcing the user to detach all other outputs
1343
+ # of their forward),
1344
+ # we'll automatically detach them here.
1345
+ if o.requires_grad and i != output_loss_index:
1346
+ raise RuntimeError(
1347
+ f"""\
1348
+ Found an output of the forward that requires gradients, that was not the scalar loss.
1349
+ We require all outputs to the forward that are not the scalar loss to not require gradient,
1350
+ because we will only compute a backward graph against the scalar loss.
1351
+ You can fix this by calling .detach() on each of your forward outputs that is not the loss.
1352
+ You specified that output index {output_loss_index} is the loss, but we found that
1353
+ the output at index {i} requires gradients."""
1354
+ )
1355
+ out_loss = out[output_loss_index]
1356
+ num_fw_outs = len(out)
1357
+ if not out_loss.requires_grad:
1358
+ raise RuntimeError(
1359
+ f"""\
1360
+ The output at index {output_loss_index} was marked as the loss, but it does not require gradients"""
1361
+ )
1362
+ if out_loss.numel() != 1:
1363
+ raise RuntimeError(
1364
+ f"""\
1365
+ We require the output marked as the loss (at index {output_loss_index}) to be a scalar, but it has shape {out_loss.shape}"""
1366
+ )
1367
+ return out
1368
+
1369
+ ctx = nullcontext
1370
+ else:
1371
+ # Run under no_grad, so our tracing machinery only traces an inference graph.
1372
+ # However if pre_dispatch=True, we want to correctly trace set_grad_enabled calls for training.
1373
+ ctx = nullcontext if pre_dispatch else torch.no_grad
1374
+ fn_to_trace = functional_call
1375
+
1376
+ full_args = []
1377
+ # First, the params
1378
+ # NB: It is REQUIRED that parameters come first, Inductor infers "fixed"
1379
+ # parameters by looking at the difference in parameter count outside
1380
+ # and inside AOTAutograd, and assumes the prefix of arguments are fixed
1381
+ # arguments
1382
+ full_args.extend(params_and_buffers_flat)
1383
+ # Next, the input args
1384
+ full_args.extend(args)
1385
+
1386
+ with ctx():
1387
+ fx_g, metadata, in_spec, out_spec = _aot_export_function(
1388
+ fn_to_trace,
1389
+ full_args,
1390
+ decompositions=decompositions,
1391
+ num_params_buffers=params_len,
1392
+ no_tangents=True,
1393
+ pre_dispatch=pre_dispatch,
1394
+ dynamic_shapes=dynamic_shapes,
1395
+ kwargs=kwargs,
1396
+ )
1397
+ if trace_joint:
1398
+
1399
+ @wraps(functional_call)
1400
+ def flattened_joint(*args):
1401
+ # The idea here is that the joint graph that AOTAutograd creates has some strict properties:
1402
+ # (1) It accepts two arguments (primals, tangents), and pytree_flattens them
1403
+ # (2) It returns a tuple of (fw_outs, gradients)
1404
+ # This is a very useful convention for anyone who wants to partition the joint graph
1405
+ # into a separate forward and backward graph.
1406
+ # However,
1407
+ # (1) for people exporting a single joint graph, it would be preferable not to have
1408
+ # any pytrees in the graph.
1409
+ # (2) We are guaranteed in the aot_export_module case that the forward outputs a loss,
1410
+ # and there are therefore no tangents that are needed to run the joint graph.
1411
+ # (3) AOTAutograd creates a grad_input for every input in the forward,
1412
+ # including None's for inputs that are not grad-requiring tensors.
1413
+ # we don't want these in our export graph.
1414
+ # and there are therefore no tangents that are needed to run the joint graph.
1415
+ # This function "fixes" both of the above by removing any tangent inputs,
1416
+ # and removing pytrees from the original FX graph.
1417
+ fake_tangents = [
1418
+ None
1419
+ for _ in range(
1420
+ metadata.num_outputs + metadata.num_mutated_inp_runtime_indices
1421
+ )
1422
+ ]
1423
+ fw_outs, gradients = fx_g(args, fake_tangents)
1424
+ assert len(gradients) == len(args)
1425
+ output_gradients = []
1426
+ for a, grad in zip(args, gradients):
1427
+ if isinstance(a, torch.Tensor) and a.requires_grad:
1428
+ assert (
1429
+ grad is not None
1430
+ ), """\
1431
+ Found a parameter that did not receive a gradient.
1432
+ "This is most likely a bug, but if this needs to be supported please comment on this Github issue:
1433
+ https://github.com/pytorch/pytorch/issues/101192
1434
+ """
1435
+ output_gradients.append(grad)
1436
+ else:
1437
+ assert grad is None
1438
+ return *fw_outs, *output_gradients
1439
+
1440
+ fx_g = make_fx(flattened_joint, record_module_stack=True)(*full_args)
1441
+
1442
+ user_args_flat = pytree.arg_tree_leaves(*args, **kwargs)
1443
+ return fx_g, create_graph_signature(
1444
+ fx_g,
1445
+ metadata,
1446
+ in_spec,
1447
+ out_spec,
1448
+ user_args_flat=user_args_flat,
1449
+ params_and_buffers_flat=params_and_buffers_flat,
1450
+ param_names=list(named_parameters.keys()),
1451
+ buffer_names=list(named_buffers.keys()),
1452
+ trace_joint=trace_joint,
1453
+ num_user_fw_outs=num_fw_outs,
1454
+ loss_index=output_loss_index,
1455
+ )
1456
+
1457
+
1458
+ def aot_export_joint_simple(
1459
+ func: Callable,
1460
+ args,
1461
+ *,
1462
+ trace_joint: bool,
1463
+ # It looks like the main consequence of this API is that for dynamic shapes,
1464
+ # it will assume that parms/buffers are static.
1465
+ # With the new inferred dynamic shapes API, maybe this doesn't matter?
1466
+ num_params_buffers: int = 0,
1467
+ decompositions: Optional[dict] = None,
1468
+ ) -> torch.fx.GraphModule:
1469
+ """
1470
+ A simplified version of export. Used by higher order operators.
1471
+
1472
+ This function makes a high-level "no calling convention changes" guarantee:
1473
+ - If no inputs require grad (so we export an inference graph),
1474
+ there are *no* calling convention change between the exported graph, and "func".
1475
+ - If at least one input requires grad (so we trace out and export a joint fw-bw graph),
1476
+ Then if you were partition the graph into a separate forward and backward graph,
1477
+ The forward graph will have no calling convention changes compared to "func".
1478
+
1479
+ The above also relies on some strong restrictions around which functions this API accepts:
1480
+ (1) `args` cannot contain any pytrees (they must have been pytree_flattened already)
1481
+ (2) `func` cannot mutate any inputs
1482
+ (3) The outputs of `func` cannot alias any inputs.
1483
+
1484
+ Note: this function is only lightly tested today. It will probably be tested more heavily by higher order ops.
1485
+ """
1486
+ if trace_joint:
1487
+ ctx = nullcontext
1488
+ else:
1489
+ # Run under no_grad, so our tracing machinery only traces an inference graph.
1490
+ ctx = torch.no_grad
1491
+
1492
+ with ctx():
1493
+ fx_g, metadata, in_spec, out_spec = _aot_export_function(
1494
+ func,
1495
+ args,
1496
+ decompositions=decompositions,
1497
+ )
1498
+ in_spec, _kw_in_spec = in_spec.children_specs
1499
+ # At this point, we can just directly return the (joint or inference graph) that we traced.
1500
+ # First though: a bunch of assertions to make sure that our graph doesn't require
1501
+ # any calling convention changes compared to the original function.
1502
+ # These restrictions are *in addition to* the general restrictions on export.
1503
+
1504
+ # No input mutations
1505
+ if (
1506
+ len([x for x in metadata.input_info if x.mutates_data or x.mutates_metadata])
1507
+ != 0
1508
+ ):
1509
+ raise RuntimeError(
1510
+ f"aot_export_joint_simple does not support input mutations. {str(metadata)}"
1511
+ )
1512
+ # No output aliasing
1513
+ if (
1514
+ len([x for x in metadata.output_info if x.output_type != OutputType.non_alias])
1515
+ != 0
1516
+ ):
1517
+ raise RuntimeError(
1518
+ f"aot_export_joint_simple does not support outputs that alias inputs. {str(metadata)}"
1519
+ )
1520
+ # No pytrees
1521
+ if in_spec.is_leaf():
1522
+ raise RuntimeError(
1523
+ f"aot_export_joint_simple requires inputs to be a single list/tuple. in_spec={str(in_spec)}"
1524
+ )
1525
+ if not all(child.is_leaf() for child in in_spec.children_specs):
1526
+ raise RuntimeError(
1527
+ f"aot_export_joint_simple requires individual inputs not to be pytrees. in_spec={str(in_spec)}"
1528
+ )
1529
+ if out_spec.is_leaf():
1530
+ raise RuntimeError(
1531
+ f"aot_export_joint_simple requires outputs to be a single list/tuple. out_spec={str(out_spec)}"
1532
+ )
1533
+ if not all(child.is_leaf() for child in out_spec.children_specs):
1534
+ raise RuntimeError(
1535
+ f"aot_export_joint_simple requires individual outputs not to be pytrees. out_spec={str(out_spec)}"
1536
+ )
1537
+ # TODO: we might have to temporarily patch config.functionalize_rng
1538
+ # so that it doesn't run when we're exporting a higher order op.
1539
+
1540
+ if config.debug_assert:
1541
+ # Smoke test that after partitioning, we can run the forward without any calling convention changes.
1542
+ fw_module, _bw_module = aot_config.default_partition( # noqa: F821
1543
+ fx_g, args, num_fwd_outputs=len(fw_metadata.output_infos) # noqa: F821
1544
+ )
1545
+ # Attempt to run the fw_module with the original user inputs
1546
+ fake_mode = detect_fake_mode(args)
1547
+ if fake_mode is None:
1548
+ fake_mode = FakeTensorMode()
1549
+ with fake_mode:
1550
+ fw_module(*args)
1551
+ return fx_g
1552
+
1553
+
1554
+ # Private for now because we aren't providing a contract on what to return
1555
+ # for joint graphs (we could when there's a clearer use case)
1556
+ # In the future, we may need to add more export API's that provide their own strong guarantees.
1557
+ # This is meant as a general helper function for handling various export-y use cases.
1558
+ def _aot_export_function(
1559
+ func: Callable,
1560
+ args,
1561
+ *,
1562
+ num_params_buffers: int = 0,
1563
+ decompositions: Optional[dict] = None,
1564
+ # If we're exporting a joint graph and we don't want any tangent inputs in the graph
1565
+ # (because we are backpropping through a scalar 1 loss),
1566
+ # we need to explicitly specify not to include tangents in the graph.
1567
+ # It's not enough just to check that our tangent is a scalar, since we also
1568
+ # need to know if it is a 1 (no need to make it a graph input), or something else
1569
+ # (requiring it to be a graph input).
1570
+ # We don't know this info at trace time though, so we need to make it an explicit config.
1571
+ no_tangents: bool = False,
1572
+ pre_dispatch: bool = False,
1573
+ # If None, `dynamic_shapes` will be infered from inputs, but the inferred result might be wrong.
1574
+ dynamic_shapes: Optional[bool] = None,
1575
+ kwargs=None,
1576
+ ) -> tuple[torch.fx.GraphModule, ViewAndMutationMeta, pytree.TreeSpec, pytree.TreeSpec]:
1577
+ kwargs = kwargs or {}
1578
+
1579
+ flat_fn, out_spec = create_tree_flattened_fn(func, args, kwargs)
1580
+ flat_args, in_spec = pytree.tree_flatten((args, kwargs))
1581
+
1582
+ fake_mode = None
1583
+ if dynamic_shapes is None:
1584
+ # Try to infer `dynamic_shapes from inputs and graph nodes
1585
+ fake_mode = detect_fake_mode(flat_args)
1586
+ if (
1587
+ fake_mode is None
1588
+ and hasattr(func, "_orig_mod")
1589
+ and isinstance(func._orig_mod, torch.fx.GraphModule)
1590
+ ):
1591
+ vals = [
1592
+ node.meta["val"]
1593
+ for node in func._orig_mod.graph.nodes
1594
+ if "val" in node.meta
1595
+ ]
1596
+ fake_mode = detect_fake_mode(vals)
1597
+ dynamic_shapes = fake_mode is not None and fake_mode.shape_env is not None
1598
+
1599
+ # The export use case doesn't care about several bits of AOTConfig
1600
+ # (1) compilers (we just export the graph)
1601
+ # (2) partitioners (export is only full graph, user can partition themselves)
1602
+ aot_config = AOTConfig(
1603
+ fw_compiler=None,
1604
+ bw_compiler=None,
1605
+ inference_compiler=None,
1606
+ partition_fn=None,
1607
+ decompositions=decompositions,
1608
+ num_params_buffers=num_params_buffers,
1609
+ aot_id=next(AOT_COUNTER),
1610
+ # For now there's no use case involving keeping input mutations in the graph
1611
+ # (which we can only do in the inference case anyway).
1612
+ # We can add this later if we need to.
1613
+ keep_inference_input_mutations=False,
1614
+ dynamic_shapes=dynamic_shapes,
1615
+ aot_autograd_arg_pos_to_source=None,
1616
+ is_export=True,
1617
+ no_tangents=no_tangents,
1618
+ pre_dispatch=pre_dispatch,
1619
+ )
1620
+ if fake_mode is None:
1621
+ fake_mode, shape_env = construct_fake_mode(flat_args, aot_config)
1622
+ else:
1623
+ shape_env = fake_mode.shape_env
1624
+ fake_flat_args = process_inputs(flat_args, aot_config, fake_mode, shape_env)
1625
+
1626
+ fx_g, meta = create_aot_dispatcher_function(
1627
+ flat_fn,
1628
+ fake_flat_args,
1629
+ aot_config,
1630
+ fake_mode,
1631
+ shape_env,
1632
+ )
1633
+ return fx_g, meta, in_spec, out_spec.spec
1634
+
1635
+
1636
+ @contextmanager
1637
+ def _detect_attribute_assignment(mod: torch.nn.Module):
1638
+ # Do not allow assignment of tensor attributes during export unless
1639
+ # the attribute is registered as a buffer.
1640
+
1641
+ NN_MODULE_STD_ATTRS = [
1642
+ "_backward_hooks",
1643
+ "_backward_pre_hooks",
1644
+ "_buffers",
1645
+ "_forward_hooks",
1646
+ "_forward_hooks_always_called",
1647
+ "_forward_hooks_with_kwargs",
1648
+ "_forward_pre_hooks",
1649
+ "_forward_pre_hooks_with_kwargs",
1650
+ "_is_full_backward_hook",
1651
+ "_load_state_dict_post_hooks",
1652
+ "_load_state_dict_pre_hooks",
1653
+ "_modules",
1654
+ "_non_persistent_buffers_set",
1655
+ "_parameters",
1656
+ "_state_dict_hooks",
1657
+ "_state_dict_pre_hooks",
1658
+ "training",
1659
+ ]
1660
+ NN_MODULE_LAZY_STD_ATTRS = [
1661
+ "_initialize_hook",
1662
+ "_load_hook",
1663
+ ]
1664
+ STD_ATTRS = {
1665
+ *NN_MODULE_STD_ATTRS,
1666
+ *NN_MODULE_LAZY_STD_ATTRS,
1667
+ }
1668
+
1669
+ def _get_attributes(mod):
1670
+ # return any attributes of a module that are not standard attributes
1671
+ return {k: v for k, v in mod.__dict__.items() if k not in STD_ATTRS}
1672
+
1673
+ # save state of attributes before enter
1674
+ snapshot = pytree.tree_map(
1675
+ lambda x: x,
1676
+ _get_attributes(mod),
1677
+ is_leaf=lambda x: type(x) in _pytree_subclasses_that_lose_info,
1678
+ )
1679
+ try:
1680
+ yield
1681
+ finally:
1682
+ # after exit, compare state of attributes with snapshot
1683
+ # to detect which tensor attributes were assigned
1684
+ assigned_tensor_attributes = []
1685
+
1686
+ def _collect_assigned_tensor_attributes(kp, v, _v):
1687
+ if _v is not v:
1688
+ attr, *rest = kp
1689
+ if isinstance(v, torch.Tensor):
1690
+ assigned_tensor_attributes.append(
1691
+ f"self.{attr.key}{pytree.keystr(rest)}"
1692
+ )
1693
+ # TODO(avik): Assigning all other types are allowed right now.
1694
+ # Maybe in the future we want to limit this to primitive types?
1695
+ return v
1696
+
1697
+ new_attrs = _get_attributes(mod)
1698
+ if len(new_attrs) != len(snapshot):
1699
+ added_attrs = new_attrs.keys() - snapshot.keys()
1700
+ deleted_attrs = snapshot.keys() - new_attrs.keys()
1701
+
1702
+ if len(added_attrs) > 0:
1703
+ raise ValueError(
1704
+ f"During torch.export, following attrs were created in the model.forward: {added_attrs} "
1705
+ f"Such attributes must be registered as buffers using the `register_buffer` "
1706
+ f"API and must be initialized at model.__init__ "
1707
+ f"(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
1708
+ )
1709
+
1710
+ if len(deleted_attrs) > 0:
1711
+ raise ValueError(
1712
+ f"During torch.export, following attrs were deleted in the model.forward: {deleted_attrs} "
1713
+ f"Such attributes must be registered as buffers using the `register_buffer` "
1714
+ f"API and must be initialized at model.__init__ "
1715
+ f"(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
1716
+ )
1717
+
1718
+ pytree.tree_map_with_path(
1719
+ _collect_assigned_tensor_attributes, snapshot, new_attrs
1720
+ )
1721
+ # restore state of all attributes (including, e.g., of primitive types)
1722
+ mod.__dict__.update(snapshot)
1723
+
1724
+ if assigned_tensor_attributes:
1725
+ if len(assigned_tensor_attributes) > 1:
1726
+ noun, verb = "attributes", "were"
1727
+ else:
1728
+ noun, verb = "attribute", "was"
1729
+ raise ValueError(
1730
+ f"The tensor {noun} {', '.join(assigned_tensor_attributes)} {verb} assigned during export. "
1731
+ "Such attributes must be registered as buffers using the `register_buffer` API "
1732
+ "(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
1733
+ )
1734
+
1735
+
1736
+ compiled_function = aot_function
1737
+ compiled_module = aot_module
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/apis.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # NOTE: We allow Dynamo to see this file (via torch/_dynamo/trace_rules.py) so that it can
3
+ # trace through functorch transforms.
4
+ # Currently, we can't allow Dynamo to see `eager_transforms.py`/`vmap.py` as that break a lot of thing
5
+ # and there isn't a mechanism to selectively expose only some functions (eg. grad) from a file
6
+ # to Dynamo.
7
+ import functools
8
+
9
+ from torch._functorch.utils import argnums_t, exposed_in
10
+ from torch._functorch.vmap import (
11
+ _check_out_dims_is_int_or_int_pytree,
12
+ _check_randomness_arg,
13
+ _chunked_vmap,
14
+ _process_batched_inputs,
15
+ Callable,
16
+ in_dims_t,
17
+ out_dims_t,
18
+ vmap_impl,
19
+ )
20
+
21
+
22
+ # vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
23
+ # sends those into func, and then unwraps the output BatchedTensors. Operations
24
+ # on BatchedTensors perform the batched operations that the user is asking for.
25
+ #
26
+ # vmap's randomness behavior differs from JAX's, which would require a PRNG key
27
+ # to be passed everywhere.
28
+
29
+
30
+ @exposed_in("torch.func")
31
+ def vmap(
32
+ func: Callable,
33
+ in_dims: in_dims_t = 0,
34
+ out_dims: out_dims_t = 0,
35
+ randomness: str = "error",
36
+ *,
37
+ chunk_size=None,
38
+ ) -> Callable:
39
+ """
40
+ vmap is the vectorizing map; ``vmap(func)`` returns a new function that
41
+ maps ``func`` over some dimension of the inputs. Semantically, vmap
42
+ pushes the map into PyTorch operations called by ``func``, effectively
43
+ vectorizing those operations.
44
+
45
+ vmap is useful for handling batch dimensions: one can write a function
46
+ ``func`` that runs on examples and then lift it to a function that can
47
+ take batches of examples with ``vmap(func)``. vmap can also be used to
48
+ compute batched gradients when composed with autograd.
49
+
50
+ .. note::
51
+ :func:`torch.vmap` is aliased to :func:`torch.func.vmap` for
52
+ convenience. Use whichever one you'd like.
53
+
54
+ Args:
55
+ func (function): A Python function that takes one or more arguments.
56
+ Must return one or more Tensors.
57
+ in_dims (int or nested structure): Specifies which dimension of the
58
+ inputs should be mapped over. ``in_dims`` should have a
59
+ structure like the inputs. If the ``in_dim`` for a particular
60
+ input is None, then that indicates there is no map dimension.
61
+ Default: 0.
62
+ out_dims (int or Tuple[int]): Specifies where the mapped dimension
63
+ should appear in the outputs. If ``out_dims`` is a Tuple, then
64
+ it should have one element per output. Default: 0.
65
+ randomness (str): Specifies whether the randomness in this
66
+ vmap should be the same or different across batches. If 'different',
67
+ the randomness for each batch will be different. If 'same', the
68
+ randomness will be the same across batches. If 'error', any calls to
69
+ random functions will error. Default: 'error'. WARNING: this flag
70
+ only applies to random PyTorch operations and does not apply to
71
+ Python's random module or numpy randomness.
72
+ chunk_size (None or int): If None (default), apply a single vmap over inputs.
73
+ If not None, then compute the vmap :attr:`chunk_size` samples at a time.
74
+ Note that :attr:`chunk_size=1` is equivalent to computing the vmap with a for-loop.
75
+ If you run into memory issues computing the vmap, please try a non-None chunk_size.
76
+
77
+ Returns:
78
+ Returns a new "batched" function. It takes the same inputs as
79
+ ``func``, except each input has an extra dimension at the index
80
+ specified by ``in_dims``. It takes returns the same outputs as
81
+ ``func``, except each output has an extra dimension at the index
82
+ specified by ``out_dims``.
83
+
84
+ .. warning:
85
+ :func:`vmap` works best with functional-style code. Please do not
86
+ perform any side-effects in ``func``, with the exception of
87
+ in-place PyTorch operations. Examples of side-effects include mutating
88
+ Python data structures and assigning values to variables not captured
89
+ in ``func``.
90
+
91
+ One example of using :func:`vmap` is to compute batched dot products. PyTorch
92
+ doesn't provide a batched ``torch.dot`` API; instead of unsuccessfully
93
+ rummaging through docs, use :func:`vmap` to construct a new function.
94
+
95
+ >>> torch.dot # [D], [D] -> []
96
+ >>> batched_dot = torch.func.vmap(torch.dot) # [N, D], [N, D] -> [N]
97
+ >>> x, y = torch.randn(2, 5), torch.randn(2, 5)
98
+ >>> batched_dot(x, y)
99
+
100
+ :func:`vmap` can be helpful in hiding batch dimensions, leading to a simpler
101
+ model authoring experience.
102
+
103
+ >>> batch_size, feature_size = 3, 5
104
+ >>> weights = torch.randn(feature_size, requires_grad=True)
105
+ >>>
106
+ >>> def model(feature_vec):
107
+ >>> # Very simple linear model with activation
108
+ >>> return feature_vec.dot(weights).relu()
109
+ >>>
110
+ >>> examples = torch.randn(batch_size, feature_size)
111
+ >>> result = torch.vmap(model)(examples)
112
+
113
+ :func:`vmap` can also help vectorize computations that were previously difficult
114
+ or impossible to batch. One example is higher-order gradient computation.
115
+ The PyTorch autograd engine computes vjps (vector-Jacobian products).
116
+ Computing a full Jacobian matrix for some function f: R^N -> R^N usually
117
+ requires N calls to ``autograd.grad``, one per Jacobian row. Using :func:`vmap`,
118
+ we can vectorize the whole computation, computing the Jacobian in a single
119
+ call to ``autograd.grad``.
120
+
121
+ >>> # Setup
122
+ >>> N = 5
123
+ >>> f = lambda x: x ** 2
124
+ >>> x = torch.randn(N, requires_grad=True)
125
+ >>> y = f(x)
126
+ >>> I_N = torch.eye(N)
127
+ >>>
128
+ >>> # Sequential approach
129
+ >>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
130
+ >>> for v in I_N.unbind()]
131
+ >>> jacobian = torch.stack(jacobian_rows)
132
+ >>>
133
+ >>> # vectorized gradient computation
134
+ >>> def get_vjp(v):
135
+ >>> return torch.autograd.grad(y, x, v)
136
+ >>> jacobian = torch.vmap(get_vjp)(I_N)
137
+
138
+ :func:`vmap` can also be nested, producing an output with multiple batched dimensions
139
+
140
+ >>> torch.dot # [D], [D] -> []
141
+ >>> batched_dot = torch.vmap(torch.vmap(torch.dot)) # [N1, N0, D], [N1, N0, D] -> [N1, N0]
142
+ >>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5)
143
+ >>> batched_dot(x, y) # tensor of size [2, 3]
144
+
145
+ If the inputs are not batched along the first dimension, ``in_dims`` specifies
146
+ the dimension that each inputs are batched along as
147
+
148
+ >>> torch.dot # [N], [N] -> []
149
+ >>> batched_dot = torch.vmap(torch.dot, in_dims=1) # [N, D], [N, D] -> [D]
150
+ >>> x, y = torch.randn(2, 5), torch.randn(2, 5)
151
+ >>> batched_dot(x, y) # output is [5] instead of [2] if batched along the 0th dimension
152
+
153
+ If there are multiple inputs each of which is batched along different dimensions,
154
+ ``in_dims`` must be a tuple with the batch dimension for each input as
155
+
156
+ >>> torch.dot # [D], [D] -> []
157
+ >>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None)) # [N, D], [D] -> [N]
158
+ >>> x, y = torch.randn(2, 5), torch.randn(5)
159
+ >>> batched_dot(x, y) # second arg doesn't have a batch dim because in_dim[1] was None
160
+
161
+ If the input is a Python struct, ``in_dims`` must be a tuple containing a struct
162
+ matching the shape of the input:
163
+
164
+ >>> f = lambda dict: torch.dot(dict['x'], dict['y'])
165
+ >>> x, y = torch.randn(2, 5), torch.randn(5)
166
+ >>> input = {'x': x, 'y': y}
167
+ >>> batched_dot = torch.vmap(f, in_dims=({'x': 0, 'y': None},))
168
+ >>> batched_dot(input)
169
+
170
+ By default, the output is batched along the first dimension. However, it can be batched
171
+ along any dimension by using ``out_dims``
172
+
173
+ >>> f = lambda x: x ** 2
174
+ >>> x = torch.randn(2, 5)
175
+ >>> batched_pow = torch.vmap(f, out_dims=1)
176
+ >>> batched_pow(x) # [5, 2]
177
+
178
+ For any function that uses kwargs, the returned function will not batch the kwargs but will
179
+ accept kwargs
180
+
181
+ >>> x = torch.randn([2, 5])
182
+ >>> def fn(x, scale=4.):
183
+ >>> return x * scale
184
+ >>>
185
+ >>> batched_pow = torch.vmap(fn)
186
+ >>> assert torch.allclose(batched_pow(x), x * 4)
187
+ >>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5]
188
+
189
+ .. note::
190
+ vmap does not provide general autobatching or handle variable-length
191
+ sequences out of the box.
192
+ """
193
+ from torch.compiler import is_compiling
194
+
195
+ _check_randomness_arg(randomness)
196
+ if not (chunk_size is None or chunk_size > 0):
197
+ raise ValueError(
198
+ f"vmap: chunk_size should be None or greater than 0. (got {chunk_size})"
199
+ )
200
+
201
+ def wrapped(*args, **kwargs):
202
+ return vmap_impl(
203
+ func, in_dims, out_dims, randomness, chunk_size, *args, **kwargs
204
+ )
205
+
206
+ if not is_compiling():
207
+ wrapped = functools.wraps(func)(wrapped)
208
+
209
+ return wrapped
210
+
211
+
212
+ def chunk_vmap(
213
+ func: Callable,
214
+ in_dims: in_dims_t = 0,
215
+ out_dims: out_dims_t = 0,
216
+ randomness: str = "error",
217
+ chunks=2,
218
+ ) -> Callable:
219
+ """
220
+ chunk_vmap is the vectorizing map (vmap) using chunks of input data. It is a mix of vmap (which vectorizes
221
+ everything) and map (which executes things sequentially). ``chunk_vmap`` vectorizes the input with number of
222
+ chunks at a time. For more details about vectorizing map, see :func:`vmap`.
223
+
224
+ .. note::
225
+ Please use :func:`vmap` with ``chunk_size`` argument instead of this API.
226
+
227
+ Args:
228
+ func (function): A Python function that takes one or more arguments.
229
+ Must return one or more Tensors.
230
+ in_dims (int or nested structure): Specifies which dimension of the
231
+ inputs should be mapped over. ``in_dims`` should have a
232
+ structure like the inputs. If the ``in_dim`` for a particular
233
+ input is None, then that indicates there is no map dimension.
234
+ Default: 0.
235
+ out_dims (int or Tuple[int]): Specifies where the mapped dimension
236
+ should appear in the outputs. If ``out_dims`` is a Tuple, then
237
+ it should have one element per output. Default: 0.
238
+ randomness (str): Specifies whether the randomness in this
239
+ vmap should be the same or different across batches. If 'different',
240
+ the randomness for each batch will be different. If 'same', the
241
+ randomness will be the same across batches. If 'error', any calls to
242
+ random functions will error. Default: 'error'. WARNING: this flag
243
+ only applies to random PyTorch operations and does not apply to
244
+ Python's random module or numpy randomness.
245
+ chunks (int): Number of chunks to use to split the input data. Default is 2.
246
+ If equals to 1 then :func:`vmap` is called.
247
+
248
+ Returns:
249
+ Returns a new "batched" function. It takes the same inputs as
250
+ ``func``, except each input has an extra dimension at the index
251
+ specified by ``in_dims``. It takes returns the same outputs as
252
+ ``func``, except each output has an extra dimension at the index
253
+ specified by ``out_dims``.
254
+ """
255
+ _check_randomness_arg(randomness)
256
+
257
+ if chunks == 1:
258
+ return vmap(func, in_dims=in_dims, out_dims=out_dims, randomness=randomness)
259
+
260
+ def _get_chunk_flat_args(flat_args_, flat_in_dims_, chunks_):
261
+ flat_args_chunks = tuple(
262
+ t.chunk(chunks_, dim=in_dim)
263
+ if in_dim is not None
264
+ else [
265
+ t,
266
+ ]
267
+ * chunks_
268
+ for t, in_dim in zip(flat_args_, flat_in_dims_)
269
+ )
270
+ # transpose chunk dim and flatten structure
271
+ # chunks_flat_args is a list of flatten args
272
+ chunks_flat_args = zip(*flat_args_chunks)
273
+ return chunks_flat_args
274
+
275
+ @functools.wraps(func)
276
+ def wrapped_with_chunks(*args, **kwargs):
277
+ _check_out_dims_is_int_or_int_pytree(out_dims, func)
278
+ _, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
279
+ in_dims, args, func
280
+ )
281
+ # Chunk flat arguments
282
+ chunks_flat_args = _get_chunk_flat_args(flat_args, flat_in_dims, chunks)
283
+
284
+ # Apply vmap on chunks
285
+ return _chunked_vmap(
286
+ func,
287
+ flat_in_dims,
288
+ chunks_flat_args,
289
+ args_spec,
290
+ out_dims,
291
+ randomness,
292
+ **kwargs,
293
+ )
294
+
295
+ return wrapped_with_chunks
296
+
297
+
298
+ @exposed_in("torch.func")
299
+ def grad(func: Callable, argnums: argnums_t = 0, has_aux: bool = False) -> Callable:
300
+ """``grad`` operator helps computing gradients of ``func`` with respect to the
301
+ input(s) specified by ``argnums``. This operator can be nested to
302
+ compute higher-order gradients.
303
+
304
+ Args:
305
+ func (Callable): A Python function that takes one or more arguments.
306
+ Must return a single-element Tensor. If specified ``has_aux`` equals ``True``,
307
+ function can return a tuple of single-element Tensor and other auxiliary objects:
308
+ ``(output, aux)``.
309
+ argnums (int or Tuple[int]): Specifies arguments to compute gradients with respect to.
310
+ ``argnums`` can be single integer or tuple of integers. Default: 0.
311
+ has_aux (bool): Flag indicating that ``func`` returns a tensor and other
312
+ auxiliary objects: ``(output, aux)``. Default: False.
313
+
314
+ Returns:
315
+ Function to compute gradients with respect to its inputs. By default, the output of
316
+ the function is the gradient tensor(s) with respect to the first argument.
317
+ If specified ``has_aux`` equals ``True``, tuple of gradients and output auxiliary objects
318
+ is returned. If ``argnums`` is a tuple of integers, a tuple of output gradients with
319
+ respect to each ``argnums`` value is returned.
320
+
321
+ Example of using ``grad``:
322
+
323
+ >>> # xdoctest: +SKIP
324
+ >>> from torch.func import grad
325
+ >>> x = torch.randn([])
326
+ >>> cos_x = grad(lambda x: torch.sin(x))(x)
327
+ >>> assert torch.allclose(cos_x, x.cos())
328
+ >>>
329
+ >>> # Second-order gradients
330
+ >>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x)
331
+ >>> assert torch.allclose(neg_sin_x, -x.sin())
332
+
333
+ When composed with ``vmap``, ``grad`` can be used to compute per-sample-gradients:
334
+
335
+ >>> # xdoctest: +SKIP
336
+ >>> from torch.func import grad, vmap
337
+ >>> batch_size, feature_size = 3, 5
338
+ >>>
339
+ >>> def model(weights, feature_vec):
340
+ >>> # Very simple linear model with activation
341
+ >>> assert feature_vec.dim() == 1
342
+ >>> return feature_vec.dot(weights).relu()
343
+ >>>
344
+ >>> def compute_loss(weights, example, target):
345
+ >>> y = model(weights, example)
346
+ >>> return ((y - target) ** 2).mean() # MSELoss
347
+ >>>
348
+ >>> weights = torch.randn(feature_size, requires_grad=True)
349
+ >>> examples = torch.randn(batch_size, feature_size)
350
+ >>> targets = torch.randn(batch_size)
351
+ >>> inputs = (weights, examples, targets)
352
+ >>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))(*inputs)
353
+
354
+ Example of using ``grad`` with ``has_aux`` and ``argnums``:
355
+
356
+ >>> # xdoctest: +SKIP
357
+ >>> from torch.func import grad
358
+ >>> def my_loss_func(y, y_pred):
359
+ >>> loss_per_sample = (0.5 * y_pred - y) ** 2
360
+ >>> loss = loss_per_sample.mean()
361
+ >>> return loss, (y_pred, loss_per_sample)
362
+ >>>
363
+ >>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True)
364
+ >>> y_true = torch.rand(4)
365
+ >>> y_preds = torch.rand(4, requires_grad=True)
366
+ >>> out = fn(y_true, y_preds)
367
+ >>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample))
368
+
369
+ .. note::
370
+ Using PyTorch ``torch.no_grad`` together with ``grad``.
371
+
372
+ Case 1: Using ``torch.no_grad`` inside a function:
373
+
374
+ >>> # xdoctest: +SKIP
375
+ >>> def f(x):
376
+ >>> with torch.no_grad():
377
+ >>> c = x ** 2
378
+ >>> return x - c
379
+
380
+ In this case, ``grad(f)(x)`` will respect the inner ``torch.no_grad``.
381
+
382
+ Case 2: Using ``grad`` inside ``torch.no_grad`` context manager:
383
+
384
+ >>> # xdoctest: +SKIP
385
+ >>> with torch.no_grad():
386
+ >>> grad(f)(x)
387
+
388
+ In this case, ``grad`` will respect the inner ``torch.no_grad``, but not the
389
+ outer one. This is because ``grad`` is a "function transform": its result
390
+ should not depend on the result of a context manager outside of ``f``.
391
+
392
+ """
393
+ # To avoid cyclical dependency.
394
+ import torch._functorch.eager_transforms as eager_transforms
395
+ from torch.compiler import is_compiling
396
+
397
+ def wrapper(*args, **kwargs):
398
+ return eager_transforms.grad_impl(func, argnums, has_aux, args, kwargs)
399
+
400
+ if not is_compiling():
401
+ wrapper = functools.wraps(func)(wrapper)
402
+
403
+ return wrapper
404
+
405
+
406
+ @exposed_in("torch.func")
407
+ def grad_and_value(
408
+ func: Callable, argnums: argnums_t = 0, has_aux: bool = False
409
+ ) -> Callable:
410
+ """
411
+ Returns a function to compute a tuple of the gradient and primal, or
412
+ forward, computation.
413
+
414
+ Args:
415
+ func (Callable): A Python function that takes one or more arguments.
416
+ Must return a single-element Tensor. If specified ``has_aux``
417
+ equals ``True``, function can return a tuple of single-element
418
+ Tensor and other auxiliary objects: ``(output, aux)``.
419
+ argnums (int or Tuple[int]): Specifies arguments to compute gradients
420
+ with respect to. ``argnums`` can be single integer or tuple of
421
+ integers. Default: 0.
422
+ has_aux (bool): Flag indicating that ``func`` returns a tensor and
423
+ other auxiliary objects: ``(output, aux)``. Default: False.
424
+
425
+ Returns:
426
+ Function to compute a tuple of gradients with respect to its inputs
427
+ and the forward computation. By default, the output of the function is
428
+ a tuple of the gradient tensor(s) with respect to the first argument
429
+ and the primal computation. If specified ``has_aux`` equals
430
+ ``True``, tuple of gradients and tuple of the forward computation with
431
+ output auxiliary objects is returned. If ``argnums`` is a tuple of
432
+ integers, a tuple of a tuple of the output gradients with respect to
433
+ each ``argnums`` value and the forward computation is returned.
434
+
435
+ See :func:`grad` for examples
436
+ """
437
+ from torch._functorch import eager_transforms
438
+ from torch.compiler import is_compiling
439
+
440
+ def wrapper(*args, **kwargs):
441
+ return eager_transforms.grad_and_value_impl(
442
+ func, argnums, has_aux, args, kwargs
443
+ )
444
+
445
+ if not is_compiling():
446
+ wrapper = functools.wraps(func)(wrapper)
447
+
448
+ return wrapper
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/_functorch/autograd_function.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import NamedTuple
3
+
4
+ import torch
5
+ import torch.utils._pytree as pytree
6
+ from torch._C._functorch import (
7
+ _unwrap_for_grad,
8
+ _wrap_for_grad,
9
+ current_level,
10
+ TransformType,
11
+ )
12
+ from torch._functorch.apis import vmap
13
+ from torch._functorch.utils import enable_single_level_autograd_function
14
+ from torch._functorch.vmap import (
15
+ _add_batch_dim,
16
+ _broadcast_to_and_flatten,
17
+ restore_vmap,
18
+ unwrap_batched,
19
+ wrap_batched,
20
+ )
21
+ from torch._ops import HigherOrderOperator
22
+ from torch.autograd.forward_ad import _set_fwd_grad_enabled
23
+
24
+
25
+ # autograd.Function technically runs before the regular PyTorch dispatcher.
26
+ # This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot)
27
+ # work with it. One day we might decide to change this, but until then,
28
+ # we need to give the illusion that autograd.Function runs before those things.
29
+ #
30
+ # We do this by using creating a custom HigherOrderOperator that only functorch
31
+ # dispatches specially.
32
+ class CustomFunctionHigherOrderOperator(HigherOrderOperator):
33
+ def __init__(self) -> None:
34
+ super().__init__("custom_function_call")
35
+
36
+ def __call__(self, autograd_function, *args, **kwargs):
37
+ # When custom_function_call is done dispatching through functorch,
38
+ # it should just invoke the autograd.Function. This is consistent
39
+ # with the autograd.Function behavior of being invoked before the
40
+ # PyTorch dispatcher.
41
+ #
42
+ # This will lead us into trouble later down the line, but this is
43
+ # pre-existing. There is an invariant that a function traced by
44
+ # make_fx should have the same behavior when provided the same
45
+ # Tensor. However, make_fx sees autograd.Function as a composite
46
+ # (because autograd.Function happens before the Python dispatch key)
47
+ # and only traces the forward pass.
48
+ if torch._C._are_functorch_transforms_active():
49
+ return super().__call__(autograd_function, *args, **kwargs)
50
+ return autograd_function.apply(*args, **kwargs)
51
+
52
+
53
+ # "custom_function_call"
54
+ # This is the mechanism for an autograd.Function that works with functorch transforms.
55
+ # It wraps an autograd.Function; interactions with functorch transforms are defined
56
+ # via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch
57
+ # dispatcher.
58
+ custom_function_call = CustomFunctionHigherOrderOperator()
59
+
60
+
61
+ # The grad rule for custom_function_call is to construct a new _SingleLevelFunction
62
+ # (autograd.Function that only works with a single layer (level) of functorch) that:
63
+ # - unwraps the inputs
64
+ # - redispatches to custom_function_call
65
+ # - wraps the outputs
66
+ # and whose backward pass calls the original autograd.Function's backward.
67
+ #
68
+ # Why do we need to redispatch to custom_function_call?
69
+ # -----------------------------------------------------
70
+ # This is consistent with how ATen operators work with functorch's grad transform:
71
+ # they always redispatch to the original operator.
72
+ # Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x)
73
+ #
74
+ # grad1 will:
75
+ # - set up the autograd graph
76
+ # - unwrap the inputs
77
+ # - redispatch to at::sin (*)
78
+ # - rewrap the outputs on the return
79
+ #
80
+ # On the redispatch in (*), grad0 will:
81
+ # - set up the autograd graph
82
+ # - unwrap the inputs
83
+ # - redispatch to at::sin
84
+ # - rewrap the outputs on the return
85
+ #
86
+ # To "set up the autograd graph", we generate a _SingleLevelFunction
87
+ # and apply it.
88
+ @custom_function_call.py_impl(TransformType.Grad)
89
+ @custom_function_call.py_impl(TransformType.Jvp)
90
+ def custom_function_call_grad(interpreter, autograd_function, *operands):
91
+ Generated = generate_single_level_function(interpreter, autograd_function)
92
+ with enable_single_level_autograd_function():
93
+ flat_out = Generated.apply(*operands)
94
+ return flat_out
95
+
96
+
97
+ def generate_single_level_function(interpreter, autograd_function):
98
+ level = interpreter.level()
99
+
100
+ def forward(*operands):
101
+ unwrapped_operands = pytree.tree_map_only(
102
+ torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands
103
+ )
104
+ # Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter
105
+ # the transform. _SingleLevelFunction will turn off both fwd and bwd
106
+ # gradient computation and we need to turn it back on here.
107
+ with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower():
108
+ unwrapped_output = custom_function_call(
109
+ autograd_function, *unwrapped_operands
110
+ )
111
+
112
+ # See NOTE [mark_dirty object identity check]
113
+ def wrap_fn(output):
114
+ return _wrap_for_grad(output, level)
115
+
116
+ return wrap_outputs_maintaining_identity(
117
+ unwrapped_output, unwrapped_operands, operands, wrap_fn
118
+ )
119
+
120
+ def setup_context(ctx, inputs, output):
121
+ return autograd_function.setup_context(ctx, inputs, output)
122
+
123
+ # backward is only used if the transform is TransformType.Grad
124
+ def backward(ctx, *grads):
125
+ result = autograd_function.backward(ctx, *grads)
126
+ return result
127
+
128
+ # jvp is only used if the transform is TransformType.Jvp
129
+ def jvp(ctx, *tangents):
130
+ result = autograd_function.jvp(ctx, *tangents)
131
+ return result
132
+
133
+ # This is the sequence of magic words to dynamically generate a Subclass with
134
+ # a given name. A Tensor's .grad_fn field has a class name that is the original
135
+ # autograd.Function's name + Backward, so we do this to generate some
136
+ # meaningful name.
137
+ name = f"{autograd_function.__name__}Generated"
138
+ Generated = type(
139
+ name,
140
+ (torch.autograd.function._SingleLevelFunction,),
141
+ {
142
+ "forward": staticmethod(forward),
143
+ "backward": staticmethod(backward),
144
+ "jvp": staticmethod(jvp),
145
+ "setup_context": staticmethod(setup_context),
146
+ },
147
+ )
148
+ return Generated
149
+
150
+
151
+ # wrap_outputs_maintaining_identity handles outputs from the vmap,
152
+ # backward (vjp), and jvp staticmethod. The way it distinguishes
153
+ # between the vmap case and the {backward, jvp} case is if the out_dims
154
+ # are specified or not.
155
+ #
156
+ # NB: we cannot use out_dims=None as the deciding factor. This because
157
+ # out_dims=None can still happen in the vmap staticmethod! What the
158
+ # user is saying in that case is that their output does not have a
159
+ # dimension that is being vmapped over, which is valid.
160
+ NO_OUT_DIMS = "not specified"
161
+
162
+
163
+ # NOTE [mark_dirty object identity check]
164
+ # autograd.Function's ctx.mark_dirty expect a returned input
165
+ # to have the same object identity as the input.
166
+ # Mode-only functorch will greatly simplify this logic.
167
+ def wrap_outputs_maintaining_identity(
168
+ outputs, unwrapped_inputs, orig_inputs, wrap_fn, out_dims=NO_OUT_DIMS
169
+ ):
170
+ flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs)
171
+ flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs)
172
+
173
+ unwrapped_input_to_orig_input = {
174
+ id(unwrapped): orig
175
+ for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs)
176
+ }
177
+
178
+ flat_outputs, spec = pytree.tree_flatten(outputs)
179
+ result = []
180
+
181
+ out_dims_specified = out_dims != NO_OUT_DIMS
182
+
183
+ if out_dims_specified:
184
+ flat_out_dims = _broadcast_to_and_flatten(out_dims, spec)
185
+ # _broadcast_to_and_flatten returns None if it is unable to broadcast.
186
+ # TODO: update following link from master to stable once that's out
187
+ if flat_out_dims is None:
188
+ raise RuntimeError(
189
+ f"The autograd.Function's vmap staticmethod returned an "
190
+ f"incompatible (output, out_dims) tuple. "
191
+ f"Expected out_dims={out_dims} "
192
+ f"to be compatible with the structure of `output`. "
193
+ f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} "
194
+ f"but output has structure {spec}. "
195
+ f"For more details, please see "
196
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
197
+ )
198
+
199
+ for i, output in enumerate(flat_outputs):
200
+ if not isinstance(output, torch.Tensor):
201
+ result.append(output)
202
+ continue
203
+ if id(output) in unwrapped_input_to_orig_input:
204
+ result.append(unwrapped_input_to_orig_input[id(output)])
205
+ continue
206
+ if out_dims_specified:
207
+ result.append(wrap_fn(output, flat_out_dims[i])) # type: ignore[possibly-undefined, index]
208
+ else:
209
+ result.append(wrap_fn(output))
210
+
211
+ return pytree.tree_unflatten(result, spec)
212
+
213
+
214
+ # NOTE: [functorch vjp and autograd interaction]
215
+ # There's an edge case with the functorch vjp and autograd interaction
216
+ # that will eventually be fixed by mode-only functorch.
217
+ # The TL;DR is that there's no way to unwrap a dead GradTensorWrapper,
218
+ # so we (the framework) need to do it manually. Regular PyTorch operators
219
+ # automatically do so this is consistent.
220
+ #
221
+ # class MyExp(torch.autograd.Function):
222
+ # @staticmethod
223
+ # def forward(x):
224
+ # return x.exp()
225
+ #
226
+ # @staticmethod
227
+ # def setup_context(ctx, inputs, output):
228
+ # y = output
229
+ # ctx.save_for_backward(y)
230
+ #
231
+ # @staticmethod
232
+ # def backward(gy):
233
+ # y, = ctx.saved_tensors()
234
+ # return MyMul.apply(gy, y)
235
+ #
236
+ # x = torch.randn([], requires_grad=True)
237
+ # gy = torch.randn([], requires_grad=True)
238
+ # _, vjp_fn = vjp(MySin.apply, x)
239
+ # result = vjp_fn(gy)
240
+ #
241
+ # MyMul is an autograd.Function that is not shown here.
242
+ # It saves a `y` for backward (since gy requires grad).
243
+ #
244
+ # in vjp_fn(gy), we get:
245
+ # > MyMul.apply(gy, GradTensorWrapper(y, level=dead))
246
+ # Because the y that is saved for backward by MyExp is a GradTensorWrapper
247
+ # but is now dead since we are outside the vjp context.
248
+ #
249
+ # PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper,
250
+ # will automatically unwrap the GradTensorWrapper when applied.
251
+ # But since autograd.Function technically sits above the regular PyTorch
252
+ # dispatcher, it doesn't get this treatment. So we manually do
253
+ # the unwrapping to be consistent with regular PyTorch dispatcher operations.
254
+
255
+
256
+ class VmapInfo(NamedTuple):
257
+ batch_size: int
258
+ randomness: str
259
+
260
+
261
+ def has_overridden_vmap_rule(autograd_function):
262
+ return autograd_function.vmap is not torch.autograd.Function.vmap
263
+
264
+
265
+ def validate_vmap_returns_tuple_of_two_elements(result):
266
+ base_error_msg = (
267
+ "Expected the vmap staticmethod to have two returns, an output "
268
+ "and out_dims with pytree structure compatible with the output. "
269
+ )
270
+ if not isinstance(result, tuple):
271
+ raise RuntimeError(base_error_msg + f"Got a {type(result)} instead")
272
+ if not len(result) == 2:
273
+ raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead")
274
+
275
+
276
+ @custom_function_call.py_impl(TransformType.Vmap)
277
+ def custom_function_call_vmap(interpreter, autograd_function, *operands, **kwargs):
278
+ if any(
279
+ isinstance(val, torch.Tensor)
280
+ for val in torch.utils._pytree.tree_flatten(kwargs)[0]
281
+ ):
282
+ raise NotImplementedError(
283
+ f"Run vmap on autograd.Function with kwarg-only Tensor args. "
284
+ f"Please do not pass kwarg-only Tensors to autograd.Function. "
285
+ f"Got: {kwargs}"
286
+ )
287
+
288
+ if autograd_function.generate_vmap_rule:
289
+ if has_overridden_vmap_rule(autograd_function):
290
+ # TODO: Update link to stable once that's out
291
+ # https://github.com/pytorch/pytorch/issues/92029
292
+ raise RuntimeError(
293
+ f"You tried to vmap over {autograd_function.__name__}, but "
294
+ f"it has both generate_vmap_rule=True and an overridden vmap "
295
+ f"staticmethod. Please set generate_vmap_rule=False or delete "
296
+ f"the overridden vmap staticmethod to avoid ambiguity. "
297
+ f"For more details, please see "
298
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
299
+ )
300
+ return custom_function_call_vmap_generate_rule(
301
+ interpreter, autograd_function, *operands
302
+ )
303
+
304
+ if not has_overridden_vmap_rule(autograd_function):
305
+ # TODO: Update link to stable once that's out
306
+ # https://github.com/pytorch/pytorch/issues/92029
307
+ raise RuntimeError(
308
+ f"You tried to vmap over {autograd_function.__name__}, but "
309
+ f"it does not have vmap support. Please override and implement the "
310
+ f"vmap staticmethod or set generate_vmap_rule=True. "
311
+ f"For more details, please see "
312
+ f"https://pytorch.org/docs/main/notes/extending.func.html"
313
+ )
314
+
315
+ return custom_function_call_vmap_helper(
316
+ interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs
317
+ )
318
+
319
+
320
+ def custom_function_call_vmap_helper(
321
+ interpreter, vmap_function, op, *operands, **kwargs
322
+ ):
323
+ current_level = interpreter.level()
324
+ info = VmapInfo(
325
+ batch_size=interpreter.batch_size(),
326
+ randomness=interpreter.randomness(),
327
+ )
328
+ # We're either in the autograd.Function case (vmap staticmethod)
329
+ # or the torch.library.register_vmap case.
330
+ autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta)
331
+
332
+ def lower_to_next():
333
+ if autograd_function_case:
334
+ return interpreter.lower()
335
+ else:
336
+ return torch._C._ExcludeDispatchKeyGuard(
337
+ torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched)
338
+ )
339
+
340
+ unwrapped_operands, in_dims = unwrap_batched(operands, current_level)
341
+ # If none of the tensors are batched at the current level, then we skip the
342
+ # current level. This saves the user from needing to handle this case in
343
+ # their vmap staticmethod (and is consistent with our C++ batching rule API)
344
+ if pytree.tree_all(lambda dim: dim is None, in_dims):
345
+ with lower_to_next():
346
+ if autograd_function_case:
347
+ return custom_function_call(op, *operands)
348
+ else:
349
+ return op(*operands, **kwargs)
350
+
351
+ with lower_to_next():
352
+ result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs)
353
+ validate_vmap_returns_tuple_of_two_elements(result)
354
+ unwrapped_output, out_dims = result
355
+
356
+ # See NOTE [mark_dirty object identity check]
357
+ def wrap_fn(output, out_dim):
358
+ return (
359
+ output
360
+ if out_dim is None
361
+ else _add_batch_dim(output, out_dim, current_level)
362
+ )
363
+
364
+ return wrap_outputs_maintaining_identity(
365
+ unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims
366
+ )
367
+
368
+
369
+ def unpack_outputs(outputs):
370
+ out_dims = outputs[-1]
371
+ if isinstance(out_dims, tuple):
372
+ outputs = outputs[:-1]
373
+ else:
374
+ outputs = outputs[0]
375
+ return outputs, out_dims
376
+
377
+
378
+ def custom_function_call_vmap_generate_rule(interpreter, autograd_function, *operands):
379
+ unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level())
380
+ vmapped_function = vmapify_autograd_function(
381
+ autograd_function, in_dims, interpreter.batch_size(), interpreter.randomness()
382
+ )
383
+ with interpreter.lower():
384
+ outputs = custom_function_call(vmapped_function, *unwrapped_operands)
385
+
386
+ assert isinstance(outputs, tuple)
387
+ outputs, out_dims = unpack_outputs(outputs)
388
+ return wrap_batched(outputs, out_dims, interpreter.level())
389
+
390
+
391
+ @custom_function_call.py_impl(TransformType.Functionalize)
392
+ def custom_function_call_functionalize(
393
+ interpreter, autograd_function, generate_vmap_rule, *operands
394
+ ):
395
+ raise RuntimeError("NYI: Functionalize rule for custom_function_call")
396
+
397
+
398
+ def vmapify_autograd_function(autograd_function, in_dims, batch_size, randomness):
399
+ def forward(*operands):
400
+ outputs, out_dims = restore_vmap(
401
+ autograd_function.forward, in_dims, batch_size, randomness
402
+ )(*operands)
403
+ if isinstance(outputs, torch.Tensor):
404
+ return outputs, out_dims
405
+ else:
406
+ return *outputs, out_dims
407
+
408
+ def setup_context(ctx, inputs, outputs):
409
+ outputs, out_dims = unpack_outputs(outputs)
410
+ key = id(Generated)
411
+
412
+ def inner(inputs, outputs):
413
+ # wrapped_ctx.save_for_backward will:
414
+ # - unwrap batchedtensors into (tensor, bdim)
415
+ # - save_for_backward(*unwrapped_tensors)
416
+ # - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims
417
+ wrapped_ctx = CtxCustomSave(ctx, current_level())
418
+ autograd_function.setup_context(wrapped_ctx, inputs, outputs)
419
+
420
+ # input_shapes are used for reductify later to reduce expanded gradients
421
+ # to the correct shape.
422
+ # See NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
423
+ # for more details
424
+ input_shapes = tuple(
425
+ inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs
426
+ )
427
+ if not hasattr(ctx, "_pt_input_shapes"):
428
+ ctx._pt_input_shapes = {}
429
+ ctx._pt_input_shapes.update({key: input_shapes})
430
+
431
+ if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"):
432
+ ctx._pt_saved_tensors_bdims_stack = {}
433
+ ctx._pt_saved_tensors_bdims_stack.update(
434
+ {key: (wrapped_ctx._pt_saved_tensors_bdims)}
435
+ )
436
+
437
+ # See NOTE: [Why do we need to run setup_context under a vmap?]
438
+ restore_vmap(
439
+ inner,
440
+ (in_dims, out_dims),
441
+ batch_size,
442
+ randomness,
443
+ )(inputs, outputs)
444
+
445
+ if not hasattr(ctx, "_pt_out_dims"):
446
+ ctx._pt_out_dims = {}
447
+ ctx._pt_out_dims.update({key: out_dims})
448
+
449
+ def jvp(ctx, *tangents):
450
+ key = id(Generated)
451
+
452
+ def jvp_no_context(saved_tensors, tangents):
453
+ wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
454
+ return autograd_function.jvp(wrapped_ctx, *tangents)
455
+
456
+ tangent_in_dims = get_tangents_in_dims(in_dims, tangents)
457
+ out_tangents, out_tangents_dims = restore_vmap(
458
+ jvp_no_context,
459
+ (ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims),
460
+ batch_size,
461
+ randomness,
462
+ )(ctx.saved_tensors, tangents)
463
+
464
+ result = reductify(
465
+ out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size
466
+ )
467
+ if isinstance(result, torch.Tensor):
468
+ return result, None
469
+ else:
470
+ return *result, None
471
+
472
+ def backward(ctx, *grad_outputs):
473
+ key = id(Generated)
474
+ grad_outputs_ = grad_outputs[:-1]
475
+ grad_outputs_in_dims = ctx._pt_out_dims[key]
476
+
477
+ if not isinstance(grad_outputs_in_dims, tuple):
478
+ grad_outputs_in_dims = (grad_outputs_in_dims,)
479
+
480
+ grad_outputs_in_dims = tuple(
481
+ in_dim if grad_output is not None else None
482
+ for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims)
483
+ )
484
+
485
+ def backward_no_context(inputs):
486
+ saved_tensors, grad_outputs = inputs
487
+ wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors)
488
+ return autograd_function.backward(wrapped_ctx, *grad_outputs)
489
+
490
+ grad_ins, grad_ins_dims = restore_vmap(
491
+ backward_no_context,
492
+ ((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),),
493
+ batch_size,
494
+ randomness,
495
+ )((ctx.saved_tensors, grad_outputs_))
496
+ result = reductify(
497
+ grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key]
498
+ )
499
+ return result
500
+
501
+ name = f"Vmapped{autograd_function.__name__}"
502
+ Generated = type(
503
+ name,
504
+ (torch.autograd.Function,),
505
+ {
506
+ "forward": staticmethod(forward),
507
+ "backward": staticmethod(backward),
508
+ "jvp": staticmethod(jvp),
509
+ "setup_context": staticmethod(setup_context),
510
+ "generate_vmap_rule": True,
511
+ },
512
+ )
513
+
514
+ return Generated
515
+
516
+
517
+ # tangents might be None, so we need to replace
518
+ # the corresponding in_dims with None.
519
+ def get_tangents_in_dims(input_dims, tangents):
520
+ flat_in_dims, spec = pytree.tree_flatten(input_dims)
521
+ flat_tangents = pytree.arg_tree_leaves(*tangents)
522
+ result = [
523
+ None if tangent is None else in_dim
524
+ for in_dim, tangent in zip(flat_in_dims, flat_tangents)
525
+ ]
526
+ return pytree.tree_unflatten(result, spec)
527
+
528
+
529
+ # NOTE: [Why do we need to run setup_context under a vmap?]
530
+ # Consider the following autograd.Function
531
+ #
532
+ # class Sum(torch.autograd.Function):
533
+ # @staticmethod
534
+ # def forward(x):
535
+ # return x.sum()
536
+ # @staticmethod
537
+ # def setup_context(ctx, inputs, outputs):
538
+ # ctx.x_shape = inputs[0]
539
+ # @staticmethod
540
+ # def backward(ctx, gy):
541
+ # return gy.expand(ctx.x_shape)
542
+ #
543
+ # x = torch.randn(B, 4)
544
+ # in_dims = 0
545
+ # vmap(Sum.apply, in_dims)(x)
546
+ #
547
+ # Let's assume for a moment that we didn't vmap setup_context in VmappedSum:
548
+ #
549
+ # class VmappedSum(torch.autograd.Function):
550
+ # @staticmethod
551
+ # def forward(x):
552
+ # return vmap(Sum.forward, in_dims)(x)
553
+ #
554
+ # @staticmethod
555
+ # def setup_context(ctx, inputs, outputs):
556
+ # Sum.setup_context(ctx, inputs, outputs)
557
+ #
558
+ # @staticmethod
559
+ # def backward(ctx, gy):
560
+ # def backward_no_context(gy):
561
+ # return gy.expand(ctx.x_shape)
562
+ #
563
+ # dims = (0,)
564
+ # gx = vmap(backward_no_context, dims)(gy)
565
+ # return gx
566
+ #
567
+ # We end up saving [B, 4] as x_shape. In the backward, gy has shape [B],
568
+ # and we're doing:
569
+ #
570
+ # def backward_no_context(gy):
571
+ # return gy.expand([B, 4])
572
+ #
573
+ # gx = vmap(backward_no_context, dims)(gy: "Tensor[B]")
574
+ #
575
+ # This gives us the wrong result (gx has shape [B, B, 4], but it should
576
+ # have shape [4]). Performing vmap over setup_context means the shape
577
+ # saved has shape [4] and leads to a correct result shape for gx.
578
+
579
+
580
+ # Wraps a ctx object. Forwards all attr accesses to the underlying object
581
+ # except for the attrs in _pt_attrs
582
+ class WrappedCtx:
583
+ _pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx")
584
+
585
+ def __init__(self, ctx):
586
+ if not isinstance(ctx, WrappedCtx):
587
+ reserved_attrs = type(self)._pt_reserved_attrs
588
+ for name in reserved_attrs:
589
+ if not hasattr(ctx, name):
590
+ continue
591
+ raise RuntimeError(
592
+ f"PyTorch reserves the {reserved_attrs} field on ctx. "
593
+ "Please name your fields on ctx something else to avoid name "
594
+ "collision."
595
+ )
596
+ self._pt_inner_ctx = ctx
597
+
598
+ def __getattr__(self, name):
599
+ return getattr(self._pt_inner_ctx, name)
600
+
601
+ def __setattr__(self, name, value):
602
+ if name in type(self)._pt_reserved_attrs:
603
+ self.__dict__[name] = value
604
+ return
605
+ return setattr(self._pt_inner_ctx, name, value)
606
+
607
+
608
+ # Wraps ctx to create a new ctx object that overrides saved_tensors.
609
+ class CtxWithSavedTensors(WrappedCtx):
610
+ _pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs)
611
+
612
+ def __init__(self, ctx, new_saved_tensors):
613
+ super().__init__(ctx)
614
+ self._pt_new_saved_tensors = new_saved_tensors
615
+
616
+ @property
617
+ def saved_tensors(self):
618
+ return self._pt_new_saved_tensors
619
+
620
+
621
+ class CtxCustomSave(WrappedCtx):
622
+ _pt_reserved_attrs = (
623
+ "_pt_saved_tensors_bdims",
624
+ "_pt_current_level",
625
+ *WrappedCtx._pt_reserved_attrs,
626
+ )
627
+
628
+ def __init__(self, ctx, current_level):
629
+ super().__init__(ctx)
630
+ self._pt_saved_tensors_bdims = ()
631
+ self._pt_current_level = current_level
632
+
633
+ def save_for_backward(self, *tensors):
634
+ unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
635
+ self._pt_inner_ctx.save_for_backward(*unwrapped_tensors)
636
+ self._pt_saved_tensors_bdims = bdims
637
+
638
+ def save_for_forward(self, *tensors):
639
+ unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level)
640
+ self._pt_inner_ctx.save_for_forward(*unwrapped_tensors)
641
+ self._pt_saved_tensors_bdims = bdims
642
+
643
+
644
+ def reductify(
645
+ grad_input,
646
+ grad_input_bdim,
647
+ input_bdim,
648
+ batch_size,
649
+ target_shape_without_bdim_to_reduce_to=None,
650
+ ):
651
+ if not isinstance(grad_input, tuple):
652
+ grad_input = (grad_input,)
653
+ if not isinstance(grad_input_bdim, tuple):
654
+ grad_input_bdim = (grad_input_bdim,)
655
+ if not isinstance(input_bdim, tuple):
656
+ input_bdim = (input_bdim,)
657
+
658
+ if target_shape_without_bdim_to_reduce_to is None:
659
+ target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,)
660
+ result = tuple(
661
+ reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape)
662
+ for gi, gi_bdim, i_bdim, maybe_ishape in zip(
663
+ grad_input,
664
+ grad_input_bdim,
665
+ input_bdim,
666
+ target_shape_without_bdim_to_reduce_to,
667
+ )
668
+ )
669
+ return result
670
+
671
+
672
+ def reductify_leaf(
673
+ grad_input,
674
+ grad_input_bdim,
675
+ input_bdim,
676
+ batch_size,
677
+ target_shape_without_bdim_to_reduce_to=None,
678
+ ):
679
+ if grad_input is None:
680
+ return None
681
+
682
+ if grad_input_bdim is None and input_bdim is None:
683
+ return grad_input
684
+
685
+ if grad_input_bdim is not None and input_bdim is None:
686
+ return grad_input.sum(grad_input_bdim)
687
+
688
+ # NOTE: [Why can't we rely on autograd to reduce expanded gradients?]
689
+ # For reverse-mode AD,
690
+ # given a grad_input and input, it is valid for the user to return a
691
+ # grad_input that has a broadcasted shape when compared to the input.
692
+ # In this situation, autograd automatically reduces the grad_input to
693
+ # the shape of the input.
694
+ #
695
+ # However, when input_bdim is not None, we have problems.
696
+ #
697
+ # [example 1]
698
+ # grad_input: Tensor[3, 4], input: Tensor[B, 4]
699
+ # We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable
700
+ # from [B, 4].
701
+ #
702
+ # [example 2]
703
+ # grad_input: Tensor[3, B, 4], input: Tensor[B, 4]
704
+ # We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable
705
+ # from [B, 4].
706
+ #
707
+ # This means that we need to also reduce the grad_input to the shape of the
708
+ # input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag;
709
+ # if not-None then we do the reducing manually, otherwise, we do not do a reduction.
710
+ assert input_bdim is not None
711
+
712
+ if grad_input_bdim is None:
713
+ grad_input = grad_input.unsqueeze(input_bdim)
714
+ new_shape = list(grad_input.shape)
715
+ new_shape[input_bdim] = batch_size
716
+ grad_input = grad_input.expand(new_shape)
717
+ grad_input_bdim = input_bdim
718
+
719
+ if target_shape_without_bdim_to_reduce_to is not None:
720
+ return vmap(
721
+ torch.Tensor.sum_to_size,
722
+ in_dims=(grad_input_bdim, None),
723
+ out_dims=input_bdim,
724
+ )(grad_input, target_shape_without_bdim_to_reduce_to)
725
+
726
+ if input_bdim != grad_input_bdim:
727
+ grad_input = grad_input.movedim(grad_input_bdim, input_bdim)
728
+ return grad_input
729
+
730
+
731
+ def autograd_function_forward_rewritten(original_forward, original_setup_context):
732
+ def new_forward(ctx, *args, **kwargs):
733
+ output = original_forward(*args, **kwargs)
734
+ original_setup_context(ctx, args, output)
735
+ return output
736
+
737
+ return new_forward
738
+
739
+
740
+ class AutogradFunctionApply(HigherOrderOperator):
741
+ def __init__(self) -> None:
742
+ super().__init__("autograd_function_apply")
743
+
744
+ def __call__(self, fwd, bwd, *fwd_args, **fwd_kwargs):
745
+ saved_values = None
746
+ args_tensor_mask = fwd_kwargs["args_tensor_mask"]
747
+ non_differentiable_idx = fwd_kwargs["non_differentiable_idx"]
748
+ length_of_tensor_args = sum(args_tensor_mask)
749
+ # Filter out the original tensor args from fwd_args,
750
+ # lifted freevars should not be args of ApplyTemplate.apply
751
+ # since we don't need to calculate the gradients of them.
752
+ new_fwd_args = fwd_args[:length_of_tensor_args]
753
+
754
+ class ApplyTemplate(torch.autograd.Function):
755
+ @staticmethod
756
+ def forward(ctx, *args):
757
+ nonlocal saved_values
758
+ output, saved_values = fwd(None, *fwd_args)
759
+
760
+ # If users call ctx.mark_non_differentiable() in the original fwd function.
761
+ if len(non_differentiable_idx) > 0:
762
+ non_differentiable_output = []
763
+ for i, x in enumerate(output):
764
+ if i in non_differentiable_idx:
765
+ non_differentiable_output.append(x)
766
+ ctx.mark_non_differentiable(*non_differentiable_output)
767
+
768
+ return output
769
+
770
+ @staticmethod
771
+ def backward(ctx, *grad):
772
+ return bwd(None, *grad, *saved_values)
773
+
774
+ return ApplyTemplate.apply(*new_fwd_args)
775
+
776
+
777
+ autograd_function_apply = AutogradFunctionApply()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/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