_script.py 66 KB

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