_jit_internal.py 53 KB

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