_script.py 64 KB

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