debug.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. import collections
  2. import contextlib
  3. import copy
  4. import dataclasses
  5. import functools
  6. import io
  7. import itertools
  8. import json
  9. import logging
  10. import os
  11. import os.path
  12. import pickle
  13. import pstats
  14. import shutil
  15. import traceback
  16. from collections.abc import Iterator, Sequence
  17. from typing import Any, Callable, IO, Optional, Union
  18. from unittest.mock import patch
  19. import torch
  20. from functorch.compile import draw_graph, get_aot_graph_name, get_graph_being_compiled
  21. from torch import fx as fx
  22. from torch._dynamo.repro.after_aot import save_graph_repro
  23. from torch._dynamo.utils import get_debug_dir
  24. from torch._inductor import utils
  25. from torch._logging import getArtifactLogger
  26. from torch._logging._internal import trace_structured
  27. from torch._utils_internal import signpost_event
  28. from torch.fx.graph_module import GraphModule
  29. from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata
  30. from torch.fx.passes.tools_common import legalize_graph
  31. from torch.types import FileLike
  32. from torch.utils._ordered_set import OrderedSet
  33. from torch.utils._pytree import tree_map
  34. from . import config, ir # noqa: F811, this is needed
  35. from .ir import ExternKernel
  36. from .scheduler import (
  37. BaseSchedulerNode,
  38. FusedSchedulerNode,
  39. NopKernelSchedulerNode,
  40. OutputNode,
  41. SchedulerNode,
  42. )
  43. from .virtualized import V
  44. log = logging.getLogger(__name__)
  45. # Graph execution tracking for debugging
  46. GRAPH_EXECUTION_ORDER: Optional[list[dict[str, object]]] = None
  47. RECORD_GRAPH_EXECUTION: bool = False
  48. GRAPH_COMPILE_IDS: Optional[dict[int, Optional[str]]] = None
  49. ir_pre_fusion_log = getArtifactLogger(__name__, "ir_pre_fusion")
  50. ir_post_fusion_log = getArtifactLogger(__name__, "ir_post_fusion")
  51. SchedulerNodeList = list[Any]
  52. BufMeta = collections.namedtuple("BufMeta", ["name", "n_origin"])
  53. GRAPHVIZ_COMMAND_SCALABLE = ["dot", "-Gnslimit=2", "-Gnslimit1=2", "-Gmaxiter=5000"]
  54. @functools.cache
  55. def has_dot() -> bool:
  56. return shutil.which("dot") is not None
  57. def draw_buffers(
  58. nodes: list[BaseSchedulerNode],
  59. print_graph: bool = False,
  60. fname: Optional[str] = None,
  61. ) -> None:
  62. """
  63. Draw a graph in fname.svg.
  64. """
  65. if not has_dot():
  66. log.warning("draw_buffers() requires `graphviz` package")
  67. return
  68. if fname is None:
  69. fname = get_graph_being_compiled()
  70. graph = create_fx_from_snodes(nodes)
  71. for node in graph.nodes:
  72. if "fusion_meta" not in node.meta:
  73. continue
  74. group = node.meta["fusion_meta"].group
  75. if isinstance(group, tuple):
  76. if isinstance(group[1], int):
  77. group = (group[1],)
  78. else:
  79. group = group[1]
  80. # gather meta data
  81. dtype = None
  82. if isinstance(node, ir.ComputedBuffer):
  83. dtype = node.data.dtype
  84. metadata = TensorMetadata(group, dtype, None, None, None, None, None) # type: ignore[arg-type]
  85. node.meta["tensor_meta"] = metadata
  86. if print_graph:
  87. print(graph)
  88. gm = GraphModule({}, graph)
  89. legalize_graph(gm)
  90. gm.graph.lint()
  91. draw_graph(
  92. gm, fname, clear_meta=False, dot_graph_shape=config.trace.dot_graph_shape
  93. )
  94. def create_fx_from_snodes(snodes: list[BaseSchedulerNode]) -> fx.Graph:
  95. """
  96. Creates a FX Graph from a list of SchedulerNode objects.
  97. """
  98. def get_fake_func(name: str) -> Callable[..., int]:
  99. def func1(*args: Any) -> int:
  100. return 0
  101. func1.__name__ = name
  102. return func1
  103. FusionMeta = collections.namedtuple("FusionMeta", ["group", "snode", "type"])
  104. buf_to_fx_node = {}
  105. node_to_fx_node = {}
  106. graph = torch.fx.Graph()
  107. first_node = None
  108. outputs = []
  109. group: Any = None
  110. # create call_function node for each Buffer and Kernel
  111. for snode in snodes:
  112. if snode.is_extern():
  113. node_type = "extern"
  114. group = node_type
  115. elif snode.is_template():
  116. node_type = "template"
  117. group = node_type
  118. elif isinstance(snode, NopKernelSchedulerNode):
  119. node_type = "nop"
  120. group = node_type
  121. elif isinstance(snode, SchedulerNode):
  122. node_type = "compute"
  123. group = snode.group
  124. elif isinstance(snode, FusedSchedulerNode):
  125. node_type = "fused"
  126. group = snode.group
  127. else:
  128. raise RuntimeError("Unknown node type")
  129. fused_name = torch._inductor.utils.get_fused_kernel_name(
  130. snode.get_nodes(), "original_aten"
  131. )
  132. func_name = f"{node_type}: {fused_name}"
  133. node_func = get_fake_func(func_name)
  134. kwargs = {}
  135. if hasattr(snode, "get_device"):
  136. kwargs = {"device": snode.get_device()}
  137. fx_node = graph.call_function(node_func, args=(), kwargs=kwargs) # type: ignore[arg-type]
  138. def in_output(snode: Union[BaseSchedulerNode, FusedSchedulerNode]) -> bool:
  139. if isinstance(snode, FusedSchedulerNode):
  140. return any(in_output(x) for x in snode.snodes)
  141. return any(
  142. isinstance(user.node, OutputNode)
  143. for buf in snode.get_outputs()
  144. for user in buf.users
  145. )
  146. if in_output(snode):
  147. outputs.append(fx_node)
  148. name = snode.get_name()
  149. fx_node.name = name
  150. fx_node.meta["fusion_meta"] = FusionMeta(group, snode, node_type)
  151. node_to_fx_node[name] = fx_node
  152. for buf in snode.get_outputs():
  153. buf_to_fx_node[buf.get_name()] = fx_node
  154. if first_node is None:
  155. first_node = fx_node
  156. # create edges between nodes
  157. for snode in snodes:
  158. name = snode.get_name()
  159. deps = snode.read_writes.reads
  160. fx_node = node_to_fx_node[name]
  161. new_args = []
  162. for dep in deps:
  163. if dep.name in buf_to_fx_node:
  164. dep_node = buf_to_fx_node[dep.name]
  165. else:
  166. with graph.inserting_before(first_node):
  167. dep_node = graph.placeholder(dep.name)
  168. buf_to_fx_node[dep.name] = dep_node
  169. if dep_node == fx_node: # to avoid cycles
  170. continue
  171. new_args.append(dep_node)
  172. fx_node.args = tuple(new_args)
  173. graph.output(outputs[0] if len(outputs) == 1 else tuple(outputs))
  174. return graph
  175. def update_orig_fx_node_name_to_buf_name(
  176. nodes: Optional[SchedulerNodeList],
  177. node_name_to_buf_name: dict[str, str],
  178. parent_buf_name: Optional[str] = None,
  179. n_origins: int = 0,
  180. ) -> None:
  181. if nodes is None:
  182. return
  183. for node in nodes:
  184. # for FusedSchedulerNode, traverse recursively into get_nodes()
  185. buf_name = node.get_name()
  186. children_nodes = node.get_nodes()
  187. if children_nodes is not None and len(children_nodes) > 1:
  188. update_orig_fx_node_name_to_buf_name(
  189. children_nodes,
  190. node_name_to_buf_name,
  191. buf_name if parent_buf_name is None else parent_buf_name,
  192. )
  193. continue
  194. else:
  195. assert len(children_nodes) == 1 and children_nodes[0] == node
  196. ir_node = node.node
  197. if ir_node is None or ir_node.origins is None:
  198. continue
  199. for origin in ir_node.origins:
  200. node_name = origin.name
  201. # when buf1 and buf2 both have origin=node1
  202. # we draw node1 according to buf1
  203. if node_name not in node_name_to_buf_name:
  204. node_name_to_buf_name[node_name] = (
  205. buf_name if parent_buf_name is None else parent_buf_name
  206. )
  207. def get_node_name_to_buf_meta(
  208. node_name_to_buf_name: dict[str, str],
  209. ) -> dict[str, BufMeta]:
  210. buf_name_to_n_node = {}
  211. for node_name, buf_name in node_name_to_buf_name.items():
  212. if buf_name not in buf_name_to_n_node:
  213. buf_name_to_n_node[buf_name] = OrderedSet([node_name])
  214. else:
  215. buf_name_to_n_node[buf_name].add(node_name)
  216. node_name_to_buf_meta = {}
  217. for node_name, buf_name in node_name_to_buf_name.items():
  218. n_node = len(buf_name_to_n_node[buf_name])
  219. node_name_to_buf_meta[node_name] = BufMeta(buf_name, n_node)
  220. return node_name_to_buf_meta
  221. def annotate_orig_fx_with_snodes(
  222. gm: torch.fx.GraphModule,
  223. snodes: SchedulerNodeList,
  224. ) -> None:
  225. """
  226. Creates a FX Graph from a list of SchedulerNode objects.
  227. """
  228. node_name_to_buf_name: dict[str, str] = {}
  229. update_orig_fx_node_name_to_buf_name(snodes, node_name_to_buf_name)
  230. if node_name_to_buf_name is None:
  231. return
  232. node_name_to_buf_meta = get_node_name_to_buf_meta(node_name_to_buf_name)
  233. for node in gm.graph.nodes:
  234. if node.name in node_name_to_buf_meta:
  235. node.meta["buf_meta"] = node_name_to_buf_meta.get(node.name)
  236. @contextlib.contextmanager
  237. def enable_aot_logging() -> Iterator[None]:
  238. compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
  239. import torch._functorch.aot_autograd
  240. log = logging.getLogger(torch._functorch.aot_autograd.__name__)
  241. stack = contextlib.ExitStack()
  242. if not compile_debug:
  243. try:
  244. yield
  245. finally:
  246. stack.close()
  247. return
  248. # Enable all graphs to be logged to a file by setting the flags to True
  249. # and the log level of the file logger to DEBUG
  250. stack.enter_context(patch("functorch.compile.config.debug_partitioner", True))
  251. path = os.path.join(get_debug_dir(), "torchinductor")
  252. os.makedirs(path, exist_ok=True)
  253. fh = logging.FileHandler(
  254. os.path.join(
  255. path,
  256. f"aot_{get_aot_graph_name()}_debug.log",
  257. )
  258. )
  259. fh.setLevel(logging.DEBUG)
  260. fh.setFormatter(
  261. logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s")
  262. )
  263. log.addHandler(fh)
  264. try:
  265. yield
  266. finally:
  267. log.removeHandler(fh)
  268. stack.close()
  269. # Used for provenance tracking
  270. # They are not stored in DebugContext because they are not set in
  271. # _inductor_triton_kernel_to_post_grad_node_info's Debug Context
  272. _inductor_post_to_pre_grad_nodes: dict[str, dict[str, list[str]]] = {}
  273. _inductor_triton_kernel_to_post_grad_node_info: dict[str, list[str]] = {}
  274. _pre_grad_graph_id: Optional[int] = None
  275. _inductor_pre_grad_node_stack_trace: dict[str, str] = {}
  276. _inductor_kernel_stack_trace: dict[str, list[str]] = {}
  277. _inductor_kernel_provenance_debug_handle: int = 0
  278. def reset_inductor_kernel_provenance_debug_handle() -> None:
  279. global _inductor_kernel_provenance_debug_handle
  280. _inductor_kernel_provenance_debug_handle = 0
  281. @contextlib.contextmanager
  282. def reset_provenance_globals() -> Iterator[None]:
  283. """Context manager that resets provenance tracking globals upon entering
  284. and restores their original values when exiting."""
  285. global _pre_grad_graph_id
  286. global _inductor_post_to_pre_grad_nodes
  287. global _inductor_triton_kernel_to_post_grad_node_info
  288. global _inductor_pre_grad_node_stack_trace
  289. global _inductor_kernel_stack_trace
  290. # Store original values
  291. original_pre_grad_graph_id = _pre_grad_graph_id
  292. original_post_to_pre_grad_nodes = _inductor_post_to_pre_grad_nodes.copy()
  293. original_triton_kernel_to_post_grad_node_info = (
  294. _inductor_triton_kernel_to_post_grad_node_info.copy()
  295. )
  296. original_inductor_pre_grad_node_stack_trace = (
  297. _inductor_pre_grad_node_stack_trace.copy()
  298. )
  299. original_inductor_kernel_stack_trace = _inductor_kernel_stack_trace.copy()
  300. # Reset to default values
  301. _pre_grad_graph_id = -1
  302. _inductor_post_to_pre_grad_nodes = {}
  303. _inductor_triton_kernel_to_post_grad_node_info = {}
  304. _inductor_pre_grad_node_stack_trace = {}
  305. _inductor_kernel_stack_trace = {}
  306. try:
  307. yield
  308. finally:
  309. # Restore original values
  310. _pre_grad_graph_id = original_pre_grad_graph_id
  311. _inductor_post_to_pre_grad_nodes = original_post_to_pre_grad_nodes
  312. _inductor_triton_kernel_to_post_grad_node_info = (
  313. original_triton_kernel_to_post_grad_node_info
  314. )
  315. _inductor_kernel_stack_trace = original_inductor_kernel_stack_trace
  316. _inductor_pre_grad_node_stack_trace = (
  317. original_inductor_pre_grad_node_stack_trace
  318. )
  319. class DebugContext:
  320. _counter = itertools.count()
  321. @staticmethod
  322. def create_debug_dir(folder_name: str) -> Optional[str]:
  323. debug_dir = config.trace.debug_dir or get_debug_dir()
  324. for n in DebugContext._counter:
  325. dirname = os.path.join(
  326. debug_dir,
  327. "torchinductor",
  328. f"{folder_name}.{n}",
  329. )
  330. if not os.path.exists(dirname):
  331. os.makedirs(dirname)
  332. return dirname
  333. return None
  334. def __init__(self) -> None:
  335. self._prof = None
  336. self._path = None
  337. self._stack = contextlib.ExitStack()
  338. def copy(self, new_path: str) -> None:
  339. if not self._path:
  340. return
  341. assert new_path.endswith(".debug"), new_path
  342. from filelock import FileLock
  343. try:
  344. with FileLock(f"{new_path}.lock"):
  345. if os.path.exists(new_path):
  346. shutil.rmtree(new_path)
  347. shutil.copytree(self._path, new_path)
  348. except OSError:
  349. log.warning(
  350. "Failed to copy debug files from %s to %s", self._path, new_path
  351. )
  352. def fopen(
  353. self,
  354. filename: str,
  355. write_mode: str = "w",
  356. *args: Any,
  357. **kwargs: Any,
  358. ) -> IO[Any]:
  359. assert self._path
  360. return open(os.path.join(self._path, filename), write_mode, *args, **kwargs)
  361. @contextlib.contextmanager
  362. def fopen_context(
  363. self,
  364. filename: str,
  365. write_mode: str = "w",
  366. *args: Any,
  367. **kwargs: Any,
  368. ) -> Iterator[IO[Any]]:
  369. assert self._path
  370. with open(os.path.join(self._path, filename), write_mode, *args, **kwargs) as f:
  371. yield f
  372. def filename(self, suffix: str) -> str:
  373. assert self._path
  374. return os.path.join(self._path, suffix)
  375. def upload_tar(self) -> None:
  376. if config.trace.upload_tar is not None:
  377. import tarfile
  378. assert self._path
  379. tar_file = os.path.join(
  380. self._path, f"{os.path.basename(self._path)}.tar.gz"
  381. )
  382. with tarfile.open(tar_file, "w:gz") as tar:
  383. tar.add(self._path, arcname=os.path.basename(self._path))
  384. config.trace.upload_tar(tar_file)
  385. def __enter__(self) -> None:
  386. if config.debug:
  387. log = logging.getLogger("torch._dynamo")
  388. prev_level = log.level
  389. log.setLevel(logging.DEBUG)
  390. def reset_log_level(level: Any) -> None:
  391. log.setLevel(level)
  392. self._stack.callback(reset_log_level, prev_level)
  393. self._stack.enter_context(V.set_debug_handler(self))
  394. if not config.trace.enabled:
  395. return
  396. self._path = self.create_debug_dir(get_aot_graph_name()) # type: ignore[assignment]
  397. if config.trace.debug_log:
  398. self._setup_log_capture("debug.log", logging.DEBUG)
  399. if config.trace.info_log:
  400. self._setup_log_capture("info.log", logging.INFO)
  401. def _setup_log_capture(
  402. self,
  403. filename: str,
  404. level: int,
  405. ) -> None:
  406. log = logging.getLogger("torch._inductor")
  407. fd = self._stack.enter_context(self.fopen(filename))
  408. ch = logging.StreamHandler(fd)
  409. ch.setLevel(level)
  410. ch.setFormatter(
  411. logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s")
  412. )
  413. log.addHandler(ch)
  414. log.setLevel(min(log.level, level))
  415. self._stack.callback(log.removeHandler, ch)
  416. def __exit__(
  417. self,
  418. exc_type: Optional[type[BaseException]],
  419. exc_val: Optional[BaseException],
  420. exc_tb: Optional[Any],
  421. ) -> None:
  422. if self._prof:
  423. self._prof.disable()
  424. self._save_profile_data()
  425. if self._path:
  426. self.upload_tar()
  427. log.warning("%s debug trace: %s", get_graph_being_compiled(), self._path)
  428. self._stack.close()
  429. def _save_profile_data(self) -> None:
  430. assert self._prof
  431. self._prof.dump_stats(self.filename("compile.prof"))
  432. with self.fopen("compile.stats") as fd:
  433. stats = pstats.Stats(self._prof, stream=fd)
  434. stats.strip_dirs()
  435. stats.sort_stats("cumtime")
  436. stats.print_stats(100)
  437. stats.sort_stats("tottime")
  438. stats.print_stats(100)
  439. def __getattr__(self, name: str) -> Optional[Callable[..., None]]:
  440. if config.trace.enabled and getattr(config.trace, name):
  441. try:
  442. return getattr(DebugFormatter(self), name)
  443. except Exception:
  444. log.warning("Ignoring exception in debug code", exc_info=True)
  445. return None
  446. else:
  447. def ignored(*args: Any, **kwargs: Any) -> None:
  448. pass
  449. return ignored
  450. class DebugFormatter:
  451. def __init__(self, handler: DebugContext) -> None:
  452. self.fopen = handler.fopen
  453. self.fopen_context = handler.fopen_context
  454. self.filename = handler.filename
  455. self.handler = handler
  456. def fx_graph(
  457. self,
  458. gm: torch.fx.GraphModule,
  459. inputs: list[torch.Tensor],
  460. ) -> None:
  461. with self.fopen("fx_graph_runnable.py") as fd:
  462. save_dir = None
  463. if torch._inductor.config.trace.save_real_tensors:
  464. inputs = torch._subclasses.fake_utils.try_convert_fake_to_real(inputs)
  465. save_dir = os.path.dirname(fd.name)
  466. # dont try to use stable hash torchinductor compilation if saving real tensors
  467. # and avoid recursively trying to save real tensors inside of the inductor compilation
  468. # regardless
  469. stable_hash = torch._inductor.config.trace.save_real_tensors
  470. with torch._inductor.config.patch(
  471. {"trace.enabled": False, "trace.save_real_tensors": False}
  472. ):
  473. save_graph_repro(
  474. fd,
  475. gm,
  476. inputs,
  477. "inductor",
  478. save_dir=save_dir,
  479. stable_hash=stable_hash,
  480. )
  481. with self.fopen("fx_graph_readable.py") as fd:
  482. fd.write(gm.print_readable(print_output=False))
  483. def fx_graph_transformed(
  484. self,
  485. gm: torch.fx.GraphModule,
  486. inputs: list[torch.Tensor],
  487. ) -> None:
  488. with self.fopen("fx_graph_transformed.py") as fd:
  489. fd.write(gm.print_readable(print_output=False))
  490. def ir_pre_fusion(self, nodes: SchedulerNodeList) -> None:
  491. with self.fopen("ir_pre_fusion.txt") as fd:
  492. fd.write(self._write_ir(nodes))
  493. def ir_post_fusion(self, nodes: SchedulerNodeList) -> None:
  494. with self.fopen("ir_post_fusion.txt") as fd:
  495. fd.write(self._write_ir(nodes))
  496. @staticmethod
  497. def _write_ir(nodes: SchedulerNodeList) -> str:
  498. buf = io.StringIO()
  499. for node in nodes:
  500. buf.write(node.debug_str())
  501. buf.write("\n\n\n")
  502. return buf.getvalue()
  503. def graph_diagram(self, nodes: SchedulerNodeList) -> None:
  504. draw_buffers(nodes, fname=self.filename("graph_diagram.svg"))
  505. def draw_orig_fx_graph(
  506. self,
  507. gm: torch.fx.GraphModule,
  508. nodes: SchedulerNodeList,
  509. ) -> None:
  510. annotate_orig_fx_with_snodes(gm, nodes)
  511. draw_graph(
  512. gm,
  513. fname=self.filename("orig_fx_graph_diagram.svg"),
  514. clear_meta=False,
  515. prog=GRAPHVIZ_COMMAND_SCALABLE,
  516. parse_stack_trace=True,
  517. dot_graph_shape=config.trace.dot_graph_shape,
  518. )
  519. def output_code(self, filename: str, extension: str = "py") -> None:
  520. shutil.copy(filename, self.filename(f"output_code.{extension}"))
  521. def log_autotuning_results(
  522. self,
  523. name: str,
  524. input_nodes: list[ir.IRNode],
  525. timings: dict["ChoiceCaller", float], # type: ignore[name-defined] # noqa: F821
  526. elapse: float,
  527. precompile_elapse: float,
  528. prescreening_elapse: Optional[float],
  529. ) -> None:
  530. from .ir import FixedLayout
  531. def build_node_info(node: ir.IRNode) -> dict[str, str]:
  532. if hasattr(node, "name"):
  533. node_name = node.name
  534. else:
  535. node_name = ""
  536. node_info = {
  537. "name": node_name,
  538. "type": type(node).__name__,
  539. }
  540. try:
  541. layout = node.get_output_spec()
  542. if isinstance(layout, FixedLayout):
  543. offset = 0
  544. try:
  545. offset = int(layout.offset)
  546. except Exception:
  547. try:
  548. offset = V.graph.sizevars.size_hint(
  549. layout.offset, fallback=0
  550. )
  551. except Exception:
  552. pass
  553. static_layout = FixedLayout(
  554. layout.device,
  555. dtype=layout.dtype,
  556. size=[*V.graph.sizevars.size_hints(layout.size)],
  557. stride=[*V.graph.sizevars.size_hints(layout.stride)],
  558. offset=offset,
  559. )
  560. node_info["layout"] = str(static_layout)
  561. else:
  562. node_info["layout"] = str(layout)
  563. except Exception:
  564. pass
  565. try:
  566. node_info["dtype"] = str(node.get_dtype())
  567. except Exception:
  568. pass
  569. try:
  570. node_info["device"] = str(node.get_device())
  571. except Exception:
  572. pass
  573. try:
  574. node_info["stride"] = str(
  575. V.graph.sizevars.size_hints(node.get_stride())
  576. )
  577. except Exception:
  578. pass
  579. try:
  580. node_info["size"] = str(V.graph.sizevars.size_hints(node.get_size())) # type: ignore[arg-type]
  581. except Exception:
  582. pass
  583. try:
  584. node_info["numel"] = str(V.graph.sizevars.size_hint(node.get_numel()))
  585. except Exception:
  586. pass
  587. if hasattr(node, "data") and isinstance(node.data, ir.IRNode):
  588. node_info["data"] = build_node_info(node.data)
  589. return node_info
  590. general_properties = {
  591. "op_name": name,
  592. "cuda_device_name": torch.cuda.get_device_name(),
  593. "cuda_device_count": torch.cuda.device_count(),
  594. "input_nodes": [build_node_info(node) for node in input_nodes],
  595. "autotuning_time": elapse,
  596. "precompile_time": precompile_elapse,
  597. "prescreening_time": prescreening_elapse,
  598. }
  599. with self.fopen_context(
  600. "autotuning_result_json_list.txt", "at", encoding="utf-8"
  601. ) as fd:
  602. for caller, time in timings.items():
  603. info_dict = dict(caller.info_dict())
  604. info_dict.update(general_properties)
  605. info_dict["benchmark_result"] = time
  606. json.dump(info_dict, fd)
  607. fd.write("\n")
  608. def log_ir_pre_fusion(nodes: SchedulerNodeList) -> None:
  609. if ir_pre_fusion_log.isEnabledFor(logging.INFO):
  610. ir_pre_fusion_log.info("BEFORE FUSION\n%s", DebugFormatter._write_ir(nodes))
  611. V.debug.ir_pre_fusion(nodes)
  612. def log_ir_post_fusion(nodes: SchedulerNodeList) -> None:
  613. if ir_post_fusion_log.isEnabledFor(logging.INFO):
  614. ir_post_fusion_log.info("AFTER FUSION\n%s", DebugFormatter._write_ir(nodes))
  615. V.debug.ir_post_fusion(nodes)
  616. def _dump_collective_schedule(schedule: list[Union[str, None]]) -> None:
  617. try:
  618. trace_structured(
  619. "artifact",
  620. metadata_fn=lambda: {
  621. "name": "inductor_collective_schedule",
  622. "encoding": "json",
  623. },
  624. payload_fn=lambda: schedule,
  625. )
  626. except Exception:
  627. log.debug(
  628. "Failed to log inductor_collective_schedule via structured logging",
  629. exc_info=True,
  630. )
  631. def log_collective_schedule(nodes: Sequence[BaseSchedulerNode]) -> None:
  632. schedule = [
  633. getattr(op, "python_kernel_name", None)
  634. for node in nodes
  635. if isinstance(op := getattr(node, "node", None), ir._CollectiveKernel)
  636. ]
  637. # Only log when there is at least one collective op
  638. if schedule:
  639. _dump_collective_schedule(schedule)
  640. def log_runtime_and_tensor_meta(node_runtimes: Sequence[tuple[Any, float]]) -> None:
  641. """Log per-op runtime estimates and output tensor metadata for TLParse."""
  642. try:
  643. to_size_hints = V.graph.sizevars.size_hints
  644. def to_list(x: Optional[Sequence[Any]]) -> list[Any]:
  645. return list(to_size_hints(x)) if x is not None else []
  646. def dtype_to_str(dtype: Any) -> Optional[str]:
  647. if dtype is None:
  648. return None
  649. s = str(dtype)
  650. s = s.removeprefix("torch.")
  651. return s
  652. ops: list[dict[str, Any]] = []
  653. for s, runtime_ns in node_runtimes:
  654. name = getattr(s.node, "python_kernel_name", s.get_name())
  655. op_type = "collective" if utils.is_collective(s.node) else "compute"
  656. # Build outputs metadata if available
  657. outputs: list[dict[str, Any]] = []
  658. try:
  659. for buf in s.get_outputs():
  660. irnode = buf.node
  661. shape = irnode.maybe_get_size()
  662. stride = (
  663. irnode.get_stride()
  664. if isinstance(irnode.layout, ir.Layout)
  665. else None
  666. )
  667. dtype = irnode.maybe_get_dtype()
  668. outputs.append(
  669. {
  670. "shape": to_list(shape),
  671. "stride": to_list(stride),
  672. "dtype": dtype_to_str(dtype),
  673. }
  674. )
  675. except Exception:
  676. pass
  677. ops.append(
  678. {
  679. "name": name,
  680. "type": op_type,
  681. "estimated_runtime_ns": runtime_ns,
  682. "outputs": outputs,
  683. }
  684. )
  685. trace_structured(
  686. "artifact",
  687. metadata_fn=lambda: {
  688. "name": "inductor_runtime_and_tensor_meta",
  689. "encoding": "json",
  690. },
  691. payload_fn=lambda: {"ops": ops},
  692. )
  693. except Exception:
  694. log.debug("Failed to log inductor_runtime_and_tensor_meta", exc_info=True)
  695. def log_graph_execution() -> None:
  696. """Emit a structured artifact with the graph execution order."""
  697. if not GRAPH_EXECUTION_ORDER:
  698. return
  699. try:
  700. trace_structured(
  701. "artifact",
  702. metadata_fn=lambda: {
  703. "name": "graph_execution",
  704. "encoding": "json",
  705. },
  706. payload_fn=lambda: {"graph_execution_order": GRAPH_EXECUTION_ORDER},
  707. )
  708. except Exception:
  709. log.debug("Failed to log graph_execution", exc_info=True)
  710. @contextlib.contextmanager
  711. def record_and_log_graph_execution_order() -> Iterator[None]:
  712. """Record graph execution order and log it once on exit."""
  713. global RECORD_GRAPH_EXECUTION, GRAPH_EXECUTION_ORDER, GRAPH_COMPILE_IDS
  714. GRAPH_EXECUTION_ORDER = []
  715. GRAPH_COMPILE_IDS = {}
  716. RECORD_GRAPH_EXECUTION = True
  717. try:
  718. yield
  719. finally:
  720. log_graph_execution()
  721. RECORD_GRAPH_EXECUTION = False
  722. GRAPH_EXECUTION_ORDER = None
  723. GRAPH_COMPILE_IDS = None
  724. @dataclasses.dataclass
  725. class TensorMetadataHolder:
  726. tensor_metadata: TensorMetadata
  727. device: torch.device
  728. save_args_cnt = itertools.count()
  729. def create_mapping_pre_post_grad_nodes(
  730. pre_grad_graph_id: Optional[int],
  731. post_to_pre_grad_nodes_json: dict[str, Any],
  732. ) -> dict[str, dict[str, list[str]]]:
  733. """
  734. Create bidirectional mappings between pre_grad graph nodes
  735. and post_grad graph code nodes, and vice versa.
  736. """
  737. # return a dummy dict if there's any error
  738. empty_return: dict[str, dict[str, list[str]]] = {
  739. "preToPost": {},
  740. "postToPre": {},
  741. }
  742. if not isinstance(post_to_pre_grad_nodes_json, dict):
  743. log.error("Provenance tacking error: post_to_pre_grad_nodes_json is not a dict")
  744. return empty_return
  745. if not isinstance(pre_grad_graph_id, int):
  746. # pre_grad_graph_id may be empty if there's no pre_grad graph
  747. # and there's only a backward graph from backward pass engine
  748. return empty_return
  749. pre_to_post: dict[str, Any] = collections.defaultdict(OrderedSet)
  750. post_to_pre: dict[str, Any] = collections.defaultdict(OrderedSet)
  751. try:
  752. def check_format(node: dict[str, Any]) -> bool:
  753. if not isinstance(node, dict):
  754. log.error(
  755. "Provenance tacking error: node provenance in post_to_pre_grad_nodes_json is not a dict"
  756. )
  757. return False
  758. if "graph_id" not in node or "name" not in node or "from_node" not in node:
  759. log.error(
  760. "Provenance tacking error: node provenance in post_to_pre_grad_nodes_json has wrong format"
  761. )
  762. return False
  763. return True
  764. for outer_key, node_array in post_to_pre_grad_nodes_json.items():
  765. if not isinstance(node_array, list):
  766. log.error(
  767. "Provenance tacking error: post_to_pre_grad_nodes_json value is not a list"
  768. )
  769. return empty_return
  770. for node in node_array:
  771. if not check_format(node):
  772. return empty_return
  773. # Check the current node first
  774. if node.get("graph_id") == pre_grad_graph_id:
  775. pre_to_post[node["name"]].add(outer_key)
  776. post_to_pre[outer_key].add(node["name"])
  777. # Check nested from_node array recursively, add node with the right graph_id to the map
  778. stack = [(n, outer_key) for n in node.get("from_node", [])]
  779. while stack:
  780. current_node, parent_key = stack.pop()
  781. if not check_format(current_node):
  782. return empty_return
  783. if current_node.get("graph_id") == pre_grad_graph_id:
  784. pre_to_post[current_node["name"]].add(parent_key)
  785. post_to_pre[parent_key].add(current_node["name"])
  786. stack.extend(
  787. (n, parent_key) for n in current_node.get("from_node", [])
  788. )
  789. def convert_sets_to_lists(d: dict[str, Any]) -> None:
  790. for key in d:
  791. d[key] = list(d[key])
  792. d = dict(d)
  793. # convert to list because set is not JSON serializable
  794. convert_sets_to_lists(pre_to_post)
  795. convert_sets_to_lists(post_to_pre)
  796. return {
  797. "preToPost": pre_to_post,
  798. "postToPre": post_to_pre,
  799. }
  800. except Exception as e:
  801. # Since this is just logging code, it should never interfere with regular
  802. # program execution, so we use this try-except to guard against any error
  803. signpost_event(
  804. "inductor",
  805. "provenance_tracking_error",
  806. {
  807. "function": "create_mapping_pre_post_grad_nodes",
  808. "error_msg": str(e),
  809. "stack_trace": traceback.format_exc(),
  810. },
  811. )
  812. log.error("post_to_pre_grad_nodes_json: %s", post_to_pre_grad_nodes_json)
  813. log.error("pre_grad_graph_id: %s", pre_grad_graph_id)
  814. return empty_return
  815. def create_node_mapping_kernel_to_post_grad(
  816. triton_kernel_to_post_grad_json: dict[str, Any],
  817. ) -> dict[str, dict[str, Any]]:
  818. """Create bidirectional mappings between triton kernel name and post_grad
  819. graph code nodes, and vice versa.
  820. """
  821. # return a dummy dict if there's any error
  822. empty_return: dict[str, dict[str, Any]] = {
  823. "cppCodeToPost": {},
  824. "postToCppCode": {},
  825. }
  826. if not isinstance(triton_kernel_to_post_grad_json, dict):
  827. log.error(
  828. "Provenance tacking error: triton_kernel_to_post_grad_json is not a dict"
  829. )
  830. return empty_return
  831. post_to_cpp_code: dict[str, Any] = collections.defaultdict(OrderedSet)
  832. try:
  833. for outer_key, node_array in triton_kernel_to_post_grad_json.items():
  834. if not isinstance(node_array, list):
  835. log.error(
  836. "Provenance tacking error: triton_kernel_to_post_grad_json value is not a list"
  837. )
  838. return empty_return
  839. for curr_node in node_array:
  840. post_to_cpp_code[curr_node].add(outer_key)
  841. def convert_sets_to_lists(d: dict[str, Any]) -> None:
  842. for key in d:
  843. d[key] = list(d[key])
  844. d = dict(d)
  845. # convert to list because set is not JSON serializable
  846. convert_sets_to_lists(post_to_cpp_code)
  847. return {
  848. "cppCodeToPost": triton_kernel_to_post_grad_json,
  849. "postToCppCode": post_to_cpp_code,
  850. }
  851. except Exception as e:
  852. # Since this is just logging code, it should never interfere with regular
  853. # program execution, so we use this try-except to guard against any error
  854. signpost_event(
  855. "inductor",
  856. "provenance_tracking_error",
  857. {
  858. "function": "create_mapping_kernel_to_post_grad",
  859. "error_msg": str(e),
  860. "stack_trace": traceback.format_exc(),
  861. },
  862. )
  863. log.error(
  864. "triton_kernel_to_post_grad_json: %s", triton_kernel_to_post_grad_json
  865. )
  866. return empty_return
  867. def dump_inductor_provenance_info() -> dict[str, Any]:
  868. try:
  869. global _pre_grad_graph_id
  870. global _inductor_post_to_pre_grad_nodes
  871. global _inductor_triton_kernel_to_post_grad_node_info
  872. node_mapping: dict[str, Any] = {}
  873. if _pre_grad_graph_id:
  874. node_mapping_kernel = create_node_mapping_kernel_to_post_grad(
  875. _inductor_triton_kernel_to_post_grad_node_info
  876. )
  877. node_mapping = {
  878. **_inductor_post_to_pre_grad_nodes,
  879. **node_mapping_kernel,
  880. }
  881. if config.trace.enabled:
  882. with V.debug.fopen(
  883. "inductor_provenance_tracking_node_mappings.json", "w"
  884. ) as fd:
  885. json.dump(node_mapping, fd)
  886. # we need to update the node mapping version when node mapping format changes
  887. # so the tlparse tool knows which node mapping version it is looking at
  888. node_mapping["version"] = 2.0
  889. return node_mapping
  890. except Exception as e:
  891. # Since this is just debugging, it should never interfere with regular
  892. # program execution, so we use this try-except to guard against any error
  893. signpost_event(
  894. "inductor",
  895. "provenance_tracking_error",
  896. {
  897. "function": "dump_inductor_provenance_info",
  898. "error_msg": str(e),
  899. "stack_trace": traceback.format_exc(),
  900. },
  901. )
  902. return {}
  903. def create_kernel_information_json() -> dict[str, dict[str, list[str]]]:
  904. """Create kernel information JSON"""
  905. try:
  906. global _inductor_post_to_pre_grad_nodes
  907. global _inductor_kernel_stack_trace
  908. global _inductor_triton_kernel_to_post_grad_node_info
  909. post_to_pre = _inductor_post_to_pre_grad_nodes.get("postToPre", {})
  910. all_kernels = OrderedSet(_inductor_kernel_stack_trace.keys()) | OrderedSet(
  911. _inductor_triton_kernel_to_post_grad_node_info.keys()
  912. )
  913. result = {}
  914. for kernel_name in all_kernels:
  915. post_grad_nodes = _inductor_triton_kernel_to_post_grad_node_info.get(
  916. kernel_name, []
  917. )
  918. pre_grad_nodes: OrderedSet[str] = OrderedSet()
  919. for post_node in post_grad_nodes:
  920. pre_grad_nodes.update(post_to_pre.get(post_node, []))
  921. result[kernel_name] = {
  922. "stack_traces": _inductor_kernel_stack_trace.get(kernel_name, []),
  923. "post_grad_nodes": post_grad_nodes,
  924. "pre_grad_nodes": list(pre_grad_nodes),
  925. }
  926. return result
  927. except Exception as e:
  928. signpost_event(
  929. "inductor",
  930. "provenance_tracking_error",
  931. {
  932. "function": "create_kernel_information_json",
  933. "error_msg": str(e),
  934. "stack_trace": traceback.format_exc(),
  935. },
  936. )
  937. return {}
  938. def set_kernel_post_grad_provenance_tracing(
  939. node_schedule: Union[Sequence[BaseSchedulerNode], ExternKernel],
  940. kernel_name: str,
  941. is_extern: bool = False,
  942. ) -> Optional[int]:
  943. """
  944. Set the mapping between `kernel_name` and the post_grad nodes in `node_schedule`.
  945. Returns a unique int debug handler for each call to this function.
  946. """
  947. try:
  948. from .codegen.simd_kernel_features import DisableReduction, EnableReduction
  949. global _inductor_triton_kernel_to_post_grad_node_info
  950. global _inductor_kernel_stack_trace
  951. global _inductor_kernel_provenance_debug_handle
  952. _inductor_kernel_provenance_debug_handle += 1
  953. stack_traces: list[str] = []
  954. kernel_name = f"{kernel_name}:{_inductor_kernel_provenance_debug_handle}"
  955. if is_extern:
  956. assert isinstance(node_schedule, ExternKernel)
  957. curr_node_info = _inductor_triton_kernel_to_post_grad_node_info.setdefault(
  958. kernel_name, []
  959. )
  960. # 'origins' on IR nodes gives what FX IR nodes contributed to any given fused kernel.
  961. # "origin_node" is more precise and says that the contents of this node corresponds
  962. # EXACTLY to the output of a particular FX node, but it's not always available
  963. if node_schedule.origin_node:
  964. origin_node_name = node_schedule.origin_node.name
  965. if origin_node_name not in curr_node_info:
  966. curr_node_info.append(origin_node_name)
  967. else:
  968. curr_node_info.extend(
  969. origin.name
  970. for origin in node_schedule.origins
  971. if origin.name not in curr_node_info
  972. )
  973. stack_traces = list(node_schedule.get_stack_traces())
  974. else:
  975. assert isinstance(node_schedule, list)
  976. stack_traces_set: OrderedSet[str] = OrderedSet()
  977. for snode in node_schedule:
  978. if snode not in (EnableReduction, DisableReduction):
  979. if snode.node is not None:
  980. curr_node_info = (
  981. _inductor_triton_kernel_to_post_grad_node_info.setdefault(
  982. kernel_name, []
  983. )
  984. )
  985. stack_traces_set.update(snode.node.get_stack_traces())
  986. curr_node_info.extend(
  987. origin.name
  988. for origin in snode.node.origins
  989. if origin.name not in curr_node_info
  990. )
  991. stack_traces = list(stack_traces_set)
  992. _inductor_kernel_stack_trace.setdefault(kernel_name, []).extend(stack_traces)
  993. return _inductor_kernel_provenance_debug_handle
  994. except Exception as e:
  995. # Since this is just debugging, it should never interfere with regular
  996. # program execution, so we use this try-except to guard against any error
  997. signpost_event(
  998. "inductor",
  999. "provenance_tracking_error",
  1000. {
  1001. "function": "set_kernel_post_grad_provenance_tracing",
  1002. "error_msg": str(e),
  1003. "stack_trace": traceback.format_exc(),
  1004. },
  1005. )
  1006. return None
  1007. def save_args_for_compile_fx_inner(*args: Any, **kwargs: Any) -> None:
  1008. """
  1009. This function is used to save arguments for a compile_fx_inner function call
  1010. to the file system. Later on one can replay the compile_fx_inner call
  1011. with the saved arguments using load_args_and_run_compile_fx_inner.
  1012. """
  1013. folder = "/tmp/inductor_saved_args"
  1014. if not os.path.exists(folder):
  1015. os.mkdir(folder)
  1016. def handle_tensor(x: Any) -> Any:
  1017. """
  1018. Pickle FakeTensor will result in error:
  1019. AttributeError: Can't pickle local object 'WeakValueDictionary.__init__.<locals>.remove'
  1020. Convert all Tensor to metadata. This may also makes pickle faster.
  1021. """
  1022. if isinstance(x, torch.Tensor):
  1023. return TensorMetadataHolder(_extract_tensor_metadata(x), x.device)
  1024. else:
  1025. return x
  1026. args_to_save, kwargs_to_save = tree_map(handle_tensor, (args, kwargs))
  1027. fn_name = "compile_fx_inner"
  1028. path = f"{folder}/{fn_name}_{next(save_args_cnt)}.pkl"
  1029. with open(path, "wb") as f:
  1030. pickle.dump((args_to_save, kwargs_to_save), f)
  1031. if log.isEnabledFor(logging.DEBUG):
  1032. message = f"""
  1033. Arguments for a compile_fx_inner call is saved to {path}. To replay the call,
  1034. run the following:
  1035. from torch._inductor.debug import load_args_and_run_compile_fx_inner
  1036. load_args_and_run_compile_fx_inner({path!r})
  1037. """
  1038. # call print rather than log.debug. log.debug will print message
  1039. # prefix for each line which makes the code snippet harder to be
  1040. # copied.
  1041. # Not a big deal since the code is already been guarded by checking
  1042. # the log level.
  1043. print(message)
  1044. def load_args_and_run_compile_fx_inner(path: str) -> Any:
  1045. from torch._inductor.compile_fx import compile_fx_inner
  1046. with open(path, "rb") as f:
  1047. args, kwargs = pickle.load(f)
  1048. def handle_tensor(x: Any) -> Any:
  1049. if isinstance(x, TensorMetadataHolder):
  1050. return torch._dynamo.testing.rand_strided(
  1051. x.tensor_metadata.shape,
  1052. x.tensor_metadata.stride,
  1053. x.tensor_metadata.dtype,
  1054. x.device,
  1055. )
  1056. else:
  1057. return x
  1058. fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True)
  1059. with fake_mode, config.patch("save_args", False):
  1060. args, kwargs = tree_map(handle_tensor, (args, kwargs))
  1061. return compile_fx_inner(*args, **kwargs)
  1062. def aot_inductor_minifier_wrapper(
  1063. func: Callable[..., str],
  1064. exported_program: torch.export.ExportedProgram,
  1065. *,
  1066. inductor_configs: dict[str, Any],
  1067. package_path: Optional[FileLike] = None,
  1068. ) -> str:
  1069. from torch._dynamo.debug_utils import AccuracyError
  1070. from torch._dynamo.repro.aoti import dump_to_minify
  1071. from torch._inductor import config
  1072. from torch._inductor.compile_fx import _aoti_flatten_inputs
  1073. use_minifier = config.aot_inductor.dump_aoti_minifier
  1074. gm = exported_program.module(check_guards=False)
  1075. assert isinstance(gm, torch.fx.GraphModule)
  1076. args, kwargs = exported_program.example_inputs
  1077. try:
  1078. if use_minifier and config.aot_inductor.repro_level == 3:
  1079. # Always dump the original module in case we have segfaults
  1080. dump_to_minify(
  1081. exported_program,
  1082. "aot_inductor",
  1083. options=inductor_configs,
  1084. )
  1085. if use_minifier and config.aot_inductor.repro_level == 4:
  1086. # Check for accuracy
  1087. # We will first flatten the inputs before compiling and checking for accuracy.
  1088. # This is ok because we will flatten the inputs in the minifier anyway.
  1089. gm_copy = copy.deepcopy(gm)
  1090. example_inputs_copy = copy.deepcopy(exported_program.example_inputs)
  1091. config_copy = copy.deepcopy(inductor_configs)
  1092. flat_example_inputs, config_copy = _aoti_flatten_inputs(
  1093. gm_copy,
  1094. example_inputs_copy[0],
  1095. example_inputs_copy[1],
  1096. options=config_copy,
  1097. )
  1098. tuple_inputs = tuple(flat_example_inputs)
  1099. flattened_ep = torch.export.export(gm_copy, tuple_inputs, strict=False)
  1100. func(
  1101. flattened_ep.module(check_guards=False),
  1102. tuple_inputs,
  1103. inductor_configs=config_copy,
  1104. package_path=package_path,
  1105. load_and_run=True,
  1106. check_accuracy="accuracy",
  1107. )
  1108. return func(
  1109. gm,
  1110. args,
  1111. kwargs,
  1112. inductor_configs=inductor_configs,
  1113. package_path=package_path,
  1114. load_and_run=use_minifier,
  1115. )
  1116. except AccuracyError as e:
  1117. dump_to_minify(
  1118. exported_program,
  1119. "aot_inductor_accuracy",
  1120. command="minify",
  1121. options=inductor_configs,
  1122. )
  1123. log.warning("Accuracy failed")
  1124. raise e
  1125. except Exception as e:
  1126. if use_minifier:
  1127. command = "minify"
  1128. if config.aot_inductor.repro_level == 1:
  1129. command = "run"
  1130. dump_to_minify(
  1131. exported_program,
  1132. "aot_inductor",
  1133. command=command,
  1134. options=inductor_configs,
  1135. )
  1136. raise e