ZTWHHH commited on
Commit
080a04a
·
verified ·
1 Parent(s): a9b49d7

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 +6 -0
  2. llava_next/lib/python3.10/site-packages/et_xmlfile/__init__.py +8 -0
  3. llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/incremental_tree.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/et_xmlfile/incremental_tree.py +917 -0
  7. llava_next/lib/python3.10/site-packages/et_xmlfile/xmlfile.py +158 -0
  8. llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/__init__.py +14 -0
  9. llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/axes_grid.py +23 -0
  10. llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/floating_axes.py +286 -0
  11. llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/RECORD +22 -0
  12. llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/WHEEL +6 -0
  13. llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/top_level.txt +1 -0
  14. llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/zip-safe +1 -0
  15. llava_next/lib/python3.10/site-packages/sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-310.pyc +3 -0
  16. llava_next/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc +3 -0
  17. llava_next/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc +3 -0
  18. llava_next/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc +3 -0
  19. vlmpy310/lib/python3.10/site-packages/torch/__pycache__/library.cpython-310.pyc +0 -0
  20. vlmpy310/lib/python3.10/site-packages/torch/_inductor/__init__.py +142 -0
  21. vlmpy310/lib/python3.10/site-packages/torch/_inductor/autotune_process.py +616 -0
  22. vlmpy310/lib/python3.10/site-packages/torch/_inductor/bounds.py +122 -0
  23. vlmpy310/lib/python3.10/site-packages/torch/_inductor/codecache.py +2477 -0
  24. vlmpy310/lib/python3.10/site-packages/torch/_inductor/comm_analysis.py +250 -0
  25. vlmpy310/lib/python3.10/site-packages/torch/_inductor/comms.py +365 -0
  26. vlmpy310/lib/python3.10/site-packages/torch/_inductor/compile_fx.py +1302 -0
  27. vlmpy310/lib/python3.10/site-packages/torch/_inductor/config.py +664 -0
  28. vlmpy310/lib/python3.10/site-packages/torch/_inductor/constant_folding.py +190 -0
  29. vlmpy310/lib/python3.10/site-packages/torch/_inductor/coordinate_descent_tuner.py +315 -0
  30. vlmpy310/lib/python3.10/site-packages/torch/_inductor/cudagraph_trees.py +2157 -0
  31. vlmpy310/lib/python3.10/site-packages/torch/_inductor/debug.py +561 -0
  32. vlmpy310/lib/python3.10/site-packages/torch/_inductor/decomposition.py +613 -0
  33. vlmpy310/lib/python3.10/site-packages/torch/_inductor/dependencies.py +444 -0
  34. vlmpy310/lib/python3.10/site-packages/torch/_inductor/exc.py +98 -0
  35. vlmpy310/lib/python3.10/site-packages/torch/_inductor/freezing.py +266 -0
  36. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__init__.py +0 -0
  37. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-310.pyc +0 -0
  39. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-310.pyc +0 -0
  40. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-310.pyc +0 -0
  41. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/replace_random.cpython-310.pyc +0 -0
  42. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/binary_folding.py +277 -0
  43. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/efficient_conv_bn_eval.py +157 -0
  44. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/freezing_patterns.py +212 -0
  45. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/fuse_attention.py +564 -0
  46. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/group_batch_fusion.py +791 -0
  47. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/joint_graph.py +323 -0
  48. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/misc_patterns.py +130 -0
  49. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/mkldnn_fusion.py +1085 -0
  50. vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/pad_mm.py +469 -0
.gitattributes CHANGED
@@ -1168,3 +1168,9 @@ vlmpy310/lib/python3.10/site-packages/babel/locale-data/zh_Hant.dat filter=lfs d
1168
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/so.dat filter=lfs diff=lfs merge=lfs -text
1169
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/bn.dat filter=lfs diff=lfs merge=lfs -text
1170
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/gu.dat filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
1168
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/so.dat filter=lfs diff=lfs merge=lfs -text
1169
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/bn.dat filter=lfs diff=lfs merge=lfs -text
1170
  vlmpy310/lib/python3.10/site-packages/babel/locale-data/gu.dat filter=lfs diff=lfs merge=lfs -text
1171
+ vlmpy310/lib/python3.10/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1172
+ vlmpy310/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1173
+ llava_next/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1174
+ llava_next/lib/python3.10/site-packages/sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1175
+ llava_next/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1176
+ llava_next/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/et_xmlfile/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .xmlfile import xmlfile
2
+
3
+ # constants
4
+ __version__ = '2.0.0'
5
+ __author__ = 'See AUTHORS.txt'
6
+ __license__ = 'MIT'
7
+ __author_email__ = 'charlie.clark@clark-consulting.eu'
8
+ __url__ = 'https://foss.heptapod.net/openpyxl/et_xmlfile'
llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (402 Bytes). View file
 
llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/incremental_tree.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
llava_next/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
llava_next/lib/python3.10/site-packages/et_xmlfile/incremental_tree.py ADDED
@@ -0,0 +1,917 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code modified from cPython's Lib/xml/etree/ElementTree.py
2
+ # The write() code is modified to allow specifying a particular namespace
3
+ # uri -> prefix mapping.
4
+ #
5
+ # ---------------------------------------------------------------------
6
+ # Licensed to PSF under a Contributor Agreement.
7
+ # See https://www.python.org/psf/license for licensing details.
8
+ #
9
+ # ElementTree
10
+ # Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
11
+ #
12
+ # fredrik@pythonware.com
13
+ # http://www.pythonware.com
14
+ # --------------------------------------------------------------------
15
+ # The ElementTree toolkit is
16
+ #
17
+ # Copyright (c) 1999-2008 by Fredrik Lundh
18
+ #
19
+ # By obtaining, using, and/or copying this software and/or its
20
+ # associated documentation, you agree that you have read, understood,
21
+ # and will comply with the following terms and conditions:
22
+ #
23
+ # Permission to use, copy, modify, and distribute this software and
24
+ # its associated documentation for any purpose and without fee is
25
+ # hereby granted, provided that the above copyright notice appears in
26
+ # all copies, and that both that copyright notice and this permission
27
+ # notice appear in supporting documentation, and that the name of
28
+ # Secret Labs AB or the author not be used in advertising or publicity
29
+ # pertaining to distribution of the software without specific, written
30
+ # prior permission.
31
+ #
32
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
33
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
34
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
35
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
36
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
37
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
38
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
39
+ # OF THIS SOFTWARE.
40
+ # --------------------------------------------------------------------
41
+ import contextlib
42
+ import io
43
+
44
+ import xml.etree.ElementTree as ET
45
+
46
+
47
+ def current_global_nsmap():
48
+ return {
49
+ prefix: uri for uri, prefix in ET._namespace_map.items()
50
+ }
51
+
52
+
53
+ class IncrementalTree(ET.ElementTree):
54
+
55
+ def write(
56
+ self,
57
+ file_or_filename,
58
+ encoding=None,
59
+ xml_declaration=None,
60
+ default_namespace=None,
61
+ method=None,
62
+ *,
63
+ short_empty_elements=True,
64
+ nsmap=None,
65
+ root_ns_only=False,
66
+ minimal_ns_only=False,
67
+ ):
68
+ """Write element tree to a file as XML.
69
+
70
+ Arguments:
71
+ *file_or_filename* -- file name or a file object opened for writing
72
+
73
+ *encoding* -- the output encoding (default: US-ASCII)
74
+
75
+ *xml_declaration* -- bool indicating if an XML declaration should be
76
+ added to the output. If None, an XML declaration
77
+ is added if encoding IS NOT either of:
78
+ US-ASCII, UTF-8, or Unicode
79
+
80
+ *default_namespace* -- sets the default XML namespace (for "xmlns").
81
+ Takes precedence over any default namespace
82
+ provided in nsmap or
83
+ xml.etree.ElementTree.register_namespace().
84
+
85
+ *method* -- either "xml" (default), "html, "text", or "c14n"
86
+
87
+ *short_empty_elements* -- controls the formatting of elements
88
+ that contain no content. If True (default)
89
+ they are emitted as a single self-closed
90
+ tag, otherwise they are emitted as a pair
91
+ of start/end tags
92
+
93
+ *nsmap* -- a mapping of namespace prefixes to URIs. These take
94
+ precedence over any mappings registered using
95
+ xml.etree.ElementTree.register_namespace(). The
96
+ default_namespace argument, if supplied, takes precedence
97
+ over any default namespace supplied in nsmap. All supplied
98
+ namespaces will be declared on the root element, even if
99
+ unused in the document.
100
+
101
+ *root_ns_only* -- bool indicating namespace declrations should only
102
+ be written on the root element. This requires two
103
+ passes of the xml tree adding additional time to
104
+ the writing process. This is primarily meant to
105
+ mimic xml.etree.ElementTree's behaviour.
106
+
107
+ *minimal_ns_only* -- bool indicating only namespaces that were used
108
+ to qualify elements or attributes should be
109
+ declared. All namespace declarations will be
110
+ written on the root element regardless of the
111
+ value of the root_ns_only arg. Requires two
112
+ passes of the xml tree adding additional time to
113
+ the writing process.
114
+
115
+ """
116
+ if not method:
117
+ method = "xml"
118
+ elif method not in ("text", "xml", "html"):
119
+ raise ValueError("unknown method %r" % method)
120
+ if not encoding:
121
+ encoding = "us-ascii"
122
+
123
+ with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
124
+ if method == "xml" and (
125
+ xml_declaration
126
+ or (
127
+ xml_declaration is None
128
+ and encoding.lower() != "unicode"
129
+ and declared_encoding.lower() not in ("utf-8", "us-ascii")
130
+ )
131
+ ):
132
+ write("<?xml version='1.0' encoding='%s'?>\n" % (declared_encoding,))
133
+ if method == "text":
134
+ ET._serialize_text(write, self._root)
135
+ else:
136
+ if method == "xml":
137
+ is_html = False
138
+ else:
139
+ is_html = True
140
+ if nsmap:
141
+ if None in nsmap:
142
+ raise ValueError(
143
+ 'Found None as default nsmap prefix in nsmap. '
144
+ 'Use "" as the default namespace prefix.'
145
+ )
146
+ new_nsmap = nsmap.copy()
147
+ else:
148
+ new_nsmap = {}
149
+ if default_namespace:
150
+ new_nsmap[""] = default_namespace
151
+ if root_ns_only or minimal_ns_only:
152
+ # _namespaces returns a mapping of only the namespaces that
153
+ # were used.
154
+ new_nsmap = _namespaces(
155
+ self._root,
156
+ default_namespace,
157
+ new_nsmap,
158
+ )
159
+ if not minimal_ns_only:
160
+ if nsmap:
161
+ # We want all namespaces defined in the provided
162
+ # nsmap to be declared regardless of whether
163
+ # they've been used.
164
+ new_nsmap.update(nsmap)
165
+ if default_namespace:
166
+ new_nsmap[""] = default_namespace
167
+ global_nsmap = {
168
+ prefix: uri for uri, prefix in ET._namespace_map.items()
169
+ }
170
+ if None in global_nsmap:
171
+ raise ValueError(
172
+ 'Found None as default nsmap prefix in nsmap registered with '
173
+ 'register_namespace. Use "" for the default namespace prefix.'
174
+ )
175
+ nsmap_scope = {}
176
+ _serialize_ns_xml(
177
+ write,
178
+ self._root,
179
+ nsmap_scope,
180
+ global_nsmap,
181
+ is_html=is_html,
182
+ is_root=True,
183
+ short_empty_elements=short_empty_elements,
184
+ new_nsmap=new_nsmap,
185
+ )
186
+
187
+
188
+ def _make_new_ns_prefix(
189
+ nsmap_scope,
190
+ global_prefixes,
191
+ local_nsmap=None,
192
+ default_namespace=None,
193
+ ):
194
+ i = len(nsmap_scope)
195
+ if default_namespace is not None and "" not in nsmap_scope:
196
+ # Keep the same numbering scheme as python which assumes the default
197
+ # namespace is present if supplied.
198
+ i += 1
199
+
200
+ while True:
201
+ prefix = f"ns{i}"
202
+ if (
203
+ prefix not in nsmap_scope
204
+ and prefix not in global_prefixes
205
+ and (
206
+ not local_nsmap or prefix not in local_nsmap
207
+ )
208
+ ):
209
+ return prefix
210
+ i += 1
211
+
212
+
213
+ def _get_or_create_prefix(
214
+ uri,
215
+ nsmap_scope,
216
+ global_nsmap,
217
+ new_namespace_prefixes,
218
+ uri_to_prefix,
219
+ for_default_namespace_attr_prefix=False,
220
+ ):
221
+ """Find a prefix that doesn't conflict with the ns scope or create a new prefix
222
+
223
+ This function mutates nsmap_scope, global_nsmap, new_namespace_prefixes and
224
+ uri_to_prefix. It is intended to keep state in _serialize_ns_xml consistent
225
+ while deduplicating the house keeping code or updating these dictionaries.
226
+ """
227
+ # Check if we can reuse an existing (global) prefix within the current
228
+ # namespace scope. There maybe many prefixes pointing to a single URI by
229
+ # this point and we need to select a prefix that is not in use in the
230
+ # current scope.
231
+ for global_prefix, global_uri in global_nsmap.items():
232
+ if uri == global_uri and global_prefix not in nsmap_scope:
233
+ prefix = global_prefix
234
+ break
235
+ else: # no break
236
+ # We couldn't find a suitable existing prefix for this namespace scope,
237
+ # let's create a new one.
238
+ prefix = _make_new_ns_prefix(nsmap_scope, global_prefixes=global_nsmap)
239
+ global_nsmap[prefix] = uri
240
+ nsmap_scope[prefix] = uri
241
+ if not for_default_namespace_attr_prefix:
242
+ # Don't override the actual default namespace prefix
243
+ uri_to_prefix[uri] = prefix
244
+ if prefix != "xml":
245
+ new_namespace_prefixes.add(prefix)
246
+ return prefix
247
+
248
+
249
+ def _find_default_namespace_attr_prefix(
250
+ default_namespace,
251
+ nsmap,
252
+ local_nsmap,
253
+ global_prefixes,
254
+ provided_default_namespace=None,
255
+ ):
256
+ # Search the provided nsmap for any prefixes for this uri that aren't the
257
+ # default namespace ""
258
+ for prefix, uri in nsmap.items():
259
+ if uri == default_namespace and prefix != "":
260
+ return prefix
261
+
262
+ for prefix, uri in local_nsmap.items():
263
+ if uri == default_namespace and prefix != "":
264
+ return prefix
265
+
266
+ # _namespace_map is a 1:1 mapping of uri -> prefix
267
+ prefix = ET._namespace_map.get(default_namespace)
268
+ if prefix and prefix not in nsmap:
269
+ return prefix
270
+
271
+ return _make_new_ns_prefix(
272
+ nsmap,
273
+ global_prefixes,
274
+ local_nsmap,
275
+ provided_default_namespace,
276
+ )
277
+
278
+
279
+ def process_attribs(
280
+ elem,
281
+ is_nsmap_scope_changed,
282
+ default_ns_attr_prefix,
283
+ nsmap_scope,
284
+ global_nsmap,
285
+ new_namespace_prefixes,
286
+ uri_to_prefix,
287
+ ):
288
+ item_parts = []
289
+ for k, v in elem.items():
290
+ if isinstance(k, ET.QName):
291
+ k = k.text
292
+ try:
293
+ if k[:1] == "{":
294
+ uri_and_name = k[1:].rsplit("}", 1)
295
+ try:
296
+ prefix = uri_to_prefix[uri_and_name[0]]
297
+ except KeyError:
298
+ if not is_nsmap_scope_changed:
299
+ # We're about to mutate the these dicts so
300
+ # let's copy them first. We don't have to
301
+ # recompute other mappings as we're looking up
302
+ # or creating a new prefix
303
+ nsmap_scope = nsmap_scope.copy()
304
+ uri_to_prefix = uri_to_prefix.copy()
305
+ is_nsmap_scope_changed = True
306
+ prefix = _get_or_create_prefix(
307
+ uri_and_name[0],
308
+ nsmap_scope,
309
+ global_nsmap,
310
+ new_namespace_prefixes,
311
+ uri_to_prefix,
312
+ )
313
+
314
+ if not prefix:
315
+ if default_ns_attr_prefix:
316
+ prefix = default_ns_attr_prefix
317
+ else:
318
+ for prefix, known_uri in nsmap_scope.items():
319
+ if known_uri == uri_and_name[0] and prefix != "":
320
+ default_ns_attr_prefix = prefix
321
+ break
322
+ else: # no break
323
+ if not is_nsmap_scope_changed:
324
+ # We're about to mutate the these dicts so
325
+ # let's copy them first. We don't have to
326
+ # recompute other mappings as we're looking up
327
+ # or creating a new prefix
328
+ nsmap_scope = nsmap_scope.copy()
329
+ uri_to_prefix = uri_to_prefix.copy()
330
+ is_nsmap_scope_changed = True
331
+ prefix = _get_or_create_prefix(
332
+ uri_and_name[0],
333
+ nsmap_scope,
334
+ global_nsmap,
335
+ new_namespace_prefixes,
336
+ uri_to_prefix,
337
+ for_default_namespace_attr_prefix=True,
338
+ )
339
+ default_ns_attr_prefix = prefix
340
+ k = f"{prefix}:{uri_and_name[1]}"
341
+ except TypeError:
342
+ ET._raise_serialization_error(k)
343
+
344
+ if isinstance(v, ET.QName):
345
+ if v.text[:1] != "{":
346
+ v = v.text
347
+ else:
348
+ uri_and_name = v.text[1:].rsplit("}", 1)
349
+ try:
350
+ prefix = uri_to_prefix[uri_and_name[0]]
351
+ except KeyError:
352
+ if not is_nsmap_scope_changed:
353
+ # We're about to mutate the these dicts so
354
+ # let's copy them first. We don't have to
355
+ # recompute other mappings as we're looking up
356
+ # or creating a new prefix
357
+ nsmap_scope = nsmap_scope.copy()
358
+ uri_to_prefix = uri_to_prefix.copy()
359
+ is_nsmap_scope_changed = True
360
+ prefix = _get_or_create_prefix(
361
+ uri_and_name[0],
362
+ nsmap_scope,
363
+ global_nsmap,
364
+ new_namespace_prefixes,
365
+ uri_to_prefix,
366
+ )
367
+ v = f"{prefix}:{uri_and_name[1]}"
368
+ item_parts.append((k, v))
369
+ return item_parts, default_ns_attr_prefix, nsmap_scope
370
+
371
+
372
+ def write_elem_start(
373
+ write,
374
+ elem,
375
+ nsmap_scope,
376
+ global_nsmap,
377
+ short_empty_elements,
378
+ is_html,
379
+ is_root=False,
380
+ uri_to_prefix=None,
381
+ default_ns_attr_prefix=None,
382
+ new_nsmap=None,
383
+ **kwargs,
384
+ ):
385
+ """Write the opening tag (including self closing) and element text.
386
+
387
+ Refer to _serialize_ns_xml for description of arguments.
388
+
389
+ nsmap_scope should be an empty dictionary on first call. All nsmap prefixes
390
+ must be strings with the default namespace prefix represented by "".
391
+
392
+ eg.
393
+ - <foo attr1="one"> (returns tag = 'foo')
394
+ - <foo attr1="one">text (returns tag = 'foo')
395
+ - <foo attr1="one" /> (returns tag = None)
396
+
397
+ Returns:
398
+ tag:
399
+ The tag name to be closed or None if no closing required.
400
+ nsmap_scope:
401
+ The current nsmap after any prefix to uri additions from this
402
+ element. This is the input dict if unmodified or an updated copy.
403
+ default_ns_attr_prefix:
404
+ The prefix for the default namespace to use with attrs.
405
+ uri_to_prefix:
406
+ The current uri to prefix map after any uri to prefix additions
407
+ from this element. This is the input dict if unmodified or an
408
+ updated copy.
409
+ next_remains_root:
410
+ A bool indicating if the child element(s) should be treated as
411
+ their own roots.
412
+ """
413
+ tag = elem.tag
414
+ text = elem.text
415
+
416
+ if tag is ET.Comment:
417
+ write("<!--%s-->" % text)
418
+ tag = None
419
+ next_remains_root = False
420
+ elif tag is ET.ProcessingInstruction:
421
+ write("<?%s?>" % text)
422
+ tag = None
423
+ next_remains_root = False
424
+ else:
425
+ if new_nsmap:
426
+ is_nsmap_scope_changed = True
427
+ nsmap_scope = nsmap_scope.copy()
428
+ nsmap_scope.update(new_nsmap)
429
+ new_namespace_prefixes = set(new_nsmap.keys())
430
+ new_namespace_prefixes.discard("xml")
431
+ # We need to recompute the uri to prefixes
432
+ uri_to_prefix = None
433
+ default_ns_attr_prefix = None
434
+ else:
435
+ is_nsmap_scope_changed = False
436
+ new_namespace_prefixes = set()
437
+
438
+ if uri_to_prefix is None:
439
+ if None in nsmap_scope:
440
+ raise ValueError(
441
+ 'Found None as a namespace prefix. Use "" as the default namespace prefix.'
442
+ )
443
+ uri_to_prefix = {uri: prefix for prefix, uri in nsmap_scope.items()}
444
+ if "" in nsmap_scope:
445
+ # There may be multiple prefixes for the default namespace but
446
+ # we want to make sure we preferentially use "" (for elements)
447
+ uri_to_prefix[nsmap_scope[""]] = ""
448
+
449
+ if tag is None:
450
+ # tag supression where tag is set to None
451
+ # Don't change is_root so namespaces can be passed down
452
+ next_remains_root = is_root
453
+ if text:
454
+ write(ET._escape_cdata(text))
455
+ else:
456
+ next_remains_root = False
457
+ if isinstance(tag, ET.QName):
458
+ tag = tag.text
459
+ try:
460
+ # These splits / fully qualified tag creationg are the
461
+ # bottleneck in this implementation vs the python
462
+ # implementation.
463
+ # The following split takes ~42ns with no uri and ~85ns if a
464
+ # prefix is present. If the uri was present, we then need to
465
+ # look up a prefix (~14ns) and create the fully qualified
466
+ # string (~41ns). This gives a total of ~140ns where a uri is
467
+ # present.
468
+ # Python's implementation needs to preprocess the tree to
469
+ # create a dict of qname -> tag by traversing the tree which
470
+ # takes a bit of extra time but it quickly makes that back by
471
+ # only having to do a dictionary look up (~14ns) for each tag /
472
+ # attrname vs our splitting (~140ns).
473
+ # So here we have the flexibility of being able to redefine the
474
+ # uri a prefix points to midway through serialisation at the
475
+ # expense of performance (~10% slower for a 1mb file on my
476
+ # machine).
477
+ if tag[:1] == "{":
478
+ uri_and_name = tag[1:].rsplit("}", 1)
479
+ try:
480
+ prefix = uri_to_prefix[uri_and_name[0]]
481
+ except KeyError:
482
+ if not is_nsmap_scope_changed:
483
+ # We're about to mutate the these dicts so let's
484
+ # copy them first. We don't have to recompute other
485
+ # mappings as we're looking up or creating a new
486
+ # prefix
487
+ nsmap_scope = nsmap_scope.copy()
488
+ uri_to_prefix = uri_to_prefix.copy()
489
+ is_nsmap_scope_changed = True
490
+ prefix = _get_or_create_prefix(
491
+ uri_and_name[0],
492
+ nsmap_scope,
493
+ global_nsmap,
494
+ new_namespace_prefixes,
495
+ uri_to_prefix,
496
+ )
497
+ if prefix:
498
+ tag = f"{prefix}:{uri_and_name[1]}"
499
+ else:
500
+ tag = uri_and_name[1]
501
+ elif "" in nsmap_scope:
502
+ raise ValueError(
503
+ "cannot use non-qualified names with default_namespace option"
504
+ )
505
+ except TypeError:
506
+ ET._raise_serialization_error(tag)
507
+
508
+ write("<" + tag)
509
+
510
+ if elem.attrib:
511
+ item_parts, default_ns_attr_prefix, nsmap_scope = process_attribs(
512
+ elem,
513
+ is_nsmap_scope_changed,
514
+ default_ns_attr_prefix,
515
+ nsmap_scope,
516
+ global_nsmap,
517
+ new_namespace_prefixes,
518
+ uri_to_prefix,
519
+ )
520
+ else:
521
+ item_parts = []
522
+ if new_namespace_prefixes:
523
+ ns_attrs = []
524
+ for k in sorted(new_namespace_prefixes):
525
+ v = nsmap_scope[k]
526
+ if k:
527
+ k = "xmlns:" + k
528
+ else:
529
+ k = "xmlns"
530
+ ns_attrs.append((k, v))
531
+ if is_html:
532
+ write("".join([f' {k}="{ET._escape_attrib_html(v)}"' for k, v in ns_attrs]))
533
+ else:
534
+ write("".join([f' {k}="{ET._escape_attrib(v)}"' for k, v in ns_attrs]))
535
+ if item_parts:
536
+ if is_html:
537
+ write("".join([f' {k}="{ET._escape_attrib_html(v)}"' for k, v in item_parts]))
538
+ else:
539
+ write("".join([f' {k}="{ET._escape_attrib(v)}"' for k, v in item_parts]))
540
+ if is_html:
541
+ write(">")
542
+ ltag = tag.lower()
543
+ if text:
544
+ if ltag == "script" or ltag == "style":
545
+ write(text)
546
+ else:
547
+ write(ET._escape_cdata(text))
548
+ if ltag in ET.HTML_EMPTY:
549
+ tag = None
550
+ elif text or len(elem) or not short_empty_elements:
551
+ write(">")
552
+ if text:
553
+ write(ET._escape_cdata(text))
554
+ else:
555
+ tag = None
556
+ write(" />")
557
+ return (
558
+ tag,
559
+ nsmap_scope,
560
+ default_ns_attr_prefix,
561
+ uri_to_prefix,
562
+ next_remains_root,
563
+ )
564
+
565
+
566
+ def _serialize_ns_xml(
567
+ write,
568
+ elem,
569
+ nsmap_scope,
570
+ global_nsmap,
571
+ short_empty_elements,
572
+ is_html,
573
+ is_root=False,
574
+ uri_to_prefix=None,
575
+ default_ns_attr_prefix=None,
576
+ new_nsmap=None,
577
+ **kwargs,
578
+ ):
579
+ """Serialize an element or tree using 'write' for output.
580
+
581
+ Args:
582
+ write:
583
+ A function to write the xml to its destination.
584
+ elem:
585
+ The element to serialize.
586
+ nsmap_scope:
587
+ The current prefix to uri mapping for this element. This should be
588
+ an empty dictionary for the root element. Additional namespaces are
589
+ progressively added using the new_nsmap arg.
590
+ global_nsmap:
591
+ A dict copy of the globally registered _namespace_map in uri to
592
+ prefix form
593
+ short_empty_elements:
594
+ Controls the formatting of elements that contain no content. If True
595
+ (default) they are emitted as a single self-closed tag, otherwise
596
+ they are emitted as a pair of start/end tags.
597
+ is_html:
598
+ Set to True to serialize as HTML otherwise XML.
599
+ is_root:
600
+ Boolean indicating if this is a root element.
601
+ uri_to_prefix:
602
+ Current state of the mapping of uri to prefix.
603
+ default_ns_attr_prefix:
604
+ new_nsmap:
605
+ New prefix -> uri mapping to be applied to this element.
606
+ """
607
+ (
608
+ tag,
609
+ nsmap_scope,
610
+ default_ns_attr_prefix,
611
+ uri_to_prefix,
612
+ next_remains_root,
613
+ ) = write_elem_start(
614
+ write,
615
+ elem,
616
+ nsmap_scope,
617
+ global_nsmap,
618
+ short_empty_elements,
619
+ is_html,
620
+ is_root,
621
+ uri_to_prefix,
622
+ default_ns_attr_prefix,
623
+ new_nsmap=new_nsmap,
624
+ )
625
+ for e in elem:
626
+ _serialize_ns_xml(
627
+ write,
628
+ e,
629
+ nsmap_scope,
630
+ global_nsmap,
631
+ short_empty_elements,
632
+ is_html,
633
+ next_remains_root,
634
+ uri_to_prefix,
635
+ default_ns_attr_prefix,
636
+ new_nsmap=None,
637
+ )
638
+ if tag:
639
+ write(f"</{tag}>")
640
+ if elem.tail:
641
+ write(ET._escape_cdata(elem.tail))
642
+
643
+
644
+ def _qnames_iter(elem):
645
+ """Iterate through all the qualified names in elem"""
646
+ seen_el_qnames = set()
647
+ seen_other_qnames = set()
648
+ for this_elem in elem.iter():
649
+ tag = this_elem.tag
650
+ if isinstance(tag, str):
651
+ if tag not in seen_el_qnames:
652
+ seen_el_qnames.add(tag)
653
+ yield tag, True
654
+ elif isinstance(tag, ET.QName):
655
+ tag = tag.text
656
+ if tag not in seen_el_qnames:
657
+ seen_el_qnames.add(tag)
658
+ yield tag, True
659
+ elif (
660
+ tag is not None
661
+ and tag is not ET.ProcessingInstruction
662
+ and tag is not ET.Comment
663
+ ):
664
+ ET._raise_serialization_error(tag)
665
+
666
+ for key, value in this_elem.items():
667
+ if isinstance(key, ET.QName):
668
+ key = key.text
669
+ if key not in seen_other_qnames:
670
+ seen_other_qnames.add(key)
671
+ yield key, False
672
+
673
+ if isinstance(value, ET.QName):
674
+ if value.text not in seen_other_qnames:
675
+ seen_other_qnames.add(value.text)
676
+ yield value.text, False
677
+
678
+ text = this_elem.text
679
+ if isinstance(text, ET.QName):
680
+ if text.text not in seen_other_qnames:
681
+ seen_other_qnames.add(text.text)
682
+ yield text.text, False
683
+
684
+
685
+ def _namespaces(
686
+ elem,
687
+ default_namespace=None,
688
+ nsmap=None,
689
+ ):
690
+ """Find all namespaces used in the document and return a prefix to uri map"""
691
+ if nsmap is None:
692
+ nsmap = {}
693
+
694
+ out_nsmap = {}
695
+
696
+ seen_uri_to_prefix = {}
697
+ # Multiple prefixes may be present for a single uri. This will select the
698
+ # last prefix found in nsmap for a given uri.
699
+ local_prefix_map = {uri: prefix for prefix, uri in nsmap.items()}
700
+ if default_namespace is not None:
701
+ local_prefix_map[default_namespace] = ""
702
+ elif "" in nsmap:
703
+ # but we make sure the default prefix always take precedence
704
+ local_prefix_map[nsmap[""]] = ""
705
+
706
+ global_prefixes = set(ET._namespace_map.values())
707
+ has_unqual_el = False
708
+ default_namespace_attr_prefix = None
709
+ for qname, is_el in _qnames_iter(elem):
710
+ try:
711
+ if qname[:1] == "{":
712
+ uri_and_name = qname[1:].rsplit("}", 1)
713
+
714
+ prefix = seen_uri_to_prefix.get(uri_and_name[0])
715
+ if prefix is None:
716
+ prefix = local_prefix_map.get(uri_and_name[0])
717
+ if prefix is None or prefix in out_nsmap:
718
+ prefix = ET._namespace_map.get(uri_and_name[0])
719
+ if prefix is None or prefix in out_nsmap:
720
+ prefix = _make_new_ns_prefix(
721
+ out_nsmap,
722
+ global_prefixes,
723
+ nsmap,
724
+ default_namespace,
725
+ )
726
+ if prefix or is_el:
727
+ out_nsmap[prefix] = uri_and_name[0]
728
+ seen_uri_to_prefix[uri_and_name[0]] = prefix
729
+
730
+ if not is_el and not prefix and not default_namespace_attr_prefix:
731
+ # Find the alternative prefix to use with non-element
732
+ # names
733
+ default_namespace_attr_prefix = _find_default_namespace_attr_prefix(
734
+ uri_and_name[0],
735
+ out_nsmap,
736
+ nsmap,
737
+ global_prefixes,
738
+ default_namespace,
739
+ )
740
+ out_nsmap[default_namespace_attr_prefix] = uri_and_name[0]
741
+ # Don't add this uri to prefix mapping as it might override
742
+ # the uri -> "" default mapping. We'll fix this up at the
743
+ # end of the fn.
744
+ # local_prefix_map[uri_and_name[0]] = default_namespace_attr_prefix
745
+ else:
746
+ if is_el:
747
+ has_unqual_el = True
748
+ except TypeError:
749
+ ET._raise_serialization_error(qname)
750
+
751
+ if "" in out_nsmap and has_unqual_el:
752
+ # FIXME: can this be handled in XML 1.0?
753
+ raise ValueError(
754
+ "cannot use non-qualified names with default_namespace option"
755
+ )
756
+
757
+ # The xml prefix doesn't need to be declared but may have been used to
758
+ # prefix names. Let's remove it if it has been used
759
+ out_nsmap.pop("xml", None)
760
+ return out_nsmap
761
+
762
+
763
+ def tostring(
764
+ element,
765
+ encoding=None,
766
+ method=None,
767
+ *,
768
+ xml_declaration=None,
769
+ default_namespace=None,
770
+ short_empty_elements=True,
771
+ nsmap=None,
772
+ root_ns_only=False,
773
+ minimal_ns_only=False,
774
+ tree_cls=IncrementalTree,
775
+ ):
776
+ """Generate string representation of XML element.
777
+
778
+ All subelements are included. If encoding is "unicode", a string
779
+ is returned. Otherwise a bytestring is returned.
780
+
781
+ *element* is an Element instance, *encoding* is an optional output
782
+ encoding defaulting to US-ASCII, *method* is an optional output which can
783
+ be one of "xml" (default), "html", "text" or "c14n", *default_namespace*
784
+ sets the default XML namespace (for "xmlns").
785
+
786
+ Returns an (optionally) encoded string containing the XML data.
787
+
788
+ """
789
+ stream = io.StringIO() if encoding == "unicode" else io.BytesIO()
790
+ tree_cls(element).write(
791
+ stream,
792
+ encoding,
793
+ xml_declaration=xml_declaration,
794
+ default_namespace=default_namespace,
795
+ method=method,
796
+ short_empty_elements=short_empty_elements,
797
+ nsmap=nsmap,
798
+ root_ns_only=root_ns_only,
799
+ minimal_ns_only=minimal_ns_only,
800
+ )
801
+ return stream.getvalue()
802
+
803
+
804
+ def tostringlist(
805
+ element,
806
+ encoding=None,
807
+ method=None,
808
+ *,
809
+ xml_declaration=None,
810
+ default_namespace=None,
811
+ short_empty_elements=True,
812
+ nsmap=None,
813
+ root_ns_only=False,
814
+ minimal_ns_only=False,
815
+ tree_cls=IncrementalTree,
816
+ ):
817
+ lst = []
818
+ stream = ET._ListDataStream(lst)
819
+ tree_cls(element).write(
820
+ stream,
821
+ encoding,
822
+ xml_declaration=xml_declaration,
823
+ default_namespace=default_namespace,
824
+ method=method,
825
+ short_empty_elements=short_empty_elements,
826
+ nsmap=nsmap,
827
+ root_ns_only=root_ns_only,
828
+ minimal_ns_only=minimal_ns_only,
829
+ )
830
+ return lst
831
+
832
+
833
+ def compat_tostring(
834
+ element,
835
+ encoding=None,
836
+ method=None,
837
+ *,
838
+ xml_declaration=None,
839
+ default_namespace=None,
840
+ short_empty_elements=True,
841
+ nsmap=None,
842
+ root_ns_only=True,
843
+ minimal_ns_only=False,
844
+ tree_cls=IncrementalTree,
845
+ ):
846
+ """tostring with options that produce the same results as xml.etree.ElementTree.tostring
847
+
848
+ root_ns_only=True is a bit slower than False as it needs to traverse the
849
+ tree one more time to collect all the namespaces.
850
+ """
851
+ return tostring(
852
+ element,
853
+ encoding=encoding,
854
+ method=method,
855
+ xml_declaration=xml_declaration,
856
+ default_namespace=default_namespace,
857
+ short_empty_elements=short_empty_elements,
858
+ nsmap=nsmap,
859
+ root_ns_only=root_ns_only,
860
+ minimal_ns_only=minimal_ns_only,
861
+ tree_cls=tree_cls,
862
+ )
863
+
864
+
865
+ # --------------------------------------------------------------------
866
+ # serialization support
867
+
868
+ @contextlib.contextmanager
869
+ def _get_writer(file_or_filename, encoding):
870
+ # Copied from Python 3.12
871
+ # returns text write method and release all resources after using
872
+ try:
873
+ write = file_or_filename.write
874
+ except AttributeError:
875
+ # file_or_filename is a file name
876
+ if encoding.lower() == "unicode":
877
+ encoding = "utf-8"
878
+ with open(file_or_filename, "w", encoding=encoding,
879
+ errors="xmlcharrefreplace") as file:
880
+ yield file.write, encoding
881
+ else:
882
+ # file_or_filename is a file-like object
883
+ # encoding determines if it is a text or binary writer
884
+ if encoding.lower() == "unicode":
885
+ # use a text writer as is
886
+ yield write, getattr(file_or_filename, "encoding", None) or "utf-8"
887
+ else:
888
+ # wrap a binary writer with TextIOWrapper
889
+ with contextlib.ExitStack() as stack:
890
+ if isinstance(file_or_filename, io.BufferedIOBase):
891
+ file = file_or_filename
892
+ elif isinstance(file_or_filename, io.RawIOBase):
893
+ file = io.BufferedWriter(file_or_filename)
894
+ # Keep the original file open when the BufferedWriter is
895
+ # destroyed
896
+ stack.callback(file.detach)
897
+ else:
898
+ # This is to handle passed objects that aren't in the
899
+ # IOBase hierarchy, but just have a write method
900
+ file = io.BufferedIOBase()
901
+ file.writable = lambda: True
902
+ file.write = write
903
+ try:
904
+ # TextIOWrapper uses this methods to determine
905
+ # if BOM (for UTF-16, etc) should be added
906
+ file.seekable = file_or_filename.seekable
907
+ file.tell = file_or_filename.tell
908
+ except AttributeError:
909
+ pass
910
+ file = io.TextIOWrapper(file,
911
+ encoding=encoding,
912
+ errors="xmlcharrefreplace",
913
+ newline="\n")
914
+ # Keep the original file open when the TextIOWrapper is
915
+ # destroyed
916
+ stack.callback(file.detach)
917
+ yield file.write, encoding
llava_next/lib/python3.10/site-packages/et_xmlfile/xmlfile.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ # Copyright (c) 2010-2015 openpyxl
3
+
4
+ """Implements the lxml.etree.xmlfile API using the standard library xml.etree"""
5
+
6
+
7
+ from contextlib import contextmanager
8
+
9
+ from xml.etree.ElementTree import (
10
+ Element,
11
+ _escape_cdata,
12
+ )
13
+
14
+ from . import incremental_tree
15
+
16
+
17
+ class LxmlSyntaxError(Exception):
18
+ pass
19
+
20
+
21
+ class _IncrementalFileWriter(object):
22
+ """Replacement for _IncrementalFileWriter of lxml"""
23
+ def __init__(self, output_file):
24
+ self._element_stack = []
25
+ self._file = output_file
26
+ self._have_root = False
27
+ self.global_nsmap = incremental_tree.current_global_nsmap()
28
+ self.is_html = False
29
+
30
+ @contextmanager
31
+ def element(self, tag, attrib=None, nsmap=None, **_extra):
32
+ """Create a new xml element using a context manager."""
33
+ if nsmap and None in nsmap:
34
+ # Normalise None prefix (lxml's default namespace prefix) -> "", as
35
+ # required for incremental_tree
36
+ if "" in nsmap and nsmap[""] != nsmap[None]:
37
+ raise ValueError(
38
+ 'Found None and "" as default nsmap prefixes with different URIs'
39
+ )
40
+ nsmap = nsmap.copy()
41
+ nsmap[""] = nsmap.pop(None)
42
+
43
+ # __enter__ part
44
+ self._have_root = True
45
+ if attrib is None:
46
+ attrib = {}
47
+ elem = Element(tag, attrib=attrib, **_extra)
48
+ elem.text = ''
49
+ elem.tail = ''
50
+ if self._element_stack:
51
+ is_root = False
52
+ (
53
+ nsmap_scope,
54
+ default_ns_attr_prefix,
55
+ uri_to_prefix,
56
+ ) = self._element_stack[-1]
57
+ else:
58
+ is_root = True
59
+ nsmap_scope = {}
60
+ default_ns_attr_prefix = None
61
+ uri_to_prefix = {}
62
+ (
63
+ tag,
64
+ nsmap_scope,
65
+ default_ns_attr_prefix,
66
+ uri_to_prefix,
67
+ next_remains_root,
68
+ ) = incremental_tree.write_elem_start(
69
+ self._file,
70
+ elem,
71
+ nsmap_scope=nsmap_scope,
72
+ global_nsmap=self.global_nsmap,
73
+ short_empty_elements=False,
74
+ is_html=self.is_html,
75
+ is_root=is_root,
76
+ uri_to_prefix=uri_to_prefix,
77
+ default_ns_attr_prefix=default_ns_attr_prefix,
78
+ new_nsmap=nsmap,
79
+ )
80
+ self._element_stack.append(
81
+ (
82
+ nsmap_scope,
83
+ default_ns_attr_prefix,
84
+ uri_to_prefix,
85
+ )
86
+ )
87
+ yield
88
+
89
+ # __exit__ part
90
+ self._element_stack.pop()
91
+ self._file(f"</{tag}>")
92
+ if elem.tail:
93
+ self._file(_escape_cdata(elem.tail))
94
+
95
+ def write(self, arg):
96
+ """Write a string or subelement."""
97
+
98
+ if isinstance(arg, str):
99
+ # it is not allowed to write a string outside of an element
100
+ if not self._element_stack:
101
+ raise LxmlSyntaxError()
102
+ self._file(_escape_cdata(arg))
103
+
104
+ else:
105
+ if not self._element_stack and self._have_root:
106
+ raise LxmlSyntaxError()
107
+
108
+ if self._element_stack:
109
+ is_root = False
110
+ (
111
+ nsmap_scope,
112
+ default_ns_attr_prefix,
113
+ uri_to_prefix,
114
+ ) = self._element_stack[-1]
115
+ else:
116
+ is_root = True
117
+ nsmap_scope = {}
118
+ default_ns_attr_prefix = None
119
+ uri_to_prefix = {}
120
+ incremental_tree._serialize_ns_xml(
121
+ self._file,
122
+ arg,
123
+ nsmap_scope=nsmap_scope,
124
+ global_nsmap=self.global_nsmap,
125
+ short_empty_elements=True,
126
+ is_html=self.is_html,
127
+ is_root=is_root,
128
+ uri_to_prefix=uri_to_prefix,
129
+ default_ns_attr_prefix=default_ns_attr_prefix,
130
+ )
131
+
132
+ def __enter__(self):
133
+ pass
134
+
135
+ def __exit__(self, type, value, traceback):
136
+ # without root the xml document is incomplete
137
+ if not self._have_root:
138
+ raise LxmlSyntaxError()
139
+
140
+
141
+ class xmlfile(object):
142
+ """Context manager that can replace lxml.etree.xmlfile."""
143
+ def __init__(self, output_file, buffered=False, encoding="utf-8", close=False):
144
+ self._file = output_file
145
+ self._close = close
146
+ self.encoding = encoding
147
+ self.writer_cm = None
148
+
149
+ def __enter__(self):
150
+ self.writer_cm = incremental_tree._get_writer(self._file, encoding=self.encoding)
151
+ writer, declared_encoding = self.writer_cm.__enter__()
152
+ return _IncrementalFileWriter(writer)
153
+
154
+ def __exit__(self, type, value, traceback):
155
+ if self.writer_cm:
156
+ self.writer_cm.__exit__(type, value, traceback)
157
+ if self._close:
158
+ self._file.close()
llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .axislines import Axes
2
+ from .axislines import ( # noqa: F401
3
+ AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear,
4
+ GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero)
5
+ from .axis_artist import AxisArtist, GridlinesCollection # noqa: F401
6
+ from .grid_helper_curvelinear import GridHelperCurveLinear # noqa: F401
7
+ from .floating_axes import FloatingAxes, FloatingSubplot # noqa: F401
8
+ from mpl_toolkits.axes_grid1.parasite_axes import (
9
+ host_axes_class_factory, parasite_axes_class_factory)
10
+
11
+
12
+ ParasiteAxes = parasite_axes_class_factory(Axes)
13
+ HostAxes = host_axes_class_factory(Axes)
14
+ SubplotHost = HostAxes
llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/axes_grid.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import _api
2
+
3
+ import mpl_toolkits.axes_grid1.axes_grid as axes_grid_orig
4
+ from .axislines import Axes
5
+
6
+
7
+ _api.warn_deprecated(
8
+ "3.8", name=__name__, obj_type="module", alternative="axes_grid1.axes_grid")
9
+
10
+
11
+ @_api.deprecated("3.8", alternative=(
12
+ "axes_grid1.axes_grid.Grid(..., axes_class=axislines.Axes"))
13
+ class Grid(axes_grid_orig.Grid):
14
+ _defaultAxesClass = Axes
15
+
16
+
17
+ @_api.deprecated("3.8", alternative=(
18
+ "axes_grid1.axes_grid.ImageGrid(..., axes_class=axislines.Axes"))
19
+ class ImageGrid(axes_grid_orig.ImageGrid):
20
+ _defaultAxesClass = Axes
21
+
22
+
23
+ AxesGrid = ImageGrid
llava_next/lib/python3.10/site-packages/mpl_toolkits/axisartist/floating_axes.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ An experimental support for curvilinear grid.
3
+ """
4
+
5
+ # TODO :
6
+ # see if tick_iterator method can be simplified by reusing the parent method.
7
+
8
+ import functools
9
+
10
+ import numpy as np
11
+
12
+ import matplotlib as mpl
13
+ from matplotlib import _api, cbook
14
+ import matplotlib.patches as mpatches
15
+ from matplotlib.path import Path
16
+
17
+ from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory
18
+
19
+ from . import axislines, grid_helper_curvelinear
20
+ from .axis_artist import AxisArtist
21
+ from .grid_finder import ExtremeFinderSimple
22
+
23
+
24
+ class FloatingAxisArtistHelper(
25
+ grid_helper_curvelinear.FloatingAxisArtistHelper):
26
+ pass
27
+
28
+
29
+ class FixedAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper):
30
+
31
+ def __init__(self, grid_helper, side, nth_coord_ticks=None):
32
+ """
33
+ nth_coord = along which coordinate value varies.
34
+ nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
35
+ """
36
+ lon1, lon2, lat1, lat2 = grid_helper.grid_finder.extreme_finder(*[None] * 5)
37
+ value, nth_coord = _api.check_getitem(
38
+ dict(left=(lon1, 0), right=(lon2, 0), bottom=(lat1, 1), top=(lat2, 1)),
39
+ side=side)
40
+ super().__init__(grid_helper, nth_coord, value, axis_direction=side)
41
+ if nth_coord_ticks is None:
42
+ nth_coord_ticks = nth_coord
43
+ self.nth_coord_ticks = nth_coord_ticks
44
+
45
+ self.value = value
46
+ self.grid_helper = grid_helper
47
+ self._side = side
48
+
49
+ def update_lim(self, axes):
50
+ self.grid_helper.update_lim(axes)
51
+ self._grid_info = self.grid_helper._grid_info
52
+
53
+ def get_tick_iterators(self, axes):
54
+ """tick_loc, tick_angle, tick_label, (optionally) tick_label"""
55
+
56
+ grid_finder = self.grid_helper.grid_finder
57
+
58
+ lat_levs, lat_n, lat_factor = self._grid_info["lat_info"]
59
+ yy0 = lat_levs / lat_factor
60
+
61
+ lon_levs, lon_n, lon_factor = self._grid_info["lon_info"]
62
+ xx0 = lon_levs / lon_factor
63
+
64
+ extremes = self.grid_helper.grid_finder.extreme_finder(*[None] * 5)
65
+ xmin, xmax = sorted(extremes[:2])
66
+ ymin, ymax = sorted(extremes[2:])
67
+
68
+ def trf_xy(x, y):
69
+ trf = grid_finder.get_transform() + axes.transData
70
+ return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T
71
+
72
+ if self.nth_coord == 0:
73
+ mask = (ymin <= yy0) & (yy0 <= ymax)
74
+ (xx1, yy1), (dxx1, dyy1), (dxx2, dyy2) = \
75
+ grid_helper_curvelinear._value_and_jacobian(
76
+ trf_xy, self.value, yy0[mask], (xmin, xmax), (ymin, ymax))
77
+ labels = self._grid_info["lat_labels"]
78
+
79
+ elif self.nth_coord == 1:
80
+ mask = (xmin <= xx0) & (xx0 <= xmax)
81
+ (xx1, yy1), (dxx2, dyy2), (dxx1, dyy1) = \
82
+ grid_helper_curvelinear._value_and_jacobian(
83
+ trf_xy, xx0[mask], self.value, (xmin, xmax), (ymin, ymax))
84
+ labels = self._grid_info["lon_labels"]
85
+
86
+ labels = [l for l, m in zip(labels, mask) if m]
87
+
88
+ angle_normal = np.arctan2(dyy1, dxx1)
89
+ angle_tangent = np.arctan2(dyy2, dxx2)
90
+ mm = (dyy1 == 0) & (dxx1 == 0) # points with degenerate normal
91
+ angle_normal[mm] = angle_tangent[mm] + np.pi / 2
92
+
93
+ tick_to_axes = self.get_tick_transform(axes) - axes.transAxes
94
+ in_01 = functools.partial(
95
+ mpl.transforms._interval_contains_close, (0, 1))
96
+
97
+ def f1():
98
+ for x, y, normal, tangent, lab \
99
+ in zip(xx1, yy1, angle_normal, angle_tangent, labels):
100
+ c2 = tick_to_axes.transform((x, y))
101
+ if in_01(c2[0]) and in_01(c2[1]):
102
+ yield [x, y], *np.rad2deg([normal, tangent]), lab
103
+
104
+ return f1(), iter([])
105
+
106
+ def get_line(self, axes):
107
+ self.update_lim(axes)
108
+ k, v = dict(left=("lon_lines0", 0),
109
+ right=("lon_lines0", 1),
110
+ bottom=("lat_lines0", 0),
111
+ top=("lat_lines0", 1))[self._side]
112
+ xx, yy = self._grid_info[k][v]
113
+ return Path(np.column_stack([xx, yy]))
114
+
115
+
116
+ class ExtremeFinderFixed(ExtremeFinderSimple):
117
+ # docstring inherited
118
+
119
+ def __init__(self, extremes):
120
+ """
121
+ This subclass always returns the same bounding box.
122
+
123
+ Parameters
124
+ ----------
125
+ extremes : (float, float, float, float)
126
+ The bounding box that this helper always returns.
127
+ """
128
+ self._extremes = extremes
129
+
130
+ def __call__(self, transform_xy, x1, y1, x2, y2):
131
+ # docstring inherited
132
+ return self._extremes
133
+
134
+
135
+ class GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear):
136
+
137
+ def __init__(self, aux_trans, extremes,
138
+ grid_locator1=None,
139
+ grid_locator2=None,
140
+ tick_formatter1=None,
141
+ tick_formatter2=None):
142
+ # docstring inherited
143
+ super().__init__(aux_trans,
144
+ extreme_finder=ExtremeFinderFixed(extremes),
145
+ grid_locator1=grid_locator1,
146
+ grid_locator2=grid_locator2,
147
+ tick_formatter1=tick_formatter1,
148
+ tick_formatter2=tick_formatter2)
149
+
150
+ @_api.deprecated("3.8")
151
+ def get_data_boundary(self, side):
152
+ """
153
+ Return v=0, nth=1.
154
+ """
155
+ lon1, lon2, lat1, lat2 = self.grid_finder.extreme_finder(*[None] * 5)
156
+ return dict(left=(lon1, 0),
157
+ right=(lon2, 0),
158
+ bottom=(lat1, 1),
159
+ top=(lat2, 1))[side]
160
+
161
+ def new_fixed_axis(
162
+ self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None):
163
+ if axes is None:
164
+ axes = self.axes
165
+ if axis_direction is None:
166
+ axis_direction = loc
167
+ # This is not the same as the FixedAxisArtistHelper class used by
168
+ # grid_helper_curvelinear.GridHelperCurveLinear.new_fixed_axis!
169
+ helper = FixedAxisArtistHelper(
170
+ self, loc, nth_coord_ticks=nth_coord)
171
+ axisline = AxisArtist(axes, helper, axis_direction=axis_direction)
172
+ # Perhaps should be moved to the base class?
173
+ axisline.line.set_clip_on(True)
174
+ axisline.line.set_clip_box(axisline.axes.bbox)
175
+ return axisline
176
+
177
+ # new_floating_axis will inherit the grid_helper's extremes.
178
+
179
+ # def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"):
180
+ # axis = super(GridHelperCurveLinear,
181
+ # self).new_floating_axis(nth_coord,
182
+ # value, axes=axes,
183
+ # axis_direction=axis_direction)
184
+ # # set extreme values of the axis helper
185
+ # if nth_coord == 1:
186
+ # axis.get_helper().set_extremes(*self._extremes[:2])
187
+ # elif nth_coord == 0:
188
+ # axis.get_helper().set_extremes(*self._extremes[2:])
189
+ # return axis
190
+
191
+ def _update_grid(self, x1, y1, x2, y2):
192
+ if self._grid_info is None:
193
+ self._grid_info = dict()
194
+
195
+ grid_info = self._grid_info
196
+
197
+ grid_finder = self.grid_finder
198
+ extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,
199
+ x1, y1, x2, y2)
200
+
201
+ lon_min, lon_max = sorted(extremes[:2])
202
+ lat_min, lat_max = sorted(extremes[2:])
203
+ grid_info["extremes"] = lon_min, lon_max, lat_min, lat_max # extremes
204
+
205
+ lon_levs, lon_n, lon_factor = \
206
+ grid_finder.grid_locator1(lon_min, lon_max)
207
+ lon_levs = np.asarray(lon_levs)
208
+ lat_levs, lat_n, lat_factor = \
209
+ grid_finder.grid_locator2(lat_min, lat_max)
210
+ lat_levs = np.asarray(lat_levs)
211
+
212
+ grid_info["lon_info"] = lon_levs, lon_n, lon_factor
213
+ grid_info["lat_info"] = lat_levs, lat_n, lat_factor
214
+
215
+ grid_info["lon_labels"] = grid_finder._format_ticks(
216
+ 1, "bottom", lon_factor, lon_levs)
217
+ grid_info["lat_labels"] = grid_finder._format_ticks(
218
+ 2, "bottom", lat_factor, lat_levs)
219
+
220
+ lon_values = lon_levs[:lon_n] / lon_factor
221
+ lat_values = lat_levs[:lat_n] / lat_factor
222
+
223
+ lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
224
+ lon_values[(lon_min < lon_values) & (lon_values < lon_max)],
225
+ lat_values[(lat_min < lat_values) & (lat_values < lat_max)],
226
+ lon_min, lon_max, lat_min, lat_max)
227
+
228
+ grid_info["lon_lines"] = lon_lines
229
+ grid_info["lat_lines"] = lat_lines
230
+
231
+ lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
232
+ # lon_min, lon_max, lat_min, lat_max)
233
+ extremes[:2], extremes[2:], *extremes)
234
+
235
+ grid_info["lon_lines0"] = lon_lines
236
+ grid_info["lat_lines0"] = lat_lines
237
+
238
+ def get_gridlines(self, which="major", axis="both"):
239
+ grid_lines = []
240
+ if axis in ["both", "x"]:
241
+ grid_lines.extend(self._grid_info["lon_lines"])
242
+ if axis in ["both", "y"]:
243
+ grid_lines.extend(self._grid_info["lat_lines"])
244
+ return grid_lines
245
+
246
+
247
+ class FloatingAxesBase:
248
+
249
+ def __init__(self, *args, grid_helper, **kwargs):
250
+ _api.check_isinstance(GridHelperCurveLinear, grid_helper=grid_helper)
251
+ super().__init__(*args, grid_helper=grid_helper, **kwargs)
252
+ self.set_aspect(1.)
253
+
254
+ def _gen_axes_patch(self):
255
+ # docstring inherited
256
+ x0, x1, y0, y1 = self.get_grid_helper().grid_finder.extreme_finder(*[None] * 5)
257
+ patch = mpatches.Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
258
+ patch.get_path()._interpolation_steps = 100
259
+ return patch
260
+
261
+ def clear(self):
262
+ super().clear()
263
+ self.patch.set_transform(
264
+ self.get_grid_helper().grid_finder.get_transform()
265
+ + self.transData)
266
+ # The original patch is not in the draw tree; it is only used for
267
+ # clipping purposes.
268
+ orig_patch = super()._gen_axes_patch()
269
+ orig_patch.set_figure(self.figure)
270
+ orig_patch.set_transform(self.transAxes)
271
+ self.patch.set_clip_path(orig_patch)
272
+ self.gridlines.set_clip_path(orig_patch)
273
+ self.adjust_axes_lim()
274
+
275
+ def adjust_axes_lim(self):
276
+ bbox = self.patch.get_path().get_extents(
277
+ # First transform to pixel coords, then to parent data coords.
278
+ self.patch.get_transform() - self.transData)
279
+ bbox = bbox.expanded(1.02, 1.02)
280
+ self.set_xlim(bbox.xmin, bbox.xmax)
281
+ self.set_ylim(bbox.ymin, bbox.ymax)
282
+
283
+
284
+ floatingaxes_class_factory = cbook._make_class_factory(FloatingAxesBase, "Floating{}")
285
+ FloatingAxes = floatingaxes_class_factory(host_axes_class_factory(axislines.Axes))
286
+ FloatingSubplot = FloatingAxes
llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/RECORD ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ shellingham-1.5.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ shellingham-1.5.4.dist-info/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
3
+ shellingham-1.5.4.dist-info/METADATA,sha256=GD2AIgo3STJieVc53TV8xbs_Sb05DMkZjVGA5UUaB_o,3461
4
+ shellingham-1.5.4.dist-info/RECORD,,
5
+ shellingham-1.5.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ shellingham-1.5.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110
7
+ shellingham-1.5.4.dist-info/top_level.txt,sha256=uKMQL5AKxPi4O9_Rbd838QeEs4ImpGQKNbEDZYqgBgk,12
8
+ shellingham-1.5.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
9
+ shellingham/__init__.py,sha256=pAKXUPKUdwyErC0ZjS-5w-fRdSbmdcfvnpt_x1yWqtA,635
10
+ shellingham/__pycache__/__init__.cpython-310.pyc,,
11
+ shellingham/__pycache__/_core.cpython-310.pyc,,
12
+ shellingham/__pycache__/nt.cpython-310.pyc,,
13
+ shellingham/_core.py,sha256=v-CTr_7F7cJAtNnzpa1N_Hl8afkY5yiDA4joGmsUBu0,300
14
+ shellingham/nt.py,sha256=m6J6SuwyqVVlxXT9Bc-9F_1x-T5u0gCFFrRAF2LIkeg,4516
15
+ shellingham/posix/__init__.py,sha256=pB69qtvZJ_yIf48nl4-ZfS3wLwwuXuknXOZhBnC2T1o,3129
16
+ shellingham/posix/__pycache__/__init__.cpython-310.pyc,,
17
+ shellingham/posix/__pycache__/_core.cpython-310.pyc,,
18
+ shellingham/posix/__pycache__/proc.cpython-310.pyc,,
19
+ shellingham/posix/__pycache__/ps.cpython-310.pyc,,
20
+ shellingham/posix/_core.py,sha256=_v18UaXbzr4muNhr3-mH1FdSdjZ_dOXQrtUyomIbKYQ,81
21
+ shellingham/posix/proc.py,sha256=nSUxIuQSotvaDW76i0oTQAM9aZ9PXBLFAEktWljSKCo,2659
22
+ shellingham/posix/ps.py,sha256=NGmDKCukhNp0lahwYCaMXphBYaVbhbiR9BtE0OkT8qU,1770
llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ shellingham
llava_next/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/zip-safe ADDED
@@ -0,0 +1 @@
 
 
1
+
llava_next/lib/python3.10/site-packages/sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5630314a1385497ef8653f45c224dfb975574307f0b9d281fb889d8f7b4d959
3
+ size 154767
llava_next/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89f49c2fefdf54ec2822f2b4ff1eb947abe7bbfb580ad4323240b1c1db1c7fa8
3
+ size 106618
llava_next/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab108c654a4b2729c304fcd79e951604550796d2664c8947034e324f29233ce7
3
+ size 108388
llava_next/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da6ba7092807f97ceee953305bde6feee135bbe791da7678a231ec306ec6206d
3
+ size 152966
vlmpy310/lib/python3.10/site-packages/torch/__pycache__/library.cpython-310.pyc ADDED
Binary file (17.6 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/__init__.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ import torch.fx
4
+ import torch.utils._pytree as pytree
5
+
6
+ __all__ = ["compile", "list_mode_options", "list_options", "cudagraph_mark_step_begin"]
7
+
8
+
9
+ def compile(
10
+ gm: torch.fx.GraphModule,
11
+ example_inputs: List[torch.Tensor],
12
+ options: Optional[Dict[str, Any]] = None,
13
+ ):
14
+ """
15
+ Compile a given FX graph with TorchInductor. This allows compiling
16
+ FX graphs captured without using TorchDynamo.
17
+
18
+ Args:
19
+ gm: The FX graph to compile.
20
+ example_inputs: List of tensor inputs.
21
+ options: Optional dict of config options. See `torch._inductor.config`.
22
+
23
+ Returns:
24
+ Callable with same behavior as gm but faster.
25
+ """
26
+ from .compile_fx import compile_fx
27
+
28
+ return compile_fx(gm, example_inputs, config_patches=options)
29
+
30
+
31
+ # TODO: aot_compile can only work with fx generated by export. Will remove this next
32
+ # to prevent people from calling it with arbitrary fx graph.
33
+ def aot_compile(
34
+ gm: torch.fx.GraphModule,
35
+ example_inputs: List[torch.Tensor],
36
+ options: Optional[Dict[str, Any]] = None,
37
+ ) -> str:
38
+ """
39
+ Ahead-of-time compile a given FX graph with TorchInductor into a shared library.
40
+
41
+ Args:
42
+ gm: The FX graph to compile.
43
+ example_inputs: List of tensor inputs.
44
+ options: Optional dict of config options. See `torch._inductor.config`.
45
+
46
+ Returns:
47
+ Path to the generated shared library
48
+ """
49
+ from .compile_fx import compile_fx_aot
50
+
51
+ # We will serialize the pytree info into the .so as constant strings
52
+ serialized_in_spec = ""
53
+ serialized_out_spec = ""
54
+ if isinstance(gm.graph._codegen, torch.fx.graph._PyTreeCodeGen):
55
+ codegen = gm.graph._codegen
56
+ gm.graph._codegen = torch.fx.graph.CodeGen()
57
+ gm.recompile()
58
+
59
+ if codegen.pytree_info.in_spec is not None:
60
+ serialized_in_spec = pytree.treespec_dumps(codegen.pytree_info.in_spec)
61
+
62
+ if codegen.pytree_info.out_spec is not None:
63
+ serialized_out_spec = pytree.treespec_dumps(codegen.pytree_info.out_spec)
64
+
65
+ options = (
66
+ {
67
+ "aot_inductor.serialized_in_spec": serialized_in_spec,
68
+ "aot_inductor.serialized_out_spec": serialized_out_spec,
69
+ }
70
+ if options is None
71
+ else {
72
+ **options,
73
+ "aot_inductor.serialized_in_spec": serialized_in_spec,
74
+ "aot_inductor.serialized_out_spec": serialized_out_spec,
75
+ }
76
+ )
77
+
78
+ return compile_fx_aot(
79
+ gm,
80
+ example_inputs,
81
+ config_patches=options,
82
+ )
83
+
84
+
85
+ def list_mode_options(
86
+ mode: Optional[str] = None, dynamic: Optional[bool] = None
87
+ ) -> Dict[str, Any]:
88
+ r"""Returns a dictionary describing the optimizations that each of the available
89
+ modes passed to `torch.compile()` performs.
90
+
91
+ Args:
92
+ mode (str, optional): The mode to return the optimizations for.
93
+ If None, returns optimizations for all modes
94
+ dynamic (bool, optional): Whether dynamic shape is enabled.
95
+
96
+ Example::
97
+ >>> torch._inductor.list_mode_options()
98
+ """
99
+
100
+ mode_options: Dict[str, Dict[str, bool]] = {
101
+ "default": {},
102
+ # enable cudagraphs
103
+ "reduce-overhead": {
104
+ "triton.cudagraphs": True,
105
+ },
106
+ # enable max-autotune
107
+ "max-autotune-no-cudagraphs": {
108
+ "max_autotune": True,
109
+ },
110
+ # enable max-autotune
111
+ # enable cudagraphs
112
+ "max-autotune": {
113
+ "max_autotune": True,
114
+ "triton.cudagraphs": True,
115
+ },
116
+ }
117
+ return mode_options[mode] if mode else mode_options # type: ignore[return-value]
118
+
119
+
120
+ def list_options() -> List[str]:
121
+ r"""Returns a dictionary describing the optimizations and debug configurations
122
+ that are available to `torch.compile()`.
123
+
124
+ The options are documented in `torch._inductor.config`.
125
+
126
+ Example::
127
+
128
+ >>> torch._inductor.list_options()
129
+ """
130
+
131
+ from torch._inductor import config
132
+
133
+ current_config: Dict[str, Any] = config.shallow_copy_dict()
134
+
135
+ return list(current_config.keys())
136
+
137
+
138
+ def cudagraph_mark_step_begin():
139
+ "Indicates that a new iteration of inference or training is about to begin."
140
+ from .cudagraph_trees import mark_step_begin
141
+
142
+ mark_step_begin()
vlmpy310/lib/python3.10/site-packages/torch/_inductor/autotune_process.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import functools
6
+ import logging
7
+ import os
8
+ import queue
9
+ import time
10
+ import warnings
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from ctypes import byref, c_size_t, c_void_p
13
+ from multiprocessing.process import BaseProcess
14
+ from multiprocessing.queues import Queue
15
+ from typing import (
16
+ Any,
17
+ Callable,
18
+ Dict,
19
+ Iterable,
20
+ List,
21
+ Optional,
22
+ Sequence,
23
+ TYPE_CHECKING,
24
+ Union,
25
+ )
26
+
27
+ import torch
28
+ from torch import multiprocessing
29
+ from torch._dynamo.testing import rand_strided
30
+
31
+ from torch._inductor import ir
32
+ from torch._inductor.codecache import CUDACodeCache, DLLWrapper, PyCodeCache
33
+
34
+ if TYPE_CHECKING:
35
+ from torch._inductor.select_algorithm import TritonTemplateCaller
36
+
37
+ from . import config
38
+ from .utils import do_bench
39
+ from .virtualized import V
40
+
41
+ CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
42
+ EXIT_HANDLER_REGISTERED = False
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+
47
+ # Used to synchronize between parent and child processes
48
+ class Ping:
49
+ pass
50
+
51
+
52
+ class Pong:
53
+ pass
54
+
55
+
56
+ @contextlib.contextmanager
57
+ def set_cuda_visible_device(device: Optional[int]):
58
+ """
59
+ Context manager to set the CUDA_VISIBLE_DEVICES environment variable to the
60
+ specified single device. If device is None, don't manipulate the environment.
61
+ """
62
+ if device is None:
63
+ yield
64
+ return
65
+
66
+ current = os.environ.get(CUDA_VISIBLE_DEVICES)
67
+ os.environ[CUDA_VISIBLE_DEVICES] = str(device)
68
+ try:
69
+ yield
70
+ finally:
71
+ if current is None:
72
+ del os.environ[CUDA_VISIBLE_DEVICES]
73
+ else:
74
+ os.environ[CUDA_VISIBLE_DEVICES] = current
75
+
76
+
77
+ @dataclasses.dataclass
78
+ class TuningProcess:
79
+ """
80
+ Abstraction for launching a helper process to benchmark kernels. Spawns
81
+ the parent process and uses multiprocessing queues to send benchmark
82
+ requests and return results.
83
+ """
84
+
85
+ device: Optional[int] = None
86
+ process: Optional[BaseProcess] = None
87
+ request_queue: Optional[Queue[Any]] = None
88
+ response_queue: Optional[Queue[Any]] = None
89
+
90
+ @staticmethod
91
+ def process_main(
92
+ request_queue: Queue[Any],
93
+ response_queue: Queue[Any],
94
+ ) -> None:
95
+ """
96
+ Entry point for the child process.
97
+ """
98
+ log.debug(
99
+ "Entering TuningProcess child. Visible devices = %s",
100
+ os.environ.get(CUDA_VISIBLE_DEVICES),
101
+ )
102
+ try:
103
+ TuningProcess.workloop(request_queue, response_queue)
104
+ except Exception as ex:
105
+ log.exception("Exception in TuningProcess: %s", ex)
106
+
107
+ @staticmethod
108
+ def workloop(request_queue: Queue[Any], response_queue: Queue[Any]) -> None:
109
+ """
110
+ Work loop for the benchmarking subprocess.
111
+ """
112
+ while True:
113
+ obj = request_queue.get()
114
+
115
+ if obj is None:
116
+ break # None is a sentinel for the child to terminate
117
+ elif isinstance(obj, Ping):
118
+ response_queue.put(Pong())
119
+ elif isinstance(obj, BenchmarkRequest):
120
+ response_queue.put(obj.benchmark())
121
+ else:
122
+ raise RuntimeError(f"Invalid request type {type(obj)}")
123
+
124
+ def valid(self) -> bool:
125
+ """
126
+ True if the sub-process has been initialized.
127
+ """
128
+ return (
129
+ self.process is not None
130
+ and self.request_queue is not None
131
+ and self.response_queue is not None
132
+ )
133
+
134
+ def clear(self) -> None:
135
+ """
136
+ Reset to an uninitialized state.
137
+ """
138
+ self.process = self.request_queue = self.response_queue = None
139
+
140
+ def initialize(self) -> None:
141
+ """
142
+ Create child process, request/response queues, and do the warm up.
143
+ Set the environment to make only the provided GPU device visible
144
+ to the process.
145
+ """
146
+ if self.valid():
147
+ return
148
+
149
+ # cuda runtime does not work with "fork", use "spawn" to start processes.
150
+ ctx = multiprocessing.get_context("spawn")
151
+ self.request_queue = ctx.Queue()
152
+ self.response_queue = ctx.Queue()
153
+
154
+ self.process = ctx.Process(
155
+ target=self.process_main,
156
+ args=(
157
+ self.request_queue,
158
+ self.response_queue,
159
+ ),
160
+ )
161
+ assert self.process is not None
162
+ with set_cuda_visible_device(self.device):
163
+ self.process.start()
164
+
165
+ def put(self, obj: Any) -> None:
166
+ """
167
+ Push a work item to the child process.
168
+ """
169
+ # In case of a prior crash, ensure the subprocess is running
170
+ self.initialize()
171
+ assert self.request_queue is not None
172
+ self.request_queue.put(obj)
173
+
174
+ def get(self) -> Any:
175
+ """
176
+ Get a response from the child process.
177
+ """
178
+ assert self.process is not None
179
+ assert self.response_queue is not None
180
+ while True:
181
+ try:
182
+ return self.response_queue.get(timeout=1.0)
183
+ except queue.Empty:
184
+ status = self.process.exitcode
185
+ if status is None:
186
+ # child process is still running
187
+ continue
188
+ # child process crashed
189
+ self.clear()
190
+ raise
191
+
192
+ def terminate(self) -> None:
193
+ """
194
+ Signal the child process to terminate.
195
+ """
196
+ if self.valid():
197
+ assert self.process is not None
198
+ assert self.request_queue is not None
199
+ self.request_queue.put(None)
200
+
201
+ def wait(self) -> None:
202
+ """
203
+ Wait for the child process to exit.
204
+ """
205
+ if self.process is not None:
206
+ self.process.join()
207
+ self.clear()
208
+
209
+
210
+ @dataclasses.dataclass
211
+ class TuningProcessPool:
212
+ """
213
+ Maintains a pool of TuningProcesses to benchmark kernels in parallel
214
+ across devices. By default, we create one TuningProcess per device and
215
+ set the sub-process environment to make only that device visible.
216
+ """
217
+
218
+ processes: Optional[queue.Queue[TuningProcess]] = None
219
+ executor: Optional[ThreadPoolExecutor] = None
220
+
221
+ def initialize(self) -> None:
222
+ """
223
+ Start the child processes.
224
+ """
225
+ assert (self.processes is None) == (self.executor is None)
226
+ if self.processes is not None:
227
+ return
228
+
229
+ devices = self.get_device_list()
230
+ log.debug("Sub-process autotune device list: %s", devices)
231
+
232
+ # Launch the child processes and push a msg to "warm up"
233
+ self.processes = queue.Queue()
234
+ for device in devices:
235
+ p = TuningProcess(device=device)
236
+ p.initialize()
237
+ p.put(Ping())
238
+ self.processes.put(p)
239
+
240
+ # Wait for the initialization to finish
241
+ for p in self.processes.queue:
242
+ assert isinstance(p.get(), Pong)
243
+
244
+ # Use a thread pool to manage distributing work to the subprocesses.
245
+ # Threads block on an available process, so it makes sense to match
246
+ # the number of threads with the number of devices.
247
+ self.executor = ThreadPoolExecutor(max_workers=len(devices))
248
+
249
+ # Register the exit handler for the parent process so it will terminate
250
+ # the child processes.
251
+ global EXIT_HANDLER_REGISTERED
252
+ if not EXIT_HANDLER_REGISTERED:
253
+ EXIT_HANDLER_REGISTERED = True
254
+ import atexit
255
+
256
+ atexit.register(self.terminate)
257
+
258
+ def get_device_list(self) -> Sequence[Optional[int]]:
259
+ """
260
+ Gather the list of devices to be used in the pool.
261
+ """
262
+ if not config.autotune_multi_device:
263
+ # Don't use multiple devices
264
+ return [None]
265
+
266
+ count = torch.cuda.device_count()
267
+
268
+ # If the user specified the visible devices in the env, use those.
269
+ if CUDA_VISIBLE_DEVICES in os.environ:
270
+ devices = [int(d) for d in os.environ[CUDA_VISIBLE_DEVICES].split(",")]
271
+ assert len(devices) <= count
272
+ return devices
273
+
274
+ return list(range(count))
275
+
276
+ def terminate(self) -> None:
277
+ """
278
+ Signal all child processes to terminate.
279
+ """
280
+ if self.executor is not None:
281
+ self.executor.shutdown()
282
+ self.executor = None
283
+
284
+ if self.processes is not None:
285
+ for p in self.processes.queue:
286
+ p.terminate()
287
+ for p in self.processes.queue:
288
+ p.wait()
289
+ self.processes = None
290
+
291
+ def target(self, choice: TritonTemplateCaller) -> float:
292
+ """
293
+ Entry point for the thread-pool helper threads: Wait for an open TuningProcess,
294
+ remove it from the queue, execute the benchmark in that subprocess, and return
295
+ the TuningProcess to the queue.
296
+ """
297
+ assert choice.bmreq is not None
298
+ assert self.processes is not None
299
+
300
+ process = self.processes.get()
301
+ process.put(choice.bmreq)
302
+ try:
303
+ return process.get()
304
+ except queue.Empty:
305
+ warnings.warn(
306
+ f"Failed to benchmark choice '{choice}'. It will be ignored. "
307
+ "Please debug the root cause in case the choice can bring perf gains."
308
+ )
309
+ # set to INF so this choice will be ignored
310
+ return float("inf")
311
+ finally:
312
+ self.processes.put(process)
313
+
314
+ def benchmark(
315
+ self,
316
+ choices: List[TritonTemplateCaller],
317
+ ) -> Dict[TritonTemplateCaller, float]:
318
+ """
319
+ Benchmark each choice in a separate process.
320
+ """
321
+ assert self.processes is not None, "Tuning process pool is not initialized"
322
+ assert self.executor is not None
323
+
324
+ results = {}
325
+
326
+ # Use a ThreadExecutorPool to spread the work across the subprocesses and
327
+ # to grab subprocesses as soon as they're free.
328
+ for choice, result in zip(choices, self.executor.map(self.target, choices)):
329
+ results[choice] = result
330
+
331
+ return results
332
+
333
+
334
+ tuning_pool = TuningProcessPool()
335
+
336
+
337
+ LayoutOrBuffer = Union[ir.Layout, ir.Buffer]
338
+
339
+
340
+ @dataclasses.dataclass
341
+ class TensorMeta:
342
+ device: torch.device
343
+ dtype: torch.dtype
344
+ sizes: torch._prims_common.ShapeType
345
+ strides: torch._prims_common.StrideType
346
+ offset: int
347
+
348
+ @classmethod
349
+ def from_irnodes(
350
+ cls, irnodes: Union[LayoutOrBuffer, Sequence[LayoutOrBuffer]]
351
+ ) -> Union[TensorMeta, List[TensorMeta]]:
352
+ if isinstance(irnodes, Sequence):
353
+ result: List[Any] = [cls.from_irnodes(x) for x in irnodes]
354
+ assert all(isinstance(x, TensorMeta) for x in result)
355
+ return result
356
+
357
+ node = irnodes
358
+ if isinstance(node, ir.Layout):
359
+ node = ir.Buffer("fake", node)
360
+
361
+ dtype = node.get_dtype()
362
+ assert dtype is not None
363
+
364
+ return TensorMeta(
365
+ device=node.get_device(),
366
+ dtype=dtype,
367
+ sizes=V.graph.sizevars.size_hints(
368
+ node.get_size(),
369
+ fallback=config.unbacked_symint_fallback,
370
+ ),
371
+ strides=V.graph.sizevars.size_hints(
372
+ node.get_stride(),
373
+ fallback=config.unbacked_symint_fallback,
374
+ ),
375
+ offset=V.graph.sizevars.size_hint(
376
+ node.get_layout().offset,
377
+ fallback=config.unbacked_symint_fallback,
378
+ ),
379
+ )
380
+
381
+ def to_tensor(self) -> torch.Tensor:
382
+ return rand_strided(
383
+ self.sizes,
384
+ self.strides,
385
+ device=self.device,
386
+ dtype=self.dtype,
387
+ extra_size=self.offset,
388
+ )
389
+
390
+
391
+ @dataclasses.dataclass
392
+ class BenchmarkRequest:
393
+ """
394
+ Only handle triton template benchmark for now. The extern kernel benchmark
395
+ can be done inside the same process since they usually don't cause crash.
396
+ """
397
+
398
+ def __init__(
399
+ self,
400
+ kernel_name: str,
401
+ input_tensor_meta: Union[TensorMeta, List[TensorMeta]],
402
+ output_tensor_meta: Union[TensorMeta, List[TensorMeta]],
403
+ extra_args: Iterable[Any],
404
+ ):
405
+ # the kernel name defined in the module
406
+ self.kernel_name = kernel_name
407
+
408
+ if isinstance(input_tensor_meta, TensorMeta):
409
+ input_tensor_meta = [input_tensor_meta]
410
+ self.input_tensor_meta = input_tensor_meta
411
+
412
+ if isinstance(output_tensor_meta, (tuple, list)):
413
+ assert len(output_tensor_meta) == 1
414
+ output_tensor_meta = output_tensor_meta[0]
415
+ self.output_tensor_meta = output_tensor_meta
416
+
417
+ self.extra_args = extra_args
418
+
419
+ def make_run_fn(
420
+ self, *input_tensors: torch.Tensor, output_tensor: torch.Tensor
421
+ ) -> Callable[[], None]:
422
+ raise NotImplementedError()
423
+
424
+ def cleanup_run_fn(self) -> None:
425
+ pass
426
+
427
+ def benchmark(
428
+ self,
429
+ *input_tensors: torch.Tensor,
430
+ output_tensor: Optional[torch.Tensor] = None,
431
+ ) -> float:
432
+ debug = log.isEnabledFor(logging.DEBUG)
433
+ if debug:
434
+ start_ts = time.time()
435
+
436
+ # create args and out tensor
437
+ if output_tensor is None:
438
+ assert len(input_tensors) == 0
439
+ input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta)
440
+ output_tensor = self.output_tensor_meta.to_tensor()
441
+
442
+ if debug:
443
+ create_tensor_elapse = time.time() - start_ts
444
+ start_ts = time.time()
445
+
446
+ fn = self.make_run_fn(*input_tensors, output_tensor=output_tensor)
447
+
448
+ if debug:
449
+ load_elapse = time.time() - start_ts
450
+ start_ts = time.time()
451
+
452
+ out = do_bench(fn)
453
+ torch.cuda.synchronize() # shake out any CUDA errors
454
+
455
+ if debug:
456
+ bench_elapse = time.time() - start_ts
457
+ log.debug(
458
+ "InChildProcess %s: load %f, create tensor %f, bench %f",
459
+ str(self),
460
+ load_elapse,
461
+ create_tensor_elapse,
462
+ bench_elapse,
463
+ )
464
+ self.cleanup_run_fn()
465
+ return out
466
+
467
+
468
+ class TestBenchmarkRequest(BenchmarkRequest):
469
+ """
470
+ Supports unit testing. Defined in this file so that the TuningProcess
471
+ sub-process knows how to unpickle these objects.
472
+ """
473
+
474
+ def __init__(self, value: Optional[float] = None) -> None:
475
+ self.value = value
476
+
477
+ def benchmark(
478
+ self, *input_tensors: torch.Tensor, output_tensor: Optional[torch.Tensor] = None
479
+ ) -> float:
480
+ if self.value is None:
481
+ raise Exception("Failed to run")
482
+ return self.value
483
+
484
+
485
+ class TritonBenchmarkRequest(BenchmarkRequest):
486
+ def __init__(
487
+ self,
488
+ kernel_name: str,
489
+ input_tensor_meta: Union[TensorMeta, List[TensorMeta]],
490
+ output_tensor_meta: Union[TensorMeta, List[TensorMeta]],
491
+ extra_args: Iterable[Any],
492
+ module_path: str, # the path of the module defining the triton kernel
493
+ module_cache_key: str,
494
+ grid: List[int],
495
+ num_stages: int,
496
+ num_warps: int,
497
+ ):
498
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
499
+ self.module_path = module_path
500
+ self.module_cache_key = module_cache_key
501
+ self.grid = grid
502
+ self.num_stages = num_stages
503
+ self.num_warps = num_warps
504
+
505
+ def make_run_fn(
506
+ self, *input_tensors: torch.Tensor, output_tensor: torch.Tensor
507
+ ) -> Callable[[], None]:
508
+ mod = PyCodeCache.load_by_key_path(self.module_cache_key, self.module_path)
509
+ log.debug(
510
+ "benchmark module key: %s, path: %s",
511
+ self.module_cache_key,
512
+ self.module_path,
513
+ )
514
+
515
+ run_method = getattr(mod, self.kernel_name).run
516
+
517
+ return functools.partial(
518
+ run_method,
519
+ *input_tensors,
520
+ output_tensor,
521
+ *self.extra_args,
522
+ grid=self.grid,
523
+ num_stages=self.num_stages,
524
+ num_warps=self.num_warps,
525
+ stream=torch.cuda.current_stream().cuda_stream,
526
+ )
527
+
528
+ def __str__(self) -> str:
529
+ return f"{self.kernel_name=}, {self.module_path=}, {self.module_cache_key=}"
530
+
531
+
532
+ class CUDABenchmarkRequest(BenchmarkRequest):
533
+ def __init__(
534
+ self,
535
+ kernel_name: str,
536
+ input_tensor_meta: Union[TensorMeta, List[TensorMeta]],
537
+ output_tensor_meta: Union[TensorMeta, List[TensorMeta]],
538
+ extra_args: Iterable[Any],
539
+ source_code: str,
540
+ ):
541
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
542
+ self.source_code = source_code
543
+ self.workspace_size: int = 0
544
+ self.workspace: Optional[torch.Tensor] = None
545
+ self.DLL: Optional[DLLWrapper] = None
546
+ self.hash_key: str = ""
547
+ self.source_file: str = ""
548
+ self.hash_key, self.source_file = CUDACodeCache.write(self.source_code, "so")
549
+
550
+ def make_run_fn(
551
+ self, *input_tensors: torch.Tensor, output_tensor: torch.Tensor
552
+ ) -> Callable[[], None]:
553
+ self.DLL, self.hash_key, self.source_file = CUDACodeCache.load(
554
+ self.source_code, "so"
555
+ )
556
+ args = [
557
+ c_void_p(tensor.data_ptr())
558
+ for tensor in list(input_tensors) + [output_tensor]
559
+ ]
560
+ log.debug(
561
+ "make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s",
562
+ self.kernel_name,
563
+ self.source_file,
564
+ self.hash_key,
565
+ self.DLL,
566
+ args,
567
+ self.extra_args,
568
+ )
569
+ run_method = getattr(self.DLL, self.kernel_name)
570
+ stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream)
571
+
572
+ # Retrieve workspace_size and initialize workspace.
573
+ c_workspace_size = c_size_t()
574
+ run_method(
575
+ *args, # input ptrs and output ptrs
576
+ *self.extra_args,
577
+ byref(
578
+ c_workspace_size
579
+ ), # set workspace size ptr to retrieve workspace size
580
+ None, # null workspace ptr
581
+ stream_ptr,
582
+ )
583
+ self.workspace_size = c_workspace_size.value
584
+ # TODO: Support non-zero workspace_size.
585
+ assert self.workspace_size == 0, (
586
+ "Things need to be fixed to support non-zero workspace_size: "
587
+ "1) max autotune cache needs to store workspace size; "
588
+ "2) memory allocation needs to allocate / deallocate workspace correctly; "
589
+ )
590
+
591
+ # Generate partial function.
592
+ return functools.partial(
593
+ run_method,
594
+ *args,
595
+ *self.extra_args,
596
+ None, # null workspace size ptr
597
+ None, # set workspace ptr, TODO: update it to a real ptr if workspace_size > 0
598
+ stream_ptr,
599
+ )
600
+
601
+ def cleanup_run_fn(self) -> None:
602
+ if self.DLL is not None:
603
+ self.DLL.close()
604
+ self.workspace = None
605
+
606
+ def __str__(self) -> str:
607
+ return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}"
608
+
609
+
610
+ def benchmark_in_sub_process(
611
+ choices: List[TritonTemplateCaller],
612
+ ) -> Dict[TritonTemplateCaller, float]:
613
+ """
614
+ Do benchmarking in a subprocess and return the perf number (latency).
615
+ """
616
+ return tuning_pool.benchmark(choices)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/bounds.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from functools import partial
3
+ from typing import Any, Callable, Dict
4
+
5
+ from sympy import Expr
6
+
7
+ import torch
8
+ from torch.utils._sympy.value_ranges import bound_sympy, ValueRangeAnalysis, ValueRanges
9
+ from .ir import InterpreterShim, LoopBody, LoopBodyBlock
10
+ from .utils import cache_on_self, dominated_nodes
11
+ from .virtualized import V
12
+
13
+
14
+ class BoundVars:
15
+ """
16
+ Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run()
17
+ It exposes the ranges of the nodes in the `bounds` variable
18
+
19
+ Note. A current limitation of this analysis is that it just works on a per-loop basis.
20
+ We should be able to propagate the bounds between across the whole graph. This may benefit
21
+ the case a bounded variable is returned by a kernel and fed into another.
22
+ """
23
+
24
+ def __init__(self, loop_body: LoopBody) -> None:
25
+ self.loop_body = loop_body
26
+ self.replacement_vals = {
27
+ k: ValueRanges(0, v - 1)
28
+ if (isinstance(v, int) or v.is_number)
29
+ else bound_sympy(v)
30
+ for k, v in loop_body.var_ranges.items()
31
+ }
32
+ # avoid computing these values, pessimistically assume that they are unbounded
33
+ self.unbounded_vars = dominated_nodes(
34
+ node
35
+ for node in self.loop_body.get_nodes()
36
+ if node.target in ["load", "reduction", operator.getitem]
37
+ or "masked_subblock" in node.target
38
+ )
39
+ # To access this variable call `get_bounds()`
40
+ self._bounds: Dict[torch.fx.Node, ValueRanges] = {}
41
+
42
+ @cache_on_self
43
+ def get_bounds(self) -> Dict[torch.fx.Node, ValueRanges]:
44
+ submodules = self.swap_submodules(self.loop_body.submodules)
45
+
46
+ # Initialize the environment with the unbounded variables
47
+ for node in self.unbounded_vars:
48
+ # we need to evaluate masked_subblock to recurse, and we need to set indirect values
49
+ if not isinstance(node.target, str) or (
50
+ "masked_subblock" not in node.target
51
+ and "set_indirect" not in node.target
52
+ ):
53
+ self._bounds[node] = ValueRanges.unknown()
54
+
55
+ with V.set_ops_handler(ValueRangeAnalysis()):
56
+ interpreter = InterpreterShim(self.loop_body.root_block.graph, submodules)
57
+ interpreter.run(V.get_ops_handler(), initial_env=self._bounds)
58
+ return self._bounds
59
+
60
+ def swap_submodules(
61
+ self, submodules: Dict[str, Callable[..., Any]]
62
+ ) -> Dict[str, Callable[..., ValueRanges]]:
63
+ result: Dict[str, Callable[..., ValueRanges]] = {}
64
+ for key in submodules.keys():
65
+ if key == "get_index":
66
+ result[key] = self.get_index
67
+ elif "masked_subblock" in key:
68
+ subblock = self.loop_body.subblocks[key]
69
+ # The result within the lambda will reference to the final
70
+ # set of modules at the end of the for-loop as it stores a reference to it
71
+
72
+ # bind subblock in a function because python lambdas close over by reference
73
+ # moving the lambda out of make_fn would close over the reference to subblock,
74
+ # so all lambdas would have the same subblock reference that is the final
75
+ # subblock in the loop
76
+ def make_fn(subblock):
77
+ return lambda mask, value: self.masked_subblock(
78
+ subblock, self._bounds, mask, value, result
79
+ )
80
+
81
+ result[key] = make_fn(subblock)
82
+
83
+ else:
84
+ assert "set_indirect" in key
85
+ idx = int(key[len("set_indirect") :])
86
+ var = self.loop_body.indirect_vars[idx]
87
+ indirect = partial(self.set_indirect, var)
88
+ result[key] = indirect
89
+
90
+ return result
91
+
92
+ def masked_subblock(
93
+ self,
94
+ subblock: LoopBodyBlock,
95
+ env: Dict[torch.fx.Node, ValueRanges],
96
+ mask: Any,
97
+ value: Any,
98
+ submodules: Dict[str, Callable[..., Any]],
99
+ ) -> ValueRanges:
100
+ interp = InterpreterShim(subblock.graph, submodules)
101
+ interp.run(V.get_ops_handler(), initial_env=env)
102
+ output = [node for node in subblock.graph.nodes if node.target == "output"]
103
+ assert len(output) == 1
104
+ # dont bother unioning with value since the load from buffer will be
105
+ # pessimistically assumed to be inf anyway
106
+ return interp.env[output[0]]
107
+
108
+ def set_indirect(self, old: Expr, new: ValueRanges) -> ValueRanges:
109
+ assert isinstance(new, ValueRanges)
110
+ self.replacement_vals[old] = new
111
+ return new
112
+
113
+ def get_index(self, name: Expr) -> ValueRanges:
114
+ expr = self.loop_body.indexing_exprs[name]
115
+ bound = self.replacement_vals.get(expr)
116
+ if bound is None:
117
+ bound = bound_sympy(expr, self.replacement_vals)
118
+ # The following assertion is true at the time of this writing
119
+ # We don't assert is as to not execute bound_sympy when bound is not None
120
+ # assert bound is None or bound == bound_sympy(expr, self.replacement_vals)
121
+ self.replacement_vals[name] = bound
122
+ return bound
vlmpy310/lib/python3.10/site-packages/torch/_inductor/codecache.py ADDED
@@ -0,0 +1,2477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import copyreg
5
+ import dataclasses
6
+ import functools
7
+ import hashlib
8
+ import importlib
9
+ import io
10
+ import json
11
+ import logging
12
+ import multiprocessing
13
+ import os
14
+ import pathlib
15
+ import pickle
16
+ import pkgutil
17
+ import platform
18
+ import re
19
+ import shlex
20
+ import shutil
21
+ import signal
22
+ import subprocess
23
+ import sys
24
+ import sysconfig
25
+ import tempfile
26
+ import threading
27
+ import warnings
28
+ import weakref
29
+ from bisect import bisect_right
30
+ from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor
31
+ from copy import copy
32
+ from ctypes import c_void_p, cdll, CDLL
33
+ from dataclasses import field
34
+ from functools import partial
35
+ from importlib import abc
36
+ from pathlib import Path
37
+ from threading import Thread
38
+ from time import sleep, time
39
+ from types import ModuleType
40
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, TYPE_CHECKING, Union
41
+
42
+ import torch
43
+
44
+ from torch._dynamo.device_interface import (
45
+ get_interface_for_device,
46
+ get_registered_device_interfaces,
47
+ )
48
+ from torch._dynamo.utils import counters
49
+ from torch._inductor import config, exc
50
+ from torch._inductor.codegen.cuda import cuda_env
51
+ from torch._inductor.utils import cache_dir, developer_warning, is_linux
52
+ from torch._prims_common import suggest_memory_format
53
+ from torch.fx.experimental.symbolic_shapes import has_hint, hint_int, ShapeEnv
54
+
55
+ if TYPE_CHECKING:
56
+ from torch._inductor.graph import GraphLowering
57
+ from torch._inductor.select_algorithm import ChoiceCaller
58
+
59
+ from torch.hub import _Faketqdm, tqdm
60
+
61
+ _HERE = os.path.abspath(__file__)
62
+ _TORCH_PATH = os.path.dirname(os.path.dirname(_HERE))
63
+
64
+ if config.is_fbcode():
65
+ from triton.fb import build_paths
66
+ from triton.fb.build import _run_build_command
67
+
68
+ from torch._inductor.fb.utils import (
69
+ log_global_cache_errors,
70
+ log_global_cache_stats,
71
+ log_global_cache_vals,
72
+ use_global_cache,
73
+ )
74
+ else:
75
+
76
+ def log_global_cache_errors(*args, **kwargs):
77
+ pass
78
+
79
+ def log_global_cache_stats(*args, **kwargs):
80
+ pass
81
+
82
+ def log_global_cache_vals(*args, **kwargs):
83
+ pass
84
+
85
+ def use_global_cache() -> bool:
86
+ return False
87
+
88
+
89
+ LOCK_TIMEOUT = 600
90
+
91
+ # timing metrics for time spent in the compilation
92
+ _cumulative_compile_time = 0.0
93
+ _t0 = None
94
+
95
+
96
+ def _compile_start() -> None:
97
+ global _t0
98
+ if _t0 is None:
99
+ _t0 = time()
100
+
101
+
102
+ def _compile_end() -> None:
103
+ global _cumulative_compile_time, _t0
104
+ if _t0 is not None:
105
+ t1 = time()
106
+ _cumulative_compile_time += t1 - _t0
107
+ _t0 = None
108
+ # print("CUMULATIVE COMPILE TIME", _cumulative_compile_time)
109
+
110
+
111
+ log = logging.getLogger(__name__)
112
+
113
+
114
+ def cpp_wrapper_cache_dir(name: str) -> str:
115
+ cu_str = (
116
+ "cpu"
117
+ if torch.version.cuda is None
118
+ else f'cu{torch.version.cuda.replace(".", "")}'
119
+ )
120
+ python_version = f"py{sys.version_info.major}{sys.version_info.minor}"
121
+ build_folder = f"{python_version}_{cu_str}"
122
+
123
+ cpp_wrapper_dir = os.path.join(cache_dir(), build_folder)
124
+ cpp_wrapper_build_directory = os.path.join(cpp_wrapper_dir, name)
125
+ os.makedirs(cpp_wrapper_build_directory, exist_ok=True)
126
+ return cpp_wrapper_build_directory
127
+
128
+
129
+ def get_cpp_wrapper_cubin_path_name():
130
+ return "cubin_path" if torch.version.hip is None else "hsaco_path"
131
+
132
+
133
+ class CacheBase:
134
+ @staticmethod
135
+ @functools.lru_cache(None)
136
+ def get_system() -> Dict[str, Any]:
137
+ try:
138
+ import triton
139
+
140
+ triton_version = triton.__version__
141
+ except ModuleNotFoundError:
142
+ triton_version = None
143
+
144
+ try:
145
+ system: Dict[str, Any] = {
146
+ "device": {
147
+ "name": torch.cuda.get_device_properties(
148
+ torch.cuda.current_device()
149
+ ).name,
150
+ },
151
+ "version": {
152
+ "cuda": torch.version.cuda,
153
+ "triton": triton_version,
154
+ },
155
+ "other": {
156
+ "allow_tf32": torch.backends.cuda.matmul.allow_tf32,
157
+ },
158
+ }
159
+ except (AssertionError, RuntimeError):
160
+ # If cuda is not installed, none of the above config is relevant.
161
+ system = {}
162
+
163
+ system["hash"] = hashlib.sha256(
164
+ json.dumps(system, sort_keys=True).encode("utf-8")
165
+ ).hexdigest()
166
+
167
+ return system
168
+
169
+ @staticmethod
170
+ @functools.lru_cache(None)
171
+ def get_local_cache_path() -> Path:
172
+ return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"]))
173
+
174
+ @staticmethod
175
+ @functools.lru_cache(None)
176
+ def get_global_cache_path() -> Optional[Path]:
177
+ return (
178
+ Path(os.path.join(config.global_cache_dir, CacheBase.get_system()["hash"]))
179
+ if config.global_cache_dir is not None
180
+ else None
181
+ )
182
+
183
+ def __init__(self) -> None:
184
+ if not torch.cuda.is_available():
185
+ return
186
+
187
+ self.system = CacheBase.get_system()
188
+
189
+ self.local_cache_path = CacheBase.get_local_cache_path()
190
+ self.global_cache_path = CacheBase.get_global_cache_path()
191
+
192
+ def get_local_cache(self) -> Dict[str, Any]:
193
+ if not self.local_cache_path.is_file():
194
+ return {}
195
+ with open(self.local_cache_path) as local_cache_fp:
196
+ local_cache = json.load(local_cache_fp)
197
+ return local_cache["cache"]
198
+
199
+ def update_local_cache(self, local_cache: Dict[str, Any]) -> None:
200
+ if not os.path.exists(self.local_cache_path.parent):
201
+ os.makedirs(self.local_cache_path.parent, exist_ok=True)
202
+ write_atomic(
203
+ str(self.local_cache_path),
204
+ json.dumps({"system": self.system, "cache": local_cache}, indent=4),
205
+ )
206
+
207
+
208
+ class LocalCache(CacheBase):
209
+ def lookup(self, *keys: str) -> Optional[Dict[str, Any]]:
210
+ cache = self.get_local_cache()
211
+
212
+ sub_cache = cache
213
+ for key in keys:
214
+ if key in cache:
215
+ sub_cache = cache[key]
216
+ else:
217
+ return None
218
+
219
+ return sub_cache
220
+
221
+ def set_value(self, *keys: str, value: Any) -> None:
222
+ cache = self.get_local_cache()
223
+
224
+ sub_cache = cache
225
+ for key in keys[0:-1]:
226
+ sub_cache.setdefault(key, {})
227
+ sub_cache = sub_cache[key]
228
+ sub_cache[keys[-1]] = value
229
+
230
+ self.update_local_cache(cache)
231
+
232
+
233
+ class PersistentCache(CacheBase):
234
+ @functools.lru_cache(None)
235
+ def get_global_cache(self):
236
+ if self.global_cache_path is None or not self.global_cache_path.is_file():
237
+ return {}
238
+ with open(self.global_cache_path) as global_cache_fp:
239
+ global_cache = json.load(global_cache_fp)
240
+ return global_cache["cache"]
241
+
242
+ def lookup(
243
+ self,
244
+ choices: List[ChoiceCaller],
245
+ name: str,
246
+ inputs: str,
247
+ benchmark: Callable[[Any], Dict[ChoiceCaller, float]],
248
+ ) -> Dict[ChoiceCaller, float]:
249
+ """
250
+ Check to see if we have benchmarked the given choice callers. For each
251
+ choice caller:
252
+
253
+ 1. Check global_cache[name][inputs][choice], return benchmark if cached.
254
+ 2. Check local_cache[name][inputs][choice], return benchmark if cached.
255
+ 3.
256
+ a. `max_autotune_gemm=True`: benchmark the choice, update
257
+ local_cache[name][inputs][choice], and return the benchmark.
258
+ b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing.
259
+ """
260
+
261
+ log_stats = partial(log_global_cache_stats, self.system, name, inputs)
262
+ log_vals = partial(log_global_cache_vals, self.system, name, inputs)
263
+ log_errors = partial(log_global_cache_errors, self.system, name, inputs)
264
+ timings = {}
265
+
266
+ def check_cache(cache, callback=None) -> bool:
267
+ """Check if `cache` contains data for all the choices"""
268
+ hit = True
269
+ for choice in choices:
270
+ choice_hash = choice.hash_key()
271
+ if choice_hash in cache.get(name, {}).get(inputs, {}):
272
+ # cache hit
273
+ timings[choice] = cache[name][inputs][choice_hash]
274
+ else:
275
+ # cache miss
276
+ hit = False
277
+ break
278
+ if callback:
279
+ callback(cached=hit)
280
+ return hit
281
+
282
+ if config.max_autotune or config.max_autotune_gemm:
283
+ local_cache = self.get_local_cache()
284
+ # check local cache first since it is data specific to the current machine
285
+ if not check_cache(local_cache) and not (
286
+ use_global_cache()
287
+ and check_cache(self.get_global_cache(), callback=log_stats)
288
+ ):
289
+ try:
290
+ # re-benchmark everything to try to get consistent numbers from the same machine
291
+ timings = benchmark(choices)
292
+ assert all(choice in timings for choice in choices)
293
+
294
+ local_cache.setdefault(name, {})
295
+ local_cache[name].setdefault(inputs, {})
296
+ for choice, timing in timings.items():
297
+ local_cache[name][inputs][choice.hash_key()] = timing
298
+ except RuntimeError as e:
299
+ # catch and log autotuning failures
300
+ log_errors(e)
301
+ raise e
302
+
303
+ self.update_local_cache(local_cache)
304
+
305
+ timings_to_log = {
306
+ choice.hash_key(): timings[choice] for choice in choices
307
+ }
308
+ log_vals(timings_to_log)
309
+ elif use_global_cache():
310
+ # only check global cache, not local one
311
+ check_cache(self.get_global_cache(), callback=log_stats)
312
+ # may have a partial cache hit, where not everything is benchmarked
313
+
314
+ return timings
315
+
316
+
317
+ def get_lock_dir() -> str:
318
+ lock_dir = os.path.join(cache_dir(), "locks")
319
+ if not os.path.exists(lock_dir):
320
+ os.makedirs(lock_dir, exist_ok=True)
321
+ return lock_dir
322
+
323
+
324
+ def sha256_hash(data: bytes) -> str:
325
+ # [:51] to strip off the "Q====" suffix common to every hash value.
326
+ return base64.b32encode(hashlib.sha256(data).digest())[:51].decode("utf-8").lower()
327
+
328
+
329
+ def code_hash(code: Union[str, bytes], extra: str = ""):
330
+ hashing_str = code if isinstance(code, bytes) else code.encode("utf-8")
331
+ if extra != "":
332
+ hashing_str = hashing_str + b"||" + extra.encode("utf-8")
333
+ return "c" + sha256_hash(hashing_str)
334
+
335
+
336
+ def get_path(
337
+ basename: str, extension: str, specified_dir: str = ""
338
+ ) -> Tuple[str, str, str]:
339
+ if specified_dir:
340
+ if os.path.isabs(specified_dir):
341
+ subdir = specified_dir
342
+ else:
343
+ subdir = os.path.join(cache_dir(), specified_dir)
344
+ else:
345
+ subdir = os.path.join(cache_dir(), basename[1:3])
346
+ path = os.path.join(subdir, f"{basename}.{extension}")
347
+ return basename, subdir, path
348
+
349
+
350
+ def get_hash(content: Union[str, bytes], extra: str = "", hash_type: str = "code"):
351
+ if hash_type == "code":
352
+ return code_hash(content, extra)
353
+ if hash_type in ["cubin", "hsaco"]:
354
+ return code_hash(repr(content))
355
+ raise AssertionError(f"Unknown hash type {hash_type}")
356
+
357
+
358
+ def write(
359
+ content: Union[str, bytes],
360
+ extension: str,
361
+ extra: str = "",
362
+ hash_type: str = "code",
363
+ specified_dir: str = "",
364
+ ) -> Tuple[str, str]:
365
+ # use striped content to compute hash so we don't end up with different
366
+ # hashes just because the content begins/ends with differnet number of
367
+ # spaces.
368
+ key: str = get_hash(content.strip(), extra, hash_type)
369
+ basename, subdir, path = get_path(key, extension, specified_dir)
370
+ if not os.path.exists(subdir):
371
+ os.makedirs(subdir, exist_ok=True)
372
+ if not os.path.exists(path):
373
+ write_atomic(path, content)
374
+ return basename, path
375
+
376
+
377
+ def write_atomic(path: str, content: Union[str, bytes]) -> None:
378
+ # Write into temporary file first to avoid conflicts between threads
379
+ # Avoid using a named temporary file, as those have restricted permissions
380
+ assert isinstance(
381
+ content, (str, bytes)
382
+ ), "Only strings and byte arrays can be saved in the cache"
383
+ path = pathlib.Path(path)
384
+ tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp"
385
+ write_mode = "w" if isinstance(content, str) else "wb"
386
+ with tmp_path.open(write_mode) as f:
387
+ f.write(content)
388
+ tmp_path.rename(path)
389
+
390
+
391
+ @dataclasses.dataclass
392
+ class TensorMetadata:
393
+ """
394
+ The Tensor metadata relevant when hashing FxGraph cache keys.
395
+ """
396
+
397
+ dtype: torch.dtype
398
+ shape: torch.Size
399
+ stride: Tuple[Any, ...]
400
+ device: torch.device
401
+ layout: torch.layout
402
+ memory_format: Optional[torch.memory_format]
403
+ storage_offset: int
404
+ requires_grad: bool
405
+ is_quantized: bool
406
+ is_conj: bool
407
+ is_neg: bool
408
+ is_coalesced: bool
409
+ dense_dim: int
410
+ sparse_dim: int
411
+
412
+
413
+ @dataclasses.dataclass
414
+ class TensorMetadataAndValues:
415
+ """
416
+ TensorMetadata plus the elements as a list of raw values.
417
+ Used for hashing inlined constants.
418
+ """
419
+
420
+ tensor_metadata: TensorMetadata
421
+ values: List[Any]
422
+
423
+
424
+ def extract_tensor_metadata(t: torch.Tensor) -> TensorMetadata:
425
+ """
426
+ Extract the TensorMetadata of a tensor.
427
+ """
428
+ memory_format: Optional[torch.memory_format] = suggest_memory_format(t)
429
+ if not t.is_contiguous(memory_format=memory_format):
430
+ memory_format = None
431
+
432
+ return TensorMetadata(
433
+ dtype=t.dtype,
434
+ shape=t.shape,
435
+ stride=t.stride() if t.layout == torch.strided else (),
436
+ device=t.device,
437
+ layout=t.layout,
438
+ memory_format=memory_format,
439
+ storage_offset=t.storage_offset(),
440
+ requires_grad=t.requires_grad,
441
+ is_quantized=t.is_quantized,
442
+ is_conj=t.is_conj(),
443
+ is_neg=t.is_neg(),
444
+ is_coalesced=t.is_coalesced() if t.is_sparse else False,
445
+ dense_dim=t.dense_dim() if t.is_sparse else False,
446
+ sparse_dim=t.sparse_dim() if t.is_sparse else False,
447
+ )
448
+
449
+
450
+ def _ident(x: Any) -> Any:
451
+ return x
452
+
453
+
454
+ def _reduce_fake_tensor(t):
455
+ """
456
+ See FxGraphCachePickler. Custom reducer to pickle FakeTensors.
457
+ """
458
+ metadata = extract_tensor_metadata(t)
459
+ return (_ident, (metadata,))
460
+
461
+
462
+ def _reduce_tensor(t):
463
+ """
464
+ See FxGraphCachePickler. Custom reducer to pickle Tensors.
465
+ """
466
+ # If we see tensors, we know they're contstants stored as attributes on
467
+ # the GraphModule. See tensor lowering; small constants are inlined. If
468
+ # we see a small tensor, therefore, no reference will ultimately remain
469
+ # in the generated code. So we need to include its value in the cache key.
470
+ # Large constannts are effectively treated as inputs and we consider only
471
+ # their metadata.
472
+ metadata = extract_tensor_metadata(t)
473
+ if len(t.shape) == 0 or torch._inductor.graph.GraphLowering.can_inline_constant(t):
474
+ return (_ident, (TensorMetadataAndValues(metadata, t.tolist()),))
475
+ else:
476
+ return (_ident, (metadata,))
477
+
478
+
479
+ def _reduce_symint(s):
480
+ """
481
+ See FxGraphCachePickler. Custom reducer to pickle SymInts.
482
+ """
483
+ # For hashing purposes, we only care about the name of the symbol and
484
+ # not the backed value. We evaluate guards stored with a cached graph
485
+ # to ensure a cached entity with SymInt args is safe to reuse.
486
+ return (_ident, (str(s),))
487
+
488
+
489
+ class FxGraphCachePickler(pickle.Pickler):
490
+ """
491
+ Custom pickler to customize the pickling of some objects (Tensors), only for the
492
+ purpose of computing a hash for keying into the FxGraphCache. Tensors contain
493
+ objects that don't pickle and/or vary between runs, and we want to capture the
494
+ data that allow us to compute a stable, but safe hash.
495
+ """
496
+
497
+ dispatch_table = copyreg.dispatch_table.copy()
498
+ dispatch_table[torch._subclasses.fake_tensor.FakeTensor] = _reduce_fake_tensor
499
+ dispatch_table[torch.Tensor] = _reduce_tensor
500
+ dispatch_table[torch.SymInt] = _reduce_symint
501
+
502
+ @staticmethod
503
+ def dumps(obj) -> bytes:
504
+ """
505
+ Pickle an object using the FxGraphCachePickler.
506
+ """
507
+ with io.BytesIO() as stream:
508
+ pickler = FxGraphCachePickler(stream)
509
+ pickler.dump(obj)
510
+ return stream.getvalue()
511
+
512
+ @staticmethod
513
+ def get_hash(obj: Any) -> str:
514
+ """
515
+ Serialize an object using the FxGraphCachePickler and return a hash
516
+ of the pickled object.
517
+ """
518
+ serialized_data = FxGraphCachePickler.dumps(obj)
519
+ return sha256_hash(serialized_data)
520
+
521
+
522
+ @functools.lru_cache(None)
523
+ def get_inductor_code_hash() -> bytes:
524
+ """
525
+ Compute a hash of all inductor code modules. Used by the FxGraph cache
526
+ so any inductor code changes would result in new cache keys.
527
+ """
528
+ inductor_root = os.path.dirname(__file__)
529
+
530
+ contents: Dict[str, bytes] = {}
531
+ for lib in pkgutil.iter_modules([inductor_root]):
532
+ spec = lib.module_finder.find_spec(lib.name, None)
533
+ assert spec is not None
534
+ module = spec.origin
535
+ assert module is not None
536
+ with open(module, "rb") as f:
537
+ contents[module] = f.read()
538
+
539
+ return hashlib.sha256(pickle.dumps(contents)).digest()
540
+
541
+
542
+ @dataclasses.dataclass
543
+ class OrderedSetHolder:
544
+ """
545
+ See FxGraphHashDetails. Holds a sorted list to support stable hashing
546
+ of set kwargs.
547
+ """
548
+
549
+ items: List[Any]
550
+
551
+
552
+ class FxGraphHashDetails:
553
+ """
554
+ Object to capture all the details for a compiled FX graph relevant to computing
555
+ a safe and stable cache key.
556
+ """
557
+
558
+ # Excluded kwargs param that are not stable between runs
559
+ EXCLUDED_KWARGS = ["graph_id"]
560
+
561
+ def __init__(
562
+ self,
563
+ gm: torch.fx.GraphModule,
564
+ example_inputs: List[torch.Tensor],
565
+ fx_kwargs: Dict[str, Any],
566
+ ):
567
+ self.gm = gm
568
+ self.example_inputs = example_inputs
569
+
570
+ # Order kwargs so hashing is stable to changes in kwarg order.
571
+ self.fx_kwargs = {}
572
+ for k in sorted(fx_kwargs):
573
+ if k not in self.EXCLUDED_KWARGS:
574
+ if type(fx_kwargs[k]) is set:
575
+ # Special case to handle set params. Python sets can't be
576
+ # ordered, so sort the elements and store them in a proxy.
577
+ self.fx_kwargs[k] = OrderedSetHolder(sorted(fx_kwargs[k]))
578
+ else:
579
+ self.fx_kwargs[k] = fx_kwargs[k]
580
+
581
+ # Also hash on various system info (including the triton compiler version), as
582
+ # well as the inductor configuration and code.
583
+ self.torch_version = torch.__version__
584
+ self.system_info = CacheBase.get_system()
585
+
586
+ self.inductor_config = config.save_config()
587
+ self.inductor_code_hash = get_inductor_code_hash()
588
+
589
+ def debug_str(self) -> str:
590
+ """
591
+ Get a printable string describing in more detail all the attributes
592
+ comprising this object. Useful for debugging when one graph hashes
593
+ to a different value than another.
594
+ """
595
+
596
+ def get_str(obj) -> str:
597
+ if isinstance(obj, torch.Tensor):
598
+ return str(extract_tensor_metadata(obj))
599
+ elif isinstance(obj, bytes):
600
+ return "<bytes>"
601
+ else:
602
+ return str(obj)
603
+
604
+ lines = []
605
+ for attr, obj in vars(self).items():
606
+ if isinstance(obj, list):
607
+ for ii in range(len(obj)):
608
+ h = FxGraphCachePickler.get_hash(obj[ii])
609
+ lines.append(f"[{h}] {attr}[{ii}]: {get_str(obj[ii])}")
610
+ elif isinstance(obj, dict):
611
+ for k, v in obj.items():
612
+ h = FxGraphCachePickler.get_hash(v)
613
+ lines.append(f"[{h}] {attr}[{k}]: {get_str(v)}")
614
+ else:
615
+ h = FxGraphCachePickler.get_hash(obj)
616
+ lines.append(f"[{h}] {attr}: {get_str(obj)}")
617
+ return "\n".join(lines)
618
+
619
+
620
+ def compiled_fx_graph_hash(
621
+ gm: torch.fx.GraphModule,
622
+ example_inputs: List[torch.Tensor],
623
+ fx_kwargs: Dict[str, Any],
624
+ ) -> str:
625
+ """
626
+ Generate a unique hash of the FX graph for caching.
627
+ """
628
+ details = FxGraphHashDetails(gm, example_inputs, fx_kwargs)
629
+ # The prefix distinguishes among the other kinds of objects we
630
+ # cache in this module.
631
+ key = "f" + FxGraphCachePickler.get_hash(details)
632
+ log.debug("FX graph cache hash details for key %s:\n%s", key, details.debug_str())
633
+ return key
634
+
635
+
636
+ class FxGraphCache:
637
+ """
638
+ Supports caching and reusing compiled Fx graphs.
639
+
640
+ The overall strategy is as follows:
641
+ - This cache stores entries on disk. When saving an entry, we can't
642
+ serialize callables (that could be C++, Triton, etc.), so we serialize
643
+ their own disk cache location. We then recreate the compiled artifact
644
+ after fetching from disk.
645
+ - For indexing the cache, we gather the fields relevant to identifying an
646
+ FxGraph (the graph module, graph inputs, system settings etc.) into an
647
+ FxGraphCacheDetails object, pickle it, and compute a hash for the key.
648
+ See FxGraphCachePickler.
649
+ - Among the metadata we store, we also include a guards expression that's
650
+ appropriate for validating any symbols for Tensor arguments that have
651
+ symbolic bounds. On cache lookup then, we evaluate those guards in the
652
+ current context to validate that a cached entry can be served.
653
+ - A given graph could have multiple compiled versions, corresponding to
654
+ different sets of guards. Therefore, we store cache entries in the form:
655
+ <temp dir>/<fx graph hash>/<serialized metatdata>
656
+ - On lookup, we compute the key from the graph details, iterate over all
657
+ leaf files in the corresponding subdirectory, deserialize the entry, and
658
+ evaluate its guards expression. If the evaluation succeeds, we have a
659
+ cache hit. If it fails, we compile the graph and store a new entry.
660
+ - Finally, on a cache hit, we need to make sure any guards that would
661
+ have been created during compilation are added to the current context.
662
+ """
663
+
664
+ # TODO(masnesral): Investigate whether it's beneficial to store compiled graphs
665
+ # in an in-memory cache after loading from disk.
666
+ @staticmethod
667
+ def _get_tmp_dir() -> str:
668
+ """
669
+ Get the toplevel temporary directory for storing compiled graphs.
670
+ """
671
+ return os.path.join(cache_dir(), "fxgraph")
672
+
673
+ @staticmethod
674
+ def _get_tmp_dir_for_key(key: str) -> str:
675
+ """
676
+ Return the disk location for a given cache key.
677
+ """
678
+ return os.path.join(FxGraphCache._get_tmp_dir(), key[1:3], key)
679
+
680
+ @staticmethod
681
+ def _filter_symints(inputs: List[Any]) -> List[torch.SymInt]:
682
+ """
683
+ Get the SymInt objects from the input list.
684
+ """
685
+ return [s for s in inputs if isinstance(s, torch.SymInt)]
686
+
687
+ @staticmethod
688
+ def _get_shape_env() -> ShapeEnv:
689
+ """
690
+ Helper to get the shape env from the tracing context.
691
+ """
692
+ return torch._guards.TracingContext.get().fake_mode.shape_env
693
+
694
+ @staticmethod
695
+ def _lookup_graph(
696
+ key: str,
697
+ example_inputs: List[torch.Tensor],
698
+ ) -> Optional[CompiledFxGraph]:
699
+ """
700
+ Lookup a compiled graph in the cache by key. On a hit, return the
701
+ deserialized CompiledFxGraph object. On a miss, return None.
702
+ """
703
+ subdir = FxGraphCache._get_tmp_dir_for_key(key)
704
+ if not os.path.exists(subdir):
705
+ return None
706
+
707
+ # Iterate over any entries in the subdir for this key and evaluate
708
+ # their guards to determine whether there's a hit.
709
+ for path in sorted(os.listdir(subdir)):
710
+ with open(os.path.join(subdir, path), "rb") as f:
711
+ graph: CompiledFxGraph = pickle.load(f)
712
+
713
+ guards_expr = graph.guards_expr
714
+ if not guards_expr:
715
+ # No guards to evaluate
716
+ return graph
717
+
718
+ # Evaluate the guard expression in the current context.
719
+ shape_env = FxGraphCache._get_shape_env()
720
+ symints = FxGraphCache._filter_symints(example_inputs)
721
+
722
+ # If there's not a cache hit, we don't want the evaluation to
723
+ # affect the current env, e.g., cause the creation of new guards,
724
+ # so we evaluate with the hints instead of the symbols.
725
+ assert all(has_hint(s) for s in symints)
726
+ hints = [hint_int(s) for s in symints]
727
+ hit = bool(shape_env.evaluate_guards_expression(guards_expr, hints))
728
+ log.debug(
729
+ "fx graph cache key %s evaluating guards for %s with values %s => %s",
730
+ key,
731
+ guards_expr,
732
+ hints,
733
+ hit,
734
+ )
735
+ if hit:
736
+ # Now re-evaluate with the symints to add any guards to the current env.
737
+ check = bool(shape_env.evaluate_guards_expression(guards_expr, symints))
738
+ assert check is True
739
+ log.debug(
740
+ "fx graph cache key %s post-load guards: %s",
741
+ key,
742
+ shape_env.guards,
743
+ )
744
+ return graph
745
+
746
+ return None
747
+
748
+ @staticmethod
749
+ def _save_graph(
750
+ key: str, compiled_graph: CompiledFxGraph, example_inputs: List[torch.Tensor]
751
+ ):
752
+ """
753
+ Store a serialized CompiledFxGraph on disk.
754
+ """
755
+ disk_compiled_graph = copy(compiled_graph)
756
+ # Important as compiled models are not pickleable:
757
+ disk_compiled_graph.compiled_artifact = None
758
+
759
+ # Before serializing, compute the guard expression that will be used to
760
+ # ensure that a CompiledFxGraph is valid when loaded from the cache. It's
761
+ # sufficient to consider only the SymInt args to the fx graph since the
762
+ # Tensor shapes are already captured in the hash for the cache key. Any
763
+ # Tensor arg with a symbolic shape will have a SymInt arg for the graph.
764
+ shape_env = FxGraphCache._get_shape_env()
765
+ symints = FxGraphCache._filter_symints(example_inputs)
766
+ disk_compiled_graph.guards_expr = shape_env.produce_guards_expression(symints)
767
+
768
+ content = pickle.dumps(disk_compiled_graph)
769
+
770
+ subdir = FxGraphCache._get_tmp_dir_for_key(key)
771
+ if not os.path.exists(subdir):
772
+ os.makedirs(subdir, exist_ok=True)
773
+
774
+ # Use a hash of the serialized CompiledFxGraph to get a unique file
775
+ # name. The specific name doesn't matter since a lookup involves
776
+ # iterating over all entries in the parent subdir.
777
+ path = os.path.join(subdir, sha256_hash(content))
778
+ write_atomic(path, content)
779
+
780
+ @staticmethod
781
+ def load(
782
+ compile_fx_fn: Callable[..., Any],
783
+ gm: torch.fx.GraphModule,
784
+ example_inputs: List[torch.Tensor],
785
+ fx_kwargs: Dict[str, Any],
786
+ ):
787
+ """
788
+ Load a compiled graph from the cache. If a cached entry does not exist,
789
+ compile the graph and save it to the cache.
790
+ """
791
+ from filelock import FileLock
792
+
793
+ key = compiled_fx_graph_hash(gm, example_inputs, fx_kwargs)
794
+
795
+ lock_dir = get_lock_dir()
796
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
797
+ with lock:
798
+ compiled_graph = FxGraphCache._lookup_graph(key, example_inputs)
799
+ if compiled_graph is None:
800
+ log.debug("fx graph cache miss for key %s", key)
801
+ counters["inductor"]["fxgraph_cache_miss"] += 1
802
+ compiled_graph = compile_fx_fn(gm, example_inputs, **fx_kwargs)
803
+ FxGraphCache._save_graph(key, compiled_graph, example_inputs)
804
+ else:
805
+ log.debug("fx graph cache hit for key %s", key)
806
+ counters["inductor"]["fxgraph_cache_hit"] += 1
807
+
808
+ return compiled_graph
809
+
810
+ @staticmethod
811
+ def clear():
812
+ """
813
+ Clear out the on-disk cache.
814
+ """
815
+ shutil.rmtree(FxGraphCache._get_tmp_dir())
816
+
817
+
818
+ @dataclasses.dataclass
819
+ class CompiledFxGraph:
820
+ """
821
+ Class holding a compiled FX graph. This is the object serialized on disk
822
+ to support FxGraph caching.
823
+ """
824
+
825
+ compiled_artifact: Optional[Callable[..., Any]] = None
826
+ current_callable: Optional[Callable[..., Any]] = None
827
+ cache_key: Optional[str] = None
828
+ artifact_path: Optional[str] = None
829
+ cache_linemap: Optional[List[Tuple[int, str]]] = None
830
+ device_types: Set[str] = field(default_factory=set)
831
+ device_idxs: Set[int] = field(default_factory=set)
832
+ mutated_inputs: Set[str] = field(default_factory=set)
833
+ mutated_input_idxs: Set[int] = field(default_factory=set)
834
+ constants: Dict[str, torch.Tensor] = field(default_factory=dict)
835
+ output_strides: Optional[List[Optional[Tuple[int, ...]]]] = None
836
+ # This is a string representation of an expression we serialize
837
+ # with the object so the guards can be evaluated in a different
838
+ # context in order to verify the validity of serving a cached
839
+ # fx graph. The expression must be generated by:
840
+ # ShapeEnv.produce_guards_expression()
841
+ guards_expr: Optional[str] = None
842
+
843
+ _boxed_call: Optional[bool] = None
844
+
845
+ def __init__(
846
+ self,
847
+ compiled_artifact: Optional[Callable[..., Any]],
848
+ graph: GraphLowering,
849
+ output_strides: List[Optional[Tuple[int, ...]]],
850
+ ):
851
+ self.compiled_artifact = compiled_artifact
852
+ self.cache_key = graph.cache_key
853
+ self.artifact_path = graph.cache_path
854
+ self.cache_linemap = graph.cache_linemap
855
+ self.device_types = graph.device_types
856
+ self.device_idxs = graph.device_idxs
857
+ self.mutated_inputs = graph.mutated_inputs
858
+ self.mutated_input_idxs = set(graph.mutated_input_idxs)
859
+ self.constants = graph.constants
860
+ self.output_strides = output_strides
861
+ self.guards_expr = None
862
+
863
+ def __call__(self, inputs: List[Any]) -> Any:
864
+ return self.get_current_callable()(inputs)
865
+
866
+ def get_current_callable(self) -> Callable[..., Any]:
867
+ if self.current_callable is None:
868
+ # This prevents a circular reference that makes CompiledFxGraph
869
+ # get stuck without getting garbage collected
870
+ return functools.partial(_run_from_cache, weakref.proxy(self))
871
+ else:
872
+ return self.current_callable
873
+
874
+
875
+ def _run_from_cache(compiled_graph: CompiledFxGraph, inputs: List[Any]) -> Any:
876
+ # We can't really serialize callables that may be C++/Triton/etc.,
877
+ # so we serialize their disk cache location instead
878
+ # TODO: When making an API that can save compiled models e2e to disk
879
+ # this will need to be better
880
+ if compiled_graph.compiled_artifact is None:
881
+ from .codecache import PyCodeCache
882
+
883
+ assert compiled_graph.cache_key
884
+ assert compiled_graph.artifact_path
885
+ compiled_graph.compiled_artifact = PyCodeCache.load_by_key_path(
886
+ compiled_graph.cache_key,
887
+ compiled_graph.artifact_path,
888
+ compiled_graph.cache_linemap,
889
+ compiled_graph.constants,
890
+ ).call
891
+
892
+ return compiled_graph.compiled_artifact(inputs)
893
+
894
+
895
+ def cpp_compiler() -> str:
896
+ if config.is_fbcode():
897
+ return build_paths.cc()
898
+ if isinstance(config.cpp.cxx, (list, tuple)):
899
+ search = tuple(config.cpp.cxx)
900
+ else:
901
+ search = (config.cpp.cxx,)
902
+ return cpp_compiler_search(search)
903
+
904
+
905
+ @functools.lru_cache(1)
906
+ def cpp_compiler_search(search: str) -> str:
907
+ for cxx in search:
908
+ try:
909
+ if cxx is None:
910
+ # gxx package is only available for Linux
911
+ # according to https://anaconda.org/conda-forge/gxx/
912
+ if sys.platform != "linux":
913
+ continue
914
+ # Do not install GXX by default
915
+ if not os.getenv("TORCH_INDUCTOR_INSTALL_GXX"):
916
+ continue
917
+ from filelock import FileLock
918
+
919
+ lock_dir = get_lock_dir()
920
+ lock = FileLock(
921
+ os.path.join(lock_dir, "g++.lock"), timeout=LOCK_TIMEOUT
922
+ )
923
+ with lock:
924
+ cxx = install_gcc_via_conda()
925
+ subprocess.check_output([cxx, "--version"])
926
+ return cxx
927
+ except (subprocess.SubprocessError, FileNotFoundError, ImportError):
928
+ continue
929
+ raise exc.InvalidCxxCompiler()
930
+
931
+
932
+ def install_gcc_via_conda() -> str:
933
+ """On older systems, this is a quick way to get a modern compiler"""
934
+ prefix = os.path.join(cache_dir(), "gcc")
935
+ cxx_path = os.path.join(prefix, "bin", "g++")
936
+ if not os.path.exists(cxx_path):
937
+ log.info("Downloading GCC via conda")
938
+ conda = os.environ.get("CONDA_EXE", "conda")
939
+ if conda is None:
940
+ conda = shutil.which("conda")
941
+ if conda is not None:
942
+ subprocess.check_call(
943
+ [
944
+ conda,
945
+ "create",
946
+ f"--prefix={prefix}",
947
+ "--channel=conda-forge",
948
+ "--quiet",
949
+ "-y",
950
+ "python=3.8",
951
+ "gxx",
952
+ ],
953
+ stdout=subprocess.PIPE,
954
+ )
955
+ return cxx_path
956
+
957
+
958
+ def is_gcc() -> bool:
959
+ return bool(re.search(r"(gcc|g\+\+)", cpp_compiler()))
960
+
961
+
962
+ def is_clang() -> bool:
963
+ return bool(re.search(r"(clang|clang\+\+)", cpp_compiler()))
964
+
965
+
966
+ @functools.lru_cache(None)
967
+ def is_apple_clang() -> bool:
968
+ cxx = cpp_compiler()
969
+ version_string = subprocess.check_output([cxx, "--version"]).decode("utf8")
970
+ return "Apple" in version_string.splitlines()[0]
971
+
972
+
973
+ class VecISA:
974
+ _bit_width: int
975
+ _macro: str
976
+ _arch_flags: str
977
+ _dtype_nelements: Dict[torch.dtype, int]
978
+
979
+ # Note [Checking for Vectorized Support in Inductor]
980
+ # TorchInductor CPU vectorization reuses PyTorch vectorization utility functions
981
+ # Hence, TorchInductor would depend on Sleef* to accelerate mathematical functions
982
+ # like exp, pow, sin, cos and etc.
983
+ # But PyTorch and TorchInductor might use different compilers to build code. If
984
+ # PyTorch uses gcc-7/g++-7 to build the release package, the libtorch_cpu.so
985
+ # will not expose the Sleef* AVX512 symbols since gcc-7/g++-7 cannot pass
986
+ # avx512 check in CMake - FindAVX.cmake. But TorchInductor install the latest
987
+ # gcc/g++ compiler by default while it could support the AVX512 compilation.
988
+ # Therefore, there would be a conflict sleef version between PyTorch and
989
+ # TorchInductor. Hence, we dry-compile the following code to check whether current
990
+ # HW platform and PyTorch both could support AVX512 or AVX2. And suppose ARM
991
+ # also needs the logic
992
+ # In fbcode however, we are using the same compiler for pytorch and for inductor codegen,
993
+ # making the runtime check unnecessary.
994
+ _avx_code = """
995
+ #if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_ZVECTOR)
996
+ #include <ATen/cpu/vec/functional.h>
997
+ #include <ATen/cpu/vec/vec.h>
998
+ #endif
999
+
1000
+ __attribute__((aligned(64))) float in_out_ptr0[16] = {0.0};
1001
+
1002
+ extern "C" void __avx_chk_kernel() {
1003
+ auto tmp0 = at::vec::Vectorized<float>(1);
1004
+ auto tmp1 = tmp0.exp();
1005
+ tmp1.store(in_out_ptr0);
1006
+ }
1007
+ """
1008
+
1009
+ _avx_py_load = """
1010
+ import torch
1011
+ from ctypes import cdll
1012
+ cdll.LoadLibrary("__lib_path__")
1013
+ """
1014
+
1015
+ def bit_width(self) -> int:
1016
+ return self._bit_width
1017
+
1018
+ def nelements(self, dtype: torch.dtype = torch.float) -> int:
1019
+ return self._dtype_nelements[dtype]
1020
+
1021
+ def build_macro(self) -> str:
1022
+ return self._macro
1023
+
1024
+ def build_arch_flags(self) -> str:
1025
+ return self._arch_flags
1026
+
1027
+ def __hash__(self) -> int:
1028
+ return hash(str(self))
1029
+
1030
+ @functools.lru_cache(None)
1031
+ def __bool__(self) -> bool:
1032
+ if config.cpp.vec_isa_ok is not None:
1033
+ return config.cpp.vec_isa_ok
1034
+
1035
+ if config.is_fbcode():
1036
+ return True
1037
+
1038
+ key, input_path = write(VecISA._avx_code, "cpp")
1039
+ from filelock import FileLock
1040
+
1041
+ lock_dir = get_lock_dir()
1042
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
1043
+ with lock:
1044
+ output_path = input_path[:-3] + "so"
1045
+ build_cmd = shlex.split(
1046
+ cpp_compile_command(
1047
+ input_path, output_path, warning_all=False, vec_isa=self
1048
+ )
1049
+ )
1050
+ try:
1051
+ # Check build result
1052
+ compile_file(input_path, output_path, build_cmd)
1053
+ subprocess.check_call(
1054
+ [
1055
+ sys.executable,
1056
+ "-c",
1057
+ VecISA._avx_py_load.replace("__lib_path__", output_path),
1058
+ ],
1059
+ stderr=subprocess.DEVNULL,
1060
+ env={**os.environ, "PYTHONPATH": ":".join(sys.path)},
1061
+ )
1062
+ except Exception as e:
1063
+ return False
1064
+
1065
+ return True
1066
+
1067
+
1068
+ @dataclasses.dataclass
1069
+ class VecAVX512(VecISA):
1070
+ _bit_width = 512
1071
+ _macro = "-DCPU_CAPABILITY_AVX512"
1072
+ _arch_flags = "-mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma"
1073
+ _dtype_nelements = {torch.float: 16, torch.bfloat16: 32, torch.float16: 32}
1074
+
1075
+ def __str__(self) -> str:
1076
+ return "avx512"
1077
+
1078
+ __hash__: Callable[[VecISA], Any] = VecISA.__hash__
1079
+
1080
+
1081
+ @dataclasses.dataclass
1082
+ class VecAVX2(VecISA):
1083
+ _bit_width = 256
1084
+ _macro = "-DCPU_CAPABILITY_AVX2"
1085
+ _arch_flags = "-mavx2 -mfma"
1086
+ _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16}
1087
+
1088
+ def __str__(self) -> str:
1089
+ return "avx2"
1090
+
1091
+ __hash__: Callable[[VecISA], Any] = VecISA.__hash__
1092
+
1093
+
1094
+ @dataclasses.dataclass
1095
+ class VecZVECTOR(VecISA):
1096
+ _bit_width = 256
1097
+ _macro = "-DCPU_CAPABILITY_ZVECTOR -DCPU_CAPABILITY=ZVECTOR -DHAVE_ZVECTOR_CPU_DEFINITION"
1098
+ _arch_flags = "-mvx -mzvector"
1099
+ _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16}
1100
+
1101
+ def __str__(self) -> str:
1102
+ return "zvector"
1103
+
1104
+ __hash__: Callable[[VecISA], Any] = VecISA.__hash__
1105
+
1106
+
1107
+ class InvalidVecISA(VecISA):
1108
+ _bit_width = 0
1109
+ _macro = ""
1110
+ _arch_flags = ""
1111
+ _dtype_nelements = {}
1112
+
1113
+ def __str__(self) -> str:
1114
+ return "INVALID_VEC_ISA"
1115
+
1116
+ def __bool__(self) -> bool: # type: ignore[override]
1117
+ return False
1118
+
1119
+ __hash__: Callable[[VecISA], Any] = VecISA.__hash__
1120
+
1121
+
1122
+ invalid_vec_isa = InvalidVecISA()
1123
+ supported_vec_isa_list = [VecAVX512(), VecAVX2()]
1124
+
1125
+
1126
+ # Cache the cpuinfo to avoid I/O overhead. Meanwhile, the cpuinfo content
1127
+ # might have too much redundant content that is useless for ISA check. Hence,
1128
+ # we only cache some key isa information.
1129
+ @functools.lru_cache(None)
1130
+ def valid_vec_isa_list() -> List[VecISA]:
1131
+ if sys.platform != "linux":
1132
+ return []
1133
+
1134
+ if platform.machine() == "s390x":
1135
+ return [VecZVECTOR()]
1136
+
1137
+ isa_list = []
1138
+ with open("/proc/cpuinfo") as _cpu_info:
1139
+ _cpu_info_content = _cpu_info.read()
1140
+ for isa in supported_vec_isa_list:
1141
+ if str(isa) in _cpu_info_content and isa:
1142
+ isa_list.append(isa)
1143
+ return isa_list
1144
+
1145
+
1146
+ def pick_vec_isa() -> VecISA:
1147
+ if config.is_fbcode():
1148
+ return VecAVX2()
1149
+
1150
+ _valid_vec_isa_list: List[VecISA] = valid_vec_isa_list()
1151
+ if not _valid_vec_isa_list:
1152
+ return invalid_vec_isa
1153
+
1154
+ # If the simdlen is None, it indicates determin the vectorization length automatically
1155
+ if config.cpp.simdlen is None:
1156
+ assert _valid_vec_isa_list
1157
+ return _valid_vec_isa_list[0]
1158
+
1159
+ for isa in _valid_vec_isa_list:
1160
+ if config.cpp.simdlen == isa.bit_width():
1161
+ return isa
1162
+
1163
+ return invalid_vec_isa
1164
+
1165
+
1166
+ def get_compile_only(compile_only: bool = True) -> str:
1167
+ return "-c" if compile_only else ""
1168
+
1169
+
1170
+ def get_shared(shared: bool = True) -> str:
1171
+ return "-shared -fPIC" if shared else ""
1172
+
1173
+
1174
+ def get_warning_all_flag(warning_all: bool = True) -> str:
1175
+ return "-Wall" if warning_all else ""
1176
+
1177
+
1178
+ def get_glibcxx_abi_build_flags() -> str:
1179
+ return "-D_GLIBCXX_USE_CXX11_ABI=" + str(int(torch._C._GLIBCXX_USE_CXX11_ABI))
1180
+
1181
+
1182
+ def cpp_flags() -> str:
1183
+ flags = ["-std=c++17", "-Wno-unused-variable", "-Wno-unknown-pragmas"]
1184
+ if is_clang():
1185
+ flags.append("-Werror=ignored-optimization-argument")
1186
+ return " ".join(flags)
1187
+
1188
+
1189
+ def cpp_wrapper_flags() -> str:
1190
+ return "-DTORCH_INDUCTOR_CPP_WRAPPER"
1191
+
1192
+
1193
+ def optimization_flags() -> str:
1194
+ base_flags = "-O0 -g" if config.aot_inductor.debug_compile else "-O3 -DNDEBUG"
1195
+ base_flags += " -ffast-math -fno-finite-math-only"
1196
+ if not config.cpp.enable_unsafe_math_opt_flag:
1197
+ base_flags += " -fno-unsafe-math-optimizations"
1198
+
1199
+ if config.is_fbcode():
1200
+ # FIXME: passing `-fopenmp` adds libgomp.so to the generated shared library's dependencies.
1201
+ # This causes `ldopen` to fail in fbcode, because libgomp does not exist in the default paths.
1202
+ # We will fix it later by exposing the lib path.
1203
+ return base_flags
1204
+
1205
+ if sys.platform == "darwin":
1206
+ # Per https://mac.r-project.org/openmp/ right way to pass `openmp` flags to MacOS is via `-Xclang`
1207
+ # Also, `-march=native` is unrecognized option on M1
1208
+ base_flags += " -Xclang"
1209
+ else:
1210
+ if platform.machine() == "ppc64le":
1211
+ base_flags += " -mcpu=native"
1212
+ else:
1213
+ base_flags += " -march=native"
1214
+
1215
+ # Internal cannot find libgomp.so
1216
+ if not config.is_fbcode():
1217
+ base_flags += " -fopenmp"
1218
+ return base_flags
1219
+
1220
+
1221
+ def use_custom_generated_macros() -> str:
1222
+ return "-D C10_USING_CUSTOM_GENERATED_MACROS"
1223
+
1224
+
1225
+ def use_fb_internal_macros() -> str:
1226
+ if config.is_fbcode():
1227
+ openmp_lib = build_paths.openmp_lib()
1228
+ preprocessor_flags = " ".join(
1229
+ (
1230
+ "-D C10_USE_GLOG",
1231
+ "-D C10_USE_MINIMAL_GLOG",
1232
+ "-D C10_DISABLE_TENSORIMPL_EXTENSIBILITY",
1233
+ )
1234
+ )
1235
+ return f"-Wp,-fopenmp {openmp_lib} {preprocessor_flags}"
1236
+ else:
1237
+ return ""
1238
+
1239
+
1240
+ def use_standard_sys_dir_headers() -> str:
1241
+ if config.is_fbcode():
1242
+ return "-nostdinc"
1243
+ else:
1244
+ return ""
1245
+
1246
+
1247
+ @functools.lru_cache(None)
1248
+ def is_conda_llvm_openmp_installed() -> bool:
1249
+ try:
1250
+ command = "conda list llvm-openmp --json"
1251
+ output = subprocess.check_output(command.split()).decode("utf8")
1252
+ return len(json.loads(output)) > 0
1253
+ except subprocess.SubprocessError:
1254
+ return False
1255
+
1256
+
1257
+ @functools.lru_cache(None)
1258
+ def homebrew_libomp() -> Tuple[bool, str]:
1259
+ try:
1260
+ # check if `brew` is installed
1261
+ subprocess.check_output(["which", "brew"])
1262
+ # get the location of `libomp` if it is installed
1263
+ # this is the location that `libomp` **would** be installed
1264
+ # see https://github.com/Homebrew/brew/issues/10261#issuecomment-756563567 for details
1265
+ libomp_path = (
1266
+ subprocess.check_output(["brew", "--prefix", "libomp"])
1267
+ .decode("utf8")
1268
+ .strip()
1269
+ )
1270
+ # check if `libomp` is installed
1271
+ omp_available = os.path.exists(libomp_path)
1272
+ return omp_available, libomp_path
1273
+ except subprocess.SubprocessError:
1274
+ return False, ""
1275
+
1276
+
1277
+ def get_include_and_linking_paths(
1278
+ include_pytorch: bool = False,
1279
+ vec_isa: VecISA = invalid_vec_isa,
1280
+ cuda: bool = False,
1281
+ aot_mode: bool = False,
1282
+ ) -> Tuple[List[str], str, str, str, str]:
1283
+ if (
1284
+ config.is_fbcode()
1285
+ and "CUDA_HOME" not in os.environ
1286
+ and "CUDA_PATH" not in os.environ
1287
+ ):
1288
+ os.environ["CUDA_HOME"] = os.path.dirname(build_paths.cuda())
1289
+ from torch.utils import cpp_extension
1290
+
1291
+ macros = ""
1292
+ build_arch_flags = ""
1293
+ if sys.platform == "linux" and (
1294
+ include_pytorch
1295
+ or vec_isa != invalid_vec_isa
1296
+ or cuda
1297
+ or config.cpp.enable_kernel_profile
1298
+ ):
1299
+ # Note - We include pytorch only on linux right now. There is more work
1300
+ # to do to enable OMP build on darwin where PyTorch is built with IOMP
1301
+ # and we need a way to link to what PyTorch links.
1302
+ ipaths = cpp_extension.include_paths(cuda) + [sysconfig.get_path("include")]
1303
+ lpaths = cpp_extension.library_paths(cuda) + [
1304
+ sysconfig.get_config_var("LIBDIR")
1305
+ ]
1306
+
1307
+ libs = []
1308
+
1309
+ # No need to manually specify libraries in fbcode.
1310
+ if not config.is_fbcode():
1311
+ libs += ["torch", "torch_cpu"]
1312
+ libs += ["gomp"]
1313
+ if not aot_mode:
1314
+ libs += ["torch_python"]
1315
+ else:
1316
+ # internal remote execution is able to find omp, but not gomp
1317
+ libs += ["omp"]
1318
+ if aot_mode:
1319
+ ipaths += [os.path.dirname(cpp_prefix_path())]
1320
+ if cuda:
1321
+ # This is a special treatment for Meta internal cuda-12 where all libs
1322
+ # are in lib/cuda-12 and lib/cuda-12/stubs
1323
+ for i, path in enumerate(lpaths):
1324
+ if path.startswith(
1325
+ os.environ["CUDA_HOME"]
1326
+ ) and not os.path.exists(f"{path}/libcudart_static.a"):
1327
+ for root, dirs, files in os.walk(path):
1328
+ if "libcudart_static.a" in files:
1329
+ lpaths[i] = os.path.join(path, root)
1330
+ lpaths.append(os.path.join(lpaths[i], "stubs"))
1331
+ break
1332
+ macros = vec_isa.build_macro()
1333
+ if macros:
1334
+ if config.is_fbcode() and vec_isa != invalid_vec_isa:
1335
+ cap = str(vec_isa).upper()
1336
+ macros = " ".join(
1337
+ [
1338
+ vec_isa.build_arch_flags(),
1339
+ f"-D CPU_CAPABILITY={cap}",
1340
+ f"-D CPU_CAPABILITY_{cap}",
1341
+ f"-D HAVE_{cap}_CPU_DEFINITION",
1342
+ ]
1343
+ )
1344
+
1345
+ if aot_mode and cuda:
1346
+ if macros is None:
1347
+ macros = ""
1348
+ macros += " -D USE_CUDA"
1349
+
1350
+ if cuda:
1351
+ if torch.version.hip is not None:
1352
+ libs += ["c10_hip", "torch_hip"]
1353
+ else:
1354
+ if config.is_fbcode():
1355
+ libs += ["cuda"]
1356
+ else:
1357
+ libs += ["c10_cuda", "cuda", "torch_cuda"]
1358
+ build_arch_flags = vec_isa.build_arch_flags()
1359
+ else:
1360
+ # Note - this is effectively a header only inclusion. Usage of some header files may result in
1361
+ # symbol not found, if those header files require a library.
1362
+ # For those cases, include the lpath and libs command as we do for pytorch above.
1363
+ # This approach allows us to only pay for what we use.
1364
+ ipaths = cpp_extension.include_paths(cuda) + [sysconfig.get_path("include")]
1365
+ if aot_mode:
1366
+ ipaths += [os.path.dirname(cpp_prefix_path())]
1367
+ lpaths = []
1368
+ if sys.platform == "darwin":
1369
+ # only Apple builtin compilers (Apple Clang++) require openmp
1370
+ omp_available = not is_apple_clang()
1371
+
1372
+ # check the `OMP_PREFIX` environment first
1373
+ if os.getenv("OMP_PREFIX") is not None:
1374
+ header_path = os.path.join(os.getenv("OMP_PREFIX"), "include", "omp.h")
1375
+ valid_env = os.path.exists(header_path)
1376
+ if valid_env:
1377
+ ipaths.append(os.path.join(os.getenv("OMP_PREFIX"), "include"))
1378
+ lpaths.append(os.path.join(os.getenv("OMP_PREFIX"), "lib"))
1379
+ else:
1380
+ warnings.warn("environment variable `OMP_PREFIX` is invalid.")
1381
+ omp_available = omp_available or valid_env
1382
+
1383
+ libs = [] if omp_available else ["omp"]
1384
+
1385
+ # prefer to use openmp from `conda install llvm-openmp`
1386
+ if not omp_available and os.getenv("CONDA_PREFIX") is not None:
1387
+ omp_available = is_conda_llvm_openmp_installed()
1388
+ if omp_available:
1389
+ conda_lib_path = os.path.join(os.getenv("CONDA_PREFIX"), "lib")
1390
+ ipaths.append(os.path.join(os.getenv("CONDA_PREFIX"), "include"))
1391
+ lpaths.append(conda_lib_path)
1392
+ # Prefer Intel OpenMP on x86 machine
1393
+ if os.uname().machine == "x86_64" and os.path.exists(
1394
+ os.path.join(conda_lib_path, "libiomp5.dylib")
1395
+ ):
1396
+ libs = ["iomp5"]
1397
+
1398
+ # next, try to use openmp from `brew install libomp`
1399
+ if not omp_available:
1400
+ omp_available, libomp_path = homebrew_libomp()
1401
+ if omp_available:
1402
+ ipaths.append(os.path.join(libomp_path, "include"))
1403
+ lpaths.append(os.path.join(libomp_path, "lib"))
1404
+
1405
+ # if openmp is still not available, we let the compiler to have a try,
1406
+ # and raise error together with instructions at compilation error later
1407
+ else:
1408
+ libs = ["omp"] if config.is_fbcode() else ["gomp"]
1409
+
1410
+ # Unconditionally import c10 for non-abi-compatible mode to use TORCH_CHECK - See PyTorch #108690
1411
+ if not config.aot_inductor.abi_compatible:
1412
+ libs += ["c10"]
1413
+ lpaths += [cpp_extension.TORCH_LIB_PATH]
1414
+
1415
+ # third party libs
1416
+ if config.is_fbcode():
1417
+ ipaths.append(build_paths.sleef())
1418
+ ipaths.append(build_paths.openmp())
1419
+ ipaths.append(build_paths.cc_include())
1420
+ ipaths.append(build_paths.libgcc())
1421
+ ipaths.append(build_paths.libgcc_arch())
1422
+ ipaths.append(build_paths.libgcc_backward())
1423
+ ipaths.append(build_paths.glibc())
1424
+ ipaths.append(build_paths.linux_kernel())
1425
+ ipaths.append(build_paths.cuda())
1426
+ # We also need to bundle includes with absolute paths into a remote directory
1427
+ # (later on, we copy the include paths from cpp_extensions into our remote dir)
1428
+ ipaths.append("include")
1429
+
1430
+ static_link_libs = []
1431
+ if aot_mode and cuda and config.is_fbcode():
1432
+ # For Meta internal cuda-12, it is recommended to static link cudart
1433
+ static_link_libs = ["-Wl,-Bstatic", "-lcudart_static", "-Wl,-Bdynamic"]
1434
+
1435
+ lpaths_str = " ".join(["-L" + p for p in lpaths])
1436
+ libs_str = " ".join(static_link_libs + ["-l" + p for p in libs])
1437
+ return ipaths, lpaths_str, libs_str, macros, build_arch_flags
1438
+
1439
+
1440
+ def cpp_compile_command(
1441
+ input: Union[str, List[str]],
1442
+ output: str,
1443
+ warning_all: bool = True,
1444
+ shared: bool = True,
1445
+ include_pytorch: bool = False,
1446
+ vec_isa: VecISA = invalid_vec_isa,
1447
+ cuda: bool = False,
1448
+ aot_mode: bool = False,
1449
+ compile_only: bool = False,
1450
+ use_absolute_path: bool = False,
1451
+ ) -> str:
1452
+ ipaths, lpaths, libs, macros, build_arch_flags = get_include_and_linking_paths(
1453
+ include_pytorch, vec_isa, cuda, aot_mode
1454
+ )
1455
+ if isinstance(input, str):
1456
+ input = [input]
1457
+ ipaths_str = " ".join(["-I" + p for p in ipaths])
1458
+ clang_flags = ""
1459
+ if config.is_fbcode():
1460
+ if aot_mode and not use_absolute_path:
1461
+ inp_name = input
1462
+ out_name = output
1463
+ else:
1464
+ # We need to copy any absolute-path torch includes
1465
+ inp_name = [os.path.basename(i) for i in input]
1466
+ out_name = os.path.basename(output)
1467
+ assert is_clang()
1468
+ # Use clang runtime instead of libgcc
1469
+ clang_flags += " --rtlib=compiler-rt"
1470
+ clang_flags += " -fuse-ld=lld"
1471
+ linker_paths = "-B" + build_paths.glibc_lib()
1472
+ linker_paths += " -L" + build_paths.glibc_lib()
1473
+ else:
1474
+ inp_name = input
1475
+ out_name = output
1476
+ linker_paths = "" # let the compiler pick
1477
+ inp_name_str = " ".join(inp_name)
1478
+ return re.sub(
1479
+ r"[ \n]+",
1480
+ " ",
1481
+ f"""
1482
+ {cpp_compiler()} {inp_name_str} {get_shared(shared)}
1483
+ {get_warning_all_flag(warning_all)} {cpp_flags()}
1484
+ {get_glibcxx_abi_build_flags()}
1485
+ {ipaths_str} {lpaths} {libs} {build_arch_flags}
1486
+ {macros} {linker_paths} {clang_flags}
1487
+ {optimization_flags()}
1488
+ {use_custom_generated_macros()}
1489
+ {use_fb_internal_macros()}
1490
+ {use_standard_sys_dir_headers()}
1491
+ {get_compile_only(compile_only)}
1492
+ -o {out_name}
1493
+ """,
1494
+ ).strip()
1495
+
1496
+
1497
+ def run_command_and_check(cmd: str):
1498
+ cmd = shlex.split(cmd)
1499
+ try:
1500
+ subprocess.check_call(cmd)
1501
+ except subprocess.CalledProcessError as e:
1502
+ raise exc.CppCompileError(cmd, e.output) from e
1503
+
1504
+
1505
+ @functools.lru_cache(None)
1506
+ def split_aot_inductor_output_path(path: str) -> Tuple[str, str]:
1507
+ """Returns the path where the AOT Inductor compiled kernels are stored."""
1508
+ if path.endswith(".so"):
1509
+ return os.path.split(path)
1510
+ else:
1511
+ return path, ""
1512
+
1513
+
1514
+ class CudaKernelParamCache:
1515
+ cache: Dict[str, Dict[str, str]] = dict()
1516
+ clear = staticmethod(cache.clear)
1517
+
1518
+ @classmethod
1519
+ def set(cls, key: str, params: Dict[str, str], cubin: str) -> None:
1520
+ bin_type = "cubin" if torch.version.hip is None else "hsaco"
1521
+ _, path = write(
1522
+ cubin,
1523
+ bin_type,
1524
+ hash_type=bin_type,
1525
+ specified_dir=split_aot_inductor_output_path(
1526
+ config.aot_inductor.output_path
1527
+ )[0],
1528
+ )
1529
+
1530
+ params[get_cpp_wrapper_cubin_path_name()] = path
1531
+
1532
+ cls.cache[key] = params
1533
+
1534
+ @classmethod
1535
+ def get(cls, key: str) -> Optional[Dict[str, str]]:
1536
+ return cls.cache.get(key, None)
1537
+
1538
+
1539
+ class AotCodeCache:
1540
+ cache: Dict[str, str] = dict()
1541
+ clear = staticmethod(cache.clear)
1542
+
1543
+ @classmethod
1544
+ def compile(
1545
+ cls,
1546
+ graph: GraphLowering,
1547
+ source_code: str,
1548
+ serialized_extern_kernel_nodes: Optional[str],
1549
+ cuda: bool,
1550
+ ) -> str:
1551
+ picked_vec_isa = pick_vec_isa()
1552
+ cpp_command = repr(
1553
+ cpp_compile_command(
1554
+ "i", "o", vec_isa=picked_vec_isa, cuda=cuda, aot_mode=graph.aot_mode
1555
+ )
1556
+ )
1557
+ fbcode_aot_cpu_re = False
1558
+ use_absolute_path = False
1559
+ if config.is_fbcode():
1560
+ ld_command = build_paths.ld()
1561
+ if not cuda and graph.aot_mode: # Meta internal AOTInductor CPU
1562
+ objcopy_command = build_paths.objcopy_fallback()
1563
+ fbcode_aot_cpu_re = True
1564
+ use_absolute_path = True
1565
+ else:
1566
+ objcopy_command = build_paths.objcopy()
1567
+ else:
1568
+ ld_command = "ld"
1569
+ objcopy_command = "objcopy"
1570
+
1571
+ (
1572
+ specified_output_path,
1573
+ specified_so_name,
1574
+ ) = split_aot_inductor_output_path(config.aot_inductor.output_path)
1575
+ key, input_path = write(
1576
+ source_code,
1577
+ "cpp",
1578
+ extra=cpp_command,
1579
+ specified_dir=specified_output_path,
1580
+ )
1581
+
1582
+ if key not in cls.cache or (
1583
+ specified_output_path
1584
+ and os.path.dirname(cls.cache[key]) != specified_output_path
1585
+ or specified_so_name
1586
+ and os.path.basename(cls.cache[key]) != specified_so_name
1587
+ ):
1588
+ from filelock import FileLock
1589
+
1590
+ lock_dir = get_lock_dir()
1591
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
1592
+ with lock:
1593
+ # Currently, this only support serializing extern nodes in fbcode
1594
+ # Eventually, we should also have a serializer for OSS.
1595
+ if config.is_fbcode() and serialized_extern_kernel_nodes:
1596
+ output_json = os.path.splitext(input_path)[0] + ".json"
1597
+ with open(output_json, "w") as f:
1598
+ f.write(serialized_extern_kernel_nodes)
1599
+
1600
+ output_so = (
1601
+ config.aot_inductor.output_path
1602
+ if specified_so_name
1603
+ else os.path.splitext(input_path)[0] + ".so"
1604
+ )
1605
+
1606
+ if not os.path.exists(output_so):
1607
+ output_o = os.path.splitext(input_path)[0] + ".o"
1608
+ cmd = cpp_compile_command(
1609
+ input=input_path,
1610
+ output=output_o,
1611
+ vec_isa=picked_vec_isa,
1612
+ cuda=cuda,
1613
+ aot_mode=graph.aot_mode,
1614
+ compile_only=True,
1615
+ use_absolute_path=use_absolute_path,
1616
+ )
1617
+ log.debug("aot compilation command: %s", cmd)
1618
+ if fbcode_aot_cpu_re:
1619
+ compile_file(input_path, output_o, cmd.split())
1620
+ os.chmod(output_o, 0o644)
1621
+ else:
1622
+ run_command_and_check(cmd)
1623
+
1624
+ def _to_bytes(t: torch.Tensor) -> bytes:
1625
+ # This serializes the tensor's untyped_storage to bytes by accessing
1626
+ # the raw data of the underlying structure.
1627
+ import ctypes
1628
+
1629
+ if t.numel() == 0:
1630
+ return b""
1631
+
1632
+ t_cpu = t.untyped_storage().cpu()
1633
+ raw_array = ctypes.cast(
1634
+ t_cpu.data_ptr(),
1635
+ ctypes.POINTER(ctypes.c_ubyte * t_cpu.nbytes()),
1636
+ )
1637
+
1638
+ return bytes(raw_array.contents)
1639
+
1640
+ aot_constants = b"".join(
1641
+ _to_bytes(tensor) for tensor in graph.constants.values()
1642
+ )
1643
+
1644
+ consts_key, consts_path = write(
1645
+ aot_constants,
1646
+ "bin",
1647
+ specified_dir=specified_output_path,
1648
+ )
1649
+
1650
+ consts_o = os.path.splitext(consts_path)[0] + ".o"
1651
+ if fbcode_aot_cpu_re:
1652
+ cmd = f"{ld_command} -r -b binary -o {os.path.basename(consts_o)} {os.path.basename(consts_path)}"
1653
+ compile_file(consts_path, consts_o, cmd.split())
1654
+ os.chmod(consts_o, 0o644)
1655
+ else:
1656
+ cmd = f"{ld_command} -r -b binary -o {consts_o} {consts_path}"
1657
+ run_command_and_check(cmd)
1658
+ log.debug("aot constant binary command: %s", cmd)
1659
+
1660
+ cmd = (
1661
+ f"{objcopy_command} --rename-section"
1662
+ " .data=.lrodata,alloc,load,readonly,data,contents"
1663
+ f" {consts_o} {consts_o}"
1664
+ )
1665
+ log.debug("aot constant obj command: %s", cmd)
1666
+ run_command_and_check(cmd)
1667
+
1668
+ cmd = f"rm {consts_path}"
1669
+ log.debug("aot constant bin removal command: %s", cmd)
1670
+ run_command_and_check(cmd)
1671
+
1672
+ if fbcode_aot_cpu_re:
1673
+ body = re.sub(r"[\W]", "_", os.path.basename(consts_path))
1674
+ else:
1675
+ body = re.sub(r"[\W]", "_", consts_path)
1676
+
1677
+ symbol_list = []
1678
+ symbol_list.append(
1679
+ f"{objcopy_command} --redefine-sym _binary_{body}_start=_binary_constants_bin_start {consts_o}"
1680
+ )
1681
+ symbol_list.append(
1682
+ f"{objcopy_command} --redefine-sym _binary_{body}_size=_binary_constants_bin_size {consts_o}"
1683
+ )
1684
+ symbol_list.append(
1685
+ f"{objcopy_command} --redefine-sym _binary_{body}_end=_binary_constants_bin_end {consts_o}"
1686
+ )
1687
+ log.debug(
1688
+ "aot constant binary redefine symbol: %s", " ".join(symbol_list)
1689
+ )
1690
+ for cmd in symbol_list:
1691
+ run_command_and_check(cmd)
1692
+
1693
+ cmd = cpp_compile_command(
1694
+ input=[output_o, consts_o],
1695
+ output=output_so,
1696
+ vec_isa=picked_vec_isa,
1697
+ cuda=cuda,
1698
+ aot_mode=graph.aot_mode,
1699
+ use_absolute_path=use_absolute_path,
1700
+ )
1701
+ log.debug("aot linkage command: %s", cmd)
1702
+ if fbcode_aot_cpu_re:
1703
+ compile_file([output_o, consts_o], output_so, cmd.split())
1704
+ os.chmod(output_so, 0o755)
1705
+ else:
1706
+ run_command_and_check(cmd)
1707
+ else:
1708
+ log.debug(
1709
+ "aot_inductor dynamic library already exist: %s", output_so
1710
+ )
1711
+
1712
+ cls.cache[key] = output_so
1713
+
1714
+ return cls.cache[key]
1715
+
1716
+
1717
+ # Putting this fn in cpp.py (unfortunately) causes a deadlock, which is why it's in codecache.py.
1718
+ # Why? importing from cpp.py invokes codecache.pick_vec_isa(), which takes out a lock.
1719
+ # Cycle goes:
1720
+ # - CppCodeCache.load()
1721
+ # - pick_vec_isa()
1722
+ # - valid_vec_isa_list()
1723
+ # - VecISA.__bool__() <-- takes out a lock
1724
+ # - compile_file() <-- imports cpp_prefix_path from cpp, which causes us to try to take out the same lock.
1725
+ @functools.lru_cache
1726
+ def cpp_prefix_path() -> str:
1727
+ path = Path(__file__).parent / "codegen/cpp_prefix.h"
1728
+ with path.open() as f:
1729
+ content = f.read()
1730
+ _, filename = write(
1731
+ content,
1732
+ "h",
1733
+ )
1734
+ return filename
1735
+
1736
+
1737
+ def cpp_prefix() -> str:
1738
+ filename = cpp_prefix_path()
1739
+ if config.is_fbcode():
1740
+ # We need relative paths, since we bundle up
1741
+ # everything that we compile into a folder for remote compilation.
1742
+ return f'#include "{os.path.basename(filename)}"'
1743
+ else:
1744
+ return f'#include "{filename}"'
1745
+
1746
+
1747
+ # Given a path to an input cpp file and an output path,
1748
+ # Attempts to compile the file, storing the output in "output_path"
1749
+ def compile_file(
1750
+ input_path: Union[str, List[str]], output_path: str, cmd: List[str]
1751
+ ) -> None:
1752
+ input_paths = [input_path] if isinstance(input_path, str) else input_path
1753
+ input_files = [
1754
+ os.path.basename(ip) if config.is_fbcode() else ip for ip in input_paths
1755
+ ]
1756
+ try:
1757
+ if config.is_fbcode():
1758
+ # Need to copy our header into the same folder as the sourcecode.
1759
+ header_path = cpp_prefix_path()
1760
+ header_name = os.path.basename(header_path)
1761
+ output_name = os.path.basename(output_path)
1762
+ # When we build remotely, we need to make sure to carefully copy any files
1763
+ # that are required during the compilation process into our build directly.
1764
+ # This is where all of the ATen/c10/Torch includes come from.
1765
+ torch_includes_path = os.path.join(
1766
+ torch.utils.cpp_extension._TORCH_PATH, "include"
1767
+ )
1768
+ with tempfile.TemporaryDirectory() as tmp_dir:
1769
+ # Copy everything to tmp compilation folder
1770
+ shutil.copy(header_path, os.path.join(tmp_dir, header_name))
1771
+ for p, f in zip(input_paths, input_files):
1772
+ shutil.copy(p, os.path.join(tmp_dir, f))
1773
+ dest_include_path = os.path.join(tmp_dir, "include")
1774
+ shutil.copytree(torch_includes_path, dest_include_path)
1775
+ # Run the build
1776
+ output_file_path = _run_build_command(cmd, tmp_dir, output_name)
1777
+ # Copy output from the build
1778
+ if os.path.exists(output_path):
1779
+ os.remove(output_path)
1780
+ shutil.copy(output_file_path, output_path)
1781
+ else:
1782
+ subprocess.check_output(cmd, stderr=subprocess.STDOUT)
1783
+ except subprocess.CalledProcessError as e:
1784
+ output = e.output.decode("utf-8")
1785
+ openmp_problem = "'omp.h' file not found" in output or "libomp" in output
1786
+ if openmp_problem and sys.platform == "darwin":
1787
+ instruction = (
1788
+ "\n\nOpenMP support not found. Please try one of the following solutions:\n"
1789
+ "(1) Set the `CXX` environment variable to a compiler other than Apple clang++/g++ "
1790
+ "that has builtin OpenMP support;\n"
1791
+ "(2) install OpenMP via conda: `conda install llvm-openmp`;\n"
1792
+ "(3) install libomp via brew: `brew install libomp`;\n"
1793
+ "(4) manually setup OpenMP and set the `OMP_PREFIX` environment variable to point to a path"
1794
+ " with `include/omp.h` under it."
1795
+ )
1796
+ output += instruction
1797
+ raise exc.CppCompileError(cmd, output) from e
1798
+
1799
+
1800
+ _libgomp: Optional[CDLL] = None
1801
+
1802
+
1803
+ class CppCodeCache:
1804
+ cache: Dict[str, CDLL] = dict()
1805
+ clear = staticmethod(cache.clear)
1806
+
1807
+ @staticmethod
1808
+ def _load_library(path: str) -> CDLL:
1809
+ try:
1810
+ return cdll.LoadLibrary(path)
1811
+ except OSError as e:
1812
+ if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"):
1813
+ # hacky workaround for fbcode/buck
1814
+ global _libgomp
1815
+ _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1")
1816
+ return cdll.LoadLibrary(path)
1817
+ if "failed to map segment from shared object" in str(e):
1818
+ raise OSError(
1819
+ f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder "
1820
+ "is mounted with noexec (e.g., by default Docker mounts tmp file systems "
1821
+ f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another "
1822
+ "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable."
1823
+ ) from e
1824
+ raise
1825
+
1826
+ @classmethod
1827
+ def load(cls, source_code: str) -> CDLL:
1828
+ picked_vec_isa = pick_vec_isa()
1829
+ cpp_command = repr(cpp_compile_command("i", "o", vec_isa=picked_vec_isa))
1830
+ key, input_path = write(source_code, "cpp", extra=cpp_command)
1831
+ if key not in cls.cache:
1832
+ from filelock import FileLock
1833
+
1834
+ lock_dir = get_lock_dir()
1835
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
1836
+ with lock:
1837
+ output_path = input_path[:-3] + "so"
1838
+ if not os.path.exists(output_path):
1839
+ cmd = shlex.split(
1840
+ cpp_compile_command(
1841
+ input=input_path, output=output_path, vec_isa=picked_vec_isa
1842
+ )
1843
+ )
1844
+ compile_file(input_path, output_path, cmd)
1845
+ cls.cache[key] = cls._load_library(output_path)
1846
+ cls.cache[key].key = key # type: ignore[attr-defined]
1847
+
1848
+ return cls.cache[key]
1849
+
1850
+
1851
+ class PyCodeCache:
1852
+ cache: Dict[str, ModuleType] = dict()
1853
+ linemaps: Dict[str, List[Tuple[Any, ...]]] = dict()
1854
+ clear = staticmethod(cache.clear)
1855
+
1856
+ @classmethod
1857
+ def write(cls, source_code: str, extra: str = "") -> Tuple[str, str]:
1858
+ return write(source_code, "py", extra=extra)
1859
+
1860
+ @classmethod
1861
+ def load(
1862
+ cls,
1863
+ source_code: str,
1864
+ extra: str = "",
1865
+ linemap: Optional[List[Tuple[int, str]]] = None,
1866
+ attrs: Optional[Dict[str, Any]] = None,
1867
+ ) -> ModuleType:
1868
+ key, path = write(source_code, "py", extra=extra)
1869
+ return cls.load_by_key_path(key, path, linemap, attrs)
1870
+
1871
+ @classmethod
1872
+ def load_by_key_path(
1873
+ cls,
1874
+ key: str,
1875
+ path: str,
1876
+ linemap: Optional[List[Tuple[int, str]]] = None,
1877
+ attrs: Optional[Dict[str, Any]] = None,
1878
+ ) -> ModuleType:
1879
+ if linemap is None:
1880
+ linemap = []
1881
+ if key not in cls.cache:
1882
+ with open(path) as f:
1883
+ try:
1884
+ code = compile(f.read(), path, "exec")
1885
+ except Exception as e:
1886
+ raise RuntimeError(
1887
+ f"Failed to import {path}\n{type(e).__name__}: {e}"
1888
+ ) from None
1889
+ mod = ModuleType(f"{__name__}.{key}")
1890
+ mod.__file__ = path
1891
+ mod.key = key # type: ignore[attr-defined]
1892
+ exec(code, mod.__dict__, mod.__dict__)
1893
+ sys.modules[mod.__name__] = mod
1894
+ # another thread might set this first
1895
+ cls.cache.setdefault(key, mod)
1896
+ # unzip into separate lines/nodes lists
1897
+ cls.linemaps[path] = list(zip(*linemap))
1898
+
1899
+ if attrs is not None:
1900
+ for k, v in attrs.items():
1901
+ setattr(mod, k, v)
1902
+
1903
+ return cls.cache[key]
1904
+
1905
+ @classmethod
1906
+ @functools.lru_cache(None)
1907
+ def stack_frames_for_code(
1908
+ cls, path: str, lineno: int
1909
+ ) -> Optional[List[Dict[str, Any]]]:
1910
+ if path not in cls.linemaps:
1911
+ return None
1912
+ # [(starting_line, <fx node>), ...]
1913
+ lines, nodes = cls.linemaps[path]
1914
+ p = bisect_right(lines, lineno)
1915
+ if p == 0:
1916
+ return None
1917
+ entry = nodes[p - 1]
1918
+ if not entry:
1919
+ return None
1920
+
1921
+ def parse_stack_trace(stack_trace: str) -> List[Dict[str, Any]]:
1922
+ # ideally fx stores stack traces as data rather than a string
1923
+ # but this is not along a performance critical path
1924
+ regex = r'File "(.+)", line (\d+), in (.+)\n'
1925
+ matches = re.findall(regex, stack_trace)
1926
+ return [
1927
+ {"filename": f, "line": int(l), "name": n}
1928
+ for f, l, n in reversed(matches)
1929
+ ]
1930
+
1931
+ return parse_stack_trace(entry)
1932
+
1933
+
1934
+ class CppWrapperCodeCache:
1935
+ cache: Dict[str, CDLL] = dict()
1936
+ clear = staticmethod(cache.clear)
1937
+
1938
+ @classmethod
1939
+ def load(cls, source_code: str, func_name: str, key: str, cuda: bool) -> CDLL:
1940
+ name = f"inline_extension_{key}"
1941
+ cpp_wrapper_dir = cpp_wrapper_cache_dir(name)
1942
+ if not os.path.exists(cpp_wrapper_dir):
1943
+ os.makedirs(cpp_wrapper_dir)
1944
+
1945
+ ext = "so"
1946
+ filepath = os.path.join(cpp_wrapper_dir, f"{name}.{ext}")
1947
+ log.debug("Cpp wrapper code path %s", filepath)
1948
+
1949
+ if key not in cls.cache:
1950
+ log.debug("Cpp wrapper cache miss for %s", filepath)
1951
+ from filelock import FileLock
1952
+
1953
+ lock_dir = get_lock_dir()
1954
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
1955
+ with lock:
1956
+ if not os.path.exists(filepath):
1957
+ log.debug("Cpp wrapper building %s", filepath)
1958
+
1959
+ _cpp_flags = cpp_flags()
1960
+ _opt_flags = optimization_flags()
1961
+ _shared = get_shared()
1962
+ _warning_all_flag = get_warning_all_flag()
1963
+ (
1964
+ _ipaths,
1965
+ _lpaths,
1966
+ _libs,
1967
+ _macros,
1968
+ _build_arch_flags,
1969
+ ) = get_include_and_linking_paths(
1970
+ vec_isa=pick_vec_isa(),
1971
+ cuda=cuda,
1972
+ )
1973
+ _use_custom_generated_macros = use_custom_generated_macros()
1974
+ _cpp_wrapper_flags = cpp_wrapper_flags()
1975
+
1976
+ extra_cflags = f"{_cpp_flags} {_opt_flags} {_warning_all_flag} {_build_arch_flags} {_macros} \
1977
+ {_cpp_wrapper_flags} {_use_custom_generated_macros}"
1978
+ # For CPP wrapper, add -ffast-math during linking to make CPU flush denormals.
1979
+ # CPP wrapper leverages cpp_extension which will do the compilation and linking in two stages.
1980
+ # We need to explicitly add -ffast-math as a linking flag.
1981
+ # For the default python wrapper, the compilation and linking are done in one command thus -ffast-math
1982
+ # will take effect in both compilation and linking.
1983
+ extra_ldflags = f"{_shared} {_lpaths} {_libs} -ffast-math"
1984
+
1985
+ mod = torch.utils.cpp_extension.load_inline(
1986
+ name=name,
1987
+ build_directory=cpp_wrapper_dir,
1988
+ cpp_sources=[source_code],
1989
+ functions=[func_name],
1990
+ extra_cflags=[extra_cflags],
1991
+ extra_ldflags=[extra_ldflags],
1992
+ extra_include_paths=_ipaths,
1993
+ use_pch=True,
1994
+ )
1995
+ log.debug("Cpp wrapper done building %s", filepath)
1996
+ else:
1997
+ log.debug("Found target .so, cpp wrapper loading %s", filepath)
1998
+ spec = importlib.util.spec_from_file_location(name, filepath) # type: ignore[attr-defined]
1999
+ assert spec is not None
2000
+ mod = importlib.util.module_from_spec(spec) # type: ignore[attr-defined]
2001
+ assert isinstance(spec.loader, abc.Loader)
2002
+ spec.loader.exec_module(mod)
2003
+ log.debug("Cpp wrapper done loading %s", filepath)
2004
+
2005
+ cls.cache[key] = mod
2006
+
2007
+ return cls.cache[key]
2008
+
2009
+
2010
+ class TritonCodeCache:
2011
+ @classmethod
2012
+ def load(cls, kernel_name: str, source_code: str) -> ModuleType:
2013
+ mod = PyCodeCache.load(source_code)
2014
+ return getattr(mod, kernel_name)
2015
+
2016
+
2017
+ def _cuda_compiler() -> Optional[str]:
2018
+ if cuda_env.nvcc_exist(config.cuda.cuda_cxx):
2019
+ return config.cuda.cuda_cxx
2020
+ if cuda_env.nvcc_exist(os.getenv("CUDACXX")):
2021
+ return os.getenv("CUDACXX", "")
2022
+ if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")):
2023
+ return os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc")
2024
+ return "nvcc"
2025
+
2026
+
2027
+ def _cutlass_include_paths() -> List[str]:
2028
+ cutlass_path = config.cuda.cutlass_dir
2029
+ return [
2030
+ os.path.join(cutlass_path, "include"),
2031
+ os.path.join(cutlass_path, "tools/library/include"),
2032
+ os.path.join(cutlass_path, "tools/library/src"),
2033
+ os.path.join(cutlass_path, "tools/util/include"),
2034
+ ]
2035
+
2036
+
2037
+ def _cuda_lib_options() -> List[str]:
2038
+ from torch.utils import cpp_extension
2039
+
2040
+ extra_ldflags: List[str] = []
2041
+ if is_linux():
2042
+ extra_lib_dir = "lib64"
2043
+ if not os.path.exists(
2044
+ cpp_extension._join_cuda_home(extra_lib_dir)
2045
+ ) and os.path.exists(cpp_extension._join_cuda_home("lib")):
2046
+ # 64-bit CUDA may be installed in "lib"
2047
+ # Note that it's also possible both don't exist (see _find_cuda_home) - in that case we stay with "lib64"
2048
+ extra_lib_dir = "lib"
2049
+ extra_ldflags.append(f"-L{cpp_extension._join_cuda_home(extra_lib_dir)}")
2050
+ extra_ldflags.append(
2051
+ f'-L{cpp_extension._join_cuda_home(extra_lib_dir, "stubs")}'
2052
+ )
2053
+ extra_ldflags.append("-lcuda")
2054
+ extra_ldflags.append("-lcudart")
2055
+ else:
2056
+ raise NotImplementedError(
2057
+ "Unsupported env, failed to find cuda libs! Currently only Linux is supported."
2058
+ )
2059
+ return extra_ldflags
2060
+
2061
+
2062
+ def _nvcc_host_compiler_options() -> List[str]:
2063
+ return [
2064
+ "-fPIC",
2065
+ "-fno-strict-aliasing",
2066
+ "-fvisibility=hidden",
2067
+ "-Wconversion",
2068
+ ]
2069
+
2070
+
2071
+ def _nvcc_compiler_options() -> List[str]:
2072
+ arch = cuda_env.get_cuda_arch()
2073
+ if arch == "90":
2074
+ # Required by cutlass compilation.
2075
+ arch = "90a"
2076
+ code = [f"sm_{arch}", f"compute_{arch}"]
2077
+ if config.cuda.enable_cuda_lto:
2078
+ code += [f"lto_{arch}"]
2079
+ options = [
2080
+ "-t=0",
2081
+ "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
2082
+ "-w",
2083
+ f"-gencode=arch=compute_{arch},code=[{','.join(code)}]",
2084
+ config.cuda.compile_opt_level,
2085
+ "-std=c++17",
2086
+ "--expt-relaxed-constexpr",
2087
+ ]
2088
+ if config.cuda.enable_debug_info:
2089
+ options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"])
2090
+ if config.cuda.enable_ptxas_info:
2091
+ options.extend(
2092
+ [
2093
+ "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.)
2094
+ "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels
2095
+ "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels
2096
+ "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.)
2097
+ "--source-in-ptx",
2098
+ ]
2099
+ ) # Annotate the ptx file with source information
2100
+ if config.cuda.use_fast_math:
2101
+ options.extend(
2102
+ [
2103
+ "--use_fast_math",
2104
+ "-DCUTLASS_USE_TANH_FOR_SIGMOID=1",
2105
+ ]
2106
+ )
2107
+ return options
2108
+
2109
+
2110
+ def cuda_compile_command(
2111
+ src_files: List[str],
2112
+ dst_file: str,
2113
+ dst_file_ext: str,
2114
+ ) -> str:
2115
+ include_paths = _cutlass_include_paths()
2116
+ cuda_lib_options = _cuda_lib_options()
2117
+ nvcc_host_compiler_options = _nvcc_host_compiler_options()
2118
+ nvcc_compiler_options = _nvcc_compiler_options()
2119
+ options = (
2120
+ nvcc_compiler_options
2121
+ + [
2122
+ f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}"
2123
+ for opt in nvcc_host_compiler_options
2124
+ ]
2125
+ + ["-I" + path for path in include_paths]
2126
+ + cuda_lib_options
2127
+ )
2128
+ src_file = " ".join(src_files)
2129
+ res = ""
2130
+ if dst_file_ext == "o":
2131
+ res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}"
2132
+ elif dst_file_ext == "so":
2133
+ options.append("-shared")
2134
+ res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
2135
+ else:
2136
+ raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
2137
+ log.debug("CUDA command: %s", res)
2138
+ return res
2139
+
2140
+
2141
+ class DLLWrapper:
2142
+ """A wrapper for a dynamic library."""
2143
+
2144
+ def __init__(
2145
+ self,
2146
+ lib_path: str,
2147
+ ):
2148
+ self.lib_path = lib_path
2149
+ self.DLL = cdll.LoadLibrary(lib_path)
2150
+ self.is_open = True
2151
+
2152
+ def close(self):
2153
+ if self.is_open:
2154
+ self._dlclose()
2155
+ self.is_open = False
2156
+
2157
+ def _dlclose(self):
2158
+ f_dlclose = None
2159
+
2160
+ if is_linux():
2161
+ syms = CDLL(None)
2162
+ if not hasattr(syms, "dlclose"):
2163
+ # Apline Linux
2164
+ syms = CDLL("libc.so")
2165
+
2166
+ if hasattr(syms, "dlclose"):
2167
+ f_dlclose = syms.dlclose
2168
+ else:
2169
+ raise NotImplementedError("Unsupported env, failed to do dlclose!")
2170
+
2171
+ if f_dlclose is not None:
2172
+ f_dlclose.argtypes = [c_void_p]
2173
+ f_dlclose(self.DLL._handle)
2174
+ else:
2175
+ log.warning(
2176
+ "dll unloading function was not found, library may not be unloaded properly!"
2177
+ )
2178
+
2179
+ def __getattr__(self, name):
2180
+ if not self.is_open:
2181
+ raise RuntimeError(f"Cannot use closed DLL library: {self.lib_path}")
2182
+
2183
+ method = getattr(self.DLL, name)
2184
+
2185
+ def _wrapped_func(*args):
2186
+ err = method(*args)
2187
+ if err:
2188
+ raise RuntimeError(f"Error in function: {method.__name__}")
2189
+
2190
+ return _wrapped_func
2191
+
2192
+ def __enter__(self):
2193
+ return self
2194
+
2195
+ def __exit__(self, *args):
2196
+ self.close()
2197
+
2198
+ def __del__(self):
2199
+ self.close()
2200
+
2201
+
2202
+ class CUDACodeCache:
2203
+ @dataclasses.dataclass
2204
+ class CacheEntry:
2205
+ input_path: str
2206
+ output_path: str
2207
+
2208
+ cache: Dict[str, CacheEntry] = dict()
2209
+ clear = staticmethod(cache.clear)
2210
+ _SOURCE_CODE_SUFFIX = "cu"
2211
+
2212
+ @classmethod
2213
+ def write(cls, source_code, dst_file_ext) -> Tuple[str, str]:
2214
+ """
2215
+ Writes source code into a file with dst_file_ext as the file extension.
2216
+ Returns the hash key of source code, and the path to the file.
2217
+ """
2218
+
2219
+ cuda_command = repr(
2220
+ cuda_compile_command(["dummy_input"], "dummy_output", dst_file_ext)
2221
+ )
2222
+ key, input_path = write(
2223
+ source_code, cls._SOURCE_CODE_SUFFIX, extra=cuda_command
2224
+ )
2225
+ return key, input_path
2226
+
2227
+ @classmethod
2228
+ def compile(cls, source_code, dst_file_ext) -> Tuple[str, str, str]:
2229
+ """
2230
+ Compiles CUDA source_code into a file with dst_file_ext extension.
2231
+ Returns a tuple of dst_file_path, hash_key, source_code_path
2232
+ """
2233
+
2234
+ key, input_path = cls.write(source_code, dst_file_ext)
2235
+ if key not in cls.cache:
2236
+ from filelock import FileLock
2237
+
2238
+ lock_dir = get_lock_dir()
2239
+ lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT)
2240
+ with lock:
2241
+ output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext
2242
+ if not os.path.exists(output_path):
2243
+ cmd = cuda_compile_command(
2244
+ [input_path], output_path, dst_file_ext
2245
+ ).split(" ")
2246
+ try:
2247
+ subprocess.check_output(
2248
+ cmd, stderr=subprocess.STDOUT, env=os.environ
2249
+ )
2250
+ except subprocess.CalledProcessError as error:
2251
+ raise exc.CUDACompileError(cmd, error.output) from error
2252
+ cls.cache[key] = CUDACodeCache.CacheEntry(input_path, output_path)
2253
+
2254
+ return (cls.cache[key].output_path, key, input_path)
2255
+
2256
+ @classmethod
2257
+ def load(cls, source_code, dst_file_ext) -> Tuple[DLLWrapper, str, str]:
2258
+ """
2259
+ Compiles source code and loads the generated .so file.
2260
+ Returns a tuple of DLLWrapper, hash_key, source_code_path
2261
+ """
2262
+
2263
+ if dst_file_ext != "so":
2264
+ raise RuntimeError(
2265
+ f"Only support loading a .so file for now. "
2266
+ f"Requested file extension: {dst_file_ext}. Source code: {source_code}"
2267
+ )
2268
+ dst_file_path, hash_key, source_code_path = cls.compile(
2269
+ source_code, dst_file_ext
2270
+ )
2271
+ return (DLLWrapper(dst_file_path), hash_key, source_code_path)
2272
+
2273
+
2274
+ def caching_device_properties():
2275
+ for _, device_interface in get_registered_device_interfaces():
2276
+ if device_interface.is_available():
2277
+ device_interface.Worker.get_device_properties()
2278
+
2279
+
2280
+ def _worker_compile(
2281
+ kernel_name: str, source_code: str, cc: int, device: torch.device
2282
+ ) -> None:
2283
+ device_interface = get_interface_for_device(device.type)
2284
+ device_interface.Worker.set_device(device.index)
2285
+ kernel = TritonCodeCache.load(kernel_name, source_code)
2286
+ kernel.precompile(warm_cache_only_with_cc=cc)
2287
+
2288
+
2289
+ def _load_kernel(kernel_name: str, source_code: str) -> ModuleType:
2290
+ kernel = TritonCodeCache.load(kernel_name, source_code)
2291
+ kernel.precompile()
2292
+ return kernel
2293
+
2294
+
2295
+ class TritonFuture:
2296
+ kernel: ModuleType
2297
+
2298
+ def __init__(
2299
+ self,
2300
+ kernel_name: str,
2301
+ source_code: str,
2302
+ future: Future[Any],
2303
+ ) -> None:
2304
+ self.kernel_name = kernel_name
2305
+ self.source_code = source_code
2306
+ self.future = future
2307
+
2308
+ # @dynamo_utils.dynamo_timed
2309
+ def result(self) -> ModuleType:
2310
+ t0 = time()
2311
+ if hasattr(self, "kernel"):
2312
+ return self.kernel
2313
+ # If the worker failed this will throw an exception.
2314
+ self.future.result()
2315
+ kernel = self.kernel = _load_kernel(self.kernel_name, self.source_code)
2316
+ latency = time() - t0
2317
+ if latency > 50:
2318
+ developer_warning(
2319
+ f"Detected long compilation time of {latency} seconds for kernel name {self.kernel_name}"
2320
+ )
2321
+ developer_warning(self.source_code)
2322
+ del self.kernel_name, self.source_code, self.future
2323
+ return kernel
2324
+
2325
+
2326
+ # If this process dies abnormally (e.g. segfault)
2327
+ # it will not shut down the workers. Instead
2328
+ # the workers will have their parent reassigned to the
2329
+ # init process. This launches a separate thread to
2330
+ # watch for the worker getting reassigned,
2331
+ # and cleans it up in this case.
2332
+ #
2333
+ # This function cannot be an inner function since otherwise mp_context="spawn" would
2334
+ # not work for ProcessPoolExecutor since inner functions cannot be pickled.
2335
+ def _async_compile_initializer(orig_ppid) -> None:
2336
+ def run() -> None:
2337
+ while True:
2338
+ sleep(1)
2339
+ if orig_ppid != os.getppid():
2340
+ os.kill(os.getpid(), signal.SIGKILL)
2341
+
2342
+ global _watchdog_thread
2343
+ _watchdog_thread = Thread(target=run, daemon=True)
2344
+ _watchdog_thread.start()
2345
+
2346
+
2347
+ _watchdog_thread: Optional[Thread] = None
2348
+
2349
+
2350
+ class AsyncCompile:
2351
+ def __init__(self) -> None:
2352
+ pass
2353
+
2354
+ @staticmethod
2355
+ @functools.lru_cache(1)
2356
+ def pool() -> ThreadPoolExecutor:
2357
+ assert config.compile_threads > 1
2358
+ return ThreadPoolExecutor(config.compile_threads)
2359
+
2360
+ @staticmethod
2361
+ @functools.lru_cache(1)
2362
+ def process_pool() -> ProcessPoolExecutor:
2363
+ # ensure properties have been calculated before processes
2364
+ # are forked
2365
+ caching_device_properties()
2366
+ assert config.compile_threads > 1
2367
+ orig_ppid = os.getpid()
2368
+
2369
+ ctx = multiprocessing.get_context(config.worker_start_method)
2370
+ pool = ProcessPoolExecutor(
2371
+ config.compile_threads,
2372
+ mp_context=ctx,
2373
+ initializer=partial(_async_compile_initializer, orig_ppid),
2374
+ )
2375
+ # when this pool is created in a subprocess object, the normal exit handler
2376
+ # doesn't run, and we need to register our own handler.
2377
+ # exitpriority has to be high, because another one of the finalizers will
2378
+ # kill the worker thread that sends the shutdown message to the workers...
2379
+ multiprocessing.util.Finalize(None, pool.shutdown, exitpriority=sys.maxsize)
2380
+ return pool
2381
+
2382
+ @classmethod
2383
+ def warm_pool(cls) -> None:
2384
+ if config.compile_threads <= 1:
2385
+ return
2386
+ _compile_start()
2387
+ pool = cls.process_pool()
2388
+
2389
+ # We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the
2390
+ # slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread.
2391
+
2392
+ # Examples:
2393
+ # A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup
2394
+ # tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup
2395
+
2396
+ # So we want to start the workers early when it is still cheap, and also to allow the workers to get
2397
+ # ready before we have work for them.
2398
+
2399
+ # ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle.
2400
+ # But if we waited until then fork time will be long and we will be waiting for the processes to initialize.
2401
+
2402
+ # We force them to start here with some YOLOing of the internal methods.
2403
+ if hasattr(pool, "_start_queue_management_thread"):
2404
+ pool._start_queue_management_thread()
2405
+ else:
2406
+ for _ in range(config.compile_threads):
2407
+ pool._adjust_process_count()
2408
+ if hasattr(pool, "_start_executor_manager_thread"):
2409
+ pool._start_executor_manager_thread()
2410
+ _compile_end()
2411
+
2412
+ @classmethod
2413
+ def submit(cls, task: Callable[..., Any]) -> Any:
2414
+ if config.compile_threads <= 1:
2415
+ return task()
2416
+ return cls.pool().submit(task)
2417
+
2418
+ @classmethod
2419
+ def map(cls, fn: Callable[..., Any], seq: List[Any]) -> List[Any]:
2420
+ if config.compile_threads <= 1 or len(seq) <= 1:
2421
+ return list(map(fn, seq))
2422
+ return [t.result() for t in [cls.pool().submit(fn, x) for x in seq]]
2423
+
2424
+ def triton(
2425
+ self, kernel_name: str, source_code: str, device_str: str = "cuda"
2426
+ ) -> Union[TritonFuture, ModuleType]:
2427
+ _compile_start()
2428
+
2429
+ if config.compile_threads > 1:
2430
+ device_interface = get_interface_for_device(device_str)
2431
+ device = torch.device(device_str, device_interface.current_device())
2432
+ cc = device_interface.get_compute_capability(device)
2433
+ future = self.process_pool().submit(
2434
+ _worker_compile, kernel_name, source_code, cc, device
2435
+ )
2436
+ return TritonFuture(kernel_name, source_code, future)
2437
+ else:
2438
+ return _load_kernel(kernel_name, source_code)
2439
+
2440
+ def cpp(self, source_code: str) -> ModuleType:
2441
+ def task():
2442
+ return CppCodeCache.load(source_code).kernel
2443
+
2444
+ return self.submit(task)
2445
+
2446
+ def cuda(self, source_code, dst_file_ext):
2447
+ def task():
2448
+ return CUDACodeCache.load(source_code, dst_file_ext)[0]
2449
+
2450
+ return self.submit(task)
2451
+
2452
+ def wait(self, scope: Dict[str, Any]) -> None:
2453
+ num_kernels = len(
2454
+ [
2455
+ value
2456
+ for key, value in scope.items()
2457
+ if isinstance(value, (Future, TritonFuture))
2458
+ ]
2459
+ )
2460
+ pbar = tqdm(
2461
+ total=num_kernels,
2462
+ desc="Inductor Compilation",
2463
+ disable=config.disable_progress,
2464
+ delay=0,
2465
+ )
2466
+ if config.compile_threads > 1:
2467
+ for key, result in scope.items():
2468
+ if config.verbose_progress and not isinstance(pbar, _Faketqdm):
2469
+ pbar.set_postfix_str(key)
2470
+ if isinstance(result, (Future, TritonFuture)):
2471
+ scope[key] = result.result()
2472
+ pbar.update(1)
2473
+
2474
+ _compile_end()
2475
+
2476
+
2477
+ AsyncCompile.warm_pool()
vlmpy310/lib/python3.10/site-packages/torch/_inductor/comm_analysis.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from enum import IntEnum
3
+
4
+ from typing import TYPE_CHECKING
5
+
6
+ import torch
7
+ from . import ir
8
+
9
+ from .utils import get_dtype_size, sympy_product
10
+ from .virtualized import V
11
+
12
+ if TYPE_CHECKING:
13
+ from torch._inductor.scheduler import BaseSchedulerNode
14
+
15
+
16
+ class NCCL_COLL(IntEnum):
17
+ ALL_REDUCE = 0
18
+ ALL_GATHER = 1
19
+ REDUCE_SCATTER = 2
20
+
21
+
22
+ class NVIDIA_GPU_TYPE(IntEnum):
23
+ VOLTA = 0
24
+ AMPERE = 1
25
+ HOPPER = 2
26
+
27
+
28
+ def get_gpu_type() -> NVIDIA_GPU_TYPE:
29
+ gpu_info = torch.utils.collect_env.get_gpu_info(torch.utils.collect_env.run)
30
+ if "V100" in gpu_info:
31
+ return NVIDIA_GPU_TYPE.VOLTA
32
+ elif "A100" in gpu_info:
33
+ return NVIDIA_GPU_TYPE.AMPERE
34
+ elif "H100" in gpu_info:
35
+ return NVIDIA_GPU_TYPE.HOPPER
36
+ else:
37
+ # for other gpu types, assume Ampere
38
+ return NVIDIA_GPU_TYPE.AMPERE
39
+
40
+
41
+ def get_collective_type(snode: "BaseSchedulerNode") -> NCCL_COLL:
42
+ if isinstance(snode.node, (ir.AllReduce, ir.AllReduceCoalesced)):
43
+ return NCCL_COLL.ALL_REDUCE
44
+ elif isinstance(
45
+ snode.node, (ir.AllGatherIntoTensor, ir.AllGatherIntoTensorCoalesced)
46
+ ):
47
+ return NCCL_COLL.ALL_GATHER
48
+ elif isinstance(
49
+ snode.node, (ir.ReduceScatterTensor, ir.ReduceScatterTensorCoalesced)
50
+ ):
51
+ return NCCL_COLL.REDUCE_SCATTER
52
+ else:
53
+ raise Exception(f"Unsupported collective type: {snode.node}")
54
+
55
+
56
+ ####################################################################################################################
57
+ # The following code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
58
+ ####################################################################################################################
59
+
60
+
61
+ class NCCL_HW(IntEnum):
62
+ NVLINK = 0
63
+ PCI = 1
64
+ NET = 2
65
+
66
+
67
+ class NCCL_ALGO(IntEnum):
68
+ TREE = 0
69
+ RING = 1
70
+
71
+
72
+ class NCCL_PROTO(IntEnum):
73
+ # The ordering and enum values here matches original in
74
+ # https://github.com/NVIDIA/nccl/blob/0b083e52096c387bad7a5c5c65b26a9dca54de8c/src/include/devcomm.h#L28
75
+ # For difference between these protocols, see https://github.com/NVIDIA/nccl/issues/281#issuecomment-571816990
76
+ LL = 0 # Low-latency
77
+ # LL128 = 1 # Low-latency 128-byte
78
+ # SIMPLE = 2
79
+
80
+
81
+ # Latencies in us
82
+ # len(NCCL_ALGO) x len(NCCL_PROTO)
83
+ baseLat = torch.tensor(
84
+ [
85
+ # Tree
86
+ [
87
+ 6.8, # LL
88
+ ],
89
+ # Ring
90
+ [
91
+ 6.6, # LL
92
+ ],
93
+ ]
94
+ )
95
+
96
+ # Latencies in us
97
+ # len(NCCL_HW) x len(NCCL_ALGO) x len(NCCL_PROTO)
98
+ hwLat = torch.tensor(
99
+ [
100
+ # NVLINK
101
+ [
102
+ [0.6], # Tree (LL)
103
+ [0.6], # Ring (LL)
104
+ ],
105
+ # PCI
106
+ [
107
+ [1.0], # Tree (LL)
108
+ [1.0], # Ring (LL)
109
+ ],
110
+ # NET
111
+ [
112
+ [5.0], # Tree (LL)
113
+ [2.7], # Ring (LL)
114
+ ],
115
+ ]
116
+ )
117
+
118
+
119
+ # LL128 max BW per channel
120
+ llMaxBws = torch.tensor(
121
+ [
122
+ # Volta-N1/Intel-N2/Intel-N4
123
+ [
124
+ 39.0,
125
+ 39.0,
126
+ 20.4,
127
+ ],
128
+ # Ampere-N1/AMD-N2/AMD-N4
129
+ [
130
+ 87.7,
131
+ 22.5, # avg of ring & tree
132
+ 19.0,
133
+ ],
134
+ # Hopper-N1/AMD-N2/AMD-N4
135
+ [
136
+ 87.7,
137
+ 22.5, # avg of ring & tree
138
+ 19.0,
139
+ ],
140
+ ]
141
+ )
142
+
143
+
144
+ def estimate_nccl_collective_runtime(snode: "BaseSchedulerNode") -> float:
145
+ """
146
+ Returns estimated NCCL collective runtime in nanoseconds (ns).
147
+
148
+ The following heuristics are copied from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc.
149
+ We aim to estimate the runtime as accurately as possible.
150
+
151
+ Assumptions:
152
+ - only ring algorithm (NCCL_ALGO_RING) is used
153
+ - only Low-Latency protocol (NCCL_PROTO_LL) is used, i.e. Simple or LL128 is not used
154
+ - 8 gpus per node # TODO: Need to find a way to get accurate "gpus per node" and "# nodes" info.
155
+ - collective is one of: allreduce, reducescatter, allgather
156
+ """
157
+ tensor_numel = V.graph.sizevars.size_hint(sympy_product(snode.node.layout.size))
158
+ tensor_dtype = snode.node.layout.dtype
159
+ tensor_storage_size_bytes = tensor_numel * get_dtype_size(tensor_dtype)
160
+ # Convert bytes to GB
161
+ tensor_storage_size_GB = tensor_storage_size_bytes / 1024 / 1024 / 1024
162
+
163
+ # Currently assumes each node has 8 gpus. And when >1 node is used, assumes each node uses all 8 gpus.
164
+ # TODO: Need to find a way to get accurate "gpus per node" and "# nodes" info.
165
+ num_gpus_per_node = 8
166
+ _, _, group_size = snode.node.constant_args # type: ignore[attr-defined]
167
+ nNodes = math.ceil(group_size / num_gpus_per_node)
168
+ nRanks = group_size # this is total # of gpus globally that participate in this collective op
169
+
170
+ if nRanks <= 1:
171
+ return 0
172
+
173
+ # Assumes ring algorithm
174
+ nccl_algo = NCCL_ALGO.RING
175
+ nccl_proto = NCCL_PROTO.LL
176
+ coll = get_collective_type(snode)
177
+
178
+ # =============== bandwidth computation ===============
179
+ # First compute bandwidth in GB/s; then at the end, convert it to GB/ns
180
+
181
+ bwIntra = torch._inductor.config.intra_node_bw
182
+ bwInter = torch._inductor.config.inter_node_bw
183
+
184
+ compCapIndex = get_gpu_type()
185
+ index2 = nNodes - 1 if nNodes <= 2 else 2
186
+ # LL: for single node, we look at GPU type; for multi-node, we look at CPU type
187
+ index1 = compCapIndex if nNodes == 1 else 0
188
+ llMaxBw = llMaxBws[index1][index2].item()
189
+
190
+ # NOTE: each step of ring algorithm is synchronized,
191
+ # and is bottlenecked by the slowest link which is the inter-node interconnect.
192
+ # hence when nNodes >= 2, bw is inter-node bandwidth.
193
+ # NOTE: the original code in https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc
194
+ # have this as `if nNodes <= 2` which seems wrong. Corrected it here.
195
+ bw = bwIntra if nNodes == 1 else bwInter
196
+ nChannels = 2 # Assume # channels is 2
197
+ busBw = nChannels * bw
198
+
199
+ # Various model refinements
200
+ busBw = min(
201
+ llMaxBw,
202
+ busBw
203
+ * (1.0 / 4.0 if (nNodes > 1 or coll == NCCL_COLL.ALL_REDUCE) else 1.0 / 3.0),
204
+ )
205
+
206
+ if coll == NCCL_COLL.ALL_REDUCE:
207
+ nsteps = 2 * (nRanks - 1)
208
+ elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER):
209
+ nsteps = nRanks - 1
210
+
211
+ # Convert bus BW to algorithm BW (tensor bytes / algoBW = actual execution time)
212
+ ratio = (1.0 * nRanks) / nsteps
213
+ bandwidth = busBw * ratio
214
+ # Convert GB/s to GB/ns
215
+ bandwidth_GB_per_ns = bandwidth / 1e9
216
+
217
+ # =============== latency computation ===============
218
+ intraHw = NCCL_HW.NVLINK
219
+ hw = intraHw if nNodes == 1 else NCCL_HW.NET
220
+
221
+ if coll == NCCL_COLL.ALL_REDUCE:
222
+ if nNodes > 1:
223
+ nInterSteps = 2 * nNodes
224
+ else:
225
+ nInterSteps = 0
226
+ elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER):
227
+ nInterSteps = nNodes - 1
228
+
229
+ # First compute latency in us; then at the end, convert it to ns
230
+ latency = baseLat[nccl_algo][nccl_proto].item()
231
+ intraLat = hwLat[intraHw][nccl_algo][nccl_proto].item()
232
+ interLat = hwLat[NCCL_HW.NET][nccl_algo][nccl_proto].item()
233
+
234
+ # Inter-node rings still have to launch nsteps * net overhead.
235
+ netOverhead = 0.0
236
+ if nNodes > 1:
237
+ netOverhead = 1.0 # getNetOverhead(comm);
238
+ intraLat = max(intraLat, netOverhead)
239
+ latency += (nsteps - nInterSteps) * intraLat + nInterSteps * interLat
240
+ # Convert us to ns
241
+ latency_ns = latency * 1e3
242
+
243
+ # =============== final result ===============
244
+ transport_ns = tensor_storage_size_GB / bandwidth_GB_per_ns
245
+ return transport_ns + latency_ns
246
+
247
+
248
+ ################################################################################################################
249
+ # The above code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
250
+ ################################################################################################################
vlmpy310/lib/python3.10/site-packages/torch/_inductor/comms.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyre-strict
2
+
3
+ from typing import List
4
+
5
+ import torch
6
+
7
+ from . import config, ir, scheduler
8
+ from .dependencies import WeakDep
9
+ from .utils import tuple_sorted
10
+
11
+ overlap_log = torch._logging.getArtifactLogger(__name__, "overlap")
12
+
13
+
14
+ def sink_waits(
15
+ snodes: List["scheduler.BaseSchedulerNode"],
16
+ ) -> List["scheduler.BaseSchedulerNode"]:
17
+ """
18
+ Greedily moves waits as late as possible (i.e. until we reach a use). Optimal in terms of
19
+ communication overlap.
20
+ """
21
+ new_order = []
22
+ cur_waits = set()
23
+ for snode in snodes:
24
+ if isinstance(snode.node, ir.Wait):
25
+ cur_waits.add(snode)
26
+ else:
27
+ for wait in tuple_sorted(cur_waits):
28
+ if snode in wait.node_users:
29
+ new_order.append(wait)
30
+ cur_waits.remove(wait)
31
+ new_order.append(snode)
32
+ for snode in tuple_sorted(cur_waits):
33
+ new_order.append(snode)
34
+ return new_order
35
+
36
+
37
+ def raise_comms(
38
+ snodes: List["scheduler.BaseSchedulerNode"],
39
+ ) -> List["scheduler.BaseSchedulerNode"]:
40
+ """
41
+ Greedily moves comms as early as possible (i.e. until we reach an input).
42
+ Optimal in terms of communication overlap.
43
+
44
+ TODO: We might want to adjust this in the future to account for memory limitations.
45
+ e.g. when we are compiling FSDP, this heuristics will cause the all-gathers to be prefetched as soon as possible,
46
+ which is the beginning of the forwards pass. We'll have to either do a special pass for FSDP,
47
+ or we'll want to redo this pass with memory considerations so we handle the FSDP case in a general way.
48
+ """
49
+ new_order_reversed: List["scheduler.BaseSchedulerNode"] = []
50
+ cur_comms: List["scheduler.BaseSchedulerNode"] = []
51
+ for snode in reversed(snodes):
52
+ if isinstance(snode.node, ir.CollectiveKernel):
53
+ cur_comms.append(snode)
54
+ else:
55
+ for comm in cur_comms:
56
+ assert len(comm.inverse_users) > 0
57
+ while len(cur_comms) > 0 and any(
58
+ snode in comm.inverse_users for comm in cur_comms
59
+ ):
60
+ comm = cur_comms.pop(0)
61
+ new_order_reversed.append(comm)
62
+ new_order_reversed.append(snode)
63
+ assert len(cur_comms) <= 1
64
+ for snode in tuple_sorted(cur_comms):
65
+ new_order_reversed.append(snode)
66
+ return new_order_reversed[::-1]
67
+
68
+
69
+ def get_ancestors(node):
70
+ ancestors = set()
71
+ cur_nodes = [node]
72
+ while len(cur_nodes) > 0:
73
+ new_nodes = []
74
+ for node in cur_nodes:
75
+ for inp in node.inverse_users:
76
+ if inp not in ancestors:
77
+ ancestors.add(inp)
78
+ new_nodes.append(inp)
79
+ cur_nodes = new_nodes
80
+ return ancestors
81
+
82
+
83
+ def get_descendants(node):
84
+ descendants = set()
85
+ cur_nodes = [node]
86
+ while len(cur_nodes) > 0:
87
+ new_nodes = []
88
+ for node in cur_nodes:
89
+ for inp in node.node_users:
90
+ if inp not in descendants:
91
+ descendants.add(inp)
92
+ new_nodes.append(inp)
93
+ cur_nodes = new_nodes
94
+ return descendants
95
+
96
+
97
+ def decide_global_ordering_of_comms(nodes: List["scheduler.BaseSchedulerNode"]):
98
+ """
99
+ Decide global ordering of comms, by just enforcing the ordering that's in the input graph
100
+ (might not be the same ordering as the eager mode program).
101
+ TODO: Come up with a better approach
102
+ """
103
+ comm_nodes = [n for n in nodes if isinstance(n.node, ir.CollectiveKernel)]
104
+ for i in range(1, len(comm_nodes)):
105
+ # Enforce ordering by making previous comm a `WeakDep` dependency of the next comm
106
+ comm_nodes[i].add_fake_dep(WeakDep(comm_nodes[i - 1].get_name()))
107
+
108
+
109
+ def assert_no_comm_nodes(snodes: List["scheduler.BaseSchedulerNode"]) -> None:
110
+ assert not any(isinstance(snode.node, ir.CollectiveKernel) for snode in snodes)
111
+
112
+
113
+ def estimate_op_runtime(snode: "scheduler.BaseSchedulerNode") -> float:
114
+ """
115
+ Returns estimated op runtime in nanoseconds (ns)
116
+ """
117
+ if config.estimate_op_runtime == "default":
118
+ runtime = snode.get_estimated_runtime()
119
+ else:
120
+ assert callable(config.estimate_op_runtime)
121
+ runtime = config.estimate_op_runtime(snode)
122
+ return runtime
123
+
124
+
125
+ def reorder_compute_for_overlap(
126
+ snodes: List["scheduler.BaseSchedulerNode"],
127
+ ) -> List["scheduler.BaseSchedulerNode"]:
128
+ """
129
+ Decides a global ordering of all compute and communication nodes,
130
+ assuming that we already have a global ordering of communication nodes.
131
+
132
+ Overall scheduling procedure is:
133
+ Step 1: Given that we've currently scheduled comm N, we now schedule all compute nodes
134
+ that are required for comm N + 1 but do not depend on comm N, to run at the same time with comm N.
135
+ Step 2: If all those compute nodes are sufficient to overlap comm N, we're done.
136
+ Otherwise, we now need to look elsewhere to find compute that overlaps with comm N.
137
+ We prioritize compute nodes that are needed sooner.
138
+ Step 3: We schedule the compute nodes dependent on comm N and required for comm N + 1.
139
+ Step 4: We schedule comm N + 1.
140
+ Repeat this for subsequent comm nodes.
141
+ """
142
+ final_order = []
143
+
144
+ comm_nodes = []
145
+ for snode in snodes:
146
+ if isinstance(snode.node, ir.CollectiveKernel):
147
+ comm_nodes.append(snode)
148
+ if len(comm_nodes) == 0:
149
+ # if there is no comm nodes, return the current order
150
+ return snodes
151
+
152
+ comm_ancestors = {node: get_ancestors(node) for node in comm_nodes}
153
+ comm_descendants = {node: get_descendants(node) for node in comm_nodes}
154
+
155
+ indeg = {k: 0 for k in snodes}
156
+ for snode in snodes:
157
+ for user in snode.node_users:
158
+ if user in indeg:
159
+ indeg[user] += 1
160
+ ready_to_schedule_nodes = {node for node in snodes if indeg[node] == 0}
161
+
162
+ unscheduled_nodes = set()
163
+ unscheduled_nodes = set(snodes)
164
+
165
+ def schedule_node(snode):
166
+ """
167
+ Schedule a single node.
168
+ """
169
+ assert snode in unscheduled_nodes
170
+ assert snode in ready_to_schedule_nodes
171
+ ready_to_schedule_nodes.remove(snode)
172
+ unscheduled_nodes.remove(snode)
173
+ final_order.append(snode)
174
+ for user in tuple_sorted(snode.node_users):
175
+ if user in indeg:
176
+ indeg[user] -= 1
177
+ if indeg[user] == 0:
178
+ ready_to_schedule_nodes.add(user)
179
+
180
+ def schedule_nodes(snodes):
181
+ """
182
+ Schedules all nodes in `snodes` in an arbitrary topologically valid order.
183
+ """
184
+ all_nodes = set(snodes)
185
+ assert all(node in unscheduled_nodes for node in all_nodes)
186
+ while len(all_nodes) > 0:
187
+ # NOTE: since model graph is always a DAG and does not have circular dependency inside,
188
+ # there should be at least one node that is a "free node" (i.e. indeg == 0),
189
+ # hence infinite loop is not possible. But we check here just to be safe.
190
+ progress = False
191
+ for node in tuple_sorted(all_nodes):
192
+ if node in ready_to_schedule_nodes:
193
+ schedule_node(node)
194
+ all_nodes.remove(node)
195
+ progress = True
196
+ if not progress:
197
+ raise Exception(
198
+ "Unable to find a free node (indeg == 0). This is an impossible state to reach. "
199
+ "Please report a bug to PyTorch."
200
+ )
201
+
202
+ # First, schedule all compute nodes that are required by first comm node,
203
+ # as well as the first comm node itself.
204
+ assert len(comm_nodes) > 0
205
+ schedule_nodes(
206
+ list(comm_ancestors[comm_nodes[0]]) + [comm_nodes[0]],
207
+ )
208
+
209
+ rolled_over_compute_cost = 0
210
+ for idx in range(1, len(comm_ancestors)):
211
+ # Step 1: Given that we've currently scheduled comm `idx-1`, we now schedule
212
+ # all compute nodes that are required for comm `idx` but do not depend on comm `idx-1`,
213
+ # to run at the same time with comm `idx-1`.
214
+ needed_by_next_comm_and_ready_compute_nodes = unscheduled_nodes & (
215
+ comm_ancestors[comm_nodes[idx]] - comm_descendants[comm_nodes[idx - 1]]
216
+ )
217
+ assert_no_comm_nodes(needed_by_next_comm_and_ready_compute_nodes)
218
+
219
+ total_compute_runtime_cost = rolled_over_compute_cost + sum(
220
+ [
221
+ estimate_op_runtime(node)
222
+ for node in needed_by_next_comm_and_ready_compute_nodes
223
+ ]
224
+ )
225
+ prev_comm_runtime_cost = estimate_op_runtime(comm_nodes[idx - 1])
226
+ schedule_nodes(tuple_sorted(needed_by_next_comm_and_ready_compute_nodes))
227
+
228
+ # Step 2: If all those compute nodes are sufficient to overlap comm `idx-1`, we're done.
229
+ # Otherwise, we now need to look elsewhere to find compute that overlaps with comm `idx`.
230
+ # We prioritize compute nodes that are needed sooner.
231
+ step1_runtime_cost = total_compute_runtime_cost
232
+ if step1_runtime_cost >= prev_comm_runtime_cost:
233
+ pass
234
+ else:
235
+ # Find all ready to schedule compute nodes that do not depend on comm `idx-1`.
236
+ ready_to_schedule_compute_nodes = tuple_sorted(
237
+ ready_to_schedule_nodes - comm_descendants[comm_nodes[idx - 1]]
238
+ )
239
+ assert_no_comm_nodes(ready_to_schedule_compute_nodes)
240
+
241
+ def earliest_comm_descendant(node):
242
+ for idx in range(len(comm_nodes)):
243
+ if node in comm_ancestors[comm_nodes[idx]]:
244
+ return idx
245
+ return len(comm_nodes)
246
+
247
+ # Prioritize compute nodes that are needed sooner.
248
+ ready_to_schedule_compute_nodes = sorted(
249
+ ready_to_schedule_compute_nodes, key=earliest_comm_descendant
250
+ )
251
+
252
+ for snode in ready_to_schedule_compute_nodes:
253
+ if total_compute_runtime_cost >= prev_comm_runtime_cost:
254
+ # If accumulated compute runtime cost is greater than comm `idx-1` runtime cost,
255
+ # it means we have maximized overlap for comm `idx-1`, and hence we stop looking
256
+ # for more compute to schedule.
257
+ break
258
+ compute_runtime_cost = estimate_op_runtime(snode)
259
+ # If we're not able to leverage more than half of this
260
+ # node's compute to overlap, we skip it.
261
+ # TODO: Smarter heuristics here
262
+ if (
263
+ prev_comm_runtime_cost - total_compute_runtime_cost
264
+ ) <= compute_runtime_cost / 2:
265
+ continue
266
+ schedule_node(snode)
267
+ total_compute_runtime_cost += compute_runtime_cost
268
+ rollable_compute_cost = total_compute_runtime_cost - step1_runtime_cost
269
+
270
+ # Step 3: We schedule the compute nodes dependent on comm `idx-1` and required for comm `idx`.
271
+ needed_by_next_comm_nodes = unscheduled_nodes & comm_ancestors[comm_nodes[idx]]
272
+ schedule_nodes(list(needed_by_next_comm_nodes))
273
+
274
+ # Step 4: We schedule comm `idx`.
275
+ schedule_nodes([comm_nodes[idx]])
276
+
277
+ is_prev_comm_blocking_next_comm = len(needed_by_next_comm_nodes) > 0
278
+ # The idea here is that if there are no compute nodes from Step 3
279
+ # (i.e. if prev comm is not blocking next comm), we can roll over the compute nodes
280
+ # in Step 2 to overlap with the next comm, since they're not required to finish
281
+ # before the next comm starts.
282
+ if is_prev_comm_blocking_next_comm:
283
+ rolled_over_compute_cost = 0
284
+ else:
285
+ rolled_over_compute_cost = rollable_compute_cost # type: ignore[assignment]
286
+
287
+ schedule_nodes(unscheduled_nodes)
288
+ return final_order
289
+
290
+
291
+ def node_summary(snode):
292
+ detail = ""
293
+ if isinstance(snode.node, ir.ExternKernelOut):
294
+ detail = f" ({snode.node.kernel})"
295
+ out_tensor_info = ""
296
+ if (
297
+ hasattr(snode.node, "layout")
298
+ and hasattr(snode.node.layout, "size")
299
+ and hasattr(snode.node.layout, "stride")
300
+ ):
301
+ out_tensor_info = (
302
+ f" (size={snode.node.layout.size}, stride={snode.node.layout.stride})"
303
+ )
304
+ node_name = ""
305
+ if hasattr(snode.node, "name"):
306
+ node_name = snode.node.name
307
+ return f"{snode.node.__class__.__name__}{detail}{out_tensor_info} ({node_name})"
308
+
309
+
310
+ def visualize_overlap(order):
311
+ total_est_runtime: float = 0.0
312
+ cur_comm_node = None
313
+ for snode in order:
314
+ if cur_comm_node is None:
315
+ if isinstance(snode.node, ir.CollectiveKernel):
316
+ total_est_runtime += estimate_op_runtime(snode)
317
+ cur_comm_node = snode.node
318
+ elif isinstance(snode.node, ir.Wait):
319
+ raise Exception(
320
+ "Wait is not expected when there is no collective running"
321
+ )
322
+ else: # exposed compute op
323
+ total_est_runtime += estimate_op_runtime(snode)
324
+ overlap_log.debug(f"{node_summary(snode)}") # noqa: G004
325
+ else: # cur_comm_node is not None
326
+ if isinstance(snode.node, ir.CollectiveKernel):
327
+ raise Exception(
328
+ "Found two collectives running at the same time. "
329
+ "`visualize_overlap` needs to be updated to handle this case"
330
+ )
331
+ elif isinstance(snode.node, ir.Wait): # end of this comm op
332
+ overlap_log.debug(f"{node_summary(snode)}") # noqa: G004
333
+ cur_comm_node = None
334
+ else: # overlapped compute op
335
+ overlap_log.debug(f"| {node_summary(snode)}") # noqa: G004
336
+ overlap_log.debug(
337
+ f"Est. runtime (ms): {total_est_runtime / 1000 / 1000}" # noqa: G004
338
+ )
339
+
340
+
341
+ def reorder_compute_and_comm_for_overlap(
342
+ snodes: List["scheduler.BaseSchedulerNode"],
343
+ ) -> List["scheduler.BaseSchedulerNode"]:
344
+ order = snodes
345
+ for p in config.reorder_for_compute_comm_overlap_passes:
346
+ if isinstance(p, str) and p in globals():
347
+ p = globals()[p] # it is a builtin pass
348
+ if torch.distributed.get_rank() == 0:
349
+ overlap_log.debug(
350
+ f"==== Visualize overlap before reordering pass {p} ====" # noqa: G004
351
+ )
352
+ try:
353
+ visualize_overlap(order)
354
+ except Exception as e:
355
+ overlap_log.debug(str(e))
356
+ order = p(order) # type: ignore[operator]
357
+ if torch.distributed.get_rank() == 0:
358
+ overlap_log.debug(
359
+ f"==== Visualize overlap after reordering pass {p} ====" # noqa: G004
360
+ )
361
+ try:
362
+ visualize_overlap(order)
363
+ except Exception as e:
364
+ overlap_log.debug(str(e))
365
+ return order
vlmpy310/lib/python3.10/site-packages/torch/_inductor/compile_fx.py ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import dataclasses
3
+ import functools
4
+ import logging
5
+ import os
6
+ import sys
7
+ import time
8
+ import warnings
9
+ from itertools import count
10
+
11
+ from typing import (
12
+ Any,
13
+ Callable,
14
+ Dict,
15
+ FrozenSet,
16
+ List,
17
+ Optional,
18
+ Sequence,
19
+ Tuple,
20
+ Union,
21
+ )
22
+ from unittest import mock
23
+
24
+ from functorch.compile import min_cut_rematerialization_partition
25
+
26
+ import torch._functorch.config as functorch_config
27
+
28
+ import torch.fx
29
+ import torch.utils._pytree as pytree
30
+ from torch._dynamo import (
31
+ compiled_autograd,
32
+ logging as dynamo_logging,
33
+ utils as dynamo_utils,
34
+ )
35
+ from torch._dynamo.utils import detect_fake_mode, lazy_format_graph_code
36
+ from torch._functorch.aot_autograd import aot_export_module, make_boxed_func
37
+ from torch._inductor.codecache import code_hash, CompiledFxGraph, FxGraphCache
38
+
39
+ from torch._inductor.debug import save_args_for_compile_fx_inner
40
+ from torch._ops import OpOverload
41
+ from torch._subclasses.fake_tensor import FakeTensor
42
+ from torch.fx.passes.fake_tensor_prop import FakeTensorProp
43
+
44
+ from .._dynamo.backends.common import aot_autograd
45
+ from ..fx.graph import _PyTreeCodeGen
46
+ from . import config, metrics
47
+ from .debug import DebugContext
48
+ from .decomposition import select_decomp_table
49
+ from .fx_passes.joint_graph import joint_graph_passes
50
+ from .fx_passes.post_grad import post_grad_passes, view_to_reshape
51
+ from .fx_passes.pre_grad import pre_grad_passes
52
+ from .graph import GraphLowering
53
+ from .ir import ExternKernelNode
54
+ from .utils import get_dtype_size, has_incompatible_cudagraph_ops
55
+ from .virtualized import V
56
+
57
+ if config.is_fbcode():
58
+ from torch._inductor.fb.utils import time_and_log
59
+ else:
60
+ # no-op decorator
61
+ def time_and_log(attr: str):
62
+ return dynamo_utils.identity
63
+
64
+
65
+ log = logging.getLogger(__name__)
66
+ perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints")
67
+ post_grad_graphs_log = torch._logging.getArtifactLogger(__name__, "post_grad_graphs")
68
+ ALIGNMENT = 16
69
+
70
+
71
+ @dataclasses.dataclass
72
+ class BoxedBool:
73
+ value: bool
74
+
75
+ def __bool__(self):
76
+ return self.value
77
+
78
+ @staticmethod
79
+ def disable(obj):
80
+ if isinstance(obj, BoxedBool):
81
+ obj.value = False
82
+ return obj
83
+ return False
84
+
85
+
86
+ @dataclasses.dataclass
87
+ class BoxedDeviceIndex:
88
+ value: Optional[int]
89
+
90
+ def set(self, device_idx):
91
+ assert device_idx is None or isinstance(device_idx, int)
92
+ self.value = device_idx
93
+
94
+
95
+ # copy_ fails when trying to write to tensors with memory overlap,
96
+ # for expanded dimensions (a dimension which used to have size 1 -> ?)
97
+ # we can select one element from that dimension and write to it
98
+ # to achieve writing to all values of that dimension of the input tensor
99
+ def get_expanded_dims(t):
100
+ if not isinstance(t, torch.Tensor):
101
+ return None
102
+ return [i for i in range(t.ndim) if t.stride(i) == 0 and t.size(i) != 1]
103
+
104
+
105
+ def index_expanded_dims(t: torch.Tensor, expanded_dims: List[int]) -> torch.Tensor:
106
+ for expanded_dim in expanded_dims:
107
+ t = torch.ops.aten.slice(t, expanded_dim, 0, 1)
108
+ return t
109
+
110
+
111
+ def complex_memory_overlap(t: torch.Tensor) -> bool:
112
+ # if torch._debug_has_internal_overlap thinks this tensor potentially has
113
+ # memory overlap internally, let's dig deeper to find out whether it's true.
114
+ t = index_expanded_dims(t, get_expanded_dims(t))
115
+ if torch._debug_has_internal_overlap(t) != 0:
116
+ strides = t.stride()
117
+ sizes = t.shape
118
+ indices = list(range(len(strides)))
119
+ indices = [x for _, x in sorted(zip(strides, indices))]
120
+ for i in range(len(strides)):
121
+ prev_stride = 1 if i == 0 else strides[indices[i - 1]]
122
+ prev_size = 1 if i == 0 else sizes[indices[i - 1]]
123
+ if strides[indices[i]] < prev_stride * prev_size:
124
+ return True
125
+ return False
126
+
127
+
128
+ @functools.lru_cache(None)
129
+ def _step_logger():
130
+ return dynamo_logging.get_step_logger(log)
131
+
132
+
133
+ @functools.lru_cache(None)
134
+ def _warn_tf32_disabled():
135
+ if (
136
+ torch.cuda.is_available()
137
+ and not torch.backends.cuda.matmul.allow_tf32
138
+ and torch.cuda.get_device_capability() >= (8, 0)
139
+ ):
140
+ warnings.warn(
141
+ "TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. "
142
+ "Consider setting `torch.set_float32_matmul_precision('high')` for better performance."
143
+ )
144
+
145
+
146
+ def _unlift_graph(mod, gm, graph_signature):
147
+ state_dict = {}
148
+ for name, param in mod.named_parameters(remove_duplicate=False):
149
+ state_dict[name] = param
150
+ for name, param in mod.named_buffers(remove_duplicate=False):
151
+ state_dict[name] = param
152
+
153
+ from torch._export.exported_program import (
154
+ _construct_inp_pos_to_param_buffer_name,
155
+ _unlift,
156
+ )
157
+
158
+ inp_pos_to_param_buffer_name = _construct_inp_pos_to_param_buffer_name(
159
+ gm,
160
+ graph_signature,
161
+ state_dict,
162
+ {},
163
+ )
164
+ unlifted_gm = _unlift(
165
+ gm,
166
+ inp_pos_to_param_buffer_name,
167
+ pytree.LeafSpec(),
168
+ None,
169
+ state_dict,
170
+ {},
171
+ graph_signature.buffers_to_mutate,
172
+ )
173
+ return unlifted_gm
174
+
175
+
176
+ def is_tf32_warning_applicable(gm: torch.fx.GraphModule):
177
+ aten = torch.ops.aten
178
+ tf32_ops = {
179
+ aten.mm.default,
180
+ aten.addmm.default,
181
+ aten.bmm.default,
182
+ aten.baddbmm.default,
183
+ }
184
+ for node in gm.graph.nodes:
185
+ if (
186
+ node.op == "call_function"
187
+ and node.target in tf32_ops
188
+ and isinstance(node.meta.get("val", None), torch.Tensor)
189
+ and node.meta["val"].dtype == torch.float32
190
+ and node.meta["val"].device.type == "cuda"
191
+ ):
192
+ return True
193
+ return False
194
+
195
+
196
+ @DebugContext.wrap
197
+ def count_bytes_inner(
198
+ gm: torch.fx.GraphModule,
199
+ example_inputs: List[torch.Tensor],
200
+ num_fixed: int = 0,
201
+ **kwargs,
202
+ ):
203
+ shape_env = _shape_env_from_inputs(example_inputs)
204
+ fake_mode = fake_tensor_prop(gm, example_inputs)
205
+
206
+ with V.set_fake_mode(fake_mode):
207
+ post_grad_passes(gm, False)
208
+
209
+ graph = GraphLowering(gm, shape_env=shape_env, num_static_inputs=num_fixed)
210
+ with V.set_graph_handler(graph), V.set_real_inputs(example_inputs):
211
+ graph.run(*example_inputs)
212
+ num_bytes, nodes_num_elem, node_runtimes = graph.count_bytes()
213
+ metrics.num_bytes_accessed += num_bytes
214
+ metrics.nodes_num_elem += nodes_num_elem
215
+ metrics.node_runtimes += node_runtimes
216
+ return make_boxed_func(gm.forward)
217
+
218
+
219
+ def fake_tensor_prop(
220
+ gm: torch.fx.GraphModule,
221
+ example_inputs: List[torch.Tensor],
222
+ force_allow_non_fake_inputs: bool = False,
223
+ ):
224
+ """
225
+ If we can not detect fake mode from the context of inputs, create one.
226
+
227
+ The created fake mode will be returned.
228
+ """
229
+ fake_mode = detect_fake_mode(example_inputs)
230
+ if not fake_mode:
231
+ fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True)
232
+ FakeTensorProp(gm, mode=fake_mode).propagate(*example_inputs)
233
+ else:
234
+ ctx = (
235
+ contextlib.nullcontext()
236
+ if not force_allow_non_fake_inputs
237
+ else mock.patch.object(fake_mode, "allow_non_fake_inputs", True)
238
+ )
239
+ with ctx: # type: ignore[attr-defined]
240
+ FakeTensorProp(gm, mode=fake_mode).propagate_dont_convert_inputs(
241
+ *example_inputs
242
+ )
243
+
244
+ return fake_mode
245
+
246
+
247
+ @DebugContext.wrap
248
+ @torch.utils._python_dispatch._disable_current_modes()
249
+ @time_and_log(attr="compilation time (in seconds)")
250
+ def compile_fx_inner(
251
+ gm: torch.fx.GraphModule,
252
+ example_inputs: List[torch.Tensor],
253
+ cudagraphs: Optional[BoxedBool] = None,
254
+ num_fixed: int = 0,
255
+ is_backward: bool = False,
256
+ graph_id: Optional[int] = None,
257
+ cpp_wrapper: bool = False,
258
+ aot_mode: bool = False,
259
+ is_inference: bool = False,
260
+ boxed_forward_device_index: Optional[BoxedDeviceIndex] = None,
261
+ user_visible_outputs: FrozenSet[str] = frozenset(),
262
+ layout_opt: Optional[bool] = None,
263
+ extern_node_serializer: Optional[Callable[[List[ExternKernelNode]], Any]] = None,
264
+ ) -> Union[CompiledFxGraph, str]:
265
+ """
266
+ Inductor API that compiles a single graph.
267
+
268
+ If you change the argument list for this function, make sure you
269
+ also update the call to save_args_for_compile_fx_inner below accordingly.
270
+ """
271
+ if dynamo_utils.count_calls(gm.graph) == 0 and not aot_mode:
272
+ return make_boxed_func(gm.forward)
273
+
274
+ assert isinstance(
275
+ next(iter(reversed(gm.graph.nodes))).args[0], (tuple, list)
276
+ ), f"inductor can only compile FX graphs which return a tuple/list, but got {gm.graph}"
277
+
278
+ if config.save_args:
279
+ save_args_for_compile_fx_inner(
280
+ gm,
281
+ example_inputs,
282
+ cudagraphs=cudagraphs,
283
+ num_fixed=num_fixed,
284
+ is_backward=is_backward,
285
+ graph_id=graph_id,
286
+ cpp_wrapper=cpp_wrapper,
287
+ aot_mode=aot_mode,
288
+ is_inference=is_inference,
289
+ boxed_forward_device_index=boxed_forward_device_index,
290
+ user_visible_outputs=user_visible_outputs,
291
+ layout_opt=layout_opt,
292
+ )
293
+
294
+ if cudagraphs is None:
295
+ cudagraphs = BoxedBool(config.triton.cudagraphs)
296
+
297
+ # Inputs to fx_codegen_and_compile
298
+ # Anything that affects codegen should go here, so if the signature
299
+ # of fx_codegen_and_compile changes, the dict should be updated accordingly
300
+ graph_kwargs = {
301
+ "cudagraphs": cudagraphs,
302
+ "num_fixed": num_fixed,
303
+ "is_backward": is_backward,
304
+ "graph_id": graph_id,
305
+ "cpp_wrapper": cpp_wrapper,
306
+ "aot_mode": aot_mode,
307
+ "is_inference": is_inference,
308
+ "user_visible_outputs": user_visible_outputs,
309
+ "layout_opt": layout_opt,
310
+ "extern_node_serializer": extern_node_serializer,
311
+ }
312
+
313
+ start = time.time()
314
+
315
+ if config.fx_graph_cache and not aot_mode:
316
+ compiled_graph = FxGraphCache.load(
317
+ fx_codegen_and_compile, gm, example_inputs, graph_kwargs
318
+ )
319
+ else:
320
+ compiled_graph = fx_codegen_and_compile(
321
+ gm, example_inputs, **graph_kwargs # type: ignore[arg-type]
322
+ )
323
+
324
+ log.debug("FX codegen and compilation took %.3fs", time.time() - start)
325
+
326
+ # Return the output strides to the caller via TracingContext
327
+ context = torch._guards.TracingContext.try_get()
328
+ if context is not None and context.output_strides is not None:
329
+ assert len(context.output_strides) == 0
330
+ context.output_strides.extend(compiled_graph.output_strides)
331
+
332
+ if aot_mode:
333
+ return compiled_graph
334
+
335
+ if cudagraphs:
336
+ # output args are tuple of first argument
337
+ output = list(gm.graph.nodes)[-1]
338
+ assert len(output.args) == 1
339
+ stack_traces = [
340
+ (arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None)
341
+ for arg in output.args[0]
342
+ ]
343
+
344
+ complex_memory_overlap_inputs = any(
345
+ complex_memory_overlap(t)
346
+ for t in example_inputs
347
+ if isinstance(t, torch.Tensor)
348
+ )
349
+
350
+ # doesnt work for non-trees because the warmup run would apply mutation twice
351
+ if config.triton.cudagraph_trees:
352
+ # checking if mutation is only on parameters/static inputs
353
+ has_mutation = not all(
354
+ idx < num_fixed for idx in compiled_graph.mutated_input_idxs
355
+ )
356
+ else:
357
+ has_mutation = len(compiled_graph.mutated_inputs) != 0
358
+
359
+ cudagraph_tests = [
360
+ (set(compiled_graph.device_types) == {"cuda"}, "non-cuda device in graph"),
361
+ (not has_mutation, "mutated inputs"),
362
+ (not has_incompatible_cudagraph_ops(gm), "incompatible ops"),
363
+ (not complex_memory_overlap_inputs, "complex memory overlap"),
364
+ (
365
+ all(
366
+ isinstance(t, (torch.Tensor, torch.SymInt)) for t in example_inputs
367
+ ),
368
+ "non-Tensor inputs",
369
+ ),
370
+ (
371
+ (
372
+ len(compiled_graph.device_idxs) == 1
373
+ or not config.triton.cudagraph_trees
374
+ ),
375
+ "multiple device indices without cudagraph_trees",
376
+ ),
377
+ ]
378
+ cudagraph_fail_reasons = [s for b, s in cudagraph_tests if not b]
379
+
380
+ if not cudagraph_fail_reasons:
381
+ if not config.triton.cudagraph_trees:
382
+ # Force specialize all inputs so that CUDA graphs will work
383
+ for t in example_inputs:
384
+ if isinstance(t, torch.SymInt):
385
+ int(t) # guard
386
+
387
+ if (
388
+ boxed_forward_device_index is not None
389
+ and not is_inference
390
+ and not is_backward
391
+ ):
392
+ boxed_forward_device_index.set(next(iter(compiled_graph.device_idxs)))
393
+
394
+ compiled_graph.current_callable = cudagraphify(
395
+ compiled_graph.get_current_callable(),
396
+ example_inputs,
397
+ static_input_idxs=range(num_fixed),
398
+ device_index=next(iter(compiled_graph.device_idxs)),
399
+ stack_traces=stack_traces,
400
+ is_backward=is_backward,
401
+ is_inference=is_inference,
402
+ constants=tuple(compiled_graph.constants.values()),
403
+ )
404
+ else:
405
+ BoxedBool.disable(cudagraphs)
406
+
407
+ # See [Backward Generation Handling]
408
+ # if cudagraph'd the forward and set the device, we need to let the cudagraph manager
409
+ # know we are we running the backward even if we will not run it in cudagraphs
410
+ if is_backward and config.triton.cudagraph_trees:
411
+ assert boxed_forward_device_index is not None
412
+ assert boxed_forward_device_index.value is not None
413
+ compiled_graph_callable = compiled_graph.get_current_callable()
414
+
415
+ manager = torch._inductor.cudagraph_trees.get_manager(
416
+ boxed_forward_device_index.value, create_if_none_exists=False
417
+ )
418
+ # should already exist from forward
419
+ assert manager is not None
420
+
421
+ def compiled_artifact(new_inputs):
422
+ manager.set_to_running_backward()
423
+ return compiled_graph_callable(new_inputs)
424
+
425
+ compiled_graph.current_callable = compiled_artifact
426
+
427
+ if "cuda" in compiled_graph.device_types:
428
+ perf_hint_log.warning(
429
+ "skipping cudagraphs due to %s", cudagraph_fail_reasons
430
+ )
431
+
432
+ # cudagraphs does its own aligning of inputs
433
+ if not cudagraphs:
434
+ new_callable = align_inputs(
435
+ compiled_graph.get_current_callable(), example_inputs, range(num_fixed)
436
+ )
437
+ if new_callable is not compiled_graph.get_current_callable():
438
+ compiled_graph.current_callable = new_callable
439
+
440
+ _step_logger()(
441
+ logging.INFO,
442
+ "torchinductor done compiling "
443
+ f"{'BACKWARDS' if is_backward else 'FORWARDS'} "
444
+ f"graph {graph_id}",
445
+ )
446
+
447
+ # aot autograd needs to know to pass in inputs as a list
448
+ compiled_graph._boxed_call = True
449
+ return compiled_graph
450
+
451
+
452
+ def fx_codegen_and_compile(
453
+ gm: torch.fx.GraphModule,
454
+ example_inputs: List[torch.Tensor],
455
+ cudagraphs: Optional[BoxedBool] = None,
456
+ num_fixed: int = 0,
457
+ is_backward: bool = False,
458
+ graph_id: Optional[int] = None,
459
+ cpp_wrapper: bool = False,
460
+ aot_mode: bool = False,
461
+ is_inference: bool = False,
462
+ user_visible_outputs: FrozenSet[str] = frozenset(),
463
+ layout_opt: Optional[bool] = None,
464
+ extern_node_serializer: Optional[Callable[[List[ExternKernelNode]], Any]] = None,
465
+ ) -> Union[CompiledFxGraph, str]:
466
+ if is_tf32_warning_applicable(gm):
467
+ _warn_tf32_disabled()
468
+
469
+ # lift the maximum depth of the Python interpreter stack
470
+ # to adapt large/deep models
471
+ sys.setrecursionlimit(max(sys.getrecursionlimit(), 2000))
472
+
473
+ _step_logger()(
474
+ logging.INFO,
475
+ "torchinductor compiling "
476
+ f"{'BACKWARDS' if is_backward else 'FORWARDS'} "
477
+ f"graph {graph_id}",
478
+ )
479
+ V.debug.fx_graph(gm, example_inputs)
480
+
481
+ shape_env = _shape_env_from_inputs(example_inputs)
482
+
483
+ # Convert view to reshape in the graph. This is necessary primarily for
484
+ # layout optimization. Do it unconditionally for uniformity.
485
+ #
486
+ # It's needed because when we do layout optimization, an contiguous tensor
487
+ # in eager mode may becomes a channels last tensor. A view op previously
488
+ # can be applied to the contiguous tensor may not be able to be applied
489
+ # on the channels tensor any more. An error like
490
+ # RuntimeError: view size is not compatible with input tensor's size and stride
491
+ # (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
492
+ # will be printed.
493
+ #
494
+ # Replace view op to reshape op in this case.
495
+ # As an example, timm_resnest/botnet26t_256/convnext_base etc. will fail if we don't do this.
496
+ #
497
+ # Also this has to be done before FakeTensorProp below to avoid the failed
498
+ # .view() call.
499
+ view_to_reshape(gm)
500
+
501
+ # It is safe to run FakeTensorProp under no_grad because by the time
502
+ # we're in inductor, we assume that AOTAutograd has already "taken care"
503
+ # of autograd, so there should be no more autograd-related API's in the
504
+ # graph.
505
+ with torch.no_grad():
506
+ fake_mode = fake_tensor_prop(gm, example_inputs)
507
+
508
+ # pattern matcher passes might not preserve striding information
509
+ # on node.meta["val"]. if in the future we rely on these being
510
+ # correct we will need to fix.
511
+
512
+ with V.set_fake_mode(fake_mode):
513
+ # has some issues with memory in training
514
+ post_grad_passes(gm, is_inference=is_inference)
515
+ V.debug.fx_graph_transformed(gm, example_inputs)
516
+ post_grad_graphs_log.info("%s", lazy_format_graph_code("AFTER POST GRAD", gm))
517
+
518
+ with V.set_fake_mode(fake_mode):
519
+ graph = GraphLowering(
520
+ gm,
521
+ # example_inputs will be used by AOTInductor to dry-run the generated code for Triton kernel tuning.
522
+ # For the forward pass, we have the real inputs to be used as example_inputs. For the backward pass,
523
+ # we currently use fake tensors and defake them later.
524
+ example_inputs=V.real_inputs if is_inference else example_inputs,
525
+ shape_env=shape_env,
526
+ num_static_inputs=num_fixed,
527
+ graph_id=graph_id,
528
+ cpp_wrapper=cpp_wrapper,
529
+ aot_mode=aot_mode,
530
+ user_visible_outputs=user_visible_outputs,
531
+ extern_node_serializer=extern_node_serializer,
532
+ is_inference=is_inference,
533
+ )
534
+ with V.set_graph_handler(graph):
535
+ graph.run(*example_inputs)
536
+ output_strides: List[Optional[Tuple[int, ...]]] = []
537
+ if graph.graph_outputs is not None:
538
+ # We'll put the output strides in the compiled graph so we
539
+ # can later return them to the caller via TracingContext
540
+ for out in graph.graph_outputs:
541
+ if hasattr(out, "layout"):
542
+ output_strides.append(
543
+ tuple(
544
+ V.graph.sizevars.size_hint(s) for s in out.layout.stride
545
+ )
546
+ )
547
+ else:
548
+ output_strides.append(None)
549
+
550
+ compiled_fn = graph.compile_to_fn()
551
+
552
+ if V.aot_compilation is True:
553
+ return compiled_fn
554
+
555
+ if graph.disable_cudagraphs:
556
+ perf_hint_log.warning(
557
+ "skipping cudagraphs due to %s", V.graph.disable_cudagraphs_reason
558
+ )
559
+ BoxedBool.disable(cudagraphs)
560
+
561
+ compiled_graph = CompiledFxGraph(compiled_fn, graph, output_strides)
562
+
563
+ return compiled_graph
564
+
565
+
566
+ def clone_preserve_strides(x: torch.Tensor):
567
+ needed_size = (
568
+ sum((shape - 1) * stride for shape, stride in zip(x.size(), x.stride())) + 1
569
+ )
570
+ buffer = torch.as_strided(x, (needed_size,), (1,)).clone()
571
+ return torch.as_strided(buffer, x.size(), x.stride())
572
+
573
+
574
+ def copy_misaligned_inputs(
575
+ new_inputs: List[torch.Tensor], check_inputs_idxs: Sequence[int]
576
+ ) -> None:
577
+ for i in check_inputs_idxs:
578
+ if new_inputs[i].data_ptr() % ALIGNMENT:
579
+ new_inputs[i] = clone_preserve_strides(new_inputs[i])
580
+
581
+
582
+ def get_input_idxs_to_check(
583
+ inputs: Union[List[torch.Tensor], Sequence[int]],
584
+ static_input_idxs: Sequence[int],
585
+ ) -> Sequence[int]:
586
+ def is_aligned(storage_offset, dtype):
587
+ return (storage_offset * get_dtype_size(dtype)) % ALIGNMENT == 0
588
+
589
+ ids_to_check = []
590
+ for i, input in enumerate(inputs):
591
+ if (
592
+ isinstance(input, torch.Tensor)
593
+ and (
594
+ i not in static_input_idxs
595
+ or not is_aligned(input.storage_offset(), input.dtype)
596
+ )
597
+ and input.device.type == "cuda"
598
+ ):
599
+ ids_to_check.append(i)
600
+ return ids_to_check
601
+
602
+
603
+ def align_inputs_from_check_idxs(
604
+ model: Callable[[List[torch.Tensor]], Any], inputs_to_check: Sequence[int]
605
+ ):
606
+ if len(inputs_to_check) == 0:
607
+ return model
608
+
609
+ def run(new_inputs):
610
+ copy_misaligned_inputs(new_inputs, inputs_to_check)
611
+ return model(new_inputs)
612
+
613
+ return run
614
+
615
+
616
+ def align_inputs(
617
+ model: Callable[[List[torch.Tensor]], Any],
618
+ inputs: List[torch.Tensor],
619
+ static_input_idxs: Sequence[int] = (),
620
+ ):
621
+ inputs_to_check = get_input_idxs_to_check(inputs, static_input_idxs)
622
+ return align_inputs_from_check_idxs(model, inputs_to_check)
623
+
624
+
625
+ @dynamo_utils.dynamo_timed
626
+ def cudagraphify(
627
+ model: torch.fx.GraphModule,
628
+ inputs: List[torch.Tensor],
629
+ static_input_idxs: Sequence[int] = (),
630
+ *,
631
+ device_index: int,
632
+ stack_traces: List[Optional[str]],
633
+ is_backward: bool,
634
+ is_inference: bool,
635
+ constants: Tuple[torch.Tensor, ...] = (),
636
+ ):
637
+ from torch._inductor.cudagraph_trees import (
638
+ cudagraphify_impl as new_cudagraphify_impl,
639
+ )
640
+
641
+ cudagraphify_fn: Callable[..., Any]
642
+ if config.triton.cudagraph_trees:
643
+ cudagraphify_fn = functools.partial(
644
+ new_cudagraphify_impl,
645
+ device_index=device_index,
646
+ stack_traces=stack_traces,
647
+ is_backward=is_backward,
648
+ is_inference=is_inference,
649
+ constants=constants,
650
+ )
651
+ else:
652
+ cudagraphify_fn = cudagraphify_impl
653
+
654
+ # if using fake tensors, defer cudagraphs until we get real inputs at runtime
655
+ if not any(isinstance(inp, FakeTensor) for inp in inputs):
656
+ return cudagraphify_fn(model, inputs, static_input_idxs)
657
+
658
+ compiled_fn = None
659
+
660
+ def run(new_inputs):
661
+ nonlocal compiled_fn
662
+ if compiled_fn is None:
663
+ with dynamo_utils.preserve_rng_state():
664
+ compiled_fn = cudagraphify_fn(model, new_inputs, static_input_idxs)
665
+ return compiled_fn(new_inputs)
666
+
667
+ return run
668
+
669
+
670
+ def remove_unaligned_input_idxs(
671
+ inputs: Union[List[torch.Tensor], Sequence[int]],
672
+ static_input_idxs: Sequence[int],
673
+ ):
674
+ """
675
+ We require all inputs to be aligned, so introduce a copy for any
676
+ that aren't.
677
+ """
678
+ aligned_static_input_idxs = []
679
+ for idx, input in zip(static_input_idxs, inputs):
680
+ if isinstance(input, torch.Tensor) and (input.data_ptr() % ALIGNMENT) == 0:
681
+ aligned_static_input_idxs.append(idx)
682
+ if len(aligned_static_input_idxs) != len(static_input_idxs):
683
+ return aligned_static_input_idxs
684
+ return static_input_idxs
685
+
686
+
687
+ def static_input(x: torch.Tensor):
688
+ """
689
+ Copy and input while preserving strides
690
+ """
691
+ # TODO(jansel): figure out why this version doesn't work:
692
+ # return torch.empty_strided(x.size(), x.stride(), dtype=x.dtype, device=x.device)
693
+ needed_size = (
694
+ sum((shape - 1) * stride for shape, stride in zip(x.size(), x.stride())) + 1
695
+ )
696
+ buffer = torch.empty(needed_size, dtype=x.dtype, device=x.device)
697
+ return torch.as_strided(buffer, x.size(), x.stride())
698
+
699
+
700
+ def index_expanded_dims_and_copy_(
701
+ dst: torch.Tensor,
702
+ src: torch.Tensor,
703
+ expanded_dims: List[int],
704
+ ):
705
+ "Index into expanded dimensions of both dst and src then copy_"
706
+ dst = index_expanded_dims(dst, expanded_dims)
707
+ src = index_expanded_dims(src, expanded_dims)
708
+ dst.copy_(src)
709
+
710
+
711
+ def cudagraphify_impl(
712
+ model: torch.fx.GraphModule,
713
+ inputs: List[torch.Tensor],
714
+ static_input_idxs: Sequence[int] = (),
715
+ ):
716
+ """
717
+ Assumes inputs[static_input_idxs[i]] are always the same memory address
718
+ """
719
+ check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs)
720
+ static_input_idxs = remove_unaligned_input_idxs(inputs, static_input_idxs)
721
+ copy_misaligned_inputs(inputs, check_input_idxs)
722
+
723
+ assert isinstance(inputs, list)
724
+
725
+ inps_expanded_dims = [
726
+ get_expanded_dims(x) if idx not in static_input_idxs else []
727
+ for idx, x in enumerate(inputs)
728
+ ]
729
+
730
+ # allocate static tensor inputs
731
+ static_inputs = [
732
+ x
733
+ if not isinstance(x, torch.Tensor)
734
+ else static_input(x)
735
+ if idx not in static_input_idxs
736
+ else x.detach()
737
+ for idx, x in enumerate(inputs)
738
+ ]
739
+
740
+ # copy over input values for fresh allocations
741
+ for idx, (x, expanded_dims) in enumerate(zip(inputs, inps_expanded_dims)):
742
+ if isinstance(x, torch.Tensor) and idx not in static_input_idxs:
743
+ index_expanded_dims_and_copy_(static_inputs[idx], x, expanded_dims)
744
+
745
+ # warmup
746
+ torch.cuda.synchronize()
747
+ stream = torch.cuda.Stream()
748
+ stream.wait_stream(torch.cuda.current_stream())
749
+ # copy static_inputs because it will be cleared in model
750
+ with torch.cuda.stream(stream):
751
+ model(list(static_inputs))
752
+ stream.synchronize()
753
+ torch.cuda.current_stream().wait_stream(stream)
754
+ torch.cuda.synchronize()
755
+
756
+ # record
757
+ graph = torch.cuda.CUDAGraph()
758
+ with torch.cuda.graph(graph, stream=stream, capture_error_mode="thread_local"):
759
+ static_outputs = model(list(static_inputs))
760
+ if not isinstance(static_outputs, (list, tuple)):
761
+ static_outputs = (static_outputs,)
762
+
763
+ if config.size_asserts:
764
+
765
+ def run(new_inputs):
766
+ assert len(static_inputs) == len(new_inputs)
767
+ for idx, (dst, src, expanded_dims) in enumerate(
768
+ zip(static_inputs, new_inputs, inps_expanded_dims)
769
+ ):
770
+ if not isinstance(dst, torch.Tensor):
771
+ pass
772
+ elif idx in static_input_idxs:
773
+ assert dst.data_ptr() == src.data_ptr()
774
+ else:
775
+ # TODO - could make one single op of multiple slices
776
+ # and avoid dispatch.
777
+ # Could also pre-index the `dst` tensors
778
+ index_expanded_dims_and_copy_(dst, src, expanded_dims)
779
+ new_inputs.clear()
780
+ graph.replay()
781
+ return static_outputs
782
+
783
+ else:
784
+ copy_indices = [
785
+ idx for idx in range(len(static_inputs)) if idx not in static_input_idxs
786
+ ]
787
+
788
+ def run(new_inputs):
789
+ for idx in copy_indices:
790
+ expanded_dims = inps_expanded_dims[idx]
791
+ index_expanded_dims_and_copy_(
792
+ static_inputs[idx], new_inputs[idx], expanded_dims
793
+ )
794
+ new_inputs.clear()
795
+ graph.replay()
796
+ return static_outputs
797
+
798
+ return align_inputs_from_check_idxs(run, check_input_idxs)
799
+
800
+
801
+ def count_tangents(fx_g: torch.fx.GraphModule):
802
+ """
803
+ Infers which inputs are static for a backwards graph
804
+ """
805
+
806
+ def is_saved_tensor(x):
807
+ return (
808
+ "tangents" not in x.name
809
+ and "bwd_seed" not in x.name
810
+ and "bwd_base_offset" not in x.name
811
+ )
812
+
813
+ arg_count = 0
814
+ static_arg_idxs = []
815
+ for n in fx_g.graph.nodes:
816
+ if n.op == "placeholder":
817
+ if is_saved_tensor(n):
818
+ static_arg_idxs.append(arg_count)
819
+ arg_count += 1
820
+
821
+ assert static_arg_idxs == list(range(len(static_arg_idxs)))
822
+ return len(static_arg_idxs)
823
+
824
+
825
+ def compile_fx_aot(
826
+ model_: torch.fx.GraphModule,
827
+ example_inputs_: List[torch.Tensor],
828
+ inner_compile: Callable[..., Any] = compile_fx_inner,
829
+ config_patches: Optional[Dict[str, Any]] = None,
830
+ ):
831
+ config_patches: Dict[str, Any] = (
832
+ {"cpp_wrapper": True}
833
+ if config_patches is None
834
+ else {**config_patches, "cpp_wrapper": True}
835
+ )
836
+ if (
837
+ "aot_inductor.output_path" not in config_patches
838
+ and not config.aot_inductor.output_path
839
+ ):
840
+ config_patches = {
841
+ **config_patches,
842
+ "aot_inductor.output_path": code_hash(model_.code),
843
+ }
844
+
845
+ extern_node_serializer = config_patches.pop("extern_node_serializer", None)
846
+ with V.set_aot_compilation(True):
847
+ compiled_lib_path = compile_fx(
848
+ model_,
849
+ example_inputs_,
850
+ inner_compile=functools.partial(
851
+ inner_compile,
852
+ aot_mode=True,
853
+ extern_node_serializer=extern_node_serializer,
854
+ ),
855
+ config_patches=config_patches,
856
+ )
857
+ assert os.path.exists(
858
+ compiled_lib_path
859
+ ), f"AOTInductor compiled library does not exist at {compiled_lib_path}"
860
+ return compiled_lib_path
861
+
862
+
863
+ _graph_counter = count(0)
864
+
865
+
866
+ def fw_compiler_freezing(
867
+ aot_autograd_model: torch.fx.GraphModule,
868
+ aot_example_inputs: List[torch.Tensor],
869
+ dynamo_model: torch.fx.GraphModule,
870
+ num_example_inputs: int,
871
+ inner_compile: Callable[..., Any],
872
+ cudagraphs: BoxedBool,
873
+ graph_id: int,
874
+ forward_device: BoxedDeviceIndex,
875
+ ):
876
+ from torch._inductor.freezing import convert_conv_weights_to_channels_last, freeze
877
+
878
+ # partition_fn won't be called
879
+ joint_graph_passes(aot_autograd_model)
880
+
881
+ layout_opt = GraphLowering.decide_layout_opt(aot_autograd_model, is_inference=True)
882
+ if layout_opt:
883
+ # make sure meta['val'] is properly setup
884
+ fake_tensor_prop(aot_autograd_model, aot_example_inputs, True)
885
+ convert_conv_weights_to_channels_last(aot_autograd_model)
886
+
887
+ opt_model, preserved_arg_indices = freeze(
888
+ dynamo_model,
889
+ aot_autograd_model,
890
+ aot_example_inputs, # type: ignore[arg-type]
891
+ )
892
+
893
+ aot_example_inputs = [aot_example_inputs[ind] for ind in preserved_arg_indices]
894
+ num_fixed = len(preserved_arg_indices) - num_example_inputs
895
+
896
+ fake_mode = detect_fake_mode(aot_example_inputs)
897
+
898
+ # for freezing, all graph outputs should be user visible
899
+ *_, model_outputs_node = opt_model.graph.nodes
900
+ model_outputs = model_outputs_node.args[0]
901
+ user_visible_outputs = [
902
+ n.name for n in model_outputs if isinstance(n, torch.fx.Node)
903
+ ]
904
+
905
+ # constant params will be real tensors, not fake
906
+ tracing_context = torch._guards.TracingContext.try_get()
907
+ if tracing_context is not None:
908
+ params_flat = tracing_context.params_flat
909
+ assert params_flat is not None
910
+ for i in range(len(params_flat)):
911
+ if i not in preserved_arg_indices:
912
+ params_flat[i] = None
913
+
914
+ with mock.patch.object(fake_mode, "allow_non_fake_inputs", True):
915
+ optimized_function = inner_compile(
916
+ opt_model,
917
+ aot_example_inputs,
918
+ num_fixed=num_fixed,
919
+ cudagraphs=cudagraphs,
920
+ graph_id=graph_id,
921
+ is_inference=True,
922
+ boxed_forward_device_index=forward_device,
923
+ layout_opt=layout_opt,
924
+ user_visible_outputs=user_visible_outputs,
925
+ )
926
+
927
+ # aot_inductor codegens a call that takes in just the inputs, so we don't return a wrapper
928
+ # that drops constant-ified params
929
+ if V.aot_compilation is True:
930
+ return optimized_function
931
+
932
+ def wrapper(args):
933
+ args_new = [args[i] for i in preserved_arg_indices]
934
+ args.clear()
935
+ return optimized_function(args_new)
936
+
937
+ wrapper._boxed_call = True # type: ignore[attr-defined]
938
+
939
+ return wrapper
940
+
941
+
942
+ def compile_fx(
943
+ model_: torch.fx.GraphModule,
944
+ example_inputs_: List[torch.Tensor],
945
+ inner_compile: Callable[..., Any] = compile_fx_inner,
946
+ config_patches: Optional[Dict[str, Any]] = None,
947
+ decompositions: Optional[Dict[OpOverload, Callable[..., Any]]] = None,
948
+ ):
949
+ """Main entrypoint to a compile given FX graph"""
950
+ if config_patches:
951
+ with config.patch(config_patches):
952
+ return compile_fx(
953
+ model_,
954
+ example_inputs_,
955
+ # need extra layer of patching as backwards is compiled out of scope
956
+ inner_compile=config.patch(config_patches)(inner_compile),
957
+ decompositions=decompositions,
958
+ )
959
+
960
+ if config.cpp_wrapper:
961
+ with config.patch(
962
+ {
963
+ "cpp_wrapper": False,
964
+ "triton.autotune_cublasLt": False,
965
+ "triton.cudagraphs": False,
966
+ "triton.store_cubin": True,
967
+ }
968
+ ), V.set_real_inputs(example_inputs_):
969
+ inputs_ = example_inputs_
970
+ if isinstance(model_, torch.fx.GraphModule):
971
+ fake_inputs = [
972
+ node.meta.get("val")
973
+ for node in model_.graph.nodes
974
+ if node.op == "placeholder"
975
+ ]
976
+ if all(v is not None for v in fake_inputs):
977
+ # Validate devices before switching to fake tensors.
978
+ for idx, fi, i in zip(count(), fake_inputs, inputs_):
979
+ if fi.device != i.device:
980
+ raise ValueError(
981
+ f"Device mismatch between fake input and example input at position #{idx}: "
982
+ f"{fi.device} vs {i.device}. If the model was exported via torch.export(), "
983
+ "make sure torch.export() and torch.aot_compile() run on the same device."
984
+ )
985
+ inputs_ = fake_inputs
986
+ return compile_fx(
987
+ model_,
988
+ inputs_,
989
+ inner_compile=functools.partial(inner_compile, cpp_wrapper=True),
990
+ decompositions=decompositions,
991
+ )
992
+
993
+ recursive_compile_fx = functools.partial(
994
+ compile_fx,
995
+ inner_compile=inner_compile,
996
+ decompositions=decompositions,
997
+ )
998
+
999
+ if not graph_returns_tuple(model_):
1000
+ return make_graph_return_tuple(
1001
+ model_,
1002
+ example_inputs_,
1003
+ recursive_compile_fx,
1004
+ )
1005
+
1006
+ if isinstance(model_, torch.fx.GraphModule):
1007
+ if isinstance(model_.graph._codegen, _PyTreeCodeGen):
1008
+ # this graph is the result of dynamo.export()
1009
+ return handle_dynamo_export_graph(
1010
+ model_,
1011
+ example_inputs_,
1012
+ recursive_compile_fx,
1013
+ )
1014
+
1015
+ model_ = pre_grad_passes(model_, example_inputs_)
1016
+
1017
+ if any(isinstance(x, (list, tuple, dict)) for x in example_inputs_):
1018
+ return flatten_graph_inputs(
1019
+ model_,
1020
+ example_inputs_,
1021
+ recursive_compile_fx,
1022
+ )
1023
+
1024
+ assert not config._raise_error_for_testing
1025
+ num_example_inputs = len(example_inputs_)
1026
+ cudagraphs = BoxedBool(config.triton.cudagraphs)
1027
+ forward_device = BoxedDeviceIndex(None)
1028
+
1029
+ graph_id = next(_graph_counter)
1030
+
1031
+ decompositions = (
1032
+ decompositions if decompositions is not None else select_decomp_table()
1033
+ )
1034
+
1035
+ @dynamo_utils.dynamo_timed
1036
+ def fw_compiler_base(
1037
+ model: torch.fx.GraphModule,
1038
+ example_inputs: List[torch.Tensor],
1039
+ is_inference: bool,
1040
+ ):
1041
+ if is_inference:
1042
+ # partition_fn won't be called
1043
+ joint_graph_passes(model)
1044
+
1045
+ num_rng_seed_offset_inputs = 2 if functorch_config.functionalize_rng_ops else 0
1046
+ fixed = len(example_inputs) - num_example_inputs - num_rng_seed_offset_inputs
1047
+ user_visible_outputs = set()
1048
+
1049
+ if config.keep_output_stride:
1050
+ *_, model_outputs_node = model.graph.nodes
1051
+ assert model_outputs_node.op == "output"
1052
+ model_outputs = pytree.arg_tree_leaves(*model_outputs_node.args)
1053
+ num_model_outputs = len(model_outputs)
1054
+
1055
+ context = torch._guards.TracingContext.try_get()
1056
+ # See Note [User Outputs in the inductor graph]
1057
+ if context is not None and context.fw_metadata and not is_inference:
1058
+ original_output_start_index = (
1059
+ context.fw_metadata.num_mutated_inp_runtime_indices
1060
+ )
1061
+ else:
1062
+ original_output_start_index = 0
1063
+
1064
+ if isinstance(model_, torch.fx.GraphModule):
1065
+ *_, orig_model_outputs_node = model_.graph.nodes
1066
+ assert orig_model_outputs_node.op == "output"
1067
+ orig_model_outputs, _ = pytree.tree_flatten(
1068
+ orig_model_outputs_node.args
1069
+ )
1070
+ num_orig_model_outputs = len(orig_model_outputs)
1071
+ else:
1072
+ num_orig_model_outputs = num_model_outputs
1073
+
1074
+ assert num_orig_model_outputs <= num_model_outputs
1075
+
1076
+ # Note [User Outputs in the inductor graph]
1077
+ # We makes the following assumption
1078
+ # For inference
1079
+ # len(orig_model_outputs) == len(model_outputs)
1080
+ # For training
1081
+ # len(orig_model_outputs) <= len(model_outputs)
1082
+ # During training, most of the time the model_outputs starts with
1083
+ # original module's outputs followed by saved activations.
1084
+ # But this can be not true if the model have inplace updated tensors.
1085
+ # AOTAutograd will make those tensors being returned before the original
1086
+ # module's output.
1087
+ # To make things safe, we'll use original_output_start_index field
1088
+ # set by AOTAutograd to decide where the original module outputs start.
1089
+ orig_output_end_idx = original_output_start_index + num_orig_model_outputs
1090
+ # Sanity chec: we are about to splice out the "user" outputs from the full set
1091
+ # of "graph" outputs. Make sure we're within bounds.
1092
+ assert orig_output_end_idx <= num_model_outputs
1093
+
1094
+ user_visible_outputs = {
1095
+ n.name
1096
+ for n in model_outputs[original_output_start_index:orig_output_end_idx]
1097
+ if isinstance(n, torch.fx.Node)
1098
+ }
1099
+
1100
+ return inner_compile(
1101
+ model,
1102
+ example_inputs,
1103
+ num_fixed=fixed,
1104
+ cudagraphs=cudagraphs,
1105
+ graph_id=graph_id,
1106
+ is_inference=is_inference,
1107
+ boxed_forward_device_index=forward_device,
1108
+ user_visible_outputs=user_visible_outputs,
1109
+ )
1110
+
1111
+ fw_compiler = functools.partial(fw_compiler_base, is_inference=False)
1112
+
1113
+ if config.freezing and not torch.is_grad_enabled():
1114
+ inference_compiler = functools.partial(
1115
+ fw_compiler_freezing,
1116
+ dynamo_model=model_,
1117
+ num_example_inputs=num_example_inputs,
1118
+ inner_compile=inner_compile,
1119
+ cudagraphs=cudagraphs,
1120
+ graph_id=graph_id,
1121
+ forward_device=forward_device,
1122
+ )
1123
+ else:
1124
+ inference_compiler = functools.partial(fw_compiler_base, is_inference=True)
1125
+
1126
+ def partition_fn(graph, joint_inputs, **kwargs):
1127
+ joint_graph_passes(graph)
1128
+ return min_cut_rematerialization_partition(
1129
+ graph, joint_inputs, **kwargs, compiler="inductor"
1130
+ )
1131
+
1132
+ @dynamo_utils.dynamo_timed
1133
+ def bw_compiler(model: torch.fx.GraphModule, example_inputs: List[torch.Tensor]):
1134
+ fixed = count_tangents(model)
1135
+ return inner_compile(
1136
+ model,
1137
+ example_inputs,
1138
+ num_fixed=fixed,
1139
+ cudagraphs=cudagraphs,
1140
+ is_backward=True,
1141
+ graph_id=graph_id,
1142
+ boxed_forward_device_index=forward_device,
1143
+ )
1144
+
1145
+ # TODO: can add logging before/after the call to create_aot_dispatcher_function
1146
+ # in torch._functorch/aot_autograd.py::aot_module_simplified::aot_function_simplified::new_func
1147
+ # once torchdynamo is merged into pytorch
1148
+
1149
+ fake_mode = detect_fake_mode(example_inputs_) or torch._subclasses.FakeTensorMode(
1150
+ allow_non_fake_inputs=True
1151
+ )
1152
+ tracing_context = (
1153
+ torch._guards.TracingContext.try_get()
1154
+ or torch._guards.TracingContext(fake_mode)
1155
+ )
1156
+
1157
+ if V.aot_compilation is True:
1158
+ gm, graph_signature = aot_export_module(
1159
+ model_, example_inputs_, trace_joint=False, decompositions=decompositions
1160
+ )
1161
+ unlifted_gm = _unlift_graph(model_, gm, graph_signature)
1162
+ with V.set_fake_mode(fake_mode), compiled_autograd.disable():
1163
+ return inference_compiler(unlifted_gm, example_inputs_)
1164
+
1165
+ with V.set_fake_mode(fake_mode), torch._guards.tracing(
1166
+ tracing_context
1167
+ ), compiled_autograd.disable():
1168
+ return aot_autograd(
1169
+ fw_compiler=fw_compiler,
1170
+ bw_compiler=bw_compiler,
1171
+ inference_compiler=inference_compiler,
1172
+ decompositions=decompositions,
1173
+ partition_fn=partition_fn,
1174
+ keep_inference_input_mutations=True,
1175
+ )(model_, example_inputs_)
1176
+
1177
+
1178
+ # pass config dict back to user
1179
+ def get_patched_config_dict(config_patches=None):
1180
+ with config.patch(config_patches):
1181
+ return config.get_config_copy()
1182
+
1183
+
1184
+ def _shape_env_from_inputs(inputs: List[torch.Tensor]):
1185
+ shape_env = None
1186
+ fake_mode = detect_fake_mode(inputs)
1187
+
1188
+ # TODO(voz): It would be nice to enable this assert, but there are lots of tests that
1189
+ # pass in real inputs for now.
1190
+ # if len(inputs) > 0:
1191
+ # assert fake_mode is not None, breakpoint()
1192
+
1193
+ if fake_mode is not None:
1194
+ return fake_mode.shape_env
1195
+
1196
+ # When there are no tensor inputs, get shape_env from the first SymInt.
1197
+ for input in inputs:
1198
+ if isinstance(input, torch.SymInt):
1199
+ return input.node.shape_env
1200
+
1201
+ # TODO(voz): Should we always have one anyway?
1202
+ return None
1203
+
1204
+
1205
+ def output_node(gm: torch.fx.GraphModule):
1206
+ """Get the output node from an FX graph"""
1207
+ last_node = next(iter(reversed(gm.graph.nodes)))
1208
+ assert last_node.op == "output"
1209
+ return last_node
1210
+
1211
+
1212
+ def graph_returns_tuple(gm: torch.fx.GraphModule):
1213
+ """True if a FX graph returns a tuple"""
1214
+ if not isinstance(gm, torch.fx.GraphModule):
1215
+ return True # can't check this, assume true
1216
+ (rv,) = output_node(gm).args
1217
+ if isinstance(rv, (list, tuple)):
1218
+ return True
1219
+ if (
1220
+ isinstance(rv, torch.fx.node.Node)
1221
+ and hasattr(rv.target, "_schema")
1222
+ and len(rv.target._schema.returns) > 1
1223
+ and all(str(ret.type) == "Tensor" for ret in rv.target._schema.returns)
1224
+ ):
1225
+ # for graphs whose result is one node with multiple outputs
1226
+ return True
1227
+ return False
1228
+
1229
+
1230
+ def make_graph_return_tuple(
1231
+ gm: torch.fx.GraphModule,
1232
+ inputs: List[torch.Tensor],
1233
+ compile_gm: Callable[..., Any],
1234
+ ):
1235
+ """
1236
+ Mutate gm so it returns a tuple. This is only needed for graphs
1237
+ not created by torchdynamo that return non-tuples.
1238
+ """
1239
+ node = output_node(gm)
1240
+ (rv,) = node.args
1241
+ rv, spec = pytree.tree_flatten(rv)
1242
+ with gm.graph.inserting_before(node):
1243
+ gm.graph.output(rv)
1244
+ gm.graph.erase_node(node)
1245
+ assert graph_returns_tuple(gm)
1246
+
1247
+ compiled_fn = compile_gm(gm, inputs)
1248
+
1249
+ @functools.wraps(compiled_fn)
1250
+ def wrapper(*args, **kwargs):
1251
+ return pytree.tree_unflatten(compiled_fn(*args, **kwargs), spec)
1252
+
1253
+ return wrapper
1254
+
1255
+
1256
+ def flatten_graph_inputs(gm: torch.fx.GraphModule, inputs, compile_gm):
1257
+ """
1258
+ Mutate inputs so that they are flat and wrap gm such that it
1259
+ accepts those inputs. This is only needed for graphs not created
1260
+ by torchdynamo that take bumpy inputs.
1261
+ """
1262
+ inputs, spec = pytree.tree_flatten(inputs)
1263
+
1264
+ class GmWrapper(torch.nn.Module):
1265
+ def __init__(self):
1266
+ super().__init__()
1267
+ self.gm = gm
1268
+
1269
+ def forward(self, *args):
1270
+ args: List[Any] = list(args)
1271
+ return self.gm(*pytree.tree_unflatten(args, spec))
1272
+
1273
+ compiled_fn = compile_gm(GmWrapper(), inputs)
1274
+
1275
+ @functools.wraps(compiled_fn)
1276
+ def wrapper(*args):
1277
+ # note this doesn't check the spec, assuming it is the same
1278
+ return compiled_fn(*pytree.arg_tree_leaves(*args))
1279
+
1280
+ return wrapper
1281
+
1282
+
1283
+ def handle_dynamo_export_graph(
1284
+ gm: torch.fx.GraphModule,
1285
+ inputs: List[torch.Tensor],
1286
+ compile_gm: Callable[..., Any],
1287
+ ):
1288
+ """
1289
+ `torch._dynamo.export` embeds pytrees in the FX graph codegen object,
1290
+ convert that to a normal FX graph so inductor can compile it.
1291
+ """
1292
+ codegen = gm.graph._codegen
1293
+ gm.graph._codegen = torch.fx.graph.CodeGen()
1294
+ gm.recompile()
1295
+
1296
+ compiled_fn = compile_gm(gm, codegen.process_inputs(*inputs))
1297
+
1298
+ @functools.wraps(compiled_fn)
1299
+ def wrapper(*args):
1300
+ return codegen.process_outputs(compiled_fn(*codegen.process_inputs(*args)))
1301
+
1302
+ return wrapper
vlmpy310/lib/python3.10/site-packages/torch/_inductor/config.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os # noqa: C101
2
+ import sys
3
+ from typing import Any, Dict, TYPE_CHECKING
4
+
5
+ import torch
6
+
7
+ # add some debug printouts
8
+ debug = False
9
+
10
+ # add inf and NaN checkers
11
+ debug_check_inf_and_nan = False
12
+
13
+ # Whether to disable a progress bar for autotuning
14
+ disable_progress = True
15
+
16
+ # Whether to enable printing the source code for each future
17
+ verbose_progress = False
18
+
19
+ # use fx aot graph codegen cache
20
+ fx_graph_cache = os.environ.get("TORCHINDUCTOR_FX_GRAPH_CACHE") == "1"
21
+
22
+ # use cpp wrapper instead of python wrapper
23
+ cpp_wrapper = False
24
+
25
+ # dead code elimination
26
+ dce = False
27
+
28
+ # assume weight tensors are fixed size
29
+ static_weight_shapes = True
30
+
31
+ # put correctness assertions in generated code
32
+ size_asserts = os.environ.get("TORCHINDUCTOR_SIZE_ASSERTS", "1") == "1"
33
+ nan_asserts = os.environ.get("TORCHINDUCTOR_NAN_ASSERTS") == "1"
34
+
35
+ # enable loop reordering based on input orders
36
+ pick_loop_orders = True
37
+
38
+ # reuse a kernel input as the output
39
+ inplace_buffers = True
40
+
41
+ # reuse a buffer for an unrelated purpose
42
+ allow_buffer_reuse = True
43
+
44
+ # Enable pooled allocations for non-output tensors
45
+ memory_planning = os.environ.get("TORCHINDUCTOR_MEMORY_PLANNING", "0") == "1"
46
+
47
+ # How to organize memory under memory_planning=True:
48
+ # - "none": do not try to pool storage, just reuse
49
+ # - "intermediates": all non-outputs share storage, outputs each get unique storage
50
+ # - "outputs": two pools, one for intermediates (freed on return) and one for outputs
51
+ # - "combined": a single pool for both intermediates and outputs
52
+ memory_pool = os.environ.get("TORCHINDUCTOR_MEMORY_POOL", "intermediates")
53
+
54
+ # codegen benchmark harness
55
+ benchmark_harness = True
56
+
57
+ # fuse pointwise into templates
58
+ epilogue_fusion = True
59
+
60
+ # do epilogue fusions before other fusions
61
+ epilogue_fusion_first = False
62
+
63
+ # enable pattern match+replace optimizations
64
+ pattern_matcher = True
65
+
66
+ # register custom graph optimization pass hook. so far, pre/post passes are
67
+ # only applied before/after pattern_matcher in post_grad_passes.
68
+ #
69
+ # def my_custom_pre_pass(graph: torch.fx.graph.Graph):
70
+ # # my custom graph optimization pass
71
+ # ...
72
+ #
73
+ # def my_custom_post_pass(graph: torch.fx.graph.Graph):
74
+ # # my custom graph optimization pass
75
+ # ...
76
+ #
77
+ # torch._inductor.config.post_grad_custom_pre_pass = my_custom_pre_pass
78
+ # torch._inductor.config.post_grad_custom_post_pass = my_custom_post_pass
79
+ post_grad_custom_pre_pass = None
80
+ post_grad_custom_post_pass = None
81
+
82
+ # Registers a custom pregrad pass. Note that the pre-grad IR is 1.
83
+ # non-functional, 2. non-normalized, and 3. prone to change. Ideally we should
84
+ # use post-grad passes.
85
+ pre_grad_custom_pass = None
86
+
87
+ # Optimize away split cat patterns (Experimental)
88
+ split_cat_fx_passes = True
89
+
90
+ # Optimize conv-batchnorm if batchnorm is in eval mode. Slightly reduces numerical stability.
91
+ efficient_conv_bn_eval_fx_passes = False
92
+
93
+ # Deprecated
94
+ group_fusion = False
95
+
96
+ # Deprecated
97
+ batch_fusion = True
98
+
99
+ # Pre grad group/batch fusion and options in order, set to empty dict to disable fusion.
100
+ # Call `torch._inductor.fx_passes.group_batch_fusion.list_group_batch_fusions()` to see available fusions.
101
+ pre_grad_fusion_options: Dict[str, Dict[str, Any]] = {
102
+ "batch_linear": {},
103
+ "batch_linear_lhs": {},
104
+ "batch_layernorm": {},
105
+ "batch_tanh": {},
106
+ "batch_relu": {},
107
+ "batch_sigmoid": {},
108
+ }
109
+
110
+ # Post grad group/batch fusion and options, set to empty dict to disable fusion.
111
+ # Call `torch._inductor.fx_passes.group_batch_fusion.list_group_batch_fusions(False)` to see available fusions.
112
+ post_grad_fusion_options: Dict[str, Dict[str, Any]] = {}
113
+
114
+ # enable reordering pass for improving memory locality
115
+ reorder_for_locality = True
116
+
117
+ # Scale down RBLOCK for better occupancy
118
+ dynamic_scale_rblock = os.environ.get("TORCHINDUCTOR_DYNAMIC_SCALE_RBLOCK", "1") == "1"
119
+
120
+ # this forces fusion for int_mm with mul. Needed when you want to avoid realizing the int32
121
+ # but the mul gets fused with other pointwise ops instead.
122
+ force_fuse_int_mm_with_mul = False
123
+
124
+ # for pattern torch.mm(a, b.to(dtype)) with cuda tensors,
125
+ # enable torch._inductor.kernel.mm.tuned_mixed_mm fused kernel.
126
+ # Autotune will compare perf with normal cast->then->mm option
127
+ use_mixed_mm = False
128
+
129
+ # for pattern torch.mm(a, b.to(dtype)) with cuda tensors, always use
130
+ # torch._inductor.kernel.mm.tuned_mixed_mm's fused kernel.
131
+ # Autotune will not compare with normal cast->then->mm option.
132
+ # (if force_mixed_mm is true, the use_mixed_mm flag will be ignored)
133
+ force_mixed_mm = False
134
+
135
+ # enable reordering pass for increasing overlap between compute and communication
136
+ reorder_for_compute_comm_overlap = False
137
+
138
+ # passes (in execution order) for increasing overlap between compute and communication
139
+ # for built-in passes, use string name; for user-defined passes, pass in the function handle
140
+ reorder_for_compute_comm_overlap_passes = [
141
+ "reorder_compute_for_overlap",
142
+ "sink_waits",
143
+ "raise_comms",
144
+ ]
145
+
146
+ # runtime estimation function for ops
147
+ # for built-in estimation function, pass in "default"; for user-defined estimation function, pass in the function handle
148
+ estimate_op_runtime = "default"
149
+
150
+ # unit: GB/s, uni-directional P2P bandwidth per card
151
+ # default value is NVLink
152
+ intra_node_bw = 300
153
+
154
+ # unit: GB/s, uni-directional P2P bandwidth per node
155
+ # default value is InfiniBand
156
+ inter_node_bw = 25
157
+
158
+ # enable slow autotuning passes to select algorithms
159
+ max_autotune = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE") == "1"
160
+
161
+ # enable slow autotuning passes to select pointwise/reductions algorithms
162
+ max_autotune_pointwise = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE") == "1"
163
+
164
+ # enable slow autotuning passes to select gemm algorithms
165
+ max_autotune_gemm = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_GEMM") == "1"
166
+
167
+ # Specify candidate backends for gemm autotune.
168
+ # Possible choices are combinations of: ATen, Triton, CUTLASS.
169
+ # ATen: default Pytorch ATen kernels.
170
+ # Triton: Triton templates defined in torch inductor.
171
+ # CUTLASS: Cutlass templates and kernels.
172
+ max_autotune_gemm_backends = os.environ.get(
173
+ "TORCHINDUCTOR_MAX_AUTOTUNE_GEMM_BACKENDS", "ATEN,TRITON"
174
+ ).upper()
175
+
176
+ # the value used as a fallback for the unbacked SymInts
177
+ # that can appear in the input shapes (e.g., in autotuning)
178
+ unbacked_symint_fallback = 8192
179
+
180
+ # enable searching global and local cache regardless of `max_autotune`
181
+ search_autotune_cache = os.environ.get("TORCHINDUCTOR_SEARCH_AUTOTUNE_CACHE") == "1"
182
+
183
+ save_args = os.environ.get("TORCHINDUCTOR_SAVE_ARGS") == "1"
184
+
185
+ # We will disable creating subprocess for autotuning if this is False
186
+ autotune_in_subproc = os.environ.get("TORCHINDUCTOR_AUTOTUNE_IN_SUBPROC") == "1"
187
+
188
+ # If autotuning in subprocess, whether to use multiple devices
189
+ autotune_multi_device = os.environ.get("TORCHINDUCTOR_AUTOTUNE_MULTI_DEVICE") == "1"
190
+
191
+ coordinate_descent_tuning = (
192
+ os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_TUNING") == "1"
193
+ )
194
+ coordinate_descent_check_all_directions = (
195
+ os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS") == "1"
196
+ )
197
+ coordinate_descent_search_radius = int(
198
+ os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_RADIUS", "1")
199
+ )
200
+
201
+ layout_optimization = os.environ.get("TORCHINDUCTOR_LAYOUT_OPTIMIZATION", "1") == "1"
202
+
203
+
204
+ force_layout_optimization = os.environ.get("TORCHINDUCTOR_FORCE_LAYOUT_OPT", "0") == "1"
205
+
206
+
207
+ # Whether to keep the output strides the same as eager after layout optimization.
208
+ keep_output_stride = os.environ.get("TORCHINDUCTOR_KEEP_OUTPUT_STRIDE", "1") == "1"
209
+
210
+ # Enabling this will let compiler print warning messages if a generated triton
211
+ # kernel has inputs with mixed layouts. This is helpful for perf debugging
212
+ # since kernel with mixed layout inputs may run much slower then one whose inputs
213
+ # have uniform layouts.
214
+ warn_mix_layout = os.environ.get("TORCHINDUCTOR_WARN_MIX_LAYOUT") == "1"
215
+
216
+ # control store vs recompute heuristic
217
+ # For fanouts, rematerialization can lead to exponential blowup. So, have
218
+ # smaller threshold
219
+ realize_reads_threshold = 4
220
+ realize_bytes_threshold = 2000
221
+
222
+ # Threshold to prevent excessive accumulation of ops in one buffer during lowering
223
+ realize_acc_reads_threshold = 8
224
+
225
+ # fallback to eager for random/dropout, this is slow but useful for debugging
226
+ fallback_random = False
227
+
228
+ # automatically create fallbacks when encountering an unhandled op
229
+ implicit_fallbacks = True
230
+
231
+ # fuse even in cases without common reads
232
+ aggressive_fusion = False
233
+
234
+ # For each fused kernel in the wrapper, comment with the nodes that get fused.
235
+ # Useful for debugging fusion.
236
+ debug_fusion = os.environ.get("TORCHINDUCTOR_DEBUG_FUSION") == "1"
237
+ benchmark_fusion = os.environ.get("TORCHINDUCTOR_BENCHMARK_FUSION") == "1"
238
+ enabled_metric_tables = os.environ.get("TORCHINDUCTOR_ENABLED_METRIC_TABLES", "")
239
+
240
+ # how many nodes to allow into a single fusion
241
+ max_fusion_size = 64
242
+
243
+ # max number of inputs to generate cat as a pointwise op with masked laods
244
+ max_pointwise_cat_inputs = 4
245
+
246
+ # replace small reductions with pointwise, disable with `= 1`
247
+ unroll_reductions_threshold = 8
248
+
249
+ # Add extra comments to output code (causes compile cache misses)
250
+ comment_origin = False
251
+
252
+ # Convert 1x1 convs into matmuls
253
+ conv_1x1_as_mm = False
254
+
255
+ # Enable split reductions for better utilization when the dimension
256
+ # being reduced over is large (by splitting it)
257
+ split_reductions = True
258
+
259
+ benchmark_kernel = os.environ.get("TORCHINDUCTOR_BENCHMARK_KERNEL", "0") == "1"
260
+
261
+ # Enable constant and index_expr folding
262
+ constant_and_index_propagation = True
263
+
264
+ # we always add constants into graph.constants without
265
+ # performing any constant-inlining optimization
266
+ always_keep_tensor_constants = False
267
+
268
+ # assert that indirect indexing does not read / write out of bounds
269
+ assert_indirect_indexing = True
270
+
271
+
272
+ def is_fbcode():
273
+ return not hasattr(torch.version, "git_version")
274
+
275
+
276
+ # constant folding on the joint graph
277
+ joint_graph_constant_folding = True
278
+
279
+ # Enable indirect_indexing asserts for decompositions and lowerings
280
+ debug_index_asserts = False
281
+
282
+ # warnings intended for PyTorch developers, disable for point releases
283
+ is_nightly_or_source = "dev" in torch.__version__ or "git" in torch.__version__
284
+ developer_warnings = is_fbcode() or is_nightly_or_source
285
+
286
+ # The multiprocessing start method to use for inductor workers in the codecache.
287
+ # TODO: fork is not safe in a multithreaded environment, we should evaluate changing
288
+ # the default to spawn.
289
+ worker_start_method = "fork"
290
+
291
+
292
+ def decide_compile_threads():
293
+ """
294
+ Here are the precedence to decide compile_threads
295
+ 1. User can override it by TORCHINDUCTOR_COMPILE_THREADS. One may want to disable async compiling by
296
+ setting this to 1 to make pdb happy.
297
+ 2. Set to 1 if it's win32 platform or it's a fbcode build
298
+ 3. decide by the number of CPU cores
299
+ """
300
+ if "TORCHINDUCTOR_COMPILE_THREADS" in os.environ:
301
+ return int(os.environ["TORCHINDUCTOR_COMPILE_THREADS"])
302
+ elif sys.platform == "win32" or is_fbcode():
303
+ return 1
304
+ else:
305
+ cpu_count = (
306
+ len(os.sched_getaffinity(0))
307
+ if hasattr(os, "sched_getaffinity")
308
+ else os.cpu_count()
309
+ )
310
+ assert cpu_count
311
+ return min(32, cpu_count)
312
+
313
+
314
+ compile_threads = decide_compile_threads()
315
+
316
+ # gemm autotuning global cache dir
317
+ if is_fbcode():
318
+ from libfb.py import parutil
319
+
320
+ try:
321
+ if __package__:
322
+ global_cache_dir = parutil.get_dir_path(
323
+ os.path.join(__package__.replace(".", os.sep), "fb/cache")
324
+ )
325
+ else:
326
+ global_cache_dir = parutil.get_dir_path("fb/cache")
327
+ except ValueError:
328
+ global_cache_dir = None
329
+ else:
330
+ global_cache_dir = None
331
+
332
+ # If kernel is fused, the name is generated from the origin node op names
333
+ # for larger kernels limit this
334
+ kernel_name_max_ops = 10
335
+
336
+ # Pad input tensors of matmul/bmm/addmm to leverage Tensor Cores in NVIDIA GPUs
337
+ shape_padding = os.environ.get("TORCHINDUCTOR_SHAPE_PADDING", "1") == "1"
338
+
339
+ # Fx-based linear/matmul/bmm + permute/transpose vertical fusion
340
+ permute_fusion = os.environ.get("TORCHINDUCTOR_PERMUTE_FUSION", "0") == "1"
341
+
342
+ # Mark the wrapper call in PyTorch profiler
343
+ profiler_mark_wrapper_call = False
344
+
345
+ # Generate hook calls to torch._inductor.hooks.run_intermediate_hooks for
346
+ # every intermediate for which we can correlate it with an intermediate
347
+ # from the original FX graph
348
+ generate_intermediate_hooks = False
349
+
350
+ # Populate traceback field on IRNode; good for debugging why origin_node is
351
+ # not populated, or finding out where an IRNode was constructed
352
+ debug_ir_traceback = False
353
+
354
+ # used for debugging to make sure config is properly set
355
+ _raise_error_for_testing = False
356
+
357
+ _profile_var = os.environ.get("TORCHINDUCTOR_PROFILE", "")
358
+ profile_bandwidth = _profile_var != ""
359
+ profile_bandwidth_regex = "" if _profile_var == "1" else _profile_var
360
+ # Specify a file where we print out the profiling results.
361
+ # None means we do not dump results to a file.
362
+ profile_bandwidth_output = os.environ.get("TORCHINDUCTOR_PROFILE_OUTPUT", None)
363
+
364
+ # TODO: remove later
365
+ disable_cpp_codegen = False
366
+
367
+
368
+ # Freezing will attempt to inline weights as constants in optimization
369
+ # and run constant folding and other optimizations on them. After freezing, weights
370
+ # can no longer be updated.
371
+ freezing: bool = os.environ.get("TORCHINDUCTOR_FREEZING", "0") == "1"
372
+
373
+ # Make freezing invalidate the eager Parameters of nn modules, to avoid memory overhead
374
+ # of potentially keeping multiple copies of weights.
375
+ freezing_discard_parameters: bool = False
376
+
377
+
378
+ # config specific to codegen/cpp.py
379
+ class cpp:
380
+ # set to torch.get_num_threads()
381
+ threads = -1
382
+
383
+ # Do not generate loops when the condition doesn't hold, like:
384
+ # for(long i0=4096; i0<4096; i0+=1)
385
+ no_redundant_loops = True
386
+
387
+ # Assume number of threads is dynamic, don't specialize thread number.
388
+ # Kernels don't recompile on thread number changes with this flag on.
389
+ # For single-threaded workload, turning it on would incur a slight
390
+ # performance degradation.
391
+ dynamic_threads = False
392
+
393
+ simdlen = None
394
+ min_chunk_size = 4096
395
+ cxx = (
396
+ None, # download gcc12 from conda-forge if conda is installed
397
+ # "g++-12",
398
+ # "g++-11",
399
+ # "g++-10",
400
+ # "clang++",
401
+ os.environ.get("CXX", "g++"),
402
+ # "g++.par",
403
+ )
404
+ # Allow kernel performance profiling via PyTorch profiler
405
+ enable_kernel_profile = False
406
+
407
+ # enable weight prepacking to get a better performance; may lead to large memory footprint
408
+ weight_prepack = True
409
+
410
+ # Inject a bug into our relu implementation; useful for testing our repro
411
+ # extraction and minification functionality.
412
+ # Valid values: "compile_error", "runtime_error", "accuracy"
413
+ inject_relu_bug_TESTING_ONLY = None
414
+ inject_log1p_bug_TESTING_ONLY = None
415
+
416
+ # If None, autodetect whether or not AVX512/AVX2 can be used. Otherwise,
417
+ # force usage as specified, without testing.
418
+ vec_isa_ok = None
419
+
420
+ # similar to config.triton.descriptive_names
421
+ descriptive_names = "original_aten"
422
+
423
+ # how many nodes to allow into a single horizontal fusion
424
+ max_horizontal_fusion_size = 16
425
+
426
+ # Make scatter_reduce fallback when reduce is sum to avoid performance regression
427
+ # using atomic_add.
428
+ fallback_scatter_reduce_sum = True
429
+
430
+ # Use funsafe-math-optimizations when compiling
431
+ enable_unsafe_math_opt_flag = False
432
+
433
+
434
+ # config specific to codegen/triton.py
435
+ class triton:
436
+ # Use cudagraphs on output code
437
+ cudagraphs = False
438
+
439
+ # Use cudagraph trees for memory pooling if `cudagraphs` is True
440
+ cudagraph_trees = True
441
+
442
+ # assertions not on the fast path, steady state
443
+ slow_path_cudagraph_asserts = True
444
+
445
+ # TODO - need to debug why this prevents cleanup
446
+ cudagraph_trees_history_recording = False
447
+
448
+ # assertions on the fast path
449
+ fast_path_cudagraph_asserts = False
450
+
451
+ # skip warmup for cudagraph trees
452
+ skip_cudagraph_warmup = False
453
+
454
+ # Synchronize before and after every compiled graph.
455
+ debug_sync_graph = False
456
+
457
+ # Synchronize after every kernel launch, to help pinpoint bugs
458
+ debug_sync_kernel = False
459
+
460
+ # Always load full blocks (rather than broadcasting inside the block)
461
+ dense_indexing = False
462
+
463
+ # limit tiling dimensions
464
+ max_tiles = 2
465
+
466
+ # use triton.autotune for pointwise ops with complex layouts
467
+ # this should only be disabled for debugging/testing
468
+ autotune_pointwise = True
469
+
470
+ # max autotune gemm with cublasLt
471
+ autotune_cublasLt = True
472
+
473
+ # should we stop a fusion to allow better tiling?
474
+ tiling_prevents_pointwise_fusion = True
475
+ tiling_prevents_reduction_fusion = True
476
+
477
+ # should we give different names to kernels
478
+ # Note: This is orthogonal to descriptive_names - this is deciding whether
479
+ # our triton kernel names should all be `triton_` (to maximize caching) or
480
+ # whether they should be unique.
481
+ unique_kernel_names = os.environ.get("TORCHINDUCTOR_UNIQUE_KERNEL_NAMES") == "1"
482
+
483
+ # should we put op names in kernel names
484
+ # False: No special names (just triton__1, triton__2, etc.)
485
+ # "torch": Maps to the fx op in the Dynamo graph (module name, method name, etc.)
486
+ # "original_aten": Maps to the highest-level aten op (i.e. pre-decompositions)
487
+ # "inductor_node": Maps to the node name in the FX graph passed to Inductor
488
+ descriptive_names = "original_aten"
489
+
490
+ # use alternate codegen for smaller reductions
491
+ persistent_reductions = (
492
+ os.environ.get("TORCHINDUCTOR_PERSISTENT_REDUCTIONS", "1") == "1"
493
+ )
494
+
495
+ # hint to Triton when arguments are divisible by 16
496
+ divisible_by_16 = True
497
+
498
+ # theses are not enforced, but they are used by asserts in triton_heuristics.py
499
+ # NOTE: mobilevit_s in timm_models required X to be set to the higher value 2048
500
+ max_block = {"X": 2048, "Y": 1024, "Z": 1024}
501
+
502
+ # Store the generated cubin files for cpp wrapper code to load
503
+ store_cubin = False
504
+
505
+ # the max number of spills we allow for the configs we benchmark.
506
+ # Setting this to 0 means we skip a config if it spills even a single
507
+ # register.
508
+ # Setting it to a larger value allows a config spilling a small amount
509
+ # of registers being benchmarked.
510
+ #
511
+ # NOTE: triton will always report >0 register spills for kernels using sin/cos.
512
+ # (check this issue https://github.com/openai/triton/issues/1756 )
513
+ # So far we see a fixed 8 spilled registers for kernels using sin/cos.
514
+ # Raise the threshold to 16 to be safe.
515
+ # We should revisit this once we understand more of the source of register spills.
516
+ spill_threshold: int = 16
517
+
518
+ # Inject a bug into our relu implementation; useful for testing our repro
519
+ # extraction and minification functionality.
520
+ # Valid values: "compile_error", "runtime_error", "accuracy"
521
+ inject_relu_bug_TESTING_ONLY = None
522
+
523
+
524
+ class aot_inductor:
525
+ # AOTInductor output path
526
+ # If an absolute path is specified, the generated lib files will be stored under the directory;
527
+ # If a relative path is specified, it will be used as a subdirectory under the default caching path;
528
+ # If not specified, a temp directory will be created under the default caching path.
529
+ # If the specified path contains something like "model.so", the sub-string will be used
530
+ # to name the generated library.
531
+ output_path = ""
532
+
533
+ debug_compile = os.environ.get("AOT_INDUCTOR_DEBUG_COMPILE", "0") == "1"
534
+
535
+ # Wether to codegen abi compatible model.so
536
+ abi_compatible = is_fbcode()
537
+
538
+ # Serialized tree spec for flattening inputs
539
+ serialized_in_spec = ""
540
+
541
+ # Serialized tree spec for flattening outputs
542
+ serialized_out_spec = ""
543
+
544
+
545
+ class cuda:
546
+ # CUDA arch to use for CUDA template kernel compilation.
547
+ # e.g. "70", "75", "80", "90", etc.
548
+ # When arch is None, Inductor uses torch.cuda.get_device_capability(0).
549
+ arch = None
550
+
551
+ # CUDA version to use for CUDA template kernel compilation.
552
+ # e.g. "11.4", "12.1", etc.
553
+ # When version is None, Inductor uses torch.version.cuda.
554
+ version = None
555
+
556
+ # Optimization level for the host compiler.
557
+ compile_opt_level = "-O1"
558
+
559
+ # Whether to enable device LTO (link-time-optimization).
560
+ enable_cuda_lto = False
561
+
562
+ # Whether to keep intermediate files dring compilation.
563
+ enable_ptxas_info = False
564
+
565
+ # Whether to enable debug info, e.g. line number, cutlass debug info.
566
+ enable_debug_info = False
567
+
568
+ # Whether to use fast math.
569
+ use_fast_math = False
570
+
571
+ # Path to the CUTLASS repo root directory.
572
+ # The default path only works under PyTorch local development environment.
573
+ cutlass_dir = os.environ.get(
574
+ "TORCHINDUCTOR_CUTLASS_DIR",
575
+ os.path.abspath(
576
+ os.path.join(os.path.dirname(torch.__file__), "../third_party/cutlass/")
577
+ ),
578
+ )
579
+
580
+ # Configures the maximum number of CUTLASS configs to profile in max_autotune.
581
+ # By default it's None, so that all CUTLASS configs are tuned.
582
+ # This is mainly used to reduce test time in CI.
583
+ cutlass_max_profiling_configs = None
584
+
585
+ # Path to CUDA NVCC.
586
+ # NVCC search order:
587
+ # 1) cuda_cxx set in this config
588
+ # 2)CUDACXX environment variable
589
+ # 3)CUDA_HOME environment variable
590
+ # 4) default system search PATH.
591
+ cuda_cxx = None
592
+
593
+ # If set to True, it will ensure that only GEMM ops capable of
594
+ # epilogue fusion via CUTLASS Epilogue Visitor Trees ( EVT )
595
+ # are enabled for the CUTLASS backend.
596
+ cutlass_only_evt_capable_ops: bool = False
597
+
598
+
599
+ # create a directory containing lots of debug information
600
+ class trace:
601
+ # master switch for all debugging flags below
602
+ enabled = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
603
+
604
+ # Save debug information to a temporary directory
605
+ # If not specified, a temp directory will be created by system
606
+ debug_dir = None
607
+
608
+ # Save python logger call >=logging.DEBUG
609
+ debug_log = False
610
+
611
+ # Save python logger call >=logging.INFO
612
+ info_log = False
613
+
614
+ # Save input FX graph (post decomps, pre optimization)
615
+ fx_graph = True
616
+
617
+ # Save FX graph after transformations
618
+ fx_graph_transformed = True
619
+
620
+ # Save TorchInductor IR before fusion pass
621
+ ir_pre_fusion = True
622
+
623
+ # Save TorchInductor IR after fusion pass
624
+ ir_post_fusion = True
625
+
626
+ # Copy generated code to trace dir
627
+ output_code = True
628
+
629
+ # SVG figure showing post-fusion graph
630
+ graph_diagram = os.environ.get("INDUCTOR_POST_FUSION_SVG", "0") == "1"
631
+
632
+ # SVG figure showing fx with fusion
633
+ draw_orig_fx_graph = os.environ.get("INDUCTOR_ORIG_FX_SVG", "0") == "1"
634
+
635
+ # We draw our fx graphs with the "record" shape attribute by default.
636
+ # Sometimes, when the graph is very complex, we may hit dot errors like below:
637
+ # "flat edge between adjacent nodes one of which has a record shape -
638
+ # replace records with HTML-like labels"
639
+ # and thus fail to generate a graph. So, let's give the user an option
640
+ # to specify the shape attribute for the dot graph. For example, passing
641
+ # INDUCTOR_DOT_GRAPH_SHAPE_SVG = "none" would let us generate HTML-like lables
642
+ # to workaround the above failure.
643
+ dot_graph_shape = os.environ.get("INDUCTOR_DOT_GRAPH_SHAPE_SVG", None)
644
+
645
+ # Store cProfile (see snakeviz to view)
646
+ compile_profile = False
647
+
648
+ # Upload the .tar.gz file
649
+ # Needs to be overriden based on specific environment needs
650
+ upload_tar = None
651
+
652
+
653
+ _save_config_ignore = {
654
+ # workaround: "Can't pickle <function ...>"
655
+ "trace.upload_tar",
656
+ }
657
+
658
+ if TYPE_CHECKING:
659
+ from torch.utils._config_typing import * # noqa: F401, F403
660
+
661
+ from torch.utils._config_module import install_config_module
662
+
663
+ # adds patch, save_config, etc
664
+ install_config_module(sys.modules[__name__])
vlmpy310/lib/python3.10/site-packages/torch/_inductor/constant_folding.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ from typing import Any, Callable, Dict, Optional
3
+
4
+ import torch
5
+ import torch.utils._pytree as pytree
6
+
7
+ aten = torch.ops.aten
8
+
9
+
10
+ def replace_node_with_constant(gm, node, constant):
11
+ g = gm.graph
12
+
13
+ if not hasattr(gm, "_frozen_param_count"):
14
+ gm._frozen_param_count = 0
15
+
16
+ i = gm._frozen_param_count
17
+
18
+ while True:
19
+ qualname = f"_frozen_param{i}"
20
+ if not hasattr(gm, qualname):
21
+ break
22
+ i += 1
23
+
24
+ gm._frozen_param_count = i + 1
25
+
26
+ with g.inserting_before(node):
27
+ new_input_node = g.create_node("get_attr", qualname, (), {})
28
+ node.replace_all_uses_with(new_input_node)
29
+ new_input_node.meta.update(node.meta)
30
+ g.erase_node(node)
31
+
32
+ # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning
33
+ gm.register_buffer(qualname, constant)
34
+ setattr(gm, qualname, constant)
35
+
36
+
37
+ class ConstantFolder(torch.fx.Interpreter):
38
+ def __init__(
39
+ self,
40
+ gm,
41
+ skip_constructors=False,
42
+ ):
43
+ super().__init__(gm)
44
+ self.node_replacements: Dict[torch.fx.Node, Any] = {}
45
+ self.replaced_uses: Dict[torch.fx.Node, int] = collections.Counter()
46
+ self.unknown_value = object()
47
+ self.skip_constructors: bool = skip_constructors
48
+
49
+ # overwrite this to deallocate env values if their only remaining use
50
+ # is the output
51
+ self.user_to_last_uses = self.node_to_last_non_output_use()
52
+
53
+ def is_impure(self, node: torch.fx.node.Node):
54
+ if node.target in [
55
+ torch.ops.quantized_decomposed.dequantize_per_channel.default,
56
+ torch.ops.quantized_decomposed.dequantize_per_tensor.default,
57
+ torch.ops.quantized_decomposed.dequantize_per_tensor.tensor,
58
+ ]:
59
+ # For the pattern fp32_weight -> q -> dq
60
+ # We only folding fp32_weight -> q
61
+ # int8_weight and leave dq in graph to be fused
62
+ return True
63
+ return False
64
+
65
+ def node_to_last_non_output_use(self):
66
+ last_non_output_use = collections.defaultdict(list)
67
+ seen_uses = set()
68
+ output_node = next(iter(reversed(self.module.graph.nodes)))
69
+
70
+ for node in reversed(self.module.graph.nodes):
71
+ if node.target == "output":
72
+ continue
73
+
74
+ def add_use(inp):
75
+ if inp in seen_uses:
76
+ return
77
+
78
+ seen_uses.add(inp)
79
+ last_non_output_use[node].append(inp)
80
+
81
+ pytree.tree_map_only(torch.fx.Node, add_use, (node.args, node.kwargs))
82
+
83
+ # if this node is only used in output, we want to gc it right away
84
+ if len(node.users) == 1 and output_node in node.users:
85
+ last_non_output_use[node].append(node)
86
+
87
+ return last_non_output_use
88
+
89
+ def run_node(self, node):
90
+ if node.target == "output":
91
+ # because we remove nodes from env on last non output use,
92
+ # re-define them now or we'll get error in interpreter
93
+ def set_env(arg):
94
+ self.env[arg] = self.unknown_value
95
+
96
+ pytree.tree_map_only(torch.fx.Node, set_env, node.args)
97
+ return super().run_node(node)
98
+
99
+ args, kwargs = self.fetch_args_kwargs_from_env(node)
100
+ flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs)
101
+
102
+ if self.unknown_value in flattened_inputs:
103
+ return self.unknown_value
104
+
105
+ # TODO - fix errors with this
106
+ if (
107
+ node.op == "call_function"
108
+ and node.target == aten._efficientzerotensor.default
109
+ ):
110
+ return self.unknown_value
111
+
112
+ # skip constructors, since inductor generates optimal code for them already
113
+ # and turning into tensor would result in an additional global memory read
114
+ # TODO - more complicated strategy
115
+ if (
116
+ self.skip_constructors
117
+ and node.op != "get_attr"
118
+ and not any(isinstance(e, torch.Tensor) for e in flattened_inputs)
119
+ ):
120
+ return self.unknown_value
121
+
122
+ # All mutations should either be removed or on inputs which we did not make constant
123
+ if (
124
+ isinstance(node.target, torch._ops.OpOverload)
125
+ and torch.Tag.nondeterministic_seeded in node.target.tags
126
+ ):
127
+ return self.unknown_value
128
+
129
+ out = super().run_node(node)
130
+
131
+ if node.op != "get_attr" and isinstance(out, torch.Tensor):
132
+ if not self.insertable_tensor_check(out):
133
+ return out
134
+
135
+ if self.is_impure(node):
136
+ return self.unknown_value
137
+
138
+ self.add_node_replacement(node, out)
139
+
140
+ flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs)
141
+
142
+ for n in flattened_node_inps:
143
+ if not isinstance(n, torch.fx.Node):
144
+ continue
145
+
146
+ self.replaced_uses[n] += 1
147
+
148
+ for to_delete in self.user_to_last_uses.get(node, []):
149
+ if self.replaced_uses[to_delete] == len(to_delete.users):
150
+ self.node_replacements.pop(to_delete, None)
151
+
152
+ return out
153
+
154
+ def insertable_tensor_check(self, tensor: torch.Tensor) -> bool:
155
+ return True
156
+
157
+ def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None:
158
+ self.node_replacements[node] = tensor
159
+
160
+ def run(self):
161
+ env = {}
162
+ for n in self.module.graph.nodes:
163
+ if n.op == "placeholder":
164
+ env[n] = self.unknown_value
165
+ return super().run(initial_env=env)
166
+
167
+
168
+ @torch.utils._python_dispatch._disable_current_modes()
169
+ def constant_fold(gm, constraint_fn: Optional[Callable[[torch.fx.Node], bool]] = None):
170
+ cf = ConstantFolder(gm, skip_constructors=True)
171
+ cf.run()
172
+
173
+ for node, constant in cf.node_replacements.items():
174
+ if constraint_fn is not None and not constraint_fn(node):
175
+ continue
176
+ replace_node_with_constant(gm, node, constant)
177
+
178
+ erased_params = []
179
+ for node in gm.graph.nodes:
180
+ if node.op == "get_attr" and len(node.users) == 0:
181
+ if hasattr(gm, node.target):
182
+ delattr(gm, node.target)
183
+ erased_params.append(node)
184
+
185
+ for node in erased_params:
186
+ gm.graph.erase_node(node)
187
+
188
+ gm.graph.eliminate_dead_code()
189
+ gm.graph.lint()
190
+ gm.recompile()
vlmpy310/lib/python3.10/site-packages/torch/_inductor/coordinate_descent_tuner.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import itertools
3
+ import logging
4
+ from typing import Callable, Optional
5
+
6
+ from torch.utils._triton import has_triton
7
+ from .utils import red_text, triton_config_to_hashable
8
+
9
+ if has_triton():
10
+ import triton
11
+ else:
12
+ triton = None
13
+
14
+ from . import config as inductor_config
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ def get_field(config, name):
20
+ if name == "num_warps":
21
+ return config.num_warps
22
+ elif name == "num_stages":
23
+ return config.num_stages
24
+ else:
25
+ return config.kwargs.get(name, None)
26
+
27
+
28
+ def set_field(config, name, value):
29
+ if name == "num_warps":
30
+ config.num_warps = value
31
+ elif name == "num_stages":
32
+ config.num_stages = value
33
+ else:
34
+ config.kwargs[name] = value
35
+
36
+
37
+ class CoordescTuner:
38
+ """
39
+ The coordinate descent tuner. Tune one field/coordinate at a time.
40
+
41
+ TODO will it be necessary to tune multiple fields simultaneously.
42
+
43
+
44
+ TODO: what if both increasing and decreasing a field can improve perf.
45
+ i.e., there are multiple local optima..
46
+ """
47
+
48
+ def __init__(self, is_mm=False, name="unknown", size_hints=None):
49
+ self.is_mm = is_mm # we will tune num_stages for mm
50
+ self.cached_benchmark_results = {}
51
+ self.name = name
52
+ self.size_hints = size_hints
53
+
54
+ def get_xmax(self):
55
+ xmax = inductor_config.triton.max_block["X"]
56
+ if self.size_hints and len(self.size_hints) > 0:
57
+ xmax = min(xmax, self.size_hints[0])
58
+ return xmax
59
+
60
+ def get_ymax(self):
61
+ ymax = inductor_config.triton.max_block["Y"]
62
+ if self.size_hints and len(self.size_hints) > 1:
63
+ ymax = min(ymax, self.size_hints[1])
64
+ return ymax
65
+
66
+ def get_zmax(self):
67
+ zmax = inductor_config.triton.max_block["Z"]
68
+ if self.size_hints and len(self.size_hints) > 2:
69
+ zmax = min(zmax, self.size_hints[2])
70
+ return zmax
71
+
72
+ def get_rmax(self):
73
+ if self.size_hints and len(self.size_hints) > 0:
74
+ return self.size_hints[-1] # the last one is for reduction
75
+ else:
76
+ # large enough. We should not pick this large RBLOCK anyway
77
+ return 2**30
78
+
79
+ def get_warpsmax(self):
80
+ # Currently, CUDA has a maximum of 1024 threads, so 32 is the max
81
+ # number of warps.
82
+ return 1024 // 32
83
+
84
+ def cache_benchmark_result(self, config, timing):
85
+ self.cached_benchmark_results[triton_config_to_hashable(config)] = timing
86
+
87
+ def lookup_in_cache(self, config):
88
+ return self.cached_benchmark_results.get(triton_config_to_hashable(config))
89
+
90
+ def call_func(self, func, config):
91
+ found = self.lookup_in_cache(config)
92
+ if found is not None:
93
+ log.debug(" CACHED")
94
+ return found
95
+ timing = func(config)
96
+ self.cache_benchmark_result(config, timing)
97
+ return timing
98
+
99
+ @property
100
+ def tunable_fields(self):
101
+ out = [
102
+ "XBLOCK",
103
+ "YBLOCK",
104
+ "ZBLOCK",
105
+ # NOTE: we should not tune RBLOCK for persistent reduction.
106
+ # We rely on the fact that persistent reduction's triton.Config
107
+ # does not have the RBLOCK field to guarantee that.
108
+ "RBLOCK",
109
+ # the following 3 are for mm
110
+ "BLOCK_M",
111
+ "BLOCK_N",
112
+ "BLOCK_K",
113
+ "num_warps",
114
+ ]
115
+ if self.is_mm:
116
+ out.append("num_stages")
117
+
118
+ return out
119
+
120
+ def value_too_large(self, name, val):
121
+ if name == "XBLOCK":
122
+ return val > self.get_xmax()
123
+ if name == "YBLOCK":
124
+ return val > self.get_ymax()
125
+ if name == "ZBLOCK":
126
+ return val > self.get_zmax()
127
+ if name == "RBLOCK":
128
+ return val > self.get_rmax()
129
+ if name == "num_warps":
130
+ return val > self.get_warpsmax()
131
+
132
+ return False
133
+
134
+ def get_neighbour_values(self, name, orig_val, radius=1, include_self=False):
135
+ """
136
+ Get neighbour values in 'radius' steps. The original value is not
137
+ returned as it's own neighbour.
138
+ """
139
+ assert radius >= 1
140
+
141
+ def update(cur_val, inc=True):
142
+ if name == "num_stages":
143
+ if inc:
144
+ return cur_val + 1
145
+ else:
146
+ return cur_val - 1
147
+ else:
148
+ if inc:
149
+ return cur_val * 2
150
+ else:
151
+ return cur_val // 2
152
+
153
+ out = []
154
+ # increment loop
155
+ cur_val = orig_val
156
+ for _ in range(radius):
157
+ cur_val = update(cur_val, True)
158
+ if self.value_too_large(name, cur_val):
159
+ break
160
+ out.append(cur_val)
161
+
162
+ # decrement loop
163
+ cur_val = orig_val
164
+ for _ in range(radius):
165
+ cur_val = update(cur_val, False)
166
+ if cur_val <= 0:
167
+ break
168
+ out.append(cur_val)
169
+
170
+ if include_self:
171
+ out.append(orig_val)
172
+ return out
173
+
174
+ @staticmethod
175
+ def has_improvement(baseline, test):
176
+ threshold = 0.001 # 0.1%
177
+ return test is not None and test < baseline * (1 - threshold)
178
+
179
+ def check_all_tuning_directions(
180
+ self,
181
+ func: Callable[["triton.Config"], float],
182
+ best_config,
183
+ best_timing,
184
+ ):
185
+ """
186
+ Check all directions. We only do this once the regular coordinate
187
+ descent tuning find no better choices any more.
188
+ We only have a few tunable fields, so this should be fine.
189
+ """
190
+ candidate_values_list = []
191
+ effective_fields = []
192
+ for field in self.tunable_fields:
193
+ old_value = get_field(best_config, field)
194
+ if old_value is None:
195
+ continue
196
+ candidate_values = self.get_neighbour_values(
197
+ field,
198
+ old_value,
199
+ radius=inductor_config.coordinate_descent_search_radius,
200
+ include_self=True,
201
+ )
202
+ candidate_values_list.append(candidate_values)
203
+ effective_fields.append(field)
204
+
205
+ choices = itertools.product(*candidate_values_list)
206
+ improved = False
207
+ for choice in choices:
208
+ assert len(choice) == len(effective_fields)
209
+ candidate_config = copy.deepcopy(best_config)
210
+ for new_val, field in zip(choice, effective_fields):
211
+ set_field(candidate_config, field, new_val)
212
+ cmp_res, candidate_timing = self.compare_config(
213
+ func, candidate_config, best_config, best_timing
214
+ )
215
+ if cmp_res:
216
+ improved = True
217
+ best_config = candidate_config
218
+ best_timing = candidate_timing
219
+
220
+ return improved, best_config, best_timing
221
+
222
+ def compare_config(self, func, candidate_config, best_config, best_timing):
223
+ """
224
+ Check if candidate_config is better than best_config.
225
+
226
+ Return a touple of (compare_result, candidate_timing).
227
+ compare_result is true iff candidate_config is better.
228
+ """
229
+ log.debug("Try config %s", candidate_config)
230
+ try:
231
+ candidate_timing = self.call_func(func, candidate_config)
232
+ except Exception as e:
233
+ log.debug("Got exception %s", e)
234
+ return False, float("inf")
235
+
236
+ if self.has_improvement(best_timing, candidate_timing):
237
+ log.debug(
238
+ "Tune from %s %f -> %s %f",
239
+ best_config,
240
+ best_timing,
241
+ candidate_config,
242
+ candidate_timing,
243
+ )
244
+
245
+ return True, candidate_timing
246
+ return False, candidate_timing
247
+
248
+ def autotune(
249
+ self,
250
+ func: Callable[["triton.Config"], float],
251
+ baseline_config: "triton.Config",
252
+ baseline_timing: Optional[float] = None,
253
+ ) -> "triton.Config":
254
+ if baseline_timing is None:
255
+ baseline_timing = self.call_func(func, baseline_config)
256
+
257
+ log.debug("= Do coordinate descent tuning for %s =", self.name)
258
+ log.debug(
259
+ "Baseline Config %s, baseline timing %f", baseline_config, baseline_timing
260
+ )
261
+ improved = True
262
+ best_config = baseline_config
263
+ best_timing = baseline_timing
264
+ tunable_fields = self.tunable_fields
265
+
266
+ while improved:
267
+ improved = False
268
+
269
+ for name in tunable_fields:
270
+ cur_val = get_field(best_config, name)
271
+ # some kernel don't have RBLOCK/YBLOCK/ZBLOCK. So cur_val may be None
272
+ if cur_val is None:
273
+ continue
274
+
275
+ # It's possible that candidate_values is empty.
276
+ # E.g., if XBLOCK is 1 initially and size_hint for x is also 1.
277
+ # We would not try either larger or smaller XBLOCK in this case.
278
+ candidate_values = self.get_neighbour_values(name, cur_val)
279
+
280
+ for next_val in candidate_values:
281
+ candidate_config = copy.deepcopy(best_config)
282
+ set_field(candidate_config, name, next_val)
283
+
284
+ cmp_res, candidate_timing = self.compare_config(
285
+ func, candidate_config, best_config, best_timing
286
+ )
287
+ if cmp_res:
288
+ improved = True
289
+ best_config, best_timing = candidate_config, candidate_timing
290
+
291
+ if not improved and inductor_config.coordinate_descent_check_all_directions:
292
+ old_best_timing = best_timing
293
+ improved, best_config, best_timing = self.check_all_tuning_directions(
294
+ func, best_config, best_timing
295
+ )
296
+
297
+ if improved:
298
+ msg = red_text(
299
+ "Coordinate descend tuning found improvement of %.3fx by looking in all directions."
300
+ )
301
+ log.debug(
302
+ msg,
303
+ old_best_timing / best_timing,
304
+ )
305
+
306
+ log.debug(
307
+ "Improve from %s %f -> %s %f, %.3fx",
308
+ baseline_config,
309
+ baseline_timing,
310
+ best_config,
311
+ best_timing,
312
+ baseline_timing / best_timing,
313
+ )
314
+
315
+ return best_config
vlmpy310/lib/python3.10/site-packages/torch/_inductor/cudagraph_trees.py ADDED
@@ -0,0 +1,2157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CUDA graph trees are a safety abstraction over CUDAGraphs, similar to make_graph_callables,
3
+ which share the same memory pool. Sharing a memory pool is an extremely
4
+ important optimization when chaining multiple CUDA graphs together, as it
5
+ prevents you from needing to copy intermediate tensors from one graph to the
6
+ next, and reduces overall memory usage by allowing dead memory from the first
7
+ pool to be reused in the second.
8
+
9
+ The standard graph/make_graph_callables support sharing memory pool, but
10
+ with a lot of caveats. CUDA graph trees remove these restrictions:
11
+
12
+ * Previously, if you recorded graphs A, B, you had to replay A, B in that
13
+ order. With CUDA graph trees, after replaying A, you can change your
14
+ mind and record/replay a different graph B'; we will support efficient
15
+ execution of both A, B and A, B', using only max(mem(A, B), mem(A, B')). In
16
+ other words: we support arbitrary trees of CUDA graph operations, not just
17
+ sequences (this is why this feature is called CUDA graph trees.)
18
+
19
+ * Previously, if you executed graph A, some non-CUDA graph code, and then
20
+ graph B, after executing graph B, it was not safe to retain any references
21
+ to intermediates produced by A. With CUDA graph trees, we track if any
22
+ outputs of graph A are still live by the time graph B is run, and make
23
+ sure graph B doesn't clobber there memory when reusing the CUDA graphs
24
+ pool. You'll get a separate recording of B depending on what tensors
25
+ stay live or dead.
26
+
27
+ CUDA graph trees are flexible enough to be used in Dynamo across graph breaks,
28
+ which is their primary use case.
29
+
30
+ The ability to switch from replay to record is fairly nontrivial: remember that
31
+ when you replay a CUDA graph, you only replay CUDA operations; no CPU side state
32
+ is updated. In particular, the CPU-side book-keeping for the allocator is not
33
+ reconstructed. However, to record a new child CUDA graph, we must restore this
34
+ book-keeping. This is what checkpoint pool state is used for.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import contextlib
40
+ import dataclasses
41
+ import functools
42
+ import gc
43
+ import itertools
44
+ import logging
45
+ import operator
46
+ import sys
47
+ import threading
48
+ import traceback
49
+ import warnings
50
+ import weakref
51
+ from collections import defaultdict
52
+
53
+ from enum import auto, Enum
54
+ from typing import (
55
+ Any,
56
+ Callable,
57
+ cast,
58
+ Dict,
59
+ Iterator,
60
+ List,
61
+ Optional,
62
+ Sequence,
63
+ Set,
64
+ Tuple,
65
+ Union,
66
+ )
67
+
68
+ import torch.fx
69
+ from torch import Tensor
70
+ from torch._dynamo.mutation_guard import GenerationTracker
71
+ from torch._dynamo.utils import preserve_rng_state
72
+ from torch._inductor.compile_fx import (
73
+ align_inputs_from_check_idxs,
74
+ copy_misaligned_inputs,
75
+ get_expanded_dims,
76
+ get_input_idxs_to_check,
77
+ index_expanded_dims,
78
+ remove_unaligned_input_idxs,
79
+ static_input,
80
+ )
81
+ from torch.multiprocessing.reductions import StorageWeakRef
82
+ from torch.storage import UntypedStorage
83
+ from torch.types import _bool
84
+ from torch.utils import _pytree as pytree
85
+ from torch.utils.weak import TensorWeakRef
86
+
87
+ StorageWeakRefPointer = int
88
+ StorageDataPtr = int
89
+ NBytes = int
90
+
91
+ if torch.backends.cuda.is_built():
92
+ from torch._C import (
93
+ _cuda_CUDAAllocator_AllocatorState as AllocatorState,
94
+ _set_cached_tensors_enabled as _set_cached_tensors_enabled,
95
+ )
96
+ else:
97
+
98
+ class AllocatorState: # type: ignore[no-redef]
99
+ pass
100
+
101
+ def _set_cached_tensors_enabled(enabled: _bool) -> None:
102
+ pass
103
+
104
+
105
+ log = logging.getLogger(__name__)
106
+
107
+ from . import config
108
+
109
+
110
+ @dataclasses.dataclass(frozen=True)
111
+ class GraphID:
112
+ "Unique counter of a cuda graph recording"
113
+ id: int
114
+
115
+
116
+ @dataclasses.dataclass(frozen=True)
117
+ class FunctionID:
118
+ "Unique counter of a function wrapped in cudagraphify_impl"
119
+ id: int
120
+
121
+
122
+ @dataclasses.dataclass(frozen=True)
123
+ class WrappedFunction:
124
+ """
125
+ Represents a function that you want to record for CUDA graph replay,
126
+ with a little more metadata so we can identify if we have an applicable
127
+ CUDA graph in our CUDA graph tree for it.
128
+ """
129
+
130
+ model: Callable[..., Any]
131
+ static_input_idxs: Sequence[int]
132
+ id: FunctionID
133
+ constants: Tuple[torch.Tensor, ...]
134
+
135
+
136
+ def clear_cublass_cache():
137
+ """
138
+ Cublas keeps a persistent workspace allocation for running matmuls. This poses a problem for
139
+ doing warmup within a CUDAGraph private pool because we do not want persistent allocations from
140
+ one one run to the next. When we begin a new run of a cudagraphs path (generation), all tensors
141
+ from the previous generation are freed. This frees them the memory pool, but not elsewhere.
142
+ A tensor in the cublas workspace would continue to be in use the workspace but would also get allocated
143
+ in the next run. The memory would be in use in two places.
144
+
145
+ To solve this, we clear cublas caches before and after warming up or recording. If a workspace is required
146
+ it will be allocated to the cudagraph private pool and accounted for in the allocator for the duration of the
147
+ program. There is no overhead to this on replay since cudagraphs removes allocation overhead.
148
+ """
149
+ torch._C._cuda_clearCublasWorkspaces()
150
+
151
+
152
+ @contextlib.contextmanager
153
+ def clear_cublas_manager():
154
+ "Context manager around clearing cublas caches that will clear on enter and exit"
155
+ clear_cublass_cache()
156
+ try:
157
+ yield
158
+ finally:
159
+ clear_cublass_cache()
160
+
161
+
162
+ @contextlib.contextmanager
163
+ def disable_conv_cache_emptying():
164
+ prev = torch._C._cuda_get_conv_benchmark_empty_cache()
165
+ torch._C._cudnn_set_conv_benchmark_empty_cache(False)
166
+ try:
167
+ yield
168
+ finally:
169
+ torch._C._cudnn_set_conv_benchmark_empty_cache(prev)
170
+
171
+
172
+ @contextlib.contextmanager
173
+ def enable_history_recording():
174
+ "Turns on history recording in the CUDA Caching Allocator"
175
+ enabled = torch._C._cuda_isHistoryEnabled()
176
+ try:
177
+ if not enabled:
178
+ torch.cuda.memory._record_memory_history()
179
+ yield
180
+ finally:
181
+ if not enabled:
182
+ torch.cuda.memory._record_memory_history(None)
183
+
184
+
185
+ def get_history_recording():
186
+ # TODO - remove, prevents cleanup
187
+ if not config.triton.cudagraph_trees_history_recording:
188
+ return contextlib.nullcontext()
189
+ return enable_history_recording()
190
+
191
+
192
+ class TreeManagerContainer:
193
+ """
194
+ Manages the lifetime of the tree manager. Like `PrivatePool` in cuda caching allocator,
195
+ the tree and its corresponding memory pool should be kept alive as long as any outstanding
196
+ graph or tensor which is an output of a graph remains alive.
197
+
198
+ There is a single tree manager container per device.
199
+
200
+ The lifecycle of a tree_manager is:
201
+ - Is constructed, no graph, no fns, no tensors
202
+ - Tree manager is fetched, resulting in tree manager being allocated
203
+ - We generate a bunch of functions, calling add_strong_reference
204
+ - These functions die, calling finalize_reference
205
+ - When all the functions die, we finalize_tree_manager.
206
+
207
+ TODO: in the future, we would like to do the following once storage weak refs land
208
+ - We look for all the live storages and add references to THOSE
209
+ - We count as storages die
210
+ - All the storages are dead, we deallocate the tree manager
211
+ """
212
+
213
+ def __init__(self, device_index):
214
+ # This class keeps a strong reference to tree_manager,
215
+ # but upon all other strong references to the tree_manager will reset it to None.
216
+ # We need a strong reference so that we can still access its attributes upon cleanup.
217
+ self.tree_manager: Optional[CUDAGraphTreeManager] = None
218
+
219
+ # Number of outstanding references to the current tree manager
220
+ self.live_cudagraphify_fns = 0
221
+
222
+ self.device_index = device_index
223
+
224
+ # Following two objects are only set in the case that Tensor outputs outlive
225
+ # the cudagraphify_fns. Reference to the Graph is needed to keep the private pool from
226
+ # deallocation.
227
+ self.live_storages_count = 0
228
+ self.graph: Optional[torch.cuda.CUDAGraph] = None
229
+
230
+ self.lock = threading.Lock()
231
+
232
+ def _finalize_tensor(self):
233
+ with self.lock:
234
+ self.live_storages_count -= 1
235
+ if self.live_storages_count == 0:
236
+ self.graph = None
237
+
238
+ # manager was used again after existing cleanup,
239
+ # we shouldnt set it to None
240
+ if self.live_cudagraphify_fns == 0:
241
+ self.tree_manager = None
242
+
243
+ def finalize_cudagraphify_fn(self):
244
+ with self.lock:
245
+ self.live_cudagraphify_fns -= 1
246
+ if self.live_cudagraphify_fns == 0:
247
+ self._finalize_tree_manager()
248
+
249
+ def _finalize_tree_manager(self):
250
+ assert self.lock.locked()
251
+ self.tree_manager = None
252
+
253
+ # TODO - when issue #91395 is landed, we can set a weakref on
254
+ # storages and trigger a deallocation when all outputs of the
255
+ # cudagraph are dead.
256
+
257
+ # live_storages = list(
258
+ # tree_manager.live_cudagraph_pool_storages_in_curr_execution()
259
+ # )
260
+
261
+ # # Maintain reference to graph to keep tensors alive
262
+ # assert len(tree_manager.roots) > 0, "expected at least one use"
263
+ # root = next(tree_manager.get_roots())
264
+ # self.graph = root.graph
265
+ # seen_storages = set()
266
+ # for stor in live_storages:
267
+ # if stor in seen_storages:
268
+ # continue
269
+ # seen_storages.add(stor)
270
+ # self.live_storages_count += 1
271
+ # . weakref.finalize(stor, self._finalize_tensor)
272
+
273
+ def add_strong_reference(self, fn: Callable[..., Any]):
274
+ with self.lock:
275
+ self.live_cudagraphify_fns += 1
276
+
277
+ weakref.finalize(fn, self.finalize_cudagraphify_fn)
278
+
279
+ def get_tree_manager(self) -> CUDAGraphTreeManager:
280
+ with self.lock:
281
+ if self.tree_manager is None:
282
+ self.tree_manager = CUDAGraphTreeManager(self.device_index)
283
+ return self.tree_manager
284
+
285
+
286
+ local = threading.local()
287
+
288
+ # one tree manager per device
289
+ local.tree_manager_containers = {}
290
+ local.tree_manager_locks = defaultdict(threading.Lock)
291
+
292
+
293
+ # only incremented by user call of mark_step_begin
294
+ class MarkStepBox:
295
+ mark_step_counter = 0
296
+
297
+
298
+ # We need to register this as an object that will be copied over as TLS when new
299
+ # threads are created in autograd
300
+ torch._C._stash_obj_in_tls("tree_manager_containers", local.tree_manager_containers)
301
+ torch._C._stash_obj_in_tls("tree_manager_locks", local.tree_manager_locks)
302
+
303
+
304
+ def mark_step_begin():
305
+ "Indicates that a new iteration of inference or training is about to begin."
306
+
307
+ # iterate down to distinguish from GenerationTracking counter
308
+ MarkStepBox.mark_step_counter -= 1
309
+
310
+
311
+ def reset_cudagraph_trees():
312
+ "Clear all cudagraph trees"
313
+ # see shutdown below for why this is necessary
314
+ container_dict = get_obj(local, "tree_manager_containers")
315
+ locks_dict = get_obj(local, "tree_manager_locks")
316
+ for device, lock in locks_dict.items():
317
+ with lock:
318
+ container = container_dict.get(device)
319
+ if not container or not container.tree_manager:
320
+ continue
321
+
322
+ container.tree_manager.shutdown()
323
+
324
+ _set_cached_tensors_enabled(False)
325
+ container_dict.clear()
326
+
327
+ MarkStepBox.mark_step_counter = 0
328
+
329
+
330
+ def get_obj(local, attr_name):
331
+ if hasattr(local, attr_name):
332
+ return getattr(local, attr_name)
333
+ else:
334
+ assert torch._C._is_key_in_tls(attr_name)
335
+ return torch._C._get_obj_in_tls(attr_name)
336
+
337
+
338
+ def get_container(device_index: int):
339
+ container_dict = get_obj(local, "tree_manager_containers")
340
+ lock = get_obj(local, "tree_manager_locks")[device_index]
341
+
342
+ with lock:
343
+ if device_index not in container_dict:
344
+ container_dict[device_index] = TreeManagerContainer(device_index)
345
+
346
+ return container_dict[device_index]
347
+
348
+
349
+ def get_manager(
350
+ device_index: int, create_if_none_exists=True
351
+ ) -> Optional[CUDAGraphTreeManager]:
352
+ if create_if_none_exists:
353
+ return get_container(device_index).get_tree_manager()
354
+ return get_container(device_index).tree_manager
355
+
356
+
357
+ def cudagraphify_impl(model, inputs, static_input_idxs, *args, **kwargs):
358
+ fn_cache: Dict[Tuple[int, ...], Callable[..., Any]] = {}
359
+
360
+ # Detect int inputs: we need to index on these
361
+ int_key = [i for i, v in enumerate(inputs) if isinstance(v, int)]
362
+ get_ints: Any = operator.itemgetter(*int_key) if int_key else lambda _: None
363
+
364
+ del inputs
365
+
366
+ def deferred_cudagraphify(inputs):
367
+ int_key = get_ints(inputs)
368
+ fn = fn_cache.get(int_key)
369
+ if fn is not None:
370
+ return fn(inputs)
371
+
372
+ log.info("recording cudagraph tree for %s", int_key)
373
+
374
+ # first get indices we need to check to align, then update our static inputs,
375
+ # and finally copy
376
+ check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs)
377
+ new_static_input_idxs = remove_unaligned_input_idxs(inputs, static_input_idxs)
378
+ copy_misaligned_inputs(inputs, check_input_idxs)
379
+
380
+ fn, out = cudagraphify(model, inputs, new_static_input_idxs, *args, **kwargs)
381
+ fn = align_inputs_from_check_idxs(fn, inputs_to_check=check_input_idxs)
382
+ fn_cache[int_key] = fn
383
+
384
+ return out
385
+
386
+ return deferred_cudagraphify
387
+
388
+
389
+ def cudagraphify(
390
+ model,
391
+ inputs,
392
+ static_input_idxs=(),
393
+ *,
394
+ device_index: int,
395
+ is_backward: bool,
396
+ is_inference: bool,
397
+ stack_traces: Optional[StackTraces] = None,
398
+ constants: Tuple[torch.Tensor, ...] = (),
399
+ ):
400
+ manager = get_container(device_index).get_tree_manager()
401
+ assert not (is_backward and is_inference)
402
+ mode = (
403
+ CompilationMode.BACKWARD
404
+ if is_backward
405
+ else (CompilationMode.INFERENCE if is_inference else CompilationMode.FORWARD)
406
+ )
407
+
408
+ return manager.add_function(
409
+ model,
410
+ inputs,
411
+ static_input_idxs,
412
+ stack_traces,
413
+ mode,
414
+ constants,
415
+ )
416
+
417
+
418
+ class StorageWeakRefWrapper:
419
+ """
420
+ Wrapper around a storage weak ref. Will deallocate it upon expiration if invoked.
421
+ """
422
+
423
+ __slots__ = ["ref", "_data_ptr", "extra_ref_check"]
424
+
425
+ storage_ref: Optional[StorageWeakRef]
426
+
427
+ def __init__(
428
+ self,
429
+ inp: Union[Tensor, UntypedStorage],
430
+ extra_ref_check: Optional[Callable[[], None]] = None,
431
+ ):
432
+ """
433
+ extra_ref_check is an additional check we need to run to check if the
434
+ weak ref has expired. in checking storage use count we assume extra_ref_check
435
+ will hold an additional reference to the storage.
436
+ """
437
+ if isinstance(inp, Tensor):
438
+ stor = inp.untyped_storage()
439
+ else:
440
+ assert isinstance(inp, UntypedStorage)
441
+ stor = inp
442
+ self.ref = StorageWeakRef(stor)
443
+ self._data_ptr = stor.data_ptr()
444
+ self.extra_ref_check = extra_ref_check
445
+
446
+ @classmethod
447
+ def from_weakref_and_data_ptr(cls, cdata, data_ptr, extra_ref_check=None):
448
+ instance = cls.__new__(cls)
449
+ instance._data_ptr = data_ptr
450
+ instance.ref = StorageWeakRef.from_weakref(cdata)
451
+ instance.extra_ref_check = extra_ref_check
452
+ return instance
453
+
454
+ def __call__(self) -> Optional[StorageWeakRefPointer]:
455
+ if self.expired():
456
+ return None
457
+
458
+ return self.ref.cdata
459
+
460
+ def swap_weakref(self, cdata):
461
+ self.ref.__del__()
462
+ self.ref.cdata = cdata
463
+
464
+ def data_ptr(self) -> int:
465
+ "NB: returns the data ptr even if the storage has expired"
466
+ return self._data_ptr
467
+
468
+ def remove_extra_reference(self):
469
+ self.extra_ref_check = None
470
+
471
+ def expired(self):
472
+ if self.extra_ref_check is not None and not self.extra_ref_check():
473
+ return False
474
+
475
+ # if extra_ref_check is not None we expect an additional reference
476
+ stor_count = torch._C._storage_Use_Count(self.ref.cdata)
477
+ return (stor_count - (self.extra_ref_check is not None)) == 0
478
+
479
+ def __repr__(self):
480
+ if self.ref is None or self.ref.expired():
481
+ return f"StorageWeakRefWrapper to {self.data_ptr()}; dead"
482
+ else:
483
+ return f"StorageWeakRefWrapper to {self.data_ptr()}; alive"
484
+
485
+
486
+ def is_live(weak_ref: Optional[StorageWeakRefWrapper]) -> bool:
487
+ return maybe_deref(weak_ref) is not None
488
+
489
+
490
+ def maybe_deref(
491
+ weak_ref: Optional[StorageWeakRefWrapper],
492
+ ) -> Optional[Tuple[StorageWeakRefPointer, int]]:
493
+ if weak_ref is None:
494
+ return None
495
+ r = weak_ref()
496
+ if r is None:
497
+ return None
498
+ # NB: r.data_ptr() does not necessarily equal weak_ref.data_ptr()
499
+ return r, weak_ref.data_ptr()
500
+
501
+
502
+ @contextlib.contextmanager
503
+ def _use_cuda_memory_pool_manager(device, mem_pool, stream):
504
+ """
505
+ Context manager to use cuda graph pool for new allocations. If you use this manager
506
+ all cudagraph tensors in use should be reflected in the allocator or they will be overwritten.
507
+ existing_graph should already have been used in a capture, and the mem_pool must already exist,
508
+ because this manager will not preserve a reference to the pool which keeps it alive.
509
+ """
510
+ torch.cuda.synchronize()
511
+ stream.wait_stream(torch.cuda.current_stream())
512
+
513
+ with torch.cuda.stream(stream), torch.device(device):
514
+ torch._C._cuda_beginAllocateCurrentStreamToPool(device, mem_pool)
515
+ try:
516
+ yield
517
+ finally:
518
+ torch._C._cuda_endAllocateCurrentStreamToPool(device)
519
+ torch._C._cuda_releasePool(device, mem_pool)
520
+
521
+
522
+ def map_to_ref(t: Optional[Tensor]) -> Optional[StorageWeakRefWrapper]:
523
+ if not isinstance(t, torch.Tensor):
524
+ assert t is None
525
+ return None
526
+ return StorageWeakRefWrapper(t)
527
+
528
+
529
+ # A path index of (depth, offset) indices into a graph that is `depth`` number of nodes from the root
530
+ # at graph output offset
531
+ PathOutputIndex = Tuple[int, int]
532
+
533
+ # For each node in the path, for each output, is the output alive
534
+ PathLiveness = List[List[bool]]
535
+
536
+ StackTraces = List[Optional[str]]
537
+
538
+
539
+ class CUDAWarmupNode:
540
+ """
541
+ Simplified Wrapper around A CUDA Model that wraps outputs in storage refs and exposes
542
+ apis to get the live storages in the current chain of warmup.
543
+
544
+ A CUDAWarmupNode may have either CUDAGraphNode or CUDAWarmupNode as a parent, but may only have
545
+ CUDAWarmupNode as children, because we cannot record or execute with tensors which do not have stable
546
+ memory addresses.
547
+
548
+ CUDAWarmupNode and CUDAGraphNode have a number of differences that make it easier to use separate classes.
549
+ - Much of the CUDAGraphNode logic & initialization is based on the tensor properties of first recording. In the
550
+ first instance of warmup, these are not finalized yet.
551
+ - All Inputs to the RecordedFunction must be copied over to the cuda graph memory pool, this is unnecessary in warmup.
552
+ - CUDAWarmup is only used once and so does not need to optimize as much bookkeeping. It is much simpler.
553
+
554
+ NB: this class and CUDAGraphNode need to expose `path_live_weakrefs`, `all_outputs_are_dead`, and
555
+ `self.outputs_weakrefs`, `stack_traces`, and `tensor_weakrefs` for compatibility.
556
+ """
557
+
558
+ def __init__(
559
+ self,
560
+ wrapped_function: WrappedFunction,
561
+ parent,
562
+ cuda_graphs_pool: Tuple[int, int],
563
+ existing_cuda_graph: Optional[torch.cuda.CUDAGraph],
564
+ device_index: int,
565
+ stack_traces: Optional[StackTraces],
566
+ stream: torch.cuda.Stream,
567
+ already_warm: bool,
568
+ ):
569
+ self.wrapped_function = wrapped_function
570
+ self.parent = parent
571
+ self.cuda_graphs_pool = cuda_graphs_pool
572
+ self.outputs_weakrefs: List[Optional[StorageWeakRefWrapper]] = []
573
+ self.tensor_weakrefs: List[Optional[TensorWeakRef]] = []
574
+ self.existing_cuda_graph = existing_cuda_graph
575
+ self.has_run = False
576
+ self.device_index = device_index
577
+ self.stack_traces = stack_traces
578
+ self.stream = stream
579
+ self.already_warm = already_warm
580
+
581
+ def run(self, new_inputs):
582
+ assert not self.has_run, "Wrapped function should never be run twice"
583
+
584
+ # See: output_is_alias_of_persistent_static_inputs below. We should only be returning freshly created
585
+ # storages in path_live_weakrefs.
586
+ existing_path_data_ptrs = {
587
+ t.data_ptr() for t in self.path_live_weakrefs() if t()
588
+ }
589
+
590
+ def get_non_cudagraph_inps():
591
+ non_cudagraph_inps = set()
592
+ for t in itertools.chain(new_inputs, self.wrapped_function.constants):
593
+ if (
594
+ isinstance(t, torch.Tensor)
595
+ and t.untyped_storage().data_ptr() not in existing_path_data_ptrs
596
+ ):
597
+ non_cudagraph_inps.add(t.untyped_storage().data_ptr())
598
+ return non_cudagraph_inps
599
+
600
+ non_cudagraph_inps = get_non_cudagraph_inps()
601
+
602
+ if config.triton.slow_path_cudagraph_asserts and not self.already_warm:
603
+ refs = list(self.path_live_weakrefs())
604
+ check_memory_pool(self.device_index, self.cuda_graphs_pool, refs)
605
+
606
+ with torch.cuda.device(
607
+ self.device_index
608
+ ), disable_conv_cache_emptying(), clear_cublas_manager(), _use_cuda_memory_pool_manager(
609
+ self.device_index, self.cuda_graphs_pool, self.stream
610
+ ), get_history_recording():
611
+ out = self.wrapped_function.model(new_inputs)
612
+
613
+ # sync up stream used in `_use_cuda_memory_pool_manager` - TODO - wait stream instead ?
614
+ torch.cuda.synchronize()
615
+
616
+ assert len(new_inputs) == 0
617
+
618
+ # sdpa returns cpu tensors when not recording cuda graph
619
+ def add_ref(o):
620
+ return (
621
+ o is not None
622
+ and isinstance(o, torch.Tensor)
623
+ and o.is_cuda
624
+ and o.untyped_storage().data_ptr() not in non_cudagraph_inps
625
+ and o.untyped_storage().data_ptr() != 0
626
+ )
627
+
628
+ self.outputs_weakrefs.extend(
629
+ [map_to_ref(o) if add_ref(o) else None for o in out]
630
+ )
631
+ self.tensor_weakrefs.extend(
632
+ [TensorWeakRef(o) if add_ref(o) else None for o in out]
633
+ )
634
+
635
+ if config.triton.slow_path_cudagraph_asserts and not self.already_warm:
636
+ out_refs = self.path_live_weakrefs()
637
+ new_storages = [
638
+ t for t in out_refs if t.data_ptr() not in non_cudagraph_inps
639
+ ]
640
+ check_memory_pool(self.device_index, self.cuda_graphs_pool, new_storages)
641
+
642
+ return out
643
+
644
+ @property
645
+ def _path_from_root(self):
646
+ nodes = []
647
+ node = self
648
+ while node:
649
+ nodes.append(node)
650
+ node = node.parent
651
+
652
+ yield from reversed(nodes)
653
+
654
+ def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]:
655
+ "Returns all live storages weakrefs that created by nodes in this path"
656
+ for node in self._path_from_root:
657
+ for output in node.outputs_weakrefs:
658
+ if is_live(output):
659
+ yield output
660
+
661
+ def all_outputs_are_dead(self):
662
+ return not list(self.path_live_weakrefs())
663
+
664
+
665
+ # Aliases for List that say what the indices denote
666
+ InputList = List # input indexes
667
+ OutputList = List # output indexes
668
+ LevelList = List # levels (distance from root of tree)
669
+
670
+
671
+ class OutputAliasInfo:
672
+ pass
673
+
674
+
675
+ class _UnaliasedStorage(OutputAliasInfo):
676
+ "Singleton to mark that the graph output constructs a new alias or is None"
677
+ pass
678
+
679
+
680
+ UnaliasedStorage = _UnaliasedStorage()
681
+
682
+
683
+ class AliasesPriorGraphOutput(OutputAliasInfo):
684
+ "Marks that the graph output aliases an output of a prior graph"
685
+ __slots__ = ["index"]
686
+
687
+ index: PathOutputIndex
688
+
689
+ def __init__(self, index: PathOutputIndex):
690
+ assert isinstance(index, tuple)
691
+ self.index = index
692
+
693
+
694
+ class AliasesNewOutput(OutputAliasInfo):
695
+ "Marks that the graph output aliases an index in the new, returned outputs"
696
+
697
+ __slots__ = ["index"]
698
+
699
+ index: int
700
+
701
+ def __init__(self, index):
702
+ assert isinstance(index, int)
703
+ self.index = index
704
+
705
+
706
+ class CUDAGraphNode:
707
+ """
708
+ A single recording of a function into a CUDA Graph. Recordings of CUDA Graphs share a single memory pool
709
+ and are structured into a tree, where there is a single recording that can precede it (parent) and multiple
710
+ subsequent recordings that may follow (children). A node will have no parent if it is the first recording
711
+ in a tree; i.e., when it is first recorded, there are no live tensors from a previous recording which
712
+ would force a dependency.
713
+
714
+ On first recording, all of the live tensors in the current CUDA Graph Node path will be
715
+ reflected in the corresponding private pool. On subsequent executions, the caching allocator
716
+ is unaffected when the graph is replayed.
717
+
718
+ In order to support recording a subsequent cuda graph recording after execution of this graph,
719
+ we checkpoint the state of the memory pool so that it may later be resumed.
720
+
721
+ WrappedFunction should have already been warmed up prior to invocation.
722
+
723
+ See [setCheckpointPoolState] for further explanation, as well as
724
+ https://user-images.githubusercontent.com/13564/222815509-374f3400-f83d-4f7d-8fa6-4a092b3250bb.png
725
+ """
726
+
727
+ def __init__(
728
+ self,
729
+ wrapped_function: WrappedFunction,
730
+ id: GraphID,
731
+ parent: Optional[CUDAGraphNode],
732
+ inputs: List[Tensor],
733
+ cuda_graphs_pool: Tuple[int, int],
734
+ device_index: int,
735
+ stack_traces: Optional[StackTraces],
736
+ stream: torch.cuda.Stream,
737
+ ):
738
+ assert isinstance(inputs, (list, tuple))
739
+
740
+ self.wrapped_function = wrapped_function
741
+ self.id = id
742
+ self.device = device_index
743
+ self.stack_traces = stack_traces
744
+ self.stream = stream
745
+
746
+ # if this is a root parent will be None. use weakref to prevent reference cycle
747
+ self._parent = weakref.ref(parent) if parent is not None else None
748
+ # reference to the shared memory pool for the entire cuda graphs tree
749
+ self.cuda_graphs_pool = cuda_graphs_pool
750
+
751
+ # A single wrapped function may be recorded multiple times if memory patterns or
752
+ # invariants change from one execution to the next
753
+ self.children: Dict[FunctionID, List[CUDAGraphNode]] = defaultdict(list)
754
+
755
+ # StorageWeakRef maintains whether the Storage C++ object remains allocated,
756
+ # not whether the corresponding memory has been deallocated. In order
757
+ # to use them to track memory deallocations we must maintain a single StorageWeakRef
758
+ # for all Storages that reference that memory (even if we are constructing Storages
759
+ # that do not have a deallocator function). We maintain one single storage_cache
760
+ # as we execute any tree path. When we retrieve a storage from the cache we
761
+ # check that it is still alive, and we hash based on observed recording data ptr
762
+ # and storage cdata.
763
+
764
+ # we preserve a single reference to executed outputs that is then referenced
765
+ # in children to avoid children having to chase parent pointers in the hot path
766
+ # DO NOT reassign output_weakrefs, only call `clear()`
767
+ # Path is a series of nodes from root to the current node
768
+ self.outputs_weakrefs: OutputList[Optional[StorageWeakRefWrapper]] = []
769
+ self.path_weakrefs: LevelList[OutputList[Optional[StorageWeakRefWrapper]]] = [
770
+ node.outputs_weakrefs for node in self._path_from_root
771
+ ]
772
+ self.path_stacktraces: LevelList[StackTraces] = [
773
+ node.stack_traces for node in self._path_from_root
774
+ ]
775
+ self.tensor_weakrefs: OutputList[Optional[TensorWeakRef]] = []
776
+
777
+ # tensors which are outputs of previous graphs in the tree
778
+ self.cudagraph_managed_idxs: List[int] = [
779
+ idx
780
+ for idx, t in enumerate(inputs)
781
+ if isinstance(t, torch.Tensor) and self._is_cuda_graph_recorded_tensor(t)
782
+ ]
783
+
784
+ self.static_input_idxs: List[int] = list(
785
+ set(wrapped_function.static_input_idxs) | set(self.cudagraph_managed_idxs)
786
+ )
787
+
788
+ self.static_input_data_ptrs: InputList[Optional[int]] = [
789
+ (
790
+ inputs[i].data_ptr()
791
+ if isinstance(inputs[i], torch.Tensor) and i in self.static_input_idxs
792
+ else None
793
+ )
794
+ for i in range(len(inputs))
795
+ ]
796
+
797
+ # When we checkpoint, and free generations, we will be manually freeing the outputs
798
+ # of CUDAGraphNodes. We should not be freeing parameters, not do we need to account for
799
+ # their liveness (they are static), so we need to compute which outputs are aliases of
800
+ # parameters. Some static inputs are saved tensors from the forward that die in the backward.
801
+ # Their locations are static but lifetimes are not. We only include the persistent static
802
+ # data ptrs below because the non persistent data ptrs may be outputs of this record and
803
+ # fresh allocations.
804
+
805
+ # precompute expanded dims to avoid computing in the hot path
806
+ self.expanded_dims: List[List[int]] = [
807
+ get_expanded_dims(x)
808
+ if isinstance(x, torch.Tensor) and idx not in self.static_input_idxs
809
+ else []
810
+ for idx, x in enumerate(inputs)
811
+ ]
812
+
813
+ # For each node in path, which outputs were observed to be live
814
+ # before invoking graph recording, and after graph recording
815
+ self.recorded_liveness_before_graph: LevelList[OutputList[bool]] = []
816
+ self.recorded_liveness_after_graph: LevelList[OutputList[bool]] = []
817
+
818
+ # List of Tuples of (depth, output_index) that index into node at depth
819
+ # number of nodes from root and output_index of outputs. Will index into
820
+ # path_weakrefs.
821
+ self.expected_dead_indices_before_graph: List[PathOutputIndex] = []
822
+ self.expected_dead_indices_after_graph: List[PathOutputIndex] = []
823
+
824
+ # all live indices after graph recording
825
+ self.live_indices_after_graph: List[PathOutputIndex] = []
826
+
827
+ if self.parent is not None:
828
+ previous_liveness = self.parent.recorded_liveness_after_graph
829
+ curr_liveness = self._get_liveness(self.path_weakrefs)
830
+
831
+ different_indices = self._get_different_indices(
832
+ previous_liveness, curr_liveness
833
+ )
834
+
835
+ self.recorded_liveness_before_graph = curr_liveness
836
+ self.expected_dead_indices_before_graph = different_indices
837
+
838
+ recording_inputs = self._allocate_and_copy_recording_inputs(inputs)
839
+ # recording inputs will copy over memory, so we can free non recording inputs
840
+ inputs.clear()
841
+ del inputs
842
+
843
+ # graph used for recording model invocation
844
+ self.graph: Optional[torch.cuda.CUDAGraph] = torch.cuda.CUDAGraph()
845
+
846
+ # we allocate non-static inputs within the same memory pool as the CUDAGraph
847
+ # which we will record the model with. For memory efficiency, it is important
848
+ # to reclaim the input memory when the inputs are no longer live. To accomplish this,
849
+ # we reconstruct tensors at the correct data pointers of our inputs which are
850
+ # non owning and do not prevent deallocation. On subsequent executions, input values
851
+ # will be copied over to these tensors.
852
+ self.reconstructed_inputs: InputList[Union[Tensor, int]] = [
853
+ self._reconstruct_from_tensor_metadata(self._tensor_metadata(x))
854
+ if isinstance(x, torch.Tensor)
855
+ else x
856
+ for x in recording_inputs
857
+ ]
858
+
859
+ # DO THE RECORDING!!!
860
+ # We record the CUDA graph in the constructor of CUDAGraphNode, which
861
+ # gives you what the CPU side compute of the function would do. We
862
+ # don't throw the recording outputs away: their memory is
863
+ # correctly accounted for in the CUDAGraphs caching allocator. This
864
+ # means on the very FIRST run of the CUDA graph node, we can directly
865
+ # do more recording, because we have a valid caching allocator state.
866
+ # NB: This relies on run() being called immediately after the
867
+ # constructor, otherwise this optimization would not be valid.
868
+
869
+ # initialized below in _record
870
+
871
+ self.checkpointed_caching_state: Optional[AllocatorState] = None
872
+
873
+ # Output Storage Alias information, can be:
874
+ # - A new, unaliased storage, or the output is None
875
+ # - An alias of an output of a prior graph
876
+ # - An alias of an output already created in the reconstructed outputs
877
+ # This is None if the output in question is an int
878
+ self.output_storage_alias: OutputList[Optional[OutputAliasInfo]] = []
879
+
880
+ # is the output Storage unaliased in subsequent outputs, of all subsequent paths
881
+ # if it is, we cached the output tensor and adjust storage liveness tracking to also
882
+ # check if the output tensor does not have an additional python reference.
883
+ # If a descendent node discovers it has an alias of a prior output, then the output
884
+ # will no longer be cached in the ancestor.
885
+ # The large majority of tensors are unaliased, and preserving aliased output tensors would add
886
+ # significant additional complexity with marginal gains
887
+ # The cached tensor outputs are added on the first execution, and cleared whenever we need
888
+ # to do subsequent recording
889
+ self.unaliased_in_all_paths: OutputList[bool] = []
890
+ self.cached_tensor_outputs: OutputList[Optional[Tensor]] = []
891
+
892
+ # if an output aliases a static, persistent input then the corresponding Tensor will
893
+ # be set here. These are different than cached tensors, because they are tensors that
894
+ # are aliases of parameters that are always live.
895
+ self.static_output_tensors: OutputList[Optional[Tensor]] = []
896
+
897
+ # Cleared after recording
898
+ self.recording_outputs: Optional[
899
+ OutputList[Union[torch.Tensor, int]]
900
+ ] = self._record(wrapped_function.model, recording_inputs)
901
+ self.outputs_metadata: OutputList[Union[Dict[str, Any], int, None]] = []
902
+
903
+ # As with inputs, we do not want to keep the outputs permanently alive because that would prevent
904
+ # their memory being reclaimed in subsequent cuda graph recordings. We record the tensor metadata
905
+ # needed to reconstruct instead.
906
+ assert self.recording_outputs is not None
907
+ for out in self.recording_outputs:
908
+ if isinstance(out, torch.Tensor):
909
+ self.outputs_metadata.append(
910
+ self._tensor_metadata(out, ignore_storage_offset=False)
911
+ )
912
+ else:
913
+ assert isinstance(out, (int, type(None))), type(out)
914
+ self.outputs_metadata.append(out)
915
+
916
+ self.graph.replay()
917
+
918
+ def _copy_input(self, idx, dst, src):
919
+ expanded_dims = self.expanded_dims[idx]
920
+ dst = index_expanded_dims(dst, expanded_dims)
921
+ src = index_expanded_dims(src, expanded_dims)
922
+ # TODO - one jit kernel across multiple inputs
923
+ dst.copy_(src)
924
+
925
+ def run_first_inputs(self, new_inputs):
926
+ if config.triton.fast_path_cudagraph_asserts:
927
+ self.debug_check_invariants_before_invocation()
928
+
929
+ # graph is already invoked in the __init__
930
+ # inputs are copied over in _allocate_recording_inputs and subsequently cleared
931
+ assert len(new_inputs) == 0
932
+ outputs = self.recording_outputs
933
+ self.recording_outputs = None
934
+ return outputs
935
+
936
+ def run(self, new_inputs):
937
+ if config.triton.fast_path_cudagraph_asserts:
938
+ self.debug_check_invariants_before_invocation()
939
+
940
+ assert len(self.static_input_data_ptrs) == len(new_inputs)
941
+ # NB: this ranges over non-static inputs too
942
+ for idx, data_ptr in enumerate(self.static_input_data_ptrs):
943
+ if idx in self.cudagraph_managed_idxs:
944
+ continue
945
+ if not isinstance(new_inputs[idx], torch.Tensor):
946
+ pass
947
+ elif data_ptr is not None:
948
+ # static input, e.g., parameter
949
+ assert data_ptr == new_inputs[idx].data_ptr()
950
+ else:
951
+ # non-static input, need to copy it into CUDA graph
952
+ dst = self.reconstructed_inputs[idx]
953
+ src = new_inputs[idx]
954
+ self._copy_input(idx, dst, src)
955
+
956
+ new_inputs.clear()
957
+ self.run_graph()
958
+
959
+ outputs = self.reconstruct_outputs()
960
+ self.debug_check_invariants_after_invocation()
961
+
962
+ return outputs
963
+
964
+ def reconstruct_outputs(self):
965
+ "Reconstruct output tensors according to their saved metadata and alias information"
966
+
967
+ # Cached tensors will not yet be set on the first execution
968
+ # They are also cleared in checkpointing, so if we checkpoint this node
969
+ # and then execute it again we will need to repopulate cached tensors
970
+ if not self.cached_tensor_outputs:
971
+ self._initialize_cached_tensors()
972
+
973
+ outputs: List[Optional[Union[int, torch.Tensor]]] = []
974
+
975
+ for i, (storage_info, metadata) in enumerate(
976
+ zip(self.output_storage_alias, self.outputs_metadata)
977
+ ):
978
+ if not isinstance(metadata, dict): # tensor metadata
979
+ assert isinstance(metadata, (int, type(None)))
980
+ outputs.append(metadata)
981
+ continue
982
+
983
+ cached_t = self.cached_tensor_outputs[i]
984
+ if cached_t is not None:
985
+ # No need to update weakrefs, already correctly initialized
986
+ outputs.append(cached_t)
987
+ continue
988
+
989
+ static_t = self.static_output_tensors[i]
990
+ if static_t is not None:
991
+ assert self.outputs_weakrefs[i] is None
992
+ outputs.append(static_t)
993
+ continue
994
+
995
+ storage = self.prepare_alias_info_for_tensor_construction(
996
+ storage_info, metadata
997
+ )
998
+
999
+ if isinstance(storage, UntypedStorage) or storage is None:
1000
+ out = self._reconstruct_from_tensor_metadata(metadata, storage)
1001
+ else:
1002
+ assert isinstance(storage, int)
1003
+ out = self._reconstruct_from_tensor_metadata(
1004
+ metadata, cast(torch.Tensor, outputs[storage]).untyped_storage()
1005
+ )
1006
+
1007
+ outputs.append(out)
1008
+ w = self.outputs_weakrefs[i]
1009
+ assert w is not None
1010
+ w.swap_weakref(out.untyped_storage()._weak_ref())
1011
+
1012
+ return outputs
1013
+
1014
+ def prepare_alias_info_for_tensor_construction(
1015
+ self,
1016
+ out_alias_info: Optional[OutputAliasInfo],
1017
+ metadata: Union[Dict[str, Any], int, None],
1018
+ ) -> Union[UntypedStorage, None, int]:
1019
+ if (
1020
+ isinstance(metadata, (int, type(None)))
1021
+ or out_alias_info is UnaliasedStorage
1022
+ ):
1023
+ return None
1024
+
1025
+ if isinstance(out_alias_info, AliasesPriorGraphOutput):
1026
+ depth, existing_output_index = out_alias_info.index
1027
+ ref = self.path_weakrefs[depth][existing_output_index]
1028
+ assert ref is not None
1029
+ return torch.UntypedStorage._new_with_weak_ptr(ref())
1030
+
1031
+ assert isinstance(out_alias_info, AliasesNewOutput)
1032
+ return out_alias_info.index
1033
+
1034
+ def prepare_storages_for_construction(
1035
+ self,
1036
+ ) -> List[Union[UntypedStorage, None, int]]:
1037
+ output_storages = []
1038
+ for output_storage_alias, metadata in zip(
1039
+ self.output_storage_alias, self.outputs_metadata
1040
+ ):
1041
+ output_storages.append(
1042
+ self.prepare_alias_info_for_tensor_construction(
1043
+ output_storage_alias, metadata
1044
+ )
1045
+ )
1046
+
1047
+ return output_storages
1048
+
1049
+ def run_graph(self):
1050
+ assert self.graph is not None
1051
+ self.graph.replay()
1052
+
1053
+ def all_outputs_are_dead(self):
1054
+ "All outputs of the path from this node to its root are dead"
1055
+ for depth, output_index in self.live_indices_after_graph:
1056
+ if is_live(self.path_weakrefs[depth][output_index]):
1057
+ return False
1058
+ return True
1059
+
1060
+ def _record(self, model, inputs):
1061
+ "Record the model"
1062
+
1063
+ def static_input_iter():
1064
+ for i in self.wrapped_function.static_input_idxs:
1065
+ if isinstance(
1066
+ inputs[i], torch.Tensor
1067
+ ) and not self._is_cuda_graph_recorded_tensor(inputs[i]):
1068
+ yield inputs[i]
1069
+
1070
+ # see: output_is_alias_of_persistent_static_inputs above
1071
+ static_input_persistent_storage_ptrs: Dict[int, StorageWeakRefWrapper] = {
1072
+ inp.untyped_storage().data_ptr(): StorageWeakRefWrapper(inp)
1073
+ for inp in itertools.chain(
1074
+ static_input_iter(), self.wrapped_function.constants
1075
+ )
1076
+ }
1077
+
1078
+ if config.triton.slow_path_cudagraph_asserts:
1079
+ # need to use parent live weakrefs because live_indices isnt set yet
1080
+ memory = (
1081
+ [] if self.parent is None else list(self.parent.path_live_weakrefs())
1082
+ )
1083
+ memory += [
1084
+ StorageWeakRefWrapper(elem)
1085
+ for i, elem in enumerate(inputs)
1086
+ if isinstance(elem, torch.Tensor)
1087
+ and i not in self.wrapped_function.static_input_idxs
1088
+ and elem.untyped_storage().data_ptr() != 0
1089
+ ]
1090
+ check_memory_pool(self.device, self.cuda_graphs_pool, memory)
1091
+
1092
+ with preserve_rng_state(), torch.cuda.device(
1093
+ self.device
1094
+ ), clear_cublas_manager(), torch.cuda.graph(
1095
+ self.graph,
1096
+ stream=self.stream,
1097
+ pool=self.cuda_graphs_pool,
1098
+ capture_error_mode="thread_local",
1099
+ ), get_history_recording():
1100
+ static_outputs = model(inputs)
1101
+
1102
+ # running model should reclaim memory
1103
+ assert len(inputs) == 0
1104
+
1105
+ if not isinstance(static_outputs, (list, tuple)):
1106
+ static_outputs = (static_outputs,)
1107
+
1108
+ self._add_first_outputs(static_outputs, static_input_persistent_storage_ptrs)
1109
+
1110
+ return static_outputs
1111
+
1112
+ def _add_first_outputs(
1113
+ self,
1114
+ outputs,
1115
+ static_input_persistent_storage_ptrs: Dict[int, StorageWeakRefWrapper],
1116
+ ):
1117
+ "Add the outputs from the first invocation of the node and set up metadata"
1118
+
1119
+ # getting liveness before we have added the outputs to path, so the length
1120
+ # of the two lists is equal
1121
+ prev_liveness = self.recorded_liveness_before_graph
1122
+ curr_liveness = self._get_liveness(self.path_weakrefs)
1123
+
1124
+ delta = self._get_different_indices(prev_liveness, curr_liveness)
1125
+ self.expected_dead_indices_after_graph = delta
1126
+
1127
+ assert len(self.outputs_weakrefs) == 0
1128
+ # index from data pointer to index in outputs
1129
+ output_new_storages_index: Dict[StorageDataPtr, int] = {}
1130
+
1131
+ self.unaliased_in_all_paths = [False for _ in range(len(outputs))]
1132
+ self.static_output_tensors = [None for _ in range(len(outputs))]
1133
+
1134
+ for i, o in enumerate(outputs):
1135
+ if o is None or not isinstance(o, torch.Tensor):
1136
+ self.output_storage_alias.append(UnaliasedStorage)
1137
+ continue
1138
+
1139
+ torch._check(
1140
+ o.is_cuda or o.untyped_storage().data_ptr() == 0,
1141
+ lambda: (
1142
+ "Expected all cuda outputs in cuda graph recording. Non cuda output "
1143
+ f"from {self.stack_traces[i] if self.stack_traces else '(unknown)'}"
1144
+ ),
1145
+ ),
1146
+
1147
+ ref = static_input_persistent_storage_ptrs.get(
1148
+ o.untyped_storage().data_ptr(), None
1149
+ )
1150
+ # also treat empty storages as static outputs because we do not need to manage their lifetime
1151
+ # and they should not participate in checkpointing
1152
+ is_empty_storage = o.untyped_storage().data_ptr() == 0
1153
+ if (ref and ref() is not None) or is_empty_storage:
1154
+ self.output_storage_alias.append(None)
1155
+ self.static_output_tensors[i] = o
1156
+ continue
1157
+
1158
+ path_ref = self._is_alias_of_live_recorded_tensor(o)
1159
+ if path_ref is not None:
1160
+ self._mark_prior_graph_output_as_aliased(path_ref)
1161
+ self.output_storage_alias.append(AliasesPriorGraphOutput(path_ref))
1162
+ continue
1163
+
1164
+ if o.untyped_storage().data_ptr() in output_new_storages_index:
1165
+ index = output_new_storages_index[o.untyped_storage().data_ptr()]
1166
+ self.unaliased_in_all_paths[index] = False
1167
+ self.output_storage_alias.append(AliasesNewOutput(index))
1168
+ continue
1169
+
1170
+ output_new_storages_index[o.untyped_storage().data_ptr()] = i
1171
+ self.output_storage_alias.append(UnaliasedStorage)
1172
+ self.unaliased_in_all_paths[i] = True
1173
+
1174
+ if self.stack_traces is None:
1175
+ self.stack_traces = [None for _ in range(len(outputs))]
1176
+ else:
1177
+ assert len(self.stack_traces) == len(
1178
+ outputs
1179
+ ), "Wrong number of stack traces passed in"
1180
+
1181
+ assert not self.outputs_weakrefs
1182
+ for out, static_output_tensor in zip(outputs, self.static_output_tensors):
1183
+ if not isinstance(out, torch.Tensor) or static_output_tensor is not None:
1184
+ self.outputs_weakrefs.append(None)
1185
+ self.tensor_weakrefs.append(None)
1186
+ else:
1187
+ self.outputs_weakrefs.append(StorageWeakRefWrapper(out))
1188
+ self.tensor_weakrefs.append(TensorWeakRef(out))
1189
+
1190
+ self.recorded_liveness_after_graph = self._get_liveness(self.path_weakrefs)
1191
+ self.checkpointed_caching_state = torch._C._cuda_getCheckpointState(
1192
+ self.device, self.cuda_graphs_pool
1193
+ )
1194
+
1195
+ # now, get liveness with outputs added
1196
+ for depth in range(len(self.path_weakrefs)):
1197
+ for output_index in range(len(self.path_weakrefs[depth])):
1198
+ if is_live(self.path_weakrefs[depth][output_index]):
1199
+ self.live_indices_after_graph.append((depth, output_index))
1200
+
1201
+ self.debug_check_invariants_after_invocation()
1202
+ if config.triton.slow_path_cudagraph_asserts:
1203
+ check_memory_pool(
1204
+ self.device, self.cuda_graphs_pool, list(self.path_live_weakrefs())
1205
+ )
1206
+
1207
+ def _mark_prior_graph_output_as_aliased(self, index: PathOutputIndex):
1208
+ "Remove a graph output from the unaliased, cached tensors in an ancestor node"
1209
+ depth, output_index = index
1210
+ node = list(self._path_from_root)[depth]
1211
+ node.unaliased_in_all_paths[output_index] = False
1212
+ x = self.path_weakrefs[depth][output_index]
1213
+ assert x is not None
1214
+ x.remove_extra_reference()
1215
+
1216
+ def _initialize_cached_tensors(self):
1217
+ # we should not be clearing output_weakrefs, and they should be set in the first
1218
+ # record run
1219
+ assert len(self.outputs_weakrefs) == len(self.outputs_metadata)
1220
+
1221
+ for i, (storage_info, metadata, make_cached) in enumerate(
1222
+ zip(
1223
+ self.output_storage_alias,
1224
+ self.outputs_metadata,
1225
+ self.unaliased_in_all_paths,
1226
+ )
1227
+ ):
1228
+ if not make_cached:
1229
+ self.cached_tensor_outputs.append(None)
1230
+ continue
1231
+
1232
+ assert storage_info is UnaliasedStorage
1233
+ assert isinstance(metadata, dict)
1234
+ s = self.create_storage(metadata)
1235
+ out = self._reconstruct_from_tensor_metadata(metadata, storage=s)
1236
+
1237
+ # XXX: let autograd know that there will be an additional reference to the tensor
1238
+ # that can be ignored when deciding whether to do gradient buffer inplacing.
1239
+ # Otherwise, inplacing could differ between tracing and subsequent execution.
1240
+ # For some models we tested this led to inputs no longer being in cudagraph pools,
1241
+ # leading to spurious re-recordings.
1242
+ # It also tells AMP cache that even though the tensor impls cannot be cached
1243
+ # in dtype conversions.
1244
+
1245
+ torch._C._add_cached_tensor(out)
1246
+
1247
+ self_ref = weakref.ref(self)
1248
+
1249
+ # one reference in our array, and calling sys.getrefcount bumps the refcount by one
1250
+ def check_refcount(i):
1251
+ self_loc = self_ref()
1252
+ if self_loc is None:
1253
+ return False
1254
+ return self_loc.get_output_refcount(i) == 2
1255
+
1256
+ check = functools.partial(check_refcount, i=i)
1257
+
1258
+ self.outputs_weakrefs[i] = StorageWeakRefWrapper(out, extra_ref_check=check)
1259
+ self.cached_tensor_outputs.append(out)
1260
+
1261
+ def get_output_refcount(self, index):
1262
+ return sys.getrefcount(self.cached_tensor_outputs[index])
1263
+
1264
+ @property
1265
+ def parent(self):
1266
+ "unwraps the weakref to _parent"
1267
+ return self._parent() if self._parent is not None else None
1268
+
1269
+ @property
1270
+ def _path_to_root(self):
1271
+ "Returns all nodes in the path starting at self and ending at root"
1272
+ node = self
1273
+ while node:
1274
+ yield node
1275
+ node = node.parent
1276
+
1277
+ @property
1278
+ def _path_from_root(self):
1279
+ "Returns all nodes in the path starting at the root and ending at self"
1280
+ nodes = reversed(list(self._path_to_root))
1281
+ yield from nodes
1282
+
1283
+ def _is_cuda_graph_recorded_tensor(self, t: torch.Tensor):
1284
+ "Is this tensor an output of a node in this path"
1285
+ for output_refs in self.path_weakrefs:
1286
+ for storage_weak_ref in output_refs:
1287
+ if storage_weak_ref is None:
1288
+ continue
1289
+ # don't need to check liveness of storage since the cuda graph managed
1290
+ # memory is never released.
1291
+ data_ptr = storage_weak_ref.data_ptr()
1292
+ if t.untyped_storage().data_ptr() == data_ptr:
1293
+ return True
1294
+
1295
+ return False
1296
+
1297
+ def _is_alias_of_live_recorded_tensor(
1298
+ self, t: torch.Tensor
1299
+ ) -> Optional[PathOutputIndex]:
1300
+ for depth, output_refs in enumerate(self.path_weakrefs):
1301
+ for output_index, storage_ref in enumerate(output_refs):
1302
+ if (storage_and_ptr := maybe_deref(storage_ref)) is not None:
1303
+ storage, ptr = storage_and_ptr
1304
+ if ptr == t.untyped_storage().data_ptr():
1305
+ return (depth, output_index)
1306
+
1307
+ return None
1308
+
1309
+ @staticmethod
1310
+ def _check_liveness(
1311
+ indices: List[PathOutputIndex],
1312
+ output_refs: List[List[Optional[StorageWeakRefWrapper]]],
1313
+ ):
1314
+ "Check that all of the indices specified are dead references"
1315
+ for depth, output_index in indices:
1316
+ w = output_refs[depth][output_index]
1317
+ assert w is not None
1318
+ if w() is not None:
1319
+ return False
1320
+ return True
1321
+
1322
+ def add_child(self, function_id: FunctionID, node: CUDAGraphNode):
1323
+ "Adds node as a a child of self"
1324
+ self.children[function_id].append(node)
1325
+
1326
+ @staticmethod
1327
+ def _get_different_indices(
1328
+ prev: List[List[bool]], curr: List[List[bool]]
1329
+ ) -> List[PathOutputIndex]:
1330
+ "Find indices where the two lists differ."
1331
+ dead_indices = []
1332
+ assert len(prev) <= len(curr)
1333
+ for i, (outputs1, outputs2) in enumerate(zip(prev, curr)):
1334
+ assert len(outputs1) == len(outputs2)
1335
+ for j, (output1, output2) in enumerate(zip(outputs1, outputs2)):
1336
+ if output1 != output2:
1337
+ dead_indices.append((i, j))
1338
+
1339
+ return dead_indices
1340
+
1341
+ @staticmethod
1342
+ def _get_liveness(
1343
+ weakrefs: List[List[Optional[StorageWeakRefWrapper]]],
1344
+ ) -> List[List[bool]]:
1345
+ "Maps weakrefs to true if the reference is alive and false otherwise"
1346
+ if len(weakrefs) == 0:
1347
+ return []
1348
+
1349
+ return [pytree.tree_map(is_live, outputs) for outputs in weakrefs]
1350
+
1351
+ def debug_assert_invariants(
1352
+ self, expected_liveness: List[List[bool]], newly_dead: List[PathOutputIndex]
1353
+ ):
1354
+ if not config.triton.fast_path_cudagraph_asserts:
1355
+ return
1356
+
1357
+ for i, node in enumerate(self._path_from_root):
1358
+ assert self.path_weakrefs[i] is node.outputs_weakrefs
1359
+
1360
+ nodes = list(self._path_from_root)
1361
+
1362
+ live_blocks = get_block_addrs(self.cuda_graphs_pool)
1363
+
1364
+ live_storage_data_ptrs = set()
1365
+ live_storage_weak_ptrs = set()
1366
+
1367
+ for depth, outputs_liveness in enumerate(expected_liveness):
1368
+ for output_idx, output_liveness in enumerate(outputs_liveness):
1369
+ # tensor can die early, but it can't be alive when it should be dead
1370
+ w = self.path_weakrefs[depth][output_idx]
1371
+ if (stor_weak_ptr_and_data_ptr := maybe_deref(w)) is not None:
1372
+ assert output_liveness
1373
+ stor_weak_ptr, stor_data_ptr = stor_weak_ptr_and_data_ptr
1374
+ assert (stor_data_ptr in live_storage_data_ptrs) == (
1375
+ stor_weak_ptr in live_storage_weak_ptrs
1376
+ )
1377
+ live_storage_data_ptrs.add(stor_data_ptr)
1378
+ live_storage_weak_ptrs.add(stor_weak_ptr)
1379
+
1380
+ is_persistent_alias = (
1381
+ nodes[depth].static_output_tensors[output_idx] is not None
1382
+ )
1383
+
1384
+ if is_persistent_alias:
1385
+ assert stor_data_ptr not in live_blocks
1386
+
1387
+ for depth, output_index in newly_dead:
1388
+ assert not is_live(self.path_weakrefs[depth][output_index])
1389
+
1390
+ def debug_check_invariants_before_invocation(self):
1391
+ self.debug_assert_invariants(
1392
+ self.recorded_liveness_before_graph, self.expected_dead_indices_before_graph
1393
+ )
1394
+
1395
+ def debug_check_invariants_after_invocation(self):
1396
+ self.debug_assert_invariants(
1397
+ self.recorded_liveness_before_graph, self.expected_dead_indices_after_graph
1398
+ )
1399
+
1400
+ def data_ptrs_dead_since_invocation(self) -> List[int]:
1401
+ """
1402
+ Since this node was invoked, return data ptrs of all tensor outputs that have died
1403
+ in the current executing tree path.
1404
+ """
1405
+ curr_liveness = self._get_liveness(self.path_weakrefs)
1406
+ _get_different_indices = self._get_different_indices(
1407
+ self.recorded_liveness_after_graph, curr_liveness
1408
+ )
1409
+
1410
+ path = list(self._path_from_root)
1411
+ ptrs_to_deallocate = []
1412
+ for depth, output_index in _get_different_indices:
1413
+ ptrs_to_deallocate.append(
1414
+ path[depth].outputs_metadata[output_index]["data_ptr"]
1415
+ )
1416
+
1417
+ return ptrs_to_deallocate
1418
+
1419
+ def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]:
1420
+ for i, j in self.live_indices_after_graph:
1421
+ out = self.path_weakrefs[i][j]
1422
+ if out is not None and is_live(out):
1423
+ yield out
1424
+
1425
+ def remove_node_cached_tensors(self):
1426
+ for t in self.cached_tensor_outputs:
1427
+ if t is not None:
1428
+ torch._C._remove_cached_tensor(t)
1429
+ self.cached_tensor_outputs.clear()
1430
+
1431
+ for i, unaliased in enumerate(self.unaliased_in_all_paths):
1432
+ if unaliased:
1433
+ n = self.outputs_weakrefs[i]
1434
+ assert n is not None
1435
+ n.remove_extra_reference()
1436
+
1437
+ def remove_path_cached_tensors(self):
1438
+ for node in self._path_from_root:
1439
+ node.remove_node_cached_tensors()
1440
+
1441
+ def clear_path_state(self):
1442
+ "Clear the path state in this current executing node"
1443
+ # this doesnt actually do anything right now, leaving it as placeholder
1444
+ pass
1445
+
1446
+ @staticmethod
1447
+ def _tensor_metadata(x, ignore_storage_offset=True):
1448
+ assert isinstance(x, torch.Tensor)
1449
+ # We ignore the storage offset for inputs, but not for outputs
1450
+ # TODO: - should we make the storage resizable ?
1451
+ return {
1452
+ "nbytes": x.untyped_storage().nbytes(),
1453
+ "data_ptr": x.untyped_storage().data_ptr(),
1454
+ "size": x.shape,
1455
+ "stride": x.stride(),
1456
+ "dtype": x.dtype,
1457
+ "device": x.device,
1458
+ "storage_offset": x.storage_offset() if not ignore_storage_offset else 0,
1459
+ }
1460
+
1461
+ def _reconstruct_from_tensor_metadata(
1462
+ self, metadata: Dict[str, Any], storage=None
1463
+ ) -> Tensor:
1464
+ s = self.create_storage(metadata) if storage is None else storage
1465
+ return torch._C._construct_CUDA_Tensor_From_Storage_And_Metadata(metadata, s)
1466
+
1467
+ def create_storage(self, metadata):
1468
+ return torch._C._construct_storage_from_data_pointer(
1469
+ metadata["data_ptr"], metadata["device"], metadata["nbytes"]
1470
+ )
1471
+
1472
+ def _allocate_and_copy_recording_inputs(
1473
+ self, inputs
1474
+ ) -> List[Union[torch.Tensor, int]]:
1475
+ """
1476
+ Allocate inputs for non static, non cudagraph managraphed managed tensors in the memory pool
1477
+ and copy over the tensor values.
1478
+ """
1479
+
1480
+ torch.cuda.synchronize()
1481
+ self.stream.wait_stream(torch.cuda.current_stream())
1482
+ recording_inputs: List[Union[Tensor, int]] = []
1483
+
1484
+ with warnings.catch_warnings(record=True), torch.cuda.device(
1485
+ self.device
1486
+ ), _use_cuda_memory_pool_manager(
1487
+ self.device,
1488
+ mem_pool=self.cuda_graphs_pool,
1489
+ stream=self.stream,
1490
+ ):
1491
+ for i, inp in enumerate(inputs):
1492
+ if not isinstance(inp, torch.Tensor):
1493
+ assert isinstance(inp, int)
1494
+ recording_inputs.append(inp)
1495
+ elif i not in self.static_input_idxs:
1496
+ # static_input does an allocation!
1497
+ recording_inputs.append(static_input(inp))
1498
+ # copy over and clear non recording input
1499
+ self._copy_input(i, recording_inputs[-1], inp)
1500
+ inputs[i] = None
1501
+ del inp
1502
+ else:
1503
+ recording_inputs.append(inp)
1504
+
1505
+ return recording_inputs
1506
+
1507
+ def check_invariants(self, inputs: List[Tensor]) -> bool:
1508
+ """
1509
+ Checks if this node can be run. The same pattern of tensor liveness and tensors
1510
+ managed in the cudagraph private pool must remain stable.
1511
+ """
1512
+
1513
+ # previously managed data pointers remain stable
1514
+ for idx in self.cudagraph_managed_idxs:
1515
+ if inputs[idx].data_ptr() != self.static_input_data_ptrs[idx]:
1516
+ return False
1517
+
1518
+ if not self._check_liveness(
1519
+ self.expected_dead_indices_before_graph, self.path_weakrefs
1520
+ ):
1521
+ return False
1522
+
1523
+ # the cudagraph managed tensors which died upon recording must also die upon
1524
+ # this invocation. it is too late to check after we've replayed the graph,
1525
+ # because we would have already written over their memory.
1526
+ for idx in self.cudagraph_managed_idxs:
1527
+ inputs[idx] = None # type: ignore[call-overload]
1528
+
1529
+ torch._check(
1530
+ self._check_liveness(
1531
+ self.expected_dead_indices_after_graph, self.path_weakrefs
1532
+ ),
1533
+ lambda: "TODO: graph recording observed an input tensor deallocate during graph "
1534
+ " recording that did not occur during replay. Please file an issue.",
1535
+ )
1536
+ return True
1537
+
1538
+ def num_descendants(self) -> int:
1539
+ "Total number of descendents of this node"
1540
+ num_desc = 0
1541
+ for children in self.children.values():
1542
+ for child in children:
1543
+ num_desc += 1
1544
+ num_desc += child.num_descendants()
1545
+ return num_desc
1546
+
1547
+
1548
+ def get_cudagraph_segments(pool_id):
1549
+ segments = torch.cuda.memory_snapshot()
1550
+ return [segment for segment in segments if segment["segment_pool_id"] == pool_id]
1551
+
1552
+
1553
+ def get_block_addrs(pool_id, live_only=True):
1554
+ blocks = []
1555
+
1556
+ for segment in get_cudagraph_segments(pool_id):
1557
+ addr = segment["address"]
1558
+ for block in segment["blocks"]:
1559
+ if block["state"] == "active_allocated" or not live_only:
1560
+ blocks.append(addr)
1561
+
1562
+ addr += block["size"]
1563
+
1564
+ return blocks
1565
+
1566
+
1567
+ def format_tb(frames):
1568
+ formatted_traceback = []
1569
+
1570
+ for entry in frames:
1571
+ formatted_traceback.append(
1572
+ traceback.FrameSummary(entry["filename"], entry["line"], entry["name"])
1573
+ )
1574
+
1575
+ return "".join(traceback.format_list(formatted_traceback))
1576
+
1577
+
1578
+ def check_memory_pool(device, pool_id, live_storages_ptrs: List[StorageWeakRefWrapper]):
1579
+ assert all(
1580
+ isinstance(elem, StorageWeakRefWrapper) for elem in live_storages_ptrs
1581
+ ) # noqa: C419
1582
+ unique_storages = {stor.data_ptr() for stor in live_storages_ptrs if stor()}
1583
+
1584
+ # check if there is a divergence first, then do the expensive snapshot call after
1585
+ # we know it will error
1586
+ if torch._C._cuda_checkPoolLiveAllocations(device, pool_id, unique_storages):
1587
+ return
1588
+
1589
+ # at this point we are past the fast-path. we have seen rare cases where a dead tensor is dead,
1590
+ # but hasn't been gc'd yet, and gives false positive for allocated_not_in_live_storages
1591
+ gc.collect()
1592
+
1593
+ segments = get_cudagraph_segments(pool_id)
1594
+
1595
+ allocated_not_in_live_storages = {}
1596
+
1597
+ for segment in segments:
1598
+ addr = segment["address"]
1599
+ for block in segment["blocks"]:
1600
+ if block["state"] == "active_allocated":
1601
+ if addr not in unique_storages:
1602
+ allocated_not_in_live_storages[addr] = block
1603
+ else:
1604
+ unique_storages.remove(addr)
1605
+
1606
+ addr += block["size"]
1607
+
1608
+ torch._check(
1609
+ len(unique_storages) == 0,
1610
+ lambda: f"These storage data ptrs are not allocated in pool {pool_id} but should be {unique_storages}",
1611
+ )
1612
+
1613
+ if allocated_not_in_live_storages != 0:
1614
+ formatted = []
1615
+ for dp, block in allocated_not_in_live_storages.items():
1616
+ trace = format_tb(block.get("frames", []))
1617
+ formatted.append(f"Data Pointer: {dp}, history: \n{trace}")
1618
+ formatted_s = "\n".join(formatted)
1619
+ msg = (
1620
+ f"These live storage data ptrs are in the cudagraph pool but not "
1621
+ f"accounted for as an output of cudagraph trees: \n\n{formatted_s}"
1622
+ )
1623
+ raise RuntimeError(msg)
1624
+
1625
+
1626
+ class ExecutionState(Enum):
1627
+ """
1628
+ Represents the state of the CUDAGraph Tree. Will be None if there is no live current memory allocated
1629
+ in the cuda graph pool. Otherwise will reflect the state of the most recently executed node.
1630
+ """
1631
+
1632
+ NONE = auto()
1633
+ WARMUP = auto()
1634
+ RECORDING = auto()
1635
+ EXECUTION = auto()
1636
+
1637
+
1638
+ class CompilationMode(Enum):
1639
+ FORWARD = auto()
1640
+ BACKWARD = auto()
1641
+ INFERENCE = auto()
1642
+
1643
+
1644
+ class CUDAGraphTreeManager:
1645
+ """
1646
+ Groups individual recordings or executions of cuda graphs into a tree of recordings,
1647
+ and checks required invariants, and manages warmups of graphs.
1648
+
1649
+ When graphs are recorded in the same tree, it enforces subsequent execution
1650
+ to follow the same order and have the same output tensor livespans. To remove
1651
+ unnecessary coupling of cuda graphs (and additional imposed invariants),
1652
+ the tree manager will end a currently recording tree whenever it is valid - when
1653
+ the memory pool no longer has any live allocations.
1654
+
1655
+ We ignore outputs from a previous generation that correspond to prior model outputs.
1656
+ Currently this is hardcoded `GenerationTracker.generation` tracked in torch dynamo.
1657
+ # TODO: make generation increment configurable, warn on overwrite.
1658
+
1659
+ We run graph warmups in the cudagraph memory pool and return the result on the first invocation
1660
+ of a function. For many models it is important to reclaim activations as you run the backward.
1661
+ If we were to warm up the model and keep an extra copy of the inputs around to subsequently
1662
+ use for recording, we would incur a memory penalty. Additionally, if we are part way through training
1663
+ your model and need to recompile, memory will be allocated to the cuda graph pool, so we run this
1664
+ warmup run in the cuda graph memory pool. As for recording, warm up needs the state of live tensors
1665
+ to be accurately reflected so we checkpoint the allocator state if we need to warm up following graph
1666
+ replay.
1667
+ """
1668
+
1669
+ def __init__(self, device_index: int):
1670
+ # roots are functions which have no dependencies on an other node. I.e.,
1671
+ # when they are first invoked, none of their inputs are outputs are outputs
1672
+ # of another node, nor are there any live outputs of another node whose
1673
+ # liveness would create a dependency.
1674
+ self.roots: Dict[FunctionID, List[CUDAGraphNode]] = defaultdict(list)
1675
+
1676
+ # mapping from function id to wrapped function
1677
+ self.ids_to_funcs: Dict[FunctionID, WrappedFunction] = {}
1678
+
1679
+ self.ids_to_stack_traces: Dict[FunctionID, StackTraces] = {}
1680
+
1681
+ self.warmed_up_functions: Set[FunctionID] = set()
1682
+ # if we fail to increment generation, and are stuck warming up,
1683
+ # only warn on each function once
1684
+ self.warned_functions: Set[FunctionID] = set()
1685
+ torch._C._set_cached_tensors_enabled(True)
1686
+
1687
+ # NB: cuda caching allocator will remember the stream a segment is allocated to
1688
+ # and only allocate that segment to the same stream. we need to use a single stream
1689
+ # for all allocations to the memory pool, otherwise the allocations to separate streams
1690
+ # will not be reused; separate recordings would have use the same memory pool, but not
1691
+ # the same memory.
1692
+
1693
+ with torch.cuda.device(device_index):
1694
+ torch.cuda.synchronize()
1695
+ self.stream = torch.cuda.Stream()
1696
+ self.stream.wait_stream(torch.cuda.current_stream())
1697
+
1698
+ # Keeps Memory Pool Alive
1699
+ self.graph: Optional[torch.cuda.CUDAGraph] = torch.cuda.CUDAGraph()
1700
+ self.cuda_graphs_thread_pool = torch.cuda.graph_pool_handle()
1701
+
1702
+ with warnings.catch_warnings(record=True), torch.cuda.graph(
1703
+ self.graph,
1704
+ pool=self.cuda_graphs_thread_pool,
1705
+ stream=self.stream,
1706
+ capture_error_mode="thread_local",
1707
+ ):
1708
+ pass
1709
+
1710
+ self.graph_counter = itertools.count(0)
1711
+ self.func_counter = itertools.count(0)
1712
+
1713
+ # whether we the current node is in a state of warmup, recording, execution. If
1714
+ # there is no current node the state will be ExecutionState.None.
1715
+ self.path_state = ExecutionState.NONE
1716
+ self.device_index = device_index
1717
+
1718
+ # the most recently invoked cudagraph wrapping of a function. Will be None
1719
+ # when there is no output from a previous recording or execution whose memory
1720
+ # we need to respect in the cuda caching allocation. If you incremented generation,
1721
+ # this will also be none, as ignore those allocations.
1722
+ self.current_node: Optional[CUDAGraphNode] = None
1723
+
1724
+ # current generation of cudagraph invocations. when torch.compile is run
1725
+ # we increment the current generation. are willing to ignore live outputs
1726
+ # of a previous generation in checking liveness.
1727
+ self.current_gen: int = -1
1728
+
1729
+ # number of instances we are in execution and failed to match to an
1730
+ # existing child
1731
+ self.debug_fail_counter = 0
1732
+ # number of instances we had to checkpoint the function
1733
+ self.debug_checkpointing_counter = 0
1734
+
1735
+ self.id_to_mode: Dict[FunctionID, CompilationMode] = {}
1736
+
1737
+ # Note: [Backward Generation Handling]
1738
+ # We generally perform a sequence of forward executions followed by backward executions.
1739
+ # If multiple torch.compile wrapped forwards are executed with their backwards pending,
1740
+ # we should not disregard the outputs from a prior torch.compile since the entire training
1741
+ # loop hasn't completed. Occasionally, a backward pass corresponding to a forward pass may
1742
+ # not be executed, so we cannot wait for all pending forward pass backward completions, so
1743
+ # we cannot wait for all backwards to have been invoked. Instead we wait for a single backward
1744
+ # invocation. Triggering a backward pass typically doesn't lead to another torch.compile
1745
+ # invocation, making it less likely for the generation to increase between multiple
1746
+ # backward calls. The following use case is covered by this approach:
1747
+ # mod1 = torch.compile(...)
1748
+ # mod2 = torch.compile(...)
1749
+ # mod2(mod1(x)).sum().backward()
1750
+
1751
+ self.running_forwards_with_pending_backwards = False
1752
+
1753
+ def run(self, new_inputs: List[Tensor], function_id: FunctionID):
1754
+ assert self.graph is not None, "Running CUDAGraph after shutdown"
1755
+ out = self._run(new_inputs, function_id)
1756
+
1757
+ # The forwards are only pending following invocation, not before
1758
+ mode = self.id_to_mode[function_id]
1759
+ if mode == CompilationMode.FORWARD:
1760
+ self.running_forwards_with_pending_backwards = True
1761
+ elif mode == CompilationMode.BACKWARD:
1762
+ self.running_forwards_with_pending_backwards = False
1763
+
1764
+ return out
1765
+
1766
+ def set_to_running_backward(self):
1767
+ self.running_forwards_with_pending_backwards = False
1768
+
1769
+ def _run(self, new_inputs: List[Tensor], function_id: FunctionID):
1770
+ # we will try to end the current execution lazily, since
1771
+ # we dont want to do unnecessary checking of the existing outputs
1772
+ # on the hot path, but both recording and warmup only happen once
1773
+ # so we check up front
1774
+ if self.in_recording:
1775
+ self.try_end_curr_recording(function_id)
1776
+
1777
+ if self.in_warmup:
1778
+ self.try_end_curr_warmup(function_id)
1779
+
1780
+ # warming up a function and subsequentally recording may use different memory addresses
1781
+ # because both depend on the state of the caching allocator. if we warm up graph A,
1782
+ # then warm up graph B and make more allocations, the subsequent recording of A will not
1783
+ # necessarily use the same addresses as in the warm up. Thus any warm up of a node can only
1784
+ # be followed by warm up runs.
1785
+ if (
1786
+ not (
1787
+ function_id in self.warmed_up_functions
1788
+ or config.triton.skip_cudagraph_warmup
1789
+ )
1790
+ ) or self.in_warmup:
1791
+ # If we are in the middle of executing cuda graphs, then we need to checkpoint memory state.
1792
+ # Both Recording and Warmup will be reflected in the allocator and dont need changes
1793
+ if self.path_state == ExecutionState.EXECUTION:
1794
+ self.apply_checkpoint_execution_state_in_allocator()
1795
+
1796
+ return self.run_eager(new_inputs, function_id)
1797
+
1798
+ child_nodes = (
1799
+ self.roots if self.current_node is None else self.current_node.children
1800
+ )
1801
+
1802
+ if not self.in_recording:
1803
+ for child in child_nodes[function_id]:
1804
+ # here we are checking memory consistency between recording and execution,
1805
+ # as well as things like stability of tensor locations, etc
1806
+ # and other
1807
+ if child.check_invariants(new_inputs):
1808
+ return self.execute_node(child, new_inputs)
1809
+
1810
+ # now that we know the new function can't be run as a child of the
1811
+ # current node, if it is a root, try to end the current execution.
1812
+ # as noted above, we want to do this lazily to avoid having to
1813
+ # check all existing outputs
1814
+ if self.current_node is not None and function_id in self.roots:
1815
+ self.try_end_curr_execution()
1816
+
1817
+ # run again to hit the root matching case which must succeed
1818
+ if self.current_node is None:
1819
+ return self.run(new_inputs, function_id)
1820
+
1821
+ # at this point, we necessarily will do a new recording
1822
+ self.debug_fail_counter += 1
1823
+
1824
+ self.try_end_curr_execution()
1825
+ if self.current_node is not None:
1826
+ self.apply_checkpoint_execution_state_in_allocator()
1827
+
1828
+ # now, we are in a recording state !
1829
+ return self.record_function(new_inputs, function_id)
1830
+
1831
+ def shutdown(self):
1832
+ """
1833
+ Remove all cached tensors in all nodes. Because cached tensors can hold gradients which in turn
1834
+ might reference a backward which invokes a CUDA Graph Node, we have to manually clear them on shutdown
1835
+ to avoid a reference cycle.
1836
+ """
1837
+ nodes = []
1838
+ for roots in self.roots.values():
1839
+ nodes.extend(roots)
1840
+
1841
+ while nodes:
1842
+ node = nodes.pop()
1843
+ for children in node.children.values():
1844
+ nodes.extend(children)
1845
+ node.remove_node_cached_tensors()
1846
+ node.graph = None
1847
+
1848
+ self.graph = None
1849
+ self.roots = None # type: ignore[assignment]
1850
+ self.current_node = None
1851
+
1852
+ def record_function(self, new_inputs, function_id) -> List[Optional[Tensor]]:
1853
+ graph_id = self.new_graph_id()
1854
+ log.debug(
1855
+ "Recording function %d of graph recording id %d",
1856
+ function_id.id,
1857
+ graph_id.id,
1858
+ )
1859
+ torch.cuda.synchronize()
1860
+ node = CUDAGraphNode(
1861
+ self.ids_to_funcs[function_id],
1862
+ graph_id,
1863
+ self.current_node,
1864
+ new_inputs,
1865
+ self.cuda_graphs_thread_pool,
1866
+ self.device_index,
1867
+ self.ids_to_stack_traces[function_id],
1868
+ self.stream,
1869
+ )
1870
+ if self.current_node is None:
1871
+ self.roots[function_id].append(node)
1872
+ else:
1873
+ self.current_node.add_child(function_id, node)
1874
+ self.current_node = node
1875
+ self.path_state = ExecutionState.RECORDING
1876
+ self.update_generation()
1877
+ torch.cuda.synchronize()
1878
+ return node.run_first_inputs(new_inputs)
1879
+
1880
+ def execute_node(self, node: CUDAGraphNode, new_inputs) -> List[Optional[Tensor]]:
1881
+ self.current_node = node
1882
+ self.path_state = ExecutionState.EXECUTION
1883
+ self.update_generation()
1884
+ return node.run(new_inputs)
1885
+
1886
+ def run_eager(self, new_inputs, function_id: FunctionID):
1887
+ # this is only stored on current node, because when we start a new path,
1888
+ # we will deallocate it
1889
+ already_warm = function_id in self.warmed_up_functions
1890
+ if not already_warm:
1891
+ log.debug("Running warmup of function %d", function_id.id)
1892
+ else:
1893
+ log.debug(
1894
+ "Running eager of function %d because ancestor needed to warm up",
1895
+ function_id.id,
1896
+ )
1897
+ self.warmed_up_functions.add(function_id)
1898
+ node = CUDAWarmupNode(
1899
+ self.ids_to_funcs[function_id],
1900
+ self.current_node,
1901
+ self.cuda_graphs_thread_pool,
1902
+ self.graph,
1903
+ self.device_index,
1904
+ self.ids_to_stack_traces[function_id],
1905
+ self.stream,
1906
+ already_warm,
1907
+ )
1908
+ self.current_node = node
1909
+ self.path_state = ExecutionState.WARMUP
1910
+ self.update_generation()
1911
+ return node.run(new_inputs)
1912
+
1913
+ def new_graph_id(self) -> GraphID:
1914
+ return GraphID(next(self.graph_counter))
1915
+
1916
+ def new_func_id(self) -> FunctionID:
1917
+ return FunctionID(next(self.func_counter))
1918
+
1919
+ def add_function(
1920
+ self,
1921
+ model,
1922
+ inputs,
1923
+ static_input_idxs,
1924
+ stack_traces,
1925
+ mode,
1926
+ constants,
1927
+ ) -> Tuple[Callable[..., Any], List[Optional[Tensor]]]:
1928
+ id = self.new_func_id()
1929
+ self.ids_to_stack_traces[id] = stack_traces
1930
+ self.ids_to_funcs[id] = WrappedFunction(
1931
+ model,
1932
+ static_input_idxs,
1933
+ id,
1934
+ tuple(t for t in constants if isinstance(t, torch.Tensor) and t.is_cuda),
1935
+ )
1936
+ self.id_to_mode[id] = mode
1937
+ fn = functools.partial(self.run, function_id=id)
1938
+
1939
+ # container needs to set clean up when fn dies
1940
+ get_container(self.device_index).add_strong_reference(fn)
1941
+ return fn, fn(inputs)
1942
+
1943
+ @property
1944
+ def in_recording(self):
1945
+ return self.path_state == ExecutionState.RECORDING
1946
+
1947
+ @property
1948
+ def in_warmup(self):
1949
+ return self.path_state == ExecutionState.WARMUP
1950
+
1951
+ def get_roots(self) -> Iterator[CUDAGraphNode]:
1952
+ for nodes in self.roots.values():
1953
+ yield from nodes
1954
+
1955
+ @property
1956
+ def current_node(self):
1957
+ return self._current_node
1958
+
1959
+ @current_node.setter
1960
+ def current_node(self, value):
1961
+ self._current_node = value
1962
+ if value is None:
1963
+ self.path_state = ExecutionState.NONE
1964
+
1965
+ def update_generation(self):
1966
+ self.current_gen = self.get_curr_generation()
1967
+
1968
+ @staticmethod
1969
+ def get_curr_generation() -> int:
1970
+ if MarkStepBox.mark_step_counter != 0:
1971
+ return MarkStepBox.mark_step_counter
1972
+
1973
+ return GenerationTracker.generation
1974
+
1975
+ @staticmethod
1976
+ def user_invoked_mark_step():
1977
+ return MarkStepBox.mark_step_counter != 0
1978
+
1979
+ def can_start_new_generation(self) -> bool:
1980
+ if not self.in_new_torch_compile_invocation():
1981
+ return False
1982
+
1983
+ if self.user_invoked_mark_step():
1984
+ return True
1985
+
1986
+ return not self.running_forwards_with_pending_backwards
1987
+
1988
+ def in_new_torch_compile_invocation(self):
1989
+ return self.current_gen != self.get_curr_generation()
1990
+
1991
+ def try_end_curr_recording(self, function_id: FunctionID) -> None:
1992
+ """
1993
+ Check if the current recording can be terminated, either because all outputs of the
1994
+ previously recorded node are dead or because it was executed in a different
1995
+ generation. Will set current_node to None and in_recording to False if successful.
1996
+ """
1997
+ assert self.in_recording
1998
+ assert self.current_node is not None
1999
+
2000
+ # multiple invocations, allow overwriting the previous generation
2001
+ if self.can_start_new_generation():
2002
+ self.dealloc_current_path_weakrefs()
2003
+ self.clear_current_path_state_and_set_to_none()
2004
+ return
2005
+
2006
+ if self.current_node.all_outputs_are_dead():
2007
+ self.clear_current_path_state_and_set_to_none()
2008
+ return
2009
+
2010
+ self.check_warn_on_unable_to_start_executing(function_id)
2011
+
2012
+ def try_end_curr_execution(self) -> None:
2013
+ """
2014
+ Check if the current executing node can be terminated, either because all outputs of the
2015
+ previously executed node are dead or because it was executed in a different generation.
2016
+ Will set current_node to None if successful.
2017
+ """
2018
+
2019
+ assert not self.in_recording
2020
+ if self.current_node is None:
2021
+ return
2022
+
2023
+ if self.can_start_new_generation():
2024
+ self.clear_current_path_state_and_set_to_none()
2025
+ return
2026
+
2027
+ if self.current_node.all_outputs_are_dead():
2028
+ self.clear_current_path_state_and_set_to_none()
2029
+
2030
+ def try_end_curr_warmup(self, function_id: FunctionID):
2031
+ if self.can_start_new_generation():
2032
+ self.dealloc_current_path_weakrefs()
2033
+ self.current_node = None
2034
+ return
2035
+
2036
+ if self.current_node.all_outputs_are_dead():
2037
+ self.current_node = None
2038
+ return
2039
+
2040
+ self.check_warn_on_unable_to_start_executing(function_id)
2041
+
2042
+ def check_warn_on_unable_to_start_executing(self, function_id: FunctionID):
2043
+ "Warn if we in a potential loop where we are unable to hit fast path"
2044
+ if (
2045
+ function_id in self.warned_functions
2046
+ or not self.in_new_torch_compile_invocation()
2047
+ ):
2048
+ return
2049
+
2050
+ existing_nodes = [
2051
+ node
2052
+ for node in self.current_node._path_from_root
2053
+ if node.wrapped_function.id == function_id
2054
+ ]
2055
+
2056
+ if len(existing_nodes) <= 1:
2057
+ return
2058
+
2059
+ # repeated same pattern
2060
+ parents = {
2061
+ n.parent.wrapped_function.id
2062
+ for n in itertools.chain(existing_nodes, (self.current_node,))
2063
+ if n.parent is not None
2064
+ }
2065
+ if len(parents) == len(existing_nodes):
2066
+ return
2067
+
2068
+ self.warned_functions.add(function_id)
2069
+ warnings.warn(
2070
+ "Unable to hit fast path of CUDAGraphs because of pending, uninvoked backwards. "
2071
+ "Consider running with torch.no_grad() or using torch.compiler.cudagraph_mark_step_begin() "
2072
+ "before each model invocation"
2073
+ )
2074
+
2075
+ def dealloc_current_path_weakrefs(self):
2076
+ # TODO: we could also allow the these weak refs to continue to be allocated,
2077
+ # but that adds some complications.
2078
+ for node in self.current_node._path_from_root:
2079
+ assert len(node.tensor_weakrefs) == len(node.stack_traces)
2080
+ for t, stack_trace in zip(node.tensor_weakrefs, node.stack_traces):
2081
+ ten = None if t is None else t()
2082
+ if ten is None:
2083
+ continue
2084
+
2085
+ stack_trace = (
2086
+ stack_trace.strip()
2087
+ if stack_trace
2088
+ else "[Could not find stack trace]"
2089
+ )
2090
+ msg = (
2091
+ "Error: accessing tensor output of CUDAGraphs that has been overwritten by a subsequent run. "
2092
+ f"Stack trace: {stack_trace}. "
2093
+ "To prevent overwriting, clone the tensor outside of torch.compile() "
2094
+ "or call torch.compiler.cudagraph_mark_step_begin() before each model invocation."
2095
+ )
2096
+ torch._C._set_storage_access_error_msg(ten, msg)
2097
+
2098
+ deleted = set()
2099
+ for storage_ref in self.current_node.path_live_weakrefs():
2100
+ if storage_ref() and storage_ref.data_ptr() not in deleted:
2101
+ deleted.add(storage_ref.data_ptr())
2102
+ torch._C._free_And_Remove_DeleterFn(storage_ref())
2103
+
2104
+ def clear_current_path_state_and_set_to_none(self):
2105
+ self.current_node.clear_path_state()
2106
+ self.current_node = None
2107
+
2108
+ def apply_checkpoint_execution_state_in_allocator(self):
2109
+ """
2110
+ Checkpoint the current execution state in the caching allocator so that
2111
+ additional cudagraph recordings can be made respecting existent live storages.
2112
+ """
2113
+ self.debug_checkpointing_counter += 1
2114
+ log.debug(
2115
+ "Checkpointing cuda caching allocator state. Number of checkpoints %d",
2116
+ self.debug_checkpointing_counter,
2117
+ )
2118
+
2119
+ state = self.current_node.checkpointed_caching_state
2120
+ device = self.current_node.device
2121
+ assert state is not None and device is not None
2122
+
2123
+ # currently we deallocate on instead of allowing stale recordings
2124
+ stale_storages: List[int] = []
2125
+
2126
+ # remove cached tensors, otherwise they would prevent memory from being
2127
+ # reclaimed in subsequent recordings
2128
+ self.current_node.remove_path_cached_tensors()
2129
+ live_storages_wrappers = list(self.current_node.path_live_weakrefs())
2130
+
2131
+ live_storages_weak_refs = [t() for t in live_storages_wrappers]
2132
+ ptrs_to_deallocate = self.current_node.data_ptrs_dead_since_invocation()
2133
+ torch._C._cuda_setCheckpointPoolState(
2134
+ device, state, stale_storages, live_storages_weak_refs
2135
+ )
2136
+
2137
+ # NB: deduplicate aliased outputs
2138
+ for ptr in set(ptrs_to_deallocate):
2139
+ torch._C._cuda_cudaCachingAllocator_raw_delete(ptr)
2140
+
2141
+ # Now the live blocks should be exactly equal to the live storages in private pool
2142
+ if config.triton.slow_path_cudagraph_asserts:
2143
+ check_memory_pool(
2144
+ self.device_index, self.cuda_graphs_thread_pool, live_storages_wrappers
2145
+ )
2146
+ for wrapper in live_storages_wrappers:
2147
+ assert wrapper()
2148
+ assert torch._C._has_Standard_Deleter(wrapper())
2149
+ assert wrapper.data_ptr() not in ptrs_to_deallocate
2150
+
2151
+ def live_cudagraph_pool_storages_in_curr_execution(
2152
+ self,
2153
+ ) -> List[StorageWeakRefPointer]:
2154
+ if self.current_node is None:
2155
+ return []
2156
+ # explicitly ignoring previous recorded outputs from past path
2157
+ return [t() for t in self.current_node.path_live_weakrefs()]
vlmpy310/lib/python3.10/site-packages/torch/_inductor/debug.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import contextlib
3
+ import cProfile
4
+ import dataclasses
5
+ import functools
6
+ import itertools
7
+ import logging
8
+ import os
9
+ import os.path
10
+ import pickle
11
+ import pstats
12
+ import shutil
13
+ import subprocess
14
+ from typing import Any, Dict, List, Optional
15
+ from unittest.mock import patch
16
+
17
+ from functorch.compile import draw_graph, get_aot_graph_name, get_graph_being_compiled
18
+
19
+ import torch
20
+ from torch import fx as fx
21
+
22
+ from torch._dynamo.repro.after_aot import save_graph_repro, wrap_compiler_debug
23
+ from torch._dynamo.utils import get_debug_dir
24
+ from torch.fx.graph_module import GraphModule
25
+ from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata
26
+ from torch.fx.passes.tools_common import legalize_graph
27
+ from torch.utils._pytree import tree_map
28
+
29
+ from . import config, ir # noqa: F811, this is needed
30
+ from .scheduler import (
31
+ BaseSchedulerNode,
32
+ FusedSchedulerNode,
33
+ NopKernelSchedulerNode,
34
+ OutputNode,
35
+ SchedulerNode,
36
+ )
37
+ from .virtualized import V
38
+
39
+ log = logging.getLogger(__name__)
40
+
41
+ SchedulerNodeList = List[Any]
42
+ BufMeta = collections.namedtuple("BufMeta", ["name", "n_origin"])
43
+ GRAPHVIZ_COMMAND_SCALABLE = ["dot", "-Gnslimit=2", "-Gnslimit1=2", "-Gmaxiter=5000"]
44
+
45
+
46
+ @functools.lru_cache(None)
47
+ def has_dot() -> bool:
48
+ try:
49
+ subprocess.check_output(["which", "dot"], stderr=subprocess.PIPE)
50
+ return True
51
+ except subprocess.SubprocessError:
52
+ return False
53
+
54
+
55
+ def draw_buffers(nodes: List[BaseSchedulerNode], print_graph=False, fname=None):
56
+ """
57
+ Draw a graph in fname.svg.
58
+ """
59
+ if not has_dot():
60
+ log.warning("draw_buffers() requires `graphviz` package")
61
+ return
62
+
63
+ if fname is None:
64
+ fname = get_graph_being_compiled()
65
+
66
+ graph = create_fx_from_snodes(nodes)
67
+
68
+ for node in graph.nodes:
69
+ if "fusion_meta" not in node.meta:
70
+ continue
71
+ group = node.meta["fusion_meta"].group
72
+ if isinstance(group, tuple):
73
+ if isinstance(group[1], int):
74
+ group = (group[1],)
75
+ else:
76
+ group = group[1]
77
+
78
+ # gather meta data
79
+ dtype = None
80
+ if isinstance(node, ir.ComputedBuffer):
81
+ dtype = node.data.dtype
82
+
83
+ metadata = TensorMetadata(group, dtype, None, None, None, None, None)
84
+ node.meta["tensor_meta"] = metadata
85
+
86
+ if print_graph:
87
+ print(graph)
88
+
89
+ gm = GraphModule({}, graph)
90
+ legalize_graph(gm)
91
+ gm.graph.lint()
92
+ draw_graph(
93
+ gm, fname, clear_meta=False, dot_graph_shape=config.trace.dot_graph_shape
94
+ )
95
+
96
+
97
+ def create_fx_from_snodes(snodes: List[BaseSchedulerNode]) -> fx.Graph:
98
+ """
99
+ Creates a FX Graph from a list of SchedulerNode objects.
100
+ """
101
+
102
+ def get_fake_func(name):
103
+ def func1(*args):
104
+ return 0
105
+
106
+ func1.__name__ = name
107
+ return func1
108
+
109
+ FusionMeta = collections.namedtuple("FusionMeta", ["group", "snode", "type"])
110
+
111
+ buf_to_fx_node = {}
112
+ graph = torch.fx.Graph()
113
+ first_node = None
114
+
115
+ outputs = []
116
+ group: Any = None
117
+ # create call_function node for each Buffer and Kernel
118
+ for snode in snodes:
119
+ if snode.is_extern():
120
+ node_type = "extern"
121
+ group = node_type
122
+ elif snode.is_template():
123
+ node_type = "template"
124
+ group = node_type
125
+ elif isinstance(snode, NopKernelSchedulerNode):
126
+ node_type = "nop"
127
+ group = node_type
128
+ elif isinstance(snode, SchedulerNode):
129
+ node_type = "compute"
130
+ group = snode.group
131
+ elif isinstance(snode, FusedSchedulerNode):
132
+ node_type = "fused"
133
+ group = snode.group
134
+ else:
135
+ raise RuntimeError("Unknown node type")
136
+
137
+ fused_name = torch._inductor.utils.get_fused_kernel_name(
138
+ snode.get_nodes(), "original_aten"
139
+ )
140
+ func_name = f"{node_type}: {fused_name}"
141
+ node_func = get_fake_func(func_name)
142
+ kwargs = {}
143
+ if hasattr(snode, "get_device"):
144
+ kwargs = {"device": snode.get_device()}
145
+ fx_node = graph.call_function(node_func, args=(), kwargs=kwargs)
146
+
147
+ def in_output(snode):
148
+ if isinstance(snode, FusedSchedulerNode):
149
+ return any(in_output(x) for x in snode.snodes)
150
+ return any(isinstance(user.node, OutputNode) for user in snode.users)
151
+
152
+ if in_output(snode):
153
+ outputs.append(fx_node)
154
+ name = snode.get_name()
155
+ fx_node.name = name
156
+
157
+ fx_node.meta["fusion_meta"] = FusionMeta(group, snode, node_type)
158
+
159
+ if isinstance(snode, FusedSchedulerNode):
160
+ for x in snode.snodes:
161
+ buf_to_fx_node[x.get_name()] = fx_node
162
+ buf_to_fx_node[name] = fx_node
163
+
164
+ if first_node is None:
165
+ first_node = fx_node
166
+
167
+ # create edges between nodes
168
+ for snode in snodes:
169
+ name = snode.get_name()
170
+ deps = snode.read_writes.reads
171
+
172
+ fx_node = buf_to_fx_node[name]
173
+ new_args = []
174
+ for dep in deps:
175
+ if dep.name in buf_to_fx_node:
176
+ dep_node = buf_to_fx_node[dep.name]
177
+ else:
178
+ with graph.inserting_before(first_node):
179
+ dep_node = graph.placeholder(dep.name)
180
+ buf_to_fx_node[dep.name] = dep_node
181
+ new_args.append(dep_node)
182
+
183
+ fx_node.args = tuple(new_args)
184
+
185
+ graph.output(outputs[0] if len(outputs) == 1 else tuple(outputs))
186
+ return graph
187
+
188
+
189
+ def update_orig_fx_node_name_to_buf_name(
190
+ nodes: SchedulerNodeList,
191
+ node_name_to_buf_name: Dict[str, str],
192
+ parent_buf_name: Optional[str] = None,
193
+ n_origins: int = 0,
194
+ ):
195
+ if nodes is None:
196
+ return
197
+ for node in nodes:
198
+ # for FusedSchedulerNode, traverse recursively into get_nodes()
199
+ buf_name = node.get_name()
200
+ children_nodes = node.get_nodes()
201
+ if children_nodes is not None and len(children_nodes) > 1:
202
+ update_orig_fx_node_name_to_buf_name(
203
+ children_nodes,
204
+ node_name_to_buf_name,
205
+ buf_name if parent_buf_name is None else parent_buf_name,
206
+ )
207
+ continue
208
+ else:
209
+ assert len(children_nodes) == 1 and children_nodes[0] == node
210
+
211
+ ir_node = node.node
212
+ if ir_node is None or ir_node.origins is None:
213
+ continue
214
+ for origin in ir_node.origins:
215
+ node_name = origin.name
216
+ # when buf1 and buf2 both have origin=node1
217
+ # we draw node1 according to buf1
218
+ if node_name not in node_name_to_buf_name:
219
+ node_name_to_buf_name[node_name] = (
220
+ buf_name if parent_buf_name is None else parent_buf_name
221
+ )
222
+
223
+
224
+ def get_node_name_to_buf_meta(node_name_to_buf_name: Dict[str, str]):
225
+ buf_name_to_n_node = {}
226
+ for node_name, buf_name in node_name_to_buf_name.items():
227
+ if buf_name not in buf_name_to_n_node:
228
+ buf_name_to_n_node[buf_name] = {node_name}
229
+ else:
230
+ buf_name_to_n_node[buf_name].add(node_name)
231
+
232
+ node_name_to_buf_meta = {}
233
+ for node_name, buf_name in node_name_to_buf_name.items():
234
+ n_node = len(buf_name_to_n_node[buf_name])
235
+ node_name_to_buf_meta[node_name] = BufMeta(buf_name, n_node)
236
+ return node_name_to_buf_meta
237
+
238
+
239
+ def annotate_orig_fx_with_snodes(
240
+ gm: torch.fx.GraphModule, snodes: SchedulerNodeList
241
+ ) -> None:
242
+ """
243
+ Creates a FX Graph from a list of SchedulerNode objects.
244
+ """
245
+ node_name_to_buf_name: Dict[str, str] = {}
246
+ update_orig_fx_node_name_to_buf_name(snodes, node_name_to_buf_name)
247
+ if node_name_to_buf_name is None:
248
+ return
249
+ node_name_to_buf_meta = get_node_name_to_buf_meta(node_name_to_buf_name)
250
+ for node in gm.graph.nodes:
251
+ if node.name in node_name_to_buf_meta:
252
+ node.meta["buf_meta"] = node_name_to_buf_meta.get(node.name)
253
+
254
+
255
+ @contextlib.contextmanager
256
+ def enable_aot_logging():
257
+ compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
258
+
259
+ import torch._functorch.aot_autograd
260
+
261
+ log = logging.getLogger(torch._functorch.aot_autograd.__name__)
262
+
263
+ stack = contextlib.ExitStack()
264
+ if not compile_debug:
265
+ try:
266
+ yield
267
+ finally:
268
+ stack.close()
269
+ return
270
+
271
+ # Enable all graphs to be logged to a file by setting the flags to True
272
+ # and the log level of the file logger to DEBUG
273
+ stack.enter_context(patch("functorch.compile.config.debug_partitioner", True))
274
+
275
+ path = os.path.join(get_debug_dir(), "torchinductor")
276
+ if not os.path.exists(path):
277
+ os.makedirs(path)
278
+
279
+ fh = logging.FileHandler(
280
+ os.path.join(
281
+ path,
282
+ f"aot_{get_aot_graph_name()}_debug.log",
283
+ )
284
+ )
285
+ fh.setLevel(logging.DEBUG)
286
+ fh.setFormatter(
287
+ logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s")
288
+ )
289
+ log.addHandler(fh)
290
+ try:
291
+ yield
292
+ finally:
293
+ log.removeHandler(fh)
294
+ stack.close()
295
+
296
+
297
+ class DebugContext:
298
+ _counter = itertools.count()
299
+
300
+ @staticmethod
301
+ def wrap(fn):
302
+ @functools.wraps(fn)
303
+ def inner(*args, **kwargs):
304
+ with DebugContext():
305
+ return fn(*args, **kwargs)
306
+
307
+ return wrap_compiler_debug(inner, compiler_name="inductor")
308
+
309
+ @staticmethod
310
+ def create_debug_dir(folder_name: str) -> Optional[str]:
311
+ debug_dir = config.trace.debug_dir or get_debug_dir()
312
+ for n in DebugContext._counter:
313
+ dirname = os.path.join(
314
+ debug_dir,
315
+ "torchinductor",
316
+ f"{folder_name}.{n}",
317
+ )
318
+ if not os.path.exists(dirname):
319
+ os.makedirs(dirname)
320
+ return dirname
321
+ return None
322
+
323
+ def __init__(self):
324
+ self._prof = None
325
+ self._path = None
326
+ self._stack = contextlib.ExitStack()
327
+
328
+ def copy(self, new_path: str):
329
+ if not self._path:
330
+ return
331
+ assert new_path.endswith(".debug"), new_path
332
+ if os.path.exists(new_path):
333
+ shutil.rmtree(new_path)
334
+ try:
335
+ shutil.copytree(self._path, new_path)
336
+ self._path = new_path
337
+ except OSError:
338
+ log.warning(
339
+ "Failed to copy debug files from %s to %s", self._path, new_path
340
+ )
341
+ pass
342
+
343
+ def fopen(self, filename: str):
344
+ assert self._path
345
+ return open(os.path.join(self._path, filename), "w")
346
+
347
+ def filename(self, suffix: str):
348
+ assert self._path
349
+ return os.path.join(self._path, suffix)
350
+
351
+ def upload_tar(self):
352
+ if config.trace.upload_tar is not None:
353
+ import tarfile
354
+
355
+ assert self._path
356
+ tar_file = os.path.join(
357
+ self._path, f"{os.path.basename(self._path)}.tar.gz"
358
+ )
359
+ with tarfile.open(tar_file, "w:gz") as tar:
360
+ tar.add(self._path, arcname=os.path.basename(self._path))
361
+ config.trace.upload_tar(tar_file)
362
+
363
+ def __enter__(self):
364
+ if config.debug:
365
+ log = logging.getLogger("torch._dynamo")
366
+ prev_level = log.level
367
+ log.setLevel(logging.DEBUG)
368
+
369
+ def reset_log_level(level):
370
+ log.setLevel(level)
371
+
372
+ self._stack.callback(reset_log_level, prev_level)
373
+
374
+ self._stack.enter_context(V.set_debug_handler(self))
375
+
376
+ if not config.trace.enabled:
377
+ return
378
+
379
+ self._path = self.create_debug_dir(get_aot_graph_name())
380
+
381
+ if config.trace.debug_log:
382
+ self._setup_log_capture("debug.log", logging.DEBUG)
383
+ if config.trace.info_log:
384
+ self._setup_log_capture("info.log", logging.INFO)
385
+ if config.trace.compile_profile:
386
+ self._prof = cProfile.Profile()
387
+ self._prof.enable()
388
+
389
+ def _setup_log_capture(self, filename: str, level: int):
390
+ log = logging.getLogger("torch._inductor")
391
+ fd = self._stack.enter_context(self.fopen(filename))
392
+ ch = logging.StreamHandler(fd)
393
+ ch.setLevel(level)
394
+ ch.setFormatter(
395
+ logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s")
396
+ )
397
+ log.addHandler(ch)
398
+ log.setLevel(min(log.level, level))
399
+ self._stack.callback(log.removeHandler, ch)
400
+
401
+ def __exit__(self, exc_type, exc_val, exc_tb):
402
+ if self._prof:
403
+ self._prof.disable()
404
+ self._save_profile_data()
405
+
406
+ if self._path:
407
+ self.upload_tar()
408
+ log.warning("%s debug trace: %s", get_graph_being_compiled(), self._path)
409
+ self._stack.close()
410
+
411
+ def _save_profile_data(self):
412
+ assert self._prof
413
+ self._prof.dump_stats(self.filename("compile.prof"))
414
+ with self.fopen("compile.stats") as fd:
415
+ stats = pstats.Stats(self._prof, stream=fd)
416
+ stats.strip_dirs()
417
+ stats.sort_stats("cumtime")
418
+ stats.print_stats(100)
419
+ stats.sort_stats("tottime")
420
+ stats.print_stats(100)
421
+
422
+ def __getattr__(self, name):
423
+ if config.trace.enabled and getattr(config.trace, name):
424
+ try:
425
+ return getattr(DebugFormatter(self), name)
426
+ except Exception:
427
+ log.warning("Ignoring exception in debug code", exc_info=True)
428
+ else:
429
+
430
+ def ignored(*args, **kwargs):
431
+ pass
432
+
433
+ return ignored
434
+
435
+
436
+ class DebugFormatter:
437
+ def __init__(self, handler):
438
+ self.fopen = handler.fopen
439
+ self.filename = handler.filename
440
+ self.handler = handler
441
+
442
+ def fx_graph(self, gm: torch.fx.GraphModule, inputs: List[torch.Tensor]):
443
+ with self.fopen("fx_graph_runnable.py") as fd:
444
+ save_graph_repro(fd, gm, inputs, "inductor")
445
+
446
+ with self.fopen("fx_graph_readable.py") as fd:
447
+ fd.write(gm.print_readable(print_output=False))
448
+
449
+ def fx_graph_transformed(
450
+ self, gm: torch.fx.GraphModule, inputs: List[torch.Tensor]
451
+ ):
452
+ with self.fopen("fx_graph_transformed.py") as fd:
453
+ fd.write(gm.print_readable(print_output=False))
454
+
455
+ def ir_pre_fusion(self, nodes: SchedulerNodeList):
456
+ self._write_ir("ir_pre_fusion.txt", nodes)
457
+
458
+ def ir_post_fusion(self, nodes: SchedulerNodeList):
459
+ self._write_ir("ir_post_fusion.txt", nodes)
460
+
461
+ def _write_ir(self, filename: str, nodes: SchedulerNodeList):
462
+ with self.fopen(filename) as fd:
463
+ log.info("Writing debug ir to %s", fd.name)
464
+ for node in nodes:
465
+ fd.write(node.debug_str())
466
+ fd.write("\n\n\n")
467
+
468
+ def graph_diagram(self, nodes: SchedulerNodeList):
469
+ draw_buffers(nodes, fname=self.filename("graph_diagram.svg"))
470
+
471
+ def draw_orig_fx_graph(self, gm: torch.fx.GraphModule, nodes: SchedulerNodeList):
472
+ annotate_orig_fx_with_snodes(gm, nodes)
473
+ draw_graph(
474
+ gm,
475
+ fname=self.filename("orig_fx_graph_diagram.svg"),
476
+ clear_meta=False,
477
+ prog=GRAPHVIZ_COMMAND_SCALABLE,
478
+ parse_stack_trace=True,
479
+ dot_graph_shape=config.trace.dot_graph_shape,
480
+ )
481
+
482
+ def output_code(self, filename):
483
+ shutil.copy(filename, self.filename("output_code.py"))
484
+
485
+
486
+ @dataclasses.dataclass
487
+ class TensorMetadataHolder:
488
+ tensor_metadata: TensorMetadata
489
+ device: torch.device
490
+
491
+
492
+ save_args_cnt = itertools.count()
493
+
494
+
495
+ def save_args_for_compile_fx_inner(*args, **kwargs):
496
+ """
497
+ This function is used to save arguments for a compile_fx_inner function call
498
+ to the file system. Later on one can replay the compile_fx_inner call
499
+ with the saved arguments using load_args_and_run_compile_fx_inner.
500
+ """
501
+
502
+ folder = "/tmp/inductor_saved_args"
503
+ if not os.path.exists(folder):
504
+ os.mkdir(folder)
505
+
506
+ def handle_tensor(x):
507
+ """
508
+ Pickle FakeTensor will result in error:
509
+ AttributeError: Can't pickle local object 'WeakValueDictionary.__init__.<locals>.remove'
510
+
511
+ Convert all Tensor to metadata. This may also makes pickle faster.
512
+ """
513
+ if isinstance(x, torch.Tensor):
514
+ return TensorMetadataHolder(_extract_tensor_metadata(x), x.device)
515
+ else:
516
+ return x
517
+
518
+ args_to_save, kwargs_to_save = tree_map(handle_tensor, (args, kwargs))
519
+
520
+ fn_name = "compile_fx_inner"
521
+ path = f"{folder}/{fn_name}_{next(save_args_cnt)}.pkl"
522
+ with open(path, "wb") as f:
523
+ pickle.dump((args_to_save, kwargs_to_save), f)
524
+
525
+ if log.isEnabledFor(logging.DEBUG):
526
+ message = f"""
527
+ Arguments for a compile_fx_inner call is saved to {path}. To replay the call,
528
+ run the following:
529
+
530
+ from torch._inductor.debug import load_args_and_run_compile_fx_inner
531
+ load_args_and_run_compile_fx_inner({path!r})
532
+ """
533
+ # call print rather than log.debug. log.debug will print message
534
+ # prefix for each line which makes the code snippet harder to be
535
+ # copied.
536
+ # Not a big deal since the code is already been guarded by checking
537
+ # the log level.
538
+ print(message)
539
+
540
+
541
+ def load_args_and_run_compile_fx_inner(path: str):
542
+ from torch._inductor.compile_fx import compile_fx_inner
543
+
544
+ with open(path, "rb") as f:
545
+ args, kwargs = pickle.load(f)
546
+
547
+ def handle_tensor(x):
548
+ if isinstance(x, TensorMetadataHolder):
549
+ return torch._dynamo.testing.rand_strided(
550
+ x.tensor_metadata.shape,
551
+ x.tensor_metadata.stride,
552
+ x.tensor_metadata.dtype,
553
+ x.device,
554
+ )
555
+ else:
556
+ return x
557
+
558
+ fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True)
559
+ with fake_mode, config.patch("save_args", False):
560
+ args, kwargs = tree_map(handle_tensor, (args, kwargs))
561
+ return compile_fx_inner(*args, **kwargs)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/decomposition.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import math
4
+ import sys
5
+ import typing
6
+ from typing import Optional
7
+
8
+ import torch
9
+ import torch._decomp as decomp
10
+ import torch._prims_common as utils
11
+ import torch.ao.quantization.fx._decomposed
12
+ from torch._decomp import (
13
+ core_aten_decompositions,
14
+ get_decompositions,
15
+ remove_decompositions,
16
+ )
17
+ from torch._decomp.decompositions import (
18
+ _grid_sampler_2d as decomp_grid_sampler_2d,
19
+ pw_cast_for_opmath,
20
+ )
21
+ from torch._decomp.decompositions_for_rng import extra_random_decomps
22
+ from torch._higher_order_ops.out_dtype import out_dtype
23
+ from torch._prims_common import type_to_dtype
24
+
25
+ from . import config, inductor_prims
26
+
27
+ log = logging.getLogger(__name__)
28
+ aten = torch.ops.aten
29
+ prims = torch.ops.prims
30
+ quantized_decomposed = torch.ops.quantized_decomposed
31
+
32
+ inductor_decompositions = get_decompositions(
33
+ [
34
+ aten._adaptive_avg_pool2d_backward,
35
+ aten.arange,
36
+ aten.bitwise_and_,
37
+ aten.bitwise_or_,
38
+ aten.clamp_min_,
39
+ aten.dist,
40
+ aten.empty_like,
41
+ aten.flip,
42
+ aten.gelu,
43
+ aten.hardtanh,
44
+ aten.index_select,
45
+ aten.lcm,
46
+ aten.leaky_relu,
47
+ aten.linalg_vector_norm,
48
+ aten._log_softmax,
49
+ aten.max_pool2d_with_indices_backward,
50
+ aten._native_batch_norm_legit,
51
+ aten._native_batch_norm_legit_functional,
52
+ aten._native_batch_norm_legit_no_training,
53
+ aten.native_batch_norm,
54
+ aten.native_group_norm,
55
+ aten.native_layer_norm,
56
+ aten._softmax,
57
+ aten.sin_,
58
+ aten.sqrt_,
59
+ out_dtype,
60
+ aten._to_copy,
61
+ aten.tril_indices,
62
+ aten.triu_indices,
63
+ aten.upsample_bilinear2d.vec,
64
+ ]
65
+ )
66
+ decompositions = {**core_aten_decompositions(), **inductor_decompositions}
67
+
68
+ # Remove unwanted decompositions included via the core ATen decompositions from
69
+ # the Inductor decomp table.
70
+ decomps_to_exclude = [
71
+ aten._unsafe_index,
72
+ aten._scaled_dot_product_flash_attention.default, # See comments in torch/_decomp/decompositions.py
73
+ aten.clamp_max,
74
+ aten.clamp_min,
75
+ aten.glu, # inductor lowers this directly
76
+ aten.split.Tensor, # inductor lowers this directly
77
+ aten.squeeze, # inductor lowers this directly
78
+ aten.sum, # inductor lowers this directly
79
+ aten.unbind, # inductor lowers this directly
80
+ ]
81
+
82
+ remove_decompositions(decompositions, decomps_to_exclude)
83
+
84
+
85
+ def register_decomposition(ops):
86
+ for op in [ops] if callable(ops) else ops:
87
+ if op in decompositions:
88
+ log.warning("duplicate decomp: %s", ops)
89
+ return decomp.register_decomposition(ops, decompositions)
90
+
91
+
92
+ # TODO: for now, inductor doesn't handle asserts
93
+ # because the condition is symbool -> tensor in the graph.
94
+ @register_decomposition([aten._assert_async.msg])
95
+ def assert_async_msg_decomp(tensor, msg):
96
+ return
97
+
98
+
99
+ # Following `assert_async_msg_decomp` and implement as non-op.
100
+ @register_decomposition([aten._functional_assert_async.msg])
101
+ def functional_assert_async_msg_decomp(tensor, msg):
102
+ return
103
+
104
+
105
+ @register_decomposition([aten.sym_constrain_range_for_size.default])
106
+ def sym_constrain_range_for_size(symbol, *, min=None, max=None):
107
+ return
108
+
109
+
110
+ @register_decomposition([aten.clamp])
111
+ @pw_cast_for_opmath
112
+ def clamp(x, min=None, max=None):
113
+ if min is not None:
114
+ x = x.clamp_min(min)
115
+ if max is not None:
116
+ x = x.clamp_max(max)
117
+ return x
118
+
119
+
120
+ @register_decomposition([aten.full])
121
+ def full(size, fill_value, **kwargs):
122
+ dtype = kwargs.get("dtype")
123
+ if dtype is None:
124
+ kwargs["dtype"] = type_to_dtype(type(fill_value))
125
+ return aten.full(size, fill_value, **kwargs)
126
+ return NotImplemented
127
+
128
+
129
+ # Not really sure how to put this into the main library. PrimTorch wants
130
+ # empty_permuted to go to the prim, and typically users don't really want
131
+ # to decompose to empty_strided (but inductor is OK with it, because we are
132
+ # cool with strides and everything goes to empty_strided)
133
+ @register_decomposition([aten.empty_permuted.default])
134
+ def empty_permuted(size, physical_layout, **kwargs):
135
+ perm = [0] * len(size)
136
+ for p, l in enumerate(physical_layout):
137
+ perm[l] = p
138
+ return torch.empty([size[l] for l in physical_layout], **kwargs).permute(perm)
139
+
140
+
141
+ @register_decomposition([aten.convolution_backward])
142
+ def convolution_backward(
143
+ grad_output,
144
+ input,
145
+ weight,
146
+ bias_sizes,
147
+ stride,
148
+ padding,
149
+ dilation,
150
+ transposed,
151
+ output_padding,
152
+ groups,
153
+ output_mask,
154
+ ):
155
+ if not output_mask[2] or grad_output.device.type != "cuda":
156
+ return NotImplemented
157
+ grad_bias = aten.sum(grad_output, [0] + list(range(2, grad_output.dim())))
158
+ grad_inp, grad_weight, _ = aten.convolution_backward(
159
+ grad_output,
160
+ input,
161
+ weight,
162
+ bias_sizes,
163
+ stride,
164
+ padding,
165
+ dilation,
166
+ transposed,
167
+ output_padding,
168
+ groups,
169
+ [output_mask[0], output_mask[1], False],
170
+ )
171
+ return (grad_inp, grad_weight, grad_bias)
172
+
173
+
174
+ @register_decomposition([aten.log2])
175
+ def log2(x):
176
+ return torch.log(x) * (1.0 / math.log(2.0))
177
+
178
+
179
+ @register_decomposition([aten.round.decimals])
180
+ def round_dec(x, decimals=0):
181
+ ten_pow_decimals = 10.0**decimals
182
+ return aten.round(x * ten_pow_decimals) * (1.0 / ten_pow_decimals)
183
+
184
+
185
+ @register_decomposition([aten.bmm])
186
+ @pw_cast_for_opmath
187
+ def bmm(self, batch2):
188
+ if config.coordinate_descent_tuning:
189
+ if self.shape[1] == 1:
190
+ out = (self.unsqueeze(-1) * batch2.unsqueeze(1)).sum(dim=2)
191
+ return out
192
+ if self.device.type == "cpu":
193
+ if self.size(1) == 1 and batch2.size(-1) == 1:
194
+ return torch.sum(
195
+ self.squeeze(1) * batch2.squeeze(-1), dim=1, keepdim=True
196
+ ).unsqueeze(1)
197
+ return NotImplemented
198
+
199
+
200
+ @register_decomposition([aten.addmm])
201
+ @pw_cast_for_opmath
202
+ def addmm(self, mat1, mat2, beta=1, alpha=1):
203
+ if self.device.type == "cpu":
204
+ if mat1.size(0) == 1 and mat2.size(-1) == 1:
205
+ out = torch.sum(
206
+ mat1.squeeze(0) * mat2.squeeze(-1), dim=0, keepdim=True
207
+ ).unsqueeze(0)
208
+ return alpha * out + beta * self
209
+ if mat1.size(0) == 1 and mat2.size(0) <= 16 and mat2.size(1) <= 16:
210
+ out = (mat1.T * mat2).sum(dim=0, keepdim=True)
211
+ return alpha * out + beta * self
212
+ return NotImplemented
213
+
214
+
215
+ @register_decomposition([aten.mm])
216
+ @pw_cast_for_opmath
217
+ def mm(self, input2):
218
+ # Our matrix vector multiplies only achieve peak bandwidth with coordinate descent tuning.
219
+ # todo: Look into why and fix it (hopefully)
220
+ if config.coordinate_descent_tuning:
221
+ if self.shape[0] == 1 or input2.shape[1] == 1:
222
+ return (self.unsqueeze(2) * input2.unsqueeze(0)).sum(dim=1)
223
+ if self.device.type == "cpu":
224
+ if (
225
+ self.size(-1) == 1
226
+ and self.size(0) > 0
227
+ and input2.size(0) == 1
228
+ and (self.dtype == input2.dtype)
229
+ and ((torch.numel(self) + torch.numel(input2)) <= 32)
230
+ ):
231
+ return torch.cat([self[i, :] * input2 for i in range(self.size(0))])
232
+ if self.size(0) == 1 and input2.size(-1) == 1:
233
+ return torch.sum(
234
+ self.squeeze(0) * input2.squeeze(-1), dim=0, keepdim=True
235
+ ).unsqueeze(0)
236
+ return NotImplemented
237
+
238
+
239
+ @register_decomposition([aten.cat.default])
240
+ def cat(tensors, dim=0):
241
+ def non_empty_tensor(x):
242
+ # special case for cat'ing with an empty tensor -
243
+ # just drop the 'empty' inputs so they don't confuse the logic below.
244
+ return len(x.shape) > 1 or x.shape[0] > 0
245
+
246
+ filtered_tensors = list(filter(non_empty_tensor, tensors))
247
+
248
+ if len(filtered_tensors) == 1:
249
+ return filtered_tensors[0].clone()
250
+ elif 1 < len(filtered_tensors) < len(tensors):
251
+ # on the first call, when we remove empty tensors, we redispatch recursively
252
+ return aten.cat.default(filtered_tensors, dim)
253
+ # when no 'filtering' has occurred, we raise to prevent infinite recursion (no more decomposition needed)
254
+ return NotImplemented
255
+
256
+
257
+ @register_decomposition([aten.angle])
258
+ def angle(x):
259
+ if x.is_complex():
260
+ return torch.where(
261
+ torch.isnan(x.real), float("nan"), torch.atan2(x.imag, x.real)
262
+ )
263
+ else:
264
+ # when x is real number
265
+ # if x >= 0, return 0
266
+ # if x < 0, return pi
267
+ # if x is nan, return nan
268
+ ret = torch.where(x < 0, math.pi, 0.0)
269
+ nan = torch.where(torch.isnan(x), float("nan"), 0.0)
270
+ return ret + nan
271
+
272
+
273
+ @register_decomposition([aten.add])
274
+ def add(x, y, *, alpha=None):
275
+ x_is_complex_tensor = torch.is_tensor(x) and x.is_complex()
276
+ y_is_complex_tensor = torch.is_tensor(y) and y.is_complex()
277
+ if not x_is_complex_tensor or not y_is_complex_tensor:
278
+ return NotImplemented
279
+ z = y
280
+ if alpha is not None:
281
+ z = alpha * y
282
+ complex_type = torch.promote_types(x.dtype, y.dtype)
283
+ return (x.view(x.real.dtype) + z.view(y.real.dtype)).view(complex_type)
284
+
285
+
286
+ @register_decomposition([aten.conj_physical])
287
+ def conj_physical(self):
288
+ assert not self.is_complex(), "TODO: implement this"
289
+ return self
290
+
291
+
292
+ @register_decomposition([aten.lift, aten.detach_])
293
+ def lift(self):
294
+ return self
295
+
296
+
297
+ @register_decomposition([aten.bernoulli.default])
298
+ def bernoulli(self, *, generator=None):
299
+ assert generator is None
300
+ return torch.rand_like(self, dtype=torch.float32) < self
301
+
302
+
303
+ @register_decomposition([aten.fmin, prims.fmin])
304
+ def fmin(self, other):
305
+ return torch.where(torch.isnan(other) | (other > self), self, other)
306
+
307
+
308
+ @register_decomposition([aten.fmax, prims.fmax])
309
+ def fmax(self, other):
310
+ return torch.where(torch.isnan(other) | (other < self), self, other)
311
+
312
+
313
+ @register_decomposition(aten.amax)
314
+ def amax(self, dim=None, keepdim=False):
315
+ if self.dtype == torch.bool:
316
+ return torch.any(self, dim=dim, keepdim=keepdim)
317
+ return NotImplemented
318
+
319
+
320
+ @register_decomposition(aten.amin)
321
+ def amin(self, dim=None, keepdim=False):
322
+ if self.dtype == torch.bool:
323
+ return torch.all(self, dim=dim, keepdim=keepdim)
324
+ return NotImplemented
325
+
326
+
327
+ @register_decomposition([aten.narrow_copy])
328
+ def narrow_copy(self, dim, start, length):
329
+ return torch.narrow(self, dim, start, length).clone()
330
+
331
+
332
+ @register_decomposition([aten.expand_copy])
333
+ def expand_copy(self, size, *, implicit=False):
334
+ return aten.expand(self, size, implicit=implicit).clone()
335
+
336
+
337
+ @register_decomposition([aten.view_copy.default])
338
+ def view_copy_default(self, size):
339
+ return aten.view(self, size).clone()
340
+
341
+
342
+ @register_decomposition([aten.view_copy.dtype])
343
+ def view_copy_dtype(self, dtype):
344
+ return self.to(dtype).clone()
345
+
346
+
347
+ def get_like_layout(
348
+ tensor: torch.Tensor, memory_format: Optional[torch.memory_format]
349
+ ) -> torch.memory_format:
350
+ # TODO: _to_copy tensor to stride permutation
351
+ if memory_format is torch.preserve_format or memory_format is None:
352
+ return utils.suggest_memory_format(tensor)
353
+ else:
354
+ return memory_format
355
+
356
+
357
+ @register_decomposition(aten.rand_like)
358
+ def rand_like(self, *, dtype=None, device=None, memory_format=None, **kwargs):
359
+ return torch.rand(
360
+ [*self.size()],
361
+ dtype=dtype or self.dtype,
362
+ device=device or self.device,
363
+ **kwargs,
364
+ ).to(memory_format=get_like_layout(self, memory_format))
365
+
366
+
367
+ @register_decomposition(aten.randn_like)
368
+ def randn_like(self, *, dtype=None, device=None, memory_format=None, **kwargs):
369
+ return torch.randn(
370
+ [*self.size()],
371
+ dtype=dtype or self.dtype,
372
+ device=device or self.device,
373
+ **kwargs,
374
+ ).to(memory_format=get_like_layout(self, memory_format))
375
+
376
+
377
+ @register_decomposition(aten.full_like)
378
+ def full_like(
379
+ self,
380
+ fill_value,
381
+ *,
382
+ dtype=None,
383
+ layout=None,
384
+ device=None,
385
+ pin_memory=False,
386
+ requires_grad=False,
387
+ memory_format=torch.preserve_format,
388
+ ):
389
+ return torch.full(
390
+ [*self.size()],
391
+ fill_value,
392
+ dtype=dtype or self.dtype,
393
+ layout=layout or self.layout,
394
+ device=device or self.device,
395
+ requires_grad=requires_grad,
396
+ ).to(memory_format=get_like_layout(self, memory_format))
397
+
398
+
399
+ @register_decomposition(aten.randint_like.default)
400
+ def randint_like(self, high, *, dtype=None, device=None, memory_format=None, **kwargs):
401
+ return aten.randint.low(
402
+ 0,
403
+ high,
404
+ [*self.size()],
405
+ dtype=dtype or self.dtype,
406
+ device=device or self.device,
407
+ **kwargs,
408
+ ).to(memory_format=get_like_layout(self, memory_format))
409
+
410
+
411
+ @register_decomposition(aten.randint_like.low_dtype)
412
+ def randint_like_low(
413
+ self, low, high, *, dtype=None, device=None, memory_format=None, **kwargs
414
+ ):
415
+ return aten.randint.low(
416
+ low,
417
+ high,
418
+ [*self.size()],
419
+ dtype=dtype or self.dtype,
420
+ device=device or self.device,
421
+ **kwargs,
422
+ ).to(memory_format=get_like_layout(self, memory_format))
423
+
424
+
425
+ @register_decomposition(aten.randint.default)
426
+ def randint(high, size, **kwargs):
427
+ return aten.randint.low(0, high, size, **kwargs)
428
+
429
+
430
+ # The difference between quantize_per_tensor.default and quantize_per_tensor.tensor is
431
+ # scale and zero_point is scalar or scalar tensor
432
+ @register_decomposition(quantized_decomposed.quantize_per_tensor.default)
433
+ def quantize_per_tensor_default_decomp_impl(
434
+ input: torch.Tensor,
435
+ scale: float,
436
+ zero_point: int,
437
+ quant_min: int,
438
+ quant_max: int,
439
+ dtype: torch.dtype,
440
+ ) -> torch.Tensor:
441
+ if input.dtype == torch.bfloat16:
442
+ input = input.to(torch.float32)
443
+ inv_scale = 1.0 / scale
444
+ return torch.clamp(
445
+ torch.round(input * inv_scale) + zero_point, quant_min, quant_max
446
+ ).to(dtype)
447
+
448
+
449
+ # The difference between dequantize_per_tensor.default and dequantize_per_tensor.tensor is
450
+ # scale and zero_point is scalar or scalar tensor
451
+ @register_decomposition(quantized_decomposed.dequantize_per_tensor.default)
452
+ def dequantize_per_tensor_default_decomp_impl(
453
+ input: torch.Tensor,
454
+ scale: float,
455
+ zero_point: int,
456
+ quant_min: int,
457
+ quant_max: int,
458
+ dtype: torch.dtype,
459
+ ) -> torch.Tensor:
460
+ return (input.to(torch.float32) - zero_point) * scale
461
+
462
+
463
+ @register_decomposition(quantized_decomposed.quantize_per_tensor.tensor)
464
+ def quantize_per_tensor_tensor_decomp_impl(
465
+ input: torch.Tensor,
466
+ scale: torch.Tensor,
467
+ zero_point: torch.Tensor,
468
+ quant_min: int,
469
+ quant_max: int,
470
+ dtype: torch.dtype,
471
+ ) -> torch.Tensor:
472
+ if input.dtype == torch.bfloat16:
473
+ input = input.to(torch.float32)
474
+ inv_scale = 1.0 / scale
475
+ return torch.clamp(
476
+ torch.round(input * inv_scale) + zero_point, quant_min, quant_max
477
+ ).to(dtype)
478
+
479
+
480
+ @register_decomposition(quantized_decomposed.dequantize_per_tensor.tensor)
481
+ def dequantize_per_tensor_tensor_decomp_impl(
482
+ input: torch.Tensor,
483
+ scale: torch.Tensor,
484
+ zero_point: torch.Tensor,
485
+ quant_min: int,
486
+ quant_max: int,
487
+ dtype: torch.dtype,
488
+ ) -> torch.Tensor:
489
+ return (input.to(torch.float32) - zero_point) * scale
490
+
491
+
492
+ @register_decomposition(torch.ops.quantized.embedding_bag_byte_unpack)
493
+ def q_embedding_bag_byte_unpack_decomp(packed):
494
+ def bitcast_u8_to_f32(u8):
495
+ x, y, z, w = (u8[..., n].to(torch.int32) for n in (0, 1, 2, 3))
496
+ if sys.byteorder == "little":
497
+ return (x + (y << 8) + (z << 16) + (w << 24)).view(torch.float32)[..., None]
498
+ else:
499
+ return ((x << 24) + (y << 16) + (z << 8) + w).view(torch.float32)[..., None]
500
+
501
+ scales = bitcast_u8_to_f32(packed[..., -8:-4])
502
+ offsets = bitcast_u8_to_f32(packed[..., -4:])
503
+ return packed[..., :-8].to(torch.float32) * scales + offsets
504
+
505
+
506
+ @register_decomposition([aten.grid_sampler_2d])
507
+ @pw_cast_for_opmath
508
+ def grid_sampler_2d(
509
+ a: torch.Tensor,
510
+ grid: torch.Tensor,
511
+ interpolation_mode: int = 0,
512
+ padding_mode: int = 0,
513
+ align_corners: bool = False,
514
+ ) -> torch.Tensor:
515
+ # We do not expand the grid (_expand_grid=False) on cpu for performance reasons
516
+ # Experimenting locally it was found that compiled CUDA code is accelerated by ~5x
517
+ # and CPU code by ~2x on bicubic mode, if we expand the grid from (N, H, W, 2) into (N, C, H, W, 2)
518
+ # However, this leads to a slowdown around ~0.8x on CPU bilinear mode, channels first.
519
+ # Thus we apply this hack to not expand the grid for this case.
520
+ _expand_grid = not (
521
+ a.device == torch.device("cpu")
522
+ and interpolation_mode == 0
523
+ and a.is_contiguous(memory_format=torch.contiguous_format)
524
+ )
525
+
526
+ output = decomp_grid_sampler_2d(
527
+ a,
528
+ grid=grid,
529
+ interpolation_mode=interpolation_mode,
530
+ padding_mode=padding_mode,
531
+ align_corners=align_corners,
532
+ _expand_grid=_expand_grid,
533
+ )
534
+ return output
535
+
536
+
537
+ @register_decomposition(aten._foreach_addcmul.Scalar)
538
+ def _foreach_addcmul_scalar(self, left_tensors, right_tensors, scalar=1):
539
+ return aten._foreach_add.List(
540
+ self, aten._foreach_mul.List(left_tensors, right_tensors), alpha=scalar
541
+ )
542
+
543
+
544
+ @register_decomposition(aten._foreach_addcdiv.Scalar)
545
+ def _foreach_addcdiv_scalar(self, left_tensors, right_tensors, scalar=1):
546
+ return aten._foreach_add.List(
547
+ self, aten._foreach_div.List(left_tensors, right_tensors), alpha=scalar
548
+ )
549
+
550
+
551
+ @register_decomposition(aten._foreach_lerp.Scalar)
552
+ def _foreach_lerp_scalar(start_tensors, end_tensors, weight):
553
+ return aten._foreach_add.List(
554
+ start_tensors,
555
+ aten._foreach_mul.Scalar(
556
+ aten._foreach_sub.List(end_tensors, start_tensors), weight
557
+ ),
558
+ )
559
+
560
+
561
+ @aten.miopen_batch_norm.default.py_impl(torch._C.DispatchKey.Autograd)
562
+ @register_decomposition(aten.miopen_batch_norm)
563
+ def miopen_batch_norm(
564
+ input: torch.Tensor,
565
+ weight: torch.Tensor,
566
+ bias: typing.Optional[torch.Tensor],
567
+ running_mean: typing.Optional[torch.Tensor],
568
+ running_var: typing.Optional[torch.Tensor],
569
+ training: bool,
570
+ exponential_average_factor: float,
571
+ epsilon: float,
572
+ ):
573
+ a, b, c = aten.native_batch_norm(
574
+ input,
575
+ weight,
576
+ bias,
577
+ running_mean,
578
+ running_var,
579
+ training,
580
+ exponential_average_factor,
581
+ epsilon,
582
+ )
583
+
584
+ if training:
585
+ return (a, b, c)
586
+ return (
587
+ a,
588
+ weight.new_zeros((0,)),
589
+ weight.new_zeros((0,)),
590
+ )
591
+
592
+
593
+ @functools.lru_cache(None)
594
+ def fast_random_decomps():
595
+ return {**decompositions, **extra_random_decomps}
596
+
597
+
598
+ def select_decomp_table():
599
+ """decomps can change based on config"""
600
+ if config.fallback_random:
601
+ return decompositions
602
+ return fast_random_decomps()
603
+
604
+
605
+ @register_decomposition(aten.masked_scatter)
606
+ def masked_scatter(self, mask, source):
607
+ if self.device.type == "cuda":
608
+ # This two-step algorithm is the same as eager CUDA, for eager CPU we
609
+ # use a 1-shot serial iteration.
610
+ self, mask = aten.broadcast_tensors([self, mask])
611
+ source_idx = mask.reshape(-1).cumsum(0) - 1
612
+ return inductor_prims.masked_scatter_with_index(self, mask, source_idx, source)
613
+ return NotImplemented
vlmpy310/lib/python3.10/site-packages/torch/_inductor/dependencies.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import dataclasses
3
+ import itertools
4
+ import logging
5
+ import re
6
+ import typing
7
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
8
+
9
+ import sympy
10
+
11
+ import torch
12
+ from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
13
+
14
+ from .codegen.common import index_prevent_reordering
15
+ from .utils import get_dtype_size, sympy_str, sympy_subs, sympy_symbol, VarRanges
16
+ from .virtualized import V
17
+
18
+ log = logging.getLogger(__name__)
19
+ is_indirect = re.compile(r"indirect|tmp").search
20
+ Dep = Union["MemoryDep", "StarDep", "WeakDep"]
21
+
22
+
23
+ class MemoryDep(typing.NamedTuple):
24
+ name: str
25
+ index: sympy.Expr
26
+ var_names: Tuple[sympy.Symbol, ...]
27
+ size: Tuple[sympy.Expr, ...]
28
+
29
+ def __repr__(self):
30
+ return f"MemoryDep({self.name!r}, {self.index}, {self.ranges})"
31
+
32
+ @property
33
+ def ranges(self) -> Dict[sympy.Symbol, sympy.Expr]:
34
+ """{c0: 128, c1: 512, ...}"""
35
+ return dict(zip(self.var_names, self.size))
36
+
37
+ def get_numel(self) -> sympy.Expr:
38
+ if self.is_indirect():
39
+ numel = V.graph.get_numel(self.name)
40
+ else:
41
+ vars = set(self.index.free_symbols)
42
+ numel = sympy.Integer(1)
43
+ for var, size in zip(self.var_names, self.size):
44
+ if var in vars:
45
+ numel = numel * size
46
+ return numel
47
+
48
+ def rename(self, renames: Dict[str, str]) -> "MemoryDep":
49
+ if self.name in renames:
50
+ return MemoryDep(
51
+ renames[self.name], self.index, var_names=self.var_names, size=self.size
52
+ )
53
+ return self
54
+
55
+ def numbytes_hint(self):
56
+ return V.graph.sizevars.size_hint(self.get_numel()) * get_dtype_size(
57
+ V.graph.get_dtype(self.name)
58
+ )
59
+
60
+ def has_unbacked_symbols(self):
61
+ return len(free_unbacked_symbols(self.get_numel())) > 0
62
+
63
+ def is_contiguous(self) -> bool:
64
+ return isinstance(self.index, sympy.Symbol) and self.index in self.var_names
65
+
66
+ def is_scalar(self) -> bool:
67
+ if isinstance(self.index, sympy.Symbol):
68
+ return self.index not in self.var_names and not self.is_indirect()
69
+ return isinstance(self.index, (int, sympy.Integer))
70
+
71
+ def is_indirect(self) -> bool:
72
+ return any(is_indirect(v.name) for v in self.index.free_symbols)
73
+
74
+
75
+ class StarDep(typing.NamedTuple):
76
+ # depends on the entire buffer
77
+ name: str
78
+
79
+ @property
80
+ def index(self):
81
+ raise NotImplementedError("StarDep does not have an index")
82
+
83
+ def get_numel(self) -> sympy.Expr:
84
+ return V.graph.get_numel(self.name)
85
+
86
+ def rename(self, renames: Dict[str, str]) -> "StarDep":
87
+ if self.name in renames:
88
+ return StarDep(renames[self.name])
89
+ return self
90
+
91
+ def numbytes_hint(self):
92
+ return V.graph.sizevars.size_hint(self.get_numel()) * get_dtype_size(
93
+ V.graph.get_dtype(self.name)
94
+ )
95
+
96
+ def has_unbacked_symbols(self):
97
+ return len(free_unbacked_symbols(self.get_numel())) > 0
98
+
99
+ def is_contiguous(self) -> bool:
100
+ return False
101
+
102
+ def is_scalar(self) -> bool:
103
+ return False
104
+
105
+ def is_indirect(self) -> bool:
106
+ return False
107
+
108
+
109
+ # Used for tracking mutation ordering
110
+ # if A reads a buffer and B mutates it
111
+ # B must be ordered after A
112
+ #
113
+ # It is weak because if it turns out A's read is never used, we can still
114
+ # eliminate it
115
+ class WeakDep(typing.NamedTuple):
116
+ name: str
117
+
118
+ @property
119
+ def index(self):
120
+ raise NotImplementedError("WeakDep does not have an index")
121
+
122
+ def get_numel(self) -> sympy.Expr:
123
+ return sympy.Integer(1)
124
+
125
+ def rename(self, renames: Dict[str, str]) -> "WeakDep":
126
+ if self.name in renames:
127
+ return WeakDep(renames[self.name])
128
+ return self
129
+
130
+ def numbytes_hint(self):
131
+ return 1 # Purely inserted for ordering, not an actual dep
132
+
133
+ def has_unbacked_symbols(self):
134
+ return False
135
+
136
+ def is_contiguous(self) -> bool:
137
+ return False
138
+
139
+
140
+ class IndexExprDep(typing.NamedTuple):
141
+ index: sympy.Expr
142
+ var_names: Tuple[sympy.Symbol, ...]
143
+ size: Tuple[sympy.Expr, ...]
144
+
145
+
146
+ @dataclasses.dataclass
147
+ class ReadWrites:
148
+ reads: Set[Dep]
149
+ writes: Set[Dep]
150
+ index_exprs: Set[IndexExprDep]
151
+ range_vars: Optional[List[sympy.Expr]] = None
152
+ var_ranges: Optional[VarRanges] = None
153
+ op_counts: typing.Counter[str] = dataclasses.field(
154
+ default_factory=collections.Counter
155
+ )
156
+
157
+ def rename(self, renames: typing.Dict[str, str]) -> "ReadWrites":
158
+ return ReadWrites(
159
+ {dep.rename(renames) for dep in self.reads},
160
+ {dep.rename(renames) for dep in self.writes},
161
+ self.index_exprs,
162
+ self.range_vars,
163
+ self.var_ranges,
164
+ op_counts=self.op_counts,
165
+ )
166
+
167
+ def with_read(self, dep: Dep) -> "ReadWrites":
168
+ assert isinstance(dep, (WeakDep, StarDep))
169
+ return ReadWrites(
170
+ set.union(self.reads, {dep}),
171
+ self.writes,
172
+ self.index_exprs,
173
+ self.range_vars,
174
+ self.var_ranges,
175
+ op_counts=self.op_counts,
176
+ )
177
+
178
+ def merge(self, other: "ReadWrites"):
179
+ reads = set.union(self.reads, other.reads)
180
+ writes = set.union(self.writes, other.writes)
181
+ index_exprs = set.union(self.index_exprs, other.index_exprs)
182
+ op_counts = collections.Counter(self.op_counts)
183
+ op_counts.update(other.op_counts)
184
+ return ReadWrites(reads - writes, writes, index_exprs, op_counts=op_counts)
185
+
186
+ @staticmethod
187
+ def merge_list(read_writes: List["ReadWrites"]):
188
+ all_writes = set.union(*[rw.writes for rw in read_writes])
189
+ all_reads = set.union(*[rw.reads for rw in read_writes]) - all_writes
190
+ all_index_exprs = set.union(*[rw.index_exprs for rw in read_writes])
191
+
192
+ op_counts: typing.Counter[Any] = collections.Counter()
193
+ for rw in read_writes:
194
+ op_counts.update(rw.op_counts)
195
+
196
+ return ReadWrites(all_reads, all_writes, all_index_exprs, op_counts=op_counts)
197
+
198
+ def remove_reads(self, rem_reads):
199
+ return ReadWrites(
200
+ self.reads - rem_reads,
201
+ self.writes,
202
+ self.index_exprs,
203
+ self.range_vars,
204
+ self.var_ranges,
205
+ op_counts=self.op_counts,
206
+ )
207
+
208
+ def reads_and_writes(self):
209
+ return itertools.chain(self.reads, self.writes)
210
+
211
+
212
+ class _RecordLoadStoreInner(V.MockHandler): # type: ignore[name-defined]
213
+ def __init__(self, var_ranges: VarRanges, normalize: bool):
214
+ super().__init__()
215
+ self._reads: Set[Dep] = set()
216
+ self._writes: Set[MemoryDep] = set()
217
+ self._index_exprs: Set[IndexExprDep] = set()
218
+ self._var_ranges: VarRanges = var_ranges
219
+ self._normalize: bool = normalize
220
+
221
+ def canonicalize(
222
+ self, index: sympy.Expr
223
+ ) -> Tuple[sympy.Expr, Tuple[sympy.Symbol, ...], Tuple[sympy.Expr, ...]]:
224
+ if not self._normalize:
225
+ sizes = [V.graph.sizevars.simplify(x) for x in self._var_ranges.values()]
226
+ var_names = tuple(
227
+ k for k, v in zip(self._var_ranges.keys(), sizes) if v != 1
228
+ )
229
+ sizes = tuple(v for v in sizes if v != 1)
230
+ return index, var_names, sizes
231
+
232
+ # Try to further simplify the indexes even if simplify_loops didn't
233
+ # convert it to the simplest form because of the interference from
234
+ # different indexing formulas.
235
+ free_symbols = index.free_symbols
236
+ var_ranges = {
237
+ k: V.graph.sizevars.simplify(v)
238
+ for k, v in self._var_ranges.items()
239
+ # TODO(jansel): explore this further normalization
240
+ # if k in free_symbols
241
+ }
242
+ index_vars = [*var_ranges.keys()]
243
+ sizes = tuple(var_ranges.values())
244
+ new_sizes, reindex, prune = V.graph.sizevars._simplify_loops(
245
+ index_vars,
246
+ sizes,
247
+ index_prevent_reordering([index], index_vars, sizes),
248
+ )
249
+
250
+ # assign new variables each dimension to deal with numbering mismatches
251
+ # d0, d1, d2 could become d0, d2 -- which won't match d0, d1
252
+ new_vars, add_var = var_builder(canonicalization_prefix())
253
+ replacement = dict(zip(index_vars, reindex([add_var(x) for x in new_sizes])))
254
+ index = sympy_subs(sympy.expand(index), replacement)
255
+
256
+ new_vars = [*new_vars.keys()]
257
+ new_sizes = [*new_sizes]
258
+ free_symbols = index.free_symbols
259
+ while new_vars and new_vars[-1] not in free_symbols:
260
+ # Reduction has last (reduced) dim in its sizes, but
261
+ # downstream users won't. Normalize this away.
262
+ new_vars.pop()
263
+ new_sizes.pop()
264
+ return index, tuple(new_vars), tuple(new_sizes)
265
+
266
+ def load(self, name: str, index: sympy.Expr) -> str:
267
+ self._reads.add(MemoryDep(name, *self.canonicalize(index)))
268
+ return f"load({name}, {sympy_str(index)})"
269
+
270
+ def load_seed(self, name: str, index: int):
271
+ assert isinstance(index, int)
272
+ return self.load(name, sympy.Integer(index))
273
+
274
+ def store(self, name: str, index: sympy.Expr, value: str, mode=None) -> str:
275
+ self._writes.add(MemoryDep(name, *self.canonicalize(index)))
276
+ return f"store({name}, {sympy_str(index)}, {value}, {mode})"
277
+
278
+ def store_reduction(self, name: str, index, value) -> str:
279
+ return self.store(name, index, f"store_reduction({value})")
280
+
281
+ def index_expr(self, index: sympy.Expr, dtype) -> str:
282
+ self._index_exprs.add(IndexExprDep(*self.canonicalize(index)))
283
+ return f"index_expr({sympy_str(index)}, {dtype})"
284
+
285
+ def bucketize(
286
+ self,
287
+ values,
288
+ offsets_name: str,
289
+ offsets_size: sympy.Expr,
290
+ indexing_dtype: torch.dtype,
291
+ right: bool,
292
+ ):
293
+ self._reads.add(StarDep(offsets_name))
294
+ return f"bucketize({values}, {offsets_name}, {sympy_str(offsets_size)}, {indexing_dtype}, {right})"
295
+
296
+
297
+ class _OpCounter:
298
+ """Shim to count how many times each op is used"""
299
+
300
+ def __init__(self, inner):
301
+ super().__init__()
302
+ self.parent_handler = inner
303
+ self._op_counts: typing.Counter[Any] = collections.Counter()
304
+
305
+ def __getattr__(self, name):
306
+ self._op_counts[name] += 1
307
+ return getattr(self.parent_handler, name)
308
+
309
+
310
+ class RecordLoadStore(V.KernelFormatterHandler): # type: ignore[name-defined]
311
+ def __init__(self, var_ranges: VarRanges, normalize: bool):
312
+ parent_handler = _RecordLoadStoreInner(
313
+ var_ranges=var_ranges, normalize=normalize
314
+ )
315
+ parent_handler = _OpCounter(parent_handler)
316
+ super().__init__(parent_handler=parent_handler)
317
+
318
+
319
+ def var_builder(prefix: str) -> Tuple[VarRanges, Callable[[sympy.Expr], sympy.Symbol]]:
320
+ cnt = itertools.count()
321
+ var_ranges: VarRanges = dict()
322
+
323
+ def add_var(length: sympy.Expr) -> sympy.Symbol:
324
+ v = sympy_symbol(f"{prefix}{next(cnt)}")
325
+ var_ranges[v] = length
326
+ return v
327
+
328
+ return var_ranges, add_var
329
+
330
+
331
+ def index_vars_no_squeeze(*argsizes: Tuple[sympy.Expr, ...], prefix: str):
332
+ var_ranges, add_var = var_builder(prefix)
333
+ args: List[List[sympy.Symbol]] = []
334
+ for size in argsizes:
335
+ args.append(list(map(add_var, size)))
336
+ return args, var_ranges
337
+
338
+
339
+ def index_vars_squeeze(*argsizes: Tuple[sympy.Expr, ...], prefix: str = "d"):
340
+ from .ir import SqueezeView
341
+
342
+ var_ranges, add_var = var_builder(prefix)
343
+ args: List[List[sympy.Expr]] = []
344
+ new_sizes: List[List[sympy.Expr]] = []
345
+ for size in argsizes:
346
+ new_size, reindex = SqueezeView.squeezer(size)
347
+ new_sizes.append(new_size)
348
+ args.append(reindex(list(map(add_var, new_size))))
349
+ return args, var_ranges
350
+
351
+
352
+ def extract_read_writes(
353
+ fn: Callable[..., Any],
354
+ *argsizes: Tuple[sympy.Expr, ...],
355
+ normalize: bool = False,
356
+ prefix: str = "d",
357
+ ):
358
+ args, var_ranges = index_vars_squeeze(*argsizes, prefix=prefix)
359
+ rw = RecordLoadStore(var_ranges, normalize=normalize)
360
+ with V.set_ops_handler(rw):
361
+ fn(*args)
362
+
363
+ if normalize:
364
+ range_vars = [] # Number of vars could differ due to normalization
365
+ else:
366
+ range_vars = [*itertools.chain(*args)]
367
+
368
+ inner = rw.parent_handler.parent_handler
369
+ return ReadWrites(
370
+ set(inner._reads),
371
+ set(inner._writes),
372
+ inner._index_exprs,
373
+ range_vars,
374
+ var_ranges,
375
+ rw.parent_handler._op_counts,
376
+ )
377
+
378
+
379
+ def extract_input_node_reduction_ranges(
380
+ input_node: "torch._inductor.ir.TensorBox",
381
+ ) -> Tuple[Optional[List[sympy.Expr]], Optional[List[sympy.Expr]]]:
382
+ """
383
+ Returns the size and reduction size of all inputs, if the sizes and reduction_sizes (if exist) are all the same.
384
+ It's possible that a node has multiple inputs, some are Reduction nodes and others are Pointwise nodes.
385
+ In this case, reduction_sizes of the Reduction nodes need to be the same.
386
+ Otherwise returns (None, None).
387
+ """
388
+
389
+ from .ir import ComputedBuffer, Loops
390
+
391
+ if isinstance(input_node.data, ComputedBuffer):
392
+ # Input node has already been realized. Return its size and reduction_size.
393
+ size = input_node.get_size()
394
+ reduction_size = input_node.get_reduction_size()
395
+ if len(reduction_size) > 0:
396
+ return (size, reduction_size)
397
+ else:
398
+ return (None, None)
399
+
400
+ if not isinstance(input_node.data.data, Loops): # type: ignore[attr-defined]
401
+ # Other IRNodes do not have reduction_ranges.
402
+ return (None, None)
403
+
404
+ # There is one issue: what if there are views / permutations between the input node and its dependent realized nodes?
405
+ # The current method still uses reduction ranges from the dependent realized node, which is not ideal.
406
+ # Is there a way to check whether there are permutations inbetween?
407
+ reads = input_node.get_reads()
408
+ reduction_size = None
409
+ size = None
410
+ while reduction_size is None and len(reads) > 0:
411
+ seen = set()
412
+ new_reads = []
413
+ for read in reads:
414
+ if not isinstance(read, MemoryDep):
415
+ continue
416
+ if read.name in seen:
417
+ continue
418
+ seen.add(read.name)
419
+ buffer = V.graph.get_buffer(read.name)
420
+ if buffer is None:
421
+ continue
422
+ if (
423
+ isinstance(buffer, ComputedBuffer)
424
+ and len(buffer.get_reduction_size()) > 0
425
+ ):
426
+ if reduction_size is None:
427
+ reduction_size = buffer.get_reduction_size()
428
+ size = buffer.get_size()
429
+ elif (
430
+ reduction_size != buffer.get_reduction_size()
431
+ or size != buffer.get_size()
432
+ ):
433
+ return (None, None)
434
+ else:
435
+ new_reads.extend(buffer.get_reads())
436
+ if reads == new_reads:
437
+ return (size, reduction_size)
438
+ else:
439
+ reads = new_reads
440
+ return (size, reduction_size)
441
+
442
+
443
+ def canonicalization_prefix():
444
+ return "c"
vlmpy310/lib/python3.10/site-packages/torch/_inductor/exc.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import tempfile
5
+ import textwrap
6
+ from functools import lru_cache
7
+
8
+ if os.environ.get("TORCHINDUCTOR_WRITE_MISSING_OPS") == "1":
9
+
10
+ @lru_cache(None)
11
+ def _record_missing_op(target):
12
+ with open(f"{tempfile.gettempdir()}/missing_ops.txt", "a") as fd:
13
+ fd.write(str(target) + "\n")
14
+
15
+ else:
16
+
17
+ def _record_missing_op(target): # type: ignore[misc]
18
+ pass
19
+
20
+
21
+ class OperatorIssue(RuntimeError):
22
+ @staticmethod
23
+ def operator_str(target, args, kwargs):
24
+ lines = [f"target: {target}"] + [
25
+ f"args[{i}]: {arg}" for i, arg in enumerate(args)
26
+ ]
27
+ if kwargs:
28
+ lines.append(f"kwargs: {kwargs}")
29
+ return textwrap.indent("\n".join(lines), " ")
30
+
31
+
32
+ class MissingOperatorWithoutDecomp(OperatorIssue):
33
+ def __init__(self, target, args, kwargs):
34
+ _record_missing_op(target)
35
+ super().__init__(f"missing lowering\n{self.operator_str(target, args, kwargs)}")
36
+
37
+
38
+ class MissingOperatorWithDecomp(OperatorIssue):
39
+ def __init__(self, target, args, kwargs):
40
+ _record_missing_op(target)
41
+ super().__init__(
42
+ f"missing decomposition\n{self.operator_str(target, args, kwargs)}"
43
+ + textwrap.dedent(
44
+ f"""
45
+
46
+ There is a decomposition available for {target} in
47
+ torch._decomp.get_decompositions(). Please add this operator to the
48
+ `decompositions` list in torch._inductor.decompositions
49
+ """
50
+ )
51
+ )
52
+
53
+
54
+ class LoweringException(OperatorIssue):
55
+ def __init__(self, exc: Exception, target, args, kwargs):
56
+ super().__init__(
57
+ f"{type(exc).__name__}: {exc}\n{self.operator_str(target, args, kwargs)}"
58
+ )
59
+
60
+
61
+ class InvalidCxxCompiler(RuntimeError):
62
+ def __init__(self):
63
+ from . import config
64
+
65
+ super().__init__(
66
+ f"No working C++ compiler found in {config.__name__}.cpp.cxx: {config.cpp.cxx}"
67
+ )
68
+
69
+
70
+ class CppWrapperCodeGenError(RuntimeError):
71
+ def __init__(self, msg: str):
72
+ super().__init__(f"C++ wrapper codegen error: {msg}")
73
+
74
+
75
+ class CppCompileError(RuntimeError):
76
+ def __init__(self, cmd: list[str], output: str):
77
+ if isinstance(output, bytes):
78
+ output = output.decode("utf-8")
79
+
80
+ super().__init__(
81
+ textwrap.dedent(
82
+ """
83
+ C++ compile error
84
+
85
+ Command:
86
+ {cmd}
87
+
88
+ Output:
89
+ {output}
90
+ """
91
+ )
92
+ .strip()
93
+ .format(cmd=" ".join(cmd), output=output)
94
+ )
95
+
96
+
97
+ class CUDACompileError(CppCompileError):
98
+ pass
vlmpy310/lib/python3.10/site-packages/torch/_inductor/freezing.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import logging
5
+
6
+ import weakref
7
+ from typing import Any, List, Optional, Tuple
8
+
9
+ import torch
10
+ import torch.utils._pytree as pytree
11
+ from torch._dynamo.utils import dynamo_timed, lazy_format_graph_code
12
+ from torch._functorch.aot_autograd import MutationType
13
+ from torch._functorch.compile_utils import fx_graph_cse
14
+ from torch._inductor.constant_folding import constant_fold, replace_node_with_constant
15
+
16
+ from torch._inductor.fx_passes.freezing_patterns import freezing_passes
17
+ from torch._inductor.fx_passes.post_grad import view_to_reshape
18
+
19
+ from . import config
20
+
21
+ aten = torch.ops.aten
22
+ prims = torch.ops.prims
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+
27
+ def replace_params_with_constants(
28
+ gm: torch.fx.GraphModule,
29
+ flat_params: list[Any],
30
+ fw_metadata: torch._functorch.aot_autograd.ViewAndMutationMeta,
31
+ ) -> List[int]:
32
+ """
33
+ Replaces the parameters of a PyTorch GraphModule with constants wherever possible.
34
+ Returns a list of indices representing the input parameters that were not converted to constants.
35
+ """
36
+ params = [node for node in gm.graph.nodes if node.op == "placeholder"]
37
+ fake_inp_nodes = params[: len(params)]
38
+ preserved_arg_indices = []
39
+ aliased_input_args = [
40
+ out_info.base_idx
41
+ for out_info in fw_metadata.output_info
42
+ if out_info.base_idx is not None
43
+ ]
44
+
45
+ # TODO (tmanlaibaatar) figure out why this is different
46
+ # from mutated_inp_runtime_indices
47
+ mutated_inps = [
48
+ i
49
+ for i, m in enumerate(fw_metadata.input_info)
50
+ if m.mutation_type
51
+ in (MutationType.MUTATED_IN_GRAPH, MutationType.MUTATED_OUT_GRAPH)
52
+ ]
53
+
54
+ for i, (real_input, node) in enumerate(zip(flat_params, fake_inp_nodes)):
55
+ if i in mutated_inps or i in aliased_input_args:
56
+ preserved_arg_indices.append(i)
57
+ continue
58
+ replace_node_with_constant(gm, node, real_input)
59
+ # add on non param inputs
60
+ preserved_arg_indices.extend(range(len(flat_params), len(params)))
61
+ # is this necessary ?
62
+ gm.recompile()
63
+ return preserved_arg_indices
64
+
65
+
66
+ def freeze(
67
+ dynamo_gm: torch.fx.GraphModule,
68
+ aot_autograd_gm: torch.fx.GraphModule,
69
+ example_inputs: List[torch._subclasses.FakeTensor],
70
+ ) -> Tuple[torch.fx.GraphModule, List[int]]:
71
+ """
72
+ Inlines parameters that are not mutated into constants and optimizes the graph through constant propagation
73
+ and other techniques. If enabled, the function also discards the original parameters of the module for memory efficiency.
74
+
75
+ Assumes that this function is run in dynamo tracing post aot_autograd.
76
+
77
+ Args:
78
+ dynamo_gm (torch.fx.GraphModule): The Dynamo constructed GraphModule.
79
+ aot_autograd_gm (torch.fx.GraphModule): The aot_autograd constructed GraphModule to be frozen.
80
+ example_inputs (List[torch.Tensor]): A list of example input tensors to be used in the freezing process.
81
+
82
+ Returns:
83
+ Tuple[torch.fx.GraphModule, List[int]]: A tuple containing the frozen GraphModule and a list of indices
84
+ of the inputs that were preserved (not turned into constants).
85
+ """
86
+ # We have convert conv's weight to channels last which may meet error for .view
87
+ # when doing fake_tensor_prop. So we need to convert view to reshape first.
88
+ # See the details in fx_codegen_and_compile of compile_fx.py.
89
+ view_to_reshape(aot_autograd_gm)
90
+
91
+ if tracing_context := torch._guards.TracingContext.try_get():
92
+ fw_metadata = tracing_context.fw_metadata
93
+ params_flat = tracing_context.params_flat
94
+ assert fw_metadata is not None and params_flat is not None
95
+
96
+ preserved_arg_indices = replace_params_with_constants(
97
+ aot_autograd_gm, params_flat, fw_metadata
98
+ )
99
+ else:
100
+ inputs = [
101
+ node for node in aot_autograd_gm.graph.nodes if node.op == "placeholder"
102
+ ]
103
+ preserved_arg_indices = list(range(len(inputs)))
104
+
105
+ # TODO - further restrict cse ? right now needed to dedup aliasing ops
106
+ cse_graph = fx_graph_cse(aot_autograd_gm.graph)
107
+ aot_autograd_gm.graph = cse_graph
108
+ aot_autograd_gm.recompile()
109
+
110
+ aot_example_inputs = [example_inputs[ind] for ind in preserved_arg_indices]
111
+ freezing_passes(aot_autograd_gm, aot_example_inputs)
112
+
113
+ constant_fold(aot_autograd_gm)
114
+ # invalidate nn Modules
115
+ if config.freezing_discard_parameters:
116
+ invalidate_eager_modules()
117
+ discard_traced_gm_params(dynamo_gm)
118
+
119
+ log.debug("%s", lazy_format_graph_code("FROZEN GRAPH", aot_autograd_gm))
120
+
121
+ return aot_autograd_gm, preserved_arg_indices
122
+
123
+
124
+ class ErasedTensor(torch.Tensor):
125
+ @staticmethod
126
+ def __new__(cls, elem, name, owning_mod):
127
+ return super().__new__(cls, elem.to(device="meta"))
128
+
129
+ def __init__(self, elem, name: Optional[str], mod):
130
+ self.erased_name = name
131
+ self.owning_mod_ref = weakref.ref(mod)
132
+
133
+ @classmethod
134
+ def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
135
+ erased_tensors = [
136
+ e
137
+ for e in pytree.arg_tree_leaves(*args, **kwargs)
138
+ if isinstance(e, ErasedTensor)
139
+ ]
140
+ assert len(erased_tensors) > 0
141
+ e = erased_tensors[0]
142
+
143
+ raise RuntimeError(
144
+ f"Trying to run Pytorch Eager Module after Dynamo Freezing. "
145
+ "The original parameters have been discarded for memory efficiency. "
146
+ f"Found in op {func} for erased parameter {e.erased_name} of {e.owning_mod_ref()}"
147
+ )
148
+
149
+
150
+ @torch.utils._python_dispatch._disable_current_modes()
151
+ def invalidate_eager_modules():
152
+ for mod in torch._guards.TracingContext.get().module_context.nn_modules.values():
153
+ if not isinstance(mod, torch.nn.Module):
154
+ continue
155
+
156
+ for attr_name, tensor in list(
157
+ itertools.chain(
158
+ mod.named_parameters(recurse=False), mod.named_buffers(recurse=False)
159
+ )
160
+ ):
161
+ with torch._dispatch.python.no_python_dispatcher():
162
+ e_t = ErasedTensor(tensor, attr_name, mod)
163
+ if isinstance(tensor, torch.nn.Parameter):
164
+ e_t.requires_grad_(True)
165
+ e_t._is_param = True # type: ignore[attr-defined]
166
+ setattr(mod, attr_name, e_t)
167
+
168
+
169
+ @torch.utils._python_dispatch._disable_current_modes()
170
+ def discard_traced_gm_params(mod: torch.fx.GraphModule):
171
+ for attr_name, tensor in list(
172
+ itertools.chain(
173
+ mod.named_parameters(recurse=False), mod.named_buffers(recurse=False)
174
+ )
175
+ ):
176
+ with torch._dispatch.python.no_python_dispatcher():
177
+ e_t = ErasedTensor(tensor, attr_name, mod)
178
+ if isinstance(tensor, torch.nn.Parameter):
179
+ e_t.requires_grad_(True)
180
+ e_t._is_param = True # type: ignore[attr-defined]
181
+ setattr(mod, attr_name, e_t)
182
+
183
+
184
+ def enforce_output_layout(gm: torch.fx.GraphModule):
185
+ """
186
+ Make sure the output node's layout does not change due to compiler optimizations
187
+ by adding aten.as_strided nodes with the expected strides.
188
+
189
+ Only used for inference so we can assume all graph outputs are model outputs.
190
+ """
191
+ *_, output_node = gm.graph.nodes
192
+ out_list = output_node.args[0]
193
+ with gm.graph.inserting_before(output_node):
194
+ for n in out_list:
195
+ if not isinstance(
196
+ n.meta["val"], torch.Tensor
197
+ ) or not torch._prims_common.is_non_overlapping_and_dense(n.meta["val"]):
198
+ continue
199
+
200
+ # add a node to enforce eager layout
201
+ ft = n.meta["val"]
202
+ new_node = gm.graph.call_function(
203
+ prims.inductor_force_stride_order.default, (n, ft.stride())
204
+ )
205
+
206
+ # can not call
207
+ # n.replace_all_uses_with(new_node)
208
+ # since it will replace the usage of n in new_node itself.
209
+ output_node.replace_input_with(n, new_node)
210
+
211
+ gm.graph.lint()
212
+ gm.recompile()
213
+
214
+
215
+ def enforce_as_strided_input_layout(gm: torch.fx.GraphModule):
216
+ """
217
+ Make sure the as_strided node's input's layout does not change due to compiler
218
+ optimizations, because the as_strided strides info depends on input tensor stride info.
219
+ """
220
+
221
+ as_strided_ops = [
222
+ torch.ops.aten.as_strided.default,
223
+ torch.ops.aten.as_strided_.default,
224
+ torch.ops.aten.as_strided_scatter.default,
225
+ ]
226
+ strided_nodes = [n for n in gm.graph.nodes if n.target in as_strided_ops]
227
+ for n in strided_nodes:
228
+ with gm.graph.inserting_before(n):
229
+ # add a node to enforce eager layout
230
+ ft = n.args[0].meta["val"]
231
+ new_node = gm.graph.call_function(
232
+ prims.inductor_force_stride_order.default, (n.args[0], ft.stride())
233
+ )
234
+ n.replace_input_with(n.args[0], new_node)
235
+
236
+ gm.graph.lint()
237
+ gm.recompile()
238
+
239
+
240
+ @dynamo_timed
241
+ def convert_conv_weights_to_channels_last(gm: torch.fx.GraphModule):
242
+ """
243
+ Convert 4d convolution weight tensor to channels last format.
244
+
245
+ This pass is performed before freezing so the added nodes can be constant
246
+ folded by freezing.
247
+ """
248
+ convs = [n for n in gm.graph.nodes if n.target == aten.convolution.default]
249
+ for conv in convs:
250
+ weight_node = conv.args[1]
251
+ if len(weight_node.meta["val"].size()) != 4 or weight_node.meta[
252
+ "val"
253
+ ].is_contiguous(memory_format=torch.channels_last):
254
+ # not a 4d tensor or already channels last, skip
255
+ continue
256
+
257
+ with gm.graph.inserting_before(conv):
258
+ new_node = gm.graph.call_function(
259
+ aten.clone.default,
260
+ (weight_node,),
261
+ {"memory_format": torch.channels_last},
262
+ )
263
+ conv.replace_input_with(weight_node, new_node)
264
+
265
+ enforce_as_strided_input_layout(gm)
266
+ enforce_output_layout(gm)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__init__.py ADDED
File without changes
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-310.pyc ADDED
Binary file (6.54 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-310.pyc ADDED
Binary file (3.82 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-310.pyc ADDED
Binary file (8.08 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/__pycache__/replace_random.cpython-310.pyc ADDED
Binary file (3.68 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/binary_folding.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import itertools
3
+
4
+ import torch
5
+ from ..._dynamo.utils import counters
6
+
7
+ from ..pattern_matcher import Arg, CallFunction, KeywordArg
8
+ from .freezing_patterns import register_binary_folding_pattern
9
+
10
+ aten = torch.ops.aten
11
+ prims = torch.ops.prims
12
+
13
+
14
+ def mark_mixed_dtype_conv(conv):
15
+ conv_dtype = conv.meta["val"].dtype
16
+ if conv_dtype not in (torch.float16, torch.bfloat16):
17
+ return
18
+
19
+ if not len(conv.users) == 1:
20
+ return
21
+
22
+ conv_user = next(iter(conv.users.keys()))
23
+ if not isinstance(conv_user.meta["val"], torch.Tensor):
24
+ return
25
+
26
+ if not conv_user.meta["val"].dtype == torch.float32:
27
+ return
28
+
29
+ while conv_user.target in _binary_ops:
30
+ if not len(conv_user.users) == 1:
31
+ return
32
+
33
+ conv_user = next(iter(conv_user.users.keys()))
34
+
35
+ if not (
36
+ conv_user.target == prims.convert_element_type.default
37
+ and conv_user.args[1] == conv_dtype
38
+ ):
39
+ return
40
+
41
+ conv.meta["_allow_conv_mixed_dtype_folding"] = conv_dtype
42
+
43
+
44
+ def mark_mixed_dtype_allowed_convs(gm):
45
+ """
46
+ Mark convolutions which we will binary fold even with mixed precision constants. We constant fold in the higher precision
47
+ for better accuracy and then recover the original precision after.
48
+ """
49
+ for node in gm.graph.nodes:
50
+ if node.target is aten.convolution.default:
51
+ mark_mixed_dtype_conv(node)
52
+
53
+
54
+ def recover_original_precision_folded_convs(gm):
55
+ """
56
+ After binary folding conv weights and biases to a higher dtype, recover the original precision they were in.
57
+ """
58
+ graph = gm.graph
59
+ convs = [node for node in graph.nodes if node.target is aten.convolution.default]
60
+ for node in convs:
61
+ orig_dtype = node.meta.get("_allow_conv_mixed_dtype_folding", None)
62
+ if orig_dtype is None:
63
+ continue
64
+
65
+ with graph.inserting_before(node):
66
+ for idx in [1, 2]:
67
+ old_input = node.args[idx]
68
+ if old_input is None:
69
+ continue
70
+
71
+ new_input = graph.create_node(
72
+ "call_function",
73
+ prims.convert_element_type.default,
74
+ (old_input, orig_dtype),
75
+ )
76
+ node.replace_input_with(old_input, new_input)
77
+
78
+
79
+ _binary_ops = [aten.add.Tensor, aten.sub.Tensor, aten.mul.Tensor, aten.div.Tensor]
80
+
81
+
82
+ @functools.lru_cache(None)
83
+ def binary_folding_init():
84
+ _conv_args = [Arg() for _ in range(9)]
85
+ _computation_ops = [aten.convolution.default]
86
+ _computation_calls = [CallFunction(aten.convolution.default, *_conv_args, _users=1)]
87
+
88
+ """
89
+ In order to fuse add/sub/mul/div with conv, the dimensions of its
90
+ constant tensor must satisfy the following:
91
+ - with resizing, broadcast to w/ weight/bias tensor shape
92
+ - broadcast to the conv output shape
93
+ It needs to have a shape that can resize to weight/bias
94
+ tensor shape because we need to run the op with the conv
95
+ weights/bias without changing their sizes.
96
+ It needs to broadcast to the conv output shape so that we do
97
+ accidentally change the shape of op output by pre-fusing it
98
+ compared to eager.
99
+ The only dimension value shared by weight/bias/conv output
100
+ is they all contain a dim with value = channels-out. In the
101
+ conv output tensor, this is in the second dimension,
102
+ so the pointwise op tensor may have a second dimension of
103
+ value == channels-out, but all the other dimensions have to be 1
104
+ """
105
+
106
+ def _op_not_broadcasting_with_conv(weight_tensor, other_tensor):
107
+ # According to opDoesNotBroadCastWithConv of frozen_conv_folding.cpp
108
+ weight_shape = weight_tensor.shape
109
+ other_shape = other_tensor.shape
110
+ if len(weight_shape) < len(other_shape):
111
+ return False
112
+ if len(weight_shape) == len(other_shape) + 1:
113
+ # weight shape is [o, i, *], other_shape is [o, 1...].
114
+ for i in reversed(range(len(other_shape))):
115
+ if i == 0 and weight_shape[0] == other_shape[i]:
116
+ continue
117
+ if other_shape[i] != 1:
118
+ return False
119
+ else:
120
+ # weight shape is [o, i, *], other_shape is [1, i, *]
121
+ for i in reversed(range(len(other_shape))):
122
+ if i == 1 and weight_shape[0] == other_shape[i]:
123
+ continue
124
+ if other_shape[i] != 1:
125
+ return False
126
+ return True
127
+
128
+ def _check_conv_and_broadcast_op(conv_node, other):
129
+ # According to checkConvAndBroadcastingOpPreConditions of frozen_conv_folding.cpp.
130
+ # conv.weight
131
+ if conv_node.args[1].op != "get_attr":
132
+ return False
133
+ # conv.bias
134
+ if conv_node.args[1] is not None and conv_node.args[1].op != "get_attr":
135
+ return False
136
+ if (
137
+ not isinstance(other, int)
138
+ and not isinstance(other, float)
139
+ and other.op != "get_attr"
140
+ ):
141
+ return False
142
+
143
+ if not len(conv_node.args[1].users) == 1:
144
+ return False
145
+
146
+ weight_meta_value = conv_node.args[1].meta.get("val")
147
+ if weight_meta_value is None:
148
+ return False
149
+ # Avoid fusing op that causes type promotion
150
+ # restricting to float avoids int/float difficulties with scalar overload
151
+ if not weight_meta_value.is_floating_point():
152
+ return False
153
+ if isinstance(other, torch.fx.Node) and other.op == "get_attr":
154
+ other_meta_value = other.meta.get("val")
155
+ if not other_meta_value.is_floating_point():
156
+ return False
157
+ if (
158
+ torch.promote_types(other_meta_value.dtype, weight_meta_value.dtype)
159
+ != weight_meta_value.dtype
160
+ ):
161
+ if not conv_node.meta.get("_allow_conv_mixed_dtype_folding", False):
162
+ return False
163
+
164
+ if (
165
+ other_meta_value.dtype != torch.float
166
+ and weight_meta_value.dtype not in (torch.float16, torch.bfloat16)
167
+ ):
168
+ return False
169
+
170
+ if not _op_not_broadcasting_with_conv(weight_meta_value, other_meta_value):
171
+ return False
172
+ else:
173
+ # TODO: support scalar case
174
+ return False
175
+
176
+ return True
177
+
178
+ def _is_foldable_pattern(match):
179
+ binary_node = match.output_node()
180
+ computation_node = binary_node.args[0]
181
+ other = binary_node.args[1]
182
+ if binary_node.args[0].target not in _computation_ops:
183
+ computation_node = binary_node.args[1]
184
+ other = binary_node.args[0]
185
+ if binary_node.args[0].target == aten.convolution.default:
186
+ return _check_conv_and_broadcast_op(computation_node, other)
187
+
188
+ return False
189
+
190
+ def resize_scalar_or_tensor_to_shape(graph, other, shape):
191
+ # TODO: support scalar case
192
+ if other.meta.get("val").numel() == 1:
193
+ # expand errors if the shape input has less # dims than the tensor input
194
+ res = graph.create_node(
195
+ "call_function",
196
+ aten.reshape.default,
197
+ (other, (1,)),
198
+ )
199
+ res = graph.create_node(
200
+ "call_function",
201
+ aten.expand.default,
202
+ (res, shape),
203
+ )
204
+ else:
205
+ res = graph.create_node(
206
+ "call_function",
207
+ aten.reshape.default,
208
+ (other, shape),
209
+ )
210
+ return res
211
+
212
+ def _create_new_conv_node(graph, conv_node, binary_node, other):
213
+ assert conv_node.target == aten.convolution.default
214
+ conv_args = list(conv_node.args)
215
+ weight_meta_value = conv_node.args[1].meta.get("val")
216
+ bias = conv_args[2]
217
+ if binary_node.target in [aten.add.Tensor, aten.sub.Tensor]:
218
+ other_reshape = resize_scalar_or_tensor_to_shape(
219
+ graph, other, (weight_meta_value.size(0),)
220
+ )
221
+ new_bias = graph.create_node(
222
+ "call_function",
223
+ binary_node.target,
224
+ (0 if bias is None else bias, other_reshape),
225
+ )
226
+ conv_args[2] = new_bias
227
+ else:
228
+ assert binary_node.target in [aten.mul.Tensor, aten.div.Tensor]
229
+ weight_broadcast_shape = [1 for _ in range(len(weight_meta_value.shape))]
230
+ weight_broadcast_shape[0] = weight_meta_value.size(0)
231
+ other_reshape1 = resize_scalar_or_tensor_to_shape(
232
+ graph, other, tuple(weight_broadcast_shape)
233
+ )
234
+ new_weight = graph.create_node(
235
+ "call_function", binary_node.target, (conv_args[1], other_reshape1)
236
+ )
237
+ new_weight.meta.update(conv_args[1].meta)
238
+ conv_args[1] = new_weight
239
+ if bias is not None:
240
+ other_reshape = resize_scalar_or_tensor_to_shape(
241
+ graph, other, (weight_meta_value.size(0),)
242
+ )
243
+ new_bias = graph.create_node(
244
+ "call_function", binary_node.target, (bias, other_reshape)
245
+ )
246
+ new_bias.meta.update(bias.meta)
247
+ conv_args[2] = new_bias
248
+ return graph.create_node("call_function", conv_node.target, tuple(conv_args))
249
+
250
+ for _computation_call, binary_op in itertools.product(
251
+ _computation_calls, _binary_ops
252
+ ):
253
+
254
+ @register_binary_folding_pattern(
255
+ CallFunction(binary_op, _computation_call, KeywordArg("other")),
256
+ extra_check=_is_foldable_pattern,
257
+ )
258
+ def folded_op(match, *args, **kwargs):
259
+ counters["inductor"]["binary_folding"] += 1
260
+ other = kwargs.get("other")
261
+ binary_node = match.output_node()
262
+ computation_node = (
263
+ binary_node.args[0]
264
+ if binary_node.args[0].target in _computation_ops
265
+ else binary_node.args[1]
266
+ )
267
+ graph = match.graph
268
+ with graph.inserting_before(binary_node):
269
+ # TODO: support linear?
270
+ assert computation_node.target == aten.convolution.default
271
+ new_computation_node = _create_new_conv_node(
272
+ graph, computation_node, binary_node, other
273
+ )
274
+ binary_node.replace_all_uses_with(new_computation_node)
275
+ new_computation_node.meta.update(computation_node.meta)
276
+ graph.erase_node(binary_node)
277
+ graph.erase_node(computation_node)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/efficient_conv_bn_eval.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from torch._dynamo.utils import counters
5
+ from torch._inductor import config as inductor_config
6
+ from torch.func import functional_call
7
+
8
+ from ..pattern_matcher import CallModuleVarArgs, Match, register_graph_pattern
9
+
10
+ from .pre_grad import efficient_conv_bn_eval_pass
11
+
12
+
13
+ def efficient_conv_bn_eval(
14
+ bn: nn.modules.batchnorm._BatchNorm, conv: nn.modules.conv._ConvNd, x: torch.Tensor
15
+ ):
16
+ """
17
+ Implementation based on https://arxiv.org/abs/2305.11624
18
+ "Tune-Mode ConvBN Blocks For Efficient Transfer Learning"
19
+ It leverages the associative law between convolution and affine transform,
20
+ i.e., normalize (weight conv feature) = (normalize weight) conv feature.
21
+ It works for Eval mode of ConvBN blocks during validation, and can be used
22
+ for **training** as well, but only if one sets `bn.training=False`. It
23
+ reduces memory footprint and computation cost, at the cost of slightly
24
+ reduced numerical stability.
25
+ Args:
26
+ bn (nn.modules.batchnorm._BatchNorm): a BatchNorm module.
27
+ conv (nn.modules.conv._ConvNd): a conv module
28
+ x (torch.Tensor): Input feature map.
29
+ """
30
+
31
+ assert bn.running_var is not None
32
+
33
+ # These lines of code are designed to deal with various cases
34
+ # like bn without affine transform, and conv without bias
35
+ weight_on_the_fly = conv.weight
36
+ if conv.bias is not None:
37
+ bias_on_the_fly = conv.bias
38
+ else:
39
+ bias_on_the_fly = torch.zeros_like(bn.running_var)
40
+
41
+ if bn.weight is not None:
42
+ bn_weight = bn.weight
43
+ else:
44
+ bn_weight = torch.ones_like(bn.running_var)
45
+
46
+ if bn.bias is not None:
47
+ bn_bias = bn.bias
48
+ else:
49
+ bn_bias = torch.zeros_like(bn.running_var)
50
+
51
+ # shape of [C_out, 1, 1, 1] in Conv2d
52
+ target_shape = [-1] + [1] * (conv.weight.ndim - 1)
53
+ if isinstance(conv, nn.modules.conv._ConvTransposeNd):
54
+ # for transposed conv, the C_out dimension should at index 1.
55
+ target_shape[:2] = [target_shape[1], target_shape[0]]
56
+ weight_coeff = torch.rsqrt(bn.running_var + bn.eps).reshape(target_shape)
57
+ # shape of [C_out, 1, 1, 1] in Conv2d
58
+ coefff_on_the_fly = bn_weight.view_as(weight_coeff) * weight_coeff
59
+
60
+ # shape of [C_out, C_in, k, k] in Conv2d
61
+ weight_on_the_fly = weight_on_the_fly * coefff_on_the_fly
62
+ # shape of [C_out] in Conv2d
63
+ bias_on_the_fly = bn_bias + coefff_on_the_fly.flatten() * (
64
+ bias_on_the_fly - bn.running_mean
65
+ )
66
+
67
+ input = x
68
+ params = {"weight": weight_on_the_fly, "bias": bias_on_the_fly}
69
+ output = functional_call(conv, params, input)
70
+ return output
71
+
72
+
73
+ @register_graph_pattern(
74
+ CallModuleVarArgs(
75
+ [
76
+ nn.modules.batchnorm._BatchNorm,
77
+ nn.BatchNorm1d,
78
+ nn.BatchNorm2d,
79
+ nn.BatchNorm3d,
80
+ nn.SyncBatchNorm,
81
+ ],
82
+ ),
83
+ pass_dict=efficient_conv_bn_eval_pass,
84
+ extra_check=lambda match: not inductor_config.freezing
85
+ and inductor_config.efficient_conv_bn_eval_fx_passes,
86
+ )
87
+ def efficient_conv_bn_eval_graph_transform(match: Match, *args, **kwargs):
88
+ # We matched a BN node
89
+ bn_node = match.nodes[0]
90
+ graph = match.graph
91
+ gm = graph.owning_module
92
+ bn_mod = getattr(gm, bn_node.target)
93
+
94
+ # We can only use efficient conv-bn for eval mode with track_running_stats
95
+ if not bn_mod.track_running_stats or bn_mod.training:
96
+ return
97
+
98
+ # Check if the input is Conv
99
+ if bn_node.args:
100
+ input_node = bn_node.args[0]
101
+ else:
102
+ input_node = bn_node.kwargs["input"]
103
+ if input_node.op != "call_module":
104
+ return
105
+ if not hasattr(gm, input_node.target):
106
+ return
107
+ input_mod = getattr(gm, input_node.target)
108
+ supported_convs = [
109
+ nn.Linear,
110
+ nn.Conv1d,
111
+ nn.Conv2d,
112
+ nn.Conv3d,
113
+ nn.ConvTranspose1d,
114
+ nn.ConvTranspose2d,
115
+ nn.ConvTranspose3d,
116
+ ]
117
+ if not any(isinstance(input_mod, cls) for cls in supported_convs):
118
+ return
119
+ conv_node = input_node
120
+ # Output of conv is used by other nodes, cannot optimize
121
+ if len(conv_node.users) > 1:
122
+ return
123
+
124
+ # Find a pair of conv and bn computation nodes to optimize.
125
+ counters["inductor"]["efficient_conv_bn_eval"] += 1
126
+
127
+ with graph.inserting_before(conv_node):
128
+ # create `get_attr` node to access modules
129
+ # note that we directly call `create_node` to fill the `name`
130
+ # argument. `graph.get_attr` and
131
+ # `graph.call_function` does not allow the `name` argument.
132
+ conv_get_node = graph.create_node(
133
+ op="get_attr", target=conv_node.target, name="get_conv"
134
+ )
135
+ bn_get_node = graph.create_node(
136
+ op="get_attr", target=bn_node.target, name="get_bn"
137
+ )
138
+ if conv_node.args:
139
+ conv_input = conv_node.args[0]
140
+ else:
141
+ conv_input = conv_node.kwargs["input"]
142
+ # prepare args for the fused function
143
+ args = (bn_get_node, conv_get_node, conv_input)
144
+ # create a new node
145
+ new_node = graph.create_node(
146
+ op="call_function",
147
+ target=efficient_conv_bn_eval,
148
+ args=args,
149
+ name="efficient_conv_bn_eval",
150
+ )
151
+ # this node replaces the original conv + bn, and therefore
152
+ # should replace the uses of bn_node
153
+ bn_node.replace_all_uses_with(new_node)
154
+ # take care of the deletion order:
155
+ # delete bn_node first, and then conv_node
156
+ graph.erase_node(bn_node)
157
+ graph.erase_node(conv_node)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/freezing_patterns.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ import torch
4
+ from torch._inductor.compile_fx import fake_tensor_prop
5
+ from ..._dynamo.utils import counters
6
+
7
+ from .. import config
8
+ from ..pattern_matcher import (
9
+ _return_true,
10
+ CallFunction,
11
+ fwd_only,
12
+ Ignored,
13
+ init_once_fakemode,
14
+ KeywordArg,
15
+ Match,
16
+ PatternMatcherPass,
17
+ register_graph_pattern,
18
+ register_replacement,
19
+ stable_topological_sort,
20
+ )
21
+
22
+ aten = torch.ops.aten
23
+
24
+ # First pass_patterns[0] are applied, then [1], then [2]
25
+ pass_patterns = [
26
+ PatternMatcherPass(),
27
+ PatternMatcherPass(),
28
+ PatternMatcherPass(),
29
+ ]
30
+
31
+ binary_folding_pass = PatternMatcherPass()
32
+
33
+
34
+ def freezing_passes(gm: torch.fx.GraphModule, aot_example_inputs):
35
+ """
36
+ Passes that are applied to the graph to freeze pass.
37
+ """
38
+
39
+ from ..freezing import constant_fold
40
+
41
+ lazy_init()
42
+ # We need a few rounds of binary folding to get rid of all the
43
+ # unnecessary nodes, but may need a good method to chose the rounds number.
44
+ # works like: conv+binary+binary.
45
+ binary_folding = counters["inductor"]["binary_folding"]
46
+ fake_tensor_prop(gm, aot_example_inputs, True)
47
+
48
+ torch._inductor.fx_passes.binary_folding.mark_mixed_dtype_allowed_convs(gm)
49
+ for _ in range(4):
50
+ constant_fold(gm)
51
+ # Make sure meta['val'] is properly set for all nodes
52
+ fake_tensor_prop(gm, aot_example_inputs, True)
53
+ binary_folding_pass.apply(gm.graph)
54
+ # If we don't have binary folding, we don't need to run the pass again.
55
+ # TODO: remove the need to run fake_tensor_prop on the whole model.
56
+ if counters["inductor"]["binary_folding"] == binary_folding:
57
+ break
58
+ binary_folding = counters["inductor"]["binary_folding"]
59
+
60
+ torch._inductor.fx_passes.binary_folding.recover_original_precision_folded_convs(gm)
61
+
62
+ constant_fold(gm)
63
+ fake_tensor_prop(gm, aot_example_inputs, True)
64
+
65
+ for pattern in pass_patterns:
66
+ pattern.apply(gm.graph)
67
+
68
+ # The CPU weight packing always assume the conv's weight is channels last,
69
+ # So make sure the layout_optimization is on when doing it.
70
+ if (
71
+ torch._C._has_mkldnn
72
+ and config.cpp.weight_prepack
73
+ and config.layout_optimization
74
+ ):
75
+ from .mkldnn_fusion import _eliminate_duplicate_packed_nodes
76
+
77
+ _eliminate_duplicate_packed_nodes(gm)
78
+
79
+ stable_topological_sort(gm.graph)
80
+ gm.recompile()
81
+ gm.graph.lint()
82
+
83
+
84
+ @init_once_fakemode
85
+ def lazy_init():
86
+ if torch._C._has_mkldnn and config.cpp.weight_prepack:
87
+ from .mkldnn_fusion import _mkldnn_weight_pack_init
88
+
89
+ _mkldnn_weight_pack_init()
90
+
91
+ from .binary_folding import binary_folding_init
92
+
93
+ addmm_patterns_init()
94
+ binary_folding_init()
95
+
96
+
97
+ def register_freezing_graph_pattern(pattern, extra_check=_return_true, pass_number=0):
98
+ return register_graph_pattern(
99
+ pattern,
100
+ extra_check=extra_check,
101
+ pass_dict=pass_patterns[pass_number],
102
+ )
103
+
104
+
105
+ def register_binary_folding_pattern(pattern, extra_check=_return_true):
106
+ return register_graph_pattern(
107
+ pattern,
108
+ extra_check=extra_check,
109
+ pass_dict=binary_folding_pass,
110
+ )
111
+
112
+
113
+ @functools.lru_cache(None)
114
+ def addmm_patterns_init():
115
+ if torch.cuda.is_available():
116
+ # workaround https://github.com/pytorch/pytorch/issues/97894
117
+ device = "cuda"
118
+ else:
119
+ device = "cpu"
120
+ val = functools.partial(torch.empty, (10, 10), device=device, requires_grad=False)
121
+
122
+ def check_concat_weights(match):
123
+ weights = [
124
+ match.kwargs["w1"],
125
+ match.kwargs["w2"],
126
+ ]
127
+ if "w3" in match.kwargs:
128
+ weights.append(match.kwargs["w3"])
129
+
130
+ return all(
131
+ w.op == "get_attr" and w.meta["val"].shape == weights[0].meta["val"].shape
132
+ for w in weights
133
+ )
134
+
135
+ def matmul_fuse_pattern(inp, w1, w2, w3):
136
+ return (inp @ w1, inp @ w2, inp @ w3)
137
+
138
+ def matmul_replacement(inp, w1, w2, w3):
139
+ cat_t = torch.cat((w1, w2, w3), dim=1)
140
+ mm = inp @ cat_t
141
+ return mm.chunk(3, dim=1)
142
+
143
+ register_replacement(
144
+ matmul_fuse_pattern,
145
+ matmul_replacement,
146
+ [val(), val(), val(), val()],
147
+ fwd_only,
148
+ pass_patterns[0],
149
+ extra_check=check_concat_weights,
150
+ exclusive_arg_names=("w1", "w2", "w3"),
151
+ )
152
+
153
+ def matmul_fuse_pattern_two(inp, w1, w2):
154
+ return (inp @ w1, inp @ w2)
155
+
156
+ def matmul_replacement_two(inp, w1, w2):
157
+ cat_t = torch.cat((w1, w2), dim=1)
158
+ mm = inp @ cat_t
159
+ return mm.chunk(2, dim=1)
160
+
161
+ register_replacement(
162
+ matmul_fuse_pattern_two,
163
+ matmul_replacement_two,
164
+ [val(), val(), val()],
165
+ fwd_only,
166
+ pass_patterns[0],
167
+ extra_check=check_concat_weights,
168
+ exclusive_arg_names=("w1", "w2"),
169
+ )
170
+
171
+ def addmm_fuse_pattern_second(inp, w1, w2, w3, b1, b2, b3):
172
+ return (
173
+ aten.addmm(b1, inp, w1),
174
+ aten.addmm(b2, inp, w2),
175
+ aten.addmm(b3, inp, w3),
176
+ )
177
+
178
+ def addmm_fuse_replacement_second(inp, w1, w2, w3, b1, b2, b3):
179
+ cat_w = torch.cat((w1, w2, w3), dim=1)
180
+ cat_b = torch.cat((b1, b2, b3))
181
+ return aten.addmm(cat_b, inp, cat_w).chunk(3, dim=1)
182
+
183
+ register_replacement(
184
+ addmm_fuse_pattern_second,
185
+ addmm_fuse_replacement_second,
186
+ [val() for _ in range(7)],
187
+ fwd_only,
188
+ pass_patterns[0],
189
+ extra_check=check_concat_weights,
190
+ exclusive_arg_names=("w1", "w2", "w3", "b1", "b2", "b3"),
191
+ )
192
+
193
+
194
+ def same_dtype(match):
195
+ return match.output_node().args[0].meta["val"].dtype == match.kwargs["dtype"]
196
+
197
+
198
+ @register_graph_pattern(
199
+ CallFunction(
200
+ torch.ops.prims.convert_element_type.default,
201
+ Ignored(),
202
+ KeywordArg("dtype"),
203
+ ),
204
+ pass_dict=pass_patterns[0],
205
+ extra_check=same_dtype,
206
+ )
207
+ def unnecessary_dtype_convert(match: Match, **kwargs):
208
+ """Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding"""
209
+ graph = match.graph
210
+ node = match.output_node()
211
+ node.replace_all_uses_with(node.args[0])
212
+ graph.erase_node(node)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/fuse_attention.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import logging
4
+ import math
5
+
6
+ import torch
7
+ from ..._dynamo.utils import counters
8
+ from ..pattern_matcher import (
9
+ filter_nodes,
10
+ fwd_only,
11
+ joint_fwd_bwd,
12
+ register_replacement,
13
+ )
14
+
15
+ log = logging.getLogger(__name__)
16
+ aten = torch.ops.aten
17
+
18
+
19
+ def _sfdp_pattern_1(query, key, value, inv_scale):
20
+ return (
21
+ torch.matmul(query, key.transpose(-2, -1))
22
+ .div(inv_scale)
23
+ .softmax(dim=-1)
24
+ .matmul(value)
25
+ )
26
+
27
+
28
+ def _sfdp_replacement_1(query, key, value, inv_scale):
29
+ counters["inductor"]["fuse_attention"] += 1
30
+ return aten.scaled_dot_product_attention(
31
+ query.contiguous(),
32
+ key.contiguous(),
33
+ value.contiguous(),
34
+ attn_mask=None,
35
+ dropout_p=0.0,
36
+ is_causal=False,
37
+ scale=1.0 / inv_scale,
38
+ )
39
+
40
+
41
+ def _sfdp_pattern_2(query, key, value, scale_factor):
42
+ return (
43
+ torch.matmul(query, key.transpose(-2, -1))
44
+ .mul(scale_factor)
45
+ .softmax(dim=-1)
46
+ .matmul(value)
47
+ )
48
+
49
+
50
+ def _sfdp_replacement_2(query, key, value, scale_factor):
51
+ counters["inductor"]["fuse_attention"] += 1
52
+ return aten.scaled_dot_product_attention(
53
+ query.contiguous(),
54
+ key.contiguous(),
55
+ value.contiguous(),
56
+ attn_mask=None,
57
+ dropout_p=0.0,
58
+ is_causal=False,
59
+ scale=scale_factor,
60
+ )
61
+
62
+
63
+ def _sfdp_pattern_3(query, key, value, inv_scale_factor, dropout_p):
64
+ return torch.nn.functional.dropout(
65
+ torch.matmul(query, key.transpose(-2, -1))
66
+ .div(inv_scale_factor)
67
+ .softmax(dim=-1),
68
+ p=dropout_p,
69
+ ).matmul(value)
70
+
71
+
72
+ def _sfdp_replacement_3(query, key, value, inv_scale_factor, dropout_p):
73
+ counters["inductor"]["fuse_attention"] += 1
74
+ return aten.scaled_dot_product_attention(
75
+ query.contiguous(),
76
+ key.contiguous(),
77
+ value.contiguous(),
78
+ attn_mask=None,
79
+ dropout_p=dropout_p,
80
+ is_causal=False,
81
+ scale=1.0 / inv_scale_factor,
82
+ )
83
+
84
+
85
+ def _sfdp_pattern_4(query, key, value, scale_factor, dropout_p):
86
+ return torch.nn.functional.dropout(
87
+ torch.matmul(query, key.transpose(-2, -1)).mul(scale_factor).softmax(dim=-1),
88
+ p=dropout_p,
89
+ ).matmul(value)
90
+
91
+
92
+ def _sfdp_replacement_4(query, key, value, scale_factor, dropout_p):
93
+ counters["inductor"]["fuse_attention"] += 1
94
+ return aten.scaled_dot_product_attention(
95
+ query.contiguous(),
96
+ key.contiguous(),
97
+ value.contiguous(),
98
+ attn_mask=None,
99
+ dropout_p=dropout_p,
100
+ is_causal=False,
101
+ scale=scale_factor,
102
+ )
103
+
104
+
105
+ def _sfdp_pattern_5(query, key, value, attn_mask):
106
+ attn_weight = torch.softmax(
107
+ (query @ key.transpose(-2, -1) / math.sqrt(query.size(-1))) + attn_mask, dim=-1
108
+ )
109
+ # attn_weight = torch.dropout(attn_weight, dropout_p)
110
+ return attn_weight @ value
111
+
112
+
113
+ def _sfdp_replacement_5(query, key, value, attn_mask):
114
+ counters["inductor"]["fuse_attention"] += 1
115
+ return aten.scaled_dot_product_attention(
116
+ query.contiguous(),
117
+ key.contiguous(),
118
+ value.contiguous(),
119
+ attn_mask=attn_mask.to(dtype=query.dtype),
120
+ dropout_p=0.0,
121
+ is_causal=False,
122
+ )
123
+
124
+
125
+ def _sfdp_pattern_6(query, key, value, attn_mask, dropout_p):
126
+ attn_weight = torch.softmax(
127
+ (query @ key.transpose(-2, -1) / math.sqrt(query.size(-1))) + attn_mask, dim=-1
128
+ )
129
+ attn_weight = torch.dropout(attn_weight, dropout_p, True)
130
+ return attn_weight @ value
131
+
132
+
133
+ def _sfdp_replacement_6(query, key, value, attn_mask, dropout_p):
134
+ counters["inductor"]["fuse_attention"] += 1
135
+ return aten.scaled_dot_product_attention(
136
+ query.contiguous(),
137
+ key.contiguous(),
138
+ value.contiguous(),
139
+ attn_mask=attn_mask.to(dtype=query.dtype),
140
+ dropout_p=dropout_p,
141
+ is_causal=False,
142
+ )
143
+
144
+
145
+ def _sfdp_pattern_7(query, key, value, dropout_p):
146
+ # in real workloads inputs to matmul are permuted
147
+ # causing matmul to expand to a series of expand and clone calls
148
+ # we want the same to happen during pattern tracing
149
+ q = query.permute(0, 2, 1, 3)
150
+ k = key.permute(0, 2, 1, 3)
151
+ v = value.permute(0, 2, 1, 3)
152
+ div = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
153
+ div = div.to(torch.float32)
154
+ attn_weight = torch.softmax(div, dim=-1)
155
+ attn_weight = torch.dropout(attn_weight, dropout_p, True)
156
+ attn_weight = attn_weight.to(torch.float16)
157
+ return attn_weight @ v
158
+
159
+
160
+ def _sfdp_replacement_7(query, key, value, dropout_p):
161
+ # sdpa prefers inputs in permuted format
162
+ # it makes a copy to put them in this format
163
+ # if they aren't already
164
+ # to make replacement efficient ensure that inputs to sdpa
165
+ # are in required order
166
+ counters["inductor"]["fuse_attention"] += 1
167
+ q = query.permute(0, 2, 1, 3)
168
+ k = key.permute(0, 2, 1, 3)
169
+ v = value.permute(0, 2, 1, 3)
170
+ return aten.scaled_dot_product_attention(
171
+ q,
172
+ k,
173
+ v,
174
+ attn_mask=None, # attn_mask,
175
+ dropout_p=dropout_p,
176
+ is_causal=False,
177
+ )
178
+
179
+
180
+ def _sfdp_pattern_8(query, key, value):
181
+ # no dropout version of pattern 7
182
+ q = query.permute(0, 2, 1, 3)
183
+ k = key.permute(0, 2, 1, 3)
184
+ v = value.permute(0, 2, 1, 3)
185
+ div = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
186
+ div = div.to(torch.float32)
187
+ attn_weight = torch.softmax(div, dim=-1)
188
+ attn_weight = attn_weight.to(torch.float16)
189
+ return attn_weight @ v
190
+
191
+
192
+ def _sfdp_replacement_8(query, key, value):
193
+ counters["inductor"]["fuse_attention"] += 1
194
+ q = query.permute(0, 2, 1, 3)
195
+ k = key.permute(0, 2, 1, 3)
196
+ v = value.permute(0, 2, 1, 3)
197
+ return aten.scaled_dot_product_attention(
198
+ q,
199
+ k,
200
+ v,
201
+ attn_mask=None, # attn_mask,
202
+ dropout_p=0.0,
203
+ is_causal=False,
204
+ )
205
+
206
+
207
+ def _sfdp_pattern_9(query, key, value, dropout_p):
208
+ q = query.permute(0, 2, 1, 3)
209
+ k = key.permute(0, 2, 1, 3)
210
+ v = value.permute(0, 2, 1, 3)
211
+ q = q / math.sqrt(q.size(-1))
212
+ div = q @ k.transpose(-2, -1)
213
+ div = div.to(torch.float32)
214
+ attn_weight = torch.softmax(div, dim=-1)
215
+ attn_weight = torch.dropout(attn_weight, dropout_p, True)
216
+ attn_weight = attn_weight.to(torch.float16)
217
+ return attn_weight @ v
218
+
219
+
220
+ def _sfdp_replacement_9(query, key, value, dropout_p):
221
+ counters["inductor"]["fuse_attention"] += 1
222
+ q = query.permute(0, 2, 1, 3)
223
+ k = key.permute(0, 2, 1, 3)
224
+ v = value.permute(0, 2, 1, 3)
225
+ return aten.scaled_dot_product_attention(
226
+ q,
227
+ k,
228
+ v,
229
+ attn_mask=None, # attn_mask,
230
+ dropout_p=dropout_p,
231
+ is_causal=False,
232
+ )
233
+
234
+
235
+ def _sfdp_pattern_10(query, key, value):
236
+ # no dropout version of 9
237
+ q = query.permute(0, 2, 1, 3)
238
+ k = key.permute(0, 2, 1, 3)
239
+ v = value.permute(0, 2, 1, 3)
240
+ q = q / math.sqrt(q.size(-1))
241
+ div = q @ k.transpose(-2, -1)
242
+ div = div.to(torch.float32)
243
+ attn_weight = torch.softmax(div, dim=-1)
244
+ attn_weight = attn_weight.to(torch.float16)
245
+ return attn_weight @ v
246
+
247
+
248
+ def _sfdp_replacement_10(query, key, value):
249
+ counters["inductor"]["fuse_attention"] += 1
250
+ q = query.permute(0, 2, 1, 3)
251
+ k = key.permute(0, 2, 1, 3)
252
+ v = value.permute(0, 2, 1, 3)
253
+ return aten.scaled_dot_product_attention(
254
+ q,
255
+ k,
256
+ v,
257
+ attn_mask=None, # attn_mask,
258
+ dropout_p=0.0,
259
+ is_causal=False,
260
+ )
261
+
262
+
263
+ def _sfdp_pattern_11(query, key, value, inv_scale):
264
+ # Mainly for huggingface models
265
+ q = query.permute(0, 2, 1, 3)
266
+ k = key.permute(0, 2, 1, 3)
267
+ v = value.permute(0, 2, 1, 3)
268
+ return torch.matmul(q, k.transpose(-2, -1)).div(inv_scale).softmax(dim=-1).matmul(v)
269
+
270
+
271
+ def _sfdp_replacement_11(query, key, value, inv_scale):
272
+ counters["inductor"]["fuse_attention"] += 1
273
+ return aten.scaled_dot_product_attention(
274
+ query.transpose(1, 2),
275
+ key.transpose(1, 2),
276
+ value.transpose(1, 2),
277
+ attn_mask=None,
278
+ dropout_p=0.0,
279
+ is_causal=False,
280
+ scale=1.0 / inv_scale,
281
+ )
282
+
283
+
284
+ def _sfdp_pattern_12(query, key, value, inv_scale_factor, dropout_p):
285
+ q = query.permute(0, 2, 1, 3)
286
+ k = key.permute(0, 2, 1, 3)
287
+ v = value.permute(0, 2, 1, 3)
288
+ return torch.nn.functional.dropout(
289
+ torch.matmul(q, k.transpose(-2, -1)).div(inv_scale_factor).softmax(dim=-1),
290
+ p=dropout_p,
291
+ ).matmul(v)
292
+
293
+
294
+ def _sfdp_replacement_12(query, key, value, inv_scale_factor, dropout_p):
295
+ counters["inductor"]["fuse_attention"] += 1
296
+ return aten.scaled_dot_product_attention(
297
+ query.transpose(1, 2),
298
+ key.transpose(1, 2),
299
+ value.transpose(1, 2),
300
+ attn_mask=None,
301
+ dropout_p=dropout_p,
302
+ is_causal=False,
303
+ scale=1.0 / inv_scale_factor,
304
+ )
305
+
306
+
307
+ def _sfdp_pattern_13(query, key, value, dropout_p):
308
+ attn_weight = torch.bmm(query, key.transpose(1, 2)).softmax(dim=-1)
309
+ attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p)
310
+ return torch.bmm(attn_weight, value)
311
+
312
+
313
+ def _sfdp_replacement_13(query, key, value, dropout_p):
314
+ counters["inductor"]["fuse_attention"] += 1
315
+ return aten.scaled_dot_product_attention(
316
+ query.unsqueeze(0),
317
+ key.unsqueeze(0),
318
+ value.unsqueeze(0),
319
+ dropout_p=dropout_p,
320
+ scale=1.0,
321
+ ).squeeze(0)
322
+
323
+
324
+ def _sfdp_params_check(match):
325
+ assert all(k in match.kwargs for k in ("query", "key", "value"))
326
+ query = match.kwargs["query"].meta["val"]
327
+ key = match.kwargs["key"].meta["val"]
328
+ value = match.kwargs["value"].meta["val"]
329
+ if not (query.dtype == key.dtype == value.dtype) or not (
330
+ query.device == key.device == value.device
331
+ ):
332
+ return False
333
+ add_mask_node = filter_nodes(match.nodes, aten.add.Tensor)
334
+ # Has attn_mask add.
335
+ if len(add_mask_node) > 0:
336
+ attn_mask_node = add_mask_node[0].args[1]
337
+ # attn_mask_node may be a float/int number.
338
+ if not hasattr(attn_mask_node, "meta"):
339
+ return False
340
+ attn_mask = attn_mask_node.meta["val"]
341
+ # Make sure attn_mask.dtype == query.dtype or attn_mask.dtype == torch.bool
342
+ if (
343
+ not isinstance(attn_mask, torch.Tensor)
344
+ or not (attn_mask.dtype == query.dtype or attn_mask.dtype == torch.bool)
345
+ or query.device != attn_mask.device
346
+ ):
347
+ return False
348
+ return True
349
+
350
+
351
+ def _sfdp_scale_factor_check(scale_factor_op):
352
+ def fn(match):
353
+ scale_factor_node = filter_nodes(match.nodes, scale_factor_op)[0]
354
+ # Note: args[1] of the scale_factor_node is always the scale_factor for the current patterns.
355
+ scale_factor = scale_factor_node.args[1]
356
+ # make sure the scale_factor a float/int. SymInt?
357
+ if not isinstance(scale_factor, (float, int)):
358
+ return False
359
+ return _sfdp_params_check(match)
360
+
361
+ return fn
362
+
363
+
364
+ def partialize_and_update_signature(func, **kwargs):
365
+ """
366
+ Equivalent to functools.partial but also updates the signature on returned function
367
+ """
368
+ original_sig = inspect.signature(func)
369
+ parameters = original_sig.parameters
370
+
371
+ new_parameters = {
372
+ key: value for key, value in parameters.items() if key not in kwargs
373
+ }
374
+ new_sig = inspect.Signature(parameters=list(new_parameters.values()))
375
+
376
+ partial_func = functools.partial(func, **kwargs)
377
+
378
+ def wrapper(*args, **kwargs):
379
+ return partial_func(*args, **kwargs)
380
+
381
+ wrapper.__signature__ = new_sig # type: ignore[attr-defined]
382
+ wrapper.__name__ = func.__name__
383
+
384
+ return wrapper
385
+
386
+
387
+ def _get_sfdp_patterns():
388
+ from .joint_graph import patterns
389
+
390
+ if torch.cuda.is_available():
391
+ # workaround https://github.com/pytorch/pytorch/issues/97894
392
+ device = "cuda"
393
+ else:
394
+ device = "cpu"
395
+
396
+ # sizes/values don't actually matter for initial trace
397
+ # once we get a possible match we re-trace with the actual values and verify the match still holds
398
+ g_inp = functools.partial(
399
+ torch.empty, (2, 4, 8, 16), device=device, requires_grad=True
400
+ )
401
+ b_inp = functools.partial(torch.empty, (1, 1, 8, 8), device=device)
402
+ c_inp = functools.partial(torch.tensor, 2.0, device=device)
403
+ # workaround https://github.com/pytorch/pytorch/issues/97894
404
+ # 0.113377 is a "magic" value that lets us recover the lost input arg relationship
405
+ d = {"dropout_p": 0.113377}
406
+
407
+ # we could also generate all these patterns in 3d.. TODO
408
+ g_3d_inp = functools.partial(
409
+ torch.empty, (1024, 128, 128), device=device, requires_grad=True
410
+ )
411
+
412
+ # softmax will generate a dtype conversion on inputs if they are in half,
413
+ # but will not in float, so we generate a pattern for both
414
+ for dtype in [torch.float, torch.half]:
415
+ g = functools.partial(g_inp, dtype=dtype)
416
+ b = functools.partial(b_inp, dtype=dtype)
417
+ c = functools.partial(c_inp, dtype=dtype)
418
+ g_3d = functools.partial(g_3d_inp, dtype=dtype)
419
+
420
+ for pattern, replacement, args, workaround, extra_check in [
421
+ (
422
+ _sfdp_pattern_1,
423
+ _sfdp_replacement_1,
424
+ [g(), g(), g(), c()],
425
+ {},
426
+ _sfdp_scale_factor_check(aten.div.Tensor),
427
+ ),
428
+ (
429
+ _sfdp_pattern_2,
430
+ _sfdp_replacement_2,
431
+ [g(), g(), g(), c()],
432
+ {},
433
+ _sfdp_scale_factor_check(aten.mul.Tensor),
434
+ ),
435
+ (
436
+ _sfdp_pattern_3,
437
+ _sfdp_replacement_3,
438
+ [g(), g(), g(), c()],
439
+ d,
440
+ _sfdp_scale_factor_check(aten.div.Tensor),
441
+ ),
442
+ (
443
+ _sfdp_pattern_4,
444
+ _sfdp_replacement_4,
445
+ [g(), g(), g(), c()],
446
+ d,
447
+ _sfdp_scale_factor_check(aten.mul.Tensor),
448
+ ),
449
+ (
450
+ _sfdp_pattern_5,
451
+ _sfdp_replacement_5,
452
+ [g(), g(), g(), b()],
453
+ {},
454
+ _sfdp_params_check,
455
+ ),
456
+ (
457
+ _sfdp_pattern_6,
458
+ _sfdp_replacement_6,
459
+ [g(), g(), g(), b()],
460
+ d,
461
+ _sfdp_params_check,
462
+ ),
463
+ (
464
+ _sfdp_pattern_7,
465
+ _sfdp_replacement_7,
466
+ [g(), g(), g()],
467
+ d,
468
+ _sfdp_params_check,
469
+ ),
470
+ (
471
+ _sfdp_pattern_8,
472
+ _sfdp_replacement_8,
473
+ [g(), g(), g()],
474
+ {},
475
+ _sfdp_params_check,
476
+ ),
477
+ (
478
+ _sfdp_pattern_9,
479
+ _sfdp_replacement_9,
480
+ [g(), g(), g()],
481
+ d,
482
+ _sfdp_params_check,
483
+ ),
484
+ (
485
+ _sfdp_pattern_10,
486
+ _sfdp_replacement_10,
487
+ [g(), g(), g()],
488
+ {},
489
+ _sfdp_params_check,
490
+ ),
491
+ (
492
+ _sfdp_pattern_11,
493
+ _sfdp_replacement_11,
494
+ [g(), g(), g(), c()],
495
+ {},
496
+ _sfdp_scale_factor_check(aten.div.Tensor),
497
+ ),
498
+ (
499
+ _sfdp_pattern_12,
500
+ _sfdp_replacement_12,
501
+ [g(), g(), g(), c()],
502
+ d,
503
+ _sfdp_scale_factor_check(aten.div.Tensor),
504
+ ),
505
+ (
506
+ _sfdp_pattern_13,
507
+ _sfdp_replacement_13,
508
+ [g_3d(), g_3d(), g_3d()],
509
+ d,
510
+ _sfdp_params_check,
511
+ ),
512
+ ]:
513
+ # XXX: when adding a new pattern, re-run `gen_attention_patterns` so the pattern
514
+ # gets serialized to a python file and does not require tracing at runtime.
515
+ assert isinstance(workaround, dict)
516
+ name = pattern.__name__
517
+
518
+ training_name = (
519
+ f"{name}_training" if dtype == torch.float else f"{name}_training_half"
520
+ )
521
+ yield training_name, {
522
+ "search_fn": pattern,
523
+ "replace_fn": replacement,
524
+ "example_inputs": args,
525
+ "trace_fn": joint_fwd_bwd,
526
+ "pass_dicts": patterns,
527
+ "extra_check": extra_check,
528
+ "scalar_workaround": workaround,
529
+ }
530
+
531
+ if workaround:
532
+ assert len(workaround) == 1 and "dropout_p" in workaround
533
+ # functools.partial insufficient because we look at signature downstream
534
+ pattern = partialize_and_update_signature(pattern, dropout_p=0.0)
535
+ replacement = partialize_and_update_signature(
536
+ replacement, dropout_p=0.0
537
+ )
538
+ workaround = {}
539
+
540
+ inference_name = (
541
+ f"{name}_inference"
542
+ if dtype == torch.float
543
+ else f"{name}_inference_half"
544
+ )
545
+ yield inference_name, {
546
+ "search_fn": pattern,
547
+ "replace_fn": replacement,
548
+ "example_inputs": args,
549
+ "trace_fn": fwd_only,
550
+ "pass_dicts": patterns,
551
+ "extra_check": extra_check,
552
+ "scalar_workaround": workaround,
553
+ }
554
+
555
+
556
+ @functools.lru_cache(None)
557
+ def _sfdp_init():
558
+ from .serialized_patterns.central_index import get_serialized_pattern
559
+
560
+ for key, register_replacement_kwargs in _get_sfdp_patterns():
561
+ search_fn_pattern = get_serialized_pattern(key)
562
+ register_replacement(
563
+ **register_replacement_kwargs, search_fn_pattern=search_fn_pattern
564
+ )
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/group_batch_fusion.py ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import logging
3
+ import operator
4
+ from typing import Any, DefaultDict, Deque, Dict, Iterator, List, Optional, Set, Tuple
5
+
6
+ import torch
7
+ from torch._dynamo.utils import counters
8
+ from torch._utils_internal import print_graph
9
+
10
+ from .. import config
11
+ from ..pattern_matcher import (
12
+ CallFunctionVarArgs,
13
+ get_arg_value,
14
+ stable_topological_sort,
15
+ )
16
+
17
+ try:
18
+ # importing this will register fbgemm lowerings for inductor
19
+ import deeplearning.fbgemm.fbgemm_gpu.fb.inductor_lowerings # noqa: F401
20
+
21
+ has_fbgemm = True
22
+ except Exception:
23
+ has_fbgemm = False
24
+ pass
25
+
26
+ aten = torch.ops.aten
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ MIN_FUSE_SET_SIZE = 5
31
+ MAX_FUSE_SET_SIZE = 300
32
+ MAX_FUSE_SEARCH_DEPTH = 5
33
+ # The maximum tensor size that can go into the fusion group
34
+ MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR = 4096
35
+
36
+ # exclude these nodes from BFS
37
+ # excluding get item improves optimizer compilation time by 60s
38
+ SEARCH_EXCLUSIONS = {operator.getitem}
39
+
40
+
41
+ default_graph_search_options = {
42
+ "min_fuse_set_size": MIN_FUSE_SET_SIZE,
43
+ "max_fuse_set_size": MAX_FUSE_SET_SIZE,
44
+ "max_fuse_search_depth": MAX_FUSE_SEARCH_DEPTH,
45
+ "max_fuse_tensor_size_group_linear": MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR,
46
+ }
47
+
48
+ graph_search_options = default_graph_search_options
49
+
50
+
51
+ class GroupBatchFusionBase:
52
+ def __init__(self, **kwargs):
53
+ self.graph_search_options = kwargs.pop(
54
+ "graph_search_options", default_graph_search_options
55
+ )
56
+
57
+ def match(self, node):
58
+ raise NotImplementedError("match called on base")
59
+
60
+ def fuse(self, graph, subset):
61
+ raise NotImplementedError("fuse called on base")
62
+
63
+
64
+ PRE_GRAD_FUSIONS: Dict[str, GroupBatchFusionBase] = dict()
65
+ POST_GRAD_FUSIONS: Dict[str, GroupBatchFusionBase] = dict()
66
+
67
+
68
+ def register_fusion(name: str, pre_grad=True):
69
+ def decorator(fusion_cls: GroupBatchFusionBase):
70
+ if pre_grad:
71
+ PRE_GRAD_FUSIONS[name] = fusion_cls
72
+ else:
73
+ POST_GRAD_FUSIONS[name] = fusion_cls
74
+ return fusion_cls
75
+
76
+ return decorator
77
+
78
+
79
+ def list_group_batch_fusions(pre_grad=True) -> List[str]:
80
+ if pre_grad:
81
+ return list(PRE_GRAD_FUSIONS.keys())
82
+ else:
83
+ return list(POST_GRAD_FUSIONS.keys())
84
+
85
+
86
+ def decompose_stack(graph: torch.fx.GraphModule, input_tensors: List[Any]) -> Any:
87
+ unsqueezed_inputs = []
88
+ for input_tensor in input_tensors:
89
+ unsqueezed_input = graph.call_function(aten.unsqueeze, args=(input_tensor, 0))
90
+ unsqueezed_inputs.append(unsqueezed_input)
91
+ stacked_inputs = graph.call_function(
92
+ aten.cat,
93
+ args=(unsqueezed_inputs, 0),
94
+ )
95
+ return stacked_inputs
96
+
97
+
98
+ class GroupFusion(GroupBatchFusionBase):
99
+ """
100
+ Fuse ops in a group way, e.g, fuse mm/addmm of arbitrary input shapes with fbgemm.gmm.
101
+ """
102
+
103
+ pass
104
+
105
+
106
+ class BatchFusion(GroupBatchFusionBase):
107
+ """
108
+ Fuse ops in a batch way, e.g, fuse mm/addmm of same input shapes with bmm.
109
+ """
110
+
111
+ pass
112
+
113
+
114
+ class BatchPointwiseOpsFusionFactory(BatchFusion):
115
+ def __init__(self, op, **kwargs):
116
+ super().__init__(**kwargs)
117
+ self.op = op
118
+
119
+
120
+ @register_fusion("batch_linear_post_grad", pre_grad=False)
121
+ class PostGradBatchLinearFusion(BatchFusion):
122
+ """
123
+ Fuse ops in a batch way in post grad (aten level).
124
+ """
125
+
126
+ def _addmm_node_can_be_fused(self, node: torch.fx.Node) -> bool:
127
+ return (
128
+ node.kwargs.get("beta", 1.0) == 1.0 and node.kwargs.get("alpha", 1.0) == 1.0
129
+ )
130
+
131
+ def _is_input_2d(self, input: torch.fx.Node) -> bool:
132
+ return len(input.meta["tensor_meta"].shape) == 2
133
+
134
+ def match(self, node: torch.fx.Node) -> Optional[Tuple[str, int, int, int, bool]]:
135
+ if CallFunctionVarArgs(aten.mm).match(node):
136
+ input_m, weight_m = node.args
137
+ bias_m = None
138
+
139
+ elif CallFunctionVarArgs(aten.addmm.default).match(
140
+ node
141
+ ) and self._addmm_node_can_be_fused(node):
142
+ bias_m, input_m, weight_m = node.args
143
+ else:
144
+ return None
145
+
146
+ # only handle the cases where inputs are 2D tensors
147
+ if not self._is_input_2d(input_m) or not self._is_input_2d(weight_m):
148
+ return None
149
+ m, k = input_m.meta["tensor_meta"].shape
150
+ n = weight_m.meta["tensor_meta"].shape[1]
151
+ batch_key = ("batch_linear", m, k, n, bias_m is not None)
152
+ return batch_key
153
+
154
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
155
+ batch_inputs = []
156
+ batch_weights = []
157
+ batch_biases = []
158
+ batch_nodes = []
159
+
160
+ for node in subset:
161
+ if CallFunctionVarArgs(aten.addmm.default).match(node):
162
+ bias, input, weight = node.args
163
+ elif CallFunctionVarArgs(aten.mm.default).match(node):
164
+ input, weight = node.args
165
+ bias = None
166
+ batch_nodes.append(node)
167
+ batch_inputs.append(input)
168
+ batch_weights.append(weight)
169
+ batch_biases.append(bias)
170
+
171
+ with graph.inserting_before(subset[-1]):
172
+ fused_inputs = decompose_stack(graph, batch_inputs)
173
+ fused_weights = decompose_stack(graph, batch_weights)
174
+ fused_bmm = graph.call_function(
175
+ aten.bmm,
176
+ args=(fused_inputs, fused_weights),
177
+ )
178
+
179
+ for i, original_mm in enumerate(batch_nodes):
180
+ has_bias = False
181
+ with graph.inserting_after(fused_bmm):
182
+ new_mm = graph.call_function(aten.select, args=((fused_bmm, 0, i)))
183
+ if batch_biases[i]:
184
+ has_bias = True
185
+ new_bias_add = graph.call_function(
186
+ aten.add, args=((batch_biases[i], new_mm))
187
+ )
188
+ new_mm_cont = new_bias_add if has_bias else new_mm
189
+ original_mm.replace_all_uses_with(new_mm_cont)
190
+ new_mm_cont.meta.update(original_mm.meta)
191
+ graph.erase_node(original_mm)
192
+
193
+
194
+ @register_fusion("group_linear", pre_grad=False)
195
+ class GroupLinearFusion(GroupFusion):
196
+ def _addmm_node_can_be_fused(self, node: torch.fx.Node):
197
+ input_shape = node.args[1].meta["tensor_meta"].shape
198
+ weight_shape = node.args[2].meta["tensor_meta"].shape
199
+ return (
200
+ node.kwargs.get("beta", 1.0) == 1.0
201
+ and node.kwargs.get("alpha", 1.0) == 1.0
202
+ and len(input_shape) == 2
203
+ and len(weight_shape) == 2
204
+ and all(x % 2 == 0 for x in input_shape + weight_shape)
205
+ and all(
206
+ shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"]
207
+ for shape in input_shape + weight_shape
208
+ )
209
+ )
210
+
211
+ def _mm_node_can_be_fused(self, node: torch.fx.Node):
212
+ input_shape = node.args[0].meta["tensor_meta"].shape
213
+ weight_shape = node.args[1].meta["tensor_meta"].shape
214
+ return (
215
+ len(input_shape) == 2
216
+ and len(weight_shape) == 2
217
+ and all(x % 2 == 0 for x in input_shape + weight_shape)
218
+ and all(
219
+ shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"]
220
+ for shape in input_shape + weight_shape
221
+ )
222
+ )
223
+
224
+ def match(self, node: torch.fx.Node) -> Optional[Tuple[str, bool]]:
225
+ if CallFunctionVarArgs(aten.mm.default).match(
226
+ node
227
+ ) and self._mm_node_can_be_fused(node):
228
+ group_key = ("group_linear", True)
229
+ elif CallFunctionVarArgs(aten.addmm.default).match(
230
+ node
231
+ ) and self._addmm_node_can_be_fused(node):
232
+ bias = node.args[0]
233
+ group_key = ("group_linear", bias is None)
234
+ else:
235
+ group_key = None
236
+ return group_key
237
+
238
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
239
+ group_inputs = []
240
+ group_weights = []
241
+ group_biases = []
242
+ group_nodes = []
243
+ for node in subset:
244
+ if CallFunctionVarArgs(aten.addmm.default).match(node):
245
+ bias, input, weight = node.args
246
+ else:
247
+ assert CallFunctionVarArgs(aten.mm.default).match(node)
248
+ input, weight = node.args
249
+ bias = None
250
+
251
+ group_nodes.append(node)
252
+ group_inputs.append(input)
253
+ group_weights.append(weight)
254
+ group_biases.append(bias)
255
+
256
+ if all(bias is None for bias in group_biases):
257
+ group_biases = None # type: ignore[assignment]
258
+ group_biases: Optional[List[Any]]
259
+
260
+ with graph.inserting_before(subset[0]):
261
+ fused_mm = graph.call_function(
262
+ torch.ops.fbgemm.gmm.default,
263
+ args=(group_inputs, group_weights, group_biases),
264
+ )
265
+
266
+ for i, original_mm in enumerate(group_nodes):
267
+ with graph.inserting_after(fused_mm):
268
+ new_mm = graph.call_function(operator.getitem, args=(fused_mm, i))
269
+ original_mm.replace_all_uses_with(new_mm)
270
+ new_mm.meta.update(original_mm.meta)
271
+ graph.erase_node(original_mm)
272
+
273
+
274
+ @register_fusion("batch_linear_lhs")
275
+ class BatchLinearLHSFusion(BatchFusion):
276
+ """
277
+ Batch linear left-hand side fusion. This pass tries to fuse the following patterns:
278
+
279
+ torch.nn.functional.linear(x, w1), linear(x, w2),... * linear(x, wn)
280
+ -> torch.mm(x, torch.cat([w1, w2,... * wn]).transpose(0, 1))
281
+
282
+ We have a separate pass to eliminate contiguous transpose in a generic way.
283
+ """
284
+
285
+ def match(self, node: torch.fx.Node) -> Optional[Tuple[str, bool, Any]]:
286
+ if CallFunctionVarArgs(torch.nn.functional.linear).match(
287
+ node
288
+ ) and is_linear_node_can_be_fused(node):
289
+ input = get_arg_value(node, 0, "input")
290
+ bias = get_arg_value(node, 2, "bias")
291
+ group_key = ("batch_linear_lhs", bias is None, input)
292
+ else:
293
+ group_key = None
294
+ return group_key
295
+
296
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
297
+ batch_nodes = []
298
+ batch_input = None
299
+ batch_weights = []
300
+ batch_biases = []
301
+ split_sections = []
302
+ for node in subset:
303
+ input = get_arg_value(node, 0, "input")
304
+ weight = get_arg_value(node, 1, "weight")
305
+ bias = get_arg_value(node, 2, "bias")
306
+ batch_nodes.append(node)
307
+ if batch_input is None:
308
+ batch_input = input
309
+ else:
310
+ assert batch_input is input
311
+ batch_weights.append(weight)
312
+ if bias:
313
+ batch_biases.append(bias)
314
+ split_sections.append(weight.meta["example_value"].shape[0])
315
+
316
+ with graph.inserting_before(subset[0]):
317
+ cat_weights = graph.call_function(
318
+ torch.cat, args=(batch_weights,), kwargs={"dim": 0}
319
+ )
320
+ transposed_weights = graph.call_function(
321
+ torch.transpose, args=(cat_weights, 0, 1)
322
+ )
323
+ if len(batch_biases) > 0:
324
+ cat_biases = graph.call_function(
325
+ torch.cat, args=(batch_biases,), kwargs={"dim": 0}
326
+ )
327
+ fused_lhs = graph.call_function(
328
+ torch.addmm,
329
+ args=(cat_biases, batch_input, transposed_weights),
330
+ )
331
+ else:
332
+ fused_lhs = graph.call_function(
333
+ torch.mm,
334
+ args=(batch_input, transposed_weights),
335
+ )
336
+ fused_lhs_list = graph.call_function(
337
+ torch.split, args=(fused_lhs, split_sections), kwargs={"dim": 1}
338
+ )
339
+
340
+ for i, node in enumerate(batch_nodes):
341
+ with graph.inserting_after(fused_lhs_list):
342
+ new_node = graph.call_function(
343
+ operator.getitem, args=(fused_lhs_list, i)
344
+ )
345
+ node.replace_all_uses_with(new_node)
346
+ new_node.meta.update(node.meta)
347
+ graph.erase_node(node)
348
+
349
+
350
+ def is_node_meta_valid(node: Optional[torch.fx.Node]):
351
+ if node is None:
352
+ return True
353
+ if "example_value" not in node.meta:
354
+ return False
355
+ return True
356
+
357
+
358
+ def is_linear_node_can_be_fused(node: torch.fx.Node):
359
+ input = get_arg_value(node, 0, "input")
360
+ weight = get_arg_value(node, 1, "weight")
361
+ return (
362
+ is_node_meta_valid(node)
363
+ and is_node_meta_valid(input)
364
+ and is_node_meta_valid(weight)
365
+ and len(input.meta["example_value"].shape) == 2
366
+ and len(weight.meta["example_value"].shape) == 2
367
+ )
368
+
369
+
370
+ @register_fusion("batch_linear")
371
+ class PreGradBatchLinearFusion(BatchFusion):
372
+ """
373
+ Batch linear fusion in pre grad pass.
374
+ Fuse linear with same size with torch.baddmm
375
+ """
376
+
377
+ def _getitem_args(self, getitem_node: torch.fx.Node):
378
+ if getitem_node.target != operator.__getitem__ or (
379
+ getitem_node.op != "call_function"
380
+ ):
381
+ return None
382
+ return getitem_node.args[0]
383
+
384
+ def match(self, node: torch.fx.Node):
385
+ if CallFunctionVarArgs(torch.nn.functional.linear).match(
386
+ node
387
+ ) and is_linear_node_can_be_fused(node):
388
+ input = get_arg_value(node, 0, "input")
389
+ weight = get_arg_value(node, 1, "weight")
390
+ bias = get_arg_value(node, 2, "bias")
391
+ group_key = (
392
+ "batch_linear_pre_grad",
393
+ self._getitem_args(input),
394
+ str(input.meta["example_value"].shape),
395
+ str(weight.meta["example_value"].shape),
396
+ bias is None,
397
+ )
398
+ else:
399
+ group_key = None
400
+ return group_key
401
+
402
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
403
+ batch_nodes = []
404
+ batch_inputs = []
405
+ batch_weights = []
406
+ batch_biases = []
407
+ for node in subset:
408
+ batch_nodes.append(node)
409
+ batch_inputs.append(get_arg_value(node, 0, "input"))
410
+ batch_weights.append(get_arg_value(node, 1, "weight"))
411
+ batch_biases.append(get_arg_value(node, 2, "bias"))
412
+
413
+ with graph.inserting_before(subset[0]):
414
+ stack_inputs = graph.call_function(
415
+ torch.stack, args=(batch_inputs,), kwargs={"dim": 0}
416
+ )
417
+ stack_weights = graph.call_function(
418
+ torch.stack, args=(batch_weights,), kwargs={"dim": 0}
419
+ )
420
+ transpose_weight = graph.call_function(
421
+ torch.transpose, args=(stack_weights, 1, 2)
422
+ )
423
+ if all(bias is None for bias in batch_biases):
424
+ bmm = graph.call_function(
425
+ torch.bmm,
426
+ args=(stack_inputs, transpose_weight),
427
+ )
428
+ else:
429
+ stack_biases = graph.call_function(
430
+ torch.stack, args=(batch_biases,), kwargs={"dim": 0}
431
+ )
432
+ unsqueeze_biases = graph.call_function(
433
+ torch.unsqueeze, args=(stack_biases, 1)
434
+ )
435
+ bmm = graph.call_function(
436
+ torch.baddbmm,
437
+ args=(unsqueeze_biases, stack_inputs, transpose_weight),
438
+ )
439
+
440
+ bmm = graph.call_function(torch.unbind, args=(bmm,), kwargs={"dim": 0})
441
+ for i, linear in enumerate(batch_nodes):
442
+ with graph.inserting_after(bmm):
443
+ getitem = graph.call_function(operator.getitem, args=(bmm, i))
444
+ linear.replace_all_uses_with(getitem)
445
+ getitem.meta.update(linear.meta)
446
+ graph.erase_node(linear)
447
+
448
+
449
+ @register_fusion("batch_layernorm")
450
+ class BatchLayernormFusion(BatchFusion):
451
+ """
452
+ Batch layer norm fusion in pre grad pass
453
+ """
454
+
455
+ def match(self, node: torch.fx.Node):
456
+ if CallFunctionVarArgs(torch.nn.functional.layer_norm).match(node):
457
+ input = get_arg_value(node, 0, "input")
458
+ weight = get_arg_value(node, 2, "weight")
459
+ bias = get_arg_value(node, 3, "bias")
460
+ group_key = (
461
+ (
462
+ "batch_layernorm",
463
+ str(input.meta["example_value"].shape),
464
+ str(weight.meta["example_value"].shape)
465
+ if weight is not None
466
+ else "",
467
+ str(bias.meta["example_value"].shape) if bias is not None else "",
468
+ str(get_arg_value(node, 1, "normalized_shape")),
469
+ str(get_arg_value(node, 4, "eps")),
470
+ )
471
+ if "example_value" in input.meta
472
+ and is_node_meta_valid(weight)
473
+ and is_node_meta_valid(bias)
474
+ else None
475
+ )
476
+ else:
477
+ group_key = None
478
+ return group_key
479
+
480
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
481
+ group_inputs = []
482
+ group_shapes = []
483
+ group_weights = []
484
+ group_biases = []
485
+ group_epss = []
486
+ group_nodes = []
487
+ for node in subset:
488
+ group_nodes.append(node)
489
+ group_inputs.append(get_arg_value(node, 0, "input"))
490
+ group_shapes.append(get_arg_value(node, 1, "normalized_shape"))
491
+ group_weights.append(get_arg_value(node, 2, "weight"))
492
+ group_biases.append(get_arg_value(node, 3, "bias"))
493
+ eps = get_arg_value(node, 4, "eps")
494
+ if eps is None:
495
+ eps = 1e-5
496
+ group_epss.append(eps)
497
+ stack_dim = -1 - len(group_shapes[-1])
498
+
499
+ if all(bias is None for bias in group_biases):
500
+ group_biases = None # type: ignore[assignment]
501
+ group_biases: Optional[List[Any]]
502
+ if all(weight is None for weight in group_weights):
503
+ group_weights = None # type: ignore[assignment]
504
+ group_weights: Optional[List[Any]]
505
+ assert all(
506
+ eps == group_epss[0] for eps in group_epss
507
+ ), "all epsilon values must be equal"
508
+
509
+ with graph.inserting_before(subset[0]):
510
+ stack_input = graph.call_function(
511
+ torch.stack, args=(group_inputs,), kwargs={"dim": stack_dim}
512
+ )
513
+ if group_weights is not None:
514
+ stack_weight = graph.call_function(
515
+ torch.stack, args=(group_weights,), kwargs={"dim": 0}
516
+ )
517
+ else:
518
+ stack_weight = None
519
+ if group_biases is not None:
520
+ stack_bias = graph.call_function(
521
+ torch.stack, args=(group_biases,), kwargs={"dim": 0}
522
+ )
523
+ else:
524
+ stack_bias = None
525
+
526
+ batch_layer_norm = graph.call_function(
527
+ torch.nn.functional.layer_norm,
528
+ args=(stack_input, group_shapes[-1]),
529
+ kwargs={"eps": group_epss[-1]},
530
+ )
531
+
532
+ if group_weights is not None and group_biases is not None:
533
+ batch_layer_norm = graph.call_function(
534
+ torch.addcmul, args=(stack_bias, stack_weight, batch_layer_norm)
535
+ )
536
+ elif group_weights is not None and group_biases is None:
537
+ batch_layer_norm = graph.call_function(
538
+ torch.mul, args=(stack_weight, batch_layer_norm)
539
+ )
540
+ elif group_weights is None and group_biases is not None:
541
+ batch_layer_norm = graph.call_function(
542
+ torch.add, args=(stack_bias, batch_layer_norm)
543
+ )
544
+
545
+ batch_layer_norm_unbind = graph.call_function(
546
+ torch.unbind,
547
+ args=(batch_layer_norm,),
548
+ kwargs={"dim": stack_dim},
549
+ )
550
+
551
+ for i, node in enumerate(group_nodes):
552
+ with graph.inserting_after(batch_layer_norm_unbind):
553
+ new_node = graph.call_function(
554
+ operator.getitem, args=(batch_layer_norm_unbind, i)
555
+ )
556
+ node.replace_all_uses_with(new_node)
557
+ new_node.meta.update(node.meta)
558
+ graph.erase_node(node)
559
+
560
+
561
+ class BatchPointwiseOpsPreGradFusion(BatchPointwiseOpsFusionFactory):
562
+ """
563
+ Batch poinwise ops (e.g., sigmoid, relu, tanh) fusion in pre grad pass.
564
+ We fuse it in random place, and the introduced stack node may be merged in split cat.
565
+ """
566
+
567
+ def __init__(self, op, **kwargs):
568
+ super().__init__(op, **kwargs)
569
+ self.op = op
570
+
571
+ def match(self, node: torch.fx.Node):
572
+ input = get_arg_value(node, 0, "input")
573
+ if CallFunctionVarArgs(self.op).match(node) and is_node_meta_valid(node):
574
+ # for relu op, we also use the inplace to construct the key
575
+ group_key = (
576
+ "batch_" + self.op.__name__.lower() + "_pre_grad",
577
+ str(input.meta["example_value"].shape),
578
+ str(node.kwargs.get("inplace", False)),
579
+ )
580
+ else:
581
+ group_key = None
582
+ return group_key
583
+
584
+ def fuse(self, graph: torch.fx.GraphModule, subset: List[torch.fx.Node]):
585
+ batch_nodes = []
586
+ batch_inputs = []
587
+
588
+ for node in subset:
589
+ batch_nodes.append(node)
590
+ batch_inputs.append(get_arg_value(node, 0, "input"))
591
+
592
+ with graph.inserting_before(subset[0]):
593
+ stack_inputs = graph.call_function(
594
+ torch.stack, args=(batch_inputs,), kwargs={"dim": 0}
595
+ )
596
+ if self.op == torch.nn.functional.relu:
597
+ batch_op = graph.call_function(
598
+ self.op,
599
+ args=(stack_inputs,),
600
+ kwargs={"inplace": subset[0].kwargs.get("inplace", False)},
601
+ )
602
+ else:
603
+ batch_op = graph.call_function(
604
+ self.op,
605
+ args=(stack_inputs,),
606
+ )
607
+ unbind_op = graph.call_function(
608
+ torch.unbind, args=(batch_op,), kwargs={"dim": 0}
609
+ )
610
+ for i, node in enumerate(batch_nodes):
611
+ with graph.inserting_after(unbind_op):
612
+ getitem = graph.call_function(operator.getitem, args=(unbind_op, i))
613
+ node.replace_all_uses_with(getitem)
614
+ getitem.meta.update(node.meta)
615
+ graph.erase_node(node)
616
+
617
+
618
+ @register_fusion("batch_tanh")
619
+ class BatchTanhPreGradFusion(BatchPointwiseOpsPreGradFusion):
620
+ def __init__(self, **kwargs):
621
+ super().__init__(torch.tanh, **kwargs)
622
+
623
+
624
+ @register_fusion("batch_sigmoid")
625
+ class BatchSigmoidPreGradFusion(BatchPointwiseOpsPreGradFusion):
626
+ def __init__(self, **kwargs):
627
+ super().__init__(torch.sigmoid, **kwargs)
628
+
629
+
630
+ @register_fusion("batch_relu")
631
+ class BatchReLuPreGradFusion(BatchPointwiseOpsPreGradFusion):
632
+ def __init__(self, **kwargs):
633
+ super().__init__(torch.nn.functional.relu, **kwargs)
634
+
635
+
636
+ def find_independent_subset_greedy(
637
+ node_list: List[torch.fx.Node],
638
+ graph_search_options: Dict[str, Any],
639
+ ) -> Iterator[List[torch.fx.Node]]:
640
+ """
641
+ Return a list of subset from node_list, all nodes in each subset are independent with each other and can be fused together.
642
+ The type of subset is list, so we can preserve node's order and benefit from split-cat elimination in later pass.
643
+ """
644
+ visited_node_set: Set[torch.fx.Node] = set()
645
+ dep_set: Set[torch.fx.Node] = set()
646
+
647
+ def find_dependent_nodes(src_node, cur_node):
648
+ for input_node in cur_node.all_input_nodes:
649
+ if input_node in node_list:
650
+ dep_set.add(input_node)
651
+
652
+ if input_node not in visited_node_set:
653
+ visited_node_set.add(input_node)
654
+ find_dependent_nodes(src_node, input_node)
655
+
656
+ while len(node_list) > 0:
657
+ subset: List[torch.fx.Node] = []
658
+ subset_deps: Set[torch.fx.Node] = set()
659
+
660
+ for node in node_list:
661
+ if len(subset) >= graph_search_options["max_fuse_set_size"]:
662
+ break
663
+
664
+ visited_node_set.clear()
665
+ dep_set.clear()
666
+
667
+ find_dependent_nodes(node, node)
668
+ if not dep_set.intersection(subset) and node not in subset_deps:
669
+ subset.append(node)
670
+ subset_deps.update(dep_set)
671
+
672
+ if len(subset) >= graph_search_options["min_fuse_set_size"]:
673
+ yield subset
674
+
675
+ next_round_node_list = [node for node in node_list if node not in subset]
676
+ node_list = next_round_node_list
677
+
678
+
679
+ def get_fusion_candidates(
680
+ rule: GroupBatchFusionBase, root_node: torch.fx.Node, fused_set: Set[torch.fx.Node]
681
+ ) -> DefaultDict[Any, List[torch.fx.Node]]:
682
+ """
683
+ Search fusion candidates for a specific rule using BFS starting from the root node.
684
+ We only search the subgraph within graph_search_options["max_fuse_search_depth"].
685
+ """
686
+ q: Deque[Tuple[int, torch.fx.Node]] = collections.deque()
687
+
688
+ candidate_dict: DefaultDict[Any, List[torch.fx.Node]] = collections.defaultdict(
689
+ list
690
+ )
691
+
692
+ if root_node.target in SEARCH_EXCLUSIONS:
693
+ return candidate_dict
694
+
695
+ visited_set: Set[torch.fx.Node] = set()
696
+
697
+ for next_node in root_node.all_input_nodes:
698
+ q.append((1, next_node))
699
+ visited_set.add(next_node)
700
+
701
+ while len(q) > 0:
702
+ depth, node = q.popleft()
703
+
704
+ if node in fused_set:
705
+ continue
706
+
707
+ key = rule.match(node)
708
+ # SymInt is not hashable, so we need to skip it
709
+ if key is not None and not isinstance(key, torch.SymInt):
710
+ candidate_nodes = candidate_dict[key]
711
+ if node not in candidate_nodes:
712
+ candidate_nodes.append(node)
713
+ else:
714
+ if depth < rule.graph_search_options["max_fuse_search_depth"]:
715
+ for next_node in node.all_input_nodes:
716
+ if next_node not in visited_set:
717
+ visited_set.add(next_node)
718
+ q.append((depth + 1, next_node))
719
+
720
+ return candidate_dict
721
+
722
+
723
+ def apply_group_batch_fusion(graph: torch.fx.GraphModule, rule: GroupBatchFusionBase):
724
+ stable_topological_sort(graph)
725
+ fused_set: Set[torch.fx.Node] = set()
726
+
727
+ for node in reversed(graph.nodes):
728
+ candidates = get_fusion_candidates(rule, node, fused_set)
729
+
730
+ for key, candidate_nodes in candidates.items():
731
+ if len(candidate_nodes) < MIN_FUSE_SET_SIZE:
732
+ continue
733
+
734
+ for subset in find_independent_subset_greedy(
735
+ candidate_nodes, rule.graph_search_options
736
+ ):
737
+ rule.fuse(graph, subset)
738
+ fused_set.update(subset)
739
+ if isinstance(rule, GroupFusion):
740
+ counters["inductor"]["group_fusion"] += 1
741
+ elif isinstance(rule, BatchFusion):
742
+ counters["inductor"]["batch_fusion"] += 1
743
+ else:
744
+ counters["inductor"]["unknown_group_batch_fusion"] += 1
745
+
746
+ log.info(
747
+ f"{rule.__class__.__name__}: key = {key}; subset size = {len(subset)}" # noqa: G004
748
+ )
749
+
750
+
751
+ def generate_fusion_from_config(config_options: Dict[str, Any], pre_grad=True):
752
+ fusions: List[GroupBatchFusionBase] = []
753
+ for name, options in config_options.items():
754
+ fusion_cls = PRE_GRAD_FUSIONS[name] if pre_grad else POST_GRAD_FUSIONS[name]
755
+ _options = graph_search_options.copy()
756
+ _options.update(options)
757
+ fusions.append(fusion_cls(graph_search_options=_options)) # type: ignore[operator]
758
+ return fusions
759
+
760
+
761
+ def group_batch_fusion_passes(graph: torch.fx.Graph, pre_grad=True):
762
+ print_graph(graph, "Before group_batch fusion in pre grad pass.")
763
+ fusions: List[GroupBatchFusionBase] = []
764
+ # we keep all current pre grad fusions to keep
765
+ # current implementation, will remove this later
766
+ if pre_grad:
767
+ fusions += generate_fusion_from_config(
768
+ config.pre_grad_fusion_options, pre_grad=True
769
+ )
770
+ else:
771
+ fbgemm_fusion_keys = [
772
+ x
773
+ for x in config.post_grad_fusion_options
774
+ if config.post_grad_fusion_options[x].get("require_fbgemm", False)
775
+ ]
776
+ fbgemm_fusions = {
777
+ fusion: config.post_grad_fusion_options[fusion]
778
+ for fusion in fbgemm_fusion_keys
779
+ }
780
+ non_fbgemm_fusions = {
781
+ fusion: config.post_grad_fusion_options[fusion]
782
+ for fusion in config.post_grad_fusion_options.keys()
783
+ if fusion not in fbgemm_fusion_keys
784
+ }
785
+ fusions += generate_fusion_from_config(non_fbgemm_fusions, pre_grad=False)
786
+ if has_fbgemm:
787
+ fusions += generate_fusion_from_config(fbgemm_fusions, pre_grad=False)
788
+
789
+ for rule in fusions:
790
+ apply_group_batch_fusion(graph, rule)
791
+ print_graph(graph, f"Apply fusion {rule.__class__.__name__}.")
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/joint_graph.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import typing
3
+ from collections import Counter
4
+ from typing import Dict, Set
5
+
6
+ import torch
7
+ import torch._guards
8
+ from torch._inductor.constant_folding import ConstantFolder
9
+ from torch.multiprocessing.reductions import StorageWeakRef
10
+
11
+ from .. import config
12
+ from ..pattern_matcher import (
13
+ CallFunction,
14
+ init_once_fakemode,
15
+ KeywordArg,
16
+ Match,
17
+ PatternMatcherPass,
18
+ register_graph_pattern,
19
+ stable_topological_sort,
20
+ )
21
+ from .replace_random import replace_random_passes
22
+
23
+ log = logging.getLogger(__name__)
24
+ patterns = PatternMatcherPass()
25
+
26
+
27
+ @init_once_fakemode
28
+ def lazy_init():
29
+ from .fuse_attention import _sfdp_init
30
+ from .misc_patterns import _misc_patterns_init
31
+ from .pad_mm import _pad_mm_init
32
+
33
+ _pad_mm_init()
34
+ _sfdp_init()
35
+ _misc_patterns_init()
36
+
37
+
38
+ @torch.utils._python_dispatch._disable_current_modes()
39
+ def remove_no_ops(
40
+ gm: torch.fx.GraphModule, zeros: Set[torch.fx.Node], ones: Set[torch.fx.Node]
41
+ ):
42
+ "Removes no-ops: (+ 0, - 0, * 1, / 1)"
43
+ aten = torch.ops.aten
44
+ graph = gm.graph
45
+
46
+ def fake_tensors_eq(t1, t2, fields=("shape", "dtype", "device")):
47
+ if any(not isinstance(t, torch.Tensor) for t in (t1, t2)):
48
+ return False
49
+ for field in fields:
50
+ if getattr(t1, field) != getattr(t2, field):
51
+ return False
52
+ return True
53
+
54
+ def replace_no_op(node, replace_input_index):
55
+ replacement = node.args[replace_input_index]
56
+
57
+ # https://github.com/pytorch/pytorch/issues/86128 causes
58
+ # non-Tensor inputs even for ops with only Tensor inputs.
59
+ # TODO - decompose/type promote to avoid this
60
+ if not all(isinstance(arg, torch.fx.Node) for arg in node.args):
61
+ return
62
+
63
+ if not fake_tensors_eq(node.meta["val"], replacement.meta["val"]):
64
+ if fake_tensors_eq(
65
+ node.meta["val"],
66
+ replacement.meta["val"],
67
+ ("shape", "device"),
68
+ ):
69
+ with graph.inserting_after(node):
70
+ replacement = graph.call_function(
71
+ torch.ops.prims.convert_element_type.default,
72
+ args=(replacement, node.meta["val"].dtype),
73
+ )
74
+ else:
75
+ return
76
+
77
+ node.replace_all_uses_with(replacement)
78
+ replacement.meta.update(node.meta)
79
+ graph.erase_node(node)
80
+
81
+ for node in graph.nodes:
82
+ if node.op != "call_function":
83
+ continue
84
+
85
+ # TODO handle Tensor-Scalar adds, it's a different schema
86
+ if node.target == aten.add.Tensor and len(node.args) == 2:
87
+ if (
88
+ not any(e in zeros for e in node.args)
89
+ or node.kwargs.get("alpha", 1) != 1
90
+ ):
91
+ continue
92
+
93
+ replace_index = 1 if node.args[0] in zeros else 0
94
+ replace_no_op(node, replace_index)
95
+
96
+ elif node.target == aten.sub.Tensor and len(node.args) == 2:
97
+ if node.args[1] not in zeros or node.kwargs.get("alpha", 1) != 1:
98
+ continue
99
+
100
+ replace_no_op(node, 0)
101
+
102
+ elif node.target == aten.mul.Tensor and len(node.args) == 2:
103
+ if not any(e in ones for e in node.args):
104
+ continue
105
+
106
+ replace_input_index = 1 if node.args[0] in ones else 0
107
+ replace_no_op(node, replace_input_index)
108
+
109
+ elif (
110
+ node.target == aten.div.Tensor
111
+ and len(node.args) == 2
112
+ and node.args[1] in ones
113
+ ):
114
+ replace_no_op(node, 0)
115
+
116
+
117
+ @torch.utils._python_dispatch._disable_current_modes()
118
+ def remove_redundant_views(gm: torch.fx.GraphModule):
119
+ """
120
+ Removes redundant views by reusing existing ones.
121
+ """
122
+
123
+ # A dictionary mapping a tensor to all aliased views.
124
+ views: Dict[torch.fx.Node, Dict[torch.dtype, torch.fx.Node]] = {}
125
+ graph = gm.graph
126
+
127
+ for node in graph.nodes:
128
+ if node.op != "call_function":
129
+ continue
130
+
131
+ if node.target != torch.ops.aten.view.dtype:
132
+ continue
133
+
134
+ src = node.args[0]
135
+ to_type = node.args[1]
136
+ existing_views = views.get(src)
137
+ is_needed = True
138
+
139
+ if existing_views:
140
+ # Replace the view with the an existing view if available.
141
+ alias = existing_views.get(to_type)
142
+ if alias:
143
+ is_needed = False
144
+ node.replace_all_uses_with(alias)
145
+ alias.meta.update(node.meta)
146
+ graph.erase_node(node)
147
+ else:
148
+ from_type = src.meta["val"].dtype
149
+ existing_views = {from_type: src}
150
+ views[src] = existing_views
151
+
152
+ if is_needed:
153
+ # Save the new alias but do not replace existing one.
154
+ existing_views.setdefault(to_type, node)
155
+ views[node] = existing_views
156
+
157
+ # Clean up unused views.
158
+ while True:
159
+ unused_views = []
160
+ for alias in views:
161
+ if not alias.users:
162
+ unused_views.append(alias)
163
+ if len(unused_views) == 0:
164
+ break
165
+ for unused in unused_views:
166
+ views.pop(unused)
167
+ graph.erase_node(unused)
168
+
169
+
170
+ class UniformValueConstantFolder(ConstantFolder):
171
+ """
172
+ Runs constant folding and replaces tensors that have a unifrom value
173
+ with a tensor constructor call: aten.full([shape], value, ...)
174
+ """
175
+
176
+ def __init__(self, gm, skip_constructors=False):
177
+ super().__init__(gm, skip_constructors)
178
+ self.node_storages_ptrs: Dict[torch.fx.Node, int] = {}
179
+ self.constant_data_ptrs: Dict[torch.fx.Node, StorageWeakRef] = {}
180
+
181
+ def insertable_tensor_check(self, t: torch.Tensor) -> bool:
182
+ # TODO - we could also Tensors which get replaced with arange here
183
+ return (
184
+ t.numel() != 0
185
+ and bool((t == t.flatten()[0]).all())
186
+ and torch._C._has_storage(t)
187
+ and t.layout == torch.strided
188
+ )
189
+
190
+ def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None:
191
+ self.node_replacements[node] = tensor.flatten()[0].item()
192
+ self.constant_data_ptrs[node] = StorageWeakRef(tensor.untyped_storage())
193
+
194
+
195
+ @torch.utils._python_dispatch._disable_current_modes()
196
+ def constant_fold_uniform_value(gm: torch.fx.GraphModule):
197
+ "Runs constant folding and replaces constants which can be constructed with a single `full` call. Calls into remove_no_ops."
198
+ aten = torch.ops.aten
199
+
200
+ # Constant folding can leak memory, especially with repeated compilation, so we are only going to
201
+ # remove constants which can be replaced with a constructor.
202
+ cf = UniformValueConstantFolder(gm)
203
+ cf.run()
204
+
205
+ node_replacements = cf.node_replacements
206
+
207
+ graph = gm.graph
208
+
209
+ zeros = set()
210
+ ones = set()
211
+
212
+ # Got failures in `test_is_set_to_cuda` if we change aliasing on constants,
213
+ # so just constant-ify if a Tensor is unaliased
214
+ constant_data_ptr_count: typing.Counter[StorageWeakRef] = Counter()
215
+
216
+ for node in cf.node_replacements:
217
+ constant_data_ptr_count[cf.constant_data_ptrs[node]] += 1
218
+
219
+ for node, value in node_replacements.items():
220
+ # we dont have a functional way right now of instantiating a non-contiguous tensor with full/zeros/ones right now
221
+ # hasn't shown up to be important yet
222
+ fake_tensor = node.meta["val"]
223
+ if not fake_tensor.is_contiguous(memory_format=torch.contiguous_format):
224
+ continue
225
+
226
+ if constant_data_ptr_count[cf.constant_data_ptrs[node]] > 1:
227
+ continue
228
+
229
+ with graph.inserting_after(node):
230
+ # the conversion from tensor and back to value can be lossy, just use the original full ctor value
231
+ if (
232
+ node.op == "call_function"
233
+ and node.target == aten.full.default
234
+ and len(node.args) == 2
235
+ ):
236
+ value = node.args[1]
237
+
238
+ # zeros, and ones just get traced into full, so we insert those
239
+ new_node = graph.call_function(
240
+ aten.full.default,
241
+ args=(list(fake_tensor.shape), value),
242
+ kwargs={
243
+ "dtype": fake_tensor.dtype,
244
+ "layout": torch.strided,
245
+ "device": fake_tensor.device,
246
+ "pin_memory": False,
247
+ },
248
+ )
249
+
250
+ new_node.meta.update(node.meta)
251
+ node.replace_all_uses_with(new_node)
252
+ graph.erase_node(node)
253
+
254
+ if value == 0:
255
+ zeros.add(new_node)
256
+ elif value == 1:
257
+ ones.add(new_node)
258
+
259
+ remove_no_ops(gm, zeros, ones)
260
+ remove_redundant_views(gm)
261
+
262
+
263
+ def joint_graph_passes(graph: torch.fx.GraphModule):
264
+ """
265
+ Run FX transformations on the joint forwards+backwards graph.
266
+ """
267
+ lazy_init()
268
+ count = 0
269
+
270
+ if config.joint_graph_constant_folding:
271
+ constant_fold_uniform_value(graph)
272
+
273
+ if config.pattern_matcher:
274
+ count += patterns.apply(graph.graph)
275
+
276
+ if not config.fallback_random:
277
+ count += replace_random_passes(graph)
278
+
279
+ if count:
280
+ stable_topological_sort(graph.graph)
281
+ graph.graph.lint()
282
+ graph.recompile()
283
+ return graph
284
+
285
+
286
+ @register_graph_pattern(
287
+ CallFunction(
288
+ torch.ops.prims.convert_element_type.default,
289
+ CallFunction(
290
+ torch.ops.prims.convert_element_type.default,
291
+ KeywordArg("arg"),
292
+ KeywordArg("dtype1"),
293
+ ),
294
+ KeywordArg("dtype2"),
295
+ ),
296
+ pass_dict=patterns,
297
+ )
298
+ def pointless_convert(match: Match, arg, dtype1: torch.dtype, dtype2: torch.dtype):
299
+ """Remove chain of dtype conversions often created by AMP"""
300
+ graph = match.graph
301
+ node = match.output_node()
302
+ allowed = {torch.float16, torch.bfloat16, torch.float32, torch.float64}
303
+ if dtype1 in allowed and dtype2 in allowed:
304
+ repl = graph.call_function(
305
+ torch.ops.prims.convert_element_type.default, (arg, dtype2)
306
+ )
307
+ repl.meta.update(node.meta)
308
+ node.replace_all_uses_with(repl)
309
+ match.erase_nodes(graph)
310
+
311
+
312
+ @register_graph_pattern(
313
+ CallFunction(torch.ops.aten.view.default, KeywordArg("arg"), KeywordArg("size")),
314
+ pass_dict=patterns,
315
+ )
316
+ def pointless_view(match: Match, arg, size):
317
+ """Remove no-op view"""
318
+ graph = match.graph
319
+ node = match.output_node()
320
+ arg_size = list(node.args[0].meta["val"].shape)
321
+ if size == arg_size:
322
+ node.replace_all_uses_with(node.args[0])
323
+ match.erase_nodes(graph)
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/misc_patterns.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ from typing import Dict, Set, Tuple
4
+
5
+ import torch
6
+ from torch._dynamo.utils import counters
7
+
8
+ from torch._ops import OpOverload, OpOverloadPacket
9
+ from ..pattern_matcher import fwd_only, register_replacement
10
+
11
+ aten = torch.ops.aten
12
+
13
+
14
+ @functools.lru_cache(None)
15
+ def _misc_patterns_init():
16
+ from .joint_graph import patterns as joint_graph_patterns
17
+ from .post_grad import pass_patterns as post_grad_patterns_all
18
+
19
+ post_grad_patterns = post_grad_patterns_all[1] # medium priority
20
+
21
+ if torch.cuda.is_available():
22
+ # workaround https://github.com/pytorch/pytorch/issues/97894
23
+ device = "cuda"
24
+ else:
25
+ device = "cpu"
26
+
27
+ # These patterns do 2 things
28
+ # 1. Since we know that index is completely unique, we can codegen it using
29
+ # stores instead of atomic adds, which is quite a bit faster.
30
+ # 2. Also, since we are guaranteed that they are completely within bounds,
31
+ # we can use unsafe indexing and skip debug asserts
32
+ def randperm_index_add_pattern(x, y):
33
+ index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]]
34
+ return torch.index_add(x, dim=0, source=y, index=index), index
35
+
36
+ def randperm_index_add_replacement(x, y):
37
+ index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]]
38
+ return (
39
+ torch.ops.aten._unsafe_index_put(
40
+ x, (index,), aten._unsafe_index(x, (index,)) + y, accumulate=False
41
+ ),
42
+ index,
43
+ )
44
+
45
+ register_replacement(
46
+ randperm_index_add_pattern,
47
+ randperm_index_add_replacement,
48
+ [torch.empty(4, 8, device=device), torch.empty(2, 8, device=device)],
49
+ fwd_only,
50
+ [post_grad_patterns, joint_graph_patterns],
51
+ )
52
+
53
+ def randperm_index_pattern(x, slice_shape):
54
+ index = torch.randperm(x.shape[0], device=x.device)[:slice_shape]
55
+ return torch.ops.aten.index(x, (index,)), index
56
+
57
+ def randperm_index_replacement(x, slice_shape):
58
+ index = torch.randperm(x.shape[0], device=x.device)[:slice_shape]
59
+ return torch.ops.aten._unsafe_index(x, (index,)), index
60
+
61
+ pattern = register_replacement(
62
+ randperm_index_pattern,
63
+ randperm_index_replacement,
64
+ [torch.empty(4, 8, device=device)],
65
+ fwd_only,
66
+ [post_grad_patterns, joint_graph_patterns],
67
+ scalar_workaround={"slice_shape": 42},
68
+ )
69
+
70
+
71
+ class NumpyCompatNormalization:
72
+ numpy_compat: Dict[str, Tuple[str, ...]] = {
73
+ "dim": ("axis",),
74
+ "keepdim": ("keepdims",),
75
+ "input": ("x", "a", "x1"),
76
+ "other": ("x2",),
77
+ }
78
+ inverse_mapping: Dict[str, str]
79
+ cache: Dict["torch.fx.graph.Target", Set[str]]
80
+
81
+ def __init__(self):
82
+ self.cache = {} # callable -> tuple of replaceable args e.g. ["axis"]
83
+ self.inverse_mapping = {}
84
+ for actual_kwarg, numpy_kwargs in self.numpy_compat.items():
85
+ for numpy_kwarg in numpy_kwargs:
86
+ assert numpy_kwarg not in self.inverse_mapping
87
+ self.inverse_mapping[numpy_kwarg] = actual_kwarg
88
+
89
+ def __call__(self, graph: torch.fx.Graph):
90
+ for node in graph.nodes:
91
+ if node.op != "call_function":
92
+ continue
93
+ if isinstance(node.target, (OpOverload, OpOverloadPacket)):
94
+ # only applies to torch ops; e.g. torch.stack(axis=1) works, torch.ops.aten.stack(axis=1) doesn't.
95
+ continue
96
+ kwargs = node.kwargs
97
+
98
+ if node.target in self.cache:
99
+ replaceable_kwargs = self.cache[node.target]
100
+ else:
101
+ signatures = torch.fx.operator_schemas.get_signature_for_torch_op(
102
+ node.target
103
+ )
104
+ signatures = () if signatures is None else signatures
105
+ replaceable_kwargs = set()
106
+ for sig in signatures:
107
+ for param_name in sig.parameters.keys():
108
+ if param_name in self.numpy_compat:
109
+ replaceable_kwargs.update(self.numpy_compat[param_name])
110
+
111
+ self.cache[node.target] = replaceable_kwargs
112
+
113
+ if not replaceable_kwargs:
114
+ continue
115
+
116
+ new_kwargs = {}
117
+ kwargs_changed = False
118
+ for k, v in kwargs.items():
119
+ if k in replaceable_kwargs:
120
+ kwargs_changed = True
121
+ new_kwargs[self.inverse_mapping[k]] = v
122
+ else:
123
+ new_kwargs[k] = v
124
+
125
+ if kwargs_changed:
126
+ node.kwargs = torch.fx.immutable_collections.immutable_dict(new_kwargs)
127
+ counters["inductor"]["numpy_compat_normalization"] += 1
128
+
129
+
130
+ numpy_compat_normalization = NumpyCompatNormalization()
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/mkldnn_fusion.py ADDED
@@ -0,0 +1,1085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import operator
3
+ from functools import reduce
4
+ from typing import Any, Tuple
5
+
6
+ import torch
7
+
8
+ from torch.fx.experimental.symbolic_shapes import has_free_symbols
9
+
10
+ from .. import ir
11
+
12
+ from ..lowering import lowerings as L
13
+ from ..pattern_matcher import (
14
+ Arg,
15
+ CallFunction,
16
+ filter_nodes,
17
+ get_arg_value,
18
+ KeywordArg,
19
+ MULTIPLE,
20
+ )
21
+ from ..virtualized import ops
22
+ from .freezing_patterns import register_freezing_graph_pattern
23
+ from .post_grad import register_lowering_pattern
24
+ from .quantization import (
25
+ _register_quantization_lowerings,
26
+ _register_quantization_weight_pack_pass,
27
+ )
28
+
29
+ if torch._C._has_mkldnn:
30
+ aten = torch.ops.aten
31
+ mkldnn = torch.ops.mkldnn
32
+ prims = torch.ops.prims
33
+
34
+ _conv_args = [Arg() for _ in range(10)]
35
+ _linear_args = [Arg() for _ in range(6)]
36
+ _conv_transpose_args = [Arg() for _ in range(11)]
37
+
38
+ def _conv_call(users=1):
39
+ return CallFunction(
40
+ mkldnn._convolution_pointwise.default, *_conv_args, _users=users
41
+ )
42
+
43
+ def _linear_call(users=1):
44
+ return CallFunction(
45
+ mkldnn._linear_pointwise.default, *_linear_args, _users=users
46
+ )
47
+
48
+ def _conv_transpose_call(users=1):
49
+ return CallFunction(
50
+ mkldnn._convolution_transpose_pointwise.default,
51
+ *_conv_transpose_args,
52
+ _users=users,
53
+ )
54
+
55
+ def _to_float(input_call, users=1):
56
+ return CallFunction(
57
+ prims.convert_element_type.default,
58
+ input_call,
59
+ KeywordArg("to_float"),
60
+ _users=users,
61
+ )
62
+
63
+ def _to_bf16(input_call):
64
+ return CallFunction(
65
+ prims.convert_element_type.default,
66
+ input_call,
67
+ KeywordArg("to_bf16"),
68
+ _users=1,
69
+ )
70
+
71
+ def _unary_fusion_pattern(unary_fusion, call_fn, users, is_bf16):
72
+ # only insert to_dtype if is_bf16 is True
73
+ computation_call = (
74
+ _to_float(call_fn(), users=users) if is_bf16 else call_fn(users=users)
75
+ )
76
+ out = unary_fusion(computation_call)
77
+ return _to_bf16(out) if is_bf16 else out
78
+
79
+ def _gelu_fusion_1(computation_call):
80
+ return CallFunction(
81
+ aten.mul,
82
+ CallFunction(aten.mul, computation_call, 0.5),
83
+ CallFunction(
84
+ aten.add,
85
+ CallFunction(
86
+ aten.erf,
87
+ CallFunction(aten.mul, computation_call, 0.7071067811865476),
88
+ ),
89
+ 1,
90
+ ),
91
+ )
92
+
93
+ def _gelu_fusion_2(computation_call):
94
+ return CallFunction(
95
+ aten.mul,
96
+ CallFunction(aten.mul, computation_call, 0.5),
97
+ CallFunction(
98
+ aten.add,
99
+ CallFunction(
100
+ aten.tanh,
101
+ CallFunction(
102
+ aten.mul,
103
+ CallFunction(
104
+ aten.add,
105
+ computation_call,
106
+ CallFunction(
107
+ aten.mul,
108
+ CallFunction(
109
+ aten.mul,
110
+ CallFunction(
111
+ aten.mul, computation_call, computation_call
112
+ ),
113
+ computation_call,
114
+ ),
115
+ 0.044715,
116
+ ),
117
+ ),
118
+ 0.7978845608028654,
119
+ ),
120
+ ),
121
+ 1,
122
+ ),
123
+ )
124
+
125
+ def _hardswish_fusion(computation_call):
126
+ return CallFunction(
127
+ aten.div,
128
+ CallFunction(
129
+ aten.mul,
130
+ computation_call,
131
+ CallFunction(
132
+ aten.clamp_max,
133
+ CallFunction(
134
+ aten.clamp_min, CallFunction(aten.add, computation_call, 3), 0
135
+ ),
136
+ 6,
137
+ ),
138
+ ),
139
+ 6,
140
+ )
141
+
142
+ def _silu_fusion(computation_call):
143
+ return CallFunction(
144
+ aten.mul, computation_call, CallFunction(aten.sigmoid, computation_call)
145
+ )
146
+
147
+ def _hardsigmoid_fusion(computation_call):
148
+ return CallFunction(
149
+ aten.div,
150
+ CallFunction(
151
+ aten.clamp_max,
152
+ CallFunction(
153
+ aten.clamp_min, CallFunction(aten.add, computation_call, 3), 0
154
+ ),
155
+ 6,
156
+ ),
157
+ 6,
158
+ )
159
+
160
+ def _leaky_relu_fusion(computation_call):
161
+ return CallFunction(
162
+ aten.where,
163
+ CallFunction(aten.gt, computation_call, 0),
164
+ computation_call,
165
+ CallFunction(aten.mul, computation_call, KeywordArg("negative_slope")),
166
+ )
167
+
168
+ def _hardtanh_fusion(computation_call):
169
+ return CallFunction(
170
+ aten.clamp_max,
171
+ CallFunction(aten.clamp_min, computation_call, KeywordArg("min_value")),
172
+ KeywordArg("max_value"),
173
+ )
174
+
175
+ def _combined_fusion(computation_call, elementwise_op):
176
+ return CallFunction(elementwise_op, computation_call)
177
+
178
+ # binary_op(other, computation_op)
179
+ def _binary_fusion_v1(computation_call, binary_fn):
180
+ return CallFunction(binary_fn, KeywordArg("other"), computation_call)
181
+
182
+ # binary_op(computation_op, other)
183
+ def _binary_fusion_v2(computation_call, binary_fn):
184
+ return CallFunction(binary_fn, computation_call, KeywordArg("other"))
185
+
186
+ def _is_single_computation_op(computation_op):
187
+ def fn(match):
188
+ computation_nodes = filter_nodes(match.nodes, computation_op)
189
+ if len(computation_nodes) < 1:
190
+ return False
191
+ if any(n.args[-3] != "none" for n in computation_nodes):
192
+ return False
193
+ return True
194
+
195
+ return fn
196
+
197
+ def _is_valid_computation_unary_fusion(computation_op, is_bf16=False):
198
+ def fn(match):
199
+ matched = _is_single_computation_op(computation_op)(match)
200
+ computation_node = filter_nodes(match.nodes, computation_op)[0]
201
+ if is_bf16:
202
+ conversion_dtype_nodes = filter_nodes(
203
+ match.nodes, prims.convert_element_type.default
204
+ )
205
+ if len(conversion_dtype_nodes) != 2:
206
+ return False
207
+ # fusion pattern is always in the form of computation_op + to_float32 + unary_op + to_bfloat16
208
+ if computation_node == conversion_dtype_nodes[0].args[0]:
209
+ to_float = conversion_dtype_nodes[0].args[1]
210
+ to_bf16 = conversion_dtype_nodes[1].args[1]
211
+ else:
212
+ to_float = conversion_dtype_nodes[1].args[1]
213
+ to_bf16 = conversion_dtype_nodes[0].args[1]
214
+ matched = (
215
+ matched and to_float == torch.float and to_bf16 == torch.bfloat16
216
+ )
217
+ return matched
218
+
219
+ return fn
220
+
221
+ def _register_unary_fusion_lowering(
222
+ pattern, unary_attr, computation_op, is_bf16=False
223
+ ):
224
+ @register_lowering_pattern(
225
+ pattern,
226
+ extra_check=_is_valid_computation_unary_fusion(computation_op, is_bf16),
227
+ )
228
+ def fn(match, *args, **kwargs):
229
+ computation_args = list(args)[:-3] + [
230
+ unary_attr.op_name,
231
+ unary_attr.scalars_attr,
232
+ unary_attr.algorithm_attr,
233
+ ]
234
+ return L[computation_op](*computation_args)
235
+
236
+ return fn
237
+
238
+ def _register_leaky_relu_fusion_lowering(pattern, computation_op, is_bf16=False):
239
+ @register_lowering_pattern(
240
+ pattern, extra_check=_is_single_computation_op(computation_op)
241
+ )
242
+ def fn(match, *args, **kwargs):
243
+ negative_slope = kwargs.get("negative_slope")
244
+ if isinstance(negative_slope, ir.TensorBox):
245
+ matched = False
246
+ else: # inp is a Number
247
+ matched = True
248
+ if is_bf16:
249
+ dtype1 = kwargs.get("to_float")
250
+ dtype2 = kwargs.get("to_bf16")
251
+ matched = matched and dtype1 == torch.float and dtype2 == torch.bfloat16
252
+ computation_args = list(args)
253
+ if matched:
254
+ computation_args = computation_args[:-3] + [
255
+ "leaky_relu",
256
+ [negative_slope],
257
+ "",
258
+ ]
259
+ return L[computation_op](*computation_args)
260
+ else:
261
+ # computation_args += ["none", [], ""]
262
+ out = L[computation_op](*computation_args)
263
+ if is_bf16:
264
+ out = L[prims.convert_element_type.default](out, dtype=torch.float)
265
+ out = L[aten.where](
266
+ L[aten.gt](out, 0),
267
+ out,
268
+ L[aten.mul](out, negative_slope),
269
+ )
270
+ if is_bf16:
271
+ out = L[prims.convert_element_type.default](
272
+ out, dtype=torch.bfloat16
273
+ )
274
+ return out
275
+
276
+ return fn
277
+
278
+ def _register_hardtanh_fusion_lowering(pattern, computation_op, is_bf16=False):
279
+ @register_lowering_pattern(
280
+ pattern, extra_check=_is_single_computation_op(computation_op)
281
+ )
282
+ def fn(match, *args, **kwargs):
283
+ min_value = kwargs.get("min_value")
284
+ max_value = kwargs.get("max_value")
285
+ if isinstance(min_value, ir.TensorBox) or isinstance(
286
+ max_value, ir.TensorBox
287
+ ):
288
+ matched = False
289
+ else: # inp is a Number
290
+ assert max_value is not None
291
+ matched = min_value <= max_value
292
+ if is_bf16:
293
+ dtype1 = kwargs.get("to_float")
294
+ dtype2 = kwargs.get("to_bf16")
295
+ matched = matched and dtype1 == torch.float and dtype2 == torch.bfloat16
296
+ computation_args = list(args)
297
+ if matched:
298
+ computation_args = computation_args[:-3] + [
299
+ "hardtanh",
300
+ [min_value, max_value],
301
+ "",
302
+ ]
303
+ return L[computation_op](*computation_args)
304
+ else:
305
+ out = L[computation_op](*computation_args)
306
+ if is_bf16:
307
+ out = L[prims.convert_element_type.default](out, dtype=torch.float)
308
+ out = L[aten.clamp_max](L[aten.clamp_min](out, min_value), max_value)
309
+ if is_bf16:
310
+ out = L[prims.convert_element_type.default](
311
+ out, dtype=torch.bfloat16
312
+ )
313
+ return out
314
+
315
+ return fn
316
+
317
+ _binary_attr = {
318
+ aten.add: "add",
319
+ ops.add: "add",
320
+ aten.sub: "sub",
321
+ ops.sub: "sub",
322
+ }
323
+
324
+ def _is_valid_binary(match, fn):
325
+ binary_nodes = filter_nodes(match.nodes, fn)
326
+ if len(binary_nodes) < 1:
327
+ return False
328
+ if any(
329
+ not (
330
+ hasattr(n.args[0], "meta")
331
+ and isinstance(n.args[0].meta.get("val", None), torch.Tensor)
332
+ )
333
+ or not (
334
+ hasattr(n.args[1], "meta")
335
+ and isinstance(n.args[1].meta.get("val", None), torch.Tensor)
336
+ )
337
+ for n in binary_nodes
338
+ ):
339
+ return False
340
+ # check alpha is one.
341
+ if any(
342
+ get_arg_value(n, 2, kwarg_name="alpha") != 1.0
343
+ and get_arg_value(n, 2, kwarg_name="alpha") is not None
344
+ for n in binary_nodes
345
+ ):
346
+ return False
347
+ if any(
348
+ n.args[0].meta["val"].size() != n.args[1].meta["val"].size()
349
+ or n.args[0].meta["val"].device != n.args[1].meta["val"].device
350
+ or n.args[0].meta["val"].dtype != n.args[1].meta["val"].dtype
351
+ for n in binary_nodes
352
+ ):
353
+ return False
354
+ # check args[0] and args[1] is not same
355
+ if any(n.args[0] == n.args[1] for n in binary_nodes):
356
+ return False
357
+ return True
358
+
359
+ def _is_valid_computation_binary(computation_op, binary_op, other_index=None):
360
+ def fn(match):
361
+ if not _is_single_computation_op(computation_op)(match):
362
+ return False
363
+ if not _is_valid_binary(match, binary_op):
364
+ return False
365
+ return True
366
+
367
+ return fn
368
+
369
+ def _is_valid_computation_binary_inplace(computation_op, binary_op, other_index):
370
+ def fn(match):
371
+ if not _is_valid_computation_binary(computation_op, binary_op)(match):
372
+ return False
373
+ binary_nodes = filter_nodes(match.nodes, binary_op)
374
+ if any(len(n.args[other_index].users) > 1 for n in binary_nodes):
375
+ return False
376
+ if any(
377
+ n.args[other_index].op in ["placeholder", "output"]
378
+ for n in binary_nodes
379
+ ):
380
+ return False
381
+ return True
382
+
383
+ return fn
384
+
385
+ def _register_binary_unary_fusion_lowering(
386
+ pattern,
387
+ computation_op,
388
+ binary_op,
389
+ fusion_op,
390
+ unary_attr=None,
391
+ ):
392
+ @register_lowering_pattern(
393
+ pattern, extra_check=_is_valid_computation_binary(computation_op, binary_op)
394
+ )
395
+ def fn(match, *args, **kwargs):
396
+ other = kwargs.get("other")
397
+ assert isinstance(other, ir.TensorBox)
398
+ binary_attr = _binary_attr[binary_op]
399
+ args_list = list(args)
400
+ computation_args = [args_list[0], other] + args_list[1:-3] + [binary_attr]
401
+ if len(args_list) > 6:
402
+ if unary_attr is not None:
403
+ computation_args += [
404
+ 1.0,
405
+ unary_attr.op_name,
406
+ unary_attr.scalars_attr,
407
+ unary_attr.algorithm_attr,
408
+ ]
409
+ else:
410
+ computation_args += [1.0, None, [], None]
411
+ return L[fusion_op](*computation_args)
412
+
413
+ return fn
414
+
415
+ def _register_binary_unary_maybe_inplace_fusion_lowering(
416
+ pattern,
417
+ computation_op,
418
+ binary_op,
419
+ inplace_fusion_op,
420
+ outplace_fusion_op,
421
+ unary_attr=None,
422
+ other_index=None,
423
+ ):
424
+ @register_lowering_pattern(
425
+ pattern,
426
+ extra_check=_is_valid_computation_binary_inplace(
427
+ computation_op, binary_op, other_index
428
+ ),
429
+ )
430
+ def fn(match, *args, **kwargs):
431
+ other = kwargs.get("other")
432
+ assert isinstance(other, ir.TensorBox)
433
+ binary_attr = _binary_attr[binary_op]
434
+ args_list = list(args)
435
+ computation_args = [args_list[0], other] + args_list[1:-3] + [binary_attr]
436
+ if len(args_list) > 6:
437
+ if unary_attr is not None:
438
+ computation_args += [
439
+ 1.0,
440
+ unary_attr.op_name,
441
+ unary_attr.scalars_attr,
442
+ unary_attr.algorithm_attr,
443
+ ]
444
+ else:
445
+ computation_args += [1.0, None, [], None]
446
+ # Make sure the other is not an alias or mutation(fx side doesn't has such info).
447
+ other.realize()
448
+ can_be_inplace = not (
449
+ isinstance(other.data, ir.ReinterpretView)
450
+ or isinstance(other.get_layout(), (ir.MutationLayout, ir.AliasedLayout))
451
+ )
452
+ if not can_be_inplace:
453
+ return L[outplace_fusion_op](*computation_args)
454
+ return L[inplace_fusion_op](*computation_args)
455
+
456
+ return fn
457
+
458
+ computation_ops = [
459
+ mkldnn._convolution_pointwise.default,
460
+ mkldnn._linear_pointwise.default,
461
+ mkldnn._convolution_transpose_pointwise.default,
462
+ ]
463
+
464
+ class UnaryAttr:
465
+ def __init__(self, op_name: str, scalars_attr=None, algorithm_attr=None):
466
+ self.op_name = op_name
467
+ self.scalars_attr = scalars_attr if scalars_attr else []
468
+ self.algorithm_attr = algorithm_attr if algorithm_attr else ""
469
+
470
+ def _register_unary_fusion():
471
+ computation_call_fns = [_conv_call, _linear_call, _conv_transpose_call]
472
+
473
+ def _unary_fusion_patterns(is_bf16):
474
+ replacement_unary_fusion_patterns = {
475
+ UnaryAttr("gelu", algorithm_attr="tanh"): [
476
+ _unary_fusion_pattern(_gelu_fusion_2, call_fn, 4, is_bf16)
477
+ for call_fn in computation_call_fns
478
+ ],
479
+ UnaryAttr("gelu", algorithm_attr="none"): [
480
+ _unary_fusion_pattern(_gelu_fusion_1, call_fn, 2, is_bf16)
481
+ for call_fn in computation_call_fns
482
+ ],
483
+ UnaryAttr("hardswish"): [
484
+ _unary_fusion_pattern(_hardswish_fusion, call_fn, 2, is_bf16)
485
+ for call_fn in computation_call_fns
486
+ ],
487
+ UnaryAttr("hardsigmoid"): [
488
+ _unary_fusion_pattern(_hardsigmoid_fusion, call_fn, 1, is_bf16)
489
+ for call_fn in computation_call_fns
490
+ ],
491
+ UnaryAttr("swish"): [
492
+ _unary_fusion_pattern(_silu_fusion, call_fn, 2, is_bf16)
493
+ for call_fn in computation_call_fns
494
+ ],
495
+ }
496
+ if not is_bf16:
497
+ call_user1 = [call_fn(users=1) for call_fn in computation_call_fns]
498
+ replacement_unary_fusion_patterns.update(
499
+ {
500
+ UnaryAttr("relu"): [
501
+ _combined_fusion(u, aten.relu) for u in call_user1
502
+ ],
503
+ UnaryAttr("sigmoid"): [
504
+ _combined_fusion(u, aten.sigmoid) for u in call_user1
505
+ ],
506
+ UnaryAttr("tanh"): [
507
+ _combined_fusion(u, aten.tanh) for u in call_user1
508
+ ],
509
+ }
510
+ )
511
+
512
+ return replacement_unary_fusion_patterns
513
+
514
+ for is_bf16 in [True, False]:
515
+ replace_patterns = _unary_fusion_patterns(is_bf16)
516
+ for unary_attr, patterns in replace_patterns.items():
517
+ _register_unary_fusion_lowering(
518
+ patterns[0], unary_attr, computation_ops[0], is_bf16
519
+ )
520
+ _register_unary_fusion_lowering(
521
+ patterns[1], unary_attr, computation_ops[1], is_bf16
522
+ )
523
+ _register_unary_fusion_lowering(
524
+ patterns[2], unary_attr, computation_ops[2], is_bf16
525
+ )
526
+ _leaky_relu_patterns = [
527
+ _unary_fusion_pattern(_leaky_relu_fusion, call_fn, 3, is_bf16)
528
+ for call_fn in computation_call_fns
529
+ ]
530
+ for pattern, computation_op in zip(_leaky_relu_patterns, computation_ops):
531
+ _register_leaky_relu_fusion_lowering(pattern, computation_op, is_bf16)
532
+ hardtanh_patterns = [
533
+ _unary_fusion_pattern(_hardtanh_fusion, call_fn, 1, is_bf16)
534
+ for call_fn in computation_call_fns
535
+ ]
536
+ for pattern, computation_op in zip(hardtanh_patterns, computation_ops):
537
+ _register_hardtanh_fusion_lowering(pattern, computation_op, is_bf16)
538
+
539
+ def _register_inplace_fusion():
540
+ binary_ops = [aten.add, ops.add]
541
+ inplace_fusion_op = mkldnn._convolution_pointwise_.binary
542
+ outplace_fusion_op = mkldnn._convolution_pointwise.binary
543
+ conv_call = _conv_call(users=1)
544
+ conv_op = computation_ops[0]
545
+ for binary_op in binary_ops:
546
+ binary_v1 = _binary_fusion_v1(conv_call, binary_op)
547
+ binary_unary_v1 = _combined_fusion(binary_v1, aten.relu)
548
+ _register_binary_unary_maybe_inplace_fusion_lowering(
549
+ binary_unary_v1,
550
+ conv_op,
551
+ binary_op,
552
+ inplace_fusion_op,
553
+ outplace_fusion_op,
554
+ other_index=0,
555
+ unary_attr=UnaryAttr("relu"),
556
+ )
557
+ _register_binary_unary_maybe_inplace_fusion_lowering(
558
+ binary_v1,
559
+ conv_op,
560
+ binary_op,
561
+ inplace_fusion_op,
562
+ outplace_fusion_op,
563
+ other_index=0,
564
+ )
565
+ binary_v2 = _binary_fusion_v2(conv_call, binary_op)
566
+ binary_unary_v2 = _combined_fusion(binary_v2, aten.relu)
567
+ _register_binary_unary_maybe_inplace_fusion_lowering(
568
+ binary_unary_v2,
569
+ conv_op,
570
+ binary_op,
571
+ inplace_fusion_op,
572
+ outplace_fusion_op,
573
+ other_index=1,
574
+ unary_attr=UnaryAttr("relu"),
575
+ )
576
+ _register_binary_unary_maybe_inplace_fusion_lowering(
577
+ binary_v2,
578
+ conv_op,
579
+ binary_op,
580
+ inplace_fusion_op,
581
+ outplace_fusion_op,
582
+ other_index=1,
583
+ )
584
+
585
+ def _register_binary_fusion():
586
+ binary_ops = [aten.add, ops.add, aten.sub, ops.sub]
587
+ fusion_ops = [
588
+ mkldnn._convolution_pointwise.binary,
589
+ mkldnn._linear_pointwise.binary,
590
+ ]
591
+ _computation_user_1 = [_conv_call(users=1), _linear_call(users=1)]
592
+ for computation_call, computation_op, fusion_op in zip(
593
+ _computation_user_1, computation_ops[:-1], fusion_ops
594
+ ):
595
+ for binary_op in binary_ops:
596
+ pattern = _binary_fusion_v2(computation_call, binary_op)
597
+ _register_binary_unary_fusion_lowering(
598
+ pattern, computation_op, binary_op, fusion_op
599
+ )
600
+
601
+ for binary_op in [aten.add, ops.add]:
602
+ pattern = _binary_fusion_v1(computation_call, binary_op)
603
+ _register_binary_unary_fusion_lowering(
604
+ pattern, computation_op, binary_op, fusion_op
605
+ )
606
+
607
+ def _register_binary_unary_fusion():
608
+ binary_ops = [aten.add, ops.add, aten.sub, ops.sub]
609
+ fusion_ops = [mkldnn._convolution_pointwise.binary]
610
+ _computation_user_1 = [_conv_call(users=1)]
611
+ for computation_call, computation_op, fusion_op in zip(
612
+ _computation_user_1, computation_ops[:-1], fusion_ops
613
+ ):
614
+ for binary_op in binary_ops:
615
+ pattern_v1 = _combined_fusion(
616
+ _binary_fusion_v2(computation_call, binary_op), aten.relu
617
+ )
618
+ _register_binary_unary_fusion_lowering(
619
+ pattern_v1,
620
+ computation_op,
621
+ binary_op,
622
+ fusion_op,
623
+ unary_attr=UnaryAttr("relu"),
624
+ )
625
+ for binary_op in [aten.add, ops.add]:
626
+ pattern_v2 = _combined_fusion(
627
+ _binary_fusion_v1(computation_call, binary_op), aten.relu
628
+ )
629
+ _register_binary_unary_fusion_lowering(
630
+ pattern_v2,
631
+ computation_op,
632
+ binary_op,
633
+ fusion_op,
634
+ unary_attr=UnaryAttr("relu"),
635
+ )
636
+
637
+ def _recover_linear():
638
+ # convert reshape+linear+reshape to a single linear for applying fusion path.
639
+ @register_freezing_graph_pattern(
640
+ CallFunction(
641
+ aten.reshape.default,
642
+ CallFunction(
643
+ mkldnn._linear_pointwise.default,
644
+ CallFunction(
645
+ aten.reshape.default,
646
+ Arg(),
647
+ KeywordArg("reshape_1"),
648
+ _users=MULTIPLE,
649
+ ),
650
+ Arg(),
651
+ Arg(),
652
+ Arg(),
653
+ Arg(),
654
+ Arg(),
655
+ ),
656
+ KeywordArg("reshape_2"),
657
+ ),
658
+ pass_number=1,
659
+ )
660
+ def reshape_linear_reshape_pattern(match, *args, **kwargs):
661
+ reshape_1 = kwargs.get("reshape_1")
662
+ reshape_2 = kwargs.get("reshape_2")
663
+ assert isinstance(reshape_1, list)
664
+ assert isinstance(reshape_2, list)
665
+ assert len(reshape_1) == 2
666
+ dynamic_shapes = not all(
667
+ isinstance(x, int) for x in ([reshape_1[0]] + reshape_2[:-1])
668
+ )
669
+
670
+ graph = match.graph
671
+ reshape_2_node = match.output_node()
672
+ linear_input_node = reshape_2_node.args[0].args[0].args[0]
673
+ # check linear's input's shape[:-1] == reshape_2[:-1]
674
+ # and check product(reshape_2[:-1]) == reshape_1[0]
675
+ if dynamic_shapes:
676
+ # TODO: Haozhe investigate how add guard here
677
+ return
678
+ else:
679
+ can_remove_reshape = linear_input_node.meta.get("val").shape[
680
+ :-1
681
+ ] == torch.Size(reshape_2[:-1])
682
+ can_remove_reshape = can_remove_reshape and (
683
+ reduce(lambda x, y: x * y, reshape_2[:-1]) == reshape_1[0]
684
+ )
685
+
686
+ if can_remove_reshape:
687
+ repl = graph.call_function(mkldnn._linear_pointwise.default, args)
688
+ repl.meta.update(reshape_2_node.meta)
689
+ reshape_2_node.replace_all_uses_with(repl)
690
+ old_linear_node = reshape_2_node.args[0]
691
+ reshape_1_node = old_linear_node.args[0]
692
+ graph.erase_node(reshape_2_node)
693
+ graph.erase_node(old_linear_node)
694
+ if len(reshape_1_node.users) == 0:
695
+ graph.erase_node(reshape_1_node)
696
+
697
+ def is_linear_add_bias(match):
698
+ add_node = match.output_node()
699
+ linear_node = add_node.args[0]
700
+ weight_meta = linear_node.args[1].meta.get("val")
701
+ bias_meta = add_node.args[1].meta.get("val")
702
+ if weight_meta is None or bias_meta is None:
703
+ return False
704
+ return (
705
+ linear_node.args[2] is None
706
+ and bias_meta.dim() == 1
707
+ and bias_meta.size(0) == weight_meta.size(0)
708
+ )
709
+
710
+ # convert linear+bias to a single linear for applying fusion path.
711
+ @register_freezing_graph_pattern(
712
+ CallFunction(
713
+ aten.add.Tensor,
714
+ CallFunction(mkldnn._linear_pointwise.default, *_linear_args),
715
+ Arg(),
716
+ ),
717
+ pass_number=1,
718
+ extra_check=is_linear_add_bias,
719
+ )
720
+ def linear_bias_pattern(match, *args):
721
+ graph = match.graph
722
+ add_node = match.output_node()
723
+ linear_node = add_node.args[0]
724
+ new_args = list(linear_node.args)
725
+ new_args[2] = add_node.args[1]
726
+ repl = graph.call_function(
727
+ mkldnn._linear_pointwise.default, tuple(new_args)
728
+ )
729
+ repl.meta.update(add_node.meta)
730
+ add_node.replace_all_uses_with(repl)
731
+ match.erase_nodes(graph)
732
+
733
+ def _is_packable_mkldnn_rnn_layer(match):
734
+ lstm_node = match.output_node()
735
+ POS_WEIGHTS = [1, 2]
736
+ POS_INPUTS = [0, 5, 6]
737
+ POS_ARGS = POS_WEIGHTS + POS_INPUTS
738
+ # Weights should be Constant
739
+ if any(
740
+ lstm_node.args[POS_WEIGHT].op != "get_attr" for POS_WEIGHT in POS_WEIGHTS
741
+ ):
742
+ return False
743
+
744
+ # Meta info for weights and inputs should be available
745
+ if any(lstm_node.args[POS_ARG].meta.get("val") is None for POS_ARG in POS_ARGS):
746
+ return False
747
+
748
+ # Check device
749
+ if any(
750
+ lstm_node.args[POS_ARG].meta.get("val").device.type != "cpu"
751
+ for POS_ARG in POS_ARGS
752
+ ):
753
+ return False
754
+
755
+ # Check dtype
756
+ if any(
757
+ lstm_node.args[POS_ARG].meta.get("val").dtype == torch.bfloat16
758
+ and not mkldnn._is_mkldnn_bf16_supported()
759
+ for POS_ARG in POS_ARGS
760
+ ):
761
+ return False
762
+
763
+ return True
764
+
765
+ def _is_packable_convolution(match):
766
+ """
767
+ Check if the node is supported for MKLDNN convolution.
768
+ """
769
+ conv_node = match.output_node()
770
+ input_meta_value = conv_node.args[0].meta.get("val")
771
+ weight_meta_value = conv_node.args[1].meta.get("val")
772
+ if input_meta_value is None or weight_meta_value is None:
773
+ return False
774
+ input_size = input_meta_value.shape
775
+ if conv_node.args[1].op != "get_attr":
776
+ return False
777
+ for meta_value in [input_meta_value, weight_meta_value]:
778
+ if (
779
+ meta_value is None
780
+ or meta_value.device.type != "cpu"
781
+ or meta_value.dim() != 4
782
+ ):
783
+ return False
784
+ if (
785
+ input_meta_value.dtype == torch.bfloat16
786
+ or weight_meta_value.dtype == torch.bfloat16
787
+ ):
788
+ if not mkldnn._is_mkldnn_bf16_supported():
789
+ return False
790
+ is_transposed = conv_node.args[-3]
791
+ if is_transposed:
792
+ # TODO: Support dynamic shape case for MKLDNN conv transpose.
793
+ if has_free_symbols(input_size):
794
+ return False
795
+ groups = conv_node.args[-1]
796
+ in_channels = weight_meta_value.size(0)
797
+ # doesn't support group_depthwise_conv_transpose.
798
+ if groups > 1 and groups == in_channels:
799
+ return False
800
+ # Port from: aten/src/ATen/native/Convolution.cpp:is_output_padding_big
801
+ output_paddings = conv_node.args[-2]
802
+ strides = conv_node.args[3]
803
+ if any(
804
+ output_padding >= stride
805
+ for output_padding, stride in zip(output_paddings, strides)
806
+ ):
807
+ return False
808
+ return True
809
+
810
+ def _is_packable_linear(match):
811
+ """
812
+ Check if the node is supported for MKLDNN linear.
813
+ """
814
+ linear_node = match.output_node()
815
+ # weight_idx is 1 for aten.mm and is 2 for aten.addmm
816
+ weight_idx = 2 if linear_node.target == aten.addmm.default else 1
817
+ if linear_node.args[weight_idx].op != "get_attr":
818
+ return False
819
+ input_meta_value = linear_node.args[weight_idx - 1].meta.get("val")
820
+ weight_meta_value = linear_node.args[weight_idx].meta.get("val")
821
+ if input_meta_value is None or weight_meta_value is None:
822
+ return False
823
+ batch_size = input_meta_value.shape[0]
824
+ is_bf16_weight = weight_meta_value.dtype == torch.bfloat16
825
+ # for fp32, mkl should be enabled and batch_size should not be a free symbol.
826
+ if not is_bf16_weight and (
827
+ (not torch._C.has_mkl) or has_free_symbols(batch_size)
828
+ ):
829
+ return False
830
+ for meta_value in [input_meta_value, weight_meta_value]:
831
+ if (
832
+ meta_value is None
833
+ or meta_value.device.type != "cpu"
834
+ or meta_value.dim() != 2
835
+ ):
836
+ return False
837
+ if weight_idx == 2:
838
+ bias_meta_value = linear_node.args[0].meta.get("val")
839
+ if (
840
+ bias_meta_value is None
841
+ or meta_value.device.type != "cpu"
842
+ or bias_meta_value.dim() != 1
843
+ or bias_meta_value.size(0) != weight_meta_value.size(1)
844
+ ):
845
+ return False
846
+
847
+ if (
848
+ input_meta_value.dtype == torch.bfloat16
849
+ or weight_meta_value.dtype == torch.bfloat16
850
+ ):
851
+ if not mkldnn._is_mkldnn_bf16_supported():
852
+ return False
853
+ return True
854
+
855
+ _aten_conv_args = (
856
+ Arg(),
857
+ Arg(),
858
+ Arg(),
859
+ Arg(),
860
+ Arg(),
861
+ Arg(),
862
+ KeywordArg("is_transposed"),
863
+ Arg(),
864
+ Arg(),
865
+ )
866
+
867
+ _aten_mkldnn_rnn_layer_args = (
868
+ Arg(), # input
869
+ Arg(), # weight0
870
+ Arg(), # weight1
871
+ Arg(), # weight2
872
+ Arg(), # weight3
873
+ Arg(), # hx_
874
+ Arg(), # cx_
875
+ KeywordArg("reverse"), # reverse
876
+ Arg(), # batch_sizes
877
+ Arg(), # mode
878
+ Arg(), # hidden_size
879
+ Arg(), # num_layers
880
+ Arg(), # has_biases
881
+ Arg(), # bidirectional
882
+ Arg(), # batch_first
883
+ Arg(), # train
884
+ )
885
+
886
+ def _register_weight_pack_pass():
887
+ @register_freezing_graph_pattern(
888
+ CallFunction(aten.convolution.default, *_aten_conv_args),
889
+ extra_check=_is_packable_convolution,
890
+ )
891
+ def convolution(match, *args, **kwargs):
892
+ is_transposed = kwargs.get("is_transposed")
893
+ assert isinstance(is_transposed, bool)
894
+ graph = match.graph
895
+ conv_node = match.output_node()
896
+ input_size = conv_node.args[0].meta.get("val").shape
897
+ with graph.inserting_before(conv_node):
898
+ constant_args = [args[4], args[3], args[5], args[-1]]
899
+ packed_weight_op = mkldnn._reorder_convolution_weight
900
+ packed_conv_op = mkldnn._convolution_pointwise.default
901
+ if is_transposed:
902
+ constant_args.insert(1, args[-2]) # output_padding
903
+ packed_weight_op = mkldnn._reorder_convolution_transpose_weight
904
+ packed_conv_op = mkldnn._convolution_transpose_pointwise.default
905
+ if not has_free_symbols(input_size):
906
+ packed_weight_inputs = (
907
+ (args[1],) + tuple(constant_args) + (input_size,)
908
+ )
909
+ packed_weight_node = graph.create_node(
910
+ "call_function", packed_weight_op, args=packed_weight_inputs
911
+ )
912
+ else:
913
+ assert not is_transposed
914
+ # For dynamic shape case, we need to pack weight in runtime.
915
+ packed_weight_node = args[1]
916
+ packed_conv_inputs = (
917
+ (args[0], packed_weight_node, args[2])
918
+ + tuple(constant_args)
919
+ + ("none", [], "")
920
+ )
921
+ packed_conv_node = graph.create_node(
922
+ "call_function", packed_conv_op, tuple(packed_conv_inputs)
923
+ )
924
+ conv_node.replace_all_uses_with(packed_conv_node)
925
+ packed_conv_node.meta.update(conv_node.meta)
926
+ graph.erase_node(conv_node)
927
+
928
+ @register_freezing_graph_pattern(
929
+ CallFunction(aten.mkldnn_rnn_layer.default, *_aten_mkldnn_rnn_layer_args),
930
+ extra_check=_is_packable_mkldnn_rnn_layer,
931
+ )
932
+ def mkldnn_rnn_layer(match, *args, **kwargs):
933
+ def get_item(graph, node, index):
934
+ return graph.call_function(operator.getitem, (node, index))
935
+
936
+ graph = match.graph
937
+ lstm_node = match.output_node()
938
+ input = args[0]
939
+ weight0, weight1 = args[1:3]
940
+ reverse = kwargs.get("reverse")
941
+ packed_lstm_op = aten.mkldnn_rnn_layer.default
942
+ hidden_size = args[9]
943
+ has_biases = args[11]
944
+ batch_first = args[13]
945
+ with graph.inserting_before(lstm_node):
946
+ packed_weight_op = mkldnn._reorder_mkldnn_rnn_layer_weight.default
947
+ packed_weight_inputs = (
948
+ weight0,
949
+ weight1,
950
+ hidden_size,
951
+ reverse,
952
+ has_biases,
953
+ batch_first,
954
+ )
955
+ packed_weight_node = graph.create_node(
956
+ "call_function", packed_weight_op, packed_weight_inputs, {}, "name"
957
+ )
958
+ packed_weight_items = [
959
+ get_item(graph, packed_weight_node, i) for i in range(2)
960
+ ]
961
+ pack_lstm_inputs = (
962
+ args[0],
963
+ *packed_weight_items,
964
+ args[3],
965
+ args[4],
966
+ args[5],
967
+ args[6],
968
+ reverse,
969
+ *args[7:],
970
+ )
971
+
972
+ packed_lstm_node = graph.create_node(
973
+ "call_function", packed_lstm_op, args=pack_lstm_inputs
974
+ )
975
+ lstm_node.replace_all_uses_with(packed_lstm_node)
976
+ packed_lstm_node.meta.update(lstm_node.meta)
977
+ graph.erase_node(lstm_node)
978
+
979
+ @register_freezing_graph_pattern(
980
+ CallFunction(aten.addmm.default, Arg(), Arg(), Arg()),
981
+ extra_check=_is_packable_linear,
982
+ )
983
+ @register_freezing_graph_pattern(
984
+ CallFunction(aten.mm.default, Arg(), Arg()),
985
+ extra_check=_is_packable_linear,
986
+ )
987
+ def linear(match, *args, **kwargs):
988
+ graph = match.graph
989
+ linear_node = match.output_node()
990
+ input = args[0] if linear_node.target == aten.mm.default else args[1]
991
+ bias = None if linear_node.target == aten.mm.default else args[0]
992
+ weight = args[1] if linear_node.target == aten.mm.default else args[2]
993
+ with graph.inserting_before(linear_node):
994
+ transpose_weight_node = graph.create_node(
995
+ "call_function", aten.permute.default, (weight, (1, 0))
996
+ )
997
+ weight_dtype = weight.meta.get("val").dtype
998
+ is_bf16_weight = weight_dtype == torch.bfloat16
999
+ batch_size = input.meta.get("val").shape[0]
1000
+ if has_free_symbols(batch_size):
1001
+ assert (
1002
+ is_bf16_weight
1003
+ ), f"only bf16 weight prepacking supports dynamic shape inputs but got {weight_dtype}"
1004
+ # For bfloat16 dynamic shape path, using input size hint to pack weight for a better performance.
1005
+ packed_weight_inputs = (
1006
+ transpose_weight_node,
1007
+ batch_size.node.shape_env.size_hint(batch_size.node.expr)
1008
+ if has_free_symbols(batch_size)
1009
+ else batch_size,
1010
+ )
1011
+ packed_weight_op = (
1012
+ mkldnn._reorder_linear_weight
1013
+ if is_bf16_weight
1014
+ else torch.ops.mkl._mkl_reorder_linear_weight
1015
+ )
1016
+ packed_weight_node = graph.create_node(
1017
+ "call_function", packed_weight_op, args=packed_weight_inputs
1018
+ )
1019
+
1020
+ packed_linear_inputs: Tuple[Any, ...] = (input, packed_weight_node)
1021
+ if is_bf16_weight:
1022
+ packed_linear_inputs += (bias, "none", [], "")
1023
+ packed_linear_op = mkldnn._linear_pointwise.default
1024
+ else:
1025
+ packed_linear_inputs += (transpose_weight_node, bias, batch_size)
1026
+ packed_linear_op = torch.ops.mkl._mkl_linear
1027
+ packed_linear_node = graph.create_node(
1028
+ "call_function", packed_linear_op, packed_linear_inputs
1029
+ )
1030
+ linear_node.replace_all_uses_with(packed_linear_node)
1031
+ packed_linear_node.meta.update(linear_node.meta)
1032
+ graph.erase_node(linear_node)
1033
+
1034
+ def _eliminate_duplicate_packed_nodes(gm):
1035
+ """
1036
+ Combine packed weight nodes with the same inputs to reduce memory usage.
1037
+ for example:
1038
+ class Model(nn.Module):
1039
+ def __init__(self):
1040
+ super().__init__()
1041
+ self.linear = nn.Linear(32, 32, bias=True)
1042
+
1043
+ def forward(self, x):
1044
+ return self.linear(self.linear(x))
1045
+
1046
+ the above's packed weight nodes are duplicate if two linear calls have same input size.
1047
+ """
1048
+ if not (torch.backends.mkldnn.enabled and torch.backends.mkldnn.is_available()):
1049
+ return gm
1050
+
1051
+ packed_weight_ops = [
1052
+ torch._C._nn.mkldnn_reorder_conv2d_weight,
1053
+ mkldnn._reorder_convolution_transpose_weight,
1054
+ mkldnn._reorder_linear_weight,
1055
+ mkldnn._reorder_mkldnn_rnn_layer_weight,
1056
+ ]
1057
+ if torch._C.has_mkl:
1058
+ packed_weight_ops.append(torch.ops.mkl._mkl_reorder_linear_weight)
1059
+
1060
+ for node in gm.graph.nodes:
1061
+ if node.target in packed_weight_ops and len(node.args[0].users) > 1:
1062
+ for user_node in list(node.args[0].users.keys()):
1063
+ if (
1064
+ user_node.target == node.target
1065
+ and user_node != node
1066
+ and user_node.args == node.args
1067
+ ):
1068
+ user_node.replace_all_uses_with(node)
1069
+ gm.graph.erase_node(user_node)
1070
+
1071
+ @functools.lru_cache(None)
1072
+ def _mkldnn_fusion_init():
1073
+ if torch.backends.mkldnn.enabled and torch.backends.mkldnn.is_available():
1074
+ _register_unary_fusion()
1075
+ _register_inplace_fusion()
1076
+ _register_binary_unary_fusion()
1077
+ _register_binary_fusion()
1078
+ _register_quantization_lowerings()
1079
+
1080
+ @functools.lru_cache(None)
1081
+ def _mkldnn_weight_pack_init():
1082
+ if torch.backends.mkldnn.enabled and torch.backends.mkldnn.is_available():
1083
+ _register_weight_pack_pass()
1084
+ _recover_linear()
1085
+ _register_quantization_weight_pack_pass()
vlmpy310/lib/python3.10/site-packages/torch/_inductor/fx_passes/pad_mm.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from itertools import chain
3
+ from typing import List, Optional
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from torch._inductor import utils
8
+ from torch.utils._mode_utils import no_dispatch
9
+ from torch.utils._triton import has_triton
10
+
11
+ from ..pattern_matcher import fwd_only, joint_fwd_bwd, Match, register_replacement
12
+
13
+ aten = torch.ops.aten
14
+
15
+
16
+ def fetch_fake_tensors(match, kwarg_names) -> List[Tensor]:
17
+ kwargs = match.kwargs
18
+ return [kwargs[name].meta["val"] for name in kwarg_names]
19
+
20
+
21
+ def unwrap_fake_args(*arg_names):
22
+ def decorator(func):
23
+ def wrapper(match):
24
+ fake_tensors = fetch_fake_tensors(match, arg_names)
25
+ return func(*fake_tensors)
26
+
27
+ return wrapper
28
+
29
+ return decorator
30
+
31
+
32
+ def get_alignment_size(x: Tensor) -> int:
33
+ if x.dtype == torch.float16 or x.dtype == torch.half or x.dtype == torch.bfloat16:
34
+ return 8
35
+ elif x.dtype == torch.float32 or x.dtype == torch.float:
36
+ return 4
37
+ else:
38
+ return 0
39
+
40
+
41
+ def check_device(a: Tensor, b: Tensor) -> bool:
42
+ return a.is_cuda and b.is_cuda
43
+
44
+
45
+ def check_dtype(a: Tensor, b: Tensor) -> bool:
46
+ return a.is_floating_point() and b.is_floating_point()
47
+
48
+
49
+ def is_symbolic(a: Optional[Tensor]) -> bool:
50
+ return a is not None and any(
51
+ isinstance(x, torch.SymInt) for x in chain(a.size(), a.stride())
52
+ )
53
+
54
+
55
+ def any_is_symbolic(*args: Optional[Tensor]) -> bool:
56
+ return any(is_symbolic(a) for a in args)
57
+
58
+
59
+ def should_pad_common(
60
+ mat1: Tensor, mat2: Tensor, input: Optional[Tensor] = None
61
+ ) -> bool:
62
+ return (
63
+ torch._inductor.config.shape_padding
64
+ and check_device(mat1, mat2)
65
+ and check_dtype(mat1, mat2)
66
+ and not any_is_symbolic(mat1, mat2, input)
67
+ )
68
+
69
+
70
+ def get_padded_length(x: int, alignment_size) -> int:
71
+ if alignment_size == 0 or x % alignment_size == 0:
72
+ return 0
73
+ return int((x // alignment_size + 1) * alignment_size) - x
74
+
75
+
76
+ def pad_dim(x: Tensor, padded_length: int, dim: int) -> Tensor:
77
+ if padded_length == 0:
78
+ return x
79
+ pad = x.new_zeros(*x.shape[:dim], padded_length, *x.shape[dim + 1 :])
80
+ return torch.cat([x, pad], dim=dim)
81
+
82
+
83
+ def addmm_pattern(
84
+ input: Tensor, mat1: Tensor, mat2: Tensor, beta: float, alpha: float
85
+ ) -> Tensor:
86
+ return aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha)
87
+
88
+
89
+ def should_pad_addmm(match: Match) -> bool:
90
+ mat1, mat2, input = fetch_fake_tensors(match, ("mat1", "mat2", "input"))
91
+ return should_pad_common(mat1, mat2, input) and should_pad_bench(
92
+ mat1, mat2, torch.ops.aten.addmm, input=input
93
+ )
94
+
95
+
96
+ def addmm_replace(
97
+ input: Optional[Tensor], mat1: Tensor, mat2: Tensor, beta=1.0, alpha=1.0
98
+ ) -> Tensor:
99
+ m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1))
100
+ k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1))
101
+ n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2))
102
+
103
+ if m_padded_length != 0 or k_padded_length != 0 or n_padded_length != 0:
104
+ return pad_addmm(
105
+ input,
106
+ mat1,
107
+ mat2,
108
+ m_padded_length,
109
+ k_padded_length,
110
+ n_padded_length,
111
+ beta,
112
+ alpha,
113
+ )
114
+
115
+ return aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha)
116
+
117
+
118
+ def pad_addmm(
119
+ input: Optional[Tensor],
120
+ mat1: Tensor,
121
+ mat2: Tensor,
122
+ m_padded_length: int,
123
+ k_padded_length: int,
124
+ n_padded_length: int,
125
+ beta=1.0,
126
+ alpha=1.0,
127
+ ):
128
+ # addmm decomp with padding will go through pad_addmm multiple times if multiple dimensions are needed to be padded
129
+ if k_padded_length != 0:
130
+ mat1 = pad_dim(mat1, k_padded_length, 1)
131
+ mat2 = pad_dim(mat2, k_padded_length, 0)
132
+ elif n_padded_length != 0:
133
+ mat2 = pad_dim(mat2, n_padded_length, 1)
134
+ elif m_padded_length != 0:
135
+ mat1 = pad_dim(mat1, m_padded_length, 0)
136
+
137
+ # the add broadcasts, so we only pad if the dimension != 1
138
+ if input is not None and k_padded_length == 0:
139
+ if n_padded_length != 0:
140
+ if input.dim() == 2 and input.shape[1] != 1:
141
+ input = pad_dim(input, n_padded_length, 1)
142
+ elif input.dim() == 1 and input.shape[0] != 1:
143
+ input = pad_dim(input, n_padded_length, 0)
144
+ elif m_padded_length != 0 and input.dim() == 2 and input.shape[0] != 1:
145
+ input = pad_dim(input, m_padded_length, 0)
146
+
147
+ if k_padded_length != 0:
148
+ return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha)
149
+ elif n_padded_length != 0:
150
+ return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha)[
151
+ :, :-n_padded_length
152
+ ]
153
+ else:
154
+ return addmm_replace(input, mat1, mat2, beta=beta, alpha=alpha)[
155
+ :-m_padded_length, :
156
+ ]
157
+
158
+
159
+ def is_mm_compute_bound(M: int, K: int, N: int, dtype: torch.dtype) -> bool:
160
+ denominator = M * K + N * K + M * N
161
+ if denominator == 0:
162
+ return False
163
+ arithmetic_intensity = (M * N * K) / denominator
164
+
165
+ # Fails with AMD
166
+ try:
167
+ machine_balance = (
168
+ 1000 * utils.get_device_tflops(dtype)
169
+ ) / utils.get_gpu_dram_gbps()
170
+ except Exception:
171
+ return True
172
+
173
+ # dram_gbps might be underestimating bandwidth because of cache.
174
+ # if we estimate machine balance too low we might miss some speedups,
175
+ # if we extimate too high there will be unnecessary compilation time increase.
176
+ # TODO - finetune coefficient here. As a reference point, Triton mm model assumes
177
+ # 80% of reads are in cache and cache is 4x faster than dram_gbps
178
+ machine_balance = machine_balance * 0.5
179
+
180
+ return arithmetic_intensity > machine_balance
181
+
182
+
183
+ @functools.lru_cache(None)
184
+ def get_pad_cache():
185
+ return torch._inductor.codecache.LocalCache()
186
+
187
+
188
+ def get_cached_should_pad(key):
189
+ return get_pad_cache().lookup(key)
190
+
191
+
192
+ def set_cached_should_pad(key, value):
193
+ return get_pad_cache().set_value(key, value=value)
194
+
195
+
196
+ def should_pad_bench_key(
197
+ mat1: Tensor, mat2: Tensor, op, input: Optional[Tensor] = None
198
+ ) -> str:
199
+ def tensor_key(t):
200
+ return (t.shape, t.stride(), t.dtype)
201
+
202
+ tf32_key = (
203
+ None if mat1.dtype != torch.float32 else torch.backends.cuda.matmul.allow_tf32
204
+ )
205
+ key = (
206
+ tensor_key(mat1),
207
+ tensor_key(mat2),
208
+ op,
209
+ input if input is None else tensor_key(input),
210
+ tf32_key,
211
+ )
212
+
213
+ return str(key)
214
+
215
+
216
+ def should_pad_bench(
217
+ mat1: Tensor, mat2: Tensor, op, input: Optional[Tensor] = None
218
+ ) -> bool:
219
+ if not has_triton():
220
+ return False
221
+
222
+ do_bench = functools.partial(
223
+ utils.do_bench,
224
+ warmup=5,
225
+ )
226
+
227
+ with no_dispatch():
228
+ if op is torch.ops.aten.mm or op is torch.ops.aten.addmm:
229
+ m = mat1.shape[0]
230
+ k = mat1.shape[1]
231
+ n = mat2.shape[1]
232
+
233
+ m_padded_length = get_padded_length(m, get_alignment_size(mat1))
234
+ k_padded_length = get_padded_length(k, get_alignment_size(mat1))
235
+ n_padded_length = get_padded_length(n, get_alignment_size(mat2))
236
+ elif op is torch.ops.aten.bmm:
237
+ m = mat1.shape[1]
238
+ k = mat2.shape[2]
239
+ n = mat2.shape[2]
240
+
241
+ m_padded_length = get_padded_length(m, get_alignment_size(mat1))
242
+ k_padded_length = get_padded_length(k, get_alignment_size(mat1))
243
+ n_padded_length = get_padded_length(n, get_alignment_size(mat2))
244
+ else:
245
+ return False
246
+
247
+ if m_padded_length == k_padded_length == n_padded_length == 0:
248
+ return False
249
+
250
+ if not is_mm_compute_bound(m, k, n, mat1.dtype):
251
+ return False
252
+
253
+ # We don't want to look up the cache for cases that are trivially false
254
+ # since it does file io
255
+ key = should_pad_bench_key(mat1, mat2, op, input)
256
+
257
+ cached_pad = get_cached_should_pad(key)
258
+ if cached_pad is not None:
259
+ return cached_pad
260
+
261
+ mat1 = torch.randn_like(mat1)
262
+ mat2 = torch.randn_like(mat2)
263
+ if op is torch.ops.aten.bmm or op is torch.ops.aten.mm:
264
+ ori_time = do_bench(
265
+ lambda: op(mat1, mat2),
266
+ )
267
+ else:
268
+ if input is not None:
269
+ input = torch.randn_like(input)
270
+ ori_time = do_bench(
271
+ lambda: op(input, mat1, mat2),
272
+ )
273
+
274
+ mat1_pad = torch.randn_like(mat1)
275
+ mat2_pad = torch.randn_like(mat2)
276
+
277
+ if op is torch.ops.aten.addmm:
278
+ input_pad = None
279
+ if input is not None and input.is_cuda:
280
+ input_pad = torch.randn_like(input)
281
+ pad_time = do_bench(
282
+ lambda: pad_addmm(
283
+ input_pad,
284
+ mat1_pad,
285
+ mat2_pad,
286
+ m_padded_length,
287
+ k_padded_length,
288
+ n_padded_length,
289
+ ),
290
+ )
291
+ elif op is torch.ops.aten.mm:
292
+ pad_time = do_bench(
293
+ lambda: pad_mm(
294
+ mat1_pad,
295
+ mat2_pad,
296
+ m_padded_length,
297
+ k_padded_length,
298
+ n_padded_length,
299
+ ),
300
+ )
301
+ else:
302
+ pad_time = do_bench(
303
+ lambda: pad_bmm(
304
+ mat1_pad,
305
+ mat2_pad,
306
+ m_padded_length,
307
+ k_padded_length,
308
+ n_padded_length,
309
+ ),
310
+ )
311
+
312
+ # Shape padding introduces additional memory ops. Based on microbenchmarks, 1.1x represents a reasonable
313
+ # tradeoff between performance improvement from shape padding and overhead from additional memory ops
314
+ # TODO: Build a learned model which would be better than this heuristic
315
+ should_pad = ori_time > pad_time * 1.1
316
+ set_cached_should_pad(key, should_pad)
317
+
318
+ return should_pad
319
+
320
+
321
+ def mm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor:
322
+ return aten.mm(mat1, mat2)
323
+
324
+
325
+ def should_pad_mm(match: Match) -> bool:
326
+ mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2"))
327
+ return should_pad_common(mat1, mat2) and should_pad_bench(
328
+ mat1, mat2, torch.ops.aten.mm
329
+ )
330
+
331
+
332
+ def mm_replace(mat1: Tensor, mat2: Tensor) -> Tensor:
333
+ m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1))
334
+ k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1))
335
+ n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2))
336
+
337
+ return pad_mm(mat1, mat2, m_padded_length, k_padded_length, n_padded_length)
338
+
339
+
340
+ def pad_mm(
341
+ mat1: Tensor,
342
+ mat2: Tensor,
343
+ m_padded_length: int,
344
+ k_padded_length: int,
345
+ n_padded_length: int,
346
+ ) -> Tensor:
347
+ # mm_replace will go through pad_mm multiple times if multiple dimensions are needed to be padded
348
+ if k_padded_length != 0:
349
+ mat1 = pad_dim(mat1, k_padded_length, 1)
350
+ mat2 = pad_dim(mat2, k_padded_length, 0)
351
+ return torch.ops.aten.mm(mat1, mat2)
352
+ elif n_padded_length != 0:
353
+ mat2 = pad_dim(mat2, n_padded_length, 1)
354
+ return torch.ops.aten.mm(mat1, mat2)[:, :-n_padded_length]
355
+ else:
356
+ mat1 = pad_dim(mat1, m_padded_length, 0)
357
+ return torch.ops.aten.mm(mat1, mat2)[:-m_padded_length, :]
358
+
359
+
360
+ def bmm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor:
361
+ return aten.bmm(mat1, mat2)
362
+
363
+
364
+ def should_pad_bmm(match: Match) -> bool:
365
+ mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2"))
366
+ return should_pad_common(mat1, mat2) and should_pad_bench(
367
+ mat1, mat2, torch.ops.aten.bmm
368
+ )
369
+
370
+
371
+ def bmm_replace(mat1: Tensor, mat2: Tensor) -> Tensor:
372
+ m_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1))
373
+ k_padded_length = get_padded_length(mat1.shape[2], get_alignment_size(mat1))
374
+ n_padded_length = get_padded_length(mat2.shape[2], get_alignment_size(mat2))
375
+
376
+ if m_padded_length != 0 or k_padded_length != 0 or n_padded_length != 0:
377
+ return pad_bmm(mat1, mat2, m_padded_length, k_padded_length, n_padded_length)
378
+
379
+ return aten.bmm(mat1, mat2)
380
+
381
+
382
+ def pad_bmm(
383
+ mat1: Tensor,
384
+ mat2: Tensor,
385
+ m_padded_length: int,
386
+ k_padded_length: int,
387
+ n_padded_length: int,
388
+ ) -> Tensor:
389
+ # bmm_replace will go through pad_bmm multiple times if multiple dimensions are needed to be padded
390
+ if k_padded_length != 0:
391
+ mat1 = pad_dim(mat1, k_padded_length, 2)
392
+ mat2 = pad_dim(mat2, k_padded_length, 1)
393
+
394
+ return aten.bmm(mat1, mat2)
395
+ elif n_padded_length != 0:
396
+ mat2 = pad_dim(mat2, n_padded_length, 2)
397
+ return aten.bmm(mat1, mat2)[:, :, :-n_padded_length].contiguous()
398
+ else:
399
+ mat1 = pad_dim(mat1, m_padded_length, 1)
400
+ return aten.bmm(mat1, mat2)[:, :-m_padded_length, :].contiguous()
401
+
402
+
403
+ @functools.lru_cache(None)
404
+ def _pad_mm_init():
405
+ from .joint_graph import patterns
406
+
407
+ if torch.cuda.is_available():
408
+ # workaround https://github.com/pytorch/pytorch/issues/97894
409
+ device = "cuda"
410
+ else:
411
+ device = "cpu"
412
+
413
+ # sizes/values dont actually matter for initial trace
414
+ # once we get a possible match we re-trace with the actual values and verify the match still holds
415
+
416
+ dim2a = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True)
417
+ dim2b = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True)
418
+
419
+ dim3a = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True)
420
+ dim3b = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True)
421
+
422
+ dim1a = functools.partial(torch.empty, (4), device=device, requires_grad=True)
423
+
424
+ # workaround https://github.com/pytorch/pytorch/issues/97894
425
+ # 0.113377 is a "magic" value that lets us recover the lost input arg relationship
426
+ rep = {"beta": 0.213377, "alpha": 0.113377}
427
+
428
+ for pattern, replacement, args, workaround, extra_check in [
429
+ (
430
+ mm_pattern,
431
+ mm_replace,
432
+ [dim2a(), dim2b()],
433
+ {},
434
+ should_pad_mm,
435
+ ),
436
+ (
437
+ bmm_pattern,
438
+ bmm_replace,
439
+ [dim3a(), dim3b()],
440
+ {},
441
+ should_pad_bmm,
442
+ ),
443
+ (
444
+ addmm_pattern,
445
+ addmm_replace,
446
+ [dim1a(), dim2a(), dim2b()],
447
+ rep,
448
+ should_pad_addmm,
449
+ ),
450
+ ]:
451
+ assert isinstance(workaround, dict) # mypy is unable to infer the type properly
452
+ register_replacement(
453
+ pattern,
454
+ replacement,
455
+ args,
456
+ joint_fwd_bwd,
457
+ patterns,
458
+ extra_check=extra_check,
459
+ scalar_workaround=workaround,
460
+ )
461
+ register_replacement(
462
+ pattern,
463
+ replacement,
464
+ args,
465
+ fwd_only,
466
+ patterns,
467
+ extra_check=extra_check,
468
+ scalar_workaround=workaround,
469
+ )