FaustDerLegende commited on
Commit
255325a
·
verified ·
1 Parent(s): 3cda3fb

Upload folder using huggingface_hub (part 24)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. .venv/lib/python3.12/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-312.pyc +0 -0
  3. .venv/lib/python3.12/site-packages/torch/export/__pycache__/exported_program.cpython-312.pyc +0 -0
  4. .venv/lib/python3.12/site-packages/torch/export/__pycache__/graph_signature.cpython-312.pyc +0 -0
  5. .venv/lib/python3.12/site-packages/torch/export/__pycache__/unflatten.cpython-312.pyc +0 -0
  6. .venv/lib/python3.12/site-packages/torch/export/_draft_export.py +556 -0
  7. .venv/lib/python3.12/site-packages/torch/export/_leakage_detection_utils.py +113 -0
  8. .venv/lib/python3.12/site-packages/torch/export/_patches.py +352 -0
  9. .venv/lib/python3.12/site-packages/torch/export/_remove_auto_functionalized_pass.py +55 -0
  10. .venv/lib/python3.12/site-packages/torch/export/_remove_effect_tokens_pass.py +237 -0
  11. .venv/lib/python3.12/site-packages/torch/export/_safeguard.py +47 -0
  12. .venv/lib/python3.12/site-packages/torch/export/_state_dict_utils.py +187 -0
  13. .venv/lib/python3.12/site-packages/torch/export/_swap.py +472 -0
  14. .venv/lib/python3.12/site-packages/torch/export/_trace.py +0 -0
  15. .venv/lib/python3.12/site-packages/torch/export/_tree_utils.py +72 -0
  16. .venv/lib/python3.12/site-packages/torch/export/_unlift.py +904 -0
  17. .venv/lib/python3.12/site-packages/torch/export/_wrapper_utils.py +10 -0
  18. .venv/lib/python3.12/site-packages/torch/export/custom_obj.py +16 -0
  19. .venv/lib/python3.12/site-packages/torch/export/custom_ops.py +56 -0
  20. .venv/lib/python3.12/site-packages/torch/export/decomp_utils.py +160 -0
  21. .venv/lib/python3.12/site-packages/torch/export/dynamic_shapes.py +1635 -0
  22. .venv/lib/python3.12/site-packages/torch/export/experimental/__init__.py +454 -0
  23. .venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/__init__.cpython-312.pyc +0 -0
  24. .venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/_utils.cpython-312.pyc +0 -0
  25. .venv/lib/python3.12/site-packages/torch/export/experimental/_utils.py +238 -0
  26. .venv/lib/python3.12/site-packages/torch/export/exported_program.py +1820 -0
  27. .venv/lib/python3.12/site-packages/torch/export/graph_signature.py +759 -0
  28. .venv/lib/python3.12/site-packages/torch/export/passes/__init__.py +97 -0
  29. .venv/lib/python3.12/site-packages/torch/export/passes/__pycache__/__init__.cpython-312.pyc +0 -0
  30. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/__init__.py +4 -0
  31. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/__init__.cpython-312.pyc +0 -0
  32. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/_package.cpython-312.pyc +0 -0
  33. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/_package_weights.cpython-312.pyc +0 -0
  34. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/constants.cpython-312.pyc +0 -0
  35. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py +1241 -0
  36. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/_package_weights.py +213 -0
  37. .venv/lib/python3.12/site-packages/torch/export/pt2_archive/constants.py +36 -0
  38. .venv/lib/python3.12/site-packages/torch/export/unflatten.py +1909 -0
  39. .venv/lib/python3.12/site-packages/torch/fft/__init__.py +1442 -0
  40. .venv/lib/python3.12/site-packages/torch/fft/__pycache__/__init__.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/torch/func/__init__.py +33 -0
  42. .venv/lib/python3.12/site-packages/torch/func/__pycache__/__init__.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/torch/func/__pycache__/_random.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/torch/func/_random.py +284 -0
  45. .venv/lib/python3.12/site-packages/torch/functional.py +2273 -0
  46. .venv/lib/python3.12/site-packages/torch/futures/__init__.py +335 -0
  47. .venv/lib/python3.12/site-packages/torch/futures/__pycache__/__init__.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/torch/fx/__init__.py +116 -0
  49. .venv/lib/python3.12/site-packages/torch/fx/__pycache__/__init__.cpython-312.pyc +0 -0
  50. .venv/lib/python3.12/site-packages/torch/fx/__pycache__/_compatibility.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -579,3 +579,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
579
  .venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
580
  .venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
581
  .venv/lib/python3.12/site-packages/torch/export/__pycache__/_trace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
579
  .venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
580
  .venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
581
  .venv/lib/python3.12/site-packages/torch/export/__pycache__/_trace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
582
+ .venv/lib/python3.12/site-packages/torch/fx/__pycache__/graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
583
+ .venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/proxy_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
584
+ .venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-312.pyc ADDED
Binary file (72.5 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/__pycache__/exported_program.cpython-312.pyc ADDED
Binary file (73.5 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/__pycache__/graph_signature.cpython-312.pyc ADDED
Binary file (37.7 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/__pycache__/unflatten.cpython-312.pyc ADDED
Binary file (82.4 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/_draft_export.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import getpass
2
+ import json
3
+ import logging
4
+ import os
5
+ import re
6
+ import tempfile
7
+ import time
8
+ from collections.abc import Callable, Mapping
9
+ from dataclasses import dataclass
10
+ from enum import IntEnum
11
+ from typing import Any
12
+
13
+ import torch
14
+ import torch._logging._internal
15
+ import torch.utils._pytree as pytree
16
+ from torch._dynamo.exc import UserError, UserErrorType
17
+ from torch._export.passes.insert_custom_op_guards import (
18
+ get_op_profiles,
19
+ insert_custom_op_guards,
20
+ OpProfile,
21
+ )
22
+ from torch._utils_internal import log_draft_export_usage
23
+
24
+ from ._trace import _export, get_ep_stats
25
+ from .dynamic_shapes import _DimHint, _DimHintType, Dim
26
+ from .exported_program import ExportedProgram
27
+
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+
32
+ _DRAFT_EXPORT_WARNING_COLOR = "\033[31m"
33
+ _DRAFT_EXPORT_SUCCESS_COLOR = "\033[32m"
34
+ _DRAFT_EXPORT_END_COLOR = "\033[0m"
35
+
36
+
37
+ def _format_colored(text: str, color: str) -> str:
38
+ return f"{color}{text}{_DRAFT_EXPORT_END_COLOR}"
39
+
40
+
41
+ class FailureType(IntEnum):
42
+ MISSING_FAKE_KERNEL = 1
43
+ DATA_DEPENDENT_ERROR = 2
44
+ GUARD_ADDED = 3
45
+ MISMATCHED_FAKE_KERNEL = 4
46
+
47
+ def __str__(self) -> str:
48
+ return self.name
49
+
50
+
51
+ def prettify_stack(stack: list[dict[str, str]], str_to_filename: dict[int, str]) -> str:
52
+ res = ""
53
+ for frame in stack:
54
+ if frame["filename"] not in str_to_filename:
55
+ continue
56
+
57
+ res += f"""
58
+ File {str_to_filename[frame["filename"]]}, lineno {frame["line"]}, in {frame["name"]}""" # type: ignore[index]
59
+
60
+ res += f"\n {stack[-1]['loc']}"
61
+ return res
62
+
63
+
64
+ def prettify_frame_locals(
65
+ loc: str, locals: dict[str, Any], symbols: dict[str, Any]
66
+ ) -> str:
67
+ local_str = "\n".join(f" {k}: {v}" for k, v in locals.items())
68
+ res = f"""
69
+ Locals:
70
+ {local_str}
71
+ """
72
+ if any(v is not None for v in symbols.values()):
73
+ symbol_str = "\n".join(
74
+ f" {k}: {v}" for k, v in symbols.items() if v is not None
75
+ )
76
+ res += f"""
77
+ Symbols:
78
+ {symbol_str}
79
+ """
80
+ return res
81
+
82
+
83
+ def get_loc(filename: str, lineno: int) -> str | None:
84
+ try:
85
+ with open(filename) as f:
86
+ for i, line in enumerate(f):
87
+ if i == lineno - 1:
88
+ return line.strip()
89
+ except FileNotFoundError:
90
+ pass
91
+ return None
92
+
93
+
94
+ class FailureReport:
95
+ def __init__(
96
+ self, failure_type: FailureType, data: dict[str, Any], xfail: bool = False
97
+ ) -> None:
98
+ self.failure_type: FailureType = failure_type
99
+ self.data: dict[str, Any] = data
100
+ self.xfail: bool = xfail
101
+
102
+ def __repr__(self) -> str:
103
+ return f"FailureReport(failure_type={self.failure_type}, xfail={self.xfail}, data={self.data})"
104
+
105
+ def print(self, str_to_filename: dict[int, str]) -> str:
106
+ if self.failure_type == FailureType.MISSING_FAKE_KERNEL:
107
+ op = self.data["op"]
108
+
109
+ return f"""Missing fake kernel.
110
+ torch.ops.{op} is missing a fake kernel implementation.
111
+
112
+ Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a meta implementation.
113
+ """
114
+
115
+ elif self.failure_type == FailureType.GUARD_ADDED:
116
+ locals_info = (
117
+ prettify_frame_locals(**self.data["frame_locals"])
118
+ if self.data["frame_locals"]
119
+ else ""
120
+ )
121
+ return f"""Guard Added.
122
+ A guard was added during tracing, which might've resulted in some incorrect
123
+ tracing or constraint violation error.
124
+ Specifically, this guard was added: {self.data["expr"]}, where {self.data["symbol_to_sources"]}.
125
+ This occurred at the following stacktrace: {prettify_stack(self.data["user_stack"], str_to_filename)}:
126
+ {locals_info}
127
+ And the following framework stacktrace: {prettify_stack(self.data["stack"], str_to_filename)}\n
128
+ Because of this, we have modified the dynamic shapes structure to be the
129
+ following. You can also use torch.export.Dim.AUTO instead to specify your
130
+ dynamic shapes, and we will automatically infer the dynamism for you.
131
+ ```
132
+ dynamic_shapes = {self.data["new_dynamic_shapes"]}
133
+ ```
134
+ """
135
+
136
+ elif self.failure_type == FailureType.DATA_DEPENDENT_ERROR:
137
+ locals_info = (
138
+ prettify_frame_locals(**self.data["frame_locals"])
139
+ if self.data["frame_locals"]
140
+ else ""
141
+ )
142
+ return f"""Data dependent error.
143
+ When exporting, we were unable to evaluate the value of `{self.data["expr"]}`.
144
+ This was encountered {self.data["occurrences"]} times.
145
+ This occurred at the following user stacktrace: {prettify_stack(self.data["user_stack"], str_to_filename)}
146
+ {locals_info}
147
+ And the following framework stacktrace: {prettify_stack(self.data["stack"], str_to_filename)}\n
148
+ As a result, it was specialized to a constant (e.g. `{self.data["result"]}` in the 1st occurrence), and asserts were inserted into the graph.
149
+
150
+ Please add `torch._check(...)` to the original code to assert this data-dependent assumption.
151
+ Please refer to https://docs.google.com/document/d/1kZ_BbB3JnoLbUZleDT6635dHs88ZVYId8jT-yTFgf3A/edit#heading=h.boi2xurpqa0o for more details.
152
+ """
153
+
154
+ elif self.failure_type == FailureType.MISMATCHED_FAKE_KERNEL:
155
+ op = self.data["op"]
156
+ reason = self.data["reason"]
157
+ return f"""Mismatched fake kernel.
158
+ torch.ops.{op} has a fake kernel implementation, but it has incorrect behavior, based on the real kernel.
159
+ The reason for the mismatch is: {reason}.
160
+
161
+ Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a fake implementation.
162
+ """
163
+
164
+ else:
165
+ raise ValueError(f"Unknown failure type: {self.failure_type}")
166
+
167
+
168
+ class DraftExportReport:
169
+ def __init__(
170
+ self,
171
+ failures: list[FailureReport],
172
+ str_to_filename: dict[int, str],
173
+ expressions_created: dict[int, dict[str, Any]],
174
+ op_profiles: dict[str, set[OpProfile]],
175
+ ):
176
+ self.failures: list[FailureReport] = failures
177
+ self.str_to_filename = str_to_filename
178
+ self.expressions_created: dict[int, dict[str, Any]] = expressions_created
179
+ self.op_profiles = op_profiles
180
+
181
+ def successful(self) -> bool:
182
+ return len(self.failures) == 0 or all(
183
+ failure.xfail for failure in self.failures
184
+ )
185
+
186
+ def __repr__(self) -> str:
187
+ return f"DraftExportReport({self.failures})"
188
+
189
+ def __str__(self) -> str:
190
+ if self.successful():
191
+ return _format_colored(
192
+ """
193
+ ##############################################################################################
194
+ Congratulations: No issues are found during export, and it was able to soundly produce a graph.
195
+ You can now change back to torch.export.export()
196
+ ##############################################################################################
197
+ """,
198
+ _DRAFT_EXPORT_SUCCESS_COLOR,
199
+ )
200
+
201
+ error = _format_colored(
202
+ f"""
203
+ ###################################################################################################
204
+ WARNING: {len(self.failures)} issue(s) found during export, and it was not able to soundly produce a graph.
205
+ Please follow the instructions to fix the errors.
206
+ ###################################################################################################
207
+
208
+ """,
209
+ _DRAFT_EXPORT_WARNING_COLOR,
210
+ )
211
+ error += "\n"
212
+
213
+ for i, failure in enumerate(self.failures):
214
+ error += f"{i + 1}. {failure.print(self.str_to_filename)}\n"
215
+ return error
216
+
217
+ def apply_suggested_fixes(self) -> None:
218
+ raise NotImplementedError("Not implemented yet")
219
+
220
+
221
+ @dataclass
222
+ class ExpressionCreatedNode:
223
+ result_id: int
224
+ argument_ids: list[int]
225
+ record: dict[str, object]
226
+ visited: bool = False
227
+
228
+
229
+ class LogRecord:
230
+ def __init__(self) -> None:
231
+ self.log_count: dict[int, int] = {}
232
+ self.logs: list[tuple[str, dict[str, Any]]] = []
233
+
234
+ def _hash(self, element: tuple[str, dict[str, Any]]) -> int:
235
+ key, data = element
236
+
237
+ if key == "missing_fake_kernel":
238
+ return hash((key, data["op"]))
239
+ elif key == "mismatched_fake_kernel":
240
+ return hash((key, data["op"], data["reason"]))
241
+ elif key == "propagate_real_tensors_provenance":
242
+ return hash((key, json.dumps(data["user_stack"])))
243
+ elif key == "guard_added":
244
+ return hash((key, json.dumps(data["user_stack"])))
245
+ elif key == "create_unbacked_symbol":
246
+ return hash((key, json.dumps(data["user_stack"])))
247
+
248
+ return hash((key, json.dumps(data)))
249
+
250
+ def try_add(self, element: tuple[str, dict[str, str]]) -> bool:
251
+ hash_value = self._hash(element)
252
+ if hash_value in self.log_count:
253
+ self.log_count[hash_value] += 1
254
+ return False
255
+
256
+ self.log_count[hash_value] = 1
257
+ self.logs.append(element)
258
+ return True
259
+
260
+ def get_log_count(self, element: tuple[str, dict[str, Any]]) -> int:
261
+ return self.log_count[self._hash(element)]
262
+
263
+
264
+ class CaptureStructuredTrace(torch._logging._internal.LazyTraceHandler):
265
+ def __init__(self) -> None:
266
+ self.specific_log_keys = [
267
+ "str",
268
+ "exported_program",
269
+ "propagate_real_tensors_provenance",
270
+ "guard_added",
271
+ "missing_fake_kernel",
272
+ "mismatched_fake_kernel",
273
+ "expression_created",
274
+ "create_unbacked_symbol",
275
+ ]
276
+ self.log_record: LogRecord = LogRecord()
277
+ self.expression_created_logs: dict[int, ExpressionCreatedNode] = {}
278
+ self.symbol_to_expressions: dict[str, list[dict[str, Any]]] = {}
279
+ self.logger = logging.getLogger("torch.__trace")
280
+ self.prev_get_dtrace = False
281
+
282
+ if root_dir := os.environ.get(torch._logging._internal.DTRACE_ENV_VAR):
283
+ super().__init__(root_dir)
284
+ else:
285
+ sanitized_username = re.sub(r'[\\/:*?"<>|]', "_", getpass.getuser())
286
+ root_dir = os.path.join(
287
+ tempfile.gettempdir(),
288
+ "export_" + sanitized_username,
289
+ )
290
+ super().__init__(root_dir)
291
+
292
+ self.setFormatter(torch._logging._internal.TorchLogsFormatter(trace=True))
293
+
294
+ def __enter__(self) -> "CaptureStructuredTrace":
295
+ self.log_record = LogRecord()
296
+ self.expression_created_logs = {}
297
+
298
+ # Remove the lazy trace handler if it exists
299
+ possible_lazy_trace_handlers = [
300
+ handler
301
+ for handler in self.logger.handlers
302
+ if isinstance(handler, torch._logging._internal.LazyTraceHandler)
303
+ ]
304
+ for handler in possible_lazy_trace_handlers:
305
+ self.logger.removeHandler(handler)
306
+
307
+ self.logger.addHandler(self)
308
+ self.prev_get_dtrace = torch._logging._internal.GET_DTRACE_STRUCTURED
309
+ # pyrefly: ignore [bad-assignment]
310
+ torch._logging._internal.GET_DTRACE_STRUCTURED = True
311
+ return self
312
+
313
+ def __exit__(self, exc_type, exc_value, traceback) -> None: # type: ignore[no-untyped-def]
314
+ self.log_record = LogRecord()
315
+ self.expression_created_logs = {}
316
+ self.logger.removeHandler(self)
317
+ # pyrefly: ignore [bad-assignment]
318
+ torch._logging._internal.GET_DTRACE_STRUCTURED = self.prev_get_dtrace
319
+ self.prev_get_dtrace = False
320
+
321
+ def emit(self, record: Any) -> None:
322
+ def _log_expression_created(
323
+ emit_func: Callable[[Any], None], sym_node_id: int
324
+ ) -> None:
325
+ # Log all the relevant expression_created logs
326
+ if sym_node_id is None:
327
+ return
328
+ if res := self.expression_created_logs.get(sym_node_id, None):
329
+ # Don't log the expression if we have already
330
+ # printed it beforehand
331
+ if not res.visited:
332
+ res.visited = True
333
+ for arg in res.argument_ids:
334
+ _log_expression_created(emit_func, arg)
335
+
336
+ emit_func(res.record)
337
+
338
+ metadata = record.metadata
339
+ for key in self.specific_log_keys:
340
+ if key in metadata:
341
+ if self.log_record.try_add((key, metadata[key])):
342
+ if key == "expression_created":
343
+ # We don't want to log all expression_created logs, only
344
+ # the ones that are relevant to the
345
+ # guards/propagate_real_tensor
346
+ self.expression_created_logs[metadata[key]["result_id"]] = (
347
+ ExpressionCreatedNode(
348
+ metadata[key]["result_id"],
349
+ metadata[key].get("argument_ids", []),
350
+ record,
351
+ )
352
+ )
353
+ return
354
+
355
+ elif key == "propagate_real_tensors_provenance":
356
+ _log_expression_created(
357
+ super().emit, metadata[key].get("expr_node_id")
358
+ )
359
+
360
+ elif key == "guard_added":
361
+ if len(metadata[key]["symbol_to_sources"]) == 0:
362
+ # We only want to include guards added that are relevant to
363
+ # the symbolic shapes corresponding to the inputs which were
364
+ # specified in the dynamic_shapes arg. These have a source.
365
+ return
366
+ elif metadata[key]["prefix"] == "runtime_assert":
367
+ # This should've been captured by a
368
+ # propagate_real_tensors log
369
+ return
370
+
371
+ _log_expression_created(
372
+ super().emit, metadata[key].get("expr_node_id")
373
+ )
374
+
375
+ super().emit(record)
376
+
377
+
378
+ def draft_export(
379
+ mod: torch.nn.Module,
380
+ args: tuple[Any, ...],
381
+ kwargs: Mapping[str, Any] | None = None,
382
+ *,
383
+ dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None = None,
384
+ preserve_module_call_signature: tuple[str, ...] = (),
385
+ strict: bool = False,
386
+ pre_dispatch: bool = True,
387
+ prefer_deferred_runtime_asserts_over_guards: bool = False,
388
+ ) -> ExportedProgram:
389
+ start_time = time.time()
390
+ kwargs = kwargs or {}
391
+ dynamic_shapes = dynamic_shapes or {}
392
+
393
+ constraint_violation_msg = None
394
+ capture_structured_log = CaptureStructuredTrace()
395
+
396
+ with (
397
+ torch._functorch.config.patch(
398
+ fake_tensor_propagate_real_tensors=True,
399
+ generate_fake_kernels_from_real_mismatches=True,
400
+ ),
401
+ capture_structured_log,
402
+ ):
403
+ try:
404
+ new_shapes = None
405
+ ep = _export(
406
+ mod,
407
+ args,
408
+ kwargs,
409
+ dynamic_shapes=dynamic_shapes,
410
+ strict=strict,
411
+ pre_dispatch=pre_dispatch,
412
+ preserve_module_call_signature=preserve_module_call_signature,
413
+ prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards,
414
+ )
415
+ except Exception as exc:
416
+ if (
417
+ isinstance(exc, UserError)
418
+ and exc.error_type == UserErrorType.CONSTRAINT_VIOLATION
419
+ ):
420
+ constraint_violation_msg = exc.msg
421
+
422
+ def convert_dim_to_auto(dim: Any) -> Any:
423
+ if isinstance(dim, Dim):
424
+ return Dim.AUTO(min=dim.min, max=dim.max)
425
+ elif isinstance(dim, _DimHint) and dim.type == _DimHintType.DYNAMIC:
426
+ return Dim.AUTO(min=dim.min, max=dim.max)
427
+ return dim
428
+
429
+ new_shapes = pytree.tree_map(convert_dim_to_auto, dynamic_shapes)
430
+ ep = _export(
431
+ mod,
432
+ args,
433
+ kwargs,
434
+ dynamic_shapes=new_shapes,
435
+ strict=strict,
436
+ pre_dispatch=pre_dispatch,
437
+ preserve_module_call_signature=preserve_module_call_signature,
438
+ prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards,
439
+ )
440
+ else:
441
+ log_draft_export_usage(
442
+ error=True,
443
+ export_time=time.time() - start_time,
444
+ strict=strict,
445
+ message=str(exc),
446
+ type=f"{type(exc).__name__}.{type(exc).__qualname__}",
447
+ )
448
+ raise exc
449
+
450
+ torch._logging.dtrace_structured("exported_program", payload_fn=lambda: str(ep))
451
+
452
+ str_to_filename: dict[int, str] = {}
453
+ failures: list[FailureReport] = []
454
+ incorrect_custom_ops: set[str] = set()
455
+ expressions_created: dict[int, dict[str, Any]] = {}
456
+
457
+ for log_name, log_contents in capture_structured_log.log_record.logs:
458
+ failure_type = None
459
+
460
+ if log_name == "str":
461
+ str_to_filename[log_contents[1]] = log_contents[0] # type: ignore[index]
462
+ continue
463
+
464
+ elif log_name == "propagate_real_tensors_provenance":
465
+ log_contents["occurrences"] = (
466
+ capture_structured_log.log_record.get_log_count(
467
+ (log_name, log_contents)
468
+ )
469
+ )
470
+
471
+ failure_type = FailureType.DATA_DEPENDENT_ERROR
472
+
473
+ elif log_name == "guard_added":
474
+ if new_shapes is None:
475
+ continue
476
+
477
+ failure_type = FailureType.GUARD_ADDED
478
+ log_contents["new_dynamic_shapes"] = new_shapes
479
+ elif log_name == "missing_fake_kernel":
480
+ failure_type = FailureType.MISSING_FAKE_KERNEL
481
+ incorrect_custom_ops.add(log_contents["op"])
482
+
483
+ elif log_name == "mismatched_fake_kernel":
484
+ failure_type = FailureType.MISMATCHED_FAKE_KERNEL
485
+ incorrect_custom_ops.add(log_contents["op"])
486
+
487
+ else:
488
+ continue
489
+
490
+ if failure_type is None:
491
+ raise AssertionError("failure_type cannot be None at this point")
492
+ failures.append(
493
+ FailureReport(
494
+ failure_type,
495
+ log_contents,
496
+ )
497
+ )
498
+
499
+ for k, v in capture_structured_log.expression_created_logs.items():
500
+ if v.visited:
501
+ expressions_created[k] = v.record
502
+
503
+ op_profiles = get_op_profiles(ep.graph_module, incorrect_custom_ops)
504
+ report = DraftExportReport(
505
+ failures, str_to_filename, expressions_created, op_profiles
506
+ )
507
+
508
+ # Add asserts around custom ops
509
+ insert_custom_op_guards(ep.graph_module, incorrect_custom_ops)
510
+
511
+ ep._report = report
512
+ if not report.successful():
513
+ log_filename = capture_structured_log.stream.name
514
+
515
+ warning_msg = f"""
516
+ ###################################################################################################
517
+ WARNING: {len(report.failures)} issue(s) found during export, and it was not able to soundly produce a graph.
518
+ To view the report of failures in an html page, please run the command:
519
+ `tlparse {log_filename} --export`
520
+ Or, you can view the errors in python by inspecting `print(ep._report)`.
521
+ """
522
+
523
+ if len(report.op_profiles) > 0:
524
+ warning_msg += f"""
525
+ While tracing we found {len(report.op_profiles)} operator(s) which do not have a fake kernel registered.
526
+ If you intend to retrace the exported graph or run it with fake tensors, please run it under the
527
+ following context manager, which will register a fake kernel for those operators.
528
+ ```
529
+ with torch._library.fake_profile.unsafe_generate_fake_kernels(ep._report.op_profiles):
530
+ # run with fake tensors
531
+ ```
532
+ """
533
+
534
+ warning_msg += """#################################################################################################"""
535
+
536
+ log.warning(warning_msg)
537
+
538
+ else:
539
+ log.info(
540
+ """
541
+ ##############################################################################################
542
+ Congratulations: No issues are found during export, and it was able to soundly produce a graph.
543
+ You can now change back to torch.export.export()
544
+ ##############################################################################################
545
+ """
546
+ )
547
+
548
+ log_draft_export_usage(
549
+ error=False,
550
+ export_time=time.time() - start_time,
551
+ strict=strict,
552
+ constraint_violations=constraint_violation_msg,
553
+ report=ep._report,
554
+ **get_ep_stats(ep),
555
+ )
556
+ return ep
.venv/lib/python3.12/site-packages/torch/export/_leakage_detection_utils.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import types
3
+ import typing
4
+ import weakref
5
+ from typing_extensions import TypeIs
6
+
7
+ from torch.fx.experimental.symbolic_shapes import TrackedFake
8
+
9
+
10
+ """
11
+ These functions are used to detect potential fake tensor leakage when using PT2 export.
12
+ See NOTE [export non-strict fake tensor leak detection]
13
+
14
+ There are some complications that made this logic overly complicated:
15
+ 1) Python 3.10 and Python 3.12 have different ways of implementing referrer so
16
+ we need to account for whether it is ref.__dict__ or the real ref object
17
+
18
+ 2) There are some internal PT2 references to fake tensors like `TrackedFake`
19
+ 3) closures, generators, and bound methods can hold fake tensors.
20
+ 4) global object can hold onto a fake tensor
21
+
22
+ In general, these utils are our last resort to detect fake tensors. if the leak happens
23
+ within the model attributes, we have a separate mechanism to detect. This tool relies a bit
24
+ on garbage collector internal details, so I think it is unsafe to turn on by default, hence
25
+ this tool should be used as debugging tool.
26
+ """
27
+
28
+
29
+ # Things we never want to flag as leaks
30
+ _SKIP_TYPES = (
31
+ types.FrameType,
32
+ types.ModuleType,
33
+ )
34
+
35
+
36
+ def _is_globals_or_locals(obj: typing.Any) -> bool:
37
+ # These comparisons only make sense within this frame; still cheap to check.
38
+ return obj is globals() or obj is locals()
39
+
40
+
41
+ def _is_tracked_fake(obj: typing.Any) -> TypeIs[TrackedFake]:
42
+ return isinstance(obj, TrackedFake)
43
+
44
+
45
+ def _is_gm_meta_like_dict(d: dict, o: typing.Any) -> bool:
46
+ # Hope gm.meta was a custom dict we can assert on
47
+ return d.get("val") is o
48
+
49
+
50
+ def _dict_is_attr_of_tracked_fake(d: dict) -> bool:
51
+ """
52
+ Python 3.10 quirk: sometimes the referrer is obj.__dict__ instead of obj.
53
+ Check if this dict is exactly the __dict__ of a TrackedFake.
54
+ """
55
+ for parent in gc.get_referrers(d):
56
+ if (
57
+ hasattr(parent, "__dict__")
58
+ and parent.__dict__ is d
59
+ and _is_tracked_fake(parent)
60
+ ):
61
+ return True
62
+ return False
63
+
64
+
65
+ def find_legit_leaks_from_referrers(active_fakes: weakref.WeakSet) -> weakref.WeakSet:
66
+ legit_leak: weakref.WeakSet = weakref.WeakSet()
67
+
68
+ # This is so that we don't falsely flag generator to be holding fake tensor
69
+ fake_list = list(active_fakes)
70
+ fake_list_id = id(fake_list)
71
+
72
+ for act in fake_list:
73
+ # Track by id to avoid processing duplicate referrers
74
+ seen = set()
75
+ # Assume it's a leak unless we find only ignorable referrers
76
+ flagged = False
77
+
78
+ for r in gc.get_referrers(act):
79
+ rid = id(r)
80
+ if rid in seen:
81
+ continue
82
+ seen.add(rid)
83
+
84
+ # Skip our own fake_list
85
+ if rid == fake_list_id:
86
+ continue
87
+
88
+ # Fast-path: skip obvious non-owners
89
+ if _is_globals_or_locals(r):
90
+ continue
91
+ if isinstance(r, _SKIP_TYPES):
92
+ continue
93
+ if _is_tracked_fake(r):
94
+ # TrackedFake should be ignored
95
+ continue
96
+
97
+ # Handle dicts carefully (Python 3.10 sometimes shows __dict__)
98
+ if isinstance(r, dict):
99
+ if _is_gm_meta_like_dict(r, act):
100
+ continue
101
+ if _dict_is_attr_of_tracked_fake(r):
102
+ continue
103
+ flagged = True
104
+ break
105
+
106
+ # Any other referrer we don't explicitly whitelist counts as a leak
107
+ flagged = True
108
+ break
109
+
110
+ if flagged:
111
+ legit_leak.add(act)
112
+
113
+ return legit_leak
.venv/lib/python3.12/site-packages/torch/export/_patches.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ from collections.abc import Generator
3
+
4
+ import torch
5
+ from torch._decomp import global_decomposition_table
6
+ from torch._decomp.decompositions import _rnn_helper, gather_params, gru_cell, lstm_cell
7
+ from torch._higher_order_ops.while_loop import while_loop
8
+
9
+
10
+ def _clone_tensors_that_alias(tensors):
11
+ # Flattened RNN weights can share storage. while_loop rejects aliased
12
+ # closure inputs, and these weights are read-only inside the loop.
13
+ cloned_tensors = []
14
+ seen_tensors = []
15
+ for tensor in tensors:
16
+ if tensor is not None and any(
17
+ torch._C._overlaps(tensor, seen_tensor) for seen_tensor in seen_tensors
18
+ ):
19
+ tensor = tensor.clone()
20
+ cloned_tensors.append(tensor)
21
+ if tensor is not None:
22
+ seen_tensors.append(tensor)
23
+ return tuple(cloned_tensors)
24
+
25
+
26
+ def one_layer_while_loop_lstm(inp, hidden, params, has_biases, reverse=False):
27
+ """
28
+ 1 layer fn for while loop LSTM
29
+
30
+ Args:
31
+ inp: Input tensor of shape (seq_len, batch, input_size)
32
+ hidden: Tuple of (hx, cx) hidden states
33
+ params: List of weight and bias tensors
34
+ has_biases: Whether biases are included
35
+ reverse: Whether to process sequence in reverse
36
+
37
+ Returns:
38
+ Tuple of (output, (final_hx, final_cx))
39
+ """
40
+ ih_weight = params[0]
41
+ hh_weight = params[1]
42
+ ih_bias = params[2] if has_biases else None
43
+ hh_bias = params[3] if has_biases else None
44
+ hr_weight = (
45
+ params[4] if len(params) == 5 else params[2] if len(params) == 3 else None
46
+ )
47
+
48
+ hx = hidden[0].unsqueeze(0)
49
+ cx = hidden[1].unsqueeze(0)
50
+
51
+ precomputed_input = torch.nn.functional.linear(inp, ih_weight, ih_bias)
52
+ precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input
53
+ hh_weight, hh_bias, hr_weight = _clone_tensors_that_alias(
54
+ (hh_weight, hh_bias, hr_weight)
55
+ )
56
+
57
+ # while loop rewrite
58
+ step_output = torch.empty(
59
+ precomputed_input.size(0),
60
+ *tuple(hx.shape[1:]),
61
+ dtype=hx.dtype,
62
+ device=hx.device,
63
+ )
64
+
65
+ def cond_fn(i, out, hx, cx):
66
+ return i < precomputed_input.size(0)
67
+
68
+ def body_fn(idx, out, hx, cx):
69
+ # Extract the integer value from idx and constrain it for data-dependent indexing
70
+ i = idx.item()
71
+ torch._check_is_size(i)
72
+ torch._check_is_size(i, max=precomputed_input.size(0) - 1)
73
+ hx, cx = lstm_cell(
74
+ precomputed_input[i], hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=2
75
+ )
76
+ out = out.clone()
77
+ # Squeeze the first dimension before storing (lstm_cell preserves the unsqueezed dim)
78
+ out[i] = hx.squeeze(0)
79
+ return idx + 1, out, hx, cx
80
+
81
+ cnt = torch.tensor(0, dtype=torch.int64)
82
+ _, out, final_hx, final_cx = while_loop(
83
+ cond_fn, body_fn, [cnt, step_output, hx, cx]
84
+ )
85
+ if reverse:
86
+ out = out.flip(0)
87
+
88
+ return out, (final_hx.squeeze(0), final_cx.squeeze(0))
89
+
90
+
91
+ def lstm_while_loop_impl(
92
+ input,
93
+ hx,
94
+ params,
95
+ has_biases,
96
+ num_layers,
97
+ dropout,
98
+ train,
99
+ bidirectional,
100
+ batch_first,
101
+ ):
102
+ """
103
+ LSTM implementation using while_loop for export compatibility.
104
+
105
+ This is a drop-in replacement for the default LSTM decomposition that uses
106
+ while_loop instead of Python loops, making it more suitable for torch.export.
107
+
108
+ Args:
109
+ input: Input tensor
110
+ hx: Tuple of (h0, c0) hidden states
111
+ params: List of weight and bias tensors
112
+ has_biases: Whether biases are included
113
+ num_layers: Number of LSTM layers
114
+ dropout: Dropout probability
115
+ train: Training mode
116
+ bidirectional: Whether to use bidirectional LSTM
117
+ batch_first: Whether batch dimension is first
118
+
119
+ Returns:
120
+ Tuple of (output, h_n, c_n)
121
+ """
122
+ if len(hx) != 2:
123
+ raise AssertionError("lstm expects two hidden states")
124
+ params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2))
125
+ hidden = list(zip(hx[0], hx[1]))
126
+ layer_fn = one_layer_while_loop_lstm
127
+ out, final_hiddens = _rnn_helper(
128
+ input,
129
+ hidden,
130
+ params,
131
+ has_biases,
132
+ num_layers,
133
+ dropout,
134
+ train,
135
+ bidirectional,
136
+ batch_first,
137
+ layer_fn,
138
+ )
139
+ final_hiddens = list(zip(*final_hiddens))
140
+ return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0)
141
+
142
+
143
+ def one_layer_while_loop_gru(inp, hidden, params, has_biases, reverse=False):
144
+ """
145
+ 1 layer fn for while loop GRU
146
+
147
+ Args:
148
+ inp: Input tensor of shape (seq_len, batch, input_size)
149
+ hidden: Hidden state tensor
150
+ params: List of weight and bias tensors
151
+ has_biases: Whether biases are included
152
+ reverse: Whether to process sequence in reverse
153
+
154
+ Returns:
155
+ Tuple of (output, final_hidden)
156
+ """
157
+ ih_weight = params[0]
158
+ hh_weight = params[1]
159
+ ih_bias = params[2] if has_biases else None
160
+ hh_bias = params[3] if has_biases else None
161
+
162
+ precomputed_input = torch.nn.functional.linear(inp, ih_weight, ih_bias)
163
+ precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input
164
+ hh_weight, hh_bias = _clone_tensors_that_alias((hh_weight, hh_bias))
165
+ cur_hidden = hidden.unsqueeze(0)
166
+
167
+ # while loop rewrite
168
+ step_output = torch.empty(
169
+ precomputed_input.size(0),
170
+ *tuple(cur_hidden.shape[1:]),
171
+ dtype=cur_hidden.dtype,
172
+ device=cur_hidden.device,
173
+ )
174
+
175
+ def cond_fn(i, out, cur_hidden):
176
+ return i < precomputed_input.size(0)
177
+
178
+ def body_fn(idx, out, cur_hidden):
179
+ # Extract the integer value from idx and constrain it for data-dependent indexing
180
+ i = idx.item()
181
+ torch._check_is_size(i)
182
+ torch._check_is_size(i, max=precomputed_input.size(0) - 1)
183
+ cur_hidden = gru_cell(
184
+ precomputed_input[i], cur_hidden, None, None, hh_weight, hh_bias
185
+ )
186
+ out = out.clone()
187
+ out[i] = cur_hidden.squeeze(0)
188
+ return idx + 1, out, cur_hidden
189
+
190
+ cnt = torch.tensor(0, dtype=torch.int64)
191
+ _, out, final_hidden = while_loop(cond_fn, body_fn, [cnt, step_output, cur_hidden])
192
+ if reverse:
193
+ out = out.flip(0)
194
+
195
+ return out, final_hidden.squeeze(0)
196
+
197
+
198
+ def gru_while_loop_impl(
199
+ input,
200
+ hx,
201
+ params,
202
+ has_biases,
203
+ num_layers,
204
+ dropout,
205
+ train,
206
+ bidirectional,
207
+ batch_first,
208
+ ):
209
+ """
210
+ GRU implementation using while_loop for export compatibility.
211
+
212
+ This is a drop-in replacement for the default GRU decomposition that uses
213
+ while_loop instead of Python loops, making it more suitable for torch.export.
214
+
215
+ Args:
216
+ input: Input tensor
217
+ hx: Hidden state tensor
218
+ params: List of weight and bias tensors
219
+ has_biases: Whether biases are included
220
+ num_layers: Number of GRU layers
221
+ dropout: Dropout probability
222
+ train: Training mode
223
+ bidirectional: Whether to use bidirectional GRU
224
+ batch_first: Whether batch dimension is first
225
+
226
+ Returns:
227
+ Tuple of (output, h_n)
228
+ """
229
+ params = gather_params(params, has_biases, False)
230
+ hidden = list(hx.unbind(0))
231
+ layer_fn = one_layer_while_loop_gru
232
+ out, final_hiddens = _rnn_helper(
233
+ input,
234
+ hidden,
235
+ params,
236
+ has_biases,
237
+ num_layers,
238
+ dropout,
239
+ train,
240
+ bidirectional,
241
+ batch_first,
242
+ layer_fn,
243
+ )
244
+ return out, torch.stack(final_hiddens, 0)
245
+
246
+
247
+ @contextlib.contextmanager
248
+ def _register_rnn_while_loop_decomposition(
249
+ rnn_op, rnn_impl
250
+ ) -> Generator[None, None, None]:
251
+ """
252
+ Generic context manager for registering while_loop-based RNN decompositions.
253
+
254
+ Args:
255
+ rnn_op: The aten operation to patch (e.g., torch.ops.aten.lstm.input)
256
+ rnn_impl: The while_loop-based implementation function
257
+
258
+ Note:
259
+ This is an internal helper. Use register_lstm_while_loop_decomposition()
260
+ or register_gru_while_loop_decomposition() instead.
261
+ """
262
+ registry = global_decomposition_table["post_autograd"]
263
+
264
+ # Save the original decomposition if it exists
265
+ original_decomp = registry.get(rnn_op, None)
266
+
267
+ # Save the original py_kernel if it exists
268
+ original_py_kernel = rnn_op.py_kernels.get(
269
+ torch._C.DispatchKey.CompositeImplicitAutograd, None
270
+ )
271
+
272
+ try:
273
+ # Register our while_loop-based implementation
274
+ registry[rnn_op] = rnn_impl
275
+ rnn_op.py_kernels[torch._C.DispatchKey.CompositeImplicitAutograd] = rnn_impl
276
+ yield
277
+ finally:
278
+ # Restore the original decomposition
279
+ if original_decomp is not None:
280
+ registry[rnn_op] = original_decomp
281
+ else:
282
+ # If there was no original, remove our registration
283
+ registry.pop(rnn_op, None)
284
+
285
+ # Restore the original py_kernel
286
+ if original_py_kernel is not None:
287
+ rnn_op.py_kernels[torch._C.DispatchKey.CompositeImplicitAutograd] = (
288
+ original_py_kernel
289
+ )
290
+ else:
291
+ # If there was no original, remove our registration
292
+ rnn_op.py_kernels.pop(torch._C.DispatchKey.CompositeImplicitAutograd, None)
293
+
294
+
295
+ @contextlib.contextmanager
296
+ def register_lstm_while_loop_decomposition() -> Generator[None, None, None]:
297
+ """
298
+ Context manager that temporarily registers the while_loop-based LSTM decomposition.
299
+
300
+ The while_loop-based decomposition is more suitable for export and graph-based
301
+ execution, as it avoids Python control flow that cannot be captured in the graph.
302
+ This should support dynamic sequence lengths, however as while_loop does not
303
+ support Autograd yet, an ExportedProgram created with this will not be trainable.
304
+
305
+ Usage::
306
+
307
+ from torch.export._patches import register_lstm_while_loop_decomposition
308
+ from torch.export import export
309
+
310
+ with register_lstm_while_loop_decomposition():
311
+ # Export your model with LSTM
312
+ ep = export(model, (x, h0, c0))
313
+
314
+ Note:
315
+ This context manager temporarily modifies the global decomposition table
316
+ and py_kernels registration. The original registrations are restored when
317
+ exiting the context.
318
+ """
319
+ with _register_rnn_while_loop_decomposition(
320
+ torch.ops.aten.lstm.input, lstm_while_loop_impl
321
+ ):
322
+ yield
323
+
324
+
325
+ @contextlib.contextmanager
326
+ def register_gru_while_loop_decomposition() -> Generator[None, None, None]:
327
+ """
328
+ Context manager that temporarily registers the while_loop-based GRU decomposition.
329
+
330
+ The while_loop-based decomposition is more suitable for export and graph-based
331
+ execution, as it avoids Python control flow that cannot be captured in the graph.
332
+ This should support dynamic sequence lengths, however as while_loop does not
333
+ support Autograd yet, an ExportedProgram created with this will not be trainable.
334
+
335
+ Usage::
336
+
337
+ from torch.export._patches import register_gru_while_loop_decomposition
338
+ from torch.export import export
339
+
340
+ with register_gru_while_loop_decomposition():
341
+ # Export your model with GRU
342
+ ep = export(model, (x, h0))
343
+
344
+ Note:
345
+ This context manager temporarily modifies the global decomposition table
346
+ and py_kernels registration. The original registrations are restored when
347
+ exiting the context.
348
+ """
349
+ with _register_rnn_while_loop_decomposition(
350
+ torch.ops.aten.gru.input, gru_while_loop_impl
351
+ ):
352
+ yield
.venv/lib/python3.12/site-packages/torch/export/_remove_auto_functionalized_pass.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import torch
9
+ from torch._higher_order_ops.auto_functionalize import (
10
+ auto_functionalized,
11
+ auto_functionalized_v2,
12
+ )
13
+ from torch._inductor.fx_passes.post_grad import decompose_auto_functionalized
14
+ from torch.export import ExportedProgram
15
+ from torch.fx import Graph
16
+
17
+
18
+ def remove_self_clone(graph: Graph) -> None:
19
+ for node in graph.nodes:
20
+ if node.target is torch.ops.aten.copy_.default and node.args[0] == node.args[1]:
21
+ node.replace_all_uses_with(node.args[0])
22
+ graph.erase_node(node)
23
+
24
+
25
+ def unsafe_remove_auto_functionalized_pass(
26
+ ep: ExportedProgram,
27
+ ) -> ExportedProgram:
28
+ """
29
+ This pass removes an instances of the higher order op 'auto_functionalized',
30
+ and modifies the calling EP inplace to have the original mutator op.
31
+ This pass doesn't perform safety checks to make sure that this inplace mutation is safe.
32
+ """
33
+
34
+ with ep.graph_module._set_replace_hook(ep.graph_signature.get_replace_hook()):
35
+ for module in ep.graph_module.modules():
36
+ if not isinstance(module, torch.fx.GraphModule):
37
+ continue
38
+ for node in ep.graph.nodes:
39
+ if (
40
+ node.op == "call_function" and node.target is auto_functionalized
41
+ ) or (
42
+ node.op == "call_function" and node.target is auto_functionalized_v2
43
+ ):
44
+ func = node.args[0]
45
+ if not isinstance(func, torch._ops.OpOverload):
46
+ raise AssertionError(
47
+ f"Expected func to be an OpOverload, but got {type(func)}"
48
+ )
49
+ # re-inplace everything
50
+ node.meta["only_clone_these_tensors"] = []
51
+ decompose_auto_functionalized(ep.graph)
52
+ remove_self_clone(ep.graph)
53
+ ep.graph.eliminate_dead_code()
54
+
55
+ return ep
.venv/lib/python3.12/site-packages/torch/export/_remove_effect_tokens_pass.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+
4
+ import torch
5
+ from torch._higher_order_ops.effects import _get_schema, with_effects
6
+
7
+ from .exported_program import ExportedProgram
8
+ from .graph_signature import (
9
+ CustomObjArgument,
10
+ InputKind,
11
+ InputSpec,
12
+ OutputKind,
13
+ OutputSpec,
14
+ TokenArgument,
15
+ )
16
+
17
+
18
+ def _get_custom_obj_for_node(node, inputs_to_lifted_custom_objs, constants):
19
+ """Extract the custom object from a node's arguments."""
20
+ custom_obj_node = node
21
+ custom_obj_meta = custom_obj_node.meta["val"] # type: ignore[union-attr]
22
+ if not isinstance(custom_obj_meta, CustomObjArgument):
23
+ raise AssertionError(
24
+ f"Expected custom_obj_meta to be a CustomObjArgument, but got {type(custom_obj_meta)}"
25
+ )
26
+
27
+ if custom_obj_meta.fake_val:
28
+ return custom_obj_meta.fake_val
29
+ elif custom_obj_node.name in inputs_to_lifted_custom_objs: # type: ignore[union-attr]
30
+ return constants[inputs_to_lifted_custom_objs[custom_obj_node.name]] # type: ignore[union-attr]
31
+ else:
32
+ raise RuntimeError(f"Unable to find custom obj for node {node}")
33
+
34
+
35
+ def _replace_with_effects_node(
36
+ node, ep, inputs_to_lifted_custom_objs, output_tokens, input_tokens, module
37
+ ):
38
+ """Replace a with_effects node with the underlying function call."""
39
+ # Get the input nodes
40
+ token_node, func, *node_args = node.args
41
+ if token_node.op == "placeholder":
42
+ input_tokens.append(token_node)
43
+
44
+ if not isinstance(func, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)):
45
+ raise AssertionError(
46
+ f"Expected func to be an OpOverload or HigherOrderOperator, but got {type(func)}"
47
+ )
48
+
49
+ # Get the schema for the function
50
+ if func is torch.ops.higher_order.call_torchbind:
51
+ custom_obj = _get_custom_obj_for_node(
52
+ node_args[0], inputs_to_lifted_custom_objs, ep.constants
53
+ )
54
+ schema = _get_schema(func, [custom_obj] + node_args[1:])
55
+ else:
56
+ schema = _get_schema(func, node_args)
57
+
58
+ # Create the replacement node
59
+ with module.graph.inserting_before(node):
60
+ new_node = module.graph.call_function(func, tuple(node_args), node.kwargs)
61
+
62
+ # Update getitem nodes that extract outputs from with_effects
63
+ for user in list(node.users.keys()):
64
+ if user.target is not operator.getitem:
65
+ raise AssertionError(
66
+ f"Expected user target to be operator.getitem, but got {user.target}"
67
+ )
68
+ # getitem(with_effects, 0) is the token node
69
+ if user.args[1] == 0:
70
+ for user_user in list(user.users.keys()):
71
+ if user_user.op == "output":
72
+ output_tokens.append(user)
73
+
74
+ # Copy metadata from old node to new node
75
+ for k, v in node.meta.items():
76
+ new_node.meta[k] = v
77
+ if k == "unbacked_bindings":
78
+ # Remove the extra layer for effect token
79
+ old_bindings = new_node.meta[k]
80
+ new_bindings = {
81
+ k: path[1:] if path else path for k, path in old_bindings.items()
82
+ }
83
+ new_node.meta[k] = new_bindings
84
+
85
+ # Fix up the getitem nodes based on return count
86
+ if len(schema.returns) == 1:
87
+ # Single return: replace getitem(with_effects, 1) with the node itself
88
+ for user in list(node.users.keys()):
89
+ if user.args[1] == 1:
90
+ user.replace_all_uses_with(new_node)
91
+ new_node.meta["val"] = node.meta["val"][1]
92
+ elif len(schema.returns) > 1:
93
+ # Multiple returns: shift getitem indices down by 1
94
+ for user in list(node.users.keys()):
95
+ if user.args[1] >= 1:
96
+ user.args = (new_node, user.args[1] - 1)
97
+ new_node.meta["val"] = node.meta["val"][1:]
98
+ else:
99
+ # No returns
100
+ if len(schema.returns) != 0:
101
+ raise AssertionError(
102
+ f"Expected schema.returns to be empty, but got {len(schema.returns)} returns"
103
+ )
104
+ if len(new_node.users) != 0:
105
+ raise AssertionError(
106
+ f"Expected new_node to have no users, but got {len(new_node.users)} users"
107
+ )
108
+ new_node.meta["val"] = None
109
+
110
+
111
+ def _replace_invoke_subgraph_node(node, module, output_tokens, input_tokens):
112
+ """Replace an invoke_subgraph node to remove the token argument."""
113
+ if node.args[0].op != "get_attr":
114
+ raise AssertionError(
115
+ f"Expected node.args[0].op to be 'get_attr', but got {node.args[0].op}"
116
+ )
117
+ submod = getattr(module, node.args[0].target)
118
+ if not submod.meta.get("has_with_effects", False):
119
+ return
120
+
121
+ # Remove token from inputs
122
+ subgraph, identifier, token, *operands = node.args
123
+ node.args = (subgraph, identifier, *operands)
124
+ if token.op == "placeholder":
125
+ input_tokens.append(token)
126
+
127
+ # Update getitem nodes to account for removed token output
128
+ for user in list(node.users.keys()):
129
+ if user.args[1] >= 1:
130
+ user.args = (node, user.args[1] - 1)
131
+ elif user.args[1] == 0:
132
+ for user_user in list(user.users.keys()):
133
+ if user_user.op == "output":
134
+ output_tokens.append(user)
135
+
136
+
137
+ def _remove_effect_tokens(ep: ExportedProgram) -> ExportedProgram:
138
+ """
139
+ Removes the existence of tokens from the exported program, including:
140
+ - Removes the input and output tokens
141
+ - Replaces with_effects(token, func, args) with just func(args)
142
+
143
+ This function does an inplace modification on the given ExportedProgram.
144
+ """
145
+ inputs_to_lifted_custom_objs = ep.graph_signature.inputs_to_lifted_custom_objs
146
+
147
+ # mark submodules with effects as having effects. This will be used in the following pass to remove effects from subgraphs
148
+ for _, module in ep.graph_module.named_modules():
149
+ if not isinstance(module, torch.fx.GraphModule):
150
+ continue
151
+
152
+ with_effect_nodes = [
153
+ node for node in module.graph.nodes if node.target is with_effects
154
+ ]
155
+ if len(with_effect_nodes) > 0:
156
+ module.meta["has_with_effects"] = True
157
+
158
+ # Process each module with the replace hook to ensure graph signature is updated
159
+ with ep.graph_module._set_replace_hook(ep.graph_signature.get_replace_hook()):
160
+ for _, module in ep.graph_module.named_modules():
161
+ if not isinstance(module, torch.fx.GraphModule):
162
+ continue
163
+
164
+ input_tokens = []
165
+ output_tokens = []
166
+
167
+ # Process with_effects and invoke_subgraph nodes
168
+ for node in module.graph.nodes:
169
+ if node.target is with_effects:
170
+ _replace_with_effects_node(
171
+ node,
172
+ ep,
173
+ inputs_to_lifted_custom_objs,
174
+ output_tokens,
175
+ input_tokens,
176
+ module,
177
+ )
178
+ elif node.target is torch.ops.higher_order.invoke_subgraph:
179
+ _replace_invoke_subgraph_node(
180
+ node, module, output_tokens, input_tokens
181
+ )
182
+
183
+ # Remove tokens from the output node
184
+ if len(output_tokens) > 0:
185
+ output_node = next(reversed(module.graph.find_nodes(op="output")))
186
+ output_args = output_node.args[0]
187
+ if len(output_args) < len(output_tokens):
188
+ raise AssertionError(
189
+ f"{output_args} output arguments found\n"
190
+ f"{output_tokens} output tokens found\n"
191
+ f"{module.graph}"
192
+ )
193
+ output_node.args = (tuple(output_args[len(output_tokens) :]),)
194
+
195
+ module.graph.eliminate_dead_code()
196
+
197
+ # Remove tokens from the input placeholders
198
+ for node in module.graph.nodes:
199
+ if node.op == "placeholder" and node in input_tokens:
200
+ module.graph.erase_node(node)
201
+
202
+ module.recompile()
203
+
204
+ num_tokens: int = 0
205
+ input_token_names: list[str] = []
206
+ new_input_specs: list[InputSpec] = []
207
+ for inp in ep.graph_signature.input_specs:
208
+ if inp.kind == InputKind.TOKEN:
209
+ num_tokens += 1
210
+ if not isinstance(inp.arg, TokenArgument):
211
+ raise AssertionError(
212
+ f"Expected inp.arg to be a TokenArgument, but got {type(inp.arg)}"
213
+ )
214
+ input_token_names.append(inp.arg.name)
215
+ else:
216
+ new_input_specs.append(inp)
217
+
218
+ num_out_tokens: int = 0
219
+ new_output_specs: list[OutputSpec] = []
220
+ output_token_names: list[OutputSpec] = []
221
+ for out in ep.graph_signature.output_specs:
222
+ if out.kind == OutputKind.TOKEN:
223
+ num_out_tokens += 1
224
+ output_token_names.append(out.arg.name)
225
+ else:
226
+ new_output_specs.append(out)
227
+
228
+ # Update graph signature
229
+ ep.graph_signature.input_specs = new_input_specs
230
+ ep.graph_signature.output_specs = new_output_specs
231
+
232
+ if num_tokens != num_out_tokens:
233
+ raise AssertionError(
234
+ f"Number of input tokens ({num_tokens}) does not match output tokens ({num_out_tokens})"
235
+ )
236
+
237
+ return ep
.venv/lib/python3.12/site-packages/torch/export/_safeguard.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
4
+ from torch.overrides import TorchFunctionMode
5
+
6
+
7
+ class AutogradStateOpsFailSafeguard(TorchFunctionMode):
8
+ """
9
+ Detect grad state ops during exporting the graph and fail the process by
10
+ raising an error, to avoid unexpected behavior. Those grad mode ops could be:
11
+ `torch.no_grad`
12
+ `torch.enable_grad`
13
+ `torch.set_grad_enabled`
14
+
15
+ Export with predispatch mode is exempted.
16
+ """
17
+
18
+ def __torch_function__(self, func, types, args=(), kwargs=None):
19
+ kwargs = kwargs or {}
20
+ unsupported_grad_mode_ops = [
21
+ torch._C._set_grad_enabled,
22
+ ]
23
+ # It's only enabled while tracing, by confirming the torch dispatch mode is
24
+ # any active PROXY. This is to allow the autograd ops out of tracing.
25
+ current_state = torch._C.is_grad_enabled()
26
+ if func in unsupported_grad_mode_ops:
27
+ if len(args) != 1:
28
+ raise AssertionError(
29
+ f"Expected exactly 1 argument for grad mode op, but got {len(args)}"
30
+ )
31
+ changed_state = args[0]
32
+ mode = torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY)
33
+ # Intend to check if it's not the pre_dispatch mode. It's allowed to use
34
+ # autograd ops in pre_dispatch mode, e.g. `torch.no_grad`
35
+ if (
36
+ mode
37
+ and isinstance(mode, ProxyTorchDispatchMode)
38
+ and not mode.pre_dispatch
39
+ and changed_state != current_state
40
+ ):
41
+ raise RuntimeError(
42
+ f"Encountered autograd state manager op {func} trying to change global autograd state "
43
+ "while exporting. This is unsafe because we don't capture this op in torch.export "
44
+ "today, hence we can't reflect the user intention soundly. You can fix this by "
45
+ "adding a torch.no_grad() context around the export call."
46
+ )
47
+ return func(*args, **kwargs)
.venv/lib/python3.12/site-packages/torch/export/_state_dict_utils.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ State dict utilities for torch.export.
4
+
5
+ This module provides utilities for restoring state dicts to traced modules,
6
+ ensuring that FQNs (Fully Qualified Names) match the original module structure.
7
+ """
8
+
9
+ from collections.abc import Callable, Sequence
10
+ from typing import Any
11
+
12
+ import torch
13
+ import torch.fx
14
+
15
+
16
+ def _get_underlying_module(
17
+ module_or_method: torch.nn.Module | Callable[..., Any],
18
+ ) -> torch.nn.Module:
19
+ """Extract the underlying nn.Module from either a module or a bound method.
20
+
21
+ Args:
22
+ module_or_method: Either an nn.Module or a bound method of an nn.Module.
23
+
24
+ Returns:
25
+ The underlying nn.Module.
26
+
27
+ Raises:
28
+ TypeError: If module_or_method is neither an nn.Module nor a bound method.
29
+ """
30
+ if isinstance(module_or_method, torch.nn.Module):
31
+ return module_or_method
32
+ # Handle bound methods (e.g., module.method)
33
+ if (
34
+ mod_self := getattr(module_or_method, "__self__", None)
35
+ ) is not None and isinstance(mod_self, torch.nn.Module):
36
+ return mod_self
37
+ raise TypeError(
38
+ f"Expected nn.Module or bound method of nn.Module, got {type(module_or_method)}"
39
+ )
40
+
41
+
42
+ def _clear_traced_params_buffers(
43
+ traced_module: torch.fx.GraphModule, const_keys: Sequence[str]
44
+ ) -> None:
45
+ """Remove all parameters and buffers from traced module before restoring.
46
+
47
+ For constants (parameters/buffers that don't need FQN mapping), this function
48
+ removes them from the _buffers dict and re-assigns them as direct attributes.
49
+ This ensures constants don't show up as buffers in the state dict.
50
+
51
+ Args:
52
+ traced_module: The traced GraphModule to clean up.
53
+ const_keys: List of keys that represent constants to be cleared.
54
+ """
55
+ for key in const_keys:
56
+ if key not in traced_module._buffers:
57
+ raise AssertionError(f"Key {key} not found in traced_module._buffers")
58
+ # We don't want constants to show up as a buffer in the state dict.
59
+ # Instead they should just be a direct attribute.
60
+ buffer = traced_module._buffers[key]
61
+ del traced_module._buffers[key]
62
+ # Note: setattr will register the value per nn.Module rules:
63
+ # - If it's a Tensor, it'll be re-registered as a buffer (ends up back in _buffers).
64
+ # - Otherwise, it becomes a plain attribute (not part of state_dict).
65
+ setattr(traced_module, key, buffer)
66
+
67
+
68
+ def _restore_state_dict(
69
+ original_module: torch.nn.Module | Callable[..., Any],
70
+ traced_module: torch.fx.GraphModule,
71
+ ) -> None:
72
+ """
73
+ Restores the state dict of the traced module to match the original module exactly.
74
+
75
+ This function ensures that:
76
+ 1. Parameters and buffers in the traced module use the same FQNs (Fully Qualified Names)
77
+ as the original module.
78
+ 2. The ordering of parameters/buffers matches the original module.
79
+ 3. Graph nodes referencing the old names are updated to use the correct FQNs.
80
+
81
+ This is useful after using functional tracing APIs (like dynamo_graph_capture_for_export)
82
+ that may flatten parameter/buffer names.
83
+
84
+ Args:
85
+ original_module: The original nn.Module (or a bound method of one) that was traced.
86
+ traced_module: The traced fx.GraphModule whose state dict needs to be restored.
87
+
88
+ Example::
89
+
90
+ import torch
91
+ from torch._dynamo.functional_export import _dynamo_graph_capture_for_export
92
+ from torch.export import _restore_state_dict
93
+
94
+
95
+ class Model(torch.nn.Module):
96
+ def __init__(self):
97
+ super().__init__()
98
+ self.layer = torch.nn.Linear(10, 10)
99
+
100
+ def forward(self, x):
101
+ return self.layer(x)
102
+
103
+
104
+ model = Model()
105
+ gm = _dynamo_graph_capture_for_export(model)(torch.randn(1, 10))
106
+
107
+ # Before: gm may have flattened names like "p_layer_weight"
108
+ # After: gm will have proper FQNs like "layer.weight"
109
+ _restore_state_dict(model, gm)
110
+ """
111
+ # Extract the underlying module if a bound method was passed
112
+ module = _get_underlying_module(original_module)
113
+
114
+ # Build ID-based lookups for traced module params/buffers
115
+ # Collect all data first to avoid modifying during iteration
116
+ traced_params: dict[int, tuple[str, torch.nn.Parameter]] = {}
117
+ for name, param in traced_module.named_parameters(remove_duplicate=False):
118
+ traced_params[id(param)] = (name, param)
119
+
120
+ traced_buffers: dict[int, tuple[str, torch.Tensor]] = {}
121
+ for name, buffer in traced_module.named_buffers(remove_duplicate=False):
122
+ traced_buffers[id(buffer)] = (name, buffer)
123
+
124
+ # Collect original module's parameters and buffers upfront to avoid
125
+ # issues with shared tensor objects during iteration
126
+ orig_params_list: list[tuple[str, torch.nn.Parameter]] = list(
127
+ module.named_parameters(remove_duplicate=False)
128
+ )
129
+ orig_buffers_list: list[tuple[str, torch.Tensor]] = list(
130
+ module.named_buffers(remove_duplicate=False)
131
+ )
132
+
133
+ # Build mapping from old names to new names for graph node updates
134
+ name_mapping: dict[str, str] = {}
135
+
136
+ # Track which traced names we've processed
137
+ processed_traced_names: set[str] = set()
138
+
139
+ # Restore parameters in the order they appear in original module
140
+ for orig_name, orig_param in orig_params_list:
141
+ if id(orig_param) in traced_params:
142
+ # This param exists in traced module - restore it with original FQN
143
+ traced_name, traced_param = traced_params[id(orig_param)]
144
+ processed_traced_names.add(traced_name)
145
+ if traced_name != orig_name:
146
+ # Only reassign if the name is different
147
+ torch.fx.graph_module._assign_attr(
148
+ traced_param, traced_module, orig_name
149
+ )
150
+ torch.fx.graph_module._del_attr(traced_module, traced_name)
151
+ name_mapping[traced_name] = orig_name
152
+ else:
153
+ # This param doesn't exist in traced module - add it
154
+ torch.fx.graph_module._assign_attr(orig_param, traced_module, orig_name)
155
+
156
+ # Restore buffers in the order they appear in original module
157
+ for orig_name, orig_buffer in orig_buffers_list:
158
+ if id(orig_buffer) in traced_buffers:
159
+ # This buffer exists in traced module - restore it with original FQN
160
+ traced_name, traced_buffer = traced_buffers[id(orig_buffer)]
161
+ processed_traced_names.add(traced_name)
162
+ if traced_name != orig_name:
163
+ # Only reassign if the name is different
164
+ torch.fx.graph_module._assign_attr(
165
+ orig_buffer, traced_module, orig_name
166
+ )
167
+ torch.fx.graph_module._del_attr(traced_module, traced_name)
168
+ name_mapping[traced_name] = orig_name
169
+ else:
170
+ # This buffer doesn't exist in traced module - add it
171
+ torch.fx.graph_module._assign_attr(orig_buffer, traced_module, orig_name)
172
+
173
+ param_names = [v[0] for v in traced_params.values()]
174
+ buffer_names = [v[0] for v in traced_buffers.values()]
175
+ # Constants are traced params/buffers that weren't matched to any original param/buffer
176
+ const_keys = list(
177
+ set(param_names + buffer_names).difference(processed_traced_names)
178
+ )
179
+
180
+ _clear_traced_params_buffers(traced_module, const_keys)
181
+
182
+ # Update get_attr nodes in the graph to use the correct FQNs
183
+ for node in traced_module.graph.nodes:
184
+ if node.op == "get_attr" and node.target in name_mapping:
185
+ node.target = name_mapping[node.target]
186
+
187
+ traced_module.recompile()
.venv/lib/python3.12/site-packages/torch/export/_swap.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import operator
3
+ import types
4
+ from collections import defaultdict
5
+
6
+ import torch
7
+ import torch.fx._pytree as fx_pytree
8
+ import torch.utils._pytree as pytree
9
+ from torch.export.exported_program import (
10
+ ConstantArgument,
11
+ ExportedProgram,
12
+ ModuleCallSignature,
13
+ )
14
+ from torch.fx.passes.tools_common import legalize_graph, NodeList
15
+ from torch.fx.passes.utils.fuser_utils import erase_nodes, fuse_as_graphmodule
16
+
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ def _get_getitem_users(node: torch.fx.Node) -> set[torch.fx.Node]:
22
+ node_users = list(node.users.keys())
23
+ getitem_users = set()
24
+ for user in node_users:
25
+ if user.op == "output":
26
+ continue
27
+
28
+ if not (user.op == "call_function" and user.target is operator.getitem):
29
+ raise AssertionError(
30
+ f"Expected getitem node as user for {node}, instead got {user}"
31
+ )
32
+ getitem_users.update(list(user.users.keys()))
33
+ return getitem_users
34
+
35
+
36
+ def _try_remove_connecting_pytrees(curr_module_node: torch.fx.Node) -> None:
37
+ """
38
+ We want to try to remove extraneous pytree flatten/unflatten calls between modules
39
+ calls. Instead of having the following:
40
+ graph():
41
+ ...
42
+ %foo : [num_users=1] = call_module[target=foo](args = (%getitem_1, %getitem_2), kwargs = {})
43
+ %tree_flatten_spec : [num_users=1] = call_function[target=torch.fx._pytree.tree_flatten_spec](args = (%foo, %_spec_1), kwargs = {})
44
+ %getitem_4 : [num_users=1] = call_function[target=operator.getitem](args = (%tree_flatten_spec, 0), kwargs = {})
45
+ %tree_unflatten_1 : [num_users=2] = call_function[target=torch.utils._pytree.tree_unflatten](args = ([%getitem_4], %_spec_2), kwargs = {})
46
+ %getitem_5 : [num_users=1] = call_function[target=operator.getitem](args = (%tree_unflatten_1, 0), kwargs = {})
47
+ %getitem_7 : [num_users=0] = call_function[target=operator.getitem](args = (%tree_unflatten_1, 1), kwargs = {})
48
+ %getitem_6 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem_5, 0), kwargs = {})
49
+ %bar : [num_users=1] = call_module[target=bar](args = (%getitem_6,), kwargs = {})
50
+ ...
51
+
52
+ We could do the following, if we know that all the outputs of `foo` feed into `bar`:
53
+ graph():
54
+ ...
55
+ %foo : [num_users=1] = call_module[target=foo](args = (%getitem_1, %getitem_2), kwargs = {})
56
+ %bar : [num_users=1] = call_module[target=bar](args = (%getitem_6,), kwargs = {})
57
+ ...
58
+
59
+ Currently this optimization only works for the case where all of the outputs
60
+ of `foo` go directly into `bar`, and `bar` has no other inputs.
61
+ """
62
+
63
+ log.debug("Trying to remove pytrees for module call %s", curr_module_node)
64
+
65
+ curr_module_users = list(curr_module_node.users.keys())
66
+ if len(curr_module_users) != 1:
67
+ raise AssertionError(
68
+ f"Expected only one user for module node, instead got {list(curr_module_users)}"
69
+ )
70
+ flatten_node = curr_module_users[0]
71
+ if not (
72
+ flatten_node.op == "call_function"
73
+ and flatten_node.target is fx_pytree.tree_flatten_spec
74
+ ):
75
+ raise AssertionError(
76
+ f"Expected flatten_node to be a call_function with target tree_flatten_spec, "
77
+ f"but got op={flatten_node.op}, target={flatten_node.target}"
78
+ )
79
+
80
+ flatten_getitem_users = _get_getitem_users(flatten_node)
81
+ if len(flatten_getitem_users) != 1:
82
+ log.debug(
83
+ "More than one user found for flatten node, %s: %s. "
84
+ "Unable to fuse it with another unflatten call.",
85
+ flatten_node,
86
+ flatten_getitem_users,
87
+ )
88
+ return
89
+
90
+ unflatten_node = next(iter(flatten_getitem_users))
91
+ if not (
92
+ unflatten_node.op == "call_function"
93
+ and unflatten_node.target is pytree.tree_unflatten
94
+ ):
95
+ log.debug(
96
+ "Flatten node %s's user is not a pytree.tree_unflatten. "
97
+ "Instead it is: %s. Passing...",
98
+ flatten_node,
99
+ unflatten_node,
100
+ )
101
+ return
102
+
103
+ for i, arg in enumerate(unflatten_node.args[0]): # type: ignore[union-attr,arg-type]
104
+ if arg not in flatten_node.users:
105
+ log.debug(
106
+ "Module %s's outputs are not all directly used as inputs to "
107
+ "the subsequent module. Unable to fuse the connecting "
108
+ "flatten/unflatten. The inputs to the subsequent module are: %s. ",
109
+ curr_module_node,
110
+ unflatten_node.args[0],
111
+ )
112
+ return
113
+
114
+ if not (
115
+ # pyrefly: ignore [missing-attribute]
116
+ arg.op == "call_function"
117
+ # pyrefly: ignore [missing-attribute]
118
+ and arg.target is operator.getitem
119
+ # pyrefly: ignore [missing-attribute]
120
+ and arg.args[1] == i
121
+ ):
122
+ log.debug(
123
+ "Module %s's outputs are not all directly used in the same "
124
+ "order as outputted. Unable to fuse the connecting "
125
+ "flatten/unflatten. The inputs to the "
126
+ "subsequent module are: %s. ",
127
+ curr_module_node,
128
+ unflatten_node.args[0],
129
+ )
130
+ return
131
+
132
+ # Unflatten has two levels of getitem, because it gets the args and kwargs
133
+ unflatten_getitem_getitem_users = set()
134
+ unflatten_getitem_users = _get_getitem_users(unflatten_node)
135
+ for unflatten_getitem_user in unflatten_getitem_users:
136
+ unflatten_getitem_getitem_users.update(
137
+ list(unflatten_getitem_user.users.keys())
138
+ )
139
+
140
+ if len(unflatten_getitem_getitem_users) != 1:
141
+ log.debug(
142
+ "More than one user found for unflatten node, %s: %s. "
143
+ "Unable to fuse it with another flatten call.",
144
+ unflatten_node,
145
+ unflatten_getitem_getitem_users,
146
+ )
147
+ return
148
+
149
+ next_module_node = next(iter(unflatten_getitem_getitem_users))
150
+ if next_module_node.op != "call_module":
151
+ log.debug(
152
+ "Unflatten node %s's user is not a call_module. "
153
+ "Instead it is: %s. Passing...",
154
+ unflatten_node,
155
+ next_module_node,
156
+ )
157
+ return
158
+
159
+ # Directly put the outputs of the current module into the next module
160
+ next_module_node.args = (curr_module_node,)
161
+
162
+
163
+ def _remove_extraneous_pytrees(gm: torch.fx.GraphModule) -> None:
164
+ """
165
+ Remove extraneous pytree flatten/unflatten calls.
166
+
167
+ We try a couple of optimizations here:
168
+ 1. Remove pytree flatten/unflatten calls between modules
169
+ 2. TODO: Remove module's in_spec + initial unflatten call
170
+ 3. TODO: Remove module's out_spec + final flatten call
171
+ """
172
+
173
+ for node in gm.graph.nodes:
174
+ if node.op == "call_module" and node.target != "_guards_fn":
175
+ _try_remove_connecting_pytrees(node)
176
+
177
+ gm.graph.eliminate_dead_code()
178
+
179
+
180
+ def _construct_inputs(
181
+ gm: torch.fx.GraphModule,
182
+ signature: ModuleCallSignature,
183
+ node_name_map: dict[str, torch.fx.Node],
184
+ ) -> tuple[list[torch.fx.Node], dict[str, torch.fx.Node]]:
185
+ tree_unflatten_args: list[torch.fx.Node | None] = []
186
+ for input_ in signature.inputs:
187
+ if isinstance(input_, ConstantArgument) and input_.value is None:
188
+ # Constants should be directly embedded into the graph and not used
189
+ # as inputs
190
+ tree_unflatten_args.append(None)
191
+ elif input_.name not in node_name_map:
192
+ # For unused inputs
193
+ tree_unflatten_args.append(None)
194
+ else:
195
+ tree_unflatten_args.append(node_name_map[input_.name])
196
+
197
+ # Insert unflatten call
198
+ from .unflatten import _generate_unflatten
199
+
200
+ unflatten_node = _generate_unflatten(gm, tree_unflatten_args, signature.in_spec)
201
+
202
+ if signature.in_spec.num_children != 2:
203
+ raise AssertionError(
204
+ f"Expected in_spec to have 2 children, but got {signature.in_spec.num_children}"
205
+ )
206
+ if signature.in_spec.type is not tuple:
207
+ raise AssertionError(
208
+ f"Expected in_spec type to be tuple, but got {signature.in_spec.type}"
209
+ )
210
+ args_spec, kwargs_spec = signature.in_spec.children()
211
+ if args_spec.type is not tuple:
212
+ raise AssertionError(
213
+ f"Expected args_spec type to be tuple, but got {args_spec.type}"
214
+ )
215
+ if kwargs_spec.type is not dict:
216
+ raise AssertionError(
217
+ f"Expected kwargs_spec type to be dict, but got {kwargs_spec.type}"
218
+ )
219
+
220
+ args_node = gm.graph.call_function(operator.getitem, (unflatten_node, 0))
221
+ args_nodes = [
222
+ gm.graph.call_function(operator.getitem, (args_node, i))
223
+ for i in range(args_spec.num_children)
224
+ ]
225
+ kwargs_node = gm.graph.call_function(operator.getitem, (unflatten_node, 1))
226
+ kwargs_nodes = {
227
+ k: gm.graph.call_function(operator.getitem, (kwargs_node, k))
228
+ for k in kwargs_spec.context
229
+ }
230
+ return args_nodes, kwargs_nodes
231
+
232
+
233
+ def _insert_call_module(
234
+ gm: torch.fx.GraphModule,
235
+ args_nodes: list[torch.fx.Node],
236
+ kwargs_nodes: dict[str, torch.fx.Node],
237
+ module_to_swap: torch.nn.Module,
238
+ name: str,
239
+ ) -> torch.fx.Node:
240
+ from .unflatten import _assign_attr, _AttrKind
241
+
242
+ _assign_attr(module_to_swap, gm, name, _AttrKind.MODULE)
243
+ module_node = gm.graph.call_module(name, tuple(args_nodes), kwargs_nodes) # type: ignore[arg-type]
244
+ return module_node
245
+
246
+
247
+ def _deconstruct_outputs(
248
+ gm: torch.fx.GraphModule,
249
+ signature: ModuleCallSignature,
250
+ module_node: torch.fx.Node,
251
+ node_name_map: dict[str, torch.fx.Node],
252
+ orig_outputs: tuple[torch.fx.Node, ...],
253
+ ) -> None:
254
+ from .unflatten import _generate_flatten_spec
255
+
256
+ flatten_node = _generate_flatten_spec(gm, module_node, signature.out_spec)
257
+
258
+ for i, orig_output in enumerate(orig_outputs):
259
+ # Use Proxy to record getitem access.
260
+ proxy_out = torch.fx.Proxy(flatten_node)[i].node # type: ignore[index]
261
+ orig_output.replace_all_uses_with(proxy_out, propagate_meta=True)
262
+
263
+ node_name_map[orig_output.name] = proxy_out
264
+
265
+
266
+ def _swap_module_helper(
267
+ gm: torch.fx.GraphModule,
268
+ modules_to_swap: dict[str, torch.nn.Module],
269
+ module_call_graph: dict[str, ModuleCallSignature],
270
+ ) -> torch.fx.GraphModule:
271
+ log.debug("Starting graph:")
272
+ log.debug(gm.graph)
273
+
274
+ legalize_graph(gm)
275
+
276
+ partitions: dict[str, NodeList] = defaultdict(list)
277
+
278
+ node_name_map: dict[str, torch.fx.Node] = {
279
+ node.name: node for node in gm.graph.nodes
280
+ }
281
+
282
+ # TODO: Handle the duplicate module case
283
+ for node in gm.graph.nodes:
284
+ if nn_module_stack := node.meta.get("nn_module_stack"):
285
+ for path, _ in nn_module_stack.values():
286
+ if path in modules_to_swap:
287
+ partitions[path].append(node)
288
+ break
289
+
290
+ for name, nodes in partitions.items():
291
+ """
292
+ Given a graph like the following, and we want to swap out the submodule "foo":
293
+ graph():
294
+ %x : [num_users=1] = placeholder[target=x]
295
+ %y : [num_users=2] = placeholder[target=y]
296
+ %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%y, %x), kwargs = {}), nn_module_stack = {"foo": ("foo", torch.nn.Module)}
297
+ %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%y, %add), kwargs = {}), nn_module_stack = {"bar": ("bar", torch.nn.Module)}
298
+ return (sub,)
299
+
300
+ We will first partition out foo's subgraph:
301
+ graph():
302
+ %x : [num_users=1] = placeholder[target=x]
303
+ %y : [num_users=2] = placeholder[target=y]
304
+ %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%y, %x), kwargs = {})
305
+ return add
306
+
307
+ And then insert an unflatten + call_module + flatten to replace the subgraph:
308
+ graph():
309
+ %x : [num_users=1] = placeholder[target=x]
310
+ %y : [num_users=1] = placeholder[target=y]
311
+
312
+ %_spec_0 : [num_users=1] = get_attr[target=_spec_0]
313
+ %tree_unflatten : [num_users=2] = call_function[target=torch.utils._pytree.tree_unflatten](args = ([%x, %y], %_spec_0), kwargs = {})
314
+ %getitem : [num_users=2] = call_function[target=operator.getitem](args = (%tree_unflatten, 0), kwargs = {})
315
+ %getitem_1 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem, 0), kwargs = {})
316
+ %getitem_2 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem, 1), kwargs = {})
317
+ %getitem_3 : [num_users=0] = call_function[target=operator.getitem](args = (%tree_unflatten, 1), kwargs = {})
318
+ %foo : [num_users=0] = call_module[target=foo](args = (%getitem_1, %getitem_2), kwargs = {})
319
+ %_spec_1 : [num_users=1] = get_attr[target=_spec_1]
320
+ %tree_flatten_spec : [num_users=1] = call_function[target=torch.fx._pytree.tree_flatten_spec](args = (None, %_spec_1), kwargs = {})
321
+ %getitem_4 : [num_users=1] = call_function[target=operator.getitem](args = (%tree_flatten_spec, 0), kwargs = {})
322
+
323
+ %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%y, %getitem_4), kwargs = {})
324
+ return (%sub,)
325
+
326
+ The `tree_unflatten` call will construct tensor inputs into the input
327
+ format needed by the swapped eager module.
328
+ The `call_module` node should now reference the swapped torch.nn.Module.
329
+ The `tree_flatten_spec` call will deconstruct the eager outputs of the
330
+ swapped module into tensors.
331
+ """
332
+
333
+ submod_name = name.replace(".", "_")
334
+ sub_gm, orig_inputs, orig_outputs = fuse_as_graphmodule(
335
+ gm, nodes, f"fused_{submod_name}"
336
+ )
337
+
338
+ log.debug("Fused subgraph nodes:")
339
+ log.debug(sub_gm.graph)
340
+
341
+ signature: ModuleCallSignature = module_call_graph[name]
342
+
343
+ args_nodes, kwargs_nodes = _construct_inputs(gm, signature, node_name_map)
344
+ module_node = _insert_call_module(
345
+ gm, args_nodes, kwargs_nodes, modules_to_swap[name], name
346
+ )
347
+ _deconstruct_outputs(gm, signature, module_node, node_name_map, orig_outputs)
348
+
349
+ erase_nodes(gm, nodes)
350
+
351
+ log.debug("Swapped graph:")
352
+ log.debug(gm.graph)
353
+
354
+ legalize_graph(gm)
355
+
356
+ log.debug("Before removing extraneous pytrees:")
357
+ log.debug(gm.graph)
358
+
359
+ _remove_extraneous_pytrees(gm)
360
+ log.debug("After removing extraneous pytrees:")
361
+ log.debug(gm.graph)
362
+
363
+ gm.recompile()
364
+
365
+ return gm
366
+
367
+
368
+ def _fix_input_output_signature(
369
+ gm: torch.fx.GraphModule, signature: ModuleCallSignature
370
+ ) -> None:
371
+ """
372
+ Given the unlifted module from calling ep.module(), we want to remove the
373
+ pytree processing from the graph module's PyTreeCodeGen and instead make it
374
+ nodes inside of the graph. This allows us to do some optimizations, like
375
+ remove these pytree calls if it is unnecessary, and makes the PyTree part
376
+ more obvious to graph passes.
377
+ """
378
+ from torch.export.unflatten import _generate_flatten, _generate_unflatten
379
+
380
+ # Remove the registered pytree codegen because we will take care of it
381
+ # through inserting pytree nodes into the graph
382
+ gm.graph._codegen = torch.fx.graph.CodeGen()
383
+
384
+ old_placeholders = [node for node in gm.graph.nodes if node.op == "placeholder"]
385
+
386
+ new_placeholders = []
387
+ forward_arg_names = signature.forward_arg_names
388
+ if forward_arg_names is None:
389
+ forward_arg_names = []
390
+ if signature.in_spec.num_children != 2:
391
+ raise AssertionError(
392
+ f"Expected in_spec to have 2 children, but got {signature.in_spec.num_children}"
393
+ )
394
+ arg_spec = signature.in_spec.child(0)
395
+ kwarg_spec = signature.in_spec.child(1)
396
+ if arg_spec.type is not tuple:
397
+ raise AssertionError(
398
+ f"Expected arg_spec type to be tuple, but got {arg_spec.type}"
399
+ )
400
+ if kwarg_spec.type is not dict:
401
+ raise AssertionError(
402
+ f"Expected kwarg_spec type to be dict, but got {kwarg_spec.type}"
403
+ )
404
+ for i in range(arg_spec.num_children):
405
+ forward_arg_names.append(f"arg_{i}")
406
+ forward_arg_names.extend(kwarg_spec.context)
407
+
408
+ for arg in forward_arg_names:
409
+ with gm.graph.inserting_before(old_placeholders[0]):
410
+ new_placeholders.append(gm.graph.placeholder(arg))
411
+
412
+ # Insert flatten call for the inputs
413
+ with gm.graph.inserting_before(old_placeholders[0]):
414
+ flat_node = _generate_flatten(gm, tuple(new_placeholders))
415
+ for i, old_placeholder in enumerate(old_placeholders):
416
+ old_placeholder.op = "call_function"
417
+ old_placeholder.target = operator.getitem
418
+ old_placeholder.args = (flat_node, i)
419
+
420
+ # Insert unflatten call for the outputs
421
+ output_node = next(node for node in gm.graph.nodes if node.op == "output")
422
+ with gm.graph.inserting_before(output_node):
423
+ unflat = _generate_unflatten(gm, output_node.args[0], signature.out_spec)
424
+ output_node.args = (unflat,)
425
+
426
+ gm.recompile()
427
+
428
+
429
+ def _swap_modules(
430
+ ep: ExportedProgram, modules_to_swap: dict[str, torch.nn.Module]
431
+ ) -> torch.fx.GraphModule:
432
+ """
433
+ Unlifts the given ExportedProgram into a fx.GraphModule, and then swaps
434
+ previously traced modules with new eager modules specified. Returns a
435
+ fx.GraphModule with a custom forward function.
436
+
437
+ Args:
438
+ ep (ExportedProgram): Exported program to modify
439
+ modules_to_swap (Dict[str, torch.nn.Module]): Mapping from module fqn to
440
+ eager module to swap with. The specified module fqn should have also
441
+ been specified in the `preserve_module_call_signature` argument to
442
+ torch.export so that we know how to restore the calling convention
443
+ to this argument.
444
+ run_with_interpreter: Whether or not to run the graph using
445
+ fx.Interpreter. Setting to true will help result in better error
446
+ messages and easier debugging, but it has found to result in a QPS
447
+ drop.
448
+ """
449
+ module_call_graph = {
450
+ entry.fqn: entry.signature for entry in ep.module_call_graph if entry.signature
451
+ }
452
+
453
+ gm = ep.module()
454
+ gm.validate_inputs = False # type: ignore[assignment]
455
+ gm.graph.eliminate_dead_code() # type: ignore[operator, union-attr]
456
+ if not isinstance(gm, torch.fx.GraphModule):
457
+ raise AssertionError(
458
+ f"Expected gm to be a torch.fx.GraphModule, but got {type(gm)}"
459
+ )
460
+ _fix_input_output_signature(gm, ep.module_call_graph[0].signature)
461
+
462
+ gm.module_call_graph = ep.module_call_graph
463
+ gm.train = types.MethodType(type(gm).train, gm) # type: ignore[assignment]
464
+ gm.eval = types.MethodType(type(gm).eval, gm) # type: ignore[assignment]
465
+
466
+ if not isinstance(gm, torch.fx.GraphModule):
467
+ raise AssertionError(
468
+ f"Expected gm to be a torch.fx.GraphModule, but got {type(gm)}"
469
+ )
470
+ gm = _swap_module_helper(gm, modules_to_swap, module_call_graph)
471
+
472
+ return gm
.venv/lib/python3.12/site-packages/torch/export/_trace.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/export/_tree_utils.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any
3
+
4
+ from torch.utils._pytree import Context, TreeSpec
5
+
6
+
7
+ def reorder_kwargs(user_kwargs: dict[str, Any], spec: TreeSpec) -> dict[str, Any]:
8
+ """Reorder user-provided kwargs to match the order in `spec`. `spec` is
9
+ expected to be the in_spec of an exported program, i.e. the spec that
10
+ results from flattening `(args, kwargs)`.
11
+
12
+ We need this to provide consistent input ordering, such so that users can
13
+ pass in foo(a=a, b=b) OR foo(b=b, a=a) and receive the same result.
14
+ """
15
+ # Make sure that the spec is actually shaped like (args, kwargs)
16
+ if spec.type is not tuple:
17
+ raise AssertionError(f"Expected spec type to be tuple, but got {spec.type}")
18
+ if spec.num_children != 2:
19
+ raise AssertionError(
20
+ f"Expected spec to have 2 children, but got {spec.num_children}"
21
+ )
22
+ kwargs_spec = spec.child(1)
23
+ if kwargs_spec.type is not dict:
24
+ raise AssertionError(
25
+ f"Expected kwargs_spec type to be dict, but got {kwargs_spec.type}"
26
+ )
27
+
28
+ if set(user_kwargs) != set(kwargs_spec.context):
29
+ raise ValueError(
30
+ f"Ran into a kwarg keyword mismatch: "
31
+ f"Got the following keywords {list(user_kwargs)} but expected {kwargs_spec.context}"
32
+ )
33
+
34
+ reordered_kwargs = {}
35
+ for kw in kwargs_spec.context:
36
+ reordered_kwargs[kw] = user_kwargs[kw]
37
+
38
+ return reordered_kwargs
39
+
40
+
41
+ def is_equivalent(
42
+ spec1: TreeSpec,
43
+ spec2: TreeSpec,
44
+ equivalence_fn: Callable[[type | None, Context, type | None, Context], bool],
45
+ ) -> bool:
46
+ """Customizable equivalence check for two TreeSpecs.
47
+
48
+ Arguments:
49
+ spec1: The first TreeSpec to compare
50
+ spec2: The second TreeSpec to compare
51
+ equivalence_fn: A function to determine the equivalence of two
52
+ TreeSpecs by examining their types and contexts. It will be called like:
53
+
54
+ equivalence_fn(spec1.type, spec1.context, spec2.type, spec2.context)
55
+
56
+ This function will be applied recursively to all children.
57
+
58
+ Returns:
59
+ True if the two TreeSpecs are equivalent, False otherwise.
60
+ """
61
+ if not equivalence_fn(spec1.type, spec1.context, spec2.type, spec2.context):
62
+ return False
63
+
64
+ # Recurse on children
65
+ if spec1.num_children != spec2.num_children:
66
+ return False
67
+
68
+ for child_spec1, child_spec2 in zip(spec1.children(), spec2.children()):
69
+ if not is_equivalent(child_spec1, child_spec2, equivalence_fn):
70
+ return False
71
+
72
+ return True
.venv/lib/python3.12/site-packages/torch/export/_unlift.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import inspect
4
+ import math
5
+ import warnings
6
+ from collections.abc import Sequence
7
+ from itertools import chain
8
+ from typing import Any
9
+
10
+ import sympy
11
+
12
+ import torch
13
+ import torch.utils._pytree as pytree
14
+ from torch._export.non_strict_utils import (
15
+ _enter_enable_graph_inputs_of_type_nn_module,
16
+ _exit_enable_graph_inputs_of_type_nn_module,
17
+ _get_graph_inputs_of_type_nn_module,
18
+ )
19
+ from torch._export.passes.add_runtime_assertions_for_constraints_pass import (
20
+ _convert_range_to_int,
21
+ )
22
+ from torch._export.utils import _check_input_constraints_for_graph
23
+ from torch.export.unflatten import _assign_attr, _AttrKind
24
+ from torch.fx.experimental.proxy_tensor import _pytree_subclasses_that_lose_info
25
+ from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo
26
+ from torch.fx.traceback import NodeSource, NodeSourceAction
27
+ from torch.utils._sympy.solve import try_solve
28
+ from torch.utils._sympy.value_ranges import ValueRanges
29
+
30
+ from ._remove_effect_tokens_pass import _remove_effect_tokens
31
+ from ._tree_utils import reorder_kwargs
32
+ from .exported_program import (
33
+ ExportedProgram,
34
+ ExportGraphSignature,
35
+ InputKind,
36
+ OutputKind,
37
+ )
38
+
39
+
40
+ def eq_spec(self: pytree.TreeSpec, other: pytree.TreeSpec) -> bool:
41
+ """
42
+ Refinement of TreeSpec.__eq__ where, e.g., torch.Size(...) matches tuple(...).
43
+ See _pytree_subclasses_that_lose_info in proxy_tensor.py for more details.
44
+ """
45
+
46
+ def _normalize_type(t):
47
+ return str(_pytree_subclasses_that_lose_info.get(t, t))
48
+
49
+ def _match_normalized_structure(a, b):
50
+ if a is b:
51
+ return True
52
+ if _normalize_type(a.type) != _normalize_type(b.type):
53
+ return False
54
+ if a.type is dict and b.type is dict:
55
+ # in the case of dict, the context is list of keys and we allow the keys to be in any order
56
+ if set(a.context) != set(b.context):
57
+ return False
58
+ elif a.context != b.context:
59
+ return False
60
+ if a.num_children != b.num_children:
61
+ return False
62
+ return all(
63
+ _match_normalized_structure(a, b)
64
+ for a, b in zip(a.children(), b.children())
65
+ )
66
+
67
+ return _match_normalized_structure(self, other)
68
+
69
+
70
+ def _check_inputs_match(args, kwargs, in_spec: pytree.TreeSpec) -> list:
71
+ reordered_kwargs = reorder_kwargs(kwargs, in_spec)
72
+ flat_args_with_path, received_spec = pytree.tree_flatten_with_path(
73
+ (args, reordered_kwargs)
74
+ )
75
+
76
+ if not eq_spec(received_spec, in_spec):
77
+ raise ValueError(
78
+ "Trying to flatten user inputs with exported input tree spec: \n"
79
+ f"{in_spec}\n"
80
+ "but actually got inputs with tree spec of: \n"
81
+ f"{received_spec}.\n"
82
+ "Please check that the inputs have the same number and type of "
83
+ "args and kwargs as the ones you used when tracing."
84
+ )
85
+
86
+ return flat_args_with_path
87
+
88
+
89
+ def _force_ep_signature_match(ep_guards_code: list[str], input_paths):
90
+ # TODO (tmanlaibaatar)
91
+ # This is band-aid solution to export new tracer replacing
92
+ # shape env sources to flat_args. The real fix should be replacing
93
+ # shape env sources to original user sources but this is quite
94
+ # involved because you need to carefully construct new sources using
95
+ # dynamo and replace all instances of it inside shape env. But it is
96
+ # lot easier to manipulate after we turn them into strings and only
97
+ # time we use these guards is during retracing or running exported program,
98
+ # so it is probably ok to have "not useful" guards on ep for now.
99
+ name_mapping = {}
100
+ for idx, path in enumerate(input_paths):
101
+ name_mapping[f"L['flat_args'][{idx}]"] = f"L{pytree.keystr(path)}"
102
+
103
+ new_guards_code = []
104
+ for guard in ep_guards_code:
105
+ for old_name, new_name in name_mapping.items():
106
+ guard = guard.replace(old_name, new_name)
107
+ new_guards_code.append(guard)
108
+
109
+ return new_guards_code
110
+
111
+
112
+ def _force_gm_signature_match(ep_guards_code: list[str], signature):
113
+ """
114
+ The signature of the originally exported module may not match
115
+ the signature of the unlifted graph module extracted from the
116
+ exported program. The guards code extracted from the exported
117
+ program is based on the former, but the generated guards fn is
118
+ based on the latter; thus we need to reconcile any such diff.
119
+ """
120
+
121
+ import re
122
+
123
+ # Handle case where signatures may differ in var args.
124
+ orig_arg_names = set()
125
+ for g in ep_guards_code:
126
+ # match substrings of the form L['<name>'][<number>]
127
+ orig_arg_names.update(re.findall(r"L\[\'([^\']+)\'\]\[([0-9]+)\]", g))
128
+
129
+ sig_arg_names = set()
130
+ for n in signature.parameters:
131
+ # match substrings of the form <name>_<number>
132
+ sig_arg_names.update(re.findall(r"(.+)_([0-9]+)", n))
133
+
134
+ # replace L['<name>'][<number>] with L['<name>_<number>']
135
+ new_guards_code = ep_guards_code
136
+ for match in orig_arg_names:
137
+ if match in sig_arg_names:
138
+ base, idx = match
139
+ new_guards_code = [
140
+ g.replace(f"L['{base}'][{idx}]", f"L['{base}_{idx}']")
141
+ for g in new_guards_code
142
+ ]
143
+
144
+ return new_guards_code
145
+
146
+
147
+ def _convert_guards_code_to_fn(
148
+ guards_code: list[str],
149
+ paths_of_placeholders: list[pytree.KeyPath],
150
+ ):
151
+ """
152
+ Generates Python code given guards code and paths of placeholders.
153
+ We assume that, based on source information,
154
+ - the tracer generates the guards code
155
+ - the input spec generates the paths of placeholders.
156
+
157
+ Example:
158
+
159
+ Suppose we are given the guards code "L['z']['k'].size()[1] == 3"
160
+ and we are given that ['z']['k'] is the path of placeholder #2.
161
+ Then we will generate:
162
+ ```
163
+ torch._assert(
164
+ args[2].size()[0] == 3,
165
+ "Guard failed: z['k'].size()[0] == 3",
166
+ )
167
+ ```
168
+
169
+ FAQ: Why do we generate code based on (flattened) args instead of
170
+ the original (unflattened) inputs? Because this would require
171
+ inserting an additional pytree.unflatten call in our graph.
172
+
173
+ FAQ: Why do we not emit RuntimeError on guard failure as we used to?
174
+ Because it is inconvenient :/, get used to AssertionError instead.
175
+ """
176
+
177
+ import ast
178
+
179
+ from torch.fx.experimental.symbolic_shapes import SYMPY_INTERP
180
+
181
+ actual_guards_code = []
182
+ shadow_guards_code = []
183
+ for c in guards_code:
184
+ a, s = c, c
185
+ for idx, path in enumerate(paths_of_placeholders):
186
+ # e.g., replace L['z']['k'] with args[2] for Python code (actual)
187
+ a = a.replace("L" + pytree.keystr(path), f"args[{idx}]")
188
+ # e.g., replace L['z']['k'] with z['k'] for error message (shadow)
189
+ s = s.replace(
190
+ "L" + pytree.keystr(path),
191
+ path[0].key + pytree.keystr(path[1:]), # type: ignore[attr-defined]
192
+ )
193
+ actual_guards_code.append(a)
194
+ shadow_guards_code.append(s.replace("\n", ""))
195
+
196
+ # generate function code as str
197
+ code_str = "\ndef _(*args):\n"
198
+ for actual, shadow in zip(actual_guards_code, shadow_guards_code):
199
+ # printing guards code may potentially introduce redundant parens;
200
+ # we can normalize them out for readability by parsing/unparsing
201
+ # NOTE: this is not necessary for correctness, just deemed desirable
202
+ try:
203
+ _shadow = ast.unparse(ast.parse(shadow, mode="eval"))
204
+ except RecursionError as e:
205
+ # A deeply nested guard expression (e.g. a sum over many symbolic
206
+ # sizes) can exceed the recursion limit in ast.parse/ast.unparse.
207
+ # This normalization only affects the assert error message, so fall
208
+ # back to the un-normalized guard string instead of crashing.
209
+ warnings.warn(f"ast.unparse failed for guard expression: {e}", stacklevel=2)
210
+ _shadow = shadow
211
+ # actual code and shadow error message
212
+ code_str += f' torch._assert({actual}, "Guard failed: {_shadow}")\n'
213
+ code_str += " return\n"
214
+
215
+ # populate namespace with sympy globals, materialize function (named `_`)
216
+ namespace = {
217
+ **SYMPY_INTERP,
218
+ "math": math,
219
+ "inf": float("inf"),
220
+ }
221
+ exec(code_str, namespace)
222
+
223
+ # create and return a module whose forward is the materialized function
224
+ # NOTE: we want Dynamo to trace through this module, to repopulate guards:
225
+ # otherwise we would lose them when retracing
226
+ # NOTE: calling this module will be a side effect (no users): so it must
227
+ # be marked impure to avoid being not cleaned up by DCE
228
+ guards_fn = GuardsFn()
229
+ guards_fn.forward = torch._dynamo.dont_skip_tracing(namespace["_"]) # type: ignore[call-overload, method-assign]
230
+ guards_fn._is_impure = True # type: ignore[assignment]
231
+ return guards_fn
232
+
233
+
234
+ @torch._dynamo.disable
235
+ def _check_input_constraints_for_module(self, args, kwargs):
236
+ flat_args_with_path = _check_inputs_match(args, kwargs, self._in_spec)
237
+ _check_input_constraints_for_graph(
238
+ self.graph.find_nodes(op="placeholder"),
239
+ flat_args_with_path,
240
+ self.range_constraints,
241
+ )
242
+
243
+
244
+ def _check_input_constraints_pre_hook(self, args, kwargs):
245
+ # preserve current behavior for clients that do not want any validation
246
+ if not self.validate_inputs:
247
+ return
248
+
249
+ # when a guards function exists, assume that the graph does calls it!
250
+ # so we do not need to check input constraints...but we still want
251
+ # to check inputs match, otherwise we'd get obscure pytree errors
252
+ if hasattr(self, "_guards_fn"):
253
+ _check_inputs_match(args, kwargs, self._in_spec)
254
+ return
255
+
256
+ # NOTE: for some reason, Dynamo is tracing into this, we should see why and
257
+ # put compile at the right place. Until then, we can skip the input
258
+ # constraint checks.
259
+ if not torch.compiler.is_dynamo_compiling():
260
+ _check_input_constraints_for_module(self, args, kwargs)
261
+
262
+
263
+ def _unlift_inputs_as_getattr(
264
+ gm: torch.fx.GraphModule,
265
+ lifted_inputs: Sequence[str | None],
266
+ ) -> tuple[dict[str, torch.fx.Node], dict[str, torch.fx.Node]]:
267
+ """
268
+ Unlift inputs referring to params/buffers/constants as getattr nodes in the
269
+ graph
270
+ """
271
+ unlifted_name_to_node = {}
272
+ input_name_to_node = {}
273
+
274
+ placeholder_nodes = [node for node in gm.graph.nodes if node.op == "placeholder"]
275
+ if len(lifted_inputs) != len(placeholder_nodes):
276
+ raise AssertionError(
277
+ f"Number of lifted inputs ({len(lifted_inputs)}) does not match "
278
+ f"placeholder nodes ({len(placeholder_nodes)})"
279
+ )
280
+ for input_node, lifted_node in zip(placeholder_nodes, lifted_inputs):
281
+ if lifted_node is None:
282
+ input_name_to_node[input_node.name] = input_node
283
+
284
+ else:
285
+ with gm.graph.inserting_after(input_node):
286
+ # It is fine to ignore this warning because
287
+ # it is guaranteed that we will populate this
288
+ # attr later.
289
+ with warnings.catch_warnings():
290
+ warnings.simplefilter("ignore")
291
+ getattr_node = gm.graph.get_attr(lifted_node)
292
+ input_node.replace_all_uses_with(getattr_node)
293
+ metadata = input_node.meta
294
+ gm.graph.erase_node(input_node)
295
+ getattr_node.meta = metadata
296
+ getattr_node.meta["from_node"] = [
297
+ NodeSource(
298
+ input_node,
299
+ "ExportedProgram.module().unlift()",
300
+ [NodeSourceAction.CREATE, NodeSourceAction.REPLACE],
301
+ )
302
+ ]
303
+ unlifted_name_to_node[lifted_node] = getattr_node
304
+
305
+ return unlifted_name_to_node, input_name_to_node
306
+
307
+
308
+ def _insert_copy_for_mutations(
309
+ gm: torch.fx.GraphModule,
310
+ mutated_outputs: Sequence[str | None],
311
+ unlifted_name_to_node: dict[str, torch.fx.Node],
312
+ input_name_to_node: dict[str, torch.fx.Node],
313
+ ) -> None:
314
+ """
315
+ Find the all the buffers and inputs that were mutated and insert copy_
316
+ operators to reflect mutations.
317
+ """
318
+ output_node = gm.graph.output_node()
319
+ outputs = pytree.tree_flatten(output_node.args)[0]
320
+ if len(outputs) != len(mutated_outputs):
321
+ raise AssertionError(
322
+ f"Number of outputs ({len(outputs)}) does not match "
323
+ f"mutated outputs ({len(mutated_outputs)})"
324
+ )
325
+
326
+ user_output_nodes = []
327
+ return_nodes_to_copy = {}
328
+ for return_node, mutated_node_name in zip(outputs, mutated_outputs):
329
+ if mutated_node_name is None:
330
+ user_output_nodes.append(return_node)
331
+ continue
332
+
333
+ if mutated_node_name in unlifted_name_to_node:
334
+ mutated_node = unlifted_name_to_node[mutated_node_name]
335
+ elif mutated_node_name in input_name_to_node:
336
+ mutated_node = input_name_to_node[mutated_node_name]
337
+ else:
338
+ raise RuntimeError(
339
+ f"Could not find {mutated_node_name} in either buffer or input nodes"
340
+ )
341
+
342
+ with gm.graph.inserting_before(output_node):
343
+ copy_node = gm.graph.call_function(
344
+ torch.ops.aten.copy_.default, (mutated_node, return_node)
345
+ )
346
+ return_nodes_to_copy[return_node] = copy_node
347
+
348
+ output_args = tuple(
349
+ return_nodes_to_copy.get(node, node) for node in user_output_nodes
350
+ )
351
+ with gm.graph.inserting_before(output_node):
352
+ # Only return user outputs
353
+ new_output = gm.graph.output(output_args)
354
+ output_node.replace_all_uses_with(new_output)
355
+ gm.graph.erase_node(output_node)
356
+ new_output.name = output_node.name
357
+ new_output.meta.update(output_node.meta)
358
+ new_output.meta["from_node"] = [
359
+ NodeSource(
360
+ output_node,
361
+ "ExportedProgram.module().unlift()",
362
+ [NodeSourceAction.CREATE, NodeSourceAction.REPLACE],
363
+ )
364
+ ]
365
+
366
+
367
+ def _get_codegen(
368
+ in_spec: pytree.TreeSpec,
369
+ out_spec: pytree.TreeSpec | None,
370
+ forward_arg_names: list[str] | None = None,
371
+ ) -> _PyTreeCodeGen:
372
+ """
373
+ Create the codegen for the graph module based on the in/out specs
374
+ """
375
+ if forward_arg_names:
376
+ names = forward_arg_names
377
+ elif (
378
+ in_spec.type is tuple
379
+ and in_spec.num_children == 2
380
+ and in_spec.child(0).type is tuple
381
+ and in_spec.child(1).type is dict
382
+ ):
383
+ # if in_spec contains the args (tuple) and kwargs (dict)
384
+ names = [f"arg_{i}" for i in range(in_spec.child(0).num_children)]
385
+ # add kwarg names
386
+ names.extend(in_spec.child(1).context)
387
+ else:
388
+ names = [f"arg_{i}" for i in range(in_spec.num_children)]
389
+
390
+ return _PyTreeCodeGen(
391
+ _PyTreeInfo(
392
+ names,
393
+ in_spec,
394
+ out_spec,
395
+ )
396
+ )
397
+
398
+
399
+ def _unlift(
400
+ gm: torch.fx.GraphModule,
401
+ lifted_inputs: Sequence[str | None],
402
+ mutated_outputs: Sequence[str | None],
403
+ in_spec: pytree.TreeSpec,
404
+ out_spec: pytree.TreeSpec | None,
405
+ forward_arg_names: list[str] | None = None,
406
+ ):
407
+ """
408
+ Args:
409
+ lifted_inputs: A list matching the graph module's input nodes. For
410
+ an input node that is referring to a lifted parameter/buffer, this
411
+ list will contain the fqn the corresponding attribute. Otherwise, this
412
+ list will contain None. This is used to unlift the lifted parameters as
413
+ get_attr nodes.
414
+
415
+ mutated_outputs: A list matching the graph module's output nodes. For
416
+ an output node that is referring to a mutated buffer or user input, this
417
+ list will contain the name of the corresponding buffer or user input
418
+ that needs to be mutated. Otherwise, this list will contain None. This
419
+ is used to re-insert an inplace copy_ operator to copy the mutated
420
+ values back to the original node.
421
+ """
422
+ unlifted_name_to_node, input_name_to_node = _unlift_inputs_as_getattr(
423
+ gm, lifted_inputs
424
+ )
425
+ _insert_copy_for_mutations(
426
+ gm, mutated_outputs, unlifted_name_to_node, input_name_to_node
427
+ )
428
+ gm.graph._codegen = _get_codegen(in_spec, out_spec, forward_arg_names)
429
+ gm.graph.lint()
430
+ gm.recompile()
431
+ return gm
432
+
433
+
434
+ def _register_attrs_to_new_gm(
435
+ new_gm: torch.fx.GraphModule,
436
+ graph_signature: ExportGraphSignature,
437
+ state_dict: dict[str, Any],
438
+ constants: dict[str, Any],
439
+ ) -> None:
440
+ non_persistent_buffers = set(graph_signature.non_persistent_buffers)
441
+ for name in graph_signature.buffers:
442
+ if name in non_persistent_buffers:
443
+ persistent = False
444
+ value = constants[name]
445
+ else:
446
+ persistent = True
447
+ value = state_dict[name]
448
+ _assign_attr(
449
+ value, new_gm, name, attr_kind=_AttrKind.BUFFER, persistent=persistent
450
+ )
451
+ for name in graph_signature.parameters:
452
+ value = state_dict[name]
453
+ _assign_attr(
454
+ value,
455
+ new_gm,
456
+ name,
457
+ attr_kind=_AttrKind.PARAMETER,
458
+ )
459
+
460
+ # Technically this doesn't account for the aliased multiple constants but
461
+ # it is ok because we have a separate pass later in the stack that populates
462
+ # the final gm.
463
+ for name in chain(
464
+ graph_signature.lifted_custom_objs, graph_signature.lifted_tensor_constants
465
+ ):
466
+ value = constants[name]
467
+ _assign_attr(
468
+ value,
469
+ new_gm,
470
+ name,
471
+ attr_kind=_AttrKind.CONSTANT,
472
+ )
473
+
474
+
475
+ class _StatefulGraphModuleFactory(type):
476
+ """
477
+ Metaclass that ensures a private constructor for _StatefulGraphModule
478
+ """
479
+
480
+ def __call__(cls, *args, **kwargs):
481
+ raise TypeError(
482
+ f"{cls.__module__}.{cls.__qualname__} has no public constructor. "
483
+ )
484
+
485
+ def _create(cls, root, graph, range_constraints=None):
486
+ return super().__call__(
487
+ root,
488
+ graph,
489
+ range_constraints=range_constraints,
490
+ )
491
+
492
+
493
+ class _StatefulGraphModule(torch.fx.GraphModule, metaclass=_StatefulGraphModuleFactory):
494
+ def __init__(self, root, graph, range_constraints=None):
495
+ super().__init__(root, graph)
496
+ # Need to fix up non-persistent buffers.
497
+ self.range_constraints = range_constraints or []
498
+ self.validate_inputs = True
499
+
500
+
501
+ def _create_stateful_graph_module(
502
+ plain_graph_module: torch.fx.GraphModule,
503
+ range_constraints,
504
+ ep: ExportedProgram,
505
+ ) -> _StatefulGraphModule:
506
+ stateful_gm = _StatefulGraphModule._create(
507
+ plain_graph_module,
508
+ plain_graph_module.graph,
509
+ range_constraints=range_constraints,
510
+ )
511
+
512
+ module_types = _get_graph_inputs_of_type_nn_module(ep.example_inputs)
513
+ stateful_gm.register_forward_pre_hook(
514
+ lambda *args, **kwargs: _enter_enable_graph_inputs_of_type_nn_module(
515
+ module_types
516
+ )
517
+ )
518
+ stateful_gm.register_forward_pre_hook(
519
+ _check_input_constraints_pre_hook, with_kwargs=True
520
+ )
521
+
522
+ stateful_gm.register_forward_hook(
523
+ lambda *args, **kwargs: _exit_enable_graph_inputs_of_type_nn_module(
524
+ module_types
525
+ ),
526
+ always_call=True,
527
+ )
528
+
529
+ # When we have a constant that has requires_grad=True, we need to detach it
530
+ # when we unlift as the tensors that require gradients should be registered
531
+ # via parameters. But this is problematic when we have aliasing two constants
532
+ # because when we call detach, they will become different tensors. This dict
533
+ # keeps track of this logic.
534
+ original_tensor_to_detached_tensor = {}
535
+
536
+ # Fix up lifted tensor constants.
537
+ # fx.GraphModule() constructor silently turns a constant attribute of plain_graph_module
538
+ # into a buffer in stateful_gm and creates an inconsistency with graph_signature.
539
+ # We fix this by de-registering these buffers in lifted_tensor_constants
540
+ # and call _assign_attr(attr_kind=CONSTANT) to register them as constants.
541
+ for constant_fqn in ep.graph_signature.lifted_tensor_constants:
542
+ # Sometimes, the constant can require gradient, this is probably a bug in user code,
543
+ # e.g. `self.const = torch.randn(2, 2, requires_grad=True)`.
544
+ # We call detach on the constant_val since they're tensor constants and we don't need to
545
+ # compute their gradients anyway.
546
+ # Users should properly register it as parameter if they want it to require gradient.
547
+ buffer = stateful_gm.get_buffer(constant_fqn)
548
+ if buffer.requires_grad:
549
+ warnings.warn(
550
+ f"A model attribute `{constant_fqn}` requires gradient. "
551
+ f"but it's not properly registered as a parameter. "
552
+ f"torch.export will detach it and treat it as a constant tensor "
553
+ f"but please register it as parameter instead.",
554
+ stacklevel=2,
555
+ )
556
+ detached_buffer = buffer.detach()
557
+ original_tensor_to_detached_tensor[buffer] = detached_buffer
558
+ buffer = detached_buffer
559
+ *prefix, field = constant_fqn.rsplit(".")
560
+ submod = torch.fx.graph_module._get_attr_via_attr_list(stateful_gm, prefix)
561
+ delattr(submod, field)
562
+ _assign_attr(buffer, stateful_gm, constant_fqn, attr_kind=_AttrKind.CONSTANT)
563
+
564
+ # Constants are not preserved well when we create a new GraphModule unlike param/buffers
565
+ for const_name, value in ep.constants.items():
566
+ if not torch.fx.graph_module._has_attr(stateful_gm, const_name):
567
+ if isinstance(value, torch.Tensor):
568
+ if value.requires_grad:
569
+ warnings.warn(
570
+ f"A model attribute `{const_name}` requires gradient "
571
+ f"but it's not properly registered as a parameter. "
572
+ f"torch.export will detach it and treat it as a constant tensor "
573
+ f"but please register it as parameter instead.",
574
+ stacklevel=2,
575
+ )
576
+ if value in original_tensor_to_detached_tensor:
577
+ value = original_tensor_to_detached_tensor[value]
578
+ else:
579
+ detached_value = value.detach()
580
+ original_tensor_to_detached_tensor[value] = detached_value
581
+ value = detached_value
582
+ _assign_attr(
583
+ value,
584
+ stateful_gm,
585
+ const_name,
586
+ attr_kind=_AttrKind.CONSTANT,
587
+ )
588
+
589
+ # Fix up non-persistent buffers. torch.fx does not distinguish between
590
+ # persistent and non-persistent buffers, so we must restore that distinction
591
+ # here.
592
+ for buffer in ep.graph_signature.non_persistent_buffers:
593
+ _assign_attr(
594
+ plain_graph_module.get_buffer(buffer),
595
+ stateful_gm,
596
+ buffer,
597
+ attr_kind=_AttrKind.BUFFER,
598
+ persistent=False,
599
+ )
600
+
601
+ return stateful_gm
602
+
603
+
604
+ def _get_input_paths(example_inputs, signature):
605
+ """
606
+ Generate paths of placeholders, needed for generating the guards function.
607
+
608
+ NOTE: Here we make use of the example inputs used for export as well as
609
+ the signature of the unlifted graph module (not preserved by export).
610
+ """
611
+
612
+ args, kwargs = example_inputs
613
+ binded = signature.bind(*args, **kwargs)
614
+ binded.apply_defaults()
615
+ ctx = binded.arguments
616
+ flat_example_inputs_with_paths = pytree.tree_leaves_with_path(ctx)
617
+ return [path for path, _ in flat_example_inputs_with_paths]
618
+
619
+
620
+ def _replace_sources(result_str: str, flat_input_paths: list[Any]):
621
+ """
622
+ Given user specified input paths, maybe fix up the guard string
623
+ to reflect user path instead of tracer path.
624
+ """
625
+ name_mapping = {}
626
+ for idx, path in enumerate(flat_input_paths):
627
+ name_mapping[f"L['flat_args'][{idx}]"] = f"L{pytree.keystr(path)}"
628
+
629
+ replace = result_str
630
+ for key, val in name_mapping.items():
631
+ replace = replace.replace(key, val)
632
+ return replace
633
+
634
+
635
+ def _get_input_guards_for_graph(
636
+ placeholders: list[torch.fx.Node],
637
+ range_constraints: dict[sympy.Symbol, ValueRanges],
638
+ paths_for_placeholders: list[pytree.KeyPath],
639
+ ):
640
+ """
641
+ Guards generated by the tracer include conditions observed in code, but
642
+ do not include some additional checks we typically do in export.
643
+ For example, when dynamic shapes get specialized, are specified to be
644
+ within a range, or are specified to be in some equational relation,
645
+ corresponding input invalidation is done within a pre_hook, specifically,
646
+ `_check_input_constraints_for_graph`.
647
+
648
+ Here we generate guards corresponding to the checks that happen in
649
+ `_check_input_constraints_for_graph`, and add them to the guards already
650
+ generated by the tracer. In the future, it may be worthwhile to separate
651
+ them so that we can allow clients to turn off one but not the other.
652
+ (Looking at you, AOTI.)
653
+
654
+ NOTE: We should eventually reconcile this logic with `build_guards` that
655
+ is used by AOT Precompile.
656
+ """
657
+
658
+ deferred_expressions = []
659
+ new_guards_code = []
660
+ sources: dict[sympy.Expr, str] = {}
661
+
662
+ def handle_symint(expr, src):
663
+ if len(expr.free_symbols) == 1:
664
+ # complex equations (e.g., involving derived dims) need to
665
+ # handled later, since we may not have enough information
666
+ # just as we are passing through the placeholders in order
667
+ deferred_expressions.append((src, expr))
668
+ if expr in sources:
669
+ # expressions that appear in multiple sources should force
670
+ # inputs corresponding to those sources to be equal
671
+ # e.g., x.shape[0] == y.shape[1]
672
+ orig_src = sources[expr]
673
+ new_guards_code.append(f"{src} == {orig_src}")
674
+ else:
675
+ sources[expr] = src
676
+ # process value ranges as elsewhere in export
677
+ min_val, max_val = _convert_range_to_int(range_constraints[expr])
678
+ if min_val > 2:
679
+ new_guards_code.append(f"{src} >= {min_val}")
680
+ if max_val < math.inf:
681
+ new_guards_code.append(f"{src} <= {max_val}")
682
+
683
+ for placeholder, path in zip(placeholders, paths_for_placeholders):
684
+ src = "L" + pytree.keystr(path)
685
+ meta = placeholder.meta["val"]
686
+ # specializations
687
+ if isinstance(meta, int):
688
+ new_guards_code.append(f"{src} == {meta}")
689
+ if isinstance(meta, float):
690
+ if math.isnan(meta):
691
+ new_guards_code.append(f"math.isnan({src})")
692
+ elif meta == math.inf:
693
+ new_guards_code.append(f"{src} == math.inf")
694
+ elif meta == -math.inf:
695
+ new_guards_code.append(f"{src} == -math.inf")
696
+ else:
697
+ new_guards_code.append(f"{src} == {meta}")
698
+ elif isinstance(meta, str):
699
+ new_guards_code.append(f"{src} == '{meta}'")
700
+ # range constraints and equalities
701
+ elif isinstance(meta, torch.SymInt) and meta.node.expr in range_constraints:
702
+ handle_symint(meta.node.expr, src)
703
+ elif isinstance(meta, torch.Tensor):
704
+ for i, dim in enumerate(meta.shape):
705
+ src = "L" + pytree.keystr(path) + f".size()[{i}]"
706
+ if isinstance(dim, int):
707
+ # specializations
708
+ new_guards_code.append(f"{src} == {dim}")
709
+ elif (
710
+ isinstance(dim, torch.SymInt) and dim.node.expr in range_constraints
711
+ ):
712
+ # range constraints and equalities
713
+ handle_symint(dim.node.expr, src)
714
+
715
+ unification_map: dict[sympy.Symbol, sympy.Expr] = {}
716
+ py_printer = torch.utils._sympy.printers.PythonPrinter()
717
+
718
+ # process complex equations (e.g., involving derived dims)
719
+ for src, expr in deferred_expressions:
720
+ # we know this is the only symbol in expr (see check above)
721
+ symbol = next(iter(expr.free_symbols))
722
+ if symbol in sources:
723
+ # if s0 is already known to be directly sourced from inputs,
724
+ # e.g., z.shape[2], we do not need to do anything further
725
+ # (assume we have already processed constraints on s0 above)
726
+ continue
727
+
728
+ # otherwise s0 has some "hidden" source like 'dim'
729
+ # example: src = y.shape[1], expr = s0 + 1
730
+ if symbol in unification_map:
731
+ # suppose that we already know that s0 = x.shape[0] * 2
732
+ # so we can emit the guard: x.shape[0] * 2 + 1 = y.shape[1]
733
+ substitution = expr.subs(unification_map)
734
+ new_guards_code.append(
735
+ py_printer.doprint(sympy.Eq(substitution, sympy.Symbol(src)))
736
+ )
737
+ else:
738
+ # we do not yet know what s0 is, but given s0 + 1 = y.shape[1],
739
+ # we can solve for s0...now knowing that s0 = y.shape[1] - 1
740
+ solution = try_solve(sympy.Eq(expr, sympy.Symbol(src)), symbol)
741
+ if solution is not None:
742
+ definition = solution[1]
743
+ unification_map[symbol] = definition
744
+
745
+ return new_guards_code
746
+
747
+
748
+ def _ok_to_generate_guards_fn():
749
+ patterns = [
750
+ "executorch",
751
+ "modai",
752
+ "on_device_ai",
753
+ "torchao",
754
+ ]
755
+ # force check_guards=False for files matching `patterns`
756
+ # because they have too many calls to .module() and
757
+ # do not like any call modules in the graph
758
+ # TODO: fix these files to handle guard fns
759
+ frame = inspect.currentframe()
760
+ while frame is not None:
761
+ if any(path in frame.f_code.co_filename for path in patterns):
762
+ return False
763
+ frame = frame.f_back
764
+
765
+ return True
766
+
767
+
768
+ def _unlift_exported_program_lifted_states(
769
+ ep: ExportedProgram, check_guards=True
770
+ ) -> torch.fx.GraphModule:
771
+ check_guards = check_guards and _ok_to_generate_guards_fn()
772
+
773
+ source_node_dict = {
774
+ node.name: node for node in ep.graph.nodes if node.op != "placeholder"
775
+ }
776
+ # placeholder node name might change after deepcopy
777
+ placeholder_source_node_dict = {
778
+ node.target: node for node in ep.graph.nodes if node.op == "placeholder"
779
+ }
780
+
781
+ new_gm = torch.fx.GraphModule(ep.graph_module, copy.deepcopy(ep.graph))
782
+ new_gm.meta.update(ep.graph_module.meta)
783
+ ep = copy.copy(ep)
784
+ ep._graph_signature = ExportGraphSignature(
785
+ ep._graph_signature.input_specs, ep._graph_signature.output_specs
786
+ )
787
+ ep._graph_module = new_gm
788
+
789
+ # TODO T206340015
790
+ if ep.verifiers[0].dialect != "TRAINING":
791
+ ep = _remove_effect_tokens(ep)
792
+
793
+ _register_attrs_to_new_gm(new_gm, ep.graph_signature, ep.state_dict, ep.constants)
794
+ forward_arg_names = (
795
+ sig.forward_arg_names if (sig := ep.module_call_graph[0].signature) else None
796
+ )
797
+ lifted_inputs: list[str | None] = [
798
+ (
799
+ in_spec.target
800
+ if in_spec.kind
801
+ in (
802
+ InputKind.BUFFER,
803
+ InputKind.CONSTANT_TENSOR,
804
+ InputKind.PARAMETER,
805
+ InputKind.CUSTOM_OBJ,
806
+ )
807
+ else None
808
+ )
809
+ for in_spec in ep.graph_signature.input_specs
810
+ ]
811
+
812
+ mutated_outputs: list[str | None] = [
813
+ (
814
+ out_spec.target
815
+ if out_spec.kind
816
+ in (
817
+ OutputKind.BUFFER_MUTATION,
818
+ OutputKind.USER_INPUT_MUTATION,
819
+ OutputKind.PARAMETER_MUTATION,
820
+ )
821
+ else None
822
+ )
823
+ for out_spec in ep.graph_signature.output_specs
824
+ ]
825
+
826
+ for node in new_gm.graph.nodes:
827
+ source_node = None
828
+ if node.op == "placeholder":
829
+ source_node = placeholder_source_node_dict.get(node.target)
830
+ else:
831
+ if node.name in source_node_dict:
832
+ source_node = source_node_dict.get(node.name)
833
+ node.meta["from_node"] = [
834
+ NodeSource(
835
+ source_node,
836
+ "ExportedProgram.module()",
837
+ NodeSourceAction.CREATE,
838
+ )
839
+ ]
840
+
841
+ if ep.call_spec.in_spec is None:
842
+ raise AssertionError("ep.call_spec.in_spec cannot be None")
843
+ new_gm = _unlift(
844
+ new_gm,
845
+ lifted_inputs,
846
+ mutated_outputs,
847
+ ep.call_spec.in_spec,
848
+ ep.call_spec.out_spec,
849
+ forward_arg_names=forward_arg_names,
850
+ )
851
+ unlift_gm = _create_stateful_graph_module(new_gm, ep.range_constraints, ep)
852
+ unlift_gm.meta.update(ep.graph_module.meta)
853
+
854
+ # create a _guards_fn submodule and insert a call to it after placeholders
855
+ graph = unlift_gm.graph
856
+ placeholders = graph.find_nodes(op="placeholder")
857
+ if check_guards and placeholders and ep.example_inputs:
858
+ sig = inspect.signature(unlift_gm.forward)
859
+ input_paths = _get_input_paths(
860
+ ep.example_inputs,
861
+ sig,
862
+ )
863
+
864
+ # TODO (tmanlaibaatar)
865
+ # This is band-aid solution to export new tracer replacing
866
+ # shape env sources to flat_args. The real fix should be replacing
867
+ # shape env sources to original user sources but this is quite
868
+ # involved because you need to carefully construct new sources using
869
+ # dynamo and replace all instances of it inside shape env. But it is
870
+ # lot easier to manipulate after we turn them into strings and only
871
+ # time we use these guards is during retracing or running exported program,
872
+ # so it is probably ok to have "not useful" guards on ep for now.
873
+ ep_guards = []
874
+ for guard in ep._guards_code:
875
+ ep_guards.append(_replace_sources(guard, input_paths))
876
+
877
+ guards_code = _get_input_guards_for_graph(
878
+ placeholders, ep.range_constraints, input_paths
879
+ )
880
+
881
+ ep_guards_code = _force_ep_signature_match(ep._guards_code, input_paths)
882
+ ep_guards_code = _force_gm_signature_match(ep_guards_code, sig)
883
+ guards_code.extend(ep_guards_code)
884
+ unlift_gm._guards_fn = _convert_guards_code_to_fn(guards_code, input_paths)
885
+
886
+ root_nn_module_stack = torch.fx._utils.first_call_function_nn_module_stack(
887
+ graph
888
+ )
889
+ with graph.inserting_after(placeholders[-1]):
890
+ node = graph.call_module("_guards_fn", tuple(placeholders))
891
+ node.meta["nn_module_stack"] = root_nn_module_stack
892
+
893
+ unlift_gm.recompile()
894
+
895
+ return unlift_gm
896
+
897
+
898
+ class GuardsFn(torch.nn.Module):
899
+ """
900
+ Module class for guard functions.
901
+ """
902
+
903
+ def forward(self, *args):
904
+ pass
.venv/lib/python3.12/site-packages/torch/export/_wrapper_utils.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class _WrapperModule(torch.nn.Module):
5
+ def __init__(self, f): # type: ignore[no-untyped-def]
6
+ super().__init__()
7
+ self.f = f
8
+
9
+ def forward(self, *args, **kwargs): # type: ignore[no-untyped-def]
10
+ return self.f(*args, **kwargs)
.venv/lib/python3.12/site-packages/torch/export/custom_obj.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+
4
+ __all__ = ["ScriptObjectMeta"]
5
+
6
+
7
+ @dataclass
8
+ class ScriptObjectMeta:
9
+ """
10
+ Metadata which is stored on nodes representing ScriptObjects.
11
+ """
12
+
13
+ # Key into constants table to retrieve the real ScriptObject.
14
+ constant_name: str
15
+
16
+ class_fqn: str
.venv/lib/python3.12/site-packages/torch/export/custom_ops.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import importlib
3
+
4
+ import torch
5
+
6
+
7
+ lib = torch.library.Library("export", "FRAGMENT")
8
+
9
+ lib.define(
10
+ "access_subclass_inner_tensor(Tensor src_subclass_tensor, str attr) -> Tensor"
11
+ )
12
+
13
+
14
+ @torch.library.impl(lib, "access_subclass_inner_tensor", "Autograd")
15
+ # When running under torch.inference_mode(), we seem to skip Autograd key
16
+ # so we should desugar this op as soon as we start tracing to post-dispatch.
17
+ @torch.library.impl(lib, "access_subclass_inner_tensor", "Python")
18
+ def _access_subclass_inner_tensor(
19
+ src_subclass_tensor: torch.Tensor, attr: str
20
+ ) -> torch.Tensor:
21
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
22
+
23
+ if not is_traceable_wrapper_subclass(src_subclass_tensor):
24
+ raise AssertionError(
25
+ f"Expected src_subclass_tensor to be a traceable wrapper subclass, "
26
+ f"but got {type(src_subclass_tensor)}"
27
+ )
28
+ val = getattr(src_subclass_tensor, attr, None)
29
+ if val is None or not isinstance(val, torch.Tensor):
30
+ raise RuntimeError(
31
+ f"Attribute {attr} is not a tensor or doesn't exist in {src_subclass_tensor}"
32
+ )
33
+ return val
34
+
35
+
36
+ def _call_custom_autograd_function_in_pre_dispatch(function_cls_name, *args, **kwargs):
37
+ """
38
+ Import a custom autograd function by string name and call it. This is pretty bad
39
+ because:
40
+ 1) There is no schema
41
+
42
+ Ideally we should automatically wrap custom autograd functions with a custom op, but
43
+ that is too much work because we need to schematize custom autograd functions. For now,
44
+ we just hackily put it in the IR.
45
+ """
46
+ # Parse module and class name
47
+ module_name, class_name = function_cls_name.rsplit(".", 1)
48
+
49
+ # Import the module and get the class
50
+ module = importlib.import_module(module_name)
51
+ function_cls = getattr(module, class_name)
52
+ if not hasattr(function_cls, "apply"):
53
+ raise AssertionError(
54
+ f"Expected function class {function_cls_name} to have 'apply' method"
55
+ )
56
+ return function_cls.apply(*args, **kwargs)
.venv/lib/python3.12/site-packages/torch/export/decomp_utils.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable
3
+
4
+ import torch
5
+ from torch._export.utils import (
6
+ _collect_all_valid_cia_ops,
7
+ _collect_all_valid_cia_ops_for_aten_namespace,
8
+ _get_decomp_for_cia,
9
+ _is_aten_op,
10
+ )
11
+
12
+
13
+ __all__ = ["CustomDecompTable"]
14
+
15
+
16
+ """
17
+ Core ATen ops with Composite Implicit Autograd dispatch that should be excluded from decomposition
18
+ by default. The decomposition logic should eventually exclude all core-tagged CIA ops, but until all
19
+ backends are ready, this list allows opt-in one at a time.
20
+ """
21
+ PRESERVED_ATEN_CIA_OPS = {
22
+ torch.ops.aten.upsample_bilinear2d.vec,
23
+ torch.ops.aten.upsample_nearest2d.vec,
24
+ # NB: don't use the C++ decomp, because it is not functional!
25
+ torch.ops.aten.silu_backward.default,
26
+ torch.ops.aten.mish_backward.default,
27
+ torch.ops.aten._fused_rms_norm.default,
28
+ }
29
+
30
+
31
+ class CustomDecompTable(dict[torch._ops.OperatorBase, Callable]):
32
+ """
33
+ This is a custom dictionary that is specifically used for handling decomp_table in export.
34
+ The reason we need this is because in the new world, you can only *delete* an op from decomp
35
+ table to preserve it. This is problematic for custom ops because we don't know when the custom
36
+ op will actually be loaded to the dispatcher. As a result, we need to record the custom ops operations
37
+ until we really need to materialize it (which is when we run decomposition pass.)
38
+
39
+ Invariants we hold are:
40
+ 1. All aten decomp is loaded at the init time
41
+ 2. We materialize ALL ops when user ever reads from the table to make it more likely
42
+ that dispatcher picks up the custom op.
43
+ 3. If it is write operation, we don't necessarily materialize
44
+ 4. We load the final time during export, right before calling run_decompositions()
45
+
46
+ """
47
+
48
+ def __init__(self):
49
+ super().__init__()
50
+ from torch._decomp import _core_aten_decompositions_post_autograd
51
+
52
+ # For aten ops, we load them up in the beginning
53
+ self.decomp_table = _core_aten_decompositions_post_autograd()
54
+
55
+ for op in _collect_all_valid_cia_ops_for_aten_namespace():
56
+ if op not in PRESERVED_ATEN_CIA_OPS and op not in self.decomp_table:
57
+ self.decomp_table[op] = _get_decomp_for_cia(op)
58
+
59
+ # This is to track the *pending* deleted custom ops that haven't been materialized yet
60
+ self.deleted_custom_ops = set()
61
+ # When this is true, there shouldn't be any pending operations in the table.
62
+ self.has_materialized = False
63
+
64
+ def __getitem__(self, key):
65
+ self._materialize_if_needed()
66
+ return self.decomp_table.__getitem__(key)
67
+
68
+ def __setitem__(self, key, value) -> None:
69
+ self.decomp_table.__setitem__(key, value)
70
+
71
+ if key in self.deleted_custom_ops:
72
+ self.deleted_custom_ops.remove(key)
73
+
74
+ def keys(self):
75
+ self._materialize_if_needed()
76
+ return self.decomp_table.keys()
77
+
78
+ def __delitem__(self, key) -> None:
79
+ self.pop(key)
80
+
81
+ def update(self, other_dict): # type: ignore[override]
82
+ for k, v in other_dict.items():
83
+ self.decomp_table.__setitem__(k, v)
84
+
85
+ def __missing__(self, key) -> bool:
86
+ return not self.__contains__(key)
87
+
88
+ def __contains__(self, key) -> bool:
89
+ self._materialize_if_needed()
90
+ return self.decomp_table.__contains__(key)
91
+
92
+ def __len__(self) -> int:
93
+ self._materialize_if_needed()
94
+ return self.decomp_table.__len__()
95
+
96
+ def __iter__(self):
97
+ self._materialize_if_needed()
98
+ return self.decomp_table.__iter__()
99
+
100
+ def __reversed__(self):
101
+ self._materialize_if_needed()
102
+ return self.decomp_table.__reversed__()
103
+
104
+ def copy(self) -> "CustomDecompTable":
105
+ new_dict = CustomDecompTable()
106
+ new_dict.decomp_table = self.decomp_table.copy()
107
+ new_dict.deleted_custom_ops = self.deleted_custom_ops.copy()
108
+ new_dict.has_materialized = self.has_materialized
109
+ return new_dict
110
+
111
+ def pop(self, *args):
112
+ def _pop_if_can(key):
113
+ if _is_aten_op(key):
114
+ return self.decomp_table.pop(key)
115
+
116
+ if key in self.decomp_table:
117
+ # Even if we materialized it, we should add it to the deleted
118
+ # custom ops list so that when we materialize next time,
119
+ # we should respect user's intention.
120
+ self.deleted_custom_ops.add(key)
121
+ return self.decomp_table.pop(key)
122
+
123
+ if key in self.deleted_custom_ops:
124
+ raise KeyError(f"{key} doesn't exist in the table")
125
+
126
+ self.deleted_custom_ops.add(key)
127
+ # We would come here when user pops off something that is
128
+ # not in the table. In this case, we just pretend that it
129
+ # was in the table.
130
+ return _get_decomp_for_cia(key)
131
+
132
+ if len(args) == 1:
133
+ return _pop_if_can(args[0])
134
+
135
+ if len(args) == 2:
136
+ try:
137
+ return _pop_if_can(args[0])
138
+ except KeyError:
139
+ return args[1]
140
+
141
+ def items(self):
142
+ self._materialize_if_needed()
143
+ return self.decomp_table.items()
144
+
145
+ def materialize(self) -> dict[torch._ops.OperatorBase, Callable]:
146
+ for op in _collect_all_valid_cia_ops():
147
+ if _is_aten_op(op):
148
+ continue
149
+ elif op in self.decomp_table:
150
+ continue
151
+ elif op not in self.deleted_custom_ops:
152
+ self.decomp_table[op] = _get_decomp_for_cia(op)
153
+
154
+ self.has_materialized = True
155
+ self.deleted_custom_ops = set()
156
+ return {**self.decomp_table}
157
+
158
+ def _materialize_if_needed(self) -> None:
159
+ if not self.has_materialized:
160
+ self.materialize()
.venv/lib/python3.12/site-packages/torch/export/dynamic_shapes.py ADDED
@@ -0,0 +1,1635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ import inspect
4
+ import logging
5
+ import sys
6
+ from collections import defaultdict
7
+ from collections.abc import Callable
8
+ from enum import auto, Enum
9
+ from typing import Any, TYPE_CHECKING, Union
10
+
11
+ import torch
12
+ from torch.utils._pytree import (
13
+ _get_node_type,
14
+ BUILTIN_TYPES,
15
+ KeyPath,
16
+ keystr,
17
+ MappingKey,
18
+ SequenceKey,
19
+ SUPPORTED_NODES,
20
+ tree_iter,
21
+ tree_map,
22
+ tree_map_with_path,
23
+ tree_structure,
24
+ TreeSpec,
25
+ )
26
+
27
+ from .exported_program import ExportedProgram
28
+
29
+
30
+ if TYPE_CHECKING:
31
+ from sympy import Symbol
32
+
33
+ from torch._guards import Source
34
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv, StrictMinMaxConstraint
35
+
36
+ __all__ = [
37
+ "Constraint",
38
+ "Dim",
39
+ "dims",
40
+ "refine_dynamic_shapes_from_suggested_fixes",
41
+ "AdditionalInputs",
42
+ ]
43
+
44
+
45
+ log = logging.getLogger(__name__)
46
+
47
+
48
+ class _DimHintType(Enum):
49
+ """
50
+ Enum for dynamic shape hints.
51
+ - AUTO means automatic inference of shape (static or dynamic).
52
+ - STATIC means static shape (always specialized).
53
+ - DYNAMIC means dynamic, will error out if specialized.
54
+ """
55
+
56
+ AUTO = auto()
57
+ STATIC = auto()
58
+ DYNAMIC = auto()
59
+
60
+
61
+ @dataclasses.dataclass
62
+ class _DimHint:
63
+ """
64
+ Internal class for dynamic shape hints.
65
+ - min and max are optional.
66
+ - _factory is for UX only, below example:
67
+ auto_hint = _DimHint.AUTO() # _factory=True
68
+ bounded_hint = auto_hint(min=10, max=100) # Returns new instance with _factory=False
69
+ bounded_hint(min=5, max=50) # Will fail, non-factory instance cannot be called
70
+ """
71
+
72
+ type: _DimHintType
73
+ min: int | None = None
74
+ max: int | None = None
75
+ _factory: bool | None = True
76
+
77
+ @staticmethod
78
+ def AUTO():
79
+ return _DimHint(_DimHintType.AUTO)
80
+
81
+ @staticmethod
82
+ def DYNAMIC():
83
+ return _DimHint(_DimHintType.DYNAMIC)
84
+
85
+ @staticmethod
86
+ def STATIC():
87
+ return _DimHint(_DimHintType.STATIC)
88
+
89
+ def __call__(self, min=None, max=None) -> "_DimHint":
90
+ if not self._factory:
91
+ raise TypeError(f"'{type(self)}' object is not callable")
92
+ if min is not None and min < 0:
93
+ raise AssertionError(f"min must be non-negative, got {min}")
94
+ if max is not None and max < 0:
95
+ raise AssertionError(f"max must be non-negative, got {max}")
96
+ if min is not None and max is not None and min > max:
97
+ raise AssertionError(f"min must be <= max, got min={min}, max={max}")
98
+ return _DimHint(self.type, min=min, max=max, _factory=False)
99
+
100
+ def __repr__(self):
101
+ parts = [self.type.name]
102
+ if self.min is not None:
103
+ parts.append(f"min={self.min}")
104
+ if self.max is not None:
105
+ parts.append(f"max={self.max}")
106
+ return f"DimHint({', '.join(parts)})"
107
+
108
+
109
+ class Dim:
110
+ """
111
+ The ``Dim`` class allows users to specify dynamism in their exported
112
+ programs. By marking a dimension with a ``Dim``, the compiler associates the
113
+ dimension with a symbolic integer containing a dynamic range.
114
+
115
+ The API can be used in 2 ways: Dim hints (i.e. automatic dynamic shapes:
116
+ ``Dim.AUTO``, ``Dim.DYNAMIC``, ``Dim.STATIC``), or named Dims (i.e.
117
+ ``Dim("name", min=1, max=2)``).
118
+
119
+ Dim hints provide the lowest barrier to exportability, with the user only
120
+ needing to specify if a dimension is dynamic, static, or left for the
121
+ compiler to decide (``Dim.AUTO``). The export process will automatically
122
+ infer the remaining constraints on min/max ranges and relationships between
123
+ dimensions.
124
+
125
+ Example::
126
+
127
+ class Foo(nn.Module):
128
+ def forward(self, x, y):
129
+ assert x.shape[0] == 4
130
+ assert y.shape[0] >= 16
131
+ return x @ y
132
+
133
+
134
+ x = torch.randn(4, 8)
135
+ y = torch.randn(8, 16)
136
+ dynamic_shapes = {
137
+ "x": {0: Dim.AUTO, 1: Dim.AUTO},
138
+ "y": {0: Dim.AUTO, 1: Dim.AUTO},
139
+ }
140
+ ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)
141
+
142
+ Here, export would raise an exception if we replaced all uses of ``Dim.AUTO`` with ``Dim.DYNAMIC``,
143
+ as ``x.shape[0]`` is constrained to be static by the model.
144
+
145
+ More complex relations between dimensions may also be codegened as runtime assertion nodes by the compiler,
146
+ e.g. ``(x.shape[0] + y.shape[1]) % 4 == 0``, to be raised if runtime inputs do not satisfy such constraints.
147
+
148
+ You may also specify min-max bounds for Dim hints, e.g. ``Dim.AUTO(min=16, max=32)``, ``Dim.DYNAMIC(max=64)``,
149
+ with the compiler inferring the remaining constraints within the ranges. An exception will be raised if
150
+ the valid range is entirely outside the user-specified range.
151
+
152
+ Named Dims provide a stricter way of specifying dynamism, where exceptions are raised if the compiler
153
+ infers constraints that do not match the user specification. For example, exporting the previous
154
+ model, the user would need the following ``dynamic_shapes`` argument::
155
+
156
+ s0 = Dim("s0")
157
+ s1 = Dim("s1", min=16)
158
+ dynamic_shapes = {
159
+ "x": {0: 4, 1: s0},
160
+ "y": {0: s0, 1: s1},
161
+ }
162
+ ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)
163
+
164
+ Named Dims also allow specification of relationships between dimensions, up
165
+ to univariate linear relations. For example, the following indicates one
166
+ dimension is a multiple of another plus 4::
167
+
168
+ s0 = Dim("s0")
169
+ s1 = 3 * s0 + 4
170
+
171
+ """
172
+
173
+ AUTO = _DimHint.AUTO()
174
+ DYNAMIC = _DimHint.DYNAMIC()
175
+ STATIC = _DimHint.STATIC()
176
+
177
+ def __init__(self, name: str, *, min: int | None = None, max: int | None = None):
178
+ from torch.utils._sympy.numbers import int_oo
179
+
180
+ _min = 0 if min is None else min
181
+ _max = int_oo if max is None else max
182
+ if not (_max > _min):
183
+ raise AssertionError(
184
+ f"Cannot create Dim with inconsistent min={min}, max={max}"
185
+ )
186
+ if not name.isidentifier():
187
+ raise AssertionError(f"Dim name must be a valid identifier, got {name}")
188
+ self.__name__ = name
189
+ self.min = _min
190
+ self.max = _max
191
+
192
+ def __add__(self, other) -> "Dim":
193
+ # e.g., dim + 1
194
+ if type(other) is not int:
195
+ raise NotImplementedError(
196
+ f"Attempted to add {other} to {self.__name__}, where an integer was expected. "
197
+ "(Only increasing linear operations with integer coefficients are supported.)"
198
+ )
199
+ return self._derive(lambda x: x + other)
200
+
201
+ def __radd__(self, other) -> "Dim":
202
+ return self + other
203
+
204
+ def __sub__(self, other) -> "Dim":
205
+ # e.g., dim - 1
206
+ if type(other) is not int:
207
+ raise NotImplementedError(
208
+ f"Attempted to subtract {other} from {self.__name__}, where an integer was expected. "
209
+ "(Only increasing linear operations with integer coefficients are supported.)"
210
+ )
211
+ return self._derive(lambda x: x - other)
212
+
213
+ def __rsub__(self, other) -> "Dim":
214
+ raise NotImplementedError(
215
+ f"Attempted to negate {self.__name__}. "
216
+ "(Only increasing linear operations with integer coefficients are supported.)"
217
+ )
218
+
219
+ def __mul__(self, other) -> "Dim":
220
+ # e.g., dim * 2
221
+ if type(other) is not int or other <= 0:
222
+ raise NotImplementedError(
223
+ f"Attempted to multiply {other} with {self.__name__}, where a positive integer was expected. "
224
+ "(Only increasing linear operations with integer coefficients are supported.)"
225
+ )
226
+ return self._derive(lambda x: x * other)
227
+
228
+ def __rmul__(self, other) -> "Dim":
229
+ return self * other
230
+
231
+ def _derived_name(self, fn) -> str:
232
+ from sympy import sympify
233
+
234
+ return str(fn(sympify(self.__name__)))
235
+
236
+ def _derive(self, fn) -> "Dim":
237
+ return _DerivedDim(self._derived_name(fn), self, fn)
238
+
239
+ @staticmethod
240
+ def _readable(name: str, min_: int, max_: int) -> str:
241
+ from torch.utils._sympy.numbers import int_oo
242
+
243
+ if min_ == 2:
244
+ min_ = None # type: ignore[assignment]
245
+ if max_ == int_oo:
246
+ max_ = None # type: ignore[assignment]
247
+ if min_ is None and max_ is None:
248
+ return f"Dim('{name}')"
249
+ if min_ is None:
250
+ return f"Dim('{name}', max={max_})"
251
+ if max_ is None:
252
+ return f"Dim('{name}', min={min_})"
253
+ return f"Dim('{name}', min={min_}, max={max_})"
254
+
255
+ def __repr__(self):
256
+ return Dim._readable(self.__name__, self.min, self.max)
257
+
258
+
259
+ _Dim = Dim # TODO(pianpwk): remove after it's no longer internally breaking
260
+
261
+
262
+ class _StaticDim(Dim):
263
+ """
264
+ Class for static :func:`Dim` types.
265
+
266
+ This class is only for setting and checking static dim constraints,
267
+ and the user should never interact with it.
268
+ """
269
+
270
+ def __init__(self, value: int):
271
+ self.__name__ = str(value)
272
+ self.value = value
273
+
274
+ @property
275
+ def min(self): # type: ignore[override]
276
+ return self.value # type: ignore[attr-defined]
277
+
278
+ @property
279
+ def max(self): # type: ignore[override]
280
+ return self.value # type: ignore[attr-defined]
281
+
282
+
283
+ class _DerivedDim(Dim):
284
+ """
285
+ Class for derived :func:`Dim` types.
286
+
287
+ Currently we only support increasing linear expressions with integer coefficients.
288
+ In other words, a derived Dim can always be written in the form Ax + B, where
289
+ x is a regular Dim (i.e., non-derived Dim), A and B are integers, and A is positive.
290
+ (In particular, the latter ensures that x < y => Ax + B < Ay + B.)
291
+ These restrictions on the form of derived Dims makes the metatheory simpler: e.g.,
292
+ it simplifies computing ranges for derived Dims, solving for underlying regular Dims,
293
+ deciding equalities between derived Dims, and so on.
294
+
295
+ The function lambda x: Ax + B is expressed by `fn`, where x is a normal Dim, `root`.
296
+ The range of a derived Dim is computed by mapping `fn` over the range of its `root`.
297
+ """
298
+
299
+ def __init__(self, name: str, root: Dim, fn: Callable):
300
+ self.__name__ = name
301
+ self.root = root
302
+ self.fn = fn
303
+
304
+ @property
305
+ def min(self): # type: ignore[override]
306
+ # assume that self.fn is an increasing function
307
+ # TODO(avik): use sympy value range analysis instead?
308
+ from sympy import Integer
309
+
310
+ from torch.utils._sympy.numbers import int_oo
311
+
312
+ if self.root.min is -int_oo: # type: ignore[attr-defined]
313
+ return -int_oo # fn not needed cuz increasing
314
+
315
+ _min_symint = self.fn(Integer(self.root.min)) # type: ignore[attr-defined]
316
+ root = self.root # type: ignore[attr-defined]
317
+ if _min_symint < 0:
318
+ raise AssertionError(
319
+ f"Expected derived min value of {self.__name__} to be >= 0. "
320
+ f"Please specify an appropriate min value for {root.__name__} "
321
+ f"(currently {root.min})."
322
+ )
323
+ return int(_min_symint)
324
+
325
+ @property
326
+ def max(self): # type: ignore[override]
327
+ # assume that self.fn is an increasing function
328
+ # TODO(avik): use sympy value range analysis instead?
329
+ from sympy import Integer
330
+
331
+ from torch.utils._sympy.numbers import int_oo
332
+
333
+ if self.root.max is int_oo: # type: ignore[attr-defined]
334
+ return int_oo # fn not needed cuz increasing
335
+
336
+ _max_symint = self.fn(Integer(self.root.max)) # type: ignore[attr-defined]
337
+ root = self.root # type: ignore[attr-defined]
338
+ if _max_symint > sys.maxsize - 1:
339
+ raise AssertionError(
340
+ f"Expected derived max value of {self.__name__} to be <= {sys.maxsize - 1}. "
341
+ f"Please specify an appropriate max value for {root.__name__} "
342
+ f"(currently {root.max})."
343
+ )
344
+ return int(_max_symint)
345
+
346
+ def _derive(self, fn):
347
+ # We support nesting, e.g., 2*dim + 1.
348
+ # This is implemented by composing operations on the same root.
349
+ # As a consequence, roots are always regular Dims (i.e., not derived Dims).
350
+ return _DerivedDim(
351
+ self._derived_name(fn),
352
+ self.root,
353
+ lambda x: fn(self.fn(x)),
354
+ )
355
+
356
+ def __repr__(self):
357
+ return self.__name__
358
+
359
+
360
+ def dims(
361
+ *names: str, min: int | None = None, max: int | None = None
362
+ ) -> tuple[Dim, ...]:
363
+ """
364
+ Util to create multiple :func:`Dim` types.
365
+
366
+ Returns:
367
+ A tuple of :func:`Dim` types.
368
+ """
369
+ return tuple(Dim(name, min=min, max=max) for name in names) # type: ignore[misc]
370
+
371
+
372
+ @dataclasses.dataclass
373
+ class _ConstraintTarget:
374
+ """
375
+ This represents input tensor dimensions.
376
+ """
377
+
378
+ t_id: int
379
+ dim: int
380
+
381
+
382
+ @dataclasses.dataclass
383
+ class _Constraint(_ConstraintTarget):
384
+ """
385
+ This represents a Dim describing a constraint target.
386
+
387
+ `name` is the name of the Dim.
388
+ `constraint_range` contains the min/max bounds of the Dim.
389
+ """
390
+
391
+ name: str
392
+ constraint_range: "StrictMinMaxConstraint"
393
+
394
+ def _clone_with_range(self, lower=0, upper=None):
395
+ # Import sympy locally
396
+ from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint
397
+ from torch.utils._sympy.numbers import int_oo
398
+ from torch.utils._sympy.value_ranges import ValueRanges
399
+
400
+ if upper is None:
401
+ upper = int_oo
402
+
403
+ constraint_range = StrictMinMaxConstraint(
404
+ vr=self.constraint_range.vr & ValueRanges(lower=lower, upper=upper),
405
+ warn_only=False,
406
+ )
407
+ return _Constraint(
408
+ self.t_id,
409
+ self.dim,
410
+ self.name,
411
+ constraint_range,
412
+ )
413
+
414
+ def __ge__(self, lower):
415
+ return self._clone_with_range(lower=lower)
416
+
417
+ def __gt__(self, lower):
418
+ return self._clone_with_range(lower=lower + 1)
419
+
420
+ def __le__(self, upper):
421
+ return self._clone_with_range(upper=upper)
422
+
423
+ def __lt__(self, upper):
424
+ return self._clone_with_range(upper=upper - 1)
425
+
426
+ def __bool__(self):
427
+ # NOTE(avik): We do not support compound expressions like a <= x <= b.
428
+ # This is because Python implicitly desugars them into bool(a <= x) and bool(x <= b),
429
+ # and moreover, enforces that any overload of __bool__ must return True or False.
430
+ # FWIW, sympy also raises TypeError in this case.
431
+ raise TypeError(
432
+ "Cannot determine truth value of _Constraint. "
433
+ "If you are trying to combine _Constraint's with logical connectives, "
434
+ "you can specify them separately instead."
435
+ )
436
+
437
+ @property
438
+ def serializable_spec(self):
439
+ # We need a serialization compatible format of the constraint so that it
440
+ # can be savedin the graph module w/o breaking the module serialization.
441
+ # The saved constraints will be used directly for the post-exporting pass
442
+ # that converts constraints to runtime assertion. The saved constraints
443
+ # will not be saved in the serialized module.
444
+ # TODO: A better way is needed. Currently we use 't_id' to map the constraint,
445
+ # which is not reliable
446
+ return {
447
+ "t_id": self.t_id,
448
+ "dim": self.dim,
449
+ "min": self.constraint_range.vr.lower,
450
+ "max": self.constraint_range.vr.upper,
451
+ }
452
+
453
+
454
+ @dataclasses.dataclass
455
+ class _PhantomRoot:
456
+ """
457
+ This represents the root of a derived Dim where the root does not directly
458
+ specify the shape of any input dimension, but the derived Dim does.
459
+
460
+ e.g., the input shapes 2*dim and dim + 1 are related via a "phantom" dim.
461
+
462
+ The fields `name`, `constraint_range`, and `val` carried by a phantom root
463
+ help create a symbol for it. Any derived dims with this phantom root are
464
+ backed by expressions over this symbol.
465
+ """
466
+
467
+ name: str
468
+ constraint_range: "StrictMinMaxConstraint"
469
+ val: int
470
+
471
+
472
+ @dataclasses.dataclass
473
+ class _DerivedConstraint(_ConstraintTarget):
474
+ """
475
+ This represents a derived Dim, whose root is either a regular constraint target
476
+ (which directly specifies the shape of some input dimension) or a phantom root
477
+ (which does so indirectly).
478
+
479
+ It can be thought of as a subclass of `_Constraint`, except that it does not
480
+ support <, <=, >, >= operations.
481
+ """
482
+
483
+ name: str
484
+ constraint_range: "StrictMinMaxConstraint"
485
+ root: _ConstraintTarget | _PhantomRoot
486
+ fn: Callable
487
+
488
+ @property
489
+ def serializable_spec(self):
490
+ # same as _Constraint.serializable_spec
491
+ return {
492
+ "t_id": self.t_id,
493
+ "dim": self.dim,
494
+ "min": self.constraint_range.vr.lower,
495
+ "max": self.constraint_range.vr.upper,
496
+ }
497
+
498
+
499
+ @dataclasses.dataclass
500
+ class _RelaxedConstraint(_ConstraintTarget):
501
+ """
502
+ This represents a dim marked with Dim.AUTO/DYNAMIC (i.e. mark_dynamic() or maybe_mark_dynamic()),
503
+ which leaves relations & min/max ranges for inference, instead of requiring explicit specification.
504
+ The intention is for constraint violations to not be raised if produce_guards() finds equalities or
505
+ relations between a _RelaxedConstraint and another type of _Constraint.
506
+ """
507
+
508
+ @property
509
+ def serializable_spec(self):
510
+ return {
511
+ "t_id": self.t_id,
512
+ "dim": self.dim,
513
+ }
514
+
515
+
516
+ Constraint = _Constraint | _DerivedConstraint | _RelaxedConstraint
517
+
518
+
519
+ @dataclasses.dataclass
520
+ class _IntWrapper:
521
+ """
522
+ Dummy wrapper class to wrap around integer inputs so that when we parse the
523
+ dynamic_shapes structure, we can mark if any of the integers were marked as
524
+ dynamic.
525
+ """
526
+
527
+ val: int
528
+ # Disallow specifying dynamism
529
+ dynamism: _DimHint | int | None = dataclasses.field(init=False, default=None)
530
+
531
+
532
+ def _process_equalities(
533
+ constraint: Constraint,
534
+ get_sources: Callable[[int, int], list["Source"]],
535
+ shape_env: "ShapeEnv",
536
+ names: dict[str, tuple[int, int]],
537
+ source_pairs: list[tuple["Source", "Source"]],
538
+ derived_equalities: list[tuple["Source", Union["Source", "Symbol"], Callable]],
539
+ phantom_symbols: dict[str, "Symbol"],
540
+ relaxed_sources: set["Source"],
541
+ ):
542
+ """
543
+ Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
544
+ fields of `EqualityConstraint`) based on a given input `constraint`.
545
+ """
546
+
547
+ sources = get_sources(constraint.t_id, constraint.dim)
548
+ if not sources: # empty sources due to unused shapes
549
+ return
550
+
551
+ source, *other_sources = sources
552
+ # When t.size()[dim] maps to src0, src1, ..., srcN, we add
553
+ # constraints that make src0 "equal" to src1, ..., srcN.
554
+ source_pairs.extend((source, other_source) for other_source in other_sources)
555
+ if isinstance(constraint, _Constraint):
556
+ if constraint.name in names:
557
+ shared_t_id, shared_dim = names[constraint.name]
558
+ other_sources = get_sources(shared_t_id, shared_dim)
559
+ source_pairs.extend(
560
+ (source, other_source) for other_source in other_sources
561
+ )
562
+ else:
563
+ names[constraint.name] = (constraint.t_id, constraint.dim)
564
+ elif isinstance(constraint, _DerivedConstraint):
565
+ # branch based on the root of the _DerivedConstraint
566
+ if not isinstance(constraint.root, _PhantomRoot):
567
+ # either root points to an input source
568
+ root = get_sources(constraint.root.t_id, constraint.root.dim)[0]
569
+ else:
570
+ # or root points to a phantom symbol
571
+ if constraint.root.name in phantom_symbols:
572
+ root = phantom_symbols[constraint.root.name]
573
+ else:
574
+ # create a phantom symbol in the shape env based on the _PhantomRoot
575
+ root = shape_env.create_symbol(
576
+ val=constraint.root.val,
577
+ source=torch._dynamo.source.ConstantSource(constraint.root.name),
578
+ dynamic_dim=torch.fx.experimental.symbolic_shapes.DimDynamic.DYNAMIC,
579
+ constraint_dim=constraint.root.constraint_range,
580
+ )
581
+ phantom_symbols[constraint.root.name] = root
582
+
583
+ fn = constraint.fn
584
+ # A derived equality (source, root, fn) informally corresponds to source = fn(root).
585
+ # Here source describes an input and root might describe another input or a phantom symbol.
586
+ derived_equalities.append((source, root, fn))
587
+ elif isinstance(constraint, _RelaxedConstraint):
588
+ relaxed_sources.add(source)
589
+
590
+
591
+ def _tree_map_with_path(
592
+ func: Callable[..., Any],
593
+ tree: Any,
594
+ *dynamic_shapes: Any,
595
+ tree_name: str | None = None,
596
+ ) -> Any:
597
+ """
598
+ Customized tree_map for mapping pytrees to dynamic_shapes.
599
+
600
+ For built-in types (e.g., standard collections) this behaves exactly like tree_map.
601
+
602
+ OTOH for a user-defined class C registered with pytree, we cannot assume that a C
603
+ containing tensors can be mapped to a C containing dynamic shapes (i.e., C may not
604
+ be a polymorphic container). In that case we use the flattened form of C instead.
605
+ Thus a C(**tensors) that flattens to (**tensors) will map to (**dynamic_shapes).
606
+
607
+ Args:
608
+ func: function to apply to each (int, float, str, bool, None, torch.Tensor)
609
+ tree: input pytree
610
+ dynamic_shapes: zero or more (typically one) dynamic_shapes to match
611
+
612
+ Returns:
613
+ output pytree mapping func to each (int, float, str, bool, None, torch.Tensor)
614
+ """
615
+
616
+ def is_leaf(t):
617
+ # BUILTIN_TYPES is a subset of SUPPORTED_NODES, the latter being all types
618
+ # registered with pytree. Types *not* in BUILTIN_TYPES include primitive types
619
+ # (int, float, str, bool, None, torch.Tensor), which are not in SUPPORTED_NODES,
620
+ # as well as user-defined classes registered with pytree, which are.
621
+ return _get_node_type(t) not in BUILTIN_TYPES
622
+
623
+ def f(path, t, *dynamic_shapes):
624
+ typ = _get_node_type(t)
625
+ # typ is not in BUILTIN_TYPES
626
+ if typ in SUPPORTED_NODES:
627
+ # thus typ is a user-defined class registered with pytree,
628
+ # in which case flatten and recurse
629
+ return tree_map_with_path(
630
+ f,
631
+ SUPPORTED_NODES[typ].flatten_fn(t)[0],
632
+ *dynamic_shapes,
633
+ is_leaf=is_leaf,
634
+ )
635
+ else:
636
+ return func(path, t, *dynamic_shapes)
637
+
638
+ try:
639
+ return tree_map_with_path(f, tree, *dynamic_shapes, is_leaf=is_leaf)
640
+ except ValueError as e:
641
+ if "mismatch" in e.args[0]:
642
+ # When PyTree finds a structural mismatch between tree and dynamic_shapes,
643
+ # the error message is unfortunately quite horrible. Let's fix that.
644
+ if not dynamic_shapes:
645
+ raise AssertionError(
646
+ "Cannot be a mismatch if there is no dynamic_shapes"
647
+ ) from None
648
+ if not tree_name:
649
+ raise AssertionError(
650
+ "Must provide a tree_name when there might be a mismatch"
651
+ ) from None
652
+
653
+ def _key(type_, context, i):
654
+ # derive a PyTree key given the type, context, and child # of a TreeSpec
655
+ if type_ is dict:
656
+ return MappingKey(context[i])
657
+ if type_ in (list, tuple):
658
+ if context is not None:
659
+ raise AssertionError(
660
+ f"expected context to be None for type {type_}, got {context}"
661
+ )
662
+ return SequenceKey(i)
663
+ raise AssertionError(f"Did not expect type {type_}")
664
+
665
+ def raise_mismatch_error(msg):
666
+ from torch._dynamo.exc import UserError, UserErrorType
667
+
668
+ raise UserError(
669
+ UserErrorType.INVALID_INPUT,
670
+ f"Detected mismatch between the structure of `{tree_name}` and `dynamic_shapes`: {msg}",
671
+ case_name="dynamic_shapes_validation",
672
+ )
673
+
674
+ def _compare(
675
+ treespec: TreeSpec, other_treespec: TreeSpec, path: KeyPath
676
+ ) -> None:
677
+ # raise an error at the point where tree and dynamic_shapes differ,
678
+ # including the path to that point and the reason for the difference
679
+ rendered_path = keystr(path)
680
+ if treespec.is_leaf():
681
+ return
682
+ if other_treespec.is_leaf():
683
+ raise_mismatch_error(
684
+ f"`{tree_name}{rendered_path}` is a {treespec.type}, "
685
+ f"but `dynamic_shapes{rendered_path}` is not"
686
+ )
687
+ if treespec.type != other_treespec.type:
688
+ raise_mismatch_error(
689
+ f"`{tree_name}{rendered_path}` is a {treespec.type}, "
690
+ f"but `dynamic_shapes{rendered_path}` is a {other_treespec.type}"
691
+ )
692
+ if treespec.num_children != other_treespec.num_children:
693
+ raise_mismatch_error(
694
+ f"`{tree_name}{rendered_path}` has {treespec.num_children} elements, "
695
+ f"but `dynamic_shapes{rendered_path}` has {other_treespec.num_children} elements"
696
+ )
697
+ if treespec.type is dict:
698
+ # context, children could be out of order
699
+ if set(treespec.context) != set(other_treespec.context):
700
+ raise_mismatch_error(
701
+ f"`{tree_name}{rendered_path}` has keys {treespec.context}, "
702
+ f"but `dynamic_shapes{rendered_path}` has keys {other_treespec.context}"
703
+ )
704
+ _remap = dict(
705
+ zip(other_treespec.context, other_treespec.children())
706
+ )
707
+ other_children = [_remap[k] for k in treespec.context]
708
+ else:
709
+ other_children = other_treespec.children()
710
+ for i, (child, other_child) in enumerate(
711
+ zip(treespec.children(), other_children)
712
+ ):
713
+ _compare(
714
+ child,
715
+ other_child,
716
+ path + (_key(treespec.type, treespec.context, i),),
717
+ )
718
+
719
+ treespec = tree_structure(tree, is_leaf=is_leaf)
720
+ for other_tree in dynamic_shapes:
721
+ other_treespec = tree_structure(other_tree, is_leaf)
722
+ _compare(treespec, other_treespec, ())
723
+ raise
724
+
725
+
726
+ _DynamicShapesSpec = dict[str, Any] | tuple[Any, ...] | list[Any]
727
+
728
+
729
+ def _signature(
730
+ f: ExportedProgram | torch.nn.Module | Callable[..., Any],
731
+ ) -> inspect.Signature:
732
+ if isinstance(f, ExportedProgram):
733
+ f = f.module()
734
+ return (
735
+ inspect.signature(f.forward)
736
+ if isinstance(f, torch.nn.Module)
737
+ else inspect.signature(f)
738
+ )
739
+
740
+
741
+ def _combine_args_from_signature(
742
+ signature: inspect.Signature,
743
+ args: tuple[Any, ...],
744
+ kwargs: dict[str, Any] | None,
745
+ ) -> dict[str, Any]:
746
+ kwargs = kwargs if kwargs is not None else {}
747
+ return signature.bind(*args, **kwargs).arguments
748
+
749
+
750
+ def _combine_args(
751
+ f: ExportedProgram | torch.nn.Module | Callable[..., Any],
752
+ args: tuple[Any, ...],
753
+ kwargs: dict[str, Any] | None,
754
+ ) -> dict[str, Any]:
755
+ # combine args and kwargs following the signature of f, as it happens
756
+ # in the body of f when called with *args, **kwargs
757
+ return _combine_args_from_signature(_signature(f), args, kwargs)
758
+
759
+
760
+ _MISSING = object()
761
+
762
+
763
+ def _var_keyword_param_name(signature: inspect.Signature) -> str | None:
764
+ for name, param in signature.parameters.items():
765
+ if param.kind == inspect.Parameter.VAR_KEYWORD:
766
+ return name
767
+ return None
768
+
769
+
770
+ def _variadic_kwargs_info(
771
+ f: ExportedProgram | torch.nn.Module | Callable[..., Any],
772
+ args: tuple[Any, ...],
773
+ kwargs: dict[str, Any] | None,
774
+ ) -> tuple[inspect.Signature, dict[str, Any], str | None, dict[str, Any]]:
775
+ signature = _signature(f)
776
+ combined_args = _combine_args_from_signature(signature, args, kwargs)
777
+ var_keyword_name = _var_keyword_param_name(signature)
778
+ if var_keyword_name is None or var_keyword_name not in combined_args:
779
+ return signature, combined_args, var_keyword_name, {}
780
+
781
+ var_kwargs = combined_args[var_keyword_name]
782
+ if not isinstance(var_kwargs, dict):
783
+ return signature, combined_args, var_keyword_name, {}
784
+ return signature, combined_args, var_keyword_name, var_kwargs
785
+
786
+
787
+ def _colliding_variadic_kwarg_names(
788
+ signature: inspect.Signature,
789
+ args: tuple[Any, ...],
790
+ var_kwargs: dict[str, Any],
791
+ ) -> list[str]:
792
+ positional_names = set()
793
+ arg_i = 0
794
+ for param in signature.parameters.values():
795
+ if arg_i == len(args):
796
+ break
797
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
798
+ positional_names.update(
799
+ f"{param.name}_{i}" for i in range(len(args) - arg_i)
800
+ )
801
+ break
802
+ if param.kind in {
803
+ inspect.Parameter.POSITIONAL_ONLY,
804
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
805
+ }:
806
+ positional_names.add(param.name)
807
+ arg_i += 1
808
+ elif param.kind == inspect.Parameter.KEYWORD_ONLY:
809
+ break
810
+ return sorted(set(var_kwargs) & positional_names)
811
+
812
+
813
+ def _normalize_dynamic_shapes(
814
+ dynamic_shapes: _DynamicShapesSpec | None,
815
+ f: ExportedProgram | torch.nn.Module | Callable[..., Any],
816
+ args: tuple[Any, ...],
817
+ kwargs: dict[str, Any] | None,
818
+ ) -> _DynamicShapesSpec | None:
819
+ """
820
+ Normalize call-like dynamic shape specs for **kwargs to the signature-shaped
821
+ structure used by the rest of dynamic shapes processing.
822
+ """
823
+ if not dynamic_shapes:
824
+ return dynamic_shapes
825
+
826
+ signature, combined_args, var_keyword_name, var_kwargs = _variadic_kwargs_info(
827
+ f, args, kwargs
828
+ )
829
+ if var_keyword_name is None or not var_kwargs:
830
+ return dynamic_shapes
831
+
832
+ from torch._dynamo.exc import UserError, UserErrorType
833
+
834
+ collisions = _colliding_variadic_kwarg_names(signature, args, var_kwargs)
835
+ if collisions:
836
+ raise UserError(
837
+ UserErrorType.INVALID_INPUT,
838
+ "Cannot represent dynamic shapes for variadic keyword argument(s) "
839
+ f"{collisions} because they collide with another input name used "
840
+ "for positional inputs.",
841
+ case_name="dynamic_shapes_validation",
842
+ )
843
+
844
+ if not isinstance(dynamic_shapes, dict):
845
+ return dynamic_shapes
846
+
847
+ result = dict(dynamic_shapes)
848
+ nested = result.get(var_keyword_name, _MISSING)
849
+ nested_shapes = dict(nested) if isinstance(nested, dict) else nested
850
+ fixed_arg_names = set(combined_args) - {var_keyword_name}
851
+
852
+ for key in var_kwargs:
853
+ has_nested_shape = isinstance(nested_shapes, dict) and key in nested_shapes
854
+ if key in fixed_arg_names or key == var_keyword_name:
855
+ if key in result and not has_nested_shape:
856
+ raise UserError(
857
+ UserErrorType.INVALID_INPUT,
858
+ f"Cannot represent dynamic shape for variadic keyword argument "
859
+ f"'{key}' as a top-level key because it collides with another "
860
+ f"input name. Specify it under the variadic keyword parameter "
861
+ f"instead, e.g. `dynamic_shapes['{var_keyword_name}']['{key}']`.",
862
+ case_name="dynamic_shapes_validation",
863
+ )
864
+ continue
865
+
866
+ if key in result:
867
+ if nested is not _MISSING and not isinstance(nested_shapes, dict):
868
+ raise UserError(
869
+ UserErrorType.INVALID_INPUT,
870
+ f"Cannot merge dynamic shape for variadic keyword argument "
871
+ f"'{key}' into `dynamic_shapes['{var_keyword_name}']` because "
872
+ "that entry is not a dict.",
873
+ case_name="dynamic_shapes_validation",
874
+ )
875
+ if has_nested_shape:
876
+ raise UserError(
877
+ UserErrorType.INVALID_INPUT,
878
+ f"Found dynamic shape for variadic keyword argument '{key}' "
879
+ f"both as a top-level key and under "
880
+ f"`dynamic_shapes['{var_keyword_name}']`.",
881
+ case_name="dynamic_shapes_validation",
882
+ )
883
+ if not isinstance(nested_shapes, dict):
884
+ nested_shapes = {}
885
+ nested_shapes[key] = result.pop(key)
886
+
887
+ if isinstance(nested_shapes, dict):
888
+ result[var_keyword_name] = nested_shapes
889
+ return result
890
+
891
+
892
+ def _combine_args_for_tracing(
893
+ f: ExportedProgram | torch.nn.Module | Callable[..., Any],
894
+ args: tuple[Any, ...],
895
+ kwargs: dict[str, Any] | None,
896
+ dynamic_shapes: Any,
897
+ ) -> tuple[dict[Any, Any], Any]:
898
+ if not dynamic_shapes:
899
+ return _combine_args(f, args, kwargs), dynamic_shapes
900
+
901
+ kwargs = kwargs if kwargs is not None else {}
902
+ signature, combined_args, var_keyword_name, var_kwargs = _variadic_kwargs_info(
903
+ f, args, kwargs
904
+ )
905
+ if isinstance(dynamic_shapes, (tuple, list)):
906
+ dynamic_shapes_by_name = dict(zip(combined_args, dynamic_shapes))
907
+ else:
908
+ dynamic_shapes_by_name = dynamic_shapes
909
+
910
+ if not isinstance(dynamic_shapes_by_name, dict):
911
+ return combined_args, dynamic_shapes
912
+
913
+ traced_args = []
914
+ traced_dynamic_shapes = []
915
+ traced_names = []
916
+ arg_i = 0
917
+ for param in signature.parameters.values():
918
+ if arg_i == len(args):
919
+ break
920
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
921
+ var_args = combined_args[param.name]
922
+ var_arg_dynamic_shapes = dynamic_shapes_by_name[param.name]
923
+ for i, arg in enumerate(var_args):
924
+ traced_args.append(arg)
925
+ traced_dynamic_shapes.append(var_arg_dynamic_shapes[i])
926
+ traced_names.append(f"{param.name}_{i}")
927
+ arg_i = len(args)
928
+ break
929
+ if param.kind in {
930
+ inspect.Parameter.POSITIONAL_ONLY,
931
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
932
+ }:
933
+ traced_args.append(combined_args[param.name])
934
+ traced_dynamic_shapes.append(dynamic_shapes_by_name[param.name])
935
+ traced_names.append(param.name)
936
+ arg_i += 1
937
+
938
+ for key, arg in kwargs.items():
939
+ traced_args.append(arg)
940
+ traced_names.append(key)
941
+ if var_keyword_name is not None and key in var_kwargs:
942
+ traced_dynamic_shapes.append(dynamic_shapes_by_name[var_keyword_name][key])
943
+ else:
944
+ traced_dynamic_shapes.append(dynamic_shapes_by_name[key])
945
+
946
+ if isinstance(dynamic_shapes, dict) and len(set(traced_names)) == len(traced_names):
947
+ return dict(zip(traced_names, traced_args)), dict(
948
+ zip(traced_names, traced_dynamic_shapes)
949
+ )
950
+ return dict(enumerate(traced_args)), tuple(traced_dynamic_shapes)
951
+
952
+
953
+ class ShapesCollection:
954
+ """
955
+ Builder for dynamic_shapes.
956
+ Used to assign dynamic shape specifications to tensors that appear in inputs.
957
+
958
+ Note: this produces the ``Dim``-based ``dynamic_shapes`` format only; it does
959
+ not (yet) emit the structured ``ShapesSpec`` / ``ParamsSpec`` API.
960
+
961
+ This is useful particularly when :func:`args` is a nested input structure, and it's
962
+ easier to index the input tensors, than to replicate the structure of :func:`args` in
963
+ the :func:`dynamic_shapes` specification.
964
+
965
+ Example::
966
+
967
+ args = {"x": tensor_x, "others": [tensor_y, tensor_z]}
968
+
969
+ dim = torch.export.Dim(...)
970
+ dynamic_shapes = torch.export.ShapesCollection()
971
+ dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
972
+ dynamic_shapes[tensor_y] = {0: dim * 2}
973
+ # This is equivalent to the following (now auto-generated):
974
+ # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [{0: dim * 2}, None]}
975
+
976
+ torch.export(..., args, dynamic_shapes=dynamic_shapes)
977
+
978
+ To specify dynamism for integers, we need to first wrap the integers using
979
+ _IntWrapper so that we have a "unique identification tag" for each integer.
980
+
981
+ Example::
982
+
983
+ args = {"x": tensor_x, "others": [int_x, int_y]}
984
+ # Wrap all ints with _IntWrapper
985
+ mapped_args = pytree.tree_map_only(int, lambda a: _IntWrapper(a), args)
986
+
987
+ dynamic_shapes = torch.export.ShapesCollection()
988
+ dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
989
+ dynamic_shapes[mapped_args["others"][0]] = Dim.DYNAMIC
990
+
991
+ # This is equivalent to the following (now auto-generated):
992
+ # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [Dim.DYNAMIC, None]}
993
+
994
+ torch.export(..., args, dynamic_shapes=dynamic_shapes)
995
+ """
996
+
997
+ def __init__(self):
998
+ self._shapes = {}
999
+
1000
+ def __setitem__(self, t, shape):
1001
+ if not isinstance(t, (torch.Tensor, _IntWrapper)):
1002
+ raise AssertionError(
1003
+ f"Cannot assign shape to non-tensor or non-_IntWrapper type {type(t)}"
1004
+ )
1005
+
1006
+ # TODO(avik): check that shape is indeed a Shape
1007
+
1008
+ t_id = id(t)
1009
+ if t_id in self._shapes:
1010
+ _shape = self._shapes[t_id]
1011
+ if shape != _shape:
1012
+ raise AssertionError(
1013
+ f"Shapes assigned to input do not match: expected {_shape}, got {shape}"
1014
+ )
1015
+ else:
1016
+ self._shapes[id(t)] = shape
1017
+
1018
+ def __getitem__(self, t):
1019
+ t_id = id(t)
1020
+ if t_id not in self._shapes:
1021
+ self._shapes[t_id] = {}
1022
+ return self._shapes[t_id]
1023
+
1024
+ def __len__(self):
1025
+ return len(self._shapes)
1026
+
1027
+ def dynamic_shapes(self, m, args, kwargs=None):
1028
+ """
1029
+ Generates the :func:`dynamic_shapes` pytree structure according to :func:`args` and :func:`kwargs`.
1030
+ """
1031
+
1032
+ t_ids = set()
1033
+
1034
+ def find_shape(path, t):
1035
+ t_id = id(t)
1036
+ if t_id in self._shapes:
1037
+ t_ids.add(t_id)
1038
+ return self._shapes[t_id]
1039
+ else:
1040
+ return None
1041
+
1042
+ combined_args = _combine_args(m, args, kwargs)
1043
+ dynamic_shapes = _tree_map_with_path(find_shape, combined_args)
1044
+ if any(t_id not in t_ids for t_id in self._shapes):
1045
+ raise ValueError(
1046
+ "Some tensors that were assigned shapes were not found in args. "
1047
+ "Maybe such tensors were copied when passing them as args? "
1048
+ "Maybe such tensors are contained in classes that were not registered with pytree?"
1049
+ )
1050
+ return dynamic_shapes
1051
+
1052
+
1053
+ class AdditionalInputs:
1054
+ """
1055
+ Infers dynamic_shapes based on additional inputs.
1056
+
1057
+ Note: this produces the ``Dim``-based ``dynamic_shapes`` format only; it does
1058
+ not (yet) emit the structured ``ShapesSpec`` / ``ParamsSpec`` API.
1059
+
1060
+ This is useful particularly for deployment engineers who, on the one hand, may
1061
+ have access to ample testing or profiling data that can provide a fair sense of
1062
+ representative inputs for a model, but on the other hand, may not know enough
1063
+ about the model to guess which input shapes should be dynamic.
1064
+
1065
+ Input shapes that are different than the original are considered dynamic; conversely,
1066
+ those that are the same as the original are considered static. Moreover, we verify
1067
+ that the additional inputs are valid for the exported program. This guarantees that
1068
+ tracing with them instead of the original would have generated the same graph.
1069
+
1070
+ Example::
1071
+
1072
+ args0, kwargs0 = ... # example inputs for export
1073
+
1074
+ # other representative inputs that the exported program will run on
1075
+ dynamic_shapes = torch.export.AdditionalInputs()
1076
+ dynamic_shapes.add(args1, kwargs1)
1077
+ ...
1078
+ dynamic_shapes.add(argsN, kwargsN)
1079
+
1080
+ torch.export(..., args0, kwargs0, dynamic_shapes=dynamic_shapes)
1081
+ """
1082
+
1083
+ def __init__(self):
1084
+ self._examples = []
1085
+
1086
+ def add(self, args, kwargs=None):
1087
+ """
1088
+ Additional input :func:`args` and :func:`kwargs`.
1089
+ """
1090
+
1091
+ if type(args) is not tuple:
1092
+ raise AssertionError(f"Representative args {args} must be a tuple")
1093
+ if kwargs is not None and type(kwargs) is not dict:
1094
+ raise AssertionError(
1095
+ f"Representative kwargs {kwargs} must be None or a dict"
1096
+ )
1097
+ self._examples.append((args, kwargs))
1098
+
1099
+ def dynamic_shapes(self, m, args, kwargs=None):
1100
+ """
1101
+ Infers a :func:`dynamic_shapes` pytree structure by merging shapes of the
1102
+ original input :func:`args` and :func:`kwargs` and of each additional input
1103
+ args and kwargs.
1104
+ """
1105
+
1106
+ dynamic_shapes, *other_dynamic_shapes = [
1107
+ _tree_map_with_path(
1108
+ lambda path, t: tuple(t.shape) if isinstance(t, torch.Tensor) else t,
1109
+ _combine_args(m, args, kwargs),
1110
+ )
1111
+ for args, kwargs in [(args, kwargs), *self._examples]
1112
+ ]
1113
+
1114
+ def _mark_dynamism(v, *other_vs):
1115
+ if not all(type(v) is type(other) for other in other_vs):
1116
+ raise ValueError(
1117
+ "The following inputs were found to have differing types, "
1118
+ f"so they cannot be marked as dynamic: {(v,) + other_vs}."
1119
+ )
1120
+
1121
+ if isinstance(v, int) and not isinstance(v, bool):
1122
+ if all(other_v == v for other_v in other_vs):
1123
+ return None
1124
+ else:
1125
+ return Dim.DYNAMIC
1126
+ else:
1127
+ if not all(other_v == v for other_v in other_vs):
1128
+ raise ValueError(
1129
+ "The following inputs were found to have differing values, "
1130
+ f"but they cannot be marked as dynamic: {(v,) + other_vs}."
1131
+ )
1132
+ return None
1133
+
1134
+ return tree_map(
1135
+ _mark_dynamism,
1136
+ dynamic_shapes,
1137
+ *other_dynamic_shapes,
1138
+ is_leaf=lambda i: type(i) is int,
1139
+ )
1140
+
1141
+ def verify(self, ep):
1142
+ """
1143
+ Verifies that an exported program is valid for each additional input.
1144
+ """
1145
+
1146
+ epm = ep.module()
1147
+ for args, kwargs in self._examples:
1148
+ torch.export._unlift._check_input_constraints_for_module(
1149
+ epm, args, kwargs or {}
1150
+ )
1151
+
1152
+
1153
+ def _warn_on_None_dynamic_shape_dimension():
1154
+ msg = (
1155
+ "Using None as a dynamic shape dimension is deprecated. "
1156
+ "Please use Dim.STATIC instead"
1157
+ )
1158
+ # TODO(avik): raise an error in the future
1159
+ log.warning(msg)
1160
+
1161
+
1162
+ def _check_dynamic_shapes(
1163
+ combined_args: dict[str, Any],
1164
+ dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
1165
+ ):
1166
+ """
1167
+ Checks the dynamic_shapes specification for correctness,
1168
+ using combined args + kwargs as reference for inputs structure.
1169
+ """
1170
+ from torch._dynamo.exc import UserError, UserErrorType
1171
+
1172
+ if dynamic_shapes is None or len(dynamic_shapes) == 0:
1173
+ return
1174
+ if isinstance(dynamic_shapes, (tuple, list)):
1175
+ combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc]
1176
+
1177
+ bounds: dict[str, tuple[int, int]] = {}
1178
+
1179
+ def check_same_bounds(dim):
1180
+ if dim.__name__ in bounds:
1181
+ min_, max_ = bounds[dim.__name__]
1182
+ if dim.min != min_ or dim.max != max_:
1183
+ this_ = Dim._readable(dim.__name__, min_, max_)
1184
+ that_ = Dim._readable(dim.__name__, dim.min, dim.max)
1185
+ raise UserError(
1186
+ UserErrorType.INVALID_INPUT,
1187
+ f"Found different definitions {this_} and {that_} "
1188
+ f"for the same symbolic dimension {dim}!",
1189
+ )
1190
+ else:
1191
+ bounds[dim.__name__] = (dim.min, dim.max)
1192
+
1193
+ def check_symbols(path, tensor, shape):
1194
+ if isinstance(shape, dict):
1195
+ for i, dim in shape.items():
1196
+ if isinstance(dim, Dim):
1197
+ check_same_bounds(dim)
1198
+ elif dim is None:
1199
+ _warn_on_None_dynamic_shape_dimension()
1200
+ elif not (isinstance(dim, (int, _DimHint))):
1201
+ raise UserError(
1202
+ UserErrorType.INVALID_INPUT,
1203
+ f"Unexpected dimension mapped to index {i} in input tensor shape {shape} "
1204
+ f"specified at `dynamic_shapes{keystr(path)}` "
1205
+ f"(expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC, "
1206
+ f" but got {dim!r} instead)",
1207
+ case_name="dynamic_shapes_validation",
1208
+ )
1209
+ elif isinstance(shape, (tuple, list)):
1210
+ if len(shape) != len(tensor.shape):
1211
+ raise UserError(
1212
+ UserErrorType.INVALID_INPUT,
1213
+ f"Expected dynamic shape spec {shape} specified at `dynamic_shapes{keystr(path)}` "
1214
+ f"to have the same length as the actual tensor shape {tensor.shape} "
1215
+ f"(expected {len(tensor.shape)}, but got {len(shape)} instead)",
1216
+ case_name="dynamic_shapes_validation",
1217
+ )
1218
+ for i, dim in enumerate(shape):
1219
+ if isinstance(dim, Dim):
1220
+ check_same_bounds(dim)
1221
+ elif dim is None:
1222
+ _warn_on_None_dynamic_shape_dimension()
1223
+ elif not (isinstance(dim, (int, _DimHint))):
1224
+ raise UserError(
1225
+ UserErrorType.INVALID_INPUT,
1226
+ f"Unexpected dimension #{i} in input tensor shape {shape} "
1227
+ f"specified at `dynamic_shapes{keystr(path)}` "
1228
+ f"(expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC, "
1229
+ f"but got {dim!r} instead)",
1230
+ case_name="dynamic_shapes_validation",
1231
+ )
1232
+ elif shape is not None:
1233
+ raise UserError(
1234
+ UserErrorType.INVALID_INPUT,
1235
+ f"Unexpected input tensor shape {shape} specified at `dynamic_shapes{keystr(path)}` "
1236
+ f"(expected either a list/tuple of dimensions, or a dict mapping indices to dimensions,"
1237
+ f" where each dimension is an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC)",
1238
+ case_name="dynamic_shapes_validation",
1239
+ )
1240
+
1241
+ if not isinstance(dynamic_shapes, (dict, tuple, list)):
1242
+ raise AssertionError(
1243
+ f"expected dynamic_shapes to be dict, tuple, or list, got {type(dynamic_shapes)}"
1244
+ )
1245
+ if isinstance(dynamic_shapes, dict):
1246
+ got_keys = list(dynamic_shapes.keys())
1247
+ expected_arg_names = list(combined_args.keys())
1248
+ if sorted(got_keys) != sorted(expected_arg_names):
1249
+ msg = (
1250
+ f"When `dynamic_shapes` is specified as a dict, its top-level keys "
1251
+ f"must be the arg names {expected_arg_names} of `inputs`, but "
1252
+ f"here they are {got_keys}. "
1253
+ )
1254
+ if (
1255
+ len(combined_args) == 1
1256
+ and expected_arg_names[0] not in got_keys
1257
+ and isinstance(combined_args[expected_arg_names[0]], dict)
1258
+ ):
1259
+ msg += (
1260
+ "Since here `inputs` is a list/tuple enclosing a single dict, "
1261
+ "maybe you just forgot to enclose `dynamic_shapes` in a list/tuple?"
1262
+ )
1263
+ else:
1264
+ msg += (
1265
+ "Alternatively, you could also ignore arg names entirely "
1266
+ "and specify `dynamic_shapes` as a list/tuple matching `inputs`."
1267
+ )
1268
+ raise UserError(
1269
+ UserErrorType.INVALID_INPUT, msg, case_name="dynamic_shapes_validation"
1270
+ )
1271
+
1272
+ def check_shape(path, t, dynamic_shape):
1273
+ if isinstance(t, torch.Tensor):
1274
+ check_symbols(path, t, dynamic_shape)
1275
+ elif isinstance(t, _IntWrapper):
1276
+ if isinstance(dynamic_shape, _Dim):
1277
+ raise ValueError(
1278
+ "Unable to specify input integers as dynamic through named "
1279
+ "Dims. Please use Dim.AUTO/DYNAMIC instead."
1280
+ )
1281
+ if dynamic_shape is not None and not isinstance(
1282
+ dynamic_shape, (int, _DimHint)
1283
+ ):
1284
+ raise AssertionError(
1285
+ f"expected dynamic_shape to be None, int, or _DimHint for _IntWrapper, got {type(dynamic_shape)}"
1286
+ )
1287
+ else:
1288
+ if dynamic_shape is not None:
1289
+ rendered_path = keystr(path)
1290
+ raise UserError(
1291
+ UserErrorType.INVALID_INPUT,
1292
+ f"Cannot associate shape {dynamic_shape} specified at `dynamic_shapes{rendered_path}` "
1293
+ f"to non-tensor type {type(t)} at `inputs{rendered_path}` (expected None)",
1294
+ case_name="dynamic_shapes_validation",
1295
+ )
1296
+
1297
+ _tree_map_with_path(check_shape, combined_args, dynamic_shapes, tree_name="inputs")
1298
+
1299
+
1300
+ def _process_dynamic_shapes(
1301
+ combined_args: dict[str, Any],
1302
+ dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
1303
+ ) -> list[Constraint]:
1304
+ """
1305
+ Reads the dynamic_shapes specification and produces a list of constraints.
1306
+ """
1307
+ from torch._dynamo.exc import UserError, UserErrorType
1308
+
1309
+ if dynamic_shapes is None or len(dynamic_shapes) == 0:
1310
+ # we run with dynamic by default, so no need to produce constraints
1311
+ return []
1312
+ if isinstance(dynamic_shapes, (tuple, list)):
1313
+ combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc]
1314
+
1315
+ # map of Dim names representing input shape dimensions to constraints on them
1316
+ symbols: dict[str, list[Constraint]] = defaultdict(list)
1317
+ # track roots that do not directly represent input shape dimensions
1318
+ phantom_roots: dict[str, _PhantomRoot] = {}
1319
+ derived_constraints_with_phantom_root: list[_DerivedConstraint] = []
1320
+ # list of constraints to return
1321
+ constraints: list[Constraint] = []
1322
+
1323
+ def to_constraint(dim, tensor, i):
1324
+ import sympy
1325
+
1326
+ from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint
1327
+ from torch.utils._sympy.solve import try_solve
1328
+ from torch.utils._sympy.value_ranges import ValueRanges
1329
+
1330
+ def root_value():
1331
+ # given tensor.shape[i] is the value of dim = fn(root),
1332
+ # find the value of root
1333
+ symbol = sympy.Symbol(dim.root.__name__, integer=True)
1334
+ expr = dim.fn(symbol)
1335
+ solution = try_solve(sympy.Eq(expr, tensor.shape[i]), symbol)
1336
+ if solution is not None:
1337
+ return int(solution[1])
1338
+ else:
1339
+ raise UserError(
1340
+ UserErrorType.CONSTRAINT_VIOLATION,
1341
+ f"Expected shape[{i}] = {tensor.shape[i]} of input Tensor to be "
1342
+ f"of the form {expr}, where {symbol} is an integer",
1343
+ )
1344
+
1345
+ if isinstance(dim, _DerivedDim):
1346
+ # generate a _DerivedConstraint where the root is:
1347
+ # - either a _ConstraintTarget (if dim.root directly describes an input shape)
1348
+ # - or a _PhantomRoot (otherwise)
1349
+ dim_root = dim.root # type: ignore[attr-defined]
1350
+ if dim_root.__name__ in symbols:
1351
+ # root represents an input shape dimension
1352
+ root_constraint = symbols[dim_root.__name__][0]
1353
+ root = _ConstraintTarget(
1354
+ root_constraint.t_id,
1355
+ root_constraint.dim,
1356
+ )
1357
+ elif dim_root.__name__ not in phantom_roots:
1358
+ # create a phantom root
1359
+ root = _PhantomRoot( # type: ignore[assignment]
1360
+ name=dim_root.__name__,
1361
+ constraint_range=StrictMinMaxConstraint(
1362
+ vr=ValueRanges(lower=dim_root.min, upper=dim_root.max),
1363
+ warn_only=False,
1364
+ ),
1365
+ val=root_value(),
1366
+ )
1367
+ phantom_roots[dim_root.__name__] = root # type: ignore[assignment]
1368
+ else:
1369
+ root = phantom_roots[dim_root.__name__] # type: ignore[assignment]
1370
+ constraint = _DerivedConstraint(
1371
+ id(tensor),
1372
+ i,
1373
+ dim.__name__,
1374
+ StrictMinMaxConstraint(
1375
+ vr=ValueRanges(lower=dim.min, upper=dim.max),
1376
+ warn_only=False,
1377
+ ),
1378
+ root,
1379
+ dim.fn, # type: ignore[attr-defined]
1380
+ )
1381
+ if isinstance(root, _PhantomRoot):
1382
+ # NOTE(avik): since we have not processed all inputs yet, we may replace this
1383
+ # with a root that does represent an input shape dimension later (see below)
1384
+ derived_constraints_with_phantom_root.append(constraint)
1385
+ elif isinstance(dim, _StaticDim):
1386
+ constraint = _Constraint( # type: ignore[assignment]
1387
+ id(tensor),
1388
+ i,
1389
+ dim.__name__,
1390
+ StrictMinMaxConstraint(
1391
+ vr=ValueRanges(lower=dim.value, upper=dim.value), # type: ignore[attr-defined]
1392
+ warn_only=False,
1393
+ ),
1394
+ )
1395
+ else:
1396
+ if not isinstance(dim, Dim):
1397
+ raise AssertionError(f"expected dim to be Dim, got {type(dim)}")
1398
+ constraint = _Constraint( # type: ignore[assignment]
1399
+ id(tensor),
1400
+ i,
1401
+ dim.__name__,
1402
+ StrictMinMaxConstraint(
1403
+ vr=ValueRanges(lower=dim.min, upper=dim.max), # type: ignore[attr-defined]
1404
+ warn_only=False,
1405
+ ),
1406
+ )
1407
+ return constraint
1408
+
1409
+ def _parse_tensor_dim(tensor, idx, dim) -> None:
1410
+ def _create_static_dim(tensor, i, value):
1411
+ return _StaticDim(value)
1412
+
1413
+ if isinstance(dim, (int, Dim)):
1414
+ if isinstance(dim, int):
1415
+ dim = _create_static_dim(tensor, idx, dim)
1416
+ constraint = to_constraint(dim, tensor, idx)
1417
+ symbols[dim.__name__].append(constraint)
1418
+ elif isinstance(dim, _DimHint):
1419
+ if dim.type == _DimHintType.AUTO:
1420
+ torch._dynamo.maybe_mark_dynamic(tensor, idx)
1421
+ elif dim.type == _DimHintType.STATIC:
1422
+ torch._dynamo.mark_static(tensor, idx)
1423
+ elif dim.type == _DimHintType.DYNAMIC:
1424
+ torch._dynamo.mark_dynamic(tensor, idx)
1425
+ constraints.append(_RelaxedConstraint(id(tensor), idx))
1426
+ elif dim is None:
1427
+ torch._dynamo.mark_static(tensor, idx)
1428
+
1429
+ def update_symbols(path, tensor, shape):
1430
+ # clean out decorators from user side, or previous export call
1431
+ # we also delete these attributes in non_strict_utils.py/make_constraints()
1432
+ tensor._dynamo_weak_dynamic_indices = set()
1433
+ tensor._dynamo_dynamic_indices = set()
1434
+ tensor._dynamo_dynamic_range = set()
1435
+ tensor._dynamo_static_indices = set()
1436
+ tensor._dynamo_unbacked_indices = set()
1437
+
1438
+ if isinstance(shape, dict):
1439
+ for i, dim in shape.items():
1440
+ _parse_tensor_dim(tensor, i, dim)
1441
+ elif isinstance(shape, (tuple, list)):
1442
+ for i, dim in enumerate(shape):
1443
+ _parse_tensor_dim(tensor, i, dim)
1444
+ elif shape is None:
1445
+ for i in range(tensor.dim()):
1446
+ _parse_tensor_dim(tensor, i, None)
1447
+
1448
+ def assoc_shape(path, t, dynamic_shape):
1449
+ if isinstance(t, torch.Tensor):
1450
+ update_symbols(path, t, dynamic_shape)
1451
+ elif isinstance(t, _IntWrapper):
1452
+ # If tensor dimensions are marked as dynamic, the tensors themselves
1453
+ # get marked using mark_dynamic. However since we can't mark
1454
+ # integers as dynamic, we first wrap integers in this class, and
1455
+ # then set the `dim` field of the class with the dynamic shapes dim
1456
+ # to mark the integer as dynamic.
1457
+ t.dynamism = dynamic_shape
1458
+
1459
+ _tree_map_with_path(assoc_shape, combined_args, dynamic_shapes, tree_name="inputs")
1460
+
1461
+ for derived_constraint_with_phantom_root in derived_constraints_with_phantom_root:
1462
+ phantom_root_name = derived_constraint_with_phantom_root.root.name # type: ignore[union-attr]
1463
+ if phantom_root_name in symbols:
1464
+ # We found an input shape dimension corresponding to this name, so we
1465
+ # do not need a phantom symbol for it after all.
1466
+ # NOTE(avik): Overall we want to maintain the invariant that roots that
1467
+ # are phantom symbols are really "phantom," i.e., they cannot be represented
1468
+ # by any input source. This is important when we are deciding derived equalities,
1469
+ # since we can focus our attention exclusively on input sources: deciding
1470
+ # derived equalities involving phantom symbols are, in comparison, trivial.
1471
+ derived_constraint_with_phantom_root.root = symbols[phantom_root_name][0]
1472
+
1473
+ for dynamic_dims in symbols.values():
1474
+ constraints.extend(dynamic_dims)
1475
+
1476
+ return constraints
1477
+
1478
+
1479
+ def _get_dim_name_mapping(
1480
+ dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
1481
+ ):
1482
+ name_to_dim = {}
1483
+ for dim in tree_iter(dynamic_shapes, is_leaf=lambda x: isinstance(x, Dim)):
1484
+ if dim is None:
1485
+ # NOTE: this must denote a non-Tensor or automatic at this point.
1486
+ continue
1487
+ if isinstance(dim, int):
1488
+ continue
1489
+ elif isinstance(dim, Dim):
1490
+ name_to_dim[dim.__name__] = dim
1491
+ if isinstance(dim, _DerivedDim):
1492
+ name_to_dim[dim.root.__name__] = dim.root # type: ignore[attr-defined]
1493
+ else:
1494
+ if not isinstance(dim, _DimHint):
1495
+ raise AssertionError(f"expected dim to be _DimHint, got {type(dim)}")
1496
+ return name_to_dim
1497
+
1498
+
1499
+ def refine_dynamic_shapes_from_suggested_fixes(
1500
+ msg: str,
1501
+ dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any],
1502
+ ) -> dict[str, Any] | tuple[Any] | list[Any]:
1503
+ """
1504
+ When exporting with :func:`dynamic_shapes`, export may fail with a ConstraintViolation error if the specification
1505
+ doesn't match the constraints inferred from tracing the model. The error message may provide suggested fixes -
1506
+ changes that can be made to :func:`dynamic_shapes` to export successfully.
1507
+
1508
+ Example ConstraintViolation error message::
1509
+
1510
+ Suggested fixes:
1511
+
1512
+ dim = Dim('dim', min=3, max=6) # this just refines the dim's range
1513
+ dim = 4 # this specializes to a constant
1514
+ dy = dx + 1 # dy was specified as an independent dim, but is actually tied to dx with this relation
1515
+
1516
+ This is a helper function that takes the ConstraintViolation error message and the original :func:`dynamic_shapes` spec,
1517
+ and returns a new :func:`dynamic_shapes` spec that incorporates the suggested fixes.
1518
+
1519
+ Example usage::
1520
+
1521
+ try:
1522
+ ep = export(mod, args, dynamic_shapes=dynamic_shapes)
1523
+ except torch._dynamo.exc.UserError as exc:
1524
+ new_shapes = refine_dynamic_shapes_from_suggested_fixes(
1525
+ exc.msg, dynamic_shapes
1526
+ )
1527
+ ep = export(mod, args, dynamic_shapes=new_shapes)
1528
+
1529
+ """
1530
+
1531
+ import re
1532
+
1533
+ import sympy
1534
+
1535
+ from torch._dynamo.exc import UserError, UserErrorType
1536
+ from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence
1537
+
1538
+ try:
1539
+ shape_fixes_msg = msg.split("Suggested fixes:")[1].strip()
1540
+ except Exception as exc:
1541
+ raise UserError(
1542
+ UserErrorType.INVALID_INPUT,
1543
+ "Suggested fixes not found in error message given to refine_dynamic_shapes_from_suggested_fixes()",
1544
+ ) from exc
1545
+
1546
+ # build shape_fixes dictionary
1547
+ shape_fixes = {}
1548
+ for fix in shape_fixes_msg.split("\n"):
1549
+ fix = fix.strip()
1550
+ if match := re.match(r"(.*) = Dim\('(.*)'.*\)", fix):
1551
+ name = match.group(1)
1552
+ _min, _max = None, None
1553
+ if match_min := re.match(r".* = Dim\('.*', min\=([0-9]+).*\)", fix):
1554
+ _min = int(match_min.group(1))
1555
+ if match_max := re.match(r".* = Dim\('.*'.*max\=([0-9]+)\)", fix):
1556
+ _max = int(match_max.group(1))
1557
+ shape_fixes[name] = Dim(name, min=_min, max=_max)
1558
+ else:
1559
+ name, expr = fix.split(" = ")
1560
+ expr = sympy.sympify(expr)
1561
+ if isinstance(expr, sympy.Number):
1562
+ # static, integer
1563
+ shape_fixes[name] = int(expr) # type: ignore[assignment]
1564
+ else:
1565
+ # relation or derived dim
1566
+ shape_fixes[name] = expr
1567
+
1568
+ name_to_dim = _get_dim_name_mapping(dynamic_shapes)
1569
+
1570
+ # track derived dim roots
1571
+ roots: set[str] = set()
1572
+ for k, c in shape_fixes.items():
1573
+ if not isinstance(c, (int, Dim, _DerivedDim, sympy.Expr)):
1574
+ raise AssertionError(
1575
+ f"expected shape_fixes[{k!r}] to be int, Dim, _DerivedDim, or sympy.Expr, got {type(c)}"
1576
+ )
1577
+ if isinstance(c, sympy.Expr): # check dim/derived dim expression
1578
+ if not _is_supported_equivalence(c):
1579
+ raise AssertionError(f"sympy.Expr {c} is not a supported equivalence")
1580
+ shape_fixes[k] = c
1581
+ roots.add(str(next(iter(c.free_symbols))))
1582
+ if isinstance(c, _DerivedDim):
1583
+ roots.add(c.root.__name__) # type: ignore[attr-defined]
1584
+
1585
+ # check keys are existing dims or new roots
1586
+ for k in shape_fixes:
1587
+ if k not in name_to_dim and k not in roots:
1588
+ raise AssertionError(
1589
+ f"shape_fixes key {k!r} not found in name_to_dim or roots"
1590
+ )
1591
+
1592
+ # cache so we don't produce multiple derived dim objects
1593
+ derived_dim_cache: dict[str, _DerivedDim] = {}
1594
+
1595
+ def apply_fixes(path, dim, dummy):
1596
+ if dim is None or isinstance(dim, int): # not dynamic
1597
+ return dim
1598
+ elif dim.__name__ in shape_fixes: # directly fix
1599
+ fix = shape_fixes[dim.__name__]
1600
+ if isinstance(fix, sympy.Expr): # now derived or related
1601
+ if str(fix) in derived_dim_cache:
1602
+ return derived_dim_cache[str(fix)]
1603
+ else:
1604
+ symbol = next(iter(fix.free_symbols))
1605
+ # try to locate symbol
1606
+ if symbol.name in shape_fixes:
1607
+ root = shape_fixes[symbol.name]
1608
+ else:
1609
+ if symbol.name not in name_to_dim:
1610
+ raise AssertionError(
1611
+ f"symbol.name {symbol.name!r} not found in name_to_dim"
1612
+ )
1613
+ root = name_to_dim[symbol.name]
1614
+ # figure out value of fix
1615
+ modulus, remainder = sympy.polys.polytools.div(fix, symbol)
1616
+ dim = root
1617
+ if modulus != 1:
1618
+ dim = int(modulus) * dim
1619
+ if remainder != 0:
1620
+ dim = dim + int(remainder)
1621
+ # pyrefly: ignore [unsupported-operation]
1622
+ derived_dim_cache[str(fix)] = dim
1623
+ return dim
1624
+ else:
1625
+ return fix
1626
+ elif isinstance(dim, _DerivedDim) and dim.root.__name__ in shape_fixes: # type: ignore[attr-defined]
1627
+ if dim.__name__ in derived_dim_cache:
1628
+ return derived_dim_cache[dim.__name__]
1629
+ else: # evaluate new derived value based on root
1630
+ _dim = dim.fn(shape_fixes[dim.root.__name__]) # type: ignore[attr-defined]
1631
+ derived_dim_cache[dim.__name__] = _dim
1632
+ return _dim
1633
+ return dim # unchanged dim
1634
+
1635
+ return _tree_map_with_path(apply_fixes, dynamic_shapes, dynamic_shapes)
.venv/lib/python3.12/site-packages/torch/export/experimental/__init__.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import dataclasses
3
+ import functools
4
+ import os
5
+ import types
6
+ import typing
7
+ import typing_extensions
8
+ import zipfile
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ from torch.export.experimental._utils import _get_main_cpp_file, _get_make_file
13
+ from torch.export.exported_program import _decompose_exported_program
14
+ from torch.utils._ordered_set import OrderedSet
15
+
16
+
17
+ _InputT = typing_extensions.ParamSpec("_InputT")
18
+ _RetT = typing.TypeVar("_RetT")
19
+
20
+
21
+ __all__ = [] # type: ignore[var-annotated]
22
+
23
+
24
+ def _copy_graph_module_and_signature(
25
+ ep: torch.export.ExportedProgram,
26
+ ) -> tuple[torch.fx.GraphModule, torch.export.graph_signature.ExportGraphSignature]:
27
+ # copy.deepcopy lets the objects override __deepcopy__ methods with graph_copy() and node_copy(),
28
+ # and this can break placeholder names in some particular cases.
29
+ # For example, node copying will avoid Python keywords like 'input', suffixing and renaming to 'input_1'.
30
+ # So we manually overwrite placeholder names by reading the old graph.
31
+ gm = copy.deepcopy(ep.graph_module)
32
+ new_graph_signature = copy.deepcopy(ep.graph_signature)
33
+
34
+ # iterate over old/new graph modules
35
+ for old_gm, new_gm in zip(ep.graph_module.modules(), gm.modules()): # type: ignore[union-attr]
36
+ old_phs = [node for node in old_gm.graph.nodes if node.op == "placeholder"]
37
+ new_phs = [node for node in new_gm.graph.nodes if node.op == "placeholder"]
38
+ # iterate over placeholders
39
+ if len(old_phs) != len(new_phs):
40
+ raise AssertionError(
41
+ f"Number of old placeholders ({len(old_phs)}) does not match "
42
+ f"new placeholders ({len(new_phs)})"
43
+ )
44
+ for old_node, new_node in zip(old_phs, new_phs):
45
+ new_node.name = old_node.name
46
+
47
+ return gm, new_graph_signature
48
+
49
+
50
+ def _remove_detach_pass(
51
+ gm: torch.fx.GraphModule, sig: torch.export.graph_signature.ExportGraphSignature
52
+ ) -> None:
53
+ with gm._set_replace_hook(sig.get_replace_hook()):
54
+ for node in list(reversed(gm.graph.nodes)):
55
+ if node.op != "call_function":
56
+ continue
57
+ if (
58
+ node.target is torch.ops.aten.detach.default
59
+ and len(node.users) == 1
60
+ and next(iter(node.users)).target is torch.ops.aten.detach.default
61
+ ):
62
+ next(iter(node.users)).replace_all_uses_with(node)
63
+
64
+ gm.graph.eliminate_dead_code()
65
+ gm.recompile()
66
+
67
+
68
+ def _export_forward_backward(
69
+ ep: torch.export.ExportedProgram, joint_loss_index: int = 0
70
+ ) -> torch.export.ExportedProgram:
71
+ """
72
+ WARNING: This API is highly unstable and will be subject to change in the future.
73
+ """
74
+ from torch._decomp import core_aten_decompositions
75
+
76
+ ep = _decompose_exported_program(
77
+ ep,
78
+ cia_to_decomp={},
79
+ python_decomp_table=core_aten_decompositions(),
80
+ joint_loss_index=joint_loss_index,
81
+ # For serialization purpose, we don't want to decompose custom triton ops.
82
+ # If users would like to decompose custom triton ops, they could do it
83
+ # with run_decompositions() API.
84
+ decompose_custom_triton_ops=False,
85
+ )
86
+ gm, new_graph_signature = _copy_graph_module_and_signature(ep)
87
+ _remove_detach_pass(gm, new_graph_signature)
88
+
89
+ return ep._update(gm, new_graph_signature)
90
+
91
+
92
+ def _sticky_export(
93
+ forward_func: typing.Callable[_InputT, _RetT],
94
+ dynamic_shapes_callback: typing.Callable[
95
+ _InputT, list[typing.Any] | dict[str, typing.Any] | tuple[typing.Any, ...]
96
+ ]
97
+ | None = None,
98
+ ) -> typing.Callable[_InputT, _RetT]:
99
+ """
100
+ Lazily export the model on first forward call.
101
+ Usage:
102
+ model.forward = _sticky_export(model.forward, dynamic_shapes_callback=callback)
103
+ """
104
+ model = forward_func.__self__ # type: ignore[attr-defined]
105
+ original_forward = forward_func.__func__ # type: ignore[attr-defined]
106
+
107
+ @functools.wraps(forward_func)
108
+ def wrapper(*args: _InputT.args, **kwargs: _InputT.kwargs) -> _RetT:
109
+ # Unpatch forward to avoid recursion during export
110
+ model.forward = types.MethodType(original_forward, model)
111
+
112
+ dynamic_shapes_spec = None
113
+ if dynamic_shapes_callback:
114
+ dynamic_shapes_spec = dynamic_shapes_callback(*args, **kwargs)
115
+
116
+ try:
117
+ exported = torch.export.export(
118
+ model,
119
+ args,
120
+ kwargs,
121
+ dynamic_shapes=dynamic_shapes_spec,
122
+ ).module()
123
+ wrapper._exported_artifact = exported # type: ignore[attr-defined]
124
+ finally:
125
+ # Restore the wrapper after export
126
+ model.forward = wrapper
127
+
128
+ return exported(*args, **kwargs)
129
+
130
+ return wrapper
131
+
132
+
133
+ @dataclasses.dataclass
134
+ class _ExportMethod:
135
+ overloads: dict[str, torch.export.ExportedProgram]
136
+ fallbacks: list[torch.export.ExportedProgram]
137
+
138
+
139
+ class _ExportPackage:
140
+ """
141
+ An export package is a collection of torch.export()-ed PyTorch models consisting of
142
+ a list of exported methods and their corresponding overloads. ExportPackage is introduced
143
+ on top of torch.export() to support the following use cases:
144
+ - Exporting a model with multiple methods if a model has multiple independent parts.
145
+ - Exporting a function with multiple overloads based on tensor shapes or other metadata.
146
+
147
+ ExportPackage is designed to contain multiple methods (associated with method names) and for
148
+ each method, it can have multiple overloads (associated with overload names).
149
+
150
+ Here is an example of the data structure for an ExportPackage:
151
+ ```
152
+ ExportPackage(
153
+ methods={
154
+ "decoder": ExportMethod(
155
+ overloads={
156
+ "prefill": ExportedProgram(...),
157
+ "decode": ExportedProgram(...),
158
+ },
159
+ fallbacks=[],
160
+ ),
161
+ "encoder": ExportMethod(overloads={}, fallbacks=[ExportedProgram(...)]),
162
+ },
163
+ )
164
+ ```
165
+
166
+ To export a model into an ExportPackage, users can use the exporter API provided by ExportPackage.
167
+ Exporter is a decorator that takes a callable and returns a wrapper. The wrapper will export the
168
+ function into an ExportPackage, when it's invoked with some sample inputs (similar to how
169
+ torch.compile() works). For more details, please refer to the document on .exporter() method.
170
+
171
+ This design allows users to decouple the exported callables from the actual sample inputs which can
172
+ be helpful for use cases where the exported callable is hidden behind helper functions or when sample
173
+ inputs are hard to get.
174
+
175
+ NOTE: This is an experimental API and anything can be changed in the future.
176
+
177
+ Example usage:
178
+ ```
179
+ def fn(x):
180
+ return x + 1
181
+
182
+ def main(f, x):
183
+ x += 1
184
+ ret = f(x)
185
+ return ret + 1
186
+
187
+ package = ExportPackage()
188
+ main(package.exporter(fn), torch.randn(3, 2))
189
+ ```
190
+
191
+ """
192
+
193
+ def __init__(self) -> None:
194
+ self.methods: dict[str, _ExportMethod] = {}
195
+
196
+ def _exporter(
197
+ self,
198
+ method: str,
199
+ fn: typing.Callable[_InputT, _RetT],
200
+ *,
201
+ fallback: str = "once",
202
+ ) -> typing.Callable[_InputT, _RetT]:
203
+ """
204
+ A function/module decorator that sets up a callable to be exported later invoked.
205
+ By default the exporter will only trigger torch.export for once and error on
206
+ later invocations. To customize this behavior, users have the following two options:
207
+ 1. Call .define_overload() method on the returned wrapper to define an overload.
208
+ 2. Adjust the fallback policy using `fallback` argument.
209
+
210
+ An "overload" is a named branch for an ExportMethod with a user defined precondition,
211
+ typically based on input tensor shapes. It's up to a downstream backend implementation
212
+ of ExportMethod to respect the precondition later in inference.
213
+
214
+ define_overload() takes arguments like the following:
215
+ - A name, for indexing purposes in a backend.
216
+ - A callable (spec) that:
217
+ - Has the same model input signature as the original model code.
218
+ - Returns an optional dynamic shape spec.
219
+
220
+ Exporter will only export an overload when the spec callable successfully returns
221
+ a result without raising AssertionError.
222
+
223
+ For example:
224
+ ```
225
+ package = ExportPackage()
226
+
227
+
228
+ def prefill(x, xa, kv_cache):
229
+ assert x.shape[1] == 3
230
+ assert kv_cache == {}
231
+
232
+
233
+ def decode(x, xa, kv_cache):
234
+ assert x.shape[1] > 1
235
+ assert len(kv_cache) > 0
236
+ return {...} # dynamic shape specs here
237
+
238
+
239
+ exporter = (
240
+ package.exporter(decoder)
241
+ .define_overload("prefill", prefill)
242
+ .define_overload("decode", decode)
243
+ )
244
+ ```
245
+
246
+ A "fallback" is exported when no overload precondition matches a given set of sample
247
+ inputs. Overloads should
248
+ Fallbacks don't have names and are ordered in a list. It's up to a backend to decide
249
+ which fallback is used among multiple ones.
250
+
251
+ A reference backend implementation of ExportMethod may look like the following:
252
+ ```
253
+ def execute(method: ExportMethod, *args, **kwargs):
254
+ for overload in method.overloads:
255
+ if match_precondition(overload, *args, **kwargs):
256
+ return execute_overload(overload, *args, **kwargs)
257
+ for fallback in method.fallbacks:
258
+ if match_precondition(fallback, *args, **kwargs):
259
+ return execute_fallback(fallback, *args, **kwargs)
260
+ ```
261
+
262
+ Args:
263
+ method(str): The method name for an exported part of PyTorch model. This
264
+ will be saved together with the exported/compiled artifacts
265
+ in any serialization format and can be used as the key to
266
+ index ExportPackage methods later.
267
+ fn(callable): A PyTorch function/module to be exported.
268
+ fallback(str): The fallback policy to decide when to call torch.export
269
+ - "once" is the default policy. Under this policy a PyTorch program is assumed
270
+ to be only called once later and an error will be raised for subsequent
271
+ runs.
272
+ - "error" means the ExportMethod will never have any fallbacks, meaning
273
+ users should define all the possible overloads ahead of time.
274
+
275
+ """
276
+
277
+ fallbacks: list[torch.export.ExportedProgram] = []
278
+ specs: dict[str, typing.Callable[_InputT, typing.Any]] = {}
279
+ overloads: dict[str, torch.export.ExportedProgram] = {}
280
+ self.methods[method] = _ExportMethod(fallbacks=fallbacks, overloads=overloads)
281
+
282
+ @functools.wraps(fn)
283
+ def _exporter_context(*args, **kwargs): # type: ignore[no-untyped-def]
284
+ import torch.export._wrapper_utils
285
+
286
+ model: torch.nn.Module
287
+ if not isinstance(fn, torch.nn.Module):
288
+ model = torch.export._wrapper_utils._WrapperModule(fn)
289
+ else:
290
+ model = fn
291
+
292
+ for k, v in specs.items():
293
+ try:
294
+ if isinstance(fn, torch.nn.Module):
295
+ dynamic_shapes = v(fn, *args, **kwargs) # type: ignore[arg-type]
296
+ else:
297
+ # pyrefly: ignore [invalid-param-spec]
298
+ dynamic_shapes = v(*args, **kwargs)
299
+ except AssertionError:
300
+ continue
301
+ if k not in overloads:
302
+ ep = torch.export.export(
303
+ model, args, kwargs, dynamic_shapes=dynamic_shapes
304
+ )
305
+ overloads[k] = ep
306
+ ep = overloads[k]
307
+ return ep.module()(*args, **kwargs)
308
+
309
+ if fallback == "error":
310
+ raise RuntimeError(
311
+ f"Exporter: Cannot export fallback {fn} when fallback policy is set to 'error',"
312
+ + "please specify an overload or adjust the fallback policy."
313
+ )
314
+ elif fallback == "once":
315
+ if len(fallbacks) > 0:
316
+ raise RuntimeError(
317
+ f"Exporter: Cannot export {fn} more than once, "
318
+ + "please specify an overload or adjust the fallback policy."
319
+ )
320
+ else:
321
+ raise RuntimeError(f"Unknown fallback policy: {fallback}")
322
+ ep = torch.export.export(model, args, kwargs)
323
+
324
+ fallbacks.append(ep)
325
+ return ep.module()(*args, **kwargs)
326
+
327
+ if isinstance(fn, torch.nn.Module):
328
+ _exporter_context = torch._dynamo.eval_frame.OptimizedModule( # type: ignore[assignment]
329
+ fn,
330
+ lambda _: _exporter_context, # type: ignore[arg-type]
331
+ )
332
+
333
+ def _define_overload(
334
+ overload: str, spec: typing.Callable[_InputT, typing.Any]
335
+ ) -> typing.Any:
336
+ if overload in specs:
337
+ raise AssertionError(f"Overload '{overload}' already exists in specs")
338
+ if not callable(spec):
339
+ raise AssertionError(f"spec must be callable, but got {type(spec)}")
340
+ if not overload.isidentifier():
341
+ raise AssertionError(
342
+ f"Overload '{overload}' is not a valid Python identifier"
343
+ )
344
+ specs[overload] = spec
345
+ return _exporter_context
346
+
347
+ if hasattr(fn, "_define_overload"):
348
+ raise AssertionError("fn already has a '_define_overload' attribute")
349
+ _exporter_context._define_overload = _define_overload # type: ignore[attr-defined]
350
+
351
+ # pyrefly: ignore [bad-return]
352
+ return _exporter_context
353
+
354
+ @property
355
+ def _method_overloads(
356
+ self,
357
+ ) -> typing.Iterator[tuple[str, torch.export.ExportedProgram]]:
358
+ for method, method_data in self.methods.items():
359
+ for overload, ep in method_data.overloads.items():
360
+ yield f"{method}:{overload}", ep
361
+
362
+ def _compiled_and_package(
363
+ self,
364
+ f: torch.types.FileLike,
365
+ standalone: bool = False,
366
+ package_example_inputs: bool = False,
367
+ ) -> None:
368
+ options: dict[str, typing.Any] = {
369
+ "aot_inductor.package": True,
370
+ "aot_inductor.package_cpp_only": True,
371
+ "always_keep_tensor_constants": True,
372
+ # we'll change this back to False once we enable weight deduping for standalone mode
373
+ "aot_inductor.package_constants_in_so": standalone,
374
+ "aot_inductor_mode.compile_standalone": standalone,
375
+ }
376
+ aoti_files_map = {}
377
+ model_names = []
378
+ device_type = "cpu"
379
+ for name, ep in self._method_overloads:
380
+ name = name.replace(":", "__")
381
+ model_names.append(name)
382
+ options["aot_inductor.model_name_for_generated_files"] = name
383
+ aoti_files = torch._inductor.aot_compile(
384
+ ep.module(), # type: ignore[arg-type]
385
+ ep.example_inputs[0],
386
+ kwargs=ep.example_inputs[1],
387
+ options=options,
388
+ )
389
+ # pyrefly: ignore [unsupported-operation]
390
+ aoti_files_map[name] = aoti_files
391
+
392
+ from torch._inductor.package import package
393
+
394
+ pt2_path = package.package_aoti(
395
+ f,
396
+ aoti_files_map, # type: ignore[arg-type]
397
+ )
398
+
399
+ if not standalone:
400
+ return
401
+
402
+ if not isinstance(pt2_path, str):
403
+ raise AssertionError(
404
+ f"Expected pt2_path to be a string, but got {type(pt2_path)}"
405
+ )
406
+ base_directory = os.path.dirname(pt2_path)
407
+ package_name = os.path.basename(pt2_path)[:-4]
408
+ with zipfile.ZipFile(pt2_path, "r") as zip_ref:
409
+ zip_ref.extractall(base_directory)
410
+
411
+ example_inputs_map: dict[str, int] | None = (
412
+ {} if package_example_inputs else None
413
+ )
414
+ for name, ep in self._method_overloads:
415
+ name = name.replace(":", "__")
416
+ # TODO: also dump kwargs
417
+ # TODO: currently only support list of Tensors and they need to be on the same device
418
+ if not ep.example_inputs:
419
+ continue
420
+
421
+ device_types: OrderedSet[str] = OrderedSet()
422
+
423
+ for inp in ep.example_inputs[0]:
424
+ if isinstance(inp, torch.Tensor):
425
+ device_types.add(inp.device.type)
426
+ device_types.discard("cpu")
427
+ if len(device_types) > 1:
428
+ raise AssertionError(
429
+ "Does not support mixing {}".format("+".join(list(device_types)))
430
+ )
431
+ device_type = "cpu" if len(device_types) == 0 else device_types.pop()
432
+
433
+ if package_example_inputs:
434
+ if example_inputs_map is None:
435
+ raise AssertionError(
436
+ "example_inputs_map cannot be None when package_example_inputs is True"
437
+ )
438
+ example_inputs_map[name] = len(ep.example_inputs[0])
439
+ for i, t in enumerate(ep.example_inputs[0]):
440
+ path = Path(base_directory) / f"{name}_input_{i}.pt"
441
+ torch.save(t, path)
442
+
443
+ cmake_file_str = _get_make_file(
444
+ package_name, model_names, device_type=device_type
445
+ )
446
+
447
+ with open(Path(base_directory) / "CMakeLists.txt", "w") as file:
448
+ file.write(cmake_file_str)
449
+
450
+ main_file_str = _get_main_cpp_file(
451
+ package_name, model_names, example_inputs_map, device_type=device_type
452
+ )
453
+ with open(Path(base_directory) / "main.cpp", "w") as file:
454
+ file.write(main_file_str)
.venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (21.3 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/_utils.cpython-312.pyc ADDED
Binary file (10.4 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/experimental/_utils.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import torch
4
+ from torch._inductor.utils import IndentedBuffer
5
+
6
+
7
+ __all__ = [] # type: ignore[var-annotated]
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _get_main_cpp_file(
12
+ package_name: str,
13
+ model_names: list[str],
14
+ example_inputs_map: dict[str, int] | None,
15
+ device_type: str,
16
+ ) -> str:
17
+ """
18
+ Generates a main.cpp file for AOTInductor standalone models in the specified package.
19
+
20
+ Args:
21
+ package_name (str): Name of the package containing the models.
22
+ model_names (List[str]): List of model names to include in the generated main.cpp.
23
+ cuda (bool): Whether to generate code with CUDA support.
24
+ example_inputs_map (Optional[Dict[str, List[Tensor]]]): A mapping from model name to
25
+ its list of example input tensors. If provided, the generated main.cpp will
26
+ load and run these inputs.
27
+
28
+ Returns:
29
+ str: The contents of the generated main.cpp file as a string.
30
+ """
31
+
32
+ ib = IndentedBuffer()
33
+
34
+ ib.writelines(
35
+ [
36
+ "#include <dlfcn.h>",
37
+ "#include <fstream>",
38
+ "#include <iostream>",
39
+ "#include <memory>",
40
+ "#include <torch/torch.h>",
41
+ "#include <vector>",
42
+ "#include <torch/csrc/inductor/aoti_torch/tensor_converter.h>",
43
+ ]
44
+ )
45
+ if device_type == "cuda":
46
+ if torch.version.hip:
47
+ ib.writelines(
48
+ [
49
+ "#include <hip/hip_runtime.h>",
50
+ ]
51
+ )
52
+
53
+ else:
54
+ ib.writelines(
55
+ [
56
+ "#include <cuda.h>",
57
+ "#include <cuda_runtime_api.h>",
58
+ ]
59
+ )
60
+ for model_name in model_names:
61
+ ib.writeline(
62
+ f'#include "{package_name}/data/aotinductor/{model_name}/{model_name}.h"'
63
+ )
64
+
65
+ ib.newline()
66
+ for model_name in model_names:
67
+ ib.writeline(f"using torch::aot_inductor::AOTInductorModel{model_name};")
68
+
69
+ ib.writelines(
70
+ [
71
+ "using torch::aot_inductor::ConstantHandle;",
72
+ "using torch::aot_inductor::ConstantMap;",
73
+ "",
74
+ "int main(int argc, char* argv[]) {",
75
+ ]
76
+ )
77
+
78
+ with ib.indent():
79
+ ib.writeline(f'std::string device_str = "{device_type}";')
80
+ ib.writeline("try {")
81
+
82
+ with ib.indent():
83
+ ib.writeline("c10::Device device(device_str);")
84
+
85
+ if example_inputs_map is not None:
86
+ # TODO: add device
87
+ for i, model_name in enumerate(model_names):
88
+ num_inputs = example_inputs_map[model_name]
89
+
90
+ ib.writeline(f"// Load input tensors for model {model_name}")
91
+ ib.writeline(f"std::vector<at::Tensor> input_tensors{i + 1};")
92
+ ib.writeline(f"for (int j = 0; j < {num_inputs}; ++j) {{")
93
+ with ib.indent():
94
+ ib.writeline(
95
+ f'std::string filename = "{model_name}_input_" + std::to_string(j) + ".pt";'
96
+ )
97
+ ib.writeline("std::ifstream in(filename, std::ios::binary);")
98
+ ib.writeline("if (!in.is_open()) {")
99
+ with ib.indent():
100
+ ib.writeline(
101
+ 'std::cerr << "Failed to open file: " << filename << std::endl;'
102
+ )
103
+ ib.writeline("return 1;")
104
+ ib.writeline("}")
105
+ ib.writeline(
106
+ "std::vector<char> buffer((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());"
107
+ )
108
+ ib.writeline(
109
+ "torch::IValue ivalue = torch::pickle_load(buffer);"
110
+ )
111
+ ib.writeline(
112
+ f"input_tensors{i + 1}.push_back(ivalue.toTensor().to(device));"
113
+ )
114
+ ib.writeline("}")
115
+ ib.newline()
116
+
117
+ ib.newline()
118
+ ib.writeline("\n// Create array of input handles")
119
+ for i in range(len(model_names)):
120
+ ib.writelines(
121
+ [
122
+ f"auto input_handles{i + 1} =",
123
+ f" torch::aot_inductor::unsafe_alloc_new_handles_from_tensors(input_tensors{i + 1});",
124
+ ]
125
+ )
126
+
127
+ ib.writeline("\n// Create array for output handles")
128
+ for i in range(len(model_names)):
129
+ ib.writeline(f"AtenTensorHandle output_handle{i + 1};")
130
+
131
+ ib.writeline("\n// Create and load models")
132
+ for i, model_name in enumerate(model_names):
133
+ ib.writelines(
134
+ [
135
+ f"auto constants_map{i + 1} = std::make_shared<ConstantMap>();",
136
+ f"auto constants_array{i + 1} = std::make_shared<std::vector<ConstantHandle>>();",
137
+ f"auto model{i + 1} = std::make_unique<AOTInductorModel{model_name}>(",
138
+ f" std::move(constants_map{i + 1}),",
139
+ f" std::move(constants_array{i + 1}),",
140
+ " device_str,",
141
+ f' "{package_name}/data/aotinductor/{model_name}/");',
142
+ f"model{i + 1}->load_constants();",
143
+ ]
144
+ )
145
+
146
+ if example_inputs_map is not None:
147
+ ib.writeline("\n// Run the models")
148
+ for i in range(len(model_names)):
149
+ ib.writeline(
150
+ f"torch::aot_inductor::DeviceStreamType stream{i + 1} = nullptr;"
151
+ )
152
+ ib.writeline(
153
+ f"model{i + 1}->run(&input_handles{i + 1}[0], &output_handle{i + 1}, stream{i + 1}, nullptr);"
154
+ )
155
+
156
+ ib.writeline("\n// Convert output handles to tensors")
157
+ for i in range(len(model_names)):
158
+ ib.writelines(
159
+ [
160
+ f"auto output_tensor{i + 1} =",
161
+ f" torch::aot_inductor::alloc_tensors_by_stealing_from_handles(&output_handle{i + 1}, 1);",
162
+ ]
163
+ )
164
+
165
+ ib.writeline("\n// Validate outputs")
166
+ for i in range(len(model_names)):
167
+ ib.writeline(
168
+ f"""std::cout << "output_tensor{i + 1}\\n" << output_tensor{i + 1} << std::endl;"""
169
+ )
170
+ ib.writeline(
171
+ f"""torch::save(output_tensor{i + 1}, "output_tensor{i + 1}.pt");"""
172
+ )
173
+
174
+ ib.writeline("return 0;")
175
+
176
+ ib.writelines(
177
+ [
178
+ "} catch (const std::exception &e) {",
179
+ ]
180
+ )
181
+ with ib.indent():
182
+ ib.writeline('std::cerr << "Error: " << e.what() << std::endl;')
183
+ ib.writeline("return 1;")
184
+
185
+ ib.writeline("}")
186
+ ib.writeline("}")
187
+
188
+ return ib.getvalue()
189
+
190
+
191
+ def _get_make_file(package_name: str, model_names: list[str], device_type: str) -> str:
192
+ ib = IndentedBuffer()
193
+
194
+ ib.writelines(
195
+ [
196
+ "cmake_minimum_required(VERSION 3.10)",
197
+ "project(TestProject)",
198
+ "",
199
+ "set(CMAKE_CXX_STANDARD 20)",
200
+ "",
201
+ ]
202
+ )
203
+
204
+ from torch._inductor.config import test_configs
205
+
206
+ if test_configs.use_libtorch:
207
+ ib.writeline("find_package(Torch REQUIRED)")
208
+
209
+ if device_type == "cuda":
210
+ if torch.version.hip:
211
+ ib.writeline("find_package(hip REQUIRED)")
212
+ else:
213
+ ib.writeline("find_package(CUDA REQUIRED)")
214
+
215
+ ib.newline()
216
+ for model_name in model_names:
217
+ ib.writeline(f"add_subdirectory({package_name}/data/aotinductor/{model_name}/)")
218
+
219
+ ib.writeline("\nadd_executable(main main.cpp)")
220
+ if device_type == "cuda":
221
+ if torch.version.hip:
222
+ ib.writeline("target_compile_definitions(main PRIVATE USE_HIP)")
223
+ else:
224
+ ib.writeline("target_compile_definitions(main PRIVATE USE_CUDA)")
225
+ elif device_type == "xpu":
226
+ ib.writeline("target_compile_definitions(main PRIVATE USE_XPU)")
227
+
228
+ model_libs = " ".join(model_names)
229
+ ib.writeline(f"target_link_libraries(main PRIVATE torch {model_libs})")
230
+
231
+ if device_type == "cuda":
232
+ if torch.version.hip:
233
+ ib.writeline("target_link_libraries(main PRIVATE hip::host)")
234
+ else:
235
+ ib.writeline("target_link_libraries(main PRIVATE cuda ${CUDA_LIBRARIES})")
236
+ elif device_type == "xpu":
237
+ ib.writeline("target_link_libraries(main PRIVATE sycl ze_loader)")
238
+ return ib.getvalue()
.venv/lib/python3.12/site-packages/torch/export/exported_program.py ADDED
@@ -0,0 +1,1820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import contextlib
4
+ import copy
5
+ import dataclasses
6
+ import functools
7
+ import operator
8
+ import types
9
+ import warnings
10
+ from collections import defaultdict
11
+ from collections.abc import Callable, Iterator
12
+ from contextlib import contextmanager
13
+ from typing import Any, final, NamedTuple, TYPE_CHECKING
14
+
15
+ from torch._guards import tracing, TracingContext
16
+ from torch._higher_order_ops.utils import autograd_not_implemented
17
+ from torch._library.fake_class_registry import FakeScriptObject
18
+ from torch._subclasses.fake_impls import (
19
+ _deregister_op_impl,
20
+ _is_op_registered_to_fake_rule,
21
+ register_op_impl,
22
+ )
23
+ from torch._subclasses.fake_tensor import FakeTensorMode
24
+ from torch.fx._symbolic_trace import _ConstantAttributeType
25
+ from torch.fx._utils import first_call_function_nn_module_stack
26
+ from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo
27
+ from torch.fx.immutable_collections import immutable_dict, immutable_list
28
+ from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
29
+
30
+
31
+ if TYPE_CHECKING:
32
+ # Import the following modules during type checking to enable code intelligence features,
33
+ # such as auto-completion in tools like pylance, even when these modules are not explicitly
34
+ # imported in user code.
35
+
36
+ import sympy
37
+
38
+ from torch.utils._sympy.value_ranges import ValueRanges
39
+
40
+ import torch
41
+ import torch.utils._pytree as pytree
42
+ from torch._export.utils import (
43
+ _build_cache,
44
+ _collect_all_valid_cia_ops,
45
+ _collect_and_set_constant_attrs,
46
+ _collect_param_buffer_metadata,
47
+ _detect_fake_mode_from_gm,
48
+ _fakify_params_buffers,
49
+ _get_decomp_for_cia,
50
+ _is_preservable_cia_op,
51
+ _name_hoo_subgraph_placeholders,
52
+ _override_graph_signature_for_temp_registered_constants,
53
+ _overwrite_signature_for_non_persistent_buffers,
54
+ _populate_param_buffer_metadata_to_new_gm,
55
+ _register_constants_as_buffers,
56
+ _rename_without_collisions,
57
+ _special_op_to_preserve_cia,
58
+ placeholder_naming_pass,
59
+ )
60
+ from torch._export.verifier import Verifier
61
+ from torch._guards import detect_fake_mode
62
+ from torch._subclasses.fake_tensor import unset_fake_temporarily
63
+ from torch.export._tree_utils import is_equivalent, reorder_kwargs
64
+ from torch.export.decomp_utils import CustomDecompTable
65
+ from torch.fx._compatibility import compatibility
66
+ from torch.fx.passes.infra.pass_base import PassResult
67
+ from torch.fx.passes.infra.pass_manager import PassManager
68
+
69
+ from .graph_signature import ( # noqa: F401
70
+ ArgumentSpec,
71
+ ConstantArgument,
72
+ CustomObjArgument,
73
+ ExportGraphSignature,
74
+ InputKind,
75
+ InputSpec,
76
+ OutputKind,
77
+ OutputSpec,
78
+ SymBoolArgument,
79
+ SymFloatArgument,
80
+ SymIntArgument,
81
+ TensorArgument,
82
+ TokenArgument,
83
+ )
84
+
85
+
86
+ __all__ = [
87
+ "ExportedProgram",
88
+ "ModuleCallEntry",
89
+ "ModuleCallSignature",
90
+ "default_decompositions",
91
+ ]
92
+
93
+
94
+ PassType = Callable[[torch.fx.GraphModule], PassResult | None]
95
+
96
+
97
+ @dataclasses.dataclass
98
+ class ModuleCallSignature:
99
+ inputs: list[ArgumentSpec]
100
+ outputs: list[ArgumentSpec]
101
+ in_spec: pytree.TreeSpec
102
+ out_spec: pytree.TreeSpec
103
+ forward_arg_names: list[str] | None = None
104
+
105
+ def replace_all_uses_with(self, original_node, new_node):
106
+ for i in self.inputs:
107
+ if i.name == original_node.name:
108
+ i.name = new_node.name
109
+ for o in self.outputs:
110
+ if o.name == original_node.name:
111
+ o.name = new_node.name
112
+
113
+
114
+ @dataclasses.dataclass
115
+ class ModuleCallEntry:
116
+ fqn: str
117
+ signature: ModuleCallSignature | None = None
118
+
119
+
120
+ def _disable_prexisiting_fake_mode(fn):
121
+ @functools.wraps(fn)
122
+ def wrapper(*args, **kwargs):
123
+ with unset_fake_temporarily():
124
+ return fn(*args, **kwargs)
125
+
126
+ return wrapper
127
+
128
+
129
+ def _fx_collection_equivalence_fn(
130
+ spec1_type: type | None,
131
+ spec1_context: pytree.Context,
132
+ spec2_type: type | None,
133
+ spec2_context: pytree.Context,
134
+ ) -> bool:
135
+ """Treat containers and their immutable variants as the same type. Otherwise
136
+ compare as normal.
137
+ """
138
+ if spec1_type is None or spec2_type is None:
139
+ return spec1_type is spec2_type and spec1_context == spec2_context
140
+
141
+ if issubclass(spec1_type, (dict, immutable_dict)) and issubclass(
142
+ spec2_type, (dict, immutable_dict)
143
+ ):
144
+ return spec1_context == spec2_context
145
+
146
+ if issubclass(spec1_type, (list, immutable_list)) and issubclass(
147
+ spec2_type, (list, immutable_list)
148
+ ):
149
+ return spec1_context == spec2_context
150
+
151
+ return spec1_type is spec2_type and spec1_context == spec2_context
152
+
153
+
154
+ # This list is compiled from DispatchKey.cpp.
155
+ # The idea is that we use these keys to override
156
+ # CIA decomp in export
157
+ _AUTOGRAD_ALIAS_BACKEND_KEYS_TO_OVERRIDE = [
158
+ torch._C.DispatchKey.AutogradCPU,
159
+ torch._C.DispatchKey.AutogradCUDA,
160
+ torch._C.DispatchKey.AutogradMeta,
161
+ torch._C.DispatchKey.AutogradXLA,
162
+ torch._C.DispatchKey.AutogradLazy,
163
+ torch._C.DispatchKey.AutogradIPU,
164
+ torch._C.DispatchKey.AutogradXPU,
165
+ torch._C.DispatchKey.AutogradMPS,
166
+ torch._C.DispatchKey.AutogradHPU,
167
+ torch._C.DispatchKey.AutogradPrivateUse1,
168
+ torch._C.DispatchKey.AutogradPrivateUse2,
169
+ torch._C.DispatchKey.AutogradPrivateUse3,
170
+ ]
171
+
172
+
173
+ # This list is compiled from DispatchKey.cpp.
174
+ # The idea is that we use these keys to add
175
+ # python kernels that directly uses default
176
+ # CIA decomp
177
+ # See NOTE Registering old CIA to Backend kernel
178
+ _BACKEND_KEYS_TO_OVERRIDE = [
179
+ torch._C.DispatchKey.CPU,
180
+ torch._C.DispatchKey.CUDA,
181
+ torch._C.DispatchKey.Meta,
182
+ torch._C.DispatchKey.XLA,
183
+ torch._C.DispatchKey.Lazy,
184
+ torch._C.DispatchKey.IPU,
185
+ torch._C.DispatchKey.XPU,
186
+ torch._C.DispatchKey.MPS,
187
+ torch._C.DispatchKey.HPU,
188
+ ]
189
+
190
+
191
+ @contextmanager
192
+ def _override_composite_implicit_decomp(cia_ops_to_callable):
193
+ # This function overrides CompositeImplicitAutograd decomp for
194
+ # functional composite ops that user specified. Ideally we want to not-decompose
195
+ # ALL composite ops but today's C++ functionalization relies on
196
+ # the fact that it is working with the opset after decomp is run.
197
+ # Hence we can only do it for functional ops. One caveat is that
198
+ # there are some composite ops that lie about their schema (claimed to be
199
+ # functional but not really aka dropout), for these cases, we just decompose.
200
+ saved_tables = {}
201
+ patched_ops = set()
202
+ for op_overload, decomp_callable in cia_ops_to_callable.items():
203
+ saved_tables[op_overload] = op_overload.py_kernels.copy()
204
+ patched_ops.add(op_overload)
205
+ for override_dispatch_key in _AUTOGRAD_ALIAS_BACKEND_KEYS_TO_OVERRIDE:
206
+ if override_dispatch_key not in op_overload.py_kernels:
207
+ # TODO (tmanlaibaatar)https://github.com/pytorch/pytorch/issues/129430
208
+ op_overload.py_impl(override_dispatch_key)(
209
+ autograd_not_implemented(op_overload, deferred_error=True)
210
+ )
211
+ # See NOTE: Registering old CIA to Backend kernel
212
+ # It is important that we cache this before we override py_kernels.
213
+ orig_cia_callable = _get_decomp_for_cia(op_overload)
214
+ if torch._C.DispatchKey.CompositeImplicitAutograd in op_overload.py_kernels:
215
+ del op_overload.py_kernels[torch._C.DispatchKey.CompositeImplicitAutograd]
216
+
217
+ op_overload.py_impl(torch._C.DispatchKey.CompositeImplicitAutograd)(
218
+ decomp_callable
219
+ )
220
+
221
+ # [NOTE] Directly registering fake tensor rule to CIA ops
222
+ # The problem we are facing here is if your CIA custom rule
223
+ # says we want to preserve the op, we will return NotImplemented.
224
+ # Unfortunately, this will invoke meta device tracing in fake tensor
225
+ # resulting in divergent behaviour for CIA kernels that has device based
226
+ # branching (one case is torch.ops.aten.scaled_dot_product.attention)
227
+ # To get around this issue, we register direct fake impl so that we
228
+ # run the kernel before we actually try to decompose the op in FakeTensorMode.
229
+ # Note that is a no-op in most cases, because:
230
+ # 1) In post dispatch tracing, CIA would have already decomposed
231
+ # 2) Most CIA impl are device agnostic.
232
+ def _force_dispatch_to_orig_cia_callable(fake_tensor_mode, op, *args, **kwargs):
233
+ orig_cia_callable = kwargs["original_callable"]
234
+ del kwargs["original_callable"]
235
+ with fake_tensor_mode:
236
+ return orig_cia_callable(*args, **kwargs)
237
+
238
+ if not _is_op_registered_to_fake_rule(op_overload):
239
+ register_op_impl(op_overload)(
240
+ functools.partial(
241
+ _force_dispatch_to_orig_cia_callable,
242
+ original_callable=orig_cia_callable,
243
+ )
244
+ )
245
+
246
+ for key in _BACKEND_KEYS_TO_OVERRIDE:
247
+ if key not in op_overload.py_kernels:
248
+ # [NOTE] Registering old CIA to Backend kernel
249
+ # We always register original CIA behavior to the backend keys kernel
250
+ # The reason is when we are fake tensor prop-ing or executing real kernel,
251
+ # we end up calling an operator on respective backend, which in python dispatcher,
252
+ # will resolve into CIA key. (see resolve_key in torch/_ops.py)
253
+ # As a result, this CIA now will call into the custom user defined
254
+ # CIA which can cause a problem.
255
+ # To make it more concrete, the case we are handling is:
256
+ # (1) there is a tensor constant we are performing constant propagation
257
+ # on during tracing
258
+ # (2) we invoke an op underneath autograd (either because we are below autograd,
259
+ # or we are tracing in inference mode), so one of the backend keys gets hit
260
+ # (3) the op we are invoking has a CIA impl that normally runs in eager mode
261
+ # (and the user wants to tweak this CIA impl during tracing, but during
262
+ # const-prop we want the original CIA to run
263
+ op_overload.py_impl(key)(orig_cia_callable)
264
+
265
+ try:
266
+ yield
267
+ finally:
268
+ for op in patched_ops:
269
+ op.py_kernels.clear()
270
+ op.py_kernels.update(saved_tables[op])
271
+ op._dispatch_cache.clear()
272
+ _deregister_op_impl(op)
273
+
274
+
275
+ def _split_decomp_table_to_cia_and_python_decomp(
276
+ decomp_table: dict[torch._ops.OperatorBase, Callable],
277
+ ) -> tuple[dict[torch._ops.OperatorBase, Callable], ...]:
278
+ all_preservable_cia_ops = set(_collect_all_valid_cia_ops())
279
+ cia_ops_to_callable = {}
280
+
281
+ for op in list(decomp_table.keys()):
282
+ # TODO we are silently allowing non-safe(non-functional) ops through a crack
283
+ # due to core aten decomp table having non-functional entries. Once we have
284
+ # a tighter check around core aten decomp, we should warn users about them.
285
+ # Tracking issue: (https://github.com/pytorch/pytorch/issues/135759)
286
+
287
+ # if it is a valid CIA op we can mess with in export, we check if it is:
288
+ # 1. Has been marked as to be decomposed. Example:
289
+ # decomp_table = decomp_table_to_core_aten()
290
+ # del decomp_table[aten.linear]
291
+ # In this case, user says decompose everything except for aten.linear
292
+ # 2. Has been marked with custom decomp behaviour. Example:
293
+ # decomp_table = {aten.linear: some_op}
294
+ # For (1), we want to remove all the CIA ops that weren't handled by user as
295
+ # it suggests they are safe to decompose, so we should remove from preservable_list.
296
+ # for (2), we just plumb the custom decomp to AOTDIspatcher.
297
+ # In both cases, we want to remove this CIA op from the decomp_table as it is special
298
+ # handled.
299
+ if op in all_preservable_cia_ops:
300
+ cia_ops_to_callable[op] = decomp_table[op]
301
+ all_preservable_cia_ops.remove(op)
302
+ del decomp_table[op]
303
+ # If it is a custom op, we want to still preserve or do whatever
304
+ # with it if it is a functional CIA. The reason we don't remove
305
+ # from CIA list is because we don't query custom ops.
306
+ elif _is_preservable_cia_op(op):
307
+ op_name = op.name()
308
+ if op_name.startswith("aten"):
309
+ raise AssertionError(
310
+ f"This should be a custom op, got aten op: {op_name}"
311
+ )
312
+ cia_ops_to_callable[op] = decomp_table[op]
313
+
314
+ # If we reached here, it means user intentionally deleted these CIA ops from
315
+ # decomp table.
316
+ for k in all_preservable_cia_ops:
317
+ cia_ops_to_callable[k] = _special_op_to_preserve_cia
318
+
319
+ return cia_ops_to_callable, decomp_table
320
+
321
+
322
+ def default_decompositions() -> "CustomDecompTable":
323
+ """
324
+ This is the default decomposition table which contains decomposition of
325
+ all ATEN operators to core aten opset. Use this API together with
326
+ :func:`run_decompositions()`
327
+ """
328
+ return CustomDecompTable()
329
+
330
+
331
+ def _decompose_and_get_gm_with_new_signature_constants(
332
+ ep: "ExportedProgram",
333
+ *,
334
+ cia_to_decomp: dict[torch._ops.OperatorBase, Callable],
335
+ python_decomp_table: dict[torch._ops.OperatorBase, Callable],
336
+ joint_loss_index: int | None,
337
+ decompose_custom_triton_ops,
338
+ ):
339
+ from torch._export.passes.lift_constants_pass import _materialize_and_lift_constants
340
+ from torch._functorch.aot_autograd import aot_export_module
341
+ from torch.export._trace import (
342
+ _disable_custom_triton_op_functional_decomposition,
343
+ _export_to_aten_ir,
344
+ _ignore_backend_decomps,
345
+ _verify_nn_module_stack,
346
+ _verify_placeholder_names,
347
+ _verify_stack_trace,
348
+ )
349
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
350
+
351
+ def _is_joint_ir_decomp(ep, joint_loss_index):
352
+ return (
353
+ joint_loss_index is not None
354
+ or ep.graph_signature.backward_signature is not None
355
+ )
356
+
357
+ if not _is_joint_ir_decomp(ep, joint_loss_index):
358
+ mod = ep.module()
359
+
360
+ wrapped_params_buffers = {
361
+ **dict(mod.named_parameters(remove_duplicate=False)),
362
+ **dict(mod.named_buffers(remove_duplicate=False)),
363
+ }
364
+
365
+ from torch._functorch._aot_autograd.subclass_parametrization import (
366
+ unwrap_tensor_subclass_parameters,
367
+ )
368
+
369
+ # [NOTE] Unwrapping subclasses AOT
370
+ # In torch.compile, the subclass unwrapping/wrapping happen at runtime
371
+ # but at export, this is impossible as it is intended to be run on
372
+ # C++ environment. As a result, we unwrap subclass parameters AOT. After this,
373
+ # ExportedProgram state_dict won't be same as eager model because eager model
374
+ # could have subclass weights while ExportedProgram will have desugared versions.
375
+ # This is fine because run_decompositions is supposed to specialize to post-autograd
376
+ # graph where the subclass desugaring is supposed to happen.
377
+ unwrap_tensor_subclass_parameters(mod)
378
+ unwrapped_params_buffers = {
379
+ **dict(mod.named_parameters(remove_duplicate=False)),
380
+ **dict(mod.named_buffers(remove_duplicate=False)),
381
+ }
382
+
383
+ # TODO T204030333
384
+ fake_mode = _detect_fake_mode_from_gm(ep.graph_module)
385
+ if fake_mode is None:
386
+ fake_mode = FakeTensorMode(shape_env=ShapeEnv(), export=True)
387
+
388
+ # Fix the graph output signature to be tuple if scalar
389
+ out_spec = mod._out_spec
390
+
391
+ if not isinstance(mod.graph._codegen, _PyTreeCodeGen):
392
+ raise AssertionError(
393
+ f"expected mod.graph._codegen to be _PyTreeCodeGen, got {type(mod.graph._codegen)}"
394
+ )
395
+ orig_arg_names = mod.graph._codegen.pytree_info.orig_args
396
+
397
+ # aot_export expect the return type to always be a tuple.
398
+ if out_spec is None:
399
+ raise AssertionError("out_spec must not be None")
400
+ if out_spec.type not in (list, tuple):
401
+ out_spec = pytree.treespec_tuple([out_spec])
402
+
403
+ mod.graph._codegen = _PyTreeCodeGen(
404
+ _PyTreeInfo(
405
+ orig_arg_names,
406
+ mod._in_spec,
407
+ out_spec,
408
+ )
409
+ )
410
+
411
+ mod.recompile()
412
+
413
+ # the exported module will store constants & non-persistent buffers such that
414
+ # retracing treats them as persistent buffers, so we inform the constants lifting pass
415
+ # and overwrite the new graph signature using the previous program.
416
+ _collect_and_set_constant_attrs(ep.graph_signature, ep.constants, mod)
417
+
418
+ # When we have a module with constant attributes, AotDispatcher doesn't actually
419
+ # wrap them as functional tensors, because dynamo would have already made it buffer.
420
+ # In non-strict case, however, AotDispatcher can intercept constants, causing it to not
421
+ # functionalize the operators that are operating on constant tensors. Since dynamo already
422
+ # wraps constants as buffers, we temporarily register the constants as buffers and undo this
423
+ # operation after AOTDispatcher is done.
424
+ temp_registered_constants = _register_constants_as_buffers(
425
+ mod, ep.state_dict, ep.graph_signature.non_persistent_buffers
426
+ )
427
+
428
+ # get params & buffers after excluding constants
429
+ fake_params_buffers = _fakify_params_buffers(fake_mode, mod)
430
+
431
+ params_buffers_to_node_meta = _collect_param_buffer_metadata(mod)
432
+
433
+ # TODO (tmanlaibaatar) Ideally run_decomp should just call _non_strict_export
434
+ # but due to special handling of constants as non-persistent buffers make it little
435
+ # difficult. But we should unify this code path together. T206837815
436
+ from torch._export.non_strict_utils import (
437
+ _enable_graph_inputs_of_type_nn_module,
438
+ _fakify_script_objects,
439
+ )
440
+
441
+ retracing_args = []
442
+ for node in mod.graph.nodes:
443
+ if node.op == "placeholder":
444
+ if isinstance(node.meta["val"], CustomObjArgument):
445
+ real_script_obj = None
446
+ if node.meta["val"].fake_val is None:
447
+ real_script_obj = ep.constants[node.meta["val"].name]
448
+ else:
449
+ real_script_obj = node.meta["val"].fake_val.real_obj
450
+ retracing_args.append(real_script_obj)
451
+ else:
452
+ retracing_args.append(node.meta["val"])
453
+
454
+ tx = TracingContext(fake_mode)
455
+
456
+ with (
457
+ fake_mode,
458
+ _override_composite_implicit_decomp(
459
+ cia_to_decomp,
460
+ ),
461
+ _enable_graph_inputs_of_type_nn_module(ep.example_inputs),
462
+ tracing(tx),
463
+ ):
464
+ retracing_args_unwrapped = pytree.tree_unflatten(
465
+ retracing_args, mod._in_spec
466
+ )
467
+ # this requires empty kwargs, but not in pytree.flattened format
468
+ with _fakify_script_objects(
469
+ mod,
470
+ (
471
+ *retracing_args_unwrapped[0],
472
+ *retracing_args_unwrapped[1].values(),
473
+ ),
474
+ {},
475
+ fake_mode,
476
+ ) as (
477
+ patched_mod,
478
+ new_fake_args,
479
+ new_fake_kwargs,
480
+ new_fake_constant_attrs,
481
+ map_fake_to_real,
482
+ ):
483
+ aten_export_artifact = _export_to_aten_ir(
484
+ patched_mod,
485
+ new_fake_args,
486
+ new_fake_kwargs,
487
+ fake_params_buffers,
488
+ new_fake_constant_attrs,
489
+ decomp_table=python_decomp_table,
490
+ _prettify_placeholder_names=False,
491
+ decompose_custom_triton_ops=decompose_custom_triton_ops,
492
+ )
493
+
494
+ # aten_export_artifact.constants contains only fake script objects, we need to map them back
495
+ aten_export_artifact.constants = {
496
+ fqn: (
497
+ map_fake_to_real[obj]
498
+ if isinstance(obj, FakeScriptObject)
499
+ else obj
500
+ )
501
+ for fqn, obj in aten_export_artifact.constants.items()
502
+ }
503
+
504
+ gm = aten_export_artifact.gm
505
+ new_graph_signature = aten_export_artifact.sig
506
+
507
+ # In the previous step, we assume constants as buffers for AOTDispatcher to
508
+ # functionalize properly, so undo that here
509
+ new_graph_signature = (
510
+ _override_graph_signature_for_temp_registered_constants(
511
+ new_graph_signature, temp_registered_constants
512
+ )
513
+ )
514
+
515
+ _populate_param_buffer_metadata_to_new_gm(
516
+ params_buffers_to_node_meta, gm, new_graph_signature
517
+ )
518
+
519
+ # overwrite signature for non-persistent buffers
520
+ new_graph_signature = _overwrite_signature_for_non_persistent_buffers(
521
+ ep.graph_signature, new_graph_signature
522
+ )
523
+
524
+ constants = {
525
+ **ep.constants,
526
+ **aten_export_artifact.constants,
527
+ }
528
+ constants.update(
529
+ _materialize_and_lift_constants(
530
+ gm, new_graph_signature, new_fake_constant_attrs
531
+ )
532
+ )
533
+
534
+ placeholder_naming_pass(
535
+ gm,
536
+ new_graph_signature,
537
+ patched_mod,
538
+ new_fake_args,
539
+ new_fake_kwargs,
540
+ fake_params_buffers,
541
+ constants,
542
+ )
543
+
544
+ _verify_nn_module_stack(gm)
545
+ _verify_stack_trace(gm)
546
+ _verify_placeholder_names(gm, new_graph_signature)
547
+
548
+ gm, new_graph_signature = _remove_unnecessary_copy_op_pass(
549
+ gm, new_graph_signature
550
+ )
551
+
552
+ # When we apply parameterization rule to unwrap
553
+ # subclasses, the state dict will now have different
554
+ # desugared parameters. We need to manually filter those
555
+ # and update the ep.state_dict. Ideally, we should just return
556
+ # the state dict of ep.module but ep.module only stores params
557
+ # buffers that participate in forward. If we undo this behavior,
558
+ # it would break some downstream users.
559
+ new_state_dict = {
560
+ **ep.state_dict,
561
+ **{
562
+ name: p
563
+ for name, p in unwrapped_params_buffers.items()
564
+ if name not in wrapped_params_buffers
565
+ },
566
+ }
567
+
568
+ for name, p in wrapped_params_buffers.items():
569
+ # Buffers can be persistent/non-persistent
570
+ if name not in new_state_dict:
571
+ if isinstance(p, torch.nn.Parameter):
572
+ raise AssertionError(
573
+ f"expected {name!r} not to be a torch.nn.Parameter when not in state_dict"
574
+ )
575
+
576
+ if name in new_state_dict:
577
+ if name not in unwrapped_params_buffers:
578
+ new_state_dict.pop(name)
579
+
580
+ return gm, new_graph_signature, new_state_dict, constants
581
+
582
+ old_placeholders = [
583
+ node for node in ep.graph_module.graph.nodes if node.op == "placeholder"
584
+ ]
585
+ fake_args = [node.meta["val"] for node in old_placeholders]
586
+
587
+ buffers_to_remove = [name for name, _ in ep.graph_module.named_buffers()]
588
+ for name in buffers_to_remove:
589
+ delattr(ep.graph_module, name)
590
+
591
+ # TODO(zhxhchen17) Return the new graph_signature directly.
592
+ fake_mode_det = detect_fake_mode(fake_args)
593
+ fake_mode_ctx = contextlib.nullcontext() if fake_mode_det is None else fake_mode_det # type: ignore[assignment]
594
+ custom_triton_ops_decomposition_ctx = (
595
+ contextlib.nullcontext
596
+ if decompose_custom_triton_ops
597
+ else _disable_custom_triton_op_functional_decomposition
598
+ )
599
+ with (
600
+ _ignore_backend_decomps(),
601
+ fake_mode_ctx,
602
+ _override_composite_implicit_decomp(cia_to_decomp),
603
+ custom_triton_ops_decomposition_ctx(),
604
+ ):
605
+ gm, graph_signature = aot_export_module(
606
+ ep.graph_module,
607
+ fake_args,
608
+ # pyrefly: ignore[bad-argument-type]
609
+ decompositions=python_decomp_table,
610
+ trace_joint=joint_loss_index is not None,
611
+ output_loss_index=(
612
+ joint_loss_index if joint_loss_index is not None else None
613
+ ),
614
+ )
615
+ if not isinstance(gm, torch.fx.GraphModule):
616
+ raise AssertionError(f"expected torch.fx.GraphModule, got {type(gm)}")
617
+ gm.graph.eliminate_dead_code()
618
+
619
+ # Update the signatures with the new placeholder names in case they
620
+ # changed when calling aot_export
621
+ def update_arg(old_arg, new_ph):
622
+ if isinstance(old_arg, ConstantArgument):
623
+ return old_arg
624
+ elif isinstance(old_arg, TensorArgument):
625
+ return TensorArgument(name=new_ph.name)
626
+ elif isinstance(old_arg, SymIntArgument):
627
+ return SymIntArgument(name=new_ph.name)
628
+ elif isinstance(old_arg, SymFloatArgument):
629
+ return SymFloatArgument(name=new_ph.name)
630
+ elif isinstance(old_arg, SymBoolArgument):
631
+ return SymBoolArgument(name=new_ph.name)
632
+ raise RuntimeError(f"Type of old_arg not supported: {type(old_arg)}")
633
+
634
+ new_placeholders = [node for node in gm.graph.nodes if node.op == "placeholder"]
635
+ new_outputs: tuple[torch.fx.Node, ...] = tuple(gm.graph.output_node().args[0]) # type: ignore[arg-type]
636
+
637
+ # rename the placeholders
638
+ if len(new_placeholders) != len(old_placeholders):
639
+ raise AssertionError(
640
+ f"new_placeholders length {len(new_placeholders)} does not match old_placeholders length {len(old_placeholders)}"
641
+ )
642
+ for old_ph, new_ph in zip(old_placeholders, new_placeholders):
643
+ new_ph.name = new_ph.target = old_ph.name
644
+
645
+ # handle name collisions with newly decomposed graph nodes
646
+ name_map = {}
647
+ find_available: dict[str, int] = defaultdict(int)
648
+ used_names: set[str] = set()
649
+ for ph in new_placeholders:
650
+ name_map[ph.name] = ph.name
651
+ _build_cache(ph.name, find_available, used_names)
652
+ for node in gm.graph.nodes:
653
+ if node.op == "placeholder":
654
+ continue
655
+ node.name = _rename_without_collisions(
656
+ name_map, find_available, used_names, node.name, node.name
657
+ )
658
+
659
+ # propagate names to higher order op subgraphs
660
+ _name_hoo_subgraph_placeholders(gm)
661
+
662
+ # Run this pass before creating input/output specs, since size-related CSE/DCE might affect output signature.
663
+ # Overwrite output specs afterwards.
664
+ from torch._export.passes._node_metadata_hook import (
665
+ _node_metadata_hook,
666
+ _set_node_metadata_hook,
667
+ )
668
+ from torch._functorch._aot_autograd.input_output_analysis import _graph_output_names
669
+
670
+ if not torch._dynamo.config.do_not_emit_runtime_asserts:
671
+ stack_trace = (
672
+ 'File "torch/fx/passes/runtime_assert.py", line 24, '
673
+ "in insert_deferred_runtime_asserts"
674
+ )
675
+ shape_env = _get_shape_env(gm)
676
+ if shape_env is not None:
677
+ with _set_node_metadata_hook(
678
+ gm,
679
+ functools.partial(
680
+ _node_metadata_hook, metadata={"stack_trace": stack_trace}
681
+ ),
682
+ ):
683
+ insert_deferred_runtime_asserts(
684
+ gm,
685
+ shape_env,
686
+ f"exported program: {first_call_function_nn_module_stack(gm.graph)}",
687
+ export=True,
688
+ )
689
+
690
+ # update output specs
691
+ gm.recompile()
692
+ for output, name in zip(new_outputs, _graph_output_names(gm)):
693
+ if name is not None:
694
+ output.name = name
695
+
696
+ # To match the output target with correct input for input mutations
697
+ # need to find the old to new placeholder map
698
+ old_new_placeholder_map = {
699
+ spec.arg.name: new_placeholders[i].name
700
+ for i, spec in enumerate(ep.graph_signature.input_specs)
701
+ if not isinstance(spec.arg, ConstantArgument)
702
+ }
703
+
704
+ input_specs = [
705
+ InputSpec(
706
+ spec.kind,
707
+ update_arg(spec.arg, new_placeholders[i]),
708
+ spec.target,
709
+ spec.persistent,
710
+ )
711
+ for i, spec in enumerate(ep.graph_signature.input_specs)
712
+ ]
713
+
714
+ output_specs = []
715
+
716
+ # handle buffer & input mutations; these appear before loss output & gradients
717
+ # (1) ep.graph_signature.input_specs tells us types of inputs
718
+ # (2) graph_signature.user_inputs tells us node input names in order
719
+ # (3) graph_signature.user_inputs_to_mutate tells us buffer & input mutations
720
+ # map (3) -> (2) for input order, -> (1) for input type
721
+ user_inputs_index = {name: i for i, name in enumerate(graph_signature.user_inputs)}
722
+ mutation_names = list(graph_signature.user_inputs_to_mutate.keys())
723
+ expected_names = [node.name for node in new_outputs[: len(mutation_names)]]
724
+ if mutation_names != expected_names:
725
+ raise AssertionError(
726
+ f"mutation_names {mutation_names} does not match expected {expected_names}"
727
+ )
728
+ for output_name, input_name in graph_signature.user_inputs_to_mutate.items():
729
+ i = user_inputs_index[input_name]
730
+ input_spec = ep.graph_signature.input_specs[i]
731
+ if input_spec.kind not in (InputKind.USER_INPUT, InputKind.BUFFER):
732
+ raise AssertionError(
733
+ f"expected input_spec.kind to be USER_INPUT or BUFFER, got {input_spec.kind}"
734
+ )
735
+ output_kind = (
736
+ OutputKind.BUFFER_MUTATION
737
+ if input_spec.kind == InputKind.BUFFER
738
+ else OutputKind.USER_INPUT_MUTATION
739
+ )
740
+ target = (
741
+ input_spec.target
742
+ if input_spec.kind == InputKind.BUFFER
743
+ else input_spec.arg.name
744
+ )
745
+ output_specs.append(
746
+ OutputSpec(
747
+ kind=output_kind,
748
+ arg=TensorArgument(name=output_name),
749
+ target=target,
750
+ )
751
+ )
752
+
753
+ # handle actual user outputs
754
+ for i, spec in enumerate(ep.graph_signature.output_specs):
755
+ output_specs.append(
756
+ OutputSpec(
757
+ OutputKind.LOSS_OUTPUT if i == joint_loss_index else spec.kind,
758
+ update_arg(spec.arg, new_outputs[len(mutation_names) + i]),
759
+ old_new_placeholder_map.get(spec.target, spec.target),
760
+ )
761
+ )
762
+
763
+ if joint_loss_index is not None:
764
+ if graph_signature.backward_signature is None:
765
+ raise AssertionError(
766
+ "graph_signature.backward_signature must not be None when joint_loss_index is set"
767
+ )
768
+ gradients = graph_signature.backward_signature.gradients_to_user_inputs
769
+ if len(graph_signature.user_inputs) != len(ep.graph_signature.input_specs):
770
+ raise AssertionError(
771
+ f"graph_signature.user_inputs length {len(graph_signature.user_inputs)} does not match "
772
+ f"input_specs length {len(ep.graph_signature.input_specs)}"
773
+ )
774
+ specs = {
775
+ graph_signature.user_inputs[i]: spec
776
+ for i, spec in enumerate(ep.graph_signature.input_specs)
777
+ if isinstance(spec.arg, TensorArgument)
778
+ }
779
+ for node in new_outputs[len(output_specs) :]:
780
+ source = gradients[node.name]
781
+ spec = specs[source] # type: ignore[index]
782
+ if spec.kind == InputKind.PARAMETER:
783
+ kind = OutputKind.GRADIENT_TO_PARAMETER
784
+ target = spec.target
785
+ elif spec.kind == InputKind.USER_INPUT:
786
+ kind = OutputKind.GRADIENT_TO_USER_INPUT
787
+ target = source
788
+ else:
789
+ raise AssertionError(f"Unknown input kind: {spec.kind}")
790
+ output_specs.append(
791
+ OutputSpec(
792
+ kind,
793
+ TensorArgument(name=node.name),
794
+ target,
795
+ )
796
+ )
797
+
798
+ if len(new_placeholders) != len(old_placeholders):
799
+ raise AssertionError(
800
+ f"new_placeholders length {len(new_placeholders)} does not match old_placeholders length {len(old_placeholders)}"
801
+ )
802
+
803
+ new_graph_signature = ExportGraphSignature(
804
+ input_specs=input_specs, output_specs=output_specs
805
+ )
806
+ # NOTE: aot_export adds symint metadata for placeholders with int
807
+ # values; since these become specialized, we replace such metadata with
808
+ # the original values.
809
+ # Also, set the param/buffer metadata back to the placeholders.
810
+ inputs_to_parameters = new_graph_signature.inputs_to_parameters
811
+ inputs_to_buffers = new_graph_signature.inputs_to_buffers
812
+ for old_node, new_node in zip(old_placeholders, new_placeholders):
813
+ if not isinstance(old_node.meta["val"], torch.Tensor):
814
+ new_node.meta["val"] = old_node.meta["val"]
815
+
816
+ if (
817
+ new_node.target in inputs_to_parameters
818
+ or new_node.target in inputs_to_buffers
819
+ ):
820
+ for k, v in old_node.meta.items():
821
+ new_node.meta[k] = v
822
+ return gm, new_graph_signature, ep.state_dict, ep.constants
823
+
824
+
825
+ def _remove_unnecessary_copy_op_pass(
826
+ gm: torch.fx.GraphModule, new_graph_signature: ExportGraphSignature
827
+ ) -> tuple[torch.fx.GraphModule, ExportGraphSignature]:
828
+ """
829
+ Removes redundant copy_ node that was introduced due to mutated buffer.
830
+ """
831
+ buffers_to_mutate = new_graph_signature.buffers_to_mutate
832
+ parameters_to_mutate = new_graph_signature.parameters_to_mutate
833
+ with gm._set_replace_hook(new_graph_signature.get_replace_hook()):
834
+ for node in gm.graph.nodes:
835
+ if node.op == "output":
836
+ args, _ = pytree.tree_flatten(node.args)
837
+ for out in args:
838
+ if isinstance(out, torch.fx.Node) and (
839
+ out.name in buffers_to_mutate
840
+ or out.name in parameters_to_mutate
841
+ ):
842
+ if (
843
+ out.op == "call_function"
844
+ and out.target is torch.ops.aten.copy.default
845
+ ):
846
+ out.replace_all_uses_with(out.args[1]) # type: ignore[arg-type]
847
+ gm.graph.erase_node(out)
848
+ gm.recompile()
849
+ return gm, new_graph_signature
850
+
851
+
852
+ def _common_getitem_elimination_pass(
853
+ gm: torch.fx.GraphModule, graph_signature, module_call_graph
854
+ ):
855
+ with gm._set_replace_hook(graph_signature.get_replace_hook()):
856
+ for module in gm.modules():
857
+ if not isinstance(module, torch.fx.GraphModule):
858
+ continue
859
+
860
+ node_id: dict[torch.fx.Node, str] = {}
861
+ getitems: dict[str, torch.fx.Node] = {}
862
+ for node in list(module.graph.nodes):
863
+ if node.op == "call_function" and node.target is operator.getitem:
864
+ source, idx = node.args
865
+ new_id = f"{node_id[source]}.{idx}"
866
+ if new_id in getitems:
867
+ node.replace_all_uses_with(getitems[new_id])
868
+ for entry in module_call_graph:
869
+ if entry.signature is not None:
870
+ entry.signature.replace_all_uses_with(
871
+ node, getitems[new_id]
872
+ )
873
+ module.graph.erase_node(node)
874
+ else:
875
+ getitems[new_id] = node
876
+ node_id[node] = new_id
877
+ else:
878
+ node_id[node] = node.name
879
+
880
+
881
+ def _get_updated_module_call_graph(
882
+ old_gm: torch.fx.GraphModule,
883
+ old_graph_signature: ExportGraphSignature,
884
+ gm: torch.fx.GraphModule,
885
+ graph_signature: ExportGraphSignature,
886
+ old_module_call_graph: list[ModuleCallEntry],
887
+ ):
888
+ new_module_call_graph = copy.deepcopy(old_module_call_graph)
889
+
890
+ old_nodes = {node.name: node for node in old_gm.graph.nodes}
891
+
892
+ old_graph_params_buffers = {
893
+ **old_graph_signature.inputs_to_parameters,
894
+ **old_graph_signature.inputs_to_buffers,
895
+ }
896
+ new_graph_params_buffers = {
897
+ **graph_signature.inputs_to_parameters,
898
+ **graph_signature.inputs_to_buffers,
899
+ }
900
+ old_graph_non_user_inputs = {
901
+ **old_graph_params_buffers,
902
+ **old_graph_signature.inputs_to_lifted_tensor_constants,
903
+ **old_graph_signature.inputs_to_lifted_custom_objs,
904
+ }
905
+ new_graph_non_user_inputs = {
906
+ **new_graph_params_buffers,
907
+ **graph_signature.inputs_to_lifted_tensor_constants,
908
+ **graph_signature.inputs_to_lifted_custom_objs,
909
+ }
910
+
911
+ # use node-level provenance metadata to create a map
912
+ # from old node names to new node names
913
+ provenance: dict[str, str] = {}
914
+
915
+ user_input_counter = 0
916
+ old_user_input_names = [
917
+ node.target for node in old_gm.graph.nodes if node.op == "placeholder"
918
+ ]
919
+ old_user_input_names = list(
920
+ filter(
921
+ lambda x: x not in old_graph_non_user_inputs
922
+ and x not in old_graph_signature.input_tokens,
923
+ old_user_input_names,
924
+ )
925
+ )
926
+ new_user_input_names = [
927
+ node.target for node in gm.graph.nodes if node.op == "placeholder"
928
+ ]
929
+
930
+ for node in gm.graph.nodes:
931
+ if history := node.meta.get("from_node", []):
932
+ provenance[history[-1].name] = node.name
933
+
934
+ # For params and buffers, we might have applied parameterization rule
935
+ # so that the names might have changed. But for user inputs, we know we
936
+ # must preserve the old name.
937
+ elif node.op == "placeholder":
938
+ if not (
939
+ node.target in new_graph_non_user_inputs
940
+ or node.target in graph_signature.input_tokens
941
+ ):
942
+ if node.target in new_user_input_names:
943
+ if not isinstance(node.name, str):
944
+ raise AssertionError(
945
+ f"expected node.name to be str, got {type(node.name)}"
946
+ )
947
+ old_name = old_user_input_names[user_input_counter]
948
+ if not isinstance(old_name, str):
949
+ raise AssertionError(
950
+ f"expected old_name to be str, got {type(old_name)}"
951
+ )
952
+ provenance[old_name] = node.name
953
+ user_input_counter += 1
954
+
955
+ # For all the parameters and buffers, we first see
956
+ # if they are result of parametrizations and if they
957
+ # are, we log them and error later
958
+ old_param_to_desugared = defaultdict(list)
959
+ for name, target in new_graph_params_buffers.items():
960
+ # if the parameters are not parametrized, the naming won't change.
961
+ if not target.startswith("parametrizations."):
962
+ # If we are in strict mode, we can't just reuse the param names
963
+ if name in old_graph_params_buffers:
964
+ provenance[name] = name
965
+ else:
966
+ old_target = ".".join(target.split(".")[1:-1])
967
+ old_param_to_desugared[old_target].append(name)
968
+
969
+ # map old names to new names in module call signatures
970
+ for entry in new_module_call_graph:
971
+ signature = entry.signature
972
+ if signature is None:
973
+ continue
974
+ for x in [*signature.inputs, *signature.outputs]:
975
+ # We noticed that submodule is taking subclass as input. we can't
976
+ # preserve signature here.
977
+ if x.name in old_param_to_desugared:
978
+ raise ValueError(
979
+ f"It looks like {x.name} is a tensor subclass. "
980
+ f"Preserving submodule that takes subclass parameter is not supported"
981
+ f" in inference IR because we desugar them, resulting in more tensors"
982
+ )
983
+
984
+ if x.name in provenance:
985
+ x.name = provenance[x.name]
986
+
987
+ # This can happen when aten.to is called at graph boundaries.
988
+ # Basically aten.to at post-dispatch level can either be copy
989
+ # or alias. In the alias case, we will no-op it so it will
990
+ # disappear from the graph. If we detect such case, we should
991
+ # reuse the input to aten.to as the new input to the submodule.
992
+ # Technically this can happen for other maybe aliasing ops,
993
+ # but aten.to is probably the most common one.
994
+ elif x.name in old_nodes:
995
+ old_node = old_nodes[x.name]
996
+ if old_node.op == "call_function" and old_node.target in [
997
+ torch.ops.aten.to.dtype_layout,
998
+ torch.ops.aten.to.device,
999
+ torch.ops.aten.to.dtype,
1000
+ ]:
1001
+ old_target = old_node.args[0].name
1002
+ if old_target not in provenance:
1003
+ raise ValueError(
1004
+ f"It looks like {old_target} is a tensor subclass. "
1005
+ f"Preserving submodule that takes subclass parameter is not supported"
1006
+ f" in inference IR because we desugar them, resulting in more tensors"
1007
+ )
1008
+
1009
+ x.name = provenance[old_target]
1010
+
1011
+ return new_module_call_graph
1012
+
1013
+
1014
+ def _decompose_exported_program(
1015
+ ep,
1016
+ *,
1017
+ cia_to_decomp: dict[torch._ops.OperatorBase, Callable],
1018
+ python_decomp_table: dict[torch._ops.OperatorBase, Callable],
1019
+ joint_loss_index: int | None,
1020
+ decompose_custom_triton_ops: bool,
1021
+ ):
1022
+ (
1023
+ gm,
1024
+ new_graph_signature,
1025
+ state_dict,
1026
+ constants,
1027
+ ) = _decompose_and_get_gm_with_new_signature_constants(
1028
+ ep,
1029
+ cia_to_decomp=cia_to_decomp,
1030
+ python_decomp_table=python_decomp_table,
1031
+ joint_loss_index=joint_loss_index,
1032
+ decompose_custom_triton_ops=decompose_custom_triton_ops,
1033
+ )
1034
+
1035
+ # The signatures of ep.module_call_graph refer to input / output nodes of
1036
+ # the original graph module. However, the new graph module may have
1037
+ # new nodes due to decompositions. So we need to update these signatures
1038
+ # in the decomposed exported program's module_call_graph.
1039
+ new_module_call_graph = _get_updated_module_call_graph(
1040
+ ep.graph_module,
1041
+ ep.graph_signature,
1042
+ gm,
1043
+ new_graph_signature,
1044
+ ep.module_call_graph,
1045
+ )
1046
+
1047
+ # TODO unfortunately preserving graph-level metadata is not
1048
+ # working well with aot_export. So we manually copy it.
1049
+ # (The node-level meta is addressed above.)
1050
+ gm.meta.update(ep.graph_module.meta)
1051
+
1052
+ new_range_constraints = _get_updated_range_constraints(
1053
+ gm,
1054
+ ep.range_constraints,
1055
+ )
1056
+
1057
+ exported_program = ExportedProgram(
1058
+ root=gm,
1059
+ graph=gm.graph,
1060
+ graph_signature=new_graph_signature,
1061
+ state_dict=state_dict,
1062
+ range_constraints=new_range_constraints,
1063
+ module_call_graph=new_module_call_graph,
1064
+ example_inputs=ep.example_inputs,
1065
+ constants=constants,
1066
+ )
1067
+ return exported_program
1068
+
1069
+
1070
+ class ExportedProgram:
1071
+ """
1072
+ Package of a program from :func:`export`. It contains
1073
+ an :class:`torch.fx.Graph` that represents Tensor computation, a state_dict containing
1074
+ tensor values of all lifted parameters and buffers, and various metadata.
1075
+
1076
+ You can call an ExportedProgram like the original callable traced by
1077
+ :func:`export` with the same calling convention.
1078
+
1079
+ To perform transformations on the graph, use ``.module`` property to access
1080
+ an :class:`torch.fx.GraphModule`. You can then use
1081
+ `FX transformation <https://pytorch.org/docs/stable/fx.html#writing-transformations>`_
1082
+ to rewrite the graph. Afterwards, you can simply use :func:`export`
1083
+ again to construct a correct ExportedProgram.
1084
+ """
1085
+
1086
+ _graph_module: torch.fx.GraphModule
1087
+ """The underlying GraphModule containing the exported computation graph."""
1088
+
1089
+ _graph_signature: ExportGraphSignature
1090
+ """The signature containing input/output specifications for the graph."""
1091
+
1092
+ _state_dict: dict[str, Any]
1093
+ """Dictionary containing parameter and buffer values from the original module."""
1094
+
1095
+ _range_constraints: "dict[sympy.Symbol, ValueRanges]"
1096
+ """Symbolic shape constraints for dynamic shapes in the graph."""
1097
+
1098
+ _module_call_graph: list[ModuleCallEntry]
1099
+ """Call graph information tracking module hierarchy and signatures."""
1100
+
1101
+ _example_inputs: tuple[tuple[Any, ...], dict[str, Any]] | None
1102
+ """Example inputs used during export, stored as (args, kwargs) tuple."""
1103
+
1104
+ _constants: dict[str, _ConstantAttributeType]
1105
+ """Dictionary of constant values used in the graph."""
1106
+
1107
+ _verifiers: list[type[Verifier]]
1108
+ """List of verifier classes used to validate the exported program."""
1109
+
1110
+ _guards_code: list[str]
1111
+
1112
+ def __init__(
1113
+ self,
1114
+ root: torch.nn.Module | dict[str, Any],
1115
+ graph: torch.fx.Graph,
1116
+ graph_signature: ExportGraphSignature,
1117
+ state_dict: dict[str, torch.Tensor | torch.nn.Parameter],
1118
+ range_constraints: "dict[sympy.Symbol, Any]",
1119
+ module_call_graph: list[ModuleCallEntry],
1120
+ example_inputs: tuple[tuple[Any, ...], dict[str, Any]] | None = None,
1121
+ constants: dict[str, _ConstantAttributeType] | None = None,
1122
+ *,
1123
+ verifiers: list[type[Verifier]] | None = None,
1124
+ ):
1125
+ # Remove codegen related things from the graph. It should just be a flat graph.
1126
+ graph._codegen = torch.fx.graph.CodeGen()
1127
+ self._graph_module = _create_graph_module_for_export(root, graph)
1128
+ if isinstance(root, torch.fx.GraphModule):
1129
+ self._graph_module.meta.update(root.meta)
1130
+
1131
+ _common_getitem_elimination_pass(
1132
+ self._graph_module, graph_signature, module_call_graph
1133
+ )
1134
+ self._graph_signature: ExportGraphSignature = graph_signature
1135
+ self._state_dict: dict[str, Any] = state_dict
1136
+ self._range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints
1137
+ if module_call_graph is None:
1138
+ raise AssertionError("module_call_graph must not be None")
1139
+ self._module_call_graph: list[ModuleCallEntry] = module_call_graph
1140
+ self._example_inputs = example_inputs
1141
+
1142
+ self._constants = constants or {}
1143
+
1144
+ verifiers = verifiers or [Verifier]
1145
+ if not all(issubclass(v, Verifier) for v in verifiers):
1146
+ raise AssertionError(
1147
+ f"all verifiers must be subclasses of Verifier, got {verifiers}"
1148
+ )
1149
+ self._verifiers = verifiers
1150
+ # Validate should be always the last step of the constructor.
1151
+ self.validate()
1152
+
1153
+ self._guards_code = _convert_guards_to_code(self._graph_module)
1154
+
1155
+ @property
1156
+ @compatibility(is_backward_compatible=False)
1157
+ def graph_module(self):
1158
+ return self._graph_module
1159
+
1160
+ @graph_module.setter
1161
+ @compatibility(is_backward_compatible=False)
1162
+ def graph_module(self, value):
1163
+ raise RuntimeError("Unable to set ExportedProgram's graph_module attribute.")
1164
+
1165
+ @property
1166
+ @compatibility(is_backward_compatible=False)
1167
+ def graph(self):
1168
+ return self.graph_module.graph
1169
+
1170
+ @graph.setter
1171
+ @compatibility(is_backward_compatible=False)
1172
+ def graph(self, value):
1173
+ raise RuntimeError("Unable to set ExportedProgram's graph attribute.")
1174
+
1175
+ @property
1176
+ @compatibility(is_backward_compatible=False)
1177
+ def graph_signature(self):
1178
+ return self._graph_signature
1179
+
1180
+ @graph_signature.setter
1181
+ @compatibility(is_backward_compatible=False)
1182
+ def graph_signature(self, value):
1183
+ raise RuntimeError("Unable to set ExportedProgram's graph_signature attribute.")
1184
+
1185
+ @property
1186
+ @compatibility(is_backward_compatible=False)
1187
+ def state_dict(self):
1188
+ return self._state_dict
1189
+
1190
+ @state_dict.setter
1191
+ @compatibility(is_backward_compatible=False)
1192
+ def state_dict(self, value):
1193
+ raise RuntimeError("Unable to set ExportedProgram's state_dict attribute.")
1194
+
1195
+ @compatibility(is_backward_compatible=False)
1196
+ def parameters(self) -> Iterator[torch.nn.Parameter]:
1197
+ """
1198
+ Returns an iterator over original module's parameters.
1199
+ """
1200
+ for _, param in self.named_parameters():
1201
+ yield param
1202
+
1203
+ @compatibility(is_backward_compatible=False)
1204
+ def named_parameters(self) -> Iterator[tuple[str, torch.nn.Parameter]]:
1205
+ """
1206
+ Returns an iterator over original module parameters, yielding
1207
+ both the name of the parameter as well as the parameter itself.
1208
+ """
1209
+ for param_name in self.graph_signature.parameters:
1210
+ yield param_name, self.state_dict[param_name]
1211
+
1212
+ @compatibility(is_backward_compatible=False)
1213
+ def buffers(self) -> Iterator[torch.Tensor]:
1214
+ """
1215
+ Returns an iterator over original module buffers.
1216
+ """
1217
+ for _, buf in self.named_buffers():
1218
+ yield buf
1219
+
1220
+ @compatibility(is_backward_compatible=False)
1221
+ def named_buffers(self) -> Iterator[tuple[str, torch.Tensor]]:
1222
+ """
1223
+ Returns an iterator over original module buffers, yielding
1224
+ both the name of the buffer as well as the buffer itself.
1225
+ """
1226
+ non_persistent_buffers = set(self.graph_signature.non_persistent_buffers)
1227
+ # Lazily computed on first use to avoid calling graph_module.state_dict()
1228
+ # unless at least one buffer is absent from state_dict and constants.
1229
+ gm_state_dict = None
1230
+ for buffer_name in self.graph_signature.buffers:
1231
+ if buffer_name in non_persistent_buffers:
1232
+ yield buffer_name, self.constants[buffer_name]
1233
+ elif buffer_name in self.state_dict:
1234
+ yield buffer_name, self.state_dict[buffer_name]
1235
+ elif buffer_name in self.constants:
1236
+ yield buffer_name, self.constants[buffer_name]
1237
+ else:
1238
+ # Nested invoke_subgraph tracing can surface lifted tensor
1239
+ # constants owned by an inner subgraph as persistent buffers
1240
+ # in the top-level graph signature; the tensor lives in the
1241
+ # subgraph submodule rather than state_dict or constants.
1242
+ if gm_state_dict is None:
1243
+ gm_state_dict = self.graph_module.state_dict()
1244
+ yield buffer_name, gm_state_dict[buffer_name]
1245
+
1246
+ @property
1247
+ @compatibility(is_backward_compatible=False)
1248
+ def range_constraints(self):
1249
+ return self._range_constraints
1250
+
1251
+ @range_constraints.setter
1252
+ @compatibility(is_backward_compatible=False)
1253
+ def range_constraints(self, value):
1254
+ raise RuntimeError(
1255
+ "Unable to set ExportedProgram's range_constraints attribute."
1256
+ )
1257
+
1258
+ @property
1259
+ @compatibility(is_backward_compatible=False)
1260
+ def module_call_graph(self):
1261
+ return self._module_call_graph
1262
+
1263
+ @module_call_graph.setter
1264
+ @compatibility(is_backward_compatible=False)
1265
+ def module_call_graph(self, value):
1266
+ raise RuntimeError(
1267
+ "Unable to set ExportedProgram's module_call_graph attribute."
1268
+ )
1269
+
1270
+ @property
1271
+ @compatibility(is_backward_compatible=False)
1272
+ def example_inputs(self):
1273
+ return self._example_inputs
1274
+
1275
+ @example_inputs.setter
1276
+ @compatibility(is_backward_compatible=False)
1277
+ def example_inputs(self, value):
1278
+ # This is allowed
1279
+
1280
+ if value is None:
1281
+ self._example_inputs = value
1282
+ return
1283
+
1284
+ if not (
1285
+ isinstance(value, tuple)
1286
+ and len(value) == 2
1287
+ and isinstance(value[0], tuple)
1288
+ and isinstance(value[1], dict)
1289
+ ):
1290
+ raise ValueError(
1291
+ "Example inputs should be a tuple containing example arguments (as "
1292
+ "a tuple), and example kwargs (as a dictionary)."
1293
+ )
1294
+
1295
+ args, kwargs = value
1296
+ from ._unlift import _check_inputs_match
1297
+
1298
+ _check_inputs_match(args, kwargs, self.call_spec.in_spec)
1299
+
1300
+ self._example_inputs = value
1301
+
1302
+ @property
1303
+ @compatibility(is_backward_compatible=False)
1304
+ def call_spec(self):
1305
+ class CallSpec(NamedTuple):
1306
+ in_spec: pytree.TreeSpec | None
1307
+ out_spec: pytree.TreeSpec | None
1308
+
1309
+ if len(self.module_call_graph) == 0:
1310
+ return CallSpec(in_spec=None, out_spec=None)
1311
+ if self.module_call_graph[0].fqn != "":
1312
+ raise AssertionError(
1313
+ f"expected first module_call_graph fqn to be empty string, got {self.module_call_graph[0].fqn!r}"
1314
+ )
1315
+ return CallSpec(
1316
+ in_spec=self.module_call_graph[0].signature.in_spec,
1317
+ out_spec=self.module_call_graph[0].signature.out_spec,
1318
+ )
1319
+
1320
+ @call_spec.setter
1321
+ @compatibility(is_backward_compatible=False)
1322
+ def call_spec(self, value):
1323
+ raise RuntimeError("Unable to set ExportedProgram's call_spec attribute.")
1324
+
1325
+ @property
1326
+ @compatibility(is_backward_compatible=False)
1327
+ def verifier(self) -> Any:
1328
+ return self._verifiers[0]
1329
+
1330
+ @verifier.setter
1331
+ @compatibility(is_backward_compatible=False)
1332
+ def verifier(self, value):
1333
+ raise RuntimeError("Unable to set ExportedProgram's verifier attribute.")
1334
+
1335
+ @property
1336
+ @compatibility(is_backward_compatible=False)
1337
+ def dialect(self) -> str:
1338
+ if self._verifiers is None:
1339
+ raise AssertionError("_verifiers must not be None")
1340
+ return self._verifiers[0].dialect
1341
+
1342
+ @dialect.setter
1343
+ @compatibility(is_backward_compatible=False)
1344
+ def dialect(self, value):
1345
+ raise RuntimeError("Unable to set ExportedProgram's dialect attribute.")
1346
+
1347
+ @property
1348
+ @compatibility(is_backward_compatible=False)
1349
+ def verifiers(self):
1350
+ return self._verifiers
1351
+
1352
+ @verifiers.setter
1353
+ @compatibility(is_backward_compatible=False)
1354
+ def verifiers(self, value):
1355
+ raise RuntimeError("Unable to set ExportedProgram's verifiers attribute.")
1356
+
1357
+ @property
1358
+ @compatibility(is_backward_compatible=False)
1359
+ def tensor_constants(self):
1360
+ return self._constants
1361
+
1362
+ @tensor_constants.setter
1363
+ @compatibility(is_backward_compatible=False)
1364
+ def tensor_constants(self, value):
1365
+ raise RuntimeError(
1366
+ "Unable to set ExportedProgram's tensor_constants attribute."
1367
+ )
1368
+
1369
+ @property
1370
+ @compatibility(is_backward_compatible=False)
1371
+ def constants(self):
1372
+ return self._constants
1373
+
1374
+ @constants.setter
1375
+ @compatibility(is_backward_compatible=False)
1376
+ def constants(self, value):
1377
+ raise RuntimeError("Unable to set ExportedProgram's constants attribute.")
1378
+
1379
+ def _get_flat_args_with_check(self, args, kwargs):
1380
+ """Flatten args, kwargs using pytree, then, check specs.
1381
+
1382
+ Args:
1383
+ args: List[Any] original args passed to __call__
1384
+ kwargs: Dict[str, Any] original kwargs passed to __call
1385
+
1386
+ Returns:
1387
+ A tuple of (flat_args, received_spec)
1388
+ flat_args is flattened args / kwargs
1389
+ received_spec is the pytree spec produced while flattening the
1390
+ tuple (args, kwargs)
1391
+ """
1392
+ in_spec = self.call_spec.in_spec
1393
+ if in_spec is not None:
1394
+ kwargs = reorder_kwargs(kwargs, in_spec)
1395
+ flat_args_with_path, received_spec = pytree.tree_flatten_with_path(
1396
+ (args, kwargs)
1397
+ )
1398
+ self._check_input_constraints(flat_args_with_path)
1399
+ flat_args = tuple(x[1] for x in flat_args_with_path)
1400
+ return flat_args, received_spec
1401
+
1402
+ def _graph_module_flat_inputs(self, args: Any, kwargs: Any) -> Any:
1403
+ """Transform args, kwargs of __call__ to args for graph_module.
1404
+
1405
+ self.graph_module takes stuff from state dict as inputs.
1406
+ The invariant is for ep: ExportedProgram is
1407
+ ep(args, kwargs) ==
1408
+ ep.postprocess(ep.graph_module(ep.graph_module_flat_inputs(args, kwargs)))
1409
+ """
1410
+
1411
+ in_spec = self.call_spec.in_spec
1412
+ flat_args, received_spec = self._get_flat_args_with_check(args, kwargs)
1413
+ if in_spec is not None and not is_equivalent(
1414
+ received_spec, in_spec, _fx_collection_equivalence_fn
1415
+ ):
1416
+ raise ValueError(
1417
+ "Trying to flatten user inputs with exported input tree spec: \n"
1418
+ f"{in_spec}\n"
1419
+ "but actually got inputs with tree spec of: \n"
1420
+ f"{received_spec}"
1421
+ )
1422
+
1423
+ additional_inputs = []
1424
+ gm_state_dict = None
1425
+ for input_ in self.graph_signature.input_specs:
1426
+ if input_.kind == InputKind.USER_INPUT:
1427
+ continue
1428
+ elif input_.kind in (
1429
+ InputKind.PARAMETER,
1430
+ InputKind.BUFFER,
1431
+ ):
1432
+ if input_.persistent is False:
1433
+ # This is a non-persistent buffer, grab it from our
1434
+ # constants instead of the state dict.
1435
+ additional_inputs.append(self.constants[input_.target])
1436
+ elif input_.target in self.state_dict:
1437
+ additional_inputs.append(self.state_dict[input_.target])
1438
+ elif input_.target in self.constants:
1439
+ additional_inputs.append(self.constants[input_.target])
1440
+ else:
1441
+ # Nested invoke_subgraph tracing can leave a lifted tensor
1442
+ # constant in the subgraph submodule's state rather than
1443
+ # the top-level state_dict or constants.
1444
+ if gm_state_dict is None:
1445
+ gm_state_dict = self.graph_module.state_dict()
1446
+ additional_inputs.append(gm_state_dict[input_.target])
1447
+ elif input_.kind in (
1448
+ InputKind.CONSTANT_TENSOR,
1449
+ InputKind.CUSTOM_OBJ,
1450
+ ):
1451
+ additional_inputs.append(self.constants[input_.target])
1452
+ additional_inputs = tuple(additional_inputs)
1453
+
1454
+ # NOTE: calling convention is first params, then buffers, then args as user supplied them.
1455
+ # See: torch/_functorch/aot_autograd.py#L1034
1456
+ return additional_inputs + flat_args
1457
+
1458
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
1459
+ raise RuntimeError(
1460
+ "Unable to call ExportedProgram directly. "
1461
+ "You should use `exported_program.module()` instead."
1462
+ )
1463
+
1464
+ def __str__(self) -> str:
1465
+ graph_module = self.graph_module.print_readable(
1466
+ print_output=False, colored=False
1467
+ ).replace("\n", "\n ")
1468
+ graph_signature = str(self.graph_signature).replace("\n", "\n ")
1469
+ # No space after "Graph signature:" — graph_signature starts with
1470
+ # a newline; trailing whitespace breaks expecttest snapshots.
1471
+ string = (
1472
+ "ExportedProgram:\n"
1473
+ f" {graph_module}\n"
1474
+ f"Graph signature:{graph_signature}\n"
1475
+ f"Range constraints: {self.range_constraints}\n"
1476
+ )
1477
+ return string
1478
+
1479
+ def module(self, check_guards=True) -> torch.fx.GraphModule:
1480
+ """
1481
+ Returns a self contained GraphModule with all the parameters/buffers inlined.
1482
+
1483
+ - When `check_guards=True` (default), a `_guards_fn` submodule is generated
1484
+ and a call to a `_guards_fn` submodule is inserted right after placeholders
1485
+ in the graph. This module checks guards on inputs.
1486
+ - When `check_guards=False`, a subset of these checks are performed by a
1487
+ forward pre-hook on the graph module. No `_guards_fn` submodule is generated.
1488
+
1489
+ """
1490
+ from ._unlift import _unlift_exported_program_lifted_states
1491
+
1492
+ module = _unlift_exported_program_lifted_states(self, check_guards=check_guards)
1493
+
1494
+ def _train(self, mode: bool = True):
1495
+ raise NotImplementedError("Calling train() is not supported yet.")
1496
+
1497
+ def _eval(self, mode: bool = True):
1498
+ raise NotImplementedError("Calling eval() is not supported yet.")
1499
+
1500
+ module.train = types.MethodType(_train, module) # type: ignore[method-assign]
1501
+ module.eval = types.MethodType(_eval, module) # type: ignore[method-assign]
1502
+ return module
1503
+
1504
+ def _num_lifted_params_buffers(self):
1505
+ return next(
1506
+ (
1507
+ i
1508
+ for i, s in enumerate(self._graph_signature.input_specs)
1509
+ if s.kind == InputKind.USER_INPUT
1510
+ ),
1511
+ len(self._graph_signature.input_specs),
1512
+ )
1513
+
1514
+ @_disable_prexisiting_fake_mode
1515
+ def run_decompositions(
1516
+ self,
1517
+ decomp_table: dict[torch._ops.OperatorBase, Callable] | None = None,
1518
+ decompose_custom_triton_ops: bool = False,
1519
+ ) -> "ExportedProgram":
1520
+ """
1521
+ Run a set of decompositions on the exported program and returns a new
1522
+ exported program. By default we will run the Core ATen decompositions to
1523
+ get operators in the
1524
+ `Core ATen Operator Set <https://pytorch.org/docs/stable/torch.compiler_ir.html>`_.
1525
+
1526
+ For now, we do not decompose joint graphs.
1527
+
1528
+ Args:
1529
+ decomp_table:
1530
+ An optional argument that specifies decomp behaviour for Aten ops
1531
+ (1) If None, we decompose to core aten decompositions
1532
+ (2) If empty, we don't decompose any operator
1533
+
1534
+
1535
+ Some examples:
1536
+
1537
+ If you don't want to decompose anything
1538
+
1539
+ .. code-block:: python
1540
+
1541
+ ep = torch.export.export(model, ...)
1542
+ ep = ep.run_decompositions(decomp_table={})
1543
+
1544
+ If you want to get a core aten operator set except for certain operator, you can do following:
1545
+
1546
+ .. code-block:: python
1547
+
1548
+ ep = torch.export.export(model, ...)
1549
+ decomp_table = torch.export.default_decompositions()
1550
+ decomp_table[your_op] = your_custom_decomp
1551
+ ep = ep.run_decompositions(decomp_table=decomp_table)
1552
+ """
1553
+ _decomp_table = (
1554
+ default_decompositions() if decomp_table is None else dict(decomp_table)
1555
+ )
1556
+
1557
+ if isinstance(_decomp_table, CustomDecompTable):
1558
+ _decomp_table = _decomp_table.materialize()
1559
+
1560
+ # Note [Separating decomp_table into CIA decomps and non-CIA decomps]
1561
+ # At this point, we have a decomp_table that contains decomp behaviour for
1562
+ # both CIA and post-autograd ops.
1563
+ # We need to separate the op into two categories:
1564
+ # 1. CIA op: These are the ops that we want to override
1565
+ # CompositeImplicitAutograd decomp for. For them, we need to use _override_composite_implicit_decomp
1566
+ # context manager to plumb it through AOTDispatcher
1567
+ # 2. Non-CIA op: These ops are only relevant after AOTDIspatcher runs, so just
1568
+ # checking if they are statically functional is enough.
1569
+ # For joint IR case tho, we need to use the old path because we can't register
1570
+ # custom decomps this way because we can't use context manager as it installs
1571
+ # autograd_error node.
1572
+ (
1573
+ cia_to_decomp,
1574
+ python_decomp_table,
1575
+ ) = _split_decomp_table_to_cia_and_python_decomp(_decomp_table)
1576
+
1577
+ return _decompose_exported_program(
1578
+ self,
1579
+ cia_to_decomp=cia_to_decomp,
1580
+ python_decomp_table=python_decomp_table,
1581
+ joint_loss_index=None,
1582
+ decompose_custom_triton_ops=decompose_custom_triton_ops,
1583
+ )
1584
+
1585
+ def _transform_do_not_use(self, *passes: PassType) -> "ExportedProgram":
1586
+ pm = PassManager(list(passes))
1587
+ # Since we abstractly run the passes, we need to disable backend decomp here
1588
+ # again.
1589
+ from torch.export._trace import _ignore_backend_decomps
1590
+
1591
+ with _ignore_backend_decomps():
1592
+ res = pm(self.graph_module)
1593
+ transformed_gm = res.graph_module if res is not None else self.graph_module
1594
+ if transformed_gm is None:
1595
+ raise AssertionError("transformed_gm must not be None")
1596
+
1597
+ # pyrefly: ignore [missing-attribute]
1598
+ if transformed_gm is self.graph_module and not res.modified:
1599
+ return self
1600
+
1601
+ # TODO(zhxchen17) Remove this.
1602
+ def _get_updated_graph_signature(
1603
+ old_signature: ExportGraphSignature,
1604
+ new_gm: torch.fx.GraphModule,
1605
+ ) -> ExportGraphSignature:
1606
+ """
1607
+ Update the graph signature's user_input/user_outputs.
1608
+ """
1609
+ new_input_specs = []
1610
+ for i, node in enumerate(new_gm.graph.nodes):
1611
+ if node.op != "placeholder":
1612
+ break
1613
+
1614
+ if i >= len(old_signature.input_specs):
1615
+ raise AssertionError(
1616
+ f"Number of inputs changed after transformation: got index {i} "
1617
+ f"but only {len(old_signature.input_specs)} input_specs"
1618
+ )
1619
+ old_input_spec = old_signature.input_specs[i]
1620
+ arg = (
1621
+ old_input_spec.arg
1622
+ if isinstance(
1623
+ old_input_spec.arg, (ConstantArgument, CustomObjArgument)
1624
+ )
1625
+ else type(old_input_spec.arg)(node.name)
1626
+ )
1627
+ new_input_specs.append(
1628
+ InputSpec(
1629
+ old_input_spec.kind,
1630
+ arg,
1631
+ old_input_spec.target,
1632
+ old_input_spec.persistent,
1633
+ )
1634
+ )
1635
+
1636
+ output_node = list(new_gm.graph.nodes)[-1]
1637
+ if output_node.op != "output":
1638
+ raise AssertionError(
1639
+ f"expected last node to have op='output', got {output_node.op!r}"
1640
+ )
1641
+
1642
+ new_output_specs = []
1643
+ for i, node in enumerate(output_node.args[0]):
1644
+ if i >= len(old_signature.output_specs):
1645
+ raise AssertionError(
1646
+ f"Number of outputs changed after transformation: got index {i} "
1647
+ f"but only {len(old_signature.output_specs)} output_specs"
1648
+ )
1649
+ old_output_spec = old_signature.output_specs[i]
1650
+ arg = (
1651
+ old_output_spec.arg
1652
+ if isinstance(
1653
+ old_output_spec.arg, (ConstantArgument, CustomObjArgument)
1654
+ )
1655
+ else type(old_output_spec.arg)(node.name)
1656
+ )
1657
+ new_output_specs.append(
1658
+ OutputSpec(old_output_spec.kind, arg, old_output_spec.target)
1659
+ )
1660
+
1661
+ new_signature = ExportGraphSignature(
1662
+ input_specs=new_input_specs, output_specs=new_output_specs
1663
+ )
1664
+ return new_signature
1665
+
1666
+ transformed_ep = ExportedProgram(
1667
+ root=transformed_gm,
1668
+ graph=transformed_gm.graph,
1669
+ graph_signature=_get_updated_graph_signature(
1670
+ self.graph_signature, transformed_gm
1671
+ ),
1672
+ state_dict=self.state_dict,
1673
+ range_constraints=_get_updated_range_constraints(
1674
+ transformed_gm,
1675
+ self.range_constraints,
1676
+ ),
1677
+ module_call_graph=copy.deepcopy(self._module_call_graph),
1678
+ example_inputs=self.example_inputs,
1679
+ constants=self.constants,
1680
+ verifiers=self.verifiers,
1681
+ )
1682
+ transformed_ep.graph_module.meta.update(self.graph_module.meta)
1683
+ # pyrefly: ignore [missing-attribute]
1684
+ transformed_ep.graph_module.meta.update(res.graph_module.meta)
1685
+ return transformed_ep
1686
+
1687
+ def _check_input_constraints(self, flat_args_with_path):
1688
+ from torch._export.utils import _check_input_constraints_for_graph
1689
+
1690
+ placeholders = [p for p in self.graph.nodes if p.op == "placeholder"]
1691
+ input_placeholders = [
1692
+ p
1693
+ for p, s in zip(placeholders, self.graph_signature.input_specs)
1694
+ if s.kind == InputKind.USER_INPUT
1695
+ ]
1696
+ _check_input_constraints_for_graph(
1697
+ input_placeholders, flat_args_with_path, self.range_constraints
1698
+ )
1699
+
1700
+ @compatibility(is_backward_compatible=False)
1701
+ def validate(self):
1702
+ self._validate()
1703
+
1704
+ # TODO: remove this
1705
+ @final
1706
+ def _validate(self):
1707
+ if len(self.verifiers) == 0:
1708
+ raise AssertionError("ExportedProgram must have at least one verifier.")
1709
+ for v in self.verifiers:
1710
+ v().check(self)
1711
+
1712
+ # TODO(zhxchen17) Formalize this.
1713
+ def _update(
1714
+ self,
1715
+ graph_module,
1716
+ graph_signature,
1717
+ *,
1718
+ state_dict=None,
1719
+ constants=None,
1720
+ verifiers=None,
1721
+ ) -> "ExportedProgram":
1722
+ return ExportedProgram(
1723
+ root=graph_module,
1724
+ graph=graph_module.graph,
1725
+ graph_signature=graph_signature,
1726
+ state_dict=state_dict if state_dict is not None else self.state_dict,
1727
+ range_constraints=copy.deepcopy(self.range_constraints),
1728
+ module_call_graph=copy.deepcopy(self._module_call_graph),
1729
+ example_inputs=self.example_inputs,
1730
+ constants=constants if constants is not None else self.constants,
1731
+ verifiers=verifiers if verifiers is not None else self.verifiers,
1732
+ )
1733
+
1734
+
1735
+ def _get_shape_env(gm):
1736
+ vals = [
1737
+ node.meta["val"]
1738
+ for node in gm.graph.nodes
1739
+ if node.meta.get("val", None) is not None
1740
+ ]
1741
+ from torch._guards import detect_fake_mode
1742
+
1743
+ fake_mode = detect_fake_mode(vals)
1744
+ if fake_mode is not None:
1745
+ return fake_mode.shape_env
1746
+ for v in vals:
1747
+ if isinstance(v, torch.SymInt):
1748
+ return v.node.shape_env
1749
+
1750
+
1751
+ def _get_updated_range_constraints(
1752
+ gm: torch.fx.GraphModule,
1753
+ old_range_constraints: "dict[sympy.Symbol, Any] | None" = None,
1754
+ ) -> "dict[sympy.Symbol, Any]":
1755
+ if old_range_constraints is None:
1756
+ raise AssertionError("old_range_constraints must not be None")
1757
+
1758
+ shape_env = _get_shape_env(gm)
1759
+ if shape_env is None:
1760
+ return {}
1761
+
1762
+ range_constraints = copy.copy(old_range_constraints)
1763
+ range_constraints = {
1764
+ k: v for k, v in range_constraints.items() if k not in shape_env.replacements
1765
+ }
1766
+ # Only when we have an unbacked symint, and it's used as constructor inputs,
1767
+ # runtime_var_to_range will make a difference compated to var_to_range.
1768
+ # e.g. [2, oo) -> [0, oo)
1769
+ for k, v in shape_env.var_to_range.items():
1770
+ if k not in shape_env.replacements and k not in range_constraints:
1771
+ range_constraints[k] = v
1772
+ return range_constraints
1773
+
1774
+
1775
+ def _create_graph_module_for_export(root, graph):
1776
+ try:
1777
+ gm = torch.fx.GraphModule(root, graph)
1778
+ except SyntaxError:
1779
+ # If custom objects stored in memory are being used in the graph,
1780
+ # the generated python code will result in a syntax error on the custom
1781
+ # object, since it is unable to parse the in-memory object. However
1782
+ # we can still run the graph eagerly through torch.fx.Interpreter,
1783
+ # so we will bypass this error.
1784
+ warnings.warn(
1785
+ "Unable to execute the generated python source code from "
1786
+ "the graph. The graph module will no longer be directly callable, "
1787
+ "but you can still run the ExportedProgram, and if needed, you can "
1788
+ "run the graph module eagerly using torch.fx.Interpreter.",
1789
+ stacklevel=2,
1790
+ )
1791
+ gm = torch.fx.GraphModule(root, torch.fx.Graph())
1792
+ gm._graph = graph
1793
+
1794
+ return gm
1795
+
1796
+
1797
+ def _convert_guards_to_code(graph_module):
1798
+ shape_env = _get_shape_env(graph_module)
1799
+ if shape_env is None:
1800
+ return []
1801
+
1802
+ local_vars = {
1803
+ var
1804
+ for var, sources in shape_env.var_to_sources.items()
1805
+ if all(
1806
+ not isinstance(source, torch._dynamo.source.ConstantSource)
1807
+ for source in sources
1808
+ )
1809
+ }
1810
+ py_printer = torch.fx.experimental.symbolic_shapes.ShapeGuardPythonPrinter(
1811
+ shape_env.var_to_sources, lambda s: s.name, shape_env.var_to_sources
1812
+ )
1813
+ ret = [
1814
+ py_printer.doprint(guard.expr)
1815
+ for guard in shape_env.guards
1816
+ if guard.expr.free_symbols.issubset(local_vars)
1817
+ ]
1818
+ # TODO Figure out how to resolve guards containing weight sizes.
1819
+ # This is not a big deal as _guards_code is mostly empty today.
1820
+ return [guard for guard in ret if "L['self']" not in guard]
.venv/lib/python3.12/site-packages/torch/export/graph_signature.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ from collections.abc import Collection, Mapping
4
+ from enum import auto, Enum
5
+ from typing import TYPE_CHECKING
6
+
7
+ from torch._library.fake_class_registry import FakeScriptObject
8
+ from torch._library.opaque_object import get_opaque_type_name, is_custom_class
9
+ from torch._subclasses.fake_tensor import is_fake
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ import torch
14
+ from torch._functorch._aot_autograd.schemas import GraphSignature
15
+
16
+ __all__ = [
17
+ "ConstantArgument",
18
+ "CustomObjArgument",
19
+ "ExportBackwardSignature",
20
+ "ExportGraphSignature",
21
+ "InputKind",
22
+ "InputSpec",
23
+ "OutputKind",
24
+ "OutputSpec",
25
+ "SymIntArgument",
26
+ "SymFloatArgument",
27
+ "SymBoolArgument",
28
+ "TensorArgument",
29
+ ]
30
+
31
+
32
+ @dataclasses.dataclass
33
+ class TensorArgument:
34
+ name: str
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class TokenArgument:
39
+ name: str
40
+
41
+
42
+ @dataclasses.dataclass
43
+ class SymIntArgument:
44
+ name: str
45
+
46
+
47
+ @dataclasses.dataclass
48
+ class SymFloatArgument:
49
+ name: str
50
+
51
+
52
+ @dataclasses.dataclass
53
+ class SymBoolArgument:
54
+ name: str
55
+
56
+
57
+ @dataclasses.dataclass
58
+ class CustomObjArgument:
59
+ name: str
60
+ class_fqn: str
61
+ fake_val: FakeScriptObject | None = None
62
+
63
+
64
+ @dataclasses.dataclass
65
+ class ConstantArgument:
66
+ name: str
67
+ value: int | float | bool | str | None
68
+
69
+
70
+ ArgumentSpec = (
71
+ TensorArgument
72
+ | SymIntArgument
73
+ | SymFloatArgument
74
+ | SymBoolArgument
75
+ | ConstantArgument
76
+ | CustomObjArgument
77
+ | TokenArgument
78
+ )
79
+
80
+
81
+ class InputKind(Enum):
82
+ USER_INPUT = auto()
83
+ PARAMETER = auto()
84
+ BUFFER = auto()
85
+ CONSTANT_TENSOR = auto()
86
+ CUSTOM_OBJ = auto()
87
+ TOKEN = auto()
88
+
89
+
90
+ @dataclasses.dataclass
91
+ class InputSpec:
92
+ kind: InputKind
93
+ arg: ArgumentSpec
94
+ target: str | None
95
+ persistent: bool | None = None
96
+
97
+ def __post_init__(self):
98
+ if self.kind == InputKind.BUFFER:
99
+ if self.persistent is None:
100
+ raise AssertionError("Failed to specify persistent flag on BUFFER.")
101
+ if not isinstance(
102
+ self.arg,
103
+ (
104
+ TensorArgument,
105
+ SymIntArgument,
106
+ SymFloatArgument,
107
+ SymBoolArgument,
108
+ ConstantArgument,
109
+ CustomObjArgument,
110
+ TokenArgument,
111
+ ),
112
+ ):
113
+ raise AssertionError(f"expected valid arg type, got {type(self.arg)}")
114
+
115
+ def __str__(self):
116
+ target = "" if self.target is None else f" target='{self.target}'"
117
+ persistent = "" if self.persistent is None else f" persistent={self.persistent}"
118
+ return f"{str(self.arg.name)}: {str(self.kind.name)}{target}{persistent}"
119
+
120
+
121
+ class OutputKind(Enum):
122
+ USER_OUTPUT = auto()
123
+ LOSS_OUTPUT = auto()
124
+ BUFFER_MUTATION = auto()
125
+ PARAMETER_MUTATION = auto()
126
+ GRADIENT_TO_PARAMETER = auto()
127
+ GRADIENT_TO_USER_INPUT = auto()
128
+ USER_INPUT_MUTATION = auto()
129
+ TOKEN = auto()
130
+
131
+
132
+ @dataclasses.dataclass
133
+ class OutputSpec:
134
+ kind: OutputKind
135
+ arg: ArgumentSpec
136
+ target: str | None
137
+
138
+ def __post_init__(self):
139
+ if not isinstance(
140
+ self.arg,
141
+ (
142
+ TensorArgument,
143
+ SymIntArgument,
144
+ SymFloatArgument,
145
+ SymBoolArgument,
146
+ ConstantArgument,
147
+ TokenArgument,
148
+ CustomObjArgument,
149
+ ),
150
+ ):
151
+ raise AssertionError(f"expected valid arg type, got {self.arg}")
152
+
153
+ def __str__(self):
154
+ target = "" if self.target is None else f" target='{self.target}'"
155
+ return f"{str(self.arg.name)}: {str(self.kind.name)}{target}"
156
+
157
+
158
+ @dataclasses.dataclass
159
+ class ExportBackwardSignature:
160
+ gradients_to_parameters: dict[str, str]
161
+ gradients_to_user_inputs: dict[str, str]
162
+ loss_output: str
163
+
164
+
165
+ @dataclasses.dataclass
166
+ class ExportGraphSignature:
167
+ """
168
+ :class:`ExportGraphSignature` models the input/output signature of Export Graph,
169
+ which is a fx.Graph with stronger invariants guarantees.
170
+
171
+ Export Graph is functional and does not access "states" like parameters
172
+ or buffers within the graph via ``getattr`` nodes. Instead, :func:`export`
173
+ guarantees that parameters, buffers, and constant tensors are lifted out of
174
+ the graph as inputs. Similarly, any mutations to buffers are not included
175
+ in the graph either, instead the updated values of mutated buffers are
176
+ modeled as additional outputs of Export Graph.
177
+
178
+ The ordering of all inputs and outputs are::
179
+
180
+ Inputs = [*parameters_buffers_constant_tensors, *flattened_user_inputs]
181
+ Outputs = [*mutated_inputs, *flattened_user_outputs]
182
+
183
+ e.g. If following module is exported::
184
+
185
+ class CustomModule(nn.Module):
186
+ def __init__(self) -> None:
187
+ super(CustomModule, self).__init__()
188
+
189
+ # Define a parameter
190
+ self.my_parameter = nn.Parameter(torch.tensor(2.0))
191
+
192
+ # Define two buffers
193
+ self.register_buffer("my_buffer1", torch.tensor(3.0))
194
+ self.register_buffer("my_buffer2", torch.tensor(4.0))
195
+
196
+ def forward(self, x1, x2):
197
+ # Use the parameter, buffers, and both inputs in the forward method
198
+ output = (
199
+ x1 + self.my_parameter
200
+ ) * self.my_buffer1 + x2 * self.my_buffer2
201
+
202
+ # Mutate one of the buffers (e.g., increment it by 1)
203
+ self.my_buffer2.add_(1.0) # In-place addition
204
+
205
+ return output
206
+
207
+
208
+ mod = CustomModule()
209
+ ep = torch.export.export(mod, (torch.tensor(1.0), torch.tensor(2.0)))
210
+
211
+ Resulting Graph is non-functional::
212
+
213
+ graph():
214
+ %p_my_parameter : [num_users=1] = placeholder[target=p_my_parameter]
215
+ %b_my_buffer1 : [num_users=1] = placeholder[target=b_my_buffer1]
216
+ %b_my_buffer2 : [num_users=2] = placeholder[target=b_my_buffer2]
217
+ %x1 : [num_users=1] = placeholder[target=x1]
218
+ %x2 : [num_users=1] = placeholder[target=x2]
219
+ %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%x1, %p_my_parameter), kwargs = {})
220
+ %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add, %b_my_buffer1), kwargs = {})
221
+ %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%x2, %b_my_buffer2), kwargs = {})
222
+ %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul, %mul_1), kwargs = {})
223
+ %add_ : [num_users=0] = call_function[target=torch.ops.aten.add_.Tensor](args = (%b_my_buffer2, 1.0), kwargs = {})
224
+ return (add_1,)
225
+
226
+ Resulting ExportGraphSignature of the non-functional Graph would be::
227
+
228
+ # inputs
229
+ p_my_parameter: PARAMETER target='my_parameter'
230
+ b_my_buffer1: BUFFER target='my_buffer1' persistent=True
231
+ b_my_buffer2: BUFFER target='my_buffer2' persistent=True
232
+ x1: USER_INPUT
233
+ x2: USER_INPUT
234
+
235
+ # outputs
236
+ add_1: USER_OUTPUT
237
+
238
+ To get a functional Graph, you can use :func:`run_decompositions`::
239
+
240
+ mod = CustomModule()
241
+ ep = torch.export.export(mod, (torch.tensor(1.0), torch.tensor(2.0)))
242
+ ep = ep.run_decompositions()
243
+
244
+ Resulting Graph is functional::
245
+
246
+ graph():
247
+ %p_my_parameter : [num_users=1] = placeholder[target=p_my_parameter]
248
+ %b_my_buffer1 : [num_users=1] = placeholder[target=b_my_buffer1]
249
+ %b_my_buffer2 : [num_users=2] = placeholder[target=b_my_buffer2]
250
+ %x1 : [num_users=1] = placeholder[target=x1]
251
+ %x2 : [num_users=1] = placeholder[target=x2]
252
+ %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%x1, %p_my_parameter), kwargs = {})
253
+ %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add, %b_my_buffer1), kwargs = {})
254
+ %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%x2, %b_my_buffer2), kwargs = {})
255
+ %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul, %mul_1), kwargs = {})
256
+ %add_2 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%b_my_buffer2, 1.0), kwargs = {})
257
+ return (add_2, add_1)
258
+
259
+ Resulting ExportGraphSignature of the functional Graph would be::
260
+
261
+ # inputs
262
+ p_my_parameter: PARAMETER target='my_parameter'
263
+ b_my_buffer1: BUFFER target='my_buffer1' persistent=True
264
+ b_my_buffer2: BUFFER target='my_buffer2' persistent=True
265
+ x1: USER_INPUT
266
+ x2: USER_INPUT
267
+
268
+ # outputs
269
+ add_2: BUFFER_MUTATION target='my_buffer2'
270
+ add_1: USER_OUTPUT
271
+
272
+ """
273
+
274
+ input_specs: list[InputSpec]
275
+ output_specs: list[OutputSpec]
276
+
277
+ # A list of parameters uniquely identified by mangled fully qualified name
278
+ @property
279
+ def parameters(self) -> Collection[str]:
280
+ return tuple(
281
+ s.target
282
+ for s in self.input_specs
283
+ if s.kind == InputKind.PARAMETER
284
+ if isinstance(s.target, str)
285
+ )
286
+
287
+ # A list of buffers uniquely identified by mangled fully qualified name
288
+ @property
289
+ def buffers(self) -> Collection[str]:
290
+ return tuple(
291
+ s.target
292
+ for s in self.input_specs
293
+ if s.kind == InputKind.BUFFER
294
+ if isinstance(s.target, str)
295
+ )
296
+
297
+ @property
298
+ def non_persistent_buffers(self) -> Collection[str]:
299
+ return tuple(
300
+ s.target
301
+ for s in self.input_specs
302
+ if s.kind == InputKind.BUFFER
303
+ if s.persistent is False
304
+ if isinstance(s.target, str)
305
+ )
306
+
307
+ # A list of lifted constant tensors
308
+ @property
309
+ def lifted_tensor_constants(self) -> Collection[str]:
310
+ return tuple(
311
+ s.target
312
+ for s in self.input_specs
313
+ if s.kind == InputKind.CONSTANT_TENSOR
314
+ if isinstance(s.target, str)
315
+ )
316
+
317
+ @property
318
+ def lifted_custom_objs(self) -> Collection[str]:
319
+ return tuple(
320
+ s.target
321
+ for s in self.input_specs
322
+ if s.kind == InputKind.CUSTOM_OBJ
323
+ if isinstance(s.target, str)
324
+ )
325
+
326
+ # Graph node names of pytree-flattened inputs of original program
327
+ @property
328
+ def user_inputs(self) -> Collection[int | float | bool | str | None]:
329
+ user_inputs: list[int | float | bool | str | None] = []
330
+ for s in self.input_specs:
331
+ if s.kind != InputKind.USER_INPUT:
332
+ continue
333
+
334
+ if isinstance(
335
+ s.arg,
336
+ (
337
+ TensorArgument,
338
+ SymIntArgument,
339
+ SymFloatArgument,
340
+ SymBoolArgument,
341
+ CustomObjArgument,
342
+ ),
343
+ ):
344
+ user_inputs.append(s.arg.name)
345
+ elif isinstance(s.arg, ConstantArgument):
346
+ user_inputs.append(s.arg.value)
347
+ else:
348
+ raise RuntimeError(f"{s.arg} is not a valid user input")
349
+ return tuple(user_inputs)
350
+
351
+ # Graph node names of pytree-flattened outputs of original program
352
+ # For joint-graph purposes, will include the loss output.
353
+ @property
354
+ def user_outputs(self) -> Collection[int | float | bool | str | None]:
355
+ user_outputs: list[int | float | bool | str | None] = []
356
+ for s in self.output_specs:
357
+ if s.kind not in [
358
+ OutputKind.USER_OUTPUT,
359
+ OutputKind.LOSS_OUTPUT,
360
+ ]:
361
+ continue
362
+
363
+ if isinstance(
364
+ s.arg,
365
+ (TensorArgument, SymIntArgument, SymFloatArgument, SymBoolArgument),
366
+ ):
367
+ user_outputs.append(s.arg.name)
368
+ elif isinstance(s.arg, ConstantArgument):
369
+ user_outputs.append(s.arg.value)
370
+ elif isinstance(s.arg, CustomObjArgument):
371
+ user_outputs.append(s.arg.name)
372
+ else:
373
+ raise RuntimeError(f"{s.arg} is not a valid user output")
374
+ return tuple(user_outputs)
375
+
376
+ # A dictionary mapping graph input node names to parameters. If a graph input
377
+ # name is found in this dictionary, it is guaranteed to be a lifted parameter.
378
+ @property
379
+ def inputs_to_parameters(self) -> Mapping[str, str]:
380
+ return _immutable_dict(
381
+ (s.arg.name, s.target)
382
+ for s in self.input_specs
383
+ if s.kind == InputKind.PARAMETER
384
+ and isinstance(s.arg, TensorArgument)
385
+ and isinstance(s.target, str)
386
+ )
387
+
388
+ # A dictionary mapping graph input node names to buffers. If a graph input
389
+ # name is found in this dictionary, it is guaranteed to be a lifted buffer.
390
+ @property
391
+ def inputs_to_buffers(self) -> Mapping[str, str]:
392
+ return _immutable_dict(
393
+ (s.arg.name, s.target) # type: ignore[union-attr, misc]
394
+ for s in self.input_specs
395
+ if s.kind == InputKind.BUFFER
396
+ and isinstance(s.arg, TensorArgument)
397
+ and isinstance(s.target, str)
398
+ )
399
+
400
+ # A dictionary mapping graph output node names to buffers that are mutated in the
401
+ # original program. Buffers that are not mutated will not be found in this dictionary.
402
+ @property
403
+ def buffers_to_mutate(self) -> Mapping[str, str]:
404
+ return _immutable_dict(
405
+ (s.arg.name, s.target)
406
+ for s in self.output_specs
407
+ if s.kind == OutputKind.BUFFER_MUTATION
408
+ and isinstance(s.arg, TensorArgument)
409
+ and isinstance(s.target, str)
410
+ )
411
+
412
+ @property
413
+ def parameters_to_mutate(self) -> Mapping[str, str]:
414
+ return _immutable_dict(
415
+ (s.arg.name, s.target)
416
+ for s in self.output_specs
417
+ if s.kind == OutputKind.PARAMETER_MUTATION
418
+ and isinstance(s.arg, TensorArgument)
419
+ and isinstance(s.target, str)
420
+ )
421
+
422
+ @property
423
+ def user_inputs_to_mutate(self) -> Mapping[str, str]:
424
+ return _immutable_dict(
425
+ (s.arg.name, s.target)
426
+ for s in self.output_specs
427
+ if s.kind == OutputKind.USER_INPUT_MUTATION
428
+ and isinstance(s.arg, TensorArgument)
429
+ and isinstance(s.target, str)
430
+ )
431
+
432
+ # A dictionary mapping graph input node names to lifted tensor constants.
433
+ @property
434
+ def inputs_to_lifted_tensor_constants(self) -> Mapping[str, str]:
435
+ return _immutable_dict(
436
+ (s.arg.name, s.target)
437
+ for s in self.input_specs
438
+ if s.kind == InputKind.CONSTANT_TENSOR
439
+ and isinstance(s.arg, TensorArgument)
440
+ and isinstance(s.target, str)
441
+ )
442
+
443
+ @property
444
+ def inputs_to_lifted_custom_objs(self) -> Mapping[str, str]:
445
+ return _immutable_dict(
446
+ (s.arg.name, s.target)
447
+ for s in self.input_specs
448
+ if s.kind == InputKind.CUSTOM_OBJ
449
+ and isinstance(s.arg, CustomObjArgument)
450
+ and isinstance(s.target, str)
451
+ )
452
+
453
+ @property
454
+ def backward_signature(self) -> ExportBackwardSignature | None:
455
+ loss_output = None
456
+ gradients_to_parameters: dict[str, str] = {}
457
+ gradients_to_user_inputs: dict[str, str] = {}
458
+ for spec in self.output_specs:
459
+ if spec.kind == OutputKind.LOSS_OUTPUT:
460
+ if loss_output is not None:
461
+ raise AssertionError("multiple LOSS_OUTPUT specs found")
462
+ if not isinstance(spec.arg, TensorArgument):
463
+ raise AssertionError(
464
+ f"expected TensorArgument for LOSS_OUTPUT, got {type(spec.arg)}"
465
+ )
466
+ loss_output = spec.arg.name
467
+ elif spec.kind == OutputKind.GRADIENT_TO_PARAMETER:
468
+ if not isinstance(spec.target, str):
469
+ raise AssertionError(
470
+ f"expected str target for GRADIENT_TO_PARAMETER, got {type(spec.target)}"
471
+ )
472
+ if not isinstance(spec.arg, TensorArgument):
473
+ raise AssertionError(
474
+ f"expected TensorArgument for GRADIENT_TO_PARAMETER, got {type(spec.arg)}"
475
+ )
476
+ gradients_to_parameters[spec.arg.name] = spec.target
477
+ elif spec.kind == OutputKind.GRADIENT_TO_USER_INPUT:
478
+ if not isinstance(spec.target, str):
479
+ raise AssertionError(
480
+ f"expected str target for GRADIENT_TO_USER_INPUT, got {type(spec.target)}"
481
+ )
482
+ if not isinstance(spec.arg, TensorArgument):
483
+ raise AssertionError(
484
+ f"expected TensorArgument for GRADIENT_TO_USER_INPUT, got {type(spec.arg)}"
485
+ )
486
+ gradients_to_user_inputs[spec.arg.name] = spec.target
487
+
488
+ if loss_output is None:
489
+ return None
490
+
491
+ return ExportBackwardSignature(
492
+ loss_output=loss_output,
493
+ gradients_to_parameters=gradients_to_parameters,
494
+ gradients_to_user_inputs=gradients_to_user_inputs,
495
+ )
496
+
497
+ # Map from assertion dependency token index to assertion dep token output
498
+ # name in output. The shape of output after aot_autograd will be like:
499
+ # (updated_inputs, user_outputs, dep_token).
500
+ @property
501
+ def assertion_dep_token(self) -> Mapping[int, str] | None:
502
+ return None
503
+
504
+ @property
505
+ def input_tokens(self) -> Collection[str]:
506
+ input_tokens = []
507
+ for s in self.input_specs:
508
+ if s.kind == InputKind.TOKEN:
509
+ if not isinstance(s.arg, TokenArgument):
510
+ raise AssertionError(
511
+ f"expected TokenArgument for TOKEN kind, got {type(s.arg)}"
512
+ )
513
+ input_tokens.append(s.arg.name)
514
+ return tuple(input_tokens)
515
+
516
+ @property
517
+ def output_tokens(self) -> Collection[str]:
518
+ output_tokens = []
519
+ for s in self.output_specs:
520
+ if s.kind == OutputKind.TOKEN:
521
+ if not isinstance(s.arg, TokenArgument):
522
+ raise AssertionError(
523
+ f"expected TokenArgument for TOKEN kind, got {type(s.arg)}"
524
+ )
525
+ output_tokens.append(s.arg.name)
526
+ return tuple(output_tokens)
527
+
528
+ def __post_init__(self) -> None:
529
+ assertion_dep_token = self.assertion_dep_token
530
+ if assertion_dep_token is None:
531
+ return
532
+ if len(assertion_dep_token) != 1:
533
+ raise AssertionError(
534
+ f"expected exactly 1 assertion_dep_token, got {len(assertion_dep_token)}"
535
+ )
536
+ assertion_dep_token_index = next(iter(assertion_dep_token.keys()))
537
+ expected_index = len(self.user_outputs) + len(self.buffers_to_mutate)
538
+ if expected_index != assertion_dep_token_index:
539
+ raise AssertionError(
540
+ f"expected assertion_dep_token_index to be {expected_index}, got {assertion_dep_token_index}"
541
+ )
542
+
543
+ def replace_all_uses(self, old: str, new: str):
544
+ """
545
+ Replace all uses of the old name with new name in the signature.
546
+ """
547
+ if not isinstance(old, str):
548
+ raise AssertionError(f"expected old to be str, got {type(old)}")
549
+ if not isinstance(new, str):
550
+ raise AssertionError(f"expected new to be str, got {type(new)}")
551
+ arg_types = (
552
+ TensorArgument,
553
+ SymIntArgument,
554
+ SymFloatArgument,
555
+ SymBoolArgument,
556
+ CustomObjArgument,
557
+ TokenArgument,
558
+ )
559
+ for o in self.output_specs:
560
+ if isinstance(o.arg, arg_types):
561
+ if o.arg.name == old:
562
+ o.arg.name = new
563
+ for i in self.input_specs:
564
+ if isinstance(i.arg, arg_types):
565
+ if i.arg.name == old:
566
+ i.arg.name = new
567
+
568
+ def get_replace_hook(self, replace_inputs=False):
569
+ def _(old, new, user):
570
+ if user.op == "output":
571
+ self.replace_all_uses(old.name, new)
572
+ if replace_inputs and old.op == "placeholder":
573
+ self.replace_all_uses(old.name, new)
574
+
575
+ return _
576
+
577
+ def __str__(self):
578
+ input_specs = "\n".join(str(s) for s in self.input_specs)
579
+ output_specs = "\n".join(str(s) for s in self.output_specs)
580
+ return f"\n# inputs\n{input_specs}\n\n# outputs\n{output_specs}\n"
581
+
582
+
583
+ def _immutable_dict(items):
584
+ """
585
+ Creates a mapping where items cannot be added, deleted, or updated.
586
+ NOTE: The immutability is shallow (like tuple is an immutable collection).
587
+ """
588
+ from types import MappingProxyType
589
+
590
+ return MappingProxyType(dict(items))
591
+
592
+
593
+ def _make_argument_spec(node, token_names) -> ArgumentSpec:
594
+ from torch import ScriptObject, SymBool, SymFloat, SymInt
595
+ from torch._library.fake_class_registry import FakeScriptObject
596
+
597
+ if isinstance(node, (int, bool, float, type(None), str)):
598
+ # For const outputs we just directly return this
599
+ return ConstantArgument(name="", value=node)
600
+
601
+ if "val" not in node.meta:
602
+ raise AssertionError(
603
+ f"{node} is not a constant or a node with a 'val' metadata field"
604
+ )
605
+ val = node.meta["val"]
606
+ if node.name in token_names:
607
+ return TokenArgument(name=node.name)
608
+ elif is_fake(val):
609
+ return TensorArgument(name=node.name)
610
+ elif isinstance(val, SymInt):
611
+ return SymIntArgument(name=node.name)
612
+ elif isinstance(val, SymFloat):
613
+ return SymFloatArgument(name=node.name)
614
+ elif isinstance(val, SymBool):
615
+ return SymBoolArgument(name=node.name)
616
+ elif isinstance(val, ScriptObject):
617
+ return CustomObjArgument(name=node.name, class_fqn=val._type().qualified_name()) # type: ignore[attr-defined]
618
+ elif isinstance(val, FakeScriptObject):
619
+ return CustomObjArgument(
620
+ name=node.name, class_fqn=val.script_class_name, fake_val=val
621
+ )
622
+ elif is_custom_class(type(val)):
623
+ return CustomObjArgument(
624
+ name=node.name, class_fqn=get_opaque_type_name(type(val)), fake_val=val
625
+ )
626
+ elif isinstance(val, (int, bool, str, float, type(None))):
627
+ return ConstantArgument(name=node.name, value=val)
628
+ else:
629
+ raise AssertionError(
630
+ f"Encountered an unsupported object of type {type(val)} "
631
+ f"while writing the metadata for exported program"
632
+ )
633
+
634
+
635
+ def _convert_to_export_graph_signature(
636
+ graph_signature: "GraphSignature",
637
+ gm: "torch.fx.GraphModule",
638
+ non_persistent_buffers: set[str],
639
+ ) -> "ExportGraphSignature":
640
+ from torch.utils import _pytree as pytree
641
+
642
+ is_joint = graph_signature.backward_signature is not None
643
+
644
+ # unpack objects
645
+ user_inputs = set(graph_signature.user_inputs)
646
+ inputs_to_parameters = graph_signature.inputs_to_parameters
647
+ inputs_to_buffers = graph_signature.inputs_to_buffers
648
+ user_outputs = set(graph_signature.user_outputs)
649
+ buffer_mutations = graph_signature.buffers_to_mutate
650
+ parameter_mutations = graph_signature.parameters_to_mutate
651
+ user_input_mutations = graph_signature.user_inputs_to_mutate
652
+ grad_params = (
653
+ graph_signature.backward_signature.gradients_to_parameter # type: ignore[union-attr]
654
+ if is_joint
655
+ else {}
656
+ )
657
+ grad_user_inputs = (
658
+ graph_signature.backward_signature.gradients_to_user_inputs # type: ignore[union-attr]
659
+ if is_joint
660
+ else {}
661
+ )
662
+ loss_output = (
663
+ graph_signature.backward_signature.loss_output # type: ignore[union-attr]
664
+ if is_joint
665
+ else None
666
+ )
667
+ input_tokens = graph_signature.input_tokens
668
+ output_tokens = graph_signature.output_tokens
669
+
670
+ inputs = [
671
+ _make_argument_spec(node, input_tokens)
672
+ for node in gm.graph.nodes
673
+ if node.op == "placeholder"
674
+ ]
675
+ outputs = [
676
+ _make_argument_spec(node, output_tokens)
677
+ for node in pytree.tree_leaves(next(iter(reversed(gm.graph.nodes))).args)
678
+ ]
679
+
680
+ def to_input_spec(inp: ArgumentSpec) -> InputSpec:
681
+ if isinstance(inp, TokenArgument):
682
+ return InputSpec(kind=InputKind.TOKEN, arg=inp, target=None)
683
+
684
+ if not isinstance(inp, TensorArgument):
685
+ return InputSpec(kind=InputKind.USER_INPUT, arg=inp, target=None)
686
+ name = inp.name
687
+ if name in user_inputs:
688
+ return InputSpec(kind=InputKind.USER_INPUT, arg=inp, target=None)
689
+ elif name in inputs_to_parameters:
690
+ return InputSpec(
691
+ kind=InputKind.PARAMETER,
692
+ arg=inp,
693
+ target=inputs_to_parameters[name], # type: ignore[index]
694
+ )
695
+ elif name in inputs_to_buffers:
696
+ return InputSpec(
697
+ kind=InputKind.BUFFER,
698
+ arg=inp,
699
+ target=inputs_to_buffers[name], # type: ignore[index]
700
+ persistent=(inputs_to_buffers[name] not in non_persistent_buffers), # type: ignore[index]
701
+ )
702
+ else:
703
+ raise AssertionError(f"Unknown tensor input kind: {name}")
704
+
705
+ def to_output_spec(idx: int, o: ArgumentSpec) -> OutputSpec:
706
+ if isinstance(o, TokenArgument):
707
+ return OutputSpec(kind=OutputKind.TOKEN, arg=o, target=None)
708
+
709
+ if not isinstance(o, TensorArgument):
710
+ return OutputSpec(kind=OutputKind.USER_OUTPUT, arg=o, target=None)
711
+ name = o.name
712
+ if idx < len(buffer_mutations) + len(parameter_mutations) + len(
713
+ user_input_mutations
714
+ ) + len(output_tokens):
715
+ if name in buffer_mutations:
716
+ return OutputSpec(
717
+ kind=OutputKind.BUFFER_MUTATION,
718
+ arg=o,
719
+ target=buffer_mutations[name], # type: ignore[index]
720
+ )
721
+ elif name in parameter_mutations:
722
+ return OutputSpec(
723
+ kind=OutputKind.PARAMETER_MUTATION,
724
+ arg=o,
725
+ target=parameter_mutations[name], # type: ignore[index]
726
+ )
727
+ elif name in user_input_mutations:
728
+ return OutputSpec(
729
+ kind=OutputKind.USER_INPUT_MUTATION,
730
+ arg=o,
731
+ target=user_input_mutations[name], # type: ignore[index]
732
+ )
733
+ else:
734
+ raise AssertionError(f"Unknown tensor mutation kind: {name}")
735
+ else:
736
+ if name in user_outputs:
737
+ return OutputSpec(kind=OutputKind.USER_OUTPUT, arg=o, target=None)
738
+
739
+ elif name in grad_params:
740
+ return OutputSpec(
741
+ kind=OutputKind.GRADIENT_TO_PARAMETER,
742
+ arg=o,
743
+ target=grad_params[name],
744
+ )
745
+ elif name in grad_user_inputs:
746
+ return OutputSpec(
747
+ kind=OutputKind.GRADIENT_TO_USER_INPUT,
748
+ arg=o,
749
+ target=grad_user_inputs[name],
750
+ )
751
+ elif name == loss_output:
752
+ return OutputSpec(kind=OutputKind.LOSS_OUTPUT, arg=o, target=None)
753
+
754
+ else:
755
+ raise AssertionError(f"Unknown tensor output kind: {name}")
756
+
757
+ input_specs = [to_input_spec(inp) for inp in inputs]
758
+ output_specs = [to_output_spec(idx, o) for idx, o in enumerate(outputs)]
759
+ return ExportGraphSignature(input_specs=input_specs, output_specs=output_specs)
.venv/lib/python3.12/site-packages/torch/export/passes/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch
4
+ import torch.utils._pytree as pytree
5
+ from torch.export.exported_program import ExportedProgram
6
+
7
+
8
+ __all__ = ["move_to_device_pass"]
9
+
10
+
11
+ def move_to_device_pass(
12
+ ep: ExportedProgram, location: torch.device | str | dict[str, str]
13
+ ) -> ExportedProgram:
14
+ """
15
+ Move the exported program to the given device.
16
+
17
+ Args:
18
+ ep (ExportedProgram): The exported program to move.
19
+ location (Union[torch.device, str, Dict[str, str]]): The device to move the exported program to.
20
+ If a string, it is interpreted as a device name.
21
+ If a dict, it is interpreted as a mapping from
22
+ the existing device to the intended one
23
+
24
+ Returns:
25
+ ExportedProgram: The moved exported program.
26
+ """
27
+
28
+ def _get_new_device(
29
+ curr_device: torch.device,
30
+ location: torch.device | str | dict[str, str],
31
+ ) -> str:
32
+ if isinstance(location, dict):
33
+ if str(curr_device) in location:
34
+ return location[str(curr_device)]
35
+ else:
36
+ return str(curr_device)
37
+ else:
38
+ return str(location)
39
+
40
+ # move all the state_dict
41
+ for k, v in ep.state_dict.items():
42
+ if isinstance(v, torch.nn.Parameter):
43
+ ep._state_dict[k] = torch.nn.Parameter(
44
+ v.to(_get_new_device(v.device, location)),
45
+ v.requires_grad,
46
+ )
47
+ else:
48
+ ep._state_dict[k] = v.to(_get_new_device(v.device, location))
49
+
50
+ # move all the constants
51
+ for k, v in ep.constants.items():
52
+ if isinstance(v, torch.Tensor):
53
+ ep._constants[k] = v.to(_get_new_device(v.device, location))
54
+
55
+ # move example_inputs if they exist
56
+ if ep.example_inputs is not None:
57
+ args, kwargs = ep.example_inputs
58
+ moved_args = pytree.tree_map_only(
59
+ torch.Tensor,
60
+ lambda tensor: tensor.to(_get_new_device(tensor.device, location)),
61
+ args,
62
+ )
63
+ moved_kwargs = pytree.tree_map_only(
64
+ torch.Tensor,
65
+ lambda tensor: tensor.to(_get_new_device(tensor.device, location)),
66
+ kwargs,
67
+ )
68
+ ep._example_inputs = (moved_args, moved_kwargs)
69
+
70
+ for m in ep.graph_module.modules():
71
+ if isinstance(m, torch.fx.GraphModule):
72
+ for node in m.graph.nodes:
73
+ # move all the nodes kwargs with burnt-in device
74
+ if "device" in node.kwargs:
75
+ kwargs = node.kwargs.copy()
76
+ kwargs["device"] = _get_new_device(kwargs["device"], location)
77
+ node.kwargs = kwargs
78
+
79
+ if (
80
+ node.op == "call_function"
81
+ and node.target is torch.ops.aten.to.device
82
+ ):
83
+ args = list(node.args)
84
+ # pyrefly: ignore [unsupported-operation]
85
+ args[1] = _get_new_device(args[1], location)
86
+ node.args = tuple(args)
87
+
88
+ # move all the tensor metadata
89
+ node.meta["val"] = pytree.tree_map(
90
+ lambda v: v.to(_get_new_device(v.device, location))
91
+ if isinstance(v, torch.Tensor)
92
+ else v,
93
+ node.meta.get("val"),
94
+ )
95
+
96
+ ep.validate()
97
+ return ep
.venv/lib/python3.12/site-packages/torch/export/passes/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (5.11 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from ._package import is_pt2_package, PT2ArchiveReader, PT2ArchiveWriter
2
+
3
+
4
+ __all__ = ["PT2ArchiveWriter", "PT2ArchiveReader", "is_pt2_package"]
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (348 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/_package.cpython-312.pyc ADDED
Binary file (50 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/_package_weights.cpython-312.pyc ADDED
Binary file (9.08 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/__pycache__/constants.cpython-312.pyc ADDED
Binary file (2.18 kB). View file
 
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py ADDED
@@ -0,0 +1,1241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import io
3
+ import json
4
+ import logging
5
+ import os
6
+ import pickle
7
+ import tempfile
8
+ import zipfile
9
+ from dataclasses import dataclass
10
+ from typing import Any, IO, TYPE_CHECKING, TypeAlias
11
+ from typing_extensions import TypeIs
12
+
13
+ import torch
14
+ import torch.utils._pytree as pytree
15
+ from torch._export.serde import schema
16
+ from torch._export.serde.serialize import (
17
+ _dataclass_to_dict,
18
+ _dict_to_dataclass,
19
+ deserialize_device,
20
+ deserialize_scalar_type,
21
+ deserialize_size,
22
+ deserialize_storage_offset,
23
+ deserialize_stride,
24
+ ExportedProgramDeserializer,
25
+ serialize,
26
+ serialize_tensor_meta,
27
+ SerializedArtifact,
28
+ )
29
+ from torch._inductor.cpp_builder import normalize_path_separator
30
+ from torch._library.opaque_object import is_custom_class_obj
31
+ from torch._subclasses.fake_tensor import FakeTensor, is_fake_tensor
32
+ from torch.export import ExportedProgram
33
+ from torch.export._tree_utils import reorder_kwargs
34
+ from torch.export.pt2_archive._package_weights import (
35
+ get_complete_tensor,
36
+ group_weights,
37
+ TensorProperties,
38
+ Weights,
39
+ )
40
+ from torch.export.pt2_archive.constants import (
41
+ AOTINDUCTOR_DIR,
42
+ ARCHIVE_FORMAT_PATH,
43
+ ARCHIVE_FORMAT_VALUE,
44
+ ARCHIVE_VERSION_PATH,
45
+ ARCHIVE_VERSION_VALUE,
46
+ CONSTANTS_CONFIG_FILENAME_FORMAT,
47
+ CONSTANTS_DIR,
48
+ CUSTOM_OBJ_FILENAME_PREFIX,
49
+ EXECUTORCH_DIR,
50
+ EXTRA_DIR,
51
+ MODELS_DIR,
52
+ MODELS_FILENAME_FORMAT,
53
+ OPAQUE_OBJ_FILENAME_PREFIX,
54
+ SAMPLE_INPUTS_FILENAME_FORMAT,
55
+ TENSOR_CONSTANT_FILENAME_PREFIX,
56
+ WEIGHT_FILENAME_PREFIX,
57
+ WEIGHTS_CONFIG_FILENAME_FORMAT,
58
+ WEIGHTS_DIR,
59
+ )
60
+ from torch.types import FileLike
61
+
62
+
63
+ if TYPE_CHECKING:
64
+ from torch.utils._ordered_set import OrderedSet
65
+
66
+
67
+ DEFAULT_PICKLE_PROTOCOL = 2
68
+ AOTI_FILES: TypeAlias = list[str | Weights] | dict[str, list[str | Weights]]
69
+
70
+
71
+ logger: logging.Logger = logging.getLogger(__name__)
72
+
73
+
74
+ def is_pt2_package(serialized_model: bytes | str) -> bool:
75
+ """
76
+ Check if the serialized model is a PT2 Archive package.
77
+ """
78
+ try:
79
+ with zipfile.ZipFile(
80
+ io.BytesIO(serialized_model)
81
+ if isinstance(serialized_model, bytes)
82
+ else serialized_model
83
+ ) as zip_reader:
84
+ root_folder = zip_reader.namelist()[0].split(os.path.sep)[0]
85
+ archive_format_path = f"{root_folder}/{ARCHIVE_FORMAT_PATH}"
86
+ if archive_format_path in zip_reader.namelist():
87
+ return zip_reader.read(archive_format_path) == b"pt2"
88
+ except Exception:
89
+ logger.info("Model is not a PT2 package")
90
+ return False
91
+
92
+
93
+ class PT2ArchiveWriter:
94
+ """
95
+ Context manager for writing a PT2 archive.
96
+ """
97
+
98
+ def __init__(self, archive_path_or_buffer: FileLike):
99
+ if isinstance(archive_path_or_buffer, str):
100
+ archive_path_or_buffer = normalize_path_separator(archive_path_or_buffer)
101
+ self.archive_file = torch._C.PyTorchFileWriter(archive_path_or_buffer) # type: ignore[arg-type]
102
+ # NOTICE: version here is different from the archive_version
103
+ # this is the version of zip file format, which is used by PyTorchFileWriter, which write to /.data/version
104
+ # archive_version is the version of the PT2 archive spec, which write to /archive_version
105
+ self.archive_file.set_min_version(6)
106
+
107
+ def __enter__(self) -> "PT2ArchiveWriter":
108
+ return self
109
+
110
+ def __exit__(self, *args: Any) -> None:
111
+ if not self.has_record(ARCHIVE_FORMAT_PATH):
112
+ self.write_string(ARCHIVE_FORMAT_PATH, ARCHIVE_FORMAT_VALUE)
113
+
114
+ if not self.has_record(ARCHIVE_VERSION_PATH):
115
+ self.write_string(ARCHIVE_VERSION_PATH, ARCHIVE_VERSION_VALUE)
116
+
117
+ self.close()
118
+
119
+ def has_record(self, name: str) -> bool:
120
+ """
121
+ Check if a record exists in the archive.
122
+ """
123
+ return name in self.archive_file.get_all_written_records()
124
+
125
+ def count_prefix(self, prefix: str) -> int:
126
+ """
127
+ Count the number of records that start with a given prefix.
128
+ """
129
+ return sum(
130
+ 1
131
+ for record in self.archive_file.get_all_written_records()
132
+ if record.startswith(prefix)
133
+ )
134
+
135
+ def write_bytes(self, name: str, data: bytes) -> None:
136
+ """
137
+ Write a bytes object to the archive.
138
+ name: The destination file inside the archive.
139
+ data: The bytes object to write.
140
+ """
141
+ if not isinstance(data, bytes):
142
+ raise AssertionError(f"Expected bytes but got {type(data)}")
143
+ self.archive_file.write_record(name, data, len(data))
144
+
145
+ def write_string(self, name: str, data: str) -> None:
146
+ """
147
+ Write a string object to the archive.
148
+ name: The destination file inside the archive.
149
+ data: The string object to write.
150
+ """
151
+ if not isinstance(data, str):
152
+ raise AssertionError(f"Expected string but got {type(data)}")
153
+ data_bytes = data.encode()
154
+ self.write_bytes(name, data_bytes)
155
+
156
+ def write_file(self, name: str, file_path: str) -> None:
157
+ """
158
+ Copy a file into the archive.
159
+ name: The destination file inside the archive.
160
+ file_path: The source file on disk.
161
+ """
162
+ if not os.path.isfile(file_path):
163
+ raise AssertionError(f"{file_path} is not a valid file path")
164
+
165
+ with open(file_path, "rb") as f:
166
+ file_bytes = f.read()
167
+ self.write_bytes(name, file_bytes)
168
+
169
+ def write_folder(self, archive_dir: str, folder_dir: str) -> None:
170
+ """
171
+ Copy a folder into the archive.
172
+ archive_dir: The destination folder inside the archive.
173
+ folder_dir: The source folder on disk.
174
+ """
175
+ if not os.path.isdir(folder_dir):
176
+ raise AssertionError(f"{folder_dir} is not a valid directory path")
177
+
178
+ file_paths = filter(
179
+ os.path.isfile, glob.glob(f"{folder_dir}/**", recursive=True)
180
+ )
181
+ for file_path in file_paths:
182
+ # pyrefly: ignore [no-matching-overload]
183
+ filename = os.path.relpath(file_path, folder_dir)
184
+ archive_path = os.path.join(archive_dir, filename)
185
+ # pyrefly: ignore [bad-argument-type]
186
+ self.write_file(archive_path, file_path)
187
+
188
+ def close(self) -> None:
189
+ """
190
+ Close the archive.
191
+ """
192
+ self.archive_file.write_end_of_file()
193
+
194
+
195
+ class PT2ArchiveReader:
196
+ """
197
+ Context manager for reading a PT2 archive.
198
+ """
199
+
200
+ def __init__(self, archive_path_or_buffer: FileLike):
201
+ if isinstance(archive_path_or_buffer, str):
202
+ archive_path_or_buffer = normalize_path_separator(archive_path_or_buffer)
203
+ self.archive_file = torch._C.PyTorchFileReader(archive_path_or_buffer) # type: ignore[arg-type]
204
+ if self.read_string(ARCHIVE_FORMAT_PATH) != ARCHIVE_FORMAT_VALUE:
205
+ raise AssertionError("Invalid archive format")
206
+
207
+ def __enter__(self) -> "PT2ArchiveReader":
208
+ return self
209
+
210
+ def __exit__(self, *args: Any) -> None:
211
+ # torch._C.PyTorchFileReader doesn't have a close method
212
+ pass
213
+
214
+ def read_bytes(self, name: str) -> bytes:
215
+ """
216
+ Read a bytes object from the archive.
217
+ name: The source file inside the archive.
218
+ """
219
+ return self.archive_file.get_record(name)
220
+
221
+ def read_string(self, name: str) -> str:
222
+ """
223
+ Read a string object from the archive.
224
+ name: The source file inside the archive.
225
+ """
226
+ data = self.read_bytes(name)
227
+ return data.decode()
228
+
229
+ def archive_version(self) -> int:
230
+ """
231
+ Get the archive version.
232
+ """
233
+ try:
234
+ archive_version = self.read_string(ARCHIVE_VERSION_PATH)
235
+ except Exception:
236
+ # if archive_version is not found, it means the archive is older than version 0.
237
+ # In this case, we assume the archive is version 0.
238
+ archive_version = "0"
239
+
240
+ return int(archive_version)
241
+
242
+ def get_file_names(self) -> list[str]:
243
+ """
244
+ Get the file names in the archive.
245
+ """
246
+ return self.archive_file.get_all_records()
247
+
248
+
249
+ is_pt2_package.__module__ = "torch.export.pt2_archive"
250
+ PT2ArchiveWriter.__module__ = "torch.export.pt2_archive"
251
+ PT2ArchiveReader.__module__ = "torch.export.pt2_archive"
252
+
253
+
254
+ def _package_aoti_files(
255
+ archive_writer: PT2ArchiveWriter,
256
+ aoti_files: AOTI_FILES | None,
257
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
258
+ ) -> None:
259
+ if aoti_files is None:
260
+ return
261
+
262
+ if isinstance(aoti_files, list):
263
+ aoti_files = {"model": aoti_files}
264
+
265
+ if not isinstance(aoti_files, dict):
266
+ raise AssertionError(
267
+ f"Expected aoti_files to be a dict, but got {type(aoti_files)}"
268
+ )
269
+
270
+ all_weights: dict[str, Weights] = {} # model_name -> weight
271
+ weights_configs: dict[
272
+ str, dict[str, Any]
273
+ ] = {} # model_name -> (weight_name -> (filename, shape, stride, offset))
274
+
275
+ for model_name, files in aoti_files.items():
276
+ weights_configs[model_name] = {}
277
+
278
+ for file in files:
279
+ if file == "":
280
+ continue
281
+
282
+ if isinstance(file, Weights):
283
+ all_weights[model_name] = file
284
+ continue
285
+
286
+ # Note: Previously we rejected multiple .so cases. But Triton CPU AOTI
287
+ # has multiple .so files per model (wrapper, launcher, kernel).
288
+
289
+ filename = os.path.basename(file)
290
+ if filename.startswith(CUSTOM_OBJ_FILENAME_PREFIX):
291
+ new_filepath = os.path.join(CONSTANTS_DIR, filename)
292
+ else:
293
+ new_filepath = os.path.join(AOTINDUCTOR_DIR, model_name, filename)
294
+ logger.debug(
295
+ "Saving AOTI generated file %s to archive in %s", file, new_filepath
296
+ )
297
+ archive_writer.write_file(
298
+ str(new_filepath),
299
+ file,
300
+ )
301
+
302
+ if len(all_weights) > 0:
303
+ # Dedup weights
304
+ grouped_tensors: list[OrderedSet[tuple[str, str]]] = group_weights(all_weights)
305
+ for idx, group in enumerate(grouped_tensors):
306
+ filename = f"{WEIGHT_FILENAME_PREFIX}{idx}"
307
+ complete_tensor = get_complete_tensor(group, all_weights)
308
+ buffer = io.BytesIO()
309
+ torch.save(complete_tensor, buffer, pickle_protocol=pickle_protocol)
310
+ archive_writer.write_bytes(
311
+ os.path.join(WEIGHTS_DIR, filename), buffer.getvalue()
312
+ )
313
+ for model_name, weight_name in group:
314
+ _, w_property = all_weights[model_name].get_weight(weight_name)
315
+ weights_configs[model_name][weight_name] = (
316
+ filename,
317
+ w_property.shape,
318
+ w_property.stride,
319
+ w_property.offset,
320
+ )
321
+
322
+ for model_name, weights_config in weights_configs.items():
323
+ archive_writer.write_string(
324
+ os.path.join(AOTINDUCTOR_DIR, model_name, "weights_config.json"),
325
+ json.dumps(weights_config),
326
+ )
327
+ logger.debug("packaging weights_config for model %s", model_name)
328
+ logger.debug(weights_config)
329
+
330
+
331
+ def _is_fake_tensor(t: torch.Tensor) -> TypeIs[FakeTensor]:
332
+ return is_fake_tensor(t)
333
+
334
+
335
+ def _is_tensor_subclass(t: torch.Tensor) -> bool:
336
+ return isinstance(t, torch.Tensor) and type(t.data) is not torch.Tensor
337
+
338
+
339
+ def _get_raw_tensor_bytes(value: torch.Tensor) -> bytes:
340
+ """
341
+ Get the raw bytes of a tensor. This is used to save the tensor in pt2 archive.
342
+ """
343
+ # NOTE: don't chain .cpu() with .data_ptr(). If an HtoD copy needs to be
344
+ # performed, the CPU copy needs to be kept alive when its underlying
345
+ # memory is accessed.
346
+ import ctypes
347
+
348
+ if _is_fake_tensor(value):
349
+ value_bytes = b""
350
+ elif value.data_ptr():
351
+ cpu_tensor = value.cpu()
352
+ value_untyped_storage = cpu_tensor.untyped_storage()
353
+ # we store the raw bytes the untyped storage. Tensor metadata is stored separately
354
+ value_bytes = bytes(
355
+ ctypes.cast(
356
+ value_untyped_storage.data_ptr(),
357
+ ctypes.POINTER(ctypes.c_ubyte * value_untyped_storage.size()),
358
+ ).contents
359
+ )
360
+ else:
361
+ # for empty tensor
362
+ value_bytes = b""
363
+ return value_bytes
364
+
365
+
366
+ def _should_use_pickle(t: torch.Tensor) -> bool:
367
+ return _is_tensor_subclass(t) and not _is_fake_tensor(t)
368
+
369
+
370
+ def _save_pickled_tensors(
371
+ pickled_items: list[tuple[str, torch.Tensor]],
372
+ archive_writer: PT2ArchiveWriter,
373
+ config: dict[str, schema.PayloadMeta],
374
+ directory: str,
375
+ filename_prefix: str,
376
+ idx: int,
377
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
378
+ ) -> int:
379
+ """Save pickled tensors and update config. Returns updated index."""
380
+ for item_fqn, tensor in pickled_items:
381
+ path_name = f"{filename_prefix}{idx}"
382
+ archive_path = os.path.join(directory, path_name)
383
+ buffer = io.BytesIO()
384
+ torch.save(tensor, buffer, pickle_protocol=pickle_protocol)
385
+ archive_writer.write_bytes(archive_path, buffer.getvalue())
386
+
387
+ config[item_fqn] = schema.PayloadMeta(
388
+ path_name=path_name,
389
+ is_param=isinstance(tensor, torch.nn.Parameter),
390
+ use_pickle=True,
391
+ tensor_meta=serialize_tensor_meta(tensor),
392
+ )
393
+ idx += 1
394
+ return idx
395
+
396
+
397
+ def _save_raw_tensors(
398
+ raw_items: dict[str, tuple[torch.Tensor, TensorProperties]],
399
+ model_name: str,
400
+ archive_writer: PT2ArchiveWriter,
401
+ config: dict[str, schema.PayloadMeta],
402
+ directory: str,
403
+ filename_prefix: str,
404
+ idx: int,
405
+ ) -> int:
406
+ """Save deduplicated raw tensor bytes and update config. Returns updated index."""
407
+ if not raw_items:
408
+ return idx
409
+
410
+ weights_dict = {model_name: Weights(raw_items)}
411
+ storage_groups = group_weights(weights_dict)
412
+
413
+ for group in storage_groups:
414
+ # Find the complete tensor that covers all others in this storage group
415
+ complete_tensor = get_complete_tensor(group, weights_dict)
416
+
417
+ path_name = f"{filename_prefix}{idx}"
418
+ archive_path = os.path.join(directory, path_name)
419
+ tensor_bytes = _get_raw_tensor_bytes(complete_tensor)
420
+ archive_writer.write_bytes(archive_path, tensor_bytes)
421
+ idx += 1
422
+
423
+ for _, item_fqn in group:
424
+ tensor, _ = weights_dict[model_name].get_weight(item_fqn)
425
+ config[item_fqn] = schema.PayloadMeta(
426
+ path_name=path_name,
427
+ is_param=isinstance(tensor, torch.nn.Parameter),
428
+ use_pickle=False,
429
+ tensor_meta=serialize_tensor_meta(tensor),
430
+ )
431
+
432
+ return idx
433
+
434
+
435
+ def _package_state_dict(
436
+ model_name: str,
437
+ exported_program: ExportedProgram,
438
+ archive_writer: PT2ArchiveWriter,
439
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
440
+ ) -> schema.PayloadConfig:
441
+ weights_config: dict[str, schema.PayloadMeta] = {}
442
+
443
+ pickled_weights: list[tuple[str, torch.Tensor]] = []
444
+ raw_weights: dict[str, tuple[torch.Tensor, TensorProperties]] = {}
445
+
446
+ # Categorize weights
447
+ for weight_fqn, weight_tensor in exported_program.state_dict.items():
448
+ if not isinstance(weight_tensor, torch.Tensor):
449
+ raise AssertionError("only torch.Tensor is allowed in state_dict")
450
+ if _should_use_pickle(weight_tensor):
451
+ pickled_weights.append((weight_fqn, weight_tensor))
452
+ else:
453
+ raw_weights[weight_fqn] = (weight_tensor, TensorProperties(weight_tensor))
454
+
455
+ idx = archive_writer.count_prefix(os.path.join(WEIGHTS_DIR, WEIGHT_FILENAME_PREFIX))
456
+
457
+ # Save weights in pickle format
458
+ idx = _save_pickled_tensors(
459
+ pickled_weights,
460
+ archive_writer,
461
+ weights_config,
462
+ WEIGHTS_DIR,
463
+ WEIGHT_FILENAME_PREFIX,
464
+ idx,
465
+ pickle_protocol,
466
+ )
467
+
468
+ # Save weights in raw bytes format
469
+ _save_raw_tensors(
470
+ raw_weights,
471
+ model_name,
472
+ archive_writer,
473
+ weights_config,
474
+ WEIGHTS_DIR,
475
+ WEIGHT_FILENAME_PREFIX,
476
+ idx,
477
+ )
478
+
479
+ return schema.PayloadConfig(config=weights_config)
480
+
481
+
482
+ def _package_constants(
483
+ model_name: str,
484
+ exported_program: ExportedProgram,
485
+ archive_writer: PT2ArchiveWriter,
486
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
487
+ ) -> schema.PayloadConfig:
488
+ constants_config: dict[str, schema.PayloadMeta] = {}
489
+
490
+ pickled_constants: list[tuple[str, torch.Tensor]] = []
491
+ raw_constants: dict[str, tuple[torch.Tensor, TensorProperties]] = {}
492
+ custom_objects: list[tuple[str, Any]] = []
493
+
494
+ # Categorize constants
495
+ for constant_fqn, constant in exported_program.constants.items():
496
+ if isinstance(constant, torch.Tensor):
497
+ if _should_use_pickle(constant):
498
+ pickled_constants.append((constant_fqn, constant))
499
+ else:
500
+ raw_constants[constant_fqn] = (constant, TensorProperties(constant))
501
+
502
+ elif isinstance(constant, torch._C.ScriptObject) or is_custom_class_obj(
503
+ constant
504
+ ):
505
+ custom_objects.append((constant_fqn, constant))
506
+
507
+ else:
508
+ raise RuntimeError(f"Unsupported constant type: {type(constant)}")
509
+
510
+ tensor_idx = archive_writer.count_prefix(
511
+ os.path.join(CONSTANTS_DIR, TENSOR_CONSTANT_FILENAME_PREFIX)
512
+ )
513
+ custom_obj_idx = archive_writer.count_prefix(
514
+ os.path.join(CONSTANTS_DIR, CUSTOM_OBJ_FILENAME_PREFIX)
515
+ )
516
+ opaque_obj_idx = archive_writer.count_prefix(
517
+ os.path.join(CONSTANTS_DIR, OPAQUE_OBJ_FILENAME_PREFIX)
518
+ )
519
+
520
+ # Save constants in pickle format
521
+ tensor_idx = _save_pickled_tensors(
522
+ pickled_constants,
523
+ archive_writer,
524
+ constants_config,
525
+ CONSTANTS_DIR,
526
+ TENSOR_CONSTANT_FILENAME_PREFIX,
527
+ tensor_idx,
528
+ pickle_protocol,
529
+ )
530
+
531
+ # Save constants in raw bytes format
532
+ _save_raw_tensors(
533
+ raw_constants,
534
+ model_name,
535
+ archive_writer,
536
+ constants_config,
537
+ CONSTANTS_DIR,
538
+ TENSOR_CONSTANT_FILENAME_PREFIX,
539
+ tensor_idx,
540
+ )
541
+
542
+ # ScriptObjects use the torchbind-aware pickler (zip-archive format,
543
+ # readable from C++ at load time). Opaque values use standard Python
544
+ # pickle. Distinct filename prefixes act as the format discriminator
545
+ # for the reader.
546
+ for constant_fqn, constant in custom_objects:
547
+ if isinstance(constant, torch._C.ScriptObject):
548
+ path_name = f"{CUSTOM_OBJ_FILENAME_PREFIX}{custom_obj_idx}"
549
+ obj_bytes = torch._C._pickle_save(constant)
550
+ custom_obj_idx += 1
551
+ else:
552
+ path_name = f"{OPAQUE_OBJ_FILENAME_PREFIX}{opaque_obj_idx}"
553
+ obj_bytes = pickle.dumps(constant, protocol=pickle_protocol)
554
+ opaque_obj_idx += 1
555
+ archive_path = os.path.join(CONSTANTS_DIR, path_name)
556
+ archive_writer.write_bytes(archive_path, obj_bytes)
557
+
558
+ constants_config[constant_fqn] = schema.PayloadMeta(
559
+ path_name=path_name,
560
+ is_param=False,
561
+ use_pickle=True,
562
+ tensor_meta=None,
563
+ )
564
+
565
+ return schema.PayloadConfig(config=constants_config)
566
+
567
+
568
+ def _package_payload_config(
569
+ archive_writer: PT2ArchiveWriter,
570
+ payload_config: schema.PayloadConfig,
571
+ config_file: str,
572
+ ) -> None:
573
+ """
574
+ Save the payload config as json file in the archive.
575
+ """
576
+ archive_writer.write_string(
577
+ config_file, json.dumps(_dataclass_to_dict(payload_config))
578
+ )
579
+
580
+
581
+ def _package_exported_programs(
582
+ archive_writer: PT2ArchiveWriter,
583
+ exported_programs: ExportedProgram | dict[str, ExportedProgram] | None,
584
+ opset_version: dict[str, int] | None = None,
585
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
586
+ ) -> None:
587
+ if exported_programs is None:
588
+ return
589
+
590
+ if isinstance(exported_programs, ExportedProgram):
591
+ exported_programs = {"model": exported_programs}
592
+
593
+ if not isinstance(exported_programs, dict):
594
+ raise AssertionError(
595
+ f"Expected exported_programs to be a dict, but got {type(exported_programs)}"
596
+ )
597
+
598
+ for model_name, ep in exported_programs.items():
599
+ weights_config = _package_state_dict(
600
+ model_name, ep, archive_writer, pickle_protocol
601
+ )
602
+ weights_config_file = WEIGHTS_CONFIG_FILENAME_FORMAT.format(model_name)
603
+ _package_payload_config(archive_writer, weights_config, weights_config_file)
604
+
605
+ constants_config = _package_constants(
606
+ model_name, ep, archive_writer, pickle_protocol
607
+ )
608
+ constants_config_file = CONSTANTS_CONFIG_FILENAME_FORMAT.format(model_name)
609
+ _package_payload_config(archive_writer, constants_config, constants_config_file)
610
+
611
+ artifact: SerializedArtifact = serialize(
612
+ ep,
613
+ opset_version,
614
+ pickle_protocol,
615
+ serialize_state_dict=False,
616
+ serialize_constants=False,
617
+ )
618
+
619
+ archive_writer.write_bytes(
620
+ MODELS_FILENAME_FORMAT.format(model_name), artifact.exported_program
621
+ )
622
+ archive_writer.write_bytes(
623
+ SAMPLE_INPUTS_FILENAME_FORMAT.format(model_name),
624
+ artifact.example_inputs,
625
+ )
626
+
627
+
628
+ def _package_extra_files(
629
+ archive_writer: PT2ArchiveWriter, extra_files: dict[str, Any] | None
630
+ ) -> None:
631
+ if extra_files is None:
632
+ return
633
+
634
+ for extra_file_name, content in extra_files.items():
635
+ archive_writer.write_string(f"{EXTRA_DIR}{extra_file_name}", content)
636
+
637
+
638
+ def _package_executorch_files(
639
+ archive_writer: PT2ArchiveWriter, executorch_files: dict[str, bytes] | None
640
+ ) -> None:
641
+ if executorch_files is None:
642
+ return
643
+
644
+ for file_name, content in executorch_files.items():
645
+ archive_writer.write_bytes(f"{EXECUTORCH_DIR}{file_name}", content)
646
+
647
+
648
+ def package_pt2(
649
+ f: FileLike,
650
+ *,
651
+ exported_programs: ExportedProgram | dict[str, ExportedProgram] | None = None,
652
+ aoti_files: AOTI_FILES | None = None,
653
+ extra_files: dict[str, Any] | None = None,
654
+ opset_version: dict[str, int] | None = None,
655
+ pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
656
+ executorch_files: dict[str, bytes] | None = None,
657
+ ) -> FileLike:
658
+ r"""
659
+ Saves the artifacts to a PT2Archive format. The artifact can then be loaded
660
+ using ``load_pt2``.
661
+
662
+ Args:
663
+ f (str | os.PathLike[str] | IO[bytes]): A file-like object (has to
664
+ implement write and flush) or a string containing a file name.
665
+
666
+ exported_programs (Union[ExportedProgram, dict[str, ExportedProgram]]):
667
+ The exported program to save, or a dictionary mapping model name to an
668
+ exported program to save. The exported program will be saved under
669
+ models/\*.json. If only one ExportedProgram is specified, this will
670
+ automatically be named "model".
671
+
672
+ aoti_files (Union[list[str], dict[str, list[str]]]): A list of files
673
+ generated by AOTInductor via
674
+ ``torch._inductor.aot_compile(..., {"aot_inductor.package": True})``,
675
+ or a dictionary mapping model name to its AOTInductor generated files.
676
+ If only one set of files is specified, this will automatically be named
677
+ "model".
678
+
679
+ extra_files (Optional[Dict[str, Any]]): Map from filename to contents
680
+ which will be stored as part of the pt2.
681
+
682
+ opset_version (Optional[Dict[str, int]]): A map of opset names
683
+ to the version of this opset
684
+
685
+ pickle_protocol: can be specified to override the default protocol
686
+
687
+ executorch_files (Optional[dict[str, bytes]]): Optional executorch
688
+ artifacts to save.
689
+
690
+ """
691
+ if exported_programs is None and aoti_files is None and extra_files is None:
692
+ raise AssertionError(
693
+ "No value passed in for `exported_programs`, `aoti_files`, and "
694
+ "`extra_files`, implying that you do not plan on saving anything."
695
+ )
696
+
697
+ if not (
698
+ (isinstance(f, (io.IOBase, IO)) and f.writable() and f.seekable())
699
+ or (isinstance(f, (str, os.PathLike)) and os.fspath(f).endswith(".pt2"))
700
+ or (isinstance(f, tempfile._TemporaryFileWrapper) and f.name.endswith(".pt2"))
701
+ ):
702
+ # TODO: turn this into an error
703
+ logger.warning(
704
+ "Expect archive file to be a file ending in .pt2, or is a buffer. "
705
+ "Instead got {%s}",
706
+ f,
707
+ )
708
+
709
+ if isinstance(f, (str, os.PathLike)):
710
+ f = os.fspath(f)
711
+
712
+ # pyrefly: ignore [bad-argument-type]
713
+ with PT2ArchiveWriter(f) as archive_writer:
714
+ _package_exported_programs(
715
+ archive_writer, exported_programs, pickle_protocol=pickle_protocol
716
+ )
717
+ _package_aoti_files(
718
+ archive_writer,
719
+ aoti_files,
720
+ pickle_protocol=pickle_protocol,
721
+ )
722
+ _package_extra_files(archive_writer, extra_files)
723
+ _package_executorch_files(archive_writer, executorch_files)
724
+
725
+ if isinstance(f, (io.IOBase, IO)):
726
+ f.seek(0)
727
+ # pyrefly: ignore [bad-return]
728
+ return f
729
+
730
+
731
+ class AOTICompiledModel:
732
+ """
733
+ Callable AOT Inductor loaded model from a .pt2
734
+ """
735
+
736
+ def __init__(self, loader: torch._C._aoti.AOTIModelPackageLoader) -> None:
737
+ self.loader = loader
738
+
739
+ def __call__(self, *args, **kwargs): # type: ignore[no-untyped-def]
740
+ call_spec = self.loader.get_call_spec()
741
+ in_spec = pytree.treespec_loads(call_spec[0])
742
+ out_spec = pytree.treespec_loads(call_spec[1])
743
+ flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, in_spec)))[0]
744
+ flat_inputs = [x for x in flat_inputs if isinstance(x, torch.Tensor)]
745
+ flat_outputs = self.loader.boxed_run(flat_inputs)
746
+ return pytree.tree_unflatten(flat_outputs, out_spec)
747
+
748
+ def get_metadata(self) -> dict[str, str]:
749
+ return self.loader.get_metadata()
750
+
751
+ def load_constants(
752
+ self,
753
+ constants_map: dict[str, torch.Tensor],
754
+ *,
755
+ check_full_update: bool,
756
+ user_managed: bool = False,
757
+ allow_h2d_copy: bool = False,
758
+ ) -> None:
759
+ """
760
+ Given a mapping of constant fqns to tensors, load the constants into the model.
761
+ You can use ``get_constant_fqns`` to get the list of constant fqns that
762
+ are needed in the compiled model.
763
+
764
+ Args:
765
+ constants_map: A mapping of constant fqns to tensors.
766
+ check_full_update: Whether to add check to see if all the constants
767
+ are updated and have values.
768
+ user_managed: If True, the loader stores the tensor pointers
769
+ directly; the caller must keep them alive.
770
+ allow_h2d_copy: If True, CPU tensors are silently copied to the
771
+ model's device. Useful for loading a CPU ``state_dict()`` into a
772
+ non-CPU model. Incompatible with ``user_managed``.
773
+ """
774
+ self.loader.load_constants(
775
+ constants_map, False, check_full_update, user_managed, allow_h2d_copy
776
+ )
777
+
778
+ def get_constant_fqns(self) -> list[str]:
779
+ return self.loader.get_constant_fqns()
780
+
781
+ def __deepcopy__(self, memo: dict[Any, Any] | None) -> "AOTICompiledModel":
782
+ logger.warning(
783
+ "AOTICompiledModel deepcopy warning: AOTICompiledModel.loader is not deepcopied."
784
+ )
785
+ return AOTICompiledModel(self.loader)
786
+
787
+
788
+ @dataclass
789
+ class PT2ArchiveContents:
790
+ exported_programs: dict[str, ExportedProgram]
791
+ aoti_runners: dict[str, AOTICompiledModel]
792
+ extra_files: dict[str, Any]
793
+
794
+
795
+ def _build_file_map(
796
+ archive_reader: PT2ArchiveReader,
797
+ config: schema.PayloadConfig,
798
+ base_dir: str,
799
+ ) -> dict[str, torch.Tensor]:
800
+ """
801
+ Build a map from file path to the payload in flat tensor format.
802
+ """
803
+ file_map: dict[str, torch.Tensor] = {}
804
+ for payload_meta in config.config.values():
805
+ # skip pickled objects
806
+ if payload_meta.use_pickle:
807
+ continue
808
+ # skip files that already exist in the map
809
+ if payload_meta.path_name in file_map:
810
+ continue
811
+
812
+ if payload_meta.tensor_meta is None:
813
+ raise AssertionError("payload_meta.tensor_meta cannot be None")
814
+
815
+ tensor_meta = payload_meta.tensor_meta
816
+ dtype = deserialize_scalar_type(tensor_meta.dtype)
817
+ device = deserialize_device(tensor_meta.device)
818
+ record_name = os.path.join(base_dir, payload_meta.path_name)
819
+ nbytes = archive_reader.archive_file.get_record_size(record_name)
820
+
821
+ if nbytes == 0:
822
+ size = deserialize_size(tensor_meta.sizes)
823
+ tensor = torch.zeros(size, dtype=dtype, device=device)
824
+ if tensor_meta.requires_grad:
825
+ tensor.requires_grad_(True)
826
+ else:
827
+ element_size = torch._utils._element_size(dtype)
828
+ if nbytes % element_size != 0:
829
+ raise ValueError(
830
+ f"Record {record_name}: size {nbytes} is not a multiple of "
831
+ f"element size {element_size} for dtype {dtype}"
832
+ )
833
+ numel = nbytes // element_size
834
+ raw = archive_reader.archive_file.get_storage_from_record(
835
+ record_name, numel, dtype
836
+ )
837
+ # get_storage_from_record returns a tensor with empty DispatchKeySet,
838
+ # so we wrap the storage in a proper CPU tensor via set_().
839
+ tensor = torch.empty(0, dtype=dtype)
840
+ tensor.set_(raw.untyped_storage(), 0, (numel,), (1,))
841
+ if tensor_meta.requires_grad:
842
+ tensor.requires_grad_(True)
843
+ if device != torch.device("cpu"):
844
+ tensor = tensor.to(device)
845
+
846
+ file_map[payload_meta.path_name] = tensor
847
+
848
+ return file_map
849
+
850
+
851
+ def _load_payload_config(
852
+ archive_reader: PT2ArchiveReader,
853
+ config_file: str,
854
+ ) -> schema.PayloadConfig:
855
+ """
856
+ Load and parse a payload config from the archive.
857
+ """
858
+ return _dict_to_dataclass(
859
+ schema.PayloadConfig,
860
+ json.loads(archive_reader.read_string(config_file)),
861
+ )
862
+
863
+
864
+ def _load_state_dict(
865
+ archive_reader: PT2ArchiveReader,
866
+ model_name: str,
867
+ ) -> dict[str, torch.Tensor] | bytes:
868
+ # Make it BC compatible with legacy weight files
869
+ legacy_weights_file = f"{WEIGHTS_DIR}{model_name}.pt"
870
+ if legacy_weights_file in archive_reader.get_file_names():
871
+ logger.warning(
872
+ "You are loading weight from the legacy format. "
873
+ "Please generate a new pt2 file using torch.export.save()."
874
+ )
875
+ return archive_reader.read_bytes(legacy_weights_file)
876
+ else:
877
+ weights_config_file = WEIGHTS_CONFIG_FILENAME_FORMAT.format(model_name)
878
+ if weights_config_file not in archive_reader.get_file_names():
879
+ raise AssertionError(f"{weights_config_file} not found in PT2 archive")
880
+ weights_config = _load_payload_config(archive_reader, weights_config_file)
881
+ # construct the mapping from file name (e.g. weight_0) to flat weight payload
882
+ state_dict_file_map = _build_file_map(
883
+ archive_reader, weights_config, WEIGHTS_DIR
884
+ )
885
+ # chain the mapping weight FQN -> weight file name -> strided weight payload
886
+ # so that the aliasing of weights is preserved
887
+ state_dict: dict[str, torch.Tensor] = {}
888
+ for weight_fqn, payload_meta in weights_config.config.items():
889
+ if payload_meta.use_pickle:
890
+ weight_bytes = archive_reader.read_bytes(
891
+ os.path.join(WEIGHTS_DIR, payload_meta.path_name)
892
+ )
893
+ state_dict[weight_fqn] = torch.load(
894
+ io.BytesIO(weight_bytes), weights_only=False
895
+ )
896
+ else:
897
+ tensor_meta = payload_meta.tensor_meta
898
+ if tensor_meta is None:
899
+ raise AssertionError(
900
+ "tensor_meta cannot be None for non-pickled weight"
901
+ )
902
+ weight_tensor = torch.as_strided(
903
+ input=state_dict_file_map[payload_meta.path_name],
904
+ size=deserialize_size(tensor_meta.sizes),
905
+ stride=deserialize_stride(tensor_meta.strides),
906
+ storage_offset=deserialize_storage_offset(
907
+ tensor_meta.storage_offset
908
+ ),
909
+ )
910
+ if payload_meta.is_param:
911
+ state_dict[weight_fqn] = torch.nn.Parameter(
912
+ weight_tensor, requires_grad=tensor_meta.requires_grad
913
+ )
914
+ else:
915
+ state_dict[weight_fqn] = weight_tensor
916
+
917
+ return state_dict
918
+
919
+
920
+ def _load_constants(
921
+ archive_reader: PT2ArchiveReader,
922
+ model_name: str,
923
+ ) -> dict[str, torch.Tensor] | bytes:
924
+ # Make it BC compatible with legacy constant files
925
+ legacy_constants_file = f"{CONSTANTS_DIR}{model_name}.pt"
926
+ if legacy_constants_file in archive_reader.get_file_names():
927
+ logger.warning(
928
+ "You are loading constant from the legacy format. "
929
+ "Please generate a new pt2 file using torch.export.save()."
930
+ )
931
+ return archive_reader.read_bytes(legacy_constants_file)
932
+ else:
933
+ constants_config_file = CONSTANTS_CONFIG_FILENAME_FORMAT.format(model_name)
934
+ if constants_config_file not in archive_reader.get_file_names():
935
+ raise AssertionError(f"{constants_config_file} not found in PT2 archive")
936
+ constants_config = _load_payload_config(archive_reader, constants_config_file)
937
+ # construct the mapping from file name (e.g. constant_0) to constant payload
938
+ constant_file_map = _build_file_map(
939
+ archive_reader, constants_config, CONSTANTS_DIR
940
+ )
941
+ # chain the mapping constant FQN -> constant file name -> strided constant payload
942
+ # so that the aliasing of constants is preserved
943
+ constants: dict[str, torch.Tensor] = {}
944
+ for constant_fqn, payload_meta in constants_config.config.items():
945
+ path_name = payload_meta.path_name
946
+ if path_name.startswith(TENSOR_CONSTANT_FILENAME_PREFIX):
947
+ if payload_meta.use_pickle:
948
+ constant_bytes = archive_reader.read_bytes(
949
+ os.path.join(CONSTANTS_DIR, path_name)
950
+ )
951
+ constants[constant_fqn] = torch.load(
952
+ io.BytesIO(constant_bytes), weights_only=False
953
+ )
954
+ else:
955
+ tensor_meta = payload_meta.tensor_meta
956
+ if tensor_meta is None:
957
+ raise AssertionError(
958
+ "tensor_meta cannot be None for non-pickled constant"
959
+ )
960
+ constant_tensor = torch.as_strided(
961
+ input=constant_file_map[path_name],
962
+ size=deserialize_size(tensor_meta.sizes),
963
+ stride=deserialize_stride(tensor_meta.strides),
964
+ storage_offset=deserialize_storage_offset(
965
+ tensor_meta.storage_offset
966
+ ),
967
+ )
968
+ constants[constant_fqn] = constant_tensor
969
+
970
+ elif path_name.startswith(CUSTOM_OBJ_FILENAME_PREFIX):
971
+ constant_bytes = archive_reader.read_bytes(
972
+ os.path.join(CONSTANTS_DIR, path_name)
973
+ )
974
+ constants[constant_fqn] = torch._C._pickle_load_obj(constant_bytes)
975
+
976
+ elif path_name.startswith(OPAQUE_OBJ_FILENAME_PREFIX):
977
+ constant_bytes = archive_reader.read_bytes(
978
+ os.path.join(CONSTANTS_DIR, path_name)
979
+ )
980
+ constants[constant_fqn] = pickle.loads(constant_bytes)
981
+
982
+ else:
983
+ raise RuntimeError(f"Unsupported constant type: {path_name}")
984
+
985
+ return constants
986
+
987
+
988
+ def _load_exported_programs(
989
+ archive_reader: PT2ArchiveReader,
990
+ file_names: list[str],
991
+ expected_opset_version: dict[str, int] | None,
992
+ ) -> dict[str, ExportedProgram]:
993
+ exported_program_files = [
994
+ file for file in file_names if file.startswith(MODELS_DIR)
995
+ ]
996
+ exported_programs = {}
997
+ for file in exported_program_files:
998
+ prefix, suffix = MODELS_FILENAME_FORMAT.split(
999
+ "{}"
1000
+ ) # split "models/{}.json" into "models/" and "json"
1001
+ model_name = file[
1002
+ len(prefix) : -len(suffix)
1003
+ ] # given "models/foo.json" we can now get "foo"
1004
+
1005
+ sample_inputs_file = SAMPLE_INPUTS_FILENAME_FORMAT.format(model_name)
1006
+ serialized_sample_inputs = archive_reader.read_bytes(sample_inputs_file)
1007
+
1008
+ from torch._export.serde.serialize import _bytes_to_dataclass
1009
+
1010
+ exported_program_bytes = archive_reader.read_bytes(file)
1011
+ serialized_exported_program = _bytes_to_dataclass(
1012
+ schema.ExportedProgram, exported_program_bytes
1013
+ )
1014
+ state_dict = _load_state_dict(archive_reader, model_name)
1015
+ constants = _load_constants(archive_reader, model_name)
1016
+
1017
+ ep = ExportedProgramDeserializer(expected_opset_version).deserialize(
1018
+ serialized_exported_program,
1019
+ state_dict,
1020
+ constants,
1021
+ serialized_sample_inputs,
1022
+ )
1023
+
1024
+ exported_programs[model_name] = ep
1025
+
1026
+ return exported_programs
1027
+
1028
+
1029
+ def _load_extra_files(
1030
+ archive_reader: PT2ArchiveReader, file_names: list[str]
1031
+ ) -> dict[str, Any]:
1032
+ extra_files = [file for file in file_names if file.startswith(EXTRA_DIR)]
1033
+
1034
+ extra_file_contents: dict[str, Any] = {}
1035
+ for file in extra_files:
1036
+ contents = archive_reader.read_string(file)
1037
+ extra_file_contents[file[len(EXTRA_DIR) :]] = contents
1038
+
1039
+ return extra_file_contents
1040
+
1041
+
1042
+ def _load_aoti(
1043
+ file: str,
1044
+ model_name: str,
1045
+ run_single_threaded: bool,
1046
+ num_runners: int,
1047
+ device_idx: int,
1048
+ ) -> AOTICompiledModel:
1049
+ loaded_metadata = torch._C._aoti.AOTIModelPackageLoader.load_metadata_from_package( # type: ignore[attr-defined]
1050
+ file, model_name
1051
+ )
1052
+
1053
+ aoti_compiled_model = AOTICompiledModel(
1054
+ torch._C._aoti.AOTIModelPackageLoader(
1055
+ file,
1056
+ model_name,
1057
+ run_single_threaded,
1058
+ num_runners,
1059
+ device_idx,
1060
+ )
1061
+ )
1062
+
1063
+ device = loaded_metadata["AOTI_DEVICE_KEY"]
1064
+ from torch._inductor.codecache import get_device_information
1065
+
1066
+ current_device_info = get_device_information(device)
1067
+
1068
+ for k, v in current_device_info.items():
1069
+ if k in loaded_metadata:
1070
+ if v != loaded_metadata[k]:
1071
+ logger.warning(
1072
+ "Device information mismatch for %s: %s vs %s. "
1073
+ "This could cause some issues when loading the AOTInductor compiled artifacts.",
1074
+ k,
1075
+ v,
1076
+ loaded_metadata[k],
1077
+ )
1078
+
1079
+ return aoti_compiled_model
1080
+
1081
+
1082
+ def load_pt2(
1083
+ f: FileLike,
1084
+ *,
1085
+ expected_opset_version: dict[str, int] | None = None,
1086
+ run_single_threaded: bool = False,
1087
+ num_runners: int = 1,
1088
+ device_index: int = -1,
1089
+ load_weights_from_disk: bool = False,
1090
+ ) -> PT2ArchiveContents: # type: ignore[type-arg]
1091
+ """
1092
+ Loads all the artifacts previously saved with ``package_pt2``.
1093
+
1094
+ Args:
1095
+ f (str | os.PathLike[str] | IO[bytes]): A file-like object (has to
1096
+ implement write and flush) or a string containing a file name.
1097
+
1098
+ expected_opset_version (Optional[Dict[str, int]]): A map of opset names
1099
+ to expected opset versions
1100
+
1101
+ num_runners (int): Number of runners to load AOTInductor artifacts
1102
+
1103
+ run_single_threaded (bool): Whether the model should be run without
1104
+ thread synchronization logic. This is useful to avoid conflicts with
1105
+ CUDAGraphs.
1106
+
1107
+ device_index (int): The index of the device to which the PT2 package is
1108
+ to be loaded. By default, `device_index=-1` is used, which corresponds
1109
+ to the device `cuda` when using CUDA. Passing `device_index=1` would
1110
+ load the package to `cuda:1`, for example.
1111
+
1112
+ Returns:
1113
+ A ``PT2ArchiveContents`` object which contains all the objects in the PT2.
1114
+ """
1115
+
1116
+ from torch._inductor.cpp_builder import normalize_path_separator
1117
+
1118
+ if not (
1119
+ (isinstance(f, (io.IOBase, IO)) and f.readable() and f.seekable())
1120
+ or (isinstance(f, (str, os.PathLike)) and os.fspath(f).endswith(".pt2"))
1121
+ ):
1122
+ # TODO: turn this into an error in 2.9
1123
+ logger.warning(
1124
+ "Unable to load package. f must be a buffer or a file ending in "
1125
+ ".pt2. Instead got {%s}",
1126
+ f,
1127
+ )
1128
+
1129
+ if isinstance(f, (str, os.PathLike)):
1130
+ f = os.fspath(f)
1131
+
1132
+ weights = {}
1133
+ weight_maps = {}
1134
+ # pyrefly: ignore [bad-argument-type]
1135
+ with PT2ArchiveReader(f) as archive_reader:
1136
+ version = archive_reader.read_string(ARCHIVE_VERSION_PATH)
1137
+ if version != ARCHIVE_VERSION_VALUE:
1138
+ raise ValueError(
1139
+ f"Saved archive version {version} does not match our current "
1140
+ f"archive version {ARCHIVE_VERSION_VALUE}."
1141
+ )
1142
+
1143
+ file_names = archive_reader.get_file_names()
1144
+
1145
+ exported_programs = _load_exported_programs(
1146
+ archive_reader, file_names, expected_opset_version
1147
+ )
1148
+ extra_files = _load_extra_files(archive_reader, file_names)
1149
+
1150
+ # Get a list of AOTI model names
1151
+ aoti_model_names: set[str] = set()
1152
+ for file in file_names:
1153
+ if file.startswith(AOTINDUCTOR_DIR):
1154
+ file_end = file[
1155
+ len(AOTINDUCTOR_DIR) :
1156
+ ] # remove data/aotinductor/ prefix
1157
+ file_end = normalize_path_separator(
1158
+ file_end
1159
+ ) # Win32 need normalize path before split.
1160
+ model_name = file_end.split("/")[
1161
+ 0
1162
+ ] # split "model_name/...cpp" into "model_name"
1163
+ aoti_model_names.add(model_name)
1164
+ if load_weights_from_disk and file.endswith("weights_config.json"):
1165
+ weight_map = json.loads(archive_reader.read_string(file))
1166
+ weight_maps[model_name] = weight_map
1167
+ elif load_weights_from_disk and file.startswith(WEIGHTS_DIR):
1168
+ weight_file_name = file[
1169
+ len(WEIGHTS_DIR) :
1170
+ ] # remove data/weights/ prefix
1171
+ weight_bytes = archive_reader.read_bytes(file)
1172
+ loaded_weight = torch.load(io.BytesIO(weight_bytes))
1173
+ weights[weight_file_name] = loaded_weight
1174
+
1175
+ if isinstance(f, (io.IOBase, IO)):
1176
+ if len(aoti_model_names) > 0:
1177
+ # Workaround for AOTIModelPackageLoader not reading buffers
1178
+ with tempfile.NamedTemporaryFile(suffix=".pt2") as tf:
1179
+ f.seek(0)
1180
+ tf.write(f.read())
1181
+ f.seek(0)
1182
+ logger.debug("Writing buffer to tmp file located at %s.", tf.name)
1183
+
1184
+ aoti_runners = {
1185
+ model_name: _load_aoti(
1186
+ tf.name,
1187
+ model_name,
1188
+ run_single_threaded,
1189
+ num_runners,
1190
+ device_index,
1191
+ )
1192
+ for model_name in aoti_model_names
1193
+ }
1194
+ else:
1195
+ aoti_runners = {}
1196
+ else:
1197
+ aoti_runners = {
1198
+ model_name: _load_aoti(
1199
+ f,
1200
+ model_name,
1201
+ run_single_threaded,
1202
+ num_runners,
1203
+ device_index,
1204
+ )
1205
+ for model_name in aoti_model_names
1206
+ }
1207
+
1208
+ if weight_maps:
1209
+ for model_name in aoti_model_names:
1210
+ model_weights = {}
1211
+ for weight_name, (file, shape, stride, storage_offset) in weight_maps[
1212
+ model_name
1213
+ ].items():
1214
+ weight = weights[file]
1215
+ model_weights[weight_name] = weight.as_strided(
1216
+ shape, stride, storage_offset
1217
+ )
1218
+
1219
+ # user_managed=True ensures the weights updates are shared by all runners.
1220
+ aoti_runners[model_name].load_constants(
1221
+ model_weights, check_full_update=True, user_managed=True
1222
+ )
1223
+
1224
+ return PT2ArchiveContents(exported_programs, aoti_runners, extra_files)
1225
+
1226
+
1227
+ def load_weights_to_pt2_contents(
1228
+ pt2_contents: PT2ArchiveContents, weights_map: dict[str, Any]
1229
+ ) -> None:
1230
+ """
1231
+ Load weights into the models in PT2 archive contents
1232
+
1233
+ Args:
1234
+ pt2_contents (PT2ArchiveContents): The contents of the PT2 archive.
1235
+ """
1236
+ for model_name, weights in weights_map.items():
1237
+ if model_name not in pt2_contents.aoti_runners:
1238
+ raise RuntimeError(f"Model {model_name} not found in PT2 archive contents.")
1239
+ pt2_contents.aoti_runners[model_name].load_constants(
1240
+ weights, check_full_update=True, user_managed=True
1241
+ )
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/_package_weights.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import warnings
3
+
4
+ import torch
5
+ from torch._subclasses.fake_tensor import is_fake_tensor
6
+ from torch.utils._ordered_set import OrderedSet
7
+
8
+
9
+ def _end_ptr(tensor: torch.Tensor) -> int:
10
+ if tensor.nelement():
11
+ stop = tensor.view(-1)[-1].data_ptr() + tensor.element_size()
12
+ else:
13
+ stop = tensor.data_ptr()
14
+ return stop
15
+
16
+
17
+ class TensorProperties:
18
+ def __init__(self, tensor: torch.Tensor):
19
+ self.is_fake = is_fake_tensor(tensor)
20
+ self.is_contiguous = tensor.is_contiguous()
21
+ self.storage_ptr = None
22
+ self.storage_size = None
23
+ self.start = None
24
+ self.end = None
25
+
26
+ if not self.is_fake:
27
+ # only get the storage pointer for real tensors
28
+ # pyrefly: ignore [bad-assignment]
29
+ self.storage_ptr = tensor.untyped_storage().data_ptr()
30
+ if self.is_contiguous:
31
+ # only get storage size and start/end pointers for contiguous tensors
32
+ # pyrefly: ignore [bad-assignment]
33
+ self.storage_size = tensor.untyped_storage().nbytes()
34
+ # pyrefly: ignore [bad-assignment]
35
+ self.start = tensor.data_ptr()
36
+ # pyrefly: ignore [bad-assignment]
37
+ self.end = _end_ptr(tensor)
38
+
39
+ # info to recover tensor
40
+ self.shape = tensor.shape
41
+ self.stride = tensor.stride()
42
+ self.offset = tensor.storage_offset()
43
+
44
+ def is_complete(self) -> bool:
45
+ """
46
+ Whether the tensor completely overlaps with its underlying storage
47
+ """
48
+ if self.is_fake:
49
+ # Theoretically, fake tensors should not appear in weights
50
+ # But we handle this corner case to make it always complete
51
+ return True
52
+ if not self.is_contiguous:
53
+ return False
54
+
55
+ if self.storage_ptr is None:
56
+ raise AssertionError("storage_ptr cannot be None for complete check")
57
+ if self.storage_size is None:
58
+ raise AssertionError("storage_size cannot be None for complete check")
59
+ if self.start is None:
60
+ raise AssertionError("start cannot be None for complete check")
61
+ if self.end is None:
62
+ raise AssertionError("end cannot be None for complete check")
63
+ return (
64
+ self.start == self.storage_ptr
65
+ and self.end == self.storage_ptr + self.storage_size
66
+ )
67
+
68
+
69
+ class Weights(dict):
70
+ """
71
+ A dictionary mapping from weight name to a tuple of (tensor, TensorProperties).
72
+ tensor represents the actual initial value of the weight.
73
+ TensorProperties represents the properties of the weight that are needed to recover the weight.
74
+
75
+ We use two separate entries because `tensor` could be a clone of the original weight tensor,
76
+ so it doesn't have the same property as the original weight (such as underlying storage pointer).
77
+ """
78
+
79
+ def __init__(self, weight_dict: dict[str, tuple[torch.Tensor, TensorProperties]]):
80
+ super().__init__(weight_dict)
81
+
82
+ def get_weight(self, name: str) -> tuple[torch.Tensor, TensorProperties]:
83
+ return self[name]
84
+
85
+ def get_weight_properties(self, name: str) -> TensorProperties:
86
+ return self[name][1]
87
+
88
+
89
+ def get_complete_tensor(
90
+ group: OrderedSet[tuple[str, str]], models_weights: dict[str, Weights]
91
+ ) -> torch.Tensor:
92
+ """
93
+ Given a group of (model_name, weight_name) pairs whose tensors share the same
94
+ underlying storage, return the complete (maximal) tensor covering that storage
95
+ region.
96
+
97
+ This function handles two cases:
98
+
99
+ 1. If any tensor in the group is already marked as complete, return it directly.
100
+ 2. Otherwise, all tensors in the group are assumed to be slices of a larger,
101
+ contiguous tensor backed by the same storage. In this case, reconstruct
102
+ the complete tensor by taking the union of their storage ranges. This assumes
103
+ all tensors in the group have the same dtype.
104
+
105
+ Args:
106
+ group: Set of (model_name, weight_name) tuples identifying tensors that share storage.
107
+ models_weights: Dictionary mapping model names to their Weights objects.
108
+
109
+ Returns:
110
+ The complete tensor (either found directly or reconstructed from slices).
111
+
112
+ Example:
113
+ # Tensors a, b, c share storage:
114
+ # a = full_tensor[0:5] -> start=addr_0, end=addr_5
115
+ # b = full_tensor[3:8] -> start=addr_3, end=addr_8
116
+ # c = full_tensor -> complete tensor
117
+
118
+ # Case 1: If c is in group -> return c
119
+ # Case 2: If only a, b in group -> reconstruct from addr_0 to addr_8
120
+ """
121
+
122
+ if len(group) == 0:
123
+ raise AssertionError("group cannot be empty")
124
+
125
+ start_addr = None
126
+ end_addr = None
127
+ for model_name, weight_name in group:
128
+ tensor_property = models_weights[model_name].get_weight_properties(weight_name)
129
+
130
+ # Case 1: Found a complete tensor.
131
+ if tensor_property.is_complete():
132
+ return models_weights[model_name].get_weight(weight_name)[0]
133
+
134
+ # Case 2: Track the widest boundary across all slices.
135
+ if tensor_property.start is not None:
136
+ start_addr = (
137
+ tensor_property.start
138
+ if start_addr is None
139
+ else min(start_addr, tensor_property.start)
140
+ )
141
+ if tensor_property.end is not None:
142
+ end_addr = (
143
+ tensor_property.end
144
+ if end_addr is None
145
+ else max(end_addr, tensor_property.end)
146
+ )
147
+
148
+ # Case 2: Reconstruct complete tensor from slices.
149
+ # Pick any tensor from the group as a reference (they all share the same storage).
150
+ warnings.warn(
151
+ "No complete tensor found in the group! Returning the first one. "
152
+ "This may cause issues when your weights are not on CPU.",
153
+ stacklevel=2,
154
+ )
155
+
156
+ model_name, weight_name = next(iter(group))
157
+ reference_tensor = models_weights[model_name].get_weight(weight_name)[0]
158
+
159
+ # If no boundary information available (e.g., FakeTensor), return reference tensor as is.
160
+ if start_addr is None and end_addr is None:
161
+ return reference_tensor
162
+
163
+ # Validate that we have both boundaries.
164
+ if start_addr is None or end_addr is None:
165
+ raise AssertionError(
166
+ f"Inconsistent boundary information: start={start_addr}, end={end_addr}. "
167
+ "Unable to reconstruct complete tensor from group."
168
+ )
169
+
170
+ # Reconstruct a view over the full contiguous storage range.
171
+ storage = reference_tensor.untyped_storage()
172
+ total_size_bytes = end_addr - storage.data_ptr()
173
+ element_size = reference_tensor.element_size()
174
+ # It assumes all tensors in the group have the same dtype.
175
+ total_size = total_size_bytes // element_size
176
+
177
+ # Validate alignment: size must be multiples of element_size.
178
+ if total_size_bytes % element_size != 0:
179
+ raise AssertionError(
180
+ f"Total size ({total_size_bytes} bytes) is not aligned with "
181
+ f"element size ({element_size} bytes). Cannot reconstruct tensor safely. "
182
+ f"Expected size to be a multiple of {element_size}."
183
+ )
184
+
185
+ # Reconstruct a tensor that spans the needed storage range, the metadata will be handled separately.
186
+ return torch.tensor(
187
+ [], device=reference_tensor.device, dtype=reference_tensor.dtype
188
+ ).set_(
189
+ storage,
190
+ 0,
191
+ torch.Size([total_size]),
192
+ (),
193
+ )
194
+
195
+
196
+ def group_weights(all_weights: dict[str, Weights]) -> list[OrderedSet[tuple[str, str]]]:
197
+ """
198
+ Group weights that share the same underlying storage.
199
+
200
+ Returns a list of sets, each set contains a tuple of (model_name, weight_name).
201
+ """
202
+
203
+ weights_dict: dict[tuple[int, torch.dtype], OrderedSet[tuple[str, str]]] = (
204
+ collections.defaultdict(OrderedSet)
205
+ ) # (storage_key, dtype) -> set(weight)
206
+
207
+ for model_name, weights in all_weights.items():
208
+ for weight_name, (tensor, properties) in weights.items():
209
+ weights_dict[(properties.storage_ptr, tensor.dtype)].add(
210
+ (model_name, weight_name)
211
+ )
212
+
213
+ return list(weights_dict.values())
.venv/lib/python3.12/site-packages/torch/export/pt2_archive/constants.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Defined in torch/csrc/export/pt2_archive_constants.h
2
+ from torch._C._export import pt2_archive_constants
3
+
4
+
5
+ AOTINDUCTOR_DIR: str = pt2_archive_constants.AOTINDUCTOR_DIR
6
+ ARCHIVE_FORMAT_PATH: str = pt2_archive_constants.ARCHIVE_FORMAT_PATH
7
+ ARCHIVE_FORMAT_VALUE: str = pt2_archive_constants.ARCHIVE_FORMAT_VALUE
8
+ ARCHIVE_ROOT_NAME: str = pt2_archive_constants.ARCHIVE_ROOT_NAME
9
+ ARCHIVE_VERSION_PATH: str = pt2_archive_constants.ARCHIVE_VERSION_PATH
10
+ ARCHIVE_VERSION_VALUE: str = pt2_archive_constants.ARCHIVE_VERSION_VALUE
11
+ CONSTANTS_DIR: str = pt2_archive_constants.CONSTANTS_DIR
12
+ CONSTANTS_CONFIG_FILENAME_FORMAT: str = (
13
+ pt2_archive_constants.CONSTANTS_CONFIG_FILENAME_FORMAT
14
+ )
15
+ CUSTOM_OBJ_FILENAME_PREFIX: str = pt2_archive_constants.CUSTOM_OBJ_FILENAME_PREFIX
16
+ OPAQUE_OBJ_FILENAME_PREFIX: str = pt2_archive_constants.OPAQUE_OBJ_FILENAME_PREFIX
17
+ EXECUTORCH_DIR: str = pt2_archive_constants.EXECUTORCH_DIR
18
+ EXTRA_DIR: str = pt2_archive_constants.EXTRA_DIR
19
+ MODELS_DIR: str = pt2_archive_constants.MODELS_DIR
20
+ MODELS_FILENAME_FORMAT: str = pt2_archive_constants.MODELS_FILENAME_FORMAT
21
+ MODULE_INFO_PATH: str = pt2_archive_constants.MODULE_INFO_PATH
22
+ MTIA_DIR: str = pt2_archive_constants.MTIA_DIR
23
+ SAMPLE_INPUTS_DIR: str = pt2_archive_constants.SAMPLE_INPUTS_DIR
24
+ SAMPLE_INPUTS_FILENAME_FORMAT: str = pt2_archive_constants.SAMPLE_INPUTS_FILENAME_FORMAT
25
+ TENSOR_CONSTANT_FILENAME_PREFIX: str = (
26
+ pt2_archive_constants.TENSOR_CONSTANT_FILENAME_PREFIX
27
+ )
28
+ WEIGHTS_CONFIG_FILENAME_FORMAT: str = (
29
+ pt2_archive_constants.WEIGHTS_CONFIG_FILENAME_FORMAT
30
+ )
31
+ WEIGHT_FILENAME_PREFIX: str = pt2_archive_constants.WEIGHT_FILENAME_PREFIX
32
+ WEIGHTS_DIR: str = pt2_archive_constants.WEIGHTS_DIR
33
+ XL_MODEL_WEIGHTS_DIR: str = pt2_archive_constants.XL_MODEL_WEIGHTS_DIR
34
+ XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = (
35
+ pt2_archive_constants.XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH
36
+ )
.venv/lib/python3.12/site-packages/torch/export/unflatten.py ADDED
@@ -0,0 +1,1909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import abc
3
+ import copy
4
+ import logging
5
+ import operator
6
+ import re
7
+ from collections import defaultdict
8
+ from collections.abc import Callable
9
+ from contextlib import contextmanager
10
+ from copy import deepcopy
11
+ from dataclasses import dataclass
12
+ from enum import Enum
13
+ from typing import Any, cast
14
+
15
+ import torch
16
+ import torch.fx._pytree as fx_pytree
17
+ import torch.utils._pytree as pytree
18
+ from torch._library.fake_class_registry import FakeScriptObject
19
+ from torch._library.opaque_object import is_custom_class_obj
20
+ from torch.export import ExportedProgram
21
+ from torch.export._tree_utils import reorder_kwargs
22
+ from torch.export.exported_program import (
23
+ ConstantArgument,
24
+ ExportGraphSignature,
25
+ InputKind,
26
+ ModuleCallSignature,
27
+ SymBoolArgument,
28
+ SymFloatArgument,
29
+ SymIntArgument,
30
+ TensorArgument,
31
+ )
32
+ from torch.fx._symbolic_trace import is_fx_symbolic_tracing
33
+ from torch.fx.graph_module import _get_attr, _get_attr_via_attr_list, _print_readable
34
+ from torch.utils._pytree import GetAttrKey, SequenceKey
35
+
36
+ from ._remove_effect_tokens_pass import _remove_effect_tokens
37
+
38
+
39
+ log = logging.getLogger(__name__)
40
+
41
+
42
+ __all__ = [
43
+ "FlatArgsAdapter",
44
+ "InterpreterModule",
45
+ "InterpreterModuleDispatcher",
46
+ "UnflattenedModule",
47
+ "unflatten",
48
+ ]
49
+
50
+
51
+ class _AttrKind(Enum):
52
+ PARAMETER = "parameter"
53
+ BUFFER = "buffer"
54
+ CONSTANT = "constant"
55
+ MODULE = "module"
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class _TensorID:
60
+ """Custom tensor identifier containing storage, stride, and size information."""
61
+
62
+ untyped_storage: torch.UntypedStorage
63
+ stride: tuple
64
+ size: tuple
65
+ storage_offset: int
66
+
67
+
68
+ RUN_WITH_INTERPRETER = True
69
+
70
+
71
+ @contextmanager
72
+ def _disable_interpreter():
73
+ global RUN_WITH_INTERPRETER
74
+ old_flag = RUN_WITH_INTERPRETER
75
+ RUN_WITH_INTERPRETER = False
76
+ try:
77
+ yield
78
+ finally:
79
+ RUN_WITH_INTERPRETER = old_flag
80
+
81
+
82
+ # Assign attribute 'from_obj' to the qualified name 'target' on 'to_module
83
+ # This installs empty Modules where none exist yet if they are subpaths of target
84
+ def _assign_attr(
85
+ from_obj: Any,
86
+ to_module: torch.nn.Module,
87
+ target: str,
88
+ attr_kind: _AttrKind,
89
+ persistent: bool = True,
90
+ ):
91
+ *prefix, field = target.split(".")
92
+ # We need to generate all submodules of `to_module` that are at `prefix` and
93
+ # variants of `prefix` that differ only by call name. All of these submodules
94
+ # will then be assigned `from_obj` at `field` so that they can share this attribute.
95
+ # For example, if target is foo.bar.f, foo has another call name foo@1,
96
+ # and bar has other call names bar@1, bar@2, then we will assign f to
97
+ # foo.bar, foo.bar@1, foo.bar@2, foo@1.bar, foo@1.bar@1, foo@1.bar@2.
98
+ to_modules = {to_module}
99
+ for item in prefix:
100
+ ts: set[torch.nn.Module] = set()
101
+ for to_module in to_modules:
102
+ if not hasattr(to_module, item):
103
+ setattr(to_module, item, torch.nn.Module())
104
+ # Collect `item` and every call-name variant `item@N` present in
105
+ # _modules, regardless of contiguity. Export passes (e.g.
106
+ # replace_set_grad_with_hop_pass) can relocate intermediate calls
107
+ # into HOP subgraphs, leaving non-contiguous indices (e.g. base + @3
108
+ # with @1/@2 absent); scanning contiguously from @1 would stop at the
109
+ # gap and never populate the surviving higher-index copies.
110
+ ts.update(
111
+ t_call # type: ignore[misc]
112
+ for k, t_call in to_module._modules.items()
113
+ if _is_call_name(k, item)
114
+ )
115
+ to_modules = ts
116
+
117
+ for to_module in to_modules:
118
+ if attr_kind == _AttrKind.PARAMETER:
119
+ if not isinstance(from_obj, torch.nn.Parameter):
120
+ raise AssertionError(
121
+ f"expected torch.nn.Parameter for PARAMETER attr_kind, got {type(from_obj)}"
122
+ )
123
+ to_module.register_parameter(field, from_obj)
124
+ elif attr_kind == _AttrKind.BUFFER:
125
+ if not isinstance(from_obj, torch.Tensor):
126
+ raise AssertionError(
127
+ f"expected torch.Tensor for BUFFER attr_kind, got {type(from_obj)}"
128
+ )
129
+ to_module.register_buffer(field, from_obj, persistent=persistent)
130
+ elif attr_kind == _AttrKind.CONSTANT:
131
+ if isinstance(from_obj, FakeScriptObject):
132
+ raise AssertionError(
133
+ "FakeScriptObject should only exist during tracing."
134
+ )
135
+ if not isinstance(
136
+ from_obj,
137
+ (
138
+ torch.Tensor,
139
+ torch.ScriptObject,
140
+ ),
141
+ ) and not is_custom_class_obj(from_obj):
142
+ raise AssertionError(
143
+ f"expected torch.Tensor, torch.ScriptObject, or opaque type for CONSTANT attr_kind, got {type(from_obj)}"
144
+ )
145
+ setattr(to_module, field, from_obj)
146
+ elif attr_kind == _AttrKind.MODULE:
147
+ if not isinstance(from_obj, torch.nn.Module):
148
+ raise AssertionError(
149
+ f"expected torch.nn.Module for MODULE attr_kind, got {type(from_obj)}"
150
+ )
151
+ setattr(to_module, field, from_obj)
152
+
153
+
154
+ class _SubmoduleBase:
155
+ _ty: str | None
156
+
157
+ def type_name(self) -> str | None:
158
+ """
159
+ Subclass of this class - InterpreterModule, InterpreterModuleDispatcher, represents
160
+ corresponding model in eager model. To get this type information for those modules
161
+ in eager model we need to use this method.
162
+ """
163
+ return self._ty
164
+
165
+
166
+ class InterpreterModule(_SubmoduleBase, torch.nn.Module):
167
+ """A module that uses torch.fx.Interpreter to execute instead of the usual
168
+ codegen that GraphModule uses. This provides better stack trace information
169
+ and makes it easier to debug execution.
170
+ """
171
+
172
+ graph_module: torch.fx.GraphModule | None
173
+
174
+ def __init__(
175
+ self,
176
+ graph: torch.fx.Graph,
177
+ ty: str | None = None,
178
+ ):
179
+ super().__init__()
180
+ self.graph = graph
181
+ self._ty = ty
182
+ self.graph.owning_module = self # type: ignore[assignment]
183
+ self._run_with_interpreter = RUN_WITH_INTERPRETER
184
+
185
+ def forward(self, *args, **kwargs):
186
+ if self.graph_module is None:
187
+ raise AssertionError("Didn't finalize this InterpreterModule")
188
+ if not is_fx_symbolic_tracing() and (
189
+ torch.compiler.is_dynamo_compiling() or not self._run_with_interpreter
190
+ ):
191
+ # Dynamo cannot trace through torch.fx.Interpreter, so fall back to
192
+ # GraphModule codegen in this instance.
193
+ # Patch the codegened forward to run with this InterpreterModule,
194
+ # so attribute accesses, etc. are on this module instead.
195
+ return type(self.graph_module).forward(self, *args, **kwargs)
196
+ else:
197
+ if kwargs:
198
+ # Handle **kwargs. FX only natively supports positional
199
+ # arguments (through placeholders). So in order to pass in
200
+ # kwargs, we must correspond the names of the placeholders with
201
+ # the keys in the kwarg dict.
202
+ arg_list = list(args)
203
+ kwarg_names = self.arg_names[len(arg_list) :]
204
+ arg_list.extend(
205
+ kwargs[kwarg_name]
206
+ for kwarg_name in kwarg_names
207
+ if kwarg_name in kwargs
208
+ )
209
+
210
+ # Assert that the kwargs passed in exactly match the positional
211
+ # arguments specified by the GraphModule. This should be
212
+ # guaranteed by the unflattening process.
213
+ if len(kwarg_names) != len(kwargs):
214
+ raise AssertionError(
215
+ f"kwarg_names length {len(kwarg_names)} does not match kwargs length {len(kwargs)}"
216
+ )
217
+ if len(arg_list) != len(self.arg_names):
218
+ raise AssertionError(
219
+ f"arg_list length {len(arg_list)} does not match arg_names length {len(self.arg_names)}"
220
+ )
221
+ args = tuple(arg_list)
222
+
223
+ return torch.fx.Interpreter(self, graph=self.graph).run(
224
+ *args, enable_io_processing=False
225
+ )
226
+
227
+ def finalize(self):
228
+ # We need to "finalize" because GraphModule populates its own state_dict
229
+ # based on the get_attrs observed in the graph. So we need to fully
230
+ # construct the graph and call _sink_params before generating this
231
+ # GraphModule.
232
+
233
+ # need to set `graph_module` directly on the dict to avoid it getting
234
+ # registered as a submodule.
235
+ self.__dict__["graph_module"] = torch.fx.GraphModule(self, self.graph)
236
+ self.graph.lint()
237
+
238
+ # Cache arg names for kwarg handling (see forward())
239
+ self.arg_names = []
240
+ for node in self.graph.nodes:
241
+ if node.op == "placeholder":
242
+ self.arg_names.append(node.target)
243
+
244
+ def print_readable(
245
+ self,
246
+ print_output=True,
247
+ include_stride=False,
248
+ include_device=False,
249
+ colored=False,
250
+ ):
251
+ return _print_readable(
252
+ self,
253
+ "InterpreterModule",
254
+ print_output,
255
+ include_stride,
256
+ include_device,
257
+ colored,
258
+ )
259
+
260
+
261
+ class InterpreterModuleDispatcher(_SubmoduleBase, torch.nn.Module):
262
+ """
263
+ A module that carries a sequence of InterpreterModules corresponding to
264
+ a sequence of calls of that module. Each call to the module dispatches
265
+ to the next InterpreterModule, and wraps back around after the last.
266
+ """
267
+
268
+ def __init__(self, attrs: set[str], call_modules: list[InterpreterModule]):
269
+ super().__init__()
270
+ if not call_modules:
271
+ raise AssertionError("call_modules must not be empty")
272
+ self._modules = call_modules[0]._modules
273
+ for accessor in attrs:
274
+ setattr(self, accessor, getattr(call_modules[0], accessor))
275
+ self._ty = call_modules[0]._ty
276
+ self._call_modules = call_modules
277
+ self._num_calls = 0
278
+
279
+ def forward(self, *args, **kwargs):
280
+ call_module = self._call_modules[self._num_calls]
281
+ self._num_calls = (self._num_calls + 1) % len(self._call_modules)
282
+ try:
283
+ return call_module(*args, **kwargs)
284
+ except Exception:
285
+ self._num_calls = 0
286
+ raise
287
+
288
+ def call_modules(self):
289
+ return self._call_modules
290
+
291
+ def print_readable(
292
+ self,
293
+ print_output=True,
294
+ include_stride=False,
295
+ include_device=False,
296
+ colored=False,
297
+ ):
298
+ outputs = [
299
+ mod.print_readable(
300
+ print_output,
301
+ include_stride,
302
+ include_device,
303
+ colored,
304
+ )
305
+ for mod in self._call_modules
306
+ ]
307
+ return "\n".join(outputs)
308
+
309
+
310
+ class FlatArgsAdapter(abc.ABC):
311
+ """
312
+ Adapts input arguments with ``input_spec`` to align ``target_spec``.
313
+ """
314
+
315
+ @abc.abstractmethod
316
+ def adapt(
317
+ self,
318
+ target_spec: pytree.TreeSpec,
319
+ input_spec: pytree.TreeSpec,
320
+ input_args: list[Any],
321
+ metadata: dict[str, Any] | None = None,
322
+ obj: Any | None = None,
323
+ ) -> list[Any]:
324
+ """NOTE: This adapter may mutate given ``input_args_with_path``."""
325
+ ...
326
+
327
+ def get_flat_arg_paths(self) -> list[str]:
328
+ """Returns a list of paths that are used to access the flat args."""
329
+ return []
330
+
331
+
332
+ class UnflattenedModule(_SubmoduleBase, torch.nn.Module):
333
+ def __init__(
334
+ self,
335
+ export_module: ExportedProgram,
336
+ flat_args_adapter: FlatArgsAdapter | None = None,
337
+ ):
338
+ super().__init__()
339
+ if export_module.graph_signature.backward_signature is not None:
340
+ raise ValueError("Unflattening on JointExportModule NYI")
341
+
342
+ def _id(obj):
343
+ """Returns _TensorID dataclass for tensors, otherwise id()."""
344
+ if isinstance(obj, torch.Tensor):
345
+ return _TensorID(
346
+ untyped_storage=obj.untyped_storage(),
347
+ stride=obj.stride(),
348
+ size=obj.size(),
349
+ storage_offset=obj.storage_offset(), # type: ignore[arg-type]
350
+ )
351
+ return id(obj)
352
+
353
+ fqn_list = [entry.fqn for entry in export_module.module_call_graph]
354
+ if fqn_list[0] != "":
355
+ raise AssertionError(
356
+ f"expected first fqn to be empty string, got {fqn_list[0]!r}"
357
+ )
358
+ export_graph = deepcopy(export_module.graph)
359
+ self.graph_signature = deepcopy(export_module.graph_signature)
360
+ self.graph = torch.fx.Graph()
361
+ self.graph.owning_module = self # type: ignore[assignment]
362
+ self.module_call_graph = deepcopy(export_module.module_call_graph)
363
+ self.flat_args_adapter = flat_args_adapter
364
+
365
+ self.meta = export_module.graph_module.meta
366
+ self.meta["unflattened_module"] = self
367
+
368
+ # Flag to indicate whether args have been adapted.
369
+ self.adapted = False
370
+ self._run_with_interpreter = RUN_WITH_INTERPRETER
371
+
372
+ _inplace_buffer_and_input_mutations(export_graph, self.graph_signature)
373
+ _fix_nn_module_stacks(export_graph)
374
+ self._ty = _root_module_type(export_graph)
375
+
376
+ self.ivals = _IVals()
377
+ # for any intermediate value of a mutation that is read, track the mutation
378
+ seen_modules, seen_attrs = _outline_submodules(export_graph, self)
379
+ # for each read intermediate value of a mutation, find where it was created,
380
+ # and perform the mutation
381
+ self.ivals.update(seen_modules.values())
382
+ # move attributes that correspond to graph arguments for HOPs
383
+ # from exported program to unflattened submodules
384
+ _copy_graph_attrs(export_module._graph_module, self, seen_attrs)
385
+
386
+ self.range_constraints = export_module.range_constraints
387
+ self.equality_constraints: list = []
388
+
389
+ # aliasing/unused param or buffer issues:
390
+ # in strict-mode export, dynamo export will deduplicate aliased tensors,
391
+ # and ignore unused tensors. For aliasing, this causes issues when some aliases
392
+ # are unused, and we're unable to match the placeholder node to the correct FQN.
393
+ # This leads to the graph signature potentially having the wrong target FQN,
394
+ # and downstream issues where parameters are assigned to the wrong target attribute,
395
+ # mismatching the relevant placeholder node in the unflattened module.
396
+ # To resolve this we restore (_assign_attr) all aliased/unused tensors in
397
+ # the state_dict as module attributes, but only keep the used tensors in the
398
+ # graph's forward pass (_sink_params).
399
+ state_dict = export_module.state_dict
400
+ assigned_params: set[str] = set() # tracking unused params
401
+ id_to_param: dict[
402
+ int | _TensorID, torch.nn.Parameter
403
+ ] = {} # handling weight-sharing
404
+ for name in self.graph_signature.parameters: # this loop adds used params
405
+ param = state_dict[name]
406
+ if _id(param) not in id_to_param:
407
+ id_to_param[_id(param)] = torch.nn.Parameter(
408
+ param.clone(), requires_grad=param.requires_grad
409
+ )
410
+
411
+ _assign_attr(
412
+ id_to_param[_id(param)],
413
+ self,
414
+ name,
415
+ attr_kind=_AttrKind.PARAMETER,
416
+ )
417
+ assigned_params.add(name)
418
+
419
+ non_persistent_buffers = set(self.graph_signature.non_persistent_buffers)
420
+ assigned_buffers: set[str] = set() # tracking unused buffers
421
+ id_to_buffer: dict[int | _TensorID, tuple[torch.nn.Parameter, bool]] = {}
422
+ for name in self.graph_signature.buffers: # this loop adds used buffers
423
+ if name in non_persistent_buffers:
424
+ persistent = False
425
+ buffer = export_module.constants[name]
426
+ else:
427
+ persistent = True
428
+ buffer = state_dict[name]
429
+
430
+ if _id(buffer) not in id_to_buffer:
431
+ id_to_buffer[_id(buffer)] = (buffer.clone(), persistent)
432
+
433
+ _assign_attr(
434
+ id_to_buffer[_id(buffer)][0],
435
+ self,
436
+ name,
437
+ attr_kind=_AttrKind.BUFFER,
438
+ persistent=persistent,
439
+ )
440
+ assigned_buffers.add(name)
441
+
442
+ # restore aliased/unused params and buffers
443
+ # these appear in state dict but not graph signature
444
+ for name, tensor in state_dict.items():
445
+ if name in assigned_params or name in assigned_buffers: # already assigned
446
+ continue
447
+
448
+ is_buffer = False
449
+ if _id(tensor) in id_to_buffer or not isinstance(
450
+ tensor, torch.nn.Parameter
451
+ ): # aliased buffer
452
+ is_buffer = True
453
+
454
+ if is_buffer:
455
+ if (
456
+ _id(tensor) not in id_to_buffer
457
+ ): # this is completely unused (not weight-sharing)
458
+ id_to_buffer[_id(tensor)] = (
459
+ tensor,
460
+ True,
461
+ ) # assign to respect original model
462
+ _assign_attr(
463
+ id_to_buffer[_id(tensor)][0],
464
+ self,
465
+ name,
466
+ attr_kind=_AttrKind.BUFFER,
467
+ persistent=True,
468
+ )
469
+ else:
470
+ if _id(tensor) not in id_to_param: # this is unused
471
+ id_to_param[_id(tensor)] = tensor
472
+ _assign_attr(
473
+ id_to_param[_id(tensor)],
474
+ self,
475
+ name,
476
+ attr_kind=_AttrKind.PARAMETER,
477
+ )
478
+
479
+ # use id map so we don't double-clone aliased constants
480
+ id_to_const: dict[int | _TensorID, torch.Tensor | torch._C.ScriptObject] = {}
481
+ for fqn, constant in export_module.constants.items():
482
+ if _id(constant) not in id_to_const:
483
+ if isinstance(constant, torch.Tensor):
484
+ constant = constant.clone()
485
+ id_to_const[_id(constant)] = constant
486
+ _constant = id_to_const[_id(constant)]
487
+ _assign_attr(
488
+ _constant,
489
+ self,
490
+ fqn,
491
+ attr_kind=_AttrKind.CONSTANT,
492
+ )
493
+
494
+ # This is to handle parameters/buffers that point to the same tensor
495
+ # object id -> list of (node_name, target_name)
496
+ consts_map: dict[int | _TensorID, list[tuple[str, str]]] = defaultdict(list)
497
+ consts_targets: set[str] = set()
498
+
499
+ def add_to_consts_map(obj_id, node_name, target_name):
500
+ name_list = consts_map[obj_id]
501
+ name_list.append((node_name, target_name))
502
+
503
+ # track aliased/unused params, buffers
504
+ # prefer using untyped_storage() over id() when it's available
505
+ added_params_buffers: set[str] = set()
506
+ for s in self.graph_signature.input_specs:
507
+ if s.kind == InputKind.PARAMETER or (
508
+ s.kind == InputKind.BUFFER and s.persistent
509
+ ):
510
+ if not hasattr(s.arg, "name"):
511
+ raise AssertionError(
512
+ f"expected s.arg to have 'name' attribute, got {type(s.arg)}"
513
+ )
514
+ if not isinstance(s.target, str):
515
+ raise AssertionError(
516
+ f"expected s.target to be str, got {type(s.target)}"
517
+ )
518
+ add_to_consts_map(
519
+ _id(export_module.state_dict[s.target]),
520
+ s.arg.name,
521
+ s.target,
522
+ )
523
+ consts_targets.add(s.target)
524
+ added_params_buffers.add(s.target)
525
+ elif (
526
+ s.kind == InputKind.BUFFER
527
+ and not s.persistent
528
+ or s.kind == InputKind.CONSTANT_TENSOR
529
+ or s.kind == InputKind.CUSTOM_OBJ
530
+ ):
531
+ if not hasattr(s.arg, "name"):
532
+ raise AssertionError(
533
+ f"expected s.arg to have 'name' attribute for kind {s.kind}, got {type(s.arg)}"
534
+ )
535
+ if not isinstance(s.target, str):
536
+ raise AssertionError(
537
+ f"expected s.target to be str for kind {s.kind}, got {type(s.target)}"
538
+ )
539
+ add_to_consts_map(
540
+ _id(export_module.constants[s.target]),
541
+ s.arg.name,
542
+ s.target,
543
+ )
544
+ consts_targets.add(s.target)
545
+
546
+ # add constants that are aliased and don't appear in graph signature
547
+ for const_name, const in export_module.constants.items():
548
+ if const_name not in consts_targets:
549
+ const_id = _id(const)
550
+ if const_id not in consts_map:
551
+ raise AssertionError(
552
+ f"constant {const_name!r} id not found in consts_map"
553
+ )
554
+ ph_name, _ = consts_map[const_id][0]
555
+ add_to_consts_map(const_id, ph_name, const_name)
556
+ added_params_buffers.add(s.target)
557
+
558
+ # add aliased/unused params and buffers that don't appear in graph signature
559
+ for fqn, tensor in export_module.state_dict.items():
560
+ if fqn not in added_params_buffers:
561
+ tensor_id = _id(tensor)
562
+ if tensor_id not in consts_map:
563
+ # completely unused (no weight-sharing), ignore.
564
+ # this weight doesn't appear in graph module,
565
+ # so won't cause FQN assignment issues
566
+ continue
567
+ ph_name, _ = consts_map[tensor_id][0]
568
+ add_to_consts_map(tensor_id, ph_name, fqn)
569
+
570
+ # node name -> list of possible targets
571
+ inputs_to_state: dict[str, list[str]] = {}
572
+ for node_target in consts_map.values():
573
+ targets = [t[1] for t in node_target]
574
+ for n, _ in node_target:
575
+ inputs_to_state[n] = targets
576
+
577
+ _sink_params(self, inputs_to_state, [])
578
+
579
+ redirected_call_indices = _deduplicate_modules(seen_modules.values())
580
+ fqn_list = [fqn for fqn in fqn_list if fqn not in redirected_call_indices]
581
+
582
+ self._dispatch_modules(redirected_call_indices, consts_targets)
583
+ fqn_list = [fqn for fqn in fqn_list if "@" not in fqn]
584
+
585
+ # Cache so we don't have to compute this every time.
586
+ # NOTE: this needs to be kept in sync with the placeholders in
587
+ # self.graph, but currently we have no way to guarantee that.
588
+ self.input_placeholders = [
589
+ node for node in self.graph.nodes if node.op == "placeholder"
590
+ ]
591
+ self.check_input_constraints = True
592
+ # TODO(zhxchen17) We can register modules ahead of time instead of reorder later.
593
+ fqn_order = {fqn: i for i, fqn in enumerate(fqn_list)}
594
+ # In the case of legacy IR, we might be missing some modules from metadata.
595
+ for name, _ in self.named_modules(remove_duplicate=False):
596
+ if name not in fqn_order:
597
+ fqn_order[name] = len(fqn_order)
598
+ _reorder_submodules(self, fqn_order)
599
+ self.graph.lint()
600
+ self.finalize()
601
+
602
+ def _print_graph(self):
603
+ for fqn, mod in self.named_modules():
604
+ print(fqn + ":")
605
+ if hasattr(mod, "graph") and isinstance(mod.graph, torch.fx.Graph):
606
+ print(mod.graph)
607
+
608
+ def _adapt_flat_args(self, flat_args, in_spec, input):
609
+ signature = self.module_call_graph[0].signature
610
+ if in_spec == signature.in_spec:
611
+ return flat_args
612
+
613
+ if self.flat_args_adapter is None:
614
+ raise TypeError(
615
+ "There is no flat args adapter specified. "
616
+ "Are you sure you are calling this with the right arguments? "
617
+ )
618
+ else:
619
+ flat_args = self.flat_args_adapter.adapt(
620
+ target_spec=signature.in_spec,
621
+ input_spec=in_spec,
622
+ input_args=flat_args,
623
+ metadata=self.meta,
624
+ obj=input,
625
+ )
626
+
627
+ if len(flat_args) != signature.in_spec.num_leaves:
628
+ raise TypeError(
629
+ f"Flat args adaption failed, number of args mismatch "
630
+ f"Adapted: {len(flat_args)} \n"
631
+ f"Exported module: {signature.in_spec.num_leaves}"
632
+ )
633
+ return flat_args
634
+
635
+ def process_forward_inputs(self, *args, **kwargs):
636
+ signature = self.module_call_graph[0].signature
637
+
638
+ reordered_kwargs = kwargs
639
+ if kwargs:
640
+ reordered_kwargs = reorder_kwargs(kwargs, signature.in_spec)
641
+
642
+ flat_args_with_path, in_spec = pytree.tree_flatten_with_path(
643
+ (args, reordered_kwargs)
644
+ )
645
+ flat_args = [x[1] for x in flat_args_with_path]
646
+
647
+ if is_fx_symbolic_tracing():
648
+ return flat_args
649
+
650
+ if in_spec != signature.in_spec:
651
+ if not self.adapted:
652
+ print(
653
+ "Input treespec does not match with exported module's: \n"
654
+ f"Input treespec: {in_spec}. ",
655
+ f"Exported module treespec: {signature.in_spec}",
656
+ )
657
+ print("Adapting flat arg to match exported module's treespec")
658
+ flat_args = self._adapt_flat_args(flat_args, in_spec, args)
659
+ self.adapted = True
660
+
661
+ if self.check_input_constraints:
662
+ # Import here to avoid an unfortunate circular dependency.
663
+ # TODO(suo): untangle this.
664
+ from torch._export.utils import _check_input_constraints_for_graph
665
+
666
+ if self.adapted is True:
667
+ flat_arg_paths = (
668
+ self.flat_args_adapter.get_flat_arg_paths()
669
+ if self.flat_args_adapter
670
+ else []
671
+ )
672
+ if flat_arg_paths and len(flat_arg_paths) != len(flat_args):
673
+ raise AssertionError(
674
+ f"flat_arg_paths length {len(flat_arg_paths)} does not match flat_args length {len(flat_args)}"
675
+ )
676
+ new_flat_args_with_path = [ # type: ignore[var-annotated]
677
+ (
678
+ (
679
+ SequenceKey(idx=idx),
680
+ GetAttrKey(
681
+ name=flat_arg_paths[idx]
682
+ if flat_arg_paths
683
+ else "<unknown location>"
684
+ ),
685
+ ),
686
+ arg,
687
+ )
688
+ for idx, arg in enumerate(flat_args)
689
+ ]
690
+ else:
691
+ new_flat_args_with_path = flat_args_with_path # type: ignore[assignment]
692
+
693
+ _check_input_constraints_for_graph(
694
+ self.input_placeholders, new_flat_args_with_path, self.range_constraints
695
+ )
696
+
697
+ return flat_args
698
+
699
+ def forward(self, *args, **kwargs):
700
+ flat_args = self.process_forward_inputs(*args, **kwargs)
701
+ signature = self.module_call_graph[0].signature
702
+
703
+ if is_fx_symbolic_tracing():
704
+ return_val = torch.fx.Interpreter(self, graph=self.graph).run(
705
+ *flat_args, enable_io_processing=False
706
+ )
707
+ # For scalar return value, fx.Graph wraps in a tuple
708
+ if isinstance(return_val, tuple) and len(return_val) == 1:
709
+ return return_val[0]
710
+ return return_val
711
+
712
+ if torch.compiler.is_dynamo_compiling() or not self._run_with_interpreter:
713
+ tree_out = type(self.graph_module).forward(self, *flat_args) # type: ignore[union-attr]
714
+ else:
715
+ tree_out = torch.fx.Interpreter(self, graph=self.graph).run(
716
+ *flat_args, enable_io_processing=False
717
+ )
718
+ return pytree.tree_unflatten(tree_out, signature.out_spec)
719
+
720
+ def finalize(self):
721
+ self.__dict__["graph_module"] = torch.fx.GraphModule(self, self.graph)
722
+ self.graph.lint()
723
+
724
+ def _dispatch_modules(self, redirected_call_indices, consts_targets):
725
+ """For a module whose call signatures are preserved, replace
726
+ multiple modules corresponding to multiple calls to that module
727
+ with a single dispatcher module that tracks which module to call.
728
+ """
729
+
730
+ # for each fqn whose module call signature is preserved,
731
+ # map that fqn to a list of called modules
732
+ called_modules = defaultdict(list)
733
+ for entry in self.module_call_graph:
734
+ if entry.fqn and entry.signature:
735
+ # some modules were removed and their fqns redirected to other
736
+ # fqns during deduplication
737
+ fqn = entry.fqn
738
+ mod = _get_attr(self, redirected_call_indices.get(fqn, fqn))
739
+ base, idx = fqn.split("@") if "@" in fqn else [fqn, "0"]
740
+ called_modules[base].append((int(idx), mod))
741
+
742
+ attrs_map = defaultdict(set)
743
+ for target in consts_targets:
744
+ if "." in target:
745
+ orig_fqn, name = target.rsplit(".", 1)
746
+ attrs_map[orig_fqn].add(name)
747
+ else:
748
+ attrs_map[""].add(target)
749
+
750
+ # replace multiple call modules with a single dispatcher module
751
+ for orig_fqn, indexed_call_modules in called_modules.items():
752
+ call_modules = [mod for _, mod in sorted(indexed_call_modules)]
753
+ if len(call_modules) > 1:
754
+ for i in range(len(call_modules)):
755
+ fqn = _call_name(orig_fqn, i + 1)
756
+ if fqn not in redirected_call_indices:
757
+ *prefix, name = fqn.split(".")
758
+ _get_attr_via_attr_list(self, prefix)._modules.pop(name)
759
+ self.set_submodule(
760
+ orig_fqn,
761
+ InterpreterModuleDispatcher(attrs_map[orig_fqn], call_modules),
762
+ )
763
+
764
+ # elide call indices in call modules because they are
765
+ # tracked automatically inside the dispatcher module
766
+ def elide_call_indices(prefix, graph):
767
+ for node in graph.nodes:
768
+ if node.op == "call_module":
769
+ fqn = node.target.split("@")[0]
770
+ path = f"{prefix}.{fqn}" if prefix else fqn
771
+ if path in called_modules:
772
+ node.target = fqn
773
+
774
+ for fqn, mod in self.named_modules(remove_duplicate=False):
775
+ if hasattr(mod, "graph"):
776
+ elide_call_indices(fqn, mod.graph)
777
+ elif hasattr(mod, "_call_modules"):
778
+ for mod_ in mod._call_modules:
779
+ if not hasattr(mod_, "graph"):
780
+ raise AssertionError(
781
+ f"expected mod_ to have 'graph' attribute, got {type(mod_)}"
782
+ )
783
+ elide_call_indices(fqn, mod_.graph)
784
+
785
+ def print_readable(
786
+ self,
787
+ print_output=True,
788
+ include_stride=False,
789
+ include_device=False,
790
+ colored=False,
791
+ ):
792
+ return _print_readable(
793
+ self,
794
+ "UnflattenedModule",
795
+ print_output,
796
+ include_stride,
797
+ include_device,
798
+ colored,
799
+ )
800
+
801
+
802
+ def unflatten(
803
+ module: ExportedProgram, flat_args_adapter: FlatArgsAdapter | None = None
804
+ ) -> UnflattenedModule:
805
+ """Unflatten an ExportedProgram, producing a module with the same module
806
+ hierarchy as the original eager module. This can be useful if you are trying
807
+ to use :mod:`torch.export` with another system that expects a module
808
+ hierarchy instead of the flat graph that :mod:`torch.export` usually produces.
809
+
810
+ .. note:: The args/kwargs of unflattened modules will not necessarily match
811
+ the eager module, so doing a module swap (e.g. :code:`self.submod =
812
+ new_mod`) will not necessarily work. If you need to swap a module out, you
813
+ need to set the :code:`preserve_module_call_signature` parameter of
814
+ :func:`torch.export.export`.
815
+
816
+ Args:
817
+ module (ExportedProgram): The ExportedProgram to unflatten.
818
+ flat_args_adapter (Optional[FlatArgsAdapter]): Adapt flat args if input TreeSpec does not match with exported module's.
819
+
820
+ Returns:
821
+ An instance of :class:`UnflattenedModule`, which has the same module
822
+ hierarchy as the original eager module pre-export.
823
+ """
824
+ module = _remove_effect_tokens(module)
825
+ m = UnflattenedModule(module, flat_args_adapter)
826
+
827
+ # Disable process_forward_inputs as the adapter has many
828
+ # non-dynamo-traceable behavior.
829
+ m.process_forward_inputs = torch._dynamo.disable( # type: ignore[method-assign]
830
+ m.process_forward_inputs,
831
+ reason="do not trace into preprocessing the inputs",
832
+ recursive=True,
833
+ )
834
+
835
+ return m
836
+
837
+
838
+ def _inplace_buffer_and_input_mutations(
839
+ graph: torch.fx.Graph,
840
+ graph_signature: ExportGraphSignature,
841
+ ) -> None:
842
+ """Transform buffer and input mutations from their functionalized form
843
+ into copy_ nodes in the graph.
844
+
845
+ Functionalization represents a buffer mutation by passing the buffer as
846
+ an input and output. For example, consider the eager code:
847
+ def forward(self, x):
848
+ self.buffer += x
849
+ return x * x
850
+
851
+ This corresponds to a graph that looks like:
852
+ def forward(self, buffer, x):
853
+ mutated_buffer = aten.add(buffer, x)
854
+ mul = aten.mul(x, x)
855
+ return (mutated_buffer, mul)
856
+
857
+ We want to inplace this into something that looks like the original
858
+ eager code:
859
+ def forward(self, buffer, x):
860
+ mutated_buffer = aten.add(buffer, x)
861
+ buffer.copy_(mutated_buffer)
862
+ mul = aten.mul(x, x)
863
+ return (mul,)
864
+
865
+ Input mutations are handled similarly.
866
+ """
867
+ output_node = next(iter(reversed(graph.nodes)))
868
+ if output_node.op != "output" or len(output_node.args) != 1:
869
+ raise AssertionError(
870
+ f"expected output node with op='output' and 1 arg, got op={output_node.op!r} with {len(output_node.args)} args"
871
+ )
872
+ return_args = output_node.args[0]
873
+
874
+ input_name_to_node = {
875
+ node.name: node for node in graph.nodes if node.op == "placeholder"
876
+ }
877
+ mutation_name_to_input_name = {}
878
+
879
+ # Collect mutated buffers.
880
+ buffer_fqn_to_input_name = {
881
+ buffer_fqn: k for k, buffer_fqn in graph_signature.inputs_to_buffers.items()
882
+ }
883
+ mutation_name_to_input_name = {
884
+ k: buffer_fqn_to_input_name[buffer_fqn]
885
+ for k, buffer_fqn in graph_signature.buffers_to_mutate.items()
886
+ }
887
+ # Collect mutated user inputs.
888
+ mutation_name_to_input_name.update(graph_signature.user_inputs_to_mutate)
889
+
890
+ num_mutations = len(mutation_name_to_input_name)
891
+
892
+ for mutation in return_args[:num_mutations]:
893
+ input_name = mutation_name_to_input_name[mutation.name]
894
+ input_node = input_name_to_node[input_name]
895
+
896
+ with graph.inserting_after(mutation):
897
+ # Create a copy_ node that inplaces the mutation.
898
+ new_node = graph.create_node(
899
+ "call_function", torch.ops.aten.copy_.default, (input_node, mutation)
900
+ )
901
+ for k, v in mutation.meta.items():
902
+ new_node.meta[k] = v
903
+ # Replace all uses of the previously functional mutation with
904
+ # our copy_ node.
905
+ mutation.replace_all_uses_with(new_node, lambda x: x is not new_node)
906
+
907
+ # Remove the mutated buffer / input from the graph outputs, since we don't
908
+ # need to thread it through anymore.
909
+ user_outputs = tuple(return_args[num_mutations:])
910
+ output_node.args = ((user_outputs),)
911
+
912
+
913
+ def _root_module_type(graph: torch.fx.Graph) -> str | None:
914
+ for node in graph.nodes:
915
+ if "nn_module_stack" not in node.meta:
916
+ continue
917
+
918
+ for path, ty in node.meta["nn_module_stack"].values():
919
+ if not path:
920
+ return ty
921
+ return None
922
+
923
+
924
+ def _fix_nn_module_stacks(graph):
925
+ # For each nn module stack in the graph, check if the fqns in it represent a stack:
926
+ # 1. Each fqn must be a prefix of the next fqn.
927
+ # 2. If not, remove the entries starting from the next fqn, emitting a warning.
928
+ for node in graph.nodes:
929
+ if "nn_module_stack" not in node.meta:
930
+ continue
931
+
932
+ nn_module_stack = node.meta["nn_module_stack"]
933
+ fqns = [
934
+ fqn.split("@")[0] if "@" in fqn else fqn
935
+ for fqn, _t in nn_module_stack.values()
936
+ ]
937
+
938
+ # Check if each FQN is a prefix of the next one
939
+ prev_fqn, *next_fqns = fqns
940
+ num_valid_indices = 1 # root FQN
941
+ for curr_fqn in next_fqns:
942
+ # Check if the previous FQN is a prefix of the current one
943
+ if _is_prefix(prev_fqn, curr_fqn):
944
+ num_valid_indices += 1
945
+ prev_fqn = curr_fqn
946
+ else:
947
+ # Found a non-prefix FQN, stop here
948
+ break
949
+
950
+ # If we need to remove entries, create a new stack with only valid entries
951
+ if num_valid_indices < len(nn_module_stack):
952
+ log.warning(
953
+ "nn_module_stack fqns %s at node %s do not form a stack! dropping last %d entries",
954
+ fqns,
955
+ node,
956
+ len(nn_module_stack) - num_valid_indices,
957
+ )
958
+ node.meta["nn_module_stack"] = dict(
959
+ list(nn_module_stack.items())[:num_valid_indices]
960
+ )
961
+
962
+
963
+ def _is_prefix(candidate, target):
964
+ """Check whether `candidate` is a prefix of `target`."""
965
+ return len(candidate) < len(target) and target[: len(candidate)] == candidate
966
+
967
+
968
+ def _compute_accessor(parent_fqn: str, child_fqn: str) -> str:
969
+ if parent_fqn == "":
970
+ # Handle the root module correctly.
971
+ return child_fqn
972
+
973
+ parent_split = parent_fqn.split(".")
974
+ child_split = child_fqn.split(".")
975
+
976
+ # TODO: support skip connection by inlining the child module.
977
+ if child_split[: len(parent_split)] != parent_split:
978
+ raise RuntimeError(
979
+ f"Child module '{child_fqn}' is not a descendant of parent module '{parent_fqn}'."
980
+ "This is currently unsupported."
981
+ "Please try to make child module attach to parent module directly."
982
+ )
983
+ return ".".join(child_split[len(parent_split) :])
984
+
985
+
986
+ def _check_graph_equivalence(x: torch.nn.Module, y: torch.nn.Module):
987
+ def graph_dump(graph: torch.fx.Graph) -> str:
988
+ ret = []
989
+ nodes_idx: dict[int, int] = {}
990
+
991
+ def arg_dump(arg) -> str:
992
+ if isinstance(arg, torch.fx.Node):
993
+ return "%" + str(nodes_idx[id(arg)])
994
+ return str(arg)
995
+
996
+ for i, node in enumerate(graph.nodes):
997
+ args_dump = [str(arg) for arg in pytree.tree_map(arg_dump, node.args)]
998
+ args_dump += [
999
+ f"{key}={value}"
1000
+ for key, value in pytree.tree_map(arg_dump, node.kwargs).items()
1001
+ ]
1002
+ target = node.target if node.op in ("call_function", "get_attr") else ""
1003
+ # pyrefly: ignore [bad-argument-type]
1004
+ ret.append(f"{i}: {node.op}[{target}]({', '.join(args_dump)})")
1005
+ nodes_idx[id(node)] = i
1006
+ return "\n".join(ret)
1007
+
1008
+ if not isinstance(x.graph, torch.fx.Graph):
1009
+ raise AssertionError(
1010
+ f"expected x.graph to be torch.fx.Graph, got {type(x.graph)}"
1011
+ )
1012
+ if not isinstance(y.graph, torch.fx.Graph):
1013
+ raise AssertionError(
1014
+ f"expected y.graph to be torch.fx.Graph, got {type(y.graph)}"
1015
+ )
1016
+ return graph_dump(x.graph) == graph_dump(y.graph)
1017
+
1018
+
1019
+ def _add_spec(gm: torch.nn.Module, spec) -> str:
1020
+ i = 0
1021
+ while hasattr(gm, f"_spec_{i}"):
1022
+ i += 1
1023
+ name = f"_spec_{i}"
1024
+ setattr(gm, name, spec)
1025
+ return name
1026
+
1027
+
1028
+ def _generate_flatten(gm: torch.fx.GraphModule, node) -> torch.fx.Node:
1029
+ flatten = gm.graph.call_function(pytree.tree_flatten, (node,))
1030
+ getitem_0 = gm.graph.call_function(operator.getitem, (flatten, 0))
1031
+ return getitem_0
1032
+
1033
+
1034
+ def _generate_flatten_spec(
1035
+ gm: torch.fx.GraphModule | InterpreterModule | UnflattenedModule, node, spec
1036
+ ) -> torch.fx.Node:
1037
+ name = _add_spec(gm, spec)
1038
+ spec_node = gm.graph.get_attr(name)
1039
+ return gm.graph.call_function(fx_pytree.tree_flatten_spec, (node, spec_node))
1040
+
1041
+
1042
+ def _generate_unflatten(
1043
+ gm: torch.fx.GraphModule | InterpreterModule | UnflattenedModule, nodes, spec
1044
+ ) -> torch.fx.Node:
1045
+ name = _add_spec(gm, spec)
1046
+ spec_node = gm.graph.get_attr(name)
1047
+ return gm.graph.call_function(pytree.tree_unflatten, (nodes, spec_node))
1048
+
1049
+
1050
+ def _get_submodule(mod: torch.nn.Module, target: str):
1051
+ *prefix, field = target.split(".")
1052
+
1053
+ for item in prefix:
1054
+ submod = getattr(mod, item, None)
1055
+
1056
+ if submod is None:
1057
+ return None
1058
+
1059
+ if not isinstance(submod, torch.nn.Module):
1060
+ return None
1061
+
1062
+ mod = submod
1063
+
1064
+ return getattr(mod, field, None)
1065
+
1066
+
1067
+ def _add_submodule(
1068
+ mod: torch.nn.Module,
1069
+ target: str,
1070
+ module_to_add: torch.nn.Module,
1071
+ create_module: Callable[[str], torch.nn.Module] | None = None,
1072
+ ):
1073
+ *prefix, field = target.split(".")
1074
+
1075
+ for i, item in enumerate(prefix):
1076
+ submod = getattr(mod, item, None)
1077
+
1078
+ if submod is None:
1079
+ if create_module is not None:
1080
+ submod = create_module(".".join(prefix[: i + 1]))
1081
+ else:
1082
+ submod = torch.nn.Module()
1083
+ setattr(mod, item, submod)
1084
+
1085
+ if not isinstance(submod, torch.nn.Module):
1086
+ return False
1087
+
1088
+ mod = submod
1089
+
1090
+ mod.add_module(field, module_to_add)
1091
+
1092
+
1093
+ def _call_name(base: str, n: int) -> str:
1094
+ # Given n >= 0, generate call names to a submodule `base` of the form
1095
+ # `base`, `base@1`, `base@2`, etc.
1096
+ return base if n == 1 else f"{base}@{n - 1}"
1097
+
1098
+
1099
+ def _is_call_name(call_name: str, base: str) -> bool:
1100
+ # Recognize when call_name = _call_name(base, n) for some n >= 0.
1101
+ return re.match(re.escape(base) + r"(@\d+)?$", call_name) is not None
1102
+
1103
+
1104
+ class _ModuleFrame:
1105
+ def __init__(
1106
+ self,
1107
+ flat_graph: torch.fx.Graph,
1108
+ nodes: tuple[torch.fx.Node, ...],
1109
+ seen_nodes,
1110
+ seen_modules,
1111
+ seen_attrs,
1112
+ created_modules,
1113
+ parent,
1114
+ module_stack: list[tuple[str, str | None, int]],
1115
+ module_id,
1116
+ module_call_graph: dict[str, ModuleCallSignature],
1117
+ module: torch.fx.GraphModule | UnflattenedModule | None = None,
1118
+ ):
1119
+ self.flat_graph = flat_graph
1120
+ self.nodes = nodes
1121
+ self.seen_nodes = seen_nodes
1122
+ self.seen_modules = seen_modules
1123
+ self.seen_attrs = seen_attrs
1124
+ self.created_modules = created_modules
1125
+ self.parent = parent
1126
+ self.module_stack = module_stack
1127
+ self.module_id = module_id
1128
+
1129
+ self.module_call_graph = module_call_graph
1130
+ self.verbose = False
1131
+
1132
+ self.fqn, ty, num_calls = self.module_stack[-1]
1133
+ # generate call name for self.fqn
1134
+ self.child_fqn = _call_name(self.fqn, num_calls + 1)
1135
+
1136
+ self.module: torch.fx.GraphModule | UnflattenedModule | InterpreterModule
1137
+ if module is not None:
1138
+ self.module = module
1139
+ self.ivals = module.ivals if hasattr(module, "ivals") else {} # type: ignore[var-annotated]
1140
+ else:
1141
+ self.module = self.created_modules.get(
1142
+ self.fqn,
1143
+ InterpreterModule(torch.fx.Graph(), ty=ty),
1144
+ )
1145
+ self.ivals = parent.ivals
1146
+
1147
+ self.graph = self.module.graph
1148
+
1149
+ # Mapping of nodes in the flat graph to nodes in this graph.
1150
+ self.node_map: dict[torch.fx.Node, torch.fx.Node] = {}
1151
+ self.node_to_placeholder = {}
1152
+
1153
+ self.parent_call_module: torch.fx.Node | None = None
1154
+ if parent is not None:
1155
+ accessor = _compute_accessor(parent.fqn, self.child_fqn)
1156
+
1157
+ def create_module(fqn):
1158
+ path = f"{parent.fqn}.{fqn}" if parent.fqn else fqn
1159
+ if path in self.created_modules:
1160
+ return self.created_modules[path]
1161
+ submod = InterpreterModule(torch.fx.Graph(), ty=ty)
1162
+ self.created_modules[path] = submod
1163
+ return submod
1164
+
1165
+ _add_submodule(parent.module, accessor, self.module, create_module)
1166
+ self.parent_call_module = parent.graph.call_module(accessor)
1167
+ if self.seen_modules[self.module_id]:
1168
+ base_module_frame = self.seen_modules[self.module_id][0]
1169
+ self.module._modules = base_module_frame.module._modules
1170
+ self.seen_modules[self.module_id].append(
1171
+ _SubmoduleEntry(
1172
+ parent_fqn=self.parent.fqn,
1173
+ parent_module=self.parent.module,
1174
+ parent_call_module=self.parent_call_module,
1175
+ fqn=self.fqn,
1176
+ call_idx=num_calls + 1,
1177
+ module=self.module,
1178
+ )
1179
+ )
1180
+
1181
+ signature = module_call_graph.get(self.child_fqn)
1182
+ if signature is not None and self.parent is not None:
1183
+ if signature.in_spec.num_children != 2:
1184
+ raise AssertionError(
1185
+ f"expected in_spec to have 2 children, got {signature.in_spec.num_children}"
1186
+ )
1187
+ if signature.in_spec.type is not tuple:
1188
+ raise AssertionError(
1189
+ f"expected in_spec.type to be tuple, got {signature.in_spec.type}"
1190
+ )
1191
+ args_spec, kwargs_spec = signature.in_spec.children()
1192
+ if args_spec.type is not tuple:
1193
+ raise AssertionError(
1194
+ f"expected args_spec.type to be tuple, got {args_spec.type}"
1195
+ )
1196
+ if kwargs_spec.type is not dict:
1197
+ raise AssertionError(
1198
+ f"expected kwargs_spec.type to be dict, got {kwargs_spec.type}"
1199
+ )
1200
+
1201
+ with self.graph.inserting_after(None):
1202
+ arg_nodes = [
1203
+ self.graph.placeholder(f"_positional_arg_{idx}")
1204
+ for idx in range(args_spec.num_children)
1205
+ ]
1206
+ kwarg_nodes = {}
1207
+ for name in kwargs_spec.context:
1208
+ kwarg_nodes[name] = self.graph.placeholder(name)
1209
+ flat_args = _generate_flatten_spec(
1210
+ self.module,
1211
+ (tuple(arg_nodes), kwarg_nodes),
1212
+ signature.in_spec,
1213
+ )
1214
+ for idx, arg in enumerate(signature.inputs):
1215
+ flat_arg_node = self.graph.create_node(
1216
+ op="call_function",
1217
+ target=operator.getitem,
1218
+ args=(flat_args, idx),
1219
+ name=(
1220
+ arg.name
1221
+ if not isinstance(arg, ConstantArgument)
1222
+ else f"_constant_{idx}"
1223
+ ),
1224
+ )
1225
+ if isinstance(arg, ConstantArgument):
1226
+ continue
1227
+
1228
+ if arg.name in self.seen_nodes:
1229
+ flat_arg_node.meta = copy.copy(self.seen_nodes[arg.name].meta)
1230
+ self.node_to_placeholder[self.seen_nodes[arg.name]] = (
1231
+ flat_arg_node
1232
+ )
1233
+
1234
+ with self.parent.graph.inserting_before(self.parent_call_module):
1235
+ input_nodes: list[torch.fx.Node | None] = []
1236
+ for input in signature.inputs:
1237
+ if isinstance(input, ConstantArgument):
1238
+ input_nodes.append(input.value) # type: ignore[arg-type]
1239
+ elif input.name not in self.seen_nodes:
1240
+ input_nodes.append(None)
1241
+ else:
1242
+ if not isinstance(
1243
+ input,
1244
+ (
1245
+ TensorArgument,
1246
+ SymIntArgument,
1247
+ SymBoolArgument,
1248
+ SymFloatArgument,
1249
+ ),
1250
+ ):
1251
+ raise AssertionError(
1252
+ f"expected input to be TensorArgument, SymIntArgument, "
1253
+ f"SymBoolArgument, or SymFloatArgument, got {type(input)}"
1254
+ )
1255
+ input_nodes.append(
1256
+ self.parent.remap_input(self.seen_nodes[input.name])
1257
+ )
1258
+
1259
+ inputs_node = _generate_unflatten(
1260
+ self.parent.module,
1261
+ input_nodes,
1262
+ signature.in_spec,
1263
+ )
1264
+
1265
+ args_node = self.parent.graph.call_function(
1266
+ operator.getitem, (inputs_node, 0)
1267
+ )
1268
+ kwargs_node = self.parent.graph.call_function(
1269
+ operator.getitem, (inputs_node, 1)
1270
+ )
1271
+ arg_nodes = [
1272
+ self.parent.graph.call_function(operator.getitem, (args_node, i))
1273
+ for i in range(args_spec.num_children)
1274
+ ]
1275
+ kwarg_nodes = {
1276
+ k: self.parent.graph.call_function(
1277
+ operator.getitem, (kwargs_node, k)
1278
+ )
1279
+ for k in kwargs_spec.context
1280
+ }
1281
+ if self.parent_call_module is None:
1282
+ raise AssertionError("parent_call_module must not be None")
1283
+ # pyrefly: ignore [bad-assignment]
1284
+ self.parent_call_module.args = tuple(arg_nodes)
1285
+ self.parent_call_module.kwargs = kwarg_nodes # type: ignore[assignment]
1286
+
1287
+ def add_placeholder(self, x):
1288
+ if self.fqn == "":
1289
+ raise AssertionError(f"Cannot add placeholder {x} to root module")
1290
+ if x.graph is not self.flat_graph:
1291
+ raise AssertionError(
1292
+ "expected x.graph to be flat_graph, got different graph"
1293
+ )
1294
+ # x is not in subgraph, create a new placeholder for subgraph
1295
+ with self.graph.inserting_before(None):
1296
+ placeholder_node = self.graph.placeholder(x.name, type_expr=x.type)
1297
+ # copy all meta fields, even if some fields might be irrelevant for
1298
+ # the placeholder node
1299
+ placeholder_node.meta = copy.copy(x.meta)
1300
+ self.node_to_placeholder[x] = placeholder_node
1301
+
1302
+ def copy_sym_call_function(self, x):
1303
+ # This only exists because we deduplicate sym_size nodes in the flat export graph,
1304
+ # and if preserve_module_call_signature is set, we may not be able to pass sym_size
1305
+ # nodes, or their downstream users, as inputs to submodule calls.
1306
+ # To avoid this we copy these call_function nodes with sym_type results.
1307
+ # This should however only be done for sym_type nodes - call_function nodes on tensors
1308
+ # should not be deduplicated in the first place.
1309
+ args = pytree.tree_map_only(torch.fx.Node, self.remap_input, x.args)
1310
+ kwargs = pytree.tree_map_only(torch.fx.Node, self.remap_input, x.kwargs)
1311
+ node = self.graph.call_function(x.target, args, kwargs)
1312
+ node.meta = copy.copy(x.meta)
1313
+ self.node_map[x] = node
1314
+ return node
1315
+
1316
+ def remap_input(self, x):
1317
+ if x.graph is not self.flat_graph:
1318
+ raise AssertionError(
1319
+ "expected x.graph to be flat_graph, got different graph"
1320
+ )
1321
+ if x in self.node_map:
1322
+ return self.node_map[x]
1323
+ self.print(f"remap_input({x})")
1324
+ if x in self.node_to_placeholder:
1325
+ return self.node_to_placeholder[x]
1326
+ elif (
1327
+ x.op == "placeholder" or self.module_call_graph.get(self.fqn) is None
1328
+ # allow placeholder creation if we are not preserving module call signature
1329
+ ):
1330
+ self.add_placeholder(x)
1331
+ if self.parent_call_module is not None:
1332
+ # Important to *prepend* the output to match how we are
1333
+ # inserting placeholder nodes.
1334
+ with self.parent.graph.inserting_before(self.parent_call_module):
1335
+ self.parent_call_module.insert_arg(0, self.parent.remap_input(x))
1336
+ return self.node_to_placeholder[x]
1337
+ elif x.op == "call_function" and (
1338
+ x.target
1339
+ in (
1340
+ torch.ops.aten.sym_size.int,
1341
+ torch.ops.aten.item.default,
1342
+ torch.ops.aten.unbind.int,
1343
+ torch.ops.aten.sum.dim_IntList,
1344
+ torch.ops.aten.view.default,
1345
+ torch.ops.aten.diff.default,
1346
+ )
1347
+ or (hasattr(x.target, "__module__") and x.target.__module__ == "_operator")
1348
+ ):
1349
+ # export deduplicates sym_size nodes, and may need to re-copy them
1350
+ # if module call signature needs to be preserved
1351
+ self.copy_sym_call_function(x)
1352
+ return self.node_map[x]
1353
+ elif self.module_call_graph.get(self.fqn) is not None:
1354
+ # x is reading the intermediate value of a mutation, so record it;
1355
+ # later we will find where it was created and perform the update
1356
+ return self.ivals.read(self, x) # type: ignore[operator, union-attr]
1357
+ else:
1358
+ raise RuntimeError(
1359
+ f"Could not run remap_input() on op type: {x.op} for node {x}"
1360
+ )
1361
+
1362
+ def uplift_common_custom_metadata(self) -> None:
1363
+ # Copy custom metadata if all nodes have same custom metadata
1364
+ custom_meta = None
1365
+ for node in self.node_map.values():
1366
+ curr_meta = node.meta.get("custom", {})
1367
+ if custom_meta is None:
1368
+ # first node
1369
+ custom_meta = curr_meta
1370
+ continue
1371
+
1372
+ if curr_meta != custom_meta:
1373
+ custom_meta = {}
1374
+ break
1375
+
1376
+ if custom_meta:
1377
+ # Lift common custom metadata to parent node and clear children node's custom metadata
1378
+ if self.parent_call_module is None:
1379
+ raise AssertionError(
1380
+ "parent_call_module must not be None when uplifting custom metadata"
1381
+ )
1382
+ self.parent_call_module.meta["custom"] = custom_meta
1383
+ for node in self.node_map.values():
1384
+ del node.meta["custom"]
1385
+
1386
+ def finalize_outputs(self):
1387
+ self.created_modules.pop(self.fqn, None)
1388
+
1389
+ orig_outputs = []
1390
+
1391
+ signature = self.module_call_graph.get(self.child_fqn)
1392
+ if signature is not None and self.parent is not None:
1393
+ for output in signature.outputs:
1394
+ if isinstance(
1395
+ output,
1396
+ (
1397
+ TensorArgument,
1398
+ SymIntArgument,
1399
+ SymBoolArgument,
1400
+ SymFloatArgument,
1401
+ ConstantArgument,
1402
+ ),
1403
+ ):
1404
+ if output.name in self.seen_nodes:
1405
+ orig_outputs.append(self.seen_nodes[output.name])
1406
+ else:
1407
+ orig_outputs.append(None)
1408
+ else:
1409
+ raise RuntimeError(
1410
+ f"Unsupported data type for output node: {output}"
1411
+ )
1412
+
1413
+ def get_actual_output_node(output):
1414
+ if output is None:
1415
+ return None
1416
+
1417
+ seen_node = self.seen_nodes[output.name]
1418
+ if seen_node in self.node_map:
1419
+ return self.node_map[seen_node]
1420
+ elif seen_node in self.node_to_placeholder:
1421
+ return self.node_to_placeholder[seen_node]
1422
+ else:
1423
+ raise RuntimeError(
1424
+ f"Could not find output node {output}. Graph: {self.graph}"
1425
+ )
1426
+
1427
+ tree_out_node = _generate_unflatten(
1428
+ self.module,
1429
+ tuple(get_actual_output_node(output) for output in orig_outputs),
1430
+ signature.out_spec,
1431
+ )
1432
+ parent_out: torch.fx.Node | None = _generate_flatten_spec(
1433
+ self.parent.module, self.parent_call_module, signature.out_spec
1434
+ )
1435
+ graph_outputs: torch.fx.Node | list[torch.fx.Node] = tree_out_node
1436
+ else:
1437
+ graph_outputs = []
1438
+ # Iterate through nodes we have copied into self.graph.
1439
+ for orig_node in self.node_map:
1440
+ for user_node in orig_node.users:
1441
+ if user_node.name not in self.seen_nodes:
1442
+ # external user node, need to expose as an output
1443
+ orig_outputs.append(orig_node)
1444
+ graph_outputs.append(self.node_map[orig_node])
1445
+ break
1446
+
1447
+ parent_out = self.parent_call_module
1448
+ if len(graph_outputs) == 1:
1449
+ graph_outputs = graph_outputs[0]
1450
+
1451
+ if not isinstance(graph_outputs, (list, torch.fx.Node)):
1452
+ raise AssertionError(
1453
+ f"expected graph_outputs to be list or torch.fx.Node, got {type(graph_outputs)}"
1454
+ )
1455
+
1456
+ self.graph.output(graph_outputs)
1457
+
1458
+ # Rewrite outputs in parent module
1459
+ if parent_out is None:
1460
+ return
1461
+
1462
+ parent_out.meta["val"] = (
1463
+ graph_outputs.meta.get("val")
1464
+ if isinstance(graph_outputs, torch.fx.Node)
1465
+ else [o.meta.get("val") for o in graph_outputs]
1466
+ )
1467
+ self.uplift_common_custom_metadata()
1468
+
1469
+ if len(orig_outputs) == 1 and signature is None:
1470
+ self.parent.node_map[orig_outputs[0]] = parent_out
1471
+ else:
1472
+ for i, orig_output in enumerate(orig_outputs):
1473
+ if orig_output is None:
1474
+ continue
1475
+ # Use Proxy to record getitem access.
1476
+ proxy_out = torch.fx.Proxy(parent_out)[i].node # type: ignore[index]
1477
+ proxy_out.meta["val"] = orig_output.meta.get("val")
1478
+ self.parent.node_map[orig_output] = proxy_out
1479
+
1480
+ def copy_node(self, node):
1481
+ self.print("copying", node.format_node())
1482
+ self.node_map[node] = self.graph.node_copy(node, self.remap_input)
1483
+ self.seen_nodes[node.name] = node
1484
+
1485
+ def run_outer(self):
1486
+ for i, node in enumerate(self.flat_graph.nodes):
1487
+ self.print(i, node.meta.get("nn_module_stack"), node.format_node())
1488
+
1489
+ # Copy all graph inputs
1490
+ node_idx: int = 0
1491
+ node = self.nodes[node_idx]
1492
+ while node.op == "placeholder":
1493
+ self.copy_node(node)
1494
+ node_idx += 1
1495
+ node = self.nodes[node_idx]
1496
+
1497
+ self.run_from(node_idx)
1498
+
1499
+ # Copy graph outputs
1500
+ for node in self.flat_graph.nodes:
1501
+ if node.op == "output":
1502
+ self.copy_node(node)
1503
+
1504
+ def print(self, *args, **kwargs):
1505
+ if self.verbose:
1506
+ # pyrefly: ignore [not-iterable]
1507
+ print(*args, **kwargs)
1508
+
1509
+ def run_from(self, node_idx):
1510
+ module_idx = 0
1511
+ # Walk through the graph, building up a new graph with the right submodules
1512
+ while node_idx < len(self.nodes):
1513
+ node = self.nodes[node_idx]
1514
+ if node.op == "placeholder":
1515
+ raise AssertionError(f"unexpected placeholder node at index {node_idx}")
1516
+
1517
+ self.print()
1518
+ self.print("STEP", node_idx, node.format_node())
1519
+ self.print(self.module_stack)
1520
+ depth = len(self.module_stack)
1521
+ if node.op == "output":
1522
+ if depth == 1:
1523
+ # We want the output node of the original graph to be handled
1524
+ # specially by the outermost stack frame (in run_outer). So
1525
+ # skip finalization here.
1526
+ return node_idx
1527
+
1528
+ # We've reached the end of the graph. Wrap up all the existing stack frames.
1529
+ self.finalize_outputs()
1530
+ return node_idx
1531
+
1532
+ if len(node.meta.get("nn_module_stack", {})) == 0:
1533
+ raise RuntimeError(f"Unable to find nn_module_stack for node {node}")
1534
+
1535
+ nn_module_stack = node.meta["nn_module_stack"]
1536
+ from torch._export.passes._node_metadata_hook import (
1537
+ _EMPTY_NN_MODULE_STACK_KEY,
1538
+ )
1539
+
1540
+ if (
1541
+ len(nn_module_stack) == 1
1542
+ and _EMPTY_NN_MODULE_STACK_KEY in nn_module_stack
1543
+ ):
1544
+ # Empty case from the node_metadata_hook
1545
+ node_module_stack = self.module_stack
1546
+ else:
1547
+ node_module_stack = [
1548
+ (
1549
+ path,
1550
+ ty if path else None,
1551
+ int(k.split("@")[-1]) if "@" in k else 0,
1552
+ )
1553
+ for k, (path, ty) in node.meta["nn_module_stack"].items()
1554
+ ]
1555
+
1556
+ if node_module_stack[:depth] != self.module_stack:
1557
+ # This means that the current module is done executing and the
1558
+ # current node is the beginning of a new module.
1559
+ #
1560
+ # In this case, we should finalize this module and return without
1561
+ # incrementing the node counter.
1562
+ self.finalize_outputs()
1563
+ self.print("outlining", self.fqn)
1564
+ self.print(self.graph)
1565
+ return node_idx
1566
+
1567
+ if node_module_stack is None:
1568
+ raise AssertionError("node_module_stack must not be None")
1569
+
1570
+ if _is_prefix(self.module_stack, node_module_stack):
1571
+ # This means that the current node represents the execution of a new
1572
+ # module.
1573
+ next_module = node_module_stack[depth]
1574
+ self.print("Creating new stack frame for", next_module)
1575
+ # Run a nested version of module outliner from the current node
1576
+ # counter. Once it is complete, continue from that point.
1577
+ next_module_key = list(node.meta["nn_module_stack"].keys())[depth]
1578
+ node_idx = _ModuleFrame(
1579
+ self.flat_graph,
1580
+ self.nodes,
1581
+ self.seen_nodes,
1582
+ self.seen_modules,
1583
+ self.seen_attrs,
1584
+ self.created_modules,
1585
+ self,
1586
+ self.module_stack + [next_module],
1587
+ next_module_key.split("@")[0],
1588
+ self.module_call_graph,
1589
+ ).run_from(node_idx)
1590
+ module_idx += 1
1591
+ continue
1592
+
1593
+ # The only remaining possibility is that we are in the right stack
1594
+ # frame. Copy the node into this frame's graph and increment the node counter.
1595
+ if node_module_stack != self.module_stack:
1596
+ raise AssertionError(
1597
+ f"expected node_module_stack {node_module_stack} to equal module_stack {self.module_stack}"
1598
+ )
1599
+
1600
+ if node.op == "get_attr":
1601
+ # this must be a graph argument for a HOP
1602
+ self.seen_attrs[self.child_fqn].add(node.target)
1603
+
1604
+ self.copy_node(node)
1605
+ # pyrefly: ignore [unsupported-operation]
1606
+ node_idx += 1
1607
+
1608
+
1609
+ @dataclass
1610
+ class _SubmoduleEntry:
1611
+ parent_fqn: str
1612
+ parent_module: torch.nn.Module
1613
+ parent_call_module: torch.fx.Node
1614
+ fqn: str
1615
+ call_idx: int
1616
+ module: torch.nn.Module
1617
+
1618
+
1619
+ def _outline_submodules(orig_graph: torch.fx.Graph, root_module: UnflattenedModule):
1620
+ seen_nodes: dict[str, torch.fx.Node] = {}
1621
+ seen_modules: dict[int, list[_SubmoduleEntry]] = defaultdict(list)
1622
+ seen_attrs: dict[str, set[str]] = defaultdict(set)
1623
+ created_modules: dict[str, torch.nn.Module] = {}
1624
+ _ModuleFrame(
1625
+ orig_graph,
1626
+ tuple(orig_graph.nodes),
1627
+ seen_nodes,
1628
+ seen_modules,
1629
+ seen_attrs,
1630
+ created_modules,
1631
+ None,
1632
+ [("", None, 0)],
1633
+ "",
1634
+ {
1635
+ entry.fqn: entry.signature
1636
+ for entry in root_module.module_call_graph
1637
+ if entry.signature
1638
+ },
1639
+ module=root_module,
1640
+ ).run_outer()
1641
+ return seen_modules, seen_attrs
1642
+
1643
+
1644
+ def _reorder_submodules(
1645
+ parent: torch.nn.Module, fqn_order: dict[str, int], prefix: str = ""
1646
+ ):
1647
+ # TODO Can be optimized by adding submodules ahead of time.
1648
+ if prefix == "":
1649
+ for fqn in list(fqn_order.keys())[1:]:
1650
+ if _get_submodule(parent, fqn) is None:
1651
+ _add_submodule(parent, fqn, torch.nn.Module())
1652
+
1653
+ children = []
1654
+ for name, child in list(parent._modules.items()):
1655
+ if child is None:
1656
+ continue
1657
+ fqn = prefix + name
1658
+ _reorder_submodules(child, fqn_order, prefix=fqn.split("@")[0] + ".")
1659
+ delattr(parent, name)
1660
+ base_fqn = fqn.split("@")[0]
1661
+ children.append(
1662
+ (fqn_order.get(fqn, fqn_order.get(base_fqn, len(fqn_order))), name, child)
1663
+ )
1664
+ children.sort(key=operator.itemgetter(0))
1665
+ for _, name, child in children:
1666
+ parent.register_module(name, child)
1667
+
1668
+
1669
+ class _IVals:
1670
+ """
1671
+ Collect the intermediate values of mutations in a graph.
1672
+
1673
+ Example: in the following graph, suppose that buf_in and buf_out
1674
+ are the input and output values of a buffer.
1675
+
1676
+ buf_in = placeholder()
1677
+ ...
1678
+ ival1 = f0(buf_in, ...) # inside self.n0(...)
1679
+ ...
1680
+ ival2 = f1(ival1, ...) # inside self.n1(...)
1681
+ ...
1682
+ buf_out = f2(ival2, ...) # inside self.n2(...)
1683
+ return buf_out, ...
1684
+
1685
+ Here ival1 and ival2 are intermediate values created inside
1686
+ calls to n0 and n1 respectively, and used inside calls to
1687
+ n1 and n2 respectively.
1688
+ """
1689
+
1690
+ def __init__(self):
1691
+ # for each fqn, set of node names corresponding to intermediate values
1692
+ self.node_names_by_fqn = defaultdict(set)
1693
+
1694
+ def _is_mutable(self, target):
1695
+ if isinstance(target, torch._ops.OpOverload):
1696
+ return target._schema.is_mutable
1697
+ return False
1698
+
1699
+ def read(self, mf, node):
1700
+ """
1701
+ Read state corresponding to a given intermediate value.
1702
+ """
1703
+ # we can assume that the node must be from a mutation
1704
+ if node.op != "call_function":
1705
+ raise AssertionError(
1706
+ f"expected node.op to be 'call_function', got {node.op!r}"
1707
+ )
1708
+ b = self._is_mutable(node.target)
1709
+ print("Checking mutability", node.target, b)
1710
+ if not b:
1711
+ # so the mutation was functionalized;
1712
+ # we will apply the original mutation later (see below)
1713
+ fqn, _ = next(reversed(node.meta["nn_module_stack"].values()))
1714
+ self.node_names_by_fqn[fqn].add(node.name)
1715
+ return mf.remap_input(node.args[0])
1716
+
1717
+ def update(self, partitions):
1718
+ """
1719
+ Update states corresponding to intermediate values that were read.
1720
+ """
1721
+ for shared_submodules in partitions:
1722
+ for entry in shared_submodules:
1723
+ graph = entry.module.graph
1724
+ node_names = self.node_names_by_fqn[entry.fqn]
1725
+ nodes = [n for n in graph.nodes if n.name in node_names]
1726
+ for node in nodes:
1727
+ # so node must be from a functionalized mutation;
1728
+ # we perform the original mutation now
1729
+ with graph.inserting_after(node):
1730
+ new_node = graph.create_node(
1731
+ "call_function",
1732
+ torch.ops.aten.copy_.default,
1733
+ (node.args[0], node),
1734
+ )
1735
+ new_node.meta = copy.copy(node.meta)
1736
+
1737
+
1738
+ def _copy_graph_attrs(
1739
+ gm: torch.fx.GraphModule,
1740
+ root_module: UnflattenedModule,
1741
+ seen_attrs: dict[str, set[str]],
1742
+ ):
1743
+ for child_fqn, names in seen_attrs.items():
1744
+ module = _get_attr(root_module, child_fqn) if child_fqn else root_module
1745
+ for name in names:
1746
+ val = getattr(gm, name)
1747
+ setattr(module, name, val)
1748
+
1749
+
1750
+ def _deduplicate_modules(partitions):
1751
+ redirected_call_indices = {}
1752
+ for shared_submodules in partitions:
1753
+ for i, entry in enumerate(shared_submodules):
1754
+ child_fqn = _call_name(entry.fqn, entry.call_idx)
1755
+ target = _compute_accessor(entry.parent_fqn, child_fqn)
1756
+ deduplicated = False
1757
+ # Iterate over all previously seen modules, and deduplicate if possible
1758
+ for seen in shared_submodules[:i]:
1759
+ if _check_graph_equivalence(seen.module, entry.module):
1760
+ parent = entry.parent_module
1761
+ # Since graphs are equivalent, we can deduplicate.
1762
+ # There are two cases.
1763
+ if seen.fqn == entry.fqn:
1764
+ # Case 1: The current module has the same fqn as the seen module.
1765
+ # In this case we have generated a call name that can be optimized away.
1766
+ # So we remove the current module from the hierarchy and replace
1767
+ # the current call name with the seen call name in the parent graph.
1768
+ *prefix, name = target.split(".")
1769
+ _get_attr_via_attr_list(parent, prefix)._modules.pop(name)
1770
+ seen_child_fqn = _call_name(seen.fqn, seen.call_idx)
1771
+ seen_target = _compute_accessor(
1772
+ entry.parent_fqn, seen_child_fqn
1773
+ )
1774
+ entry.parent_call_module.target = seen_target
1775
+ redirected_call_indices[child_fqn] = seen_child_fqn
1776
+ break
1777
+ elif not deduplicated:
1778
+ # Case 2: The current module has a different fqn than the seen module.
1779
+ # In this case we replace the current module with the seen module.
1780
+ # There should be nothing pointing to the current module any more,
1781
+ # so it can be garbage collected.
1782
+ # NOTE: We *do not* replace the current call name with the seen call name
1783
+ # in the parent graph, because this will lose information on which fqn
1784
+ # was actually called. However, it is possible that the current call name
1785
+ # will be optimized away when we find another seen module with the same fqn,
1786
+ # so we do not break out of the loop yet.
1787
+ parent.set_submodule(target, seen.module)
1788
+ deduplicated = True
1789
+
1790
+ return redirected_call_indices
1791
+
1792
+
1793
+ def _sink_params(
1794
+ module: torch.nn.Module,
1795
+ inputs_to_state: dict[str, list[str]],
1796
+ scope: list[str],
1797
+ module_id_to_inputs_removed: dict[int, set[str]] | None = None,
1798
+ ):
1799
+ """Sink params, buffers, and constants from graph inputs into get_attr nodes.
1800
+
1801
+ Exported modules are purely functional, so they pass their parameters and
1802
+ buffers in as inputs to the graph.
1803
+
1804
+ To replicate eager's semantics, we need to get them from the module state
1805
+ via get_attr instead.
1806
+
1807
+ module: GraphModule, potentially containing nested submodules.
1808
+ inputs_to_state: mapping graph input names to the corresponding key in the state_dict.
1809
+ scope: tracks where we are in the module hierarchy, so that we can emit the
1810
+ right `getattr(self, "foo.bar")` calls, etc.
1811
+ module_id_to_inputs_removed: records inputs removed by child modules, mapping
1812
+ the module object id to the list of placeholder node names in the child module
1813
+ that were removed.
1814
+ """
1815
+ if module_id_to_inputs_removed is None:
1816
+ module_id_to_inputs_removed = defaultdict(set)
1817
+
1818
+ if id(module) in module_id_to_inputs_removed:
1819
+ return {id(module): module_id_to_inputs_removed[id(module)]}
1820
+
1821
+ # We need to use _modules here instead of named_children(), because we
1822
+ # explicitly want duplicate modules to show up in the traversal.
1823
+ for name, submodule in module._modules.items():
1824
+ submod_id_to_inputs_removed = _sink_params(
1825
+ cast("torch.nn.Module", submodule),
1826
+ inputs_to_state,
1827
+ scope + [name],
1828
+ module_id_to_inputs_removed,
1829
+ )
1830
+ for k, v in submod_id_to_inputs_removed.items():
1831
+ module_id_to_inputs_removed[k].update(v)
1832
+
1833
+ graph = getattr(module, "graph", None)
1834
+ if graph is None or len(graph.nodes) == 0:
1835
+ # Not all modules have graphs defined, if they are empty modules with no operations (like ParameterList)
1836
+ return module_id_to_inputs_removed
1837
+
1838
+ if not isinstance(graph, torch.fx.Graph):
1839
+ raise AssertionError(f"expected graph to be torch.fx.Graph, got {type(graph)}")
1840
+
1841
+ inputs = list(filter(lambda n: n.op == "placeholder", graph.nodes))
1842
+ the_last_input = None if len(inputs) == 0 else inputs[-1]
1843
+
1844
+ # Also remove from call_module nodes
1845
+ call_module_nodes = filter(lambda n: n.op == "call_module", graph.nodes)
1846
+ for node in call_module_nodes:
1847
+ submodule = _get_attr(module, node.target)
1848
+ # remove placeholder from call_module node arguments, only if we've
1849
+ # erased the placeholder node in the corresponding _sink_params() call
1850
+ if submodule is not None and id(submodule) in module_id_to_inputs_removed:
1851
+ node.args = tuple(
1852
+ filter(
1853
+ lambda n: n.name not in module_id_to_inputs_removed[id(submodule)],
1854
+ node.args,
1855
+ )
1856
+ )
1857
+
1858
+ # Filter out inputs_to_state corresponding to current scope.
1859
+ inputs_to_state_of_scope: dict[torch.fx.Node, list[str]] = {}
1860
+ for node in inputs:
1861
+ if node.name not in inputs_to_state:
1862
+ continue
1863
+
1864
+ state_name = None
1865
+ for sn in inputs_to_state[node.name]:
1866
+ sn_split = sn.split(".")
1867
+ if sn_split[: len(scope)] == [x.split("@")[0] for x in scope]:
1868
+ state_name = sn_split
1869
+ break
1870
+
1871
+ # If there's a mismatch between scope name and state name, then
1872
+ # there must be multiple scopes pointing to the same state name,
1873
+ # meaning some modules are shared. In such case, we can simply skip
1874
+ # updating the current node because another later iteration will
1875
+ # take care of this input node when the unique match between scope
1876
+ # and state name occurs. To make sure this always happen, we should
1877
+ # enforce the invariant that no placeholder node in the unflattened
1878
+ # graph appears in inputs_to_state dict, which means all the extra
1879
+ # input nodes have been handled.
1880
+ if state_name is None:
1881
+ continue
1882
+
1883
+ inputs_to_state_of_scope[node] = state_name
1884
+
1885
+ # Record name of removed inputs for return purpose.
1886
+ inputs_removed: set[str] = set()
1887
+
1888
+ for node, state_name in inputs_to_state_of_scope.items():
1889
+ if len(node.users) > 0:
1890
+ attr_path = state_name[len(scope) :]
1891
+ state_attr = _get_attr_via_attr_list(module, attr_path)
1892
+ if not isinstance(state_attr, (torch.Tensor, torch.ScriptObject)):
1893
+ raise AssertionError(
1894
+ f"expected state_attr to be torch.Tensor or torch.ScriptObject, got {type(state_attr)}"
1895
+ )
1896
+
1897
+ # Make sure the newly created get_attr node is placed after the last placeholder node
1898
+ with graph.inserting_after(the_last_input):
1899
+ new_node = graph.create_node("get_attr", ".".join(attr_path))
1900
+
1901
+ node.replace_all_uses_with(new_node, propagate_meta=True)
1902
+
1903
+ graph.erase_node(node)
1904
+ inputs_removed.add(node.name)
1905
+
1906
+ if isinstance(module, InterpreterModule):
1907
+ module.finalize()
1908
+
1909
+ return {id(module): inputs_removed}
.venv/lib/python3.12/site-packages/torch/fft/__init__.py ADDED
@@ -0,0 +1,1442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._C import _add_docstr, _fft # type: ignore[attr-defined]
3
+ from torch._torch_docs import common_args, factory_common_args
4
+
5
+
6
+ __all__ = [
7
+ "fft",
8
+ "ifft",
9
+ "fft2",
10
+ "ifft2",
11
+ "fftn",
12
+ "ifftn",
13
+ "rfft",
14
+ "irfft",
15
+ "rfft2",
16
+ "irfft2",
17
+ "rfftn",
18
+ "irfftn",
19
+ "hfft",
20
+ "ihfft",
21
+ "fftfreq",
22
+ "rfftfreq",
23
+ "fftshift",
24
+ "ifftshift",
25
+ "Tensor",
26
+ ]
27
+
28
+ Tensor = torch.Tensor
29
+
30
+ # Note: This not only adds the doc strings for the spectral ops, but
31
+ # connects the torch.fft Python namespace to the torch._C._fft builtins.
32
+
33
+ fft = _add_docstr(
34
+ _fft.fft_fft,
35
+ r"""
36
+ fft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
37
+
38
+ Computes the one dimensional discrete Fourier transform of :attr:`input`.
39
+
40
+ Note:
41
+ The Fourier domain representation of any real signal satisfies the
42
+ Hermitian property: `X[i] = conj(X[-i])`. This function always returns both
43
+ the positive and negative frequency terms even though, for real inputs, the
44
+ negative frequencies are redundant. :func:`~torch.fft.rfft` returns the
45
+ more compact one-sided representation where only the positive frequencies
46
+ are returned.
47
+
48
+ Note:
49
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
50
+ However it only supports powers of 2 signal length in every transformed dimension.
51
+
52
+ Args:
53
+ input (Tensor): the input tensor
54
+ n (int, optional): Signal length. If given, the input will either be zero-padded
55
+ or trimmed to this length before computing the FFT.
56
+ dim (int, optional): The dimension along which to take the one dimensional FFT.
57
+ norm (str, optional): Normalization mode. For the forward transform
58
+ (:func:`~torch.fft.fft`), these correspond to:
59
+
60
+ * ``"forward"`` - normalize by ``1/n``
61
+ * ``"backward"`` - no normalization
62
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the FFT orthonormal)
63
+
64
+ Calling the backward transform (:func:`~torch.fft.ifft`) with the same
65
+ normalization mode will apply an overall normalization of ``1/n`` between
66
+ the two transforms. This is required to make :func:`~torch.fft.ifft`
67
+ the exact inverse.
68
+
69
+ Default is ``"backward"`` (no normalization).
70
+
71
+ Keyword args:
72
+ {out}
73
+
74
+ Example:
75
+
76
+ >>> t = torch.arange(4)
77
+ >>> t
78
+ tensor([0, 1, 2, 3])
79
+ >>> torch.fft.fft(t)
80
+ tensor([ 6.+0.j, -2.+2.j, -2.+0.j, -2.-2.j])
81
+
82
+ >>> t = torch.tensor([0.+1.j, 2.+3.j, 4.+5.j, 6.+7.j])
83
+ >>> torch.fft.fft(t)
84
+ tensor([12.+16.j, -8.+0.j, -4.-4.j, 0.-8.j])
85
+ """.format(**common_args),
86
+ )
87
+
88
+ ifft = _add_docstr(
89
+ _fft.fft_ifft,
90
+ r"""
91
+ ifft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
92
+
93
+ Computes the one dimensional inverse discrete Fourier transform of :attr:`input`.
94
+
95
+ Note:
96
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
97
+ However it only supports powers of 2 signal length in every transformed dimension.
98
+
99
+ Args:
100
+ input (Tensor): the input tensor
101
+ n (int, optional): Signal length. If given, the input will either be zero-padded
102
+ or trimmed to this length before computing the IFFT.
103
+ dim (int, optional): The dimension along which to take the one dimensional IFFT.
104
+ norm (str, optional): Normalization mode. For the backward transform
105
+ (:func:`~torch.fft.ifft`), these correspond to:
106
+
107
+ * ``"forward"`` - no normalization
108
+ * ``"backward"`` - normalize by ``1/n``
109
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the IFFT orthonormal)
110
+
111
+ Calling the forward transform (:func:`~torch.fft.fft`) with the same
112
+ normalization mode will apply an overall normalization of ``1/n`` between
113
+ the two transforms. This is required to make :func:`~torch.fft.ifft`
114
+ the exact inverse.
115
+
116
+ Default is ``"backward"`` (normalize by ``1/n``).
117
+
118
+ Keyword args:
119
+ {out}
120
+
121
+ Example:
122
+
123
+ >>> t = torch.tensor([ 6.+0.j, -2.+2.j, -2.+0.j, -2.-2.j])
124
+ >>> torch.fft.ifft(t)
125
+ tensor([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j])
126
+ """.format(**common_args),
127
+ )
128
+
129
+ fft2 = _add_docstr(
130
+ _fft.fft_fft2,
131
+ r"""
132
+ fft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
133
+
134
+ Computes the 2 dimensional discrete Fourier transform of :attr:`input`.
135
+ Equivalent to :func:`~torch.fft.fftn` but FFTs only the last two dimensions by default.
136
+
137
+ Note:
138
+ The Fourier domain representation of any real signal satisfies the
139
+ Hermitian property: ``X[i, j] = conj(X[-i, -j])``. This
140
+ function always returns all positive and negative frequency terms even
141
+ though, for real inputs, half of these values are redundant.
142
+ :func:`~torch.fft.rfft2` returns the more compact one-sided representation
143
+ where only the positive frequencies of the last dimension are returned.
144
+
145
+ Note:
146
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
147
+ However it only supports powers of 2 signal length in every transformed dimensions.
148
+
149
+ Args:
150
+ input (Tensor): the input tensor
151
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
152
+ If given, each dimension ``dim[i]`` will either be zero-padded or
153
+ trimmed to the length ``s[i]`` before computing the FFT.
154
+ If a length ``-1`` is specified, no padding is done in that dimension.
155
+ Default: ``s = [input.size(d) for d in dim]``
156
+ dim (Tuple[int], optional): Dimensions to be transformed.
157
+ Default: last two dimensions.
158
+ norm (str, optional): Normalization mode. For the forward transform
159
+ (:func:`~torch.fft.fft2`), these correspond to:
160
+
161
+ * ``"forward"`` - normalize by ``1/n``
162
+ * ``"backward"`` - no normalization
163
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the FFT orthonormal)
164
+
165
+ Where ``n = prod(s)`` is the logical FFT size.
166
+ Calling the backward transform (:func:`~torch.fft.ifft2`) with the same
167
+ normalization mode will apply an overall normalization of ``1/n``
168
+ between the two transforms. This is required to make
169
+ :func:`~torch.fft.ifft2` the exact inverse.
170
+
171
+ Default is ``"backward"`` (no normalization).
172
+
173
+ Keyword args:
174
+ {out}
175
+
176
+ Example:
177
+
178
+ >>> x = torch.rand(10, 10, dtype=torch.complex64)
179
+ >>> fft2 = torch.fft.fft2(x)
180
+
181
+ The discrete Fourier transform is separable, so :func:`~torch.fft.fft2`
182
+ here is equivalent to two one-dimensional :func:`~torch.fft.fft` calls:
183
+
184
+ >>> two_ffts = torch.fft.fft(torch.fft.fft(x, dim=0), dim=1)
185
+ >>> torch.testing.assert_close(fft2, two_ffts, check_stride=False)
186
+
187
+ """.format(**common_args),
188
+ )
189
+
190
+ ifft2 = _add_docstr(
191
+ _fft.fft_ifft2,
192
+ r"""
193
+ ifft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
194
+
195
+ Computes the 2 dimensional inverse discrete Fourier transform of :attr:`input`.
196
+ Equivalent to :func:`~torch.fft.ifftn` but IFFTs only the last two dimensions by default.
197
+
198
+ Note:
199
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
200
+ However it only supports powers of 2 signal length in every transformed dimensions.
201
+
202
+ Args:
203
+ input (Tensor): the input tensor
204
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
205
+ If given, each dimension ``dim[i]`` will either be zero-padded or
206
+ trimmed to the length ``s[i]`` before computing the IFFT.
207
+ If a length ``-1`` is specified, no padding is done in that dimension.
208
+ Default: ``s = [input.size(d) for d in dim]``
209
+ dim (Tuple[int], optional): Dimensions to be transformed.
210
+ Default: last two dimensions.
211
+ norm (str, optional): Normalization mode. For the backward transform
212
+ (:func:`~torch.fft.ifft2`), these correspond to:
213
+
214
+ * ``"forward"`` - no normalization
215
+ * ``"backward"`` - normalize by ``1/n``
216
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the IFFT orthonormal)
217
+
218
+ Where ``n = prod(s)`` is the logical IFFT size.
219
+ Calling the forward transform (:func:`~torch.fft.fft2`) with the same
220
+ normalization mode will apply an overall normalization of ``1/n`` between
221
+ the two transforms. This is required to make :func:`~torch.fft.ifft2`
222
+ the exact inverse.
223
+
224
+ Default is ``"backward"`` (normalize by ``1/n``).
225
+
226
+ Keyword args:
227
+ {out}
228
+
229
+ Example:
230
+
231
+ >>> x = torch.rand(10, 10, dtype=torch.complex64)
232
+ >>> ifft2 = torch.fft.ifft2(x)
233
+
234
+ The discrete Fourier transform is separable, so :func:`~torch.fft.ifft2`
235
+ here is equivalent to two one-dimensional :func:`~torch.fft.ifft` calls:
236
+
237
+ >>> two_iffts = torch.fft.ifft(torch.fft.ifft(x, dim=0), dim=1)
238
+ >>> torch.testing.assert_close(ifft2, two_iffts, check_stride=False)
239
+
240
+ """.format(**common_args),
241
+ )
242
+
243
+ fftn = _add_docstr(
244
+ _fft.fft_fftn,
245
+ r"""
246
+ fftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
247
+
248
+ Computes the N dimensional discrete Fourier transform of :attr:`input`.
249
+
250
+ Note:
251
+ The Fourier domain representation of any real signal satisfies the
252
+ Hermitian property: ``X[i_1, ..., i_n] = conj(X[-i_1, ..., -i_n])``. This
253
+ function always returns all positive and negative frequency terms even
254
+ though, for real inputs, half of these values are redundant.
255
+ :func:`~torch.fft.rfftn` returns the more compact one-sided representation
256
+ where only the positive frequencies of the last dimension are returned.
257
+
258
+ Note:
259
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
260
+ However it only supports powers of 2 signal length in every transformed dimensions.
261
+
262
+ Args:
263
+ input (Tensor): the input tensor
264
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
265
+ If given, each dimension ``dim[i]`` will either be zero-padded or
266
+ trimmed to the length ``s[i]`` before computing the FFT.
267
+ If a length ``-1`` is specified, no padding is done in that dimension.
268
+ Default: ``s = [input.size(d) for d in dim]``
269
+ dim (Tuple[int], optional): Dimensions to be transformed.
270
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
271
+ norm (str, optional): Normalization mode. For the forward transform
272
+ (:func:`~torch.fft.fftn`), these correspond to:
273
+
274
+ * ``"forward"`` - normalize by ``1/n``
275
+ * ``"backward"`` - no normalization
276
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the FFT orthonormal)
277
+
278
+ Where ``n = prod(s)`` is the logical FFT size.
279
+ Calling the backward transform (:func:`~torch.fft.ifftn`) with the same
280
+ normalization mode will apply an overall normalization of ``1/n``
281
+ between the two transforms. This is required to make
282
+ :func:`~torch.fft.ifftn` the exact inverse.
283
+
284
+ Default is ``"backward"`` (no normalization).
285
+
286
+ Keyword args:
287
+ {out}
288
+
289
+ Example:
290
+
291
+ >>> x = torch.rand(10, 10, dtype=torch.complex64)
292
+ >>> fftn = torch.fft.fftn(x)
293
+
294
+ The discrete Fourier transform is separable, so :func:`~torch.fft.fftn`
295
+ here is equivalent to two one-dimensional :func:`~torch.fft.fft` calls:
296
+
297
+ >>> two_ffts = torch.fft.fft(torch.fft.fft(x, dim=0), dim=1)
298
+ >>> torch.testing.assert_close(fftn, two_ffts, check_stride=False)
299
+
300
+ """.format(**common_args),
301
+ )
302
+
303
+ ifftn = _add_docstr(
304
+ _fft.fft_ifftn,
305
+ r"""
306
+ ifftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
307
+
308
+ Computes the N dimensional inverse discrete Fourier transform of :attr:`input`.
309
+
310
+ Note:
311
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
312
+ However it only supports powers of 2 signal length in every transformed dimensions.
313
+
314
+ Args:
315
+ input (Tensor): the input tensor
316
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
317
+ If given, each dimension ``dim[i]`` will either be zero-padded or
318
+ trimmed to the length ``s[i]`` before computing the IFFT.
319
+ If a length ``-1`` is specified, no padding is done in that dimension.
320
+ Default: ``s = [input.size(d) for d in dim]``
321
+ dim (Tuple[int], optional): Dimensions to be transformed.
322
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
323
+ norm (str, optional): Normalization mode. For the backward transform
324
+ (:func:`~torch.fft.ifftn`), these correspond to:
325
+
326
+ * ``"forward"`` - no normalization
327
+ * ``"backward"`` - normalize by ``1/n``
328
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the IFFT orthonormal)
329
+
330
+ Where ``n = prod(s)`` is the logical IFFT size.
331
+ Calling the forward transform (:func:`~torch.fft.fftn`) with the same
332
+ normalization mode will apply an overall normalization of ``1/n`` between
333
+ the two transforms. This is required to make :func:`~torch.fft.ifftn`
334
+ the exact inverse.
335
+
336
+ Default is ``"backward"`` (normalize by ``1/n``).
337
+
338
+ Keyword args:
339
+ {out}
340
+
341
+ Example:
342
+
343
+ >>> x = torch.rand(10, 10, dtype=torch.complex64)
344
+ >>> ifftn = torch.fft.ifftn(x)
345
+
346
+ The discrete Fourier transform is separable, so :func:`~torch.fft.ifftn`
347
+ here is equivalent to two one-dimensional :func:`~torch.fft.ifft` calls:
348
+
349
+ >>> two_iffts = torch.fft.ifft(torch.fft.ifft(x, dim=0), dim=1)
350
+ >>> torch.testing.assert_close(ifftn, two_iffts, check_stride=False)
351
+
352
+ """.format(**common_args),
353
+ )
354
+
355
+ rfft = _add_docstr(
356
+ _fft.fft_rfft,
357
+ r"""
358
+ rfft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
359
+
360
+ Computes the one dimensional Fourier transform of real-valued :attr:`input`.
361
+
362
+ The FFT of a real signal is Hermitian-symmetric, ``X[i] = conj(X[-i])`` so
363
+ the output contains only the positive frequencies below the Nyquist frequency.
364
+ To compute the full output, use :func:`~torch.fft.fft`
365
+
366
+ Note:
367
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
368
+ However it only supports powers of 2 signal length in every transformed dimension.
369
+
370
+ Args:
371
+ input (Tensor): the real input tensor
372
+ n (int, optional): Signal length. If given, the input will either be zero-padded
373
+ or trimmed to this length before computing the real FFT.
374
+ dim (int, optional): The dimension along which to take the one dimensional real FFT.
375
+ norm (str, optional): Normalization mode. For the forward transform
376
+ (:func:`~torch.fft.rfft`), these correspond to:
377
+
378
+ * ``"forward"`` - normalize by ``1/n``
379
+ * ``"backward"`` - no normalization
380
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the FFT orthonormal)
381
+
382
+ Calling the backward transform (:func:`~torch.fft.irfft`) with the same
383
+ normalization mode will apply an overall normalization of ``1/n`` between
384
+ the two transforms. This is required to make :func:`~torch.fft.irfft`
385
+ the exact inverse.
386
+
387
+ Default is ``"backward"`` (no normalization).
388
+
389
+ Keyword args:
390
+ {out}
391
+
392
+ Example:
393
+
394
+ >>> t = torch.arange(4)
395
+ >>> t
396
+ tensor([0, 1, 2, 3])
397
+ >>> torch.fft.rfft(t)
398
+ tensor([ 6.+0.j, -2.+2.j, -2.+0.j])
399
+
400
+ Compare against the full output from :func:`~torch.fft.fft`:
401
+
402
+ >>> torch.fft.fft(t)
403
+ tensor([ 6.+0.j, -2.+2.j, -2.+0.j, -2.-2.j])
404
+
405
+ Notice that the symmetric element ``T[-1] == T[1].conj()`` is omitted.
406
+ At the Nyquist frequency ``T[-2] == T[2]`` is its own symmetric pair,
407
+ and therefore must always be real-valued.
408
+ """.format(**common_args),
409
+ )
410
+
411
+ irfft = _add_docstr(
412
+ _fft.fft_irfft,
413
+ r"""
414
+ irfft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
415
+
416
+ Computes the inverse of :func:`~torch.fft.rfft`.
417
+
418
+ :attr:`input` is interpreted as a one-sided Hermitian signal in the Fourier
419
+ domain, as produced by :func:`~torch.fft.rfft`. By the Hermitian property, the
420
+ output will be real-valued.
421
+
422
+ Note:
423
+ Some input frequencies must be real-valued to satisfy the Hermitian
424
+ property. In these cases the imaginary component will be ignored.
425
+ For example, any imaginary component in the zero-frequency term cannot
426
+ be represented in a real output and so will always be ignored.
427
+
428
+ Note:
429
+ The correct interpretation of the Hermitian input depends on the length of
430
+ the original data, as given by :attr:`n`. This is because each input shape
431
+ could correspond to either an odd or even length signal. By default, the
432
+ signal is assumed to be even length and odd signals will not round-trip
433
+ properly. So, it is recommended to always pass the signal length :attr:`n`.
434
+
435
+ Note:
436
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
437
+ However it only supports powers of 2 signal length in every transformed dimension.
438
+ With default arguments, size of the transformed dimension should be (2^n + 1) as argument
439
+ `n` defaults to even output size = 2 * (transformed_dim_size - 1)
440
+
441
+ Args:
442
+ input (Tensor): the input tensor representing a half-Hermitian signal
443
+ n (int, optional): Output signal length. This determines the length of the
444
+ output signal. If given, the input will either be zero-padded or trimmed to this
445
+ length before computing the real IFFT.
446
+ Defaults to even output: ``n=2*(input.size(dim) - 1)``.
447
+ dim (int, optional): The dimension along which to take the one dimensional real IFFT.
448
+ norm (str, optional): Normalization mode. For the backward transform
449
+ (:func:`~torch.fft.irfft`), these correspond to:
450
+
451
+ * ``"forward"`` - no normalization
452
+ * ``"backward"`` - normalize by ``1/n``
453
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the real IFFT orthonormal)
454
+
455
+ Calling the forward transform (:func:`~torch.fft.rfft`) with the same
456
+ normalization mode will apply an overall normalization of ``1/n`` between
457
+ the two transforms. This is required to make :func:`~torch.fft.irfft`
458
+ the exact inverse.
459
+
460
+ Default is ``"backward"`` (normalize by ``1/n``).
461
+
462
+ Keyword args:
463
+ {out}
464
+
465
+ Example:
466
+
467
+ >>> t = torch.linspace(0, 1, 5)
468
+ >>> t
469
+ tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
470
+ >>> T = torch.fft.rfft(t)
471
+ >>> T
472
+ tensor([ 2.5000+0.0000j, -0.6250+0.8602j, -0.6250+0.2031j])
473
+
474
+ Without specifying the output length to :func:`~torch.fft.irfft`, the output
475
+ will not round-trip properly because the input is odd-length:
476
+
477
+ >>> torch.fft.irfft(T)
478
+ tensor([0.1562, 0.3511, 0.7812, 1.2114])
479
+
480
+ So, it is recommended to always pass the signal length :attr:`n`:
481
+
482
+ >>> roundtrip = torch.fft.irfft(T, t.numel())
483
+ >>> torch.testing.assert_close(roundtrip, t, check_stride=False)
484
+
485
+ """.format(**common_args),
486
+ )
487
+
488
+ rfft2 = _add_docstr(
489
+ _fft.fft_rfft2,
490
+ r"""
491
+ rfft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
492
+
493
+ Computes the 2-dimensional discrete Fourier transform of real :attr:`input`.
494
+ Equivalent to :func:`~torch.fft.rfftn` but FFTs only the last two dimensions by default.
495
+
496
+ The FFT of a real signal is Hermitian-symmetric, ``X[i, j] = conj(X[-i, -j])``,
497
+ so the full :func:`~torch.fft.fft2` output contains redundant information.
498
+ :func:`~torch.fft.rfft2` instead omits the negative frequencies in the last
499
+ dimension.
500
+
501
+ Note:
502
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
503
+ However it only supports powers of 2 signal length in every transformed dimensions.
504
+
505
+ Args:
506
+ input (Tensor): the input tensor
507
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
508
+ If given, each dimension ``dim[i]`` will either be zero-padded or
509
+ trimmed to the length ``s[i]`` before computing the real FFT.
510
+ If a length ``-1`` is specified, no padding is done in that dimension.
511
+ Default: ``s = [input.size(d) for d in dim]``
512
+ dim (Tuple[int], optional): Dimensions to be transformed.
513
+ Default: last two dimensions.
514
+ norm (str, optional): Normalization mode. For the forward transform
515
+ (:func:`~torch.fft.rfft2`), these correspond to:
516
+
517
+ * ``"forward"`` - normalize by ``1/n``
518
+ * ``"backward"`` - no normalization
519
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the real FFT orthonormal)
520
+
521
+ Where ``n = prod(s)`` is the logical FFT size.
522
+ Calling the backward transform (:func:`~torch.fft.irfft2`) with the same
523
+ normalization mode will apply an overall normalization of ``1/n`` between
524
+ the two transforms. This is required to make :func:`~torch.fft.irfft2`
525
+ the exact inverse.
526
+
527
+ Default is ``"backward"`` (no normalization).
528
+
529
+ Keyword args:
530
+ {out}
531
+
532
+ Example:
533
+
534
+ >>> t = torch.rand(10, 10)
535
+ >>> rfft2 = torch.fft.rfft2(t)
536
+ >>> rfft2.size()
537
+ torch.Size([10, 6])
538
+
539
+ Compared against the full output from :func:`~torch.fft.fft2`, we have all
540
+ elements up to the Nyquist frequency.
541
+
542
+ >>> fft2 = torch.fft.fft2(t)
543
+ >>> torch.testing.assert_close(fft2[..., :6], rfft2, check_stride=False)
544
+
545
+ The discrete Fourier transform is separable, so :func:`~torch.fft.rfft2`
546
+ here is equivalent to a combination of :func:`~torch.fft.fft` and
547
+ :func:`~torch.fft.rfft`:
548
+
549
+ >>> two_ffts = torch.fft.fft(torch.fft.rfft(t, dim=1), dim=0)
550
+ >>> torch.testing.assert_close(rfft2, two_ffts, check_stride=False)
551
+
552
+ """.format(**common_args),
553
+ )
554
+
555
+ irfft2 = _add_docstr(
556
+ _fft.fft_irfft2,
557
+ r"""
558
+ irfft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
559
+
560
+ Computes the inverse of :func:`~torch.fft.rfft2`.
561
+ Equivalent to :func:`~torch.fft.irfftn` but IFFTs only the last two dimensions by default.
562
+
563
+ :attr:`input` is interpreted as a one-sided Hermitian signal in the Fourier
564
+ domain, as produced by :func:`~torch.fft.rfft2`. By the Hermitian property, the
565
+ output will be real-valued.
566
+
567
+ Note:
568
+ Some input frequencies must be real-valued to satisfy the Hermitian
569
+ property. In these cases the imaginary component will be ignored.
570
+ For example, any imaginary component in the zero-frequency term cannot
571
+ be represented in a real output and so will always be ignored.
572
+
573
+ Note:
574
+ The correct interpretation of the Hermitian input depends on the length of
575
+ the original data, as given by :attr:`s`. This is because each input shape
576
+ could correspond to either an odd or even length signal. By default, the
577
+ signal is assumed to be even length and odd signals will not round-trip
578
+ properly. So, it is recommended to always pass the signal shape :attr:`s`.
579
+
580
+ Note:
581
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
582
+ However it only supports powers of 2 signal length in every transformed dimensions.
583
+ With default arguments, the size of last dimension should be (2^n + 1) as argument
584
+ `s` defaults to even output size = 2 * (last_dim_size - 1)
585
+
586
+ Args:
587
+ input (Tensor): the input tensor
588
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
589
+ If given, each dimension ``dim[i]`` will either be zero-padded or
590
+ trimmed to the length ``s[i]`` before computing the real FFT.
591
+ If a length ``-1`` is specified, no padding is done in that dimension.
592
+ Defaults to even output in the last dimension:
593
+ ``s[-1] = 2*(input.size(dim[-1]) - 1)``.
594
+ dim (Tuple[int], optional): Dimensions to be transformed.
595
+ The last dimension must be the half-Hermitian compressed dimension.
596
+ Default: last two dimensions.
597
+ norm (str, optional): Normalization mode. For the backward transform
598
+ (:func:`~torch.fft.irfft2`), these correspond to:
599
+
600
+ * ``"forward"`` - no normalization
601
+ * ``"backward"`` - normalize by ``1/n``
602
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the real IFFT orthonormal)
603
+
604
+ Where ``n = prod(s)`` is the logical IFFT size.
605
+ Calling the forward transform (:func:`~torch.fft.rfft2`) with the same
606
+ normalization mode will apply an overall normalization of ``1/n`` between
607
+ the two transforms. This is required to make :func:`~torch.fft.irfft2`
608
+ the exact inverse.
609
+
610
+ Default is ``"backward"`` (normalize by ``1/n``).
611
+
612
+ Keyword args:
613
+ {out}
614
+
615
+ Example:
616
+
617
+ >>> t = torch.rand(10, 9)
618
+ >>> T = torch.fft.rfft2(t)
619
+
620
+ Without specifying the output length to :func:`~torch.fft.irfft2`, the output
621
+ will not round-trip properly because the input is odd-length in the last
622
+ dimension:
623
+
624
+ >>> torch.fft.irfft2(T).size()
625
+ torch.Size([10, 8])
626
+
627
+ So, it is recommended to always pass the signal shape :attr:`s`.
628
+
629
+ >>> roundtrip = torch.fft.irfft2(T, t.size())
630
+ >>> roundtrip.size()
631
+ torch.Size([10, 9])
632
+ >>> torch.testing.assert_close(roundtrip, t, check_stride=False)
633
+
634
+ """.format(**common_args),
635
+ )
636
+
637
+ rfftn = _add_docstr(
638
+ _fft.fft_rfftn,
639
+ r"""
640
+ rfftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
641
+
642
+ Computes the N-dimensional discrete Fourier transform of real :attr:`input`.
643
+
644
+ The FFT of a real signal is Hermitian-symmetric,
645
+ ``X[i_1, ..., i_n] = conj(X[-i_1, ..., -i_n])`` so the full
646
+ :func:`~torch.fft.fftn` output contains redundant information.
647
+ :func:`~torch.fft.rfftn` instead omits the negative frequencies in the
648
+ last dimension.
649
+
650
+ Note:
651
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
652
+ However it only supports powers of 2 signal length in every transformed dimensions.
653
+
654
+ Args:
655
+ input (Tensor): the input tensor
656
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
657
+ If given, each dimension ``dim[i]`` will either be zero-padded or
658
+ trimmed to the length ``s[i]`` before computing the real FFT.
659
+ If a length ``-1`` is specified, no padding is done in that dimension.
660
+ Default: ``s = [input.size(d) for d in dim]``
661
+ dim (Tuple[int], optional): Dimensions to be transformed.
662
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
663
+ norm (str, optional): Normalization mode. For the forward transform
664
+ (:func:`~torch.fft.rfftn`), these correspond to:
665
+
666
+ * ``"forward"`` - normalize by ``1/n``
667
+ * ``"backward"`` - no normalization
668
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the real FFT orthonormal)
669
+
670
+ Where ``n = prod(s)`` is the logical FFT size.
671
+ Calling the backward transform (:func:`~torch.fft.irfftn`) with the same
672
+ normalization mode will apply an overall normalization of ``1/n`` between
673
+ the two transforms. This is required to make :func:`~torch.fft.irfftn`
674
+ the exact inverse.
675
+
676
+ Default is ``"backward"`` (no normalization).
677
+
678
+ Keyword args:
679
+ {out}
680
+
681
+ Example:
682
+
683
+ >>> t = torch.rand(10, 10)
684
+ >>> rfftn = torch.fft.rfftn(t)
685
+ >>> rfftn.size()
686
+ torch.Size([10, 6])
687
+
688
+ Compared against the full output from :func:`~torch.fft.fftn`, we have all
689
+ elements up to the Nyquist frequency.
690
+
691
+ >>> fftn = torch.fft.fftn(t)
692
+ >>> torch.testing.assert_close(fftn[..., :6], rfftn, check_stride=False)
693
+
694
+ The discrete Fourier transform is separable, so :func:`~torch.fft.rfftn`
695
+ here is equivalent to a combination of :func:`~torch.fft.fft` and
696
+ :func:`~torch.fft.rfft`:
697
+
698
+ >>> two_ffts = torch.fft.fft(torch.fft.rfft(t, dim=1), dim=0)
699
+ >>> torch.testing.assert_close(rfftn, two_ffts, check_stride=False)
700
+
701
+ """.format(**common_args),
702
+ )
703
+
704
+ irfftn = _add_docstr(
705
+ _fft.fft_irfftn,
706
+ r"""
707
+ irfftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
708
+
709
+ Computes the inverse of :func:`~torch.fft.rfftn`.
710
+
711
+ :attr:`input` is interpreted as a one-sided Hermitian signal in the Fourier
712
+ domain, as produced by :func:`~torch.fft.rfftn`. By the Hermitian property, the
713
+ output will be real-valued.
714
+
715
+ Note:
716
+ Some input frequencies must be real-valued to satisfy the Hermitian
717
+ property. In these cases the imaginary component will be ignored.
718
+ For example, any imaginary component in the zero-frequency term cannot
719
+ be represented in a real output and so will always be ignored.
720
+
721
+ Note:
722
+ The correct interpretation of the Hermitian input depends on the length of
723
+ the original data, as given by :attr:`s`. This is because each input shape
724
+ could correspond to either an odd or even length signal. By default, the
725
+ signal is assumed to be even length and odd signals will not round-trip
726
+ properly. So, it is recommended to always pass the signal shape :attr:`s`.
727
+
728
+ Note:
729
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
730
+ However it only supports powers of 2 signal length in every transformed dimensions.
731
+ With default arguments, the size of last dimension should be (2^n + 1) as argument
732
+ `s` defaults to even output size = 2 * (last_dim_size - 1)
733
+
734
+ Args:
735
+ input (Tensor): the input tensor
736
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
737
+ If given, each dimension ``dim[i]`` will either be zero-padded or
738
+ trimmed to the length ``s[i]`` before computing the real FFT.
739
+ If a length ``-1`` is specified, no padding is done in that dimension.
740
+ Defaults to even output in the last dimension:
741
+ ``s[-1] = 2*(input.size(dim[-1]) - 1)``.
742
+ dim (Tuple[int], optional): Dimensions to be transformed.
743
+ The last dimension must be the half-Hermitian compressed dimension.
744
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
745
+ norm (str, optional): Normalization mode. For the backward transform
746
+ (:func:`~torch.fft.irfftn`), these correspond to:
747
+
748
+ * ``"forward"`` - no normalization
749
+ * ``"backward"`` - normalize by ``1/n``
750
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the real IFFT orthonormal)
751
+
752
+ Where ``n = prod(s)`` is the logical IFFT size.
753
+ Calling the forward transform (:func:`~torch.fft.rfftn`) with the same
754
+ normalization mode will apply an overall normalization of ``1/n`` between
755
+ the two transforms. This is required to make :func:`~torch.fft.irfftn`
756
+ the exact inverse.
757
+
758
+ Default is ``"backward"`` (normalize by ``1/n``).
759
+
760
+ Keyword args:
761
+ {out}
762
+
763
+ Example:
764
+
765
+ >>> t = torch.rand(10, 9)
766
+ >>> T = torch.fft.rfftn(t)
767
+
768
+ Without specifying the output length to :func:`~torch.fft.irfft`, the output
769
+ will not round-trip properly because the input is odd-length in the last
770
+ dimension:
771
+
772
+ >>> torch.fft.irfftn(T).size()
773
+ torch.Size([10, 8])
774
+
775
+ So, it is recommended to always pass the signal shape :attr:`s`.
776
+
777
+ >>> roundtrip = torch.fft.irfftn(T, t.size())
778
+ >>> roundtrip.size()
779
+ torch.Size([10, 9])
780
+ >>> torch.testing.assert_close(roundtrip, t, check_stride=False)
781
+
782
+ """.format(**common_args),
783
+ )
784
+
785
+ hfft = _add_docstr(
786
+ _fft.fft_hfft,
787
+ r"""
788
+ hfft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
789
+
790
+ Computes the one dimensional discrete Fourier transform of a Hermitian
791
+ symmetric :attr:`input` signal.
792
+
793
+ Note:
794
+
795
+ :func:`~torch.fft.hfft`/:func:`~torch.fft.ihfft` are analogous to
796
+ :func:`~torch.fft.rfft`/:func:`~torch.fft.irfft`. The real FFT expects
797
+ a real signal in the time-domain and gives a Hermitian symmetry in the
798
+ frequency-domain. The Hermitian FFT is the opposite; Hermitian symmetric in
799
+ the time-domain and real-valued in the frequency-domain. For this reason,
800
+ special care needs to be taken with the length argument :attr:`n`, in the
801
+ same way as with :func:`~torch.fft.irfft`.
802
+
803
+ Note:
804
+ Because the signal is Hermitian in the time-domain, the result will be
805
+ real in the frequency domain. Note that some input frequencies must be
806
+ real-valued to satisfy the Hermitian property. In these cases the imaginary
807
+ component will be ignored. For example, any imaginary component in
808
+ ``input[0]`` would result in one or more complex frequency terms which
809
+ cannot be represented in a real output and so will always be ignored.
810
+
811
+ Note:
812
+ The correct interpretation of the Hermitian input depends on the length of
813
+ the original data, as given by :attr:`n`. This is because each input shape
814
+ could correspond to either an odd or even length signal. By default, the
815
+ signal is assumed to be even length and odd signals will not round-trip
816
+ properly. So, it is recommended to always pass the signal length :attr:`n`.
817
+
818
+ Note:
819
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
820
+ However it only supports powers of 2 signal length in every transformed dimension.
821
+ With default arguments, size of the transformed dimension should be (2^n + 1) as argument
822
+ `n` defaults to even output size = 2 * (transformed_dim_size - 1)
823
+
824
+ Args:
825
+ input (Tensor): the input tensor representing a half-Hermitian signal
826
+ n (int, optional): Output signal length. This determines the length of the
827
+ real output. If given, the input will either be zero-padded or trimmed to this
828
+ length before computing the Hermitian FFT.
829
+ Defaults to even output: ``n=2*(input.size(dim) - 1)``.
830
+ dim (int, optional): The dimension along which to take the one dimensional Hermitian FFT.
831
+ norm (str, optional): Normalization mode. For the forward transform
832
+ (:func:`~torch.fft.hfft`), these correspond to:
833
+
834
+ * ``"forward"`` - normalize by ``1/n``
835
+ * ``"backward"`` - no normalization
836
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the Hermitian FFT orthonormal)
837
+
838
+ Calling the backward transform (:func:`~torch.fft.ihfft`) with the same
839
+ normalization mode will apply an overall normalization of ``1/n`` between
840
+ the two transforms. This is required to make :func:`~torch.fft.ihfft`
841
+ the exact inverse.
842
+
843
+ Default is ``"backward"`` (no normalization).
844
+
845
+ Keyword args:
846
+ {out}
847
+
848
+ Example:
849
+
850
+ Taking a real-valued frequency signal and bringing it into the time domain
851
+ gives Hermitian symmetric output:
852
+
853
+ >>> t = torch.linspace(0, 1, 5)
854
+ >>> t
855
+ tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
856
+ >>> T = torch.fft.ifft(t)
857
+ >>> T
858
+ tensor([ 0.5000-0.0000j, -0.1250-0.1720j, -0.1250-0.0406j, -0.1250+0.0406j,
859
+ -0.1250+0.1720j])
860
+
861
+ Note that ``T[1] == T[-1].conj()`` and ``T[2] == T[-2].conj()`` is
862
+ redundant. We can thus compute the forward transform without considering
863
+ negative frequencies:
864
+
865
+ >>> torch.fft.hfft(T[:3], n=5)
866
+ tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
867
+
868
+ Like with :func:`~torch.fft.irfft`, the output length must be given in order
869
+ to recover an even length output:
870
+
871
+ >>> torch.fft.hfft(T[:3])
872
+ tensor([0.1250, 0.2809, 0.6250, 0.9691])
873
+ """.format(**common_args),
874
+ )
875
+
876
+ ihfft = _add_docstr(
877
+ _fft.fft_ihfft,
878
+ r"""
879
+ ihfft(input, n=None, dim=-1, norm=None, *, out=None) -> Tensor
880
+
881
+ Computes the inverse of :func:`~torch.fft.hfft`.
882
+
883
+ :attr:`input` must be a real-valued signal, interpreted in the Fourier domain.
884
+ The IFFT of a real signal is Hermitian-symmetric, ``X[i] = conj(X[-i])``.
885
+ :func:`~torch.fft.ihfft` represents this in the one-sided form where only the
886
+ positive frequencies below the Nyquist frequency are included. To compute the
887
+ full output, use :func:`~torch.fft.ifft`.
888
+
889
+ Note:
890
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
891
+ However it only supports powers of 2 signal length in every transformed dimension.
892
+
893
+ Args:
894
+ input (Tensor): the real input tensor
895
+ n (int, optional): Signal length. If given, the input will either be zero-padded
896
+ or trimmed to this length before computing the Hermitian IFFT.
897
+ dim (int, optional): The dimension along which to take the one dimensional Hermitian IFFT.
898
+ norm (str, optional): Normalization mode. For the backward transform
899
+ (:func:`~torch.fft.ihfft`), these correspond to:
900
+
901
+ * ``"forward"`` - no normalization
902
+ * ``"backward"`` - normalize by ``1/n``
903
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the IFFT orthonormal)
904
+
905
+ Calling the forward transform (:func:`~torch.fft.hfft`) with the same
906
+ normalization mode will apply an overall normalization of ``1/n`` between
907
+ the two transforms. This is required to make :func:`~torch.fft.ihfft`
908
+ the exact inverse.
909
+
910
+ Default is ``"backward"`` (normalize by ``1/n``).
911
+
912
+ Keyword args:
913
+ {out}
914
+
915
+ Example:
916
+
917
+ >>> t = torch.arange(5)
918
+ >>> t
919
+ tensor([0, 1, 2, 3, 4])
920
+ >>> torch.fft.ihfft(t)
921
+ tensor([ 2.0000-0.0000j, -0.5000-0.6882j, -0.5000-0.1625j])
922
+
923
+ Compare against the full output from :func:`~torch.fft.ifft`:
924
+
925
+ >>> torch.fft.ifft(t)
926
+ tensor([ 2.0000-0.0000j, -0.5000-0.6882j, -0.5000-0.1625j, -0.5000+0.1625j,
927
+ -0.5000+0.6882j])
928
+ """.format(**common_args),
929
+ )
930
+
931
+ hfft2 = _add_docstr(
932
+ _fft.fft_hfft2,
933
+ r"""
934
+ hfft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
935
+
936
+ Computes the 2-dimensional discrete Fourier transform of a Hermitian symmetric
937
+ :attr:`input` signal. Equivalent to :func:`~torch.fft.hfftn` but only
938
+ transforms the last two dimensions by default.
939
+
940
+ :attr:`input` is interpreted as a one-sided Hermitian signal in the time
941
+ domain. By the Hermitian property, the Fourier transform will be real-valued.
942
+
943
+ Note:
944
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
945
+ However it only supports powers of 2 signal length in every transformed dimensions.
946
+ With default arguments, the size of last dimension should be (2^n + 1) as argument
947
+ `s` defaults to even output size = 2 * (last_dim_size - 1)
948
+
949
+ Args:
950
+ input (Tensor): the input tensor
951
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
952
+ If given, each dimension ``dim[i]`` will either be zero-padded or
953
+ trimmed to the length ``s[i]`` before computing the Hermitian FFT.
954
+ If a length ``-1`` is specified, no padding is done in that dimension.
955
+ Defaults to even output in the last dimension:
956
+ ``s[-1] = 2*(input.size(dim[-1]) - 1)``.
957
+ dim (Tuple[int], optional): Dimensions to be transformed.
958
+ The last dimension must be the half-Hermitian compressed dimension.
959
+ Default: last two dimensions.
960
+ norm (str, optional): Normalization mode. For the forward transform
961
+ (:func:`~torch.fft.hfft2`), these correspond to:
962
+
963
+ * ``"forward"`` - normalize by ``1/n``
964
+ * ``"backward"`` - no normalization
965
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the Hermitian FFT orthonormal)
966
+
967
+ Where ``n = prod(s)`` is the logical FFT size.
968
+ Calling the backward transform (:func:`~torch.fft.ihfft2`) with the same
969
+ normalization mode will apply an overall normalization of ``1/n`` between
970
+ the two transforms. This is required to make :func:`~torch.fft.ihfft2`
971
+ the exact inverse.
972
+
973
+ Default is ``"backward"`` (no normalization).
974
+
975
+ Keyword args:
976
+ {out}
977
+
978
+ Example:
979
+
980
+ Starting from a real frequency-space signal, we can generate a
981
+ Hermitian-symmetric time-domain signal:
982
+ >>> T = torch.rand(10, 9)
983
+ >>> t = torch.fft.ihfft2(T)
984
+
985
+ Without specifying the output length to :func:`~torch.fft.hfftn`, the
986
+ output will not round-trip properly because the input is odd-length in the
987
+ last dimension:
988
+
989
+ >>> torch.fft.hfft2(t).size()
990
+ torch.Size([10, 10])
991
+
992
+ So, it is recommended to always pass the signal shape :attr:`s`.
993
+
994
+ >>> roundtrip = torch.fft.hfft2(t, T.size())
995
+ >>> roundtrip.size()
996
+ torch.Size([10, 9])
997
+ >>> torch.allclose(roundtrip, T)
998
+ True
999
+
1000
+ """.format(**common_args),
1001
+ )
1002
+
1003
+ ihfft2 = _add_docstr(
1004
+ _fft.fft_ihfft2,
1005
+ r"""
1006
+ ihfft2(input, s=None, dim=(-2, -1), norm=None, *, out=None) -> Tensor
1007
+
1008
+ Computes the 2-dimensional inverse discrete Fourier transform of real
1009
+ :attr:`input`. Equivalent to :func:`~torch.fft.ihfftn` but transforms only the
1010
+ two last dimensions by default.
1011
+
1012
+ Note:
1013
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
1014
+ However it only supports powers of 2 signal length in every transformed dimensions.
1015
+
1016
+ Args:
1017
+ input (Tensor): the input tensor
1018
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
1019
+ If given, each dimension ``dim[i]`` will either be zero-padded or
1020
+ trimmed to the length ``s[i]`` before computing the Hermitian IFFT.
1021
+ If a length ``-1`` is specified, no padding is done in that dimension.
1022
+ Default: ``s = [input.size(d) for d in dim]``
1023
+ dim (Tuple[int], optional): Dimensions to be transformed.
1024
+ Default: last two dimensions.
1025
+ norm (str, optional): Normalization mode. For the backward transform
1026
+ (:func:`~torch.fft.ihfft2`), these correspond to:
1027
+
1028
+ * ``"forward"`` - no normalization
1029
+ * ``"backward"`` - normalize by ``1/n``
1030
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the Hermitian IFFT orthonormal)
1031
+
1032
+ Where ``n = prod(s)`` is the logical IFFT size.
1033
+ Calling the forward transform (:func:`~torch.fft.hfft2`) with the same
1034
+ normalization mode will apply an overall normalization of ``1/n`` between
1035
+ the two transforms. This is required to make :func:`~torch.fft.ihfft2`
1036
+ the exact inverse.
1037
+
1038
+ Default is ``"backward"`` (normalize by ``1/n``).
1039
+
1040
+ Keyword args:
1041
+ {out}
1042
+
1043
+ Example:
1044
+
1045
+ >>> T = torch.rand(10, 10)
1046
+ >>> t = torch.fft.ihfft2(t)
1047
+ >>> t.size()
1048
+ torch.Size([10, 6])
1049
+
1050
+ Compared against the full output from :func:`~torch.fft.ifft2`, the
1051
+ Hermitian time-space signal takes up only half the space.
1052
+
1053
+ >>> fftn = torch.fft.ifft2(t)
1054
+ >>> torch.allclose(fftn[..., :6], rfftn)
1055
+ True
1056
+
1057
+ The discrete Fourier transform is separable, so :func:`~torch.fft.ihfft2`
1058
+ here is equivalent to a combination of :func:`~torch.fft.ifft` and
1059
+ :func:`~torch.fft.ihfft`:
1060
+
1061
+ >>> two_ffts = torch.fft.ifft(torch.fft.ihfft(t, dim=1), dim=0)
1062
+ >>> torch.allclose(t, two_ffts)
1063
+ True
1064
+
1065
+ """.format(**common_args),
1066
+ )
1067
+
1068
+ hfftn = _add_docstr(
1069
+ _fft.fft_hfftn,
1070
+ r"""
1071
+ hfftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
1072
+
1073
+ Computes the n-dimensional discrete Fourier transform of a Hermitian symmetric
1074
+ :attr:`input` signal.
1075
+
1076
+ :attr:`input` is interpreted as a one-sided Hermitian signal in the time
1077
+ domain. By the Hermitian property, the Fourier transform will be real-valued.
1078
+
1079
+ Note:
1080
+ :func:`~torch.fft.hfftn`/:func:`~torch.fft.ihfftn` are analogous to
1081
+ :func:`~torch.fft.rfftn`/:func:`~torch.fft.irfftn`. The real FFT expects
1082
+ a real signal in the time-domain and gives Hermitian symmetry in the
1083
+ frequency-domain. The Hermitian FFT is the opposite; Hermitian symmetric in
1084
+ the time-domain and real-valued in the frequency-domain. For this reason,
1085
+ special care needs to be taken with the shape argument :attr:`s`, in the
1086
+ same way as with :func:`~torch.fft.irfftn`.
1087
+
1088
+ Note:
1089
+ Some input frequencies must be real-valued to satisfy the Hermitian
1090
+ property. In these cases the imaginary component will be ignored.
1091
+ For example, any imaginary component in the zero-frequency term cannot
1092
+ be represented in a real output and so will always be ignored.
1093
+
1094
+ Note:
1095
+ The correct interpretation of the Hermitian input depends on the length of
1096
+ the original data, as given by :attr:`s`. This is because each input shape
1097
+ could correspond to either an odd or even length signal. By default, the
1098
+ signal is assumed to be even length and odd signals will not round-trip
1099
+ properly. It is recommended to always pass the signal shape :attr:`s`.
1100
+
1101
+ Note:
1102
+ Supports torch.half and torch.chalf on CUDA with GPU Architecture SM53 or greater.
1103
+ However it only supports powers of 2 signal length in every transformed dimensions.
1104
+ With default arguments, the size of last dimension should be (2^n + 1) as argument
1105
+ `s` defaults to even output size = 2 * (last_dim_size - 1)
1106
+
1107
+ Args:
1108
+ input (Tensor): the input tensor
1109
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
1110
+ If given, each dimension ``dim[i]`` will either be zero-padded or
1111
+ trimmed to the length ``s[i]`` before computing the real FFT.
1112
+ If a length ``-1`` is specified, no padding is done in that dimension.
1113
+ Defaults to even output in the last dimension:
1114
+ ``s[-1] = 2*(input.size(dim[-1]) - 1)``.
1115
+ dim (Tuple[int], optional): Dimensions to be transformed.
1116
+ The last dimension must be the half-Hermitian compressed dimension.
1117
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
1118
+ norm (str, optional): Normalization mode. For the forward transform
1119
+ (:func:`~torch.fft.hfftn`), these correspond to:
1120
+
1121
+ * ``"forward"`` - normalize by ``1/n``
1122
+ * ``"backward"`` - no normalization
1123
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the Hermitian FFT orthonormal)
1124
+
1125
+ Where ``n = prod(s)`` is the logical FFT size.
1126
+ Calling the backward transform (:func:`~torch.fft.ihfftn`) with the same
1127
+ normalization mode will apply an overall normalization of ``1/n`` between
1128
+ the two transforms. This is required to make :func:`~torch.fft.ihfftn`
1129
+ the exact inverse.
1130
+
1131
+ Default is ``"backward"`` (no normalization).
1132
+
1133
+ Keyword args:
1134
+ {out}
1135
+
1136
+ Example:
1137
+
1138
+ Starting from a real frequency-space signal, we can generate a
1139
+ Hermitian-symmetric time-domain signal:
1140
+ >>> T = torch.rand(10, 9)
1141
+ >>> t = torch.fft.ihfftn(T)
1142
+
1143
+ Without specifying the output length to :func:`~torch.fft.hfftn`, the
1144
+ output will not round-trip properly because the input is odd-length in the
1145
+ last dimension:
1146
+
1147
+ >>> torch.fft.hfftn(t).size()
1148
+ torch.Size([10, 10])
1149
+
1150
+ So, it is recommended to always pass the signal shape :attr:`s`.
1151
+
1152
+ >>> roundtrip = torch.fft.hfftn(t, T.size())
1153
+ >>> roundtrip.size()
1154
+ torch.Size([10, 9])
1155
+ >>> torch.allclose(roundtrip, T)
1156
+ True
1157
+
1158
+ """.format(**common_args),
1159
+ )
1160
+
1161
+ ihfftn = _add_docstr(
1162
+ _fft.fft_ihfftn,
1163
+ r"""
1164
+ ihfftn(input, s=None, dim=None, norm=None, *, out=None) -> Tensor
1165
+
1166
+ Computes the N-dimensional inverse discrete Fourier transform of real :attr:`input`.
1167
+
1168
+ :attr:`input` must be a real-valued signal, interpreted in the Fourier domain.
1169
+ The n-dimensional IFFT of a real signal is Hermitian-symmetric,
1170
+ ``X[i, j, ...] = conj(X[-i, -j, ...])``. :func:`~torch.fft.ihfftn` represents
1171
+ this in the one-sided form where only the positive frequencies below the
1172
+ Nyquist frequency are included in the last signal dimension. To compute the
1173
+ full output, use :func:`~torch.fft.ifftn`.
1174
+
1175
+ Note:
1176
+ Supports torch.half on CUDA with GPU Architecture SM53 or greater.
1177
+ However it only supports powers of 2 signal length in every transformed dimensions.
1178
+
1179
+ Args:
1180
+ input (Tensor): the input tensor
1181
+ s (Tuple[int], optional): Signal size in the transformed dimensions.
1182
+ If given, each dimension ``dim[i]`` will either be zero-padded or
1183
+ trimmed to the length ``s[i]`` before computing the Hermitian IFFT.
1184
+ If a length ``-1`` is specified, no padding is done in that dimension.
1185
+ Default: ``s = [input.size(d) for d in dim]``
1186
+ dim (Tuple[int], optional): Dimensions to be transformed.
1187
+ Default: all dimensions, or the last ``len(s)`` dimensions if :attr:`s` is given.
1188
+ norm (str, optional): Normalization mode. For the backward transform
1189
+ (:func:`~torch.fft.ihfftn`), these correspond to:
1190
+
1191
+ * ``"forward"`` - no normalization
1192
+ * ``"backward"`` - normalize by ``1/n``
1193
+ * ``"ortho"`` - normalize by ``1/sqrt(n)`` (making the Hermitian IFFT orthonormal)
1194
+
1195
+ Where ``n = prod(s)`` is the logical IFFT size.
1196
+ Calling the forward transform (:func:`~torch.fft.hfftn`) with the same
1197
+ normalization mode will apply an overall normalization of ``1/n`` between
1198
+ the two transforms. This is required to make :func:`~torch.fft.ihfftn`
1199
+ the exact inverse.
1200
+
1201
+ Default is ``"backward"`` (normalize by ``1/n``).
1202
+
1203
+ Keyword args:
1204
+ {out}
1205
+
1206
+ Example:
1207
+
1208
+ >>> T = torch.rand(10, 10)
1209
+ >>> ihfftn = torch.fft.ihfftn(T)
1210
+ >>> ihfftn.size()
1211
+ torch.Size([10, 6])
1212
+
1213
+ Compared against the full output from :func:`~torch.fft.ifftn`, we have all
1214
+ elements up to the Nyquist frequency.
1215
+
1216
+ >>> ifftn = torch.fft.ifftn(t)
1217
+ >>> torch.allclose(ifftn[..., :6], ihfftn)
1218
+ True
1219
+
1220
+ The discrete Fourier transform is separable, so :func:`~torch.fft.ihfftn`
1221
+ here is equivalent to a combination of :func:`~torch.fft.ihfft` and
1222
+ :func:`~torch.fft.ifft`:
1223
+
1224
+ >>> two_iffts = torch.fft.ifft(torch.fft.ihfft(t, dim=1), dim=0)
1225
+ >>> torch.allclose(ihfftn, two_iffts)
1226
+ True
1227
+
1228
+ """.format(**common_args),
1229
+ )
1230
+
1231
+ fftfreq = _add_docstr(
1232
+ _fft.fft_fftfreq,
1233
+ r"""
1234
+ fftfreq(n, d=1.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
1235
+
1236
+ Computes the discrete Fourier Transform sample frequencies for a signal of size :attr:`n`.
1237
+
1238
+ Note:
1239
+ By convention, :func:`~torch.fft.fft` returns positive frequency terms
1240
+ first, followed by the negative frequencies in reverse order, so that
1241
+ ``f[-i]`` for all :math:`0 < i \leq n/2`` in Python gives the negative
1242
+ frequency terms. For an FFT of length :attr:`n` and with inputs spaced in
1243
+ length unit :attr:`d`, the frequencies are::
1244
+
1245
+ f = [0, 1, ..., (n - 1) // 2, -(n // 2), ..., -1] / (d * n)
1246
+
1247
+ Note:
1248
+ For even lengths, the Nyquist frequency at ``f[n/2]`` can be thought of as
1249
+ either negative or positive. :func:`~torch.fft.fftfreq` follows NumPy's
1250
+ convention of taking it to be negative.
1251
+
1252
+ Args:
1253
+ n (int): the FFT length
1254
+ d (float, optional): The sampling length scale.
1255
+ The spacing between individual samples of the FFT input.
1256
+ The default assumes unit spacing, dividing that result by the actual
1257
+ spacing gives the result in physical frequency units.
1258
+
1259
+ Keyword Args:
1260
+ {out}
1261
+ {dtype}
1262
+ {layout}
1263
+ {device}
1264
+ {requires_grad}
1265
+
1266
+ Example:
1267
+
1268
+ >>> torch.fft.fftfreq(5)
1269
+ tensor([ 0.0000, 0.2000, 0.4000, -0.4000, -0.2000])
1270
+
1271
+ For even input, we can see the Nyquist frequency at ``f[2]`` is given as
1272
+ negative:
1273
+
1274
+ >>> torch.fft.fftfreq(4)
1275
+ tensor([ 0.0000, 0.2500, -0.5000, -0.2500])
1276
+
1277
+ """.format(**factory_common_args),
1278
+ )
1279
+
1280
+ rfftfreq = _add_docstr(
1281
+ _fft.fft_rfftfreq,
1282
+ r"""
1283
+ rfftfreq(n, d=1.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
1284
+
1285
+ Computes the sample frequencies for :func:`~torch.fft.rfft` with a signal of size :attr:`n`.
1286
+
1287
+ Note:
1288
+ :func:`~torch.fft.rfft` returns Hermitian one-sided output, so only the
1289
+ positive frequency terms are returned. For a real FFT of length :attr:`n`
1290
+ and with inputs spaced in length unit :attr:`d`, the frequencies are::
1291
+
1292
+ f = torch.arange((n + 1) // 2) / (d * n)
1293
+
1294
+ Note:
1295
+ For even lengths, the Nyquist frequency at ``f[n/2]`` can be thought of as
1296
+ either negative or positive. Unlike :func:`~torch.fft.fftfreq`,
1297
+ :func:`~torch.fft.rfftfreq` always returns it as positive.
1298
+
1299
+ Args:
1300
+ n (int): the real FFT length
1301
+ d (float, optional): The sampling length scale.
1302
+ The spacing between individual samples of the FFT input.
1303
+ The default assumes unit spacing, dividing that result by the actual
1304
+ spacing gives the result in physical frequency units.
1305
+
1306
+ Keyword Args:
1307
+ {out}
1308
+ {dtype}
1309
+ {layout}
1310
+ {device}
1311
+ {requires_grad}
1312
+
1313
+ Example:
1314
+
1315
+ >>> torch.fft.rfftfreq(5)
1316
+ tensor([0.0000, 0.2000, 0.4000])
1317
+
1318
+ >>> torch.fft.rfftfreq(4)
1319
+ tensor([0.0000, 0.2500, 0.5000])
1320
+
1321
+ Compared to the output from :func:`~torch.fft.fftfreq`, we see that the
1322
+ Nyquist frequency at ``f[2]`` has changed sign:
1323
+ >>> torch.fft.fftfreq(4)
1324
+ tensor([ 0.0000, 0.2500, -0.5000, -0.2500])
1325
+
1326
+ """.format(**factory_common_args),
1327
+ )
1328
+
1329
+ fftshift = _add_docstr(
1330
+ _fft.fft_fftshift,
1331
+ r"""
1332
+ fftshift(input, dim=None) -> Tensor
1333
+
1334
+ Reorders n-dimensional FFT data, as provided by :func:`~torch.fft.fftn`, to have
1335
+ negative frequency terms first.
1336
+
1337
+ This performs a periodic shift of n-dimensional data such that the origin
1338
+ ``(0, ..., 0)`` is moved to the center of the tensor. Specifically, to
1339
+ ``input.shape[dim] // 2`` in each selected dimension.
1340
+
1341
+ Note:
1342
+ By convention, the FFT returns positive frequency terms first, followed by
1343
+ the negative frequencies in reverse order, so that ``f[-i]`` for all
1344
+ :math:`0 < i \leq n/2` in Python gives the negative frequency terms.
1345
+ :func:`~torch.fft.fftshift` rearranges all frequencies into ascending order
1346
+ from negative to positive with the zero-frequency term in the center.
1347
+
1348
+ Note:
1349
+ For even lengths, the Nyquist frequency at ``f[n/2]`` can be thought of as
1350
+ either negative or positive. :func:`~torch.fft.fftshift` always puts the
1351
+ Nyquist term at the 0-index. This is the same convention used by
1352
+ :func:`~torch.fft.fftfreq`.
1353
+
1354
+ Args:
1355
+ input (Tensor): the tensor in FFT order
1356
+ dim (int, Tuple[int], optional): The dimensions to rearrange.
1357
+ Only dimensions specified here will be rearranged, any other dimensions
1358
+ will be left in their original order.
1359
+ Default: All dimensions of :attr:`input`.
1360
+
1361
+ Example:
1362
+
1363
+ >>> f = torch.fft.fftfreq(4)
1364
+ >>> f
1365
+ tensor([ 0.0000, 0.2500, -0.5000, -0.2500])
1366
+
1367
+ >>> torch.fft.fftshift(f)
1368
+ tensor([-0.5000, -0.2500, 0.0000, 0.2500])
1369
+
1370
+ Also notice that the Nyquist frequency term at ``f[2]`` was moved to the
1371
+ beginning of the tensor.
1372
+
1373
+ This also works for multi-dimensional transforms:
1374
+
1375
+ >>> x = torch.fft.fftfreq(5, d=1/5) + 0.1 * torch.fft.fftfreq(5, d=1/5).unsqueeze(1)
1376
+ >>> x
1377
+ tensor([[ 0.0000, 1.0000, 2.0000, -2.0000, -1.0000],
1378
+ [ 0.1000, 1.1000, 2.1000, -1.9000, -0.9000],
1379
+ [ 0.2000, 1.2000, 2.2000, -1.8000, -0.8000],
1380
+ [-0.2000, 0.8000, 1.8000, -2.2000, -1.2000],
1381
+ [-0.1000, 0.9000, 1.9000, -2.1000, -1.1000]])
1382
+
1383
+ >>> torch.fft.fftshift(x)
1384
+ tensor([[-2.2000, -1.2000, -0.2000, 0.8000, 1.8000],
1385
+ [-2.1000, -1.1000, -0.1000, 0.9000, 1.9000],
1386
+ [-2.0000, -1.0000, 0.0000, 1.0000, 2.0000],
1387
+ [-1.9000, -0.9000, 0.1000, 1.1000, 2.1000],
1388
+ [-1.8000, -0.8000, 0.2000, 1.2000, 2.2000]])
1389
+
1390
+ :func:`~torch.fft.fftshift` can also be useful for spatial data. If our
1391
+ data is defined on a centered grid (``[-(N//2), (N-1)//2]``) then we can
1392
+ use the standard FFT defined on an uncentered grid (``[0, N)``) by first
1393
+ applying an :func:`~torch.fft.ifftshift`.
1394
+
1395
+ >>> x_centered = torch.arange(-5, 5)
1396
+ >>> x_uncentered = torch.fft.ifftshift(x_centered)
1397
+ >>> fft_uncentered = torch.fft.fft(x_uncentered)
1398
+
1399
+ Similarly, we can convert the frequency domain components to centered
1400
+ convention by applying :func:`~torch.fft.fftshift`.
1401
+
1402
+ >>> fft_centered = torch.fft.fftshift(fft_uncentered)
1403
+
1404
+ The inverse transform, from centered Fourier space back to centered spatial
1405
+ data, can be performed by applying the inverse shifts in reverse order:
1406
+
1407
+ >>> x_centered_2 = torch.fft.fftshift(torch.fft.ifft(torch.fft.ifftshift(fft_centered)))
1408
+ >>> torch.testing.assert_close(x_centered.to(torch.complex64), x_centered_2, check_stride=False)
1409
+
1410
+
1411
+ """,
1412
+ )
1413
+
1414
+ ifftshift = _add_docstr(
1415
+ _fft.fft_ifftshift,
1416
+ r"""
1417
+ ifftshift(input, dim=None) -> Tensor
1418
+
1419
+ Inverse of :func:`~torch.fft.fftshift`.
1420
+
1421
+ Args:
1422
+ input (Tensor): the tensor in FFT order
1423
+ dim (int, Tuple[int], optional): The dimensions to rearrange.
1424
+ Only dimensions specified here will be rearranged, any other dimensions
1425
+ will be left in their original order.
1426
+ Default: All dimensions of :attr:`input`.
1427
+
1428
+ Example:
1429
+
1430
+ >>> f = torch.fft.fftfreq(5)
1431
+ >>> f
1432
+ tensor([ 0.0000, 0.2000, 0.4000, -0.4000, -0.2000])
1433
+
1434
+ A round-trip through :func:`~torch.fft.fftshift` and
1435
+ :func:`~torch.fft.ifftshift` gives the same result:
1436
+
1437
+ >>> shifted = torch.fft.fftshift(f)
1438
+ >>> torch.fft.ifftshift(shifted)
1439
+ tensor([ 0.0000, 0.2000, 0.4000, -0.4000, -0.2000])
1440
+
1441
+ """,
1442
+ )
.venv/lib/python3.12/site-packages/torch/fft/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (56.8 kB). View file
 
.venv/lib/python3.12/site-packages/torch/func/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._functorch.apis import grad, grad_and_value, vmap
2
+ from torch._functorch.batch_norm_replacement import replace_all_batch_norm_modules_
3
+ from torch._functorch.eager_transforms import (
4
+ debug_unwrap,
5
+ functionalize,
6
+ hessian,
7
+ jacfwd,
8
+ jacrev,
9
+ jvp,
10
+ linearize,
11
+ vjp,
12
+ )
13
+ from torch._functorch.einops import rearrange
14
+ from torch._functorch.functional_call import functional_call, stack_module_state
15
+
16
+
17
+ __all__ = [
18
+ "grad",
19
+ "grad_and_value",
20
+ "vmap",
21
+ "replace_all_batch_norm_modules_",
22
+ "functionalize",
23
+ "hessian",
24
+ "jacfwd",
25
+ "jacrev",
26
+ "jvp",
27
+ "linearize",
28
+ "rearrange",
29
+ "vjp",
30
+ "functional_call",
31
+ "stack_module_state",
32
+ "debug_unwrap",
33
+ ]
.venv/lib/python3.12/site-packages/torch/func/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (847 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/func/__pycache__/_random.cpython-312.pyc ADDED
Binary file (13.1 kB). View file
 
.venv/lib/python3.12/site-packages/torch/func/_random.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stateless PRNG APIs.
2
+
3
+ These are experimental and subject to change without notice.
4
+ Access via ``torch.func._random``.
5
+ """
6
+
7
+ from collections.abc import Sequence
8
+
9
+ import torch
10
+
11
+
12
+ def key(
13
+ seed: int, *, device: torch.device | None = None, impl: str = "philox4x32-10"
14
+ ) -> torch.Tensor:
15
+ r"""Create a PRNG key from a seed.
16
+
17
+ A key is a tensor that encodes the state needed to deterministically
18
+ produce random values. Keys are consumed by generation functions to produce
19
+ reproducible random tensors without any global state. The internal
20
+ representation of the key depends on the chosen PRNG algorithm.
21
+
22
+ Args:
23
+ seed (int): The seed value for the PRNG.
24
+ device (:class:`torch.device`, optional): The desired device for the
25
+ returned key. Default: ``cpu``.
26
+ impl (str): PRNG algorithm. Currently only ``"philox4x32-10"`` is
27
+ supported.
28
+
29
+ Returns:
30
+ A tensor representing the PRNG key.
31
+
32
+ .. note::
33
+
34
+ For the ``"philox4x32-10"`` algorithm, the key is a uint64 tensor of
35
+ shape ``(2,)`` encoding a ``(seed, offset)`` pair. The offset determines
36
+ the starting position in the Philox output stream.
37
+
38
+ Example::
39
+
40
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
41
+ """
42
+ if impl != "philox4x32-10":
43
+ raise NotImplementedError(f"key() does not support PRNG impl '{impl}'")
44
+
45
+ # (seed, offset)
46
+ return torch.tensor([seed, 0], dtype=torch.uint64, device=device)
47
+
48
+
49
+ def split(key: torch.Tensor, num: int = 2) -> torch.Tensor:
50
+ r"""Split a PRNG key into ``num`` new independent keys.
51
+
52
+ Each returned key produces a different, deterministic random sequence.
53
+ This is the primary mechanism for deriving multiple independent keys from
54
+ a single parent key without mutating any state.
55
+
56
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, each key in the
57
+ batch is split independently and the result has shape ``(num, *batch, K)``.
58
+
59
+ Args:
60
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
61
+ :func:`fold_in`.
62
+ num (int): Number of keys to produce. Default: ``2``.
63
+
64
+ Returns:
65
+ A tensor of shape ``(num, *key.shape)`` containing the derived keys.
66
+
67
+ Example::
68
+
69
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
70
+ >>> k1, k2 = torch.func._random.split(key) # doctest: +SKIP
71
+ """
72
+ return torch.ops.aten._philox_key_split(key, num)
73
+
74
+
75
+ def fold_in(key: torch.Tensor, data: int | torch.Tensor) -> torch.Tensor:
76
+ r"""Deterministically derive a new key by folding in an integer value.
77
+
78
+ ``data`` may be a Python ``int`` or a single-item ``uint64`` tensor on the
79
+ same device as ``key``. Note that passing ``data`` as a tensor prevents it
80
+ from being baked into a captured CUDA graph, so the graph can be replayed
81
+ with a different value without recapture.
82
+
83
+ Equivalent to ``split(key, data + 1)[data]``, but more efficient when
84
+ only a single derived key is needed. Useful for associating a key with
85
+ a loop iteration, layer index, or other integer identifier.
86
+
87
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, ``data`` is
88
+ folded into each key independently.
89
+
90
+ Args:
91
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
92
+ :func:`fold_in`.
93
+ data (int or Tensor): The value to fold into the key, interpreted as
94
+ uint64. An ``int`` must be within the inclusive range
95
+ ``[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]``. Negative inputs
96
+ are remapped to positive values with the formula
97
+ ``0x1_0000_0000_0000_0000 + data``. A tensor must have dtype
98
+ ``uint64``, contain a single value, and reside on the same device
99
+ as ``key``.
100
+
101
+ Returns:
102
+ A new key tensor with the same shape as ``key``.
103
+
104
+ Example::
105
+
106
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
107
+ >>> k0 = torch.func._random.fold_in(key, 0) # doctest: +SKIP
108
+ >>> k1 = torch.func._random.fold_in(key, 1) # doctest: +SKIP
109
+ >>> # Equivalent to split:
110
+ >>> keys = torch.func._random.split(key, 2) # doctest: +SKIP
111
+ >>> assert torch.equal(k0, keys[0]) # doctest: +SKIP
112
+ >>> assert torch.equal(k1, keys[1]) # doctest: +SKIP
113
+ """
114
+ if isinstance(data, torch.Tensor):
115
+ return torch.ops.aten._philox_key_fold_in.Tensor(key, data)
116
+ data = int(data)
117
+ if not -(1 << 63) <= data <= (1 << 64) - 1:
118
+ raise ValueError(
119
+ f"fold_in: int data must be in [-2**63, 2**64 - 1], got {data}"
120
+ )
121
+ # Reinterpret as signed int64 due to ATen op schema; kernel will cast back
122
+ if data >= (1 << 63):
123
+ data -= 1 << 64
124
+ return torch.ops.aten._philox_key_fold_in(key, data)
125
+
126
+
127
+ def normal_(
128
+ key: torch.Tensor,
129
+ result: torch.Tensor,
130
+ *,
131
+ mean: float = 0.0,
132
+ std: float = 1.0,
133
+ ) -> torch.Tensor:
134
+ r"""Fill ``result`` in-place with normal random values from a PRNG key.
135
+
136
+ The values are drawn from a normal distribution with the specified ``mean``
137
+ and ``std``. The output is fully determined by the key, so calling with the
138
+ same key always produces the same result.
139
+
140
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, the leading
141
+ dimensions of ``result`` must be broadcastable with ``*batch`` and each key
142
+ independently generates its slice of the output.
143
+
144
+ Args:
145
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
146
+ :func:`fold_in`.
147
+ result (Tensor): The output tensor to fill in-place.
148
+ mean (float): Mean of the normal distribution. Default: ``0.0``.
149
+ std (float): Standard deviation of the normal distribution. Default: ``1.0``.
150
+
151
+ Returns:
152
+ ``result``, filled with normal random values.
153
+
154
+ Example::
155
+
156
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
157
+ >>> result = torch.empty(1000, device="cuda") # doctest: +SKIP
158
+ >>> torch.func._random.normal_(key, result) # doctest: +SKIP
159
+ """
160
+ return torch.ops.aten._philox_normal_(result, key, mean, std)
161
+
162
+
163
+ def normal(
164
+ key: torch.Tensor,
165
+ *shape: tuple[int, ...],
166
+ mean: float = 0.0,
167
+ std: float = 1.0,
168
+ dtype: torch.dtype | None = None,
169
+ ) -> torch.Tensor:
170
+ r"""Generate normally distributed random values from a PRNG key.
171
+
172
+ Produces a tensor of the given shape filled with values drawn from a normal
173
+ distribution with the specified ``mean`` and ``std``. The output is fully
174
+ determined by the key, so calling with the same key always returns the same
175
+ result. The output is placed on the same device as ``key``.
176
+
177
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, the leading
178
+ dimensions of ``shape`` must be broadcastable with ``*batch`` and each key
179
+ independently generates its slice of the output.
180
+
181
+ Args:
182
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
183
+ :func:`fold_in`.
184
+ *shape (int): The desired output shape.
185
+ mean (float): Mean of the normal distribution. Default: ``0.0``.
186
+ std (float): Standard deviation of the normal distribution. Default: ``1.0``.
187
+ dtype (:class:`torch.dtype`, optional): The desired dtype. Default: ``torch.float32``.
188
+
189
+ Returns:
190
+ A tensor of the given shape filled with normal random values.
191
+
192
+ Example::
193
+
194
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
195
+ >>> torch.func._random.normal(key, (1000,)) # doctest: +SKIP
196
+ """
197
+ if len(shape) == 1 and isinstance(shape[0], Sequence):
198
+ # pyrefly: ignore [bad-argument-type]
199
+ shape = tuple(shape[0])
200
+ if dtype is None:
201
+ dtype = torch.float32
202
+ # pyrefly: ignore [no-matching-overload]
203
+ result = torch.empty(shape, dtype=dtype, device=key.device)
204
+ return normal_(key, result, mean=mean, std=std)
205
+
206
+
207
+ def uniform_(
208
+ key: torch.Tensor,
209
+ result: torch.Tensor,
210
+ *,
211
+ low: float = 0.0,
212
+ high: float = 1.0,
213
+ ) -> torch.Tensor:
214
+ r"""Fill ``result`` in-place with uniform random values from a PRNG key.
215
+
216
+ The values are drawn uniformly from the interval ``[low, high)``. The output
217
+ is fully determined by the key, so calling with the same key always produces
218
+ the same result.
219
+
220
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, the leading
221
+ dimensions of ``result`` must be broadcastable with ``*batch`` and each key
222
+ independently generates its slice of the output.
223
+
224
+ Args:
225
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
226
+ :func:`fold_in`.
227
+ result (Tensor): The output tensor to fill in-place.
228
+ low (float): Lower bound (inclusive) of the uniform distribution. Default: ``0.0``.
229
+ high (float): Upper bound (exclusive) of the uniform distribution. Default: ``1.0``.
230
+
231
+ Returns:
232
+ ``result``, filled with uniform random values.
233
+
234
+ Example::
235
+
236
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
237
+ >>> result = torch.empty(1000, device="cuda") # doctest: +SKIP
238
+ >>> torch.func._random.uniform_(key, result) # doctest: +SKIP
239
+ """
240
+ return torch.ops.aten._philox_uniform_(result, key, low, high)
241
+
242
+
243
+ def uniform(
244
+ key: torch.Tensor,
245
+ *shape: tuple[int, ...],
246
+ low: float = 0.0,
247
+ high: float = 1.0,
248
+ dtype: torch.dtype | None = None,
249
+ ) -> torch.Tensor:
250
+ r"""Generate uniformly distributed random values from a PRNG key.
251
+
252
+ Produces a tensor of the given shape filled with values drawn uniformly
253
+ from the interval ``[low, high)``. The output is fully determined by the
254
+ key, so calling with the same key always returns the same result. The output
255
+ is placed on the same device as ``key``.
256
+
257
+ Supports batched keys: if ``key`` has shape ``(*batch, K)``, the leading
258
+ dimensions of ``shape`` must be broadcastable with ``*batch`` and each key
259
+ independently generates its slice of the output.
260
+
261
+ Args:
262
+ key (Tensor): A PRNG key returned by :func:`key`, :func:`split`, or
263
+ :func:`fold_in`.
264
+ *shape (int): The desired output shape.
265
+ low (float): Lower bound (inclusive) of the uniform distribution. Default: ``0.0``.
266
+ high (float): Upper bound (exclusive) of the uniform distribution. Default: ``1.0``.
267
+ dtype (:class:`torch.dtype`, optional): The desired dtype. Default: ``torch.float32``.
268
+
269
+ Returns:
270
+ A tensor of the given shape filled with uniform random values.
271
+
272
+ Example::
273
+
274
+ >>> key = torch.func._random.key(42, device="cuda") # doctest: +SKIP
275
+ >>> torch.func._random.uniform(key, (1000,)) # doctest: +SKIP
276
+ """
277
+ if len(shape) == 1 and isinstance(shape[0], Sequence):
278
+ # pyrefly: ignore [bad-argument-type]
279
+ shape = tuple(shape[0])
280
+ if dtype is None:
281
+ dtype = torch.float32
282
+ # pyrefly: ignore [no-matching-overload]
283
+ result = torch.empty(shape, dtype=dtype, device=key.device)
284
+ return uniform_(key, result, low=low, high=high)
.venv/lib/python3.12/site-packages/torch/functional.py ADDED
@@ -0,0 +1,2273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ import operator
4
+ from collections.abc import Sequence
5
+ from typing import Any, TYPE_CHECKING
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import _VF, Tensor
10
+ from torch._C import _add_docstr
11
+ from torch._jit_internal import _overload as overload, boolean_dispatch
12
+ from torch._lowrank import pca_lowrank, svd_lowrank
13
+ from torch.overrides import (
14
+ handle_torch_function,
15
+ has_torch_function,
16
+ has_torch_function_unary,
17
+ has_torch_function_variadic,
18
+ )
19
+
20
+
21
+ __all__ = [
22
+ "atleast_1d",
23
+ "atleast_2d",
24
+ "atleast_3d",
25
+ "broadcast_shapes",
26
+ "broadcast_tensors",
27
+ "cartesian_prod",
28
+ "block_diag",
29
+ "cdist",
30
+ "chain_matmul",
31
+ "einsum",
32
+ "istft",
33
+ "lu",
34
+ "norm",
35
+ "meshgrid",
36
+ "pca_lowrank",
37
+ "split",
38
+ "stft",
39
+ "svd_lowrank",
40
+ "tensordot",
41
+ "unique",
42
+ "unique_consecutive",
43
+ "unravel_index",
44
+ ]
45
+
46
+
47
+ def broadcast_tensors(*tensors):
48
+ r"""broadcast_tensors(*tensors) -> List of Tensors
49
+
50
+ Broadcasts the given tensors according to :ref:`broadcasting-semantics`.
51
+
52
+ Args:
53
+ *tensors: any number of tensors of the same type
54
+
55
+ .. warning::
56
+
57
+ More than one element of a broadcasted tensor may refer to a single
58
+ memory location. As a result, in-place operations (especially ones that
59
+ are vectorized) may result in incorrect behavior. If you need to write
60
+ to the tensors, please clone them first.
61
+
62
+ Example::
63
+
64
+ >>> x = torch.arange(3).view(1, 3)
65
+ >>> y = torch.arange(2).view(2, 1)
66
+ >>> a, b = torch.broadcast_tensors(x, y)
67
+ >>> a.size()
68
+ torch.Size([2, 3])
69
+ >>> a
70
+ tensor([[0, 1, 2],
71
+ [0, 1, 2]])
72
+ """
73
+ # This wrapper exists to support variadic args.
74
+ if has_torch_function(tensors):
75
+ return handle_torch_function(broadcast_tensors, tensors, *tensors)
76
+ return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined]
77
+
78
+
79
+ def broadcast_shapes(*shapes):
80
+ r"""broadcast_shapes(*shapes) -> Size
81
+
82
+ Similar to :func:`broadcast_tensors` but for shapes.
83
+
84
+ This is equivalent to
85
+ ``torch.broadcast_tensors(*map(torch.empty, shapes))[0].shape``
86
+ but avoids the need to create intermediate tensors. This is useful for
87
+ broadcasting tensors of common batch shape but different rightmost shape,
88
+ e.g. to broadcast mean vectors with covariance matrices.
89
+
90
+ Example::
91
+
92
+ >>> torch.broadcast_shapes((2,), (3, 1), (1, 1, 1))
93
+ torch.Size([1, 3, 2])
94
+
95
+ Args:
96
+ \*shapes (torch.Size): Shapes of tensors.
97
+
98
+ Returns:
99
+ shape (torch.Size): A shape compatible with all input shapes.
100
+
101
+ Raises:
102
+ RuntimeError: If shapes are incompatible.
103
+ """
104
+ # This wrapper exists to support variadic args.
105
+ # TODO Move this to C++ once the jit has better support for torch.Size.
106
+ if not torch.jit.is_tracing():
107
+ result = torch._refs._broadcast_shapes(*shapes)
108
+ if result is None:
109
+ return torch.Size([])
110
+ return torch.Size(result)
111
+ else:
112
+ # with implementation above, torch.jit.trace hardcodes the sizes which makes subsequent replays fail
113
+ with torch.no_grad():
114
+ scalar = torch.zeros((), device="cpu")
115
+ tensors = [scalar.expand(shape) for shape in shapes]
116
+ tensors = broadcast_tensors(*tensors)
117
+ return tensors[0].shape
118
+
119
+
120
+ def split(
121
+ tensor: Tensor,
122
+ split_size_or_sections: int | list[int],
123
+ dim: int = 0,
124
+ ) -> tuple[Tensor, ...]:
125
+ r"""Splits the tensor into chunks. Each chunk is a view of the original tensor.
126
+
127
+ If :attr:`split_size_or_sections` is an integer type, then :attr:`tensor` will
128
+ be split into equally sized chunks (if possible). Last chunk will be smaller if
129
+ the tensor size along the given dimension :attr:`dim` is not divisible by
130
+ :attr:`split_size`.
131
+
132
+ If :attr:`split_size_or_sections` is a list, then :attr:`tensor` will be split
133
+ into ``len(split_size_or_sections)`` chunks with sizes in :attr:`dim` according
134
+ to :attr:`split_size_or_sections`.
135
+
136
+ Args:
137
+ tensor (Tensor): tensor to split.
138
+ split_size_or_sections (int) or (list(int)): size of a single chunk or
139
+ list of sizes for each chunk
140
+ dim (int): dimension along which to split the tensor.
141
+
142
+ Example::
143
+
144
+ >>> a = torch.arange(10).reshape(5, 2)
145
+ >>> a
146
+ tensor([[0, 1],
147
+ [2, 3],
148
+ [4, 5],
149
+ [6, 7],
150
+ [8, 9]])
151
+ >>> torch.split(a, 2)
152
+ (tensor([[0, 1],
153
+ [2, 3]]),
154
+ tensor([[4, 5],
155
+ [6, 7]]),
156
+ tensor([[8, 9]]))
157
+ >>> torch.split(a, [1, 4])
158
+ (tensor([[0, 1]]),
159
+ tensor([[2, 3],
160
+ [4, 5],
161
+ [6, 7],
162
+ [8, 9]]))
163
+ """
164
+ if has_torch_function_unary(tensor):
165
+ return handle_torch_function(
166
+ split, (tensor,), tensor, split_size_or_sections, dim=dim
167
+ )
168
+ # Overwriting reason:
169
+ # This dispatches to two ATen functions depending on the type of
170
+ # split_size_or_sections. The branching code is in _tensor.py, which we
171
+ # call here.
172
+ return tensor.split(split_size_or_sections, dim)
173
+
174
+
175
+ def einsum(*args: Any) -> Tensor:
176
+ r"""einsum(equation, *operands) -> Tensor
177
+
178
+ Sums the product of the elements of the input :attr:`operands` along dimensions specified using a notation
179
+ based on the Einstein summation convention.
180
+
181
+ Einsum allows computing many common multi-dimensional linear algebraic array operations by representing them
182
+ in a short-hand format based on the Einstein summation convention, given by :attr:`equation`. The details of
183
+ this format are described below, but the general idea is to label every dimension of the input :attr:`operands`
184
+ with some subscript and define which subscripts are part of the output. The output is then computed by summing
185
+ the product of the elements of the :attr:`operands` along the dimensions whose subscripts are not part of the
186
+ output. For example, matrix multiplication can be computed using einsum as `torch.einsum("ij,jk->ik", A, B)`.
187
+ Here, j is the summation subscript and i and k the output subscripts (see section below for more details on why).
188
+
189
+ Equation:
190
+
191
+ The :attr:`equation` string specifies the subscripts (letters in `[a-zA-Z]`) for each dimension of
192
+ the input :attr:`operands` in the same order as the dimensions, separating subscripts for each operand by a
193
+ comma (','), e.g. `'ij,jk'` specify subscripts for two 2D operands. The dimensions labeled with the same subscript
194
+ must be broadcastable, that is, their size must either match or be `1`. The exception is if a subscript is
195
+ repeated for the same input operand, in which case the dimensions labeled with this subscript for this operand
196
+ must match in size and the operand will be replaced by its diagonal along these dimensions. The subscripts that
197
+ appear exactly once in the :attr:`equation` will be part of the output, sorted in increasing alphabetical order.
198
+ The output is computed by multiplying the input :attr:`operands` element-wise, with their dimensions aligned based
199
+ on the subscripts, and then summing out the dimensions whose subscripts are not part of the output.
200
+
201
+ Optionally, the output subscripts can be explicitly defined by adding an arrow ('->') at the end of the equation
202
+ followed by the subscripts for the output. For instance, the following equation computes the transpose of a
203
+ matrix multiplication: 'ij,jk->ki'. The output subscripts must appear at least once for some input operand and
204
+ at most once for the output.
205
+
206
+ Ellipsis ('...') can be used in place of subscripts to broadcast the dimensions covered by the ellipsis.
207
+ Each input operand may contain at most one ellipsis which will cover the dimensions not covered by subscripts,
208
+ e.g. for an input operand with 5 dimensions, the ellipsis in the equation `'ab...c'` cover the third and fourth
209
+ dimensions. The ellipsis does not need to cover the same number of dimensions across the :attr:`operands` but the
210
+ 'shape' of the ellipsis (the size of the dimensions covered by them) must broadcast together. If the output is not
211
+ explicitly defined with the arrow ('->') notation, the ellipsis will come first in the output (left-most dimensions),
212
+ before the subscript labels that appear exactly once for the input operands. e.g. the following equation implements
213
+ batch matrix multiplication `'...ij,...jk'`.
214
+
215
+ A few final notes: the equation may contain whitespaces between the different elements (subscripts, ellipsis,
216
+ arrow and comma) but something like `'. . .'` is not valid. An empty string `''` is valid for scalar operands.
217
+
218
+ .. note::
219
+
220
+ ``torch.einsum`` handles ellipsis ('...') differently from NumPy in that it allows dimensions
221
+ covered by the ellipsis to be summed over, that is, ellipsis are not required to be part of the output.
222
+
223
+ .. note::
224
+
225
+ Please install opt-einsum (https://optimized-einsum.readthedocs.io/en/stable/) in order to enroll into a more
226
+ performant einsum. You can install when installing torch like so: `pip install torch[opt-einsum]` or by itself
227
+ with `pip install opt-einsum`.
228
+
229
+ If opt-einsum is available, this function will automatically speed up computation and/or consume less memory
230
+ by optimizing contraction order through our opt_einsum backend :mod:`torch.backends.opt_einsum` (The _ vs - is
231
+ confusing, I know). This optimization occurs when there are at least three inputs, since the order does not matter
232
+ otherwise. Note that finding `the` optimal path is an NP-hard problem, thus, opt-einsum relies on different
233
+ heuristics to achieve near-optimal results. If opt-einsum is not available, the default order is to contract
234
+ from left to right.
235
+
236
+ To bypass this default behavior, add the following to disable opt_einsum and skip path calculation:
237
+ ``torch.backends.opt_einsum.enabled = False``
238
+
239
+ To specify which strategy you'd like for opt_einsum to compute the contraction path, add the following line:
240
+ ``torch.backends.opt_einsum.strategy = 'auto'``. The default strategy is 'auto', and we also support 'greedy' and
241
+ 'optimal'. Disclaimer that the runtime of 'optimal' is factorial in the number of inputs! See more details in
242
+ the opt_einsum documentation (https://optimized-einsum.readthedocs.io/en/stable/path_finding.html).
243
+
244
+ .. note::
245
+
246
+ As of PyTorch 1.10 :func:`torch.einsum` also supports the sublist format (see examples below). In this format,
247
+ subscripts for each operand are specified by sublists, list of integers in the range [0, 52). These sublists
248
+ follow their operands, and an extra sublist can appear at the end of the input to specify the output's
249
+ subscripts., e.g. `torch.einsum(op1, sublist1, op2, sublist2, ..., [subslist_out])`. Python's `Ellipsis` object
250
+ may be provided in a sublist to enable broadcasting as described in the Equation section above.
251
+
252
+ Args:
253
+ equation (str): The subscripts for the Einstein summation.
254
+ operands (List[Tensor]): The tensors to compute the Einstein summation of.
255
+
256
+ Examples::
257
+
258
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
259
+ >>> # trace
260
+ >>> torch.einsum('ii', torch.randn(4, 4))
261
+ tensor(-1.2104)
262
+
263
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
264
+ >>> # diagonal
265
+ >>> torch.einsum('ii->i', torch.randn(4, 4))
266
+ tensor([-0.1034, 0.7952, -0.2433, 0.4545])
267
+
268
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
269
+ >>> # outer product
270
+ >>> x = torch.randn(5)
271
+ >>> y = torch.randn(4)
272
+ >>> torch.einsum('i,j->ij', x, y)
273
+ tensor([[ 0.1156, -0.2897, -0.3918, 0.4963],
274
+ [-0.3744, 0.9381, 1.2685, -1.6070],
275
+ [ 0.7208, -1.8058, -2.4419, 3.0936],
276
+ [ 0.1713, -0.4291, -0.5802, 0.7350],
277
+ [ 0.5704, -1.4290, -1.9323, 2.4480]])
278
+
279
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
280
+ >>> # batch matrix multiplication
281
+ >>> As = torch.randn(3, 2, 5)
282
+ >>> Bs = torch.randn(3, 5, 4)
283
+ >>> torch.einsum('bij,bjk->bik', As, Bs)
284
+ tensor([[[-1.0564, -1.5904, 3.2023, 3.1271],
285
+ [-1.6706, -0.8097, -0.8025, -2.1183]],
286
+
287
+ [[ 4.2239, 0.3107, -0.5756, -0.2354],
288
+ [-1.4558, -0.3460, 1.5087, -0.8530]],
289
+
290
+ [[ 2.8153, 1.8787, -4.3839, -1.2112],
291
+ [ 0.3728, -2.1131, 0.0921, 0.8305]]])
292
+
293
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
294
+ >>> # with sublist format and ellipsis
295
+ >>> torch.einsum(As, [..., 0, 1], Bs, [..., 1, 2], [..., 0, 2])
296
+ tensor([[[-1.0564, -1.5904, 3.2023, 3.1271],
297
+ [-1.6706, -0.8097, -0.8025, -2.1183]],
298
+
299
+ [[ 4.2239, 0.3107, -0.5756, -0.2354],
300
+ [-1.4558, -0.3460, 1.5087, -0.8530]],
301
+
302
+ [[ 2.8153, 1.8787, -4.3839, -1.2112],
303
+ [ 0.3728, -2.1131, 0.0921, 0.8305]]])
304
+
305
+ >>> # batch permute
306
+ >>> A = torch.randn(2, 3, 4, 5)
307
+ >>> torch.einsum('...ij->...ji', A).shape
308
+ torch.Size([2, 3, 5, 4])
309
+
310
+ >>> # equivalent to torch.nn.functional.bilinear
311
+ >>> A = torch.randn(3, 5, 4)
312
+ >>> l = torch.randn(2, 5)
313
+ >>> r = torch.randn(2, 4)
314
+ >>> torch.einsum('bn,anm,bm->ba', l, A, r)
315
+ tensor([[-0.3430, -5.2405, 0.4494],
316
+ [ 0.3311, 5.5201, -3.0356]])
317
+ """
318
+ import torch.backends.opt_einsum as opt_einsum
319
+
320
+ # This wrapper exists to support variadic args.
321
+ if len(args) < 2:
322
+ raise ValueError(
323
+ "einsum(): must specify the equation string and at least one operand, "
324
+ "or at least one operand and its subscripts list"
325
+ )
326
+
327
+ equation = None
328
+ operands = None
329
+
330
+ if isinstance(args[0], torch.Tensor):
331
+ # Convert the subscript list format which is an interleaving of operand and its subscripts
332
+ # list with an optional output subscripts list at the end (see documentation for more details on this)
333
+ # to the equation string format by creating the equation string from the subscripts list and grouping the
334
+ # input operands into a tensorlist (List[Tensor]).
335
+ def parse_subscript(n: int) -> str:
336
+ if n == Ellipsis:
337
+ return "..."
338
+ if n >= 0 and n < 26:
339
+ return chr(ord("A") + n)
340
+ if n >= 26 and n < 52:
341
+ return chr(ord("a") + n - 26)
342
+ raise ValueError(
343
+ "einsum(): subscript in subscript list is not within the valid range [0, 52)"
344
+ )
345
+
346
+ # Parse subscripts for input operands
347
+ equation = ",".join("".join(parse_subscript(s) for s in l) for l in args[1::2])
348
+
349
+ # Parse optional output subscripts (provided when the number of arguments is odd)
350
+ if len(args) % 2 == 1:
351
+ equation += "->" + "".join(parse_subscript(s) for s in args[-1])
352
+ operands = args[:-1:2]
353
+ else:
354
+ operands = args[::2]
355
+ else:
356
+ equation = args[0]
357
+ operands = args[1:]
358
+
359
+ if has_torch_function(operands):
360
+ return handle_torch_function(einsum, operands, equation, *operands)
361
+
362
+ if len(operands) == 1 and isinstance(operands[0], (list, tuple)):
363
+ # the old interface of passing the operands as one list argument
364
+ _operands = operands[0]
365
+ # recurse in case operands contains value that has torch function
366
+ # in the original implementation this line is omitted
367
+ return einsum(equation, *_operands)
368
+
369
+ if len(operands) <= 2 or not opt_einsum.enabled:
370
+ # the path for contracting 0 or 1 time(s) is already optimized
371
+ # or the user has disabled using opt_einsum
372
+ return _VF.einsum(equation, operands) # type: ignore[attr-defined]
373
+
374
+ path = None
375
+ if opt_einsum.is_available():
376
+ _opt_einsum = opt_einsum.get_opt_einsum()
377
+ tupled_path = _opt_einsum.contract_path(
378
+ equation, *operands, optimize=opt_einsum.strategy
379
+ )[0]
380
+ # flatten path for dispatching to C++
381
+ path = [*itertools.chain.from_iterable(tupled_path)]
382
+ return _VF.einsum(equation, operands, path=path) # type: ignore[attr-defined]
383
+
384
+
385
+ # This wrapper exists to support variadic args.
386
+ if TYPE_CHECKING:
387
+ # The JIT doesn't understand Union, so only add type annotation for mypy
388
+ def meshgrid(
389
+ *tensors: Tensor | list[Tensor], indexing: str | None = None
390
+ ) -> tuple[Tensor, ...]:
391
+ return _meshgrid(*tensors, indexing=indexing)
392
+
393
+ else:
394
+
395
+ def meshgrid(*tensors, indexing: str | None = None) -> tuple[Tensor, ...]:
396
+ r"""Creates grids of coordinates specified by the 1D inputs in `attr`:tensors.
397
+
398
+ This is helpful when you want to visualize data over some
399
+ range of inputs. See below for a plotting example.
400
+
401
+ Given :math:`N` 1D tensors :math:`T_0 \ldots T_{N-1}` as
402
+ inputs with corresponding sizes :math:`S_0 \ldots S_{N-1}`,
403
+ this creates :math:`N` N-dimensional tensors :math:`G_0 \ldots
404
+ G_{N-1}`, each with shape :math:`(S_0, ..., S_{N-1})` where
405
+ the output :math:`G_i` is constructed by expanding :math:`T_i`
406
+ to the result shape.
407
+
408
+ .. note::
409
+ 0D inputs are treated equivalently to 1D inputs of a
410
+ single element.
411
+
412
+ .. warning::
413
+ `torch.meshgrid(*tensors)` currently has the same behavior
414
+ as calling `numpy.meshgrid(*arrays, indexing='ij')`.
415
+
416
+ In the future `torch.meshgrid` will transition to
417
+ `indexing='xy'` as the default.
418
+
419
+ https://github.com/pytorch/pytorch/issues/50276 tracks
420
+ this issue with the goal of migrating to NumPy's behavior.
421
+
422
+ .. seealso::
423
+
424
+ :func:`torch.cartesian_prod` has the same effect but it
425
+ collects the data in a tensor of vectors.
426
+
427
+ Args:
428
+ tensors (list of Tensor): list of scalars or 1 dimensional tensors. Scalars will be
429
+ treated as tensors of size :math:`(1,)` automatically
430
+
431
+ indexing: (str, optional): the indexing mode, either "xy"
432
+ or "ij", defaults to "ij". See warning for future changes.
433
+
434
+ If "xy" is selected, the first dimension corresponds
435
+ to the cardinality of the second input and the second
436
+ dimension corresponds to the cardinality of the first
437
+ input.
438
+
439
+ If "ij" is selected, the dimensions are in the same
440
+ order as the cardinality of the inputs.
441
+
442
+ Returns:
443
+ seq (sequence of Tensors): If the input has :math:`N`
444
+ tensors of size :math:`S_0 \ldots S_{N-1}``, then the
445
+ output will also have :math:`N` tensors, where each tensor
446
+ is of shape :math:`(S_0, ..., S_{N-1})`.
447
+
448
+ Example::
449
+
450
+ >>> x = torch.tensor([1, 2, 3])
451
+ >>> y = torch.tensor([4, 5, 6])
452
+
453
+ Observe the element-wise pairings across the grid, (1, 4),
454
+ (1, 5), ..., (3, 6). This is the same thing as the
455
+ cartesian product.
456
+ >>> grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
457
+ >>> grid_x
458
+ tensor([[1, 1, 1],
459
+ [2, 2, 2],
460
+ [3, 3, 3]])
461
+ >>> grid_y
462
+ tensor([[4, 5, 6],
463
+ [4, 5, 6],
464
+ [4, 5, 6]])
465
+
466
+ This correspondence can be seen when these grids are
467
+ stacked properly.
468
+ >>> torch.equal(torch.cat(tuple(torch.dstack([grid_x, grid_y]))),
469
+ ... torch.cartesian_prod(x, y))
470
+ True
471
+
472
+ `torch.meshgrid` is commonly used to produce a grid for
473
+ plotting.
474
+ >>> # xdoctest: +REQUIRES(module:matplotlib)
475
+ >>> # xdoctest: +REQUIRES(env:DOCTEST_SHOW)
476
+ >>> import matplotlib.pyplot as plt
477
+ >>> xs = torch.linspace(-5, 5, steps=100)
478
+ >>> ys = torch.linspace(-5, 5, steps=100)
479
+ >>> x, y = torch.meshgrid(xs, ys, indexing='xy')
480
+ >>> z = torch.sin(torch.sqrt(x * x + y * y))
481
+ >>> ax = plt.axes(projection='3d')
482
+ >>> ax.plot_surface(x.numpy(), y.numpy(), z.numpy())
483
+ >>> plt.show()
484
+
485
+ .. image:: ../_static/img/meshgrid.png
486
+ :width: 512
487
+
488
+ """
489
+ return _meshgrid(*tensors, indexing=indexing)
490
+
491
+
492
+ def _meshgrid(*tensors, indexing: str | None):
493
+ if has_torch_function(tensors):
494
+ return handle_torch_function(meshgrid, tensors, *tensors, indexing=indexing)
495
+ if len(tensors) == 1 and isinstance(tensors[0], (list, tuple)):
496
+ # the old interface of passing the operands as one list argument
497
+ tensors = tensors[0] # type: ignore[assignment]
498
+
499
+ # Continue allowing call of old method that takes no indexing
500
+ # kwarg for forward compatibility reasons.
501
+ #
502
+ # Remove this two weeks after landing.
503
+ kwargs = {} if indexing is None else {"indexing": indexing}
504
+ return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
505
+
506
+
507
+ def stft(
508
+ input: Tensor,
509
+ n_fft: int,
510
+ hop_length: int | None = None,
511
+ win_length: int | None = None,
512
+ window: Tensor | None = None,
513
+ center: bool = True,
514
+ pad_mode: str = "reflect",
515
+ normalized: bool = False,
516
+ onesided: bool | None = None,
517
+ return_complex: bool | None = None,
518
+ align_to_window: bool | None = None,
519
+ ) -> Tensor:
520
+ r"""Short-time Fourier transform (STFT).
521
+
522
+ .. warning::
523
+ From version 1.8.0, :attr:`return_complex` must always be given
524
+ explicitly for real inputs and `return_complex=False` has been
525
+ deprecated. Strongly prefer `return_complex=True` as in a future
526
+ pytorch release, this function will only return complex tensors.
527
+
528
+ Note that :func:`torch.view_as_real` can be used to recover a real
529
+ tensor with an extra last dimension for real and imaginary components.
530
+
531
+ .. warning::
532
+ From version 2.1, a warning will be provided if a :attr:`window` is
533
+ not specified. In a future release, this attribute will be required.
534
+ Not providing a window currently defaults to using a rectangular window,
535
+ which may result in undesirable artifacts. Consider using tapered windows,
536
+ such as :func:`torch.hann_window`.
537
+
538
+ The STFT computes the Fourier transform of short overlapping windows of the
539
+ input. This gives frequency components of the signal as they change over
540
+ time. The interface of this function is modeled after (but *not* a drop-in
541
+ replacement for) librosa_ stft function.
542
+
543
+ .. _librosa: https://librosa.org/doc/latest/generated/librosa.stft.html
544
+
545
+ Ignoring the optional batch dimension, this method computes the following
546
+ expression:
547
+
548
+ .. math::
549
+ X[\omega, m] = \sum_{k = 0}^{\text{win\_length-1}}%
550
+ \text{window}[k]\ \text{input}[m \times \text{hop\_length} + k]\ %
551
+ \exp\left(- j \frac{2 \pi \cdot \omega k}{\text{n\_fft}}\right),
552
+
553
+ where :math:`m` is the index of the sliding window, and :math:`\omega` is
554
+ the frequency :math:`0 \leq \omega < \text{n\_fft}` for ``onesided=False``,
555
+ or :math:`0 \leq \omega < \lfloor \text{n\_fft} / 2 \rfloor + 1` for ``onesided=True``.
556
+
557
+ * :attr:`input` must be either a 1-D time sequence or a 2-D batch of time
558
+ sequences.
559
+
560
+ * If :attr:`hop_length` is ``None`` (default), it is treated as equal to
561
+ ``floor(n_fft / 4)``.
562
+
563
+ * If :attr:`win_length` is ``None`` (default), it is treated as equal to
564
+ :attr:`n_fft`.
565
+
566
+ * :attr:`window` can be a 1-D tensor of size :attr:`win_length`, e.g., from
567
+ :meth:`torch.hann_window`. If :attr:`window` is ``None`` (default), it is
568
+ treated as if having :math:`1` everywhere in the window. If
569
+ :math:`\text{win\_length} < \text{n\_fft}`, :attr:`window` will be padded on
570
+ both sides to length :attr:`n_fft` before being applied.
571
+
572
+ * If :attr:`center` is ``True`` (default), :attr:`input` will be padded on
573
+ both sides so that the :math:`t`-th frame is centered at time
574
+ :math:`t \times \text{hop\_length}`. Otherwise, the :math:`t`-th frame
575
+ begins at time :math:`t \times \text{hop\_length}`.
576
+
577
+ * :attr:`pad_mode` determines the padding method used on :attr:`input` when
578
+ :attr:`center` is ``True``. See :meth:`torch.nn.functional.pad` for
579
+ all available options. Default is ``"reflect"``.
580
+
581
+ * If :attr:`onesided` is ``True`` (default for real input), only values for
582
+ :math:`\omega` in :math:`\left[0, 1, 2, \dots, \left\lfloor
583
+ \frac{\text{n\_fft}}{2} \right\rfloor + 1\right]` are returned because
584
+ the real-to-complex Fourier transform satisfies the conjugate symmetry,
585
+ i.e., :math:`X[m, \omega] = X[m, \text{n\_fft} - \omega]^*`.
586
+ Note if the input or window tensors are complex, then :attr:`onesided`
587
+ output is not possible.
588
+
589
+ * If :attr:`normalized` is ``True`` (default is ``False``), the function
590
+ returns the normalized STFT results, i.e., multiplied by :math:`(\text{frame\_length})^{-0.5}`.
591
+
592
+ * If :attr:`return_complex` is ``True`` (default if input is complex), the
593
+ return is a ``input.dim() + 1`` dimensional complex tensor. If ``False``,
594
+ the output is a ``input.dim() + 2`` dimensional real tensor where the last
595
+ dimension represents the real and imaginary components.
596
+
597
+ Returns either a complex tensor of size :math:`(* \times N \times T)` if
598
+ :attr:`return_complex` is true, or a real tensor of size :math:`(* \times N
599
+ \times T \times 2)`. Where :math:`*` is the optional batch size of
600
+ :attr:`input`, :math:`N` is the number of frequencies where STFT is applied
601
+ and :math:`T` is the total number of frames used.
602
+
603
+ .. warning::
604
+ This function changed signature at version 0.4.1. Calling with the
605
+ previous signature may cause error or return incorrect result.
606
+
607
+ Args:
608
+ input (Tensor): the input tensor of shape `(B?, L)` where `B?` is an optional
609
+ batch dimension
610
+ n_fft (int): size of Fourier transform
611
+ hop_length (int, optional): the distance between neighboring sliding window
612
+ frames. Default: ``None`` (treated as equal to ``floor(n_fft / 4)``)
613
+ win_length (int, optional): the size of window frame and STFT filter.
614
+ Default: ``None`` (treated as equal to :attr:`n_fft`)
615
+ window (Tensor, optional): the optional window function.
616
+ Shape must be 1d and `<= n_fft`
617
+ Default: ``None`` (treated as window of all :math:`1` s)
618
+ center (bool, optional): whether to pad :attr:`input` on both sides so
619
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
620
+ Default: ``True``
621
+ pad_mode (str, optional): controls the padding method used when
622
+ :attr:`center` is ``True``. Default: ``"reflect"``
623
+ normalized (bool, optional): controls whether to return the normalized STFT results
624
+ Default: ``False``
625
+ onesided (bool, optional): controls whether to return half of results to
626
+ avoid redundancy for real inputs.
627
+ Default: ``True`` for real :attr:`input` and :attr:`window`, ``False`` otherwise.
628
+ return_complex (bool, optional): whether to return a complex tensor, or
629
+ a real tensor with an extra last dimension for the real and
630
+ imaginary components.
631
+
632
+ .. versionchanged:: 2.0
633
+ ``return_complex`` is now a required argument for real inputs,
634
+ as the default is being transitioned to ``True``.
635
+
636
+ .. deprecated:: 2.0
637
+ ``return_complex=False`` is deprecated, instead use ``return_complex=True``
638
+ Note that calling :func:`torch.view_as_real` on the output will
639
+ recover the deprecated output format.
640
+
641
+ Returns:
642
+ Tensor: A tensor containing the STFT result with shape `(B?, N, T, C?)` where
643
+ - `B?` is an optional batch dimension from the input.
644
+ - `N` is the number of frequency samples, `(n_fft // 2) + 1` for
645
+ `onesided=True`, or otherwise `n_fft`.
646
+ - `T` is the number of frames, `1 + L // hop_length`
647
+ for `center=True`, or `1 + (L - n_fft) // hop_length` otherwise.
648
+ - `C?` is an optional length-2 dimension of real and imaginary
649
+ components, present when `return_complex=False`.
650
+
651
+ """
652
+ if has_torch_function_unary(input):
653
+ return handle_torch_function(
654
+ stft,
655
+ (input,),
656
+ input,
657
+ n_fft,
658
+ hop_length=hop_length,
659
+ win_length=win_length,
660
+ window=window,
661
+ center=center,
662
+ pad_mode=pad_mode,
663
+ normalized=normalized,
664
+ onesided=onesided,
665
+ return_complex=return_complex,
666
+ align_to_window=align_to_window,
667
+ )
668
+ if center and align_to_window is not None:
669
+ raise RuntimeError(
670
+ "stft align_to_window should only be set when center = false"
671
+ )
672
+ # NOTE: Do not edit. This code will be removed once the forward-compatibility
673
+ # period is over for PR #73432
674
+ if center:
675
+ signal_dim = input.dim()
676
+ extended_shape = [1] * (3 - signal_dim) + list(input.size())
677
+ pad = int(n_fft // 2)
678
+ input = F.pad(input.view(extended_shape), [pad, pad], pad_mode)
679
+ input = input.view(input.shape[-signal_dim:])
680
+ return _VF.stft( # type: ignore[attr-defined]
681
+ input,
682
+ n_fft,
683
+ hop_length,
684
+ win_length,
685
+ window,
686
+ normalized,
687
+ onesided,
688
+ return_complex,
689
+ align_to_window,
690
+ )
691
+
692
+
693
+ istft = _add_docstr(
694
+ torch.istft,
695
+ "istft(input, n_fft, hop_length=None, win_length=None, window=None, center=True, "
696
+ "normalized=False, onesided=None, length=None, return_complex=False) -> Tensor:\n"
697
+ r"""
698
+ Inverse short time Fourier Transform. This is expected to be the inverse of :func:`~torch.stft`.
699
+
700
+ .. warning::
701
+ From version 2.1, a warning will be provided if a :attr:`window` is
702
+ not specified. In a future release, this attribute will be required.
703
+ Please provide the same window used in the stft call.
704
+
705
+ It has the same parameters (+ additional optional parameter of :attr:`length`) and it should return the
706
+ least squares estimation of the original signal. The algorithm will check using the NOLA condition (
707
+ nonzero overlap).
708
+
709
+ Important consideration in the parameters :attr:`window` and :attr:`center` so that the envelope
710
+ created by the summation of all the windows is never zero at certain point in time. Specifically,
711
+ :math:`\sum_{t=-\infty}^{\infty} |w|^2[n-t\times hop\_length] \cancel{=} 0`.
712
+
713
+ Since :func:`~torch.stft` discards elements at the end of the signal if they do not fit in a frame,
714
+ ``istft`` may return a shorter signal than the original signal (can occur if :attr:`center` is False
715
+ since the signal isn't padded). If `length` is given in the arguments and is longer than expected,
716
+ ``istft`` will pad zeros to the end of the returned signal.
717
+
718
+ If :attr:`center` is ``True``, then there will be padding e.g. ``'constant'``, ``'reflect'``, etc.
719
+ Left padding can be trimmed off exactly because they can be calculated but right padding cannot be
720
+ calculated without additional information.
721
+
722
+ Example: Suppose the last window is:
723
+ ``[17, 18, 0, 0, 0]`` vs ``[18, 0, 0, 0, 0]``
724
+
725
+ The :attr:`n_fft`, :attr:`hop_length`, :attr:`win_length` are all the same which prevents the calculation
726
+ of right padding. These additional values could be zeros or a reflection of the signal so providing
727
+ :attr:`length` could be useful. If :attr:`length` is ``None`` then padding will be aggressively removed
728
+ (some loss of signal).
729
+
730
+ [1] D. W. Griffin and J. S. Lim, "Signal estimation from modified short-time Fourier transform,"
731
+ IEEE Trans. ASSP, vol.32, no.2, pp.236-243, Apr. 1984.
732
+
733
+ Args:
734
+ input (Tensor): The input tensor. Expected to be in the format of :func:`~torch.stft`,
735
+ output. That is a complex tensor of shape `(B?, N, T)` where
736
+
737
+ - `B?` is an optional batch dimension
738
+ - `N` is the number of frequency samples, `(n_fft // 2) + 1`
739
+ for onesided input, or otherwise `n_fft`.
740
+ - `T` is the number of frames, `1 + length // hop_length` for centered stft,
741
+ or `1 + (length - n_fft) // hop_length` otherwise.
742
+
743
+ .. versionchanged:: 2.0
744
+ Real datatype inputs are no longer supported. Input must now have a
745
+ complex datatype, as returned by ``stft(..., return_complex=True)``.
746
+ n_fft (int): Size of Fourier transform
747
+ hop_length (Optional[int]): The distance between neighboring sliding window frames.
748
+ (Default: ``n_fft // 4``)
749
+ win_length (Optional[int]): The size of window frame and STFT filter. (Default: ``n_fft``)
750
+ window (Optional[torch.Tensor]): The optional window function.
751
+ Shape must be 1d and `<= n_fft`
752
+ (Default: ``torch.ones(win_length)``)
753
+ center (bool): Whether :attr:`input` was padded on both sides so that the :math:`t`-th frame is
754
+ centered at time :math:`t \times \text{hop\_length}`.
755
+ (Default: ``True``)
756
+ normalized (bool): Whether the STFT was normalized. (Default: ``False``)
757
+ onesided (Optional[bool]): Whether the STFT was onesided.
758
+ (Default: ``True`` if `n_fft != fft_size` in the input size)
759
+ length (Optional[int]): The amount to trim the signal by (i.e. the
760
+ original signal length). Defaults to `(T - 1) * hop_length` for
761
+ centered stft, or `n_fft + (T - 1) * hop_length` otherwise, where `T`
762
+ is the number of input frames.
763
+ return_complex (Optional[bool]):
764
+ Whether the output should be complex, or if the input should be
765
+ assumed to derive from a real signal and window.
766
+ Note that this is incompatible with ``onesided=True``.
767
+ (Default: ``False``)
768
+
769
+ Returns:
770
+ Tensor: Least squares estimation of the original signal of shape `(B?, length)` where
771
+ `B?` is an optional batch dimension from the input tensor.
772
+ """,
773
+ )
774
+
775
+
776
+ if TYPE_CHECKING:
777
+ # These _impl functions return a variable number of tensors as output with
778
+ # __torch_function__; tuple unpacking is done already rather than being
779
+ # done by the caller of the _impl function
780
+ _unique_impl_out = Any
781
+ else:
782
+ _unique_impl_out = tuple[Tensor, Tensor, Tensor]
783
+
784
+
785
+ def _unique_torch_function(
786
+ input: Tensor,
787
+ sorted: bool = True,
788
+ return_inverse: bool = False,
789
+ return_counts: bool = False,
790
+ dim: int | None = None,
791
+ ) -> Any:
792
+ return handle_torch_function(
793
+ unique,
794
+ (input,),
795
+ input,
796
+ sorted=sorted,
797
+ return_inverse=return_inverse,
798
+ return_counts=return_counts,
799
+ dim=dim,
800
+ )
801
+
802
+
803
+ def _unique_impl(
804
+ input: Tensor,
805
+ sorted: bool = True,
806
+ return_inverse: bool = False,
807
+ return_counts: bool = False,
808
+ dim: int | None = None,
809
+ ) -> _unique_impl_out:
810
+ r"""unique(input, sorted=True, return_inverse=False, return_counts=False, dim=None) -> tuple[Tensor, Tensor, Tensor]
811
+
812
+ Returns the unique elements of the input tensor.
813
+
814
+ .. note:: This function is different from :func:`torch.unique_consecutive` in the sense that
815
+ this function also eliminates non-consecutive duplicate values.
816
+
817
+ .. note:: Currently in the CUDA implementation and the CPU implementation,
818
+ `torch.unique` always sort the tensor at the beginning regardless of the `sort` argument.
819
+ Sorting could be slow, so if your input tensor is already sorted, it is recommended to use
820
+ :func:`torch.unique_consecutive` which avoids the sorting.
821
+
822
+ Args:
823
+ input (Tensor): the input tensor
824
+ sorted (bool): Whether to sort the unique elements in ascending order
825
+ before returning as output.
826
+ return_inverse (bool): Whether to also return the indices for where
827
+ elements in the original input ended up in the returned unique list.
828
+ return_counts (bool): Whether to also return the counts for each unique
829
+ element.
830
+ dim (int, optional): the dimension to operate upon. If ``None``, the
831
+ unique of the flattened input is returned. Otherwise, each of the
832
+ tensors indexed by the given dimension is treated as one of the
833
+ elements to apply the unique operation upon. **Important:** when ``dim``
834
+ is specified, the operation finds unique sub-tensors (e.g., unique rows
835
+ or columns), not unique scalar values. This means individual values may
836
+ appear multiple times in the output if they exist in different sub-tensors.
837
+ See examples for more details. Default: ``None``
838
+
839
+ Returns:
840
+ (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
841
+
842
+ - **output** (*Tensor*): the output list of unique scalar elements if :attr:`dim`
843
+ is ``None``; otherwise, the unique sub-tensors along the specified dimension.
844
+ Note that when :attr:`dim` is specified, scalar values may repeat in the output.
845
+ - **inverse_indices** (*Tensor*): (optional) if
846
+ :attr:`return_inverse` is True, there will be an additional
847
+ returned tensor (same shape as input) representing the indices
848
+ for where elements in the original input map to in the output;
849
+ otherwise, this function will only return a single tensor.
850
+ - **counts** (*Tensor*): (optional) if
851
+ :attr:`return_counts` is True, there will be an additional
852
+ returned tensor (same shape as output or output.size(dim),
853
+ if dim was specified) representing the number of occurrences
854
+ for each unique value or tensor.
855
+
856
+ Example::
857
+
858
+ >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
859
+ >>> output
860
+ tensor([1, 2, 3])
861
+
862
+ >>> output, inverse_indices = torch.unique(
863
+ ... torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True)
864
+ >>> output
865
+ tensor([1, 2, 3])
866
+ >>> inverse_indices
867
+ tensor([0, 2, 1, 2])
868
+
869
+ >>> output, inverse_indices = torch.unique(
870
+ ... torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True)
871
+ >>> output
872
+ tensor([1, 2, 3])
873
+ >>> inverse_indices
874
+ tensor([[0, 2],
875
+ [1, 2]])
876
+
877
+ >>> # When using dim, the operation finds unique sub-tensors, not unique values.
878
+ >>> # Notice how values can repeat in the output:
879
+ >>> x = torch.tensor([[1, 3, 2, 3], [1, 2, 1, 2]], dtype=torch.long)
880
+ >>> torch.unique(x, dim=0) # unique rows
881
+ tensor([[1, 2, 1, 2],
882
+ [1, 3, 2, 3]])
883
+ >>> # Both rows are kept because they're different from each other,
884
+ >>> # even though values 1, 2, 3 appear multiple times in the output.
885
+ >>> torch.unique(x, dim=1) # unique columns
886
+ tensor([[1, 2, 3],
887
+ [1, 1, 2]])
888
+ >>> # The value 1 appears twice because we're comparing columns, not values.
889
+ >>> # Compare with flattened (no dim):
890
+ >>> torch.unique(x)
891
+ tensor([1, 2, 3])
892
+
893
+ >>> a = torch.tensor([
894
+ ... [
895
+ ... [1, 1, 0, 0],
896
+ ... [1, 1, 0, 0],
897
+ ... [0, 0, 1, 1],
898
+ ... ],
899
+ ... [
900
+ ... [0, 0, 1, 1],
901
+ ... [0, 0, 1, 1],
902
+ ... [1, 1, 1, 1],
903
+ ... ],
904
+ ... [
905
+ ... [1, 1, 0, 0],
906
+ ... [1, 1, 0, 0],
907
+ ... [0, 0, 1, 1],
908
+ ... ],
909
+ ... ])
910
+
911
+ >>> # If we call `torch.unique(a, dim=0)`, each of the tensors `a[idx, :, :]`
912
+ >>> # will be compared. We can see that `a[0, :, :]` and `a[2, :, :]` match
913
+ >>> # each other, so one of them will be removed.
914
+ >>> (a[0, :, :] == a[2, :, :]).all()
915
+ tensor(True)
916
+ >>> a_unique_dim0 = torch.unique(a, dim=0)
917
+ >>> a_unique_dim0
918
+ tensor([[[0, 0, 1, 1],
919
+ [0, 0, 1, 1],
920
+ [1, 1, 1, 1]],
921
+ [[1, 1, 0, 0],
922
+ [1, 1, 0, 0],
923
+ [0, 0, 1, 1]]])
924
+
925
+ >>> # Notice which sub-tensors from `a` match with the sub-tensors from
926
+ >>> # `a_unique_dim0`:
927
+ >>> (a_unique_dim0[0, :, :] == a[1, :, :]).all()
928
+ tensor(True)
929
+ >>> (a_unique_dim0[1, :, :] == a[0, :, :]).all()
930
+ tensor(True)
931
+
932
+ >>> # For `torch.unique(a, dim=1)`, each of the tensors `a[:, idx, :]` are
933
+ >>> # compared. `a[:, 0, :]` and `a[:, 1, :]` match each other, so one of
934
+ >>> # them will be removed.
935
+ >>> (a[:, 0, :] == a[:, 1, :]).all()
936
+ tensor(True)
937
+ >>> torch.unique(a, dim=1)
938
+ tensor([[[0, 0, 1, 1],
939
+ [1, 1, 0, 0]],
940
+ [[1, 1, 1, 1],
941
+ [0, 0, 1, 1]],
942
+ [[0, 0, 1, 1],
943
+ [1, 1, 0, 0]]])
944
+
945
+ >>> # For `torch.unique(a, dim=2)`, the tensors `a[:, :, idx]` are compared.
946
+ >>> # `a[:, :, 0]` and `a[:, :, 1]` match each other. Also, `a[:, :, 2]` and
947
+ >>> # `a[:, :, 3]` match each other as well. So in this case, two of the
948
+ >>> # sub-tensors will be removed.
949
+ >>> (a[:, :, 0] == a[:, :, 1]).all()
950
+ tensor(True)
951
+ >>> (a[:, :, 2] == a[:, :, 3]).all()
952
+ tensor(True)
953
+ >>> torch.unique(a, dim=2)
954
+ tensor([[[0, 1],
955
+ [0, 1],
956
+ [1, 0]],
957
+ [[1, 0],
958
+ [1, 0],
959
+ [1, 1]],
960
+ [[0, 1],
961
+ [0, 1],
962
+ [1, 0]]])
963
+ """
964
+ if dim is not None:
965
+ output, inverse_indices, counts = _VF.unique_dim(
966
+ input,
967
+ dim,
968
+ sorted=sorted,
969
+ return_inverse=return_inverse,
970
+ return_counts=return_counts,
971
+ )
972
+ else:
973
+ output, inverse_indices, counts = torch._unique2(
974
+ input,
975
+ sorted=sorted,
976
+ return_inverse=return_inverse,
977
+ return_counts=return_counts,
978
+ )
979
+ return output, inverse_indices, counts
980
+
981
+
982
+ def _unique_consecutive_torch_function(
983
+ input: Tensor,
984
+ return_inverse: bool = False,
985
+ return_counts: bool = False,
986
+ dim: int | None = None,
987
+ ) -> Any:
988
+ return handle_torch_function(
989
+ unique_consecutive,
990
+ (input,),
991
+ input,
992
+ return_inverse=return_inverse,
993
+ return_counts=return_counts,
994
+ dim=dim,
995
+ )
996
+
997
+
998
+ def _unique_consecutive_impl(
999
+ input: Tensor,
1000
+ return_inverse: bool = False,
1001
+ return_counts: bool = False,
1002
+ dim: int | None = None,
1003
+ ) -> _unique_impl_out:
1004
+ r"""Eliminates all but the first element from every consecutive group of equivalent elements.
1005
+
1006
+ .. note:: This function is different from :func:`torch.unique` in the sense that this function
1007
+ only eliminates consecutive duplicate values. This semantics is similar to `std::unique`
1008
+ in C++.
1009
+
1010
+ Args:
1011
+ input (Tensor): the input tensor
1012
+ return_inverse (bool): Whether to also return the indices for where
1013
+ elements in the original input ended up in the returned unique list.
1014
+ return_counts (bool): Whether to also return the counts for each unique
1015
+ element.
1016
+ dim (int): the dimension to apply unique. If ``None``, the unique of the
1017
+ flattened input is returned. default: ``None``
1018
+
1019
+ Returns:
1020
+ (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
1021
+
1022
+ - **output** (*Tensor*): the output list of unique scalar elements.
1023
+ - **inverse_indices** (*Tensor*): (optional) if
1024
+ :attr:`return_inverse` is True, there will be an additional
1025
+ returned tensor (same shape as input) representing the indices
1026
+ for where elements in the original input map to in the output;
1027
+ otherwise, this function will only return a single tensor.
1028
+ - **counts** (*Tensor*): (optional) if
1029
+ :attr:`return_counts` is True, there will be an additional
1030
+ returned tensor (same shape as output or output.size(dim),
1031
+ if dim was specified) representing the number of occurrences
1032
+ for each unique value or tensor.
1033
+
1034
+ Example::
1035
+
1036
+ >>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2])
1037
+ >>> output = torch.unique_consecutive(x)
1038
+ >>> output
1039
+ tensor([1, 2, 3, 1, 2])
1040
+
1041
+ >>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True)
1042
+ >>> output
1043
+ tensor([1, 2, 3, 1, 2])
1044
+ >>> inverse_indices
1045
+ tensor([0, 0, 1, 1, 2, 3, 3, 4])
1046
+
1047
+ >>> output, counts = torch.unique_consecutive(x, return_counts=True)
1048
+ >>> output
1049
+ tensor([1, 2, 3, 1, 2])
1050
+ >>> counts
1051
+ tensor([2, 2, 1, 2, 1])
1052
+ """
1053
+ output, inverse_indices, counts = _VF.unique_consecutive( # type: ignore[attr-defined]
1054
+ input, return_inverse=return_inverse, return_counts=return_counts, dim=dim
1055
+ )
1056
+ return output, inverse_indices, counts
1057
+
1058
+
1059
+ def _return_inverse_and_counts(
1060
+ input,
1061
+ sorted=True,
1062
+ return_inverse=False,
1063
+ return_counts=False,
1064
+ dim=None,
1065
+ ):
1066
+ # type: (Tensor, bool, bool, bool, Optional[int]) -> tuple[Tensor, Tensor, Tensor]
1067
+
1068
+ if has_torch_function_unary(input):
1069
+ return _unique_torch_function(input, sorted, return_inverse, return_counts, dim)
1070
+
1071
+ return _unique_impl(input, sorted, return_inverse, return_counts, dim)
1072
+
1073
+
1074
+ def _return_counts(
1075
+ input,
1076
+ sorted=True,
1077
+ return_inverse=False,
1078
+ return_counts=False,
1079
+ dim=None,
1080
+ ):
1081
+ # type: (Tensor, bool, bool, bool, Optional[int]) -> tuple[Tensor, Tensor]
1082
+
1083
+ if has_torch_function_unary(input):
1084
+ return _unique_torch_function(input, sorted, return_inverse, return_counts, dim)
1085
+
1086
+ output, _, counts = _unique_impl(input, sorted, return_inverse, return_counts, dim)
1087
+ return output, counts
1088
+
1089
+
1090
+ def _return_output(
1091
+ input,
1092
+ sorted=True,
1093
+ return_inverse=False,
1094
+ return_counts=False,
1095
+ dim=None,
1096
+ ):
1097
+ # type: (Tensor, bool, bool, bool, Optional[int]) -> Tensor
1098
+
1099
+ if has_torch_function_unary(input):
1100
+ return _unique_torch_function(input, sorted, return_inverse, return_counts, dim)
1101
+
1102
+ output, _, _ = _unique_impl(input, sorted, return_inverse, return_counts, dim)
1103
+ return output
1104
+
1105
+
1106
+ def _return_inverse(
1107
+ input,
1108
+ sorted=True,
1109
+ return_inverse=False,
1110
+ return_counts=False,
1111
+ dim=None,
1112
+ ):
1113
+ # type: (Tensor, bool, bool, bool, Optional[int]) -> tuple[Tensor, Tensor]
1114
+
1115
+ if has_torch_function_unary(input):
1116
+ return _unique_torch_function(input, sorted, return_inverse, return_counts, dim)
1117
+
1118
+ output, inverse_indices, _ = _unique_impl(
1119
+ input, sorted, return_inverse, return_counts, dim
1120
+ )
1121
+ return output, inverse_indices
1122
+
1123
+
1124
+ _return_inverse_false = boolean_dispatch(
1125
+ arg_name="return_counts",
1126
+ arg_index=3,
1127
+ default=False,
1128
+ if_true=_return_counts,
1129
+ if_false=_return_output,
1130
+ module_name=__name__,
1131
+ func_name="unique",
1132
+ )
1133
+
1134
+ _return_inverse_true = boolean_dispatch(
1135
+ arg_name="return_counts",
1136
+ arg_index=3,
1137
+ default=False,
1138
+ if_true=_return_inverse_and_counts,
1139
+ if_false=_return_inverse,
1140
+ module_name=__name__,
1141
+ func_name="unique",
1142
+ )
1143
+
1144
+ # The return type of unique depends on `return_inverse`, and `return_counts` so in order to
1145
+ # resolve the output type in TorchScript we need to statically know the value of both parameters
1146
+
1147
+ unique = boolean_dispatch(
1148
+ arg_name="return_inverse",
1149
+ arg_index=2,
1150
+ default=False,
1151
+ if_true=_return_inverse_true,
1152
+ if_false=_return_inverse_false,
1153
+ module_name=__name__,
1154
+ func_name="unique",
1155
+ )
1156
+ unique.__doc__ = _unique_impl.__doc__
1157
+
1158
+
1159
+ def _consecutive_return_inverse_and_counts(
1160
+ input,
1161
+ return_inverse=False,
1162
+ return_counts=False,
1163
+ dim=None,
1164
+ ):
1165
+ # type: (Tensor, bool, bool, Optional[int]) -> tuple[Tensor, Tensor, Tensor]
1166
+ if has_torch_function_unary(input):
1167
+ return _unique_consecutive_torch_function(
1168
+ input, return_inverse, return_counts, dim
1169
+ )
1170
+
1171
+ return _unique_consecutive_impl(input, return_inverse, return_counts, dim)
1172
+
1173
+
1174
+ def _consecutive_return_counts(
1175
+ input,
1176
+ return_inverse=False,
1177
+ return_counts=False,
1178
+ dim=None,
1179
+ ):
1180
+ # type: (Tensor, bool, bool, Optional[int]) -> tuple[Tensor, Tensor]
1181
+
1182
+ if has_torch_function_unary(input):
1183
+ return _unique_consecutive_torch_function(
1184
+ input, return_inverse, return_counts, dim
1185
+ )
1186
+
1187
+ output, _, counts = _unique_consecutive_impl(
1188
+ input, return_inverse, return_counts, dim
1189
+ )
1190
+ return output, counts
1191
+
1192
+
1193
+ def _consecutive_return_output(
1194
+ input,
1195
+ return_inverse=False,
1196
+ return_counts=False,
1197
+ dim=None,
1198
+ ):
1199
+ # type: (Tensor, bool, bool, Optional[int]) -> Tensor
1200
+
1201
+ if has_torch_function_unary(input):
1202
+ return _unique_consecutive_torch_function(
1203
+ input, return_inverse, return_counts, dim
1204
+ )
1205
+
1206
+ output, _, _ = _unique_consecutive_impl(input, return_inverse, return_counts, dim)
1207
+ return output
1208
+
1209
+
1210
+ def _consecutive_return_inverse(
1211
+ input,
1212
+ return_inverse=False,
1213
+ return_counts=False,
1214
+ dim=None,
1215
+ ):
1216
+ # type: (Tensor, bool, bool, Optional[int]) -> tuple[Tensor, Tensor]
1217
+
1218
+ if has_torch_function_unary(input):
1219
+ return _unique_consecutive_torch_function(
1220
+ input, return_inverse, return_counts, dim
1221
+ )
1222
+
1223
+ output, inverse_indices, _ = _unique_consecutive_impl(
1224
+ input, return_inverse, return_counts, dim
1225
+ )
1226
+ return output, inverse_indices
1227
+
1228
+
1229
+ _consecutive_return_inverse_false = boolean_dispatch(
1230
+ arg_name="return_counts",
1231
+ arg_index=1,
1232
+ default=False,
1233
+ if_true=_consecutive_return_counts,
1234
+ if_false=_consecutive_return_output,
1235
+ module_name=__name__,
1236
+ func_name="unique_consecutive",
1237
+ )
1238
+
1239
+ _consecutive_return_inverse_true = boolean_dispatch(
1240
+ arg_name="return_counts",
1241
+ arg_index=1,
1242
+ default=False,
1243
+ if_true=_consecutive_return_inverse_and_counts,
1244
+ if_false=_consecutive_return_inverse,
1245
+ module_name=__name__,
1246
+ func_name="unique_consecutive",
1247
+ )
1248
+
1249
+ # The return type of unique depends on `return_inverse`, and `return_counts` so in order to
1250
+ # resolve the output type in TorchScript we need to statically know the value of both parameters
1251
+
1252
+ unique_consecutive = boolean_dispatch(
1253
+ arg_name="return_inverse",
1254
+ arg_index=2,
1255
+ default=False,
1256
+ if_true=_consecutive_return_inverse_true,
1257
+ if_false=_consecutive_return_inverse_false,
1258
+ module_name=__name__,
1259
+ func_name="unique_consecutive",
1260
+ )
1261
+ unique_consecutive.__doc__ = _unique_consecutive_impl.__doc__
1262
+
1263
+ if TYPE_CHECKING:
1264
+ pass
1265
+ # There's no good way to use this type annotation without breaking JIT
1266
+ # overloads. So leave untyped for mypy for now.
1267
+ else:
1268
+
1269
+ @overload
1270
+ def tensordot(
1271
+ a,
1272
+ b,
1273
+ dims: int = 2,
1274
+ out: torch.Tensor | None = None,
1275
+ ):
1276
+ pass
1277
+
1278
+ @overload
1279
+ def tensordot( # noqa: F811
1280
+ a,
1281
+ b,
1282
+ dims: tuple[list[int], list[int]],
1283
+ out: torch.Tensor | None = None,
1284
+ ):
1285
+ pass
1286
+
1287
+ @overload
1288
+ def tensordot( # noqa: F811
1289
+ a,
1290
+ b,
1291
+ dims: list[list[int]],
1292
+ out: torch.Tensor | None = None,
1293
+ ):
1294
+ pass
1295
+
1296
+ @overload
1297
+ def tensordot( # noqa: F811
1298
+ a,
1299
+ b,
1300
+ dims: torch.Tensor,
1301
+ out: torch.Tensor | None = None,
1302
+ ):
1303
+ pass
1304
+
1305
+
1306
+ def tensordot(
1307
+ a,
1308
+ b,
1309
+ dims=2,
1310
+ out: torch.Tensor | None = None,
1311
+ ):
1312
+ r"""Returns a contraction of a and b over multiple dimensions.
1313
+
1314
+ :attr:`tensordot` implements a generalized matrix product.
1315
+
1316
+ Args:
1317
+ a (Tensor): Left tensor to contract
1318
+ b (Tensor): Right tensor to contract
1319
+ dims (int or Tuple[List[int], List[int]] or List[List[int]] containing two lists or Tensor): number of dimensions to
1320
+ contract or explicit lists of dimensions for :attr:`a` and
1321
+ :attr:`b` respectively
1322
+
1323
+ When called with a non-negative integer argument :attr:`dims` = :math:`d`, and
1324
+ the number of dimensions of :attr:`a` and :attr:`b` is :math:`m` and :math:`n`,
1325
+ respectively, :func:`~torch.tensordot` computes the tensor :math:`r` of shape
1326
+ ``a.shape[:-dims] + b.shape[dims:]`` given by:
1327
+
1328
+ .. math::
1329
+ r_{i_1,...,i_{m-d}, j_1,...,j_{n-d}}
1330
+ = \sum_{k_1,...,k_d} a_{i_1,...,i_{m-d},k_1,...,k_d} \times b_{k_1,...,k_d, j_1,...,j_{n-d}}.
1331
+
1332
+ When called with :attr:`dims` of the list form, the given dimensions will be contracted
1333
+ in place of the last :math:`d` of :attr:`a` and the first :math:`d` of :math:`b`. The sizes
1334
+ in these dimensions must match, but :func:`~torch.tensordot` will deal with broadcasted
1335
+ dimensions.
1336
+
1337
+ Examples::
1338
+
1339
+ >>> a = torch.arange(60.).reshape(3, 4, 5)
1340
+ >>> b = torch.arange(24.).reshape(4, 3, 2)
1341
+ >>> torch.tensordot(a, b, dims=([1, 0], [0, 1]))
1342
+ tensor([[4400., 4730.],
1343
+ [4532., 4874.],
1344
+ [4664., 5018.],
1345
+ [4796., 5162.],
1346
+ [4928., 5306.]])
1347
+
1348
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
1349
+ >>> a = torch.randn(3, 4, 5, device='cuda')
1350
+ >>> b = torch.randn(4, 5, 6, device='cuda')
1351
+ >>> c = torch.tensordot(a, b, dims=2).cpu()
1352
+ tensor([[ 8.3504, -2.5436, 6.2922, 2.7556, -1.0732, 3.2741],
1353
+ [ 3.3161, 0.0704, 5.0187, -0.4079, -4.3126, 4.8744],
1354
+ [ 0.8223, 3.9445, 3.2168, -0.2400, 3.4117, 1.7780]])
1355
+
1356
+ >>> a = torch.randn(3, 5, 4, 6)
1357
+ >>> b = torch.randn(6, 4, 5, 3)
1358
+ >>> torch.tensordot(a, b, dims=([2, 1, 3], [1, 2, 0]))
1359
+ tensor([[ 7.7193, -2.4867, -10.3204],
1360
+ [ 1.5513, -14.4737, -6.5113],
1361
+ [ -0.2850, 4.2573, -3.5997]])
1362
+ """
1363
+ if has_torch_function_variadic(a, b):
1364
+ return handle_torch_function(tensordot, (a, b), a, b, dims=dims, out=out)
1365
+
1366
+ if not isinstance(dims, (tuple, list, torch.Tensor, int, torch.SymInt)):
1367
+ raise RuntimeError(
1368
+ "tensordot expects dims to be int or "
1369
+ + "tuple[list[int], list[int]] or "
1370
+ + "list[list[int]] containing two lists, but got "
1371
+ + f"dims={dims}"
1372
+ )
1373
+
1374
+ dims_a: list[int] = []
1375
+ dims_b: list[int] = []
1376
+
1377
+ if isinstance(dims, (tuple, list)):
1378
+ dims_a, dims_b = dims
1379
+
1380
+ if isinstance(dims, torch.Tensor):
1381
+ num_elements = dims.numel()
1382
+ if num_elements > 1:
1383
+ if dims.size()[0] != 2:
1384
+ raise AssertionError(
1385
+ f"dims tensor must have size 2 in first dimension, got {dims.size()[0]}"
1386
+ )
1387
+ dims_a = torch.jit.annotate(list[int], dims[0].tolist())
1388
+ dims_b = torch.jit.annotate(list[int], dims[1].tolist())
1389
+ else:
1390
+ dims_val = int(dims.item())
1391
+ if dims_val < 0:
1392
+ raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}")
1393
+ dims_a = list(range(-dims_val, 0))
1394
+ dims_b = list(range(dims_val))
1395
+
1396
+ if isinstance(dims, (int, torch.SymInt)):
1397
+ if dims < 0:
1398
+ raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}")
1399
+ if dims > min(a.dim(), b.dim()):
1400
+ raise RuntimeError(
1401
+ f"tensordot expects dims < ndim_a or ndim_b, but got dims={dims}"
1402
+ )
1403
+ dims_a = list(range(-dims, 0))
1404
+ dims_b = list(range(dims))
1405
+
1406
+ if out is None:
1407
+ return _VF.tensordot(a, b, dims_a, dims_b) # type: ignore[attr-defined]
1408
+ else:
1409
+ return _VF.tensordot(a, b, dims_a, dims_b, out=out) # type: ignore[attr-defined]
1410
+
1411
+
1412
+ def cartesian_prod(*tensors: Tensor) -> Tensor:
1413
+ """Do cartesian product of the given sequence of tensors. The behavior is similar to
1414
+ python's `itertools.product`.
1415
+
1416
+ Args:
1417
+ *tensors: any number of 1 dimensional tensors.
1418
+
1419
+ Returns:
1420
+ Tensor: A tensor equivalent to converting all the input tensors into lists,
1421
+ do `itertools.product` on these lists, and finally convert the resulting list
1422
+ into tensor.
1423
+
1424
+ Example::
1425
+
1426
+ >>> import itertools
1427
+ >>> a = [1, 2, 3]
1428
+ >>> b = [4, 5]
1429
+ >>> list(itertools.product(a, b))
1430
+ [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
1431
+ >>> tensor_a = torch.tensor(a)
1432
+ >>> tensor_b = torch.tensor(b)
1433
+ >>> torch.cartesian_prod(tensor_a, tensor_b)
1434
+ tensor([[1, 4],
1435
+ [1, 5],
1436
+ [2, 4],
1437
+ [2, 5],
1438
+ [3, 4],
1439
+ [3, 5]])
1440
+ """
1441
+ # This wrapper exists to support variadic args.
1442
+ if has_torch_function(tensors):
1443
+ return handle_torch_function(cartesian_prod, tensors, *tensors)
1444
+ return _VF.cartesian_prod(tensors) # type: ignore[attr-defined]
1445
+
1446
+
1447
+ def block_diag(*tensors):
1448
+ """Create a block diagonal matrix from provided tensors.
1449
+
1450
+ Args:
1451
+ *tensors: One or more tensors with 0, 1, or 2 dimensions.
1452
+
1453
+ Returns:
1454
+ Tensor: A 2 dimensional tensor with all the input tensors arranged in
1455
+ order such that their upper left and lower right corners are
1456
+ diagonally adjacent. All other elements are set to 0.
1457
+
1458
+ Example::
1459
+
1460
+ >>> import torch
1461
+ >>> A = torch.tensor([[0, 1], [1, 0]])
1462
+ >>> B = torch.tensor([[3, 4, 5], [6, 7, 8]])
1463
+ >>> C = torch.tensor(7)
1464
+ >>> D = torch.tensor([1, 2, 3])
1465
+ >>> E = torch.tensor([[4], [5], [6]])
1466
+ >>> torch.block_diag(A, B, C, D, E)
1467
+ tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
1468
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1469
+ [0, 0, 3, 4, 5, 0, 0, 0, 0, 0],
1470
+ [0, 0, 6, 7, 8, 0, 0, 0, 0, 0],
1471
+ [0, 0, 0, 0, 0, 7, 0, 0, 0, 0],
1472
+ [0, 0, 0, 0, 0, 0, 1, 2, 3, 0],
1473
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
1474
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
1475
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 6]])
1476
+ """
1477
+ # This wrapper exists to support variadic args.
1478
+ if has_torch_function(tensors):
1479
+ return handle_torch_function(block_diag, tensors, *tensors)
1480
+ return torch._C._VariableFunctions.block_diag(tensors) # type: ignore[attr-defined]
1481
+
1482
+
1483
+ def cdist(x1, x2, p=2.0, compute_mode="use_mm_for_euclid_dist_if_necessary"):
1484
+ # type: (Tensor, Tensor, float, str) -> (Tensor)
1485
+ r"""Computes the batched p-norm distance between each pair of the two collections of row vectors.
1486
+
1487
+ Args:
1488
+ x1 (Tensor): input tensor where the last two dimensions represent the points and the feature dimension respectively.
1489
+ The shape can be :math:`D_1 \times D_2 \times \cdots \times D_n \times P \times M`,
1490
+ where :math:`P` is the number of points and :math:`M` is the feature dimension.
1491
+ x2 (Tensor): input tensor where the last two dimensions also represent the points and the feature dimension respectively.
1492
+ The shape can be :math:`D_1' \times D_2' \times \cdots \times D_m' \times R \times M`,
1493
+ where :math:`R` is the number of points and :math:`M` is the feature dimension,
1494
+ which should match the feature dimension of `x1`.
1495
+ p: p value for the p-norm distance to calculate between each vector pair
1496
+ :math:`\in [0, \infty]`.
1497
+ compute_mode:
1498
+ 'use_mm_for_euclid_dist_if_necessary' - will use matrix multiplication approach to calculate
1499
+ euclidean distance (p = 2) if P > 25 or R > 25
1500
+ 'use_mm_for_euclid_dist' - will always use matrix multiplication approach to calculate
1501
+ euclidean distance (p = 2)
1502
+ 'donot_use_mm_for_euclid_dist' - will never use matrix multiplication approach to calculate
1503
+ euclidean distance (p = 2)
1504
+ Default: use_mm_for_euclid_dist_if_necessary.
1505
+
1506
+ If x1 has shape :math:`B \times P \times M` and x2 has shape :math:`B \times R \times M` then the
1507
+ output will have shape :math:`B \times P \times R`.
1508
+
1509
+ This function is equivalent to `scipy.spatial.distance.cdist(input,'minkowski', p=p)`
1510
+ if :math:`p \in (0, \infty)`. When :math:`p = 0` it is equivalent to
1511
+ `scipy.spatial.distance.cdist(input, 'hamming') * M`. When :math:`p = \infty`, the closest
1512
+ scipy function is `scipy.spatial.distance.cdist(xn, lambda x, y: np.abs(x - y).max())`.
1513
+
1514
+ Example:
1515
+
1516
+ >>> a = torch.tensor([[0.9041, 0.0196], [-0.3108, -2.4423], [-0.4821, 1.059]])
1517
+ >>> a
1518
+ tensor([[ 0.9041, 0.0196],
1519
+ [-0.3108, -2.4423],
1520
+ [-0.4821, 1.0590]])
1521
+ >>> b = torch.tensor([[-2.1763, -0.4713], [-0.6986, 1.3702]])
1522
+ >>> b
1523
+ tensor([[-2.1763, -0.4713],
1524
+ [-0.6986, 1.3702]])
1525
+ >>> torch.cdist(a, b, p=2)
1526
+ tensor([[3.1193, 2.0959],
1527
+ [2.7138, 3.8322],
1528
+ [2.2830, 0.3791]])
1529
+ """
1530
+ if has_torch_function_variadic(x1, x2):
1531
+ return handle_torch_function(
1532
+ cdist, (x1, x2), x1, x2, p=p, compute_mode=compute_mode
1533
+ )
1534
+ if compute_mode == "use_mm_for_euclid_dist_if_necessary":
1535
+ return _VF.cdist(x1, x2, p, None) # type: ignore[attr-defined]
1536
+ elif compute_mode == "use_mm_for_euclid_dist":
1537
+ return _VF.cdist(x1, x2, p, 1) # type: ignore[attr-defined]
1538
+ elif compute_mode == "donot_use_mm_for_euclid_dist":
1539
+ return _VF.cdist(x1, x2, p, 2) # type: ignore[attr-defined]
1540
+ else:
1541
+ raise ValueError(f"{compute_mode} is not a valid value for compute_mode")
1542
+
1543
+
1544
+ def atleast_1d(*tensors):
1545
+ r"""
1546
+ Returns a 1-dimensional view of each input tensor with zero dimensions.
1547
+ Input tensors with one or more dimensions are returned as-is.
1548
+
1549
+ Args:
1550
+ input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 1-dimensional.
1551
+
1552
+ Returns:
1553
+ output (Tensor or tuple of Tensors)
1554
+
1555
+ Example::
1556
+
1557
+ >>> x = torch.arange(2)
1558
+ >>> x
1559
+ tensor([0, 1])
1560
+ >>> torch.atleast_1d(x)
1561
+ tensor([0, 1])
1562
+ >>> x = torch.tensor(1.)
1563
+ >>> x
1564
+ tensor(1.)
1565
+ >>> torch.atleast_1d(x)
1566
+ tensor([1.])
1567
+ >>> x = torch.tensor(0.5)
1568
+ >>> y = torch.tensor(1.)
1569
+ >>> torch.atleast_1d((x, y))
1570
+ (tensor([0.5000]), tensor([1.]))
1571
+ >>> torch.atleast_1d()
1572
+ ()
1573
+ """
1574
+ # This wrapper exists to support variadic args.
1575
+ if has_torch_function(tensors):
1576
+ return handle_torch_function(atleast_1d, tensors, *tensors)
1577
+ if len(tensors) == 1:
1578
+ tensors = tensors[0]
1579
+ return _VF.atleast_1d(tensors) # type: ignore[attr-defined]
1580
+
1581
+
1582
+ def atleast_2d(*tensors):
1583
+ r"""
1584
+ Returns a 2-dimensional view of each input tensor with zero dimensions.
1585
+ Input tensors with two or more dimensions are returned as-is.
1586
+
1587
+ Args:
1588
+ input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 2-dimensional.
1589
+
1590
+ Returns:
1591
+ output (Tensor or tuple of Tensors)
1592
+
1593
+ Example::
1594
+
1595
+ >>> x = torch.tensor(1.)
1596
+ >>> x
1597
+ tensor(1.)
1598
+ >>> torch.atleast_2d(x)
1599
+ tensor([[1.]])
1600
+ >>> x = torch.arange(4).view(2, 2)
1601
+ >>> x
1602
+ tensor([[0, 1],
1603
+ [2, 3]])
1604
+ >>> torch.atleast_2d(x)
1605
+ tensor([[0, 1],
1606
+ [2, 3]])
1607
+ >>> x = torch.tensor(0.5)
1608
+ >>> y = torch.tensor(1.)
1609
+ >>> torch.atleast_2d((x, y))
1610
+ (tensor([[0.5000]]), tensor([[1.]]))
1611
+ >>> torch.atleast_2d()
1612
+ ()
1613
+ """
1614
+ # This wrapper exists to support variadic args.
1615
+ if has_torch_function(tensors):
1616
+ return handle_torch_function(atleast_2d, tensors, *tensors)
1617
+ if len(tensors) == 1:
1618
+ tensors = tensors[0]
1619
+ return _VF.atleast_2d(tensors) # type: ignore[attr-defined]
1620
+
1621
+
1622
+ def atleast_3d(*tensors):
1623
+ r"""
1624
+ Returns a 3-dimensional view of each input tensor with zero dimensions.
1625
+ Input tensors with three or more dimensions are returned as-is.
1626
+
1627
+ Args:
1628
+ input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 3-dimensional.
1629
+
1630
+ Returns:
1631
+ output (Tensor or tuple of Tensors)
1632
+
1633
+ Example:
1634
+
1635
+ >>> x = torch.tensor(0.5)
1636
+ >>> x
1637
+ tensor(0.5000)
1638
+ >>> torch.atleast_3d(x)
1639
+ tensor([[[0.5000]]])
1640
+ >>> y = torch.arange(4).view(2, 2)
1641
+ >>> y
1642
+ tensor([[0, 1],
1643
+ [2, 3]])
1644
+ >>> torch.atleast_3d(y)
1645
+ tensor([[[0],
1646
+ [1]],
1647
+ <BLANKLINE>
1648
+ [[2],
1649
+ [3]]])
1650
+ >>> x = torch.tensor(1).view(1, 1, 1)
1651
+ >>> x
1652
+ tensor([[[1]]])
1653
+ >>> torch.atleast_3d(x)
1654
+ tensor([[[1]]])
1655
+ >>> x = torch.tensor(0.5)
1656
+ >>> y = torch.tensor(1.0)
1657
+ >>> torch.atleast_3d((x, y))
1658
+ (tensor([[[0.5000]]]), tensor([[[1.]]]))
1659
+ >>> torch.atleast_3d()
1660
+ ()
1661
+ """
1662
+ # This wrapper exists to support variadic args.
1663
+ if has_torch_function(tensors):
1664
+ return handle_torch_function(atleast_3d, tensors, *tensors)
1665
+ if len(tensors) == 1:
1666
+ tensors = tensors[0]
1667
+ return _VF.atleast_3d(tensors) # type: ignore[attr-defined]
1668
+
1669
+
1670
+ if TYPE_CHECKING:
1671
+ pass
1672
+ # There's no good way to use this type annotation; cannot rename norm() to
1673
+ # _norm_impl() in a way that doesn't break JIT overloads. So leave untyped
1674
+ # for mypy for now.
1675
+ # def norm(input: Tensor,
1676
+ # p: Optional[Union[str, Number]] = "fro",
1677
+ # dim: Optional[Union[int, List[int]]] = None,
1678
+ # keepdim: bool = False,
1679
+ # out: Optional[Tensor] = None,
1680
+ # dtype: _dtype = None) -> Tensor:
1681
+ # return _norm_impl(input, p, dim, keepdim, out, dtype)
1682
+ else:
1683
+ # TODO: type dim as BroadcastingList when
1684
+ # https://github.com/pytorch/pytorch/issues/33782 is fixed
1685
+ @overload
1686
+ def norm(
1687
+ input,
1688
+ p="fro",
1689
+ dim=None,
1690
+ keepdim=False,
1691
+ out=None,
1692
+ dtype=None,
1693
+ ):
1694
+ # type: (Tensor, str, Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor
1695
+ pass
1696
+
1697
+ @overload
1698
+ def norm( # noqa: F811
1699
+ input,
1700
+ p="fro",
1701
+ dim=None,
1702
+ keepdim=False,
1703
+ out=None,
1704
+ dtype=None,
1705
+ ):
1706
+ # type: (Tensor, Optional[number], Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor
1707
+ pass
1708
+
1709
+ @overload
1710
+ def norm( # noqa: F811
1711
+ input,
1712
+ p="fro",
1713
+ dim=None,
1714
+ keepdim=False,
1715
+ out=None,
1716
+ dtype=None,
1717
+ ):
1718
+ # type: (Tensor, Optional[number], Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor
1719
+ pass
1720
+
1721
+ @overload
1722
+ def norm( # noqa: F811
1723
+ input,
1724
+ p="fro",
1725
+ dim=None,
1726
+ keepdim=False,
1727
+ out=None,
1728
+ dtype=None,
1729
+ ):
1730
+ # type: (Tensor, str, Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor
1731
+ pass
1732
+
1733
+
1734
+ def norm(
1735
+ input,
1736
+ p: float | str | None = "fro",
1737
+ dim=None,
1738
+ keepdim=False,
1739
+ out=None,
1740
+ dtype=None,
1741
+ ):
1742
+ r"""Returns the matrix norm or vector norm of a given tensor.
1743
+
1744
+ .. warning::
1745
+
1746
+ torch.norm is deprecated and may be removed in a future PyTorch release.
1747
+ Its documentation and behavior may be incorrect, and it is no longer
1748
+ actively maintained.
1749
+
1750
+ Use :func:`torch.linalg.vector_norm` when computing vector norms and
1751
+ :func:`torch.linalg.matrix_norm` when computing matrix norms.
1752
+ For a function with a similar behavior as this one see :func:`torch.linalg.norm`.
1753
+ Note, however, the signature for these functions is slightly different than the
1754
+ signature for ``torch.norm``.
1755
+
1756
+ Args:
1757
+ input (Tensor): The input tensor. Its data type must be either a floating
1758
+ point or complex type. For complex inputs, the norm is calculated using the
1759
+ absolute value of each element. If the input is complex and neither
1760
+ :attr:`dtype` nor :attr:`out` is specified, the result's data type will
1761
+ be the corresponding floating point type (e.g. float if :attr:`input` is
1762
+ complexfloat).
1763
+
1764
+ p (int, float, inf, -inf, 'fro', 'nuc', optional): the order of norm. Default: ``'fro'``
1765
+ The following norms can be calculated:
1766
+
1767
+ ====== ============== ==========================
1768
+ ord matrix norm vector norm
1769
+ ====== ============== ==========================
1770
+ 'fro' Frobenius norm --
1771
+ 'nuc' nuclear norm --
1772
+ Number -- sum(abs(x)**ord)**(1./ord)
1773
+ ====== ============== ==========================
1774
+
1775
+ The vector norm can be calculated across any number of dimensions.
1776
+ The corresponding dimensions of :attr:`input` are flattened into
1777
+ one dimension, and the norm is calculated on the flattened
1778
+ dimension.
1779
+
1780
+ Frobenius norm produces the same result as ``p=2`` in all cases
1781
+ except when :attr:`dim` is a list of three or more dims, in which
1782
+ case Frobenius norm throws an error.
1783
+
1784
+ Nuclear norm can only be calculated across exactly two dimensions.
1785
+
1786
+ dim (int, tuple of ints, list of ints, optional):
1787
+ Specifies which dimension or dimensions of :attr:`input` to
1788
+ calculate the norm across. If :attr:`dim` is ``None``, the norm will
1789
+ be calculated across all dimensions of :attr:`input`. If the norm
1790
+ type indicated by :attr:`p` does not support the specified number of
1791
+ dimensions, an error will occur.
1792
+ keepdim (bool, optional): whether the output tensors have :attr:`dim`
1793
+ retained or not. Ignored if :attr:`dim` = ``None`` and
1794
+ :attr:`out` = ``None``. Default: ``False``
1795
+ out (Tensor, optional): the output tensor. Ignored if
1796
+ :attr:`dim` = ``None`` and :attr:`out` = ``None``.
1797
+ dtype (:class:`torch.dtype`, optional): the desired data type of
1798
+ returned tensor. If specified, the input tensor is casted to
1799
+ :attr:`dtype` while performing the operation. Default: None.
1800
+
1801
+ .. note::
1802
+ Even though ``p='fro'`` supports any number of dimensions, the true
1803
+ mathematical definition of Frobenius norm only applies to tensors with
1804
+ exactly two dimensions. :func:`torch.linalg.matrix_norm` with ``ord='fro'``
1805
+ aligns with the mathematical definition, since it can only be applied across
1806
+ exactly two dimensions.
1807
+
1808
+ Example::
1809
+
1810
+ >>> import torch
1811
+ >>> a = torch.arange(9, dtype= torch.float) - 4
1812
+ >>> b = a.reshape((3, 3))
1813
+ >>> torch.norm(a)
1814
+ tensor(7.7460)
1815
+ >>> torch.norm(b)
1816
+ tensor(7.7460)
1817
+ >>> torch.norm(a, float('inf'))
1818
+ tensor(4.)
1819
+ >>> torch.norm(b, float('inf'))
1820
+ tensor(4.)
1821
+ >>> c = torch.tensor([[ 1, 2, 3], [-1, 1, 4]] , dtype=torch.float)
1822
+ >>> torch.norm(c, dim=0)
1823
+ tensor([1.4142, 2.2361, 5.0000])
1824
+ >>> torch.norm(c, dim=1)
1825
+ tensor([3.7417, 4.2426])
1826
+ >>> torch.norm(c, p=1, dim=1)
1827
+ tensor([6., 6.])
1828
+ >>> d = torch.arange(8, dtype=torch.float).reshape(2, 2, 2)
1829
+ >>> torch.norm(d, dim=(1, 2))
1830
+ tensor([ 3.7417, 11.2250])
1831
+ >>> torch.norm(d[0, :, :]), torch.norm(d[1, :, :])
1832
+ (tensor(3.7417), tensor(11.2250))
1833
+ """
1834
+
1835
+ if has_torch_function_unary(input):
1836
+ return handle_torch_function(
1837
+ norm, (input,), input, p=p, dim=dim, keepdim=keepdim, out=out, dtype=dtype
1838
+ )
1839
+
1840
+ # NB. All the repeated code and weird python is to please TorchScript.
1841
+ # For a more compact implementation see the relevant function in `_refs/__init__.py`
1842
+
1843
+ # We don't do this for MPS or sparse tensors
1844
+ if input.layout == torch.strided and input.device.type in (
1845
+ "cpu",
1846
+ "cuda",
1847
+ "xpu",
1848
+ "meta",
1849
+ torch.utils.backend_registration._privateuse1_backend_name,
1850
+ ):
1851
+ if dim is not None:
1852
+ if isinstance(dim, (int, torch.SymInt)):
1853
+ _dim = [dim]
1854
+ else:
1855
+ _dim = dim
1856
+ else:
1857
+ _dim = None # type: ignore[assignment]
1858
+
1859
+ if isinstance(p, str):
1860
+ if p == "fro" and (
1861
+ dim is None
1862
+ or isinstance(dim, (int, torch.SymInt))
1863
+ or len(dim) <= 2 # pyrefly: ignore # bad-argument-type
1864
+ ):
1865
+ if out is None:
1866
+ return torch.linalg.vector_norm(
1867
+ input, 2, _dim, keepdim, dtype=dtype
1868
+ )
1869
+ else:
1870
+ return torch.linalg.vector_norm(
1871
+ input, 2, _dim, keepdim, dtype=dtype, out=out
1872
+ )
1873
+
1874
+ # Here we either call the nuclear norm, or we call matrix_norm with some arguments
1875
+ # that will throw an error
1876
+ if _dim is None:
1877
+ _dim = list(range(input.ndim))
1878
+ if out is None:
1879
+ return torch.linalg.matrix_norm(input, p, _dim, keepdim, dtype=dtype)
1880
+ else:
1881
+ return torch.linalg.matrix_norm(
1882
+ input, p, _dim, keepdim, dtype=dtype, out=out
1883
+ )
1884
+ else:
1885
+ # NB. p should be Union[str, number], not Optional!
1886
+ _p = 2.0 if p is None else p
1887
+ if out is None:
1888
+ return torch.linalg.vector_norm(input, _p, _dim, keepdim, dtype=dtype)
1889
+ else:
1890
+ return torch.linalg.vector_norm(
1891
+ input, _p, _dim, keepdim, dtype=dtype, out=out
1892
+ )
1893
+
1894
+ ndim = input.dim()
1895
+
1896
+ # catch default case
1897
+ if dim is None and out is None and dtype is None and p is not None:
1898
+ if isinstance(p, str):
1899
+ if p == "fro":
1900
+ return _VF.frobenius_norm(input, dim=(), keepdim=keepdim)
1901
+ if not isinstance(p, str):
1902
+ _dim = list(range(ndim))
1903
+ return _VF.norm(input, p, dim=_dim, keepdim=keepdim) # type: ignore[attr-defined]
1904
+
1905
+ # TODO: when https://github.com/pytorch/pytorch/issues/33782 is fixed
1906
+ # remove the overloads where dim is an int and replace with BroadcastingList1
1907
+ # and remove next four lines, replace _dim with dim
1908
+ if dim is not None:
1909
+ if isinstance(dim, (int, torch.SymInt)):
1910
+ _dim = [dim]
1911
+ else:
1912
+ _dim = dim
1913
+ else:
1914
+ _dim = None # type: ignore[assignment]
1915
+
1916
+ if isinstance(p, str):
1917
+ if p == "fro":
1918
+ if dtype is not None:
1919
+ raise ValueError("dtype argument is not supported in frobenius norm")
1920
+
1921
+ if _dim is None:
1922
+ _dim = list(range(ndim))
1923
+ if out is None:
1924
+ return _VF.frobenius_norm(input, _dim, keepdim=keepdim) # type: ignore[arg-type]
1925
+ else:
1926
+ return _VF.frobenius_norm(input, _dim, keepdim=keepdim, out=out) # type: ignore[arg-type]
1927
+ elif p == "nuc":
1928
+ if dtype is not None:
1929
+ raise ValueError("dtype argument is not supported in nuclear norm")
1930
+ if _dim is None:
1931
+ if out is None:
1932
+ return _VF.nuclear_norm(input, keepdim=keepdim) # type: ignore[arg-type]
1933
+ else:
1934
+ return _VF.nuclear_norm(input, keepdim=keepdim, out=out) # type: ignore[arg-type]
1935
+ else:
1936
+ if out is None:
1937
+ return _VF.nuclear_norm(input, _dim, keepdim=keepdim) # type: ignore[arg-type]
1938
+ else:
1939
+ return _VF.nuclear_norm(input, _dim, keepdim=keepdim, out=out) # type: ignore[arg-type]
1940
+ raise RuntimeError(f"only valid string values are 'fro' and 'nuc', found {p}")
1941
+ else:
1942
+ if _dim is None:
1943
+ _dim = list(range(ndim))
1944
+
1945
+ if out is None:
1946
+ if dtype is None:
1947
+ return _VF.norm(input, p, _dim, keepdim=keepdim) # type: ignore[attr-defined]
1948
+ else:
1949
+ return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype) # type: ignore[attr-defined]
1950
+ else:
1951
+ if dtype is None:
1952
+ return _VF.norm(input, p, _dim, keepdim=keepdim, out=out) # type: ignore[attr-defined]
1953
+ else:
1954
+ return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype, out=out) # type: ignore[attr-defined]
1955
+
1956
+
1957
+ def unravel_index(
1958
+ indices: Tensor,
1959
+ shape: int | Sequence[int] | torch.Size,
1960
+ ) -> tuple[Tensor, ...]:
1961
+ r"""Converts a tensor of flat indices into a tuple of coordinate tensors that
1962
+ index into an arbitrary tensor of the specified shape.
1963
+
1964
+ Args:
1965
+ indices (Tensor): An integer tensor containing indices into the
1966
+ flattened version of an arbitrary tensor of shape :attr:`shape`.
1967
+ All elements must be in the range ``[0, prod(shape) - 1]``.
1968
+
1969
+ shape (int, sequence of ints, or torch.Size): The shape of the arbitrary
1970
+ tensor. All elements must be non-negative.
1971
+
1972
+ Returns:
1973
+ tuple of Tensors: Each ``i``-th tensor in the output corresponds with
1974
+ dimension ``i`` of :attr:`shape`. Each tensor has the same shape as
1975
+ ``indices`` and contains one index into dimension ``i`` for each of the
1976
+ flat indices given by ``indices``.
1977
+
1978
+ Example::
1979
+
1980
+ >>> import torch
1981
+ >>> torch.unravel_index(torch.tensor(4), (3, 2))
1982
+ (tensor(2),
1983
+ tensor(0))
1984
+
1985
+ >>> torch.unravel_index(torch.tensor([4, 1]), (3, 2))
1986
+ (tensor([2, 0]),
1987
+ tensor([0, 1]))
1988
+
1989
+ >>> torch.unravel_index(torch.tensor([0, 1, 2, 3, 4, 5]), (3, 2))
1990
+ (tensor([0, 0, 1, 1, 2, 2]),
1991
+ tensor([0, 1, 0, 1, 0, 1]))
1992
+
1993
+ >>> torch.unravel_index(torch.tensor([1234, 5678]), (10, 10, 10, 10))
1994
+ (tensor([1, 5]),
1995
+ tensor([2, 6]),
1996
+ tensor([3, 7]),
1997
+ tensor([4, 8]))
1998
+
1999
+ >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (10, 10, 10, 10))
2000
+ (tensor([[1], [5]]),
2001
+ tensor([[2], [6]]),
2002
+ tensor([[3], [7]]),
2003
+ tensor([[4], [8]]))
2004
+
2005
+ >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (100, 100))
2006
+ (tensor([[12], [56]]),
2007
+ tensor([[34], [78]]))
2008
+ """
2009
+ if has_torch_function_unary(indices):
2010
+ return handle_torch_function(unravel_index, (indices,), indices, shape=shape)
2011
+ res_tensor = _unravel_index(indices, shape)
2012
+ return res_tensor.unbind(-1)
2013
+
2014
+
2015
+ def _unravel_index(indices: Tensor, shape: int | Sequence[int]) -> Tensor:
2016
+ torch._check_type(
2017
+ not indices.is_complex()
2018
+ and not indices.is_floating_point()
2019
+ and indices.dtype != torch.bool,
2020
+ lambda: f"expected 'indices' to be integer dtype, but got {indices.dtype}",
2021
+ )
2022
+
2023
+ torch._check_type(
2024
+ isinstance(shape, (int, torch.SymInt, Sequence)),
2025
+ lambda: f"expected 'shape' to be int or sequence of ints, but got {type(shape)}",
2026
+ )
2027
+
2028
+ if isinstance(shape, (int, torch.SymInt)):
2029
+ shape = torch.Size([shape]) # pyrefly: ignore [bad-argument-type]
2030
+ else:
2031
+ for dim in shape:
2032
+ torch._check_type(
2033
+ isinstance(dim, (int, torch.SymInt)),
2034
+ lambda: f"expected 'shape' sequence to only contain ints, but got {type(dim)}",
2035
+ )
2036
+ shape = torch.Size(shape)
2037
+
2038
+ torch._check_value(
2039
+ all(dim >= 0 for dim in shape),
2040
+ lambda: f"'shape' cannot have negative values, but got {tuple(shape)}",
2041
+ )
2042
+
2043
+ torch._check_value(
2044
+ all(dim > 0 for dim in shape) or indices.numel() == 0,
2045
+ lambda: f"'shape' cannot have zero dimensions when 'indices' is non-empty, but got {tuple(shape)}",
2046
+ )
2047
+
2048
+ coefs = list(
2049
+ reversed(
2050
+ list(
2051
+ itertools.accumulate(
2052
+ reversed(shape[1:] + torch.Size([1])), func=operator.mul
2053
+ )
2054
+ )
2055
+ )
2056
+ )
2057
+ return indices.unsqueeze(-1).floor_divide(
2058
+ torch.tensor(coefs, device=indices.device, dtype=torch.int64)
2059
+ ) % torch.tensor(shape, device=indices.device, dtype=torch.int64)
2060
+
2061
+
2062
+ def chain_matmul(*matrices, out=None):
2063
+ r"""Returns the matrix product of the :math:`N` 2-D tensors. This product is efficiently computed
2064
+ using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms
2065
+ of arithmetic operations (`[CLRS]`_). Note that since this is a function to compute the product, :math:`N`
2066
+ needs to be greater than or equal to 2; if equal to 2 then a trivial matrix-matrix product is returned.
2067
+ If :math:`N` is 1, then this is a no-op - the original matrix is returned as is.
2068
+
2069
+ .. warning::
2070
+
2071
+ :func:`torch.chain_matmul` is deprecated and will be removed in a future PyTorch release.
2072
+ Use :func:`torch.linalg.multi_dot` instead, which accepts a list of two or more tensors
2073
+ rather than multiple arguments.
2074
+
2075
+ Args:
2076
+ matrices (Tensors...): a sequence of 2 or more 2-D tensors whose product is to be determined.
2077
+ out (Tensor, optional): the output tensor. Ignored if :attr:`out` = ``None``.
2078
+
2079
+ Returns:
2080
+ Tensor: if the :math:`i^{th}` tensor was of dimensions :math:`p_{i} \times p_{i + 1}`, then the product
2081
+ would be of dimensions :math:`p_{1} \times p_{N + 1}`.
2082
+
2083
+ Example::
2084
+
2085
+ >>> # xdoctest: +SKIP
2086
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
2087
+ >>> a = torch.randn(3, 4)
2088
+ >>> b = torch.randn(4, 5)
2089
+ >>> c = torch.randn(5, 6)
2090
+ >>> d = torch.randn(6, 7)
2091
+ >>> # will raise a deprecation warning
2092
+ >>> torch.chain_matmul(a, b, c, d)
2093
+ tensor([[ -2.3375, -3.9790, -4.1119, -6.6577, 9.5609, -11.5095, -3.2614],
2094
+ [ 21.4038, 3.3378, -8.4982, -5.2457, -10.2561, -2.4684, 2.7163],
2095
+ [ -0.9647, -5.8917, -2.3213, -5.2284, 12.8615, -12.2816, -2.5095]])
2096
+
2097
+ .. _`[CLRS]`: https://mitpress.mit.edu/books/introduction-algorithms-third-edition
2098
+ """
2099
+ # This wrapper exists to support variadic args.
2100
+ if has_torch_function(matrices):
2101
+ return handle_torch_function(chain_matmul, matrices, *matrices)
2102
+
2103
+ if out is None:
2104
+ return _VF.chain_matmul(matrices) # type: ignore[attr-defined]
2105
+ else:
2106
+ return _VF.chain_matmul(matrices, out=out) # type: ignore[attr-defined]
2107
+
2108
+
2109
+ def _lu_impl(A, pivot=True, get_infos=False, out=None):
2110
+ # type: (Tensor, bool, bool, Any) -> tuple[Tensor, Tensor, Tensor]
2111
+ r"""Computes the LU factorization of a matrix or batches of matrices
2112
+ :attr:`A`. Returns a tuple containing the LU factorization and
2113
+ pivots of :attr:`A`. Pivoting is done if :attr:`pivot` is set to
2114
+ ``True``.
2115
+
2116
+ .. warning::
2117
+
2118
+ :func:`torch.lu` is deprecated in favor of :func:`torch.linalg.lu_factor`
2119
+ and :func:`torch.linalg.lu_factor_ex`. :func:`torch.lu` will be removed in a
2120
+ future PyTorch release.
2121
+ ``LU, pivots, info = torch.lu(A, compute_pivots)`` should be replaced with
2122
+
2123
+ .. code:: python
2124
+
2125
+ LU, pivots = torch.linalg.lu_factor(A, compute_pivots)
2126
+
2127
+ ``LU, pivots, info = torch.lu(A, compute_pivots, get_infos=True)`` should be replaced with
2128
+
2129
+ .. code:: python
2130
+
2131
+ LU, pivots, info = torch.linalg.lu_factor_ex(A, compute_pivots)
2132
+
2133
+ .. note::
2134
+ * The returned permutation matrix for every matrix in the batch is
2135
+ represented by a 1-indexed vector of size ``min(A.shape[-2], A.shape[-1])``.
2136
+ ``pivots[i] == j`` represents that in the ``i``-th step of the algorithm,
2137
+ the ``i``-th row was permuted with the ``j-1``-th row.
2138
+ * LU factorization with :attr:`pivot` = ``False`` is not available
2139
+ for CPU, and attempting to do so will throw an error. However,
2140
+ LU factorization with :attr:`pivot` = ``False`` is available for
2141
+ CUDA.
2142
+ * This function does not check if the factorization was successful
2143
+ or not if :attr:`get_infos` is ``True`` since the status of the
2144
+ factorization is present in the third element of the return tuple.
2145
+ * In the case of batches of square matrices with size less or equal
2146
+ to 32 on a CUDA device, the LU factorization is repeated for
2147
+ singular matrices due to the bug in the MAGMA library
2148
+ (see magma issue 13).
2149
+ * ``L``, ``U``, and ``P`` can be derived using :func:`torch.lu_unpack`.
2150
+
2151
+ .. warning::
2152
+ The gradients of this function will only be finite when :attr:`A` is full rank.
2153
+ This is because the LU decomposition is just differentiable at full rank matrices.
2154
+ Furthermore, if :attr:`A` is close to not being full rank,
2155
+ the gradient will be numerically unstable as it depends on the computation of :math:`L^{-1}` and :math:`U^{-1}`.
2156
+
2157
+ Args:
2158
+ A (Tensor): the tensor to factor of size :math:`(*, m, n)`
2159
+ pivot (bool, optional): Whether to compute the LU decomposition with partial pivoting, or the regular LU
2160
+ decomposition. :attr:`pivot`\ `= False` not supported on CPU. Default: `True`.
2161
+ get_infos (bool, optional): if set to ``True``, returns an info IntTensor.
2162
+ Default: ``False``
2163
+ out (tuple, optional): optional output tuple. If :attr:`get_infos` is ``True``,
2164
+ then the elements in the tuple are Tensor, IntTensor,
2165
+ and IntTensor. If :attr:`get_infos` is ``False``, then the
2166
+ elements in the tuple are Tensor, IntTensor. Default: ``None``
2167
+
2168
+ Returns:
2169
+ (Tensor, IntTensor, IntTensor (optional)): A tuple of tensors containing
2170
+
2171
+ - **factorization** (*Tensor*): the factorization of size :math:`(*, m, n)`
2172
+
2173
+ - **pivots** (*IntTensor*): the pivots of size :math:`(*, \text{min}(m, n))`.
2174
+ ``pivots`` stores all the intermediate transpositions of rows.
2175
+ The final permutation ``perm`` could be reconstructed by
2176
+ applying ``swap(perm[i], perm[pivots[i] - 1])`` for ``i = 0, ..., pivots.size(-1) - 1``,
2177
+ where ``perm`` is initially the identity permutation of :math:`m` elements
2178
+ (essentially this is what :func:`torch.lu_unpack` is doing).
2179
+
2180
+ - **infos** (*IntTensor*, *optional*): if :attr:`get_infos` is ``True``, this is a tensor of
2181
+ size :math:`(*)` where non-zero values indicate whether factorization for the matrix or
2182
+ each minibatch has succeeded or failed
2183
+
2184
+ Example::
2185
+
2186
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
2187
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
2188
+ >>> warnings.filterwarnings("ignore", message=".*torch.lu is deprecated") # docs: hide
2189
+ >>> A = torch.randn(2, 3, 3)
2190
+ >>> A_LU, pivots = torch.lu(A)
2191
+ >>> A_LU
2192
+ tensor([[[ 1.3506, 2.5558, -0.0816],
2193
+ [ 0.1684, 1.1551, 0.1940],
2194
+ [ 0.1193, 0.6189, -0.5497]],
2195
+
2196
+ [[ 0.4526, 1.2526, -0.3285],
2197
+ [-0.7988, 0.7175, -0.9701],
2198
+ [ 0.2634, -0.9255, -0.3459]]])
2199
+ >>> pivots
2200
+ tensor([[ 3, 3, 3],
2201
+ [ 3, 3, 3]], dtype=torch.int32)
2202
+ >>> A_LU, pivots, info = torch.lu(A, get_infos=True)
2203
+ >>> if info.nonzero().size(0) == 0:
2204
+ ... print('LU factorization succeeded for all samples!')
2205
+ LU factorization succeeded for all samples!
2206
+ """
2207
+ # If get_infos is True, then we don't need to check for errors and vice versa
2208
+ return torch._lu_with_info(A, pivot=pivot, check_errors=(not get_infos))
2209
+
2210
+
2211
+ if TYPE_CHECKING:
2212
+ _ListOrSeq = Sequence[Tensor]
2213
+ else:
2214
+ _ListOrSeq = list[Tensor]
2215
+
2216
+
2217
+ def _check_list_size(out_len: int, get_infos: bool, out: _ListOrSeq) -> None:
2218
+ get_infos_int = 1 if get_infos else 0
2219
+ if out_len - get_infos_int != 2:
2220
+ raise TypeError(
2221
+ f"expected tuple of {2 + int(get_infos)} elements but got {out_len}"
2222
+ )
2223
+ if not isinstance(out, (tuple, list)):
2224
+ raise TypeError(
2225
+ f"argument 'out' must be tuple of Tensors, not {type(out).__name__}"
2226
+ )
2227
+
2228
+
2229
+ def _lu_with_infos(A, pivot=True, get_infos=False, out=None):
2230
+ # type: (Tensor, bool, bool, Optional[tuple[Tensor, Tensor, Tensor]]) -> tuple[Tensor, Tensor, Tensor]
2231
+ if has_torch_function_unary(A):
2232
+ return handle_torch_function(
2233
+ lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out
2234
+ )
2235
+ result = _lu_impl(A, pivot, get_infos, out)
2236
+ if out is not None:
2237
+ _check_list_size(len(out), get_infos, out)
2238
+ for i in range(len(out)):
2239
+ out[i].resize_as_(result[i]).copy_(result[i])
2240
+ return out
2241
+ else:
2242
+ return result # A_LU, pivots, infos
2243
+
2244
+
2245
+ def _lu_no_infos(A, pivot=True, get_infos=False, out=None):
2246
+ # type: (Tensor, bool, bool, Optional[tuple[Tensor, Tensor]]) -> tuple[Tensor, Tensor]
2247
+ # need to check for torch_function here so that we exit if
2248
+ if has_torch_function_unary(A):
2249
+ return handle_torch_function(
2250
+ lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out
2251
+ )
2252
+ result = _lu_impl(A, pivot, get_infos, out)
2253
+ if out is not None:
2254
+ _check_list_size(len(out), get_infos, out)
2255
+ for i in range(len(out)):
2256
+ out[i].resize_as_(result[i]).copy_(result[i])
2257
+ return out
2258
+ else:
2259
+ return result[0], result[1] # A_LU, pivots
2260
+
2261
+
2262
+ # The return type of lu depends on `get_infos`, so in order to resolve the output type
2263
+ # of lu in TorchScript we need to statically know the value of `get_infos`
2264
+ lu = boolean_dispatch(
2265
+ arg_name="get_infos",
2266
+ arg_index=2,
2267
+ default=False,
2268
+ if_true=_lu_with_infos,
2269
+ if_false=_lu_no_infos,
2270
+ module_name=__name__,
2271
+ func_name="lu",
2272
+ )
2273
+ lu.__doc__ = _lu_impl.__doc__
.venv/lib/python3.12/site-packages/torch/futures/__init__.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # pylint: disable=useless-parent-delegation
3
+ from __future__ import annotations
4
+
5
+ from typing import cast, Generic, TYPE_CHECKING, TypeVar
6
+
7
+ import torch
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Callable
12
+
13
+
14
+ __all__ = ["Future", "collect_all", "wait_all"]
15
+
16
+
17
+ T = TypeVar("T")
18
+ S = TypeVar("S")
19
+
20
+
21
+ class Future(torch._C.Future, Generic[T]):
22
+ r"""
23
+ Wrapper around a ``torch._C.Future`` which encapsulates an asynchronous
24
+ execution of a callable, e.g. :meth:`~torch.distributed.rpc.rpc_async`. It
25
+ also exposes a set of APIs to add callback functions and set results.
26
+
27
+ .. warning:: GPU support is a beta feature, subject to changes.
28
+ """
29
+
30
+ def __init__(self, *, devices: list[int | str | torch.device] | None = None):
31
+ r"""
32
+ Create an empty unset ``Future``. If the future is intended to hold
33
+ values containing CUDA tensors, (a superset of) their CUDA devices must
34
+ be specified at construction. (This is only supported if
35
+ ``torch.cuda.is_available()`` returns ``True``). This is needed to
36
+ ensure proper CUDA stream synchronization. The child futures, returned
37
+ by the ``then`` method, will inherit these devices.
38
+
39
+ Args:
40
+ devices(``List[Union[int, str, torch.device]]``, optional): the set
41
+ of devices on which tensors contained in this future's value are
42
+ allowed to reside and on which callbacks are allowed to operate.
43
+ """
44
+ if devices is None:
45
+ devices = []
46
+ super().__init__([torch.device(d) for d in devices])
47
+
48
+ def done(self) -> bool:
49
+ r"""
50
+ Return ``True`` if this ``Future`` is done. A ``Future`` is done if it
51
+ has a result or an exception.
52
+
53
+ If the value contains tensors that reside on GPUs, ``Future.done()``
54
+ will return ``True`` even if the asynchronous kernels that are
55
+ populating those tensors haven't yet completed running on the device,
56
+ because at such stage the result is already usable, provided one
57
+ performs the appropriate synchronizations (see :meth:`wait`).
58
+ """
59
+ return super().done()
60
+
61
+ def wait(self) -> T:
62
+ r"""
63
+ Block until the value of this ``Future`` is ready.
64
+
65
+ If the value contains tensors that reside on GPUs, then an additional
66
+ synchronization is performed with the kernels (executing on the device)
67
+ which may be asynchronously populating those tensors. Such sync is
68
+ non-blocking, which means that ``wait()`` will insert the necessary
69
+ instructions in the current streams to ensure that further operations
70
+ enqueued on those streams will be properly scheduled after the async
71
+ kernels but, once that is done, ``wait()`` will return, even if those
72
+ kernels are still running. No further synchronization is required when
73
+ accessing and using the values, as long as one doesn't change streams.
74
+
75
+ Returns:
76
+ The value held by this ``Future``. If the function (callback or RPC)
77
+ creating the value has thrown an error, this ``wait`` method will
78
+ also throw an error.
79
+ """
80
+ return super().wait()
81
+
82
+ def value(self) -> T:
83
+ r"""
84
+ Obtain the value of an already-completed future.
85
+
86
+ This method should only be called after a call to :meth:`wait` has
87
+ completed, or inside a callback function passed to :meth:`then`. In
88
+ other cases this ``Future`` may not yet hold a value and calling
89
+ ``value()`` could fail.
90
+
91
+ If the value contains tensors that reside on GPUs, then this method will
92
+ *not* perform any additional synchronization. This should be done
93
+ beforehand, separately, through a call to :meth:`wait` (except within
94
+ callbacks, for which it's already being taken care of by :meth:`then`).
95
+
96
+ Returns:
97
+ The value held by this ``Future``. If the function (callback or RPC)
98
+ creating the value has thrown an error, this ``value()`` method will
99
+ also throw an error.
100
+ """
101
+ return super().value()
102
+
103
+ def then(self, callback: Callable[[Future[T]], S]) -> Future[S]:
104
+ r"""
105
+ Append the given callback function to this ``Future``, which will be run
106
+ when the ``Future`` is completed. Multiple callbacks can be added to
107
+ the same ``Future``, but the order in which they will be executed cannot
108
+ be guaranteed (to enforce a certain order consider chaining:
109
+ ``fut.then(cb1).then(cb2)``). The callback must take one argument, which
110
+ is the reference to this ``Future``. The callback function can use the
111
+ :meth:`value` method to get the value. Note that if this ``Future`` is
112
+ already completed, the given callback will be run immediately inline.
113
+
114
+ If the ``Future``'s value contains tensors that reside on GPUs, the
115
+ callback might be invoked while the async kernels that are populating
116
+ those tensors haven't yet finished executing on the device. However, the
117
+ callback will be invoked with some dedicated streams set as current
118
+ (fetched from a global pool) which will be synchronized with those
119
+ kernels. Hence any operation performed by the callback on these tensors
120
+ will be scheduled on the device after the kernels complete. In other
121
+ words, as long as the callback doesn't switch streams, it can safely
122
+ manipulate the result without any additional synchronization. This is
123
+ similar to the non-blocking behavior of :meth:`wait`.
124
+
125
+ Similarly, if the callback returns a value that contains tensors that
126
+ reside on a GPU, it can do so even if the kernels that are producing
127
+ these tensors are still running on the device, as long as the callback
128
+ didn't change streams during its execution. If one wants to change
129
+ streams, one must be careful to re-synchronize them with the original
130
+ streams, that is, those that were current when the callback was invoked.
131
+
132
+ Args:
133
+ callback(``Callable``): a ``Callable`` that takes this ``Future`` as
134
+ the only argument.
135
+
136
+ Returns:
137
+ A new ``Future`` object that holds the return value of the
138
+ ``callback`` and will be marked as completed when the given
139
+ ``callback`` finishes.
140
+
141
+ .. note:: Note that if the callback function throws, either
142
+ through the original future being completed with an exception and
143
+ calling ``fut.wait()``, or through other code in the callback, the
144
+ future returned by ``then`` will be marked appropriately with the
145
+ encountered error. However, if this callback later completes
146
+ additional futures, those futures are not marked as completed with
147
+ an error and the user is responsible for handling completion/waiting
148
+ on those futures independently.
149
+
150
+ Example::
151
+
152
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_FUTURES)
153
+ >>> def callback(fut):
154
+ ... print(f"RPC return value is {fut.wait()}.")
155
+ >>> fut = torch.futures.Future()
156
+ >>> # The inserted callback will print the return value when
157
+ >>> # receiving the response from "worker1"
158
+ >>> cb_fut = fut.then(callback)
159
+ >>> chain_cb_fut = cb_fut.then(
160
+ ... lambda x : print(f"Chained cb done. {x.wait()}")
161
+ ... )
162
+ >>> fut.set_result(5)
163
+ RPC return value is 5.
164
+ Chained cb done. None
165
+ """
166
+ return cast(Future[S], super().then(callback))
167
+
168
+ def add_done_callback(self, callback: Callable[[Future[T]], None]) -> None:
169
+ r"""
170
+ Append the given callback function to this ``Future``, which will be run
171
+ when the ``Future`` is completed. Multiple callbacks can be added to
172
+ the same ``Future``, but the order in which they will be executed cannot
173
+ be guaranteed. The callback must take one argument, which is the
174
+ reference to this ``Future``. The callback function can use the
175
+ :meth:`value` method to get the value. Note that if this ``Future`` is
176
+ already completed, the given callback will be run inline.
177
+
178
+ We recommend that you use the :meth:`then` method as it provides a way
179
+ to synchronize after your callback has completed. ``add_done_callback``
180
+ can be cheaper if your callback does not return anything. But both
181
+ :meth:`then` and ``add_done_callback`` use the same callback
182
+ registration API under the hood.
183
+
184
+ With respect to GPU tensors, this method behaves in the same way as
185
+ :meth:`then`.
186
+
187
+ Args:
188
+ callback(``Future``): a ``Callable`` that takes in one argument,
189
+ which is the reference to this ``Future``.
190
+
191
+ .. note:: Note that if the callback function throws, either
192
+ through the original future being completed with an exception and
193
+ calling ``fut.wait()``, or through other code in the callback,
194
+ error handling must be carefully taken care of. For example, if
195
+ this callback later completes additional futures, those futures are
196
+ not marked as completed with an error and the user is responsible
197
+ for handling completion/waiting on those futures independently.
198
+
199
+ Example::
200
+
201
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_FUTURES)
202
+ >>> def callback(fut):
203
+ ... print("This will run after the future has finished.")
204
+ ... print(fut.wait())
205
+ >>> fut = torch.futures.Future()
206
+ >>> fut.add_done_callback(callback)
207
+ >>> fut.set_result(5)
208
+ This will run after the future has finished.
209
+ 5
210
+ """
211
+ super().add_done_callback(callback)
212
+
213
+ def set_result(self, result: T) -> None:
214
+ r"""
215
+ Set the result for this ``Future``, which will mark this ``Future`` as
216
+ completed and trigger all attached callbacks. Note that a ``Future``
217
+ cannot be marked completed twice.
218
+
219
+ If the result contains tensors that reside on GPUs, this method can be
220
+ called even if the asynchronous kernels that are populating those
221
+ tensors haven't yet completed running on the device, provided that the
222
+ streams on which those kernels were enqueued are set as the current ones
223
+ when this method is called. Put simply, it's safe to call this method
224
+ immediately after launching those kernels, without any additional
225
+ synchronization, as long as one doesn't change streams in between. This
226
+ method will record events on all the relevant current streams and will
227
+ use them to ensure proper scheduling for all the consumers of this
228
+ ``Future``.
229
+
230
+ Args:
231
+ result (object): the result object of this ``Future``.
232
+
233
+ Example::
234
+
235
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_FUTURES)
236
+ >>> import threading
237
+ >>> import time
238
+ >>> def slow_set_future(fut, value):
239
+ ... time.sleep(0.5)
240
+ ... fut.set_result(value)
241
+ >>> fut = torch.futures.Future()
242
+ >>> t = threading.Thread(
243
+ ... target=slow_set_future,
244
+ ... args=(fut, torch.ones(2) * 3)
245
+ ... )
246
+ >>> t.start()
247
+ >>> print(fut.wait())
248
+ tensor([3., 3.])
249
+ >>> t.join()
250
+ """
251
+ super().set_result(result)
252
+
253
+ def set_exception(self, result: T) -> None:
254
+ r"""
255
+ Set an exception for this ``Future``, which will mark this ``Future`` as
256
+ completed with an error and trigger all attached callbacks. Note that
257
+ when calling wait()/value() on this ``Future``, the exception set here
258
+ will be raised inline.
259
+
260
+ Args:
261
+ result (BaseException): the exception for this ``Future``.
262
+
263
+ Example::
264
+
265
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_FUTURES)
266
+ >>> fut = torch.futures.Future()
267
+ >>> fut.set_exception(ValueError("foo"))
268
+ >>> fut.wait()
269
+ Traceback (most recent call last):
270
+ ...
271
+ ValueError: foo
272
+ """
273
+ if not isinstance(result, Exception):
274
+ raise AssertionError(
275
+ f"{result} is of type {type(result)}, not an Exception."
276
+ )
277
+
278
+ def raise_error(fut_result):
279
+ raise fut_result
280
+
281
+ super()._set_unwrap_func(raise_error)
282
+ self.set_result(result) # type: ignore[arg-type]
283
+
284
+
285
+ def collect_all(futures: list[Future]) -> Future[list[Future]]:
286
+ r"""
287
+ Collects the provided :class:`~torch.futures.Future` objects into a single
288
+ combined :class:`~torch.futures.Future` that is completed when all of the
289
+ sub-futures are completed.
290
+
291
+ Args:
292
+ futures (list): a list of :class:`~torch.futures.Future` objects.
293
+
294
+ Returns:
295
+ Returns a :class:`~torch.futures.Future` object to a list of the passed
296
+ in Futures.
297
+
298
+ Example::
299
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_FUTURES)
300
+ >>> fut0 = torch.futures.Future()
301
+ >>> fut1 = torch.futures.Future()
302
+ >>> fut = torch.futures.collect_all([fut0, fut1])
303
+ >>> fut0.set_result(0)
304
+ >>> fut1.set_result(1)
305
+ >>> fut_list = fut.wait()
306
+ >>> print(f"fut0 result = {fut_list[0].wait()}")
307
+ fut0 result = 0
308
+ >>> print(f"fut1 result = {fut_list[1].wait()}")
309
+ fut1 result = 1
310
+ """
311
+ return cast(
312
+ Future[list[Future]],
313
+ torch._C._collect_all(cast(list[torch._C.Future], futures)),
314
+ )
315
+
316
+
317
+ def wait_all(futures: list[Future]) -> list:
318
+ r"""
319
+ Waits for all provided futures to be complete, and returns
320
+ the list of completed values. If any of the futures encounters an error,
321
+ the method will exit early and report the error not waiting for other
322
+ futures to complete.
323
+
324
+ Args:
325
+ futures (list): a list of :class:`~torch.futures.Future` object.
326
+
327
+ Returns:
328
+ A list of the completed :class:`~torch.futures.Future` results. This
329
+ method will throw an error if ``wait`` on any
330
+ :class:`~torch.futures.Future` throws.
331
+ """
332
+ return [
333
+ fut.wait()
334
+ for fut in torch._C._collect_all(cast(list[torch._C.Future], futures)).wait()
335
+ ]
.venv/lib/python3.12/site-packages/torch/futures/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (16.6 kB). View file
 
.venv/lib/python3.12/site-packages/torch/fx/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r'''
2
+ FX is a toolkit for developers to use to transform ``nn.Module``
3
+ instances. FX consists of three main components: a **symbolic tracer,**
4
+ an **intermediate representation**, and **Python code generation**. A
5
+ demonstration of these components in action:
6
+
7
+ ::
8
+
9
+ import torch
10
+
11
+
12
+ # Simple module for demonstration
13
+ class MyModule(torch.nn.Module):
14
+ def __init__(self) -> None:
15
+ super().__init__()
16
+ self.param = torch.nn.Parameter(torch.rand(3, 4))
17
+ self.linear = torch.nn.Linear(4, 5)
18
+
19
+ def forward(self, x):
20
+ return self.linear(x + self.param).clamp(min=0.0, max=1.0)
21
+
22
+
23
+ module = MyModule()
24
+
25
+ from torch.fx import symbolic_trace
26
+
27
+ # Symbolic tracing frontend - captures the semantics of the module
28
+ symbolic_traced: torch.fx.GraphModule = symbolic_trace(module)
29
+
30
+ # High-level intermediate representation (IR) - Graph representation
31
+ print(symbolic_traced.graph)
32
+ """
33
+ graph():
34
+ %x : [num_users=1] = placeholder[target=x]
35
+ %param : [num_users=1] = get_attr[target=param]
36
+ %add : [num_users=1] = call_function[target=operator.add](args = (%x, %param), kwargs = {})
37
+ %linear : [num_users=1] = call_module[target=linear](args = (%add,), kwargs = {})
38
+ %clamp : [num_users=1] = call_method[target=clamp](args = (%linear,), kwargs = {min: 0.0, max: 1.0})
39
+ return clamp
40
+ """
41
+
42
+ # Code generation - valid Python code
43
+ print(symbolic_traced.code)
44
+ """
45
+ def forward(self, x):
46
+ param = self.param
47
+ add = x + param; x = param = None
48
+ linear = self.linear(add); add = None
49
+ clamp = linear.clamp(min = 0.0, max = 1.0); linear = None
50
+ return clamp
51
+ """
52
+
53
+ The **symbolic tracer** performs "symbolic execution" of the Python
54
+ code. It feeds fake values, called Proxies, through the code. Operations
55
+ on these Proxies are recorded. More information about symbolic tracing
56
+ can be found in the :func:`symbolic_trace` and :class:`Tracer`
57
+ documentation.
58
+
59
+ The **intermediate representation** is the container for the operations
60
+ that were recorded during symbolic tracing. It consists of a list of
61
+ Nodes that represent function inputs, callsites (to functions, methods,
62
+ or :class:`torch.nn.Module` instances), and return values. More information
63
+ about the IR can be found in the documentation for :class:`Graph`. The
64
+ IR is the format on which transformations are applied.
65
+
66
+ **Python code generation** is what makes FX a Python-to-Python (or
67
+ Module-to-Module) transformation toolkit. For each Graph IR, we can
68
+ create valid Python code matching the Graph's semantics. This
69
+ functionality is wrapped up in :class:`GraphModule`, which is a
70
+ :class:`torch.nn.Module` instance that holds a :class:`Graph` as well as a
71
+ ``forward`` method generated from the Graph.
72
+
73
+ Taken together, this pipeline of components (symbolic tracing ->
74
+ intermediate representation -> transforms -> Python code generation)
75
+ constitutes the Python-to-Python transformation pipeline of FX. In
76
+ addition, these components can be used separately. For example,
77
+ symbolic tracing can be used in isolation to capture a form of
78
+ the code for analysis (and not transformation) purposes. Code
79
+ generation can be used for programmatically generating models, for
80
+ example from a config file. There are many uses for FX!
81
+
82
+ Several example transformations can be found at the
83
+ `examples <https://github.com/pytorch/examples/tree/master/fx>`__
84
+ repository.
85
+ '''
86
+
87
+ from torch.fx import immutable_collections
88
+ from torch.fx._symbolic_trace import (
89
+ PH,
90
+ ProxyableClassMeta,
91
+ symbolic_trace,
92
+ Tracer,
93
+ wrap,
94
+ )
95
+ from torch.fx.graph import CodeGen, Graph
96
+ from torch.fx.graph_module import GraphModule
97
+ from torch.fx.interpreter import Interpreter, Transformer
98
+ from torch.fx.node import has_side_effect, map_arg, Node
99
+ from torch.fx.proxy import Proxy
100
+ from torch.fx.subgraph_rewriter import replace_pattern
101
+
102
+
103
+ __all__ = [
104
+ "symbolic_trace",
105
+ "Tracer",
106
+ "wrap",
107
+ "Graph",
108
+ "GraphModule",
109
+ "Interpreter",
110
+ "Transformer",
111
+ "Node",
112
+ "Proxy",
113
+ "replace_pattern",
114
+ "has_side_effect",
115
+ "map_arg",
116
+ ]
.venv/lib/python3.12/site-packages/torch/fx/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.36 kB). View file
 
.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_compatibility.cpython-312.pyc ADDED
Binary file (1.87 kB). View file