utils.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. # mypy: allow-untyped-defs
  2. import ast
  3. import copy
  4. import dataclasses
  5. import functools
  6. import inspect
  7. import json
  8. import math
  9. import operator
  10. import re
  11. from collections import defaultdict
  12. from collections.abc import Callable, Iterable
  13. from contextlib import contextmanager
  14. from inspect import ismethod, Parameter
  15. from typing import Any, Optional, TYPE_CHECKING, Union
  16. import torch
  17. from torch._guards import detect_fake_mode
  18. from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
  19. from torch._subclasses.functional_tensor import FunctionalTensor
  20. from torch.fx._utils import first_call_function_nn_module_stack
  21. from torch.fx.experimental.proxy_tensor import PreDispatchTorchFunctionMode
  22. from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
  23. if TYPE_CHECKING:
  24. import sympy
  25. from torch._export.passes.lift_constants_pass import ConstantAttrMap
  26. from torch._ops import OperatorBase
  27. from torch.export import ExportedProgram
  28. from torch.export.graph_signature import ExportGraphSignature
  29. from torch.export.graph_signature import CustomObjArgument, InputKind, OutputKind
  30. from torch.fx._pytree import (
  31. _deregister_pytree_flatten_spec,
  32. register_pytree_flatten_spec,
  33. )
  34. from torch.utils._pytree import (
  35. _deregister_pytree_node,
  36. _register_pytree_node,
  37. Context,
  38. FlattenFunc,
  39. FromDumpableContextFn,
  40. GetAttrKey,
  41. KeyPath,
  42. keystr,
  43. MappingKey,
  44. SequenceKey,
  45. ToDumpableContextFn,
  46. tree_flatten_with_path,
  47. UnflattenFunc,
  48. )
  49. placeholder_prefixes = {
  50. InputKind.USER_INPUT: "",
  51. InputKind.PARAMETER: "p_",
  52. InputKind.BUFFER: "b_",
  53. InputKind.CONSTANT_TENSOR: "c_",
  54. InputKind.CUSTOM_OBJ: "obj_",
  55. InputKind.TOKEN: "token",
  56. }
  57. _DISABLE_ATEN_TO_ASSERTION_PASS = False
  58. def _collect_and_set_constant_attrs(
  59. graph_signature, constants, mod
  60. ) -> "ConstantAttrMap":
  61. # the exported module will store constants & non-persistent buffers such that
  62. # retracing treats them as persistent buffers, so we inform the constants lifting pass
  63. # and overwrite the new graph signature using the previous program. This is intended to only be used
  64. # in run_decompositions where we still have access to original EP.
  65. from torch._export.passes.lift_constants_pass import ConstantAttrMap
  66. constant_attrs = ConstantAttrMap()
  67. non_persistent_buffers = {
  68. spec.target
  69. for spec in graph_signature.input_specs
  70. if spec.kind == InputKind.BUFFER and not spec.persistent
  71. }
  72. for name, value in constants.items():
  73. if name in non_persistent_buffers:
  74. continue
  75. # recursive getattr
  76. _mod = mod
  77. *atoms, attr = name.split(".")
  78. for atom in atoms:
  79. _mod = getattr(_mod, atom)
  80. # remove as buffer, reassign as constant/non-persistent buffer
  81. _mod._buffers.pop(attr, None)
  82. setattr(_mod, attr, value)
  83. constant_attrs.add(value, name)
  84. return constant_attrs
  85. def _register_constants_as_buffers(
  86. mod: torch.fx.GraphModule, state_dict, non_persistent_buffers
  87. ):
  88. # TODO some annoying circular dependency issue
  89. from torch.export.unflatten import _assign_attr, _AttrKind
  90. temp_registered_constants = set()
  91. for node in mod.graph.nodes:
  92. if node.op == "get_attr":
  93. target = torch.fx.graph_module._get_attr(mod, node.target)
  94. if isinstance(target, torch.Tensor):
  95. # Make sure we also check if the original buffer is
  96. # non persistent as well.
  97. if (node.target not in state_dict) and (
  98. node.target not in non_persistent_buffers
  99. ):
  100. torch.fx.graph_module._del_attr(mod, node.target)
  101. _assign_attr(target, mod, node.target, _AttrKind.BUFFER, False)
  102. temp_registered_constants.add(node.target)
  103. mod.recompile()
  104. return temp_registered_constants
  105. def _override_graph_signature_for_temp_registered_constants(
  106. sig: "ExportGraphSignature", temp_registered_constants
  107. ):
  108. for spec in sig.input_specs:
  109. if spec.target in temp_registered_constants:
  110. spec.kind = InputKind.CONSTANT_TENSOR
  111. spec.persistent = None
  112. for spec in sig.output_specs:
  113. if (
  114. spec.kind == OutputKind.BUFFER_MUTATION
  115. and spec.target in temp_registered_constants
  116. ):
  117. raise RuntimeError(
  118. f"Constant {spec.target} is mutated in the forward method. Pls register it as buffer"
  119. )
  120. return sig
  121. def _overwrite_signature_for_non_persistent_buffers(
  122. old_sig: "ExportGraphSignature", new_sig: "ExportGraphSignature"
  123. ):
  124. # overwrite signature for non-persistent buffers
  125. non_persistent_buffers = {
  126. spec.target
  127. for spec in old_sig.input_specs
  128. if spec.kind == InputKind.BUFFER and not spec.persistent
  129. }
  130. for spec in new_sig.input_specs:
  131. if spec.kind == InputKind.BUFFER and spec.target in non_persistent_buffers:
  132. spec.persistent = False
  133. return new_sig
  134. def _collect_param_buffer_metadata(mod: torch.fx.GraphModule) -> dict[str, Any]:
  135. """
  136. Param/buffer metadata needs to be saved before lowering to aten IR
  137. because aten IR lifts them, as a result, automatic preservation doesn't work.
  138. This is intended to be called on the strict mode tracing right before lowering to
  139. aten IR OR run_decomposition pass.
  140. """
  141. params_buffers_to_node_meta = {}
  142. def _getattr(model: torch.fx.GraphModule, attr_name: str):
  143. *prefix, field = attr_name.split(".")
  144. t = model
  145. for item in prefix:
  146. t = getattr(t, item, None) # type: ignore[assignment]
  147. if t is None:
  148. raise AssertionError(f"attribute {item!r} not found in path")
  149. return getattr(t, field)
  150. for node in mod.graph.nodes:
  151. target = node.target
  152. meta = node.meta
  153. if node.op == "call_module":
  154. submodule = _getattr(mod, target)
  155. if isinstance(submodule, torch.nn.Module):
  156. for name, _ in submodule.named_parameters(
  157. recurse=True, remove_duplicate=False
  158. ):
  159. params_buffers_to_node_meta[target + "." + name] = meta
  160. for name, _ in submodule.named_buffers(
  161. recurse=True, remove_duplicate=False
  162. ):
  163. params_buffers_to_node_meta[target + "." + name] = meta
  164. if node.op == "get_attr":
  165. submodule = _getattr(mod, target)
  166. if not isinstance(submodule, torch.fx.GraphModule):
  167. params_buffers_to_node_meta[target] = meta
  168. # If the call_function uses param as input, we also need to update params' meta
  169. # with this call_function node's meta.
  170. # This is basically the same flow as torch.fx.traceback.preserve_meta()
  171. if node.op == "call_function" and not isinstance(
  172. node.target, torch._ops.HigherOrderOperator
  173. ):
  174. for arg in node._input_nodes:
  175. if arg.op == "get_attr":
  176. for entry in torch.fx.proxy._COPY_META_FIELDS:
  177. # the custom field should not be copied
  178. if entry == "custom":
  179. continue
  180. if entry in meta:
  181. params_buffers_to_node_meta[arg.target][entry] = meta[entry]
  182. return params_buffers_to_node_meta
  183. def _maybe_find_pre_dispatch_tf_mode_for_export():
  184. if not torch._C._is_torch_function_mode_enabled():
  185. return None
  186. torch_function_mode_stack = torch.overrides._get_current_function_mode_stack()
  187. pre_dispatch_tf_modes = [
  188. mode
  189. for mode in torch_function_mode_stack
  190. if isinstance(mode, PreDispatchTorchFunctionMode)
  191. ]
  192. if len(pre_dispatch_tf_modes) > 1:
  193. raise AssertionError(
  194. f"Expected only one PreDispatchTorchFunctionMode, found {len(pre_dispatch_tf_modes)}"
  195. )
  196. if len(pre_dispatch_tf_modes) == 0:
  197. return None
  198. mode = pre_dispatch_tf_modes[0]
  199. return mode
  200. def _populate_param_buffer_metadata_to_new_gm(
  201. params_buffers_to_node_meta: dict[str, Any],
  202. gm: torch.fx.GraphModule,
  203. new_sig: "ExportGraphSignature",
  204. ) -> None:
  205. """
  206. Given that we collected param'buffer metadata before, we put them back in
  207. newly traced graph module
  208. """
  209. # Don't copy over nn_module_stack, stack_trace metadata for params/buffers nodes
  210. for metadata in params_buffers_to_node_meta.values():
  211. metadata.pop("nn_module_stack", None)
  212. metadata.pop("stack_trace", None)
  213. for node in gm.graph.nodes:
  214. if node.op == "placeholder":
  215. if node.target in new_sig.inputs_to_parameters:
  216. param_name = new_sig.inputs_to_parameters[node.target]
  217. if param_name in params_buffers_to_node_meta:
  218. for k, v in params_buffers_to_node_meta[param_name].items():
  219. node.meta[k] = v
  220. if node.target in new_sig.inputs_to_buffers:
  221. buffer_name = new_sig.inputs_to_buffers[node.target]
  222. if buffer_name in params_buffers_to_node_meta:
  223. for k, v in params_buffers_to_node_meta[buffer_name].items():
  224. node.meta[k] = v
  225. def _get_shape_env_from_gm(gm: torch.fx.GraphModule):
  226. vals = [
  227. node.meta["val"]
  228. for node in gm.graph.nodes
  229. if node.meta.get("val", None) is not None
  230. ]
  231. fake_mode = _detect_fake_mode_from_gm(gm)
  232. if fake_mode is not None:
  233. return fake_mode.shape_env
  234. for v in vals:
  235. if isinstance(v, torch.SymInt):
  236. return v.node.shape_env
  237. def _rename_without_collisions(
  238. name_map: dict[str, str],
  239. find_available: dict[str, int],
  240. used_names: set[str],
  241. orig_name: str,
  242. name: str,
  243. is_placeholder: bool = False,
  244. ):
  245. """
  246. Renames nodes to avoid name collisions, with suffixing.
  247. name_map: map from original name to new name
  248. find_available: map prefix to available suffix
  249. used_names: cache of used names
  250. orig_name: mapping key
  251. name: candidate name (potentially suffixed, e.g. mul_2)
  252. is_placeholder: if the node is a placeholder, avoid detecting suffix
  253. """
  254. match = re.match(r"(.*)_(\d+)", name)
  255. key = name
  256. if match and not is_placeholder:
  257. prefix, n = match.group(1), match.group(2)
  258. key = prefix
  259. new_name = name
  260. if new_name in used_names:
  261. new_name = f"{key}_{find_available[key] + 1}"
  262. match = re.match(r"(.*)_(\d+)", new_name)
  263. if match:
  264. prefix, n = match.group(1), match.group(2)
  265. if int(n) > find_available[prefix]:
  266. find_available[prefix] = int(n)
  267. name_map[orig_name] = new_name
  268. used_names.add(new_name)
  269. return name_map[orig_name]
  270. def get_keystr(key_path: KeyPath) -> str:
  271. """For a given index into the flat_args, return a human readable string
  272. describing how to access it, e.g. "*args["foo"][0].bar"
  273. """
  274. # Prefix the keypath with "*args" or "**kwargs" to make it clearer where
  275. # the arguments come from. Ultimately we ought to serialize the
  276. # original arg names for the best error message here.
  277. args_kwargs_key_path = key_path[0]
  278. if not isinstance(args_kwargs_key_path, SequenceKey):
  279. raise AssertionError(
  280. f"expected SequenceKey, got {type(args_kwargs_key_path).__name__}"
  281. )
  282. if args_kwargs_key_path.idx == 0:
  283. return f"*args{keystr(key_path[1:])}"
  284. else:
  285. kwarg_key = key_path[1]
  286. if not isinstance(kwarg_key, (GetAttrKey, MappingKey)):
  287. raise AssertionError(
  288. f"expected GetAttrKey or MappingKey, got {type(kwarg_key).__name__}"
  289. )
  290. name = str(kwarg_key)[1:-1] # get rid of the enclosed []
  291. return f"{name}{keystr(key_path[2:])}"
  292. def _check_symint(
  293. symint: Union[int, torch.SymInt],
  294. arg: int,
  295. range_constraints,
  296. unification_map,
  297. keypath: KeyPath,
  298. i: Optional[int] = None,
  299. ) -> None:
  300. from torch.export.dynamic_shapes import _IntWrapper
  301. if (
  302. isinstance(arg, torch.SymInt)
  303. and not arg.node.expr.is_number
  304. or isinstance(arg, _IntWrapper)
  305. ):
  306. # This can happen when, say, arg is a fake tensor.
  307. # We do not run checks on symbolic shapes of fake inputs as
  308. # such checks can affect the shape env.
  309. return
  310. import sympy
  311. from torch._export.passes.add_runtime_assertions_for_constraints_pass import (
  312. _convert_range_to_int,
  313. )
  314. from torch.utils._sympy.solve import try_solve
  315. if isinstance(symint, torch.SymInt) and len(symint.node.expr.free_symbols) == 1:
  316. symbol = next(iter(symint.node.expr.free_symbols))
  317. if symbol in unification_map:
  318. existing_dim = symint.node.expr.subs(unification_map)
  319. if arg != existing_dim:
  320. path = get_keystr(keypath)
  321. if i is not None:
  322. path += f".shape[{i}]"
  323. raise RuntimeError(
  324. f"Expected input at {path} to be equal to {existing_dim}, but got {arg}",
  325. )
  326. else:
  327. if isinstance(symint.node.expr, sympy.Symbol):
  328. # Short cut for try_solve below. Also useful in cases where
  329. # sympy.Eq(symint.node.expr, arg) would evaluate to False
  330. # purely because symbol is constrained to be size-like,
  331. # e.g., when symint.node.expr = symbol and arg = 0.
  332. unification_map[symbol] = int(arg)
  333. else:
  334. solution = try_solve(sympy.Eq(symint.node.expr, arg), symbol)
  335. if solution is None:
  336. path = get_keystr(keypath)
  337. if i is not None:
  338. path += f".shape[{i}]"
  339. raise RuntimeError( # noqa: B904
  340. f"Expected input {path} = {arg} to be "
  341. f"of the form {symint.node.expr}, where {symbol} is an integer"
  342. )
  343. else:
  344. unification_map[symbol] = int(solution[1])
  345. if symint.node.expr in range_constraints:
  346. min_val, max_val = _convert_range_to_int(
  347. range_constraints[symint.node.expr]
  348. )
  349. # NOTE: we allow dimensions to be 0/1 at runtime
  350. if min_val > 2:
  351. if arg < min_val:
  352. path = get_keystr(keypath)
  353. if i is not None:
  354. path += f".shape[{i}]"
  355. raise RuntimeError(
  356. f"Expected input at {path} to be >= {min_val}, but got {arg}",
  357. )
  358. if max_val < math.inf:
  359. if arg > max_val:
  360. path = get_keystr(keypath)
  361. if i is not None:
  362. path += f".shape[{i}]"
  363. raise RuntimeError(
  364. f"Expected input at {path} to be <= {max_val}, but got {arg}",
  365. )
  366. elif isinstance(symint, torch.SymInt) and not symint.node.expr.is_number:
  367. # this means we deferred a guard from export analysis to runtime, let this pass
  368. # we'll add a runtime assert checking equality to this replacement expression
  369. pass
  370. elif arg != int(symint):
  371. path = get_keystr(keypath)
  372. if i is not None:
  373. path += f".shape[{i}]"
  374. raise RuntimeError(
  375. f"Expected input at {path} to be equal to {symint}, but got {arg}. "
  376. "If you meant for this dimension to be dynamic, please re-export and specify dynamic_shapes "
  377. "(e.g. with Dim.DYNAMIC)"
  378. )
  379. def _check_input_constraints_for_graph(
  380. input_placeholders: list[torch.fx.Node], flat_args_with_path, range_constraints
  381. ) -> None:
  382. if len(flat_args_with_path) != len(input_placeholders):
  383. raise RuntimeError(
  384. "Unexpected number of inputs "
  385. f"(expected {len(input_placeholders)}, got {len(flat_args_with_path)})"
  386. )
  387. # NOTE: export already guarantees that the same symbol is used in metadata
  388. # for all InputDims related by equality constraints, so we can just unify
  389. # symbols with given input dimension values to check equality constraints.
  390. unification_map: dict[sympy.Symbol, Any] = {}
  391. for (key_path, arg), node in zip(flat_args_with_path, input_placeholders):
  392. node_val = node.meta.get("val")
  393. if isinstance(node_val, FakeTensor):
  394. if not isinstance(arg, torch.Tensor):
  395. raise RuntimeError(
  396. f"Expected input at {get_keystr(key_path)} to be a tensor, but got {type(arg)}",
  397. )
  398. if len(node_val.shape) != len(arg.shape):
  399. raise RuntimeError(
  400. f"Unexpected number of dimensions in input at {get_keystr(key_path)}.shape "
  401. f"(expected {node_val.shape}, got {arg.shape})"
  402. )
  403. for j, (arg_dim, node_dim) in enumerate(zip(arg.shape, node_val.shape)):
  404. _check_symint(
  405. node_dim, arg_dim, range_constraints, unification_map, key_path, j
  406. )
  407. elif isinstance(node_val, (int, float, str)):
  408. if type(arg) is not type(node_val) or arg != node_val:
  409. raise RuntimeError(
  410. f"Expected input at {get_keystr(key_path)} to be equal to {node_val}, but got {arg}",
  411. )
  412. elif isinstance(node_val, torch.SymInt):
  413. _check_symint(
  414. node_val,
  415. arg,
  416. range_constraints,
  417. unification_map,
  418. key_path,
  419. None,
  420. )
  421. def register_dataclass_as_pytree_node(
  422. cls: type[Any],
  423. flatten_fn: Optional[FlattenFunc] = None,
  424. unflatten_fn: Optional[UnflattenFunc] = None,
  425. *,
  426. serialized_type_name: Optional[str] = None,
  427. to_dumpable_context: Optional[ToDumpableContextFn] = None,
  428. from_dumpable_context: Optional[FromDumpableContextFn] = None,
  429. return_none_fields: bool = False,
  430. ) -> None:
  431. if not dataclasses.is_dataclass(cls):
  432. raise AssertionError(
  433. f"Only dataclasses can be registered with this function: {cls}"
  434. )
  435. @torch._dynamo.dont_skip_tracing
  436. def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]:
  437. flattened = []
  438. flat_names = []
  439. none_names = []
  440. for f in dataclasses.fields(obj):
  441. name, val = f.name, getattr(obj, f.name)
  442. if val is not None or return_none_fields:
  443. flattened.append(val)
  444. flat_names.append(name)
  445. else:
  446. none_names.append(name)
  447. return flattened, [flat_names, none_names]
  448. @torch._dynamo.dont_skip_tracing
  449. def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any:
  450. flat_names, none_names = context
  451. return cls(**dict(zip(flat_names, values)), **dict.fromkeys(none_names))
  452. @torch._dynamo.dont_skip_tracing
  453. def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]:
  454. flattened, (flat_names, _none_names) = flatten_fn(obj) # type: ignore[misc]
  455. return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], flat_names
  456. flatten_fn = flatten_fn if flatten_fn is not None else default_flatten_fn
  457. unflatten_fn = unflatten_fn if unflatten_fn is not None else default_unflatten_fn
  458. if (to_dumpable_context is None) ^ (from_dumpable_context is None):
  459. raise ValueError(
  460. f"Both to_dumpable_context and from_dumpable_context for {cls} must "
  461. "be None or registered."
  462. )
  463. _register_pytree_node(
  464. cls,
  465. flatten_fn,
  466. unflatten_fn,
  467. serialized_type_name=serialized_type_name,
  468. flatten_with_keys_fn=default_flatten_fn_with_keys,
  469. to_dumpable_context=to_dumpable_context,
  470. from_dumpable_context=from_dumpable_context,
  471. )
  472. def is_param(program: "ExportedProgram", node: torch.fx.Node) -> bool:
  473. """
  474. Checks if the given node is a parameter within the exported program
  475. """
  476. return node.name in program.graph_signature.inputs_to_parameters
  477. def get_param(
  478. program: "ExportedProgram",
  479. node: torch.fx.Node,
  480. ) -> Optional[torch.nn.Parameter]:
  481. """
  482. Returns the parameter associated with the given node in the exported program.
  483. Returns None if the node is not a parameter within the exported program
  484. """
  485. if is_param(program, node):
  486. parameter_name = program.graph_signature.inputs_to_parameters[node.name]
  487. return program.state_dict[parameter_name]
  488. return None
  489. def is_buffer(program: "ExportedProgram", node: torch.fx.Node) -> bool:
  490. """
  491. Checks if the given node is a buffer within the exported program
  492. """
  493. return node.name in program.graph_signature.inputs_to_buffers
  494. def get_buffer(
  495. program: "ExportedProgram",
  496. node: torch.fx.Node,
  497. ) -> Optional[torch.Tensor]:
  498. """
  499. Returns the buffer associated with the given node in the exported program.
  500. Returns None if the node is not a buffer within the exported program
  501. """
  502. if is_buffer(program, node):
  503. buffer_name = program.graph_signature.inputs_to_buffers[node.name]
  504. if buffer_name in program.graph_signature.non_persistent_buffers:
  505. return program.constants[buffer_name]
  506. else:
  507. return program.state_dict[buffer_name]
  508. return None
  509. def is_lifted_tensor_constant(
  510. program: "ExportedProgram",
  511. node: torch.fx.Node,
  512. ) -> bool:
  513. """
  514. Checks if the given node is a lifted tensor constant within the exported program
  515. """
  516. return node.name in program.graph_signature.inputs_to_lifted_tensor_constants
  517. def get_lifted_tensor_constant(
  518. program: "ExportedProgram",
  519. node: torch.fx.Node,
  520. ) -> Optional[torch.Tensor]:
  521. """
  522. Returns the lifted tensor constant associated with the given node in the exported program.
  523. Returns None if the node is not a lifted tensor constant within the exported program
  524. """
  525. if is_lifted_tensor_constant(program, node):
  526. lifted_tensor_name = program.graph_signature.inputs_to_lifted_tensor_constants[
  527. node.name
  528. ]
  529. return program.constants[lifted_tensor_name]
  530. return None
  531. def sequential_split(
  532. gm: torch.fx.GraphModule,
  533. node_call_back: Callable[[torch.fx.Node], Union[torch.fx.Node, bool]],
  534. ) -> torch.fx.GraphModule:
  535. """
  536. sequential_split creates a new graph module that splits the input graph module into multiple submodules
  537. based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return
  538. True if the node is a delimiter. Delimiter will be the first node in the next submodule.
  539. """
  540. from torch.fx.passes.split_module import split_module
  541. split_map = {}
  542. split_id = 0
  543. for node in gm.graph.nodes:
  544. if node_call_back(node):
  545. split_id += 1
  546. split_map[node] = split_id
  547. new_gm = split_module(
  548. gm,
  549. gm,
  550. lambda node: split_map[node],
  551. keep_original_order=True,
  552. keep_original_node_name=True,
  553. )
  554. # Keep the codegen from original graph module to preserve e.g. pytree info.
  555. new_gm.graph._codegen = gm.graph._codegen
  556. new_gm.recompile()
  557. return new_gm
  558. def nodes_filter(nodes: list[torch.fx.Node], node_call_back) -> list[torch.fx.Node]:
  559. """Returns the nodes that match the node_call_back as a list."""
  560. return [node for node in nodes if node_call_back(node)]
  561. @contextmanager
  562. def _disable_aten_to_metadata_assertions():
  563. global _DISABLE_ATEN_TO_ASSERTION_PASS
  564. orig_val = _DISABLE_ATEN_TO_ASSERTION_PASS
  565. _DISABLE_ATEN_TO_ASSERTION_PASS = True
  566. try:
  567. yield
  568. finally:
  569. _DISABLE_ATEN_TO_ASSERTION_PASS = orig_val
  570. def _insert_aten_to_metadata_assert_pass(gm: torch.fx.GraphModule) -> None:
  571. from torch._export.passes._node_metadata_hook import (
  572. _node_metadata_hook,
  573. _set_node_metadata_hook,
  574. )
  575. if _DISABLE_ATEN_TO_ASSERTION_PASS:
  576. return
  577. aten_to_variants = [
  578. torch.ops.aten.to.device,
  579. torch.ops.aten.to.dtype,
  580. torch.ops.aten.to.dtype_layout,
  581. ]
  582. for node in gm.graph.nodes:
  583. if node.target in aten_to_variants:
  584. if (
  585. node.prev.target is torch.ops.aten._assert_tensor_metadata.default
  586. and node.args[0] == node.prev.args[0]
  587. ):
  588. # skip if already guarded
  589. continue
  590. if (tensor_val := node.args[0].meta.get("val")) is not None:
  591. with (
  592. gm.graph.inserting_before(node),
  593. _set_node_metadata_hook(
  594. gm,
  595. functools.partial(
  596. _node_metadata_hook,
  597. metadata={
  598. "stack_trace": node.meta.get("stack_trace"),
  599. "nn_module_stack": node.meta.get("nn_module_stack"),
  600. },
  601. ),
  602. ),
  603. ):
  604. gm.graph.call_function(
  605. torch.ops.aten._assert_tensor_metadata.default,
  606. args=(node.args[0],),
  607. kwargs={
  608. "dtype": tensor_val.dtype,
  609. "device": tensor_val.device,
  610. "layout": tensor_val.layout,
  611. },
  612. )
  613. def apply_runtime_assertion_pass(gm: torch.fx.GraphModule, graph_signature):
  614. from torch._export.passes._node_metadata_hook import (
  615. _node_metadata_hook,
  616. _set_node_metadata_hook,
  617. )
  618. from torch._functorch._aot_autograd.input_output_analysis import _graph_output_names
  619. if not torch._dynamo.config.do_not_emit_runtime_asserts:
  620. stack_trace = (
  621. 'File "torch/fx/passes/runtime_assert.py", line 24, '
  622. "in insert_deferred_runtime_asserts"
  623. )
  624. with _set_node_metadata_hook(
  625. gm,
  626. functools.partial(
  627. _node_metadata_hook, metadata={"stack_trace": stack_trace}
  628. ),
  629. ):
  630. shape_env = _get_shape_env_from_gm(gm)
  631. if shape_env:
  632. insert_deferred_runtime_asserts(
  633. gm,
  634. shape_env,
  635. f"exported program: {first_call_function_nn_module_stack(gm.graph)}",
  636. export=True,
  637. )
  638. # insert runtime assertions for aten.to nodes
  639. _insert_aten_to_metadata_assert_pass(gm)
  640. # update output specs
  641. gm.recompile()
  642. graph_signature.user_outputs = _graph_output_names(gm)
  643. return gm, graph_signature
  644. def nodes_first(
  645. nodes: list[torch.fx.Node], node_call_back=None
  646. ) -> Optional[torch.fx.Node]:
  647. """
  648. Returns the first node that matches the node_call_back. If no node matches, returns None.
  649. When node_call_back is None, returns the first node in the node list.
  650. """
  651. ret = nodes_filter(nodes, node_call_back if node_call_back else lambda node: True)
  652. if len(ret) > 0:
  653. return ret[0]
  654. return None
  655. def nodes_count(nodes: list[torch.fx.Node], node_call_back) -> int:
  656. """Returns the number of nodes that match the node_call_back."""
  657. return len(nodes_filter(nodes, node_call_back))
  658. def nodes_map(nodes: list[torch.fx.Node], node_call_back) -> list[torch.fx.Node]:
  659. """
  660. Sequentially visit the nodes list and invoke node_call_back on each element.
  661. Returns the nodes list after the node_call_back is invoked on each element.
  662. """
  663. for node in nodes:
  664. node_call_back(node)
  665. return nodes
  666. def node_replace_(old_node: torch.fx.Node, new_node: torch.fx.Node) -> None:
  667. """
  668. Replace all uses of old_node with new_node.
  669. """
  670. old_node.replace_all_uses_with(new_node)
  671. old_node.users.clear()
  672. old_node.graph.erase_node(old_node)
  673. def _update_gm_meta_if_possible(gm: torch.fx.GraphModule, mod: torch.nn.Module) -> None:
  674. if (
  675. isinstance(mod, torch.fx.GraphModule)
  676. and hasattr(mod, "meta")
  677. and "custom" in mod.meta
  678. ):
  679. gm.meta.update({"custom": mod.meta["custom"]})
  680. def node_inline_(call_mod_node: torch.fx.Node) -> Optional[torch.fx.GraphModule]:
  681. """
  682. Inline the submodule of the given node into the parent module.
  683. Note: we only support the case where submodule takes tensors inputs.
  684. """
  685. if call_mod_node.op != "call_module":
  686. raise AssertionError(f"expected call_module op, got {call_mod_node.op}")
  687. gm = call_mod_node.graph.owning_module
  688. if gm is None:
  689. raise AssertionError("owning_module should not be None")
  690. if not isinstance(call_mod_node.target, str):
  691. raise AssertionError(
  692. f"expected target to be str, got {type(call_mod_node.target).__name__}"
  693. )
  694. sub_gm = getattr(gm, call_mod_node.target)
  695. phs = (node for node in sub_gm.graph.nodes if node.op == "placeholder")
  696. body = (
  697. node for node in sub_gm.graph.nodes if node.op not in ("placeholder", "output")
  698. )
  699. output = [node for node in sub_gm.graph.nodes if node.op == "output"]
  700. for ph, arg in zip(phs, call_mod_node.args):
  701. if not isinstance(arg, torch.fx.Node):
  702. raise AssertionError(f"expected fx.Node, got {type(arg)}")
  703. node_replace_(ph, arg)
  704. with gm.graph.inserting_before(call_mod_node):
  705. for node in body:
  706. new_node = gm.graph.node_copy(node)
  707. if node.op == "get_attr":
  708. new_target_name = new_node.target
  709. if hasattr(gm, new_target_name):
  710. # Loop through and find the "submod_{i}" that have no name collision
  711. i = 1
  712. new_target_name = f"submod_{i}"
  713. while hasattr(gm, new_target_name):
  714. i += 1
  715. new_target_name = f"submod_{i}"
  716. new_node.target = new_target_name
  717. setattr(gm, new_node.target, getattr(sub_gm, node.target))
  718. node_replace_(node, new_node)
  719. if len(output) > 0:
  720. if len(output) != 1 or len(output[0].args) != 1:
  721. raise AssertionError(
  722. f"expected exactly 1 output with 1 arg, got {len(output)} outputs"
  723. )
  724. new_output = output[0].args[0]
  725. if isinstance(new_output, torch.fx.Node):
  726. # Clear the users of the output node and set
  727. # the users to be the users of original call_module node.
  728. new_output.users.clear()
  729. node_replace_(call_mod_node, new_output)
  730. elif isinstance(new_output, (list, tuple)):
  731. # Pop subgraph output node from users.
  732. for node in new_output:
  733. node.users.pop(output[0])
  734. # Inline the get_item calls for the output node.
  735. get_item_users = nodes_filter(
  736. list(call_mod_node.users.keys()),
  737. lambda node: node.op == "call_function"
  738. and node.target is operator.getitem,
  739. )
  740. # get_item_node.args[1] is the idx referring to new_output[idx]
  741. nodes_map(
  742. get_item_users,
  743. lambda get_item_node: node_replace_(
  744. get_item_node,
  745. new_output[get_item_node.args[1]],
  746. ),
  747. )
  748. call_mod_node.graph.erase_node(call_mod_node)
  749. else:
  750. raise NotImplementedError(
  751. f"Unsupported output type {type(new_output)}. Expect it to be a Node or a list/tuple of Nodes."
  752. )
  753. else:
  754. call_mod_node.graph.erase_node(call_mod_node)
  755. gm.delete_all_unused_submodules()
  756. gm.recompile()
  757. return gm
  758. def _get_torch_jit_trace_forward_signature(mod: torch.nn.Module) -> inspect.Signature:
  759. """
  760. Get source code and parse argument names using AST. The function returns
  761. a signature of the forward() function.
  762. # TODO: Directly provide inspect.signature compatible TS-d module.
  763. """
  764. ast_mod = ast.parse(mod.code) # type: ignore[call-overload]
  765. ast_func_def: ast.FunctionDef = ast_mod.body[0]
  766. # FIXME(jiashenc): TorchScript should only allow positional or keywords arguments.
  767. arg_type_map = {"args": Parameter.POSITIONAL_OR_KEYWORD}
  768. # Traverse all argument types in AST tree and create associated parameters.
  769. param_list = []
  770. for arg_type, param_type in arg_type_map.items():
  771. arg_name_list = [a.arg for a in getattr(ast_func_def.args, arg_type)]
  772. for arg_name in arg_name_list:
  773. if arg_name == "self":
  774. continue # Skip self argument.
  775. param_list.append(inspect.Parameter(arg_name, param_type))
  776. return inspect.Signature(parameters=param_list)
  777. def _bind_signature_to_inputs(mod, fake_args, fake_kwargs):
  778. if isinstance(mod, (torch.jit.ScriptModule, torch.jit.TracedModule)):
  779. sig = _get_torch_jit_trace_forward_signature(mod)
  780. # Sanity check for placeholder names coming from TorchScript.
  781. if len(sig.parameters) != len(fake_args) + len(fake_kwargs):
  782. raise AssertionError(
  783. "Arguments other than POSITIONAL_OR_KEYWORD kinds in forward() "
  784. "are not supported in _get_torch_jit_trace_forward_signature"
  785. )
  786. else:
  787. sig = inspect.signature(mod.forward)
  788. # Rather than binding both fake_args and fake_kwargs to sig names, we
  789. # (partially) bind only fake_args, while reusing fake_kwarg names. This
  790. # ensures that fake_kwargs do not get reordered, which is important to
  791. # match flattened user inputs.
  792. return {**sig.bind_partial(*fake_args).arguments, **fake_kwargs}
  793. def _build_cache(name, find_available, used_names):
  794. used_names.add(name)
  795. match = re.match(r"(.*)_(\d+)", name)
  796. if match:
  797. prefix, n = match.group(1), match.group(2)
  798. if int(n) > find_available[prefix]:
  799. find_available[prefix] = int(n)
  800. def _name_hoo_subgraph_placeholders(gm: torch.fx.GraphModule) -> None:
  801. """
  802. Propagate placeholder names from the top-level graph into HigherOrderOp subgraphs,
  803. and handle collisions with non-placeholders by count suffixing.
  804. Different HOO subgraph types have different input schemas, so we first enumerate them
  805. and gather the top-level named placeholder nodes.
  806. """
  807. # gather all HOO subgraphs and their top-level named placeholder nodes
  808. subgraph_ph_tuples: list[tuple[torch.fx.GraphModule, list[torch.fx.Node]]] = []
  809. for node in gm.graph.nodes:
  810. if node.op == "call_function" and isinstance(
  811. node.target, torch._ops.HigherOrderOperator
  812. ):
  813. # HOO subgraphs have varying input schemas, so we enumerate them there
  814. if node.target._name == "cond":
  815. _, true_graph, false_graph, cond_args = node._args
  816. subgraph_ph_tuples.append((getattr(gm, true_graph.target), cond_args))
  817. subgraph_ph_tuples.append((getattr(gm, false_graph.target), cond_args))
  818. elif node.target._name == "wrap_with_set_grad_enabled":
  819. subgraph, phs = node._args[1], node._args[2:]
  820. subgraph_ph_tuples.append((getattr(gm, subgraph.target), phs))
  821. elif node.target._name == "map_impl":
  822. body_graph, array, args = node._args
  823. subgraph_ph_tuples.append(
  824. (getattr(gm, body_graph.target), array + args)
  825. )
  826. # propagate names
  827. for subgraph, hoo_phs in subgraph_ph_tuples:
  828. name_map: dict[str, str] = {}
  829. find_available: dict[str, int] = defaultdict(int)
  830. used_names: set[str] = set()
  831. for i, node in enumerate(subgraph.graph.nodes):
  832. if i < len(hoo_phs): # placeholder, retain name
  833. name_map[node.name] = hoo_phs[i].name
  834. node.name = node.target = hoo_phs[i].name
  835. _build_cache(node.name, find_available, used_names)
  836. else: # non-placeholder, check for collisions
  837. node.name = _rename_without_collisions(
  838. name_map, find_available, used_names, node.name, node.name
  839. )
  840. # recurse and recompile
  841. _name_hoo_subgraph_placeholders(subgraph)
  842. subgraph.recompile()
  843. def _assign_new_node_names(
  844. gm: torch.fx.GraphModule,
  845. name_map: dict[str, str],
  846. custom_meta: dict[str, Any],
  847. ) -> None:
  848. """
  849. Assign new names to all nodes, in the graph module, from name map.
  850. """
  851. for node in gm.graph.nodes:
  852. if node.op == "placeholder":
  853. if node.name not in name_map:
  854. raise AssertionError(f"placeholder node {node.name!r} not in name_map")
  855. node.name = node.target = name_map[node.name]
  856. if node.name in custom_meta:
  857. if node.meta.get("custom") is None:
  858. node.meta["custom"] = {}
  859. else:
  860. # Assert if any existing key has different value
  861. for k, v in node.meta["custom"].items():
  862. if (
  863. k in custom_meta[node.name]
  864. and v != custom_meta[node.name][k]
  865. ):
  866. raise AssertionError(
  867. f"Mismatch in custom metadata for key {k}. Value in "
  868. f"node.meta is {v} and value in custom_meta is {custom_meta[node.name][k]}."
  869. )
  870. node.meta["custom"].update(custom_meta[node.name])
  871. # if the constant obj is an input, we also need to update meta["val"]
  872. # because this is created before the placeholder naming pass
  873. if isinstance(node.meta["val"], CustomObjArgument):
  874. node.meta["val"].name = node.name
  875. elif node.name in name_map:
  876. node.name = name_map[node.name]
  877. def placeholder_naming_pass(
  878. gm: torch.fx.GraphModule,
  879. export_graph_signature: "ExportGraphSignature",
  880. mod: torch.nn.Module,
  881. fake_args,
  882. fake_kwargs,
  883. fake_params_buffers,
  884. constants: dict[str, Any],
  885. ) -> None:
  886. """
  887. This pass is run at the end of _export_non_strict() to assign better placeholder node names:
  888. - User inputs:
  889. These follow the signature of mod.forward(), e.g. forward(x, y) produces nodes x, y.
  890. For nested inputs from dictionaries, lists, tuples, or dataclasses,
  891. the names are a concatenation of the path to the tensor.
  892. e.g. x = {
  893. 'a': torch.randn(),
  894. 'b': [torch.randn(), torch.randn()]
  895. }
  896. produces nodes x_a, x_b_0, x_b_1.
  897. - Parameters/buffers/constants/custom objects:
  898. These follow the FQN of the object, prefixed by "p", "b", "c", "obj" respectively.
  899. e.g. self.bar.l0.weight produces "p_bar_l0_weight".
  900. - Effect tokens:
  901. These are named token, token_1, ...
  902. """
  903. custom_meta: dict[str, Any] = {}
  904. if isinstance(mod, torch.fx.GraphModule):
  905. for node in mod.graph.nodes:
  906. if "custom" in node.meta:
  907. custom_meta[node.name] = node.meta["custom"]
  908. def _strip_name(x):
  909. if x.startswith("L__self___"):
  910. x = x[len("L__self___") :]
  911. elif x.startswith("self_"):
  912. x = x[len("self_") :]
  913. x = re.sub(r"[^a-zA-Z0-9]", "_", x)
  914. return x
  915. def _extract_pytree_key(x):
  916. if isinstance(x, MappingKey):
  917. x = re.sub(r"[^a-zA-Z0-9]", "_", str(x.key))
  918. return x
  919. elif isinstance(x, SequenceKey):
  920. return str(x.idx)
  921. elif isinstance(x, GetAttrKey):
  922. return x.name
  923. else:
  924. raise RuntimeError(f"Pytree key of type {type(x)} not handled for {x}")
  925. name_map: dict[str, str] = {}
  926. find_available: dict[str, int] = defaultdict(int)
  927. used_names: set[str] = set()
  928. # map user input names with mod.forward() signature
  929. combined_args = _bind_signature_to_inputs(mod, fake_args, fake_kwargs)
  930. flat_args_with_path, _ = tree_flatten_with_path(combined_args)
  931. user_input_names = [
  932. spec.arg.name
  933. for spec in export_graph_signature.input_specs
  934. if spec.kind == InputKind.USER_INPUT
  935. ]
  936. # use pytree path to name nested user inputs
  937. for (arg_path, _arg), user_input_name in zip(flat_args_with_path, user_input_names):
  938. if user_input_name:
  939. _rename_without_collisions(
  940. name_map,
  941. find_available,
  942. used_names,
  943. user_input_name,
  944. placeholder_prefixes[InputKind.USER_INPUT]
  945. + "_".join(_extract_pytree_key(x).lower() for x in arg_path),
  946. is_placeholder=True,
  947. )
  948. # use graph signature input specs to map param/buffer/constant names
  949. # name effect tokens as token, token_1, ... (these aren't visible to user)
  950. for spec in export_graph_signature.input_specs:
  951. if spec.kind == InputKind.USER_INPUT:
  952. continue
  953. if spec.kind == InputKind.TOKEN:
  954. base_name = ""
  955. else:
  956. base_name = _strip_name(spec.target).lower()
  957. base_name = re.sub(r"[^a-zA-Z0-9]", "_", base_name)
  958. _rename_without_collisions(
  959. name_map,
  960. find_available,
  961. used_names,
  962. spec.arg.name,
  963. placeholder_prefixes[spec.kind] + base_name,
  964. is_placeholder=True,
  965. )
  966. if base_name in custom_meta:
  967. # the keys in custom_meta are node names from `mod`,
  968. # which is the base_name here.
  969. # we need the re-mapped name for lookup later
  970. custom_meta[name_map[spec.arg.name]] = custom_meta[base_name]
  971. del custom_meta[base_name]
  972. # handle naming collisions with call_function/get_attr inputs.
  973. # here, we want to prioritize user input names over call_function names
  974. # e.g. not have forward(self, mul): lead to a placeholder node called mul_13,
  975. # so we increment the suffix of call_function nodes as needed
  976. for node in gm.graph.nodes:
  977. if node.op == "placeholder":
  978. continue
  979. _rename_without_collisions(
  980. name_map, find_available, used_names, node.name, node.name
  981. )
  982. # assign new node names
  983. _assign_new_node_names(gm, name_map, custom_meta)
  984. # propagate names to higher order op subgraphs
  985. _name_hoo_subgraph_placeholders(gm)
  986. # re-generate graph module code
  987. gm.recompile()
  988. # modify graph signature (input specs, output specs, user input mutations)
  989. for spec in export_graph_signature.input_specs:
  990. if spec.arg.name not in name_map:
  991. raise AssertionError(f"input spec arg {spec.arg.name!r} not in name_map")
  992. spec.arg.name = name_map[spec.arg.name]
  993. if ( # handle targets for custom objects
  994. spec.kind == InputKind.CUSTOM_OBJ and spec.target in name_map
  995. ):
  996. # pyrefly: ignore [bad-index, index-error]
  997. spec.target = name_map[spec.target][4:] # strip obj_ prefix
  998. for spec in export_graph_signature.output_specs:
  999. if spec.arg.name in name_map:
  1000. spec.arg.name = name_map[spec.arg.name]
  1001. if spec.kind == OutputKind.USER_INPUT_MUTATION and spec.target in name_map:
  1002. # pyrefly: ignore [bad-index, index-error]
  1003. spec.target = name_map[spec.target]
  1004. # rename keys in constants dict for custom objects
  1005. for name in list(constants.keys()):
  1006. constant = constants[name]
  1007. if name in name_map and not isinstance(
  1008. constant, torch.Tensor
  1009. ): # rename custom objects with generic names
  1010. new_name = name_map[name]
  1011. if (
  1012. new_name != name
  1013. and re.match(r"arg(\d+)_1", name)
  1014. and new_name != placeholder_prefixes[InputKind.CUSTOM_OBJ] + name
  1015. ):
  1016. constants[new_name] = constant
  1017. del constants[name]
  1018. def remove_proxy_from_state_dict(state_dict: dict, in_place: bool) -> dict:
  1019. """
  1020. If `in_place` is false, return a new copy of `state_dict` with "proxy" removed from `v.__dict__`.
  1021. `v` is the values in the dictionary.
  1022. If `in_place` is true, modify `state_dict` in place.
  1023. """
  1024. if in_place:
  1025. for k, v in state_dict.items():
  1026. if hasattr(v, "proxy"):
  1027. delattr(state_dict[k], "proxy")
  1028. return state_dict
  1029. else:
  1030. new_state_dict = {}
  1031. for k, v in state_dict.items():
  1032. if hasattr(v, "proxy"):
  1033. new_state_dict[k] = v.detach().clone()
  1034. else:
  1035. new_state_dict[k] = v
  1036. return new_state_dict
  1037. def _detect_fake_mode_from_gm(
  1038. gm: torch.fx.GraphModule,
  1039. ) -> Optional[torch._subclasses.fake_tensor.FakeTensorMode]:
  1040. """
  1041. For a given graph module, we look at the "val" of placeholder nodes to find the fake inputs.
  1042. Additionally, if gm doesn't have placeholders, we further look at the "example_value" or "val" of other nodes.
  1043. If no fake mode is found, we return None for fake_mode.
  1044. """
  1045. fake_inps: list[torch.Tensor] = []
  1046. fake_vals: list[torch.Tensor] = []
  1047. for node in gm.graph.nodes:
  1048. if node.op == "placeholder" and "val" in node.meta:
  1049. fake_val = node.meta["val"]
  1050. if fake_val is not None and isinstance(fake_val, torch.Tensor):
  1051. fake_inps.append(fake_val)
  1052. elif len(fake_inps) == 0 and (
  1053. "example_value" in node.meta or "val" in node.meta
  1054. ):
  1055. fake_val = None
  1056. if "example_value" in node.meta:
  1057. fake_val = node.meta["example_value"]
  1058. elif "val" in node.meta:
  1059. fake_val = node.meta["val"]
  1060. if fake_val is not None and isinstance(fake_val, torch.Tensor):
  1061. fake_vals.append(fake_val)
  1062. return detect_fake_mode(fake_inps + fake_vals)
  1063. @contextmanager
  1064. def _disable_load_state_dict_hooks(mod: torch.nn.Module):
  1065. state_dict_hooks: dict[int, Callable] = dict(mod._state_dict_hooks)
  1066. state_dict_pre_hooks: dict[int, Callable] = dict(mod._state_dict_pre_hooks)
  1067. mod._state_dict_hooks.clear()
  1068. mod._state_dict_pre_hooks.clear()
  1069. try:
  1070. yield
  1071. finally:
  1072. mod._state_dict_hooks = state_dict_hooks
  1073. mod._state_dict_pre_hooks = state_dict_pre_hooks
  1074. def _is_cia_op(op: "OperatorBase") -> bool:
  1075. return (
  1076. torch._C._dispatch_has_kernel_for_dispatch_key(
  1077. op.name(), torch._C.DispatchKey.CompositeImplicitAutograd
  1078. )
  1079. or torch._C.DispatchKey.CompositeImplicitAutograd in op.py_kernels
  1080. )
  1081. def _is_preservable_cia_op(op: "OperatorBase") -> bool:
  1082. return _check_valid_to_preserve(op) and _is_cia_op(op)
  1083. def _is_aten_op(op: "OperatorBase") -> bool:
  1084. return op.name().split("::")[0] == "aten"
  1085. def _is_custom_op(op: "OperatorBase") -> bool:
  1086. return not _is_aten_op(op)
  1087. # We can't cache this because custom op registry API in python can still
  1088. # add entries to the C++ dispatcher.
  1089. def _materialize_cpp_cia_ops() -> None:
  1090. """
  1091. Utility function to query C++ dispatcher to get the all
  1092. possible CIA ops and populate them into torch.ops namespace
  1093. """
  1094. cia_ops = torch._C._dispatch_get_registrations_for_dispatch_key(
  1095. "CompositeImplicitAutograd"
  1096. )
  1097. # Materialize all CIA ops
  1098. for op in cia_ops:
  1099. namespace, op_name = tuple(op.split("::"))
  1100. split_list = op_name.split(".")
  1101. # Sometime overload could be missing
  1102. if len(split_list) not in (1, 2):
  1103. raise AssertionError(f"expected 1 or 2 parts, got {len(split_list)}")
  1104. op_name = split_list[0]
  1105. op_overload_name = "default"
  1106. if len(split_list) == 2:
  1107. op_overload_name = split_list[1]
  1108. _ = getattr(getattr(getattr(torch.ops, namespace), op_name), op_overload_name)
  1109. def _special_op_to_preserve_cia(*args, **kwargs):
  1110. """
  1111. This is an special marker that tells our infra that we shouldn't decompose this op.
  1112. """
  1113. return NotImplemented
  1114. # Our strategy for deciding if we can preserve a op is following:
  1115. # 1. The op should be known statically that it is functional
  1116. # 2. If it is maybe aliasing, we decompose because we must know if an op
  1117. # is mutating or aliasing.
  1118. def _check_valid_to_preserve(op_overload: "OperatorBase"):
  1119. from torch._decomp import _should_decompose_because_unsafe_op
  1120. if _should_decompose_because_unsafe_op(op_overload):
  1121. return False
  1122. if op_overload in FunctionalTensor.metadata_fns:
  1123. return False
  1124. if not hasattr(op_overload, "_schema"):
  1125. return False
  1126. alias_info = len(
  1127. [i for i in op_overload._schema.arguments if i.alias_info is not None]
  1128. )
  1129. is_mutating_or_aliasing = alias_info != 0 or op_overload._schema.is_mutable
  1130. if is_mutating_or_aliasing:
  1131. return False
  1132. if not torch._C._dispatch_has_kernel(op_overload.name()):
  1133. return False
  1134. return True
  1135. @functools.lru_cache(maxsize=1)
  1136. def _collect_all_valid_cia_ops_for_aten_namespace() -> set["OperatorBase"]:
  1137. return _collect_all_valid_cia_ops_for_namespace(torch.ops.aten)
  1138. def _collect_all_valid_cia_ops_for_namespace(
  1139. op_namespace: torch._ops._OpNamespace,
  1140. ) -> set["OperatorBase"]:
  1141. # Step 1: Materialize all ops from C++ dispatcher
  1142. _materialize_cpp_cia_ops()
  1143. # Step 2: Query all ops from python dispatcher
  1144. cia_ops = set()
  1145. for op in op_namespace:
  1146. op_packet = getattr(op_namespace, op)
  1147. for overload in op_packet.overloads():
  1148. op_overload = getattr(op_packet, overload)
  1149. if _is_preservable_cia_op(op_overload):
  1150. cia_ops.add(op_overload)
  1151. return cia_ops
  1152. def _collect_all_valid_cia_ops() -> set["OperatorBase"]:
  1153. """
  1154. This is an util function that gets the all CIA functional ops.
  1155. The algorithm is in 2 steps:
  1156. 1. We first query C++ dispatcher to get the list of CIA ops
  1157. and then we call getattr on torch.ops.aten to lazily populate
  1158. them.
  1159. 2. Sometimes, handful of ops have CIA registered in python dispatcher
  1160. but not on the C++ side, these can't be caught at the first step.
  1161. So we walk again to get the final list.
  1162. Note that the output of this function should never be modified
  1163. """
  1164. cia_ops = set()
  1165. for op_namespace_name in torch.ops._dir:
  1166. # The reason we split here is because aten ops are safe to cache.
  1167. if op_namespace_name != "aten":
  1168. if not hasattr(torch.ops, op_namespace_name):
  1169. raise AssertionError(
  1170. f"torch.ops does not have attribute {op_namespace_name!r}"
  1171. )
  1172. op_namespace = getattr(torch.ops, op_namespace_name)
  1173. if isinstance(op_namespace, torch._ops._OpNamespace):
  1174. cia_ops |= _collect_all_valid_cia_ops_for_namespace(op_namespace)
  1175. else:
  1176. cia_ops |= _collect_all_valid_cia_ops_for_aten_namespace()
  1177. return cia_ops
  1178. def _get_decomp_for_cia(op: "OperatorBase"):
  1179. # [NOTE] Separating out func.decompose
  1180. # Ideally we should be able to just register func.decompose but
  1181. # we can't as this decomp is gonna be registered to the py_impl.
  1182. # As a result it will infinitely recurse. So we first check if the op
  1183. # has py_impl entry for CIA and if it is we use that first. If not,
  1184. # we register C++ query to py_impl.
  1185. dk = torch._C.DispatchKey.CompositeImplicitAutograd
  1186. if dk in op.py_kernels and not isinstance(op.py_kernels[dk], torch._C.DispatchKey):
  1187. return op.py_kernels[dk]
  1188. def _special_op_to_decompose_cia(*args, **kwargs):
  1189. kernel = kwargs["kernel"]
  1190. del kwargs["kernel"]
  1191. # Can't call kernel.decompose due to infinite recursion as
  1192. # we register this kernel to py_impl directly
  1193. dk = torch._C.DispatchKey.CompositeImplicitAutograd
  1194. if torch._C._dispatch_has_kernel_for_dispatch_key(
  1195. kernel.name(), torch._C.DispatchKey.CompositeImplicitAutograd
  1196. ):
  1197. return kernel._op_dk(dk, *args, **kwargs)
  1198. else:
  1199. raise AssertionError(
  1200. f"Expected {kernel} to have CompositeImplicitAutograd kernel"
  1201. )
  1202. return functools.partial(_special_op_to_decompose_cia, kernel=op)
  1203. @contextmanager
  1204. def _compiling_state_context():
  1205. old_compiling_flag = torch.compiler._is_compiling_flag
  1206. old_exporting_flag = torch.compiler._is_exporting_flag
  1207. try:
  1208. torch.compiler._is_compiling_flag = True
  1209. torch.compiler._is_exporting_flag = True
  1210. yield
  1211. finally:
  1212. torch.compiler._is_compiling_flag = old_compiling_flag
  1213. torch.compiler._is_exporting_flag = old_exporting_flag
  1214. def _fakify_params_buffers(
  1215. fake_mode: FakeTensorMode,
  1216. mod: torch.nn.Module,
  1217. ) -> dict[str, Union[torch.Tensor, torch.nn.Parameter]]:
  1218. params_buffers = {
  1219. **dict(mod.named_parameters(remove_duplicate=False)),
  1220. **dict(mod.named_buffers(remove_duplicate=False)),
  1221. }
  1222. faked_params_buffers = {}
  1223. memo: dict[int, FakeTensor] = {}
  1224. for key, value in params_buffers.items():
  1225. if id(value) in memo:
  1226. fake_tensor = memo[id(value)]
  1227. else:
  1228. fake_tensor = fake_mode.from_tensor(value, static_shapes=True)
  1229. memo[id(value)] = fake_tensor
  1230. faked_params_buffers[key] = fake_tensor
  1231. return faked_params_buffers # type: ignore[return-value]
  1232. def register_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None:
  1233. """
  1234. Registers a module as a valid input type for :func:`torch.export.export`.
  1235. Args:
  1236. mod: the module instance
  1237. serialized_type_name: The serialized name for the module. This is
  1238. required if you want to serialize the pytree TreeSpec containing this
  1239. module.
  1240. Example::
  1241. import torch
  1242. class Module(torch.nn.Module):
  1243. def __init__(self):
  1244. super().__init__()
  1245. self.linear = torch.nn.Linear(3, 3)
  1246. def forward(self, x):
  1247. return self.linear(x)
  1248. torch._export.utils.register_module_as_pytree_node(InputDataClass)
  1249. class Mod(torch.nn.Module):
  1250. def forward(self, x, m):
  1251. return m(x) + x
  1252. ep = torch.export.export(Mod(), (torch.randn(3), Module()))
  1253. print(ep)
  1254. """
  1255. if not issubclass(cls, torch.nn.Module):
  1256. raise AssertionError(f"expected nn.Module subclass, got {cls}")
  1257. import weakref
  1258. class PrototypeModule(weakref.ref):
  1259. def __init__(self, m, *args, **kwargs):
  1260. super().__init__(m, *args, **kwargs) # type: ignore[call-arg]
  1261. if not isinstance(m, torch.nn.Module):
  1262. raise AssertionError(f"expected nn.Module, got {type(m).__name__}")
  1263. if hasattr(self, "_proto_cls"):
  1264. raise AssertionError("_proto_cls should not be set")
  1265. self._proto_cls = cls
  1266. def __eq__(self, other):
  1267. return self._proto_cls == other._proto_cls
  1268. def __deepcopy__(self, memo):
  1269. return PrototypeModule(self())
  1270. def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]:
  1271. named_parameters = dict(obj.named_parameters())
  1272. named_buffers = dict(obj.named_buffers())
  1273. params_buffers = {**named_parameters, **named_buffers}
  1274. return list(params_buffers.values()), [
  1275. list(params_buffers.keys()),
  1276. PrototypeModule(obj),
  1277. ]
  1278. def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any:
  1279. flat_names, ref = context
  1280. if ref is None or ref() is None:
  1281. raise RuntimeError("Module has been garbage collected")
  1282. obj = ref()
  1283. if flatten_fn is None:
  1284. raise AssertionError("flatten_fn should not be None")
  1285. flattened, _ = flatten_fn(obj)
  1286. # NOTE: This helper function will replicate an nn.Module in the exactly same
  1287. # structure to be used together with _reparameterize_module. This will
  1288. # create a clone of the module with the new parameters and buffers without
  1289. # affecting the original module.
  1290. def copy_module(mod: torch.nn.Module):
  1291. ret = copy.copy(mod)
  1292. ret.__dict__ = {copy.copy(k): copy.copy(v) for k, v in mod.__dict__.items()}
  1293. for name, child in ret.named_children():
  1294. setattr(ret, name, copy_module(child))
  1295. return ret
  1296. if any(v is not o for v, o in zip(values, flattened)):
  1297. with torch.nn.utils.stateless._reparametrize_module(
  1298. obj, dict(zip(flat_names, values)), tie_weights=True, strict=True
  1299. ):
  1300. ret = copy_module(obj)
  1301. else:
  1302. ret = obj
  1303. return ret
  1304. def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]:
  1305. flattened, [flat_names, *args] = flatten_fn(obj) # type: ignore[misc]
  1306. return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], [
  1307. flat_names,
  1308. *args,
  1309. ]
  1310. flatten_fn = default_flatten_fn
  1311. unflatten_fn = default_unflatten_fn
  1312. serialized_type_name = cls.__module__ + "." + cls.__qualname__
  1313. def to_dumpable_context(context):
  1314. keys, *_ = context
  1315. return json.dumps([keys, *([None] * len(_))])
  1316. def from_dumpable_context(dumpable):
  1317. s = json.loads(dumpable)
  1318. s[1] = PrototypeModule(torch.nn.Module())
  1319. return s
  1320. _register_pytree_node(
  1321. cls,
  1322. flatten_fn,
  1323. unflatten_fn,
  1324. serialized_type_name=serialized_type_name,
  1325. flatten_with_keys_fn=default_flatten_fn_with_keys,
  1326. to_dumpable_context=to_dumpable_context,
  1327. from_dumpable_context=from_dumpable_context,
  1328. )
  1329. def default_flatten_fn_spec(obj, spec) -> list[Any]:
  1330. flats, context = flatten_fn(obj)
  1331. if context != spec.context:
  1332. raise AssertionError(f"context mismatch: {context} != {spec.context}")
  1333. return flats
  1334. register_pytree_flatten_spec(
  1335. cls,
  1336. default_flatten_fn_spec,
  1337. )
  1338. def deregister_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None:
  1339. _deregister_pytree_node(cls)
  1340. _deregister_pytree_flatten_spec(cls)
  1341. def _sync_state(src, dst):
  1342. if not isinstance(src, torch.nn.Module):
  1343. raise AssertionError(f"Expected {src} to be a nn.Module")
  1344. if not isinstance(dst, torch.nn.Module):
  1345. raise AssertionError(f"Expected {dst} to be a nn.Module")
  1346. # Share state (params, buffers) between modules.
  1347. # This ensures that state mutations are visible across them.
  1348. # Since tensor constants are not mutable, copying (without sharing) is OK.
  1349. # Also, primitive constants are specialized, so copying (without sharing) is OK.
  1350. dst._parameters = src._parameters
  1351. dst._buffers = src._buffers
  1352. def sync_state(*wrapped_method_modules):
  1353. """
  1354. Sync state between exported modules corresponding to wrapped methods.
  1355. This might be necessary after serializing/deserializing due to copying.
  1356. """
  1357. if wrapped_method_modules:
  1358. m, *other_ms = wrapped_method_modules
  1359. for other_m in other_ms:
  1360. _sync_state(m, other_m)
  1361. class _WrappedMethod(torch.nn.Module):
  1362. def __init__(self, method):
  1363. super().__init__()
  1364. # share state of method's self module
  1365. _sync_state(method.__self__, self)
  1366. # redirect forward to method
  1367. self.forward = method
  1368. def wrap_method(method):
  1369. """
  1370. Wrap a method as a module so that it can be exported.
  1371. The wrapped module's forward points to the method, and
  1372. the method's original module state is shared.
  1373. """
  1374. if not ismethod(method):
  1375. raise AssertionError(f"Expected {method} to be a method")
  1376. return _WrappedMethod(method)