graph.py 57 KB

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