testing.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import contextlib
  2. import dis
  3. import functools
  4. import logging
  5. import os.path
  6. import types
  7. import unittest
  8. from unittest.mock import patch
  9. import torch
  10. from torch import fx
  11. from . import config, eval_frame, optimize_assert, reset
  12. from .bytecode_transformation import (
  13. create_instruction,
  14. debug_checks,
  15. is_generator,
  16. transform_code_object,
  17. )
  18. from .guards import CheckFunctionManager, GuardedCode
  19. from .utils import same
  20. unsupported = eval_frame.unsupported
  21. three = 3
  22. log = logging.getLogger(__name__)
  23. def clone_me(x):
  24. if x is None:
  25. return None
  26. return x.detach().clone().requires_grad_(x.requires_grad)
  27. def skip_if_pytest(fn):
  28. @functools.wraps(fn)
  29. def wrapped(*args, **kwargs):
  30. if "PYTEST_CURRENT_TEST" in os.environ:
  31. raise unittest.SkipTest("does not work under pytest")
  32. return fn(*args, **kwargs)
  33. return wrapped
  34. def named_parameters_for_optimized_module(mod):
  35. assert isinstance(mod, eval_frame.OptimizedModule)
  36. return mod._orig_mod.named_parameters
  37. def named_buffers_for_optimized_module(mod):
  38. assert isinstance(mod, eval_frame.OptimizedModule)
  39. return mod._orig_mod.named_buffers
  40. def remove_optimized_module_prefix(name):
  41. prefix = "_orig_mod."
  42. assert name.startswith(prefix)
  43. name = name[len(prefix) :]
  44. return name
  45. def collect_results(model, prediction, loss, example_inputs):
  46. results = []
  47. results.append(prediction)
  48. results.append(loss)
  49. # if isinstance(loss, torch.Tensor) and loss.item() > 1:
  50. # log.warning(
  51. # f"High loss value alert - {loss:.2f}. Can result in unstable gradients."
  52. # )
  53. grads = dict()
  54. params = dict()
  55. for name, param in model.named_parameters():
  56. if isinstance(model, eval_frame.OptimizedModule):
  57. name = remove_optimized_module_prefix(name)
  58. param_copy = param
  59. grad = param.grad
  60. # Treat None and zero grad as same
  61. if param.grad is None:
  62. grad = torch.zeros_like(param)
  63. grads[name + ".grad"] = grad
  64. params[name] = param_copy
  65. results.append(grads)
  66. results.append(params)
  67. buffers = dict()
  68. for name, buffer in model.named_buffers():
  69. if isinstance(model, eval_frame.OptimizedModule):
  70. name = remove_optimized_module_prefix(name)
  71. buffers[name] = buffer
  72. results.append(buffers)
  73. for example in example_inputs:
  74. if isinstance(example, (tuple, list)):
  75. for inp in example:
  76. if isinstance(inp, torch.Tensor):
  77. results.append(inp.grad)
  78. else:
  79. if isinstance(example, torch.Tensor):
  80. results.append(example.grad)
  81. return results
  82. def requires_bwd_pass(out):
  83. if isinstance(out, torch.Tensor):
  84. return out.requires_grad
  85. elif isinstance(out, (list, tuple)):
  86. return any([requires_bwd_pass(x) for x in out])
  87. elif out is None:
  88. return False
  89. raise NotImplementedError("Don't know how to reduce", type(out))
  90. def reduce_to_scalar_loss(out):
  91. """Reduce the output of a model to get scalar loss"""
  92. if isinstance(out, torch.Tensor):
  93. # Mean does not work on integer tensors
  94. return out.sum() / out.numel()
  95. elif isinstance(out, (list, tuple)):
  96. return sum([reduce_to_scalar_loss(x) for x in out]) / len(out)
  97. elif type(out).__name__ in (
  98. "MaskedLMOutput",
  99. "Seq2SeqLMOutput",
  100. "CausalLMOutputWithCrossAttentions",
  101. ):
  102. return reduce_to_scalar_loss(out.logits)
  103. elif type(out).__name__ == "SquashedNormal":
  104. return out.mean.sum()
  105. elif isinstance(out, dict):
  106. return sum([reduce_to_scalar_loss(value) for value in out.values()]) / len(
  107. out.keys()
  108. )
  109. raise NotImplementedError("Don't know how to reduce", type(out))
  110. def debug_dir():
  111. path = os.path.join(os.path.dirname(__file__), "../debug")
  112. if not os.path.exists(path):
  113. os.mkdir(path)
  114. return path
  115. def debug_dump(name, code: types.CodeType, extra=""):
  116. with open(os.path.join(debug_dir(), name), "w") as fd:
  117. fd.write(
  118. f"{dis.Bytecode(code).info()}\n\n{dis.Bytecode(code).dis()}\n\n{extra}\n"
  119. )
  120. def debug_insert_nops(frame, cache_size, hooks):
  121. """used to debug jump updates"""
  122. def insert_nops(instructions, code_options):
  123. instructions.insert(0, create_instruction("NOP"))
  124. instructions.insert(0, create_instruction("NOP"))
  125. if is_generator(frame.f_code):
  126. return None
  127. debug_checks(frame.f_code)
  128. code = transform_code_object(frame.f_code, insert_nops)
  129. return GuardedCode(code, CheckFunctionManager().check_fn)
  130. class CompileCounter:
  131. def __init__(self):
  132. self.frame_count = 0
  133. self.op_count = 0
  134. def __call__(self, gm: torch.fx.GraphModule, example_inputs):
  135. self.frame_count += 1
  136. for node in gm.graph.nodes:
  137. if "call" in node.op:
  138. self.op_count += 1
  139. return gm.forward
  140. def clear(self):
  141. self.frame_count = 0
  142. self.op_count = 0
  143. class CompileCounterWithBackend:
  144. def __init__(self, backend):
  145. self.frame_count = 0
  146. self.op_count = 0
  147. self.backend = backend
  148. def __call__(self, gm: torch.fx.GraphModule, example_inputs):
  149. from .backends.registry import lookup_backend
  150. self.frame_count += 1
  151. for node in gm.graph.nodes:
  152. if "call" in node.op:
  153. self.op_count += 1
  154. return lookup_backend(self.backend)(gm, example_inputs)
  155. def standard_test(self, fn, nargs, expected_ops=None, expected_ops_dynamic=None):
  156. if config.dynamic_shapes and expected_ops_dynamic is not None:
  157. expected_ops = expected_ops_dynamic
  158. actual = CompileCounter()
  159. if expected_ops is None:
  160. expected = CompileCounter()
  161. try:
  162. gm = torch.fx.symbolic_trace(fn)
  163. expected(gm)
  164. print("\nfx.symbolic_trace graph:")
  165. gm.graph.print_tabular()
  166. expected_ops = expected.op_count
  167. except Exception:
  168. pass # Silently ignore FX errors (not our issue)
  169. args1 = [torch.randn(10, 10) for _ in range(nargs)]
  170. args2 = [torch.randn(10, 10) for _ in range(nargs)]
  171. correct1 = fn(*args1)
  172. correct2 = fn(*args2)
  173. reset()
  174. opt_fn = optimize_assert(actual)(fn)
  175. val1a = opt_fn(*args1)
  176. val2a = opt_fn(*args2)
  177. val1b = opt_fn(*args1)
  178. val2b = opt_fn(*args2)
  179. reset()
  180. self.assertTrue(same(val1a, correct1))
  181. self.assertTrue(same(val1b, correct1))
  182. self.assertTrue(same(val2a, correct2))
  183. self.assertTrue(same(val2b, correct2))
  184. self.assertEqual(actual.frame_count, 1)
  185. if expected_ops is not None:
  186. self.assertEqual(actual.op_count, expected_ops)
  187. def dummy_fx_compile(gm: fx.GraphModule, example_inputs):
  188. return gm.forward
  189. def format_speedup(speedup, pvalue, is_correct=True, pvalue_threshold=0.1):
  190. if not is_correct:
  191. return "ERROR"
  192. if pvalue > pvalue_threshold:
  193. return f"{speedup:.3f}x SAME"
  194. return f"{speedup:.3f}x p={pvalue:.2f}"
  195. def requires_static_shapes(fn):
  196. @functools.wraps(fn)
  197. def _fn(*args, **kwargs):
  198. if config.dynamic_shapes:
  199. raise unittest.SkipTest("requires static shapes")
  200. return fn(*args, **kwargs)
  201. return _fn
  202. def rand_strided(size, stride, dtype=torch.float32, device="cpu", extra_size=0):
  203. needed_size = (
  204. sum((shape - 1) * stride for shape, stride in zip(size, stride))
  205. + 1
  206. + extra_size
  207. )
  208. if dtype.is_floating_point:
  209. buffer = torch.randn(needed_size, dtype=dtype, device=device)
  210. else:
  211. buffer = torch.zeros(size=[needed_size], dtype=dtype, device=device)
  212. return torch.as_strided(buffer, size, stride)
  213. def _make_fn_with_patches(fn, *patches):
  214. @functools.wraps(fn)
  215. def _fn(*args, **kwargs):
  216. with contextlib.ExitStack() as stack:
  217. for module, attr, val in patches:
  218. stack.enter_context(patch.object(module, attr, val))
  219. return fn(*args, **kwargs)
  220. return _fn
  221. def make_test_cls_with_patches(cls, cls_prefix, fn_suffix, *patches):
  222. class DummyTestClass(cls):
  223. pass
  224. DummyTestClass.__name__ = f"{cls_prefix}{cls.__name__}"
  225. for name in dir(cls):
  226. if name.startswith("test_"):
  227. fn = getattr(cls, name)
  228. if not callable(fn):
  229. continue
  230. new_name = f"{name}{fn_suffix}"
  231. fn = _make_fn_with_patches(fn, *patches)
  232. fn.__name__ = new_name
  233. setattr(DummyTestClass, new_name, fn)
  234. return DummyTestClass