_jit_internal.py 53 KB

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