graph.py 87 KB

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