jonghanko commited on
Commit
aee18e5
·
verified ·
1 Parent(s): b0b6adc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi +11 -0
  2. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/__init__.cpython-310.pyc +0 -0
  3. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/apis.cpython-310.pyc +0 -0
  4. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-310.pyc +0 -0
  5. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-310.pyc +0 -0
  6. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/config.cpython-310.pyc +0 -0
  7. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/deprecated.cpython-310.pyc +0 -0
  8. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-310.pyc +0 -0
  9. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/functional_call.cpython-310.pyc +0 -0
  10. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/make_functional.cpython-310.pyc +0 -0
  11. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/predispatch.cpython-310.pyc +0 -0
  12. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-310.pyc +0 -0
  13. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/utils.cpython-310.pyc +0 -0
  14. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/vmap.cpython-310.pyc +0 -0
  15. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py +145 -0
  16. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py +121 -0
  17. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py +273 -0
  18. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__init__.py +5 -0
  19. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-310.pyc +0 -0
  20. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-310.pyc +0 -0
  21. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-310.pyc +0 -0
  22. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-310.pyc +0 -0
  23. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-310.pyc +0 -0
  24. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-310.pyc +0 -0
  25. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-310.pyc +0 -0
  26. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-310.pyc +0 -0
  27. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-310.pyc +0 -0
  28. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-310.pyc +0 -0
  29. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-310.pyc +0 -0
  30. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py +1534 -0
  31. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py +869 -0
  32. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/descriptors.py +749 -0
  33. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py +284 -0
  34. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/functional_utils.py +543 -0
  35. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/fx_utils.py +315 -0
  36. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_capture.py +466 -0
  37. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py +1372 -0
  38. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_compile.py +1928 -0
  39. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py +466 -0
  40. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/logging_utils.py +146 -0
  41. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py +0 -0
  42. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/schemas.py +1299 -0
  43. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py +103 -0
  44. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py +518 -0
  45. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/utils.py +582 -0
  46. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/python_key.py +15 -0
  47. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/pytree_hacks.py +23 -0
  48. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/top_operators_github_usage.py +630 -0
  49. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/vmap.py +487 -0
  50. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py +76 -0
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from torch._C import LiteScriptModule, ScriptModule
3
+
4
+ def _load_mobile_module_from_file(filename: str): ...
5
+ def _load_mobile_module_from_bytes(bytes_: bytes): ...
6
+ def _load_jit_module_from_file(filename: str): ...
7
+ def _load_jit_module_from_bytes(bytes_: bytes): ...
8
+ def _save_mobile_module(m: LiteScriptModule, filename: str): ...
9
+ def _save_jit_module(m: ScriptModule, filename: str): ...
10
+ def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ...
11
+ def _save_jit_module_to_bytes(m: ScriptModule) -> bytes: ...
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (230 Bytes). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/apis.cpython-310.pyc ADDED
Binary file (18.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/config.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/deprecated.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-310.pyc ADDED
Binary file (55.6 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/functional_call.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/make_functional.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/predispatch.cpython-310.pyc ADDED
Binary file (3.39 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-310.pyc ADDED
Binary file (9.62 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/__pycache__/vmap.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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"]
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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.
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (244 Bytes). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-310.pyc ADDED
Binary file (30.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-310.pyc ADDED
Binary file (29.2 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-310.pyc ADDED
Binary file (4.57 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-310.pyc ADDED
Binary file (52.3 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-310.pyc ADDED
Binary file (30.1 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-310.pyc ADDED
Binary file (12 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py ADDED
@@ -0,0 +1,1534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Utils for caching the outputs of AOTAutograd
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import contextlib
10
+ import functools
11
+ import json
12
+ import logging
13
+ import os
14
+ import pickle
15
+ import shutil
16
+ import time
17
+ import traceback
18
+ from abc import ABC, abstractmethod
19
+ from copy import copy
20
+ from dataclasses import dataclass
21
+ from typing import Any, Callable, Generic, Optional, TYPE_CHECKING, TypeVar, Union
22
+ from typing_extensions import override
23
+
24
+ import torch
25
+ from torch._dynamo.precompile_context import PrecompileCacheArtifact, PrecompileContext
26
+ from torch._dynamo.trace_rules import torch_non_c_binding_in_graph_functions
27
+ from torch._dynamo.utils import (
28
+ chromium_event_log_active,
29
+ CompileEventLogger,
30
+ counters,
31
+ dynamo_timed,
32
+ )
33
+ from torch._functorch import config
34
+ from torch._inductor.codecache import (
35
+ _ident,
36
+ add_ephemeral_timeout_increase_for_distributed,
37
+ BypassFxGraphCache,
38
+ create_cache,
39
+ extract_tensor_metadata_for_cache_key,
40
+ FxGraphCache,
41
+ FxGraphCachePickler,
42
+ FxGraphHashDetails,
43
+ GuardedCache,
44
+ sha256_hash,
45
+ write_atomic,
46
+ )
47
+ from torch._inductor.cudagraph_utils import BoxedDeviceIndex
48
+ from torch._inductor.output_code import (
49
+ CompiledFxGraph,
50
+ CompiledFxGraphConstants,
51
+ OutputCode,
52
+ )
53
+ from torch._inductor.runtime.runtime_utils import cache_dir
54
+ from torch._inductor.utils import should_use_remote_fx_graph_cache
55
+ from torch._logging import LazyString
56
+ from torch._utils_internal import log_cache_bypass
57
+ from torch.compiler._cache import (
58
+ CacheArtifact,
59
+ CacheArtifactFactory,
60
+ CacheArtifactManager,
61
+ )
62
+ from torch.fx.experimental.symbolic_shapes import hint_int
63
+ from torch.utils._triton import has_triton_package
64
+ from torchgen.utils import dataclass_repr
65
+
66
+ from .runtime_wrappers import (
67
+ AOTDispatchAutograd,
68
+ AOTDispatchSubclassWrapper,
69
+ CachedAutogradLazyBackwardCompileInfo,
70
+ CompilerWrapper,
71
+ FunctionalizedRngRuntimeWrapper,
72
+ post_compile,
73
+ RuntimeWrapper,
74
+ SubclassMeta,
75
+ )
76
+ from .schemas import AOTAutogradCacheInfo, AOTConfig, ViewAndMutationMeta # noqa: F401
77
+
78
+
79
+ if TYPE_CHECKING:
80
+ from torch._inductor.compile_fx import _CompileFxKwargs
81
+ from torch._inductor.remote_cache import JsonDataTy, RemoteCache
82
+ from torch._inductor.utils import BoxedBool
83
+ from torch.fx.node import Node
84
+
85
+ log = logging.getLogger(__name__)
86
+
87
+
88
+ class BypassAOTAutogradCache(Exception):
89
+ pass
90
+
91
+
92
+ # Used to signify when FXGraphCache missed when AOTAutogradCache uses it
93
+ class FXGraphCacheMiss(BypassAOTAutogradCache):
94
+ pass
95
+
96
+
97
+ def should_use_remote_autograd_cache():
98
+ if torch.compiler.config.force_disable_caches:
99
+ return False
100
+ if config.enable_remote_autograd_cache is not None:
101
+ return config.enable_remote_autograd_cache
102
+ if not config.is_fbcode():
103
+ return False
104
+
105
+ if torch._utils_internal.is_fb_unit_test():
106
+ return False
107
+
108
+ try:
109
+ from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
110
+ except ModuleNotFoundError:
111
+ return False
112
+
113
+ jk_name = "pytorch/remote_cache:aot_autograd_cache_version"
114
+
115
+ return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(jk_name)
116
+
117
+
118
+ def should_use_local_autograd_cache():
119
+ if torch.compiler.config.force_disable_caches:
120
+ return False
121
+ return config.enable_autograd_cache
122
+
123
+
124
+ def should_bundle_autograd_cache():
125
+ return config.bundled_autograd_cache or torch._dynamo.config.caching_precompile
126
+
127
+
128
+ def check_node_safe(node: Node):
129
+ """
130
+ Checks that the node only uses supported operators. We are starting with very
131
+ conservative cacheability constraints, and incrementally adding more support as we expand.
132
+
133
+ [Note: AOTAutograd Cacheability checks]
134
+ - Our cache key is computed from the FX graph produced by Dynamo and the input example values
135
+ - A node is "safe" if the same cache key results in a compiled artifact that has the same behavior
136
+ (i.e, the set of inputs that go into our cache key is sufficient to distinguish its behavior)
137
+
138
+ To accomplish this safety check, we consider the following functions to be safe:
139
+ - Public functions under modules torch, torch.functional, and torch.nn.functional: these are
140
+ allowed in the graph by dynamo, so we can assume they are safe to cache.
141
+ - method calls on base tensor types
142
+ - Any call_module that dynamo deemed safe to allow AOTAutograd to trace
143
+ - Non callable nodes, such as placeholder, output, get_attr
144
+
145
+ The test suite test_aot_autograd_cache.py::AOTAutogradCachePicklerTests tries its best to fully cover/specify this behavior.
146
+ """
147
+ SAFE_TORCH_MODULES = ("torch.functional", "torch.nn.functional")
148
+ SAFE_TORCH_FUNCTIONS = (
149
+ "torch.Size",
150
+ "torch.Tensor",
151
+ "torch.sym_int",
152
+ "torch._sym_sqrt",
153
+ "torch.sym_float",
154
+ "torch.sym_sum",
155
+ )
156
+ SAFE_NON_TORCH_FUNCTIONS = (
157
+ "einops.einops.rearrange",
158
+ "einops.einops.repeat",
159
+ )
160
+
161
+ def is_public_torch_api(target):
162
+ # Don't blindly allow private functions in the torch namespace
163
+ is_private = target.__name__.startswith("_")
164
+
165
+ return (
166
+ getattr(target, "__module__", None) in SAFE_TORCH_MODULES and not is_private
167
+ )
168
+
169
+ def is_safe_torch_function(target):
170
+ """Allowlisted torch functions"""
171
+ function_name = f"{target.__module__}.{target.__name__}"
172
+ # Allow torch.autograd.function.FunctionCtx if custom autograd functions are allowed
173
+ if function_name == "torch.autograd.function.FunctionCtx":
174
+ return (
175
+ torch._functorch.config.autograd_cache_allow_custom_autograd_functions
176
+ )
177
+
178
+ # Functions in torch_non_c_binding_in_graph_functions
179
+ # are guaranteed to be cache safe.
180
+ # See NOTE: [Cacheability of in-graph torch functions]
181
+ return (
182
+ function_name in torch_non_c_binding_in_graph_functions
183
+ or function_name in SAFE_TORCH_FUNCTIONS
184
+ or function_name in torch._inductor.config.unsafe_marked_cacheable_functions
185
+ )
186
+
187
+ def is_cacheable_function(target):
188
+ if isinstance(target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)):
189
+ return True
190
+ if is_public_torch_api(target):
191
+ return True
192
+ # Technically, FXGraphCache._check_for_hop already checks this,
193
+ # but better to error earlier anyway
194
+ if isinstance(target, torch._ops.HigherOrderOperator):
195
+ return target.cacheable()
196
+ is_builtin_fun_or_type = type(target).__name__ == "builtin_function_or_method"
197
+ if is_builtin_fun_or_type:
198
+ return True
199
+ if is_safe_torch_function(target):
200
+ return True
201
+ function_name = f"{target.__module__}.{target.__name__}"
202
+ if function_name in SAFE_NON_TORCH_FUNCTIONS:
203
+ return True
204
+ return False
205
+
206
+ def is_tensor(target):
207
+ # Tensors always have example values in meta field
208
+ return "example_value" in target.meta
209
+
210
+ # I'd love to use a match statement here, but it wasn't introduced until py3.10
211
+ if node.op == "call_function":
212
+ if node.meta and node.meta.get("is_wrapped", False):
213
+ # This is fx.wrap function
214
+ # By default we BypassAOTAutogradCache for unknown functions,
215
+ # But if user explicitly specified cache hash - allow to cache it.
216
+ if node.meta.get("user_cache_hash", None):
217
+ return
218
+
219
+ if not is_cacheable_function(node.target):
220
+ module = getattr(node.target, "__module__", None)
221
+ name = getattr(node.target, "__name__", None)
222
+ raise BypassAOTAutogradCache(
223
+ f"Unsupported call_function target {node.target}. \n Function module: {module}, \nFunction name: {name}"
224
+ )
225
+ elif node.op == "call_method":
226
+ method_name = node.target
227
+ method_target = node.args[0]
228
+ # Only support method calls on base tensors
229
+ if not is_tensor(method_target):
230
+ module = getattr(method_target, "__module__", None)
231
+ name = getattr(method_target, "__name__", None)
232
+ raise BypassAOTAutogradCache(
233
+ f"Unsupported call_method target {method_target}. \nMethod module: {module}, \nMethod name: {name}"
234
+ )
235
+ if (
236
+ type(method_name) != str
237
+ and type(method_name).__name__ != "method_descriptor"
238
+ ):
239
+ raise BypassAOTAutogradCache(
240
+ f"Unsupported call_method method {node.target}: {method_name}"
241
+ )
242
+ # Cache safe
243
+ elif node.op in ("placeholder", "get_attr", "call_module", "output"):
244
+ # Assumption today for call_module being a safe op:
245
+ # (1) today the only call_module ops that can show up in a graph come from "built-in-nn-modules"
246
+ # that dynamo assumes are safe to trace. If dynamo assumes they are safely to blindly trace, then
247
+ # they should be safe to cache as well.
248
+ # (2) in the steady-state (some time in H2?) we shouldn't see these anymore, once inline builtin nn modules by default
249
+ # (3) We do not allow user made nn modules in the graph today, only function calls.
250
+ pass
251
+ else:
252
+ raise BypassAOTAutogradCache(f"Unsupported node op {node.op}")
253
+
254
+
255
+ def check_cacheable(gm: torch.fx.GraphModule):
256
+ """
257
+ Checks that the graph module only uses supported operators
258
+ """
259
+ nodes = gm.graph.nodes
260
+ if torch._inductor.config.freezing:
261
+ raise BypassAOTAutogradCache("Cannot cache a graph with freezing enabled")
262
+
263
+ if not (
264
+ torch._inductor.config.fx_graph_cache or should_use_remote_fx_graph_cache()
265
+ ):
266
+ raise BypassAOTAutogradCache("FX graph cache is not enabled")
267
+
268
+ tracing_context = torch._guards.TracingContext.try_get()
269
+ if tracing_context and tracing_context.fakify_first_call:
270
+ raise BypassAOTAutogradCache(
271
+ "Won't cache a graph with fakify_first_call enabled"
272
+ )
273
+ for node in nodes:
274
+ check_node_safe(node)
275
+
276
+ # Saved tensors hooks are globally set subgraphs,
277
+ # that are not used explicitly in the main graph.
278
+ # They are inlined in aot_autograd graphs.
279
+ # Subgraphs are only used for caching logic.
280
+ if hasattr(gm, "saved_tensors_hooks_pack_0"):
281
+ check_cacheable(gm.saved_tensors_hooks_pack_0) # type: ignore[arg-type]
282
+ # We have guarantee of unpack sugraph existence if pack subgraph exists
283
+ check_cacheable(gm.saved_tensors_hooks_unpack_0) # type: ignore[arg-type]
284
+
285
+
286
+ class AOTAutogradCacheDetails(FxGraphHashDetails):
287
+ """
288
+ Object to capture all the details for a dynamo graph module relevant to computing
289
+ a safe and stable cache key for AOTAutograd.
290
+ """
291
+
292
+ def get_triton_source_codes_from_gm(
293
+ self,
294
+ gm: torch.fx.GraphModule,
295
+ ):
296
+ triton_kernels = []
297
+ for module in gm.modules():
298
+ if not isinstance(module, torch.fx.GraphModule):
299
+ continue
300
+ for node in module.graph.nodes:
301
+ if isinstance(node.target, torch._ops.OpOverloadPacket):
302
+ attrs = node.target._dir
303
+ for attr in attrs:
304
+ if custom_op := getattr(node.target, attr, None):
305
+ kernels = torch._library.triton.get_triton_kernels_for_op(
306
+ custom_op._name
307
+ )
308
+ triton_kernels.extend(kernels)
309
+ elif isinstance(node.target, torch._ops.OpOverload):
310
+ kernels = torch._library.triton.get_triton_kernels_for_op(
311
+ node.target._name
312
+ )
313
+ triton_kernels.extend(kernels)
314
+
315
+ triton_kernel_source_codes = []
316
+ from torch._inductor.codegen.wrapper import (
317
+ user_defined_triton_kernel_transitive_closure_source_code,
318
+ )
319
+
320
+ for kernel in triton_kernels:
321
+ source_codes = user_defined_triton_kernel_transitive_closure_source_code(
322
+ kernel
323
+ )
324
+ triton_kernel_source_codes.append(source_codes)
325
+
326
+ return triton_kernel_source_codes
327
+
328
+ def __init__(
329
+ self,
330
+ gm: torch.fx.GraphModule,
331
+ example_inputs,
332
+ aot_config: AOTConfig,
333
+ fx_config: _CompileFxKwargs,
334
+ ):
335
+ # FxGraphHashDetails contains all the keys related to inductor. Also includes some system info
336
+ self.aot_config = aot_config
337
+ self.grad_enabled = torch.is_grad_enabled()
338
+ self.disable_amp = torch._C._is_any_autocast_enabled()
339
+ self.deterministic_algorithms = torch.are_deterministic_algorithms_enabled()
340
+ self.autograd_config = config.save_config()
341
+ self.saved_tensors_hooks_fx_wrap_cache_hashes: tuple[list[str], list[str]] = (
342
+ [],
343
+ [],
344
+ )
345
+ self.triton_kernel_source_codes = self.get_triton_source_codes_from_gm(gm)
346
+
347
+ if hasattr(gm, "saved_tensors_hooks_pack_0"):
348
+
349
+ def _add_wrapped_user_cache_hashes(_gm, _l):
350
+ for node in _gm.graph.nodes:
351
+ if node.meta and node.meta.get("is_wrapped", False):
352
+ _l.append(node.meta["user_cache_hash"])
353
+
354
+ _add_wrapped_user_cache_hashes(
355
+ gm.saved_tensors_hooks_pack_0,
356
+ self.saved_tensors_hooks_fx_wrap_cache_hashes[0],
357
+ )
358
+ _add_wrapped_user_cache_hashes(
359
+ gm.saved_tensors_hooks_unpack_0,
360
+ self.saved_tensors_hooks_fx_wrap_cache_hashes[1],
361
+ )
362
+
363
+ try:
364
+ # FXGraphCache has constraints on what can be pickled in its inductor
365
+ # config. Check that the gm is cacheable by inductor first,
366
+ # and if it raises an exception, also bypass on our end.
367
+ FxGraphCache._check_can_cache(gm)
368
+ super().__init__(gm, example_inputs, fx_config, [])
369
+ except BypassFxGraphCache as e:
370
+ # Sometimes inductor configs are unpickleable and can fail
371
+ raise BypassAOTAutogradCache(str(e)) from e
372
+
373
+
374
+ class AOTAutogradCachePickler(FxGraphCachePickler):
375
+ def __init__(self, gm: torch.fx.GraphModule):
376
+ super().__init__(gm)
377
+ self.dispatch_table: dict
378
+ self.dispatch_table.update(
379
+ {
380
+ AOTConfig: functools.partial(self._reduce_aot_config),
381
+ torch.Tensor: functools.partial(self._reduce_tensor),
382
+ }
383
+ )
384
+
385
+ def _reduce_aot_config(self, aot_config: AOTConfig):
386
+ """
387
+ Reduce the config to a stable key for caching.
388
+ """
389
+ return (
390
+ _ident,
391
+ (
392
+ aot_config.num_params_buffers,
393
+ aot_config.keep_inference_input_mutations,
394
+ aot_config.is_export,
395
+ aot_config.no_tangents,
396
+ aot_config.dynamic_shapes,
397
+ aot_config.aot_autograd_arg_pos_to_source,
398
+ aot_config.enable_log,
399
+ aot_config.pre_dispatch,
400
+ ),
401
+ )
402
+
403
+ def _reduce_tensor(self, tensor):
404
+ """
405
+ Reduce the tensor to a stable key for caching.
406
+ """
407
+ metadata = extract_tensor_metadata_for_cache_key(tensor)
408
+ return (_ident, (metadata,))
409
+
410
+
411
+ @contextlib.contextmanager
412
+ def normalize_placeholder_names(gm: torch.fx.GraphModule):
413
+ """
414
+ Context manager that normalizes the placeholder names in the graph module.
415
+ This is used while generating a cache key for AOTAutogradCache, so that two graphs
416
+ that are isomorphic when normalizing names can hit the same cache entry.
417
+ This is safe because nothing underneath AOTAutograd uses the node names on the
418
+ original dynamo graph: AOTAutograd re-traces with its own nodes, and guards are
419
+ in terms of original sources rather than placeholder names.
420
+ """
421
+ # Standalone inductor: we're bypassing AOTAutogradCache anyway, so return the graph
422
+ # as-is
423
+ if not config.autograd_cache_normalize_inputs or not hasattr(gm, "graph"):
424
+ yield
425
+ return
426
+
427
+ # Track all the old state of placeholders
428
+ old_placeholder_names = []
429
+ old_used_names = copy(gm.graph._graph_namespace._used_names)
430
+ i = 0
431
+ for n in gm.graph.find_nodes(op="placeholder", sort=True):
432
+ if n.type != torch.SymInt:
433
+ # _rename renames the node in the body of the function,
434
+ # but it doesn't change the raw name from node.target
435
+ # So we also set the raw_name of node.target to a new placeholder name
436
+ new_placeholder_name = f"p_{i}"
437
+ old_placeholder_names.append((n.name, n.target))
438
+ n.target = new_placeholder_name
439
+ n._rename(new_placeholder_name)
440
+ i += 1
441
+ gm.recompile()
442
+ try:
443
+ yield
444
+ finally:
445
+ # Used_names contains all our old placeholder names,
446
+ # so we clear it temporarily when we put them back
447
+ gm.graph._graph_namespace._used_names = set()
448
+ # Restore the placeholder names
449
+ i = 0
450
+ for n in gm.graph.find_nodes(op="placeholder", sort=True):
451
+ if n.type != torch.SymInt:
452
+ (name, target) = old_placeholder_names[i]
453
+ n.target = target
454
+ n._rename(name)
455
+ i += 1
456
+ assert i == len(old_placeholder_names)
457
+ # Now restore the old namespace's used names
458
+ gm.graph._graph_namespace._used_names = old_used_names
459
+ gm.recompile()
460
+
461
+
462
+ def autograd_cache_key(
463
+ gm: torch.fx.GraphModule,
464
+ example_inputs,
465
+ config: AOTConfig,
466
+ fx_config: _CompileFxKwargs,
467
+ # TODO: add args and parameters
468
+ ) -> tuple[str, list[str]]:
469
+ """
470
+ Generate a unique hash of the FX graph for caching.
471
+ """
472
+ check_cacheable(gm)
473
+ if has_triton_package():
474
+ # Due to https://github.com/triton-lang/triton/issues/3729,
475
+ # if triton is < 3.2.0, AOTAutogradCache may cause us to
476
+ # attempt to load a cache entry without initializing
477
+ # the CUDA context on the autograd thread.
478
+
479
+ # Without caching, we naturally do this initialization when
480
+ # tracing through the graph with the autograd engine.
481
+ import triton
482
+
483
+ if triton.__version__ < "3.2.0":
484
+ raise BypassAOTAutogradCache("AOTAutogradCache requires triton 3.2.0")
485
+ details = AOTAutogradCacheDetails(gm, example_inputs, config, fx_config)
486
+ pickler = AOTAutogradCachePickler(gm)
487
+ # The prefix distinguishes among the other kinds of objects we cache
488
+ key = "a" + pickler.get_hash(details)
489
+ debug_lines = pickler.debug_lines(details)
490
+ log.debug(
491
+ "Autograd graph cache hash details for key %s:\n%s",
492
+ key,
493
+ LazyString(lambda: "\n".join(debug_lines)),
494
+ )
495
+ return key, debug_lines
496
+
497
+
498
+ TOut = TypeVar("TOut", bound=OutputCode)
499
+
500
+
501
+ class InductorOutput(Generic[TOut], ABC):
502
+ """
503
+ Class representing a single inductor output
504
+ """
505
+
506
+ @abstractmethod
507
+ def pre_save(self) -> None: ...
508
+
509
+ @abstractmethod
510
+ def load(self, example_inputs) -> TOut: ...
511
+
512
+ @abstractmethod
513
+ def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut: ...
514
+
515
+
516
+ @dataclass
517
+ class CompiledFxGraphLoadable(InductorOutput[CompiledFxGraph]):
518
+ """
519
+ A full compiled fx graph that doesn't need to lookup the FxGraphCache
520
+ to run
521
+ """
522
+
523
+ result: CompiledFxGraph
524
+
525
+ def pre_save(self) -> None:
526
+ disk_compiled_graph = copy(self.result)
527
+ disk_compiled_graph.prepare_for_serialization()
528
+ self.result = disk_compiled_graph
529
+ return
530
+
531
+ def load(self, example_inputs) -> CompiledFxGraph:
532
+ self.example_inputs = example_inputs
533
+
534
+ return self.result
535
+
536
+ def post_compile(
537
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
538
+ ) -> CompiledFxGraph:
539
+ constants = CompiledFxGraphConstants()
540
+ # Cache hit specific post compile
541
+ graph, cache_info = FxGraphCache.cache_hit_post_compile(result, {}, constants)
542
+ if graph is None:
543
+ raise BypassAOTAutogradCache("Failed to reload cache entry from disk")
544
+ torch._logging.trace_structured(
545
+ "artifact",
546
+ metadata_fn=lambda: {
547
+ "name": "fx_graph_bundled_cache_hit", # always a hit
548
+ "encoding": "json",
549
+ },
550
+ payload_fn=lambda: json.dumps(cache_info),
551
+ )
552
+ # Run normal post compile
553
+ graph.post_compile(self.example_inputs, constants, fx_config)
554
+ return graph
555
+
556
+
557
+ @dataclass
558
+ class FxGraphCacheLoadable(InductorOutput[CompiledFxGraph]):
559
+ fx_graph_cache_info: tuple[str, list[str]]
560
+ fx_graph_guard_expr: Optional[str]
561
+
562
+ def pre_save(self):
563
+ return
564
+
565
+ def _is_backward(self) -> bool:
566
+ return False
567
+
568
+ def load(self, example_inputs) -> CompiledFxGraph:
569
+ # [Note: AOTAutogradCache and FXGraphCache Guard interactions]
570
+ # As mentioned, AOTAutograd takes in the symint inputs from dynamo's list of arguments.
571
+ # FXGraphCache serializes guards that are needed in the shape_env based on these symint inputs to the graph.
572
+ # The invariant that AOTAutograd uses here is that the sources for symints given to it by dynamo are exactly
573
+ # the same as the ones it passes to inductor, for both the forward and backward passes.
574
+ # (This does not mean that the tensor values passed in are the same: only that their symints are).
575
+ # That is, AOTAutograd and Inductor never create new guards based on symints with different sources
576
+ # than those passed to it by inductor.
577
+
578
+ # We pass the post compile function, which sets various fx_config boxed values,
579
+ # so we can call it only after we're sure both forward and backward have
580
+
581
+ # Clear CompiledTritonKernels before loading from FXGraphCache
582
+ torch._inductor.async_compile.CompiledTritonKernels.cache_clear()
583
+ remote_cache = None
584
+ constants = CompiledFxGraphConstants()
585
+ if should_use_remote_fx_graph_cache():
586
+ remote_cache = FxGraphCache.get_remote_cache()
587
+ (cache_key, debug_lines) = self.fx_graph_cache_info
588
+
589
+ def check_exact_guard_match(guard_expr, _hints):
590
+ """
591
+ AOTAutogradCache tracks its own guards, so we just need to treat these guard expressions as a second
592
+ cache key of sorts: we just check for equality, i.e. the FXGraphCache entry with
593
+ the exact same guards as we originally saved into the cache.
594
+ """
595
+ return guard_expr == self.fx_graph_guard_expr
596
+
597
+ result, cache_info = FxGraphCache.load_with_key(
598
+ cache_key,
599
+ debug_lines,
600
+ example_inputs,
601
+ local=True,
602
+ remote_cache=remote_cache,
603
+ is_backward=self._is_backward(),
604
+ constants=constants,
605
+ evaluate_guards=check_exact_guard_match,
606
+ )
607
+ if result is None:
608
+ log.info("FXGraphCache cache miss for key %s", self.fx_graph_cache_info)
609
+ torch._logging.trace_structured(
610
+ "artifact",
611
+ metadata_fn=lambda: {
612
+ "name": "fx_graph_cache_miss", # always a hit
613
+ "encoding": "json",
614
+ },
615
+ payload_fn=lambda: json.dumps(cache_info),
616
+ )
617
+
618
+ raise FXGraphCacheMiss
619
+
620
+ # No need to log chromium event because AOTAutograd will log that immediately for us
621
+ torch._logging.trace_structured(
622
+ "artifact",
623
+ metadata_fn=lambda: {
624
+ "name": "fx_graph_cache_hit", # always a hit
625
+ "encoding": "json",
626
+ },
627
+ payload_fn=lambda: json.dumps(cache_info),
628
+ )
629
+ self.example_inputs = example_inputs
630
+ self.constants = constants
631
+ return result
632
+
633
+ def post_compile(
634
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
635
+ ) -> CompiledFxGraph:
636
+ """
637
+ Called after FXGraphCacheLoadable.load, mutates fx_config
638
+ """
639
+ result.post_compile(self.example_inputs, self.constants, fx_config)
640
+ return result
641
+
642
+
643
+ @dataclass
644
+ class CompiledForward(FxGraphCacheLoadable):
645
+ """
646
+ Cacheable entry for a forward function
647
+ """
648
+
649
+ def _is_backward(self) -> bool:
650
+ return False
651
+
652
+
653
+ @dataclass
654
+ class GenericCompiledBackward(InductorOutput[TOut]):
655
+ # Used by AOTDispatchAutograd.post_compile
656
+ backward_state_indices: list[int]
657
+ num_symints_saved_for_bw_: int
658
+
659
+
660
+ @dataclass
661
+ class CompiledBackward(GenericCompiledBackward[CompiledFxGraph], FxGraphCacheLoadable):
662
+ """
663
+ Cacheable entry for a forward function
664
+ """
665
+
666
+ def _is_backward(self) -> bool:
667
+ return True
668
+
669
+ def post_compile(
670
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
671
+ ) -> CompiledFxGraph:
672
+ compiled_bw = super().post_compile(result, fx_config)
673
+ # See note [Wrapping bw_compiler in disable]
674
+ # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py
675
+ # But since on cache hit we do not call the bw_compiler, we need to reapply the disable
676
+ return torch._dynamo.disable( # type: ignore[return-value]
677
+ compiled_bw, reason="do not trace generated backwards pass"
678
+ )
679
+
680
+
681
+ # Forward types don't have any extra parameters, so this is just a TypeAlias, in essence
682
+ class BundledCompiledForward(CompiledFxGraphLoadable):
683
+ pass
684
+
685
+
686
+ @dataclass
687
+ class BundledCompiledBackward(
688
+ GenericCompiledBackward[CompiledFxGraph], CompiledFxGraphLoadable
689
+ ):
690
+ def post_compile(
691
+ self, result: CompiledFxGraph, fx_config: _CompileFxKwargs
692
+ ) -> CompiledFxGraph:
693
+ compiled_bw = super().post_compile(result, fx_config)
694
+ # See note [Wrapping bw_compiler in disable]
695
+ # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py
696
+ # But since on cache hit we do not call the bw_compiler, we need to reapply the disable
697
+ return torch._dynamo.disable( # type: ignore[return-value]
698
+ compiled_bw, reason="do not trace generated backwards pass"
699
+ )
700
+
701
+
702
+ @dataclass
703
+ class SerializedGraphModule:
704
+ fn: Callable[[dict[Any, Any], str], torch.nn.Module]
705
+ args: tuple[Any, ...]
706
+
707
+ def __init__(self, gm: torch.fx.GraphModule):
708
+ self.fn, self.args = gm.__reduce__()
709
+
710
+ def deserialize(self) -> torch.fx.GraphModule:
711
+ gm = self.fn(*self.args)
712
+ assert isinstance(gm, torch.fx.GraphModule)
713
+ return gm
714
+
715
+
716
+ def serialize_graph_module(gm: torch.fx.GraphModule) -> SerializedGraphModule:
717
+ # NOTE: mutates the graph module
718
+ gm.meta = {}
719
+ for node in gm.graph.nodes:
720
+ node.meta = {}
721
+ return SerializedGraphModule(gm)
722
+
723
+
724
+ TForward = TypeVar("TForward", bound=InductorOutput)
725
+ TBackward = TypeVar("TBackward", bound=GenericCompiledBackward)
726
+
727
+
728
+ @dataclass
729
+ class GenericAOTAutogradCacheEntry(Generic[TForward, TBackward]):
730
+ """A single entry into the cache, genericized by Forward and Backward types.
731
+
732
+ A TForward is always an InductorOutput of some sort, which represents the
733
+ forward graph of the compile.
734
+ A TBackward is an InductorOutput + metadata about the backward, useful for specific
735
+ backward-only wrappers. This type is encapsulated by GenericCompiledBackward.
736
+
737
+ Each AOTAutogradCacheEntry is essentially parameterized by 1. the method of loading
738
+ from the cache (either Bundled or UnBundled), and 2. The type of the output. For now,
739
+ the only type of output we support is Python Wrapper output, i.e. OutputCode.CompiledFxGraph,
740
+ but the same technique works for C++ wrapper code; we'd just add an extra InductorOutput type.
741
+ """
742
+
743
+ # Forward and Backward info
744
+ compiled_fw: TForward
745
+ compiled_bw: Optional[TBackward]
746
+
747
+ # Code of the joint graph using print_readable()
748
+ # Used for logging purposes
749
+ aot_joint_graph_str: Optional[str]
750
+ aot_forward_graph_str: Optional[str]
751
+ aot_backward_graph_str: Optional[str]
752
+
753
+ # Runtime_metadata saved right before compilation
754
+ runtime_metadata: ViewAndMutationMeta
755
+
756
+ # Wrappers that run after each aot_dispatch_* function
757
+ dispatch_wrappers: list[CompilerWrapper]
758
+
759
+ # Used by AOTSubclassWrapper
760
+ maybe_subclass_meta: Optional[SubclassMeta]
761
+ num_fw_outs_saved_for_bw: Optional[int]
762
+
763
+ # Used by RuntimeWrapepr
764
+ indices_of_inps_to_detach: list[int]
765
+
766
+ # Time taken to trace/compile the forward
767
+ # forward_time_taken includes AOTAutograd tracing time + inductor compilation time
768
+ # backward_time_taken is essentially just the time inductor took to compile
769
+ forward_time_taken_ns: int
770
+ backward_time_taken_ns: int
771
+
772
+ # Used by standalone_compile
773
+ sanitized_aot_config: AOTConfig
774
+
775
+ guards_expr: Optional[str]
776
+
777
+ # Used by Compiled Autograd
778
+ serialized_bw_module: Optional[SerializedGraphModule]
779
+
780
+ def pre_save(self):
781
+ """
782
+ Perform any preparations to make the cache entry ready for serialization.
783
+ """
784
+ self.compiled_fw.pre_save()
785
+ if self.compiled_bw is not None:
786
+ self.compiled_bw.pre_save()
787
+
788
+ # Turn cache entry into the original callable
789
+ def wrap_post_compile(
790
+ self,
791
+ args: list[torch.Tensor],
792
+ aot_config: AOTConfig,
793
+ fx_config: _CompileFxKwargs,
794
+ ) -> Callable:
795
+ """
796
+ This function takes a cache entry and carefully reconstructs the original callable
797
+ that AOTAutograd returned the first time it was run. It does this by running the various
798
+ post compile steps that AOTAutograd runs on its compiled artifact after running the fw/bw compilers.
799
+
800
+ In the inference path, this consists of the Subclass, FunctionalzedRngRuntime, and RuntimeWrappers.
801
+ In the autograd path, this consists of AOTAutogradDispatch.post_compile.
802
+
803
+ The steps here should match exactly the steps that are run in aot_dispatch_base and aot_dispatch_autograd.
804
+
805
+ Notably absent from the cached path are:
806
+ - DebugAssertWrapper
807
+ - FakifiedOutWrapper
808
+
809
+ Which we'll handle separately later on, if necessary.
810
+ """
811
+ # Log the output of AOTAutogradCache
812
+ if aot_config.enable_log:
813
+ # TODO: maybe also log to aot_graphs_log
814
+ # Unfortunately aot_graphs_log uses
815
+ # slightly different formatting though
816
+ if self.aot_joint_graph_str is not None:
817
+ torch._logging.trace_structured(
818
+ "aot_joint_graph", payload_fn=lambda: self.aot_joint_graph_str
819
+ )
820
+
821
+ if self.aot_forward_graph_str is not None:
822
+ torch._logging.trace_structured(
823
+ "artifact",
824
+ metadata_fn=lambda: {
825
+ "name": "aot_forward_graph_fw_metadata",
826
+ "encoding": "string",
827
+ },
828
+ payload_fn=lambda: dataclass_repr(self.runtime_metadata),
829
+ )
830
+ if self.maybe_subclass_meta is not None:
831
+ torch._logging.trace_structured(
832
+ "artifact",
833
+ metadata_fn=lambda: {
834
+ "name": "aot_forward_graph_fw_subclass_metadata",
835
+ "encoding": "string",
836
+ },
837
+ payload_fn=lambda: dataclass_repr(self.maybe_subclass_meta),
838
+ )
839
+
840
+ # It's called an inference graph if not running with autograd
841
+ name = (
842
+ "aot_forward_graph"
843
+ if self.aot_backward_graph_str is not None
844
+ else "aot_inference_graph"
845
+ )
846
+ torch._logging.trace_structured(
847
+ name, payload_fn=lambda: self.aot_forward_graph_str
848
+ )
849
+
850
+ if self.aot_backward_graph_str is not None:
851
+ torch._logging.trace_structured(
852
+ "aot_backward_graph", payload_fn=lambda: self.aot_backward_graph_str
853
+ )
854
+ with dynamo_timed("AOTAutogradCache.inductor_load"):
855
+ compiled_fw_func = self.compiled_fw.load(args)
856
+ compiled_bw_func = None
857
+ if self.compiled_bw is not None:
858
+ compiled_bw_func = self.compiled_bw.load(args)
859
+ needs_autograd = True
860
+ CompileEventLogger.try_add_pt2_compile(
861
+ "backend_compile", dispatch_mode="autograd"
862
+ )
863
+ # Now that we've loaded forward and backward, call post compile on both
864
+ # This avoids setting things like BoxedBools in fx_config until
865
+ # after both forward and backward cache hit
866
+ fw_fx_config: _CompileFxKwargs = {
867
+ **fx_config,
868
+ "is_backward": False,
869
+ }
870
+ bw_fx_config: _CompileFxKwargs = {
871
+ **fx_config,
872
+ "is_backward": True,
873
+ }
874
+ compiled_fw_func = self.compiled_fw.post_compile(
875
+ compiled_fw_func, fw_fx_config
876
+ )
877
+ compiled_bw_func = self.compiled_bw.post_compile(
878
+ compiled_bw_func, bw_fx_config
879
+ )
880
+ else:
881
+ inference_fx_config: _CompileFxKwargs = {
882
+ **fx_config,
883
+ "is_backward": False,
884
+ }
885
+
886
+ needs_autograd = False
887
+ CompileEventLogger.try_add_pt2_compile(
888
+ "backend_compile", dispatch_mode="inference"
889
+ )
890
+ compiled_fw_func = self.compiled_fw.post_compile(
891
+ compiled_fw_func, inference_fx_config
892
+ )
893
+
894
+ # Wrap the forward function in post compile wrappers
895
+ compiled_fw_func = AOTDispatchSubclassWrapper(
896
+ trace_joint=needs_autograd,
897
+ fw_only=None,
898
+ maybe_subclass_meta=self.maybe_subclass_meta,
899
+ num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw,
900
+ ).post_compile(
901
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
902
+ )
903
+
904
+ req_subclass_dispatch = self.maybe_subclass_meta is not None
905
+ CompileEventLogger.try_add_pt2_compile(
906
+ "backend_compile", requires_subclass_dispatch=req_subclass_dispatch
907
+ )
908
+
909
+ # In autograd case, functionalizedRngWrapper should not modify outs
910
+ return_new_outs = not needs_autograd
911
+ compiled_fw_func = FunctionalizedRngRuntimeWrapper(
912
+ return_new_outs=return_new_outs
913
+ ).post_compile(
914
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
915
+ )
916
+ disable_amp = torch._C._is_any_autocast_enabled()
917
+
918
+ if needs_autograd:
919
+ assert self.compiled_bw is not None
920
+
921
+ cached_lazy_backward = None
922
+ if self.serialized_bw_module is not None:
923
+ cached_lazy_backward = CachedAutogradLazyBackwardCompileInfo(
924
+ self.serialized_bw_module.deserialize
925
+ )
926
+ # This function is run on both cache miss and cache hit, either here
927
+ # or in aot_dispatch_autograd. On a cache hit,
928
+ # 1. the bw is already compiled
929
+ # 2. we don't need to save to the cache again
930
+ # so those corresponding arguments are set to None.
931
+ compiled_function = AOTDispatchAutograd.post_compile(
932
+ compiled_fw_func,
933
+ compiled_bw_func,
934
+ self.maybe_subclass_meta,
935
+ self.compiled_bw.num_symints_saved_for_bw_,
936
+ self.compiled_bw.backward_state_indices,
937
+ disable_amp,
938
+ self.indices_of_inps_to_detach,
939
+ cached_lazy_backward,
940
+ aot_config,
941
+ fw_metadata=self.runtime_metadata,
942
+ try_save_cache_entry=None,
943
+ )
944
+ else:
945
+ compiled_function = RuntimeWrapper(
946
+ indices_of_inps_to_detach=self.indices_of_inps_to_detach,
947
+ trace_joint=False,
948
+ disable_amp=disable_amp,
949
+ ).post_compile(
950
+ compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata
951
+ )
952
+
953
+ compiled_function, _ = post_compile(
954
+ self.dispatch_wrappers,
955
+ compiled_function,
956
+ aot_config,
957
+ runtime_metadata=self.runtime_metadata,
958
+ )
959
+
960
+ # Now that we're pretty sure it's a successful load, add guards
961
+ # to the existing shape environment from the cache
962
+ if self.guards_expr:
963
+ symints = AOTAutogradCache._filter_backed_symints(args)
964
+ check = bool(AOTAutogradCache.evaluate_guards(self.guards_expr, symints))
965
+ assert check is True
966
+
967
+ return compiled_function
968
+
969
+
970
+ class AOTAutogradCacheEntry(
971
+ GenericAOTAutogradCacheEntry[CompiledForward, CompiledBackward]
972
+ ):
973
+ """
974
+ Regular AOTAutogradCacheEntry: saves the forward/backward FxGraphCache keys
975
+ and looks them up in FxGraphCache on load
976
+ """
977
+
978
+
979
+ class BundledAOTAutogradCacheEntry(
980
+ GenericAOTAutogradCacheEntry[BundledCompiledForward, BundledCompiledBackward]
981
+ ):
982
+ """
983
+ AOTAutogradCacheEntry where we save the entire CompiledFxGraph instead
984
+ of relying on cache keys from FxGraphCache
985
+ """
986
+
987
+
988
+ @contextlib.contextmanager
989
+ def sanitize_gm_for_cache(gm: torch.fx.GraphModule):
990
+ """
991
+ Clears a few fields in a dynamo supplied Graph Module that are not stable between graph inputs, but don't
992
+ affect inductor or aotdispatch correctness.
993
+
994
+ These fields **can** be used by code calling into aotdispatch (namely, dynamo), so we can't null them out completely.
995
+
996
+ To ensure that these fields are not accessed by inductor or aotdispatch, we clear them during AOTAutogradCache.load,
997
+ and then put them back before returning. This way, we generate a cache key based off of a canonical graph
998
+ without these fields, and also guarantee they aren't used to affect the cache's output.
999
+ """
1000
+ # Mapping from each field to a default value
1001
+ IGNORED_FIELDS: dict[str, Any] = {
1002
+ "meta": {}, # metadata used by export
1003
+ "compile_subgraph_reason": None, # Used by dynamo only for logging, no change in inductor/autograd behavior
1004
+ "_param_name_to_source": None, # Encapsulated by aot_config.aot_autograd_arg_pos_to_source
1005
+ "_backend_id": None,
1006
+ }
1007
+ saved_fields = {}
1008
+ for field, default_value in IGNORED_FIELDS.items():
1009
+ saved_fields[field] = getattr(gm, field, None)
1010
+ # Clear the field
1011
+ setattr(gm, field, default_value)
1012
+ try:
1013
+ with normalize_placeholder_names(gm):
1014
+ yield
1015
+ finally:
1016
+ for field, value in saved_fields.items():
1017
+ setattr(gm, field, value)
1018
+
1019
+
1020
+ @CacheArtifactFactory.register
1021
+ class AOTAutogradCacheArtifact(CacheArtifact):
1022
+ @override
1023
+ def populate_cache(self):
1024
+ AOTAutogradCache._write_to_local_cache(self.key, self.content)
1025
+
1026
+ @override
1027
+ @staticmethod
1028
+ def type():
1029
+ return "aot_autograd"
1030
+
1031
+
1032
+ @CacheArtifactFactory.register
1033
+ class BundledAOTAutogradCacheArtifact(PrecompileCacheArtifact[Callable]):
1034
+ @override
1035
+ @staticmethod
1036
+ def type():
1037
+ return "precompile_aot_autograd"
1038
+
1039
+ @override
1040
+ def after_deserialization(self) -> Callable:
1041
+ entry = pickle.loads(self.content)
1042
+ # In the precompile use case, guards are already serialized
1043
+ # by dynamo, so we don't need to add them to the environment
1044
+ entry.guards_expr = None
1045
+ # TODO: this isn't exactly right, because cudagraphs needs to be a shared config
1046
+ # which is set by compile_fx. But in precompile, we never actually call compile_fx
1047
+ # so we don't have a place to track cudagraphs here.
1048
+ cudagraphs = torch._inductor.config.triton.cudagraphs
1049
+ boxed_forward_device_index = BoxedDeviceIndex(None)
1050
+ compiled_fn = entry.wrap_post_compile(
1051
+ [],
1052
+ entry.sanitized_aot_config,
1053
+ {
1054
+ "cudagraphs": cudagraphs,
1055
+ "boxed_forward_device_index": boxed_forward_device_index,
1056
+ },
1057
+ )
1058
+
1059
+ # TODO: this ignores flat_params, which can exist
1060
+ # if inline_builtin_nn_modules=False
1061
+ def forward(*runtime_args: tuple[Any]):
1062
+ return compiled_fn(list(runtime_args))
1063
+
1064
+ return forward
1065
+
1066
+
1067
+ class AOTAutogradCache(GuardedCache[GenericAOTAutogradCacheEntry]):
1068
+ """
1069
+ Caches the results of running AOTAutograd. This class mostly handles the save and load logic, whereas
1070
+ AOTAutogradCacheEntry handles the wrapping/unwrapping logic.
1071
+
1072
+ Cache Inputs (AOTAutogradCacheDetails)
1073
+ - AOTAutogradCache takes in the following inputs, which are analogous to inputs given
1074
+ to AOTAutograd by dynamo:
1075
+ - A fx graph module generated by dynamo
1076
+ - A list of args, which consists of:
1077
+ - Symint inputs to the graph, generated by dynamo
1078
+ - The **real tensor** inputs, which inductor uses for cudagraphs
1079
+ - Notably, the real tensor inputs don't have symints in their metadata.
1080
+ AOTAutograd then retraces those real tensor arguments into FakeTensors later during execution.
1081
+ - A set of global configurations that affect AOTAutograd or Inductor behavior.
1082
+
1083
+ It then generates a cache key given these values. Notably, this means AOTAutogradCache currently
1084
+ specializes on the sizes and strides of the real tensor inputs when dynamic shapes are turned on.
1085
+ In a later PR, we'll likely generate the cache key based on the FakeTensors AOTAutograd generates
1086
+ based on the real tensor inputs, which can contain symints.
1087
+
1088
+ # Cache Outputs (AOTAutogradCacheEntry)
1089
+ - AOTAutogradCache caches the following values:
1090
+ - The compiled forward and backward functions from inductor, via keys to the FXGraphCache
1091
+ - Metadata to reconstruct the AOTModule from the compiled inductor artifacts
1092
+ - See AOTAutogradCacheEntry for more info
1093
+
1094
+ [Note: Caching guards generated by AOTAutograd and Inductor]
1095
+ AOTAutograd and inductor both can introduce new guards to the shape environment. FXGraphCache saves guards with each
1096
+ compiled graph inductor generates. On a cache hit, AOTAutograd reloads the compiled forward and backward functions
1097
+ from FXGraphCache, giving it new symint arguments from the input args.
1098
+ FXGraphCache uses those symints and its saved guards to repopulate the ShapeEnv with guards.
1099
+ **No new guards are generated into the shape env after inductor finishes compiling**, so the guards
1100
+ saved by inductor are sufficient for correctness for both AOTAutograd and Inductor's caches.
1101
+ """
1102
+
1103
+ @staticmethod
1104
+ def clear():
1105
+ """Clear the cache"""
1106
+ try:
1107
+ shutil.rmtree(AOTAutogradCache._get_tmp_dir())
1108
+ except FileNotFoundError:
1109
+ pass
1110
+
1111
+ @staticmethod
1112
+ def try_load(
1113
+ mod: Union[torch.fx.GraphModule, torch._dynamo.utils.GmWrapper],
1114
+ args,
1115
+ aot_config: AOTConfig,
1116
+ cudagraphs: BoxedBool,
1117
+ boxed_forward_device_index: Optional[BoxedDeviceIndex],
1118
+ local: bool,
1119
+ remote: bool,
1120
+ ) -> Optional[Callable]:
1121
+ """
1122
+ Load a result from the cache, and reconstruct a runtime wrapper around the object
1123
+ """
1124
+ gm = mod.gm if isinstance(mod, torch._dynamo.utils.GmWrapper) else mod
1125
+ with sanitize_gm_for_cache(gm):
1126
+ compiled_fn = None
1127
+ cache_info: dict[str, Any] = {}
1128
+ cache_key = None
1129
+ debug_lines: list[str] = []
1130
+ cache_event_time = time.time_ns()
1131
+ cache_state = None
1132
+ fx_config: _CompileFxKwargs = {
1133
+ "cudagraphs": cudagraphs,
1134
+ "boxed_forward_device_index": boxed_forward_device_index,
1135
+ }
1136
+ try:
1137
+ cache_key, debug_lines = autograd_cache_key(
1138
+ gm, args, aot_config, fx_config
1139
+ )
1140
+ entry: Optional[GenericAOTAutogradCacheEntry] = (
1141
+ AOTAutogradCache._lookup(
1142
+ cache_key, local, remote, args, cache_info, aot_config
1143
+ )
1144
+ )
1145
+ if entry is not None:
1146
+ compiled_fn = entry.wrap_post_compile(args, aot_config, fx_config)
1147
+ log.info("AOTAutograd cache hit for key %s", cache_key)
1148
+
1149
+ counters["aot_autograd"]["autograd_cache_hit"] += 1
1150
+ cache_state = "hit"
1151
+ cache_event_time = time.time_ns()
1152
+ forward_time_saved = entry.forward_time_taken_ns // 1e6
1153
+ backward_time_saved = entry.backward_time_taken_ns // 1e6
1154
+ cache_info.update(
1155
+ {
1156
+ "forward_time_saved_ms": forward_time_saved,
1157
+ "backward_time_saved_ms": backward_time_saved,
1158
+ "time_saved_ms": forward_time_saved + backward_time_saved,
1159
+ }
1160
+ )
1161
+ time_saved_ns = (
1162
+ entry.forward_time_taken_ns + entry.backward_time_taken_ns
1163
+ )
1164
+ # TODO: should we use the same field for remote cache time saved for both
1165
+ # FXGraphCache and AOTAutogradCache?
1166
+ # get_metrics_context().increment(...)
1167
+ if (
1168
+ ephemeral_increase
1169
+ := add_ephemeral_timeout_increase_for_distributed(time_saved_ns)
1170
+ ) != 0:
1171
+ cache_info["ephemeral_timeout_increase"] = ephemeral_increase
1172
+
1173
+ if compiled_fn is None:
1174
+ log.info("AOTAutograd cache miss for key %s", cache_key)
1175
+ counters["aot_autograd"]["autograd_cache_miss"] += 1
1176
+ cache_state = "miss"
1177
+ cache_event_time = time.time_ns()
1178
+ # Count missing the FXGraphCache as a miss not a bypass
1179
+ except FXGraphCacheMiss as e:
1180
+ counters["aot_autograd"]["autograd_cache_miss"] += 1
1181
+ cache_state = "miss"
1182
+ if (
1183
+ config.strict_autograd_cache
1184
+ or torch._dynamo.config.caching_precompile
1185
+ ):
1186
+ raise e
1187
+ # Most often this is BypassAOTAutogradCache, but
1188
+ # if there's ever different reason we can't cache,
1189
+ # we still never want to hard throw an exception, since
1190
+ # we can always fallback to a cache bypass.
1191
+ # As an example, if the user calls autograd via
1192
+ # standalone inductor, we will sometimes get a GraphModule
1193
+ # that doesn't actually have a `.graph` on it. Instead
1194
+ # of checking every single case, we safely catch the exception
1195
+ # in those cases.
1196
+ except Exception as e:
1197
+ cache_key = None
1198
+ counters["aot_autograd"]["autograd_cache_bypass"] += 1
1199
+ log.info("Bypassing autograd cache due to: %s", e)
1200
+ cache_state = "bypass"
1201
+ cache_event_time = time.time_ns()
1202
+ cache_info["cache_bypass_reason"] = str(e)
1203
+ cache_info["cache_bypass_exception_type"] = type(e).__name__
1204
+ cache_info["cache_bypass_traceback"] = traceback.format_exc().split(
1205
+ "\n"
1206
+ )
1207
+ # TODO: this gets logged implicitly by cache_bypass_reason,
1208
+ # and here we explicitly log it into tlparse.
1209
+ # We may want to log this as an extra column in Scuba, though.
1210
+ cache_info["cache_bypass_hard_exception"] = not isinstance(
1211
+ e, BypassAOTAutogradCache
1212
+ )
1213
+ if remote:
1214
+ log_cache_bypass("bypass_aot_autograd", str(e))
1215
+ if (
1216
+ config.strict_autograd_cache
1217
+ or torch._dynamo.config.caching_precompile
1218
+ ):
1219
+ raise e
1220
+ if compiled_fn is None:
1221
+ # Set the cache key so we can save a cache result later
1222
+ symints = AOTAutogradCache._filter_backed_symints(args)
1223
+ if cache_key is not None:
1224
+ aot_config.cache_info = AOTAutogradCacheInfo(
1225
+ cache_key,
1226
+ time.time_ns(),
1227
+ forward_symints=symints,
1228
+ )
1229
+
1230
+ cache_info.update(
1231
+ {
1232
+ "key": cache_key,
1233
+ "cache_state": cache_state,
1234
+ "components": debug_lines,
1235
+ }
1236
+ )
1237
+ if chromium_event_log_active():
1238
+ CompileEventLogger.instant(
1239
+ f"autograd_cache_{cache_state}",
1240
+ metadata=cache_info,
1241
+ time_ns=cache_event_time,
1242
+ )
1243
+ CompileEventLogger.try_add_pt2_compile(
1244
+ "backend_compile",
1245
+ cache_state=cache_state,
1246
+ cache_event_time=cache_event_time,
1247
+ key=cache_info.get("key"),
1248
+ components=cache_info.get("components"),
1249
+ cache_bypass_reason=cache_info.get("cache_bypass_reason"),
1250
+ remote_cache_enabled=remote,
1251
+ local_cache_enabled=local,
1252
+ )
1253
+
1254
+ torch._logging.trace_structured(
1255
+ "artifact",
1256
+ metadata_fn=lambda: {
1257
+ "name": f"aotautograd_cache_{cache_state}",
1258
+ "encoding": "json",
1259
+ },
1260
+ payload_fn=lambda: json.dumps(cache_info),
1261
+ )
1262
+
1263
+ return compiled_fn
1264
+
1265
+ @classmethod
1266
+ def generate_guards_expression(
1267
+ cls: type[AOTAutogradCache], cache_info: AOTAutogradCacheInfo
1268
+ ) -> Optional[str]:
1269
+ shape_env = cls._get_shape_env()
1270
+ assert shape_env is not None
1271
+ symints = cache_info.forward_symints
1272
+ guards = shape_env.get_pruned_guards(symints)
1273
+ return shape_env.produce_guards_expression(placeholders=symints, guards=guards)
1274
+
1275
+ @classmethod
1276
+ def _get_tmp_dir(cls: type[AOTAutogradCache]) -> str:
1277
+ """
1278
+ Get the toplevel temporary directory for storing compiled graphs.
1279
+ """
1280
+ return os.path.join(cache_dir(), "aotautograd")
1281
+
1282
+ @classmethod
1283
+ def _get_tmp_dir_for_key(cls: type[AOTAutogradCache], key) -> str:
1284
+ """
1285
+ Get the toplevel temporary directory for storing compiled graphs.
1286
+ """
1287
+ return os.path.join(cls._get_tmp_dir(), key)
1288
+
1289
+ @staticmethod
1290
+ def evaluate_guards(guard_expr: str, hints: Union[list[int], list[torch.SymInt]]):
1291
+ if torch._inductor.config.unsafe_skip_cache_dynamic_shape_guards:
1292
+ return True
1293
+ shape_env = AOTAutogradCache._get_shape_env()
1294
+ assert shape_env is not None
1295
+ result = shape_env.evaluate_guards_expression(guard_expr, hints)
1296
+ return result
1297
+
1298
+ @staticmethod
1299
+ def _lookup(
1300
+ key: str,
1301
+ local: bool,
1302
+ remote: bool,
1303
+ args: list[Any],
1304
+ cache_info: dict[str, Any],
1305
+ aot_config: Optional[AOTConfig],
1306
+ ) -> Optional[GenericAOTAutogradCacheEntry]:
1307
+ """Given a key generated by AOTAutogradCachePickler, look up its location in the cache."""
1308
+ remote_cache: Optional[RemoteCache[JsonDataTy]] = None
1309
+ if remote:
1310
+ remote_cache = AOTAutogradCache.get_remote_cache()
1311
+
1312
+ symints = AOTAutogradCache._filter_backed_symints(args)
1313
+ hints = [hint_int(s) for s in symints]
1314
+ entry = None
1315
+ try:
1316
+ (
1317
+ entry,
1318
+ pickled_content,
1319
+ guard_info,
1320
+ ) = AOTAutogradCache.find_guarded_entry(
1321
+ key, local, remote_cache, AOTAutogradCache.evaluate_guards, hints
1322
+ )
1323
+
1324
+ if entry is None and guard_info["cache_status_detailed"] == "guard_miss":
1325
+ counters["aot_autograd"]["autograd_cache_guard_miss"] += 1
1326
+ cache_info.update(guard_info)
1327
+ if pickled_content is not None:
1328
+ CacheArtifactManager.record_artifact(
1329
+ AOTAutogradCacheArtifact.type(), key, pickled_content
1330
+ )
1331
+ if (
1332
+ should_bundle_autograd_cache()
1333
+ and aot_config is not None
1334
+ and aot_config.precompile_backend_id is not None
1335
+ ):
1336
+ # NB: We don't want to use the cached aot_config.precompile_backend_id
1337
+ # 1. because we set it to None on save 2. even if we didn't, this new run
1338
+ # that cache hit has a *new* backend id associated with it.
1339
+ PrecompileContext.record_artifact(
1340
+ BundledAOTAutogradCacheArtifact.type(),
1341
+ aot_config.precompile_backend_id,
1342
+ pickled_content,
1343
+ )
1344
+ except Exception as e:
1345
+ log.info("AOTAutograd cache unable to load compiled graph: %s", e)
1346
+ if config.strict_autograd_cache:
1347
+ raise e
1348
+ return entry
1349
+
1350
+ @staticmethod
1351
+ def _write_to_local_cache(key: str, content: bytes):
1352
+ """Write an entry to the local cache."""
1353
+ subdir = AOTAutogradCache._get_tmp_dir_for_key(key)
1354
+ if not os.path.exists(subdir):
1355
+ os.makedirs(subdir, exist_ok=True)
1356
+
1357
+ # Use a hash of the serialized entry to get a unique file
1358
+ # name. The specific name doesn't matter since a lookup involves
1359
+ # iterating over all entries in the parent subdir.
1360
+ path = os.path.join(subdir, sha256_hash(content))
1361
+ log.info("Writing AOTAutograd cache entry to %s", path)
1362
+ write_atomic(path, content)
1363
+
1364
+ @staticmethod
1365
+ def save(key: str, entry: GenericAOTAutogradCacheEntry, remote: bool):
1366
+ """Save a single entry into the cache."""
1367
+ try:
1368
+ entry.pre_save()
1369
+ content = pickle.dumps(entry)
1370
+ CacheArtifactManager.record_artifact(
1371
+ AOTAutogradCacheArtifact.type(), key, content
1372
+ )
1373
+ if (
1374
+ should_bundle_autograd_cache()
1375
+ and entry.sanitized_aot_config.precompile_backend_id is not None
1376
+ ):
1377
+ precompile_key = entry.sanitized_aot_config.precompile_backend_id
1378
+ # Now that we're saving it, the precompile_backend_id field is no longer
1379
+ # useful, remove it from the entry.
1380
+ entry.sanitized_aot_config.precompile_backend_id = None
1381
+ PrecompileContext.record_artifact(
1382
+ BundledAOTAutogradCacheArtifact.type(),
1383
+ precompile_key,
1384
+ entry,
1385
+ editable=True,
1386
+ )
1387
+ AOTAutogradCache._write_to_local_cache(key, content)
1388
+ counters["aot_autograd"]["autograd_cache_saved"] += 1
1389
+ except BypassAOTAutogradCache as e:
1390
+ counters["aot_autograd"]["autograd_cache_bypass"] += 1
1391
+ log.info("Bypassing autograd cache due to: %s", e)
1392
+ if remote:
1393
+ log_cache_bypass("bypass_aot_autograd", str(e))
1394
+ return None
1395
+ except Exception as e:
1396
+ log.info("AOTAutograd cache unable to serialize compiled graph: %s", e)
1397
+ if remote:
1398
+ log_cache_bypass(
1399
+ "bypass_aot_autograd", "Unable to serialize: " + str(e)
1400
+ )
1401
+ if config.strict_autograd_cache:
1402
+ raise e
1403
+ return None
1404
+
1405
+ if remote:
1406
+ remote_cache: Optional[RemoteCache[JsonDataTy]] = (
1407
+ AOTAutogradCache.get_remote_cache()
1408
+ )
1409
+ if remote_cache is not None:
1410
+ time_taken_ms = int(
1411
+ (entry.forward_time_taken_ns + entry.backward_time_taken_ns) // 1e6
1412
+ )
1413
+ cache_data: JsonDataTy = {
1414
+ "data": base64.b64encode(content).decode("ascii"),
1415
+ "time_taken_ms": time_taken_ms,
1416
+ }
1417
+ remote_cache.put(key, cache_data)
1418
+
1419
+ @staticmethod
1420
+ @functools.cache
1421
+ def get_remote_cache() -> Optional[RemoteCache[JsonDataTy]]:
1422
+ """
1423
+ Attempts to load the remote cache, returns None on error.
1424
+ """
1425
+ cache_id = "autograd-experimental"
1426
+ return create_cache(
1427
+ cache_id,
1428
+ config.is_fbcode(),
1429
+ "FbRemoteAOTAutogradCache",
1430
+ "RemoteAOTAutogradCache",
1431
+ )
1432
+
1433
+ @staticmethod
1434
+ def make_entry(
1435
+ compiled_fw_func: CompiledFxGraph,
1436
+ compiled_bw_func: Optional[CompiledFxGraph],
1437
+ aot_joint_graph_str: Optional[str],
1438
+ aot_forward_graph_str: Optional[str],
1439
+ aot_backward_graph_str: Optional[str],
1440
+ runtime_metadata: ViewAndMutationMeta,
1441
+ dispatch_wrappers: list[CompilerWrapper],
1442
+ maybe_subclass_meta: Optional[SubclassMeta],
1443
+ num_fw_outs_saved_for_bw: Optional[int],
1444
+ indices_of_inps_to_detach: list[int],
1445
+ forward_time_taken_ns: int,
1446
+ backward_time_taken_ns: int,
1447
+ sanitized_aot_config: AOTConfig,
1448
+ guards_expr: Optional[str],
1449
+ backward_state_indices: Optional[list[int]],
1450
+ num_symints_saved_for_bw: Optional[int],
1451
+ serialized_bw_module: Optional[SerializedGraphModule],
1452
+ ) -> GenericAOTAutogradCacheEntry:
1453
+ if should_bundle_autograd_cache():
1454
+ # Helper function to unwrap all the wrappers we added during aotdispatch
1455
+ # They get reapplied on cache load
1456
+ def unwrap_compiled_fx_graph(obj):
1457
+ while hasattr(obj, "__wrapped__"):
1458
+ obj = obj.__wrapped__
1459
+ assert isinstance(obj, CompiledFxGraph)
1460
+ return obj
1461
+
1462
+ compiled_fw_graph = unwrap_compiled_fx_graph(compiled_fw_func)
1463
+ bundled_compiled_forward = BundledCompiledForward(compiled_fw_graph)
1464
+ bundled_compiled_backward = None
1465
+ if compiled_bw_func is not None:
1466
+ assert backward_state_indices is not None
1467
+ assert num_symints_saved_for_bw is not None
1468
+ compiled_bw_graph = unwrap_compiled_fx_graph(compiled_bw_func)
1469
+ bundled_compiled_backward = BundledCompiledBackward(
1470
+ compiled_bw_graph, backward_state_indices, num_symints_saved_for_bw
1471
+ )
1472
+
1473
+ return BundledAOTAutogradCacheEntry(
1474
+ compiled_fw=bundled_compiled_forward,
1475
+ compiled_bw=bundled_compiled_backward,
1476
+ aot_joint_graph_str=aot_joint_graph_str,
1477
+ aot_forward_graph_str=aot_forward_graph_str,
1478
+ aot_backward_graph_str=aot_backward_graph_str,
1479
+ runtime_metadata=runtime_metadata,
1480
+ dispatch_wrappers=dispatch_wrappers,
1481
+ maybe_subclass_meta=maybe_subclass_meta,
1482
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1483
+ indices_of_inps_to_detach=indices_of_inps_to_detach,
1484
+ forward_time_taken_ns=forward_time_taken_ns,
1485
+ backward_time_taken_ns=backward_time_taken_ns,
1486
+ sanitized_aot_config=sanitized_aot_config,
1487
+ guards_expr=guards_expr,
1488
+ serialized_bw_module=serialized_bw_module,
1489
+ )
1490
+
1491
+ else:
1492
+ fw_key = getattr(compiled_fw_func, "_fx_graph_cache_key", None)
1493
+ fw_debug_lines = getattr(
1494
+ compiled_fw_func, "_fx_graph_cache_debug_lines", []
1495
+ )
1496
+
1497
+ assert fw_key is not None
1498
+ compiled_forward = CompiledForward(
1499
+ fx_graph_cache_info=(fw_key, fw_debug_lines),
1500
+ fx_graph_guard_expr=getattr(compiled_fw_func, "guards_expr", None),
1501
+ )
1502
+ compiled_backward = None
1503
+ if compiled_bw_func is not None:
1504
+ bw_key = getattr(compiled_bw_func, "_fx_graph_cache_key", None)
1505
+ bw_debug_lines = getattr(
1506
+ compiled_bw_func, "_fx_graph_cache_debug_lines", []
1507
+ )
1508
+ assert bw_key is not None
1509
+ assert backward_state_indices is not None
1510
+ assert num_symints_saved_for_bw is not None
1511
+ compiled_backward = CompiledBackward(
1512
+ fx_graph_cache_info=(bw_key, bw_debug_lines),
1513
+ fx_graph_guard_expr=getattr(compiled_bw_func, "guards_expr", None),
1514
+ backward_state_indices=backward_state_indices,
1515
+ num_symints_saved_for_bw_=num_symints_saved_for_bw,
1516
+ )
1517
+
1518
+ return AOTAutogradCacheEntry(
1519
+ compiled_fw=compiled_forward,
1520
+ compiled_bw=compiled_backward,
1521
+ aot_joint_graph_str=aot_joint_graph_str,
1522
+ aot_forward_graph_str=aot_forward_graph_str,
1523
+ aot_backward_graph_str=aot_backward_graph_str,
1524
+ runtime_metadata=runtime_metadata,
1525
+ dispatch_wrappers=dispatch_wrappers,
1526
+ maybe_subclass_meta=maybe_subclass_meta,
1527
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1528
+ indices_of_inps_to_detach=indices_of_inps_to_detach,
1529
+ forward_time_taken_ns=forward_time_taken_ns,
1530
+ backward_time_taken_ns=backward_time_taken_ns,
1531
+ sanitized_aot_config=sanitized_aot_config,
1532
+ guards_expr=guards_expr,
1533
+ serialized_bw_module=serialized_bw_module,
1534
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Callable, Optional
15
+
16
+ import torch
17
+ import torch.utils._pytree as pytree
18
+ from torch import Tensor
19
+ from torch._guards import detect_fake_mode
20
+ from torch._logging import getArtifactLogger
21
+ from torch._subclasses.functional_tensor import FunctionalTensor, FunctionalTensorMode
22
+ from torch._subclasses.meta_utils import safe_is_leaf
23
+ from torch.fx.experimental.symbolic_shapes import is_concrete_int
24
+ from torch.multiprocessing.reductions import StorageWeakRef
25
+ from torch.utils._python_dispatch import (
26
+ is_traceable_wrapper_subclass,
27
+ transform_subclass,
28
+ )
29
+
30
+ from .descriptors import (
31
+ AOTInput,
32
+ AOTOutput,
33
+ InputMutationAOTOutput,
34
+ IntermediateBaseAOTOutput,
35
+ PlainAOTOutput,
36
+ TangentAOTInput,
37
+ )
38
+ from .functional_utils import (
39
+ are_all_mutations_hidden_from_autograd,
40
+ are_all_mutations_under_no_grad_or_inference_mode,
41
+ from_fun,
42
+ has_data_mutation,
43
+ has_metadata_mutation,
44
+ MetadataKey,
45
+ to_fun,
46
+ ViewMetaSequence,
47
+ was_inductor_storage_resized,
48
+ )
49
+ from .schemas import (
50
+ InputAliasInfo,
51
+ MemoryFormatMeta,
52
+ MutationType,
53
+ OutputAliasInfo,
54
+ OutputType,
55
+ ViewAndMutationMeta,
56
+ )
57
+ from .subclass_utils import create_subclass_meta
58
+ from .utils import _get_autocast_states, KNOWN_TYPES, simple_wraps, strict_zip
59
+
60
+
61
+ zip = strict_zip
62
+
63
+ log = logging.getLogger(__name__)
64
+ static_input_logger = getArtifactLogger("torch._dynamo", "cudagraph_static_inputs")
65
+
66
+
67
+ # Note [Tangents memory format]
68
+ # We assume tangents memory format to be similar to corresponding output's memory_format.
69
+ # The idea is that we are technically making a guess about the strides of our tangents,
70
+ # while we trace out the joint.
71
+ # If runtime specified tangents will not have the same memory format as predicted traced tangents,
72
+ # we coerce them at runtime to traced tangents memory format.
73
+
74
+
75
+ # Coercing and collecting traced tangents memory format in one recursive traversal
76
+ # mypy: ignore-errors
77
+ def coerce_tangent_and_suggest_memory_format(x: Tensor):
78
+ updated = False
79
+ if not isinstance(x, Tensor):
80
+ return x, None, updated
81
+
82
+ out = x.detach()
83
+
84
+ is_subclass = is_traceable_wrapper_subclass(out)
85
+
86
+ memory_format = MemoryFormatMeta.from_tensor(out)
87
+
88
+ if memory_format.memory_format is not None:
89
+ was = out
90
+ out = out.contiguous(memory_format=memory_format.memory_format)
91
+ updated = was is not out
92
+
93
+ # For subclass we keep memory format of outer strides at the beginning of the list
94
+ out_memory_format = [memory_format] if is_subclass else memory_format
95
+
96
+ # Note [Tangents memory format, Part 2]
97
+ # In the same way that "what strides do we assigns to our tangents" is a question
98
+ # that we can not answer (and therefore have to guess) as we trace the backward ahead-of-time,
99
+ # The same applies to any tensor subclass metadata, when we have tangents that are subclasses.
100
+ # To handle this situation, we have two new methods that a tensor subclass can implement:
101
+ # (1) __coerce_tangent_metadata__(self)
102
+ # Given a subclass with "non-standard" metadata, turn it into a new subclass with "normal" metadata.
103
+ # The main example here is a DTensor with the "_Partial" placement.
104
+ # If we have a forward output with a _Partial placement, and corresponding tangent
105
+ # with a Replicate/Shard placement, we have no way to convert the tangent "back" to a _Partial placement.
106
+ # This method lets us avoid the problem entirely by allowing subclasses to ensure that we can never
107
+ # have a tangent with "problematic" metadata, that we cannot convert to.
108
+ # (1) __coerce_same_metadata_as_tangent__(self, metadata)
109
+ # Given a subclass, and a target differing metadata,
110
+ # convert self to have the same metadata as the target.
111
+ # With DTensor being the main example, we can use this to convert a DTensor with a Replicate()
112
+ # placement into one with a Shard() placement, in the case that we "guessed wrong",
113
+ # and traced tangents with a Shard() placement at compile time.
114
+ #
115
+ if is_subclass and hasattr(out, "__coerce_tangent_metadata__"):
116
+ out = out.__coerce_tangent_metadata__() # type: ignore[attr-defined]
117
+
118
+ if is_subclass:
119
+ attrs = out.__tensor_flatten__()[0]
120
+
121
+ for attr in attrs:
122
+ elem = getattr(out, attr)
123
+ (
124
+ new_elem,
125
+ new_elem_memory_format,
126
+ elem_updated,
127
+ ) = coerce_tangent_and_suggest_memory_format(elem)
128
+ out_memory_format.append(new_elem_memory_format)
129
+ if elem_updated:
130
+ setattr(out, attr, new_elem)
131
+
132
+ return out, out_memory_format, updated
133
+
134
+
135
+ # This is a version of functionalization that is specifically designed
136
+ # for the AOTAutograd use case.
137
+ #
138
+ # Unlike functorch's variant, this doesn't use the functorch level system,
139
+ # instead it directly uses PyTorch's conventional dispatcher to hit the
140
+ # functionalization key. In particular, this means that FunctionalTensorWrapper
141
+ # can have autograd data stored directly on it.
142
+ #
143
+ # In typical AOTAutograd usage, the dispatch key order will look like:
144
+ #
145
+ # Autograd - Functionalization ~~~~> Proxy Mode - Fake Tensor
146
+ # outer tensor inner tensor
147
+ #
148
+ # Returns:
149
+ # - ViewAndMutationMeta, telling us metadata about the inputs and outputs, and
150
+ # The list of outputs from the forward, but **only** the outputs that we need
151
+ # to pass in as tangents into the backward.
152
+ # Specifically, aliased outputs from the forward get regenerated, and don't participate
153
+ # in the compiled backward function.
154
+ def run_functionalized_fw_and_collect_metadata(
155
+ f,
156
+ *,
157
+ flat_args_descs: list[AOTInput],
158
+ keep_input_mutations: bool,
159
+ # TODO: refactor to kill this flag
160
+ is_train: bool = False,
161
+ # Note: this is guaranteed to be set when running under dynamo
162
+ static_input_indices: Optional[list[int]] = None,
163
+ pre_dispatch: bool = False,
164
+ # is_export is technically only needed to avoid using functionalization V2
165
+ # during analysis
166
+ is_export: bool = False,
167
+ ) -> Callable[..., ViewAndMutationMeta]:
168
+ memo: dict[Tensor, Tensor] = {}
169
+
170
+ def _to_fun(t):
171
+ if isinstance(t, Tensor):
172
+ if t in memo:
173
+ return memo[t]
174
+ r = to_fun(t)
175
+ memo[t] = r
176
+ return r
177
+ else:
178
+ return t
179
+
180
+ @simple_wraps(f)
181
+ def inner(*flat_args):
182
+ # This function is meant to be run with the forward, which expects a flat list of tensor/symint/other args.
183
+ assert all(isinstance(a, tuple(KNOWN_TYPES)) for a in flat_args)
184
+
185
+ input_info: list[InputAliasInfo] = []
186
+ output_info: list[OutputAliasInfo] = []
187
+
188
+ prior_grad_enabled = torch.is_grad_enabled()
189
+ prior_autocast_states = _get_autocast_states()
190
+
191
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
192
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
193
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
194
+ )
195
+
196
+ # It doesn't matter if we run this under predispatch or not because it is
197
+ # only for figuring out metadata
198
+ mode = FunctionalTensorMode(_allow_token_discovery=True, export=is_export)
199
+ suppress_pending = contextlib.nullcontext()
200
+ fake_mode = detect_fake_mode()
201
+ if fake_mode and (shape_env := fake_mode.shape_env):
202
+ suppress_pending = shape_env.ignore_fresh_unbacked_symbols()
203
+ with disable_above, mode, suppress_pending:
204
+ # precondition: The passed in function already handles unflattening inputs + flattening outputs
205
+ flat_f_args = pytree.tree_map(_to_fun, flat_args)
206
+ flat_f_args_descs = flat_args_descs
207
+ flat_f_outs = f(*flat_f_args)
208
+
209
+ # Assert that f does NOT have an AOTOutputs in it, easy mistake to
210
+ # make! You need to drop the second output before calling this
211
+ # function
212
+ assert not pytree.tree_any(
213
+ lambda x: isinstance(x, AOTOutput), flat_f_outs
214
+ ), (
215
+ f"{f} returned AOTOutput when it shouldn't. Did you remember to wrap the "
216
+ "function with without_output_descs before passing it here?"
217
+ )
218
+
219
+ # NB: this is just to setup the input descriptors, we will
220
+ # recreate these descriptors (with the same convention!) when we
221
+ # actually do the trace
222
+ flat_f_outs_descs = [PlainAOTOutput(i) for i in range(len(flat_f_outs))]
223
+
224
+ # We didn't do any tracing, so we don't need to process the
225
+ # unbacked symbols, they will just disappear into the ether.
226
+ # Also, prevent memoization from applying.
227
+ if fake_mode:
228
+ fake_mode.epoch += 1
229
+ fake_mode.reset_nt_tensor_id_counter()
230
+
231
+ if prior_autocast_states != _get_autocast_states():
232
+ raise RuntimeError(
233
+ "AOTAutograd does not support tracing graphs that mutate the autocast state. "
234
+ "Dynamo will only insert autocast context managers (e.g. with torch.autocast(..)) into the graph, "
235
+ "which will unwind all of their mutations to autocast state before the graph exits. "
236
+ "If you encounter this error while using torch.compile, please file a bug."
237
+ )
238
+
239
+ # Inspect the state of the input tensor functional wrapper to detect input mutation info
240
+ # If inp[i] has a metadata-only mutation, then maybe_inputs_with_mutated_metadata[i] contains the updated version
241
+ for i, (arg, f_arg) in enumerate(zip(flat_args, flat_f_args)):
242
+ # NB: Mutation of non-contiguous tensor subclass input can result in a mismatch in
243
+ # strides between the functionalized arg inner tensors and non-functionalized arg inner
244
+ # tensors. This is a problem as the inner tensor stride change may not be reflected
245
+ # correctly in the outer tensor, so disallow this for now.
246
+ mutates_data = has_data_mutation(f_arg)
247
+ mutates_metadata = has_metadata_mutation(
248
+ f_arg, arg, check_only_storage_mutation=False
249
+ )
250
+ if mutates_metadata and is_traceable_wrapper_subclass(arg):
251
+ raise RuntimeError(
252
+ "Metadata mutations are currently not allowed on tensor subclasses"
253
+ )
254
+ mutates_storage_metadata = has_metadata_mutation(
255
+ f_arg, arg, check_only_storage_mutation=True
256
+ )
257
+ mutations_hidden_from_autograd = are_all_mutations_hidden_from_autograd(
258
+ f_arg
259
+ )
260
+ mutations_under_no_grad_or_inference_mode = (
261
+ mutates_data
262
+ and are_all_mutations_under_no_grad_or_inference_mode(f_arg)
263
+ )
264
+ mutation_inductor_storage_resize = was_inductor_storage_resized(f_arg)
265
+
266
+ if mutates_storage_metadata:
267
+ mutates_data = False
268
+
269
+ requires_grad = isinstance(f_arg, torch.Tensor) and f_arg.requires_grad
270
+
271
+ input_info.append(
272
+ InputAliasInfo(
273
+ is_leaf=isinstance(arg, Tensor) and safe_is_leaf(arg),
274
+ mutates_data=mutates_data,
275
+ mutates_metadata=mutates_metadata,
276
+ mutations_hidden_from_autograd=mutations_hidden_from_autograd,
277
+ mutates_storage_metadata=mutates_storage_metadata,
278
+ mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode,
279
+ mutation_inductor_storage_resize=mutation_inductor_storage_resize,
280
+ requires_grad=requires_grad,
281
+ keep_input_mutations=keep_input_mutations,
282
+ )
283
+ )
284
+
285
+ # If a function involves creating a tensor, and returning a view of it, such that its _base is the intermediate,
286
+ # We need to make sure our graph returns the _base as a graph output, and we manually recreate the view
287
+ # to return to the user. Why? The backend compiler is free to (incorrectly) not set requires_grad
288
+ # on the base tensor, but we are obligated to properly set requires-gradness on the real output.
289
+
290
+ inp_storage_refs = {
291
+ StorageWeakRef(inpt.untyped_storage()): idx
292
+ for idx, inpt in enumerate(flat_f_args)
293
+ if isinstance(inpt, Tensor)
294
+ }
295
+
296
+ # We need inp tensor id's to be able to tell if an outputs **are** inputs.
297
+ inp_tensor_ids = {id(inpt) for inpt in flat_f_args if isinstance(inpt, Tensor)}
298
+ # We need output tensor id's to tell if any output._base` attributes **are** other outputs.
299
+ # (This is also a dict because we need to know that output's index, so we can regenerate
300
+ # the alias from it).
301
+ out_tensor_ids = {id(o): i for i, o in enumerate(flat_f_outs)}
302
+
303
+ # Keep track of which outputs alias other outputs
304
+ out_tensor_alias_counts: collections.defaultdict = collections.defaultdict(int)
305
+ # This tells us, for a given group of outputs that alias each other,
306
+ # whether they e.g. all came from an unbind call
307
+ num_aliased_tensors_that_are_multi_output_views: collections.defaultdict = (
308
+ collections.defaultdict(int)
309
+ )
310
+
311
+ out_storage_to_metadata_key_to_tensors: collections.defaultdict[
312
+ Optional[StorageWeakRef],
313
+ collections.defaultdict[MetadataKey, set[torch.Tensor]],
314
+ ] = collections.defaultdict(lambda: collections.defaultdict(set))
315
+
316
+ curr_storage = None
317
+ for o in flat_f_outs:
318
+ if isinstance(o, torch.Tensor):
319
+ curr_storage = StorageWeakRef(o.untyped_storage())
320
+ out_tensor_alias_counts[curr_storage] += 1
321
+ # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
322
+ # This is an optimization on top of the "alias of intermediates" logic,
323
+ # which you can read more about under Note [AOT Autograd: outputs aliasing inputs or intermediates!]
324
+ #
325
+ # Before describing the optimization: this is important for AOTAutograd to have good
326
+ # perf around, multi-output views. HOWEVER:
327
+ # - There is a more generic change to AOTAutograd that we'd like to make, that subsumes this case,
328
+ # around using pre-dispatch tracing to partition out a graph so we can faithfully replay all
329
+ # views without having to regenerate them at runtime.
330
+ # - It's loosely described in this doc (more details will be added soon):
331
+ # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit
332
+ # - Once that change lands, we should just rip out this "optimization", since:
333
+ # (1) It will be fully unnecessary
334
+ # (2) Although it is only a few lines of code, it is a bit difficult to reason about
335
+ # its correctness with the autograd engine in all cases.
336
+ #
337
+ #
338
+ # What is this optimization? Consider the below case:
339
+ # def f(x):
340
+ # intermediate = x.mul(2)
341
+ # # x and intermediate here require grad
342
+ # o1, o2, ... o10 = intermediate.unbind(-1)
343
+ # return intermediate, o1, o2, ... o10
344
+ # Now, the "intermediate base" handling in AOTAutograd implies that we must do the following:
345
+ # (1) return "intermediate as an extra output of the compiled graph
346
+ # (2) regenerate each aliased output off of "intermediate", **outside** of the autograd.Function.
347
+ # The reason AOTAutograd ordinarily does this is for safety: the autograd engine needs to know
348
+ # that o1 through o10 are all aliased, and if we blindly return o1 through o10 from the autograd.Function,
349
+ # this information will be hidden.
350
+ # In particular, mutating one alias might require autograd to update autograd metadata on the other aliases
351
+ # (like their grad_fn, for example, when the autograd engine needs to do view-replay).
352
+ #
353
+ # However, intermediate_base logic can be bad for backward performance (we sometimes generate
354
+ # as_strided calls during the intermediate base logic, which can have a slow backward formula).
355
+ # Is it possible to find a set of conditions where it is **safe** to hide the output aliasing from autograd?
356
+ #
357
+ # For a set of outputs of the graph that alias each other, o_1...o_k, consider:
358
+ # (1) They came from the same multi-output view op, e.g. o_1, ..., o_k = intermediate.unbind(0)
359
+ # (2) If there are any other aliases of o_1 through o_k (in the example above, intermediate),
360
+ # **at most** 1 can escape from the graph (e.g. there is not some other graph input/output
361
+ # o_other, that aliases these outputs)
362
+ # (3) o_1...o_k all require_grad, they all share the same ._base, and their ._base requires grad.
363
+ # This condition is important because it's what causes slowness in the intermediate_base
364
+ # codepath of aot_autograd. Ordinarily, o_1...o_k would all get a grad_fn, and
365
+ # aot_autograd's view-replay might give each output an AsStridedBackward as its grad_fn.
366
+ # "K" AsStridedBackward calls will be *much* slower than a single UnbindBackward.
367
+ # In this setup, is it possible to mutate one of the outputs o_i in a way that would affect the autograd meta
368
+ # of the other aliases?
369
+ #
370
+ # Claim: No! Consider a few example (which I'm pretty sure cover all cases of mutation w.r.t. autograd):
371
+ # (a) What happens if we mutate any of o_1 through o_k directly?
372
+ # Autograd raises an error:
373
+ # "RuntimeError: Output 0 of UnbindBackward0 is a view and is being modified inplace. This view is
374
+ # the output of a function that returns multiple views. Such functions do not allow the output
375
+ # views to be modified inplace. You should replace the inplace operation by an out-of-place one."
376
+ # (b) What if we take a view of o_k and mutate it, o_k.view(o_k.shape).mul_(2)?
377
+ # Autograd raises the same error- the "multi-output-view"ness of an alias propagates to future views.
378
+ # (c) What if we mutate o_k under no_grad?
379
+ # Autograd raises the same error
380
+ # (d) What if we detach and mutate, e.g. o_k.detach().mul_(2)?
381
+ # Autograd allows this, *but* autograd updates all alias's grad_fn's to be error functions when accessed.
382
+ # Autograd raises the same error
383
+ # (e) What if we try to mutate another alias of o_1...o_k, that was **not** created from a multi-output view?
384
+ # We promised that there is at most **one** such alias, e.g. intermediate in the example above.
385
+ # You can mutate intermediate, but in eager mode this will change the grad_fn of o_1...o_k
386
+ # to be error fn's.
387
+ # Since intermediate was the *only* non-multi-output-alias, there are no other aliases
388
+ # of `intermediate` around that were produced by the compiled fn and have a valid grad_fn.
389
+ #
390
+ # Coming back to this optimization:
391
+ # Given that it is not possible for mutating one of these aliases to affect the autograd metadata of another alias
392
+ # without causing an error in eager mode, we will simple hide the aliasing from autograd during torch.compile
393
+ # if all of the above conditions are met.
394
+ # This has the slight downside that it's possible to write some "bad" code that autograd will raise an error on
395
+ # in eager but fail to during torch.compile, but it has the benefit that this code has much better performance.
396
+ # NOTE: if and when we eventually update AOTAutograd to do the "view graph slicing" defined here:
397
+ # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit,
398
+ # then this optimization will probably matter less and might be ok to remove.
399
+ is_cur_tensor_multi_out_view = isinstance(
400
+ o, FunctionalTensor
401
+ ) and torch._functionalize_is_multi_output_view( # type: ignore[attr-defined]
402
+ o.elem
403
+ )
404
+ if is_cur_tensor_multi_out_view:
405
+ num_aliased_tensors_that_are_multi_output_views[curr_storage] += 1
406
+ if o.requires_grad:
407
+ out_storage_to_metadata_key_to_tensors[curr_storage][
408
+ MetadataKey.make(o)
409
+ ].add(o)
410
+
411
+ # maps the id of an intermediate base to its index in the output of the compiled forward
412
+ intermediate_base_tensor_id_to_output_idx: dict[int, int] = {}
413
+ intermediate_bases: list[torch.Tensor] = []
414
+ intermediate_bases_descs: list[AOTInput] = []
415
+ # Why Do We Care If Storage Changed?
416
+ # It's important to understand the implications of storage changes in complex scenarios. Take this example:
417
+ #
418
+ # def f(x):
419
+ # x_storage = x.untyped_storage()
420
+ # non_leaf_tensor = torch.ones(4, requires_grad=True).clone()
421
+ #
422
+ # # Using no_grad() and _unsafe_preserve_version_counter to simulate the .data = operation
423
+ # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x):
424
+ # x.set_(non_leaf_tensor.untyped_storage())
425
+ #
426
+ # out = x.view(-1)
427
+ #
428
+ # # Restoring x to its original storage, again simulating .data = operation
429
+ # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x):
430
+ # x.set_(x_storage)
431
+ #
432
+ # return out
433
+ #
434
+ # In this scenario, 'x' and 'out' have different shapes and are stored at different memory addresses, aka no aliasing.
435
+ # However, due to how set_() and more specificlaly, set is functionalized, is defined to preserve eager semantics,
436
+ # the autograd engine mistakenly assumes that 'x' and 'out' are aliased, treating 'x' as 'out._base'.
437
+ # This misinterpretation leads to an 'alias_of_input' flag, causing an unnecessary as_strided() call to be generated,
438
+ # which could lead to issues later in the code.
439
+ for o, desc in zip(flat_f_outs, flat_f_outs_descs):
440
+ functional_tensor_storage_changed = isinstance(
441
+ o, FunctionalTensor
442
+ ) and torch._functionalize_was_storage_changed( # type: ignore[attr-defined]
443
+ o.elem
444
+ )
445
+ curr_storage = (
446
+ None
447
+ if not isinstance(o, torch.Tensor)
448
+ else StorageWeakRef(o.untyped_storage())
449
+ )
450
+ outs_with_identical_metadata_that_require_grad = (
451
+ []
452
+ if not isinstance(o, Tensor)
453
+ else [
454
+ curr
455
+ for curr in out_storage_to_metadata_key_to_tensors[curr_storage][
456
+ MetadataKey.make(o)
457
+ ]
458
+ if o is not curr
459
+ ]
460
+ )
461
+
462
+ # See Note [Accessing .grad_fn on FunctionalTensor]
463
+ # In-place operations on views will trigger a lazy rebase of the autograd graph;
464
+ # this runs during access to the .grad_fn. The rebase logic will invoke view ops
465
+ # on FunctionalTensors, so we must enable a FunctionalTensorMode here to ensure
466
+ # these op calls succeed.
467
+ grad_fn = None
468
+ if isinstance(o, Tensor):
469
+ with FunctionalTensorMode():
470
+ grad_fn = o.grad_fn
471
+
472
+ is_result_of_custom_autograd_fn = False
473
+ # Need to check for both custom cpp (CppFunction) and python (BackwardCFunction)
474
+ # autograd fns
475
+ if type(grad_fn).__name__ == "CppFunction":
476
+ is_result_of_custom_autograd_fn = True
477
+ if isinstance(grad_fn, torch.autograd.function.BackwardCFunction):
478
+ is_result_of_custom_autograd_fn = True
479
+
480
+ if not isinstance(o, Tensor):
481
+ output_type = OutputType.non_alias
482
+ base_idx = None
483
+ elif (
484
+ curr_storage in inp_storage_refs
485
+ and grad_fn is not None
486
+ and is_result_of_custom_autograd_fn
487
+ ):
488
+ output_type = OutputType.custom_function_view
489
+ base_idx = None
490
+ elif (
491
+ curr_storage in inp_storage_refs
492
+ and not functional_tensor_storage_changed
493
+ ):
494
+ base_idx = inp_storage_refs[curr_storage]
495
+ is_input_tensor = id(o) in inp_tensor_ids
496
+ num_aliased_outs = out_tensor_alias_counts[curr_storage]
497
+ num_multi_output_view_outs = (
498
+ num_aliased_tensors_that_are_multi_output_views[curr_storage]
499
+ )
500
+ num_aliased_outs_that_are_not_multi_output_views = (
501
+ num_aliased_outs - num_multi_output_view_outs
502
+ )
503
+ if (
504
+ grad_fn is not None
505
+ and num_aliased_outs_that_are_not_multi_output_views == 0
506
+ ):
507
+ # See Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
508
+ # In particular, given:
509
+ # def f(x):
510
+ # return list(x.unbind(0))
511
+ # The main reason we ordinarily try to regenerate these output aliases outside of the
512
+ # compiled autograd.Function is because if any of the outputs are later mutated,
513
+ # autograd needs to perform view-replay to regenerate them.
514
+ # However, autograd does not allow users to mutate multi-output views
515
+ # in any way that can change the autograd metadata of other aliases.
516
+ # So we hide this aliasing from autograd here.
517
+ log.debug(
518
+ "Encountered AOTAutograd case: differentiable outputs that \
519
+ alias each other from a multi-output view call"
520
+ )
521
+ output_type = OutputType.non_alias
522
+ elif is_input_tensor:
523
+ output_type = OutputType.is_input
524
+ else:
525
+ output_type = OutputType.alias_of_input
526
+ elif functional_tensor_storage_changed and id(o) in inp_tensor_ids:
527
+ # When there is a set_() on an input, we cannot rely on checking storages
528
+ # to detect if we are returning an input (since the inputs storage is different)
529
+ assert curr_storage is not None
530
+ base_idx = inp_storage_refs[curr_storage]
531
+ output_type = OutputType.is_input
532
+
533
+ # We only need to handle the intermediate base case when both
534
+ # the intermediate base and the output require gradients.
535
+ # See Note [AOT Autograd: outputs aliasing inputs or intermediates!]
536
+ elif o._base is not None and o.requires_grad and o._base.requires_grad:
537
+ num_aliased_outs = out_tensor_alias_counts[curr_storage]
538
+ num_multi_output_view_outs = (
539
+ num_aliased_tensors_that_are_multi_output_views[curr_storage]
540
+ )
541
+ num_aliased_outs_that_are_not_multi_output_views = (
542
+ num_aliased_outs - num_multi_output_view_outs
543
+ )
544
+ # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call]
545
+ if (
546
+ out_tensor_alias_counts[curr_storage] == 1
547
+ or num_aliased_outs_that_are_not_multi_output_views <= 1
548
+ ):
549
+ # Note [Intermediate Bases Optimization]
550
+ # Normally if we have an output that aliases an intermediate,
551
+ # we need to add the extra "intermediate base" logic further down
552
+ # to prevent autograd from yelling at us if the user later tries to
553
+ # mutate that output.
554
+ # However, the common case here is if we have an output that aliases an intermediate,
555
+ # but doesn't alias any other outputs.
556
+ # In that case, autograd shouldn't have to worry about the aliasing at all
557
+ # (if that output is mutated, there are no other live aliases for autograd to worry about).
558
+ # The "intermediate bases" can hurt inductor perf by forcing more variables to become outputs.
559
+ # So as an optimization, we won't do intermediate base handling in this case.
560
+ # Instead, we'll hide the aliasing from autograd using aten._unsafe_view().
561
+ if (
562
+ out_tensor_alias_counts[curr_storage] != 1
563
+ and num_aliased_outs_that_are_not_multi_output_views <= 1
564
+ ):
565
+ log.debug(
566
+ "Encountered AOTAutograd case: differentiable outputs that alias each other \
567
+ from a multi-output view call"
568
+ )
569
+ output_type = OutputType.unsafe_view_alias
570
+ base_idx = None
571
+ else:
572
+ # First, check if o's ._base is an existing output
573
+ maybe_existing_out_idx = out_tensor_ids.get(id(o._base), None)
574
+ if maybe_existing_out_idx is not None:
575
+ # Special case where the output is an alias of a graph intermediate, but that intermediate
576
+ # is itself also a user output.
577
+ output_type = (
578
+ OutputType.alias_of_intermediate_base_is_user_output
579
+ )
580
+ base_idx = maybe_existing_out_idx
581
+ else:
582
+ # Next, check if o's ._base is an intermediate base that we already returned
583
+ maybe_existing_base_output_idx = (
584
+ intermediate_base_tensor_id_to_output_idx.get(
585
+ id(o._base), None
586
+ )
587
+ )
588
+ if maybe_existing_base_output_idx is not None:
589
+ output_type = OutputType.alias_of_intermediate
590
+ base_idx = maybe_existing_base_output_idx
591
+ else:
592
+ # Otherwise, take o._base and explicitly return it as an output in the compiled graph
593
+ new_out_idx = len(intermediate_bases)
594
+ base_idx = new_out_idx
595
+ # Indicate to the logic later on (when we trace the joint)
596
+ # that this particular output should get it's ._base appended to the forward graph outputs
597
+ output_type = (
598
+ OutputType.alias_of_intermediate_save_as_output
599
+ )
600
+ intermediate_base_tensor_id_to_output_idx[id(o._base)] = (
601
+ new_out_idx
602
+ )
603
+ intermediate_bases.append(o._base)
604
+ # NB: The desc we picked here is guaranteed to be
605
+ # synchronized with the one in
606
+ # graph_capture_wrappers.py because we
607
+ # SPECIFICALLY notated this output as
608
+ # alias_of_intermediate_save_as_output
609
+ intermediate_bases_descs.append(
610
+ TangentAOTInput(IntermediateBaseAOTOutput(desc))
611
+ )
612
+ elif (
613
+ # See https://github.com/pytorch/pytorch/issues/100348 for this case.
614
+ # This protects against the specific case where a user fn returns (output, output.detach())
615
+ out_tensor_alias_counts[curr_storage] > 1
616
+ and len(outs_with_identical_metadata_that_require_grad) > 0
617
+ and not o.requires_grad
618
+ ):
619
+ # In theory we could use any of these tensors to regenerate the aliased outputs from,
620
+ # since they all alias each other and have identical metadata
621
+ out_alias = outs_with_identical_metadata_that_require_grad[0]
622
+ existing_out_idx = out_tensor_ids[id(out_alias)]
623
+ output_type = OutputType.alias_of_intermediate_base_is_user_output
624
+ base_idx = existing_out_idx
625
+ else:
626
+ output_type = OutputType.non_alias
627
+ base_idx = None
628
+
629
+ if isinstance(o, torch.Tensor):
630
+ dynamic_dims = {
631
+ i for i, s in enumerate(o.shape) if not is_concrete_int(s)
632
+ }
633
+ else:
634
+ dynamic_dims = None
635
+
636
+ # Save the current FunctionalTensor output.
637
+ #
638
+ # This will be used at runtime for reconstructing output views from
639
+ # their respective base tensors.
640
+ #
641
+ # The FunctionalTensor will be saved if one of the 2 conditions below
642
+ # is true:
643
+ view_meta_sequence = None
644
+ if (
645
+ # 1. If the output_type is either of:
646
+ # (i) alias_of_intermediate;
647
+ # (ii) alias_of_intermediate_save_as_output; or
648
+ # (iii) alias_of_intermediate_base_is_user_output.
649
+ #
650
+ # No need to worry about in-place view operations here, since
651
+ # this functionalization step elimitates mutations.
652
+ #
653
+ # i.e. we have access to the actual base tensor, before the
654
+ # in-place operation was applied.
655
+ output_type
656
+ in (
657
+ OutputType.alias_of_intermediate,
658
+ OutputType.alias_of_intermediate_save_as_output,
659
+ OutputType.alias_of_intermediate_base_is_user_output,
660
+ )
661
+ ) or (
662
+ # 2. If the output_type is alias_of_input, and no in-place view
663
+ # operationthe was run on the input (base tensor).
664
+ #
665
+ # In this case, we need to check for metadata mutation because
666
+ # the runtime explicitly reconstructs the inputs, before actually
667
+ # reconstructing the outputs. Due to in-place view operations, the
668
+ # fully reconstructed input may not be this output base tensor
669
+ # anymore.
670
+ output_type == OutputType.alias_of_input
671
+ and base_idx is not None
672
+ and not input_info[base_idx].mutates_metadata
673
+ ):
674
+ if isinstance(o, FunctionalTensor):
675
+ view_meta_sequence = ViewMetaSequence(o)
676
+
677
+ out_info = OutputAliasInfo(
678
+ output_type=output_type,
679
+ raw_type=type(o),
680
+ base_idx=base_idx,
681
+ dynamic_dims=dynamic_dims,
682
+ requires_grad=isinstance(o, torch.Tensor) and o.requires_grad,
683
+ view_meta_sequence=view_meta_sequence,
684
+ )
685
+ output_info.append(out_info)
686
+
687
+ # See Note [AOT Autograd: Views to avoid tangents aliasing inputs]
688
+ def view_avoid_dupes_with_primals(t):
689
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
690
+ return transform_subclass(
691
+ t, lambda _, inner_t: view_avoid_dupes_with_primals(inner_t)
692
+ )
693
+ if isinstance(t, Tensor):
694
+ return t.view(t.shape)
695
+ return t
696
+
697
+ # This analysis function returns *only* the outputs that are meant to be tangents to the backwards.
698
+ # Anything that aliases (inputs returned in the fw due to metadata mutations, or outputs that alias inputs/intermediates)
699
+ # are *regenerated* later, and not used directly in the autograd graph
700
+ def _plain_fake_tensor_like_subclass(x):
701
+ with detect_fake_mode():
702
+ return torch.empty(
703
+ x.shape, dtype=x.dtype, device=x.device, layout=x.layout
704
+ )
705
+
706
+ def _is_subclass_mutated_input_tangent_always_subclass(inp):
707
+ return (
708
+ isinstance(inp, torch.nested._internal.nested_tensor.NestedTensor)
709
+ or torch._functorch.config.disable_guess_zero_tangent_for_mutated_input_subclass
710
+ )
711
+
712
+ f_input_tangents_pairs = [
713
+ # Note: [AOTAutograd Tangent Subclassness for mutated inputs]
714
+ # Generally when creating tangents to trace with, we assume that tangents will have
715
+ # the same subclass-ness as their forward outs
716
+ # however: for tangents that correspond to input mutations, in practice it is more likely
717
+ # that these tangents will be plain tensors of zeros at runtime, so we tweak our guess
718
+ # to assume that these tangents should always be plaint tensors.
719
+ # Example:
720
+ # def f(x):
721
+ # x.mul_(2)
722
+ # return x + 1
723
+ # out = f(x)
724
+ # out.sum().backward()
725
+ # In the above code, we will have a tangent "x_updated_tangent",
726
+ # which will be a plain tensor of zeros, *unless* x is used in some compute after executing f
727
+ #
728
+ # However, there are exceptions to this logic. If a view is created from mutated input and is used in backward,
729
+ # The tangent for this subclass input will be a subclass tensor.
730
+ # Example:
731
+ # def f(a, b):
732
+ # a.mul_(2)
733
+ # b.mul_(3)
734
+ # return b.view(b.shape), a + b
735
+ # a_out, b_out = f(..., Subclass)
736
+ # (a * b).sum().backward()
737
+ #
738
+ # We can not deduce it easily now, so introducing a debug config to be able to turn off this for specific cases.
739
+ # NJT guarantees to have its tangent as NJT, because it has dedicated integration in Autograd
740
+ # See torch/csrc/autograd/python_function.cpp, use_zeros_like.
741
+ (
742
+ (
743
+ _plain_fake_tensor_like_subclass(inp)
744
+ if is_traceable_wrapper_subclass(inp)
745
+ and not _is_subclass_mutated_input_tangent_always_subclass(inp)
746
+ else inp
747
+ ),
748
+ TangentAOTInput(InputMutationAOTOutput(inp_desc)),
749
+ )
750
+ for inp, inp_desc, info in zip(flat_f_args, flat_f_args_descs, input_info)
751
+ if info.mutation_type == MutationType.MUTATED_OUT_GRAPH
752
+ and info.mutates_data
753
+ and info.requires_grad
754
+ ]
755
+ f_input_tangents, f_input_tangents_descs = (
756
+ [x[0] for x in f_input_tangents_pairs],
757
+ [x[1] for x in f_input_tangents_pairs],
758
+ )
759
+
760
+ f_output_tangents_pairs = [
761
+ (o, TangentAOTInput(desc))
762
+ for o, info, desc in zip(flat_f_outs, output_info, flat_f_outs_descs)
763
+ if info.output_type
764
+ in [
765
+ OutputType.non_alias,
766
+ OutputType.unsafe_view_alias,
767
+ OutputType.custom_function_view,
768
+ ]
769
+ and issubclass(info.raw_type, torch.Tensor)
770
+ and info.requires_grad
771
+ ]
772
+ f_output_tangents, f_output_tangents_descs = (
773
+ [x[0] for x in f_output_tangents_pairs],
774
+ [x[1] for x in f_output_tangents_pairs],
775
+ )
776
+
777
+ # intermediate bases are also included in the backward graph
778
+ f_tangents = f_input_tangents + f_output_tangents + intermediate_bases
779
+ f_tangents_descs = (
780
+ f_input_tangents_descs + f_output_tangents_descs + intermediate_bases_descs
781
+ )
782
+
783
+ # TODO: I'm pretty sure you don't need a tree_map here
784
+ traced_tangents = pytree.tree_map(from_fun, f_tangents)
785
+ traced_tangents = pytree.tree_map(
786
+ view_avoid_dupes_with_primals, traced_tangents
787
+ )
788
+ traced_tangents = [
789
+ coerce_tangent_and_suggest_memory_format(tt)[0]
790
+ for i, tt in enumerate(traced_tangents)
791
+ ]
792
+ # NB: update this if the maps above ever change structure.
793
+ # Also, it might be helpful to add coercion information to the tangent desc!
794
+ traced_tangents_descs = f_tangents_descs
795
+
796
+ nonlocal static_input_indices
797
+ static_input_indices = static_input_indices or []
798
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
799
+ passed_indices = set(static_input_indices)
800
+ static_input_indices = [
801
+ i
802
+ for i, arg in enumerate(flat_args)
803
+ if (isinstance(arg, torch.nn.Parameter) or i in passed_indices)
804
+ ]
805
+
806
+ static_input_logger.debug(
807
+ "static input indices metadata analysis: %s", static_input_indices
808
+ )
809
+
810
+ f_mutated_inputs = [
811
+ inp
812
+ for inp, info in zip(flat_f_args, input_info)
813
+ if info.mutation_type == MutationType.MUTATED_OUT_GRAPH
814
+ ]
815
+ f_metadata_mutated_inputs = [
816
+ inp for inp, info in zip(flat_f_args, input_info) if info.mutates_metadata
817
+ ]
818
+ # This logic (annoyingly) re-figures out exactly what the outputs to the compiled fw graph will be.
819
+ # When handling subclasses, we need info about **all** outputs of compiled forward graph,
820
+ # so we know precisely which graph outputs to wrap back into tensor subclasses
821
+ # Ideally we would refactor this so not have an is_train flag, and have the separate
822
+ # inference and training paths decide which inputs/output to ask for subclass info on.
823
+ # However, we currently stash indexing information on each SubclassMeta about its order
824
+ # in the graph outputs list.
825
+ f_fw_graph_outs = list(flat_f_outs)
826
+ if is_train or not keep_input_mutations:
827
+ f_fw_graph_outs = f_mutated_inputs + f_fw_graph_outs
828
+ else:
829
+ # even when "keep_input_mutations" is True,
830
+ # we never keep metadata-only mutations in the fw graph
831
+ f_fw_graph_outs = f_metadata_mutated_inputs + f_fw_graph_outs
832
+ if is_train:
833
+ f_fw_graph_outs = f_fw_graph_outs + intermediate_bases
834
+ fw_graph_outs = pytree.tree_map(from_fun, f_fw_graph_outs)
835
+
836
+ grad_enabled_mutation = None
837
+ if torch.is_grad_enabled() != prior_grad_enabled:
838
+ grad_enabled_mutation = torch.is_grad_enabled()
839
+ torch.set_grad_enabled(
840
+ prior_grad_enabled
841
+ ) # Restore the prior state after tracing it
842
+ log.debug(
843
+ (
844
+ "grad_mode mutation encountered in graph. "
845
+ "Will emit mutation epilogue, to set grad_mode=%s"
846
+ ),
847
+ grad_enabled_mutation,
848
+ )
849
+
850
+ metadata = ViewAndMutationMeta(
851
+ input_info=input_info,
852
+ output_info=output_info,
853
+ num_intermediate_bases=len(intermediate_bases),
854
+ keep_input_mutations=keep_input_mutations,
855
+ traced_tangents=traced_tangents,
856
+ traced_tangents_descs=traced_tangents_descs,
857
+ subclass_inp_meta=create_subclass_meta(flat_args),
858
+ subclass_fw_graph_out_meta=create_subclass_meta(fw_graph_outs),
859
+ subclass_tangent_meta=create_subclass_meta(
860
+ traced_tangents, count_symints=False, with_memory_format=True
861
+ ),
862
+ is_train=is_train,
863
+ grad_enabled_mutation=grad_enabled_mutation,
864
+ static_input_indices=static_input_indices,
865
+ tokens=mode._tokens,
866
+ )
867
+ return metadata
868
+
869
+ return inner
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/descriptors.py ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AOTAutograd descriptors are a path-like data structure (similar to pytree
3
+ paths and sources) that describe the semantic meaning of an input/output to FX
4
+ graphs. Although you may know the input/output meaning at the top level of
5
+ the original function you traced, because we have many graph capture wrappers
6
+ that change the calling convention, it can be difficult to tell how these
7
+ correspond to the actual FX graph you get back, to say nothing about the extra
8
+ arguments/outputs for tangents, gradients, etc. Descriptors describe the meaning
9
+ of arguments.
10
+
11
+ Examples
12
+ --------
13
+
14
+ Before we talk about the precise semantics, it's helpful to look at some
15
+ examples to get some intuition for the meaning of descriptors. Here are some
16
+ input descriptors you might find on the joint FX graph:
17
+
18
+ * PlainAOTInput(idx=0) - the first input from the original callable, as is
19
+
20
+ * ParamAOTInput(target="mod.weight") - the parameter with FQN mod.weight
21
+
22
+ * TangentAOTInput(output=PlainAOTOutput(idx=1)) - the input tangent
23
+ corresponding to the gradients for the second output in the forward graph
24
+
25
+ * ViewBaseAOTInput(base_of=PlainAOTInput(idx=0)) - it turned out the first
26
+ input was actually a (differentiable) view of a tensor which aliased with
27
+ another input tensor. We replaced this input with a single input for the
28
+ base of all of these inputs, replacing the original inputs (one of which is
29
+ mentioned in base_of). We would generate a GradAOTOutput for *this* input
30
+ (and not the original PlainAOTInputs!) If you have a joint graph where a
31
+ view base like this is undesirable, you can eliminate this by cloning
32
+ the views outside of the compiled region (assuming you aren't mutating this
33
+ tensor).
34
+
35
+ * SubclassGetAttrAOTInput(base=AOTInput(idx=0), attr="inner") - this tensor
36
+ corresponds to the "inner" tensor from the tensor subclass that is at the
37
+ first index. In general, joint graphs from AOTAutograd never take tensor
38
+ subclasses as inputs; they are always unpacked into their constituent plain
39
+ tensor pieces; use the descriptors to identify the parts of the tensor that
40
+ are related. Note that this can be nested (if you have nested tensor
41
+ subclasses!)
42
+
43
+ Here are some output descriptors you might find on the Joint FX graph:
44
+
45
+ * PlainAOTOutput(idx=0) - the first output from the original forward function,
46
+ as is
47
+
48
+ * GradAOTOutput(grad_of=PlainAOTInput(idx=1)) - the computed gradient for the
49
+ second input to the graph, an output of the backward graph
50
+
51
+ * InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=0)) - when the first
52
+ input is mutated, the new value to be copied into the first input of the
53
+ graph. Sometimes, these outputs can be elided and the ``copy_`` is done directly
54
+ in the graph (controlled by keep_input_mutations), but if the input
55
+ mutation must be differentiated through we always generate an output like this
56
+
57
+ * IntermediateBaseAOTOutput(base_of=PlainAOTOutput(idx=0)) - if we return
58
+ multiple outputs which alias each other, we instead replace them with a single
59
+ output tensor representing the base of all the aliases. This output indicates
60
+ it is the base for /one/ of those original outputs. If this is undesirable in
61
+ the joint graph, clone all outputs before returning from the graph.
62
+
63
+ * SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), idx="inner") - this
64
+ tensor correspondings to the inner tensor of the first original output which
65
+ is a tensor subclass. This and other subclass components of that output will
66
+ get repacked into a tensor subclass.
67
+
68
+ High level semantics
69
+ --------------------
70
+
71
+ OK, let's formally define a descriptor. Intuitively, suppose we have::
72
+
73
+ def wrapped_graph(*args):
74
+ ret = graph(*in_transform(args))
75
+ return out_transform(ret)
76
+
77
+ Then the descriptor for input[i] to graph describes a function fin_i such that::
78
+
79
+ fin_i(args) == in_transform(args)[i]
80
+
81
+ and the descriptor for output[j] from graph describes a function fout_j such that::
82
+
83
+ fout_j(out_transform(ret)) == ret[j]
84
+
85
+ AKA input descriptors tell you how to get from outer inputs to inner inputs,
86
+ while output descriptors tell you how to get from outer outputs to inner
87
+ outputs (inverse data flow!)
88
+
89
+ We haven't said anything about what these transformations actually do. There
90
+ are three major transformations AOTAutograd does (performed in this order):
91
+
92
+ * View/mutation handling
93
+ * Autograd
94
+ * Subclasses
95
+
96
+ So intuitively, descriptors are built like this:
97
+
98
+ 1. **PlainAOTInput, PlainAOTOutput.**
99
+
100
+ We start off descriptors describing the exact inputs/outputs of the
101
+ original flattened user function. This user function is assumed to already
102
+ be flattened; you would chain on pytree KeyPaths to further describe where
103
+ in the pytree each input/output lived if you needed to deal with
104
+ unflattened functions: this can be done from userland on top of
105
+ descriptors, so the main descriptors mechanism doesn't handle it.
106
+
107
+ 2. **SyntheticBaseAOTInput, ViewBaseAOTInput, MetadataMutationAOTOutput,
108
+ InputMutationAOTOutput, IntermediateBaseAOTOutput**
109
+
110
+ We deal with mutations and aliasing by removing duplicate PlainAOTInputs
111
+ and introduce some new artificial inputs/outputs. These inputs do not
112
+ have a straightforward correspondence to the original user inputs, but if
113
+ you are implementing a pass that doesn't care about the exact semantics of
114
+ inputs, you should handle all of these uniformly in the same way as regular
115
+ inputs.
116
+
117
+ 3. **TangentAOTInput, GradAOTOutput**
118
+
119
+ We deal with autograd by introducing a tangent input for every
120
+ differentiable AOTOutput (including the new ones introduced above), and a
121
+ gradient output for every differentiable AOTInput (also including new ones
122
+ introduced above.) The arguments to these AOTInput/AOTOutput can ONLY be
123
+ the ones we already have above (from steps 1-2). As AOTAutograd does not
124
+ currently support double backwards, you never have tangents of grads or
125
+ vice versa (but in the future we could!)
126
+
127
+ 4. **SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput, et al.**
128
+
129
+ We deal with subclasses by introducing flattened inputs/outputs (including
130
+ potentially symbolic sizes/strides) for every AOTInput/AOTOutput that was a
131
+ subclass. As above, the arguments to these AOTInput/AOTOutput can ONLY be
132
+ the ones we have above (from steps 1-3). Recursive subclasses are
133
+ supported, so these descriptors can nest with each other (so descriptors
134
+ from step 4 are fair game as well.)
135
+
136
+ 5. **ForwardTokenAOTInput, ForwardTokenAOTOutput, BackwardTokenAOTInput, BackwardTokenAOTOutput.**
137
+
138
+ Some extra token inputs/outputs get added, these are synthetic and are just here to
139
+ prevent DCE/reordering.
140
+
141
+ The important thing about the pipeline is that descriptors can ONLY be
142
+ created from top-to-bottom. So for example, you can have::
143
+
144
+ SubclassGetAttrAOTInput(TangentAOTInput(PlainAOTOutput(...))) # OK
145
+
146
+ As you can see that PlainAOTOutput -> TangentAOTInput ->
147
+ SubclassGetAttrAOTInput is consistent with the pipeline ordering), but you can
148
+ NEVER have::
149
+
150
+ TangentAOTInput(SubclassGetAttrAOTOutput(PlainAOTOutput(...)) # BAD
151
+
152
+ This is inconsistent; we always do autograd BEFORE we process subclasses!
153
+
154
+ Similarly, for example, this is illegal::
155
+
156
+ GradAOTOutput(SubclassGetAttrAOTInput(PlainAOTInput(...))) # BAD
157
+
158
+ It is illegal because subclasses are handled *after* create joint during
159
+ wrapper construction. Instead, you would have::
160
+
161
+ SubclassGetAttrAOTOutput(GradAOTOutput(PlainAOTInput(...))) # OK
162
+
163
+ This intuitively captures the fact that we always to autograd directly on the
164
+ subclass, rather than after desugaring the subclass into its inner tensors.
165
+
166
+ Descriptor index
167
+ ----------------
168
+
169
+ Here is a list of all AOTInput/AOTOutput, organized by how likely you need to
170
+ handle them:
171
+
172
+ * AOTInput
173
+
174
+ * Important:
175
+
176
+ * PlainAOTInput (the primals!)
177
+ * ParamAOTInput
178
+ * TangentAOTInput
179
+ * SubclassGetAttrAOTInput et al. (if you use subclasses)
180
+
181
+ * View related (can be eliminated by cloning inputs to graph; if you don't
182
+ eliminate them, make sure to handle pairing them with GradAOTOutput):
183
+
184
+ * ViewBaseAOTInput
185
+ * SyntheticBaseAOTInput
186
+
187
+ * Non-tensor, mostly just ignore them:
188
+
189
+ * DummyAOTInput
190
+ * PhiloxForwardSeedAOTInput
191
+ * PhiloxForwardBaseOffsetAOTInput
192
+ * PhiloxBackwardSeedAOTInput
193
+ * PhiloxBackwardBaseOffsetAOTInput
194
+ * ForwardTokenAOTInput
195
+ * BackwardTokenAOTInput
196
+
197
+ * AOTOutput
198
+
199
+ * Important:
200
+
201
+ * PlainAOTOutput
202
+ * GradAOTOutput
203
+ * SubclassGetAttrAOTOutput et al. (if you use subclasses)
204
+
205
+ * More obscure (if not eliminated, make sure you handle pairing them with
206
+ TangentAOTInput):
207
+
208
+ * InputMutationAOTOutput (can be eliminated if mutations are non-differentiable)
209
+ * IntermediateBaseAOTOutput (can be eliminated by cloning outputs of graph)
210
+ * MetadataMutationAOTOutput (uhh, just don't mutate metadata?)
211
+
212
+ * Non-tensor, mostly just ignore them:
213
+
214
+ * PhiloxUpdatedForwardOffsetAOTOutput
215
+ * PhiloxUpdatedBackwardOffsetAOTOutput
216
+ * ForwardTokenAOTOutput
217
+ * BackwardTokenAOTOutput
218
+ * DummyAOTOutput
219
+
220
+ For convenience, we also have DifferentiableAOTInput and
221
+ DifferentiableAOTOutput to help you classify which inputs/outputs can be
222
+ wrapped by GradAOTOutput/TangentAOTInput (respectively), which are essentially
223
+ all tensor AOTInput/AOTOutput excluding the subclass descriptors.
224
+
225
+ Implementation details
226
+ ----------------------
227
+
228
+ The stylized view above is good for understanding how to interpret
229
+ descriptors, but the way that descriptors are generated in code is a bit more
230
+ complicated. Specifically, AOTAutograd is structured as a series of wrappers
231
+ on the original user function, which are composed together to form the final
232
+ function to trace. As a result of this, AOTAutograd ends up first building
233
+ the full AOTInputs for a function to be traced (as it builds the wrappers and
234
+ modifies the flat arguments to be compatible with the new input signature of
235
+ the wrapper), and then in reverse builds up the AOTOutput as it is tracing.
236
+
237
+ There is one major exception to this general idea of "build AOTInput first",
238
+ and then "build AOTOutput second": when we create TangentAOTInput, we need to
239
+ reference AOTOutputs (which output we are the tangents of) which we generally
240
+ haven't created yet. There's two ways we deal with this:
241
+
242
+ - After the precompile steps (dedup and synthetic base handling), we do an
243
+ initial pass to collect forward metadata that produces the initial set of
244
+ PlainAOTOutputs which we use to create the tangent inputs.
245
+
246
+ - We also sometimes just violate causality and predict that an AOTOutput will
247
+ be created in a particular way at some later point in time when we build an
248
+ AOTInput.
249
+
250
+ As of July 2025, here is an exhaustive description of how inputs/outputs
251
+ traverse the wrappers from AOTAutograd, and what descriptors can be introduced
252
+ at these phases.
253
+
254
+ ::
255
+
256
+ Build wrappers (FLOWS DOWN) Run trace (FLOWS UP)
257
+ -------------------------------------------------------------------------------------------------
258
+ Begin PlainAOTInput (n/a)
259
+ ParamAOTInput
260
+
261
+ Precompile dedupe (remove dupes) (nothing)
262
+
263
+ Precompile synthetic base SyntheticBaseAOTInput MetadataMutationAOTOutput
264
+ ViewBaseAOTInput
265
+
266
+ Forward metadata trace PlainAOTOutput (n/a)
267
+ MetadataMutationAOTOutput
268
+
269
+ Prepare for autograd (nothing) InputMutationAOTOutput
270
+ IntermediateBaseAOTOutput
271
+
272
+ Create joint TangentAOTInput GradAOTOutput
273
+ w/ InputMutationAOTOutput
274
+ w/ IntermediateBaseAOTOutput
275
+
276
+ Precompile subclass SubclassGetAttrAOTInput et al. SubclassGetAttrAOTOutput et al.
277
+
278
+ Effect tokens ForwardTokenAOTInput ForwardTokenAOTOutput
279
+ BackwardTokenAOTInput BackwardTokenAOTOutput
280
+
281
+ End (n/a) PlainAOTOutput
282
+
283
+ It can be helpful to separately write down the input flow and the output flow
284
+ for ease of understanding the data flow:
285
+
286
+ * Input desc propagation (happens as we build wrappers)
287
+
288
+ * [IN] Begin with original calling convention (PlainAOTInput, ParamAOTInput)
289
+ * [IN] Precompile dedupe: (removes duplicate AOTInputs)
290
+ * [IN] Precompile synthetic base: SyntheticBaseAOTInput, ViewBaseAOTInput
291
+ * Forward metadata trace (mini output desc propagation)
292
+
293
+ * [OUT] Original output convention: PlainAOTOutput
294
+ * [OUT] Precompile synthetic base: MetadataMutationAOTOutput
295
+
296
+ * [IN] Prepare for autograd: (nothing)
297
+ * [IN] Create joint: TangentAOTInput (potentially w/
298
+ IntermediateBaseAOTOutput, InputMutationAOTOutput)
299
+ * [IN] Precompile subclass: SubclassGetAttrAOTInput et al.
300
+ * [IN] Effect tokens: ForwardTokenAOTInput, BackwardTokenAOTInput
301
+ (Note: BackwardTokenAOTInput is technically generated not by a wrapper but
302
+ actually done by token_discovery which implicitly adds extra arguments
303
+ to the FX trace on-the-fly.)
304
+
305
+ * Trigger a trace with the modified inputs on the wrapper
306
+ * Output desc propagation (happens as we unwind from the user function call in trace)
307
+
308
+ * [OUT] Begin with original calling convention: PlainAOTOutput
309
+ * [OUT] Effect tokens: ForwardTokenAOTOutput, BackwardTokenAOTOutput
310
+ * [OUT] Precompile subclass: SubclassGetAttrAOTOutput et al.
311
+ * [OUT] Create joint: GradAOTOutput
312
+ * [OUT] Prepare for autograd: InputMutationAOTOutput, IntermediateBaseAOTOutput
313
+ * [OUT] Precompile synthetic base: MetadataMutationAOTOutput
314
+ * [OUT] Precompile dedupe: (nothing)
315
+ """
316
+
317
+ import dataclasses
318
+
319
+
320
+ # TODO: the is_* predicates are a little suspicious because (1) they're not
321
+ # used by anything and (2) they always report False even when a parameter got
322
+ # swizzled into a view base or deduped with a non-parameter. It is pretty
323
+ # difficult to exercise these cases but it's not clear if you will write code
324
+ # that works correctly in those cases.
325
+
326
+
327
+ @dataclasses.dataclass(frozen=True)
328
+ class AOTInput:
329
+ """Describes where an input from an AOTAutograd produced FX graph comes from"""
330
+
331
+ def expr(self) -> str:
332
+ raise NotImplementedError("Subclasses must implement expr()")
333
+
334
+ def is_param(self) -> bool:
335
+ """True if this input is a parameter or derived from a parameter (e.g., subclass attr)"""
336
+ return False
337
+
338
+ def is_buffer(self) -> bool:
339
+ """True if this input is a buffer or derived from a buffer (e.g., subclass attr)"""
340
+ return False
341
+
342
+ def is_tangent(self) -> bool:
343
+ """True if this input is a tangent or derived from a tangent (e.g., subclass attr)"""
344
+ return False
345
+
346
+
347
+ # Note: Currently, our typing discipline for differentiable versus not is not
348
+ # very good, so feel free to rely on runtime tests instead.
349
+
350
+
351
+ @dataclasses.dataclass(frozen=True)
352
+ class DifferentiableAOTInput(AOTInput):
353
+ """A subclass that classifies AOTInput that can be wrapped by GradAOTOutput"""
354
+
355
+
356
+ @dataclasses.dataclass(frozen=True)
357
+ class AOTOutput:
358
+ """Describes where an output from an AOTAutograd produced FX graph will
359
+ eventually be bundled into the final output"""
360
+
361
+ def expr(self) -> str:
362
+ raise NotImplementedError("Subclasses must implement expr()")
363
+
364
+ def is_grad(self) -> bool:
365
+ """True if this output is a grad or derived from a grad (e.g., subclass attr)"""
366
+ return False
367
+
368
+
369
+ @dataclasses.dataclass(frozen=True)
370
+ class DifferentiableAOTOutput(AOTOutput):
371
+ """A subclass that classifies AOTOutput that can be wrapped by TangentAOTInput"""
372
+
373
+
374
+ # ------------
375
+
376
+ # AOTInput
377
+
378
+ # ------------
379
+
380
+
381
+ @dataclasses.dataclass(frozen=True)
382
+ class ParamAOTInput(DifferentiableAOTInput):
383
+ """The input is a parameter, whose FQN is target"""
384
+
385
+ target: str
386
+
387
+ def expr(self) -> str:
388
+ return f"self.get_parameter({self.target!r})"
389
+
390
+ def is_param(self) -> bool:
391
+ return True
392
+
393
+ def is_buffer(self) -> bool:
394
+ return False
395
+
396
+
397
+ @dataclasses.dataclass(frozen=True)
398
+ class BufferAOTInput(DifferentiableAOTInput):
399
+ """The input is a buffer, whose FQN is target"""
400
+
401
+ target: str
402
+
403
+ def expr(self) -> str:
404
+ return f"self.get_buffer({self.target!r})"
405
+
406
+ def is_param(self) -> bool:
407
+ return False
408
+
409
+ def is_buffer(self) -> bool:
410
+ return True
411
+
412
+
413
+ @dataclasses.dataclass(frozen=True)
414
+ class DummyAOTInput(AOTInput):
415
+ """In some circumstances, we want to call into a function that expects AOTInput, but
416
+ we don't actually care about that logic (most typically, because some code is being used
417
+ for both compile-time and run-time; AOTInput processing is not needed in this situation.
418
+ Pass a dummy in this situation; but it is better to just have a version of the function
419
+ that doesn't have this at all."""
420
+
421
+ idx: int
422
+
423
+ def expr(self) -> str:
424
+ return f"__dummy{self.idx}"
425
+
426
+
427
+ @dataclasses.dataclass(frozen=True)
428
+ class PlainAOTInput(DifferentiableAOTInput):
429
+ """The input is a plain input, corresponding to a particular positional index.
430
+
431
+ Note that AOTInput is always relative to a function with a *flat* calling convention,
432
+ e.g., as accepted by `aot_module_simplified`. There are some AOTAutograd APIs that
433
+ flatten pytrees, and we don't record PyTree key paths from the flattening (but we
434
+ could and should!)
435
+ """
436
+
437
+ idx: int
438
+
439
+ def expr(self) -> str:
440
+ return f"args[{self.idx}]"
441
+
442
+
443
+ @dataclasses.dataclass(frozen=True)
444
+ class SubclassGetAttrAOTInput(AOTInput):
445
+ """Subclass inputs get unpacked into their constituent pieces before going into an FX
446
+ graph. This tells you which particular attribute of the subclass this particular
447
+ input corresponds to (of the 'base' originally subclass argument.)
448
+ """
449
+
450
+ base: AOTInput
451
+ attr: str
452
+
453
+ def expr(self) -> str:
454
+ return f"{self.base.expr()}.{self.attr}"
455
+
456
+ def is_param(self) -> bool:
457
+ return self.base.is_param()
458
+
459
+ def is_buffer(self) -> bool:
460
+ return self.base.is_buffer()
461
+
462
+ def is_tangent(self) -> bool:
463
+ return self.base.is_tangent()
464
+
465
+
466
+ @dataclasses.dataclass(frozen=True)
467
+ class SubclassSizeAOTInput(AOTInput):
468
+ """Which subclass this particular outer size SymInt input (at dim idx) came from."""
469
+
470
+ base: AOTInput
471
+ idx: int
472
+
473
+ def expr(self) -> str:
474
+ return f"{self.base.expr()}.size({self.idx})"
475
+
476
+
477
+ @dataclasses.dataclass(frozen=True)
478
+ class SubclassStrideAOTInput(AOTInput):
479
+ """Which subclass this particular outer stride SymInt input (at dim idx) came from."""
480
+
481
+ base: AOTInput
482
+ idx: int
483
+
484
+ def expr(self) -> str:
485
+ return f"{self.base.expr()}.stride({self.idx})"
486
+
487
+
488
+ @dataclasses.dataclass(frozen=True)
489
+ class ViewBaseAOTInput(DifferentiableAOTInput):
490
+ """
491
+ When multiple differentiable inputs are views of the same input, AOTAutograd will replace all of these
492
+ views with a single input representing the base. If this is undesirable, you can clone the views
493
+ example inputs before passing them into AOTAutograd.
494
+
495
+ TODO: In principle we could report ALL of the inputs who this is a base of.
496
+ """
497
+
498
+ base_of: AOTInput
499
+
500
+ def expr(self) -> str:
501
+ return f"{self.base_of.expr()}._base"
502
+
503
+
504
+ @dataclasses.dataclass(frozen=True)
505
+ class SyntheticBaseAOTInput(DifferentiableAOTInput):
506
+ """This is similar to ViewBaseAOTInput, but this happens when none of the views were differentiable, so
507
+ we weren't able to get our hands on the true original view and constructed a synthetic one instead
508
+ for the sake of autograd.
509
+ """
510
+
511
+ base_of: AOTInput
512
+
513
+ def expr(self) -> str:
514
+ return f"__make_synthetic_base({self.base_of.expr()})"
515
+
516
+
517
+ @dataclasses.dataclass(frozen=True)
518
+ class PhiloxForwardSeedAOTInput(AOTInput):
519
+ """The seed for functionalized Philox RNG calls, specifically for forward graph."""
520
+
521
+ def expr(self) -> str:
522
+ return "__philox_forward_seed"
523
+
524
+
525
+ @dataclasses.dataclass(frozen=True)
526
+ class PhiloxForwardBaseOffsetAOTInput(AOTInput):
527
+ """The offset for functionalized Philox RNG calls, specifically for forward graph."""
528
+
529
+ def expr(self) -> str:
530
+ return "__philox_forward_base_offset"
531
+
532
+
533
+ @dataclasses.dataclass(frozen=True)
534
+ class PhiloxBackwardSeedAOTInput(AOTInput):
535
+ """The seed for functionalized Philox RNG calls, specifically for backward graph."""
536
+
537
+ def expr(self) -> str:
538
+ return "__philox_backward_seed"
539
+
540
+
541
+ @dataclasses.dataclass(frozen=True)
542
+ class PhiloxBackwardBaseOffsetAOTInput(AOTInput):
543
+ """The offset for functionalized Philox RNG calls, specifically for backward graph."""
544
+
545
+ def expr(self) -> str:
546
+ return "__philox_backward_base_offset"
547
+
548
+
549
+ @dataclasses.dataclass(frozen=True)
550
+ class ForwardTokenAOTInput(AOTInput):
551
+ """The world token which is threaded through side-effectful operations"""
552
+
553
+ idx: int
554
+
555
+ def expr(self) -> str:
556
+ return f"__forward_token{self.idx}"
557
+
558
+
559
+ @dataclasses.dataclass(frozen=True)
560
+ class BackwardTokenAOTInput(AOTInput):
561
+ """The world token which is threaded through side-effectful operations, for backwards"""
562
+
563
+ idx: int
564
+
565
+ def expr(self) -> str:
566
+ return f"__backward_token{self.idx}"
567
+
568
+
569
+ # Technically the "output" here is redundant, tangents always correspond to
570
+ # outputs
571
+ # NB: this is marked differentiable as it /would/ be differentiable if we
572
+ # support double backwards, but we never generate this today because we
573
+ # don't support double backwards.
574
+ @dataclasses.dataclass(frozen=True)
575
+ class TangentAOTInput(DifferentiableAOTInput):
576
+ """An input to the joint graph representing the tangent of an output."""
577
+
578
+ output: DifferentiableAOTOutput
579
+
580
+ def __post_init__(self) -> None:
581
+ assert isinstance(self.output, DifferentiableAOTOutput)
582
+
583
+ def expr(self) -> str:
584
+ return f"__output_tangent({self.output.expr()})"
585
+
586
+ def is_tangent(self) -> bool:
587
+ return True
588
+
589
+
590
+ # ------------
591
+
592
+ # AOTOutput
593
+
594
+ # ------------
595
+
596
+
597
+ @dataclasses.dataclass(frozen=True)
598
+ class PlainAOTOutput(DifferentiableAOTOutput):
599
+ """A plain tensor output at position idx of the output tuple"""
600
+
601
+ idx: int
602
+
603
+ def expr(self) -> str:
604
+ return f"output[{self.idx}]"
605
+
606
+
607
+ @dataclasses.dataclass(frozen=True)
608
+ class InputMutationAOTOutput(DifferentiableAOTOutput):
609
+ """The mutated value of an input tensor, returned so we can appropriately propagate autograd."""
610
+
611
+ mutated_input: AOTInput
612
+
613
+ def expr(self) -> str:
614
+ return f"__input_mutation({self.mutated_input.expr()})"
615
+
616
+
617
+ @dataclasses.dataclass(frozen=True)
618
+ class IntermediateBaseAOTOutput(DifferentiableAOTOutput):
619
+ """An intermediate base of multiple outputs which alias each other. We only report ONE of
620
+ the outputs that contributed to this base"""
621
+
622
+ base_of: "AOTOutput"
623
+
624
+ def expr(self) -> str:
625
+ return f"__intermediate_base({self.base_of.expr()})"
626
+
627
+
628
+ # TODO: it's a little dodgy this is differentiable lol, but we do generate
629
+ # these BEFORE autograd is handled
630
+ @dataclasses.dataclass(frozen=True)
631
+ class MetadataMutationAOTOutput(DifferentiableAOTOutput):
632
+ idx: int
633
+
634
+ def expr(self) -> str:
635
+ return f"__aliased_arg_with_metadata_mutation{self.idx}"
636
+
637
+
638
+ # NB: this is marked differentiable as it /would/ be differentiable if we
639
+ # support double backwards, but we never generate this today because we
640
+ # don't support double backwards.
641
+ @dataclasses.dataclass(frozen=True)
642
+ class GradAOTOutput(DifferentiableAOTOutput):
643
+ """An output representing the computed gradient for a differentiable input, in the joint graph"""
644
+
645
+ grad_of: DifferentiableAOTInput
646
+
647
+ def __post_init__(self) -> None:
648
+ assert isinstance(self.grad_of, DifferentiableAOTInput)
649
+
650
+ def expr(self) -> str:
651
+ return f"__grad({self.grad_of.expr()})"
652
+
653
+ def is_grad(self) -> bool:
654
+ return True
655
+
656
+
657
+ @dataclasses.dataclass(frozen=True)
658
+ class PhiloxUpdatedForwardOffsetAOTOutput(AOTOutput):
659
+ """The final offset from the functionalized RNG calls, forward only"""
660
+
661
+ def expr(self) -> str:
662
+ return "__philox_updated_forward_offset"
663
+
664
+
665
+ @dataclasses.dataclass(frozen=True)
666
+ class PhiloxUpdatedBackwardOffsetAOTOutput(AOTOutput):
667
+ """The final offset from the functionalized RNG calls, backward only"""
668
+
669
+ def expr(self) -> str:
670
+ return "__philox_updated_backward_offset"
671
+
672
+
673
+ @dataclasses.dataclass(frozen=True)
674
+ class ForwardTokenAOTOutput(AOTOutput):
675
+ """The world token output for side-effectful calls, returned so we cannot DCE it, forward only"""
676
+
677
+ idx: int
678
+
679
+ def expr(self) -> str:
680
+ return f"__forward_token{self.idx}"
681
+
682
+
683
+ @dataclasses.dataclass(frozen=True)
684
+ class BackwardTokenAOTOutput(AOTOutput):
685
+ """The world token output for side-effectful calls, returned so we cannot DCE it, backward only"""
686
+
687
+ idx: int
688
+
689
+ def expr(self) -> str:
690
+ return f"__backward_token{self.idx}"
691
+
692
+
693
+ # These are seemingly symmetric with their AOTInput counterparts. The way to
694
+ # think about it is that a subclass could be an input or an output, and they
695
+ # get exploded into plain tensors on the way in and out. So we need
696
+ # descriptors for both.
697
+ @dataclasses.dataclass(frozen=True)
698
+ class SubclassGetAttrAOTOutput(AOTOutput):
699
+ """This output will be bundled into a subclass at this location"""
700
+
701
+ base: AOTOutput
702
+ attr: str
703
+
704
+ def expr(self) -> str:
705
+ return f"{self.base.expr()}.{self.attr}"
706
+
707
+ def is_grad(self) -> bool:
708
+ return self.base.is_grad()
709
+
710
+
711
+ @dataclasses.dataclass(frozen=True)
712
+ class SubclassSizeAOTOutput(AOTOutput):
713
+ """This output size will be bundled into a subclass at this location"""
714
+
715
+ base: AOTOutput
716
+ idx: int
717
+
718
+ def expr(self) -> str:
719
+ return f"{self.base.expr()}.size({self.idx})"
720
+
721
+
722
+ @dataclasses.dataclass(frozen=True)
723
+ class SubclassStrideAOTOutput(AOTOutput):
724
+ """This output stride will be bundled into a subclass at this location"""
725
+
726
+ base: AOTOutput
727
+ idx: int
728
+
729
+ def expr(self) -> str:
730
+ return f"{self.base.expr()}.stride({self.idx})"
731
+
732
+
733
+ @dataclasses.dataclass(frozen=True)
734
+ class DummyAOTOutput(AOTOutput):
735
+ """For cases when you don't actually care about descriptor propagation, do not use under normal
736
+ circumstances."""
737
+
738
+ idx: int
739
+
740
+ def expr(self) -> str:
741
+ return f"__dummy{self.idx}"
742
+
743
+
744
+ @dataclasses.dataclass(frozen=True)
745
+ class SavedForBackwardsAOTOutput(AOTOutput):
746
+ idx: int
747
+
748
+ def expr(self) -> str:
749
+ return f"__saved_for_backwards_{self.idx}"
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from collections.abc import KeysView
4
+ from contextlib import contextmanager
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+ import torch.utils._pytree as pytree
9
+ from torch._guards import detect_fake_mode
10
+ from torch._subclasses import FakeTensor, FakeTensorMode
11
+ from torch.fx.experimental.proxy_tensor import _pytree_subclasses_that_lose_info
12
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
13
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
14
+
15
+ from .. import config
16
+ from .schemas import AOTConfig, FakifiedFlatArgs
17
+
18
+
19
+ static_inputs_log = torch._logging.getArtifactLogger(
20
+ __name__, "cudagraph_static_inputs"
21
+ )
22
+
23
+
24
+ def process_inputs(
25
+ flat_args: list[Any],
26
+ aot_config: AOTConfig,
27
+ fake_mode: FakeTensorMode,
28
+ shape_env: Optional[ShapeEnv],
29
+ ignore_shape_env: bool = False,
30
+ ) -> FakifiedFlatArgs:
31
+ with fake_mode:
32
+
33
+ def convert(idx, x):
34
+ if shape_env is not None and not ignore_shape_env:
35
+ from torch._dynamo.source import ConstantSource
36
+
37
+ if isinstance(x, int):
38
+ # We always specialize on scalar values in export.
39
+ if aot_config.is_export:
40
+ return x
41
+ source = ConstantSource(f"sym_{idx}")
42
+ return shape_env.create_symintnode(
43
+ shape_env.create_symbol(x, source), hint=x, source=source
44
+ )
45
+ if isinstance(x, torch.ScriptObject):
46
+ return torch._library.fake_class_registry.maybe_to_fake_obj(
47
+ fake_mode, x
48
+ )
49
+ if not isinstance(x, torch.Tensor):
50
+ return x
51
+ if isinstance(x, FakeTensor):
52
+ assert x.fake_mode is fake_mode
53
+ return x
54
+ if is_traceable_wrapper_subclass(x):
55
+ attrs, _ = x.__tensor_flatten__()
56
+ if all(isinstance(getattr(x, attr), FakeTensor) for attr in attrs):
57
+ assert all(
58
+ getattr(x, attr).fake_mode is fake_mode for attr in attrs
59
+ )
60
+ return x
61
+
62
+ # see note [Tensor Fakification and Symbol Caching]
63
+ symbolic_context = None
64
+ source = None
65
+ trace = True
66
+ if tracing_context := torch._guards.TracingContext.try_get():
67
+ if x in tracing_context.tensor_to_context:
68
+ symbolic_context = tracing_context.tensor_to_context[x]
69
+ source = symbolic_context.tensor_source
70
+ # We already fakeified this tensor in Dynamo, don't
71
+ # dump the trace for it again
72
+ trace = False
73
+ if (
74
+ idx < aot_config.num_params_buffers
75
+ and config.static_weight_shapes
76
+ and not symbolic_context
77
+ ):
78
+ # TODO: Ensure that this codepath is never exercised from
79
+ # Dynamo
80
+ return fake_mode.from_tensor(x, static_shapes=True)
81
+
82
+ result = fake_mode.from_tensor(
83
+ x,
84
+ static_shapes=ignore_shape_env,
85
+ symbolic_context=symbolic_context,
86
+ source=source,
87
+ trace=trace,
88
+ )
89
+ return result
90
+
91
+ return FakifiedFlatArgs([convert(idx, x) for idx, x in enumerate(flat_args)])
92
+
93
+
94
+ def construct_fake_mode(
95
+ flat_args: list[Any], aot_config: AOTConfig
96
+ ) -> tuple[FakeTensorMode, Optional[ShapeEnv]]:
97
+ fake_mode = detect_fake_mode(flat_args)
98
+ if fake_mode is None:
99
+ shape_env = ShapeEnv() if aot_config.dynamic_shapes else None
100
+ fake_mode = FakeTensorMode(shape_env=shape_env)
101
+ else:
102
+ shape_env = fake_mode.shape_env
103
+ return (fake_mode, shape_env)
104
+
105
+
106
+ def _try_get_metadata_from_dynamo(
107
+ mod: torch.nn.Module, param_keys: KeysView[str], full_args_num: int
108
+ ) -> tuple[Optional[list[torch._guards.Source]], list[int]]:
109
+ """
110
+ Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModule.
111
+ We first verify that `mod` does come from Dynamo, then we handle cases where
112
+ metadata might be missing.
113
+
114
+ Returns:
115
+ aot_autograd_arg_pos_to_source: used to dedup params and their guards
116
+ static_input_indices: used to identify static inputs for cudagraphs
117
+ """
118
+ # Note [Assumption on Dynamo Metadata]
119
+ # This function assumes a graph module from dynamo provides `dynamo_compiled_id`,
120
+ # _param_name_to_source, and every placeholder node has `_dynamo_source` attributes.
121
+ # When gm is modified (e.g., DDPOptimizer via split_module), metadata needs to
122
+ # be propagated in order to be recognized as a dynamo graph
123
+
124
+ if not (isinstance(mod, torch.fx.GraphModule) and "dynamo_compile_id" in mod.meta):
125
+ # graph was not captured by dynamo
126
+ return None, []
127
+
128
+ if not hasattr(mod, "_param_name_to_source"):
129
+ # is from export
130
+ return None, []
131
+
132
+ # We now know this came from dynamo, and (1) we care about guards,
133
+ # so setting up aot_autograd_arg_pos_to_source for downstream dedup guards
134
+ # can now be done safely. (2) Dynamo logic protects the 1:1 sizing below.
135
+ # Additionally, we mark static indices for cudagraphs.
136
+ param_name_to_source = mod._param_name_to_source
137
+ seen_sources = set()
138
+
139
+ aot_autograd_arg_pos_to_source = []
140
+ static_input_indices = []
141
+ # Collect the new inputs lifted by aotdispatch
142
+ for i, name in enumerate(param_keys):
143
+ assert name in param_name_to_source, f"{name} not found."
144
+ source = param_name_to_source[name]
145
+ assert source not in seen_sources, source
146
+ seen_sources.add(source)
147
+ aot_autograd_arg_pos_to_source.append(source)
148
+
149
+ static_input_indices.append(i)
150
+
151
+ # Collect the dynamo graph inputs
152
+ # TODO(mlazos): Revisit if this is still needed. With Dynamo install ID
153
+ # matched tensors back into the Fx graph, this might not be necessary.
154
+ for pos, node in enumerate(mod.graph.find_nodes(op="placeholder")):
155
+ assert hasattr(node, "_dynamo_source")
156
+ source = node._dynamo_source
157
+ # `source`` specifies the source from user code. ddp optimizer may have
158
+ # intermediate values becoming submodule placeholders which does not
159
+ # have a source
160
+ assert source is None or source not in seen_sources, source
161
+ seen_sources.add(source)
162
+ aot_autograd_arg_pos_to_source.append(source)
163
+ source_name = source.name() if source else str(source)
164
+
165
+ # input[i] in dynamo is now:
166
+ # input[i + len(extra_params)] in AOT,
167
+ # where extra_params are the params/buffers that dynamo baked into the
168
+ # OutputGraph
169
+ actual_pos = pos + len(param_keys)
170
+
171
+ if "tensor_dict" in node.meta and node.meta["tensor_dict"].get(
172
+ "_dynamo_static_input_type", None
173
+ ):
174
+ static_inputs_log.debug(
175
+ "Adding static input pos %s for source %s", actual_pos, source_name
176
+ )
177
+ static_input_indices.append(actual_pos)
178
+ else:
179
+ static_inputs_log.debug(
180
+ "Non-static input pos %s for source %s", actual_pos, source_name
181
+ )
182
+
183
+ assert full_args_num == len(aot_autograd_arg_pos_to_source)
184
+ return aot_autograd_arg_pos_to_source, static_input_indices
185
+
186
+
187
+ @contextmanager
188
+ def _detect_attribute_assignment(mod: torch.nn.Module):
189
+ # Do not allow assignment of tensor attributes during export unless
190
+ # the attribute is registered as a buffer.
191
+
192
+ NN_MODULE_STD_ATTRS = [
193
+ "_backward_hooks",
194
+ "_backward_pre_hooks",
195
+ "_buffers",
196
+ "_forward_hooks",
197
+ "_forward_hooks_always_called",
198
+ "_forward_hooks_with_kwargs",
199
+ "_forward_pre_hooks",
200
+ "_forward_pre_hooks_with_kwargs",
201
+ "_is_full_backward_hook",
202
+ "_load_state_dict_post_hooks",
203
+ "_load_state_dict_pre_hooks",
204
+ "_modules",
205
+ "_non_persistent_buffers_set",
206
+ "_parameters",
207
+ "_state_dict_hooks",
208
+ "_state_dict_pre_hooks",
209
+ "training",
210
+ ]
211
+ NN_MODULE_LAZY_STD_ATTRS = [
212
+ "_initialize_hook",
213
+ "_load_hook",
214
+ ]
215
+ STD_ATTRS = {
216
+ *NN_MODULE_STD_ATTRS,
217
+ *NN_MODULE_LAZY_STD_ATTRS,
218
+ }
219
+
220
+ def _get_attributes(mod):
221
+ # return any attributes of a module that are not standard attributes
222
+ return {k: v for k, v in mod.__dict__.items() if k not in STD_ATTRS}
223
+
224
+ # save state of attributes before enter
225
+ snapshot = pytree.tree_map(
226
+ lambda x: x,
227
+ _get_attributes(mod),
228
+ is_leaf=lambda x: type(x) in _pytree_subclasses_that_lose_info,
229
+ )
230
+ try:
231
+ yield
232
+ finally:
233
+ # after exit, compare state of attributes with snapshot
234
+ # to detect which tensor attributes were assigned
235
+ assigned_tensor_attributes = []
236
+
237
+ def _collect_assigned_tensor_attributes(kp, v, _v):
238
+ if _v is not v:
239
+ attr, *rest = kp
240
+ if isinstance(v, torch.Tensor):
241
+ assigned_tensor_attributes.append(
242
+ f"self.{attr.key}{pytree.keystr(rest)}"
243
+ )
244
+ # TODO(avik): Assigning all other types are allowed right now.
245
+ # Maybe in the future we want to limit this to primitive types?
246
+ return v
247
+
248
+ new_attrs = _get_attributes(mod)
249
+ if len(new_attrs) != len(snapshot):
250
+ added_attrs = new_attrs.keys() - snapshot.keys()
251
+ deleted_attrs = snapshot.keys() - new_attrs.keys()
252
+
253
+ if len(added_attrs) > 0:
254
+ raise ValueError(
255
+ f"During torch.export, following attrs were created in the model.forward: {added_attrs} "
256
+ f"Such attributes must be registered as buffers using the `register_buffer` "
257
+ f"API and must be initialized at model.__init__ "
258
+ f"(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
259
+ )
260
+
261
+ if len(deleted_attrs) > 0:
262
+ raise ValueError(
263
+ f"During torch.export, following attrs were deleted in the model.forward: {deleted_attrs} "
264
+ f"Such attributes must be registered as buffers using the `register_buffer` "
265
+ f"API and must be initialized at model.__init__ "
266
+ f"(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
267
+ )
268
+
269
+ pytree.tree_map_with_path(
270
+ _collect_assigned_tensor_attributes, snapshot, new_attrs
271
+ )
272
+ # restore state of all attributes (including, e.g., of primitive types)
273
+ mod.__dict__.update(snapshot)
274
+
275
+ if assigned_tensor_attributes:
276
+ if len(assigned_tensor_attributes) > 1:
277
+ noun, verb = "attributes", "were"
278
+ else:
279
+ noun, verb = "attribute", "was"
280
+ raise ValueError(
281
+ f"The tensor {noun} {', '.join(assigned_tensor_attributes)} {verb} assigned during export. "
282
+ "Such attributes must be registered as buffers using the `register_buffer` API "
283
+ "(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer)."
284
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/functional_utils.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Optional
14
+
15
+ import torch
16
+ from torch import Tensor
17
+ from torch._C import _functionalization
18
+ from torch._logging import getArtifactLogger
19
+ from torch._subclasses.fake_tensor import FakeTensor
20
+ from torch._subclasses.functional_tensor import FunctionalTensor
21
+ from torch._subclasses.meta_utils import is_sparse_any
22
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq, SymIntEqByExpr
23
+ from torch.multiprocessing.reductions import StorageWeakRef
24
+ from torch.utils._python_dispatch import (
25
+ is_traceable_wrapper_subclass,
26
+ transform_subclass,
27
+ )
28
+
29
+
30
+ aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph")
31
+
32
+
33
+ def to_fun(t):
34
+ if isinstance(t, Tensor):
35
+ if is_traceable_wrapper_subclass(t):
36
+ # See Note [Functionalization always runs last]
37
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
38
+ # goes at the bottom.
39
+ # recurse here, so we can support nested wrapper subclasses
40
+ out = transform_subclass(t, lambda _, inner_t: to_fun(inner_t))
41
+ torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined]
42
+ return out
43
+ else:
44
+ return FunctionalTensor.to_functional(t)
45
+ else:
46
+ return t
47
+
48
+
49
+ def sync_functional_tensor(t):
50
+ if is_traceable_wrapper_subclass(t):
51
+ attrs, _ctx = t.__tensor_flatten__() # type: ignore[attr-defined]
52
+ for attr in attrs:
53
+ sync_functional_tensor(getattr(t, attr))
54
+ else:
55
+ torch._sync(t)
56
+
57
+
58
+ # When subclasses are involved, t here will usually look something like:
59
+ # SubclassA(SubclassB(FunctionalTensor(_to_fun_tensor(FakeTensor))))
60
+ def from_fun(t):
61
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
62
+ # See Note [Functionalization always runs last]
63
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
64
+ # goes at the bottom.
65
+ # recurse here, so we can support nested wrapper subclasses
66
+ out = transform_subclass(t, lambda _, inner_t: from_fun(inner_t))
67
+ torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined]
68
+ return out
69
+
70
+ if not isinstance(t, FunctionalTensor):
71
+ # quick sanity assert
72
+ if isinstance(t, torch.Tensor):
73
+ assert not torch._is_functional_tensor(t) # type: ignore[attr-defined]
74
+ return t
75
+ sync_functional_tensor(t)
76
+ return torch._from_functional_tensor(t.elem)
77
+
78
+
79
+ def is_fun(t):
80
+ if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t):
81
+ # See Note [Functionalization always runs last]
82
+ # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper
83
+ # goes at the bottom.
84
+ # recurse here, so we can support nested wrapper subclasses
85
+ t_attrs, _ = t.__tensor_flatten__() # type: ignore[attr-defined]
86
+ t_inners = [getattr(t, attr) for attr in t_attrs]
87
+ any_fun = any(is_fun(x) for x in t_inners)
88
+ all_fun = all(is_fun(x) for x in t_inners)
89
+ assert any_fun == all_fun
90
+ return any_fun
91
+
92
+ return isinstance(t, FunctionalTensor)
93
+
94
+
95
+ # t here is either
96
+ # (1) A FunctionalTensor(_to_functional_tensor(FakeTensor))
97
+ # (2) A traceable tensor subclass that holds a FunctionalTensor
98
+ # (3) Not a tensor
99
+ def has_data_mutation(t):
100
+ if is_traceable_wrapper_subclass(t):
101
+ attrs, _ = t.__tensor_flatten__()
102
+ # A tensor subclass was updated if any of its inner elements were updated
103
+ return any(has_data_mutation(getattr(t, attr)) for attr in attrs)
104
+ else:
105
+ if isinstance(t, torch.Tensor):
106
+ assert isinstance(t, FunctionalTensor)
107
+ return torch._functionalize_has_data_mutation(t.elem) # type: ignore[attr-defined]
108
+ return False
109
+
110
+
111
+ def are_all_mutations_hidden_from_autograd(t):
112
+ if is_traceable_wrapper_subclass(t):
113
+ attrs, _ = t.__tensor_flatten__()
114
+ # If all inner elements are mutations hidden from autograd, then it is a mutation hidden from autograd.
115
+ return all(
116
+ are_all_mutations_hidden_from_autograd(getattr(t, attr)) for attr in attrs
117
+ )
118
+ elif isinstance(t, torch.Tensor):
119
+ assert isinstance(t, FunctionalTensor)
120
+ return torch._functionalize_are_all_mutations_hidden_from_autograd(t.elem)
121
+ else:
122
+ return False
123
+
124
+
125
+ def are_all_mutations_under_no_grad_or_inference_mode(t):
126
+ if is_traceable_wrapper_subclass(t):
127
+ attrs, _ = t.__tensor_flatten__()
128
+ return all(
129
+ are_all_mutations_under_no_grad_or_inference_mode(getattr(t, attr))
130
+ for attr in attrs
131
+ )
132
+ else:
133
+ assert isinstance(t, FunctionalTensor)
134
+ return torch._functionalize_are_all_mutations_under_no_grad_or_inference_mode(
135
+ t.elem
136
+ )
137
+
138
+
139
+ def was_inductor_storage_resized(t):
140
+ if is_traceable_wrapper_subclass(t):
141
+ attrs, _ = t.__tensor_flatten__()
142
+ if any(was_inductor_storage_resized(getattr(t, attr)) for attr in attrs):
143
+ raise RuntimeError(
144
+ f"storage resizing is not supported on tensor subclass: {type(t)}"
145
+ )
146
+ elif not isinstance(t, torch.Tensor):
147
+ return False
148
+ else:
149
+ assert isinstance(t, FunctionalTensor)
150
+ return torch._functionalize_was_inductor_storage_resized(t.elem)
151
+
152
+
153
+ # f_arg here is either
154
+ # (1) A FunctionalTensor(_to_functional_tensor(FakeTensor))
155
+ # (2) A traceable tensor subclass that holds a FunctionalTensor
156
+ # (3) Not a tensor
157
+ # Assumption: arg promises to be the "original" tensor wrapped by f_arg
158
+ # Note: "storage mutations" coming from set_() are a type of metadata mutation. So:
159
+ # - check_only_storage_mutation=True: only return true if there was a storage mutation
160
+ # - check_only_storage_mutation=Flse: return true if there was any metadata mutation (including a storage mutation)
161
+ def has_metadata_mutation(f_arg, arg, *, check_only_storage_mutation: bool):
162
+ if is_traceable_wrapper_subclass(f_arg):
163
+ attrs, _ = f_arg.__tensor_flatten__()
164
+ # A tensor subclass was updated if any of its inner elements were updated
165
+ f_inner_ts = [getattr(f_arg, attr) for attr in attrs]
166
+ inner_ts = [getattr(arg, attr) for attr in attrs]
167
+ return any(
168
+ has_metadata_mutation(
169
+ f_inner_t,
170
+ inner_t,
171
+ check_only_storage_mutation=check_only_storage_mutation,
172
+ )
173
+ for f_inner_t, inner_t in zip(f_inner_ts, inner_ts)
174
+ )
175
+ else:
176
+ if not isinstance(f_arg, torch.Tensor):
177
+ assert not isinstance(arg, torch.Tensor)
178
+ return False
179
+ assert isinstance(f_arg, FunctionalTensor)
180
+ assert isinstance(arg, FakeTensor)
181
+
182
+ arg_after = torch._from_functional_tensor(f_arg.elem)
183
+ # This is true if the current tensor experienced at least one set_() call
184
+ maybe_storage_changed = torch._functionalize_was_storage_changed(f_arg.elem) # type: ignore[attr-defined]
185
+ # However, multiple set_() calls can cancel out. So we also check whether the
186
+ # storage of the tensor has changed.
187
+ # Note: if an input experienced two set_() calls that cancel out, **and**
188
+ # it experiences an data mutation, we pessimistically think that the set_()
189
+ # call is necessary here. We could in theory fix this, but this will
190
+ # hopefully never happen in user code, and is not needed for fsdp.
191
+ if is_sparse_any(arg):
192
+ # TODO:add sparse tensors support to functionalization
193
+ same_storages = False
194
+ else:
195
+ same_storages = StorageWeakRef(arg.untyped_storage()) == StorageWeakRef(
196
+ arg_after.untyped_storage()
197
+ )
198
+ has_storage_metadata_mutation = maybe_storage_changed and not same_storages
199
+ if check_only_storage_mutation:
200
+ return has_storage_metadata_mutation
201
+
202
+ # storage metadata mutation is a type of metadata mutation, so return true if we saw one
203
+ if has_storage_metadata_mutation:
204
+ return True
205
+
206
+ maybe_metadata_mutated = torch._functionalize_has_metadata_mutation(f_arg.elem) # type: ignore[attr-defined]
207
+ # This is true if the current tensor experienced at least one metadata mutation.
208
+ # So if false, we know there was no metadata mutation
209
+ if not maybe_metadata_mutated:
210
+ return False
211
+
212
+ # However, multi metadata mutations can cancel out.
213
+ # So we also check if the concrete sizes/strides on the tensor have changed.
214
+ same_sizes = arg.shape == arg_after.shape
215
+ same_strides = arg.stride() == arg_after.stride()
216
+ same_offsets = arg.storage_offset() == arg_after.storage_offset()
217
+ has_metadata_mutation_ = maybe_metadata_mutated and not (
218
+ same_sizes and same_strides and same_offsets
219
+ )
220
+ # We consider a tensor to have been metadata mutated if its storage was mutated through a set_() call.
221
+ return has_metadata_mutation_
222
+
223
+
224
+ def gen_alias_from_base(
225
+ aliased_base_tensor,
226
+ target_meta_tensor,
227
+ target_requires_grad,
228
+ target_view_meta_sequence: Optional[ViewMetaSequence] = None,
229
+ *,
230
+ replay_views: bool,
231
+ ):
232
+ # Patch the correct requires_grad field of the output tensor, depending on whether:
233
+ # (i) the reconstructed output (out) was came from a tensor that requires grad or not;
234
+ # and (ii) the concrete returned output does require grad or not.
235
+ def patch_requires_grad(out):
236
+ if aliased_base_tensor.requires_grad and not target_requires_grad:
237
+ out = out.detach()
238
+ elif not aliased_base_tensor.requires_grad and target_requires_grad:
239
+ out.requires_grad_(True)
240
+ return out
241
+
242
+ # If provided, use the target functional tensor for replaying the views.
243
+ #
244
+ # In summary, we use the fact that FunctionalTensorWrapper saves the view
245
+ # functions applied to itself (collected during functionalization) so as
246
+ # to replay them (view functions) on the aliased_base_tensor.
247
+ if (
248
+ replay_views
249
+ and target_view_meta_sequence is not None
250
+ and not any(vm.has_symbolic_inputs for vm in target_view_meta_sequence.sequence)
251
+ ):
252
+ out = _functionalization.apply_view_meta_sequence(
253
+ aliased_base_tensor, target_view_meta_sequence.sequence
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
+ # ViewMeta sequence wrapper for equality comparisons.
360
+ #
361
+ # Even though we can compare each ViewMeta instance, we compare the resulting
362
+ # tensor metadata, instead. That's because the creation of synthetic bases + the
363
+ # re-generation of input views might end-up creating a different sequence of
364
+ # ViewMeta that is semantically equivalent. i.e. gets to a tensor with the same
365
+ # metadata.
366
+ #
367
+ # Therefore, we store what the end result should look like as serializable
368
+ # metadata.
369
+ #
370
+ # When logging, this class should look like:
371
+ #
372
+ # ViewMetaSequence(view, select_int, slice_Tensor)
373
+ #
374
+ # i.e. a parenthesized list of view operations within that ViewMeta sequence.
375
+ class ViewMetaSequence:
376
+ def __init__(self, tensor: FunctionalTensor) -> None:
377
+ assert torch._is_functional_tensor(tensor.elem)
378
+ self.sequence = _functionalization.get_view_meta_sequence(tensor.elem)
379
+ self.metadata = MetadataKey.make(tensor)
380
+
381
+ def __repr__(self) -> str:
382
+ suffix = len("_ViewMeta")
383
+ types = ", ".join(type(vm).__name__[:-suffix] for vm in self.sequence)
384
+ return f"ViewMetaSequence({types})"
385
+
386
+ def __eq__(self, other: object) -> bool:
387
+ # If other is None, then it probably means that we weren't able to recreate
388
+ # the ViewMeta sequence. One example is when we update the view metadata by
389
+ # calling: create_synthetic_base_metadata.
390
+ if other is None:
391
+ return True
392
+
393
+ # Comparison against any other type is not implemented.
394
+ if not isinstance(other, ViewMetaSequence):
395
+ return NotImplemented
396
+
397
+ return self.metadata == other.metadata
398
+
399
+
400
+ # new_arg and arg here are either:
401
+ # (1) both a FakeTensor
402
+ # (2) both a traceable tensor subclass that holds a FakeTensor
403
+ # Pre-condition: the two args are the "old" and "new" inputs from running functionalization.
404
+ # When we run functionalization and wrap our inputs into FunctionalTensors,
405
+ # we can detect whether or not an input was mutated by checking to see if the inner tensor has changed
406
+ #
407
+ # Normally it would be enough just to check if arg is new_arg, which is normally enough for functionalization
408
+ # to confirm that inputs were not mutated when running the user's model with functionalization on.
409
+ # But when we have subclass inputs, we can't rely on that:
410
+ # `from_fun(to_fun(x)) is x` will return False, because the call to `from_fun` constructs
411
+ # a brand new subclass instance: we are calling __tensor_unflatten__, and going
412
+ # from Subclass(FakeTensor) to Subclass(FunctionalTensor(FakeTensor))
413
+ def was_tensor_updated(arg, new_arg):
414
+ if is_traceable_wrapper_subclass(arg):
415
+ assert is_traceable_wrapper_subclass(new_arg)
416
+ attrs, _ = arg.__tensor_flatten__()
417
+ new_attrs, _ = new_arg.__tensor_flatten__()
418
+ assert attrs == new_attrs
419
+ # A tensor subclass was updated if any of its inner elements were updated
420
+ return any(
421
+ was_tensor_updated(getattr(arg, attr), getattr(new_arg, attr))
422
+ for attr in attrs
423
+ )
424
+ else:
425
+ return arg is not new_arg
426
+
427
+
428
+ # new_arg and arg here are either:
429
+ # (1) both a FakeTensor
430
+ # (2) both a traceable tensor subclass that holds a FakeTensor
431
+ # Pre-condition: the two args are the "old" and "new" inputs from running functionalization.
432
+ # When we run functionalization and wrap our inputs into FunctionalTensors,
433
+ # we can detect whether or not an input was mutated by checking to see if the inner tensor has changed,
434
+ # but shares storage with the old input
435
+ def was_tensor_metadata_updated(arg, new_arg):
436
+ if is_traceable_wrapper_subclass(arg):
437
+ assert is_traceable_wrapper_subclass(new_arg)
438
+ attrs, _ = arg.__tensor_flatten__()
439
+ new_attrs, _ = new_arg.__tensor_flatten__()
440
+ assert attrs == new_attrs
441
+ # A tensor subclass was updated if any of its inner elements were updated
442
+ return any(
443
+ was_tensor_metadata_updated(getattr(arg, attr), getattr(new_arg, attr))
444
+ for attr in attrs
445
+ )
446
+ else:
447
+ return arg is not new_arg and StorageWeakRef(
448
+ arg.untyped_storage()
449
+ ) == StorageWeakRef(new_arg.untyped_storage())
450
+
451
+
452
+ # Returns the number of detected copy_
453
+ def assert_functional_graph(fx_g: torch.fx.Graph) -> int:
454
+ allowed_mutation_ops = [
455
+ torch.ops.aten.copy_.default,
456
+ torch.ops.aten.set_.source_Tensor,
457
+ ]
458
+ if hasattr(torch.ops.fsdp, "copy_"):
459
+ allowed_mutation_ops.append(torch.ops.fsdp.copy_.default)
460
+
461
+ placeholders = set()
462
+ mutation_count = 0
463
+ # NB: It would also be nice to verify that the mutations all happen at the
464
+ # end, but we also do some administrative views after mutations so this
465
+ # isn't actually true. (TODO: Could this cause problems for Inductor?)
466
+ for n in fx_g.nodes:
467
+ if n.op == "placeholder":
468
+ placeholders.add(n)
469
+ if isinstance(n.target, torch._ops.OpOverload):
470
+ if n.target in allowed_mutation_ops:
471
+ # Can only copy_/set_ into an input
472
+ # this is mostly a hack to avoid failing XLA tests.
473
+ # See https://github.com/pytorch/pytorch/pull/122434#issuecomment-2101012113
474
+ if "set_buffer_donor_" not in str(n.args[0]):
475
+ assert n.args[0] in placeholders, (
476
+ f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}"
477
+ )
478
+ mutation_count += 1
479
+ else:
480
+ assert not n.target._schema.is_mutable, (
481
+ f"aot_autograd expected to have an entirely functional graph, but found {n.format_node()}"
482
+ )
483
+ return mutation_count
484
+
485
+
486
+ def propagate_input_mutation_stacktraces(fx_g: torch.fx.Graph) -> None:
487
+ placeholders = set()
488
+ for n in fx_g.nodes:
489
+ if n.op == "placeholder":
490
+ placeholders.add(n)
491
+ if isinstance(n.target, torch._ops.OpOverload):
492
+ if n.target is torch.ops.aten.copy_.default:
493
+ # Can only copy_ into an input, and can only do so once
494
+ if "set_buffer_donor_" not in str(n.args[0]):
495
+ assert n.args[0] in placeholders, (
496
+ f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}"
497
+ )
498
+ placeholders.remove(n.args[0])
499
+ copy_from_node = n.args[1]
500
+ # Pre-condition: every node has a "stack_trace" field in its meta,
501
+ # but copy_() nodes do not (since we manually added them during functionalization).
502
+ # Instead, we manually propagate here.
503
+ if "stack_trace" in copy_from_node.meta:
504
+ n.meta["stack_trace"] = copy_from_node.meta["stack_trace"]
505
+
506
+
507
+ def _check_if_mutation_can_be_in_graph(
508
+ keep_input_mutations: bool,
509
+ mutates_data,
510
+ mutates_metadata,
511
+ mutations_hidden_from_autograd,
512
+ mutations_under_no_grad_or_inference_mode,
513
+ mutates_storage_metadata,
514
+ mutation_inductor_storage_resize,
515
+ requires_grad,
516
+ ):
517
+ if keep_input_mutations:
518
+ in_graph = (
519
+ mutates_data or mutates_storage_metadata or mutation_inductor_storage_resize
520
+ ) and (
521
+ (not mutates_metadata and not requires_grad)
522
+ or mutations_hidden_from_autograd
523
+ or mutations_under_no_grad_or_inference_mode
524
+ )
525
+ else:
526
+ in_graph = False
527
+ # See Note [set_() Input Mutations in AOTAutograd]
528
+ # If there was a `set_()`, we require that all mutations were under no_grad,
529
+ # so we can (safely) emit the set_() in the graph at runtime
530
+ # resize_() gets the same treatment
531
+ if mutation_inductor_storage_resize or mutates_storage_metadata:
532
+ op_name = "resize_" if mutation_inductor_storage_resize else "set_"
533
+ assert in_graph, f"""\
534
+ Encountered a {op_name} on a graph input, but the input has other mutations that we cannot
535
+ keep in the graph. This is not supported today. Current state:
536
+ keep_input_mutations={keep_input_mutations}
537
+ mutates_data={mutates_data}
538
+ mutates_metadata={mutates_metadata}
539
+ mutations_hidden_from_autograd={mutations_hidden_from_autograd}
540
+ mutations_under_no_grad_or_inference_mode={mutations_under_no_grad_or_inference_mode}
541
+ mutation_inductor_storage_resize={mutation_inductor_storage_resize}
542
+ requires_grad={requires_grad}"""
543
+ return in_graph
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/fx_utils.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains utility functions for working with joint FX graphs with descriptors
3
+ that are produced by AOTAutograd. They will NOT work on generic FX graphs. See also
4
+ :func:`torch._functorch.aot_autograd.aot_export_joint_with_descriptors`. We also
5
+ recommend reading :mod:torch._functorch._aot_autograd.descriptors`.
6
+ """
7
+
8
+ from typing import NoReturn, Optional, Union
9
+
10
+ import torch.fx as fx
11
+
12
+ from .descriptors import (
13
+ AOTInput,
14
+ AOTOutput,
15
+ BufferAOTInput,
16
+ DifferentiableAOTInput,
17
+ DifferentiableAOTOutput,
18
+ GradAOTOutput,
19
+ ParamAOTInput,
20
+ PlainAOTInput,
21
+ PlainAOTOutput,
22
+ SubclassGetAttrAOTInput,
23
+ SubclassGetAttrAOTOutput,
24
+ TangentAOTInput,
25
+ )
26
+
27
+
28
+ def _raise_autograd_subclass_not_implemented(
29
+ n: fx.Node, desc: Union[AOTInput, AOTOutput]
30
+ ) -> NoReturn:
31
+ raise RuntimeError(
32
+ "Subclasses are currently not supported by this function, but a desugared subclass input "
33
+ f"was found at {n} ({desc}). The problem is "
34
+ "that there may not necessarily be a 1-1 correspondence between primals/tangents/outputs/grads "
35
+ "when subclasses are involved: for example, the primal might be a plain tensor "
36
+ "but the tangent a tensor subclass that desugared into multiple plain tensors. "
37
+ "It is not clear what exactly you would like this function to do in this case "
38
+ "(Collect all nodes for the subclass together? Match up the inner nodes if "
39
+ "subclasses match exactly?) If you have a concrete use case, please file an "
40
+ "issue so we can understand it and design an API that works for your case."
41
+ )
42
+
43
+
44
+ def get_all_input_and_grad_nodes(
45
+ g: fx.Graph,
46
+ ) -> dict[DifferentiableAOTInput, tuple[fx.Node, Optional[fx.Node]]]:
47
+ """
48
+ Given a joint graph with descriptors (meta['desc'] on placeholders and
49
+ output), returns the node for every input and its corresponding grad
50
+ output node if it exists. These tuples are in a dict that is indexed by
51
+ the AOTInput descriptor that describes the input.
52
+
53
+ NB: *all* forward tensor inputs are returned, including non-differentiable
54
+ inputs (which simply have a None grad), so it is safe to use this function
55
+ to perform operations on all inputs. (Non-tensor inputs like symbolic
56
+ integers, tokens or RNG state are NOT traversed by this function.)
57
+
58
+ Args:
59
+ g: The FX joint graph with descriptors
60
+
61
+ Returns:
62
+ A dictionary mapping each DifferentiableAOTInput descriptor to a tuple
63
+ containing:
64
+ - The input node itself
65
+ - The grad (output) node if it exists, None otherwise
66
+
67
+ Raises:
68
+ RuntimeError: If the joint graph has subclass tensor inputs/outputs; this
69
+ is not supported by API as there is not necessarily a 1-1 correspondence
70
+ between inputs and grads when subclasses are involved.
71
+ """
72
+ input_index: dict[DifferentiableAOTInput, tuple[fx.Node, Optional[fx.Node]]] = {}
73
+ for n in g.nodes:
74
+ if n.op == "placeholder":
75
+ desc = n.meta["desc"]
76
+ # Skip inputs that cannot possibly be differentiable
77
+ if not isinstance(desc, DifferentiableAOTInput):
78
+ continue
79
+ if isinstance(desc, SubclassGetAttrAOTInput):
80
+ _raise_autograd_subclass_not_implemented(n, desc)
81
+ input_index[desc] = (n, None)
82
+ elif n.op == "output":
83
+ assert "desc" in n.meta, (n, n.meta)
84
+ desc = n.meta["desc"]
85
+ for sub_n, sub_desc in zip(n.args[0], desc):
86
+ if isinstance(sub_desc, SubclassGetAttrAOTOutput):
87
+ _raise_autograd_subclass_not_implemented(sub_n, sub_desc)
88
+ if isinstance(sub_desc, GradAOTOutput):
89
+ inp, grad = input_index[sub_desc.grad_of]
90
+ assert grad is None, (sub_n, sub_desc, input_index)
91
+ input_index[sub_desc.grad_of] = (inp, sub_n)
92
+ return input_index
93
+
94
+
95
+ def get_all_output_and_tangent_nodes(
96
+ g: fx.Graph,
97
+ ) -> dict[DifferentiableAOTOutput, tuple[fx.Node, Optional[fx.Node]]]:
98
+ """Get all output nodes and their corresponding tangent nodes from a joint graph.
99
+
100
+ Similar to get_all_input_and_grad_nodes, but returns output nodes paired with
101
+ their tangent nodes (if they exist). This function traverses the graph to find
102
+ all differentiable outputs and matches them with their corresponding tangent
103
+ inputs used in forward-mode autodiff.
104
+
105
+ NB: *all* forward tensor output sare turned, including non-differentiable outputs,
106
+ so you can use this function to perform operations on all outputs.
107
+
108
+ Args:
109
+ g: The FX joint graph with descriptors
110
+
111
+ Returns:
112
+ A dictionary mapping each DifferentiableAOTOutput descriptor to a tuple
113
+ containing:
114
+ - The output node itself
115
+ - The tangent (input) node if it exists, None otherwise
116
+
117
+ Raises:
118
+ RuntimeError: If the joint graph has subclass tensor inputs/outputs; this
119
+ is not supported by API as there is not necessarily a 1-1 correspondence
120
+ between outputs and tangents when subclasses are involved.
121
+ """
122
+ output_index: dict[DifferentiableAOTOutput, tuple[fx.Node, Optional[fx.Node]]] = {}
123
+ for n in g.nodes:
124
+ if n.op == "output":
125
+ desc = n.meta["desc"]
126
+ for sub_n, sub_d in zip(n.args[0], desc):
127
+ # Skip outputs that cannot possibly be differentiable
128
+ if not isinstance(sub_d, DifferentiableAOTOutput):
129
+ continue
130
+ if isinstance(sub_d, SubclassGetAttrAOTOutput):
131
+ _raise_autograd_subclass_not_implemented(sub_n, sub_d)
132
+ output_index[sub_d] = (sub_n, None)
133
+ for n in g.nodes:
134
+ if n.op == "placeholder":
135
+ desc = n.meta["desc"]
136
+ if isinstance(desc, SubclassGetAttrAOTInput):
137
+ _raise_autograd_subclass_not_implemented(n, desc)
138
+ if isinstance(desc, TangentAOTInput):
139
+ out, tangent = output_index[desc.output]
140
+ assert tangent is None, (n, desc, output_index)
141
+ output_index[desc.output] = (out, n)
142
+ return output_index
143
+
144
+
145
+ def get_param_and_grad_nodes(
146
+ graph: fx.Graph,
147
+ ) -> dict[ParamAOTInput, tuple[fx.Node, Optional[fx.Node]]]:
148
+ """Get parameter nodes and their corresponding gradient nodes from a joint graph.
149
+
150
+ Args:
151
+ graph: The FX joint graph with descriptors
152
+
153
+ Returns:
154
+ A dictionary mapping each ParamAOTInput descriptor to a tuple containing:
155
+ - The parameter input node
156
+ - The gradient (output) node if it exists, None otherwise
157
+ """
158
+ return {
159
+ desc: (n, g)
160
+ for desc, (n, g) in get_all_input_and_grad_nodes(graph).items()
161
+ if isinstance(desc, ParamAOTInput)
162
+ }
163
+
164
+
165
+ def get_plain_input_and_grad_nodes(
166
+ graph: fx.Graph,
167
+ ) -> dict[PlainAOTInput, tuple[fx.Node, Optional[fx.Node]]]:
168
+ """Get plain input nodes and their corresponding gradient nodes from a joint graph.
169
+
170
+ Args:
171
+ graph: The FX joint graph with descriptors
172
+
173
+ Returns:
174
+ A dictionary mapping each PlainAOTInput descriptor to a tuple containing:
175
+ - The plain input node
176
+ - The gradient (output) node if it exists, None otherwise
177
+ """
178
+ return {
179
+ desc: (n, g)
180
+ for desc, (n, g) in get_all_input_and_grad_nodes(graph).items()
181
+ if isinstance(desc, PlainAOTInput)
182
+ }
183
+
184
+
185
+ def get_plain_output_and_tangent_nodes(
186
+ graph: fx.Graph,
187
+ ) -> dict[PlainAOTOutput, tuple[fx.Node, Optional[fx.Node]]]:
188
+ """Get plain output nodes and their corresponding tangent nodes from a joint graph.
189
+
190
+ Args:
191
+ graph: The FX joint graph with descriptors
192
+
193
+ Returns:
194
+ A dictionary mapping each PlainAOTOutput descriptor to a tuple containing:
195
+ - The plain output node
196
+ - The tangent (input) node if it exists, None otherwise
197
+ """
198
+ return {
199
+ desc: (n, g)
200
+ for desc, (n, g) in get_all_output_and_tangent_nodes(graph).items()
201
+ if isinstance(desc, PlainAOTOutput)
202
+ }
203
+
204
+
205
+ def _raise_fqn_subclass_not_implemented(
206
+ n: fx.Node, desc: Union[AOTInput, AOTOutput]
207
+ ) -> NoReturn:
208
+ raise RuntimeError(
209
+ "Subclasses are currently not supported by this function, but a desugared subclass input "
210
+ f"was found at {n} ({desc}). The problem is "
211
+ "that there may not necessarily be a 1-1 correspondence between a FQN and a plain tensor "
212
+ "when subclasses are involved: for example, a parameter that is a subclass "
213
+ "would desugar into multiple plain tensors, which we can't uniquely assign the "
214
+ "FQN to. It's not clear what you want the API to do in this case: do you want to "
215
+ "instead return a struct of nodes showing how to assemble the subclass? But you "
216
+ "don't (directly) have the metadata for the subclass? If you have a concrete use "
217
+ "case, please file an issue so we can understand it and design an API that works for your case."
218
+ )
219
+
220
+
221
+ def get_named_param_nodes(graph: fx.Graph) -> dict[str, fx.Node]:
222
+ """Get parameter nodes mapped by their fully qualified names.
223
+
224
+ This function traverses the graph to find all parameter input nodes and
225
+ returns them in a dictionary where keys are the parameter names (FQNs)
226
+ and values are the corresponding FX nodes.
227
+
228
+ Args:
229
+ graph: The FX joint graph with descriptors
230
+
231
+ Returns:
232
+ A dictionary mapping parameter names (str) to their corresponding FX nodes.
233
+
234
+ Raises:
235
+ RuntimeError: If subclass tensors are encountered (not yet supported), as
236
+ with subclasses a FQN does not necessarily map to a single plain tensor.
237
+ """
238
+ r = {}
239
+ for n in graph.nodes:
240
+ if n.op == "placeholder":
241
+ desc = n.meta["desc"]
242
+ if isinstance(desc, SubclassGetAttrAOTInput):
243
+ _raise_fqn_subclass_not_implemented(n, desc)
244
+ elif isinstance(desc, ParamAOTInput):
245
+ r[desc.target] = n
246
+ return r
247
+
248
+
249
+ def get_named_buffer_nodes(graph: fx.Graph) -> dict[str, fx.Node]:
250
+ """Get buffer nodes mapped by their fully qualified names.
251
+
252
+ This function traverses the graph to find all buffer input nodes and
253
+ returns them in a dictionary where keys are the buffer names (FQNs)
254
+ and values are the corresponding FX nodes.
255
+
256
+ Args:
257
+ graph: The FX joint graph with descriptors
258
+
259
+ Returns:
260
+ A dictionary mapping buffer names (str) to their corresponding FX nodes.
261
+
262
+ Raises:
263
+ RuntimeError: If subclass tensors are encountered (not yet supported), as
264
+ with subclasses a FQN does not necessarily map to a single plain tensor.
265
+ """
266
+ r = {}
267
+ for n in graph.nodes:
268
+ if n.op == "placeholder":
269
+ desc = n.meta["desc"]
270
+ if isinstance(desc, SubclassGetAttrAOTInput):
271
+ _raise_fqn_subclass_not_implemented(n, desc)
272
+ elif isinstance(desc, BufferAOTInput):
273
+ r[desc.target] = n
274
+ return r
275
+
276
+
277
+ def get_param_nodes(graph: fx.Graph) -> list[fx.Node]:
278
+ """Get all parameter nodes from a graph as a list.
279
+
280
+ You can rely on this providing the correct order of parameters you need
281
+ to feed into the joint graph (at the very beginning of the argument list,
282
+ before buffers).
283
+
284
+ Args:
285
+ graph: The FX joint graph with descriptors
286
+
287
+ Returns:
288
+ A list of FX nodes representing all parameters in the graph.
289
+
290
+ Raises:
291
+ RuntimeError: If subclass tensors are encountered (not yet supported), as
292
+ it is not clear if you wanted each individual constituent piece of the
293
+ subclasses, or have them grouped up in some way.
294
+ """
295
+ return list(get_named_param_nodes(graph).values())
296
+
297
+
298
+ def get_buffer_nodes(graph: fx.Graph) -> list[fx.Node]:
299
+ """Get all buffer nodes from a graph as a list.
300
+
301
+ You can rely on this providing the correct order of buffers you need
302
+ to feed into the joint graph (after parameters).
303
+
304
+ Args:
305
+ graph: The FX joint graph with descriptors
306
+
307
+ Returns:
308
+ A list of FX nodes representing all buffers in the graph.
309
+
310
+ Raises:
311
+ RuntimeError: If subclass tensors are encountered (not yet supported), as
312
+ it is not clear if you wanted each individual constituent piece of the
313
+ subclasses, or have them grouped up in some way.
314
+ """
315
+ return list(get_named_buffer_nodes(graph).values())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_capture.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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._dispatch.python import enable_python_dispatcher
14
+ from torch._dynamo.utils import detect_fake_mode, lazy_format_graph_code
15
+ from torch._logging import getArtifactLogger, trace_structured
16
+ from torch._subclasses.functional_tensor import FunctionalTensorMode
17
+ from torch.fx.experimental.proxy_tensor import make_fx
18
+ from torchgen.utils import dataclass_repr
19
+
20
+ from .. import config
21
+ from .descriptors import AOTInput, BackwardTokenAOTInput
22
+ from .functional_utils import (
23
+ assert_functional_graph,
24
+ propagate_input_mutation_stacktraces,
25
+ )
26
+ from .graph_capture_wrappers import (
27
+ aot_dispatch_subclass,
28
+ create_functionalized_fn,
29
+ create_joint,
30
+ fn_input_mutations_to_outputs,
31
+ fn_prepped_for_autograd,
32
+ handle_effect_tokens_fn,
33
+ )
34
+ from .schemas import AOTConfig, FxValue, SubclassMeta, TraceFn, ViewAndMutationMeta
35
+ from .utils import (
36
+ call_and_expect_output_descs,
37
+ copy_fwd_metadata_to_bw_nodes,
38
+ fn_wrappers,
39
+ register_buffer_assignment_hook,
40
+ root_module_when_exporting_non_strict,
41
+ simple_wraps,
42
+ unlift_tokens,
43
+ )
44
+
45
+
46
+ aot_graphs_log = getArtifactLogger(__name__, "aot_graphs")
47
+
48
+
49
+ def _create_graph(
50
+ f,
51
+ args: list[torch.Tensor],
52
+ args_descs: Optional[
53
+ list[AOTInput]
54
+ ] = None, # keep compat with old clients; maybe we should split into two impls
55
+ *,
56
+ aot_config: AOTConfig,
57
+ ) -> torch.fx.GraphModule:
58
+ # FunctionalTensorMode must be enabled here.
59
+ # See Note [Accessing .grad_fn on FunctionalTensor]
60
+ out_descs = None
61
+
62
+ if args_descs is None:
63
+ inner_f = f
64
+ else:
65
+
66
+ @simple_wraps(f)
67
+ def inner_f(*args):
68
+ nonlocal out_descs
69
+ assert out_descs is None
70
+ out, out_descs = call_and_expect_output_descs(f, args)
71
+ return out
72
+
73
+ with (
74
+ enable_python_dispatcher(),
75
+ FunctionalTensorMode(
76
+ pre_dispatch=aot_config.pre_dispatch,
77
+ export=aot_config.is_export,
78
+ # Allow token discovery for joint fn tracing as tokens can be used in backward.
79
+ _allow_token_discovery=True,
80
+ ),
81
+ ):
82
+ fx_g = make_fx(
83
+ inner_f,
84
+ decomposition_table=aot_config.decompositions,
85
+ record_module_stack=True,
86
+ pre_dispatch=aot_config.pre_dispatch,
87
+ )(*args)
88
+
89
+ if args_descs is not None:
90
+ flat_args_descs, _ = pytree.tree_flatten(args_descs)
91
+ flat_out_descs, _ = pytree.tree_flatten(out_descs)
92
+
93
+ # Unfortunately, flat_args_descs is not guaranteed to match the
94
+ # number of actual arguments that show up on the FX graph.
95
+ # Specifically, allow_token_discovery=True means that we will
96
+ # silently add extra token arguments to the backwards graph.
97
+ #
98
+ # Although there are a few ways to detect what these tokens are,
99
+ # we are going to settle for something dodgy but simple to
100
+ # implement: match tangents_token placeholders specifically,
101
+ # as these are the only placeholders that are created by token
102
+ # discovery (NB: there is NO other code that treats this name
103
+ # as load bearing, so this is a bit naughty!)
104
+ #
105
+ # I originally wanted to detect tokens in exactly the same way
106
+ # that they are detected at normal runtime, but to be honest
107
+ # the normal runtime detection is pretty strange: it seems the
108
+ # backward tokens are not reliably at the end of the argument list
109
+ # but *precede* the RNG arguments (I don't understand why this is
110
+ # the case). And in unlift_tokens, token arguments are detected
111
+ # by seeing if they feed into an effects call! Dastardly. Why
112
+ # didn't we just introduce a new type.
113
+
114
+ i = 0
115
+ j = 0
116
+ for n in fx_g.graph.nodes:
117
+ if n.op == "placeholder":
118
+ if n.name.startswith("tangents_token"):
119
+ n.meta["desc"] = BackwardTokenAOTInput(j)
120
+ j += 1
121
+ else:
122
+ assert i < len(flat_args_descs), (
123
+ (fn_wrappers(inner_f)),
124
+ [n for n in fx_g.graph.nodes if n.op == "placeholder"],
125
+ flat_args_descs,
126
+ )
127
+ n.meta["desc"] = flat_args_descs[i]
128
+ i += 1
129
+ elif n.op == "output":
130
+ n.meta["desc"] = flat_out_descs
131
+
132
+ return fx_g
133
+
134
+
135
+ # TODO: Refactor the following code so detach() persists item_memo
136
+ def _detach_and_copy_item_memo(t):
137
+ detached_t = t.detach()
138
+ if hasattr(t, "item_memo"):
139
+ detached_t.item_memo = t.item_memo
140
+ return detached_t
141
+
142
+
143
+ def aot_dispatch_base_graph(
144
+ flat_fn: TraceFn,
145
+ flat_args: list[FxValue],
146
+ flat_args_descs: list[AOTInput],
147
+ aot_config: AOTConfig,
148
+ *,
149
+ fw_metadata: ViewAndMutationMeta,
150
+ ) -> tuple[torch.fx.GraphModule, list[FxValue], list[AOTInput], Optional[SubclassMeta]]:
151
+ # aot_dispatch_base requires functionalization, but doesn't need to handle as many cases as the autograd case.
152
+ # The cases that aot_dispatch_base doesn't need to handle include:
153
+ # - outputs that are aliases of graph intermediates
154
+ # - outputs that are aliases of graph inputs
155
+ # While cases that it does need to handle include:
156
+ # - input mutations (including when inputs are aliases of each other)
157
+ # - input metadata mutations
158
+ fn_to_trace = fn_input_mutations_to_outputs(
159
+ flat_fn,
160
+ flat_args_descs,
161
+ fw_metadata,
162
+ keep_data_input_mutations=aot_config.keep_inference_input_mutations,
163
+ )
164
+
165
+ fn_to_trace, updated_flat_args, updated_flat_args_descs = create_functionalized_fn(
166
+ fn_to_trace,
167
+ flat_args,
168
+ flat_args_descs,
169
+ meta=fw_metadata,
170
+ aot_config=aot_config,
171
+ trace_joint=False,
172
+ )
173
+
174
+ # TODO: replace with AOTDispatchSubclassWrapper once we refactor
175
+ # fn_input_mutations_to_outputs and create_functionalized_fn
176
+ # into CompilerWrappers.
177
+ (
178
+ fn_to_trace,
179
+ updated_flat_args_subclasses_desugared,
180
+ updated_flat_args_subclasses_desugared_descs,
181
+ maybe_subclass_meta,
182
+ ) = aot_dispatch_subclass(
183
+ fn_to_trace,
184
+ updated_flat_args,
185
+ updated_flat_args_descs,
186
+ is_joint_structure=False,
187
+ meta=fw_metadata,
188
+ fw_only=flat_fn,
189
+ )
190
+
191
+ (
192
+ fn_to_trace,
193
+ updated_flat_args_subclasses_desugared,
194
+ updated_flat_args_subclasses_desugared_descs,
195
+ ) = handle_effect_tokens_fn(
196
+ fn_to_trace,
197
+ updated_flat_args_subclasses_desugared,
198
+ updated_flat_args_subclasses_desugared_descs,
199
+ meta=fw_metadata,
200
+ trace_joint=False,
201
+ )
202
+
203
+ aot_graphs_log.debug(
204
+ "aot_config id: %s, fw_metadata=%s,subclass_metadata=%s",
205
+ str(aot_config.aot_id),
206
+ str(fw_metadata),
207
+ str(maybe_subclass_meta),
208
+ )
209
+
210
+ # We track buffer assignments when exporting in non-strict mode.
211
+ # (In contrast, strict mode errors on any attribute assignment.)
212
+ mod_when_exporting_non_strict = root_module_when_exporting_non_strict(flat_fn)
213
+ if aot_config.is_export and mod_when_exporting_non_strict is not None:
214
+ # For any buffer that is assigned, we want to associate it to the final proxy node
215
+ # that it is assigned to. This node can then be added as a buffer mutation output.
216
+ assigned_buffers: dict[str, str] = {}
217
+ hook = register_buffer_assignment_hook(
218
+ mod_when_exporting_non_strict, assigned_buffers
219
+ )
220
+
221
+ fake_mode = detect_fake_mode()
222
+ if fake_mode:
223
+ saved_updated_flat_args_subclasses_desugared = pytree.tree_map_only(
224
+ torch.Tensor,
225
+ _detach_and_copy_item_memo,
226
+ updated_flat_args_subclasses_desugared,
227
+ )
228
+ else:
229
+ saved_updated_flat_args_subclasses_desugared = pytree.tree_map_only(
230
+ torch.Tensor, lambda t: t.detach(), updated_flat_args_subclasses_desugared
231
+ )
232
+ saved_updated_flat_args_subclasses_desugared_descs = (
233
+ updated_flat_args_subclasses_desugared_descs
234
+ )
235
+
236
+ fw_module = _create_graph(
237
+ fn_to_trace,
238
+ updated_flat_args_subclasses_desugared,
239
+ updated_flat_args_subclasses_desugared_descs,
240
+ aot_config=aot_config,
241
+ )
242
+
243
+ if aot_config.is_export and mod_when_exporting_non_strict is not None:
244
+ # We update metadata to consider any assigned buffers as buffer mutations.
245
+ i = len(dict(mod_when_exporting_non_strict.named_parameters()))
246
+ for name, _ in mod_when_exporting_non_strict.named_buffers():
247
+ if name in assigned_buffers and not fw_metadata.input_info[i].mutates_data: # type: ignore[possibly-undefined]
248
+ fw_metadata.input_info[i] = dataclasses.replace(
249
+ fw_metadata.input_info[i], mutates_data=True
250
+ )
251
+ fw_metadata.num_mutated_inp_runtime_indices += 1
252
+ i += 1
253
+
254
+ # We add nodes corresponding to buffer assignments as output nodes in the graph.
255
+ add_nodes = []
256
+ output_node = list(fw_module.graph.nodes)[-1]
257
+ for name in assigned_buffers.values(): # type: ignore[possibly-undefined]
258
+ for node in fw_module.graph.nodes:
259
+ if node.name == name:
260
+ add_nodes.append(node)
261
+ node.users[output_node] = None
262
+ output_node.args = ((*add_nodes, *output_node.args[0]),)
263
+
264
+ hook.remove() # type: ignore[possibly-undefined]
265
+
266
+ # As long as we opted to remove input mutations, then
267
+ # there should be *NO* mutating ops in the graph at this point.
268
+ copy_count = assert_functional_graph(fw_module.graph)
269
+ fw_module.graph.eliminate_dead_code()
270
+ fw_module.recompile()
271
+
272
+ copy_count2 = assert_functional_graph(fw_module.graph)
273
+ propagate_input_mutation_stacktraces(fw_module.graph)
274
+
275
+ # See Note [Side-Effectful Tokens in AOTAutograd]
276
+ num_tokens = len(fw_metadata.tokens)
277
+ if num_tokens != 0 and config.unlift_effect_tokens:
278
+ unlift_tokens(fw_module, fw_metadata, aot_config)
279
+ saved_updated_flat_args_subclasses_desugared = (
280
+ saved_updated_flat_args_subclasses_desugared[num_tokens:]
281
+ )
282
+ saved_updated_flat_args_subclasses_desugared_descs = (
283
+ saved_updated_flat_args_subclasses_desugared_descs[num_tokens:]
284
+ )
285
+
286
+ assert copy_count == copy_count2
287
+
288
+ if aot_config.enable_log:
289
+ aot_graphs_log.info(
290
+ "%s",
291
+ lazy_format_graph_code(
292
+ "Forward graph",
293
+ fw_module,
294
+ aot_config.aot_id,
295
+ include_stride=True,
296
+ include_device=True,
297
+ colored=True,
298
+ ),
299
+ )
300
+
301
+ trace_structured(
302
+ "artifact",
303
+ metadata_fn=lambda: {
304
+ "name": "aot_forward_graph_fw_metadata",
305
+ "encoding": "string",
306
+ },
307
+ payload_fn=lambda: dataclass_repr(fw_metadata),
308
+ )
309
+ if maybe_subclass_meta is not None:
310
+ trace_structured(
311
+ "artifact",
312
+ metadata_fn=lambda: {
313
+ "name": "aot_forward_graph_fw_subclass_metadata",
314
+ "encoding": "string",
315
+ },
316
+ payload_fn=lambda: dataclass_repr(maybe_subclass_meta),
317
+ )
318
+
319
+ trace_structured(
320
+ "aot_inference_graph",
321
+ payload_fn=lambda: fw_module.print_readable(
322
+ print_output=False,
323
+ include_stride=True,
324
+ include_device=True,
325
+ expanded_def=True,
326
+ ),
327
+ )
328
+
329
+ # TODO: should factor this into a separate function for export that always only returns just the graph.
330
+ if aot_config.is_export:
331
+ assert maybe_subclass_meta is None, (
332
+ "aot_export_module does not support tensor subclass inputs for now."
333
+ )
334
+ return (
335
+ fw_module,
336
+ saved_updated_flat_args_subclasses_desugared,
337
+ saved_updated_flat_args_subclasses_desugared_descs,
338
+ maybe_subclass_meta,
339
+ )
340
+
341
+
342
+ # Has the precondition that there
343
+ # are no duplicate arguments in flat_args (e.g., the same Tensor
344
+ # object never shows up twice. However, two tensor inputs MAY alias
345
+ # the same storage, so long as they have separate TensorImpls.)
346
+ def aot_dispatch_autograd_graph(
347
+ flat_fn: TraceFn,
348
+ flat_args: list[Any],
349
+ flat_args_descs: list[AOTInput],
350
+ aot_config: AOTConfig,
351
+ *,
352
+ fw_metadata: ViewAndMutationMeta,
353
+ ) -> tuple[
354
+ torch.fx.GraphModule,
355
+ tuple[list[Any], list[Any]],
356
+ tuple[list[AOTInput], list[AOTInput]],
357
+ Optional[SubclassMeta],
358
+ ]:
359
+ # NB: flat_fn here is the original user function (as far as
360
+ # aot_module_simplified is concerned)
361
+
362
+ # traced_tangents corresponds to the set of outputs in the traced forward that should get grad_outputs in the traced backward.
363
+ # It includes outputs of the original forward, *and* any updated inputs due to input mutations.
364
+ # However, it does *not* include any outputs that are aliases of inputs or intermediates, or any metadata-only input mutations.
365
+ joint_inputs = (flat_args, fw_metadata.traced_tangents)
366
+ joint_inputs_descs = (flat_args_descs, fw_metadata.traced_tangents_descs)
367
+
368
+ fn_prepared_for_autograd = fn_prepped_for_autograd(
369
+ flat_fn,
370
+ flat_args_descs,
371
+ fw_metadata,
372
+ )
373
+ joint_fn_to_trace = create_joint(
374
+ fn_prepared_for_autograd, flat_args_descs, aot_config=aot_config
375
+ )
376
+ joint_fn_handle = joint_fn_to_trace.handle
377
+
378
+ joint_fn_to_trace, updated_joint_inputs, updated_joint_inputs_descs = (
379
+ create_functionalized_fn(
380
+ joint_fn_to_trace,
381
+ joint_inputs,
382
+ joint_inputs_descs,
383
+ meta=fw_metadata,
384
+ aot_config=aot_config,
385
+ trace_joint=True,
386
+ joint_fn_handle=joint_fn_handle,
387
+ )
388
+ )
389
+
390
+ # TODO: replace with AOTDispatchSubclassWrapper once we refactor
391
+ # fn_input_mutations_to_outputs and create_functionalized_fn
392
+ # into CompilerWrappers.
393
+ subclass_tracing_info = aot_dispatch_subclass(
394
+ joint_fn_to_trace,
395
+ updated_joint_inputs,
396
+ updated_joint_inputs_descs,
397
+ is_joint_structure=True,
398
+ meta=fw_metadata,
399
+ fw_only=flat_fn,
400
+ )
401
+
402
+ joint_fn_to_trace = subclass_tracing_info.plain_tensor_trace_fn
403
+ updated_joint_inputs = subclass_tracing_info.plain_tensor_args
404
+ updated_joint_inputs_descs = subclass_tracing_info.plain_tensor_args_descs
405
+
406
+ (joint_fn_to_trace, updated_joint_inputs, updated_joint_inputs_descs) = (
407
+ handle_effect_tokens_fn(
408
+ joint_fn_to_trace,
409
+ updated_joint_inputs,
410
+ updated_joint_inputs_descs,
411
+ meta=fw_metadata,
412
+ trace_joint=True,
413
+ )
414
+ )
415
+
416
+ # When we call _create_graph, this may mutate the metadata of joint
417
+ # inputs. But callers are expecting to get the original joint inputs. So
418
+ # we make aliases of all the inputs to make sure we have a copy that
419
+ # doesn't get modified.
420
+ #
421
+ # This destroys requires_grad/grad_fn information. However, backends
422
+ # beneath AOTAutograd are indifferent to this information, so it doesn't
423
+ # matter.
424
+
425
+ fake_mode = detect_fake_mode()
426
+ if fake_mode:
427
+ saved_updated_joint_inputs = pytree.tree_map_only(
428
+ torch.Tensor, _detach_and_copy_item_memo, updated_joint_inputs
429
+ )
430
+ else:
431
+ saved_updated_joint_inputs = pytree.tree_map_only(
432
+ torch.Tensor, lambda t: t.detach(), updated_joint_inputs
433
+ )
434
+ maybe_subclass_meta = subclass_tracing_info.maybe_subclass_meta
435
+
436
+ fx_g = _create_graph(
437
+ joint_fn_to_trace,
438
+ updated_joint_inputs,
439
+ updated_joint_inputs_descs,
440
+ aot_config=aot_config,
441
+ )
442
+
443
+ # There should be *NO* mutating ops in the graph at this point.
444
+ assert_functional_graph(fx_g.graph)
445
+
446
+ # Redundant with the check above, but worth having in case tracing introduced
447
+ # a fake tensor. Unlikely.
448
+ # See Note: [Fake Modules and AOTAutograd]
449
+ torch._dynamo.utils.assert_no_fake_params_or_buffers(fx_g)
450
+ fx_g.graph.eliminate_dead_code()
451
+ copy_fwd_metadata_to_bw_nodes(fx_g)
452
+ fx_g.recompile()
453
+
454
+ # TODO: in AOTAutograd, we create metadata like _indices_of_inps_to_detach to detect
455
+ # when we need to manually detach() some inputs in the forward.
456
+ # Higher order ops might eventually need to do the same.
457
+ if aot_config.is_export:
458
+ assert maybe_subclass_meta is None, (
459
+ "aot_export_module does not support tensor subclass inputs for now."
460
+ )
461
+ return (
462
+ fx_g,
463
+ saved_updated_joint_inputs,
464
+ updated_joint_inputs_descs,
465
+ maybe_subclass_meta,
466
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py ADDED
@@ -0,0 +1,1372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 AbstractContextManager, contextmanager, ExitStack, nullcontext
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable, cast, Optional, TypeVar, 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
+ _proxy_tensor_disable_update_tensor_tracker,
29
+ maybe_disable_thunkify,
30
+ maybe_enable_thunkify,
31
+ )
32
+ from torch.fx.experimental.symbolic_shapes import (
33
+ guard_or_true,
34
+ PropagateUnbackedSymInts,
35
+ sym_eq,
36
+ )
37
+ from torch.nn.utils import stateless
38
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
39
+ from torch.utils._pytree import TreeSpec
40
+
41
+ from .. import config
42
+ from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata
43
+ from .descriptors import (
44
+ AOTInput,
45
+ AOTOutput,
46
+ BackwardTokenAOTOutput,
47
+ ForwardTokenAOTInput,
48
+ ForwardTokenAOTOutput,
49
+ GradAOTOutput,
50
+ InputMutationAOTOutput,
51
+ IntermediateBaseAOTOutput,
52
+ PhiloxBackwardBaseOffsetAOTInput,
53
+ PhiloxBackwardSeedAOTInput,
54
+ PhiloxForwardBaseOffsetAOTInput,
55
+ PhiloxForwardSeedAOTInput,
56
+ PhiloxUpdatedBackwardOffsetAOTOutput,
57
+ PhiloxUpdatedForwardOffsetAOTOutput,
58
+ )
59
+ from .functional_utils import (
60
+ _check_if_mutation_can_be_in_graph,
61
+ are_all_mutations_hidden_from_autograd,
62
+ are_all_mutations_under_no_grad_or_inference_mode,
63
+ from_fun,
64
+ has_data_mutation,
65
+ has_metadata_mutation,
66
+ is_fun,
67
+ sync_functional_tensor,
68
+ to_fun,
69
+ was_inductor_storage_resized,
70
+ )
71
+ from .logging_utils import setup_stacktrace_preservation_hooks
72
+ from .schemas import (
73
+ AOTConfig,
74
+ FxValue,
75
+ JointTraceFn,
76
+ MutationType,
77
+ OutputType,
78
+ PreppedForAutogradTraceFn,
79
+ SubclassMeta,
80
+ SubclassTracingInfo,
81
+ TraceFn,
82
+ ViewAndMutationMeta,
83
+ )
84
+ from .subclass_utils import (
85
+ create_subclass_meta,
86
+ remap_unwrapped_subclass_arg_indices,
87
+ requires_subclass_dispatch,
88
+ unwrap_tensor_subclasses,
89
+ wrap_tensor_subclasses_maybe_joint,
90
+ )
91
+ from .utils import (
92
+ call_and_expect_output_descs,
93
+ maybe_to_fresh_input,
94
+ simple_wraps,
95
+ without_output_descs,
96
+ )
97
+
98
+
99
+ # This function returns a new function that returns mutated inputs as outputs.
100
+ # if keep_data_input_mutations is set, then we assume that data-only mutations
101
+ # will be left in the graph, and we only return metadata-mutated inputs as outputs.
102
+ def fn_input_mutations_to_outputs(
103
+ fn: Callable,
104
+ args_descs: list[AOTInput],
105
+ meta: ViewAndMutationMeta,
106
+ keep_data_input_mutations: bool,
107
+ ) -> Any:
108
+ @simple_wraps(fn)
109
+ def inner_fn(*args):
110
+ outs, outs_descs = call_and_expect_output_descs(fn, args)
111
+ assert len(meta.output_info) == len(outs)
112
+ # The compiled fw will return mutated input tensors, *including* metadata-only mutation.
113
+ # However, if keep_data_input_mutations is set, the compiled fw only needs to return metadata-mutated inputs.
114
+ # (because data-only input mutations are handled directly in the compiled graph)
115
+ mutated_input_pairs = [
116
+ (x, InputMutationAOTOutput(src))
117
+ for (i, (x, src)) in enumerate(zip(args, args_descs))
118
+ if i in meta.mutated_inp_runtime_indices
119
+ ]
120
+ if mutated_input_pairs:
121
+ mutated_inputs_to_return, mutated_inputs_to_return_descs = zip(
122
+ *mutated_input_pairs
123
+ )
124
+ else:
125
+ mutated_inputs_to_return, mutated_inputs_to_return_descs = (), ()
126
+ return (
127
+ (*mutated_inputs_to_return, *outs),
128
+ (*mutated_inputs_to_return_descs, *outs_descs),
129
+ )
130
+
131
+ return inner_fn
132
+
133
+
134
+ @contextmanager
135
+ def disable_autocast():
136
+ with ExitStack() as stack:
137
+ autocast_enabled_devices = torch._C._autocast_supported_devices()
138
+ for device_type in autocast_enabled_devices:
139
+ if hasattr(torch, device_type):
140
+ stack.enter_context(torch.amp.autocast(device_type, enabled=False))
141
+ yield
142
+
143
+
144
+ # This function takes in a fn with external aliasing and mutation,
145
+ # and returns a new fn with no external aliasing and mutation,
146
+ # as needed for autograd.
147
+ # The main transformations are:
148
+ # - Return mutated inputs as extra outputs
149
+ # - Clone mutated inputs that require gradients,
150
+ # because autograd will require us to pass the pre-mutated inputs into autograd.grad
151
+ # - Return intermediate bases of outputs as additional outputs,
152
+ # needed to appease autograd.Function
153
+ # The new function returns:
154
+ # (1) The updated outputs
155
+ # (2) A boolean mask of len(new_fn_outputs),
156
+ # that can be used to tell autograd.grad which outputs should get tangents
157
+ # if we trace the backward.
158
+ def fn_prepped_for_autograd(
159
+ fn: TraceFn,
160
+ args_descs: list[AOTInput],
161
+ meta: ViewAndMutationMeta,
162
+ ) -> PreppedForAutogradTraceFn:
163
+ @simple_wraps(fn)
164
+ def inner_fn(*args):
165
+ args_maybe_cloned = [
166
+ maybe_to_fresh_input(i, t, meta) for i, t in enumerate(args)
167
+ ]
168
+
169
+ outs, outs_descs = call_and_expect_output_descs(fn, args_maybe_cloned)
170
+ assert isinstance(outs, (tuple, list))
171
+ outs = list(outs)
172
+ assert len(meta.output_info) == len(outs)
173
+
174
+ mutated_input_pairs = [
175
+ (x, InputMutationAOTOutput(src))
176
+ for (i, (x, src)) in enumerate(zip(args_maybe_cloned, args_descs))
177
+ if i in meta.mutated_inp_runtime_indices
178
+ ]
179
+ if mutated_input_pairs:
180
+ mutated_inputs_to_return, mutated_inputs_to_return_descs = zip(
181
+ *mutated_input_pairs
182
+ )
183
+ else:
184
+ mutated_inputs_to_return, mutated_inputs_to_return_descs = (), ()
185
+
186
+ intermediate_bases = []
187
+ intermediate_bases_descs = []
188
+ for o, info, o_desc in zip(outs, meta.output_info, outs_descs):
189
+ if info.output_type == OutputType.alias_of_intermediate_save_as_output:
190
+ assert isinstance(o, torch.Tensor), (
191
+ f"Expected tensor for intermediate base, got {type(o)}"
192
+ )
193
+ intermediate_bases.append(o._base)
194
+ intermediate_bases_descs.append(IntermediateBaseAOTOutput(o_desc))
195
+
196
+ assert meta.num_intermediate_bases == len(intermediate_bases)
197
+
198
+ # the compiled forward should return (mutated_inputs, user_outs, intermediate_bases)
199
+ fw_outs_to_return = *mutated_inputs_to_return, *outs, *intermediate_bases
200
+ fw_outs_to_return_descs = (
201
+ *mutated_inputs_to_return_descs,
202
+ *outs_descs,
203
+ *intermediate_bases_descs,
204
+ )
205
+
206
+ # Also return a boolean mask specifying which outputs to this function will be used as tangents
207
+ mutated_inputs_grad_mask = [
208
+ meta.input_info[meta.mutated_inp_runtime_indices[i]].mutates_data
209
+ and meta.input_info[meta.mutated_inp_runtime_indices[i]].requires_grad
210
+ for (i, x) in enumerate(mutated_inputs_to_return)
211
+ ]
212
+
213
+ # Pass any (non-aliased) outputs in as tangents, since they'll be returned as outputs in the fw
214
+ # For outputs that are aliases of intermediates, we will have returned the output's _base as an output in the graph instead,
215
+ # which we *should* send to grad()
216
+ output_grad_mask = [
217
+ meta.output_info[i].output_type
218
+ in [
219
+ OutputType.non_alias,
220
+ OutputType.unsafe_view_alias,
221
+ OutputType.custom_function_view,
222
+ ]
223
+ # Also, only tensor outputs should participate in the backward
224
+ # (in particular, Symint outputs in the forward graph shouldn't get tangents)
225
+ and issubclass(meta.output_info[i].raw_type, Tensor)
226
+ and meta.output_info[i].requires_grad
227
+ for (i, x) in enumerate(outs)
228
+ ]
229
+
230
+ intermediate_base_grad_mask = [True for _ in range(len(intermediate_bases))]
231
+
232
+ out_grad_mask = (
233
+ mutated_inputs_grad_mask + output_grad_mask + intermediate_base_grad_mask
234
+ )
235
+ assert len(out_grad_mask) == len(fw_outs_to_return)
236
+
237
+ # Take care to grab and sync the updated inputs from primals_after_cloning (the inputs we actually mutate!)
238
+ # and not primals (the preserved inputs, pre-mutation, that we pass to grad())
239
+ # This is annoying: our joint function needs to be aware of functionalization
240
+ # (syncing mutated inputs before calling autograd.grad())
241
+ # In theory, we could make the autograd engine do this automatically, although that probably isn't any cleaner.
242
+ for arg in args_maybe_cloned:
243
+ if not isinstance(arg, Tensor):
244
+ continue
245
+ sync_functional_tensor(arg)
246
+
247
+ return (fw_outs_to_return, out_grad_mask), (
248
+ fw_outs_to_return_descs,
249
+ out_grad_mask,
250
+ )
251
+
252
+ return inner_fn
253
+
254
+
255
+ @dataclass
256
+ class JointFnHandle:
257
+ post_forward: Optional[Callable] = None
258
+
259
+
260
+ # Given a fn, computes the joint.
261
+ # NOTE: fn is expects the following behavior:
262
+ # (1) fn() needs to return a tuple of (outs, mask),
263
+ # where `mask` tells us which outputs are meant to have tangents.
264
+ # we don't know this info automatically, because we don't actually want to blindly
265
+ # compute tangents for every output that requires grad.
266
+ # Specifically, outputs that alias inputs won't participate in the backward and get tangents.
267
+ # (2) fn() cannot mutate any inputs that require gradient.
268
+ # otherwise, when we compute autograd.grad(), we will not take those input mutations into account
269
+ # (the way this is handled is that we ensure any inputs that normally get mutated are cloned first)
270
+ def create_joint(
271
+ fn: Any, # PreppedForAutogradTraceFn
272
+ primals_descs: Optional[list[AOTInput]] = None,
273
+ *,
274
+ aot_config: AOTConfig,
275
+ ) -> Any: # JointTraceFn
276
+ joint_fn_handle = JointFnHandle()
277
+
278
+ # post_forward
279
+ # NB: this type is inaccurate when primals_descs is None
280
+ @simple_wraps(fn)
281
+ def inner_fn(
282
+ primals: list[FxValue], tangents: list[FxValue]
283
+ ) -> tuple[
284
+ tuple[list[FxValue], list[Optional[Tensor]]],
285
+ tuple[list[AOTOutput], list[Optional[AOTOutput]]],
286
+ ]:
287
+ outs_descs = None
288
+ if primals_descs is None:
289
+ outs, tangent_mask = fn(*primals)
290
+ assert not pytree.tree_any(lambda x: isinstance(x, AOTOutput), tangent_mask)
291
+ else:
292
+ (outs, tangent_mask), (outs_descs, _) = call_and_expect_output_descs(
293
+ fn, primals
294
+ )
295
+
296
+ # TODO: I think this hook can also be eliminated now
297
+ if joint_fn_handle and joint_fn_handle.post_forward:
298
+ joint_fn_handle.post_forward(primals)
299
+
300
+ assert len(tangent_mask) == len(outs)
301
+ outs_to_grad = [
302
+ o for needs_tangent, o in zip(tangent_mask, outs) if needs_tangent
303
+ ]
304
+ assert len(outs_to_grad) == len(tangents)
305
+
306
+ # Get the inputs that need gradients
307
+ grad_primals: list[torch.Tensor] = []
308
+ inputs_needs_grads = []
309
+ # Note that we're not using primals here,
310
+ # being carefully not to pass any mutated inputs into autograd.grad()
311
+ for p in primals:
312
+ if isinstance(p, Tensor) and p.requires_grad:
313
+ inputs_needs_grads.append(True)
314
+ assert isinstance(p, torch.Tensor) # Help mypy understand the type
315
+ grad_primals.append(p)
316
+ else:
317
+ inputs_needs_grads.append(False)
318
+
319
+ # Get the outputs that need gradients
320
+ needed_outs = []
321
+ needed_tangents = []
322
+ for out, tangent in zip(outs_to_grad, tangents):
323
+ if isinstance(out, Tensor) and out.requires_grad:
324
+ # A bit sketchy, but fixes e.g. test_aot_autograd_exhaustive_matmul_cpu_float32
325
+ # The issue is that we are sensitive to decomps that don't accurately maintain
326
+ # their output's _base.shape compared to eager mode, and this helps mitigate a bit.
327
+ # The guard_or_true also sketchy; if unbacked
328
+ # symints are involved, we're just going to assume that the
329
+ # decomps setup the base shape correctly
330
+
331
+ # Return out if the result of out.shape==tangent.shape is unknown or known to be true.
332
+ # otherwise if its a known false return out.view(tangent.shape).
333
+ # tangent should also be a tensor since it corresponds to a tensor output
334
+ assert isinstance(tangent, torch.Tensor), (
335
+ f"Expected tensor tangent, got {type(tangent)}"
336
+ )
337
+ needed_outs.append(
338
+ out
339
+ if guard_or_true(sym_eq(out.shape, tangent.shape))
340
+ else out.view(tangent.shape)
341
+ )
342
+ needed_tangents.append(tangent)
343
+
344
+ setup_stacktrace_preservation_hooks([out.grad_fn for out in needed_outs])
345
+
346
+ if config.functionalize_rng_ops:
347
+ PhiloxStateTracker.mark_beginning_of_backward()
348
+ backward_out: tuple[Tensor, ...] = ()
349
+ # Call the backwards pass
350
+ if grad_primals:
351
+ functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode(
352
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
353
+ )
354
+ if functional_tensor_mode is not None:
355
+ # Side-Effect Tokens:
356
+ # We want to have independent chains of tokens for forward and backward.
357
+ # functional_tensor_mode._tokens is used by both.
358
+ # We memoize the result tokens of forward in functional_tensor_mode._tokens_forward_output,
359
+ # to return them as joint graph outputs.
360
+ # We clean functional_tensor_mode._tokens before backward, to prevent reuse of forward tokens in backward.
361
+ # Joint graph tracing allows tokens discovery,
362
+ # So all the tokens in backward will be created and added as a graph inputs during tracing.
363
+ functional_tensor_mode._tokens_forward_output = (
364
+ functional_tensor_mode._tokens
365
+ )
366
+ functional_tensor_mode._tokens = {}
367
+
368
+ with (
369
+ set_partitioner_tag_is_backward(),
370
+ fx_traceback.preserve_node_meta(),
371
+ ExitStack() as stack,
372
+ ):
373
+ backward_pass_autocast = torch._functorch.config.backward_pass_autocast
374
+ if backward_pass_autocast == "same_as_forward":
375
+ # Use the ambient autocast mode(s)
376
+ pass
377
+ elif backward_pass_autocast == "off":
378
+ stack.enter_context(disable_autocast())
379
+ else:
380
+ # Disable autocast, then enable anything in `backward_pass_autocast`.
381
+ stack.enter_context(disable_autocast())
382
+ assert isinstance(backward_pass_autocast, list)
383
+ for kwargs in backward_pass_autocast:
384
+ assert isinstance(kwargs, dict)
385
+ stack.enter_context(torch.amp.autocast(**kwargs))
386
+
387
+ # for full graph export, we always export a joint graph where we assume no tangents are needed.
388
+ if aot_config.no_tangents:
389
+ assert len(needed_tangents) == 1 and needed_tangents[0].numel() == 1
390
+ backward_out = torch.autograd.grad(
391
+ needed_outs,
392
+ grad_primals,
393
+ allow_unused=True,
394
+ )
395
+ else:
396
+ backward_out = torch.autograd.grad(
397
+ needed_outs,
398
+ grad_primals,
399
+ grad_outputs=needed_tangents,
400
+ allow_unused=True,
401
+ )
402
+ backward_out_iter = iter(backward_out)
403
+ final_outs = (
404
+ outs,
405
+ [next(backward_out_iter) if i else None for i in inputs_needs_grads],
406
+ )
407
+ if primals_descs is None:
408
+ return final_outs # type: ignore[return-value]
409
+ assert outs_descs is not None
410
+ return final_outs, (
411
+ outs_descs,
412
+ [
413
+ # TODO: ideally we do know this is DifferentiableAOTInput
414
+ # but this is quite an involved refactor
415
+ GradAOTOutput(desc) if i else None # type: ignore[arg-type]
416
+ for i, desc in zip(inputs_needs_grads, primals_descs)
417
+ ],
418
+ )
419
+
420
+ @simple_wraps(inner_fn)
421
+ def inner_fn_with_anomaly(
422
+ primals: list[FxValue], tangents: list[FxValue]
423
+ ) -> tuple[
424
+ tuple[list[FxValue], list[Optional[Tensor]]],
425
+ tuple[list[AOTOutput], list[Optional[AOTOutput]]],
426
+ ]:
427
+ with fx_traceback.preserve_node_meta(), warnings.catch_warnings():
428
+ warnings.filterwarnings("ignore", "Anomaly Detection has been enabled.")
429
+ with torch.autograd.detect_anomaly(check_nan=False):
430
+ return inner_fn(primals, tangents)
431
+
432
+ inner_fn_with_anomaly.handle = joint_fn_handle # type: ignore[attr-defined]
433
+
434
+ return cast(JointTraceFn, inner_fn_with_anomaly) # deal with 'handle' property
435
+
436
+
437
+ def create_functionalized_rng_ops_wrapper(
438
+ func, args, args_descs, trace_joint=True
439
+ ) -> Any:
440
+ # Functionalization of rng ops changes the calling convention of the joint graph.
441
+ # It goes from (primals, tangents) to (seed, offset, primals, tangents)
442
+ # At runtime, we pass on the current seed and offset. This is hidden from
443
+ # the user.
444
+ fake_mode_det = detect_fake_mode()
445
+ fake_mode: AbstractContextManager[Any] = nullcontext()
446
+ if fake_mode_det is not None:
447
+ fake_mode = fake_mode_det
448
+
449
+ def override_get_rng_state(device: Union[int, str, torch.device] = "cuda"):
450
+ out = PhiloxStateTracker.get_state_as_tensor()
451
+ return out
452
+
453
+ def override_set_rng_state(x, device: Union[int, str, torch.device] = "cuda"):
454
+ PhiloxStateTracker.set_state_from_tensor(x)
455
+
456
+ def append_rng_offsets(outs, outs_descs):
457
+ if trace_joint:
458
+ # outs signature before: Tuple(fwd_outputs), Tuple(bwd_outputs)
459
+ # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset), Tuple(bwd_offset, new_bwd_rng_offset)
460
+ return (
461
+ (
462
+ (*outs[0], PhiloxStateTracker.get_updated_fwd_offset()),
463
+ (*outs[1], PhiloxStateTracker.get_updated_bwd_offset()),
464
+ ),
465
+ (
466
+ (*outs_descs[0], PhiloxUpdatedForwardOffsetAOTOutput()),
467
+ (*outs_descs[1], PhiloxUpdatedBackwardOffsetAOTOutput()),
468
+ ),
469
+ )
470
+ else:
471
+ # outs signature before: Tuple(fwd_outputs)
472
+ # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset)
473
+ return (
474
+ (*outs, PhiloxStateTracker.get_updated_fwd_offset()),
475
+ (*outs_descs, PhiloxUpdatedForwardOffsetAOTOutput()),
476
+ )
477
+
478
+ def traced_joint(
479
+ primals, tangents, fwd_seed, fwd_base_offset, bwd_seed, bwd_base_offset
480
+ ):
481
+ with (
482
+ patch("torch.cuda.get_rng_state", override_get_rng_state),
483
+ patch("torch.cuda.set_rng_state", override_set_rng_state),
484
+ ):
485
+ return append_rng_offsets(*func(primals, tangents))
486
+
487
+ def traced_forward(*primals_fwd_seed_fwd_base_offset):
488
+ # The signature is (*primals, seed, offset)
489
+ with (
490
+ patch("torch.cuda.get_rng_state", override_get_rng_state),
491
+ patch("torch.cuda.set_rng_state", override_set_rng_state),
492
+ ):
493
+ return append_rng_offsets(*func(*primals_fwd_seed_fwd_base_offset[:-2]))
494
+
495
+ if trace_joint:
496
+ # Get the current seed and offset to setup tracing.
497
+ fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
498
+ fake_mode
499
+ )
500
+ bwd_seed, bwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
501
+ fake_mode
502
+ )
503
+ PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward")
504
+ PhiloxStateTracker.record_state(bwd_seed, bwd_base_offset, "backward")
505
+ return (
506
+ traced_joint,
507
+ (
508
+ *args,
509
+ fwd_seed,
510
+ fwd_base_offset,
511
+ bwd_seed,
512
+ bwd_base_offset,
513
+ ),
514
+ (
515
+ *args_descs,
516
+ PhiloxForwardSeedAOTInput(),
517
+ PhiloxForwardBaseOffsetAOTInput(),
518
+ PhiloxBackwardSeedAOTInput(),
519
+ PhiloxBackwardBaseOffsetAOTInput(),
520
+ ),
521
+ )
522
+ else:
523
+ # Get the current seed and offset to setup tracing.
524
+ fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple(
525
+ fake_mode
526
+ )
527
+ PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward")
528
+ return (
529
+ traced_forward,
530
+ (*args, fwd_seed, fwd_base_offset),
531
+ (
532
+ *args_descs,
533
+ PhiloxForwardSeedAOTInput(),
534
+ PhiloxForwardBaseOffsetAOTInput(),
535
+ ),
536
+ )
537
+
538
+
539
+ @contextmanager
540
+ def set_partitioner_tag(tag: str):
541
+ meta_key = "partitioner_tag"
542
+ assert fx_traceback.has_preserved_node_meta()
543
+
544
+ original_val = fx_traceback.current_meta.get(meta_key, None)
545
+ fx_traceback.current_meta[meta_key] = tag
546
+ try:
547
+ yield
548
+ finally:
549
+ fx_traceback.current_meta[meta_key] = original_val
550
+
551
+
552
+ def set_partitioner_tag_is_backward():
553
+ return set_partitioner_tag("is_backward")
554
+
555
+
556
+ def set_partitioner_tag_must_be_in_backward():
557
+ return set_partitioner_tag("must_be_in_backward")
558
+
559
+
560
+ def set_partitioner_tag_must_be_in_forward():
561
+ return set_partitioner_tag("must_be_in_forward")
562
+
563
+
564
+ @dataclass
565
+ class MutationCounters:
566
+ mc_data: int
567
+ mc_storage: int
568
+ mc_inductor_storage_resized: int
569
+
570
+
571
+ T = TypeVar("T")
572
+
573
+
574
+ def sc_visit(
575
+ t, fn: Callable[[Tensor], T], reduce_fn: Callable[[T, T], T], accum_init: T
576
+ ) -> T:
577
+ if not is_traceable_wrapper_subclass(t):
578
+ return fn(t)
579
+
580
+ accum = accum_init
581
+
582
+ def visit(e):
583
+ if not is_traceable_wrapper_subclass(e):
584
+ nonlocal accum
585
+ accum = reduce_fn(accum, fn(e))
586
+ return
587
+
588
+ for a in e.__tensor_flatten__()[0]:
589
+ visit(getattr(e, a))
590
+
591
+ visit(t)
592
+ return accum
593
+
594
+
595
+ def _get_mutation_counter(t) -> int:
596
+ return sc_visit(
597
+ t,
598
+ lambda t: torch._functionalize_mutation_counter(t.elem), # type: ignore[attr-defined]
599
+ lambda l, r: max(l, r),
600
+ -1,
601
+ )
602
+
603
+
604
+ def _get_storage_changed_counter(t) -> int:
605
+ return sc_visit(
606
+ t,
607
+ lambda t: torch._functionalize_storage_changed_counter(t.elem), # type: ignore[attr-defined]
608
+ lambda l, r: max(l, r),
609
+ -1,
610
+ )
611
+
612
+
613
+ def _get_inductor_storage_resized_counter(t) -> int:
614
+ return sc_visit(
615
+ t,
616
+ lambda t: torch._functionalize_inductor_storage_resized_counter(t.elem), # type: ignore[attr-defined]
617
+ lambda l, r: max(l, r),
618
+ -1,
619
+ )
620
+
621
+
622
+ def _get_mutation_counters(t) -> MutationCounters:
623
+ return MutationCounters(
624
+ _get_mutation_counter(t),
625
+ _get_storage_changed_counter(t),
626
+ _get_inductor_storage_resized_counter(t),
627
+ )
628
+
629
+
630
+ def apply_in_graph_mutations(
631
+ input_info,
632
+ inpt_old,
633
+ inpt_new,
634
+ f_inpt,
635
+ input_idx,
636
+ mcs: Optional[MutationCounters] = None,
637
+ applied_mcs: Optional[MutationCounters] = None,
638
+ ):
639
+ assert input_info.mutation_type == MutationType.MUTATED_IN_GRAPH
640
+ # See Note [set_() Input Mutations in AOTAutograd]
641
+ # all mutations on the input must be under no_grad, so it is safe to put in the graph
642
+ # Here, we're saying that if an input experienced a set call, inp.set_(other),
643
+ # then we can effectively not have to worry about whether its data was mutated.
644
+ # There are 3 cases:
645
+ # (1) We mutate inp *after* the set_() call. other is a graph intermediate.
646
+ # In this case, we're not really mutating the input storage of "inp";
647
+ # we're mutating the storage of an intermdiate value (other),
648
+ # and slamming that storage into the input tensor. So no data mutation is necessary.
649
+ # (2) We mutate inp *after* the set_() call. other is a graph *input*.
650
+ # In this case, the data mutation will be properly handled in the runtime
651
+ # epilogue during the processing of "other"
652
+ # (3) We mutate inp *before* the set_() call.
653
+ # This case is *not* currently handled.
654
+ if input_info.mutates_storage_metadata:
655
+ if mcs is None or mcs.mc_storage > applied_mcs.mc_storage: # type: ignore[union-attr]
656
+ with torch.no_grad():
657
+ inpt_old.set_(inpt_new)
658
+
659
+ # Note [Ordering of resize_() and set_()]
660
+ # Importantly: the common usage in FSDP is that we have a dummy parameter
661
+ # that sees a set_() and **Then** a resize_().
662
+ # We must put those mutations into the graph in the same order,
663
+ # Since running them in the opposite order will have different behavior.
664
+ # We fully ban resize_() followed by set_() for now, although in principal
665
+ # we could support this
666
+ if input_info.mutation_inductor_storage_resize:
667
+ if (
668
+ mcs is None
669
+ or mcs.mc_inductor_storage_resized > applied_mcs.mc_inductor_storage_resized # type: ignore[union-attr]
670
+ ):
671
+ # resizing is not supported on subclasses (we error earlier if this happens)
672
+ from torch._subclasses.functional_tensor import FunctionalTensor
673
+
674
+ assert isinstance(f_inpt, FunctionalTensor)
675
+ old_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined]
676
+ f_inpt.elem, before=True
677
+ )
678
+ new_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined]
679
+ f_inpt.elem, before=False
680
+ )
681
+ if old_storage_size != new_storage_size:
682
+ assert old_storage_size == 0 or new_storage_size == 0, f"""\
683
+ Encosize during tracing on input {input_idx}. Old nbytes={old_storage_size}, new nbytes={new_storage_size}
684
+ We oresizing on graph inputs as long as the input either starts or ends with a storage size of 0
685
+ (thee for FSDP)"""
686
+ torch.ops.inductor.resize_storage_bytes_(inpt_old, new_storage_size)
687
+ if new_storage_size == 0:
688
+ # Even if we marked the input as having a data mutation (thus needing a copy_()),
689
+ # We should **ignore** it if our input has no storage
690
+ # (this can happen if, e.g. we temporarily resize our input, copy data into it,
691
+ # and resize it back down to zero)
692
+ return
693
+
694
+ # Optimization: if the copy_() is a no-op then don't include it in the graph.
695
+ # In theory inductor could optimize this away, however in fsdp, we end up with
696
+ # param.copy_(param), where param is a zero-storage-size tensor,
697
+ # and running this op in eager mode (using the aot_eager backend) will result in a segfault.
698
+ # So we may as well optimize it away here.
699
+ if inpt_old is inpt_new:
700
+ # (This check needs to be done after putting resize_() in the graph,
701
+ # since a resize_(0) doesn't actually change the FunctionalTensor's inner tensor)
702
+ return
703
+ # We found an input that had a (data-only) mutation.
704
+ # Since keep_input_mutations is set, we need to faithfully apply a copy_()
705
+ # so the compiler will see the input mutation in the graph.
706
+
707
+ if not input_info.mutates_data:
708
+ return
709
+
710
+ if mcs is not None and mcs.mc_data <= applied_mcs.mc_data: # type: ignore[union-attr]
711
+ return
712
+
713
+ if input_info.mutations_hidden_from_autograd:
714
+ # Hidden from autograd = run under no_grad, **and** don't bump VC
715
+ # (although if the tensor was created in inference mode, it has no VC)
716
+ if inpt_old.is_inference():
717
+ maybe_preserve_vc = nullcontext()
718
+ else:
719
+ maybe_preserve_vc = torch.autograd._unsafe_preserve_version_counter(
720
+ inpt_old # type: ignore[assignment]
721
+ )
722
+ with torch.no_grad(), maybe_preserve_vc:
723
+ inpt_old.copy_(inpt_new)
724
+ elif input_info.mutations_under_no_grad_or_inference_mode:
725
+ # Under no_grad = run under no_grad (we still bump the VC though)
726
+ # (inference_mode will also bump the VC, as long as the tensor in question
727
+ # was created outside of inference_mode)
728
+
729
+ with torch.no_grad():
730
+ inpt_old.copy_(inpt_new)
731
+ else:
732
+ inpt_old.copy_(inpt_new)
733
+
734
+
735
+ # This creates the final function that we want to trace using make_fx(),
736
+ # in both aot_dispatch_autograd and aot_dispatch_base.
737
+ # Preconditions:
738
+ # - fn corresponds to the user's fw function
739
+ # - fn arguments have been flattened, duplicate arguments have been handled
740
+ # - In the returned function, the "primals" arguments *includes* synthetic bases.
741
+ # This function does the work of functionalizing the input function,
742
+ # and performing copy_() calls at the end of the function if `keep_input_mutations` is set.
743
+ # The function returned has signature that is either:
744
+ # (1) "traced_fn(primals: List[Any])" if trace_joint is False
745
+ # (2) "traced_fn(primals: List[Any], tangents: List[Any])" if trace_joint is True
746
+ # Returns a new (functionalized) function, and updated arguments to call it with.
747
+ def create_functionalized_fn(
748
+ fn,
749
+ args,
750
+ args_descs,
751
+ *,
752
+ meta: ViewAndMutationMeta,
753
+ aot_config: AOTConfig,
754
+ trace_joint: bool,
755
+ joint_fn_handle: Optional[JointFnHandle] = None,
756
+ ) -> Any:
757
+ primals_after_forward = None
758
+ f_args_after_forward = None
759
+ f_args_mutation_counters_after_forward: Optional[list[MutationCounters]] = None
760
+ inputs_mutated_in_graph = [
761
+ info.mutation_type == MutationType.MUTATED_IN_GRAPH for info in meta.input_info
762
+ ]
763
+ has_input_mutated_in_graph = any(inputs_mutated_in_graph)
764
+
765
+ @simple_wraps(fn)
766
+ def _functionalized_f_helper(
767
+ *args: list[FxValue],
768
+ ) -> tuple[tuple[list[FxValue], list[Tensor]], list[Optional[AOTOutput]]]:
769
+ with maybe_enable_thunkify():
770
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
771
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
772
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
773
+ )
774
+
775
+ with disable_above:
776
+ # The functionalization code here can potentially trigger traces
777
+ # into the graph, but we'd prefer to NOT do this, because if we
778
+ # trace them now, we will end up with FX nodes that don't have
779
+ # module stack annotations, which makes unflattener unhappy.
780
+ # Wrap inputs into functional wrappers
781
+ f_args = pytree.tree_map(to_fun, args)
782
+
783
+ if trace_joint and has_input_mutated_in_graph and joint_fn_handle:
784
+ # TODO(ivankobzarev): Support fw and bw mutations for subclasses
785
+ def _post_forward(primals):
786
+ nonlocal primals_after_forward
787
+ primals_after_forward = pytree.tree_map(from_fun, primals)
788
+ nonlocal f_args_after_forward
789
+ f_args_after_forward = f_args[0]
790
+ nonlocal f_args_mutation_counters_after_forward
791
+ f_args_mutation_counters_after_forward = [
792
+ MutationCounters(-1, -1, -1)
793
+ if not inputs_mutated_in_graph[i]
794
+ else _get_mutation_counters(f_arg)
795
+ for i, f_arg in enumerate(f_args_after_forward)
796
+ ]
797
+
798
+ joint_fn_handle.post_forward = _post_forward
799
+
800
+ # Run the joint
801
+ f_outs, f_outs_descs = call_and_expect_output_descs(fn, f_args)
802
+
803
+ if trace_joint:
804
+ # We support a limited amount of mutation of graph inputs during the backward pass.
805
+ # (This is used e.g. by Float8, which needs to update buffers during the backward pass)
806
+ # Here, we perform extra checks for primals that were mutated in the **backward**
807
+ # We're doing the checks here instead of doing them with the rest of the input mutation handling because:
808
+ # - We need to detect inputs that were mutated in the backward **separately** from mutations that happened
809
+ # during the forward, because the handling is different: some input mutations from the the forward
810
+ # can be only handled in a fw-only runtime epilogue, and in theory if we wanted to handle those same
811
+ # types of mutations in the backward we would need a bw-only runtime epilogue.
812
+ # - We could in theory have our analysis pass differentiate mutations in the fw from mutations in
813
+ # the bw by running our analysis first on the fw-only graph, and then on the joint graph. This would
814
+ # require an extra round of tracing though, so it's more efficient to do in-line here.
815
+ assert (
816
+ isinstance(args, tuple)
817
+ and len(args) == 2
818
+ and isinstance(args[0], (list, tuple))
819
+ )
820
+ # Only look at mutations that happened to forward inputs (e.g. fw buffers that were saved for bw)
821
+ primals_before = args[0]
822
+ primals_after = pytree.tree_map(from_fun, f_args[0])
823
+ for idx, (f_inpt, before, after, inpt_info) in enumerate(
824
+ zip(f_args[0], primals_before, primals_after, meta.input_info)
825
+ ):
826
+ # Store information about mutations in joint(for backward analysis)
827
+ joint_mutates_data = has_data_mutation(f_inpt)
828
+
829
+ joint_mutates_metadata = has_metadata_mutation(
830
+ f_inpt, before, check_only_storage_mutation=False
831
+ )
832
+
833
+ # Ban metadata mutations on fw inputs during the bw
834
+ if not inpt_info.mutates_metadata:
835
+ assert not joint_mutates_metadata, (
836
+ "Found a graph input that had its metadata mutated in the backward. This is not supported"
837
+ )
838
+
839
+ # Ban storage resizing on fw inputs during the bw
840
+ if not inpt_info.mutation_inductor_storage_resize:
841
+ assert not was_inductor_storage_resized(f_inpt), (
842
+ "Found a graph input that had storage resizing in the backward. This is not supported"
843
+ )
844
+
845
+ # Allow data mutations on fw inputs during the bw, but only if they do not require grad
846
+ # So we can guarantee that we can keep the mutations in the graph
847
+ if (
848
+ joint_mutates_data
849
+ and not inpt_info.mutates_data
850
+ and not inpt_info.mutates_storage_metadata
851
+ ):
852
+ # Not banning here mutations on inpt_info.requires_grad -
853
+ # we'll check at runtime and fail only when backward is under torch.is_grad_enabled (create_graph)
854
+ # Add node meta for copy_ for partitioner that this node should be in backward graph.
855
+ with (
856
+ torch.fx.traceback.preserve_node_meta(),
857
+ set_partitioner_tag_must_be_in_backward(),
858
+ ):
859
+ # before and after should be tensors if we're calling copy_ on them
860
+ assert isinstance(before, torch.Tensor) and isinstance(
861
+ after, torch.Tensor
862
+ )
863
+ before.copy_(after)
864
+ meta.indices_of_inputs_that_requires_grad_with_mutations_in_bw.append(
865
+ idx
866
+ )
867
+ # Now that we covered mutations to *forward* inputs during the backward,
868
+ # we also need to cover mutations to *backward-only* inputs during the backward (e.g. mutation to a grad_out).
869
+ # Today, we will just error in all cases of this happening unless someone needs us to support it.
870
+ tangents_before = args[1]
871
+ tangents_after = pytree.tree_map(from_fun, f_args[1])
872
+ for f_inpt, before, after in zip(
873
+ f_args[1], tangents_before, tangents_after
874
+ ):
875
+ assert not has_metadata_mutation(
876
+ f_inpt, before, check_only_storage_mutation=False
877
+ ), (
878
+ "Found an input to the backward that had metadata mutated during the backward pass. This is not supported"
879
+ )
880
+ if has_data_mutation(f_inpt):
881
+ can_be_in_graph = _check_if_mutation_can_be_in_graph(
882
+ keep_input_mutations=True,
883
+ mutates_data=True,
884
+ mutates_metadata=False,
885
+ mutations_hidden_from_autograd=are_all_mutations_hidden_from_autograd(
886
+ f_inpt
887
+ ),
888
+ mutations_under_no_grad_or_inference_mode=are_all_mutations_under_no_grad_or_inference_mode(
889
+ f_inpt
890
+ ),
891
+ mutates_storage_metadata=False,
892
+ mutation_inductor_storage_resize=was_inductor_storage_resized(
893
+ f_inpt
894
+ ),
895
+ requires_grad=f_inpt.requires_grad,
896
+ )
897
+ assert can_be_in_graph, (
898
+ "a backward input that had data mutated in an autograd-aware way. This is not supported"
899
+ )
900
+ # Perform the input mutation
901
+ with torch.fx.traceback.preserve_node_meta():
902
+ # before and after should be tensors if we're calling copy_ on them
903
+ assert isinstance(before, torch.Tensor) and isinstance(
904
+ after, torch.Tensor
905
+ )
906
+ before.copy_(after)
907
+
908
+ if aot_config.keep_inference_input_mutations:
909
+ # Note: This is a bit annoying. There's a layering issue here, where:
910
+ # (1) functionalization needs to operate on **synthetic base** inputs, before unpacking them into the "real" inputs.
911
+ # (2) For keep_input_mutations, we support tracing a call to copy_() directly on mutated inputs.
912
+ # However, we **only** want to support this for inputs that have data-only (and no metadata) mutations,
913
+ # because inductor (and backends in generally) would prefer not to see these (e.g. as_strided_(), resize_()).
914
+ # This makes it pretty difficult for this logic to operate on synthetic bases.
915
+ # (3) In addition, there are cases where it's significantly cheaper to perform the copy on the individual
916
+ # (unpacked) input aliases, instead of the synthetic base.
917
+ # Example case where (3) could be important:
918
+ #
919
+ # def f(x, y):
920
+ # x.mul_(2)
921
+ # y.mul_(3)
922
+ # return x, y
923
+ # a = torch.ones(1'000'000)
924
+ # x, y = out(a[0:9], a[1:10])
925
+ #
926
+ # It would be much better to add copy_() calls into the graph for the two tiny slices, instead of materializing
927
+ # a giant "updated synthetic base" and copying into a's entire storage.
928
+ #
929
+ # For now, we are pessimistically not performing the optimization from (3);
930
+ # we will materialize an "updated" synthetic base, and copy it back to the synthetic input base.
931
+ # This allows us to factor aot autograd much more nicely, since only one area of the code needs to worry
932
+ # about synthetic bases.
933
+
934
+ # Apply in graph forward mutations only in joint case.
935
+ # Note: Mutations of primals in forward AND backward.
936
+ # If we have mutations of the same input in forward and in backward,
937
+ # we can not fuse them into one copy_ node. As in this case partitioner will put it
938
+ # either in forward or in backward. This will lead to incorrect state
939
+ # after forward and before backward.
940
+ # We have to emit two copy_ nodes, marking with additional meta each node,
941
+ # if it must be in forward or backward.
942
+ # We memorize mutation counter of the inputs after forward.
943
+ # Based on this after joint graph we check if backward also mutated input or not.
944
+ # We emit copy_ only in the end of joint tracing, to provide invariant for joint
945
+ # graph passes, that our graph is functional, except only some number of copy_ nodes
946
+ # in the end.
947
+ mcs_applied: list[MutationCounters] = [MutationCounters(0, 0, 0)] * len(
948
+ meta.input_info
949
+ )
950
+ if f_args_mutation_counters_after_forward is not None:
951
+ primals_before = args[0]
952
+ for idx, (f_inpt, before, after, inpt_info) in enumerate(
953
+ zip(
954
+ f_args_after_forward, # type: ignore[arg-type]
955
+ primals_before, # type: ignore[arg-type]
956
+ primals_after_forward, # type: ignore[arg-type]
957
+ meta.input_info,
958
+ )
959
+ ):
960
+ if inpt_info.mutation_type != MutationType.MUTATED_IN_GRAPH:
961
+ continue
962
+
963
+ mcs_after_forward = f_args_mutation_counters_after_forward[idx]
964
+ with (
965
+ torch.fx.traceback.preserve_node_meta(),
966
+ set_partitioner_tag_must_be_in_forward(),
967
+ _proxy_tensor_disable_update_tensor_tracker(),
968
+ ):
969
+ apply_in_graph_mutations(
970
+ inpt_info,
971
+ before,
972
+ after,
973
+ f_inpt,
974
+ idx,
975
+ mcs_after_forward,
976
+ mcs_applied[idx],
977
+ )
978
+ mcs_applied[idx] = mcs_after_forward
979
+
980
+ for idx, (inpt_old, f_inpt) in enumerate(
981
+ zip(args, f_args) if not trace_joint else zip(args[0], f_args[0]) # type: ignore[arg-type]
982
+ ):
983
+ if not isinstance(f_inpt, torch.Tensor):
984
+ continue
985
+ assert is_fun(f_inpt)
986
+ inpt_new = from_fun(f_inpt)
987
+ if (
988
+ meta.input_info[idx].mutation_type
989
+ != MutationType.MUTATED_IN_GRAPH
990
+ ):
991
+ continue
992
+ mcs: Optional[MutationCounters] = None
993
+ if f_args_mutation_counters_after_forward is not None:
994
+ # This could happen for subclasses tracing
995
+ # Subclasses support for mutations in fw and bw is TBD.
996
+ mcs = _get_mutation_counters(f_inpt)
997
+ if mcs == mcs_applied[idx]:
998
+ # No mutation in backward; mutation was already applied.
999
+ continue
1000
+
1001
+ with (
1002
+ torch.fx.traceback.preserve_node_meta(),
1003
+ set_partitioner_tag_must_be_in_backward(),
1004
+ ):
1005
+ apply_in_graph_mutations(
1006
+ meta.input_info[idx],
1007
+ inpt_old,
1008
+ inpt_new,
1009
+ f_inpt,
1010
+ idx,
1011
+ mcs,
1012
+ mcs_applied[idx],
1013
+ )
1014
+
1015
+ # When an output tensor is a functionalized mutated input, and we
1016
+ # were able to move the mutation in to the graph then we can return
1017
+ # the mutated input directly. This prevents duplicating the
1018
+ # tensors contents.
1019
+ flat_outs, outs_spec = pytree.tree_flatten(f_outs)
1020
+ flat_outs = [from_fun(o) for o in flat_outs]
1021
+ num_outs = len(meta.output_info)
1022
+
1023
+ for i in range(num_outs):
1024
+ info = meta.output_info[i]
1025
+ if info.output_type != OutputType.is_input:
1026
+ continue
1027
+
1028
+ assert info.base_idx is not None
1029
+ if (
1030
+ meta.input_info[info.base_idx].mutation_type
1031
+ == MutationType.MUTATED_IN_GRAPH
1032
+ ):
1033
+ fw_args = args[0] if trace_joint else args
1034
+ flat_outs[i] = fw_args[info.base_idx]
1035
+ return pytree.tree_unflatten(flat_outs, outs_spec), f_outs_descs
1036
+
1037
+ return pytree.tree_map(from_fun, f_outs), f_outs_descs
1038
+
1039
+ # Kinda annoying, but needed to make sure that the fx graph we trace out has "primals"
1040
+ # and "tangents" as its input names (which are special-cased by the partitioner)
1041
+ # TODO (tmanlaibaatar) revisit this if we ever need to turn on non-strict joint graph export
1042
+ def joint_helper(primals, tangents):
1043
+ return _functionalized_f_helper(primals, tangents)
1044
+
1045
+ helper = joint_helper if trace_joint else _functionalized_f_helper
1046
+ if config.functionalize_rng_ops:
1047
+ # Setup the wrapper for functionalization of rng ops
1048
+ helper, args, args_descs = create_functionalized_rng_ops_wrapper(
1049
+ helper, args, args_descs, trace_joint
1050
+ )
1051
+
1052
+ return helper, args, args_descs
1053
+
1054
+
1055
+ def handle_effect_tokens_fn(
1056
+ fn,
1057
+ args,
1058
+ args_descs: list[AOTInput],
1059
+ *,
1060
+ meta: ViewAndMutationMeta,
1061
+ trace_joint: bool,
1062
+ ) -> Any:
1063
+ num_tokens = len(meta.tokens)
1064
+
1065
+ @simple_wraps(fn)
1066
+ def inner_fn(*args):
1067
+ # See Note [Disabling Functionalize TLS Above Python Functionalization]
1068
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
1069
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
1070
+ )
1071
+
1072
+ with disable_above:
1073
+ # See Note [Side-Effectful Tokens in AOTAutograd]
1074
+ if trace_joint:
1075
+ assert isinstance(args, tuple) and isinstance(args[0], (list, tuple))
1076
+ tokens = args[0][:num_tokens]
1077
+ assert all(token.numel() == 0 for token in tokens)
1078
+ args = (args[0][num_tokens:], *args[1:])
1079
+ else:
1080
+ tokens = args[:num_tokens]
1081
+ assert all(token.numel() == 0 for token in tokens)
1082
+ args = args[num_tokens:]
1083
+
1084
+ # Populate the current FunctionalTensorMode with the tokens per
1085
+ # operator. See Note [FunctionalTensorMode is Stateful]
1086
+ functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode(
1087
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
1088
+ )
1089
+ assert functional_tensor_mode is not None
1090
+ f_tokens = pytree.tree_map(to_fun, tokens)
1091
+ for i, k in enumerate(meta.tokens.keys()):
1092
+ functional_tensor_mode._tokens[k] = f_tokens[i]
1093
+
1094
+ # Run the joint
1095
+ outs, outs_descs = call_and_expect_output_descs(fn, args)
1096
+
1097
+ # Return both the tokens and the outputs
1098
+ # See Note [Side-Effectful Tokens in AOTAutograd]
1099
+ if trace_joint:
1100
+ assert len(outs) == 2
1101
+ assert len(functional_tensor_mode._tokens_forward_output) == num_tokens
1102
+ fwd_out_tokens = functional_tensor_mode._tokens_forward_output.values()
1103
+
1104
+ bwd_out_tokens = functional_tensor_mode._tokens.values()
1105
+
1106
+ f_fwd_out_tokens = [from_fun(t) for t in fwd_out_tokens]
1107
+ f_bwd_out_tokens = [from_fun(t) for t in bwd_out_tokens]
1108
+ f_fwd_out_tokens_descs = [
1109
+ ForwardTokenAOTOutput(i) for i in range(len(fwd_out_tokens))
1110
+ ]
1111
+ f_bwd_out_tokens_descs = [
1112
+ BackwardTokenAOTOutput(i) for i in range(len(bwd_out_tokens))
1113
+ ]
1114
+
1115
+ meta.num_backward_tokens = len(bwd_out_tokens)
1116
+ return (
1117
+ ((*f_fwd_out_tokens, *outs[0]), (*outs[1], *f_bwd_out_tokens)),
1118
+ (
1119
+ (*f_fwd_out_tokens_descs, *outs_descs[0]),
1120
+ (*outs_descs[1], *f_bwd_out_tokens_descs),
1121
+ ),
1122
+ )
1123
+
1124
+ out_tokens = [from_fun(t) for t in functional_tensor_mode._tokens.values()]
1125
+ # TODO: can probably do a little more resolution here
1126
+ out_tokens_descs = [
1127
+ ForwardTokenAOTOutput(i)
1128
+ for i in range(len(functional_tensor_mode._tokens.values()))
1129
+ ]
1130
+ return ((*out_tokens, *outs), (*out_tokens_descs, *outs_descs))
1131
+
1132
+ # Additionally pass in tokens as inputs
1133
+ # See Note [Side-Effectful Tokens in AOTAutograd]
1134
+ additional_fwd_token_inputs = [torch.tensor([])] * num_tokens
1135
+ additional_fwd_token_inputs_descs = [
1136
+ ForwardTokenAOTInput(i) for i in range(num_tokens)
1137
+ ]
1138
+
1139
+ if trace_joint:
1140
+ args = ([*additional_fwd_token_inputs, *args[0]], *args[1:])
1141
+ args_descs = ( # type: ignore[assignment]
1142
+ [*additional_fwd_token_inputs_descs, *args_descs[0]], # type: ignore[misc]
1143
+ *args_descs[1:],
1144
+ )
1145
+ else:
1146
+ args = [*additional_fwd_token_inputs, *args]
1147
+ args_descs = [*additional_fwd_token_inputs_descs, *args_descs]
1148
+ return inner_fn, args, args_descs
1149
+
1150
+
1151
+ # Given a function operating on Subclass -> Subclass, returns an function that operates on Tensor -> Tensor
1152
+ # Also returns:
1153
+ # - the new set of arguments to pass into this function (now that tensor subclasses have been eliminated)
1154
+ # - the updated ViewAndMutationMeta for this dense -> dense function.
1155
+ # The other important arguments are:
1156
+ # - flat_fn_maybe_joint: when is_joint_structure=True, this is the joint fw-bw function.
1157
+ # when is_joint_structure=False, this is just the forward function.
1158
+ # - fw_only: this is *always* the forward-only function.
1159
+ # Why do we need this? We need to collect updated ViewAndMutationMeta on our new dense -> dense functions.
1160
+ # In particular, we need this to tell the partitioner how many dense forward outputs there are.
1161
+ def aot_dispatch_subclass(
1162
+ flat_fn_maybe_joint: Union[JointTraceFn, TraceFn],
1163
+ args: Union[list[FxValue], tuple[list[FxValue], list[FxValue]]],
1164
+ args_descs: Union[list[AOTInput], tuple[list[AOTInput], list[AOTInput]]],
1165
+ *,
1166
+ is_joint_structure: bool,
1167
+ meta: ViewAndMutationMeta,
1168
+ fw_only: Callable,
1169
+ ) -> SubclassTracingInfo:
1170
+ # Skip logic if we don't need to trace through any subclasses
1171
+ req_subclass_dispatch = requires_subclass_dispatch(args, meta)
1172
+ if not req_subclass_dispatch:
1173
+ return SubclassTracingInfo(
1174
+ plain_tensor_trace_fn=flat_fn_maybe_joint,
1175
+ plain_tensor_args=args,
1176
+ plain_tensor_args_descs=args_descs,
1177
+ maybe_subclass_meta=None,
1178
+ )
1179
+
1180
+ # TODO: add subclass guards (later PR).
1181
+
1182
+ # What's going on here? We need to compute subclass metadata about the outputs of the joint (grad_inputs).
1183
+ # Annoying: we don't know the grad input metas until we're in the middle of tracing the joint,
1184
+ # so we set it later, while we're tracing the joint (see inner_fn() below).
1185
+ # Another option would be to run our run_functionalized_fw_and_collect_metadata() function
1186
+ # directly on the joint, but this would hurt compile time (adding yet another pass through the joint).
1187
+ subclass_meta = SubclassMeta()
1188
+
1189
+ # NB: doesn't take descs, this is going from the NEW flat_args to the
1190
+ # subclasses, we don't need to do bookkeeping here
1191
+ def inner_fn(fn, args, *, use_trace_joint: bool):
1192
+ # Step 1: wrap tensor inputs into subclasses if necessary
1193
+ all_args = wrap_tensor_subclasses_maybe_joint(
1194
+ args, is_joint_structure=use_trace_joint, meta=meta
1195
+ )
1196
+
1197
+ # Step 2: call the inner function, with our (maybe subclass) inputs
1198
+ wrapped_outs, wrapped_outs_descs = call_and_expect_output_descs(fn, all_args)
1199
+
1200
+ if use_trace_joint:
1201
+ # See Note: [Computing Subclass Metadata about grad_inputs]
1202
+ # We also stash subclass info on our grad_inputs, if we're tracing the joint.
1203
+ nonlocal subclass_meta
1204
+ assert isinstance(wrapped_outs, tuple) and len(wrapped_outs) == 2, (
1205
+ wrapped_outs,
1206
+ wrapped_outs_descs,
1207
+ )
1208
+ # Don't need fw outs since we already have subclass metadata on them
1209
+ grad_inputs = wrapped_outs[1]
1210
+ subclass_meta.grad_input_metas = create_subclass_meta(grad_inputs)
1211
+
1212
+ # Add extra symints as outputs to the forward/backward graphs
1213
+ # ignore nested ints here
1214
+ forward_outs, forward_outs_descs = unwrap_tensor_subclasses(
1215
+ wrapped_outs[0], wrapped_outs_descs[0], append_symints=True
1216
+ )
1217
+ # ignore nested ints here
1218
+ backward_outs, backward_outs_descs = unwrap_tensor_subclasses(
1219
+ wrapped_outs[1], wrapped_outs_descs[1], append_symints=True
1220
+ )
1221
+ return (
1222
+ (forward_outs, backward_outs),
1223
+ (forward_outs_descs, backward_outs_descs),
1224
+ )
1225
+
1226
+ # Step 3: Unwrap any subclass outputs back into dense tensors
1227
+ return unwrap_tensor_subclasses(
1228
+ wrapped_outs, wrapped_outs_descs, append_symints=True
1229
+ )
1230
+
1231
+ def joint_fn(
1232
+ primals: list[FxValue], tangents: list[FxValue]
1233
+ ) -> tuple[
1234
+ tuple[list[FxValue], list[FxValue]], tuple[list[AOTOutput], list[AOTOutput]]
1235
+ ]:
1236
+ with maybe_enable_thunkify():
1237
+ return inner_fn(
1238
+ flat_fn_maybe_joint, (primals, tangents), use_trace_joint=True
1239
+ )
1240
+
1241
+ def fw_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]:
1242
+ with maybe_enable_thunkify():
1243
+ return inner_fn(flat_fn_maybe_joint, primals, use_trace_joint=False)
1244
+
1245
+ def metadata_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]:
1246
+ @simple_wraps(fw_only)
1247
+ def inner_fw_only(*args):
1248
+ return call_and_expect_output_descs(fw_only, args)
1249
+
1250
+ return inner_fn(inner_fw_only, primals, use_trace_joint=False)
1251
+
1252
+ if is_joint_structure:
1253
+ # Add extra symints (size/strides) as input to the forward graph
1254
+ primals_unwrapped_pair = unwrap_tensor_subclasses(
1255
+ args[0], # type: ignore[arg-type]
1256
+ args_descs[0], # type: ignore[arg-type]
1257
+ append_symints=True,
1258
+ )
1259
+ # We pass append_symints=False here because the partitioner will
1260
+ # capture and add any extra argument
1261
+ tangents_unwrapped_pair = unwrap_tensor_subclasses(
1262
+ args[1], # type: ignore[arg-type]
1263
+ args_descs[1], # type: ignore[arg-type]
1264
+ append_symints=False,
1265
+ )
1266
+
1267
+ args_unwrapped = (primals_unwrapped_pair[0], tangents_unwrapped_pair[0])
1268
+ args_descs_unwrapped = (primals_unwrapped_pair[1], tangents_unwrapped_pair[1])
1269
+ else:
1270
+ args_unwrapped, args_descs_unwrapped = unwrap_tensor_subclasses( # type: ignore[assignment]
1271
+ args, # type: ignore[arg-type]
1272
+ args_descs, # type: ignore[arg-type]
1273
+ append_symints=True,
1274
+ )
1275
+ remapped_static_indices = remap_unwrapped_subclass_arg_indices(
1276
+ args, meta.static_input_indices
1277
+ )
1278
+
1279
+ if is_joint_structure:
1280
+ primals_unwrapped = args_unwrapped[0] # type: ignore[assignment]
1281
+ primals_unwrapped_descs = args_descs_unwrapped[0] # type: ignore[assignment]
1282
+ fn_to_trace = joint_fn # type: ignore[assignment]
1283
+ else:
1284
+ primals_unwrapped = args_unwrapped # type: ignore[assignment]
1285
+ primals_unwrapped_descs = args_descs_unwrapped # type: ignore[assignment]
1286
+ fn_to_trace = fw_fn # type: ignore[assignment]
1287
+
1288
+ # Note: [Partitioner handling for Subclasses, Part 1]
1289
+ # The way the partitioner works is that:
1290
+ # (1) we pass is a single graph containing the joint fw/bw,
1291
+ # where the # of graph outputs corresponds to # fw_outputs + # grad_inputs
1292
+ # (2) The partitioner accepts an arguments, num_fwd_outputs,
1293
+ # and assumes that the first "num_fwd_outputs" graph outputs correspond
1294
+ # to outputs of the forward graph.
1295
+ # How do tensor subclasses enter the picture?
1296
+ # the num_fwd_outputs in the final graph is actually non-trivial to compute,
1297
+ # because it can be influenced by input mutations and intermediate bases.
1298
+ # So we compute it by inspecting the current ViewAndMutationMeta object.
1299
+ # However, the original ViewAndMutationMeta that we computed was created
1300
+ # on the subclass -> subclass graph,
1301
+ # which can have a different number of outputs than the dense -> dense graph.
1302
+ # That's why we created a fresh metadata object on the dense -> dense function here,
1303
+ # and plumb it back up to the partitioner.
1304
+ # See Note: [Partitioner handling for Subclasses, Part 2] for more info.
1305
+ meta_updated = run_functionalized_fw_and_collect_metadata(
1306
+ without_output_descs(metadata_fn),
1307
+ flat_args_descs=primals_unwrapped_descs,
1308
+ static_input_indices=remapped_static_indices,
1309
+ keep_input_mutations=meta.keep_input_mutations,
1310
+ is_train=meta.is_train,
1311
+ )(*primals_unwrapped)
1312
+
1313
+ subclass_meta.fw_metadata = meta_updated
1314
+
1315
+ return SubclassTracingInfo(
1316
+ plain_tensor_trace_fn=fn_to_trace,
1317
+ plain_tensor_args=args_unwrapped,
1318
+ plain_tensor_args_descs=args_descs_unwrapped,
1319
+ maybe_subclass_meta=subclass_meta,
1320
+ )
1321
+
1322
+
1323
+ def create_functional_call(
1324
+ mod, params_spec, params_len, store_orig_mod=False, strict_out_tuple=True
1325
+ ):
1326
+ # Redundant with dynamo, but worth having in case this gets invoked elsewhere.
1327
+ # https://github.com/pytorch/pytorch/issues/103569
1328
+
1329
+ @simple_wraps(mod)
1330
+ def functional_call(*args, **kwargs):
1331
+ flat_params = args[:params_len]
1332
+ if isinstance(params_spec, TreeSpec):
1333
+ params = pytree.tree_unflatten(flat_params, params_spec)
1334
+ else:
1335
+ assert isinstance(params_spec, list)
1336
+ params = dict(zip(params_spec, flat_params))
1337
+ with (
1338
+ stateless._reparametrize_module(mod, params),
1339
+ maybe_disable_thunkify(),
1340
+ ):
1341
+ if isinstance(mod, torch.fx.GraphModule):
1342
+ with fx_traceback.preserve_node_meta(), warnings.catch_warnings():
1343
+ warnings.filterwarnings(
1344
+ "ignore", "Anomaly Detection has been enabled."
1345
+ )
1346
+ with torch.autograd.detect_anomaly(check_nan=False):
1347
+ fake_mode = detect_fake_mode()
1348
+ assert fake_mode is not None
1349
+ fake_mode.epoch += 1
1350
+ out = PropagateUnbackedSymInts(mod).run(
1351
+ *args[params_len:], **kwargs
1352
+ )
1353
+ else:
1354
+ out = mod(*args[params_len:], **kwargs)
1355
+
1356
+ if strict_out_tuple and not isinstance(out, (tuple, list)):
1357
+ raise RuntimeError(
1358
+ "Graph output must be a (). This is so that we can avoid "
1359
+ "pytree processing of the outputs. Please change the module to "
1360
+ "have tuple outputs or use aot_module instead."
1361
+ )
1362
+ return out
1363
+
1364
+ # Note [Preserving the nn module stack metadata during export non-strict mode]
1365
+ # This path is currently only used by the non-strict export flow,
1366
+ # where we cannot rely on dynamo to preserve nn stack metadata in our captured graph.
1367
+ # Instead, we stash the original user nn module here, and rely on `make_fx` to grab
1368
+ # this stashed module and use it to track nn module stack metadata
1369
+ if store_orig_mod and not hasattr(functional_call, "_orig_mod"):
1370
+ functional_call._orig_mod = mod # type: ignore[attr-defined]
1371
+
1372
+ return functional_call
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/graph_compile.py ADDED
@@ -0,0 +1,1928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Union
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Sequence
26
+
27
+ import torch
28
+ import torch.utils._pytree as pytree
29
+ import torch.utils.dlpack
30
+ from torch import Tensor
31
+ from torch._dynamo.utils import (
32
+ CompileEventLogger,
33
+ detect_fake_mode,
34
+ dynamo_timed,
35
+ lazy_format_graph_code,
36
+ )
37
+ from torch._guards import CompileContext, TracingContext
38
+ from torch._logging import getArtifactLogger, trace_structured
39
+ from torch._subclasses import FakeTensor
40
+ from torch._subclasses.meta_utils import is_sparse_any
41
+ from torch.fx.experimental._backward_state import BackwardState
42
+ from torch.fx.experimental.proxy_tensor import is_sym_node
43
+ from torch.fx.experimental.symbolic_shapes import fx_placeholder_vals
44
+ from torch.fx.graph_module import GraphModule
45
+ from torch.fx.passes._tensorify_python_scalars import tensorify_python_scalars
46
+ from torch.multiprocessing.reductions import StorageWeakRef
47
+ from torch.types import py_sym_types
48
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
49
+ from torchgen.utils import dataclass_repr
50
+
51
+ from .. import config
52
+ from .autograd_cache import (
53
+ AOTAutogradCache,
54
+ serialize_graph_module,
55
+ should_bundle_autograd_cache,
56
+ should_use_remote_autograd_cache,
57
+ )
58
+ from .descriptors import AOTOutput, PlainAOTOutput
59
+ from .graph_capture import aot_dispatch_autograd_graph, aot_dispatch_base_graph
60
+ from .logging_utils import track_graph_compiling
61
+ from .runtime_wrappers import (
62
+ AOTDedupeWrapper,
63
+ AOTDispatchAutograd,
64
+ AOTDispatchSubclassWrapper,
65
+ AOTSyntheticBaseWrapper,
66
+ AutogradLazyBackwardCompileInfo,
67
+ CompilerWrapper,
68
+ DebugAssertWrapper,
69
+ EffectTokensWrapper,
70
+ FakifiedOutWrapper,
71
+ FunctionalizedRngRuntimeWrapper,
72
+ make_runtime_safe,
73
+ post_compile,
74
+ pre_compile,
75
+ RuntimeWrapper,
76
+ )
77
+ from .schemas import (
78
+ AOTConfig,
79
+ AOTGraphCapture,
80
+ AOTState,
81
+ FlatFn,
82
+ FxValue,
83
+ MutationType,
84
+ ViewAndMutationMeta,
85
+ )
86
+ from .subclass_utils import compute_inner_mutated_inp_indices_from_subclass_meta
87
+ from .utils import (
88
+ _get_symint_hints,
89
+ contain_metadata_mutation_ops,
90
+ get_cuda_generator_meta_val,
91
+ make_boxed_func,
92
+ simple_wraps,
93
+ strict_zip,
94
+ unlift_tokens,
95
+ )
96
+
97
+
98
+ zip = strict_zip
99
+
100
+ log = logging.getLogger(__name__)
101
+ aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph")
102
+ aot_graphs_log = getArtifactLogger(__name__, "aot_graphs")
103
+
104
+ aten = torch.ops.aten
105
+
106
+ # Returns a Callable and a ViewAndMutationMeta.
107
+ # Currently, only export needs the ViewAndMutationMeta after this function.
108
+ # TODO: Refactor this
109
+ DispatchReturn = tuple[Callable, ViewAndMutationMeta]
110
+
111
+
112
+ def _create_wrappers_for_dispatch(needs_autograd: bool) -> list[CompilerWrapper]:
113
+ """
114
+ Wrappers that run on every dispatch function
115
+ """
116
+ return [AOTDedupeWrapper(), AOTSyntheticBaseWrapper(trace_joint=needs_autograd)]
117
+
118
+
119
+ def aot_stage1_graph_capture(
120
+ aot_state: AOTState,
121
+ orig_flat_fn: FlatFn,
122
+ ) -> AOTGraphCapture:
123
+ # NB: flat_fn at this point coincides with the initial info from forward
124
+ # metadata collection returning a list[Tensor]. We are now going to
125
+ # augment the output to return a tuple[list[Tensor], list[AOTOutput]] and
126
+ # then preserve this convention through the rest of the passes.
127
+
128
+ # TODO: We could test for consistency with fw_metadata, but this is not a
129
+ # big deal
130
+ @simple_wraps(orig_flat_fn)
131
+ def orig_flat_fn2(*args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]:
132
+ out = orig_flat_fn(*args)
133
+ out_descs: list[AOTOutput] = type(out)( # type: ignore[assignment]
134
+ PlainAOTOutput(i) # type: ignore[misc]
135
+ for i in range(len(out)) # type: ignore[misc]
136
+ )
137
+ return out, out_descs
138
+
139
+ aot_config = aot_state.aot_config
140
+
141
+ wrappers = _create_wrappers_for_dispatch(aot_state.needs_autograd)
142
+ flat_fn, aot_state.flat_args, aot_state.flat_args_descs, aot_state.fw_metadata = (
143
+ pre_compile(
144
+ wrappers,
145
+ orig_flat_fn2,
146
+ aot_state.flat_args,
147
+ aot_state.flat_args_descs,
148
+ aot_config,
149
+ fw_metadata=aot_state.fw_metadata,
150
+ )
151
+ )
152
+
153
+ # NB: This is currently only used for backwards, where fwd/bwd
154
+ # deterministic TLS can be different
155
+ aot_state.fw_metadata.deterministic = torch.are_deterministic_algorithms_enabled()
156
+ updated_flat_args: Union[list[Any], tuple[list[Any], list[Any]]]
157
+ if aot_state.needs_autograd and not aot_config.pre_dispatch:
158
+ # FYI: this being moved to trigger in export is new, seems fine!
159
+ with dynamo_timed("aot_trace_joint_graph", log_pt2_compile_event=True):
160
+ graph, updated_flat_args, updated_flat_args_descs, maybe_subclass_meta = (
161
+ aot_dispatch_autograd_graph(
162
+ flat_fn,
163
+ aot_state.flat_args,
164
+ aot_state.flat_args_descs,
165
+ aot_config,
166
+ fw_metadata=aot_state.fw_metadata,
167
+ )
168
+ )
169
+ else:
170
+ graph, updated_flat_args, updated_flat_args_descs, maybe_subclass_meta = (
171
+ aot_dispatch_base_graph( # type: ignore[assignment]
172
+ flat_fn,
173
+ aot_state.flat_args,
174
+ aot_state.flat_args_descs,
175
+ aot_config,
176
+ fw_metadata=aot_state.fw_metadata,
177
+ )
178
+ )
179
+
180
+ return AOTGraphCapture(
181
+ wrappers=wrappers,
182
+ graph_module=graph,
183
+ updated_flat_args=updated_flat_args,
184
+ updated_flat_args_descs=updated_flat_args_descs,
185
+ maybe_subclass_meta=maybe_subclass_meta,
186
+ )
187
+
188
+
189
+ def aot_stage2_export(
190
+ aot_state: AOTState, aot_graph_capture: AOTGraphCapture
191
+ ) -> DispatchReturn:
192
+ graph = aot_graph_capture.graph_module
193
+ aot_config = aot_state.aot_config
194
+ wrappers = aot_graph_capture.wrappers
195
+
196
+ CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="export")
197
+
198
+ # NB: the wrappers that run in pre_compile for export are
199
+ # either a no-op, because they're not needed, or will raise a runtime error,
200
+ # since they don't support export.
201
+ # We still run these wrappers to make sure that they're not needed pre compile,
202
+ # but we technically don't need to run them post compile at all here.
203
+ compiled_fn, aot_state.fw_metadata = post_compile(
204
+ wrappers, graph, aot_config, runtime_metadata=aot_state.fw_metadata
205
+ )
206
+
207
+ # Therefore, since no wrapperes run, we don't get back a callable - we get back the raw fx graph
208
+ # (either a joint or an inference-only graph)
209
+ assert isinstance(compiled_fn, torch.fx.GraphModule)
210
+ return compiled_fn, aot_state.fw_metadata
211
+
212
+
213
+ def sanitize_aot_config(input: AOTConfig) -> AOTConfig:
214
+ return AOTConfig(
215
+ fw_compiler=None, # type: ignore[arg-type]
216
+ bw_compiler=None, # type: ignore[arg-type]
217
+ partition_fn=None, # type: ignore[arg-type]
218
+ decompositions={},
219
+ inference_compiler=None,
220
+ num_params_buffers=input.num_params_buffers,
221
+ aot_id=input.aot_id,
222
+ keep_inference_input_mutations=input.keep_inference_input_mutations,
223
+ is_export=input.is_export,
224
+ no_tangents=input.no_tangents,
225
+ aot_autograd_arg_pos_to_source=input.aot_autograd_arg_pos_to_source,
226
+ dynamic_shapes=input.dynamic_shapes,
227
+ enable_log=input.enable_log,
228
+ static_input_indices=input.static_input_indices,
229
+ pre_dispatch=input.pre_dispatch,
230
+ cache_info=None,
231
+ precompile_backend_id=input.precompile_backend_id,
232
+ )
233
+
234
+
235
+ def aot_stage2_compile(
236
+ aot_state: AOTState,
237
+ aot_graph_capture: AOTGraphCapture,
238
+ ) -> DispatchReturn:
239
+ if aot_state.needs_autograd and not aot_state.aot_config.pre_dispatch:
240
+ return aot_stage2_autograd(aot_state, aot_graph_capture)
241
+ else:
242
+ return aot_stage2_inference(aot_state, aot_graph_capture)
243
+
244
+
245
+ def aot_stage2_inference(
246
+ aot_state: AOTState,
247
+ aot_graph_capture: AOTGraphCapture,
248
+ ) -> DispatchReturn:
249
+ """
250
+ Handles functions that don't need autograd. Runs wrappers and compiles with fw_compiler.
251
+ """
252
+
253
+ aot_config = aot_state.aot_config
254
+ fw_metadata = aot_state.fw_metadata
255
+ fw_module = aot_graph_capture.graph_module
256
+ wrappers = aot_graph_capture.wrappers
257
+ updated_flat_args = aot_graph_capture.updated_flat_args
258
+ maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta
259
+
260
+ CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="inference")
261
+
262
+ # Save the forward_graph_str right after aot_dispatch_base_graph,
263
+ # to save in the cache
264
+ aot_forward_graph_str = None
265
+ if aot_config.cache_info is not None:
266
+ aot_forward_graph_str = fw_module.print_readable(
267
+ print_output=False,
268
+ include_stride=True,
269
+ include_device=True,
270
+ fast_sympy_print=True,
271
+ expanded_def=True,
272
+ )
273
+
274
+ fakified_out_wrapper = FakifiedOutWrapper()
275
+ fakified_out_wrapper.pre_compile(
276
+ fw_module, updated_flat_args, aot_config, fw_metadata=fw_metadata
277
+ )
278
+ functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper()
279
+ functionalized_rng_wrapper.pre_compile(
280
+ fw_module, updated_flat_args, aot_config, fw_metadata=fw_metadata
281
+ )
282
+ assert isinstance(fw_module, GraphModule)
283
+
284
+ if aot_config.enable_log:
285
+ trace_structured(
286
+ "artifact",
287
+ metadata_fn=lambda: {
288
+ "name": "torch._functorch.config",
289
+ "encoding": "string",
290
+ },
291
+ payload_fn=lambda: torch._functorch.config.get_config_copy(),
292
+ )
293
+
294
+ disable_amp = torch._C._is_any_autocast_enabled()
295
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
296
+
297
+ with context(), track_graph_compiling(aot_config, "inference"):
298
+ compiler = (
299
+ aot_config.inference_compiler
300
+ if aot_config.inference_compiler is not None
301
+ else aot_config.fw_compiler
302
+ )
303
+
304
+ if tracing_context := torch._guards.TracingContext.try_get():
305
+ tracing_context.fw_metadata = (
306
+ fw_metadata
307
+ if maybe_subclass_meta is None
308
+ else maybe_subclass_meta.fw_metadata
309
+ )
310
+
311
+ with TracingContext.report_output_strides() as fwd_output_strides:
312
+ fake_mode = detect_fake_mode()
313
+ if fake_mode is not None and fake_mode.shape_env is not None:
314
+ tensorify_python_scalars(fw_module, fake_mode.shape_env, fake_mode)
315
+ compiled_fw = compiler(fw_module, updated_flat_args)
316
+
317
+ if fakified_out_wrapper.needs_post_compile:
318
+ fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides)
319
+
320
+ make_runtime_safe(fw_metadata, maybe_subclass_meta)
321
+
322
+ # However, RuntimeWrapper does not expect the rng offsets in the
323
+ # output. So, we have to create another wrapper and take out the offset. As
324
+ # a result, we have to account for not boxed_call compilers as well.
325
+ if not getattr(compiled_fw, "_boxed_call", False):
326
+ compiled_fw = make_boxed_func(compiled_fw)
327
+
328
+ # Create a wrapper to set up the rng functionalize and fakified out bits
329
+ compiled_fw = functionalized_rng_wrapper.post_compile(
330
+ compiled_fw, aot_config, runtime_metadata=fw_metadata
331
+ )
332
+ cache_info = aot_config.cache_info
333
+
334
+ def should_save_cache():
335
+ if should_bundle_autograd_cache():
336
+ return True
337
+ else:
338
+ return hasattr(compiled_fw, "_fx_graph_cache_key")
339
+
340
+ if cache_info is not None:
341
+ if should_save_cache():
342
+ time_taken_ns = time.time_ns() - cache_info.start_time_ns
343
+ guards_expr = AOTAutogradCache.generate_guards_expression(cache_info)
344
+ entry = AOTAutogradCache.make_entry(
345
+ compiled_fw_func=compiled_fw, # type: ignore[arg-type]
346
+ compiled_bw_func=None,
347
+ aot_joint_graph_str=None,
348
+ aot_forward_graph_str=aot_forward_graph_str,
349
+ aot_backward_graph_str=None,
350
+ runtime_metadata=fw_metadata,
351
+ dispatch_wrappers=wrappers,
352
+ maybe_subclass_meta=maybe_subclass_meta,
353
+ num_fw_outs_saved_for_bw=None,
354
+ indices_of_inps_to_detach=[],
355
+ forward_time_taken_ns=time_taken_ns,
356
+ backward_time_taken_ns=0,
357
+ sanitized_aot_config=sanitize_aot_config(aot_config),
358
+ guards_expr=guards_expr,
359
+ backward_state_indices=None,
360
+ num_symints_saved_for_bw=None,
361
+ serialized_bw_module=None,
362
+ )
363
+ AOTAutogradCache.save(
364
+ cache_info.cache_key, entry, remote=should_use_remote_autograd_cache()
365
+ )
366
+
367
+ compiled_fw = fakified_out_wrapper.post_compile(
368
+ compiled_fw,
369
+ aot_config,
370
+ runtime_metadata=fw_metadata,
371
+ )
372
+
373
+ compiled_fw = EffectTokensWrapper().post_compile(
374
+ compiled_fw,
375
+ aot_config,
376
+ runtime_metadata=fw_metadata,
377
+ )
378
+
379
+ # Why do we need to pass in num_fw_outs_saved_for_bw?
380
+ # See Note: [Partitioner handling for Subclasses, Part 2]
381
+ compiled_fw = AOTDispatchSubclassWrapper(
382
+ trace_joint=False,
383
+ # TODO: once we use pre_compile this will be flat_fn at the top of this function
384
+ fw_only=None,
385
+ maybe_subclass_meta=maybe_subclass_meta,
386
+ num_fw_outs_saved_for_bw=None,
387
+ ).post_compile(
388
+ compiled_fw,
389
+ aot_config, # not used
390
+ runtime_metadata=fw_metadata,
391
+ )
392
+
393
+ if not getattr(compiled_fw, "_boxed_call", False):
394
+ compiled_fw = make_boxed_func(compiled_fw)
395
+
396
+ compiled_fn = RuntimeWrapper(
397
+ indices_of_inps_to_detach=[],
398
+ trace_joint=False,
399
+ disable_amp=disable_amp,
400
+ ).post_compile(
401
+ compiled_fw,
402
+ aot_config,
403
+ runtime_metadata=fw_metadata,
404
+ )
405
+
406
+ compiled_fn = post_compile(
407
+ wrappers, compiled_fn, aot_config, runtime_metadata=fw_metadata
408
+ )
409
+ return compiled_fn
410
+
411
+
412
+ def collect_fw_donated_buffer_idxs(
413
+ fw_ins: list[Optional[FakeTensor]],
414
+ user_fw_outs: list[Optional[FakeTensor]],
415
+ bw_outs: list[Optional[FakeTensor]],
416
+ saved_tensors: list[FakeTensor],
417
+ ) -> list[int]:
418
+ """
419
+ Checks if the saved tensors are donated buffers, which means a saved tensor is not
420
+ an alias of any tensors in fw_ins, user_fw_outs, and bw_outs.
421
+ """
422
+
423
+ storage_refs = set()
424
+ for t in itertools.chain(fw_ins, user_fw_outs, bw_outs):
425
+ # Only access storage if a tensor has storage (not sparse)
426
+ if t is not None and isinstance(t, FakeTensor) and not is_sparse_any(t):
427
+ storage_refs.add(StorageWeakRef(t.untyped_storage()))
428
+
429
+ num_saved_tensor = len(saved_tensors)
430
+ donated_buffer_idxs = []
431
+ for i in range(num_saved_tensor):
432
+ t = saved_tensors[i]
433
+ if (
434
+ t is not None
435
+ and not is_sparse_any(t)
436
+ and StorageWeakRef(t.untyped_storage()) not in storage_refs
437
+ ):
438
+ donated_buffer_idxs.append(i)
439
+
440
+ return donated_buffer_idxs
441
+
442
+
443
+ def collect_bw_donated_buffer_idxs(
444
+ fw_module: torch.fx.GraphModule,
445
+ bw_module: torch.fx.GraphModule,
446
+ fw_metadata: ViewAndMutationMeta,
447
+ ) -> list[int]:
448
+ """
449
+ Collects backward donated buffer indexes from fw_module and bw_module.
450
+ """
451
+
452
+ # [Note: Metadata mutation in proxy tracing]
453
+ # node.meta["val"] is a snapshot of the tensor value when tracing a graph,
454
+ # instead of the final state after the graph has run. node.meta["val"] is
455
+ # not updated even if later there is a metadata mutation op.
456
+ # See: https://github.com/pytorch/pytorch/pull/141308#issuecomment-2495798947
457
+ #
458
+ # Currently, metadata mutation op happens only for sacrificial parameter
459
+ # specifically the `set_` op. This motivates banning metadata mutation from
460
+ # proxy tracing.
461
+ #
462
+ # Since node.meta["val"] is used to detect donated buffer, we return an empty
463
+ # list if there exists metadata mutation op.
464
+ if contain_metadata_mutation_ops(fw_module) or contain_metadata_mutation_ops(
465
+ bw_module
466
+ ):
467
+ return []
468
+
469
+ fw_ins = fw_module.graph.find_nodes(op="placeholder")
470
+ bw_outs = next(reversed(bw_module.graph.find_nodes(op="output"))).args[0]
471
+ fw_outs = next(reversed(fw_module.graph.find_nodes(op="output"))).args[0]
472
+
473
+ fw_ins = [
474
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
475
+ for n in fw_ins
476
+ ]
477
+ fw_outs = [
478
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
479
+ for n in fw_outs
480
+ ]
481
+ bw_outs = [
482
+ n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None
483
+ for n in bw_outs
484
+ ]
485
+
486
+ user_fw_outs = fw_outs[: fw_metadata.num_forward]
487
+ saved_tensors = fw_outs[fw_metadata.tensors_saved_for_backwards_slice]
488
+
489
+ fw_donated_buffer = collect_fw_donated_buffer_idxs(
490
+ fw_ins,
491
+ user_fw_outs,
492
+ bw_outs,
493
+ saved_tensors,
494
+ )
495
+
496
+ assert fw_metadata.num_symints_saved_for_bw is not None
497
+ return [fw_metadata.num_symints_saved_for_bw + i for i in fw_donated_buffer]
498
+
499
+
500
+ @dataclasses.dataclass
501
+ class InvokeSubgraphHopGraphs:
502
+ """
503
+ A data structure to hold all the information needed to partition the
504
+ `joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and
505
+ `new_bw_hop_gm` into the bigger `joint_gm`.
506
+ """
507
+
508
+ # To avoid re-partitioning subgraphs
509
+ partitioning_done: bool = False
510
+ old_num_fw_outputs: Optional[int] = None
511
+ old_num_fw_inputs: Optional[int] = None
512
+
513
+ new_fw_hop_gm: Optional[torch.fx.GraphModule] = None
514
+ new_bw_hop_gm: Optional[torch.fx.GraphModule] = None
515
+ new_num_sym_nodes: Optional[int] = None
516
+ new_num_saved_nodes: Optional[int] = None
517
+
518
+
519
+ def prepare_for_partitioner(mod, num_primals, num_fw_outputs):
520
+ # min-cut partitioner requires the placeholders to have primals and
521
+ # tangents string in the node.name. The signature of the joint graph is
522
+ # (*primals, *tangents)
523
+
524
+ # We also have to update the output signature which is right now
525
+ # (*grads, *fw_outs) and we have to change to (*fw_outs, *grads) for the
526
+ # partitioner to work.
527
+ new_graph = torch.fx.Graph()
528
+ env = {}
529
+
530
+ primals_counter = itertools.count(0)
531
+ tangents_counter = itertools.count(0)
532
+
533
+ for idx, node in enumerate(mod.graph.nodes):
534
+ if node.op == "placeholder":
535
+ if idx < num_primals:
536
+ env[node] = new_graph.placeholder(f"primals_{next(primals_counter)}")
537
+ else:
538
+ env[node] = new_graph.placeholder(f"tangents_{next(tangents_counter)}")
539
+ env[node].meta = copy.copy(node.meta)
540
+ elif node.op == "output":
541
+ # Reverse the (*grads, *fw_outs) to (*fw_outs, *grads)
542
+ # The reason for having the reversed signature in the first
543
+ # place is to simplify step 3.
544
+ old_outputs = node.args[0]
545
+ new_outputs = (
546
+ *old_outputs[-num_fw_outputs:],
547
+ *old_outputs[:-num_fw_outputs],
548
+ )
549
+ new_outputs = [env[n] if n else None for n in new_outputs]
550
+ new_graph.output(tuple(new_outputs))
551
+ else:
552
+ env[node] = new_graph.node_copy(node, lambda n: env[n])
553
+ env[node].meta = copy.copy(node.meta)
554
+
555
+ new_graph.lint()
556
+
557
+ out = torch.fx.GraphModule(mod, new_graph)
558
+ return out
559
+
560
+
561
+ def run_joint_graph_passes_on_hops(
562
+ joint_gm: torch.fx.GraphModule,
563
+ joint_inputs: Any,
564
+ aot_config: AOTConfig,
565
+ ) -> torch.fx.GraphModule:
566
+ """
567
+ This pass runs the joint graph passes on the HOP graph. In torch.compile, we
568
+ typically have many passes which work on the joint graph and then end with a
569
+ partitioner.
570
+
571
+
572
+ The partitioner part is quite mechanical to handle. HOP have their own
573
+ forward and backward graph. The process can be broken into following steps
574
+
575
+ 1) Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm`
576
+ 2) Run joint graph passes on the `joint_hop_gm` to get `new_fw_hop_gm` and `new_bw_hop_gm`
577
+ 3) Stitch the `new_fw_hop_gm` and `new_bw_hop_gm` back into the `joint_gm`.
578
+
579
+ The terminology used in the code is
580
+ `joint_graph/joint_gm` : Refers to the main graph. This may contain many HOPs which have their own `hop_graph`
581
+ `fw_hop_graph/fw_hop_gm` : Refers to the forward graph associated with a HOP.
582
+ `bw_hop_graph/bw_hop_gm` : Refers to the backward graph associated with a HOP.
583
+ `joint_hop_graph/joint_hop_gm` : Refers to the subgraph associated with the HOP like invoke_subgraph.
584
+ `new_fw_hop_graph/new_fw_hop_gm` : Refers to the forward graph after partitioning is applied to `joint_hop_gm`.
585
+ `new_bw_hop_graph/new_bw_hop_gm` : Refers to the backward graph after partitioning is applied to `joint_hop_gm`.
586
+
587
+ NB: This pass works for invoke_subgraph today because we took extra care in
588
+ the Autograd.Dispatch key of invoke_subgraph to vastly simplify Step 1.
589
+ """
590
+ from torch._higher_order_ops import invoke_subgraph
591
+
592
+ def num_outputs(mod):
593
+ return len(mod.graph.find_nodes(op="output")[0].args[0])
594
+
595
+ def num_inputs(mod):
596
+ return len(mod.graph.find_nodes(op="placeholder"))
597
+
598
+ new_hop_graphs: dict[str, InvokeSubgraphHopGraphs] = defaultdict(
599
+ lambda: InvokeSubgraphHopGraphs()
600
+ )
601
+
602
+ # Step 1 - Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` This is
603
+ # easy to do for `invoke_subgraph` HOP. During the Autograd dispatch key
604
+ # tracing, we have put the joint_hop_graph in the backward hop graph itself.
605
+ # So to recover the joint_hop_gm, we just have to look at the backward
606
+ # HOP graphs.
607
+ # So we will merge step 1 and step 2 in this next section
608
+
609
+ # Save the fw and bwd hop nodes. We will later in-place modify the graph
610
+ # using these nodes.
611
+ fw_hop_nodes = []
612
+ bw_hop_nodes = []
613
+ for node in joint_gm.graph.nodes:
614
+ if (
615
+ node.op == "call_function"
616
+ and node.target is invoke_subgraph
617
+ and isinstance(node.args[1], str)
618
+ ):
619
+ if node.args[1].startswith("fw"):
620
+ fw_hop_nodes.append(node)
621
+ elif node.args[1].startswith("bw"):
622
+ bw_hop_nodes.append(node)
623
+
624
+ if not bw_hop_nodes:
625
+ return joint_gm
626
+
627
+ assert len(fw_hop_nodes) == len(bw_hop_nodes)
628
+
629
+ # Create a bw to hop node mapping. This helps us in identifying the bw and
630
+ # fw subgraph pairs without relying on the identifier. This is important
631
+ # because we can have different subgraphs for bwd for same subgraph in the
632
+ # fwd because of differing strides in the backward.
633
+ bw_to_fw_hop_node = dict(zip(list(reversed(bw_hop_nodes)), fw_hop_nodes))
634
+
635
+ for node in bw_hop_nodes:
636
+ identifier = node.args[1].removeprefix("bw")
637
+
638
+ # If partitioning already done for this identifier, skip. This saves
639
+ # redundant joint graph passes for same subgraphs.
640
+ if new_hop_graphs[identifier].partitioning_done:
641
+ continue
642
+
643
+ # Collect some information from the forward hop graph
644
+ fw_hop_node = bw_to_fw_hop_node[node]
645
+ fw_hop_gm = getattr(joint_gm, fw_hop_node.args[0].target)
646
+ assert isinstance(fw_hop_gm, torch.fx.GraphModule)
647
+ num_fw_inputs = num_inputs(fw_hop_gm)
648
+ num_fw_outputs = num_outputs(fw_hop_gm)
649
+ new_hop_graphs[identifier].old_num_fw_inputs = num_fw_inputs
650
+ new_hop_graphs[identifier].old_num_fw_outputs = num_fw_outputs
651
+
652
+ # Step 1) - Get the `joint_hop_gm`. As mentioned earlier, the
653
+ # backward graph is the joint graph.
654
+ joint_hop_gm = getattr(joint_gm, node.args[0].target)
655
+ assert isinstance(joint_hop_gm, torch.fx.GraphModule)
656
+
657
+ # Prepare the graph for the partitioner
658
+ joint_hop_gm = prepare_for_partitioner(
659
+ joint_hop_gm, num_fw_inputs, num_fw_outputs
660
+ )
661
+
662
+ # TODO: invoke_subgraph should track which of its inputs static indices
663
+ # so it can propagate them to the partitioner (and use in cudagraphs)
664
+ static_lifetime_input_indices: list[int] = []
665
+ # Step 2) and 3) - Run joint graph passes and partitioner
666
+ new_fw_hop_gm, new_bw_hop_gm = aot_config.partition_fn(
667
+ joint_hop_gm,
668
+ [],
669
+ num_fwd_outputs=num_fw_outputs,
670
+ static_lifetime_input_indices=static_lifetime_input_indices,
671
+ )
672
+
673
+ # Save the new forward and backward graph modules
674
+ new_hop_graphs[identifier].new_fw_hop_gm = new_fw_hop_gm
675
+ new_hop_graphs[identifier].new_bw_hop_gm = new_bw_hop_gm
676
+
677
+ # Save the number of symints and saved tensors
678
+ new_fw_out_nodes = new_fw_hop_gm.graph.find_nodes(op="output")[0].args[0]
679
+ extra_outputs = new_fw_out_nodes[num_fw_outputs:]
680
+ symint_outputs = [n for n in extra_outputs if is_sym_node(n)]
681
+
682
+ new_hop_graphs[identifier].new_num_sym_nodes = len(symint_outputs)
683
+ new_hop_graphs[identifier].new_num_saved_nodes = len(extra_outputs) - len(
684
+ symint_outputs
685
+ )
686
+
687
+ new_hop_graphs[identifier].partitioning_done = True
688
+
689
+ # Step 3) Restitch the new fw and bw graphs back into the main graph.
690
+ #
691
+ # This is a very mechanical process. There are a quite a few pieces that we
692
+ # need to connect together to make it work. Lets try to understand the
693
+ # problem statement first.
694
+ #
695
+ # For the forward graph, the signature of the old_fw_hop_gm is
696
+ # inputs - (*primals)
697
+ # outputs - (*fw_outs)
698
+ # Now the signature of the new_fw_hop_gm is
699
+ # inputs - (*primals) -- This is same
700
+ # outputs - (*fw_outs, *saved_tensors) - This is different
701
+ # At a high level, this is an easy transformation, in the new graph we just
702
+ # have to replace the old_fw_hop_gm with the new_fw_hop_gm. Everything else
703
+ # falls into place, because the input signature (i.e. args) is same. And
704
+ # even though output signature is different, fw_outs are still at the same
705
+ # indexes as before. So the forward of the `joint_gm` works nicely.
706
+ #
707
+ # Now, lets look at the backward hop graph. Old signature
708
+ # inputs - (*primals, *tangents)
709
+ # outputs - (*grad_outs, *fw_outs)
710
+ # New signature
711
+ # inputs - (*saved_tensors, *tangents) -- Different
712
+ # outputs - (*grad_outs) -- Different
713
+ # Here both input and output signature change. The output signature handling
714
+ # is quite easy because the grads_out are sitting at the right place, so we
715
+ # dont have to do anything.
716
+ #
717
+ # For the input signature, we have to collect the saved tensors from the
718
+ # corresponding forward graph output. We collect all saved_tensors when we
719
+ # see the forward graph, and save it into a map and then later use it during
720
+ # the backward.
721
+
722
+ # The stack of fw_nodes for invoke_subgraph HOP. There is an implicit
723
+ # assumption about the graph structure, i.e., if we have hop1, hop2, hop3,
724
+ # ... in the forward part of the joint graph, we will have .., hop3, hop2,
725
+ # hop1 order for the backward. This structure allows us to just use a stack
726
+ # to collect all the information that we need to pass from the forward hop
727
+ # node to the corresponding backward node.
728
+
729
+ already_added_new_hop_mods = set()
730
+
731
+ def add_new_hop_gm(new_subgraph_mod, name):
732
+ new_subgraph_attr_name = f"partitioned_{name}"
733
+ if new_subgraph_attr_name in already_added_new_hop_mods:
734
+ return new_subgraph_attr_name
735
+
736
+ joint_gm.register_module(new_subgraph_attr_name, new_subgraph_mod)
737
+ already_added_new_hop_mods.add(new_subgraph_attr_name)
738
+ return new_subgraph_attr_name
739
+
740
+ def propagate_meta_info(new_hop_gm, new_call_function_node, old_call_function_node):
741
+ # Copy all the fields from the old call_function node. And then override
742
+ # the `val` meta field with the outputs of new_hop_gm.
743
+ new_call_function_node.meta = copy.copy(old_call_function_node.meta)
744
+
745
+ output = new_hop_gm.graph.find_nodes(op="output")[0]
746
+ out_example_vals = [n.meta["val"] if n else None for n in output.args[0]]
747
+ new_call_function_node.meta["val"] = tuple(out_example_vals)
748
+
749
+ for bw_node in reversed(bw_hop_nodes):
750
+ identifier = bw_node.args[1].removeprefix("bw")
751
+
752
+ # Make changes to the corresponding fw and bw node pair simultaneously.
753
+ # The removes the need of any bookkeeping.
754
+
755
+ # Fw node changes
756
+ # Insert the new_fw_hop_gm. This is straightforward. Get the
757
+ # new_fw_hop_gm, insert the hop_gm as a get_attr fw_node, and then
758
+ # add a call_function fw_node. Additionally, also use getitem
759
+ # call_functions to collect the saved_tensor nodes
760
+
761
+ fw_node = bw_to_fw_hop_node[bw_node]
762
+ new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm
763
+ assert new_fw_hop_gm is not None
764
+
765
+ old_num_fw_outputs = new_hop_graphs[identifier].old_num_fw_outputs
766
+ new_num_sym_nodes = new_hop_graphs[identifier].new_num_sym_nodes
767
+ new_num_saved_nodes = new_hop_graphs[identifier].new_num_saved_nodes
768
+ assert old_num_fw_outputs is not None
769
+ assert new_num_sym_nodes is not None
770
+ assert new_num_saved_nodes is not None
771
+ total_outputs = old_num_fw_outputs + new_num_saved_nodes + new_num_sym_nodes
772
+
773
+ extra_fw_outputs = []
774
+
775
+ # Insert the new_fw_hop_gm into the joint_gm
776
+ with joint_gm.graph.inserting_after(fw_node):
777
+ new_fw_mod_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}")
778
+ new_fw_mod_attr = joint_gm.graph.get_attr(new_fw_mod_attr_name)
779
+
780
+ # new_hop_fw_gm output signature is (*fw_outs, *saved_tensors)
781
+ with joint_gm.graph.inserting_after(new_fw_mod_attr):
782
+ new_fw_node = joint_gm.graph.call_function(
783
+ the_function=invoke_subgraph,
784
+ args=(
785
+ new_fw_mod_attr,
786
+ new_fw_mod_attr_name,
787
+ *fw_node.args[2:],
788
+ ),
789
+ )
790
+ propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node)
791
+
792
+ # old_num_fw_outputs = (*fw_outs)
793
+ # new_num_fw_outputs = (*fw_outs, *saved_tensors, *sym_nodes)
794
+ with joint_gm.graph.inserting_after(new_fw_node):
795
+ for fw_out_idx in range(old_num_fw_outputs, total_outputs):
796
+ saved_tensor_node = joint_gm.graph.call_function(
797
+ the_function=operator.getitem, args=(new_fw_node, fw_out_idx)
798
+ )
799
+ saved_tensor_node.meta = copy.copy(new_fw_node.meta)
800
+ saved_tensor_node.meta["val"] = new_fw_node.meta["val"][fw_out_idx]
801
+ extra_fw_outputs.append(saved_tensor_node)
802
+
803
+ fw_node.replace_all_uses_with(new_fw_node)
804
+ joint_gm.graph.erase_node(fw_node)
805
+
806
+ # Bw node changes
807
+ # Prepare the operands for the bwd graph
808
+ # Old bw graph signature : (*primals, *tangents)
809
+ # New signature will be : (*sym_nodes, *saved_tensors, *tangents)
810
+ # We have already collected the saved_tensors in the forward hop processing.
811
+
812
+ # extra_fw_outputs are in the order (*saved_nodes, *sym_nodes).
813
+ # Partitioner has this quirk where the backward wants sym_nodes
814
+ # first. So extract the sym and saved nodes.
815
+
816
+ new_bw_hop_gm = new_hop_graphs[identifier].new_bw_hop_gm
817
+ assert new_bw_hop_gm is not None
818
+
819
+ saved_tensor_nodes = extra_fw_outputs[:new_num_saved_nodes]
820
+ sym_nodes = extra_fw_outputs[new_num_saved_nodes:]
821
+
822
+ num_primals = new_hop_graphs[identifier].old_num_fw_inputs
823
+ assert num_primals is not None
824
+ tangents = list(bw_node.args[2 + num_primals :])
825
+ operands = sym_nodes + saved_tensor_nodes + tangents
826
+
827
+ # Insert the new_bw_hop_gm into the joint_gm
828
+ with joint_gm.graph.inserting_after(bw_node):
829
+ new_bw_mod_attr_name = add_new_hop_gm(new_bw_hop_gm, bw_node.args[1])
830
+ new_bw_mod_attr = joint_gm.graph.get_attr(new_bw_mod_attr_name)
831
+
832
+ with joint_gm.graph.inserting_after(new_bw_mod_attr):
833
+ new_bw_node = joint_gm.graph.call_function(
834
+ the_function=invoke_subgraph,
835
+ args=(
836
+ new_bw_mod_attr,
837
+ new_bw_mod_attr_name,
838
+ *operands,
839
+ ),
840
+ )
841
+ propagate_meta_info(new_bw_hop_gm, new_bw_node, bw_node)
842
+ # Since the partitioner is run after the graph passes, we have lost
843
+ # the eager information and cannot faithfully extract the eager
844
+ # inputs for the new partitioned backward graph. For the forward
845
+ # graph, it was fine because the input signature remains same.
846
+ new_bw_node.meta.pop("eager_input_vals", None)
847
+
848
+ bw_node.replace_all_uses_with(new_bw_node)
849
+ joint_gm.graph.erase_node(bw_node)
850
+
851
+ joint_gm.graph.eliminate_dead_code()
852
+ joint_gm.graph.lint()
853
+ joint_gm.recompile()
854
+ return joint_gm
855
+
856
+
857
+ def maybe_log_graph(
858
+ gm,
859
+ graph_name,
860
+ aot_config,
861
+ structured_log_prefix_fn,
862
+ out_structured_logs: Optional[list[str]] = None,
863
+ ):
864
+ if not aot_config.enable_log:
865
+ return
866
+ aot_graphs_log.debug(
867
+ "%s",
868
+ lazy_format_graph_code(
869
+ f"{graph_name}",
870
+ gm,
871
+ aot_config.aot_id,
872
+ include_stride=True,
873
+ include_device=True,
874
+ colored=True,
875
+ ),
876
+ )
877
+
878
+ def gm_str_fn() -> str:
879
+ return gm.print_readable(
880
+ print_output=False,
881
+ include_stride=True,
882
+ include_device=True,
883
+ expanded_def=True,
884
+ )
885
+
886
+ if out_structured_logs is not None:
887
+ out_structured_logs.append(f"{structured_log_prefix_fn()}:{gm_str_fn()}")
888
+ else:
889
+ trace_structured(
890
+ f"{structured_log_prefix_fn()}",
891
+ payload_fn=lambda: gm_str_fn(),
892
+ )
893
+
894
+
895
+ def create_wrap_fn(fn, args):
896
+ from torch.fx.experimental.proxy_tensor import maybe_enable_thunkify
897
+
898
+ from .functional_utils import from_fun, has_data_mutation, to_fun
899
+
900
+ def assert_no_mutation(t):
901
+ assert not has_data_mutation(t), (
902
+ "Saved tensors hooks with inputs mutations are not allowed"
903
+ )
904
+
905
+ @simple_wraps(fn)
906
+ def _wrapper(*args):
907
+ with maybe_enable_thunkify():
908
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
909
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
910
+ )
911
+
912
+ with disable_above:
913
+ f_args = pytree.tree_map(to_fun, args)
914
+ f_outs = fn(*f_args)
915
+ pytree.tree_map(assert_no_mutation, f_args)
916
+ return pytree.tree_map(from_fun, f_outs)
917
+
918
+ return _wrapper, args
919
+
920
+
921
+ def prepare_hook_gm(aot_config, fn, args):
922
+ from torch._functorch._aot_autograd.graph_capture import _create_graph
923
+
924
+ fn, args = create_wrap_fn(fn, args)
925
+ gm = _create_graph(fn, args, aot_config=aot_config)
926
+ return gm
927
+
928
+
929
+ # Inline Autograd saved_tensors_hooks into epilogue of forward graph
930
+ # and prologue of backward graph.
931
+ # This changes forward graph outputs and inputs.
932
+ # Pack hook can return tensors, sym scalars, constants.
933
+ # All tensors to save for backward will be grouped together at front.
934
+ # Sym scalars grouped on another end. Constants are inlined in the graph.
935
+ def maybe_inline_graph_saved_tensors_hooks(
936
+ fw_module, # torch.fx.GraphModule
937
+ bw_module, # torch.fx.GraphModule
938
+ num_inner_fwd_outputs,
939
+ inner_meta,
940
+ aot_config,
941
+ static_input_indices,
942
+ ):
943
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
944
+ return
945
+
946
+ get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks
947
+ are_inline_hooks = (
948
+ torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable
949
+ )
950
+
951
+ hooks = get_hooks()
952
+ if not are_inline_hooks(hooks):
953
+ return
954
+
955
+ pack_hook_gm, unpack_hook_gm = hooks
956
+
957
+ structured_logs: list[str] = []
958
+ maybe_log_graph(
959
+ fw_module,
960
+ "Forward graph pre saved_tensors_hooks inlining",
961
+ aot_config,
962
+ lambda: "aot_forward_graph_pre_saved_tensors_hooks",
963
+ structured_logs,
964
+ )
965
+ maybe_log_graph(
966
+ bw_module,
967
+ "Backward graph pre saved_tensors_hooks inlining",
968
+ aot_config,
969
+ lambda: "aot_backward_graph_pre_saved_tensors_hooks",
970
+ structured_logs,
971
+ )
972
+ fw_g = fw_module.graph
973
+ bw_g = bw_module.graph
974
+
975
+ fw_g_names = {node.name for node in fw_g.nodes}
976
+ bw_g_names = {node.name for node in bw_g.nodes}
977
+
978
+ def _gen_unused_name(candidate: str):
979
+ c = candidate
980
+ i = 0
981
+ while c in fw_g_names or c in bw_g_names:
982
+ c = f"{candidate}_{i}"
983
+ i = i + 1
984
+ return c
985
+
986
+ bw_g_inputs = bw_g.find_nodes(op="placeholder")
987
+
988
+ fw_out_n = fw_g.output_node()
989
+ fw_outs = fw_out_n.args[0] # type: ignore[var-annotated]
990
+ fw_outs_inner_set = set(fw_outs[:num_inner_fwd_outputs])
991
+ fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
992
+ fw_outs_packed_tensors = [] # type: ignore[var-annotated]
993
+ fw_outs_packed_syms = [] # type: ignore[var-annotated]
994
+
995
+ # The main use case for saved_tensors_hooks is activation quantization,
996
+ # for memory usage optimization.
997
+ # Desired behavior is to quantize saved activations to free the original saved tensor.
998
+ # Saved nodes may include forward inputs, outputs, parameters.
999
+ # They may be held by something else and will not be deallocated after quantization.
1000
+ # Donated buffers are intermediates in the graph invisible for the user,
1001
+ # this guarantees that they can be deallocated.
1002
+ # Using this as a default behavior to select saved nodes to apply hooks.
1003
+ # There is also a config to apply hooks for all saved nodes without any filtering.
1004
+ # The plan is to propagate meta about the source of the saved node to the user hook function.
1005
+ mode = torch._functorch.config.saved_tensors_hooks_filtering_mode
1006
+ allow_set = None
1007
+ exclude_set = None
1008
+
1009
+ if mode == "donated":
1010
+ # collect_bw_donated_buffer_idxs requires inner_meta to have num_symints_saved_for_bw
1011
+ inner_meta.num_symints_saved_for_bw = len(
1012
+ [n for n in fw_outs_saved_for_bw if is_sym_node(n)]
1013
+ )
1014
+ bw_donated_idxs = collect_bw_donated_buffer_idxs(
1015
+ fw_module,
1016
+ bw_module,
1017
+ inner_meta,
1018
+ )
1019
+ fw_donated_idxs = [
1020
+ i - inner_meta.num_symints_saved_for_bw for i in bw_donated_idxs
1021
+ ]
1022
+ allow_set = {fw_outs_saved_for_bw[i].name for i in fw_donated_idxs}
1023
+ elif mode == "no_static":
1024
+ fw_g_inputs = fw_g.find_nodes(op="placeholder")
1025
+ exclude_set = {fw_g_inputs[i].name for i in static_input_indices}
1026
+
1027
+ if (allow_set is not None) and (not allow_set):
1028
+ # This means we have empty whitelist,
1029
+ # No donated (intermediate) saved.
1030
+ # Do not do anything in this case
1031
+ return
1032
+
1033
+ if aot_config.enable_log:
1034
+ structured_logs.append(f"fw_outs_saved_for_bw:{fw_outs_saved_for_bw}")
1035
+ structured_logs.append(f"mode:{mode}")
1036
+ structured_logs.append(f"allow_set:{allow_set}")
1037
+ structured_logs.append(f"exclude_set:{exclude_set}")
1038
+
1039
+ for saved in fw_outs_saved_for_bw:
1040
+ if ((allow_set is not None) and (saved.name not in allow_set)) or (
1041
+ (exclude_set is not None) and (saved.name in exclude_set)
1042
+ ):
1043
+ if isinstance(saved.meta["val"], torch.Tensor):
1044
+ fw_outs_packed_tensors.append(saved)
1045
+ continue
1046
+
1047
+ val = saved.meta["val"]
1048
+ if not isinstance(val, torch.Tensor):
1049
+ continue
1050
+
1051
+ pack_out_val = pack_hook_gm(val)
1052
+
1053
+ requires_sc_handling = any(
1054
+ is_traceable_wrapper_subclass(x) for x in pytree.tree_leaves(pack_out_val)
1055
+ )
1056
+ if requires_sc_handling:
1057
+ raise NotImplementedError(
1058
+ "Tensor subclasses in GraphModule saved tensors hooks are not supported"
1059
+ "You can workaround it by manually returning subclass's inner tensors"
1060
+ " in the pack hook, and reconstructing the subclass in the unpack hook"
1061
+ )
1062
+
1063
+ pack_gm = prepare_hook_gm(aot_config, pack_hook_gm, (val,))
1064
+ pack_g = pack_gm.graph
1065
+ maybe_log_graph(
1066
+ pack_gm,
1067
+ f"saved_tensors_pack_hook {saved.name}",
1068
+ aot_config,
1069
+ lambda: f"aot_saved_tensors_hooks_pack {saved.name}",
1070
+ structured_logs,
1071
+ )
1072
+ pack_out_val = pack_gm(val)
1073
+
1074
+ # Install pack hook graph as eiplogue of fw_module.
1075
+ # Saved tensor output becomes input of pack hook graph.
1076
+ # Replace saved tensor output with pack hook graph output.
1077
+ # Outputs symbolic scalars, tensors are accumulated separately.
1078
+ # Then in forward outputs and backward inputs installed in order
1079
+ # sym_scalars, packed_saved_tensors.
1080
+ # Keeping all tensors together allows to preserve
1081
+ # the same identification at runtime,
1082
+ # updating only number of saved sym_scalars and tensors.
1083
+ pack_g_inputs = pack_g.find_nodes(op="placeholder")
1084
+ assert len(pack_g_inputs) == 1
1085
+ env = {pack_g_inputs[0]: saved}
1086
+ fw_pack_out_args = None
1087
+ with fw_g.inserting_before(fw_out_n):
1088
+ for node in pack_g.nodes:
1089
+ if node.op == "placeholder":
1090
+ continue
1091
+ new_n = fw_g.node_copy(node, lambda n: env[n])
1092
+ fw_g_names.add(new_n.name)
1093
+ env[node] = new_n
1094
+ # Output node is temporarily copied to have remapped arguments.
1095
+ # Removed in the end.
1096
+ if node.op == "output":
1097
+ fw_pack_out_args = new_n.args[0]
1098
+ fw_g.erase_node(new_n)
1099
+
1100
+ env.clear()
1101
+ assert fw_pack_out_args
1102
+ fw_outs_bw_ins_node_names = []
1103
+ for out_idx, _n in enumerate(pytree.tree_leaves(fw_pack_out_args)):
1104
+ if not isinstance(_n, torch.fx.Node):
1105
+ fw_outs_bw_ins_node_names.append("")
1106
+ continue
1107
+
1108
+ # This happens when hook is noop and it is either user input or user output.
1109
+ # Do not do anything with this node.
1110
+ if _n.op == "placeholder" or _n in fw_outs_inner_set:
1111
+ # This means the hook returned input primals unchanged
1112
+ # Do not rename in this case.
1113
+ n = _n
1114
+ new_node_name = _n.name
1115
+ fw_outs_bw_ins_node_names.append(new_node_name)
1116
+ else:
1117
+ # We can not specify desired name in node_copy.
1118
+ # Copying node manually to set specific name,
1119
+ # to have matching fw_outs, bw_inputs names.
1120
+ new_node_name = _gen_unused_name(f"{saved.name}_hook_{out_idx}")
1121
+ with fw_g.inserting_before(_n):
1122
+ n = fw_g.create_node(
1123
+ _n.op,
1124
+ _n.target,
1125
+ _n.args,
1126
+ _n.kwargs,
1127
+ name=new_node_name,
1128
+ )
1129
+ assert n.name == new_node_name
1130
+ fw_outs_bw_ins_node_names.append(new_node_name)
1131
+ n.meta = copy.copy(_n.meta)
1132
+ _n.replace_all_uses_with(n)
1133
+ fw_g.erase_node(_n)
1134
+ if isinstance(n.meta["val"], torch.Tensor):
1135
+ fw_outs_packed_tensors.append(n)
1136
+ elif is_sym_node(n):
1137
+ fw_outs_packed_syms.append(n)
1138
+
1139
+ # Install unpack hook graph as a prologue of backward graph
1140
+ # Saved tensors inputs are replaced with packed tensors and packed sym scalars.
1141
+ # The saved tensors inputs usages in the graph are replaced with unpack hook graph outputs.
1142
+ unpack_gm = prepare_hook_gm(aot_config, unpack_hook_gm, (pack_out_val,))
1143
+ unpack_g = unpack_gm.graph
1144
+ maybe_log_graph(
1145
+ unpack_gm,
1146
+ f"saved_tensors_unpack_hook {saved.name}",
1147
+ aot_config,
1148
+ lambda: f"aot_saved_tensors_hooks_unpack {saved.name}",
1149
+ structured_logs,
1150
+ )
1151
+
1152
+ def find_saved_in_bw_inputs(bw_inputs):
1153
+ for n in bw_inputs:
1154
+ if n.name == saved.name:
1155
+ return n
1156
+
1157
+ bw_g_input = find_saved_in_bw_inputs(bw_g_inputs)
1158
+ assert bw_g_input
1159
+ original_bw_g_input_users = list(bw_g_input.users.keys())
1160
+ bw_g_input_used_directly = False
1161
+
1162
+ # Replace backward graph saved tensor input with copy of pack graph outputs
1163
+ # All non-Tensor, non-symscalars outputs are constanted.
1164
+
1165
+ unpack_g_inputs = unpack_g.find_nodes(op="placeholder")
1166
+ env = {}
1167
+ for out_idx, (unp_in_n, out_n, val) in enumerate(
1168
+ zip(
1169
+ unpack_g_inputs,
1170
+ pytree.tree_leaves(fw_pack_out_args),
1171
+ pytree.tree_leaves(pack_out_val),
1172
+ )
1173
+ ):
1174
+ is_sym = isinstance(val, py_sym_types)
1175
+ if isinstance(val, torch.Tensor) or is_sym:
1176
+ # We want forward_outputs names to match backward_inputs,
1177
+ # Potentially backward may already have "{saved.name}_hook_{idx}",
1178
+ # In this case fx.Graph will add suffix.
1179
+ new_node_name = fw_outs_bw_ins_node_names[out_idx]
1180
+ if bw_g_input.name == new_node_name:
1181
+ env[unp_in_n] = bw_g_input
1182
+ bw_g_input_used_directly = True
1183
+ else:
1184
+ # Backward calling convention: ctx_symints,ctx_saved_tensors
1185
+ # Inserting packed sym scalars before first saved tensor input.
1186
+ # Inserting packed tensors before last saved tensor input.
1187
+ # Saved tensor inputs between them will be removed.
1188
+ with (
1189
+ bw_g.inserting_before(bw_g_inputs[0])
1190
+ if is_sym
1191
+ else bw_g.inserting_before(bw_g_input)
1192
+ ):
1193
+ new_n = bw_g.placeholder(new_node_name)
1194
+ assert new_n.name == new_node_name
1195
+ new_n.meta = copy.copy(out_n.meta)
1196
+ env[unp_in_n] = new_n
1197
+ else:
1198
+ # Inline values of non-Tensor, non-SymScalars
1199
+ env[unp_in_n] = val
1200
+
1201
+ # Inserting unpack hook after placeholders.
1202
+ bw_unpack_out_n = None
1203
+ with bw_g.inserting_before(bw_g_inputs[-1].next):
1204
+ for node in unpack_g.nodes:
1205
+ if node.op == "placeholder":
1206
+ continue
1207
+ new_n = bw_g.node_copy(node, lambda n: env[n])
1208
+ bw_g_names.add(new_n.name)
1209
+ env[node] = new_n
1210
+ # Temporary insert output, to have remapped by node_copy args.
1211
+ # Removed in the end.
1212
+ if node.op == "output":
1213
+ bw_unpack_out_n = new_n
1214
+
1215
+ assert bw_unpack_out_n
1216
+ _leaves = pytree.tree_leaves(bw_unpack_out_n.args)
1217
+ assert len(_leaves) == 1
1218
+ unpack_saved_tensor_n = _leaves[0]
1219
+
1220
+ if not bw_g_input_used_directly:
1221
+ bw_g_input.replace_all_uses_with(unpack_saved_tensor_n)
1222
+ bw_g.erase_node(bw_g_input)
1223
+ else:
1224
+ # Keep usages of bw_g_input in inserted unpacked hook graph.
1225
+ # Replace other usages of bw_g_input with unpack_saved_tensor_n.
1226
+ from torch._C import _fx_map_arg
1227
+
1228
+ def maybe_replace_node(n):
1229
+ return unpack_saved_tensor_n if n == bw_g_input else n
1230
+
1231
+ for use_node in original_bw_g_input_users:
1232
+ new_args = _fx_map_arg(use_node.args, maybe_replace_node)
1233
+ new_kwargs = _fx_map_arg(use_node.kwargs, maybe_replace_node)
1234
+ assert isinstance(new_args, tuple)
1235
+ assert isinstance(new_kwargs, dict)
1236
+ use_node._update_args_kwargs(new_args, new_kwargs)
1237
+ bw_g.erase_node(bw_unpack_out_n)
1238
+
1239
+ # Changing forward graph outputs,
1240
+ # Inserting packed_tensors and packed_syms on the place of saved tensors.
1241
+ # Packed sym_scalars are together with saved symints
1242
+ symint_outs_saved_for_bw = [n for n in fw_outs_saved_for_bw if is_sym_node(n)]
1243
+ fw_new_outs = pytree.tree_leaves(
1244
+ (
1245
+ fw_outs[:num_inner_fwd_outputs],
1246
+ fw_outs_packed_tensors,
1247
+ fw_outs_packed_syms,
1248
+ symint_outs_saved_for_bw,
1249
+ )
1250
+ )
1251
+ fw_out_n.args = (tuple(fw_new_outs),)
1252
+
1253
+ # Assert that saved tensors and symints in forward outputs are aligned with backward inputs
1254
+ _fw_n = num_inner_fwd_outputs
1255
+ _fw_num_t = len(fw_outs_packed_tensors)
1256
+ _fw_num_s = len(fw_outs_packed_syms) + len(symint_outs_saved_for_bw)
1257
+ fw_outs_saved_tensors = fw_new_outs[_fw_n : _fw_n + _fw_num_t]
1258
+ fw_outs_saved_syms = fw_new_outs[_fw_n + _fw_num_t :]
1259
+ bw_new_ins = list(bw_g.find_nodes(op="placeholder"))
1260
+ bw_ins_saved_syms = bw_new_ins[:_fw_num_s]
1261
+ bw_ins_saved_tensors = bw_new_ins[_fw_num_s : _fw_num_s + _fw_num_t]
1262
+
1263
+ fw_t_names = [n.name for n in fw_outs_saved_tensors]
1264
+ bw_t_names = [n.name for n in bw_ins_saved_tensors]
1265
+ fw_s_names = [n.name for n in fw_outs_saved_syms]
1266
+ bw_s_names = [n.name for n in bw_ins_saved_syms]
1267
+
1268
+ def _log_structured_logs():
1269
+ if not aot_config.enable_log:
1270
+ return
1271
+
1272
+ trace_structured(
1273
+ "artifact",
1274
+ metadata_fn=lambda: {
1275
+ "name": "aot_saved_tensors_hooks_graphs",
1276
+ "encoding": "string",
1277
+ },
1278
+ payload_fn=lambda: "\n".join(structured_logs),
1279
+ )
1280
+
1281
+ if aot_config.enable_log:
1282
+ structured_logs.append(
1283
+ f"fw_outs[:num_inner_fwd_outputs]:{fw_outs[:num_inner_fwd_outputs]}"
1284
+ )
1285
+ structured_logs.append(f"fw_outs_packed_tensors:{fw_outs_packed_tensors}")
1286
+ structured_logs.append(f"fw_t_names:{fw_t_names}")
1287
+ structured_logs.append(f"bw_t_names:{bw_t_names}")
1288
+ structured_logs.append(f"fw_s_names:{fw_s_names}")
1289
+ structured_logs.append(f"bw_s_names:{bw_s_names}")
1290
+ structured_logs.append(f"\nfw_g_pre_assert:{fw_g}")
1291
+ structured_logs.append(f"\nbw_g_pre_assert:{bw_g}")
1292
+ maybe_log_graph(
1293
+ fw_module,
1294
+ "Forward graph after transform pre-assert",
1295
+ aot_config,
1296
+ lambda: "aot_forward_graph_pre_assert_saved_tensors_hooks",
1297
+ structured_logs,
1298
+ )
1299
+ maybe_log_graph(
1300
+ bw_module,
1301
+ "Backward graph after transform pre-assert",
1302
+ aot_config,
1303
+ lambda: "aot_backward_graph_pre_assert_saved_tensors_hooks",
1304
+ structured_logs,
1305
+ )
1306
+ _log_structured_logs()
1307
+
1308
+ assert fw_t_names == bw_t_names
1309
+ assert fw_s_names == bw_s_names
1310
+
1311
+ fw_g.lint()
1312
+ bw_g.lint()
1313
+ fw_module.recompile()
1314
+ bw_module.recompile()
1315
+
1316
+
1317
+ def aot_stage2_autograd(
1318
+ aot_state: AOTState, aot_graph_capture: AOTGraphCapture
1319
+ ) -> DispatchReturn:
1320
+ """
1321
+ Autograd logic. Generates a joint graph, partitions it, manipulates the input with various wrappers,
1322
+ and returns a wrapped torch.autograd.Function with a forward and backward.
1323
+ """
1324
+
1325
+ wrappers = aot_graph_capture.wrappers
1326
+ fx_g = aot_graph_capture.graph_module
1327
+ flat_args = aot_state.flat_args
1328
+ joint_inputs = aot_graph_capture.updated_flat_args
1329
+ maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta
1330
+ aot_config = aot_state.aot_config
1331
+ fw_metadata = aot_state.fw_metadata
1332
+
1333
+ CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="autograd")
1334
+
1335
+ # Copied from aot_dispatch_autograd_graph.
1336
+ disable_amp = torch._C._is_any_autocast_enabled()
1337
+ joint_graph_str = None
1338
+ if aot_config.enable_log:
1339
+ aot_joint_log.info(
1340
+ "%s",
1341
+ lazy_format_graph_code(
1342
+ "Joint graph",
1343
+ fx_g,
1344
+ aot_config.aot_id,
1345
+ include_stride=True,
1346
+ include_device=True,
1347
+ colored=True,
1348
+ ),
1349
+ )
1350
+ joint_graph_str = fx_g.print_readable(
1351
+ print_output=False,
1352
+ include_stride=True,
1353
+ include_device=True,
1354
+ expanded_def=True,
1355
+ )
1356
+ trace_structured(
1357
+ "aot_joint_graph",
1358
+ payload_fn=lambda: joint_graph_str,
1359
+ )
1360
+
1361
+ with torch.no_grad():
1362
+ inner_meta = (
1363
+ fw_metadata
1364
+ if maybe_subclass_meta is None
1365
+ else maybe_subclass_meta.fw_metadata
1366
+ )
1367
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
1368
+ with context(), track_graph_compiling(aot_config, "joint"):
1369
+ # See Note: [Partitioner handling for Subclasses, Part 1]
1370
+ # See Note: [Recomputing subclass mutation handling]
1371
+ mutated_inp_runtime_indices = (
1372
+ compute_inner_mutated_inp_indices_from_subclass_meta(
1373
+ fw_metadata, inner_meta
1374
+ )
1375
+ )
1376
+ num_tokens = len(fw_metadata.tokens)
1377
+ num_mutated_inp_runtime_indices = len(mutated_inp_runtime_indices)
1378
+ num_inner_fwd_outputs = (
1379
+ num_mutated_inp_runtime_indices
1380
+ + inner_meta.num_outputs
1381
+ + inner_meta.num_intermediate_bases
1382
+ + inner_meta.num_outputs_rng_offset
1383
+ + num_tokens # See Note [Side-Effectful Tokens in AOTAutograd]
1384
+ )
1385
+ fake_mode = detect_fake_mode()
1386
+ fx_g = run_joint_graph_passes_on_hops(fx_g, joint_inputs, aot_config)
1387
+
1388
+ # TODO(anijain2305) - Add tensorify_python_scalars to the HOP graph passes.
1389
+ if fake_mode is not None and fake_mode.shape_env is not None:
1390
+ tensorify_python_scalars(fx_g, fake_mode.shape_env, fake_mode)
1391
+
1392
+ static_lifetime_input_indices = fw_metadata.static_input_indices
1393
+ fw_module, bw_module = aot_config.partition_fn(
1394
+ fx_g,
1395
+ joint_inputs,
1396
+ num_fwd_outputs=num_inner_fwd_outputs,
1397
+ static_lifetime_input_indices=static_lifetime_input_indices,
1398
+ )
1399
+ rng_states = [
1400
+ n
1401
+ for n in fw_module.graph.find_nodes(op="placeholder")
1402
+ if "fwd_rng_state" in n.name
1403
+ ]
1404
+ fw_metadata.num_graphsafe_rng_states = len(rng_states)
1405
+ if rng_states:
1406
+ fw_metadata.graphsafe_rng_state_index = (
1407
+ rng_states[0].meta["val"].device.index
1408
+ )
1409
+
1410
+ # See Note [Side-Effectful Tokens in AOTAutograd]
1411
+ if config.unlift_effect_tokens and (
1412
+ num_tokens > 0 or fw_metadata.num_backward_tokens > 0
1413
+ ):
1414
+ unlift_tokens(fw_module, fw_metadata, aot_config, bw_module)
1415
+
1416
+ num_inner_fwd_outputs -= num_tokens
1417
+ joint_inputs = (
1418
+ joint_inputs[0][num_tokens:],
1419
+ joint_inputs[1],
1420
+ )
1421
+
1422
+ maybe_inline_graph_saved_tensors_hooks(
1423
+ fw_module,
1424
+ bw_module,
1425
+ num_inner_fwd_outputs,
1426
+ inner_meta,
1427
+ aot_config,
1428
+ fw_metadata.static_input_indices,
1429
+ )
1430
+ static_lifetime_input_indices = fw_metadata.static_input_indices
1431
+
1432
+ fw_outs = next(iter(fw_module.graph.find_nodes(op="output"))).args[0]
1433
+ # we only need to bookkeep the symints that are saved for bw, not any symints
1434
+ # the user forward might have returned in its own output
1435
+ fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
1436
+ num_fw_outs_saved_for_bw = len(fw_outs_saved_for_bw)
1437
+ symint_outs_saved_for_bw = []
1438
+ for idx, node in enumerate(fw_outs_saved_for_bw):
1439
+ if is_sym_node(node):
1440
+ symint_outs_saved_for_bw.append(node)
1441
+ elif (
1442
+ isinstance(node, torch.fx.Node)
1443
+ and "val" in getattr(node, "meta", {})
1444
+ and isinstance(node.meta["val"], FakeTensor)
1445
+ ):
1446
+ # record dynamic tensor activations
1447
+ dynamic_dims: set[int] = {
1448
+ dim
1449
+ for dim, size in enumerate(node.meta["val"].shape)
1450
+ if not isinstance(size, int)
1451
+ }
1452
+ if dynamic_dims:
1453
+ fw_metadata.dynamic_saved_tensors_idxs[idx] = dynamic_dims
1454
+
1455
+ fw_metadata.num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1456
+ inner_meta.num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1457
+ num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
1458
+ if torch._functorch.config.donated_buffer:
1459
+ fw_metadata.bw_donated_idxs = collect_bw_donated_buffer_idxs(
1460
+ fw_module,
1461
+ bw_module,
1462
+ inner_meta,
1463
+ )
1464
+ inner_meta.bw_donated_idxs = fw_metadata.bw_donated_idxs
1465
+
1466
+ if aot_config.enable_log:
1467
+ trace_structured(
1468
+ "artifact",
1469
+ metadata_fn=lambda: {
1470
+ "name": "torch._functorch.config",
1471
+ "encoding": "string",
1472
+ },
1473
+ payload_fn=lambda: torch._functorch.config.get_config_copy(),
1474
+ )
1475
+ aot_graphs_log.info(
1476
+ "aot_config id: %s, fw_metadata=%s, inner_meta=%s",
1477
+ str(aot_config.aot_id),
1478
+ str(fw_metadata),
1479
+ str(inner_meta),
1480
+ )
1481
+
1482
+ # Note [Detaching inputs that never need gradients]
1483
+ # See https://github.com/pytorch/pytorch/issues/97745
1484
+ # Suppose we have a function like this that we want to compile:
1485
+ #
1486
+ # def f(x, y):
1487
+ # return torch.mul(x, y.detach())
1488
+ #
1489
+ # What gradients should we compute for x and y?
1490
+ # By default, AOTAutograd will compute a gradient for **every** input that requires gradients,
1491
+ # and so we'll compute:
1492
+ # x_grad_input = y
1493
+ # y_grad_input = None
1494
+ # Does this preserve the semantics of eager mode?
1495
+ # Unfortunately, no.
1496
+ # Doing the above will cause autograd to **continue** to backprop the autograd tape
1497
+ # that was generated from constructing y.
1498
+ #
1499
+ # This is **different** from what would have happened in eager mode.
1500
+ # In eager mode, if we backprop through the output of this function, autograd will only traverse
1501
+ # the bit of the autograd tape corresponding to "x".
1502
+ # In particular, if a user had previously backpropped through y's autograd tape,
1503
+ # And then they try to backprop through the output of the above function,
1504
+ # then we'll hit the dreaded "Trying to backward through the graph a second time" error.
1505
+ #
1506
+ # You might think: If autograd sees that a gradient is None, shouldn't it stop early,
1507
+ # instead of continuing the backprop through the ancestors of that node in the graph?
1508
+ #
1509
+ # Autograd has two passes:
1510
+ # (1) a first pass that traverses the autograd graph and figures out which nodes need to be executed
1511
+ # (2) a second pass that actually goes ahead and executes each node when it becomes ready,
1512
+ # propagating gradients
1513
+ # By the time we're executing a node and we see that it produces a None, the set of nodes to execute
1514
+ # is already locked-in.
1515
+ #
1516
+ # The fix: instead, we can recognize statically that the graph we're compiling will never contribute
1517
+ # gradients to y, and prevent autograd from trying to traverse y's autograd tape at all.
1518
+ # We can do this by manually detach'ing y before sending it through the `CompiledFunction`.
1519
+ #
1520
+ # Note that this solution is not bulletproof.
1521
+ # It's possible to construct a case where eager may or may not have have tried to autograd through y,
1522
+ # depending on the actual grad_outputs that were passed in during the backward.
1523
+ # There is no easy fix for this: the simplest fix would be to run with `retain_graph=True`,
1524
+ # allowing autograd to reuse the graph.
1525
+ #
1526
+ # An example of this case is:
1527
+ # def f(x):
1528
+ # return x.detach() * 2, x * 3
1529
+ # If we were to only backprop through outs[0], in eager, we would stop
1530
+ # If we backward only on the first output, we shouldn't send a grad through x.
1531
+ # But the custom autograd function doesn't know that: it will materialize zero grads for x * 3
1532
+ # and we will end up with a zero grad at x.
1533
+ # If we later backprop through the second output, this will also require backprop'ing through x.
1534
+ # Meaning we'll need to use `retain_graph=True` to be able to backprop through x the second time.
1535
+ _indices_of_inps_to_detach: list[int] = []
1536
+
1537
+ # reversed() since we expect output at end of graph
1538
+ bw_output = next(reversed(bw_module.graph.find_nodes(op="output")))
1539
+ bw_outs: Sequence[torch.fx.Node] = bw_output.args[0] # type: ignore[assignment]
1540
+
1541
+ # TODO: we should apply the below "detach inputs if their gradients are statically known to be None"
1542
+ # optimization even if we have subclass inputs/outputs (we do not handle this today).
1543
+ # Computing which our our inputs get None gradients is a bit more complicated,
1544
+ # if any of our inputs are subclasses. Why?
1545
+ # (a) we need to make sure that we call .detach() on the input subclasses, since autograd sees subclasses.
1546
+ # (b) The grad_outputs that we AOT computed in our backward graph are the desugared tensor tensors,
1547
+ # so we need to figure out which subclass fw inputs they map to.
1548
+ if maybe_subclass_meta is None:
1549
+ num_backward_tokens: int = inner_meta.num_backward_tokens
1550
+ assert (
1551
+ len(bw_outs)
1552
+ == len(fw_metadata.input_info)
1553
+ + inner_meta.num_outputs_rng_offset
1554
+ + num_backward_tokens
1555
+ )
1556
+ bw_outs_no_rng_no_tokens = bw_outs
1557
+ if (inner_meta.num_outputs_rng_offset + num_backward_tokens) > 0:
1558
+ bw_outs_no_rng_no_tokens = bw_outs[
1559
+ : -(inner_meta.num_outputs_rng_offset + num_backward_tokens)
1560
+ ]
1561
+ assert len(bw_outs_no_rng_no_tokens) == len(fw_metadata.input_info)
1562
+
1563
+ for i, (bw_out) in enumerate(bw_outs_no_rng_no_tokens):
1564
+ # If our input experiences a metadata mutation inside the graph (e.g. set_()),
1565
+ # we *must* not detach, otherwise it will be the detach'd input that gets the metadata mutation
1566
+ metadata_mutation_in_graph = (
1567
+ fw_metadata.input_info[i].mutation_type
1568
+ == MutationType.MUTATED_IN_GRAPH
1569
+ and fw_metadata.input_info[i].mutates_storage_metadata
1570
+ )
1571
+ is_non_leaf = (
1572
+ fw_metadata.input_info[i].requires_grad
1573
+ and not fw_metadata.input_info[i].is_leaf
1574
+ )
1575
+ if bw_out is None and not metadata_mutation_in_graph and is_non_leaf:
1576
+ _indices_of_inps_to_detach.append(i)
1577
+
1578
+ fw_module_str = None
1579
+ bw_module_str = None
1580
+ if aot_config.enable_log:
1581
+ aot_graphs_log.info(
1582
+ "%s",
1583
+ lazy_format_graph_code(
1584
+ "Forward graph",
1585
+ fw_module,
1586
+ aot_config.aot_id,
1587
+ include_stride=True,
1588
+ include_device=True,
1589
+ colored=True,
1590
+ ),
1591
+ )
1592
+ aot_graphs_log.info(
1593
+ "%s",
1594
+ lazy_format_graph_code(
1595
+ "Backward graph",
1596
+ bw_module,
1597
+ aot_config.aot_id,
1598
+ include_stride=True,
1599
+ include_device=True,
1600
+ colored=True,
1601
+ ),
1602
+ )
1603
+ fw_module_str = fw_module.print_readable(
1604
+ print_output=False,
1605
+ include_stride=True,
1606
+ include_device=True,
1607
+ expanded_def=True,
1608
+ )
1609
+ bw_module_str = bw_module.print_readable(
1610
+ print_output=False,
1611
+ include_stride=True,
1612
+ include_device=True,
1613
+ expanded_def=True,
1614
+ )
1615
+
1616
+ trace_structured(
1617
+ "artifact",
1618
+ metadata_fn=lambda: {
1619
+ "name": "aot_forward_graph_fw_metadata",
1620
+ "encoding": "string",
1621
+ },
1622
+ payload_fn=lambda: dataclass_repr(fw_metadata),
1623
+ )
1624
+ if maybe_subclass_meta is not None:
1625
+ trace_structured(
1626
+ "artifact",
1627
+ metadata_fn=lambda: {
1628
+ "name": "aot_forward_graph_fw_subclass_metadata",
1629
+ "encoding": "string",
1630
+ },
1631
+ payload_fn=lambda: dataclass_repr(maybe_subclass_meta),
1632
+ )
1633
+
1634
+ trace_structured(
1635
+ "aot_forward_graph",
1636
+ payload_fn=lambda: fw_module_str,
1637
+ )
1638
+ trace_structured(
1639
+ "aot_backward_graph",
1640
+ payload_fn=lambda: bw_module_str,
1641
+ )
1642
+
1643
+ # AMP is already traced out in joint graph. we do not wish to reapply it accidentally
1644
+ # in the compiler.
1645
+ with track_graph_compiling(aot_config, "forward"), torch._C._DisableAutocast():
1646
+ # flat_args at this point might still be subclasses-
1647
+ # make sure to pass the unwrapped fake tensors into the compiler!
1648
+ adjusted_flat_args = joint_inputs[0]
1649
+
1650
+ fakified_out_wrapper = FakifiedOutWrapper()
1651
+ fakified_out_wrapper.pre_compile(
1652
+ fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
1653
+ )
1654
+
1655
+ functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper(
1656
+ return_new_outs=False
1657
+ )
1658
+
1659
+ if rng_states:
1660
+ index = fw_metadata.graphsafe_rng_state_index
1661
+ assert index is not None
1662
+ rng_states = [
1663
+ get_cuda_generator_meta_val(index)
1664
+ for _ in range(fw_metadata.num_graphsafe_rng_states)
1665
+ ]
1666
+ adjusted_flat_args.extend(rng_states) # type: ignore[arg-type]
1667
+
1668
+ functionalized_rng_wrapper.pre_compile(
1669
+ fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
1670
+ )
1671
+ if tracing_context := torch._guards.TracingContext.try_get():
1672
+ tracing_context.fw_metadata = inner_meta
1673
+
1674
+ with TracingContext.report_output_strides() as fwd_output_strides:
1675
+ compiled_fw_func = aot_config.fw_compiler(fw_module, adjusted_flat_args)
1676
+
1677
+ if not getattr(compiled_fw_func, "_boxed_call", False):
1678
+ compiled_fw_func = make_boxed_func(compiled_fw_func)
1679
+
1680
+ if fakified_out_wrapper.needs_post_compile:
1681
+ fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides)
1682
+
1683
+ compiled_fw_func = EffectTokensWrapper().post_compile(
1684
+ compiled_fw_func,
1685
+ aot_config,
1686
+ runtime_metadata=fw_metadata,
1687
+ )
1688
+
1689
+ compiled_fw_func = AOTDispatchSubclassWrapper(
1690
+ fw_only=None,
1691
+ trace_joint=False,
1692
+ maybe_subclass_meta=maybe_subclass_meta,
1693
+ num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
1694
+ ).post_compile(
1695
+ compiled_fw_func,
1696
+ aot_config, # not used
1697
+ runtime_metadata=fw_metadata,
1698
+ )
1699
+
1700
+ compiled_fw_func = functionalized_rng_wrapper.post_compile(
1701
+ compiled_fw_func, aot_config, runtime_metadata=fw_metadata
1702
+ )
1703
+ compiled_fw_func = fakified_out_wrapper.post_compile(
1704
+ compiled_fw_func,
1705
+ aot_config,
1706
+ runtime_metadata=fw_metadata,
1707
+ )
1708
+
1709
+ # NB: It's important to compile backwards ahead of time, as this may
1710
+ # add extra guards which we need to apply to the Dynamo cache at
1711
+ # forwards
1712
+ with track_graph_compiling(aot_config, "backward"), torch._C._DisableAutocast():
1713
+ placeholder_list = fx_placeholder_vals(bw_module)
1714
+
1715
+ forward_saved_for_backwards_strides = None
1716
+ if fwd_output_strides is not None:
1717
+ forward_saved_for_backwards_strides = fwd_output_strides[
1718
+ inner_meta.tensors_saved_for_backwards_slice
1719
+ ]
1720
+
1721
+ # saved activations can have different stride to eager if
1722
+ # the compiler does layout optimization. We should restride the
1723
+ # tensor passed in for compiling the backward graph using the
1724
+ # saved tensor's stride.
1725
+ for i in range(len(placeholder_list)):
1726
+ ph_arg = placeholder_list[i]
1727
+ if not isinstance(ph_arg, torch.Tensor):
1728
+ continue
1729
+
1730
+ if forward_saved_for_backwards_strides is None:
1731
+ continue
1732
+
1733
+ real_stride = None
1734
+ # Per all_args calling convention
1735
+ j = i - num_symints_saved_for_bw
1736
+ if 0 <= j < len(forward_saved_for_backwards_strides):
1737
+ real_stride = forward_saved_for_backwards_strides[j]
1738
+ if real_stride is None:
1739
+ continue
1740
+
1741
+ # Comparing ph_arg.stride() with real_stride directly may
1742
+ # cause dynamic dimensions in ph_arg being specialized to static
1743
+ # value. Using the hints to avoid that.
1744
+ if _get_symint_hints(ph_arg.stride()) != real_stride:
1745
+ # Note that here we use the stride of the real tensor to
1746
+ # restride a FakeTensor. This does not cause trouble
1747
+ # for dynamic shape since this code path only get
1748
+ # executed if layout optimization is enabled. And we
1749
+ # disable layout optimization for dynamic shape right
1750
+ # now.
1751
+ #
1752
+ # A solution that decide stride order based on real
1753
+ # tensor's stride and then apply that stride order to
1754
+ # the FakeTensor does not work smoothly since some
1755
+ # tensor's layout is not 'dense'. E.g. mixnet_l has a
1756
+ # tensor with size [8, 64, 112, 112] and strides
1757
+ # (2408448, 1, 21504, 192). The solution mentioned will
1758
+ # decide a stride of (802816, 1, 7168, 64) for this
1759
+ # tensor which is wrong.
1760
+ placeholder_list[i] = ph_arg.as_strided(ph_arg.size(), real_stride)
1761
+
1762
+ compiled_bw_func = None
1763
+ if (
1764
+ num_symints_saved_for_bw > 0
1765
+ or aot_config.force_non_lazy_backward_lowering
1766
+ ):
1767
+ try:
1768
+ # See Note: [Backward graph lazy lowering]
1769
+ with torch._subclasses.fake_tensor.unset_fake_temporarily():
1770
+ # If bw_module contains lifted constants, they will be real tensors stored as
1771
+ # GraphModule. Deepcopying tensors under fake mode is not supported and will
1772
+ # raise when attempting to set storage.
1773
+ bw_module_copy = copy.deepcopy(bw_module)
1774
+ compiled_bw_func = aot_config.bw_compiler(
1775
+ bw_module_copy, placeholder_list
1776
+ )
1777
+ del bw_module_copy
1778
+ except Exception as e:
1779
+ if aot_config.force_non_lazy_backward_lowering:
1780
+ raise
1781
+ exc = e
1782
+ trace_structured(
1783
+ "artifact",
1784
+ metadata_fn=lambda: {
1785
+ "name": "eager_compile_backwards_failure",
1786
+ "encoding": "string",
1787
+ },
1788
+ payload_fn=lambda: "\n".join(
1789
+ traceback.format_exception(
1790
+ type(exc), exc, exc.__traceback__
1791
+ )
1792
+ ),
1793
+ )
1794
+ log.warning(
1795
+ "failed to eagerly compile backwards for dynamic, suppressing in case backwards not needed",
1796
+ exc_info=True,
1797
+ )
1798
+ # Compiled autograd will run the bw_module in the backward pass,
1799
+ # so recompilation need happen anyway if the backward pass is ever
1800
+ # called.
1801
+ #
1802
+ # The reason we do the GraphModule recompilation here is because
1803
+ # the lazy recompilation will cause issue in the backward pass
1804
+ # with compiled autograd.
1805
+ #
1806
+ # Do the _LazyGraphModule.force_recompile here rather than when
1807
+ # bw_module is first generated by the partitioner because the bw_module.recompile
1808
+ # may be called in some code path later and cause the _LazyGraphModule.forward
1809
+ # becomes the lazy version again. One example is when dynamic shape is enabled
1810
+ # upfront, the bw_compiler will be called above which can cause extra
1811
+ # graph module recompilation on bw_module.
1812
+ if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
1813
+ from torch.fx._lazy_graph_module import _LazyGraphModule
1814
+
1815
+ _LazyGraphModule.force_recompile(bw_module)
1816
+
1817
+ saved_context = TracingContext.try_get()
1818
+ saved_compile_context = CompileContext.try_get()
1819
+
1820
+ backward_state_indices = [
1821
+ idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState)
1822
+ ]
1823
+ assert len(backward_state_indices) <= 1
1824
+
1825
+ lazy_backward_info = AutogradLazyBackwardCompileInfo(
1826
+ bw_module,
1827
+ placeholder_list,
1828
+ saved_context,
1829
+ saved_compile_context,
1830
+ )
1831
+
1832
+ make_runtime_safe(fw_metadata, maybe_subclass_meta)
1833
+
1834
+ try_save_cache_entry: Optional[Callable] = None
1835
+
1836
+ if aot_config.cache_info is not None:
1837
+ forward_time_taken_ns = time.time_ns() - aot_config.cache_info.start_time_ns
1838
+
1839
+ # NB: aot_config here is technically not needed as an argument: we could just
1840
+ # close over aot_config.cache_info, since aot_config never changes.
1841
+ # But closing over random variables is confusing IMO, so I'm leaving it.
1842
+ def try_save_cache_entry( # noqa: F811
1843
+ compiled_bw_func: Callable,
1844
+ bw_module: torch.fx.GraphModule,
1845
+ _fw_metadata: ViewAndMutationMeta,
1846
+ aot_config: AOTConfig,
1847
+ ):
1848
+ cache_info = aot_config.cache_info
1849
+
1850
+ def should_save_cache():
1851
+ if should_bundle_autograd_cache():
1852
+ return True
1853
+ else:
1854
+ return hasattr(compiled_fw_func, "_fx_graph_cache_key") and hasattr(
1855
+ compiled_bw_func, "_fx_graph_cache_key"
1856
+ )
1857
+
1858
+ if cache_info is not None and should_save_cache():
1859
+ assert forward_time_taken_ns is not None
1860
+ # TODO: technically, AOTAutograd does a *little* bit of post processing work
1861
+ # in the backward that isn't measured here. But it's small enough that it's not worth
1862
+ # the complexity of threading a bunch of times through the code, so we
1863
+ # use the compiled_bw_func's inductor compile time instead.
1864
+ # It's possible this changes in the future, in which case we should
1865
+ # update backward_time_taken_ns to be more inclusive
1866
+ backward_time_taken_ns = getattr(compiled_bw_func, "_time_taken_ns", 0)
1867
+
1868
+ aot_forward_graph_str: Optional[str] = fw_module_str
1869
+ aot_backward_graph_str: Optional[str] = bw_module_str
1870
+ aot_joint_graph_str: Optional[str] = joint_graph_str
1871
+ guards_expr = AOTAutogradCache.generate_guards_expression(cache_info)
1872
+
1873
+ entry = AOTAutogradCache.make_entry(
1874
+ compiled_fw_func, # type: ignore[arg-type]
1875
+ compiled_bw_func, # type: ignore[arg-type]
1876
+ aot_joint_graph_str,
1877
+ aot_forward_graph_str,
1878
+ aot_backward_graph_str,
1879
+ _fw_metadata,
1880
+ wrappers,
1881
+ maybe_subclass_meta,
1882
+ num_fw_outs_saved_for_bw,
1883
+ _indices_of_inps_to_detach,
1884
+ forward_time_taken_ns,
1885
+ backward_time_taken_ns,
1886
+ sanitized_aot_config=sanitize_aot_config(aot_config),
1887
+ guards_expr=guards_expr,
1888
+ backward_state_indices=backward_state_indices,
1889
+ num_symints_saved_for_bw=num_symints_saved_for_bw,
1890
+ serialized_bw_module=serialize_graph_module(bw_module),
1891
+ )
1892
+ remote = should_use_remote_autograd_cache()
1893
+ AOTAutogradCache.save(cache_info.cache_key, entry, remote)
1894
+
1895
+ if compiled_bw_func is not None:
1896
+ # If we already compiled the backward, we save its cache entry now
1897
+ try_save_cache_entry(compiled_bw_func, bw_module, fw_metadata, aot_config)
1898
+ try_save_cache_entry = None
1899
+
1900
+ compiled_fn = AOTDispatchAutograd.post_compile(
1901
+ compiled_fw_func,
1902
+ compiled_bw_func,
1903
+ maybe_subclass_meta,
1904
+ num_symints_saved_for_bw,
1905
+ backward_state_indices,
1906
+ disable_amp,
1907
+ _indices_of_inps_to_detach,
1908
+ lazy_backward_info,
1909
+ aot_config,
1910
+ fw_metadata=fw_metadata,
1911
+ try_save_cache_entry=try_save_cache_entry,
1912
+ )
1913
+
1914
+ if config.debug_assert:
1915
+ flat_requires_grad: list[Optional[bool]] = [
1916
+ a.requires_grad if isinstance(a, Tensor) else None for a in flat_args
1917
+ ]
1918
+ compiled_fn = DebugAssertWrapper(
1919
+ flat_requires_grad=flat_requires_grad
1920
+ ).post_compile(compiled_fn, aot_config, runtime_metadata=fw_metadata)
1921
+
1922
+ compiled_fn = post_compile(
1923
+ wrappers,
1924
+ compiled_fn,
1925
+ aot_config,
1926
+ runtime_metadata=fw_metadata,
1927
+ )
1928
+ return compiled_fn
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .descriptors import AOTInput, InputMutationAOTOutput, TangentAOTInput
28
+ from .schemas import (
29
+ BackwardSignature,
30
+ GraphSignature,
31
+ InputAliasInfo,
32
+ MemoryFormatMeta,
33
+ OutputAliasInfo,
34
+ OutputType,
35
+ ViewAndMutationMeta,
36
+ )
37
+ from .utils import strict_zip
38
+
39
+
40
+ zip = strict_zip
41
+
42
+
43
+ def remove_dupe_metadata(
44
+ m: ViewAndMutationMeta,
45
+ keep_arg_mask: list[bool],
46
+ add_dupe_map: list[int],
47
+ ) -> ViewAndMutationMeta:
48
+ assert len(m.input_info) == len(keep_arg_mask)
49
+ # Easy invariant: the first argument should never be a dupe (it will be kept)
50
+ assert len(keep_arg_mask) > 0 and keep_arg_mask[0]
51
+
52
+ # Filter dupe'd mutated inputs out of traced_tangents
53
+ num_data_mutations = len([x for x in m.input_info if x.mutates_data])
54
+ other_traced_tangents = m.traced_tangents[num_data_mutations:]
55
+ inp_traced_tangents = m.traced_tangents[:num_data_mutations]
56
+ other_traced_tangents_descs = m.traced_tangents_descs[num_data_mutations:]
57
+ inp_traced_tangents_descs = m.traced_tangents_descs[:num_data_mutations]
58
+ filtered_inp_traced_tangents = [
59
+ # See Note [Tangents memory format]
60
+ x
61
+ for i, x in enumerate(inp_traced_tangents)
62
+ if keep_arg_mask[m.mutated_inp_runtime_indices[i]]
63
+ ]
64
+ filtered_inp_traced_tangents_descs = [
65
+ x_desc
66
+ for i, x_desc in enumerate(inp_traced_tangents_descs)
67
+ if keep_arg_mask[m.mutated_inp_runtime_indices[i]]
68
+ ]
69
+ traced_tangents = filtered_inp_traced_tangents + other_traced_tangents
70
+ traced_tangents_descs = (
71
+ filtered_inp_traced_tangents_descs + other_traced_tangents_descs
72
+ )
73
+
74
+ assert m.subclass_tangent_meta is not None
75
+ subclass_tangent_meta = [
76
+ PlainTensorMeta(
77
+ 0, memory_format=MemoryFormatMeta(memory_format=torch.contiguous_format)
78
+ )
79
+ ] * len(filtered_inp_traced_tangents) + m.subclass_tangent_meta[num_data_mutations:]
80
+
81
+ return ViewAndMutationMeta(
82
+ input_info=[x for i, x in enumerate(m.input_info) if keep_arg_mask[i]],
83
+ # For outputs that are views of inputs, we store the index of the input that the output
84
+ # was generated from. Need to update that index to account for removed dupes.
85
+ output_info=[
86
+ OutputAliasInfo(
87
+ output_type=o.output_type,
88
+ raw_type=o.raw_type,
89
+ dynamic_dims=o.dynamic_dims,
90
+ base_idx=None if o.base_idx is None else add_dupe_map[o.base_idx],
91
+ requires_grad=o.requires_grad,
92
+ view_meta_sequence=o.view_meta_sequence,
93
+ )
94
+ for o in m.output_info
95
+ ],
96
+ num_intermediate_bases=m.num_intermediate_bases,
97
+ keep_input_mutations=m.keep_input_mutations,
98
+ traced_tangents=traced_tangents,
99
+ traced_tangents_descs=traced_tangents_descs,
100
+ # We are guaranteed not to get here, since dupes are not supported today with subclass inputs.
101
+ subclass_inp_meta=[],
102
+ subclass_fw_graph_out_meta=[],
103
+ subclass_tangent_meta=subclass_tangent_meta,
104
+ is_train=m.is_train,
105
+ )
106
+
107
+
108
+ # Given our ViewAndMutation metadata, this fn constructs a new set of metadata,
109
+ # after adding synthetic base arguments to the function.
110
+ # Most of the work in this fn is slogging through all of the metadata corresponding to inputs,
111
+ # and updating it with our synthetic base calling convention.
112
+ #
113
+ # When config.debug_assert is set, we automatically regenerate the metadata
114
+ # and compare it to this output for sanity.
115
+ #
116
+ # In addition to the updated metadata, also return the list of input indices
117
+ # that will need to be updated in the synthetic base epilogue
118
+ def create_synthetic_base_metadata(
119
+ m: ViewAndMutationMeta,
120
+ # Maps each outer argument idx to its inner idx (or, if this outer arg is generated from a
121
+ # synthetic base, you get a tuple of (i, TensorMeta), telling you the base tensor idx, and view metadata)
122
+ synthetic_base_info: list[Union[int, tuple[int, torch.Tensor]]],
123
+ outer_args: list[Any],
124
+ inner_args: list[Any],
125
+ inner_args_desc: list[AOTInput],
126
+ ) -> tuple[ViewAndMutationMeta, list[int]]:
127
+ # maps inner arg indices to outer arg indices
128
+ synthetic_base_to_indices: dict[int, list[int]] = {}
129
+ for inner_idx in range(len(inner_args)):
130
+ outer_aliased_indices_of_current_base_arg = [
131
+ outer_idx
132
+ for outer_idx, inner_idx_or_tuple in enumerate(synthetic_base_info)
133
+ if (isinstance(inner_idx_or_tuple, int) and inner_idx_or_tuple == inner_idx)
134
+ or (
135
+ isinstance(inner_idx_or_tuple, tuple)
136
+ and inner_idx_or_tuple[0] == inner_idx
137
+ )
138
+ ]
139
+ synthetic_base_to_indices[inner_idx] = outer_aliased_indices_of_current_base_arg
140
+
141
+ # given the requires_grad info on mutated inputs,
142
+ # generate the requires_grad info on those same mutated inputs, but after constructing synthetic bases.
143
+ input_infos = []
144
+ for outer_indices in synthetic_base_to_indices.values():
145
+ # leaf-ness should be all-or-nothing for aliased tensor.
146
+ # (aka if "a" and "b" are views, then a.is_leaf == b.is_leaf)
147
+ any_leaf = any(m.input_info[x].is_leaf for x in outer_indices)
148
+ all_leaf = all(m.input_info[x].is_leaf for x in outer_indices)
149
+ assert any_leaf == all_leaf
150
+
151
+ mutates_data = (
152
+ True
153
+ if len(outer_indices) > 1
154
+ else m.input_info[outer_indices[0]].mutates_data
155
+ )
156
+ mutates_metadata = (
157
+ False
158
+ if len(outer_indices) > 1
159
+ else m.input_info[outer_indices[0]].mutates_metadata
160
+ )
161
+ requires_grad = any(m.input_info[x].requires_grad for x in outer_indices)
162
+ mutations_under_no_grad_or_inference_mode = all(
163
+ m.input_info[x].mutations_under_no_grad_or_inference_mode
164
+ for x in outer_indices
165
+ )
166
+
167
+ mutation_inductor_storage_resize = all(
168
+ m.input_info[x].mutation_inductor_storage_resize for x in outer_indices
169
+ )
170
+
171
+ inpt_info = InputAliasInfo(
172
+ # If len(outer_indices) > 1, then this input is a synthetic base.
173
+ # The invariant is that to the rest of aot autograd, synthetic bases only show up if
174
+ # one of their aliases gets a data mutation. And if any of their aliases get metadata
175
+ # mutations, they will be hidden from the rest of aot autograd.
176
+ mutates_data=mutates_data,
177
+ mutates_metadata=mutates_metadata,
178
+ mutations_hidden_from_autograd=all(
179
+ m.input_info[x].mutations_hidden_from_autograd for x in outer_indices
180
+ ),
181
+ mutates_storage_metadata=(
182
+ False
183
+ if len(outer_indices) > 1
184
+ else m.input_info[outer_indices[0]].mutates_storage_metadata
185
+ ),
186
+ mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode,
187
+ mutation_inductor_storage_resize=mutation_inductor_storage_resize,
188
+ is_leaf=any_leaf,
189
+ requires_grad=requires_grad,
190
+ keep_input_mutations=m.keep_input_mutations,
191
+ )
192
+ input_infos.append(inpt_info)
193
+
194
+ # Find any inputs that fulfill the following criteria:
195
+ # (1) They are part of a synthetic base (because they alias another input,
196
+ # and at least one input experiences a data mutation)
197
+ # (2) They experience a metadata mutation
198
+ outer_aliased_arg_idx_with_metadata_mutations = [
199
+ outer_idx
200
+ for outer_idx, inpt_info in enumerate(m.input_info)
201
+ if inpt_info.mutates_metadata
202
+ and not isinstance(synthetic_base_info[outer_idx], int)
203
+ ]
204
+
205
+ # grab the original requires grad info on the outputs, except the ones from the mutated inputs
206
+ input_metadata_output_info = [
207
+ OutputAliasInfo(
208
+ output_type=OutputType.alias_of_input,
209
+ raw_type=FunctionalTensor,
210
+ dynamic_dims={
211
+ i
212
+ for i, s in enumerate(outer_args[outer_idx].shape)
213
+ if not is_concrete_int(s)
214
+ },
215
+ base_idx=synthetic_base_info[outer_idx][0], # type: ignore[index]
216
+ requires_grad=outer_args[outer_idx].requires_grad,
217
+ )
218
+ for outer_idx in outer_aliased_arg_idx_with_metadata_mutations
219
+ ]
220
+ existing_output_infos = []
221
+ for o in m.output_info:
222
+ new_base_idx = (
223
+ None
224
+ if o.base_idx is None
225
+ else (
226
+ synthetic_base_info[o.base_idx]
227
+ if isinstance(synthetic_base_info[o.base_idx], int)
228
+ else synthetic_base_info[o.base_idx][0] # type: ignore[index]
229
+ )
230
+ )
231
+ # If base_idx is changed for OutputType.is_input, we need to update the output type to reflect the change
232
+ new_output_type = (
233
+ OutputType.alias_of_input
234
+ if o.output_type == OutputType.is_input and o.base_idx != new_base_idx
235
+ else o.output_type
236
+ )
237
+ existing_output_infos.append(
238
+ OutputAliasInfo(
239
+ output_type=new_output_type,
240
+ raw_type=o.raw_type,
241
+ dynamic_dims=o.dynamic_dims,
242
+ # Map the input idx pre-synthetic-bases to the new idx post-synthetic-bases
243
+ base_idx=new_base_idx, # type: ignore[arg-type]
244
+ requires_grad=o.requires_grad,
245
+ view_meta_sequence=o.view_meta_sequence,
246
+ )
247
+ )
248
+
249
+ inner_mutated_tangents_and_memory_formats = [
250
+ # See Note [Tangents memory format]
251
+ (
252
+ coerce_tangent_and_suggest_memory_format(x),
253
+ TangentAOTInput(InputMutationAOTOutput(x_desc)),
254
+ )
255
+ for inner_idx, (x, x_desc) in enumerate(zip(inner_args, inner_args_desc))
256
+ if input_infos[inner_idx].mutates_data and input_infos[inner_idx].requires_grad
257
+ ]
258
+ inner_mutated_tangents = [
259
+ x[0][0] for x in inner_mutated_tangents_and_memory_formats
260
+ ]
261
+ inner_mutated_tangents_descs = [
262
+ x[1] for x in inner_mutated_tangents_and_memory_formats
263
+ ]
264
+ inner_mutated_tangents_memory_formats = [
265
+ x[0][1] for x in inner_mutated_tangents_and_memory_formats
266
+ ]
267
+
268
+ output_info = existing_output_infos + input_metadata_output_info
269
+ # Regenerate traced tangents to include mutated inputs including synthetic bases
270
+ traced_tangents = (
271
+ inner_mutated_tangents + m.traced_tangents[len(inner_mutated_tangents) :]
272
+ )
273
+ traced_tangents_descs = (
274
+ inner_mutated_tangents_descs
275
+ + m.traced_tangents_descs[len(inner_mutated_tangents) :]
276
+ )
277
+ assert m.subclass_tangent_meta is not None
278
+ subclass_tangent_meta = [
279
+ PlainTensorMeta(0, memory_format=x)
280
+ for x in inner_mutated_tangents_memory_formats
281
+ ] + m.subclass_tangent_meta[len(inner_mutated_tangents) :]
282
+
283
+ return (
284
+ ViewAndMutationMeta(
285
+ input_info=input_infos,
286
+ output_info=output_info,
287
+ num_intermediate_bases=m.num_intermediate_bases,
288
+ keep_input_mutations=m.keep_input_mutations,
289
+ traced_tangents=traced_tangents,
290
+ traced_tangents_descs=traced_tangents_descs,
291
+ # We are guaranteed not to get here, since synthetic_base codepaths are not supported today with subclass inputs.
292
+ subclass_inp_meta=[],
293
+ subclass_fw_graph_out_meta=[],
294
+ subclass_tangent_meta=subclass_tangent_meta,
295
+ is_train=m.is_train,
296
+ ),
297
+ outer_aliased_arg_idx_with_metadata_mutations,
298
+ )
299
+
300
+
301
+ def compute_overlapping_inputs(aot_config, fwd_inputs, aliased_input_indices):
302
+ num_aliases = len(aliased_input_indices)
303
+
304
+ shape_env = None
305
+ maybe_suppress_guards = contextlib.nullcontext
306
+ tracing_context = torch._guards.TracingContext.try_get()
307
+
308
+ if tracing_context is not None:
309
+ assert tracing_context.fake_mode is not None
310
+ shape_env = tracing_context.fake_mode.shape_env
311
+
312
+ # Check whether we can actually get the dynamo sources from within AOTAutograd.
313
+ if aot_config.aot_autograd_arg_pos_to_source and shape_env is not None:
314
+ maybe_suppress_guards = shape_env.suppress_guards # type: ignore[assignment]
315
+
316
+ # Check whether there are any symbolic values being used.
317
+ # We do this for 2 reasons:
318
+ # 1. StorageOverlap guard is only issued whenever dynamic shapes is turned on
319
+ # 2. Triggers the fast-path for computing storage overlapping
320
+ symbolic = any(
321
+ isinstance(x, torch.SymInt)
322
+ for i in aliased_input_indices
323
+ for x in [
324
+ *fwd_inputs[i].shape,
325
+ *fwd_inputs[i].stride(),
326
+ fwd_inputs[i].storage_offset(),
327
+ ]
328
+ )
329
+
330
+ if torch._inductor.config.is_fbcode():
331
+ if symbolic and num_aliases > 400:
332
+ from torch._subclasses.fake_tensor import (
333
+ UnsupportedMutationAliasingException,
334
+ )
335
+ from torch._utils_internal import justknobs_check
336
+
337
+ msg = f"Encountered {num_aliases} dynamic, aliased/mutated inputs, consider setting dynamic=False"
338
+
339
+ if justknobs_check(
340
+ "pytorch/compiler:aliased_inputs_with_mutation_and_dyn_shapes_killswitch",
341
+ False,
342
+ ):
343
+ raise UnsupportedMutationAliasingException(msg)
344
+
345
+ with maybe_suppress_guards():
346
+ aliased_fwd_inputs = [fwd_inputs[i] for i in aliased_input_indices]
347
+ actual_aliased_indices = {
348
+ aliased_input_indices[i]
349
+ for i in compute_overlapping_tensors(aliased_fwd_inputs, symbolic=symbolic)
350
+ }
351
+
352
+ # Add the StorageOverlap AOTAutograd guard only if we are actually keeping track of
353
+ # dynamo sources inside AOTAutograd.
354
+ if (
355
+ tracing_context is not None
356
+ # Make sure dynamic shapes is currently being used.
357
+ and symbolic
358
+ # We check that we have more than 1 aliased tensor, which should be true at
359
+ # this point, anyway.
360
+ and num_aliases > 1
361
+ and aot_config.aot_autograd_arg_pos_to_source
362
+ ):
363
+ no_overlap_indices = list(set(aliased_input_indices) - actual_aliased_indices)
364
+
365
+ overlapping_sources = [
366
+ aot_config.aot_autograd_arg_pos_to_source[i] for i in actual_aliased_indices
367
+ ]
368
+ non_overlapping_sources = [
369
+ aot_config.aot_autograd_arg_pos_to_source[i] for i in no_overlap_indices
370
+ ]
371
+
372
+ tracing_context.guards_context.aotautograd_guards.append(
373
+ StorageOverlap(overlapping_sources, non_overlapping_sources)
374
+ )
375
+
376
+ return actual_aliased_indices
377
+
378
+
379
+ def _graph_input_names(gm):
380
+ return [node.name for node in gm.graph.find_nodes(op="placeholder")]
381
+
382
+
383
+ def _graph_output_names(gm):
384
+ output_node = next(iter(reversed(gm.graph.nodes)))
385
+ assert output_node.op == "output" and len(output_node.args) == 1
386
+ return_args = output_node.args[0]
387
+ return [getattr(return_arg, "name", None) for return_arg in return_args]
388
+
389
+
390
+ def create_graph_signature(
391
+ fx_g: torch.fx.GraphModule,
392
+ fw_metadata: ViewAndMutationMeta,
393
+ in_spec: pytree.TreeSpec,
394
+ out_spec: pytree.TreeSpec,
395
+ *,
396
+ user_args_flat: list[Tensor],
397
+ params_and_buffers_flat: list[Tensor],
398
+ param_names: list[str],
399
+ buffer_names: list[str],
400
+ trace_joint: bool,
401
+ num_user_fw_outs: Optional[int],
402
+ loss_index: Optional[int],
403
+ ) -> GraphSignature:
404
+ # Retrieve graph input names
405
+ graph_input_names = _graph_input_names(fx_g)
406
+ # Retrieve graph output names
407
+ graph_output_names = _graph_output_names(fx_g)
408
+
409
+ num_params_buffers = len(param_names) + len(buffer_names)
410
+ num_tokens = len(fw_metadata.tokens)
411
+ # We have enough restrictions on the graph (no de-duping, synthetic bases, etc),
412
+ # Such that # graph inps = # user inps + # params + # buffers
413
+ num_user_args = len(graph_input_names) - num_params_buffers - num_tokens
414
+
415
+ if trace_joint:
416
+ assert num_user_fw_outs is not None
417
+ num_fw_outs = num_user_fw_outs + fw_metadata.num_mutated_inp_runtime_indices
418
+ backward_output_names = graph_output_names[num_fw_outs:]
419
+
420
+ grad_index = itertools.count(0)
421
+ gradients_to_parameters = {
422
+ backward_output_names[next(grad_index)]: param_names[i]
423
+ for i, param in enumerate(params_and_buffers_flat)
424
+ if param.requires_grad
425
+ }
426
+
427
+ gradients_to_user_inputs = {
428
+ backward_output_names[next(grad_index)]: graph_input_names[
429
+ i + len(params_and_buffers_flat)
430
+ ]
431
+ for i, user_input in enumerate(user_args_flat)
432
+ if user_input.requires_grad
433
+ }
434
+
435
+ assert len(gradients_to_parameters) + len(gradients_to_user_inputs) == len(
436
+ backward_output_names
437
+ )
438
+
439
+ # Check that we have fully accounted for all graph outputs
440
+ backward_signature = BackwardSignature(
441
+ gradients_to_parameters,
442
+ gradients_to_user_inputs,
443
+ graph_output_names[loss_index],
444
+ )
445
+ else:
446
+ backward_signature = None
447
+ num_user_fw_outs = (
448
+ len(graph_output_names)
449
+ - fw_metadata.num_mutated_inp_runtime_indices
450
+ - num_tokens
451
+ )
452
+
453
+ return GraphSignature.from_tracing_metadata(
454
+ in_spec=in_spec,
455
+ out_spec=out_spec,
456
+ graph_input_names=graph_input_names,
457
+ graph_output_names=graph_output_names,
458
+ view_mutation_metadata=fw_metadata,
459
+ named_parameters=param_names,
460
+ named_buffers=buffer_names,
461
+ num_user_inputs=num_user_args,
462
+ num_user_outputs=num_user_fw_outs,
463
+ trace_joint=trace_joint,
464
+ loss_index=loss_index,
465
+ backward_signature=backward_signature,
466
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/schemas.py ADDED
@@ -0,0 +1,1299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from __future__ import annotations
8
+
9
+ import collections
10
+ import functools
11
+ import itertools
12
+ from dataclasses import dataclass, field
13
+ from enum import Enum
14
+ from typing import (
15
+ Any,
16
+ Callable,
17
+ NewType,
18
+ Optional,
19
+ Protocol,
20
+ TYPE_CHECKING,
21
+ TypeVar,
22
+ Union,
23
+ )
24
+
25
+ import torch
26
+ import torch.utils._pytree as pytree
27
+ from torch import SymInt, Tensor
28
+ from torch._subclasses import FakeTensor
29
+ from torch._subclasses.fake_tensor import is_fake
30
+ from torch.fx.experimental._backward_state import BackwardState
31
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
32
+
33
+ from .. import config
34
+ from .functional_utils import _check_if_mutation_can_be_in_graph, ViewMetaSequence
35
+ from .utils import strict_zip
36
+
37
+
38
+ if TYPE_CHECKING:
39
+ import contextlib
40
+ from collections.abc import Iterable, Sequence
41
+
42
+ from torch._guards import Source
43
+ from torch._inductor.output_code import OutputCode
44
+ from torch._inductor.utils import InputType
45
+ from torch._ops import OpOverload
46
+
47
+ from .descriptors import AOTInput, AOTOutput
48
+ from .graph_capture_wrappers import JointFnHandle
49
+
50
+
51
+ zip = strict_zip
52
+
53
+
54
+ OutputType = Enum(
55
+ "OutputType",
56
+ (
57
+ # output is not an alias
58
+ "non_alias",
59
+ # output aliases an input
60
+ "alias_of_input",
61
+ # output **is** an input tensor
62
+ "is_input",
63
+ # output has a ._base tensor, which is a graph intermediate.
64
+ # We need to return its ._base as a graph output,
65
+ # so its requires_grad info is populated correctly.
66
+ # Instructs the runtime code to regenerate the current output
67
+ # from a base tensor, graph_intermediates[base_idx]
68
+ "alias_of_intermediate_save_as_output",
69
+ # Same as above; but we don't need to explicitly add its ._base
70
+ # as a graph output, because it already **is** a graph output.
71
+ "alias_of_intermediate",
72
+ # Same as above; but the output's ._base is **already** a user output.
73
+ # Instructs the runtime code to regenerate the current output from
74
+ # a base tensor, user_outputs[base_idx]
75
+ "alias_of_intermediate_base_is_user_output",
76
+ # See Note [Intermediate Bases Optimization]
77
+ "unsafe_view_alias",
78
+ # output is an alias, but has a custom autograd.Function backward.
79
+ # In this case, we don't want to do view-replay, since we won't be able to replay the custom function.
80
+ # Instead, we'll treat this output "normally", and trace its backward into the graph.
81
+ "custom_function_view",
82
+ ),
83
+ )
84
+
85
+
86
+ # This class stores info about every user output.
87
+ @dataclass(frozen=True)
88
+ class OutputAliasInfo:
89
+ # Tells us if this output is:
90
+ # (1) a regular (non-aliased) output
91
+ # (2) an alias of a forward input
92
+ # (3) **is** a forward input (special case of "alias_of_input")
93
+ # (4) an alias of an intermediate (aka an alias of an output of the inner traced forward)
94
+ # (5) an alias of an intermediate, that explicitly requires returning the intermediate
95
+ # as a graph output
96
+ # (6) an alias of an intermediate, where that intermediate is also a user output
97
+ output_type: OutputType
98
+ # The raw type of the output (torch.Tensor, SymInt, etc)
99
+ raw_type: type
100
+ # If (1) above, then
101
+ # - base_idx is None
102
+ # If (2) or (3) above, then
103
+ # - Tells us that the base of this alias is user_fwd_input[base_idx]
104
+ # (This is an index into the inputs *before* we make synthetic bases)
105
+ # If (4) or (5) above, then
106
+ # - Tells us that the base of this alias is output_graph_intermediates[base_idx]
107
+ # here, this refers to the index of the *direct* traced
108
+ # If (6) above, then:
109
+ # - Tells us that the base of this alias is output_user_fwds[base_idx]
110
+ # here, this refers to the index of the *direct* traced
111
+ base_idx: Optional[int]
112
+ # If it is a Tensor, what the dynamic dims are (otherwise is None)
113
+ dynamic_dims: Optional[set[int]]
114
+ # requires_grad
115
+ requires_grad: bool
116
+ # Sequence of ViewMeta objects.
117
+ #
118
+ # Provides us the means to re-run view functions on other tensors.
119
+ #
120
+ # We need to wrap the actual list of ViewMeta with this class so that
121
+ # we compare the ViewMeta elements appropriately, i.e. their type and
122
+ # the elements returned by the `as_tuple()` call.
123
+ view_meta_sequence: Optional[ViewMetaSequence] = None
124
+
125
+
126
+ class MutationType(Enum):
127
+ NOT_MUTATED = 1
128
+ MUTATED_IN_GRAPH = 2
129
+ MUTATED_OUT_GRAPH = 3
130
+
131
+
132
+ # This class tells us info about user inputs.
133
+ @dataclass(frozen=True)
134
+ class InputAliasInfo:
135
+ is_leaf: bool
136
+ mutates_data: bool
137
+ mutates_metadata: bool
138
+ mutations_hidden_from_autograd: bool
139
+ mutations_under_no_grad_or_inference_mode: bool
140
+ mutation_inductor_storage_resize: bool
141
+ mutates_storage_metadata: bool
142
+ requires_grad: bool
143
+ keep_input_mutations: bool
144
+
145
+ def __post_init__(self):
146
+ if self.mutates_storage_metadata:
147
+ # For convenience, we guarantee that this is always true.
148
+ # In practice, If we call .set_(), then at runtime there is no need
149
+ # to additionally fix up the tensor metadata, since our runtime
150
+ # call to inp.set_(updated_inp) will already have the right metadata
151
+ assert self.mutates_metadata
152
+
153
+ @functools.cached_property
154
+ def mutation_type(self) -> MutationType:
155
+ if (
156
+ (not self.mutates_data)
157
+ and (not self.mutates_metadata)
158
+ and not (self.mutation_inductor_storage_resize)
159
+ ):
160
+ return MutationType.NOT_MUTATED
161
+
162
+ if _check_if_mutation_can_be_in_graph(
163
+ self.keep_input_mutations,
164
+ self.mutates_data,
165
+ self.mutates_metadata,
166
+ self.mutations_hidden_from_autograd,
167
+ self.mutations_under_no_grad_or_inference_mode,
168
+ self.mutates_storage_metadata,
169
+ self.mutation_inductor_storage_resize,
170
+ self.requires_grad,
171
+ ):
172
+ return MutationType.MUTATED_IN_GRAPH
173
+
174
+ return MutationType.MUTATED_OUT_GRAPH
175
+
176
+
177
+ @dataclass
178
+ class MemoryFormatMeta:
179
+ # For static shapes we assume tangents have the same strideness as outputs
180
+ size: Optional[Sequence[int]] = None
181
+ stride: Optional[Sequence[int]] = None
182
+
183
+ # For dynamic shapes we assume the same memory format: contiguous, channels_last etc.
184
+ memory_format: Optional[torch.memory_format] = None
185
+
186
+ @staticmethod
187
+ def from_tensor(t: torch.Tensor) -> Optional[MemoryFormatMeta]:
188
+ # We only memorize expected memory format for
189
+ # 1. Traceable wrapper subclasses
190
+ # We can not create restrided subclass tensor, as torch.empty_strided works only with dense tensors.
191
+ # 2. Dynamic shape tensors
192
+ # Support for symbolic shapes is not implemented yet.
193
+ use_memory_format: bool = (
194
+ not torch._functorch.config.guess_tangent_strides_as_outputs
195
+ or is_traceable_wrapper_subclass(t)
196
+ )
197
+ if not use_memory_format:
198
+ is_static_shape = True
199
+ for s in itertools.chain(t.shape, t.stride()):
200
+ if not isinstance(s, int):
201
+ is_static_shape = False
202
+ break
203
+
204
+ use_memory_format = not is_static_shape
205
+
206
+ if use_memory_format:
207
+ return MemoryFormatMeta(
208
+ memory_format=torch._prims_common.suggest_memory_format(t),
209
+ )
210
+
211
+ return MemoryFormatMeta(
212
+ size=t.size(),
213
+ stride=t.stride(),
214
+ )
215
+
216
+
217
+ @dataclass
218
+ class PlainTensorMeta:
219
+ unwrapped_idx: int
220
+ memory_format: Optional[MemoryFormatMeta] = None
221
+
222
+
223
+ @dataclass
224
+ class SubclassCreationMeta:
225
+ """
226
+ Used for AOTDispatch.
227
+ This dataclass gives us the information we need to reconstruct a tensor subclass
228
+ from our flat inputs.
229
+ Why is this important? The graph that we'd like to trace out contains flat tensor inputs,
230
+ But the user's original model may have subclass inputs and outputs.
231
+ So we need to wrap/unwrap subclasses as necessary to translate between the user's
232
+ view (subclass inps/outs), and the backend compiler's view (graph with no subclass args).
233
+
234
+ Complications arise mostly from the fact that a subclass can hold more than one inner tensor;
235
+ So for a given subclass input/output, we need to carefully track which indices map
236
+ to the subclass tensor in the corresponding "dense-tensor-only" graph.
237
+ """
238
+
239
+ # In the inner graph that only takes in dense tensor inputs,
240
+ # this maps to the first index of "tensors that should go in this subclass wrapper"
241
+ flat_tensor_start_idx: int
242
+ # arg_count is inclusive of the arg_counts of any
243
+ # inner tensor subclasses: If I have a TwoTensor and
244
+ # both of its inner elements are TwoTensors, then the
245
+ # arg_count of the outer-most subclass will be 4
246
+ arg_count: int
247
+ # Mark where or not symints were included. This flag is only used in one assertion
248
+ # in "wrap_tensor_subclasses"
249
+ included_subclass_symints: bool
250
+ # meta and attrs are produced by the subclass's __tensor_flatten__.
251
+ # We need to keep them around along with outer_size / outer_stride to plumb them
252
+ # into __tensor_unflatten__
253
+ attrs: dict[str, Union[SubclassCreationMeta, PlainTensorMeta]]
254
+ outer_size: Iterable[Union[None, int, torch.SymInt]]
255
+ outer_stride: Iterable[Union[None, int, torch.SymInt]]
256
+ meta: Any
257
+ # Stores the original subclass itself.
258
+ # This is needed because we need the autograd metadata on the original subclass
259
+ # (this is guaranteed to be a wrapper subclass that holds a fake tensor,
260
+ # so holding onto this at runtime shouldn't leak memory)
261
+ # This field is nulled out after calling make_runtime_safe()
262
+ original_subclass: Optional[torch.Tensor]
263
+
264
+ # Used at runtime to determine the subclass type, so we don't need to save the original subclass
265
+ original_subclass_type: Optional[type] = None
266
+ memory_format: Optional[MemoryFormatMeta] = None
267
+
268
+ def compute_outer_size_and_stride(
269
+ self,
270
+ all_args,
271
+ *,
272
+ curr_start_idx: int,
273
+ ):
274
+ from .subclass_utils import compute_symint_placeholders
275
+
276
+ def compute(outer, start_idx):
277
+ placeholders = compute_symint_placeholders(outer)
278
+ has_symbolic = any(placeholders)
279
+
280
+ if has_symbolic:
281
+ start = curr_start_idx
282
+ end = start_idx + sum(placeholders)
283
+ it_args = iter(all_args[start:end])
284
+ it_placeholders = iter(placeholders)
285
+ return pytree.tree_map_only(
286
+ lambda _: next(it_placeholders), lambda _: next(it_args), outer
287
+ ), start + len(placeholders)
288
+ else:
289
+ return outer, start_idx
290
+
291
+ outer_size, next_idx = compute(self.outer_size, curr_start_idx)
292
+ outer_stride, _ = compute(self.outer_stride, next_idx)
293
+ return outer_size, outer_stride
294
+
295
+ def creation_fn(
296
+ self,
297
+ all_args,
298
+ *,
299
+ is_runtime: bool,
300
+ ):
301
+ inner_tensors = {}
302
+
303
+ curr_start_idx = self.flat_tensor_start_idx
304
+ for attr, creation_meta in self.attrs.items():
305
+ if isinstance(creation_meta, PlainTensorMeta):
306
+ subclass = all_args[curr_start_idx]
307
+ curr_start_idx += 1
308
+ else:
309
+ subclass = creation_meta.creation_fn(
310
+ all_args,
311
+ is_runtime=is_runtime,
312
+ )
313
+ curr_start_idx += creation_meta.arg_count
314
+ inner_tensors[attr] = subclass
315
+
316
+ if is_runtime:
317
+ assert self.original_subclass_type is not None
318
+ original_subclass_type = self.original_subclass_type
319
+ else:
320
+ original_subclass_type = type(self.original_subclass)
321
+
322
+ if is_runtime:
323
+ outer_size, outer_stride = self.compute_outer_size_and_stride(
324
+ all_args,
325
+ curr_start_idx=curr_start_idx,
326
+ )
327
+ else:
328
+ outer_size, outer_stride = self.outer_size, self.outer_stride
329
+
330
+ rebuilt = original_subclass_type.__tensor_unflatten__( # type: ignore[attr-defined]
331
+ inner_tensors, self.meta, outer_size, outer_stride
332
+ )
333
+
334
+ if not is_runtime:
335
+ # After wrapping up the inner dense tensors into a subclass, we need to make sure that our new wrapper
336
+ # has correct autograd metadata, since we'll be tracing through the autograd engine with the subclass.
337
+ # We don't trace through the autograd engine at runtime though, so no need
338
+ # to compute this extra metadata then!
339
+ torch._mirror_autograd_meta_to(self.original_subclass, rebuilt) # type: ignore[attr-defined]
340
+
341
+ return rebuilt
342
+
343
+ def make_runtime_safe(self):
344
+ def _make_size_runtime_safe(x: Union[None, int, torch.SymInt]) -> Optional[int]:
345
+ dummy = -1
346
+ if isinstance(x, torch.SymInt):
347
+ # Replace nested ints by a dummy value (-1) as NJT ignores
348
+ # the outer_size/outer_stride at runtime.
349
+ return dummy if x.node.is_nested_int() else None
350
+ return x
351
+
352
+ assert self.original_subclass is not None
353
+ self.original_subclass_type = type(self.original_subclass)
354
+ self.original_subclass = None
355
+
356
+ # Note: NJT outer_size in AOTDispatcher
357
+ # `_make_size_runtime_safe` replaces any nested int with a dummy value (-1)
358
+ # to prevent serializing a SymInt at runtime. Internally, nested tensor __tensor_unflatten__
359
+ # is designed to safely ignore this dummy value.
360
+ # For more details, see: https://github.com/pytorch/pytorch/blob/5141ade8e30c64e873e14dcc8de233da45d15025/torch/nested/_internal/nested_tensor.py#L266-L299 # noqa: B950
361
+ self.outer_size = tuple(map(_make_size_runtime_safe, self.outer_size))
362
+ self.outer_stride = tuple(map(_make_size_runtime_safe, self.outer_stride))
363
+
364
+ # Recurse on nested subclass info
365
+ for creation_meta in self.attrs.values():
366
+ if isinstance(creation_meta, SubclassCreationMeta):
367
+ creation_meta.make_runtime_safe()
368
+
369
+ def __post_init__(self):
370
+ # sanity assert to make sure we don't leak memory
371
+ assert is_fake(self.original_subclass)
372
+
373
+
374
+ # This class encapsulates all aliasing + mutation info we need about the forward graph
375
+ # See a more detailed overview of the edge case handling at
376
+ # https://docs.google.com/document/d/19UoIh_SVrMy_b2Sx5ZaeOJttm6P0Qmyss2rdBuyfoic/edit
377
+ # NOTE: This class is saved in AOTAutogradCache, If you are adding elements, make sure
378
+ # they are covered by warm cache tests.
379
+ @dataclass(eq=False)
380
+ class ViewAndMutationMeta:
381
+ # length = # user inputs
382
+ # This gives us info about every input, and what sort of mutation happened to it (if any)
383
+ input_info: list[InputAliasInfo]
384
+
385
+ # length = # user outputs
386
+ # This gives us info about every output (mostly around whether it aliases other tensors)
387
+ output_info: list[OutputAliasInfo]
388
+
389
+ # length = the number of intermediate bases appended as outputs to the end of the forward graph.
390
+ # Note: this is not necessarily the same thing as:
391
+ # len([x for x in output_info if x.output_type == OutputType.alias_of_intermediate])
392
+ # Because outputs might share a ._base, or an output's ._base might itself be
393
+ # another user output (in both cases, we won't redundantly append bases to the end of the graph)
394
+ num_intermediate_bases: int
395
+
396
+ # For inference only: instructs us to keep data-only input mutations directly in the graph
397
+ keep_input_mutations: bool
398
+
399
+ # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors)
400
+ # + (# intermediate bases)
401
+ # These are the FakeTensor (or potential SymInt) outputs that we traced from our
402
+ # metadata pass of the user's forward function.
403
+ # Their only use today is to pass them as a best-guess for tangents when tracing the joint.
404
+ # Stashing them as part of our "metadata" makes it simpler if we want to run our analysis
405
+ # pass once, and reuse the output throughout AOTAutograd
406
+ traced_tangents: list[Any]
407
+
408
+ # TODO doc
409
+ traced_tangents_descs: list[AOTInput]
410
+
411
+ # Each of these is a list telling us about subclasses for the inputs/outputs/grad_outs
412
+ # They are used throughout AOTDispatch to tell us how to generate a list of subclass tensors,
413
+ # Given a (potentially larger) list of plain torch tensors.
414
+
415
+ # Taking subclass_inp_meta as an example:
416
+ # subclass_inp_meta[i] = j (an int) tells us:
417
+ # "The i'th user input is not a subclass, and corresponds to inputs[j] of the plain-tensor graph."
418
+ # subclass_inp_meta[i] = SubclassCreationMeta(flat_tensor_start_idx=3, arg_count=2)
419
+ # "The i'th user input is subclass holding two inner tensors, which are
420
+ # inputs[3] and inputs[4] of the plain-tensor graph".
421
+
422
+ # length = # user inputs
423
+ subclass_inp_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
424
+ # So, the full set of outputs to the forward graph looks something like:
425
+ # (*mutated_inps, *user_outs, *intermediate_bases, *saved_for_bw_tensors)
426
+ # where the first 3 of those 4 can be subclasses
427
+ # (but not saved_for_bw tensors, since these are internal to the compiler
428
+ # and not user visible, so there's no point in wrapping/unwrapping them at runtime).
429
+ # This list contains subclass information on all of the fw graph outputs
430
+ # except for saved_for_bw_tensors.
431
+ subclass_fw_graph_out_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
432
+ # length = # backward graph inputs
433
+ subclass_tangent_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]]
434
+ # TODO: we should kill this
435
+ # (need to default it to not break internal)
436
+ is_train: bool = False
437
+
438
+ # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors)
439
+ # + (# intermediate bases)
440
+ # At runtime, we don't keep the traced_tangents around since they're not serializable.
441
+ # Instead, we keep any necessary subclass metadata necessary about each traced_tangent.
442
+ # This list is generated after calling make_runtime_safe().
443
+ traced_tangent_metas: Optional[list[Any]] = None
444
+
445
+ num_symints_saved_for_bw: Optional[int] = None
446
+
447
+ # The grad_enabled mutation that will be emitted in the runtime_wrapper epilogue
448
+ # NOTE: AOTAutograd will assume that the ambient `is_grad_enabled` is the grad mode
449
+ # that is intended to be in effect prior to running the graph, in keeping with
450
+ # equivalence to eager mode. It is the responsibility of upstream graph acquisition
451
+ # to reset the grad mode to its pre-graph value prior to calling aot_autograd.
452
+ grad_enabled_mutation: Optional[bool] = None
453
+
454
+ # Keeps track of whether `torch.use_deterministic_algorithms` was turned on
455
+ # when the forward was run. If deterministic mode was turned off during the
456
+ # forward, but is turned on during the backward call, then an error is
457
+ # raised
458
+ deterministic: Optional[bool] = None
459
+
460
+ # Keeps track of which input indices store parameters (which we will treat as static)
461
+ static_input_indices: list[int] = field(default_factory=list)
462
+
463
+ # Map of effect type (ex. _EffectType.ORDERED) to token. If there are
464
+ # side-effectful operators, FunctionalTensorMode will populate this
465
+ # dictionary telling us how many tokens we will need during tracing.
466
+ tokens: dict[Any, torch.Tensor] = field(default_factory=dict)
467
+
468
+ # Only filled in if/when we trace the joint function
469
+ # If an input requires grad and is mutated in the backward, it is only safe to keep the mutation
470
+ # in the graph if gradients are disabled while the backward runs
471
+ # (grad mode is disabled by default when users run the backward, but can be turned on with create_graph=True)
472
+ # At runtime during the backward, we use this list of indices to error properly if we find out
473
+ # that it was not safe to include a backward mutation in the graph.
474
+ indices_of_inputs_that_requires_grad_with_mutations_in_bw: list[int] = field(
475
+ default_factory=list
476
+ )
477
+
478
+ # Indexes of saved tensors which are donated buffer.
479
+ # Donated buffer means the tensor is not alias of any forward user input, forward user output,
480
+ # and backward output.
481
+ bw_donated_idxs: Optional[list[int]] = None
482
+
483
+ # Number of tokens used in backward, appended at the end of backward outputs.
484
+ # Filled after tracing joint function.
485
+ num_backward_tokens: int = 0
486
+
487
+ # Number of rng states that will get thread into the forward and backward for
488
+ # cudagraph compatible run_and_save_rng
489
+ num_graphsafe_rng_states: int = 0
490
+
491
+ graphsafe_rng_state_index: Optional[int] = None
492
+
493
+ def __post_init__(self):
494
+ # pre-compute the indices of the inputs that are mutated.
495
+ # When keep_input_mutations is set, we don't need to worry about our epilogue
496
+ # handling data-only mutations, because we keep them directly in the graph.
497
+ mutated_inp_runtime_indices = [
498
+ i
499
+ for i, m in enumerate(self.input_info)
500
+ if (m.mutation_type == MutationType.MUTATED_OUT_GRAPH)
501
+ ]
502
+
503
+ mutated_graph_handled_indices = [
504
+ i
505
+ for i, m in enumerate(self.input_info)
506
+ if m.mutation_type == MutationType.MUTATED_IN_GRAPH
507
+ ]
508
+ self.mutated_graph_handled_indices = mutated_graph_handled_indices
509
+ self.num_mutated_graph_handled_indices = len(self.mutated_graph_handled_indices)
510
+
511
+ mutated_graph_handled_indices_seen_by_autograd = [
512
+ i
513
+ for i in mutated_graph_handled_indices
514
+ if not self.input_info[i].mutations_hidden_from_autograd
515
+ ]
516
+
517
+ self.mutated_graph_handled_indices_seen_by_autograd = (
518
+ mutated_graph_handled_indices_seen_by_autograd
519
+ )
520
+ self.num_mutated_graph_handled_indices_seen_by_autograd = len(
521
+ self.mutated_graph_handled_indices_seen_by_autograd
522
+ )
523
+
524
+ aliased_out_indices = [
525
+ i
526
+ for i, m in enumerate(self.output_info)
527
+ if m.output_type
528
+ not in [
529
+ OutputType.non_alias,
530
+ OutputType.unsafe_view_alias,
531
+ OutputType.custom_function_view,
532
+ ]
533
+ ]
534
+ unsafe_view_out_indices = [
535
+ i
536
+ for i, m in enumerate(self.output_info)
537
+ if m.output_type is OutputType.unsafe_view_alias
538
+ ]
539
+
540
+ # This is pre-computed in post_init for perf.
541
+ # It contains the index of every element
542
+ # of input_info that corresponds to a mutation (data or metadata or both)
543
+ self.mutated_inp_runtime_indices = mutated_inp_runtime_indices
544
+ self.num_mutated_inp_runtime_indices = len(self.mutated_inp_runtime_indices)
545
+
546
+ # This is pre-computed for perf.
547
+ # It contains the index of every element
548
+ # of output_info that corresponds to an alias (either of an input or intermediate)
549
+ self.aliased_out_indices = aliased_out_indices
550
+ self.unsafe_view_out_indices = unsafe_view_out_indices
551
+ self.num_outputs = len(self.output_info)
552
+ self.num_outputs_non_aliased = len(
553
+ [
554
+ x
555
+ for x in self.output_info
556
+ if x.output_type
557
+ in [
558
+ OutputType.non_alias,
559
+ OutputType.unsafe_view_alias,
560
+ OutputType.custom_function_view,
561
+ ]
562
+ ]
563
+ )
564
+ self.num_outputs_aliased_to_inputs = len(
565
+ [
566
+ x
567
+ for x in self.output_info
568
+ if x.output_type
569
+ in [
570
+ OutputType.alias_of_input,
571
+ OutputType.is_input,
572
+ ]
573
+ ]
574
+ )
575
+ self.num_unsafe_view_outputs = len(self.unsafe_view_out_indices)
576
+ self.num_outputs_aliased_to_intermediates = len(
577
+ [
578
+ x
579
+ for x in self.output_info
580
+ if x.output_type
581
+ in [
582
+ OutputType.alias_of_intermediate,
583
+ OutputType.alias_of_intermediate_save_as_output,
584
+ OutputType.alias_of_intermediate_base_is_user_output,
585
+ ]
586
+ ]
587
+ )
588
+ self.num_outputs_aliased = (
589
+ self.num_outputs_aliased_to_inputs
590
+ + self.num_outputs_aliased_to_intermediates
591
+ )
592
+
593
+ # Record dynamic outputs of the Dynamo traced forward graph
594
+ # Mark them as dynamic at the end of the runtime wrapper
595
+ self.dynamic_outputs = any(o.dynamic_dims for o in self.output_info)
596
+
597
+ # Record the indices of dynamic outputs in the partitioned forward graph
598
+ # Mark them as dynamic in the runtime wrapper
599
+ # activation index -> dynamic dims indices
600
+ self.dynamic_saved_tensors_idxs: dict[int, set[int]] = {}
601
+
602
+ # See Note: [AOTAutograd Backward Guards]
603
+ # This is pre-computed for fast asserts on the types of our grad_outputs in the backward.
604
+ # Eventually, we should kill this and replace with real backward guards.
605
+ # (we want to precompute the "runtime" types, so replace FakeTensor with torch.Tensor)
606
+ self.output_types = [
607
+ torch.Tensor if isinstance(x, FakeTensor) else type(x)
608
+ for x in self.traced_tangents
609
+ ]
610
+
611
+ self.is_rng_op_functionalized = config.functionalize_rng_ops
612
+ # All of the above metadata is collected by tracing the fw function.
613
+ # However, extra outputs for rng offsets behave differently. Both fwd
614
+ # and bwd graphs have their own outputs for the total consumed offsets.
615
+ # Unlike mutated inputs, we don't have to worry about sending the right
616
+ # set of tensors between fwd and bwd. Fwd and bwd offsets are
617
+ # independent and simpler to handle. Therefore, we track them
618
+ # separately.
619
+ self.num_outputs_rng_offset = 1 if self.is_rng_op_functionalized else 0
620
+
621
+ # Our forward() returns both (tokens, mutated_inputs, outputs, output_intermediate_bases, saved_tensors, saved_symints)
622
+ # Tokens will be split out before mutations/view handling and we do not count them here.
623
+ self.num_forward_returns = (
624
+ self.num_mutated_inp_runtime_indices
625
+ + self.num_outputs
626
+ + self.num_intermediate_bases
627
+ )
628
+ # In case of functionalization of rng ops, the fw_module returns one
629
+ # additional output for rng offset. This rng offset is used right
630
+ # away to advance the rng state, and is not passed on to the raw
631
+ # outputs. However, we need to know the exact boundary to identify
632
+ # which tensors to be saved for the bwd graph. num_forward captures
633
+ # this information.
634
+ self.num_forward = self.num_forward_returns + self.num_outputs_rng_offset
635
+
636
+ def make_runtime_safe(self):
637
+ """
638
+ There are various fields in ViewAndMutationMeta that aren't serializable. This function is called after all tracing
639
+ is completed to simplify certain fields in the metadata so that they can be safely cached.
640
+
641
+ Doing so may lose information (in the case of traced_tangents), but none of the information is needed at runtime.
642
+ """
643
+ # TODO: This function is only a best effort: there are other fields that may not be cache safe
644
+ # (i.e., there's no guarantee that tensor_flatten() returns a serializable result), or that
645
+ # SubclassCreationMeta is cache safe.
646
+ assert self.traced_tangent_metas is None
647
+
648
+ def extract_metadata(t):
649
+ if isinstance(t, torch.Tensor) and is_traceable_wrapper_subclass(t):
650
+ (inner_tensors, flatten_spec) = t.__tensor_flatten__() # type: ignore[attr-defined]
651
+ # Technically, we only need the flatten_spec, not the inner tensors.
652
+ # However, some Tensor subclasses (like TwoTensor) may have flatten_spec = None.
653
+ # And we want to be able to assert that this metadata is non-None,
654
+ # to distinguish between "this was a tensor subclass with no metadata" vs.
655
+ # "this wasn't a tensor subclass at all".
656
+ return (inner_tensors, flatten_spec)
657
+ else:
658
+ return None
659
+
660
+ self.traced_tangent_metas = [extract_metadata(t) for t in self.traced_tangents]
661
+ # Clear traced tangents at runtime
662
+ self.traced_tangents = []
663
+ for inp_meta in self.subclass_inp_meta:
664
+ if isinstance(inp_meta, SubclassCreationMeta):
665
+ inp_meta.make_runtime_safe()
666
+ for inp_meta in self.subclass_fw_graph_out_meta:
667
+ if isinstance(inp_meta, SubclassCreationMeta):
668
+ inp_meta.make_runtime_safe()
669
+ for inp_meta in self.subclass_tangent_meta:
670
+ if isinstance(inp_meta, SubclassCreationMeta):
671
+ inp_meta.make_runtime_safe()
672
+
673
+ @property
674
+ def tensors_saved_for_backwards_slice(self):
675
+ assert self.num_symints_saved_for_bw is not None
676
+ if self.num_symints_saved_for_bw > 0:
677
+ return slice(self.num_forward, -self.num_symints_saved_for_bw)
678
+ else:
679
+ return slice(self.num_forward, None)
680
+
681
+ @property
682
+ def symints_saved_for_backwards_slice(self):
683
+ assert self.num_symints_saved_for_bw is not None
684
+ if self.num_symints_saved_for_bw > 0:
685
+ return slice(-self.num_symints_saved_for_bw, None)
686
+ else:
687
+ return slice(0, 0) # empty slice
688
+
689
+ def __eq__(self, other):
690
+ if not isinstance(other, ViewAndMutationMeta):
691
+ return NotImplemented
692
+ return (
693
+ self.input_info == other.input_info
694
+ and self.output_info == other.output_info
695
+ and self.num_intermediate_bases == other.num_intermediate_bases
696
+ and self.keep_input_mutations == other.keep_input_mutations
697
+ and self.is_rng_op_functionalized == other.is_rng_op_functionalized
698
+ and self.num_outputs_rng_offset == other.num_outputs_rng_offset
699
+ and len(self.traced_tangents) == len(other.traced_tangents)
700
+ and all(
701
+ x.shape == y.shape and x.dtype == y.dtype
702
+ for x, y in zip(self.traced_tangents, other.traced_tangents)
703
+ )
704
+ and self.num_backward_tokens == other.num_backward_tokens
705
+ )
706
+
707
+
708
+ @dataclass(eq=False)
709
+ class SubclassMeta:
710
+ # A copy of all forward metadata, but computed on the *dense* tensor forward (after desugaring subclasses)
711
+ # So for example, if the user had a model containing two `TwoTensor` inputs,
712
+ # Then `SubclassMeta.fw_metadata.input_infos` would have length 4 here.
713
+ fw_metadata: ViewAndMutationMeta
714
+
715
+ # Note: [Computing Subclass Metadata about grad_inputs]
716
+ # Given a list of flattened, plain tensor grad_inputs, this tells us how to reconstruct the grad_input subclasses
717
+ #
718
+ # You might think: why not just assume that all grad_inputs will have the same subclass-ness as the original inputs?
719
+ # (AOTAutograd generally assumes other properties, e.g. that grad_outputs are contiguous)
720
+ #
721
+ # This doesn't really work though. take this example:
722
+ #
723
+ # def f(DoubleTensor, DenseTensor):
724
+ # return DoubleTensor * DenseTensor
725
+ #
726
+ # In the above example, the .grad field of *both* DoubleTensor and DenseTensor will be a DoubleTensor.
727
+ # When we trace out a joint fw-bw graph, we'll end up returning two subclasses for the two grad_inputs.
728
+ # This means that our backward graph will return 4 outputs (two dense tensors for each DoubleTensor grad_input)
729
+ # and we need to properly store the metadata that tells us how to turn these 4 outputs back into DoubleTensors.
730
+ #
731
+ # Note that this info **cannot** easily be figured out from ViewAndMutationMeta.
732
+ # We can only compute this info by tracing the entire joint and examining the grad_inputs that we computed.
733
+ #
734
+ # See Note: [AOTAutograd Backward Guards]
735
+ # This will also eventually require us to install backward guards,
736
+ # in case we made incorrect assumptions about the subclass-ness of our grad_outputs
737
+ #
738
+ # Optional field because we don't compute for inference graphs
739
+ grad_input_metas: Optional[list[Union[PlainTensorMeta, SubclassCreationMeta]]] = (
740
+ None
741
+ )
742
+
743
+ def __init__(self) -> None:
744
+ # The fields in this class get set after its construction.
745
+ pass
746
+
747
+
748
+ # This class exists because:
749
+ # - the autograd.Function.forward() in aot autograd returns outputs that might alias inputs
750
+ # - we only care about the metadata on those aliases, so we can regenerate them.
751
+ # We do not want them to participate in the autograd.Function.
752
+ # We do that by wrapping them in an opaque class, so the autograd.Function
753
+ # does not know to treat them as tensors.
754
+ @dataclass(frozen=True)
755
+ class TensorAlias:
756
+ alias: torch.Tensor
757
+
758
+
759
+ @dataclass
760
+ class BackwardSignature:
761
+ """
762
+ Provides information about the backward section of an exported
763
+ joint forward-backward graph.
764
+ For a particular fx GraphModule, this class contains information on:
765
+ (1) A mapping from each gradient (backwards output) to the parameter
766
+ it corresponds to (forward input)
767
+ (2) A mapping from each gradient (backwards output) to the user input
768
+ it corresponds to (forward input)
769
+ (3) Which of the forward outputs corresponds to the loss, that we backprop on.
770
+
771
+ Each string name is the `node.name` of the corresponding node in the fx graph.
772
+ """
773
+
774
+ gradients_to_parameters: dict[str, str]
775
+ gradients_to_user_inputs: dict[str, str]
776
+ loss_output: str
777
+
778
+
779
+ GraphOutputName = NewType("GraphOutputName", str)
780
+ GraphInputName = NewType("GraphInputName", str)
781
+ FQN = NewType("FQN", str)
782
+
783
+
784
+ @dataclass
785
+ class GraphSignature:
786
+ """
787
+ Provides information about an exported module.
788
+ For a particular fx GraphModule, this class contains information on:
789
+ (1) Which graph inputs are parameters, buffers, or user inputs
790
+ (2) (for params/buffers) a mapping from the name of each graph argument
791
+ to its parameter/buffer FQN in the original nn.Module.
792
+ (3) If there are input mutations, these are represented as extra outputs
793
+ in the fx GraphModule. We provide a mapping from these
794
+ extra output names to the names of the actual inputs.
795
+ (4) The pytree metadata on how to flatten/unflatten inputs and outputs.
796
+ The corresponding FX GraphModule only accepts and returns
797
+ pytree-flattened inputs/outputs.
798
+ (5) (Optionally) if the FX is a joint forward-backward graph, we provide
799
+ a signature on the backward section of the joint graph.
800
+ """
801
+
802
+ parameters: list[FQN]
803
+ buffers: list[FQN]
804
+
805
+ user_inputs: list[GraphInputName]
806
+ user_outputs: list[GraphOutputName]
807
+ inputs_to_parameters: dict[GraphInputName, FQN]
808
+ inputs_to_buffers: dict[GraphInputName, FQN]
809
+
810
+ # If the user's module mutates a buffer,
811
+ # it's represented in the graph as an extra graph output.
812
+ # This dict is a mapping from
813
+ # "graph outputs that correspond to updated buffers"
814
+ # to the FQN names of those mutated buffers.
815
+ buffers_to_mutate: dict[GraphOutputName, FQN]
816
+ parameters_to_mutate: dict[GraphOutputName, FQN]
817
+ user_inputs_to_mutate: dict[GraphOutputName, GraphInputName]
818
+
819
+ in_spec: pytree.TreeSpec
820
+ out_spec: pytree.TreeSpec
821
+
822
+ backward_signature: Optional[BackwardSignature]
823
+
824
+ input_tokens: list[GraphInputName]
825
+ output_tokens: list[GraphOutputName]
826
+
827
+ @classmethod
828
+ def from_tracing_metadata(
829
+ cls,
830
+ *,
831
+ in_spec: pytree.TreeSpec,
832
+ out_spec: pytree.TreeSpec,
833
+ graph_input_names: list[str],
834
+ graph_output_names: list[str],
835
+ view_mutation_metadata: ViewAndMutationMeta,
836
+ named_parameters: list[str],
837
+ named_buffers: list[str],
838
+ num_user_inputs: int,
839
+ num_user_outputs: int,
840
+ trace_joint: bool,
841
+ loss_index: Optional[int],
842
+ backward_signature: Optional[BackwardSignature],
843
+ ) -> GraphSignature:
844
+ graph_inputs = graph_input_names
845
+ graph_outputs = graph_output_names
846
+ parameters = list(named_parameters)
847
+ buffers = list(named_buffers)
848
+ num_tokens = len(view_mutation_metadata.tokens)
849
+
850
+ # Calling convention assumptions:
851
+ # (1) graph inputs = (input_tokens, params, buffers, user_inputs)
852
+ # (2) graph outputs = (output_tokens, mutated_inputs, user_outs, param_gradients)
853
+ # (If we are capturing an inference graph, this convention is identical
854
+ # except that param_gradients is empty)
855
+ # See Note [Side-Effectful Tokens in AOTAutograd] for information on tokens
856
+
857
+ # Address input calling conventions:
858
+ start, stop = 0, num_tokens
859
+ input_tokens = graph_inputs[start:stop]
860
+
861
+ start, stop = stop, stop + len(parameters)
862
+ inputs_to_parameters = dict(zip(graph_inputs[start:stop], parameters))
863
+
864
+ start, stop = stop, stop + len(buffers)
865
+ inputs_to_buffers = dict(
866
+ zip(
867
+ graph_inputs[start:stop],
868
+ buffers,
869
+ )
870
+ )
871
+
872
+ start, stop = stop, stop + num_user_inputs
873
+ user_inputs = graph_inputs[start:stop]
874
+
875
+ # We should've gone through all the inputs now
876
+ assert len(graph_inputs) - stop == 0
877
+
878
+ # Address output calling conventions:
879
+ start, stop = 0, num_tokens
880
+ output_tokens = graph_outputs[start:stop]
881
+
882
+ names = [*input_tokens, *parameters, *buffers, *user_inputs]
883
+ mutations = []
884
+ for idx, input_info in enumerate(view_mutation_metadata.input_info):
885
+ if input_info.mutates_data:
886
+ if trace_joint:
887
+ # Only buffers can be mutated, not parameters
888
+ assert idx >= len(parameters)
889
+ mutations.append(names[idx + num_tokens])
890
+
891
+ assert len(mutations) == view_mutation_metadata.num_mutated_inp_runtime_indices
892
+
893
+ start, stop = (
894
+ stop,
895
+ stop + view_mutation_metadata.num_mutated_inp_runtime_indices,
896
+ )
897
+ outputs_to_mutations = dict(zip(graph_outputs[start:stop], mutations))
898
+
899
+ user_inputs_to_mutate = {}
900
+ buffers_to_mutate = {}
901
+ parameters_to_mutate = {}
902
+ for output_name, mutation_name in outputs_to_mutations.items():
903
+ if mutation_name in user_inputs:
904
+ user_inputs_to_mutate[output_name] = mutation_name
905
+ else:
906
+ assert mutation_name in buffers or mutation_name in parameters
907
+ if mutation_name in buffers:
908
+ buffers_to_mutate[output_name] = mutation_name
909
+ else:
910
+ parameters_to_mutate[output_name] = mutation_name
911
+
912
+ start, stop = stop, stop + num_user_outputs
913
+ user_outputs = graph_outputs[start:stop]
914
+
915
+ unused_outputs = len(graph_outputs) - stop
916
+ if backward_signature is not None:
917
+ unused_outputs -= len(backward_signature.gradients_to_parameters) + len(
918
+ backward_signature.gradients_to_user_inputs
919
+ )
920
+ assert unused_outputs == 0
921
+
922
+ return GraphSignature(
923
+ parameters=parameters, # type: ignore[arg-type]
924
+ buffers=buffers, # type: ignore[arg-type]
925
+ user_inputs=user_inputs, # type: ignore[arg-type]
926
+ user_outputs=user_outputs, # type: ignore[arg-type]
927
+ inputs_to_buffers=inputs_to_buffers, # type: ignore[arg-type]
928
+ inputs_to_parameters=inputs_to_parameters, # type: ignore[arg-type]
929
+ user_inputs_to_mutate=user_inputs_to_mutate,
930
+ buffers_to_mutate=buffers_to_mutate, # type: ignore[arg-type]
931
+ parameters_to_mutate=parameters_to_mutate, # type: ignore[arg-type]
932
+ in_spec=in_spec,
933
+ out_spec=out_spec,
934
+ backward_signature=backward_signature,
935
+ input_tokens=input_tokens, # type: ignore[arg-type]
936
+ output_tokens=output_tokens, # type: ignore[arg-type]
937
+ )
938
+
939
+
940
+ @dataclass
941
+ class AOTAutogradCacheInfo:
942
+ cache_key: str
943
+ start_time_ns: int
944
+ forward_symints: list[torch.SymInt]
945
+
946
+
947
+ @dataclass
948
+ class AOTConfig:
949
+ """
950
+ Configuration for AOTDispatcher
951
+ """
952
+
953
+ fw_compiler: Callable
954
+ bw_compiler: Callable
955
+ partition_fn: Callable
956
+ decompositions: dict[OpOverload, Callable]
957
+ num_params_buffers: int
958
+ aot_id: int
959
+ keep_inference_input_mutations: bool
960
+ is_export: bool = False
961
+ no_tangents: bool = False
962
+ dynamic_shapes: bool = False
963
+ aot_autograd_arg_pos_to_source: Optional[list[Source]] = None
964
+ static_input_indices: Optional[list[int]] = None
965
+ inference_compiler: Optional[Callable] = None
966
+ enable_log: bool = True
967
+ # this is always false outside of export.
968
+ pre_dispatch: bool = False
969
+ # Key to use for AOTAutogradCache
970
+ cache_info: Optional[AOTAutogradCacheInfo] = None
971
+ # If we should ignore the shape_env in the ambient tracing_context.
972
+ # The net effect is that if dynamic shapes are on, we end up
973
+ # specializing on example_inputs.
974
+ # Used only by standalone_compile.
975
+ ignore_shape_env: bool = False
976
+ precompile_backend_id: Optional[str] = None
977
+ force_non_lazy_backward_lowering: bool = False
978
+ # This config makes sure to check certain things like
979
+ # mutating input with req_grad in export joint tracing.
980
+ export_trace_joint: bool = False
981
+
982
+ def __post_init__(self):
983
+ if self.pre_dispatch:
984
+ assert self.is_export, "Can only have pre_dispatch IR for export."
985
+
986
+
987
+ # TODO: types here
988
+ # plain_tensor_trace_fn, when it is joint, has tuple structure on the trace
989
+ # info too!
990
+ # TODO: this needs to be generic, parameterized on AOTDescriptor
991
+ SubclassTracingInfo = collections.namedtuple(
992
+ "SubclassTracingInfo",
993
+ [
994
+ "plain_tensor_trace_fn",
995
+ "plain_tensor_args",
996
+ "plain_tensor_args_descs",
997
+ "maybe_subclass_meta",
998
+ ],
999
+ )
1000
+
1001
+
1002
+ @dataclass
1003
+ class AOTState:
1004
+ """
1005
+ When we run AOTAutograd, this class encapsulates the state in the compiler which
1006
+ must be preserved across stages. This is state in the traditional sense (not an
1007
+ environment) because some values in this structure change as we progress through
1008
+ pipelines in AOTAutograd.
1009
+ """
1010
+
1011
+ # Whether or not we need to handle autograd when doing graph capture and
1012
+ # compilation. Although the calling convention for non-autograd graph
1013
+ # capture in AOTAutograd is simple and can be relied upon, the autograph
1014
+ # capture calling convention is quite complicated and in general you are
1015
+ # only expected to pass to aot_stage2_compile to process.
1016
+ needs_autograd: bool
1017
+
1018
+ # The FAKE flat arguments which we will do tracing with. Although you
1019
+ # might naively expect this to be immutable, it's not: when we perform
1020
+ # tracing, we may execute code that modifies the metadata of inputs,
1021
+ # causing the args to become "invalid". It's also nontrivial to have a
1022
+ # "golden" set of fake values and deepcopy them just in time when you
1023
+ # might destructively mutate them (Voz and I tried very hard to do this).
1024
+ # So we just periodically renew this field. Don't worry too much about
1025
+ # this unless you're specifically trying to track down an input metadata
1026
+ # mutation bug.
1027
+ #
1028
+ # (By the way, this is NEVER the joint inputs! Those only ever go in
1029
+ # AOTGraphCapture)
1030
+ flat_args: list[FxValue]
1031
+
1032
+ # The descriptor for each argument in flat_args.
1033
+ flat_args_descs: list[AOTInput]
1034
+
1035
+ # This contains view and mutation information about the function, which we
1036
+ # detected by doing an initial trace when we created this state.
1037
+ fw_metadata: ViewAndMutationMeta
1038
+
1039
+ # Top-level configuration
1040
+ # This is morally immutable but sometimes we are naughty and mutate it.
1041
+ aot_config: AOTConfig
1042
+
1043
+ # When performing AOTAutograd traces and other passes, we typically
1044
+ # require a lot of active context managers; most typically these either
1045
+ # (1) ensure we are faithfully replicating the original PyTorch context
1046
+ # managers or (2) toggle some behaviors in PyTorch to make it more
1047
+ # suitable for tracing. When you use AOTState, you're expected to have
1048
+ # created an ExitStack, entered it; then while we are running AOTAutograd
1049
+ # we will add things onto the stack as necessary. When you're all done
1050
+ # with processing AOTAutograd, you can exit this stack. All functions
1051
+ # that take AOTState expect the ExitStack to not have been exited yet.
1052
+ #
1053
+ # TODO: We potentially could offer a resumable context manager, where you
1054
+ # can cancel it and reenable it later when you need it.
1055
+ stack: contextlib.ExitStack
1056
+
1057
+
1058
+ FxValue = Union[Tensor, int, SymInt, BackwardState]
1059
+
1060
+
1061
+ class CompilerWrapper:
1062
+ """
1063
+ AOTAutograd needs to do many transformations to the calling convention of the user function
1064
+ it is tracing, e.g., deduplicating inputs, unpacking subclasses, etc. CompilerWrapper lets
1065
+ us factor these into compositional stages so we can handle each transformation incrementally
1066
+ instead of having to do it all at once.
1067
+
1068
+ Since there is a calling convention change, there are two parts to the wrpaper:
1069
+
1070
+ 1. The prologue, which is about compile-time behavior: given this original function, what
1071
+ is the new function with modified calling convention that we should trace with AOTAutograd
1072
+ to get the FX graph we will do joint passes, partitioning and ultimate Inductor compilation on?
1073
+ We get (flat_fn, flat_args), the original function under trace and inputs we were
1074
+ going to feed it, and produce a new function and new inputs to feed it.
1075
+
1076
+ 2. The epilogue, which is about run-time behavior: we have now compiled the modified calling
1077
+ convention function, we need to wrap it so that we have a new function that has the
1078
+ original calling convention of the original function, so that our users can call it
1079
+ at the old signature they expected. We get (compiled_fn, real arguments), the newly
1080
+ compiled function we need to wrap.
1081
+
1082
+ Note about caching: we do NOT directly serialize the runtime wrappers; instead, they
1083
+ are reapplied to compiled_fn after we have finished deserializing the compiled_fn.
1084
+
1085
+ Extra metadata that is needed to compute pre or post compile can be passed in via attributes.
1086
+ """
1087
+
1088
+ def pre_compile(
1089
+ self,
1090
+ flat_fn,
1091
+ flat_args: list[FxValue],
1092
+ flat_args_descs: list[AOTInput],
1093
+ aot_config: AOTConfig,
1094
+ *,
1095
+ fw_metadata: ViewAndMutationMeta,
1096
+ ) -> tuple[Callable, list[FxValue], list[AOTInput], ViewAndMutationMeta]:
1097
+ """
1098
+ Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs.
1099
+ Args:
1100
+ flat_fn: The function to compile
1101
+ flat_args: Metadata from example inputs of the function to compile
1102
+ aot_config: AOTConfig passed in at compile time
1103
+ fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args
1104
+ """
1105
+ return flat_fn, flat_args, flat_args_descs, fw_metadata
1106
+
1107
+ def post_compile(self, compiled_fn, aot_config, *, runtime_metadata) -> Callable:
1108
+ """
1109
+ Given an output of the compiler, wrap it with information received from prologue.
1110
+ Args:
1111
+ compiled_fn: Callable after calling compiler_fn
1112
+ aot_config: AOTConfig after calling prologue
1113
+ runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps.
1114
+ Example:
1115
+
1116
+ def wrapped_compiled_fn(args):
1117
+ # do something with args, aot_config, fw_metadata
1118
+ return compiled_fn(args)
1119
+
1120
+ return wrapped_compiled_fn
1121
+ """
1122
+ return compiled_fn
1123
+
1124
+
1125
+ class InductorWrapper:
1126
+ """
1127
+ This is sort of like CompilerWrapper, but it happens at a different part of the lifecycle:
1128
+ it talks about transformations we do to the traced and partitioned FX graph before we
1129
+ send it to the Inductor compiler.
1130
+
1131
+ Once again, there are two parts:
1132
+
1133
+ 1. The prologue, which "modifies" the FX graph before we send it to
1134
+ Inductor. I say "modifies" because... we don't really actually do
1135
+ anything nontrivial in either of our two implementations.
1136
+ 2. The epilogue, which modifies the compiled function produced by Inductor
1137
+
1138
+ Although hypothetically these wrappers could be used compositionally in a centralized
1139
+ wrappers list, in practice they seem to just be invoked manually when needed.
1140
+
1141
+ NB: The flat_args input is sometimes mutated. This is probably naughty but whatever.
1142
+ """
1143
+
1144
+ def pre_compile(
1145
+ self,
1146
+ fw_module: torch.fx.GraphModule,
1147
+ flat_args: list[Tensor],
1148
+ aot_config: AOTConfig,
1149
+ *,
1150
+ fw_metadata: ViewAndMutationMeta,
1151
+ ) -> None:
1152
+ """
1153
+ Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs.
1154
+ Args:
1155
+ flat_fn: The function to compile
1156
+ flat_args: Metadata from example inputs of the function to compile
1157
+ aot_config: AOTConfig passed in at compile time
1158
+ fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args
1159
+ """
1160
+ return
1161
+
1162
+ def post_compile(self, compiled_fn, aot_config, *, runtime_metadata) -> Callable:
1163
+ """
1164
+ Given an output of the compiler, wrap it with information received from prologue.
1165
+ Args:
1166
+ compiled_fn: Callable after calling compiler_fn
1167
+ aot_config: AOTConfig after calling prologue
1168
+ runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps.
1169
+ Example:
1170
+
1171
+ def wrapped_compiled_fn(args):
1172
+ # do something with args, aot_config, fw_metadata
1173
+ return compiled_fn(args)
1174
+
1175
+ return wrapped_compiled_fn
1176
+ """
1177
+ return compiled_fn
1178
+
1179
+
1180
+ @dataclass
1181
+ class AOTGraphCapture: # Produced by aot_stage1_graph_capture
1182
+ # AOTAutograd typically operates by taking complicated graphs and
1183
+ # desugaring them into simpler graphs that use PyTorch features. These
1184
+ # wrappers establish invariants so that when we actually do tracing we can
1185
+ # assume these invariants hold, leading to a simpler tracing
1186
+ # implementation. However, this means that we have to keep track of how
1187
+ # to enter/exit these wrappers when passing inputs into the compiled
1188
+ # graph, among other things!
1189
+ wrappers: list[CompilerWrapper]
1190
+
1191
+ # The actual captured graph module. In some circumstances (export) this
1192
+ # graph has a specific calling convention that can be relied upon by
1193
+ # external callers. In other situations, the calling convention is
1194
+ # unspecified and only aot_stage2_compile knows how to deal with them.
1195
+ graph_module: torch.fx.GraphModule
1196
+
1197
+ # When compiling with autograd support, this is the joint_inputs, which is
1198
+ # larger than the original flat_args as all tangents get inputs. The
1199
+ # tuple organizes into primals and tangents. When not autograd it's just
1200
+ # a plain list.
1201
+ updated_flat_args: Union[list[Any], tuple[list[Any], list[Any]]]
1202
+
1203
+ updated_flat_args_descs: Union[
1204
+ list[AOTInput], tuple[list[AOTInput], list[AOTInput]]
1205
+ ]
1206
+
1207
+ # Metadata about subclass inputs/outputs in the graph trace.
1208
+ maybe_subclass_meta: Any
1209
+
1210
+
1211
+ FakifiedFlatArgs = NewType("FakifiedFlatArgs", list[Any])
1212
+
1213
+
1214
+ TOutputCode = TypeVar("TOutputCode", bound="OutputCode")
1215
+
1216
+
1217
+ class AOTDispatchCompiler(Protocol):
1218
+ """
1219
+ Represents a fw or bw_compiler passed to AOTAutograd.
1220
+ """
1221
+
1222
+ def __call__(
1223
+ self,
1224
+ gm: torch.fx.GraphModule,
1225
+ example_inputs: Sequence[InputType],
1226
+ ) -> Any: ...
1227
+
1228
+
1229
+ # TODO: bikeshed on this name
1230
+ class SerializableAOTDispatchCompiler(AOTDispatchCompiler):
1231
+ """
1232
+ Represents an AOTDispatchCompiler that returns an OutputCode, and is
1233
+ therefore cacheable. SerializableAOTDispatchCompiler always return an OutputCode.
1234
+ A _CompileFxCallable usually gets converted into an AOTDispatchCompiler after binding all of
1235
+ the kwargs in _CompileFxKwargs.
1236
+ """
1237
+
1238
+ def __init__(
1239
+ self,
1240
+ output_code_ty: type[TOutputCode],
1241
+ compiler_fn: Callable[[torch.fx.GraphModule, Sequence[InputType]], TOutputCode],
1242
+ ):
1243
+ self.output_code_ty = output_code_ty
1244
+ self.compiler_fn = compiler_fn
1245
+
1246
+ def __call__(
1247
+ self,
1248
+ gm: torch.fx.GraphModule,
1249
+ example_inputs: Sequence[InputType],
1250
+ ) -> OutputCode:
1251
+ return self.compiler_fn(gm, example_inputs)
1252
+
1253
+
1254
+ class FlatFn(Protocol):
1255
+ def __call__(self, *args: FxValue) -> list[FxValue]: ...
1256
+
1257
+
1258
+ class TraceFn(Protocol):
1259
+ def __call__(self, *args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: ...
1260
+
1261
+
1262
+ class PreppedForAutogradTraceFn(Protocol):
1263
+ def __call__(
1264
+ self,
1265
+ *args: FxValue,
1266
+ ) -> tuple[tuple[list[FxValue], list[bool]], list[AOTOutput]]: ...
1267
+
1268
+
1269
+ class JointTraceFn(Protocol):
1270
+ handle: JointFnHandle
1271
+
1272
+ def __call__(
1273
+ self, primals: list[FxValue], tangents: list[FxValue]
1274
+ ) -> tuple[
1275
+ tuple[list[FxValue], list[Optional[Tensor]]],
1276
+ tuple[list[AOTOutput], list[Optional[AOTOutput]]],
1277
+ ]: ...
1278
+
1279
+
1280
+ @dataclass
1281
+ class JointWithDescriptors:
1282
+ _aot_state: AOTState
1283
+ _aot_graph_capture: AOTGraphCapture
1284
+
1285
+ # The exact order parameters and buffers are expected to be passed into
1286
+ # the final compiled function. Parameters before buffers.
1287
+ params_spec: list[str]
1288
+ buffers_spec: list[str]
1289
+
1290
+ in_spec: pytree.TreeSpec
1291
+ out_spec: pytree.TreeSpec
1292
+
1293
+ @property
1294
+ def graph_module(self):
1295
+ return self._aot_graph_capture.graph_module
1296
+
1297
+ @graph_module.setter
1298
+ def graph_module(self, value):
1299
+ self._aot_graph_capture.graph_module = value
Scripts_Climate_n_LAI_to_Yield/.venv/lib/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
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing_extensions import TypeGuard
13
+
14
+ import torch
15
+ import torch.utils._pytree as pytree
16
+ from torch import SymInt, Tensor
17
+ from torch._subclasses.fake_tensor import get_plain_tensors
18
+ from torch.types import IntLikeType
19
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
20
+
21
+ from .descriptors import (
22
+ AOTInput,
23
+ AOTOutput,
24
+ DummyAOTInput,
25
+ SubclassGetAttrAOTInput,
26
+ SubclassGetAttrAOTOutput,
27
+ SubclassSizeAOTInput,
28
+ SubclassSizeAOTOutput,
29
+ SubclassStrideAOTInput,
30
+ SubclassStrideAOTOutput,
31
+ )
32
+ from .schemas import (
33
+ FxValue,
34
+ MutationType,
35
+ PlainTensorMeta,
36
+ SubclassCreationMeta,
37
+ ViewAndMutationMeta,
38
+ )
39
+ from .utils import strict_zip
40
+
41
+
42
+ zip = strict_zip
43
+
44
+ T = TypeVar("T", bound=torch.Tensor)
45
+
46
+
47
+ def requires_subclass_dispatch(args, fw_metadata: ViewAndMutationMeta) -> bool:
48
+ args_flattened = pytree.arg_tree_leaves(*args)
49
+ any_subclass_args = any(
50
+ is_traceable_wrapper_subclass(x)
51
+ for x in args_flattened
52
+ if isinstance(x, Tensor)
53
+ )
54
+ from torch._functorch._aot_autograd.schemas import SubclassCreationMeta
55
+
56
+ any_subclass_outputs = any(
57
+ type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta
58
+ )
59
+ # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime.
60
+ return any_subclass_args or any_subclass_outputs
61
+
62
+
63
+ from .schemas import MemoryFormatMeta
64
+
65
+
66
+ def maybe_suggest_memory_format(
67
+ t, with_memory_format: bool
68
+ ) -> Optional[MemoryFormatMeta]:
69
+ if not with_memory_format:
70
+ return None
71
+
72
+ return MemoryFormatMeta.from_tensor(t)
73
+
74
+
75
+ def get_subclass_typing_container(
76
+ tensor_subclass: torch.Tensor,
77
+ ) -> dict[type[torch.Tensor], list[type[torch.Tensor]]]:
78
+ """
79
+ Given a subclass, returns a recursive dictionary mapping each
80
+ inner tensors to its' subclass types.
81
+ """
82
+
83
+ def _get_types_for_subclass(tensor_subclass: torch.Tensor) -> None:
84
+ if not is_traceable_wrapper_subclass(tensor_subclass):
85
+ return
86
+ tracker[type(tensor_subclass)].append(tensor_subclass)
87
+ inner_keys, _ = tensor_subclass.__tensor_flatten__()
88
+ for key in inner_keys:
89
+ inner_tensor = getattr(tensor_subclass, key)
90
+ _get_types_for_subclass(inner_tensor)
91
+
92
+ tracker: dict[Any, list[Any]] = collections.defaultdict(list)
93
+ _get_types_for_subclass(tensor_subclass)
94
+ return tracker
95
+
96
+
97
+ def create_subclass_metadata(
98
+ a: Any, start_idx: int, count_symints: bool, with_memory_format: bool = False
99
+ ):
100
+ if not is_traceable_wrapper_subclass(a):
101
+ idx = start_idx + 1
102
+ return (
103
+ PlainTensorMeta(
104
+ idx,
105
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
106
+ ),
107
+ idx,
108
+ )
109
+
110
+ inner_keys, metadata = a.__tensor_flatten__()
111
+ new_start_idx = start_idx
112
+ attrs = {}
113
+
114
+ for key in inner_keys:
115
+ new_subclass_meta, new_start_idx = create_subclass_metadata(
116
+ getattr(a, key),
117
+ new_start_idx,
118
+ count_symints=count_symints,
119
+ with_memory_format=with_memory_format,
120
+ )
121
+ attrs[key] = new_subclass_meta
122
+
123
+ # It *must* be because is_traceable_wrapper_subclass() - but mypy is not smart.
124
+ assert isinstance(a, Tensor)
125
+
126
+ new_start_idx = (
127
+ new_start_idx
128
+ + count_symints * len(enumerate_filter_symints(a.size()))
129
+ + count_symints * len(enumerate_filter_symints(a.stride()))
130
+ )
131
+
132
+ return (
133
+ SubclassCreationMeta(
134
+ flat_tensor_start_idx=start_idx,
135
+ arg_count=new_start_idx - start_idx,
136
+ included_subclass_symints=count_symints,
137
+ attrs=attrs,
138
+ meta=metadata,
139
+ outer_size=a.size(), # type: ignore[attr-defined, arg-type]
140
+ outer_stride=a.stride(), # type: ignore[arg-type]
141
+ original_subclass=a,
142
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
143
+ ),
144
+ new_start_idx,
145
+ )
146
+
147
+
148
+ # Given a flat list of arguments, some of which may be tensor subclasses,
149
+ # computes metadata about "how to reconstruct the current list of subclasses,
150
+ # if we were given their flattened dense tensors instead"
151
+ def create_subclass_meta(
152
+ curr_args: Union[list[Any], tuple[Any, ...]],
153
+ *,
154
+ count_symints: bool = True,
155
+ with_memory_format: bool = False,
156
+ ) -> list[Union[PlainTensorMeta, SubclassCreationMeta]]:
157
+ idx = 0
158
+ infos: list[Union[PlainTensorMeta, SubclassCreationMeta]] = []
159
+ for a in curr_args:
160
+ if is_traceable_wrapper_subclass(a):
161
+ assert isinstance(a, Tensor)
162
+ start_idx = idx
163
+ subclass_meta, _ = create_subclass_metadata(
164
+ a,
165
+ start_idx,
166
+ count_symints=count_symints,
167
+ with_memory_format=with_memory_format,
168
+ )
169
+ infos.append(subclass_meta)
170
+ cnt = subclass_meta.arg_count
171
+ else:
172
+ infos.append(
173
+ PlainTensorMeta(
174
+ idx,
175
+ memory_format=maybe_suggest_memory_format(a, with_memory_format),
176
+ )
177
+ )
178
+ cnt = 1
179
+ idx += cnt
180
+ return infos
181
+
182
+
183
+ def enumerate_filter_symints(lst: Iterable[IntLikeType]) -> list[tuple[int, SymInt]]:
184
+ # Capture all SymInts from the iterable.
185
+ def symint_check(s: IntLikeType) -> TypeGuard[SymInt]:
186
+ return isinstance(s, SymInt) and not s.node.is_nested_int()
187
+
188
+ return [(i, s) for i, s in enumerate(lst) if symint_check(s)]
189
+
190
+
191
+ def compute_symint_placeholders(lst: Iterable[Union[None, int, SymInt]]) -> list[bool]:
192
+ # Non-nested symints are replaced with None in `make_runtime_safe()`
193
+ return [s is None for s in lst]
194
+
195
+
196
+ # Intended to make it easier to define function that is
197
+ # either (AOTInput -> AOTInput) or (AOTOutput -> AOTOutput)
198
+ # but not the other combos
199
+ AOTDescriptor = TypeVar("AOTDescriptor", AOTInput, AOTOutput)
200
+
201
+
202
+ # This function takes in a pytree of arguments and unwraps any tensor
203
+ # subclasses.
204
+ #
205
+ # NOTE: The reason for "append_symints":
206
+ #
207
+ # * At compile time: we append extra symint args when unwrapping primals
208
+ # (but not tangents, because they should always share symints with primals).
209
+ # We also append extra symints when unwrapping the subclass outputs of the
210
+ # traced function, so we can return them as extra outputs
211
+ #
212
+ # * At runtime: we similarly append subclass sizes when we unwrap subclass
213
+ # primals (but not tangents) on entry to the forward. See the runtime version of
214
+ # this function below.
215
+ def unwrap_tensor_subclasses(
216
+ wrapped_args: list[FxValue],
217
+ wrapped_args_descs: list[AOTDescriptor],
218
+ *,
219
+ append_symints: bool,
220
+ ) -> tuple[list[FxValue], list[AOTDescriptor]]:
221
+ def flatten_subclass(
222
+ t: FxValue,
223
+ desc: AOTDescriptor,
224
+ *,
225
+ out: tuple[list[FxValue], list[AOTDescriptor]],
226
+ ):
227
+ # unwrap a subclass into plain tensors and their size/stride if "append_symint"
228
+ # is True
229
+ if not is_traceable_wrapper_subclass(t):
230
+ out[0].append(t)
231
+ out[1].append(desc)
232
+ return
233
+
234
+ attrs, _ = t.__tensor_flatten__()
235
+
236
+ for attr in attrs:
237
+ inner_tensor = getattr(t, attr)
238
+ n_desc: Any = (
239
+ SubclassGetAttrAOTInput(desc, attr)
240
+ if isinstance(desc, AOTInput)
241
+ else SubclassGetAttrAOTOutput(desc, attr)
242
+ )
243
+ flatten_subclass(inner_tensor, n_desc, out=out)
244
+
245
+ if append_symints:
246
+ sizes = enumerate_filter_symints(t.size())
247
+ strides = enumerate_filter_symints(t.stride())
248
+ out[0].extend(s for _, s in sizes)
249
+ out[0].extend(s for _, s in strides)
250
+ if isinstance(desc, AOTInput):
251
+ out[1].extend(SubclassSizeAOTInput(desc, i) for i, _ in sizes) # type: ignore[misc]
252
+ out[1].extend(SubclassStrideAOTInput(desc, i) for i, _ in strides) # type: ignore[misc]
253
+ else:
254
+ out[1].extend(SubclassSizeAOTOutput(desc, i) for i, _ in sizes) # type: ignore[misc]
255
+ out[1].extend(SubclassStrideAOTOutput(desc, i) for i, _ in strides) # type: ignore[misc]
256
+
257
+ xs_inner: list[FxValue] = []
258
+ descs_inner: list[AOTDescriptor] = []
259
+
260
+ for x, desc in zip(wrapped_args, wrapped_args_descs):
261
+ flatten_subclass(typing.cast(Tensor, x), desc, out=(xs_inner, descs_inner))
262
+
263
+ return xs_inner, descs_inner
264
+
265
+
266
+ # subclass_metas is needed at runtime to compute which indices are symints in
267
+ # the outer_size/outer_stride
268
+ def runtime_unwrap_tensor_subclasses(
269
+ wrapped_args: list[Union[Tensor, int]],
270
+ *,
271
+ append_symints: bool,
272
+ subclass_metas: Optional[list[Union[PlainTensorMeta, SubclassCreationMeta]]] = None,
273
+ ):
274
+ def flatten_subclass(x: Tensor, meta: Optional[SubclassCreationMeta], *, out):
275
+ if not is_traceable_wrapper_subclass(x):
276
+ out.append(x)
277
+ return out
278
+
279
+ assert isinstance(x, Tensor)
280
+
281
+ attrs, _ = x.__tensor_flatten__()
282
+
283
+ for attr in attrs:
284
+ inner_tensor = getattr(x, attr)
285
+ inner_meta = meta.attrs.get(attr)
286
+ flatten_subclass(inner_tensor, inner_meta, out=out)
287
+
288
+ if append_symints:
289
+ assert isinstance(meta, SubclassCreationMeta)
290
+ # outer_size
291
+ size = x.size()
292
+ symint_placeholders = compute_symint_placeholders(meta.outer_size)
293
+ assert len(size) == len(symint_placeholders)
294
+ out.extend(
295
+ [r for (r, is_symint) in zip(size, symint_placeholders) if is_symint]
296
+ )
297
+
298
+ # outer_stride
299
+ stride = x.stride()
300
+ symint_placeholders = compute_symint_placeholders(meta.outer_stride)
301
+ assert len(stride) == len(symint_placeholders)
302
+ out.extend(
303
+ [r for (r, is_symint) in zip(stride, symint_placeholders) if is_symint]
304
+ )
305
+ return out
306
+
307
+ xs_inner: list[Union[int, Tensor, SymInt]] = []
308
+
309
+ if append_symints:
310
+ assert subclass_metas is not None
311
+
312
+ for idx, x in enumerate(wrapped_args):
313
+ if not is_traceable_wrapper_subclass(x):
314
+ xs_inner.append(x)
315
+ continue
316
+
317
+ if subclass_metas is None:
318
+ get_plain_tensors(typing.cast(Tensor, x), out=xs_inner)
319
+ else:
320
+ meta = subclass_metas[idx]
321
+ assert isinstance(meta, SubclassCreationMeta)
322
+ flatten_subclass(typing.cast(Tensor, x), meta, out=xs_inner)
323
+
324
+ return xs_inner
325
+
326
+
327
+ def unwrap_tensor_subclasses_with_indices_to_original(wrapped_args):
328
+ ret_unwrapped = []
329
+ ret_indices_to_original = []
330
+ for i, a in enumerate(wrapped_args):
331
+ a_unwrapped, _ = unwrap_tensor_subclasses(
332
+ [a], [DummyAOTInput(9999)], append_symints=False
333
+ )
334
+ ret_unwrapped.extend(a_unwrapped)
335
+ n = len(a_unwrapped)
336
+ ret_indices_to_original.extend([i] * n)
337
+
338
+ return ret_unwrapped, ret_indices_to_original
339
+
340
+
341
+ def remap_unwrapped_subclass_arg_indices(wrapped_args, static_input_indices):
342
+ static_input_indices = set(static_input_indices)
343
+ new_ind = 0
344
+ remapped_static_indices = []
345
+ for i, arg in enumerate(wrapped_args):
346
+ num_indices = 1
347
+ if is_traceable_wrapper_subclass(arg):
348
+ num_indices = (
349
+ len(get_plain_tensors(typing.cast(Tensor, arg), out=[]))
350
+ + len(enumerate_filter_symints(arg.size()))
351
+ + len(enumerate_filter_symints(arg.stride()))
352
+ )
353
+
354
+ for _ in range(num_indices):
355
+ if i in static_input_indices:
356
+ remapped_static_indices.append(new_ind)
357
+
358
+ new_ind += 1
359
+
360
+ return remapped_static_indices
361
+
362
+
363
+ # Turns a flattened list of tensor arguments into (maybe) subclass tensors.
364
+ # This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in.
365
+ def wrap_tensor_subclasses(
366
+ unwrapped_args: Union[tuple[Any, ...], list[Any]],
367
+ *,
368
+ subclass_metas: list[Union[PlainTensorMeta, SubclassCreationMeta]],
369
+ num_fw_outs_saved_for_bw: Optional[int] = None,
370
+ included_subclass_symints: bool = False,
371
+ is_runtime: bool = False,
372
+ make_subclass_override: Optional[Callable] = None,
373
+ ) -> tuple[Any, ...]:
374
+ wrapped_args = []
375
+ num_args_tallied = 0
376
+ for subclass_meta in subclass_metas:
377
+ if isinstance(subclass_meta, PlainTensorMeta):
378
+ wrapped_args.append(unwrapped_args[subclass_meta.unwrapped_idx])
379
+ num_args_tallied += 1
380
+ else:
381
+ assert isinstance(subclass_meta, SubclassCreationMeta)
382
+ assert subclass_meta.included_subclass_symints == included_subclass_symints
383
+
384
+ if make_subclass_override:
385
+ wrapped_args.append(
386
+ make_subclass_override(subclass_meta, is_runtime, unwrapped_args)
387
+ )
388
+ else:
389
+ wrapped_args.append(
390
+ subclass_meta.creation_fn(unwrapped_args, is_runtime=is_runtime)
391
+ )
392
+ num_args_tallied += subclass_meta.arg_count
393
+
394
+ # Note: [Partitioner handling for Subclasses, Part 2]
395
+ # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw,
396
+ # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them.
397
+ #
398
+ # When this function is called at runtime in the forward,
399
+ # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs.
400
+ #
401
+ # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen?
402
+ # Answer: we do it **inside of our compiled autograd.Function**.
403
+ # This seems like morally the right place: autograd happens above subclass desugaring,
404
+ # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors.
405
+ #
406
+ # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph
407
+ # into a forward and backward graph, we end up with some activations that show up as extra outputs
408
+ # in the compiled forward graph, that are **not** user outputs.
409
+ # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses.
410
+ #
411
+ # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`),
412
+ # we computed subclass metadata on every forward output, but this did **not** include activations
413
+ # created by the partitioner.
414
+ # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations),
415
+ # but `subclass_metas` will only correspond to subclass metadata on `user_fw_outs`.
416
+ # We then need to make sure that we return (*wrapped_user_fw_outs, *activations).
417
+ if num_fw_outs_saved_for_bw is not None:
418
+ assert len(unwrapped_args) == num_args_tallied + num_fw_outs_saved_for_bw, (
419
+ f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal "
420
+ f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of "
421
+ f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})"
422
+ )
423
+ activations = unwrapped_args[num_args_tallied:]
424
+ if isinstance(wrapped_args, tuple) and isinstance(activations, tuple):
425
+ return wrapped_args + activations
426
+ return tuple(list(wrapped_args) + list(activations))
427
+ else:
428
+ assert len(unwrapped_args) == num_args_tallied, (
429
+ f"Expected {len(unwrapped_args)} == {num_args_tallied}"
430
+ )
431
+ return tuple(wrapped_args)
432
+
433
+
434
+ # Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses.
435
+ # This function carefully handles the inference vs. joint cases:
436
+ # - when is_joint_structure is True, args is (primals, tangents)
437
+ # - when is_joint_structure is False, args is [*primals]
438
+ def wrap_tensor_subclasses_maybe_joint(
439
+ unwrapped_args, *, is_joint_structure: bool, meta: ViewAndMutationMeta
440
+ ) -> Union[tuple[Any, ...], list[Any]]:
441
+ # Since this function is reused for both inference and joint graphs,
442
+ if is_joint_structure:
443
+ assert isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2
444
+ assert isinstance(unwrapped_args[0], (tuple, list)) and isinstance(
445
+ unwrapped_args[1], (tuple, list)
446
+ )
447
+ primals, tangents = unwrapped_args[0], unwrapped_args[1]
448
+ wrapped_primals = wrap_tensor_subclasses(
449
+ primals,
450
+ subclass_metas=meta.subclass_inp_meta,
451
+ included_subclass_symints=True,
452
+ )
453
+ wrapped_tangents = wrap_tensor_subclasses(
454
+ tangents,
455
+ subclass_metas=meta.subclass_tangent_meta,
456
+ included_subclass_symints=False,
457
+ )
458
+ return (wrapped_primals, wrapped_tangents)
459
+ else:
460
+ wrapped_args = wrap_tensor_subclasses(
461
+ unwrapped_args,
462
+ subclass_metas=meta.subclass_inp_meta,
463
+ included_subclass_symints=True,
464
+ )
465
+ return wrapped_args
466
+
467
+
468
+ def compute_inner_mutated_inp_indices_from_subclass_meta(
469
+ fw_metadata: ViewAndMutationMeta,
470
+ inner_metadata: ViewAndMutationMeta,
471
+ ) -> list[int]:
472
+ # Note: [Recomputing subclass mutation handling]
473
+ #
474
+ # Generally, if a subclass requires grad, its components will not require grad.
475
+ # But for the purposes of tracking returned tensors, we should treat those component
476
+ # tensors as if they require grad.
477
+ #
478
+ # For example, if the subclass tensor requires grad and will be mutated in a way that
479
+ # requires us to handle the mutation outside of the graph, we need to return it
480
+ # from the forward graph. The inner_meta data won't consider the component tensors
481
+ # as if they need to be returned, because they don't require grad; but really, we
482
+ # should handle those tensors the same way we handle the subclass tensor itself; i.e.
483
+ # if we'd include the subclass tensor as part of the outputs, then we should also
484
+ # include the component tensors.
485
+ #
486
+ # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs
487
+ # from the outer subclass tensors and propagating
488
+
489
+ updated_input_info = []
490
+ inner_idx = 0
491
+ if not fw_metadata.subclass_inp_meta:
492
+ # Sometimes we don't have subclass info, e.g. synthetic_base codepaths
493
+ return inner_metadata.mutated_inp_runtime_indices
494
+ assert len(fw_metadata.subclass_inp_meta) == len(fw_metadata.input_info)
495
+ for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta):
496
+ if isinstance(inp_meta, PlainTensorMeta):
497
+ assert outer_idx < len(fw_metadata.input_info)
498
+ if inner_metadata is not None:
499
+ assert inner_idx < len(inner_metadata.input_info)
500
+ assert (
501
+ inner_metadata.input_info[inner_idx]
502
+ == fw_metadata.input_info[outer_idx]
503
+ )
504
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
505
+ inner_idx += 1
506
+ else:
507
+ assert inp_meta.original_subclass is not None
508
+ for _ in range(inp_meta.arg_count):
509
+ updated_input_info.append(fw_metadata.input_info[outer_idx])
510
+ inner_idx += 1
511
+ if inner_metadata is not None:
512
+ assert len(inner_metadata.input_info) == len(updated_input_info)
513
+
514
+ return [
515
+ i
516
+ for i, inp in enumerate(updated_input_info)
517
+ if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH
518
+ ]
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/_aot_autograd/utils.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, TypeVar, Union
12
+ from typing_extensions import ParamSpec
13
+
14
+ import torch
15
+ import torch.utils._pytree as pytree
16
+ from torch._library.fake_class_registry import FakeScriptObject
17
+ from torch._logging import getArtifactLogger
18
+ from torch._subclasses.fake_tensor import FakeTensor
19
+ from torch._subclasses.functional_tensor import FunctionalTensor
20
+ from torch.fx.experimental._backward_state import BackwardState
21
+ from torch.fx.experimental.proxy_tensor import py_sym_types
22
+
23
+ from .descriptors import AOTOutput
24
+
25
+
26
+ KNOWN_TYPES = [
27
+ torch.Tensor,
28
+ BackwardState,
29
+ int,
30
+ str,
31
+ float,
32
+ bool,
33
+ type(None),
34
+ *py_sym_types,
35
+ FakeScriptObject,
36
+ torch.ScriptObject,
37
+ ]
38
+
39
+ original_zip = zip
40
+
41
+ aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects")
42
+
43
+
44
+ def strict_zip(*iterables, strict=True, **kwargs):
45
+ if not strict:
46
+ return original_zip(*iterables, **kwargs)
47
+
48
+ length = len(iterables[0])
49
+ for iterable in iterables[1:]:
50
+ if len(iterable) != length:
51
+ raise ValueError(
52
+ "The iterables have different lengths and strict mode is enabled."
53
+ )
54
+
55
+ return original_zip(*iterables, **kwargs)
56
+
57
+
58
+ def _get_symint_hints(exprs):
59
+ """
60
+ Get the hints of a list/tuple of int/SymInt.
61
+ """
62
+ if isinstance(exprs, (list, tuple)):
63
+ return type(exprs)(_get_symint_hints(e) for e in exprs)
64
+ elif isinstance(exprs, torch.SymInt):
65
+ return exprs.node.shape_env.size_hint(exprs.node.expr)
66
+ else:
67
+ return exprs
68
+
69
+
70
+ def partial_flatten_asdict(obj: Any) -> Any:
71
+ if dataclasses.is_dataclass(obj):
72
+ return {
73
+ field.name: getattr(obj, field.name) for field in dataclasses.fields(obj)
74
+ }
75
+ elif isinstance(obj, (list, tuple)):
76
+ return obj.__class__([partial_flatten_asdict(item) for item in obj])
77
+ elif isinstance(obj, dict):
78
+ return {k: partial_flatten_asdict(v) for k, v in obj.items()}
79
+ else:
80
+ return obj
81
+
82
+
83
+ def normalize_as_list(x):
84
+ if isinstance(x, tuple):
85
+ return list(x)
86
+ elif isinstance(x, list):
87
+ return x
88
+ return [x]
89
+
90
+
91
+ def _get_autocast_states():
92
+ return [
93
+ torch.is_autocast_enabled("cuda"),
94
+ torch.is_autocast_enabled("cpu"),
95
+ torch.get_autocast_dtype("cuda"),
96
+ torch.get_autocast_dtype("cpu"),
97
+ torch.is_autocast_cache_enabled(),
98
+ ]
99
+
100
+
101
+ def make_boxed_func(f):
102
+ def g(args):
103
+ return f(*args)
104
+
105
+ g._boxed_call = True # type: ignore[attr-defined]
106
+ return g
107
+
108
+
109
+ def make_boxed_compiler(compiler):
110
+ @wraps(compiler)
111
+ def f(fx_g, inps):
112
+ out_f = compiler(fx_g, inps)
113
+ fx_g = make_boxed_func(out_f)
114
+ return fx_g
115
+
116
+ return f
117
+
118
+
119
+ def call_func_at_runtime_with_args(
120
+ f, args: Union[tuple[Any], list[Any]], steal_args=False, disable_amp=False
121
+ ):
122
+ if not steal_args:
123
+ args = list(args)
124
+ assert isinstance(args, list)
125
+
126
+ context = torch._C._DisableAutocast if disable_amp else nullcontext
127
+ with context():
128
+ if getattr(f, "_boxed_call", False):
129
+ out = normalize_as_list(f(args))
130
+ else:
131
+ # TODO: Please remove soon
132
+ # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670
133
+ warnings.warn(
134
+ "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. "
135
+ "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. "
136
+ "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale."
137
+ )
138
+ out = normalize_as_list(f(*args))
139
+ return out
140
+
141
+
142
+ # Inspired by autodidax (thanks!)
143
+ class PytreeThunk:
144
+ spec: Optional[pytree.TreeSpec] = None
145
+ # These are some kinda dumb microoptimizations that save about 3-4 us of overhead.
146
+ is_simple: Optional[bool] = (
147
+ None # if the output spec is a tuple/list, we won't bother unflattening it.
148
+ )
149
+ is_really_simple: Optional[bool] = None # if the output spec is a LeafSpec
150
+
151
+ def set(self, spec: pytree.TreeSpec) -> None:
152
+ assert self.spec is None or self.spec == spec
153
+ assert spec is not None
154
+ self.spec: pytree.TreeSpec = spec
155
+ if self.spec.type in {tuple, list} and all(
156
+ child.is_leaf() for child in spec.children_specs
157
+ ):
158
+ self.is_simple = True
159
+ if self.spec.is_leaf():
160
+ self.is_really_simple = True
161
+
162
+ def unflatten(self, x: list[Any]) -> Any:
163
+ if self.is_really_simple:
164
+ return x[0]
165
+ if self.is_simple:
166
+ return x
167
+ assert self.spec is not None
168
+ return pytree.tree_unflatten(x, self.spec)
169
+
170
+
171
+ # Creates a function that returns flattened inputs and outputs
172
+ # Also returns the output tree spec, which is needed to recover the "unflattened"
173
+ # output tree structure later.
174
+ def create_tree_flattened_fn(fn, args, kwargs=None) -> tuple[Callable, PytreeThunk]:
175
+ if kwargs is None:
176
+ kwargs = {}
177
+ # Save the args_spec for flat_tensor_args to unflatten while tracing
178
+ _, tensor_args_spec = pytree.tree_flatten((args, kwargs))
179
+ out_spec = PytreeThunk()
180
+
181
+ def flat_fn(*flat_args):
182
+ # The input are flattened tensor args. Prepare the args in the
183
+ # order that original function expects. Add static args as well.
184
+ # They will appear as tensor constants in the traced graph.
185
+ nonlocal out_spec
186
+ args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec)
187
+ tree_out = fn(*args, **kwargs)
188
+ flat_out, spec = pytree.tree_flatten(tree_out)
189
+ for i in flat_out:
190
+ is_known_type = False
191
+ for j in KNOWN_TYPES:
192
+ if isinstance(i, j):
193
+ is_known_type = True
194
+ break
195
+ if not is_known_type:
196
+ raise RuntimeError(
197
+ f"Found {type(i)} in output, which is not a known type. "
198
+ "If this type holds tensors, you need to register a pytree for it. "
199
+ "See https://github.com/pytorch/functorch/issues/475 for a brief "
200
+ "explanation why. If you don't need to register a pytree, please "
201
+ "leave a comment explaining your use case and we'll make this more "
202
+ "ergonomic to deal with"
203
+ )
204
+ out_spec.set(spec)
205
+ return flat_out
206
+
207
+ # Can't use functools.wraps here because the wrapper has different
208
+ # calling convention
209
+ if hasattr(fn, "_orig_mod"):
210
+ flat_fn._orig_mod = fn._orig_mod # type: ignore[attr-defined]
211
+
212
+ return flat_fn, out_spec
213
+
214
+
215
+ # This function takes in a tensor t, and returns one of t, t.view(), or t.clone().
216
+ # When tracing the joint forward + backward, for any inputs in the graph that are mutated,
217
+ # we need to clone them first (and similarly for metadata-only mutations, we need to view them first).
218
+ # The idea is that when we trace the backward, we need to pass in the *original* primals
219
+ # to autograd.grad(), before they were mutated.
220
+ # Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them.
221
+ # This means that "idx" here represents the index of the (potentially) synthetic base.
222
+ # What we need to do is:
223
+ # (1) map the current (post-synthetic-base calling convention) input argument index
224
+ # to int index pre-synthetic-base-calling-convention.
225
+ # (2) There could be multiple, if this index corresponds to a synthetic base
226
+ # that has multiple input aliases.
227
+ # (3) If any of those corresponding inputs get metadata mutations, then we clone the base.
228
+ def maybe_to_fresh_input(idx, t, meta):
229
+ if not isinstance(t, torch.Tensor):
230
+ return t
231
+ if idx in meta.mutated_inp_runtime_indices:
232
+ # We only need to bother cloning mutated inputs that participate in autograd.
233
+ if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data:
234
+ # Make sure the primal we pass to autograd.grad()
235
+ # sees the tensor before the mutation
236
+ return t.clone()
237
+ if meta.input_info[idx] and meta.input_info[idx].mutates_metadata:
238
+ # Make sure the primal we pass to autograd.grad()
239
+ # sees the tensor before the metadata mutation
240
+ return t.view(t.shape)
241
+ return t
242
+
243
+
244
+ def is_with_effects(node):
245
+ return (
246
+ node.op == "call_function"
247
+ and node.target == torch.ops.higher_order.with_effects
248
+ )
249
+
250
+
251
+ def is_with_effects_op(node, op):
252
+ return is_with_effects(node) and node.args[1] == op
253
+
254
+
255
+ def unlift_tokens(fw_module, fw_metadata, aot_config, bw_module=None):
256
+ # Remove the tokens from the inputs/outputs of the graph since inductor does
257
+ # not want these extra inputs/outputs, and replace them with
258
+ # _make_token() to create a token, and _sink_tokens() to collect the
259
+ # tokens. See Note [Side-Effectful Tokens in AOTAutograd]
260
+ # Logic:
261
+ # 1. Inputs identified as input tokens:
262
+ # - If used as a first argument in with_effects
263
+ #
264
+ # 2. Outputs identified as output tokens:
265
+ # - If Produced by getitem(with_effects, 0)
266
+ #
267
+ # 3. Checks invariants of number input output tokens:
268
+ # forward:
269
+ # expected_num_erased_inputs == len(fw_metadata.tokens)
270
+ # expected_num_erased_outputs == len(fw_metadata.tokens)
271
+ # backward:
272
+ # expected_num_erased_inputs == fw_metadata.num_backward_tokens
273
+ # expected_num_erased_outputs == fw_metadata.num_backward_tokens
274
+ num_forward_tokens = len(fw_metadata.tokens)
275
+ num_backward_tokens = fw_metadata.num_backward_tokens
276
+
277
+ def rewrite_with_effects_input_token(module, node):
278
+ with module.graph.inserting_before(node):
279
+ new_token_node = module.graph.call_function(
280
+ torch.ops.prims._make_token.default, ()
281
+ )
282
+ new_token_node.meta["val"] = torch.tensor([])
283
+ new_token_node.meta["tensor_meta"] = torch.tensor([])
284
+
285
+ args = list(node.args)
286
+ args[0] = new_token_node
287
+ node.args = tuple(args)
288
+
289
+ def rewrite_output(module, node, output_token_nodes, other_output_args):
290
+ for output_token_node in output_token_nodes:
291
+ assert (
292
+ output_token_node.op == "call_function"
293
+ and output_token_node.target == operator.getitem
294
+ and output_token_node.args[1] == 0
295
+ )
296
+ with module.graph.inserting_before(node):
297
+ module.graph.call_function(
298
+ torch.ops.prims._sink_tokens.default,
299
+ (output_token_nodes,),
300
+ )
301
+ node.args = (other_output_args,)
302
+
303
+ def do(module, subgraph, expected_num_erased):
304
+ num_erased_inputs = 0
305
+ num_erased_outs = 0
306
+ input_nodes = []
307
+ input_token_nodes = set()
308
+ with_effect_nodes = []
309
+ output_token_nodes = []
310
+ other_output_nodes = []
311
+ for node in module.graph.nodes:
312
+ if node.op == "placeholder":
313
+ input_nodes.append(node)
314
+ elif is_with_effects(node):
315
+ with_effect_nodes.append(node)
316
+ if node.args[0] in input_nodes:
317
+ input_token_nodes.add(node.args[0])
318
+ rewrite_with_effects_input_token(module, node)
319
+ elif node.op == "output":
320
+ outs = node.args[0]
321
+ for out in outs:
322
+ if (
323
+ isinstance(out, torch.fx.node.Node)
324
+ and out.op == "call_function"
325
+ and out.target == operator.getitem
326
+ and out.args[1] == 0
327
+ and out.args[0] in with_effect_nodes
328
+ ):
329
+ output_token_nodes.append(out)
330
+ else:
331
+ other_output_nodes.append(out)
332
+
333
+ rewrite_output(module, node, output_token_nodes, other_output_nodes)
334
+ num_erased_outs = len(output_token_nodes)
335
+
336
+ for input_token_node in input_token_nodes:
337
+ module.graph.erase_node(input_token_node)
338
+
339
+ num_erased_inputs = len(input_token_nodes)
340
+
341
+ assert num_erased_inputs == expected_num_erased, (
342
+ f"{subgraph} num_erased_inputs:{num_erased_inputs} {input_token_nodes}!=expected {expected_num_erased}"
343
+ )
344
+ assert num_erased_outs == expected_num_erased, (
345
+ f"{subgraph} num_erased_outs:{num_erased_outs} {output_token_nodes}!=expected {expected_num_erased}"
346
+ )
347
+
348
+ module.recompile()
349
+
350
+ if num_forward_tokens > 0:
351
+ if aot_config.enable_log:
352
+ from torch._dynamo.utils import lazy_format_graph_code
353
+
354
+ aot_graphs_effects_log.debug(
355
+ "%s",
356
+ lazy_format_graph_code(
357
+ "Forward graph before unlifting tokens",
358
+ fw_module,
359
+ aot_config.aot_id,
360
+ include_stride=True,
361
+ include_device=True,
362
+ colored=True,
363
+ ),
364
+ )
365
+ do(
366
+ fw_module,
367
+ "forward",
368
+ num_forward_tokens,
369
+ )
370
+
371
+ if bw_module is not None and num_backward_tokens > 0:
372
+ if aot_config.enable_log:
373
+ from torch._dynamo.utils import lazy_format_graph_code
374
+
375
+ aot_graphs_effects_log.debug(
376
+ "%s",
377
+ lazy_format_graph_code(
378
+ "Backward graph before unlifting tokens",
379
+ bw_module,
380
+ aot_config.aot_id,
381
+ include_stride=True,
382
+ include_device=True,
383
+ colored=True,
384
+ ),
385
+ )
386
+ do(bw_module, "backward", num_backward_tokens)
387
+
388
+ # This is sad, but we need to update the metadata to get rid of
389
+ # the tokens.
390
+ fw_metadata.tokens = {}
391
+ fw_metadata.num_backward_tokens = 0
392
+
393
+
394
+ def root_module_when_exporting_non_strict(flat_fn):
395
+ # When exporting in non-strict mode, we wrap the root module in a specific pattern.
396
+ # See `_aot_export_non_strict` in torch.export._trace.py.
397
+ # We look for that wrapping pattern here.
398
+ if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"):
399
+ return flat_fn._orig_mod._export_root
400
+ else:
401
+ return None
402
+
403
+
404
+ def copy_fwd_metadata_to_bw_nodes(fx_g):
405
+ """
406
+ Input: `fx_g` which contains the joint fwd+bwd FX graph created by
407
+ aot_autograd.
408
+
409
+ This function walks the graph and copies over metadata from forward nodes
410
+ to backward nodes, using the `seq_nr` field as a one-to-many mapping
411
+ from forward node to backward node. This metadata is useful for performance
412
+ profiling and debugging.
413
+ """
414
+
415
+ def _is_forward_node_with_seq_nr(node):
416
+ # For now, assume that if nn_module_stack_metadata is populated, this
417
+ # node is from the forward. Ignore nodes without `seq_nr`.
418
+ # TODO(future): there is likely a less brittle way to do this by walking
419
+ # the descendants of graph inputs corresponding to fwd inputs, didn't
420
+ # seem obvious at first glance on how to partition graph inputs into
421
+ # fwd vs bwd without relying on string names.
422
+ return "nn_module_stack" in node.meta and "seq_nr" in node.meta
423
+
424
+ def _is_backward_node_with_seq_nr(node):
425
+ # For now, assume that if nn_module_stack_metadata is not populated,
426
+ # this node is from the backward. Ignore nodes without `seq_nr`.
427
+ # TODO(future): there is likely a less brittle way to do this, same
428
+ # as with the forward.
429
+ return ("nn_module_stack" not in node.meta) and "seq_nr" in node.meta
430
+
431
+ fwd_seq_nr_to_node = {}
432
+ for node in fx_g.graph.nodes:
433
+ if not _is_forward_node_with_seq_nr(node):
434
+ continue
435
+ seq_nr = node.meta["seq_nr"]
436
+ if seq_nr in fwd_seq_nr_to_node:
437
+ # If we already saw an op with the current `seq_nr`, that means
438
+ # that the current op did not create an autograd node, and there
439
+ # is no corresponding backward node, so we skip.
440
+ continue
441
+ fwd_seq_nr_to_node[node.meta["seq_nr"]] = node
442
+
443
+ for node in fx_g.graph.nodes:
444
+ if not _is_backward_node_with_seq_nr(node):
445
+ continue
446
+ # fwd_node should always exist, but handle non-existence just in case
447
+ fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"])
448
+ if fwd_node is not None:
449
+ node.meta["fwd_nn_module_stack"] = fwd_node.meta["nn_module_stack"]
450
+ node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack")
451
+
452
+
453
+ def register_buffer_assignment_hook(mod, assigned_buffers):
454
+ """
455
+ Register a hook that intercepts buffer assignments.
456
+ This is used to detect when a buffer is assigned to, and then we can
457
+ map that buffer to the corresponding proxy node in the graph.
458
+ """
459
+
460
+ def _map_assigned_buffer_to_proxy(_mod, name, buffer):
461
+ # We intercept buffer assignments on the root module through this hook.
462
+ if _mod._buffers is mod._buffers:
463
+ # either buffer is a functional tensor, which wraps a fake tensor
464
+ if isinstance(buffer, FunctionalTensor):
465
+ buffer = buffer.from_functional()
466
+ # or buffer is a fake tensor
467
+ assert isinstance(buffer, FakeTensor)
468
+ # The fake tensor in turn is associated with a proxy node.
469
+ proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode()
470
+ assert proxy_mode is not None
471
+ proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot(
472
+ buffer, proxy_mode.tracer
473
+ ).proxy.node
474
+ # We map the assigned buffer to this proxy node.
475
+ assigned_buffers[name] = proxy.name
476
+ return buffer
477
+
478
+ return torch.nn.modules.module.register_module_buffer_registration_hook(
479
+ _map_assigned_buffer_to_proxy
480
+ )
481
+
482
+
483
+ def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool:
484
+ """
485
+ Checks if the module contains any metadata mutation ops.
486
+ """
487
+ for node in module.graph.nodes:
488
+ if (
489
+ node.op == "call_function"
490
+ and hasattr(node.target, "tags")
491
+ and torch.Tag.inplace_view in node.target.tags
492
+ ):
493
+ return True
494
+ return False
495
+
496
+
497
+ def get_cuda_generator_meta_val(device_idx: int):
498
+ """
499
+ Get a generator value to use as a meta val
500
+
501
+ newly cloned generator will not contain tensors. it is only Generators that are
502
+ registered to a CUDAGraph that contain tensors. since this does not contain Tensor
503
+ it is fine to use in the meta.
504
+ """
505
+ return torch.cuda.default_generators[device_idx].clone_state()
506
+
507
+
508
+ def top_saved_tensors_hooks():
509
+ return torch._C._autograd._top_saved_tensors_default_hooks(True)
510
+
511
+
512
+ def saved_tensors_hooks_are_inlineable(hooks) -> bool:
513
+ if not hooks:
514
+ return False
515
+ pack, unpack = hooks
516
+ return isinstance(pack, torch.fx.GraphModule) and isinstance(
517
+ unpack, torch.fx.GraphModule
518
+ )
519
+
520
+
521
+ _P = ParamSpec("_P")
522
+ _T = TypeVar("_T")
523
+ _S = TypeVar("_S")
524
+
525
+
526
+ def without_output_descs(f: Callable[_P, tuple[_T, _S]]) -> Callable[_P, _T]:
527
+ @wraps(f)
528
+ @simple_wraps(f)
529
+ def inner(*args, **kwargs):
530
+ return f(*args, **kwargs)[0]
531
+
532
+ return inner
533
+
534
+
535
+ _P2 = ParamSpec("_P2")
536
+ _R = TypeVar("_R")
537
+ _R2 = TypeVar("_R2")
538
+
539
+
540
+ def simple_wraps(
541
+ f: Callable[_P, _R],
542
+ ) -> Callable[[Callable[_P2, _R2]], Callable[_P2, _R2]]:
543
+ # NB: omit ('__module__', '__name__', '__qualname__') for ease of
544
+ # debugging
545
+ return wraps(f, assigned=("__doc__", "__annotations__", "__type_params__"))
546
+
547
+
548
+ def call_and_expect_output_descs(fn, args):
549
+ outs_pair = fn(*args)
550
+ assert isinstance(outs_pair, tuple) and len(outs_pair) == 2, (fn, outs_pair)
551
+ outs, outs_descs = outs_pair
552
+ # The Tensor tests protects against the test when there are no outputs
553
+ out_vals, out_spec = pytree.tree_flatten(outs)
554
+ out_desc_vals, out_desc_spec = pytree.tree_flatten(outs_descs)
555
+ assert out_spec == out_desc_spec, (
556
+ fn_wrappers(fn),
557
+ outs,
558
+ outs_descs,
559
+ out_spec,
560
+ out_desc_spec,
561
+ )
562
+ assert not any(isinstance(x, AOTOutput) for x in out_vals), (
563
+ fn_wrappers(fn),
564
+ outs,
565
+ outs_descs,
566
+ out_vals,
567
+ )
568
+ assert all(
569
+ isinstance(d, AOTOutput)
570
+ for (x, d) in zip(out_vals, out_desc_vals)
571
+ if isinstance(x, (torch.Tensor, torch.SymInt)) or type(x) is int
572
+ ), (fn_wrappers(fn), outs, outs_descs, out_vals, out_desc_vals)
573
+ return outs_pair
574
+
575
+
576
+ def fn_wrappers(fn):
577
+ fns = [fn]
578
+ f = fn
579
+ while hasattr(f, "__wrapped__"):
580
+ f = f.__wrapped__
581
+ fns.append(f)
582
+ return fns
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/python_key.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ __all__ = ["make_fx", "dispatch_trace", "PythonKeyTracer", "pythonkey_decompose"]
7
+ from torch.fx.experimental.proxy_tensor import (
8
+ decompose,
9
+ dispatch_trace,
10
+ make_fx,
11
+ PythonKeyTracer,
12
+ )
13
+
14
+
15
+ pythonkey_decompose = decompose
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/pytree_hacks.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+
9
+ # TODO: remove this file when the migration of the pytree utility is done
10
+ from torch.utils._pytree import tree_map_, treespec_pprint
11
+
12
+
13
+ __all__ = ["tree_map_", "treespec_pprint"]
14
+
15
+
16
+ with warnings.catch_warnings():
17
+ warnings.simplefilter("always")
18
+ warnings.warn(
19
+ "`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. "
20
+ "Please `use torch.utils._pytree` instead.",
21
+ DeprecationWarning,
22
+ stacklevel=2,
23
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/top_operators_github_usage.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """
4
+ From https://docs.google.com/spreadsheets/d/12R3nCOLskxPYjjiNkdqy4OdQ65eQp_htebXGODsjSeA/edit#gid=0
5
+ Try to keep this list in sync with that.
6
+ """
7
+
8
+ import operator
9
+
10
+
11
+ top_torch = [
12
+ ("t", 6837449),
13
+ ("tensor", 585786),
14
+ ("mode", 462182),
15
+ ("cat", 394818),
16
+ ("max", 368038),
17
+ ("zeros", 329495),
18
+ ("load", 327756),
19
+ ("no_grad", 294694),
20
+ ("save", 265130),
21
+ ("from_numpy", 243063),
22
+ ("manual_seed", 165044),
23
+ ("ones", 153696),
24
+ ("randn", 150796),
25
+ ("stack", 133358),
26
+ ("sum", 130772),
27
+ ("arange", 98087),
28
+ ("rand", 94715),
29
+ ("mean", 88546),
30
+ ("exp", 73883),
31
+ ("zeros_like", 72831),
32
+ ("min", 72248),
33
+ ("sigmoid", 66798),
34
+ ("log", 62135),
35
+ ("matmul", 47811),
36
+ ("clamp", 45304),
37
+ ("sqrt", 44911),
38
+ ("abs", 43535),
39
+ ("tanh", 42793),
40
+ ("empty", 40311),
41
+ ("argmax", 38435),
42
+ ("bmm", 33984),
43
+ ("pow", 33571),
44
+ ("norm", 31125),
45
+ ("mm", 30995),
46
+ ("is_tensor", 29546),
47
+ ("ones_like", 29512),
48
+ ("nonzero", 28681),
49
+ ("full", 28373),
50
+ ("unsqueeze", 27911),
51
+ ("where", 26585),
52
+ ("randperm", 26450),
53
+ ("eye", 24342),
54
+ ("mul", 23236),
55
+ ("topk", 22537),
56
+ ("as_tensor", 21967),
57
+ ("sort", 21412),
58
+ ("squeeze", 20863),
59
+ ("randint", 20771),
60
+ ("linspace", 20041),
61
+ ("add", 19201),
62
+ ("transpose", 18663),
63
+ ("split", 18325),
64
+ ("gather", 17904),
65
+ ("set_grad_enabled", 16013),
66
+ ("sin", 15669),
67
+ ("cos", 15562),
68
+ ("div", 15513),
69
+ ("index_select", 14866),
70
+ ("multinomial", 14331),
71
+ ("flatten", 14267),
72
+ ("isnan", 14170),
73
+ ("randn_like", 13096),
74
+ ("eq", 12680),
75
+ ("einsum", 12480),
76
+ ("round", 12367),
77
+ ("floor", 11628),
78
+ ("allclose", 11000),
79
+ ("reshape", 10605),
80
+ ("diag", 10167),
81
+ ("chunk", 9581),
82
+ ("std", 9379),
83
+ ("set_default_tensor_type", 9281),
84
+ ("triu", 8559),
85
+ ("meshgrid", 8292),
86
+ ("set_num_threads", 8126),
87
+ ("unique", 7964),
88
+ ("full_like", 7780),
89
+ ("tril", 7538),
90
+ ("dot", 7275),
91
+ ("sign", 6943),
92
+ ("equal", 6916),
93
+ ("normal", 6750),
94
+ ("cumsum", 6556),
95
+ ("dist", 6058),
96
+ ("isfinite", 6030),
97
+ ("gt", 5935),
98
+ ("set_printoptions", 5888),
99
+ ("range", 5491),
100
+ ("empty_like", 5351),
101
+ ("flip", 5342),
102
+ ("masked_select", 5341),
103
+ ("bernoulli", 5262),
104
+ ("atan", 5253),
105
+ ("var", 5247),
106
+ ("prod", 5200),
107
+ ("erf", 5088),
108
+ ("inverse", 5072),
109
+ ("addmm", 4854),
110
+ ("logsumexp", 4582),
111
+ ("fft", 4436),
112
+ ("lt", 4421),
113
+ ("log2", 4316),
114
+ ("enable_grad", 4238),
115
+ ("rand_like", 4187),
116
+ ("argsort", 3972),
117
+ ("seed", 3932),
118
+ ("mv", 3547),
119
+ ("ger", 3309),
120
+ ("ge", 3248),
121
+ ("atan2", 3210),
122
+ ("ceil", 3202),
123
+ ("ne", 3075),
124
+ ("bincount", 3063),
125
+ ("acos", 3055),
126
+ ("rsqrt", 3031),
127
+ ("svd", 3029),
128
+ ("numel", 3003),
129
+ ("log1p", 2840),
130
+ ("unbind", 2808),
131
+ ("le", 2714),
132
+ ("isinf", 2707),
133
+ ("cross", 2646),
134
+ ("set_default_dtype", 2536),
135
+ ("argmin", 2535),
136
+ ("sparse_coo_tensor", 2489),
137
+ ("log10", 2304),
138
+ ("kthvalue", 2192),
139
+ ("set_rng_state", 2158),
140
+ ("get_rng_state", 1996),
141
+ ("get_default_dtype", 1879),
142
+ ("det", 1868),
143
+ ("qr", 1864),
144
+ ("histc", 1852),
145
+ ("symeig", 1832),
146
+ ("trace", 1801),
147
+ ("median", 1795),
148
+ ("addcmul", 1751),
149
+ ("remainder", 1717),
150
+ ("baddbmm", 1693),
151
+ ("lgamma", 1665),
152
+ ("repeat_interleave", 1598),
153
+ ("fmod", 1576),
154
+ ("reciprocal", 1575),
155
+ ("tan", 1560),
156
+ ("initial_seed", 1532),
157
+ ("take", 1529),
158
+ ("stft", 1487),
159
+ ("get_num_threads", 1477),
160
+ ("real", 1459),
161
+ ("cholesky", 1406),
162
+ ("quantize_per_tensor", 1392),
163
+ ("diag_embed", 1364),
164
+ ("lerp", 1363),
165
+ ("asin", 1345),
166
+ ("eig", 1333),
167
+ ("trunc", 1290),
168
+ ("diagonal", 1287),
169
+ ("cosh", 1279),
170
+ ("rfft", 1269),
171
+ ("cumprod", 1260),
172
+ ("addr", 1211),
173
+ ("roll", 1198),
174
+ ("narrow", 1188),
175
+ ("digamma", 1172),
176
+ ("square", 1163),
177
+ ("sinh", 1131),
178
+ ("logspace", 1084),
179
+ ("broadcast_tensors", 1070),
180
+ ("irfft", 1013),
181
+ ("frac", 997),
182
+ ("hann_window", 994),
183
+ ("solve", 989),
184
+ ("logdet", 977),
185
+ ("expm1", 968),
186
+ ("cdist", 946),
187
+ ("addmv", 903),
188
+ ("randint_like", 888),
189
+ ("tensordot", 888),
190
+ ("ifft", 877),
191
+ ("true_divide", 854),
192
+ ("erfinv", 830),
193
+ ("addcdiv", 819),
194
+ ("addbmm", 813),
195
+ ("renorm", 781),
196
+ ("pinverse", 753),
197
+ ("isclose", 740),
198
+ ("erfc", 729),
199
+ ("is_storage", 725),
200
+ ("triangular_solve", 723),
201
+ ("rot90", 709),
202
+ ("logical_not", 686),
203
+ ("geqrf", 681),
204
+ ("slogdet", 677),
205
+ ("lu", 665),
206
+ ("hamming_window", 659),
207
+ ("orgqr", 651),
208
+ ("ormqr", 622),
209
+ ("is_floating_point", 602),
210
+ ("diagflat", 562),
211
+ ("cholesky_solve", 559),
212
+ ("tril_indices", 552),
213
+ ("chain_matmul", 551),
214
+ ("triu_indices", 548),
215
+ ("angle", 522),
216
+ ("poisson", 505),
217
+ ("matrix_power", 485),
218
+ ("unique_consecutive", 471),
219
+ ("quantize_per_channel", 465),
220
+ ("std_mean", 458),
221
+ ("bartlett_window", 447),
222
+ ("var_mean", 428),
223
+ ("lstsq", 421),
224
+ ("logical_and", 419),
225
+ ("mvlgamma", 411),
226
+ ("blackman_window", 400),
227
+ ("bitwise_not", 395),
228
+ ("cholesky_inverse", 388),
229
+ ("as_strided", 384),
230
+ ("floor_divide", 353),
231
+ ("cartesian_prod", 321),
232
+ ("lu_solve", 317),
233
+ ("set_flush_denormal", 310),
234
+ ("empty_strided", 283),
235
+ ("logical_xor", 282),
236
+ ("polygamma", 282),
237
+ ("logical_or", 280),
238
+ ("set_num_interop_threads", 278),
239
+ ("combinations", 274),
240
+ ("trapz", 270),
241
+ ("matrix_rank", 260),
242
+ ("lu_unpack", 255),
243
+ ("result_type", 244),
244
+ ("conj", 231),
245
+ ("cummax", 230),
246
+ ("lobpcg", 229),
247
+ ("bitwise_xor", 217),
248
+ ("promote_types", 213),
249
+ ("get_num_interop_threads", 211),
250
+ ("cummin", 205),
251
+ ("bitwise_and", 198),
252
+ ("dequantize", 192),
253
+ ("bitwise_or", 191),
254
+ ("imag", 191),
255
+ ("can_cast", 184),
256
+ ("istft", 180),
257
+ ("compiled_with_cxx11_abi", 159),
258
+ ("is_complex", 151),
259
+ ("block_diag", 136),
260
+ ("pca_lowrank", 124),
261
+ ("absolute", 122),
262
+ ("svd_lowrank", 108),
263
+ ("neg", 2),
264
+ ]
265
+
266
+ top_nn_functional = [
267
+ ("nn.functional.softmax", 10522),
268
+ ("nn.functional.relu", 8572),
269
+ ("nn.functional.interpolate", 7277),
270
+ ("nn.functional.pad", 5207),
271
+ ("nn.functional.log_softmax", 4699),
272
+ ("nn.functional.normalize", 2338),
273
+ ("nn.functional.cross_entropy", 2083),
274
+ ("nn.functional.grid_sample", 1970),
275
+ ("nn.functional.one_hot", 1967),
276
+ ("nn.functional.mse_loss", 1920),
277
+ ("nn.functional.conv2d", 1593),
278
+ ("nn.functional.dropout", 1516),
279
+ ("nn.functional.softplus", 1385),
280
+ ("nn.functional.sigmoid", 1128),
281
+ ("nn.functional.linear", 1036),
282
+ ("nn.functional.gelu", 930),
283
+ ("nn.functional.avg_pool2d", 899),
284
+ ("nn.functional.max_pool2d", 876),
285
+ ("nn.functional.nll_loss", 863),
286
+ ("nn.functional.embedding", 737),
287
+ ("nn.functional.tanh", 664),
288
+ ("nn.functional.leaky_relu", 640),
289
+ ("nn.functional.adaptive_avg_pool2d", 633),
290
+ ("nn.functional.cosine_similarity", 627),
291
+ ("nn.functional.unfold", 609),
292
+ ("nn.functional.conv1d", 596),
293
+ ("nn.functional.binary_cross_entropy_with_logits", 591),
294
+ ("nn.functional.l1_loss", 571),
295
+ ("nn.functional.binary_cross_entropy", 492),
296
+ ("nn.functional.elu", 416),
297
+ ("nn.functional.batch_norm", 413),
298
+ ("nn.functional.upsample", 413),
299
+ ("nn.functional.fold", 305),
300
+ ("nn.functional.affine_grid", 298),
301
+ ("nn.functional.max_pool1d", 297),
302
+ ("nn.functional.torch", 294),
303
+ ("nn.functional.threshold", 263),
304
+ ("nn.functional.smooth_l1_loss", 262),
305
+ ("nn.functional.pairwise_distance", 253),
306
+ ("nn.functional.logsigmoid", 243),
307
+ ("nn.functional.adaptive_max_pool2d", 235),
308
+ ("nn.functional.relu6", 213),
309
+ ("nn.functional.pixel_shuffle", 209),
310
+ ("nn.functional.avg_pool3d", 203),
311
+ ("nn.functional.bilinear", 203),
312
+ ("nn.functional.conv_transpose2d", 201),
313
+ ("nn.functional.gumbel_softmax", 197),
314
+ ("nn.functional.max_unpool2d", 196),
315
+ ("nn.functional.kl_div", 191),
316
+ ("nn.functional.hardtanh", 189),
317
+ ("nn.functional.ctc_loss", 185),
318
+ ("nn.functional.layer_norm", 178),
319
+ ("nn.functional.conv3d", 172),
320
+ ("nn.functional.max_unpool3d", 167),
321
+ ("nn.functional.hardshrink", 165),
322
+ ("nn.functional.hardswish", 156),
323
+ ("nn.functional.selu", 156),
324
+ ("nn.functional.glu", 155),
325
+ ("nn.functional.assert_int_or_pair", 150),
326
+ ("nn.functional.hardsigmoid", 146),
327
+ ("nn.functional.upsample_bilinear", 146),
328
+ ("nn.functional.max_pool3d", 140),
329
+ ("nn.functional.adaptive_avg_pool3d", 139),
330
+ ("nn.functional.instance_norm", 124),
331
+ ("nn.functional.embedding_bag", 122),
332
+ ("nn.functional.upsample_nearest", 110),
333
+ ("nn.functional.avg_pool1d", 105),
334
+ ("nn.functional.prelu", 102),
335
+ ("nn.functional.celu", 92),
336
+ ("nn.functional.dropout2d", 86),
337
+ ("nn.functional.hinge_embedding_loss", 82),
338
+ ("nn.functional.softsign", 81),
339
+ ("nn.functional.max_unpool1d", 74),
340
+ ("nn.functional.silu", 74),
341
+ ("nn.functional.softshrink", 70),
342
+ ("nn.functional.leaky_relu_", 68),
343
+ ("nn.functional.softmin", 67),
344
+ ("nn.functional.channel_shuffle", 66),
345
+ ("nn.functional.multilabel_margin_loss", 66),
346
+ ("nn.functional.dropout3d", 65),
347
+ ("nn.functional.multi_margin_loss", 65),
348
+ ("nn.functional.lp_pool2d", 64),
349
+ ("nn.functional.conv_transpose1d", 62),
350
+ ("nn.functional.triplet_margin_loss", 62),
351
+ ("nn.functional.tanhshrink", 61),
352
+ ("nn.functional.adaptive_max_pool1d", 59),
353
+ ("nn.functional.cosine_embedding_loss", 58),
354
+ ("nn.functional.multi_head_attention_forward", 58),
355
+ ("nn.functional.max_pool1d_with_indices", 53),
356
+ ("nn.functional.poisson_nll_loss", 53),
357
+ ("nn.functional.margin_ranking_loss", 52),
358
+ ("nn.functional.soft_margin_loss", 52),
359
+ ("nn.functional.adaptive_max_pool3d", 51),
360
+ ("nn.functional.group_norm", 51),
361
+ ("nn.functional.local_response_norm", 51),
362
+ ("nn.functional.multilabel_soft_margin_loss", 51),
363
+ ("nn.functional.relu_", 50),
364
+ ("nn.functional.alpha_dropout", 49),
365
+ ("nn.functional.feature_alpha_dropout", 49),
366
+ ("nn.functional.lp_pool1d", 49),
367
+ ("nn.functional.adaptive_max_pool1d_with_indices", 48),
368
+ ("nn.functional.adaptive_max_pool2d_with_indices", 48),
369
+ ("nn.functional.adaptive_max_pool3d_with_indices", 48),
370
+ ("nn.functional.fractional_max_pool2d", 48),
371
+ ("nn.functional.fractional_max_pool2d_with_indices", 48),
372
+ ("nn.functional.fractional_max_pool3d", 48),
373
+ ("nn.functional.fractional_max_pool3d_with_indices", 48),
374
+ ("nn.functional.max_pool2d_with_indices", 48),
375
+ ("nn.functional.max_pool3d_with_indices", 48),
376
+ ("nn.functional.handle_torch_function", 47),
377
+ ("nn.functional.has_torch_function", 47),
378
+ ("nn.functional.adaptive_avg_pool1d", 43),
379
+ ("nn.functional.pdist", 43),
380
+ ("nn.functional.rrelu_", 37),
381
+ ("nn.functional.elu_", 34),
382
+ ("nn.functional.boolean_dispatch", 33),
383
+ ("nn.functional.hardtanh_", 26),
384
+ ("nn.functional.triplet_margin_with_distance_loss", 23),
385
+ ("nn.functional.selu_", 20),
386
+ ("nn.functional.pixel_unshuffle", 19),
387
+ ("nn.functional.conv_transpose3d", 18),
388
+ ("nn.functional.gaussian_nll_loss", 15),
389
+ ("nn.functional.has_torch_function_unary", 15),
390
+ ("nn.functional.has_torch_function_variadic", 15),
391
+ ("nn.functional.celu_", 13),
392
+ ("nn.functional.huber_loss", 7),
393
+ ("nn.functional.mish", 4),
394
+ ("nn.functional.threshold_", 3),
395
+ ("nn.functional.grad", 2),
396
+ ("nn.functional.conv_tbc", 1),
397
+ ("nn.functional.math", 1),
398
+ ]
399
+
400
+ top_nn_module = [
401
+ ("nn.Module", 927129, None),
402
+ ("nn.Linear", 530688, "nn.functional.linear"),
403
+ ("nn.Sequential", 384968, None),
404
+ ("nn.Conv2d", 383320, "nn.functional.conv2d"),
405
+ ("nn.ReLU", 318877, "nn.functional.relu"),
406
+ ("nn.BatchNorm2d", 233265, "nn.functional.batch_norm"),
407
+ ("nn.Dropout", 179268, "nn.functional.dropout"),
408
+ ("nn.ModuleList", 171225, None),
409
+ ("nn.Parameter", 153291, None),
410
+ ("nn.CrossEntropyLoss", 152696, "nn.functional.cross_entropy"),
411
+ ("nn.MaxPool2d", 138619, "nn.functional.max_pool2d"),
412
+ ("nn.Embedding", 111844, "nn.functional.embedding"),
413
+ ("nn.DataParallel", 104238, None),
414
+ ("nn.MSELoss", 82954, "nn.functional.mse_loss"),
415
+ ("nn.Sigmoid", 75810, "nn.functional.sigmoid"),
416
+ ("nn.LeakyReLU", 65632, "nn.functional.leaky_relu"),
417
+ ("nn.BatchNorm1d", 65374, "nn.functional.batch_norm"),
418
+ ("nn.Softmax", 65114, "nn.functional.softmax"),
419
+ ("nn.Tanh", 59445, "nn.functional.tanh"),
420
+ ("nn.AdaptiveAvgPool2d", 59071, "nn.functional.adaptive_avg_pool2d"),
421
+ ("nn.AvgPool2d", 58377, "nn.functional.avg_pool2d"),
422
+ ("nn.ConvTranspose2d", 57524, "nn.functional.conv_transpose2d"),
423
+ ("nn.LSTM", 57411, None),
424
+ ("nn.Conv1d", 41108, "nn.functional.conv1d"),
425
+ ("nn.LayerNorm", 36089, "nn.functional.layer_norm"),
426
+ ("nn.BCELoss", 34005, "nn.functional.binary_cross_entropy"),
427
+ ("nn.Upsample", 32527, "nn.functional.interpolate"),
428
+ ("nn.BCEWithLogitsLoss", 29944, "nn.functional.binary_cross_entropy_with_logits"),
429
+ ("nn.GRU", 25421, None),
430
+ ("nn.Dropout2d", 23512, "nn.functional.dropout2d"),
431
+ ("nn.LogSoftmax", 22897, "nn.functional.log_softmax"),
432
+ ("nn.L1Loss", 22778, "nn.functional.l1_loss"),
433
+ ("nn.GroupNorm", 22183, "nn.functional.group_norm"),
434
+ ("nn.NLLLoss", 21751, "nn.functional.nll_loss"),
435
+ ("nn.Conv3d", 20874, "nn.functional.conv3d"),
436
+ ("nn.Identity", 17911, None),
437
+ ("nn.InstanceNorm2d", 16426, "nn.functional.instance_norm"),
438
+ ("nn.BatchNorm3d", 16378, "nn.functional.batch_norm"),
439
+ ("nn.PReLU", 13472, "nn.functional.prelu"),
440
+ ("nn.ReLU6", 12622, "nn.functional.relu6"),
441
+ ("nn.ELU", 12508, "nn.functional.elu"),
442
+ ("nn.LSTMCell", 10885, None),
443
+ ("nn.Flatten", 10384, "torch.flatten"),
444
+ ("nn.ModuleDict", 10255, None),
445
+ ("nn.ReflectionPad2d", 9954, "nn.functional.pad"),
446
+ ("nn.MaxPool3d", 9526, "nn.functional.max_pool3d"),
447
+ ("nn.MaxPool1d", 9154, "nn.functional.max_pool1d"),
448
+ ("nn.RNN", 9154, None),
449
+ ("nn.ZeroPad2d", 8847, "nn.functional.pad"),
450
+ ("nn.ParameterList", 7702, None),
451
+ ("nn.SyncBatchNorm", 6814, None),
452
+ ("nn.PixelShuffle", 6571, "nn.functional.pixel_shuffle"),
453
+ ("nn.SmoothL1Loss", 6517, "nn.functional.smooth_l1_loss"),
454
+ ("nn.Hardswish", 6458, "nn.functional.hardswish"),
455
+ ("nn.AdaptiveMaxPool2d", 6071, "nn.functional.adaptive_max_pool2d"),
456
+ ("nn.SELU", 6043, "nn.functional.selu"),
457
+ ("nn.ConvTranspose3d", 6039, "nn.functional.conv_transpose3d"),
458
+ ("nn.GRUCell", 5840, None),
459
+ ("nn.ReplicationPad2d", 5600, "nn.functional.pad"),
460
+ ("nn.KLDivLoss", 5541, "nn.functional.kl_div"),
461
+ ("nn.ConvTranspose1d", 5183, "nn.functional.conv_transpose1d"),
462
+ ("nn.Softplus", 5120, "nn.functional.softplus"),
463
+ ("nn.SiLU", 4895, "nn.functional.silu"),
464
+ ("nn.AvgPool3d", 4523, "nn.functional.avg_pool3d"),
465
+ ("nn.CosineSimilarity", 4058, "nn.functional.cosine_similarity"),
466
+ ("nn.GELU", 3932, "nn.functional.gelu"),
467
+ ("nn.UpsamplingBilinear2d", 3673, "nn.functional.interpolate"),
468
+ ("nn.InstanceNorm1d", 3658, "nn.functional.instance_norm"),
469
+ ("nn.Transformer", 3604, None),
470
+ ("nn.MultiheadAttention", 3435, "nn.functional.multi_head_attention_forward"),
471
+ ("nn.AvgPool1d", 3195, "nn.functional.avg_pool1d"),
472
+ ("nn.Dropout3d", 2964, "nn.functional.dropout3d"),
473
+ ("nn.AdaptiveAvgPool3d", 2915, "nn.functional.adaptive_avg_pool3d"),
474
+ ("nn.InstanceNorm3d", 2893, "nn.functional.instance_norm"),
475
+ ("nn.Hardtanh", 2613, "nn.functional.hardtanh"),
476
+ ("nn.MarginRankingLoss", 2568, "nn.functional.margin_ranking_loss"),
477
+ ("nn.GLU", 2526, "nn.functional.glu"),
478
+ ("nn.AdaptiveAvgPool1d", 2481, "nn.functional.adaptive_avg_pool1d"),
479
+ ("nn.EmbeddingBag", 2344, "nn.functional.embedding_bag"),
480
+ ("nn.TransformerEncoderLayer", 2292, None),
481
+ ("nn.TransformerEncoder", 2091, None),
482
+ ("nn.MaxUnpool2d", 2031, "nn.functional.max_unpool2d"),
483
+ ("nn.UpsamplingNearest2d", 2004, "nn.functional.interpolate"),
484
+ ("nn.ConstantPad1d", 1904, "nn.functional.pad"),
485
+ ("nn.ConstantPad2d", 1791, "nn.functional.pad"),
486
+ ("nn.CTCLoss", 1789, "nn.functional.ctc_loss"),
487
+ ("nn.AdaptiveMaxPool1d", 1713, "nn.functional.adaptive_max_pool1d"),
488
+ ("nn.AdaptiveLogSoftmaxWithLoss", 1665, None),
489
+ ("nn.Bilinear", 1664, "nn.functional.bilinear"),
490
+ ("nn.RNNCell", 1653, None),
491
+ ("nn.MultiLabelSoftMarginLoss", 1624, "nn.functional.multilabel_soft_margin_loss"),
492
+ ("nn.Unfold", 1452, "nn.functional.unfold"),
493
+ ("nn.RReLU", 1431, "nn.functional.rrelu"),
494
+ ("nn.CosineEmbeddingLoss", 1357, "nn.functional.cosine_embedding_loss"),
495
+ ("nn.LocalResponseNorm", 1331, "nn.functional.local_response_norm"),
496
+ ("nn.Softmax2d", 1300, "nn.functional.softmax"),
497
+ ("nn.PairwiseDistance", 1241, "nn.functional.pairwise_distance"),
498
+ ("nn.LogSigmoid", 1235, "nn.functional.logsigmoid"),
499
+ ("nn.TripletMarginLoss", 1230, "nn.functional.triplet_margin_loss"),
500
+ ("nn.RNNBase", 1133, None),
501
+ ("nn.Threshold", 1043, "nn.functional.threshold"),
502
+ ("nn.AdaptiveMaxPool3d", 1025, "nn.functional.adaptive_max_pool3d"),
503
+ ("nn.CELU", 1018, "nn.functional.celu"),
504
+ ("nn.NLLLoss2d", 966, "nn.functional.nll_loss"),
505
+ ("nn.Softsign", 877, "nn.functional.softsign"),
506
+ ("nn.ReplicationPad1d", 862, "nn.functional.pad"),
507
+ ("nn.SoftMarginLoss", 856, "nn.functional.soft_margin_loss"),
508
+ ("nn.ParameterDict", 742, None),
509
+ ("nn.ReflectionPad1d", 731, "nn.functional.pad"),
510
+ ("nn.Softshrink", 713, "nn.functional.softshrink"),
511
+ ("nn.AlphaDropout", 710, "nn.functional.alpha_dropout"),
512
+ ("nn.Tanhshrink", 681, "nn.functional.tanhshrink"),
513
+ ("nn.PoissonNLLLoss", 676, "nn.functional.poisson_nll_loss"),
514
+ ("nn.MaxUnpool3d", 660, "nn.functional.max_unpool3d"),
515
+ ("nn.Fold", 630, "nn.functional.fold"),
516
+ ("nn.MultiMarginLoss", 622, "nn.functional.multi_margin_loss"),
517
+ ("nn.TransformerDecoderLayer", 614, None),
518
+ ("nn.TransformerDecoder", 607, None),
519
+ ("nn.Hardshrink", 592, "nn.functional.hardshrink"),
520
+ ("nn.ConstantPad3d", 582, "nn.functional.pad"),
521
+ ("nn.MultiLabelMarginLoss", 580, "nn.functional.multilabel_margin_loss"),
522
+ ("nn.LPPool2d", 550, "nn.functional.lp_pool2d"),
523
+ ("nn.Softmin", 537, "nn.functional.softmin"),
524
+ ("nn.MaxUnpool1d", 518, "nn.functional.max_unpool1d"),
525
+ ("nn.FractionalMaxPool2d", 484, "nn.functional.fractional_max_pool2d"),
526
+ ("nn.Hardsigmoid", 477, "nn.functional.hardsigmoid"),
527
+ ("nn.ReplicationPad3d", 470, "nn.functional.pad"),
528
+ ("nn.HingeEmbeddingLoss", 442, "nn.functional.hinge_embedding_loss"),
529
+ ("nn.LPPool1d", 386, "nn.functional.lp_pool1d"),
530
+ ("nn.FractionalMaxPool3d", 252, "nn.functional.fractional_max_pool3d"),
531
+ ("nn.Container", 217, None),
532
+ ("nn.Unflatten", 206, "nn.functional.unflatten"),
533
+ ("nn.FeatureAlphaDropout", 136, "nn.functional.feature_alpha_dropout"),
534
+ (
535
+ "nn.TripletMarginWithDistanceLoss",
536
+ 107,
537
+ "nn.functional.triplet_margin_with_distance_loss",
538
+ ),
539
+ ("nn.ChannelShuffle", 90, "nn.functional.channel_shuffle"),
540
+ ("nn.RNNCellBase", 88, None),
541
+ ("nn.LazyLinear", 81, "nn.functional.linear"),
542
+ ("nn.UninitializedParameter", 60, None),
543
+ ("nn.CrossMapLRN2d", 59, None),
544
+ ("nn.GaussianNLLLoss", 55, "nn.functional.gaussian_nll_loss"),
545
+ ("nn.PixelUnshuffle", 45, "nn.functional.pixel_unshuffle"),
546
+ ("nn.Mish", 31, "nn.functional.mish"),
547
+ ("nn.ReflectionPad3d", 22, "nn.functional.pad"),
548
+ ("nn.HuberLoss", 18, "nn.functional.huber_loss"),
549
+ ("nn.LazyConv2d", 15, None),
550
+ ("nn.LazyConv1d", 9, None),
551
+ ("nn.LazyConv3d", 8, None),
552
+ ("nn.LazyConvTranspose1d", 8, None),
553
+ ("nn.LazyConvTranspose2d", 8, None),
554
+ ("nn.LazyConvTranspose3d", 8, None),
555
+ ("nn.LazyBatchNorm1d", 3, None),
556
+ ("nn.LazyBatchNorm2d", 3, None),
557
+ ("nn.LazyBatchNorm3d", 3, None),
558
+ ("nn.UninitializedBuffer", 3, None),
559
+ ]
560
+
561
+ # No rankings because these are a little hard to get rankings for
562
+ method_only_ops = [
563
+ "bfloat16",
564
+ "bool",
565
+ "byte",
566
+ "char",
567
+ "contiguous",
568
+ "cpu",
569
+ "cuda",
570
+ "detach",
571
+ "double",
572
+ "expand",
573
+ "expand_as",
574
+ "float",
575
+ "get_device",
576
+ "half",
577
+ "hardshrink",
578
+ "index_add",
579
+ "index_copy",
580
+ "index_fill",
581
+ "index_put",
582
+ "int",
583
+ "is_contiguous",
584
+ "is_pinned",
585
+ "is_set_to",
586
+ "is_shared",
587
+ "is_signed",
588
+ "item",
589
+ "long",
590
+ "masked_scatter",
591
+ "masked_fill",
592
+ "narrow_copy",
593
+ "numpy",
594
+ "pin_memory",
595
+ "repeat",
596
+ "reshape_as",
597
+ "select",
598
+ "short",
599
+ "storage_offset",
600
+ "sum_to_size",
601
+ "to",
602
+ "to_mkldnn",
603
+ "tolist",
604
+ "type",
605
+ "type_as",
606
+ "unfold",
607
+ "view",
608
+ "view_as",
609
+ ]
610
+
611
+
612
+ def get_nn_functional_top_list():
613
+ top_nn_functional_ = dict(top_nn_functional)
614
+ for _, count, functional_name in top_nn_module:
615
+ if functional_name is None:
616
+ continue
617
+ if functional_name == "torch.flatten":
618
+ continue
619
+ if functional_name not in top_nn_functional_:
620
+ top_nn_functional_[functional_name] = count
621
+ else:
622
+ top_nn_functional_[functional_name] += count
623
+
624
+ top_nn_functional_ = list(top_nn_functional_.items())
625
+ top_nn_functional_.sort(key=operator.itemgetter(1), reverse=True)
626
+ return top_nn_functional_
627
+
628
+
629
+ usage_count = dict(get_nn_functional_top_list())
630
+ usage_count.update(top_torch)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_functorch/vmap.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import contextlib
10
+ import functools
11
+ import itertools
12
+ from functools import partial
13
+ from typing import Any, Callable, Optional, Union
14
+
15
+ import torch
16
+ from torch import Tensor
17
+ from torch._C._functorch import is_batchedtensor
18
+ from torch._functorch.predispatch import (
19
+ _add_batch_dim,
20
+ _remove_batch_dim,
21
+ _vmap_decrement_nesting,
22
+ _vmap_increment_nesting,
23
+ lazy_load_decompositions,
24
+ )
25
+ from torch.utils._pytree import (
26
+ _broadcast_to_and_flatten,
27
+ tree_flatten,
28
+ tree_map_,
29
+ tree_unflatten,
30
+ TreeSpec,
31
+ )
32
+
33
+
34
+ in_dims_t = Union[int, tuple]
35
+ out_dims_t = Union[int, tuple[int, ...]]
36
+
37
+
38
+ def doesnt_support_saved_tensors_hooks(f):
39
+ message = (
40
+ "torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. "
41
+ "Please open an issue with your use case."
42
+ )
43
+
44
+ @functools.wraps(f)
45
+ def fn(*args, **kwargs):
46
+ with torch.autograd.graph.disable_saved_tensors_hooks(message):
47
+ return f(*args, **kwargs)
48
+
49
+ return fn
50
+
51
+
52
+ # Checks that all args-to-be-batched have the same batch dim size
53
+ def _validate_and_get_batch_size(
54
+ flat_in_dims: list[Optional[int]], flat_args: list
55
+ ) -> int:
56
+ batch_sizes = [
57
+ arg.size(in_dim)
58
+ for in_dim, arg in zip(flat_in_dims, flat_args)
59
+ if in_dim is not None
60
+ ]
61
+ if len(batch_sizes) == 0:
62
+ raise ValueError("vmap: Expected at least one Tensor to vmap over")
63
+ if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes):
64
+ raise ValueError(
65
+ f"vmap: Expected all tensors to have the same size in the mapped "
66
+ f"dimension, got sizes {batch_sizes} for the mapped dimension"
67
+ )
68
+ return batch_sizes[0]
69
+
70
+
71
+ def _num_outputs(batched_outputs: Union[Tensor, tuple[Tensor, ...]]) -> int:
72
+ if isinstance(batched_outputs, tuple):
73
+ return len(batched_outputs)
74
+ return 1
75
+
76
+
77
+ # If value is a tuple, check it has length `num_elements`.
78
+ # If value is not a tuple, make a tuple with `value` repeated `num_elements` times
79
+
80
+
81
+ def _as_tuple(
82
+ value: Any, num_elements: int, error_message_lambda: Callable[[], str]
83
+ ) -> tuple:
84
+ if not isinstance(value, tuple):
85
+ return (value,) * num_elements
86
+ if len(value) != num_elements:
87
+ raise ValueError(error_message_lambda())
88
+ return value
89
+
90
+
91
+ def _process_batched_inputs(
92
+ in_dims: in_dims_t, args: tuple, func: Callable
93
+ ) -> tuple[int, list[Any], list[Any], TreeSpec]:
94
+ if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
95
+ raise ValueError(
96
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
97
+ f"expected `in_dims` to be int or a (potentially nested) tuple "
98
+ f"matching the structure of inputs, got: {type(in_dims)}."
99
+ )
100
+ if len(args) == 0:
101
+ raise ValueError(
102
+ f"vmap({_get_name(func)})(<inputs>): got no inputs. Maybe you forgot to add "
103
+ f"inputs, or you are trying to vmap over a function with no inputs. "
104
+ f"The latter is unsupported."
105
+ )
106
+
107
+ flat_args, args_spec = tree_flatten(args)
108
+ flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
109
+ if flat_in_dims is None:
110
+ raise ValueError(
111
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
112
+ f"in_dims is not compatible with the structure of `inputs`. "
113
+ f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs "
114
+ f"has structure {args_spec}."
115
+ )
116
+
117
+ for i, (arg, in_dim) in enumerate(zip(flat_args, flat_in_dims)):
118
+ if not isinstance(in_dim, int) and in_dim is not None:
119
+ raise ValueError(
120
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
121
+ f"Got in_dim={in_dim} for an input but in_dim must be either "
122
+ f"an integer dimension or None."
123
+ )
124
+ if isinstance(in_dim, int) and not isinstance(arg, Tensor):
125
+ raise ValueError(
126
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
127
+ f"Got in_dim={in_dim} for an input but the input is of type "
128
+ f"{type(arg)}. We cannot vmap over non-Tensor arguments, "
129
+ f"please use None as the respective in_dim"
130
+ )
131
+ if in_dim is not None and (in_dim < -arg.dim() or in_dim >= arg.dim()):
132
+ raise ValueError(
133
+ f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
134
+ f"Got in_dim={in_dim} for some input, but that input is a Tensor "
135
+ f"of dimensionality {arg.dim()} so expected in_dim to satisfy "
136
+ f"-{arg.dim()} <= in_dim < {arg.dim()}."
137
+ )
138
+ if in_dim is not None and in_dim < 0:
139
+ flat_in_dims[i] = in_dim % arg.dim()
140
+
141
+ return (
142
+ _validate_and_get_batch_size(flat_in_dims, flat_args),
143
+ flat_in_dims,
144
+ flat_args,
145
+ args_spec,
146
+ )
147
+
148
+
149
+ # Creates BatchedTensors for every Tensor in arg that should be batched.
150
+ # Returns the (potentially) batched arguments and the batch_size.
151
+
152
+
153
+ def _create_batched_inputs(
154
+ flat_in_dims: list[Any], flat_args: list[Any], vmap_level: int, args_spec
155
+ ) -> tuple:
156
+ # See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
157
+ batched_inputs = [
158
+ arg if in_dim is None else _add_batch_dim(arg, in_dim, vmap_level)
159
+ for in_dim, arg in zip(flat_in_dims, flat_args)
160
+ ]
161
+ return tree_unflatten(batched_inputs, args_spec)
162
+
163
+
164
+ def _maybe_remove_batch_dim(name, batched_output, vmap_level, batch_size, out_dim):
165
+ if out_dim is None:
166
+ if isinstance(batched_output, torch.Tensor) and is_batchedtensor(
167
+ batched_output
168
+ ):
169
+ raise ValueError(
170
+ f"vmap({name}, ...): `{name}` can not return a "
171
+ f"BatchedTensor when out_dim is None"
172
+ )
173
+ return batched_output
174
+
175
+ # out_dim is non None
176
+ if not isinstance(batched_output, torch.Tensor):
177
+ raise ValueError(
178
+ f"vmap({name}, ...): `{name}` must only return "
179
+ f"Tensors, got type {type(batched_output)}. "
180
+ "Did you mean to set out_dims= to None for output?"
181
+ )
182
+
183
+ return _remove_batch_dim(batched_output, vmap_level, batch_size, out_dim)
184
+
185
+
186
+ # Undos the batching (and any batch dimensions) associated with the `vmap_level`.
187
+ def _unwrap_batched(
188
+ batched_outputs: Union[Tensor, tuple[Tensor, ...]],
189
+ out_dims: out_dims_t,
190
+ vmap_level: int,
191
+ batch_size: int,
192
+ func: Callable,
193
+ ) -> tuple:
194
+ flat_batched_outputs, output_spec = tree_flatten(batched_outputs)
195
+
196
+ def incompatible_error():
197
+ raise ValueError(
198
+ f"vmap({_get_name(func)}, ..., out_dims={out_dims})(<inputs>): "
199
+ f"out_dims is not compatible with the structure of `outputs`. "
200
+ f"out_dims has structure {tree_flatten(out_dims)[1]} but outputs "
201
+ f"has structure {output_spec}."
202
+ )
203
+
204
+ if isinstance(batched_outputs, torch.Tensor):
205
+ # Some weird edge case requires us to spell out the following
206
+ # see test_out_dims_edge_case
207
+ if isinstance(out_dims, int):
208
+ flat_out_dims = [out_dims]
209
+ elif isinstance(out_dims, tuple) and len(out_dims) == 1:
210
+ flat_out_dims = out_dims
211
+ elif out_dims is None:
212
+ flat_out_dims = [out_dims]
213
+ else:
214
+ incompatible_error()
215
+ else:
216
+ flat_out_dims = _broadcast_to_and_flatten(out_dims, output_spec)
217
+ if flat_out_dims is None:
218
+ incompatible_error()
219
+
220
+ flat_outputs = [
221
+ _maybe_remove_batch_dim(
222
+ _get_name(func), batched_output, vmap_level, batch_size, out_dim
223
+ )
224
+ for batched_output, out_dim in zip(flat_batched_outputs, flat_out_dims)
225
+ ]
226
+ return tree_unflatten(flat_outputs, output_spec)
227
+
228
+
229
+ def _check_int_or_none(x, func, out_dims):
230
+ if isinstance(x, int):
231
+ return
232
+ if x is None:
233
+ return
234
+ raise ValueError(
235
+ f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be "
236
+ f"an int, None or a python collection of ints representing where in the outputs the "
237
+ f"vmapped dimension should appear."
238
+ )
239
+
240
+
241
+ def _check_out_dims_is_int_or_int_pytree(out_dims: out_dims_t, func: Callable) -> None:
242
+ if isinstance(out_dims, int):
243
+ return
244
+ tree_map_(partial(_check_int_or_none, func=func, out_dims=out_dims), out_dims)
245
+
246
+
247
+ def _get_name(func: Callable):
248
+ if hasattr(func, "__name__"):
249
+ return func.__name__
250
+
251
+ if isinstance(func, functools.partial):
252
+ return f"functools.partial({_get_name(func.func)}, ...)"
253
+
254
+ # Not all callables have __name__, in fact, only static functions/methods
255
+ # do. A callable created via nn.Module, to name one example, doesn't have a
256
+ # __name__.
257
+ return repr(func)
258
+
259
+
260
+ def vmap_impl(func, in_dims, out_dims, randomness, chunk_size, *args, **kwargs):
261
+ lazy_load_decompositions()
262
+ _check_out_dims_is_int_or_int_pytree(out_dims, func)
263
+ batch_size, flat_in_dims, flat_args, args_spec = _process_batched_inputs(
264
+ in_dims, args, func
265
+ )
266
+
267
+ if chunk_size is not None:
268
+ chunks_flat_args = _get_chunked_inputs(
269
+ flat_args, flat_in_dims, batch_size, chunk_size
270
+ )
271
+ return _chunked_vmap(
272
+ func,
273
+ flat_in_dims,
274
+ chunks_flat_args,
275
+ args_spec,
276
+ out_dims,
277
+ randomness,
278
+ **kwargs,
279
+ )
280
+
281
+ # If chunk_size is not specified.
282
+ return _flat_vmap(
283
+ func,
284
+ batch_size,
285
+ flat_in_dims,
286
+ flat_args,
287
+ args_spec,
288
+ out_dims,
289
+ randomness,
290
+ **kwargs,
291
+ )
292
+
293
+
294
+ def get_chunk_sizes(total_elems, chunk_size):
295
+ n_chunks = n_chunks = total_elems // chunk_size
296
+ chunk_sizes = [chunk_size] * n_chunks
297
+ # remainder chunk
298
+ remainder = total_elems % chunk_size
299
+ if remainder != 0:
300
+ chunk_sizes.append(remainder)
301
+ return chunk_sizes
302
+
303
+
304
+ def _get_chunked_inputs(flat_args, flat_in_dims, batch_size, chunk_size):
305
+ split_idxs = (batch_size,)
306
+ if chunk_size is not None:
307
+ chunk_sizes = get_chunk_sizes(batch_size, chunk_size)
308
+ split_idxs = tuple(itertools.accumulate(chunk_sizes))
309
+
310
+ flat_args_chunks = tuple(
311
+ (
312
+ t.tensor_split(split_idxs, dim=in_dim)
313
+ if in_dim is not None
314
+ else [
315
+ t,
316
+ ]
317
+ * len(split_idxs)
318
+ )
319
+ for t, in_dim in zip(flat_args, flat_in_dims)
320
+ )
321
+
322
+ # transpose chunk dim and flatten structure
323
+ # chunks_flat_args is a list of flatten args
324
+ chunks_flat_args = zip(*flat_args_chunks)
325
+ return chunks_flat_args
326
+
327
+
328
+ def _flatten_chunks_output(chunks_output_):
329
+ # chunks_output is a list of chunked outputs
330
+ # flatten chunked outputs:
331
+ flat_chunks_output = []
332
+ arg_spec = None
333
+ for output in chunks_output_:
334
+ flat_output, arg_specs = tree_flatten(output)
335
+ flat_chunks_output.append(flat_output)
336
+ if arg_spec is None:
337
+ arg_spec = arg_specs
338
+
339
+ # transpose chunk dim and flatten structure
340
+ # flat_output_chunks is flat list of chunks
341
+ flat_output_chunks = list(zip(*flat_chunks_output))
342
+ return flat_output_chunks, arg_spec
343
+
344
+
345
+ def _concat_chunked_outputs(out_dims, arg_spec, flat_output_chunks):
346
+ # concat chunks on out_dim
347
+ flat_out_dims = _broadcast_to_and_flatten(out_dims, arg_spec)
348
+ assert len(flat_out_dims) == len(flat_output_chunks)
349
+ flat_output = []
350
+ for idx, out_dim in enumerate(flat_out_dims):
351
+ flat_output.append(torch.cat(flat_output_chunks[idx], dim=out_dim))
352
+ # release tensors
353
+ flat_output_chunks[idx] = None
354
+
355
+ return flat_output
356
+
357
+
358
+ # Applies vmap on chunked_input and returns concatenated output over the chunks.
359
+ def _chunked_vmap(
360
+ func, flat_in_dims, chunks_flat_args, args_spec, out_dims, randomness, **kwargs
361
+ ):
362
+ chunks_output = []
363
+ rs = torch.get_rng_state() if randomness == "same" else None
364
+ for flat_args in chunks_flat_args:
365
+ batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
366
+
367
+ # The way we compute split the input in `_get_chunked_inputs`,
368
+ # we may get a tensor with `0` batch-size. We skip any computation
369
+ # in that case.
370
+ # Eg.
371
+ # >>> chunk_size = 1
372
+ # >>> batch_size = 6
373
+ # >>> t = torch.zeros(batch_size, 1)
374
+ # >>> t.tensor_split([1, 2, 3, 4, 5, 6])
375
+ # (tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), tensor([[0.]]),
376
+ # tensor([[0.]]), tensor([[0.]]), tensor([], size=(0, 1)))
377
+ if batch_size == 0:
378
+ continue
379
+
380
+ if rs is not None:
381
+ torch.set_rng_state(rs)
382
+ chunks_output.append(
383
+ _flat_vmap(
384
+ func,
385
+ batch_size,
386
+ flat_in_dims,
387
+ flat_args,
388
+ args_spec,
389
+ out_dims,
390
+ randomness,
391
+ **kwargs,
392
+ )
393
+ )
394
+
395
+ flat_output_chunks, arg_spec = _flatten_chunks_output(chunks_output)
396
+
397
+ # chunked output tensors are held by both `flat_output_chunks` and `chunks_output`.
398
+ # eagerly remove the reference from `chunks_output`.
399
+ del chunks_output
400
+
401
+ # concat chunks on out_dim
402
+ flat_output = _concat_chunked_outputs(out_dims, arg_spec, flat_output_chunks)
403
+
404
+ # finally unflatten the output
405
+ return tree_unflatten(flat_output, arg_spec)
406
+
407
+
408
+ # Vmap refactored helper functions:
409
+ def _check_randomness_arg(randomness):
410
+ if randomness not in ["error", "different", "same"]:
411
+ raise RuntimeError(
412
+ f"Only allowed values for randomness are 'error', 'different', or 'same'. Got {randomness}"
413
+ )
414
+
415
+
416
+ @contextlib.contextmanager
417
+ def vmap_increment_nesting(batch_size, randomness):
418
+ try:
419
+ vmap_level = _vmap_increment_nesting(batch_size, randomness)
420
+ yield vmap_level
421
+ finally:
422
+ _vmap_decrement_nesting()
423
+
424
+
425
+ def _flat_vmap(
426
+ func, batch_size, flat_in_dims, flat_args, args_spec, out_dims, randomness, **kwargs
427
+ ):
428
+ with vmap_increment_nesting(batch_size, randomness) as vmap_level:
429
+ batched_inputs = _create_batched_inputs(
430
+ flat_in_dims, flat_args, vmap_level, args_spec
431
+ )
432
+ batched_outputs = func(*batched_inputs, **kwargs)
433
+ return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func)
434
+
435
+
436
+ # `restore_vmap` is a private helper function. It is vmap but has the following
437
+ # differences:
438
+ # - instead of returning outputs, it returns an (outputs, out_dims) tuple.
439
+ # out_dims is a pytree of same shape as outputs and contains Optional[int]
440
+ # specifying where the vmapped dimension, if it exists, is in the corresponding output.
441
+ # - does no validation on in_dims or inputs (vmap expects at least one Tensor to be vmapped).
442
+ # restore_vmap allows for no inputs to have the vmap dimension
443
+ # - does no validation on outputs (vmap expects only Tensor outputs)
444
+ # restore_vmap allows for return of arbitrary outputs (not just Tensors)
445
+ #
446
+ # The TL;DR is that restore_vmap is more general than vmap and has a slightly
447
+ # different API. The relaxations are so that we can "pause" vmap in the middle
448
+ # of its execution and then "restore" it later (this is what we do in
449
+ # the generate_vmap_rule=True implementation of autograd.Function).
450
+ #
451
+ # restore_vmap can be technically used in the implementation of vmap, but doing
452
+ # that refactor is a bit technically challenging because:
453
+ # - vmap couples the tensor-wrapping code with error checking
454
+ # - vmap's tensor unwrapping code is in C++; we would need to rewrite part of it
455
+ # in python because it overlaps with unwrap_batched
456
+ def restore_vmap(func, in_dims, batch_size, randomness):
457
+ def inner(*args, **kwargs):
458
+ with vmap_increment_nesting(batch_size, randomness) as vmap_level:
459
+ batched_inputs = wrap_batched(args, in_dims, vmap_level)
460
+ batched_outputs = func(*batched_inputs, **kwargs)
461
+ return unwrap_batched(batched_outputs, vmap_level)
462
+
463
+ return inner
464
+
465
+
466
+ def wrap_batched(args, bdims, level):
467
+ flat_args, spec = tree_flatten(args)
468
+ flat_bdims = _broadcast_to_and_flatten(bdims, spec)
469
+ assert flat_bdims is not None
470
+ result = _create_batched_inputs(flat_bdims, flat_args, level, spec)
471
+ return result
472
+
473
+
474
+ def unwrap_batched(args, level):
475
+ flat_args, spec = tree_flatten(args)
476
+ if len(flat_args) == 0:
477
+ return args, ()
478
+ result = [
479
+ (
480
+ torch._C._functorch._unwrap_batched(arg, level)
481
+ if isinstance(arg, torch.Tensor)
482
+ else (arg, None)
483
+ )
484
+ for arg in flat_args
485
+ ]
486
+ output, bdims = zip(*result)
487
+ return tree_unflatten(output, spec), tree_unflatten(bdims, spec)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._higher_order_ops._invoke_quant import (
2
+ invoke_quant,
3
+ invoke_quant_packed,
4
+ InvokeQuant,
5
+ )
6
+ from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate
7
+ from torch._higher_order_ops.associative_scan import associative_scan
8
+ from torch._higher_order_ops.auto_functionalize import (
9
+ auto_functionalized,
10
+ auto_functionalized_v2,
11
+ )
12
+ from torch._higher_order_ops.base_hop import BaseHOP
13
+ from torch._higher_order_ops.cond import cond
14
+ from torch._higher_order_ops.effects import with_effects
15
+ from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate
16
+ from torch._higher_order_ops.flat_apply import flat_apply
17
+ from torch._higher_order_ops.flex_attention import (
18
+ flex_attention,
19
+ flex_attention_backward,
20
+ )
21
+ from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map
22
+ from torch._higher_order_ops.hints_wrap import hints_wrapper
23
+ from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
24
+ from torch._higher_order_ops.map import map
25
+ from torch._higher_order_ops.out_dtype import out_dtype
26
+ from torch._higher_order_ops.run_const_graph import run_const_graph
27
+ from torch._higher_order_ops.scan import scan
28
+ from torch._higher_order_ops.strict_mode import strict_mode
29
+ from torch._higher_order_ops.torchbind import call_torchbind
30
+ from torch._higher_order_ops.while_loop import (
31
+ while_loop,
32
+ while_loop_stack_output_op as while_loop_stack_output,
33
+ )
34
+ from torch._higher_order_ops.wrap import (
35
+ dynamo_bypassing_wrapper,
36
+ tag_activation_checkpoint,
37
+ wrap_activation_checkpoint,
38
+ wrap_with_autocast,
39
+ wrap_with_set_grad_enabled,
40
+ )
41
+
42
+
43
+ __all__ = [
44
+ "cond",
45
+ "while_loop",
46
+ "invoke_subgraph",
47
+ "scan",
48
+ "map",
49
+ "flex_attention",
50
+ "flex_attention_backward",
51
+ "hints_wrapper",
52
+ "BaseHOP",
53
+ "flat_apply",
54
+ "foreach_map",
55
+ "_foreach_map",
56
+ "with_effects",
57
+ "tag_activation_checkpoint",
58
+ "auto_functionalized",
59
+ "auto_functionalized_v2",
60
+ "associative_scan",
61
+ "out_dtype",
62
+ "executorch_call_delegate",
63
+ "call_torchbind",
64
+ "run_const_graph",
65
+ "InvokeQuant",
66
+ "invoke_quant",
67
+ "invoke_quant_packed",
68
+ "wrap_with_set_grad_enabled",
69
+ "wrap_with_autocast",
70
+ "wrap_activation_checkpoint",
71
+ "dynamo_bypassing_wrapper",
72
+ "strict_mode",
73
+ "aoti_call_delegate",
74
+ "map",
75
+ "while_loop_stack_output",
76
+ ]