testing.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. """Testing utilities and infrastructure for Dynamo.
  2. This module provides a comprehensive set of testing utilities including:
  3. - Test result collection and validation
  4. - Graph manipulation and comparison tools
  5. - Test case management and execution helpers
  6. - Specialized test decorators for different Python versions and features
  7. - RNG state management
  8. - Compilation counting and monitoring
  9. - Debug utilities for bytecode transformation
  10. The utilities in this module are used across Dynamo's test suite to ensure
  11. consistent testing patterns and proper test isolation.
  12. """
  13. import contextlib
  14. import dis
  15. import functools
  16. import logging
  17. import os.path
  18. import random
  19. import re
  20. import sys
  21. import types
  22. import unittest
  23. from collections.abc import Sequence
  24. from typing import Any, Callable, Optional, overload, TypeVar, Union
  25. from typing_extensions import ParamSpec
  26. from unittest.mock import patch
  27. import torch
  28. from torch import fx
  29. from torch._dynamo.backends.debugging import aot_eager
  30. from torch._dynamo.output_graph import OutputGraph
  31. from . import config, eval_frame, optimize_assert, reset
  32. from .bytecode_transformation import (
  33. create_instruction,
  34. debug_checks,
  35. is_generator,
  36. transform_code_object,
  37. )
  38. from .guards import CheckFunctionManager, CompileId, GuardedCode
  39. from .types import ConvertFrameReturn, DynamoFrameType, wrap_guarded_code
  40. from .utils import CompileCounterInt, same
  41. np: Optional[types.ModuleType] = None
  42. try:
  43. import numpy as np
  44. except ModuleNotFoundError:
  45. np = None
  46. unsupported = eval_frame.unsupported
  47. three = 3
  48. log = logging.getLogger(__name__)
  49. _P = ParamSpec("_P")
  50. def clone_me(x: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
  51. if x is None:
  52. return None
  53. return x.detach().clone().requires_grad_(x.requires_grad)
  54. def remove_optimized_module_prefix(name: str) -> str:
  55. return re.sub(r"^_orig_mod[.]", "", name)
  56. def extract_graph_and_tracker(fn, *args, **kwargs): # type: ignore[no-untyped-def]
  57. from torch._dynamo.symbolic_convert import InstructionTranslator
  58. gm = None
  59. region_tracker = None
  60. def extract_graph_backend(_gm, *args, **kwargs): # type: ignore[no-untyped-def]
  61. nonlocal gm
  62. nonlocal region_tracker
  63. gm = _gm
  64. region_tracker = InstructionTranslator.current_tx().output.region_tracker
  65. return _gm
  66. torch.compile(backend=extract_graph_backend, fullgraph=True)(fn)(*args, **kwargs)
  67. return gm.graph, region_tracker # type: ignore[union-attr]
  68. def collect_results(
  69. model: torch.nn.Module, prediction: Any, loss: Any, example_inputs: Any
  70. ) -> list[Any]:
  71. results = []
  72. results.append(prediction)
  73. results.append(loss)
  74. # if isinstance(loss, torch.Tensor) and loss.item() > 1:
  75. # log.warning(
  76. # f"High loss value alert - {loss:.2f}. Can result in unstable gradients."
  77. # )
  78. grads = {}
  79. params = {}
  80. for name, param in model.named_parameters():
  81. if isinstance(model, eval_frame.OptimizedModule):
  82. name = remove_optimized_module_prefix(name)
  83. param_copy = param
  84. grad = param.grad
  85. # Treat None and zero grad as same
  86. if param.grad is None:
  87. grad = torch.zeros_like(param)
  88. grads[name + ".grad"] = grad
  89. params[name] = param_copy
  90. results.append(grads)
  91. results.append(params)
  92. buffers = {}
  93. for name, buffer in model.named_buffers():
  94. if isinstance(model, eval_frame.OptimizedModule):
  95. name = remove_optimized_module_prefix(name)
  96. buffers[name] = buffer
  97. results.append(buffers)
  98. for example in example_inputs:
  99. if isinstance(example, (tuple, list)):
  100. results.extend(inp.grad for inp in example if isinstance(inp, torch.Tensor))
  101. else:
  102. if isinstance(example, torch.Tensor):
  103. results.append(example.grad)
  104. return results
  105. def requires_bwd_pass(out: Any) -> bool:
  106. if isinstance(out, torch.Tensor):
  107. return out.requires_grad
  108. elif isinstance(out, (list, tuple)):
  109. return any(requires_bwd_pass(x) for x in out)
  110. elif out is None:
  111. return False
  112. elif isinstance(out, int):
  113. return False
  114. raise NotImplementedError("Don't know how to reduce", type(out))
  115. @overload
  116. def reduce_to_scalar_loss(out: torch.Tensor) -> torch.Tensor: ...
  117. @overload
  118. def reduce_to_scalar_loss(
  119. out: Union[list[Any], tuple[Any, ...], dict[Any, Any]],
  120. ) -> float: ...
  121. def reduce_to_scalar_loss(out: Any) -> Union[torch.Tensor, float]:
  122. """Reduce the output of a model to get scalar loss"""
  123. if isinstance(out, torch.Tensor):
  124. # Mean does not work on integer tensors
  125. return out.sum() / out.numel()
  126. elif isinstance(out, (list, tuple)):
  127. return sum(reduce_to_scalar_loss(x) for x in out) / len(out)
  128. elif type(out).__name__ in (
  129. "MaskedLMOutput",
  130. "Seq2SeqLMOutput",
  131. "CausalLMOutputWithCrossAttentions",
  132. ):
  133. return reduce_to_scalar_loss(out.logits)
  134. elif type(out).__name__ == "SquashedNormal":
  135. return out.mean.sum()
  136. elif isinstance(out, dict):
  137. return sum(reduce_to_scalar_loss(value) for value in out.values()) / len(
  138. out.keys()
  139. )
  140. raise NotImplementedError("Don't know how to reduce", type(out))
  141. def debug_dir() -> str:
  142. path = os.path.join(os.path.dirname(__file__), "../debug")
  143. if not os.path.exists(path):
  144. os.mkdir(path)
  145. return path
  146. def debug_dump(name: str, code: types.CodeType, extra: str = "") -> None:
  147. with open(os.path.join(debug_dir(), name), "w") as fd:
  148. fd.write(
  149. f"{dis.Bytecode(code).info()}\n\n{dis.Bytecode(code).dis()}\n\n{extra}\n"
  150. )
  151. def debug_insert_nops(
  152. frame: DynamoFrameType, cache_size: int, hooks: Any, _: Any, *, skip: int = 0
  153. ) -> ConvertFrameReturn:
  154. """used to debug jump updates"""
  155. def insert_nops(instructions: list[Any], code_options: Any) -> None:
  156. instructions.insert(0, create_instruction("NOP"))
  157. instructions.insert(0, create_instruction("NOP"))
  158. metrics_context = torch._dynamo.utils.get_metrics_context()
  159. with torch._dynamo.utils.dynamo_timed("debug_insert_nops"), metrics_context:
  160. if is_generator(frame.f_code):
  161. return ConvertFrameReturn()
  162. debug_checks(frame.f_code)
  163. code, _ = transform_code_object(frame.f_code, insert_nops)
  164. graph = OutputGraph(
  165. code_options={},
  166. compiler_fn=None,
  167. root_tx=None, # type: ignore[arg-type]
  168. export=False,
  169. export_constraints=[],
  170. frame_state={"_id": 0},
  171. # TODO: shouldn't this be f_locals/f_globals from frame?
  172. local_scope=locals(),
  173. global_scope=globals(),
  174. f_code=frame.f_code,
  175. torch_function_mode_stack=[],
  176. package=None,
  177. )
  178. return wrap_guarded_code(
  179. GuardedCode(
  180. code,
  181. CheckFunctionManager(frame.f_code, graph).guard_manager, # type: ignore[arg-type]
  182. CompileId(frame_id=0, frame_compile_id=0),
  183. )
  184. )
  185. class CompileCounter:
  186. def __init__(self) -> None:
  187. self.frame_count: Union[int, CompileCounterInt] = 0
  188. self.clear()
  189. def __call__(
  190. self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  191. ) -> Callable[..., Any]:
  192. self.frame_count += 1
  193. for node in gm.graph.nodes:
  194. if "call" in node.op:
  195. self.op_count += 1
  196. return gm.forward
  197. def clear(self) -> None:
  198. if config.debug_disable_compile_counter:
  199. self.frame_count = CompileCounterInt(0)
  200. else:
  201. self.frame_count = 0
  202. self.op_count = 0
  203. class CompileCounterWithBackend:
  204. def __init__(self, backend: str) -> None:
  205. self.frame_count: Union[int, CompileCounterInt] = 0
  206. self.backend = backend
  207. self.graphs: list[torch.fx.GraphModule] = []
  208. self.clear()
  209. def __call__(
  210. self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  211. ) -> Callable[..., Any]:
  212. from .backends.registry import lookup_backend
  213. self.frame_count += 1
  214. for node in gm.graph.nodes:
  215. if "call" in node.op:
  216. self.op_count += 1
  217. self.graphs.append(gm)
  218. return lookup_backend(self.backend)(gm, example_inputs)
  219. def clear(self) -> None:
  220. if config.debug_disable_compile_counter:
  221. self.frame_count = CompileCounterInt(0)
  222. else:
  223. self.frame_count = 0
  224. self.op_count = 0
  225. self.graphs = []
  226. # Equivalent to backend="eager", but also records graphs that
  227. # we can assert on
  228. class EagerAndRecordGraphs:
  229. def __init__(self) -> None:
  230. self.graphs: list[torch.fx.GraphModule] = []
  231. def __call__(
  232. self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  233. ) -> Callable[..., Any]:
  234. self.graphs.append(gm)
  235. return gm.forward
  236. class AotEagerAndRecordGraphs:
  237. def __init__(self) -> None:
  238. self.graphs: list[torch.fx.GraphModule] = []
  239. self.fw_graphs: list[torch.fx.GraphModule] = []
  240. self.bw_graphs: list[torch.fx.GraphModule] = []
  241. def __call__(
  242. self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  243. ) -> Callable[..., Any]:
  244. self.graphs.append(gm)
  245. def fw_compiler(
  246. gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  247. ) -> Callable[..., Any]:
  248. self.fw_graphs.append(gm)
  249. return gm.forward
  250. def bw_compiler(
  251. gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
  252. ) -> Callable[..., Any]:
  253. self.bw_graphs.append(gm)
  254. return gm.forward
  255. return aot_eager(
  256. gm,
  257. example_inputs,
  258. fw_compiler=fw_compiler,
  259. bw_compiler=bw_compiler,
  260. )
  261. class InductorAndRecordGraphs:
  262. def __init__(self) -> None:
  263. self.graphs: list[torch.fx.GraphModule] = []
  264. self.inductor_graphs: list[torch.fx.GraphModule] = []
  265. def __call__(self, gm, example_inputs): # type: ignore[no-untyped-def]
  266. import torch._inductor.compile_fx as compile_fx_mod
  267. self.graphs.append(gm)
  268. old_compile_fx_inner = compile_fx_mod._compile_fx_inner
  269. def patched(*args, **kwargs): # type: ignore[no-untyped-def]
  270. self.inductor_graphs.append(args[0])
  271. return old_compile_fx_inner(*args, **kwargs)
  272. with patch.object(compile_fx_mod, "_compile_fx_inner", new=patched):
  273. return compile_fx_mod.compile_fx(gm, example_inputs)
  274. def strip_comment(code: str) -> str:
  275. return re.sub(r"(?m)^ *#.*\n?", "", code)
  276. def remove_trailing_space(code: str) -> str:
  277. return "\n".join([line.rstrip() for line in code.split("\n")])
  278. def normalize_gm(gm_str: str) -> str:
  279. # strip comments as comments have path to files which may differ from
  280. # system to system.
  281. return remove_trailing_space(strip_comment(gm_str))
  282. def empty_line_normalizer(code: str) -> str:
  283. """
  284. Normalize code: remove empty lines.
  285. """
  286. normal_code = re.sub(r"[\r\n]+", "\n", code)
  287. return normal_code
  288. def standard_test(
  289. self: Any,
  290. fn: Callable[..., Any],
  291. nargs: int,
  292. expected_ops: Optional[int] = None,
  293. expected_ops_dynamic: Optional[int] = None,
  294. expected_frame_count: int = 1,
  295. ) -> None:
  296. if not config.assume_static_by_default and expected_ops_dynamic is not None:
  297. expected_ops = expected_ops_dynamic
  298. actual = CompileCounter()
  299. args1 = [torch.randn(10, 10) for _ in range(nargs)]
  300. args2 = [torch.randn(10, 10) for _ in range(nargs)]
  301. correct1 = fn(*args1)
  302. correct2 = fn(*args2)
  303. reset()
  304. opt_fn = optimize_assert(actual)(fn)
  305. val1a = opt_fn(*args1)
  306. val2a = opt_fn(*args2)
  307. val1b = opt_fn(*args1)
  308. val2b = opt_fn(*args2)
  309. reset()
  310. self.assertTrue(same(val1a, correct1))
  311. self.assertTrue(same(val1b, correct1))
  312. self.assertTrue(same(val2a, correct2))
  313. self.assertTrue(same(val2b, correct2))
  314. self.assertEqual(actual.frame_count, expected_frame_count)
  315. if expected_ops is not None:
  316. self.assertEqual(actual.op_count, expected_ops)
  317. def dummy_fx_compile(
  318. gm: fx.GraphModule, example_inputs: list[torch.Tensor]
  319. ) -> Callable[..., Any]:
  320. return gm.forward
  321. def format_speedup(
  322. speedup: float,
  323. pvalue: float,
  324. is_correct: bool = True,
  325. pvalue_threshold: float = 0.1,
  326. ) -> str:
  327. if not is_correct:
  328. return "ERROR"
  329. if pvalue > pvalue_threshold:
  330. return f"{speedup:.3f}x SAME"
  331. return f"{speedup:.3f}x p={pvalue:.2f}"
  332. def rand_strided(
  333. size: Sequence[int],
  334. stride: Sequence[int],
  335. dtype: torch.dtype = torch.float32,
  336. device: Union[str, torch.device] = "cpu",
  337. extra_size: int = 0,
  338. ) -> torch.Tensor:
  339. needed_size = extra_size
  340. if all(s > 0 for s in size):
  341. # only need to allocate if all sizes are non-zero
  342. needed_size += (
  343. sum((shape - 1) * stride for shape, stride in zip(size, stride)) + 1
  344. )
  345. if dtype.is_floating_point:
  346. if dtype.itemsize == 1:
  347. """
  348. normal distribution kernel is not implemented for fp8..
  349. Workaround that by creating a fp16 tensor and then cast.
  350. """
  351. buffer = torch.randn(needed_size, dtype=torch.float16, device=device).to(
  352. dtype=dtype
  353. )
  354. else:
  355. buffer = torch.randn(needed_size, dtype=dtype, device=device)
  356. else:
  357. buffer = torch.zeros(size=[needed_size], dtype=dtype, device=device)
  358. return torch.as_strided(buffer, size, stride)
  359. _T = TypeVar("_T")
  360. def check_dynamic_shape_capture() -> bool:
  361. # This also mirrors config from `test/dynamo/test_dynamic_shapes.py:make_dynamic_cls`
  362. return not config.assume_static_by_default
  363. def _make_fn_with_patches(fn: Callable[_P, _T], *patches: Any) -> Callable[_P, _T]:
  364. @functools.wraps(fn)
  365. def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  366. with contextlib.ExitStack() as stack:
  367. for module, attr, val in patches:
  368. stack.enter_context(patch.object(module, attr, val))
  369. return fn(*args, **kwargs)
  370. return _fn
  371. def make_test_cls_with_patches(
  372. cls: type,
  373. cls_prefix: str,
  374. fn_suffix: str,
  375. *patches: Any,
  376. xfail_prop: Optional[str] = None,
  377. decorator: Callable[[Callable[..., Any]], Callable[..., Any]] = lambda x: x,
  378. ) -> type:
  379. DummyTestClass = type(f"{cls_prefix}{cls.__name__}", cls.__bases__, {})
  380. DummyTestClass.__qualname__ = DummyTestClass.__name__
  381. for name in dir(cls):
  382. if name.startswith("test_"):
  383. fn = getattr(cls, name)
  384. if not callable(fn):
  385. setattr(DummyTestClass, name, getattr(cls, name))
  386. continue
  387. new_name = f"{name}{fn_suffix}"
  388. new_fn = _make_fn_with_patches(fn, *patches)
  389. new_fn.__name__ = new_name
  390. if xfail_prop is not None and hasattr(fn, xfail_prop):
  391. new_fn = unittest.expectedFailure(new_fn)
  392. setattr(DummyTestClass, new_name, decorator(new_fn))
  393. # NB: Doesn't handle slots correctly, but whatever
  394. elif not hasattr(DummyTestClass, name):
  395. setattr(DummyTestClass, name, getattr(cls, name))
  396. return DummyTestClass
  397. # test Python 3.11+ specific features
  398. def skipIfNotPy311(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  399. if sys.version_info >= (3, 11):
  400. return fn
  401. return unittest.skip(fn)
  402. def skipIfNotPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  403. if sys.version_info >= (3, 12):
  404. return fn
  405. return unittest.skip("Requires Python 3.12+")(fn)
  406. def xfailIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  407. if sys.version_info >= (3, 12):
  408. return unittest.expectedFailure(fn)
  409. return fn
  410. def skipIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  411. if sys.version_info >= (3, 12):
  412. return unittest.skip("Not supported in Python 3.12+")(fn)
  413. return fn
  414. def requiresPy310(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  415. if sys.version_info >= (3, 10):
  416. return fn
  417. else:
  418. return unittest.skip("Requires Python 3.10+")(fn)
  419. # Controls tests generated in test/inductor/test_torchinductor_dynamic_shapes.py
  420. # and test/dynamo/test_dynamic_shapes.py
  421. def expectedFailureDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  422. fn._expected_failure_dynamic = True # type: ignore[attr-defined]
  423. return fn
  424. # Controls tests generated in test/inductor/test_torchinductor_codegen_dynamic_shapes.py
  425. def expectedFailureCodegenDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  426. fn._expected_failure_codegen_dynamic = True # type: ignore[attr-defined]
  427. return fn
  428. # Controls test generated in test/inductor/test_cpp_wrapper.py
  429. def expectedFailureDynamicWrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  430. fn._expected_failure_dynamic_wrapper = True # type: ignore[attr-defined]
  431. return fn
  432. def reset_rng_state(use_xla: bool = False) -> None:
  433. torch.manual_seed(1337)
  434. random.seed(1337)
  435. if np:
  436. np.random.seed(1337)
  437. if use_xla:
  438. import torch_xla.core.xla_model as xm
  439. xm.set_rng_state(1337, str(xm.xla_device()))
  440. def _skipped_function_for_test_reconstruct(
  441. f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
  442. ) -> _T:
  443. return f(*args, **kwargs)