graph.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. # mypy: allow-untyped-defs
  2. from collections import defaultdict
  3. from .node import Node, Argument, Target, map_arg, _type_repr, _get_qualified_name
  4. import torch.utils._pytree as pytree
  5. from . import _pytree as fx_pytree
  6. from ._compatibility import compatibility
  7. import os
  8. import contextlib
  9. from typing import TYPE_CHECKING, Callable, Any, List, Dict, NamedTuple, Optional, Tuple, Set, FrozenSet, Type, Iterable
  10. from dataclasses import dataclass
  11. from contextlib import contextmanager
  12. import copy
  13. import enum
  14. import torch
  15. import keyword
  16. import re
  17. import builtins
  18. import math
  19. import warnings
  20. import inspect
  21. __all__ = ["PythonCode", "CodeGen", "Graph"]
  22. if TYPE_CHECKING:
  23. from .graph_module import GraphModule # noqa: F401
  24. from ._symbolic_trace import Tracer # noqa: F401
  25. # Mapping of builtins to their `typing` equivalent.
  26. _origin_type_map = {
  27. list: List,
  28. dict: Dict,
  29. set: Set,
  30. frozenset: FrozenSet,
  31. tuple: Tuple,
  32. }
  33. # Signature for functions thattransforms the body (`list[str]`) of the
  34. # generated code
  35. TransformCodeFunc = Callable[[List[str]], List[str]]
  36. class _CustomBuiltin(NamedTuple):
  37. """Additional objs that we add to every graph's globals.
  38. The repr() for some standard library objects is not valid Python code without
  39. an import. For common objects of this sort, we bundle them in the globals of
  40. every FX graph.
  41. """
  42. # How to import this object from the standard library.
  43. import_str: str
  44. # The actual object, produced from that import string.
  45. obj: Any
  46. _custom_builtins: Dict[str, _CustomBuiltin] = {}
  47. def _register_custom_builtin(name: str, import_str: str, obj: Any):
  48. _custom_builtins[name] = _CustomBuiltin(import_str, obj)
  49. _register_custom_builtin('inf', 'from math import inf', math.inf)
  50. _register_custom_builtin('nan', 'from math import nan', math.nan)
  51. _register_custom_builtin('NoneType', 'NoneType = type(None)', type(None))
  52. _register_custom_builtin('torch', 'import torch', torch)
  53. _register_custom_builtin('device', 'from torch import device', torch.device)
  54. _register_custom_builtin('fx_pytree', 'import torch.fx._pytree as fx_pytree', fx_pytree)
  55. _register_custom_builtin('pytree', 'import torch.utils._pytree as pytree', pytree)
  56. def _is_magic(x: str) -> bool:
  57. return x.startswith('__') and x.endswith('__')
  58. def _snake_case(s: str) -> str:
  59. """
  60. Transforms the given string ``s`` to a Python-style variable name
  61. Examples:
  62. ``mod.snake_case`` -> ``mod.snake_case``
  63. ``mod.pascalCase``-> ``mod.pascal_case``
  64. ``mod.ALL_CAPS`` -> ``mod.all_caps``
  65. """
  66. chars = []
  67. prev_lower = False
  68. for c in s:
  69. if prev_lower and c.isupper():
  70. chars.append('_')
  71. chars.append(c.lower())
  72. prev_lower = c.islower()
  73. return ''.join(chars)
  74. def _is_from_torch(obj: Any) -> bool:
  75. module_name = getattr(obj, '__module__', None)
  76. if module_name is not None:
  77. base_module = module_name.partition('.')[0]
  78. return (
  79. base_module == 'torch' and
  80. not module_name.startswith("torch._dynamo.") and
  81. not module_name.startswith("torch._inductor.")
  82. )
  83. name = getattr(obj, '__name__', None)
  84. # exclude torch because torch.torch.torch.torch works. idk mang
  85. if name is not None and name != 'torch':
  86. for guess in [torch, torch.nn.functional]:
  87. if getattr(guess, name, None) is obj:
  88. return True
  89. return False
  90. class _Namespace:
  91. """A context for associating names uniquely with objects.
  92. The following invariants are enforced:
  93. - Each object gets a single name.
  94. - Each name is unique within a given namespace.
  95. - Names generated do not shadow builtins, unless the object is indeed that builtin.
  96. """
  97. def __init__(self):
  98. self._obj_to_name: Dict[Any, str] = {}
  99. self._unassociated_names = set()
  100. self._used_names: Set[str] = set()
  101. self._base_count: Dict[str, int] = defaultdict(int)
  102. self._illegal_char_regex = re.compile('[^0-9a-zA-Z_]+')
  103. self._name_suffix_regex = re.compile(r"(.*)_(\d+)$")
  104. def create_name(self, candidate: str, obj: Optional[Any]) -> str:
  105. """Create a unique name.
  106. Arguments:
  107. candidate: used as the basis for the unique name, relevant to the user.
  108. obj: If not None, an object that will be associated with the unique name.
  109. """
  110. if obj is not None and obj in self._obj_to_name:
  111. return self._obj_to_name[obj]
  112. # delete all characters that are illegal in a Python identifier
  113. candidate = self._illegal_char_regex.sub('_', candidate)
  114. if not candidate:
  115. candidate = '_unnamed'
  116. if candidate[0].isdigit():
  117. candidate = f'_{candidate}'
  118. match = self._name_suffix_regex.match(candidate)
  119. if match is None:
  120. base = candidate
  121. num = None
  122. else:
  123. base, num_str = match.group(1, 2)
  124. num = int(num_str)
  125. candidate = base if num is None else f'{base}_{num}'
  126. if not num:
  127. num = self._base_count[base]
  128. while candidate in self._used_names or self._is_illegal_name(candidate, obj):
  129. num += 1
  130. candidate = f'{base}_{num}'
  131. self._used_names.add(candidate)
  132. self._base_count[base] = num
  133. if obj is None:
  134. self._unassociated_names.add(candidate)
  135. else:
  136. self._obj_to_name[obj] = candidate
  137. return candidate
  138. def associate_name_with_obj(self, name: str, obj: Any):
  139. """Associate a unique name with an object.
  140. Neither `name` nor `obj` should be associated already.
  141. """
  142. assert obj not in self._obj_to_name
  143. assert name in self._unassociated_names
  144. self._obj_to_name[obj] = name
  145. self._unassociated_names.remove(name)
  146. def _is_illegal_name(self, name: str, obj: Any) -> bool:
  147. # 1. keywords are never allowed as names.
  148. if name in keyword.kwlist:
  149. return True
  150. # 2. Can't shadow a builtin name, unless you *are* that builtin.
  151. if name in builtins.__dict__:
  152. return obj is not builtins.__dict__[name]
  153. # 3. Can't shadow our custom builtins either
  154. if name in _custom_builtins:
  155. return obj is not _custom_builtins[name].obj
  156. return False
  157. def _rename_object(self, obj: Any, name: str):
  158. assert obj in self._obj_to_name
  159. self._obj_to_name[obj] = name
  160. self._used_names.add(name)
  161. dtype_abbrs = {
  162. torch.bfloat16: 'bf16',
  163. torch.float64: 'f64',
  164. torch.float32: 'f32',
  165. torch.float16: 'f16',
  166. torch.float8_e4m3fn: 'f8e4m3fn',
  167. torch.float8_e5m2: 'f8e5m2',
  168. torch.float8_e4m3fnuz: 'f8e4m3fnuz',
  169. torch.float8_e5m2fnuz: 'f8e5m2fnuz',
  170. torch.complex32: 'c32',
  171. torch.complex64: 'c64',
  172. torch.complex128: 'c128',
  173. torch.int8: 'i8',
  174. torch.int16: 'i16',
  175. torch.int32: 'i32',
  176. torch.int64: 'i64',
  177. torch.bool: 'b8',
  178. torch.uint8: 'u8',
  179. torch.uint32: 'u32',
  180. torch.uint64: 'u64',
  181. }
  182. @compatibility(is_backward_compatible=True)
  183. @dataclass
  184. class PythonCode:
  185. """
  186. Represents all the information necessary to exec or save a graph as Python code.
  187. """
  188. # Python source code for the forward function definition.
  189. src: str
  190. # Values in global scope during execution of `src_def`.
  191. globals: Dict[str, Any]
  192. # Optional mapping from the forward function's line number to
  193. # node index.
  194. _lineno_map: Optional[Dict[int, Optional[int]]]
  195. def _format_target(base: str, target: str) -> str:
  196. elems = target.split('.')
  197. r = base
  198. for e in elems:
  199. if not e.isidentifier():
  200. r = f'getattr({r}, "{e}")'
  201. else:
  202. r = f'{r}.{e}'
  203. return r
  204. class _InsertPoint:
  205. def __init__(self, graph, new_insert):
  206. self.graph = graph
  207. self.orig_insert, graph._insert = graph._insert, new_insert
  208. def __enter__(self):
  209. pass
  210. def __exit__(self, type, value, tb):
  211. self.graph._insert = self.orig_insert
  212. class _node_list:
  213. def __init__(self, graph: 'Graph', direction: str = '_next'):
  214. assert direction in ['_next', '_prev']
  215. self.graph = graph
  216. self.direction = direction
  217. def __len__(self):
  218. return self.graph._len
  219. def __iter__(self):
  220. root = self.graph._root
  221. if self.direction == "_next":
  222. cur = root._next
  223. while cur is not root:
  224. if not cur._erased:
  225. yield cur
  226. cur = cur._next
  227. else:
  228. assert self.direction == "_prev"
  229. cur = root._prev
  230. while cur is not root:
  231. if not cur._erased:
  232. yield cur
  233. cur = cur._prev
  234. def __reversed__(self):
  235. return _node_list(self.graph, '_next' if self.direction == '_prev' else '_prev')
  236. class _PyTreeInfo(NamedTuple):
  237. """
  238. Contains extra info stored when we're using Pytrees
  239. """
  240. orig_args: List[str]
  241. in_spec: pytree.TreeSpec
  242. out_spec: Optional[pytree.TreeSpec]
  243. @dataclass(frozen=True)
  244. class _ParsedStackTrace:
  245. """
  246. Represents the top-most frame of a parsed stack trace
  247. """
  248. file: str
  249. lineno: str
  250. name: str
  251. code: str
  252. def get_summary_str(self):
  253. return f'File: {self.file}:{self.lineno} in {self.name}, code: {self.code}'
  254. # get File:lineno code from stack_trace
  255. def _parse_stack_trace(stack_trace: str):
  256. if stack_trace is None:
  257. return None
  258. pattern = re.compile(r"^File \"(.+)\", line (\d+), in (.+)$")
  259. lines = stack_trace.strip().split('\n')
  260. # stacktrace should have innermost frame last, so we
  261. # iterate backwards to find the first line that starts
  262. # with 'File '
  263. summary_str = ""
  264. for idx in range(len(lines) - 2, -1, -1):
  265. line = lines[idx].strip()
  266. matches = pattern.match(line)
  267. if matches:
  268. file = matches.group(1)
  269. lineno = matches.group(2)
  270. name = matches.group(3)
  271. # next line should be the code
  272. code = lines[idx + 1].strip()
  273. return _ParsedStackTrace(file, lineno, name, code)
  274. return None
  275. @compatibility(is_backward_compatible=False)
  276. class CodeGen:
  277. def __init__(self):
  278. self._body_transformer: Optional[TransformCodeFunc] = None
  279. self._func_name: str = "forward"
  280. def gen_fn_def(self, free_vars: List[str], maybe_return_annotation: str) -> str:
  281. """
  282. Given the free variables and a return annotation, generates the beginning of the FX function.
  283. By default, `gen_fn_def(['a', 'b'], '') == 'def {self._func_name}(a, b):'`
  284. """
  285. # If the original function didn't have self as its first argument, we
  286. # would have added it.
  287. if len(free_vars) == 0 or free_vars[0] != 'self':
  288. free_vars.insert(0, 'self')
  289. return f"def {self._func_name}({', '.join(free_vars)}){maybe_return_annotation}:"
  290. def generate_output(self, output_args: Argument) -> str:
  291. """
  292. Given the output arguments, generates the return statement of the FX function.
  293. Note: The returned statement should not be indented.
  294. """
  295. return f'return {repr(output_args)}'
  296. def process_inputs(self, *args: Any) -> Any:
  297. """
  298. Transforms the inputs so that the graph can take them as arguments, as
  299. non-default codegen may result in the inputs to the function being
  300. different from the inputs to the graph.
  301. If the graph was directly runnable, this invariant should hold true
  302. `f.graph.process_outputs(f.graph(*f.graph.process_inputs(*inputs))) == f(*inputs)`
  303. """
  304. return args
  305. def process_outputs(self, outputs: Any) -> Any:
  306. """
  307. Transforms the outputs of the graph to be identical to the codegen.
  308. See ``process_inputs`` for more details.
  309. """
  310. return outputs
  311. def additional_globals(self) -> List[Tuple[str, Any]]:
  312. """
  313. If your codegen uses extra global values, add tuples of (identifier,reference to the value) here.
  314. For example, return ['List', typing.List] if you need ``List`` in the global context.
  315. """
  316. return []
  317. def _gen_python_code(
  318. self, nodes, root_module: str, namespace: _Namespace, *,
  319. verbose: bool = False, include_stride: bool = False, include_device: bool = False
  320. ) -> PythonCode:
  321. free_vars: List[str] = []
  322. body: List[str] = []
  323. globals_: Dict[str, Any] = {}
  324. wrapped_fns: Dict[str, None] = {}
  325. # Wrap string in list to pass by reference
  326. maybe_return_annotation : List[str] = ['']
  327. include_stride = include_stride or (os.environ.get("FX_GRAPH_SHOW_STRIDE", "0") == "1")
  328. include_device = include_device or (os.environ.get("FX_GRAPH_SHOW_DEVICE", "0") == "1")
  329. def add_global(name_hint: str, obj: Any):
  330. """Add an obj to be tracked as a global.
  331. We call this for names that reference objects external to the
  332. Graph, like functions or types.
  333. Returns: the global name that should be used to reference 'obj' in generated source.
  334. """
  335. if _is_from_torch(obj) and obj != torch.device: # to support registering torch.device
  336. # HACK: workaround for how torch custom ops are registered. We
  337. # can't import them like normal modules so they must retain their
  338. # fully qualified name.
  339. return _get_qualified_name(obj)
  340. # normalize the name hint to get a proper identifier
  341. global_name = namespace.create_name(name_hint, obj)
  342. if global_name in globals_:
  343. assert globals_[global_name] is obj
  344. return global_name
  345. globals_[global_name] = obj
  346. return global_name
  347. # Pre-fill the globals table with registered builtins.
  348. for name, (_, obj) in _custom_builtins.items():
  349. add_global(name, obj)
  350. def type_repr(o : Any):
  351. if o == ():
  352. # Empty tuple is used for empty tuple type annotation Tuple[()]
  353. return '()'
  354. typename = _type_repr(o)
  355. if hasattr(o, '__origin__'):
  356. # This is a generic type, e.g. typing.List[torch.Tensor]
  357. origin_type = _origin_type_map.get(o.__origin__, o.__origin__)
  358. origin_typename = add_global(_type_repr(origin_type), origin_type)
  359. if hasattr(o, '__args__'):
  360. # Assign global names for each of the inner type variables.
  361. args = [type_repr(arg) for arg in o.__args__]
  362. if len(args) == 0:
  363. # Bare type, such as `typing.Tuple` with no subscript
  364. # This code-path used in Python < 3.9
  365. return origin_typename
  366. return f'{origin_typename}[{",".join(args)}]'
  367. else:
  368. # Bare type, such as `typing.Tuple` with no subscript
  369. # This code-path used in Python 3.9+
  370. return origin_typename
  371. # Common case: this is a regular module name like 'foo.bar.baz'
  372. return add_global(typename, o)
  373. def _get_repr(arg: Any) -> str:
  374. # Handle NamedTuples (if it has `_fields`) via add_global.
  375. if isinstance(arg, tuple) and hasattr(arg, '_fields'):
  376. qualified_name = _get_qualified_name(type(arg))
  377. global_name = add_global(qualified_name, type(arg))
  378. return f"{global_name}{repr(tuple(arg))}"
  379. elif isinstance(arg, torch._ops.OpOverload):
  380. qualified_name = _get_qualified_name(arg)
  381. global_name = add_global(qualified_name, arg)
  382. return f"{global_name}"
  383. elif isinstance(arg, enum.Enum):
  384. cls = arg.__class__
  385. clsname = add_global(cls.__name__, cls)
  386. return f"{clsname}.{arg.name}"
  387. return repr(arg)
  388. def _format_args(args: Tuple[Argument, ...], kwargs: Dict[str, Argument]) -> str:
  389. args_s = ', '.join(_get_repr(a) for a in args)
  390. kwargs_s = ', '.join(f'{k} = {_get_repr(v)}' for k, v in kwargs.items())
  391. if args_s and kwargs_s:
  392. return f'{args_s}, {kwargs_s}'
  393. return args_s or kwargs_s
  394. # Run through reverse nodes and record the first instance of a use
  395. # of a given node. This represents the *last* use of the node in the
  396. # execution order of the program, which we will use to free unused
  397. # values
  398. node_to_last_use : Dict[Node, Node] = {}
  399. user_to_last_uses : Dict[Node, List[Node]] = {}
  400. def register_last_uses(n : Node, user : Node):
  401. if n not in node_to_last_use:
  402. node_to_last_use[n] = user
  403. user_to_last_uses.setdefault(user, []).append(n)
  404. for node in reversed(nodes):
  405. map_arg(node.args, lambda n: register_last_uses(n, node))
  406. map_arg(node.kwargs, lambda n: register_last_uses(n, node))
  407. def delete_unused_values(user : Node):
  408. """
  409. Delete values after their last use. This ensures that values that are
  410. not used in the remainder of the code are freed and the memory usage
  411. of the code is optimal.
  412. """
  413. if user.op == 'placeholder':
  414. return
  415. if user.op == 'output':
  416. body.append('\n')
  417. return
  418. nodes_to_delete = user_to_last_uses.get(user, [])
  419. if len(nodes_to_delete):
  420. to_delete_str = ' = '.join([repr(n) for n in nodes_to_delete] + ['None'])
  421. body.append(f'; {to_delete_str}\n')
  422. else:
  423. body.append('\n')
  424. prev_stacktrace = None
  425. def append_stacktrace_summary(node : Node):
  426. """
  427. Append a summary of the stacktrace to the generated code. This is
  428. useful for debugging.
  429. """
  430. nonlocal prev_stacktrace
  431. if node.op not in {'placeholder', 'output'}:
  432. if node.stack_trace:
  433. if node.stack_trace != prev_stacktrace:
  434. prev_stacktrace = node.stack_trace
  435. summary_str = ""
  436. if parsed_stack_trace := _parse_stack_trace(node.stack_trace):
  437. summary_str = parsed_stack_trace.get_summary_str()
  438. body.append(f'\n# {summary_str}\n')
  439. elif prev_stacktrace != "":
  440. prev_stacktrace = ""
  441. body.append('\n# No stacktrace found for following nodes\n')
  442. def stringify_shape(shape : Iterable) -> str:
  443. return f"[{', '.join(str(x) for x in shape)}]"
  444. def emit_node(node : Node):
  445. maybe_type_annotation = '' if node.type is None else f' : {type_repr(node.type)}'
  446. if verbose:
  447. # override annotation with more detailed information
  448. from torch._subclasses.fake_tensor import FakeTensor
  449. from torch.fx.experimental.proxy_tensor import py_sym_types
  450. from torch.fx.passes.shape_prop import TensorMetadata
  451. meta_val = node.meta.get('val', node.meta.get('tensor_meta', node.meta.get('example_value', None)))
  452. # use string as annotation, to make it valid python code
  453. if isinstance(meta_val, FakeTensor):
  454. stride_annotation = f"{stringify_shape(meta_val.stride())}" if include_stride else ""
  455. device_annotation = f"{meta_val.device}" if include_device else ""
  456. maybe_type_annotation = \
  457. f': "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}' \
  458. f'{stride_annotation}{device_annotation}"'
  459. elif isinstance(meta_val, py_sym_types):
  460. maybe_type_annotation = f': "Sym({meta_val})"'
  461. elif isinstance(meta_val, TensorMetadata):
  462. maybe_type_annotation = f': "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}"'
  463. if node.op == 'placeholder':
  464. assert isinstance(node.target, str)
  465. maybe_default_arg = '' if not node.args else f' = {_get_repr(node.args[0])}'
  466. free_vars.append(f'{node.target}{maybe_type_annotation}{maybe_default_arg}')
  467. raw_name = node.target.replace('*', '')
  468. if raw_name != repr(node):
  469. body.append(f'{repr(node)} = {raw_name}\n')
  470. return
  471. elif node.op == 'call_method':
  472. assert isinstance(node.target, str)
  473. body.append(
  474. f'{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.target)}'
  475. f'({_format_args(node.args[1:], node.kwargs)})')
  476. return
  477. elif node.op == 'call_function':
  478. assert callable(node.target)
  479. # pretty print operators
  480. if getattr(node.target, "__module__", "") == '_operator' and node.target.__name__ in magic_methods:
  481. assert isinstance(node.args, tuple)
  482. body.append(f'{repr(node)}{maybe_type_annotation} = '
  483. f'{magic_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}')
  484. return
  485. # pretty print inplace operators; required for jit.script to work properly
  486. # not currently supported in normal FX graphs, but generated by torchdynamo
  487. if getattr(node.target, "__module__", "") == '_operator' and node.target.__name__ in inplace_methods:
  488. body.append(f'{inplace_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}; '
  489. f'{repr(node)}{maybe_type_annotation} = {_get_repr(node.args[0])}')
  490. return
  491. qualified_name = _get_qualified_name(node.target)
  492. global_name = add_global(qualified_name, node.target)
  493. # special case for getattr: node.args could be 2-argument or 3-argument
  494. # 2-argument: attribute access; 3-argument: fall through to attrib function call with default value
  495. if global_name == 'getattr' and \
  496. isinstance(node.args, tuple) and \
  497. isinstance(node.args[1], str) and \
  498. node.args[1].isidentifier() and \
  499. len(node.args) == 2:
  500. body.append(f'{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.args[1])}')
  501. return
  502. body.append(f'{repr(node)}{maybe_type_annotation} = {global_name}({_format_args(node.args, node.kwargs)})')
  503. if node.meta.get('is_wrapped', False):
  504. wrapped_fns.setdefault(global_name)
  505. return
  506. elif node.op == 'call_module':
  507. assert isinstance(node.target, str)
  508. body.append(f'{repr(node)}{maybe_type_annotation} = '
  509. f'{_format_target(root_module, node.target)}({_format_args(node.args, node.kwargs)})')
  510. return
  511. elif node.op == 'get_attr':
  512. assert isinstance(node.target, str)
  513. body.append(f'{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}')
  514. return
  515. elif node.op == 'output':
  516. if node.type is not None:
  517. maybe_return_annotation[0] = f" -> {type_repr(node.type)}"
  518. body.append(self.generate_output(node.args[0]))
  519. return
  520. raise NotImplementedError(f'node: {node.op} {node.target}')
  521. for i, node in enumerate(nodes):
  522. # NOTE: emit_node does not emit a string with newline. It depends
  523. # on delete_unused_values to append one
  524. if verbose:
  525. append_stacktrace_summary(node)
  526. # emit a counter comment to keep track of
  527. # node index, which will be deleted later
  528. # after going through _body_transformer
  529. body.append(f"# COUNTER: {i}\n")
  530. emit_node(node)
  531. delete_unused_values(node)
  532. if len(body) == 0:
  533. # If the Graph has no non-placeholder nodes, no lines for the body
  534. # have been emitted. To continue to have valid Python code, emit a
  535. # single pass statement
  536. body.append('pass\n')
  537. if len(wrapped_fns) > 0:
  538. wrap_name = add_global('wrap', torch.fx.wrap)
  539. wrap_stmts = '\n'.join([f'{wrap_name}("{name}")' for name in wrapped_fns])
  540. else:
  541. wrap_stmts = ''
  542. if self._body_transformer:
  543. body = self._body_transformer(body)
  544. for name, value in self.additional_globals():
  545. add_global(name, value)
  546. prologue = self.gen_fn_def(free_vars, maybe_return_annotation[0])
  547. # remove counter and generate lineno to node index mapping
  548. lineno_map: Dict[int, Optional[int]] = {}
  549. prologue_len = prologue.count('\n') + 1
  550. new_lines: List[str] = []
  551. cur_idx = None
  552. for line in ''.join(body).split('\n'):
  553. counter = re.search(r"# COUNTER: (\d+)", line)
  554. if counter and counter.group(1) is not None:
  555. cur_idx = int(counter.group(1))
  556. else:
  557. lineno_map[len(new_lines) + prologue_len] = cur_idx
  558. new_lines.append(line)
  559. code = "\n".join(new_lines).lstrip('\n')
  560. code = '\n'.join(' ' + line for line in code.split('\n'))
  561. fn_code = f"""
  562. {wrap_stmts}
  563. {prologue}
  564. {code}"""
  565. return PythonCode(fn_code, globals_, _lineno_map=lineno_map)
  566. # Ideally, we'd like to refactor all of the pytree logic into this codegen
  567. # class. Unfortunately, there are 3 areas we currently need extra logic in FX.
  568. # 1. In the initial symbolic trace, the pytree logic is tied up with `concrete_args`.
  569. # 2. In the FX graph, we need to access 2 attributes - in_spec and out_spec.
  570. # Since we can't access .graph within the FX forward, we need to copy the attribute to the module.
  571. # 3. We currently can't register the pytree imports with `add_global` - not sure why.
  572. class _PyTreeCodeGen(CodeGen):
  573. def __init__(self, pytree_info: _PyTreeInfo):
  574. super().__init__()
  575. self.pytree_info: _PyTreeInfo = pytree_info
  576. def process_inputs(self, *inputs: Any) -> Any:
  577. flat_args = pytree.arg_tree_leaves(*inputs)
  578. return flat_args
  579. def process_outputs(self, out: Any) -> Any:
  580. if self.pytree_info is None or self.pytree_info.out_spec is None:
  581. return out
  582. if not isinstance(out, (list, tuple)):
  583. out = [out]
  584. assert self.pytree_info.out_spec is not None
  585. return pytree.tree_unflatten(out, self.pytree_info.out_spec)
  586. def gen_fn_def(self, free_vars, maybe_return_annotation):
  587. # Given a user function/model:
  588. # myargs = [myargs0, myargs1]
  589. # mykwargs = {'mykwargs0': ..., 'mykwargs1': ...}
  590. # def forward(self, mypos, *myargs, mykey=None, **mykwargs):
  591. #
  592. # The generated code flattens all keywords into positional arguments for `forward()`
  593. # e.g forward(self, mypos, myargs0, myargs1, mykey, mykwargs0, mykwargs1):
  594. #
  595. # Within `forward`, `tree_flatten_spec``still parses args and kwargs separately
  596. # e.g. tree_flatten_spec(([mypos, myargs0, myargs1],
  597. # {'mykey':mykey, 'mykwargs0':mykwargs0, 'mykwargs1':mykwargs1}),
  598. # self._in_spec)
  599. #
  600. # If the user function/model does not have keywords, the dict is suppressed from tree_flatten_spec
  601. # e.g. tree_flatten_spec([mypos, myargs0, myargs1]), self._in_spec)
  602. if self.pytree_info is None:
  603. return super().gen_fn_def(free_vars, maybe_return_annotation)
  604. fn_args = self.pytree_info.orig_args
  605. has_orig_self = (fn_args[0] == 'self') if len(fn_args) > 0 else False
  606. if has_orig_self:
  607. free_vars.insert(0, 'self')
  608. fn_definition = super().gen_fn_def(fn_args[:], maybe_return_annotation)
  609. if len(free_vars) > 0: # pytree has placeholders in it
  610. # when kwargs is present, in_spec is tuple(args, kwargs)
  611. has_args_kwargs_tuple = self.pytree_info.in_spec.type == tuple and \
  612. self.pytree_info.in_spec.num_children == 2 and \
  613. self.pytree_info.in_spec.children_specs[0].type == tuple and \
  614. self.pytree_info.in_spec.children_specs[1].type == dict
  615. fn_kwargs = '{}'
  616. fn_signature = f"[{', '.join(fn_args)}], self._in_spec"
  617. if has_args_kwargs_tuple:
  618. count_args = self.pytree_info.in_spec.children_specs[0].num_children
  619. fn_args = self.pytree_info.orig_args[:count_args]
  620. fn_kwargs = '{' + ', '.join(f"'{k}':{v}" for k, v in zip(
  621. self.pytree_info.in_spec.children_specs[1].context,
  622. self.pytree_info.orig_args[count_args:])) + '}'
  623. fn_signature = f"([{', '.join(fn_args)}], {fn_kwargs}), self._in_spec"
  624. # in Python, `var1: annotation1, var2: annotation2 = function_call()` is invalid.
  625. # we need to split it to two lines:
  626. # one for annotation: `var1: annotation1; var2: annotation2;` (note the semicolon)
  627. # one for code: `var1, var2, = function_call()`
  628. without_annotation = [x.split(":")[0] for x in free_vars]
  629. has_annotation = [x + "; " for x in free_vars if ":" in x]
  630. if len(has_annotation) > 0:
  631. fn_definition += "\n " + "".join(has_annotation) + "\n"
  632. fn_definition += f"""
  633. {', '.join(without_annotation)}, = fx_pytree.tree_flatten_spec({fn_signature})"""
  634. return fn_definition
  635. def generate_output(self, output_args):
  636. if self.pytree_info and self.pytree_info.out_spec:
  637. return f'return pytree.tree_unflatten({repr(output_args)}, self._out_spec)'
  638. else:
  639. return super().generate_output(output_args)
  640. class _FindNodesLookupTable:
  641. """
  642. Side table for the graph for the purpose of doing fast queries
  643. """
  644. def __init__(self):
  645. self.table: Dict[Tuple[str, Optional[Target]], Dict[Node, None]] = defaultdict(dict)
  646. def _key(self, node) -> Tuple[str, Optional[Target]]:
  647. return (node.op, node.target if node.op == "call_function" else None)
  648. def __contains__(self, node) -> bool:
  649. return node in self.table[self._key(node)]
  650. def insert(self, node: Node) -> None:
  651. self.table[self._key(node)][node] = None
  652. def remove(self, node: Node) -> None:
  653. self.table[self._key(node)].pop(node)
  654. def find_nodes(self, *, op: str, target: Optional['Target'] = None):
  655. if op == "call_function":
  656. assert target is not None
  657. return dict(self.table[(op, target)]).keys()
  658. if target is None:
  659. return dict(self.table[(op, None)]).keys()
  660. # op is call_method, get_attr, call_module
  661. return [node for node in self.table[(op, None)].keys() if node.target == target]
  662. @compatibility(is_backward_compatible=True)
  663. class Graph:
  664. """
  665. ``Graph`` is the main data structure used in the FX Intermediate Representation.
  666. It consists of a series of ``Node`` s, each representing callsites (or other
  667. syntactic constructs). The list of ``Node`` s, taken together, constitute a
  668. valid Python function.
  669. For example, the following code
  670. .. code-block:: python
  671. import torch
  672. import torch.fx
  673. class MyModule(torch.nn.Module):
  674. def __init__(self):
  675. super().__init__()
  676. self.param = torch.nn.Parameter(torch.rand(3, 4))
  677. self.linear = torch.nn.Linear(4, 5)
  678. def forward(self, x):
  679. return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3)
  680. m = MyModule()
  681. gm = torch.fx.symbolic_trace(m)
  682. Will produce the following Graph::
  683. print(gm.graph)
  684. .. code-block:: text
  685. graph(x):
  686. %linear_weight : [num_users=1] = self.linear.weight
  687. %add_1 : [num_users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {})
  688. %linear_1 : [num_users=1] = call_module[target=linear](args = (%add_1,), kwargs = {})
  689. %relu_1 : [num_users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {})
  690. %sum_1 : [num_users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1})
  691. %topk_1 : [num_users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {})
  692. return topk_1
  693. For the semantics of operations represented in the ``Graph``, please see :class:`Node`.
  694. """
  695. @compatibility(is_backward_compatible=True)
  696. def __init__(self, owning_module: Optional["GraphModule"] = None, tracer_cls: Optional[Type["Tracer"]] = None,
  697. tracer_extras: Optional[Dict[str, Any]] = None):
  698. """
  699. Construct an empty Graph.
  700. """
  701. self._root : Node = Node(self, '', 'root', '', (), {})
  702. self._used_names : Dict[str, int] = {} # base name -> number
  703. self._insert = self._root.prepend
  704. self._len = 0
  705. self._graph_namespace = _Namespace()
  706. self._owning_module = owning_module
  707. self._tracer_cls = tracer_cls
  708. self._tracer_extras = tracer_extras
  709. self._codegen = CodeGen()
  710. self._co_fields : Dict[str, Any] = {}
  711. self._find_nodes_lookup_table = _FindNodesLookupTable()
  712. @property
  713. def owning_module(self):
  714. return self._owning_module
  715. @owning_module.setter
  716. def owning_module(self, mod: Optional["GraphModule"]):
  717. self._owning_module = mod
  718. @property
  719. def nodes(self) -> _node_list:
  720. """
  721. Get the list of Nodes that constitute this Graph.
  722. Note that this ``Node`` list representation is a doubly-linked list. Mutations
  723. during iteration (e.g. delete a Node, add a Node) are safe.
  724. Returns:
  725. A doubly-linked list of Nodes. Note that ``reversed`` can be called on
  726. this list to switch iteration order.
  727. """
  728. return _node_list(self)
  729. @compatibility(is_backward_compatible=False)
  730. def find_nodes(self, *, op: str, target: Optional['Target'] = None, sort: bool = True):
  731. """
  732. Allows for fast query of nodes
  733. Args:
  734. op (str): the name of the operation
  735. target (Optional[Target]): the target of the node. For call_function,
  736. the target is required. For other ops, the target is optional.
  737. sort (bool): whether to return nodes in the order they appear on
  738. on the graph.
  739. Returns:
  740. Iteratable of nodes with the requested op and target.
  741. """
  742. node_list = self._find_nodes_lookup_table.find_nodes(op=op, target=target)
  743. if sort:
  744. return sorted(node_list)
  745. return node_list
  746. @compatibility(is_backward_compatible=True)
  747. def graph_copy(self, g : 'Graph', val_map : Dict[Node, Node], return_output_node=False) -> 'Optional[Argument]':
  748. """
  749. Copy all nodes from a given graph into ``self``.
  750. Args:
  751. g (Graph): The source graph from which to copy Nodes.
  752. val_map (Dict[Node, Node]): a dictionary that will be populated with a mapping
  753. from nodes in ``g`` to nodes in ``self``. Note that ``val_map`` can be passed
  754. in with values in it already to override copying of certain values.
  755. Returns:
  756. The value in ``self`` that is now equivalent to the output value in ``g``,
  757. if ``g`` had an ``output`` node. ``None`` otherwise.
  758. """
  759. for node in g.nodes:
  760. if node in val_map:
  761. continue
  762. if node.op == 'output':
  763. rv = map_arg(node.args[0], lambda n: val_map[n])
  764. return rv if not return_output_node else (rv, node)
  765. val_map[node] = self.node_copy(node, lambda n : val_map[n])
  766. return None
  767. def __deepcopy__(self, memo=None) -> 'Graph':
  768. """
  769. Explicitly implement __deepcopy__ to prevent excessive recursion depth
  770. from the default implementation. This uses graph_copy to copy the nodes
  771. in an iterative way, rather than recursive. It also populates the
  772. memoization table to prevent unnecessary copies (e.g. references to
  773. nodes or other parts of the Graph from a custom GraphModule implementation.
  774. """
  775. memo = memo if memo else {}
  776. g = Graph(tracer_cls=self._tracer_cls)
  777. output_vals = g.graph_copy(self, val_map=memo, return_output_node=True)
  778. g._codegen = copy.deepcopy(self._codegen)
  779. assert isinstance(output_vals, tuple)
  780. output_val, old_output_node = output_vals
  781. new_output_node = g.output(output_val, type_expr=getattr(old_output_node, 'type', None))
  782. new_output_node.meta = copy.copy(old_output_node.meta)
  783. return g
  784. @compatibility(is_backward_compatible=True)
  785. def create_node(self, op: str, target: 'Target',
  786. args: Optional[Tuple['Argument', ...]] = None,
  787. kwargs: Optional[Dict[str, 'Argument']] = None,
  788. name: Optional[str] = None,
  789. type_expr: Optional[Any] = None) -> Node:
  790. """
  791. Create a ``Node`` and add it to the ``Graph`` at the current insert-point.
  792. Note that the current insert-point can be set via :meth:`Graph.inserting_before`
  793. and :meth:`Graph.inserting_after`.
  794. Args:
  795. op (str): the opcode for this Node. One of 'call_function', 'call_method', 'get_attr',
  796. 'call_module', 'placeholder', or 'output'. The semantics of these opcodes are
  797. described in the ``Graph`` docstring.
  798. args (Optional[Tuple[Argument, ...]]): is a tuple of arguments to this node.
  799. kwargs (Optional[Dict[str, Argument]]): the kwargs of this Node
  800. name (Optional[str]): an optional string name for the ``Node``.
  801. This will influence the name of the value assigned to in the
  802. Python generated code.
  803. type_expr (Optional[Any]): an optional type annotation representing the
  804. Python type the output of this node will have.
  805. Returns:
  806. The newly-created and inserted node.
  807. """
  808. assert op in ('call_function', 'call_method', 'get_attr', 'call_module', 'placeholder', 'output')
  809. args = () if args is None else args
  810. kwargs = {} if kwargs is None else kwargs
  811. assert isinstance(args, tuple), "args must be a tuple"
  812. assert isinstance(kwargs, dict), "kwargs must be a dict"
  813. candidate = name if name is not None else self._target_to_str(target)
  814. name = self._graph_namespace.create_name(candidate, None)
  815. n = Node(self, name, op, target, args, kwargs, type_expr)
  816. if self.owning_module is not None and getattr(self.owning_module, "_create_node_hooks", None) is not None:
  817. for f in self.owning_module._create_node_hooks:
  818. f(n)
  819. self._graph_namespace.associate_name_with_obj(name, n)
  820. self._insert(n)
  821. self._find_nodes_lookup_table.insert(n)
  822. self._len += 1
  823. return n
  824. @compatibility(is_backward_compatible=False)
  825. def process_inputs(self, *args):
  826. """
  827. Processes args so that they can be passed to the FX graph.
  828. """
  829. return self._codegen.process_inputs(*args)
  830. @compatibility(is_backward_compatible=False)
  831. def process_outputs(self, out):
  832. return self._codegen.process_outputs(out)
  833. @compatibility(is_backward_compatible=True)
  834. def erase_node(self, to_erase : Node) -> None:
  835. """
  836. Erases a ``Node`` from the ``Graph``. Throws an exception if
  837. there are still users of that node in the ``Graph``.
  838. Args:
  839. to_erase (Node): The ``Node`` to erase from the ``Graph``.
  840. """
  841. if len(to_erase.users) > 0:
  842. raise RuntimeError(f'Tried to erase Node {to_erase} but it still had {len(to_erase.users)} '
  843. f'users in the graph: {to_erase.users}!')
  844. if to_erase.graph != self:
  845. raise RuntimeError(f"Attempting to remove {to_erase} from wrong graph!")
  846. if to_erase._erased:
  847. warnings.warn(f"erase_node({to_erase}) on an already erased node")
  848. return
  849. if self.owning_module is not None and getattr(self.owning_module, "_erase_node_hooks", None) is not None:
  850. for f in self.owning_module._erase_node_hooks:
  851. f(to_erase)
  852. self._find_nodes_lookup_table.remove(to_erase)
  853. to_erase._remove_from_list()
  854. to_erase._erased = True # iterators may retain handles to erased nodes
  855. self._len -= 1
  856. # Null out this Node's argument nodes so that the Nodes referred to
  857. # can update their ``users`` accordingly
  858. new_args = map_arg(to_erase.args, lambda n: None)
  859. assert isinstance(new_args, tuple)
  860. to_erase.args = new_args
  861. new_kwargs = map_arg(to_erase.kwargs, lambda n: None)
  862. assert isinstance(new_kwargs, dict)
  863. to_erase.kwargs = new_kwargs
  864. @compatibility(is_backward_compatible=True)
  865. def inserting_before(self, n: Optional[Node] = None):
  866. """Set the point at which create_node and companion methods will insert into the graph.
  867. When used within a 'with' statement, this will temporary set the insert point and
  868. then restore it when the with statement exits::
  869. with g.inserting_before(n):
  870. ... # inserting before node n
  871. ... # insert point restored to what it was previously
  872. g.inserting_before(n) # set the insert point permanently
  873. Args:
  874. n (Optional[Node]): The node before which to insert. If None this will insert before
  875. the beginning of the entire graph.
  876. Returns:
  877. A resource manager that will restore the insert point on ``__exit__``.
  878. """
  879. if n is None:
  880. return self.inserting_after(self._root)
  881. assert n.graph == self, "Node to insert before is not in graph."
  882. return _InsertPoint(self, n.prepend)
  883. @compatibility(is_backward_compatible=True)
  884. def inserting_after(self, n: Optional[Node] = None):
  885. """Set the point at which create_node and companion methods will insert into the graph.
  886. When used within a 'with' statement, this will temporary set the insert point and
  887. then restore it when the with statement exits::
  888. with g.inserting_after(n):
  889. ... # inserting after node n
  890. ... # insert point restored to what it was previously
  891. g.inserting_after(n) # set the insert point permanently
  892. Args:
  893. n (Optional[Node]): The node before which to insert. If None this will insert after
  894. the beginning of the entire graph.
  895. Returns:
  896. A resource manager that will restore the insert point on ``__exit__``.
  897. """
  898. if n is None:
  899. return self.inserting_before(self._root)
  900. assert n.graph == self, "Node to insert after is not in graph."
  901. return _InsertPoint(self, n.append)
  902. @compatibility(is_backward_compatible=True)
  903. def placeholder(self, name: str, type_expr: Optional[Any] = None,
  904. default_value : Any = inspect.Signature.empty) -> Node:
  905. """
  906. Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents
  907. a function input.
  908. Args:
  909. name (str): A name for the input value. This corresponds to the name
  910. of the positional argument to the function this ``Graph`` represents.
  911. type_expr (Optional[Any]): an optional type annotation representing the
  912. Python type the output of this node will have. This is needed in some
  913. cases for proper code generation (e.g. when the function is used
  914. subsequently in TorchScript compilation).
  915. default_value (Any): The default value this function argument should take
  916. on. NOTE: to allow for `None` as a default value, `inspect.Signature.empty`
  917. should be passed as this argument to specify that the parameter does _not_
  918. have a default value.
  919. .. note::
  920. The same insertion point and type expression rules apply for this method
  921. as ``Graph.create_node``.
  922. """
  923. args = () if default_value is inspect.Signature.empty else (default_value,)
  924. return self.create_node('placeholder', name, args=args, type_expr=type_expr)
  925. @compatibility(is_backward_compatible=True)
  926. def get_attr(self, qualified_name: str, type_expr: Optional[Any] = None) -> Node:
  927. """
  928. Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the
  929. fetch of an attribute from the ``Module`` hierarchy.
  930. Args:
  931. qualified_name (str): the fully-qualified name of the attribute to be retrieved.
  932. For example, if the traced Module has a submodule named ``foo``, which has a
  933. submodule named ``bar``, which has an attribute named ``baz``, the qualified
  934. name ``foo.bar.baz`` should be passed as ``qualified_name``.
  935. type_expr (Optional[Any]): an optional type annotation representing the
  936. Python type the output of this node will have.
  937. Returns:
  938. The newly-created and inserted ``get_attr`` node.
  939. .. note::
  940. The same insertion point and type expression rules apply for this method
  941. as ``Graph.create_node``.
  942. """
  943. def _get_attr_reference_exists(mod: torch.nn.Module, qualified_name: str) -> bool:
  944. module_path, _, name = qualified_name.rpartition(".")
  945. try:
  946. submod: torch.nn.Module = mod.get_submodule(module_path)
  947. except AttributeError:
  948. warnings.warn(f"Failed to fetch module {module_path}!")
  949. return False
  950. if not hasattr(submod, name):
  951. return False
  952. res = getattr(submod, name)
  953. if (not isinstance(res, torch.nn.Module)
  954. and not isinstance(res, torch.nn.Parameter)
  955. and name not in submod._buffers):
  956. return False
  957. return True
  958. if (self.owning_module and
  959. not _get_attr_reference_exists(self.owning_module, qualified_name)):
  960. warnings.warn("Attempted to insert a get_attr Node with no "
  961. "underlying reference in the owning "
  962. "GraphModule! Call "
  963. "GraphModule.add_submodule to add the "
  964. "necessary submodule, "
  965. "GraphModule.add_parameter to add the "
  966. "necessary Parameter, or "
  967. "nn.Module.register_buffer to add the "
  968. "necessary buffer", stacklevel=2)
  969. return self.create_node('get_attr', qualified_name, type_expr=type_expr)
  970. @compatibility(is_backward_compatible=True)
  971. def call_module(self,
  972. module_name: str,
  973. args: Optional[Tuple['Argument', ...]] = None,
  974. kwargs: Optional[Dict[str, 'Argument']] = None,
  975. type_expr: Optional[Any] = None) -> Node:
  976. """
  977. Insert a ``call_module`` ``Node`` into the ``Graph``. A ``call_module`` node
  978. represents a call to the forward() function of a ``Module`` in the ``Module``
  979. hierarchy.
  980. Args:
  981. module_name (str): The qualified name of the ``Module`` in the ``Module``
  982. hierarchy to be called. For example, if the traced ``Module`` has a
  983. submodule named ``foo``, which has a submodule named ``bar``, the
  984. qualified name ``foo.bar`` should be passed as ``module_name`` to
  985. call that module.
  986. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  987. to the called method. Note that this should *not* include a ``self`` argument.
  988. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  989. to the called method
  990. type_expr (Optional[Any]): an optional type annotation representing the
  991. Python type the output of this node will have.
  992. Returns:
  993. The newly-created and inserted ``call_module`` node.
  994. .. note::
  995. The same insertion point and type expression rules apply for this method
  996. as :meth:`Graph.create_node`.
  997. """
  998. if (self.owning_module and
  999. self.owning_module.get_submodule(module_name) is None):
  1000. warnings.warn("Attempted to insert a call_module Node with "
  1001. "no underlying reference in the owning "
  1002. "GraphModule! Call "
  1003. "GraphModule.add_submodule to add the "
  1004. "necessary submodule")
  1005. return self.create_node('call_module', module_name, args, kwargs, type_expr=type_expr)
  1006. @compatibility(is_backward_compatible=True)
  1007. def call_method(self,
  1008. method_name: str,
  1009. args: Optional[Tuple['Argument', ...]] = None,
  1010. kwargs: Optional[Dict[str, 'Argument']] = None,
  1011. type_expr: Optional[Any] = None) -> Node:
  1012. """
  1013. Insert a ``call_method`` ``Node`` into the ``Graph``. A ``call_method`` node
  1014. represents a call to a given method on the 0th element of ``args``.
  1015. Args:
  1016. method_name (str): The name of the method to apply to the self argument.
  1017. For example, if args[0] is a ``Node`` representing a ``Tensor``,
  1018. then to call ``relu()`` on that ``Tensor``, pass ``relu`` to ``method_name``.
  1019. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  1020. to the called method. Note that this *should* include a ``self`` argument.
  1021. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  1022. to the called method
  1023. type_expr (Optional[Any]): an optional type annotation representing the
  1024. Python type the output of this node will have.
  1025. Returns:
  1026. The newly created and inserted ``call_method`` node.
  1027. .. note::
  1028. The same insertion point and type expression rules apply for this method
  1029. as :meth:`Graph.create_node`.
  1030. """
  1031. return self.create_node('call_method', method_name, args, kwargs, type_expr=type_expr)
  1032. @compatibility(is_backward_compatible=True)
  1033. def call_function(self,
  1034. the_function: Callable[..., Any],
  1035. args: Optional[Tuple['Argument', ...]] = None,
  1036. kwargs: Optional[Dict[str, 'Argument']] = None,
  1037. type_expr: Optional[Any] = None) -> Node:
  1038. """
  1039. Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node
  1040. represents a call to a Python callable, specified by ``the_function``.
  1041. Args:
  1042. the_function (Callable[..., Any]): The function to be called. Can be any PyTorch
  1043. operator, Python function, or member of the ``builtins`` or ``operator``
  1044. namespaces.
  1045. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
  1046. to the called function.
  1047. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
  1048. to the called function
  1049. type_expr (Optional[Any]): an optional type annotation representing the
  1050. Python type the output of this node will have.
  1051. Returns:
  1052. The newly created and inserted ``call_function`` node.
  1053. .. note::
  1054. The same insertion point and type expression rules apply for this method
  1055. as :meth:`Graph.create_node`.
  1056. """
  1057. return self.create_node('call_function', the_function, args, kwargs, type_expr=type_expr)
  1058. @compatibility(is_backward_compatible=True)
  1059. def node_copy(self, node: Node, arg_transform: Callable[[Node], 'Argument'] = lambda x: x) -> Node:
  1060. """
  1061. Copy a node from one graph into another. ``arg_transform`` needs to transform arguments from
  1062. the graph of node to the graph of self. Example::
  1063. # Copying all the nodes in `g` into `new_graph`
  1064. g : torch.fx.Graph = ...
  1065. new_graph = torch.fx.graph()
  1066. value_remap = {}
  1067. for node in g.nodes:
  1068. value_remap[node] = new_graph.node_copy(node, lambda n : value_remap[n])
  1069. Args:
  1070. node (Node): The node to copy into ``self``.
  1071. arg_transform (Callable[[Node], Argument]): A function that transforms
  1072. ``Node`` arguments in node's ``args`` and ``kwargs`` into the
  1073. equivalent argument in ``self``. In the simplest case, this should
  1074. retrieve a value out of a table mapping Nodes in the original
  1075. graph to ``self``.
  1076. """
  1077. args = map_arg(node.args, arg_transform)
  1078. kwargs = map_arg(node.kwargs, arg_transform)
  1079. assert isinstance(args, tuple)
  1080. assert isinstance(kwargs, dict)
  1081. result_node = self.create_node(node.op, node.target, args, kwargs, node.name, node.type)
  1082. result_node.meta = copy.copy(node.meta)
  1083. return result_node
  1084. @compatibility(is_backward_compatible=True)
  1085. def output(self, result: 'Argument', type_expr: Optional[Any] = None):
  1086. """
  1087. Insert an ``output`` ``Node`` into the ``Graph``. An ``output`` node represents
  1088. a ``return`` statement in Python code. ``result`` is the value that should
  1089. be returned.
  1090. Args:
  1091. result (Argument): The value to be returned.
  1092. type_expr (Optional[Any]): an optional type annotation representing the
  1093. Python type the output of this node will have.
  1094. .. note::
  1095. The same insertion point and type expression rules apply for this method
  1096. as ``Graph.create_node``.
  1097. """
  1098. return self.create_node(op='output', target='output', args=(result,), type_expr=type_expr)
  1099. def _target_to_str(self, target : Target) -> str:
  1100. if callable(target):
  1101. op = target.__name__
  1102. else:
  1103. assert isinstance(target, str)
  1104. op = target
  1105. if _is_magic(op):
  1106. op = op[2:-2]
  1107. op = _snake_case(op)
  1108. return op
  1109. @compatibility(is_backward_compatible=True)
  1110. def python_code(
  1111. self, root_module: str, *,
  1112. verbose: bool = False, include_stride: bool = False, include_device: bool = False
  1113. ) -> PythonCode:
  1114. """
  1115. Turn this ``Graph`` into valid Python code.
  1116. Args:
  1117. root_module (str): The name of the root module on which to look-up
  1118. qualified name targets. This is usually 'self'.
  1119. Returns:
  1120. A PythonCode object, consisting of two fields:
  1121. src: the Python source code representing the object
  1122. globals: a dictionary of global names in `src` -> the objects that they reference.
  1123. """
  1124. # NOTE: [Graph Namespaces]
  1125. #
  1126. # There are two types of symbols in generated Python source code:
  1127. # locals and globals.
  1128. # Locals are locally defined by the output of a node in the Graph.
  1129. # Globals are references to external objects, like functions or types.
  1130. #
  1131. # When generating Python code, we need to make sure to name things
  1132. # appropriately. In particular:
  1133. # - All names should be unique, to avoid weird shadowing bugs.
  1134. # - These names need to be consistent, e.g. a object should always be
  1135. # referenced by the same name.
  1136. #
  1137. # To do this, we create a new namespace just for this source. All names
  1138. # that get printed must come from this namespace.
  1139. #
  1140. # Why can't we re-use node.name? Because it was generated within the
  1141. # namespace `self._graph_namespace`. In order to provide uniqueness
  1142. # over both locals (node.name) *and* globals, we create a completely
  1143. # new namespace to put all identifiers in.
  1144. namespace = _Namespace()
  1145. # Override Node's repr to generate a valid name within our namespace.
  1146. # Since repr() is designed to produce a valid Python expression, it
  1147. # makes sense to re-use it. This way, it's easy to print something like
  1148. # Tuple[Node, Node] by simply calling repr() on it. Node's __repr__ is
  1149. # implemented cooperatively to allow this.
  1150. def node_repr(n: Node):
  1151. return namespace.create_name(n.name, n)
  1152. @contextmanager
  1153. def override_node_repr(graph: Graph):
  1154. orig_repr_fns = {}
  1155. for node in graph.nodes:
  1156. orig_repr_fns[node] = node._repr_fn
  1157. node._repr_fn = node_repr
  1158. try:
  1159. yield None
  1160. finally:
  1161. # restore the original repr functions
  1162. for node in graph.nodes:
  1163. node._repr_fn = orig_repr_fns[node]
  1164. with override_node_repr(self):
  1165. return self._python_code(
  1166. root_module, namespace,
  1167. verbose=verbose, include_stride=include_stride, include_device=include_device
  1168. )
  1169. def _python_code(
  1170. self, root_module: str, namespace: _Namespace, *,
  1171. verbose: bool = False, include_stride: bool = False, include_device: bool = False
  1172. ) -> PythonCode:
  1173. return self._codegen._gen_python_code(
  1174. self.nodes, root_module, namespace,
  1175. verbose=verbose, include_stride=include_stride, include_device=include_device
  1176. )
  1177. def __str__(self) -> str:
  1178. """
  1179. Return a human-readable (not machine-readable) string representation
  1180. of this Graph
  1181. """
  1182. placeholder_names : List[str] = []
  1183. # This is a one-element array just so ``format_node`` can modify the closed
  1184. # over value
  1185. maybe_return_typename : List[str] = ['']
  1186. node_strs = [node.format_node(placeholder_names) for node in self.nodes]
  1187. param_str = ', '.join(placeholder_names)
  1188. s = f'graph({param_str}){maybe_return_typename[0]}:'
  1189. for node_str in node_strs:
  1190. if node_str:
  1191. s += '\n ' + node_str
  1192. return s
  1193. @compatibility(is_backward_compatible=True)
  1194. def print_tabular(self):
  1195. """
  1196. Prints the intermediate representation of the graph in tabular
  1197. format. Note that this API requires the ``tabulate`` module to be
  1198. installed.
  1199. """
  1200. try:
  1201. from tabulate import tabulate
  1202. except ImportError:
  1203. print("`print_tabular` relies on the library `tabulate`, "
  1204. "which could not be found on this machine. Run `pip "
  1205. "install tabulate` to install the library.")
  1206. raise
  1207. node_specs = [[n.op, n.name, n.target, n.args, n.kwargs]
  1208. for n in self.nodes]
  1209. print(tabulate(node_specs,
  1210. headers=['opcode', 'name', 'target', 'args', 'kwargs']))
  1211. @compatibility(is_backward_compatible=True)
  1212. def lint(self):
  1213. """
  1214. Runs various checks on this Graph to make sure it is well-formed. In
  1215. particular:
  1216. - Checks Nodes have correct ownership (owned by this graph)
  1217. - Checks Nodes appear in topological order
  1218. - If this Graph has an owning GraphModule, checks that targets
  1219. exist in that GraphModule
  1220. """
  1221. # Check topo order
  1222. def check_arg(arg : Node, n : Optional[Node] = None) -> None:
  1223. context_str = f' of Node \'{n}\' ' if n else ' '
  1224. if arg.graph is not self:
  1225. raise RuntimeError(f'Argument \'{arg}\'{context_str}does not belong to this Graph, '
  1226. f'but was used as an argument! If you are copying nodes from another graph, make '
  1227. f'sure to use ``arg_transform`` on node_copy() to remap values\n{self}')
  1228. if arg not in seen_values:
  1229. raise RuntimeError(f'Argument \'{arg}\'{context_str}was used before it has been '
  1230. f'defined! Please check that Nodes in the graph are topologically ordered\n{self}')
  1231. seen_names : Set[str] = set()
  1232. seen_values : Set[Node] = set()
  1233. for node in self.nodes:
  1234. if node.op not in ['placeholder', 'call_method', 'call_module', 'call_function', 'get_attr', 'output']:
  1235. raise RuntimeError(f'Node {node} had unknown opcode {node.op}!')
  1236. if node.graph is not self:
  1237. raise RuntimeError(f'Node \'{node}\' does not belong to this Graph!')
  1238. if node not in self._find_nodes_lookup_table:
  1239. raise RuntimeError(f"Node '{node}' is not added to the side table")
  1240. map_arg(node.args, lambda arg: check_arg(arg, node))
  1241. map_arg(node.kwargs, lambda arg: check_arg(arg, node))
  1242. seen_values.add(node)
  1243. if node.name in seen_names:
  1244. raise RuntimeError(f'Node redefined name {node.name}!')
  1245. seen_names.add(node.name)
  1246. # Check targets are legit
  1247. if self.owning_module:
  1248. for node in self.nodes:
  1249. if node.op == 'call_function':
  1250. if not callable(node.target):
  1251. raise ValueError(f'Node {node} target {node.target} has type {torch.typename(node.target)} but '
  1252. 'a Callable is expected')
  1253. else:
  1254. if not isinstance(node.target, str):
  1255. raise ValueError(f'Node {node} target {node.target} has type {torch.typename(node.target)} but '
  1256. 'a str is expected')
  1257. if node.op in ['get_attr', 'call_module']:
  1258. target_atoms = node.target.split('.')
  1259. m_itr = self.owning_module
  1260. for i, atom in enumerate(target_atoms):
  1261. new_m_itr = getattr(m_itr, atom, None)
  1262. seen_qualname = '.'.join(target_atoms[:i])
  1263. if new_m_itr is None:
  1264. raise RuntimeError(f'Node {node} target {node.target} references nonexistent attribute '
  1265. f'{atom} of {seen_qualname}')
  1266. if (node.op == "call_module"
  1267. and not isinstance(new_m_itr, torch.nn.Module)):
  1268. raise RuntimeError(f'Node {node} target {node.target} {atom} of {seen_qualname} does '
  1269. 'not reference an nn.Module')
  1270. elif (node.op == "get_attr"
  1271. and not isinstance(new_m_itr, torch.nn.Module)
  1272. and not isinstance(new_m_itr, torch.nn.Parameter)
  1273. and atom not in m_itr._buffers):
  1274. warnings.warn(f'Node {node} target {node.target} {atom} of {seen_qualname} does '
  1275. 'not reference an nn.Module, nn.Parameter, or buffer, which is '
  1276. 'what \'get_attr\' Nodes typically target')
  1277. else:
  1278. m_itr = new_m_itr
  1279. @compatibility(is_backward_compatible=True)
  1280. def eliminate_dead_code(self):
  1281. """
  1282. Remove all dead code from the graph, based on each node's number of
  1283. users, and whether the nodes have any side effects. The graph must be
  1284. topologically sorted before calling.
  1285. Returns:
  1286. bool: Whether the graph was changed as a result of the pass.
  1287. Example:
  1288. Before dead code is eliminated, `a` from `a = x + 1` below has no users
  1289. and thus can be eliminated from the graph without having an effect.
  1290. .. code-block:: python
  1291. def forward(self, x):
  1292. a = x + 1
  1293. return x + self.attr_1
  1294. After dead code is eliminated, `a = x + 1` has been removed, and the rest
  1295. of `forward` remains.
  1296. .. code-block:: python
  1297. def forward(self, x):
  1298. return x + self.attr_1
  1299. .. warning::
  1300. Dead code elimination has some heuristics to avoid removing
  1301. side-effectful nodes (see Node.is_impure) but in general coverage
  1302. is very bad, so you should assume that this method is not sound
  1303. to call unless you know that your FX graph consists entirely
  1304. of functional operations.
  1305. """
  1306. # Lint the graph first to make sure its topologically sorted, otherwise
  1307. # DCE below will not behave as expected.
  1308. self.lint()
  1309. # Reverse iterate so that when we remove a node, any nodes used as an
  1310. # input to that node have an updated user count that no longer reflects
  1311. # the removed node.
  1312. changed = False
  1313. for node in reversed(self.nodes):
  1314. if not node.is_impure() and len(node.users) == 0:
  1315. self.erase_node(node)
  1316. changed = True
  1317. return changed
  1318. @compatibility(is_backward_compatible=False)
  1319. def set_codegen(self, codegen: CodeGen):
  1320. self._codegen = codegen
  1321. @compatibility(is_backward_compatible=False)
  1322. def on_generate_code(
  1323. self,
  1324. make_transformer: Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]
  1325. ):
  1326. """Register a transformer function when python code is generated
  1327. Args:
  1328. make_transformer (Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]):
  1329. a function that returns a code transformer to be registered.
  1330. This function is called by `on_generate_code` to obtain the
  1331. code transformer.
  1332. This function is also given as its input the currently
  1333. registered code transformer (or None if nothing is registered),
  1334. in case it is not desirable to overwrite it. This is useful to
  1335. chain code transformers together.
  1336. Returns:
  1337. a context manager that when used in a `with` statement, to automatically
  1338. restore the previously registered code transformer.
  1339. Example:
  1340. .. code-block:: python
  1341. gm: fx.GraphModule = ...
  1342. # This is a code transformer we want to register. This code
  1343. # transformer prepends a pdb import and trace statement at the very
  1344. # beginning of the generated torch.fx code to allow for manual
  1345. # debugging with the PDB library.
  1346. def insert_pdb(body):
  1347. return ["import pdb; pdb.set_trace()\\n", *body]
  1348. # Registers `insert_pdb`, and overwrites the current registered
  1349. # code transformer (given by `_` to the lambda):
  1350. gm.graph.on_generate_code(
  1351. lambda _: insert_pdb
  1352. )
  1353. # Or alternatively, registers a code transformer which first
  1354. # runs `body` through existing registered transformer, then
  1355. # through `insert_pdb`:
  1356. gm.graph.on_generate_code(
  1357. lambda current_trans: (
  1358. lambda body: insert_pdb(
  1359. current_trans(body) if current_trans
  1360. else body
  1361. )
  1362. )
  1363. )
  1364. gm.recompile()
  1365. gm(*inputs) # drops into pdb
  1366. This function can also be used as a context manager, with the benefit to
  1367. automatically restores the previously registered code transformer:
  1368. .. code-block:: python
  1369. # ... continue from previous example
  1370. with gm.graph.on_generate_code(lambda _: insert_pdb):
  1371. # do more stuff with `gm`...
  1372. gm.recompile()
  1373. gm(*inputs) # drops into pdb
  1374. # now previous code transformer is restored (but `gm`'s code with pdb
  1375. # remains - that means you can run `gm` with pdb here too, until you
  1376. # run next `recompile()`).
  1377. """
  1378. on_gen_code_old = self._codegen._body_transformer
  1379. self._codegen._body_transformer = make_transformer(on_gen_code_old)
  1380. @contextlib.contextmanager
  1381. def on_generate_code_context_manager():
  1382. try:
  1383. yield
  1384. finally:
  1385. self._codegen._body_transformer = on_gen_code_old
  1386. return on_generate_code_context_manager()
  1387. reflectable_magic_methods = {
  1388. 'add': '{} + {}',
  1389. 'sub': '{} - {}',
  1390. 'mul': '{} * {}',
  1391. 'floordiv': '{} // {}',
  1392. 'truediv': '{} / {}',
  1393. 'div': '{} / {}',
  1394. 'mod': '{} % {}',
  1395. 'pow': '{} ** {}',
  1396. 'lshift': '{} << {}',
  1397. 'rshift': '{} >> {}',
  1398. 'and_': '{} & {}',
  1399. 'or_': '{} | {}',
  1400. 'xor': '{} ^ {}',
  1401. 'getitem': '{}[{}]',
  1402. 'matmul': '{} @ {}',
  1403. }
  1404. magic_methods = dict({
  1405. 'eq': '{} == {}',
  1406. 'ne': '{} != {}',
  1407. 'lt': '{} < {}',
  1408. 'gt': '{} > {}',
  1409. 'le': '{} <= {}',
  1410. 'ge': '{} >= {}',
  1411. 'pos': '+{}',
  1412. 'neg': '-{}',
  1413. 'invert': '~{}'}, **reflectable_magic_methods)
  1414. inplace_methods = {
  1415. 'iadd': '{} += {}',
  1416. 'iand': '{} &= {}',
  1417. 'ifloordiv': '{} //= {}',
  1418. 'ilshift': '{} <<= {}',
  1419. 'imod': '{} %= {}',
  1420. 'imul': '{} *= {}',
  1421. 'imatmul': '{} @= {}',
  1422. 'ior': '{} |= {}',
  1423. 'ipow': '{} **= {}',
  1424. 'irshift': '{} >>= {}',
  1425. 'isub': '{} -= {}',
  1426. 'itruediv': '{} /= {}',
  1427. 'ixor': '{} ^= {}',
  1428. 'setitem': '{}[{}] = {}',
  1429. }