utils.py 56 KB

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