jit_utils.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. # mypy: ignore-errors
  2. # Torch
  3. from torch.autograd import Variable
  4. from torch.autograd.function import _nested_map
  5. from torch.jit.annotations import BroadcastingList2, BroadcastingList3 # noqa: F401
  6. from torch.onnx import OperatorExportTypes
  7. import torch
  8. import torch.cuda
  9. import torch.jit
  10. import torch.jit._logging
  11. import torch.jit.frontend
  12. import torch.jit.quantized
  13. import zipfile
  14. import functools
  15. # Testing utils
  16. from torch.testing import FileCheck
  17. from torch.testing._internal.common_utils import IS_WINDOWS, \
  18. freeze_rng_state, enable_profiling_mode_for_profiling_tests, ProfilingMode, TEST_BAILOUTS, \
  19. is_iterable_of_tensors
  20. from torch.testing._internal.common_jit import JitCommonTestCase
  21. from torch.testing._internal.common_utils import enable_profiling_mode # noqa: F401
  22. # Standard library
  23. from contextlib import contextmanager
  24. from functools import reduce
  25. from io import StringIO
  26. from collections import defaultdict
  27. import importlib.util
  28. import inspect
  29. import io
  30. import math
  31. import os
  32. import pickle
  33. import sys
  34. import tempfile
  35. import textwrap
  36. from importlib.abc import Loader
  37. from typing import Any, Dict, List, Tuple, Union
  38. RUN_CUDA = torch.cuda.is_available()
  39. RUN_CUDA_MULTI_GPU = RUN_CUDA and torch.cuda.device_count() > 1
  40. RUN_CUDA_HALF = RUN_CUDA
  41. # HIP supports half, no version check necessary
  42. if torch.cuda.is_available() and not torch.version.hip:
  43. CUDA_VERSION = torch._C._cuda_getCompiledVersion()
  44. for d in range(torch.cuda.device_count()):
  45. major = torch.cuda.get_device_capability(d)[0]
  46. if (major < 6):
  47. RUN_CUDA_HALF = False
  48. def execWrapper(code, glob, loc):
  49. exec(code, glob, loc)
  50. def do_input_map(fn, input):
  51. return _nested_map(lambda t: isinstance(t, torch.Tensor), fn)(input)
  52. def clear_class_registry():
  53. torch._C._jit_clear_class_registry()
  54. torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore()
  55. torch.jit._state._clear_class_state()
  56. def get_execution_plan(graph_executor_state):
  57. execution_plans = list(graph_executor_state.execution_plans.values())
  58. num_plans = len(execution_plans)
  59. if num_plans != 1:
  60. raise RuntimeError('This test assumes this GraphExecutor should '
  61. f'only have one execution plan, got: {num_plans}')
  62. return execution_plans[0]
  63. class _AssertRaisesRegexWithHighlightContext:
  64. """
  65. A context manager that is useful for checking that error messages highlight
  66. the correct part of the source code.
  67. """
  68. def __init__(self, test_case, exception, regex, highlight):
  69. self.test_case = test_case
  70. self.exception_type = exception
  71. self.regex = regex
  72. self.highlight = highlight
  73. def __enter__(self):
  74. return self
  75. def __exit__(self, type, value, traceback):
  76. with self.test_case.assertRaisesRegex(self.exception_type, self.regex):
  77. if type:
  78. raise value
  79. if self.highlight:
  80. FileCheck().check_source_highlighted(self.highlight).run(str(value))
  81. return True
  82. FUSION_GROUP = "prim::TensorExprGroup"
  83. class JitTestCase(JitCommonTestCase):
  84. _do_cuda_memory_leak_check = True
  85. _restored_warnings = False
  86. class capture_stdout(list):
  87. """
  88. Replace sys.stdout with a temporary StringIO
  89. """
  90. def __enter__(self):
  91. self.sys_stdout = sys.stdout
  92. self.stringio = StringIO()
  93. sys.stdout = self.stringio
  94. return self
  95. def __exit__(self, *args):
  96. self.append(str(self.stringio.getvalue()))
  97. del self.stringio
  98. sys.stdout = self.sys_stdout
  99. class capture_stderr(list):
  100. """
  101. Replace sys.stderr with a temporary StringIO
  102. """
  103. def __enter__(self):
  104. self.sys_stderr = sys.stderr
  105. self.stringio = StringIO()
  106. sys.stderr = self.stringio
  107. return self
  108. def __exit__(self, *args):
  109. self.append(str(self.stringio.getvalue()))
  110. del self.stringio
  111. sys.stderr = self.sys_stderr
  112. def setHooks(self):
  113. torch._C._jit_set_emit_hooks(self.emitModuleHook, self.emitFunctionHook)
  114. def clearHooks(self):
  115. torch._C._jit_set_emit_hooks(None, None)
  116. def setUp(self):
  117. super().setUp()
  118. # unittest overrides all warning filters and forces all of them to show up
  119. # after we install our own to silence those coming from inside PyTorch.
  120. # This will ensure that our filter still takes precedence.
  121. if not JitTestCase._restored_warnings:
  122. torch.jit.TracerWarning.ignore_lib_warnings()
  123. JitTestCase._restored_warnings = True
  124. self.setHooks()
  125. def tearDown(self):
  126. super().tearDown()
  127. # needs to be cleared because python might be unloaded before
  128. # the callback gets destructed
  129. self.clearHooks()
  130. clear_class_registry()
  131. def assertAllFused(self, graph, except_for=()):
  132. # note this helper collects nodes on 'fast path' only
  133. # i.e. the true blocks of specialized checks
  134. def get_nodes_and_parents_recursively(block, kind, acc):
  135. for node in block.nodes():
  136. if node.kind() == kind:
  137. acc[block].append(node)
  138. elif node.kind() == 'prim::DifferentiableGraph':
  139. get_nodes_and_parents_recursively(node.g('Subgraph'), kind, acc)
  140. elif node.kind() == 'prim::If' and (node.inputs().__next__().node().kind() == 'aten::all' or
  141. node.inputs().__next__().node().kind() == 'prim::TypeCheck' or
  142. node.inputs().__next__().node().kind() == 'prim::RequiresGradCheck'):
  143. get_nodes_and_parents_recursively(node.blocks().__next__(), kind, acc)
  144. else:
  145. for inner_block in node.blocks():
  146. get_nodes_and_parents_recursively(inner_block, kind, acc)
  147. allowed_nodes = {'prim::Constant', FUSION_GROUP, 'prim::BailoutTemplate',
  148. 'prim::TupleConstruct', 'prim::If', 'prim::TypeCheck', 'prim::RequiresGradCheck'} | set(except_for)
  149. fusion_groups : Dict[torch._C.Block, List[torch._C.Node]] = defaultdict(list)
  150. get_nodes_and_parents_recursively(graph, FUSION_GROUP, fusion_groups)
  151. self.assertTrue(len(fusion_groups) == 1, f'got {graph}')
  152. (graph, fusion_nodes) = next(iter(fusion_groups.items()))
  153. # the block contains one FUSION_GROUP and the rest of nodes are `allowed_nodes`
  154. self.assertTrue(len(fusion_nodes) == 1, f'got {graph}')
  155. self.assertTrue(all(node.kind() in allowed_nodes for node in graph.nodes()),
  156. f'got {graph}')
  157. def _isHookExceptionOk(self, e):
  158. se = str(e)
  159. allowed = ("Could not export Python function",
  160. "closures are not exportable")
  161. for a in allowed:
  162. if a in se:
  163. return True
  164. return False
  165. def _compared_saved_loaded(self, m):
  166. def extract_files(buffer):
  167. # crack open the zip format to get at the main module code
  168. archive = zipfile.ZipFile(buffer)
  169. # check that we have no duplicate names
  170. self.assertEqual(len(set(archive.namelist())), len(archive.namelist()))
  171. files = list(filter(lambda x: x.startswith('archive/code/'), archive.namelist()))
  172. # unwrap all the code files into strings
  173. code_files_str = filter(lambda x: x.endswith('.py'), files)
  174. code_files_stream = (archive.open(f) for f in code_files_str)
  175. code_files = ("".join([line.decode() for line in file]) for file in code_files_stream)
  176. # unpickled all the debug files
  177. debug_files_str = filter(lambda f: f.endswith('.debug_pkl'), files)
  178. debug_files_stream = (archive.open(f) for f in debug_files_str)
  179. debug_files = (pickle.load(f) for f in debug_files_stream)
  180. return code_files, debug_files
  181. # disable the hook while we parse code, otherwise we will re-enter the hook
  182. with torch._jit_internal._disable_emit_hooks():
  183. try:
  184. # short-circuit if this is an empty function or module
  185. if len(m.code) == 0:
  186. return
  187. if isinstance(m, torch._C.ScriptModule):
  188. if len(m._method_names()) == 0:
  189. return
  190. # save the module to a buffer
  191. buffer = io.BytesIO()
  192. torch.jit.save(m, buffer)
  193. # copy the data in the buffer so we can restore it later. This
  194. # is because py2 and py3 have different semantics with zipfile
  195. # and it's easier to just work with a fresh copy each time.
  196. buffer_copy = buffer.getvalue()
  197. code_files, debug_files = extract_files(buffer)
  198. except RuntimeError as e:
  199. if not self._isHookExceptionOk(e):
  200. raise
  201. else:
  202. return
  203. # import the model again (from a the copy we made of the original)
  204. buffer2 = io.BytesIO(buffer_copy)
  205. imported = torch.jit.load(buffer2)
  206. # save it again
  207. saved_module_buffer_2 = io.BytesIO()
  208. torch.jit.save(imported, saved_module_buffer_2)
  209. saved_module_buffer_2.seek(0)
  210. code_files_2, debug_files_2 = extract_files(saved_module_buffer_2)
  211. for a, b in zip(code_files, code_files_2):
  212. self.assertMultiLineEqual(a, b)
  213. if isinstance(m, torch._C.ScriptModule):
  214. self.assertTrue(torch._C._ivalue_tags_match(m, imported._c))
  215. def emitFunctionHook(self, func):
  216. # func has invalid names for export, skip the jitter check
  217. if func.name == "<lambda>" or "aten::" in func.name:
  218. return
  219. self._compared_saved_loaded(func)
  220. def emitModuleHook(self, module):
  221. self._compared_saved_loaded(module)
  222. def getExportImportCopyWithPacking(self, m, also_test_file=True, map_location=None):
  223. buffer = io.BytesIO()
  224. m.apply(lambda s: s._pack() if s._c._has_method('_pack') else None)
  225. torch.jit.save(m, buffer)
  226. m.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  227. buffer.seek(0)
  228. imported = torch.jit.load(buffer, map_location=map_location)
  229. imported.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  230. if not also_test_file:
  231. return imported
  232. # Ideally we would like to not have to manually delete the file, but NamedTemporaryFile
  233. # opens the file, and it cannot be opened multiple times in Windows. To support Windows,
  234. # close the file after creation and try to remove it manually
  235. f = tempfile.NamedTemporaryFile(delete=False)
  236. try:
  237. f.close()
  238. imported.save(f.name)
  239. result = torch.jit.load(f.name, map_location=map_location)
  240. finally:
  241. os.unlink(f.name)
  242. result.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  243. return result
  244. def assertGraphContains(self, graph, kind, consider_subgraphs=False):
  245. if consider_subgraphs:
  246. strgraph = str(graph)
  247. count = strgraph.count(kind) - strgraph.count(f'with {kind}')
  248. self.assertTrue(count > 0)
  249. return
  250. def nodes(block):
  251. out = []
  252. for node in block.nodes():
  253. if node.kind() == kind:
  254. out.append(node)
  255. for block in node.blocks():
  256. out += nodes(block)
  257. return out
  258. out_nodes = nodes(graph)
  259. self.assertTrue(len(out_nodes) > 0)
  260. def assertGraphContainsExactly(self, graph, kind, num_kind_nodes, consider_subgraphs=False):
  261. def perform_assert(graph, kind, actual, expected, consider_subgraphs):
  262. if actual == expected:
  263. return
  264. subgraph = 'including' if consider_subgraphs else 'excluding'
  265. raise AssertionError(
  266. f'{graph}\nError: graph contains {actual} {kind} nodes ({subgraph} subgraphs) but expected {expected}')
  267. if consider_subgraphs:
  268. strgraph = str(graph)
  269. count = strgraph.count(kind) - strgraph.count(f'with {kind}')
  270. perform_assert(graph, kind, count, num_kind_nodes,
  271. consider_subgraphs)
  272. return
  273. def nodes(block):
  274. out = []
  275. for node in block.nodes():
  276. if node.kind() == kind:
  277. out.append(node)
  278. for block in node.blocks():
  279. out += nodes(block)
  280. return out
  281. out_nodes = nodes(graph)
  282. perform_assert(graph, kind, len(out_nodes), num_kind_nodes,
  283. consider_subgraphs)
  284. def assertExpectedONNXGraph(self, g, *args, **kwargs):
  285. g = torch.onnx._optimize_trace(g, operator_export_type=OperatorExportTypes.ONNX)
  286. self.assertExpectedGraph(g, *args, **kwargs)
  287. def assertExpectedGraph(self, trace, *args, **kwargs):
  288. if isinstance(trace, torch._C.Graph):
  289. graph = trace
  290. else:
  291. graph = trace.graph()
  292. torch._C._jit_pass_lint(graph)
  293. torch._C._jit_pass_dce(graph)
  294. torch._C._jit_pass_lint(graph)
  295. graph = torch._C._jit_pass_canonicalize(graph)
  296. torch._C._jit_pass_lint(graph)
  297. self.assertExpected(str(graph), *args, **kwargs)
  298. def run_pass(self, name, trace):
  299. if isinstance(trace, torch._C.Graph):
  300. graph = trace
  301. set_graph = False
  302. else:
  303. set_graph = True
  304. graph = trace.graph()
  305. torch._C._jit_pass_lint(graph)
  306. result = getattr(torch._C, '_jit_pass_' + name)(graph)
  307. if result is not None and not isinstance(result, bool):
  308. graph = result
  309. torch._C._jit_pass_lint(graph)
  310. if set_graph:
  311. trace.set_graph(graph)
  312. return graph
  313. def get_frame_vars(self, frames_up):
  314. frame = inspect.currentframe()
  315. if not frame:
  316. raise RuntimeError("failed to inspect frame")
  317. i = 0
  318. while i < frames_up + 1:
  319. frame = frame.f_back
  320. if not frame:
  321. raise RuntimeError("failed to get frame")
  322. i += 1
  323. defined_vars: Dict[str, Any] = {}
  324. defined_vars.update(frame.f_locals)
  325. defined_vars.update(frame.f_globals)
  326. return defined_vars
  327. def assertRaisesRegexWithHighlight(self, exception, regex, highlight):
  328. return _AssertRaisesRegexWithHighlightContext(self, exception, regex, highlight)
  329. def checkScriptRaisesRegex(self, script, inputs, exception, regex,
  330. name=None, outputs=None, capture_output=False,
  331. frames_up=1, profiling=ProfilingMode.PROFILING):
  332. """
  333. Checks that a given function will throw the correct exception,
  334. when executed with normal python, the string frontend, and the
  335. AST frontend. Logic taken from `checkScript` (see comments there
  336. for details)
  337. """
  338. with enable_profiling_mode_for_profiling_tests():
  339. # Normal Python
  340. with self.assertRaisesRegex(exception, regex):
  341. if isinstance(script, str):
  342. frame = self.get_frame_vars(frames_up)
  343. the_locals: Dict[str, Any] = {}
  344. execWrapper(script, glob=frame, loc=the_locals)
  345. frame.update(the_locals)
  346. python_fn = frame[name]
  347. else:
  348. python_fn = script
  349. python_fn(*inputs)
  350. # String frontend
  351. with self.assertRaisesRegex(exception, regex):
  352. if isinstance(script, str):
  353. cu = torch.jit.CompilationUnit(script, _frames_up=frames_up)
  354. string_frontend = getattr(cu, name)
  355. else:
  356. source = textwrap.dedent(inspect.getsource(script))
  357. cu = torch.jit.CompilationUnit(source, _frames_up=frames_up)
  358. string_frontend = getattr(cu, script.__name__)
  359. string_frontend(*inputs)
  360. # Python AST frontend
  361. if not isinstance(script, str):
  362. with self.assertRaisesRegex(exception, regex):
  363. ge = torch.jit.script(python_fn)
  364. ge(*inputs)
  365. def checkBailouts(self, model, inputs, expected):
  366. state = model.get_debug_state()
  367. plan = get_execution_plan(state)
  368. num_bailouts = plan.code.num_bailouts()
  369. for i in range(0, num_bailouts):
  370. plan.code.request_bailout(i)
  371. bailout_outputs = model(*inputs)
  372. self.assertEqual(bailout_outputs, expected)
  373. def checkScript(self,
  374. script,
  375. inputs,
  376. name='func',
  377. optimize=True,
  378. inputs_requires_grad=False,
  379. capture_output=False,
  380. frames_up=1,
  381. profiling=ProfilingMode.PROFILING,
  382. atol=None,
  383. rtol=None):
  384. """
  385. Checks that a given script generates the same output as the Python
  386. version using the given inputs.
  387. """
  388. with torch.jit.optimized_execution(optimize):
  389. with enable_profiling_mode_for_profiling_tests():
  390. extra_profile_runs = any(isinstance(x, torch.Tensor) and x.requires_grad for x in inputs)
  391. if isinstance(script, str):
  392. # Compile the string to a Script function
  393. # with enable_profiling_mode():
  394. cu = torch.jit.CompilationUnit(script, _frames_up=frames_up)
  395. # Execute the Python function so we can run it later and get its
  396. # outputs
  397. frame = self.get_frame_vars(frames_up)
  398. the_locals: Dict[str, Any] = {}
  399. execWrapper(script, glob=frame, loc=the_locals)
  400. frame.update(the_locals)
  401. python_fn = frame[name]
  402. scripted_fn = getattr(cu, name)
  403. else:
  404. # Check the string frontend first
  405. source = textwrap.dedent(inspect.getsource(script))
  406. self.checkScript(
  407. source,
  408. inputs,
  409. script.__name__,
  410. optimize=optimize,
  411. inputs_requires_grad=inputs_requires_grad,
  412. capture_output=capture_output,
  413. profiling=profiling,
  414. frames_up=2)
  415. # Continue checking the Python frontend
  416. scripted_fn = torch.jit.script(script, _frames_up=1)
  417. python_fn = script
  418. if inputs_requires_grad:
  419. recording_inputs = do_input_map(lambda t: t.detach().requires_grad_(), inputs)
  420. else:
  421. recording_inputs = inputs
  422. if capture_output:
  423. with self.capture_stdout() as script_stdout:
  424. script_outputs = scripted_fn(*recording_inputs)
  425. with self.capture_stdout() as opt_script_stdout:
  426. opt_script_outputs = scripted_fn(*recording_inputs)
  427. with self.capture_stdout() as _python_stdout:
  428. python_outputs = python_fn(*inputs)
  429. if not IS_WINDOWS:
  430. self.assertExpected(script_stdout[0], subname='stdout')
  431. self.assertEqual(python_outputs, opt_script_outputs, atol=atol, rtol=rtol)
  432. else:
  433. # profiling run
  434. script_outputs = scripted_fn(*recording_inputs)
  435. if inputs_requires_grad or extra_profile_runs:
  436. opt_script_outputs = scripted_fn(*recording_inputs)
  437. # optimized run
  438. opt_script_outputs = scripted_fn(*recording_inputs)
  439. if TEST_BAILOUTS:
  440. self.checkBailouts(scripted_fn, inputs, opt_script_outputs)
  441. python_outputs = python_fn(*inputs)
  442. self.assertEqual(python_outputs, script_outputs, atol=atol, rtol=rtol)
  443. self.assertEqual(script_outputs, opt_script_outputs, atol=atol, rtol=rtol)
  444. return scripted_fn
  445. def checkTrace(self, func, reference_tensors, input_tensors=None,
  446. drop=None, allow_unused=False, verbose=False,
  447. inputs_require_grads=True, check_tolerance=1e-5, export_import=True,
  448. _force_outplace=False, grad_atol=None, grad_rtol=None):
  449. # TODO: check gradients for parameters, not just inputs
  450. def allSum(vs):
  451. # drop allows us to remove some values from ever being used
  452. # to test unused outputs
  453. if drop is not None:
  454. vs = vs[:-drop]
  455. # we don't want all the grad for all the outputs to be the same
  456. # so we multiply each by a constant
  457. return sum(math.log(i + 2) * v.sum() for i, v in enumerate(vs) if v is not None)
  458. if input_tensors is None:
  459. input_tensors = reference_tensors
  460. def flatten_inputs(inputs):
  461. def input_reduce(input, fn, acc):
  462. if isinstance(input, torch.Tensor):
  463. fn(input, acc)
  464. elif isinstance(input, dict):
  465. reduce(lambda acc, key: input_reduce(input[key], fn, acc), input, acc)
  466. else:
  467. reduce(lambda acc, val: input_reduce(val, fn, acc), input, acc)
  468. return acc
  469. return tuple(input_reduce(recording_inputs, lambda t, acc: acc.append(t), []))
  470. nograd_inputs = reference_tensors
  471. if inputs_require_grads:
  472. recording_inputs = do_input_map(lambda t: t.clone().requires_grad_(), reference_tensors)
  473. flattened_recording_inputs = flatten_inputs(recording_inputs)
  474. else:
  475. recording_inputs = reference_tensors
  476. # `check_trace` is set to False because check_trace is run with @no_grad
  477. # Also, `checkTrace` already does all the checks
  478. # against python function
  479. ge = torch.jit.trace(func, input_tensors, check_tolerance=check_tolerance,
  480. _force_outplace=_force_outplace, check_trace=False)
  481. if export_import:
  482. ge = self.getExportImportCopy(ge)
  483. if verbose:
  484. print(ge.graph)
  485. # test no gradients case
  486. outputs = func(*nograd_inputs)
  487. outputs_ge = ge(*nograd_inputs)
  488. self.assertEqual(outputs, outputs_ge)
  489. # test gradients case
  490. outputs = func(*recording_inputs)
  491. if inputs_require_grads:
  492. grads = torch.autograd.grad(allSum(outputs), flattened_recording_inputs,
  493. allow_unused=allow_unused)
  494. outputs_ge = ge(*recording_inputs)
  495. if inputs_require_grads:
  496. grads_ge = torch.autograd.grad(allSum(outputs_ge), flattened_recording_inputs,
  497. allow_unused=allow_unused)
  498. self.assertEqual(outputs, outputs_ge)
  499. if inputs_require_grads:
  500. self.assertEqual(grads, grads_ge, atol=grad_atol, rtol=grad_rtol)
  501. # test the grad grad case
  502. outputs = func(*recording_inputs)
  503. l1 = allSum(outputs)
  504. if inputs_require_grads:
  505. grads = torch.autograd.grad(l1, flattened_recording_inputs, create_graph=True,
  506. allow_unused=allow_unused)
  507. if inputs_require_grads:
  508. l2 = (allSum(grads) * l1)
  509. grads2 = torch.autograd.grad(l2, flattened_recording_inputs, allow_unused=allow_unused)
  510. if inputs_require_grads:
  511. recording_inputs = do_input_map(lambda t: Variable(t, requires_grad=True), reference_tensors)
  512. flattened_recording_inputs = flatten_inputs(recording_inputs)
  513. outputs_ge = ge(*recording_inputs)
  514. l1_ge = allSum(outputs_ge)
  515. if inputs_require_grads:
  516. grads_ge = torch.autograd.grad(
  517. l1_ge, flattened_recording_inputs, create_graph=True, allow_unused=allow_unused)
  518. if inputs_require_grads:
  519. l2_ge = (allSum(grads_ge) * l1_ge)
  520. grads2_ge = torch.autograd.grad(l2_ge, flattened_recording_inputs, allow_unused=allow_unused)
  521. self.assertEqual(outputs, outputs_ge)
  522. if inputs_require_grads:
  523. self.assertEqual(grads, grads_ge, atol=grad_atol, rtol=grad_rtol)
  524. for g2, g2_ge in zip(grads2, grads2_ge):
  525. if g2 is None and g2_ge is None:
  526. continue
  527. self.assertEqual(g2, g2_ge, atol=8e-4, rtol=8e-4)
  528. return ge
  529. def checkModule(self, nn_module, args):
  530. """
  531. Check that a nn.Module's results in Script mode match eager and that it
  532. can be exported
  533. """
  534. sm = torch.jit.script(nn_module)
  535. with freeze_rng_state():
  536. eager_out = nn_module(*args)
  537. with freeze_rng_state():
  538. script_out = sm(*args)
  539. self.assertEqual(eager_out, script_out)
  540. self.assertExportImportModule(sm, args)
  541. return sm
  542. class NoTracerWarnContextManager:
  543. def __enter__(self):
  544. self.prev = torch._C._jit_get_tracer_state_warn()
  545. torch._C._jit_set_tracer_state_warn(False)
  546. def __exit__(self, *args):
  547. torch._C._jit_set_tracer_state_warn(self.prev)
  548. @contextmanager
  549. def inline_everything_mode(should_inline):
  550. old = torch._C._jit_get_inline_everything_mode()
  551. torch._C._jit_set_inline_everything_mode(should_inline)
  552. try:
  553. yield
  554. finally:
  555. torch._C._jit_set_inline_everything_mode(old)
  556. @contextmanager
  557. def set_fusion_group_inlining(inlining):
  558. old = torch._C._debug_get_fusion_group_inlining()
  559. torch._C._debug_set_fusion_group_inlining(inlining)
  560. try:
  561. yield
  562. finally:
  563. torch._C._debug_set_fusion_group_inlining(old)
  564. # note: not re-entrant, use unnested only
  565. @contextmanager
  566. def disable_autodiff_subgraph_inlining(enabled=True):
  567. torch._C._debug_set_autodiff_subgraph_inlining(not enabled)
  568. try:
  569. yield
  570. finally:
  571. torch._C._debug_set_autodiff_subgraph_inlining(True)
  572. def _inline_everything(fn):
  573. @functools.wraps(fn)
  574. def wrapper(*args, **kwargs):
  575. with inline_everything_mode(True):
  576. fn(*args, **kwargs)
  577. return wrapper
  578. # this exists for forward compatibility reasons temporarily.
  579. # TODO(suo) remove
  580. def _tmp_donotuse_dont_inline_everything(fn):
  581. @functools.wraps(fn)
  582. def wrapper(*args, **kwargs):
  583. with inline_everything_mode(False):
  584. fn(*args, **kwargs)
  585. return wrapper
  586. # make it easy to quicky define/trace a function for these tests
  587. def _trace(*args, **kwargs):
  588. def wrapper(func):
  589. return torch.jit.trace(func, args, **kwargs)
  590. return wrapper
  591. def enable_cpu_fuser(fn):
  592. def wrapper(*args, **kwargs):
  593. torch._C._jit_override_can_fuse_on_cpu_legacy(True)
  594. torch._C._jit_override_can_fuse_on_cpu(True)
  595. torch._C._jit_set_te_must_use_llvm_cpu(False)
  596. try:
  597. fn(*args, **kwargs)
  598. finally:
  599. torch._C._jit_override_can_fuse_on_cpu_legacy(False)
  600. torch._C._jit_override_can_fuse_on_cpu(False)
  601. torch._C._jit_set_te_must_use_llvm_cpu(True)
  602. return wrapper
  603. def enable_cpu_fuser_if(cond):
  604. if cond:
  605. return enable_cpu_fuser
  606. else:
  607. def noop_fuser(fn):
  608. def wrapper(*args, **kwargs):
  609. return fn(*args, **kwargs)
  610. return wrapper
  611. return noop_fuser
  612. def get_forward(c):
  613. return c._get_method('forward')
  614. def get_forward_graph(c):
  615. return c._get_method('forward').graph
  616. def get_module_method(m, module, method):
  617. return m._c.getattr(module)._get_method(method)
  618. def attrs_with_prefix(module, prefix):
  619. return [x for x, _ in module._modules._c.items()
  620. if x.startswith(prefix)]
  621. def warmup_backward(f, *args):
  622. profiling_count = 3
  623. results = []
  624. for i in range(profiling_count):
  625. if len(args) > 0:
  626. r = torch.autograd.grad(f, *args)
  627. results.append(r)
  628. else:
  629. f.backward(retain_graph=True)
  630. return results
  631. # TODO: Remove me once https://bugs.python.org/issue42666 is resolved
  632. def make_global(*args):
  633. for arg in args:
  634. setattr(sys.modules[arg.__module__], arg.__name__, arg)
  635. # Helper function to eval Python3 code without causing a syntax error for
  636. # this file under py2
  637. def _get_py3_code(code, fn_name):
  638. with tempfile.TemporaryDirectory() as tmp_dir:
  639. script_path = os.path.join(tmp_dir, 'script.py')
  640. with open(script_path, 'w') as f:
  641. f.write(code)
  642. spec = importlib.util.spec_from_file_location(fn_name, script_path)
  643. module = importlib.util.module_from_spec(spec)
  644. loader = spec.loader
  645. assert isinstance(loader, Loader) # Assert type to meet MyPy requirement
  646. loader.exec_module(module)
  647. fn = getattr(module, fn_name)
  648. return fn
  649. class TensorExprTestOptions:
  650. def __init__(self):
  651. self.old_profiling_executor = torch._C._jit_set_profiling_executor(True)
  652. self.old_profiling_mode = torch._C._get_graph_executor_optimize(True)
  653. self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu()
  654. self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu()
  655. torch._C._jit_override_can_fuse_on_cpu(True)
  656. torch._C._jit_override_can_fuse_on_gpu(True)
  657. self.texpr_fuser_state = torch._C._jit_texpr_fuser_enabled()
  658. torch._C._jit_set_texpr_fuser_enabled(True)
  659. self.old_fusion_inlining = torch._C._debug_get_fusion_group_inlining()
  660. torch._C._debug_set_fusion_group_inlining(False)
  661. self.old_te_must_use_llvm_cpu = torch._C._jit_get_te_must_use_llvm_cpu()
  662. torch._C._jit_set_te_must_use_llvm_cpu(False)
  663. def restore(self):
  664. torch._C._jit_set_profiling_executor(self.old_profiling_executor)
  665. torch._C._get_graph_executor_optimize(self.old_profiling_mode)
  666. torch._C._jit_set_texpr_fuser_enabled(self.texpr_fuser_state)
  667. torch._C._jit_override_can_fuse_on_gpu(self.old_gpu_fuser_state)
  668. torch._C._jit_override_can_fuse_on_cpu(self.old_cpu_fuser_state)
  669. torch._C._debug_set_fusion_group_inlining(self.old_fusion_inlining)
  670. torch._C._jit_set_te_must_use_llvm_cpu(self.old_te_must_use_llvm_cpu)
  671. def clone_inputs(args):
  672. inputs: List[Union[torch.Tensor, List[torch.Tensor]]] = []
  673. for arg in args:
  674. if isinstance(arg, torch.Tensor):
  675. inputs.append(arg.detach().clone())
  676. elif is_iterable_of_tensors(arg):
  677. inputs.append([t.detach().clone() for t in arg])
  678. else:
  679. inputs.append(arg)
  680. return inputs
  681. def get_traced_sample_variant_pairs(device, dtype, op):
  682. # tuples of (variant, sample)
  683. outputs: List[Tuple[Any, Any]] = []
  684. samples = op.sample_inputs(device, dtype)
  685. # Acquires variants to test
  686. func = op.get_op()
  687. method = op.get_method()
  688. variants = {
  689. # TODO: inplace tests currently fail, fix and add inplace variant
  690. 'function': func, 'method': method,
  691. }
  692. # TODO: find better way to standardize on op registration itself..
  693. has_fake_function = op.name in ["resize_", 'resize_as_']
  694. if has_fake_function:
  695. variants = {'method': getattr(torch.Tensor, op.name)}
  696. # In eager mode, these ops can take (Tensor, bool) args; but in
  697. # JIT they can only take (Tensor, Scalar), and bool is not a
  698. # scalar in the JIT type system. So to test these in JIT, the bool
  699. # is converted to an int for the test.
  700. ops_with_unsupported_bool_args = [
  701. {
  702. "name": "div_floor_rounding",
  703. "arg_idx": [0],
  704. },
  705. {
  706. "name": "div_no_rounding_mode",
  707. "arg_idx": [0],
  708. },
  709. {
  710. "name": "div_trunc_rounding",
  711. "arg_idx": [0],
  712. },
  713. {
  714. "name": "index_fill",
  715. "arg_idx": [2],
  716. },
  717. {
  718. "name": "full_like",
  719. "arg_idx": [0],
  720. },
  721. {
  722. "name": "mul",
  723. "arg_idx": [0],
  724. },
  725. {
  726. "name": "new_full",
  727. "arg_idx": [1],
  728. },
  729. ]
  730. # doesn't support tracing
  731. if has_fake_function:
  732. return outputs
  733. for sample in samples:
  734. for variant in variants.values():
  735. if variant is None:
  736. continue
  737. if is_lambda(variant):
  738. continue
  739. matching_ops = filter(lambda x: op.formatted_name == x["name"], ops_with_unsupported_bool_args)
  740. for op_data in matching_ops:
  741. for idx in op_data["arg_idx"]:
  742. args = list(sample.args)
  743. if len(sample.args) > idx and isinstance(sample.args[idx], bool):
  744. args[idx] = int(args[idx])
  745. sample.args = tuple(args)
  746. outputs.append((variant, sample))
  747. return outputs
  748. # types.LambdaType gave false positives
  749. def is_lambda(lamb):
  750. LAMBDA = lambda: 0 # noqa: E731
  751. return isinstance(lamb, type(LAMBDA)) and lamb.__name__ == LAMBDA.__name__