_script.py 61 KB

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