_script.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. """TorchScript.
  2. This module contains functionality to support the JIT's scripting frontend, notably:
  3. - torch.jit.script
  4. This is not intended to be imported directly; please use the exposed
  5. functionalities in `torch.jit`.
  6. """
  7. import collections
  8. import copy
  9. import enum
  10. import functools
  11. import inspect
  12. import pickle
  13. import sys
  14. import warnings
  15. from collections.abc import Callable, Iterator, Mapping, Sequence
  16. from typing import Any, TypeVar, Union
  17. from typing_extensions import deprecated, Self
  18. import torch
  19. import torch._jit_internal as _jit_internal
  20. from torch._classes import classes
  21. from torch._jit_internal import _get_model_id, _qualified_name
  22. from torch._utils_internal import log_torchscript_usage
  23. from torch.jit._builtins import _register_builtin
  24. from torch.jit._fuser import _graph_for, _script_method_graph_for
  25. from torch.jit._monkeytype_config import (
  26. JitTypeTraceConfig,
  27. JitTypeTraceStore,
  28. monkeytype_trace,
  29. )
  30. from torch.jit._recursive import (
  31. _compile_and_register_class,
  32. infer_methods_to_compile,
  33. ScriptMethodStub,
  34. wrap_cpp_module,
  35. )
  36. from torch.jit._state import (
  37. _enabled,
  38. _set_jit_function_cache,
  39. _set_jit_overload_cache,
  40. _try_get_jit_cached_function,
  41. _try_get_jit_cached_overloads,
  42. )
  43. from torch.jit.frontend import get_default_args, get_jit_class_def, get_jit_def
  44. from torch.nn import Module
  45. from torch.overrides import (
  46. has_torch_function,
  47. has_torch_function_unary,
  48. has_torch_function_variadic,
  49. )
  50. from torch.package import PackageExporter, PackageImporter
  51. from torch.utils import set_module
  52. from ._serialization import validate_map_location
  53. _T = TypeVar("_T")
  54. type_trace_db = JitTypeTraceStore() # DB to hold all call traces from MonkeyType
  55. torch._C.ScriptMethod.graph_for = _script_method_graph_for # type: ignore[attr-defined]
  56. torch._C.ScriptFunction.graph_for = _graph_for # type: ignore[attr-defined]
  57. ScriptFunction = torch._C.ScriptFunction
  58. ScriptFunction.__doc__ = """
  59. Functionally equivalent to a :class:`ScriptModule`, but represents a single
  60. function and does not have any attributes or Parameters.
  61. """
  62. ScriptFunction.__name__ = "ScriptFunction"
  63. ScriptFunction.__qualname__ = "torch.jit.ScriptFunction"
  64. set_module(ScriptFunction, "torch.jit")
  65. # Throws an error if a jit function is pickled.
  66. # Helps to avoid Python crashes for Python versions 3.9.5 + when protocol 0 or 1 is given as an argument.
  67. def _reduce(cls):
  68. raise pickle.PickleError("ScriptFunction cannot be pickled")
  69. ScriptFunction.__reduce__ = _reduce # type: ignore[assignment]
  70. if _enabled:
  71. Attribute = collections.namedtuple("Attribute", ["value", "type"])
  72. else:
  73. def Attribute(value, type): # type: ignore[no-redef]
  74. return value
  75. Attribute.__doc__ = """
  76. This method is a pass-through function that returns `value`, mostly
  77. used to indicate to the TorchScript compiler that the left-hand side
  78. expression is a class instance attribute with type of `type`. Note that
  79. `torch.jit.Attribute` should only be used in `__init__` method of `jit.ScriptModule`
  80. subclasses.
  81. Though TorchScript can infer correct type for most Python expressions, there are some cases where
  82. type inference can be wrong, including:
  83. - Empty containers like `[]` and `{}`, which TorchScript assumes to be container of `Tensor`
  84. - Optional types like `Optional[T]` but assigned a valid value of type `T`, TorchScript would assume
  85. it is type `T` rather than `Optional[T]`
  86. In eager mode, it is simply a pass-through function that returns `value`
  87. without other implications.
  88. Example:
  89. .. testcode::
  90. import torch
  91. from typing import Dict
  92. class AttributeModule(torch.jit.ScriptModule):
  93. def __init__(self) -> None:
  94. super().__init__()
  95. self.foo = torch.jit.Attribute(0.1, float)
  96. # we should be able to use self.foo as a float here
  97. assert 0.0 < self.foo
  98. self.names_ages = torch.jit.Attribute({}, Dict[str, int])
  99. self.names_ages["someone"] = 20
  100. assert isinstance(self.names_ages["someone"], int)
  101. m = AttributeModule()
  102. # m will contain two attributes
  103. # 1. foo of type float
  104. # 2. names_ages of type Dict[str, int]
  105. .. testcleanup::
  106. del AttributeModule
  107. del m
  108. Note: it's now preferred to instead use type annotations instead of `torch.jit.Attribute`:
  109. .. testcode::
  110. import torch
  111. from typing import Dict
  112. class AttributeModule(torch.nn.Module):
  113. names: Dict[str, int]
  114. def __init__(self) -> None:
  115. super().__init__()
  116. self.names = {}
  117. m = AttributeModule()
  118. .. testcleanup::
  119. del AttributeModule
  120. del m
  121. Args:
  122. value: An initial value to be assigned to attribute.
  123. type: A Python type
  124. Returns:
  125. Returns `value`
  126. """
  127. def _get_type_trace_db():
  128. # This is a private API. Use of this for external purposes is discouraged.
  129. return type_trace_db
  130. # Gets a function from the name of a method on a type
  131. def _get_function_from_type(cls, name):
  132. return getattr(cls, name, None)
  133. # ScriptClasses must be new-style classes because we construct them using their
  134. # __new__ method.
  135. def _is_new_style_class(cls):
  136. if hasattr(cls, "__class__"):
  137. return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
  138. # These OrderedDictWrapper classes replace the actual OrderedDicts in
  139. # module with versions that get/set properties inside of Module.
  140. # This allows us to reuse most of nn.Module while still storing the
  141. # data in C++.
  142. # Each OrderedDict needs to support:
  143. # x not in view
  144. # x in view
  145. # view[name] = ...
  146. # view.values()
  147. # del view[name]
  148. # view.items()
  149. # view.keys()
  150. # len(view)
  151. class OrderedDictWrapper:
  152. def __init__(self, _c):
  153. self._c = _c
  154. def keys(self):
  155. return [k for k, v in self.items()]
  156. def values(self):
  157. return [v for k, v in self.items()]
  158. def __len__(self):
  159. return len(self.values())
  160. def __delitem__(self, k):
  161. raise RuntimeError("cannot delete methods or parameters of a script module")
  162. def items(self):
  163. return self._c.items()
  164. def __setitem__(self, k, v):
  165. if k not in self:
  166. raise RuntimeError(
  167. f"Can't add a new parameter after ScriptModule construction. Tried to add '{k}"
  168. )
  169. self._c.setattr(k, v)
  170. def __contains__(self, k):
  171. return self._c.contains(k)
  172. def __getitem__(self, k):
  173. if k not in self:
  174. raise KeyError(k)
  175. return self._c.getattr(k)
  176. class OrderedModuleDict(OrderedDictWrapper):
  177. def __init__(self, module, python_dict):
  178. super().__init__(torch._C.ModuleDict(module))
  179. # contains _both_ script modules and non-script python-only modules
  180. # because script modules are subclassed in python and the
  181. # C++ Module class will not hold references to them,
  182. # to ensure that you always get the same python value here
  183. # we store it in the python dict as well
  184. self._python_modules = python_dict
  185. def items(self):
  186. r = self._python_modules.items()
  187. return r
  188. def __contains__(self, k):
  189. return k in self._python_modules
  190. def __setitem__(self, k, v):
  191. # Cases where sub-module can be re-assigned after ScriptModule construction
  192. # 1. If the attr is an module interface type, it's guaranteed that the module is
  193. # not inlined in the graph, so it's safe to swap a new ScriptModule in.
  194. # 2. if the new value if a ScriptModule with the same JIT type, IR won't change
  195. # and it's legit to swap a new module in.
  196. # In these two cases we allow swapping a new scripted module and update the
  197. # corresponding python module dict to keep sync.
  198. # Note: the value to be swapped in has to be ScriptModule instead of nn.Module,
  199. # otherwise it's illegal and we throw error.
  200. if isinstance(v, ScriptModule):
  201. self._c.setattr(k, v)
  202. self._python_modules[k] = v
  203. else:
  204. raise RuntimeError(
  205. "Cannot re-assign modules in a ScriptModule with non-scripted "
  206. f"module, tried to replace existing module '{k}': {v}"
  207. )
  208. def __getitem__(self, k):
  209. return self._python_modules[k]
  210. # For each user-defined class that subclasses ScriptModule, this meta-class:
  211. # (1) finds all the methods annotated with @script_method in a ScriptModule and
  212. # removes them from the class attributes
  213. # (2) puts a wrapper around the class's __init__ method to recursively compile
  214. # all of the script_methods with the module after the original __init__ has
  215. # run. This has to occur after the user-defined __init__ so that submodules and
  216. # parameters are initialized _before_ the script compiler resolve references to
  217. # `self.param` or `self.module`.
  218. class ScriptMeta(type):
  219. def __init__(cls, name, bases, attrs): # noqa: B902
  220. # Aggregate all the ScriptMethods and constants from superclasses
  221. cls._methods: dict[str, Any] = {}
  222. cls._constants_set = set(getattr(cls, "__constants__", ()))
  223. for base in reversed(bases):
  224. for k, v in getattr(base, "_methods", {}).items():
  225. cls._methods[k] = v
  226. base_constants: set = getattr(base, "_constants_set", set())
  227. cls._constants_set = cls._constants_set.union(base_constants)
  228. # find all the script methods of the current class
  229. for k, v in sorted(attrs.items()):
  230. if isinstance(v, ScriptMethodStub):
  231. delattr(cls, k)
  232. cls._methods[v.original_method.__name__] = v
  233. if getattr(cls, "_disable_script_meta", False):
  234. # We leave built-in ScriptModule types alone, since this metaclass
  235. # is only for compiling user classes that inherit from
  236. # ScriptModule.
  237. super().__init__(name, bases, attrs)
  238. return
  239. original_init = getattr(cls, "__init__", lambda self: None)
  240. @functools.wraps(original_init)
  241. def init_then_script(self, *args, **kwargs):
  242. num_methods = len(cls._methods)
  243. original_init(self, *args, **kwargs)
  244. added_methods_in_init = len(cls._methods) > num_methods
  245. if type(self) is cls:
  246. def make_stubs(module):
  247. cls = type(module)
  248. if hasattr(cls, "_methods"):
  249. return [v for k, v in sorted(cls._methods.items())]
  250. else:
  251. return infer_methods_to_compile(module)
  252. self.__dict__["_actual_script_module"] = (
  253. torch.jit._recursive.create_script_module(
  254. self, make_stubs, share_types=not added_methods_in_init
  255. )
  256. )
  257. # Delete the Python attributes that now shadow the ScriptModule
  258. # ones, so that __getattr__ and __setattr__ will properly find
  259. # the scripted versions.
  260. concrete_type = self._actual_script_module._concrete_type
  261. for name in concrete_type.get_attributes():
  262. delattr(self, name)
  263. for name, _ in concrete_type.get_modules():
  264. delattr(self, name)
  265. for name in ("_parameters", "_buffers", "_modules"):
  266. delattr(self, name)
  267. cls.__init__ = init_then_script # type: ignore[misc]
  268. super().__init__(name, bases, attrs)
  269. class _CachedForward:
  270. def __get__(self, obj, cls):
  271. return self.__getattr__("forward") # type: ignore[attr-defined]
  272. class ScriptWarning(Warning):
  273. pass
  274. def script_method(fn):
  275. if sys.version_info >= (3, 14):
  276. warnings.warn(
  277. "`torch.jit.script_method` is not supported in Python 3.14+ and may break. "
  278. "Please switch to `torch.compile` or `torch.export`.",
  279. DeprecationWarning,
  280. )
  281. else:
  282. warnings.warn(
  283. "`torch.jit.script_method` is deprecated. Please switch to `torch.compile` or `torch.export`.",
  284. DeprecationWarning,
  285. )
  286. if not _enabled:
  287. return fn
  288. # NOTE: we need to traverse two frames here because the meta-class frame
  289. # for ScriptModule will be present, as opposed to invoking @script on a
  290. # a function or invoking define() on a CompilationUnit.
  291. # The stack will look like:
  292. #
  293. # 0. createResolutionCallback()
  294. # 1. script_method()
  295. # 2. ScriptModule metaclass frame
  296. # 3. Surrounding scope
  297. #
  298. # createResolutionCallback internally adds 1 to get us to the scope of this
  299. # function (the calling function). Adding 2 gets us to the proper surrounding scope.
  300. _rcb = _jit_internal.createResolutionCallbackFromFrame(frames_up=2)
  301. ast = get_jit_def(fn, fn.__name__, self_name="ScriptModule")
  302. return ScriptMethodStub(_rcb, ast, fn)
  303. class ConstMap:
  304. def __init__(self, const_mapping: Mapping[str, Any]) -> None:
  305. self.const_mapping = const_mapping
  306. def __getattr__(self, attr: str) -> Any:
  307. return self.const_mapping[attr]
  308. def unpackage_script_module(
  309. importer: PackageImporter, script_module_id: str
  310. ) -> torch.nn.Module:
  311. """
  312. Call by ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function.
  313. Performs work of loading and returning a ScriptModule from a ``torch.package`` archive.
  314. """
  315. if not isinstance(importer.zip_reader, torch._C.PyTorchFileReader):
  316. raise RuntimeError(
  317. "Loading ScriptObjects from a PackageImporter created from a "
  318. "directory is not supported. Use a package archive file instead."
  319. )
  320. cu = torch._C.CompilationUnit()
  321. cpp_module = torch._C._import_ir_module_from_package(
  322. cu,
  323. importer.zip_reader,
  324. importer.storage_context,
  325. validate_map_location(importer.last_map_location),
  326. script_module_id,
  327. )
  328. return wrap_cpp_module(cpp_module)
  329. if _enabled:
  330. _magic_methods = [
  331. "__iter__",
  332. "__len__",
  333. "__neg__",
  334. "__mul__",
  335. "__contains__",
  336. "__add__",
  337. "__sub__",
  338. "__pow__",
  339. "__truediv__",
  340. "__mod__",
  341. "__ne__",
  342. "__eq__",
  343. "__lt__",
  344. "__gt__",
  345. "__le__",
  346. "__ge__",
  347. "__and__",
  348. "__or__",
  349. "__xor__",
  350. "__getitem__",
  351. "__setitem__",
  352. "__call__",
  353. "__int__",
  354. "__float__",
  355. "__bool__",
  356. "__str__",
  357. "__enter__",
  358. "__exit__",
  359. ]
  360. class RecursiveScriptClass:
  361. """Wrapper for a TorchScript class instance for use in Python.
  362. An analogue of RecursiveScriptModule for regular objects that are not modules.
  363. This class is a wrapper around a torch._C.ScriptObject that represents an instance
  364. of a TorchScript class and allows it to be used in Python.
  365. Attributes:
  366. _c [torch._C.ScriptObject]: The C++ object to which attribute lookups and method
  367. calls are forwarded.
  368. _props [Dict[str, property]]: A dictionary of properties fetched from self._c and
  369. exposed on this wrppaer.
  370. """
  371. def __init__(self, cpp_class):
  372. super().__init__()
  373. self.__dict__["_initializing"] = True
  374. self._c = cpp_class
  375. # Add wrapped object's properties to this class instance.
  376. self._props = {
  377. prop.name: property(prop.getter, prop.setter)
  378. for prop in self._c._properties()
  379. }
  380. self.__dict__["_initializing"] = False
  381. def __getattr__(self, attr: str) -> Any:
  382. if self.__dict__.get("_initializing"):
  383. return super().__getattr__(attr) # type: ignore[misc]
  384. if attr in self._props:
  385. return self._props[attr].fget() # type: ignore[call-arg, misc]
  386. return getattr(self._c, attr)
  387. def __setattr__(self, attr: str, value: Any) -> None:
  388. if self.__dict__.get("_initializing"):
  389. return super().__setattr__(attr, value)
  390. if attr in self._props:
  391. return self._props[attr].fset(value) # type: ignore[call-arg, misc]
  392. setattr(self._c, attr, value)
  393. # Delegate calls to magic methods like __len__ to the C++ module backing the
  394. # RecursiveScriptClass.
  395. def forward_magic_method(
  396. self, method_name: str, *args: Any, **kwargs: Any
  397. ) -> Any:
  398. if not self._c._has_method(method_name):
  399. raise TypeError
  400. self_method = self.__getattr__(method_name)
  401. return self_method(*args, **kwargs)
  402. def __getstate__(self):
  403. raise pickle.PickleError("ScriptClasses cannot be pickled")
  404. def __iadd__(self, other: Self) -> Self:
  405. if self._c._has_method("__iadd__"):
  406. return self.forward_magic_method("__iadd__", other)
  407. else:
  408. return self.forward_magic_method("__add__", other)
  409. for method_name in _magic_methods:
  410. def method_template(self, *args, **kwargs):
  411. return self.forward_magic_method(method_name, *args, **kwargs)
  412. setattr(RecursiveScriptClass, method_name, method_template)
  413. # this is a Python 'non-data descriptor' that causes the first access
  414. # to ScriptModule's forward to look up the forward method and stash
  415. # it in the objects dict. Due to the standard rules for attribute lookup,
  416. # subsequent lookups will just directly return the previously looked up method.
  417. # This is necessary because nn.Module defines forward as a method. If we
  418. # did nothing, __getattr__ would not be called. Instead we'd get nn.Module.forward
  419. # which always throws an exception.
  420. class ScriptModule(Module, metaclass=ScriptMeta):
  421. r"""Wrapper for C++ torch::jit::Module with methods, attributes, and parameters.
  422. A wrapper around C++ ``torch::jit::Module``. ``ScriptModule``\s
  423. contain methods, attributes, parameters, and
  424. constants. These can be accessed the same way as on a normal ``nn.Module``.
  425. """
  426. __jit_unused_properties__ = [
  427. "code",
  428. "code_with_constants",
  429. "graph",
  430. "inlined_graph",
  431. "original_name",
  432. ]
  433. def __init__(self) -> None:
  434. super().__init__()
  435. forward: Callable[..., Any] = _CachedForward() # type: ignore[assignment]
  436. def __getattr__(self, attr: str) -> Any:
  437. if "_actual_script_module" not in self.__dict__:
  438. return super().__getattr__(attr)
  439. return getattr(self._actual_script_module, attr)
  440. def __setattr__(self, attr: str, value: Any) -> None:
  441. if "_actual_script_module" not in self.__dict__:
  442. # Unwrap torch.jit.Attribute into a regular setattr + record
  443. # the provided type in __annotations__.
  444. #
  445. # This ensures that if we use the attr again in `__init__`, it
  446. # will look like the actual value, not an instance of Attribute.
  447. # pyrefly: ignore [invalid-argument]
  448. if isinstance(value, Attribute):
  449. # NB: Ensure that we set __annotations__ on the specific
  450. # class in question, and not on a superclass (which would
  451. # be wrong wrong wrong!).
  452. # See also https://github.com/pytorch/pytorch/issues/39463
  453. if "__annotations__" not in self.__class__.__dict__:
  454. self.__class__.__annotations__ = {}
  455. self.__annotations__[attr] = value.type
  456. value = value.value
  457. return super().__setattr__(attr, value)
  458. setattr(self._actual_script_module, attr, value)
  459. def define(self, src):
  460. if "_actual_script_module" in self.__dict__:
  461. # If we have completed initialization, just defer to the
  462. # backing RecursiveScriptModule to eagerly compile the provided
  463. # source.
  464. return self._actual_script_module.define(src)
  465. # Otherwise, we are still in the object's __init__.
  466. # In that case, add `src` as a stub to be compiled.
  467. #
  468. # We use frames_up=1 to get to the proper surrounding scope. The stack
  469. # will look like:
  470. # 0. createResolutionCallback
  471. # 1. define()
  472. # 2. surrounding scope.
  473. #
  474. # createResolutionCallback internally adds 1 to get us to our frame, then
  475. # we add 1 to get to the proper surrounding scope.
  476. rcb = _jit_internal.createResolutionCallbackFromFrame(frames_up=1)
  477. ast = torch._C._parse_source_def(src)
  478. self._methods[ast.name().name] = ScriptMethodStub(rcb, ast, None)
  479. def _replicate_for_data_parallel(self):
  480. return self._actual_script_module._replicate_for_data_parallel()
  481. def __reduce_package__(self, exporter: PackageExporter):
  482. """Save a ScriptModule inside of a ``torch.package`` archive.
  483. Called by ``torch.package.PackageExporter``'s Pickler's ``persistent_id`` when
  484. saving TorchScript objects. Performs act of saving a ScriptModule inside of
  485. a ``torch.package`` archive.
  486. Returns method to load the ScriptModule from a ``torch.package.PackageImporter``'s
  487. Pickler's ``persistent_load`` function.
  488. """
  489. script_module_id = exporter.get_unique_id()
  490. exporter.script_module_serializer.serialize(self._c, int(script_module_id))
  491. return (unpackage_script_module, (script_module_id,))
  492. class RecursiveScriptModule(ScriptModule):
  493. # XXX: RecursiveScriptModule inherits from ScriptModule for the sole
  494. # reason that it retains the existing isinstance(ScriptModule)
  495. # behavior.
  496. r"""Retain the existing isinstance(ScriptModule) behavior.
  497. The core data structure in TorchScript is the ``ScriptModule``. It is an
  498. analogue of torch's ``nn.Module`` and represents an entire model as a tree of
  499. submodules. Like normal modules, each individual module in a ``ScriptModule`` can
  500. have submodules, parameters, and methods. In ``nn.Module``\s methods are implemented
  501. as Python functions, but in ``ScriptModule``\s methods are implemented as
  502. TorchScript functions, a statically-typed subset of Python that contains all
  503. of PyTorch's built-in Tensor operations. This difference allows your
  504. ``ScriptModule``\s code to run without the need for a Python interpreter.
  505. ``ScriptModule``\s should not be created manually, instead use
  506. either :func:`tracing <torch.jit.trace>` or :func:`scripting <torch.jit.script>`.
  507. Tracing and scripting can be applied incrementally and :ref:`composed as necessary <Types>`.
  508. * Tracing records the tensor operations as executed with a set of example inputs and uses these
  509. operations to construct a computation graph. You can use the full dynamic behavior of Python with tracing,
  510. but values other than Tensors and control flow aren't captured in the graph.
  511. * Scripting inspects the Python code of the model
  512. and compiles it to TorchScript. Scripting allows the use of many `types`_ of values and supports dynamic control flow.
  513. Many, but not all features of Python are supported by the compiler, so changes to the source code may be necessary.
  514. """
  515. _disable_script_meta = True
  516. def __init__(self, cpp_module):
  517. self.__dict__["_initializing"] = True
  518. self._c = cpp_module
  519. super().__init__()
  520. # Delete the 'training' attribute set up by `Module.__init__`. It
  521. # will get set on the underlying cpp module, so we delete it here
  522. # to avoid this version shadowing the cpp module version.
  523. delattr(self, "training")
  524. @staticmethod
  525. def _construct(cpp_module, init_fn):
  526. """
  527. Construct a RecursiveScriptModule that's ready for use.
  528. PyTorch code should use this to construct a RecursiveScriptModule instead
  529. of instead of calling `__init__` directly, as it makes sure the
  530. object is properly finalized (and in the future, we may take
  531. control of how the RecursiveScriptModule instance is created).
  532. Args:
  533. cpp_module: The C++ Module that will hold the actual state of
  534. this RecursiveScriptModule instance.
  535. init_fn: Lambda that initializes the RecursiveScriptModule passed to it.
  536. """
  537. script_module = RecursiveScriptModule(cpp_module)
  538. init_fn(script_module)
  539. # Finalize the ScriptModule: replace the nn.Module state with our
  540. # custom implementations and flip the _initializing bit.
  541. # pyrefly: ignore [missing-attribute]
  542. RecursiveScriptModule._finalize_scriptmodule(script_module)
  543. return script_module
  544. @staticmethod
  545. def _finalize_scriptmodule(script_module):
  546. script_module._parameters = OrderedDictWrapper(
  547. torch._C.ParameterDict(script_module._c)
  548. )
  549. script_module._buffers = OrderedDictWrapper(
  550. torch._C.BufferDict(script_module._c)
  551. )
  552. script_module._modules = OrderedModuleDict(
  553. script_module._c, script_module._modules
  554. )
  555. script_module._initializing = False
  556. def _reconstruct(self, cpp_module):
  557. """
  558. Re-construct an instance of RecursiveScriptModule using an instance of a C++ module.
  559. Args:
  560. cpp_module: The C++ module that this RecursiveScriptModule will be rebuilt around.
  561. """
  562. self.__init__(cpp_module) # type: ignore[misc]
  563. # Copy the concrete type from the C++ module to this ScriptModule.
  564. self._concrete_type = torch._C.ConcreteModuleType.from_jit_type(
  565. self._c._type()
  566. )
  567. # Copy submodules from the C++ module to this ScriptModule.
  568. modules = {}
  569. for name, cpp_module in torch._C.ModuleDict(self._c).items():
  570. modules[name] = wrap_cpp_module(cpp_module)
  571. self._modules = OrderedModuleDict(self._c, modules) # type: ignore[assignment]
  572. # Copy parameters and buffers.
  573. self._parameters = OrderedDictWrapper(torch._C.ParameterDict(self._c)) # type: ignore[assignment]
  574. self._buffers = OrderedDictWrapper(torch._C.BufferDict(self._c)) # type: ignore[assignment]
  575. # Get rid of the functions from the old C++ module.
  576. self.__dict__ = {
  577. k: v
  578. for k, v in self.__dict__.items()
  579. if not isinstance(v, torch._C.ScriptMethod)
  580. }
  581. self.__dict__["_initializing"] = False
  582. @property
  583. def graph(self):
  584. r"""Return a string representation of the internal graph for the ``forward`` method."""
  585. return self._c._get_method("forward").graph
  586. @property
  587. def inlined_graph(self):
  588. r"""
  589. Return a string representation of the internal graph for the ``forward`` method.
  590. This graph will be preprocessed to inline all function and method calls.
  591. """
  592. return self.forward.inlined_graph # type: ignore[attr-defined]
  593. @property
  594. def code(self):
  595. r"""
  596. Return a pretty-printed representation (as valid Python syntax) of the internal graph for the ``forward`` method.
  597. """
  598. return self.forward.code # type: ignore[attr-defined]
  599. @property
  600. def code_with_constants(self):
  601. r"""Return a tuple.
  602. Returns a tuple of:
  603. [0] a pretty-printed representation (as valid Python syntax) of
  604. the internal graph for the ``forward`` method. See `code`.
  605. [1] a ConstMap following the CONSTANT.cN format of the output in [0].
  606. The indices in the [0] output are keys to the underlying constant's values.
  607. """
  608. r = self.forward.code_with_constants # type: ignore[attr-defined]
  609. return (r[0], ConstMap(r[1]))
  610. def save(self, f, **kwargs):
  611. r"""Save with a file-like object.
  612. save(f, _extra_files={})
  613. See :func:`torch.jit.save <torch.jit.save>` which accepts a file-like object.
  614. This function, torch.save(), converts the object to a string, treating it as a path.
  615. DO NOT confuse these two functions when it comes to the 'f' parameter functionality.
  616. """
  617. return self._c.save(str(f), **kwargs)
  618. @deprecated(
  619. "Lite Interpreter is deprecated. Please consider switching to ExecuTorch. \
  620. https://docs.pytorch.org/executorch/stable/getting-started.html"
  621. )
  622. def _save_for_lite_interpreter(self, *args, **kwargs):
  623. r"""Add (or update) the bytecode session to the script model.
  624. _save_for_lite_interpreter(f)
  625. The updated model is used
  626. in lite interpreter for mobile applications.
  627. Args:
  628. f: a string containing a file name.
  629. _extra_files: Map from filename to contents which will be stored as part of 'f'.
  630. """
  631. warnings.warn(
  632. "Lite Interpreter is deprecated. Please consider switching to ExecuTorch. \
  633. https://docs.pytorch.org/executorch/stable/getting-started.html",
  634. DeprecationWarning,
  635. stacklevel=2,
  636. )
  637. return self._c._save_for_mobile(*args, **kwargs)
  638. @deprecated(
  639. "Lite Interpreter is deprecated. Please consider switching to ExecuTorch. \
  640. https://docs.pytorch.org/executorch/stable/getting-started.html"
  641. )
  642. def _save_to_buffer_for_lite_interpreter(self, *args, **kwargs):
  643. warnings.warn(
  644. "Lite Interpreter is deprecated. Please consider switching to ExecuTorch. \
  645. https://docs.pytorch.org/executorch/stable/getting-started.html",
  646. DeprecationWarning,
  647. stacklevel=2,
  648. )
  649. return self._c._save_to_buffer_for_mobile(*args, **kwargs)
  650. def save_to_buffer(self, *args: Any, **kwargs: Any) -> Any:
  651. return self._c.save_to_buffer(*args, **kwargs)
  652. def get_debug_state(self, *args: Any, **kwargs: Any) -> Any:
  653. return self._c.get_debug_state()
  654. def extra_repr(self) -> str:
  655. return f"original_name={self.original_name}"
  656. def graph_for(self, *args: Any, **kwargs: Any) -> Any:
  657. return self.forward.graph_for(self, *args, **kwargs) # type: ignore[attr-defined]
  658. @property
  659. def original_name(self):
  660. # pyrefly: ignore [unnecessary-comparison]
  661. if type(self) is str(self._c._type().name()):
  662. return ""
  663. return str(self._c._type().name())
  664. def define(self, src):
  665. # We use frames_up=1 to get to the proper surrounding scope. The stack
  666. # will look like:
  667. # 0. createResolutionCallback
  668. # 1. define()
  669. # 2. surrounding scope.
  670. #
  671. # createResolutionCallback internally adds 1 to get us to our frame, then
  672. # we add 1 to get to the proper surrounding scope.
  673. rcb = _jit_internal.createResolutionCallbackFromFrame(frames_up=1)
  674. self._c._define(self._concrete_type, src, rcb)
  675. def __getattr__(self, attr: str) -> Any:
  676. if "_initializing" not in self.__dict__:
  677. raise RuntimeError(
  678. "ScriptModule has not been initialized, did you forget to call super's init?"
  679. )
  680. if self._initializing:
  681. return super().__getattr__(attr)
  682. # _modules check is before hasattr since modules are included as attributes in _c,
  683. # but we want to get the python wrapper from _modules instead of the raw _c object.
  684. if attr in self._modules:
  685. return self._modules[attr]
  686. elif self._c.hasattr(attr):
  687. return self._c.getattr(attr)
  688. elif self._c._has_method(attr):
  689. script_method = self._c._get_method(attr)
  690. # cache method so future calls do not go through __getattr__
  691. # to improve invocation performance
  692. self.__dict__[attr] = script_method
  693. return script_method
  694. return super().__getattr__(attr)
  695. def __setattr__(self, attr: str, value: Any) -> None:
  696. if self._initializing:
  697. return super().__setattr__(attr, value)
  698. if attr in self._modules:
  699. self._modules[attr] = value
  700. elif self._c.hasattr(attr):
  701. self._c.setattr(attr, value)
  702. elif (
  703. hasattr(self, "_concrete_type")
  704. and attr in self._concrete_type.get_constants()
  705. ):
  706. # TODO: we don't have _concrete_type set after load(), and in general we lose constant information.
  707. # We should encode constants as class type attributes (or something) so it persists across save/load.
  708. raise AttributeError(
  709. f"Cannot mutate TorchScript constant value: '{attr}'. Value: '{value}'"
  710. )
  711. else:
  712. # We allow setting Python attributes on the ScriptModule, for
  713. # when people want to stash some convenience info on it.
  714. # TODO: it's possible that the following is confusing:
  715. # s = torch.jit.script(...)
  716. # s.python_attr = ...
  717. # s.save() <--- this doesn't have `python_attr`
  718. # It's fairly trivial to save enough info to warn in this case.
  719. return super().__setattr__(attr, value)
  720. def __copy__(self) -> Self:
  721. return torch.jit._recursive.wrap_cpp_module(copy.copy(self._c))
  722. def __deepcopy__(self, memo: dict[int, Any] | None) -> Self:
  723. return torch.jit._recursive.wrap_cpp_module(copy.deepcopy(self._c, memo))
  724. # Python magic methods do method lookups on an object's class type, instead of looking up
  725. # the method defines on the class instance. In order to continue to expose the magic methods
  726. # of builtin-containers (ModuleList, Sequential, ModuleDict) to Python, we
  727. # define magic methods here as a shim to the correct attribute.
  728. def forward_magic_method(
  729. self, method_name: str, *args: Any, **kwargs: Any
  730. ) -> Any:
  731. self_method = getattr(self, method_name)
  732. if getattr(self_method, "__func__", None) == getattr(
  733. RecursiveScriptModule, method_name
  734. ):
  735. raise NotImplementedError
  736. return self_method(*args, **kwargs)
  737. def __iter__(self) -> Iterator[Any]:
  738. return self.forward_magic_method("__iter__")
  739. def __getitem__(self, idx: int) -> Any:
  740. return self.forward_magic_method("__getitem__", idx)
  741. def __len__(self):
  742. return self.forward_magic_method("__len__")
  743. def __contains__(self, key):
  744. return self.forward_magic_method("__contains__", key)
  745. # dir is defined by the base nn.Module, so instead of throwing if
  746. # it is not overridden, we call into the nn.Module __dir__ method
  747. def __dir__(self) -> Sequence[str]:
  748. self_method = self.__dir__
  749. if (
  750. self_method.__func__ # type: ignore[attr-defined]
  751. is _get_function_from_type(RecursiveScriptModule, "__dir__")
  752. ):
  753. return super().__dir__()
  754. return self_method()
  755. # to resolve bool(value), Python looks if __bool__ is defined then __iter__
  756. # is defined then returns true for classes. Since __iter__() on this
  757. # class throws if it isn't overridden, we define __bool__ to preserve default behavior
  758. def __bool__(self):
  759. self_method = self.__bool__
  760. if (
  761. self_method.__func__ # type: ignore[attr-defined]
  762. is _get_function_from_type(RecursiveScriptModule, "__bool__")
  763. ):
  764. return True
  765. return self_method()
  766. def _replicate_for_data_parallel(self):
  767. # we have to initialize ScriptModule properly so that
  768. # it works with pybind11
  769. def init_fn(script_module):
  770. # Don't do anything here, we'll initialize the ScriptModule below
  771. return
  772. # pyrefly: ignore [missing-attribute]
  773. return RecursiveScriptModule._construct(
  774. self._c._replicate_for_data_parallel(), init_fn
  775. )
  776. # Need to copy all RecursiveScriptModule methods to ScriptModule.
  777. #
  778. # This is because `super().foo()` does not use
  779. # `__getattr__` to look up `foo`. So we need to make each method available on
  780. # the ScriptModule manually.
  781. # pyrefly: ignore [missing-attribute]
  782. for name, item in RecursiveScriptModule.__dict__.items():
  783. if not callable(item) and not isinstance(item, property):
  784. continue
  785. if name.startswith("__") or hasattr(ScriptModule, name):
  786. continue
  787. # We can copy over the implementation wholesale because besides the
  788. # `super()` thing above, ScriptModule behaves exactly like
  789. # RecursiveScriptModule
  790. setattr(ScriptModule, name, item)
  791. def _get_methods(cls):
  792. import inspect
  793. # In Python 3 unbound methods are functions, but in Python 2 they are methods
  794. return inspect.getmembers(
  795. cls, predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x)
  796. )
  797. _compiled_methods_allowlist = {
  798. "forward",
  799. "register_buffer",
  800. "register_parameter",
  801. "register_module",
  802. "add_module",
  803. "_apply",
  804. "apply",
  805. "cuda",
  806. "cpu",
  807. "to",
  808. "type",
  809. "float",
  810. "double",
  811. "half",
  812. "state_dict",
  813. "_save_to_state_dict",
  814. "load_state_dict",
  815. "_load_from_state_dict",
  816. "_named_members",
  817. "parameters",
  818. "named_parameters",
  819. "buffers",
  820. "named_buffers",
  821. "children",
  822. "named_children",
  823. "modules",
  824. "named_modules",
  825. "zero_grad",
  826. "share_memory",
  827. "_get_name",
  828. "extra_repr",
  829. "_slow_forward",
  830. "_tracing_name",
  831. "eval",
  832. "train",
  833. "get_extra_state",
  834. "set_extra_state",
  835. }
  836. def _make_fail(name):
  837. def fail(self, *args, **kwargs):
  838. raise RuntimeError(name + " is not supported on ScriptModules")
  839. return fail
  840. for name, method in _get_methods(torch.nn.Module):
  841. if name.startswith("__") or name.endswith("_call_impl"):
  842. continue
  843. if (
  844. # pyrefly: ignore [missing-attribute]
  845. name not in RecursiveScriptModule.__dict__
  846. and name not in _compiled_methods_allowlist
  847. ):
  848. setattr(RecursiveScriptModule, method.__name__, _make_fail(name))
  849. else:
  850. # TODO MAKE SURE THAT DISABLING WORKS
  851. class RecursiveScriptClass: # type: ignore[no-redef]
  852. pass
  853. class ScriptModule(torch.nn.Module): # type: ignore[no-redef]
  854. def __init__(self, arg=None):
  855. super().__init__()
  856. class RecursiveScriptModule(ScriptModule): # type: ignore[no-redef]
  857. def __init__(self, arg=None):
  858. super().__init__()
  859. def call_prepare_scriptable_func_impl(obj, memo):
  860. if not isinstance(obj, torch.nn.Module):
  861. return obj
  862. obj_id = id(obj)
  863. # If obj_id is in memo, obj has already been prepared or is being
  864. # prepared in another call up the stack.
  865. if obj_id in memo:
  866. return memo[id(obj)]
  867. obj = (
  868. # pyrefly: ignore [not-callable]
  869. obj.__prepare_scriptable__() if hasattr(obj, "__prepare_scriptable__") else obj
  870. ) # type: ignore[operator]
  871. # Record obj in memo to avoid infinite recursion in the case of cycles in the module
  872. # hierarchy when recursing below.
  873. memo[obj_id] = obj
  874. new_obj_dict = {}
  875. for name, sub_module in obj.__dict__.items():
  876. if name == "_modules":
  877. for k, v in sub_module.items():
  878. sub_module[k] = call_prepare_scriptable_func_impl(v, memo)
  879. new_obj_dict[name] = sub_module
  880. elif isinstance(sub_module, torch.nn.Module) and not isinstance(
  881. sub_module, ScriptModule
  882. ):
  883. new_obj_dict[name] = call_prepare_scriptable_func_impl(sub_module, memo)
  884. else:
  885. new_obj_dict[name] = sub_module
  886. for v in new_obj_dict.values():
  887. obj.__dict__[name] = v
  888. return obj
  889. def call_prepare_scriptable_func(obj):
  890. memo: dict[int, torch.nn.Module] = {}
  891. return call_prepare_scriptable_func_impl(obj, memo)
  892. def create_script_dict(obj):
  893. """
  894. Create a ``torch._C.ScriptDict`` instance with the data from ``obj``.
  895. Args:
  896. obj (dict): The Python dictionary that is used to initialize the ``ScriptDict``
  897. returned by this function.
  898. Returns:
  899. An instance of ``torch._C.ScriptDict`` that has the same data as ``obj``
  900. and can be passed between Python and TorchScript with reference semantics and
  901. zero copy overhead.
  902. """
  903. return torch._C.ScriptDict(obj) # type: ignore[attr-defined]
  904. def create_script_list(obj, type_hint=None):
  905. """
  906. Create a ``torch._C.ScriptList`` instance with the data from ``obj``.
  907. Args:
  908. obj (dict): The Python list that is used to initialize the ``ScriptList``
  909. returned by this function.
  910. Returns:
  911. An instance of ``torch._C.ScriptList`` that has the same data as ``obj``
  912. and can be passed between Python and TorchScript with reference semantics and
  913. zero copy overhead.
  914. """
  915. return torch._C.ScriptList(obj) # type: ignore[attr-defined]
  916. _TOPLEVEL: bool = True
  917. def _script_impl(
  918. obj,
  919. optimize=None,
  920. _frames_up=0,
  921. _rcb=None,
  922. example_inputs: Union[list[tuple], dict[Callable, list[tuple]], None] = None,
  923. ):
  924. global type_trace_db
  925. if optimize is not None:
  926. warnings.warn(
  927. "`optimize` is deprecated and has no effect. "
  928. "Use `with torch.jit.optimized_execution()` instead",
  929. FutureWarning,
  930. stacklevel=3,
  931. )
  932. # No-op for modules, functions, class instances that are already scripted
  933. if isinstance(obj, RecursiveScriptClass):
  934. return obj
  935. if isinstance(obj, ScriptModule):
  936. return obj
  937. if isinstance(obj, ScriptFunction):
  938. return obj
  939. if example_inputs:
  940. # If MonkeyType is installed, enable profile directed type annotation
  941. # Check if example_inputs are defined and generate call traces
  942. # for the method by running eager mode version of the method with
  943. # the provide example inputs. This logs all the traces in type_trace_db
  944. type_trace_db = JitTypeTraceStore()
  945. if monkeytype_trace:
  946. # pyrefly: ignore [bad-argument-count]
  947. monkeytype_config = JitTypeTraceConfig(type_trace_db)
  948. with monkeytype_trace(monkeytype_config):
  949. if isinstance(example_inputs, dict):
  950. # If the obj is an nn.Module or a class, then each method is
  951. # executed with the arguments provided in the example inputs.
  952. # example inputs here will be of type Dict(class.method, (arguments))
  953. # This is used to infer type annotations for those methods
  954. # which are not called directly under the hood of monkeytype.
  955. for module, example_input in example_inputs.items():
  956. for example in example_input:
  957. module(*example)
  958. elif isinstance(example_inputs, list):
  959. for examples in example_inputs:
  960. obj(*examples)
  961. else:
  962. raise ValueError(
  963. "Error: Unable to infer types. Please format the inputs to type `List[Tuple]`"
  964. " or `Dict[Callable, List[Tuple]]` to be run with MonkeyType."
  965. )
  966. else:
  967. warnings.warn(
  968. "Warning: monkeytype is not installed. Please install https://github.com/Instagram/MonkeyType "
  969. "to enable Profile-Directed Typing in TorchScript. Refer to "
  970. "https://github.com/Instagram/MonkeyType/blob/master/README.rst to install MonkeyType. ",
  971. stacklevel=2,
  972. )
  973. if isinstance(obj, torch.nn.Module):
  974. obj = call_prepare_scriptable_func(obj)
  975. return torch.jit._recursive.create_script_module(
  976. obj, torch.jit._recursive.infer_methods_to_compile
  977. )
  978. else:
  979. obj = (
  980. obj.__prepare_scriptable__()
  981. if hasattr(obj, "__prepare_scriptable__")
  982. else obj
  983. ) # type: ignore[operator]
  984. if isinstance(obj, dict):
  985. return create_script_dict(obj)
  986. if isinstance(obj, list):
  987. return create_script_list(obj)
  988. if inspect.isclass(obj):
  989. qualified_name = _qualified_name(obj)
  990. # If this type is a `nn.Module` subclass, they probably meant to pass
  991. # an instance instead of a Module
  992. if issubclass(obj, torch.nn.Module):
  993. raise RuntimeError(
  994. f"Type '{obj}' cannot be compiled since it inherits from nn.Module, pass an instance instead"
  995. )
  996. # Enums are automatically usable in TorchScript, explicitly scripting
  997. # is not necessary, but not harmful either.
  998. if issubclass(obj, enum.Enum):
  999. return obj
  1000. if not _is_new_style_class(obj):
  1001. raise RuntimeError(
  1002. "TorchScript classes must be new-style classes. "
  1003. "Please inherit from 'object'."
  1004. )
  1005. if len(obj.mro()) > 2:
  1006. raise RuntimeError(
  1007. "TorchScript classes does not support inheritance yet. "
  1008. "Please directly inherit from 'object'."
  1009. )
  1010. if _rcb is None:
  1011. _rcb = _jit_internal.createResolutionCallbackFromFrame(_frames_up + 1)
  1012. _compile_and_register_class(obj, _rcb, qualified_name)
  1013. return obj
  1014. elif inspect.isfunction(obj) or inspect.ismethod(obj):
  1015. qualified_name = _qualified_name(obj)
  1016. # this is a decorated fn, and we need to the underlying fn and its rcb
  1017. if hasattr(obj, "__script_if_tracing_wrapper"):
  1018. obj = obj.__original_fn # type: ignore[union-attr]
  1019. _rcb = _jit_internal.createResolutionCallbackFromClosure(obj)
  1020. # some functions are explicitly marked as not supported in script mode
  1021. if hasattr(obj, "__script_unsupported"):
  1022. raise RuntimeError("TorchScript error: " + obj.__script_unsupported)
  1023. _check_directly_compile_overloaded(obj)
  1024. maybe_already_compiled_fn = _try_get_jit_cached_function(obj)
  1025. if maybe_already_compiled_fn:
  1026. maybe_already_compiled_fn._torchdynamo_inline = obj # type: ignore[attr-defined]
  1027. return maybe_already_compiled_fn
  1028. ast = get_jit_def(obj, obj.__name__)
  1029. if _rcb is None:
  1030. _rcb = _jit_internal.createResolutionCallbackFromClosure(obj)
  1031. fn = torch._C._jit_script_compile(
  1032. qualified_name, ast, _rcb, get_default_args(obj)
  1033. )
  1034. # Forward docstrings
  1035. fn.__doc__ = obj.__doc__
  1036. fn.__name__ = "ScriptFunction"
  1037. fn.__qualname__ = "torch.jit.ScriptFunction"
  1038. # Allow torch.compile() to inline
  1039. fn._torchdynamo_inline = obj # type: ignore[attr-defined]
  1040. _set_jit_function_cache(obj, fn)
  1041. return fn
  1042. else:
  1043. return torch.jit._recursive.create_script_class(obj)
  1044. def script(
  1045. obj: Any,
  1046. optimize: None = None,
  1047. _frames_up: int = 0,
  1048. _rcb: Callable[[str], Any] | None = None,
  1049. example_inputs: Union[list[tuple], dict[Callable, list[tuple]], None] = None,
  1050. ) -> Any:
  1051. r"""Script the function.
  1052. Scripting a function or ``nn.Module`` will inspect the source code, compile
  1053. it as TorchScript code using the TorchScript compiler, and return a :class:`ScriptModule` or
  1054. :class:`ScriptFunction`. TorchScript itself is a subset of the Python language, so not all
  1055. features in Python work, but we provide enough functionality to compute on
  1056. tensors and do control-dependent operations. For a complete guide, see the
  1057. :ref:`language-reference`.
  1058. Scripting a dictionary or list copies the data inside it into a TorchScript instance than can be
  1059. subsequently passed by reference between Python and TorchScript with zero copy overhead.
  1060. ``torch.jit.script`` can be used as a function for modules, functions, dictionaries and lists
  1061. and as a decorator ``@torch.jit.script`` for torchscript-classes and functions.
  1062. Args:
  1063. obj (Callable, class, or nn.Module): The ``nn.Module``, function, class type,
  1064. dictionary, or list to compile.
  1065. example_inputs (Union[List[Tuple], Dict[Callable, List[Tuple]], None]): Provide example inputs
  1066. to annotate the arguments for a function or ``nn.Module``.
  1067. Returns:
  1068. If ``obj`` is ``nn.Module``, ``script`` returns
  1069. a :class:`ScriptModule` object. The returned :class:`ScriptModule` will
  1070. have the same set of sub-modules and parameters as the
  1071. original ``nn.Module``. If ``obj`` is a standalone function,
  1072. a :class:`ScriptFunction` will be returned. If ``obj`` is a ``dict``, then
  1073. ``script`` returns an instance of `torch._C.ScriptDict`. If ``obj`` is a ``list``,
  1074. then ``script`` returns an instance of `torch._C.ScriptList`.
  1075. **Scripting a function**
  1076. The ``@torch.jit.script`` decorator will construct a :class:`ScriptFunction`
  1077. by compiling the body of the function.
  1078. Example (scripting a function):
  1079. .. testcode::
  1080. import torch
  1081. @torch.jit.script
  1082. def foo(x, y):
  1083. if x.max() > y.max():
  1084. r = x
  1085. else:
  1086. r = y
  1087. return r
  1088. print(type(foo)) # torch.jit.ScriptFunction
  1089. # See the compiled graph as Python code
  1090. print(foo.code)
  1091. # Call the function using the TorchScript interpreter
  1092. foo(torch.ones(2, 2), torch.ones(2, 2))
  1093. .. testoutput::
  1094. :hide:
  1095. ...
  1096. ****Scripting a function using example_inputs**
  1097. Example inputs can be used to annotate a function arguments.
  1098. Example (annotating a function before scripting):
  1099. .. testcode::
  1100. import torch
  1101. def test_sum(a, b):
  1102. return a + b
  1103. # Annotate the arguments to be int
  1104. scripted_fn = torch.jit.script(test_sum, example_inputs=[(3, 4)])
  1105. print(type(scripted_fn)) # torch.jit.ScriptFunction
  1106. # See the compiled graph as Python code
  1107. print(scripted_fn.code)
  1108. # Call the function using the TorchScript interpreter
  1109. scripted_fn(20, 100)
  1110. .. testoutput::
  1111. :hide:
  1112. ...
  1113. **Scripting an nn.Module**
  1114. Scripting an ``nn.Module`` by default will compile the ``forward`` method and recursively
  1115. compile any methods, submodules, and functions called by ``forward``. If a ``nn.Module`` only uses
  1116. features supported in TorchScript, no changes to the original module code should be necessary. ``script``
  1117. will construct :class:`ScriptModule` that has copies of the attributes, parameters, and methods of
  1118. the original module.
  1119. Example (scripting a simple module with a Parameter):
  1120. .. testcode::
  1121. import torch
  1122. class MyModule(torch.nn.Module):
  1123. def __init__(self, N, M):
  1124. super().__init__()
  1125. # This parameter will be copied to the new ScriptModule
  1126. self.weight = torch.nn.Parameter(torch.rand(N, M))
  1127. # When this submodule is used, it will be compiled
  1128. self.linear = torch.nn.Linear(N, M)
  1129. def forward(self, input):
  1130. output = self.weight.mv(input)
  1131. # This calls the `forward` method of the `nn.Linear` module, which will
  1132. # cause the `self.linear` submodule to be compiled to a `ScriptModule` here
  1133. output = self.linear(output)
  1134. return output
  1135. scripted_module = torch.jit.script(MyModule(2, 3))
  1136. Example (scripting a module with traced submodules):
  1137. .. testcode::
  1138. import torch
  1139. import torch.nn as nn
  1140. import torch.nn.functional as F
  1141. class MyModule(nn.Module):
  1142. def __init__(self) -> None:
  1143. super().__init__()
  1144. # torch.jit.trace produces a ScriptModule's conv1 and conv2
  1145. self.conv1 = torch.jit.trace(nn.Conv2d(1, 20, 5), torch.rand(1, 1, 16, 16))
  1146. self.conv2 = torch.jit.trace(nn.Conv2d(20, 20, 5), torch.rand(1, 20, 16, 16))
  1147. def forward(self, input):
  1148. input = F.relu(self.conv1(input))
  1149. input = F.relu(self.conv2(input))
  1150. return input
  1151. scripted_module = torch.jit.script(MyModule())
  1152. To compile a method other than ``forward`` (and recursively compile anything it calls), add
  1153. the :func:`@torch.jit.export <torch.jit.export>` decorator to the method. To opt out of compilation
  1154. use :func:`@torch.jit.ignore <torch.jit.ignore>` or :func:`@torch.jit.unused <torch.jit.unused>`.
  1155. Example (an exported and ignored method in a module)::
  1156. import torch
  1157. import torch.nn as nn
  1158. class MyModule(nn.Module):
  1159. def __init__(self) -> None:
  1160. super().__init__()
  1161. @torch.jit.export
  1162. def some_entry_point(self, input):
  1163. return input + 10
  1164. @torch.jit.ignore
  1165. def python_only_fn(self, input):
  1166. # This function won't be compiled, so any
  1167. # Python APIs can be used
  1168. import pdb
  1169. pdb.set_trace()
  1170. def forward(self, input):
  1171. if self.training:
  1172. self.python_only_fn(input)
  1173. return input * 99
  1174. scripted_module = torch.jit.script(MyModule())
  1175. print(scripted_module.some_entry_point(torch.randn(2, 2)))
  1176. print(scripted_module(torch.randn(2, 2)))
  1177. Example ( Annotating forward of nn.Module using example_inputs)::
  1178. import torch
  1179. import torch.nn as nn
  1180. from typing import NamedTuple
  1181. class MyModule(NamedTuple):
  1182. result: List[int]
  1183. class TestNNModule(torch.nn.Module):
  1184. def forward(self, a) -> MyModule:
  1185. result = MyModule(result=a)
  1186. return result
  1187. pdt_model = TestNNModule()
  1188. # Runs the pdt_model in eager model with the inputs provided and annotates the arguments of forward
  1189. scripted_model = torch.jit.script(pdt_model, example_inputs={pdt_model: [([10, 20, ], ), ], })
  1190. # Run the scripted_model with actual inputs
  1191. print(scripted_model([20]))
  1192. """
  1193. if sys.version_info >= (3, 14):
  1194. warnings.warn(
  1195. "`torch.jit.script` is not supported in Python 3.14+ and may break. "
  1196. "Please switch to `torch.compile` or `torch.export`.",
  1197. DeprecationWarning,
  1198. )
  1199. else:
  1200. warnings.warn(
  1201. "`torch.jit.script` is deprecated. Please switch to `torch.compile` or `torch.export`.",
  1202. DeprecationWarning,
  1203. )
  1204. if not _enabled:
  1205. return obj
  1206. try:
  1207. global _TOPLEVEL
  1208. prev = _TOPLEVEL
  1209. _TOPLEVEL = False
  1210. ret = _script_impl(
  1211. obj=obj,
  1212. optimize=optimize,
  1213. _frames_up=_frames_up + 1,
  1214. _rcb=_rcb,
  1215. example_inputs=example_inputs,
  1216. )
  1217. if prev:
  1218. log_torchscript_usage("script", model_id=_get_model_id(ret))
  1219. return ret
  1220. finally:
  1221. _TOPLEVEL = prev
  1222. # overloads are registered in _jit_internal and compiled here so that _overload
  1223. # can be used in nn/functional.py without an import cycle
  1224. def _check_overload_defaults(impl_defaults, overload_defaults, loc):
  1225. for name, overload_value in overload_defaults.items():
  1226. if name not in impl_defaults or impl_defaults[name] != overload_value:
  1227. raise torch.jit.frontend.FrontendError(
  1228. loc,
  1229. "Default parameters on overloads do not affect the runtime so they "
  1230. "must equal to the default parameter on the implementation function. Found on "
  1231. f"parameter {name}",
  1232. )
  1233. def _compile_function_with_overload(overload_fn, qual_name, impl_fn):
  1234. overload_decl = get_jit_def(overload_fn, overload_fn.__name__).decl()
  1235. overload_signature = torch.jit.annotations.get_signature(
  1236. overload_fn, None, None, inspect.ismethod(overload_fn)
  1237. )
  1238. impl_ast = get_jit_def(impl_fn, impl_fn.__name__)
  1239. overload_defaults = get_default_args(overload_fn)
  1240. implementation_defaults = get_default_args(impl_fn)
  1241. _rcb = _jit_internal.createResolutionCallbackFromClosure(impl_fn)
  1242. _check_overload_defaults(
  1243. implementation_defaults, overload_defaults, overload_decl.range()
  1244. )
  1245. fn = torch._C._jit_script_compile_overload(
  1246. qual_name,
  1247. overload_decl,
  1248. impl_ast,
  1249. _rcb,
  1250. implementation_defaults,
  1251. overload_signature,
  1252. )
  1253. return fn
  1254. def _get_overloads(obj):
  1255. # check for cached compiled fns
  1256. existing_compiled_fns = _try_get_jit_cached_overloads(obj)
  1257. qual_name = _qualified_name(obj)
  1258. uncompiled_overloads = _jit_internal._get_fn_overloads(qual_name)
  1259. if uncompiled_overloads is None:
  1260. return existing_compiled_fns
  1261. if obj in uncompiled_overloads:
  1262. raise RuntimeError(
  1263. _jit_internal.get_overload_no_implementation_error_message("function", obj)
  1264. )
  1265. compiled_fns = [
  1266. _compile_function_with_overload(overload_fn, qual_name, obj)
  1267. for overload_fn in uncompiled_overloads
  1268. ]
  1269. if existing_compiled_fns:
  1270. compiled_fns = existing_compiled_fns + compiled_fns
  1271. # cache compilation, remove information stored to do compilation
  1272. _set_jit_overload_cache(obj, compiled_fns)
  1273. _jit_internal._clear_fn_overloads(qual_name)
  1274. return compiled_fns
  1275. def _check_directly_compile_overloaded(obj):
  1276. qual_name = _qualified_name(obj)
  1277. if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj):
  1278. raise RuntimeError(
  1279. f"Function {qual_name} cannot be directly compiled because it"
  1280. " is overloaded. It must be used in a context of a function"
  1281. " where its inputs can determine which overload to call."
  1282. )
  1283. def interface(obj: _T) -> _T:
  1284. r"""Decorate to annotate classes or modules of different types.
  1285. .. deprecated:: 2.5
  1286. TorchScript is deprecated, please use ``torch.compile`` instead.
  1287. This decorator can be used to define an interface that can be used to annotate
  1288. classes or modules of different types. This can be used for to annotate a submodule
  1289. or attribute class that could have different types that implement the same
  1290. interface, or which could be swapped at runtime; or to store a list of modules or
  1291. classes of varying types.
  1292. It is sometimes used to implement "Callables" - functions or modules that implement
  1293. an interface but whose implementations differ and which can be swapped out.
  1294. Example:
  1295. .. testcode::
  1296. import torch
  1297. from typing import List
  1298. @torch.jit.interface
  1299. class InterfaceType:
  1300. def run(self, x: torch.Tensor) -> torch.Tensor:
  1301. pass
  1302. # implements InterfaceType
  1303. @torch.jit.script
  1304. class Impl1:
  1305. def run(self, x: torch.Tensor) -> torch.Tensor:
  1306. return x.relu()
  1307. class Impl2(torch.nn.Module):
  1308. def __init__(self) -> None:
  1309. super().__init__()
  1310. self.val = torch.rand(())
  1311. @torch.jit.export
  1312. def run(self, x: torch.Tensor) -> torch.Tensor:
  1313. return x + self.val
  1314. def user_fn(impls: List[InterfaceType], idx: int, val: torch.Tensor) -> torch.Tensor:
  1315. return impls[idx].run(val)
  1316. user_fn_jit = torch.jit.script(user_fn)
  1317. impls = [Impl1(), torch.jit.script(Impl2())]
  1318. val = torch.rand(4, 4)
  1319. user_fn_jit(impls, 0, val)
  1320. user_fn_jit(impls, 1, val)
  1321. """
  1322. warnings.warn(
  1323. "`torch.jit.interface` is deprecated. Please use `torch.compile` instead.",
  1324. DeprecationWarning,
  1325. )
  1326. if not inspect.isclass(obj):
  1327. raise RuntimeError("interface must be applied to a class")
  1328. if not _is_new_style_class(obj):
  1329. raise RuntimeError("TorchScript interfaces must inherit from 'object'")
  1330. # Expected MRO is:
  1331. # User module
  1332. # torch.nn.modules.module.Module
  1333. # object
  1334. is_module_interface = issubclass(obj, torch.nn.Module) and len(obj.mro()) == 3
  1335. if not is_module_interface and len(obj.mro()) > 2:
  1336. raise RuntimeError(
  1337. "TorchScript interface does not support inheritance yet. "
  1338. "Please directly inherit from 'object' or 'nn.Module'."
  1339. )
  1340. qualified_name = _qualified_name(obj)
  1341. rcb = _jit_internal.createResolutionCallbackFromFrame(1)
  1342. # if this type is a `nn.Module` subclass, generate a module interface type
  1343. # instead of a class interface type; a module interface type only compiles
  1344. # the user provided methods as part of the interface
  1345. ast = get_jit_class_def(obj, obj.__name__)
  1346. mangled_classname = torch._C._jit_script_interface_compile(
  1347. qualified_name, ast, rcb, is_module_interface
  1348. )
  1349. obj.__torch_script_interface__ = mangled_classname
  1350. return obj
  1351. def _recursive_compile_class(obj, loc):
  1352. _qual_name = _qualified_name(obj)
  1353. # We're starting a new compilation, so update the error call stack in
  1354. # case it fails
  1355. error_stack = torch._C.CallStack(_qual_name, loc) # noqa: F841
  1356. rcb = _jit_internal.createResolutionCallbackForClassMethods(obj)
  1357. return _compile_and_register_class(obj, rcb, _qual_name)
  1358. CompilationUnit = torch._C.CompilationUnit
  1359. set_module(CompilationUnit, "torch.jit")
  1360. def pad(s: str, padding: int, offset: int = 0, char: str = " "):
  1361. if padding >= len(s):
  1362. padding -= len(s)
  1363. return "".join([char for _ in range(padding + offset)]) + s
  1364. class _ScriptProfileColumn:
  1365. def __init__(self, header: str, alignment: int = 4, offset: int = 0):
  1366. self.header = header
  1367. self.alignment = alignment
  1368. self.offset = offset
  1369. self.rows: dict[int, Any] = {}
  1370. def add_row(self, lineno: int, value: Any):
  1371. self.rows[lineno] = value
  1372. def materialize(self):
  1373. max_length = len(self.header)
  1374. rows: list[tuple[int, str]] = []
  1375. for key, value in self.rows.items():
  1376. cell = str(value)
  1377. rows.append((key, cell))
  1378. max_length = max(len(cell), max_length)
  1379. if self.alignment > 0:
  1380. padding = max_length + self.alignment
  1381. padding -= padding % self.alignment
  1382. else:
  1383. padding = 0
  1384. rows = [(key, pad(cell, padding, self.offset)) for key, cell in rows]
  1385. return pad(self.header, padding, self.offset), rows
  1386. class _ScriptProfileTable:
  1387. def __init__(self, cols: list[_ScriptProfileColumn], source_range: list[int]):
  1388. self.cols = cols
  1389. self.source_range = source_range
  1390. def dump_string(self):
  1391. outputs: list[str] = []
  1392. cells: list[tuple[str, dict[int, str]]] = []
  1393. header_buffer = ""
  1394. for col in self.cols:
  1395. header, rows = col.materialize()
  1396. header_buffer += header
  1397. cells.append((header, dict(rows)))
  1398. outputs.append(header_buffer)
  1399. outputs.append(pad("", len(header_buffer), 0, "="))
  1400. for line in self.source_range:
  1401. row_buffer = ""
  1402. for header, rows in cells:
  1403. cell = rows.get(line)
  1404. if cell is None:
  1405. row_buffer += pad("", len(header))
  1406. else:
  1407. row_buffer += cell
  1408. outputs.append(row_buffer)
  1409. return "\n".join(outputs)
  1410. class _ScriptProfile:
  1411. def __init__(self) -> None:
  1412. self.profile = classes.profiling._ScriptProfile()
  1413. def enable(self):
  1414. self.profile.enable()
  1415. def disable(self):
  1416. self.profile.disable()
  1417. def dump_string(self) -> str:
  1418. outputs: list[str] = []
  1419. for source_stats in self.profile._dump_stats():
  1420. source_ref = source_stats.source()
  1421. source_lines = source_ref.text().splitlines()
  1422. dedent = min(len(line) - len(line.lstrip(" ")) for line in source_lines)
  1423. source_lines = [line[dedent:] for line in source_lines]
  1424. start_line = source_ref.starting_lineno()
  1425. end_line = start_line + len(source_lines)
  1426. source_range = range(start_line, end_line)
  1427. lineno = _ScriptProfileColumn("Line #")
  1428. hits = _ScriptProfileColumn("Hits")
  1429. time_ns = _ScriptProfileColumn("Time (ns)")
  1430. line_contents = _ScriptProfileColumn("Line Contents", 0, 1)
  1431. stats = source_stats.line_map()
  1432. for line in source_range:
  1433. lineno.add_row(line, line)
  1434. line_contents.add_row(line, source_lines[line - start_line])
  1435. stat = stats.get(line)
  1436. if stat is not None:
  1437. hits.add_row(line, stat.count())
  1438. time_ns.add_row(line, stat.duration_ns())
  1439. table = _ScriptProfileTable(
  1440. [lineno, hits, time_ns, line_contents], list(source_range)
  1441. )
  1442. outputs.append(table.dump_string())
  1443. return "\n\n".join(outputs)
  1444. def dump(self):
  1445. print(self.dump_string())
  1446. def _unwrap_optional(x):
  1447. if x is None:
  1448. raise AssertionError("Unwrapping null optional")
  1449. return x
  1450. _register_builtin(_unwrap_optional, "aten::_unwrap_optional")
  1451. _register_builtin(_jit_internal.is_scripting, "aten::is_scripting")
  1452. _register_builtin(has_torch_function, "aten::has_torch_function")
  1453. _register_builtin(has_torch_function_unary, "aten::has_torch_function")
  1454. _register_builtin(has_torch_function_variadic, "aten::has_torch_function")