_recursive.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. import inspect
  2. import torch
  3. import types
  4. import collections
  5. import textwrap
  6. import functools
  7. import warnings
  8. import sys
  9. from typing import Dict, List, Set, Type
  10. import torch._jit_internal as _jit_internal
  11. from torch._sources import fake_range
  12. from torch.jit.frontend import get_default_args, get_jit_class_def, get_jit_def, get_class_properties
  13. from torch.jit._builtins import _find_builtin
  14. from torch.jit._check import AttributeTypeIsSupportedChecker
  15. from torch.jit._state import _python_cu, _add_script_class, _get_script_class
  16. from torch.nn import Module
  17. ScriptMethodStub = collections.namedtuple('ScriptMethodStub', ('resolution_callback', 'def_', 'original_method'))
  18. PropertyStub = collections.namedtuple('PropertyStub', ('resolution_callback', 'def_'))
  19. # TODO: there should be a more principled way of doing this.
  20. ignored_attributes = [
  21. "_version",
  22. "_parameters",
  23. "_buffers",
  24. "_non_persistent_buffers_set",
  25. "_backward_hooks",
  26. "_backward_pre_hooks",
  27. "_forward_hooks",
  28. "_forward_hooks_with_kwargs",
  29. "_forward_pre_hooks",
  30. "_forward_pre_hooks_with_kwargs",
  31. "_state_dict_hooks",
  32. "_state_dict_pre_hooks",
  33. "_load_state_dict_pre_hooks",
  34. "_load_state_dict_post_hooks",
  35. "_modules",
  36. "_initializing",
  37. "dump_patches",
  38. ]
  39. def _compile_and_register_class(obj, rcb, qualified_name):
  40. script_class = _get_script_class(obj)
  41. if not script_class:
  42. ast = get_jit_class_def(obj, obj.__name__)
  43. defaults = torch.jit.frontend.get_default_args_for_class(obj)
  44. script_class = torch._C._jit_script_class_compile(qualified_name, ast, defaults, rcb)
  45. _add_script_class(obj, script_class)
  46. return script_class
  47. def make_stub(func, name):
  48. rcb = _jit_internal.createResolutionCallbackFromClosure(func)
  49. ast = get_jit_def(func, name, self_name="RecursiveScriptModule")
  50. return ScriptMethodStub(rcb, ast, func)
  51. def make_stub_from_method(nn_module, method_name):
  52. func = getattr(nn_module, method_name)
  53. if isinstance(func, ScriptMethodStub):
  54. return func
  55. # Make sure the name present in the resulting AST will match the name
  56. # requested here. The only time they don't match is if you do something
  57. # like:
  58. # def _forward(self):
  59. # pass
  60. # forward = _forward
  61. # In this case, the actual function object will have the name `_forward`,
  62. # even though we requested a stub for `forward`.
  63. return make_stub(func, method_name)
  64. def make_stubs_from_exported_methods(mod):
  65. stubs = []
  66. for name in dir(mod):
  67. item = getattr(mod, name, None)
  68. if (
  69. _jit_internal.get_torchscript_modifier(item)
  70. is _jit_internal.FunctionModifiers.EXPORT
  71. ):
  72. stubs.append(make_stub_from_method(mod, name))
  73. return stubs
  74. def jit_ignored_properties(module):
  75. user_annotated_ignored_attributes = getattr(module, "__jit_ignored_attributes__", list())
  76. def get_properties_names(module):
  77. return {k for k, v in vars(module).items() if isinstance(v, property)}
  78. properties = get_properties_names(type(module))
  79. user_annoted_ignored_properties = set()
  80. for ignored_attr in user_annotated_ignored_attributes:
  81. if ignored_attr in properties:
  82. user_annoted_ignored_properties.add(ignored_attr)
  83. return user_annoted_ignored_properties
  84. # base types that can be constants
  85. # in addition, tuples and lists of these base types are also considered constants
  86. # If you edit this list, then you also need to edit the handlers in
  87. # ConstantValue in jit/script/init.cpp
  88. _constant_types = (bool, float, int, str, type(None), torch.device, torch.layout, torch.dtype)
  89. def _get_valid_constant(attr, v, owner_type):
  90. if isinstance(v, _constant_types):
  91. return v
  92. elif isinstance(v, (tuple, list)):
  93. return tuple(_get_valid_constant(attr, x, owner_type) for x in v)
  94. constants = ", ".join(torch.typename(typ) for typ in _constant_types)
  95. raise TypeError(textwrap.dedent("""
  96. '{}' object in attribute '{}.{}' is not a valid constant.
  97. Valid constants are:
  98. 1. a nn.ModuleList
  99. 2. a value of type {{{}}}
  100. 3. a list or tuple of (2)
  101. """.format(torch.typename(type(v)), owner_type, attr, constants)))
  102. class SourceContext(torch._C._jit_tree_views.SourceRangeFactory):
  103. def __init__(self, source, filename, file_lineno, leading_whitespace_len):
  104. super().__init__(source, filename, file_lineno, leading_whitespace_len)
  105. def infer_concrete_type_builder(nn_module, share_types=True):
  106. """
  107. Build a ConcreteModuleTypeBuilder from an nn.Module. This
  108. ConcreteModuleType doesn't have a JIT type associated with it yet, it
  109. must be filled in by the caller.
  110. """
  111. concrete_type_builder = torch._C.ConcreteModuleTypeBuilder(type(nn_module))
  112. if isinstance(nn_module, (torch.nn.ModuleDict)):
  113. concrete_type_builder.set_module_dict()
  114. if isinstance(nn_module, (torch.nn.ModuleList, torch.nn.Sequential)):
  115. concrete_type_builder.set_module_list()
  116. if isinstance(nn_module, (torch.nn.ParameterList)):
  117. concrete_type_builder.set_parameter_list()
  118. if isinstance(nn_module, (torch.nn.ParameterDict)):
  119. concrete_type_builder.set_parameter_dict()
  120. def get_annotations(obj):
  121. if sys.version_info < (3, 10):
  122. return getattr(obj, '__annotations__', {})
  123. # In Python-3.10+ it is recommended to use inspect.get_annotations
  124. # See https://docs.python.org/3.10/howto/annotations.html
  125. # But also, in 3.10 annotations from base class are not inherited
  126. # by unannotated derived one, so they must be manually extracted
  127. annotations = inspect.get_annotations(obj)
  128. if len(annotations) > 0:
  129. return annotations
  130. cls = obj if isinstance(obj, type) else type(obj)
  131. if len(cls.__bases__) == 0:
  132. return {}
  133. return inspect.get_annotations(cls.__bases__[0])
  134. class_annotations = get_annotations(nn_module)
  135. if isinstance(nn_module, (torch.ao.quantization.QuantWrapper)):
  136. class_annotations = {}
  137. # Get user-annotated ignored attributes.
  138. user_annotated_ignored_attributes = getattr(nn_module, "__jit_ignored_attributes__", list())
  139. concrete_type_builder.add_ignored_attributes(user_annotated_ignored_attributes)
  140. ignored_properties = jit_ignored_properties(nn_module)
  141. # try to infer the type from type annotation or from the object itself
  142. def infer_type(name, item):
  143. # The forward function from Module is special; never use this annotations; we
  144. # need to infer type directly using JIT. I originally wanted to write
  145. # this test as isinstance(class_annotations[name], Callable) but
  146. # isinstance on typing things doesn't seem to work: isinstance(list, Callable)
  147. # is also true!
  148. inferred = False
  149. try:
  150. if name in class_annotations and class_annotations[name] != torch.nn.Module.__annotations__["forward"]:
  151. ann_to_type = torch.jit.annotations.ann_to_type(class_annotations[name], fake_range())
  152. attr_type = torch._C.InferredType(ann_to_type)
  153. elif isinstance(item, torch.jit.Attribute):
  154. ann_to_type = torch.jit.annotations.ann_to_type(item.type, fake_range())
  155. attr_type = torch._C.InferredType(ann_to_type)
  156. else:
  157. attr_type = torch._C._jit_try_infer_type(item)
  158. inferred = True
  159. except RuntimeError as re:
  160. raise RuntimeError(
  161. "Error inferring type for {name}: {item}: {re}".format(name=name, item=item, re=re)
  162. ) from re
  163. return attr_type, inferred
  164. added_names = set()
  165. for name, item in nn_module._parameters.items():
  166. if name in user_annotated_ignored_attributes:
  167. continue
  168. assert item is None or isinstance(item, torch.Tensor)
  169. attr_type, _ = infer_type(name, item)
  170. # We currently have the invariant in various places in our code
  171. # that parameters must be Tensors. However, the nn.Module API also
  172. # allows NoneType parameters. These parameters are not returned as
  173. # part of `parameters()` and its variants, but are available
  174. # through direct attribute access.
  175. concrete_type_builder.add_attribute(name, attr_type.type(), True, False)
  176. added_names.add(name)
  177. for name, item in nn_module._buffers.items():
  178. if name in user_annotated_ignored_attributes:
  179. continue
  180. assert item is None or isinstance(item, torch.Tensor)
  181. attr_type, _ = infer_type(name, item)
  182. concrete_type_builder.add_attribute(name, attr_type.type(), False, True)
  183. added_names.add(name)
  184. for name, item in nn_module._modules.items():
  185. if name in user_annotated_ignored_attributes:
  186. continue
  187. attr_type, _ = infer_type(name, item)
  188. if item is None:
  189. # Modules can be None. We don't have direct support for optional
  190. # Modules, so the register it as an NoneType attribute instead.
  191. concrete_type_builder.add_attribute(name, attr_type.type(), False, False)
  192. continue
  193. if attr_type.success():
  194. assert attr_type.type().is_interface_type()
  195. # if the type can be inferred, it should be a module interface type
  196. sub_concrete_type = torch._C.ConcreteModuleType.from_jit_type(attr_type.type())
  197. else:
  198. # otherwise we get the concrete module type for item and add it to concrete_type
  199. sub_concrete_type = get_module_concrete_type(item, share_types)
  200. concrete_type_builder.add_module(name, sub_concrete_type)
  201. added_names.add(name)
  202. # populate constants_set
  203. constants_set = set(getattr(nn_module, "__constants__", ()))
  204. # Constants annotated via `Final[T]` rather than being added to `__constants__`
  205. for name, ann in class_annotations.items():
  206. if torch._jit_internal.is_final(ann):
  207. constants_set.add(name)
  208. for name in constants_set:
  209. if name in added_names:
  210. # TODO: We should really error in this case, but its bc-breaking so
  211. # we need to warn for at least one release
  212. if name in nn_module._modules:
  213. hint = "submodule"
  214. elif name in nn_module._buffers:
  215. hint = "buffer"
  216. elif name in nn_module._parameters:
  217. hint = "parameter"
  218. else:
  219. raise AssertionError("added_names must be submodule, parameter, or buffer")
  220. warnings.warn("'{}' was found in ScriptModule constants, "
  221. " but it is a non-constant {}. Consider removing it.".format(name, hint))
  222. continue
  223. if not hasattr(nn_module, name):
  224. # TODO: We should really error in this case, but its bc-breaking so
  225. # we need to warn for at least one release
  226. warnings.warn("'{}' was found in ScriptModule constants, "
  227. "but was not actually set in __init__. "
  228. "Consider removing it.".format(name))
  229. continue
  230. value = getattr(nn_module, name)
  231. concrete_type_builder.add_constant(name, _get_valid_constant(name, value, type(nn_module).__name__))
  232. added_names.add(name)
  233. # populate overloads
  234. overloads = getattr(nn_module, "__overloads__", {})
  235. # update with any annotated overloads
  236. overloads.update(get_overload_name_mapping(get_overload_annotations(nn_module, ignored_properties)))
  237. for name, overloaded_names in overloads.items():
  238. concrete_type_builder.add_overload(name, overloaded_names)
  239. for name, value in nn_module.__dict__.items():
  240. if name in ignored_attributes or name.startswith("__"):
  241. # Python objects have lots of random attributes attached to them;
  242. # PyTorch adds a few more. Prevent these from getting compiled.
  243. continue
  244. if name in user_annotated_ignored_attributes:
  245. continue
  246. if name in added_names:
  247. # Don't re-add anything we already added
  248. continue
  249. isoverloadpacket = isinstance(value, torch._ops.OpOverloadPacket)
  250. if isoverloadpacket:
  251. value = value.op
  252. # Handle Python function attributes
  253. if inspect.isfunction(value):
  254. try:
  255. scripted_fn = torch.jit.script(value)
  256. concrete_type_builder.add_function_attribute(
  257. name,
  258. torch._C._jit_try_infer_type(scripted_fn).type(),
  259. value)
  260. except Exception as e:
  261. # If we fail to script the function, it isn't a hard error.
  262. # Instead, we will add it to the list of attributes we failed
  263. # to convert, with the compilation error.
  264. hint = ("(This function exists as an attribute on the Python module, "
  265. "but we failed to compile it to a TorchScript function. "
  266. "\nThe error stack is reproduced here:\n{}").format(e)
  267. concrete_type_builder.add_failed_attribute(name, hint)
  268. pass
  269. continue
  270. # Handle calls to builtin functions (either bespoke builtins from torch.jit._builtins or
  271. # a call to an aten function like torch.add)
  272. builtin_symbol_name = _find_builtin(value)
  273. if builtin_symbol_name:
  274. concrete_type_builder.add_builtin_function(name, builtin_symbol_name)
  275. continue
  276. # Handle Script function attributes
  277. if isinstance(value, torch.jit.ScriptFunction):
  278. concrete_type_builder.add_function_attribute(
  279. name,
  280. torch._C._jit_try_infer_type(value).type(),
  281. value)
  282. continue
  283. # If we got here, this is a regular "data" attribute, add it to the concrete type
  284. attr_type, inferred = infer_type(name, value)
  285. if attr_type.success():
  286. concrete_type_builder.add_attribute(name, attr_type.type(), False, False)
  287. else:
  288. # TODO: could add more detail here. For example, what the user should do
  289. # when the pytype is `list` or `NoneType`
  290. inferred_msg = "Its type was inferred; try adding a type annotation for the attribute." if inferred else ""
  291. additional_info = f"{attr_type.reason()}. {inferred_msg}"
  292. hint = "(This attribute exists on the Python module, " \
  293. f"but we failed to convert Python type: '{torch.typename(type(value))}' " \
  294. f"to a TorchScript type. {additional_info})"
  295. concrete_type_builder.add_failed_attribute(name, hint)
  296. # add hooks to concrete type
  297. for hook in nn_module._forward_hooks.values():
  298. concrete_type_builder.add_forward_hook(hook)
  299. for pre_hook in nn_module._forward_pre_hooks.values():
  300. concrete_type_builder.add_forward_pre_hook(pre_hook)
  301. return concrete_type_builder
  302. class ConcreteTypeStore:
  303. type_store: Dict[Type[Module], List[torch._C.ConcreteModuleType]]
  304. methods_compiled: Set[torch._C.ConcreteModuleType]
  305. def __init__(self):
  306. # Python module type => List[ConcreteModuleType)]
  307. self.type_store = {}
  308. # ConcreteTypes that have had their methods already compiled
  309. self.methods_compiled = set()
  310. def get_or_create_concrete_type(self, nn_module):
  311. """
  312. Infer a ConcreteType from this `nn.Module` instance. Underlying JIT
  313. types are re-used if possible.
  314. """
  315. concrete_type_builder = infer_concrete_type_builder(nn_module)
  316. nn_module_type = type(nn_module)
  317. if nn_module_type not in self.type_store:
  318. self.type_store[nn_module_type] = []
  319. # Search the type store for an already-available JIT type
  320. known_types = self.type_store[nn_module_type]
  321. for known_type in known_types:
  322. if known_type.equals(concrete_type_builder):
  323. return known_type
  324. # We didn't find anything; generate a new JIT type from this concrete type
  325. concrete_type = concrete_type_builder.build()
  326. self.type_store[nn_module_type].append(concrete_type)
  327. return concrete_type
  328. concrete_type_store = ConcreteTypeStore()
  329. def create_methods_and_properties_from_stubs(concrete_type, method_stubs, property_stubs):
  330. method_defs = [m.def_ for m in method_stubs]
  331. method_rcbs = [m.resolution_callback for m in method_stubs]
  332. method_defaults = [get_default_args(m.original_method) for m in method_stubs]
  333. property_defs = [p.def_ for p in property_stubs]
  334. property_rcbs = [p.resolution_callback for p in property_stubs]
  335. concrete_type._create_methods_and_properties(property_defs, property_rcbs, method_defs, method_rcbs, method_defaults)
  336. def create_hooks_from_stubs(concrete_type, hook_stubs, pre_hook_stubs):
  337. hook_defs = [h.def_ for h in hook_stubs]
  338. hook_rcbs = [h.resolution_callback for h in hook_stubs]
  339. pre_hook_defs = [h.def_ for h in pre_hook_stubs]
  340. pre_hook_rcbs = [h.resolution_callback for h in pre_hook_stubs]
  341. concrete_type._create_hooks(hook_defs, hook_rcbs, pre_hook_defs, pre_hook_rcbs)
  342. def get_module_concrete_type(nn_module, share_types=True):
  343. """
  344. Gets a concrete type for nn_modules. If share_types is True, the concrete
  345. type is fetched from concrete_type_store. If it is False, a new concrete type
  346. is created without first searching concrete_type_store.
  347. Args:
  348. nn_module: The original Python nn.Module that we are creating a ScriptModule for.
  349. share_types = Whether to share underlying JIT types between modules (if possible).
  350. Returns:
  351. A concrete type for nn_module.
  352. """
  353. assert isinstance(nn_module, Module)
  354. if isinstance(nn_module, torch.jit.ScriptModule) and \
  355. hasattr(nn_module, "_concrete_type"):
  356. return nn_module._concrete_type
  357. if share_types:
  358. # Look into the store of cached JIT types
  359. concrete_type = concrete_type_store.get_or_create_concrete_type(nn_module)
  360. else:
  361. # Get a concrete type directly, without trying to re-use an existing JIT
  362. # type from the type store.
  363. concrete_type_builder = infer_concrete_type_builder(nn_module, share_types)
  364. concrete_type_builder.set_poisoned()
  365. concrete_type = concrete_type_builder.build()
  366. return concrete_type
  367. def create_script_class(obj):
  368. """
  369. Create and return a RecursiveScriptClass instance from a Python object.
  370. Arguments:
  371. obj: A Python object.
  372. """
  373. qualified_class_name = _jit_internal._qualified_name(type(obj))
  374. rcb = _jit_internal.createResolutionCallbackForClassMethods(type(obj))
  375. # Script the type of obj if it hasn't already been scripted.
  376. _compile_and_register_class(type(obj), rcb, qualified_class_name)
  377. class_ty = _python_cu.get_class(qualified_class_name)
  378. # Create an empty torch._C.ScriptObject with the scripted type.
  379. cpp_object = torch._C._create_object_with_type(class_ty)
  380. # Copy all of the attributes over to the torch._C.ScriptObject.
  381. for name, value in obj.__dict__.items():
  382. cpp_object.setattr(name, value)
  383. # Wrap the torch._C.ScriptObject in a RecursiveScriptClass instance.
  384. return wrap_cpp_class(cpp_object)
  385. def create_script_module(nn_module, stubs_fn, share_types=True, is_tracing=False):
  386. """
  387. Creates a new ScriptModule from an nn.Module
  388. Args:
  389. nn_module: The original Python nn.Module that we are creating a ScriptModule for.
  390. stubs_fn: Lambda that takes an nn.Module and generates a list of ScriptMethodStubs to compile.
  391. share_types: Whether to share underlying JIT types between modules (if possible).
  392. NOTE: Only set to False this when we cannot guarantee type sharing will work
  393. correctly. This only happens today for traced modules, where the same
  394. module can produce different traced methods depending on the inputs.
  395. is_tracing: Whether this function is called during tracing or scripting. If tracing,
  396. we don't need to do AttributeTypeIsSupportedChecker because all the unsupported
  397. attributes will be baked as constant in the tracing graph. In addition,
  398. this check significantly slows down the traced modules when the module size is big.
  399. """
  400. assert not isinstance(nn_module, torch.jit.RecursiveScriptModule)
  401. check_module_initialized(nn_module)
  402. concrete_type = get_module_concrete_type(nn_module, share_types)
  403. if not is_tracing:
  404. AttributeTypeIsSupportedChecker().check(nn_module)
  405. return create_script_module_impl(nn_module, concrete_type, stubs_fn)
  406. def create_script_module_impl(nn_module, concrete_type, stubs_fn):
  407. """
  408. Convert an nn.Module to a RecursiveScriptModule.
  409. Args:
  410. nn_module: The original Python nn.Module that we are creating a ScriptModule for.
  411. concrete_type: The fully initialized ConcreteType of the module.
  412. stubs_fn: Lambda that takes an nn.Module and generates a list of ScriptMethodStubs to compile.
  413. """
  414. cpp_module = torch._C._create_module_with_type(concrete_type.jit_type)
  415. method_stubs = stubs_fn(nn_module)
  416. property_stubs = get_property_stubs(nn_module)
  417. hook_stubs, pre_hook_stubs = get_hook_stubs(nn_module)
  418. user_annotated_ignored_attributes = getattr(nn_module, "__jit_ignored_attributes__", list())
  419. ignored_properties = jit_ignored_properties(nn_module)
  420. def init_fn(script_module):
  421. # Initialize the ScriptModule:
  422. # 1. Copy the attributes/parameters/buffers from the original `nn_module` to the new ScriptModule.
  423. for name, (attr_type, is_param) in concrete_type.get_attributes().items():
  424. orig_value = getattr(nn_module, name)
  425. orig_value = orig_value.value if isinstance(orig_value, torch.jit.Attribute) else orig_value
  426. cpp_module.setattr(name, orig_value)
  427. # 2. Copy the submodules from the original `nn_module` to the new ScriptModule,
  428. # recursively scripting them.
  429. for name, sub_concrete_type in concrete_type.get_modules():
  430. orig_value = getattr(nn_module, name)
  431. assert isinstance(orig_value, Module), "Expected Module but got {}".format(type(orig_value))
  432. module_type = sub_concrete_type.jit_type
  433. if isinstance(module_type, torch._C.InterfaceType):
  434. # use the interface inference rule to compile the module
  435. scripted = interface_script(module_type, orig_value)
  436. elif isinstance(orig_value, torch.jit.ScriptModule):
  437. scripted = orig_value
  438. else:
  439. # always reuse the provided stubs_fn to infer the methods to compile
  440. scripted = create_script_module_impl(orig_value, sub_concrete_type, stubs_fn)
  441. cpp_module.setattr(name, scripted)
  442. script_module._modules[name] = scripted
  443. # 3. Copy @ignored/@unused methods and attrs from the original `nn_module` to the new ScriptModule.
  444. # This ensures we can access these Python methods on the ScriptModule.
  445. for name in dir(nn_module):
  446. if name in ignored_properties:
  447. continue
  448. item = getattr(nn_module, name, None)
  449. if inspect.ismethod(item) and _jit_internal.is_ignored_fn(item):
  450. unbound_function = getattr(nn_module, name).__func__
  451. bound_method = unbound_function.__get__(script_module)
  452. setattr(script_module, name, bound_method)
  453. elif concrete_type.is_ignored_attribute(name):
  454. setattr(script_module, name, item)
  455. # For convenience, attach the concrete type to the new ScriptModule
  456. script_module._concrete_type = concrete_type
  457. # Actually create the ScriptModule, initializing it with the function we just defined
  458. script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  459. # Compile methods if necessary
  460. if concrete_type not in concrete_type_store.methods_compiled:
  461. create_methods_and_properties_from_stubs(concrete_type, method_stubs, property_stubs)
  462. # Create hooks after methods to ensure no name collisions between hooks and methods.
  463. # If done before, hooks can overshadow methods that aren't exported.
  464. create_hooks_from_stubs(concrete_type, hook_stubs, pre_hook_stubs)
  465. torch._C._run_emit_module_hook(cpp_module)
  466. concrete_type_store.methods_compiled.add(concrete_type)
  467. # Copy the forward hooks and pre-hooks to the new ScriptModule
  468. # to allow the hooks to be run from eager as ScriptFunctions
  469. for idx, fn in enumerate(script_module._c._get_forward_pre_hooks()):
  470. script_module._forward_pre_hooks[idx] = fn
  471. for idx, fn in enumerate(script_module._c._get_forward_hooks()):
  472. script_module._forward_hooks[idx] = fn
  473. # Special handling so methods like __len__ work in script methods on classes derived from containers
  474. if isinstance(nn_module, (torch.nn.ModuleList, torch.nn.Sequential, torch.nn.ModuleDict)) and \
  475. '__len__' not in cpp_module._method_names():
  476. script_module.define("def __len__(self):\n return {}\n".format(len(nn_module)))
  477. if isinstance(nn_module, torch.nn.ModuleDict) and \
  478. '__contains__' not in cpp_module._method_names():
  479. if len(nn_module.keys()):
  480. keys = repr(list(nn_module.keys()))
  481. script_module.define("def __contains__(self, key: str):\n return key in {}\n".format(keys))
  482. else:
  483. script_module.define("def __contains__(self, key: str):\n return False\n")
  484. # Make the compiled methods available to the Python ScriptModule class.
  485. for method_stub in method_stubs:
  486. if method_stub.original_method is None:
  487. # define()'d methods don't have an Python original_method, so we
  488. # don't need to do any Python re-wrapping stuff
  489. continue
  490. name = method_stub.original_method.__name__
  491. if name != method_stub.def_.name().name:
  492. # TODO: Why skip this? Because @torch.jit._overload_method will
  493. # mangle the name of the function.
  494. continue
  495. script_method = cpp_module._get_method(name)
  496. # Wrap the original to propagate docstrings and such.
  497. # TODO: we don't currently do this functions that are recursively
  498. # compiled, we should.
  499. wrapped_script_method = functools.wraps(method_stub.original_method)(script_method)
  500. # Add the methods to the script_module directly. This ensures they will
  501. # be found first when `name` is looked up (as opposed to the stubs or
  502. # nn.Module.forward)
  503. script_module.__dict__[name] = wrapped_script_method
  504. # Make module properties available on the Python ScriptModule class.
  505. for property_stub in property_stubs:
  506. property_name = property_stub.def_.name().name
  507. fget = cpp_module._get_method(property_stub.def_.getter_name().name)
  508. # Setter is optional, so it may not exist.
  509. setter_name = property_stub.def_.setter_name()
  510. fset = cpp_module._get_method(setter_name.name) if setter_name else None
  511. script_module.__dict__[property_name] = property(property_name, fget, fset) # type: ignore[arg-type]
  512. # copy over python methods to script module if they aren't defined on the script module
  513. # this is currently an internal api used only on module containers
  514. for name in dir(nn_module):
  515. if name in ignored_properties:
  516. continue
  517. item = getattr(nn_module, name, None)
  518. if _jit_internal.get_torchscript_modifier(item) is _jit_internal.FunctionModifiers.COPY_TO_SCRIPT_WRAPPER:
  519. add_python_attr_to_scripted_model(script_module, nn_module, name)
  520. return script_module
  521. # We define shims of certain attributes on the RecursiveScriptModule to support
  522. # magic methods. To check if a script model defines an attribute we need
  523. # to also check that the attribute is not the shim
  524. def script_model_defines_attr(script_model, attr):
  525. script_attr = getattr(script_model, attr, None)
  526. if script_attr is None:
  527. return False
  528. default_attr = getattr(torch.jit.RecursiveScriptModule, attr, None)
  529. if default_attr is None:
  530. return False
  531. return script_attr != default_attr
  532. def add_python_attr_to_scripted_model(script_model, orig, attr):
  533. if hasattr(orig, attr) and script_model_defines_attr(script_model, attr):
  534. setattr(script_model, attr, getattr(orig, attr))
  535. def get_overload_annotations(mod, jit_ignored_properties):
  536. # original function => [(mangled overload name, overload function)]
  537. overloads = {}
  538. for name in dir(type(mod)):
  539. if name in jit_ignored_properties:
  540. continue
  541. item = getattr(mod, name, None)
  542. if not callable(item):
  543. continue
  544. # builtin functions like repr() in python 2 do not have __module__ defined
  545. if hasattr(item, "__module__") and item.__module__ is not None:
  546. method_overloads = _jit_internal._get_overloaded_methods(item, mod.__class__)
  547. if method_overloads is None:
  548. continue
  549. if item.__func__ in method_overloads:
  550. raise RuntimeError(_jit_internal.get_overload_no_implementation_error_message(
  551. 'method', item.__func__))
  552. names = [name + "__" + str(i) for i in range(len(method_overloads))]
  553. overloads[item] = list(zip(names, method_overloads))
  554. return overloads
  555. def get_overload_name_mapping(overload_info):
  556. # Same format as __overloads__
  557. # original function => [overload names]
  558. overload_name_mappings: Dict[str, List[str]] = {}
  559. for orig_fn, overloads in overload_info.items():
  560. original_name = orig_fn.__name__
  561. if original_name not in overload_name_mappings:
  562. overload_name_mappings[original_name] = []
  563. for overload_name, _ in overloads:
  564. overload_name_mappings[original_name].append(overload_name)
  565. return overload_name_mappings
  566. def _check_no_signature(func):
  567. signature = torch.jit.annotations.get_signature(func, None, fake_range(), inspect.ismethod(func))
  568. if signature is None:
  569. qual_name = _jit_internal._qualified_name(func)
  570. raise RuntimeError("Must explicitly add type annotations to overloaded functions: {}".format(qual_name))
  571. def make_stubs_for_overloads(overload_info):
  572. overload_stubs = []
  573. for orig_fn, overloads in overload_info.items():
  574. orig_ast = get_jit_def(orig_fn, orig_fn.__name__, self_name="RecursiveScriptModule")
  575. for overload_name, overload_fn in overloads:
  576. _check_no_signature(overload_fn)
  577. over_ast = get_jit_def(overload_fn, overload_fn.__name__, self_name="RecursiveScriptModule")
  578. new_ast = torch._C._replace_overloaded_method_decl(over_ast.decl(), orig_ast, overload_name)
  579. _rcb = _jit_internal.createResolutionCallbackFromClosure(orig_fn)
  580. overload_stubs.append(ScriptMethodStub(_rcb, new_ast, overload_fn))
  581. return overload_stubs
  582. def check_module_initialized(mod):
  583. assert isinstance(mod, torch.nn.Module)
  584. if not hasattr(mod, '_parameters'):
  585. raise RuntimeError("'{}' has not been initialized, did you forget to call 'super()'?"
  586. .format(torch.typename(type(mod))))
  587. # This is to avoid importing torch.distributed.nn
  588. if not hasattr(mod, 'remote_parameters'):
  589. for name, param in mod._parameters.items():
  590. if param is not None and torch.nn.parameter.is_lazy(param):
  591. raise RuntimeError("'{}' has uninitialized parameters {}. Did you forget to run a forward pass?"
  592. .format(torch.typename(type(mod)), name))
  593. for name, buf in mod._buffers.items():
  594. if buf is not None and torch.nn.parameter.is_lazy(buf):
  595. raise RuntimeError("'{}' has uninitialized buffers {}. Did you forget to run a forward pass?"
  596. .format(torch.typename(type(mod)), name))
  597. def infer_methods_to_compile(nn_module):
  598. """
  599. Implements the default rules for which methods should act as starting
  600. points for compilation (TODO add a link when the rules are published).
  601. """
  602. check_module_initialized(nn_module)
  603. user_annotated_ignored_attributes = getattr(nn_module, "__jit_ignored_attributes__", list())
  604. ignored_properties = jit_ignored_properties(nn_module)
  605. methods: List[str] = []
  606. if hasattr(nn_module, 'forward') and not _jit_internal.is_ignored_fn(nn_module.forward):
  607. forward_func = getattr(nn_module.forward, "__func__", None)
  608. module_forward = getattr(torch.nn.Module, "forward", None)
  609. if forward_func != module_forward:
  610. methods = ['forward']
  611. exported = []
  612. for name in dir(nn_module):
  613. if name in ignored_properties:
  614. continue
  615. item = getattr(nn_module, name, None)
  616. if _jit_internal.get_torchscript_modifier(item) is _jit_internal.FunctionModifiers.EXPORT:
  617. exported.append(name)
  618. methods = methods + exported
  619. overload_name_mappings = dict(getattr(nn_module, "__overloads__", {}))
  620. overload_info = get_overload_annotations(nn_module, ignored_properties)
  621. overload_name_mappings.update(get_overload_name_mapping(overload_info))
  622. overload_stubs = make_stubs_for_overloads(overload_info)
  623. nn_module.__overloads__ = overload_name_mappings
  624. # we shouldn't directly compile overloaded methods, just its overloads
  625. def ignore_overloaded(method_name):
  626. return method_name not in overload_name_mappings
  627. filtered_methods = filter(ignore_overloaded, methods)
  628. # Unique the methods. We don't want to use a set to store the methods because it
  629. # introduces non-determinism to compile order.
  630. uniquer: Set[str] = set()
  631. uniqued_methods = []
  632. for name in filtered_methods:
  633. if name in uniquer:
  634. continue
  635. uniqued_methods.append(name)
  636. uniquer.add(name)
  637. stubs = []
  638. for method in uniqued_methods:
  639. stubs.append(make_stub_from_method(nn_module, method))
  640. return overload_stubs + stubs
  641. def get_hook_stubs(nn_module):
  642. """
  643. Returns forward hook and pre_hook ScriptModuleStubs
  644. """
  645. check_module_initialized(nn_module)
  646. hook_map: Dict = {}
  647. hook_stubs = []
  648. for hook in nn_module._forward_hooks.values():
  649. if hook.__name__ in hook_map:
  650. if id(hook) != id(hook_map[hook.__name__]):
  651. raise RuntimeError(
  652. f"Hook '{hook.__name__}' on {type(nn_module).__name__} "
  653. "has at least two different python definitions."
  654. " Please use unique names for all hooks."
  655. )
  656. else:
  657. hook_map[hook.__name__] = hook
  658. hook_stubs.append(make_stub(hook, hook.__name__))
  659. pre_hook_stubs = []
  660. for pre_hook in nn_module._forward_pre_hooks.values():
  661. if pre_hook.__name__ in hook_map:
  662. if id(pre_hook) != id(hook_map[pre_hook.__name__]):
  663. raise RuntimeError(
  664. f"Pre-hook '{pre_hook.__name__}' on {type(nn_module).__name__} "
  665. "has at least two different python definitions."
  666. " Please use unique names for all hooks."
  667. )
  668. else:
  669. hook_map[pre_hook.__name__] = pre_hook
  670. pre_hook_stubs.append(make_stub(pre_hook, pre_hook.__name__))
  671. return hook_stubs, pre_hook_stubs
  672. def get_property_stubs(nn_module):
  673. """
  674. Create property stubs for the properties of the module by creating method
  675. stubs for the getter and setter.
  676. """
  677. module_ty = type(nn_module)
  678. properties_asts = get_class_properties(module_ty, self_name="RecursiveScriptModule")
  679. rcbs = {}
  680. for name in dir(module_ty):
  681. item = getattr(module_ty, name, None)
  682. if isinstance(item, property):
  683. if not item.fget:
  684. raise RuntimeError(f'Property {name} of {nn_module.__name__} must have a getter')
  685. rcbs[name] = _jit_internal.createResolutionCallbackFromClosure(item.fget)
  686. stubs = [PropertyStub(rcbs[ast.name().name], ast) for ast in properties_asts]
  687. return stubs
  688. def interface_script(mod_interface, nn_module):
  689. """
  690. Makes a ScriptModule from an nn.Module, using the interface methods rule for
  691. determining which methods to compile.
  692. Args:
  693. mod_interface: the interface type that the module have
  694. nn_module: The original Python nn.Module that we are creating a ScriptModule for.
  695. """
  696. if isinstance(nn_module, torch.jit.ScriptModule):
  697. return nn_module
  698. check_module_initialized(nn_module)
  699. def infer_interface_methods_to_compile(nn_module):
  700. """
  701. Rule to infer the methods from the interface type to know which
  702. methods need to act as starting points for compilation.
  703. """
  704. stubs = []
  705. for method in mod_interface.getMethodNames():
  706. stubs.append(make_stub_from_method(nn_module, method))
  707. return stubs
  708. return create_script_module(nn_module, infer_interface_methods_to_compile)
  709. def try_compile_fn(fn, loc):
  710. if _jit_internal.is_ignored_fn(fn):
  711. # Don't do anything for @ignore'd functions
  712. return None
  713. if isinstance(fn, torch.nn.Module):
  714. # Since modules are callable pybind recognizes them as functions, but
  715. # don't do anything for them
  716. return None
  717. if not inspect.isfunction(fn) and not inspect.ismethod(fn):
  718. raise RuntimeError("`{}` is not a function. Recursive scripting only supports "
  719. "Python functions or methods currently.\n"
  720. "Consider manually annotating `{}` with @torch.jit.script.".format(fn, fn))
  721. # We don't have the actual scope where the function was defined, but we can
  722. # extract the necessary info from the closed over variables on the function
  723. # object
  724. rcb = _jit_internal.createResolutionCallbackFromClosure(fn)
  725. return torch.jit.script(fn, _rcb=rcb)
  726. def wrap_cpp_class(cpp_class):
  727. """
  728. Wrap this torch._C.Object in a Python RecursiveScriptClass.
  729. """
  730. return torch.jit.RecursiveScriptClass(cpp_class)
  731. def wrap_cpp_module(cpp_module):
  732. """
  733. Wrap this torch._C.ScriptModule in a Python ScriptModule, recursively for all submodules
  734. """
  735. def init_fn(script_module):
  736. for name, cpp_module in torch._C.ModuleDict(script_module._c).items():
  737. setattr(script_module, name, wrap_cpp_module(cpp_module))
  738. script_module._concrete_type = torch._C.ConcreteModuleType.from_jit_type(script_module._c._type())
  739. for idx, fn in enumerate(script_module._c._get_forward_pre_hooks()):
  740. script_module._forward_pre_hooks[idx] = fn
  741. for idx, fn in enumerate(script_module._c._get_forward_hooks()):
  742. script_module._forward_hooks[idx] = fn
  743. return torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  744. def compile_unbound_method(concrete_type, fn):
  745. if _jit_internal.is_ignored_fn(fn):
  746. return None
  747. stub = make_stub(fn, fn.__name__)
  748. with torch._jit_internal._disable_emit_hooks():
  749. # We don't want to call the hooks here since the graph that is calling
  750. # this function is not yet complete
  751. create_methods_and_properties_from_stubs(concrete_type, (stub,), ())
  752. return stub
  753. def lazy_bind(concrete_type, unbound_method):
  754. """
  755. Returns a function that lazily binds `unbound_method` to a provided
  756. Module IValue, then invokes the method. We do this so that any Python
  757. shenanigans that will poison type sharing are impossible at compile
  758. time.
  759. """
  760. def lazy_binding_method(cpp_module, *args):
  761. def init_fn(script_module):
  762. orig_class = concrete_type.py_class
  763. # Copy @ignored/@unused methods from the original module to the new one.
  764. # This ensures they are available during execution.
  765. for name in dir(orig_class):
  766. item = getattr(orig_class, name, None)
  767. if _jit_internal.is_ignored_fn(item):
  768. setattr(script_module, name, item)
  769. # Copy constants over so they are available during execution.
  770. for name, value in concrete_type.get_constants().items():
  771. setattr(script_module, name, value)
  772. script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  773. method = types.MethodType(unbound_method, script_module)
  774. return method(*args)
  775. # make the lazy binding method "look like" the original method
  776. lazy_binding_method.original_fn = unbound_method # type: ignore[attr-defined]
  777. lazy_binding_method.__name__ = unbound_method.__name__
  778. torch._jit_internal.copy_torchscript_modifier(unbound_method, lazy_binding_method)
  779. return lazy_binding_method