jit_utils.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. # Torch
  2. from torch.autograd import Variable
  3. from torch.autograd.function import _nested_map
  4. from torch.jit.annotations import BroadcastingList2, BroadcastingList3 # noqa: F401
  5. from torch.onnx import OperatorExportTypes
  6. import torch
  7. import torch.cuda
  8. import torch.jit
  9. import torch.jit._logging
  10. import torch.jit.frontend
  11. import torch.jit.quantized
  12. import zipfile
  13. import functools
  14. # Testing utils
  15. from torch.testing import FileCheck
  16. from torch.testing._internal.common_utils import IS_WINDOWS, \
  17. freeze_rng_state, enable_profiling_mode_for_profiling_tests, ProfilingMode, TEST_BAILOUTS, \
  18. is_iterable_of_tensors
  19. from torch.testing._internal.common_jit import JitCommonTestCase
  20. from torch.testing._internal.common_utils import enable_profiling_mode # noqa: F401
  21. # Standard library
  22. from contextlib import contextmanager
  23. from functools import reduce
  24. from io import StringIO
  25. from collections import defaultdict
  26. import importlib.util
  27. import inspect
  28. import io
  29. import math
  30. import os
  31. import pickle
  32. import sys
  33. import tempfile
  34. import textwrap
  35. from importlib.abc import Loader
  36. from typing import Any, Dict, List, Tuple, Union
  37. RUN_CUDA = torch.cuda.is_available()
  38. RUN_CUDA_MULTI_GPU = RUN_CUDA and torch.cuda.device_count() > 1
  39. RUN_CUDA_HALF = RUN_CUDA
  40. # HIP supports half, no version check necessary
  41. if torch.cuda.is_available() and not torch.version.hip:
  42. CUDA_VERSION = torch._C._cuda_getCompiledVersion()
  43. for d in range(torch.cuda.device_count()):
  44. major = torch.cuda.get_device_capability(d)[0]
  45. if (major < 6):
  46. RUN_CUDA_HALF = False
  47. def execWrapper(code, glob, loc):
  48. exec(code, glob, loc)
  49. def do_input_map(fn, input):
  50. return _nested_map(lambda t: isinstance(t, torch.Tensor), fn)(input)
  51. def clear_class_registry():
  52. torch._C._jit_clear_class_registry()
  53. torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore()
  54. torch.jit._state._clear_class_state()
  55. def get_execution_plan(graph_executor_state):
  56. execution_plans = list(graph_executor_state.execution_plans.values())
  57. num_plans = len(execution_plans)
  58. if num_plans != 1:
  59. raise RuntimeError('This test assumes this GraphExecutor should '
  60. 'only have one execution plan, got: {}'.format(num_plans))
  61. return execution_plans[0]
  62. class _AssertRaisesRegexWithHighlightContext:
  63. """
  64. A context manager that is useful for checking that error messages highlight
  65. the correct part of the source code.
  66. """
  67. def __init__(self, test_case, exception, regex, highlight):
  68. self.test_case = test_case
  69. self.exception_type = exception
  70. self.regex = regex
  71. self.highlight = highlight
  72. def __enter__(self):
  73. return self
  74. def __exit__(self, type, value, traceback):
  75. with self.test_case.assertRaisesRegex(self.exception_type, self.regex):
  76. if type:
  77. raise value
  78. if self.highlight:
  79. FileCheck().check_source_highlighted(self.highlight).run(str(value))
  80. return True
  81. FUSION_GROUP = "prim::TensorExprGroup"
  82. class JitTestCase(JitCommonTestCase):
  83. _do_cuda_memory_leak_check = True
  84. _restored_warnings = False
  85. class capture_stdout(list):
  86. """
  87. Replace sys.stdout with a temporary StringIO
  88. """
  89. def __enter__(self):
  90. self.sys_stdout = sys.stdout
  91. self.stringio = StringIO()
  92. sys.stdout = self.stringio
  93. return self
  94. def __exit__(self, *args):
  95. self.append(str(self.stringio.getvalue()))
  96. del self.stringio
  97. sys.stdout = self.sys_stdout
  98. class capture_stderr(list):
  99. """
  100. Replace sys.stderr with a temporary StringIO
  101. """
  102. def __enter__(self):
  103. self.sys_stderr = sys.stderr
  104. self.stringio = StringIO()
  105. sys.stderr = self.stringio
  106. return self
  107. def __exit__(self, *args):
  108. self.append(str(self.stringio.getvalue()))
  109. del self.stringio
  110. sys.stderr = self.sys_stderr
  111. def setHooks(self):
  112. torch._C._jit_set_emit_hooks(self.emitModuleHook, self.emitFunctionHook)
  113. def clearHooks(self):
  114. torch._C._jit_set_emit_hooks(None, None)
  115. def setUp(self):
  116. super().setUp()
  117. # unittest overrides all warning filters and forces all of them to show up
  118. # after we install our own to silence those coming from inside PyTorch.
  119. # This will ensure that our filter still takes precedence.
  120. if not JitTestCase._restored_warnings:
  121. torch.jit.TracerWarning.ignore_lib_warnings()
  122. JitTestCase._restored_warnings = True
  123. self.setHooks()
  124. def tearDown(self):
  125. super().tearDown()
  126. # needs to be cleared because python might be unloaded before
  127. # the callback gets destucted
  128. self.clearHooks()
  129. clear_class_registry()
  130. def assertAllFused(self, graph, except_for=()):
  131. # note this helper collects nodes on 'fast path' only
  132. # i.e. the true blocks of specialized checks
  133. def get_nodes_and_parents_recursively(block, kind, acc):
  134. for node in block.nodes():
  135. if node.kind() == kind:
  136. acc[block].append(node)
  137. elif node.kind() == 'prim::DifferentiableGraph':
  138. get_nodes_and_parents_recursively(node.g('Subgraph'), kind, acc)
  139. elif node.kind() == 'prim::If' and (node.inputs().__next__().node().kind() == 'aten::all' or
  140. node.inputs().__next__().node().kind() == 'prim::TypeCheck' or
  141. node.inputs().__next__().node().kind() == 'prim::RequiresGradCheck'):
  142. get_nodes_and_parents_recursively(node.blocks().__next__(), kind, acc)
  143. else:
  144. for inner_block in node.blocks():
  145. get_nodes_and_parents_recursively(inner_block, kind, acc)
  146. allowed_nodes = {'prim::Constant', FUSION_GROUP, 'prim::BailoutTemplate',
  147. 'prim::TupleConstruct', 'prim::If', 'prim::TypeCheck', 'prim::RequiresGradCheck'} | set(except_for)
  148. fusion_groups : Dict[torch._C.Block, List[torch._C.Node]] = defaultdict(list)
  149. get_nodes_and_parents_recursively(graph, FUSION_GROUP, fusion_groups)
  150. self.assertTrue(len(fusion_groups) == 1, 'got {}'.format(graph))
  151. (graph, fusion_nodes) = list(fusion_groups.items())[0]
  152. # the block contains one FUSION_GROUP and the rest of nodes are `allowed_nodes`
  153. self.assertTrue(len(fusion_nodes) == 1, 'got {}'.format(graph))
  154. self.assertTrue(all(node.kind() in allowed_nodes for node in graph.nodes()),
  155. 'got {}'.format(graph))
  156. def _isHookExceptionOk(self, e):
  157. se = str(e)
  158. allowed = ("Could not export Python function",
  159. "closures are not exportable")
  160. for a in allowed:
  161. if a in se:
  162. return True
  163. return False
  164. def _compared_saved_loaded(self, m):
  165. def extract_files(buffer):
  166. # crack open the zip format to get at the main module code
  167. archive = zipfile.ZipFile(buffer)
  168. # check that we have no duplicate names
  169. self.assertEqual(len(set(archive.namelist())), len(archive.namelist()))
  170. files = list(filter(lambda x: x.startswith('archive/code/'), archive.namelist()))
  171. # unwrap all the code files into strings
  172. code_files_str = filter(lambda x: x.endswith('.py'), files)
  173. code_files_stream = (archive.open(f) for f in code_files_str)
  174. code_files = ("".join([line.decode() for line in file]) for file in code_files_stream)
  175. # unpickled all the debug files
  176. debug_files_str = filter(lambda f: f.endswith('.debug_pkl'), files)
  177. debug_files_stream = (archive.open(f) for f in debug_files_str)
  178. debug_files = (pickle.load(f) for f in debug_files_stream)
  179. return code_files, debug_files
  180. # disable the hook while we parse code, otherwise we will re-enter the hook
  181. with torch._jit_internal._disable_emit_hooks():
  182. try:
  183. # short-circuit if this is an empty function or module
  184. if len(m.code) == 0:
  185. return
  186. if isinstance(m, torch._C.ScriptModule):
  187. if len(m._method_names()) == 0:
  188. return
  189. # save the module to a buffer
  190. buffer = io.BytesIO()
  191. torch.jit.save(m, buffer)
  192. # copy the data in the buffer so we can restore it later. This
  193. # is because py2 and py3 have different semantics with zipfile
  194. # and it's easier to just work with a fresh copy each time.
  195. buffer_copy = buffer.getvalue()
  196. code_files, debug_files = extract_files(buffer)
  197. except RuntimeError as e:
  198. if not self._isHookExceptionOk(e):
  199. raise
  200. else:
  201. return
  202. # import the model again (from a the copy we made of the original)
  203. buffer2 = io.BytesIO(buffer_copy)
  204. imported = torch.jit.load(buffer2)
  205. # save it again
  206. saved_module_buffer_2 = io.BytesIO()
  207. torch.jit.save(imported, saved_module_buffer_2)
  208. saved_module_buffer_2.seek(0)
  209. code_files_2, debug_files_2 = extract_files(saved_module_buffer_2)
  210. for a, b in zip(code_files, code_files_2):
  211. self.assertMultiLineEqual(a, b)
  212. if isinstance(m, torch._C.ScriptModule):
  213. self.assertTrue(torch._C._ivalue_tags_match(m, imported._c))
  214. def emitFunctionHook(self, func):
  215. # func has invalid names for export, skip the jitter check
  216. if func.name == "<lambda>" or "aten::" in func.name:
  217. return
  218. self._compared_saved_loaded(func)
  219. def emitModuleHook(self, module):
  220. self._compared_saved_loaded(module)
  221. def getExportImportCopyWithPacking(self, m, also_test_file=True, map_location=None):
  222. buffer = io.BytesIO()
  223. m.apply(lambda s: s._pack() if s._c._has_method('_pack') else None)
  224. torch.jit.save(m, buffer)
  225. m.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  226. buffer.seek(0)
  227. imported = torch.jit.load(buffer, map_location=map_location)
  228. imported.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  229. if not also_test_file:
  230. return imported
  231. # Ideally we would like to not have to manually delete the file, but NamedTemporaryFile
  232. # opens the file, and it cannot be opened multiple times in Windows. To support Windows,
  233. # close the file after creation and try to remove it manually
  234. f = tempfile.NamedTemporaryFile(delete=False)
  235. try:
  236. f.close()
  237. imported.save(f.name)
  238. result = torch.jit.load(f.name, map_location=map_location)
  239. finally:
  240. os.unlink(f.name)
  241. result.apply(lambda s: s._unpack() if s._c._has_method('_unpack') else None)
  242. return result
  243. def assertGraphContains(self, graph, kind, consider_subgraphs=False):
  244. if consider_subgraphs:
  245. strgraph = str(graph)
  246. count = strgraph.count(kind) - strgraph.count('with {}'.format(kind))
  247. self.assertTrue(count > 0)
  248. return
  249. def nodes(block):
  250. out = []
  251. for node in block.nodes():
  252. if node.kind() == kind:
  253. out.append(node)
  254. for block in node.blocks():
  255. out += nodes(block)
  256. return out
  257. out_nodes = nodes(graph)
  258. self.assertTrue(len(out_nodes) > 0)
  259. def assertGraphContainsExactly(self, graph, kind, num_kind_nodes, consider_subgraphs=False):
  260. def perform_assert(graph, kind, actual, expected, consider_subgraphs):
  261. if actual == expected:
  262. return
  263. subgraph = 'including' if consider_subgraphs else 'excluding'
  264. raise AssertionError(
  265. '{}\nError: graph contains {} {} nodes ({} subgraphs) but expected {}'.format(
  266. graph, actual, kind, subgraph, expected))
  267. if consider_subgraphs:
  268. strgraph = str(graph)
  269. count = strgraph.count(kind) - strgraph.count('with {}'.format(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):
  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)
  501. self.assertEqual(outputs, outputs_ge)
  502. if inputs_require_grads:
  503. self.assertEqual(grads, grads_ge)
  504. # test the grad grad case
  505. outputs = func(*recording_inputs)
  506. l1 = allSum(outputs)
  507. if inputs_require_grads:
  508. grads = torch.autograd.grad(l1, flattened_recording_inputs, create_graph=True,
  509. allow_unused=allow_unused)
  510. if inputs_require_grads:
  511. l2 = (allSum(grads) * l1)
  512. grads2 = torch.autograd.grad(l2, flattened_recording_inputs, allow_unused=allow_unused)
  513. if inputs_require_grads:
  514. recording_inputs = do_input_map(lambda t: Variable(t, requires_grad=True), reference_tensors)
  515. flattened_recording_inputs = flatten_inputs(recording_inputs)
  516. outputs_ge = ge(*recording_inputs)
  517. l1_ge = allSum(outputs_ge)
  518. if inputs_require_grads:
  519. grads_ge = torch.autograd.grad(
  520. l1_ge, flattened_recording_inputs, create_graph=True, allow_unused=allow_unused)
  521. if inputs_require_grads:
  522. l2_ge = (allSum(grads_ge) * l1_ge)
  523. grads2_ge = torch.autograd.grad(l2_ge, flattened_recording_inputs, allow_unused=allow_unused)
  524. self.assertEqual(outputs, outputs_ge)
  525. if inputs_require_grads:
  526. self.assertEqual(grads, grads_ge)
  527. for g2, g2_ge in zip(grads2, grads2_ge):
  528. if g2 is None and g2_ge is None:
  529. continue
  530. self.assertEqual(g2, g2_ge, atol=8e-4, rtol=8e-4)
  531. return ge
  532. def checkModule(self, nn_module, args):
  533. """
  534. Check that a nn.Module's results in Script mode match eager and that it
  535. can be exported
  536. """
  537. sm = torch.jit.script(nn_module)
  538. with freeze_rng_state():
  539. eager_out = nn_module(*args)
  540. with freeze_rng_state():
  541. script_out = sm(*args)
  542. self.assertEqual(eager_out, script_out)
  543. self.assertExportImportModule(sm, args)
  544. return sm
  545. class NoTracerWarnContextManager:
  546. def __enter__(self):
  547. self.prev = torch._C._jit_get_tracer_state_warn()
  548. torch._C._jit_set_tracer_state_warn(False)
  549. def __exit__(self, *args):
  550. torch._C._jit_set_tracer_state_warn(self.prev)
  551. @contextmanager
  552. def inline_everything_mode(should_inline):
  553. old = torch._C._jit_get_inline_everything_mode()
  554. torch._C._jit_set_inline_everything_mode(should_inline)
  555. try:
  556. yield
  557. finally:
  558. torch._C._jit_set_inline_everything_mode(old)
  559. @contextmanager
  560. def set_fusion_group_inlining(inlining):
  561. old = torch._C._debug_get_fusion_group_inlining()
  562. torch._C._debug_set_fusion_group_inlining(inlining)
  563. try:
  564. yield
  565. finally:
  566. torch._C._debug_set_fusion_group_inlining(old)
  567. # note: not re-entrant, use unnested only
  568. @contextmanager
  569. def disable_autodiff_subgraph_inlining(enabled=True):
  570. torch._C._debug_set_autodiff_subgraph_inlining(not enabled)
  571. try:
  572. yield
  573. finally:
  574. torch._C._debug_set_autodiff_subgraph_inlining(True)
  575. def _inline_everything(fn):
  576. @functools.wraps(fn)
  577. def wrapper(*args, **kwargs):
  578. with inline_everything_mode(True):
  579. fn(*args, **kwargs)
  580. return wrapper
  581. # this exists for forward compatibility reasons temporarily.
  582. # TODO(suo) remove
  583. def _tmp_donotuse_dont_inline_everything(fn):
  584. @functools.wraps(fn)
  585. def wrapper(*args, **kwargs):
  586. with inline_everything_mode(False):
  587. fn(*args, **kwargs)
  588. return wrapper
  589. # make it easy to quicky define/trace a function for these tests
  590. def _trace(*args, **kwargs):
  591. def wrapper(func):
  592. return torch.jit.trace(func, args, **kwargs)
  593. return wrapper
  594. def enable_cpu_fuser(fn):
  595. def wrapper(*args, **kwargs):
  596. torch._C._jit_override_can_fuse_on_cpu_legacy(True)
  597. torch._C._jit_override_can_fuse_on_cpu(True)
  598. torch._C._jit_set_te_must_use_llvm_cpu(False)
  599. try:
  600. fn(*args, **kwargs)
  601. finally:
  602. torch._C._jit_override_can_fuse_on_cpu_legacy(False)
  603. torch._C._jit_override_can_fuse_on_cpu(False)
  604. torch._C._jit_set_te_must_use_llvm_cpu(True)
  605. return wrapper
  606. def enable_cpu_fuser_if(cond):
  607. if cond:
  608. return enable_cpu_fuser
  609. else:
  610. def noop_fuser(fn):
  611. def wrapper(*args, **kwargs):
  612. return fn(*args, **kwargs)
  613. return wrapper
  614. return noop_fuser
  615. def get_forward(c):
  616. return c._get_method('forward')
  617. def get_forward_graph(c):
  618. return c._get_method('forward').graph
  619. def get_module_method(m, module, method):
  620. return m._c.getattr(module)._get_method(method)
  621. def attrs_with_prefix(module, prefix):
  622. return [x for x, _ in module._modules._c.items()
  623. if x.startswith(prefix)]
  624. def warmup_backward(f, *args):
  625. profiling_count = 3
  626. results = []
  627. for i in range(profiling_count):
  628. if len(args) > 0:
  629. r = torch.autograd.grad(f, *args)
  630. results.append(r)
  631. else:
  632. f.backward(retain_graph=True)
  633. return results
  634. # TODO: Remove me once https://bugs.python.org/issue42666 is resolved
  635. def make_global(*args):
  636. for arg in args:
  637. setattr(sys.modules[arg.__module__], arg.__name__, arg)
  638. # Helper function to eval Python3 code without causing a syntax error for
  639. # this file under py2
  640. def _get_py3_code(code, fn_name):
  641. with tempfile.TemporaryDirectory() as tmp_dir:
  642. script_path = os.path.join(tmp_dir, 'script.py')
  643. with open(script_path, 'w') as f:
  644. f.write(code)
  645. spec = importlib.util.spec_from_file_location(fn_name, script_path)
  646. module = importlib.util.module_from_spec(spec)
  647. loader = spec.loader
  648. assert isinstance(loader, Loader) # Assert type to meet MyPy requriement
  649. loader.exec_module(module)
  650. fn = getattr(module, fn_name)
  651. return fn
  652. class TensorExprTestOptions():
  653. def __init__(self):
  654. self.old_profiling_executor = torch._C._jit_set_profiling_executor(True)
  655. self.old_profiling_mode = torch._C._get_graph_executor_optimize(True)
  656. self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu()
  657. self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu()
  658. torch._C._jit_override_can_fuse_on_cpu(True)
  659. torch._C._jit_override_can_fuse_on_gpu(True)
  660. self.texpr_fuser_state = torch._C._jit_texpr_fuser_enabled()
  661. torch._C._jit_set_texpr_fuser_enabled(True)
  662. self.old_fusion_inlining = torch._C._debug_get_fusion_group_inlining()
  663. torch._C._debug_set_fusion_group_inlining(False)
  664. self.old_te_must_use_llvm_cpu = torch._C._jit_get_te_must_use_llvm_cpu()
  665. torch._C._jit_set_te_must_use_llvm_cpu(False)
  666. self.old_nvfuser = torch._C._jit_set_nvfuser_enabled(False)
  667. def restore(self):
  668. torch._C._jit_set_profiling_executor(self.old_profiling_executor)
  669. torch._C._get_graph_executor_optimize(self.old_profiling_mode)
  670. torch._C._jit_set_texpr_fuser_enabled(self.texpr_fuser_state)
  671. torch._C._jit_override_can_fuse_on_gpu(self.old_gpu_fuser_state)
  672. torch._C._jit_override_can_fuse_on_cpu(self.old_cpu_fuser_state)
  673. torch._C._debug_set_fusion_group_inlining(self.old_fusion_inlining)
  674. torch._C._jit_set_te_must_use_llvm_cpu(self.old_te_must_use_llvm_cpu)
  675. torch._C._jit_set_nvfuser_enabled(self.old_nvfuser)
  676. def clone_inputs(args):
  677. inputs: List[Union[torch.Tensor, List[torch.Tensor]]] = []
  678. for arg in args:
  679. if isinstance(arg, torch.Tensor):
  680. inputs.append(arg.detach().clone())
  681. elif is_iterable_of_tensors(arg):
  682. inputs.append([t.detach().clone() for t in arg])
  683. else:
  684. inputs.append(arg)
  685. return inputs
  686. def get_traced_sample_variant_pairs(device, dtype, op):
  687. # tuples of (variant, sample)
  688. outputs: List[Tuple[Any, Any]] = []
  689. samples = op.sample_inputs(device, dtype)
  690. # Acquires variants to test
  691. func = op.get_op()
  692. method = op.get_method()
  693. variants = {
  694. # TODO: inplace tests currently fail, fix and add inplace variant
  695. 'function': func, 'method': method,
  696. }
  697. # TODO: find better way to standardize on op registration itself..
  698. has_fake_function = op.name in ["resize_", 'resize_as_']
  699. if has_fake_function:
  700. variants = {'method': getattr(torch.Tensor, op.name)}
  701. # In eager mode, these ops can take (Tensor, bool) args; but in
  702. # JIT they can only take (Tensor, Scalar), and bool is not a
  703. # scalar in the JIT type system. So to test these in JIT, the bool
  704. # is converted to an int for the test.
  705. ops_with_unsupported_bool_args = [
  706. {
  707. "name": "div_floor_rounding",
  708. "arg_idx": [0],
  709. },
  710. {
  711. "name": "div_no_rounding_mode",
  712. "arg_idx": [0],
  713. },
  714. {
  715. "name": "div_trunc_rounding",
  716. "arg_idx": [0],
  717. },
  718. {
  719. "name": "index_fill",
  720. "arg_idx": [2],
  721. },
  722. {
  723. "name": "full_like",
  724. "arg_idx": [0],
  725. },
  726. {
  727. "name": "mul",
  728. "arg_idx": [0],
  729. },
  730. {
  731. "name": "new_full",
  732. "arg_idx": [1],
  733. },
  734. ]
  735. # doesn't support tracing
  736. if has_fake_function:
  737. return outputs
  738. for sample in samples:
  739. for func_type, variant in variants.items():
  740. if variant is None:
  741. continue
  742. if is_lambda(variant):
  743. continue
  744. matching_ops = filter(lambda x: op.formatted_name == x["name"], ops_with_unsupported_bool_args)
  745. for op_data in matching_ops:
  746. for idx in op_data["arg_idx"]:
  747. args = list(sample.args)
  748. if len(sample.args) > idx and isinstance(sample.args[idx], bool):
  749. args[idx] = int(args[idx])
  750. sample.args = tuple(args)
  751. outputs.append((variant, sample))
  752. return outputs
  753. # types.LambdaType gave false positives
  754. def is_lambda(lamb):
  755. LAMBDA = lambda: 0 # noqa: E731
  756. return isinstance(lamb, type(LAMBDA)) and lamb.__name__ == LAMBDA.__name__