_recursive.py 41 KB

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