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