_jit_internal.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. """
  2. The weak_script annotation needs to be here instead of inside torch/jit/ so it
  3. can be used in other places in torch/ (namely torch.nn) without running into
  4. circular dependency problems
  5. """
  6. import contextlib
  7. import collections
  8. import enum
  9. import inspect
  10. import ast
  11. import weakref
  12. import warnings
  13. from textwrap import dedent
  14. import torch
  15. import sys
  16. import builtins
  17. import typing
  18. import io
  19. import pickle
  20. import threading
  21. # This is needed. `torch._jit_internal` is imported before `torch.distributed.__init__`.
  22. # Explicitly ask to import `torch.distributed.__init__` first.
  23. # Otherwise, "AttributeError: module 'torch' has no attribute 'distributed'" is raised.
  24. import torch.distributed.rpc
  25. from torch._C import Future as CFuture
  26. from torch._sources import get_source_lines_and_file, parse_def, fake_range
  27. from torch.futures import Future
  28. import torch.package._mangling as package_mangling
  29. from typing import Any, Callable, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union # noqa: F401
  30. if sys.version_info[:2] > (3, 7):
  31. from typing import Final
  32. else:
  33. from typing_extensions import Final
  34. LockType: Type
  35. try:
  36. import _thread
  37. LockType = _thread.LockType
  38. except ImportError:
  39. import _dummy_thread
  40. LockType = _dummy_thread.LockType
  41. # Wrapper functions that can call either of 2 functions depending on a boolean
  42. # argument
  43. boolean_dispatched: 'weakref.WeakKeyDictionary[Callable, Dict[str, Callable]]' = weakref.WeakKeyDictionary() # noqa: T484
  44. def createResolutionCallbackFromEnv(lookup_base):
  45. """
  46. Creates a resolution callback that will look up qualified names in an
  47. environment, starting with `lookup_base` for the base of any qualified
  48. names, then proceeding down the lookup chain with the resolved object.
  49. You should not use this directly, it should only be used from the other
  50. createResolutionCallbackFrom* functions.
  51. """
  52. def lookupInModule(qualified_name, module):
  53. if '.' in qualified_name:
  54. parts = qualified_name.split('.')
  55. base = parts[0]
  56. remaining_pieces = '.'.join(parts[1:])
  57. module_value = getattr(module, base)
  58. return lookupInModule(remaining_pieces, module_value)
  59. else:
  60. return getattr(module, qualified_name)
  61. def parseNestedExpr(expr, module) -> Tuple[Any, int]:
  62. i = 0
  63. while i < len(expr) and expr[i] not in (',', '[', ']'):
  64. i += 1
  65. # Special case logic for the empty Tuple as a subscript (used
  66. # in the type annotation `Tuple[()]`)
  67. if expr[:i] == '()':
  68. return (), i
  69. base = lookupInModule(expr[:i].strip(), module)
  70. assert base is not None, f"Unresolvable type {expr[:i]}"
  71. if i == len(expr) or expr[i] != '[':
  72. return base, i
  73. assert expr[i] == '['
  74. parts = []
  75. while expr[i] != ']':
  76. part_len = 0
  77. i += 1
  78. part, part_len = parseNestedExpr(expr[i:], module)
  79. parts.append(part)
  80. i += part_len
  81. if len(parts) > 1:
  82. return base[tuple(parts)], i + 1
  83. else:
  84. return base[parts[0]], i + 1
  85. def parseExpr(expr, module):
  86. try:
  87. value, len_parsed = parseNestedExpr(expr, module)
  88. assert len_parsed == len(expr), "whole expression was not parsed, falling back to c++ parser"
  89. return value
  90. except Exception:
  91. """
  92. The python resolver fails in several cases in known unit tests, and is intended
  93. to fall back gracefully to the c++ resolver in general. For example, python 2 style
  94. annotations which are frequent in our unit tests often fail with types e.g. int not
  95. resolvable from the calling frame.
  96. """
  97. return None
  98. return lambda expr: parseExpr(expr, lookup_base)
  99. def createResolutionCallbackFromFrame(frames_up: int = 0):
  100. """
  101. Creates a function which, given a string variable name,
  102. returns the value of the variable in the scope of the caller of
  103. the function which called createResolutionCallbackFromFrame (by default).
  104. This is used to enable access in-scope Python variables inside
  105. TorchScript fragments.
  106. frames_up is number of additional frames to go up on the stack.
  107. The default value is 0, which correspond to the frame of the caller
  108. of createResolutionCallbackFromFrame. Also for example, if frames_up is set
  109. to 1, then the frame of the caller's caller of createResolutionCallbackFromFrame
  110. will be taken.
  111. For example, the following program prints 2::
  112. def bar():
  113. cb = createResolutionCallbackFromFrame(1)
  114. print(cb("foo"))
  115. def baz():
  116. foo = 2
  117. bar()
  118. baz()
  119. """
  120. frame = inspect.currentframe()
  121. i = 0
  122. while i < frames_up + 1:
  123. assert frame is not None
  124. frame = frame.f_back
  125. i += 1
  126. assert frame is not None
  127. f_locals = frame.f_locals
  128. f_globals = frame.f_globals
  129. class env(object):
  130. def __getattr__(self, key):
  131. if key in f_locals:
  132. return f_locals[key]
  133. elif key in f_globals:
  134. return f_globals[key]
  135. elif key in dir(builtins):
  136. return getattr(builtins, key)
  137. return createResolutionCallbackFromEnv(env())
  138. def get_closure(fn):
  139. """
  140. Get a dictionary of closed over variables from a function
  141. """
  142. captures = {}
  143. captures.update(fn.__globals__)
  144. for index, captured_name in enumerate(fn.__code__.co_freevars):
  145. captures[captured_name] = fn.__closure__[index].cell_contents
  146. return captures
  147. # [local resolution in python]
  148. # Depending on where a variable is defined, and where it is used, we may
  149. # or may not be able to recover its value when recursively compiling a
  150. # script function. Remember in the general case, a module or function is
  151. # first defined and then later scripted. This means we do not have a
  152. # chance to capture the active frames when the function is defined. Hence any
  153. # name resolution has to happen later on the created closure. The way
  154. # python captures type annotations restricts what we can recover. The
  155. # follow example illustrates the different cases:
  156. #
  157. # class MyGlobalClass:
  158. # ...
  159. # def my_local_scope():
  160. # @torch.jit.script
  161. # class MyClass:
  162. # ...
  163. # @torch.jit.script
  164. # class MyClassUsedAsVar:
  165. # ...
  166. # def eg(x: MyClass, y: MyGlobalClass):
  167. # a_local_capture : Foo
  168. # return MyClassUsedAsVar(x)
  169. #
  170. # MyGlobalClass is defined in the __globals__ dictionary of function
  171. # 'eg', so it is always recoverable. my_local_scope introduces a new local
  172. # variable scope in the function. Classes defined here are only visible as
  173. # local variables. For the case of MyClassUsedAsVar, it is captured
  174. # because it is used as a variable inside the body of the function, and we
  175. # can resolve it using the captures returned from `get_closure`. However,
  176. # the type annotations are not captured by the closure. In Python
  177. # 3.0--3.9, the _value_ of MyClass and MyGlobalClass will be available as
  178. # annotations on `eg``, but starting in Python 4.0, they will represented as
  179. # strings and no longer present. Furthermore, since the body of `eg` does
  180. # not reference those names, they do not appear in the list of closed over
  181. # variables. In Python 2.x, type annotations are in comments, leading to a
  182. # similar situation where their definitions are not available. We anticipate
  183. # that most users will not run into this issue because their modules and
  184. # functions will be defined at a global scope like MyGlobalClass. In cases
  185. # where they are not, it is possible to work around issues by declaring the
  186. # values global in the function.
  187. # In Python 3.9 declaring class as global will make it invisible to
  188. # `inspect.getsource`, see https://bugs.python.org/issue42666 .
  189. # This could be worked around by manualy adding it to `global()` dictionary.
  190. def createResolutionCallbackFromClosure(fn):
  191. """
  192. Create a resolutionCallback by introspecting the function instead of
  193. looking up the stack for the enclosing scope
  194. """
  195. closure = get_closure(fn)
  196. class closure_lookup(object):
  197. # This is a class since `closure` is a dict and it's easier in
  198. # `env_helper` if everything just works with `getattr` calls
  199. def __getattr__(self, key):
  200. if key in closure:
  201. return closure[key]
  202. elif hasattr(typing, key):
  203. return getattr(typing, key)
  204. elif hasattr(builtins, key):
  205. return getattr(builtins, key)
  206. return None
  207. return createResolutionCallbackFromEnv(closure_lookup())
  208. def can_compile_class(cls) -> bool:
  209. # If any of the functions on a type don't have a code object, this type can't
  210. # be compiled and is probably a builtin / bound from C
  211. if is_ignored_fn(cls):
  212. return False
  213. # Ignore the following list of built-in classes.
  214. ignored_builtin_classes = (torch.nn.Module, tuple, list, Exception)
  215. if issubclass(cls, ignored_builtin_classes):
  216. return False
  217. names = cls.__dict__
  218. fns = [getattr(cls, name) for name in names if inspect.isroutine(getattr(cls, name, None))]
  219. has_code = [hasattr(fn, '__code__') for fn in fns]
  220. return all(has_code)
  221. def get_callable_argument_names(fn) -> List[str]:
  222. """
  223. Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`.
  224. Returns an empty list when other types of arguments are present.
  225. This is used by `torch.jit.trace` to assign meaningful argument names to
  226. traced functions and modules.
  227. Args:
  228. fn: A callable.
  229. Returns:
  230. Argument names: List[str]
  231. """
  232. # inspect.signature may fail, give up in that case.
  233. try:
  234. callable_signature = inspect.signature(fn)
  235. except Exception:
  236. return []
  237. argument_names = []
  238. for name, param in callable_signature.parameters.items():
  239. # All four other types of arguments do not map to individual values
  240. # with a keyword as name.
  241. if not param.kind == param.POSITIONAL_OR_KEYWORD:
  242. return []
  243. argument_names.append(name)
  244. return argument_names
  245. def get_annotation_str(annotation):
  246. """
  247. Convert an AST node containing a type annotation to the string present in the source
  248. that represents the same annotation.
  249. """
  250. if isinstance(annotation, ast.Name):
  251. return annotation.id
  252. elif isinstance(annotation, ast.Attribute):
  253. return '.'.join([get_annotation_str(annotation.value), annotation.attr])
  254. elif isinstance(annotation, ast.Subscript):
  255. # In Python3.9+ subscript indicies are not wrapped in ast.Index
  256. subscript_slice = annotation.slice if sys.version_info >= (3, 9) else annotation.slice.value # type: ignore[attr-defined]
  257. return f"{get_annotation_str(annotation.value)}[{get_annotation_str(subscript_slice)}]"
  258. elif isinstance(annotation, ast.Tuple):
  259. return ','.join([get_annotation_str(elt) for elt in annotation.elts])
  260. elif isinstance(annotation, ast.Constant) or isinstance(annotation, ast.NameConstant):
  261. return f"{annotation.value}"
  262. # If an AST node is not handled here, it's probably handled in ScriptTypeParser.
  263. return None
  264. def get_type_hint_captures(fn):
  265. """
  266. Get a dictionary containing type resolution mappings necessary to resolve types
  267. for the literal annotations on 'fn'. These are not considered to be closed-over by fn
  268. and must be obtained separately (e.g. using this function).
  269. Args:
  270. fn: A callable.
  271. Returns:
  272. A Dict[str, Any] containing a mapping from the literal annotations used on
  273. fn to the Python objects they refer to.
  274. """
  275. # Gather a dictionary of parameter name -> type, skipping any parameters whose annotated
  276. # types are strings. These are only understood by TorchScript in the context of a type annotation
  277. # that refers to a class in its own definition, but trying to include a mapping for this in the result
  278. # function would cause infinite recursion because the class is currently being compiled.
  279. # In addition, there is logic in ScriptTypeParser to handle this.
  280. signature = inspect.signature(fn)
  281. name_to_type = {
  282. name: parameter.annotation
  283. for name, parameter in signature.parameters.items()
  284. if parameter.annotation is not inspect.Parameter.empty and not isinstance(parameter.annotation, str)
  285. }
  286. # Then, get the literal type annotations from the function declaration
  287. # by source inspection. This accounts for the case in which aliases are used
  288. # to annotate the arguments (e.g device_t = torch.device, and then d: device_t).
  289. src = inspect.getsource(fn)
  290. # frontend.py cannot be used here because it includes _jit_internal, so use ast instead.
  291. a = ast.parse(dedent(src))
  292. if len(a.body) != 1 or not isinstance(a.body[0], ast.FunctionDef):
  293. raise RuntimeError(f"Expected {fn} to be a function")
  294. f = a.body[0]
  295. # Prepare a dictionary of source annotation -> type, which will be the final result of this function,
  296. # by using the parsed AST (f) to reconstruct source annotations as strings for each parameter and mapping
  297. # them to the type object corresponding to the annotation via name_to_type using the parameter name.
  298. annotation_to_type = {}
  299. for arg in f.args.args:
  300. # Get the source type annotation string for this argument if possible.
  301. arg_annotation_str = get_annotation_str(arg.annotation) if arg.annotation else None
  302. # If the argument has no annotation or get_annotation_str cannot convert it to a string,
  303. # arg_annotation_str will be None. Skip this arg; ScriptTypeParser will probably handle
  304. # this in the latter case.
  305. if arg_annotation_str is None:
  306. continue
  307. # Insert {arg_annotation_str: type} into annotation_to_type if possible. One reason arg_name may not
  308. # be present in name_to_type is that the annotation itself is a string and not a type object
  309. # (common for self-refential annotations in classes). Once again, let ScriptTypeParser handle this.
  310. arg_name = arg.arg
  311. if arg_name in name_to_type:
  312. annotation_to_type[arg_annotation_str] = name_to_type[arg_name]
  313. # If there is a valid return annotation, include it in annotation_to_type. As with argument annotations,
  314. # the literal annotation has to be convertible to a string by get_annotation_str, and the actual type
  315. # of the annotation cannot be a string.
  316. literal_return_annotation = get_annotation_str(f.returns)
  317. valid_literal_annotation = literal_return_annotation is not None
  318. return_annotation = signature.return_annotation
  319. valid_return_annotation_type = return_annotation is not inspect.Parameter.empty and not isinstance(return_annotation, str)
  320. if valid_literal_annotation and valid_return_annotation_type:
  321. annotation_to_type[literal_return_annotation] = return_annotation
  322. return annotation_to_type
  323. def createResolutionCallbackForClassMethods(cls):
  324. """
  325. This looks at all the methods defined in a class and pulls their closed-over
  326. variables into a dictionary and uses that to resolve variables.
  327. """
  328. # cls is a type here, so `ismethod` is false since the methods on the type
  329. # aren't bound to anything, so Python treats them as regular functions
  330. fns = [getattr(cls, name) for name in cls.__dict__ if inspect.isroutine(getattr(cls, name))]
  331. captures = {}
  332. for fn in fns:
  333. captures.update(get_closure(fn))
  334. captures.update(get_type_hint_captures(fn))
  335. def lookup_in_class(key):
  336. if key in captures:
  337. return captures[key]
  338. else:
  339. return getattr(builtins, key, None)
  340. return lookup_in_class
  341. def boolean_dispatch(arg_name, arg_index, default, if_true, if_false, module_name, func_name):
  342. """
  343. Dispatches to either of 2 script functions based on a boolean argument.
  344. In TorchScript, the boolean argument must be constant so that the correct
  345. function to use can be determined at compile time.
  346. """
  347. def fn(*args, **kwargs):
  348. dispatch_flag = False
  349. if arg_name in kwargs:
  350. dispatch_flag = kwargs[arg_name]
  351. elif arg_index < len(args):
  352. dispatch_flag = args[arg_index]
  353. if dispatch_flag:
  354. return if_true(*args, **kwargs)
  355. else:
  356. return if_false(*args, **kwargs)
  357. if if_true.__doc__ is None and if_false.__doc__ is not None:
  358. doc = if_false.__doc__
  359. if_true.__doc__ = doc
  360. elif if_false.__doc__ is None and if_true.__doc__ is not None:
  361. doc = if_true.__doc__
  362. if_false.__doc__ = doc
  363. elif if_false.__doc__ is None and if_true.__doc__ is None:
  364. # neither function has a docstring
  365. doc = None
  366. else:
  367. raise RuntimeError("only one function can have a docstring")
  368. fn.__doc__ = doc
  369. if module_name is not None:
  370. fn.__module__ = module_name
  371. if func_name is not None:
  372. fn.__name__ = func_name
  373. boolean_dispatched[fn] = {
  374. "if_true": if_true,
  375. "if_false": if_false,
  376. "index": arg_index,
  377. "default": default,
  378. "arg_name": arg_name
  379. }
  380. return fn
  381. class FunctionModifiers(object):
  382. """
  383. Used to denote the behavior of a function in TorchScript. See export() and
  384. ignore() for details.
  385. """
  386. UNUSED = "unused (ignored and replaced with raising of an exception)"
  387. IGNORE = "ignore (leave as a call to Python, cannot be torch.jit.save'd)"
  388. EXPORT = "export (compile this function even if nothing calls it)"
  389. DEFAULT = "default (compile if called from a exported function / forward)"
  390. COPY_TO_SCRIPT_WRAPPER = \
  391. "if this method is not scripted, copy the python method onto the scripted model"
  392. def export(fn):
  393. """
  394. This decorator indicates that a method on an ``nn.Module`` is used as an entry point into a
  395. :class:`ScriptModule` and should be compiled.
  396. ``forward`` implicitly is assumed to be an entry point, so it does not need this decorator.
  397. Functions and methods called from ``forward`` are compiled as they are seen
  398. by the compiler, so they do not need this decorator either.
  399. Example (using ``@torch.jit.export`` on a method):
  400. .. testcode::
  401. import torch
  402. import torch.nn as nn
  403. class MyModule(nn.Module):
  404. def implicitly_compiled_method(self, x):
  405. return x + 99
  406. # `forward` is implicitly decorated with `@torch.jit.export`,
  407. # so adding it here would have no effect
  408. def forward(self, x):
  409. return x + 10
  410. @torch.jit.export
  411. def another_forward(self, x):
  412. # When the compiler sees this call, it will compile
  413. # `implicitly_compiled_method`
  414. return self.implicitly_compiled_method(x)
  415. def unused_method(self, x):
  416. return x - 20
  417. # `m` will contain compiled methods:
  418. # `forward`
  419. # `another_forward`
  420. # `implicitly_compiled_method`
  421. # `unused_method` will not be compiled since it was not called from
  422. # any compiled methods and wasn't decorated with `@torch.jit.export`
  423. m = torch.jit.script(MyModule())
  424. """
  425. fn._torchscript_modifier = FunctionModifiers.EXPORT
  426. return fn
  427. def unused(fn):
  428. """
  429. This decorator indicates to the compiler that a function or method should
  430. be ignored and replaced with the raising of an exception. This allows you
  431. to leave code in your model that is not yet TorchScript compatible and still
  432. export your model.
  433. Example (using ``@torch.jit.unused`` on a method)::
  434. import torch
  435. import torch.nn as nn
  436. class MyModule(nn.Module):
  437. def __init__(self, use_memory_efficient):
  438. super(MyModule, self).__init__()
  439. self.use_memory_efficient = use_memory_efficient
  440. @torch.jit.unused
  441. def memory_efficient(self, x):
  442. import pdb
  443. pdb.set_trace()
  444. return x + 10
  445. def forward(self, x):
  446. # Use not-yet-scriptable memory efficient mode
  447. if self.use_memory_efficient:
  448. return self.memory_efficient(x)
  449. else:
  450. return x + 10
  451. m = torch.jit.script(MyModule(use_memory_efficient=False))
  452. m.save("m.pt")
  453. m = torch.jit.script(MyModule(use_memory_efficient=True))
  454. # exception raised
  455. m(torch.rand(100))
  456. """
  457. if isinstance(fn, property):
  458. prop = fn
  459. setattr(prop.fget, "_torchscript_modifier", FunctionModifiers.UNUSED) # noqa: B010
  460. if prop.fset:
  461. setattr(prop.fset, "_torchscript_modifier", FunctionModifiers.UNUSED) # noqa: B010
  462. return prop
  463. fn._torchscript_modifier = FunctionModifiers.UNUSED
  464. return fn
  465. # No op context manager from python side
  466. class _IgnoreContextManager(contextlib.AbstractContextManager):
  467. def __init__(self, **kwargs):
  468. pass
  469. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  470. pass
  471. def ignore(drop=False, **kwargs):
  472. """
  473. This decorator indicates to the compiler that a function or method should
  474. be ignored and left as a Python function. This allows you to leave code in
  475. your model that is not yet TorchScript compatible. If called from TorchScript,
  476. ignored functions will dispatch the call to the Python interpreter. Models with ignored
  477. functions cannot be exported; use :func:`@torch.jit.unused <torch.jit.unused>` instead.
  478. Example (using ``@torch.jit.ignore`` on a method)::
  479. import torch
  480. import torch.nn as nn
  481. class MyModule(nn.Module):
  482. @torch.jit.ignore
  483. def debugger(self, x):
  484. import pdb
  485. pdb.set_trace()
  486. def forward(self, x):
  487. x += 10
  488. # The compiler would normally try to compile `debugger`,
  489. # but since it is `@ignore`d, it will be left as a call
  490. # to Python
  491. self.debugger(x)
  492. return x
  493. m = torch.jit.script(MyModule())
  494. # Error! The call `debugger` cannot be saved since it calls into Python
  495. m.save("m.pt")
  496. Example (using ``@torch.jit.ignore(drop=True)`` on a method):
  497. .. testcode::
  498. import torch
  499. import torch.nn as nn
  500. class MyModule(nn.Module):
  501. @torch.jit.ignore(drop=True)
  502. def training_method(self, x):
  503. import pdb
  504. pdb.set_trace()
  505. def forward(self, x):
  506. if self.training:
  507. self.training_method(x)
  508. return x
  509. m = torch.jit.script(MyModule())
  510. # This is OK since `training_method` is not saved, the call is replaced
  511. # with a `raise`.
  512. m.save("m.pt")
  513. .. testcleanup::
  514. import os
  515. os.remove('m.pt')
  516. """
  517. if callable(drop):
  518. # used without any args, so drop is actually a function
  519. # @torch.jit.ignore
  520. # def fn(...):
  521. fn = drop
  522. fn._torchscript_modifier = FunctionModifiers.IGNORE
  523. return fn
  524. if not isinstance(drop, bool):
  525. raise RuntimeError("Argument to @torch.jit.ignore must be a bool or "
  526. f"a function but got {drop}")
  527. # for backwards compat
  528. drop_on_export = kwargs.pop("drop_on_export", None)
  529. if drop_on_export:
  530. warnings.warn("ignore(drop_on_export=True) has been deprecated. TorchScript will now drop the function "
  531. "call on compilation. Use torch.jit.unused now. {}", category=FutureWarning)
  532. drop = drop_on_export
  533. elif drop:
  534. warnings.warn("ignore(True) has been deprecated. TorchScript will now drop the function "
  535. "call on compilation. Use torch.jit.unused now. {}", category=FutureWarning)
  536. def decorator(fn):
  537. if drop:
  538. fn._torchscript_modifier = FunctionModifiers.UNUSED
  539. else:
  540. fn._torchscript_modifier = FunctionModifiers.IGNORE
  541. return fn
  542. return decorator
  543. def _copy_to_script_wrapper(fn):
  544. fn._torchscript_modifier = FunctionModifiers.COPY_TO_SCRIPT_WRAPPER
  545. return fn
  546. def module_has_exports(mod):
  547. for name in dir(mod):
  548. if hasattr(mod, name):
  549. item = getattr(mod, name)
  550. if callable(item):
  551. if get_torchscript_modifier(item) is FunctionModifiers.EXPORT:
  552. return True
  553. return False
  554. # WARNING: should_drop is currently being used by our JIT code coverage plug-in to mark JIT'd code as covered. If you
  555. # rename this function, please update references in tools/coverage_plugins_package/src/coverage_plugins/jit_plugin.py to
  556. # allow JIT'd code to still be covered.
  557. def should_drop(fn) -> bool:
  558. attr = get_torchscript_modifier(fn)
  559. if attr is None:
  560. return False
  561. return attr is FunctionModifiers.UNUSED
  562. def is_ignored_fn(fn) -> bool:
  563. mod = get_torchscript_modifier(fn)
  564. return mod is FunctionModifiers.UNUSED or mod is FunctionModifiers.IGNORE
  565. def is_static_fn(cls, fn) -> bool:
  566. return isinstance(inspect.getattr_static(cls, fn, default=None), staticmethod)
  567. def get_static_fn(cls, fn):
  568. return inspect.getattr_static(cls, fn).__func__
  569. def get_torchscript_modifier(fn):
  570. if not callable(fn):
  571. return None
  572. if hasattr(fn, '__func__'):
  573. fn = fn.__func__
  574. return getattr(fn, '_torchscript_modifier', FunctionModifiers.DEFAULT)
  575. def copy_torchscript_modifier(orig, new) -> None:
  576. attr = get_torchscript_modifier(orig)
  577. if attr is None:
  578. return
  579. new._torchscript_modifier = attr
  580. # overloading registration
  581. # overloads get registered in this file, and compiled in torch/jit/__init__.py
  582. # so that they can be imported in nn/functional.py without an import cycle
  583. # qualified_name => list[overload_functions]
  584. _overloaded_fns : Dict[str, List[Callable]] = {} # noqa: T484
  585. _OVERLOAD_EXAMPLE = '''
  586. Example usage of overload function:
  587. @torch.jit._overload
  588. def my_function(x: type0) -> type0: # decl 1
  589. pass
  590. @torch.jit._overload
  591. def my_function(x: type1) -> type1: # decl 2
  592. pass
  593. def my_function(x): # implementation
  594. if isinstance(x, type0):
  595. return x
  596. elif isinstance(x, type1):
  597. return x
  598. '''
  599. def get_overload_no_implementation_error_message(kind, obj):
  600. sourcelines, file_lineno, filename = get_source_lines_and_file(obj)
  601. return (
  602. f'Implementation for the {kind} "{_qualified_name(obj)}" is missing. Please make '
  603. f'sure a definition is provided and defined after all overload declarations.\n'
  604. f'File "{filename}", line {file_lineno}:\n' + ''.join(sourcelines) + "\n" + _OVERLOAD_EXAMPLE
  605. )
  606. def _check_overload_body(func):
  607. try:
  608. parsed_def = parse_def(func)
  609. except OSError as e:
  610. # Parsing the function definition can raise an OSError if source is unavailable.
  611. # Since this is just an initial check, just raise a warning if this is the case.
  612. warnings.warn(f"Unable to retrieve source for @torch.jit._overload function: {func}.")
  613. return
  614. body = parsed_def.ast.body[0].body
  615. def is_pass(x):
  616. return isinstance(x, ast.Pass)
  617. def is_ellipsis(x):
  618. return isinstance(x, ast.Expr) and isinstance(x.value, ast.Ellipsis)
  619. if len(body) != 1 or not (is_pass(body[0]) or is_ellipsis(body[0])):
  620. msg = "Only `pass` statement or `...` can be the body of overload declaration:\n"
  621. msg += '\n'.join(parsed_def.source.split("\n")[:3])
  622. msg += " <- Expecting `pass` or `...` here!\n" + _OVERLOAD_EXAMPLE
  623. raise RuntimeError(msg)
  624. def _overload(func):
  625. _check_overload_body(func)
  626. qual_name = _qualified_name(func)
  627. global _overloaded_fns
  628. fn_overload_list = _overloaded_fns.get(qual_name)
  629. if fn_overload_list is None:
  630. fn_overload_list = []
  631. _overloaded_fns[qual_name] = fn_overload_list
  632. fn_overload_list.append(func)
  633. return func
  634. def _get_fn_overloads(qual_name):
  635. return _overloaded_fns.get(qual_name)
  636. def _clear_fn_overloads(qual_name) -> None:
  637. del _overloaded_fns[qual_name]
  638. def get_class_name_lineno(method) -> Tuple[str, int]:
  639. current_frame = inspect.currentframe()
  640. # one for the get_class_name call, one for _overload_method call
  641. for i in range(2):
  642. assert current_frame is not None # assert current frame is not an Optional[FrameType]
  643. current_frame = current_frame.f_back
  644. assert current_frame is not None # same here
  645. class_name = current_frame.f_code.co_name
  646. line_no = current_frame.f_code.co_firstlineno
  647. return class_name, line_no
  648. # At the the point the decorator is applied to class methods the method
  649. # has no reference to its owning class. _qualified_name would not include
  650. # the class it is defined in, so any methods with the same name in the same file
  651. # would have the same _qualified_name, even if they were defined in different
  652. # classes. This problem only exists in python 2.
  653. # We get around this problem by looking at the stack frame and identifying
  654. # the class name, and throwing an error whenever overloads are used
  655. # when modules of the same name are in the same file
  656. # qualified_name => class name => list[overload_functions]
  657. _overloaded_methods : Dict[str, Dict[str, List[Callable]]] = {} # noqa: T484
  658. # (qualified_name, class name) => class_fileno
  659. _overloaded_method_class_fileno = {}
  660. def _overload_method(func):
  661. _check_overload_body(func)
  662. qual_name = _qualified_name(func)
  663. global _overloaded_methods
  664. class_name_map = _overloaded_methods.get(qual_name, None)
  665. if class_name_map is None:
  666. class_name_map = {}
  667. _overloaded_methods[qual_name] = class_name_map
  668. class_name, line_no = get_class_name_lineno(func)
  669. method_overloads = class_name_map.get(class_name, None)
  670. if method_overloads is None:
  671. method_overloads = []
  672. class_name_map[class_name] = method_overloads
  673. _overloaded_method_class_fileno[(qual_name, class_name)] = line_no
  674. else:
  675. existing_lineno = _overloaded_method_class_fileno[(qual_name, class_name)]
  676. if existing_lineno != line_no:
  677. raise RuntimeError("Cannot currently overload the same method name in two different"
  678. " classes with the same name in the same module")
  679. method_overloads.append(func)
  680. return func
  681. def _get_overloaded_methods(method, mod_class):
  682. # TODO: __name__ not set for submodules in recursive script
  683. if not hasattr(method, "__name__"):
  684. return None
  685. qual_name = _qualified_name(method)
  686. class_name_map = _overloaded_methods.get(qual_name, None)
  687. if class_name_map is None:
  688. return None
  689. overloads = class_name_map.get(mod_class.__name__, None)
  690. if overloads is None:
  691. return None
  692. method_line_no = get_source_lines_and_file(method)[1]
  693. mod_class_fileno = get_source_lines_and_file(mod_class)[1]
  694. mod_end_fileno = mod_class_fileno + len(get_source_lines_and_file(mod_class)[0])
  695. if not (method_line_no >= mod_class_fileno and method_line_no <= mod_end_fileno):
  696. raise Exception("Overloads are not useable when a module is redeclared within the same file: " + str(method))
  697. return overloads
  698. def is_tuple(ann) -> bool:
  699. if ann is Tuple:
  700. raise_error_container_parameter_missing("Tuple")
  701. # For some reason Python 3.7 violates the Type[A, B].__origin__ == Type rule
  702. if not hasattr(ann, '__module__'):
  703. return False
  704. return ann.__module__ == 'typing' and \
  705. (getattr(ann, '__origin__', None) is Tuple or
  706. getattr(ann, '__origin__', None) is tuple)
  707. def is_list(ann) -> bool:
  708. if ann is List:
  709. raise_error_container_parameter_missing("List")
  710. if not hasattr(ann, '__module__'):
  711. return False
  712. return ann.__module__ == 'typing' and \
  713. (getattr(ann, '__origin__', None) is List or
  714. getattr(ann, '__origin__', None) is list)
  715. def is_dict(ann) -> bool:
  716. if ann is Dict:
  717. raise_error_container_parameter_missing("Dict")
  718. if not hasattr(ann, '__module__'):
  719. return False
  720. return ann.__module__ == 'typing' and \
  721. (getattr(ann, '__origin__', None) is Dict or
  722. getattr(ann, '__origin__', None) is dict)
  723. def is_union(ann):
  724. if ann is Union:
  725. raise_error_container_parameter_missing("Union")
  726. return (hasattr(ann, '__module__') and
  727. ann.__module__ == 'typing' and
  728. (getattr(ann, '__origin__', None) is Union))
  729. def is_optional(ann):
  730. if ann is Optional:
  731. raise_error_container_parameter_missing("Optional")
  732. def is_optional_as_optional(ann):
  733. return (hasattr(ann, '__module__') and
  734. ann.__module__ == 'typing' and
  735. (getattr(ann, '__origin__', None) is Optional))
  736. def is_union_as_optional(ann):
  737. ann_args = ann.__args__
  738. return len(ann_args) == 2 and None in ann_args
  739. return is_optional_as_optional(ann) or (is_union(ann) and is_union_as_optional(ann))
  740. def is_future(ann) -> bool:
  741. if ann is Future:
  742. raise RuntimeError(
  743. "Attempted to use Future without a "
  744. "contained type. Please add a contained type, e.g. "
  745. "Future[int]"
  746. )
  747. return getattr(ann, "__origin__", None) is Future
  748. if torch.distributed.rpc.is_available():
  749. from torch.distributed.rpc import RRef
  750. from torch._C._distributed_rpc import PyRRef
  751. def is_rref(ann) -> bool:
  752. if ann is RRef:
  753. raise RuntimeError(
  754. "Attempted to use RRef without a "
  755. "contained type. Please add a contained type, e.g. "
  756. "RRef[int]"
  757. )
  758. return getattr(ann, "__origin__", None) is RRef
  759. def is_rref_instance(obj) -> bool:
  760. return isinstance(obj, PyRRef)
  761. else:
  762. def is_rref_instance(obj) -> bool:
  763. # If the RPC module doesn't exist then RRefs don't exist either.
  764. return False
  765. def is_final(ann) -> bool:
  766. return ann.__module__ in {'typing', 'typing_extensions'} and \
  767. (getattr(ann, '__origin__', None) is Final or isinstance(ann, type(Final)))
  768. # allows BroadcastingList instance to be subscriptable
  769. class BroadcastingListCls(object):
  770. def __getitem__(self, types):
  771. return
  772. # mypy doesn't support parameters on types, so we have to explicitly type each
  773. # list size
  774. BroadcastingList1 = BroadcastingListCls()
  775. for i in range(2, 7):
  776. globals()[f"BroadcastingList{i}"] = BroadcastingList1
  777. def is_scripting() -> bool:
  778. r"""
  779. Function that returns True when in compilation and False otherwise. This
  780. is useful especially with the @unused decorator to leave code in your
  781. model that is not yet TorchScript compatible.
  782. .. testcode::
  783. import torch
  784. @torch.jit.unused
  785. def unsupported_linear_op(x):
  786. return x
  787. def linear(x):
  788. if torch.jit.is_scripting():
  789. return torch.linear(x)
  790. else:
  791. return unsupported_linear_op(x)
  792. """
  793. return False
  794. # Retrieves a fully-qualified name (module hierarchy + classname) for a given obj.
  795. def _qualified_name(obj, mangle_name=True) -> str:
  796. # This special case allows us to override the qualified name on a type.
  797. # It's currently used in conjunction with tracing, where we create a
  798. # fake module to filter only supported attributes. However, since this
  799. # new type is defined as a local class, we need a mechanism to override
  800. # its qualname so it appears correctly in the TorchScript system. This,
  801. # we set '_jit_override_qualname' with the original traced module's
  802. # qualified name, which is picked up here
  803. if hasattr(obj, '_jit_override_qualname'):
  804. return obj._jit_override_qualname
  805. # short-circuit in cases where the object already has a known qualified name
  806. if isinstance(obj, torch._C.ScriptFunction):
  807. return obj.qualified_name
  808. if getattr(obj, "__name__", None):
  809. name = obj.__name__
  810. # Enum classes do not have `__name__` attr, instead they have `name`.
  811. elif isinstance(obj, enum.Enum):
  812. name = obj.name
  813. else:
  814. raise RuntimeError("Could not get name of python class object")
  815. if name == '<lambda>':
  816. name = '_lambda' # make name a valid identifier
  817. module_name = obj.__module__
  818. # If the module is actually a torchbind module, then we should short circuit
  819. if module_name == "torch._classes":
  820. return obj.qualified_name
  821. # The Python docs are very clear that `__module__` can be None, but I can't
  822. # figure out when it actually would be.
  823. if module_name is None:
  824. raise RuntimeError(f"Could not get qualified name for class '{name}': "
  825. "__module__ can't be None.")
  826. # if getattr(sys.modules[module_name], name) is not obj:
  827. # raise RuntimeError(f"Could not get qualified name for class '{name}': "
  828. # f"the attr {name} on module {module_name} is not the the class")
  829. # torch.package and TorchScript have separate mangling schemes to avoid
  830. # name collisions from multiple packages. To avoid them interfering with
  831. # each other, normalize the package manging here.
  832. if package_mangling.is_mangled(module_name):
  833. module_name = module_name.replace("<", "_")
  834. module_name = module_name.replace(">", "_")
  835. # The PythonExceptionValue C++ class in torch/csrc/jit/python/python_sugared_value.h
  836. # does not need mangle the python class name.
  837. if mangle_name:
  838. # __main__ is a builtin module, so rewrite it to "__torch__".
  839. if module_name == "__main__":
  840. module_name = "__torch__"
  841. else:
  842. # Everything else gets a "__torch__" prefix to avoid name collisions
  843. # with the names of user values.
  844. module_name = "__torch__." + module_name
  845. if "." in name:
  846. raise RuntimeError(f"Could not get qualified name for class '{name}': "
  847. f"'{name}' is not a valid identifier")
  848. return module_name + "." + name
  849. def _try_get_dispatched_fn(fn):
  850. if not callable(fn):
  851. return None
  852. return boolean_dispatched.get(fn)
  853. def _get_named_tuple_properties(obj):
  854. assert issubclass(obj, tuple) and hasattr(obj, '_fields')
  855. if hasattr(obj, "_field_defaults"):
  856. defaults = [obj._field_defaults[field]
  857. for field in obj._fields
  858. if field in obj._field_defaults]
  859. else:
  860. defaults = []
  861. annotations = []
  862. has_annotations = hasattr(obj, '__annotations__')
  863. for field in obj._fields:
  864. if has_annotations and field in obj.__annotations__:
  865. the_type = torch.jit.annotations.ann_to_type(obj.__annotations__[field], fake_range())
  866. annotations.append(the_type)
  867. else:
  868. annotations.append(torch._C.TensorType.getInferred())
  869. return type(obj).__name__, obj._fields, annotations, defaults
  870. def _create_named_tuple(t, unqual_name: str, field_names: List[str], defaults: Tuple[Any, ...]):
  871. # mypy: namedtuple() expects a string literal as the first argument
  872. if sys.version_info < (3, 7, 0):
  873. TupleType = collections.namedtuple(unqual_name, field_names) # type: ignore[no-redef, misc]
  874. TupleType.__new__.__defaults__ = defaults # type: ignore[attr-defined]
  875. else:
  876. TupleType = collections.namedtuple(unqual_name, field_names, defaults=defaults) # type: ignore[call-arg, no-redef, misc]
  877. return TupleType(*t)
  878. @contextlib.contextmanager
  879. def _disable_emit_hooks():
  880. hooks = torch._C._jit_get_emit_hooks()
  881. torch._C._jit_set_emit_hooks(None, None)
  882. yield
  883. torch._C._jit_set_emit_hooks(hooks[0], hooks[1])
  884. def _disable_emit_hooks_decorator(_DecoratorContextManager) -> None: # noqa: F811
  885. def __enter__(self) -> None:
  886. self.hooks = torch._C._jit_get_emit_hooks()
  887. torch._C._jit_set_emit_hooks(None, None)
  888. def __exit__(self, *args) -> None:
  889. torch._C._jit_set_emit_hooks(self.hooks[0], self.hooks[1])
  890. def _is_exception(obj) -> bool:
  891. if not inspect.isclass(obj):
  892. return False
  893. return issubclass(obj, Exception)
  894. def raise_error_container_parameter_missing(target_type) -> None:
  895. if target_type == 'Dict':
  896. raise RuntimeError(
  897. "Attempted to use Dict without "
  898. "contained types. Please add contained type, e.g. "
  899. "Dict[int, int]"
  900. )
  901. raise RuntimeError(
  902. f"Attempted to use {target_type} without a "
  903. "contained type. Please add a contained type, e.g. "
  904. f"{target_type}[int]"
  905. )
  906. def get_origin(target_type):
  907. return getattr(target_type, "__origin__", None)
  908. def get_args(target_type):
  909. return getattr(target_type, "__args__", None)
  910. def check_args_exist(target_type) -> None:
  911. if target_type is List or target_type is list:
  912. raise_error_container_parameter_missing("List")
  913. elif target_type is Tuple or target_type is tuple:
  914. raise_error_container_parameter_missing("Tuple")
  915. elif target_type is Dict or target_type is dict:
  916. raise_error_container_parameter_missing("Dict")
  917. elif target_type is None or target_type is Optional:
  918. raise_error_container_parameter_missing("Optional")
  919. def check_empty_containers(obj) -> None:
  920. if obj == [] or obj == {} or obj == ():
  921. warnings.warn("The inner type of a container is lost when "
  922. "calling torch.jit.isinstance in eager mode. For "
  923. "example, List[int] would become list and "
  924. "therefore falsely return True for List[float] or"
  925. " List[str].")
  926. # supports List/Dict/Tuple and Optional types
  927. # TODO support future
  928. def container_checker(obj, target_type) -> bool:
  929. origin_type = get_origin(target_type)
  930. check_args_exist(target_type)
  931. if origin_type is list or origin_type is List:
  932. check_empty_containers(obj)
  933. if not isinstance(obj, list):
  934. return False
  935. arg_type = get_args(target_type)[0]
  936. arg_origin = get_origin(arg_type)
  937. for el in obj:
  938. # check if nested container, ex: List[List[str]]
  939. if arg_origin: # processes nested container, ex: List[List[str]]
  940. if not container_checker(el, arg_type):
  941. return False
  942. elif not isinstance(el, arg_type):
  943. return False
  944. return True
  945. elif origin_type is Dict or origin_type is dict:
  946. check_empty_containers(obj)
  947. if not isinstance(obj, dict):
  948. return False
  949. key_type = get_args(target_type)[0]
  950. val_type = get_args(target_type)[1]
  951. for key, val in obj.items():
  952. # check if keys are of right type
  953. if not isinstance(key, key_type):
  954. return False
  955. val_origin = get_origin(val_type)
  956. if val_origin:
  957. if not container_checker(val, val_type):
  958. return False
  959. elif not isinstance(val, val_type):
  960. return False
  961. return True
  962. elif origin_type is Tuple or origin_type is tuple:
  963. check_empty_containers(obj)
  964. if not isinstance(obj, tuple):
  965. return False
  966. arg_types = get_args(target_type)
  967. if len(obj) != len(arg_types):
  968. return False
  969. for el, el_type in zip(obj, arg_types):
  970. el_origin = get_origin(el_type)
  971. if el_origin:
  972. if not container_checker(el, el_type):
  973. return False
  974. elif not isinstance(el, el_type):
  975. return False
  976. return True
  977. elif origin_type is Union: # also handles Optional
  978. if obj is None: # check before recursion because None is always fine
  979. return True
  980. inner_types = get_args(target_type)
  981. for t in inner_types:
  982. t_origin = get_origin(t)
  983. if (t_origin):
  984. return container_checker(obj, t)
  985. elif isinstance(obj, t):
  986. return True
  987. return False
  988. def _isinstance(obj, target_type) -> bool:
  989. if isinstance(target_type, collections.abc.Container):
  990. if not isinstance(target_type, tuple):
  991. raise RuntimeError("The second argument to "
  992. "`torch.jit.isinstance` must be a type "
  993. "or a tuple of types")
  994. for t_type in target_type:
  995. if _isinstance(obj, t_type):
  996. return True
  997. return False
  998. origin_type = get_origin(target_type)
  999. if origin_type:
  1000. return container_checker(obj, target_type)
  1001. # Check to handle non-typed optional origin returns as none instead
  1002. # of as optional in 3.7-3.8
  1003. check_args_exist(target_type)
  1004. # handle non-containers
  1005. return isinstance(obj, target_type)
  1006. class _TensorExtractor(pickle.Pickler):
  1007. def __init__(self, *args, tensors: List[torch.Tensor], **kwargs):
  1008. super().__init__(*args, **kwargs)
  1009. self.tensors = tensors
  1010. def persistent_id(self, obj):
  1011. if isinstance(obj, torch.Tensor):
  1012. self.tensors.append(obj)
  1013. return ""
  1014. # Since we just want to extract tensors, we don't mind if an object is
  1015. # unpicklable if it doesn't contain tensors, as we can just ignore/skip
  1016. # it. To play it safe, we only do so for common objects that we're sure
  1017. # don't contain tensors. Feel free to add new types here. Note also that
  1018. # even if a type isn't listed here this won't block users, since thet
  1019. # can just add a __getstate__ or __reduce__ method to their class.
  1020. if isinstance(obj, LockType):
  1021. return ""
  1022. # Futures and RRefs don't technically contain a value, they just offer
  1023. # the means to access a value.
  1024. if isinstance(obj, CFuture) or is_rref_instance(obj):
  1025. return ""
  1026. if isinstance(obj, torch.cuda.Event):
  1027. return ""
  1028. if isinstance(obj, threading.Thread):
  1029. return ""
  1030. return None
  1031. def _extract_tensors(obj):
  1032. r"""
  1033. This function is exclusively called from C++.
  1034. See ``torch/csrc/jit/python/python_ivalue.h``.
  1035. It extracts the tensors contained in the given object, through pickling.
  1036. """
  1037. tensors: List[torch.Tensor] = []
  1038. extractor = _TensorExtractor(io.BytesIO(), protocol=-1, tensors=tensors)
  1039. extractor.dump(obj)
  1040. return tensors