ZTWHHH commited on
Commit
f573a4c
·
verified ·
1 Parent(s): 80eaa7f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. mplug_owl2/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc +3 -0
  3. mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__init__.py +0 -0
  4. mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__pycache__/__init__.cpython-310.pyc +0 -0
  5. mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__pycache__/python.cpython-310.pyc +0 -0
  6. mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/python.py +180 -0
  7. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/__init__.cpython-310.pyc +0 -0
  8. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/config.cpython-310.pyc +0 -0
  9. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/device_context.cpython-310.pyc +0 -0
  10. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/extract_compiled_graph.cpython-310.pyc +0 -0
  11. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/ir_cache.cpython-310.pyc +0 -0
  12. mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/metrics.cpython-310.pyc +0 -0
  13. mplug_owl2/lib/python3.10/site-packages/torch/fx/__init__.py +89 -0
  14. mplug_owl2/lib/python3.10/site-packages/torch/fx/__init__.pyi +15 -0
  15. mplug_owl2/lib/python3.10/site-packages/torch/fx/_compatibility.py +36 -0
  16. mplug_owl2/lib/python3.10/site-packages/torch/fx/_lazy_graph_module.py +185 -0
  17. mplug_owl2/lib/python3.10/site-packages/torch/fx/_pytree.py +103 -0
  18. mplug_owl2/lib/python3.10/site-packages/torch/fx/_symbolic_trace.py +1290 -0
  19. mplug_owl2/lib/python3.10/site-packages/torch/fx/_utils.py +63 -0
  20. mplug_owl2/lib/python3.10/site-packages/torch/fx/annotate.py +32 -0
  21. mplug_owl2/lib/python3.10/site-packages/torch/fx/config.py +6 -0
  22. mplug_owl2/lib/python3.10/site-packages/torch/fx/graph.py +1796 -0
  23. mplug_owl2/lib/python3.10/site-packages/torch/fx/graph_module.py +955 -0
  24. mplug_owl2/lib/python3.10/site-packages/torch/fx/interpreter.py +520 -0
  25. mplug_owl2/lib/python3.10/site-packages/torch/fx/node.py +788 -0
  26. mplug_owl2/lib/python3.10/site-packages/torch/fx/operator_schemas.py +451 -0
  27. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/__init__.py +12 -0
  28. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/annotate_getitem_nodes.py +44 -0
  29. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__init__.py +0 -0
  30. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__pycache__/__init__.cpython-310.pyc +0 -0
  31. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__pycache__/cudagraphs.cpython-310.pyc +0 -0
  32. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/cudagraphs.py +57 -0
  33. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/__init__.py +0 -0
  34. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/__pycache__/__init__.cpython-310.pyc +0 -0
  35. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__init__.py +0 -0
  36. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__pycache__/__init__.cpython-310.pyc +0 -0
  37. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__pycache__/cse_pass.cpython-310.pyc +0 -0
  38. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/cse_pass.py +113 -0
  39. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/fake_tensor_prop.py +70 -0
  40. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_drawer.py +443 -0
  41. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_manipulation.py +111 -0
  42. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_transform_observer.py +91 -0
  43. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__init__.py +2 -0
  44. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/__init__.cpython-310.pyc +0 -0
  45. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/partitioner.cpython-310.pyc +0 -0
  46. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/pass_base.cpython-310.pyc +0 -0
  47. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/pass_manager.cpython-310.pyc +0 -0
  48. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/partitioner.py +335 -0
  49. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/pass_base.py +73 -0
  50. mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/pass_manager.py +302 -0
.gitattributes CHANGED
@@ -707,3 +707,5 @@ mplug_owl2/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/axes3d.
707
  mplug_owl2/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
708
  mplug_owl2/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
709
  mplug_owl2/lib/python3.10/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
707
  mplug_owl2/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
708
  mplug_owl2/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
709
  mplug_owl2/lib/python3.10/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
710
+ mplug_owl2/lib/python3.10/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
711
+ mplug_owl2/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
mplug_owl2/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6f9ca08269a6618b2d423c48d038a935b3ce6c3064e2ea78e99054688589b95
3
+ size 413367
mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__init__.py ADDED
File without changes
mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/__pycache__/python.cpython-310.pyc ADDED
Binary file (6.66 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_dispatch/python.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ import unittest.mock
4
+ from contextlib import contextmanager
5
+ from typing import Iterator
6
+
7
+ import torch
8
+ import torch._C
9
+ import torch._ops
10
+ import torch.utils._python_dispatch
11
+ import torch.utils._pytree as pytree
12
+
13
+
14
+ __all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"]
15
+
16
+ no_python_dispatcher = torch._C._DisablePythonDispatcher
17
+ enable_python_dispatcher = torch._C._EnablePythonDispatcher
18
+ enable_pre_dispatch = torch._C._EnablePreDispatch
19
+
20
+ CROSSREF_FUNCTIONALIZE = False
21
+
22
+
23
+ def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]:
24
+ """
25
+ Warning: the set of overloads this will report is very subtle. It is precisely
26
+ the set of torch.ops functions that have actually been accessed from Python
27
+ (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT
28
+ from the set of registered operators, which will in general be a larger set,
29
+ as this would include all operators which we ran C++ static initializers or
30
+ Python operator registration on. This does not eagerly populate the list on
31
+ torch.ops.aten; this list is lazy!
32
+
33
+ In other words, this is good for traversing over everything that has an
34
+ OpOverload object allocated in Python. We use it for cache invalidation, but
35
+ don't rely on this list being complete.
36
+
37
+ Note that even if we did report all C++ registered overloads, this isn't guaranteed
38
+ to be complete either, as a subsequent lazy load of a library which triggers more
39
+ registrations could add more things to the set.
40
+ """
41
+ for ns in torch.ops:
42
+ packets = getattr(torch.ops, ns)
43
+ for op_name in packets:
44
+ packet = getattr(packets, op_name)
45
+ for overload in packet:
46
+ yield getattr(packet, overload)
47
+
48
+
49
+ @contextmanager
50
+ def suspend_functionalization():
51
+ f_tls = torch._C._dispatch_tls_is_dispatch_key_included(
52
+ torch._C.DispatchKey.Functionalize
53
+ )
54
+ f_rv = torch._C._functionalization_reapply_views_tls()
55
+ if f_tls:
56
+ torch._disable_functionalization()
57
+ try:
58
+ yield
59
+ finally:
60
+ if f_tls:
61
+ torch._enable_functionalization(reapply_views=f_rv)
62
+
63
+
64
+ def check_tensor_metadata_matches(nv, rv, desc):
65
+ assert callable(desc)
66
+ assert nv.size() == rv.size(), f"{desc()}: sizes {nv.size()} != {rv.size()}"
67
+ assert nv.dtype == rv.dtype, f"{desc()}: dtype {nv.dtype} != {rv.dtype}"
68
+ same_strides, idx = torch._prims_common.check_significant_strides(
69
+ nv, rv, only_cuda=False
70
+ )
71
+ assert (
72
+ same_strides
73
+ ), f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})"
74
+
75
+
76
+ def check_metadata_matches(n, r, desc):
77
+ assert callable(desc)
78
+ n_vals, n_spec = pytree.tree_flatten(n)
79
+ r_vals, r_spec = pytree.tree_flatten(r)
80
+ # TODO: test the specs match; empirically sometimes we have a tuple
81
+ # on one side and a list on the other
82
+ assert len(n_vals) == len(r_vals), f"{len(n_vals)} != {len(r_vals)}"
83
+ for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals):
84
+ if not isinstance(rv, torch.Tensor):
85
+ continue
86
+ check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}")
87
+
88
+
89
+ class Lit:
90
+ def __init__(self, s):
91
+ self.s = s
92
+
93
+ def __repr__(self):
94
+ return self.s
95
+
96
+
97
+ def _fmt(a: object) -> object:
98
+ if isinstance(a, torch.Tensor):
99
+ return Lit(
100
+ f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})"
101
+ )
102
+ else:
103
+ return a
104
+
105
+
106
+ def make_crossref_functionalize(op, final_key):
107
+ from torch._subclasses.fake_tensor import FakeTensorMode
108
+
109
+ # This case is pretty weird, suppress it for now
110
+ if op == torch.ops.aten.lift_fresh.default:
111
+ return final_key
112
+
113
+ def handler(*args, **kwargs):
114
+ fake_mode = FakeTensorMode()
115
+
116
+ def fakeify_defun(t):
117
+ if isinstance(t, torch.Tensor):
118
+ if torch._is_functional_tensor(t):
119
+ r = torch._from_functional_tensor(t)
120
+ # NB: This assumes that the inner tensor sizes/strides match
121
+ # the outer tensor sizes/strides. This doesn't necessarily have to
122
+ # be the case, see discussion at
123
+ # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456
124
+ assert t.size() == r.size()
125
+ assert t.stride() == r.stride()
126
+ else:
127
+ r = t
128
+ # TODO: suppress guards
129
+ return fake_mode.from_tensor(r)
130
+ return t
131
+
132
+ def maybe_detach(t):
133
+ if isinstance(t, torch.Tensor):
134
+ return t.detach()
135
+ else:
136
+ return t
137
+
138
+ # TODO: This probably does the wrong thing if you're running other
139
+ # substantive modes with the normal op outside here
140
+ with torch.utils._python_dispatch._disable_current_modes(), suspend_functionalization():
141
+ f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs))
142
+ orig_f_args, orig_f_kwargs = pytree.tree_map(
143
+ maybe_detach, (f_args, f_kwargs)
144
+ )
145
+ with fake_mode:
146
+ f_r = op(*f_args, **f_kwargs)
147
+ r = op._op_dk(final_key, *args, **kwargs)
148
+
149
+ def desc():
150
+ fmt_args = ", ".join(
151
+ itertools.chain(
152
+ (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args),
153
+ (
154
+ f"{k}={pytree.tree_map(_fmt, v)}"
155
+ for k, v in orig_f_kwargs.items()
156
+ ),
157
+ )
158
+ )
159
+ return f"{op}({fmt_args})"
160
+
161
+ check_metadata_matches(f_r, r, desc)
162
+ return r
163
+
164
+ return handler
165
+
166
+
167
+ # NB: enabling this is slow, don't do it in a hot loop. This is purely
168
+ # for debugging purposes.
169
+ @contextmanager
170
+ def enable_crossref_functionalize():
171
+ for op in all_py_loaded_overloads():
172
+ op._uncache_dispatch(torch._C.DispatchKey.Functionalize)
173
+ try:
174
+ with enable_python_dispatcher(), unittest.mock.patch(
175
+ "torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True
176
+ ):
177
+ yield
178
+ finally:
179
+ for op in all_py_loaded_overloads():
180
+ op._uncache_dispatch(torch._C.DispatchKey.Functionalize)
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/config.cpython-310.pyc ADDED
Binary file (806 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/device_context.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/extract_compiled_graph.cpython-310.pyc ADDED
Binary file (7.21 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/ir_cache.cpython-310.pyc ADDED
Binary file (635 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/_lazy/__pycache__/metrics.cpython-310.pyc ADDED
Binary file (974 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/__init__.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r'''
2
+ FX is a toolkit for developers to use to transform ``nn.Module``
3
+ instances. FX consists of three main components: a **symbolic tracer,**
4
+ an **intermediate representation**, and **Python code generation**. A
5
+ demonstration of these components in action:
6
+
7
+ ::
8
+
9
+ import torch
10
+ # Simple module for demonstration
11
+ class MyModule(torch.nn.Module):
12
+ def __init__(self) -> None:
13
+ super().__init__()
14
+ self.param = torch.nn.Parameter(torch.rand(3, 4))
15
+ self.linear = torch.nn.Linear(4, 5)
16
+
17
+ def forward(self, x):
18
+ return self.linear(x + self.param).clamp(min=0.0, max=1.0)
19
+
20
+ module = MyModule()
21
+
22
+ from torch.fx import symbolic_trace
23
+ # Symbolic tracing frontend - captures the semantics of the module
24
+ symbolic_traced : torch.fx.GraphModule = symbolic_trace(module)
25
+
26
+ # High-level intermediate representation (IR) - Graph representation
27
+ print(symbolic_traced.graph)
28
+ """
29
+ graph():
30
+ %x : [num_users=1] = placeholder[target=x]
31
+ %param : [num_users=1] = get_attr[target=param]
32
+ %add : [num_users=1] = call_function[target=operator.add](args = (%x, %param), kwargs = {})
33
+ %linear : [num_users=1] = call_module[target=linear](args = (%add,), kwargs = {})
34
+ %clamp : [num_users=1] = call_method[target=clamp](args = (%linear,), kwargs = {min: 0.0, max: 1.0})
35
+ return clamp
36
+ """
37
+
38
+ # Code generation - valid Python code
39
+ print(symbolic_traced.code)
40
+ """
41
+ def forward(self, x):
42
+ param = self.param
43
+ add = x + param; x = param = None
44
+ linear = self.linear(add); add = None
45
+ clamp = linear.clamp(min = 0.0, max = 1.0); linear = None
46
+ return clamp
47
+ """
48
+
49
+ The **symbolic tracer** performs "symbolic execution" of the Python
50
+ code. It feeds fake values, called Proxies, through the code. Operations
51
+ on theses Proxies are recorded. More information about symbolic tracing
52
+ can be found in the :func:`symbolic_trace` and :class:`Tracer`
53
+ documentation.
54
+
55
+ The **intermediate representation** is the container for the operations
56
+ that were recorded during symbolic tracing. It consists of a list of
57
+ Nodes that represent function inputs, callsites (to functions, methods,
58
+ or :class:`torch.nn.Module` instances), and return values. More information
59
+ about the IR can be found in the documentation for :class:`Graph`. The
60
+ IR is the format on which transformations are applied.
61
+
62
+ **Python code generation** is what makes FX a Python-to-Python (or
63
+ Module-to-Module) transformation toolkit. For each Graph IR, we can
64
+ create valid Python code matching the Graph's semantics. This
65
+ functionality is wrapped up in :class:`GraphModule`, which is a
66
+ :class:`torch.nn.Module` instance that holds a :class:`Graph` as well as a
67
+ ``forward`` method generated from the Graph.
68
+
69
+ Taken together, this pipeline of components (symbolic tracing ->
70
+ intermediate representation -> transforms -> Python code generation)
71
+ constitutes the Python-to-Python transformation pipeline of FX. In
72
+ addition, these components can be used separately. For example,
73
+ symbolic tracing can be used in isolation to capture a form of
74
+ the code for analysis (and not transformation) purposes. Code
75
+ generation can be used for programmatically generating models, for
76
+ example from a config file. There are many uses for FX!
77
+
78
+ Several example transformations can be found at the
79
+ `examples <https://github.com/pytorch/examples/tree/master/fx>`__
80
+ repository.
81
+ '''
82
+
83
+ from .graph_module import GraphModule
84
+ from ._symbolic_trace import symbolic_trace, Tracer, wrap, PH, ProxyableClassMeta
85
+ from .graph import Graph, CodeGen
86
+ from .node import Node, map_arg, has_side_effect
87
+ from .proxy import Proxy
88
+ from .interpreter import Interpreter as Interpreter, Transformer as Transformer
89
+ from .subgraph_rewriter import replace_pattern
mplug_owl2/lib/python3.10/site-packages/torch/fx/__init__.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.fx._symbolic_trace import (
2
+ symbolic_trace as symbolic_trace,
3
+ Tracer as Tracer,
4
+ wrap as wrap,
5
+ )
6
+ from torch.fx.graph import Graph as Graph
7
+ from torch.fx.graph_module import GraphModule as GraphModule
8
+ from torch.fx.interpreter import Interpreter as Interpreter, Transformer as Transformer
9
+ from torch.fx.node import (
10
+ has_side_effect as has_side_effect,
11
+ map_arg as map_arg,
12
+ Node as Node,
13
+ )
14
+ from torch.fx.proxy import Proxy as Proxy
15
+ from torch.fx.subgraph_rewriter import replace_pattern as replace_pattern
mplug_owl2/lib/python3.10/site-packages/torch/fx/_compatibility.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Callable, TypeVar
2
+ import textwrap
3
+
4
+ _BACK_COMPAT_OBJECTS : Dict[Any, None] = {}
5
+ _MARKED_WITH_COMPATIBILITY : Dict[Any, None] = {}
6
+
7
+ _T = TypeVar("_T")
8
+
9
+ def compatibility(is_backward_compatible: bool) -> Callable[[_T], _T]:
10
+ if is_backward_compatible:
11
+
12
+ def mark_back_compat(fn: _T) -> _T:
13
+ docstring = textwrap.dedent(getattr(fn, '__doc__', None) or '')
14
+ docstring += """
15
+ .. note::
16
+ Backwards-compatibility for this API is guaranteed.
17
+ """
18
+ fn.__doc__ = docstring
19
+ _BACK_COMPAT_OBJECTS.setdefault(fn)
20
+ _MARKED_WITH_COMPATIBILITY.setdefault(fn)
21
+ return fn
22
+
23
+ return mark_back_compat
24
+ else:
25
+
26
+ def mark_not_back_compat(fn: _T) -> _T:
27
+ docstring = textwrap.dedent(getattr(fn, '__doc__', None) or '')
28
+ docstring += """
29
+ .. warning::
30
+ This API is experimental and is *NOT* backward-compatible.
31
+ """
32
+ fn.__doc__ = docstring
33
+ _MARKED_WITH_COMPATIBILITY.setdefault(fn)
34
+ return fn
35
+
36
+ return mark_not_back_compat
mplug_owl2/lib/python3.10/site-packages/torch/fx/_lazy_graph_module.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from contextlib import contextmanager
3
+
4
+ from torch.fx import GraphModule
5
+ from torch.fx.graph_module import (
6
+ _format_import_block,
7
+ reduce_graph_module,
8
+ reduce_package_graph_module,
9
+ )
10
+ from torch.package import PackageExporter, sys_importer
11
+
12
+ from ._compatibility import compatibility
13
+
14
+
15
+ _use_lazy_graph_module_flag = False
16
+ _force_skip_lazy_graph_module_flag = False
17
+
18
+
19
+ @compatibility(is_backward_compatible=False)
20
+ @contextmanager
21
+ def _force_skip_lazy_graph_module():
22
+ """
23
+ Skip using lazy graph module disregarding the setting of _use_lazy_graph_module.
24
+ Use to skip _LazyGraphModule when testing inductor torchscript related backend.
25
+
26
+ torch.jit.script a _LazyGraphModule results in following error:
27
+ https://gist.github.com/shunting314/5143654c8084aed84ecd19b818258a69
28
+ """
29
+ try:
30
+ global _force_skip_lazy_graph_module_flag
31
+ prior = _force_skip_lazy_graph_module_flag
32
+ _force_skip_lazy_graph_module_flag = True
33
+ yield
34
+ finally:
35
+ _force_skip_lazy_graph_module_flag = prior
36
+
37
+
38
+ @compatibility(is_backward_compatible=False)
39
+ @contextmanager
40
+ def _use_lazy_graph_module(should_use: bool):
41
+ try:
42
+ global _use_lazy_graph_module_flag
43
+ prior = _use_lazy_graph_module_flag
44
+ _use_lazy_graph_module_flag = (
45
+ should_use and not _force_skip_lazy_graph_module_flag
46
+ )
47
+ yield
48
+ finally:
49
+ _use_lazy_graph_module_flag = prior
50
+
51
+
52
+ @compatibility(is_backward_compatible=False)
53
+ def _get_graph_module_cls():
54
+ return _LazyGraphModule if _use_lazy_graph_module_flag else GraphModule
55
+
56
+
57
+ def _make_graph_module(*args, graph_module_cls=None, **kwargs):
58
+ if graph_module_cls is None:
59
+ graph_module_cls = _get_graph_module_cls()
60
+
61
+ return graph_module_cls(*args, **kwargs)
62
+
63
+
64
+ @compatibility(is_backward_compatible=False)
65
+ class _LazyGraphModule(GraphModule):
66
+ """
67
+ The main difference between _LazyGraphModule and GraphModule is how recompile happens.
68
+ GraphModule will do a 'recompile' call to generate python code and the forward method when it's
69
+ constructed. Later on if the graph get updated, recompile method can be called again to refresh
70
+ the saved python code and forward method.
71
+
72
+ However in some cases especially in inductor, the recompilation can be a waste since we never
73
+ check the python code for the graph module or call its forward method. A few more concreate
74
+ examples regarding pattern matching fx passes in inductor:
75
+ 1. some passes will update the graph to be compiled and then call recompile on the GraphModule.
76
+ 2. some passes will trace small pattern function to search it in the graph being compiled and
77
+ replace the match with the traced graph of a replacement function. The pattern graph and
78
+ replacement graph are quite small but there are large amount of them. Doing GraphModule.recompile
79
+ for them in GraphModule.__init__ is also a waste of time.
80
+
81
+ However simply skip calling GraphModule.recompile in these scenarios is also dangeruous.
82
+ People may want to check the python code or call the GraphModule's forward method for debugging purposes.
83
+
84
+ The way _LazyGraphModule solves it is, we override the recompile method to just mark the
85
+ need for recompilation but does not do the actual recompilation. Later on if people really
86
+ access the compiled python code or call the GraphModule's forward method, we do the real
87
+ recompilation.
88
+ """
89
+
90
+ @classmethod
91
+ def from_graphmodule(cls, gm: GraphModule):
92
+ if isinstance(gm, _LazyGraphModule):
93
+ return gm
94
+ else:
95
+ return _LazyGraphModule(gm, gm.graph)
96
+
97
+ @staticmethod
98
+ def force_recompile(gm):
99
+ """
100
+ Sometimes we need force a recompile as a workaround
101
+ - we want to do the real recompilation before symbolic_trace to avoid error:
102
+ https://gist.github.com/shunting314/75549c2e82ae07ac1139c94a3583d259
103
+ """
104
+ if isinstance(gm, _LazyGraphModule):
105
+ gm.real_recompile()
106
+
107
+ def real_recompile(self):
108
+ if self._needs_recompile():
109
+ self._real_recompile()
110
+
111
+ @classmethod
112
+ def _needs_recompile(cls):
113
+ return cls.forward is cls._lazy_forward
114
+
115
+ def _lazy_forward(self, *args, **kwargs):
116
+ # Call self.real_recompile() rather than self._real_recompile() here.
117
+ # The _lazy_forward method may be saved and call repeatedly.
118
+ # Calling self.real_recompile can make sure we skip recompilation if
119
+ # we have already done so.
120
+ self.real_recompile()
121
+ assert not self._needs_recompile()
122
+
123
+ # call `__call__` rather than 'forward' since recompilation may
124
+ # install a wrapper for `__call__` to provide a customized error
125
+ # message.
126
+ return self(*args, **kwargs)
127
+
128
+ forward = _lazy_forward
129
+
130
+ # TODO: we shold handle __reduce_deploy__ the same way as __reduce_package__,
131
+ # or __reduce__ by calling _real_recompile. But I don't find a good way
132
+ # to test __reduce_deploy__ out. Also it's very unlikely that LazyGraphModule
133
+ # will be used in torch::deploy. So it's skipped for now.
134
+
135
+ def __reduce_package__(self, exporter: PackageExporter):
136
+ """
137
+ Follow GraphModule.__reduce__ but call 'self._real_recompile' rather
138
+ than 'self.recompile' since for a _LazyGraphModule, self.recompile just
139
+ mark the need of recompilation and does not return the PythonCode object.
140
+ """
141
+ python_code = self._real_recompile()
142
+ dict_without_graph = self.__dict__.copy()
143
+ dict_without_graph["_graphmodule_cls_name"] = self.__class__.__name__
144
+ del dict_without_graph["_graph"]
145
+
146
+ generated_module_name = f"fx-generated._{exporter.get_unique_id()}"
147
+ import_block = _format_import_block(python_code.globals, exporter.importer)
148
+ module_code = import_block + self.code
149
+ exporter.save_source_string(generated_module_name, module_code)
150
+ return (
151
+ reduce_package_graph_module,
152
+ (dict_without_graph, generated_module_name),
153
+ )
154
+
155
+ def __reduce__(self):
156
+ """
157
+ Follow GraphModule.__reduce__ but call 'self._real_recompile' rather
158
+ than 'self.recompile' since for a _LazyGraphModule, self.recompile just
159
+ mark the need of recompilation and does not return the PythonCode object.
160
+ """
161
+ python_code = self._real_recompile()
162
+ dict_without_graph = self.__dict__.copy()
163
+ import_block = _format_import_block(python_code.globals, sys_importer)
164
+ del dict_without_graph["_graph"]
165
+ return (reduce_graph_module, (dict_without_graph, import_block))
166
+
167
+ def _real_recompile(self):
168
+ return super().recompile()
169
+
170
+ @classmethod
171
+ def recompile(cls):
172
+ cls.forward = cls._lazy_forward
173
+
174
+ @property
175
+ def code(self) -> str:
176
+ self.real_recompile()
177
+ return super().code
178
+
179
+ def __str__(self) -> str:
180
+ """
181
+ str(GraphModule) will access the _code attribute. Make sure recompile
182
+ happens so _code attribute is available.
183
+ """
184
+ self.real_recompile()
185
+ return super().__str__()
mplug_owl2/lib/python3.10/site-packages/torch/fx/_pytree.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections import namedtuple
3
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type
4
+
5
+ import torch.return_types
6
+ from torch.utils._pytree import PyTree, TreeSpec
7
+
8
+
9
+ FlattenFuncSpec = Callable[[PyTree, TreeSpec], List]
10
+ FlattenFuncExactMatchSpec = Callable[[PyTree, TreeSpec], bool]
11
+
12
+ SUPPORTED_NODES: Dict[Type[Any], FlattenFuncSpec] = {}
13
+ SUPPORTED_NODES_EXACT_MATCH: Dict[Type[Any], Optional[FlattenFuncExactMatchSpec]] = {}
14
+
15
+
16
+ def register_pytree_flatten_spec(
17
+ cls: Type[Any],
18
+ flatten_fn_spec: FlattenFuncSpec,
19
+ flatten_fn_exact_match_spec: Optional[FlattenFuncExactMatchSpec] = None,
20
+ ) -> None:
21
+ SUPPORTED_NODES[cls] = flatten_fn_spec
22
+ SUPPORTED_NODES_EXACT_MATCH[cls] = flatten_fn_exact_match_spec
23
+
24
+
25
+ def tree_flatten_spec(
26
+ pytree: PyTree,
27
+ spec: TreeSpec,
28
+ exact_structural_match=False,
29
+ ) -> List[Any]:
30
+ if spec.is_leaf():
31
+ return [pytree]
32
+ if spec.type not in SUPPORTED_NODES:
33
+ raise RuntimeError(
34
+ f"{type(pytree)} does not have a flatten_fn_spec associated with it. Please register one with "
35
+ "torch.fx._pytree.register_pytree_flatten_spec. If you have serialized your model, make "
36
+ "sure that any custom pytrees have been registered before loading it.",
37
+ )
38
+ flatten_fn_spec = SUPPORTED_NODES[spec.type]
39
+ child_pytrees = flatten_fn_spec(pytree, spec)
40
+ if exact_structural_match:
41
+ flatten_fn_exact_match_spec = SUPPORTED_NODES_EXACT_MATCH[spec.type]
42
+ if flatten_fn_exact_match_spec and not flatten_fn_exact_match_spec(
43
+ pytree,
44
+ spec,
45
+ ):
46
+ raise RuntimeError(f"Cannot flatten pytree {pytree}, given spec: {spec}")
47
+ result = []
48
+ for child, child_spec in zip(child_pytrees, spec.children_specs):
49
+ flat = tree_flatten_spec(child, child_spec, exact_structural_match)
50
+ result += flat
51
+ return result
52
+
53
+
54
+ def _dict_flatten_spec(d: Dict[Any, Any], spec: TreeSpec) -> List[Any]:
55
+ return [d[k] for k in spec.context]
56
+
57
+
58
+ def _list_flatten_spec(d: List[Any], spec: TreeSpec) -> List[Any]:
59
+ return [d[i] for i in range(spec.num_children)]
60
+
61
+
62
+ def _tuple_flatten_spec(d: Tuple[Any], spec: TreeSpec) -> List[Any]:
63
+ return [d[i] for i in range(spec.num_children)]
64
+
65
+
66
+ def _namedtuple_flatten_spec(d: NamedTuple, spec: TreeSpec) -> List[Any]:
67
+ return [d[i] for i in range(spec.num_children)]
68
+
69
+
70
+ def _dict_flatten_spec_exact_match(d: Dict[Any, Any], spec: TreeSpec) -> bool:
71
+ return len(d) == spec.num_children
72
+
73
+
74
+ def _list_flatten_spec_exact_match(d: List[Any], spec: TreeSpec) -> bool:
75
+ return len(d) == spec.num_children
76
+
77
+
78
+ def _tuple_flatten_spec_exact_match(d: Tuple[Any], spec: TreeSpec) -> bool:
79
+ return len(d) == spec.num_children
80
+
81
+
82
+ def _namedtuple_flatten_spec_exact_match(d: NamedTuple, spec: TreeSpec) -> bool:
83
+ return len(d) == spec.num_children
84
+
85
+
86
+ register_pytree_flatten_spec(dict, _dict_flatten_spec, _dict_flatten_spec_exact_match)
87
+ register_pytree_flatten_spec(list, _list_flatten_spec, _list_flatten_spec_exact_match)
88
+ register_pytree_flatten_spec(
89
+ tuple,
90
+ _tuple_flatten_spec,
91
+ _tuple_flatten_spec_exact_match,
92
+ )
93
+ for return_type in torch.return_types.all_return_types:
94
+ register_pytree_flatten_spec(
95
+ return_type,
96
+ _tuple_flatten_spec,
97
+ _tuple_flatten_spec_exact_match,
98
+ )
99
+ register_pytree_flatten_spec(
100
+ namedtuple, # type: ignore[arg-type]
101
+ _namedtuple_flatten_spec,
102
+ _namedtuple_flatten_spec_exact_match,
103
+ )
mplug_owl2/lib/python3.10/site-packages/torch/fx/_symbolic_trace.py ADDED
@@ -0,0 +1,1290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import builtins
3
+ import copy
4
+ import contextlib
5
+ import functools
6
+ import inspect
7
+ import math
8
+ import os
9
+ import warnings
10
+ import collections
11
+ from itertools import chain
12
+ from types import CodeType, FunctionType, ModuleType
13
+ from typing import (
14
+ Any,
15
+ Callable,
16
+ Dict,
17
+ List,
18
+ NamedTuple,
19
+ Optional,
20
+ Set,
21
+ Tuple,
22
+ Type,
23
+ Union,
24
+ )
25
+
26
+ import torch
27
+ import torch.utils._pytree as pytree
28
+ from torch._C import ScriptObject # type: ignore[attr-defined]
29
+ from torch._library.fake_class_registry import FakeScriptObject
30
+
31
+ from ._compatibility import compatibility
32
+ from .graph import _PyTreeCodeGen, _PyTreeInfo, Graph
33
+ from .graph_module import GraphModule
34
+ from ._lazy_graph_module import _make_graph_module
35
+ from .node import Argument, base_types, map_aggregate
36
+ from .proxy import ParameterProxy, Proxy, TracerBase, Scope, ScopeContextManager
37
+
38
+ HAS_VARSTUFF = inspect.CO_VARARGS | inspect.CO_VARKEYWORDS
39
+
40
+ # These need to run in global scope to handle nested calls correctly
41
+ _orig_module_call: Callable = torch.nn.Module.__call__
42
+ _orig_module_getattr: Callable = torch.nn.Module.__getattr__
43
+
44
+ _proxyable_classes: Dict[Type, None] = {}
45
+
46
+ _is_fx_tracing_flag = False
47
+
48
+
49
+ def is_fx_tracing():
50
+ return _is_fx_tracing_flag
51
+
52
+ @compatibility(is_backward_compatible=True)
53
+ class ProxyableClassMeta(type):
54
+ """
55
+ ProxyableClassMeta allows you to make construction of a given Python class
56
+ symbolically traceable. For example::
57
+
58
+ import torch
59
+ import torch.fx
60
+
61
+ class TensorPair(metaclass=torch.fx.ProxyableClassMeta):
62
+ def __init__(self, left, right):
63
+ self.left, self.right = left, right
64
+
65
+ def add(self, other):
66
+ l = self.left + other.left
67
+ r = self.right + other.right
68
+ return TensorPair(l, r)
69
+
70
+ def mul(self, other):
71
+ l = self.left * other.left
72
+ r = self.right * other.right
73
+ return TensorPair(l, r)
74
+
75
+ def use_tensor_pair_ctor(x : TensorPair, y : torch.Tensor):
76
+ s = x.add(TensorPair(y, y))
77
+ return s.mul(x)
78
+
79
+ x = TensorPair(torch.randn(5, 3), torch.randn(5, 3))
80
+ y = torch.randn(5, 3)
81
+ ref_out = use_tensor_pair_ctor(x, y)
82
+
83
+ traced = torch.fx.symbolic_trace(use_tensor_pair_ctor)
84
+ print(traced.code)
85
+ '''
86
+ def forward(self, x : __main___TensorPair, y : torch.Tensor):
87
+ tensor_pair = __main___TensorPair(y, y); y = None
88
+ add = x.add(tensor_pair); tensor_pair = None
89
+ mul = add.mul(x); add = x = None
90
+ return mul
91
+ '''
92
+
93
+ From this example, we can see that construction of a class (``TensorPair``)
94
+ defined with ``ProxyableClassMeta`` as metaclass can be recorded in symbolic
95
+ tracing.
96
+ """
97
+
98
+ def __init__(cls, name, bases, attrs):
99
+ _proxyable_classes.setdefault(cls)
100
+ super().__init__(name, bases, attrs)
101
+
102
+ def __call__(cls, *args, **kwargs):
103
+ instance = cls.__new__(cls) # type: ignore[call-overload]
104
+
105
+ if not is_fx_tracing():
106
+ cls.__init__(instance, *args, **kwargs) # type: ignore[misc]
107
+ return instance
108
+
109
+ found_proxies = []
110
+
111
+ def check_proxy(a):
112
+ if isinstance(a, Proxy):
113
+ found_proxies.append(a)
114
+
115
+ map_aggregate(args, check_proxy)
116
+ map_aggregate(kwargs, check_proxy)
117
+
118
+ if len(found_proxies) != 0:
119
+ tracer = found_proxies[0].tracer
120
+ return tracer.create_proxy("call_function", cls, args, kwargs)
121
+ else:
122
+ cls.__init__(instance, *args, **kwargs) # type: ignore[misc]
123
+ return instance
124
+
125
+
126
+ def _patch_function(fn: FunctionType, nargs: int) -> FunctionType:
127
+ co = fn.__code__
128
+ co_flags = co.co_flags & ~HAS_VARSTUFF
129
+ co_args: tuple
130
+ if hasattr(co, "co_qualname"):
131
+ # Python-3.11+ code signature
132
+ co_args = (
133
+ nargs,
134
+ 0,
135
+ 0,
136
+ co.co_nlocals,
137
+ co.co_stacksize,
138
+ co_flags,
139
+ co.co_code,
140
+ co.co_consts,
141
+ co.co_names,
142
+ co.co_varnames,
143
+ co.co_filename,
144
+ co.co_name,
145
+ co.co_qualname, # type: ignore[attr-defined]
146
+ co.co_firstlineno,
147
+ co.co_lnotab,
148
+ co.co_exceptiontable, # type: ignore[attr-defined]
149
+ co.co_freevars,
150
+ co.co_cellvars,
151
+ )
152
+ elif hasattr(co, "co_posonlyargcount"):
153
+ co_args = (
154
+ nargs,
155
+ 0,
156
+ 0,
157
+ co.co_nlocals,
158
+ co.co_stacksize,
159
+ co_flags,
160
+ co.co_code,
161
+ co.co_consts,
162
+ co.co_names,
163
+ co.co_varnames,
164
+ co.co_filename,
165
+ co.co_name,
166
+ co.co_firstlineno,
167
+ co.co_lnotab,
168
+ co.co_freevars,
169
+ co.co_cellvars,
170
+ )
171
+ else:
172
+ co_args = (
173
+ nargs,
174
+ 0,
175
+ co.co_nlocals,
176
+ co.co_stacksize,
177
+ co_flags,
178
+ co.co_code,
179
+ co.co_consts,
180
+ co.co_names,
181
+ co.co_varnames,
182
+ co.co_filename,
183
+ co.co_name,
184
+ co.co_firstlineno,
185
+ co.co_lnotab,
186
+ co.co_freevars,
187
+ co.co_cellvars,
188
+ )
189
+ new_code = CodeType(*co_args) # type: ignore[arg-type]
190
+ return FunctionType(
191
+ new_code, fn.__globals__, fn.__name__, fn.__defaults__, fn.__closure__
192
+ )
193
+
194
+ # we need to insert placeholder nodes for *args and **kwargs
195
+ # we can't call this function normally, otherwise it would try to unpack them
196
+ # instead, let's make python think that args and kwargs are normal variables
197
+
198
+
199
+ @compatibility(is_backward_compatible=False)
200
+ class PHBase:
201
+ """
202
+ Object representing an input placeholder to `concrete_args`
203
+ """
204
+
205
+ def __repr__(self):
206
+ return "PH"
207
+
208
+
209
+ PH = PHBase()
210
+
211
+
212
+ @compatibility(is_backward_compatible=False)
213
+ class PHWithMeta(PHBase):
214
+ """
215
+ Object representing an input placeholder to `concrete_args`
216
+ """
217
+ def __init__(self, ph_key: Optional[str] = None):
218
+ super().__init__()
219
+
220
+ # Provide a hey for user to identify placeholder node during analysis
221
+ self.ph_key = ph_key
222
+
223
+
224
+ def _transfer_attrs(fr, to):
225
+ for attr_name in dir(fr):
226
+ attr_val = getattr(fr, attr_name)
227
+ if (
228
+ not callable(attr_val)
229
+ and not attr_name.startswith("__")
230
+ and not hasattr(to, attr_name)
231
+ ):
232
+ setattr(to, attr_name, attr_val)
233
+
234
+
235
+ @compatibility(is_backward_compatible=True)
236
+ class Tracer(TracerBase):
237
+ # Reference: https://github.com/pytorch/pytorch/issues/54354
238
+ # The first line of this docstring overrides the one Sphinx generates for the
239
+ # documentation. We need it so that Sphinx doesn't leak `math`s path from the
240
+ # build environment (e.g. `<module 'math' from '/leaked/path').
241
+
242
+ """Tracer(autowrap_modules=(math,), autowrap_functions=())
243
+
244
+ ``Tracer`` is the class that implements the symbolic tracing functionality
245
+ of ``torch.fx.symbolic_trace``. A call to ``symbolic_trace(m)`` is equivalent
246
+ to ``Tracer().trace(m)``.
247
+
248
+ Tracer can be subclassed to override various behaviors of the tracing
249
+ process. The different behaviors that can be overridden are described
250
+ in the docstrings of the methods on this class.
251
+ """
252
+
253
+ # Not checking BC on this API because the default value for `autowrap_modules`
254
+ # includes the local filepath to the `math` module, which would jitter
255
+ # across machines.
256
+ @compatibility(is_backward_compatible=True)
257
+ def __init__(
258
+ self,
259
+ autowrap_modules: Tuple[ModuleType] = (math,),
260
+ autowrap_functions: Tuple[Callable, ...] = (),
261
+ param_shapes_constant: bool = False,
262
+ ) -> None:
263
+ # This method's signature is overridden by the first line of this class'
264
+ # docstring. If this method's signature is modified, the signature that
265
+ # overrides it also should be modified accordingly.
266
+
267
+ """
268
+ Construct a Tracer object.
269
+
270
+ Args:
271
+
272
+ autowrap_modules (Tuple[ModuleType]): defaults to `(math, )`,
273
+ Python modules whose functions should be wrapped automatically
274
+ without needing to use fx.wrap(). Backward-compatibility for
275
+ this parameter is guaranteed.
276
+
277
+ autowrap_functions (Tuple[Callable, ...]): defaults to `()`,
278
+ Python functions that should be wrapped automatically without
279
+ needing to use fx.wrap(). Backward compatibility for this
280
+ parameter is guaranteed.
281
+
282
+ param_shapes_constant (bool): When this flag is set, calls to shape,
283
+ size and a few other shape like attributes of a module's parameter
284
+ will be evaluated directly, rather than returning a new Proxy value
285
+ for an attribute access. Backward compatibility for this parameter
286
+ is guaranteed.
287
+ """
288
+
289
+ super().__init__()
290
+
291
+ # Functions we will eagerly wrap when we see them while tracing
292
+ # this captures both `math.sqrt()` and `from math import sqrt` automatically
293
+ self._autowrap_function_ids: Set[int] = {
294
+ id(value)
295
+ for name, value in chain(*[m.__dict__.items() for m in autowrap_modules])
296
+ if not name.startswith("_") and callable(value)
297
+ }
298
+ self._autowrap_function_ids.update({id(f) for f in autowrap_functions})
299
+
300
+ # Python modules to apply autowrap to at the start, in addition to
301
+ # modules we see while tracing
302
+ self._autowrap_search: List[ModuleType] = list(autowrap_modules)
303
+ self.param_shapes_constant = param_shapes_constant
304
+
305
+ self.submodule_paths: Optional[Dict[torch.nn.Module, str]] = None
306
+ self.root_module_name: str = ""
307
+ # Maps the containing module's name to the operator name
308
+ self.scope = Scope("", None)
309
+ # Records the module call stack
310
+ self.module_stack = collections.OrderedDict()
311
+ # Mapping of node name to module scope
312
+ self.node_name_to_scope: Dict[str, Tuple[str, type]] = {}
313
+
314
+ _qualname_counter: Dict[str, int] = collections.defaultdict(int)
315
+
316
+ @compatibility(is_backward_compatible=True)
317
+ def get_fresh_qualname(self, prefix: str) -> str:
318
+ """
319
+ Gets a fresh name for a prefix and returns it. This function ensures
320
+ that it will not clash with an existing attribute on the graph.
321
+ """
322
+ # The idea here is that if the module doesn't have this prefix at all we
323
+ # should reset the counter to start from the beginning
324
+ # It's a ... little bit hacky (doesn't cover all cases) but the precise
325
+ # naming of the prefixes isn't a correctness issue, just a niceness
326
+ # issue
327
+ qualname = f"{prefix}0"
328
+ if not hasattr(self.root, qualname):
329
+ self._qualname_counter[prefix] = 0
330
+ return qualname
331
+
332
+ i = self._qualname_counter[prefix]
333
+ while True:
334
+ qualname = f"{prefix}{i}"
335
+ i += 1
336
+ if not hasattr(self.root, qualname):
337
+ break
338
+ self._qualname_counter[prefix] = i
339
+
340
+ return qualname
341
+
342
+ @compatibility(is_backward_compatible=True)
343
+ def create_arg(self, a: Any) -> "Argument":
344
+ """
345
+ A method to specify the behavior of tracing when preparing values to
346
+ be used as arguments to nodes in the ``Graph``.
347
+
348
+ By default, the behavior includes:
349
+
350
+ #. Iterate through collection types (e.g. tuple, list, dict) and recursively
351
+ call ``create_args`` on the elements.
352
+ #. Given a Proxy object, return a reference to the underlying IR ``Node``
353
+ #. Given a non-Proxy Tensor object, emit IR for various cases:
354
+
355
+ * For a Parameter, emit a ``get_attr`` node referring to that Parameter
356
+ * For a non-Parameter Tensor, store the Tensor away in a special
357
+ attribute referring to that attribute.
358
+
359
+ This method can be overridden to support more types.
360
+
361
+ Args:
362
+
363
+ a (Any): The value to be emitted as an ``Argument`` in the ``Graph``.
364
+
365
+
366
+ Returns:
367
+
368
+ The value ``a`` converted into the appropriate ``Argument``
369
+ """
370
+ # The base tracer is used to construct Graphs when there is no associated
371
+ # module hierarchy, so it can never create parameter references.
372
+ # The default tracer adds the ability to refer to parameters when
373
+ # tracing modules.
374
+ if isinstance(a, torch.nn.Parameter):
375
+ for n, p in self.root.named_parameters():
376
+ if a is p:
377
+ return self.create_node("get_attr", n, (), {})
378
+ raise NameError("parameter is not a member of this module")
379
+ elif isinstance(a, torch.Tensor):
380
+ for n_, p_ in self.root.named_buffers():
381
+ if a is p_:
382
+ return self.create_node("get_attr", n_, (), {})
383
+ elif isinstance(a, torch.nn.Module):
384
+ for n_, p_ in self.root.named_modules():
385
+ if a is p_:
386
+ return self.create_node("get_attr", n_, (), {})
387
+ # For NamedTuple instances that appear literally as args, we emit
388
+ # a node to construct the NamedTuple and use that Node as the argument.
389
+ if isinstance(a, tuple) and hasattr(a, "_fields"):
390
+ args = tuple(self.create_arg(elem) for elem in a)
391
+ return self.create_node("call_function", a.__class__, args, {})
392
+
393
+ # Tensors do not have a reliable string repr() from which they can be
394
+ # constructed (and we probably don't want to rely on that, either), so
395
+ # for any constant Tensor values we encounter, first search for if they
396
+ # are an attribute of some module in the module hierarchy. If so, emit
397
+ # a get_attr to retrieve that tensor. Otherwise, we'll store away the
398
+ # tensor value into a special attribute on the Module s.t. we can
399
+ # retrieve it with a get_attr.
400
+ if isinstance(a, (torch.Tensor, ScriptObject, FakeScriptObject)):
401
+ qualname: Optional[str] = self.tensor_attrs.get(a)
402
+
403
+ # Tensor was not found in the Module hierarchy, stow it away in a
404
+ # special attribute and set the qualname to refer to that
405
+ if not qualname:
406
+ base_name = "_tensor_constant" if isinstance(a, torch.Tensor) else "_torchbind_obj"
407
+ qualname = self.get_fresh_qualname(base_name)
408
+ assert isinstance(qualname, str)
409
+ self.tensor_attrs[a] = qualname
410
+ setattr(self.root, qualname, a)
411
+
412
+ return self.create_node("get_attr", qualname, (), {})
413
+
414
+ if type(a) in _proxyable_classes:
415
+ # This is an instance of a proxyable class for which we did not
416
+ # witness its construction. Intern this as a constant attribute
417
+
418
+ # TODO: binary search
419
+ qualname = self.get_fresh_qualname(f"_{a.__class__.__name__}_constant_")
420
+ assert isinstance(qualname, str)
421
+ setattr(self.root, qualname, a)
422
+
423
+ return self.create_node("get_attr", qualname, (), {})
424
+
425
+ return super().create_arg(a)
426
+
427
+ @compatibility(is_backward_compatible=True)
428
+ def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
429
+ """
430
+ A method to specify whether a given ``nn.Module`` is a "leaf" module.
431
+
432
+ Leaf modules are the atomic units that appear in
433
+ the IR, referenced by ``call_module`` calls. By default,
434
+ Modules in the PyTorch standard library namespace (torch.nn)
435
+ are leaf modules. All other modules are traced through and
436
+ their constituent ops are recorded, unless specified otherwise
437
+ via this parameter.
438
+
439
+ Args:
440
+
441
+ m (Module): The module being queried about
442
+ module_qualified_name (str): The path to root of this module. For example,
443
+ if you have a module hierarchy where submodule ``foo`` contains
444
+ submodule ``bar``, which contains submodule ``baz``, that module will
445
+ appear with the qualified name ``foo.bar.baz`` here.
446
+ """
447
+ return (
448
+ (m.__module__.startswith("torch.nn") or m.__module__.startswith("torch.ao.nn"))
449
+ and not isinstance(m, torch.nn.Sequential)
450
+ )
451
+
452
+ @compatibility(is_backward_compatible=True)
453
+ def path_of_module(self, mod: torch.nn.Module) -> str:
454
+ """
455
+ Helper method to find the qualified name of ``mod`` in the Module hierarchy
456
+ of ``root``. For example, if ``root`` has a submodule named ``foo``, which has
457
+ a submodule named ``bar``, passing ``bar`` into this function will return
458
+ the string "foo.bar".
459
+
460
+ Args:
461
+
462
+ mod (str): The ``Module`` to retrieve the qualified name for.
463
+ """
464
+ # Prefer the O(1) algorithm
465
+ if self.submodule_paths:
466
+ path = self.submodule_paths.get(mod)
467
+ if path is None:
468
+ raise NameError("module is not installed as a submodule")
469
+ assert isinstance(path, str)
470
+ return path
471
+ # O(N^2) fallback in the case that we didn't store the submodule
472
+ # paths.
473
+ else:
474
+ for n, p in self.root.named_modules():
475
+ if mod is p:
476
+ return n
477
+ raise NameError("module is not installed as a submodule")
478
+
479
+ @compatibility(is_backward_compatible=True)
480
+ def call_module(
481
+ self,
482
+ m: torch.nn.Module,
483
+ forward: Callable[..., Any],
484
+ args: Tuple[Any, ...],
485
+ kwargs: Dict[str, Any],
486
+ ) -> Any:
487
+ """
488
+ Method that specifies the behavior of this ``Tracer`` when it encounters
489
+ a call to an ``nn.Module`` instance.
490
+
491
+ By default, the behavior is to check if the called module is a leaf module
492
+ via ``is_leaf_module``. If it is, emit a ``call_module`` node referring to
493
+ ``m`` in the ``Graph``. Otherwise, call the ``Module`` normally, tracing through
494
+ the operations in its ``forward`` function.
495
+
496
+ This method can be overridden to--for example--create nested traced
497
+ GraphModules, or any other behavior you would want while tracing across
498
+ ``Module`` boundaries.
499
+
500
+ Args:
501
+
502
+ m (Module): The module for which a call is being emitted
503
+ forward (Callable): The forward() method of the ``Module`` to be invoked
504
+ args (Tuple): args of the module callsite
505
+ kwargs (Dict): kwargs of the module callsite
506
+
507
+ Return:
508
+
509
+ The return value from the Module call. In the case that a ``call_module``
510
+ node was emitted, this is a ``Proxy`` value. Otherwise, it is whatever
511
+ value was returned from the ``Module`` invocation.
512
+ """
513
+ module_qualified_name = self.path_of_module(m)
514
+ with ScopeContextManager(self.scope, Scope(module_qualified_name, type(m))) as _scope:
515
+ # module_stack is an ordered dict so writing then deleting the
516
+ # entry is equivalent to push/pop on a list
517
+ self.module_stack[_scope.module_path] = (module_qualified_name, _scope.module_type)
518
+ if not self.is_leaf_module(m, module_qualified_name):
519
+ ret_val = forward(*args, **kwargs)
520
+ else:
521
+ ret_val = self.create_proxy("call_module", module_qualified_name, args, kwargs)
522
+ key, _ = self.module_stack.popitem(last=True)
523
+ assert key == _scope.module_path, f" Unexpected key {key}"
524
+
525
+ return ret_val
526
+
527
+ @compatibility(is_backward_compatible=False)
528
+ def getattr(self, attr: str, attr_val: Any, parameter_proxy_cache: Dict[str, Any]):
529
+ """
530
+ Method that specifies the behavior of this ``Tracer`` when we call getattr
531
+ on a call to an ``nn.Module`` instance.
532
+
533
+ By default, the behavior is to return a proxy value for the attribute. It
534
+ also stores the proxy value in the ``parameter_proxy_cache``, so that future
535
+ calls will reuse the proxy rather than creating a new one.
536
+
537
+ This method can be overridden to --for example-- not return proxies when
538
+ querying parameters.
539
+
540
+ Args:
541
+
542
+ attr (str): The name of the attribute being queried
543
+ attr_val (Any): The value of the attribute
544
+ parameter_proxy_cache (Dict[str, Any]): A cache of attr names to proxies
545
+
546
+ Return:
547
+
548
+ The return value from the getattr call.
549
+ """
550
+ def maybe_get_proxy_for_attr(
551
+ attr_val, collection_to_search, parameter_proxy_cache
552
+ ):
553
+ for n, p in collection_to_search:
554
+ if attr_val is p:
555
+ if n not in parameter_proxy_cache:
556
+ kwargs = {}
557
+ if (
558
+ "proxy_factory_fn"
559
+ in inspect.signature(self.create_proxy).parameters
560
+ ):
561
+ kwargs["proxy_factory_fn"] = (
562
+ None
563
+ if not self.param_shapes_constant
564
+ else lambda node: ParameterProxy(
565
+ self, node, n, attr_val
566
+ )
567
+ )
568
+ val_proxy = self.create_proxy("get_attr", n, (), {}, **kwargs) # type: ignore[arg-type]
569
+ parameter_proxy_cache[n] = val_proxy
570
+ return parameter_proxy_cache[n]
571
+ return None
572
+
573
+ if isinstance(attr_val, torch.nn.Parameter):
574
+ maybe_parameter_proxy = maybe_get_proxy_for_attr(
575
+ attr_val, self.root.named_parameters(), parameter_proxy_cache
576
+ )
577
+ if maybe_parameter_proxy is not None:
578
+ return maybe_parameter_proxy
579
+
580
+ if self.proxy_buffer_attributes and isinstance(attr_val, torch.Tensor):
581
+ maybe_buffer_proxy = maybe_get_proxy_for_attr(
582
+ attr_val, self.root.named_buffers(), parameter_proxy_cache
583
+ )
584
+ if maybe_buffer_proxy is not None:
585
+ return maybe_buffer_proxy
586
+
587
+ return attr_val
588
+
589
+ # This method will be refactored
590
+ @compatibility(is_backward_compatible=False)
591
+ def create_args_for_root(self, root_fn, is_module, concrete_args=None):
592
+ """
593
+ Create ``placeholder`` nodes corresponding to the signature of the ``root``
594
+ Module. This method introspects root's signature and emits those
595
+ nodes accordingly, also supporting ``*args`` and ``**kwargs``.
596
+ """
597
+ # In some cases, a function or method has been decorated with a wrapper
598
+ # defined via ``functools.wraps``. In this case, the outer code object
599
+ # will likely not contain the actual parameters we care about, so unwrap
600
+ # the function to get to the innermost callable.
601
+ fn_for_analysis = inspect.unwrap(root_fn)
602
+ co = fn_for_analysis.__code__
603
+ total_args = co.co_argcount + co.co_kwonlyargcount
604
+ orig_args = list(co.co_varnames)
605
+ names_iter = iter(co.co_varnames)
606
+ args: List[Any] = []
607
+ skip_arg_idx = 0
608
+ if is_module:
609
+ if total_args == 0:
610
+ raise RuntimeError(
611
+ "``self`` argument cannot be part of *args expansion!"
612
+ )
613
+ skip_arg_idx = 1
614
+ next(names_iter) # skip self
615
+ args.append(self.root)
616
+
617
+ sig = inspect.signature(fn_for_analysis)
618
+
619
+
620
+ # This covers the very specific case where we are passing in flat
621
+ # concrete_args as a tuple, but our traced fn takes (*args, **kwargs).
622
+ # In this case, just take the concrete_args and pass them through.
623
+ name_idx = 0
624
+ if isinstance(concrete_args, tuple) and \
625
+ len(concrete_args) > 0 and \
626
+ (co.co_flags & HAS_VARSTUFF) and \
627
+ total_args == 1:
628
+ for concrete_arg in concrete_args:
629
+ out = self.create_proxy("placeholder", f"input_{name_idx}", (), {})
630
+ if isinstance(concrete_arg, PHBase):
631
+ if concrete_arg != PH:
632
+ # Transfer attrs in the case where you're using a placeholder other
633
+ # than the singleton PH (PH has no attributes to transfer).
634
+ # Proxies were created out of the placeholders.
635
+ # Transfer any metadata (put on the placeholders in the form of
636
+ # attributes set by the user) from the placeholder to the
637
+ # underlying nodes (the proxy is unwrapped by the user, but
638
+ # the metadata should hold).
639
+ _transfer_attrs(fr=concrete_arg, to=out.node)
640
+ args.append(out)
641
+ name_idx += 1
642
+ return root_fn, args
643
+
644
+ arg_names = [next(names_iter) for idx in range(skip_arg_idx, total_args)]
645
+ if isinstance(concrete_args, tuple):
646
+ if len(arg_names) != len(concrete_args):
647
+ raise RuntimeError(
648
+ f"Tracing expected {len(arg_names)} arguments but got {len(concrete_args)} concrete arguments"
649
+ )
650
+ concrete_args = dict(zip(arg_names, concrete_args))
651
+
652
+ def proxy_placeholder(name):
653
+ return self._proxy_placeholder(name, concrete_args, sig, fn_for_analysis)
654
+
655
+ args.extend(proxy_placeholder(names) for names in arg_names)
656
+
657
+ if co.co_kwonlyargcount > 0 or co.co_flags & HAS_VARSTUFF:
658
+ # TODO: type annotations for *args and **kwargs
659
+ if co.co_flags & inspect.CO_VARARGS:
660
+ args.append(proxy_placeholder("*" + next(names_iter)))
661
+ if co.co_flags & inspect.CO_VARKEYWORDS:
662
+ args.append(proxy_placeholder("**" + next(names_iter)))
663
+ root_fn = _patch_function(root_fn, len(args))
664
+
665
+ flat_args, in_spec = pytree.tree_flatten(tuple(args))
666
+ if not all(child.is_leaf() for child in in_spec.children_specs):
667
+ # In the case that we have pytree-flattened inputs in
668
+ # `concrete_args`, generate a flattening wrapper around the
669
+ # original root function and return that.
670
+ self.graph._codegen = _PyTreeCodeGen(
671
+ _PyTreeInfo(orig_args[:total_args], in_spec, None)
672
+ )
673
+
674
+ def flatten_fn(*args):
675
+ tree_args = pytree.tree_unflatten(list(args), in_spec)
676
+ tree_out = root_fn(*tree_args)
677
+ out_args, out_spec = pytree.tree_flatten(tree_out)
678
+ assert isinstance(self.graph._codegen, _PyTreeCodeGen)
679
+ self.graph._codegen.pytree_info = (
680
+ self.graph._codegen.pytree_info._replace(out_spec=out_spec)
681
+ )
682
+ return out_args
683
+
684
+ return flatten_fn, flat_args
685
+ return root_fn, args
686
+
687
+ @compatibility(is_backward_compatible=True)
688
+ def trace(
689
+ self,
690
+ root: Union[torch.nn.Module, Callable[..., Any]],
691
+ concrete_args: Optional[Dict[str, Any]] = None,
692
+ ) -> Graph:
693
+ """
694
+ Trace ``root`` and return the corresponding FX ``Graph`` representation. ``root``
695
+ can either be an ``nn.Module`` instance or a Python callable.
696
+
697
+ Note that after this call, ``self.root`` may be different from the ``root`` passed
698
+ in here. For example, when a free function is passed to ``trace()``, we will
699
+ create an ``nn.Module`` instance to use as the root and add embedded constants
700
+ to.
701
+
702
+
703
+ Args:
704
+
705
+ root (Union[Module, Callable]): Either a ``Module`` or a function to be
706
+ traced through. Backwards-compatibility for this parameter is
707
+ guaranteed.
708
+ concrete_args (Optional[Dict[str, any]]): Concrete arguments that should
709
+ not be treated as Proxies. This parameter is experimental and
710
+ its backwards-compatibility is *NOT* guaranteed.
711
+
712
+ Returns:
713
+
714
+ A ``Graph`` representing the semantics of the passed-in ``root``.
715
+ """
716
+ global _is_fx_tracing_flag
717
+ old_is_fx_tracing_flag = _is_fx_tracing_flag
718
+ _is_fx_tracing_flag = True
719
+ try:
720
+ if isinstance(root, torch.nn.Module):
721
+
722
+ # do real recompilation for _LazyGraphModule before retracing since the trace
723
+ # method can not trace the _lazy_forward method. Got error:
724
+ # https://gist.github.com/shunting314/75549c2e82ae07ac1139c94a3583d259
725
+ # without this.
726
+ from torch.fx._lazy_graph_module import _LazyGraphModule
727
+ _LazyGraphModule.force_recompile(root)
728
+
729
+ self.root = root
730
+
731
+ assert hasattr(
732
+ type(root), self.traced_func_name
733
+ ), f"traced_func_name={self.traced_func_name} doesn't exist in {type(root).__name__}"
734
+
735
+ fn = getattr(type(root), self.traced_func_name)
736
+ self.root_module_name = root._get_name()
737
+ self.submodule_paths = {mod: name for name, mod in root.named_modules()}
738
+ else:
739
+ self.root = torch.nn.Module()
740
+ fn = root
741
+
742
+ tracer_cls: Optional[Type[Tracer]] = getattr(self, "__class__", None)
743
+ self.graph = Graph(tracer_cls=tracer_cls)
744
+ if hasattr(fn, '__code__'):
745
+ code = fn.__code__
746
+ self.graph._co_fields = {
747
+ 'co_name': code.co_name,
748
+ 'co_filename': code.co_filename,
749
+ 'co_firstlineno': code.co_firstlineno,
750
+ }
751
+
752
+ # When we encounter a Tensor value that's not a parameter, we look if it
753
+ # is some other attribute on the model. Construct a dict mapping Tensor
754
+ # values to the qualified name here for efficiency. This is used downstream
755
+ # in create_arg
756
+ self.tensor_attrs: Dict[
757
+ Union[
758
+ torch.Tensor,
759
+ ScriptObject,
760
+ FakeScriptObject
761
+ ], str
762
+ ] = {}
763
+
764
+ def collect_tensor_attrs(m: torch.nn.Module, prefix_atoms: List[str]):
765
+ for k, v in m.__dict__.items():
766
+ if isinstance(v, (torch.Tensor, ScriptObject, FakeScriptObject)):
767
+ self.tensor_attrs[v] = ".".join(prefix_atoms + [k])
768
+ for k, v in m.named_children():
769
+ collect_tensor_attrs(v, prefix_atoms + [k])
770
+
771
+ collect_tensor_attrs(self.root, [])
772
+
773
+ assert isinstance(fn, FunctionType)
774
+
775
+ fn_globals = fn.__globals__ # run before it gets patched
776
+ fn, args = self.create_args_for_root(
777
+ fn, isinstance(root, torch.nn.Module), concrete_args
778
+ )
779
+
780
+ parameter_proxy_cache: Dict[
781
+ str, Proxy
782
+ ] = {} # Reduce number of get_attr calls
783
+
784
+ # Method dispatch on parameters is not recorded unless it's directly used.
785
+ # Thus, we need to insert a proxy when __getattr__ requests a parameter.
786
+ @functools.wraps(_orig_module_getattr)
787
+ def module_getattr_wrapper(mod, attr):
788
+ attr_val = _orig_module_getattr(mod, attr)
789
+ return self.getattr(attr, attr_val, parameter_proxy_cache)
790
+
791
+ @functools.wraps(_orig_module_call)
792
+ def module_call_wrapper(mod, *args, **kwargs):
793
+ def forward(*args, **kwargs):
794
+ return _orig_module_call(mod, *args, **kwargs)
795
+
796
+ _autowrap_check(
797
+ patcher, # type: ignore[has-type]
798
+ getattr(getattr(mod, "forward", mod), "__globals__", {}),
799
+ self._autowrap_function_ids,
800
+ )
801
+ return self.call_module(mod, forward, args, kwargs)
802
+
803
+ with _new_patcher() as patcher:
804
+ # allow duplicate patches to support the case of nested calls
805
+ patcher.patch_method(
806
+ torch.nn.Module,
807
+ "__getattr__",
808
+ module_getattr_wrapper,
809
+ deduplicate=False,
810
+ )
811
+ patcher.patch_method(
812
+ torch.nn.Module, "__call__", module_call_wrapper, deduplicate=False
813
+ )
814
+ _patch_wrapped_functions(patcher)
815
+ _autowrap_check(patcher, fn_globals, self._autowrap_function_ids)
816
+ for module in self._autowrap_search:
817
+ _autowrap_check(
818
+ patcher, module.__dict__, self._autowrap_function_ids
819
+ )
820
+ self.create_node(
821
+ "output",
822
+ "output",
823
+ (self.create_arg(fn(*args)),),
824
+ {},
825
+ type_expr=fn.__annotations__.get("return", None),
826
+ )
827
+
828
+ self.submodule_paths = None
829
+ finally:
830
+ _is_fx_tracing_flag = old_is_fx_tracing_flag
831
+ return self.graph
832
+
833
+ def __deepcopy__(self, memo):
834
+ # _autowrap_search contains modules, which cannot be deepcopied.
835
+ new_tracer = Tracer.__new__(Tracer)
836
+
837
+ for k, v in self.__dict__.items():
838
+ if k in {'_autowrap_search'}:
839
+ new_obj = copy.copy(v)
840
+ else:
841
+ new_obj = copy.deepcopy(v, memo)
842
+
843
+ new_tracer.__dict__[k] = new_obj
844
+
845
+ return new_tracer
846
+
847
+ def _proxy_placeholder(self, name, concrete_args, sig, fn_for_analysis):
848
+ if concrete_args is not None and name in concrete_args:
849
+ cnt = 0
850
+
851
+ def replace_ph(x):
852
+ nonlocal cnt
853
+ cnt += 1
854
+ param = sig.parameters[name]
855
+ default = (
856
+ ()
857
+ if param.default is inspect.Parameter.empty
858
+ else (param.default,)
859
+ )
860
+ out = self.create_proxy(
861
+ "placeholder", f"{name}_{str(cnt)}", default, {}
862
+ )
863
+ if isinstance(x, PHBase):
864
+ if x != PH:
865
+ # Transfer attrs in the case where you're using a placeholder other
866
+ # than the singleton PH (PH has no attributes to transfer).
867
+ # Proxies were created out of the placeholders.
868
+ # Transfer any metadata (put on the placeholders in the form of
869
+ # attributes set by the user) from the placeholder to the
870
+ # underlying nodes (the proxy is unwrapped by the user, but
871
+ # the metadata should hold).
872
+ _transfer_attrs(fr=x, to=out.node)
873
+
874
+ return out
875
+ # Union[int, bool] == bool in Python <= 3.6
876
+ if (
877
+ type(x) == bool
878
+ or type(x) in base_types
879
+ and type(x) != torch.Tensor
880
+ ):
881
+ torch._assert(
882
+ out == x,
883
+ f"{name} has been specialized to have value {x} but got another value",
884
+ )
885
+ elif x is None:
886
+ args = (
887
+ out,
888
+ f"{name} has been specialized to have value None but got another value",
889
+ )
890
+ self.create_proxy("call_function", _assert_is_none, args, {})
891
+ else:
892
+ warnings.warn(
893
+ f"Was not able to add assertion to guarantee correct input {name} to "
894
+ f"specialized function. It is up to the user to make sure that your inputs match the "
895
+ f"inputs you specialized the function with."
896
+ )
897
+
898
+ return x
899
+
900
+ return pytree.tree_map(replace_ph, concrete_args[name])
901
+ if name[0] == "*":
902
+ default = ()
903
+ else:
904
+ param = sig.parameters[name]
905
+ default = () if param.default is inspect.Parameter.empty else (param.default,) # type: ignore[assignment]
906
+ return self.create_proxy(
907
+ "placeholder",
908
+ name,
909
+ default,
910
+ {},
911
+ type_expr=fn_for_analysis.__annotations__.get(name, None)
912
+ )
913
+
914
+
915
+ # Dictionary of (id(globals dict), function name) => globals_dict to patch for
916
+ # the purposes of the wrap() API.
917
+ # We key by the globals dict id and function name to ensure we're wrapping a given
918
+ # function only once.
919
+ _wrapped_fns_to_patch: Dict[Tuple[int, str], dict] = {}
920
+
921
+ # List of methods on classes to wrap (class type, function name)
922
+ # this currently only works for Tensor.* methods that aren't traced properly
923
+ _wrapped_methods_to_patch: List[Tuple[type, str]] = []
924
+
925
+ if os.environ.get("FX_PATCH_GETITEM") == "1":
926
+ # This change is needed to trace models like PositionalEmbedding from BERT:
927
+ # https://github.com/pytorch/benchmark/blob/master/torchbenchmark/models/BERT_pytorch/bert_pytorch/model/embedding/position.py
928
+ # but causes issues in quantization documented here:
929
+ # https://github.com/pytorch/pytorch/issues/50710
930
+ # once that is fixed we can make this the default behavior.
931
+ _wrapped_methods_to_patch.append((torch.Tensor, "__getitem__"))
932
+
933
+
934
+ def _find_proxy(*objects_to_search):
935
+ """
936
+ Recursively search a data structure for a Proxy() and return it,
937
+ return None if not found.
938
+ """
939
+ proxy = None
940
+
941
+ def find_proxy(x):
942
+ nonlocal proxy
943
+ if isinstance(x, Proxy):
944
+ proxy = x
945
+
946
+ map_aggregate(objects_to_search, find_proxy)
947
+ return proxy
948
+
949
+
950
+ def _create_wrapped_func(orig_fn):
951
+ @functools.wraps(orig_fn)
952
+ def wrapped(*args, **kwargs):
953
+ """
954
+ Given an closed-over ``orig_function`` to invoke, search the args and kwargs for
955
+ a Proxy object. If there is one, emit a ``call_function`` node to preserve the
956
+ call to this leaf function directly. Otherwise, just return the results of
957
+ this function call, as this function is not being traced.
958
+ """
959
+ proxy = _find_proxy(args, kwargs)
960
+ if proxy is not None:
961
+ return_proxy = proxy.tracer.create_proxy(
962
+ "call_function", orig_fn, args, kwargs
963
+ )
964
+ return_proxy.node.meta["is_wrapped"] = True
965
+ return return_proxy
966
+ return orig_fn(*args, **kwargs)
967
+
968
+ return wrapped
969
+
970
+
971
+ def _create_wrapped_method(cls, name):
972
+ orig_fn = getattr(cls, name)
973
+
974
+ @functools.wraps(orig_fn)
975
+ def wrapped(*args, **kwargs):
976
+ """
977
+ Search the args and kwargs for a Proxy object. If there is one,
978
+ emit a ``call_method`` node to preserve the call to this method
979
+ directly. Otherwise, just return the results of this function
980
+ call, as this function is not being traced.
981
+ """
982
+ proxy = _find_proxy(args, kwargs)
983
+ if proxy is not None:
984
+ return proxy.tracer.create_proxy("call_method", name, args, kwargs)
985
+ return orig_fn(*args, **kwargs)
986
+
987
+ return wrapped
988
+
989
+
990
+ class _PatchedFn(NamedTuple):
991
+ frame_dict: Any
992
+ fn_name: str
993
+ orig_fn: Any
994
+ new_fn: Any
995
+
996
+ def revert(self):
997
+ raise NotImplementedError
998
+
999
+ def patch(self):
1000
+ raise NotImplementedError
1001
+
1002
+
1003
+ class _PatchedFnSetItem(_PatchedFn):
1004
+ def revert(self):
1005
+ self.frame_dict[self.fn_name] = self.orig_fn
1006
+
1007
+ def patch(self):
1008
+ self.frame_dict[self.fn_name] = self.new_fn
1009
+
1010
+ class _PatchedFnDel(_PatchedFn):
1011
+ def revert(self):
1012
+ del self.frame_dict[self.fn_name]
1013
+
1014
+ def patch(self):
1015
+ self.frame_dict[self.fn_name] = self.new_fn
1016
+
1017
+
1018
+ class _PatchedFnSetAttr(_PatchedFn):
1019
+ def revert(self):
1020
+ setattr(self.frame_dict, self.fn_name, self.orig_fn)
1021
+
1022
+ def patch(self):
1023
+ setattr(self.frame_dict, self.fn_name, self.new_fn)
1024
+
1025
+ class _Patcher:
1026
+ def __init__(self) -> None:
1027
+ super().__init__()
1028
+ self.patches_made: List[_PatchedFn] = []
1029
+ self.visited: Set[int] = set()
1030
+
1031
+ def patch(
1032
+ self,
1033
+ frame_dict: Dict[str, Any],
1034
+ name: str,
1035
+ new_fn: Callable,
1036
+ deduplicate: bool = True,
1037
+ ):
1038
+ """
1039
+ Replace frame_dict[name] with new_fn until we exit the context manager.
1040
+ """
1041
+ new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined]
1042
+ if name not in frame_dict and hasattr(builtins, name):
1043
+ self.patches_made.append(_PatchedFnDel(frame_dict, name, None, new_fn))
1044
+ self.patches_made[-1].patch()
1045
+ elif getattr(frame_dict[name], "__fx_already_patched", False):
1046
+ return # already patched, no need to do it again
1047
+ else:
1048
+ self.patches_made.append(
1049
+ _PatchedFnSetItem(frame_dict, name, frame_dict[name], new_fn)
1050
+ )
1051
+ self.patches_made[-1].patch()
1052
+
1053
+ def patch_method(
1054
+ self, cls: type, name: str, new_fn: Callable, deduplicate: bool = True
1055
+ ):
1056
+ """
1057
+ Replace object_or_dict.name with new_fn until we exit the context manager.
1058
+ """
1059
+ new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined]
1060
+ orig_fn = getattr(cls, name)
1061
+ if getattr(orig_fn, "__fx_already_patched", False):
1062
+ return # already patched, no need to do it again
1063
+ self.patches_made.append(_PatchedFnSetAttr(cls, name, orig_fn, new_fn))
1064
+ self.patches_made[-1].patch()
1065
+
1066
+ def visit_once(self, thing: Any):
1067
+ """Return True on the first call to with thing, otherwise false"""
1068
+ idx = id(thing)
1069
+ if idx in self.visited:
1070
+ return False
1071
+ self.visited.add(idx)
1072
+ return True
1073
+
1074
+ def revert_all_patches(self):
1075
+ """
1076
+ Remove all the stored patcheds. It doesn't modify patches_made.
1077
+ """
1078
+ for patch in self.patches_made:
1079
+ patch.revert()
1080
+ return self.patches_made
1081
+
1082
+ def reapply_all_patches(self):
1083
+ """
1084
+ Patch all the stored patcheds. It doesn't modify patches_made.
1085
+ """
1086
+ for patch in self.patches_made:
1087
+ patch.patch()
1088
+ return self.patches_made
1089
+
1090
+ def __enter__(self):
1091
+ return self
1092
+
1093
+ def __exit__(self, exc_type, exc_val, exc_tb):
1094
+ """
1095
+ Undo all the changes made via self.patch() and self.patch_method()
1096
+ """
1097
+ while self.patches_made:
1098
+ # unpatch in reverse order to handle duplicates correctly
1099
+ self.patches_made.pop().revert()
1100
+ self.visited.clear()
1101
+
1102
+
1103
+ CURRENT_PATCHER: Optional[_Patcher] = None
1104
+
1105
+ @contextlib.contextmanager
1106
+ def _new_patcher():
1107
+ global CURRENT_PATCHER
1108
+ prior_patcher = CURRENT_PATCHER
1109
+ try:
1110
+ CURRENT_PATCHER = _Patcher()
1111
+ yield CURRENT_PATCHER
1112
+ finally:
1113
+ # Clear all the patches made by when using current patcher.
1114
+ assert CURRENT_PATCHER is not None
1115
+ CURRENT_PATCHER.revert_all_patches()
1116
+ CURRENT_PATCHER = prior_patcher
1117
+
1118
+
1119
+ @contextlib.contextmanager
1120
+ def _maybe_revert_all_patches():
1121
+ current_patcher = CURRENT_PATCHER
1122
+ patches_made = None
1123
+ patches_removed = None
1124
+ try:
1125
+ if current_patcher is not None:
1126
+ patches_removed = current_patcher.revert_all_patches()
1127
+ yield
1128
+ finally:
1129
+ if current_patcher is not None:
1130
+ patches_made = current_patcher.reapply_all_patches()
1131
+ assert patches_made == patches_removed, "CURRENT_PATCHER was changed during a revert_all_patches"
1132
+
1133
+ def _patch_wrapped_functions(patcher: _Patcher):
1134
+ """
1135
+ Go through ``_wrapped_fn_patch_table`` and, for each frame object, wrap
1136
+ the listed global functions in the `_create_wrapped_func` wrapper.
1137
+ """
1138
+ for (_, name), frame_dict in _wrapped_fns_to_patch.copy().items():
1139
+ if name not in frame_dict and hasattr(builtins, name):
1140
+ orig_fn = getattr(builtins, name)
1141
+ else:
1142
+ orig_fn = frame_dict[name]
1143
+ patcher.patch(frame_dict, name, _create_wrapped_func(orig_fn))
1144
+
1145
+ for cls, name in _wrapped_methods_to_patch:
1146
+ patcher.patch_method(cls, name, _create_wrapped_method(cls, name))
1147
+
1148
+
1149
+ def _autowrap_check(
1150
+ patcher: _Patcher, frame_dict: Dict[str, Any], function_ids: Set[int]
1151
+ ):
1152
+ """
1153
+ Some methods, like `math.sqrt` are common enough we want to automatically wrap them as we see them.
1154
+ This method searches a scope for them and patches them if found.
1155
+ """
1156
+ if patcher.visit_once(frame_dict):
1157
+ for name, value in frame_dict.items():
1158
+ if (
1159
+ not name.startswith("_")
1160
+ and callable(value)
1161
+ and id(value) in function_ids
1162
+ ):
1163
+ patcher.patch(frame_dict, name, _create_wrapped_func(value))
1164
+
1165
+
1166
+ @compatibility(is_backward_compatible=True)
1167
+ def wrap(fn_or_name: Union[str, Callable]):
1168
+ """
1169
+ This function can be called at module-level scope to register fn_or_name as a "leaf function".
1170
+ A "leaf function" will be preserved as a CallFunction node in the FX trace instead of being
1171
+ traced through::
1172
+
1173
+ # foo/bar/baz.py
1174
+ def my_custom_function(x, y):
1175
+ return x * x + y * y
1176
+
1177
+ torch.fx.wrap('my_custom_function')
1178
+
1179
+ def fn_to_be_traced(x, y):
1180
+ # When symbolic tracing, the below call to my_custom_function will be inserted into
1181
+ # the graph rather than tracing it.
1182
+ return my_custom_function(x, y)
1183
+
1184
+ This function can also equivalently be used as a decorator::
1185
+
1186
+ # foo/bar/baz.py
1187
+ @torch.fx.wrap
1188
+ def my_custom_function(x, y):
1189
+ return x * x + y * y
1190
+
1191
+ A wrapped function can be thought of a "leaf function", analogous to the concept of
1192
+ "leaf modules", that is, they are functions that are left as calls in the FX trace
1193
+ rather than traced through.
1194
+
1195
+ Args:
1196
+
1197
+ fn_or_name (Union[str, Callable]): The function or name of the global function to insert into the
1198
+ graph when it's called
1199
+ """
1200
+ if not callable(fn_or_name) and not isinstance(fn_or_name, str):
1201
+ raise RuntimeError(
1202
+ "Unsupported type for global function! Must be either a callable or "
1203
+ "string name"
1204
+ )
1205
+
1206
+ if callable(fn_or_name):
1207
+ assert not isinstance(fn_or_name, str) # to make mypy happy
1208
+ fn_name = fn_or_name.__name__
1209
+ else:
1210
+ assert isinstance(
1211
+ fn_or_name, str
1212
+ ), "fn_or_name must be a global function or string name"
1213
+ fn_name = fn_or_name
1214
+
1215
+ currentframe = inspect.currentframe()
1216
+ assert currentframe is not None
1217
+ f = currentframe.f_back
1218
+ assert f is not None
1219
+ if f.f_code.co_name != "<module>":
1220
+ raise NotImplementedError("wrap must be called at the top level of a module")
1221
+
1222
+ # consider implementing Callable version of this via _autowrap_function_ids / _autowrap_search
1223
+ # semantics would be slightly different, but would add support `from x import wrapped_function`
1224
+ _wrapped_fns_to_patch[(id(f.f_globals), fn_name)] = f.f_globals
1225
+ return fn_or_name
1226
+
1227
+
1228
+ @compatibility(is_backward_compatible=True)
1229
+ def symbolic_trace(
1230
+ root: Union[torch.nn.Module, Callable[..., Any]],
1231
+ concrete_args: Optional[Dict[str, Any]] = None,
1232
+ ) -> GraphModule:
1233
+ """
1234
+ Symbolic tracing API
1235
+
1236
+ Given an ``nn.Module`` or function instance ``root``, this function will return a ``GraphModule``
1237
+ constructed by recording operations seen while tracing through ``root``.
1238
+
1239
+ ``concrete_args`` allows you to partially specialize your function, whether it's to remove control flow or data structures.
1240
+
1241
+ For example::
1242
+
1243
+ def f(a, b):
1244
+ if b == True:
1245
+ return a
1246
+ else:
1247
+ return a*2
1248
+
1249
+ FX can typically not trace through this due to the presence of control
1250
+ flow. However, we can use `concrete_args` to specialize on the value of
1251
+ `b` to trace through this::
1252
+
1253
+ f = fx.symbolic_trace(f, concrete_args={'b': False})
1254
+ assert f(3, False) == 6
1255
+
1256
+ Note that although you can still pass in different values of `b`, they will be ignored.
1257
+
1258
+ We can also use `concrete_args` to eliminate data-structure handling from
1259
+ our function. This will use pytrees to flatten your input. To avoid
1260
+ overspecializing, pass in `fx.PH` for values that shouldn't be
1261
+ specialized. For example::
1262
+
1263
+ def f(x):
1264
+ out = 0
1265
+ for v in x.values():
1266
+ out += v
1267
+ return out
1268
+ f = fx.symbolic_trace(f, concrete_args={'x': {'a': fx.PH, 'b': fx.PH, 'c': fx.PH}})
1269
+ assert f({'a': 1, 'b': 2, 'c': 4}) == 7
1270
+
1271
+
1272
+ Args:
1273
+ root (Union[torch.nn.Module, Callable]): Module or function to be traced and converted
1274
+ into a Graph representation.
1275
+ concrete_args (Optional[Dict[str, any]]): Inputs to be partially specialized
1276
+
1277
+ Returns:
1278
+ GraphModule: a Module created from the recorded operations from ``root``.
1279
+ """
1280
+ tracer = Tracer()
1281
+ graph = tracer.trace(root, concrete_args)
1282
+ name = (
1283
+ root.__class__.__name__ if isinstance(root, torch.nn.Module) else root.__name__
1284
+ )
1285
+ return _make_graph_module(tracer.root, graph, name)
1286
+
1287
+
1288
+ @wrap
1289
+ def _assert_is_none(value, msg):
1290
+ assert value is None, msg
mplug_owl2/lib/python3.10/site-packages/torch/fx/_utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import sys
3
+ from typing import Dict, Optional
4
+
5
+ import torch
6
+ from torch._logging import LazyString
7
+
8
+
9
+ def lazy_format_graph_code(name, gm, maybe_id=None, **kwargs):
10
+ """
11
+ Returns a LazyString that formats the graph code.
12
+ """
13
+
14
+ def format_name():
15
+ if maybe_id is not None:
16
+ return f"{name} {maybe_id}"
17
+ else:
18
+ return name
19
+
20
+ if "print_output" not in kwargs:
21
+ kwargs["print_output"] = False
22
+
23
+ if "colored" in kwargs and not sys.stdout.isatty():
24
+ kwargs["colored"] = False
25
+
26
+ return LazyString(
27
+ lambda: _format_graph_code(
28
+ f"===== {format_name()} =====\n",
29
+ gm.forward.__code__.co_filename,
30
+ gm.print_readable(**kwargs),
31
+ )
32
+ )
33
+
34
+
35
+ def _format_graph_code(name, filename, graph_str):
36
+ """
37
+ Returns a string that formats the graph code.
38
+ """
39
+ return f"TRACED GRAPH\n {name} {filename} {graph_str}\n"
40
+
41
+
42
+ def first_call_function_nn_module_stack(graph: torch.fx.Graph) -> Optional[Dict]:
43
+ """
44
+ Returns the nn_module_stack of the first call_function node.
45
+ """
46
+ for node in graph.nodes:
47
+ if node.op == "call_function" and "nn_module_stack" in node.meta:
48
+ return node.meta["nn_module_stack"]
49
+ return None
50
+
51
+
52
+ def get_node_context(node, num_nodes=2) -> str:
53
+ """
54
+ Returns a string of the last num_nodes nodes in the graph.
55
+ """
56
+ node_contexts = []
57
+ cur = node
58
+ for i in range(num_nodes):
59
+ node_contexts.append(cur.format_node())
60
+ if cur.op == "root":
61
+ break
62
+ cur = cur.prev
63
+ return "\n".join(node_contexts[::-1])
mplug_owl2/lib/python3.10/site-packages/torch/fx/annotate.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from torch.fx.proxy import Proxy
3
+ from ._compatibility import compatibility
4
+
5
+ @compatibility(is_backward_compatible=False)
6
+ def annotate(val, type):
7
+ """
8
+ Annotates a Proxy object with a given type.
9
+
10
+ This function annotates a val with a given type if a type of the val is a torch.fx.Proxy object
11
+ Args:
12
+ val (object): An object to be annotated if its type is torch.fx.Proxy.
13
+ type (object): A type to be assigned to a given proxy object as val.
14
+ Returns:
15
+ The given val.
16
+ Raises:
17
+ RuntimeError: If a val already has a type in its node.
18
+ """
19
+ if isinstance(val, Proxy):
20
+ if val.node.type:
21
+ raise RuntimeError(f"Tried to annotate a value that already had a type on it!"
22
+ f" Existing type is {val.node.type} "
23
+ f"and new type is {type}. "
24
+ f"This could happen if you tried to annotate a function parameter "
25
+ f"value (in which case you should use the type slot "
26
+ f"on the function signature) or you called "
27
+ f"annotate on the same value twice")
28
+ else:
29
+ val.node.type = type
30
+ return val
31
+ else:
32
+ return val
mplug_owl2/lib/python3.10/site-packages/torch/fx/config.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Whether to disable showing progress on compilation passes
2
+ # Need to add a new config otherwise wil get a circular import if dynamo config is imported here
3
+ disable_progress = True
4
+
5
+ # If True this also shows the node names in each pass, for small models this is great but larger models it's quite noisy
6
+ verbose_progress = False
mplug_owl2/lib/python3.10/site-packages/torch/fx/graph.py ADDED
@@ -0,0 +1,1796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torch._C import _NodeIter
8
+
9
+ import os
10
+ import contextlib
11
+ from typing import TYPE_CHECKING, Callable, Any, List, Dict, NamedTuple, Optional, Tuple, Set, FrozenSet, Type, Iterable
12
+ from dataclasses import dataclass
13
+ from contextlib import contextmanager
14
+ import copy
15
+ import enum
16
+ import torch
17
+ import keyword
18
+ import re
19
+ import builtins
20
+ import math
21
+ import warnings
22
+ import inspect
23
+
24
+ __all__ = ["PythonCode", "CodeGen", "Graph"]
25
+
26
+ if TYPE_CHECKING:
27
+ from .graph_module import GraphModule # noqa: F401
28
+ from ._symbolic_trace import Tracer # noqa: F401
29
+
30
+
31
+ # Mapping of builtins to their `typing` equivalent.
32
+ _origin_type_map = {
33
+ list: List,
34
+ dict: Dict,
35
+ set: Set,
36
+ frozenset: FrozenSet,
37
+ tuple: Tuple,
38
+ }
39
+
40
+
41
+ # Signature for functions thattransforms the body (`list[str]`) of the
42
+ # generated code
43
+ TransformCodeFunc = Callable[[List[str]], List[str]]
44
+
45
+
46
+ class _CustomBuiltin(NamedTuple):
47
+ """Additional objs that we add to every graph's globals.
48
+
49
+ The repr() for some standard library objects is not valid Python code without
50
+ an import. For common objects of this sort, we bundle them in the globals of
51
+ every FX graph.
52
+ """
53
+ # How to import this object from the standard library.
54
+ import_str: str
55
+ # The actual object, produced from that import string.
56
+ obj: Any
57
+
58
+ _custom_builtins: Dict[str, _CustomBuiltin] = {}
59
+
60
+
61
+ def _register_custom_builtin(name: str, import_str: str, obj: Any):
62
+ _custom_builtins[name] = _CustomBuiltin(import_str, obj)
63
+
64
+
65
+ _register_custom_builtin('inf', 'from math import inf', math.inf)
66
+ _register_custom_builtin('nan', 'from math import nan', math.nan)
67
+ _register_custom_builtin('NoneType', 'NoneType = type(None)', type(None))
68
+ _register_custom_builtin('torch', 'import torch', torch)
69
+ _register_custom_builtin('device', 'from torch import device', torch.device)
70
+ _register_custom_builtin('fx_pytree', 'import torch.fx._pytree as fx_pytree', fx_pytree)
71
+ _register_custom_builtin('pytree', 'import torch.utils._pytree as pytree', pytree)
72
+
73
+
74
+ def _is_magic(x: str) -> bool:
75
+ return x.startswith('__') and x.endswith('__')
76
+
77
+
78
+ def _snake_case(s: str) -> str:
79
+ """
80
+ Transforms the given string ``s`` to a Python-style variable name
81
+
82
+ Examples:
83
+ ``mod.snake_case`` -> ``mod.snake_case``
84
+ ``mod.pascalCase``-> ``mod.pascal_case``
85
+ ``mod.ALL_CAPS`` -> ``mod.all_caps``
86
+ """
87
+ chars = []
88
+ prev_lower = False
89
+ for c in s:
90
+ if prev_lower and c.isupper():
91
+ chars.append('_')
92
+ chars.append(c.lower())
93
+ prev_lower = c.islower()
94
+ return ''.join(chars)
95
+
96
+
97
+ def _is_from_torch(obj: Any) -> bool:
98
+ module_name = getattr(obj, '__module__', None)
99
+ if module_name is not None:
100
+ base_module = module_name.partition('.')[0]
101
+ return (
102
+ base_module == 'torch' and
103
+ not module_name.startswith("torch._dynamo.") and
104
+ not module_name.startswith("torch._inductor.")
105
+ )
106
+
107
+ name = getattr(obj, '__name__', None)
108
+ # exclude torch because torch.torch.torch.torch works. idk mang
109
+ if name is not None and name != 'torch':
110
+ for guess in [torch, torch.nn.functional]:
111
+ if getattr(guess, name, None) is obj:
112
+ return True
113
+
114
+ return False
115
+
116
+
117
+ class _Namespace:
118
+ """A context for associating names uniquely with objects.
119
+
120
+ The following invariants are enforced:
121
+ - Each object gets a single name.
122
+ - Each name is unique within a given namespace.
123
+ - Names generated do not shadow builtins, unless the object is indeed that builtin.
124
+ """
125
+ def __init__(self):
126
+ self._obj_to_name: Dict[Any, str] = {}
127
+ self._unassociated_names = set()
128
+ self._used_names: Set[str] = set()
129
+ self._base_count: Dict[str, int] = defaultdict(int)
130
+
131
+ self._illegal_char_regex = re.compile('[^0-9a-zA-Z_]+')
132
+ self._name_suffix_regex = re.compile(r"(.*)_(\d+)$")
133
+
134
+ def create_name(self, candidate: str, obj: Optional[Any]) -> str:
135
+ """Create a unique name.
136
+
137
+ Arguments:
138
+ candidate: used as the basis for the unique name, relevant to the user.
139
+ obj: If not None, an object that will be associated with the unique name.
140
+ """
141
+ if obj is not None and obj in self._obj_to_name:
142
+ return self._obj_to_name[obj]
143
+
144
+ # delete all characters that are illegal in a Python identifier
145
+ candidate = self._illegal_char_regex.sub('_', candidate)
146
+
147
+ if not candidate:
148
+ candidate = '_unnamed'
149
+
150
+ if candidate[0].isdigit():
151
+ candidate = f'_{candidate}'
152
+
153
+ match = self._name_suffix_regex.match(candidate)
154
+ if match is None:
155
+ base = candidate
156
+ num = None
157
+ else:
158
+ base, num_str = match.group(1, 2)
159
+ num = int(num_str)
160
+
161
+ candidate = base if num is None else f'{base}_{num}'
162
+ if not num:
163
+ num = self._base_count[base]
164
+
165
+ while candidate in self._used_names or self._is_illegal_name(candidate, obj):
166
+ num += 1
167
+ candidate = f'{base}_{num}'
168
+
169
+ self._used_names.add(candidate)
170
+ self._base_count[base] = num
171
+ if obj is None:
172
+ self._unassociated_names.add(candidate)
173
+ else:
174
+ self._obj_to_name[obj] = candidate
175
+ return candidate
176
+
177
+ def associate_name_with_obj(self, name: str, obj: Any):
178
+ """Associate a unique name with an object.
179
+
180
+ Neither `name` nor `obj` should be associated already.
181
+ """
182
+ assert obj not in self._obj_to_name
183
+ assert name in self._unassociated_names
184
+ self._obj_to_name[obj] = name
185
+ self._unassociated_names.remove(name)
186
+
187
+ def _is_illegal_name(self, name: str, obj: Any) -> bool:
188
+ # 1. keywords are never allowed as names.
189
+ if name in keyword.kwlist:
190
+ return True
191
+
192
+ # 2. Can't shadow a builtin name, unless you *are* that builtin.
193
+ if name in builtins.__dict__:
194
+ return obj is not builtins.__dict__[name]
195
+
196
+ # 3. Can't shadow our custom builtins either
197
+ if name in _custom_builtins:
198
+ return obj is not _custom_builtins[name].obj
199
+
200
+ return False
201
+
202
+ def _rename_object(self, obj: Any, name: str):
203
+ assert obj in self._obj_to_name
204
+ self._obj_to_name[obj] = name
205
+ self._used_names.add(name)
206
+
207
+ dtype_abbrs = {
208
+ torch.bfloat16: 'bf16',
209
+ torch.float64: 'f64',
210
+ torch.float32: 'f32',
211
+ torch.float16: 'f16',
212
+ torch.float8_e4m3fn: 'f8e4m3fn',
213
+ torch.float8_e5m2: 'f8e5m2',
214
+ torch.float8_e4m3fnuz: 'f8e4m3fnuz',
215
+ torch.float8_e5m2fnuz: 'f8e5m2fnuz',
216
+ torch.complex32: 'c32',
217
+ torch.complex64: 'c64',
218
+ torch.complex128: 'c128',
219
+ torch.int8: 'i8',
220
+ torch.int16: 'i16',
221
+ torch.int32: 'i32',
222
+ torch.int64: 'i64',
223
+ torch.bool: 'b8',
224
+ torch.uint8: 'u8',
225
+ torch.uint16: 'u16',
226
+ torch.uint32: 'u32',
227
+ torch.uint64: 'u64',
228
+ torch.bits16: 'b16',
229
+ }
230
+
231
+ @compatibility(is_backward_compatible=True)
232
+ @dataclass
233
+ class PythonCode:
234
+ """
235
+ Represents all the information necessary to exec or save a graph as Python code.
236
+ """
237
+ # Python source code for the forward function definition.
238
+ src: str
239
+ # Values in global scope during execution of `src_def`.
240
+ globals: Dict[str, Any]
241
+ # Optional mapping from the forward function's line number to
242
+ # node index.
243
+ _lineno_map: Optional[Dict[int, Optional[int]]]
244
+
245
+
246
+ def _format_target(base: str, target: str) -> str:
247
+ elems = target.split('.')
248
+ r = base
249
+ for e in elems:
250
+ if not e.isidentifier():
251
+ r = f'getattr({r}, "{e}")'
252
+ else:
253
+ r = f'{r}.{e}'
254
+ return r
255
+
256
+ class _InsertPoint:
257
+ def __init__(self, graph, new_insert):
258
+ self.graph = graph
259
+ self.orig_insert, graph._insert = graph._insert, new_insert
260
+
261
+ def __enter__(self):
262
+ pass
263
+
264
+ def __exit__(self, type, value, tb):
265
+ self.graph._insert = self.orig_insert
266
+
267
+ class _node_list:
268
+ def __init__(self, graph: 'Graph', direction: str = '_next'):
269
+ assert direction in ['_next', '_prev']
270
+ self.graph = graph
271
+ self.direction = direction
272
+
273
+ def __len__(self):
274
+ return self.graph._len
275
+
276
+ def __iter__(self):
277
+ assert self.direction == "_prev" or self.direction == "_next"
278
+ yield from _NodeIter(self.graph._root, self.direction == "_prev")
279
+
280
+ def __reversed__(self):
281
+ return _node_list(self.graph, '_next' if self.direction == '_prev' else '_prev')
282
+
283
+ class _PyTreeInfo(NamedTuple):
284
+ """
285
+ Contains extra info stored when we're using Pytrees
286
+ """
287
+ orig_args: List[str]
288
+ in_spec: pytree.TreeSpec
289
+ out_spec: Optional[pytree.TreeSpec]
290
+
291
+ @dataclass(frozen=True)
292
+ class _ParsedStackTrace:
293
+ """
294
+ Represents the top-most frame of a parsed stack trace
295
+ """
296
+ file: str
297
+ lineno: str
298
+ name: str
299
+ code: str
300
+
301
+ def get_summary_str(self):
302
+ return f'File: {self.file}:{self.lineno} in {self.name}, code: {self.code}'
303
+
304
+ # get File:lineno code from stack_trace
305
+ def _parse_stack_trace(stack_trace: str):
306
+ if stack_trace is None:
307
+ return None
308
+ pattern = re.compile(r"^File \"(.+)\", line (\d+), in (.+)$")
309
+ lines = stack_trace.strip().split('\n')
310
+ # stacktrace should have innermost frame last, so we
311
+ # iterate backwards to find the first line that starts
312
+ # with 'File '
313
+ summary_str = ""
314
+ for idx in range(len(lines) - 2, -1, -1):
315
+ line = lines[idx].strip()
316
+ matches = pattern.match(line)
317
+ if matches:
318
+ file = matches.group(1)
319
+ lineno = matches.group(2)
320
+ name = matches.group(3)
321
+ # next line should be the code
322
+ code = lines[idx + 1].strip()
323
+ return _ParsedStackTrace(file, lineno, name, code)
324
+ return None
325
+
326
+ @compatibility(is_backward_compatible=False)
327
+ class CodeGen:
328
+ def __init__(self):
329
+ self._body_transformer: Optional[TransformCodeFunc] = None
330
+ self._func_name: str = "forward"
331
+
332
+ def gen_fn_def(self, free_vars: List[str], maybe_return_annotation: str) -> str:
333
+ """
334
+ Given the free variables and a return annotation, generates the beginning of the FX function.
335
+ By default, `gen_fn_def(['a', 'b'], '') == 'def {self._func_name}(a, b):'`
336
+ """
337
+ # If the original function didn't have self as its first argument, we
338
+ # would have added it.
339
+ if len(free_vars) == 0 or free_vars[0] != 'self':
340
+ free_vars.insert(0, 'self')
341
+ return f"def {self._func_name}({', '.join(free_vars)}){maybe_return_annotation}:"
342
+
343
+ def generate_output(self, output_args: Argument) -> str:
344
+ """
345
+ Given the output arguments, generates the return statement of the FX function.
346
+ Note: The returned statement should not be indented.
347
+ """
348
+ return f'return {repr(output_args)}'
349
+
350
+ def process_inputs(self, *args: Any) -> Any:
351
+ """
352
+ Transforms the inputs so that the graph can take them as arguments, as
353
+ non-default codegen may result in the inputs to the function being
354
+ different from the inputs to the graph.
355
+
356
+ If the graph was directly runnable, this invariant should hold true
357
+ `f.graph.process_outputs(f.graph(*f.graph.process_inputs(*inputs))) == f(*inputs)`
358
+ """
359
+ return args
360
+
361
+ def process_outputs(self, outputs: Any) -> Any:
362
+ """
363
+ Transforms the outputs of the graph to be identical to the codegen.
364
+
365
+ See ``process_inputs`` for more details.
366
+ """
367
+ return outputs
368
+
369
+ def additional_globals(self) -> List[Tuple[str, Any]]:
370
+ """
371
+ If your codegen uses extra global values, add tuples of (identifier,reference to the value) here.
372
+ For example, return ['List', typing.List] if you need ``List`` in the global context.
373
+ """
374
+ return []
375
+
376
+ def _gen_python_code(
377
+ self, nodes, root_module: str, namespace: _Namespace, *,
378
+ verbose: bool = False, include_stride: bool = False, include_device: bool = False, colored: bool = False
379
+ ) -> PythonCode:
380
+ free_vars: List[str] = []
381
+ body: List[str] = []
382
+ globals_: Dict[str, Any] = {}
383
+ wrapped_fns: Dict[str, None] = {}
384
+
385
+ # Wrap string in list to pass by reference
386
+ maybe_return_annotation : List[str] = ['']
387
+ include_stride = include_stride or (os.environ.get("FX_GRAPH_SHOW_STRIDE", "0") == "1")
388
+ include_device = include_device or (os.environ.get("FX_GRAPH_SHOW_DEVICE", "0") == "1")
389
+
390
+ def add_global(name_hint: str, obj: Any):
391
+ """Add an obj to be tracked as a global.
392
+
393
+ We call this for names that reference objects external to the
394
+ Graph, like functions or types.
395
+
396
+ Returns: the global name that should be used to reference 'obj' in generated source.
397
+ """
398
+ if _is_from_torch(obj) and obj != torch.device: # to support registering torch.device
399
+ # HACK: workaround for how torch custom ops are registered. We
400
+ # can't import them like normal modules so they must retain their
401
+ # fully qualified name.
402
+ return _get_qualified_name(obj)
403
+
404
+ # normalize the name hint to get a proper identifier
405
+ global_name = namespace.create_name(name_hint, obj)
406
+
407
+ if global_name in globals_:
408
+ assert globals_[global_name] is obj
409
+ return global_name
410
+ globals_[global_name] = obj
411
+ return global_name
412
+
413
+ # Pre-fill the globals table with registered builtins.
414
+ for name, (_, obj) in _custom_builtins.items():
415
+ add_global(name, obj)
416
+
417
+ def type_repr(o : Any):
418
+ if o == ():
419
+ # Empty tuple is used for empty tuple type annotation Tuple[()]
420
+ return '()'
421
+
422
+ typename = _type_repr(o)
423
+
424
+ if hasattr(o, '__origin__'):
425
+ # This is a generic type, e.g. typing.List[torch.Tensor]
426
+ origin_type = _origin_type_map.get(o.__origin__, o.__origin__)
427
+ origin_typename = add_global(_type_repr(origin_type), origin_type)
428
+
429
+ if hasattr(o, '__args__'):
430
+ # Assign global names for each of the inner type variables.
431
+ args = [type_repr(arg) for arg in o.__args__]
432
+
433
+ if len(args) == 0:
434
+ # Bare type, such as `typing.Tuple` with no subscript
435
+ # This code-path used in Python < 3.9
436
+ return origin_typename
437
+
438
+ return f'{origin_typename}[{",".join(args)}]'
439
+ else:
440
+ # Bare type, such as `typing.Tuple` with no subscript
441
+ # This code-path used in Python 3.9+
442
+ return origin_typename
443
+
444
+ # Common case: this is a regular module name like 'foo.bar.baz'
445
+ return add_global(typename, o)
446
+
447
+ codes = {
448
+ "yellow": "\033[33m",
449
+ "cyan": "\033[36m",
450
+ "green": "\033[32m",
451
+ "blue": "\033[34m",
452
+ "red": "\033[31m",
453
+ "dim": "\033[2m",
454
+ "dim_blue": "\033[2m\033[34m",
455
+ "dim_green": "\033[2m\033[32m",
456
+ "reset": "\033[0m",
457
+ }
458
+
459
+ def make_wrapper_func(name):
460
+ def f(s):
461
+ if colored:
462
+ return f"{codes[name]}{s}{codes['reset']}"
463
+ return s
464
+ return f
465
+
466
+ yellow = make_wrapper_func("yellow")
467
+ cyan = make_wrapper_func("cyan")
468
+ red = make_wrapper_func("red")
469
+ green = make_wrapper_func("green")
470
+ dim_green = make_wrapper_func("dim_green")
471
+ dim = make_wrapper_func("dim")
472
+ dim_blue = make_wrapper_func("dim_blue")
473
+ blue = make_wrapper_func("blue")
474
+
475
+ def _get_repr(arg: Any) -> str:
476
+ # Handle NamedTuples (if it has `_fields`) via add_global.
477
+ if isinstance(arg, tuple) and hasattr(arg, '_fields'):
478
+ qualified_name = _get_qualified_name(type(arg))
479
+ global_name = add_global(qualified_name, type(arg))
480
+ return f"{global_name}{repr(tuple(arg))}"
481
+ elif isinstance(arg, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)):
482
+ qualified_name = _get_qualified_name(arg)
483
+ global_name = add_global(qualified_name, arg)
484
+ return f"{global_name}"
485
+ elif isinstance(arg, enum.Enum):
486
+ cls = arg.__class__
487
+ clsname = add_global(cls.__name__, cls)
488
+ return f"{clsname}.{arg.name}"
489
+ elif isinstance(arg, Node):
490
+ return repr(arg)
491
+ elif isinstance(arg, torch.Tensor):
492
+ size = list(arg.size())
493
+ dtype = str(arg.dtype).split(".")[-1]
494
+ return f"torch.Tensor(size={size}, dtype={dtype})"
495
+ else:
496
+ return blue(repr(arg))
497
+
498
+
499
+ def _format_args(args: Tuple[Argument, ...], kwargs: Dict[str, Argument]) -> str:
500
+ args_s = ', '.join(_get_repr(a) for a in args)
501
+ kwargs_s = ', '.join(f'{k} = {_get_repr(v)}' for k, v in kwargs.items())
502
+ if args_s and kwargs_s:
503
+ return f'{args_s}, {kwargs_s}'
504
+ return args_s or kwargs_s
505
+
506
+ # Run through reverse nodes and record the first instance of a use
507
+ # of a given node. This represents the *last* use of the node in the
508
+ # execution order of the program, which we will use to free unused
509
+ # values
510
+ node_to_last_use : Dict[Node, Node] = {}
511
+ user_to_last_uses : Dict[Node, List[Node]] = {}
512
+
513
+ def register_last_uses(n : Node, user : Node):
514
+ if n not in node_to_last_use:
515
+ node_to_last_use[n] = user
516
+ user_to_last_uses.setdefault(user, []).append(n)
517
+
518
+ for node in reversed(nodes):
519
+ map_arg(node.args, lambda n: register_last_uses(n, node))
520
+ map_arg(node.kwargs, lambda n: register_last_uses(n, node))
521
+
522
+ def delete_unused_values(user : Node):
523
+ """
524
+ Delete values after their last use. This ensures that values that are
525
+ not used in the remainder of the code are freed and the memory usage
526
+ of the code is optimal.
527
+ """
528
+ if user.op == 'placeholder':
529
+ return
530
+ if user.op == 'output':
531
+ body.append('\n')
532
+ return
533
+ nodes_to_delete = user_to_last_uses.get(user, [])
534
+
535
+ if len(user.users.keys()) == 0:
536
+ # This node is not used by any others. however it's also not
537
+ # removed by DCE since side-effect. We want to free it's outputs
538
+ # right after its execution done to save memory.
539
+ nodes_to_delete.append(user)
540
+
541
+ if len(nodes_to_delete):
542
+ to_delete_str = ' = '.join([repr(n) for n in nodes_to_delete] + ['None'])
543
+ body.append(f'; {dim(to_delete_str)}\n')
544
+ else:
545
+ body.append('\n')
546
+
547
+ prev_stacktrace = None
548
+
549
+ def append_stacktrace_summary(node : Node):
550
+ """
551
+ Append a summary of the stacktrace to the generated code. This is
552
+ useful for debugging.
553
+ """
554
+ nonlocal prev_stacktrace
555
+
556
+ if node.op not in {'placeholder', 'output'}:
557
+ if node.stack_trace:
558
+ if node.stack_trace != prev_stacktrace:
559
+ prev_stacktrace = node.stack_trace
560
+ summary_str = ""
561
+
562
+ if parsed_stack_trace := _parse_stack_trace(node.stack_trace):
563
+ summary_str = parsed_stack_trace.get_summary_str()
564
+
565
+ body.append(f'\n {dim("# " + summary_str)}\n')
566
+ elif prev_stacktrace != "":
567
+ prev_stacktrace = ""
568
+ no_stacktrace_msg = "# No stacktrace found for following nodes"
569
+ body.append(f'\n{dim(no_stacktrace_msg)}\n')
570
+
571
+ def stringify_shape(shape : Iterable) -> str:
572
+ return f"[{', '.join(str(x) for x in shape)}]"
573
+
574
+ def emit_node(node : Node):
575
+ maybe_type_annotation = '' if node.type is None else f' : {type_repr(node.type)}'
576
+
577
+ if verbose:
578
+ # override annotation with more detailed information
579
+ from torch.fx.experimental.proxy_tensor import py_sym_types
580
+ from torch.fx.passes.shape_prop import TensorMetadata
581
+
582
+ meta_val = node.meta.get('val', node.meta.get('tensor_meta', node.meta.get('example_value', None)))
583
+ # use string as annotation, to make it valid python code
584
+
585
+ if isinstance(meta_val, torch.Tensor):
586
+ stride_annotation = f"{stringify_shape(meta_val.stride())}" if include_stride else ""
587
+ device_annotation = f"{meta_val.device}" if include_device else ""
588
+ maybe_type_annotation = \
589
+ f': "{red(dtype_abbrs[meta_val.dtype])}{blue(stringify_shape(meta_val.shape))}' \
590
+ f'{dim_blue(stride_annotation)}{dim_green(device_annotation)}"'
591
+ elif isinstance(meta_val, py_sym_types):
592
+ maybe_type_annotation = f': "Sym({meta_val})"'
593
+ elif isinstance(meta_val, TensorMetadata):
594
+ maybe_type_annotation = f': "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}"'
595
+
596
+ if node.op == 'placeholder':
597
+ assert isinstance(node.target, str)
598
+ maybe_default_arg = '' if not node.args else f' = {_get_repr(node.args[0])}'
599
+ free_vars.append(f'{node.target}{maybe_type_annotation}{maybe_default_arg}')
600
+ raw_name = node.target.replace('*', '')
601
+ if raw_name != repr(node):
602
+ body.append(f'{repr(node)} = {raw_name}\n')
603
+ return
604
+ elif node.op == 'call_method':
605
+ assert isinstance(node.target, str)
606
+ body.append(
607
+ f'{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.target)}'
608
+ f'({_format_args(node.args[1:], node.kwargs)})')
609
+ return
610
+ elif node.op == 'call_function':
611
+ assert callable(node.target)
612
+ # pretty print operators
613
+ if getattr(node.target, "__module__", "") == '_operator' and node.target.__name__ in magic_methods:
614
+ assert isinstance(node.args, tuple)
615
+ body.append(f'{repr(node)}{maybe_type_annotation} = '
616
+ f'{magic_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}')
617
+ return
618
+
619
+ # pretty print inplace operators; required for jit.script to work properly
620
+ # not currently supported in normal FX graphs, but generated by torchdynamo
621
+ if getattr(node.target, "__module__", "") == '_operator' and node.target.__name__ in inplace_methods:
622
+ body.append(f'{inplace_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}; '
623
+ f'{repr(node)}{maybe_type_annotation} = {_get_repr(node.args[0])}')
624
+ return
625
+
626
+ qualified_name = _get_qualified_name(node.target)
627
+ global_name = add_global(qualified_name, node.target)
628
+ # special case for getattr: node.args could be 2-argument or 3-argument
629
+ # 2-argument: attribute access; 3-argument: fall through to attrib function call with default value
630
+ if global_name == 'getattr' and \
631
+ isinstance(node.args, tuple) and \
632
+ isinstance(node.args[1], str) and \
633
+ node.args[1].isidentifier() and \
634
+ len(node.args) == 2:
635
+ body.append(f'{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.args[1])}')
636
+ return
637
+ body.append(f'{repr(node)}{maybe_type_annotation} = {global_name}({_format_args(node.args, node.kwargs)})')
638
+ if node.meta.get('is_wrapped', False):
639
+ wrapped_fns.setdefault(global_name)
640
+ return
641
+ elif node.op == 'call_module':
642
+ assert isinstance(node.target, str)
643
+ body.append(f'{repr(node)}{maybe_type_annotation} = '
644
+ f'{_format_target(root_module, node.target)}({_format_args(node.args, node.kwargs)})')
645
+ return
646
+ elif node.op == 'get_attr':
647
+ assert isinstance(node.target, str)
648
+ body.append(f'{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}')
649
+ return
650
+ elif node.op == 'output':
651
+ if node.type is not None:
652
+ maybe_return_annotation[0] = f" -> {type_repr(node.type)}"
653
+ body.append(self.generate_output(node.args[0]))
654
+ return
655
+ raise NotImplementedError(f'node: {node.op} {node.target}')
656
+
657
+ for i, node in enumerate(nodes):
658
+ # NOTE: emit_node does not emit a string with newline. It depends
659
+ # on delete_unused_values to append one
660
+ if verbose:
661
+ append_stacktrace_summary(node)
662
+ # emit a counter comment to keep track of
663
+ # node index, which will be deleted later
664
+ # after going through _body_transformer
665
+ body.append(f"# COUNTER: {i}\n")
666
+ emit_node(node)
667
+ delete_unused_values(node)
668
+
669
+ if len(body) == 0:
670
+ # If the Graph has no non-placeholder nodes, no lines for the body
671
+ # have been emitted. To continue to have valid Python code, emit a
672
+ # single pass statement
673
+ body.append('pass\n')
674
+
675
+
676
+
677
+ if len(wrapped_fns) > 0:
678
+ wrap_name = add_global('wrap', torch.fx.wrap)
679
+ wrap_stmts = '\n'.join([f'{wrap_name}("{name}")' for name in wrapped_fns])
680
+ else:
681
+ wrap_stmts = ''
682
+
683
+ if self._body_transformer:
684
+ body = self._body_transformer(body)
685
+
686
+ for name, value in self.additional_globals():
687
+ add_global(name, value)
688
+
689
+ prologue = self.gen_fn_def(free_vars, maybe_return_annotation[0])
690
+
691
+ # remove counter and generate lineno to node index mapping
692
+ lineno_map: Dict[int, Optional[int]] = {}
693
+ prologue_len = prologue.count('\n') + 1
694
+ new_lines: List[str] = []
695
+ cur_idx = None
696
+ for line in ''.join(body).split('\n'):
697
+ counter = re.search(r"# COUNTER: (\d+)", line)
698
+ if counter and counter.group(1) is not None:
699
+ cur_idx = int(counter.group(1))
700
+ else:
701
+ lineno_map[len(new_lines) + prologue_len] = cur_idx
702
+ new_lines.append(line)
703
+
704
+ code = "\n".join(new_lines).lstrip('\n')
705
+ code = '\n'.join(' ' + line for line in code.split('\n'))
706
+
707
+ fn_code = f"""
708
+ {wrap_stmts}
709
+
710
+ {prologue}
711
+ {code}"""
712
+ return PythonCode(fn_code, globals_, _lineno_map=lineno_map)
713
+
714
+
715
+ # Ideally, we'd like to refactor all of the pytree logic into this codegen
716
+ # class. Unfortunately, there are 3 areas we currently need extra logic in FX.
717
+ # 1. In the initial symbolic trace, the pytree logic is tied up with `concrete_args`.
718
+ # 2. In the FX graph, we need to access 2 attributes - in_spec and out_spec.
719
+ # Since we can't access .graph within the FX forward, we need to copy the attribute to the module.
720
+ # 3. We currently can't register the pytree imports with `add_global` - not sure why.
721
+ class _PyTreeCodeGen(CodeGen):
722
+ def __init__(self, pytree_info: _PyTreeInfo):
723
+ super().__init__()
724
+ self.pytree_info: _PyTreeInfo = pytree_info
725
+
726
+ def process_inputs(self, *inputs: Any) -> Any:
727
+ flat_args = pytree.arg_tree_leaves(*inputs)
728
+ return flat_args
729
+
730
+ def process_outputs(self, out: Any) -> Any:
731
+ if self.pytree_info is None or self.pytree_info.out_spec is None:
732
+ return out
733
+ if not isinstance(out, (list, tuple)):
734
+ out = [out]
735
+ assert self.pytree_info.out_spec is not None
736
+ return pytree.tree_unflatten(out, self.pytree_info.out_spec)
737
+
738
+ def gen_fn_def(self, free_vars, maybe_return_annotation):
739
+ # Given a user function/model:
740
+ # myargs = [myargs0, myargs1]
741
+ # mykwargs = {'mykwargs0': ..., 'mykwargs1': ...}
742
+ # def forward(self, mypos, *myargs, mykey=None, **mykwargs):
743
+ #
744
+ # The generated code flattens all keywords into positional arguments for `forward()`
745
+ # e.g forward(self, mypos, myargs0, myargs1, mykey, mykwargs0, mykwargs1):
746
+ #
747
+ # Within `forward`, `tree_flatten_spec``still parses args and kwargs separately
748
+ # e.g. tree_flatten_spec(([mypos, myargs0, myargs1],
749
+ # {'mykey':mykey, 'mykwargs0':mykwargs0, 'mykwargs1':mykwargs1}),
750
+ # self._in_spec)
751
+ #
752
+ # If the user function/model does not have keywords, the dict is suppressed from tree_flatten_spec
753
+ # e.g. tree_flatten_spec([mypos, myargs0, myargs1]), self._in_spec)
754
+ if self.pytree_info is None:
755
+ return super().gen_fn_def(free_vars, maybe_return_annotation)
756
+
757
+ fn_args = self.pytree_info.orig_args
758
+ has_orig_self = (fn_args[0] == 'self') if len(fn_args) > 0 else False
759
+ if has_orig_self:
760
+ free_vars.insert(0, 'self')
761
+ fn_definition = super().gen_fn_def(fn_args[:], maybe_return_annotation)
762
+
763
+ if len(free_vars) > 0: # pytree has placeholders in it
764
+ # when kwargs is present, in_spec is tuple(args, kwargs)
765
+ has_args_kwargs_tuple = self.pytree_info.in_spec.type == tuple and \
766
+ self.pytree_info.in_spec.num_children == 2 and \
767
+ self.pytree_info.in_spec.children_specs[0].type == tuple and \
768
+ self.pytree_info.in_spec.children_specs[1].type == dict
769
+ fn_kwargs = '{}'
770
+ fn_signature = f"[{', '.join(fn_args)}], self._in_spec"
771
+ if has_args_kwargs_tuple:
772
+ count_args = self.pytree_info.in_spec.children_specs[0].num_children
773
+ fn_args = self.pytree_info.orig_args[:count_args]
774
+ fn_kwargs = '{' + ', '.join(f"'{k}':{v}" for k, v in zip(
775
+ self.pytree_info.in_spec.children_specs[1].context,
776
+ self.pytree_info.orig_args[count_args:])) + '}'
777
+ fn_signature = f"([{', '.join(fn_args)}], {fn_kwargs}), self._in_spec"
778
+
779
+ # in Python, `var1: annotation1, var2: annotation2 = function_call()` is invalid.
780
+ # we need to split it to two lines:
781
+ # one for annotation: `var1: annotation1; var2: annotation2;` (note the semicolon)
782
+ # one for code: `var1, var2, = function_call()`
783
+ without_annotation = [x.split(":")[0] for x in free_vars]
784
+ has_annotation = [x + "; " for x in free_vars if ":" in x]
785
+ if len(has_annotation) > 0:
786
+ fn_definition += "\n " + "".join(has_annotation) + "\n"
787
+ fn_definition += f"""
788
+ {', '.join(without_annotation)}, = fx_pytree.tree_flatten_spec({fn_signature})"""
789
+ return fn_definition
790
+
791
+ def generate_output(self, output_args):
792
+ if self.pytree_info and self.pytree_info.out_spec:
793
+ return f'return pytree.tree_unflatten({repr(output_args)}, self._out_spec)'
794
+ else:
795
+ return super().generate_output(output_args)
796
+
797
+ class _FindNodesLookupTable:
798
+ """
799
+ Side table for the graph for the purpose of doing fast queries
800
+ """
801
+ def __init__(self):
802
+ self.table: Dict[Tuple[str, Optional[Target]], Dict[Node, None]] = defaultdict(dict)
803
+
804
+ def _key(self, node) -> Tuple[str, Optional[Target]]:
805
+ return (node.op, node.target if node.op == "call_function" else None)
806
+
807
+ def __contains__(self, node) -> bool:
808
+ return node in self.table[self._key(node)]
809
+
810
+ def insert(self, node: Node) -> None:
811
+ self.table[self._key(node)][node] = None
812
+
813
+ def remove(self, node: Node) -> None:
814
+ self.table[self._key(node)].pop(node)
815
+
816
+ def find_nodes(self, *, op: str, target: Optional['Target'] = None):
817
+ if op == "call_function":
818
+ assert target is not None
819
+ return dict(self.table[(op, target)]).keys()
820
+
821
+ if target is None:
822
+ return dict(self.table[(op, None)]).keys()
823
+
824
+ # op is call_method, get_attr, call_module
825
+ return [node for node in self.table[(op, None)].keys() if node.target == target]
826
+
827
+ @compatibility(is_backward_compatible=True)
828
+ class Graph:
829
+ """
830
+ ``Graph`` is the main data structure used in the FX Intermediate Representation.
831
+ It consists of a series of ``Node`` s, each representing callsites (or other
832
+ syntactic constructs). The list of ``Node`` s, taken together, constitute a
833
+ valid Python function.
834
+
835
+ For example, the following code
836
+
837
+ .. code-block:: python
838
+
839
+ import torch
840
+ import torch.fx
841
+
842
+ class MyModule(torch.nn.Module):
843
+ def __init__(self):
844
+ super().__init__()
845
+ self.param = torch.nn.Parameter(torch.rand(3, 4))
846
+ self.linear = torch.nn.Linear(4, 5)
847
+
848
+ def forward(self, x):
849
+ return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3)
850
+
851
+ m = MyModule()
852
+ gm = torch.fx.symbolic_trace(m)
853
+
854
+ Will produce the following Graph::
855
+
856
+ print(gm.graph)
857
+
858
+ .. code-block:: text
859
+
860
+ graph(x):
861
+ %linear_weight : [num_users=1] = self.linear.weight
862
+ %add_1 : [num_users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {})
863
+ %linear_1 : [num_users=1] = call_module[target=linear](args = (%add_1,), kwargs = {})
864
+ %relu_1 : [num_users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {})
865
+ %sum_1 : [num_users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1})
866
+ %topk_1 : [num_users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {})
867
+ return topk_1
868
+
869
+ For the semantics of operations represented in the ``Graph``, please see :class:`Node`.
870
+ """
871
+
872
+ @compatibility(is_backward_compatible=True)
873
+ def __init__(self, owning_module: Optional["GraphModule"] = None, tracer_cls: Optional[Type["Tracer"]] = None,
874
+ tracer_extras: Optional[Dict[str, Any]] = None):
875
+ """
876
+ Construct an empty Graph.
877
+ """
878
+ self._root : Node = Node(self, '', 'root', '', (), {})
879
+ self._used_names : Dict[str, int] = {} # base name -> number
880
+ self._insert = self._root.prepend
881
+ self._len = 0
882
+ self._graph_namespace = _Namespace()
883
+ self._owning_module = owning_module
884
+ self._tracer_cls = tracer_cls
885
+ self._tracer_extras = tracer_extras
886
+ self._codegen = CodeGen()
887
+ self._co_fields : Dict[str, Any] = {}
888
+ self._find_nodes_lookup_table = _FindNodesLookupTable()
889
+
890
+ @property
891
+ def owning_module(self):
892
+ return self._owning_module
893
+
894
+ @owning_module.setter
895
+ def owning_module(self, mod: Optional["GraphModule"]):
896
+ self._owning_module = mod
897
+
898
+ @property
899
+ def nodes(self) -> _node_list:
900
+ """
901
+ Get the list of Nodes that constitute this Graph.
902
+
903
+ Note that this ``Node`` list representation is a doubly-linked list. Mutations
904
+ during iteration (e.g. delete a Node, add a Node) are safe.
905
+
906
+ Returns:
907
+
908
+ A doubly-linked list of Nodes. Note that ``reversed`` can be called on
909
+ this list to switch iteration order.
910
+ """
911
+ return _node_list(self)
912
+
913
+ @compatibility(is_backward_compatible=False)
914
+ def find_nodes(self, *, op: str, target: Optional['Target'] = None, sort: bool = True):
915
+ """
916
+ Allows for fast query of nodes
917
+
918
+ Args:
919
+
920
+ op (str): the name of the operation
921
+
922
+ target (Optional[Target]): the target of the node. For call_function,
923
+ the target is required. For other ops, the target is optional.
924
+
925
+ sort (bool): whether to return nodes in the order they appear on
926
+ on the graph.
927
+
928
+ Returns:
929
+
930
+ Iteratable of nodes with the requested op and target.
931
+ """
932
+ node_list = self._find_nodes_lookup_table.find_nodes(op=op, target=target)
933
+ if sort:
934
+ return sorted(node_list)
935
+ return node_list
936
+
937
+ @compatibility(is_backward_compatible=True)
938
+ def graph_copy(self, g : 'Graph', val_map : Dict[Node, Node], return_output_node=False) -> 'Optional[Argument]':
939
+ """
940
+ Copy all nodes from a given graph into ``self``.
941
+
942
+ Args:
943
+
944
+ g (Graph): The source graph from which to copy Nodes.
945
+
946
+ val_map (Dict[Node, Node]): a dictionary that will be populated with a mapping
947
+ from nodes in ``g`` to nodes in ``self``. Note that ``val_map`` can be passed
948
+ in with values in it already to override copying of certain values.
949
+
950
+ Returns:
951
+
952
+ The value in ``self`` that is now equivalent to the output value in ``g``,
953
+ if ``g`` had an ``output`` node. ``None`` otherwise.
954
+ """
955
+ for node in g.nodes:
956
+ if node in val_map:
957
+ continue
958
+ if node.op == 'output':
959
+ rv = map_arg(node.args[0], lambda n: val_map[n])
960
+ return rv if not return_output_node else (rv, node)
961
+ val_map[node] = self.node_copy(node, lambda n : val_map[n])
962
+ return None
963
+
964
+ def __deepcopy__(self, memo=None) -> 'Graph':
965
+ """
966
+ Explicitly implement __deepcopy__ to prevent excessive recursion depth
967
+ from the default implementation. This uses graph_copy to copy the nodes
968
+ in an iterative way, rather than recursive. It also populates the
969
+ memoization table to prevent unnecessary copies (e.g. references to
970
+ nodes or other parts of the Graph from a custom GraphModule implementation.
971
+ """
972
+ memo = memo if memo else {}
973
+ g = Graph(tracer_cls=self._tracer_cls)
974
+ output_vals = g.graph_copy(self, val_map=memo, return_output_node=True)
975
+ g._codegen = copy.deepcopy(self._codegen)
976
+ assert isinstance(output_vals, tuple)
977
+ output_val, old_output_node = output_vals
978
+ new_output_node = g.output(output_val, type_expr=getattr(old_output_node, 'type', None))
979
+ new_output_node.meta = copy.copy(old_output_node.meta)
980
+ return g
981
+
982
+ @compatibility(is_backward_compatible=True)
983
+ def create_node(self, op: str, target: 'Target',
984
+ args: Optional[Tuple['Argument', ...]] = None,
985
+ kwargs: Optional[Dict[str, 'Argument']] = None,
986
+ name: Optional[str] = None,
987
+ type_expr: Optional[Any] = None) -> Node:
988
+ """
989
+ Create a ``Node`` and add it to the ``Graph`` at the current insert-point.
990
+ Note that the current insert-point can be set via :meth:`Graph.inserting_before`
991
+ and :meth:`Graph.inserting_after`.
992
+
993
+ Args:
994
+ op (str): the opcode for this Node. One of 'call_function', 'call_method', 'get_attr',
995
+ 'call_module', 'placeholder', or 'output'. The semantics of these opcodes are
996
+ described in the ``Graph`` docstring.
997
+
998
+ args (Optional[Tuple[Argument, ...]]): is a tuple of arguments to this node.
999
+
1000
+ kwargs (Optional[Dict[str, Argument]]): the kwargs of this Node
1001
+
1002
+ name (Optional[str]): an optional string name for the ``Node``.
1003
+ This will influence the name of the value assigned to in the
1004
+ Python generated code.
1005
+
1006
+ type_expr (Optional[Any]): an optional type annotation representing the
1007
+ Python type the output of this node will have.
1008
+
1009
+ Returns:
1010
+
1011
+ The newly-created and inserted node.
1012
+ """
1013
+ assert op in ('call_function', 'call_method', 'get_attr', 'call_module', 'placeholder', 'output')
1014
+ args = () if args is None else args
1015
+ kwargs = {} if kwargs is None else kwargs
1016
+ assert isinstance(args, tuple), "args must be a tuple"
1017
+ assert isinstance(kwargs, dict), "kwargs must be a dict"
1018
+
1019
+ candidate = name if name is not None else self._target_to_str(target)
1020
+ name = self._graph_namespace.create_name(candidate, None)
1021
+ n = Node(self, name, op, target, args, kwargs, type_expr)
1022
+
1023
+ if self.owning_module is not None and getattr(self.owning_module, "_create_node_hooks", None) is not None:
1024
+ for f in self.owning_module._create_node_hooks:
1025
+ f(n)
1026
+
1027
+ self._graph_namespace.associate_name_with_obj(name, n)
1028
+
1029
+ self._insert(n)
1030
+ self._find_nodes_lookup_table.insert(n)
1031
+ self._len += 1
1032
+ return n
1033
+
1034
+ @compatibility(is_backward_compatible=False)
1035
+ def process_inputs(self, *args):
1036
+ """
1037
+ Processes args so that they can be passed to the FX graph.
1038
+ """
1039
+ return self._codegen.process_inputs(*args)
1040
+
1041
+ @compatibility(is_backward_compatible=False)
1042
+ def process_outputs(self, out):
1043
+ return self._codegen.process_outputs(out)
1044
+
1045
+
1046
+ @compatibility(is_backward_compatible=True)
1047
+ def erase_node(self, to_erase : Node) -> None:
1048
+ """
1049
+ Erases a ``Node`` from the ``Graph``. Throws an exception if
1050
+ there are still users of that node in the ``Graph``.
1051
+
1052
+ Args:
1053
+
1054
+ to_erase (Node): The ``Node`` to erase from the ``Graph``.
1055
+ """
1056
+ if len(to_erase.users) > 0:
1057
+ raise RuntimeError(f'Tried to erase Node {to_erase} but it still had {len(to_erase.users)} '
1058
+ f'users in the graph: {to_erase.users}!')
1059
+ if to_erase.graph != self:
1060
+ raise RuntimeError(f"Attempting to remove {to_erase} from wrong graph!")
1061
+ if to_erase._erased:
1062
+ warnings.warn(f"erase_node({to_erase}) on an already erased node")
1063
+ return
1064
+
1065
+ if self.owning_module is not None and getattr(self.owning_module, "_erase_node_hooks", None) is not None:
1066
+ for f in self.owning_module._erase_node_hooks:
1067
+ f(to_erase)
1068
+
1069
+ self._find_nodes_lookup_table.remove(to_erase)
1070
+ to_erase._remove_from_list()
1071
+ to_erase._erased = True # iterators may retain handles to erased nodes
1072
+ self._len -= 1
1073
+
1074
+ # Null out this Node's argument nodes so that the Nodes referred to
1075
+ # can update their ``users`` accordingly
1076
+ new_args = map_arg(to_erase.args, lambda n: None)
1077
+ assert isinstance(new_args, tuple)
1078
+ to_erase.args = new_args
1079
+ new_kwargs = map_arg(to_erase.kwargs, lambda n: None)
1080
+ assert isinstance(new_kwargs, dict)
1081
+ to_erase.kwargs = new_kwargs
1082
+
1083
+ @compatibility(is_backward_compatible=True)
1084
+ def inserting_before(self, n: Optional[Node] = None):
1085
+ """Set the point at which create_node and companion methods will insert into the graph.
1086
+ When used within a 'with' statement, this will temporary set the insert point and
1087
+ then restore it when the with statement exits::
1088
+
1089
+ with g.inserting_before(n):
1090
+ ... # inserting before node n
1091
+ ... # insert point restored to what it was previously
1092
+ g.inserting_before(n) # set the insert point permanently
1093
+
1094
+ Args:
1095
+
1096
+ n (Optional[Node]): The node before which to insert. If None this will insert before
1097
+ the beginning of the entire graph.
1098
+
1099
+ Returns:
1100
+ A resource manager that will restore the insert point on ``__exit__``.
1101
+ """
1102
+ if n is None:
1103
+ return self.inserting_after(self._root)
1104
+ assert n.graph == self, "Node to insert before is not in graph."
1105
+ return _InsertPoint(self, n.prepend)
1106
+
1107
+ @compatibility(is_backward_compatible=True)
1108
+ def inserting_after(self, n: Optional[Node] = None):
1109
+ """Set the point at which create_node and companion methods will insert into the graph.
1110
+ When used within a 'with' statement, this will temporary set the insert point and
1111
+ then restore it when the with statement exits::
1112
+
1113
+ with g.inserting_after(n):
1114
+ ... # inserting after node n
1115
+ ... # insert point restored to what it was previously
1116
+ g.inserting_after(n) # set the insert point permanently
1117
+
1118
+ Args:
1119
+
1120
+ n (Optional[Node]): The node before which to insert. If None this will insert after
1121
+ the beginning of the entire graph.
1122
+
1123
+ Returns:
1124
+ A resource manager that will restore the insert point on ``__exit__``.
1125
+ """
1126
+ if n is None:
1127
+ return self.inserting_before(self._root)
1128
+ assert n.graph == self, "Node to insert after is not in graph."
1129
+ return _InsertPoint(self, n.append)
1130
+
1131
+ @compatibility(is_backward_compatible=True)
1132
+ def placeholder(self, name: str, type_expr: Optional[Any] = None,
1133
+ default_value : Any = inspect.Signature.empty) -> Node:
1134
+ """
1135
+ Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents
1136
+ a function input.
1137
+
1138
+ Args:
1139
+
1140
+ name (str): A name for the input value. This corresponds to the name
1141
+ of the positional argument to the function this ``Graph`` represents.
1142
+
1143
+ type_expr (Optional[Any]): an optional type annotation representing the
1144
+ Python type the output of this node will have. This is needed in some
1145
+ cases for proper code generation (e.g. when the function is used
1146
+ subsequently in TorchScript compilation).
1147
+
1148
+ default_value (Any): The default value this function argument should take
1149
+ on. NOTE: to allow for `None` as a default value, `inspect.Signature.empty`
1150
+ should be passed as this argument to specify that the parameter does _not_
1151
+ have a default value.
1152
+
1153
+ .. note::
1154
+ The same insertion point and type expression rules apply for this method
1155
+ as ``Graph.create_node``.
1156
+ """
1157
+ args = () if default_value is inspect.Signature.empty else (default_value,)
1158
+ return self.create_node('placeholder', name, args=args, type_expr=type_expr)
1159
+
1160
+ @compatibility(is_backward_compatible=True)
1161
+ def get_attr(self, qualified_name: str, type_expr: Optional[Any] = None) -> Node:
1162
+ """
1163
+ Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the
1164
+ fetch of an attribute from the ``Module`` hierarchy.
1165
+
1166
+ Args:
1167
+
1168
+ qualified_name (str): the fully-qualified name of the attribute to be retrieved.
1169
+ For example, if the traced Module has a submodule named ``foo``, which has a
1170
+ submodule named ``bar``, which has an attribute named ``baz``, the qualified
1171
+ name ``foo.bar.baz`` should be passed as ``qualified_name``.
1172
+
1173
+ type_expr (Optional[Any]): an optional type annotation representing the
1174
+ Python type the output of this node will have.
1175
+
1176
+
1177
+ Returns:
1178
+
1179
+ The newly-created and inserted ``get_attr`` node.
1180
+
1181
+ .. note::
1182
+ The same insertion point and type expression rules apply for this method
1183
+ as ``Graph.create_node``.
1184
+ """
1185
+ def _get_attr_reference_exists(mod: torch.nn.Module, qualified_name: str) -> bool:
1186
+ module_path, _, name = qualified_name.rpartition(".")
1187
+
1188
+ try:
1189
+ submod: torch.nn.Module = mod.get_submodule(module_path)
1190
+ except AttributeError:
1191
+ warnings.warn(f"Failed to fetch module {module_path}!")
1192
+ return False
1193
+
1194
+ if not hasattr(submod, name):
1195
+ return False
1196
+
1197
+ res = getattr(submod, name)
1198
+
1199
+ if (not isinstance(res, torch.nn.Module)
1200
+ and not isinstance(res, torch.nn.Parameter)
1201
+ and name not in submod._buffers):
1202
+ return False
1203
+
1204
+ return True
1205
+
1206
+ if (self.owning_module and
1207
+ not _get_attr_reference_exists(self.owning_module, qualified_name)):
1208
+ warnings.warn("Attempted to insert a get_attr Node with no "
1209
+ "underlying reference in the owning "
1210
+ "GraphModule! Call "
1211
+ "GraphModule.add_submodule to add the "
1212
+ "necessary submodule, "
1213
+ "GraphModule.add_parameter to add the "
1214
+ "necessary Parameter, or "
1215
+ "nn.Module.register_buffer to add the "
1216
+ "necessary buffer", stacklevel=2)
1217
+ return self.create_node('get_attr', qualified_name, type_expr=type_expr)
1218
+
1219
+ @compatibility(is_backward_compatible=True)
1220
+ def call_module(self,
1221
+ module_name: str,
1222
+ args: Optional[Tuple['Argument', ...]] = None,
1223
+ kwargs: Optional[Dict[str, 'Argument']] = None,
1224
+ type_expr: Optional[Any] = None) -> Node:
1225
+ """
1226
+ Insert a ``call_module`` ``Node`` into the ``Graph``. A ``call_module`` node
1227
+ represents a call to the forward() function of a ``Module`` in the ``Module``
1228
+ hierarchy.
1229
+
1230
+ Args:
1231
+
1232
+ module_name (str): The qualified name of the ``Module`` in the ``Module``
1233
+ hierarchy to be called. For example, if the traced ``Module`` has a
1234
+ submodule named ``foo``, which has a submodule named ``bar``, the
1235
+ qualified name ``foo.bar`` should be passed as ``module_name`` to
1236
+ call that module.
1237
+
1238
+ args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
1239
+ to the called method. Note that this should *not* include a ``self`` argument.
1240
+
1241
+ kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
1242
+ to the called method
1243
+
1244
+ type_expr (Optional[Any]): an optional type annotation representing the
1245
+ Python type the output of this node will have.
1246
+
1247
+ Returns:
1248
+
1249
+ The newly-created and inserted ``call_module`` node.
1250
+
1251
+ .. note::
1252
+ The same insertion point and type expression rules apply for this method
1253
+ as :meth:`Graph.create_node`.
1254
+ """
1255
+ if (self.owning_module and
1256
+ self.owning_module.get_submodule(module_name) is None):
1257
+ warnings.warn("Attempted to insert a call_module Node with "
1258
+ "no underlying reference in the owning "
1259
+ "GraphModule! Call "
1260
+ "GraphModule.add_submodule to add the "
1261
+ "necessary submodule")
1262
+ return self.create_node('call_module', module_name, args, kwargs, type_expr=type_expr)
1263
+
1264
+ @compatibility(is_backward_compatible=True)
1265
+ def call_method(self,
1266
+ method_name: str,
1267
+ args: Optional[Tuple['Argument', ...]] = None,
1268
+ kwargs: Optional[Dict[str, 'Argument']] = None,
1269
+ type_expr: Optional[Any] = None) -> Node:
1270
+ """
1271
+ Insert a ``call_method`` ``Node`` into the ``Graph``. A ``call_method`` node
1272
+ represents a call to a given method on the 0th element of ``args``.
1273
+
1274
+ Args:
1275
+
1276
+ method_name (str): The name of the method to apply to the self argument.
1277
+ For example, if args[0] is a ``Node`` representing a ``Tensor``,
1278
+ then to call ``relu()`` on that ``Tensor``, pass ``relu`` to ``method_name``.
1279
+
1280
+ args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
1281
+ to the called method. Note that this *should* include a ``self`` argument.
1282
+
1283
+ kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
1284
+ to the called method
1285
+
1286
+ type_expr (Optional[Any]): an optional type annotation representing the
1287
+ Python type the output of this node will have.
1288
+
1289
+ Returns:
1290
+
1291
+ The newly created and inserted ``call_method`` node.
1292
+
1293
+ .. note::
1294
+ The same insertion point and type expression rules apply for this method
1295
+ as :meth:`Graph.create_node`.
1296
+ """
1297
+ return self.create_node('call_method', method_name, args, kwargs, type_expr=type_expr)
1298
+
1299
+ @compatibility(is_backward_compatible=True)
1300
+ def call_function(self,
1301
+ the_function: Callable[..., Any],
1302
+ args: Optional[Tuple['Argument', ...]] = None,
1303
+ kwargs: Optional[Dict[str, 'Argument']] = None,
1304
+ type_expr: Optional[Any] = None) -> Node:
1305
+ """
1306
+ Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node
1307
+ represents a call to a Python callable, specified by ``the_function``.
1308
+
1309
+ Args:
1310
+
1311
+ the_function (Callable[..., Any]): The function to be called. Can be any PyTorch
1312
+ operator, Python function, or member of the ``builtins`` or ``operator``
1313
+ namespaces.
1314
+
1315
+ args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
1316
+ to the called function.
1317
+
1318
+ kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
1319
+ to the called function
1320
+
1321
+ type_expr (Optional[Any]): an optional type annotation representing the
1322
+ Python type the output of this node will have.
1323
+
1324
+ Returns:
1325
+
1326
+ The newly created and inserted ``call_function`` node.
1327
+
1328
+ .. note::
1329
+ The same insertion point and type expression rules apply for this method
1330
+ as :meth:`Graph.create_node`.
1331
+ """
1332
+ return self.create_node('call_function', the_function, args, kwargs, type_expr=type_expr)
1333
+
1334
+ @compatibility(is_backward_compatible=True)
1335
+ def node_copy(self, node: Node, arg_transform: Callable[[Node], 'Argument'] = lambda x: x) -> Node:
1336
+ """
1337
+ Copy a node from one graph into another. ``arg_transform`` needs to transform arguments from
1338
+ the graph of node to the graph of self. Example::
1339
+
1340
+ # Copying all the nodes in `g` into `new_graph`
1341
+ g : torch.fx.Graph = ...
1342
+ new_graph = torch.fx.graph()
1343
+ value_remap = {}
1344
+ for node in g.nodes:
1345
+ value_remap[node] = new_graph.node_copy(node, lambda n : value_remap[n])
1346
+
1347
+ Args:
1348
+
1349
+ node (Node): The node to copy into ``self``.
1350
+
1351
+ arg_transform (Callable[[Node], Argument]): A function that transforms
1352
+ ``Node`` arguments in node's ``args`` and ``kwargs`` into the
1353
+ equivalent argument in ``self``. In the simplest case, this should
1354
+ retrieve a value out of a table mapping Nodes in the original
1355
+ graph to ``self``.
1356
+ """
1357
+ args = map_arg(node.args, arg_transform)
1358
+ kwargs = map_arg(node.kwargs, arg_transform)
1359
+ assert isinstance(args, tuple)
1360
+ assert isinstance(kwargs, dict)
1361
+ result_node = self.create_node(node.op, node.target, args, kwargs, node.name, node.type)
1362
+ result_node.meta = copy.copy(node.meta)
1363
+ return result_node
1364
+
1365
+ @compatibility(is_backward_compatible=True)
1366
+ def output(self, result: 'Argument', type_expr: Optional[Any] = None):
1367
+ """
1368
+ Insert an ``output`` ``Node`` into the ``Graph``. An ``output`` node represents
1369
+ a ``return`` statement in Python code. ``result`` is the value that should
1370
+ be returned.
1371
+
1372
+ Args:
1373
+
1374
+ result (Argument): The value to be returned.
1375
+
1376
+ type_expr (Optional[Any]): an optional type annotation representing the
1377
+ Python type the output of this node will have.
1378
+
1379
+ .. note::
1380
+
1381
+ The same insertion point and type expression rules apply for this method
1382
+ as ``Graph.create_node``.
1383
+ """
1384
+ return self.create_node(op='output', target='output', args=(result,), type_expr=type_expr)
1385
+
1386
+ def _target_to_str(self, target : Target) -> str:
1387
+ if callable(target):
1388
+ op = target.__name__
1389
+ else:
1390
+ assert isinstance(target, str)
1391
+ op = target
1392
+ if _is_magic(op):
1393
+ op = op[2:-2]
1394
+ op = _snake_case(op)
1395
+ return op
1396
+
1397
+ @compatibility(is_backward_compatible=True)
1398
+ def python_code(
1399
+ self, root_module: str, *,
1400
+ verbose: bool = False, include_stride: bool = False, include_device: bool = False, colored: bool = False
1401
+ ) -> PythonCode:
1402
+ """
1403
+ Turn this ``Graph`` into valid Python code.
1404
+
1405
+ Args:
1406
+
1407
+ root_module (str): The name of the root module on which to look-up
1408
+ qualified name targets. This is usually 'self'.
1409
+
1410
+ Returns:
1411
+
1412
+ A PythonCode object, consisting of two fields:
1413
+ src: the Python source code representing the object
1414
+ globals: a dictionary of global names in `src` -> the objects that they reference.
1415
+ """
1416
+ # NOTE: [Graph Namespaces]
1417
+ #
1418
+ # There are two types of symbols in generated Python source code:
1419
+ # locals and globals.
1420
+ # Locals are locally defined by the output of a node in the Graph.
1421
+ # Globals are references to external objects, like functions or types.
1422
+ #
1423
+ # When generating Python code, we need to make sure to name things
1424
+ # appropriately. In particular:
1425
+ # - All names should be unique, to avoid weird shadowing bugs.
1426
+ # - These names need to be consistent, e.g. a object should always be
1427
+ # referenced by the same name.
1428
+ #
1429
+ # To do this, we create a new namespace just for this source. All names
1430
+ # that get printed must come from this namespace.
1431
+ #
1432
+ # Why can't we re-use node.name? Because it was generated within the
1433
+ # namespace `self._graph_namespace`. In order to provide uniqueness
1434
+ # over both locals (node.name) *and* globals, we create a completely
1435
+ # new namespace to put all identifiers in.
1436
+ namespace = _Namespace()
1437
+
1438
+ # Override Node's repr to generate a valid name within our namespace.
1439
+ # Since repr() is designed to produce a valid Python expression, it
1440
+ # makes sense to re-use it. This way, it's easy to print something like
1441
+ # Tuple[Node, Node] by simply calling repr() on it. Node's __repr__ is
1442
+ # implemented cooperatively to allow this.
1443
+ def node_repr(n: Node):
1444
+ return namespace.create_name(n.name, n)
1445
+
1446
+ @contextmanager
1447
+ def override_node_repr(graph: Graph):
1448
+ orig_repr_fns = {}
1449
+ for node in graph.nodes:
1450
+ orig_repr_fns[node] = node._repr_fn
1451
+ node._repr_fn = node_repr
1452
+ try:
1453
+ yield None
1454
+ finally:
1455
+ # restore the original repr functions
1456
+ for node in graph.nodes:
1457
+ node._repr_fn = orig_repr_fns[node]
1458
+
1459
+ with override_node_repr(self):
1460
+ return self._python_code(
1461
+ root_module, namespace,
1462
+ verbose=verbose, include_stride=include_stride, include_device=include_device, colored=colored
1463
+ )
1464
+
1465
+ def _python_code(
1466
+ self, root_module: str, namespace: _Namespace, *,
1467
+ verbose: bool = False, include_stride: bool = False, include_device: bool = False, colored: bool = False,
1468
+ ) -> PythonCode:
1469
+ return self._codegen._gen_python_code(
1470
+ self.nodes, root_module, namespace,
1471
+ verbose=verbose, include_stride=include_stride, include_device=include_device, colored=colored
1472
+ )
1473
+
1474
+
1475
+ def __str__(self) -> str:
1476
+ """
1477
+ Return a human-readable (not machine-readable) string representation
1478
+ of this Graph
1479
+ """
1480
+ placeholder_names : List[str] = []
1481
+ # This is a one-element array just so ``format_node`` can modify the closed
1482
+ # over value
1483
+ maybe_return_typename : List[str] = ['']
1484
+
1485
+ node_strs = [node.format_node(placeholder_names) for node in self.nodes]
1486
+ param_str = ', '.join(placeholder_names)
1487
+ s = f'graph({param_str}){maybe_return_typename[0]}:'
1488
+ for node_str in node_strs:
1489
+ if node_str:
1490
+ s += '\n ' + node_str
1491
+ return s
1492
+
1493
+ @compatibility(is_backward_compatible=True)
1494
+ def print_tabular(self):
1495
+ """
1496
+ Prints the intermediate representation of the graph in tabular
1497
+ format. Note that this API requires the ``tabulate`` module to be
1498
+ installed.
1499
+ """
1500
+ try:
1501
+ from tabulate import tabulate
1502
+ except ImportError:
1503
+ print("`print_tabular` relies on the library `tabulate`, "
1504
+ "which could not be found on this machine. Run `pip "
1505
+ "install tabulate` to install the library.")
1506
+ raise
1507
+
1508
+ node_specs = [[n.op, n.name, n.target, n.args, n.kwargs]
1509
+ for n in self.nodes]
1510
+ print(tabulate(node_specs,
1511
+ headers=['opcode', 'name', 'target', 'args', 'kwargs']))
1512
+
1513
+ @compatibility(is_backward_compatible=True)
1514
+ def lint(self):
1515
+ """
1516
+ Runs various checks on this Graph to make sure it is well-formed. In
1517
+ particular:
1518
+ - Checks Nodes have correct ownership (owned by this graph)
1519
+ - Checks Nodes appear in topological order
1520
+ - If this Graph has an owning GraphModule, checks that targets
1521
+ exist in that GraphModule
1522
+ """
1523
+
1524
+ # Check topo order
1525
+ def check_arg(arg : Node, n : Optional[Node] = None) -> None:
1526
+ context_str = f' of Node \'{n}\' ' if n else ' '
1527
+ if arg.graph is not self:
1528
+ raise RuntimeError(f'Argument \'{arg}\'{context_str}does not belong to this Graph, '
1529
+ f'but was used as an argument! If you are copying nodes from another graph, make '
1530
+ f'sure to use ``arg_transform`` on node_copy() to remap values\n{self}')
1531
+ if arg not in seen_values:
1532
+ raise RuntimeError(f'Argument \'{arg}\'{context_str}was used before it has been '
1533
+ f'defined! Please check that Nodes in the graph are topologically ordered\n{self}')
1534
+
1535
+ seen_names : Set[str] = set()
1536
+ seen_values : Set[Node] = set()
1537
+ for node in self.nodes:
1538
+ if node.op not in ['placeholder', 'call_method', 'call_module', 'call_function', 'get_attr', 'output']:
1539
+ raise RuntimeError(f'Node {node} had unknown opcode {node.op}!')
1540
+ if node.graph is not self:
1541
+ raise RuntimeError(f'Node \'{node}\' does not belong to this Graph!')
1542
+ if node not in self._find_nodes_lookup_table:
1543
+ raise RuntimeError(f"Node '{node}' is not added to the side table")
1544
+ map_arg(node.args, lambda arg: check_arg(arg, node))
1545
+ map_arg(node.kwargs, lambda arg: check_arg(arg, node))
1546
+ seen_values.add(node)
1547
+
1548
+ if node.name in seen_names:
1549
+ raise RuntimeError(f'Node redefined name {node.name}!')
1550
+ seen_names.add(node.name)
1551
+
1552
+ # Check targets are legit
1553
+ if self.owning_module:
1554
+ num_warnings = 0
1555
+ MAX_WARNINGS = 5
1556
+ for node in self.nodes:
1557
+ if node.op == 'call_function':
1558
+ if not callable(node.target):
1559
+ raise ValueError(f'Node {node} target {node.target} has type {torch.typename(node.target)} but '
1560
+ 'a Callable is expected')
1561
+ else:
1562
+ if not isinstance(node.target, str):
1563
+ raise ValueError(f'Node {node} target {node.target} has type {torch.typename(node.target)} but '
1564
+ 'a str is expected')
1565
+ if node.op in ['get_attr', 'call_module']:
1566
+ target_atoms = node.target.split('.')
1567
+ m_itr = self.owning_module
1568
+ for i, atom in enumerate(target_atoms):
1569
+ new_m_itr = getattr(m_itr, atom, None)
1570
+ seen_qualname = '.'.join(target_atoms[:i])
1571
+ if new_m_itr is None:
1572
+ raise RuntimeError(f'Node {node} target {node.target} references nonexistent attribute '
1573
+ f'{atom} of {seen_qualname}')
1574
+ if (node.op == "call_module"
1575
+ and not isinstance(new_m_itr, torch.nn.Module)):
1576
+ raise RuntimeError(f'Node {node} target {node.target} {atom} of {seen_qualname} does '
1577
+ 'not reference an nn.Module')
1578
+ elif (node.op == "get_attr"
1579
+ and not isinstance(new_m_itr, torch.nn.Module)
1580
+ and not isinstance(new_m_itr, torch.nn.Parameter)
1581
+ and atom not in m_itr._buffers):
1582
+ if num_warnings < MAX_WARNINGS:
1583
+ # Don't emit this warning too frequently,
1584
+ # for very large graphs this can become very expensive
1585
+ # from a performance perspective.
1586
+ warnings.warn(f'Node {node} target {node.target} {atom} of {seen_qualname} does '
1587
+ 'not reference an nn.Module, nn.Parameter, or buffer, which is '
1588
+ 'what \'get_attr\' Nodes typically target')
1589
+ num_warnings += 1
1590
+ else:
1591
+ m_itr = new_m_itr
1592
+ if num_warnings > MAX_WARNINGS:
1593
+ warnings.warn(
1594
+ f'Additional {num_warnings - MAX_WARNINGS} warnings '
1595
+ 'suppressed about get_attr references'
1596
+ )
1597
+
1598
+ @compatibility(is_backward_compatible=True)
1599
+ def eliminate_dead_code(self, is_impure_node: Optional[Callable[[Node], bool]] = None):
1600
+ """
1601
+ Remove all dead code from the graph, based on each node's number of
1602
+ users, and whether the nodes have any side effects. The graph must be
1603
+ topologically sorted before calling.
1604
+
1605
+ Args:
1606
+ is_impure_node (Optional[Callable[[Node], bool]]): A function that returns
1607
+ whether a node is impure. If this is None, then the default behavior is to
1608
+ use Node.is_impure.
1609
+
1610
+ Returns:
1611
+ bool: Whether the graph was changed as a result of the pass.
1612
+
1613
+ Example:
1614
+
1615
+ Before dead code is eliminated, `a` from `a = x + 1` below has no users
1616
+ and thus can be eliminated from the graph without having an effect.
1617
+
1618
+ .. code-block:: python
1619
+
1620
+ def forward(self, x):
1621
+ a = x + 1
1622
+ return x + self.attr_1
1623
+
1624
+ After dead code is eliminated, `a = x + 1` has been removed, and the rest
1625
+ of `forward` remains.
1626
+
1627
+ .. code-block:: python
1628
+
1629
+ def forward(self, x):
1630
+ return x + self.attr_1
1631
+
1632
+ .. warning::
1633
+
1634
+ Dead code elimination has some heuristics to avoid removing
1635
+ side-effectful nodes (see Node.is_impure) but in general coverage
1636
+ is very bad, so you should assume that this method is not sound
1637
+ to call unless you know that your FX graph consists entirely
1638
+ of functional operations or you supply your own custom
1639
+ function for detecting side-effectful nodes.
1640
+ """
1641
+ # Lint the graph first to make sure its topologically sorted, otherwise
1642
+ # DCE below will not behave as expected.
1643
+ self.lint()
1644
+
1645
+ def has_side_effect(node):
1646
+ if is_impure_node is not None:
1647
+ return is_impure_node(node)
1648
+ return node.is_impure()
1649
+
1650
+ # Reverse iterate so that when we remove a node, any nodes used as an
1651
+ # input to that node have an updated user count that no longer reflects
1652
+ # the removed node.
1653
+ changed = False
1654
+ for node in reversed(self.nodes):
1655
+ if not has_side_effect(node) and len(node.users) == 0:
1656
+ self.erase_node(node)
1657
+ changed = True
1658
+
1659
+ return changed
1660
+
1661
+ @compatibility(is_backward_compatible=False)
1662
+ def set_codegen(self, codegen: CodeGen):
1663
+ self._codegen = codegen
1664
+
1665
+ @compatibility(is_backward_compatible=False)
1666
+ def on_generate_code(
1667
+ self,
1668
+ make_transformer: Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]
1669
+ ):
1670
+ """Register a transformer function when python code is generated
1671
+
1672
+ Args:
1673
+ make_transformer (Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]):
1674
+ a function that returns a code transformer to be registered.
1675
+ This function is called by `on_generate_code` to obtain the
1676
+ code transformer.
1677
+
1678
+ This function is also given as its input the currently
1679
+ registered code transformer (or None if nothing is registered),
1680
+ in case it is not desirable to overwrite it. This is useful to
1681
+ chain code transformers together.
1682
+
1683
+ Returns:
1684
+ a context manager that when used in a `with` statement, to automatically
1685
+ restore the previously registered code transformer.
1686
+
1687
+ Example:
1688
+
1689
+ .. code-block:: python
1690
+
1691
+
1692
+ gm: fx.GraphModule = ...
1693
+
1694
+ # This is a code transformer we want to register. This code
1695
+ # transformer prepends a pdb import and trace statement at the very
1696
+ # beginning of the generated torch.fx code to allow for manual
1697
+ # debugging with the PDB library.
1698
+ def insert_pdb(body):
1699
+ return ["import pdb; pdb.set_trace()\\n", *body]
1700
+
1701
+ # Registers `insert_pdb`, and overwrites the current registered
1702
+ # code transformer (given by `_` to the lambda):
1703
+ gm.graph.on_generate_code(
1704
+ lambda _: insert_pdb
1705
+ )
1706
+
1707
+ # Or alternatively, registers a code transformer which first
1708
+ # runs `body` through existing registered transformer, then
1709
+ # through `insert_pdb`:
1710
+ gm.graph.on_generate_code(
1711
+ lambda current_trans: (
1712
+ lambda body: insert_pdb(
1713
+ current_trans(body) if current_trans
1714
+ else body
1715
+ )
1716
+ )
1717
+ )
1718
+
1719
+ gm.recompile()
1720
+ gm(*inputs) # drops into pdb
1721
+
1722
+
1723
+ This function can also be used as a context manager, with the benefit to
1724
+ automatically restores the previously registered code transformer:
1725
+
1726
+ .. code-block:: python
1727
+
1728
+ # ... continue from previous example
1729
+
1730
+ with gm.graph.on_generate_code(lambda _: insert_pdb):
1731
+ # do more stuff with `gm`...
1732
+ gm.recompile()
1733
+ gm(*inputs) # drops into pdb
1734
+
1735
+ # now previous code transformer is restored (but `gm`'s code with pdb
1736
+ # remains - that means you can run `gm` with pdb here too, until you
1737
+ # run next `recompile()`).
1738
+ """
1739
+ on_gen_code_old = self._codegen._body_transformer
1740
+ self._codegen._body_transformer = make_transformer(on_gen_code_old)
1741
+
1742
+ @contextlib.contextmanager
1743
+ def on_generate_code_context_manager():
1744
+ try:
1745
+ yield
1746
+ finally:
1747
+ self._codegen._body_transformer = on_gen_code_old
1748
+
1749
+ return on_generate_code_context_manager()
1750
+
1751
+
1752
+ reflectable_magic_methods = {
1753
+ 'add': '{} + {}',
1754
+ 'sub': '{} - {}',
1755
+ 'mul': '{} * {}',
1756
+ 'floordiv': '{} // {}',
1757
+ 'truediv': '{} / {}',
1758
+ 'div': '{} / {}',
1759
+ 'mod': '{} % {}',
1760
+ 'pow': '{} ** {}',
1761
+ 'lshift': '{} << {}',
1762
+ 'rshift': '{} >> {}',
1763
+ 'and_': '{} & {}',
1764
+ 'or_': '{} | {}',
1765
+ 'xor': '{} ^ {}',
1766
+ 'getitem': '{}[{}]',
1767
+ 'matmul': '{} @ {}',
1768
+ }
1769
+
1770
+ magic_methods = dict({
1771
+ 'eq': '{} == {}',
1772
+ 'ne': '{} != {}',
1773
+ 'lt': '{} < {}',
1774
+ 'gt': '{} > {}',
1775
+ 'le': '{} <= {}',
1776
+ 'ge': '{} >= {}',
1777
+ 'pos': '+{}',
1778
+ 'neg': '-{}',
1779
+ 'invert': '~{}'}, **reflectable_magic_methods)
1780
+
1781
+ inplace_methods = {
1782
+ 'iadd': '{} += {}',
1783
+ 'iand': '{} &= {}',
1784
+ 'ifloordiv': '{} //= {}',
1785
+ 'ilshift': '{} <<= {}',
1786
+ 'imod': '{} %= {}',
1787
+ 'imul': '{} *= {}',
1788
+ 'imatmul': '{} @= {}',
1789
+ 'ior': '{} |= {}',
1790
+ 'ipow': '{} **= {}',
1791
+ 'irshift': '{} >>= {}',
1792
+ 'isub': '{} -= {}',
1793
+ 'itruediv': '{} /= {}',
1794
+ 'ixor': '{} ^= {}',
1795
+ 'setitem': '{}[{}] = {}',
1796
+ }
mplug_owl2/lib/python3.10/site-packages/torch/fx/graph_module.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import copy
4
+ import itertools
5
+ import linecache
6
+ import os
7
+ import sys
8
+ import traceback
9
+ import warnings
10
+ from pathlib import Path
11
+ from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.overrides
16
+ from torch.nn.modules.module import _addindent
17
+ from torch.package import Importer, PackageExporter, PackageImporter, sys_importer
18
+
19
+ from ._compatibility import compatibility
20
+ from .graph import _custom_builtins, _is_from_torch, _PyTreeCodeGen, Graph, PythonCode
21
+
22
+ __all__ = [
23
+ "reduce_graph_module",
24
+ "reduce_package_graph_module",
25
+ "reduce_deploy_graph_module",
26
+ "GraphModule",
27
+ ]
28
+
29
+ _USER_PRESERVED_ATTRIBUTES_KEY = "_user_preserved_attributes"
30
+
31
+ # Normal exec loses the source code, however we can work with
32
+ # the linecache module to recover it.
33
+ # Using _exec_with_source will add it to our local cache
34
+ # and then tools like TorchScript will be able to get source info.
35
+ class _EvalCacheLoader:
36
+ def __init__(self):
37
+ self.eval_cache = {}
38
+ self.next_id = 0
39
+
40
+ def cache(self, src: str, globals: Dict[str, Any], co_fields=None):
41
+ """Store the source in a private cache, and add a lazy entry in linecache
42
+ that allows the source to be retrieved by 'filename'.
43
+
44
+ Args:
45
+ src (str): The module source to cache
46
+ globals (dict): The module globals
47
+
48
+ Returns:
49
+ str: The cache key (and dummy filename) generated for src.
50
+ """
51
+
52
+ key = self._get_key()
53
+ if co_fields:
54
+ key += f" from {co_fields['co_filename']}:{co_fields['co_firstlineno']} in {co_fields['co_name']}"
55
+ self.eval_cache[key] = src
56
+
57
+ # Don't mutate globals so that this loader is only used
58
+ # to populate linecache, and doesn't interact with other modules
59
+ # that might check `__loader__`
60
+ globals_copy = globals.copy()
61
+ globals_copy["__file__"] = key
62
+ globals_copy["__name__"] = key
63
+ globals_copy["__loader__"] = self
64
+ linecache.lazycache(key, globals_copy)
65
+
66
+ return key
67
+
68
+ # Part of the loader protocol (PEP 302)
69
+ # linecache will use this method when trying to find source code
70
+ def get_source(self, module_name) -> Optional[str]:
71
+ if module_name in self.eval_cache:
72
+ return self.eval_cache[module_name]
73
+ return None
74
+
75
+ def _get_key(self):
76
+ key = f"<eval_with_key>.{self.next_id}"
77
+ self.next_id += 1
78
+ return key
79
+
80
+
81
+ _loader = _EvalCacheLoader()
82
+
83
+
84
+ def _exec_with_source(src: str, globals: Dict[str, Any], co_fields=None):
85
+ key = _loader.cache(src, globals, co_fields)
86
+ exec(compile(src, key, "exec"), globals)
87
+
88
+
89
+ def _forward_from_src(src: str, globals: Dict[str, Any], co_fields=None):
90
+ return _method_from_src(
91
+ method_name="forward", src=src, globals=globals, co_fields=co_fields
92
+ )
93
+
94
+
95
+ def _method_from_src(
96
+ method_name: str, src: str, globals: Dict[str, Any], co_fields=None
97
+ ) -> Callable:
98
+ # avoid mutating the passed in dict
99
+ globals_copy = globals.copy()
100
+ _exec_with_source(src, globals_copy, co_fields)
101
+ fn = globals_copy[method_name]
102
+ del globals_copy[method_name]
103
+ return fn
104
+
105
+
106
+ def _format_import_statement(name: str, obj: Any, importer: Importer) -> str:
107
+ if name in _custom_builtins:
108
+ return _custom_builtins[name].import_str
109
+ if _is_from_torch(name):
110
+ return "import torch"
111
+ module_name, attr_name = importer.get_name(obj)
112
+ return f"from {module_name} import {attr_name} as {name}"
113
+
114
+
115
+ def _format_import_block(globals: Dict[str, Any], importer: Importer):
116
+ import_strs: Set[str] = {_format_import_statement(name, obj, importer) for name, obj in globals.items()}
117
+ # Sort the imports so we have a stable import block that allows us to
118
+ # hash the graph module and get a consistent key for use in a cache.
119
+ return "\n".join(sorted(import_strs))
120
+
121
+
122
+ @compatibility(is_backward_compatible=True)
123
+ def reduce_graph_module(body: Dict[Any, Any], import_block: str) -> torch.nn.Module:
124
+ # BC: attribute name was changed from `code` to `_code` to facilitate
125
+ # making `code` into a property and adding a docstring to it
126
+ fn_src = body.get("_code") or body["code"]
127
+ forward = _forward_from_src(import_block + fn_src, {})
128
+ return _deserialize_graph_module(forward, body)
129
+
130
+
131
+ @compatibility(is_backward_compatible=True)
132
+ def reduce_package_graph_module(
133
+ importer: PackageImporter, body: Dict[Any, Any], generated_module_name: str
134
+ ) -> torch.nn.Module:
135
+ forward = importer.import_module(generated_module_name).forward
136
+ return _deserialize_graph_module(forward, body)
137
+
138
+
139
+ @compatibility(is_backward_compatible=True)
140
+ def reduce_deploy_graph_module(
141
+ importer: PackageImporter, body: Dict[Any, Any], import_block: str
142
+ ) -> torch.nn.Module:
143
+ ns = {}
144
+ ns["__builtins__"] = importer.patched_builtins
145
+ fn_src = body.get("_code")
146
+ assert fn_src is not None
147
+ forward = _forward_from_src(import_block + fn_src, ns)
148
+ return _deserialize_graph_module(forward, body)
149
+
150
+
151
+ # We create a dummy class here because symbolic_trace pulls the forward()
152
+ # function off of the class, rather than the instance. This class is used
153
+ # in _deserialize_graph_module() below.
154
+ class _CodeOnlyModule(torch.nn.Module):
155
+ def __init__(self, body):
156
+ super().__init__()
157
+ self.__dict__ = body
158
+
159
+
160
+ def _deserialize_graph_module(forward, body: Dict[Any, Any], graph_module_cls=None) -> torch.nn.Module:
161
+ """
162
+ Deserialize a GraphModule given the dictionary of the original module,
163
+ using the code to reconstruct the graph. We delete the actual graph before
164
+ saving the dictionary so that changes to the in-memory graph format do not
165
+ get serialized.
166
+ """
167
+
168
+ # Try to retrieve the forward source in a backward-compatible way
169
+ _CodeOnlyModule.forward = forward
170
+
171
+ tracer_cls = body.get("_tracer_cls")
172
+ if tracer_cls is None:
173
+ from ._symbolic_trace import Tracer
174
+
175
+ tracer_cls = Tracer
176
+
177
+ graphmodule_cls_name = body.get("_graphmodule_cls_name", "GraphModule")
178
+
179
+ # This is a workaround for a mypy linter issue related to
180
+ # passing base class as an argument - https://github.com/python/mypy/issues/5865.
181
+ cls_tracer: Any = tracer_cls
182
+
183
+ class KeepModules(cls_tracer):
184
+ # we shouldn't trace into any of the submodules,
185
+ # because they were not traced in the original GraphModule
186
+ def is_leaf_module(self, _: torch.nn.Module, __: str) -> bool:
187
+ return True
188
+
189
+ com = _CodeOnlyModule(body)
190
+
191
+ tracer_extras = body.get("_tracer_extras", {})
192
+ graph = KeepModules().trace(com, **tracer_extras)
193
+
194
+ # Manually set Tracer class on the reconstructed Graph, to avoid
195
+ # referencing the private local subclass KeepModules.
196
+ graph._tracer_cls = tracer_cls
197
+ from ._lazy_graph_module import _make_graph_module
198
+ gm = _make_graph_module(com, graph, class_name=graphmodule_cls_name, graph_module_cls=graph_module_cls)
199
+
200
+ # The GraphModule constructor only retains attributes referenced by the graph.
201
+ # In this case, our goal is return a GraphModule as close to identical as the one
202
+ # put into the package. If any additional attributes were present in body,
203
+ # we should keep them.
204
+ for k, v in body.items():
205
+ if not hasattr(gm, k):
206
+ setattr(gm, k, v)
207
+ return gm
208
+
209
+
210
+ # copy an attribute value with qualified name 'target' from 'from_module' to 'to_module'
211
+ # This installs empty Modules where none exist yet if they are subpaths of target
212
+ def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str):
213
+ *prefix, field = target.split(".")
214
+ for item in prefix:
215
+ f = getattr(from_module, item)
216
+ t = getattr(to_module, item, None)
217
+ if f is t:
218
+ # we have already installed one of its parents
219
+ # (e.g. target = root.linear.weight, but we have already installed root.linear)
220
+ # once we install a parent, we no longer need to copy the children
221
+ # since all the needed properties will already be present
222
+ return
223
+
224
+ if t is None:
225
+ t = torch.nn.Module()
226
+ setattr(to_module, item, t)
227
+ from_module, to_module = f, t
228
+
229
+ orig = getattr(from_module, field)
230
+ # If it is a tensor and not a parameter attribute of a module, it should be a named buffer.
231
+ # So, we register it as a named buffer in the target module.
232
+ if isinstance(orig, torch.Tensor) and not isinstance(orig, torch.nn.Parameter):
233
+ to_module.register_buffer(field, orig)
234
+ else:
235
+ setattr(to_module, field, orig)
236
+
237
+
238
+ # Assign attribute 'from_obj' to the qualified name 'target' on 'to_module
239
+ # This installs empty Modules where none exist yet if they are subpaths of target
240
+ def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str):
241
+ *prefix, field = target.split(".")
242
+ for item in prefix:
243
+ t = getattr(to_module, item, None)
244
+
245
+ if t is None:
246
+ t = torch.nn.Module()
247
+ setattr(to_module, item, t)
248
+ to_module = t
249
+
250
+ # If it is a tensor and not a parameter attribute of a module, it should be a named buffer.
251
+ # So, we register it as a named buffer in the target module.
252
+ if isinstance(from_obj, torch.Tensor) and not isinstance(
253
+ from_obj, torch.nn.Parameter
254
+ ):
255
+ to_module.register_buffer(field, from_obj)
256
+ else:
257
+ setattr(to_module, field, from_obj)
258
+
259
+
260
+ def _print_readable(
261
+ module,
262
+ module_name,
263
+ print_output=True,
264
+ include_stride=False,
265
+ include_device=False,
266
+ colored=False,
267
+ ):
268
+ graph = module.graph
269
+ assert graph is not None and isinstance(graph, torch.fx.Graph), "print_readable must be used on a module with a graph"
270
+
271
+ verbose_python_code = graph.python_code(
272
+ root_module="self",
273
+ verbose=True,
274
+ include_stride=include_stride,
275
+ include_device=include_device,
276
+ colored=colored,
277
+ )
278
+ module_code = verbose_python_code.src
279
+ module_code = module_code.lstrip("\n")
280
+ module_code = f"class {module_name}(torch.nn.Module):\n" + module_code
281
+ module_code = _addindent(module_code, 4)
282
+
283
+ submodule_code_list = [""]
284
+ for submodule_name, submodule in module.named_children():
285
+ if hasattr(submodule, "graph"):
286
+ submodule_code_list.append(
287
+ _print_readable(
288
+ submodule,
289
+ submodule_name,
290
+ print_output=False,
291
+ include_stride=include_stride,
292
+ include_device=include_device,
293
+ colored=colored,
294
+ )
295
+ )
296
+ submodule_code = "\n".join(submodule_code_list)
297
+ submodule_code = _addindent(submodule_code, 4)
298
+
299
+ output = module_code + submodule_code
300
+ if print_output:
301
+ print(module_code + submodule_code)
302
+ return output
303
+
304
+
305
+ class _WrappedCall:
306
+ def __init__(self, cls, cls_call):
307
+ self.cls = cls
308
+ self.cls_call = cls_call
309
+
310
+ # Previously, if an error occurred when valid
311
+ # symbolically-traced code was run with an invalid input, the
312
+ # user would see the source of the error as coming from
313
+ # `File "<eval_with_key_N">`, where N is some number. We use
314
+ # this function to generate a more informative error message. We
315
+ # return the traceback itself, a message explaining that the
316
+ # error occurred in a traced Module's generated forward
317
+ # function, and five lines of context surrounding the faulty
318
+ # line
319
+ @staticmethod
320
+ def _generate_error_message(frame_summary: traceback.FrameSummary) -> str:
321
+ # auxiliary variables (for readability)
322
+ err_lineno = frame_summary.lineno
323
+ assert err_lineno is not None
324
+ line = frame_summary.line
325
+ assert line is not None
326
+ err_line_len = len(line)
327
+ all_src_lines = linecache.getlines(frame_summary.filename)
328
+
329
+ # constituent substrings of the error message
330
+ tb_repr = torch._dynamo.disable(traceback.format_exc)()
331
+ custom_msg = (
332
+ "Call using an FX-traced Module, "
333
+ f"line {err_lineno} of the traced Module's "
334
+ "generated forward function:"
335
+ )
336
+ before_err = "".join(all_src_lines[err_lineno - 2 : err_lineno])
337
+ marker = "~" * err_line_len + "~~~ <--- HERE"
338
+ err_and_after_err = "\n".join(all_src_lines[err_lineno : err_lineno + 2])
339
+
340
+ # joined message
341
+ return "\n".join([tb_repr, custom_msg, before_err, marker, err_and_after_err])
342
+
343
+ def __call__(self, obj, *args, **kwargs):
344
+ try:
345
+ if self.cls_call is not None:
346
+ return self.cls_call(obj, *args, **kwargs)
347
+ else:
348
+ return super(self.cls, obj).__call__(*args, **kwargs) # type: ignore[misc]
349
+ except Exception as e:
350
+ assert e.__traceback__
351
+ topmost_framesummary: traceback.FrameSummary = (
352
+ traceback.StackSummary.extract(traceback.walk_tb(e.__traceback__))[-1]
353
+ ) # type: ignore[arg-type]
354
+ if "eval_with_key" in topmost_framesummary.filename:
355
+ print(
356
+ _WrappedCall._generate_error_message(topmost_framesummary),
357
+ file=sys.stderr,
358
+ )
359
+ raise e.with_traceback(None) # noqa: B904
360
+ else:
361
+ raise e
362
+
363
+ @compatibility(is_backward_compatible=True)
364
+ class GraphModule(torch.nn.Module):
365
+ """
366
+ GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a
367
+ ``graph`` attribute, as well as ``code`` and ``forward`` attributes generated
368
+ from that ``graph``.
369
+
370
+ .. warning::
371
+
372
+ When ``graph`` is reassigned, ``code`` and ``forward`` will be automatically
373
+ regenerated. However, if you edit the contents of the ``graph`` without reassigning
374
+ the ``graph`` attribute itself, you must call ``recompile()`` to update the generated
375
+ code.
376
+ """
377
+
378
+ def __new__(cls: "Type[GraphModule]", *args, **kwargs):
379
+ # each instance of a graph module needs its own forward method
380
+ # so create a new singleton class for each instance.
381
+ # it is a subclass of the user-defined class, the only difference
382
+ # is an extra layer to install the forward method
383
+
384
+ # address issue described at https://github.com/pytorch/pytorch/issues/63883
385
+ # in other words, traverse class hierarchy to fix the redundant class definition problem
386
+ for t in cls.__mro__:
387
+ c = t.__qualname__.split(".")[-1]
388
+ if c != "GraphModuleImpl":
389
+ cls = t
390
+ break
391
+
392
+ class GraphModuleImpl(cls): # type: ignore[misc, valid-type]
393
+ pass
394
+
395
+ return super().__new__(GraphModuleImpl)
396
+
397
+ @compatibility(is_backward_compatible=True)
398
+ def __init__(
399
+ self,
400
+ root: Union[torch.nn.Module, Dict[str, Any]],
401
+ graph: Graph,
402
+ class_name: str = "GraphModule",
403
+ ):
404
+ """
405
+ Construct a GraphModule.
406
+
407
+ Args:
408
+
409
+ root (Union[torch.nn.Module, Dict[str, Any]):
410
+ ``root`` can either be an nn.Module instance or a Dict mapping strings to any attribute type.
411
+ In the case that ``root`` is a Module, any references to Module-based objects (via qualified
412
+ name) in the Graph's Nodes' ``target`` field will be copied over from the respective place
413
+ within ``root``'s Module hierarchy into the GraphModule's module hierarchy.
414
+ In the case that ``root`` is a dict, the qualified name found in a Node's ``target`` will be
415
+ looked up directly in the dict's keys. The object mapped to by the Dict will be copied
416
+ over into the appropriate place within the GraphModule's module hierarchy.
417
+
418
+ graph (Graph): ``graph`` contains the nodes this GraphModule should use for code generation
419
+
420
+ class_name (str): ``name`` denotes the name of this GraphModule for debugging purposes. If it's unset, all
421
+ error messages will report as originating from ``GraphModule``. It may be helpful to set this
422
+ to ``root``'s original name or a name that makes sense within the context of your transform.
423
+ """
424
+ super().__init__()
425
+ self.__class__.__name__ = class_name
426
+ if isinstance(root, torch.nn.Module):
427
+ if hasattr(root, "training"):
428
+ self.training = root.training
429
+
430
+ # When we pickle/unpickle graph module, we don't want to drop any module or attributes.
431
+ if isinstance(root, _CodeOnlyModule):
432
+ for k, _ in root.named_children():
433
+ _copy_attr(root, self, k)
434
+
435
+ for k, _ in root.named_buffers():
436
+ _copy_attr(root, self, k)
437
+
438
+ for k, _ in root.named_parameters():
439
+ _copy_attr(root, self, k)
440
+
441
+ for node in graph.nodes:
442
+ if node.op in ["get_attr", "call_module"]:
443
+ assert isinstance(node.target, str)
444
+ _copy_attr(root, self, node.target)
445
+ elif isinstance(root, dict):
446
+ targets_to_copy = []
447
+ for node in graph.nodes:
448
+ if node.op in ["get_attr", "call_module"]:
449
+ assert isinstance(node.target, str)
450
+ if node.target not in root:
451
+ raise RuntimeError(
452
+ "Node "
453
+ + str(node)
454
+ + " referenced target "
455
+ + node.target
456
+ + " but that target was not provided in ``root``!"
457
+ )
458
+ targets_to_copy.append(node.target)
459
+ # Sort targets in ascending order of the # of atoms.
460
+ # This will ensure that less deeply nested attributes are assigned
461
+ # before more deeply nested attributes. For example, foo.bar
462
+ # will be assigned before foo.bar.baz. Otherwise, we might assign
463
+ # the user-provided ``foo.bar`` and wipe out the previously-assigned
464
+ # ``foo.bar.baz``
465
+ targets_to_copy.sort(key=lambda t: t.count("."))
466
+ for target_to_copy in targets_to_copy:
467
+ _assign_attr(root[target_to_copy], self, target_to_copy)
468
+ else:
469
+ raise RuntimeError("Unsupported type " + str(root) + " passed for root!")
470
+
471
+ self.graph = graph
472
+
473
+ # Store the Tracer class responsible for creating a Graph separately as part of the
474
+ # GraphModule state, except when the Tracer is defined in a local namespace.
475
+ # Locally defined Tracers are not pickleable. This is needed because torch.package will
476
+ # serialize a GraphModule without retaining the Graph, and needs to use the correct Tracer
477
+ # to re-create the Graph during deserialization.
478
+ self._tracer_cls = None
479
+ if (
480
+ self.graph._tracer_cls
481
+ and "<locals>" not in self.graph._tracer_cls.__qualname__
482
+ ):
483
+ self._tracer_cls = self.graph._tracer_cls
484
+
485
+ self._tracer_extras = {}
486
+ if self.graph._tracer_extras:
487
+ self._tracer_extras = self.graph._tracer_extras
488
+
489
+ # Dictionary to store metadata
490
+ self.meta: Dict[str, Any] = {}
491
+ self._replace_hook = None
492
+ self._create_node_hooks: List[Callable] = []
493
+ self._erase_node_hooks: List[Callable] = []
494
+
495
+ # TorchScript breaks trying to compile the graph setter because of the
496
+ # continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842
497
+ #
498
+ # Shouldn't be an issue since these methods shouldn't be used in TorchScript anyway
499
+ __jit_unused_properties__ = ["graph"]
500
+
501
+ @property
502
+ def graph(self) -> Graph:
503
+ """
504
+ Return the ``Graph`` underlying this ``GraphModule``
505
+ """
506
+ return self._graph
507
+
508
+ @graph.setter
509
+ def graph(self, g: Graph) -> None:
510
+ """
511
+ Set the underlying ``Graph`` for this ``GraphModule``. This will internally
512
+ recompile the ``GraphModule`` so that the generated ``forward()`` function
513
+ corresponds to ``g``
514
+ """
515
+ assert isinstance(g, Graph), f"Expected a Graph instance, but got {type(g)}"
516
+ self._graph = g
517
+ g.owning_module = self
518
+ self.recompile()
519
+
520
+ @compatibility(is_backward_compatible=False)
521
+ def to_folder(self, folder: Union[str, os.PathLike], module_name: str = "FxModule"):
522
+ """Dumps out module to ``folder`` with ``module_name`` so that it can be
523
+ imported with ``from <folder> import <module_name>``
524
+
525
+ Args:
526
+
527
+ folder (Union[str, os.PathLike]): The folder to write the code out to
528
+
529
+ module_name (str): Top-level name to use for the ``Module`` while
530
+ writing out the code
531
+ """
532
+ folder = Path(folder)
533
+ Path(folder).mkdir(exist_ok=True)
534
+ torch.save(self.state_dict(), folder / "state_dict.pt")
535
+ tab = " " * 4
536
+ custom_builtins = "\n".join([v.import_str for v in _custom_builtins.values()])
537
+ model_str = f"""
538
+ import torch
539
+ {custom_builtins}
540
+
541
+ from torch.nn import *
542
+ class {module_name}(torch.nn.Module):
543
+ def __init__(self):
544
+ super().__init__()
545
+ """
546
+
547
+ def _gen_model_repr(module_name: str, module: torch.nn.Module) -> Optional[str]:
548
+ safe_reprs = [
549
+ nn.Linear,
550
+ nn.Conv1d,
551
+ nn.Conv2d,
552
+ nn.Conv3d,
553
+ nn.BatchNorm1d,
554
+ nn.BatchNorm2d,
555
+ nn.BatchNorm3d,
556
+ ]
557
+ if type(module) in safe_reprs:
558
+ return f"{module.__repr__()}"
559
+ else:
560
+ return None
561
+
562
+ blobified_modules = []
563
+ for module_name, module in self.named_children():
564
+ module_str = _gen_model_repr(module_name, module)
565
+ if module_str is None:
566
+ module_file = folder / f"{module_name}.pt"
567
+ torch.save(module, module_file)
568
+ blobified_modules.append(module_name)
569
+ module_repr = module.__repr__().replace("\r", " ").replace("\n", " ")
570
+ # weights_only=False as this is legacy code that saves the model
571
+ module_str = f"torch.load(r'{module_file}', weights_only=False) # {module_repr}"
572
+ model_str += f"{tab*2}self.{module_name} = {module_str}\n"
573
+
574
+ for buffer_name, buffer in self._buffers.items():
575
+ if buffer is None:
576
+ continue
577
+ model_str += f"{tab*2}self.register_buffer('{buffer_name}', torch.empty({list(buffer.shape)}, dtype={buffer.dtype}))\n"
578
+
579
+ for param_name, param in self._parameters.items():
580
+ if param is None:
581
+ continue
582
+ model_str += f"{tab*2}self.{param_name} = torch.nn.Parameter(torch.empty({list(param.shape)}, dtype={param.dtype}))\n"
583
+
584
+ model_str += (
585
+ f"{tab*2}self.load_state_dict(torch.load(r'{folder}/state_dict.pt'))\n"
586
+ )
587
+ model_str += f"{_addindent(self.code, 4)}\n"
588
+
589
+ module_file = folder / "module.py"
590
+ module_file.write_text(model_str)
591
+
592
+ init_file = folder / "__init__.py"
593
+ init_file.write_text("from .module import *")
594
+
595
+ if len(blobified_modules) > 0:
596
+ warnings.warn(
597
+ "Was not able to save the following children modules as reprs -"
598
+ f"saved as pickled files instead: {blobified_modules}"
599
+ )
600
+
601
+ @compatibility(is_backward_compatible=True)
602
+ def add_submodule(self, target: str, m: torch.nn.Module) -> bool:
603
+ """
604
+ Adds the given submodule to ``self``.
605
+
606
+ This installs empty Modules where none exist yet if they are
607
+ subpaths of ``target``.
608
+
609
+ Args:
610
+ target: The fully-qualified string name of the new submodule
611
+ (See example in ``nn.Module.get_submodule`` for how to
612
+ specify a fully-qualified string.)
613
+ m: The submodule itself; the actual object we want to
614
+ install in the current Module
615
+
616
+ Return:
617
+ bool: Whether or not the submodule could be inserted. For
618
+ this method to return True, each object in the chain
619
+ denoted by ``target`` must either a) not exist yet,
620
+ or b) reference an ``nn.Module`` (not a parameter or
621
+ other attribute)
622
+ """
623
+ *prefix, field = target.split(".")
624
+ mod: torch.nn.Module = self
625
+
626
+ for item in prefix:
627
+
628
+ submod = getattr(mod, item, None)
629
+
630
+ if submod is None:
631
+ submod = torch.nn.Module()
632
+ setattr(mod, item, submod)
633
+
634
+ if not isinstance(submod, torch.nn.Module):
635
+ return False
636
+
637
+ mod = submod
638
+
639
+ mod.add_module(field, m)
640
+ return True
641
+
642
+ @compatibility(is_backward_compatible=True)
643
+ def delete_submodule(self, target: str) -> bool:
644
+ """
645
+ Deletes the given submodule from ``self``.
646
+
647
+ The module will not be deleted if ``target`` is not a valid
648
+ target.
649
+
650
+ Args:
651
+ target: The fully-qualified string name of the new submodule
652
+ (See example in ``nn.Module.get_submodule`` for how to
653
+ specify a fully-qualified string.)
654
+
655
+ Returns:
656
+ bool: Whether or not the target string referenced a
657
+ submodule we want to delete. A return value of ``False``
658
+ means that the ``target`` was not a valid reference to
659
+ a submodule.
660
+ """
661
+ atoms = target.split(".")
662
+ path, target_submod = atoms[:-1], atoms[-1]
663
+ mod: torch.nn.Module = self
664
+
665
+ # Get the parent module
666
+ for item in path:
667
+
668
+ if not hasattr(mod, item):
669
+ return False
670
+
671
+ mod = getattr(mod, item)
672
+
673
+ if not isinstance(mod, torch.nn.Module):
674
+ return False
675
+
676
+ if not hasattr(mod, target_submod):
677
+ return False
678
+
679
+ if not isinstance(getattr(mod, target_submod), torch.nn.Module):
680
+ return False
681
+
682
+ delattr(mod, target_submod)
683
+ return True
684
+
685
+ @compatibility(is_backward_compatible=True)
686
+ def delete_all_unused_submodules(self) -> None:
687
+ """
688
+ Deletes all unused submodules from ``self``.
689
+
690
+ A Module is considered "used" if any one of the following is
691
+ true:
692
+ 1. It has children that are used
693
+ 2. Its forward is called directly via a ``call_module`` node
694
+ 3. It has a non-Module attribute that is used from a
695
+ ``get_attr`` node
696
+
697
+ This method can be called to clean up an ``nn.Module`` without
698
+ manually calling ``delete_submodule`` on each unused submodule.
699
+ """
700
+ used: List[str] = []
701
+
702
+ for node in self.graph.nodes:
703
+
704
+ if node.op == "call_module" or node.op == "get_attr":
705
+
706
+ # A list of strings representing the different parts
707
+ # of the path. For example, `foo.bar.baz` gives us
708
+ # ["foo", "bar", "baz"]
709
+ fullpath = node.target.split(".")
710
+
711
+ # If we're looking at multiple parts of a path, join
712
+ # join them with a dot. Otherwise, return that single
713
+ # element without doing anything to it.
714
+ def join_fn(x: str, y: str) -> str:
715
+ return ".".join([x, y] if y else [x])
716
+
717
+ # Progressively collect all the names of intermediate
718
+ # modules. For example, if we have the target
719
+ # `foo.bar.baz`, we'll add `foo`, `foo.bar`, and
720
+ # `foo.bar.baz` to the list.
721
+ used.extend(itertools.accumulate(fullpath, join_fn))
722
+
723
+ # For a `call_module` node, also register all recursive submodules
724
+ # as used
725
+ if node.op == "call_module":
726
+ try:
727
+ submod = self.get_submodule(node.target)
728
+
729
+ for submod_name, _ in submod.named_modules():
730
+ if submod_name != "":
731
+ used.append(".".join([node.target, submod_name]))
732
+ except AttributeError:
733
+ # Node referenced nonexistent submodule, don't need to
734
+ # worry about GCing anything
735
+ pass
736
+
737
+ to_delete = [name for name, _ in self.named_modules() if name not in used]
738
+
739
+ for name in to_delete:
740
+ self.delete_submodule(name)
741
+
742
+ @property
743
+ def code(self) -> str:
744
+ """
745
+ Return the Python code generated from the ``Graph`` underlying this
746
+ ``GraphModule``.
747
+ """
748
+ if not hasattr(self, "_code"):
749
+ raise RuntimeError(
750
+ "Code has not been generated! Please report a bug to PyTorch"
751
+ )
752
+ return self._code
753
+
754
+ @compatibility(is_backward_compatible=True)
755
+ def recompile(self) -> PythonCode:
756
+ """
757
+ Recompile this GraphModule from its ``graph`` attribute. This should be
758
+ called after editing the contained ``graph``, otherwise the generated
759
+ code of this ``GraphModule`` will be out of date.
760
+ """
761
+ if isinstance(self._graph._codegen, _PyTreeCodeGen):
762
+ self._in_spec = self._graph._codegen.pytree_info.in_spec
763
+ self._out_spec = self._graph._codegen.pytree_info.out_spec
764
+ python_code = self._graph.python_code(root_module="self")
765
+ self._code = python_code.src
766
+ self._lineno_map = python_code._lineno_map
767
+
768
+ cls = type(self)
769
+ co_fields = self._graph._co_fields if hasattr(self._graph, "_co_fields") else {}
770
+ cls.forward = _forward_from_src(self._code, python_code.globals, co_fields)
771
+
772
+ # Determine whether this class explicitly defines a __call__ implementation
773
+ # to wrap. If it does, save it in order to have wrapped_call invoke it.
774
+ # If it does not, wrapped_call can use a dynamic call to super() instead.
775
+ # In most cases, super().__call__ should be torch.nn.Module.__call__.
776
+ # We do not want to hold a reference to Module.__call__ here; doing so will
777
+ # bypass patching of torch.nn.Module.__call__ done while symbolic tracing.
778
+ cls_call = cls.__call__ if "__call__" in vars(cls) else None
779
+
780
+ if "_wrapped_call" not in vars(cls):
781
+ cls._wrapped_call = _WrappedCall(cls, cls_call) # type: ignore[attr-defined]
782
+
783
+ def call_wrapped(self, *args, **kwargs):
784
+ return self._wrapped_call(self, *args, **kwargs)
785
+
786
+ cls.__call__ = call_wrapped # type: ignore[method-assign]
787
+
788
+ return python_code
789
+
790
+ # Passing Tracer as argument allows subclasses extending fx.GraphModule
791
+ # define their own Tracer (extending fx.Tracer).
792
+ def __reduce_deploy__(self, importer: Importer):
793
+ dict_without_graph = self.__dict__.copy()
794
+ dict_without_graph["_graphmodule_cls_name"] = self.__class__.__name__
795
+ del dict_without_graph["_graph"]
796
+
797
+ python_code = self.recompile()
798
+ import_block = _format_import_block(python_code.globals, importer)
799
+ return (reduce_deploy_graph_module, (dict_without_graph, import_block))
800
+
801
+ def __reduce_package__(self, exporter: PackageExporter):
802
+ dict_without_graph = self.__dict__.copy()
803
+ dict_without_graph["_graphmodule_cls_name"] = self.__class__.__name__
804
+ del dict_without_graph["_graph"]
805
+
806
+ generated_module_name = f"fx-generated._{exporter.get_unique_id()}"
807
+ python_code = self.recompile()
808
+ import_block = _format_import_block(python_code.globals, exporter.importer)
809
+ module_code = import_block + self.code
810
+ exporter.save_source_string(generated_module_name, module_code)
811
+ return (
812
+ reduce_package_graph_module,
813
+ (dict_without_graph, generated_module_name),
814
+ )
815
+
816
+ def __reduce__(self):
817
+ """
818
+ Serialization of GraphModule. We serialize only the generated code, not
819
+ the underlying ``Graph``. This is because ``Graph`` does not have on-disk
820
+ backward-compatibility guarantees, whereas Python source code does.
821
+ On the deserialization side, we symbolically trace through the generated
822
+ code to regenerate the underlying ``Graph``
823
+ """
824
+ dict_without_graph = self.__dict__.copy()
825
+
826
+ python_code = self.recompile()
827
+ import_block = _format_import_block(python_code.globals, sys_importer)
828
+ del dict_without_graph["_graph"]
829
+ return (reduce_graph_module, (dict_without_graph, import_block))
830
+
831
+ def _deepcopy_init(self):
832
+ return GraphModule.__init__
833
+
834
+ # because __reduce__ is defined for serialization,
835
+ # we need to define deepcopy otherwise it will call __reduce__
836
+ # and cause symbolic tracing to occur every time we try to copy the object
837
+ def __deepcopy__(self, memo):
838
+ res = type(self).__new__(type(self))
839
+ memo[id(self)] = res
840
+ fake_mod = _CodeOnlyModule(copy.deepcopy(self.__dict__, memo))
841
+ self._deepcopy_init()(res, fake_mod, fake_mod.__dict__["_graph"])
842
+ # hooks are lost during `GraphModule.__init__`, so we need to copy over
843
+ # them explicitly, note right now we are only copying state_dict related
844
+ # hooks, to reduce bc-related issues, we can copy forward/backward related
845
+ # hooks in the future as well if needed
846
+ extra_preserved_attrs = [
847
+ "_state_dict_hooks",
848
+ "_load_state_dict_pre_hooks",
849
+ "_load_state_dict_post_hooks",
850
+ "_replace_hook",
851
+ "_create_node_hooks",
852
+ "_erase_node_hooks"
853
+ ]
854
+ for attr in extra_preserved_attrs:
855
+ if attr in self.__dict__:
856
+ setattr(res, attr, copy.deepcopy(self.__dict__[attr], memo))
857
+ res.meta = copy.deepcopy(getattr(self, "meta", {}), memo)
858
+ if _USER_PRESERVED_ATTRIBUTES_KEY in res.meta:
859
+ for attr_name, attr in res.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items():
860
+ setattr(res, attr_name, attr)
861
+ return res
862
+
863
+ def __copy__(self):
864
+ from ._lazy_graph_module import _make_graph_module
865
+ res = _make_graph_module(self, self.graph)
866
+ res.meta = getattr(self, "meta", {})
867
+ return res
868
+
869
+ @compatibility(is_backward_compatible=False)
870
+ def print_readable(self, print_output=True, include_stride=False, include_device=False, colored=False):
871
+ """
872
+ Return the Python code generated for current GraphModule and its children GraphModules
873
+ """
874
+ return _print_readable(
875
+ self,
876
+ self._get_name(),
877
+ print_output,
878
+ include_stride,
879
+ include_device,
880
+ colored,
881
+ )
882
+
883
+ def __str__(self) -> str:
884
+ orig_str = super().__str__()
885
+ print_readable_reminder = (
886
+ "# To see more debug info, please use `graph_module.print_readable()`"
887
+ )
888
+ return "\n".join([orig_str, self._code, print_readable_reminder])
889
+
890
+ def _replicate_for_data_parallel(self):
891
+ new_gm = self.__copy__()
892
+ new_gm._is_replica = True
893
+ return new_gm
894
+
895
+ @contextlib.contextmanager
896
+ def _set_replace_hook(self, f):
897
+ """
898
+ Takes a callable which will be called everytime when we replace a node
899
+ to a new node, or change the node's name. Callable takes three arguments:
900
+ the old node we're changing, and NAME of the new node, followed by the
901
+ user node which consumes the old node to be replaced.
902
+ """
903
+ assert callable(f), "Replace hook must be a callable."
904
+ prev, self._replace_hook = self._replace_hook, f
905
+ try:
906
+ yield
907
+ finally:
908
+ self._replace_hook = prev
909
+
910
+ def _register_create_node_hook(self, f):
911
+ """
912
+ Takes a callable which will be called after we create a new node. The
913
+ callable takes the newly created node as input and returns None.
914
+ """
915
+ assert callable(f), "create_node hook must be a callable."
916
+ self._create_node_hooks.append(f)
917
+
918
+ def _unregister_create_node_hook(self, f):
919
+ """
920
+ Takes a callable which was previously registered to be called after we create a node.
921
+ This function will unregister that callable so it is no longer invoked on node creation.
922
+ """
923
+ assert callable(f), "create_node hook must be a callable."
924
+ self._create_node_hooks.remove(f)
925
+
926
+ def _register_erase_node_hook(self, f):
927
+ """
928
+ Takes a callable which will be called after we erase a node. The
929
+ callable takes the node that is being erased as input and returns None.
930
+ """
931
+ assert callable(f), "erase_node hook must be a callable."
932
+ self._erase_node_hooks.append(f)
933
+
934
+ def _unregister_erase_node_hook(self, f):
935
+ """
936
+ Takes a callable which was previously registered to be called after we erase a node.
937
+ This function will unregister that callable so it is no longer invoked on node erasure.
938
+ """
939
+ assert callable(f), "erase_node hook must be a callable."
940
+ self._erase_node_hooks.remove(f)
941
+
942
+ # workarounds for issues in __torch_function__
943
+
944
+ # WAR for __torch_function__ not handling tensor lists,
945
+ # fix is in https://github.com/pytorch/pytorch/pull/34725
946
+ # orig_cat = torch.cat
947
+ # def patched_cat(*args, **kwargs):
948
+ # tensors = args[0]
949
+ # for t in tensors:
950
+ # if isinstance(t, Proxy):
951
+ # return t.__torch_function__(patched_cat, (), args, kwargs)
952
+ # return orig_cat(*args, **kwargs)
953
+ # patched_cat.__module__ = 'torch'
954
+ # patched_cat.__name__ = 'cat'
955
+ # torch.cat = patched_cat
mplug_owl2/lib/python3.10/site-packages/torch/fx/interpreter.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from .graph_module import GraphModule
3
+ from ._lazy_graph_module import _make_graph_module
4
+ from .graph import Graph
5
+ from .node import Argument, Node, Target, map_arg, map_aggregate
6
+ from .proxy import Proxy
7
+ from ._symbolic_trace import Tracer
8
+ from ._compatibility import compatibility
9
+ from . import config
10
+ import torch.fx.traceback as fx_traceback
11
+ import torch
12
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
13
+ import inspect
14
+ from contextlib import contextmanager
15
+ from torch.hub import tqdm
16
+
17
+ __all__ = ['Interpreter', 'Transformer']
18
+
19
+ @compatibility(is_backward_compatible=True)
20
+ class Interpreter:
21
+ """
22
+ An Interpreter executes an FX graph Node-by-Node. This pattern
23
+ can be useful for many things, including writing code
24
+ transformations as well as analysis passes.
25
+
26
+ Methods in the Interpreter class can be overridden to customize
27
+ the behavior of execution. The map of overrideable methods
28
+ in terms of call hierarchy::
29
+
30
+ run()
31
+ +-- run_node
32
+ +-- placeholder()
33
+ +-- get_attr()
34
+ +-- call_function()
35
+ +-- call_method()
36
+ +-- call_module()
37
+ +-- output()
38
+
39
+ Example:
40
+
41
+ Suppose we want to swap all instances of ``torch.neg`` with
42
+ ``torch.sigmoid`` and vice versa (including their ``Tensor``
43
+ method equivalents). We could subclass Interpreter like so::
44
+
45
+ class NegSigmSwapInterpreter(Interpreter):
46
+ def call_function(self, target : Target,
47
+ args : Tuple, kwargs : Dict) -> Any:
48
+ if target == torch.sigmoid:
49
+ return torch.neg(*args, **kwargs)
50
+ return super().call_function(n)
51
+
52
+ def call_method(self, target : Target,
53
+ args : Tuple, kwargs : Dict) -> Any:
54
+ if target == 'neg':
55
+ call_self, *args_tail = args
56
+ return call_self.sigmoid(*args_tail, **kwargs)
57
+ return super().call_method(n)
58
+
59
+ def fn(x):
60
+ return torch.sigmoid(x).neg()
61
+
62
+ gm = torch.fx.symbolic_trace(fn)
63
+ input = torch.randn(3, 4)
64
+ result = NegSigmSwapInterpreter(gm).run(input)
65
+ torch.testing.assert_close(result, torch.neg(input).sigmoid())
66
+
67
+ Args:
68
+ module (torch.nn.Module): The module to be executed
69
+ garbage_collect_values (bool): Whether to delete values after their last
70
+ use within the Module's execution. This ensures optimal memory usage during
71
+ execution. This can be disabled to, for example, examine all of the intermediate
72
+ values in the execution by looking at the ``Interpreter.env`` attribute.
73
+ graph (Optional[Graph]): If passed, the interpreter will execute this
74
+ graph instead of `module.graph`, using the provided `module`
75
+ argument to satisfy any requests for state.
76
+ """
77
+ @compatibility(is_backward_compatible=True)
78
+ def __init__(self, module: torch.nn.Module, garbage_collect_values: bool = True, graph: Optional[Graph] = None):
79
+ self.module = module
80
+ self.submodules = dict(self.module.named_modules())
81
+ if graph is not None:
82
+ self.graph = graph
83
+ else:
84
+ self.graph = self.module.graph
85
+ self.env : Dict[Node, Any] = {}
86
+ self.name = "Interpreter"
87
+ self.garbage_collect_values = garbage_collect_values
88
+ self.extra_traceback = True
89
+
90
+ if self.garbage_collect_values:
91
+ # Run through reverse nodes and record the first instance of a use
92
+ # of a given node. This represents the *last* use of the node in the
93
+ # execution order of the program, which we will use to free unused
94
+ # values
95
+ node_to_last_use : Dict[Node, Node] = {}
96
+ self.user_to_last_uses : Dict[Node, List[Node]] = {}
97
+
98
+ def register_last_uses(n : Node, user : Node):
99
+ if n not in node_to_last_use:
100
+ node_to_last_use[n] = user
101
+ self.user_to_last_uses.setdefault(user, []).append(n)
102
+
103
+ for node in reversed(self.graph.nodes):
104
+ map_arg(node.args, lambda n: register_last_uses(n, node))
105
+ map_arg(node.kwargs, lambda n: register_last_uses(n, node))
106
+
107
+ @compatibility(is_backward_compatible=True)
108
+ def run(self, *args, initial_env : Optional[Dict[Node, Any]] = None, enable_io_processing : bool = True) -> Any:
109
+ """
110
+ Run `module` via interpretation and return the result.
111
+
112
+ Args:
113
+ *args: The arguments to the Module to run, in positional order
114
+ initial_env (Optional[Dict[Node, Any]]): An optional starting environment for execution.
115
+ This is a dict mapping `Node` to any value. This can be used, for example, to
116
+ pre-populate results for certain `Nodes` so as to do only partial evaluation within
117
+ the interpreter.
118
+ enable_io_processing (bool): If true, we process the inputs and outputs with graph's process_inputs and
119
+ process_outputs function first before using them.
120
+
121
+ Returns:
122
+ Any: The value returned from executing the Module
123
+ """
124
+ self.env = initial_env if initial_env is not None else {}
125
+
126
+ # Positional function args are consumed left-to-right by
127
+ # `placeholder` nodes. Use an iterator to keep track of
128
+ # position and extract those values.
129
+ if enable_io_processing:
130
+ args = self.graph.process_inputs(*args)
131
+ self.args_iter : Iterator[Any] = iter(args)
132
+ pbar = tqdm(total=len(self.graph.nodes),
133
+ desc=f"{self.name}: {str(list(self.graph.nodes)) if config.verbose_progress else ''}",
134
+ initial=0, position=0, leave=True, disable=config.disable_progress, delay=0)
135
+
136
+ for node in self.graph.nodes:
137
+ pbar.update(1)
138
+ if node in self.env:
139
+ # Short circuit if we have this value. This could
140
+ # be used, for example, for partial evaluation
141
+ # where the caller has pre-populated `env` with
142
+ # values for a subset of the program.
143
+ continue
144
+
145
+ try:
146
+ self.env[node] = self.run_node(node)
147
+ except Exception as e:
148
+ if self.extra_traceback:
149
+ msg = f"While executing {node.format_node()}"
150
+ msg = f'{e.args[0]}\n\n{msg}' if e.args else str(msg)
151
+ msg += f"\nOriginal traceback:\n{node.stack_trace}"
152
+ e.args = (msg,) + e.args[1:]
153
+ if isinstance(e, KeyError):
154
+ raise RuntimeError(*e.args) from e
155
+ raise
156
+
157
+ if self.garbage_collect_values:
158
+ for to_delete in self.user_to_last_uses.get(node, []):
159
+ del self.env[to_delete]
160
+
161
+ if node.op == 'output':
162
+ output_val = self.env[node]
163
+ return self.graph.process_outputs(output_val) if enable_io_processing else output_val
164
+
165
+ @compatibility(is_backward_compatible=True)
166
+ def boxed_run(self, args_list):
167
+ """
168
+ Run `module` via interpretation and return the result. This uses the "boxed"
169
+ calling convention, where you pass a list of arguments, which will be cleared
170
+ by the interpreter. This ensures that input tensors are promptly deallocated.
171
+ """
172
+ args_iter = iter(args_list)
173
+ env = {}
174
+ for n in self.graph.nodes:
175
+ if n.op == "placeholder":
176
+ env[n] = next(args_iter)
177
+ args_list.clear()
178
+ return self.run(initial_env=env)
179
+
180
+ @contextmanager
181
+ def _set_current_node(self, node):
182
+ with fx_traceback.set_current_meta(node):
183
+ yield
184
+
185
+ @compatibility(is_backward_compatible=True)
186
+ def run_node(self, n : Node) -> Any:
187
+ """
188
+ Run a specific node ``n`` and return the result.
189
+ Calls into placeholder, get_attr, call_function,
190
+ call_method, call_module, or output depending
191
+ on ``node.op``
192
+
193
+ Args:
194
+ n (Node): The Node to execute
195
+
196
+ Returns:
197
+ Any: The result of executing ``n``
198
+ """
199
+ with self._set_current_node(n):
200
+ args, kwargs = self.fetch_args_kwargs_from_env(n)
201
+ assert isinstance(args, tuple)
202
+ assert isinstance(kwargs, dict)
203
+ return getattr(self, n.op)(n.target, args, kwargs)
204
+
205
+ # Main Node running APIs
206
+ @compatibility(is_backward_compatible=True)
207
+ def placeholder(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
208
+ """
209
+ Execute a ``placeholder`` node. Note that this is stateful:
210
+ ``Interpreter`` maintains an internal iterator over
211
+ arguments passed to ``run`` and this method returns
212
+ next() on that iterator.
213
+
214
+ Args:
215
+ target (Target): The call target for this node. See
216
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
217
+ details on semantics
218
+ args (Tuple): Tuple of positional args for this invocation
219
+ kwargs (Dict): Dict of keyword arguments for this invocation
220
+
221
+ Returns:
222
+ Any: The argument value that was retrieved.
223
+ """
224
+ assert isinstance(target, str)
225
+ if target.startswith('*'):
226
+ # For a starred parameter e.g. `*args`, retrieve all
227
+ # remaining values from the args list.
228
+ return list(self.args_iter)
229
+ else:
230
+ try:
231
+ return next(self.args_iter)
232
+ except StopIteration as si:
233
+ if len(args) > 0:
234
+ return args[0]
235
+ else:
236
+ raise RuntimeError(f'Expected positional argument for parameter {target}, but one was not passed in!') from si
237
+
238
+ @compatibility(is_backward_compatible=True)
239
+ def get_attr(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
240
+ """
241
+ Execute a ``get_attr`` node. Will retrieve an attribute
242
+ value from the ``Module`` hierarchy of ``self.module``.
243
+
244
+ Args:
245
+ target (Target): The call target for this node. See
246
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
247
+ details on semantics
248
+ args (Tuple): Tuple of positional args for this invocation
249
+ kwargs (Dict): Dict of keyword arguments for this invocation
250
+
251
+ Return:
252
+ Any: The value of the attribute that was retrieved
253
+ """
254
+ assert isinstance(target, str)
255
+ return self.fetch_attr(target)
256
+
257
+ @compatibility(is_backward_compatible=True)
258
+ def call_function(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
259
+ """
260
+ Execute a ``call_function`` node and return the result.
261
+
262
+ Args:
263
+ target (Target): The call target for this node. See
264
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
265
+ details on semantics
266
+ args (Tuple): Tuple of positional args for this invocation
267
+ kwargs (Dict): Dict of keyword arguments for this invocation
268
+
269
+ Return
270
+ Any: The value returned by the function invocation
271
+ """
272
+ assert not isinstance(target, str)
273
+
274
+ # Execute the function and return the result
275
+ return target(*args, **kwargs)
276
+
277
+ @compatibility(is_backward_compatible=True)
278
+ def call_method(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
279
+ """
280
+ Execute a ``call_method`` node and return the result.
281
+
282
+ Args:
283
+ target (Target): The call target for this node. See
284
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
285
+ details on semantics
286
+ args (Tuple): Tuple of positional args for this invocation
287
+ kwargs (Dict): Dict of keyword arguments for this invocation
288
+
289
+ Return
290
+ Any: The value returned by the method invocation
291
+ """
292
+ # args[0] is the `self` object for this method call
293
+ self_obj, *args_tail = args
294
+
295
+ # Execute the method and return the result
296
+ assert isinstance(target, str)
297
+ return getattr(self_obj, target)(*args_tail, **kwargs)
298
+
299
+ @compatibility(is_backward_compatible=True)
300
+ def call_module(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
301
+ """
302
+ Execute a ``call_module`` node and return the result.
303
+
304
+ Args:
305
+ target (Target): The call target for this node. See
306
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
307
+ details on semantics
308
+ args (Tuple): Tuple of positional args for this invocation
309
+ kwargs (Dict): Dict of keyword arguments for this invocation
310
+
311
+ Return
312
+ Any: The value returned by the module invocation
313
+ """
314
+ # Retrieve executed args and kwargs values from the environment
315
+
316
+ # Execute the method and return the result
317
+ assert isinstance(target, str)
318
+ submod = self.fetch_attr(target)
319
+
320
+ return submod(*args, **kwargs)
321
+
322
+ @compatibility(is_backward_compatible=True)
323
+ def output(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
324
+ """
325
+ Execute an ``output`` node. This really just retrieves
326
+ the value referenced by the ``output`` node and returns it.
327
+
328
+ Args:
329
+ target (Target): The call target for this node. See
330
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
331
+ details on semantics
332
+ args (Tuple): Tuple of positional args for this invocation
333
+ kwargs (Dict): Dict of keyword arguments for this invocation
334
+
335
+ Return:
336
+ Any: The return value referenced by the output node
337
+ """
338
+ return args[0]
339
+
340
+ # Helper methods
341
+ @compatibility(is_backward_compatible=True)
342
+ def fetch_attr(self, target : str):
343
+ """
344
+ Fetch an attribute from the ``Module`` hierarchy of ``self.module``.
345
+
346
+ Args:
347
+ target (str): The fully-qualified name of the attribute to fetch
348
+
349
+ Return:
350
+ Any: The value of the attribute.
351
+ """
352
+ target_atoms = target.split('.')
353
+ attr_itr = self.module
354
+ for i, atom in enumerate(target_atoms):
355
+ if not hasattr(attr_itr, atom):
356
+ raise RuntimeError(f"Node referenced nonexistent target {'.'.join(target_atoms[:i+1])}")
357
+ attr_itr = getattr(attr_itr, atom)
358
+ return attr_itr
359
+
360
+ @compatibility(is_backward_compatible=True)
361
+ def fetch_args_kwargs_from_env(self, n : Node) -> Tuple[Tuple, Dict]:
362
+ """
363
+ Fetch the concrete values of ``args`` and ``kwargs`` of node ``n``
364
+ from the current execution environment.
365
+
366
+ Args:
367
+ n (Node): The node for which ``args`` and ``kwargs`` should be fetched.
368
+
369
+ Return:
370
+ Tuple[Tuple, Dict]: ``args`` and ``kwargs`` with concrete values for ``n``.
371
+ """
372
+ args = self.map_nodes_to_values(n.args, n)
373
+ assert isinstance(args, tuple)
374
+ kwargs = self.map_nodes_to_values(n.kwargs, n)
375
+ assert isinstance(kwargs, dict)
376
+ return args, kwargs
377
+
378
+ @compatibility(is_backward_compatible=True)
379
+ def map_nodes_to_values(self, args : Argument, n : Node) -> Argument:
380
+ """
381
+ Recursively descend through ``args`` and look up the concrete value
382
+ for each ``Node`` in the current execution environment.
383
+
384
+ Args:
385
+ args (Argument): Data structure within which to look up concrete values
386
+
387
+ n (Node): Node to which ``args`` belongs. This is only used for error reporting.
388
+ """
389
+ def load_arg(n_arg : Node) -> Any:
390
+ if n_arg not in self.env:
391
+ raise RuntimeError(f'Node {n} referenced nonexistent value {n_arg}! Run Graph.lint() '
392
+ f'to diagnose such issues')
393
+ return self.env[n_arg]
394
+ return map_arg(args, load_arg)
395
+
396
+ @compatibility(is_backward_compatible=True)
397
+ class Transformer(Interpreter):
398
+ """
399
+ ``Transformer`` is a special type of interpreter that produces a
400
+ new ``Module``. It exposes a ``transform()`` method that returns
401
+ the transformed ``Module``. ``Transformer`` does not require
402
+ arguments to run, as ``Interpreter`` does. ``Transformer`` works
403
+ entirely symbolically.
404
+
405
+ Example:
406
+
407
+ Suppose we want to swap all instances of ``torch.neg`` with
408
+ ``torch.sigmoid`` and vice versa (including their ``Tensor``
409
+ method equivalents). We could subclass ``Transformer`` like so::
410
+
411
+ class NegSigmSwapXformer(Transformer):
412
+ def call_function(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
413
+ if target == torch.sigmoid:
414
+ return torch.neg(*args, **kwargs)
415
+ return super().call_function(n)
416
+
417
+ def call_method(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
418
+ if target == 'neg':
419
+ call_self, *args_tail = args
420
+ return call_self.sigmoid(*args_tail, **kwargs)
421
+ return super().call_method(n)
422
+
423
+ def fn(x):
424
+ return torch.sigmoid(x).neg()
425
+
426
+ gm = torch.fx.symbolic_trace(fn)
427
+
428
+ transformed : torch.nn.Module = NegSigmSwapXformer(gm).transform()
429
+ input = torch.randn(3, 4)
430
+ torch.testing.assert_close(transformed(input), torch.neg(input).sigmoid())
431
+
432
+ Args:
433
+ module (GraphModule): The ``Module`` to be transformed.
434
+ """
435
+
436
+ @compatibility(is_backward_compatible=True)
437
+ def __init__(self, module):
438
+ super().__init__(module)
439
+ self.new_graph = Graph()
440
+ self.new_graph.set_codegen(module.graph._codegen)
441
+
442
+ class TransformerTracer(Tracer):
443
+ def __init__(self, graph: Graph):
444
+ super().__init__()
445
+ self.graph = graph
446
+ self.tensor_attrs: Dict[torch.Tensor, str] = {} # type: ignore[assignment]
447
+
448
+ def is_leaf_module(self, _, __) -> bool:
449
+ return True
450
+
451
+ self.tracer = TransformerTracer(self.new_graph)
452
+ self.tracer.root = module
453
+
454
+ @compatibility(is_backward_compatible=True)
455
+ def placeholder(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Proxy:
456
+ """
457
+ Execute a ``placeholder`` node. In ``Transformer``, this is
458
+ overridden to insert a new ``placeholder`` into the output
459
+ graph.
460
+
461
+ Args:
462
+ target (Target): The call target for this node. See
463
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
464
+ details on semantics
465
+ args (Tuple): Tuple of positional args for this invocation
466
+ kwargs (Dict): Dict of keyword arguments for this invocation
467
+ """
468
+ assert isinstance(target, str)
469
+ default_value = next(iter(args)) if args else inspect.Signature.empty
470
+ return Proxy(self.new_graph.placeholder(target, default_value=default_value), self.tracer)
471
+
472
+ @compatibility(is_backward_compatible=True)
473
+ def get_attr(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Proxy:
474
+ """
475
+ Execute a ``get_attr`` node. In ``Transformer``, this is
476
+ overridden to insert a new ``get_attr`` node into the output
477
+ graph.
478
+
479
+ Args:
480
+ target (Target): The call target for this node. See
481
+ `Node <https://pytorch.org/docs/main/fx.html#torch.fx.Node>`__ for
482
+ details on semantics
483
+ args (Tuple): Tuple of positional args for this invocation
484
+ kwargs (Dict): Dict of keyword arguments for this invocation
485
+ """
486
+ assert isinstance(target, str)
487
+ return self.tracer.create_proxy("get_attr", target, args, kwargs)
488
+
489
+ @compatibility(is_backward_compatible=True)
490
+ def call_module(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
491
+ # Override so that the leaf module policy from `self.tracer` is respected.
492
+ assert isinstance(target, str)
493
+ submod = self.fetch_attr(target)
494
+ return self.tracer.call_module(submod, submod.forward, args, kwargs)
495
+
496
+ @compatibility(is_backward_compatible=True)
497
+ def call_function(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
498
+ # Override so that functions that were wrapped are still wrapped.
499
+ return self.tracer.create_proxy('call_function', target, args, kwargs)
500
+
501
+ @compatibility(is_backward_compatible=True)
502
+ def transform(self) -> GraphModule:
503
+ """
504
+ Transform ``self.module`` and return the transformed
505
+ ``GraphModule``.
506
+ """
507
+ with fx_traceback.preserve_node_meta():
508
+ result = super().run(enable_io_processing=False)
509
+ if result is not None:
510
+ def strip_proxy(a : Union[Argument, Proxy]) -> Any:
511
+ return a.node if isinstance(a, Proxy) else a
512
+ new_output_node = self.new_graph.output(map_aggregate(result, strip_proxy))
513
+ # also preserve the metadata from the old output node, if it exists
514
+ old_output_node = list(self.graph.nodes)[-1]
515
+ assert old_output_node.op == "output"
516
+ for k, v in old_output_node.meta.items():
517
+ new_output_node.meta[k] = v
518
+
519
+
520
+ return _make_graph_module(self.module, self.new_graph)
mplug_owl2/lib/python3.10/site-packages/torch/fx/node.py ADDED
@@ -0,0 +1,788 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nodes represent a definition of a value in our graph of operators.
2
+ from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set
3
+ from ._compatibility import compatibility
4
+ from .immutable_collections import immutable_dict, immutable_list
5
+ import torch
6
+ import builtins
7
+ import types
8
+ import inspect
9
+ import warnings
10
+ from torch.fx.operator_schemas import normalize_function, normalize_module, ArgsKwargsPair
11
+ from .._ops import ops as _ops
12
+ from torch._C import _NodeBase
13
+
14
+ if TYPE_CHECKING:
15
+ from .graph import Graph
16
+
17
+ __all__ = ['Node', 'map_arg', 'map_aggregate', "has_side_effect"]
18
+
19
+ BaseArgumentTypes = Union[str, int, float, bool, complex, torch.dtype,
20
+ torch.Tensor, torch.device, torch.memory_format, torch.layout, torch._ops.OpOverload,
21
+ torch.SymInt, torch.SymBool, torch.SymFloat]
22
+ base_types = BaseArgumentTypes.__args__ # type: ignore[attr-defined]
23
+
24
+ Target = Union[Callable[..., Any], str]
25
+
26
+ Argument = Optional[Union[
27
+ Tuple[Any, ...], # actually Argument, but mypy can't represent recursive types
28
+ List[Any], # actually Argument
29
+ Dict[str, Any], # actually Argument
30
+ slice, # Slice[Argument, Argument, Argument], but slice is not a templated type in typing
31
+ range,
32
+ 'Node',
33
+ BaseArgumentTypes
34
+ ]]
35
+
36
+ _legal_ops = dict.fromkeys(['placeholder', 'call_method', 'call_module', 'call_function', 'get_attr', 'output', 'root'])
37
+
38
+ _side_effectful_need_to_be_preserved_pre_dispatch: Set[Callable] = {
39
+ torch._C._set_grad_enabled,
40
+ torch.amp._enter_autocast,
41
+ torch.amp._exit_autocast,
42
+ }
43
+
44
+ # TODO: Either refactor this into 2 functions 1 dce for functional graphs and 1 dce for all graphs,
45
+ # or add logic to correctly mark all inplace ops as side effectful.
46
+ _side_effectful_functions: Set[Callable] = {
47
+ torch._assert,
48
+ torch._assert_async,
49
+ _ops.aten._assert_async.msg,
50
+ _ops.aten._assert_scalar.default,
51
+ _ops.aten.sym_constrain_range.default,
52
+ _ops.aten.sym_constrain_range_for_size.default,
53
+ _ops.profiler._record_function_enter,
54
+ _ops.profiler._record_function_enter_new,
55
+ _ops.profiler._record_function_exit,
56
+ _ops.inductor.accumulate_grad_.default,
57
+ } | _side_effectful_need_to_be_preserved_pre_dispatch
58
+ if hasattr(_ops.inductor, "resize_storage_bytes_"):
59
+ _side_effectful_functions.add(_ops.inductor.resize_storage_bytes_.default)
60
+
61
+
62
+ @compatibility(is_backward_compatible=False)
63
+ def has_side_effect(fn: Callable) -> Callable:
64
+ _side_effectful_functions.add(fn)
65
+ return fn
66
+
67
+
68
+ # this is fixed on master, WAR for 1.5
69
+ def _find_module_of_method(orig_method: Callable[..., Any]) -> str:
70
+ name = orig_method.__name__
71
+ module = orig_method.__module__
72
+ if module is not None:
73
+ return module
74
+ for guess in [torch, torch.nn.functional]:
75
+ if getattr(guess, name, None) is orig_method:
76
+ return guess.__name__
77
+ raise RuntimeError(f'cannot find module for {orig_method}')
78
+
79
+ # Borrowed from CPython typing module
80
+ # https://github.com/python/cpython/blob/f90dc36c15d7fee0efaf6d39e97be0bdf2683e93/Lib/typing.py#L156
81
+ def _type_repr(obj: object) -> str:
82
+ """Return the repr() of an object, special-casing types (internal helper).
83
+ If obj is a type, we return a shorter version than the default
84
+ type.__repr__, based on the module and qualified name, which is
85
+ typically enough to uniquely identify a type. For everything
86
+ else, we fall back on repr(obj).
87
+ """
88
+ if isinstance(obj, type):
89
+ if obj.__module__ == 'builtins':
90
+ return obj.__qualname__
91
+ return f'{obj.__module__}.{obj.__qualname__}'
92
+ if obj is ...:
93
+ return '...'
94
+ if isinstance(obj, types.FunctionType):
95
+ return obj.__name__
96
+ return repr(obj)
97
+
98
+ def _get_qualified_name(func: Callable[..., Any]) -> str:
99
+ # things like getattr just appear in builtins
100
+ if getattr(builtins, func.__name__, None) is func:
101
+ return func.__name__
102
+ # torch.Tensor.{fn}
103
+ if (isinstance(func, (types.MethodDescriptorType, types.WrapperDescriptorType))
104
+ and func is getattr(torch.Tensor, func.__name__, None)):
105
+ return f"torch.Tensor.{func.__name__}"
106
+ name = func.__name__
107
+ if name == "<lambda>":
108
+ # For lambdas, try to get their defining name in the module
109
+ try:
110
+ name = inspect.getsource(func).split("=")[0].strip()
111
+ except Exception as e:
112
+ raise RuntimeError("Unable to represent lambda") from e
113
+ module = _find_module_of_method(func)
114
+ module = module.replace('torch._ops', 'torch.ops') # WAR for bug in how torch.ops assigns module
115
+ # Fixup segment_reduce mismatch
116
+ if module == "torch" and name == "segment_reduce":
117
+ name = "_" + name
118
+ return f'{module}.{name}'
119
+
120
+ def _format_arg(arg: object, max_list_len: float = float('inf')) -> str:
121
+ if hasattr(arg, '_custom_fx_repr_fn'):
122
+ return arg._custom_fx_repr_fn()
123
+ elif isinstance(arg, list):
124
+ items = ', '.join(_format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len)
125
+ maybe_len = '' if len(arg) < max_list_len + 1 else f', ...[total_len={len(arg)}]'
126
+ return f'[{items}{maybe_len}]'
127
+ elif isinstance(arg, tuple):
128
+ items = ', '.join(_format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len)
129
+ maybe_len = '' if len(arg) < max_list_len + 1 else f', ...[total_len={len(arg)}]'
130
+ maybe_comma = ',' if len(arg) == 1 else ''
131
+ return f'({items}{maybe_comma}{maybe_len})'
132
+ elif isinstance(arg, dict):
133
+ items_str = ', '.join(f'{k}: {_format_arg(v)}' for k, v in arg.items())
134
+ return f'{{{items_str}}}'
135
+
136
+ if isinstance(arg, Node):
137
+ return '%' + str(arg)
138
+ else:
139
+ return str(arg)
140
+
141
+ @compatibility(is_backward_compatible=True)
142
+ class Node(_NodeBase):
143
+ """
144
+ ``Node`` is the data structure that represents individual operations within
145
+ a ``Graph``. For the most part, Nodes represent callsites to various entities,
146
+ such as operators, methods, and Modules (some exceptions include nodes that
147
+ specify function inputs and outputs). Each ``Node`` has a function specified
148
+ by its ``op`` property. The ``Node`` semantics for each value of ``op`` are as follows:
149
+
150
+ - ``placeholder`` represents a function input. The ``name`` attribute specifies the name this value will take on.
151
+ ``target`` is similarly the name of the argument. ``args`` holds either: 1) nothing, or 2) a single argument
152
+ denoting the default parameter of the function input. ``kwargs`` is don't-care. Placeholders correspond to
153
+ the function parameters (e.g. ``x``) in the graph printout.
154
+ - ``get_attr`` retrieves a parameter from the module hierarchy. ``name`` is similarly the name the result of the
155
+ fetch is assigned to. ``target`` is the fully-qualified name of the parameter's position in the module hierarchy.
156
+ ``args`` and ``kwargs`` are don't-care
157
+ - ``call_function`` applies a free function to some values. ``name`` is similarly the name of the value to assign
158
+ to. ``target`` is the function to be applied. ``args`` and ``kwargs`` represent the arguments to the function,
159
+ following the Python calling convention
160
+ - ``call_module`` applies a module in the module hierarchy's ``forward()`` method to given arguments. ``name`` is
161
+ as previous. ``target`` is the fully-qualified name of the module in the module hierarchy to call.
162
+ ``args`` and ``kwargs`` represent the arguments to invoke the module on, *excluding the self argument*.
163
+ - ``call_method`` calls a method on a value. ``name`` is as similar. ``target`` is the string name of the method
164
+ to apply to the ``self`` argument. ``args`` and ``kwargs`` represent the arguments to invoke the module on,
165
+ *including the self argument*
166
+ - ``output`` contains the output of the traced function in its ``args[0]`` attribute. This corresponds to the "return" statement
167
+ in the Graph printout.
168
+ """
169
+ _args: Tuple['Argument', ...]
170
+ _kwargs: Dict[str, 'Argument']
171
+
172
+ @compatibility(is_backward_compatible=True)
173
+ def __init__(self, graph: 'Graph', name: str, op: str, target: 'Target',
174
+ args: Tuple['Argument', ...], kwargs: Dict[str, 'Argument'],
175
+ return_type : Optional[Any] = None) -> None:
176
+ """
177
+ Instantiate an instance of ``Node``. Note: most often, you want to use the
178
+ Graph APIs, i.e. ``Graph.call_module``, ``Graph.call_method``, etc. rather
179
+ than instantiating a ``Node`` directly.
180
+
181
+ Args:
182
+ graph (Graph): The ``Graph`` to which this ``Node`` should belong.
183
+
184
+ name (str): The name to which the output of this ``Node`` should be assigned
185
+
186
+ op (str): The opcode for this ``Node``. Can be one of 'placeholder',
187
+ 'call_method', 'call_module', 'call_function', 'get_attr',
188
+ 'output'
189
+
190
+ target ('Target'): The target this op should call. See the broader
191
+ ``Node`` docstring for more details.
192
+
193
+ args (Tuple['Argument']): The args to be passed to ``target``
194
+
195
+ kwargs (Dict[str, 'Argument']): The kwargs to be passed to ``target``
196
+
197
+ return_type (Optional[Any]): The python type expression representing the
198
+ type of the output of this node. This field can be used for
199
+ annotation of values in the generated code or for other types
200
+ of analyses.
201
+ """
202
+ super().__init__()
203
+ self.graph = graph
204
+ self.name = name # unique name of value being created
205
+ assert op in _legal_ops
206
+ self.op = op # the kind of operation = placeholder|call_method|call_module|call_function|get_attr
207
+ if op == 'call_function':
208
+ if not callable(target):
209
+ raise ValueError(f'Node [graph = {graph}, name = \'{name}\'] target {target} has type {torch.typename(target)} '
210
+ 'but a Callable is expected')
211
+ else:
212
+ if not isinstance(target, str):
213
+ raise ValueError(f'Node [graph = {graph}, name = \'{name}\'] target {target} has type {torch.typename(target)} '
214
+ 'but a str is expected')
215
+ self.target = target # for method/module/function, the name of the method/module/function/attr
216
+ # being invoked, e.g add, layer1, or torch.add
217
+
218
+ # All `Node`-valued inputs. Key is the Node, value is don't-care.
219
+ # The public API for this is `all_input_nodes`, this private attribute
220
+ # should not be accessed directly.
221
+ self._input_nodes : Dict[Node, None] = {}
222
+ self.__update_args_kwargs(args, kwargs)
223
+
224
+ # All of the nodes that use the value produced by this Node
225
+ # Note one user may correspond to several uses, e.g. the node fo ``x + x``
226
+ # would appear once here, but represents two uses.
227
+ #
228
+ # Is a dict to act as an "ordered set". Keys are significant, value dont-care
229
+ self.users : Dict[Node, None] = {}
230
+ # Type expression representing the output value of this node.
231
+ # This should contain the same class of Type objects that would appear
232
+ # as type annotations for function inputs/outputs.
233
+ #
234
+ # For placeholder nodes, this value will be used to type-annotate the
235
+ # generated function parameters.
236
+ # For the return node, this value will be used to type-annotate the
237
+ # generated function return type. (Note this is a special case. ``return``
238
+ # does not produce a value, it's more of a notation. Thus, this value
239
+ # describes the type of args[0] in the ``return`` node.
240
+ self.type : Optional[Any] = return_type
241
+ self._sort_key: Any = ()
242
+
243
+ # If set, use this fn to print this node
244
+ self._repr_fn : Optional[Callable[[Node], str]] = None
245
+
246
+ # Dictionary to store metadata passes need to do their
247
+ # transformations. This metadata is preserved across node copies
248
+ self.meta : Dict[str, Any] = {}
249
+
250
+ def __getstate__(self) -> Dict[str, Any]:
251
+ state = self.__dict__.copy()
252
+ state["_erased"] = self._erased
253
+ state["_prev"] = self._prev
254
+ state["_next"] = self._next
255
+ return state
256
+
257
+ def __setstate__(self, state: Dict[str, Any]) -> None:
258
+ _erased = state.pop("_erased")
259
+ _prev = state.pop("_prev")
260
+ _next = state.pop("_next")
261
+ self.__dict__.update(state)
262
+ self._erased = _erased
263
+ self._prev = _prev
264
+ self._next = _next
265
+
266
+ @property
267
+ def next(self) -> 'Node':
268
+ """
269
+ Returns the next ``Node`` in the linked list of Nodes.
270
+
271
+ Returns:
272
+
273
+ The next ``Node`` in the linked list of Nodes.
274
+ """
275
+ return self._next
276
+
277
+ @property
278
+ def prev(self) -> 'Node':
279
+ """
280
+ Returns the previous ``Node`` in the linked list of Nodes.
281
+
282
+ Returns:
283
+
284
+ The previous ``Node`` in the linked list of Nodes.
285
+ """
286
+ return self._prev
287
+
288
+ @compatibility(is_backward_compatible=True)
289
+ def prepend(self, x: 'Node') -> None:
290
+ """
291
+ Insert x before this node in the list of nodes in the graph. Example::
292
+
293
+ Before: p -> self
294
+ bx -> x -> ax
295
+ After: p -> x -> self
296
+ bx -> ax
297
+
298
+ Args:
299
+ x (Node): The node to put before this node. Must be a member of the same graph.
300
+ """
301
+ assert self.graph == x.graph, "Attempting to move a Node into a different Graph"
302
+ if self == x:
303
+ warnings.warn("Trying to prepend a node to itself. This behavior has no effect on the graph.")
304
+ return
305
+ x._remove_from_list()
306
+ p = self._prev
307
+ p._next, x._prev = x, p
308
+ x._next, self._prev = self, x
309
+
310
+ # compute x._sort_key
311
+ psk = x._prev._sort_key
312
+ nsk = x._next._sort_key
313
+ if len(psk) > len(nsk):
314
+ idx: int
315
+ *prefix, idx = psk[:len(nsk) + 1]
316
+ x._sort_key = (*prefix, idx + 1)
317
+ elif len(psk) < len(nsk):
318
+ *prefix, idx = nsk[:len(psk) + 1]
319
+ x._sort_key = (*prefix, idx - 1)
320
+ else: # same length, increase length by 1
321
+ x._sort_key = (*psk, 0)
322
+
323
+ def __gt__(self, other: 'Node') -> bool:
324
+ return self._sort_key > other._sort_key
325
+
326
+ def __lt__(self, other: 'Node') -> bool:
327
+ return self._sort_key < other._sort_key
328
+
329
+ def __ge__(self, other: 'Node') -> bool:
330
+ return self > other or self == other
331
+
332
+ def __le__(self, other: 'Node') -> bool:
333
+ return self < other or self == other
334
+
335
+ @compatibility(is_backward_compatible=True)
336
+ def append(self, x: 'Node') -> None:
337
+ """
338
+ Insert ``x`` after this node in the list of nodes in the graph.
339
+ Equivalent to ``self.next.prepend(x)``
340
+
341
+ Args:
342
+ x (Node): The node to put after this node. Must be a member of the same graph.
343
+ """
344
+ self._next.prepend(x)
345
+
346
+ def _remove_from_list(self) -> None:
347
+ p, n = self._prev, self._next
348
+ p._next, n._prev = n, p
349
+
350
+ @property
351
+ def args(self) -> Tuple[Argument, ...]:
352
+ """
353
+ The tuple of arguments to this ``Node``. The interpretation of arguments
354
+ depends on the node's opcode. See the :class:`Node` docstring for more
355
+ information.
356
+
357
+ Assignment to this property is allowed. All accounting of uses and users
358
+ is updated automatically on assignment.
359
+ """
360
+ return self._args
361
+
362
+ @args.setter
363
+ def args(self, a : Tuple[Argument, ...]) -> None:
364
+ """
365
+ Set the tuple of arguments to this Node. The interpretation of arguments
366
+ depends on the node's opcode. See the ``fx.Graph`` docstring for more
367
+ information.
368
+ """
369
+ # DO NOT CALL `__update_args_kwargs` directly. The correct way to
370
+ # set `args` is via direct assignment, i.e. `node.args = new_args`
371
+ self.__update_args_kwargs(a, self._kwargs)
372
+
373
+ @property
374
+ def kwargs(self) -> Dict[str, Argument]:
375
+ """
376
+ The dict of keyword arguments to this ``Node``. The interpretation of arguments
377
+ depends on the node's opcode. See the :class:`Node` docstring for more
378
+ information.
379
+
380
+ Assignment to this property is allowed. All accounting of uses and users
381
+ is updated automatically on assignment.
382
+ """
383
+ return self._kwargs
384
+
385
+ @kwargs.setter
386
+ def kwargs(self, k : Dict[str, Argument]) -> None:
387
+ """
388
+ Set the dict of kwargs to this Node. The interpretation of arguments
389
+ depends on the node's opcode. See the ``fx.Graph`` docstring for more
390
+ information.
391
+ """
392
+ # DO NOT CALL `__update_args_kwargs` directly. The correct way to
393
+ # set `args` is via direct assignment, i.e. `node.kwargs = new_kwargs`
394
+ self.__update_args_kwargs(self._args, k)
395
+
396
+ @property
397
+ def all_input_nodes(self) -> List['Node']:
398
+ """
399
+ Return all Nodes that are inputs to this Node. This is equivalent to
400
+ iterating over ``args`` and ``kwargs`` and only collecting the values that
401
+ are Nodes.
402
+
403
+ Returns:
404
+
405
+ List of ``Nodes`` that appear in the ``args`` and ``kwargs`` of this
406
+ ``Node``, in that order.
407
+ """
408
+ return list(self._input_nodes.keys())
409
+
410
+ @compatibility(is_backward_compatible=True)
411
+ def update_arg(self, idx : int, arg : Argument) -> None:
412
+ """
413
+ Update an existing positional argument to contain the new value
414
+ ``arg``. After calling, ``self.args[idx] == arg``.
415
+
416
+ Args:
417
+
418
+ idx (int): The index into ``self.args`` of the element to update
419
+ arg (Argument): The new argument value to write into ``args``
420
+ """
421
+ args = list(self.args)
422
+ args[idx] = arg
423
+ self.args = tuple(args)
424
+
425
+ @compatibility(is_backward_compatible=True)
426
+ def insert_arg(self, idx : int, arg : Argument) -> None:
427
+ """
428
+ Insert an positional argument to the argument list with given index.
429
+
430
+ Args:
431
+
432
+ idx (int): The index of the element in ``self.args`` to be inserted before.
433
+ arg (Argument): The new argument value to insert into ``args``
434
+ """
435
+ assert 0 <= idx <= len(self.args), "insert_args index must be between 0 and len(self.args)"
436
+ args_left = self.args[:idx]
437
+ args_right = self.args[idx:]
438
+
439
+ self._args = args_left + (arg,) + args_right
440
+
441
+ _new_input_nodes: Dict[Node, None] = {}
442
+ map_arg(arg, _new_input_nodes.setdefault)
443
+
444
+ for new_use in _new_input_nodes.keys():
445
+ if new_use not in self._input_nodes:
446
+ self._input_nodes.setdefault(new_use)
447
+ new_use.users.setdefault(self)
448
+
449
+ @compatibility(is_backward_compatible=True)
450
+ def update_kwarg(self, key : str, arg : Argument) -> None:
451
+ """
452
+ Update an existing keyword argument to contain the new value
453
+ ``arg``. After calling, ``self.kwargs[key] == arg``.
454
+
455
+ Args:
456
+
457
+ key (str): The key in ``self.kwargs`` of the element to update
458
+ arg (Argument): The new argument value to write into ``kwargs``
459
+ """
460
+ self.kwargs = {**self.kwargs, key: arg}
461
+
462
+ @property
463
+ def stack_trace(self) -> Optional[str]:
464
+ """
465
+ Return the Python stack trace that was recorded during tracing, if any.
466
+ When traced with fx.Tracer, this property is usually populated by
467
+ `Tracer.create_proxy`. To record stack traces during tracing for debug purposes,
468
+ set `record_stack_traces = True` on the `Tracer` instance.
469
+ When traced with dynamo, this property will be populated by default by
470
+ `OutputGraph.create_proxy`.
471
+
472
+ stack_trace would have the innermost frame at the end of the string.
473
+ """
474
+ return self.meta.get("stack_trace", None)
475
+
476
+ @stack_trace.setter
477
+ def stack_trace(self, trace : Optional[str]) -> None:
478
+ self.meta["stack_trace"] = trace
479
+
480
+ def __update_args_kwargs(self, new_args : Tuple['Argument', ...], new_kwargs : Dict[str, 'Argument']) -> None:
481
+ """
482
+ This API is internal. Do *not* call it directly.
483
+ """
484
+ def update_users_and_input_nodes(n: Any) -> Any:
485
+ if isinstance(n, Node):
486
+ self._input_nodes.setdefault(n)
487
+ n.users.setdefault(self)
488
+ return n
489
+
490
+ # Clear prior users and input_nodes
491
+ for old_use in self._input_nodes.keys():
492
+ old_use.users.pop(self)
493
+ self._input_nodes = {}
494
+
495
+ # We do three things in a single pass of the args
496
+ # - Normalize list->immutable_list, dict->immutable_dict, etc
497
+ # - Populate self._input_nodes
498
+ # - Populate arg.users[self] for each arg
499
+ self._args = map_aggregate(new_args, update_users_and_input_nodes) # type: ignore[assignment]
500
+ self._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes) # type: ignore[assignment]
501
+
502
+ def __repr__(self) -> str:
503
+ if self._repr_fn:
504
+ return self._repr_fn(self)
505
+ return self.name
506
+
507
+ def _pretty_print_target(self, target: object) -> str:
508
+ """
509
+ Make target printouts more user-friendly.
510
+ 1) builtins will be printed as `builtins.xyz`
511
+ 2) operators will be printed as `operator.xyz`
512
+ 3) other callables will be printed with qualified name, e.g. torch.add
513
+ """
514
+ if isinstance(target, str):
515
+ return target
516
+ if hasattr(target, '__module__'):
517
+ name = getattr(target, '__name__', None)
518
+ if name is None:
519
+ # Just to be defensive, if we don't have `__name__`, get the
520
+ # qualname. Not sure if this happens for any members of `operator`
521
+ # or `builtins`. This fallback path is not as good, since e.g.
522
+ # things in `operator` have `_operator` as their __module__.
523
+ # TODO: THIS IS BROKEN: _get_qualified_name calls `__name__`
524
+ return _get_qualified_name(target) # type: ignore[arg-type]
525
+ if target.__module__ == 'builtins':
526
+ return f'builtins.{name}'
527
+ elif target.__module__ == '_operator':
528
+ return f'operator.{name}'
529
+ return _get_qualified_name(target) # type: ignore[arg-type]
530
+
531
+ @compatibility(is_backward_compatible=True)
532
+ def format_node(self,
533
+ placeholder_names: Optional[List[str]] = None,
534
+ maybe_return_typename: Optional[List[str]] = None) -> Optional[str]:
535
+ """
536
+ Return a descriptive string representation of ``self``.
537
+
538
+ This method can be used with no arguments as a debugging
539
+ utility.
540
+
541
+ This function is also used internally in the ``__str__`` method
542
+ of ``Graph``. Together, the strings in ``placeholder_names``
543
+ and ``maybe_return_typename`` make up the signature of the
544
+ autogenerated ``forward`` function in this Graph's surrounding
545
+ GraphModule. ``placeholder_names`` and ``maybe_return_typename``
546
+ should not be used otherwise.
547
+
548
+ Args:
549
+ placeholder_names: A list that will store formatted strings
550
+ representing the placeholders in the generated
551
+ ``forward`` function. Internal use only.
552
+ maybe_return_typename: A single-element list that will store
553
+ a formatted string representing the output of the
554
+ generated ``forward`` function. Internal use only.
555
+
556
+ Returns:
557
+ str: If 1) we're using ``format_node`` as an internal helper
558
+ in the ``__str__`` method of ``Graph``, and 2) ``self``
559
+ is a placeholder Node, return ``None``. Otherwise,
560
+ return a descriptive string representation of the
561
+ current Node.
562
+ """
563
+ if self.op == 'placeholder':
564
+ assert isinstance(self.target, str)
565
+ arg_str = self.target
566
+ arg_str += arg_str + f': {_type_repr(self.type)}' if self.type else ''
567
+ if placeholder_names:
568
+ placeholder_names.append(arg_str)
569
+ return None
570
+ maybe_typename = f'{_type_repr(self.type)} ' if self.type else ''
571
+ default_val = '(default=' + str(self.args[0]) + ')' if self.args else ''
572
+ return f'%{self.name} : {maybe_typename}[num_users={len(self.users)}] = {self.op}[target={self.target}]{default_val}'
573
+ elif self.op == 'get_attr':
574
+ maybe_typename = f'{_type_repr(self.type)} ' if self.type is not None else ''
575
+ return f'%{self.name} : {maybe_typename}[num_users={len(self.users)}] = ' \
576
+ f'{self.op}[target={self._pretty_print_target(self.target)}]'
577
+ elif self.op == 'output':
578
+ if self.type and maybe_return_typename:
579
+ maybe_return_typename[0] = f' -> {_type_repr(self.type)}'
580
+ return f'return {self.args[0]}'
581
+ else:
582
+ maybe_typename = f'{_type_repr(self.type)} ' if self.type is not None else ''
583
+ return f'%{self.name} : {maybe_typename}[num_users={len(self.users)}] = ' \
584
+ f'{self.op}[target={self._pretty_print_target(self.target)}](' \
585
+ f'args = {_format_arg(self.args)}, kwargs = {_format_arg(self.kwargs)})'
586
+
587
+ @compatibility(is_backward_compatible=True)
588
+ def replace_all_uses_with(self,
589
+ replace_with: 'Node',
590
+ delete_user_cb: Callable[['Node'], bool] = lambda user: True,
591
+ *,
592
+ propagate_meta: bool = False
593
+ ) -> List['Node']:
594
+ """
595
+ Replace all uses of ``self`` in the Graph with the Node ``replace_with``.
596
+
597
+ Args:
598
+
599
+ replace_with (Node): The node to replace all uses of ``self`` with.
600
+ delete_user_cb (Callable): Callback that is called to determine
601
+ whether a given user of the self node should be removed.
602
+ propagate_meta (bool): Whether or not to copy all properties
603
+ on the .meta field of the original node onto the replacement node.
604
+ For safety, this is only valid to do if the replacement node
605
+ doesn't already have an existing .meta field.
606
+
607
+ Returns:
608
+
609
+ The list of Nodes on which this change was made.
610
+ """
611
+ if propagate_meta:
612
+ assert len(replace_with.meta) == 0, \
613
+ 'Called node.replace_all_uses_with(replace_with, propagate_meta=True), ' \
614
+ 'but replace_with already has .meta keys'
615
+ for k, v in self.meta.items():
616
+ replace_with.meta[k] = v
617
+ to_process = list(self.users)
618
+ skipped = []
619
+ m = self.graph.owning_module
620
+ for use_node in to_process:
621
+ if not delete_user_cb(use_node):
622
+ skipped.append(use_node)
623
+ continue
624
+
625
+ def maybe_replace_node(n : Node) -> Node:
626
+ if n == self:
627
+ return replace_with
628
+ else:
629
+ return n
630
+
631
+ if getattr(m, "_replace_hook", None):
632
+ m._replace_hook(old=self, new=replace_with.name, user=use_node)
633
+
634
+ new_args = map_arg(use_node.args, maybe_replace_node)
635
+ new_kwargs = map_arg(use_node.kwargs, maybe_replace_node)
636
+ assert isinstance(new_args, tuple)
637
+ assert isinstance(new_kwargs, dict)
638
+ use_node.__update_args_kwargs(new_args, new_kwargs)
639
+
640
+ assert len(self.users) - len(skipped) == 0
641
+ return [n for n in to_process if n not in skipped]
642
+
643
+ @compatibility(is_backward_compatible=False)
644
+ def is_impure(self) -> bool:
645
+ """
646
+ Returns whether this op is impure, i.e. if its op is a placeholder or
647
+ output, or if a call_function or call_module which is impure.
648
+
649
+ Returns:
650
+
651
+ bool: If the op is impure or not.
652
+ """
653
+ if self.op in {"placeholder", "output"}:
654
+ return True
655
+
656
+ # Check if an impure function based on schema.
657
+ if self.op == "call_function":
658
+ schema = getattr(self.target, "_schema", None)
659
+ schema_mutable = schema is not None and schema.is_mutable
660
+ return schema_mutable or self.target in _side_effectful_functions
661
+
662
+ # Check if an impure module.
663
+ if self.op == "call_module":
664
+ assert (
665
+ self.graph.owning_module is not None
666
+ ), "self.graph.owning_module not set for purity check"
667
+ target_mod = self.graph.owning_module.get_submodule(self.target)
668
+ assert (
669
+ target_mod is not None
670
+ ), f"Did not find expected submodule target {self.target}"
671
+ return getattr(target_mod, "_is_impure", False)
672
+
673
+ return False
674
+
675
+ @compatibility(is_backward_compatible=False)
676
+ def normalized_arguments(
677
+ self, root : torch.nn.Module, arg_types : Optional[Tuple[Any]] = None,
678
+ kwarg_types : Optional[Dict[str, Any]] = None,
679
+ normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]:
680
+ """
681
+ Returns normalized arguments to Python targets. This means that
682
+ `args/kwargs` will be matched up to the module/functional's
683
+ signature and return exclusively kwargs in positional order
684
+ if `normalize_to_only_use_kwargs` is true.
685
+ Also populates default values. Does not support positional-only
686
+ parameters or varargs parameters.
687
+
688
+ Supports module calls.
689
+
690
+ May require `arg_types` and `kwarg_types` in order to disambiguate overloads.
691
+
692
+ Args:
693
+ root (torch.nn.Module): Module upon which to resolve module targets.
694
+ arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
695
+ kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
696
+ normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
697
+
698
+ Returns:
699
+
700
+ Returns NamedTuple ArgsKwargsPair, or `None` if not successful.
701
+ """
702
+ if self.op == 'call_function':
703
+ assert callable(self.target)
704
+ return normalize_function(self.target, self.args, self.kwargs, arg_types, kwarg_types) # type: ignore[arg-type]
705
+ elif self.op == 'call_module':
706
+ assert isinstance(self.target, str)
707
+ return normalize_module(root, self.target, self.args, self.kwargs) # type: ignore[arg-type]
708
+
709
+ return None
710
+
711
+ @compatibility(is_backward_compatible=True)
712
+ def replace_input_with(self, old_input: 'Node', new_input: 'Node') -> None:
713
+ """
714
+ Loop through input nodes of ``self``, and replace all instances of
715
+ ``old_input`` with ``new_input``.
716
+
717
+ Args:
718
+
719
+ old_input (Node): The old input node to be replaced.
720
+ new_input (Node): The new input node to replace ``old_input``.
721
+ """
722
+ def maybe_replace_node(n : Node) -> Node:
723
+ return new_input if n == old_input else n
724
+
725
+ m = self.graph.owning_module
726
+ if getattr(m, "_replace_hook", None):
727
+ m._replace_hook(old=old_input, new=new_input.name, user=self)
728
+
729
+ new_args = map_arg(self.args, maybe_replace_node)
730
+ new_kwargs = map_arg(self.kwargs, maybe_replace_node)
731
+ assert isinstance(new_args, tuple)
732
+ assert isinstance(new_kwargs, dict)
733
+ self.__update_args_kwargs(new_args, new_kwargs)
734
+
735
+ def _rename(self, candidate: str) -> None:
736
+ if candidate == self.name:
737
+ return
738
+ name = self.graph._graph_namespace.create_name(candidate, None)
739
+ self.name = name
740
+ self.graph._graph_namespace._rename_object(self, name)
741
+
742
+ def __setattr__(self, name: str, value: Any) -> None:
743
+ if name == 'name' and hasattr(self, "name"):
744
+ m = self.graph.owning_module
745
+ if getattr(m, "_replace_hook", None):
746
+ assert isinstance(value, str)
747
+ for user in self.users:
748
+ m._replace_hook(old=self, new=value, user=user)
749
+ update = False
750
+ if (
751
+ hasattr(self, name) and
752
+ hasattr(self.graph, "_find_nodes_lookup_table") and
753
+ self in self.graph._find_nodes_lookup_table
754
+ ):
755
+ update = True
756
+ self.graph._find_nodes_lookup_table.remove(self)
757
+ object.__setattr__(self, name, value)
758
+ if update:
759
+ self.graph._find_nodes_lookup_table.insert(self)
760
+
761
+ @compatibility(is_backward_compatible=True)
762
+ def map_arg(a: Argument, fn: Callable[[Node], Argument]) -> Argument:
763
+ """
764
+ Apply fn to each Node appearing arg. arg may be a list, tuple, slice, or dict with string keys.
765
+ """
766
+ assert callable(fn), "torch.fx.map_arg(a, fn): fn must be a callable"
767
+ return map_aggregate(a, lambda x: fn(x) if isinstance(x, Node) else x)
768
+
769
+ @compatibility(is_backward_compatible=True)
770
+ def map_aggregate(a: Argument, fn: Callable[[Argument], Argument]) -> Argument:
771
+ """
772
+ Apply fn to each Node appearing arg. arg may be a list, tuple, slice, or dict with string keys.
773
+ """
774
+ if isinstance(a, tuple):
775
+ t = tuple([map_aggregate(elem, fn) for elem in a])
776
+ # Support NamedTuple (if it has `_fields`) by repacking into original type.
777
+ return t if not hasattr(a, '_fields') else type(a)(*t) # type: ignore[arg-type]
778
+ elif isinstance(a, list):
779
+ return immutable_list([map_aggregate(elem, fn) for elem in a])
780
+ elif isinstance(a, dict):
781
+ rv = immutable_dict()
782
+ for k, v in a.items():
783
+ dict.__setitem__(rv, k, map_aggregate(v, fn))
784
+ return rv
785
+ elif isinstance(a, slice):
786
+ return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
787
+ else:
788
+ return fn(a)
mplug_owl2/lib/python3.10/site-packages/torch/fx/operator_schemas.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import inspect
4
+ import numbers
5
+ import types
6
+ import typing
7
+ import enum
8
+ import warnings
9
+ from typing import Any, Callable, Dict, List, Optional, Tuple, NamedTuple, cast, TYPE_CHECKING
10
+ from torch._jit_internal import boolean_dispatched
11
+ from ._compatibility import compatibility
12
+ from torch._ops import OpOverloadPacket, OpOverload
13
+
14
+ if TYPE_CHECKING:
15
+ from .node import Argument
16
+
17
+ __all__ = ["ArgsKwargsPair", "check_for_mutable_operation", "get_signature_for_torch_op", "create_type_hint",
18
+ "type_matches", "normalize_function", "normalize_module"]
19
+
20
+ @compatibility(is_backward_compatible=False)
21
+ class ArgsKwargsPair(NamedTuple):
22
+ """
23
+ Simple named tuple for wrapping args/kwargs pairs.
24
+ """
25
+ args: Tuple[Any, ...]
26
+ kwargs: Dict[str, Any]
27
+
28
+ _manual_overrides : Dict[Callable, List[inspect.Signature]] = {}
29
+
30
+ def _nonzero_schemas():
31
+ signatures = []
32
+
33
+ def nonzero(self):
34
+ pass
35
+ signatures.append(inspect.signature(nonzero))
36
+
37
+ def nonzero(self, *, as_tuple : bool): # type: ignore[no-redef]
38
+ pass
39
+ signatures.append(inspect.signature(nonzero))
40
+
41
+ return signatures
42
+
43
+ _manual_overrides[torch.nonzero] = _nonzero_schemas()
44
+
45
+ class _FakeGlobalNamespace:
46
+ def __getattr__(self, name):
47
+ if name == 'torch':
48
+ return torch
49
+ raise RuntimeError('Expected a torch namespace lookup')
50
+
51
+ _type_eval_globals = {'Tensor' : torch.Tensor, 'Device' : torch.device, 'Layout' : torch.layout,
52
+ 'number' : numbers.Number, 'Future' : torch.jit.Future,
53
+ 'AnyEnumType' : enum.Enum, 'QScheme' : torch.qscheme,
54
+ '__torch__': _FakeGlobalNamespace(), 'NoneType': type(None),
55
+ 'Storage': torch.UntypedStorage,
56
+ 't': typing.TypeVar('t')}
57
+ for k in dir(typing):
58
+ _type_eval_globals[k] = getattr(typing, k)
59
+
60
+ def _torchscript_type_to_python_type(ts_type : 'torch._C.JitType') -> Any:
61
+ """
62
+ Convert a TorchScript type to a Python type (including subtypes) via
63
+ eval'ing the annotation_str. _type_eval_globals sets up expressions
64
+ like "List" and "Future" to map to actual types (typing.List and jit.Future)
65
+ """
66
+ return eval(ts_type.annotation_str, _type_eval_globals)
67
+
68
+ def _torchscript_schema_to_signature_impl(ts_schema : torch._C.FunctionSchema) -> inspect.Signature:
69
+ from inspect import Parameter
70
+ parameters : List[Parameter] = []
71
+ for arg in ts_schema.arguments:
72
+ arg_type = _torchscript_type_to_python_type(arg.type)
73
+ default = arg.default_value if arg.has_default_value() else Parameter.empty
74
+ # TODO: Figure out if this is safe. It seems like when generating the type signatures for
75
+ # PythonArgParser, we emit signatures with `input` instead of `self` as the first tensor
76
+ # argument name. Downstream, if someone converts that positional argument to a keyword
77
+ # argument, the name mismatch will break things, so here we're going to normalize the
78
+ # name to "input"
79
+ name = arg.name if arg.name != 'self' else 'input'
80
+ kind = Parameter.KEYWORD_ONLY if arg.kwarg_only else Parameter.POSITIONAL_OR_KEYWORD
81
+ # "from" is a keyword therefore it must be a POSITIONAL_ONLY argument
82
+ if name == "from":
83
+ assert kind == Parameter.POSITIONAL_OR_KEYWORD
84
+ # ParameterKind type is internal implementation detail to inspec package
85
+ # which makes it hard to do type annotation
86
+ kind = Parameter.POSITIONAL_ONLY # type: ignore[assignment]
87
+ # This renders all previous arguments to positional only
88
+ for idx, p in enumerate(parameters):
89
+ assert p.kind == Parameter.POSITIONAL_OR_KEYWORD
90
+ parameters[idx] = Parameter(name=p.name, kind=Parameter.POSITIONAL_ONLY, default=p.default, annotation=p.annotation)
91
+ parameters.append(Parameter(name=name, kind=kind, default=default, annotation=arg_type))
92
+ return_types = [_torchscript_type_to_python_type(ret.type) for ret in ts_schema.returns]
93
+ if len(return_types) == 0:
94
+ return_type = None
95
+ elif len(return_types) == 1:
96
+ return_type = return_types[0]
97
+ else:
98
+ return_type = tuple(return_types)
99
+
100
+ return inspect.Signature(parameters, return_annotation=return_type)
101
+
102
+ _SCHEMA_TO_SIGNATURE_CACHE : Dict[Tuple[str, str], inspect.Signature] = {}
103
+
104
+ def _torchscript_schema_to_signature(ts_schema : torch._C.FunctionSchema) -> inspect.Signature:
105
+ # Cached as it's called in the hot path of FakeTensor dispatch
106
+ cache_key = ts_schema.name, ts_schema.overload_name
107
+ cache_val = _SCHEMA_TO_SIGNATURE_CACHE.get(cache_key)
108
+ if cache_val is not None:
109
+ return cache_val
110
+
111
+ res = _torchscript_schema_to_signature_impl(ts_schema)
112
+ _SCHEMA_TO_SIGNATURE_CACHE[cache_key] = res
113
+ return res
114
+
115
+ @compatibility(is_backward_compatible=False)
116
+ def check_for_mutable_operation(target : Callable, args : Tuple['Argument', ...], kwargs : Dict[str, 'Argument']):
117
+ signatures, schemas = get_signature_for_torch_op(target, return_schemas=True)
118
+
119
+ if signatures and schemas:
120
+ matched_schemas = []
121
+
122
+ # Iterate through all of the schema until we find one that matches
123
+ # If one matches, populate `new_args_and_kwargs` with the new args/kwargs
124
+ # values. If none matches, `new_args_and_kwargs` will be None
125
+ for candidate_signature, schema in zip(signatures, schemas):
126
+ try:
127
+ candidate_signature.bind(*args, **kwargs)
128
+ matched_schemas.append((candidate_signature, schema))
129
+ except TypeError as e:
130
+ continue
131
+
132
+ def throw_if_mutable(schema):
133
+ if schema.is_mutable:
134
+ raise RuntimeError(f'Tried to trace mutable operation {schema}. FX only supports functional '
135
+ f'code, so operations that mutate operands in-place (e.g. via `out` arguments) '
136
+ f'are not supported')
137
+
138
+ if len(matched_schemas) == 0:
139
+ # Did not match any schema. Cannot check for mutation
140
+ pass
141
+ elif len(matched_schemas) == 1:
142
+ # Matched exactly one schema, unambiguous
143
+ _, schema_to_check = matched_schemas[0]
144
+ throw_if_mutable(schema_to_check)
145
+ else:
146
+ # Ambiguous schema match. Since mutability checking is best effort,
147
+ # do nothing.
148
+ pass
149
+
150
+ @compatibility(is_backward_compatible=False)
151
+ def get_signature_for_torch_op(op : Callable, return_schemas : bool = False):
152
+ """
153
+ Given an operator on the `torch` namespace, return a list of `inspect.Signature`
154
+ objects corresponding to the overloads of that op.. May return `None` if a signature
155
+ could not be retrieved.
156
+
157
+ Args:
158
+ op (Callable): An operator on the `torch` namespace to look up a signature for
159
+
160
+ Returns:
161
+ Optional[List[inspect.Signature]]: A list of signatures for the overloads of this
162
+ operator, or None if the operator signatures could not be retrieved. If
163
+ return_schemas=True, returns a tuple containing the optional Python signatures
164
+ and the optional TorchScript Function signature
165
+ """
166
+ if isinstance(op, OpOverload):
167
+ schemas = [op._schema]
168
+ elif isinstance(op, OpOverloadPacket):
169
+ schemas = [getattr(op, overload)._schema for overload in op.overloads()]
170
+ else:
171
+ override = _manual_overrides.get(op)
172
+ if override:
173
+ return (override, None) if return_schemas else None
174
+
175
+ aten_fn = torch.jit._builtins._find_builtin(op)
176
+
177
+ if aten_fn is None:
178
+ return (None, None) if return_schemas else None
179
+ schemas = torch._C._jit_get_schemas_for_operator(aten_fn)
180
+
181
+ signatures = [_torchscript_schema_to_signature(schema) for schema in schemas]
182
+ return (signatures, schemas) if return_schemas else signatures
183
+
184
+ @compatibility(is_backward_compatible=False)
185
+ def create_type_hint(x):
186
+ """
187
+ Produces a type hint for the given argument.
188
+
189
+ The :func:`create_type_hint` looks for a type hint compatible with the input argument `x`.
190
+
191
+ If `x` is a `list` or `tuple`, it looks for an object in the list whose type is a superclass
192
+ of the rest, and uses that as `base_type` for the `List` or `Tuple` to be returned.
193
+ If no such object is found, it defaults to `List[Any]`.
194
+
195
+ If `x` is neither a `list` nor a `tuple`, it returns `x`.
196
+ """
197
+ try:
198
+ if isinstance(x, (list, tuple)):
199
+ # todo(chilli): Figure out the right way for mypy to handle this
200
+ if isinstance(x, list):
201
+ def ret_type(x):
202
+ return List[x] # type: ignore[valid-type]
203
+ else:
204
+ def ret_type(x):
205
+ return Tuple[x, ...]
206
+ if len(x) == 0:
207
+ return ret_type(Any)
208
+ base_type = x[0]
209
+ for t in x:
210
+ if issubclass(t, base_type):
211
+ continue
212
+ elif issubclass(base_type, t):
213
+ base_type = t
214
+ else:
215
+ return ret_type(Any)
216
+ return ret_type(base_type)
217
+ except Exception as e:
218
+ # We tried to create a type hint for list but failed.
219
+ warnings.warn(f"We were not able to successfully create type hint from the type {x}")
220
+ return x
221
+
222
+ @compatibility(is_backward_compatible=False)
223
+ def type_matches(signature_type : Any, argument_type : Any):
224
+ sig_origin_type = getattr(signature_type, '__origin__', signature_type)
225
+
226
+ if signature_type is argument_type:
227
+ return True
228
+
229
+ # Union types in signature. Given type needs to match one of the
230
+ # contained types in the Union
231
+ if sig_origin_type is typing.Union and signature_type != argument_type:
232
+ sig_contained = signature_type.__args__
233
+ return any(type_matches(c, argument_type) for c in sig_contained)
234
+
235
+ if signature_type is List[int] and argument_type is int:
236
+ # int can be promoted to List[int]
237
+ return True
238
+
239
+ if getattr(signature_type, '__origin__', None) in {list, List}:
240
+ sig_el_type = signature_type.__args__[0]
241
+ if not inspect.isclass(sig_el_type):
242
+ warnings.warn(
243
+ f"Does not support nested parametric types, got {signature_type}. Please file a bug.")
244
+ return False
245
+ if getattr(argument_type, '__origin__', None) in {list, List}:
246
+ return issubclass(argument_type.__args__[0], sig_el_type)
247
+
248
+ def is_homogeneous_tuple(t):
249
+ if getattr(t, "__origin__", None) not in {tuple, Tuple}:
250
+ return False
251
+ contained = t.__args__
252
+ if t.__args__ == ((),): # Tuple[()].__args__ == ((),) for some reason
253
+ return True
254
+ return all((c is Ellipsis) or issubclass(c, sig_el_type) for c in contained)
255
+
256
+ # Tuple[T] is accepted for List[T] parameters
257
+ return is_homogeneous_tuple(argument_type)
258
+
259
+ # Dtype is an int in schemas
260
+ if signature_type is int and argument_type is torch.dtype:
261
+ return True
262
+
263
+ if signature_type is numbers.Number and argument_type in {int, float}:
264
+ return True
265
+ if inspect.isclass(argument_type) and inspect.isclass(signature_type):
266
+ return issubclass(argument_type, signature_type)
267
+
268
+ return False
269
+
270
+ @compatibility(is_backward_compatible=False)
271
+ def normalize_function(
272
+ target: Callable, args: Tuple[Any], kwargs : Optional[Dict[str, Any]] = None, arg_types : Optional[Tuple[Any]] = None,
273
+ kwarg_types : Optional[Dict[str, Any]] = None,
274
+ normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]:
275
+ """
276
+ Returns normalized arguments to PyTorch functions. This means that
277
+ `args/kwargs` will be matched up to the functional's
278
+ signature and return exclusively kwargs in positional order if
279
+ `normalize_to_only_use_kwargs` is True.
280
+ Also populates default values. Does not support positional-only
281
+ parameters or varargs parameters (*args, **kwargs). Does not support modules.
282
+
283
+ May require `arg_types` and `kwarg_types` in order to disambiguate overloads.
284
+
285
+ Args:
286
+ target (Callable): Function that we are normalizing
287
+ args (Tuple[Any]): Tuple of args to the function
288
+ kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function
289
+ arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
290
+ kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
291
+ normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
292
+
293
+ Returns:
294
+
295
+ Returns normalized_args_and_kwargs, or `None` if not successful.
296
+ """
297
+ if kwargs is None:
298
+ kwargs = {}
299
+ new_args_and_kwargs = None
300
+ if not isinstance(target, types.BuiltinFunctionType) and not (
301
+ isinstance(target, (OpOverloadPacket, OpOverload))
302
+ ):
303
+ target_for_analysis = target
304
+ if target in boolean_dispatched:
305
+ # HACK: `boolean_dispatch` as used in `torch.nn.functional` makes it so that we have
306
+ # a 2-way dispatch based on a boolean value. Here we check that the `true` and `false`
307
+ # branches of the dispatch have exactly the same signature. If they do, use the `true`
308
+ # branch signature for analysis. Otherwise, leave this un-normalized
309
+ assert not isinstance(target, str)
310
+ dispatched = boolean_dispatched[target]
311
+ if_true, if_false = dispatched['if_true'], dispatched['if_false']
312
+ if inspect.signature(if_true).parameters != inspect.signature(if_false).parameters:
313
+ return None
314
+ target_for_analysis = if_true
315
+
316
+ assert callable(target_for_analysis)
317
+ sig = inspect.signature(inspect.unwrap(target_for_analysis))
318
+ new_args_and_kwargs = _args_kwargs_to_normalized_args_kwargs(sig, args, kwargs, normalize_to_only_use_kwargs)
319
+ else:
320
+ assert callable(target)
321
+ torch_op_schemas = get_signature_for_torch_op(target)
322
+ matched_schemas = []
323
+ if torch_op_schemas:
324
+ # Iterate through all of the schema until we find one that matches
325
+ # If one matches, populate `new_args_and_kwargs` with the new args/kwargs
326
+ # values. If none matches, `new_args_and_kwargs` will be None
327
+ for candidate_signature in torch_op_schemas:
328
+ try:
329
+ candidate_signature.bind(*args, **kwargs)
330
+ matched_schemas.append(candidate_signature)
331
+ except TypeError as e:
332
+ continue
333
+
334
+ if len(matched_schemas) == 0:
335
+ # Did not match any schema. Cannot normalize
336
+ pass
337
+ elif len(matched_schemas) == 1:
338
+ # Matched exactly one schema, unambiguous
339
+ new_args_and_kwargs = _args_kwargs_to_normalized_args_kwargs(matched_schemas[0], args, kwargs,
340
+ normalize_to_only_use_kwargs)
341
+ else:
342
+ if arg_types is not None or kwarg_types is not None:
343
+ arg_types = arg_types if arg_types else cast(Tuple[Any], ())
344
+ kwarg_types = kwarg_types if kwarg_types else {}
345
+ for candidate_signature in torch_op_schemas:
346
+ sig_matches = True
347
+ try:
348
+ bound_types = candidate_signature.bind(*arg_types, **kwarg_types)
349
+ for arg_name, arg_type in bound_types.arguments.items():
350
+ param = candidate_signature.parameters[arg_name]
351
+ sig_matches = sig_matches and type_matches(param.annotation, arg_type)
352
+ except TypeError as e:
353
+ sig_matches = False
354
+ if sig_matches:
355
+ new_args_and_kwargs = _args_kwargs_to_normalized_args_kwargs(candidate_signature, args, kwargs,
356
+ normalize_to_only_use_kwargs)
357
+ break
358
+ else:
359
+ # Matched more than one schema. In this situation, the caller must provide the types of
360
+ # the arguments of the overload they expect.
361
+ schema_printouts = '\n'.join(str(schema) for schema in matched_schemas)
362
+ raise RuntimeError(f'Tried to normalize arguments to {torch.typename(target)} but '
363
+ f'the schema match was ambiguous! Please provide argument types to '
364
+ f'the normalize_arguments() call. Available schemas:\n{schema_printouts}')
365
+
366
+ return new_args_and_kwargs
367
+
368
+ @compatibility(is_backward_compatible=False)
369
+ def normalize_module(
370
+ root: torch.nn.Module, target: str, args: Tuple[Any], kwargs : Optional[Dict[str, Any]] = None,
371
+ normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]:
372
+ """
373
+ Returns normalized arguments to PyTorch modules. This means that
374
+ `args/kwargs` will be matched up to the functional's
375
+ signature and return exclusively kwargs in positional order if
376
+ `normalize_to_only_use_kwargs` is True.
377
+ Also populates default values. Does not support positional-only
378
+ parameters or varargs parameters (*args, **kwargs).
379
+
380
+ Args:
381
+ root (nn.Module): root module upon which we query modules
382
+ target (Callable): Function that we are normalizing
383
+ args (Tuple[Any]): Tuple of args to the function
384
+ kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function
385
+ normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
386
+
387
+ Returns:
388
+
389
+ Returns normalized_args_and_kwargs, or `None` if not successful.
390
+ """
391
+ try:
392
+ submod = root.get_submodule(target)
393
+ except AttributeError as e:
394
+ raise RuntimeError(f"Tried to normalize node with target {target} but root did not "
395
+ f"have that target!") from e
396
+ if hasattr(submod.__class__, '__name__'):
397
+ classname = submod.__class__.__name__
398
+ if getattr(torch.nn, classname, None) == submod.__class__:
399
+ sig = inspect.signature(inspect.unwrap(submod.forward))
400
+ if kwargs is None:
401
+ kwargs = {}
402
+ new_args_and_kwargs = _args_kwargs_to_normalized_args_kwargs(sig, args, kwargs,
403
+ normalize_to_only_use_kwargs)
404
+ return new_args_and_kwargs
405
+ return None
406
+
407
+ def _args_kwargs_to_normalized_args_kwargs(sig : inspect.Signature, args : Tuple[Any, ...],
408
+ kwargs : Dict[str, Any],
409
+ normalize_to_only_use_kwargs : bool) -> Optional[ArgsKwargsPair]:
410
+ """
411
+ Given a call target, args, and kwargs, return the arguments normalized into
412
+ an ArgsKwargsPair, or None if the type signature is not supported by
413
+ this normalization.
414
+
415
+ Args:
416
+
417
+ sig (inspect.Signature): Signature object for the target
418
+ args (Tuple): Arguments that appear at the callsite for `target`
419
+ kwargs (Dict): Keyword arguments that appear at the callsite for `target`
420
+ normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
421
+
422
+ Returns:
423
+
424
+ Optional[ArgsKwargsPair]: Normalized args and kwargs for `target`, or `None` if
425
+ this target is not supported.
426
+ """
427
+
428
+ # Don't currently support positional-only
429
+ # or varargs (*args, **kwargs) signatures
430
+ supported_parameter_types = {
431
+ inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}
432
+ if any(p.kind not in supported_parameter_types for p in sig.parameters.values()):
433
+ # Add an exception for one signature, which is common for random/uniform, i.e.:
434
+ # Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None
435
+ # `from` is Python keyword and as such functions with that signature should have
436
+ # positional-only args, but at the same time they could be dispatched as kwargs
437
+ if list(sig.parameters.keys()) != ['input', 'from', 'to', 'generator']:
438
+ return None
439
+
440
+ bound_args = sig.bind(*args, **kwargs)
441
+ bound_args.apply_defaults()
442
+
443
+ new_kwargs : Dict[str, Any] = {}
444
+ new_args : List[Any] = []
445
+ for i, param in enumerate(sig.parameters):
446
+ if not normalize_to_only_use_kwargs and i < len(args):
447
+ new_args.append(bound_args.arguments[param])
448
+ else:
449
+ new_kwargs[param] = bound_args.arguments[param]
450
+
451
+ return ArgsKwargsPair(tuple(new_args), new_kwargs)
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import graph_drawer
2
+ from . import graph_manipulation
3
+ from . import net_min_base
4
+ from . import operator_support
5
+ from . import param_fetch
6
+ from . import reinplace
7
+ from . import runtime_assert
8
+ from . import shape_prop
9
+ from . import split_module
10
+ from . import split_utils
11
+ from . import splitter_base
12
+ from . import tools_common
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/annotate_getitem_nodes.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import torch
4
+
5
+
6
+ def annotate_getitem_nodes(graph: torch.fx.Graph) -> None:
7
+ """
8
+ Annotate the type of getitem nodes, inferred from the type of sequence node.
9
+ If sequence node is not annotated with a type, do nothing.
10
+ Currently support getitem nodes from Tuple, List, and NamedTuple sequence node.
11
+
12
+ This is helpful since annotations on local names within function are lost during FX transforms.
13
+ Adding back known type annotation for getitem nodes to improve jit scriptability.
14
+
15
+ Args:
16
+ graph (Graph): The graph to be annotated
17
+ """
18
+ for node in graph.nodes:
19
+ if node.target == operator.getitem:
20
+ sequence_node, index_node = node.args
21
+ if not sequence_node.type:
22
+ continue
23
+ # container types
24
+ if hasattr(sequence_node.type, "_name"):
25
+ parameterized_types = sequence_node.type.__args__
26
+ if sequence_node.type._name == "Tuple":
27
+ if len(parameterized_types) == 2 and isinstance(
28
+ parameterized_types[1], type(...)
29
+ ):
30
+ node.type = parameterized_types[0]
31
+ else:
32
+ assert len(parameterized_types) > index_node
33
+ node_type = parameterized_types[index_node]
34
+ node.type = node_type
35
+ elif sequence_node.type._name == "List":
36
+ assert len(parameterized_types) == 1
37
+ node.type = parameterized_types[0]
38
+ # NamedTuple type
39
+ elif hasattr(sequence_node.type, "__annotations__"):
40
+ if sequence_node.type == torch.Tensor:
41
+ continue
42
+ sequence_node_field_types = sequence_node.type.__annotations__
43
+ field_name = sequence_node.type._fields[index_node]
44
+ node.type = sequence_node_field_types[field_name]
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__init__.py ADDED
File without changes
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/__pycache__/cudagraphs.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/backends/cudagraphs.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch.fx.passes.infra.partitioner import CapabilityBasedPartitioner
4
+ from torch.fx.passes.operator_support import OperatorSupport
5
+ from torch.fx.passes.tools_common import CALLABLE_NODE_OPS
6
+ from torch.fx.passes.fake_tensor_prop import FakeTensorProp
7
+ from torch.utils import _pytree as pytree
8
+
9
+ import operator
10
+
11
+ class CudaGraphsSupport(OperatorSupport):
12
+ # TODO: why is submodules passed here
13
+ def is_node_supported(self, submodules, node: torch.fx.Node) -> bool:
14
+ if node.op not in CALLABLE_NODE_OPS:
15
+ return False
16
+
17
+ if node.target in [torch.ops.aten.embedding_dense_backward.default]:
18
+ return False
19
+
20
+ if node.target in [operator.getitem]:
21
+ return True
22
+
23
+ found_not_cuda = False
24
+
25
+ def meta_fk(meta):
26
+ return meta["val"] if "val" in meta else meta["fake_result"]
27
+
28
+ def find_not_cuda(t):
29
+ nonlocal found_not_cuda
30
+ if isinstance(t, torch.Tensor) and t.device.type != 'cuda':
31
+ found_not_cuda = True
32
+
33
+ for n in node.all_input_nodes:
34
+ pytree.tree_map_(find_not_cuda, meta_fk(n.meta))
35
+
36
+ pytree.tree_map_(find_not_cuda, meta_fk(node.meta))
37
+
38
+ # NB: factory function is accounted for because the result would be
39
+ # cpu or cuda
40
+
41
+ return not found_not_cuda
42
+
43
+ def partition_cudagraphs(gm, inputs):
44
+ """
45
+ Partition an FX graph into sub-GraphModules that can be validly run under
46
+ CUDA graphs. For a subgraph to be runnable under CUDA, all of the operations
47
+ must involve CUDA tensors only/
48
+ """
49
+
50
+ FakeTensorProp(gm).propagate(*inputs)
51
+ supported_ops = CudaGraphsSupport()
52
+ # TODO: single node partition may be wrong due to the pessimization
53
+ # from copying in and out the data. Check in benchmarks, perhaps
54
+ partitioner = CapabilityBasedPartitioner(gm, supported_ops, allows_single_node_partition=True)
55
+ partitions = partitioner.propose_partitions()
56
+ fused_graph = partitioner.fuse_partitions(partitions)
57
+ return fused_graph
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/__init__.py ADDED
File without changes
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__init__.py ADDED
File without changes
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/__pycache__/cse_pass.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/dialect/common/cse_pass.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Dict, Tuple, Any
3
+
4
+ import torch
5
+ from torch.fx.passes.infra.pass_base import PassBase, PassResult
6
+ from torch.utils._pytree import tree_flatten
7
+
8
+ from torch.fx import GraphModule, Graph
9
+ from torch.fx import Node
10
+
11
+ aten = torch.ops.aten
12
+
13
+
14
+ # stateful ops are banned from CSE
15
+ rand_ops = {aten.dropout, aten._fused_dropout, aten._standard_gamma, aten.bernoulli, aten.multinomial, aten.native_dropout, aten.normal, aten.poisson, aten.binomial, aten.rrelu, aten.rand_like, aten.rand, aten.randint, aten.randn, aten.randperm} # noqa: E501,B950
16
+
17
+ inplace_ops = {aten.add_, aten.sub_, aten.mul_, aten.div_, aten.pow_, aten.lerp_, aten.relu_, aten.sigmoid_, aten.tanh_} # noqa: E501
18
+
19
+
20
+ @torch.fx._compatibility.compatibility(is_backward_compatible=False)
21
+ def get_CSE_banned_ops():
22
+ return rand_ops.union(inplace_ops)
23
+
24
+
25
+ @torch.fx._compatibility.compatibility(is_backward_compatible=False)
26
+ class CSEPass(PassBase):
27
+
28
+ def __init__(self, banned_ops=None):
29
+ """
30
+ This version of CSE Pass aims to be dialect agnostic, and it's implemented purely based on the connectivity between fx.Node.
31
+
32
+ For functional dialects, user would only need to specify the random ops in ban list.
33
+
34
+ Warning: CSE Pass cannot be safely applied on a FX graph in non-functional dialects.
35
+ If your dialect contains stateful operators, please customized the banned_ops.
36
+
37
+ """
38
+ if banned_ops is None:
39
+ banned_ops = set()
40
+ self.banned_ops = banned_ops
41
+ super().__init__()
42
+
43
+ def call(self, graph_module: GraphModule) -> PassResult:
44
+ """
45
+ Return a new copy of torch.fx.GraphModule with CSE applied to the input graph
46
+
47
+ Example usage:
48
+
49
+ from torch.fx.experimental.proxy_tensor import make_fx
50
+ def f(a):
51
+ b = a * a
52
+ c = a * a
53
+ return b+c
54
+
55
+ p = CSEPass()
56
+ traced_graph = make_fx(f)(torch.tensor(1))
57
+ print(traced_graph)
58
+ result = p(traced_graph)
59
+ print(result.graph_module)
60
+ """
61
+ def get_aten_target(node):
62
+ if hasattr(node.target, 'overloadpacket'):
63
+ return node.target.overloadpacket
64
+ return node.target
65
+
66
+ modified = False
67
+ new_graph = Graph()
68
+ env: Dict[Node, Node] = {} # map from node in the old graph to node in the new graph
69
+ hash_env: Dict[Tuple[torch._ops.OpOverload, int], Node] = {} # map from hash to a node in the new graph
70
+ token_map: Dict[Tuple[torch._ops.OpOverload, int], Dict[str, Any]] = {} # map from hash to token
71
+ for n in graph_module.graph.nodes:
72
+ # The placeholder, output, and get_attr nodes are copied to the new graph without change
73
+ # do not CSE away random operations
74
+ if n.op == 'placeholder' or n.op == 'output' or n.op == 'get_attr' or get_aten_target(n) in self.banned_ops:
75
+ new_node = new_graph.node_copy(n, lambda x: env[x])
76
+ env[n] = new_node
77
+ else: # n.op == 'call_function', should never see n.op == 'call_module' or 'call_method'
78
+ # substitute args and kwargs members to their mapping in env if exists
79
+ # specs can be used to reconstruct nested list/dictionaries
80
+ def substitute(arg_list):
81
+ arg_list, spec = tree_flatten(arg_list)
82
+ for i in range(len(arg_list)):
83
+ v = arg_list[i]
84
+ if isinstance(v, Node) and v in env:
85
+ arg_list[i] = env[v]
86
+ return tuple(arg_list), spec
87
+ args, args_spec = substitute(n.args)
88
+ kwargs, kwargs_spec = substitute(n.kwargs)
89
+
90
+ # each token corresponds to a unique node
91
+ # nodes with the same token can be substituted
92
+ token = {"target": n.target, "args": args, "args_spec": args_spec,
93
+ "kwargs": kwargs, "kwargs_spec": kwargs_spec}
94
+
95
+ # hash substituted args to a number, do not hash specs because specs are not hashable
96
+ hash_arg = hash((args, kwargs))
97
+ hash_val = (n.target, hash_arg)
98
+
99
+ # check if a node has a substitute and can be eliminated
100
+ hash_val_in_hash_env = hash_val in hash_env
101
+ if hash_val_in_hash_env and token_map[hash_val] == token:
102
+ modified = True # substitution happens and the graph is modified
103
+ env[n] = hash_env[hash_val]
104
+ continue
105
+
106
+ new_node = new_graph.node_copy(n, lambda x: env[x])
107
+ env[n] = new_node
108
+ if not hash_val_in_hash_env:
109
+ hash_env[hash_val] = new_node
110
+ token_map[hash_val] = token
111
+
112
+ csed_gm = GraphModule(graph_module, new_graph)
113
+ return PassResult(csed_gm, modified)
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/fake_tensor_prop.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch.fx
5
+ from torch.fx import Node
6
+ from torch.fx.node import map_aggregate
7
+ from torch.fx._compatibility import compatibility
8
+ from torch._subclasses.fake_tensor import FakeTensorMode, FakeTensor
9
+ from torch.fx.experimental.proxy_tensor import snapshot_fake, py_sym_types
10
+
11
+ __all__ = ['FakeTensorProp']
12
+
13
+ @compatibility(is_backward_compatible=False)
14
+ class FakeTensorProp(torch.fx.Interpreter):
15
+ """
16
+ Execute an FX graph Node-by-Node and record a fake tensor representing
17
+ the metadata for the node. Unlike ShapeProp, (1) this propagation
18
+ is cheap--it does the propagation with meta tensors which do not actually
19
+ store data, and (2) the fake tensors have much more fine grained information,
20
+ e.g., they have accurate alias information that can be consulted by looking
21
+ at the storages.
22
+
23
+ Args:
24
+ module (GraphModule): The module to be executed
25
+ mode (Optional[FakeTensorMode]): The dispatch mode used to execute computation indicated by each FX Node.
26
+ """
27
+ def __init__(self, module: torch.fx.GraphModule, mode: Optional[FakeTensorMode] = None):
28
+ super().__init__(module)
29
+ if mode is None:
30
+ mode = FakeTensorMode()
31
+ self._mode = mode
32
+ mode.epoch += 1
33
+ mode.reset_nt_tensor_id_counter()
34
+
35
+ def run_node(self, n: Node):
36
+ from torch.fx.experimental.symbolic_shapes import rebind_unbacked, compute_unbacked_bindings
37
+
38
+ result = super().run_node(n)
39
+ rebind_unbacked(self._mode.shape_env, n, result)
40
+
41
+ def extract_val(obj):
42
+ if isinstance(obj, FakeTensor):
43
+ return snapshot_fake(obj)
44
+ elif isinstance(obj, torch.Tensor):
45
+ # TODO: How is it possible that we get a non fake tensor? We
46
+ # should be running under the mode...
47
+ return snapshot_fake(self._mode.from_tensor(obj, static_shapes=True))
48
+ elif isinstance(obj, py_sym_types):
49
+ return obj
50
+ else:
51
+ return None
52
+
53
+ meta = map_aggregate(result, extract_val)
54
+ if meta is not None:
55
+ n.meta['val'] = meta
56
+ if (shape_env := self._mode.shape_env) and (symbol_to_path := compute_unbacked_bindings(shape_env, result)):
57
+ n.meta["unbacked_bindings"] = symbol_to_path
58
+
59
+ return result
60
+
61
+ def propagate(self, *args):
62
+ fake_args = [
63
+ self._mode.from_tensor(a) if isinstance(a, torch.Tensor) else a
64
+ for a in args
65
+ ]
66
+ return self.propagate_dont_convert_inputs(*fake_args)
67
+
68
+ def propagate_dont_convert_inputs(self, *args):
69
+ with self._mode:
70
+ return super().run(*args)
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_drawer.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import hashlib
4
+ from itertools import chain
5
+ from typing import Any, Dict, Optional, TYPE_CHECKING
6
+
7
+ import torch
8
+ import torch.fx
9
+ from torch.fx._compatibility import compatibility
10
+ from torch.fx.graph import _parse_stack_trace
11
+ from torch.fx.node import _format_arg, _get_qualified_name
12
+ from torch.fx.operator_schemas import normalize_function
13
+ from torch.fx.passes.shape_prop import TensorMetadata
14
+
15
+
16
+ try:
17
+ import pydot
18
+
19
+ HAS_PYDOT = True
20
+ except ModuleNotFoundError:
21
+ HAS_PYDOT = False
22
+ pydot = None
23
+
24
+
25
+ __all__ = ["FxGraphDrawer"]
26
+
27
+ _COLOR_MAP = {
28
+ "placeholder": '"AliceBlue"',
29
+ "call_module": "LemonChiffon1",
30
+ "get_param": "Yellow2",
31
+ "get_attr": "LightGrey",
32
+ "output": "PowderBlue",
33
+ }
34
+
35
+ _HASH_COLOR_MAP = [
36
+ "CadetBlue1",
37
+ "Coral",
38
+ "DarkOliveGreen1",
39
+ "DarkSeaGreen1",
40
+ "GhostWhite",
41
+ "Khaki1",
42
+ "LavenderBlush1",
43
+ "LightSkyBlue",
44
+ "MistyRose1",
45
+ "MistyRose2",
46
+ "PaleTurquoise2",
47
+ "PeachPuff1",
48
+ "Salmon",
49
+ "Thistle1",
50
+ "Thistle3",
51
+ "Wheat1",
52
+ ]
53
+
54
+ _WEIGHT_TEMPLATE = {
55
+ "fillcolor": "Salmon",
56
+ "style": '"filled,rounded"',
57
+ "fontcolor": "#000000",
58
+ }
59
+
60
+ if HAS_PYDOT:
61
+ @compatibility(is_backward_compatible=False)
62
+ class FxGraphDrawer:
63
+ """
64
+ Visualize a torch.fx.Graph with graphviz
65
+ Basic usage:
66
+ g = FxGraphDrawer(symbolic_traced, "resnet18")
67
+ g.get_dot_graph().write_svg("a.svg")
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ graph_module: torch.fx.GraphModule,
73
+ name: str,
74
+ ignore_getattr: bool = False,
75
+ ignore_parameters_and_buffers: bool = False,
76
+ skip_node_names_in_args: bool = True,
77
+ parse_stack_trace: bool = False,
78
+ dot_graph_shape: Optional[str] = None,
79
+ normalize_args: bool = False,
80
+ ):
81
+ self._name = name
82
+ self.dot_graph_shape = (
83
+ dot_graph_shape if dot_graph_shape is not None else "record"
84
+ )
85
+ self.normalize_args = normalize_args
86
+ _WEIGHT_TEMPLATE["shape"] = self.dot_graph_shape
87
+
88
+ self._dot_graphs = {
89
+ name: self._to_dot(
90
+ graph_module, name, ignore_getattr, ignore_parameters_and_buffers, skip_node_names_in_args, parse_stack_trace
91
+ )
92
+ }
93
+
94
+ for node in graph_module.graph.nodes:
95
+ if node.op != "call_module":
96
+ continue
97
+
98
+ leaf_node = self._get_leaf_node(graph_module, node)
99
+
100
+ if not isinstance(leaf_node, torch.fx.GraphModule):
101
+ continue
102
+
103
+ self._dot_graphs[f"{name}_{node.target}"] = self._to_dot(
104
+ leaf_node,
105
+ f"{name}_{node.target}",
106
+ ignore_getattr,
107
+ ignore_parameters_and_buffers,
108
+ skip_node_names_in_args,
109
+ parse_stack_trace,
110
+ )
111
+
112
+ def get_dot_graph(self, submod_name=None) -> pydot.Dot:
113
+ """
114
+ Visualize a torch.fx.Graph with graphviz
115
+ Example:
116
+ >>> # xdoctest: +REQUIRES(module:pydot)
117
+ >>> # xdoctest: +REQUIRES(module:ubelt)
118
+ >>> # define module
119
+ >>> class MyModule(torch.nn.Module):
120
+ >>> def __init__(self) -> None:
121
+ >>> super().__init__()
122
+ >>> self.linear = torch.nn.Linear(4, 5)
123
+ >>> def forward(self, x):
124
+ >>> return self.linear(x).clamp(min=0.0, max=1.0)
125
+ >>> module = MyModule()
126
+ >>> # trace the module
127
+ >>> symbolic_traced = torch.fx.symbolic_trace(module)
128
+ >>> # setup output file
129
+ >>> import ubelt as ub
130
+ >>> dpath = ub.Path.appdir('torch/tests/FxGraphDrawer').ensuredir()
131
+ >>> fpath = dpath / 'linear.svg'
132
+ >>> # draw the graph
133
+ >>> g = FxGraphDrawer(symbolic_traced, "linear")
134
+ >>> g.get_dot_graph().write_svg(fpath)
135
+ """
136
+ if submod_name is None:
137
+ return self.get_main_dot_graph()
138
+ else:
139
+ return self.get_submod_dot_graph(submod_name)
140
+
141
+ def get_main_dot_graph(self) -> pydot.Dot:
142
+ return self._dot_graphs[self._name]
143
+
144
+ def get_submod_dot_graph(self, submod_name) -> pydot.Dot:
145
+ return self._dot_graphs[f"{self._name}_{submod_name}"]
146
+
147
+ def get_all_dot_graphs(self) -> Dict[str, pydot.Dot]:
148
+ return self._dot_graphs
149
+
150
+ def _get_node_style(self, node: torch.fx.Node) -> Dict[str, str]:
151
+
152
+ template = {
153
+ "shape": self.dot_graph_shape,
154
+ "fillcolor": "#CAFFE3",
155
+ "style": '"filled,rounded"',
156
+ "fontcolor": "#000000",
157
+ }
158
+ if node.op in _COLOR_MAP:
159
+ template["fillcolor"] = _COLOR_MAP[node.op]
160
+ else:
161
+ # Use a random color for each node; based on its name so it's stable.
162
+ target_name = node._pretty_print_target(node.target)
163
+ target_hash = int(hashlib.md5(target_name.encode()).hexdigest()[:8], 16)
164
+ template["fillcolor"] = _HASH_COLOR_MAP[target_hash % len(_HASH_COLOR_MAP)]
165
+ return template
166
+
167
+ def _get_leaf_node(
168
+ self, module: torch.nn.Module, node: torch.fx.Node
169
+ ) -> torch.nn.Module:
170
+ py_obj = module
171
+ assert isinstance(node.target, str)
172
+ atoms = node.target.split(".")
173
+ for atom in atoms:
174
+ if not hasattr(py_obj, atom):
175
+ raise RuntimeError(
176
+ str(py_obj) + " does not have attribute " + atom + "!"
177
+ )
178
+ py_obj = getattr(py_obj, atom)
179
+ return py_obj
180
+
181
+ def _typename(self, target: Any) -> str:
182
+ if isinstance(target, torch.nn.Module):
183
+ ret = torch.typename(target)
184
+ elif isinstance(target, str):
185
+ ret = target
186
+ else:
187
+ ret = _get_qualified_name(target)
188
+
189
+ # Escape "{" and "}" to prevent dot files like:
190
+ # https://gist.github.com/SungMinCho/1a017aab662c75d805c5954d62c5aabc
191
+ # which triggers `Error: bad label format (...)` from dot
192
+ return ret.replace("{", r"\{").replace("}", r"\}")
193
+
194
+ # shorten path to avoid drawing long boxes
195
+ # for full path = '/home/weif/pytorch/test.py'
196
+ # return short path = 'pytorch/test.py'
197
+ def _shorten_file_name(
198
+ self,
199
+ full_file_name: str,
200
+ truncate_to_last_n: int = 2,
201
+ ):
202
+ splits = full_file_name.split('/')
203
+ if len(splits) >= truncate_to_last_n:
204
+ return '/'.join(splits[-truncate_to_last_n:])
205
+ return full_file_name
206
+
207
+
208
+ def _get_node_label(
209
+ self,
210
+ module: torch.fx.GraphModule,
211
+ node: torch.fx.Node,
212
+ skip_node_names_in_args: bool,
213
+ parse_stack_trace: bool,
214
+ ) -> str:
215
+ def _get_str_for_args_kwargs(arg):
216
+ if isinstance(arg, tuple):
217
+ prefix, suffix = r"|args=(\l", r",\n)\l"
218
+ arg_strs_list = [_format_arg(a, max_list_len=8) for a in arg]
219
+ elif isinstance(arg, dict):
220
+ prefix, suffix = r"|kwargs={\l", r",\n}\l"
221
+ arg_strs_list = [
222
+ f"{k}: {_format_arg(v, max_list_len=8)}"
223
+ for k, v in arg.items()
224
+ ]
225
+ else: # Fall back to nothing in unexpected case.
226
+ return ""
227
+
228
+ # Strip out node names if requested.
229
+ if skip_node_names_in_args:
230
+ arg_strs_list = [a for a in arg_strs_list if "%" not in a]
231
+ if len(arg_strs_list) == 0:
232
+ return ""
233
+ arg_strs = prefix + r",\n".join(arg_strs_list) + suffix
234
+ if len(arg_strs_list) == 1:
235
+ arg_strs = arg_strs.replace(r"\l", "").replace(r"\n", "")
236
+ return arg_strs.replace("{", r"\{").replace("}", r"\}")
237
+
238
+
239
+ label = "{" + f"name=%{node.name}|op_code={node.op}\n"
240
+
241
+ if node.op == "call_module":
242
+ leaf_module = self._get_leaf_node(module, node)
243
+ label += r"\n" + self._typename(leaf_module) + r"\n|"
244
+ extra = ""
245
+ if hasattr(leaf_module, "__constants__"):
246
+ extra = r"\n".join(
247
+ [f"{c}: {getattr(leaf_module, c)}" for c in leaf_module.__constants__] # type: ignore[union-attr]
248
+ )
249
+ label += extra + r"\n"
250
+ else:
251
+ label += f"|target={self._typename(node.target)}" + r"\n"
252
+ if self.normalize_args:
253
+ try:
254
+ args, kwargs = normalize_function( # type: ignore[misc]
255
+ node.target, node.args, node.kwargs, normalize_to_only_use_kwargs=True # type: ignore[arg-type]
256
+ )
257
+ except Exception:
258
+ # Fallback to not normalizing if there's an exception.
259
+ # Some functions need overloads specified to normalize.
260
+ args, kwargs = node.args, node.kwargs
261
+ else:
262
+ args, kwargs = node.args, node.kwargs
263
+ if len(args) > 0:
264
+ label += _get_str_for_args_kwargs(args)
265
+ if len(kwargs) > 0:
266
+ label += _get_str_for_args_kwargs(kwargs)
267
+ label += f"|num_users={len(node.users)}" + r"\n"
268
+
269
+ tensor_meta = node.meta.get('tensor_meta')
270
+ label += self._tensor_meta_to_label(tensor_meta)
271
+
272
+ # for original fx graph
273
+ # print buf=buf0, n_origin=6
274
+ buf_meta = node.meta.get('buf_meta', None)
275
+ if buf_meta is not None:
276
+ label += f"|buf={buf_meta.name}" + r"\n"
277
+ label += f"|n_origin={buf_meta.n_origin}" + r"\n"
278
+
279
+ # for original fx graph
280
+ # print file:lineno code
281
+ if parse_stack_trace and node.stack_trace is not None:
282
+ parsed_stack_trace = _parse_stack_trace(node.stack_trace)
283
+ fname = self._shorten_file_name(parsed_stack_trace.file)
284
+ label += f"|file={fname}:{parsed_stack_trace.lineno} {parsed_stack_trace.code}" + r"\n"
285
+
286
+
287
+ return label + "}"
288
+
289
+ def _tensor_meta_to_label(self, tm) -> str:
290
+ if tm is None:
291
+ return ""
292
+ elif isinstance(tm, TensorMetadata):
293
+ return self._stringify_tensor_meta(tm)
294
+ elif isinstance(tm, list):
295
+ result = ""
296
+ for item in tm:
297
+ result += self._tensor_meta_to_label(item)
298
+ return result
299
+ elif isinstance(tm, dict):
300
+ result = ""
301
+ for v in tm.values():
302
+ result += self._tensor_meta_to_label(v)
303
+ return result
304
+ elif isinstance(tm, tuple):
305
+ result = ""
306
+ for item in tm:
307
+ result += self._tensor_meta_to_label(item)
308
+ return result
309
+ else:
310
+ raise RuntimeError(f"Unsupported tensor meta type {type(tm)}")
311
+
312
+ def _stringify_tensor_meta(self, tm: TensorMetadata) -> str:
313
+ result = ""
314
+ if not hasattr(tm, "dtype"):
315
+ print("tm", tm)
316
+ result += "|" + "dtype" + "=" + str(tm.dtype) + r"\n"
317
+ result += "|" + "shape" + "=" + str(tuple(tm.shape)) + r"\n"
318
+ result += "|" + "requires_grad" + "=" + str(tm.requires_grad) + r"\n"
319
+ result += "|" + "stride" + "=" + str(tm.stride) + r"\n"
320
+ if tm.is_quantized:
321
+ assert tm.qparams is not None
322
+ assert "qscheme" in tm.qparams
323
+ qscheme = tm.qparams["qscheme"]
324
+ if qscheme in {
325
+ torch.per_tensor_affine,
326
+ torch.per_tensor_symmetric,
327
+ }:
328
+ result += "|" + "q_scale" + "=" + str(tm.qparams["scale"]) + r"\n"
329
+ result += "|" + "q_zero_point" + "=" + str(tm.qparams["zero_point"]) + r"\n"
330
+ elif qscheme in {
331
+ torch.per_channel_affine,
332
+ torch.per_channel_symmetric,
333
+ torch.per_channel_affine_float_qparams,
334
+ }:
335
+ result += "|" + "q_per_channel_scale" + "=" + str(tm.qparams["scale"]) + r"\n"
336
+ result += "|" + "q_per_channel_zero_point" + "=" + str(tm.qparams["zero_point"]) + r"\n"
337
+ result += "|" + "q_per_channel_axis" + "=" + str(tm.qparams["axis"]) + r"\n"
338
+ else:
339
+ raise RuntimeError(f"Unsupported qscheme: {qscheme}")
340
+ result += "|" + "qscheme" + "=" + str(tm.qparams["qscheme"]) + r"\n"
341
+ return result
342
+
343
+ def _get_tensor_label(self, t: torch.Tensor) -> str:
344
+ return str(t.dtype) + str(list(t.shape)) + r"\n"
345
+
346
+ # when parse_stack_trace=True
347
+ # print file:lineno code
348
+ def _to_dot(
349
+ self,
350
+ graph_module: torch.fx.GraphModule,
351
+ name: str,
352
+ ignore_getattr: bool,
353
+ ignore_parameters_and_buffers: bool,
354
+ skip_node_names_in_args: bool,
355
+ parse_stack_trace: bool,
356
+ ) -> pydot.Dot:
357
+ """
358
+ Actual interface to visualize a fx.Graph. Note that it takes in the GraphModule instead of the Graph.
359
+ If ignore_parameters_and_buffers is True, the parameters and buffers
360
+ created with the module will not be added as nodes and edges.
361
+ """
362
+
363
+ # "TB" means top-to-bottom rank direction in layout
364
+ dot_graph = pydot.Dot(name, rankdir="TB")
365
+
366
+
367
+ buf_name_to_subgraph = {}
368
+
369
+ for node in graph_module.graph.nodes:
370
+ if ignore_getattr and node.op == "get_attr":
371
+ continue
372
+
373
+ style = self._get_node_style(node)
374
+ dot_node = pydot.Node(
375
+ node.name, label=self._get_node_label(graph_module, node, skip_node_names_in_args, parse_stack_trace), **style
376
+ )
377
+
378
+ current_graph = dot_graph
379
+
380
+ buf_meta = node.meta.get('buf_meta', None)
381
+ if buf_meta is not None and buf_meta.n_origin > 1:
382
+ buf_name = buf_meta.name
383
+ if buf_name not in buf_name_to_subgraph:
384
+ buf_name_to_subgraph[buf_name] = pydot.Cluster(buf_name, label=buf_name)
385
+ current_graph = buf_name_to_subgraph.get(buf_name)
386
+
387
+ current_graph.add_node(dot_node)
388
+
389
+ def get_module_params_or_buffers():
390
+ for pname, ptensor in chain(
391
+ leaf_module.named_parameters(), leaf_module.named_buffers()
392
+ ):
393
+ pname1 = node.name + "." + pname
394
+ label1 = (
395
+ pname1 + "|op_code=get_" + "parameter"
396
+ if isinstance(ptensor, torch.nn.Parameter)
397
+ else "buffer" + r"\l"
398
+ )
399
+ dot_w_node = pydot.Node(
400
+ pname1,
401
+ label="{" + label1 + self._get_tensor_label(ptensor) + "}",
402
+ **_WEIGHT_TEMPLATE,
403
+ )
404
+ dot_graph.add_node(dot_w_node)
405
+ dot_graph.add_edge(pydot.Edge(pname1, node.name))
406
+
407
+ if node.op == "call_module":
408
+ leaf_module = self._get_leaf_node(graph_module, node)
409
+
410
+ if not ignore_parameters_and_buffers and not isinstance(leaf_module, torch.fx.GraphModule):
411
+ get_module_params_or_buffers()
412
+
413
+ for subgraph in buf_name_to_subgraph.values():
414
+ subgraph.set('color', 'royalblue')
415
+ subgraph.set('penwidth', '2')
416
+ dot_graph.add_subgraph(subgraph)
417
+
418
+ for node in graph_module.graph.nodes:
419
+ if ignore_getattr and node.op == "get_attr":
420
+ continue
421
+
422
+ for user in node.users:
423
+ dot_graph.add_edge(pydot.Edge(node.name, user.name))
424
+
425
+ return dot_graph
426
+
427
+ else:
428
+ if not TYPE_CHECKING:
429
+ @compatibility(is_backward_compatible=False)
430
+ class FxGraphDrawer:
431
+ def __init__(
432
+ self,
433
+ graph_module: torch.fx.GraphModule,
434
+ name: str,
435
+ ignore_getattr: bool = False,
436
+ ignore_parameters_and_buffers: bool = False,
437
+ skip_node_names_in_args: bool = True,
438
+ parse_stack_trace: bool = False,
439
+ dot_graph_shape: Optional[str] = None,
440
+ normalize_args: bool = False,
441
+ ):
442
+ raise RuntimeError('FXGraphDrawer requires the pydot package to be installed. Please install '
443
+ 'pydot through your favorite Python package manager.')
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_manipulation.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Dict, List, NamedTuple, Optional
3
+
4
+ import torch
5
+ from torch.fx._compatibility import compatibility
6
+ from torch.fx.graph import Graph
7
+ from torch.fx.graph_module import GraphModule
8
+ from torch.fx.node import (
9
+ map_arg,
10
+ Node,
11
+ Target,
12
+ )
13
+ from torch.fx.passes.shape_prop import ShapeProp
14
+
15
+ __all__ = ['replace_target_nodes_with', 'size_bytes', 'get_size_of_all_nodes', 'get_tensor_meta',
16
+ 'get_size_of_node']
17
+
18
+ @compatibility(is_backward_compatible=False)
19
+ def replace_target_nodes_with(
20
+ fx_module: GraphModule,
21
+ old_op: str,
22
+ old_target: Target,
23
+ new_op: str,
24
+ new_target: Target,
25
+ ):
26
+ """Modifies all nodes in fx_module.graph.nodes which match the specified op code and target,
27
+ and updates them to match the new op code and target"""
28
+ new_graph = Graph()
29
+ val_map: Dict[Node, Node] = {}
30
+ for node in fx_module.graph.nodes:
31
+ if node.op == old_op and node.target == old_target:
32
+ args = map_arg(node.args, lambda n: val_map[n])
33
+ kwargs = map_arg(node.kwargs, lambda n: val_map[n])
34
+ assert isinstance(args, tuple)
35
+ assert isinstance(kwargs, dict)
36
+ val_map[node] = new_graph.create_node(
37
+ new_op, new_target, args, kwargs, node.name
38
+ )
39
+ else:
40
+ val_map[node] = new_graph.node_copy(node, lambda n: val_map[n])
41
+ fx_module.graph = new_graph
42
+
43
+
44
+ @compatibility(is_backward_compatible=False)
45
+ class size_bytes(NamedTuple):
46
+ output_size: int
47
+ total_size: int
48
+
49
+
50
+ @compatibility(is_backward_compatible=False)
51
+ def get_size_of_all_nodes(
52
+ fx_module: GraphModule, args: Optional[List[torch.Tensor]] = None
53
+ ) -> None:
54
+ """Given a fx graph module, update each node with its total size (weights + bias + output)
55
+ and its output_size(output). For a non-module node, the total size is the output size.
56
+ return total size"""
57
+ if args is not None:
58
+ # Mark shape and dtype for each node (node.shape and node.dtype)
59
+ ShapeProp(fx_module).propagate(*args)
60
+ # Calculate the total size of the whole fx graph
61
+ total_size_of_graph = 0.0
62
+ for node in fx_module.graph.nodes:
63
+ if node.op == "output":
64
+ break
65
+ node.size_bytes = get_size_of_node(fx_module, node)
66
+ return
67
+
68
+
69
+ @compatibility(is_backward_compatible=False)
70
+ def get_tensor_meta(node: Node) -> Any:
71
+ tensor_meta = node.meta.get("tensor_meta")
72
+
73
+ if not tensor_meta:
74
+ raise RuntimeError(
75
+ f"Node {node} has no tensor metadata associated with it! "
76
+ f"Check that shape propagation has run."
77
+ )
78
+
79
+ return tensor_meta
80
+
81
+
82
+ @compatibility(is_backward_compatible=False)
83
+ def get_size_of_node(fx_module: GraphModule, node: Node) -> size_bytes:
84
+ """Given a node with node.dtype and node.shape, return its total size and its output size.
85
+ total_size = weights + bias + output_size
86
+ """
87
+ # Total num of elements
88
+ total_num_of_elems = 0
89
+ # For a module, conside all parameters
90
+ if node.op == "call_module":
91
+ submodule_dict = dict(fx_module.named_modules())
92
+ submodule = submodule_dict[node.target]
93
+ parameters = submodule.named_parameters()
94
+ # Parameters are named tuples
95
+ for name, p in parameters:
96
+ total_num_of_elems += p.numel()
97
+ # Don't forget the output size
98
+ # node.shape is the shape of this node's output
99
+ tensor_meta = get_tensor_meta(node)
100
+ output_elem = tensor_meta.shape.numel()
101
+ total_num_of_elems += output_elem
102
+ # Assume for now if it's quantized then it's qint8 or quint8
103
+ if tensor_meta.is_quantized:
104
+ size_per_elem_bytes = torch._empty_affine_quantized(
105
+ [], dtype=tensor_meta.dtype
106
+ ).element_size()
107
+ else:
108
+ size_per_elem_bytes = torch.tensor([], dtype=tensor_meta.dtype).element_size()
109
+ total_size = size_per_elem_bytes * total_num_of_elems
110
+ output_size = size_per_elem_bytes * output_elem
111
+ return size_bytes(output_size, total_size)
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/graph_transform_observer.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import os
3
+ from typing import Optional
4
+
5
+ from torch.fx._compatibility import compatibility
6
+ from torch.fx.graph_module import GraphModule
7
+
8
+ from .graph_drawer import FxGraphDrawer
9
+
10
+
11
+ __all__ = ["GraphTransformObserver"]
12
+
13
+
14
+ @compatibility(is_backward_compatible=False)
15
+ class GraphTransformObserver:
16
+ __pass_count = 0
17
+
18
+ def __init__(self, gm: GraphModule, passname: str, log_url: Optional[str] = None):
19
+ # If log_url is None, we don't log anything
20
+ self.log_url = log_url
21
+ if self.log_url is None:
22
+ return
23
+ GraphTransformObserver.__pass_count += 1
24
+ self.gm = gm
25
+ self.passname = passname
26
+
27
+ self.input_dot_graph = FxGraphDrawer(
28
+ self.gm,
29
+ self.passname,
30
+ ignore_getattr=True,
31
+ ignore_parameters_and_buffers=True,
32
+ ).get_dot_graph()
33
+
34
+ @classmethod
35
+ def get_current_pass_count(cls):
36
+ return cls.__pass_count
37
+
38
+ def __enter__(self):
39
+ if self.log_url is None or self.gm is None:
40
+ return self
41
+
42
+ self.erased_nodes = set()
43
+ self.created_nodes = set()
44
+ self.gm._register_create_node_hook(self.on_node_creation)
45
+ self.gm._register_erase_node_hook(self.on_node_erase)
46
+
47
+ return self
48
+
49
+ def __exit__(self, type, value, tb):
50
+ if self.log_url is None or self.gm is None:
51
+ return
52
+
53
+ self.gm._unregister_create_node_hook(self.on_node_creation)
54
+ self.gm._unregister_erase_node_hook(self.on_node_erase)
55
+
56
+ if len(self.created_nodes) > 0 or len(self.erased_nodes) > 0:
57
+ for e in self.input_dot_graph.get_node_list():
58
+ if e.get_name() in self.erased_nodes:
59
+ e.obj_dict["attributes"]["fillcolor"] = "yellow"
60
+ else:
61
+ e.obj_dict["attributes"]["fillcolor"] = "grey"
62
+ self.input_dot_graph.write(
63
+ os.path.join(
64
+ self.log_url,
65
+ f"pass_{GraphTransformObserver.__pass_count}_{self.passname}_input_graph.dot",
66
+ )
67
+ )
68
+
69
+ output_dot_graph = FxGraphDrawer(
70
+ self.gm,
71
+ self.passname,
72
+ ignore_getattr=True,
73
+ ignore_parameters_and_buffers=True,
74
+ ).get_dot_graph()
75
+ for e in output_dot_graph.get_node_list():
76
+ if e.get_name() in self.created_nodes:
77
+ e.obj_dict["attributes"]["fillcolor"] = "yellow"
78
+ else:
79
+ e.obj_dict["attributes"]["fillcolor"] = "grey"
80
+ output_dot_graph.write(
81
+ os.path.join(
82
+ self.log_url,
83
+ f"pass_{GraphTransformObserver.__pass_count}_{self.passname}_output_graph.dot",
84
+ )
85
+ )
86
+
87
+ def on_node_creation(self, node):
88
+ self.created_nodes.add(node.name)
89
+
90
+ def on_node_erase(self, node):
91
+ self.erased_nodes.add(node.name)
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+
2
+ from . import pass_manager
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (214 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/partitioner.cpython-310.pyc ADDED
Binary file (9.57 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/pass_base.cpython-310.pyc ADDED
Binary file (3.06 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/__pycache__/pass_manager.cpython-310.pyc ADDED
Binary file (9.4 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/partitioner.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from torch.fx.passes.utils.fuser_utils import fuse_by_partitions
3
+ import collections
4
+ import itertools
5
+ import logging
6
+
7
+ from copy import copy
8
+ from typing import Dict, Iterable, List, Optional, Sequence, Set
9
+
10
+ from torch.fx.graph_module import GraphModule
11
+ from torch.fx.node import Node, _get_qualified_name
12
+ from torch.fx.passes.operator_support import OperatorSupportBase
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logger.setLevel(logging.WARNING)
17
+
18
+ class Partition:
19
+ def __init__(self, id: Optional[int] = None, nodes: Optional[Iterable[Node]] = None):
20
+ self.id = id
21
+ self.nodes = dict.fromkeys(nodes) if nodes is not None else {}
22
+
23
+ def __repr__(self) -> str:
24
+ return str(self.nodes)
25
+
26
+ def add_node(self, node: Node):
27
+ self.nodes.update({node: None})
28
+
29
+ def remove_node(self, node: Node):
30
+ del self.nodes[node]
31
+
32
+ def size(self):
33
+ return len(self.nodes)
34
+
35
+ class _DependencyViewer:
36
+ def __init__(self, graph_module: GraphModule):
37
+ self.upstreams = collections.defaultdict(set)
38
+ self.downstreams = collections.defaultdict(set)
39
+
40
+ for node in graph_module.graph.nodes:
41
+ for input_node in node.all_input_nodes:
42
+ # add input_node and input_node's upstream dependency
43
+ self.upstreams[node].add(input_node)
44
+ self.upstreams[node].update(self.upstreams[input_node])
45
+
46
+ for node in reversed(graph_module.graph.nodes):
47
+ for output_node in node.users:
48
+ # add output_node and output_node's downstream dependency
49
+ self.downstreams[node].add(output_node)
50
+ self.downstreams[node].update(self.downstreams[output_node])
51
+
52
+ def downstreams_of(self, node: Node) -> Set[Node]:
53
+ return self.downstreams[node]
54
+
55
+ def upstreams_of(self, node: Node) -> Set[Node]:
56
+ return self.upstreams[node]
57
+
58
+ class CapabilityBasedPartitioner:
59
+
60
+ def __init__(self,
61
+ graph_module: GraphModule,
62
+ operator_support: OperatorSupportBase,
63
+ allows_single_node_partition: bool = False,
64
+ non_compute_ops: Optional[Sequence[str]] = None,
65
+ allowed_single_node_partition_ops: Optional[Sequence[str]] = None,
66
+ ) -> None:
67
+ self.graph_module = graph_module
68
+ self.operator_support = operator_support
69
+ self.allows_single_node_partition = allows_single_node_partition
70
+ self.non_compute_ops = non_compute_ops if non_compute_ops is not None else []
71
+ self.allowed_single_node_partition_ops = (
72
+ allowed_single_node_partition_ops
73
+ if allowed_single_node_partition_ops is not None
74
+ else []
75
+ )
76
+ self.dependency_viewer = _DependencyViewer(graph_module)
77
+
78
+ def __is_node_supported(self, node: Node) -> bool:
79
+ return (
80
+ self.operator_support.is_node_supported(dict(self.graph_module.named_modules()), node)
81
+ )
82
+
83
+ def propose_partitions(self) -> List[Partition]:
84
+ # partition_map is a mapping from partition id to a set of partition id's.
85
+ # The value set contains all the partition ids that can be reached by doing a
86
+ # DFS starting from the partition id in the key.
87
+ partition_map : Dict[int, Set] = collections.defaultdict(set)
88
+
89
+ # assumptions: nodes in candidate list is sorted in topological order
90
+ assignment: Dict[Node, int] = {} # mapping from node to partition_id
91
+ partitions_by_id: Dict[int, Partition] = {} # mapping from partition_id to partition
92
+ new_partition_id = itertools.count()
93
+
94
+ # try to merge partition other_id into partition self_id
95
+ # merge only happens if the end graph doesn't contain cyclic dependency
96
+ # returns `True` when merge happens, `False` otherwise.
97
+ def maybe_merge_partition(self_id: int, other_id: int):
98
+ # merged_nodes is the union of nodes in two partition to-be-merged
99
+ merged_nodes = copy(partitions_by_id[self_id].nodes)
100
+ merged_nodes.update(partitions_by_id[other_id].nodes)
101
+
102
+ def dfs_iter_find_cycle(all_user_nodes: Set[Node]):
103
+ for user_node in all_user_nodes:
104
+ visited_partition_ids = set()
105
+
106
+ for path_node in self.dependency_viewer.downstreams_of(user_node):
107
+ # If any of the nodes in the dfs path of this node are in the merged_nodes
108
+ # list then there is a cycle in the graph.
109
+ if path_node in merged_nodes:
110
+ return True
111
+
112
+ # If any of the nodes in the dfs path of this node are in the assignment
113
+ # map then we have to make sure that the partitions that these nodes belong
114
+ # to do not form a cycle with the current partitions being merged. This means
115
+ # iterating through all the nodes in all the parititons that are traversed in
116
+ # the dfs path and checking if they are in the merged_nodes list.
117
+ if path_node in assignment:
118
+ partition_id = assignment[path_node]
119
+ # If the partition id has already been visited then we know that it doesn't
120
+ # form a cycle with the current partitions being merged.
121
+ if partition_id in visited_partition_ids:
122
+ continue
123
+ p_map = partition_map[partition_id]
124
+ if self_id in p_map or other_id in p_map:
125
+ return True
126
+
127
+ visited_partition_ids.add(partition_id)
128
+
129
+ return False
130
+
131
+ # check if merge would create cyclic dependency.
132
+ all_user_nodes = set()
133
+ for node in merged_nodes:
134
+ for user_node in node.users:
135
+ if user_node not in merged_nodes:
136
+ all_user_nodes.add(user_node)
137
+
138
+ if dfs_iter_find_cycle(all_user_nodes):
139
+ # return false indicating cyclic dependency found and
140
+ # merge is aborted
141
+ return False
142
+
143
+ # no cyclic dependency found, move forward with the merge
144
+ # updating partition nodes
145
+ partitions_by_id[self_id].nodes = merged_nodes
146
+ # updating assignment map
147
+ for node in partitions_by_id[other_id].nodes:
148
+ assignment[node] = self_id
149
+ # delete other partition
150
+ del partitions_by_id[other_id]
151
+
152
+ partition_map[self_id] = partition_map[self_id].union(partition_map[other_id])
153
+ del partition_map[other_id]
154
+
155
+ return True
156
+
157
+ def merge_single_node(node: Node, id: Optional[int]):
158
+ def _update_partition_map(node: Node, id: int):
159
+ # Iterate through all the downstream nodes of this node and update the partition map
160
+ # to indicate that there is a path from the partition id of this node to the target
161
+ # partition id.
162
+ downstream_nodes = self.dependency_viewer.downstreams_of(node)
163
+ for curr_node in downstream_nodes:
164
+ target_id = assignment.get(curr_node, None)
165
+ if target_id is not None:
166
+ partition_map[id].add(target_id)
167
+
168
+ # Iterate through all the upstream nodes of this node and update the partition map
169
+ # to indicate that there is a path from the partition id of the upstream node to the
170
+ # current node's partition id.
171
+ upstream_nodes = self.dependency_viewer.upstreams_of(node)
172
+ for curr_node in upstream_nodes:
173
+ source_id = assignment.get(curr_node, None)
174
+ if source_id is not None:
175
+ partition_map[source_id].add(id)
176
+
177
+ if node in assignment:
178
+ partitions_by_id[assignment[node]].remove_node(node)
179
+
180
+ if id is None:
181
+ assignment.pop(node)
182
+ elif id not in partitions_by_id:
183
+ assignment[node] = id
184
+ partitions_by_id[id] = Partition(id=id, nodes=[node])
185
+ _update_partition_map(node, id)
186
+ else:
187
+ assignment[node] = id
188
+ partitions_by_id[id].add_node(node)
189
+ _update_partition_map(node, id)
190
+
191
+ logger.debug("Proposing partitions...")
192
+
193
+ for node in reversed(self.graph_module.graph.nodes):
194
+ # use Dict as an ordered set to ensure deterministic partitioning result, don't care value
195
+ merge_candidates: Dict[int, None] = {}
196
+
197
+ # Note a limited horizontal fusion is enabled:
198
+ # when `node` is not supported, the code below attempts to fuse consumer of `node`.
199
+ #
200
+ # I don't see a need to add a knob to disable horizontal fusion yet, we can short-cut
201
+ # the fusion by adding an `else` block here to skip horizontal fusion.
202
+ if self.__is_node_supported(node) and node not in assignment:
203
+ partition_id = next(new_partition_id)
204
+ merge_single_node(node, partition_id)
205
+ merge_candidates[partition_id] = None
206
+
207
+ # merge all possible partitions
208
+ for node in assignment:
209
+ merge_candidates[assignment[node]] = None
210
+
211
+ merge_candidates_list = list(merge_candidates.keys())
212
+ if len(merge_candidates_list) > 1:
213
+ self_id = merge_candidates_list[0]
214
+ for other_id in merge_candidates_list[1:]:
215
+ # note: merge partition `other_id` into partition `self_id` if
216
+ # it doesn't create cyclic dependency in the graph, otherwise,
217
+ # this is a no-op
218
+ maybe_merge_partition(self_id, other_id)
219
+
220
+ # post processing to re-assign "getitem" nodes into upstream partition
221
+ logger.debug("Reassigning getitem nodes to its producer node's partition...")
222
+ nodes_reassignment: Dict[Node, int] = {}
223
+ for node in self.graph_module.graph.nodes:
224
+ is_tuple_output = True
225
+ for user in node.users:
226
+ if user.op != "call_function" or \
227
+ _get_qualified_name(user.target) != "_operator.getitem": # type: ignore[arg-type]
228
+ is_tuple_output = False
229
+ break
230
+
231
+ # node has tuple outputs, re-assign all following getitem node into node's partition
232
+ if is_tuple_output:
233
+ id = assignment.get(node, None) # type: ignore[arg-type]
234
+ for user in node.users:
235
+ if assignment.get(user, None) != id: # type: ignore[arg-type]
236
+ nodes_reassignment[user] = id # type: ignore[assignment]
237
+ for node, id in nodes_reassignment.items():
238
+ merge_single_node(node, id)
239
+
240
+ # filter out single node partitions
241
+ if not self.allows_single_node_partition:
242
+ logger.debug("Filtering out single node partitions...")
243
+ default_non_compute_ops = {"torch.ops.aten.view", "_operator.getitem"}
244
+ non_compute_ops = default_non_compute_ops.union(set(self.non_compute_ops))
245
+ partitions_to_remove: List[int] = []
246
+ for id, partition in partitions_by_id.items():
247
+ compute_node_count = 0
248
+ for node in partition.nodes:
249
+ if node.op == "call_function":
250
+ assert callable(node.target)
251
+ if _get_qualified_name(node.target) not in non_compute_ops:
252
+ compute_node_count += 1
253
+ if _get_qualified_name(node.target) in self.allowed_single_node_partition_ops:
254
+ compute_node_count += 1
255
+ if compute_node_count <= 1:
256
+ partitions_to_remove.append(id)
257
+ for id in partitions_to_remove:
258
+ del partitions_by_id[id]
259
+
260
+ logger.debug("Partitions proposed:")
261
+ for id, partition in partitions_by_id.items():
262
+ logger.debug("partition #%s: %s", id, [node.name for node in partition.nodes])
263
+
264
+ return [partition for partition in partitions_by_id.values() if partition.size() > 0]
265
+
266
+ def fuse_partitions(self, partitions: List[Partition], prefix: str = "fused_") -> GraphModule:
267
+ logger.debug("Fusing partitions...")
268
+ # fuse_by_partitions expects partitions in List[List[Node]]: [ [node0, node1], [node2, node3] ]
269
+ return fuse_by_partitions(
270
+ self.graph_module,
271
+ [list(partition.nodes) for partition in partitions],
272
+ prefix=prefix,
273
+ )
274
+
275
+ # remove non-compute-ops that sits at the boundary of a partition.
276
+ def remove_bookend_non_compute_ops(self, partitions: List[Partition]):
277
+ non_compute_ops = set(self.non_compute_ops)
278
+
279
+ def is_non_compute_node(node: Node):
280
+ return node.op == "call_function" and \
281
+ _get_qualified_name(node.target) in non_compute_ops # type: ignore[arg-type]
282
+
283
+ # cache transparent nodes
284
+ transparent_input_nodes: Dict[Node, bool] = {}
285
+ transparent_output_nodes: Dict[Node, bool] = {}
286
+
287
+ def is_transparent_input_node(node: Node, partition: Set[Node], removed_nodes: Set[Node]):
288
+ if node.op == "placeholder" or (node not in partition) or (node in removed_nodes):
289
+ return True
290
+ if node in transparent_input_nodes:
291
+ return transparent_input_nodes[node]
292
+ if is_non_compute_node(node):
293
+ for input_n in node.all_input_nodes:
294
+ if not is_transparent_input_node(input_n, partition, removed_nodes):
295
+ transparent_input_nodes[node] = False
296
+ return False
297
+ transparent_input_nodes[node] = True
298
+ return True
299
+ transparent_input_nodes[node] = False
300
+ return False
301
+
302
+ def is_transparent_output_node(node: Node, partition: Set[Node], removed_nodes: Set[Node]):
303
+ if node.op == "placeholder" or (node not in partition) or (node in removed_nodes):
304
+ return True
305
+ if node in transparent_output_nodes:
306
+ return transparent_output_nodes[node]
307
+ if is_non_compute_node(node):
308
+ for output_n in node.users:
309
+ if not is_transparent_output_node(output_n, partition, removed_nodes):
310
+ transparent_output_nodes[node] = False
311
+ return False
312
+ transparent_output_nodes[node] = True
313
+ return True
314
+ transparent_output_nodes[node] = False
315
+ return False
316
+
317
+ for partition in partitions:
318
+ # Note it's ok to use `set` here, since we are only query if a node
319
+ # has been removed. We are NEVER going to iterate on nodes inside
320
+ # the set.
321
+ remove_node: Set[Node] = set()
322
+ for node in partition.nodes:
323
+ if is_non_compute_node(node) and \
324
+ (is_transparent_input_node(node, set(partition.nodes), remove_node) or
325
+ is_transparent_output_node(node, set(partition.nodes), remove_node)):
326
+ remove_node.add(node)
327
+
328
+ if len(remove_node) != 0:
329
+ for node in remove_node:
330
+ partition.nodes.pop(node, None)
331
+
332
+ def partition_and_fuse(self, prefix: str = "fused_") -> GraphModule:
333
+ partitions = self.propose_partitions()
334
+ fused_gm = self.fuse_partitions(partitions, prefix=prefix)
335
+ return fused_gm
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/pass_base.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import abc
3
+ from collections import namedtuple
4
+ from typing import Optional
5
+
6
+ from torch.fx.graph_module import GraphModule
7
+ from torch.fx._compatibility import compatibility
8
+
9
+
10
+ __all__ = ['PassResult', 'PassBase']
11
+
12
+ @compatibility(is_backward_compatible=False)
13
+ class PassResult(namedtuple("PassResult", ["graph_module", "modified"])):
14
+ """
15
+ Result of a pass:
16
+ graph_module: The modified graph module
17
+ modified: A flag for if the pass has modified the graph module
18
+ """
19
+ def __new__(cls, graph_module, modified):
20
+ return super().__new__(cls, graph_module, modified)
21
+
22
+ @compatibility(is_backward_compatible=False)
23
+ class PassBase(abc.ABC):
24
+ """
25
+ Base interface for implementing passes.
26
+
27
+ It is required to implement the `call` function so that we can directly
28
+ pass instances of the Pass directly to the PassManager and call them as a
29
+ function.
30
+
31
+ We can directly pass an instance of a class implementing this interface into
32
+ the PassManager's `passes` attribute.
33
+ """
34
+
35
+ def __call__(self, graph_module: GraphModule) -> Optional[PassResult]:
36
+ """
37
+ Runs the precondition check, the pass itself, and the postcondition check.
38
+ """
39
+
40
+ self.requires(graph_module)
41
+ res = self.call(graph_module)
42
+ self.ensures(graph_module)
43
+ return res
44
+
45
+ @abc.abstractmethod
46
+ def call(self, graph_module: GraphModule) -> Optional[PassResult]:
47
+ """
48
+ The pass that is run through the given graph module. To implement a
49
+ pass, it is required to implement this function.
50
+
51
+ Args:
52
+ graph_module: The graph module we will run a pass on
53
+ """
54
+
55
+ def requires(self, graph_module: GraphModule) -> None: # noqa: B027
56
+ """
57
+ This function will be called before the pass is run and will check that
58
+ the given graph module contains the preconditions needed to run the
59
+ pass. It is not required to implement this function.
60
+
61
+ Args:
62
+ graph_module: The graph module we will run checks on
63
+ """
64
+
65
+ def ensures(self, graph_module: GraphModule) -> None: # noqa: B027
66
+ """
67
+ This function will be called after the pass is run and will check that
68
+ the given graph module contains the postconditions needed to run the
69
+ pass. It is not required to implement this function.
70
+
71
+ Args:
72
+ graph_module: The graph module we will run checks on
73
+ """
mplug_owl2/lib/python3.10/site-packages/torch/fx/passes/infra/pass_manager.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ import logging
4
+ from queue import Queue
5
+ from functools import wraps
6
+ from typing import Callable, Dict, List
7
+
8
+ import torch.nn as nn
9
+ from torch.fx.graph_module import GraphModule
10
+ from torch.fx._compatibility import compatibility
11
+ from torch.fx.passes.infra.pass_base import PassResult
12
+
13
+ logger = logging.getLogger(__name__)
14
+ logger.setLevel(logging.WARNING)
15
+
16
+ __all__ = ['pass_result_wrapper', 'this_before_that_pass_constraint', 'PassManager']
17
+
18
+ @compatibility(is_backward_compatible=False)
19
+ def pass_result_wrapper(fn: Callable) -> Callable:
20
+ """
21
+ Wrapper for passes which currently do not return a PassResult.
22
+ This wrapper makes them return a PassResult containing the modified object
23
+ and True for the "modified" flag.
24
+
25
+ Args:
26
+ fn (Callable[Module, Any])
27
+
28
+ Returns:
29
+ wrapped_fn (Callable[Module, PassResult])
30
+ """
31
+ if fn is None:
32
+ return None
33
+
34
+ @wraps(fn)
35
+ def wrapped_fn(gm):
36
+ res = fn(gm)
37
+ if res is None:
38
+ return PassResult(gm, True)
39
+ if isinstance(res, PassResult):
40
+ return res
41
+ elif isinstance(res, nn.Module):
42
+ return PassResult(res, True)
43
+
44
+ if not inspect.isfunction(fn):
45
+ wrapped_fn.__name__ = type(fn).__name__
46
+
47
+ return wrapped_fn
48
+
49
+ def _validate_pass_schedule_constraint(
50
+ constraint: Callable[[Callable, Callable], bool], passes: List[Callable]
51
+ ) -> None:
52
+ for i, a in enumerate(passes):
53
+ for j, b in enumerate(passes[i + 1 :]):
54
+ if constraint(a, b):
55
+ continue
56
+ raise RuntimeError(
57
+ f"pass schedule constraint violated. Expected {a} before {b}"
58
+ f" but found {a} at index {i} and {b} at index{j} in pass"
59
+ f" list."
60
+ )
61
+
62
+ def _topological_sort_passes(
63
+ passes: List[Callable], constraints: List[Callable]
64
+ ) -> List[Callable]:
65
+ """
66
+ Args
67
+ passes: Passes that we are ordering
68
+ constraints: Constraints applied on these passes
69
+
70
+ Returns
71
+ A sorted list of callables and a boolean of if a circular dependency
72
+ existed
73
+ """
74
+ if len(constraints) == 0:
75
+ return passes
76
+
77
+ # Contruct a graph mapping nodes to a list of their users
78
+ graph: Dict[Callable, List[Callable]] = {p : [] for p in passes}
79
+ indegree_map: Dict[Callable, int] = dict.fromkeys(passes, 0)
80
+ candidates: Queue = Queue()
81
+ for a in passes:
82
+ for b in passes:
83
+ if a == b:
84
+ continue
85
+
86
+ for constraint in constraints:
87
+ if not constraint(a, b):
88
+ graph[b].append(a)
89
+ indegree_map[a] += 1
90
+
91
+ if indegree_map[a] == 0:
92
+ candidates.put(a)
93
+
94
+ visited: Dict[Callable, bool] = dict.fromkeys(passes, False)
95
+ sorted_passes: List[Callable] = []
96
+
97
+ while not candidates.empty():
98
+ p = candidates.get()
99
+ sorted_passes.append(p)
100
+ visited[p] = True
101
+
102
+ for n in graph[p]:
103
+ if not visited[n]:
104
+ indegree_map[n] -= 1
105
+ if indegree_map[n] == 0:
106
+ candidates.put(n)
107
+
108
+ # Check if there are unvisited nodes (aka cycles in the graph)
109
+ cycle_passes = list(filter(lambda p: indegree_map[p] != 0, indegree_map.keys()))
110
+ if len(cycle_passes) != 0:
111
+ error = f"Circular dependency detected within the following passes: {cycle_passes}"
112
+ raise RuntimeError(error)
113
+
114
+ return sorted_passes
115
+
116
+ @compatibility(is_backward_compatible=False)
117
+ def this_before_that_pass_constraint(this: Callable, that: Callable) -> Callable:
118
+ """
119
+ Defines a partial order ('depends on' function) where `this` must occur
120
+ before `that`.
121
+
122
+ For example, the following pass list and constraint list would be invalid.
123
+ ```
124
+ passes = [pass_b, pass_a]
125
+
126
+ constraints = [
127
+ this_before_that_pass_constraint(pass_a, pass_b)
128
+ ]
129
+ ```
130
+
131
+ Args:
132
+ this (Callable): pass which should occur first
133
+ that (Callable): pass which should occur later
134
+
135
+ Returns:
136
+ depends_on (Callable[[Object, Object], bool]
137
+ """
138
+
139
+ def depends_on(a: Callable, b: Callable):
140
+ return a != that or b != this
141
+
142
+ return depends_on
143
+
144
+
145
+ @compatibility(is_backward_compatible=False)
146
+ class PassManager:
147
+ """
148
+ Construct a PassManager.
149
+
150
+ Collects passes and constraints. This defines the pass schedule, manages
151
+ pass constraints and pass execution.
152
+
153
+ Args:
154
+ passes (Optional[List[Callable]]): List of passes. A pass is a
155
+ callable which modifies an object and returns a PassResult
156
+ constraint (Optional[List[Callable]]): List of constraints. A
157
+ constraint is a callable which takes two passes (A, B) and returns
158
+ True if A depends on B and False otherwise. See implementation of
159
+ `this_before_that_pass_constraint` for example.
160
+ steps (int): Max number of times we run the passes (default = 1).
161
+ run_checks_after_each_pass (bool): Whether to run checks and linting
162
+ after each pass
163
+ suppress_check_failures (bool): Whether to raise errors when running
164
+ checks
165
+ """
166
+
167
+ passes: List[Callable[[nn.Module], PassResult]]
168
+ constraints: List[Callable[[Callable, Callable], bool]]
169
+ _validated: bool = False
170
+ steps: int = 1
171
+
172
+ def __init__(
173
+ self,
174
+ passes=None,
175
+ constraints=None,
176
+ steps=None,
177
+ run_checks_after_each_pass: bool = False,
178
+ suppress_check_failures: bool = False,
179
+ ):
180
+ self.passes = passes or []
181
+ self.constraints = constraints or []
182
+ if steps:
183
+ self.steps = steps
184
+
185
+ self.run_checks_after_each_pass = run_checks_after_each_pass
186
+ self.suppress_check_failures = suppress_check_failures
187
+
188
+ def add_pass(self, _pass: Callable):
189
+ """
190
+ Adds a pass into the current list of passes.
191
+ """
192
+ self.passes.append(_pass)
193
+ self._validated = False
194
+
195
+ def add_constraint(self, constraint: Callable):
196
+ """
197
+ Adds a constraint into the current list of constraints.
198
+ """
199
+ self.constraints.append(constraint)
200
+ self._validated = False
201
+
202
+ def validate_constraints(self):
203
+ """
204
+ Validates that current pass schedule defined by `self.passes` is valid
205
+ according to all constraints in `self.constraints`
206
+ """
207
+ if self._validated:
208
+ return
209
+ for constraint in self.constraints:
210
+ _validate_pass_schedule_constraint(constraint, self.passes)
211
+ self._validated = True
212
+
213
+ def solve_constraints(self):
214
+ """
215
+ Finds a valid traversal order based on the given constraints and orders
216
+ the passes based on this order.
217
+
218
+ If a circular dependency exists between the constraints and steps = 1,
219
+ then we will raise an error because if steps != 1 this means that we
220
+ will re-run the passes, allowing for circular dependencies.
221
+ """
222
+ self.passes = _topological_sort_passes(self.passes, self.constraints)
223
+ self._validated = True
224
+
225
+ def add_checks(self, check: Callable) -> None:
226
+ """
227
+ Adds a function which takes runs various checks on a given graph module.
228
+ This function is run before and after each pass if the
229
+ `run_checks_after_each_pass` flag is enabled.
230
+ """
231
+ sig = inspect.signature(check)
232
+
233
+ if len(list(sig.parameters.values())) != 1:
234
+ raise TypeError("PassManager check function should only take in one variable, a module")
235
+
236
+ setattr(self, "check", check) # noqa: B010
237
+
238
+ def check(self, module: nn.Module) -> None:
239
+ pass
240
+
241
+ def __call__(self, module: nn.Module) -> PassResult:
242
+ """
243
+ Runs a list of passes in the order based on `self.passes` on the given
244
+ graph module. Each time a pass is run, checks and linting will be run on
245
+ the graph module if `run_checks_after_each_pass` is set.
246
+
247
+ If the module is a graph module, we will run the list of passes until
248
+ the graph stops changing, or until `steps` number of times.
249
+ """
250
+ # Order the passes based on the constraints
251
+ if not self._validated:
252
+ self.solve_constraints()
253
+
254
+ # Check graph invariants
255
+ self.check(module)
256
+
257
+ # Run the set of passes `steps` number of times or until the graph stops
258
+ # changing
259
+ overall_modified = False
260
+ for _ in range(self.steps):
261
+ modified = False
262
+
263
+ # Run the set of passes on the graph module
264
+ for i, fn in enumerate(self.passes):
265
+ fn_name = fn.__name__ if inspect.isfunction(fn) else type(fn).__name__
266
+ logger.debug("Running pass '%s'", fn_name)
267
+
268
+ try:
269
+ res = fn(module)
270
+
271
+ if not isinstance(res, PassResult) and not hasattr(
272
+ res, "graph_module"
273
+ ):
274
+ raise TypeError(
275
+ f"The result of the pass {fn_name} should be type PassResult."
276
+ + "Please wrap it with pass_result_wrapper()"
277
+ )
278
+ module = res.graph_module
279
+ modified = modified or res.modified
280
+
281
+ if isinstance(module, GraphModule):
282
+ logger.debug("Graph after pass '%s': %s", fn_name, module.graph)
283
+ module.recompile()
284
+
285
+ # Check graph invariants
286
+ if self.run_checks_after_each_pass:
287
+ self.check(module)
288
+
289
+ except Exception as e:
290
+ prev_pass_names = [
291
+ p.__name__ if inspect.isfunction(p) else type(p).__name__
292
+ for p in self.passes[:i]
293
+ ]
294
+ msg = f"An error occurred when running the '{fn_name}' pass after the following passes: {prev_pass_names}"
295
+ raise Exception(msg) from e # noqa: TRY002
296
+
297
+ # If the graph no longer changes, then we can stop running these passes
298
+ overall_modified = overall_modified or modified
299
+ if not modified:
300
+ break
301
+
302
+ return PassResult(module, overall_modified)