graph.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  1. # mypy: allow-untyped-defs
  2. import builtins
  3. import contextlib
  4. import copy
  5. import enum
  6. import functools
  7. import inspect
  8. import keyword
  9. import logging
  10. import math
  11. import os
  12. import pprint
  13. import re
  14. import types
  15. import typing
  16. import warnings
  17. from collections import defaultdict
  18. from collections.abc import Callable, Iterable, Iterator
  19. from contextlib import contextmanager
  20. from dataclasses import dataclass
  21. from typing import Any, Literal, NamedTuple, Optional, TYPE_CHECKING
  22. import torch
  23. import torch.utils._pytree as pytree
  24. from torch._C import _fx_map_arg as map_arg, _NodeIter
  25. from torch._library.opaque_object import get_opaque_obj_repr, is_opaque_value_type
  26. from torch.utils._dtype_abbrs import dtype_abbrs
  27. from . import _pytree as fx_pytree
  28. from ._compatibility import compatibility
  29. from .immutable_collections import immutable_dict
  30. from .node import _get_qualified_name, _type_repr, Argument, Node, Target
  31. log = logging.getLogger(__name__)
  32. __all__ = ["PythonCode", "CodeGen", "Graph"]
  33. if TYPE_CHECKING:
  34. from ._symbolic_trace import Tracer # noqa: F401
  35. from .graph_module import GraphModule # noqa: F401
  36. # Mapping of builtins to their `typing` equivalent.
  37. # (PEP585: See D68459095 test plan)
  38. _origin_type_map = {
  39. list: typing.List, # noqa: UP006
  40. dict: typing.Dict, # noqa: UP006
  41. set: typing.Set, # noqa: UP006
  42. frozenset: typing.FrozenSet, # noqa: UP006
  43. tuple: typing.Tuple, # noqa: UP006
  44. }
  45. _legal_ops = dict.fromkeys(
  46. ["call_function", "call_method", "get_attr", "call_module", "placeholder", "output"]
  47. )
  48. # Signature for functions thattransforms the body (`list[str]`) of the
  49. # generated code
  50. TransformCodeFunc = Callable[[list[str]], list[str]]
  51. class _CustomBuiltin(NamedTuple):
  52. """Additional objs that we add to every graph's globals.
  53. The repr() for some standard library objects is not valid Python code without
  54. an import. For common objects of this sort, we bundle them in the globals of
  55. every FX graph.
  56. """
  57. # How to import this object from the standard library.
  58. import_str: str
  59. # The actual object, produced from that import string.
  60. obj: Any
  61. # Combined dict of disallowed variable names so we can check with one lookup
  62. _illegal_names = {k: object() for k in keyword.kwlist}
  63. _illegal_names.update(builtins.__dict__) # can't shadow a builtin name
  64. _custom_builtins: dict[str, _CustomBuiltin] = {}
  65. def _register_custom_builtin(name: str, import_str: str, obj: Any):
  66. _custom_builtins[name] = _CustomBuiltin(import_str, obj)
  67. _illegal_names[name] = obj
  68. _register_custom_builtin("inf", "from math import inf", math.inf)
  69. _register_custom_builtin("nan", "from math import nan", math.nan)
  70. _register_custom_builtin("NoneType", "NoneType = type(None)", type(None))
  71. _register_custom_builtin("torch", "import torch", torch)
  72. _register_custom_builtin("device", "from torch import device", torch.device)
  73. _register_custom_builtin("fx_pytree", "import torch.fx._pytree as fx_pytree", fx_pytree)
  74. _register_custom_builtin("pytree", "import torch.utils._pytree as pytree", pytree)
  75. def _is_magic(x: str) -> bool:
  76. return x.startswith("__") and x.endswith("__")
  77. def _snake_case(s: str) -> str:
  78. """
  79. Transforms the given string ``s`` to a Python-style variable name
  80. Examples:
  81. ``mod.snake_case`` -> ``mod.snake_case``
  82. ``mod.pascalCase``-> ``mod.pascal_case``
  83. ``mod.ALL_CAPS`` -> ``mod.all_caps``
  84. """
  85. return _snake_case_sub(s).lower()
  86. # Replace occurrences where a lowercase letter is followed by an uppercase letter
  87. _snake_case_sub = functools.partial(re.compile(r"(?<=[a-z])([A-Z])").sub, r"_\1")
  88. # Find chars that can't be in a Python identifier
  89. _illegal_char_regex = re.compile("[^0-9a-zA-Z_]+")
  90. # Combined check for variable names:
  91. # 1) Checks name is not empty
  92. # 2) Checks first character is not a digit
  93. # 3) Checks name has no illegal characters (_illegal_char_regex)
  94. # 3) Splits off the number suffix (if present)
  95. _name_regex = re.compile(r"^([a-zA-Z_][0-9a-zA-Z_]*?)(?:_(\d+))?$")
  96. # starts with torch but does not start with torch._dynamo. or torch._inductor.
  97. _torch_but_not_dynamo = re.compile(
  98. r"^torch(?:\.(?!_dynamo\.|_inductor\.)[^.]+)*$"
  99. ).fullmatch
  100. def _is_from_torch(obj: Any) -> bool:
  101. module_name = getattr(obj, "__module__", None)
  102. if module_name is not None:
  103. return _torch_but_not_dynamo(module_name) is not None
  104. name = getattr(obj, "__name__", None)
  105. # exclude torch because torch.torch.torch.torch works. idk mang
  106. if name is not None and name != "torch":
  107. for guess in [torch, torch.nn.functional]:
  108. if getattr(guess, name, None) is obj:
  109. return True
  110. return False
  111. class _Namespace:
  112. """A context for associating names uniquely with objects.
  113. The following invariants are enforced:
  114. - Each object gets a single name.
  115. - Each name is unique within a given namespace.
  116. - Names generated do not shadow builtins, unless the object is indeed that builtin.
  117. """
  118. def __init__(self):
  119. self._obj_to_name: dict[Any, str] = {}
  120. self._used_names: set[str] = set()
  121. self._base_count: dict[str, int] = {}
  122. def create_name(self, candidate: str, obj: Optional[Any]) -> str:
  123. """Create a unique name.
  124. Arguments:
  125. candidate: used as the basis for the unique name, relevant to the user.
  126. obj: If not None, an object that will be associated with the unique name.
  127. """
  128. if obj is not None and obj in self._obj_to_name:
  129. return self._obj_to_name[obj]
  130. # optimistically check if candidate is already a valid name
  131. match = _name_regex.match(candidate)
  132. if match is None:
  133. # delete all characters that are illegal in a Python identifier
  134. candidate = _illegal_char_regex.sub("_", candidate)
  135. if not candidate:
  136. candidate = "_unnamed"
  137. if candidate[0].isdigit():
  138. candidate = f"_{candidate}"
  139. match = _name_regex.match(candidate)
  140. if match is None:
  141. raise AssertionError(
  142. f"Name regex failed to match candidate: {candidate}"
  143. )
  144. base, num = match.group(1, 2)
  145. if num is None or candidate in self._used_names:
  146. num = self._base_count.get(candidate, 0)
  147. if _illegal_names.get(candidate, obj) is not obj:
  148. num += 1
  149. candidate = f"{base}_{num}"
  150. # assume illegal names don't end in _\d so no need to check again
  151. else:
  152. num = int(num)
  153. while candidate in self._used_names:
  154. num += 1
  155. candidate = f"{base}_{num}"
  156. self._used_names.add(candidate)
  157. self._base_count[base] = num
  158. if obj is not None:
  159. self._obj_to_name[obj] = candidate
  160. return candidate
  161. def associate_name_with_obj(self, name: str, obj: Any):
  162. """Associate a unique name with an object.
  163. Neither `name` nor `obj` should be associated already.
  164. """
  165. maybe_existing = self._obj_to_name.setdefault(obj, name)
  166. if maybe_existing is not name:
  167. raise AssertionError("obj is already associated")
  168. def _rename_object(self, obj: Any, name: str):
  169. if obj not in self._obj_to_name:
  170. raise AssertionError(f"Object {obj} is not in _obj_to_name")
  171. self._obj_to_name[obj] = name
  172. self._used_names.add(name)
  173. @compatibility(is_backward_compatible=True)
  174. @dataclass
  175. class PythonCode:
  176. """
  177. Represents all the information necessary to exec or save a graph as Python code.
  178. """
  179. # Python source code for the forward function definition.
  180. src: str
  181. # Values in global scope during execution of `src_def`.
  182. globals: dict[str, Any]
  183. # Optional mapping from the forward function's line number to
  184. # node index. Line number starts at the prologue (i.e. forward()).
  185. _lineno_map: Optional[dict[int, Optional[int]]]
  186. # The line number of prologue in fn_code
  187. _prologue_start: int = 0
  188. def _format_target(base: str, target: str) -> str:
  189. elems = target.split(".")
  190. r = base
  191. for e in elems:
  192. if not e.isidentifier():
  193. r = f'getattr({r}, "{e}")'
  194. else:
  195. r = f"{r}.{e}"
  196. return r
  197. class _InsertPoint:
  198. def __init__(self, graph, new_insert):
  199. self.graph = graph
  200. self.orig_insert, graph._insert = graph._insert, new_insert
  201. def __enter__(self):
  202. pass
  203. def __exit__(self, type, value, tb):
  204. self.graph._insert = self.orig_insert
  205. class _node_list:
  206. def __init__(self, graph: "Graph", direction: Literal["_prev", "_next"] = "_next"):
  207. if direction not in ("_next", "_prev"):
  208. raise AssertionError(
  209. f"direction must be '_next' or '_prev', got {direction}"
  210. )
  211. self.graph = graph
  212. self.direction = direction
  213. def __len__(self):
  214. return self.graph._len
  215. def __iter__(self):
  216. return _NodeIter(self.graph._root, self.direction == "_prev")
  217. def __reversed__(self):
  218. return _node_list(self.graph, "_next" if self.direction == "_prev" else "_prev")
  219. class _PyTreeInfo(NamedTuple):
  220. """
  221. Contains extra info stored when we're using Pytrees
  222. """
  223. orig_args: list[str]
  224. in_spec: pytree.TreeSpec
  225. out_spec: Optional[pytree.TreeSpec]
  226. @dataclass(frozen=True)
  227. class _ParsedStackTrace:
  228. """
  229. Represents the top-most frame of a parsed stack trace
  230. """
  231. file: str
  232. lineno: str
  233. name: str
  234. code: str
  235. def get_summary_str(self):
  236. return f"File: {self.file}:{self.lineno} in {self.name}, code: {self.code}"
  237. # get File:lineno code from stack_trace
  238. def _parse_stack_trace(
  239. stack_trace: str, filter_fn: Optional[Callable[[str, str, str], bool]] = None
  240. ):
  241. if stack_trace is None:
  242. return None
  243. pattern = re.compile(r"^File \"(.+)\", line (\d+), in (.+)$")
  244. lines = stack_trace.strip().split("\n")
  245. # stacktrace should have innermost frame last, so we
  246. # iterate backwards to find the first line that starts
  247. # with 'File '
  248. for idx in range(len(lines) - 2, -1, -1):
  249. line = lines[idx].strip()
  250. matches = pattern.match(line)
  251. if matches:
  252. file = matches.group(1)
  253. lineno = matches.group(2)
  254. name = matches.group(3)
  255. # next line should be the code
  256. code = lines[idx + 1].strip()
  257. if filter_fn and not filter_fn(file, name, code):
  258. continue
  259. return _ParsedStackTrace(file, lineno, name, code)
  260. return None
  261. @compatibility(is_backward_compatible=False)
  262. class CodeGen:
  263. # This is an override hook so we can customize the SymNode printer.
  264. _sym_repr: Callable[["torch.types.PySymType"], str] = lambda x: repr(x)
  265. def __init__(self):
  266. self._body_transformer: Optional[TransformCodeFunc] = None
  267. self._func_name: str = "forward"
  268. def _format_multiline_args(self, args: list[str]) -> str:
  269. """Helper to format function arguments in expanded multiline format."""
  270. return "".join(self._format_single_arg(arg) for arg in args)
  271. def _format_single_arg(self, arg: str) -> str:
  272. """Helper to format a single argument with optional comment."""
  273. if "#" in arg:
  274. arg_part, comment_part = arg.split("#", 1)
  275. return f" {arg_part.rstrip()}, # {comment_part.lstrip()}\n"
  276. else:
  277. return f" {arg},\n"
  278. def _get_delimiters(self, container) -> tuple[str, str]:
  279. """Helper to get opening and closing delimiters for containers."""
  280. return ("(", ")") if isinstance(container, tuple) else ("[", "]")
  281. def _format_multiline_container(self, items, descs=None, prefix="") -> str:
  282. """Helper to format containers (lists/tuples) in multiline format."""
  283. ldelim, rdelim = self._get_delimiters(items)
  284. desc_trailers = self._get_desc_trailers(items, descs)
  285. return (
  286. f"{prefix}{ldelim}\n"
  287. + "".join(
  288. f" {item},{trailer}\n" for item, trailer in zip(items, desc_trailers)
  289. )
  290. + f"{rdelim}"
  291. )
  292. def _get_desc_trailers(self, items, descs):
  293. """Helper to generate description trailers for items."""
  294. if descs is None:
  295. return [""] * len(items)
  296. return [f" # {desc}" for desc in descs]
  297. def _call_method_with_signature_check(self, method, *args, **kwargs):
  298. """Helper to call a method with optional parameters based on signature."""
  299. sig = inspect.signature(method)
  300. # Filter kwargs to only include parameters that exist in the method signature
  301. filtered_kwargs = {k: v for k, v in kwargs.items() if k in sig.parameters}
  302. return method(*args, **filtered_kwargs)
  303. def gen_fn_def(
  304. self,
  305. free_vars: list[str],
  306. maybe_return_annotation: str,
  307. *,
  308. expanded_def: bool = False,
  309. ) -> str:
  310. """
  311. Given the free variables and a return annotation, generates the beginning of the FX function.
  312. By default, `gen_fn_def(['a', 'b'], '') == 'def {self._func_name}(a, b):'`
  313. """
  314. # If the original function didn't have self as its first argument, we
  315. # would have added it.
  316. if len(free_vars) == 0 or free_vars[0] != "self":
  317. free_vars.insert(0, "self")
  318. if expanded_def:
  319. args_formatted = self._format_multiline_args(free_vars)
  320. return (
  321. f"def {self._func_name}(\n{args_formatted}){maybe_return_annotation}:"
  322. )
  323. else:
  324. return f"def {self._func_name}({', '.join(free_vars)}){maybe_return_annotation}:"
  325. def generate_output(
  326. self, output_args: Argument, *, descs: Optional[Any] = None
  327. ) -> str:
  328. """
  329. Given the output arguments, generates the return statement of the FX function.
  330. Note: The returned statement should not be indented.
  331. """
  332. if descs is not None and isinstance(output_args, (list, tuple)):
  333. return self._format_multiline_container(output_args, descs, "return ")
  334. else:
  335. return f"return {repr(output_args)}"
  336. def process_inputs(self, *args: Any) -> Any:
  337. """
  338. Transforms the inputs so that the graph can take them as arguments, as
  339. non-default codegen may result in the inputs to the function being
  340. different from the inputs to the graph.
  341. If the graph was directly runnable, this invariant should hold true
  342. `f.graph.process_outputs(f.graph(*f.graph.process_inputs(*inputs))) == f(*inputs)`
  343. """
  344. return args
  345. def process_outputs(self, outputs: Any) -> Any:
  346. """
  347. Transforms the outputs of the graph to be identical to the codegen.
  348. See ``process_inputs`` for more details.
  349. """
  350. return outputs
  351. def additional_globals(self) -> list[tuple[str, Any]]:
  352. """
  353. If your codegen uses extra global values, add tuples of (identifier,reference to the value) here.
  354. For example, return ['List', typing.List] if you need ``List`` in the global context.
  355. """
  356. return []
  357. def _gen_python_code(
  358. self,
  359. nodes,
  360. root_module: str,
  361. namespace: _Namespace,
  362. *,
  363. verbose: bool = False,
  364. include_stride: bool = False,
  365. include_device: bool = False,
  366. colored: bool = False,
  367. # Render each argument on its own line
  368. expanded_def: bool = False,
  369. record_func: bool = False,
  370. additional_meta: Optional[list[str]] = None,
  371. ) -> PythonCode:
  372. free_vars: list[str] = []
  373. body: list[str] = []
  374. globals_: dict[str, Any] = {}
  375. wrapped_fns: dict[str, None] = {}
  376. # Wrap string in list to pass by reference
  377. maybe_return_annotation: list[str] = [""]
  378. include_stride = include_stride or (
  379. os.environ.get("FX_GRAPH_SHOW_STRIDE", "0") == "1"
  380. )
  381. include_device = include_device or (
  382. os.environ.get("FX_GRAPH_SHOW_DEVICE", "0") == "1"
  383. )
  384. include_meta = os.environ.get("FX_GRAPH_SHOW_META", "0") == "1"
  385. def add_global(name_hint: str, obj: Any):
  386. """Add an obj to be tracked as a global.
  387. We call this for names that reference objects external to the
  388. Graph, like functions or types.
  389. Returns: the global name that should be used to reference 'obj' in generated source.
  390. """
  391. if (
  392. _is_from_torch(obj) and obj != torch.device
  393. ): # to support registering torch.device
  394. # HACK: workaround for how torch custom ops are registered. We
  395. # can't import them like normal modules so they must retain their
  396. # fully qualified name.
  397. return _get_qualified_name(obj)
  398. # normalize the name hint to get a proper identifier
  399. global_name = namespace.create_name(name_hint, obj)
  400. if global_name in globals_:
  401. if globals_[global_name] != obj:
  402. raise AssertionError(
  403. f"Global name {global_name} already assigned to different object"
  404. )
  405. return global_name
  406. globals_[global_name] = obj
  407. return global_name
  408. # Pre-fill the globals table with registered builtins.
  409. for name, (_, obj) in _custom_builtins.items():
  410. add_global(name, obj)
  411. def type_repr(o: Any):
  412. if o == ():
  413. # Empty tuple is used for empty tuple type annotation Tuple[()]
  414. return "()"
  415. typename = _type_repr(o)
  416. if isinstance(o, types.UnionType) and "|" in typename:
  417. # str | int
  418. args = [type_repr(arg) for arg in o.__args__]
  419. return "|".join(args)
  420. if origin_type := getattr(o, "__origin__", None):
  421. # list[...], typing.List[...], TensorType[...]
  422. if isinstance(o, typing._GenericAlias): # type: ignore[attr-defined]
  423. # This is a generic pre-PEP585 type, e.g. typing.List[torch.Tensor]
  424. origin_type = _origin_type_map.get(origin_type, origin_type)
  425. origin_typename = add_global(_type_repr(origin_type), origin_type)
  426. if hasattr(o, "__args__") and o.__args__:
  427. args = [type_repr(arg) for arg in o.__args__]
  428. return f"{origin_typename}[{','.join(args)}]"
  429. else:
  430. return origin_typename
  431. # Common case: this is a regular module name like 'foo.bar.baz'
  432. return add_global(typename, o)
  433. if colored:
  434. red = _color_fns["red"]
  435. dim_green = _color_fns["dim_green"]
  436. dim = _color_fns["dim"]
  437. dim_blue = _color_fns["dim_blue"]
  438. blue = _color_fns["blue"]
  439. else:
  440. red = _identity
  441. dim_green = _identity
  442. dim = _identity
  443. dim_blue = _identity
  444. blue = _identity
  445. def _get_repr(arg: Any) -> str:
  446. if isinstance(arg, Node): # first because common
  447. return repr(arg)
  448. elif isinstance(arg, tuple) and hasattr(arg, "_fields"):
  449. # Handle NamedTuples (if it has `_fields`) via add_global.
  450. qualified_name = _get_qualified_name(type(arg))
  451. global_name = add_global(qualified_name, type(arg))
  452. return f"{global_name}{repr(tuple(arg))}"
  453. elif isinstance(
  454. arg, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)
  455. ):
  456. qualified_name = _get_qualified_name(arg)
  457. global_name = add_global(qualified_name, arg)
  458. return f"{global_name}"
  459. elif isinstance(arg, enum.Enum):
  460. cls = arg.__class__
  461. clsname = add_global(cls.__name__, cls)
  462. return f"{clsname}.{arg.name}"
  463. elif isinstance(arg, torch.Tensor):
  464. size = list(arg.size())
  465. dtype = str(arg.dtype).split(".")[-1]
  466. return f"torch.Tensor(size={size}, dtype={dtype})"
  467. elif isinstance(arg, tuple):
  468. if len(arg) == 1:
  469. return f"({_get_repr(arg[0])},)"
  470. else:
  471. return "(" + ", ".join(_get_repr(a) for a in arg) + ")"
  472. elif isinstance(arg, list):
  473. return "[" + ", ".join(_get_repr(a) for a in arg) + "]"
  474. elif isinstance(arg, slice):
  475. return f"slice({_get_repr(arg.start)}, {_get_repr(arg.stop)}, {_get_repr(arg.step)})"
  476. elif is_opaque_value_type(type(arg)):
  477. obj_repr, opaque_types = get_opaque_obj_repr(arg)
  478. for n, t in opaque_types.items():
  479. add_global(n, t)
  480. return obj_repr
  481. else:
  482. return blue(repr(arg))
  483. def _format_args(
  484. args: tuple[Argument, ...], kwargs: dict[str, Argument]
  485. ) -> str:
  486. res = [_get_repr(a) for a in args]
  487. res.extend([f"{k} = {_get_repr(v)}" for k, v in kwargs.items()])
  488. return ", ".join(res)
  489. # Run through reverse nodes and record the first instance of a use
  490. # of a given node. This represents the *last* use of the node in the
  491. # execution order of the program, which we will use to free unused
  492. # values
  493. node_to_last_use: dict[Node, Node] = {}
  494. user_to_last_uses: dict[Node, list[Node]] = {}
  495. def register_last_uses(n: Node, user: Node):
  496. if n not in node_to_last_use:
  497. node_to_last_use[n] = user
  498. user_to_last_uses.setdefault(user, []).append(n)
  499. for node in reversed(nodes):
  500. for input_node in node._input_nodes:
  501. register_last_uses(input_node, node)
  502. def delete_unused_values(user: Node):
  503. """
  504. Delete values after their last use. This ensures that values that are
  505. not used in the remainder of the code are freed and the memory usage
  506. of the code is optimal.
  507. """
  508. if user.op == "placeholder":
  509. return
  510. if user.op == "output":
  511. body.append("\n")
  512. return
  513. nodes_to_delete = user_to_last_uses.get(user, [])
  514. if len(user.users.keys()) == 0:
  515. # This node is not used by any others. however it's also not
  516. # removed by DCE since side-effect. We want to free it's outputs
  517. # right after its execution done to save memory.
  518. nodes_to_delete.append(user)
  519. if len(nodes_to_delete):
  520. to_delete_str = " = ".join(
  521. [repr(n) for n in nodes_to_delete] + ["None"]
  522. )
  523. body.append(f"; {dim(to_delete_str)}\n")
  524. else:
  525. body.append("\n")
  526. prev_summary_str = None
  527. def append_stacktrace_summary(node: Node):
  528. """
  529. Append a summary of the stacktrace to the generated code. This is
  530. useful for debugging.
  531. """
  532. nonlocal prev_summary_str
  533. if node.op not in {"placeholder", "output"}:
  534. additional_meta_str = ""
  535. if additional_meta:
  536. parts = []
  537. for key in additional_meta:
  538. if key in node.meta:
  539. parts.append(f"{key}: {node.meta[key]}")
  540. if parts:
  541. additional_meta_str = f"# {', '.join(parts)} "
  542. annotation_str = ""
  543. annotation = node.meta.get("custom", {})
  544. annotation_trunc = {}
  545. if annotation:
  546. for key, value in annotation.items():
  547. value_str = str(value)
  548. if len(value_str) > 40:
  549. annotation_trunc[key] = value_str[:40] + "..."
  550. else:
  551. annotation_trunc[key] = value
  552. annotation_str = f" Annotation: {annotation_trunc}"
  553. stack_trace_str = "No stacktrace found for following nodes"
  554. if stack_trace := node.stack_trace:
  555. if parsed_stack_trace := _parse_stack_trace(stack_trace):
  556. stack_trace_str = parsed_stack_trace.get_summary_str()
  557. maybe_recompute_info = ""
  558. if hasattr(node, "meta") and node.meta:
  559. # recompute tags are generated by torch.compile and put in the joint graph.
  560. # These tags are load bearing enough that we want them to show up by default
  561. # in tlparse, when you run torch.compile.
  562. recompute = node.meta.get("recompute", None)
  563. ac_graph_id = node.meta.get("ac_graph_id", None)
  564. if recompute is not None and ac_graph_id is not None:
  565. maybe_recompute_info = (
  566. f" ac_graph_id: {str(ac_graph_id)} - {str(recompute.name)}"
  567. )
  568. elif recompute is not None:
  569. maybe_recompute_info = f" recompute: {str(recompute.name)}"
  570. elif ac_graph_id is not None:
  571. maybe_recompute_info = f" ac_graph_id: {str(ac_graph_id)}"
  572. summary_str = f"\n{dim(f'{additional_meta_str}#{annotation_str}{maybe_recompute_info} {stack_trace_str}')}\n"
  573. if summary_str != prev_summary_str:
  574. prev_summary_str = summary_str
  575. body.append(summary_str)
  576. def stringify_shape(shape: Iterable) -> str:
  577. return f"[{', '.join([str(x) for x in shape])}]"
  578. def emit_node(node: Node):
  579. maybe_type_annotation = (
  580. "" if node.type is None else f" : {type_repr(node.type)}"
  581. )
  582. maybe_comment = ""
  583. if verbose:
  584. # override annotation with more detailed information
  585. try:
  586. from torch.distributed.tensor._api import DTensor, DTensorSpec
  587. dtensorspec_format_shard_order_str = (
  588. DTensorSpec.format_shard_order_str
  589. )
  590. except ModuleNotFoundError:
  591. DTensor = None # type: ignore[assignment,misc]
  592. dtensorspec_format_shard_order_str = None
  593. from torch.fx.experimental.proxy_tensor import py_sym_types
  594. from torch.fx.passes.shape_prop import TensorMetadata
  595. meta_val = node.meta.get(
  596. "val",
  597. node.meta.get("tensor_meta", node.meta.get("example_value", None)),
  598. )
  599. def _tensor_annotation(t: torch.Tensor) -> str:
  600. stride = stringify_shape(t.stride()) if include_stride else ""
  601. device = f"{t.device}" if include_device else ""
  602. return (
  603. f"{red(dtype_abbrs[t.dtype])}"
  604. f"{blue(stringify_shape(t.shape))}"
  605. f"{dim_blue(stride)}"
  606. f"{dim_green(device)}"
  607. )
  608. # use string as annotation, to make it valid python code
  609. if isinstance(meta_val, torch.Tensor) and meta_val.layout not in (
  610. torch.sparse_csc,
  611. torch.sparse_csr,
  612. ):
  613. # Fake tensors cause tests to wobble, so do not custom print them.
  614. is_plain = type(meta_val) is torch.Tensor or isinstance(
  615. meta_val, torch._subclasses.FakeTensor
  616. )
  617. core = _tensor_annotation(meta_val)
  618. if is_plain:
  619. maybe_type_annotation = f': "{core}"'
  620. elif type(meta_val) is DTensor:
  621. if dtensorspec_format_shard_order_str is None:
  622. raise AssertionError(
  623. "dtensorspec_format_shard_order_str is None for DTensor"
  624. )
  625. dtensor_meta = dtensorspec_format_shard_order_str(
  626. meta_val._spec.placements, # type: ignore[attr-defined]
  627. meta_val._spec.shard_order, # type: ignore[attr-defined]
  628. )
  629. cls = meta_val.__class__.__name__
  630. maybe_type_annotation = (
  631. f': "{cls}({core}, {dim_green(dtensor_meta)})"'
  632. )
  633. else:
  634. cls = meta_val.__class__.__name__
  635. maybe_type_annotation = f': "{cls}({core})"'
  636. elif isinstance(meta_val, py_sym_types):
  637. val_str = CodeGen._sym_repr(meta_val)
  638. maybe_type_annotation = f': "Sym({val_str})"'
  639. elif isinstance(meta_val, TensorMetadata):
  640. maybe_type_annotation = f': "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}"'
  641. desc = None
  642. if expanded_def:
  643. desc = node.meta.get("desc", None)
  644. if desc is not None and node.op == "placeholder":
  645. maybe_comment += f" # {desc}"
  646. # output is handled specially
  647. if include_meta and hasattr(node, "meta") and node.meta:
  648. body.append('"""\n')
  649. for k, v in node.meta.items():
  650. # use str over repr since repr is susceptible to sympy
  651. # errors such as "cannot determine truth value of Relational"
  652. # Pretty print the high-level dict with str() for values
  653. body.append(
  654. f"{k}: {pprint.pformat(str(v), width=80, compact=True)}\n"
  655. )
  656. body.append('"""\n')
  657. if node.op == "placeholder":
  658. if not isinstance(node.target, str):
  659. raise AssertionError(
  660. f"Expected node.target to be str, got {type(node.target)}"
  661. )
  662. maybe_default_arg = (
  663. "" if not node.args else f" = {_get_repr(node.args[0])}"
  664. )
  665. free_vars.append(
  666. f"{node.target}{maybe_type_annotation}{maybe_default_arg}{maybe_comment}"
  667. )
  668. raw_name = node.target.replace("*", "")
  669. if raw_name != repr(node):
  670. body.append(f"{repr(node)} = {raw_name}\n")
  671. return
  672. elif node.op == "call_method":
  673. if not isinstance(node.target, str):
  674. raise AssertionError(
  675. f"Expected node.target to be str for call_method, got {type(node.target)}"
  676. )
  677. body.append(
  678. f"{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.target)}"
  679. f"({_format_args(node.args[1:], node.kwargs)})"
  680. )
  681. return
  682. elif node.op == "call_function":
  683. if not callable(node.target):
  684. raise AssertionError(
  685. f"Expected node.target to be callable, got {type(node.target)}"
  686. )
  687. # pretty print operators
  688. if (
  689. getattr(node.target, "__module__", "") == "_operator"
  690. and node.target.__name__ in magic_methods
  691. ):
  692. if not isinstance(node.args, tuple):
  693. raise AssertionError(
  694. f"Expected node.args to be tuple, got {type(node.args)}"
  695. )
  696. body.append(
  697. f"{repr(node)}{maybe_type_annotation} = "
  698. f"{magic_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}"
  699. )
  700. return
  701. # pretty print inplace operators; required for jit.script to work properly
  702. # not currently supported in normal FX graphs, but generated by torchdynamo
  703. if (
  704. getattr(node.target, "__module__", "") == "_operator"
  705. and node.target.__name__ in inplace_methods
  706. ):
  707. body.append(
  708. f"{inplace_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}; "
  709. f"{repr(node)}{maybe_type_annotation} = {_get_repr(node.args[0])}"
  710. )
  711. return
  712. qualified_name = _get_qualified_name(node.target)
  713. global_name = add_global(qualified_name, node.target)
  714. # special case for getattr: node.args could be 2-argument or 3-argument
  715. # 2-argument: attribute access; 3-argument: fall through to attrib function call with default value
  716. if (
  717. global_name == "getattr"
  718. and isinstance(node.args, tuple)
  719. and isinstance(node.args[1], str)
  720. and node.args[1].isidentifier()
  721. and len(node.args) == 2
  722. ):
  723. body.append(
  724. f"{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.args[1])}"
  725. )
  726. return
  727. body.append(
  728. f"{repr(node)}{maybe_type_annotation} = {global_name}({_format_args(node.args, node.kwargs)})"
  729. )
  730. if node.meta.get("is_wrapped", False):
  731. wrapped_fns.setdefault(global_name)
  732. return
  733. elif node.op == "call_module":
  734. if not isinstance(node.target, str):
  735. raise AssertionError(
  736. f"Expected node.target to be str for call_module, got {type(node.target)}"
  737. )
  738. body.append(
  739. f"{repr(node)}{maybe_type_annotation} = "
  740. f"{_format_target(root_module, node.target)}({_format_args(node.args, node.kwargs)})"
  741. )
  742. return
  743. elif node.op == "get_attr":
  744. if not isinstance(node.target, str):
  745. raise AssertionError(
  746. f"Expected node.target to be str for get_attr, got {type(node.target)}"
  747. )
  748. body.append(
  749. f"{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}"
  750. )
  751. return
  752. elif node.op == "output":
  753. if node.type is not None:
  754. maybe_return_annotation[0] = f" -> {type_repr(node.type)}"
  755. body.append(
  756. self._call_method_with_signature_check(
  757. self.generate_output,
  758. node.args[0],
  759. descs=desc if expanded_def else None,
  760. )
  761. )
  762. return
  763. raise NotImplementedError(f"node: {node.op} {node.target}")
  764. if record_func:
  765. body.append(
  766. "_rf = torch._C._profiler._RecordFunctionFast('## ENTER_GRAPH_PLACEHOLDER_KEY ##'); _rf.__enter__()\n"
  767. )
  768. for i, node in enumerate(nodes):
  769. # NOTE: emit_node does not emit a string with newline. It depends
  770. # on delete_unused_values to append one
  771. if verbose:
  772. append_stacktrace_summary(node)
  773. # emit a counter comment to keep track of
  774. # node index, which will be deleted later
  775. # after going through _body_transformer
  776. body.append(f"# COUNTER: {i}\n")
  777. do_record = record_func and node.op in (
  778. "call_function",
  779. "call_method",
  780. "call_module",
  781. )
  782. if do_record:
  783. # The double hash ## convention is used by post-processing to find the fx markers
  784. body.append(
  785. f"_rf_{node.name} = torch._C._profiler._RecordFunctionFast('## {i} ##'); _rf_{node.name}.__enter__()\n"
  786. )
  787. emit_node(node)
  788. delete_unused_values(node)
  789. if do_record:
  790. body.append(f"_rf_{node.name}.__exit__(None, None, None)\n")
  791. if record_func:
  792. body.append("_rf.__exit__(None, None, None)\n")
  793. if len(body) == 0:
  794. # If the Graph has no non-placeholder nodes, no lines for the body
  795. # have been emitted. To continue to have valid Python code, emit a
  796. # single pass statement
  797. body.append("pass\n")
  798. if len(wrapped_fns) > 0:
  799. wrap_name = add_global("wrap", torch.fx.wrap)
  800. wrap_stmts = "\n".join([f'{wrap_name}("{name}")' for name in wrapped_fns])
  801. else:
  802. wrap_stmts = ""
  803. if self._body_transformer:
  804. body = self._body_transformer(body)
  805. for name, value in self.additional_globals():
  806. add_global(name, value)
  807. prologue = self._call_method_with_signature_check(
  808. self.gen_fn_def,
  809. free_vars,
  810. maybe_return_annotation[0],
  811. expanded_def=expanded_def,
  812. )
  813. # remove counter and generate lineno to node index mapping
  814. lineno_map: dict[int, Optional[int]] = {}
  815. prologue_len = prologue.count("\n") + 1
  816. new_lines: list[str] = []
  817. cur_idx = None
  818. for line in "".join(body).split("\n"):
  819. counter = _counter_regexp.search(line)
  820. if counter is not None:
  821. cur_idx = int(counter.group(1))
  822. else:
  823. lineno_map[len(new_lines) + prologue_len] = cur_idx
  824. new_lines.append(line)
  825. code = "\n".join(new_lines).lstrip("\n")
  826. code = "\n".join(" " + line for line in code.split("\n"))
  827. fn_code = f"""
  828. {wrap_stmts}
  829. {prologue}
  830. {code}"""
  831. # The +4 accounts for the empty lines before prologue in fn_code
  832. prologue_start = wrap_stmts.count("\n") + 4
  833. return PythonCode(
  834. fn_code,
  835. globals_,
  836. _lineno_map=lineno_map,
  837. _prologue_start=prologue_start,
  838. )
  839. # Ideally, we'd like to refactor all of the pytree logic into this codegen
  840. # class. Unfortunately, there are 3 areas we currently need extra logic in FX.
  841. # 1. In the initial symbolic trace, the pytree logic is tied up with `concrete_args`.
  842. # 2. In the FX graph, we need to access 2 attributes - in_spec and out_spec.
  843. # Since we can't access .graph within the FX forward, we need to copy the attribute to the module.
  844. # 3. We currently can't register the pytree imports with `add_global` - not sure why.
  845. class _BoxedCodeGen(CodeGen):
  846. """
  847. CodeGen subclass that generates code using the "boxed" calling convention.
  848. The boxed calling convention takes a single list argument and clears it
  849. after extracting the arguments, which allows for early deallocation of
  850. input tensors.
  851. """
  852. def gen_fn_def(
  853. self, free_vars, maybe_return_annotation, *, expanded_def: bool = False
  854. ):
  855. """
  856. Generate function definition for boxed calling convention.
  857. Instead of taking individual arguments, the generated function takes
  858. a single 'args_list' parameter, extracts placeholder values from it,
  859. and clears the list.
  860. """
  861. # Generate the function signature with args_list parameter
  862. fn_def = f"def {self._func_name}(self, args_list){maybe_return_annotation}:"
  863. if free_vars:
  864. # This is horribly manual but we don't get the "raw" free vars
  865. # without a bigger refactor.
  866. placeholder_vars = [
  867. v.split(":")[0].split("=")[0].strip() for v in free_vars if v != "self"
  868. ]
  869. if placeholder_vars:
  870. fn_def += "\n args_iter = iter(args_list)"
  871. for var in placeholder_vars:
  872. fn_def += f"\n {var} = next(args_iter)"
  873. fn_def += "\n args_list.clear()"
  874. return fn_def
  875. class _PyTreeCodeGen(CodeGen):
  876. def __init__(self, pytree_info: _PyTreeInfo):
  877. super().__init__()
  878. self.pytree_info: _PyTreeInfo = pytree_info
  879. def process_inputs(self, *inputs: Any) -> Any:
  880. flat_args = pytree.arg_tree_leaves(*inputs)
  881. return flat_args
  882. def process_outputs(self, out: Any) -> Any:
  883. if self.pytree_info is None or self.pytree_info.out_spec is None:
  884. return out
  885. if not isinstance(out, (list, tuple)):
  886. out = [out]
  887. if self.pytree_info.out_spec is None:
  888. raise AssertionError("pytree_info.out_spec is None")
  889. return pytree.tree_unflatten(out, self.pytree_info.out_spec)
  890. def _format_annotations(self, free_vars: list[str], expanded_def: bool) -> str:
  891. """Helper to format annotations for variables in pytree codegen."""
  892. if not free_vars:
  893. return ""
  894. has_annotation = [x for x in free_vars if ":" in x]
  895. if not has_annotation:
  896. return ""
  897. if expanded_def:
  898. return "\n " + "\n ".join(has_annotation)
  899. else:
  900. return "\n " + "".join(x + "; " for x in has_annotation) + "\n"
  901. def gen_var_bindings(self, fn_args, free_vars, expanded_def) -> str:
  902. in_spec = self.pytree_info.in_spec
  903. # when kwargs is present, in_spec is tuple(args, kwargs)
  904. has_args_kwargs_tuple = (
  905. in_spec.type is tuple
  906. and in_spec.num_children == 2
  907. and in_spec.child(0).type is tuple
  908. and in_spec.child(1).type is dict
  909. )
  910. fn_kwargs = "{}"
  911. fn_signature = f"[{', '.join(fn_args)}], self._in_spec"
  912. if has_args_kwargs_tuple:
  913. count_args = in_spec.child(0).num_children
  914. fn_args = self.pytree_info.orig_args[:count_args]
  915. fn_kwargs = (
  916. "{"
  917. + ", ".join(
  918. f"'{k}':{v}"
  919. for k, v in zip(
  920. in_spec.child(1).context,
  921. self.pytree_info.orig_args[count_args:],
  922. )
  923. )
  924. + "}"
  925. )
  926. fn_signature = f"([{', '.join(fn_args)}], {fn_kwargs}), self._in_spec"
  927. # in Python, `var1: annotation1, var2: annotation2 = function_call()` is invalid.
  928. # we need to split it to two lines:
  929. # one for annotation: `var1: annotation1; var2: annotation2;` (note the semicolon)
  930. # one for code: `var1, var2, = function_call()`
  931. without_annotation = [x.split(":")[0].split("#")[0] for x in free_vars]
  932. bindings = self._format_annotations(free_vars, expanded_def)
  933. bindings += f"""
  934. {", ".join(without_annotation)}, = fx_pytree.tree_flatten_spec({fn_signature})"""
  935. return bindings
  936. def gen_fn_def(
  937. self, free_vars, maybe_return_annotation, *, expanded_def: bool = False
  938. ):
  939. # Given a user function/model:
  940. # myargs = [myargs0, myargs1]
  941. # mykwargs = {'mykwargs0': ..., 'mykwargs1': ...}
  942. # def forward(self, mypos, *myargs, mykey=None, **mykwargs):
  943. #
  944. # The generated code flattens all keywords into positional arguments for `forward()`
  945. # e.g forward(self, mypos, myargs0, myargs1, mykey, mykwargs0, mykwargs1):
  946. #
  947. # Within `forward`, `tree_flatten_spec``still parses args and kwargs separately
  948. # e.g. tree_flatten_spec(([mypos, myargs0, myargs1],
  949. # {'mykey':mykey, 'mykwargs0':mykwargs0, 'mykwargs1':mykwargs1}),
  950. # self._in_spec)
  951. #
  952. # If the user function/model does not have keywords, the dict is suppressed from tree_flatten_spec
  953. # e.g. tree_flatten_spec([mypos, myargs0, myargs1]), self._in_spec)
  954. if self.pytree_info is None:
  955. return super().gen_fn_def(
  956. free_vars, maybe_return_annotation, expanded_def=expanded_def
  957. )
  958. fn_args = self.pytree_info.orig_args
  959. has_orig_self = (fn_args[0] == "self") if len(fn_args) > 0 else False
  960. if has_orig_self:
  961. free_vars.insert(0, "self")
  962. fn_definition = super().gen_fn_def(
  963. fn_args[:], maybe_return_annotation, expanded_def=expanded_def
  964. )
  965. if len(free_vars) > 0: # pytree has placeholders in it
  966. fn_definition += self.gen_var_bindings(fn_args, free_vars, expanded_def)
  967. return fn_definition
  968. def generate_output(self, output_args, *, descs: Optional[Any] = None):
  969. if self.pytree_info and self.pytree_info.out_spec:
  970. if descs is not None and isinstance(output_args, (list, tuple)):
  971. return (
  972. self._format_multiline_container(
  973. output_args, descs, "return pytree.tree_unflatten("
  974. )
  975. + ", self._out_spec)"
  976. )
  977. else:
  978. return (
  979. f"return pytree.tree_unflatten({repr(output_args)}, self._out_spec)"
  980. )
  981. else:
  982. return super().generate_output(output_args, descs=descs)
  983. class _ExportCodeGen(_PyTreeCodeGen):
  984. def __init__(
  985. self,
  986. pytree_info: _PyTreeInfo,
  987. in_shuffle_graph: "GraphModule",
  988. out_shuffle_graph: "GraphModule",
  989. tree_leaf_names: list[str],
  990. root: Optional[torch.nn.Module],
  991. ):
  992. super().__init__(pytree_info)
  993. self.in_shuffle_graph = in_shuffle_graph
  994. self.out_shuffle_graph = out_shuffle_graph
  995. self.tree_leaf_names = tree_leaf_names
  996. self.root = root
  997. def process_inputs(self, *inputs: Any) -> Any:
  998. flat_args = super().process_inputs(*inputs)
  999. if self.root is not None:
  1000. flat_args = (self.root, *flat_args)
  1001. self.flat_args = flat_args
  1002. return self.in_shuffle_graph(*flat_args)
  1003. def process_outputs(self, out: Any) -> Any:
  1004. flat_outs = self.out_shuffle_graph(*self.flat_args, *out)
  1005. del self.flat_args
  1006. ret = super().process_outputs(flat_outs)
  1007. return ret
  1008. def gen_fn_def(self, *args, **kwargs) -> str:
  1009. fn_def = super().gen_fn_def(*args, **kwargs)
  1010. return fn_def
  1011. def gen_var_bindings(self, fn_args, free_vars, expanded_def) -> str:
  1012. without_annotation = [x.split(":")[0].split("#")[0] for x in free_vars]
  1013. fn_signature: str = f"{', '.join(fn_args)}"
  1014. if self.root is not None:
  1015. fn_signature = f"self, {fn_signature}"
  1016. return f"""
  1017. {", ".join(self.tree_leaf_names)}, = pytree.tree_leaves(({fn_signature},))
  1018. {", ".join(without_annotation)}, = self._in_shuffle_graph({", ".join(self.tree_leaf_names)})"""
  1019. def generate_output(self, output_args, *args, **kwargs) -> str:
  1020. output = f"self._out_shuffle_graph({', '.join(self.tree_leaf_names)}, {', '.join([str(a) for a in output_args])})"
  1021. return f"return pytree.tree_unflatten({output}, self._out_spec)"
  1022. class _FindNodesLookupTable:
  1023. """
  1024. Side table for the graph for the purpose of doing fast queries
  1025. """
  1026. def __init__(self):
  1027. self.table: dict[tuple[str, Optional[Target]], dict[Node, None]] = defaultdict(
  1028. dict
  1029. )
  1030. def _key(self, node) -> tuple[str, Optional[Target]]:
  1031. return (node.op, node.target if node.op == "call_function" else None)
  1032. def __contains__(self, node) -> bool:
  1033. return node in self.table[self._key(node)]
  1034. def insert(self, node: Node) -> None:
  1035. self.table[self._key(node)][node] = None
  1036. def remove(self, node: Node) -> None:
  1037. self.table[self._key(node)].pop(node)
  1038. def find_nodes(self, *, op: str, target: Optional["Target"] = None):
  1039. if op == "call_function":
  1040. if target is None:
  1041. raise AssertionError("target must not be None for call_function op")
  1042. return [*self.table[(op, target)].keys()]
  1043. if target is None:
  1044. return [*self.table[(op, None)].keys()]
  1045. # op is call_method, get_attr, call_module
  1046. return [node for node in self.table[(op, None)] if node.target == target]
  1047. @compatibility(is_backward_compatible=True)
  1048. class Graph:
  1049. """
  1050. ``Graph`` is the main data structure used in the FX Intermediate Representation.
  1051. It consists of a series of ``Node`` s, each representing callsites (or other
  1052. syntactic constructs). The list of ``Node`` s, taken together, constitute a
  1053. valid Python function.
  1054. For example, the following code
  1055. .. code-block:: python
  1056. import torch
  1057. import torch.fx
  1058. class MyModule(torch.nn.Module):
  1059. def __init__(self):
  1060. super().__init__()
  1061. self.param = torch.nn.Parameter(torch.rand(3, 4))
  1062. self.linear = torch.nn.Linear(4, 5)
  1063. def forward(self, x):
  1064. return torch.topk(
  1065. torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3
  1066. )
  1067. m = MyModule()
  1068. gm = torch.fx.symbolic_trace(m)
  1069. Will produce the following Graph::
  1070. print(gm.graph)
  1071. .. code-block:: text
  1072. graph(x):
  1073. %linear_weight : [num_users=1] = self.linear.weight
  1074. %add_1 : [num_users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {})
  1075. %linear_1 : [num_users=1] = call_module[target=linear](args = (%add_1,), kwargs = {})
  1076. %relu_1 : [num_users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {})
  1077. %sum_1 : [num_users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1})
  1078. %topk_1 : [num_users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {})
  1079. return topk_1
  1080. For the semantics of operations represented in the ``Graph``, please see :class:`Node`.
  1081. """
  1082. @compatibility(is_backward_compatible=True)
  1083. def __init__(
  1084. self,
  1085. owning_module: Optional["GraphModule"] = None,
  1086. tracer_cls: Optional[type["Tracer"]] = None,
  1087. tracer_extras: Optional[dict[str, Any]] = None,
  1088. ):
  1089. """
  1090. Construct an empty Graph.
  1091. """
  1092. self._root: Node = Node(self, "", "root", "", (), {})
  1093. self._used_names: dict[str, int] = {} # base name -> number
  1094. self._insert = self._root.prepend
  1095. self._len = 0
  1096. self._graph_namespace = _Namespace()
  1097. self._owning_module = owning_module
  1098. self._tracer_cls = tracer_cls
  1099. self._tracer_extras = tracer_extras
  1100. self._codegen = CodeGen()
  1101. self._co_fields: dict[str, Any] = {}
  1102. self._find_nodes_lookup_table = _FindNodesLookupTable()
  1103. @property
  1104. def owning_module(self):
  1105. return self._owning_module
  1106. @owning_module.setter
  1107. def owning_module(self, mod: Optional["GraphModule"]):
  1108. self._owning_module = mod
  1109. @property
  1110. def nodes(self) -> _node_list:
  1111. """
  1112. Get the list of Nodes that constitute this Graph.
  1113. Note that this ``Node`` list representation is a doubly-linked list. Mutations
  1114. during iteration (e.g. delete a Node, add a Node) are safe.
  1115. Returns:
  1116. A doubly-linked list of Nodes. Note that ``reversed`` can be called on
  1117. this list to switch iteration order.
  1118. """
  1119. return _node_list(self)
  1120. @compatibility(is_backward_compatible=False)
  1121. def output_node(self) -> Node:
  1122. output_node = next(iter(reversed(self.nodes)))
  1123. if output_node.op != "output":
  1124. raise AssertionError(f"Expected output node, got op={output_node.op}")
  1125. return output_node
  1126. @compatibility(is_backward_compatible=False)
  1127. def find_nodes(
  1128. self, *, op: str, target: Optional["Target"] = None, sort: bool = True
  1129. ):
  1130. """
  1131. Allows for fast query of nodes
  1132. Args:
  1133. op (str): the name of the operation
  1134. target (Optional[Target]): the target of the node. For call_function,
  1135. the target is required. For other ops, the target is optional.
  1136. sort (bool): whether to return nodes in the order they appear on
  1137. on the graph.
  1138. Returns:
  1139. Iterable of nodes with the requested op and target.
  1140. """
  1141. node_list = self._find_nodes_lookup_table.find_nodes(op=op, target=target)
  1142. if sort:
  1143. return sorted(node_list)
  1144. return node_list
  1145. @compatibility(is_backward_compatible=True)
  1146. def graph_copy(
  1147. self, g: "Graph", val_map: dict[Node, Node], return_output_node=False
  1148. ) -> "Optional[Argument]":
  1149. """
  1150. Copy all nodes from a given graph into ``self``.
  1151. Args:
  1152. g (Graph): The source graph from which to copy Nodes.
  1153. val_map (Dict[Node, Node]): a dictionary that will be populated with a mapping
  1154. from nodes in ``g`` to nodes in ``self``. Note that ``val_map`` can be passed
  1155. in with values in it already to override copying of certain values.
  1156. Returns:
  1157. The value in ``self`` that is now equivalent to the output value in ``g``,
  1158. if ``g`` had an ``output`` node. ``None`` otherwise.
  1159. """
  1160. for node in g.nodes:
  1161. if node in val_map:
  1162. continue
  1163. if node.op == "output":
  1164. rv = map_arg(node.args[0], lambda n: val_map[n])
  1165. return rv if not return_output_node else (rv, node)
  1166. val_map[node] = self.node_copy(node, lambda n: val_map[n])
  1167. return None
  1168. def __deepcopy__(self, memo=None) -> "Graph":
  1169. """
  1170. Explicitly implement __deepcopy__ to prevent excessive recursion depth
  1171. from the default implementation. This uses graph_copy to copy the nodes
  1172. in an iterative way, rather than recursive. It also populates the
  1173. memoization table to prevent unnecessary copies (e.g. references to
  1174. nodes or other parts of the Graph from a custom GraphModule implementation.
  1175. """
  1176. memo = memo if memo else {}
  1177. g = Graph(tracer_cls=self._tracer_cls)
  1178. output_vals = g.graph_copy(self, val_map=memo, return_output_node=True)
  1179. g._codegen = copy.deepcopy(self._codegen)
  1180. if output_vals is not None:
  1181. if not isinstance(output_vals, tuple):
  1182. raise AssertionError(
  1183. f"Expected output_vals to be tuple, got {type(output_vals)}"
  1184. )
  1185. output_val, old_output_node = output_vals
  1186. new_output_node = g.output(
  1187. # pyrefly: ignore [bad-argument-type]
  1188. output_val,
  1189. type_expr=getattr(old_output_node, "type", None),
  1190. )
  1191. # pyrefly: ignore [missing-attribute]
  1192. new_output_node.meta = copy.copy(old_output_node.meta)
  1193. return g
  1194. @compatibility(is_backward_compatible=True)
  1195. def create_node(
  1196. self,
  1197. op: str,
  1198. target: "Target",
  1199. args: Optional[tuple["Argument", ...]] = None,
  1200. kwargs: Optional[dict[str, "Argument"]] = None,
  1201. name: Optional[str] = None,
  1202. type_expr: Optional[Any] = None,
  1203. ) -> Node:
  1204. """
  1205. Create a ``Node`` and add it to the ``Graph`` at the current insert-point.
  1206. Note that the current insert-point can be set via :meth:`Graph.inserting_before`
  1207. and :meth:`Graph.inserting_after`.
  1208. Args:
  1209. op (str): the opcode for this Node. One of 'call_function', 'call_method', 'get_attr',
  1210. 'call_module', 'placeholder', or 'output'. The semantics of these opcodes are
  1211. described in the ``Graph`` docstring.
  1212. args (Optional[Tuple[Argument, ...]]): is a tuple of arguments to this node.
  1213. kwargs (Optional[Dict[str, Argument]]): the kwargs of this Node
  1214. name (Optional[str]): an optional string name for the ``Node``.
  1215. This will influence the name of the value assigned to in the
  1216. Python generated code.
  1217. type_expr (Optional[Any]): an optional type annotation representing the
  1218. Python type the output of this node will have.
  1219. Returns:
  1220. The newly-created and inserted node.
  1221. """
  1222. # `target in _legal_ops` is checked in Node.__init__
  1223. if not args:
  1224. args = ()
  1225. else:
  1226. if not isinstance(args, tuple):
  1227. raise AssertionError(f"args must be a tuple, got {type(args)}")
  1228. if not kwargs:
  1229. kwargs = immutable_dict()
  1230. else:
  1231. if not isinstance(kwargs, dict):
  1232. raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
  1233. candidate = name if name is not None else self._target_to_str(target)
  1234. name = self._graph_namespace.create_name(candidate, None)
  1235. n = Node(self, name, op, target, args, kwargs, type_expr)
  1236. if (
  1237. self.owning_module is not None
  1238. and getattr(self.owning_module, "_create_node_hooks", None) is not None
  1239. ):
  1240. for f in self.owning_module._create_node_hooks:
  1241. f(n)
  1242. self._graph_namespace.associate_name_with_obj(name, n)
  1243. self._insert(n)
  1244. self._find_nodes_lookup_table.insert(n)
  1245. self._len += 1
  1246. return n
  1247. @compatibility(is_backward_compatible=False)
  1248. def process_inputs(self, *args):
  1249. """
  1250. Processes args so that they can be passed to the FX graph.
  1251. """
  1252. return self._codegen.process_inputs(*args)
  1253. @compatibility(is_backward_compatible=False)
  1254. def process_outputs(self, out):
  1255. return self._codegen.process_outputs(out)
  1256. @compatibility(is_backward_compatible=True)
  1257. def erase_node(self, to_erase: Node) -> None:
  1258. """
  1259. Erases a ``Node`` from the ``Graph``. Throws an exception if
  1260. there are still users of that node in the ``Graph``.
  1261. Args:
  1262. to_erase (Node): The ``Node`` to erase from the ``Graph``.
  1263. """
  1264. if len(to_erase.users) > 0:
  1265. raise RuntimeError(
  1266. f"Tried to erase Node {to_erase} but it still had {len(to_erase.users)} "
  1267. f"users in the graph: {to_erase.users}!"
  1268. )
  1269. if to_erase.graph != self:
  1270. raise RuntimeError(f"Attempting to remove {to_erase} from wrong graph!")
  1271. if to_erase._erased:
  1272. warnings.warn(f"erase_node({to_erase}) on an already erased node")
  1273. return
  1274. if (
  1275. self.owning_module is not None
  1276. and getattr(self.owning_module, "_erase_node_hooks", None) is not None
  1277. ):
  1278. for f in self.owning_module._erase_node_hooks:
  1279. f(to_erase)
  1280. self._find_nodes_lookup_table.remove(to_erase)
  1281. to_erase._remove_from_list()
  1282. to_erase._erased = True # iterators may retain handles to erased nodes
  1283. self._len -= 1
  1284. # Null out this Node's argument nodes so that the Nodes referred to
  1285. # can update their ``users`` accordingly
  1286. to_erase._update_args_kwargs(
  1287. map_arg(to_erase._args, lambda n: None),
  1288. map_arg(to_erase._kwargs, lambda n: None),
  1289. )
  1290. @compatibility(is_backward_compatible=True)
  1291. def inserting_before(self, n: Optional[Node] = None):
  1292. """Set the point at which create_node and companion methods will insert into the graph.
  1293. When used within a 'with' statement, this will temporary set the insert point and
  1294. then restore it when the with statement exits::
  1295. with g.inserting_before(n):
  1296. ... # inserting before node n
  1297. ... # insert point restored to what it was previously
  1298. g.inserting_before(n) # set the insert point permanently
  1299. Args:
  1300. n (Optional[Node]): The node before which to insert. If None this will insert before
  1301. the beginning of the entire graph.
  1302. Returns:
  1303. A resource manager that will restore the insert point on ``__exit__``.
  1304. """
  1305. if n is None:
  1306. return self.inserting_after(self._root)
  1307. if n.graph != self:
  1308. raise AssertionError("Node to insert before is not in graph.")
  1309. return _InsertPoint(self, n.prepend)
  1310. @compatibility(is_backward_compatible=True)
  1311. def inserting_after(self, n: Optional[Node] = None):
  1312. """Set the point at which create_node and companion methods will insert into the graph.
  1313. When used within a 'with' statement, this will temporary set the insert point and
  1314. then restore it when the with statement exits::
  1315. with g.inserting_after(n):
  1316. ... # inserting after node n
  1317. ... # insert point restored to what it was previously
  1318. g.inserting_after(n) # set the insert point permanently
  1319. Args:
  1320. n (Optional[Node]): The node before which to insert. If None this will insert after
  1321. the beginning of the entire graph.
  1322. Returns:
  1323. A resource manager that will restore the insert point on ``__exit__``.
  1324. """
  1325. if n is None:
  1326. return self.inserting_before(self._root)
  1327. if n.graph != self:
  1328. raise AssertionError("Node to insert after is not in graph.")
  1329. return _InsertPoint(self, n.append)
  1330. @compatibility(is_backward_compatible=True)
  1331. def placeholder(
  1332. self,
  1333. name: str,
  1334. type_expr: Optional[Any] = None,
  1335. default_value: Any = inspect.Signature.empty,
  1336. ) -> Node:
  1337. """
  1338. Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents
  1339. a function input.
  1340. Args:
  1341. name (str): A name for the input value. This corresponds to the name
  1342. of the positional argument to the function this ``Graph`` represents.
  1343. type_expr (Optional[Any]): an optional type annotation representing the
  1344. Python type the output of this node will have. This is needed in some
  1345. cases for proper code generation (e.g. when the function is used
  1346. subsequently in TorchScript compilation).
  1347. default_value (Any): The default value this function argument should take
  1348. on. NOTE: to allow for `None` as a default value, `inspect.Signature.empty`
  1349. should be passed as this argument to specify that the parameter does _not_
  1350. have a default value.
  1351. .. note::
  1352. The same insertion point and type expression rules apply for this method
  1353. as ``Graph.create_node``.
  1354. """
  1355. args = () if default_value is inspect.Signature.empty else (default_value,)
  1356. return self.create_node("placeholder", name, args=args, type_expr=type_expr)
  1357. @compatibility(is_backward_compatible=True)
  1358. def get_attr(self, qualified_name: str, type_expr: Optional[Any] = None) -> Node:
  1359. """
  1360. Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the
  1361. fetch of an attribute from the ``Module`` hierarchy.
  1362. Args:
  1363. qualified_name (str): the fully-qualified name of the attribute to be retrieved.
  1364. For example, if the traced Module has a submodule named ``foo``, which has a
  1365. submodule named ``bar``, which has an attribute named ``baz``, the qualified
  1366. name ``foo.bar.baz`` should be passed as ``qualified_name``.
  1367. type_expr (Optional[Any]): an optional type annotation representing the
  1368. Python type the output of this node will have.
  1369. Returns:
  1370. The newly-created and inserted ``get_attr`` node.
  1371. .. note::
  1372. The same insertion point and type expression rules apply for this method
  1373. as ``Graph.create_node``.
  1374. """
  1375. def _get_attr_reference_exists(
  1376. mod: torch.nn.Module, qualified_name: str
  1377. ) -> bool:
  1378. module_path, _, name = qualified_name.rpartition(".")
  1379. try:
  1380. submod: torch.nn.Module = mod.get_submodule(module_path)
  1381. except AttributeError:
  1382. warnings.warn(f"Failed to fetch module {module_path}!")
  1383. return False
  1384. if not hasattr(submod, name):
  1385. return False
  1386. res = getattr(submod, name)
  1387. if (
  1388. not isinstance(res, torch.nn.Module)
  1389. and not isinstance(res, torch.nn.Parameter)
  1390. and name not in submod._buffers
  1391. ):
  1392. return False
  1393. return True
  1394. if self.owning_module and not _get_attr_reference_exists(
  1395. self.owning_module, qualified_name
  1396. ):
  1397. warnings.warn(
  1398. "Attempted to insert a get_attr Node with no "
  1399. "underlying reference in the owning "
  1400. "GraphModule! Call "
  1401. "GraphModule.add_submodule to add the "
  1402. "necessary submodule, "
  1403. "GraphModule.add_parameter to add the "
  1404. "necessary Parameter, or "
  1405. "nn.Module.register_buffer to add the "
  1406. "necessary buffer",
  1407. stacklevel=2,
  1408. )
  1409. return self.create_node("get_attr", qualified_name, type_expr=type_expr)
  1410. @compatibility(is_backward_compatible=True)
  1411. def call_module(
  1412. self,
  1413. module_name: str,
  1414. args: Optional[tuple["Argument", ...]] = None,
  1415. kwargs: Optional[dict[str, "Argument"]] = None,
  1416. type_expr: Optional[Any] = None,
  1417. ) -> Node:
  1418. """
  1419. Insert a ``call_module`` ``Node`` into the ``Graph``. A ``call_module`` node
  1420. represents a call to the forward() function of a ``Module`` in the ``Module``
  1421. hierarchy.
  1422. Args:
  1423. module_name (str): The qualified name of the ``Module`` in the ``Module``
  1424. hierarchy to be called. For example, if the traced ``Module`` has a
  1425. submodule named ``foo``, which has a submodule named ``bar``, the
  1426. qualified name ``foo.bar`` should be passed as ``module_name`` to
  1427. call that module.
  1428. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  1429. to the called method. Note that this should *not* include a ``self`` argument.
  1430. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  1431. to the called method
  1432. type_expr (Optional[Any]): an optional type annotation representing the
  1433. Python type the output of this node will have.
  1434. Returns:
  1435. The newly-created and inserted ``call_module`` node.
  1436. .. note::
  1437. The same insertion point and type expression rules apply for this method
  1438. as :meth:`Graph.create_node`.
  1439. """
  1440. if self.owning_module and self.owning_module.get_submodule(module_name) is None:
  1441. warnings.warn(
  1442. "Attempted to insert a call_module Node with "
  1443. "no underlying reference in the owning "
  1444. "GraphModule! Call "
  1445. "GraphModule.add_submodule to add the "
  1446. "necessary submodule"
  1447. )
  1448. return self.create_node(
  1449. "call_module", module_name, args, kwargs, type_expr=type_expr
  1450. )
  1451. @compatibility(is_backward_compatible=True)
  1452. def call_method(
  1453. self,
  1454. method_name: str,
  1455. args: Optional[tuple["Argument", ...]] = None,
  1456. kwargs: Optional[dict[str, "Argument"]] = None,
  1457. type_expr: Optional[Any] = None,
  1458. ) -> Node:
  1459. """
  1460. Insert a ``call_method`` ``Node`` into the ``Graph``. A ``call_method`` node
  1461. represents a call to a given method on the 0th element of ``args``.
  1462. Args:
  1463. method_name (str): The name of the method to apply to the self argument.
  1464. For example, if args[0] is a ``Node`` representing a ``Tensor``,
  1465. then to call ``relu()`` on that ``Tensor``, pass ``relu`` to ``method_name``.
  1466. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  1467. to the called method. Note that this *should* include a ``self`` argument.
  1468. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  1469. to the called method
  1470. type_expr (Optional[Any]): an optional type annotation representing the
  1471. Python type the output of this node will have.
  1472. Returns:
  1473. The newly created and inserted ``call_method`` node.
  1474. .. note::
  1475. The same insertion point and type expression rules apply for this method
  1476. as :meth:`Graph.create_node`.
  1477. """
  1478. return self.create_node(
  1479. "call_method", method_name, args, kwargs, type_expr=type_expr
  1480. )
  1481. @compatibility(is_backward_compatible=True)
  1482. def call_function(
  1483. self,
  1484. the_function: Callable[..., Any],
  1485. args: Optional[tuple["Argument", ...]] = None,
  1486. kwargs: Optional[dict[str, "Argument"]] = None,
  1487. type_expr: Optional[Any] = None,
  1488. name: Optional[str] = None,
  1489. ) -> Node:
  1490. """
  1491. Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node
  1492. represents a call to a Python callable, specified by ``the_function``.
  1493. Args:
  1494. the_function (Callable[..., Any]): The function to be called. Can be any PyTorch
  1495. operator, Python function, or member of the ``builtins`` or ``operator``
  1496. namespaces.
  1497. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  1498. to the called function.
  1499. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  1500. to the called function
  1501. type_expr (Optional[Any]): an optional type annotation representing the
  1502. Python type the output of this node will have.
  1503. name (Optional[str]): The name of the node. If not specified, set to None
  1504. Returns:
  1505. The newly created and inserted ``call_function`` node.
  1506. .. note::
  1507. The same insertion point and type expression rules apply for this method
  1508. as :meth:`Graph.create_node`.
  1509. """
  1510. return self.create_node(
  1511. "call_function", the_function, args, kwargs, name=name, type_expr=type_expr
  1512. )
  1513. @compatibility(is_backward_compatible=True)
  1514. def node_copy(
  1515. self, node: Node, arg_transform: Callable[[Node], "Argument"] = lambda x: x
  1516. ) -> Node:
  1517. """
  1518. Copy a node from one graph into another. ``arg_transform`` needs to transform arguments from
  1519. the graph of node to the graph of self. Example::
  1520. # Copying all the nodes in `g` into `new_graph`
  1521. g: torch.fx.Graph = ...
  1522. new_graph = torch.fx.graph()
  1523. value_remap = {}
  1524. for node in g.nodes:
  1525. value_remap[node] = new_graph.node_copy(node, lambda n: value_remap[n])
  1526. Args:
  1527. node (Node): The node to copy into ``self``.
  1528. arg_transform (Callable[[Node], Argument]): A function that transforms
  1529. ``Node`` arguments in node's ``args`` and ``kwargs`` into the
  1530. equivalent argument in ``self``. In the simplest case, this should
  1531. retrieve a value out of a table mapping Nodes in the original
  1532. graph to ``self``.
  1533. """
  1534. args = map_arg(node.args, arg_transform)
  1535. kwargs = map_arg(node.kwargs, arg_transform)
  1536. if not isinstance(args, tuple):
  1537. raise AssertionError(f"Expected args to be tuple, got {type(args)}")
  1538. if not isinstance(kwargs, dict):
  1539. raise AssertionError(f"Expected kwargs to be dict, got {type(kwargs)}")
  1540. result_node = self.create_node(
  1541. node.op, node.target, args, kwargs, node.name, node.type
  1542. )
  1543. result_node.meta = copy.copy(node.meta)
  1544. return result_node
  1545. @compatibility(is_backward_compatible=True)
  1546. def output(self, result: "Argument", type_expr: Optional[Any] = None):
  1547. """
  1548. Insert an ``output`` ``Node`` into the ``Graph``. An ``output`` node represents
  1549. a ``return`` statement in Python code. ``result`` is the value that should
  1550. be returned.
  1551. Args:
  1552. result (Argument): The value to be returned.
  1553. type_expr (Optional[Any]): an optional type annotation representing the
  1554. Python type the output of this node will have.
  1555. .. note::
  1556. The same insertion point and type expression rules apply for this method
  1557. as ``Graph.create_node``.
  1558. """
  1559. return self.create_node(
  1560. op="output", target="output", args=(result,), type_expr=type_expr
  1561. )
  1562. def _target_to_str(self, target: Optional[Target]) -> str:
  1563. if callable(target):
  1564. op = target.__name__
  1565. else:
  1566. if not isinstance(target, str):
  1567. raise AssertionError(f"Expected target to be str, got {type(target)}")
  1568. op = target
  1569. if _is_magic(op):
  1570. op = op[2:-2]
  1571. op = _snake_case(op)
  1572. return op
  1573. @compatibility(is_backward_compatible=True)
  1574. def python_code(
  1575. self,
  1576. root_module: str,
  1577. *,
  1578. verbose: bool = False,
  1579. include_stride: bool = False,
  1580. include_device: bool = False,
  1581. colored: bool = False,
  1582. expanded_def: bool = False,
  1583. record_func: bool = False,
  1584. additional_meta: Optional[list[str]] = None,
  1585. ) -> PythonCode:
  1586. """
  1587. Turn this ``Graph`` into valid Python code.
  1588. Args:
  1589. root_module (str): The name of the root module on which to look-up
  1590. qualified name targets. This is usually 'self'.
  1591. Returns:
  1592. A PythonCode object, consisting of two fields:
  1593. src: the Python source code representing the object
  1594. globals: a dictionary of global names in `src` -> the objects that they reference.
  1595. """
  1596. # NOTE: [Graph Namespaces]
  1597. #
  1598. # There are two types of symbols in generated Python source code:
  1599. # locals and globals.
  1600. # Locals are locally defined by the output of a node in the Graph.
  1601. # Globals are references to external objects, like functions or types.
  1602. #
  1603. # When generating Python code, we need to make sure to name things
  1604. # appropriately. In particular:
  1605. # - All names should be unique, to avoid weird shadowing bugs.
  1606. # - These names need to be consistent, e.g. a object should always be
  1607. # referenced by the same name.
  1608. #
  1609. # To do this, we create a new namespace just for this source. All names
  1610. # that get printed must come from this namespace.
  1611. #
  1612. # Why can't we reuse node.name? Because it was generated within the
  1613. # namespace `self._graph_namespace`. In order to provide uniqueness
  1614. # over both locals (node.name) *and* globals, we create a completely
  1615. # new namespace to put all identifiers in.
  1616. namespace = _Namespace()
  1617. # Override Node's repr to generate a valid name within our namespace.
  1618. # Since repr() is designed to produce a valid Python expression, it
  1619. # makes sense to reuse it. This way, it's easy to print something like
  1620. # Tuple[Node, Node] by simply calling repr() on it. Node's __repr__ is
  1621. # implemented cooperatively to allow this.
  1622. def node_repr(n: Node):
  1623. return namespace.create_name(n.name, n)
  1624. @contextmanager
  1625. def override_node_repr(graph: Graph):
  1626. orig_repr_fns = {}
  1627. for node in graph.nodes:
  1628. orig_repr_fns[node] = node._repr_fn
  1629. node._repr_fn = node_repr
  1630. try:
  1631. yield None
  1632. finally:
  1633. # restore the original repr functions
  1634. for node in graph.nodes:
  1635. node._repr_fn = orig_repr_fns[node]
  1636. with override_node_repr(self):
  1637. return self._python_code(
  1638. root_module,
  1639. namespace,
  1640. verbose=verbose,
  1641. include_stride=include_stride,
  1642. include_device=include_device,
  1643. colored=colored,
  1644. expanded_def=expanded_def,
  1645. record_func=record_func,
  1646. additional_meta=additional_meta,
  1647. )
  1648. def _python_code(
  1649. self,
  1650. root_module: str,
  1651. namespace: _Namespace,
  1652. *,
  1653. verbose: bool = False,
  1654. include_stride: bool = False,
  1655. include_device: bool = False,
  1656. colored: bool = False,
  1657. expanded_def: bool = False,
  1658. record_func: bool = False,
  1659. additional_meta: Optional[list[str]] = None,
  1660. ) -> PythonCode:
  1661. return self._codegen._gen_python_code(
  1662. self.nodes,
  1663. root_module,
  1664. namespace,
  1665. verbose=verbose,
  1666. include_stride=include_stride,
  1667. include_device=include_device,
  1668. colored=colored,
  1669. expanded_def=expanded_def,
  1670. record_func=record_func,
  1671. additional_meta=additional_meta,
  1672. )
  1673. def __str__(self) -> str:
  1674. """
  1675. Return a human-readable (not machine-readable) string representation
  1676. of this Graph
  1677. """
  1678. placeholder_names: list[str] = []
  1679. # This is a one-element array just so ``format_node`` can modify the closed
  1680. # over value
  1681. maybe_return_typename: list[str] = [""]
  1682. node_strs = [node.format_node(placeholder_names) for node in self.nodes]
  1683. param_str = ", ".join(placeholder_names)
  1684. s = f"graph({param_str}){maybe_return_typename[0]}:"
  1685. for node_str in node_strs:
  1686. if node_str:
  1687. s += "\n " + node_str
  1688. return s
  1689. @compatibility(is_backward_compatible=True)
  1690. def print_tabular(self):
  1691. """
  1692. Prints the intermediate representation of the graph in tabular
  1693. format. Note that this API requires the ``tabulate`` module to be
  1694. installed.
  1695. """
  1696. try:
  1697. from tabulate import tabulate
  1698. except ImportError:
  1699. print(
  1700. "`print_tabular` relies on the library `tabulate`, "
  1701. "which could not be found on this machine. Run `pip "
  1702. "install tabulate` to install the library."
  1703. )
  1704. raise
  1705. node_specs = [[n.op, n.name, n.target, n.args, n.kwargs] for n in self.nodes]
  1706. print(
  1707. tabulate(node_specs, headers=["opcode", "name", "target", "args", "kwargs"])
  1708. )
  1709. @compatibility(is_backward_compatible=True)
  1710. def lint(self):
  1711. """
  1712. Runs various checks on this Graph to make sure it is well-formed. In
  1713. particular:
  1714. - Checks Nodes have correct ownership (owned by this graph)
  1715. - Checks Nodes appear in topological order
  1716. - If this Graph has an owning GraphModule, checks that targets
  1717. exist in that GraphModule
  1718. """
  1719. # Check topo order
  1720. def check_arg(arg: Node, n: Optional[Node] = None) -> None:
  1721. context_str = f" of Node '{n}' " if n else " "
  1722. if arg.graph is not self:
  1723. raise RuntimeError(
  1724. f"Argument '{arg}'{context_str}does not belong to this Graph, "
  1725. f"but was used as an argument! If you are copying nodes from another graph, make "
  1726. f"sure to use ``arg_transform`` on node_copy() to remap values\n{self}"
  1727. )
  1728. if arg not in seen_values:
  1729. raise RuntimeError(
  1730. f"Argument '{arg}'{context_str}was used before it has been "
  1731. f"defined! Please check that Nodes in the graph are topologically ordered\n{self}"
  1732. )
  1733. seen_names: set[str] = set()
  1734. seen_values: set[Node] = set()
  1735. for node in self.nodes:
  1736. if node.op not in _legal_ops:
  1737. raise RuntimeError(f"Node {node} had unknown opcode {node.op}!")
  1738. if node.graph is not self:
  1739. raise RuntimeError(f"Node '{node}' does not belong to this Graph!")
  1740. if node not in self._find_nodes_lookup_table:
  1741. raise RuntimeError(f"Node '{node}' is not added to the side table")
  1742. for arg in node._input_nodes:
  1743. check_arg(arg, node)
  1744. seen_values.add(node)
  1745. if node.name in seen_names:
  1746. raise RuntimeError(f"Node redefined name {node.name}!")
  1747. seen_names.add(node.name)
  1748. # Check targets are legit
  1749. if self.owning_module:
  1750. for node in self.nodes:
  1751. if node.op == "call_function":
  1752. if not callable(node.target):
  1753. raise ValueError(
  1754. f"Node {node} target {node.target} has type {torch.typename(node.target)} but "
  1755. "a Callable is expected"
  1756. )
  1757. else:
  1758. if not isinstance(node.target, str):
  1759. raise ValueError(
  1760. f"Node {node} target {node.target} has type {torch.typename(node.target)} but "
  1761. "a str is expected"
  1762. )
  1763. if node.op in ["get_attr", "call_module"]:
  1764. # pyrefly: ignore [missing-attribute]
  1765. target_atoms = node.target.split(".")
  1766. m_itr = self.owning_module
  1767. for i, atom in enumerate(target_atoms):
  1768. new_m_itr = getattr(m_itr, atom, None)
  1769. seen_qualname = ".".join(target_atoms[:i])
  1770. if new_m_itr is None:
  1771. raise RuntimeError(
  1772. f"Node {node} target {node.target} references nonexistent attribute "
  1773. f"{atom} of {seen_qualname}"
  1774. )
  1775. if node.op == "call_module" and not isinstance(
  1776. new_m_itr, torch.nn.Module
  1777. ):
  1778. raise RuntimeError(
  1779. f"Node {node} target {node.target} {atom} of {seen_qualname} does "
  1780. "not reference an nn.Module"
  1781. )
  1782. m_itr = new_m_itr
  1783. @compatibility(is_backward_compatible=True)
  1784. def eliminate_dead_code(
  1785. self, is_impure_node: Optional[Callable[[Node], bool]] = None
  1786. ) -> bool:
  1787. """
  1788. Remove all dead code from the graph, based on each node's number of
  1789. users, and whether the nodes have any side effects. The graph must be
  1790. topologically sorted before calling.
  1791. Args:
  1792. is_impure_node (Optional[Callable[[Node], bool]]): A function that returns
  1793. whether a node is impure. If this is None, then the default behavior is to
  1794. use Node.is_impure.
  1795. Returns:
  1796. bool: Whether the graph was changed as a result of the pass.
  1797. Example:
  1798. Before dead code is eliminated, `a` from `a = x + 1` below has no users
  1799. and thus can be eliminated from the graph without having an effect.
  1800. .. code-block:: python
  1801. def forward(self, x):
  1802. a = x + 1
  1803. return x + self.attr_1
  1804. After dead code is eliminated, `a = x + 1` has been removed, and the rest
  1805. of `forward` remains.
  1806. .. code-block:: python
  1807. def forward(self, x):
  1808. return x + self.attr_1
  1809. .. warning::
  1810. Dead code elimination has some heuristics to avoid removing
  1811. side-effectful nodes (see Node.is_impure) but in general coverage
  1812. is very bad, so you should assume that this method is not sound
  1813. to call unless you know that your FX graph consists entirely
  1814. of functional operations or you supply your own custom
  1815. function for detecting side-effectful nodes.
  1816. """
  1817. from torch.utils._ordered_set import OrderedSet
  1818. # Lint the graph first to make sure its topologically sorted, otherwise
  1819. # DCE below will not behave as expected.
  1820. self.lint()
  1821. impure_random = True
  1822. if torch._guards.TracingContext.try_get():
  1823. impure_random = torch._inductor.config.fallback_random
  1824. def has_side_effect(node):
  1825. if is_impure_node is not None:
  1826. return is_impure_node(node)
  1827. return node.is_impure(impure_random)
  1828. # Reverse iterate so that when we remove a node, any nodes used as an
  1829. # input to that node have an updated user count that no longer reflects
  1830. # the removed node.
  1831. removed_nodes = set()
  1832. for node in reversed(self.nodes):
  1833. if not has_side_effect(node) and len(node.users) == 0:
  1834. self.erase_node(node)
  1835. removed_nodes.add(node.name)
  1836. changed = len(removed_nodes) > 0
  1837. if changed:
  1838. log.info("The following nodes were dead code eliminated: %s", removed_nodes)
  1839. # Call DCE on the subgraphs
  1840. if self.owning_module is not None:
  1841. subgraph_names = OrderedSet(
  1842. x.target for x in self.find_nodes(op="get_attr")
  1843. )
  1844. for child_name, child_module in self.owning_module.named_children():
  1845. # Sometimes an owning_module can have unused children. Skip them
  1846. # by checking them from get_attr node targets.
  1847. if child_name in subgraph_names and isinstance(
  1848. child_module, torch.fx.GraphModule
  1849. ):
  1850. changed |= child_module.graph.eliminate_dead_code()
  1851. child_module.recompile()
  1852. return changed
  1853. @compatibility(is_backward_compatible=False)
  1854. def set_codegen(self, codegen: CodeGen):
  1855. self._codegen = codegen
  1856. @compatibility(is_backward_compatible=False)
  1857. def on_generate_code(
  1858. self,
  1859. make_transformer: Callable[[Optional[TransformCodeFunc]], TransformCodeFunc],
  1860. ):
  1861. """Register a transformer function when python code is generated
  1862. Args:
  1863. make_transformer (Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]):
  1864. a function that returns a code transformer to be registered.
  1865. This function is called by `on_generate_code` to obtain the
  1866. code transformer.
  1867. This function is also given as its input the currently
  1868. registered code transformer (or None if nothing is registered),
  1869. in case it is not desirable to overwrite it. This is useful to
  1870. chain code transformers together.
  1871. Returns:
  1872. a context manager that when used in a `with` statement, to automatically
  1873. restore the previously registered code transformer.
  1874. Example:
  1875. .. code-block:: python
  1876. gm: fx.GraphModule = ...
  1877. # This is a code transformer we want to register. This code
  1878. # transformer prepends a pdb import and trace statement at the very
  1879. # beginning of the generated torch.fx code to allow for manual
  1880. # debugging with the PDB library.
  1881. def insert_pdb(body):
  1882. return ["import pdb; pdb.set_trace()\\n", *body]
  1883. # Registers `insert_pdb`, and overwrites the current registered
  1884. # code transformer (given by `_` to the lambda):
  1885. gm.graph.on_generate_code(lambda _: insert_pdb)
  1886. # Or alternatively, registers a code transformer which first
  1887. # runs `body` through existing registered transformer, then
  1888. # through `insert_pdb`:
  1889. gm.graph.on_generate_code(
  1890. lambda current_trans: (
  1891. lambda body: insert_pdb(
  1892. current_trans(body) if current_trans else body
  1893. )
  1894. )
  1895. )
  1896. gm.recompile()
  1897. gm(*inputs) # drops into pdb
  1898. This function can also be used as a context manager, with the benefit to
  1899. automatically restores the previously registered code transformer:
  1900. .. code-block:: python
  1901. # ... continue from previous example
  1902. with gm.graph.on_generate_code(lambda _: insert_pdb):
  1903. # do more stuff with `gm`...
  1904. gm.recompile()
  1905. gm(*inputs) # drops into pdb
  1906. # now previous code transformer is restored (but `gm`'s code with pdb
  1907. # remains - that means you can run `gm` with pdb here too, until you
  1908. # run next `recompile()`).
  1909. """
  1910. on_gen_code_old = self._codegen._body_transformer
  1911. self._codegen._body_transformer = make_transformer(on_gen_code_old)
  1912. @contextlib.contextmanager
  1913. def on_generate_code_context_manager():
  1914. try:
  1915. yield
  1916. finally:
  1917. self._codegen._body_transformer = on_gen_code_old
  1918. return on_generate_code_context_manager()
  1919. def _clear_nodes(self) -> None:
  1920. for node in reversed(self.nodes):
  1921. node.meta.clear()
  1922. self.erase_node(node)
  1923. @contextmanager
  1924. def _override_sym_repr(
  1925. override: Callable[["torch.types.PySymType"], str],
  1926. ) -> Iterator[None]:
  1927. tmp = CodeGen._sym_repr
  1928. try:
  1929. CodeGen._sym_repr = override
  1930. yield
  1931. finally:
  1932. CodeGen._sym_repr = tmp
  1933. def _identity(x):
  1934. return x
  1935. def _make_color_fn(code):
  1936. def f(s):
  1937. reset = "\033[0m"
  1938. return f"{code}{s}{reset}"
  1939. return f
  1940. _color_codes = {
  1941. "yellow": "\033[33m",
  1942. "cyan": "\033[36m",
  1943. "green": "\033[32m",
  1944. "blue": "\033[34m",
  1945. "red": "\033[31m",
  1946. "dim": "\033[2m",
  1947. "dim_blue": "\033[2m\033[34m",
  1948. "dim_green": "\033[2m\033[32m",
  1949. }
  1950. _color_fns = {k: _make_color_fn(v) for k, v in _color_codes.items()}
  1951. _counter_regexp = re.compile(r"# COUNTER: (\d+)")
  1952. reflectable_magic_methods = {
  1953. "add": "{} + {}",
  1954. "sub": "{} - {}",
  1955. "mul": "{} * {}",
  1956. "floordiv": "{} // {}",
  1957. "truediv": "{} / {}",
  1958. "div": "{} / {}",
  1959. "mod": "{} % {}",
  1960. "pow": "{} ** {}",
  1961. "lshift": "{} << {}",
  1962. "rshift": "{} >> {}",
  1963. "and_": "{} & {}",
  1964. "or_": "{} | {}",
  1965. "xor": "{} ^ {}",
  1966. "getitem": "{}[{}]",
  1967. "matmul": "{} @ {}",
  1968. }
  1969. magic_methods = {
  1970. "eq": "{} == {}",
  1971. "ne": "{} != {}",
  1972. "lt": "{} < {}",
  1973. "gt": "{} > {}",
  1974. "le": "{} <= {}",
  1975. "ge": "{} >= {}",
  1976. "pos": "+{}",
  1977. "neg": "-{}",
  1978. "invert": "~{}",
  1979. **reflectable_magic_methods,
  1980. }
  1981. inplace_methods = {
  1982. "iadd": "{} += {}",
  1983. "iand": "{} &= {}",
  1984. "ifloordiv": "{} //= {}",
  1985. "ilshift": "{} <<= {}",
  1986. "imod": "{} %= {}",
  1987. "imul": "{} *= {}",
  1988. "imatmul": "{} @= {}",
  1989. "ior": "{} |= {}",
  1990. "ipow": "{} **= {}",
  1991. "irshift": "{} >>= {}",
  1992. "isub": "{} -= {}",
  1993. "itruediv": "{} /= {}",
  1994. "ixor": "{} ^= {}",
  1995. "setitem": "{}[{}] = {}",
  1996. }