_jit_internal.py 48 KB

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