_script.py 63 KB

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